repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
Accelize/pycosio | pycosio/_core/io_base_buffered.py | ObjectBufferedIOBase.seek | def seek(self, offset, whence=SEEK_SET):
"""
Change the stream position to the given byte offset.
Args:
offset: Offset is interpreted relative to the position indicated by
whence.
whence: The default value for whence is SEEK_SET.
Values for whence are:
SEEK_SET or 0 β start of the stream (the default);
offset should be zero or positive
SEEK_CUR or 1 β current stream position;
offset may be negative
SEEK_END or 2 β end of the stream;
offset is usually negative
Returns:
int: The new absolute position.
"""
if not self._seekable:
raise UnsupportedOperation('seek')
# Only read mode is seekable
with self._seek_lock:
# Set seek using raw method and
# sync buffered seek with raw seek
self.raw.seek(offset, whence)
self._seek = seek = self.raw._seek
# Preload starting from current seek
self._preload_range()
return seek | python | def seek(self, offset, whence=SEEK_SET):
"""
Change the stream position to the given byte offset.
Args:
offset: Offset is interpreted relative to the position indicated by
whence.
whence: The default value for whence is SEEK_SET.
Values for whence are:
SEEK_SET or 0 β start of the stream (the default);
offset should be zero or positive
SEEK_CUR or 1 β current stream position;
offset may be negative
SEEK_END or 2 β end of the stream;
offset is usually negative
Returns:
int: The new absolute position.
"""
if not self._seekable:
raise UnsupportedOperation('seek')
# Only read mode is seekable
with self._seek_lock:
# Set seek using raw method and
# sync buffered seek with raw seek
self.raw.seek(offset, whence)
self._seek = seek = self.raw._seek
# Preload starting from current seek
self._preload_range()
return seek | [
"def",
"seek",
"(",
"self",
",",
"offset",
",",
"whence",
"=",
"SEEK_SET",
")",
":",
"if",
"not",
"self",
".",
"_seekable",
":",
"raise",
"UnsupportedOperation",
"(",
"'seek'",
")",
"# Only read mode is seekable",
"with",
"self",
".",
"_seek_lock",
":",
"# S... | Change the stream position to the given byte offset.
Args:
offset: Offset is interpreted relative to the position indicated by
whence.
whence: The default value for whence is SEEK_SET.
Values for whence are:
SEEK_SET or 0 β start of the stream (the default);
offset should be zero or positive
SEEK_CUR or 1 β current stream position;
offset may be negative
SEEK_END or 2 β end of the stream;
offset is usually negative
Returns:
int: The new absolute position. | [
"Change",
"the",
"stream",
"position",
"to",
"the",
"given",
"byte",
"offset",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_base_buffered.py#L439-L471 |
Accelize/pycosio | pycosio/_core/io_base_buffered.py | ObjectBufferedIOBase.write | def write(self, b):
"""
Write the given bytes-like object, b, to the underlying raw stream,
and return the number of bytes written.
Args:
b (bytes-like object): Bytes to write.
Returns:
int: The number of bytes written.
"""
if not self._writable:
raise UnsupportedOperation('write')
size = len(b)
b_view = memoryview(b)
size_left = size
buffer_size = self._buffer_size
max_buffers = self._max_buffers
with self._seek_lock:
end = self._buffer_seek
buffer_view = memoryview(self._write_buffer)
while size_left > 0:
# Get range to copy
start = end
end = start + size_left
if end > buffer_size:
# End of buffer, need flush after copy
end = buffer_size
flush = True
else:
flush = False
buffer_range = end - start
# Update not remaining data size
b_start = size - size_left
size_left -= buffer_range
# Copy data
buffer_view[start:end] = b_view[b_start: b_start + buffer_range]
# Flush buffer if needed
if flush:
# Update buffer seek
# Needed to write the good amount of data
self._buffer_seek = end
# Update global seek, this is the number
# of buffer flushed
self._seek += 1
# Block flush based on maximum number of
# buffers in flush progress
if max_buffers:
futures = self._write_futures
flush_wait = self._FLUSH_WAIT
while sum(1 for future in futures
if not future.done()) >= max_buffers:
sleep(flush_wait)
# Flush
with handle_os_exceptions():
self._flush()
# Clear buffer
self._write_buffer = bytearray(buffer_size)
buffer_view = memoryview(self._write_buffer)
end = 0
# Update buffer seek
self._buffer_seek = end
return size | python | def write(self, b):
"""
Write the given bytes-like object, b, to the underlying raw stream,
and return the number of bytes written.
Args:
b (bytes-like object): Bytes to write.
Returns:
int: The number of bytes written.
"""
if not self._writable:
raise UnsupportedOperation('write')
size = len(b)
b_view = memoryview(b)
size_left = size
buffer_size = self._buffer_size
max_buffers = self._max_buffers
with self._seek_lock:
end = self._buffer_seek
buffer_view = memoryview(self._write_buffer)
while size_left > 0:
# Get range to copy
start = end
end = start + size_left
if end > buffer_size:
# End of buffer, need flush after copy
end = buffer_size
flush = True
else:
flush = False
buffer_range = end - start
# Update not remaining data size
b_start = size - size_left
size_left -= buffer_range
# Copy data
buffer_view[start:end] = b_view[b_start: b_start + buffer_range]
# Flush buffer if needed
if flush:
# Update buffer seek
# Needed to write the good amount of data
self._buffer_seek = end
# Update global seek, this is the number
# of buffer flushed
self._seek += 1
# Block flush based on maximum number of
# buffers in flush progress
if max_buffers:
futures = self._write_futures
flush_wait = self._FLUSH_WAIT
while sum(1 for future in futures
if not future.done()) >= max_buffers:
sleep(flush_wait)
# Flush
with handle_os_exceptions():
self._flush()
# Clear buffer
self._write_buffer = bytearray(buffer_size)
buffer_view = memoryview(self._write_buffer)
end = 0
# Update buffer seek
self._buffer_seek = end
return size | [
"def",
"write",
"(",
"self",
",",
"b",
")",
":",
"if",
"not",
"self",
".",
"_writable",
":",
"raise",
"UnsupportedOperation",
"(",
"'write'",
")",
"size",
"=",
"len",
"(",
"b",
")",
"b_view",
"=",
"memoryview",
"(",
"b",
")",
"size_left",
"=",
"size"... | Write the given bytes-like object, b, to the underlying raw stream,
and return the number of bytes written.
Args:
b (bytes-like object): Bytes to write.
Returns:
int: The number of bytes written. | [
"Write",
"the",
"given",
"bytes",
"-",
"like",
"object",
"b",
"to",
"the",
"underlying",
"raw",
"stream",
"and",
"return",
"the",
"number",
"of",
"bytes",
"written",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_base_buffered.py#L473-L548 |
mnooner256/pyqrcode | pyqrcode/__init__.py | create | def create(content, error='H', version=None, mode=None, encoding=None):
"""When creating a QR code only the content to be encoded is required,
all the other properties of the code will be guessed based on the
contents given. This function will return a :class:`QRCode` object.
Unless you are familiar with QR code's inner workings
it is recommended that you just specify the *content* and nothing else.
However, there are cases where you may want to specify the various
properties of the created code manually, this is what the other
parameters do. Below, you will find a lengthy explanation of what
each parameter is for. Note, the parameter names and values are taken
directly from the standards. You may need to familiarize yourself
with the terminology of QR codes for the names and their values to
make sense.
The *error* parameter sets the error correction level of the code. There
are four levels defined by the standard. The first is level 'L' which
allows for 7% of the code to be corrected. Second, is level 'M' which
allows for 15% of the code to be corrected. Next, is level 'Q' which
is the most common choice for error correction, it allow 25% of the
code to be corrected. Finally, there is the highest level 'H' which
allows for 30% of the code to be corrected. There are several ways to
specify this parameter, you can use an upper or lower case letter,
a float corresponding to the percentage of correction, or a string
containing the percentage. See tables.modes for all the possible
values. By default this parameter is set to 'H' which is the highest
possible error correction, but it has the smallest available data
capacity.
The *version* parameter specifies the size and data capacity of the
code. Versions are any integer between 1 and 40. Where version 1 is
the smallest QR code, and version 40 is the largest. If this parameter
is left unspecified, then the contents and error correction level will
be used to guess the smallest possible QR code version that the
content will fit inside of. You may want to specify this parameter
for consistency when generating several QR codes with varying amounts
of data. That way all of the generated codes would have the same size.
The *mode* parameter specifies how the contents will be encoded. By
default, the best possible mode for the contents is guessed. There
are four possible modes. First, is 'numeric' which is
used to encode integer numbers. Next, is 'alphanumeric' which is
used to encode some ASCII characters. This mode uses only a limited
set of characters. Most problematic is that it can only use upper case
English characters, consequently, the content parameter will be
subjected to str.upper() before encoding. See tables.ascii_codes for
a complete list of available characters. The is 'kanji' mode can be
used for Japanese characters, but only those that can be understood
via the shift-jis string encoding. Finally, we then have 'binary' mode
which just encodes the bytes directly into the QR code (this encoding
is the least efficient).
The *encoding* parameter specifies how the content will be interpreted.
This parameter only matters if the *content* is a string, unicode, or
byte array type. This parameter must be a valid encoding string or None.
t will be passed the *content*'s encode/decode methods.
"""
return QRCode(content, error, version, mode, encoding) | python | def create(content, error='H', version=None, mode=None, encoding=None):
"""When creating a QR code only the content to be encoded is required,
all the other properties of the code will be guessed based on the
contents given. This function will return a :class:`QRCode` object.
Unless you are familiar with QR code's inner workings
it is recommended that you just specify the *content* and nothing else.
However, there are cases where you may want to specify the various
properties of the created code manually, this is what the other
parameters do. Below, you will find a lengthy explanation of what
each parameter is for. Note, the parameter names and values are taken
directly from the standards. You may need to familiarize yourself
with the terminology of QR codes for the names and their values to
make sense.
The *error* parameter sets the error correction level of the code. There
are four levels defined by the standard. The first is level 'L' which
allows for 7% of the code to be corrected. Second, is level 'M' which
allows for 15% of the code to be corrected. Next, is level 'Q' which
is the most common choice for error correction, it allow 25% of the
code to be corrected. Finally, there is the highest level 'H' which
allows for 30% of the code to be corrected. There are several ways to
specify this parameter, you can use an upper or lower case letter,
a float corresponding to the percentage of correction, or a string
containing the percentage. See tables.modes for all the possible
values. By default this parameter is set to 'H' which is the highest
possible error correction, but it has the smallest available data
capacity.
The *version* parameter specifies the size and data capacity of the
code. Versions are any integer between 1 and 40. Where version 1 is
the smallest QR code, and version 40 is the largest. If this parameter
is left unspecified, then the contents and error correction level will
be used to guess the smallest possible QR code version that the
content will fit inside of. You may want to specify this parameter
for consistency when generating several QR codes with varying amounts
of data. That way all of the generated codes would have the same size.
The *mode* parameter specifies how the contents will be encoded. By
default, the best possible mode for the contents is guessed. There
are four possible modes. First, is 'numeric' which is
used to encode integer numbers. Next, is 'alphanumeric' which is
used to encode some ASCII characters. This mode uses only a limited
set of characters. Most problematic is that it can only use upper case
English characters, consequently, the content parameter will be
subjected to str.upper() before encoding. See tables.ascii_codes for
a complete list of available characters. The is 'kanji' mode can be
used for Japanese characters, but only those that can be understood
via the shift-jis string encoding. Finally, we then have 'binary' mode
which just encodes the bytes directly into the QR code (this encoding
is the least efficient).
The *encoding* parameter specifies how the content will be interpreted.
This parameter only matters if the *content* is a string, unicode, or
byte array type. This parameter must be a valid encoding string or None.
t will be passed the *content*'s encode/decode methods.
"""
return QRCode(content, error, version, mode, encoding) | [
"def",
"create",
"(",
"content",
",",
"error",
"=",
"'H'",
",",
"version",
"=",
"None",
",",
"mode",
"=",
"None",
",",
"encoding",
"=",
"None",
")",
":",
"return",
"QRCode",
"(",
"content",
",",
"error",
",",
"version",
",",
"mode",
",",
"encoding",
... | When creating a QR code only the content to be encoded is required,
all the other properties of the code will be guessed based on the
contents given. This function will return a :class:`QRCode` object.
Unless you are familiar with QR code's inner workings
it is recommended that you just specify the *content* and nothing else.
However, there are cases where you may want to specify the various
properties of the created code manually, this is what the other
parameters do. Below, you will find a lengthy explanation of what
each parameter is for. Note, the parameter names and values are taken
directly from the standards. You may need to familiarize yourself
with the terminology of QR codes for the names and their values to
make sense.
The *error* parameter sets the error correction level of the code. There
are four levels defined by the standard. The first is level 'L' which
allows for 7% of the code to be corrected. Second, is level 'M' which
allows for 15% of the code to be corrected. Next, is level 'Q' which
is the most common choice for error correction, it allow 25% of the
code to be corrected. Finally, there is the highest level 'H' which
allows for 30% of the code to be corrected. There are several ways to
specify this parameter, you can use an upper or lower case letter,
a float corresponding to the percentage of correction, or a string
containing the percentage. See tables.modes for all the possible
values. By default this parameter is set to 'H' which is the highest
possible error correction, but it has the smallest available data
capacity.
The *version* parameter specifies the size and data capacity of the
code. Versions are any integer between 1 and 40. Where version 1 is
the smallest QR code, and version 40 is the largest. If this parameter
is left unspecified, then the contents and error correction level will
be used to guess the smallest possible QR code version that the
content will fit inside of. You may want to specify this parameter
for consistency when generating several QR codes with varying amounts
of data. That way all of the generated codes would have the same size.
The *mode* parameter specifies how the contents will be encoded. By
default, the best possible mode for the contents is guessed. There
are four possible modes. First, is 'numeric' which is
used to encode integer numbers. Next, is 'alphanumeric' which is
used to encode some ASCII characters. This mode uses only a limited
set of characters. Most problematic is that it can only use upper case
English characters, consequently, the content parameter will be
subjected to str.upper() before encoding. See tables.ascii_codes for
a complete list of available characters. The is 'kanji' mode can be
used for Japanese characters, but only those that can be understood
via the shift-jis string encoding. Finally, we then have 'binary' mode
which just encodes the bytes directly into the QR code (this encoding
is the least efficient).
The *encoding* parameter specifies how the content will be interpreted.
This parameter only matters if the *content* is a string, unicode, or
byte array type. This parameter must be a valid encoding string or None.
t will be passed the *content*'s encode/decode methods. | [
"When",
"creating",
"a",
"QR",
"code",
"only",
"the",
"content",
"to",
"be",
"encoded",
"is",
"required",
"all",
"the",
"other",
"properties",
"of",
"the",
"code",
"will",
"be",
"guessed",
"based",
"on",
"the",
"contents",
"given",
".",
"This",
"function",... | train | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/__init__.py#L54-L111 |
mnooner256/pyqrcode | pyqrcode/__init__.py | QRCode._detect_content_type | def _detect_content_type(self, content, encoding):
"""This method tries to auto-detect the type of the data. It first
tries to see if the data is a valid integer, in which case it returns
numeric. Next, it tests the data to see if it is 'alphanumeric.' QR
Codes use a special table with very limited range of ASCII characters.
The code's data is tested to make sure it fits inside this limited
range. If all else fails, the data is determined to be of type
'binary.'
Returns a tuple containing the detected mode and encoding.
Note, encoding ECI is not yet implemented.
"""
def two_bytes(c):
"""Output two byte character code as a single integer."""
def next_byte(b):
"""Make sure that character code is an int. Python 2 and
3 compatibility.
"""
if not isinstance(b, int):
return ord(b)
else:
return b
#Go through the data by looping to every other character
for i in range(0, len(c), 2):
yield (next_byte(c[i]) << 8) | next_byte(c[i+1])
#See if the data is a number
try:
if str(content).isdigit():
return 'numeric', encoding
except (TypeError, UnicodeError):
pass
#See if that data is alphanumeric based on the standards
#special ASCII table
valid_characters = ''.join(tables.ascii_codes.keys())
#Force the characters into a byte array
valid_characters = valid_characters.encode('ASCII')
try:
if isinstance(content, bytes):
c = content.decode('ASCII')
else:
c = str(content).encode('ASCII')
if all(map(lambda x: x in valid_characters, c)):
return 'alphanumeric', 'ASCII'
#This occurs if the content does not contain ASCII characters.
#Since the whole point of the if statement is to look for ASCII
#characters, the resulting mode should not be alphanumeric.
#Hence, this is not an error.
except TypeError:
pass
except UnicodeError:
pass
try:
if isinstance(content, bytes):
if encoding is None:
encoding = 'shiftjis'
c = content.decode(encoding).encode('shiftjis')
else:
c = content.encode('shiftjis')
#All kanji characters must be two bytes long, make sure the
#string length is not odd.
if len(c) % 2 != 0:
return 'binary', encoding
#Make sure the characters are actually in range.
for asint in two_bytes(c):
#Shift the two byte value as indicated by the standard
if not (0x8140 <= asint <= 0x9FFC or
0xE040 <= asint <= 0xEBBF):
return 'binary', encoding
return 'kanji', encoding
except UnicodeError:
#This occurs if the content does not contain Shift JIS kanji
#characters. Hence, the resulting mode should not be kanji.
#This is not an error.
pass
#All of the other attempts failed. The content can only be binary.
return 'binary', encoding | python | def _detect_content_type(self, content, encoding):
"""This method tries to auto-detect the type of the data. It first
tries to see if the data is a valid integer, in which case it returns
numeric. Next, it tests the data to see if it is 'alphanumeric.' QR
Codes use a special table with very limited range of ASCII characters.
The code's data is tested to make sure it fits inside this limited
range. If all else fails, the data is determined to be of type
'binary.'
Returns a tuple containing the detected mode and encoding.
Note, encoding ECI is not yet implemented.
"""
def two_bytes(c):
"""Output two byte character code as a single integer."""
def next_byte(b):
"""Make sure that character code is an int. Python 2 and
3 compatibility.
"""
if not isinstance(b, int):
return ord(b)
else:
return b
#Go through the data by looping to every other character
for i in range(0, len(c), 2):
yield (next_byte(c[i]) << 8) | next_byte(c[i+1])
#See if the data is a number
try:
if str(content).isdigit():
return 'numeric', encoding
except (TypeError, UnicodeError):
pass
#See if that data is alphanumeric based on the standards
#special ASCII table
valid_characters = ''.join(tables.ascii_codes.keys())
#Force the characters into a byte array
valid_characters = valid_characters.encode('ASCII')
try:
if isinstance(content, bytes):
c = content.decode('ASCII')
else:
c = str(content).encode('ASCII')
if all(map(lambda x: x in valid_characters, c)):
return 'alphanumeric', 'ASCII'
#This occurs if the content does not contain ASCII characters.
#Since the whole point of the if statement is to look for ASCII
#characters, the resulting mode should not be alphanumeric.
#Hence, this is not an error.
except TypeError:
pass
except UnicodeError:
pass
try:
if isinstance(content, bytes):
if encoding is None:
encoding = 'shiftjis'
c = content.decode(encoding).encode('shiftjis')
else:
c = content.encode('shiftjis')
#All kanji characters must be two bytes long, make sure the
#string length is not odd.
if len(c) % 2 != 0:
return 'binary', encoding
#Make sure the characters are actually in range.
for asint in two_bytes(c):
#Shift the two byte value as indicated by the standard
if not (0x8140 <= asint <= 0x9FFC or
0xE040 <= asint <= 0xEBBF):
return 'binary', encoding
return 'kanji', encoding
except UnicodeError:
#This occurs if the content does not contain Shift JIS kanji
#characters. Hence, the resulting mode should not be kanji.
#This is not an error.
pass
#All of the other attempts failed. The content can only be binary.
return 'binary', encoding | [
"def",
"_detect_content_type",
"(",
"self",
",",
"content",
",",
"encoding",
")",
":",
"def",
"two_bytes",
"(",
"c",
")",
":",
"\"\"\"Output two byte character code as a single integer.\"\"\"",
"def",
"next_byte",
"(",
"b",
")",
":",
"\"\"\"Make sure that character code... | This method tries to auto-detect the type of the data. It first
tries to see if the data is a valid integer, in which case it returns
numeric. Next, it tests the data to see if it is 'alphanumeric.' QR
Codes use a special table with very limited range of ASCII characters.
The code's data is tested to make sure it fits inside this limited
range. If all else fails, the data is determined to be of type
'binary.'
Returns a tuple containing the detected mode and encoding.
Note, encoding ECI is not yet implemented. | [
"This",
"method",
"tries",
"to",
"auto",
"-",
"detect",
"the",
"type",
"of",
"the",
"data",
".",
"It",
"first",
"tries",
"to",
"see",
"if",
"the",
"data",
"is",
"a",
"valid",
"integer",
"in",
"which",
"case",
"it",
"returns",
"numeric",
".",
"Next",
... | train | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/__init__.py#L240-L330 |
mnooner256/pyqrcode | pyqrcode/__init__.py | QRCode._pick_best_fit | def _pick_best_fit(self, content):
"""This method return the smallest possible QR code version number
that will fit the specified data with the given error level.
"""
import math
for version in range(1, 41):
#Get the maximum possible capacity
capacity = tables.data_capacity[version][self.error][self.mode_num]
#Check the capacity
#Kanji's count in the table is "characters" which are two bytes
if (self.mode_num == tables.modes['kanji'] and
capacity >= math.ceil(len(content) / 2)):
return version
if capacity >= len(content):
return version
raise ValueError('The data will not fit in any QR code version '
'with the given encoding and error level.') | python | def _pick_best_fit(self, content):
"""This method return the smallest possible QR code version number
that will fit the specified data with the given error level.
"""
import math
for version in range(1, 41):
#Get the maximum possible capacity
capacity = tables.data_capacity[version][self.error][self.mode_num]
#Check the capacity
#Kanji's count in the table is "characters" which are two bytes
if (self.mode_num == tables.modes['kanji'] and
capacity >= math.ceil(len(content) / 2)):
return version
if capacity >= len(content):
return version
raise ValueError('The data will not fit in any QR code version '
'with the given encoding and error level.') | [
"def",
"_pick_best_fit",
"(",
"self",
",",
"content",
")",
":",
"import",
"math",
"for",
"version",
"in",
"range",
"(",
"1",
",",
"41",
")",
":",
"#Get the maximum possible capacity",
"capacity",
"=",
"tables",
".",
"data_capacity",
"[",
"version",
"]",
"[",... | This method return the smallest possible QR code version number
that will fit the specified data with the given error level. | [
"This",
"method",
"return",
"the",
"smallest",
"possible",
"QR",
"code",
"version",
"number",
"that",
"will",
"fit",
"the",
"specified",
"data",
"with",
"the",
"given",
"error",
"level",
"."
] | train | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/__init__.py#L332-L351 |
mnooner256/pyqrcode | pyqrcode/__init__.py | QRCode.show | def show(self, wait=1.2, scale=10, module_color=(0, 0, 0, 255),
background=(255, 255, 255, 255), quiet_zone=4):
"""Displays this QR code.
This method is mainly intended for debugging purposes.
This method saves the output of the :py:meth:`png` method (with a default
scaling factor of 10) to a temporary file and opens it with the
standard PNG viewer application or within the standard webbrowser. The
temporary file is deleted afterwards.
If this method does not show any result, try to increase the `wait`
parameter. This parameter specifies the time in seconds to wait till
the temporary file is deleted. Note, that this method does not return
until the provided amount of seconds (default: 1.2) has passed.
The other parameters are simply passed on to the `png` method.
"""
import os
import time
import tempfile
import webbrowser
try: # Python 2
from urlparse import urljoin
from urllib import pathname2url
except ImportError: # Python 3
from urllib.parse import urljoin
from urllib.request import pathname2url
f = tempfile.NamedTemporaryFile('wb', suffix='.png', delete=False)
self.png(f, scale=scale, module_color=module_color,
background=background, quiet_zone=quiet_zone)
f.close()
webbrowser.open_new_tab(urljoin('file:', pathname2url(f.name)))
time.sleep(wait)
os.unlink(f.name) | python | def show(self, wait=1.2, scale=10, module_color=(0, 0, 0, 255),
background=(255, 255, 255, 255), quiet_zone=4):
"""Displays this QR code.
This method is mainly intended for debugging purposes.
This method saves the output of the :py:meth:`png` method (with a default
scaling factor of 10) to a temporary file and opens it with the
standard PNG viewer application or within the standard webbrowser. The
temporary file is deleted afterwards.
If this method does not show any result, try to increase the `wait`
parameter. This parameter specifies the time in seconds to wait till
the temporary file is deleted. Note, that this method does not return
until the provided amount of seconds (default: 1.2) has passed.
The other parameters are simply passed on to the `png` method.
"""
import os
import time
import tempfile
import webbrowser
try: # Python 2
from urlparse import urljoin
from urllib import pathname2url
except ImportError: # Python 3
from urllib.parse import urljoin
from urllib.request import pathname2url
f = tempfile.NamedTemporaryFile('wb', suffix='.png', delete=False)
self.png(f, scale=scale, module_color=module_color,
background=background, quiet_zone=quiet_zone)
f.close()
webbrowser.open_new_tab(urljoin('file:', pathname2url(f.name)))
time.sleep(wait)
os.unlink(f.name) | [
"def",
"show",
"(",
"self",
",",
"wait",
"=",
"1.2",
",",
"scale",
"=",
"10",
",",
"module_color",
"=",
"(",
"0",
",",
"0",
",",
"0",
",",
"255",
")",
",",
"background",
"=",
"(",
"255",
",",
"255",
",",
"255",
",",
"255",
")",
",",
"quiet_zo... | Displays this QR code.
This method is mainly intended for debugging purposes.
This method saves the output of the :py:meth:`png` method (with a default
scaling factor of 10) to a temporary file and opens it with the
standard PNG viewer application or within the standard webbrowser. The
temporary file is deleted afterwards.
If this method does not show any result, try to increase the `wait`
parameter. This parameter specifies the time in seconds to wait till
the temporary file is deleted. Note, that this method does not return
until the provided amount of seconds (default: 1.2) has passed.
The other parameters are simply passed on to the `png` method. | [
"Displays",
"this",
"QR",
"code",
"."
] | train | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/__init__.py#L353-L389 |
mnooner256/pyqrcode | pyqrcode/__init__.py | QRCode.get_png_size | def get_png_size(self, scale=1, quiet_zone=4):
"""This is method helps users determine what *scale* to use when
creating a PNG of this QR code. It is meant mostly to be used in the
console to help the user determine the pixel size of the code
using various scales.
This method will return an integer representing the width and height of
the QR code in pixels, as if it was drawn using the given *scale*.
Because QR codes are square, the number represents both the width
and height dimensions.
The *quiet_zone* parameter sets how wide the quiet zone around the code
should be. According to the standard this should be 4 modules. It is
left settable because such a wide quiet zone is unnecessary in many
applications where the QR code is not being printed.
Example:
>>> code = pyqrcode.QRCode("I don't like spam!")
>>> print(code.get_png_size(1))
31
>>> print(code.get_png_size(5))
155
"""
return builder._get_png_size(self.version, scale, quiet_zone) | python | def get_png_size(self, scale=1, quiet_zone=4):
"""This is method helps users determine what *scale* to use when
creating a PNG of this QR code. It is meant mostly to be used in the
console to help the user determine the pixel size of the code
using various scales.
This method will return an integer representing the width and height of
the QR code in pixels, as if it was drawn using the given *scale*.
Because QR codes are square, the number represents both the width
and height dimensions.
The *quiet_zone* parameter sets how wide the quiet zone around the code
should be. According to the standard this should be 4 modules. It is
left settable because such a wide quiet zone is unnecessary in many
applications where the QR code is not being printed.
Example:
>>> code = pyqrcode.QRCode("I don't like spam!")
>>> print(code.get_png_size(1))
31
>>> print(code.get_png_size(5))
155
"""
return builder._get_png_size(self.version, scale, quiet_zone) | [
"def",
"get_png_size",
"(",
"self",
",",
"scale",
"=",
"1",
",",
"quiet_zone",
"=",
"4",
")",
":",
"return",
"builder",
".",
"_get_png_size",
"(",
"self",
".",
"version",
",",
"scale",
",",
"quiet_zone",
")"
] | This is method helps users determine what *scale* to use when
creating a PNG of this QR code. It is meant mostly to be used in the
console to help the user determine the pixel size of the code
using various scales.
This method will return an integer representing the width and height of
the QR code in pixels, as if it was drawn using the given *scale*.
Because QR codes are square, the number represents both the width
and height dimensions.
The *quiet_zone* parameter sets how wide the quiet zone around the code
should be. According to the standard this should be 4 modules. It is
left settable because such a wide quiet zone is unnecessary in many
applications where the QR code is not being printed.
Example:
>>> code = pyqrcode.QRCode("I don't like spam!")
>>> print(code.get_png_size(1))
31
>>> print(code.get_png_size(5))
155 | [
"This",
"is",
"method",
"helps",
"users",
"determine",
"what",
"*",
"scale",
"*",
"to",
"use",
"when",
"creating",
"a",
"PNG",
"of",
"this",
"QR",
"code",
".",
"It",
"is",
"meant",
"mostly",
"to",
"be",
"used",
"in",
"the",
"console",
"to",
"help",
"... | train | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/__init__.py#L391-L414 |
mnooner256/pyqrcode | pyqrcode/__init__.py | QRCode.png | def png(self, file, scale=1, module_color=(0, 0, 0, 255),
background=(255, 255, 255, 255), quiet_zone=4):
"""This method writes the QR code out as an PNG image. The resulting
PNG has a bit depth of 1. The file parameter is used to specify where
to write the image to. It can either be an writable stream or a
file path.
.. note::
This method depends on the pypng module to actually create the
PNG file.
This method will write the given *file* out as a PNG file. The file
can be either a string file path, or a writable stream. The file
will not be automatically closed if a stream is given.
The *scale* parameter sets how large to draw a single module. By
default one pixel is used to draw a single module. This may make the
code too small to be read efficiently. Increasing the scale will make
the code larger. Only integer scales are usable. This method will
attempt to coerce the parameter into an integer (e.g. 2.5 will become 2,
and '3' will become 3). You can use the :py:meth:`get_png_size` method
to calculate the actual pixel size of the resulting PNG image.
The *module_color* parameter sets what color to use for the encoded
modules (the black part on most QR codes). The *background* parameter
sets what color to use for the background (the white part on most
QR codes). If either parameter is set, then both must be
set or a ValueError is raised. Colors should be specified as either
a list or a tuple of length 3 or 4. The components of the list must
be integers between 0 and 255. The first three member give the RGB
color. The fourth member gives the alpha component, where 0 is
transparent and 255 is opaque. Note, many color
combinations are unreadable by scanners, so be judicious.
The *quiet_zone* parameter sets how wide the quiet zone around the code
should be. According to the standard this should be 4 modules. It is
left settable because such a wide quiet zone is unnecessary in many
applications where the QR code is not being printed.
Example:
>>> code = pyqrcode.create('Are you suggesting coconuts migrate?')
>>> code.png('swallow.png', scale=5)
>>> code.png('swallow.png', scale=5,
module_color=(0x66, 0x33, 0x0), #Dark brown
background=(0xff, 0xff, 0xff, 0x88)) #50% transparent white
"""
builder._png(self.code, self.version, file, scale,
module_color, background, quiet_zone) | python | def png(self, file, scale=1, module_color=(0, 0, 0, 255),
background=(255, 255, 255, 255), quiet_zone=4):
"""This method writes the QR code out as an PNG image. The resulting
PNG has a bit depth of 1. The file parameter is used to specify where
to write the image to. It can either be an writable stream or a
file path.
.. note::
This method depends on the pypng module to actually create the
PNG file.
This method will write the given *file* out as a PNG file. The file
can be either a string file path, or a writable stream. The file
will not be automatically closed if a stream is given.
The *scale* parameter sets how large to draw a single module. By
default one pixel is used to draw a single module. This may make the
code too small to be read efficiently. Increasing the scale will make
the code larger. Only integer scales are usable. This method will
attempt to coerce the parameter into an integer (e.g. 2.5 will become 2,
and '3' will become 3). You can use the :py:meth:`get_png_size` method
to calculate the actual pixel size of the resulting PNG image.
The *module_color* parameter sets what color to use for the encoded
modules (the black part on most QR codes). The *background* parameter
sets what color to use for the background (the white part on most
QR codes). If either parameter is set, then both must be
set or a ValueError is raised. Colors should be specified as either
a list or a tuple of length 3 or 4. The components of the list must
be integers between 0 and 255. The first three member give the RGB
color. The fourth member gives the alpha component, where 0 is
transparent and 255 is opaque. Note, many color
combinations are unreadable by scanners, so be judicious.
The *quiet_zone* parameter sets how wide the quiet zone around the code
should be. According to the standard this should be 4 modules. It is
left settable because such a wide quiet zone is unnecessary in many
applications where the QR code is not being printed.
Example:
>>> code = pyqrcode.create('Are you suggesting coconuts migrate?')
>>> code.png('swallow.png', scale=5)
>>> code.png('swallow.png', scale=5,
module_color=(0x66, 0x33, 0x0), #Dark brown
background=(0xff, 0xff, 0xff, 0x88)) #50% transparent white
"""
builder._png(self.code, self.version, file, scale,
module_color, background, quiet_zone) | [
"def",
"png",
"(",
"self",
",",
"file",
",",
"scale",
"=",
"1",
",",
"module_color",
"=",
"(",
"0",
",",
"0",
",",
"0",
",",
"255",
")",
",",
"background",
"=",
"(",
"255",
",",
"255",
",",
"255",
",",
"255",
")",
",",
"quiet_zone",
"=",
"4",... | This method writes the QR code out as an PNG image. The resulting
PNG has a bit depth of 1. The file parameter is used to specify where
to write the image to. It can either be an writable stream or a
file path.
.. note::
This method depends on the pypng module to actually create the
PNG file.
This method will write the given *file* out as a PNG file. The file
can be either a string file path, or a writable stream. The file
will not be automatically closed if a stream is given.
The *scale* parameter sets how large to draw a single module. By
default one pixel is used to draw a single module. This may make the
code too small to be read efficiently. Increasing the scale will make
the code larger. Only integer scales are usable. This method will
attempt to coerce the parameter into an integer (e.g. 2.5 will become 2,
and '3' will become 3). You can use the :py:meth:`get_png_size` method
to calculate the actual pixel size of the resulting PNG image.
The *module_color* parameter sets what color to use for the encoded
modules (the black part on most QR codes). The *background* parameter
sets what color to use for the background (the white part on most
QR codes). If either parameter is set, then both must be
set or a ValueError is raised. Colors should be specified as either
a list or a tuple of length 3 or 4. The components of the list must
be integers between 0 and 255. The first three member give the RGB
color. The fourth member gives the alpha component, where 0 is
transparent and 255 is opaque. Note, many color
combinations are unreadable by scanners, so be judicious.
The *quiet_zone* parameter sets how wide the quiet zone around the code
should be. According to the standard this should be 4 modules. It is
left settable because such a wide quiet zone is unnecessary in many
applications where the QR code is not being printed.
Example:
>>> code = pyqrcode.create('Are you suggesting coconuts migrate?')
>>> code.png('swallow.png', scale=5)
>>> code.png('swallow.png', scale=5,
module_color=(0x66, 0x33, 0x0), #Dark brown
background=(0xff, 0xff, 0xff, 0x88)) #50% transparent white | [
"This",
"method",
"writes",
"the",
"QR",
"code",
"out",
"as",
"an",
"PNG",
"image",
".",
"The",
"resulting",
"PNG",
"has",
"a",
"bit",
"depth",
"of",
"1",
".",
"The",
"file",
"parameter",
"is",
"used",
"to",
"specify",
"where",
"to",
"write",
"the",
... | train | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/__init__.py#L416-L463 |
mnooner256/pyqrcode | pyqrcode/__init__.py | QRCode.png_as_base64_str | def png_as_base64_str(self, scale=1, module_color=(0, 0, 0, 255),
background=(255, 255, 255, 255), quiet_zone=4):
"""This method uses the png render and returns the PNG image encoded as
base64 string. This can be useful for creating dynamic PNG images for
web development, since no file needs to be created.
Example:
>>> code = pyqrcode.create('Are you suggesting coconuts migrate?')
>>> image_as_str = code.png_as_base64_str(scale=5)
>>> html_img = '<img src="data:image/png;base64,{}">'.format(image_as_str)
The parameters are passed directly to the :py:meth:`png` method. Refer
to that method's documentation for the meaning behind the parameters.
.. note::
This method depends on the pypng module to actually create the
PNG image.
"""
import io
import base64
with io.BytesIO() as virtual_file:
self.png(file=virtual_file, scale=scale, module_color=module_color,
background=background, quiet_zone=quiet_zone)
image_as_str = base64.b64encode(virtual_file.getvalue()).decode("ascii")
return image_as_str | python | def png_as_base64_str(self, scale=1, module_color=(0, 0, 0, 255),
background=(255, 255, 255, 255), quiet_zone=4):
"""This method uses the png render and returns the PNG image encoded as
base64 string. This can be useful for creating dynamic PNG images for
web development, since no file needs to be created.
Example:
>>> code = pyqrcode.create('Are you suggesting coconuts migrate?')
>>> image_as_str = code.png_as_base64_str(scale=5)
>>> html_img = '<img src="data:image/png;base64,{}">'.format(image_as_str)
The parameters are passed directly to the :py:meth:`png` method. Refer
to that method's documentation for the meaning behind the parameters.
.. note::
This method depends on the pypng module to actually create the
PNG image.
"""
import io
import base64
with io.BytesIO() as virtual_file:
self.png(file=virtual_file, scale=scale, module_color=module_color,
background=background, quiet_zone=quiet_zone)
image_as_str = base64.b64encode(virtual_file.getvalue()).decode("ascii")
return image_as_str | [
"def",
"png_as_base64_str",
"(",
"self",
",",
"scale",
"=",
"1",
",",
"module_color",
"=",
"(",
"0",
",",
"0",
",",
"0",
",",
"255",
")",
",",
"background",
"=",
"(",
"255",
",",
"255",
",",
"255",
",",
"255",
")",
",",
"quiet_zone",
"=",
"4",
... | This method uses the png render and returns the PNG image encoded as
base64 string. This can be useful for creating dynamic PNG images for
web development, since no file needs to be created.
Example:
>>> code = pyqrcode.create('Are you suggesting coconuts migrate?')
>>> image_as_str = code.png_as_base64_str(scale=5)
>>> html_img = '<img src="data:image/png;base64,{}">'.format(image_as_str)
The parameters are passed directly to the :py:meth:`png` method. Refer
to that method's documentation for the meaning behind the parameters.
.. note::
This method depends on the pypng module to actually create the
PNG image. | [
"This",
"method",
"uses",
"the",
"png",
"render",
"and",
"returns",
"the",
"PNG",
"image",
"encoded",
"as",
"base64",
"string",
".",
"This",
"can",
"be",
"useful",
"for",
"creating",
"dynamic",
"PNG",
"images",
"for",
"web",
"development",
"since",
"no",
"... | train | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/__init__.py#L465-L491 |
mnooner256/pyqrcode | pyqrcode/__init__.py | QRCode.xbm | def xbm(self, scale=1, quiet_zone=4):
"""Returns a string representing an XBM image of the QR code.
The XBM format is a black and white image format that looks like a
C header file.
Because displaying QR codes in Tkinter is the
primary use case for this renderer, this method does not take a file
parameter. Instead it retuns the rendered QR code data as a string.
Example of using this renderer with Tkinter:
>>> import pyqrcode
>>> import tkinter
>>> code = pyqrcode.create('Knights who say ni!')
>>> code_xbm = code.xbm(scale=5)
>>>
>>> top = tkinter.Tk()
>>> code_bmp = tkinter.BitmapImage(data=code_xbm)
>>> code_bmp.config(foreground="black")
>>> code_bmp.config(background="white")
>>> label = tkinter.Label(image=code_bmp)
>>> label.pack()
The *scale* parameter sets how large to draw a single module. By
default one pixel is used to draw a single module. This may make the
code too small to be read efficiently. Increasing the scale will make
the code larger. Only integer scales are usable. This method will
attempt to coerce the parameter into an integer (e.g. 2.5 will become 2,
and '3' will become 3). You can use the :py:meth:`get_png_size` method
to calculate the actual pixel size of this image when displayed.
The *quiet_zone* parameter sets how wide the quiet zone around the code
should be. According to the standard this should be 4 modules. It is
left settable because such a wide quiet zone is unnecessary in many
applications where the QR code is not being printed.
"""
return builder._xbm(self.code, scale, quiet_zone) | python | def xbm(self, scale=1, quiet_zone=4):
"""Returns a string representing an XBM image of the QR code.
The XBM format is a black and white image format that looks like a
C header file.
Because displaying QR codes in Tkinter is the
primary use case for this renderer, this method does not take a file
parameter. Instead it retuns the rendered QR code data as a string.
Example of using this renderer with Tkinter:
>>> import pyqrcode
>>> import tkinter
>>> code = pyqrcode.create('Knights who say ni!')
>>> code_xbm = code.xbm(scale=5)
>>>
>>> top = tkinter.Tk()
>>> code_bmp = tkinter.BitmapImage(data=code_xbm)
>>> code_bmp.config(foreground="black")
>>> code_bmp.config(background="white")
>>> label = tkinter.Label(image=code_bmp)
>>> label.pack()
The *scale* parameter sets how large to draw a single module. By
default one pixel is used to draw a single module. This may make the
code too small to be read efficiently. Increasing the scale will make
the code larger. Only integer scales are usable. This method will
attempt to coerce the parameter into an integer (e.g. 2.5 will become 2,
and '3' will become 3). You can use the :py:meth:`get_png_size` method
to calculate the actual pixel size of this image when displayed.
The *quiet_zone* parameter sets how wide the quiet zone around the code
should be. According to the standard this should be 4 modules. It is
left settable because such a wide quiet zone is unnecessary in many
applications where the QR code is not being printed.
"""
return builder._xbm(self.code, scale, quiet_zone) | [
"def",
"xbm",
"(",
"self",
",",
"scale",
"=",
"1",
",",
"quiet_zone",
"=",
"4",
")",
":",
"return",
"builder",
".",
"_xbm",
"(",
"self",
".",
"code",
",",
"scale",
",",
"quiet_zone",
")"
] | Returns a string representing an XBM image of the QR code.
The XBM format is a black and white image format that looks like a
C header file.
Because displaying QR codes in Tkinter is the
primary use case for this renderer, this method does not take a file
parameter. Instead it retuns the rendered QR code data as a string.
Example of using this renderer with Tkinter:
>>> import pyqrcode
>>> import tkinter
>>> code = pyqrcode.create('Knights who say ni!')
>>> code_xbm = code.xbm(scale=5)
>>>
>>> top = tkinter.Tk()
>>> code_bmp = tkinter.BitmapImage(data=code_xbm)
>>> code_bmp.config(foreground="black")
>>> code_bmp.config(background="white")
>>> label = tkinter.Label(image=code_bmp)
>>> label.pack()
The *scale* parameter sets how large to draw a single module. By
default one pixel is used to draw a single module. This may make the
code too small to be read efficiently. Increasing the scale will make
the code larger. Only integer scales are usable. This method will
attempt to coerce the parameter into an integer (e.g. 2.5 will become 2,
and '3' will become 3). You can use the :py:meth:`get_png_size` method
to calculate the actual pixel size of this image when displayed.
The *quiet_zone* parameter sets how wide the quiet zone around the code
should be. According to the standard this should be 4 modules. It is
left settable because such a wide quiet zone is unnecessary in many
applications where the QR code is not being printed. | [
"Returns",
"a",
"string",
"representing",
"an",
"XBM",
"image",
"of",
"the",
"QR",
"code",
".",
"The",
"XBM",
"format",
"is",
"a",
"black",
"and",
"white",
"image",
"format",
"that",
"looks",
"like",
"a",
"C",
"header",
"file",
".",
"Because",
"displayin... | train | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/__init__.py#L493-L529 |
mnooner256/pyqrcode | pyqrcode/__init__.py | QRCode.svg | def svg(self, file, scale=1, module_color='#000', background=None,
quiet_zone=4, xmldecl=True, svgns=True, title=None,
svgclass='pyqrcode', lineclass='pyqrline', omithw=False,
debug=False):
"""This method writes the QR code out as an SVG document. The
code is drawn by drawing only the modules corresponding to a 1. They
are drawn using a line, such that contiguous modules in a row
are drawn with a single line.
The *file* parameter is used to specify where to write the document
to. It can either be a writable stream or a file path.
The *scale* parameter sets how large to draw
a single module. By default one pixel is used to draw a single
module. This may make the code too small to be read efficiently.
Increasing the scale will make the code larger. Unlike the png() method,
this method will accept fractional scales (e.g. 2.5).
Note, three things are done to make the code more appropriate for
embedding in a HTML document. The "white" part of the code is actually
transparent. The code itself has a class given by *svgclass* parameter.
The path making up the QR code uses the class set using the *lineclass*.
These should make the code easier to style using CSS.
By default the output of this function is a complete SVG document. If
only the code itself is desired, set the *xmldecl* to false. This will
result in a fragment that contains only the "drawn" portion of the code.
Likewise, you can set the *title* of the document. The SVG name space
attribute can be suppressed by setting *svgns* to False.
When True the *omithw* indicates if width and height attributes should
be omitted. If these attributes are omitted, a ``viewBox`` attribute
will be added to the document.
You can also set the colors directly using the *module_color* and
*background* parameters. The *module_color* parameter sets what color to
use for the data modules (the black part on most QR codes). The
*background* parameter sets what color to use for the background (the
white part on most QR codes). The parameters can be set to any valid
SVG or HTML color. If the background is set to None, then no background
will be drawn, i.e. the background will be transparent. Note, many color
combinations are unreadable by scanners, so be careful.
The *quiet_zone* parameter sets how wide the quiet zone around the code
should be. According to the standard this should be 4 modules. It is
left settable because such a wide quiet zone is unnecessary in many
applications where the QR code is not being printed.
Example:
>>> code = pyqrcode.create('Hello. Uhh, can we have your liver?')
>>> code.svg('live-organ-transplants.svg', 3.6)
>>> code.svg('live-organ-transplants.svg', scale=4,
module_color='brown', background='0xFFFFFF')
"""
builder._svg(self.code, self.version, file, scale=scale,
module_color=module_color, background=background,
quiet_zone=quiet_zone, xmldecl=xmldecl, svgns=svgns,
title=title, svgclass=svgclass, lineclass=lineclass,
omithw=omithw, debug=debug) | python | def svg(self, file, scale=1, module_color='#000', background=None,
quiet_zone=4, xmldecl=True, svgns=True, title=None,
svgclass='pyqrcode', lineclass='pyqrline', omithw=False,
debug=False):
"""This method writes the QR code out as an SVG document. The
code is drawn by drawing only the modules corresponding to a 1. They
are drawn using a line, such that contiguous modules in a row
are drawn with a single line.
The *file* parameter is used to specify where to write the document
to. It can either be a writable stream or a file path.
The *scale* parameter sets how large to draw
a single module. By default one pixel is used to draw a single
module. This may make the code too small to be read efficiently.
Increasing the scale will make the code larger. Unlike the png() method,
this method will accept fractional scales (e.g. 2.5).
Note, three things are done to make the code more appropriate for
embedding in a HTML document. The "white" part of the code is actually
transparent. The code itself has a class given by *svgclass* parameter.
The path making up the QR code uses the class set using the *lineclass*.
These should make the code easier to style using CSS.
By default the output of this function is a complete SVG document. If
only the code itself is desired, set the *xmldecl* to false. This will
result in a fragment that contains only the "drawn" portion of the code.
Likewise, you can set the *title* of the document. The SVG name space
attribute can be suppressed by setting *svgns* to False.
When True the *omithw* indicates if width and height attributes should
be omitted. If these attributes are omitted, a ``viewBox`` attribute
will be added to the document.
You can also set the colors directly using the *module_color* and
*background* parameters. The *module_color* parameter sets what color to
use for the data modules (the black part on most QR codes). The
*background* parameter sets what color to use for the background (the
white part on most QR codes). The parameters can be set to any valid
SVG or HTML color. If the background is set to None, then no background
will be drawn, i.e. the background will be transparent. Note, many color
combinations are unreadable by scanners, so be careful.
The *quiet_zone* parameter sets how wide the quiet zone around the code
should be. According to the standard this should be 4 modules. It is
left settable because such a wide quiet zone is unnecessary in many
applications where the QR code is not being printed.
Example:
>>> code = pyqrcode.create('Hello. Uhh, can we have your liver?')
>>> code.svg('live-organ-transplants.svg', 3.6)
>>> code.svg('live-organ-transplants.svg', scale=4,
module_color='brown', background='0xFFFFFF')
"""
builder._svg(self.code, self.version, file, scale=scale,
module_color=module_color, background=background,
quiet_zone=quiet_zone, xmldecl=xmldecl, svgns=svgns,
title=title, svgclass=svgclass, lineclass=lineclass,
omithw=omithw, debug=debug) | [
"def",
"svg",
"(",
"self",
",",
"file",
",",
"scale",
"=",
"1",
",",
"module_color",
"=",
"'#000'",
",",
"background",
"=",
"None",
",",
"quiet_zone",
"=",
"4",
",",
"xmldecl",
"=",
"True",
",",
"svgns",
"=",
"True",
",",
"title",
"=",
"None",
",",... | This method writes the QR code out as an SVG document. The
code is drawn by drawing only the modules corresponding to a 1. They
are drawn using a line, such that contiguous modules in a row
are drawn with a single line.
The *file* parameter is used to specify where to write the document
to. It can either be a writable stream or a file path.
The *scale* parameter sets how large to draw
a single module. By default one pixel is used to draw a single
module. This may make the code too small to be read efficiently.
Increasing the scale will make the code larger. Unlike the png() method,
this method will accept fractional scales (e.g. 2.5).
Note, three things are done to make the code more appropriate for
embedding in a HTML document. The "white" part of the code is actually
transparent. The code itself has a class given by *svgclass* parameter.
The path making up the QR code uses the class set using the *lineclass*.
These should make the code easier to style using CSS.
By default the output of this function is a complete SVG document. If
only the code itself is desired, set the *xmldecl* to false. This will
result in a fragment that contains only the "drawn" portion of the code.
Likewise, you can set the *title* of the document. The SVG name space
attribute can be suppressed by setting *svgns* to False.
When True the *omithw* indicates if width and height attributes should
be omitted. If these attributes are omitted, a ``viewBox`` attribute
will be added to the document.
You can also set the colors directly using the *module_color* and
*background* parameters. The *module_color* parameter sets what color to
use for the data modules (the black part on most QR codes). The
*background* parameter sets what color to use for the background (the
white part on most QR codes). The parameters can be set to any valid
SVG or HTML color. If the background is set to None, then no background
will be drawn, i.e. the background will be transparent. Note, many color
combinations are unreadable by scanners, so be careful.
The *quiet_zone* parameter sets how wide the quiet zone around the code
should be. According to the standard this should be 4 modules. It is
left settable because such a wide quiet zone is unnecessary in many
applications where the QR code is not being printed.
Example:
>>> code = pyqrcode.create('Hello. Uhh, can we have your liver?')
>>> code.svg('live-organ-transplants.svg', 3.6)
>>> code.svg('live-organ-transplants.svg', scale=4,
module_color='brown', background='0xFFFFFF') | [
"This",
"method",
"writes",
"the",
"QR",
"code",
"out",
"as",
"an",
"SVG",
"document",
".",
"The",
"code",
"is",
"drawn",
"by",
"drawing",
"only",
"the",
"modules",
"corresponding",
"to",
"a",
"1",
".",
"They",
"are",
"drawn",
"using",
"a",
"line",
"su... | train | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/__init__.py#L531-L589 |
mnooner256/pyqrcode | pyqrcode/__init__.py | QRCode.eps | def eps(self, file, scale=1, module_color=(0, 0, 0),
background=None, quiet_zone=4):
"""This method writes the QR code out as an EPS document. The
code is drawn by only writing the data modules corresponding to a 1.
They are drawn using a line, such that contiguous modules in a row
are drawn with a single line.
The *file* parameter is used to specify where to write the document
to. It can either be a writable (text) stream or a file path.
The *scale* parameter sets how large to draw a single module. By
default one point (1/72 inch) is used to draw a single module. This may
make the code to small to be read efficiently. Increasing the scale
will make the code larger. This method will accept fractional scales
(e.g. 2.5).
The *module_color* parameter sets the color of the data modules. The
*background* parameter sets the background (page) color to use. They
are specified as either a triple of floats, e.g. (0.5, 0.5, 0.5), or a
triple of integers, e.g. (128, 128, 128). The default *module_color* is
black. The default *background* color is no background at all.
The *quiet_zone* parameter sets how large to draw the border around
the code. As per the standard, the default value is 4 modules.
Examples:
>>> qr = pyqrcode.create('Hello world')
>>> qr.eps('hello-world.eps', scale=2.5, module_color='#36C')
>>> qr.eps('hello-world2.eps', background='#eee')
>>> out = io.StringIO()
>>> qr.eps(out, module_color=(.4, .4, .4))
"""
builder._eps(self.code, self.version, file, scale, module_color,
background, quiet_zone) | python | def eps(self, file, scale=1, module_color=(0, 0, 0),
background=None, quiet_zone=4):
"""This method writes the QR code out as an EPS document. The
code is drawn by only writing the data modules corresponding to a 1.
They are drawn using a line, such that contiguous modules in a row
are drawn with a single line.
The *file* parameter is used to specify where to write the document
to. It can either be a writable (text) stream or a file path.
The *scale* parameter sets how large to draw a single module. By
default one point (1/72 inch) is used to draw a single module. This may
make the code to small to be read efficiently. Increasing the scale
will make the code larger. This method will accept fractional scales
(e.g. 2.5).
The *module_color* parameter sets the color of the data modules. The
*background* parameter sets the background (page) color to use. They
are specified as either a triple of floats, e.g. (0.5, 0.5, 0.5), or a
triple of integers, e.g. (128, 128, 128). The default *module_color* is
black. The default *background* color is no background at all.
The *quiet_zone* parameter sets how large to draw the border around
the code. As per the standard, the default value is 4 modules.
Examples:
>>> qr = pyqrcode.create('Hello world')
>>> qr.eps('hello-world.eps', scale=2.5, module_color='#36C')
>>> qr.eps('hello-world2.eps', background='#eee')
>>> out = io.StringIO()
>>> qr.eps(out, module_color=(.4, .4, .4))
"""
builder._eps(self.code, self.version, file, scale, module_color,
background, quiet_zone) | [
"def",
"eps",
"(",
"self",
",",
"file",
",",
"scale",
"=",
"1",
",",
"module_color",
"=",
"(",
"0",
",",
"0",
",",
"0",
")",
",",
"background",
"=",
"None",
",",
"quiet_zone",
"=",
"4",
")",
":",
"builder",
".",
"_eps",
"(",
"self",
".",
"code"... | This method writes the QR code out as an EPS document. The
code is drawn by only writing the data modules corresponding to a 1.
They are drawn using a line, such that contiguous modules in a row
are drawn with a single line.
The *file* parameter is used to specify where to write the document
to. It can either be a writable (text) stream or a file path.
The *scale* parameter sets how large to draw a single module. By
default one point (1/72 inch) is used to draw a single module. This may
make the code to small to be read efficiently. Increasing the scale
will make the code larger. This method will accept fractional scales
(e.g. 2.5).
The *module_color* parameter sets the color of the data modules. The
*background* parameter sets the background (page) color to use. They
are specified as either a triple of floats, e.g. (0.5, 0.5, 0.5), or a
triple of integers, e.g. (128, 128, 128). The default *module_color* is
black. The default *background* color is no background at all.
The *quiet_zone* parameter sets how large to draw the border around
the code. As per the standard, the default value is 4 modules.
Examples:
>>> qr = pyqrcode.create('Hello world')
>>> qr.eps('hello-world.eps', scale=2.5, module_color='#36C')
>>> qr.eps('hello-world2.eps', background='#eee')
>>> out = io.StringIO()
>>> qr.eps(out, module_color=(.4, .4, .4)) | [
"This",
"method",
"writes",
"the",
"QR",
"code",
"out",
"as",
"an",
"EPS",
"document",
".",
"The",
"code",
"is",
"drawn",
"by",
"only",
"writing",
"the",
"data",
"modules",
"corresponding",
"to",
"a",
"1",
".",
"They",
"are",
"drawn",
"using",
"a",
"li... | train | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/__init__.py#L591-L624 |
mnooner256/pyqrcode | pyqrcode/__init__.py | QRCode.terminal | def terminal(self, module_color='default', background='reverse',
quiet_zone=4):
"""This method returns a string containing ASCII escape codes,
such that if printed to a compatible terminal, it will display
a vaild QR code. The code is printed using ASCII escape
codes that alter the coloring of the background.
The *module_color* parameter sets what color to
use for the data modules (the black part on most QR codes).
Likewise, the *background* parameter sets what color to use
for the background (the white part on most QR codes).
There are two options for colors. The first, and most widely
supported, is to use the 8 or 16 color scheme. This scheme uses
eight to sixteen named colors. The following colors are
supported the most widely supported: black, red, green,
yellow, blue, magenta, and cyan. There are an some additional
named colors that are supported by most terminals: light gray,
dark gray, light red, light green, light blue, light yellow,
light magenta, light cyan, and white.
There are two special named colors. The first is the
"default" color. This color is the color the background of
the terminal is set to. The next color is the "reverse"
color. This is not really a color at all but a special
property that will reverse the current color. These two colors
are the default values for *module_color* and *background*
respectively. These values should work on most terminals.
Finally, there is one more way to specify the color. Some
terminals support 256 colors. The actual colors displayed in the
terminal is system dependent. This is the least transportable option.
To use the 256 color scheme set *module_color* and/or
*background* to a number between 0 and 256.
The *quiet_zone* parameter sets how wide the quiet zone around the code
should be. According to the standard this should be 4 modules. It is
left settable because such a wide quiet zone is unnecessary in many
applications.
Example:
>>> code = pyqrcode.create('Example')
>>> text = code.terminal()
>>> print(text)
"""
return builder._terminal(self.code, module_color, background,
quiet_zone) | python | def terminal(self, module_color='default', background='reverse',
quiet_zone=4):
"""This method returns a string containing ASCII escape codes,
such that if printed to a compatible terminal, it will display
a vaild QR code. The code is printed using ASCII escape
codes that alter the coloring of the background.
The *module_color* parameter sets what color to
use for the data modules (the black part on most QR codes).
Likewise, the *background* parameter sets what color to use
for the background (the white part on most QR codes).
There are two options for colors. The first, and most widely
supported, is to use the 8 or 16 color scheme. This scheme uses
eight to sixteen named colors. The following colors are
supported the most widely supported: black, red, green,
yellow, blue, magenta, and cyan. There are an some additional
named colors that are supported by most terminals: light gray,
dark gray, light red, light green, light blue, light yellow,
light magenta, light cyan, and white.
There are two special named colors. The first is the
"default" color. This color is the color the background of
the terminal is set to. The next color is the "reverse"
color. This is not really a color at all but a special
property that will reverse the current color. These two colors
are the default values for *module_color* and *background*
respectively. These values should work on most terminals.
Finally, there is one more way to specify the color. Some
terminals support 256 colors. The actual colors displayed in the
terminal is system dependent. This is the least transportable option.
To use the 256 color scheme set *module_color* and/or
*background* to a number between 0 and 256.
The *quiet_zone* parameter sets how wide the quiet zone around the code
should be. According to the standard this should be 4 modules. It is
left settable because such a wide quiet zone is unnecessary in many
applications.
Example:
>>> code = pyqrcode.create('Example')
>>> text = code.terminal()
>>> print(text)
"""
return builder._terminal(self.code, module_color, background,
quiet_zone) | [
"def",
"terminal",
"(",
"self",
",",
"module_color",
"=",
"'default'",
",",
"background",
"=",
"'reverse'",
",",
"quiet_zone",
"=",
"4",
")",
":",
"return",
"builder",
".",
"_terminal",
"(",
"self",
".",
"code",
",",
"module_color",
",",
"background",
",",... | This method returns a string containing ASCII escape codes,
such that if printed to a compatible terminal, it will display
a vaild QR code. The code is printed using ASCII escape
codes that alter the coloring of the background.
The *module_color* parameter sets what color to
use for the data modules (the black part on most QR codes).
Likewise, the *background* parameter sets what color to use
for the background (the white part on most QR codes).
There are two options for colors. The first, and most widely
supported, is to use the 8 or 16 color scheme. This scheme uses
eight to sixteen named colors. The following colors are
supported the most widely supported: black, red, green,
yellow, blue, magenta, and cyan. There are an some additional
named colors that are supported by most terminals: light gray,
dark gray, light red, light green, light blue, light yellow,
light magenta, light cyan, and white.
There are two special named colors. The first is the
"default" color. This color is the color the background of
the terminal is set to. The next color is the "reverse"
color. This is not really a color at all but a special
property that will reverse the current color. These two colors
are the default values for *module_color* and *background*
respectively. These values should work on most terminals.
Finally, there is one more way to specify the color. Some
terminals support 256 colors. The actual colors displayed in the
terminal is system dependent. This is the least transportable option.
To use the 256 color scheme set *module_color* and/or
*background* to a number between 0 and 256.
The *quiet_zone* parameter sets how wide the quiet zone around the code
should be. According to the standard this should be 4 modules. It is
left settable because such a wide quiet zone is unnecessary in many
applications.
Example:
>>> code = pyqrcode.create('Example')
>>> text = code.terminal()
>>> print(text) | [
"This",
"method",
"returns",
"a",
"string",
"containing",
"ASCII",
"escape",
"codes",
"such",
"that",
"if",
"printed",
"to",
"a",
"compatible",
"terminal",
"it",
"will",
"display",
"a",
"vaild",
"QR",
"code",
".",
"The",
"code",
"is",
"printed",
"using",
"... | train | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/__init__.py#L626-L672 |
mnooner256/pyqrcode | pyqrcode/builder.py | _get_writable | def _get_writable(stream_or_path, mode):
"""This method returns a tuple containing the stream and a flag to indicate
if the stream should be automatically closed.
The `stream_or_path` parameter is returned if it is an open writable stream.
Otherwise, it treats the `stream_or_path` parameter as a file path and
opens it with the given mode.
It is used by the svg and png methods to interpret the file parameter.
:type stream_or_path: str | io.BufferedIOBase
:type mode: str | unicode
:rtype: (io.BufferedIOBase, bool)
"""
is_stream = hasattr(stream_or_path, 'write')
if not is_stream:
# No stream provided, treat "stream_or_path" as path
stream_or_path = open(stream_or_path, mode)
return stream_or_path, not is_stream | python | def _get_writable(stream_or_path, mode):
"""This method returns a tuple containing the stream and a flag to indicate
if the stream should be automatically closed.
The `stream_or_path` parameter is returned if it is an open writable stream.
Otherwise, it treats the `stream_or_path` parameter as a file path and
opens it with the given mode.
It is used by the svg and png methods to interpret the file parameter.
:type stream_or_path: str | io.BufferedIOBase
:type mode: str | unicode
:rtype: (io.BufferedIOBase, bool)
"""
is_stream = hasattr(stream_or_path, 'write')
if not is_stream:
# No stream provided, treat "stream_or_path" as path
stream_or_path = open(stream_or_path, mode)
return stream_or_path, not is_stream | [
"def",
"_get_writable",
"(",
"stream_or_path",
",",
"mode",
")",
":",
"is_stream",
"=",
"hasattr",
"(",
"stream_or_path",
",",
"'write'",
")",
"if",
"not",
"is_stream",
":",
"# No stream provided, treat \"stream_or_path\" as path",
"stream_or_path",
"=",
"open",
"(",
... | This method returns a tuple containing the stream and a flag to indicate
if the stream should be automatically closed.
The `stream_or_path` parameter is returned if it is an open writable stream.
Otherwise, it treats the `stream_or_path` parameter as a file path and
opens it with the given mode.
It is used by the svg and png methods to interpret the file parameter.
:type stream_or_path: str | io.BufferedIOBase
:type mode: str | unicode
:rtype: (io.BufferedIOBase, bool) | [
"This",
"method",
"returns",
"a",
"tuple",
"containing",
"the",
"stream",
"and",
"a",
"flag",
"to",
"indicate",
"if",
"the",
"stream",
"should",
"be",
"automatically",
"closed",
"."
] | train | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/builder.py#L907-L925 |
mnooner256/pyqrcode | pyqrcode/builder.py | _get_png_size | def _get_png_size(version, scale, quiet_zone=4):
"""See: QRCode.get_png_size
This function was abstracted away from QRCode to allow for the output of
QR codes during the build process, i.e. for debugging. It works
just the same except you must specify the code's version. This is needed
to calculate the PNG's size.
"""
#Formula: scale times number of modules plus the border on each side
return (int(scale) * tables.version_size[version]) + (2 * quiet_zone * int(scale)) | python | def _get_png_size(version, scale, quiet_zone=4):
"""See: QRCode.get_png_size
This function was abstracted away from QRCode to allow for the output of
QR codes during the build process, i.e. for debugging. It works
just the same except you must specify the code's version. This is needed
to calculate the PNG's size.
"""
#Formula: scale times number of modules plus the border on each side
return (int(scale) * tables.version_size[version]) + (2 * quiet_zone * int(scale)) | [
"def",
"_get_png_size",
"(",
"version",
",",
"scale",
",",
"quiet_zone",
"=",
"4",
")",
":",
"#Formula: scale times number of modules plus the border on each side",
"return",
"(",
"int",
"(",
"scale",
")",
"*",
"tables",
".",
"version_size",
"[",
"version",
"]",
"... | See: QRCode.get_png_size
This function was abstracted away from QRCode to allow for the output of
QR codes during the build process, i.e. for debugging. It works
just the same except you must specify the code's version. This is needed
to calculate the PNG's size. | [
"See",
":",
"QRCode",
".",
"get_png_size"
] | train | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/builder.py#L928-L937 |
mnooner256/pyqrcode | pyqrcode/builder.py | _terminal | def _terminal(code, module_color='default', background='reverse', quiet_zone=4):
"""This method returns a string containing ASCII escape codes,
such that if printed to a terminal, it will display a vaild
QR code. The module_color and the background color should be keys
in the tables.term_colors table for printing using the 8/16
color scheme. Alternatively, they can be a number between 0 and
256 in order to use the 88/256 color scheme. Otherwise, a
ValueError will be raised.
Note, the code is outputted by changing the background color. Then
two spaces are written to the terminal. Finally, the terminal is
reset back to how it was.
"""
buf = io.StringIO()
def draw_border():
for i in range(quiet_zone):
buf.write(background)
if module_color in tables.term_colors:
data = '\033[{0}m \033[0m'.format(
tables.term_colors[module_color])
elif 0 <= module_color <= 256:
data = '\033[48;5;{0}m \033[0m'.format(module_color)
else:
raise ValueError('The module color, {0}, must a key in '
'pyqrcode.tables.term_colors or a number '
'between 0 and 256.'.format(
module_color))
if background in tables.term_colors:
background = '\033[{0}m \033[0m'.format(
tables.term_colors[background])
elif 0 <= background <= 256:
background = '\033[48;5;{0}m \033[0m'.format(background)
else:
raise ValueError('The background color, {0}, must a key in '
'pyqrcode.tables.term_colors or a number '
'between 0 and 256.'.format(
background))
#This will be the beginning and ending row for the code.
border_row = background * (len(code[0]) + (2 * quiet_zone))
#Make sure we begin on a new line, and force the terminal back
#to normal
buf.write('\n')
#QRCodes have a quiet zone consisting of background modules
for i in range(quiet_zone):
buf.write(border_row)
buf.write('\n')
for row in code:
#Each code has a quiet zone on the left side, this is the left
#border for this code
draw_border()
for bit in row:
if bit == 1:
buf.write(data)
elif bit == 0:
buf.write(background)
#Each row ends with a quiet zone on the right side, this is the
#right hand border background modules
draw_border()
buf.write('\n')
#QRCodes have a background quiet zone row following the code
for i in range(quiet_zone):
buf.write(border_row)
buf.write('\n')
return buf.getvalue() | python | def _terminal(code, module_color='default', background='reverse', quiet_zone=4):
"""This method returns a string containing ASCII escape codes,
such that if printed to a terminal, it will display a vaild
QR code. The module_color and the background color should be keys
in the tables.term_colors table for printing using the 8/16
color scheme. Alternatively, they can be a number between 0 and
256 in order to use the 88/256 color scheme. Otherwise, a
ValueError will be raised.
Note, the code is outputted by changing the background color. Then
two spaces are written to the terminal. Finally, the terminal is
reset back to how it was.
"""
buf = io.StringIO()
def draw_border():
for i in range(quiet_zone):
buf.write(background)
if module_color in tables.term_colors:
data = '\033[{0}m \033[0m'.format(
tables.term_colors[module_color])
elif 0 <= module_color <= 256:
data = '\033[48;5;{0}m \033[0m'.format(module_color)
else:
raise ValueError('The module color, {0}, must a key in '
'pyqrcode.tables.term_colors or a number '
'between 0 and 256.'.format(
module_color))
if background in tables.term_colors:
background = '\033[{0}m \033[0m'.format(
tables.term_colors[background])
elif 0 <= background <= 256:
background = '\033[48;5;{0}m \033[0m'.format(background)
else:
raise ValueError('The background color, {0}, must a key in '
'pyqrcode.tables.term_colors or a number '
'between 0 and 256.'.format(
background))
#This will be the beginning and ending row for the code.
border_row = background * (len(code[0]) + (2 * quiet_zone))
#Make sure we begin on a new line, and force the terminal back
#to normal
buf.write('\n')
#QRCodes have a quiet zone consisting of background modules
for i in range(quiet_zone):
buf.write(border_row)
buf.write('\n')
for row in code:
#Each code has a quiet zone on the left side, this is the left
#border for this code
draw_border()
for bit in row:
if bit == 1:
buf.write(data)
elif bit == 0:
buf.write(background)
#Each row ends with a quiet zone on the right side, this is the
#right hand border background modules
draw_border()
buf.write('\n')
#QRCodes have a background quiet zone row following the code
for i in range(quiet_zone):
buf.write(border_row)
buf.write('\n')
return buf.getvalue() | [
"def",
"_terminal",
"(",
"code",
",",
"module_color",
"=",
"'default'",
",",
"background",
"=",
"'reverse'",
",",
"quiet_zone",
"=",
"4",
")",
":",
"buf",
"=",
"io",
".",
"StringIO",
"(",
")",
"def",
"draw_border",
"(",
")",
":",
"for",
"i",
"in",
"r... | This method returns a string containing ASCII escape codes,
such that if printed to a terminal, it will display a vaild
QR code. The module_color and the background color should be keys
in the tables.term_colors table for printing using the 8/16
color scheme. Alternatively, they can be a number between 0 and
256 in order to use the 88/256 color scheme. Otherwise, a
ValueError will be raised.
Note, the code is outputted by changing the background color. Then
two spaces are written to the terminal. Finally, the terminal is
reset back to how it was. | [
"This",
"method",
"returns",
"a",
"string",
"containing",
"ASCII",
"escape",
"codes",
"such",
"that",
"if",
"printed",
"to",
"a",
"terminal",
"it",
"will",
"display",
"a",
"vaild",
"QR",
"code",
".",
"The",
"module_color",
"and",
"the",
"background",
"color"... | train | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/builder.py#L940-L1014 |
mnooner256/pyqrcode | pyqrcode/builder.py | _text | def _text(code, quiet_zone=4):
"""This method returns a text based representation of the QR code.
This is useful for debugging purposes.
"""
buf = io.StringIO()
border_row = '0' * (len(code[0]) + (quiet_zone*2))
#Every QR code start with a quiet zone at the top
for b in range(quiet_zone):
buf.write(border_row)
buf.write('\n')
for row in code:
#Draw the starting quiet zone
for b in range(quiet_zone):
buf.write('0')
#Actually draw the QR code
for bit in row:
if bit == 1:
buf.write('1')
elif bit == 0:
buf.write('0')
#This is for debugging unfinished QR codes,
#unset pixels will be spaces.
else:
buf.write(' ')
#Draw the ending quiet zone
for b in range(quiet_zone):
buf.write('0')
buf.write('\n')
#Every QR code ends with a quiet zone at the bottom
for b in range(quiet_zone):
buf.write(border_row)
buf.write('\n')
return buf.getvalue() | python | def _text(code, quiet_zone=4):
"""This method returns a text based representation of the QR code.
This is useful for debugging purposes.
"""
buf = io.StringIO()
border_row = '0' * (len(code[0]) + (quiet_zone*2))
#Every QR code start with a quiet zone at the top
for b in range(quiet_zone):
buf.write(border_row)
buf.write('\n')
for row in code:
#Draw the starting quiet zone
for b in range(quiet_zone):
buf.write('0')
#Actually draw the QR code
for bit in row:
if bit == 1:
buf.write('1')
elif bit == 0:
buf.write('0')
#This is for debugging unfinished QR codes,
#unset pixels will be spaces.
else:
buf.write(' ')
#Draw the ending quiet zone
for b in range(quiet_zone):
buf.write('0')
buf.write('\n')
#Every QR code ends with a quiet zone at the bottom
for b in range(quiet_zone):
buf.write(border_row)
buf.write('\n')
return buf.getvalue() | [
"def",
"_text",
"(",
"code",
",",
"quiet_zone",
"=",
"4",
")",
":",
"buf",
"=",
"io",
".",
"StringIO",
"(",
")",
"border_row",
"=",
"'0'",
"*",
"(",
"len",
"(",
"code",
"[",
"0",
"]",
")",
"+",
"(",
"quiet_zone",
"*",
"2",
")",
")",
"#Every QR ... | This method returns a text based representation of the QR code.
This is useful for debugging purposes. | [
"This",
"method",
"returns",
"a",
"text",
"based",
"representation",
"of",
"the",
"QR",
"code",
".",
"This",
"is",
"useful",
"for",
"debugging",
"purposes",
"."
] | train | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/builder.py#L1016-L1055 |
mnooner256/pyqrcode | pyqrcode/builder.py | _xbm | def _xbm(code, scale=1, quiet_zone=4):
"""This function will format the QR code as a X BitMap.
This can be used to display the QR code with Tkinter.
"""
try:
str = unicode # Python 2
except NameError:
str = __builtins__['str']
buf = io.StringIO()
# Calculate the width in pixels
pixel_width = (len(code[0]) + quiet_zone * 2) * scale
# Add the size information and open the pixel data section
buf.write('#define im_width ')
buf.write(str(pixel_width))
buf.write('\n')
buf.write('#define im_height ')
buf.write(str(pixel_width))
buf.write('\n')
buf.write('static char im_bits[] = {\n')
# Calculate the number of bytes per row
byte_width = int(math.ceil(pixel_width / 8.0))
# Add the top quiet zone
buf.write(('0x00,' * byte_width + '\n') * quiet_zone * scale)
for row in code:
# Add the left quiet zone
row_bits = '0' * quiet_zone * scale
# Add the actual QR code
for pixel in row:
row_bits += str(pixel) * scale
# Add the right quiet zone
row_bits += '0' * quiet_zone * scale
# Format the row
formated_row = ''
for b in range(byte_width):
formated_row += '0x{0:02x},'.format(int(row_bits[:8][::-1], 2))
row_bits = row_bits[8:]
formated_row += '\n'
# Add the formatted row
buf.write(formated_row * scale)
# Add the bottom quiet zone and close the pixel data section
buf.write(('0x00,' * byte_width + '\n') * quiet_zone * scale)
buf.write('};')
return buf.getvalue() | python | def _xbm(code, scale=1, quiet_zone=4):
"""This function will format the QR code as a X BitMap.
This can be used to display the QR code with Tkinter.
"""
try:
str = unicode # Python 2
except NameError:
str = __builtins__['str']
buf = io.StringIO()
# Calculate the width in pixels
pixel_width = (len(code[0]) + quiet_zone * 2) * scale
# Add the size information and open the pixel data section
buf.write('#define im_width ')
buf.write(str(pixel_width))
buf.write('\n')
buf.write('#define im_height ')
buf.write(str(pixel_width))
buf.write('\n')
buf.write('static char im_bits[] = {\n')
# Calculate the number of bytes per row
byte_width = int(math.ceil(pixel_width / 8.0))
# Add the top quiet zone
buf.write(('0x00,' * byte_width + '\n') * quiet_zone * scale)
for row in code:
# Add the left quiet zone
row_bits = '0' * quiet_zone * scale
# Add the actual QR code
for pixel in row:
row_bits += str(pixel) * scale
# Add the right quiet zone
row_bits += '0' * quiet_zone * scale
# Format the row
formated_row = ''
for b in range(byte_width):
formated_row += '0x{0:02x},'.format(int(row_bits[:8][::-1], 2))
row_bits = row_bits[8:]
formated_row += '\n'
# Add the formatted row
buf.write(formated_row * scale)
# Add the bottom quiet zone and close the pixel data section
buf.write(('0x00,' * byte_width + '\n') * quiet_zone * scale)
buf.write('};')
return buf.getvalue() | [
"def",
"_xbm",
"(",
"code",
",",
"scale",
"=",
"1",
",",
"quiet_zone",
"=",
"4",
")",
":",
"try",
":",
"str",
"=",
"unicode",
"# Python 2",
"except",
"NameError",
":",
"str",
"=",
"__builtins__",
"[",
"'str'",
"]",
"buf",
"=",
"io",
".",
"StringIO",
... | This function will format the QR code as a X BitMap.
This can be used to display the QR code with Tkinter. | [
"This",
"function",
"will",
"format",
"the",
"QR",
"code",
"as",
"a",
"X",
"BitMap",
".",
"This",
"can",
"be",
"used",
"to",
"display",
"the",
"QR",
"code",
"with",
"Tkinter",
"."
] | train | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/builder.py#L1057-L1105 |
mnooner256/pyqrcode | pyqrcode/builder.py | _svg | def _svg(code, version, file, scale=1, module_color='#000', background=None,
quiet_zone=4, xmldecl=True, svgns=True, title=None, svgclass='pyqrcode',
lineclass='pyqrline', omithw=False, debug=False):
"""This function writes the QR code out as an SVG document. The
code is drawn by drawing only the modules corresponding to a 1. They
are drawn using a line, such that contiguous modules in a row
are drawn with a single line. The file parameter is used to
specify where to write the document to. It can either be a writable (binary)
stream or a file path. The scale parameter is sets how large to draw
a single module. By default one pixel is used to draw a single
module. This may make the code to small to be read efficiently.
Increasing the scale will make the code larger. This method will accept
fractional scales (e.g. 2.5).
:param module_color: Color of the QR code (default: ``#000`` (black))
:param background: Optional background color.
(default: ``None`` (no background))
:param quiet_zone: Border around the QR code (also known as quiet zone)
(default: ``4``). Set to zero (``0``) if the code shouldn't
have a border.
:param xmldecl: Inidcates if the XML declaration header should be written
(default: ``True``)
:param svgns: Indicates if the SVG namespace should be written
(default: ``True``)
:param title: Optional title of the generated SVG document.
:param svgclass: The CSS class of the SVG document
(if set to ``None``, the SVG element won't have a class).
:param lineclass: The CSS class of the path element
(if set to ``None``, the path won't have a class).
:param omithw: Indicates if width and height attributes should be
omitted (default: ``False``). If these attributes are omitted,
a ``viewBox`` attribute will be added to the document.
:param debug: Inidicates if errors in the QR code should be added to the
output (default: ``False``).
"""
from functools import partial
from xml.sax.saxutils import quoteattr
def write_unicode(write_meth, unicode_str):
"""\
Encodes the provided string into UTF-8 and writes the result using
the `write_meth`.
"""
write_meth(unicode_str.encode('utf-8'))
def line(x, y, length, relative):
"""Returns coordinates to draw a line with the provided length.
"""
return '{0}{1} {2}h{3}'.format(('m' if relative else 'M'), x, y, length)
def errline(col_number, row_number):
"""Returns the coordinates to draw an error bit.
"""
# Debug path uses always absolute coordinates
# .5 == stroke / 2
return line(col_number + quiet_zone, row_number + quiet_zone + .5, 1, False)
f, autoclose = _get_writable(file, 'wb')
write = partial(write_unicode, f.write)
write_bytes = f.write
# Write the document header
if xmldecl:
write_bytes(b'<?xml version="1.0" encoding="UTF-8"?>\n')
write_bytes(b'<svg')
if svgns:
write_bytes(b' xmlns="http://www.w3.org/2000/svg"')
size = tables.version_size[version] * scale + (2 * quiet_zone * scale)
if not omithw:
write(' height="{0}" width="{0}"'.format(size))
else:
write(' viewBox="0 0 {0} {0}"'.format(size))
if svgclass is not None:
write_bytes(b' class=')
write(quoteattr(svgclass))
write_bytes(b'>')
if title is not None:
write('<title>{0}</title>'.format(title))
# Draw a background rectangle if necessary
if background is not None:
write('<path fill="{1}" d="M0 0h{0}v{0}h-{0}z"/>'
.format(size, background))
write_bytes(b'<path')
if scale != 1:
write(' transform="scale({0})"'.format(scale))
if module_color is not None:
write_bytes(b' stroke=')
write(quoteattr(module_color))
if lineclass is not None:
write_bytes(b' class=')
write(quoteattr(lineclass))
write_bytes(b' d="')
# Used to keep track of unknown/error coordinates.
debug_path = ''
# Current pen pointer position
x, y = -quiet_zone, quiet_zone - .5 # .5 == stroke-width / 2
wrote_bit = False
# Loop through each row of the code
for rnumber, row in enumerate(code):
start_column = 0 # Reset the starting column number
coord = '' # Reset row coordinates
y += 1 # Pen position on y-axis
length = 0 # Reset line length
# Examine every bit in the row
for colnumber, bit in enumerate(row):
if bit == 1:
length += 1
else:
if length:
x = start_column - x
coord += line(x, y, length, relative=wrote_bit)
x = start_column + length
y = 0 # y-axis won't change unless the row changes
length = 0
wrote_bit = True
start_column = colnumber + 1
if debug and bit != 0:
debug_path += errline(colnumber, rnumber)
if length:
x = start_column - x
coord += line(x, y, length, relative=wrote_bit)
x = start_column + length
wrote_bit = True
write(coord)
# Close path
write_bytes(b'"/>')
if debug and debug_path:
write_bytes(b'<path')
if scale != 1:
write(' transform="scale({0})"'.format(scale))
write(' class="pyqrerr" stroke="red" d="{0}"/>'.format(debug_path))
# Close document
write_bytes(b'</svg>\n')
if autoclose:
f.close() | python | def _svg(code, version, file, scale=1, module_color='#000', background=None,
quiet_zone=4, xmldecl=True, svgns=True, title=None, svgclass='pyqrcode',
lineclass='pyqrline', omithw=False, debug=False):
"""This function writes the QR code out as an SVG document. The
code is drawn by drawing only the modules corresponding to a 1. They
are drawn using a line, such that contiguous modules in a row
are drawn with a single line. The file parameter is used to
specify where to write the document to. It can either be a writable (binary)
stream or a file path. The scale parameter is sets how large to draw
a single module. By default one pixel is used to draw a single
module. This may make the code to small to be read efficiently.
Increasing the scale will make the code larger. This method will accept
fractional scales (e.g. 2.5).
:param module_color: Color of the QR code (default: ``#000`` (black))
:param background: Optional background color.
(default: ``None`` (no background))
:param quiet_zone: Border around the QR code (also known as quiet zone)
(default: ``4``). Set to zero (``0``) if the code shouldn't
have a border.
:param xmldecl: Inidcates if the XML declaration header should be written
(default: ``True``)
:param svgns: Indicates if the SVG namespace should be written
(default: ``True``)
:param title: Optional title of the generated SVG document.
:param svgclass: The CSS class of the SVG document
(if set to ``None``, the SVG element won't have a class).
:param lineclass: The CSS class of the path element
(if set to ``None``, the path won't have a class).
:param omithw: Indicates if width and height attributes should be
omitted (default: ``False``). If these attributes are omitted,
a ``viewBox`` attribute will be added to the document.
:param debug: Inidicates if errors in the QR code should be added to the
output (default: ``False``).
"""
from functools import partial
from xml.sax.saxutils import quoteattr
def write_unicode(write_meth, unicode_str):
"""\
Encodes the provided string into UTF-8 and writes the result using
the `write_meth`.
"""
write_meth(unicode_str.encode('utf-8'))
def line(x, y, length, relative):
"""Returns coordinates to draw a line with the provided length.
"""
return '{0}{1} {2}h{3}'.format(('m' if relative else 'M'), x, y, length)
def errline(col_number, row_number):
"""Returns the coordinates to draw an error bit.
"""
# Debug path uses always absolute coordinates
# .5 == stroke / 2
return line(col_number + quiet_zone, row_number + quiet_zone + .5, 1, False)
f, autoclose = _get_writable(file, 'wb')
write = partial(write_unicode, f.write)
write_bytes = f.write
# Write the document header
if xmldecl:
write_bytes(b'<?xml version="1.0" encoding="UTF-8"?>\n')
write_bytes(b'<svg')
if svgns:
write_bytes(b' xmlns="http://www.w3.org/2000/svg"')
size = tables.version_size[version] * scale + (2 * quiet_zone * scale)
if not omithw:
write(' height="{0}" width="{0}"'.format(size))
else:
write(' viewBox="0 0 {0} {0}"'.format(size))
if svgclass is not None:
write_bytes(b' class=')
write(quoteattr(svgclass))
write_bytes(b'>')
if title is not None:
write('<title>{0}</title>'.format(title))
# Draw a background rectangle if necessary
if background is not None:
write('<path fill="{1}" d="M0 0h{0}v{0}h-{0}z"/>'
.format(size, background))
write_bytes(b'<path')
if scale != 1:
write(' transform="scale({0})"'.format(scale))
if module_color is not None:
write_bytes(b' stroke=')
write(quoteattr(module_color))
if lineclass is not None:
write_bytes(b' class=')
write(quoteattr(lineclass))
write_bytes(b' d="')
# Used to keep track of unknown/error coordinates.
debug_path = ''
# Current pen pointer position
x, y = -quiet_zone, quiet_zone - .5 # .5 == stroke-width / 2
wrote_bit = False
# Loop through each row of the code
for rnumber, row in enumerate(code):
start_column = 0 # Reset the starting column number
coord = '' # Reset row coordinates
y += 1 # Pen position on y-axis
length = 0 # Reset line length
# Examine every bit in the row
for colnumber, bit in enumerate(row):
if bit == 1:
length += 1
else:
if length:
x = start_column - x
coord += line(x, y, length, relative=wrote_bit)
x = start_column + length
y = 0 # y-axis won't change unless the row changes
length = 0
wrote_bit = True
start_column = colnumber + 1
if debug and bit != 0:
debug_path += errline(colnumber, rnumber)
if length:
x = start_column - x
coord += line(x, y, length, relative=wrote_bit)
x = start_column + length
wrote_bit = True
write(coord)
# Close path
write_bytes(b'"/>')
if debug and debug_path:
write_bytes(b'<path')
if scale != 1:
write(' transform="scale({0})"'.format(scale))
write(' class="pyqrerr" stroke="red" d="{0}"/>'.format(debug_path))
# Close document
write_bytes(b'</svg>\n')
if autoclose:
f.close() | [
"def",
"_svg",
"(",
"code",
",",
"version",
",",
"file",
",",
"scale",
"=",
"1",
",",
"module_color",
"=",
"'#000'",
",",
"background",
"=",
"None",
",",
"quiet_zone",
"=",
"4",
",",
"xmldecl",
"=",
"True",
",",
"svgns",
"=",
"True",
",",
"title",
... | This function writes the QR code out as an SVG document. The
code is drawn by drawing only the modules corresponding to a 1. They
are drawn using a line, such that contiguous modules in a row
are drawn with a single line. The file parameter is used to
specify where to write the document to. It can either be a writable (binary)
stream or a file path. The scale parameter is sets how large to draw
a single module. By default one pixel is used to draw a single
module. This may make the code to small to be read efficiently.
Increasing the scale will make the code larger. This method will accept
fractional scales (e.g. 2.5).
:param module_color: Color of the QR code (default: ``#000`` (black))
:param background: Optional background color.
(default: ``None`` (no background))
:param quiet_zone: Border around the QR code (also known as quiet zone)
(default: ``4``). Set to zero (``0``) if the code shouldn't
have a border.
:param xmldecl: Inidcates if the XML declaration header should be written
(default: ``True``)
:param svgns: Indicates if the SVG namespace should be written
(default: ``True``)
:param title: Optional title of the generated SVG document.
:param svgclass: The CSS class of the SVG document
(if set to ``None``, the SVG element won't have a class).
:param lineclass: The CSS class of the path element
(if set to ``None``, the path won't have a class).
:param omithw: Indicates if width and height attributes should be
omitted (default: ``False``). If these attributes are omitted,
a ``viewBox`` attribute will be added to the document.
:param debug: Inidicates if errors in the QR code should be added to the
output (default: ``False``). | [
"This",
"function",
"writes",
"the",
"QR",
"code",
"out",
"as",
"an",
"SVG",
"document",
".",
"The",
"code",
"is",
"drawn",
"by",
"drawing",
"only",
"the",
"modules",
"corresponding",
"to",
"a",
"1",
".",
"They",
"are",
"drawn",
"using",
"a",
"line",
"... | train | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/builder.py#L1107-L1241 |
mnooner256/pyqrcode | pyqrcode/builder.py | _png | def _png(code, version, file, scale=1, module_color=(0, 0, 0, 255),
background=(255, 255, 255, 255), quiet_zone=4, debug=False):
"""See: pyqrcode.QRCode.png()
This function was abstracted away from QRCode to allow for the output of
QR codes during the build process, i.e. for debugging. It works
just the same except you must specify the code's version. This is needed
to calculate the PNG's size.
This method will write the given file out as a PNG file. Note, it
depends on the PyPNG module to do this.
:param module_color: Color of the QR code (default: ``(0, 0, 0, 255)`` (black))
:param background: Optional background color. If set to ``None`` the PNG
will have a transparent background.
(default: ``(255, 255, 255, 255)`` (white))
:param quiet_zone: Border around the QR code (also known as quiet zone)
(default: ``4``). Set to zero (``0``) if the code shouldn't
have a border.
:param debug: Inidicates if errors in the QR code should be added (as red
modules) to the output (default: ``False``).
"""
import png
# Coerce scale parameter into an integer
try:
scale = int(scale)
except ValueError:
raise ValueError('The scale parameter must be an integer')
def scale_code(size):
"""To perform the scaling we need to inflate the number of bits.
The PNG library expects all of the bits when it draws the PNG.
Effectively, we double, tripple, etc. the number of columns and
the number of rows.
"""
# This is one row's worth of each possible module
# PNG's use 0 for black and 1 for white, this is the
# reverse of the QR standard
black = [0] * scale
white = [1] * scale
# Tuple to lookup colors
# The 3rd color is the module_color unless "debug" is enabled
colors = (white, black, (([2] * scale) if debug else black))
# Whitespace added on the left and right side
border_module = white * quiet_zone
# This is the row to show up at the top and bottom border
border_row = [[1] * size] * scale * quiet_zone
# This will hold the final PNG's bits
bits = []
# Add scale rows before the code as a border,
# as per the standard
bits.extend(border_row)
# Add each row of the to the final PNG bits
for row in code:
tmp_row = []
# Add one all white module to the beginning
# to create the vertical border
tmp_row.extend(border_module)
# Go through each bit in the code
for bit in row:
# Use the standard color or the "debug" color
tmp_row.extend(colors[(bit if bit in (0, 1) else 2)])
# Add one all white module to the end
# to create the vertical border
tmp_row.extend(border_module)
# Copy each row scale times
for n in range(scale):
bits.append(tmp_row)
# Add the bottom border
bits.extend(border_row)
return bits
def png_pallete_color(color):
"""This creates a palette color from a list or tuple. The list or
tuple must be of length 3 (for rgb) or 4 (for rgba). The values
must be between 0 and 255. Note rgb colors will be given an added
alpha component set to 255.
The pallete color is represented as a list, this is what is returned.
"""
if color is None:
return ()
if not isinstance(color, (tuple, list)):
r, g, b = _hex_to_rgb(color)
return r, g, b, 255
rgba = []
if not (3 <= len(color) <= 4):
raise ValueError('Colors must be a list or tuple of length '
' 3 or 4. You passed in "{0}".'.format(color))
for c in color:
c = int(c)
if 0 <= c <= 255:
rgba.append(int(c))
else:
raise ValueError('Color components must be between 0 and 255')
# Make all colors have an alpha channel
if len(rgba) == 3:
rgba.append(255)
return tuple(rgba)
if module_color is None:
raise ValueError('The module_color must not be None')
bitdepth = 1
# foreground aka module color
fg_col = png_pallete_color(module_color)
transparent = background is None
# If background color is set to None, the inverse color of the
# foreground color is calculated
bg_col = png_pallete_color(background) if background is not None else tuple([255 - c for c in fg_col])
# Assume greyscale if module color is black and background color is white
greyscale = fg_col[:3] == (0, 0, 0) and (not debug and transparent or bg_col == (255, 255, 255, 255))
transparent_color = 1 if transparent and greyscale else None
palette = [fg_col, bg_col] if not greyscale else None
if debug:
# Add "red" as color for error modules
palette.append((255, 0, 0, 255))
bitdepth = 2
# The size of the PNG
size = _get_png_size(version, scale, quiet_zone)
# We need to increase the size of the code to match up to the
# scale parameter.
code_rows = scale_code(size)
# Write out the PNG
f, autoclose = _get_writable(file, 'wb')
w = png.Writer(width=size, height=size, greyscale=greyscale,
transparent=transparent_color, palette=palette,
bitdepth=bitdepth)
try:
w.write(f, code_rows)
finally:
if autoclose:
f.close() | python | def _png(code, version, file, scale=1, module_color=(0, 0, 0, 255),
background=(255, 255, 255, 255), quiet_zone=4, debug=False):
"""See: pyqrcode.QRCode.png()
This function was abstracted away from QRCode to allow for the output of
QR codes during the build process, i.e. for debugging. It works
just the same except you must specify the code's version. This is needed
to calculate the PNG's size.
This method will write the given file out as a PNG file. Note, it
depends on the PyPNG module to do this.
:param module_color: Color of the QR code (default: ``(0, 0, 0, 255)`` (black))
:param background: Optional background color. If set to ``None`` the PNG
will have a transparent background.
(default: ``(255, 255, 255, 255)`` (white))
:param quiet_zone: Border around the QR code (also known as quiet zone)
(default: ``4``). Set to zero (``0``) if the code shouldn't
have a border.
:param debug: Inidicates if errors in the QR code should be added (as red
modules) to the output (default: ``False``).
"""
import png
# Coerce scale parameter into an integer
try:
scale = int(scale)
except ValueError:
raise ValueError('The scale parameter must be an integer')
def scale_code(size):
"""To perform the scaling we need to inflate the number of bits.
The PNG library expects all of the bits when it draws the PNG.
Effectively, we double, tripple, etc. the number of columns and
the number of rows.
"""
# This is one row's worth of each possible module
# PNG's use 0 for black and 1 for white, this is the
# reverse of the QR standard
black = [0] * scale
white = [1] * scale
# Tuple to lookup colors
# The 3rd color is the module_color unless "debug" is enabled
colors = (white, black, (([2] * scale) if debug else black))
# Whitespace added on the left and right side
border_module = white * quiet_zone
# This is the row to show up at the top and bottom border
border_row = [[1] * size] * scale * quiet_zone
# This will hold the final PNG's bits
bits = []
# Add scale rows before the code as a border,
# as per the standard
bits.extend(border_row)
# Add each row of the to the final PNG bits
for row in code:
tmp_row = []
# Add one all white module to the beginning
# to create the vertical border
tmp_row.extend(border_module)
# Go through each bit in the code
for bit in row:
# Use the standard color or the "debug" color
tmp_row.extend(colors[(bit if bit in (0, 1) else 2)])
# Add one all white module to the end
# to create the vertical border
tmp_row.extend(border_module)
# Copy each row scale times
for n in range(scale):
bits.append(tmp_row)
# Add the bottom border
bits.extend(border_row)
return bits
def png_pallete_color(color):
"""This creates a palette color from a list or tuple. The list or
tuple must be of length 3 (for rgb) or 4 (for rgba). The values
must be between 0 and 255. Note rgb colors will be given an added
alpha component set to 255.
The pallete color is represented as a list, this is what is returned.
"""
if color is None:
return ()
if not isinstance(color, (tuple, list)):
r, g, b = _hex_to_rgb(color)
return r, g, b, 255
rgba = []
if not (3 <= len(color) <= 4):
raise ValueError('Colors must be a list or tuple of length '
' 3 or 4. You passed in "{0}".'.format(color))
for c in color:
c = int(c)
if 0 <= c <= 255:
rgba.append(int(c))
else:
raise ValueError('Color components must be between 0 and 255')
# Make all colors have an alpha channel
if len(rgba) == 3:
rgba.append(255)
return tuple(rgba)
if module_color is None:
raise ValueError('The module_color must not be None')
bitdepth = 1
# foreground aka module color
fg_col = png_pallete_color(module_color)
transparent = background is None
# If background color is set to None, the inverse color of the
# foreground color is calculated
bg_col = png_pallete_color(background) if background is not None else tuple([255 - c for c in fg_col])
# Assume greyscale if module color is black and background color is white
greyscale = fg_col[:3] == (0, 0, 0) and (not debug and transparent or bg_col == (255, 255, 255, 255))
transparent_color = 1 if transparent and greyscale else None
palette = [fg_col, bg_col] if not greyscale else None
if debug:
# Add "red" as color for error modules
palette.append((255, 0, 0, 255))
bitdepth = 2
# The size of the PNG
size = _get_png_size(version, scale, quiet_zone)
# We need to increase the size of the code to match up to the
# scale parameter.
code_rows = scale_code(size)
# Write out the PNG
f, autoclose = _get_writable(file, 'wb')
w = png.Writer(width=size, height=size, greyscale=greyscale,
transparent=transparent_color, palette=palette,
bitdepth=bitdepth)
try:
w.write(f, code_rows)
finally:
if autoclose:
f.close() | [
"def",
"_png",
"(",
"code",
",",
"version",
",",
"file",
",",
"scale",
"=",
"1",
",",
"module_color",
"=",
"(",
"0",
",",
"0",
",",
"0",
",",
"255",
")",
",",
"background",
"=",
"(",
"255",
",",
"255",
",",
"255",
",",
"255",
")",
",",
"quiet... | See: pyqrcode.QRCode.png()
This function was abstracted away from QRCode to allow for the output of
QR codes during the build process, i.e. for debugging. It works
just the same except you must specify the code's version. This is needed
to calculate the PNG's size.
This method will write the given file out as a PNG file. Note, it
depends on the PyPNG module to do this.
:param module_color: Color of the QR code (default: ``(0, 0, 0, 255)`` (black))
:param background: Optional background color. If set to ``None`` the PNG
will have a transparent background.
(default: ``(255, 255, 255, 255)`` (white))
:param quiet_zone: Border around the QR code (also known as quiet zone)
(default: ``4``). Set to zero (``0``) if the code shouldn't
have a border.
:param debug: Inidicates if errors in the QR code should be added (as red
modules) to the output (default: ``False``). | [
"See",
":",
"pyqrcode",
".",
"QRCode",
".",
"png",
"()"
] | train | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/builder.py#L1244-L1391 |
mnooner256/pyqrcode | pyqrcode/builder.py | _eps | def _eps(code, version, file_or_path, scale=1, module_color=(0, 0, 0),
background=None, quiet_zone=4):
"""This function writes the QR code out as an EPS document. The
code is drawn by drawing only the modules corresponding to a 1. They
are drawn using a line, such that contiguous modules in a row
are drawn with a single line. The file parameter is used to
specify where to write the document to. It can either be a writable (text)
stream or a file path. The scale parameter is sets how large to draw
a single module. By default one point (1/72 inch) is used to draw a single
module. This may make the code to small to be read efficiently.
Increasing the scale will make the code larger. This function will accept
fractional scales (e.g. 2.5).
:param module_color: Color of the QR code (default: ``(0, 0, 0)`` (black))
The color can be specified as triple of floats (range: 0 .. 1) or
triple of integers (range: 0 .. 255) or as hexadecimal value (i.e.
``#36c`` or ``#33B200``).
:param background: Optional background color.
(default: ``None`` (no background)). See `module_color` for the
supported values.
:param quiet_zone: Border around the QR code (also known as quiet zone)
(default: ``4``). Set to zero (``0``) if the code shouldn't
have a border.
"""
from functools import partial
import time
import textwrap
def write_line(writemeth, content):
"""\
Writes `content` and ``LF``.
"""
# Postscript: Max. 255 characters per line
for line in textwrap.wrap(content, 255):
writemeth(line)
writemeth('\n')
def line(offset, length):
"""\
Returns coordinates to draw a line with the provided length.
"""
res = ''
if offset > 0:
res = ' {0} 0 m'.format(offset)
res += ' {0} 0 l'.format(length)
return res
def rgb_to_floats(color):
"""\
Converts the provided color into an acceptable format for Postscript's
``setrgbcolor``
"""
def to_float(clr):
if isinstance(clr, float):
if not 0.0 <= clr <= 1.0:
raise ValueError('Invalid color "{0}". Not in range 0 .. 1'
.format(clr))
return clr
if not 0 <= clr <= 255:
raise ValueError('Invalid color "{0}". Not in range 0 .. 255'
.format(clr))
return 1/255.0 * clr if clr != 1 else clr
if not isinstance(color, (tuple, list)):
color = _hex_to_rgb(color)
return tuple([to_float(i) for i in color])
f, autoclose = _get_writable(file_or_path, 'w')
writeline = partial(write_line, f.write)
size = tables.version_size[version] * scale + (2 * quiet_zone * scale)
# Write common header
writeline('%!PS-Adobe-3.0 EPSF-3.0')
writeline('%%Creator: PyQRCode <https://pypi.python.org/pypi/PyQRCode/>')
writeline('%%CreationDate: {0}'.format(time.strftime("%Y-%m-%d %H:%M:%S")))
writeline('%%DocumentData: Clean7Bit')
writeline('%%BoundingBox: 0 0 {0} {0}'.format(size))
# Write the shortcuts
writeline('/M { moveto } bind def')
writeline('/m { rmoveto } bind def')
writeline('/l { rlineto } bind def')
mod_color = module_color if module_color == (0, 0, 0) else rgb_to_floats(module_color)
if background is not None:
writeline('{0:f} {1:f} {2:f} setrgbcolor clippath fill'
.format(*rgb_to_floats(background)))
if mod_color == (0, 0, 0):
# Reset RGB color back to black iff module color is black
# In case module color != black set the module RGB color later
writeline('0 0 0 setrgbcolor')
if mod_color != (0, 0, 0):
writeline('{0:f} {1:f} {2:f} setrgbcolor'.format(*mod_color))
if scale != 1:
writeline('{0} {0} scale'.format(scale))
writeline('newpath')
# Current pen position y-axis
# Note: 0, 0 = lower left corner in PS coordinate system
y = tables.version_size[version] + quiet_zone + .5 # .5 = linewidth / 2
last_bit = 1
# Loop through each row of the code
for row in code:
offset = 0 # Set x-offset of the pen
length = 0
y -= 1 # Move pen along y-axis
coord = '{0} {1} M'.format(quiet_zone, y) # Move pen to initial pos
for bit in row:
if bit != last_bit:
if length:
coord += line(offset, length)
offset = 0
length = 0
last_bit = bit
if bit == 1:
length += 1
else:
offset += 1
if length:
coord += line(offset, length)
writeline(coord)
writeline('stroke')
writeline('%%EOF')
if autoclose:
f.close() | python | def _eps(code, version, file_or_path, scale=1, module_color=(0, 0, 0),
background=None, quiet_zone=4):
"""This function writes the QR code out as an EPS document. The
code is drawn by drawing only the modules corresponding to a 1. They
are drawn using a line, such that contiguous modules in a row
are drawn with a single line. The file parameter is used to
specify where to write the document to. It can either be a writable (text)
stream or a file path. The scale parameter is sets how large to draw
a single module. By default one point (1/72 inch) is used to draw a single
module. This may make the code to small to be read efficiently.
Increasing the scale will make the code larger. This function will accept
fractional scales (e.g. 2.5).
:param module_color: Color of the QR code (default: ``(0, 0, 0)`` (black))
The color can be specified as triple of floats (range: 0 .. 1) or
triple of integers (range: 0 .. 255) or as hexadecimal value (i.e.
``#36c`` or ``#33B200``).
:param background: Optional background color.
(default: ``None`` (no background)). See `module_color` for the
supported values.
:param quiet_zone: Border around the QR code (also known as quiet zone)
(default: ``4``). Set to zero (``0``) if the code shouldn't
have a border.
"""
from functools import partial
import time
import textwrap
def write_line(writemeth, content):
"""\
Writes `content` and ``LF``.
"""
# Postscript: Max. 255 characters per line
for line in textwrap.wrap(content, 255):
writemeth(line)
writemeth('\n')
def line(offset, length):
"""\
Returns coordinates to draw a line with the provided length.
"""
res = ''
if offset > 0:
res = ' {0} 0 m'.format(offset)
res += ' {0} 0 l'.format(length)
return res
def rgb_to_floats(color):
"""\
Converts the provided color into an acceptable format for Postscript's
``setrgbcolor``
"""
def to_float(clr):
if isinstance(clr, float):
if not 0.0 <= clr <= 1.0:
raise ValueError('Invalid color "{0}". Not in range 0 .. 1'
.format(clr))
return clr
if not 0 <= clr <= 255:
raise ValueError('Invalid color "{0}". Not in range 0 .. 255'
.format(clr))
return 1/255.0 * clr if clr != 1 else clr
if not isinstance(color, (tuple, list)):
color = _hex_to_rgb(color)
return tuple([to_float(i) for i in color])
f, autoclose = _get_writable(file_or_path, 'w')
writeline = partial(write_line, f.write)
size = tables.version_size[version] * scale + (2 * quiet_zone * scale)
# Write common header
writeline('%!PS-Adobe-3.0 EPSF-3.0')
writeline('%%Creator: PyQRCode <https://pypi.python.org/pypi/PyQRCode/>')
writeline('%%CreationDate: {0}'.format(time.strftime("%Y-%m-%d %H:%M:%S")))
writeline('%%DocumentData: Clean7Bit')
writeline('%%BoundingBox: 0 0 {0} {0}'.format(size))
# Write the shortcuts
writeline('/M { moveto } bind def')
writeline('/m { rmoveto } bind def')
writeline('/l { rlineto } bind def')
mod_color = module_color if module_color == (0, 0, 0) else rgb_to_floats(module_color)
if background is not None:
writeline('{0:f} {1:f} {2:f} setrgbcolor clippath fill'
.format(*rgb_to_floats(background)))
if mod_color == (0, 0, 0):
# Reset RGB color back to black iff module color is black
# In case module color != black set the module RGB color later
writeline('0 0 0 setrgbcolor')
if mod_color != (0, 0, 0):
writeline('{0:f} {1:f} {2:f} setrgbcolor'.format(*mod_color))
if scale != 1:
writeline('{0} {0} scale'.format(scale))
writeline('newpath')
# Current pen position y-axis
# Note: 0, 0 = lower left corner in PS coordinate system
y = tables.version_size[version] + quiet_zone + .5 # .5 = linewidth / 2
last_bit = 1
# Loop through each row of the code
for row in code:
offset = 0 # Set x-offset of the pen
length = 0
y -= 1 # Move pen along y-axis
coord = '{0} {1} M'.format(quiet_zone, y) # Move pen to initial pos
for bit in row:
if bit != last_bit:
if length:
coord += line(offset, length)
offset = 0
length = 0
last_bit = bit
if bit == 1:
length += 1
else:
offset += 1
if length:
coord += line(offset, length)
writeline(coord)
writeline('stroke')
writeline('%%EOF')
if autoclose:
f.close() | [
"def",
"_eps",
"(",
"code",
",",
"version",
",",
"file_or_path",
",",
"scale",
"=",
"1",
",",
"module_color",
"=",
"(",
"0",
",",
"0",
",",
"0",
")",
",",
"background",
"=",
"None",
",",
"quiet_zone",
"=",
"4",
")",
":",
"from",
"functools",
"impor... | This function writes the QR code out as an EPS document. The
code is drawn by drawing only the modules corresponding to a 1. They
are drawn using a line, such that contiguous modules in a row
are drawn with a single line. The file parameter is used to
specify where to write the document to. It can either be a writable (text)
stream or a file path. The scale parameter is sets how large to draw
a single module. By default one point (1/72 inch) is used to draw a single
module. This may make the code to small to be read efficiently.
Increasing the scale will make the code larger. This function will accept
fractional scales (e.g. 2.5).
:param module_color: Color of the QR code (default: ``(0, 0, 0)`` (black))
The color can be specified as triple of floats (range: 0 .. 1) or
triple of integers (range: 0 .. 255) or as hexadecimal value (i.e.
``#36c`` or ``#33B200``).
:param background: Optional background color.
(default: ``None`` (no background)). See `module_color` for the
supported values.
:param quiet_zone: Border around the QR code (also known as quiet zone)
(default: ``4``). Set to zero (``0``) if the code shouldn't
have a border. | [
"This",
"function",
"writes",
"the",
"QR",
"code",
"out",
"as",
"an",
"EPS",
"document",
".",
"The",
"code",
"is",
"drawn",
"by",
"drawing",
"only",
"the",
"modules",
"corresponding",
"to",
"a",
"1",
".",
"They",
"are",
"drawn",
"using",
"a",
"line",
"... | train | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/builder.py#L1394-L1514 |
mnooner256/pyqrcode | pyqrcode/builder.py | _hex_to_rgb | def _hex_to_rgb(color):
"""\
Helper function to convert a color provided in hexadecimal format
as RGB triple.
"""
if color[0] == '#':
color = color[1:]
if len(color) == 3:
color = color[0] * 2 + color[1] * 2 + color[2] * 2
if len(color) != 6:
raise ValueError('Input #{0} is not in #RRGGBB format'.format(color))
return [int(n, 16) for n in (color[:2], color[2:4], color[4:])] | python | def _hex_to_rgb(color):
"""\
Helper function to convert a color provided in hexadecimal format
as RGB triple.
"""
if color[0] == '#':
color = color[1:]
if len(color) == 3:
color = color[0] * 2 + color[1] * 2 + color[2] * 2
if len(color) != 6:
raise ValueError('Input #{0} is not in #RRGGBB format'.format(color))
return [int(n, 16) for n in (color[:2], color[2:4], color[4:])] | [
"def",
"_hex_to_rgb",
"(",
"color",
")",
":",
"if",
"color",
"[",
"0",
"]",
"==",
"'#'",
":",
"color",
"=",
"color",
"[",
"1",
":",
"]",
"if",
"len",
"(",
"color",
")",
"==",
"3",
":",
"color",
"=",
"color",
"[",
"0",
"]",
"*",
"2",
"+",
"c... | \
Helper function to convert a color provided in hexadecimal format
as RGB triple. | [
"\\",
"Helper",
"function",
"to",
"convert",
"a",
"color",
"provided",
"in",
"hexadecimal",
"format",
"as",
"RGB",
"triple",
"."
] | train | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/builder.py#L1517-L1528 |
mnooner256/pyqrcode | pyqrcode/builder.py | QRCodeBuilder.grouper | def grouper(self, n, iterable, fillvalue=None):
"""This generator yields a set of tuples, where the
iterable is broken into n sized chunks. If the
iterable is not evenly sized then fillvalue will
be appended to the last tuple to make up the difference.
This function is copied from the standard docs on
itertools.
"""
args = [iter(iterable)] * n
if hasattr(itertools, 'zip_longest'):
return itertools.zip_longest(*args, fillvalue=fillvalue)
return itertools.izip_longest(*args, fillvalue=fillvalue) | python | def grouper(self, n, iterable, fillvalue=None):
"""This generator yields a set of tuples, where the
iterable is broken into n sized chunks. If the
iterable is not evenly sized then fillvalue will
be appended to the last tuple to make up the difference.
This function is copied from the standard docs on
itertools.
"""
args = [iter(iterable)] * n
if hasattr(itertools, 'zip_longest'):
return itertools.zip_longest(*args, fillvalue=fillvalue)
return itertools.izip_longest(*args, fillvalue=fillvalue) | [
"def",
"grouper",
"(",
"self",
",",
"n",
",",
"iterable",
",",
"fillvalue",
"=",
"None",
")",
":",
"args",
"=",
"[",
"iter",
"(",
"iterable",
")",
"]",
"*",
"n",
"if",
"hasattr",
"(",
"itertools",
",",
"'zip_longest'",
")",
":",
"return",
"itertools"... | This generator yields a set of tuples, where the
iterable is broken into n sized chunks. If the
iterable is not evenly sized then fillvalue will
be appended to the last tuple to make up the difference.
This function is copied from the standard docs on
itertools. | [
"This",
"generator",
"yields",
"a",
"set",
"of",
"tuples",
"where",
"the",
"iterable",
"is",
"broken",
"into",
"n",
"sized",
"chunks",
".",
"If",
"the",
"iterable",
"is",
"not",
"evenly",
"sized",
"then",
"fillvalue",
"will",
"be",
"appended",
"to",
"the",... | train | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/builder.py#L98-L110 |
mnooner256/pyqrcode | pyqrcode/builder.py | QRCodeBuilder.get_data_length | def get_data_length(self):
"""QR codes contain a "data length" field. This method creates this
field. A binary string representing the appropriate length is
returned.
"""
#The "data length" field varies by the type of code and its mode.
#discover how long the "data length" field should be.
if 1 <= self.version <= 9:
max_version = 9
elif 10 <= self.version <= 26:
max_version = 26
elif 27 <= self.version <= 40:
max_version = 40
data_length = tables.data_length_field[max_version][self.mode]
if self.mode != tables.modes['kanji']:
length_string = self.binary_string(len(self.data), data_length)
else:
length_string = self.binary_string(len(self.data) / 2, data_length)
if len(length_string) > data_length:
raise ValueError('The supplied data will not fit '
'within this version of a QRCode.')
return length_string | python | def get_data_length(self):
"""QR codes contain a "data length" field. This method creates this
field. A binary string representing the appropriate length is
returned.
"""
#The "data length" field varies by the type of code and its mode.
#discover how long the "data length" field should be.
if 1 <= self.version <= 9:
max_version = 9
elif 10 <= self.version <= 26:
max_version = 26
elif 27 <= self.version <= 40:
max_version = 40
data_length = tables.data_length_field[max_version][self.mode]
if self.mode != tables.modes['kanji']:
length_string = self.binary_string(len(self.data), data_length)
else:
length_string = self.binary_string(len(self.data) / 2, data_length)
if len(length_string) > data_length:
raise ValueError('The supplied data will not fit '
'within this version of a QRCode.')
return length_string | [
"def",
"get_data_length",
"(",
"self",
")",
":",
"#The \"data length\" field varies by the type of code and its mode.",
"#discover how long the \"data length\" field should be.",
"if",
"1",
"<=",
"self",
".",
"version",
"<=",
"9",
":",
"max_version",
"=",
"9",
"elif",
"10",... | QR codes contain a "data length" field. This method creates this
field. A binary string representing the appropriate length is
returned. | [
"QR",
"codes",
"contain",
"a",
"data",
"length",
"field",
".",
"This",
"method",
"creates",
"this",
"field",
".",
"A",
"binary",
"string",
"representing",
"the",
"appropriate",
"length",
"is",
"returned",
"."
] | train | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/builder.py#L119-L144 |
mnooner256/pyqrcode | pyqrcode/builder.py | QRCodeBuilder.encode | def encode(self):
"""This method encodes the data into a binary string using
the appropriate algorithm specified by the mode.
"""
if self.mode == tables.modes['alphanumeric']:
encoded = self.encode_alphanumeric()
elif self.mode == tables.modes['numeric']:
encoded = self.encode_numeric()
elif self.mode == tables.modes['binary']:
encoded = self.encode_bytes()
elif self.mode == tables.modes['kanji']:
encoded = self.encode_kanji()
return encoded | python | def encode(self):
"""This method encodes the data into a binary string using
the appropriate algorithm specified by the mode.
"""
if self.mode == tables.modes['alphanumeric']:
encoded = self.encode_alphanumeric()
elif self.mode == tables.modes['numeric']:
encoded = self.encode_numeric()
elif self.mode == tables.modes['binary']:
encoded = self.encode_bytes()
elif self.mode == tables.modes['kanji']:
encoded = self.encode_kanji()
return encoded | [
"def",
"encode",
"(",
"self",
")",
":",
"if",
"self",
".",
"mode",
"==",
"tables",
".",
"modes",
"[",
"'alphanumeric'",
"]",
":",
"encoded",
"=",
"self",
".",
"encode_alphanumeric",
"(",
")",
"elif",
"self",
".",
"mode",
"==",
"tables",
".",
"modes",
... | This method encodes the data into a binary string using
the appropriate algorithm specified by the mode. | [
"This",
"method",
"encodes",
"the",
"data",
"into",
"a",
"binary",
"string",
"using",
"the",
"appropriate",
"algorithm",
"specified",
"by",
"the",
"mode",
"."
] | train | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/builder.py#L146-L158 |
mnooner256/pyqrcode | pyqrcode/builder.py | QRCodeBuilder.encode_alphanumeric | def encode_alphanumeric(self):
"""This method encodes the QR code's data if its mode is
alphanumeric. It returns the data encoded as a binary string.
"""
#Convert the string to upper case
self.data = self.data.upper()
#Change the data such that it uses a QR code ascii table
ascii = []
for char in self.data:
if isinstance(char, int):
ascii.append(tables.ascii_codes[chr(char)])
else:
ascii.append(tables.ascii_codes[char])
#Now perform the algorithm that will make the ascii into bit fields
with io.StringIO() as buf:
for (a,b) in self.grouper(2, ascii):
if b is not None:
buf.write(self.binary_string((45*a)+b, 11))
else:
#This occurs when there is an odd number
#of characters in the data
buf.write(self.binary_string(a, 6))
#Return the binary string
return buf.getvalue() | python | def encode_alphanumeric(self):
"""This method encodes the QR code's data if its mode is
alphanumeric. It returns the data encoded as a binary string.
"""
#Convert the string to upper case
self.data = self.data.upper()
#Change the data such that it uses a QR code ascii table
ascii = []
for char in self.data:
if isinstance(char, int):
ascii.append(tables.ascii_codes[chr(char)])
else:
ascii.append(tables.ascii_codes[char])
#Now perform the algorithm that will make the ascii into bit fields
with io.StringIO() as buf:
for (a,b) in self.grouper(2, ascii):
if b is not None:
buf.write(self.binary_string((45*a)+b, 11))
else:
#This occurs when there is an odd number
#of characters in the data
buf.write(self.binary_string(a, 6))
#Return the binary string
return buf.getvalue() | [
"def",
"encode_alphanumeric",
"(",
"self",
")",
":",
"#Convert the string to upper case",
"self",
".",
"data",
"=",
"self",
".",
"data",
".",
"upper",
"(",
")",
"#Change the data such that it uses a QR code ascii table",
"ascii",
"=",
"[",
"]",
"for",
"char",
"in",
... | This method encodes the QR code's data if its mode is
alphanumeric. It returns the data encoded as a binary string. | [
"This",
"method",
"encodes",
"the",
"QR",
"code",
"s",
"data",
"if",
"its",
"mode",
"is",
"alphanumeric",
".",
"It",
"returns",
"the",
"data",
"encoded",
"as",
"a",
"binary",
"string",
"."
] | train | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/builder.py#L160-L186 |
mnooner256/pyqrcode | pyqrcode/builder.py | QRCodeBuilder.encode_numeric | def encode_numeric(self):
"""This method encodes the QR code's data if its mode is
numeric. It returns the data encoded as a binary string.
"""
with io.StringIO() as buf:
#Break the number into groups of three digits
for triplet in self.grouper(3, self.data):
number = ''
for digit in triplet:
if isinstance(digit, int):
digit = chr(digit)
#Only build the string if digit is not None
if digit:
number = ''.join([number, digit])
else:
break
#If the number is one digits, make a 4 bit field
if len(number) == 1:
bin = self.binary_string(number, 4)
#If the number is two digits, make a 7 bit field
elif len(number) == 2:
bin = self.binary_string(number, 7)
#Three digit numbers use a 10 bit field
else:
bin = self.binary_string(number, 10)
buf.write(bin)
return buf.getvalue() | python | def encode_numeric(self):
"""This method encodes the QR code's data if its mode is
numeric. It returns the data encoded as a binary string.
"""
with io.StringIO() as buf:
#Break the number into groups of three digits
for triplet in self.grouper(3, self.data):
number = ''
for digit in triplet:
if isinstance(digit, int):
digit = chr(digit)
#Only build the string if digit is not None
if digit:
number = ''.join([number, digit])
else:
break
#If the number is one digits, make a 4 bit field
if len(number) == 1:
bin = self.binary_string(number, 4)
#If the number is two digits, make a 7 bit field
elif len(number) == 2:
bin = self.binary_string(number, 7)
#Three digit numbers use a 10 bit field
else:
bin = self.binary_string(number, 10)
buf.write(bin)
return buf.getvalue() | [
"def",
"encode_numeric",
"(",
"self",
")",
":",
"with",
"io",
".",
"StringIO",
"(",
")",
"as",
"buf",
":",
"#Break the number into groups of three digits",
"for",
"triplet",
"in",
"self",
".",
"grouper",
"(",
"3",
",",
"self",
".",
"data",
")",
":",
"numbe... | This method encodes the QR code's data if its mode is
numeric. It returns the data encoded as a binary string. | [
"This",
"method",
"encodes",
"the",
"QR",
"code",
"s",
"data",
"if",
"its",
"mode",
"is",
"numeric",
".",
"It",
"returns",
"the",
"data",
"encoded",
"as",
"a",
"binary",
"string",
"."
] | train | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/builder.py#L188-L219 |
mnooner256/pyqrcode | pyqrcode/builder.py | QRCodeBuilder.encode_bytes | def encode_bytes(self):
"""This method encodes the QR code's data if its mode is
8 bit mode. It returns the data encoded as a binary string.
"""
with io.StringIO() as buf:
for char in self.data:
if not isinstance(char, int):
buf.write('{{0:0{0}b}}'.format(8).format(ord(char)))
else:
buf.write('{{0:0{0}b}}'.format(8).format(char))
return buf.getvalue() | python | def encode_bytes(self):
"""This method encodes the QR code's data if its mode is
8 bit mode. It returns the data encoded as a binary string.
"""
with io.StringIO() as buf:
for char in self.data:
if not isinstance(char, int):
buf.write('{{0:0{0}b}}'.format(8).format(ord(char)))
else:
buf.write('{{0:0{0}b}}'.format(8).format(char))
return buf.getvalue() | [
"def",
"encode_bytes",
"(",
"self",
")",
":",
"with",
"io",
".",
"StringIO",
"(",
")",
"as",
"buf",
":",
"for",
"char",
"in",
"self",
".",
"data",
":",
"if",
"not",
"isinstance",
"(",
"char",
",",
"int",
")",
":",
"buf",
".",
"write",
"(",
"'{{0:... | This method encodes the QR code's data if its mode is
8 bit mode. It returns the data encoded as a binary string. | [
"This",
"method",
"encodes",
"the",
"QR",
"code",
"s",
"data",
"if",
"its",
"mode",
"is",
"8",
"bit",
"mode",
".",
"It",
"returns",
"the",
"data",
"encoded",
"as",
"a",
"binary",
"string",
"."
] | train | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/builder.py#L221-L231 |
mnooner256/pyqrcode | pyqrcode/builder.py | QRCodeBuilder.encode_kanji | def encode_kanji(self):
"""This method encodes the QR code's data if its mode is
kanji. It returns the data encoded as a binary string.
"""
def two_bytes(data):
"""Output two byte character code as a single integer."""
def next_byte(b):
"""Make sure that character code is an int. Python 2 and
3 compatibility.
"""
if not isinstance(b, int):
return ord(b)
else:
return b
#Go through the data by looping to every other character
for i in range(0, len(data), 2):
yield (next_byte(data[i]) << 8) | next_byte(data[i+1])
#Force the data into Kanji encoded bytes
if isinstance(self.data, bytes):
data = self.data.decode('shiftjis').encode('shiftjis')
else:
data = self.data.encode('shiftjis')
#Now perform the algorithm that will make the kanji into 13 bit fields
with io.StringIO() as buf:
for asint in two_bytes(data):
#Shift the two byte value as indicated by the standard
if 0x8140 <= asint <= 0x9FFC:
difference = asint - 0x8140
elif 0xE040 <= asint <= 0xEBBF:
difference = asint - 0xC140
#Split the new value into most and least significant bytes
msb = (difference >> 8)
lsb = (difference & 0x00FF)
#Calculate the actual 13 bit binary value
buf.write('{0:013b}'.format((msb * 0xC0) + lsb))
#Return the binary string
return buf.getvalue() | python | def encode_kanji(self):
"""This method encodes the QR code's data if its mode is
kanji. It returns the data encoded as a binary string.
"""
def two_bytes(data):
"""Output two byte character code as a single integer."""
def next_byte(b):
"""Make sure that character code is an int. Python 2 and
3 compatibility.
"""
if not isinstance(b, int):
return ord(b)
else:
return b
#Go through the data by looping to every other character
for i in range(0, len(data), 2):
yield (next_byte(data[i]) << 8) | next_byte(data[i+1])
#Force the data into Kanji encoded bytes
if isinstance(self.data, bytes):
data = self.data.decode('shiftjis').encode('shiftjis')
else:
data = self.data.encode('shiftjis')
#Now perform the algorithm that will make the kanji into 13 bit fields
with io.StringIO() as buf:
for asint in two_bytes(data):
#Shift the two byte value as indicated by the standard
if 0x8140 <= asint <= 0x9FFC:
difference = asint - 0x8140
elif 0xE040 <= asint <= 0xEBBF:
difference = asint - 0xC140
#Split the new value into most and least significant bytes
msb = (difference >> 8)
lsb = (difference & 0x00FF)
#Calculate the actual 13 bit binary value
buf.write('{0:013b}'.format((msb * 0xC0) + lsb))
#Return the binary string
return buf.getvalue() | [
"def",
"encode_kanji",
"(",
"self",
")",
":",
"def",
"two_bytes",
"(",
"data",
")",
":",
"\"\"\"Output two byte character code as a single integer.\"\"\"",
"def",
"next_byte",
"(",
"b",
")",
":",
"\"\"\"Make sure that character code is an int. Python 2 and\n 3 co... | This method encodes the QR code's data if its mode is
kanji. It returns the data encoded as a binary string. | [
"This",
"method",
"encodes",
"the",
"QR",
"code",
"s",
"data",
"if",
"its",
"mode",
"is",
"kanji",
".",
"It",
"returns",
"the",
"data",
"encoded",
"as",
"a",
"binary",
"string",
"."
] | train | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/builder.py#L233-L274 |
mnooner256/pyqrcode | pyqrcode/builder.py | QRCodeBuilder.add_data | def add_data(self):
"""This function properly constructs a QR code's data string. It takes
into account the interleaving pattern required by the standard.
"""
#Encode the data into a QR code
self.buffer.write(self.binary_string(self.mode, 4))
self.buffer.write(self.get_data_length())
self.buffer.write(self.encode())
#Converts the buffer into "code word" integers.
#The online debugger outputs them this way, makes
#for easier comparisons.
#s = self.buffer.getvalue()
#for i in range(0, len(s), 8):
# print(int(s[i:i+8], 2), end=',')
#print()
#Fix for issue #3: https://github.com/mnooner256/pyqrcode/issues/3#
#I was performing the terminate_bits() part in the encoding.
#As per the standard, terminating bits are only supposed to
#be added after the bit stream is complete. I took that to
#mean after the encoding, but actually it is after the entire
#bit stream has been constructed.
bits = self.terminate_bits(self.buffer.getvalue())
if bits is not None:
self.buffer.write(bits)
#delimit_words and add_words can return None
add_bits = self.delimit_words()
if add_bits:
self.buffer.write(add_bits)
fill_bytes = self.add_words()
if fill_bytes:
self.buffer.write(fill_bytes)
#Get a numeric representation of the data
data = [int(''.join(x),2)
for x in self.grouper(8, self.buffer.getvalue())]
#This is the error information for the code
error_info = tables.eccwbi[self.version][self.error]
#This will hold our data blocks
data_blocks = []
#This will hold our error blocks
error_blocks = []
#Some codes have the data sliced into two different sized blocks
#for example, first two 14 word sized blocks, then four 15 word
#sized blocks. This means that slicing size can change over time.
data_block_sizes = [error_info[2]] * error_info[1]
if error_info[3] != 0:
data_block_sizes.extend([error_info[4]] * error_info[3])
#For every block of data, slice the data into the appropriate
#sized block
current_byte = 0
for n_data_blocks in data_block_sizes:
data_blocks.append(data[current_byte:current_byte+n_data_blocks])
current_byte += n_data_blocks
#I am not sure about the test after the "and". This was added to
#fix a bug where after delimit_words padded the bit stream, a zero
#byte ends up being added. After checking around, it seems this extra
#byte is supposed to be chopped off, but I cannot find that in the
#standard! I am adding it to solve the bug, I believe it is correct.
if current_byte < len(data):
raise ValueError('Too much data for this code version.')
#DEBUG CODE!!!!
#Print out the data blocks
#print('Data Blocks:\n{0}'.format(data_blocks))
#Calculate the error blocks
for n, block in enumerate(data_blocks):
error_blocks.append(self.make_error_block(block, n))
#DEBUG CODE!!!!
#Print out the error blocks
#print('Error Blocks:\n{0}'.format(error_blocks))
#Buffer we will write our data blocks into
data_buffer = io.StringIO()
#Add the data blocks
#Write the buffer such that: block 1 byte 1, block 2 byte 1, etc.
largest_block = max(error_info[2], error_info[4])+error_info[0]
for i in range(largest_block):
for block in data_blocks:
if i < len(block):
data_buffer.write(self.binary_string(block[i], 8))
#Add the error code blocks.
#Write the buffer such that: block 1 byte 1, block 2 byte 2, etc.
for i in range(error_info[0]):
for block in error_blocks:
data_buffer.write(self.binary_string(block[i], 8))
self.buffer = data_buffer | python | def add_data(self):
"""This function properly constructs a QR code's data string. It takes
into account the interleaving pattern required by the standard.
"""
#Encode the data into a QR code
self.buffer.write(self.binary_string(self.mode, 4))
self.buffer.write(self.get_data_length())
self.buffer.write(self.encode())
#Converts the buffer into "code word" integers.
#The online debugger outputs them this way, makes
#for easier comparisons.
#s = self.buffer.getvalue()
#for i in range(0, len(s), 8):
# print(int(s[i:i+8], 2), end=',')
#print()
#Fix for issue #3: https://github.com/mnooner256/pyqrcode/issues/3#
#I was performing the terminate_bits() part in the encoding.
#As per the standard, terminating bits are only supposed to
#be added after the bit stream is complete. I took that to
#mean after the encoding, but actually it is after the entire
#bit stream has been constructed.
bits = self.terminate_bits(self.buffer.getvalue())
if bits is not None:
self.buffer.write(bits)
#delimit_words and add_words can return None
add_bits = self.delimit_words()
if add_bits:
self.buffer.write(add_bits)
fill_bytes = self.add_words()
if fill_bytes:
self.buffer.write(fill_bytes)
#Get a numeric representation of the data
data = [int(''.join(x),2)
for x in self.grouper(8, self.buffer.getvalue())]
#This is the error information for the code
error_info = tables.eccwbi[self.version][self.error]
#This will hold our data blocks
data_blocks = []
#This will hold our error blocks
error_blocks = []
#Some codes have the data sliced into two different sized blocks
#for example, first two 14 word sized blocks, then four 15 word
#sized blocks. This means that slicing size can change over time.
data_block_sizes = [error_info[2]] * error_info[1]
if error_info[3] != 0:
data_block_sizes.extend([error_info[4]] * error_info[3])
#For every block of data, slice the data into the appropriate
#sized block
current_byte = 0
for n_data_blocks in data_block_sizes:
data_blocks.append(data[current_byte:current_byte+n_data_blocks])
current_byte += n_data_blocks
#I am not sure about the test after the "and". This was added to
#fix a bug where after delimit_words padded the bit stream, a zero
#byte ends up being added. After checking around, it seems this extra
#byte is supposed to be chopped off, but I cannot find that in the
#standard! I am adding it to solve the bug, I believe it is correct.
if current_byte < len(data):
raise ValueError('Too much data for this code version.')
#DEBUG CODE!!!!
#Print out the data blocks
#print('Data Blocks:\n{0}'.format(data_blocks))
#Calculate the error blocks
for n, block in enumerate(data_blocks):
error_blocks.append(self.make_error_block(block, n))
#DEBUG CODE!!!!
#Print out the error blocks
#print('Error Blocks:\n{0}'.format(error_blocks))
#Buffer we will write our data blocks into
data_buffer = io.StringIO()
#Add the data blocks
#Write the buffer such that: block 1 byte 1, block 2 byte 1, etc.
largest_block = max(error_info[2], error_info[4])+error_info[0]
for i in range(largest_block):
for block in data_blocks:
if i < len(block):
data_buffer.write(self.binary_string(block[i], 8))
#Add the error code blocks.
#Write the buffer such that: block 1 byte 1, block 2 byte 2, etc.
for i in range(error_info[0]):
for block in error_blocks:
data_buffer.write(self.binary_string(block[i], 8))
self.buffer = data_buffer | [
"def",
"add_data",
"(",
"self",
")",
":",
"#Encode the data into a QR code",
"self",
".",
"buffer",
".",
"write",
"(",
"self",
".",
"binary_string",
"(",
"self",
".",
"mode",
",",
"4",
")",
")",
"self",
".",
"buffer",
".",
"write",
"(",
"self",
".",
"g... | This function properly constructs a QR code's data string. It takes
into account the interleaving pattern required by the standard. | [
"This",
"function",
"properly",
"constructs",
"a",
"QR",
"code",
"s",
"data",
"string",
".",
"It",
"takes",
"into",
"account",
"the",
"interleaving",
"pattern",
"required",
"by",
"the",
"standard",
"."
] | train | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/builder.py#L277-L377 |
mnooner256/pyqrcode | pyqrcode/builder.py | QRCodeBuilder.terminate_bits | def terminate_bits(self, payload):
"""This method adds zeros to the end of the encoded data so that the
encoded data is of the correct length. It returns a binary string
containing the bits to be added.
"""
data_capacity = tables.data_capacity[self.version][self.error][0]
if len(payload) > data_capacity:
raise ValueError('The supplied data will not fit '
'within this version of a QR code.')
#We must add up to 4 zeros to make up for any shortfall in the
#length of the data field.
if len(payload) == data_capacity:
return None
elif len(payload) <= data_capacity-4:
bits = self.binary_string(0,4)
else:
#Make up any shortfall need with less than 4 zeros
bits = self.binary_string(0, data_capacity - len(payload))
return bits | python | def terminate_bits(self, payload):
"""This method adds zeros to the end of the encoded data so that the
encoded data is of the correct length. It returns a binary string
containing the bits to be added.
"""
data_capacity = tables.data_capacity[self.version][self.error][0]
if len(payload) > data_capacity:
raise ValueError('The supplied data will not fit '
'within this version of a QR code.')
#We must add up to 4 zeros to make up for any shortfall in the
#length of the data field.
if len(payload) == data_capacity:
return None
elif len(payload) <= data_capacity-4:
bits = self.binary_string(0,4)
else:
#Make up any shortfall need with less than 4 zeros
bits = self.binary_string(0, data_capacity - len(payload))
return bits | [
"def",
"terminate_bits",
"(",
"self",
",",
"payload",
")",
":",
"data_capacity",
"=",
"tables",
".",
"data_capacity",
"[",
"self",
".",
"version",
"]",
"[",
"self",
".",
"error",
"]",
"[",
"0",
"]",
"if",
"len",
"(",
"payload",
")",
">",
"data_capacity... | This method adds zeros to the end of the encoded data so that the
encoded data is of the correct length. It returns a binary string
containing the bits to be added. | [
"This",
"method",
"adds",
"zeros",
"to",
"the",
"end",
"of",
"the",
"encoded",
"data",
"so",
"that",
"the",
"encoded",
"data",
"is",
"of",
"the",
"correct",
"length",
".",
"It",
"returns",
"a",
"binary",
"string",
"containing",
"the",
"bits",
"to",
"be",... | train | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/builder.py#L379-L400 |
mnooner256/pyqrcode | pyqrcode/builder.py | QRCodeBuilder.delimit_words | def delimit_words(self):
"""This method takes the existing encoded binary string
and returns a binary string that will pad it such that
the encoded string contains only full bytes.
"""
bits_short = 8 - (len(self.buffer.getvalue()) % 8)
#The string already falls on an byte boundary do nothing
if bits_short == 0 or bits_short == 8:
return None
else:
return self.binary_string(0, bits_short) | python | def delimit_words(self):
"""This method takes the existing encoded binary string
and returns a binary string that will pad it such that
the encoded string contains only full bytes.
"""
bits_short = 8 - (len(self.buffer.getvalue()) % 8)
#The string already falls on an byte boundary do nothing
if bits_short == 0 or bits_short == 8:
return None
else:
return self.binary_string(0, bits_short) | [
"def",
"delimit_words",
"(",
"self",
")",
":",
"bits_short",
"=",
"8",
"-",
"(",
"len",
"(",
"self",
".",
"buffer",
".",
"getvalue",
"(",
")",
")",
"%",
"8",
")",
"#The string already falls on an byte boundary do nothing",
"if",
"bits_short",
"==",
"0",
"or"... | This method takes the existing encoded binary string
and returns a binary string that will pad it such that
the encoded string contains only full bytes. | [
"This",
"method",
"takes",
"the",
"existing",
"encoded",
"binary",
"string",
"and",
"returns",
"a",
"binary",
"string",
"that",
"will",
"pad",
"it",
"such",
"that",
"the",
"encoded",
"string",
"contains",
"only",
"full",
"bytes",
"."
] | train | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/builder.py#L402-L413 |
mnooner256/pyqrcode | pyqrcode/builder.py | QRCodeBuilder.add_words | def add_words(self):
"""The data block must fill the entire data capacity of the QR code.
If we fall short, then we must add bytes to the end of the encoded
data field. The value of these bytes are specified in the standard.
"""
data_blocks = len(self.buffer.getvalue()) // 8
total_blocks = tables.data_capacity[self.version][self.error][0] // 8
needed_blocks = total_blocks - data_blocks
if needed_blocks == 0:
return None
#This will return item1, item2, item1, item2, etc.
block = itertools.cycle(['11101100', '00010001'])
#Create a string of the needed blocks
return ''.join([next(block) for x in range(needed_blocks)]) | python | def add_words(self):
"""The data block must fill the entire data capacity of the QR code.
If we fall short, then we must add bytes to the end of the encoded
data field. The value of these bytes are specified in the standard.
"""
data_blocks = len(self.buffer.getvalue()) // 8
total_blocks = tables.data_capacity[self.version][self.error][0] // 8
needed_blocks = total_blocks - data_blocks
if needed_blocks == 0:
return None
#This will return item1, item2, item1, item2, etc.
block = itertools.cycle(['11101100', '00010001'])
#Create a string of the needed blocks
return ''.join([next(block) for x in range(needed_blocks)]) | [
"def",
"add_words",
"(",
"self",
")",
":",
"data_blocks",
"=",
"len",
"(",
"self",
".",
"buffer",
".",
"getvalue",
"(",
")",
")",
"//",
"8",
"total_blocks",
"=",
"tables",
".",
"data_capacity",
"[",
"self",
".",
"version",
"]",
"[",
"self",
".",
"err... | The data block must fill the entire data capacity of the QR code.
If we fall short, then we must add bytes to the end of the encoded
data field. The value of these bytes are specified in the standard. | [
"The",
"data",
"block",
"must",
"fill",
"the",
"entire",
"data",
"capacity",
"of",
"the",
"QR",
"code",
".",
"If",
"we",
"fall",
"short",
"then",
"we",
"must",
"add",
"bytes",
"to",
"the",
"end",
"of",
"the",
"encoded",
"data",
"field",
".",
"The",
"... | train | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/builder.py#L415-L432 |
mnooner256/pyqrcode | pyqrcode/builder.py | QRCodeBuilder.make_error_block | def make_error_block(self, block, block_number):
"""This function constructs the error correction block of the
given data block. This is *very complicated* process. To
understand the code you need to read:
* http://www.thonky.com/qr-code-tutorial/part-2-error-correction/
* http://www.matchadesign.com/blog/qr-code-demystified-part-4/
"""
#Get the error information from the standards table
error_info = tables.eccwbi[self.version][self.error]
#This is the number of 8-bit words per block
if block_number < error_info[1]:
code_words_per_block = error_info[2]
else:
code_words_per_block = error_info[4]
#This is the size of the error block
error_block_size = error_info[0]
#Copy the block as the message polynomial coefficients
mp_co = block[:]
#Add the error blocks to the message polynomial
mp_co.extend([0] * (error_block_size))
#Get the generator polynomial
generator = tables.generator_polynomials[error_block_size]
#This will hold the temporary sum of the message coefficient and the
#generator polynomial
gen_result = [0] * len(generator)
#Go through every code word in the block
for i in range(code_words_per_block):
#Get the first coefficient from the message polynomial
coefficient = mp_co.pop(0)
#Skip coefficients that are zero
if coefficient == 0:
continue
else:
#Turn the coefficient into an alpha exponent
alpha_exp = tables.galois_antilog[coefficient]
#Add the alpha to the generator polynomial
for n in range(len(generator)):
gen_result[n] = alpha_exp + generator[n]
if gen_result[n] > 255:
gen_result[n] = gen_result[n] % 255
#Convert the alpha notation back into coefficients
gen_result[n] = tables.galois_log[gen_result[n]]
#XOR the sum with the message coefficients
mp_co[n] = gen_result[n] ^ mp_co[n]
#Pad the end of the error blocks with zeros if needed
if len(mp_co) < code_words_per_block:
mp_co.extend([0] * (code_words_per_block - len(mp_co)))
return mp_co | python | def make_error_block(self, block, block_number):
"""This function constructs the error correction block of the
given data block. This is *very complicated* process. To
understand the code you need to read:
* http://www.thonky.com/qr-code-tutorial/part-2-error-correction/
* http://www.matchadesign.com/blog/qr-code-demystified-part-4/
"""
#Get the error information from the standards table
error_info = tables.eccwbi[self.version][self.error]
#This is the number of 8-bit words per block
if block_number < error_info[1]:
code_words_per_block = error_info[2]
else:
code_words_per_block = error_info[4]
#This is the size of the error block
error_block_size = error_info[0]
#Copy the block as the message polynomial coefficients
mp_co = block[:]
#Add the error blocks to the message polynomial
mp_co.extend([0] * (error_block_size))
#Get the generator polynomial
generator = tables.generator_polynomials[error_block_size]
#This will hold the temporary sum of the message coefficient and the
#generator polynomial
gen_result = [0] * len(generator)
#Go through every code word in the block
for i in range(code_words_per_block):
#Get the first coefficient from the message polynomial
coefficient = mp_co.pop(0)
#Skip coefficients that are zero
if coefficient == 0:
continue
else:
#Turn the coefficient into an alpha exponent
alpha_exp = tables.galois_antilog[coefficient]
#Add the alpha to the generator polynomial
for n in range(len(generator)):
gen_result[n] = alpha_exp + generator[n]
if gen_result[n] > 255:
gen_result[n] = gen_result[n] % 255
#Convert the alpha notation back into coefficients
gen_result[n] = tables.galois_log[gen_result[n]]
#XOR the sum with the message coefficients
mp_co[n] = gen_result[n] ^ mp_co[n]
#Pad the end of the error blocks with zeros if needed
if len(mp_co) < code_words_per_block:
mp_co.extend([0] * (code_words_per_block - len(mp_co)))
return mp_co | [
"def",
"make_error_block",
"(",
"self",
",",
"block",
",",
"block_number",
")",
":",
"#Get the error information from the standards table",
"error_info",
"=",
"tables",
".",
"eccwbi",
"[",
"self",
".",
"version",
"]",
"[",
"self",
".",
"error",
"]",
"#This is the ... | This function constructs the error correction block of the
given data block. This is *very complicated* process. To
understand the code you need to read:
* http://www.thonky.com/qr-code-tutorial/part-2-error-correction/
* http://www.matchadesign.com/blog/qr-code-demystified-part-4/ | [
"This",
"function",
"constructs",
"the",
"error",
"correction",
"block",
"of",
"the",
"given",
"data",
"block",
".",
"This",
"is",
"*",
"very",
"complicated",
"*",
"process",
".",
"To",
"understand",
"the",
"code",
"you",
"need",
"to",
"read",
":"
] | train | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/builder.py#L434-L495 |
mnooner256/pyqrcode | pyqrcode/builder.py | QRCodeBuilder.make_code | def make_code(self):
"""This method returns the best possible QR code."""
from copy import deepcopy
#Get the size of the underlying matrix
matrix_size = tables.version_size[self.version]
#Create a template matrix we will build the codes with
row = [' ' for x in range(matrix_size)]
template = [deepcopy(row) for x in range(matrix_size)]
#Add mandatory information to the template
self.add_detection_pattern(template)
self.add_position_pattern(template)
self.add_version_pattern(template)
#Create the various types of masks of the template
self.masks = self.make_masks(template)
self.best_mask = self.choose_best_mask()
self.code = self.masks[self.best_mask] | python | def make_code(self):
"""This method returns the best possible QR code."""
from copy import deepcopy
#Get the size of the underlying matrix
matrix_size = tables.version_size[self.version]
#Create a template matrix we will build the codes with
row = [' ' for x in range(matrix_size)]
template = [deepcopy(row) for x in range(matrix_size)]
#Add mandatory information to the template
self.add_detection_pattern(template)
self.add_position_pattern(template)
self.add_version_pattern(template)
#Create the various types of masks of the template
self.masks = self.make_masks(template)
self.best_mask = self.choose_best_mask()
self.code = self.masks[self.best_mask] | [
"def",
"make_code",
"(",
"self",
")",
":",
"from",
"copy",
"import",
"deepcopy",
"#Get the size of the underlying matrix",
"matrix_size",
"=",
"tables",
".",
"version_size",
"[",
"self",
".",
"version",
"]",
"#Create a template matrix we will build the codes with",
"row",... | This method returns the best possible QR code. | [
"This",
"method",
"returns",
"the",
"best",
"possible",
"QR",
"code",
"."
] | train | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/builder.py#L497-L517 |
mnooner256/pyqrcode | pyqrcode/builder.py | QRCodeBuilder.add_detection_pattern | def add_detection_pattern(self, m):
"""This method add the detection patterns to the QR code. This lets
the scanner orient the pattern. It is required for all QR codes.
The detection pattern consists of three boxes located at the upper
left, upper right, and lower left corners of the matrix. Also, two
special lines called the timing pattern is also necessary. Finally,
a single black pixel is added just above the lower left black box.
"""
#Draw outer black box
for i in range(7):
inv = -(i+1)
for j in [0,6,-1,-7]:
m[j][i] = 1
m[i][j] = 1
m[inv][j] = 1
m[j][inv] = 1
#Draw inner white box
for i in range(1, 6):
inv = -(i+1)
for j in [1, 5, -2, -6]:
m[j][i] = 0
m[i][j] = 0
m[inv][j] = 0
m[j][inv] = 0
#Draw inner black box
for i in range(2, 5):
for j in range(2, 5):
inv = -(i+1)
m[i][j] = 1
m[inv][j] = 1
m[j][inv] = 1
#Draw white border
for i in range(8):
inv = -(i+1)
for j in [7, -8]:
m[i][j] = 0
m[j][i] = 0
m[inv][j] = 0
m[j][inv] = 0
#To keep the code short, it draws an extra box
#in the lower right corner, this removes it.
for i in range(-8, 0):
for j in range(-8, 0):
m[i][j] = ' '
#Add the timing pattern
bit = itertools.cycle([1,0])
for i in range(8, (len(m)-8)):
b = next(bit)
m[i][6] = b
m[6][i] = b
#Add the extra black pixel
m[-8][8] = 1 | python | def add_detection_pattern(self, m):
"""This method add the detection patterns to the QR code. This lets
the scanner orient the pattern. It is required for all QR codes.
The detection pattern consists of three boxes located at the upper
left, upper right, and lower left corners of the matrix. Also, two
special lines called the timing pattern is also necessary. Finally,
a single black pixel is added just above the lower left black box.
"""
#Draw outer black box
for i in range(7):
inv = -(i+1)
for j in [0,6,-1,-7]:
m[j][i] = 1
m[i][j] = 1
m[inv][j] = 1
m[j][inv] = 1
#Draw inner white box
for i in range(1, 6):
inv = -(i+1)
for j in [1, 5, -2, -6]:
m[j][i] = 0
m[i][j] = 0
m[inv][j] = 0
m[j][inv] = 0
#Draw inner black box
for i in range(2, 5):
for j in range(2, 5):
inv = -(i+1)
m[i][j] = 1
m[inv][j] = 1
m[j][inv] = 1
#Draw white border
for i in range(8):
inv = -(i+1)
for j in [7, -8]:
m[i][j] = 0
m[j][i] = 0
m[inv][j] = 0
m[j][inv] = 0
#To keep the code short, it draws an extra box
#in the lower right corner, this removes it.
for i in range(-8, 0):
for j in range(-8, 0):
m[i][j] = ' '
#Add the timing pattern
bit = itertools.cycle([1,0])
for i in range(8, (len(m)-8)):
b = next(bit)
m[i][6] = b
m[6][i] = b
#Add the extra black pixel
m[-8][8] = 1 | [
"def",
"add_detection_pattern",
"(",
"self",
",",
"m",
")",
":",
"#Draw outer black box",
"for",
"i",
"in",
"range",
"(",
"7",
")",
":",
"inv",
"=",
"-",
"(",
"i",
"+",
"1",
")",
"for",
"j",
"in",
"[",
"0",
",",
"6",
",",
"-",
"1",
",",
"-",
... | This method add the detection patterns to the QR code. This lets
the scanner orient the pattern. It is required for all QR codes.
The detection pattern consists of three boxes located at the upper
left, upper right, and lower left corners of the matrix. Also, two
special lines called the timing pattern is also necessary. Finally,
a single black pixel is added just above the lower left black box. | [
"This",
"method",
"add",
"the",
"detection",
"patterns",
"to",
"the",
"QR",
"code",
".",
"This",
"lets",
"the",
"scanner",
"orient",
"the",
"pattern",
".",
"It",
"is",
"required",
"for",
"all",
"QR",
"codes",
".",
"The",
"detection",
"pattern",
"consists",... | train | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/builder.py#L519-L577 |
mnooner256/pyqrcode | pyqrcode/builder.py | QRCodeBuilder.add_position_pattern | def add_position_pattern(self, m):
"""This method draws the position adjustment patterns onto the QR
Code. All QR code versions larger than one require these special boxes
called position adjustment patterns.
"""
#Version 1 does not have a position adjustment pattern
if self.version == 1:
return
#Get the coordinates for where to place the boxes
coordinates = tables.position_adjustment[self.version]
#Get the max and min coordinates to handle special cases
min_coord = coordinates[0]
max_coord = coordinates[-1]
#Draw a box at each intersection of the coordinates
for i in coordinates:
for j in coordinates:
#Do not draw these boxes because they would
#interfere with the detection pattern
if (i == min_coord and j == min_coord) or \
(i == min_coord and j == max_coord) or \
(i == max_coord and j == min_coord):
continue
#Center black pixel
m[i][j] = 1
#Surround the pixel with a white box
for x in [-1,1]:
m[i+x][j+x] = 0
m[i+x][j] = 0
m[i][j+x] = 0
m[i-x][j+x] = 0
m[i+x][j-x] = 0
#Surround the white box with a black box
for x in [-2,2]:
for y in [0,-1,1]:
m[i+x][j+x] = 1
m[i+x][j+y] = 1
m[i+y][j+x] = 1
m[i-x][j+x] = 1
m[i+x][j-x] = 1 | python | def add_position_pattern(self, m):
"""This method draws the position adjustment patterns onto the QR
Code. All QR code versions larger than one require these special boxes
called position adjustment patterns.
"""
#Version 1 does not have a position adjustment pattern
if self.version == 1:
return
#Get the coordinates for where to place the boxes
coordinates = tables.position_adjustment[self.version]
#Get the max and min coordinates to handle special cases
min_coord = coordinates[0]
max_coord = coordinates[-1]
#Draw a box at each intersection of the coordinates
for i in coordinates:
for j in coordinates:
#Do not draw these boxes because they would
#interfere with the detection pattern
if (i == min_coord and j == min_coord) or \
(i == min_coord and j == max_coord) or \
(i == max_coord and j == min_coord):
continue
#Center black pixel
m[i][j] = 1
#Surround the pixel with a white box
for x in [-1,1]:
m[i+x][j+x] = 0
m[i+x][j] = 0
m[i][j+x] = 0
m[i-x][j+x] = 0
m[i+x][j-x] = 0
#Surround the white box with a black box
for x in [-2,2]:
for y in [0,-1,1]:
m[i+x][j+x] = 1
m[i+x][j+y] = 1
m[i+y][j+x] = 1
m[i-x][j+x] = 1
m[i+x][j-x] = 1 | [
"def",
"add_position_pattern",
"(",
"self",
",",
"m",
")",
":",
"#Version 1 does not have a position adjustment pattern",
"if",
"self",
".",
"version",
"==",
"1",
":",
"return",
"#Get the coordinates for where to place the boxes",
"coordinates",
"=",
"tables",
".",
"posit... | This method draws the position adjustment patterns onto the QR
Code. All QR code versions larger than one require these special boxes
called position adjustment patterns. | [
"This",
"method",
"draws",
"the",
"position",
"adjustment",
"patterns",
"onto",
"the",
"QR",
"Code",
".",
"All",
"QR",
"code",
"versions",
"larger",
"than",
"one",
"require",
"these",
"special",
"boxes",
"called",
"position",
"adjustment",
"patterns",
"."
] | train | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/builder.py#L579-L623 |
mnooner256/pyqrcode | pyqrcode/builder.py | QRCodeBuilder.add_version_pattern | def add_version_pattern(self, m):
"""For QR codes with a version 7 or higher, a special pattern
specifying the code's version is required.
For further information see:
http://www.thonky.com/qr-code-tutorial/format-version-information/#example-of-version-7-information-string
"""
if self.version < 7:
return
#Get the bit fields for this code's version
#We will iterate across the string, the bit string
#needs the least significant digit in the zero-th position
field = iter(tables.version_pattern[self.version][::-1])
#Where to start placing the pattern
start = len(m)-11
#The version pattern is pretty odd looking
for i in range(6):
#The pattern is three modules wide
for j in range(start, start+3):
bit = int(next(field))
#Bottom Left
m[i][j] = bit
#Upper right
m[j][i] = bit | python | def add_version_pattern(self, m):
"""For QR codes with a version 7 or higher, a special pattern
specifying the code's version is required.
For further information see:
http://www.thonky.com/qr-code-tutorial/format-version-information/#example-of-version-7-information-string
"""
if self.version < 7:
return
#Get the bit fields for this code's version
#We will iterate across the string, the bit string
#needs the least significant digit in the zero-th position
field = iter(tables.version_pattern[self.version][::-1])
#Where to start placing the pattern
start = len(m)-11
#The version pattern is pretty odd looking
for i in range(6):
#The pattern is three modules wide
for j in range(start, start+3):
bit = int(next(field))
#Bottom Left
m[i][j] = bit
#Upper right
m[j][i] = bit | [
"def",
"add_version_pattern",
"(",
"self",
",",
"m",
")",
":",
"if",
"self",
".",
"version",
"<",
"7",
":",
"return",
"#Get the bit fields for this code's version",
"#We will iterate across the string, the bit string",
"#needs the least significant digit in the zero-th position",... | For QR codes with a version 7 or higher, a special pattern
specifying the code's version is required.
For further information see:
http://www.thonky.com/qr-code-tutorial/format-version-information/#example-of-version-7-information-string | [
"For",
"QR",
"codes",
"with",
"a",
"version",
"7",
"or",
"higher",
"a",
"special",
"pattern",
"specifying",
"the",
"code",
"s",
"version",
"is",
"required",
"."
] | train | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/builder.py#L625-L653 |
mnooner256/pyqrcode | pyqrcode/builder.py | QRCodeBuilder.make_masks | def make_masks(self, template):
"""This method generates all seven masks so that the best mask can
be determined. The template parameter is a code matrix that will
server as the base for all the generated masks.
"""
from copy import deepcopy
nmasks = len(tables.mask_patterns)
masks = [''] * nmasks
count = 0
for n in range(nmasks):
cur_mask = deepcopy(template)
masks[n] = cur_mask
#Add the type pattern bits to the code
self.add_type_pattern(cur_mask, tables.type_bits[self.error][n])
#Get the mask pattern
pattern = tables.mask_patterns[n]
#This will read the 1's and 0's one at a time
bits = iter(self.buffer.getvalue())
#These will help us do the up, down, up, down pattern
row_start = itertools.cycle([len(cur_mask)-1, 0])
row_stop = itertools.cycle([-1,len(cur_mask)])
direction = itertools.cycle([-1, 1])
#The data pattern is added using pairs of columns
for column in range(len(cur_mask)-1, 0, -2):
#The vertical timing pattern is an exception to the rules,
#move the column counter over by one
if column <= 6:
column = column - 1
#This will let us fill in the pattern
#right-left, right-left, etc.
column_pair = itertools.cycle([column, column-1])
#Go through each row in the pattern moving up, then down
for row in range(next(row_start), next(row_stop),
next(direction)):
#Fill in the right then left column
for i in range(2):
col = next(column_pair)
#Go to the next column if we encounter a
#preexisting pattern (usually an alignment pattern)
if cur_mask[row][col] != ' ':
continue
#Some versions don't have enough bits. You then fill
#in the rest of the pattern with 0's. These are
#called "remainder bits."
try:
bit = int(next(bits))
except:
bit = 0
#If the pattern is True then flip the bit
if pattern(row, col):
cur_mask[row][col] = bit ^ 1
else:
cur_mask[row][col] = bit
#DEBUG CODE!!!
#Save all of the masks as png files
#for i, m in enumerate(masks):
# _png(m, self.version, 'mask-{0}.png'.format(i), 5)
return masks | python | def make_masks(self, template):
"""This method generates all seven masks so that the best mask can
be determined. The template parameter is a code matrix that will
server as the base for all the generated masks.
"""
from copy import deepcopy
nmasks = len(tables.mask_patterns)
masks = [''] * nmasks
count = 0
for n in range(nmasks):
cur_mask = deepcopy(template)
masks[n] = cur_mask
#Add the type pattern bits to the code
self.add_type_pattern(cur_mask, tables.type_bits[self.error][n])
#Get the mask pattern
pattern = tables.mask_patterns[n]
#This will read the 1's and 0's one at a time
bits = iter(self.buffer.getvalue())
#These will help us do the up, down, up, down pattern
row_start = itertools.cycle([len(cur_mask)-1, 0])
row_stop = itertools.cycle([-1,len(cur_mask)])
direction = itertools.cycle([-1, 1])
#The data pattern is added using pairs of columns
for column in range(len(cur_mask)-1, 0, -2):
#The vertical timing pattern is an exception to the rules,
#move the column counter over by one
if column <= 6:
column = column - 1
#This will let us fill in the pattern
#right-left, right-left, etc.
column_pair = itertools.cycle([column, column-1])
#Go through each row in the pattern moving up, then down
for row in range(next(row_start), next(row_stop),
next(direction)):
#Fill in the right then left column
for i in range(2):
col = next(column_pair)
#Go to the next column if we encounter a
#preexisting pattern (usually an alignment pattern)
if cur_mask[row][col] != ' ':
continue
#Some versions don't have enough bits. You then fill
#in the rest of the pattern with 0's. These are
#called "remainder bits."
try:
bit = int(next(bits))
except:
bit = 0
#If the pattern is True then flip the bit
if pattern(row, col):
cur_mask[row][col] = bit ^ 1
else:
cur_mask[row][col] = bit
#DEBUG CODE!!!
#Save all of the masks as png files
#for i, m in enumerate(masks):
# _png(m, self.version, 'mask-{0}.png'.format(i), 5)
return masks | [
"def",
"make_masks",
"(",
"self",
",",
"template",
")",
":",
"from",
"copy",
"import",
"deepcopy",
"nmasks",
"=",
"len",
"(",
"tables",
".",
"mask_patterns",
")",
"masks",
"=",
"[",
"''",
"]",
"*",
"nmasks",
"count",
"=",
"0",
"for",
"n",
"in",
"rang... | This method generates all seven masks so that the best mask can
be determined. The template parameter is a code matrix that will
server as the base for all the generated masks. | [
"This",
"method",
"generates",
"all",
"seven",
"masks",
"so",
"that",
"the",
"best",
"mask",
"can",
"be",
"determined",
".",
"The",
"template",
"parameter",
"is",
"a",
"code",
"matrix",
"that",
"will",
"server",
"as",
"the",
"base",
"for",
"all",
"the",
... | train | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/builder.py#L655-L729 |
mnooner256/pyqrcode | pyqrcode/builder.py | QRCodeBuilder.choose_best_mask | def choose_best_mask(self):
"""This method returns the index of the "best" mask as defined by
having the lowest total penalty score. The penalty rules are defined
by the standard. The mask with the lowest total score should be the
easiest to read by optical scanners.
"""
self.scores = []
for n in range(len(self.masks)):
self.scores.append([0,0,0,0])
#Score penalty rule number 1
#Look for five consecutive squares with the same color.
#Each one found gets a penalty of 3 + 1 for every
#same color square after the first five in the row.
for (n, mask) in enumerate(self.masks):
current = mask[0][0]
counter = 0
total = 0
#Examine the mask row wise
for row in range(0,len(mask)):
counter = 0
for col in range(0,len(mask)):
bit = mask[row][col]
if bit == current:
counter += 1
else:
if counter >= 5:
total += (counter - 5) + 3
counter = 1
current = bit
if counter >= 5:
total += (counter - 5) + 3
#Examine the mask column wise
for col in range(0,len(mask)):
counter = 0
for row in range(0,len(mask)):
bit = mask[row][col]
if bit == current:
counter += 1
else:
if counter >= 5:
total += (counter - 5) + 3
counter = 1
current = bit
if counter >= 5:
total += (counter - 5) + 3
self.scores[n][0] = total
#Score penalty rule 2
#This rule will add 3 to the score for each 2x2 block of the same
#colored pixels there are.
for (n, mask) in enumerate(self.masks):
count = 0
#Don't examine the 0th and Nth row/column
for i in range(0, len(mask)-1):
for j in range(0, len(mask)-1):
if mask[i][j] == mask[i+1][j] and \
mask[i][j] == mask[i][j+1] and \
mask[i][j] == mask[i+1][j+1]:
count += 1
self.scores[n][1] = count * 3
#Score penalty rule 3
#This rule looks for 1011101 within the mask prefixed
#and/or suffixed by four zeros.
patterns = [[0,0,0,0,1,0,1,1,1,0,1],
[1,0,1,1,1,0,1,0,0,0,0],]
#[0,0,0,0,1,0,1,1,1,0,1,0,0,0,0]]
for (n, mask) in enumerate(self.masks):
nmatches = 0
for i in range(len(mask)):
for j in range(len(mask)):
for pattern in patterns:
match = True
k = j
#Look for row matches
for p in pattern:
if k >= len(mask) or mask[i][k] != p:
match = False
break
k += 1
if match:
nmatches += 1
match = True
k = j
#Look for column matches
for p in pattern:
if k >= len(mask) or mask[k][i] != p:
match = False
break
k += 1
if match:
nmatches += 1
self.scores[n][2] = nmatches * 40
#Score the last rule, penalty rule 4. This rule measures how close
#the pattern is to being 50% black. The further it deviates from
#this this ideal the higher the penalty.
for (n, mask) in enumerate(self.masks):
nblack = 0
for row in mask:
nblack += sum(row)
total_pixels = len(mask)**2
ratio = nblack / total_pixels
percent = (ratio * 100) - 50
self.scores[n][3] = int((abs(int(percent)) / 5) * 10)
#Calculate the total for each score
totals = [0] * len(self.scores)
for i in range(len(self.scores)):
for j in range(len(self.scores[i])):
totals[i] += self.scores[i][j]
#DEBUG CODE!!!
#Prints out a table of scores
#print('Rule Scores\n 1 2 3 4 Total')
#for i in range(len(self.scores)):
# print(i, end='')
# for s in self.scores[i]:
# print('{0: >6}'.format(s), end='')
# print('{0: >7}'.format(totals[i]))
#print('Mask Chosen: {0}'.format(totals.index(min(totals))))
#The lowest total wins
return totals.index(min(totals)) | python | def choose_best_mask(self):
"""This method returns the index of the "best" mask as defined by
having the lowest total penalty score. The penalty rules are defined
by the standard. The mask with the lowest total score should be the
easiest to read by optical scanners.
"""
self.scores = []
for n in range(len(self.masks)):
self.scores.append([0,0,0,0])
#Score penalty rule number 1
#Look for five consecutive squares with the same color.
#Each one found gets a penalty of 3 + 1 for every
#same color square after the first five in the row.
for (n, mask) in enumerate(self.masks):
current = mask[0][0]
counter = 0
total = 0
#Examine the mask row wise
for row in range(0,len(mask)):
counter = 0
for col in range(0,len(mask)):
bit = mask[row][col]
if bit == current:
counter += 1
else:
if counter >= 5:
total += (counter - 5) + 3
counter = 1
current = bit
if counter >= 5:
total += (counter - 5) + 3
#Examine the mask column wise
for col in range(0,len(mask)):
counter = 0
for row in range(0,len(mask)):
bit = mask[row][col]
if bit == current:
counter += 1
else:
if counter >= 5:
total += (counter - 5) + 3
counter = 1
current = bit
if counter >= 5:
total += (counter - 5) + 3
self.scores[n][0] = total
#Score penalty rule 2
#This rule will add 3 to the score for each 2x2 block of the same
#colored pixels there are.
for (n, mask) in enumerate(self.masks):
count = 0
#Don't examine the 0th and Nth row/column
for i in range(0, len(mask)-1):
for j in range(0, len(mask)-1):
if mask[i][j] == mask[i+1][j] and \
mask[i][j] == mask[i][j+1] and \
mask[i][j] == mask[i+1][j+1]:
count += 1
self.scores[n][1] = count * 3
#Score penalty rule 3
#This rule looks for 1011101 within the mask prefixed
#and/or suffixed by four zeros.
patterns = [[0,0,0,0,1,0,1,1,1,0,1],
[1,0,1,1,1,0,1,0,0,0,0],]
#[0,0,0,0,1,0,1,1,1,0,1,0,0,0,0]]
for (n, mask) in enumerate(self.masks):
nmatches = 0
for i in range(len(mask)):
for j in range(len(mask)):
for pattern in patterns:
match = True
k = j
#Look for row matches
for p in pattern:
if k >= len(mask) or mask[i][k] != p:
match = False
break
k += 1
if match:
nmatches += 1
match = True
k = j
#Look for column matches
for p in pattern:
if k >= len(mask) or mask[k][i] != p:
match = False
break
k += 1
if match:
nmatches += 1
self.scores[n][2] = nmatches * 40
#Score the last rule, penalty rule 4. This rule measures how close
#the pattern is to being 50% black. The further it deviates from
#this this ideal the higher the penalty.
for (n, mask) in enumerate(self.masks):
nblack = 0
for row in mask:
nblack += sum(row)
total_pixels = len(mask)**2
ratio = nblack / total_pixels
percent = (ratio * 100) - 50
self.scores[n][3] = int((abs(int(percent)) / 5) * 10)
#Calculate the total for each score
totals = [0] * len(self.scores)
for i in range(len(self.scores)):
for j in range(len(self.scores[i])):
totals[i] += self.scores[i][j]
#DEBUG CODE!!!
#Prints out a table of scores
#print('Rule Scores\n 1 2 3 4 Total')
#for i in range(len(self.scores)):
# print(i, end='')
# for s in self.scores[i]:
# print('{0: >6}'.format(s), end='')
# print('{0: >7}'.format(totals[i]))
#print('Mask Chosen: {0}'.format(totals.index(min(totals))))
#The lowest total wins
return totals.index(min(totals)) | [
"def",
"choose_best_mask",
"(",
"self",
")",
":",
"self",
".",
"scores",
"=",
"[",
"]",
"for",
"n",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"masks",
")",
")",
":",
"self",
".",
"scores",
".",
"append",
"(",
"[",
"0",
",",
"0",
",",
"0",
... | This method returns the index of the "best" mask as defined by
having the lowest total penalty score. The penalty rules are defined
by the standard. The mask with the lowest total score should be the
easiest to read by optical scanners. | [
"This",
"method",
"returns",
"the",
"index",
"of",
"the",
"best",
"mask",
"as",
"defined",
"by",
"having",
"the",
"lowest",
"total",
"penalty",
"score",
".",
"The",
"penalty",
"rules",
"are",
"defined",
"by",
"the",
"standard",
".",
"The",
"mask",
"with",
... | train | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/builder.py#L731-L868 |
mnooner256/pyqrcode | pyqrcode/builder.py | QRCodeBuilder.add_type_pattern | def add_type_pattern(self, m, type_bits):
"""This will add the pattern to the QR code that represents the error
level and the type of mask used to make the code.
"""
field = iter(type_bits)
for i in range(7):
bit = int(next(field))
#Skip the timing bits
if i < 6:
m[8][i] = bit
else:
m[8][i+1] = bit
if -8 < -(i+1):
m[-(i+1)][8] = bit
for i in range(-8,0):
bit = int(next(field))
m[8][i] = bit
i = -i
#Skip timing column
if i > 6:
m[i][8] = bit
else:
m[i-1][8] = bit | python | def add_type_pattern(self, m, type_bits):
"""This will add the pattern to the QR code that represents the error
level and the type of mask used to make the code.
"""
field = iter(type_bits)
for i in range(7):
bit = int(next(field))
#Skip the timing bits
if i < 6:
m[8][i] = bit
else:
m[8][i+1] = bit
if -8 < -(i+1):
m[-(i+1)][8] = bit
for i in range(-8,0):
bit = int(next(field))
m[8][i] = bit
i = -i
#Skip timing column
if i > 6:
m[i][8] = bit
else:
m[i-1][8] = bit | [
"def",
"add_type_pattern",
"(",
"self",
",",
"m",
",",
"type_bits",
")",
":",
"field",
"=",
"iter",
"(",
"type_bits",
")",
"for",
"i",
"in",
"range",
"(",
"7",
")",
":",
"bit",
"=",
"int",
"(",
"next",
"(",
"field",
")",
")",
"#Skip the timing bits",... | This will add the pattern to the QR code that represents the error
level and the type of mask used to make the code. | [
"This",
"will",
"add",
"the",
"pattern",
"to",
"the",
"QR",
"code",
"that",
"represents",
"the",
"error",
"level",
"and",
"the",
"type",
"of",
"mask",
"used",
"to",
"make",
"the",
"code",
"."
] | train | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/builder.py#L870-L897 |
arokem/python-matlab-bridge | tools/github_stats.py | split_pulls | def split_pulls(all_issues, project="arokem/python-matlab-bridge"):
"""split a list of closed issues into non-PR Issues and Pull Requests"""
pulls = []
issues = []
for i in all_issues:
if is_pull_request(i):
pull = get_pull_request(project, i['number'], auth=True)
pulls.append(pull)
else:
issues.append(i)
return issues, pulls | python | def split_pulls(all_issues, project="arokem/python-matlab-bridge"):
"""split a list of closed issues into non-PR Issues and Pull Requests"""
pulls = []
issues = []
for i in all_issues:
if is_pull_request(i):
pull = get_pull_request(project, i['number'], auth=True)
pulls.append(pull)
else:
issues.append(i)
return issues, pulls | [
"def",
"split_pulls",
"(",
"all_issues",
",",
"project",
"=",
"\"arokem/python-matlab-bridge\"",
")",
":",
"pulls",
"=",
"[",
"]",
"issues",
"=",
"[",
"]",
"for",
"i",
"in",
"all_issues",
":",
"if",
"is_pull_request",
"(",
"i",
")",
":",
"pull",
"=",
"ge... | split a list of closed issues into non-PR Issues and Pull Requests | [
"split",
"a",
"list",
"of",
"closed",
"issues",
"into",
"non",
"-",
"PR",
"Issues",
"and",
"Pull",
"Requests"
] | train | https://github.com/arokem/python-matlab-bridge/blob/9822c7b55435662f4f033c5479cc03fea2255755/tools/github_stats.py#L53-L63 |
arokem/python-matlab-bridge | tools/github_stats.py | issues_closed_since | def issues_closed_since(period=timedelta(days=365), project="arokem/python-matlab-bridge", pulls=False):
"""Get all issues closed since a particular point in time. period
can either be a datetime object, or a timedelta object. In the
latter case, it is used as a time before the present.
"""
which = 'pulls' if pulls else 'issues'
if isinstance(period, timedelta):
since = round_hour(datetime.utcnow() - period)
else:
since = period
url = "https://api.github.com/repos/%s/%s?state=closed&sort=updated&since=%s&per_page=%i" % (project, which, since.strftime(ISO8601), PER_PAGE)
allclosed = get_paged_request(url, headers=make_auth_header())
filtered = [ i for i in allclosed if _parse_datetime(i['closed_at']) > since ]
if pulls:
filtered = [ i for i in filtered if _parse_datetime(i['merged_at']) > since ]
# filter out PRs not against master (backports)
filtered = [ i for i in filtered if i['base']['ref'] == 'master' ]
else:
filtered = [ i for i in filtered if not is_pull_request(i) ]
return filtered | python | def issues_closed_since(period=timedelta(days=365), project="arokem/python-matlab-bridge", pulls=False):
"""Get all issues closed since a particular point in time. period
can either be a datetime object, or a timedelta object. In the
latter case, it is used as a time before the present.
"""
which = 'pulls' if pulls else 'issues'
if isinstance(period, timedelta):
since = round_hour(datetime.utcnow() - period)
else:
since = period
url = "https://api.github.com/repos/%s/%s?state=closed&sort=updated&since=%s&per_page=%i" % (project, which, since.strftime(ISO8601), PER_PAGE)
allclosed = get_paged_request(url, headers=make_auth_header())
filtered = [ i for i in allclosed if _parse_datetime(i['closed_at']) > since ]
if pulls:
filtered = [ i for i in filtered if _parse_datetime(i['merged_at']) > since ]
# filter out PRs not against master (backports)
filtered = [ i for i in filtered if i['base']['ref'] == 'master' ]
else:
filtered = [ i for i in filtered if not is_pull_request(i) ]
return filtered | [
"def",
"issues_closed_since",
"(",
"period",
"=",
"timedelta",
"(",
"days",
"=",
"365",
")",
",",
"project",
"=",
"\"arokem/python-matlab-bridge\"",
",",
"pulls",
"=",
"False",
")",
":",
"which",
"=",
"'pulls'",
"if",
"pulls",
"else",
"'issues'",
"if",
"isin... | Get all issues closed since a particular point in time. period
can either be a datetime object, or a timedelta object. In the
latter case, it is used as a time before the present. | [
"Get",
"all",
"issues",
"closed",
"since",
"a",
"particular",
"point",
"in",
"time",
".",
"period",
"can",
"either",
"be",
"a",
"datetime",
"object",
"or",
"a",
"timedelta",
"object",
".",
"In",
"the",
"latter",
"case",
"it",
"is",
"used",
"as",
"a",
"... | train | https://github.com/arokem/python-matlab-bridge/blob/9822c7b55435662f4f033c5479cc03fea2255755/tools/github_stats.py#L66-L89 |
arokem/python-matlab-bridge | tools/github_stats.py | sorted_by_field | def sorted_by_field(issues, field='closed_at', reverse=False):
"""Return a list of issues sorted by closing date date."""
return sorted(issues, key = lambda i:i[field], reverse=reverse) | python | def sorted_by_field(issues, field='closed_at', reverse=False):
"""Return a list of issues sorted by closing date date."""
return sorted(issues, key = lambda i:i[field], reverse=reverse) | [
"def",
"sorted_by_field",
"(",
"issues",
",",
"field",
"=",
"'closed_at'",
",",
"reverse",
"=",
"False",
")",
":",
"return",
"sorted",
"(",
"issues",
",",
"key",
"=",
"lambda",
"i",
":",
"i",
"[",
"field",
"]",
",",
"reverse",
"=",
"reverse",
")"
] | Return a list of issues sorted by closing date date. | [
"Return",
"a",
"list",
"of",
"issues",
"sorted",
"by",
"closing",
"date",
"date",
"."
] | train | https://github.com/arokem/python-matlab-bridge/blob/9822c7b55435662f4f033c5479cc03fea2255755/tools/github_stats.py#L92-L94 |
arokem/python-matlab-bridge | tools/github_stats.py | report | def report(issues, show_urls=False):
"""Summary report about a list of issues, printing number and title.
"""
# titles may have unicode in them, so we must encode everything below
if show_urls:
for i in issues:
print(u'#%d: %s' % (i['number'],
i['title'].replace(u'`', u'``')))
else:
for i in issues:
print(u'* %d: %s' % (i['number'], i['title'].replace(u'`', u'``'))) | python | def report(issues, show_urls=False):
"""Summary report about a list of issues, printing number and title.
"""
# titles may have unicode in them, so we must encode everything below
if show_urls:
for i in issues:
print(u'#%d: %s' % (i['number'],
i['title'].replace(u'`', u'``')))
else:
for i in issues:
print(u'* %d: %s' % (i['number'], i['title'].replace(u'`', u'``'))) | [
"def",
"report",
"(",
"issues",
",",
"show_urls",
"=",
"False",
")",
":",
"# titles may have unicode in them, so we must encode everything below",
"if",
"show_urls",
":",
"for",
"i",
"in",
"issues",
":",
"print",
"(",
"u'#%d: %s'",
"%",
"(",
"i",
"[",
"'number'",
... | Summary report about a list of issues, printing number and title. | [
"Summary",
"report",
"about",
"a",
"list",
"of",
"issues",
"printing",
"number",
"and",
"title",
"."
] | train | https://github.com/arokem/python-matlab-bridge/blob/9822c7b55435662f4f033c5479cc03fea2255755/tools/github_stats.py#L97-L107 |
arokem/python-matlab-bridge | pymatbridge/pymatbridge.py | encode_ndarray | def encode_ndarray(obj):
"""Write a numpy array and its shape to base64 buffers"""
shape = obj.shape
if len(shape) == 1:
shape = (1, obj.shape[0])
if obj.flags.c_contiguous:
obj = obj.T
elif not obj.flags.f_contiguous:
obj = asfortranarray(obj.T)
else:
obj = obj.T
try:
data = obj.astype(float64).tobytes()
except AttributeError:
data = obj.astype(float64).tostring()
data = base64.b64encode(data).decode('utf-8')
return data, shape | python | def encode_ndarray(obj):
"""Write a numpy array and its shape to base64 buffers"""
shape = obj.shape
if len(shape) == 1:
shape = (1, obj.shape[0])
if obj.flags.c_contiguous:
obj = obj.T
elif not obj.flags.f_contiguous:
obj = asfortranarray(obj.T)
else:
obj = obj.T
try:
data = obj.astype(float64).tobytes()
except AttributeError:
data = obj.astype(float64).tostring()
data = base64.b64encode(data).decode('utf-8')
return data, shape | [
"def",
"encode_ndarray",
"(",
"obj",
")",
":",
"shape",
"=",
"obj",
".",
"shape",
"if",
"len",
"(",
"shape",
")",
"==",
"1",
":",
"shape",
"=",
"(",
"1",
",",
"obj",
".",
"shape",
"[",
"0",
"]",
")",
"if",
"obj",
".",
"flags",
".",
"c_contiguou... | Write a numpy array and its shape to base64 buffers | [
"Write",
"a",
"numpy",
"array",
"and",
"its",
"shape",
"to",
"base64",
"buffers"
] | train | https://github.com/arokem/python-matlab-bridge/blob/9822c7b55435662f4f033c5479cc03fea2255755/pymatbridge/pymatbridge.py#L46-L63 |
arokem/python-matlab-bridge | pymatbridge/pymatbridge.py | decode_arr | def decode_arr(data):
"""Extract a numpy array from a base64 buffer"""
data = data.encode('utf-8')
return frombuffer(base64.b64decode(data), float64) | python | def decode_arr(data):
"""Extract a numpy array from a base64 buffer"""
data = data.encode('utf-8')
return frombuffer(base64.b64decode(data), float64) | [
"def",
"decode_arr",
"(",
"data",
")",
":",
"data",
"=",
"data",
".",
"encode",
"(",
"'utf-8'",
")",
"return",
"frombuffer",
"(",
"base64",
".",
"b64decode",
"(",
"data",
")",
",",
"float64",
")"
] | Extract a numpy array from a base64 buffer | [
"Extract",
"a",
"numpy",
"array",
"from",
"a",
"base64",
"buffer"
] | train | https://github.com/arokem/python-matlab-bridge/blob/9822c7b55435662f4f033c5479cc03fea2255755/pymatbridge/pymatbridge.py#L88-L91 |
arokem/python-matlab-bridge | pymatbridge/pymatbridge.py | _Session.run_func | def run_func(self, func_path, *func_args, **kwargs):
"""Run a function in Matlab and return the result.
Parameters
----------
func_path: str
Name of function to run or a path to an m-file.
func_args: object, optional
Function args to send to the function.
nargout: int, optional
Desired number of return arguments.
kwargs:
Keyword arguments are passed to Matlab in the form [key, val] so
that matlab.plot(x, y, '--', LineWidth=2) would be translated into
plot(x, y, '--', 'LineWidth', 2)
Returns
-------
Result dictionary with keys: 'message', 'result', and 'success'
"""
if not self.started:
raise ValueError('Session not started, use start()')
nargout = kwargs.pop('nargout', 1)
func_args += tuple(item for pair in zip(kwargs.keys(), kwargs.values())
for item in pair)
dname = os.path.dirname(func_path)
fname = os.path.basename(func_path)
func_name, ext = os.path.splitext(fname)
if ext and not ext == '.m':
raise TypeError('Need to give path to .m file')
return self._json_response(cmd='eval',
func_name=func_name,
func_args=func_args or '',
dname=dname,
nargout=nargout) | python | def run_func(self, func_path, *func_args, **kwargs):
"""Run a function in Matlab and return the result.
Parameters
----------
func_path: str
Name of function to run or a path to an m-file.
func_args: object, optional
Function args to send to the function.
nargout: int, optional
Desired number of return arguments.
kwargs:
Keyword arguments are passed to Matlab in the form [key, val] so
that matlab.plot(x, y, '--', LineWidth=2) would be translated into
plot(x, y, '--', 'LineWidth', 2)
Returns
-------
Result dictionary with keys: 'message', 'result', and 'success'
"""
if not self.started:
raise ValueError('Session not started, use start()')
nargout = kwargs.pop('nargout', 1)
func_args += tuple(item for pair in zip(kwargs.keys(), kwargs.values())
for item in pair)
dname = os.path.dirname(func_path)
fname = os.path.basename(func_path)
func_name, ext = os.path.splitext(fname)
if ext and not ext == '.m':
raise TypeError('Need to give path to .m file')
return self._json_response(cmd='eval',
func_name=func_name,
func_args=func_args or '',
dname=dname,
nargout=nargout) | [
"def",
"run_func",
"(",
"self",
",",
"func_path",
",",
"*",
"func_args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"started",
":",
"raise",
"ValueError",
"(",
"'Session not started, use start()'",
")",
"nargout",
"=",
"kwargs",
".",
"pop... | Run a function in Matlab and return the result.
Parameters
----------
func_path: str
Name of function to run or a path to an m-file.
func_args: object, optional
Function args to send to the function.
nargout: int, optional
Desired number of return arguments.
kwargs:
Keyword arguments are passed to Matlab in the form [key, val] so
that matlab.plot(x, y, '--', LineWidth=2) would be translated into
plot(x, y, '--', 'LineWidth', 2)
Returns
-------
Result dictionary with keys: 'message', 'result', and 'success' | [
"Run",
"a",
"function",
"in",
"Matlab",
"and",
"return",
"the",
"result",
"."
] | train | https://github.com/arokem/python-matlab-bridge/blob/9822c7b55435662f4f033c5479cc03fea2255755/pymatbridge/pymatbridge.py#L276-L311 |
arokem/python-matlab-bridge | pymatbridge/pymatbridge.py | _Session._bind_method | def _bind_method(self, name, unconditionally=False):
"""Generate a Matlab function and bind it to the instance
This is where the magic happens. When an unknown attribute of the
Matlab class is requested, it is assumed to be a call to a
Matlab function, and is generated and bound to the instance.
This works because getattr() falls back to __getattr__ only if no
attributes of the requested name can be found through normal
routes (__getattribute__, __dict__, class tree).
bind_method first checks whether the requested name is a callable
Matlab function before generating a binding.
Parameters
----------
name : str
The name of the Matlab function to call
e.g. 'sqrt', 'sum', 'svd', etc
unconditionally : bool, optional
Bind the method without performing
checks. Used to bootstrap methods that are required and
know to exist
Returns
-------
MatlabFunction
A reference to a newly bound MatlabFunction instance if the
requested name is determined to be a callable function
Raises
------
AttributeError: if the requested name is not a callable
Matlab function
"""
# TODO: This does not work if the function is a mex function inside a folder of the same name
exists = self.run_func('exist', name)['result'] in [2, 3, 5]
if not unconditionally and not exists:
raise AttributeError("'Matlab' object has no attribute '%s'" % name)
# create a new method instance
method_instance = MatlabFunction(weakref.ref(self), name)
method_instance.__name__ = name
# bind to the Matlab instance with a weakref (to avoid circular references)
if sys.version.startswith('3'):
method = types.MethodType(method_instance, weakref.ref(self))
else:
method = types.MethodType(method_instance, weakref.ref(self),
_Session)
setattr(self, name, method)
return getattr(self, name) | python | def _bind_method(self, name, unconditionally=False):
"""Generate a Matlab function and bind it to the instance
This is where the magic happens. When an unknown attribute of the
Matlab class is requested, it is assumed to be a call to a
Matlab function, and is generated and bound to the instance.
This works because getattr() falls back to __getattr__ only if no
attributes of the requested name can be found through normal
routes (__getattribute__, __dict__, class tree).
bind_method first checks whether the requested name is a callable
Matlab function before generating a binding.
Parameters
----------
name : str
The name of the Matlab function to call
e.g. 'sqrt', 'sum', 'svd', etc
unconditionally : bool, optional
Bind the method without performing
checks. Used to bootstrap methods that are required and
know to exist
Returns
-------
MatlabFunction
A reference to a newly bound MatlabFunction instance if the
requested name is determined to be a callable function
Raises
------
AttributeError: if the requested name is not a callable
Matlab function
"""
# TODO: This does not work if the function is a mex function inside a folder of the same name
exists = self.run_func('exist', name)['result'] in [2, 3, 5]
if not unconditionally and not exists:
raise AttributeError("'Matlab' object has no attribute '%s'" % name)
# create a new method instance
method_instance = MatlabFunction(weakref.ref(self), name)
method_instance.__name__ = name
# bind to the Matlab instance with a weakref (to avoid circular references)
if sys.version.startswith('3'):
method = types.MethodType(method_instance, weakref.ref(self))
else:
method = types.MethodType(method_instance, weakref.ref(self),
_Session)
setattr(self, name, method)
return getattr(self, name) | [
"def",
"_bind_method",
"(",
"self",
",",
"name",
",",
"unconditionally",
"=",
"False",
")",
":",
"# TODO: This does not work if the function is a mex function inside a folder of the same name",
"exists",
"=",
"self",
".",
"run_func",
"(",
"'exist'",
",",
"name",
")",
"[... | Generate a Matlab function and bind it to the instance
This is where the magic happens. When an unknown attribute of the
Matlab class is requested, it is assumed to be a call to a
Matlab function, and is generated and bound to the instance.
This works because getattr() falls back to __getattr__ only if no
attributes of the requested name can be found through normal
routes (__getattribute__, __dict__, class tree).
bind_method first checks whether the requested name is a callable
Matlab function before generating a binding.
Parameters
----------
name : str
The name of the Matlab function to call
e.g. 'sqrt', 'sum', 'svd', etc
unconditionally : bool, optional
Bind the method without performing
checks. Used to bootstrap methods that are required and
know to exist
Returns
-------
MatlabFunction
A reference to a newly bound MatlabFunction instance if the
requested name is determined to be a callable function
Raises
------
AttributeError: if the requested name is not a callable
Matlab function | [
"Generate",
"a",
"Matlab",
"function",
"and",
"bind",
"it",
"to",
"the",
"instance"
] | train | https://github.com/arokem/python-matlab-bridge/blob/9822c7b55435662f4f033c5479cc03fea2255755/pymatbridge/pymatbridge.py#L359-L411 |
arokem/python-matlab-bridge | pymatbridge/publish.py | format_line | def format_line(line):
"""
Format a line of Matlab into either a markdown line or a code line.
Parameters
----------
line : str
The line of code to be formatted. Formatting occurs according to the
following rules:
- If the line starts with (at least) two %% signs, a new cell will be
started.
- If the line doesn't start with a '%' sign, it is assumed to be legit
matlab code. We will continue to add to the same cell until reaching
the next comment line
"""
if line.startswith('%%'):
md = True
new_cell = True
source = line.split('%%')[1] + '\n' # line-breaks in md require a line
# gap!
elif line.startswith('%'):
md = True
new_cell = False
source = line.split('%')[1] + '\n'
else:
md = False
new_cell = False
source = line
return new_cell, md, source | python | def format_line(line):
"""
Format a line of Matlab into either a markdown line or a code line.
Parameters
----------
line : str
The line of code to be formatted. Formatting occurs according to the
following rules:
- If the line starts with (at least) two %% signs, a new cell will be
started.
- If the line doesn't start with a '%' sign, it is assumed to be legit
matlab code. We will continue to add to the same cell until reaching
the next comment line
"""
if line.startswith('%%'):
md = True
new_cell = True
source = line.split('%%')[1] + '\n' # line-breaks in md require a line
# gap!
elif line.startswith('%'):
md = True
new_cell = False
source = line.split('%')[1] + '\n'
else:
md = False
new_cell = False
source = line
return new_cell, md, source | [
"def",
"format_line",
"(",
"line",
")",
":",
"if",
"line",
".",
"startswith",
"(",
"'%%'",
")",
":",
"md",
"=",
"True",
"new_cell",
"=",
"True",
"source",
"=",
"line",
".",
"split",
"(",
"'%%'",
")",
"[",
"1",
"]",
"+",
"'\\n'",
"# line-breaks in md ... | Format a line of Matlab into either a markdown line or a code line.
Parameters
----------
line : str
The line of code to be formatted. Formatting occurs according to the
following rules:
- If the line starts with (at least) two %% signs, a new cell will be
started.
- If the line doesn't start with a '%' sign, it is assumed to be legit
matlab code. We will continue to add to the same cell until reaching
the next comment line | [
"Format",
"a",
"line",
"of",
"Matlab",
"into",
"either",
"a",
"markdown",
"line",
"or",
"a",
"code",
"line",
"."
] | train | https://github.com/arokem/python-matlab-bridge/blob/9822c7b55435662f4f033c5479cc03fea2255755/pymatbridge/publish.py#L11-L45 |
arokem/python-matlab-bridge | pymatbridge/publish.py | lines_to_notebook | def lines_to_notebook(lines, name=None):
"""
Convert the lines of an m file into an IPython notebook
Parameters
----------
lines : list
A list of strings. Each element is a line in the m file
Returns
-------
notebook : an IPython NotebookNode class instance, containing the
information required to create a file
"""
source = []
md = np.empty(len(lines), dtype=object)
new_cell = np.empty(len(lines), dtype=object)
for idx, l in enumerate(lines):
new_cell[idx], md[idx], this_source = format_line(l)
# Transitions between markdown and code and vice-versa merit a new
# cell, even if no newline, or "%%" is found. Make sure not to do this
# check for the very first line!
if idx>1 and not new_cell[idx]:
if md[idx] != md[idx-1]:
new_cell[idx] = True
source.append(this_source)
# This defines the breaking points between cells:
new_cell_idx = np.hstack([np.where(new_cell)[0], -1])
# Listify the sources:
cell_source = [source[new_cell_idx[i]:new_cell_idx[i+1]]
for i in range(len(new_cell_idx)-1)]
cell_md = [md[new_cell_idx[i]] for i in range(len(new_cell_idx)-1)]
cells = []
# Append the notebook with loading matlab magic extension
notebook_head = "import pymatbridge as pymat\n" + "ip = get_ipython()\n" \
+ "pymat.load_ipython_extension(ip)"
cells.append(nbformat.new_code_cell(notebook_head))#, language='python'))
for cell_idx, cell_s in enumerate(cell_source):
if cell_md[cell_idx]:
cells.append(nbformat.new_markdown_cell(cell_s))
else:
cell_s.insert(0, '%%matlab\n')
cells.append(nbformat.new_code_cell(cell_s))#, language='matlab'))
#ws = nbformat.new_worksheet(cells=cells)
notebook = nbformat.new_notebook(cells=cells)
return notebook | python | def lines_to_notebook(lines, name=None):
"""
Convert the lines of an m file into an IPython notebook
Parameters
----------
lines : list
A list of strings. Each element is a line in the m file
Returns
-------
notebook : an IPython NotebookNode class instance, containing the
information required to create a file
"""
source = []
md = np.empty(len(lines), dtype=object)
new_cell = np.empty(len(lines), dtype=object)
for idx, l in enumerate(lines):
new_cell[idx], md[idx], this_source = format_line(l)
# Transitions between markdown and code and vice-versa merit a new
# cell, even if no newline, or "%%" is found. Make sure not to do this
# check for the very first line!
if idx>1 and not new_cell[idx]:
if md[idx] != md[idx-1]:
new_cell[idx] = True
source.append(this_source)
# This defines the breaking points between cells:
new_cell_idx = np.hstack([np.where(new_cell)[0], -1])
# Listify the sources:
cell_source = [source[new_cell_idx[i]:new_cell_idx[i+1]]
for i in range(len(new_cell_idx)-1)]
cell_md = [md[new_cell_idx[i]] for i in range(len(new_cell_idx)-1)]
cells = []
# Append the notebook with loading matlab magic extension
notebook_head = "import pymatbridge as pymat\n" + "ip = get_ipython()\n" \
+ "pymat.load_ipython_extension(ip)"
cells.append(nbformat.new_code_cell(notebook_head))#, language='python'))
for cell_idx, cell_s in enumerate(cell_source):
if cell_md[cell_idx]:
cells.append(nbformat.new_markdown_cell(cell_s))
else:
cell_s.insert(0, '%%matlab\n')
cells.append(nbformat.new_code_cell(cell_s))#, language='matlab'))
#ws = nbformat.new_worksheet(cells=cells)
notebook = nbformat.new_notebook(cells=cells)
return notebook | [
"def",
"lines_to_notebook",
"(",
"lines",
",",
"name",
"=",
"None",
")",
":",
"source",
"=",
"[",
"]",
"md",
"=",
"np",
".",
"empty",
"(",
"len",
"(",
"lines",
")",
",",
"dtype",
"=",
"object",
")",
"new_cell",
"=",
"np",
".",
"empty",
"(",
"len"... | Convert the lines of an m file into an IPython notebook
Parameters
----------
lines : list
A list of strings. Each element is a line in the m file
Returns
-------
notebook : an IPython NotebookNode class instance, containing the
information required to create a file | [
"Convert",
"the",
"lines",
"of",
"an",
"m",
"file",
"into",
"an",
"IPython",
"notebook"
] | train | https://github.com/arokem/python-matlab-bridge/blob/9822c7b55435662f4f033c5479cc03fea2255755/pymatbridge/publish.py#L62-L114 |
arokem/python-matlab-bridge | pymatbridge/publish.py | convert_mfile | def convert_mfile(mfile, outfile=None):
"""
Convert a Matlab m-file into a Matlab notebook in ipynb format
Parameters
----------
mfile : string
Full path to a matlab m file to convert
outfile : string (optional)
Full path to the output ipynb file
"""
lines = mfile_to_lines(mfile)
nb = lines_to_notebook(lines)
if outfile is None:
outfile = mfile.split('.m')[0] + '.ipynb'
with open(outfile, 'w') as fid:
nbwrite(nb, fid) | python | def convert_mfile(mfile, outfile=None):
"""
Convert a Matlab m-file into a Matlab notebook in ipynb format
Parameters
----------
mfile : string
Full path to a matlab m file to convert
outfile : string (optional)
Full path to the output ipynb file
"""
lines = mfile_to_lines(mfile)
nb = lines_to_notebook(lines)
if outfile is None:
outfile = mfile.split('.m')[0] + '.ipynb'
with open(outfile, 'w') as fid:
nbwrite(nb, fid) | [
"def",
"convert_mfile",
"(",
"mfile",
",",
"outfile",
"=",
"None",
")",
":",
"lines",
"=",
"mfile_to_lines",
"(",
"mfile",
")",
"nb",
"=",
"lines_to_notebook",
"(",
"lines",
")",
"if",
"outfile",
"is",
"None",
":",
"outfile",
"=",
"mfile",
".",
"split",
... | Convert a Matlab m-file into a Matlab notebook in ipynb format
Parameters
----------
mfile : string
Full path to a matlab m file to convert
outfile : string (optional)
Full path to the output ipynb file | [
"Convert",
"a",
"Matlab",
"m",
"-",
"file",
"into",
"a",
"Matlab",
"notebook",
"in",
"ipynb",
"format"
] | train | https://github.com/arokem/python-matlab-bridge/blob/9822c7b55435662f4f033c5479cc03fea2255755/pymatbridge/publish.py#L117-L135 |
arokem/python-matlab-bridge | pymatbridge/matlab_magic.py | load_ipython_extension | def load_ipython_extension(ip, **kwargs):
"""Load the extension in IPython."""
global _loaded
if not _loaded:
ip.register_magics(MatlabMagics(ip, **kwargs))
_loaded = True | python | def load_ipython_extension(ip, **kwargs):
"""Load the extension in IPython."""
global _loaded
if not _loaded:
ip.register_magics(MatlabMagics(ip, **kwargs))
_loaded = True | [
"def",
"load_ipython_extension",
"(",
"ip",
",",
"*",
"*",
"kwargs",
")",
":",
"global",
"_loaded",
"if",
"not",
"_loaded",
":",
"ip",
".",
"register_magics",
"(",
"MatlabMagics",
"(",
"ip",
",",
"*",
"*",
"kwargs",
")",
")",
"_loaded",
"=",
"True"
] | Load the extension in IPython. | [
"Load",
"the",
"extension",
"in",
"IPython",
"."
] | train | https://github.com/arokem/python-matlab-bridge/blob/9822c7b55435662f4f033c5479cc03fea2255755/pymatbridge/matlab_magic.py#L205-L210 |
arokem/python-matlab-bridge | tools/gh_api.py | post_gist | def post_gist(content, description='', filename='file', auth=False):
"""Post some text to a Gist, and return the URL."""
post_data = json.dumps({
"description": description,
"public": True,
"files": {
filename: {
"content": content
}
}
}).encode('utf-8')
headers = make_auth_header() if auth else {}
response = requests.post("https://api.github.com/gists", data=post_data, headers=headers)
response.raise_for_status()
response_data = json.loads(response.text)
return response_data['html_url'] | python | def post_gist(content, description='', filename='file', auth=False):
"""Post some text to a Gist, and return the URL."""
post_data = json.dumps({
"description": description,
"public": True,
"files": {
filename: {
"content": content
}
}
}).encode('utf-8')
headers = make_auth_header() if auth else {}
response = requests.post("https://api.github.com/gists", data=post_data, headers=headers)
response.raise_for_status()
response_data = json.loads(response.text)
return response_data['html_url'] | [
"def",
"post_gist",
"(",
"content",
",",
"description",
"=",
"''",
",",
"filename",
"=",
"'file'",
",",
"auth",
"=",
"False",
")",
":",
"post_data",
"=",
"json",
".",
"dumps",
"(",
"{",
"\"description\"",
":",
"description",
",",
"\"public\"",
":",
"True... | Post some text to a Gist, and return the URL. | [
"Post",
"some",
"text",
"to",
"a",
"Gist",
"and",
"return",
"the",
"URL",
"."
] | train | https://github.com/arokem/python-matlab-bridge/blob/9822c7b55435662f4f033c5479cc03fea2255755/tools/gh_api.py#L80-L96 |
arokem/python-matlab-bridge | tools/gh_api.py | get_pull_request | def get_pull_request(project, num, auth=False):
"""get pull request info by number
"""
url = "https://api.github.com/repos/{project}/pulls/{num}".format(project=project, num=num)
if auth:
header = make_auth_header()
else:
header = None
response = requests.get(url, headers=header)
response.raise_for_status()
return json.loads(response.text, object_hook=Obj) | python | def get_pull_request(project, num, auth=False):
"""get pull request info by number
"""
url = "https://api.github.com/repos/{project}/pulls/{num}".format(project=project, num=num)
if auth:
header = make_auth_header()
else:
header = None
response = requests.get(url, headers=header)
response.raise_for_status()
return json.loads(response.text, object_hook=Obj) | [
"def",
"get_pull_request",
"(",
"project",
",",
"num",
",",
"auth",
"=",
"False",
")",
":",
"url",
"=",
"\"https://api.github.com/repos/{project}/pulls/{num}\"",
".",
"format",
"(",
"project",
"=",
"project",
",",
"num",
"=",
"num",
")",
"if",
"auth",
":",
"... | get pull request info by number | [
"get",
"pull",
"request",
"info",
"by",
"number"
] | train | https://github.com/arokem/python-matlab-bridge/blob/9822c7b55435662f4f033c5479cc03fea2255755/tools/gh_api.py#L98-L108 |
arokem/python-matlab-bridge | tools/gh_api.py | get_pull_request_files | def get_pull_request_files(project, num, auth=False):
"""get list of files in a pull request"""
url = "https://api.github.com/repos/{project}/pulls/{num}/files".format(project=project, num=num)
if auth:
header = make_auth_header()
else:
header = None
return get_paged_request(url, headers=header) | python | def get_pull_request_files(project, num, auth=False):
"""get list of files in a pull request"""
url = "https://api.github.com/repos/{project}/pulls/{num}/files".format(project=project, num=num)
if auth:
header = make_auth_header()
else:
header = None
return get_paged_request(url, headers=header) | [
"def",
"get_pull_request_files",
"(",
"project",
",",
"num",
",",
"auth",
"=",
"False",
")",
":",
"url",
"=",
"\"https://api.github.com/repos/{project}/pulls/{num}/files\"",
".",
"format",
"(",
"project",
"=",
"project",
",",
"num",
"=",
"num",
")",
"if",
"auth"... | get list of files in a pull request | [
"get",
"list",
"of",
"files",
"in",
"a",
"pull",
"request"
] | train | https://github.com/arokem/python-matlab-bridge/blob/9822c7b55435662f4f033c5479cc03fea2255755/tools/gh_api.py#L110-L117 |
arokem/python-matlab-bridge | tools/gh_api.py | get_paged_request | def get_paged_request(url, headers=None, **params):
"""get a full list, handling APIv3's paging"""
results = []
params.setdefault("per_page", 100)
while True:
if '?' in url:
params = None
print("fetching %s" % url, file=sys.stderr)
else:
print("fetching %s with %s" % (url, params), file=sys.stderr)
response = requests.get(url, headers=headers, params=params)
response.raise_for_status()
results.extend(response.json())
if 'next' in response.links:
url = response.links['next']['url']
else:
break
return results | python | def get_paged_request(url, headers=None, **params):
"""get a full list, handling APIv3's paging"""
results = []
params.setdefault("per_page", 100)
while True:
if '?' in url:
params = None
print("fetching %s" % url, file=sys.stderr)
else:
print("fetching %s with %s" % (url, params), file=sys.stderr)
response = requests.get(url, headers=headers, params=params)
response.raise_for_status()
results.extend(response.json())
if 'next' in response.links:
url = response.links['next']['url']
else:
break
return results | [
"def",
"get_paged_request",
"(",
"url",
",",
"headers",
"=",
"None",
",",
"*",
"*",
"params",
")",
":",
"results",
"=",
"[",
"]",
"params",
".",
"setdefault",
"(",
"\"per_page\"",
",",
"100",
")",
"while",
"True",
":",
"if",
"'?'",
"in",
"url",
":",
... | get a full list, handling APIv3's paging | [
"get",
"a",
"full",
"list",
"handling",
"APIv3",
"s",
"paging"
] | train | https://github.com/arokem/python-matlab-bridge/blob/9822c7b55435662f4f033c5479cc03fea2255755/tools/gh_api.py#L122-L139 |
arokem/python-matlab-bridge | tools/gh_api.py | get_pulls_list | def get_pulls_list(project, auth=False, **params):
"""get pull request list"""
params.setdefault("state", "closed")
url = "https://api.github.com/repos/{project}/pulls".format(project=project)
if auth:
headers = make_auth_header()
else:
headers = None
pages = get_paged_request(url, headers=headers, **params)
return pages | python | def get_pulls_list(project, auth=False, **params):
"""get pull request list"""
params.setdefault("state", "closed")
url = "https://api.github.com/repos/{project}/pulls".format(project=project)
if auth:
headers = make_auth_header()
else:
headers = None
pages = get_paged_request(url, headers=headers, **params)
return pages | [
"def",
"get_pulls_list",
"(",
"project",
",",
"auth",
"=",
"False",
",",
"*",
"*",
"params",
")",
":",
"params",
".",
"setdefault",
"(",
"\"state\"",
",",
"\"closed\"",
")",
"url",
"=",
"\"https://api.github.com/repos/{project}/pulls\"",
".",
"format",
"(",
"p... | get pull request list | [
"get",
"pull",
"request",
"list"
] | train | https://github.com/arokem/python-matlab-bridge/blob/9822c7b55435662f4f033c5479cc03fea2255755/tools/gh_api.py#L141-L150 |
arokem/python-matlab-bridge | tools/gh_api.py | encode_multipart_formdata | def encode_multipart_formdata(fields, boundary=None):
"""
Encode a dictionary of ``fields`` using the multipart/form-data mime format.
:param fields:
Dictionary of fields or list of (key, value) field tuples. The key is
treated as the field name, and the value as the body of the form-data
bytes. If the value is a tuple of two elements, then the first element
is treated as the filename of the form-data section.
Field names and filenames must be unicode.
:param boundary:
If not specified, then a random boundary will be generated using
:func:`mimetools.choose_boundary`.
"""
# copy requests imports in here:
from io import BytesIO
from requests.packages.urllib3.filepost import (
choose_boundary, six, writer, b, get_content_type
)
body = BytesIO()
if boundary is None:
boundary = choose_boundary()
for fieldname, value in iter_fields(fields):
body.write(b('--%s\r\n' % (boundary)))
if isinstance(value, tuple):
filename, data = value
writer(body).write('Content-Disposition: form-data; name="%s"; '
'filename="%s"\r\n' % (fieldname, filename))
body.write(b('Content-Type: %s\r\n\r\n' %
(get_content_type(filename))))
else:
data = value
writer(body).write('Content-Disposition: form-data; name="%s"\r\n'
% (fieldname))
body.write(b'Content-Type: text/plain\r\n\r\n')
if isinstance(data, int):
data = str(data) # Backwards compatibility
if isinstance(data, six.text_type):
writer(body).write(data)
else:
body.write(data)
body.write(b'\r\n')
body.write(b('--%s--\r\n' % (boundary)))
content_type = b('multipart/form-data; boundary=%s' % boundary)
return body.getvalue(), content_type | python | def encode_multipart_formdata(fields, boundary=None):
"""
Encode a dictionary of ``fields`` using the multipart/form-data mime format.
:param fields:
Dictionary of fields or list of (key, value) field tuples. The key is
treated as the field name, and the value as the body of the form-data
bytes. If the value is a tuple of two elements, then the first element
is treated as the filename of the form-data section.
Field names and filenames must be unicode.
:param boundary:
If not specified, then a random boundary will be generated using
:func:`mimetools.choose_boundary`.
"""
# copy requests imports in here:
from io import BytesIO
from requests.packages.urllib3.filepost import (
choose_boundary, six, writer, b, get_content_type
)
body = BytesIO()
if boundary is None:
boundary = choose_boundary()
for fieldname, value in iter_fields(fields):
body.write(b('--%s\r\n' % (boundary)))
if isinstance(value, tuple):
filename, data = value
writer(body).write('Content-Disposition: form-data; name="%s"; '
'filename="%s"\r\n' % (fieldname, filename))
body.write(b('Content-Type: %s\r\n\r\n' %
(get_content_type(filename))))
else:
data = value
writer(body).write('Content-Disposition: form-data; name="%s"\r\n'
% (fieldname))
body.write(b'Content-Type: text/plain\r\n\r\n')
if isinstance(data, int):
data = str(data) # Backwards compatibility
if isinstance(data, six.text_type):
writer(body).write(data)
else:
body.write(data)
body.write(b'\r\n')
body.write(b('--%s--\r\n' % (boundary)))
content_type = b('multipart/form-data; boundary=%s' % boundary)
return body.getvalue(), content_type | [
"def",
"encode_multipart_formdata",
"(",
"fields",
",",
"boundary",
"=",
"None",
")",
":",
"# copy requests imports in here:",
"from",
"io",
"import",
"BytesIO",
"from",
"requests",
".",
"packages",
".",
"urllib3",
".",
"filepost",
"import",
"(",
"choose_boundary",
... | Encode a dictionary of ``fields`` using the multipart/form-data mime format.
:param fields:
Dictionary of fields or list of (key, value) field tuples. The key is
treated as the field name, and the value as the body of the form-data
bytes. If the value is a tuple of two elements, then the first element
is treated as the filename of the form-data section.
Field names and filenames must be unicode.
:param boundary:
If not specified, then a random boundary will be generated using
:func:`mimetools.choose_boundary`. | [
"Encode",
"a",
"dictionary",
"of",
"fields",
"using",
"the",
"multipart",
"/",
"form",
"-",
"data",
"mime",
"format",
"."
] | train | https://github.com/arokem/python-matlab-bridge/blob/9822c7b55435662f4f033c5479cc03fea2255755/tools/gh_api.py#L207-L260 |
arokem/python-matlab-bridge | tools/gh_api.py | post_download | def post_download(project, filename, name=None, description=""):
"""Upload a file to the GitHub downloads area"""
if name is None:
name = os.path.basename(filename)
with open(filename, 'rb') as f:
filedata = f.read()
url = "https://api.github.com/repos/{project}/downloads".format(project=project)
payload = json.dumps(dict(name=name, size=len(filedata),
description=description))
response = requests.post(url, data=payload, headers=make_auth_header())
response.raise_for_status()
reply = json.loads(response.content)
s3_url = reply['s3_url']
fields = dict(
key=reply['path'],
acl=reply['acl'],
success_action_status=201,
Filename=reply['name'],
AWSAccessKeyId=reply['accesskeyid'],
Policy=reply['policy'],
Signature=reply['signature'],
file=(reply['name'], filedata),
)
fields['Content-Type'] = reply['mime_type']
data, content_type = encode_multipart_formdata(fields)
s3r = requests.post(s3_url, data=data, headers={'Content-Type': content_type})
return s3r | python | def post_download(project, filename, name=None, description=""):
"""Upload a file to the GitHub downloads area"""
if name is None:
name = os.path.basename(filename)
with open(filename, 'rb') as f:
filedata = f.read()
url = "https://api.github.com/repos/{project}/downloads".format(project=project)
payload = json.dumps(dict(name=name, size=len(filedata),
description=description))
response = requests.post(url, data=payload, headers=make_auth_header())
response.raise_for_status()
reply = json.loads(response.content)
s3_url = reply['s3_url']
fields = dict(
key=reply['path'],
acl=reply['acl'],
success_action_status=201,
Filename=reply['name'],
AWSAccessKeyId=reply['accesskeyid'],
Policy=reply['policy'],
Signature=reply['signature'],
file=(reply['name'], filedata),
)
fields['Content-Type'] = reply['mime_type']
data, content_type = encode_multipart_formdata(fields)
s3r = requests.post(s3_url, data=data, headers={'Content-Type': content_type})
return s3r | [
"def",
"post_download",
"(",
"project",
",",
"filename",
",",
"name",
"=",
"None",
",",
"description",
"=",
"\"\"",
")",
":",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"filename",
")",
"with",
"open",
"(",... | Upload a file to the GitHub downloads area | [
"Upload",
"a",
"file",
"to",
"the",
"GitHub",
"downloads",
"area"
] | train | https://github.com/arokem/python-matlab-bridge/blob/9822c7b55435662f4f033c5479cc03fea2255755/tools/gh_api.py#L263-L292 |
arokem/python-matlab-bridge | pymatbridge/messenger/make.py | is_executable_file | def is_executable_file(path):
"""Checks that path is an executable regular file (or a symlink to a file).
This is roughly ``os.path isfile(path) and os.access(path, os.X_OK)``, but
on some platforms :func:`os.access` gives us the wrong answer, so this
checks permission bits directly.
Note
----
This function is taken from the pexpect module, see module doc-string for
license.
"""
# follow symlinks,
fpath = os.path.realpath(path)
# return False for non-files (directories, fifo, etc.)
if not os.path.isfile(fpath):
return False
# On Solaris, etc., "If the process has appropriate privileges, an
# implementation may indicate success for X_OK even if none of the
# execute file permission bits are set."
#
# For this reason, it is necessary to explicitly check st_mode
# get file mode using os.stat, and check if `other',
# that is anybody, may read and execute.
mode = os.stat(fpath).st_mode
if mode & stat.S_IROTH and mode & stat.S_IXOTH:
return True
# get current user's group ids, and check if `group',
# when matching ours, may read and execute.
user_gids = os.getgroups() + [os.getgid()]
if (os.stat(fpath).st_gid in user_gids and
mode & stat.S_IRGRP and mode & stat.S_IXGRP):
return True
# finally, if file owner matches our effective userid,
# check if `user', may read and execute.
user_gids = os.getgroups() + [os.getgid()]
if (os.stat(fpath).st_uid == os.geteuid() and
mode & stat.S_IRUSR and mode & stat.S_IXUSR):
return True
return False | python | def is_executable_file(path):
"""Checks that path is an executable regular file (or a symlink to a file).
This is roughly ``os.path isfile(path) and os.access(path, os.X_OK)``, but
on some platforms :func:`os.access` gives us the wrong answer, so this
checks permission bits directly.
Note
----
This function is taken from the pexpect module, see module doc-string for
license.
"""
# follow symlinks,
fpath = os.path.realpath(path)
# return False for non-files (directories, fifo, etc.)
if not os.path.isfile(fpath):
return False
# On Solaris, etc., "If the process has appropriate privileges, an
# implementation may indicate success for X_OK even if none of the
# execute file permission bits are set."
#
# For this reason, it is necessary to explicitly check st_mode
# get file mode using os.stat, and check if `other',
# that is anybody, may read and execute.
mode = os.stat(fpath).st_mode
if mode & stat.S_IROTH and mode & stat.S_IXOTH:
return True
# get current user's group ids, and check if `group',
# when matching ours, may read and execute.
user_gids = os.getgroups() + [os.getgid()]
if (os.stat(fpath).st_gid in user_gids and
mode & stat.S_IRGRP and mode & stat.S_IXGRP):
return True
# finally, if file owner matches our effective userid,
# check if `user', may read and execute.
user_gids = os.getgroups() + [os.getgid()]
if (os.stat(fpath).st_uid == os.geteuid() and
mode & stat.S_IRUSR and mode & stat.S_IXUSR):
return True
return False | [
"def",
"is_executable_file",
"(",
"path",
")",
":",
"# follow symlinks,",
"fpath",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"path",
")",
"# return False for non-files (directories, fifo, etc.)",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"fpath",
"... | Checks that path is an executable regular file (or a symlink to a file).
This is roughly ``os.path isfile(path) and os.access(path, os.X_OK)``, but
on some platforms :func:`os.access` gives us the wrong answer, so this
checks permission bits directly.
Note
----
This function is taken from the pexpect module, see module doc-string for
license. | [
"Checks",
"that",
"path",
"is",
"an",
"executable",
"regular",
"file",
"(",
"or",
"a",
"symlink",
"to",
"a",
"file",
")",
"."
] | train | https://github.com/arokem/python-matlab-bridge/blob/9822c7b55435662f4f033c5479cc03fea2255755/pymatbridge/messenger/make.py#L40-L85 |
arokem/python-matlab-bridge | pymatbridge/messenger/make.py | which | def which(filename):
'''This takes a given filename; tries to find it in the environment path;
then checks if it is executable. This returns the full path to the filename
if found and executable. Otherwise this returns None.
Note
----
This function is taken from the pexpect module, see module doc-string for
license.
'''
# Special case where filename contains an explicit path.
if os.path.dirname(filename) != '' and is_executable_file(filename):
return filename
if 'PATH' not in os.environ or os.environ['PATH'] == '':
p = os.defpath
else:
p = os.environ['PATH']
pathlist = p.split(os.pathsep)
for path in pathlist:
ff = os.path.join(path, filename)
if pty:
if is_executable_file(ff):
return ff
else:
pathext = os.environ.get('Pathext', '.exe;.com;.bat;.cmd')
pathext = pathext.split(os.pathsep) + ['']
for ext in pathext:
if os.access(ff + ext, os.X_OK):
return ff + ext
return None | python | def which(filename):
'''This takes a given filename; tries to find it in the environment path;
then checks if it is executable. This returns the full path to the filename
if found and executable. Otherwise this returns None.
Note
----
This function is taken from the pexpect module, see module doc-string for
license.
'''
# Special case where filename contains an explicit path.
if os.path.dirname(filename) != '' and is_executable_file(filename):
return filename
if 'PATH' not in os.environ or os.environ['PATH'] == '':
p = os.defpath
else:
p = os.environ['PATH']
pathlist = p.split(os.pathsep)
for path in pathlist:
ff = os.path.join(path, filename)
if pty:
if is_executable_file(ff):
return ff
else:
pathext = os.environ.get('Pathext', '.exe;.com;.bat;.cmd')
pathext = pathext.split(os.pathsep) + ['']
for ext in pathext:
if os.access(ff + ext, os.X_OK):
return ff + ext
return None | [
"def",
"which",
"(",
"filename",
")",
":",
"# Special case where filename contains an explicit path.",
"if",
"os",
".",
"path",
".",
"dirname",
"(",
"filename",
")",
"!=",
"''",
"and",
"is_executable_file",
"(",
"filename",
")",
":",
"return",
"filename",
"if",
... | This takes a given filename; tries to find it in the environment path;
then checks if it is executable. This returns the full path to the filename
if found and executable. Otherwise this returns None.
Note
----
This function is taken from the pexpect module, see module doc-string for
license. | [
"This",
"takes",
"a",
"given",
"filename",
";",
"tries",
"to",
"find",
"it",
"in",
"the",
"environment",
"path",
";",
"then",
"checks",
"if",
"it",
"is",
"executable",
".",
"This",
"returns",
"the",
"full",
"path",
"to",
"the",
"filename",
"if",
"found",... | train | https://github.com/arokem/python-matlab-bridge/blob/9822c7b55435662f4f033c5479cc03fea2255755/pymatbridge/messenger/make.py#L88-L118 |
arokem/python-matlab-bridge | pymatbridge/messenger/make.py | build_matlab | def build_matlab(static=False):
"""build the messenger mex for MATLAB
static : bool
Determines if the zmq library has been statically linked.
If so, it will append the command line option -DZMQ_STATIC
when compiling the mex so it matches libzmq.
"""
cfg = get_config()
# To deal with spaces, remove quotes now, and add
# to the full commands themselves.
if 'matlab_bin' in cfg and cfg['matlab_bin'] != '.':
matlab_bin = cfg['matlab_bin'].strip('"')
else: # attempt to autodetect MATLAB filepath
matlab_bin = which_matlab()
if matlab_bin is None:
raise ValueError("specify 'matlab_bin' in cfg file")
# Get the extension
extcmd = esc(os.path.join(matlab_bin, "mexext"))
extension = subprocess.check_output(extcmd, shell=use_shell)
extension = extension.decode('utf-8').rstrip('\r\n')
# Build the mex file
mex = esc(os.path.join(matlab_bin, "mex"))
paths = "-L%(zmq_lib)s -I%(zmq_inc)s" % cfg
make_cmd = '%s -O %s -lzmq ./src/messenger.c' % (mex, paths)
if static:
make_cmd += ' -DZMQ_STATIC'
do_build(make_cmd, 'messenger.%s' % extension) | python | def build_matlab(static=False):
"""build the messenger mex for MATLAB
static : bool
Determines if the zmq library has been statically linked.
If so, it will append the command line option -DZMQ_STATIC
when compiling the mex so it matches libzmq.
"""
cfg = get_config()
# To deal with spaces, remove quotes now, and add
# to the full commands themselves.
if 'matlab_bin' in cfg and cfg['matlab_bin'] != '.':
matlab_bin = cfg['matlab_bin'].strip('"')
else: # attempt to autodetect MATLAB filepath
matlab_bin = which_matlab()
if matlab_bin is None:
raise ValueError("specify 'matlab_bin' in cfg file")
# Get the extension
extcmd = esc(os.path.join(matlab_bin, "mexext"))
extension = subprocess.check_output(extcmd, shell=use_shell)
extension = extension.decode('utf-8').rstrip('\r\n')
# Build the mex file
mex = esc(os.path.join(matlab_bin, "mex"))
paths = "-L%(zmq_lib)s -I%(zmq_inc)s" % cfg
make_cmd = '%s -O %s -lzmq ./src/messenger.c' % (mex, paths)
if static:
make_cmd += ' -DZMQ_STATIC'
do_build(make_cmd, 'messenger.%s' % extension) | [
"def",
"build_matlab",
"(",
"static",
"=",
"False",
")",
":",
"cfg",
"=",
"get_config",
"(",
")",
"# To deal with spaces, remove quotes now, and add",
"# to the full commands themselves.",
"if",
"'matlab_bin'",
"in",
"cfg",
"and",
"cfg",
"[",
"'matlab_bin'",
"]",
"!="... | build the messenger mex for MATLAB
static : bool
Determines if the zmq library has been statically linked.
If so, it will append the command line option -DZMQ_STATIC
when compiling the mex so it matches libzmq. | [
"build",
"the",
"messenger",
"mex",
"for",
"MATLAB"
] | train | https://github.com/arokem/python-matlab-bridge/blob/9822c7b55435662f4f033c5479cc03fea2255755/pymatbridge/messenger/make.py#L242-L270 |
sixty-north/asq | asq/extension.py | add_method | def add_method(function, klass, name=None):
'''Add an existing function to a class as a method.
Note: Consider using the extend decorator as a more readable alternative
to using this function directly.
Args:
function: The function to be added to the class klass.
klass: The class to which the new method will be added.
name: An optional name for the new method. If omitted or None the
original name of the function is used.
Returns:
The function argument unmodified.
Raises:
ValueError: If klass already has an attribute with the same name as the
extension method.
'''
# Should we be using functools.update_wrapper in here?
if name is None:
name = function_name(function)
if hasattr(klass, name):
raise ValueError("Cannot replace existing attribute with method "
"'{name}'".format(name=name))
setattr(klass, name, function)
return function | python | def add_method(function, klass, name=None):
'''Add an existing function to a class as a method.
Note: Consider using the extend decorator as a more readable alternative
to using this function directly.
Args:
function: The function to be added to the class klass.
klass: The class to which the new method will be added.
name: An optional name for the new method. If omitted or None the
original name of the function is used.
Returns:
The function argument unmodified.
Raises:
ValueError: If klass already has an attribute with the same name as the
extension method.
'''
# Should we be using functools.update_wrapper in here?
if name is None:
name = function_name(function)
if hasattr(klass, name):
raise ValueError("Cannot replace existing attribute with method "
"'{name}'".format(name=name))
setattr(klass, name, function)
return function | [
"def",
"add_method",
"(",
"function",
",",
"klass",
",",
"name",
"=",
"None",
")",
":",
"# Should we be using functools.update_wrapper in here?\r",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"function_name",
"(",
"function",
")",
"if",
"hasattr",
"(",
"klass"... | Add an existing function to a class as a method.
Note: Consider using the extend decorator as a more readable alternative
to using this function directly.
Args:
function: The function to be added to the class klass.
klass: The class to which the new method will be added.
name: An optional name for the new method. If omitted or None the
original name of the function is used.
Returns:
The function argument unmodified.
Raises:
ValueError: If klass already has an attribute with the same name as the
extension method. | [
"Add",
"an",
"existing",
"function",
"to",
"a",
"class",
"as",
"a",
"method",
".",
"Note",
":",
"Consider",
"using",
"the",
"extend",
"decorator",
"as",
"a",
"more",
"readable",
"alternative",
"to",
"using",
"this",
"function",
"directly",
".",
"Args",
":"... | train | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/extension.py#L8-L36 |
sixty-north/asq | asq/extension.py | extend | def extend(klass, name=None):
'''A function decorator for extending an existing class.
Use as a decorator for functions to add to an existing class.
Args:
klass: The class to be decorated.
name: The name the new method is to be given in the klass class.
Returns:
A decorator function which accepts a single function as its only
argument. The decorated function will be added to class klass.
Raises:
ValueError: If klass already has an attribute with the same name as the
extension method.
'''
def decorator(f):
return add_method(f, klass, name)
return decorator | python | def extend(klass, name=None):
'''A function decorator for extending an existing class.
Use as a decorator for functions to add to an existing class.
Args:
klass: The class to be decorated.
name: The name the new method is to be given in the klass class.
Returns:
A decorator function which accepts a single function as its only
argument. The decorated function will be added to class klass.
Raises:
ValueError: If klass already has an attribute with the same name as the
extension method.
'''
def decorator(f):
return add_method(f, klass, name)
return decorator | [
"def",
"extend",
"(",
"klass",
",",
"name",
"=",
"None",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"return",
"add_method",
"(",
"f",
",",
"klass",
",",
"name",
")",
"return",
"decorator"
] | A function decorator for extending an existing class.
Use as a decorator for functions to add to an existing class.
Args:
klass: The class to be decorated.
name: The name the new method is to be given in the klass class.
Returns:
A decorator function which accepts a single function as its only
argument. The decorated function will be added to class klass.
Raises:
ValueError: If klass already has an attribute with the same name as the
extension method. | [
"A",
"function",
"decorator",
"for",
"extending",
"an",
"existing",
"class",
".",
"Use",
"as",
"a",
"decorator",
"for",
"functions",
"to",
"add",
"to",
"an",
"existing",
"class",
".",
"Args",
":",
"klass",
":",
"The",
"class",
"to",
"be",
"decorated",
".... | train | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/extension.py#L39-L60 |
sixty-north/asq | asq/queryables.py | Queryable.select | def select(
self,
selector):
'''Transforms each element of a sequence into a new form.
Each element of the source is transformed through a selector function
to produce a corresponding element in teh result sequence.
If the selector is identity the method will return self.
Note: This method uses deferred execution.
Args:
selector: A unary function mapping a value in the source sequence
to the corresponding value in the generated generated sequence.
The single positional argument to the selector function is the
element value. The return value of the selector function
should be the corresponding element of the result sequence.
Returns:
A Queryable over generated sequence whose elements are the result
of invoking the selector function on each element of the source
sequence.
Raises:
ValueError: If this Queryable has been closed.
TypeError: If selector is not callable.
'''
if self.closed():
raise ValueError("Attempt to call select() on a closed Queryable.")
try:
selector = make_selector(selector)
except ValueError:
raise TypeError("select() parameter selector={selector} cannot be"
"converted into a callable "
"selector".format(selector=repr(selector)))
if selector is identity:
return self
return self._create(imap(selector, self)) | python | def select(
self,
selector):
'''Transforms each element of a sequence into a new form.
Each element of the source is transformed through a selector function
to produce a corresponding element in teh result sequence.
If the selector is identity the method will return self.
Note: This method uses deferred execution.
Args:
selector: A unary function mapping a value in the source sequence
to the corresponding value in the generated generated sequence.
The single positional argument to the selector function is the
element value. The return value of the selector function
should be the corresponding element of the result sequence.
Returns:
A Queryable over generated sequence whose elements are the result
of invoking the selector function on each element of the source
sequence.
Raises:
ValueError: If this Queryable has been closed.
TypeError: If selector is not callable.
'''
if self.closed():
raise ValueError("Attempt to call select() on a closed Queryable.")
try:
selector = make_selector(selector)
except ValueError:
raise TypeError("select() parameter selector={selector} cannot be"
"converted into a callable "
"selector".format(selector=repr(selector)))
if selector is identity:
return self
return self._create(imap(selector, self)) | [
"def",
"select",
"(",
"self",
",",
"selector",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call select() on a closed Queryable.\"",
")",
"try",
":",
"selector",
"=",
"make_selector",
"(",
"selector",
")",
"ex... | Transforms each element of a sequence into a new form.
Each element of the source is transformed through a selector function
to produce a corresponding element in teh result sequence.
If the selector is identity the method will return self.
Note: This method uses deferred execution.
Args:
selector: A unary function mapping a value in the source sequence
to the corresponding value in the generated generated sequence.
The single positional argument to the selector function is the
element value. The return value of the selector function
should be the corresponding element of the result sequence.
Returns:
A Queryable over generated sequence whose elements are the result
of invoking the selector function on each element of the source
sequence.
Raises:
ValueError: If this Queryable has been closed.
TypeError: If selector is not callable. | [
"Transforms",
"each",
"element",
"of",
"a",
"sequence",
"into",
"a",
"new",
"form",
"."
] | train | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L151-L192 |
sixty-north/asq | asq/queryables.py | Queryable.select_with_index | def select_with_index(
self,
selector=IndexedElement,
transform=identity):
'''Transforms each element of a sequence into a new form, incorporating
the index of the element.
Each element is transformed through a selector function which accepts
the element value and its zero-based index in the source sequence. The
generated sequence is lazily evaluated.
Note: This method uses deferred execution.
Args:
selector: A binary function mapping the index of a value in
the source sequence and the element value itself to the
corresponding value in the generated sequence. The two
positional arguments of the selector function are the zero-
based index of the current element and the value of the current
element. The return value should be the corresponding value in
the result sequence. The default selector produces an IndexedElement
containing the index and the element giving this function
similar behaviour to the built-in enumerate().
Returns:
A Queryable whose elements are the result of invoking the selector
function on each element of the source sequence
Raises:
ValueError: If this Queryable has been closed.
TypeError: If selector is not callable.
'''
if self.closed():
raise ValueError("Attempt to call select_with_index() on a "
"closed Queryable.")
if not is_callable(selector):
raise TypeError("select_with_index() parameter selector={0} is "
"not callable".format(repr(selector)))
if not is_callable(transform):
raise TypeError("select_with_index() parameter item_selector={0} is "
"not callable".format(repr(selector)))
return self._create(itertools.starmap(selector, enumerate(imap(transform, iter(self))))) | python | def select_with_index(
self,
selector=IndexedElement,
transform=identity):
'''Transforms each element of a sequence into a new form, incorporating
the index of the element.
Each element is transformed through a selector function which accepts
the element value and its zero-based index in the source sequence. The
generated sequence is lazily evaluated.
Note: This method uses deferred execution.
Args:
selector: A binary function mapping the index of a value in
the source sequence and the element value itself to the
corresponding value in the generated sequence. The two
positional arguments of the selector function are the zero-
based index of the current element and the value of the current
element. The return value should be the corresponding value in
the result sequence. The default selector produces an IndexedElement
containing the index and the element giving this function
similar behaviour to the built-in enumerate().
Returns:
A Queryable whose elements are the result of invoking the selector
function on each element of the source sequence
Raises:
ValueError: If this Queryable has been closed.
TypeError: If selector is not callable.
'''
if self.closed():
raise ValueError("Attempt to call select_with_index() on a "
"closed Queryable.")
if not is_callable(selector):
raise TypeError("select_with_index() parameter selector={0} is "
"not callable".format(repr(selector)))
if not is_callable(transform):
raise TypeError("select_with_index() parameter item_selector={0} is "
"not callable".format(repr(selector)))
return self._create(itertools.starmap(selector, enumerate(imap(transform, iter(self))))) | [
"def",
"select_with_index",
"(",
"self",
",",
"selector",
"=",
"IndexedElement",
",",
"transform",
"=",
"identity",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call select_with_index() on a \"",
"\"closed Queryable... | Transforms each element of a sequence into a new form, incorporating
the index of the element.
Each element is transformed through a selector function which accepts
the element value and its zero-based index in the source sequence. The
generated sequence is lazily evaluated.
Note: This method uses deferred execution.
Args:
selector: A binary function mapping the index of a value in
the source sequence and the element value itself to the
corresponding value in the generated sequence. The two
positional arguments of the selector function are the zero-
based index of the current element and the value of the current
element. The return value should be the corresponding value in
the result sequence. The default selector produces an IndexedElement
containing the index and the element giving this function
similar behaviour to the built-in enumerate().
Returns:
A Queryable whose elements are the result of invoking the selector
function on each element of the source sequence
Raises:
ValueError: If this Queryable has been closed.
TypeError: If selector is not callable. | [
"Transforms",
"each",
"element",
"of",
"a",
"sequence",
"into",
"a",
"new",
"form",
"incorporating",
"the",
"index",
"of",
"the",
"element",
"."
] | train | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L194-L238 |
sixty-north/asq | asq/queryables.py | Queryable.select_with_correspondence | def select_with_correspondence(
self,
selector,
result_selector=KeyedElement):
'''Apply a callable to each element in an input sequence, generating a new
sequence of 2-tuples where the first element is the input value and the
second is the transformed input value.
The generated sequence is lazily evaluated.
Note: This method uses deferred execution.
Args:
selector: A unary function mapping a value in the source sequence
to the second argument of the result selector.
result_selector: A binary callable mapping the of a value in
the source sequence and the transformed value to the
corresponding value in the generated sequence. The two
positional arguments of the selector function are the original
source element and the transformed value. The return value
should be the corresponding value in the result sequence. The
default selector produces a KeyedElement containing the index
and the element giving this function similar behaviour to the
built-in enumerate().
Returns:
When using the default selector, a Queryable whose elements are
KeyedElements where the first element is from the input sequence
and the second is the result of invoking the transform function on
the first value.
Raises:
ValueError: If this Queryable has been closed.
TypeError: If transform is not callable.
'''
if self.closed():
raise ValueError("Attempt to call select_with_correspondence() on a "
"closed Queryable.")
if not is_callable(selector):
raise TypeError("select_with_correspondence() parameter selector={0} is "
"not callable".format(repr(selector)))
if not is_callable(result_selector):
raise TypeError("select_with_correspondence() parameter result_selector={0} is "
"not callable".format(repr(result_selector)))
return self._create(result_selector(elem, selector(elem)) for elem in iter(self)) | python | def select_with_correspondence(
self,
selector,
result_selector=KeyedElement):
'''Apply a callable to each element in an input sequence, generating a new
sequence of 2-tuples where the first element is the input value and the
second is the transformed input value.
The generated sequence is lazily evaluated.
Note: This method uses deferred execution.
Args:
selector: A unary function mapping a value in the source sequence
to the second argument of the result selector.
result_selector: A binary callable mapping the of a value in
the source sequence and the transformed value to the
corresponding value in the generated sequence. The two
positional arguments of the selector function are the original
source element and the transformed value. The return value
should be the corresponding value in the result sequence. The
default selector produces a KeyedElement containing the index
and the element giving this function similar behaviour to the
built-in enumerate().
Returns:
When using the default selector, a Queryable whose elements are
KeyedElements where the first element is from the input sequence
and the second is the result of invoking the transform function on
the first value.
Raises:
ValueError: If this Queryable has been closed.
TypeError: If transform is not callable.
'''
if self.closed():
raise ValueError("Attempt to call select_with_correspondence() on a "
"closed Queryable.")
if not is_callable(selector):
raise TypeError("select_with_correspondence() parameter selector={0} is "
"not callable".format(repr(selector)))
if not is_callable(result_selector):
raise TypeError("select_with_correspondence() parameter result_selector={0} is "
"not callable".format(repr(result_selector)))
return self._create(result_selector(elem, selector(elem)) for elem in iter(self)) | [
"def",
"select_with_correspondence",
"(",
"self",
",",
"selector",
",",
"result_selector",
"=",
"KeyedElement",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call select_with_correspondence() on a \"",
"\"closed Queryabl... | Apply a callable to each element in an input sequence, generating a new
sequence of 2-tuples where the first element is the input value and the
second is the transformed input value.
The generated sequence is lazily evaluated.
Note: This method uses deferred execution.
Args:
selector: A unary function mapping a value in the source sequence
to the second argument of the result selector.
result_selector: A binary callable mapping the of a value in
the source sequence and the transformed value to the
corresponding value in the generated sequence. The two
positional arguments of the selector function are the original
source element and the transformed value. The return value
should be the corresponding value in the result sequence. The
default selector produces a KeyedElement containing the index
and the element giving this function similar behaviour to the
built-in enumerate().
Returns:
When using the default selector, a Queryable whose elements are
KeyedElements where the first element is from the input sequence
and the second is the result of invoking the transform function on
the first value.
Raises:
ValueError: If this Queryable has been closed.
TypeError: If transform is not callable. | [
"Apply",
"a",
"callable",
"to",
"each",
"element",
"in",
"an",
"input",
"sequence",
"generating",
"a",
"new",
"sequence",
"of",
"2",
"-",
"tuples",
"where",
"the",
"first",
"element",
"is",
"the",
"input",
"value",
"and",
"the",
"second",
"is",
"the",
"t... | train | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L240-L289 |
sixty-north/asq | asq/queryables.py | Queryable.select_many | def select_many(
self,
collection_selector=identity,
result_selector=identity):
'''Projects each element of a sequence to an intermediate new sequence,
flattens the resulting sequences into one sequence and optionally
transforms the flattened sequence using a selector function.
Note: This method uses deferred execution.
Args:
collection_selector: A unary function mapping each element of the
source iterable into an intermediate sequence. The single
argument of the collection_selector is the value of an element
from the source sequence. The return value should be an
iterable derived from that element value. The default
collection_selector, which is the identity function, assumes
that each element of the source sequence is itself iterable.
result_selector: An optional unary function mapping the elements in
the flattened intermediate sequence to corresponding elements
of the result sequence. The single argument of the
result_selector is the value of an element from the flattened
intermediate sequence. The return value should be the
corresponding value in the result sequence. The default
result_selector is the identity function.
Returns:
A Queryable over a generated sequence whose elements are the result
of applying the one-to-many collection_selector to each element of
the source sequence, concatenating the results into an intermediate
sequence, and then mapping each of those elements through the
result_selector into the result sequence.
Raises:
ValueError: If this Queryable has been closed.
TypeError: If either collection_selector or result_selector are not
callable.
'''
if self.closed():
raise ValueError("Attempt to call select_many() on a closed "
"Queryable.")
if not is_callable(collection_selector):
raise TypeError("select_many() parameter projector={0} is not "
"callable".format(repr(collection_selector)))
if not is_callable(result_selector):
raise TypeError("select_many() parameter selector={selector} is "
" not callable".format(selector=repr(result_selector)))
sequences = self.select(collection_selector)
chained_sequence = itertools.chain.from_iterable(sequences)
return self._create(chained_sequence).select(result_selector) | python | def select_many(
self,
collection_selector=identity,
result_selector=identity):
'''Projects each element of a sequence to an intermediate new sequence,
flattens the resulting sequences into one sequence and optionally
transforms the flattened sequence using a selector function.
Note: This method uses deferred execution.
Args:
collection_selector: A unary function mapping each element of the
source iterable into an intermediate sequence. The single
argument of the collection_selector is the value of an element
from the source sequence. The return value should be an
iterable derived from that element value. The default
collection_selector, which is the identity function, assumes
that each element of the source sequence is itself iterable.
result_selector: An optional unary function mapping the elements in
the flattened intermediate sequence to corresponding elements
of the result sequence. The single argument of the
result_selector is the value of an element from the flattened
intermediate sequence. The return value should be the
corresponding value in the result sequence. The default
result_selector is the identity function.
Returns:
A Queryable over a generated sequence whose elements are the result
of applying the one-to-many collection_selector to each element of
the source sequence, concatenating the results into an intermediate
sequence, and then mapping each of those elements through the
result_selector into the result sequence.
Raises:
ValueError: If this Queryable has been closed.
TypeError: If either collection_selector or result_selector are not
callable.
'''
if self.closed():
raise ValueError("Attempt to call select_many() on a closed "
"Queryable.")
if not is_callable(collection_selector):
raise TypeError("select_many() parameter projector={0} is not "
"callable".format(repr(collection_selector)))
if not is_callable(result_selector):
raise TypeError("select_many() parameter selector={selector} is "
" not callable".format(selector=repr(result_selector)))
sequences = self.select(collection_selector)
chained_sequence = itertools.chain.from_iterable(sequences)
return self._create(chained_sequence).select(result_selector) | [
"def",
"select_many",
"(",
"self",
",",
"collection_selector",
"=",
"identity",
",",
"result_selector",
"=",
"identity",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call select_many() on a closed \"",
"\"Queryable.... | Projects each element of a sequence to an intermediate new sequence,
flattens the resulting sequences into one sequence and optionally
transforms the flattened sequence using a selector function.
Note: This method uses deferred execution.
Args:
collection_selector: A unary function mapping each element of the
source iterable into an intermediate sequence. The single
argument of the collection_selector is the value of an element
from the source sequence. The return value should be an
iterable derived from that element value. The default
collection_selector, which is the identity function, assumes
that each element of the source sequence is itself iterable.
result_selector: An optional unary function mapping the elements in
the flattened intermediate sequence to corresponding elements
of the result sequence. The single argument of the
result_selector is the value of an element from the flattened
intermediate sequence. The return value should be the
corresponding value in the result sequence. The default
result_selector is the identity function.
Returns:
A Queryable over a generated sequence whose elements are the result
of applying the one-to-many collection_selector to each element of
the source sequence, concatenating the results into an intermediate
sequence, and then mapping each of those elements through the
result_selector into the result sequence.
Raises:
ValueError: If this Queryable has been closed.
TypeError: If either collection_selector or result_selector are not
callable. | [
"Projects",
"each",
"element",
"of",
"a",
"sequence",
"to",
"an",
"intermediate",
"new",
"sequence",
"flattens",
"the",
"resulting",
"sequences",
"into",
"one",
"sequence",
"and",
"optionally",
"transforms",
"the",
"flattened",
"sequence",
"using",
"a",
"selector"... | train | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L291-L344 |
sixty-north/asq | asq/queryables.py | Queryable.select_many_with_index | def select_many_with_index(
self,
collection_selector=IndexedElement,
result_selector=lambda source_element,
collection_element: collection_element):
'''Projects each element of a sequence to an intermediate new sequence,
incorporating the index of the element, flattens the resulting sequence
into one sequence and optionally transforms the flattened sequence
using a selector function.
Note: This method uses deferred execution.
Args:
collection_selector: A binary function mapping each element of the
source sequence into an intermediate sequence, by incorporating
its index in the source sequence. The two positional arguments
to the function are the zero-based index of the source element
and the value of the element. The result of the function
should be an iterable derived from the index and element value.
If no collection_selector is provided, the elements of the
intermediate sequence will consist of tuples of (index,
element) from the source sequence.
result_selector:
An optional binary function mapping the elements in the
flattened intermediate sequence together with their
corresponding source elements to elements of the result
sequence. The two positional arguments of the result_selector
are, first the source element corresponding to an element from
the intermediate sequence, and second the actual element from
the intermediate sequence. The return value should be the
corresponding value in the result sequence. If no
result_selector function is provided, the elements of the
flattened intermediate sequence are returned untransformed.
Returns:
A Queryable over a generated sequence whose elements are the result
of applying the one-to-many collection_selector to each element of
the source sequence which incorporates both the index and value of
the source element, concatenating the results into an intermediate
sequence, and then mapping each of those elements through the
result_selector into the result sequence.
Raises:
ValueError: If this Queryable has been closed.
TypeError: If projector [and selector] are not callable.
'''
if self.closed():
raise ValueError("Attempt to call select_many_with_index() on a "
"closed Queryable.")
if not is_callable(collection_selector):
raise TypeError("select_many_with_index() parameter "
"projector={0} is not callable".format(repr(collection_selector)))
if not is_callable(result_selector):
raise TypeError("select_many_with_index() parameter "
"selector={0} is not callable".format(repr(result_selector)))
return self._create(
self._generate_select_many_with_index(collection_selector,
result_selector)) | python | def select_many_with_index(
self,
collection_selector=IndexedElement,
result_selector=lambda source_element,
collection_element: collection_element):
'''Projects each element of a sequence to an intermediate new sequence,
incorporating the index of the element, flattens the resulting sequence
into one sequence and optionally transforms the flattened sequence
using a selector function.
Note: This method uses deferred execution.
Args:
collection_selector: A binary function mapping each element of the
source sequence into an intermediate sequence, by incorporating
its index in the source sequence. The two positional arguments
to the function are the zero-based index of the source element
and the value of the element. The result of the function
should be an iterable derived from the index and element value.
If no collection_selector is provided, the elements of the
intermediate sequence will consist of tuples of (index,
element) from the source sequence.
result_selector:
An optional binary function mapping the elements in the
flattened intermediate sequence together with their
corresponding source elements to elements of the result
sequence. The two positional arguments of the result_selector
are, first the source element corresponding to an element from
the intermediate sequence, and second the actual element from
the intermediate sequence. The return value should be the
corresponding value in the result sequence. If no
result_selector function is provided, the elements of the
flattened intermediate sequence are returned untransformed.
Returns:
A Queryable over a generated sequence whose elements are the result
of applying the one-to-many collection_selector to each element of
the source sequence which incorporates both the index and value of
the source element, concatenating the results into an intermediate
sequence, and then mapping each of those elements through the
result_selector into the result sequence.
Raises:
ValueError: If this Queryable has been closed.
TypeError: If projector [and selector] are not callable.
'''
if self.closed():
raise ValueError("Attempt to call select_many_with_index() on a "
"closed Queryable.")
if not is_callable(collection_selector):
raise TypeError("select_many_with_index() parameter "
"projector={0} is not callable".format(repr(collection_selector)))
if not is_callable(result_selector):
raise TypeError("select_many_with_index() parameter "
"selector={0} is not callable".format(repr(result_selector)))
return self._create(
self._generate_select_many_with_index(collection_selector,
result_selector)) | [
"def",
"select_many_with_index",
"(",
"self",
",",
"collection_selector",
"=",
"IndexedElement",
",",
"result_selector",
"=",
"lambda",
"source_element",
",",
"collection_element",
":",
"collection_element",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"r... | Projects each element of a sequence to an intermediate new sequence,
incorporating the index of the element, flattens the resulting sequence
into one sequence and optionally transforms the flattened sequence
using a selector function.
Note: This method uses deferred execution.
Args:
collection_selector: A binary function mapping each element of the
source sequence into an intermediate sequence, by incorporating
its index in the source sequence. The two positional arguments
to the function are the zero-based index of the source element
and the value of the element. The result of the function
should be an iterable derived from the index and element value.
If no collection_selector is provided, the elements of the
intermediate sequence will consist of tuples of (index,
element) from the source sequence.
result_selector:
An optional binary function mapping the elements in the
flattened intermediate sequence together with their
corresponding source elements to elements of the result
sequence. The two positional arguments of the result_selector
are, first the source element corresponding to an element from
the intermediate sequence, and second the actual element from
the intermediate sequence. The return value should be the
corresponding value in the result sequence. If no
result_selector function is provided, the elements of the
flattened intermediate sequence are returned untransformed.
Returns:
A Queryable over a generated sequence whose elements are the result
of applying the one-to-many collection_selector to each element of
the source sequence which incorporates both the index and value of
the source element, concatenating the results into an intermediate
sequence, and then mapping each of those elements through the
result_selector into the result sequence.
Raises:
ValueError: If this Queryable has been closed.
TypeError: If projector [and selector] are not callable. | [
"Projects",
"each",
"element",
"of",
"a",
"sequence",
"to",
"an",
"intermediate",
"new",
"sequence",
"incorporating",
"the",
"index",
"of",
"the",
"element",
"flattens",
"the",
"resulting",
"sequence",
"into",
"one",
"sequence",
"and",
"optionally",
"transforms",
... | train | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L346-L407 |
sixty-north/asq | asq/queryables.py | Queryable.select_many_with_correspondence | def select_many_with_correspondence(
self,
collection_selector=identity,
result_selector=KeyedElement):
'''Projects each element of a sequence to an intermediate new sequence,
and flattens the resulting sequence, into one sequence and uses a
selector function to incorporate the corresponding source for each item
in the result sequence.
Note: This method uses deferred execution.
Args:
collection_selector: A unary function mapping each element of the
source iterable into an intermediate sequence. The single
argument of the collection_selector is the value of an element
from the source sequence. The return value should be an
iterable derived from that element value. The default
collection_selector, which is the identity function, assumes
that each element of the source sequence is itself iterable.
result_selector:
An optional binary function mapping the elements in the
flattened intermediate sequence together with their
corresponding source elements to elements of the result
sequence. The two positional arguments of the result_selector
are, first the source element corresponding to an element from
the intermediate sequence, and second the actual element from
the intermediate sequence. The return value should be the
corresponding value in the result sequence. If no
result_selector function is provided, the elements of the
result sequence are KeyedElement namedtuples.
Returns:
A Queryable over a generated sequence whose elements are the result
of applying the one-to-many collection_selector to each element of
the source sequence, concatenating the results into an intermediate
sequence, and then mapping each of those elements through the
result_selector which incorporates the corresponding source element
into the result sequence.
Raises:
ValueError: If this Queryable has been closed.
TypeError: If projector or selector are not callable.
'''
if self.closed():
raise ValueError("Attempt to call "
"select_many_with_correspondence() on a closed Queryable.")
if not is_callable(collection_selector):
raise TypeError("select_many_with_correspondence() parameter "
"projector={0} is not callable".format(repr(collection_selector)))
if not is_callable(result_selector):
raise TypeError("select_many_with_correspondence() parameter "
"selector={0} is not callable".format(repr(result_selector)))
return self._create(
self._generate_select_many_with_correspondence(collection_selector,
result_selector)) | python | def select_many_with_correspondence(
self,
collection_selector=identity,
result_selector=KeyedElement):
'''Projects each element of a sequence to an intermediate new sequence,
and flattens the resulting sequence, into one sequence and uses a
selector function to incorporate the corresponding source for each item
in the result sequence.
Note: This method uses deferred execution.
Args:
collection_selector: A unary function mapping each element of the
source iterable into an intermediate sequence. The single
argument of the collection_selector is the value of an element
from the source sequence. The return value should be an
iterable derived from that element value. The default
collection_selector, which is the identity function, assumes
that each element of the source sequence is itself iterable.
result_selector:
An optional binary function mapping the elements in the
flattened intermediate sequence together with their
corresponding source elements to elements of the result
sequence. The two positional arguments of the result_selector
are, first the source element corresponding to an element from
the intermediate sequence, and second the actual element from
the intermediate sequence. The return value should be the
corresponding value in the result sequence. If no
result_selector function is provided, the elements of the
result sequence are KeyedElement namedtuples.
Returns:
A Queryable over a generated sequence whose elements are the result
of applying the one-to-many collection_selector to each element of
the source sequence, concatenating the results into an intermediate
sequence, and then mapping each of those elements through the
result_selector which incorporates the corresponding source element
into the result sequence.
Raises:
ValueError: If this Queryable has been closed.
TypeError: If projector or selector are not callable.
'''
if self.closed():
raise ValueError("Attempt to call "
"select_many_with_correspondence() on a closed Queryable.")
if not is_callable(collection_selector):
raise TypeError("select_many_with_correspondence() parameter "
"projector={0} is not callable".format(repr(collection_selector)))
if not is_callable(result_selector):
raise TypeError("select_many_with_correspondence() parameter "
"selector={0} is not callable".format(repr(result_selector)))
return self._create(
self._generate_select_many_with_correspondence(collection_selector,
result_selector)) | [
"def",
"select_many_with_correspondence",
"(",
"self",
",",
"collection_selector",
"=",
"identity",
",",
"result_selector",
"=",
"KeyedElement",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call \"",
"\"select_many_... | Projects each element of a sequence to an intermediate new sequence,
and flattens the resulting sequence, into one sequence and uses a
selector function to incorporate the corresponding source for each item
in the result sequence.
Note: This method uses deferred execution.
Args:
collection_selector: A unary function mapping each element of the
source iterable into an intermediate sequence. The single
argument of the collection_selector is the value of an element
from the source sequence. The return value should be an
iterable derived from that element value. The default
collection_selector, which is the identity function, assumes
that each element of the source sequence is itself iterable.
result_selector:
An optional binary function mapping the elements in the
flattened intermediate sequence together with their
corresponding source elements to elements of the result
sequence. The two positional arguments of the result_selector
are, first the source element corresponding to an element from
the intermediate sequence, and second the actual element from
the intermediate sequence. The return value should be the
corresponding value in the result sequence. If no
result_selector function is provided, the elements of the
result sequence are KeyedElement namedtuples.
Returns:
A Queryable over a generated sequence whose elements are the result
of applying the one-to-many collection_selector to each element of
the source sequence, concatenating the results into an intermediate
sequence, and then mapping each of those elements through the
result_selector which incorporates the corresponding source element
into the result sequence.
Raises:
ValueError: If this Queryable has been closed.
TypeError: If projector or selector are not callable. | [
"Projects",
"each",
"element",
"of",
"a",
"sequence",
"to",
"an",
"intermediate",
"new",
"sequence",
"and",
"flattens",
"the",
"resulting",
"sequence",
"into",
"one",
"sequence",
"and",
"uses",
"a",
"selector",
"function",
"to",
"incorporate",
"the",
"correspond... | train | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L417-L476 |
sixty-north/asq | asq/queryables.py | Queryable.group_by | def group_by(self, key_selector=identity,
element_selector=identity,
result_selector=lambda key, grouping: grouping):
'''Groups the elements according to the value of a key extracted by a
selector function.
Note: This method has different behaviour to itertools.groupby in the
Python standard library because it aggregates all items with the
same key, rather than returning groups of consecutive items of the
same key.
Note: This method uses deferred execution, but consumption of a single
result will lead to evaluation of the whole source sequence.
Args:
key_selector: An optional unary function used to extract a key from
each element in the source sequence. The default is the
identity function.
element_selector: A optional unary function to map elements in the
source sequence to elements in a resulting Grouping. The
default is the identity function.
result_selector: An optional binary function to create a result
from each group. The first positional argument is the key
identifying the group. The second argument is a Grouping object
containing the members of the group. The default is a function
which simply returns the Grouping.
Returns:
A Queryable sequence of elements of the where each element
represents a group. If the default result_selector is relied upon
this is a Grouping object.
Raises:
ValueError: If the Queryable is closed().
TypeError: If key_selector is not callable.
TypeError: If element_selector is not callable.
TypeError: If result_selector is not callable.
'''
if self.closed():
raise ValueError("Attempt to call group_by() on a closed "
"Queryable.")
if not is_callable(key_selector):
raise TypeError("group_by() parameter key_selector={0} is not "
"callable".format(repr(key_selector)))
if not is_callable(element_selector):
raise TypeError("group_by() parameter element_selector={0} is not "
"callable".format(repr(element_selector)))
if not is_callable(result_selector):
raise TypeError("group_by() parameter result_selector={0} is not "
"callable".format(repr(result_selector)))
return self._create(self._generate_group_by_result(key_selector,
element_selector, result_selector)) | python | def group_by(self, key_selector=identity,
element_selector=identity,
result_selector=lambda key, grouping: grouping):
'''Groups the elements according to the value of a key extracted by a
selector function.
Note: This method has different behaviour to itertools.groupby in the
Python standard library because it aggregates all items with the
same key, rather than returning groups of consecutive items of the
same key.
Note: This method uses deferred execution, but consumption of a single
result will lead to evaluation of the whole source sequence.
Args:
key_selector: An optional unary function used to extract a key from
each element in the source sequence. The default is the
identity function.
element_selector: A optional unary function to map elements in the
source sequence to elements in a resulting Grouping. The
default is the identity function.
result_selector: An optional binary function to create a result
from each group. The first positional argument is the key
identifying the group. The second argument is a Grouping object
containing the members of the group. The default is a function
which simply returns the Grouping.
Returns:
A Queryable sequence of elements of the where each element
represents a group. If the default result_selector is relied upon
this is a Grouping object.
Raises:
ValueError: If the Queryable is closed().
TypeError: If key_selector is not callable.
TypeError: If element_selector is not callable.
TypeError: If result_selector is not callable.
'''
if self.closed():
raise ValueError("Attempt to call group_by() on a closed "
"Queryable.")
if not is_callable(key_selector):
raise TypeError("group_by() parameter key_selector={0} is not "
"callable".format(repr(key_selector)))
if not is_callable(element_selector):
raise TypeError("group_by() parameter element_selector={0} is not "
"callable".format(repr(element_selector)))
if not is_callable(result_selector):
raise TypeError("group_by() parameter result_selector={0} is not "
"callable".format(repr(result_selector)))
return self._create(self._generate_group_by_result(key_selector,
element_selector, result_selector)) | [
"def",
"group_by",
"(",
"self",
",",
"key_selector",
"=",
"identity",
",",
"element_selector",
"=",
"identity",
",",
"result_selector",
"=",
"lambda",
"key",
",",
"grouping",
":",
"grouping",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
... | Groups the elements according to the value of a key extracted by a
selector function.
Note: This method has different behaviour to itertools.groupby in the
Python standard library because it aggregates all items with the
same key, rather than returning groups of consecutive items of the
same key.
Note: This method uses deferred execution, but consumption of a single
result will lead to evaluation of the whole source sequence.
Args:
key_selector: An optional unary function used to extract a key from
each element in the source sequence. The default is the
identity function.
element_selector: A optional unary function to map elements in the
source sequence to elements in a resulting Grouping. The
default is the identity function.
result_selector: An optional binary function to create a result
from each group. The first positional argument is the key
identifying the group. The second argument is a Grouping object
containing the members of the group. The default is a function
which simply returns the Grouping.
Returns:
A Queryable sequence of elements of the where each element
represents a group. If the default result_selector is relied upon
this is a Grouping object.
Raises:
ValueError: If the Queryable is closed().
TypeError: If key_selector is not callable.
TypeError: If element_selector is not callable.
TypeError: If result_selector is not callable. | [
"Groups",
"the",
"elements",
"according",
"to",
"the",
"value",
"of",
"a",
"key",
"extracted",
"by",
"a",
"selector",
"function",
"."
] | train | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L486-L543 |
sixty-north/asq | asq/queryables.py | Queryable.where | def where(self, predicate):
'''Filters elements according to whether they match a predicate.
Note: This method uses deferred execution.
Args:
predicate: A unary function which is applied to each element in the
source sequence. Source elements for which the predicate
returns True will be present in the result.
Returns:
A Queryable over those elements of the source sequence for which
the predicate is True.
Raises:
ValueError: If the Queryable is closed.
TypeError: If the predicate is not callable.
'''
if self.closed():
raise ValueError("Attempt to call where() on a closed Queryable.")
if not is_callable(predicate):
raise TypeError("where() parameter predicate={predicate} is not "
"callable".format(predicate=repr(predicate)))
return self._create(ifilter(predicate, self)) | python | def where(self, predicate):
'''Filters elements according to whether they match a predicate.
Note: This method uses deferred execution.
Args:
predicate: A unary function which is applied to each element in the
source sequence. Source elements for which the predicate
returns True will be present in the result.
Returns:
A Queryable over those elements of the source sequence for which
the predicate is True.
Raises:
ValueError: If the Queryable is closed.
TypeError: If the predicate is not callable.
'''
if self.closed():
raise ValueError("Attempt to call where() on a closed Queryable.")
if not is_callable(predicate):
raise TypeError("where() parameter predicate={predicate} is not "
"callable".format(predicate=repr(predicate)))
return self._create(ifilter(predicate, self)) | [
"def",
"where",
"(",
"self",
",",
"predicate",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call where() on a closed Queryable.\"",
")",
"if",
"not",
"is_callable",
"(",
"predicate",
")",
":",
"raise",
"TypeEr... | Filters elements according to whether they match a predicate.
Note: This method uses deferred execution.
Args:
predicate: A unary function which is applied to each element in the
source sequence. Source elements for which the predicate
returns True will be present in the result.
Returns:
A Queryable over those elements of the source sequence for which
the predicate is True.
Raises:
ValueError: If the Queryable is closed.
TypeError: If the predicate is not callable. | [
"Filters",
"elements",
"according",
"to",
"whether",
"they",
"match",
"a",
"predicate",
"."
] | train | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L551-L576 |
sixty-north/asq | asq/queryables.py | Queryable.of_type | def of_type(self, classinfo):
'''Filters elements according to whether they are of a certain type.
Note: This method uses deferred execution.
Args:
classinfo: If classinfo is neither a class object nor a type object
it may be a tuple of class or type objects, or may recursively
contain other such tuples (other sequence types are not
accepted).
Returns:
A Queryable over those elements of the source sequence for which
the predicate is True.
Raises:
ValueError: If the Queryable is closed.
TypeError: If classinfo is not a class, type, or tuple of classes,
types, and such tuples.
'''
if self.closed():
raise ValueError("Attempt to call of_type() on a closed "
"Queryable.")
if not is_type(classinfo):
raise TypeError("of_type() parameter classinfo={0} is not a class "
"object or a type objector a tuple of class or "
"type objects.".format(classinfo))
return self.where(lambda x: isinstance(x, classinfo)) | python | def of_type(self, classinfo):
'''Filters elements according to whether they are of a certain type.
Note: This method uses deferred execution.
Args:
classinfo: If classinfo is neither a class object nor a type object
it may be a tuple of class or type objects, or may recursively
contain other such tuples (other sequence types are not
accepted).
Returns:
A Queryable over those elements of the source sequence for which
the predicate is True.
Raises:
ValueError: If the Queryable is closed.
TypeError: If classinfo is not a class, type, or tuple of classes,
types, and such tuples.
'''
if self.closed():
raise ValueError("Attempt to call of_type() on a closed "
"Queryable.")
if not is_type(classinfo):
raise TypeError("of_type() parameter classinfo={0} is not a class "
"object or a type objector a tuple of class or "
"type objects.".format(classinfo))
return self.where(lambda x: isinstance(x, classinfo)) | [
"def",
"of_type",
"(",
"self",
",",
"classinfo",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call of_type() on a closed \"",
"\"Queryable.\"",
")",
"if",
"not",
"is_type",
"(",
"classinfo",
")",
":",
"raise",... | Filters elements according to whether they are of a certain type.
Note: This method uses deferred execution.
Args:
classinfo: If classinfo is neither a class object nor a type object
it may be a tuple of class or type objects, or may recursively
contain other such tuples (other sequence types are not
accepted).
Returns:
A Queryable over those elements of the source sequence for which
the predicate is True.
Raises:
ValueError: If the Queryable is closed.
TypeError: If classinfo is not a class, type, or tuple of classes,
types, and such tuples. | [
"Filters",
"elements",
"according",
"to",
"whether",
"they",
"are",
"of",
"a",
"certain",
"type",
"."
] | train | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L578-L607 |
sixty-north/asq | asq/queryables.py | Queryable.order_by | def order_by(self, key_selector=identity):
'''Sorts by a key in ascending order.
Introduces a primary sorting order to the sequence. Additional sort
criteria should be specified by subsequent calls to then_by() and
then_by_descending(). Calling order_by() or order_by_descending() on
the results of a call to order_by() will introduce a new primary
ordering which will override any already established ordering.
This method performs a stable sort. The order of two elements with the
same key will be preserved.
Note: This method uses deferred execution.
Args:
key_selector: A unary function which extracts a key from each
element using which the result will be ordered.
Returns:
An OrderedQueryable over the sorted elements.
Raises:
ValueError: If the Queryable is closed.
TypeError: If the key_selector is not callable.
'''
if self.closed():
raise ValueError("Attempt to call order_by() on a "
"closed Queryable.")
if not is_callable(key_selector):
raise TypeError("order_by() parameter key_selector={key_selector} "
"is not callable".format(key_selector=repr(key_selector)))
return self._create_ordered(iter(self), -1, key_selector) | python | def order_by(self, key_selector=identity):
'''Sorts by a key in ascending order.
Introduces a primary sorting order to the sequence. Additional sort
criteria should be specified by subsequent calls to then_by() and
then_by_descending(). Calling order_by() or order_by_descending() on
the results of a call to order_by() will introduce a new primary
ordering which will override any already established ordering.
This method performs a stable sort. The order of two elements with the
same key will be preserved.
Note: This method uses deferred execution.
Args:
key_selector: A unary function which extracts a key from each
element using which the result will be ordered.
Returns:
An OrderedQueryable over the sorted elements.
Raises:
ValueError: If the Queryable is closed.
TypeError: If the key_selector is not callable.
'''
if self.closed():
raise ValueError("Attempt to call order_by() on a "
"closed Queryable.")
if not is_callable(key_selector):
raise TypeError("order_by() parameter key_selector={key_selector} "
"is not callable".format(key_selector=repr(key_selector)))
return self._create_ordered(iter(self), -1, key_selector) | [
"def",
"order_by",
"(",
"self",
",",
"key_selector",
"=",
"identity",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call order_by() on a \"",
"\"closed Queryable.\"",
")",
"if",
"not",
"is_callable",
"(",
"key_se... | Sorts by a key in ascending order.
Introduces a primary sorting order to the sequence. Additional sort
criteria should be specified by subsequent calls to then_by() and
then_by_descending(). Calling order_by() or order_by_descending() on
the results of a call to order_by() will introduce a new primary
ordering which will override any already established ordering.
This method performs a stable sort. The order of two elements with the
same key will be preserved.
Note: This method uses deferred execution.
Args:
key_selector: A unary function which extracts a key from each
element using which the result will be ordered.
Returns:
An OrderedQueryable over the sorted elements.
Raises:
ValueError: If the Queryable is closed.
TypeError: If the key_selector is not callable. | [
"Sorts",
"by",
"a",
"key",
"in",
"ascending",
"order",
"."
] | train | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L609-L642 |
sixty-north/asq | asq/queryables.py | Queryable.take | def take(self, count=1):
'''Returns a specified number of elements from the start of a sequence.
If the source sequence contains fewer elements than requested only the
available elements will be returned and no exception will be raised.
Note: This method uses deferred execution.
Args:
count: An optional number of elements to take. The default is one.
Returns:
A Queryable over the first count elements of the source sequence,
or the all elements of elements in the source, whichever is fewer.
Raises:
ValueError: If the Queryable is closed()
'''
if self.closed():
raise ValueError("Attempt to call take() on a closed Queryable.")
count = max(0, count)
return self._create(itertools.islice(self, count)) | python | def take(self, count=1):
'''Returns a specified number of elements from the start of a sequence.
If the source sequence contains fewer elements than requested only the
available elements will be returned and no exception will be raised.
Note: This method uses deferred execution.
Args:
count: An optional number of elements to take. The default is one.
Returns:
A Queryable over the first count elements of the source sequence,
or the all elements of elements in the source, whichever is fewer.
Raises:
ValueError: If the Queryable is closed()
'''
if self.closed():
raise ValueError("Attempt to call take() on a closed Queryable.")
count = max(0, count)
return self._create(itertools.islice(self, count)) | [
"def",
"take",
"(",
"self",
",",
"count",
"=",
"1",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call take() on a closed Queryable.\"",
")",
"count",
"=",
"max",
"(",
"0",
",",
"count",
")",
"return",
"s... | Returns a specified number of elements from the start of a sequence.
If the source sequence contains fewer elements than requested only the
available elements will be returned and no exception will be raised.
Note: This method uses deferred execution.
Args:
count: An optional number of elements to take. The default is one.
Returns:
A Queryable over the first count elements of the source sequence,
or the all elements of elements in the source, whichever is fewer.
Raises:
ValueError: If the Queryable is closed() | [
"Returns",
"a",
"specified",
"number",
"of",
"elements",
"from",
"the",
"start",
"of",
"a",
"sequence",
"."
] | train | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L679-L702 |
sixty-north/asq | asq/queryables.py | Queryable.take_while | def take_while(self, predicate):
'''Returns elements from the start while the predicate is True.
Note: This method uses deferred execution.
Args:
predicate: A function returning True or False with which elements
will be tested.
Returns:
A Queryable over the elements from the beginning of the source
sequence for which predicate is True.
Raises:
ValueError: If the Queryable is closed()
TypeError: If the predicate is not callable.
'''
if self.closed():
raise ValueError("Attempt to call take_while() on a closed "
"Queryable.")
if not is_callable(predicate):
raise TypeError("take_while() parameter predicate={0} is "
"not callable".format(repr(predicate)))
# Cannot use itertools.takewhile here because it is not lazy
return self._create(self._generate_take_while_result(predicate)) | python | def take_while(self, predicate):
'''Returns elements from the start while the predicate is True.
Note: This method uses deferred execution.
Args:
predicate: A function returning True or False with which elements
will be tested.
Returns:
A Queryable over the elements from the beginning of the source
sequence for which predicate is True.
Raises:
ValueError: If the Queryable is closed()
TypeError: If the predicate is not callable.
'''
if self.closed():
raise ValueError("Attempt to call take_while() on a closed "
"Queryable.")
if not is_callable(predicate):
raise TypeError("take_while() parameter predicate={0} is "
"not callable".format(repr(predicate)))
# Cannot use itertools.takewhile here because it is not lazy
return self._create(self._generate_take_while_result(predicate)) | [
"def",
"take_while",
"(",
"self",
",",
"predicate",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call take_while() on a closed \"",
"\"Queryable.\"",
")",
"if",
"not",
"is_callable",
"(",
"predicate",
")",
":",
... | Returns elements from the start while the predicate is True.
Note: This method uses deferred execution.
Args:
predicate: A function returning True or False with which elements
will be tested.
Returns:
A Queryable over the elements from the beginning of the source
sequence for which predicate is True.
Raises:
ValueError: If the Queryable is closed()
TypeError: If the predicate is not callable. | [
"Returns",
"elements",
"from",
"the",
"start",
"while",
"the",
"predicate",
"is",
"True",
"."
] | train | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L704-L730 |
sixty-north/asq | asq/queryables.py | Queryable.skip | def skip(self, count=1):
'''Skip the first count contiguous elements of the source sequence.
If the source sequence contains fewer than count elements returns an
empty sequence and does not raise an exception.
Note: This method uses deferred execution.
Args:
count: The number of elements to skip from the beginning of the
sequence. If omitted defaults to one. If count is less than one
the result sequence will be empty.
Returns:
A Queryable over the elements of source excluding the first count
elements.
Raises:
ValueError: If the Queryable is closed().
'''
if self.closed():
raise ValueError("Attempt to call skip() on a closed Queryable.")
count = max(0, count)
if count == 0:
return self
# Try an optimised version
if hasattr(self._iterable, "__getitem__"):
try:
stop = len(self._iterable)
return self._create(self._generate_optimized_skip_result(count,
stop))
except TypeError:
pass
# Fall back to the unoptimized version
return self._create(self._generate_skip_result(count)) | python | def skip(self, count=1):
'''Skip the first count contiguous elements of the source sequence.
If the source sequence contains fewer than count elements returns an
empty sequence and does not raise an exception.
Note: This method uses deferred execution.
Args:
count: The number of elements to skip from the beginning of the
sequence. If omitted defaults to one. If count is less than one
the result sequence will be empty.
Returns:
A Queryable over the elements of source excluding the first count
elements.
Raises:
ValueError: If the Queryable is closed().
'''
if self.closed():
raise ValueError("Attempt to call skip() on a closed Queryable.")
count = max(0, count)
if count == 0:
return self
# Try an optimised version
if hasattr(self._iterable, "__getitem__"):
try:
stop = len(self._iterable)
return self._create(self._generate_optimized_skip_result(count,
stop))
except TypeError:
pass
# Fall back to the unoptimized version
return self._create(self._generate_skip_result(count)) | [
"def",
"skip",
"(",
"self",
",",
"count",
"=",
"1",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call skip() on a closed Queryable.\"",
")",
"count",
"=",
"max",
"(",
"0",
",",
"count",
")",
"if",
"count... | Skip the first count contiguous elements of the source sequence.
If the source sequence contains fewer than count elements returns an
empty sequence and does not raise an exception.
Note: This method uses deferred execution.
Args:
count: The number of elements to skip from the beginning of the
sequence. If omitted defaults to one. If count is less than one
the result sequence will be empty.
Returns:
A Queryable over the elements of source excluding the first count
elements.
Raises:
ValueError: If the Queryable is closed(). | [
"Skip",
"the",
"first",
"count",
"contiguous",
"elements",
"of",
"the",
"source",
"sequence",
"."
] | train | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L739-L777 |
sixty-north/asq | asq/queryables.py | Queryable.skip_while | def skip_while(self, predicate):
'''Omit elements from the start for which a predicate is True.
Note: This method uses deferred execution.
Args:
predicate: A single argument predicate function.
Returns:
A Queryable over the sequence of elements beginning with the first
element for which the predicate returns False.
Raises:
ValueError: If the Queryable is closed().
TypeError: If predicate is not callable.
'''
if self.closed():
raise ValueError("Attempt to call take_while() on a "
"closed Queryable.")
if not is_callable(predicate):
raise TypeError("skip_while() parameter predicate={0} is "
"not callable".format(repr(predicate)))
return self._create(itertools.dropwhile(predicate, self)) | python | def skip_while(self, predicate):
'''Omit elements from the start for which a predicate is True.
Note: This method uses deferred execution.
Args:
predicate: A single argument predicate function.
Returns:
A Queryable over the sequence of elements beginning with the first
element for which the predicate returns False.
Raises:
ValueError: If the Queryable is closed().
TypeError: If predicate is not callable.
'''
if self.closed():
raise ValueError("Attempt to call take_while() on a "
"closed Queryable.")
if not is_callable(predicate):
raise TypeError("skip_while() parameter predicate={0} is "
"not callable".format(repr(predicate)))
return self._create(itertools.dropwhile(predicate, self)) | [
"def",
"skip_while",
"(",
"self",
",",
"predicate",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call take_while() on a \"",
"\"closed Queryable.\"",
")",
"if",
"not",
"is_callable",
"(",
"predicate",
")",
":",
... | Omit elements from the start for which a predicate is True.
Note: This method uses deferred execution.
Args:
predicate: A single argument predicate function.
Returns:
A Queryable over the sequence of elements beginning with the first
element for which the predicate returns False.
Raises:
ValueError: If the Queryable is closed().
TypeError: If predicate is not callable. | [
"Omit",
"elements",
"from",
"the",
"start",
"for",
"which",
"a",
"predicate",
"is",
"True",
"."
] | train | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L789-L813 |
sixty-north/asq | asq/queryables.py | Queryable.concat | def concat(self, second_iterable):
'''Concatenates two sequences.
Note: This method uses deferred execution.
Args:
second_iterable: The sequence to concatenate on to the sequence.
Returns:
A Queryable over the concatenated sequences.
Raises:
ValueError: If the Queryable is closed().
TypeError: If second_iterable is not in fact iterable.
'''
if self.closed():
raise ValueError("Attempt to call concat() on a closed Queryable.")
if not is_iterable(second_iterable):
raise TypeError("Cannot compute concat() with second_iterable of "
"non-iterable {0}".format(str(type(second_iterable))[7: -1]))
return self._create(itertools.chain(self, second_iterable)) | python | def concat(self, second_iterable):
'''Concatenates two sequences.
Note: This method uses deferred execution.
Args:
second_iterable: The sequence to concatenate on to the sequence.
Returns:
A Queryable over the concatenated sequences.
Raises:
ValueError: If the Queryable is closed().
TypeError: If second_iterable is not in fact iterable.
'''
if self.closed():
raise ValueError("Attempt to call concat() on a closed Queryable.")
if not is_iterable(second_iterable):
raise TypeError("Cannot compute concat() with second_iterable of "
"non-iterable {0}".format(str(type(second_iterable))[7: -1]))
return self._create(itertools.chain(self, second_iterable)) | [
"def",
"concat",
"(",
"self",
",",
"second_iterable",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call concat() on a closed Queryable.\"",
")",
"if",
"not",
"is_iterable",
"(",
"second_iterable",
")",
":",
"rai... | Concatenates two sequences.
Note: This method uses deferred execution.
Args:
second_iterable: The sequence to concatenate on to the sequence.
Returns:
A Queryable over the concatenated sequences.
Raises:
ValueError: If the Queryable is closed().
TypeError: If second_iterable is not in fact iterable. | [
"Concatenates",
"two",
"sequences",
"."
] | train | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L815-L837 |
sixty-north/asq | asq/queryables.py | Queryable.reverse | def reverse(self):
'''Returns the sequence reversed.
Note: This method uses deferred execution, but the whole source
sequence is consumed once execution commences.
Returns:
The source sequence in reverse order.
Raises:
ValueError: If the Queryable is closed().
'''
if self.closed():
raise ValueError("Attempt to call reverse() on a "
"closed Queryable.")
# Attempt an optimised version
try:
r = reversed(self._iterable)
return self._create(r)
except TypeError:
pass
# Fall through to a sequential version
return self._create(self._generate_reverse_result()) | python | def reverse(self):
'''Returns the sequence reversed.
Note: This method uses deferred execution, but the whole source
sequence is consumed once execution commences.
Returns:
The source sequence in reverse order.
Raises:
ValueError: If the Queryable is closed().
'''
if self.closed():
raise ValueError("Attempt to call reverse() on a "
"closed Queryable.")
# Attempt an optimised version
try:
r = reversed(self._iterable)
return self._create(r)
except TypeError:
pass
# Fall through to a sequential version
return self._create(self._generate_reverse_result()) | [
"def",
"reverse",
"(",
"self",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call reverse() on a \"",
"\"closed Queryable.\"",
")",
"# Attempt an optimised version",
"try",
":",
"r",
"=",
"reversed",
"(",
"self",
... | Returns the sequence reversed.
Note: This method uses deferred execution, but the whole source
sequence is consumed once execution commences.
Returns:
The source sequence in reverse order.
Raises:
ValueError: If the Queryable is closed(). | [
"Returns",
"the",
"sequence",
"reversed",
"."
] | train | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L839-L863 |
sixty-north/asq | asq/queryables.py | Queryable.element_at | def element_at(self, index):
'''Return the element at ordinal index.
Note: This method uses immediate execution.
Args:
index: The index of the element to be returned.
Returns:
The element at ordinal index in the source sequence.
Raises:
ValueError: If the Queryable is closed().
ValueError: If index is out of range.
'''
if self.closed():
raise ValueError("Attempt to call element_at() on a "
"closed Queryable.")
if index < 0:
raise OutOfRangeError("Attempt to use negative index.")
# Attempt to use __getitem__
try:
return self._iterable[index]
except IndexError:
raise OutOfRangeError("Index out of range.")
except TypeError:
pass
# Fall back to iterating
for i, item in enumerate(self):
if i == index:
return item
raise OutOfRangeError("element_at(index) out of range.") | python | def element_at(self, index):
'''Return the element at ordinal index.
Note: This method uses immediate execution.
Args:
index: The index of the element to be returned.
Returns:
The element at ordinal index in the source sequence.
Raises:
ValueError: If the Queryable is closed().
ValueError: If index is out of range.
'''
if self.closed():
raise ValueError("Attempt to call element_at() on a "
"closed Queryable.")
if index < 0:
raise OutOfRangeError("Attempt to use negative index.")
# Attempt to use __getitem__
try:
return self._iterable[index]
except IndexError:
raise OutOfRangeError("Index out of range.")
except TypeError:
pass
# Fall back to iterating
for i, item in enumerate(self):
if i == index:
return item
raise OutOfRangeError("element_at(index) out of range.") | [
"def",
"element_at",
"(",
"self",
",",
"index",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call element_at() on a \"",
"\"closed Queryable.\"",
")",
"if",
"index",
"<",
"0",
":",
"raise",
"OutOfRangeError",
... | Return the element at ordinal index.
Note: This method uses immediate execution.
Args:
index: The index of the element to be returned.
Returns:
The element at ordinal index in the source sequence.
Raises:
ValueError: If the Queryable is closed().
ValueError: If index is out of range. | [
"Return",
"the",
"element",
"at",
"ordinal",
"index",
"."
] | train | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L871-L905 |
sixty-north/asq | asq/queryables.py | Queryable.count | def count(self, predicate=None):
'''Return the number of elements (which match an optional predicate).
Note: This method uses immediate execution.
Args:
predicate: An optional unary predicate function used to identify
elements which will be counted. The single positional argument
of the function is the element value. The function should
return True or False.
Returns:
The number of elements in the sequence if the predicate is None
(the default), or if the predicate is supplied the number of
elements for which the predicate evaluates to True.
Raises:
ValueError: If the Queryable is closed().
TypeError: If predicate is neither None nor a callable.
'''
if self.closed():
raise ValueError("Attempt to call element_at() on a "
"closed Queryable.")
return self._count() if predicate is None else self._count_predicate(predicate) | python | def count(self, predicate=None):
'''Return the number of elements (which match an optional predicate).
Note: This method uses immediate execution.
Args:
predicate: An optional unary predicate function used to identify
elements which will be counted. The single positional argument
of the function is the element value. The function should
return True or False.
Returns:
The number of elements in the sequence if the predicate is None
(the default), or if the predicate is supplied the number of
elements for which the predicate evaluates to True.
Raises:
ValueError: If the Queryable is closed().
TypeError: If predicate is neither None nor a callable.
'''
if self.closed():
raise ValueError("Attempt to call element_at() on a "
"closed Queryable.")
return self._count() if predicate is None else self._count_predicate(predicate) | [
"def",
"count",
"(",
"self",
",",
"predicate",
"=",
"None",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call element_at() on a \"",
"\"closed Queryable.\"",
")",
"return",
"self",
".",
"_count",
"(",
")",
"... | Return the number of elements (which match an optional predicate).
Note: This method uses immediate execution.
Args:
predicate: An optional unary predicate function used to identify
elements which will be counted. The single positional argument
of the function is the element value. The function should
return True or False.
Returns:
The number of elements in the sequence if the predicate is None
(the default), or if the predicate is supplied the number of
elements for which the predicate evaluates to True.
Raises:
ValueError: If the Queryable is closed().
TypeError: If predicate is neither None nor a callable. | [
"Return",
"the",
"number",
"of",
"elements",
"(",
"which",
"match",
"an",
"optional",
"predicate",
")",
"."
] | train | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L907-L932 |
sixty-north/asq | asq/queryables.py | Queryable.any | def any(self, predicate=None):
'''Determine if the source sequence contains any elements which satisfy
the predicate.
Only enough of the sequence to satisfy the predicate once is consumed.
Note: This method uses immediate execution.
Args:
predicate: An optional single argument function used to test each
element. If omitted, or None, this method returns True if there
is at least one element in the source.
Returns:
True if the sequence contains at least one element which satisfies
the predicate, otherwise False.
Raises:
ValueError: If the Queryable is closed()
'''
if self.closed():
raise ValueError("Attempt to call any() on a closed Queryable.")
if predicate is None:
predicate = lambda x: True
if not is_callable(predicate):
raise TypeError("any() parameter predicate={predicate} is not callable".format(predicate=repr(predicate)))
for item in self.select(predicate):
if item:
return True
return False | python | def any(self, predicate=None):
'''Determine if the source sequence contains any elements which satisfy
the predicate.
Only enough of the sequence to satisfy the predicate once is consumed.
Note: This method uses immediate execution.
Args:
predicate: An optional single argument function used to test each
element. If omitted, or None, this method returns True if there
is at least one element in the source.
Returns:
True if the sequence contains at least one element which satisfies
the predicate, otherwise False.
Raises:
ValueError: If the Queryable is closed()
'''
if self.closed():
raise ValueError("Attempt to call any() on a closed Queryable.")
if predicate is None:
predicate = lambda x: True
if not is_callable(predicate):
raise TypeError("any() parameter predicate={predicate} is not callable".format(predicate=repr(predicate)))
for item in self.select(predicate):
if item:
return True
return False | [
"def",
"any",
"(",
"self",
",",
"predicate",
"=",
"None",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call any() on a closed Queryable.\"",
")",
"if",
"predicate",
"is",
"None",
":",
"predicate",
"=",
"lamb... | Determine if the source sequence contains any elements which satisfy
the predicate.
Only enough of the sequence to satisfy the predicate once is consumed.
Note: This method uses immediate execution.
Args:
predicate: An optional single argument function used to test each
element. If omitted, or None, this method returns True if there
is at least one element in the source.
Returns:
True if the sequence contains at least one element which satisfies
the predicate, otherwise False.
Raises:
ValueError: If the Queryable is closed() | [
"Determine",
"if",
"the",
"source",
"sequence",
"contains",
"any",
"elements",
"which",
"satisfy",
"the",
"predicate",
"."
] | train | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L956-L988 |
sixty-north/asq | asq/queryables.py | Queryable.all | def all(self, predicate=bool):
'''Determine if all elements in the source sequence satisfy a condition.
All of the source sequence will be consumed.
Note: This method uses immediate execution.
Args:
predicate (callable): An optional single argument function used to
test each elements. If omitted, the bool() function is used
resulting in the elements being tested directly.
Returns:
True if all elements in the sequence meet the predicate condition,
otherwise False.
Raises:
ValueError: If the Queryable is closed()
TypeError: If predicate is not callable.
'''
if self.closed():
raise ValueError("Attempt to call all() on a closed Queryable.")
if not is_callable(predicate):
raise TypeError("all() parameter predicate={0} is "
"not callable".format(repr(predicate)))
return all(self.select(predicate)) | python | def all(self, predicate=bool):
'''Determine if all elements in the source sequence satisfy a condition.
All of the source sequence will be consumed.
Note: This method uses immediate execution.
Args:
predicate (callable): An optional single argument function used to
test each elements. If omitted, the bool() function is used
resulting in the elements being tested directly.
Returns:
True if all elements in the sequence meet the predicate condition,
otherwise False.
Raises:
ValueError: If the Queryable is closed()
TypeError: If predicate is not callable.
'''
if self.closed():
raise ValueError("Attempt to call all() on a closed Queryable.")
if not is_callable(predicate):
raise TypeError("all() parameter predicate={0} is "
"not callable".format(repr(predicate)))
return all(self.select(predicate)) | [
"def",
"all",
"(",
"self",
",",
"predicate",
"=",
"bool",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call all() on a closed Queryable.\"",
")",
"if",
"not",
"is_callable",
"(",
"predicate",
")",
":",
"rais... | Determine if all elements in the source sequence satisfy a condition.
All of the source sequence will be consumed.
Note: This method uses immediate execution.
Args:
predicate (callable): An optional single argument function used to
test each elements. If omitted, the bool() function is used
resulting in the elements being tested directly.
Returns:
True if all elements in the sequence meet the predicate condition,
otherwise False.
Raises:
ValueError: If the Queryable is closed()
TypeError: If predicate is not callable. | [
"Determine",
"if",
"all",
"elements",
"in",
"the",
"source",
"sequence",
"satisfy",
"a",
"condition",
"."
] | train | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L990-L1017 |
sixty-north/asq | asq/queryables.py | Queryable.sum | def sum(self, selector=identity):
'''Return the arithmetic sum of the values in the sequence..
All of the source sequence will be consumed.
Note: This method uses immediate execution.
Args:
selector: An optional single argument function which will be used
to project the elements of the sequence. If omitted, the
identity function is used.
Returns:
The total value of the projected sequence, or zero for an empty
sequence.
Raises:
ValueError: If the Queryable has been closed.
'''
if self.closed():
raise ValueError("Attempt to call sum() on a closed Queryable.")
if not is_callable(selector):
raise TypeError("sum() parameter selector={0} is "
"not callable".format(repr(selector)))
return sum(self.select(selector)) | python | def sum(self, selector=identity):
'''Return the arithmetic sum of the values in the sequence..
All of the source sequence will be consumed.
Note: This method uses immediate execution.
Args:
selector: An optional single argument function which will be used
to project the elements of the sequence. If omitted, the
identity function is used.
Returns:
The total value of the projected sequence, or zero for an empty
sequence.
Raises:
ValueError: If the Queryable has been closed.
'''
if self.closed():
raise ValueError("Attempt to call sum() on a closed Queryable.")
if not is_callable(selector):
raise TypeError("sum() parameter selector={0} is "
"not callable".format(repr(selector)))
return sum(self.select(selector)) | [
"def",
"sum",
"(",
"self",
",",
"selector",
"=",
"identity",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call sum() on a closed Queryable.\"",
")",
"if",
"not",
"is_callable",
"(",
"selector",
")",
":",
"ra... | Return the arithmetic sum of the values in the sequence..
All of the source sequence will be consumed.
Note: This method uses immediate execution.
Args:
selector: An optional single argument function which will be used
to project the elements of the sequence. If omitted, the
identity function is used.
Returns:
The total value of the projected sequence, or zero for an empty
sequence.
Raises:
ValueError: If the Queryable has been closed. | [
"Return",
"the",
"arithmetic",
"sum",
"of",
"the",
"values",
"in",
"the",
"sequence",
".."
] | train | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L1076-L1103 |
sixty-north/asq | asq/queryables.py | Queryable.average | def average(self, selector=identity):
'''Return the arithmetic mean of the values in the sequence..
All of the source sequence will be consumed.
Note: This method uses immediate execution.
Args:
selector: An optional single argument function which will be used
to project the elements of the sequence. If omitted, the
identity function is used.
Returns:
The arithmetic mean value of the projected sequence.
Raises:
ValueError: If the Queryable has been closed.
ValueError: I the source sequence is empty.
'''
if self.closed():
raise ValueError("Attempt to call average() on a "
"closed Queryable.")
if not is_callable(selector):
raise TypeError("average() parameter selector={0} is "
"not callable".format(repr(selector)))
total = 0
count = 0
for item in self.select(selector):
total += item
count += 1
if count == 0:
raise ValueError("Cannot compute average() of an empty sequence.")
return total / count | python | def average(self, selector=identity):
'''Return the arithmetic mean of the values in the sequence..
All of the source sequence will be consumed.
Note: This method uses immediate execution.
Args:
selector: An optional single argument function which will be used
to project the elements of the sequence. If omitted, the
identity function is used.
Returns:
The arithmetic mean value of the projected sequence.
Raises:
ValueError: If the Queryable has been closed.
ValueError: I the source sequence is empty.
'''
if self.closed():
raise ValueError("Attempt to call average() on a "
"closed Queryable.")
if not is_callable(selector):
raise TypeError("average() parameter selector={0} is "
"not callable".format(repr(selector)))
total = 0
count = 0
for item in self.select(selector):
total += item
count += 1
if count == 0:
raise ValueError("Cannot compute average() of an empty sequence.")
return total / count | [
"def",
"average",
"(",
"self",
",",
"selector",
"=",
"identity",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call average() on a \"",
"\"closed Queryable.\"",
")",
"if",
"not",
"is_callable",
"(",
"selector",
... | Return the arithmetic mean of the values in the sequence..
All of the source sequence will be consumed.
Note: This method uses immediate execution.
Args:
selector: An optional single argument function which will be used
to project the elements of the sequence. If omitted, the
identity function is used.
Returns:
The arithmetic mean value of the projected sequence.
Raises:
ValueError: If the Queryable has been closed.
ValueError: I the source sequence is empty. | [
"Return",
"the",
"arithmetic",
"mean",
"of",
"the",
"values",
"in",
"the",
"sequence",
".."
] | train | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L1105-L1139 |
sixty-north/asq | asq/queryables.py | Queryable.contains | def contains(self, value, equality_comparer=operator.eq):
'''Determines whether the sequence contains a particular value.
Execution is immediate. Depending on the type of the sequence, all or
none of the sequence may be consumed by this operation.
Note: This method uses immediate execution.
Args:
value: The value to test for membership of the sequence
Returns:
True if value is in the sequence, otherwise False.
Raises:
ValueError: If the Queryable has been closed.
'''
if self.closed():
raise ValueError("Attempt to call contains() on a "
"closed Queryable.")
if not is_callable(equality_comparer):
raise TypeError("contains() parameter equality_comparer={0} is "
"not callable".format(repr(equality_comparer)))
if equality_comparer is operator.eq:
return value in self._iterable
for item in self:
if equality_comparer(value, item):
return True
return False | python | def contains(self, value, equality_comparer=operator.eq):
'''Determines whether the sequence contains a particular value.
Execution is immediate. Depending on the type of the sequence, all or
none of the sequence may be consumed by this operation.
Note: This method uses immediate execution.
Args:
value: The value to test for membership of the sequence
Returns:
True if value is in the sequence, otherwise False.
Raises:
ValueError: If the Queryable has been closed.
'''
if self.closed():
raise ValueError("Attempt to call contains() on a "
"closed Queryable.")
if not is_callable(equality_comparer):
raise TypeError("contains() parameter equality_comparer={0} is "
"not callable".format(repr(equality_comparer)))
if equality_comparer is operator.eq:
return value in self._iterable
for item in self:
if equality_comparer(value, item):
return True
return False | [
"def",
"contains",
"(",
"self",
",",
"value",
",",
"equality_comparer",
"=",
"operator",
".",
"eq",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call contains() on a \"",
"\"closed Queryable.\"",
")",
"if",
"n... | Determines whether the sequence contains a particular value.
Execution is immediate. Depending on the type of the sequence, all or
none of the sequence may be consumed by this operation.
Note: This method uses immediate execution.
Args:
value: The value to test for membership of the sequence
Returns:
True if value is in the sequence, otherwise False.
Raises:
ValueError: If the Queryable has been closed. | [
"Determines",
"whether",
"the",
"sequence",
"contains",
"a",
"particular",
"value",
"."
] | train | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L1141-L1173 |
sixty-north/asq | asq/queryables.py | Queryable.default_if_empty | def default_if_empty(self, default):
'''If the source sequence is empty return a single element sequence
containing the supplied default value, otherwise return the source
sequence unchanged.
Note: This method uses deferred execution.
Args:
default: The element to be returned if the source sequence is empty.
Returns:
The source sequence, or if the source sequence is empty an sequence
containing a single element with the supplied default value.
Raises:
ValueError: If the Queryable has been closed.
'''
if self.closed():
raise ValueError("Attempt to call default_if_empty() on a "
"closed Queryable.")
return self._create(self._generate_default_if_empty_result(default)) | python | def default_if_empty(self, default):
'''If the source sequence is empty return a single element sequence
containing the supplied default value, otherwise return the source
sequence unchanged.
Note: This method uses deferred execution.
Args:
default: The element to be returned if the source sequence is empty.
Returns:
The source sequence, or if the source sequence is empty an sequence
containing a single element with the supplied default value.
Raises:
ValueError: If the Queryable has been closed.
'''
if self.closed():
raise ValueError("Attempt to call default_if_empty() on a "
"closed Queryable.")
return self._create(self._generate_default_if_empty_result(default)) | [
"def",
"default_if_empty",
"(",
"self",
",",
"default",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call default_if_empty() on a \"",
"\"closed Queryable.\"",
")",
"return",
"self",
".",
"_create",
"(",
"self",
... | If the source sequence is empty return a single element sequence
containing the supplied default value, otherwise return the source
sequence unchanged.
Note: This method uses deferred execution.
Args:
default: The element to be returned if the source sequence is empty.
Returns:
The source sequence, or if the source sequence is empty an sequence
containing a single element with the supplied default value.
Raises:
ValueError: If the Queryable has been closed. | [
"If",
"the",
"source",
"sequence",
"is",
"empty",
"return",
"a",
"single",
"element",
"sequence",
"containing",
"the",
"supplied",
"default",
"value",
"otherwise",
"return",
"the",
"source",
"sequence",
"unchanged",
"."
] | train | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L1175-L1197 |
sixty-north/asq | asq/queryables.py | Queryable.distinct | def distinct(self, selector=identity):
'''Eliminate duplicate elements from a sequence.
Note: This method uses deferred execution.
Args:
selector: An optional single argument function the result of which
is the value compared for uniqueness against elements already
consumed. If omitted, the element value itself is compared for
uniqueness.
Returns:
Unique elements of the source sequence as determined by the
selector function. Note that it is unprojected elements that are
returned, even if a selector was provided.
Raises:
ValueError: If the Queryable is closed.
TypeError: If the selector is not callable.
'''
if self.closed():
raise ValueError("Attempt to call distinct() on a "
"closed Queryable.")
if not is_callable(selector):
raise TypeError("distinct() parameter selector={0} is "
"not callable".format(repr(selector)))
return self._create(self._generate_distinct_result(selector)) | python | def distinct(self, selector=identity):
'''Eliminate duplicate elements from a sequence.
Note: This method uses deferred execution.
Args:
selector: An optional single argument function the result of which
is the value compared for uniqueness against elements already
consumed. If omitted, the element value itself is compared for
uniqueness.
Returns:
Unique elements of the source sequence as determined by the
selector function. Note that it is unprojected elements that are
returned, even if a selector was provided.
Raises:
ValueError: If the Queryable is closed.
TypeError: If the selector is not callable.
'''
if self.closed():
raise ValueError("Attempt to call distinct() on a "
"closed Queryable.")
if not is_callable(selector):
raise TypeError("distinct() parameter selector={0} is "
"not callable".format(repr(selector)))
return self._create(self._generate_distinct_result(selector)) | [
"def",
"distinct",
"(",
"self",
",",
"selector",
"=",
"identity",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call distinct() on a \"",
"\"closed Queryable.\"",
")",
"if",
"not",
"is_callable",
"(",
"selector",... | Eliminate duplicate elements from a sequence.
Note: This method uses deferred execution.
Args:
selector: An optional single argument function the result of which
is the value compared for uniqueness against elements already
consumed. If omitted, the element value itself is compared for
uniqueness.
Returns:
Unique elements of the source sequence as determined by the
selector function. Note that it is unprojected elements that are
returned, even if a selector was provided.
Raises:
ValueError: If the Queryable is closed.
TypeError: If the selector is not callable. | [
"Eliminate",
"duplicate",
"elements",
"from",
"a",
"sequence",
"."
] | train | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L1216-L1244 |
sixty-north/asq | asq/queryables.py | Queryable.difference | def difference(self, second_iterable, selector=identity):
'''Returns those elements which are in the source sequence which are not
in the second_iterable.
This method is equivalent to the Except() LINQ operator, renamed to a
valid Python identifier.
Note: This method uses deferred execution, but as soon as execution
commences the entirety of the second_iterable is consumed;
therefore, although the source sequence may be infinite the
second_iterable must be finite.
Args:
second_iterable: Elements from this sequence are excluded from the
returned sequence. This sequence will be consumed in its
entirety, so must be finite.
selector: A optional single argument function with selects from the
elements of both sequences the values which will be
compared for equality. If omitted the identity function will
be used.
Returns:
A sequence containing all elements in the source sequence except
those which are also members of the second sequence.
Raises:
ValueError: If the Queryable has been closed.
TypeError: If the second_iterable is not in fact iterable.
TypeError: If the selector is not callable.
'''
if self.closed():
raise ValueError("Attempt to call difference() on a "
"closed Queryable.")
if not is_iterable(second_iterable):
raise TypeError("Cannot compute difference() with second_iterable"
"of non-iterable {0}".format(str(type(second_iterable))[7: -2]))
if not is_callable(selector):
raise TypeError("difference() parameter selector={0} is "
"not callable".format(repr(selector)))
return self._create(self._generate_difference_result(second_iterable,
selector)) | python | def difference(self, second_iterable, selector=identity):
'''Returns those elements which are in the source sequence which are not
in the second_iterable.
This method is equivalent to the Except() LINQ operator, renamed to a
valid Python identifier.
Note: This method uses deferred execution, but as soon as execution
commences the entirety of the second_iterable is consumed;
therefore, although the source sequence may be infinite the
second_iterable must be finite.
Args:
second_iterable: Elements from this sequence are excluded from the
returned sequence. This sequence will be consumed in its
entirety, so must be finite.
selector: A optional single argument function with selects from the
elements of both sequences the values which will be
compared for equality. If omitted the identity function will
be used.
Returns:
A sequence containing all elements in the source sequence except
those which are also members of the second sequence.
Raises:
ValueError: If the Queryable has been closed.
TypeError: If the second_iterable is not in fact iterable.
TypeError: If the selector is not callable.
'''
if self.closed():
raise ValueError("Attempt to call difference() on a "
"closed Queryable.")
if not is_iterable(second_iterable):
raise TypeError("Cannot compute difference() with second_iterable"
"of non-iterable {0}".format(str(type(second_iterable))[7: -2]))
if not is_callable(selector):
raise TypeError("difference() parameter selector={0} is "
"not callable".format(repr(selector)))
return self._create(self._generate_difference_result(second_iterable,
selector)) | [
"def",
"difference",
"(",
"self",
",",
"second_iterable",
",",
"selector",
"=",
"identity",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call difference() on a \"",
"\"closed Queryable.\"",
")",
"if",
"not",
"is... | Returns those elements which are in the source sequence which are not
in the second_iterable.
This method is equivalent to the Except() LINQ operator, renamed to a
valid Python identifier.
Note: This method uses deferred execution, but as soon as execution
commences the entirety of the second_iterable is consumed;
therefore, although the source sequence may be infinite the
second_iterable must be finite.
Args:
second_iterable: Elements from this sequence are excluded from the
returned sequence. This sequence will be consumed in its
entirety, so must be finite.
selector: A optional single argument function with selects from the
elements of both sequences the values which will be
compared for equality. If omitted the identity function will
be used.
Returns:
A sequence containing all elements in the source sequence except
those which are also members of the second sequence.
Raises:
ValueError: If the Queryable has been closed.
TypeError: If the second_iterable is not in fact iterable.
TypeError: If the selector is not callable. | [
"Returns",
"those",
"elements",
"which",
"are",
"in",
"the",
"source",
"sequence",
"which",
"are",
"not",
"in",
"the",
"second_iterable",
"."
] | train | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L1255-L1299 |
sixty-north/asq | asq/queryables.py | Queryable.intersect | def intersect(self, second_iterable, selector=identity):
'''Returns those elements which are both in the source sequence and in
the second_iterable.
Note: This method uses deferred execution.
Args:
second_iterable: Elements are returned if they are also in the
sequence.
selector: An optional single argument function which is used to
project the elements in the source and second_iterables prior
to comparing them. If omitted the identity function will be
used.
Returns:
A sequence containing all elements in the source sequence which
are also members of the second sequence.
Raises:
ValueError: If the Queryable has been closed.
TypeError: If the second_iterable is not in fact iterable.
TypeError: If the selector is not callable.
'''
if self.closed():
raise ValueError("Attempt to call intersect() on a "
"closed Queryable.")
if not is_iterable(second_iterable):
raise TypeError("Cannot compute intersect() with second_iterable "
"of non-iterable {0}".format(str(type(second_iterable))[7: -1]))
if not is_callable(selector):
raise TypeError("intersect() parameter selector={0} is "
"not callable".format(repr(selector)))
return self._create(self._generate_intersect_result(second_iterable,
selector)) | python | def intersect(self, second_iterable, selector=identity):
'''Returns those elements which are both in the source sequence and in
the second_iterable.
Note: This method uses deferred execution.
Args:
second_iterable: Elements are returned if they are also in the
sequence.
selector: An optional single argument function which is used to
project the elements in the source and second_iterables prior
to comparing them. If omitted the identity function will be
used.
Returns:
A sequence containing all elements in the source sequence which
are also members of the second sequence.
Raises:
ValueError: If the Queryable has been closed.
TypeError: If the second_iterable is not in fact iterable.
TypeError: If the selector is not callable.
'''
if self.closed():
raise ValueError("Attempt to call intersect() on a "
"closed Queryable.")
if not is_iterable(second_iterable):
raise TypeError("Cannot compute intersect() with second_iterable "
"of non-iterable {0}".format(str(type(second_iterable))[7: -1]))
if not is_callable(selector):
raise TypeError("intersect() parameter selector={0} is "
"not callable".format(repr(selector)))
return self._create(self._generate_intersect_result(second_iterable,
selector)) | [
"def",
"intersect",
"(",
"self",
",",
"second_iterable",
",",
"selector",
"=",
"identity",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call intersect() on a \"",
"\"closed Queryable.\"",
")",
"if",
"not",
"is_i... | Returns those elements which are both in the source sequence and in
the second_iterable.
Note: This method uses deferred execution.
Args:
second_iterable: Elements are returned if they are also in the
sequence.
selector: An optional single argument function which is used to
project the elements in the source and second_iterables prior
to comparing them. If omitted the identity function will be
used.
Returns:
A sequence containing all elements in the source sequence which
are also members of the second sequence.
Raises:
ValueError: If the Queryable has been closed.
TypeError: If the second_iterable is not in fact iterable.
TypeError: If the selector is not callable. | [
"Returns",
"those",
"elements",
"which",
"are",
"both",
"in",
"the",
"source",
"sequence",
"and",
"in",
"the",
"second_iterable",
"."
] | train | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L1310-L1347 |
sixty-north/asq | asq/queryables.py | Queryable.union | def union(self, second_iterable, selector=identity):
'''Returns those elements which are either in the source sequence or in
the second_iterable, or in both.
Note: This method uses deferred execution.
Args:
second_iterable: Elements from this sequence are returns if they
are not also in the source sequence.
selector: An optional single argument function which is used to
project the elements in the source and second_iterables prior
to comparing them. If omitted the identity function will be
used.
Returns:
A sequence containing all elements in the source sequence and second
sequence.
Raises:
ValueError: If the Queryable has been closed.
TypeError: If the second_iterable is not in fact iterable.
TypeError: If the selector is not callable.
'''
if self.closed():
raise ValueError("Attempt to call union() on a closed Queryable.")
if not is_iterable(second_iterable):
raise TypeError("Cannot compute union() with second_iterable of "
"non-iterable {0}".format(str(type(second_iterable))[7: -1]))
return self._create(itertools.chain(self, second_iterable)).distinct(selector) | python | def union(self, second_iterable, selector=identity):
'''Returns those elements which are either in the source sequence or in
the second_iterable, or in both.
Note: This method uses deferred execution.
Args:
second_iterable: Elements from this sequence are returns if they
are not also in the source sequence.
selector: An optional single argument function which is used to
project the elements in the source and second_iterables prior
to comparing them. If omitted the identity function will be
used.
Returns:
A sequence containing all elements in the source sequence and second
sequence.
Raises:
ValueError: If the Queryable has been closed.
TypeError: If the second_iterable is not in fact iterable.
TypeError: If the selector is not callable.
'''
if self.closed():
raise ValueError("Attempt to call union() on a closed Queryable.")
if not is_iterable(second_iterable):
raise TypeError("Cannot compute union() with second_iterable of "
"non-iterable {0}".format(str(type(second_iterable))[7: -1]))
return self._create(itertools.chain(self, second_iterable)).distinct(selector) | [
"def",
"union",
"(",
"self",
",",
"second_iterable",
",",
"selector",
"=",
"identity",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call union() on a closed Queryable.\"",
")",
"if",
"not",
"is_iterable",
"(",
... | Returns those elements which are either in the source sequence or in
the second_iterable, or in both.
Note: This method uses deferred execution.
Args:
second_iterable: Elements from this sequence are returns if they
are not also in the source sequence.
selector: An optional single argument function which is used to
project the elements in the source and second_iterables prior
to comparing them. If omitted the identity function will be
used.
Returns:
A sequence containing all elements in the source sequence and second
sequence.
Raises:
ValueError: If the Queryable has been closed.
TypeError: If the second_iterable is not in fact iterable.
TypeError: If the selector is not callable. | [
"Returns",
"those",
"elements",
"which",
"are",
"either",
"in",
"the",
"source",
"sequence",
"or",
"in",
"the",
"second_iterable",
"or",
"in",
"both",
"."
] | train | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L1358-L1389 |
sixty-north/asq | asq/queryables.py | Queryable.join | def join(self, inner_iterable, outer_key_selector=identity,
inner_key_selector=identity,
result_selector=lambda outer, inner: (outer, inner)):
'''Perform an inner join with a second sequence using selected keys.
The order of elements from outer is maintained. For each of these the
order of elements from inner is also preserved.
Note: This method uses deferred execution.
Args:
inner_iterable: The sequence to join with the outer sequence.
outer_key_selector: An optional unary function to extract keys from
elements of the outer (source) sequence. The first positional
argument of the function should accept outer elements and the
result value should be the key. If omitted, the identity
function is used.
inner_key_selector: An optional unary function to extract keys
from elements of the inner_iterable. The first positional
argument of the function should accept outer elements and the
result value should be the key. If omitted, the identity
function is used.
result_selector: An optional binary function to create a result
element from two matching elements of the outer and inner. If
omitted the result elements will be a 2-tuple pair of the
matching outer and inner elements.
Returns:
A Queryable whose elements are the result of performing an inner-
join on two sequences.
Raises:
ValueError: If the Queryable has been closed.
TypeError: If the inner_iterable is not in fact iterable.
TypeError: If the outer_key_selector is not callable.
TypeError: If the inner_key_selector is not callable.
TypeError: If the result_selector is not callable.
'''
if self.closed():
raise ValueError("Attempt to call join() on a closed Queryable.")
if not is_iterable(inner_iterable):
raise TypeError("Cannot compute join() with inner_iterable of "
"non-iterable {0}".format(str(type(inner_iterable))[7: -1]))
if not is_callable(outer_key_selector):
raise TypeError("join() parameter outer_key_selector={0} is not "
"callable".format(repr(outer_key_selector)))
if not is_callable(inner_key_selector):
raise TypeError("join() parameter inner_key_selector={0} is not "
"callable".format(repr(inner_key_selector)))
if not is_callable(result_selector):
raise TypeError("join() parameter result_selector={0} is not "
"callable".format(repr(result_selector)))
return self._create(self._generate_join_result(inner_iterable, outer_key_selector,
inner_key_selector, result_selector)) | python | def join(self, inner_iterable, outer_key_selector=identity,
inner_key_selector=identity,
result_selector=lambda outer, inner: (outer, inner)):
'''Perform an inner join with a second sequence using selected keys.
The order of elements from outer is maintained. For each of these the
order of elements from inner is also preserved.
Note: This method uses deferred execution.
Args:
inner_iterable: The sequence to join with the outer sequence.
outer_key_selector: An optional unary function to extract keys from
elements of the outer (source) sequence. The first positional
argument of the function should accept outer elements and the
result value should be the key. If omitted, the identity
function is used.
inner_key_selector: An optional unary function to extract keys
from elements of the inner_iterable. The first positional
argument of the function should accept outer elements and the
result value should be the key. If omitted, the identity
function is used.
result_selector: An optional binary function to create a result
element from two matching elements of the outer and inner. If
omitted the result elements will be a 2-tuple pair of the
matching outer and inner elements.
Returns:
A Queryable whose elements are the result of performing an inner-
join on two sequences.
Raises:
ValueError: If the Queryable has been closed.
TypeError: If the inner_iterable is not in fact iterable.
TypeError: If the outer_key_selector is not callable.
TypeError: If the inner_key_selector is not callable.
TypeError: If the result_selector is not callable.
'''
if self.closed():
raise ValueError("Attempt to call join() on a closed Queryable.")
if not is_iterable(inner_iterable):
raise TypeError("Cannot compute join() with inner_iterable of "
"non-iterable {0}".format(str(type(inner_iterable))[7: -1]))
if not is_callable(outer_key_selector):
raise TypeError("join() parameter outer_key_selector={0} is not "
"callable".format(repr(outer_key_selector)))
if not is_callable(inner_key_selector):
raise TypeError("join() parameter inner_key_selector={0} is not "
"callable".format(repr(inner_key_selector)))
if not is_callable(result_selector):
raise TypeError("join() parameter result_selector={0} is not "
"callable".format(repr(result_selector)))
return self._create(self._generate_join_result(inner_iterable, outer_key_selector,
inner_key_selector, result_selector)) | [
"def",
"join",
"(",
"self",
",",
"inner_iterable",
",",
"outer_key_selector",
"=",
"identity",
",",
"inner_key_selector",
"=",
"identity",
",",
"result_selector",
"=",
"lambda",
"outer",
",",
"inner",
":",
"(",
"outer",
",",
"inner",
")",
")",
":",
"if",
"... | Perform an inner join with a second sequence using selected keys.
The order of elements from outer is maintained. For each of these the
order of elements from inner is also preserved.
Note: This method uses deferred execution.
Args:
inner_iterable: The sequence to join with the outer sequence.
outer_key_selector: An optional unary function to extract keys from
elements of the outer (source) sequence. The first positional
argument of the function should accept outer elements and the
result value should be the key. If omitted, the identity
function is used.
inner_key_selector: An optional unary function to extract keys
from elements of the inner_iterable. The first positional
argument of the function should accept outer elements and the
result value should be the key. If omitted, the identity
function is used.
result_selector: An optional binary function to create a result
element from two matching elements of the outer and inner. If
omitted the result elements will be a 2-tuple pair of the
matching outer and inner elements.
Returns:
A Queryable whose elements are the result of performing an inner-
join on two sequences.
Raises:
ValueError: If the Queryable has been closed.
TypeError: If the inner_iterable is not in fact iterable.
TypeError: If the outer_key_selector is not callable.
TypeError: If the inner_key_selector is not callable.
TypeError: If the result_selector is not callable. | [
"Perform",
"an",
"inner",
"join",
"with",
"a",
"second",
"sequence",
"using",
"selected",
"keys",
"."
] | train | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L1391-L1452 |
sixty-north/asq | asq/queryables.py | Queryable.group_join | def group_join(self, inner_iterable, outer_key_selector=identity, inner_key_selector=identity,
result_selector=lambda outer, grouping: grouping):
'''Match elements of two sequences using keys and group the results.
The group_join() query produces a hierarchical result, with all of the
inner elements in the result grouped against the matching outer
element.
The order of elements from outer is maintained. For each of these the
order of elements from inner is also preserved.
Note: This method uses deferred execution.
Args:
inner_iterable: The sequence to join with the outer sequence.
outer_key_selector: An optional unary function to extract keys from
elements of the outer (source) sequence. The first positional
argument of the function should accept outer elements and the
result value should be the key. If omitted, the identity
function is used.
inner_key_selector: An optional unary function to extract keys
from elements of the inner_iterable. The first positional
argument of the function should accept outer elements and the
result value should be the key. If omitted, the identity
function is used.
result_selector: An optional binary function to create a result
element from an outer element and the Grouping of matching
inner elements. The first positional argument is the outer
elements and the second in the Grouping of inner elements
which match the outer element according to the key selectors
used. If omitted, the result elements will be the Groupings
directly.
Returns:
A Queryable over a sequence with one element for each group in the
result as returned by the result_selector. If the default result
selector is used, the result is a sequence of Grouping objects.
Raises:
ValueError: If the Queryable has been closed.
TypeError: If the inner_iterable is not in fact iterable.
TypeError: If the outer_key_selector is not callable.
TypeError: If the inner_key_selector is not callable.
TypeError: If the result_selector is not callable.
'''
if self.closed():
raise ValueError("Attempt to call group_join() on a closed Queryable.")
if not is_iterable(inner_iterable):
raise TypeError("Cannot compute group_join() with inner_iterable of non-iterable {type}".format(
type=str(type(inner_iterable))[7: -1]))
if not is_callable(outer_key_selector):
raise TypeError("group_join() parameter outer_key_selector={outer_key_selector} is not callable".format(
outer_key_selector=repr(outer_key_selector)))
if not is_callable(inner_key_selector):
raise TypeError("group_join() parameter inner_key_selector={inner_key_selector} is not callable".format(
inner_key_selector=repr(inner_key_selector)))
if not is_callable(result_selector):
raise TypeError("group_join() parameter result_selector={result_selector} is not callable".format(
result_selector=repr(result_selector)))
return self._create(self._generate_group_join_result(inner_iterable, outer_key_selector,
inner_key_selector, result_selector)) | python | def group_join(self, inner_iterable, outer_key_selector=identity, inner_key_selector=identity,
result_selector=lambda outer, grouping: grouping):
'''Match elements of two sequences using keys and group the results.
The group_join() query produces a hierarchical result, with all of the
inner elements in the result grouped against the matching outer
element.
The order of elements from outer is maintained. For each of these the
order of elements from inner is also preserved.
Note: This method uses deferred execution.
Args:
inner_iterable: The sequence to join with the outer sequence.
outer_key_selector: An optional unary function to extract keys from
elements of the outer (source) sequence. The first positional
argument of the function should accept outer elements and the
result value should be the key. If omitted, the identity
function is used.
inner_key_selector: An optional unary function to extract keys
from elements of the inner_iterable. The first positional
argument of the function should accept outer elements and the
result value should be the key. If omitted, the identity
function is used.
result_selector: An optional binary function to create a result
element from an outer element and the Grouping of matching
inner elements. The first positional argument is the outer
elements and the second in the Grouping of inner elements
which match the outer element according to the key selectors
used. If omitted, the result elements will be the Groupings
directly.
Returns:
A Queryable over a sequence with one element for each group in the
result as returned by the result_selector. If the default result
selector is used, the result is a sequence of Grouping objects.
Raises:
ValueError: If the Queryable has been closed.
TypeError: If the inner_iterable is not in fact iterable.
TypeError: If the outer_key_selector is not callable.
TypeError: If the inner_key_selector is not callable.
TypeError: If the result_selector is not callable.
'''
if self.closed():
raise ValueError("Attempt to call group_join() on a closed Queryable.")
if not is_iterable(inner_iterable):
raise TypeError("Cannot compute group_join() with inner_iterable of non-iterable {type}".format(
type=str(type(inner_iterable))[7: -1]))
if not is_callable(outer_key_selector):
raise TypeError("group_join() parameter outer_key_selector={outer_key_selector} is not callable".format(
outer_key_selector=repr(outer_key_selector)))
if not is_callable(inner_key_selector):
raise TypeError("group_join() parameter inner_key_selector={inner_key_selector} is not callable".format(
inner_key_selector=repr(inner_key_selector)))
if not is_callable(result_selector):
raise TypeError("group_join() parameter result_selector={result_selector} is not callable".format(
result_selector=repr(result_selector)))
return self._create(self._generate_group_join_result(inner_iterable, outer_key_selector,
inner_key_selector, result_selector)) | [
"def",
"group_join",
"(",
"self",
",",
"inner_iterable",
",",
"outer_key_selector",
"=",
"identity",
",",
"inner_key_selector",
"=",
"identity",
",",
"result_selector",
"=",
"lambda",
"outer",
",",
"grouping",
":",
"grouping",
")",
":",
"if",
"self",
".",
"clo... | Match elements of two sequences using keys and group the results.
The group_join() query produces a hierarchical result, with all of the
inner elements in the result grouped against the matching outer
element.
The order of elements from outer is maintained. For each of these the
order of elements from inner is also preserved.
Note: This method uses deferred execution.
Args:
inner_iterable: The sequence to join with the outer sequence.
outer_key_selector: An optional unary function to extract keys from
elements of the outer (source) sequence. The first positional
argument of the function should accept outer elements and the
result value should be the key. If omitted, the identity
function is used.
inner_key_selector: An optional unary function to extract keys
from elements of the inner_iterable. The first positional
argument of the function should accept outer elements and the
result value should be the key. If omitted, the identity
function is used.
result_selector: An optional binary function to create a result
element from an outer element and the Grouping of matching
inner elements. The first positional argument is the outer
elements and the second in the Grouping of inner elements
which match the outer element according to the key selectors
used. If omitted, the result elements will be the Groupings
directly.
Returns:
A Queryable over a sequence with one element for each group in the
result as returned by the result_selector. If the default result
selector is used, the result is a sequence of Grouping objects.
Raises:
ValueError: If the Queryable has been closed.
TypeError: If the inner_iterable is not in fact iterable.
TypeError: If the outer_key_selector is not callable.
TypeError: If the inner_key_selector is not callable.
TypeError: If the result_selector is not callable. | [
"Match",
"elements",
"of",
"two",
"sequences",
"using",
"keys",
"and",
"group",
"the",
"results",
"."
] | train | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L1461-L1529 |
sixty-north/asq | asq/queryables.py | Queryable.first | def first(self, predicate=None):
'''The first element in a sequence (optionally satisfying a predicate).
If the predicate is omitted or is None this query returns the first
element in the sequence; otherwise, it returns the first element in
the sequence for which the predicate evaluates to True. Exceptions are
raised if there is no such element.
Note: This method uses immediate execution.
Args:
predicate: An optional unary predicate function, the only argument
to which is the element. The return value should be True for
matching elements, otherwise False. If the predicate is
omitted or None the first element of the source sequence will
be returned.
Returns:
The first element of the sequence if predicate is None, otherwise
the first element for which the predicate returns True.
Raises:
ValueError: If the Queryable is closed.
ValueError: If the source sequence is empty.
ValueError: If there are no elements matching the predicate.
TypeError: If the predicate is not callable.
'''
if self.closed():
raise ValueError("Attempt to call first() on a closed Queryable.")
return self._first() if predicate is None else self._first_predicate(predicate) | python | def first(self, predicate=None):
'''The first element in a sequence (optionally satisfying a predicate).
If the predicate is omitted or is None this query returns the first
element in the sequence; otherwise, it returns the first element in
the sequence for which the predicate evaluates to True. Exceptions are
raised if there is no such element.
Note: This method uses immediate execution.
Args:
predicate: An optional unary predicate function, the only argument
to which is the element. The return value should be True for
matching elements, otherwise False. If the predicate is
omitted or None the first element of the source sequence will
be returned.
Returns:
The first element of the sequence if predicate is None, otherwise
the first element for which the predicate returns True.
Raises:
ValueError: If the Queryable is closed.
ValueError: If the source sequence is empty.
ValueError: If there are no elements matching the predicate.
TypeError: If the predicate is not callable.
'''
if self.closed():
raise ValueError("Attempt to call first() on a closed Queryable.")
return self._first() if predicate is None else self._first_predicate(predicate) | [
"def",
"first",
"(",
"self",
",",
"predicate",
"=",
"None",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call first() on a closed Queryable.\"",
")",
"return",
"self",
".",
"_first",
"(",
")",
"if",
"predica... | The first element in a sequence (optionally satisfying a predicate).
If the predicate is omitted or is None this query returns the first
element in the sequence; otherwise, it returns the first element in
the sequence for which the predicate evaluates to True. Exceptions are
raised if there is no such element.
Note: This method uses immediate execution.
Args:
predicate: An optional unary predicate function, the only argument
to which is the element. The return value should be True for
matching elements, otherwise False. If the predicate is
omitted or None the first element of the source sequence will
be returned.
Returns:
The first element of the sequence if predicate is None, otherwise
the first element for which the predicate returns True.
Raises:
ValueError: If the Queryable is closed.
ValueError: If the source sequence is empty.
ValueError: If there are no elements matching the predicate.
TypeError: If the predicate is not callable. | [
"The",
"first",
"element",
"in",
"a",
"sequence",
"(",
"optionally",
"satisfying",
"a",
"predicate",
")",
"."
] | train | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L1537-L1567 |
sixty-north/asq | asq/queryables.py | Queryable.first_or_default | def first_or_default(self, default, predicate=None):
'''The first element (optionally satisfying a predicate) or a default.
If the predicate is omitted or is None this query returns the first
element in the sequence; otherwise, it returns the first element in
the sequence for which the predicate evaluates to True. If there is no
such element the value of the default argument is returned.
Note: This method uses immediate execution.
Args:
default: The value which will be returned if either the sequence is
empty or there are no elements matching the predicate.
predicate: An optional unary predicate function, the only argument
to which is the element. The return value should be True for
matching elements, otherwise False. If the predicate is
omitted or None the first element of the source sequence will
be returned.
Returns:
The first element of the sequence if predicate is None, otherwise
the first element for which the predicate returns True. If there is
no such element, the default argument is returned.
Raises:
ValueError: If the Queryable is closed.
TypeError: If the predicate is not callable.
'''
if self.closed():
raise ValueError("Attempt to call first_or_default() on a "
"closed Queryable.")
return self._first_or_default(default) if predicate is None else self._first_or_default_predicate(default, predicate) | python | def first_or_default(self, default, predicate=None):
'''The first element (optionally satisfying a predicate) or a default.
If the predicate is omitted or is None this query returns the first
element in the sequence; otherwise, it returns the first element in
the sequence for which the predicate evaluates to True. If there is no
such element the value of the default argument is returned.
Note: This method uses immediate execution.
Args:
default: The value which will be returned if either the sequence is
empty or there are no elements matching the predicate.
predicate: An optional unary predicate function, the only argument
to which is the element. The return value should be True for
matching elements, otherwise False. If the predicate is
omitted or None the first element of the source sequence will
be returned.
Returns:
The first element of the sequence if predicate is None, otherwise
the first element for which the predicate returns True. If there is
no such element, the default argument is returned.
Raises:
ValueError: If the Queryable is closed.
TypeError: If the predicate is not callable.
'''
if self.closed():
raise ValueError("Attempt to call first_or_default() on a "
"closed Queryable.")
return self._first_or_default(default) if predicate is None else self._first_or_default_predicate(default, predicate) | [
"def",
"first_or_default",
"(",
"self",
",",
"default",
",",
"predicate",
"=",
"None",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call first_or_default() on a \"",
"\"closed Queryable.\"",
")",
"return",
"self",... | The first element (optionally satisfying a predicate) or a default.
If the predicate is omitted or is None this query returns the first
element in the sequence; otherwise, it returns the first element in
the sequence for which the predicate evaluates to True. If there is no
such element the value of the default argument is returned.
Note: This method uses immediate execution.
Args:
default: The value which will be returned if either the sequence is
empty or there are no elements matching the predicate.
predicate: An optional unary predicate function, the only argument
to which is the element. The return value should be True for
matching elements, otherwise False. If the predicate is
omitted or None the first element of the source sequence will
be returned.
Returns:
The first element of the sequence if predicate is None, otherwise
the first element for which the predicate returns True. If there is
no such element, the default argument is returned.
Raises:
ValueError: If the Queryable is closed.
TypeError: If the predicate is not callable. | [
"The",
"first",
"element",
"(",
"optionally",
"satisfying",
"a",
"predicate",
")",
"or",
"a",
"default",
"."
] | train | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L1581-L1614 |
sixty-north/asq | asq/queryables.py | Queryable.single | def single(self, predicate=None):
'''The only element (which satisfies a condition).
If the predicate is omitted or is None this query returns the only
element in the sequence; otherwise, it returns the only element in
the sequence for which the predicate evaluates to True. Exceptions are
raised if there is either no such element or more than one such
element.
Note: This method uses immediate execution.
Args:
predicate: An optional unary predicate function, the only argument
to which is the element. The return value should be True for
matching elements, otherwise False. If the predicate is
omitted or None the only element of the source sequence will
be returned.
Returns:
The only element of the sequence if predicate is None, otherwise
the only element for which the predicate returns True.
Raises:
ValueError: If the Queryable is closed.
ValueError: If, when predicate is None the source sequence contains
more than one element.
ValueError: If there are no elements matching the predicate or more
then one element matching the predicate.
TypeError: If the predicate is not callable.
'''
if self.closed():
raise ValueError("Attempt to call single() on a closed Queryable.")
return self._single() if predicate is None else self._single_predicate(predicate) | python | def single(self, predicate=None):
'''The only element (which satisfies a condition).
If the predicate is omitted or is None this query returns the only
element in the sequence; otherwise, it returns the only element in
the sequence for which the predicate evaluates to True. Exceptions are
raised if there is either no such element or more than one such
element.
Note: This method uses immediate execution.
Args:
predicate: An optional unary predicate function, the only argument
to which is the element. The return value should be True for
matching elements, otherwise False. If the predicate is
omitted or None the only element of the source sequence will
be returned.
Returns:
The only element of the sequence if predicate is None, otherwise
the only element for which the predicate returns True.
Raises:
ValueError: If the Queryable is closed.
ValueError: If, when predicate is None the source sequence contains
more than one element.
ValueError: If there are no elements matching the predicate or more
then one element matching the predicate.
TypeError: If the predicate is not callable.
'''
if self.closed():
raise ValueError("Attempt to call single() on a closed Queryable.")
return self._single() if predicate is None else self._single_predicate(predicate) | [
"def",
"single",
"(",
"self",
",",
"predicate",
"=",
"None",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call single() on a closed Queryable.\"",
")",
"return",
"self",
".",
"_single",
"(",
")",
"if",
"pred... | The only element (which satisfies a condition).
If the predicate is omitted or is None this query returns the only
element in the sequence; otherwise, it returns the only element in
the sequence for which the predicate evaluates to True. Exceptions are
raised if there is either no such element or more than one such
element.
Note: This method uses immediate execution.
Args:
predicate: An optional unary predicate function, the only argument
to which is the element. The return value should be True for
matching elements, otherwise False. If the predicate is
omitted or None the only element of the source sequence will
be returned.
Returns:
The only element of the sequence if predicate is None, otherwise
the only element for which the predicate returns True.
Raises:
ValueError: If the Queryable is closed.
ValueError: If, when predicate is None the source sequence contains
more than one element.
ValueError: If there are no elements matching the predicate or more
then one element matching the predicate.
TypeError: If the predicate is not callable. | [
"The",
"only",
"element",
"(",
"which",
"satisfies",
"a",
"condition",
")",
"."
] | train | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L1628-L1661 |
sixty-north/asq | asq/queryables.py | Queryable.single_or_default | def single_or_default(self, default, predicate=None):
'''The only element (which satisfies a condition) or a default.
If the predicate is omitted or is None this query returns the only
element in the sequence; otherwise, it returns the only element in
the sequence for which the predicate evaluates to True. A default value
is returned if there is no such element. An exception is raised if
there is more than one such element.
Note: This method uses immediate execution.
Args:
default: The value which will be returned if either the sequence is
empty or there are no elements matching the predicate.
predicate: An optional unary predicate function, the only argument
to which is the element. The return value should be True for
matching elements, otherwise False. If the predicate is
omitted or None the only element of the source sequence will
be returned.
Returns:
The only element of the sequence if predicate is None, otherwise
the only element for which the predicate returns True. If there are
no such elements the default value will returned.
Raises:
ValueError: If the Queryable is closed.
ValueError: If, when predicate is None the source sequence contains
more than one element.
ValueError: If there is more then one element matching the
predicate.
TypeError: If the predicate is not callable.
'''
if self.closed():
raise ValueError("Attempt to call single_or_default() on a closed Queryable.")
return self._single_or_default(default) if predicate is None else self._single_or_default_predicate(default, predicate) | python | def single_or_default(self, default, predicate=None):
'''The only element (which satisfies a condition) or a default.
If the predicate is omitted or is None this query returns the only
element in the sequence; otherwise, it returns the only element in
the sequence for which the predicate evaluates to True. A default value
is returned if there is no such element. An exception is raised if
there is more than one such element.
Note: This method uses immediate execution.
Args:
default: The value which will be returned if either the sequence is
empty or there are no elements matching the predicate.
predicate: An optional unary predicate function, the only argument
to which is the element. The return value should be True for
matching elements, otherwise False. If the predicate is
omitted or None the only element of the source sequence will
be returned.
Returns:
The only element of the sequence if predicate is None, otherwise
the only element for which the predicate returns True. If there are
no such elements the default value will returned.
Raises:
ValueError: If the Queryable is closed.
ValueError: If, when predicate is None the source sequence contains
more than one element.
ValueError: If there is more then one element matching the
predicate.
TypeError: If the predicate is not callable.
'''
if self.closed():
raise ValueError("Attempt to call single_or_default() on a closed Queryable.")
return self._single_or_default(default) if predicate is None else self._single_or_default_predicate(default, predicate) | [
"def",
"single_or_default",
"(",
"self",
",",
"default",
",",
"predicate",
"=",
"None",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call single_or_default() on a closed Queryable.\"",
")",
"return",
"self",
".",
... | The only element (which satisfies a condition) or a default.
If the predicate is omitted or is None this query returns the only
element in the sequence; otherwise, it returns the only element in
the sequence for which the predicate evaluates to True. A default value
is returned if there is no such element. An exception is raised if
there is more than one such element.
Note: This method uses immediate execution.
Args:
default: The value which will be returned if either the sequence is
empty or there are no elements matching the predicate.
predicate: An optional unary predicate function, the only argument
to which is the element. The return value should be True for
matching elements, otherwise False. If the predicate is
omitted or None the only element of the source sequence will
be returned.
Returns:
The only element of the sequence if predicate is None, otherwise
the only element for which the predicate returns True. If there are
no such elements the default value will returned.
Raises:
ValueError: If the Queryable is closed.
ValueError: If, when predicate is None the source sequence contains
more than one element.
ValueError: If there is more then one element matching the
predicate.
TypeError: If the predicate is not callable. | [
"The",
"only",
"element",
"(",
"which",
"satisfies",
"a",
"condition",
")",
"or",
"a",
"default",
"."
] | train | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L1690-L1727 |
sixty-north/asq | asq/queryables.py | Queryable.last | def last(self, predicate=None):
'''The last element in a sequence (optionally satisfying a predicate).
If the predicate is omitted or is None this query returns the last
element in the sequence; otherwise, it returns the last element in
the sequence for which the predicate evaluates to True. Exceptions are
raised if there is no such element.
Note: This method uses immediate execution.
Args:
predicate: An optional unary predicate function, the only argument
to which is the element. The return value should be True for
matching elements, otherwise False. If the predicate is
omitted or None the last element of the source sequence will
be returned.
Returns:
The last element of the sequence if predicate is None, otherwise
the last element for which the predicate returns True.
Raises:
ValueError: If the Queryable is closed.
ValueError: If the source sequence is empty.
ValueError: If there are no elements matching the predicate.
TypeError: If the predicate is not callable.
'''
if self.closed():
raise ValueError("Attempt to call last() on a closed Queryable.")
return self._last() if predicate is None else self._last_predicate(predicate) | python | def last(self, predicate=None):
'''The last element in a sequence (optionally satisfying a predicate).
If the predicate is omitted or is None this query returns the last
element in the sequence; otherwise, it returns the last element in
the sequence for which the predicate evaluates to True. Exceptions are
raised if there is no such element.
Note: This method uses immediate execution.
Args:
predicate: An optional unary predicate function, the only argument
to which is the element. The return value should be True for
matching elements, otherwise False. If the predicate is
omitted or None the last element of the source sequence will
be returned.
Returns:
The last element of the sequence if predicate is None, otherwise
the last element for which the predicate returns True.
Raises:
ValueError: If the Queryable is closed.
ValueError: If the source sequence is empty.
ValueError: If there are no elements matching the predicate.
TypeError: If the predicate is not callable.
'''
if self.closed():
raise ValueError("Attempt to call last() on a closed Queryable.")
return self._last() if predicate is None else self._last_predicate(predicate) | [
"def",
"last",
"(",
"self",
",",
"predicate",
"=",
"None",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call last() on a closed Queryable.\"",
")",
"return",
"self",
".",
"_last",
"(",
")",
"if",
"predicate"... | The last element in a sequence (optionally satisfying a predicate).
If the predicate is omitted or is None this query returns the last
element in the sequence; otherwise, it returns the last element in
the sequence for which the predicate evaluates to True. Exceptions are
raised if there is no such element.
Note: This method uses immediate execution.
Args:
predicate: An optional unary predicate function, the only argument
to which is the element. The return value should be True for
matching elements, otherwise False. If the predicate is
omitted or None the last element of the source sequence will
be returned.
Returns:
The last element of the sequence if predicate is None, otherwise
the last element for which the predicate returns True.
Raises:
ValueError: If the Queryable is closed.
ValueError: If the source sequence is empty.
ValueError: If there are no elements matching the predicate.
TypeError: If the predicate is not callable. | [
"The",
"last",
"element",
"in",
"a",
"sequence",
"(",
"optionally",
"satisfying",
"a",
"predicate",
")",
"."
] | train | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L1755-L1785 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.