text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.ssh_device.commit() time.sleep(3) self.loaded = False self.changed = True except: # noqa if self.merg...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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) self.device.op(cmd=rollback_cmd) time.sleep(5) if self.ssh_connection is False: self._open_ssh() try: self.ssh_d...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 == 0: continue midPos = reduce(operator.add, [v.pos for v in verts]) / float(numVerts) midNormal = None if verts[0...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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, cells, count = self.toVerticesAndPolygons() f.write('POINTS {0} float\n'.for...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 t...
if gzipped is not None: return File.load(filename, gzipped, byteorder) # if we don't know we read the magic number with open(filename, 'rb') as buff: magic_number = buff.read(2) buff.seek(0) if magic_number == b'\x1f\x8b': buff = gzip.GzipFile(fileobj...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
self = cls.parse(buff, byteorder) self.filename = getattr(buff, 'name', self.filename) self.gzipped = isinstance(buff, gzip.GzipFile) self.byteorder = byteorder return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load(cls, filename, gzipped, byteorder='big'): """Read, parse and return the file at the specified location. The `gzipped` argument is used to indicate i...
open_file = gzip.open if gzipped else open with open_file(filename, 'rb') as buff: return cls.from_buffer(buff, byteorder)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save(self, filename=None, *, gzipped=None, byteorder=None): """Write the file at the specified location. The `gzipped` keyword only argument indicates if...
if gzipped is None: gzipped = self.gzipped if filename is None: filename = self.filename if filename is None: raise ValueError('No filename specified') open_file = gzip.open if gzipped else open with open_file(filename, 'wb') as bu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_type, result)) return inner_func return outer_func
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
try: sess_ops = response_data.get('ops', []) except AttributeError: pass else: self._session_ops.extend(sess_ops)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: request_func = lambda u, d: \ getattr(self._connector, method.lower())(u, params=d, headers=self._request_headers) except AttributeErr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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(':...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 v...
url = (SCRAPER.API_URL + 'media-' + media_id).format( protocol=SCRAPER.PROTOCOL_INSECURE) format_pattern = re.compile(SCRAPER.VIDEO.FORMAT_PATTERN) formats = {} for format, param in iteritems(SCRAPER.VIDEO.FORMAT_PARAMS): resp = self._connector.get(url, params={...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 parser.error(f'Expected end of string but got {leftover!r}') return tag
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 = self.current_token.span return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 handler()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 Int(value) except (OutOfRange, ValueError): return Str...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_token.type == token_type: return if self.current_token.type != 'COMMA': ra...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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(f'Expected compound key but got {item_key!r}') if token.type == '...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.endswith(number_suffix)): raise self.error(f'Invalid {number_type} array element ' ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ' f'{exc.subtype.__name__} tag') from None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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): if seq not in valid_sequences: raise self.error(f'Invalid escape sequenc...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
def opener(filename): inner_file = zipfile.open(filename) if PY3: from io import TextIOWrapper return TextIOWrapper(inner_file) else: return inner_file return opener
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 = self.previous_indent self.previous_indent = previous
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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') ) or ( tag.serializer == 'compound' ) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)) for match, seq in ESCAPE_SUBS.items(): if match == quote or match not in STRING_QUOTES: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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}]'
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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(self.serialize, tag)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.join( f'{self.stringify_compound_key(key)}{self.colon}{self.serialize(value)}' ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def in_feed(self, feed): '''Return the objects in the target feed''' kwargs = {self.model._rel_to_feed: feed} return self.filter(**kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 th...
def outer_func(func): def inner_func(self, **kwargs): req_url = self._build_request_url(secure, func.__name__, version) req_func = self._build_request(req_method, req_url, params=kwargs) response = req_func() func(self, response) return response ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_TOKEN, 'version': ANDROID.APP_CODE, } base_params.update(dict((k, v) \ ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 boo...
if self.logged_in: if media_type in self._user_data['premium']: return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 exc
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 = item_type if not issubclass(subtype, List): return subty...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_tags.values() ) if incompatible: raise Inc...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: self[key] = value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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'), subtitle['data'][0].text.decode('base64'))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decrypt(self, encryption_key, iv, encrypted_data): """Decrypt encrypted subtitle data @param int subtitle_id @param str iv @param str encrypted_data @return ...
logger.info('Decrypting subtitles with length (%d bytes), key=%r', len(encrypted_data), encryption_key) return zlib.decompress(aes_decrypt(encryption_key, iv, encrypted_data))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 jus...
# generate a 160-bit SHA1 hash sha1_hash = hashlib.new('sha1', self._build_hash_secret((1, 2)) + self._build_hash_magic(subtitle_id)).digest() # pad to 256-bit hash for 32 byte key sha1_hash += '\x00' * max(key_size - len(sha1_hash), 0) return sha1_hash[:key_size]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
media_magic = self.HASH_MAGIC_CONST ^ subtitle_id hash_magic = media_magic ^ media_magic >> 3 ^ media_magic * 32 return str(hash_magic)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _build_hash_secret(self, seq_seed, seq_len=HASH_SECRET_LENGTH, mod_value=HASH_SECRET_MOD_CONST): """Build a seed for the hash based on the Fibonacci sequence...
# make sure we use a list, tuples are immutable fbn_seq = list(seq_seed) for i in range(seq_len): fbn_seq.append(fbn_seq[-1] + fbn_seq[-2]) hash_secret = list(map( lambda c: chr(c % mod_value + self.HASH_SECRET_CHAR_OFFSET), fbn_seq[2:])) ret...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def format(self, subtitles): """Turn a string containing the subs xml document into the formatted subtitle string @param str|crunchyroll.models.StyledSubtitle su...
logger.debug('Formatting subtitles (id=%s) with %s', subtitles.id, self.__class__.__name__) return self._format(subtitles).encode('utf-8')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def require_session_started(func): """Check if API sessions are started and start them if not """
@functools.wraps(func) def inner_func(self, *pargs, **kwargs): if not self.session_started: logger.info('Starting session for required meta method') self.start_session() return func(self, *pargs, **kwargs) return inner_func
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def require_android_logged_in(func): """Check if andoid API is logged in and login if not, implies `require_session_started` """
@functools.wraps(func) @require_session_started def inner_func(self, *pargs, **kwargs): if not self._android_api.logged_in: logger.info('Logging into android API for required meta method') if not self.has_credentials: raise ApiLoginFailure( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def optional_manga_logged_in(func): """Check if andoid manga API is logged in and login if credentials were provided, implies `require_session_started` """
@functools.wraps(func) @require_session_started def inner_func(self, *pargs, **kwargs): if not self._manga_api.logged_in and self.has_credentials: logger.info('Logging into android manga API for optional meta method') self._manga_api.cr_login(account=self._state['username'],...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def require_ajax_logged_in(func): """Check if ajax API is logged in and login if not """
@functools.wraps(func) def inner_func(self, *pargs, **kwargs): if not self._ajax_api.logged_in: logger.info('Logging into AJAX API for required meta method') if not self.has_credentials: raise ApiLoginFailure( 'Login is required but no credent...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start_session(self): """Start the underlying APIs sessions Calling this is not required, it will be called automatically if a method that needs a session is ...
self._android_api.start_session() self._manga_api.cr_start_session() return self.session_started
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_anime_series(self, sort=META.SORT_ALPHA, limit=META.MAX_SERIES, offset=0): """Get a list of anime series @param str sort pick how results should be sort...
result = self._android_api.list_series( media_type=ANDROID.MEDIA_TYPE_ANIME, filter=sort, limit=limit, offset=offset) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_drama_series(self, sort=META.SORT_ALPHA, limit=META.MAX_SERIES, offset=0): """Get a list of drama series @param str sort pick how results should be sort...
result = self._android_api.list_series( media_type=ANDROID.MEDIA_TYPE_DRAMA, filter=sort, limit=limit, offset=offset) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_manga_series(self, filter=None, content_type='jp_manga'): """Get a list of manga series """
result = self._manga_api.list_series(filter, content_type) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search_anime_series(self, query_string): """Search anime series list by series name, case-sensitive @param str query_string string to search for, note that t...
result = self._android_api.list_series( media_type=ANDROID.MEDIA_TYPE_ANIME, filter=ANDROID.FILTER_PREFIX + query_string) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search_drama_series(self, query_string): """Search drama series list by series name, case-sensitive @param str query_string string to search for, note that t...
result = self._android_api.list_series( media_type=ANDROID.MEDIA_TYPE_DRAMA, filter=ANDROID.FILTER_PREFIX + query_string) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search_manga_series(self, query_string): """Search the manga series list by name, case-insensitive @param str query_string @return list<crunchyroll.models.Se...
result = self._manga_api.list_series() return [series for series in result \ if series['locale']['enUS']['name'].lower().startswith( query_string.lower())]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_media(self, series, sort=META.SORT_DESC, limit=META.MAX_MEDIA, offset=0): """List media for a given series or collection @param crunchyroll.models.Serie...
params = { 'sort': sort, 'offset': offset, 'limit': limit, } params.update(self._get_series_query_dict(series)) result = self._android_api.list_media(**params) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search_media(self, series, query_string): """Search for media from a series starting with query_string, case-sensitive @param crunchyroll.models.Series serie...
params = { 'sort': ANDROID.FILTER_PREFIX + query_string, } params.update(self._get_series_query_dict(series)) result = self._android_api.list_media(**params) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_media_stream(self, media_item, format, quality): """Get the stream data for a given media item @param crunchyroll.models.Media media_item @param int form...
result = self._ajax_api.VideoPlayer_GetStandardConfig( media_id=media_item.media_id, video_format=format, video_quality=quality) return MediaStream(result)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unfold_subtitle_stub(self, subtitle_stub): """Turn a SubtitleStub into a full Subtitle object @param crunchyroll.models.SubtitleStub subtitle_stub @return cr...
return Subtitle(self._ajax_api.Subtitle_GetXml( subtitle_script_id=int(subtitle_stub.id)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_stream_formats(self, media_item): """Get the available media formats for a given media item @param crunchyroll.models.Media @return dict """
scraper = ScraperApi(self._ajax_api._connector) formats = scraper.get_media_formats(media_item.media_id) return formats
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_queue(self, media_types=[META.TYPE_ANIME, META.TYPE_DRAMA]): """List the series in the queue, optionally filtering by type of media @param list<str> med...
result = self._android_api.queue(media_types='|'.join(media_types)) return [queue_item['series'] for queue_item in result]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_to_queue(self, series): """Add a series to the queue @param crunchyroll.models.Series series @return bool """
result = self._android_api.add_to_queue(series_id=series.series_id) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_from_queue(self, series): """Remove a series from the queue @param crunchyroll.models.Series series @return bool """
result = self._android_api.remove_from_queue(series_id=series.series_id) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def schema(name, dct, *, strict=False): """Create a compound tag schema. This function is a short convenience function that makes it easy to subclass the ba...
return type(name, (CompoundSchema,), {'__slots__': (), 'schema': dct, 'strict': strict})
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cast_item(cls, key, value): """Cast schema item to the appropriate tag type."""
schema_type = cls.schema.get(key) if schema_type is None: if cls.strict: raise TypeError(f'Invalid key {key!r}') elif not isinstance(value, schema_type): try: return schema_type(value) except CastError: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tarbz(source_directory_path, output_file_full_path, silent=False): """ Tars and bzips a directory, preserving as much metadata as possible. Adds '.tbz' to th...
output_directory_path = output_file_full_path.rsplit("/", 1)[0] create_folders(output_directory_path) # Note: default compression for bzip is supposed to be -9, highest compression. full_tar_file_path = output_file_full_path + ".tbz" if path.exists(full_tar_file_path): raise Exception("%s a...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def untarbz(source_file_path, output_directory_path, silent=False): """ Restores your mongo database backup from a .tbz created using this library. This function...
if not path.exists(source_file_path): raise Exception("the provided tar file %s does not exist." % (source_file_path)) if output_directory_path[0:1] == "./": output_directory_path = path.abspath(output_directory_path) if output_directory_path[0] != "/": raise Exception("yo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def value_contains(self, value, attribute): """ Determine if any of the items in the value list for the given attribute contain value. """
for item in self[attribute]: if value in item: return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clear_search_defaults(self, args=None): """ Clear all search defaults specified by the list of parameter names given as ``args``. If ``args`` is not given, t...
if args is None: self._search_defaults.clear() else: for arg in args: if arg in self._search_defaults: del self._search_defaults[arg]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search(self, filter, base_dn=None, attrs=None, scope=None, timeout=None, limit=None): """ Search the directory. """
if base_dn is None: base_dn = self._search_defaults.get('base_dn', '') if attrs is None: attrs = self._search_defaults.get('attrs', None) if scope is None: scope = self._search_defaults.get('scope', ldap.SCOPE_SUBTREE) if timeout is None: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(self, *args, **kwargs): """ Get a single object. This is a convenience wrapper for the search method that checks that only one object was returned, and r...
results = self.search(*args, **kwargs) num_results = len(results) if num_results == 1: return results[0] if num_results > 1: raise MultipleObjectsFound() raise ObjectNotFound()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def authenticate(self, dn='', password=''): """ Attempt to authenticate given dn and password using a bind operation. Return True if the bind is successful, and ...
try: self.connection.simple_bind_s(dn, password) except tuple(self.failed_authentication_exceptions): return False else: return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compare(self, dn, attr, value): """ Compare the ``attr`` of the entry ``dn`` with given ``value``. This is a convenience wrapper for the ldap library's ``com...
return self.connection.compare_s(dn, attr, value) == 1
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_property_func(key): """ Get the accessor function for an instance to look for `key`. Look for it as an attribute, and if that does not work, look to see ...
def get_it(obj): try: return getattr(obj, key) except AttributeError: return obj.tags.get(key) return get_it
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_billing(region, filter_by_kwargs): """List available billing metrics"""
conn = boto.ec2.cloudwatch.connect_to_region(region) metrics = conn.list_metrics(metric_name='EstimatedCharges') # Filtering is based on metric Dimensions. Only really valuable one is # ServiceName. if filter_by_kwargs: filter_key = filter_by_kwargs.keys()[0] filter_value = filter_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_ebs(region, filter_by_kwargs): """List running ebs volumes."""
conn = boto.ec2.connect_to_region(region) instances = conn.get_all_volumes() return lookup(instances, filter_by=filter_by_kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_elb(region, filter_by_kwargs): """List all load balancers."""
conn = boto.ec2.elb.connect_to_region(region) instances = conn.get_all_load_balancers() return lookup(instances, filter_by=filter_by_kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_rds(region, filter_by_kwargs): """List all RDS thingys."""
conn = boto.rds.connect_to_region(region) instances = conn.get_all_dbinstances() return lookup(instances, filter_by=filter_by_kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_elasticache(region, filter_by_kwargs): """List all ElastiCache Clusters."""
conn = boto.elasticache.connect_to_region(region) req = conn.describe_cache_clusters() data = req["DescribeCacheClustersResponse"]["DescribeCacheClustersResult"]["CacheClusters"] if filter_by_kwargs: clusters = [x['CacheClusterId'] for x in data if x[filter_by_kwargs.keys()[0]] == filter_by_kwa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_autoscaling_group(region, filter_by_kwargs): """List all Auto Scaling Groups."""
conn = boto.ec2.autoscale.connect_to_region(region) groups = conn.get_all_groups() return lookup(groups, filter_by=filter_by_kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_sqs(region, filter_by_kwargs): """List all SQS Queues."""
conn = boto.sqs.connect_to_region(region) queues = conn.get_all_queues() return lookup(queues, filter_by=filter_by_kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_kinesis_applications(region, filter_by_kwargs): """List all the kinesis applications along with the shards for each stream"""
conn = boto.kinesis.connect_to_region(region) streams = conn.list_streams()['StreamNames'] kinesis_streams = {} for stream_name in streams: shard_ids = [] shards = conn.describe_stream(stream_name)['StreamDescription']['Shards'] for shard in shards: shard_ids.append(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_dynamodb(region, filter_by_kwargs): """List all DynamoDB tables."""
conn = boto.dynamodb.connect_to_region(region) tables = conn.list_tables() return lookup(tables, filter_by=filter_by_kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def comittoapi(api): """ Commit to the use of specified Qt api. Raise an error if another Qt api is already loaded in sys.modules """
global USED_API assert USED_API is None, "committoapi called again!" check = ["PyQt4", "PyQt5", "PySide", "PySide2"] assert api in [QT_API_PYQT5, QT_API_PYQT4, QT_API_PYSIDE, QT_API_PYSIDE2] for name in check: if name.lower() != api and name in sys.modules: raise RuntimeError( ...