_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q250100 | get_category_files_from_api | train | def get_category_files_from_api(category_name):
"""Yield the file names of a category by querying the MediaWiki API."""
import mwclient
site = mwclient.Site('commons.wikimedia.org')
| python | {
"resource": ""
} |
q250101 | download_from_category | train | def download_from_category(category_name, output_path, width):
"""Download files of a given category."""
file_names | python | {
"resource": ""
} |
q250102 | get_files_from_textfile | train | def get_files_from_textfile(textfile_handler):
"""Yield the file names and widths by parsing a text file handler."""
for line in textfile_handler:
line = line.rstrip()
try:
(image_name, width) = line.rsplit(',', 1)
| python | {
"resource": ""
} |
q250103 | download_from_files | train | def download_from_files(files, output_path, width):
"""Download files from a given file list.""" | python | {
"resource": ""
} |
q250104 | read_local_manifest | train | def read_local_manifest(output_path):
"""Return the contents of the local manifest, as a dictionary."""
local_manifest_path = get_local_manifest_path(output_path)
try:
with open(local_manifest_path, 'r') as | python | {
"resource": ""
} |
q250105 | write_file_to_manifest | train | def write_file_to_manifest(file_name, width, manifest_fh):
"""Write the given file in | python | {
"resource": ""
} |
q250106 | download_files_if_not_in_manifest | train | def download_files_if_not_in_manifest(files_iterator, output_path):
"""Download the given files to the given path, unless in manifest."""
local_manifest = read_local_manifest(output_path)
with open(get_local_manifest_path(output_path), 'a') as manifest_fh:
for (file_name, width) in files_iterator:
... | python | {
"resource": ""
} |
q250107 | main | train | def main():
"""Main method, entry point of the script."""
from argparse import ArgumentParser
description = "Download a bunch of thumbnails from Wikimedia Commons"
parser = ArgumentParser(description=description)
source_group = parser.add_mutually_exclusive_group()
source_group.add_argument("-l"... | python | {
"resource": ""
} |
q250108 | JsonSchema.ordered_load | train | def ordered_load(self, stream, Loader=yaml.Loader, object_pairs_hook=OrderedDict):
"""Allows you to use `pyyaml` to load as OrderedDict.
Taken from https://stackoverflow.com/a/21912744/1927102
"""
class OrderedLoader(Loader):
pass
def construct_mapping(loader, node)... | python | {
"resource": ""
} |
q250109 | SSHClientInteraction.send | train | def send(self, send_string, newline=None):
"""Saves and sends the send string provided."""
self.current_send_string = send_string
newline = newline if newline | python | {
"resource": ""
} |
q250110 | SSHClientInteraction.tail | train | def tail(
self, line_prefix=None, callback=None, output_callback=None, stop_callback=lambda x: False,
timeout=None
):
"""
This function takes control of an SSH channel and displays line
by line of output as \n is recieved. This function is specifically
made for tail-... | python | {
"resource": ""
} |
q250111 | SSHClientInteraction.take_control | train | def take_control(self):
"""
This function is a better documented and touched up version of the
posix_shell function found in the interactive.py demo script that
ships with Paramiko.
"""
if has_termios:
# Get attributes of the shell you were in before going to... | python | {
"resource": ""
} |
q250112 | Preston._get_access_from_refresh | train | def _get_access_from_refresh(self) -> Tuple[str, float]:
"""Uses the stored refresh token to get a new access token.
This method assumes that the refresh token exists.
Args:
None
Returns:
new access token and expiration time (from | python | {
"resource": ""
} |
q250113 | Preston._get_authorization_headers | train | def _get_authorization_headers(self) -> dict:
"""Constructs and returns the Authorization header for the client app.
Args:
None
Returns:
header dict for communicating with the authorization endpoints
"""
| python | {
"resource": ""
} |
q250114 | Preston._try_refresh_access_token | train | def _try_refresh_access_token(self) -> None:
"""Attempts to get a new access token using the refresh token, if needed.
If the access token is expired and this instance has a stored refresh token,
then the refresh token is in the API call to get a new access token. If
successful, this in... | python | {
"resource": ""
} |
q250115 | Preston.authenticate | train | def authenticate(self, code: str) -> 'Preston':
"""Authenticates using the code from the EVE SSO.
A new Preston object is returned; this object is not modified.
The intended usage is:
auth = preston.authenticate('some_code_here')
Args:
code: SSO code
... | python | {
"resource": ""
} |
q250116 | Preston._get_spec | train | def _get_spec(self) -> dict:
"""Fetches the OpenAPI spec from the server.
If the spec has already been fetched, the cached version is returned instead.
ArgS:
None
Returns:
OpenAPI spec data
"""
if self.spec:
| python | {
"resource": ""
} |
q250117 | Preston._get_path_for_op_id | train | def _get_path_for_op_id(self, id: str) -> Optional[str]:
"""Searches the spec for a path matching the operation id.
Args:
id: operation id
Returns:
path to the endpoint, or None if not found
"""
for path_key, path_value in self._get_spec()['paths'].items... | python | {
"resource": ""
} |
q250118 | Preston._insert_vars | train | def _insert_vars(self, path: str, data: dict) -> str:
"""Inserts variables into the ESI URL path.
Args:
path: raw ESI URL path
data: data to insert into the URL
Returns:
path with variables filled
"""
data = data.copy()
while True:
... | python | {
"resource": ""
} |
q250119 | Preston.whoami | train | def whoami(self) -> dict:
"""Returns the basic information about the authenticated character.
Obviously doesn't do anything if this Preston instance is not
authenticated, so it returns an empty dict.
| python | {
"resource": ""
} |
q250120 | Preston.get_path | train | def get_path(self, path: str, data: dict) -> Tuple[dict, dict]:
"""Queries the ESI by an endpoint URL.
This method is not marked "private" as it _can_ be used
by consuming code, but it's probably easier to call the
`get_op` method instead.
Args:
path: raw ESI URL pa... | python | {
"resource": ""
} |
q250121 | Preston.get_op | train | def get_op(self, id: str, **kwargs: str) -> dict:
"""Queries the ESI by looking up an operation id.
Endpoints are cached, so calls to this method
for the same op and args will return the data
from the cache instead of making the API call.
Args:
| python | {
"resource": ""
} |
q250122 | Preston.post_path | train | def post_path(self, path: str, path_data: Union[dict, None], post_data: Any) -> dict:
"""Modifies the ESI by an endpoint URL.
This method is not marked "private" as it _can_ be used
by consuming code, but it's probably easier to call the
`get_op` method instead.
Args:
... | python | {
"resource": ""
} |
q250123 | Preston.post_op | train | def post_op(self, id: str, path_data: Union[dict, None], post_data: Any) -> dict:
"""Modifies the ESI by looking up an operation id.
Args:
path: raw ESI URL path
path_data: data to format the path with (can be None)
| python | {
"resource": ""
} |
q250124 | Cache._get_expiration | train | def _get_expiration(self, headers: dict) -> int:
"""Gets the expiration time of the data from the response headers.
Args:
headers: dictionary of headers from ESI
Returns:
value of seconds from now the data expires
"""
expiration_str = headers.get('expire... | python | {
"resource": ""
} |
q250125 | Cache.set | train | def set(self, response: 'requests.Response') -> None:
"""Adds a response to the cache.
Args:
response: response from ESI
Returns:
None
"""
| python | {
"resource": ""
} |
q250126 | Cache._check_expiration | train | def _check_expiration(self, url: str, data: 'SavedEndpoint') -> 'SavedEndpoint':
"""Checks the expiration time for data for a url.
If the data has expired, it is deleted from the cache.
Args:
url: url to check
data: page of data for that url
Returns:
... | python | {
"resource": ""
} |
q250127 | Cache.check | train | def check(self, url: str) -> Optional[dict]:
"""Check if data for a url has expired.
Data is not fetched again if it has expired.
Args:
url: url to check expiration on
Returns:
value of the data, possibly | python | {
"resource": ""
} |
q250128 | eigvalsh | train | def eigvalsh(a, eigvec=False):
""" Eigenvalues of Hermitian matrix ``a``.
Args:
a: Two-dimensional, square Hermitian matrix/array of numbers
and/or :class:`gvar.GVar`\s. Array elements must be
real-valued if `gvar.GVar`\s are involved (i.e., symmetric
matrix).
... | python | {
"resource": ""
} |
q250129 | eigh | train | def eigh(a, eigvec=True, rcond=None):
""" Eigenvalues and eigenvectors of symmetric matrix ``a``.
Args:
a: Two-dimensional, square Hermitian matrix/array of numbers
and/or :class:`gvar.GVar`\s. Array elements must be
real-valued if `gvar.GVar`\s are involved (i.e., symmetric
... | python | {
"resource": ""
} |
q250130 | svd | train | def svd(a, compute_uv=True, rcond=None):
""" svd decomposition of matrix ``a`` containing |GVar|\s.
Args:
a: Two-dimensional matrix/array of numbers
and/or :class:`gvar.GVar`\s.
compute_uv (bool): It ``True`` (default), returns
tuple ``(u,s,vT)`` where matrix ``a = u @ n... | python | {
"resource": ""
} |
q250131 | inv | train | def inv(a):
""" Inverse of matrix ``a``.
Args:
a: Two-dimensional, square matrix/array of numbers
and/or :class:`gvar.GVar`\s.
Returns:
The inverse of matrix ``a``.
Raises:
ValueError: If matrix is not square and two-dimensional.
"""
amean = gvar.mean(a)
... | python | {
"resource": ""
} |
q250132 | ranseed | train | def ranseed(seed=None):
""" Seed random number generators with tuple ``seed``.
Argument ``seed`` is an integer or
a :class:`tuple` of integers that is used to seed
the random number generators used by :mod:`numpy` and
:mod:`random` (and therefore by :mod:`gvar`). Reusing
the same ``seed`` resul... | python | {
"resource": ""
} |
q250133 | erf | train | def erf(x):
""" Error function.
Works for floats, |GVar|\s, and :mod:`numpy` arrays.
"""
try:
return math.erf(x)
except TypeError:
pass
if isinstance(x, GVar):
f = math.erf(x.mean)
dfdx = 2. * math.exp(- x.mean ** 2) / math.sqrt(math.pi)
return gvar_funct... | python | {
"resource": ""
} |
q250134 | make_fake_data | train | def make_fake_data(g, fac=1.0):
""" Make fake data based on ``g``.
This function replaces the |GVar|\s in ``g`` by new |GVar|\s with similar
means and a similar covariance matrix, but multiplied by ``fac**2`` (so
standard deviations are ``fac`` times smaller). The changes are random.
The function ... | python | {
"resource": ""
} |
q250135 | PDF.p2x | train | def p2x(self, p):
""" Map parameters ``p`` to vector in x-space.
x-space is a vector space of dimension ``p.size``. Its axes are
in the directions specified by the eigenvectors of ``p``'s covariance
matrix, and distance along an axis is in units of the standard
deviation in that... | python | {
"resource": ""
} |
q250136 | PDFHistogram.count | train | def count(self, data):
""" Compute histogram of data.
Counts the number of elements from array ``data`` in each bin of the
histogram. Results are returned in an array, call it ``h``, of
length ``nbin+2`` where ``h[0]`` is the number of data elements
that fall below the range of ... | python | {
"resource": ""
} |
q250137 | PDFHistogram.gaussian_pdf | train | def gaussian_pdf(x, g):
""" Gaussian probability density function at ``x`` for |GVar| ``g``. """
return (
| python | {
"resource": ""
} |
q250138 | verify_checksum | train | def verify_checksum(*lines):
"""Verify the checksum of one or more TLE lines.
Raises `ValueError` if any of the lines fails its checksum, and
includes the failing line in the error message.
"""
for line in lines:
checksum = line[68:69]
| python | {
"resource": ""
} |
q250139 | compute_checksum | train | def compute_checksum(line):
"""Compute the TLE checksum for the given line."""
return sum((int(c) if | python | {
"resource": ""
} |
q250140 | Satellite.propagate | train | def propagate(self, year, month=1, day=1, hour=0, minute=0, second=0.0):
"""Return a position and velocity vector for a given date and time."""
j = jday(year, month, | python | {
"resource": ""
} |
q250141 | MiTempBtPoller.name | train | def name(self):
"""Return the name of the sensor."""
with self._bt_interface.connect(self._mac) as connection:
name = connection.read_handle(_HANDLE_READ_NAME) # pylint: disable=no-member
if not name:
raise BluetoothBackendException("Could not read NAME using handle %s"... | python | {
"resource": ""
} |
q250142 | MiTempBtPoller.handleNotification | train | def handleNotification(self, handle, raw_data): # pylint: disable=unused-argument,invalid-name
""" gets called by the bluepy backend when using wait_for_notification
"""
if raw_data is None:
return
data = raw_data.decode("utf-8").strip(' \n\t')
self._cache = data
... | python | {
"resource": ""
} |
q250143 | ThriftClient.add_journal | train | def add_journal(self, data):
"""
This method include new journals to the ArticleMeta.
data: legacy SciELO Documents JSON Type 3.
"""
journal = self.dispatcher(
| python | {
"resource": ""
} |
q250144 | watermark_process | train | def watermark_process():
"""Apply a watermark to a PDF file."""
# Redirect to watermark page that contains form
if not request.method == 'POST':
abort(403)
# Check if the post request has the file part
if 'pdf' not in request.files:
abort(403)
# Retrieve PDF file and parameters... | python | {
"resource": ""
} |
q250145 | slicer | train | def slicer(document, first_page=None, last_page=None, suffix='sliced', tempdir=None):
"""Slice a PDF document to remove pages."""
# Set output file name
if tempdir:
with NamedTemporaryFile(suffix='.pdf', dir=tempdir, delete=False) as temp:
output = temp.name
elif suffix:
outp... | python | {
"resource": ""
} |
q250146 | Info._reader | train | def _reader(path, password, prompt):
"""Read PDF and decrypt if encrypted."""
pdf = PdfFileReader(path) if not isinstance(path, PdfFileReader) else path
# Check that PDF is encrypted
if pdf.isEncrypted:
# Check that password is none
if not password:
... | python | {
"resource": ""
} |
q250147 | Info._resolved_objects | train | def _resolved_objects(pdf, xobject):
"""Retrieve rotatation info."""
| python | {
"resource": ""
} |
q250148 | Info.resources | train | def resources(self):
"""Retrieve contents of each page of PDF"""
| python | {
"resource": ""
} |
q250149 | Info.security | train | def security(self):
"""Print security object information for a pdf | python | {
"resource": ""
} |
q250150 | BaseDocumentCloudClient._make_request | train | def _make_request(self, url, params=None, opener=None):
"""
Configure a HTTP request, fire it off and return the response.
"""
# Create the request object
args = [i for i in [url, params] if i]
request = urllib.request.Request(*args)
# If the client has credential... | python | {
"resource": ""
} |
q250151 | BaseDocumentCloudClient.put | train | def put(self, method, params):
"""
Post changes back to DocumentCloud
"""
# Prepare the params, first by adding a custom command to
# simulate a PUT request even though we are actually POSTing.
# This is something DocumentCloud expects.
params['_method'] = 'put'
... | python | {
"resource": ""
} |
q250152 | BaseDocumentCloudClient.fetch | train | def fetch(self, method, params=None):
"""
Fetch an url.
"""
# Encode params if they exist
if params:
params = urllib.parse.urlencode(params, doseq=True).encode("utf-8")
content = self._make_request(
self.BASE_URI + method,
| python | {
"resource": ""
} |
q250153 | DocumentClient._get_search_page | train | def _get_search_page(
self,
query,
page,
per_page=1000,
mentions=3,
data=False,
):
"""
Retrieve one page of search results from the DocumentCloud API.
"""
if mentions > 10:
raise ValueError("You cannot search for more than 1... | python | {
"resource": ""
} |
q250154 | DocumentClient.search | train | def search(self, query, page=None, per_page=1000, mentions=3, data=False):
"""
Retrieve all objects that make a search query.
Will loop through all pages that match unless you provide
the number of pages you'd like to restrict the search to.
Example usage:
>> docum... | python | {
"resource": ""
} |
q250155 | DocumentClient.get | train | def get(self, id):
"""
Retrieve a particular document using it's unique identifier.
Example usage:
>> documentcloud.documents.get('71072-oir-final-report')
"""
data | python | {
"resource": ""
} |
q250156 | DocumentClient.upload | train | def upload(
self, pdf, title=None, source=None, description=None,
related_article=None, published_url=None, access='private',
project=None, data=None, secure=False, force_ocr=False
):
"""
Upload a PDF or other image file to DocumentCloud.
You can submit either a pdf ... | python | {
"resource": ""
} |
q250157 | DocumentClient.upload_directory | train | def upload_directory(
self, path, source=None, description=None,
related_article=None, published_url=None, access='private',
project=None, data=None, secure=False, force_ocr=False
):
"""
Uploads all the PDFs in the provided directory.
Example usage:
>> d... | python | {
"resource": ""
} |
q250158 | ProjectClient.all | train | def all(self):
"""
Retrieve all your projects. Requires authentication.
Example usage:
>> documentcloud.projects.all()
"""
project_list = self.fetch('projects.json').get("projects")
obj_list = []
for proj in project_list:
| python | {
"resource": ""
} |
q250159 | ProjectClient.get | train | def get(self, id=None, title=None):
"""
Retrieve a particular project using its unique identifier or
it's title.
But not both.
Example usage:
>> documentcloud.projects.get('arizona-shootings')
"""
# Make sure the kwargs are kosher
if id and ... | python | {
"resource": ""
} |
q250160 | ProjectClient.create | train | def create(self, title, description=None, document_ids=None):
"""
Creates a new project.
Returns its unique identifer in documentcloud
Example usage:
>> documentcloud.projects.create("The Ruben Salazar Files")
"""
params = {
'title': title,
... | python | {
"resource": ""
} |
q250161 | ProjectClient.get_or_create_by_title | train | def get_or_create_by_title(self, title):
"""
Fetch a title, if it exists. Create it if it doesn't.
Returns a tuple with the object first, and then a boolean that
indicates whether or not the object was created fresh. True means it's
brand new.
"""
| python | {
"resource": ""
} |
q250162 | Annotation.get_location | train | def get_location(self):
"""
Return the location as a good
"""
image_string = self.__dict__['location']['image']
| python | {
"resource": ""
} |
q250163 | Document.put | train | def put(self):
"""
Save changes made to the object to DocumentCloud.
According to DocumentCloud's docs, edits are allowed for the following
fields:
* title
* source
* description
* related_article
* access
* publis... | python | {
"resource": ""
} |
q250164 | Document._lazy_load | train | def _lazy_load(self):
"""
Fetch metadata if it was overlooked during the object's creation.
This can happen when you retrieve documents via search, because
the JSON response does not include complete meta data for all
results.
"""
obj = self._connection.documents... | python | {
"resource": ""
} |
q250165 | Document.set_data | train | def set_data(self, data):
"""
Update the data attribute, making sure it's a dictionary.
"""
# Make sure a dict got passed it
if not isinstance(data, type({})):
| python | {
"resource": ""
} |
q250166 | Document.get_data | train | def get_data(self):
"""
Fetch the data field if it does not exist.
"""
try:
return DocumentDataDict(self.__dict__['data'])
except | python | {
"resource": ""
} |
q250167 | Document.get_annotations | train | def get_annotations(self):
"""
Fetch the annotations field if it does not exist.
"""
try:
obj_list = self.__dict__['annotations']
return [Annotation(i) for i in obj_list]
except KeyError:
| python | {
"resource": ""
} |
q250168 | Document.get_sections | train | def get_sections(self):
"""
Fetch the sections field if it does not exist.
"""
try:
obj_list = self.__dict__['sections']
return [Section(i) for i in obj_list]
except KeyError:
| python | {
"resource": ""
} |
q250169 | Document.get_entities | train | def get_entities(self):
"""
Fetch the entities extracted from this document by OpenCalais.
"""
try:
return self.__dict__['entities']
except KeyError:
entities = self._connection.fetch(
"documents/%s/entities.json" % self.id
).ge... | python | {
"resource": ""
} |
q250170 | Document.get_page_text_url | train | def get_page_text_url(self, page):
"""
Returns the URL for the full text of a particular page in the document.
"""
| python | {
"resource": ""
} |
q250171 | Document.get_page_text | train | def get_page_text(self, page):
"""
Downloads and returns the full text of a particular | python | {
"resource": ""
} |
q250172 | Document.get_small_image_url | train | def get_small_image_url(self, page=1):
"""
Returns the URL for the small sized image of a single page.
The page kwarg specifies which page to return. One is the default.
"""
| python | {
"resource": ""
} |
q250173 | Document.get_thumbnail_image_url | train | def get_thumbnail_image_url(self, page=1):
"""
Returns the URL for the thumbnail sized image of a single page.
The page kwarg specifies which page to return. One is the default.
"""
| python | {
"resource": ""
} |
q250174 | Document.get_normal_image_url | train | def get_normal_image_url(self, page=1):
"""
Returns the URL for the "normal" sized image of a single page.
The page kwarg specifies which page to return. One is the default.
"""
| python | {
"resource": ""
} |
q250175 | Document.get_large_image_url | train | def get_large_image_url(self, page=1):
"""
Returns the URL for the large sized image of a single page.
The page kwarg specifies which page to return. One is the default.
| python | {
"resource": ""
} |
q250176 | Document.get_small_image | train | def get_small_image(self, page=1):
"""
Downloads and returns the small sized image of a single page.
The page kwarg specifies which page to return. One | python | {
"resource": ""
} |
q250177 | Document.get_thumbnail_image | train | def get_thumbnail_image(self, page=1):
"""
Downloads and returns the thumbnail sized image of a single page.
The page kwarg specifies which page to return. One | python | {
"resource": ""
} |
q250178 | Document.get_normal_image | train | def get_normal_image(self, page=1):
"""
Downloads and returns the normal sized image of a single page.
The page kwarg specifies which page to return. One | python | {
"resource": ""
} |
q250179 | Document.get_large_image | train | def get_large_image(self, page=1):
"""
Downloads and returns the large sized image of a single page.
The page kwarg specifies which page to return. One | python | {
"resource": ""
} |
q250180 | Project.put | train | def put(self):
"""
Save changes made to the object to documentcloud.org
According to DocumentCloud's docs, edits are allowed for the following
fields:
* title
* description
* document_ids
Returns nothing.
"""
params = dict(
... | python | {
"resource": ""
} |
q250181 | Project.get_document_list | train | def get_document_list(self):
"""
Retrieves all documents included in this project.
"""
try:
return self.__dict__['document_list']
except KeyError:
obj_list = DocumentSet([
| python | {
"resource": ""
} |
q250182 | Project.get_document | train | def get_document(self, id):
"""
Retrieves a particular document from this project.
"""
obj_list = self.document_list
matches = [i | python | {
"resource": ""
} |
q250183 | Watermark.draw | train | def draw(self, text1=None, text2=None, copyright=True, image=IMAGE_DEFAULT, rotate=30, opacity=0.08, compress=0,
flatten=False, add=False):
"""
Draw watermark PDF file.
Create watermark using either a reportlabs canvas or a PIL image.
:param text1: str
Text lin... | python | {
"resource": ""
} |
q250184 | Watermark.add | train | def add(self, document=None, watermark=None, underneath=False, output=None, suffix='watermarked', method='pdfrw'):
"""
Add a watermark file to an existing PDF document.
Rotate and upscale watermark file as needed to fit existing PDF document. Watermark can be overlayed or
placed undern... | python | {
"resource": ""
} |
q250185 | Watermark.encrypt | train | def encrypt(self, user_pw='', owner_pw=None, encrypt_128=True, allow_printing=True, allow_commenting=False,
document=None):
"""
Encrypt a PDF document to add passwords and restrict permissions.
Add a user password that must be entered to view document and a owner password that m... | python | {
"resource": ""
} |
q250186 | credentials_required | train | def credentials_required(method_func):
"""
Decorator for methods that checks that the client has credentials.
Throws a CredentialsMissingError when they are absent.
"""
def _checkcredentials(self, *args, **kwargs):
if self.username and self.password:
return method_func(self, *ar... | python | {
"resource": ""
} |
q250187 | retry | train | def retry(ExceptionToCheck, tries=3, delay=2, backoff=2):
"""
Retry decorator published by Saltry Crane.
http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/
"""
def deco_retry(f):
def f_retry(*args, **kwargs):
mtries, mdelay = tries, delay
try_o... | python | {
"resource": ""
} |
q250188 | text_width | train | def text_width(string, font_name, font_size):
"""Determine with width in pixels of string."""
| python | {
"resource": ""
} |
q250189 | center_str | train | def center_str(txt, font_name, font_size, offset=0):
"""Center a string on the x axis of a reportslab canvas"""
| python | {
"resource": ""
} |
q250190 | split_str | train | def split_str(string):
"""Split string in half to return two strings"""
split = string.split(' ')
| python | {
"resource": ""
} |
q250191 | WatermarkDraw._draw_image | train | def _draw_image(self, ci):
"""
Draw image object to reportlabs canvas.
:param ci: CanvasImage object
"""
img = img_adjust(ci.image, | python | {
"resource": ""
} |
q250192 | WatermarkDraw._draw_string | train | def _draw_string(self, cs):
"""
Draw string object to reportlabs canvas.
Canvas Parameter changes (applied if set values differ from string object values)
1. Font name
2. Font size
3. Font fill color & opacity
4. X and Y position
:param cs: CanvasString ... | python | {
"resource": ""
} |
q250193 | Merge._get_pdf_list | train | def _get_pdf_list(self, input_pdfs):
"""
Generate list of PDF documents.
:param input_pdfs: List of PDFs or a directory path
Directory - Scans directory contents
List - Filters list to assert all list items are paths to PDF documents
:return: List of PDF paths
... | python | {
"resource": ""
} |
q250194 | Merge.merge | train | def merge(self, pdf_files, output):
"""Merge list of PDF files to a single PDF file."""
if self.method is 'pypdf3':
| python | {
"resource": ""
} |
q250195 | set_destination | train | def set_destination(source, suffix, filename=False, ext=None):
"""Create new pdf filename for temp files"""
source_dirname = os.path.dirname(source)
# Do not create nested temp folders (/temp/temp)
if not source_dirname.endswith('temp'):
directory = os.path.join(source_dirname, 'temp') # direc... | python | {
"resource": ""
} |
q250196 | getsize | train | def getsize(o_file):
"""
get the size, either by seeeking to the end.
"""
startpos = o_file.tell()
o_file.seek(0)
| python | {
"resource": ""
} |
q250197 | WatermarkGUI.window | train | def window(self):
"""GUI window for Watermark parameters input."""
platform = system()
# Tabbed layout for Windows
if platform is 'Windows':
layout_tab_1 = []
layout_tab_1.extend(header('PDF Watermark Utility'))
layout_tab_1.extend(self.input_source())... | python | {
"resource": ""
} |
q250198 | pdf2img | train | def pdf2img(file_name, output=None, tempdir=None, ext='png', progress_bar=None):
"""Wrapper function for PDF2IMG class"""
return PDF2IMG(file_name=file_name, | python | {
"resource": ""
} |
q250199 | PDF2IMG._get_page_data | train | def _get_page_data(self, pno, zoom=0):
"""
Return a PNG image for a document page number. If zoom is other than 0, one of
the 4 page quadrants are zoomed-in instead and the corresponding clip returned.
"""
dlist = self.dlist_tab[pno] # get display list
if not dlist: # c... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.