repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
kivy/buildozer
buildozer/__init__.py
Buildozer.log_env
def log_env(self, level, env): """dump env into debug logger in readable format""" self.log(level, "ENVIRONMENT:") for k, v in env.items(): self.log(level, " {} = {}".format(k, pformat(v)))
python
def log_env(self, level, env): """dump env into debug logger in readable format""" self.log(level, "ENVIRONMENT:") for k, v in env.items(): self.log(level, " {} = {}".format(k, pformat(v)))
[ "def", "log_env", "(", "self", ",", "level", ",", "env", ")", ":", "self", ".", "log", "(", "level", ",", "\"ENVIRONMENT:\"", ")", "for", "k", ",", "v", "in", "env", ".", "items", "(", ")", ":", "self", ".", "log", "(", "level", ",", "\" {} = ...
dump env into debug logger in readable format
[ "dump", "env", "into", "debug", "logger", "in", "readable", "format" ]
586152c6ce2b6cde4d5a081d9711f9cb037a901c
https://github.com/kivy/buildozer/blob/586152c6ce2b6cde4d5a081d9711f9cb037a901c/buildozer/__init__.py#L243-L247
train
223,800
kivy/buildozer
buildozer/__init__.py
Buildozer.check_configuration_tokens
def check_configuration_tokens(self): '''Ensure the spec file is 'correct'. ''' 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)
python
def check_configuration_tokens(self): '''Ensure the spec file is 'correct'. ''' 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)
[ "def", "check_configuration_tokens", "(", "self", ")", ":", "self", ".", "info", "(", "'Check configuration tokens'", ")", "self", ".", "migrate_configuration_tokens", "(", ")", "get", "=", "self", ".", "config", ".", "getdefault", "errors", "=", "[", "]", "ad...
Ensure the spec file is 'correct'.
[ "Ensure", "the", "spec", "file", "is", "correct", "." ]
586152c6ce2b6cde4d5a081d9711f9cb037a901c
https://github.com/kivy/buildozer/blob/586152c6ce2b6cde4d5a081d9711f9cb037a901c/buildozer/__init__.py#L398-L437
train
223,801
kivy/buildozer
buildozer/__init__.py
Buildozer.check_application_requirements
def check_application_requirements(self): '''Ensure the application requirements are all available and ready to be packaged as well. ''' 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
python
def check_application_requirements(self): '''Ensure the application requirements are all available and ready to be packaged as well. ''' 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
[ "def", "check_application_requirements", "(", "self", ")", ":", "requirements", "=", "self", ".", "config", ".", "getlist", "(", "'app'", ",", "'requirements'", ",", "''", ")", "target_available_packages", "=", "self", ".", "target", ".", "get_available_packages",...
Ensure the application requirements are all available and ready to be packaged as well.
[ "Ensure", "the", "application", "requirements", "are", "all", "available", "and", "ready", "to", "be", "packaged", "as", "well", "." ]
586152c6ce2b6cde4d5a081d9711f9cb037a901c
https://github.com/kivy/buildozer/blob/586152c6ce2b6cde4d5a081d9711f9cb037a901c/buildozer/__init__.py#L488-L528
train
223,802
kivy/buildozer
buildozer/__init__.py
Buildozer.check_garden_requirements
def check_garden_requirements(self): '''Ensure required garden packages are available to be included. ''' 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
python
def check_garden_requirements(self): '''Ensure required garden packages are available to be included. ''' 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
[ "def", "check_garden_requirements", "(", "self", ")", ":", "garden_requirements", "=", "self", ".", "config", ".", "getlist", "(", "'app'", ",", "'garden_requirements'", ",", "''", ")", "# have we installed the garden packages?", "if", "exists", "(", "self", ".", ...
Ensure required garden packages are available to be included.
[ "Ensure", "required", "garden", "packages", "are", "available", "to", "be", "included", "." ]
586152c6ce2b6cde4d5a081d9711f9cb037a901c
https://github.com/kivy/buildozer/blob/586152c6ce2b6cde4d5a081d9711f9cb037a901c/buildozer/__init__.py#L537-L568
train
223,803
kivy/buildozer
buildozer/__init__.py
Buildozer.cmd_init
def cmd_init(self, *args): '''Create a initial buildozer.spec in the current directory ''' 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!')
python
def cmd_init(self, *args): '''Create a initial buildozer.spec in the current directory ''' 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!')
[ "def", "cmd_init", "(", "self", ",", "*", "args", ")", ":", "if", "exists", "(", "'buildozer.spec'", ")", ":", "print", "(", "'ERROR: You already have a buildozer.spec file.'", ")", "exit", "(", "1", ")", "copyfile", "(", "join", "(", "dirname", "(", "__file...
Create a initial buildozer.spec in the current directory
[ "Create", "a", "initial", "buildozer", ".", "spec", "in", "the", "current", "directory" ]
586152c6ce2b6cde4d5a081d9711f9cb037a901c
https://github.com/kivy/buildozer/blob/586152c6ce2b6cde4d5a081d9711f9cb037a901c/buildozer/__init__.py#L1090-L1097
train
223,804
kivy/buildozer
buildozer/__init__.py
Buildozer.cmd_distclean
def cmd_distclean(self, *args): '''Clean the whole Buildozer environment. ''' 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)
python
def cmd_distclean(self, *args): '''Clean the whole Buildozer environment. ''' 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)
[ "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", "(", ")", "...
Clean the whole Buildozer environment.
[ "Clean", "the", "whole", "Buildozer", "environment", "." ]
586152c6ce2b6cde4d5a081d9711f9cb037a901c
https://github.com/kivy/buildozer/blob/586152c6ce2b6cde4d5a081d9711f9cb037a901c/buildozer/__init__.py#L1099-L1108
train
223,805
kivy/buildozer
buildozer/__init__.py
Buildozer.cmd_serve
def cmd_serve(self, *args): '''Serve the bin directory via SimpleHTTPServer ''' 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()
python
def cmd_serve(self, *args): '''Serve the bin directory via SimpleHTTPServer ''' 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()
[ "def", "cmd_serve", "(", "self", ",", "*", "args", ")", ":", "try", ":", "from", "http", ".", "server", "import", "SimpleHTTPRequestHandler", "from", "socketserver", "import", "TCPServer", "except", "ImportError", ":", "from", "SimpleHTTPServer", "import", "Simp...
Serve the bin directory via SimpleHTTPServer
[ "Serve", "the", "bin", "directory", "via", "SimpleHTTPServer" ]
586152c6ce2b6cde4d5a081d9711f9cb037a901c
https://github.com/kivy/buildozer/blob/586152c6ce2b6cde4d5a081d9711f9cb037a901c/buildozer/__init__.py#L1126-L1141
train
223,806
kivy/buildozer
buildozer/targets/ios.py
TargetIos.cmd_xcode
def cmd_xcode(self, *args): '''Open the xcode project. ''' 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)))
python
def cmd_xcode(self, *args): '''Open the xcode project. ''' 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)))
[ "def", "cmd_xcode", "(", "self", ",", "*", "args", ")", ":", "app_name", "=", "self", ".", "buildozer", ".", "namify", "(", "self", ".", "buildozer", ".", "config", ".", "get", "(", "'app'", ",", "'package.name'", ")", ")", "app_name", "=", "app_name",...
Open the xcode project.
[ "Open", "the", "xcode", "project", "." ]
586152c6ce2b6cde4d5a081d9711f9cb037a901c
https://github.com/kivy/buildozer/blob/586152c6ce2b6cde4d5a081d9711f9cb037a901c/buildozer/targets/ios.py#L264-L273
train
223,807
kivy/buildozer
buildozer/targets/ios.py
TargetIos.cmd_list_identities
def cmd_list_identities(self, *args): '''List the available identities to use for signing. ''' identities = self._get_available_identities() print('Available identities:') for x in identities: print(' - {}'.format(x))
python
def cmd_list_identities(self, *args): '''List the available identities to use for signing. ''' identities = self._get_available_identities() print('Available identities:') for x in identities: print(' - {}'.format(x))
[ "def", "cmd_list_identities", "(", "self", ",", "*", "args", ")", ":", "identities", "=", "self", ".", "_get_available_identities", "(", ")", "print", "(", "'Available identities:'", ")", "for", "x", "in", "identities", ":", "print", "(", "' - {}'", ".", "f...
List the available identities to use for signing.
[ "List", "the", "available", "identities", "to", "use", "for", "signing", "." ]
586152c6ce2b6cde4d5a081d9711f9cb037a901c
https://github.com/kivy/buildozer/blob/586152c6ce2b6cde4d5a081d9711f9cb037a901c/buildozer/targets/ios.py#L337-L343
train
223,808
kevin1024/vcrpy
vcr/cassette.py
CassetteContextDecorator._handle_generator
def _handle_generator(self, fn): """Wraps a generator so that we're inside the cassette context for the duration of the generator. """ 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
python
def _handle_generator(self, fn): """Wraps a generator so that we're inside the cassette context for the duration of the generator. """ 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
[ "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",...
Wraps a generator so that we're inside the cassette context for the duration of the generator.
[ "Wraps", "a", "generator", "so", "that", "we", "re", "inside", "the", "cassette", "context", "for", "the", "duration", "of", "the", "generator", "." ]
114fcd29b43c55896aaa6a6613bc7766f2707c8b
https://github.com/kevin1024/vcrpy/blob/114fcd29b43c55896aaa6a6613bc7766f2707c8b/vcr/cassette.py#L126-L144
train
223,809
kevin1024/vcrpy
vcr/cassette.py
Cassette.append
def append(self, request, response): """Add a request, response pair to this cassette""" 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
python
def append(self, request, response): """Add a request, response pair to this cassette""" 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
[ "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 re...
Add a request, response pair to this cassette
[ "Add", "a", "request", "response", "pair", "to", "this", "cassette" ]
114fcd29b43c55896aaa6a6613bc7766f2707c8b
https://github.com/kevin1024/vcrpy/blob/114fcd29b43c55896aaa6a6613bc7766f2707c8b/vcr/cassette.py#L226-L238
train
223,810
kevin1024/vcrpy
vcr/cassette.py
Cassette._responses
def _responses(self, request): """ internal API, returns an iterator with all responses matching the 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
python
def _responses(self, request): """ internal API, returns an iterator with all responses matching the 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
[ "def", "_responses", "(", "self", ",", "request", ")", ":", "request", "=", "self", ".", "_before_record_request", "(", "request", ")", "for", "index", ",", "(", "stored_request", ",", "response", ")", "in", "enumerate", "(", "self", ".", "data", ")", ":...
internal API, returns an iterator with all responses matching the request.
[ "internal", "API", "returns", "an", "iterator", "with", "all", "responses", "matching", "the", "request", "." ]
114fcd29b43c55896aaa6a6613bc7766f2707c8b
https://github.com/kevin1024/vcrpy/blob/114fcd29b43c55896aaa6a6613bc7766f2707c8b/vcr/cassette.py#L243-L251
train
223,811
kevin1024/vcrpy
vcr/cassette.py
Cassette.play_response
def play_response(self, request): """ Get the response corresponding to a request, but only if it hasn't been played back before, and mark it as played """ 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) )
python
def play_response(self, request): """ Get the response corresponding to a request, but only if it hasn't been played back before, and mark it as played """ 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) )
[ "def", "play_response", "(", "self", ",", "request", ")", ":", "for", "index", ",", "response", "in", "self", ".", "_responses", "(", "request", ")", ":", "if", "self", ".", "play_counts", "[", "index", "]", "==", "0", ":", "self", ".", "play_counts", ...
Get the response corresponding to a request, but only if it hasn't been played back before, and mark it as played
[ "Get", "the", "response", "corresponding", "to", "a", "request", "but", "only", "if", "it", "hasn", "t", "been", "played", "back", "before", "and", "mark", "it", "as", "played" ]
114fcd29b43c55896aaa6a6613bc7766f2707c8b
https://github.com/kevin1024/vcrpy/blob/114fcd29b43c55896aaa6a6613bc7766f2707c8b/vcr/cassette.py#L259-L272
train
223,812
kevin1024/vcrpy
vcr/cassette.py
Cassette.responses_of
def responses_of(self, request): """ Find the responses corresponding to a request. This function isn't actually used by VCR internally, but is provided as an external API. """ 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) )
python
def responses_of(self, request): """ Find the responses corresponding to a request. This function isn't actually used by VCR internally, but is provided as an external API. """ 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) )
[ "def", "responses_of", "(", "self", ",", "request", ")", ":", "responses", "=", "[", "response", "for", "index", ",", "response", "in", "self", ".", "_responses", "(", "request", ")", "]", "if", "responses", ":", "return", "responses", "# The cassette doesn'...
Find the responses corresponding to a request. This function isn't actually used by VCR internally, but is provided as an external API.
[ "Find", "the", "responses", "corresponding", "to", "a", "request", ".", "This", "function", "isn", "t", "actually", "used", "by", "VCR", "internally", "but", "is", "provided", "as", "an", "external", "API", "." ]
114fcd29b43c55896aaa6a6613bc7766f2707c8b
https://github.com/kevin1024/vcrpy/blob/114fcd29b43c55896aaa6a6613bc7766f2707c8b/vcr/cassette.py#L274-L288
train
223,813
kevin1024/vcrpy
vcr/stubs/__init__.py
parse_headers
def parse_headers(header_list): """ Convert headers from our serialized dict with lists for keys to a HTTPMessage """ 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)
python
def parse_headers(header_list): """ Convert headers from our serialized dict with lists for keys to a HTTPMessage """ 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)
[ "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...
Convert headers from our serialized dict with lists for keys to a HTTPMessage
[ "Convert", "headers", "from", "our", "serialized", "dict", "with", "lists", "for", "keys", "to", "a", "HTTPMessage" ]
114fcd29b43c55896aaa6a6613bc7766f2707c8b
https://github.com/kevin1024/vcrpy/blob/114fcd29b43c55896aaa6a6613bc7766f2707c8b/vcr/stubs/__init__.py#L40-L50
train
223,814
kevin1024/vcrpy
vcr/stubs/__init__.py
VCRConnection._uri
def _uri(self, url): """Returns request absolute URI""" 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
python
def _uri(self, url): """Returns request absolute URI""" 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
[ "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", ".", "_prot...
Returns request absolute URI
[ "Returns", "request", "absolute", "URI" ]
114fcd29b43c55896aaa6a6613bc7766f2707c8b
https://github.com/kevin1024/vcrpy/blob/114fcd29b43c55896aaa6a6613bc7766f2707c8b/vcr/stubs/__init__.py#L137-L148
train
223,815
kevin1024/vcrpy
vcr/stubs/__init__.py
VCRConnection._url
def _url(self, uri): """Returns request selector url from absolute URI""" prefix = "{}://{}{}".format( self._protocol, self.real_connection.host, self._port_postfix(), ) return uri.replace(prefix, '', 1)
python
def _url(self, uri): """Returns request selector url from absolute URI""" prefix = "{}://{}{}".format( self._protocol, self.real_connection.host, self._port_postfix(), ) return uri.replace(prefix, '', 1)
[ "def", "_url", "(", "self", ",", "uri", ")", ":", "prefix", "=", "\"{}://{}{}\"", ".", "format", "(", "self", ".", "_protocol", ",", "self", ".", "real_connection", ".", "host", ",", "self", ".", "_port_postfix", "(", ")", ",", ")", "return", "uri", ...
Returns request selector url from absolute URI
[ "Returns", "request", "selector", "url", "from", "absolute", "URI" ]
114fcd29b43c55896aaa6a6613bc7766f2707c8b
https://github.com/kevin1024/vcrpy/blob/114fcd29b43c55896aaa6a6613bc7766f2707c8b/vcr/stubs/__init__.py#L150-L157
train
223,816
kevin1024/vcrpy
vcr/stubs/__init__.py
VCRConnection.request
def request(self, method, url, body=None, headers=None, *args, **kwargs): '''Persist the request metadata in self._vcr_request''' 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()
python
def request(self, method, url, body=None, headers=None, *args, **kwargs): '''Persist the request metadata in self._vcr_request''' 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()
[ "def", "request", "(", "self", ",", "method", ",", "url", ",", "body", "=", "None", ",", "headers", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_vcr_request", "=", "Request", "(", "method", "=", "method", ",", ...
Persist the request metadata in self._vcr_request
[ "Persist", "the", "request", "metadata", "in", "self", ".", "_vcr_request" ]
114fcd29b43c55896aaa6a6613bc7766f2707c8b
https://github.com/kevin1024/vcrpy/blob/114fcd29b43c55896aaa6a6613bc7766f2707c8b/vcr/stubs/__init__.py#L159-L174
train
223,817
kevin1024/vcrpy
vcr/stubs/__init__.py
VCRConnection.getresponse
def getresponse(self, _=False, **kwargs): '''Retrieve the response''' # 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)
python
def getresponse(self, _=False, **kwargs): '''Retrieve the response''' # 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)
[ "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", ".", ...
Retrieve the response
[ "Retrieve", "the", "response" ]
114fcd29b43c55896aaa6a6613bc7766f2707c8b
https://github.com/kevin1024/vcrpy/blob/114fcd29b43c55896aaa6a6613bc7766f2707c8b/vcr/stubs/__init__.py#L216-L272
train
223,818
kevin1024/vcrpy
vcr/stubs/__init__.py
VCRConnection.connect
def connect(self, *args, **kwargs): """ httplib2 uses this. Connects to the server I'm assuming. Only pass to the baseclass if we don't have a recorded response and are not write-protected. """ 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()
python
def connect(self, *args, **kwargs): """ httplib2 uses this. Connects to the server I'm assuming. Only pass to the baseclass if we don't have a recorded response and are not write-protected. """ 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()
[ "def", "connect", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "hasattr", "(", "self", ",", "'_vcr_request'", ")", "and", "self", ".", "cassette", ".", "can_play_response_for", "(", "self", ".", "_vcr_request", ")", ":", "# W...
httplib2 uses this. Connects to the server I'm assuming. Only pass to the baseclass if we don't have a recorded response and are not write-protected.
[ "httplib2", "uses", "this", ".", "Connects", "to", "the", "server", "I", "m", "assuming", "." ]
114fcd29b43c55896aaa6a6613bc7766f2707c8b
https://github.com/kevin1024/vcrpy/blob/114fcd29b43c55896aaa6a6613bc7766f2707c8b/vcr/stubs/__init__.py#L277-L299
train
223,819
kevin1024/vcrpy
vcr/patch.py
CassettePatcherBuilder._recursively_apply_get_cassette_subclass
def _recursively_apply_get_cassette_subclass(self, 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. This function exists to ensure that we use the same class object (reference) to patch everything that replaces VCRRequestHTTP[S]Connection, but that we can talk about patching them with the raw references instead, and without worrying about exactly where the subclass with the relevant value for `cassette` is first created. The function is recursive because it looks in to dictionaries and replaces class values at any depth with the subclass described in the previous paragraph. """ 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
python
def _recursively_apply_get_cassette_subclass(self, 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. This function exists to ensure that we use the same class object (reference) to patch everything that replaces VCRRequestHTTP[S]Connection, but that we can talk about patching them with the raw references instead, and without worrying about exactly where the subclass with the relevant value for `cassette` is first created. The function is recursive because it looks in to dictionaries and replaces class values at any depth with the subclass described in the previous paragraph. """ 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
[ "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", "(...
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. This function exists to ensure that we use the same class object (reference) to patch everything that replaces VCRRequestHTTP[S]Connection, but that we can talk about patching them with the raw references instead, and without worrying about exactly where the subclass with the relevant value for `cassette` is first created. The function is recursive because it looks in to dictionaries and replaces class values at any depth with the subclass described in the previous paragraph.
[ "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", "cas...
114fcd29b43c55896aaa6a6613bc7766f2707c8b
https://github.com/kevin1024/vcrpy/blob/114fcd29b43c55896aaa6a6613bc7766f2707c8b/vcr/patch.py#L131-L158
train
223,820
pymupdf/PyMuPDF
fitz/fitz.py
_Widget_fontdict
def _Widget_fontdict(): """Turns the above font definitions into a dictionary. Assumes certain line breaks and spaces. """ flist = Widget_fontobjects[2:-2].splitlines() fdict = {} for f in flist: k, v = f.split(" ") fdict[k[1:]] = v return fdict
python
def _Widget_fontdict(): """Turns the above font definitions into a dictionary. Assumes certain line breaks and spaces. """ flist = Widget_fontobjects[2:-2].splitlines() fdict = {} for f in flist: k, v = f.split(" ") fdict[k[1:]] = v return fdict
[ "def", "_Widget_fontdict", "(", ")", ":", "flist", "=", "Widget_fontobjects", "[", "2", ":", "-", "2", "]", ".", "splitlines", "(", ")", "fdict", "=", "{", "}", "for", "f", "in", "flist", ":", "k", ",", "v", "=", "f", ".", "split", "(", "\" \"", ...
Turns the above font definitions into a dictionary. Assumes certain line breaks and spaces.
[ "Turns", "the", "above", "font", "definitions", "into", "a", "dictionary", ".", "Assumes", "certain", "line", "breaks", "and", "spaces", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L1008-L1016
train
223,821
pymupdf/PyMuPDF
fitz/fitz.py
getTextlength
def getTextlength(text, fontname="helv", fontsize=11, encoding=0): """Calculate length of a string for a given built-in font. Args: fontname: name of the font. fontsize: size of font in points. encoding: encoding to use (0=Latin, 1=Greek, 2=Cyrillic). Returns: (float) length of text. """ 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)
python
def getTextlength(text, fontname="helv", fontsize=11, encoding=0): """Calculate length of a string for a given built-in font. Args: fontname: name of the font. fontsize: size of font in points. encoding: encoding to use (0=Latin, 1=Greek, 2=Cyrillic). Returns: (float) length of text. """ 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)
[ "def", "getTextlength", "(", "text", ",", "fontname", "=", "\"helv\"", ",", "fontsize", "=", "11", ",", "encoding", "=", "0", ")", ":", "fontname", "=", "fontname", ".", "lower", "(", ")", "basename", "=", "Base14_fontdict", ".", "get", "(", "fontname", ...
Calculate length of a string for a given built-in font. Args: fontname: name of the font. fontsize: size of font in points. encoding: encoding to use (0=Latin, 1=Greek, 2=Cyrillic). Returns: (float) length of text.
[ "Calculate", "length", "of", "a", "string", "for", "a", "given", "built", "-", "in", "font", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L1242-L1273
train
223,822
pymupdf/PyMuPDF
fitz/fitz.py
getPDFstr
def getPDFstr(s): """ Return a PDF string depending on its coding. Notes: If only ascii then "(original)" is returned, else if only 8 bit chars then "(original)" with interspersed octal strings \nnn is returned, else a string "<FEFF[hexstring]>" is returned, where [hexstring] is the UTF-16BE encoding of the original. """ 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 + ")"
python
def getPDFstr(s): """ Return a PDF string depending on its coding. Notes: If only ascii then "(original)" is returned, else if only 8 bit chars then "(original)" with interspersed octal strings \nnn is returned, else a string "<FEFF[hexstring]>" is returned, where [hexstring] is the UTF-16BE encoding of the original. """ 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 + ")"
[ "def", "getPDFstr", "(", "s", ")", ":", "if", "not", "bool", "(", "s", ")", ":", "return", "\"()\"", "def", "make_utf16be", "(", "s", ")", ":", "r", "=", "hexlify", "(", "bytearray", "(", "[", "254", ",", "255", "]", ")", "+", "bytearray", "(", ...
Return a PDF string depending on its coding. Notes: If only ascii then "(original)" is returned, else if only 8 bit chars then "(original)" with interspersed octal strings \nnn is returned, else a string "<FEFF[hexstring]>" is returned, where [hexstring] is the UTF-16BE encoding of the original.
[ "Return", "a", "PDF", "string", "depending", "on", "its", "coding", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L1464-L1516
train
223,823
pymupdf/PyMuPDF
fitz/fitz.py
CheckFont
def CheckFont(page, fontname): """Return an entry in the page's font list if reference name matches. """ for f in page.getFontList(): if f[4] == fontname: return f if f[3].lower() == fontname.lower(): return f return None
python
def CheckFont(page, fontname): """Return an entry in the page's font list if reference name matches. """ for f in page.getFontList(): if f[4] == fontname: return f if f[3].lower() == fontname.lower(): return f return None
[ "def", "CheckFont", "(", "page", ",", "fontname", ")", ":", "for", "f", "in", "page", ".", "getFontList", "(", ")", ":", "if", "f", "[", "4", "]", "==", "fontname", ":", "return", "f", "if", "f", "[", "3", "]", ".", "lower", "(", ")", "==", "...
Return an entry in the page's font list if reference name matches.
[ "Return", "an", "entry", "in", "the", "page", "s", "font", "list", "if", "reference", "name", "matches", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L1669-L1677
train
223,824
pymupdf/PyMuPDF
fitz/fitz.py
Matrix.invert
def invert(self, src=None): """Calculate the inverted matrix. Return 0 if successful and replace current one. Else return 1 and do nothing. """ 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
python
def invert(self, src=None): """Calculate the inverted matrix. Return 0 if successful and replace current one. Else return 1 and do nothing. """ 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
[ "def", "invert", "(", "self", ",", "src", "=", "None", ")", ":", "if", "src", "is", "None", ":", "dst", "=", "TOOLS", ".", "_invert_matrix", "(", "self", ")", "else", ":", "dst", "=", "TOOLS", ".", "_invert_matrix", "(", "src", ")", "if", "dst", ...
Calculate the inverted matrix. Return 0 if successful and replace current one. Else return 1 and do nothing.
[ "Calculate", "the", "inverted", "matrix", ".", "Return", "0", "if", "successful", "and", "replace", "current", "one", ".", "Else", "return", "1", "and", "do", "nothing", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L158-L169
train
223,825
pymupdf/PyMuPDF
fitz/fitz.py
Matrix.preTranslate
def preTranslate(self, tx, ty): """Calculate pre translation and replace current matrix.""" self.e += tx * self.a + ty * self.c self.f += tx * self.b + ty * self.d return self
python
def preTranslate(self, tx, ty): """Calculate pre translation and replace current matrix.""" self.e += tx * self.a + ty * self.c self.f += tx * self.b + ty * self.d return self
[ "def", "preTranslate", "(", "self", ",", "tx", ",", "ty", ")", ":", "self", ".", "e", "+=", "tx", "*", "self", ".", "a", "+", "ty", "*", "self", ".", "c", "self", ".", "f", "+=", "tx", "*", "self", ".", "b", "+", "ty", "*", "self", ".", "...
Calculate pre translation and replace current matrix.
[ "Calculate", "pre", "translation", "and", "replace", "current", "matrix", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L171-L175
train
223,826
pymupdf/PyMuPDF
fitz/fitz.py
Matrix.preScale
def preScale(self, sx, sy): """Calculate pre scaling and replace current matrix.""" self.a *= sx self.b *= sx self.c *= sy self.d *= sy return self
python
def preScale(self, sx, sy): """Calculate pre scaling and replace current matrix.""" self.a *= sx self.b *= sx self.c *= sy self.d *= sy return self
[ "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.
[ "Calculate", "pre", "scaling", "and", "replace", "current", "matrix", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L177-L183
train
223,827
pymupdf/PyMuPDF
fitz/fitz.py
Matrix.preShear
def preShear(self, h, v): """Calculate pre shearing and replace current matrix.""" 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
python
def preShear(self, h, v): """Calculate pre shearing and replace current matrix.""" 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
[ "def", "preShear", "(", "self", ",", "h", ",", "v", ")", ":", "a", ",", "b", "=", "self", ".", "a", ",", "self", ".", "b", "self", ".", "a", "+=", "v", "*", "self", ".", "c", "self", ".", "b", "+=", "v", "*", "self", ".", "d", "self", "...
Calculate pre shearing and replace current matrix.
[ "Calculate", "pre", "shearing", "and", "replace", "current", "matrix", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L185-L192
train
223,828
pymupdf/PyMuPDF
fitz/fitz.py
Matrix.preRotate
def preRotate(self, theta): """Calculate pre rotation and replace current matrix.""" 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
python
def preRotate(self, theta): """Calculate pre rotation and replace current matrix.""" 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
[ "def", "preRotate", "(", "self", ",", "theta", ")", ":", "while", "theta", "<", "0", ":", "theta", "+=", "360", "while", "theta", ">=", "360", ":", "theta", "-=", "360", "epsilon", "=", "1e-5", "if", "abs", "(", "0", "-", "theta", ")", "<", "epsi...
Calculate pre rotation and replace current matrix.
[ "Calculate", "pre", "rotation", "and", "replace", "current", "matrix", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L194-L235
train
223,829
pymupdf/PyMuPDF
fitz/fitz.py
Matrix.concat
def concat(self, one, two): """Multiply two matrices and replace current one.""" 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
python
def concat(self, one, two): """Multiply two matrices and replace current one.""" 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
[ "def", "concat", "(", "self", ",", "one", ",", "two", ")", ":", "if", "not", "len", "(", "one", ")", "==", "len", "(", "two", ")", "==", "6", ":", "raise", "ValueError", "(", "\"bad sequ. length\"", ")", "self", ".", "a", ",", "self", ".", "b", ...
Multiply two matrices and replace current one.
[ "Multiply", "two", "matrices", "and", "replace", "current", "one", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L237-L242
train
223,830
pymupdf/PyMuPDF
fitz/fitz.py
Point.transform
def transform(self, m): """Replace point by its transformation with matrix-like m.""" if len(m) != 6: raise ValueError("bad sequ. length") self.x, self.y = TOOLS._transform_point(self, m) return self
python
def transform(self, m): """Replace point by its transformation with matrix-like m.""" if len(m) != 6: raise ValueError("bad sequ. length") self.x, self.y = TOOLS._transform_point(self, m) return self
[ "def", "transform", "(", "self", ",", "m", ")", ":", "if", "len", "(", "m", ")", "!=", "6", ":", "raise", "ValueError", "(", "\"bad sequ. length\"", ")", "self", ".", "x", ",", "self", ".", "y", "=", "TOOLS", ".", "_transform_point", "(", "self", "...
Replace point by its transformation with matrix-like m.
[ "Replace", "point", "by", "its", "transformation", "with", "matrix", "-", "like", "m", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L386-L391
train
223,831
pymupdf/PyMuPDF
fitz/fitz.py
Point.unit
def unit(self): """Return unit vector of a point.""" 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)
python
def unit(self): """Return unit vector of a point.""" 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)
[ "def", "unit", "(", "self", ")", ":", "s", "=", "self", ".", "x", "*", "self", ".", "x", "+", "self", ".", "y", "*", "self", ".", "y", "if", "s", "<", "1e-5", ":", "return", "Point", "(", "0", ",", "0", ")", "s", "=", "math", ".", "sqrt",...
Return unit vector of a point.
[ "Return", "unit", "vector", "of", "a", "point", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L394-L400
train
223,832
pymupdf/PyMuPDF
fitz/fitz.py
Point.abs_unit
def abs_unit(self): """Return unit vector of a point with positive coordinates.""" 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)
python
def abs_unit(self): """Return unit vector of a point with positive coordinates.""" 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)
[ "def", "abs_unit", "(", "self", ")", ":", "s", "=", "self", ".", "x", "*", "self", ".", "x", "+", "self", ".", "y", "*", "self", ".", "y", "if", "s", "<", "1e-5", ":", "return", "Point", "(", "0", ",", "0", ")", "s", "=", "math", ".", "sq...
Return unit vector of a point with positive coordinates.
[ "Return", "unit", "vector", "of", "a", "point", "with", "positive", "coordinates", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L403-L409
train
223,833
pymupdf/PyMuPDF
fitz/fitz.py
Point.distance_to
def distance_to(self, *args): """Return the distance to a rectangle or another point.""" 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
python
def distance_to(self, *args): """Return the distance to a rectangle or another point.""" 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
[ "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", ...
Return the distance to a rectangle or another point.
[ "Return", "the", "distance", "to", "a", "rectangle", "or", "another", "point", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L411-L451
train
223,834
pymupdf/PyMuPDF
fitz/fitz.py
Rect.normalize
def normalize(self): """Replace rectangle with its finite version.""" 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
python
def normalize(self): """Replace rectangle with its finite version.""" 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
[ "def", "normalize", "(", "self", ")", ":", "if", "self", ".", "x1", "<", "self", ".", "x0", ":", "self", ".", "x0", ",", "self", ".", "x1", "=", "self", ".", "x1", ",", "self", ".", "x0", "if", "self", ".", "y1", "<", "self", ".", "y0", ":"...
Replace rectangle with its finite version.
[ "Replace", "rectangle", "with", "its", "finite", "version", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L572-L578
train
223,835
pymupdf/PyMuPDF
fitz/fitz.py
Rect.isEmpty
def isEmpty(self): """Check if rectangle area is empty.""" return self.x0 == self.x1 or self.y0 == self.y1
python
def isEmpty(self): """Check if rectangle area is empty.""" return self.x0 == self.x1 or self.y0 == self.y1
[ "def", "isEmpty", "(", "self", ")", ":", "return", "self", ".", "x0", "==", "self", ".", "x1", "or", "self", ".", "y0", "==", "self", ".", "y1" ]
Check if rectangle area is empty.
[ "Check", "if", "rectangle", "area", "is", "empty", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L581-L583
train
223,836
pymupdf/PyMuPDF
fitz/fitz.py
Rect.isInfinite
def isInfinite(self): """Check if rectangle is infinite.""" return self.x0 > self.x1 or self.y0 > self.y1
python
def isInfinite(self): """Check if rectangle is infinite.""" return self.x0 > self.x1 or self.y0 > self.y1
[ "def", "isInfinite", "(", "self", ")", ":", "return", "self", ".", "x0", ">", "self", ".", "x1", "or", "self", ".", "y0", ">", "self", ".", "y1" ]
Check if rectangle is infinite.
[ "Check", "if", "rectangle", "is", "infinite", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L586-L588
train
223,837
pymupdf/PyMuPDF
fitz/fitz.py
Rect.includePoint
def includePoint(self, p): """Extend rectangle to include point 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
python
def includePoint(self, p): """Extend rectangle to include point 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
[ "def", "includePoint", "(", "self", ",", "p", ")", ":", "if", "not", "len", "(", "p", ")", "==", "2", ":", "raise", "ValueError", "(", "\"bad sequ. length\"", ")", "self", ".", "x0", ",", "self", ".", "y0", ",", "self", ".", "x1", ",", "self", "....
Extend rectangle to include point p.
[ "Extend", "rectangle", "to", "include", "point", "p", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L624-L629
train
223,838
pymupdf/PyMuPDF
fitz/fitz.py
Rect.includeRect
def includeRect(self, r): """Extend rectangle to include rectangle 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
python
def includeRect(self, r): """Extend rectangle to include rectangle 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
[ "def", "includeRect", "(", "self", ",", "r", ")", ":", "if", "not", "len", "(", "r", ")", "==", "4", ":", "raise", "ValueError", "(", "\"bad sequ. length\"", ")", "self", ".", "x0", ",", "self", ".", "y0", ",", "self", ".", "x1", ",", "self", "."...
Extend rectangle to include rectangle r.
[ "Extend", "rectangle", "to", "include", "rectangle", "r", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L631-L636
train
223,839
pymupdf/PyMuPDF
fitz/fitz.py
Rect.intersect
def intersect(self, r): """Restrict self to common area with rectangle 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
python
def intersect(self, r): """Restrict self to common area with rectangle 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
[ "def", "intersect", "(", "self", ",", "r", ")", ":", "if", "not", "len", "(", "r", ")", "==", "4", ":", "raise", "ValueError", "(", "\"bad sequ. length\"", ")", "self", ".", "x0", ",", "self", ".", "y0", ",", "self", ".", "x1", ",", "self", ".", ...
Restrict self to common area with rectangle r.
[ "Restrict", "self", "to", "common", "area", "with", "rectangle", "r", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L638-L643
train
223,840
pymupdf/PyMuPDF
fitz/fitz.py
Rect.transform
def transform(self, m): """Replace rectangle with its transformation by matrix 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
python
def transform(self, m): """Replace rectangle with its transformation by matrix 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
[ "def", "transform", "(", "self", ",", "m", ")", ":", "if", "not", "len", "(", "m", ")", "==", "6", ":", "raise", "ValueError", "(", "\"bad sequ. length\"", ")", "self", ".", "x0", ",", "self", ".", "y0", ",", "self", ".", "x1", ",", "self", ".", ...
Replace rectangle with its transformation by matrix m.
[ "Replace", "rectangle", "with", "its", "transformation", "by", "matrix", "m", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L645-L650
train
223,841
pymupdf/PyMuPDF
fitz/fitz.py
Rect.intersects
def intersects(self, x): """Check if intersection with rectangle x is not empty.""" 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
python
def intersects(self, x): """Check if intersection with rectangle x is not empty.""" 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
[ "def", "intersects", "(", "self", ",", "x", ")", ":", "r1", "=", "Rect", "(", "x", ")", "if", "self", ".", "isEmpty", "or", "self", ".", "isInfinite", "or", "r1", ".", "isEmpty", ":", "return", "False", "r", "=", "Rect", "(", "self", ")", "if", ...
Check if intersection with rectangle x is not empty.
[ "Check", "if", "intersection", "with", "rectangle", "x", "is", "not", "empty", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L766-L774
train
223,842
pymupdf/PyMuPDF
fitz/fitz.py
Quad.isRectangular
def isRectangular(self): """Check if quad is rectangular. """ # 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
python
def isRectangular(self): """Check if quad is rectangular. """ # 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
[ "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", ...
Check if quad is rectangular.
[ "Check", "if", "quad", "is", "rectangular", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L879-L900
train
223,843
pymupdf/PyMuPDF
fitz/fitz.py
Quad.transform
def transform(self, m): """Replace quad by its transformation with matrix m.""" if len(m) != 6: raise ValueError("bad sequ. length") self.ul *= m self.ur *= m self.ll *= m self.lr *= m return self
python
def transform(self, m): """Replace quad by its transformation with matrix m.""" if len(m) != 6: raise ValueError("bad sequ. length") self.ul *= m self.ur *= m self.ll *= m self.lr *= m return self
[ "def", "transform", "(", "self", ",", "m", ")", ":", "if", "len", "(", "m", ")", "!=", "6", ":", "raise", "ValueError", "(", "\"bad sequ. length\"", ")", "self", ".", "ul", "*=", "m", "self", ".", "ur", "*=", "m", "self", ".", "ll", "*=", "m", ...
Replace quad by its transformation with matrix m.
[ "Replace", "quad", "by", "its", "transformation", "with", "matrix", "m", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L968-L976
train
223,844
pymupdf/PyMuPDF
fitz/fitz.py
Widget._validate
def _validate(self): """Validate the class entries. """ 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]()
python
def _validate(self): """Validate the class entries. """ 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]()
[ "def", "_validate", "(", "self", ")", ":", "checker", "=", "(", "self", ".", "_check0", ",", "self", ".", "_check1", ",", "self", ".", "_check2", ",", "self", ".", "_check3", ",", "self", ".", "_check4", ",", "self", ".", "_check5", ")", "if", "not...
Validate the class entries.
[ "Validate", "the", "class", "entries", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L1047-L1083
train
223,845
pymupdf/PyMuPDF
fitz/fitz.py
Widget._adjust_font
def _adjust_font(self): """Ensure the font name is from our list and correctly spelled. """ 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
python
def _adjust_font(self): """Ensure the font name is from our list and correctly spelled. """ 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
[ "def", "_adjust_font", "(", "self", ")", ":", "fnames", "=", "[", "k", "for", "k", "in", "Widget_fontdict", ".", "keys", "(", ")", "]", "fl", "=", "list", "(", "map", "(", "str", ".", "lower", ",", "fnames", ")", ")", "if", "(", "not", "self", ...
Ensure the font name is from our list and correctly spelled.
[ "Ensure", "the", "font", "name", "is", "from", "our", "list", "and", "correctly", "spelled", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L1085-L1094
train
223,846
pymupdf/PyMuPDF
fitz/fitz.py
Document.embeddedFileCount
def embeddedFileCount(self): """Return number of embedded files.""" if self.isClosed or self.isEncrypted: raise ValueError("operation illegal for closed / encrypted doc") return _fitz.Document_embeddedFileCount(self)
python
def embeddedFileCount(self): """Return number of embedded files.""" if self.isClosed or self.isEncrypted: raise ValueError("operation illegal for closed / encrypted doc") return _fitz.Document_embeddedFileCount(self)
[ "def", "embeddedFileCount", "(", "self", ")", ":", "if", "self", ".", "isClosed", "or", "self", ".", "isEncrypted", ":", "raise", "ValueError", "(", "\"operation illegal for closed / encrypted doc\"", ")", "return", "_fitz", ".", "Document_embeddedFileCount", "(", "...
Return number of embedded files.
[ "Return", "number", "of", "embedded", "files", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L1906-L1911
train
223,847
pymupdf/PyMuPDF
fitz/fitz.py
Document.embeddedFileDel
def embeddedFileDel(self, name): """Delete embedded file by name.""" if self.isClosed or self.isEncrypted: raise ValueError("operation illegal for closed / encrypted doc") return _fitz.Document_embeddedFileDel(self, name)
python
def embeddedFileDel(self, name): """Delete embedded file by name.""" if self.isClosed or self.isEncrypted: raise ValueError("operation illegal for closed / encrypted doc") return _fitz.Document_embeddedFileDel(self, name)
[ "def", "embeddedFileDel", "(", "self", ",", "name", ")", ":", "if", "self", ".", "isClosed", "or", "self", ".", "isEncrypted", ":", "raise", "ValueError", "(", "\"operation illegal for closed / encrypted doc\"", ")", "return", "_fitz", ".", "Document_embeddedFileDel...
Delete embedded file by name.
[ "Delete", "embedded", "file", "by", "name", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L1914-L1919
train
223,848
pymupdf/PyMuPDF
fitz/fitz.py
Document.embeddedFileInfo
def embeddedFileInfo(self, id): """Retrieve embedded file information given its entry number or name.""" if self.isClosed or self.isEncrypted: raise ValueError("operation illegal for closed / encrypted doc") return _fitz.Document_embeddedFileInfo(self, id)
python
def embeddedFileInfo(self, id): """Retrieve embedded file information given its entry number or name.""" if self.isClosed or self.isEncrypted: raise ValueError("operation illegal for closed / encrypted doc") return _fitz.Document_embeddedFileInfo(self, id)
[ "def", "embeddedFileInfo", "(", "self", ",", "id", ")", ":", "if", "self", ".", "isClosed", "or", "self", ".", "isEncrypted", ":", "raise", "ValueError", "(", "\"operation illegal for closed / encrypted doc\"", ")", "return", "_fitz", ".", "Document_embeddedFileInfo...
Retrieve embedded file information given its entry number or name.
[ "Retrieve", "embedded", "file", "information", "given", "its", "entry", "number", "or", "name", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L1922-L1927
train
223,849
pymupdf/PyMuPDF
fitz/fitz.py
Document.embeddedFileUpd
def embeddedFileUpd(self, id, buffer=None, filename=None, ufilename=None, desc=None): """Change an embedded file given its entry number or name.""" return _fitz.Document_embeddedFileUpd(self, id, buffer, filename, ufilename, desc)
python
def embeddedFileUpd(self, id, buffer=None, filename=None, ufilename=None, desc=None): """Change an embedded file given its entry number or name.""" return _fitz.Document_embeddedFileUpd(self, id, buffer, filename, ufilename, desc)
[ "def", "embeddedFileUpd", "(", "self", ",", "id", ",", "buffer", "=", "None", ",", "filename", "=", "None", ",", "ufilename", "=", "None", ",", "desc", "=", "None", ")", ":", "return", "_fitz", ".", "Document_embeddedFileUpd", "(", "self", ",", "id", "...
Change an embedded file given its entry number or name.
[ "Change", "an", "embedded", "file", "given", "its", "entry", "number", "or", "name", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L1930-L1932
train
223,850
pymupdf/PyMuPDF
fitz/fitz.py
Document.embeddedFileGet
def embeddedFileGet(self, id): """Retrieve embedded file content by name or by number.""" if self.isClosed or self.isEncrypted: raise ValueError("operation illegal for closed / encrypted doc") return _fitz.Document_embeddedFileGet(self, id)
python
def embeddedFileGet(self, id): """Retrieve embedded file content by name or by number.""" if self.isClosed or self.isEncrypted: raise ValueError("operation illegal for closed / encrypted doc") return _fitz.Document_embeddedFileGet(self, id)
[ "def", "embeddedFileGet", "(", "self", ",", "id", ")", ":", "if", "self", ".", "isClosed", "or", "self", ".", "isEncrypted", ":", "raise", "ValueError", "(", "\"operation illegal for closed / encrypted doc\"", ")", "return", "_fitz", ".", "Document_embeddedFileGet",...
Retrieve embedded file content by name or by number.
[ "Retrieve", "embedded", "file", "content", "by", "name", "or", "by", "number", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L1940-L1945
train
223,851
pymupdf/PyMuPDF
fitz/fitz.py
Document.embeddedFileAdd
def embeddedFileAdd(self, buffer, name, filename=None, ufilename=None, desc=None): """Embed a new file.""" if self.isClosed or self.isEncrypted: raise ValueError("operation illegal for closed / encrypted doc") return _fitz.Document_embeddedFileAdd(self, buffer, name, filename, ufilename, desc)
python
def embeddedFileAdd(self, buffer, name, filename=None, ufilename=None, desc=None): """Embed a new file.""" if self.isClosed or self.isEncrypted: raise ValueError("operation illegal for closed / encrypted doc") return _fitz.Document_embeddedFileAdd(self, buffer, name, filename, ufilename, desc)
[ "def", "embeddedFileAdd", "(", "self", ",", "buffer", ",", "name", ",", "filename", "=", "None", ",", "ufilename", "=", "None", ",", "desc", "=", "None", ")", ":", "if", "self", ".", "isClosed", "or", "self", ".", "isEncrypted", ":", "raise", "ValueErr...
Embed a new file.
[ "Embed", "a", "new", "file", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L1948-L1955
train
223,852
pymupdf/PyMuPDF
fitz/fitz.py
Document.convertToPDF
def convertToPDF(self, from_page=0, to_page=-1, rotate=0): """Convert document to PDF selecting page range and optional rotation. Output bytes object.""" if self.isClosed or self.isEncrypted: raise ValueError("operation illegal for closed / encrypted doc") return _fitz.Document_convertToPDF(self, from_page, to_page, rotate)
python
def convertToPDF(self, from_page=0, to_page=-1, rotate=0): """Convert document to PDF selecting page range and optional rotation. Output bytes object.""" if self.isClosed or self.isEncrypted: raise ValueError("operation illegal for closed / encrypted doc") return _fitz.Document_convertToPDF(self, from_page, to_page, rotate)
[ "def", "convertToPDF", "(", "self", ",", "from_page", "=", "0", ",", "to_page", "=", "-", "1", ",", "rotate", "=", "0", ")", ":", "if", "self", ".", "isClosed", "or", "self", ".", "isEncrypted", ":", "raise", "ValueError", "(", "\"operation illegal for c...
Convert document to PDF selecting page range and optional rotation. Output bytes object.
[ "Convert", "document", "to", "PDF", "selecting", "page", "range", "and", "optional", "rotation", ".", "Output", "bytes", "object", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L1958-L1963
train
223,853
pymupdf/PyMuPDF
fitz/fitz.py
Document.layout
def layout(self, rect=None, width=0, height=0, fontsize=11): """Re-layout a reflowable document.""" 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
python
def layout(self, rect=None, width=0, height=0, fontsize=11): """Re-layout a reflowable document.""" 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
[ "def", "layout", "(", "self", ",", "rect", "=", "None", ",", "width", "=", "0", ",", "height", "=", "0", ",", "fontsize", "=", "11", ")", ":", "if", "self", ".", "isClosed", "or", "self", ".", "isEncrypted", ":", "raise", "ValueError", "(", "\"oper...
Re-layout a reflowable document.
[ "Re", "-", "layout", "a", "reflowable", "document", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L1997-L2007
train
223,854
pymupdf/PyMuPDF
fitz/fitz.py
Document.makeBookmark
def makeBookmark(self, pno=0): """Make page bookmark in a reflowable document.""" if self.isClosed or self.isEncrypted: raise ValueError("operation illegal for closed / encrypted doc") return _fitz.Document_makeBookmark(self, pno)
python
def makeBookmark(self, pno=0): """Make page bookmark in a reflowable document.""" if self.isClosed or self.isEncrypted: raise ValueError("operation illegal for closed / encrypted doc") return _fitz.Document_makeBookmark(self, pno)
[ "def", "makeBookmark", "(", "self", ",", "pno", "=", "0", ")", ":", "if", "self", ".", "isClosed", "or", "self", ".", "isEncrypted", ":", "raise", "ValueError", "(", "\"operation illegal for closed / encrypted doc\"", ")", "return", "_fitz", ".", "Document_makeB...
Make page bookmark in a reflowable document.
[ "Make", "page", "bookmark", "in", "a", "reflowable", "document", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L2010-L2015
train
223,855
pymupdf/PyMuPDF
fitz/fitz.py
Document.findBookmark
def findBookmark(self, bookmark): """Find page number after layouting a document.""" if self.isClosed or self.isEncrypted: raise ValueError("operation illegal for closed / encrypted doc") return _fitz.Document_findBookmark(self, bookmark)
python
def findBookmark(self, bookmark): """Find page number after layouting a document.""" if self.isClosed or self.isEncrypted: raise ValueError("operation illegal for closed / encrypted doc") return _fitz.Document_findBookmark(self, bookmark)
[ "def", "findBookmark", "(", "self", ",", "bookmark", ")", ":", "if", "self", ".", "isClosed", "or", "self", ".", "isEncrypted", ":", "raise", "ValueError", "(", "\"operation illegal for closed / encrypted doc\"", ")", "return", "_fitz", ".", "Document_findBookmark",...
Find page number after layouting a document.
[ "Find", "page", "number", "after", "layouting", "a", "document", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L2018-L2023
train
223,856
pymupdf/PyMuPDF
fitz/fitz.py
Document._deleteObject
def _deleteObject(self, xref): """Delete an object given its xref.""" if self.isClosed: raise ValueError("operation illegal for closed doc") return _fitz.Document__deleteObject(self, xref)
python
def _deleteObject(self, xref): """Delete an object given its xref.""" if self.isClosed: raise ValueError("operation illegal for closed doc") return _fitz.Document__deleteObject(self, xref)
[ "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.
[ "Delete", "an", "object", "given", "its", "xref", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L2035-L2040
train
223,857
pymupdf/PyMuPDF
fitz/fitz.py
Document.authenticate
def authenticate(self, password): """Decrypt document with a 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
python
def authenticate(self, password): """Decrypt document with a 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
[ "def", "authenticate", "(", "self", ",", "password", ")", ":", "if", "self", ".", "isClosed", ":", "raise", "ValueError", "(", "\"operation illegal for closed doc\"", ")", "val", "=", "_fitz", ".", "Document_authenticate", "(", "self", ",", "password", ")", "i...
Decrypt document with a password.
[ "Decrypt", "document", "with", "a", "password", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L2105-L2118
train
223,858
pymupdf/PyMuPDF
fitz/fitz.py
Document.write
def write(self, garbage=0, clean=0, deflate=0, ascii=0, expand=0, linear=0, pretty=0, decrypt=1): """Write document to a bytes object.""" 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)
python
def write(self, garbage=0, clean=0, deflate=0, ascii=0, expand=0, linear=0, pretty=0, decrypt=1): """Write document to a bytes object.""" 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)
[ "def", "write", "(", "self", ",", "garbage", "=", "0", ",", "clean", "=", "0", ",", "deflate", "=", "0", ",", "ascii", "=", "0", ",", "expand", "=", "0", ",", "linear", "=", "0", ",", "pretty", "=", "0", ",", "decrypt", "=", "1", ")", ":", ...
Write document to a bytes object.
[ "Write", "document", "to", "a", "bytes", "object", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L2144-L2153
train
223,859
pymupdf/PyMuPDF
fitz/fitz.py
Document.select
def select(self, pyliste): """Build sub-pdf with page numbers in 'list'.""" 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
python
def select(self, pyliste): """Build sub-pdf with page numbers in 'list'.""" 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
[ "def", "select", "(", "self", ",", "pyliste", ")", ":", "if", "self", ".", "isClosed", "or", "self", ".", "isEncrypted", ":", "raise", "ValueError", "(", "\"operation illegal for closed / encrypted doc\"", ")", "val", "=", "_fitz", ".", "Document_select", "(", ...
Build sub-pdf with page numbers in 'list'.
[ "Build", "sub", "-", "pdf", "with", "page", "numbers", "in", "list", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L2186-L2196
train
223,860
pymupdf/PyMuPDF
fitz/fitz.py
Document._getCharWidths
def _getCharWidths(self, xref, bfname, ext, ordering, limit, idx=0): """Return list of glyphs and glyph widths of a font.""" 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)
python
def _getCharWidths(self, xref, bfname, ext, ordering, limit, idx=0): """Return list of glyphs and glyph widths of a font.""" 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)
[ "def", "_getCharWidths", "(", "self", ",", "xref", ",", "bfname", ",", "ext", ",", "ordering", ",", "limit", ",", "idx", "=", "0", ")", ":", "if", "self", ".", "isClosed", "or", "self", ".", "isEncrypted", ":", "raise", "ValueError", "(", "\"operation ...
Return list of glyphs and glyph widths of a font.
[ "Return", "list", "of", "glyphs", "and", "glyph", "widths", "of", "a", "font", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L2208-L2213
train
223,861
pymupdf/PyMuPDF
fitz/fitz.py
Document._getPageInfo
def _getPageInfo(self, pno, what): """Show fonts or images used on a page.""" 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
python
def _getPageInfo(self, pno, what): """Show fonts or images used on a page.""" 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
[ "def", "_getPageInfo", "(", "self", ",", "pno", ",", "what", ")", ":", "if", "self", ".", "isClosed", "or", "self", ".", "isEncrypted", ":", "raise", "ValueError", "(", "\"operation illegal for closed / encrypted doc\"", ")", "val", "=", "_fitz", ".", "Documen...
Show fonts or images used on a page.
[ "Show", "fonts", "or", "images", "used", "on", "a", "page", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L2224-L2237
train
223,862
pymupdf/PyMuPDF
fitz/fitz.py
Document.extractImage
def extractImage(self, xref=0): """Extract image which 'xref' is pointing to.""" if self.isClosed or self.isEncrypted: raise ValueError("operation illegal for closed / encrypted doc") return _fitz.Document_extractImage(self, xref)
python
def extractImage(self, xref=0): """Extract image which 'xref' is pointing to.""" if self.isClosed or self.isEncrypted: raise ValueError("operation illegal for closed / encrypted doc") return _fitz.Document_extractImage(self, xref)
[ "def", "extractImage", "(", "self", ",", "xref", "=", "0", ")", ":", "if", "self", ".", "isClosed", "or", "self", ".", "isEncrypted", ":", "raise", "ValueError", "(", "\"operation illegal for closed / encrypted doc\"", ")", "return", "_fitz", ".", "Document_extr...
Extract image which 'xref' is pointing to.
[ "Extract", "image", "which", "xref", "is", "pointing", "to", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L2248-L2253
train
223,863
pymupdf/PyMuPDF
fitz/fitz.py
Document.getPageFontList
def getPageFontList(self, pno): """Retrieve a list of fonts used on a page. """ if self.isClosed or self.isEncrypted: raise ValueError("operation illegal for closed / encrypted doc") if self.isPDF: return self._getPageInfo(pno, 1) return []
python
def getPageFontList(self, pno): """Retrieve a list of fonts used on a page. """ if self.isClosed or self.isEncrypted: raise ValueError("operation illegal for closed / encrypted doc") if self.isPDF: return self._getPageInfo(pno, 1) return []
[ "def", "getPageFontList", "(", "self", ",", "pno", ")", ":", "if", "self", ".", "isClosed", "or", "self", ".", "isEncrypted", ":", "raise", "ValueError", "(", "\"operation illegal for closed / encrypted doc\"", ")", "if", "self", ".", "isPDF", ":", "return", "...
Retrieve a list of fonts used on a page.
[ "Retrieve", "a", "list", "of", "fonts", "used", "on", "a", "page", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L2391-L2398
train
223,864
pymupdf/PyMuPDF
fitz/fitz.py
Document.getPageImageList
def getPageImageList(self, pno): """Retrieve a list of images used on a page. """ if self.isClosed or self.isEncrypted: raise ValueError("operation illegal for closed / encrypted doc") if self.isPDF: return self._getPageInfo(pno, 2) return []
python
def getPageImageList(self, pno): """Retrieve a list of images used on a page. """ if self.isClosed or self.isEncrypted: raise ValueError("operation illegal for closed / encrypted doc") if self.isPDF: return self._getPageInfo(pno, 2) return []
[ "def", "getPageImageList", "(", "self", ",", "pno", ")", ":", "if", "self", ".", "isClosed", "or", "self", ".", "isEncrypted", ":", "raise", "ValueError", "(", "\"operation illegal for closed / encrypted doc\"", ")", "if", "self", ".", "isPDF", ":", "return", ...
Retrieve a list of images used on a page.
[ "Retrieve", "a", "list", "of", "images", "used", "on", "a", "page", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L2400-L2407
train
223,865
pymupdf/PyMuPDF
fitz/fitz.py
Document.copyPage
def copyPage(self, pno, to=-1): """Copy a page to before some other page of the document. Specify 'to = -1' to copy after last page. """ 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)
python
def copyPage(self, pno, to=-1): """Copy a page to before some other page of the document. Specify 'to = -1' to copy after last page. """ 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)
[ "def", "copyPage", "(", "self", ",", "pno", ",", "to", "=", "-", "1", ")", ":", "pl", "=", "list", "(", "range", "(", "len", "(", "self", ")", ")", ")", "if", "pno", "<", "0", "or", "pno", ">", "pl", "[", "-", "1", "]", ":", "raise", "Val...
Copy a page to before some other page of the document. Specify 'to = -1' to copy after last page.
[ "Copy", "a", "page", "to", "before", "some", "other", "page", "of", "the", "document", ".", "Specify", "to", "=", "-", "1", "to", "copy", "after", "last", "page", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L2409-L2421
train
223,866
pymupdf/PyMuPDF
fitz/fitz.py
Document.movePage
def movePage(self, pno, to = -1): """Move a page to before some other page of the document. Specify 'to = -1' to move after last page. """ 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)
python
def movePage(self, pno, to = -1): """Move a page to before some other page of the document. Specify 'to = -1' to move after last page. """ 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)
[ "def", "movePage", "(", "self", ",", "pno", ",", "to", "=", "-", "1", ")", ":", "pl", "=", "list", "(", "range", "(", "len", "(", "self", ")", ")", ")", "if", "pno", "<", "0", "or", "pno", ">", "pl", "[", "-", "1", "]", ":", "raise", "Val...
Move a page to before some other page of the document. Specify 'to = -1' to move after last page.
[ "Move", "a", "page", "to", "before", "some", "other", "page", "of", "the", "document", ".", "Specify", "to", "=", "-", "1", "to", "move", "after", "last", "page", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L2423-L2436
train
223,867
pymupdf/PyMuPDF
fitz/fitz.py
Document.deletePage
def deletePage(self, pno = -1): """Delete a page from the document. First page is '0', last page is '-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)
python
def deletePage(self, pno = -1): """Delete a page from the document. First page is '0', last page is '-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)
[ "def", "deletePage", "(", "self", ",", "pno", "=", "-", "1", ")", ":", "pl", "=", "list", "(", "range", "(", "len", "(", "self", ")", ")", ")", "if", "pno", "<", "-", "1", "or", "pno", ">", "pl", "[", "-", "1", "]", ":", "raise", "ValueErro...
Delete a page from the document. First page is '0', last page is '-1'.
[ "Delete", "a", "page", "from", "the", "document", ".", "First", "page", "is", "0", "last", "page", "is", "-", "1", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L2438-L2448
train
223,868
pymupdf/PyMuPDF
fitz/fitz.py
Document.deletePageRange
def deletePageRange(self, from_page = -1, to_page = -1): """Delete pages from the document. First page is '0', last page is '-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)
python
def deletePageRange(self, from_page = -1, to_page = -1): """Delete pages from the document. First page is '0', last page is '-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)
[ "def", "deletePageRange", "(", "self", ",", "from_page", "=", "-", "1", ",", "to_page", "=", "-", "1", ")", ":", "pl", "=", "list", "(", "range", "(", "len", "(", "self", ")", ")", ")", "f", "=", "from_page", "t", "=", "to_page", "if", "f", "==...
Delete pages from the document. First page is '0', last page is '-1'.
[ "Delete", "pages", "from", "the", "document", ".", "First", "page", "is", "0", "last", "page", "is", "-", "1", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L2450-L2464
train
223,869
pymupdf/PyMuPDF
fitz/fitz.py
Document._forget_page
def _forget_page(self, page): """Remove a page from document page dict.""" pid = id(page) if pid in self._page_refs: self._page_refs[pid] = None
python
def _forget_page(self, page): """Remove a page from document page dict.""" pid = id(page) if pid in self._page_refs: self._page_refs[pid] = None
[ "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.
[ "Remove", "a", "page", "from", "document", "page", "dict", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L2488-L2492
train
223,870
pymupdf/PyMuPDF
fitz/fitz.py
Document._reset_page_refs
def _reset_page_refs(self): """Invalidate all pages in document dictionary.""" if self.isClosed: return for page in self._page_refs.values(): if page: page._erase() page = None self._page_refs.clear()
python
def _reset_page_refs(self): """Invalidate all pages in document dictionary.""" if self.isClosed: return for page in self._page_refs.values(): if page: page._erase() page = None self._page_refs.clear()
[ "def", "_reset_page_refs", "(", "self", ")", ":", "if", "self", ".", "isClosed", ":", "return", "for", "page", "in", "self", ".", "_page_refs", ".", "values", "(", ")", ":", "if", "page", ":", "page", ".", "_erase", "(", ")", "page", "=", "None", "...
Invalidate all pages in document dictionary.
[ "Invalidate", "all", "pages", "in", "document", "dictionary", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L2494-L2502
train
223,871
pymupdf/PyMuPDF
fitz/fitz.py
Page.addLineAnnot
def addLineAnnot(self, p1, p2): """Add 'Line' annot for points p1 and 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
python
def addLineAnnot(self, p1, p2): """Add 'Line' annot for points p1 and 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
[ "def", "addLineAnnot", "(", "self", ",", "p1", ",", "p2", ")", ":", "CheckParent", "(", "self", ")", "val", "=", "_fitz", ".", "Page_addLineAnnot", "(", "self", ",", "p1", ",", "p2", ")", "if", "not", "val", ":", "return", "val", ".", "thisown", "=...
Add 'Line' annot for points p1 and p2.
[ "Add", "Line", "annot", "for", "points", "p1", "and", "p2", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L2563-L2574
train
223,872
pymupdf/PyMuPDF
fitz/fitz.py
Page.addTextAnnot
def addTextAnnot(self, point, text): """Add a 'sticky note' at position 'point'.""" 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
python
def addTextAnnot(self, point, text): """Add a 'sticky note' at position 'point'.""" 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
[ "def", "addTextAnnot", "(", "self", ",", "point", ",", "text", ")", ":", "CheckParent", "(", "self", ")", "val", "=", "_fitz", ".", "Page_addTextAnnot", "(", "self", ",", "point", ",", "text", ")", "if", "not", "val", ":", "return", "val", ".", "this...
Add a 'sticky note' at position 'point'.
[ "Add", "a", "sticky", "note", "at", "position", "point", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L2577-L2588
train
223,873
pymupdf/PyMuPDF
fitz/fitz.py
Page.addInkAnnot
def addInkAnnot(self, list): """Add a 'handwriting' as a list of list of point-likes. Each sublist forms an independent stroke.""" 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
python
def addInkAnnot(self, list): """Add a 'handwriting' as a list of list of point-likes. Each sublist forms an independent stroke.""" 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
[ "def", "addInkAnnot", "(", "self", ",", "list", ")", ":", "CheckParent", "(", "self", ")", "val", "=", "_fitz", ".", "Page_addInkAnnot", "(", "self", ",", "list", ")", "if", "not", "val", ":", "return", "val", ".", "thisown", "=", "True", "val", ".",...
Add a 'handwriting' as a list of list of point-likes. Each sublist forms an independent stroke.
[ "Add", "a", "handwriting", "as", "a", "list", "of", "list", "of", "point", "-", "likes", ".", "Each", "sublist", "forms", "an", "independent", "stroke", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L2591-L2602
train
223,874
pymupdf/PyMuPDF
fitz/fitz.py
Page.addStampAnnot
def addStampAnnot(self, rect, stamp=0): """Add a 'rubber stamp' in a rectangle.""" 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
python
def addStampAnnot(self, rect, stamp=0): """Add a 'rubber stamp' in a rectangle.""" 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
[ "def", "addStampAnnot", "(", "self", ",", "rect", ",", "stamp", "=", "0", ")", ":", "CheckParent", "(", "self", ")", "val", "=", "_fitz", ".", "Page_addStampAnnot", "(", "self", ",", "rect", ",", "stamp", ")", "if", "not", "val", ":", "return", "val"...
Add a 'rubber stamp' in a rectangle.
[ "Add", "a", "rubber", "stamp", "in", "a", "rectangle", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L2605-L2616
train
223,875
pymupdf/PyMuPDF
fitz/fitz.py
Page.addFileAnnot
def addFileAnnot(self, point, buffer, filename, ufilename=None, desc=None): """Add a 'FileAttachment' annotation at location 'point'.""" 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
python
def addFileAnnot(self, point, buffer, filename, ufilename=None, desc=None): """Add a 'FileAttachment' annotation at location 'point'.""" 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
[ "def", "addFileAnnot", "(", "self", ",", "point", ",", "buffer", ",", "filename", ",", "ufilename", "=", "None", ",", "desc", "=", "None", ")", ":", "CheckParent", "(", "self", ")", "val", "=", "_fitz", ".", "Page_addFileAnnot", "(", "self", ",", "poin...
Add a 'FileAttachment' annotation at location 'point'.
[ "Add", "a", "FileAttachment", "annotation", "at", "location", "point", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L2619-L2630
train
223,876
pymupdf/PyMuPDF
fitz/fitz.py
Page.addStrikeoutAnnot
def addStrikeoutAnnot(self, rect): """Strike out content in a rectangle or quadrilateral.""" 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
python
def addStrikeoutAnnot(self, rect): """Strike out content in a rectangle or quadrilateral.""" 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
[ "def", "addStrikeoutAnnot", "(", "self", ",", "rect", ")", ":", "CheckParent", "(", "self", ")", "val", "=", "_fitz", ".", "Page_addStrikeoutAnnot", "(", "self", ",", "rect", ")", "if", "not", "val", ":", "return", "val", ".", "thisown", "=", "True", "...
Strike out content in a rectangle or quadrilateral.
[ "Strike", "out", "content", "in", "a", "rectangle", "or", "quadrilateral", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L2633-L2644
train
223,877
pymupdf/PyMuPDF
fitz/fitz.py
Page.addUnderlineAnnot
def addUnderlineAnnot(self, rect): """Underline content in a rectangle or quadrilateral.""" 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
python
def addUnderlineAnnot(self, rect): """Underline content in a rectangle or quadrilateral.""" 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
[ "def", "addUnderlineAnnot", "(", "self", ",", "rect", ")", ":", "CheckParent", "(", "self", ")", "val", "=", "_fitz", ".", "Page_addUnderlineAnnot", "(", "self", ",", "rect", ")", "if", "not", "val", ":", "return", "val", ".", "thisown", "=", "True", "...
Underline content in a rectangle or quadrilateral.
[ "Underline", "content", "in", "a", "rectangle", "or", "quadrilateral", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L2647-L2658
train
223,878
pymupdf/PyMuPDF
fitz/fitz.py
Page.addSquigglyAnnot
def addSquigglyAnnot(self, rect): """Wavy underline content in a rectangle or quadrilateral.""" 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
python
def addSquigglyAnnot(self, rect): """Wavy underline content in a rectangle or quadrilateral.""" 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
[ "def", "addSquigglyAnnot", "(", "self", ",", "rect", ")", ":", "CheckParent", "(", "self", ")", "val", "=", "_fitz", ".", "Page_addSquigglyAnnot", "(", "self", ",", "rect", ")", "if", "not", "val", ":", "return", "val", ".", "thisown", "=", "True", "va...
Wavy underline content in a rectangle or quadrilateral.
[ "Wavy", "underline", "content", "in", "a", "rectangle", "or", "quadrilateral", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L2661-L2672
train
223,879
pymupdf/PyMuPDF
fitz/fitz.py
Page.addHighlightAnnot
def addHighlightAnnot(self, rect): """Highlight content in a rectangle or quadrilateral.""" 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
python
def addHighlightAnnot(self, rect): """Highlight content in a rectangle or quadrilateral.""" 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
[ "def", "addHighlightAnnot", "(", "self", ",", "rect", ")", ":", "CheckParent", "(", "self", ")", "val", "=", "_fitz", ".", "Page_addHighlightAnnot", "(", "self", ",", "rect", ")", "if", "not", "val", ":", "return", "val", ".", "thisown", "=", "True", "...
Highlight content in a rectangle or quadrilateral.
[ "Highlight", "content", "in", "a", "rectangle", "or", "quadrilateral", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L2675-L2686
train
223,880
pymupdf/PyMuPDF
fitz/fitz.py
Page.addRectAnnot
def addRectAnnot(self, rect): """Add a 'Rectangle' annotation.""" 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
python
def addRectAnnot(self, rect): """Add a 'Rectangle' annotation.""" 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
[ "def", "addRectAnnot", "(", "self", ",", "rect", ")", ":", "CheckParent", "(", "self", ")", "val", "=", "_fitz", ".", "Page_addRectAnnot", "(", "self", ",", "rect", ")", "if", "not", "val", ":", "return", "val", ".", "thisown", "=", "True", "val", "....
Add a 'Rectangle' annotation.
[ "Add", "a", "Rectangle", "annotation", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L2689-L2700
train
223,881
pymupdf/PyMuPDF
fitz/fitz.py
Page.addCircleAnnot
def addCircleAnnot(self, rect): """Add a 'Circle' annotation.""" 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
python
def addCircleAnnot(self, rect): """Add a 'Circle' annotation.""" 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
[ "def", "addCircleAnnot", "(", "self", ",", "rect", ")", ":", "CheckParent", "(", "self", ")", "val", "=", "_fitz", ".", "Page_addCircleAnnot", "(", "self", ",", "rect", ")", "if", "not", "val", ":", "return", "val", ".", "thisown", "=", "True", "val", ...
Add a 'Circle' annotation.
[ "Add", "a", "Circle", "annotation", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L2703-L2714
train
223,882
pymupdf/PyMuPDF
fitz/fitz.py
Page.addPolylineAnnot
def addPolylineAnnot(self, points): """Add a 'Polyline' annotation for a sequence of 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
python
def addPolylineAnnot(self, points): """Add a 'Polyline' annotation for a sequence of 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
[ "def", "addPolylineAnnot", "(", "self", ",", "points", ")", ":", "CheckParent", "(", "self", ")", "val", "=", "_fitz", ".", "Page_addPolylineAnnot", "(", "self", ",", "points", ")", "if", "not", "val", ":", "return", "val", ".", "thisown", "=", "True", ...
Add a 'Polyline' annotation for a sequence of points.
[ "Add", "a", "Polyline", "annotation", "for", "a", "sequence", "of", "points", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L2717-L2728
train
223,883
pymupdf/PyMuPDF
fitz/fitz.py
Page.addPolygonAnnot
def addPolygonAnnot(self, points): """Add a 'Polygon' annotation for a sequence of 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
python
def addPolygonAnnot(self, points): """Add a 'Polygon' annotation for a sequence of 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
[ "def", "addPolygonAnnot", "(", "self", ",", "points", ")", ":", "CheckParent", "(", "self", ")", "val", "=", "_fitz", ".", "Page_addPolygonAnnot", "(", "self", ",", "points", ")", "if", "not", "val", ":", "return", "val", ".", "thisown", "=", "True", "...
Add a 'Polygon' annotation for a sequence of points.
[ "Add", "a", "Polygon", "annotation", "for", "a", "sequence", "of", "points", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L2731-L2742
train
223,884
pymupdf/PyMuPDF
fitz/fitz.py
Page.addFreetextAnnot
def addFreetextAnnot(self, rect, text, fontsize=12, fontname=None, color=None, rotate=0): """Add a 'FreeText' annotation in rectangle 'rect'.""" 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
python
def addFreetextAnnot(self, rect, text, fontsize=12, fontname=None, color=None, rotate=0): """Add a 'FreeText' annotation in rectangle 'rect'.""" 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
[ "def", "addFreetextAnnot", "(", "self", ",", "rect", ",", "text", ",", "fontsize", "=", "12", ",", "fontname", "=", "None", ",", "color", "=", "None", ",", "rotate", "=", "0", ")", ":", "CheckParent", "(", "self", ")", "val", "=", "_fitz", ".", "Pa...
Add a 'FreeText' annotation in rectangle 'rect'.
[ "Add", "a", "FreeText", "annotation", "in", "rectangle", "rect", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L2745-L2756
train
223,885
pymupdf/PyMuPDF
fitz/fitz.py
Page.addWidget
def addWidget(self, widget): """Add a form field. """ 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
python
def addWidget(self, widget): """Add a form field. """ 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
[ "def", "addWidget", "(", "self", ",", "widget", ")", ":", "CheckParent", "(", "self", ")", "doc", "=", "self", ".", "parent", "if", "not", "doc", ".", "isPDF", ":", "raise", "ValueError", "(", "\"not a PDF\"", ")", "widget", ".", "_validate", "(", ")",...
Add a form field.
[ "Add", "a", "form", "field", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L2762-L2805
train
223,886
pymupdf/PyMuPDF
fitz/fitz.py
Page.firstAnnot
def firstAnnot(self): """Points to first annotation on page""" 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
python
def firstAnnot(self): """Points to first annotation on page""" 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
[ "def", "firstAnnot", "(", "self", ")", ":", "CheckParent", "(", "self", ")", "val", "=", "_fitz", ".", "Page_firstAnnot", "(", "self", ")", "if", "val", ":", "val", ".", "thisown", "=", "True", "val", ".", "parent", "=", "weakref", ".", "proxy", "(",...
Points to first annotation on page
[ "Points", "to", "first", "annotation", "on", "page" ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L2848-L2858
train
223,887
pymupdf/PyMuPDF
fitz/fitz.py
Page.deleteLink
def deleteLink(self, linkdict): """Delete link if PDF""" 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
python
def deleteLink(self, linkdict): """Delete link if PDF""" 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
[ "def", "deleteLink", "(", "self", ",", "linkdict", ")", ":", "CheckParent", "(", "self", ")", "val", "=", "_fitz", ".", "Page_deleteLink", "(", "self", ",", "linkdict", ")", "if", "linkdict", "[", "\"xref\"", "]", "==", "0", ":", "return", "linkid", "=...
Delete link if PDF
[ "Delete", "link", "if", "PDF" ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L2861-L2875
train
223,888
pymupdf/PyMuPDF
fitz/fitz.py
Page.deleteAnnot
def deleteAnnot(self, fannot): """Delete annot if PDF and return next one""" 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
python
def deleteAnnot(self, fannot): """Delete annot if PDF and return next one""" 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
[ "def", "deleteAnnot", "(", "self", ",", "fannot", ")", ":", "CheckParent", "(", "self", ")", "val", "=", "_fitz", ".", "Page_deleteAnnot", "(", "self", ",", "fannot", ")", "if", "val", ":", "val", ".", "thisown", "=", "True", "val", ".", "parent", "=...
Delete annot if PDF and return next one
[ "Delete", "annot", "if", "PDF", "and", "return", "next", "one" ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L2878-L2890
train
223,889
pymupdf/PyMuPDF
fitz/fitz.py
Page._forget_annot
def _forget_annot(self, annot): """Remove an annot from reference dictionary.""" aid = id(annot) if aid in self._annot_refs: self._annot_refs[aid] = None
python
def _forget_annot(self, annot): """Remove an annot from reference dictionary.""" aid = id(annot) if aid in self._annot_refs: self._annot_refs[aid] = None
[ "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.
[ "Remove", "an", "annot", "from", "reference", "dictionary", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L3072-L3076
train
223,890
pymupdf/PyMuPDF
fitz/fitz.py
Annot.rect
def rect(self): """Rectangle containing the annot""" CheckParent(self) val = _fitz.Annot_rect(self) val = Rect(val) return val
python
def rect(self): """Rectangle containing the annot""" CheckParent(self) val = _fitz.Annot_rect(self) val = Rect(val) return val
[ "def", "rect", "(", "self", ")", ":", "CheckParent", "(", "self", ")", "val", "=", "_fitz", ".", "Annot_rect", "(", "self", ")", "val", "=", "Rect", "(", "val", ")", "return", "val" ]
Rectangle containing the annot
[ "Rectangle", "containing", "the", "annot" ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L3586-L3593
train
223,891
pymupdf/PyMuPDF
fitz/fitz.py
Annot.fileUpd
def fileUpd(self, buffer=None, filename=None, ufilename=None, desc=None): """Update annotation attached file.""" CheckParent(self) return _fitz.Annot_fileUpd(self, buffer, filename, ufilename, desc)
python
def fileUpd(self, buffer=None, filename=None, ufilename=None, desc=None): """Update annotation attached file.""" CheckParent(self) return _fitz.Annot_fileUpd(self, buffer, filename, ufilename, desc)
[ "def", "fileUpd", "(", "self", ",", "buffer", "=", "None", ",", "filename", "=", "None", ",", "ufilename", "=", "None", ",", "desc", "=", "None", ")", ":", "CheckParent", "(", "self", ")", "return", "_fitz", ".", "Annot_fileUpd", "(", "self", ",", "b...
Update annotation attached file.
[ "Update", "annotation", "attached", "file", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L3888-L3894
train
223,892
pymupdf/PyMuPDF
fitz/fitz.py
Link.dest
def dest(self): """Create link destination details.""" 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)
python
def dest(self): """Create link destination details.""" 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)
[ "def", "dest", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "\"parent\"", ")", "and", "self", ".", "parent", "is", "None", ":", "raise", "ValueError", "(", "\"orphaned object: parent is None\"", ")", "if", "self", ".", "parent", ".", "parent",...
Create link destination details.
[ "Create", "link", "destination", "details", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L4130-L4143
train
223,893
pymupdf/PyMuPDF
fitz/fitz.py
Tools.measure_string
def measure_string(self, text, fontname, fontsize, encoding=0): """Measure length of a string for a Base14 font.""" return _fitz.Tools_measure_string(self, text, fontname, fontsize, encoding)
python
def measure_string(self, text, fontname, fontsize, encoding=0): """Measure length of a string for a Base14 font.""" return _fitz.Tools_measure_string(self, text, fontname, fontsize, encoding)
[ "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.
[ "Measure", "length", "of", "a", "string", "for", "a", "Base14", "font", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L4492-L4494
train
223,894
pymupdf/PyMuPDF
fitz/fitz.py
Tools._le_annot_parms
def _le_annot_parms(self, annot, p1, p2): """Get common parameters for making line end symbols. """ 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
python
def _le_annot_parms(self, annot, p1, p2): """Get common parameters for making line end symbols. """ 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
[ "def", "_le_annot_parms", "(", "self", ",", "annot", ",", "p1", ",", "p2", ")", ":", "w", "=", "annot", ".", "border", "[", "\"width\"", "]", "# line width", "sc", "=", "annot", ".", "colors", "[", "\"stroke\"", "]", "# stroke color", "if", "not", "sc"...
Get common parameters for making line end symbols.
[ "Get", "common", "parameters", "for", "making", "line", "end", "symbols", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L4504-L4525
train
223,895
pymupdf/PyMuPDF
demo/caustic.py
pbis
def pbis(a): """End point of a reflected sun ray, given an angle a.""" return(math.cos(3*a - math.pi), (math.sin(3*a - math.pi)))
python
def pbis(a): """End point of a reflected sun ray, given an angle a.""" return(math.cos(3*a - math.pi), (math.sin(3*a - math.pi)))
[ "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.
[ "End", "point", "of", "a", "reflected", "sun", "ray", "given", "an", "angle", "a", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/demo/caustic.py#L33-L35
train
223,896
pymupdf/PyMuPDF
demo/new-annots.py
print_descr
def print_descr(rect, annot): """Print a short description to the right of an annot rect.""" annot.parent.insertText(rect.br + (10, 0), "'%s' annotation" % annot.type[1], color = red)
python
def print_descr(rect, annot): """Print a short description to the right of an annot rect.""" annot.parent.insertText(rect.br + (10, 0), "'%s' annotation" % annot.type[1], color = red)
[ "def", "print_descr", "(", "rect", ",", "annot", ")", ":", "annot", ".", "parent", ".", "insertText", "(", "rect", ".", "br", "+", "(", "10", ",", "0", ")", ",", "\"'%s' annotation\"", "%", "annot", ".", "type", "[", "1", "]", ",", "color", "=", ...
Print a short description to the right of an annot rect.
[ "Print", "a", "short", "description", "to", "the", "right", "of", "an", "annot", "rect", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/demo/new-annots.py#L41-L44
train
223,897
pymupdf/PyMuPDF
demo/extract-img2.py
recoverpix
def recoverpix(doc, item): """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. """ 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
python
def recoverpix(doc, item): """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. """ 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
[ "def", "recoverpix", "(", "doc", ",", "item", ")", ":", "x", "=", "item", "[", "0", "]", "# xref of PDF image", "s", "=", "item", "[", "1", "]", "# xref of its /SMask", "try", ":", "pix1", "=", "fitz", ".", "Pixmap", "(", "doc", ",", "x", ")", "# m...
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.
[ "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", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/demo/extract-img2.py#L39-L71
train
223,898
pymupdf/PyMuPDF
examples/PDFLinkMaint.py
PDFdisplay.on_update_page_links
def on_update_page_links(self, evt): """ Perform PDF update of changed links.""" 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
python
def on_update_page_links(self, evt): """ Perform PDF update of changed links.""" 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
[ "def", "on_update_page_links", "(", "self", ",", "evt", ")", ":", "if", "not", "self", ".", "update_links", ":", "# skip if unsupported links", "evt", ".", "Skip", "(", ")", "return", "pg", "=", "self", ".", "doc", "[", "getint", "(", "self", ".", "TextT...
Perform PDF update of changed links.
[ "Perform", "PDF", "update", "of", "changed", "links", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/examples/PDFLinkMaint.py#L464-L486
train
223,899