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.merge_config: raise MergeConfigException('Error while commiting config') else: raise ReplaceConfigException('Error while commiting config') else: raise ReplaceConfigException('No config loaded.')
<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_device.commit() self.loaded = False self.changed = False self.merge_config = False except: # noqa ReplaceConfigException("Error while loading backup config")
<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, this field is not returned by the xmltodict.parse() method. IPv6: - All addresses are returned in '<addr6>'. If no v6 configured, this is not returned either by xmltodict.parse(). Example of XML response for an intf with multiple IPv4 and IPv6 addresses: <response status="success"> <result> <ifnet> <entry> <name>ethernet1/5</name> <zone/> <fwd>N/A</fwd> <vsys>1</vsys> <dyn-addr/> <addr6> <member>fe80::d61d:71ff:fed8:fe14/64</member> <member>2001::1234/120</member> </addr6> <tag>0</tag> <ip>169.254.0.1/30</ip> <id>20</id> <addr> <member>1.1.1.1/28</member> </addr> </entry> {...} </ifnet> <hw> {...} </hw> </result> </response> ''' intf = parsed_intf_dict['name'] _ip_info = {intf: {}} v4_ip = parsed_intf_dict.get('ip') secondary_v4_ip = parsed_intf_dict.get('addr') v6_ip = parsed_intf_dict.get('addr6') if v4_ip != 'N/A': address, pref = v4_ip.split('/') _ip_info[intf].setdefault('ipv4', {})[address] = {'prefix_length': int(pref)} if secondary_v4_ip is not None: members = secondary_v4_ip['member'] if not isinstance(members, list): # If only 1 secondary IP is present, xmltodict converts field to a string, else # it converts it to a list of strings. members = [members] for address in members: address, pref = address.split('/') _ip_info[intf].setdefault('ipv4', {})[address] = {'prefix_length': int(pref)} if v6_ip is not None: members = v6_ip['member'] if not isinstance(members, list): # Same "1 vs many -> string vs list of strings" comment. members = [members] for address in members: address, pref = address.split('/') _ip_info[intf].setdefault('ipv6', {})[address] = {'prefix_length': int(pref)} # Reset dictionary if no addresses were found. if _ip_info == {intf: {}}: _ip_info = {} return _ip_info ip_interfaces = {} cmd = "<show><interface>all</interface></show>" self.device.op(cmd=cmd) interface_info_xml = xmltodict.parse(self.device.xml_root()) interface_info_json = json.dumps( interface_info_xml['response']['result']['ifnet']['entry'] ) interface_info = json.loads(interface_info_json) if isinstance(interface_info, dict): # Same "1 vs many -> dict vs list of dicts" comment. interface_info = [interface_info] for interface_dict in interface_info: ip_info = extract_ip_info(interface_dict) if ip_info: ip_interfaces.update(ip_info) return ip_interfaces
<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].normal is not None: midNormal = poly.plane.normal midVert = Vertex(midPos, midNormal) newVerts = verts + \ [verts[i].interpolate(verts[(i + 1)%numVerts], 0.5) for i in range(numVerts)] + \ [midVert] i = 0 vs = [newVerts[i], newVerts[i+numVerts], newVerts[2*numVerts], newVerts[2*numVerts-1]] newPoly = Polygon(vs, poly.shared) newPoly.shared = poly.shared newPoly.plane = poly.plane newCSG.polygons.append(newPoly) for i in range(1, numVerts): vs = [newVerts[i], newVerts[numVerts+i], newVerts[2*numVerts], newVerts[numVerts+i-1]] newPoly = Polygon(vs, poly.shared) newCSG.polygons.append(newPoly) return newCSG
<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'.format(len(verts))) for v in verts: f.write('{0} {1} {2}\n'.format(v[0], v[1], v[2])) numCells = len(cells) f.write('POLYGONS {0} {1}\n'.format(numCells, count + numCells)) for cell in cells: f.write('{0} '.format(len(cell))) for index in cell: f.write('{0} '.format(index)) f.write('\n')
<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 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 specify whether the file is little-endian or big-endian. """
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=buff) return File.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 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.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 if the specified file is gzipped. The `byteorder` argument lets you specify whether the file is big-endian or little-endian. """
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 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 and use the file's `filename`, `gzipped` and `byteorder` attributes. Calling the method without a `filename` will raise a `ValueError` if the `filename` of the file is `None`. """
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 buff: self.write(buff, byteorder or self.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 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): trip.update_geometry()
<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 for yet, seems to be a way to tell the client to do *something* if needed. """
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 AttributeError: raise ApiException('Invalid request method') # TODO: need to catch a network here and raise as ApiNetworkException def do_request(): logger.debug('Sending %s request "%s" with params: %r', method, url, full_params) try: resp = request_func(url, full_params) logger.debug('Received response code: %d', resp.status_code) except requests.RequestException as err: raise ApiNetworkException(err) try: resp_json = resp.json() except TypeError: resp_json = resp.json method_returns_list = False try: resp_json['error'] except TypeError: logger.warn('Api method did not return map: %s', method) method_returns_list = True except KeyError: logger.warn('Api method did not return map with error key: %s', method) if method_returns_list is None: raise ApiBadResponseException(resp.content) elif method_returns_list: data = resp_json else: try: if resp_json['error']: raise ApiError('%s: %s' % (resp_json['code'], resp_json['message'])) except KeyError: data = resp_json else: data = resp_json['data'] self._do_post_request_tasks(data) self._last_response = resp return data return do_request
<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(':')] elif colons == 1: hours, minutes = [int(v) for v in svalue.split(':')] seconds = 0 elif colons == 0: hours = 0 minutes = 0 seconds = int(svalue) else: raise ValueError('Must be in seconds or HH:MM:SS format') return Seconds.from_hms(hours, minutes, seconds)
<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 video page """
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={param: '1'}) if not resp.ok: continue try: match = format_pattern.search(resp.content) except TypeError: match = format_pattern.search(resp.text) if match: formats[format] = (int(match.group(1)), int(match.group(2))) 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 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 String(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_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': raise self.error(f'Expected comma but got ' f'{self.current_token.value!r}') self.next()
<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 == 'QUOTED_STRING': item_key = self.unquote_string(item_key) if self.next().current_token.type != 'COLON': raise self.error(f'Expected colon but got ' f'{self.current_token.value!r}') self.next() compound_tag[item_key] = self.parse() return compound_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 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 ' f'{token.value!r}') yield int(value.replace(number_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 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 sequence "{seq}"') for seq, sub in ESCAPE_SEQUENCES.items(): value = value.replace(seq, sub) return 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 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 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: if isinstance(item, text_type): new_row.append(item.encode('utf-8')) else: new_row.append(item) writer.writerow(new_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: string = string.replace(match, seq) return f'{quote}{string}{quote}'
<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)}' for key, value in tag.items() ))
<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: field_name = field_pattern.split('__', 1)[0] else: field_name = field_pattern # Handle point fields point_match = re_point.match(field_name) if point_match: field = None else: field = cls._meta.get_field(field_name) # Only add optional columns if they are used in the records if field and field.blank and not field.has_default(): kwargs = {field_name: get_blank_value(field)} if self.exclude(**kwargs).exists(): column_map.append((csv_name, field_pattern)) else: column_map.append((csv_name, field_pattern)) return column_map
<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 the response to the actual method. Should be used as a decorator. """
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 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 _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) \ for k, v in iteritems(self._state_params) \ if v is not None)) return base_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 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 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 subtype elif subtype is not item_type: stype, itype = subtype, item_type generic = List while issubclass(stype, List) and issubclass(itype, List): stype, itype = stype.subtype, itype.subtype generic = List[generic] if stype is End: subtype = item_type elif itype is not End: return generic.subtype return subtype
<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 IncompatibleItemType(item, cls.subtype) try: return cls.subtype(item) except EndInstantiation: raise ValueError('List tags without an explicit subtype must ' 'either be empty or instantiated with ' 'elements from which a subtype can be ' 'inferred') from None except (IncompatibleItemType, CastError): raise except Exception as exc: raise CastError(item, cls.subtype) from exc return item
<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 str """
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 just sha1(<magic value based on subtitle_id> + '"#$&).6CXzPHw=2N_+isZK') then padded with 0s to 32 chars @param int subtitle_id @param int key_size @return str """
# 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 str """
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 Take first `seq_len` + len(`seq_seed`) characters of Fibonacci sequence, starting with `seq_seed`, and applying e % `mod_value` + `HASH_SECRET_CHAR_OFFSET` to the resulting sequence, then return as a string @param tuple|list seq_seed @param int seq_len @param int mod_value @return str """
# 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:])) return ''.join(hash_secret)
<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 sub_xml_text @return str """
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( 'Login is required but no credentials were provided') self._android_api.login(account=self._state['username'], password=self._state['password']) 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 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'], password=self._state['password']) 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_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 credentials were provided') self._ajax_api.User_Login(name=self._state['username'], password=self._state['password']) 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 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 called @return bool """
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 sorted, should be one of META.SORT_* @param int limit limit number of series to return, there doesn't seem to be an upper bound @param int offset list series starting from this offset, for pagination @return list<crunchyroll.models.Series> """
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 sorted, should be one of META.SORT_* @param int limit limit number of series to return, there doesn't seem to be an upper bound @param int offset list series starting from this offset, for pagination @return list<crunchyroll.models.Series> """
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 the search is very simplistic and only matches against the start of the series name, ex) search for "space" matches "Space Brothers" but wouldn't match "Brothers Space" @return list<crunchyroll.models.Series> """
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 the search is very simplistic and only matches against the start of the series name, ex) search for "space" matches "Space Brothers" but wouldn't match "Brothers Space" @return list<crunchyroll.models.Series> """
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.Series> """
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.Series series the series to search for @param str sort choose the ordering of the results, only META.SORT_DESC is known to work @param int limit limit size of results @param int offset start results from this index, for pagination @return list<crunchyroll.models.Media> """
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 series the series to search in @param str query_string the search query, same restrictions as `search_anime_series` @return list<crunchyroll.models.Media> """
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 format @param int quality @return crunchyroll.models.MediaStream """
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 crunchyroll.models.Subtitle """
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> media_types a list of media types to filter the queue with, should be of META.TYPE_* @return list<crunchyroll.models.Series> """
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 base `CompoundSchema` class. The `name` argument is the name of the class and `dct` should be a dictionnary containing the actual schema. The schema should map keys to tag types or other compound schemas. If the `strict` keyword only argument is set to True, interacting with keys that are not defined in the schema will raise a `TypeError`. """
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: raise except Exception as exc: raise CastError(value, schema_type) from exc return 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 tarbz(source_directory_path, output_file_full_path, silent=False): """ Tars and bzips a directory, preserving as much metadata as possible. Adds '.tbz' to the provided output file name. """
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 already exists, aborting." % (full_tar_file_path)) # preserve permissions, create file, use files (not tape devices), preserve # access time. tar is the only program in the universe to use (dstn, src). tar_command = ("tar jpcfvC %s %s %s" % (full_tar_file_path, source_directory_path, "./")) call(tar_command, silent=silent) return full_tar_file_path
<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 will ensure that a directory is created at the file path if one does not exist already. If used in conjunction with this library's mongodump operation, the backup data will be extracted directly into the provided directory path. This command will fail if the output directory is not empty as existing files with identical names are not overwritten by tar. """
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("your output directory path must start with '/' or './'; you used: %s" % (output_directory_path)) create_folders(output_directory_path) if listdir(output_directory_path): raise Exception("Your output directory isn't empty. Aborting as " + "exiting files are not overwritten by tar.") untar_command = ("tar jxfvkCp %s %s --atime-preserve " % (source_file_path, output_directory_path)) call(untar_command, silent=silent)
<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, then clear all existing search defaults. Examples:: conn.set_search_defaults(scope=ldap.SCOPE_BASE, attrs=['cn']) conn.clear_search_defaults(['scope']) conn.clear_search_defaults() """
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: timeout = self._search_defaults.get('timeout', -1) if limit is None: limit = self._search_defaults.get('limit', 0) results = self.connection.search_ext_s( base_dn, scope, filter, attrs, timeout=timeout, sizelimit=limit) return self.to_items(results)
<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 returns that single object instead of a list. This method takes the exact same arguments as search. """
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 return False there was an exception raised that is contained in self.failed_authentication_exceptions. """
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 ``compare`` function that returns a boolean value instead of 1 or 0. """
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 if it is a tag. """
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_by_kwargs.values()[0] if filter_value: filtered_metrics = [x for x in metrics if x.dimensions.get(filter_key) and x.dimensions.get(filter_key)[0] == filter_value] else: # ServiceName='' filtered_metrics = [x for x in metrics if not x.dimensions.get(filter_key)] else: filtered_metrics = metrics return filtered_metrics
<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_kwargs.values()[0]] else: clusters = [x['CacheClusterId'] for x in data] return clusters
<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(shard['ShardId']) kinesis_streams[stream_name] = shard_ids return kinesis_streams
<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( "{} was already imported. Cannot commit to {}!" .format(name, api) ) else: api = _intern(api) USED_API = api AnyQt.__SELECTED_API = api AnyQt.USED_API = api