INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Parses the C { IMAGE_EXPORT_DIRECTORY } directory. | def _parseExportDirectory(self, rva, size, magic = consts.PE32):
"""
Parses the C{IMAGE_EXPORT_DIRECTORY} directory.
@type rva: int
@param rva: The RVA where the C{IMAGE_EXPORT_DIRECTORY} directory starts.
@type size: int
@param size: The size of the C{... |
Parses the C { IMAGE_DEBUG_DIRECTORY } directory. | def _parseDebugDirectory(self, rva, size, magic = consts.PE32):
"""
Parses the C{IMAGE_DEBUG_DIRECTORY} directory.
@see: U{http://msdn.microsoft.com/es-es/library/windows/desktop/ms680307(v=vs.85).aspx}
@type rva: int
@param rva: The RVA where the C{IMAGE_DEBUG_DIRECTOR... |
Parses the C { IMAGE_IMPORT_DIRECTORY } directory. | def _parseImportDirectory(self, rva, size, magic = consts.PE32):
"""
Parses the C{IMAGE_IMPORT_DIRECTORY} directory.
@type rva: int
@param rva: The RVA where the C{IMAGE_IMPORT_DIRECTORY} directory starts.
@type size: int
@param size: The size of the C{... |
Parses the NET directory. | def _parseNetDirectory(self, rva, size, magic = consts.PE32):
"""
Parses the NET directory.
@see: U{http://www.ntcore.com/files/dotnetformat.htm}
@type rva: int
@param rva: The RVA where the NET directory starts.
@type size: int
@param size: The... |
Returns a new L { DosHeader } object. | def parse(readDataInstance):
"""
Returns a new L{DosHeader} object.
@type readDataInstance: L{ReadData}
@param readDataInstance: A L{ReadData} object with data to be parsed as a L{DosHeader} object.
@rtype: L{DosHeader}
@return: A new L{DosHeader} object... |
Returns a new L { NtHeaders } object. | def parse(readDataInstance):
"""
Returns a new L{NtHeaders} object.
@type readDataInstance: L{ReadData}
@param readDataInstance: A L{ReadData} object with data to be parsed as a L{NtHeaders} object.
@rtype: L{NtHeaders}
@return: A new L{NtHeaders} object... |
Returns a new L { FileHeader } object. | def parse(readDataInstance):
"""
Returns a new L{FileHeader} object.
@type readDataInstance: L{ReadData}
@param readDataInstance: A L{ReadData} object with data to be parsed as a L{FileHeader} object.
@rtype: L{FileHeader}
@return: A new L{ReadData} obje... |
Returns a new L { OptionalHeader } object. | def parse(readDataInstance):
"""
Returns a new L{OptionalHeader} object.
@type readDataInstance: L{ReadData}
@param readDataInstance: A L{ReadData} object with data to be parsed as a L{OptionalHeader} object.
@rtype: L{OptionalHeader}
@return: A new L{Op... |
Returns a new L { SectionHeader } object. | def parse(readDataInstance):
"""
Returns a new L{SectionHeader} object.
@type readDataInstance: L{ReadData}
@param readDataInstance: A L{ReadData} object with data to be parsed as a L{SectionHeader} object.
@rtype: L{SectionHeader}
@return: A new L{Secti... |
Returns a new L { SectionHeaders } object. | def parse(readDataInstance, numberOfSectionHeaders):
"""
Returns a new L{SectionHeaders} object.
@type readDataInstance: L{ReadData}
@param readDataInstance: A L{ReadData} object with data to be parsed as a L{SectionHeaders} object.
@type numberOfSectionHeaders... |
Returns a new L { Sections } object. | def parse(readDataInstance, sectionHeadersInstance):
"""
Returns a new L{Sections} object.
@type readDataInstance: L{ReadData}
@param readDataInstance: A L{ReadData} object with data to be parsed as a L{Sections} object.
@type sectionHeadersInstance: instance
... |
Get addresses across both subchains based on the filter criteria passed in | def get_addresses_on_both_chains(wallet_obj, used=None, zero_balance=None):
'''
Get addresses across both subchains based on the filter criteria passed in
Returns a list of dicts of the following form:
[
{'address': '1abc123...', 'path': 'm/0/9', 'pubkeyhex': '0123456...'},
... |
Hit/ derive to register new unused_addresses on a subchain_index and verify them client - side | def register_unused_addresses(wallet_obj, subchain_index, num_addrs=1):
'''
Hit /derive to register new unused_addresses on a subchain_index and verify them client-side
Returns a list of dicts of the following form:
[
{'address': '1abc123...', 'path': 'm/0/9', 'public': '0123456...'},
... |
Offline - enabled mechanism to dump addresses | def dump_all_keys_or_addrs(wallet_obj):
'''
Offline-enabled mechanism to dump addresses
'''
print_traversal_warning()
puts('\nDo you understand this warning?')
if not confirm(user_prompt=DEFAULT_PROMPT, default=False):
puts(colored.red('Dump Cancelled!'))
return
mpub = wal... |
Works for both public key only or private key access | def dump_selected_keys_or_addrs(wallet_obj, used=None, zero_balance=None):
'''
Works for both public key only or private key access
'''
if wallet_obj.private_key:
content_str = 'private keys'
else:
content_str = 'addresses'
if not USER_ONLINE:
puts(colored.red('\nInterne... |
Offline - enabled mechanism to dump everything | def dump_private_keys_or_addrs_chooser(wallet_obj):
'''
Offline-enabled mechanism to dump everything
'''
if wallet_obj.private_key:
puts('Which private keys and addresses do you want?')
else:
puts('Which addresses do you want?')
with indent(2):
puts(colored.cyan('1: Acti... |
Loaded on bootup ( and stays in while loop until quitting ) | def wallet_home(wallet_obj):
'''
Loaded on bootup (and stays in while loop until quitting)
'''
mpub = wallet_obj.serialize_b58(private=False)
if wallet_obj.private_key is None:
print_pubwallet_notice(mpub=mpub)
else:
print_bcwallet_basic_pub_opening(mpub=mpub)
coin_symbol =... |
Solves the GFL for a fixed value of lambda. | def solve(self, lam):
'''Solves the GFL for a fixed value of lambda.'''
if self.penalty == 'dp':
return self.solve_dp(lam)
if self.penalty == 'gfl':
return self.solve_gfl(lam)
if self.penalty == 'gamlasso':
return self.solve_gfl(lam)
raise Exce... |
Solves the Graph - fused double Pareto ( non - convex local optima only ) | def solve_dp(self, lam):
'''Solves the Graph-fused double Pareto (non-convex, local optima only)'''
cur_converge = self.converge+1
step = 0
# Get an initial estimate using the GFL
self.solve_gfl(lam)
beta2 = np.copy(self.beta)
while cur_converge > self.converge an... |
Solves the Graph - fused gamma lasso via POSE ( Taddy 2013 ) | def solve_gamlasso(self, lam):
'''Solves the Graph-fused gamma lasso via POSE (Taddy, 2013)'''
weights = lam / (1 + self.gamma * np.abs(self.beta[self.trails[::2]] - self.beta[self.trails[1::2]]))
s = self.solve_gfl(u)
self.steps.append(s)
return self.beta |
Follows the solution path to find the best lambda value. | def solution_path(self, min_lambda, max_lambda, lambda_bins, verbose=0):
'''Follows the solution path to find the best lambda value.'''
lambda_grid = np.exp(np.linspace(np.log(max_lambda), np.log(min_lambda), lambda_bins))
aic_trace = np.zeros(lambda_grid.shape) # The AIC score for each lambda v... |
Generate sequences. | def main():
""" Generate sequences."""
parser = OptionParser(conflict_handler="resolve")
parser.add_option('--humanTRA', '--human_T_alpha', action='store_true', dest='humanTRA', default=False, help='use default human TRA model (T cell alpha chain)')
parser.add_option('--humanTRB', '--human_T_beta', ac... |
Netmiko is being used to push set commands. | def _send_merge_commands(self, config, file_config):
"""
Netmiko is being used to push set commands.
"""
if self.loaded is False:
if self._save_backup() is False:
raise MergeConfigException('Error while storing backup '
... |
Netmiko is being used to obtain config diffs because pan - python doesn t support the needed command. | def compare_config(self):
"""
Netmiko is being used to obtain config diffs because pan-python
doesn't support the needed command.
"""
if self.ssh_connection is False:
self._open_ssh()
self.ssh_device.exit_config_mode()
diff = self.ssh_device.send_comm... |
Netmiko is being used to commit the configuration because it takes a better care of results compared to pan - python. | def commit_config(self):
"""
Netmiko is being used to commit the configuration because it takes
a better care of results compared to pan-python.
"""
if self.loaded:
if self.ssh_connection is False:
self._open_ssh()
try:
self... |
Netmiko is being used to commit the rollback configuration because it takes a better care of results compared to pan - python. | def rollback(self):
"""
Netmiko is being used to commit the rollback configuration because
it takes a better care of results compared to pan-python.
"""
if self.changed:
rollback_cmd = '<load><config><from>{0}</from></config></load>'.format(self.backup_file)
... |
Return LLDP neighbors details. | def get_lldp_neighbors(self):
"""Return LLDP neighbors details."""
neighbors = {}
cmd = '<show><lldp><neighbors>all</neighbors></lldp></show>'
try:
self.device.op(cmd=cmd)
lldp_table_xml = xmltodict.parse(self.device.xml_root())
lldp_table_json = jso... |
Return route details to a specific destination learned from a certain protocol. | def get_route_to(self, destination='', protocol=''):
"""Return route details to a specific destination, learned from a certain protocol."""
# Note, it should be possible to query the FIB:
# "<show><routing><fib></fib></routing></show>"
# To add informations to this getter
routes... |
Return IP interface data. | def get_interfaces_ip(self):
'''Return IP interface data.'''
def extract_ip_info(parsed_intf_dict):
'''
IPv4:
- Primary IP is in the '<ip>' tag. If no v4 is configured the return value is 'N/A'.
- Secondary IP's are in '<addr>'. If no secondaries, thi... |
Return a refined CSG. To each polygon a middle point is added to each edge and to the center of the polygon | def refine(self):
"""
Return a refined CSG. To each polygon, a middle point is added to each edge and to the center
of the polygon
"""
newCSG = CSG()
for poly in self.polygons:
verts = poly.vertices
numVerts = len(verts)
if numVerts ... |
Translate Geometry. disp: displacement ( array of floats ) | def translate(self, disp):
"""
Translate Geometry.
disp: displacement (array of floats)
"""
d = Vector(disp[0], disp[1], disp[2])
for poly in self.polygons:
for v in poly.vertices:
v.pos = v.pos.plus(d) |
Rotate geometry. axis: axis of rotation ( array of floats ) angleDeg: rotation angle in degrees | def rotate(self, axis, angleDeg):
"""
Rotate geometry.
axis: axis of rotation (array of floats)
angleDeg: rotation angle in degrees
"""
ax = Vector(axis[0], axis[1], axis[2]).unit()
cosAngle = math.cos(math.pi * angleDeg / 180.)
sinAngle = math.sin(m... |
Return list of vertices polygons ( cells ) and the total number of vertex indices in the polygon connectivity list ( count ). | def toVerticesAndPolygons(self):
"""
Return list of vertices, polygons (cells), and the total
number of vertex indices in the polygon connectivity list
(count).
"""
offset = 1.234567890
verts = []
polys = []
vertexIndexMap = {}
count = 0
... |
Save polygons in VTK file. | def saveVTK(self, filename):
"""
Save polygons in VTK file.
"""
with open(filename, 'w') as f:
f.write('# vtk DataFile Version 3.0\n')
f.write('pycsg output\n')
f.write('ASCII\n')
f.write('DATASET POLYDATA\n')
verts, ce... |
Return a new CSG solid representing space in either this solid or in the solid csg. Neither this solid nor the solid csg are modified.:: A. union ( B ) + ------- + + ------- + | | | | | A | | | | + -- + ---- + = | + ---- + + ---- + -- + | + ---- + | | B | | | | | | | + ------- + + ------- + | def union(self, csg):
"""
Return a new CSG solid representing space in either this solid or in the
solid `csg`. Neither this solid nor the solid `csg` are modified.::
A.union(B)
+-------+ +-------+
| | | |
... |
Return a new CSG solid with solid and empty space switched. This solid is not modified. | def inverse(self):
"""
Return a new CSG solid with solid and empty space switched. This solid is
not modified.
"""
csg = self.clone()
map(lambda p: p.flip(), csg.polygons)
return csg |
Construct an axis - aligned solid cuboid. Optional parameters are center and radius which default to [ 0 0 0 ] and [ 1 1 1 ]. The radius can be specified using a single number or a list of three numbers one for each axis. Example code:: cube = CSG. cube ( center = [ 0 0 0 ] radius = 1 ) | def cube(cls, center=[0,0,0], radius=[1,1,1]):
"""
Construct an axis-aligned solid cuboid. Optional parameters are `center` and
`radius`, which default to `[0, 0, 0]` and `[1, 1, 1]`. The radius can be
specified using a single number or a list of three numbers, one for each axis.
... |
Returns a sphere. Kwargs: center ( list ): Center of sphere default [ 0 0 0 ]. radius ( float ): Radius of sphere default 1. 0. slices ( int ): Number of slices default 16. stacks ( int ): Number of stacks default 8. | def sphere(cls, **kwargs):
""" Returns a sphere.
Kwargs:
center (list): Center of sphere, default [0, 0, 0].
radius (float): Radius of sphere, default 1.0.
slices (int): Number of slices, default 16.
... |
Returns a cylinder. Kwargs: start ( list ): Start of cylinder default [ 0 - 1 0 ]. end ( list ): End of cylinder default [ 0 1 0 ]. radius ( float ): Radius of cylinder default 1. 0. slices ( int ): Number of slices default 16. | def cylinder(cls, **kwargs):
""" Returns a cylinder.
Kwargs:
start (list): Start of cylinder, default [0, -1, 0].
end (list): End of cylinder, default [0, 1, 0].
radius (float): Radius of cylinder, default... |
Returns a cone. Kwargs: start ( list ): Start of cone default [ 0 - 1 0 ]. end ( list ): End of cone default [ 0 1 0 ]. radius ( float ): Maximum radius of cone at start default 1. 0. slices ( int ): Number of slices default 16. | def cone(cls, **kwargs):
""" Returns a cone.
Kwargs:
start (list): Start of cone, default [0, -1, 0].
end (list): End of cone, default [0, 1, 0].
radius (float): Maximum radius of cone at start, default 1.... |
Load the nbt file at the specified location. By default the function will figure out by itself if the file is gzipped before loading it. You can pass a boolean to the gzipped keyword only argument to specify explicitly whether the file is compressed or not. You can also use the byteorder keyword only argument to specif... | def load(filename, *, gzipped=None, byteorder='big'):
"""Load the nbt file at the specified location.
By default, the function will figure out by itself if the file is
gzipped before loading it. You can pass a boolean to the `gzipped`
keyword only argument to specify explicitly whether the file is... |
Load nbt file from a file - like object. The buff argument can be either a standard io. BufferedReader for uncompressed nbt or a gzip. GzipFile for gzipped nbt data. | def from_buffer(cls, buff, byteorder='big'):
"""Load nbt file from a file-like object.
The `buff` argument can be either a standard `io.BufferedReader`
for uncompressed nbt or a `gzip.GzipFile` for gzipped nbt data.
"""
self = cls.parse(buff, byteorder)
self.filen... |
Read parse and return the file at the specified location. The gzipped argument is used to indicate if the specified file is gzipped. The byteorder argument lets you specify whether the file is big - endian or little - endian. | def load(cls, filename, gzipped, byteorder='big'):
"""Read, parse and return the file at the specified location.
The `gzipped` argument is used to indicate if the specified
file is gzipped. The `byteorder` argument lets you specify
whether the file is big-endian or little-endian.
... |
Write the file at the specified location. The gzipped keyword only argument indicates if the file should be gzipped. The byteorder keyword only argument lets you specify whether the file should be big - endian or little - endian. If the method is called without any argument it will default to the instance attributes an... | def save(self, filename=None, *, gzipped=None, byteorder=None):
"""Write the file at the specified location.
The `gzipped` keyword only argument indicates if the file should
be gzipped. The `byteorder` keyword only argument lets you
specify whether the file should be big-endian or ... |
Change method return value from raw API output to collection of models | def return_collection(collection_type):
"""Change method return value from raw API output to collection of models
"""
def outer_func(func):
@functools.wraps(func)
def inner_func(self, *pargs, **kwargs):
result = func(self, *pargs, **kwargs)
return list(map(collection_... |
Update related objects when the Stop is updated | def post_save_stop(sender, instance, **kwargs):
'''Update related objects when the Stop is updated'''
from multigtfs.models.trip import Trip
trip_ids = instance.stoptime_set.filter(
trip__shape=None).values_list('trip_id', flat=True).distinct()
for trip in Trip.objects.filter(id__in=trip_ids):
... |
Handle actions that need to be done with every response | def _do_post_request_tasks(self, response_data):
"""Handle actions that need to be done with every response
I'm not sure what these session_ops are actually used for yet, seems to
be a way to tell the client to do *something* if needed.
"""
try:
sess_ops = response_d... |
Build a function to do an API request | def _build_request(self, method, url, params=None):
"""Build a function to do an API request
"We have to go deeper" or "It's functions all the way down!"
"""
full_params = self._get_base_params()
if params is not None:
full_params.update(params)
try:
... |
Build a URL for a API method request | def _build_request_url(self, secure, api_method):
"""Build a URL for a API method request
"""
if secure:
proto = ANDROID_MANGA.PROTOCOL_SECURE
else:
proto = ANDROID_MANGA.PROTOCOL_INSECURE
req_url = ANDROID_MANGA.API_URL.format(
protocol=proto,... |
Login using email/ username and password used to get the auth token | def cr_login(self, response):
"""
Login using email/username and password, used to get the auth token
@param str account
@param str password
@param str hash_id (optional)
"""
self._state_params['auth'] = response['auth']
self._user_data = response['user']... |
Handle data loaded from database. | def from_db_value(self, value, expression, connection, context):
'''Handle data loaded from database.'''
if value is None:
return value
return self.parse_seconds(value) |
Handle data from serialization and form clean () methods. | def to_python(self, value):
'''Handle data from serialization and form clean() methods.'''
if isinstance(value, Seconds):
return value
if value in self.empty_values:
return None
return self.parse_seconds(value) |
Parse string into Seconds instances. | def parse_seconds(value):
'''
Parse string into Seconds instances.
Handled formats:
HH:MM:SS
HH:MM
SS
'''
svalue = str(value)
colons = svalue.count(':')
if colons == 2:
hours, minutes, seconds = [int(v) for v in svalue.split(':... |
Prepare value for database storage. | def get_prep_value(self, value):
'''Prepare value for database storage.'''
if isinstance(value, Seconds):
return value.seconds
elif value:
return self.parse_seconds(value).seconds
else:
return None |
Returns the positions and colors of all intervals inside the colorbar. | def calculate_colorbar(self):
"""
Returns the positions and colors of all intervals inside the colorbar.
"""
self._base._process_values()
self._base._find_range()
X, Y = self._base._mesh()
C = self._base._values[:, np.newaxis]
return X, Y, C |
Returns the sequence of ticks ( colorbar data locations ) ticklabels ( strings ) and the corresponding offset string. | def calculate_ticks(self):
"""
Returns the sequence of ticks (colorbar data locations),
ticklabels (strings), and the corresponding offset string.
"""
current_version = packaging.version.parse(matplotlib.__version__)
critical_version = packaging.version.parse('3.0.0')
... |
CR doesn t seem to provide the video_format and video_quality params through any of the APIs so we have to scrape the video page | def get_media_formats(self, media_id):
"""CR doesn't seem to provide the video_format and video_quality params
through any of the APIs so we have to scrape the video page
"""
url = (SCRAPER.API_URL + 'media-' + media_id).format(
protocol=SCRAPER.PROTOCOL_INSECURE)
for... |
Parse a literal nbt string and return the resulting tag. | def parse_nbt(literal):
"""Parse a literal nbt string and return the resulting tag."""
parser = Parser(tokenize(literal))
tag = parser.parse()
cursor = parser.token_span[1]
leftover = literal[cursor:]
if leftover.strip():
parser.token_span = cursor, cursor + len(leftover)
raise ... |
Match and yield all the tokens of the input string. | def tokenize(string):
"""Match and yield all the tokens of the input string."""
for match in TOKENS_REGEX.finditer(string):
yield Token(match.lastgroup, match.group().strip(), match.span()) |
Move to the next token in the token stream. | def next(self):
"""Move to the next token in the token stream."""
self.current_token = next(self.token_stream, None)
if self.current_token is None:
self.token_span = self.token_span[1], self.token_span[1]
raise self.error('Unexpected end of input')
self.token_span... |
Parse and return an nbt literal from the token stream. | def parse(self):
"""Parse and return an nbt literal from the token stream."""
token_type = self.current_token.type.lower()
handler = getattr(self, f'parse_{token_type}', None)
if handler is None:
raise self.error(f'Invalid literal {self.current_token.value!r}')
return... |
Parse a number from the token stream. | def parse_number(self):
"""Parse a number from the token stream."""
value = self.current_token.value
suffix = value[-1].lower()
try:
if suffix in NUMBER_SUFFIXES:
return NUMBER_SUFFIXES[suffix](value[:-1])
return Double(value) if '.' in value else... |
Parse a regular unquoted string from the token stream. | def parse_string(self):
"""Parse a regular unquoted string from the token stream."""
aliased_value = LITERAL_ALIASES.get(self.current_token.value.lower())
if aliased_value is not None:
return aliased_value
return String(self.current_token.value) |
Yield the item tokens in a comma - separated tag collection. | def collect_tokens_until(self, token_type):
"""Yield the item tokens in a comma-separated tag collection."""
self.next()
if self.current_token.type == token_type:
return
while True:
yield self.current_token
self.next()
if self.current_tok... |
Parse a compound from the token stream. | def parse_compound(self):
"""Parse a compound from the token stream."""
compound_tag = Compound()
for token in self.collect_tokens_until('CLOSE_COMPOUND'):
item_key = token.value
if token.type not in ('NUMBER', 'STRING', 'QUOTED_STRING'):
raise self.error... |
Parse and yield array items from the token stream. | def array_items(self, number_type, *, number_suffix=''):
"""Parse and yield array items from the token stream."""
for token in self.collect_tokens_until('CLOSE_BRACKET'):
is_number = token.type == 'NUMBER'
value = token.value.lower()
if not (is_number and value.endswi... |
Parse a list from the token stream. | def parse_list(self):
"""Parse a list from the token stream."""
try:
return List([self.parse() for _ in
self.collect_tokens_until('CLOSE_BRACKET')])
except IncompatibleItemType as exc:
raise self.error(f'Item {str(exc.item)!r} is not a '
... |
Return the unquoted value of a quoted string. | def unquote_string(self, string):
"""Return the unquoted value of a quoted string."""
value = string[1:-1]
forbidden_sequences = {ESCAPE_SUBS[STRING_QUOTES[string[0]]]}
valid_sequences = set(ESCAPE_SEQUENCES) - forbidden_sequences
for seq in ESCAPE_REGEX.findall(value):
... |
Returns a function that will open a file in a zipfile by name. | def opener_from_zipfile(zipfile):
"""
Returns a function that will open a file in a zipfile by name.
For Python3 compatibility, the raw file will be converted to text.
"""
def opener(filename):
inner_file = zipfile.open(filename)
if PY3:
from io import TextIOWrapper
... |
Write CSV row data which may include text. | def write_text_rows(writer, rows):
'''Write CSV row data which may include text.'''
for row in rows:
try:
writer.writerow(row)
except UnicodeEncodeError:
# Python 2 csv does badly with unicode outside of ASCII
new_row = []
for item in row:
... |
Serialize an nbt tag to its literal representation. | def serialize_tag(tag, *, indent=None, compact=False, quote=None):
"""Serialize an nbt tag to its literal representation."""
serializer = Serializer(indent=indent, compact=compact, quote=quote)
return serializer.serialize(tag) |
Increase the level of indentation by one. | def depth(self):
"""Increase the level of indentation by one."""
if self.indentation is None:
yield
else:
previous = self.previous_indent
self.previous_indent = self.indent
self.indent += self.indentation
yield
self.indent =... |
Return whether the specified tag should be expanded. | def should_expand(self, tag):
"""Return whether the specified tag should be expanded."""
return self.indentation is not None and tag and (
not self.previous_indent or (
tag.serializer == 'list'
and tag.subtype.serializer in ('array', 'list', 'compound')
... |
Return the escaped literal representation of an nbt string. | def escape_string(self, string):
"""Return the escaped literal representation of an nbt string."""
if self.quote:
quote = self.quote
else:
found = QUOTE_REGEX.search(string)
quote = STRING_QUOTES[found.group()] if found else next(iter(STRING_QUOTES))
... |
Escape the compound key if it can t be represented unquoted. | def stringify_compound_key(self, key):
"""Escape the compound key if it can't be represented unquoted."""
if UNQUOTED_COMPOUND_KEY.match(key):
return key
return self.escape_string(key) |
Return the literal representation of a tag. | def serialize(self, tag):
"""Return the literal representation of a tag."""
handler = getattr(self, f'serialize_{tag.serializer}', None)
if handler is None:
raise TypeError(f'Can\'t serialize {type(tag)!r} instance')
return handler(tag) |
Return the literal representation of a numeric tag. | def serialize_numeric(self, tag):
"""Return the literal representation of a numeric tag."""
str_func = int.__str__ if isinstance(tag, int) else float.__str__
return str_func(tag) + tag.suffix |
Return the literal representation of an array tag. | def serialize_array(self, tag):
"""Return the literal representation of an array tag."""
elements = self.comma.join(f'{el}{tag.item_suffix}' for el in tag)
return f'[{tag.array_prefix}{self.semicolon}{elements}]' |
Return the literal representation of a list tag. | def serialize_list(self, tag):
"""Return the literal representation of a list tag."""
separator, fmt = self.comma, '[{}]'
with self.depth():
if self.should_expand(tag):
separator, fmt = self.expand(separator, fmt)
return fmt.format(separator.join(map(sel... |
Return the literal representation of a compound tag. | def serialize_compound(self, tag):
"""Return the literal representation of a compound tag."""
separator, fmt = self.comma, '{{{}}}'
with self.depth():
if self.should_expand(tag):
separator, fmt = self.expand(separator, fmt)
return fmt.format(separator.jo... |
Return the _column_map without unused optional fields | def populated_column_map(self):
'''Return the _column_map without unused optional fields'''
column_map = []
cls = self.model
for csv_name, field_pattern in cls._column_map:
# Separate the local field name from foreign columns
if '__' in field_pattern:
... |
Return the objects in the target feed | def in_feed(self, feed):
'''Return the objects in the target feed'''
kwargs = {self.model._rel_to_feed: feed}
return self.filter(**kwargs) |
Import from the GTFS text file | def import_txt(cls, txt_file, feed, filter_func=None):
'''Import from the GTFS text file'''
# Setup the conversion from GTFS to Django Format
# Conversion functions
def no_convert(value): return value
def date_convert(value): return datetime.strptime(value, '%Y%m%d')
d... |
Export records as a GTFS comma - separated file | def export_txt(cls, feed):
'''Export records as a GTFS comma-separated file'''
objects = cls.objects.in_feed(feed)
# If no records, return None
if not objects.exists():
return
# Get the columns used in the dataset
column_map = objects.populated_column_map()
... |
Turn an AndroidApi s method into a function that builds the request sends it then passes the response to the actual method. Should be used as a decorator. | def make_android_api_method(req_method, secure=True, version=0):
"""Turn an AndroidApi's method into a function that builds the request,
sends it, then passes the response to the actual method. Should be used
as a decorator.
"""
def outer_func(func):
def inner_func(self, **kwargs):
... |
Get the params that will be included with every request | def _get_base_params(self):
"""Get the params that will be included with every request
"""
base_params = {
'locale': self._get_locale(),
'device_id': ANDROID.DEVICE_ID,
'device_type': ANDROID.APP_PACKAGE,
'access_token': ANDROID.ACCESS_TO... |
Build a URL for a API method request | def _build_request_url(self, secure, api_method, version):
"""Build a URL for a API method request
"""
if secure:
proto = ANDROID.PROTOCOL_SECURE
else:
proto = ANDROID.PROTOCOL_INSECURE
req_url = ANDROID.API_URL.format(
protocol=proto,
... |
Get if the session is premium for a given media type | def is_premium(self, media_type):
"""Get if the session is premium for a given media type
@param str media_type Should be one of ANDROID.MEDIA_TYPE_*
@return bool
"""
if self.logged_in:
if media_type in self._user_data['premium']:
return True
... |
Login using email/ username and password used to get the auth token | def login(self, response):
"""
Login using email/username and password, used to get the auth token
@param str account
@param str password
@param int duration (optional)
"""
self._state_params['auth'] = response['auth']
self._user_data = response['user']
... |
Read a numeric value from a file - like object. | def read_numeric(fmt, buff, byteorder='big'):
"""Read a numeric value from a file-like object."""
try:
fmt = fmt[byteorder]
return fmt.unpack(buff.read(fmt.size))[0]
except StructError:
return 0
except KeyError as exc:
raise ValueError('Invalid byte order') from e... |
Write a numeric value to a file - like object. | def write_numeric(fmt, value, buff, byteorder='big'):
"""Write a numeric value to a file-like object."""
try:
buff.write(fmt[byteorder].pack(value))
except KeyError as exc:
raise ValueError('Invalid byte order') from exc |
Read a string from a file - like object. | def read_string(buff, byteorder='big'):
"""Read a string from a file-like object."""
length = read_numeric(USHORT, buff, byteorder)
return buff.read(length).decode('utf-8') |
Write a string to a file - like object. | def write_string(value, buff, byteorder='big'):
"""Write a string to a file-like object."""
data = value.encode('utf-8')
write_numeric(USHORT, len(data), buff, byteorder)
buff.write(data) |
Infer a list subtype from a collection of items. | def infer_list_subtype(items):
"""Infer a list subtype from a collection of items."""
subtype = End
for item in items:
item_type = type(item)
if not issubclass(item_type, Base):
continue
if subtype is End:
subtype = ... |
Cast list item to the appropriate tag type. | def cast_item(cls, item):
"""Cast list item to the appropriate tag type."""
if not isinstance(item, cls.subtype):
incompatible = isinstance(item, Base) and not any(
issubclass(cls.subtype, tag_type) and isinstance(item, tag_type)
for tag_type in cls.all_t... |
Recursively merge tags from another compound. | def merge(self, other):
"""Recursively merge tags from another compound."""
for key, value in other.items():
if key in self and (isinstance(self[key], Compound)
and isinstance(value, dict)):
self[key].merge(value)
else:
... |
Decrypt encrypted subtitle data in high level model object | def decrypt_subtitle(self, subtitle):
"""Decrypt encrypted subtitle data in high level model object
@param crunchyroll.models.Subtitle subtitle
@return str
"""
return self.decrypt(self._build_encryption_key(int(subtitle.id)),
subtitle['iv'][0].text.decode('base64'),
... |
Decrypt encrypted subtitle data | def decrypt(self, encryption_key, iv, encrypted_data):
"""Decrypt encrypted subtitle data
@param int subtitle_id
@param str iv
@param str encrypted_data
@return str
"""
logger.info('Decrypting subtitles with length (%d bytes), key=%r',
len(encrypted_... |
Generate the encryption key for a given media item | def _build_encryption_key(self, subtitle_id, key_size=ENCRYPTION_KEY_SIZE):
"""Generate the encryption key for a given media item
Encryption key is basically just
sha1(<magic value based on subtitle_id> + '"#$&).6CXzPHw=2N_+isZK') then
padded with 0s to 32 chars
@param int subt... |
Build the other half of the encryption key hash | def _build_hash_magic(self, subtitle_id):
"""Build the other half of the encryption key hash
I have no idea what is going on here
@param int subtitle_id
@return str
"""
media_magic = self.HASH_MAGIC_CONST ^ subtitle_id
hash_magic = media_magic ^ media_magic >> ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.