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 decode_imod(packet, channel=1): """Decode an 4 channel imod. May support 6 channels."""
val = str(packet.get(QSDATA, '')) if len(val) == 8 and val.startswith('4e'): try: _map = ((5, 1), (5, 2), (5, 4), (4, 1), (5, 1), (5, 2))[ channel - 1] return (int(val[_map[0]], 16) & _map[1]) == 0 except IndexError: return None return Non...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decode_pir(packet, channel=1): """Decode a PIR."""
val = str(packet.get(QSDATA, '')) if len(val) == 8 and val.startswith('0f') and channel == 1: return int(val[-4:], 16) > 0 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 decode_temperature(packet, channel=1): """Decode the temperature."""
val = str(packet.get(QSDATA, '')) if len(val) == 12 and val.startswith('34') and channel == 1: temperature = int(val[-4:], 16) return round(float((-46.85 + (175.72 * (temperature / pow(2, 16)))))) 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 decode_humidity(packet, channel=1): """Decode the humidity."""
val = str(packet.get(QSDATA, '')) if len(val) == 12 and val.startswith('34') and channel == 1: humidity = int(val[4:-4], 16) return round(float(-6 + (125 * (humidity / pow(2, 16))))) 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 update_devices(self, devices): """Update values from response of URL_DEVICES, callback if changed."""
for qspacket in devices: try: qsid = qspacket[QS_ID] except KeyError: _LOGGER.debug("Device without ID: %s", qspacket) continue if qsid not in self: self[qsid] = QSDev(data=qspacket) dev = self[qsi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def geist_replay(wrapped, instance, args, kwargs): """Wraps a test of other function and injects a Geist GUI which will enable replay (set environment variable G...
path_parts = [] file_parts = [] if hasattr(wrapped, '__module__'): module = wrapped.__module__ module_file = sys.modules[module].__file__ root, _file = os.path.split(module_file) path_parts.append(root) _file, _ = os.path.splitext(_file) file_parts.append(_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 _nbinom_ztrunc_p(mu, k_agg): """ Calculates p parameter for truncated negative binomial Function given in Sampford 1955, equation 4 Note that omega = 1 / 1 +...
p_eq = lambda p, mu, k_agg: (k_agg * p) / (1 - (1 + p)**-k_agg) - mu # The upper bound needs to be large. p will increase with increasing mu # and decreasing k_agg p = optim.brentq(p_eq, 1e-10, 1e10, args=(mu, k_agg)) return 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 _ln_choose(n, k_agg): ''' log binomial coefficient with extended gamma factorials. n and k_agg may be int or array - if both array, must be the same length. ''' gammaln = special.gammaln return gammaln(n + 1) - (gammaln(k_agg + 1) + gammaln(n - k_agg + 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 _solve_k_from_mu(data, k_array, nll, *args): """ For given args, return k_agg from searching some k_range. Parameters data : array k_range : array nll : func...
# TODO: See if a root finder like fminbound would work with Decimal used in # logpmf method (will this work with arrays?) nll_array = np.zeros(len(k_array)) for i in range(len(k_array)): nll_array[i] = nll(data, k_array[i], *args) min_nll_idx = np.argmin(nll_array) return k_array[mi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _expon_solve_lam_from_mu(mu, b): """ For the expon_uptrunc, given mu and b, return lam. Similar to geom_uptrunc """
def lam_eq(lam, mu, b): # Small offset added to denominator to avoid 0/0 erors lam, mu, b = Decimal(lam), Decimal(mu), Decimal(b) return ( (1 - (lam*b + 1) * np.exp(-lam*b)) / (lam - lam * np.exp(-lam*b) + Decimal(1e-32)) - mu ) return optim.brentq(lam_eq, -100, 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 _make_rank(dist_obj, n, mu, sigma, crit=0.5, upper=10000, xtol=1): """ Make rank distribution using both ppf and brute force. Setting crit = 1 is equivalent ...
qs = (np.arange(1, n + 1) - 0.5) / n rank = np.empty(len(qs)) brute_ppf = lambda val, prob: prob - dist_obj.cdf(val, mu, sigma) qs_less = qs <= crit ind = np.sum(qs_less) # Use ppf if qs are below crit rank[qs_less] = dist_obj.ppf(qs[qs_less], mu, sigma) # Use brute force if they ar...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _mean_var(vals, pmf): """ Calculates the mean and variance from vals and pmf Parameters vals : ndarray Value range for a distribution pmf : ndarray pmf value...
mean = np.sum(vals * pmf) var = np.sum(vals ** 2 * pmf) - mean ** 2 return mean, var
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _pdf_w_mean(self, x, mean, sigma): """ Calculates the pdf of a lognormal distribution with parameters mean and sigma Parameters mean : float or ndarray Mean ...
# Lognorm pmf with mean for optimization mu, sigma = self.translate_args(mean, sigma) return self.logpdf(x, mu, sigma)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def union_join(left, right, left_as='left', right_as='right'): """ Join function truest to the SQL style join. Merges both objects together in a sum-type, saving...
attrs = {} attrs.update(get_object_attrs(right)) attrs.update(get_object_attrs(left)) attrs[left_as] = left attrs[right_as] = right if isinstance(left, dict) and isinstance(right, dict): return attrs else: joined_class = type(left.__class__.__name__ + right.__class__.__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 best_item_from_list(item,options,fuzzy=90,fname_match=True,fuzzy_fragment=None,guess=False): '''Returns just the best item, or ``None``''' match = best_match_from_list(item,options,fuzzy,fname_match,fuzzy_fragment,guess) if match: return match[0] 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: async def create_hlk_sw16_connection(port=None, host=None, disconnect_callback=None, reconnect_callback=None, loop=None, logger=None, timeout=None, reconnect_inte...
client = SW16Client(host, port=port, disconnect_callback=disconnect_callback, reconnect_callback=reconnect_callback, loop=loop, logger=logger, timeout=timeout, reconnect_interval=reconnect_interval) await client.set...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _reset_timeout(self): """Reset timeout for date keep alive."""
if self._timeout: self._timeout.cancel() self._timeout = self.loop.call_later(self.client.timeout, self.transport.close)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reset_cmd_timeout(self): """Reset timeout for command execution."""
if self._cmd_timeout: self._cmd_timeout.cancel() self._cmd_timeout = self.loop.call_later(self.client.timeout, self.transport.close)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _valid_packet(raw_packet): """Validate incoming packet."""
if raw_packet[0:1] != b'\xcc': return False if len(raw_packet) != 19: return False checksum = 0 for i in range(1, 17): checksum += raw_packet[i] if checksum != raw_packet[18]: return False return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _handle_raw_packet(self, raw_packet): """Parse incoming packet."""
if raw_packet[1:2] == b'\x1f': self._reset_timeout() year = raw_packet[2] month = raw_packet[3] day = raw_packet[4] hour = raw_packet[5] minute = raw_packet[6] sec = raw_packet[7] week = raw_packet[8] 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 send_packet(self): """Write next packet in send queue."""
waiter, packet = self.client.waiters.popleft() self.logger.debug('sending packet: %s', binascii.hexlify(packet)) self.client.active_transaction = waiter self.client.in_transaction = True self.client.active_packet = packet self.reset_cmd_timeout() self.transport.w...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def format_packet(command): """Format packet to be sent."""
frame_header = b"\xaa" verify = b"\x0b" send_delim = b"\xbb" return frame_header + command.ljust(17, b"\x00") + verify + send_delim
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def setup(self): """Set up the connection with automatic retry."""
while True: fut = self.loop.create_connection( lambda: SW16Protocol( self, disconnect_callback=self.handle_disconnect_callback, loop=self.loop, logger=self.logger), host=self.host, port=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 stop(self): """Shut down transport."""
self.reconnect = False self.logger.debug("Shutting down.") if self.transport: self.transport.close()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def handle_disconnect_callback(self): """Reconnect automatically unless stopping."""
self.is_connected = False if self.disconnect_callback: self.disconnect_callback() if self.reconnect: self.logger.debug("Protocol disconnected...reconnecting") await self.setup() self.protocol.reset_cmd_timeout() if self.in_transaction:...
<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_status_callback(self, callback, switch): """Register a callback which will fire when state changes."""
if self.status_callbacks.get(switch, None) is None: self.status_callbacks[switch] = [] self.status_callbacks[switch].append(callback)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _send(self, packet): """Add packet to send queue."""
fut = self.loop.create_future() self.waiters.append((fut, packet)) if self.waiters and self.in_transaction is False: self.protocol.send_packet() return fut
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def turn_on(self, switch=None): """Turn on relay."""
if switch is not None: switch = codecs.decode(switch.rjust(2, '0'), 'hex') packet = self.protocol.format_packet(b"\x10" + switch + b"\x01") else: packet = self.protocol.format_packet(b"\x0a") states = await self._send(packet) return states
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def turn_off(self, switch=None): """Turn off relay."""
if switch is not None: switch = codecs.decode(switch.rjust(2, '0'), 'hex') packet = self.protocol.format_packet(b"\x10" + switch + b"\x02") else: packet = self.protocol.format_packet(b"\x0b") states = await self._send(packet) return states
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def status(self, switch=None): """Get current relay status."""
if switch is not None: if self.waiters or self.in_transaction: fut = self.loop.create_future() self.status_waiters.append(fut) states = await fut state = states[switch] else: packet = self.protocol.format_pa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _delta_dir(): """returns the relative path of the current directory to the git repository. This path will be added the 'filename' path to find the file. It c...
repo = Repo() current_dir = os.getcwd() repo_dir = repo.tree().abspath delta_dir = current_dir.replace(repo_dir, '') if delta_dir: return delta_dir + '/' else: 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 add_file_to_repo(filename): """Add a file to the git repo This method does the same than a :: $ git add filename Keyword Arguments: :filename: (str) -- name ...
try: repo = Repo() index = repo.index index.add([_delta_dir() + filename]) except Exception as e: print("exception while gitadding file: %s" % e.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 reset_to_last_commit(): """reset a modified file to his last commit status This method does the same than a :: $ git reset --hard Keyword Arguments: <none> R...
try: repo = Repo() gitcmd = repo.git gitcmd.reset(hard=True) except Exception: pass
<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_history(filename): """Retrieve the commit history for a given filename. Keyword Arguments: :filename: (str) -- full name of the file Returns: list of ...
result = [] repo = Repo() for commit in repo.head.commit.iter_parents(paths=_delta_dir() + filename): result.append({'date': datetime.fromtimestamp(commit.committed_date + commit.committer_tz_offset), 'hexsh...
<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_committed_file(gitref, filename): """Retrieve the content of a file in an old commit and returns it. Ketword Arguments: :gitref: (str) -- full reference...
repo = Repo() commitobj = repo.commit(gitref) blob = commitobj.tree[_delta_dir() + filename] return blob.data_stream.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 get(self, key, _else=None): """The method to get an assets value """
with self._lock: self.expired() # see if everything expired try: value = self._dict[key].get() return value except KeyError: return _else except ValueError: return _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 set(self, key, value, expires=None, future=None): """Set a value """
# assert the values above with self._lock: try: self._dict[key].set(value, expires=expires, future=future) except KeyError: self._dict[key] = moment(value, expires=expires, future=future, lock=self._lock) 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 values(self): """Will only return the current values """
self.expired() values = [] for key in self._dict.keys(): try: value = self._dict[key].get() values.append(value) except: continue return values
<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_key(self, key): """Does the key exist? This method will check to see if it has expired too. """
if key in self._dict: try: self[key] return True except ValueError: return False except KeyError: return False 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 dicom2db(file_path, file_type, is_copy, step_id, db_conn, sid_by_patient=False, pid_in_vid=False, visit_in_path=False, rep_in_path=False): """Extract some me...
global conn conn = db_conn tags = dict() logging.info("Extracting DICOM headers from '%s'" % file_path) try: dcm = dicom.read_file(file_path) dataset = db_conn.get_dataset(step_id) tags['participant_id'] = _extract_participant(dcm, dataset, pid_in_vid) if visit_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 remaining_bytes(self, meta=True): """ Returns the remaining, unread bytes from the buffer. """
pos, self._pos = self._pos, len(self.buffer) return self.buffer[pos:]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decode(self, bytes): """ Decodes the packet off the byte string. """
self.buffer = bytes self._pos = 0 Packet = identifier.get_packet_from_id(self._read_variunt()) # unknown packets will be None from the identifier if Packet is None: return None packet = Packet() packet.ParseFromString(self.remaining_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 encode(self, packet): """ Pushes a packet to the writer, encoding it on the internal buffer. """
id = identifier.get_packet_id(packet) if id is None: raise EncoderException('unknown packet') self._write_variunt(id) self._write(packet.SerializeToString()) return bytes(self.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 create(self, data): """ Create object from the given data. The given data may or may not have been validated prior to calling this function. This function wi...
# todo: copy-paste code from representation.validate -> refactor if data is None: return None prototype = {} errors = {} # create and populate the prototype for field_name, field_spec in self.spec.fields.items(): try: value = 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 serialize(self, entity, request=None): """ Serialize entity into dictionary. The spec can affect how individual fields will be serialized by implementing ``s...
def should_we_insert(value, field_spec): return value not in self.missing or field_spec.required errors = {} ret = {} for field_name, field_spec in self.spec.fields.items(): value = self._get_value_for_serialization(entity, field_name, field_spec) ...
<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_value(self, data, name, spec): """ Create the value for a field. :param data: the whole data for the entity (all fields). :param name: name of the in...
field = getattr(self, 'create_' + name, None) if field: # this factory has a special creator function for this field return field(data, name, spec) value = data.get(name) return spec.fields[name].clean(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_serialize_func(self, name, spec): """ Return the function that is used for serialization. """
func = getattr(self, 'serialize_' + name, None) if func: # this factory has a special serializer function for this field return func func = getattr(spec.fields[name], 'serialize', None) if func: return func return lambda value, entity, request...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _create_mappings(self, spec): """ Create property name map based on aliases. """
ret = dict(zip(set(spec.fields), set(spec.fields))) ret.update(dict([(n, s.alias) for n, s in spec.fields.items() if s.alias])) return ret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def all_substrings(s): ''' yields all substrings of a string ''' join = ''.join for i in range(1, len(s) + 1): for sub in window(s, i): yield join(sub)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def equivalent_release_for_product(self, product): """ Returns the release for a specified product with the same channel and major version with the highest minor...
releases = self._default_manager.filter( version__startswith=self.major_version() + '.', channel=self.channel, product=product).order_by('-version') if not getattr(settings, 'DEV', False): releases = releases.filter(is_public=True) if releases: 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 notes(self, public_only=False): """ Retrieve a list of Note instances that should be shown for this release, grouped as either new features or known issues, ...
tag_index = dict((tag, i) for i, tag in enumerate(Note.TAGS)) notes = self.note_set.order_by('-sort_num', 'created') if public_only: notes = notes.filter(is_public=True) known_issues = [n for n in notes if n.is_known_issue_for(self)] new_features = sorted( ...
<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_dict(self): """Return a dict all all data about the release"""
data = model_to_dict(self, exclude=['id']) data['title'] = unicode(self) data['slug'] = self.slug data['release_date'] = self.release_date.date().isoformat() data['created'] = self.created.isoformat() data['modified'] = self.modified.isoformat() new_features, kno...
<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_simple_dict(self): """Return a dict of only the basic data about the release"""
return { 'version': self.version, 'product': self.product, 'channel': self.channel, 'is_public': self.is_public, 'slug': self.slug, 'title': unicode(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 playToneList(self, playList = None): """! \~english Play tone from a tone list @param playList a array of tones \~chinese 播放音调列表 @param playList: 音调数组 \~engl...
if playList == None: return False for t in playList: self.playTone(t["freq"], t["reps"], t["delay"], t["muteDelay"]) self.stopTone() return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def all(self, instance): """Get all ACLs associated with the instance specified by name. :param str instance: The name of the instance from which to fetch ACLs. ...
url = self._url.format(instance=instance) response = requests.get(url, **self._default_request_kwargs) data = self._get_response_data(response) return self._concrete_acl_list(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 create(self, instance, cidr_mask, description, **kwargs): """Create an ACL entry for the specified instance. :param str instance: The name of the instance to...
# Build up request data. url = self._url.format(instance=instance) request_data = { 'cidr_mask': cidr_mask, 'description': description } request_data.update(kwargs) # Call to create an instance. response = requests.post( url, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(self, instance, acl): """Get an ACL by ID belonging to the instance specified by name. :param str instance: The name of the instance from which to fetch ...
base_url = self._url.format(instance=instance) url = '{base}{aclid}/'.format(base=base_url, aclid=acl) response = requests.get(url, **self._default_request_kwargs) data = self._get_response_data(response) return self._concrete_acl(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 delete(self, instance, acl): """Delete an ACL by ID belonging to the instance specified by name. :param str instance: The name of the instance on which the A...
base_url = self._url.format(instance=instance) url = '{base}{aclid}/'.format(base=base_url, aclid=acl) response = requests.delete(url, **self._default_request_kwargs) if response.status_code == 200: logger.info('Successfully deleted ACL {}'.format(acl)) 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 _concrete_acl(self, acl_doc): """Concretize an ACL document. :param dict acl_doc: A document describing an ACL entry. Should come from the API. :returns: An ...
if not isinstance(acl_doc, dict): return None # Attempt to instantiate an Acl object with the given dict. try: return Acl(document=acl_doc, acls=self) # If construction fails, log the exception and return None. except Exception as ex: logger...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _concrete_acl_list(self, acl_docs): """Concretize a list of ACL documents. :param list acl_docs: A list of ACL documents. Should come from the API. :returns:...
if not acl_docs: return [] return list(filter(None, [self._concrete_acl(acl_doc=doc) for doc in acl_docs]))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _default_request_kwargs(self): """The default request keyword arguments to be passed to the requests library."""
defaults = copy.deepcopy(super(Acls, self)._default_request_kwargs) defaults.setdefault('headers', {}).update({ 'X-Auth-Token': self._client.auth._token }) return defaults
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _url(self): """The URL of this ACL object."""
base_url = self._client._url.rstrip('/') return '{}/instances/{}/acls/{}/'.format(base_url, self.instance_name, self.id)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def insert_list_of_dictionaries_into_database_tables( dbConn, log, dictList, dbTableName, uniqueKeyList=[], dateModified=False, dateCreated=True, batchSize=2500, ...
log.debug( 'completed the ````insert_list_of_dictionaries_into_database_tables`` function') global count global totalCount global globalDbConn global sharedList reDate = re.compile('^[0-9]{4}-[0-9]{2}-[0-9]{2}T') if dbSettings: globalDbConn = dbSettings 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 make_directory(path): """ Create directory if that not exists. """
try: makedirs(path) logging.debug('Directory created: {0}'.format(path)) except OSError as e: if e.errno != errno.EEXIST: 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_file(self, from_path, to_path): """ Copy file. """
if not op.exists(op.dirname(to_path)): self.make_directory(op.dirname(to_path)) shutil.copy(from_path, to_path) logging.debug('File copied: {0}'.format(to_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 params(self): """ Read self params from configuration. """
parser = JinjaInterpolationNamespace() parser.read(self.configuration) return dict(parser['params'] 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 scan(cls, path): """ Scan directory for templates. """
result = [] try: for _p in listdir(path): try: result.append(Template(_p, op.join(path, _p))) except ValueError: continue except OSError: pass 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 copy(self): """ Prepare and paste self templates. """
templates = self.prepare_templates() if self.params.interactive: keys = list(self.parser.default) for key in keys: if key.startswith('_'): continue prompt = "{0} (default is \"{1}\")? ".format( key, self.par...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def iterate_templates(self): """ Iterate self starter templates. :returns: A templates generator """
return [t for dd in self.dirs for t in Template.scan(dd)]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def on_canvas_slave__electrode_pair_selected(self, slave, data): ''' Process pair of selected electrodes. For now, this consists of finding the shortest path between the two electrodes and appending it to the list of droplet routes for the current step. Note that the dr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def ping_hub(self): ''' Attempt to ping the ZeroMQ plugin hub to verify connection is alive. If ping is successful, record timestamp. If ping is unsuccessful, call `on_heartbeat_error` method. ''' if self.plugin is not None: try: self.plugin.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 get_string_version(name, default=DEFAULT_STRING_NOT_FOUND, allow_ambiguous=True): """ Get string version from installed package information. It will return :...
# get filename of callar callar = inspect.getouterframes(inspect.currentframe())[1][1] if callar.startswith('<doctest'): # called from doctest, find written script file callar = inspect.getouterframes(inspect.currentframe())[-1][1] # get version info from distribution try: d...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_tuple_version(name, default=DEFAULT_TUPLE_NOT_FOUND, allow_ambiguous=True): """ Get tuple version from installed package information for easy handling. I...
def _prefer_int(x): try: return int(x) except ValueError: return x version = get_string_version(name, default=default, allow_ambiguous=allow_ambiguous) # convert string version to tuple version # prefer integer for easy handling ...
<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_versions(name, default_string=DEFAULT_STRING_NOT_FOUND, default_tuple=DEFAULT_TUPLE_NOT_FOUND, allow_ambiguous=True): """ Get string and tuple versions f...
version_string = get_string_version(name, default_string, allow_ambiguous) version_tuple = get_tuple_version(name, default_tuple, allow_ambiguous) return version_string, version_tuple
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def no_empty_value(func): """Raises an exception if function argument is empty."""
@wraps(func) def wrapper(value): if not value: raise Exception("Empty value not allowed") return func(value) return wrapper
<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_bool(value): """Converts human boolean-like values to Python boolean. Falls back to :class:`bool` when ``value`` is not recognized. :param value: the valu...
cases = { '0': False, 'false': False, 'no': False, '1': True, 'true': True, 'yes': True, } value = value.lower() if isinstance(value, basestring) else value return cases.get(value, bool(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 etree_to_dict(t, trim=True, **kw): u"""Converts an lxml.etree object to Python dict. {'root': None} :param etree.Element t: lxml tree to convert :returns d: ...
d = {t.tag: {} if t.attrib else None} children = list(t) etree_to_dict_w_args = partial(etree_to_dict, trim=trim, **kw) if children: dd = defaultdict(list) d = {t.tag: {}} for dc in map(etree_to_dict_w_args, children): for k, v in dc.iteritems(): # ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dict_to_etree(d, root): u"""Converts a dict to lxml.etree object. :param dict d: dict representing the XML tree :param etree.Element root: XML node which wil...
def _to_etree(d, node): if d is None or len(d) == 0: return elif isinstance(d, basestring): node.text = d elif isinstance(d, dict): for k, v in d.items(): assert isinstance(k, basestring) if k.startswith('#'): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def objwalk(self, obj, path=(), memo=None): """Traverse a dictionary recursively and save path Taken from: http://code.activestate.com/recipes/577982-recursively...
# dual python 2/3 compatability, inspired by the "six" library string_types = (str, unicode) if str is bytes else (str, bytes) iteritems = lambda mapping: getattr(mapping, 'iteritems', mapping.items)() if memo is None: memo = set() iterator = None if isinst...
<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_cache_dir(directory): """Set the directory to cache JSON responses from most API endpoints. """
global cache_dir if directory is None: cache_dir = None return if not os.path.exists(directory): os.makedirs(directory) if not os.path.isdir(directory): raise ValueError("not a directory") cache_dir = directory
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def element_is_empty(elem_to_parse, element_path=None): """ Returns true if the element is None, or has no text, tail, children or attributes. Whitespace in the ...
element = get_element(elem_to_parse, element_path) if element is None: return True is_empty = ( (element.text is None or not element.text.strip()) and (element.tail is None or not element.tail.strip()) and (element.attrib is None or not len(element.attrib)) and (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 insert_element(elem_to_parse, elem_idx, elem_path, elem_txt=u'', **attrib_kwargs): """ Creates an element named after elem_path, containing elem_txt, with kw...
element = get_element(elem_to_parse) if element is None or not elem_path: return None if not elem_idx: elem_idx = 0 if elem_path and XPATH_DELIM in elem_path: tags = elem_path.split(XPATH_DELIM) if element_exists(element, elem_path): # Get the next to l...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_empty_element(parent_to_parse, element_path, target_element=None): """ Searches for all empty sub-elements named after element_name in the parsed elem...
element = get_element(parent_to_parse) removed = [] if element is None or not element_path: return removed if target_element: # Always deal with just the element path if not element_path.endswith(target_element): element_path = XPATH_DELIM.join([element_path, tar...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_element_attributes(elem_to_parse, *args): """ Removes the specified keys from the element's attributes, and returns a dict containing the attributes t...
element = get_element(elem_to_parse) if element is None: return element if len(args): attribs = element.attrib return {key: attribs.pop(key) for key in args if key in attribs} 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 _get_elements_property(parent_to_parse, element_path, prop_name): """ A helper to construct a list of values from """
parent_element = get_element(parent_to_parse) if parent_element is None: return [] if element_path and not element_exists(parent_element, element_path): return [] if not element_path: texts = getattr(parent_element, prop_name) texts = texts.strip() if isinstance(text...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _set_element_property(parent_to_parse, element_path, prop_name, value): """ Assigns the value to the parsed parent element and then returns it """
element = get_element(parent_to_parse) if element is None: return None if element_path and not element_exists(element, element_path): element = insert_element(element, 0, element_path) if not isinstance(value, string_types): value = u'' setattr(element, prop_name, 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 set_elements_tail(parent_to_parse, element_path=None, tail_values=None): """ Assigns an array of tail values to each of the elements parsed from the parent. ...
if tail_values is None: tail_values = [] return _set_elements_property(parent_to_parse, element_path, _ELEM_TAIL, tail_values)
<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_elements_text(parent_to_parse, element_path=None, text_values=None): """ Assigns an array of text values to each of the elements parsed from the parent. ...
if text_values is None: text_values = [] return _set_elements_property(parent_to_parse, element_path, _ELEM_TEXT, text_values)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def strip_namespaces(file_or_xml): """ Removes all namespaces from the XML file or string passed in. If file_or_xml is not a file or string, it is returned as is...
xml_content = _xml_content_to_string(file_or_xml) if not isinstance(xml_content, string_types): return xml_content # This pattern can have overlapping matches, necessitating the loop while _NAMESPACES_FROM_DEC_REGEX.search(xml_content) is not None: xml_content = _NAMESPACES_FROM_DEC_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 strip_xml_declaration(file_or_xml): """ Removes XML declaration line from file or string passed in. If file_or_xml is not a file or string, it is returned as...
xml_content = _xml_content_to_string(file_or_xml) if not isinstance(xml_content, string_types): return xml_content # For Python 2 compliance: replacement string must not specify unicode u'' return _XML_DECLARATION_REGEX.sub(r'', xml_content, 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 floating_point_to_datetime(day, fp_time): """Convert a floating point time to a datetime."""
result = datetime(year=day.year, month=day.month, day=day.day) result += timedelta(minutes=math.ceil(60 * fp_time)) 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 adhan(day, location, parameters, timezone_offset=0): """Calculate adhan times given the parameters. This function will compute the adhan times for a certain ...
latitude, longitude = location # # To reduce a little repetitiveness, using a partial function that has the # day and latitude already set # time_at_sun_angle = partial( compute_time_at_sun_angle, day=day, latitude=latitude ) zuhr_time = compute_zuhr_utc(day, l...
<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_fn_text(self): """Makes filename text"""
if not self._f: text = "(not loaded)" elif self._f.filename: text = os.path.relpath(self._f.filename, ".") else: text = "(filename not set)" return text
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def format_BLB(): """Sets some formatting options in Matplotlib."""
rc("figure", facecolor="white") rc('font', family = 'serif', size=10) #, serif = 'cmr10') rc('xtick', labelsize=10) rc('ytick', labelsize=10) rc('axes', linewidth=1) rc('xtick.major', size=4, width=1) rc('xtick.minor', size=2, width=1) rc('ytick.major', size=4, width=1) rc(...
<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_declared_fields(bases, attrs): """ Find all fields and return them as a dictionary. note:: this function is copied and modified from django.forms.get_dec...
def is_field(prop): return isinstance(prop, forms.Field) or \ isinstance(prop, BaseRepresentation) fields = [(field_name, attrs.pop(field_name)) for field_name, obj in attrs.items() if is_field(obj)] # add fields from base classes: for base in bases[::-1]: if hasattr(base,...
<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(self, data=None): """ Validate the data Check also that no extra properties are present. :raises: ValidationError if the data is not valid. """
errors = {} data = self._getData(data) # validate each field, one by one for name, field in self.fields.items(): try: field.clean(data.get(name)) except ValidationError, e: errors[name] = e.messages except AttributeE...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _getData(self, data): """ Check that data is acceptable and return it. Default behavior is that the data has to be of type `dict`. In derived classes this me...
if not isinstance(data, dict): raise ValidationError( 'data is not a valid dictionary: %s' % (str(type(data)),)) 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 main(): """ Loop over a list of input text strings. Parse each string using a list of parsers, one included in megaparsex and one defined in this script. If ...
for text in [ "how are you", "ip address", "restart", "run command", "rain EGPF", "reverse SSH" ]: print("\nparse text: " + text + "\nWait 3 seconds, then parse.") time.sleep(3) response = megaparsex.multiparse( text ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_packet_id(self, packet): """ Returns the ID of a protocol buffer packet. Returns None if no ID was found. """
for p in self._packets: if isinstance(packet, p['cls']): return p['id'] 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 main(*args): """ Enter point. """
args = args or sys.argv[1:] params = PARSER.parse_args(args) from .log import setup_logging setup_logging(params.level.upper()) from .core import Starter starter = Starter(params) if not starter.params.TEMPLATES or starter.params.list: setup_logging('WARN') for t in sorte...