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 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_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[qsid] dev.data = qspacket # Decode value from QSUSB newqs = _legacy_status(qspacket[QS_VALUE]) if dev.is_dimmer: # Adjust dimmer exponentially to get a smoother effect newqs = min(round(math.pow(newqs, self.dim_adj)), 100) newin = round(newqs * _MAX / 100) if abs(dev.value - newin) > 1: # Significant change _LOGGER.debug("%s qs=%s --> %s", qsid, newqs, newin) dev.value = newin self._cb_value_changed(self, qsid, newin)
<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 GEIST_REPLAY_MODE to 'record' to active record mode."""
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(_file) if hasattr(wrapped, '__objclass__'): file_parts.append(wrapped.__objclass__.__name__) elif hasattr(wrapped, '__self__'): file_parts.append(wrapped.__self__.__class__.__name__) file_parts.append(wrapped.__name__ + '.log') path_parts.append('_'.join(file_parts)) filename = os.path.join(*path_parts) if is_in_record_mode(): platform_backend = get_platform_backend() backend = RecordingBackend( source_backend=platform_backend, recording_filename=filename ) else: backend = PlaybackBackend( recording_filename=filename ) gui = GUI(backend) return wrapped(gui, *args, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _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 in Sampford """
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 : function args : Returns -------- :float Minimum k_agg """
# 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[min_nll_idx]
<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, args=(mu, b), disp=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 _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 to just using the ppf Parameters {0} """
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 are above for i, tq in enumerate(qs[~qs_less]): j = ind + i try: # TODO: Use an adaptable lower bound to increase speed rank[j] = np.abs(np.ceil(optim.brentq(brute_ppf, -1, upper, args=(tq,), xtol=xtol))) except ValueError: # If it is above the upper bound set all remaining values # to the previous value rank[j:] = np.repeat(rank[j - 1], len(rank[j:])) break return rank
<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 values corresponding with vals Returns ------- : tuple (mean, variance) """
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 of the lognormal distribution sigma : float or ndarray Sigma parameter of the lognormal distribution Returns ------- : float or ndarray pdf of x """
# 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 references to each parent in ``left`` and ``right`` attributes. pleo Ruff! gatsby :param left: left object to be joined with right :param right: right object to be joined with left :return: joined object with attrs/methods from both parents available """
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__, (Union,), {}) return joined_class(attrs)
<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_interval=None): """Create HLK-SW16 Client class."""
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.setup() return client
<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] self.logger.debug( 'received date: Year: %s, Month: %s, Day: %s, Hour: %s, ' 'Minute: %s, Sec: %s, Week %s', year, month, day, hour, minute, sec, week) elif raw_packet[1:2] == b'\x0c': states = {} changes = [] for switch in range(0, 16): if raw_packet[2+switch:3+switch] == b'\x01': states[format(switch, 'x')] = True if (self.client.states.get(format(switch, 'x'), None) is not True): changes.append(format(switch, 'x')) self.client.states[format(switch, 'x')] = True elif raw_packet[2+switch:3+switch] == b'\x02': states[format(switch, 'x')] = False if (self.client.states.get(format(switch, 'x'), None) is not False): changes.append(format(switch, 'x')) self.client.states[format(switch, 'x')] = False for switch in changes: for status_cb in self.client.status_callbacks.get(switch, []): status_cb(states[switch]) self.logger.debug(states) if self.client.in_transaction: self.client.in_transaction = False self.client.active_packet = False self.client.active_transaction.set_result(states) while self.client.status_waiters: waiter = self.client.status_waiters.popleft() waiter.set_result(states) if self.client.waiters: self.send_packet() else: self._cmd_timeout.cancel() elif self._cmd_timeout: self._cmd_timeout.cancel() else: self.logger.warning('received unknown packet: %s', binascii.hexlify(raw_packet))
<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.write(packet)
<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.port) try: self.transport, self.protocol = \ await asyncio.wait_for(fut, timeout=self.timeout) except asyncio.TimeoutError: self.logger.warning("Could not connect due to timeout error.") except OSError as exc: self.logger.warning("Could not connect due to error: %s", str(exc)) else: self.is_connected = True if self.reconnect_callback: self.reconnect_callback() break await asyncio.sleep(self.reconnect_interval)
<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: self.protocol.transport.write(self.active_packet) else: packet = self.protocol.format_packet(b"\x1e") self.protocol.transport.write(packet)
<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_packet(b"\x1e") states = await self._send(packet) state = states[switch] else: if self.waiters or self.in_transaction: fut = self.loop.create_future() self.status_waiters.append(fut) state = await fut else: packet = self.protocol.format_packet(b"\x1e") state = await self._send(packet) return state
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _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 current_dir is the git root, this function returns an empty string. Keyword Arguments: <none> Returns: str -- relative path of the current dir to git root dir empty string if current dir is the git root dir """
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 of the file to commit Returns: <nothing> """
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> Returns: <nothing> """
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 dicts -- list of commit if the file is not found, returns an empty list """
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), 'hexsha': commit.hexsha}) 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 read_committed_file(gitref, filename): """Retrieve the content of a file in an old commit and returns it. Ketword Arguments: :gitref: (str) -- full reference of the git commit :filename: (str) -- name (full path) of the file Returns: str -- content of the file """
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 meta-data from a DICOM file and store in a DB. Arguments: :param file_path: File path. :param file_type: File type (should be 'DICOM'). :param is_copy: Indicate if this file is a copy. :param step_id: Step ID :param db_conn: Database connection. :param sid_by_patient: Rarely, a data set might use study IDs which are unique by patient (not for the whole study). E.g.: LREN data. In such a case, you have to enable this flag. This will use PatientID + StudyID as a session ID. :param pid_in_vid: Rarely, a data set might mix patient IDs and visit IDs. E.g. : LREN data. In such a case, you to enable this flag. This will try to split PatientID into VisitID and PatientID. :param visit_in_path: Enable this flag to get the visit ID from the folder hierarchy instead of DICOM meta-data (e.g. can be useful for PPMI). :param rep_in_path: Enable this flag to get the repetition ID from the folder hierarchy instead of DICOM meta-data (e.g. can be useful for PPMI). :return: A dictionary containing the following IDs : participant_id, visit_id, session_id, sequence_type_id, sequence_id, repetition_id, file_id. """
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_path: tags['visit_id'] = _extract_visit_from_path( dcm, file_path, pid_in_vid, sid_by_patient, dataset, tags['participant_id']) else: tags['visit_id'] = _extract_visit(dcm, dataset, tags['participant_id'], sid_by_patient, pid_in_vid) tags['session_id'] = _extract_session(dcm, tags['visit_id']) tags['sequence_type_id'] = _extract_sequence_type(dcm) tags['sequence_id'] = _extract_sequence(tags['session_id'], tags['sequence_type_id']) if rep_in_path: tags['repetition_id'] = _extract_repetition_from_path(dcm, file_path, tags['sequence_id']) else: tags['repetition_id'] = _extract_repetition(dcm, tags['sequence_id']) tags['file_id'] = extract_dicom(file_path, file_type, is_copy, tags['repetition_id'], step_id) except InvalidDicomError: logging.warning("%s is not a DICOM file !" % step_id) except IntegrityError: # TODO: properly deal with concurrency problems logging.warning("A problem occurred with the DB ! A rollback will be performed...") conn.db_session.rollback() return tags
<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()) return packet
<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 will try its best in creating the object. If the resulting object cannot be produced, raises ``ValidationError``. The spec can affect how individual fields will be created by implementing ``clean()`` for the fields needing customization. :param data: the data as a dictionary. :return: instance of ``klass`` or dictionary. :raises: ``ValidationError`` if factory is unable to create object. """
# 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 = self._create_value(data, field_name, self.spec) except ValidationError, e: if field_name not in self.default_create_values: if hasattr(e, 'message_dict'): # prefix error keys with top level field name errors.update(dict(zip( [field_name + '.' + key for key in e.message_dict.keys()], e.message_dict.values()))) else: errors[field_name] = e.messages else: key_name = self.property_name_map[field_name] prototype[key_name] = value # check extra fields if self.prevent_extra_fields: extras = set(data.keys()) - set(self.property_name_map.keys()) if extras: errors[', '.join(extras)] = ['field(s) not allowed'] # if errors, raise ValidationError if errors: raise ValidationError(errors) # return dict or object based on the prototype _data = deepcopy(self.default_create_values) _data.update(prototype) if self.klass: instance = self.klass() instance.__dict__.update(prototype) return instance else: return prototype
<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 ``serialize()`` for the fields needing customization. :returns: dictionary """
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) func = self._get_serialize_func(field_name, self.spec) try: # perform serialization value = func(value, entity, request) if should_we_insert(value, field_spec): ret[field_name] = value except ValidationError, e: if hasattr(e, 'message_dict'): # prefix error keys with top level field name errors.update(dict(zip( [field_name + '.' + key for key in e.message_dict.keys()], e.message_dict.values()))) else: errors[field_name] = e.messages if errors: raise ValidationError(errors) return None if ret == {} else 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 _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 initialized field. :param spec: spec for the whole entity. """
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: 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 _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 version, or None if no such releases exist """
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: return sorted( sorted(releases, reverse=True, key=lambda r: len(r.version.split('.'))), reverse=True, key=lambda r: r.version.split('.')[1])[0]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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, and sorted first by sort_num highest to lowest and then by created date, which is applied to both groups, and then for new features we also sort by tag in the order specified by Note.TAGS, with untagged notes coming first, then finally moving any note with the fixed tag that starts with the release version to the top, for what we call "dot fixes". """
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( sorted( (n for n in notes if not n.is_known_issue_for(self)), key=lambda note: tag_index.get(note.tag, 0)), key=lambda n: n.tag == 'Fixed' and n.note.startswith(self.version), reverse=True) return new_features, known_issues
<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, known_issues = self.notes(public_only=False) for note in known_issues: note.tag = 'Known' data['notes'] = [n.to_dict(self) for n in chain(new_features, known_issues)] 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 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: 音调数组 \~english @note <b>playList</b> format:\n \~chinese @note <b>playList</b> 格式:\n \~ <pre> [ {"freq": 440, "reps": 1, "delay": 0.08, "muteDelay": 0.15}, {"freq": 567, "reps": 3, "delay": 0.08, "muteDelay": 0.15}, ] </pre>\n \~english \e delay: >= 0(s) if 0 means do not delay. tone play will be Stop immediately <br> \e muteDelay: 0.15 >= 0(s) If 0 means no pause after playing, play the next note immediately \~chinese \e delay: >= 0(s)如果是 0 意味着不延迟。 音调会立即停止播放 <br> \e muteDelay: >= 0(s)如果是 0 表示播放音符结束后没有停顿,立刻播放下一个音符 """
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. :returns: A list of :py:class:`Acl` objects associated with the specified instance. :rtype: list """
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 associate the new ACL entry with. :param str cidr_mask: The IPv4 CIDR mask for the new ACL entry. :param str description: A short description for the new ACL entry. :param collector kwargs: (optional) Additional key=value pairs to be supplied to the creation payload. **Caution:** fields unrecognized by the API will cause this request to fail with a 400 from the API. """
# 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, data=json.dumps(request_data), **self._default_request_kwargs ) # Log outcome of instance creation request. if response.status_code == 200: logger.info('Successfully created a new ACL for instance {} with: {}.' .format(instance, request_data)) else: logger.info('Failed to create a new ACL for instance {} with: {}.' .format(instance, request_data)) 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 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 the ACL. :param str acl: The ID of the ACL to fetch. :returns: An :py:class:`Acl` object, or None if ACL does not exist. :rtype: :py:class:`Acl` """
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 ACL exists. :param str acll: The ID of the ACL to delete. """
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: logger.info('Failed to delete ACL {}'.format(acl)) logger.info('Response: [{0}] {1}'.format(response.status_code, response.content)) raise errors.ObjectRocketException('Failed to delete ACL.')
<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 :py:class:`Acl`, or None. :rtype: :py:class:`bases.BaseInstance` """
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.exception(ex) logger.error('Could not instantiate ACL document. You probably need to upgrade to a ' 'recent version of the client. Document which caused this error: {}' .format(acl_doc)) 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 _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: A list of :py:class:`ACL` objects. :rtype: list """
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, replace=False, dbSettings=False): """insert list of dictionaries into database tables **Key Arguments:** - ``dbConn`` -- mysql database connection - ``log`` -- logger - ``dictList`` -- list of python dictionaries to add to the database table - ``dbTableName`` -- name of the database table - ``uniqueKeyList`` -- a list of column names to append as a unique constraint on the database - ``dateModified`` -- add the modification date as a column in the database - ``dateCreated`` -- add the created date as a column in the database - ``batchSize`` -- batch the insert commands into *batchSize* batches - ``replace`` -- repalce row if a duplicate is found - ``dbSettings`` -- pass in the database settings so multiprocessing can establish one connection per process (might not be faster) **Return:** - None **Usage:** .. code-block:: python from fundamentals.mysql import insert_list_of_dictionaries_into_database_tables insert_list_of_dictionaries_into_database_tables( dbConn=dbConn, log=log, dictList=dictList, dbTableName="test_insert_many", uniqueKeyList=["col1", "col3"], dateModified=False, 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: globalDbConn = dbConn if len(dictList) == 0: log.warning( 'the dictionary to be added to the database is empty' % locals()) return None if len(dictList): convert_dictionary_to_mysql_table( dbConn=dbConn, log=log, dictionary=dictList[0], dbTableName=dbTableName, uniqueKeyList=uniqueKeyList, dateModified=dateModified, reDatetime=reDate, replace=replace, dateCreated=dateCreated) dictList = dictList[1:] dbConn.autocommit(False) if len(dictList): total = len(dictList) batches = int(total / batchSize) start = 0 end = 0 sharedList = [] for i in range(batches + 1): end = end + batchSize start = i * batchSize thisBatch = dictList[start:end] sharedList.append((thisBatch, end)) totalCount = total + 1 ltotalCount = totalCount print "Starting to insert %(ltotalCount)s rows into %(dbTableName)s" % locals() print dbSettings if dbSettings == False: fmultiprocess( log=log, function=_insert_single_batch_into_database, inputArray=range(len(sharedList)), dbTableName=dbTableName, uniqueKeyList=uniqueKeyList, dateModified=dateModified, replace=replace, batchSize=batchSize, reDatetime=reDate, dateCreated=dateCreated ) else: fmultiprocess(log=log, function=_add_dictlist_to_database_via_load_in_file, inputArray=range(len(sharedList)), dbTablename=dbTableName, dbSettings=dbSettings, dateModified=dateModified) sys.stdout.write("\x1b[1A\x1b[2K") print "%(ltotalCount)s / %(ltotalCount)s rows inserted into %(dbTableName)s" % locals() log.debug( 'completed the ``insert_list_of_dictionaries_into_database_tables`` function') 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 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.parser.default[key]) if _compat.PY2: value = raw_input(prompt.encode('utf-8')).decode('utf-8') else: value = input(prompt.encode('utf-8')) value = value.strip() if value: self.parser.default[key] = value self.parser.default['templates'] = tt = ','.join( t.name for t in templates) logging.warning("Paste templates: {0}".format(tt)) self.make_directory(self.params.TARGET) logging.debug("\nDefault context:\n----------------") logging.debug( ''.join('{0:<15} {1}\n'.format(*v) for v in self.parser.default.items()) ) return [t.paste( **dict(self.parser.default.items())) for t in templates]
<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 droplet routes for a step are stored in a frame/table in the `DmfDeviceController` step options. .. versionchanged:: 0.11 Clear any temporary routes (drawn while mouse is down) from routes list. .. versionchanged:: 0.11.3 Clear temporary routes by setting ``df_routes`` property of :attr:`canvas_slave`. ''' import networkx as nx source_id = data['source_id'] target_id = data['target_id'] if self.canvas_slave.device is None or self.plugin is None: return # XXX Negative `route_i` corresponds to temporary route being # drawn. Since electrode pair selection terminates route drawing, # clear any rows corresponding to negative `route_i` values from the # routes table. slave.df_routes = slave.df_routes.loc[slave.df_routes.route_i >= 0].copy() try: shortest_path = self.canvas_slave.device.find_path(source_id, target_id) self.plugin.execute_async('droplet_planning_plugin', 'add_route', drop_route=shortest_path) except nx.NetworkXNoPath: logger.error('No path found between %s and %s.', source_id, target_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 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.execute(self.plugin.hub_name, 'ping', timeout_s=1, silent=True) except IOError: self.on_heartbeat_error() else: self.heartbeat_alive_timestamp = datetime.now() logger.debug('Hub connection alive as of %s', self.heartbeat_alive_timestamp) 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 get_string_version(name, default=DEFAULT_STRING_NOT_FOUND, allow_ambiguous=True): """ Get string version from installed package information. It will return :attr:`default` value when the named package is not installed. Parameters name : string An application name used to install via setuptools. default : string A default returning value used when the named application is not installed yet allow_ambiguous : boolean ``True`` for allowing ambiguous version information. Turn this argument to ``False`` if ``get_string_version`` report wrong version. Returns -------- string A version string or not found message (:attr:`default`) Examples -------- True 'Please install this application with setup.py' """
# 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: di = get_distribution(name) installed_directory = os.path.join(di.location, name) if not callar.startswith(installed_directory) and not allow_ambiguous: # not installed, but there is another version that *is* raise DistributionNotFound except DistributionNotFound: return default else: return di.version
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_tuple_version(name, default=DEFAULT_TUPLE_NOT_FOUND, allow_ambiguous=True): """ Get tuple version from installed package information for easy handling. It will return :attr:`default` value when the named package is not installed. Parameters name : string An application name used to install via setuptools. default : tuple A default returning value used when the named application is not installed yet allow_ambiguous : boolean ``True`` for allowing ambiguous version information. Returns -------- string A version tuple Examples -------- True True True True (0, 0, 0) """
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 if isinstance(version, tuple): # not found return version return tuple(map(_prefer_int, version.split('.')))
<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 from installed package information It will return :attr:`default_string` and :attr:`default_tuple` values when the named package is not installed. Parameters name : string An application name used to install via setuptools. default : string A default returning value used when the named application is not installed yet default_tuple : tuple A default returning value used when the named application is not installed yet allow_ambiguous : boolean ``True`` for allowing ambiguous version information. Returns -------- tuple A version string and version tuple Examples -------- True True ('Please install this application with setup.py', (0, 0, 0)) """
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 value to convert :returns: ``True`` if value is truthy, ``False`` otherwise :rtype: bool """
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: a dict representing the lxml tree ``t`` :rtype: dict """
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(): # do not add Comment instance to the key if k is not etree.Comment: dd[k].append(v) d[t.tag] = {k: v[0] if len(v) == 1 else v for k, v in dd.iteritems()} if t.attrib: d[t.tag].update(('@' + k, v) for k, v in t.attrib.iteritems()) if trim and t.text: t.text = t.text.strip() if t.text: if t.tag is etree.Comment and not kw.get('without_comments'): # adds a comments node d['#comments'] = t.text elif children or t.attrib: d[t.tag]['#text'] = t.text else: d[t.tag] = t.text return 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 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 will be assigned the resulting tree :returns: Textual representation of the XML tree :rtype: str """
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('#'): assert k == '#text' assert isinstance(v, basestring) node.text = v elif k.startswith('@'): assert isinstance(v, basestring) node.set(k[1:], v) elif isinstance(v, list): # No matter the child count, their parent will be the same. sub_elem = etree.SubElement(node, k) for child_num, e in enumerate(v): if e is None: if child_num == 0: # Found the first occurrence of an empty child, # skip creating of its XML repr, since it would be # the same as ``sub_element`` higher up. continue # A list with None element means an empty child node # in its parent, thus, recreating tags we have to go # up one level. # <node><child/></child></node> <=> {'node': 'child': [None, None]} _to_etree(node, k) else: # If this isn't first child and it's a complex # value (dict), we need to check if it's value # is equivalent to None. if child_num != 0 and not (isinstance(e, dict) and not all(e.values())): # At least one child was None, we have to create # a new parent-node, which will not be empty. sub_elem = etree.SubElement(node, k) _to_etree(e, sub_elem) else: _to_etree(v, etree.SubElement(node, k)) elif etree.iselement(d): # Supports the case, when we got an empty child and want to recreate it. etree.SubElement(d, node) else: raise AttributeError('Argument is neither dict nor basestring.') _to_etree(d, 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 objwalk(self, obj, path=(), memo=None): """Traverse a dictionary recursively and save path Taken from: http://code.activestate.com/recipes/577982-recursively-walk-python-objects/ """
# 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 isinstance(obj, Mapping): iterator = iteritems elif isinstance(obj, (Sequence, Set)) and not isinstance(obj, string_types): iterator = enumerate if iterator: if id(obj) not in memo: memo.add(id(obj)) for path_component, value in iterator(obj): for result in self.objwalk(value, path + (path_component,), memo): yield result memo.remove(id(obj)) else: yield path, obj
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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 is stripped from text and tail before making the determination. """
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 (not len(element.getchildren())) ) return is_empty
<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 kwargs as attributes, inserts it into elem_to_parse at elem_idx and returns it. If elem_path is an XPATH pointing to a non-existent element, elements not in the path are inserted and the text and index are applied to the last one. If elem_path is an XPATH pointing to an existing element, the new element is inserted as a sibling of the last one in the path at the index specified. """
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 last element in the XPATH parent = get_element(element, XPATH_DELIM.join(tags[:-1])) # Insert the new element as sibling to the last one return insert_element(parent, elem_idx, tags[-1], elem_txt, **attrib_kwargs) else: this_elem = element last_idx = len(tags) - 1 # Iterate over tags from root to leaf for idx, tag in enumerate(tags): next_elem = get_element(this_elem, tag) # Insert missing elements in the path or continue if next_elem is None: # Apply text and index to last element only if idx == last_idx: next_elem = insert_element(this_elem, elem_idx, tag, elem_txt, **attrib_kwargs) else: next_elem = insert_element(this_elem, 0, tag, u'', **attrib_kwargs) this_elem = next_elem return this_elem subelem = Element(elem_path, attrib_kwargs) subelem.text = elem_txt element.insert(elem_idx, subelem) return subelem
<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 element, and if it exists, removes them all and returns them as a list. """
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, target_element]) target_element = None if XPATH_DELIM not in element_path: # Loop over and remove empty sub-elements directly for subelem in get_elements(element, element_path): if element_is_empty(subelem): removed.append(subelem) element.remove(subelem) else: # Parse target element from last node in element path xpath_segments = element_path.split(XPATH_DELIM) element_path = XPATH_DELIM.join(xpath_segments[:-1]) target_element = xpath_segments[-1] # Loop over children and remove empty ones directly for parent in get_elements(element, element_path): for child in get_elements(parent, target_element): if element_is_empty(child): removed.append(child) parent.remove(child) # Parent may be empty now: recursively remove empty elements in XPATH if element_is_empty(parent): if len(xpath_segments) == 2: removed.extend(remove_empty_element(element, xpath_segments[0])) else: next_element_path = XPATH_DELIM.join(xpath_segments[:-2]) next_target_element = parent.tag removed.extend(remove_empty_element(element, next_element_path, next_target_element)) return removed
<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 that have been removed. """
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(texts, string_types) else texts texts = [texts] if texts else [] else: texts = [t for t in ( prop.strip() if isinstance(prop, string_types) else prop for prop in (getattr(node, prop_name) for node in parent_element.findall(element_path)) if prop ) if t] return texts
<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) return element
<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. The tail values are assigned in the same order they are provided. If there are less values then elements, the remaining elements are skipped; but if there are more, new elements will be inserted for each with the remaining tail values. """
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. The text values are assigned in the same order they are provided. If there are less values then elements, the remaining elements are skipped; but if there are more, new elements will be inserted for each with the remaining text values. """
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_REGEX.sub(r'\1', xml_content) # Remove namespaces at the tag level xml_content = _NAMESPACES_FROM_TAG_REGEX.sub(r'\1', xml_content) # Remove namespaces at the attribute level xml_content = _NAMESPACES_FROM_ATTR_REGEX.sub(r'\1\3', xml_content) return xml_content
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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 is. """
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 location on certain day. The method for calculating the prayers as well as the time for Asr can also be specified. The timezone offset naively adds the specified number of hours to each time that is returned. :param day: The datetime.date to calculate for :param location: 2-tuple of floating point coordiantes for latitude and longitude of location in degrees :param parameters: A dictionary-like object of parameters for computing adhan times. Commonly used calculation methods are available in the adhan.methods module :param timezone_offset: The number of hours to add to each prayer time to account for timezones. Can be floating point """
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, longitude) shuruq_time = zuhr_time - time_at_sun_angle(angle=SUNRISE_ANGLE) maghrib_time = zuhr_time + time_at_sun_angle(angle=SUNSET_ANGLE) fajr_time = zuhr_time - time_at_sun_angle(angle=parameters['fajr_angle']) # # Most methods define Isha as a certain angle the sun has to be below # the horizon, but some methods define it as a certain number of minutes # after Maghrib # if parameters.get('isha_delay', None): isha_time = maghrib_time + parameters['isha_delay'] else: isha_time = ( zuhr_time + time_at_sun_angle(angle=parameters['isha_angle']) ) # # Default to standard Asr method if not specified # asr_multiplier = parameters.get('asr_multiplier', ASR_STANDARD) asr_time = zuhr_time + time_at_shadow_length( day=day, latitude=latitude, multiplier=asr_multiplier ) offset = timedelta(minutes=60 * timezone_offset) return { 'fajr': floating_point_to_datetime(day, fajr_time) + offset, 'zuhr': floating_point_to_datetime(day, zuhr_time) + offset, 'shuruq': floating_point_to_datetime(day, shuruq_time) + offset, 'asr': floating_point_to_datetime(day, asr_time) + offset, 'maghrib': floating_point_to_datetime(day, maghrib_time) + offset, 'isha': floating_point_to_datetime(day, isha_time) + offset, }
<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('ytick.minor', size=2, width=1)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_declared_fields(bases, attrs): """ Find all fields and return them as a dictionary. note:: this function is copied and modified from django.forms.get_declared_fields """
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, 'base_fields'): fields = base.base_fields.items() + fields return dict(fields)
<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 AttributeError, e: raise ValidationError('data should be of type dict but is %s' % (type(data),)) # check for extra fields extras = set(data.keys()) - set(self.fields.keys()) if extras: errors[', '.join(extras)] = ['field(s) not allowed'] # if errors, raise ValidationError if errors: raise ValidationError(errors)
<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 method could for example allow `None` or empty strings and just return empty dictionary. :raises: ``ValidationError`` if data is missing or wrong type :return: the data to be validated """
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 a confirmation is requested, seek confirmation, otherwise display any response text and engage any triggered functions. """
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 = text, parsers = [ megaparsex.parse, parse_networking ], help_message = "Does not compute. I can report my IP address and I " "can restart my script." ) if type(response) is megaparsex.confirmation: while response.confirmed() is None: response.test( text = megaparsex.get_input( prompt = response.prompt() + " " ) ) if response.confirmed(): print(response.feedback()) response.run() else: print(response.feedback()) elif type(response) is megaparsex.command: output = response.engage_command( command = megaparsex.get_input( prompt = response.prompt() + " " ), background = False ) if output: print("output:\n{output}".format(output = output)) else: print(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 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 sorted(starter.iterate_templates()): logging.warn("%s -- %s", t.name, t.params.get( 'description', 'no description')) return True try: starter.copy() except Exception as e: # noqa logging.error(e) sys.exit(1)