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 _create_endpoints(self): """Create all api endpoints using self.endpoint and partial from functools"""
for k, v in self.endpoints.items(): _repr = '%s.%s' % (self.__class__.__name__, k) self.__dict__[k] = EndPointPartial(self._make_request, v, _repr)
<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(binary, **params): """Turns a ZIP file into a frozen sample."""
binary = io.BytesIO(binary) collection = list() with zipfile.ZipFile(binary, 'r') as zip_: for zip_info in zip_.infolist(): content_type, encoding = mimetypes.guess_type(zip_info.filename) content = zip_.read(zip_info) content = content_encodings.get(encoding).de...
<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(collection, **params): """Truns a python object into a ZIP file."""
binary = io.BytesIO() with zipfile.ZipFile(binary, 'w') as zip_: now = datetime.datetime.utcnow().timetuple() for filename, content in collection: content_type, encoding = mimetypes.guess_type(filename) content = content_types.get(content_type).parse(content, **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 keywords_for(*args): """ Return a list of ``Keyword`` objects for the given model instance or a model class. In the case of a model class, retrieve all keywo...
# Handle a model instance. if isinstance(args[0], Model): obj = args[0] if getattr(obj, "content_model", None): obj = obj.get_content_model() keywords_name = obj.get_keywordsfield_name() keywords_queryset = getattr(obj, keywords_name).all() # Keywords may ha...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def flag(request, comment_id, next=None): """ Flags a comment. Confirmation on GET, action on POST. Templates: :template:`comments/flag.html`, Context: comment t...
comment = get_object_or_404(comments.get_model(), pk=comment_id, site__pk=settings.SITE_ID) # Flag on POST if request.method == 'POST': perform_flag(request, comment) return next_redirect(request, fallback=next or 'comments-flag-done', c=comment.pk) # Render a form on GET ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def perform_flag(request, comment): """ Actually perform the flagging of a comment from a request. """
flag, created = comments.models.CommentFlag.objects.get_or_create( comment = comment, user = request.user, flag = comments.models.CommentFlag.SUGGEST_REMOVAL ) signals.comment_was_flagged.send( sender = comment.__class__, comment = comment, flag = f...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def onConnect(self, request): """ Called when a client opens a websocket connection """
logger.debug("Connection opened ({peer})".format(peer=self.peer)) self.storage = {} self._client_id = str(uuid1())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def onOpen(self): """ Called when a client has opened a websocket connection """
self.factory.add_client(self) # Publish ON_OPEN message self.factory.mease.publisher.publish( message_type=ON_OPEN, client_id=self._client_id, client_storage=self.storage)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def onClose(self, was_clean, code, reason): """ Called when a client closes a websocket connection """
logger.debug("Connection closed ({peer})".format(peer=self.peer)) # Publish ON_CLOSE message self.factory.mease.publisher.publish( message_type=ON_CLOSE, client_id=self._client_id, client_storage=self.storage) self.factory.remove_client(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 onMessage(self, payload, is_binary): """ Called when a client sends a message """
if not is_binary: payload = payload.decode('utf-8') logger.debug("Incoming message ({peer}) : {message}".format( peer=self.peer, message=payload)) # Publish ON_RECEIVE message self.factory.mease.publisher.publish( message_type=ON...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send(self, payload, *args, **kwargs): """ Alias for WebSocketServerProtocol `sendMessage` method """
if isinstance(payload, (list, dict)): payload = json.dumps(payload) self.sendMessage(payload.encode(), *args, **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 run_server(self): """ Runs the WebSocket server """
self.protocol = MeaseWebSocketServerProtocol reactor.listenTCP(port=self.port, factory=self, interface=self.host) logger.info("Websocket server listening on {address}".format( address=self.address)) reactor.run()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def open(self, name, *args, **kwargs): """Open file, possibly relative to a base directory."""
if self.basedir is not None: name = os.path.join(self.basedir, name) return em.Subsystem.open(self, name, *args, **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 get_live_weather(lat, lon, writer): """Gets the live weather via lat and long"""
requrl = FORECAST_BASE_URL+forecast_api_token+'/'+str(lat)+','+str(lon) req = requests.get(requrl) if req.status_code == requests.codes.ok: weather = req.json() if not weather['currently']: click.secho("No live weather currently", fg="red", bold=True) return ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert(string, sanitize=False): """ Swap characters from script to transliterated version and vice versa. Optionally sanitize string by using preprocess fun...
return r.convert(string, (preprocess if sanitize else 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 load_yaml(filename): """ Loads a YAML-formatted file. """
with open(filename) as f: ydoc = yaml.safe_load(f.read()) return (ydoc, serialize_tojson(ydoc))
<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_yaml_tofile(filename, resource): """ Serializes a K8S resource to YAML-formatted file. """
stream = file(filename, "w") yaml.dump(resource, stream, default_flow_style=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 parse(binary, **params): """Turns a JSON structure into a python object."""
encoding = params.get('charset', 'UTF-8') return json.loads(binary, encoding=encoding)
<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(item, **params): """Truns a python object into a JSON structure."""
encoding = params.get('charset', 'UTF-8') return json.dumps(item, encoding=encoding)
<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_results(vcs, signature, result_path, patterns): """Save results matching `patterns` at `result_path`. Args: vcs (easyci.vcs.base.Vcs) - the VCS object f...
results_directory = _get_results_directory(vcs, signature) if not os.path.exists(results_directory): os.makedirs(results_directory) with open(os.path.join(results_directory, 'patterns'), 'w') as f: f.write('\n'.join(patterns)) if not os.path.exists(os.path.join(results_directory, 'resul...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sync_results(vcs, signature): """Sync the saved results for `signature` back to the project. Args: vcs (easyci.vcs.base.Vcs) signature (str) Raises: ResultsN...
results_directory = _get_results_directory(vcs, signature) if not os.path.exists(results_directory): raise ResultsNotFoundError with open(os.path.join(results_directory, 'patterns'), 'r') as f: patterns = f.read().strip().split() includes = ['--include={}'.format(x) 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 remove_results(vcs, signature): """Removed saved results for this signature Args: vcs (easyci.vcs.base.Vcs) signature (str) Raises: ResultsNotFoundError """
results_directory = _get_results_directory(vcs, signature) if not os.path.exists(results_directory): raise ResultsNotFoundError shutil.rmtree(results_directory)
<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_signatures_with_results(vcs): """Returns the list of signatures for which test results are saved. Args: vcs (easyci.vcs.base.Vcs) Returns: List[str] """
results_dir = os.path.join(vcs.private_dir(), 'results') if not os.path.exists(results_dir): return [] rel_paths = os.listdir(results_dir) return [p for p in rel_paths if os.path.isdir(os.path.join(results_dir, p))]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def nub(it): '''Dedups an iterable in arbitrary order. Uses memory proportional to the number of unique items in ``it``. ''' seen = set() for v in it: h = hash(v) if h in seen: continue seen.add(h) yield 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 folders(self, ann_id=None): '''Yields an unordered generator for all available folders. By default (with ``ann_id=None``), folders are shown for all anonymous users. Optionally, ``ann_id`` can be set to a username, which restricts the list to only folders owned by that user. ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def subfolders(self, folder_id, ann_id=None): '''Yields an unodered generator of subfolders in a folder. By default (with ``ann_id=None``), subfolders are shown for all anonymous users. Optionally, ``ann_id`` can be set to a username, which restricts the list to only subfolders owned by...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def parent_subfolders(self, ident, ann_id=None): '''An unordered generator of parent subfolders for ``ident``. ``ident`` can either be a ``content_id`` or a tuple of ``(content_id, subtopic_id)``. Parent subfolders are limited to the annotator id given. :param ident: identifie...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def items(self, folder_id, subfolder_id, ann_id=None): '''Yields an unodered generator of items in a subfolder. The generator yields items, which are represented by a tuple of ``content_id`` and ``subtopic_id``. The format of these identifiers is unspecified. By default (with `...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def grouped_items(self, folder_id, subfolder_id, ann_id=None): '''Returns a dictionary from content ids to subtopic ids. Namely, the mapping is ``content_id |--> list of subtopic id``. By default (with ``ann_id=None``), subfolders are shown for all anonymous users. Optionally, ``ann_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 add_folder(self, folder_id, ann_id=None): '''Add a folder. If ``ann_id`` is set, then the folder is owned by the given user. Otherwise, the folder is owned and viewable by all anonymous users. :param str folder_id: Folder id :param str ann_id: 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 add_item(self, folder_id, subfolder_id, content_id, subtopic_id=None, ann_id=None): '''Add an item to a subfolder. The format of ``content_id`` and ``subtopic_id`` is unspecified. It is application specific. If ``ann_id`` is set, then the item is owned by the given...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_models(args): """Generates models from the script input."""
data_table = get_data_table(args.filename) tables = to_tables(data_table.rows_to_dicts()) attr_indent = "\n" + args.indent * 2 attr_sep = "," + attr_indent for tname, cols in tables.items(): model_name = table_to_model_name(tname, list(cols.values())[0]["table_schema"]) pk_cols, oth_cols = split_pks...
<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_data_table(filename): """Returns a DataTable instance built from either the filename, or STDIN if filename is None."""
with get_file_object(filename, "r") as rf: return DataTable(list(csv.reader(rf)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_tables(cols): """Builds and returns a Dictionary whose keys are table names and values are OrderedDicts whose keys are column names and values are the col...
tables = OrderedDict() for col in cols: tname = col["table_name"] if tname not in tables: tables[tname] = OrderedDict() tables[tname][col["column_name"]] = col return tables
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def snake_to_pascal(name, singularize=False): """Converts snake_case to PascalCase. If singularize is True, an attempt is made at singularizing each part of the ...
parts = name.split("_") if singularize: return "".join(p.upper() if p in _ALL_CAPS else to_singular(p.title()) for p in parts) else: return "".join(p.upper() if p in _ALL_CAPS else p.title() for p in parts)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_singular(word): """Attempts to singularize a word."""
if word[-1] != "s": return word elif word.endswith("ies"): return word[:-3] + "y" elif word.endswith("ses"): return word[:-2] else: return word[:-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_timestamps(cols, created_name, updated_name): """Returns a 2-tuple of the timestamp columns that were found on the table definition."""
has_created = created_name in cols has_updated = updated_name in cols return (created_name if has_created else None, updated_name if has_updated else 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 pull_from_origin(repo_path): """Execute 'git pull' at the provided repo_path."""
LOG.info("Pulling from origin at %s." % repo_path) command = GIT_PULL_CMD.format(repo_path) resp = envoy.run(command) if resp.status_code != 0: LOG.exception("Pull failed.") raise GitException(resp.std_err) else: LOG.info("Pull successful.")
<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_remote_origin(repo_dir): """Read the remote origin URL from the given git repo, or None if unset."""
conf = ConfigParser() conf.read(os.path.join(repo_dir, '.git/config')) return conf.get('remote "origin"', 'url')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clone_from(repo_url, repo_dir): """Clone a remote git repo into a local directory."""
repo_url = _fix_repo_url(repo_url) LOG.info("Cloning %s into %s." % (repo_url, repo_dir)) cmd = GIT_CLONE_CMD.format(repo_url, repo_dir) resp = envoy.run(cmd) if resp.status_code != 0: LOG.error("Cloned failed: %s" % resp.std_err) raise GitException(resp.std_err) LOG.info("Clone...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def route(method, pattern, handler=None): """register a routing rule Example: route('GET', '/path/<param>', handler) """
if handler is None: return partial(route, method, pattern) return routes.append(method, pattern, 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 spawn(self, owner, *args, **kwargs): """Spawns a new subordinate actor of `owner` and stores it in this container. jobs = Container() jobs.spawn(self, Job) j...
return (self._spawn(owner, self.factory, *args, **kwargs) if self.factory else self._spawn(owner, *args, **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 watch(ctx): """Watch the directory for changes. Automatically run tests. """
vcs = ctx.obj['vcs'] event_handler = TestsEventHandler(vcs) observer = Observer() observer.schedule(event_handler, vcs.path, recursive=True) observer.start() click.echo('Watching directory `{path}`. Use ctrl-c to stop.'.format(path=vcs.path)) while observer.isAlive(): observer.joi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def settings(request=None): """ Add the settings object to the template context. """
from yacms.conf import settings allowed_settings = settings.TEMPLATE_ACCESSIBLE_SETTINGS template_settings = TemplateSettings(settings, allowed_settings) template_settings.update(DEPRECATED) # This is basically the same as the old ADMIN_MEDIA_PREFIX setting, # we just use it in a few spots i...
<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(options): """ list programs that belong to the authenticated user """
configuration = config.get_default() app_url = configuration['app_url'] if options.deployment != None: deployment_name = options.deployment else: deployment_name = configuration['deployment_name'] client_id = configuration['client_id'] client_secret = configuration['client_sec...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def m(self, msg, state=False, more=None, cmdd=None, critical=True, verbose=None): ''' Mysterious mega method managing multiple meshed modules magically .. note:: If this function is used, the code contains facepalms: ``m(`` * It is possible to just show a message, \ o...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def s2m(self): ''' Imports settings to meta ''' m = '%s settings' % (IDENT) self.meta.load(m, 'import %s' % (m), mdict=self.settings.get)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def file_to_base64(path_or_obj, max_mb=None): """converts contents of a file to base64 encoding :param str_or_object path_or_obj: fool pathname string for a file...
if not hasattr(path_or_obj, 'read'): rt = read_file(path_or_obj) else: rt = path_or_obj.read() if max_mb: len_mb = len(rt) / (10024.0 * 1000) if len_mb > max_mb: raise ErrorFileTooBig("File is too big ({.2f} MBytes)" (len_mb)) return b64encode(rt)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dict_clip(a_dict, inlude_keys_lst=[]): """returns a new dict with keys not in included in inlude_keys_lst clipped off"""
return dict([[i[0], i[1]] for i in list(a_dict.items()) if i[0] in inlude_keys_lst])
<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_pp(ll, separator='|', header_line=True, autonumber=True): """pretty print list of lists ll"""
if autonumber: for cnt, i in enumerate(ll): i.insert(0, cnt if cnt > 0 or not header_line else '#') def lenlst(l): return [len(str(i)) for i in l] lst_len = [lenlst(i) for i in ll] lst_rot = zip(*lst_len[::-1]) lst_len = [max(i) for i in lst_rot] frmt = separator +...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def signal_terminate(on_terminate): """a common case program termination signal"""
for i in [signal.SIGINT, signal.SIGQUIT, signal.SIGUSR1, signal.SIGUSR2, signal.SIGTERM]: signal.signal(i, on_terminate)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _safe_mkdir(directory): """Create a directory, ignoring errors if it already exists."""
try: os.makedirs(directory) except OSError as error: if error.errno != errno.EEXIST: raise error
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _stamp_and_update_hook(method, # suppress(too-many-arguments) dependencies, stampfile, func, *args, **kwargs): """Write stamp and call update_stampfile_hook ...
result = _stamp(stampfile, func, *args, **kwargs) method.update_stampfile_hook(dependencies) 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 _sha1_for_file(filename): """Return sha1 for contents of filename."""
with open(filename, "rb") as fileobj: contents = fileobj.read() return hashlib.sha1(contents).hexdigest()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_dependency(self, dependency_path): """Check if mtime of dependency_path is greater than stored mtime."""
stored_hash = self._stamp_file_hashes.get(dependency_path) # This file was newly added, or we don't have a file # with stored hashes yet. Assume out of date. if not stored_hash: return False return stored_hash == _sha1_for_file(dependency_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 update_stampfile_hook(self, dependencies): # suppress(no-self-use) """Loop over all dependencies and store hash for each of them."""
hashes = {d: _sha1_for_file(d) for d in dependencies if os.path.exists(d)} with open(self._stamp_file_hashes_path, "wb") as hashes_file: hashes_file.write(json.dumps(hashes).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 unicode_value(self, string): """ String argument must be in unicode format. """
result = 0 # don't accept strings that contain numbers if self.regex_has_numbers.search(string): raise AbnumException(error_msg % string) else: num_str = self.regex_values.sub(lambda x: '%s ' % self.values[x.group()], s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def import_from_string(value): """Copy of rest_framework.settings.import_from_string"""
value = value.replace('-', '_') try: module_path, class_name = value.rsplit('.', 1) module = import_module(module_path) return getattr(module, class_name) except (ImportError, AttributeError) as ex: raise ImportError("Could not import '{}'. {}: {}.".format( 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_args(args): """ Interpret command line arguments. :param args: `sys.argv` :return: The populated argparse namespace. """
parser = argparse.ArgumentParser(prog='nibble', description='Speed, distance and time ' 'calculations around ' 'quantities of digital ' ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(args): """ Nibble's entry point. :param args: Command-line arguments, with the program in position 0. """
args = _parse_args(args) # sort out logging output and level level = util.log_level_from_vebosity(args.verbosity) root = logging.getLogger() root.setLevel(level) handler = logging.StreamHandler(sys.stdout) handler.setLevel(level) handler.setFormatter(logging.Formatter('%(levelname)s %...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def run(self, conn, tmp, module_name, module_args, inject): ''' transfer & execute a module that is not 'copy' or 'template' ''' # shell and command are the same module if module_name == 'shell': module_name = 'command' module_args += " #USE_SHELL" vv("REMOTE_MO...
<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_models(args): """ Parse a list of ModelName, appname or appname.ModelName list, and return the list of model classes in the IndexRegistry. If the list if...
if args: models = [] for arg in args: match_found = False for model in registry.get_models(): if model._meta.app_label == arg: models.append(model) match_found = True elif '%s.%s' % (model._meta.app_labe...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def plot_dives(dv0, dv1, p, dp, t_on, t_off): '''Plots depths and delta depths with dive start stop markers Args ---- dv0: int Index position of dive start in cue array dv1: int Index position of dive stop in cue array p: ndarray Depth values dp: ndarray Delt...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def plot_dives_pitch(depths, dive_mask, des, asc, pitch, pitch_lf): '''Plot dives with phase and associated pitch angle with HF signal Args ---- depths: ndarray Depth values at each sensor sampling dive_mask: ndarray Boolean mask slicing dives from the tag data des: ndarray ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def plot_depth_descent_ascent(depths, dive_mask, des, asc): '''Plot depth data for whole deployment, descents, and ascents Args ---- depths: ndarray Depth values at each sensor sampling dive_mask: ndarray Boolean mask slicing dives from the tag data des: ndarray boolean ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _update_docstrings(self): """ Runs through the operation methods & updates their docstrings if necessary. If the method has the default placeholder docstring...
ops = self._details.resource_data['operations'] for method_name in ops.keys(): meth = getattr(self.__class__, method_name, None) if not meth: continue if meth.__doc__ != DEFAULT_DOCSTRING: # It already has a custom docstring. Leave ...
<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_relation(self, name, klass=None): """ Constructs a related ``Resource`` or ``Collection``. This allows for construction of classes with information pre...
try: rel_data = self._details.relations[name] except KeyError: msg = "No such relation named '{0}'.".format(name) raise NoRelation(msg) if klass is None: # This is the typical case, where we're not explicitly given a # class to build ...
<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_process_get(self, result): """ Given an object with identifiers, fetches the data for that object from the service. This alters the data on the object i...
if not hasattr(result, 'items'): # If it's not a dict, give up & just return whatever you get. return result # We need to possibly drill into the response & get out the data here. # Check for a result key. result_key = self._details.result_key_for('get') ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def construct_for(self, service_name, resource_name, base_class=None): """ Builds a new, specialized ``Resource`` subclass as part of a given service. This will ...
details = self.details_class( self.session, service_name, resource_name, loader=self.loader ) attrs = { '_details': details, } # Determine what we should call it. klass_name = self._build_class_name(resource_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 filter_headers(criterion): """Filter already loaded headers against some criterion. The criterion function must accept a single argument, which is an instanc...
ip = get_ipython() for headerkind in ['processed', 'raw']: for h in ip.user_ns['_headers'][headerkind][:]: if not criterion(h): ip.user_ns['_headers'][headerkind].remove(h) ip.user_ns['allsamplenames'] = {h.title for h in ip.user_ns['_headers']['processed']}
<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_headers(fsns:List[int]): """Load header files """
ip = get_ipython() ip.user_ns['_headers'] = {} for type_ in ['raw', 'processed']: print("Loading %d headers (%s)" % (len(fsns), type_), flush=True) processed = type_ == 'processed' headers = [] for f in fsns: for l in [l_ for l_ in ip.user_ns['_loaders'] if l_.pr...
<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_size(path): '''Return the size of path in bytes if it exists and can be determined.''' size = os.path.getsize(path) for item in os.walk(path): for file in item[2]: size += os.path.getsize(os.path.join(item[0], file)) return 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 local_data(path): """Return tuples of names, directories, total sizes and files. Each directory represents a single film and the files are the files containe...
dirs = [os.path.join(path, item) for item in os.listdir(path)] names, sizes, files = zip(*[(dir.split('/')[-1], str(get_size(dir)), '##'.join([file for file in os.listdir(dir)])) for dir in dirs]) return zip(names, dirs, sizes, files)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(): """Create a new database with information about the films in the specified directory or directories."""
if not all(map(os.path.isdir, ARGS.directory)): exit('Error: One or more of the specified directories does not exist.') with sqlite3.connect(ARGS.database) as connection: connection.text_factory = str cursor = connection.cursor() cursor.execute('DROP TABLE IF EXISTS Movies') ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ls(): """List all items in the database in a predefined format."""
if not os.path.exists(ARGS.database): exit('Error: The database does not exist; you must create it first.') with sqlite3.connect(ARGS.database) as connection: connection.text_factory = str cursor = connection.cursor() if ARGS.pattern: if not ARGS.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 play(): """Open the matched movie with a media player."""
with sqlite3.connect(ARGS.database) as connection: connection.text_factory = str cursor = connection.cursor() if ARGS.pattern: if not ARGS.strict: ARGS.pattern = '%{0}%'.format(ARGS.pattern) cursor.execute('SELECT * FROM Movies WHERE Name LIKE (?)', ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def random_string(length, numeric_only=False): """ Generates a random string of length equal to the length parameter """
choices = string.digits if numeric_only else string.ascii_uppercase + string.digits return ''.join(random.choice(choices) for _ in range(length))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def random_date(start_year=2000, end_year=2020): """ Generates a random "sensible" date for use in things like issue dates and maturities """
return date(random.randint(start_year, end_year), random.randint(1, 12), random.randint(1, 28))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _finite_well_energy(P, n=1, atol=1e-6): ''' Returns the nth bound-state energy for a finite-potential quantum well with the given well-strength parameter, `P`. ''' assert n > 0 and n <= _finite_well_states(P) pi_2 = pi / 2. r = (1 / (P + pi_2)) * (n * pi_2) eta = n * pi_2 - arcsin(r)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def top(self, n=10, cache=None, prefetch=False): """Find the most popular torrents. Return an array of Torrent objects representing the top n torrents. If the ca...
use_cache = self._use_cache(cache) if use_cache and len(self._top_cache) >= n: return self._top_cache[:n] soup = get(TOP).soup links = soup.find_all("a", class_="detLink")[:n] urls = [urlparse.urljoin(TOP, link.get('href')) for link in links] torrents = [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 torrent_from_url(self, url, cache=True, prefetch=False): """Create a Torrent object from a given URL. If the cache option is set, check to see if we already ...
if self._use_cache(cache) and url in self._torrent_cache: return self._torrent_cache[url] torrent = Torrent(url, cache, prefetch) if cache: self._torrent_cache[url] = torrent return torrent
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _send_command(self, command, immediate=False, timeout=1.0, check_echo=None): """ Send a single command to the drive after sanitizing it. Takes a single given...
# Use the default echo checking if None was given. if check_echo is None: check_echo = self._check_echo # Convert to bytes and then strip comments, whitespace, and # newlines. if sys.hexversion >= 0x03000000: c = bytes(command, encoding='ASCII') ...
<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_response(self, timeout=1.0, eor=('\n', '\n- ')): """ Reads a response from the drive. Reads the response returned by the drive with an optional timeout....
# If no timeout is given or it is invalid and we are using '\n' # as the eor, use the wrapper to read a line with an infinite # timeout. Otherwise, the reading and timeout must be # implemented manually. if (timeout is None or timeout < 0) and eor == '\n': return sel...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _process_response(self, response): """ Processes a response from the drive. Processes the response returned from the drive. It is broken down into the echoed...
# Strip the trailing newline and split the response into lines # by carriage returns. rsp_lines = response.rstrip('\r\n').split('\r') # If we have at least one line, the first one is the echoed # command. If available, it needs to be grabbed and that line # removed from...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send_command(self, command, immediate=False, timeout=1.0, max_retries=0, eor=('\n', '\n- ')): """ Sends a single command to the drive and returns output. Tak...
# Execute the command till it either doesn't have an error or # the maximum number of retries is exceeded. for i in range(0, max_retries+1): # Send the command and stuff the sanitized version in a # list. Then process the response and add it to the list. resp...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send_commands(self, commands, timeout=1.0, max_retries=1, eor=('\n', '\n- ')): """ Send a sequence of commands to the drive and collect output. Takes a seque...
# If eor is not a list, make a list of it replicated enough for # every command. if not isinstance(eor, list): eor = [eor]*len(commands) # Do every command one by one, collecting the responses and # stuffing them in a list. Commands that failed are retried, and ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def low_level_scan(self, verification_resource, scan_profile_resource, path_list, notification_resource_list): """ Low level implementation of the scan launch wh...
data = {"verification_href": verification_resource.href, "profile_href": scan_profile_resource.href, "start_time": "now", "email_notifications_href": [n.href for n in notification_resource_list], "path_list": path_list} url = self.build_fu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setAsApplication(myappid): """ Tells Windows this is an independent application with an unique icon on task bar. id is an unique string to identify this appl...
if os.name == 'nt': import ctypes ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getBestTranslation(basedir, lang=None): """ Find inside basedir the best translation available. lang, if defined, should be a list of prefered languages. It ...
if not lang: lang = QtCore.QLocale.system().uiLanguages() for l in lang: l = l.translate({ord('_'): '-'}) f = os.path.join(basedir, l+'.qm') if os.path.isfile(f): break l = l.translate({ord('-'): '_'}) f = os.path.join(basedir, l+'.qm') if os.path.isfi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def normalize(cls, name): """Return string in all lower case with spaces and question marks removed"""
name = name.lower() # lower-case for _replace in [' ','-','(',')','?']: name = name.replace(_replace,'') return name
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def nein(x): "this is 'not' but not is a keyword so it's 'nein'" if not isinstance(x,(bool,ThreeVL)): raise TypeError(type(x)) return not x if isinstance(x,bool) else ThreeVL(dict(t='f',f='t',u='u')[x.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 compare(operator,a,b): "this could be replaced by overloading but I want == to return a bool for 'in' use" # todo(awinter): what about nested 3vl like "(a=b)=(c=d)". is that allowed by sql? It will choke here if there's a null involved. f=({'=':lambda a,b:a==b,'!=':lambda a,b:a!=b,'>':lambda a,b:a>b,'<'...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def login(request, signature): """ Automatically logs in a user based on a signed PK of a user object. The signature should be generated with the `login` managem...
signer = TimestampSigner() try: pk = signer.unsign(signature, max_age=MAX_AGE_OF_SIGNATURE_IN_SECONDS) except (BadSignature, SignatureExpired) as e: return HttpResponseForbidden("Can't log you in") user = get_object_or_404(get_user_model(), pk=pk) # we *have* to set the backend 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 cloak(request, pk=None): """ Masquerade as a particular user and redirect based on the REDIRECT_FIELD_NAME parameter, or the LOGIN_REDIRECT_URL. Callers can ...
pk = request.POST.get('pk', pk) if pk is None: return HttpResponse("You need to pass a pk POST parameter, or include it in the URL") user = get_object_or_404(get_user_model(), pk=pk) if not can_cloak_as(request.user, user): return HttpResponseForbidden("You are not allowed to cloak as...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def select_template_from_string(arg): """ Select a template from a string, which can include multiple template paths separated by commas. """
if ',' in arg: tpl = loader.select_template( [tn.strip() for tn in arg.split(',')]) else: tpl = loader.get_template(arg) return tpl
<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_package_path(self): """Gets the path of a Python package"""
if not self.package: return [] if not hasattr(self, 'package_path'): m = __import__(self.package) parts = self.package.split('.')[1:] self.package_path = os.path.join(os.path.dirname(m.__file__), *parts) return [self.package_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 _get_paths(self): """Return a list of paths to search for plugins in The list is searched in order."""
ret = [] ret += ['%s/library/' % os.path.dirname(os.path.dirname(__file__))] ret += self._extra_dirs for basedir in _basedirs: fullpath = os.path.join(basedir, self.subdir) if fullpath not in ret: ret.append(fullpath) 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 print_paths(self): """Returns a string suitable for printing of the search path"""
# Uses a list to get the order right ret = [] for i in self._get_paths(): if i not in ret: ret.append(i) return os.pathsep.join(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 find_plugin(self, name): """Find a plugin named name"""
suffix = ".py" if not self.class_name: suffix = "" for i in self._get_paths(): path = os.path.join(i, "%s%s" % (name, suffix)) if os.path.exists(path): return path 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 get_fieldsets(self, *args, **kwargs): """Re-order fields"""
result = super(EventAdmin, self).get_fieldsets(*args, **kwargs) result = list(result) fields = list(result[0][1]['fields']) for name in ('content', 'start', 'end', 'repeat', 'repeat_until', \ 'external_link', 'calendars'): fields.remove(name) fields.a...