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 get_ordered_values(self, keypath, distance_from, open_interval=True): """ Retrieves the referents's values sorted by their distance from the min, max, or mid...
values = [] if keypath[0] == 'target': # instances start with 'target' prefix, but # don't contain it, so we remove it here. keypath = keypath[1:] for _, instance in self.iter_singleton_referents(): value = instance.get_value_from_path(keypath) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_paths_for_attribute(self, attribute_name): """ Returns a path list to all attributes that have with a particular name. """
has_name = lambda name, structure: name == attribute_name return self.find_path(has_name, on_targets=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 add_cell(self, keypath, cell): """ Adds a new cell to the end of `keypath` of type `cell`"""
keypath = keypath[:] # copy inner = self # the most inner dict where cell is added cellname = keypath # the name of the cell assert keypath not in self, "Already exists: %s " % (str(keypath)) if isinstance(keypath, list): while len(keypath) > 1: cel...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def size(self): """ Returns the size of the belief state. Initially if there are $n$ consistent members, (the result of `self.number_of_singleton_referents()`) t...
n = self.number_of_singleton_referents() targets = list(self.iter_referents_tuples()) n_targets = len(targets) if n == 0 or n_targets == 0: return 0 #if len(self.__dict__['deferred_effects']) != 0: # return -1 size1 = len(list(self.iter_referent...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def iter_referents(self): """ Generates target sets that are compatible with the current beliefstate. """
tlow, thigh = self['targetset_arity'].get_tuple() clow, chigh = self['contrast_arity'].get_tuple() referents = list(self.iter_singleton_referents()) t = len(referents) low = max(1, tlow) high = min([t, thigh]) for targets in itertools.chain.from_iterable(itert...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def number_of_singleton_referents(self): """ Returns the number of singleton elements of the referential domain that are compatible with the current belief state...
if self.__dict__['referential_domain']: ct = 0 for i in self.iter_singleton_referents(): ct += 1 return ct else: raise Exception("self.referential_domain must be defined")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def iter_singleton_referents(self): """ Iterator of all of the singleton members of the context set. NOTE: this evaluates entities one-at-a-time, and does not ha...
try: for member in self.__dict__['referential_domain'].iter_entities(): if self['target'].is_entailed_by(member) and (self['distractor'].empty() or not self['distractor'].is_entailed_by(member)): yield member['num'], member except KeyError: ra...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def iter_singleton_referents_tuples(self): """ Iterator of all of the singleton members's id number of the context set. NOTE: this evaluates entities one-at-a-ti...
try: for member in self.__dict__['referential_domain'].iter_entities(): if self['target'].is_entailed_by(member) and (self['distractor'].empty() or not self['distractor'].is_entailed_by(member)): yield member['num'].low except KeyError: raise ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copy(self): """ Copies the BeliefState by recursively deep-copying all of its parts. Domains are not copied, as they do not change during the interpretation ...
copied = BeliefState(self.__dict__['referential_domain']) for key in ['environment_variables', 'deferred_effects', 'pos', 'p']: copied.__dict__[key] = copy.deepcopy(self.__dict__[key]) return copied
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gp_datdir(initial, topN): """example for plotting from a text file via numpy.loadtxt 1. prepare input/output directories 2. load the data into an OrderedDict...
# prepare input/output directories inDir, outDir = getWorkDirs() initial = initial.capitalize() inDir = os.path.join(inDir, initial) if not os.path.exists(inDir): # catch missing initial return "initial %s doesn't exist" % initial # prepare data data = OrderedDict() for file in os.listdir(inDir): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def linreg_ols_pinv(y, X, rcond=1e-15): """Linear Regression, OLS, by multiplying with Pseudoinverse"""
import numpy as np try: # multiply with inverse to compute coefficients return np.dot(np.linalg.pinv( np.dot(X.T, X), rcond=rcond), np.dot(X.T, y)) except np.linalg.LinAlgError: print("LinAlgError: SVD does not converge") return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_error_response(code, message, status=status.BAD_REQUEST): """Create a fail response. Args: code (str): the code of the error. The title should be low...
errors = dict(code=code, message=message) return Response(errors=errors, status=status)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def display_unit(self): """ Display unit of value. :type: ``str`` """
if self._display_unit: return self._display_unit elif self._Q: config = Configuration.display.unit_systems default_system = Configuration.unit_system units = config.systems[default_system] self._display_unit = units.get(self._type, self._unit...
<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(self, new_value): """ Updates the value. If the change exceeds the change delta observers and linked values are notified. """
datetime_value = None if new_value: datetime_value = new_value.strftime("%Y-%M-%dT%H:%M:%SZ") self._set_value(datetime_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 add_option(self, value, text, selected=False): """ Add option to select :param value: The value that the option represent. :param text: The text that should ...
option = {"value": value, "text": text, "selected":selected} self.options += [option] if selected: self.selected_options += [option] self._value.append(value) if self._persist_value: self.settings.store_value("selected_options", self.selected_...
<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_logfile_name(tags): """Formulates a log file name that incorporates the provided tags. The log file will be located in ``scgpm_seqresults_dnanexus.LOG_DI...
if not os.path.exists(sd.LOG_DIR): os.mkdir(sd.LOG_DIR) filename = "log" for tag in tags: filename += "_{}".format(tag) filename += ".txt" filename = os.path.join(sd.LOG_DIR,filename) return 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 rewrap(s, width=COLS): """ Join all lines from input string and wrap it at specified width """
s = ' '.join([l.strip() for l in s.strip().split('\n')]) return '\n'.join(textwrap.wrap(s, width))
<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_configuration(options): """ interactively add a new configuration """
if options.username != None: username = options.username else: username = prompt('Username: ') if options.password != None: password = options.password else: password = prompt('Password: ', hide_input=not options.show_password) if options.app_url != None: 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 get_initial_centroids(self): '''Randomly choose k data points as initial centroids''' if self.seed is not None: # useful for obtaining consistent results np.random.seed(self.seed) n = self.data.shape[0] # number of data points # Pick K indices from range [0, 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 smart_initialize(self): '''Use k-means++ to initialize a good set of centroids''' if self.seed is not None: # useful for obtaining consistent results np.random.seed(self.seed) centroids = np.zeros((self.k, self.data.shape[1])) # Randomly choose the first centroid. ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def filter_line(line: str, context: RunContext) -> typing.Optional[str]: """ Filters out lines that match a given regex :param line: line to filter :type line: st...
if context.filters is not None: for filter_ in context.filters: if re.match(filter_, line): return None return 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 capture_output_from_running_process(context: RunContext) -> None: """ Parses output from a running sub-process Decodes and filters the process output line by ...
# Get the raw output one line at a time _output = context.capture.readline(block=False) if _output: line = decode_and_filter(_output, context) if line: if not context.mute: # Print in real time _LOGGER_PROCESS.debug(line) # Buffer...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def autorg(filename, mininterval=None, qminrg=None, qmaxrg=None, noprint=True): """Execute autorg. Inputs: filename: either a name of an ascii file, or an instan...
if isinstance(filename, Curve): curve = filename with tempfile.NamedTemporaryFile('w+b', delete=False) as f: curve.save(f) filename = f.name cmdline = ['autorg', filename, '-f', 'ssv'] if mininterval is not None: cmdli...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def datcmp(*curves, alpha=None, adjust=None, test='CORMAP'): """Run datcmp on the scattering curves. Inputs: *curves: scattering curves as positional arguments a...
if len({len(c) for c in curves}) != 1: raise ValueError('All curves have to be of the same length.') datcmpargs = [] if alpha is not None: datcmpargs.append('--alpha=%f' % alpha) if adjust is not None: datcmpargs.append('--adjust=%s' % adjust) if test is not None: da...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def datporod(gnomoutfile): """Run datporod and return the estimated Porod volume. Returns: Radius of gyration found in the input file I0 found in the input file ...
results = subprocess.check_output(['datporod', gnomoutfile]).decode('utf-8').strip().split() return float(results[0]), float(results[1]), float(results[2])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gnom(curve, Rmax, outputfilename=None, Npoints_realspace=None, initial_alpha=None): """Run GNOM on the dataset. Inputs: curve: an instance of sastool.classes...
with tempfile.TemporaryDirectory(prefix='credolib_gnom') as td: curve.save(os.path.join(td, 'curve.dat')) print('Using curve for GNOM: qrange from {} to {}'.format(curve.q.min(), curve.q.max())) if Npoints_realspace is None: Npoints_realspace = "" else: Npoin...
<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_account(netid, timestamp=None): """ The Libraries object has a method for getting information about a user's library account """
response = _get_account(netid, timestamp=timestamp) return _account_from_json(response)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete(self, list_uuid, uuid): """ Delete one list."""
res = self.get(list_uuid, uuid) url = "%(base)s/%(list_uuid)s/contacts/%(uuid)s" % { 'base': self.local_base_url, 'list_uuid': list_uuid, 'uuid': uuid } self.core.delete(url) 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 find_plugin(value, key=DEFAULT_LOOKUP_KEY, conn=None): """ get's the plugin matching the key and value example: find_plugin("plugin1", "ServiceName") => list...
# cast to list to hide rethink internals from caller result = list(RPC.filter({ key: value }).run(conn)) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sendAppliedToOwner(self, context={}): """ Sent to project owner when user applies to a project """
super(ApplyMail, self).__init__(self.apply.project.owner.email, self.async, self.apply.project.owner.locale) return self.sendEmail('volunteerApplied-ToOwner', 'New volunteer', 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 add(self, *files): """Add one or more files to the index running git-add."""
try: _run_command(("git", "add") + files) except CalledProcessError: # Only if the command fails we check if the files # exist, because git-add most of the time fails when # the provided files are not found. for f in files: if...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def commit(self, message, files=None): """Run git-commit."""
if files: self.add(*files) return _run_command(["git", "commit", "-m", f'"{message}"'])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def log(self, _from=None, to=None): """Run git-log."""
command = ["git", "log"] if _from: to = "HEAD" if not to else to revision_range = f"{_from}..{to}" command.append(revision_range) git_log_text = _run_command(command) commit_text_lst = _extract_commit_texts(git_log_text) return [Commit(com...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tag(self, name=None): """Create and list tag objects running git-tag command"""
command = ["git", "tag"] if not name: command.extend( [ "-l", "--sort=creatordate", "--format=%(creatordate:short)%09%(refname:strip=2)", ] ) command_output = _run_command(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register(self, prefix, viewset, base_name=None, router_class=None): """ Append the given viewset to the proper registry. """
if base_name is None: base_name = self.get_default_base_name(viewset) if router_class is not None: kwargs = {'trailing_slash': bool(self.trailing_slash)} single_object_router_classes = ( AuthenticationRouter, SingleObjectRouter) if issub...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_nested( self, parent_prefix, prefix, viewset, base_name=None, parent_lookup_name=None, depth_level=1 ): """ Register a nested viewset wihtout worryi...
kwargs = { 'trailing_slash': bool(self.trailing_slash) } if parent_lookup_name is not None: kwargs.update(lookup=parent_lookup_name) # Section for the depth of the route and add more routes if depth_level > 1: routers = filter( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_urls(self): """ Generate the list of URL patterns including the registered single object routers urls. """
base_urls = super(SimpleRouter, self).get_urls() single_urls = sum([r.urls for r in self._single_object_registry], []) nested_urls = sum([r.urls for r in self._nested_object_registry], []) return base_urls + single_urls + nested_urls
<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_config(path): """parse either the config file we found, or use some canned defaults"""
config = configparser.ConfigParser() if path: # if user has config with user creds in it, this will grab it config.read(path) try: return {k: v for k, v in config["default"].items()} except KeyError: return {}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lookup(path, cache=True, scope=None, safe=False): """Get element reference from input element. The element can be a builtin/globals/scope object or is resolv...
result = None found = path and cache and path in __LOOKUP_CACHE if found: result = __LOOKUP_CACHE[path] elif path: _eval = safe_eval if safe else eval try: # search among scope result = _eval(path, scope) except (NameError, SyntaxError): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getpath(element): """Get full path of a given element such as the opposite of the resolve_path behaviour. :param element: must be directly defined into a mod...
if not hasattr(element, '__name__'): raise AttributeError( 'element {0} must have the attribute __name__'.format(element) ) result = element.__name__ if ismodule(element) else \ '{0}.{1}'.format(element.__module__, element.__name__) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_eventclass(event_id): """Decorator for registering event classes for parsing """
def register(cls): if not issubclass(cls, Event): raise MessageException(('Cannot register a class that' ' is not a subclass of Event')) EVENT_REGISTRY[event_id] = cls logger.debug('######### Event registry is now: {0}'.format( EVE...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def json_minify(string, strip_space=True): # pragma: no cover """Removes whitespace from json strings, returning the string """
in_string = False in_multi = False in_single = False new_str = [] index = 0 for match in re.finditer(TOKENIZER, string): if not (in_multi or in_single): tmp = string[index:match.start()] if not in_string and strip_space: # replace white space 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 resolve_template(template): "Accepts a template object, path-to-template or list of paths" if isinstance(template, (list, tuple)): return loader.select_template(template) elif isinstance(template, basestring): try: return loader.get_template(template) except TemplateD...
<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(self, value, *args, **kwargs): """ Takes a string value and returns the Date based on the format """
from datetime import datetime value = self.obj.value(value, *args, **kwargs) try: rv = datetime.strptime(value, self.format) except ValueError as _: # noqa rv = None return rv
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _interpret_framer(self, args, kwargs): """ Interprets positional and keyword arguments related to framers. :param args: A tuple of positional arguments. The ...
# Cannot specify both positional and keyword arguments, but # must provide one or the other if not args and not kwargs: raise exc.InvalidFramerSpecification( "No framers specified") elif args and kwargs: raise exc.InvalidFramerSpecification( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connection_made(self, transport): """ Called by the underlying transport when a connection is made. :param transport: The transport representing the connecti...
# Save the underlying transport self._transport = transport # Call connection_made() on the client protocol, passing # ourself as the transport self._client.connection_made(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 data_received(self, data): """ Called by the underlying transport when data is received. :param data: The data received on the connection. """
# First, add the data to the receive buffer self._recv_buf += data # Now, pass all frames we can find to the client protocol while self._recv_buf and not self._recv_paused: try: # Extract one frame frame = self._recv_framer.to_frame(self._re...
<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_extra_info(self, name, default=None): """ Called by the client protocol to return optional transport information. Information requests not recognized by ...
# Handle data we know about if name in self._handlers: return self._handlers[name](self) # Call get_extra_info() on the transport return self._transport.get_extra_info(name, default=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 set_write_buffer_limits(self, high=None, low=None): """ Called by the client protocol to set the high- and low-water limits for write flow control. These two...
# Call set_write_buffer_limits() on the transport self._transport.set_write_buffer_limits(high=high, low=low)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send_frame(self, frame): """ Called by the client protocol to send a frame to the remote peer. This method does not block; it buffers the data and arranges f...
# Convert the frame to bytes and write them to the connection data = self._send_framer.to_bytes(frame, self._send_state) self._transport.write(data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def menu(): """ Return global menu composed from all modules menu. This method will compose the global menu by calling menu() function for module, it should be l...
root = MenuItem('') for mod in droplet.modules(): if mod.installed: module_path = mod.__class__.__module__.rsplit('.', 1)[0] menu = import_module(module_path + '.menu') if menu: menu.menu(root) return root
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def append(self, item): """ Add the given item as children """
if self.url: raise TypeError('Menu items with URL cannot have childrens') # Look for already present common node if not item.is_leaf(): for current_item in self.items: if item.name == current_item.name: for children in item.items: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def doc_id(self): """Returns the couchbase document's id, object property. :returns: The document id (that is created from :attr:'doc_type' and :attr:'__key_fiel...
if self.id: return '%s_%s' % (self.doc_type, self.id.lower()) return self._hashed_key
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def touch(self, expiration): """Updates the current document's expiration value. :param expiration: Expiration in seconds for the document to be removed by couch...
if not self.cas_value or not self.doc_id: raise self.DoesNotExist(self) return self.bucket.touch(self.doc_id, expiration)
<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_description(status_code): """ Get the description for a status code. """
description = _descriptions.get(status_code) if description is None: description = 'code = %s (no description)' % str(status_code) return description
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def metered_meta(metrics, base=type): """Creates a metaclass that will add the specified metrics at a path parametrized on the dynamic class name. Prime use case...
class _MeteredMeta(base): def __new__(meta, name, bases, dict_): new_dict = dict(**dict_) for attr_name, template, factory in metrics: new_dict[attr_name] = factory(template.format(name)) return super(_MeteredMeta, meta).__new__(meta, name, bases, new_dic...
<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_action_list(self, item_list, **kwargs): ''' Generates a list of actions for sending to Elasticsearch ''' action_list = [] es_index = get2(kwargs, "es_index", self.es_index) action_type = kwargs.get("action_type","index") action_settings = {'_op_type': action_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 bulk_save(self, action_list, **kwargs): ''' sends a passed in action_list to elasticsearch ''' lg = logging.getLogger("%s.%s" % (self.ln, inspect.stack()[0][3])) lg.setLevel(self.log_level) err_log = logging.getLogger("index.errors") es = self.es es_index = ge...
<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_list(self, method="list", **kwargs): """ returns a key value list of items based on the specfied criteria """
lg = logging.getLogger("%s.%s" % (self.ln, inspect.stack()[0][3])) lg.setLevel(self.log_level) args = inspect.getargvalues(inspect.currentframe())[3] lg.debug("\n****** Args *****:\n%s", pp.pformat(args)) es = kwargs.get("es",self.es) doc_ty...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def authorize_role(self, role, protocol, from_port, to_port, cidr_ip): """ Authorize access to machines in a given role from a given network. """
if (protocol != 'tcp' and protocol != 'udp'): raise RuntimeError('error: expected protocol to be tcp or udp '\ 'but got %s' % (protocol)) self._check_role_name(role) role_group_name = self._group_name_for_role(role) # Revoke first to avoid InvalidPermission.Duplicate...
<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_running(self, role, number): """ Check that a certain number of instances in a role are running. """
instances = self.get_instances_in_role(role, "running") if len(instances) != number: print "Expected %s instances in role %s, but was %s %s" % \ (number, role, len(instances), instances) return False else: return instances
<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_instances_in_role(self, role, state_filter=None): """ Get all the instances in a role, filtered by state. @param role: the name of the role @param state_...
self._check_role_name(role) instances = [] for instance in self._get_instances(self._group_name_for_role(role), state_filter): instances.append(Instance(instance.id, instance.dns_name, instance.private_dns_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 get_instances(self, state_filter=None): """ Get all the instances filtered by state. @param state_filter: the state that the instance should be in (e.g. "run...
instances = [] for instance in self._get_instances(self._get_cluster_group_name(), state_filter): instances.append(Instance(instance.id, instance.dns_name, instance.private_dns_name, instance.priva...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def print_status(self, roles=None, state_filter="running"): """ Print the status of instances in the given roles, filtered by state. """
if not roles: for instance in self._get_instances(self._get_cluster_group_name(), state_filter): self._print_instance("", instance) else: for role in roles: for instance in self._get_instances(self._group_name_for_role(role), ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def CreateBlockDeviceMap(self, image_id, instance_type): """ If you launch without specifying a manual device block mapping, you may not get all the ephemeral de...
# get the block device mapping stored with the image image = self.ec2.get_image(image_id) block_device_map = image.block_device_mapping assert(block_device_map) # update it to include the ephemeral devices # max is 4... is it an error for instances with fewer than 4 ? ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _create_security_groups(self, role): """ Create the security groups for a given role, including a group for the cluster if it doesn't exist. """
self._check_role_name(role) security_group_names = self._get_all_group_names() cluster_group_name = self._get_cluster_group_name() if not cluster_group_name in security_group_names: self.ec2.create_security_group(cluster_group_name, "Cluster (%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 _delete_security_groups(self): """ Delete the security groups for each role in the cluster, and the group for the cluster. """
group_names = self._get_all_group_names_for_cluster() for group in group_names: self.ec2.delete_security_group(group)
<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(expr): """Serialize input expr into a parsable value. :rtype: str"""
result = None if isinstance(expr, string_types): result = expr elif expr is not None: result = '=py:{0}'.format(expr) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse( svalue, conf=None, configurable=None, ptype=None, scope=DEFAULT_SCOPE, safe=DEFAULT_SAFE, besteffort=DEFAULT_BESTEFFORT ): """Parser which delegates p...
result = None if ptype is None: ptype = object compilation = REGEX_EXPR.match(svalue) _scope = {} if scope is None else scope.copy() if compilation: lang, expr = compilation.group('lang', 'expr') result = _exprparser( expr=expr, lang=lang, conf=conf, confi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _exprparser( expr, scope, lang=None, conf=None, configurable=None, safe=DEFAULT_SAFE, besteffort=DEFAULT_BESTEFFORT, tostr=False ): """In charge of parsing a...
if scope is None: scope = {} scope.update({ 'configurable': configurable, 'conf': conf }) expr = REGEX_EXPR_R.sub( _refrepl( configurable=configurable, conf=conf, safe=safe, scope=scope, besteffort=besteffort ), expr ) result =...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _ref( pname, conf=None, configurable=None, cname=None, path=None, history=0 ): """Resolve a parameter value. :param Configuration conf: configuration to use....
result = None if configurable is not None: kwargs = {} if conf is not None: kwargs['conf'] = conf if path is not None: kwargs['paths'] = path if conf is None: conf = configurable.getconf(**kwargs) if conf is None: raise Pars...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def mount(dev, mountpoint, flags='', log=None): '''Mount the given dev to the given mountpoint by using the given flags''' ensureDirectory(mountpoint) systemCall('mount %s %s %s' % (flags, dev, mountpoint), log=log)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def systemCall(cmd, sh=True, log=None): '''Fancy magic version of os.system''' if log is None: log = logging log.debug('System call [sh:%s]: %s' \ % (sh, cmd)) out = [] proc = None poller = None outBuf = [''] errBuf = [''] def pollOutput(): ''' ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def chrootedSystemCall(chrootDir, cmd, sh=True, mountPseudoFs=True, log=None): '''Chrooted version of systemCall. Manages necessary pseudo filesystems.''' if log is None: log = conduct.app.log # determine mount points for pseudo fs proc = path.join(chrootDir, 'proc') sys = path.join(chrootD...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extensions(self, component): """Return a list of components that declare to implement the extension point interface. """
classes = ComponentMeta._registry.get(self.interface, ()) components = [component.compmgr[cls] for cls in classes] return [c for c in components if c]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def implements(*interfaces): """Can be used in the class definition of `Component` subclasses to declare the extension points that are extended. """
import sys frame = sys._getframe(1) locals_ = frame.f_locals # Some sanity checks msg = 'implements() can only be used in a class definition' assert locals_ is not frame.f_globals and '__module__' in locals_, msg locals_.setdefault('_implements', []).extend(in...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_enabled(self, cls): """Return whether the given component class is enabled."""
if cls not in self.enabled: self.enabled[cls] = self.is_component_enabled(cls) return self.enabled[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 disable_component(self, component): """Force a component to be disabled. :param component: can be a class or an instance. """
if not isinstance(component, type): component = component.__class__ self.enabled[component] = False self.components[component] = 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 size(self): """Calculate and return the file size in bytes."""
old = self.__file.tell() # old position self.__file.seek(0, 2) # end of file n_bytes = self.__file.tell() # file size in bytes self.__file.seek(old) # back to old position return n_bytes
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prev(self, n=1): """Get the previous n data from file. Keyword argument: n -- number of structs to be retrieved (default 1) Must be greater than 0. Return: A...
# Current position - #data i = abs(self.tell - n) # Get the next n data starting from i return self.get(i, 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 get(self, i, n=1): """Get the n data starting from the ith. Keyword argument: i -- position in file n -- number of structs to be retrieved (default 1) Must b...
# If there is nothing to get... if self.size == 0: return None if n < 1: return [] # Current byte position - (n * data_size) offset = i * self.__strct.size # Set file pointer to -(#data) self.__file.seek(offset) # Unpack raw da...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def last(self): """Get the last object in file."""
# End of file self.__file.seek(0, 2) # Get the last struct data = self.get(self.length - 1) 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 append(self, value): """Write the value into the file. Keyword arguments: value -- value to be writen (tuple) """
# Pack value data = self.pack(value) # End of file self.__file.seek(0, 2) # Write packed value self.__file.write(data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write(self, i, value): """Write value in ith position in file. Keyword arguments: i -- position in file value -- value to be packed (tuple) """
# Current byte position - (n * data_size) offset = i * self.__strct.size # Set file pointer to -(#data) self.__file.seek(offset) # Pack value data = self.pack(value) # Write packed value self.__file.write(data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _inspectArguments(self, args): """inspect the command-line-args and give them to appBase"""
if args: self.exec_path = PathStr(args[0]) else: self.exec_path = None session_name = None args = args[1:] openSession = False for arg in args: if arg in ('-h', '--help'): self._showHelp() 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 save(self): """save the current session override, if session was saved earlier"""
if self.path: self._saveState(self.path) else: self.saveAs()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def open(self): """open a session to define in a dialog in an extra window"""
filename = self.dialogs.getOpenFileName(filter="*.%s" % self.FTYPE) if filename: self.new(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 new(self, filename=None): """start a session an independent process"""
path = (self.exec_path,) if self.exec_path.filetype() in ('py', 'pyw', 'pyz', self.FTYPE): # get the absolute path to the python-executable p = find_executable("python") path = (p, 'python') + path else: # if run in frozen env (.exe): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _saveState(self, path): """save current state and add a new state"""
self.addSession() # next session self._save(str(self.n_sessions), 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 _autoSave(self): """save state into 'autosave' """
a = 'autoSave' path = self.path if not path: path = self.dir.join('%s.%s' % (a, self.FTYPE)) self._createdAutosaveFile = path self.tmp_dir_save_session = self.tmp_dir_session.join(a).mkdir() self._save(a, 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 blockingSave(self, path): """ saved session to file - returns after finish only called by interactiveTutorial-save at the moment """
self.tmp_dir_save_session = self.tmp_dir_session.join('block').mkdir() state = {'session': dict(self.opts), 'dialogs': self.dialogs.saveState()} self.saveThread.prepare('0', path, self.tmp_dir_session, state) self.sigSave.emit(self) self.saveThread.run()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _save(self, stateName, path): """save into 'stateName' to pyz-path"""
print('saving...') state = {'session': dict(self.opts), 'dialogs': self.dialogs.saveState()} self.sigSave.emit(state) self.saveThread.prepare(stateName, path, self.tmp_dir_session, state) self.saveThread.start() self.current_session = stateN...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _recusiveReplaceArrayWithPlaceholder(self, state): """ replace all numpy.array within the state dict with a placeholder this allows to save the arrays ex...
arrays = {} def recursive(state): for key, val in state.items(): if isinstance(val, dict): recursive(val) else: if isinstance(val, np.ndarray): name = 'arr_%i' % recursive.c ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start_indexing(self): """ Read all the files and tokenize their text into words and accumulate all the words in a list. """
for filepath in self.filepaths: with open(filepath) as fp: blob = fp.read() self.words.extend(self.tokenize(blob))
<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_name(name): """ Split a query name into field name, operator and whether it is inverted. """
inverted, op = False, OP_EQ if name is not None: for op_ in (OP_NIN, OP_IN, OP_NOT, OP_LIKE): if name.endswith(op_): op = op_ name = name[:len(name) - len(op)] break if name.startswith('!'): inverted = True 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 connect_db(database_name=":memory:"): """ Connect lazy_record to the database at the path specified in +database_name+. """
db = repo.Repo.connect_db(database_name) base.Repo.db = db query.Repo.db = db
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def close_db(): """ Close the connection to the database opened in `connect_db` """
db = repo.Repo.db if db is not None: db.close() repo.Repo.db = None base.Repo.db = None query.Repo.db = 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 load_schema(schema): """ Load a schema file with path +schema+ into the database. Assumes that there exists an active database connection. """
with repo.Repo.db: repo.Repo.db.executescript(schema)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_values(self, min=None, max=None, conflict='warning'): """ Update the boundaries, handling possible conflicts. :param conflict: What to do in cas...
conflict_txt = None if min is not None: if min > self.min: if min > self.max: self.max = self.highest self.prefer_highest = False conflict_txt = 'Minimum {0:s} conflicts with maximum {1:s}; minimum is higher so it takes precedence, but lower values in range are not preferred.'.format('{0: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 add_selection(self, selection, conflict = 'warning'): """ Restrict the range given a selection string :param selection: A single selection (without com...
selection = selection.replace(' ', '').replace('=.', '=0.') if not selection: return if selection.count(',') or selection.count('_'): raise VersionFormatError(('Version string "{0:s}" is incorrect. Perhaps you\'re trying to add a combined one; ' + 'you should use add_selections for that').format(select...