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 doc_string(cls): """Get the doc string of this class. If this class does not have a doc string or the doc string is empty, try its base classes until the roo...
clz = cls while not clz.__doc__: clz = clz.__bases__[0] return clz.__doc__
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def launch_subshell(self, shell_cls, cmd, args, *, prompt = None, context = {}): """Launch a subshell. The doc string of the cmdloop() method explains how shell ...
# Save history of the current shell. readline.write_history_file(self.history_fname) prompt = prompt if prompt else shell_cls.__name__ mode = _ShellBase._Mode( shell = self, cmd = cmd, args = args, prompt = prompt, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def batch_string(self, content): """Process a string in batch mode. Arguments: content: A unicode string representing the content to be processed. """
pipe_send, pipe_recv = multiprocessing.Pipe() self._pipe_end = pipe_recv proc = multiprocessing.Process(target = self.cmdloop) for line in content.split('\n'): pipe_send.send(line) pipe_send.close() proc.start() proc.join()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cmdloop(self): """Start the main loop of the interactive shell. The preloop() and postloop() methods are always run before and after the main loop, respectiv...
self.print_debug("Enter subshell '{}'".format(self.prompt)) # Save the completer function, the history buffer, and the # completer_delims. old_completer = readline.get_completer() old_delims = readline.get_completer_delims() new_delims = ''.join(list(set(old_delims) - 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 parse_line(self, line): """Parse a line of input. The input line is tokenized using the same rules as the way bash shell tokenizes inputs. All quoting and es...
toks = shlex.split(line) # Safe to index the 0-th element because this line would have been # parsed by __exec_line__ if toks is an empty list. return ( toks[0], [] if len(toks) == 1 else toks[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 __driver_stub(self, text, state): """Display help messages or invoke the proper completer. The interface of helper methods and completer methods are document...
origline = readline.get_line_buffer() line = origline.lstrip() if line and line[-1] == '?': self.__driver_helper(line) else: toks = shlex.split(line) return self.__driver_completer(toks, text, state)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __driver_completer(self, toks, text, state): """Driver level completer. Arguments: toks: A list of tokens, tokenized from the original input line. text: A st...
if state != 0: return self.__completion_candidates[state] # Update the cache when this method is first called, i.e., state == 0. # If the line is empty or the user is still inputing the first token, # complete with available commands. if not toks or (len(toks) == 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 __complete_cmds(self, text): """Get the list of commands whose names start with a given text."""
return [ name for name in self._cmd_map_visible.keys() if name.startswith(text) ]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __driver_helper(self, line): """Driver level helper method. 1. Display help message for the given input. Internally calls self.__get_help_message() to obtain...
if line.strip() == '?': self.stdout.write('\n') self.stdout.write(self.doc_string()) else: toks = shlex.split(line[:-1]) try: msg = self.__get_help_message(toks) except Exception as e: self.stderr.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 __build_cmd_maps(cls): """Build the mapping from command names to method names. One command name maps to at most one method. Multiple command names can map t...
cmd_map_all = {} cmd_map_visible = {} cmd_map_internal = {} for name in dir(cls): obj = getattr(cls, name) if iscommand(obj): for cmd in getcommands(obj): if cmd in cmd_map_all.keys(): raise PyShellError...
<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_helper_map(cls): """Build a mapping from command names to helper names. One command name maps to at most one helper method. Multiple command names ca...
ret = {} for name in dir(cls): obj = getattr(cls, name) if ishelper(obj): for cmd in obj.__help_targets__: if cmd in ret.keys(): raise PyShellError("The command '{}' already has helper" ...
<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_completer_map(cls): """Build a mapping from command names to completer names. One command name maps to at most one completer method. Multiple command...
ret = {} for name in dir(cls): obj = getattr(cls, name) if iscompleter(obj): for cmd in obj.__complete_targets__: if cmd in ret.keys(): raise PyShellError("The command '{}' already has" ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def review_score(self, reviewer, product): """Find a review score from a given reviewer to a product. Args: reviewer: Reviewer i.e. an instance of :class:`ria.bi...
return self._g.retrieve_review(reviewer, product).score
<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_dict(cls: typing.Type[T], dikt) -> T: """Returns the dict as a model"""
return util.deserialize_model(dikt, cls)
<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_defs(self, cache=True): """ Gets the defitions args: cache: True will read from the file cache, False queries the triplestore """
log.debug(" *** Started") cache = self.__use_cache__(cache) if cache: log.info(" loading json cache") try: with open(self.cache_filepath) as file_obj: self.results = json.loads(file_obj.read()) except FileNotFoundError: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def conv_defs(self): """ Reads through the JSON object and converts them to Dataset """
log.setLevel(self.log_level) start = datetime.datetime.now() log.debug(" Converting to a Dataset: %s Triples", len(self.results)) self.defs = RdfDataset(self.results, def_load=True, bnode_only=True) # self.cfg.__set...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_class_dict(self): """ Reads through the dataset and assigns self.class_dict the key value pairs for the classes in the dataset """
self.class_dict = {} for name, cls_defs in self.defs.items(): def_type = set(cls_defs.get(self.rdf_type, [])) if name.type == 'bnode': continue # a class can be determined by checking to see if it is of an # rdf_type listed in the classes...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tie_properties(self, class_list): """ Runs through the classess and ties the properties to the class args: class_list: a list of class names to run """
log.setLevel(self.log_level) start = datetime.datetime.now() log.info(" Tieing properties to the class") for cls_name in class_list: cls_obj = getattr(MODULE.rdfclass, cls_name) prop_dict = dict(cls_obj.properties) for prop_name, prop_obj in cls_obj.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 elemgetter(path: str) -> t.Callable[[Element], Element]: """shortcut making an XML element getter"""
return compose( partial(_raise_if_none, exc=LookupError(path)), methodcaller('find', 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 textgetter(path: str, *, default: T=NO_DEFAULT, strip: bool=False) -> t.Callable[[Element], t.Union[str, T]]: """shortcut for making an XML element text gette...
find = compose( str.strip if strip else identity, partial(_raise_if_none, exc=LookupError(path)), methodcaller('findtext', path) ) return (find if default is NO_DEFAULT else lookup_defaults(find, default))
<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_alt_url(html_chunk): """ Parse URL from alternative location if not found where it should be. Args: html_chunk (obj): HTMLElement containing slice of...
url_list = html_chunk.find("a", fn=has_param("href")) url_list = map(lambda x: x.params["href"], url_list) url_list = filter(lambda x: not x.startswith("autori/"), url_list) if not url_list: return None return normalize_url(BASE_URL, url_list[0])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parse_from_table(html_chunk, what): """ Go thru table data in `html_chunk` and try to locate content of the neighbor cell of the cell containing `what`. Ret...
ean_tag = html_chunk.find("tr", fn=must_contain("th", what, "td")) if not ean_tag: return None return get_first_content(ean_tag[0].find("td"))
<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_publications(): """ Get list of publication offered by cpress.cz. Returns: list: List of :class:`.Publication` objects. """
data = DOWNER.download(URL) dom = dhtmlparser.parseString( handle_encodnig(data) ) book_list = dom.find("div", {"class": "polozka"}) books = [] for book in book_list: books.append( _process_book(book) ) return books
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resolve( self, configurable=None, scope=None, safe=None, besteffort=None ): """Resolve all parameters. :param Configurable configurable: configurable to use ...
if scope is None: scope = self.scope if safe is None: safe = self.safe if besteffort is None: besteffort = self.besteffort for category in self.values(): for param in category.values(): param.resolve( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def param(self, pname, cname=None, history=0): """Get parameter from a category and history. :param str pname: parameter name. :param str cname: category name. D...
result = None category = None categories = [] # list of categories containing input parameter name for cat in self.values(): if pname in cat: categories.append(cat) if cname == cat.name: break if cname is 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 apache_md5crypt(password, salt, magic='$apr1$'): """ Calculates the Apache-style MD5 hash of a password """
password = password.encode('utf-8') salt = salt.encode('utf-8') magic = magic.encode('utf-8') m = md5() m.update(password + magic + salt) mixin = md5(password + salt + password).digest() for i in range(0, len(password)): m.update(mixin[i % 16]) i = len(password) while 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 get_juttle_data_url(deployment_name, token_manager=None, app_url=defaults.APP_URL): """ return the juttle data url """
return get_data_url(deployment_name, endpoint_type='juttle', app_url=app_url, token_manager=token_manager)
<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_import_data_url(deployment_name, token_manager=None, app_url=defaults.APP_URL): """ return the import data url """
return get_data_url(deployment_name, endpoint_type='http-import', app_url=app_url, token_manager=token_manager)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __wss_connect(data_url, token_manager, job_id=None): """ Establish the websocket connection to the data engine. When job_id is provided we're basically estab...
url = '%s/api/v1/juttle/channel' % data_url.replace('https://', 'wss://') token_obj = { "accessToken": token_manager.get_access_token() } if job_id != None: token_obj['job_id'] = job_id if is_debug_enabled(): debug("connecting to %s", url) websocket = create_connecti...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connect_job(job_id, deployment_name, token_manager=None, app_url=defaults.APP_URL, persist=False, websocket=None, data_url=None): """ connect to a running Ju...
if data_url == None: data_url = get_data_url_for_job(job_id, deployment_name, token_manager=token_manager, app_url=app_url) if websocket == None: websocket = __wss_connect(d...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_jobs(deployment_name, token_manager=None, app_url=defaults.APP_URL): """ return list of currently running jobs """
headers = token_manager.get_access_token_headers() data_urls = get_data_urls(deployment_name, app_url=app_url, token_manager=token_manager) jobs = [] for data_url in data_urls: url = '%s/api/v1/jobs' % data_url response = req...
<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_job_details(job_id, deployment_name, token_manager=None, app_url=defaults.APP_URL): """ return job details for a specific job id """
jobs = get_jobs(deployment_name, token_manager=token_manager, app_url=app_url) for job in jobs: if job['id'] == job_id: return job raise JutException('Unable to find job with id "%s"' % job_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 delete_job(job_id, deployment_name, token_manager=None, app_url=defaults.APP_URL): """ delete a job with a specific job id """
headers = token_manager.get_access_token_headers() data_url = get_data_url_for_job(job_id, deployment_name, token_manager=token_manager, app_url=app_url) url = '%s/api/v1/jobs/%s' % (data_url, job_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 lines(input): """Remove comments and empty lines"""
for raw_line in input: line = raw_line.strip() if line and not line.startswith('#'): yield strip_comments(line)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def exec_command(self, cmd, tmp_path, sudo_user, sudoable=False, executable='/bin/sh'): ''' run a command on the local host ''' if not self.runner.sudo or not sudoable: if executable: local_cmd = [executable, '-c', cmd] else: local_cmd = cmd ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def put_file(self, in_path, out_path): ''' transfer a file from local to local ''' vvv("PUT %s TO %s" % (in_path, out_path), host=self.host) if not os.path.exists(in_path): raise errors.AnsibleFileNotFound("file or module does not exist: %s" % in_path) try: shuti...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getPythonVarName(name): """Get the python variable name """
return SUB_REGEX.sub('', name.replace('+', '_').replace('-', '_').replace('.', '_').replace(' ', '').replace('/', '_')).upper()
<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, text): """Parse the text content """
root = ET.fromstring(text) for elm in root.findall('{http://www.iana.org/assignments}registry'): for record in elm.findall('{http://www.iana.org/assignments}record'): for fileElm in record.findall('{http://www.iana.org/assignments}file'): if fileElm.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 parsefile(self, filename): """Parse from the file """
with open(filename, 'rb') as fd: return self.parse(fd.read())
<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(self): """ Check if we have an active login session set @rtype: bool """
self.log.debug('Testing for a valid login session') # If our cookie jar is empty, we obviously don't have a valid login session if not len(self.cookiejar): return False # Test our login session and make sure it's still active return requests.get(self.TEST_URL, cooki...
<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(self, username, password, remember=True): """ Process a login request @type username: str @type password: str @param remember: Save the login session...
self.log.debug('Processing login request') self.browser.open(self.LOGIN_URL) self.log.info('Login page loaded: %s', self.browser.title()) self.browser.select_form(nr=0) # Set the fields self.log.debug('Username: %s', username) self.log.debug('Password: %s', (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 get_libmarquise_header(): """Read the libmarquise header to extract definitions."""
# Header file is packaged in the same place as the rest of the # module. header_path = os.path.join(os.path.dirname(__file__), "marquise.h") with open(header_path) as header: libmarquise_header_lines = header.readlines() libmarquise_header_lines = [ line for line in libmarquise_header_line...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def head(self, uuid): """ Get one thread."""
url = "%(base)s/%(uuid)s" % { 'base': self.local_base_url, 'uuid': uuid } return self.core.head(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 default(self, obj): # pylint: disable=method-hidden """Use the default behavior unless the object to be encoded has a `strftime` attribute."""
if hasattr(obj, 'strftime'): return obj.strftime("%Y-%m-%dT%H:%M:%SZ") elif hasattr(obj, 'get_public_dict'): return obj.get_public_dict() else: return json.JSONEncoder.default(self, obj)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def taskotron_task(config, message, task=None): """ Particular taskotron task With this rule, you can limit messages to only those of particular `taskotron <http...
# We only operate on taskotron messages, first off. if not taskotron_result_new(config, message): return False if not task: return False tasks = [item.strip().lower() for item in task.split(',')] return message['msg']['task'].get('name').lower() in tasks
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def taskotron_changed_outcome(config, message): """ Taskotron task outcome changed With this rule, you can limit messages to only those task results with changed...
# We only operate on taskotron messages, first off. if not taskotron_result_new(config, message): return False outcome = message['msg']['result'].get('outcome') prev_outcome = message['msg']['result'].get('prev_outcome') return prev_outcome is not None and outcome != prev_outcome
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def taskotron_task_outcome(config, message, outcome=None): """ Particular taskotron task outcome With this rule, you can limit messages to only those of particul...
# We only operate on taskotron messages, first off. if not taskotron_result_new(config, message): return False if not outcome: return False outcomes = [item.strip().lower() for item in outcome.split(',')] return message['msg']['result'].get('outcome').lower() in outcomes
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def taskotron_release_critical_task(config, message): """ Release-critical taskotron tasks With this rule, you can limit messages to only those of release-critic...
# We only operate on taskotron messages, first off. if not taskotron_result_new(config, message): return False task = message['msg']['task'].get('name') return task in ['dist.depcheck', 'dist.upgradepath']
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def execute(action, io_loop=None): """Execute the given action and return a Future with the result. The ``forwards`` and/or ``backwards`` methods for the action ...
if not io_loop: io_loop = IOLoop.current() output = Future() def call(): try: result = _execute(_TornadoAction(action, io_loop)) except Exception: output.set_exc_info(sys.exc_info()) else: output.set_result(result) io_loop.add_call...
<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_triple(self, sub, pred=None, obj=None, **kwargs): """ Adds a triple to the dataset args: sub: The subject of the triple or dictionary contaning a triple ...
self.__set_map__(**kwargs) strip_orphans = kwargs.get("strip_orphans", False) obj_method = kwargs.get("obj_method") if isinstance(sub, DictClass) or isinstance(sub, dict): pred = sub[self.pmap] obj = sub[self.omap] sub = sub[self.smap] pred =...
<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_data(self, data, **kwargs): """ Bulk adds rdf data to the class args: data: the data to be loaded kwargs: strip_orphans: True or False - remove triples ...
self.__set_map__(**kwargs) start = datetime.datetime.now() log.debug("Dataload stated") if isinstance(data, list): data = self._convert_results(data, **kwargs) class_types = self.__group_data__(data, **kwargs) # generate classes and add attributes to the dat...
<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_rmap_item(self, subj, pred, obj): """ adds a triple to the inverted dataset index """
def add_item(self, subj, pred, obj): try: self.rmap[obj][pred].append(subj) except KeyError: try: self.rmap[obj][pred] = [subj] except KeyError: self.rmap[obj] = {pred: [subj]} if isinstance...
<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_classes(self, class_types, non_defined, **kwargs): """ creates the class for each class in the data set args: class_types: list of class_types in t...
# kwargs['dataset'] = self for class_type in class_types: self[class_type[self.smap]] = self._get_rdfclass(class_type, **kwargs)\ (class_type, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_rdfclass(self, class_type, **kwargs): """ returns the instanticated class from the class list args: class_type: dictionary with rdf_types """
def select_class(class_name): """ finds the class in the rdfclass Module""" try: return getattr(MODULE.rdfclass, class_name.pyuri) except AttributeError: return RdfClassBase if kwargs.get("def_load"): return RdfClassBase ...
<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_timedelta(cls, datetime_obj, duration): """Create a new TimeInterval object from a start point and a duration. If duration is positive, datetime_obj is ...
if duration.total_seconds() > 0: return TimeInterval(datetime_obj, datetime_obj + duration) else: return TimeInterval(datetime_obj + duration, datetime_obj)
<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_startstop(sheet, startcell=None, stopcell=None): """ Return two StartStop objects, based on the sheet and startcell and stopcell. sheet: xlrd.sheet.Shee...
start = StartStop(0, 0) # row, col stop = StartStop(sheet.nrows, sheet.ncols) if startcell: m = re.match(XLNOT_RX, startcell) start.row = int(m.group(2)) - 1 start.col = letter2num(m.group(1), zbase=True) if stopcell: m = re.match(XLNOT_RX, stopcell) stop....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepread(sheet, header=True, startcell=None, stopcell=None): """Return four StartStop objects, defining the outer bounds of header row and data range, respec...
datstart, datstop = _get_startstop(sheet, startcell, stopcell) headstart, headstop = StartStop(0, 0), StartStop(0, 0) # Holders def typicalprep(): headstart.row, headstart.col = datstart.row, datstart.col headstop.row, headstop.col = datstart.row + 1, datstop.col # Tick the data 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 sheetheader(sheet, startstops, usecols=None): """Return the channel names in a list suitable as an argument to ChannelPack's `set_channel_names` method. Retu...
headstart, headstop, dstart, dstop = startstops if headstart is None: return None assert headstop.row - headstart.row == 1, ('Field names must be in ' 'same row so far. Or ' 'this is a bug') header = ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _sanitize_usecols(usecols): """Make a tuple of sorted integers and return it. Return None if usecols is None"""
if usecols is None: return None try: pats = usecols.split(',') pats = [p.strip() for p in pats if p] except AttributeError: usecols = [int(c) for c in usecols] # Make error if mix. usecols.sort() return tuple(usecols) # Assume sane sequence of integers. ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def letter2num(letters, zbase=False): """A = 1, C = 3 and so on. Convert spreadsheet style column enumeration to a number. Answers: A = 1, Z = 26, AA = 27, AZ = ...
letters = letters.upper() res = 0 weight = len(letters) - 1 assert weight >= 0, letters for i, c in enumerate(letters): assert 65 <= ord(c) <= 90, c # A-Z res += (ord(c) - 64) * 26**(weight - i) if not zbase: return res return res - 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 fromxldate(xldate, datemode=1): """Return a python datetime object xldate: float The xl number. datemode: int 0: 1900-based, 1: 1904-based. See xlrd document...
t = xlrd.xldate_as_tuple(xldate, datemode) return datetime.datetime(*t)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def language(fname, is_ext=False): """Return an instance of the language class that fname is suited for. Searches through the module langs for the class that mat...
global _langmapping # Normalize the fname so that it looks like an extension. if is_ext: fname = '.' + fname _, ext = os.path.splitext(fname) return _langmapping[ext]()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def certify_text( value, min_length=None, max_length=None, nonprintable=True, required=True, ): """ Certifier for human readable string values. :param unicode va...
certify_params( (_certify_int_param, 'max_length', max_length, dict(negative=False, required=False)), (_certify_int_param, 'min_length', min_length, dict(negative=False, required=False)), (certify_bool, 'nonprintable', nonprintable), ) if certify_required( value=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 certify_int(value, min_value=None, max_value=None, required=True): """ Certifier for integer values. :param six.integer_types value: The number to be certifi...
certify_params( (_certify_int_param, 'max_length', max_value, dict(negative=True, required=False)), (_certify_int_param, 'min_length', min_value, dict(negative=True, required=False)), ) if certify_required( value=value, required=required, ): return if not is...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def certify_bool(value, required=True): """ Certifier for boolean values. :param value: The value to be certified. :param bool required: Whether the value can be...
if certify_required( value=value, required=required, ): return if not isinstance(value, bool): raise CertifierTypeError( message="expected bool, but value is of type {cls!r}".format( cls=value.__class__.__name__), value=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 certify_bytes(value, min_length=None, max_length=None, required=True): """ Certifier for bytestring values. Should not be used for certifying human readable ...
certify_params( (_certify_int_param, 'min_value', min_length, dict(negative=False, required=False)), (_certify_int_param, 'max_value', max_length, dict(negative=False, required=False)), ) if certify_required( value=value, required=required, ): return if not...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def certify_enum(value, kind=None, required=True): """ Certifier for enum. :param value: The value to be certified. :param kind: The enum type that value should ...
if certify_required( value=value, required=required, ): return if not isinstance(value, kind): raise CertifierTypeError( message="expected {expected!r}, but value is of type {actual!r}".format( expected=kind.__name__, actual=value.__class__.__nam...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def certify_enum_value(value, kind=None, required=True): """ Certifier for enum values. :param value: The value to be certified. :param kind: The enum type that ...
if certify_required( value=value, required=required, ): return try: kind(value) except: # noqa raise CertifierValueError( message="value {value!r} is not a valid member of {enum!r}".format( value=value, enum=kind.__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 certify_object(value, kind=None, required=True): """ Certifier for class object. :param object value: The object to certify. :param object kind: The type of ...
if certify_required( value=value, required=required, ): return if not isinstance(value, kind): try: name = value.__class__.__name__ except: # noqa # pragma: no cover name = type(value).__name__ try: expected = kind.__cla...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def certify_time(value, required=True): """ Certifier for datetime.time values. :param value: The value to be certified. :param bool required: Whether the value ...
if certify_required( value=value, required=required, ): return if not isinstance(value, time): raise CertifierTypeError( message="expected timestamp (time), but value is of type {cls!r}".format( cls=value.__class__.__name__), value=va...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def AsDict(self, dt=True): """ A dict representation of this User instance. The return value uses the same key names as the JSON representation. Args: dt (bool):...
data = {} if self.name: data['name'] = self.name data['mlkshk_url'] = self.mlkshk_url if self.profile_image_url: data['profile_image_url'] = self.profile_image_url if self.id: data['id'] = self.id if self.about: data['a...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def AsJsonString(self): """A JSON string representation of this User instance. Returns: A JSON string representation of this User instance """
return json.dumps(self.AsDict(dt=False), sort_keys=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 NewFromJSON(data): """ Create a new User instance from a JSON dict. Args: data (dict): JSON dictionary representing a user. Returns: A User instance. """
if data.get('shakes', None): shakes = [Shake.NewFromJSON(shk) for shk in data.get('shakes')] else: shakes = None return User( id=data.get('id', None), name=data.get('name', None), profile_image_url=data.get('profile_image_url', 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 AsDict(self, dt=True): """ A dict representation of this Comment instance. The return value uses the same key names as the JSON representation. Args: dt (boo...
data = {} if self.body: data['body'] = self.body if self.posted_at: data['posted_at'] = self.posted_at if self.user: data['user'] = self.user.AsDict() return 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 NewFromJSON(data): """ Create a new Comment instance from a JSON dict. Args: data (dict): JSON dictionary representing a Comment. Returns: A Comment instanc...
return Comment( body=data.get('body', None), posted_at=data.get('posted_at', None), user=User.NewFromJSON(data.get('user', 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 NewFromJSON(data): """ Create a new Shake instance from a JSON dict. Args: data (dict): JSON dictionary representing a Shake. Returns: A Shake instance. """
s = Shake( id=data.get('id', None), name=data.get('name', None), url=data.get('url', None), thumbnail_url=data.get('thumbnail_url', None), description=data.get('description', None), type=data.get('type', None), created_at=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 NewFromJSON(data): """ Create a new SharedFile instance from a JSON dict. Args: data (dict): JSON dictionary representing a SharedFile. Returns: A SharedFil...
return SharedFile( sharekey=data.get('sharekey', None), name=data.get('name', None), user=User.NewFromJSON(data.get('user', None)), title=data.get('title', None), description=data.get('description', None), posted_at=data.get('posted_at', 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 _start_tracer(self, origin): """ Start a new Tracer object, and store it in self.tracers. """
tracer = self._tracer_class(log=self.log) tracer.data = self.data fn = tracer.start(origin) self.tracers.append(tracer) return fn
<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(self): """ Start collecting trace information. """
origin = inspect.stack()[1][0] self.reset() # Install the tracer on this thread. self._start_tracer(origin)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gauge(self, name, producer): """Creates or gets an existing gauge. :param name: The name :return: The created or existing gauge for the given name """
return self._get_or_add_stat(name, functools.partial(Gauge, producer))
<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_stats(self): """Retrieves the current values of the metrics associated with this registry, formatted as a dict. The metrics form a hierarchy, their names...
def _get_value(stats): try: return Dict((k, _get_value(v)) for k, v in stats.items()) except AttributeError: return Dict(stats.get_values()) return _get_value(self.stats)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _populate_ips_versions(self): """ Populate IPS version data for mapping @return: """
# Get a map of version ID's from our most recent IPS version ips = IpsManager(self.ctx) ips = ips.dev_version or ips.latest with ZipFile(ips.filepath) as zip: namelist = zip.namelist() ips_versions_path = os.path.join(namelist[0], 'applications/core/data/version...
<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(data_path): """ Extract data from provided file and return it as a string. """
with open(data_path, "r") as data_file: raw_data = data_file.read() data_file.close() return raw_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 parse(self, data): """ Split and iterate through the datafile to extract genres, tags and points. """
categories = data.split("\n\n") reference = {} reference_points = {} genre_index = [] tag_index = [] for category in categories: entries = category.strip().split("\n") entry_category, entry_points = self._parse_entry(entries[0].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 _parse_entry(entry, limit=10): """ Finds both label and if provided, the points for ranking. """
entry = entry.split(",") label = entry[0] points = limit if len(entry) > 1: proc = float(entry[1].strip()) points = limit * proc return label, int(points)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def has_site_permission(user): """ Checks if a staff user has staff-level access for the current site. The actual permission lookup occurs in ``SitePermissionMid...
mw = "yacms.core.middleware.SitePermissionMiddleware" if mw not in get_middleware_setting(): from warnings import warn warn(mw + " missing from settings.MIDDLEWARE - per site" "permissions not applied") return user.is_staff and user.is_active return getattr(user, "has_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 host_theme_path(): """ Returns the directory of the theme associated with the given host. """
# Set domain to None, which we'll then query for in the first # iteration of HOST_THEMES. We use the current site_id rather # than a request object here, as it may differ for admin users. domain = None for (host, theme) in settings.HOST_THEMES: if domain is None: domain = Site...
<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(url, **args): """Loads an object from a data URI."""
info, data = url.path.split(',') info = data_re.search(info).groupdict() mediatype = info.setdefault('mediatype', 'text/plain;charset=US-ASCII') if ';' in mediatype: mimetype, params = mediatype.split(';', 1) params = [p.split('=') for p in params.split(';')] params = dict((k.st...
<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(url, object_, **args): """Writes an object to a data URI."""
default_content_type = ('text/plain', {'charset': 'US-ASCII'}) content_encoding = args.get('content_encoding', 'base64') content_type, params = args.get('content_type', default_content_type) data = content_types.get(content_type).format(object_, **params) args['data'].write('data:{}'.format(content...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def deprecated(new_fct_name, logger=None): """ Decorator to notify that a fct is deprecated """
if logger is None: logger = logging.getLogger("kodex") nfct_name = new_fct_name def aux_deprecated(func): """This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emmitted when the function is used.""" def newFunc(*a...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def blockgen(bytes, block_size=16): ''' a block generator for pprp ''' for i in range(0, len(bytes), block_size): block = bytes[i:i + block_size] block_len = len(block) if block_len > 0: yield block if block_len < block_size: break
<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_basic_logger(level=logging.WARN, scope='reliure'): """ return a basic logger that print on stdout msg from reliure lib """
logger = logging.getLogger(scope) logger.setLevel(level) # create console handler with a higher log level ch = logging.StreamHandler() ch.setLevel(level) # create formatter and add it to the handlers formatter = ColorFormatter('%(asctime)s:%(levelname)s:%(name)s:%(message)s') ch.setForm...
<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, *args, **kwargs): """ Save the created_by and last_modified_by fields based on the current admin user. """
if not self.instance.id: self.instance.created_by = self.user self.instance.last_modified_by = self.user return super(ChangeableContentForm, self).save(*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_urls(self): """ Add our preview view to our urls. """
urls = super(PageAdmin, self).get_urls() my_urls = patterns('', (r'^add/preview$', self.admin_site.admin_view(PagePreviewView.as_view())), (r'^(?P<id>\d+)/preview$', self.admin_site.admin_view(PagePreviewView.as_view())), (r'^(?P<id>\d+)/history/(\d+)/preview$', 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 get_template_names(self): """ Return the page's specified template name, or a fallback if one hasn't been chosen. """
posted_name = self.request.POST.get('template_name') if posted_name: return [posted_name,] else: return super(PagePreviewView, self).get_template_names()
<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(self, request, *args, **kwargs): """ Accepts POST requests, and substitute the data in for the page's attributes. """
self.object = self.get_object() self.object.content = request.POST['content'] self.object.title = request.POST['title'] self.object = self._mark_html_fields_as_safe(self.object) context = self.get_context_data(object=self.object) return self.render_to_response(context, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def redirect_stdout(self): """Redirect stdout to file so that it can be tailed and aggregated with the other logs."""
self.hijacked_stdout = sys.stdout self.hijacked_stderr = sys.stderr # 0 must be set as the buffer, otherwise lines won't get logged in time. sys.stdout = open(self.hitch_dir.driverout(), "ab", 0) sys.stderr = open(self.hitch_dir.drivererr(), "ab", 0)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unredirect_stdout(self): """Redirect stdout and stderr back to screen."""
if hasattr(self, 'hijacked_stdout') and hasattr(self, 'hijacked_stderr'): sys.stdout = self.hijacked_stdout sys.stderr = self.hijacked_stderr
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def time_travel(self, datetime=None, timedelta=None, seconds=0, minutes=0, hours=0, days=0): """Mock moving forward or backward in time by shifting the system cl...
if datetime is not None: self.timedelta = datetime - python_datetime.now() if timedelta is not None: self.timedelta = self.timedelta + timedelta self.timedelta = self.timedelta + python_timedelta(seconds=seconds) self.timedelta = self.timedelta + python_timedelta...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wait_for_ipykernel(self, service_name, timeout=10): """Wait for an IPython kernel-nnnn.json filename message to appear in log."""
kernel_line = self._services[service_name].logs.tail.until( lambda line: "--existing" in line[1], timeout=10, lines_back=5 ) return kernel_line.replace("--existing", "").strip()