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 utc_offset_by_timezone(timezone_name): """Returns the UTC offset of the given timezone in hours. Arguments --------- timezone_name: str A string with a name ...
return int(pytz.timezone(timezone_name).utcoffset( utc_time()).total_seconds()/SECONDS_IN_HOUR)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def localize_datetime(datetime_obj, timezone_name): """Localizes the given UTC-aligned datetime by the given timezone. Arguments --------- datetime_obj : datetim...
return datetime_obj.replace(tzinfo=pytz.utc).astimezone( pytz.timezone(timezone_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 _load_build(self): """See `pickle.py` in Python's source code."""
# if the ctor. function (penultimate on the stack) is the `Ref` class... if isinstance(self.stack[-2], Ref): # Ref.__setstate__ will know it's a remote ref if the state is a tuple self.stack[-1] = (self.stack[-1], self.node) self.load_build() # continue with the 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 path_to_zip(path): """ Compress `path` to the ZIP. Args: path (str): Path to the directory. Returns: str: Path to the zipped file (in /tmp). """
if not os.path.exists(path): raise IOError("%s doesn't exists!" % path) with tempfile.NamedTemporaryFile(delete=False) as ntf: zip_fn = ntf.name with zipfile.ZipFile(zip_fn, mode="w") as zip_file: for root, dirs, files in os.walk(path): for fn in 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 read_as_base64(fn): """ Convert given `fn` to base64 and return it. This method does the process in not-so-much memory consuming way. Args: fn (str): Path t...
with open(fn) as unpacked_file: with tempfile.TemporaryFile() as b64_file: base64.encode(unpacked_file, b64_file) b64_file.flush() b64_file.seek(0) return b64_file.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 _pad_input(incoming): """Avoid IndexError and KeyError by ignoring un-related fields. Example: '{0}{autored}' becomes '{{0}}{autored}'. Positional arguments:...
incoming_expanded = incoming.replace('{', '{{').replace('}', '}}') for key in _BASE_CODES: before, after = '{{%s}}' % key, '{%s}' % key if before in incoming_expanded: incoming_expanded = incoming_expanded.replace(before, after) return incoming_expanded
<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_input(incoming): """Performs the actual conversion of tags to ANSI escaped codes. Provides a version of the input without any colors for len() and oth...
codes = dict((k, v) for k, v in _AutoCodes().items() if '{%s}' % k in incoming) color_codes = dict((k, '' if _AutoCodes.DISABLE_COLORS else '\033[{0}m'.format(v)) for k, v in codes.items()) incoming_padded = _pad_input(incoming) output_colors = incoming_padded.format(**color_codes) # Simplify: '{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 list_tags(): """Lists the available tags. Returns: Tuple of tuples. Child tuples are four items: ('opening tag', 'closing tag', main ansi value, closing ansi...
codes = _AutoCodes() grouped = set([(k, '/{0}'.format(k), codes[k], codes['/{0}'.format(k)]) for k in codes if not k.startswith('/')]) # Add half-tags like /all. found = [c for r in grouped for c in r[:2]] missing = set([('', r[0], None, r[1]) if r[0].startswith('/') else (r[0], '', r[1], 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 _set_color(self, color_code): """Changes the foreground and background colors for subsequently printed characters. Since setting a color requires including b...
# Get current color code. current_fg, current_bg = self._get_colors() # Handle special negative codes. Also determine the final color code. if color_code == -39: final_color_code = self.default_fg | current_bg # Reset the foreground only. elif color_code == -49: ...
<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_mimetype(self): """ Use the ending of the template name to infer response's Content-Type header. """
template_name = self.get_template_names()[0] for extension, mimetype in turrentine_settings.TURRENTINE_MIMETYPE_EXTENSIONS: if template_name.endswith(extension): return mimetype return 'text/html'
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(self, request, *args, **kwargs): """ Check user authentication if the page requires a login. We could do this by overriding dispatch() instead, but we as...
try: page = self.object = self.get_object() except Http404: # If APPEND_SLASH is set and our url has no trailing slash, # look for a CMS page at the alternate url: if settings.APPEND_SLASH and not self.kwargs.get('path', '/').endswith('/'): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _try_url_with_appended_slash(self): """ Try our URL with an appended slash. If a CMS page is found at that URL, redirect to it. If no page is found at that U...
new_url_to_try = self.kwargs.get('path', '') + '/' if not new_url_to_try.startswith('/'): new_url_to_try = '/' + new_url_to_try if CMSPage.objects.published().filter(url=new_url_to_try).exists(): return HttpResponsePermanentRedirect(new_url_to_try) else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_rule_name(self, name): """ Validate rule name. Arguments: name (string): Rule name. Returns: bool: ``True`` if rule name is valid. """
if not name: raise SerializerError("Rule name is empty".format(name)) if name[0] not in RULE_ALLOWED_START: msg = "Rule name '{}' must starts with a letter" raise SerializerError(msg.format(name)) for item in name: if item not in RULE_ALLOWED_CH...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_variable_name(self, name): """ Validate variable name. Arguments: name (string): Property name. Returns: bool: ``True`` if variable name is valid. ...
if not name: raise SerializerError("Variable name is empty".format(name)) if name[0] not in PROPERTY_ALLOWED_START: msg = "Variable name '{}' must starts with a letter" raise SerializerError(msg.format(name)) for item in name: if item not in PRO...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def value_splitter(self, reference, prop, value, mode): """ Split a string into a list items. Default behavior is to split on white spaces. Arguments: reference ...
items = [] if mode == 'json-list': try: items = json.loads(value) except json.JSONDecodeError as e: print(value) msg = ("Reference '{ref}' raised JSON decoder error when " "splitting values from '{prop}': {e...
<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_to_json(self, name, datas): """ Serialize given datas to any object from assumed JSON string. Arguments: name (string): Name only used inside poss...
data_object = datas.get('object', None) if data_object is None: msg = ("JSON reference '{}' lacks of required 'object' variable") raise SerializerError(msg.format(name)) try: content = json.loads(data_object, object_pairs_hook=OrderedDict) except js...
<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_to_list(self, name, datas): """ Serialize given datas to a list structure. List structure is very simple and only require a variable ``--items`` wh...
items = datas.get('items', None) splitter = datas.get('splitter', self._DEFAULT_SPLITTER) if items is None: msg = ("List reference '{}' lacks of required 'items' variable " "or is empty") raise SerializerError(msg.format(name)) else: ...
<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_to_string(self, name, datas): """ Serialize given datas to a string. Simply return the value from required variable``value``. Arguments: name (stri...
value = datas.get('value', None) if value is None: msg = ("String reference '{}' lacks of required 'value' variable " "or is empty") raise SerializerError(msg.format(name)) return value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_meta_references(self, datas): """ Get manifest enabled references declaration This required declaration is readed from ``styleguide-metas-references`` ru...
rule = datas.get(RULE_META_REFERENCES, {}) if not rule: msg = "Manifest lacks of '.{}' or is empty" raise SerializerError(msg.format(RULE_META_REFERENCES)) else: if rule.get('names', None): names = rule.get('names').split(" ") eli...
<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_reference(self, datas, name): """ Get serialized reference datas Because every reference is turned to a dict (that stands on ``keys`` variable that is a ...
rule_name = '-'.join((RULE_REFERENCE, name)) structure_mode = 'nested' if rule_name not in datas: msg = "Unable to find enabled reference '{}'" raise SerializerError(msg.format(name)) properties = datas.get(rule_name) # Search for "structure" variable ...
<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_available_references(self, datas): """ Get available manifest reference names. Every rules starting with prefix from ``nomenclature.RULE_REFERENCE`` are ...
names = [] for k, v in datas.items(): if k.startswith(RULE_REFERENCE): names.append(k[len(RULE_REFERENCE)+1:]) return 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 get_enabled_references(self, datas, meta_references): """ Get enabled manifest references declarations. Enabled references are defined through meta reference...
references = OrderedDict() for section in meta_references: references[section] = self.get_reference(datas, section) return references
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def serialize(self, datas): """ Serialize datas to manifest structure with metas and references. Only references are returned, metas are assigned to attribute ``...
self._metas = OrderedDict({ 'references': self.get_meta_references(datas), }) return self.get_enabled_references(datas, self._metas['references'])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def contribute_to_class(self, cls, name): """ Add each of the names and fields in the ``fields`` attribute to the model the relationship field is applied to, and...
for field in cls._meta.many_to_many: if isinstance(field, self.__class__): e = "Multiple %s fields are not supported (%s.%s, %s.%s)" % ( self.__class__.__name__, cls.__name__, cls.__name__, name, field.name) raise ImproperlyCon...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _related_items_changed(self, **kwargs): """ Ensure that the given related item is actually for the model this field applies to, and pass the instance to the ...
for_model = kwargs["instance"].content_type.model_class() if for_model and issubclass(for_model, self.model): instance_id = kwargs["instance"].object_pk try: instance = for_model.objects.get(id=instance_id) except self.model.DoesNotExist: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def related_items_changed(self, instance, related_manager): """ Stores the number of comments. A custom ``count_filter`` queryset gets checked for, allowing mana...
try: count = related_manager.count_queryset() except AttributeError: count = related_manager.count() count_field_name = list(self.fields.keys())[0] % \ self.related_field_name setattr(instance, count_field_name, count) instance....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def formfield(self, **kwargs): """ Provide the custom form widget for the admin, since there isn't a form field mapped to ``GenericRelation`` model fields. """
from yacms.generic.forms import KeywordsWidget kwargs["widget"] = KeywordsWidget return super(KeywordsField, self).formfield(**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 save_form_data(self, instance, data): """ The ``KeywordsWidget`` field will return data as a string of comma separated IDs for the ``Keyword`` model - conver...
from yacms.generic.models import Keyword related_manager = getattr(instance, self.name) # Get a list of Keyword IDs being removed. old_ids = [str(a.keyword_id) for a in related_manager.all()] new_ids = data.split(",") removed_ids = set(old_ids) - set(new_ids) # 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 contribute_to_class(self, cls, name): """ Swap out any reference to ``KeywordsField`` with the ``KEYWORDS_FIELD_string`` field in ``search_fields``. """
super(KeywordsField, self).contribute_to_class(cls, name) string_field_name = list(self.fields.keys())[0] % \ self.related_field_name if hasattr(cls, "search_fields") and name in cls.search_fields: try: weight = cls.search_fields[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 related_items_changed(self, instance, related_manager): """ Stores the keywords as a single string for searching. """
assigned = related_manager.select_related("keyword") keywords = " ".join([str(a.keyword) for a in assigned]) string_field_name = list(self.fields.keys())[0] % \ self.related_field_name if getattr(instance, string_field_name) != keywords: setattr(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 related_items_changed(self, instance, related_manager): """ Calculates and saves the average rating. """
ratings = [r.value for r in related_manager.all()] count = len(ratings) _sum = sum(ratings) average = _sum / count if count > 0 else 0 setattr(instance, "%s_count" % self.related_field_name, count) setattr(instance, "%s_sum" % self.related_field_name, _sum) setat...
<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_new_packages(apt_output, include_automatic=False): """ Given the output from an apt or aptitude command, determine which packages are newly-installed. ...
pat = r'^The following NEW packages will be installed:[\r\n]+(.*?)[\r\n]\w' matcher = re.search(pat, apt_output, re.DOTALL | re.MULTILINE) if not matcher: return [] new_pkg_text = matcher.group(1) raw_names = re.findall(r'[\w{}\.+-]+', new_pkg_text) all_packages = list(map(PackageName.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 file_iterator(filehandle, verbose=False): """Iterate over a file and yield stripped lines. Optionally show progress."""
if type(filehandle).__name__ == "str": filehandle = open(filehandle) if verbose: try: pind = ProgressIndicator(totalToDo=os.path.getsize(filehandle.name), messagePrefix="completed", messageSuffix="of processing " + ...
<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_entry(parts, existing_list_d, key_value, key_field_num, key_is_field_number, header=None, output_type=OutputType.error_on_dups, ignore_missing_keys=Fal...
if key_value.strip() == "": if ignore_missing_keys: return raise MissingKeyError("missing key value") if key_value in existing_list_d: if output_type is OutputType.error_on_dups: raise DuplicateKeyError(key_value + " appears multiple times as key") elif (output_type is OutputType.all_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 __output_unpaired_vals(d_vals, used_ff_keys, f_f_header, sf_d, s_f_header, missing_val, out_handler, outfh, delim="\t"): """ Use an output handler to output ...
if missing_val is None: raise MissingValueError("Need missing value to output " + " unpaired lines") for k in d_vals: if k not in used_ff_keys: f_f_flds = d_vals[k] if s_f_header is not None: s_f_flds = [dict(zip(s_f_header, [missing_val] * len(s_f_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 get_key_field(ui, ui_option_name, default_val=0, default_is_number=True): """ parse an option from a UI object as the name of a key field. If the named optio...
key = default_val key_is_field_number = default_is_number if ui.optionIsSet(ui_option_name): key = ui.getValue(ui_option_name) try: key = int(key) - 1 key_is_field_number = True except ValueError: key_is_field_number = False return key, key_is_field_number
<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_unpaired_line(d_vals, f_f_header, missing_val=None): """ used when a value in d_vals doesn't match anything in the other file. :return: a dictionary...
if missing_val is None: raise MissingValueError("Need missing value to output " + " unpaired lines") if f_f_header is not None: f_f_flds = [dict(zip(f_f_header, [missing_val] * len(f_f_header)))] else: assert(len(d_vals) > 0) f_f_num_cols = len(d_vals[d_vals.keys()[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 build_mock_open_side_effect(string_d, stream_d): """ Build a mock open side effect using a dictionary of content for the files. :param string_d: keys are fil...
assert(len(set(string_d.keys()).intersection(set(stream_d.keys()))) == 0) def mock_open_side_effect(*args, **kwargs): if args[0] in string_d: return StringIO.StringIO(string_d[args[0]]) elif args[0] in stream_d: return stream_d[args[0]] else: raise IOError("No such file: " + args[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 write_header(self, out_strm, delim, f1_num_fields, f2_num_fields, f1_header=None, f2_header=None, missing_val=None): """ Write the header for a joined file. ...
mm = f1_header != f2_header one_none = f1_header is None or f2_header is None if mm and one_none and missing_val is None: raise InvalidHeaderError("Cannot generate output header when one " + "input file is missing a header and no " + "miss...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clean_restructuredtext(form_instance, content): """ RST syntax validation """
if content: errors = SourceReporter(content) if errors: raise ValidationError(map(map_parsing_errors, errors)) return 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 returns(*checkers_args): """ Create a decorator for validating function return values. Parameters checkers_args: positional arguments A single functions to a...
@decorator def run_checkers(func, *args, **kwargs): ret = func(*args, **kwargs) if type(ret) != tuple: ret = (ret, ) assert len(ret) == len(checkers_args) if checkers_args: for idx, checker_function in enumerate(checkers_args): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def regular_generic_msg(hostname, result, oneline, caption): ''' output on the result of a module run that is not command ''' if not oneline: return "%s | %s >> %s\n" % (hostname, caption, utils.jsonify(result,format=True)) else: return "%s | %s >> %s\n" % (hostname, caption, utils.jsonify(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def command_generic_msg(hostname, result, oneline, caption): ''' output the result of a command run ''' rc = result.get('rc', '0') stdout = result.get('stdout','') stderr = result.get('stderr', '') msg = result.get('msg', '') hostname = hostname.encode('utf-8') caption = caption.en...
<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_report_msg(hostname, module_name, result, oneline): ''' summarize the JSON results for a particular host ''' failed = utils.is_failed(result) msg = '' if module_name in [ 'command', 'shell', 'raw' ] and 'ansible_job_id' not in result and result.get('parsed',True) != False: if not faile...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _increment(self, what, host): ''' helper function to bump a statistic ''' self.processed[host] = 1 prev = (getattr(self, what)).get(host, 0) getattr(self, what)[host] = prev+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 compute(self, runner_results, setup=False, poll=False, ignore_errors=False): ''' walk through all results and increment stats ''' for (host, value) in runner_results.get('contacted', {}).iteritems(): if not ignore_errors and (('failed' in value and bool(value['failed'])) or ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def summarize(self, host): ''' return information about a particular host ''' return dict( ok = self.ok.get(host, 0), failures = self.failures.get(host, 0), unreachable = self.dark.get(host,0), changed = self.changed.get(host, 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 validate_get_dbs(connection): """ validates the connection object is capable of read access to rethink should be at least one test database by default :param...
remote_dbs = set(rethinkdb.db_list().run(connection)) assert remote_dbs return remote_dbs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_brain_requirements(connection, remote_dbs, requirements): """ validates the rethinkdb has the 'correct' databases and tables should get remote_dbs f...
for database in requirements: assert (database in remote_dbs), "database {} must exist".format(database) remote_tables = frozenset(rethinkdb.db(database).table_list().run(connection)) for table in requirements[database]: assert (table in remote_tables), "{} must exist in {}".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 brain_post(connection, requirements=None): """ Power On Self Test for the brain. Checks that the brain is appropriately seeded and ready for use. Raises Asse...
assert isinstance(connection, DefaultConnection) remote_dbs = validate_get_dbs(connection) assert validate_brain_requirements(connection, remote_dbs, requirements) assert validate_write_access(connection) return connection
<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(host=None, port=rethinkdb.DEFAULT_PORT, timeout=20, verify=True, **kwargs): """ RethinkDB semantic connection wrapper raises <brain.connection.BrainN...
if not host: host = DEFAULT_HOSTS.get(check_stage_env()) connection = None tries = 0 time_quit = time() + timeout while not connection and time() <= time_quit: tries += 1 connection = _attempt_connect(host, port, timeout/3, verify, **kwargs) if not connection: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def link_to_dashboard(self, dashboard_id=None, panel_id=None, **kwargs): r""" Links the sensor to a dashboard. :param dashboard_id: Id of the dashboard to link t...
if self._dimensions == 1: self._sensor_value.link_to_dashboard(dashboard_id, panel_id, **kwargs) else: for dimension in range(0, self._dimensions): self._sub_sensors[dimension].link_to_dashboard(dashboard_id, panel_id, **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 _new_sensor_reading(self, sensor_value): """ Call this method to signal a new sensor reading. This method handles DB storage and triggers different events. :...
if not self._active and not self._enabled: return if self._dimensions > 1: for dimension in range(0, self._dimensions): value = sensor_value[dimension] self._sub_sensors[dimension]._new_sensor_reading(value) else: self._sensor...
<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_path(label, pth): "check and expand paths" if pth is None: sys.exit("no %s path given" % label) if pth.startswith("/"): pass elif pth[0] in (".", "~"): pth = os.path.realpath(pth) else: pth = os.getcwd() + os.sep + pth if not os.path.exists(pth): ...
<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_svg(svgstr, size, filepath, target): "convert to PDF or PNG" # PREPARE CONVERSION PER TYPE if target == "PDF": img = cairo.PDFSurface(filepath, size, size) elif target == "PNG": img = cairo.ImageSurface(cairo.FORMAT_ARGB32, size, size) else: system.exit("unknown 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 var_dump(*obs): """ shows structured information of a object, list, tuple etc """
i = 0 for x in obs: str = var_dump_output(x, 0, ' ', '\n', True) print (str.strip()) #dump(x, 0, i, '', object) i += 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 difficulties_by_voivodeship(voivodeship, dt=datetime.now()): """ Get difficulties in voivodeship. :param voivodeship: Voivodeship numeric value. :param dt: D...
session = requests.Session() session.headers.update({'User-Agent': USER_AGENT}) session.headers.update({'X-Requested-With': 'XMLHttpRequest'}) session.get('{}/Mapa/'.format(HOST)) url = '{}/Mapa/PodajUtrudnieniaWWojewodztwie?KodWojewodztwa={}&_={}'.format(HOST, str(voivodeship), _datetime...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def table_to_string(headers, table, align="", *, lines=("-", "-+-", " | ")): """Write a list of headers and a table of rows to the terminal in a nice format. Par...
header_separator, header_junction, row_separator = lines align = ("{0:<<" + str(len(headers)) + "}").format(align or "") all_lens = [tuple(len(c) for c in r) for r in table] if headers: all_lens.append(tuple(len(h) for h in headers)) max_lens = [max(r[i] for r in all_lens) for i in range(len(headers))]...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ratio_and_percentage(current, total, time_remaining): """Returns the progress ratio and percentage."""
return "{} / {} ({}% completed)".format(current, total, int(current / total * 100))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ratio_and_percentage_with_time_remaining(current, total, time_remaining): """Returns the progress ratio, percentage and time remaining."""
return "{} / {} ({}% completed) (~{} remaining)".format( current, total, int(current / total * 100), time_remaining)
<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_generator(self): """ Returns a generator for the frange object instance. Returns ------- gen : generator A generator that yields successive samples from ...
s = self.slice gen = drange(s.start, s.stop, s.step) # intialises the generator return gen
<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_field_lookups(field_type, nullable): """ Return lookup table value and append isnull if this is a nullable field """
return LOOKUP_TABLE.get(field_type) + ['isnull'] if nullable else LOOKUP_TABLE.get(field_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 match_field(field_class): """ Iterates the field_classes and returns the first match """
for cls in field_class.mro(): if cls in list(LOOKUP_TABLE.keys()): return cls # could not match the field class raise Exception('{0} None Found '.format(field_class))
<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_template(template, target): """Given a dictionary template containing at least most of the relevant information and a dictionary target containing sec...
c = ConfManager('') for section in template: c.add_section(section) for option, o in template[section].items(): try: value = type(template[section][option]['value'])(target[section][option]) except KeyError: value = o['value'] finally: if 'value' in o: del o['value'] c.se...
<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_json(target, json, create_sections = False, create_options = False): """Given a confmanager object and a dictionary object, import the values from the...
is_dict = isinstance(json, dict) for o in json: if is_dict: section = o else: section = o[0] if not target.has_section(section): if create_sections: target.add_section(section) else: continue for k, v in (json[o].items() if is_dict else o[1]): if target.has_option(section,...
<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_sitemap(sitemap: typing.Mapping, prefix: list=None): """Create a sitemap template from the given sitemap. The `sitemap` should be a mapping where th...
# Ensures all generated urls are prefixed with a the prefix string if prefix is None: prefix = [] for segment, sub_segment in sitemap.items(): if isinstance(sub_segment, collections.abc.Mapping): yield from generate_sitemap(sub_segment, prefix + [segment]) elif isinstan...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _mock_input(self, target, content): """ mock human input :param target: the element to input to :param content: the content :return: """
content = helper.to_str(content) for w in content: target.send_keys(w) rand_block(0.01, 0.01)
<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_next_page(self, current_page_num=0): """
try: next_page = self.robot.get_elements( self.base.get('next_page'), multiple=True ) log.debug('<Site> has {} next page elems'.format(len(next_page))) if not next_page: return False for i, ele in enumer...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def response_result(self, **kwargs): """ default will fetch MAX_AP pages yield `self.driver.page_source, self.driver.current_url, 1` after mock submit, the first...
page_togo = kwargs.get('page_togo', self.max_page_togo) if page_togo <= 1: return self.robot.driver.page_source, self.robot.driver.current_url, 1 # 从 `1` 开始是由于已经加载了第一页 # 到 `page_togo` 结束, 是因为在 `page_togo -1` 时,已经点击了下一页 # 因此此处不能写为 range(0, page_togo), 或者(1, page_togo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _bulk_flag(self, request, queryset, action, done_message): """ Flag, approve, or remove some comments from an admin action. Actually calls the `action` argum...
n_comments = 0 for comment in queryset: action(request, comment) n_comments += 1 msg = ungettext('1 comment was successfully %(action)s.', '%(count)s comments were successfully %(action)s.', n_comments) self.messag...
<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(self, key, value): """ Updates the value of the given key in the file. Args: key (str): Key of the property to update. value (str): New value of the pr...
changed = super().set(key=key, value=value) if not changed: return False self._log.info('Saving configuration to "%s"...', self._filename) with open(self._filename, 'w') as stream: stream.write(self.content) self._log.info('Saved configuration to ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def next_color(self): """ Returns the next color. Currently returns a random color from the Colorbrewer 11-class diverging BrBG palette. Returns ------- next_rgb...
next_rgb_color = ImageColor.getrgb(random.choice(BrBG_11.hex_colors)) return next_rgb_color
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def paint_cube(self, x, y): """ Paints a cube at a certain position a color. Parameters x: int Horizontal position of the upper left corner of the cube. y: int V...
# get the color color = self.next_color() # calculate the position cube_pos = [x, y, x + self.cube_size, y + self.cube_size] # draw the cube draw = ImageDraw.Draw(im=self.image) draw.rectangle(xy=cube_pos, fill=color)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def paint_pattern(self): """ Paints all the cubes. """
x = 0 while x < self.width: y = 0 while y < self.height: self.paint_cube(x, y) y += self.cube_size x += self.cube_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 get_key_files(kfiles, dirname, names): """Return key files"""
for name in names: fullname = os.path.join(dirname, name) if os.path.isfile(fullname) and \ fullname.endswith('_rsa') or \ fullname.endswith('_dsa'): kfiles.put(fullname)
<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_ssh_keys(sshdir): """Get SSH keys"""
keys = Queue() for root, _, files in os.walk(os.path.abspath(sshdir)): if not files: continue for filename in files: fullname = os.path.join(root, filename) if (os.path.isfile(fullname) and fullname.endswith('_rsa') or fullname.endswith('_...
<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_ssh_dir(config, username): """Get the users ssh dir"""
sshdir = config.get('ssh_config_dir') if not sshdir: sshdir = os.path.expanduser('~/.ssh') if not os.path.isdir(sshdir): pwentry = getpwnam(username) sshdir = os.path.join(pwentry.pw_dir, '.ssh') if not os.path.isdir(sshdir): sshdir = 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_local_user(username): """Get the local username"""
try: _ = getpwnam(username) luser = username except KeyError: luser = getuser() return luser
<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_host_keys(hostname, sshdir): """get host key"""
hostkey = None try: host_keys = load_host_keys(os.path.join(sshdir, 'known_hosts')) except IOError: host_keys = {} if hostname in host_keys: hostkeytype = host_keys[hostname].keys()[0] hostkey = host_keys[hostname][hostkeytype] return hostkey
<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_sftp_conn(config): """Make a SFTP connection, returns sftp client and connection objects"""
remote = config.get('remote_location') parts = urlparse(remote) if ':' in parts.netloc: hostname, port = parts.netloc.split(':') else: hostname = parts.netloc port = 22 port = int(port) username = config.get('remote_username') or getuser() luser = get_local_user(us...
<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_and_consume(self): """Returns True if there is currently at least one token, and reduces it by one. """
if self._count < 1.0: self._fill() consumable = self._count >= 1.0 if consumable: self._count -= 1.0 self.throttle_count = 0 else: self.throttle_count += 1 return consumable
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _fill(self): """Fills bucket with accrued tokens since last fill."""
right_now = time.time() time_diff = right_now - self._last_fill if time_diff < 0: return self._count = min( self._count + self._fill_rate * time_diff, self._capacity, ) self._last_fill = right_now
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mysql_batch_and_fetch(mysql_config, *sql_queries): """ Excute a series of SQL statements before the final Select query Parameters mysql_config : dict The use...
# load modules import MySQLdb as mydb import sys import gc # ensure that `sqlqueries` is a list/tuple # split a string into a list if len(sql_queries) == 1: if isinstance(sql_queries[0], str): sql_queries = sql_queries[0].split(";") if isinstance(sql_queries[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 to_camel_case(snake_case_name): """ Converts snake_cased_names to CamelCaseNames. :param snake_case_name: The name you'd like to convert from. :type snake_ca...
bits = snake_case_name.split('_') return ''.join([bit.capitalize() for bit in bits])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def html_to_rst(html): """ Converts the service HTML docs to reStructured Text, for use in docstrings. :param html: The raw HTML to convert :type html: string :r...
doc = ReSTDocument() doc.include_doc_string(html) raw_doc = doc.getvalue() return raw_doc.decode('utf-8')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resize_image_folder(bucket, key_prefix, pil_size): """ This function resizes all the images in a folder """
con = boto.connect_s3() b = con.get_bucket(bucket) for key in b.list(key_prefix): key = b.get_key(key.name) if 'image' not in key.content_type: continue size = key.get_metadata('size') if size == str(pil_size): continue with tempfile.Temporary...
<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_section(self, section, friendly_name = None): """Adds a section and optionally gives it a friendly name.."""
if not isinstance(section, BASESTRING): # Make sure the user isn't expecting to use something stupid as a key. raise ValueError(section) # See if we've got this section already: if section in self.config: raise DuplicateSectionError(section) # Yep... Kick off. else: self.config[section] = Order...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def toggle(self, section, option): """Toggles option in section."""
self.set(section, option, not self.get(section, option))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(self, section, option, default = None): """Returns the option's value converted into it's intended type. If default is specified, return that on failure...
if self.has_section(section): try: return self.config[section][option].get('value', None) except KeyError: if default == None: raise NoOptionError(option) else: return default else: raise NoSectionError(section)
<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_dump(self): """Returns options and values."""
res = [] for section in self.sections(): sec = [] for option in self.options(section): sec.append([option, self.get(section, option)]) res.append([section, sec]) return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _onError(self, error): """ Stop observer, raise exception, then restart. This prevents an infinite ping pong game of exceptions. """
self.stop() self._logModule.err( error, "Unhandled error logging exception to %s" % (self.airbrakeURL,)) self.start()
<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_arguments(): """ Parses all the command line arguments using argparse and returns them. """
parser = argparse.ArgumentParser() parser.add_argument('file', metavar="FILE", nargs='+', help='file to be made executable') parser.add_argument("-p", "--python", metavar="VERSION", help="python version (2 or 3)") parser.add_argument('-v', '--version', 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 contains_shebang(f): """ Returns true if any shebang line is present in the first line of the file. """
first_line = f.readline() if first_line in shebangs.values(): return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_exec(fname, version): """ Writes the shebang and makes the file executable. """
# if no version is specified, use system default. if version is None: version = 'default' # write the shebang and then make the file executable. with open(fname, 'rb+') as f: put_shebang(f, version) # make the file os.chmod(fname, os.stat(fname).st_mode | 0o0111) print("{} ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def data_file(self): """Original uploaded data file the subject was created from. Returns ------- File-type object Reference to file on local disk """
return os.path.join(self.upload_directory, self.properties[datastore.PROPERTY_FILENAME])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def upload_file(self, filename, file_type=FILE_TYPE_FREESURFER_DIRECTORY): """Create an anatomy object on local disk from the given file. Currently, only Freesur...
# We currently only support one file type (i.e., FREESURFER_DIRECTORY). if file_type != FILE_TYPE_FREESURFER_DIRECTORY: raise ValueError('Unsupported file type: ' + file_type) return self.upload_freesurfer_archive(filename)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def upload_freesurfer_archive(self, filename, object_identifier=None, read_only=False): """Create an anatomy object on local disk from a Freesurfer anatomy tar f...
# At this point we expect the file to be a (compressed) tar archive. # Extract the archive contents into a new temporary directory temp_dir = tempfile.mkdtemp() try: tf = tarfile.open(name=filename, mode='r') tf.extractall(path=temp_dir) except (tarfile.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 getUI(args): """ build and return a UI object for this script. :param args: raw arguments to parse """
programName = os.path.basename(sys.argv[0]) longDescription = "takes a file with a list of p-values and applies " +\ "Benjamini and Hochberg FDR to convert to q-values " shortDescription = "takes a file with a list of p-values and applies " +\ "Benjamini and Hochberg FDR ...
<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): """ main entry point for the GenomicIntIntersection script. :param args: the arguments for this script, as a list of string. Should already have ...
# get options and arguments ui = getUI(args) if ui.optionIsSet("test"): # just run unit tests unittest.main(argv=[sys.argv[0]]) elif ui.optionIsSet("help"): # just show help ui.usage() else: verbose = ui.optionIsSet("verbose") # stranded? stranded = ui.optionIsSet("stranded") ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getAsTuple(self, section): """Get section name tuple :param section: section name :return: tuple object """
keys = self.getKeys(section) value_dict = self.getValues(section) return namedtuple(section, keys)(**value_dict)