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 read_packets(self): """Read packets from the socket and parse them"""
while self.running: packet_length = self.client.recv(2) if len(packet_length) < 2: self.stop() continue packet_length = struct.unpack("<h", packet_length)[0] - 2 data = self.client.recv(packet_length) packno = data[0] try: parser = "Packet" + format(packno, 'x').upper() + "Parser" packet_class = getattr(packets, parser) packet_class().parse(self.world, self.player, data, self._evman) except AttributeError as e: pass if packno == 2: self.stop() continue
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_packets(self): """Write packets from the queue"""
while self.running: if len(self.write_queue) > 0: self.write_queue[0].send(self.client) self.write_queue.pop(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 start(self): """Open sockets to the server and start threads"""
if not self.writeThread.isAlive() and not self.readThread.isAlive(): self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.client.connect(self.ADDR) self.running = True self.writeThread.start() self.readThread.start()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_param(self, name: str, v) -> None: """Add or update an existing parameter."""
self.params[zlib.crc32(name.encode())] = v
<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_object(self, name: str, pobj: ParameterObject) -> None: """Add or update an existing object."""
self.objects[zlib.crc32(name.encode())] = pobj
<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_list(self, name: str, plist) -> None: """Add or update an existing list."""
self.lists[zlib.crc32(name.encode())] = plist
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def queue_setup(filename, mode, batch_size, num_readers, min_examples): """ Sets up the queue runners for data input """
filename_queue = tf.train.string_input_producer([filename], shuffle=True, capacity=16) if mode == "train": examples_queue = tf.RandomShuffleQueue(capacity=min_examples + 3 * batch_size, min_after_dequeue=min_examples, dtypes=[tf.string]) else: examples_queue = tf.FIFOQueue(capacity=min_examples + 3 * batch_size, dtypes=[tf.string]) enqueue_ops = list() for _ in range(num_readers): reader = tf.TFRecordReader() _, value = reader.read(filename_queue) enqueue_ops.append(examples_queue.enqueue([value])) tf.train.queue_runner.add_queue_runner(tf.train.queue_runner.QueueRunner(examples_queue, enqueue_ops)) example_serialized = examples_queue.dequeue() return example_serialized
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def thread_setup(read_and_decode_fn, example_serialized, num_threads): """ Sets up the threads within each reader """
decoded_data = list() for _ in range(num_threads): decoded_data.append(read_and_decode_fn(example_serialized)) return decoded_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 init_threads(tf_session): """ Starts threads running """
coord = tf.train.Coordinator() threads = list() for qr in tf.get_collection(tf.GraphKeys.QUEUE_RUNNERS): threads.extend(qr.create_threads(tf_session, coord=coord, daemon=True, start=True)) return threads, coord
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_config_yaml(self, flags, config_dict): """ Load config dict and yaml dict and then override both with flags dict. """
if config_dict is None: print('Config File not specified. Using only input flags.') return flags try: config_yaml_dict = self.cfg_from_file(flags['YAML_FILE'], config_dict) except KeyError: print('Yaml File not specified. Using only input flags and config file.') return config_dict print('Using input flags, config file, and yaml file.') config_yaml_flags_dict = self._merge_a_into_b_simple(flags, config_yaml_dict) return config_yaml_flags_dict
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_dict_keys(self, config_yaml_flags_dict): """ Fill in all optional keys with None. Exit in a crucial key is not defined. """
crucial_keys = ['MODEL_DIRECTORY', 'SAVE_DIRECTORY'] for key in crucial_keys: if key not in config_yaml_flags_dict: print('You must define %s. Now exiting...' % key) exit() optional_keys = ['RESTORE_SLIM_FILE', 'RESTORE_META', 'RESTORE_SLIM', 'SEED', 'GPU'] for key in optional_keys: if key not in config_yaml_flags_dict: config_yaml_flags_dict[key] = None print('%s in flags, yaml or config dictionary was not found.' % key) if 'RUN_NUM' not in config_yaml_flags_dict: config_yaml_flags_dict['RUN_NUM'] = 0 if 'NUM_EPOCHS' not in config_yaml_flags_dict: config_yaml_flags_dict['NUM_EPOCHS'] = 1 return config_yaml_flags_dict
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _check_file_io(self): """ Create and define logging directory """
folder = 'Model' + str(self.flags['RUN_NUM']) + '/' folder_restore = 'Model' + str(self.flags['MODEL_RESTORE']) + '/' self.flags['RESTORE_DIRECTORY'] = self.flags['SAVE_DIRECTORY'] + self.flags[ 'MODEL_DIRECTORY'] + folder_restore self.flags['LOGGING_DIRECTORY'] = self.flags['SAVE_DIRECTORY'] + self.flags[ 'MODEL_DIRECTORY'] + folder self.make_directory(self.flags['LOGGING_DIRECTORY']) sys.stdout = Logger(self.flags['LOGGING_DIRECTORY'] + 'ModelInformation.log') print(self.flags)
<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_tf_functions(self): """ Sets up summary writer, saver, and session, with configurable gpu visibility """
merged = tf.summary.merge_all() saver = tf.train.Saver() if type(self.flags['GPU']) is int: os.environ["CUDA_VISIBLE_DEVICES"] = str(self.flags['GPU']) print('Using GPU %d' % self.flags['GPU']) gpu_options = tf.GPUOptions(allow_growth=True) config = tf.ConfigProto(log_device_placement=False, gpu_options=gpu_options) sess = tf.Session(config=config) writer = tf.summary.FileWriter(self.flags['LOGGING_DIRECTORY'], sess.graph) return merged, saver, sess, writer
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _restore_meta(self): """ Restore from meta file. 'RESTORE_META_FILE' is expected to have .meta at the end. """
restore_meta_file = self._get_restore_meta_file() filename = self.flags['RESTORE_DIRECTORY'] + self._get_restore_meta_file() new_saver = tf.train.import_meta_graph(filename) new_saver.restore(self.sess, filename[:-5]) print("Model restored from %s" % restore_meta_file)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _initialize_model(self): """ Initialize the defined network and restore from files is so specified. """
# Initialize all variables first self.sess.run(tf.local_variables_initializer()) self.sess.run(tf.global_variables_initializer()) if self.flags['RESTORE_META'] == 1: print('Restoring from .meta file') self._restore_meta() elif self.flags['RESTORE_SLIM'] == 1: print('Restoring TF-Slim Model.') all_model_variables = tf.global_variables() self._restore_slim(all_model_variables) else: print("Model training from scratch.")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _init_uninit_vars(self): """ Initialize all other trainable variables, i.e. those which are uninitialized """
uninit_vars = self.sess.run(tf.report_uninitialized_variables()) vars_list = list() for v in uninit_vars: var = v.decode("utf-8") vars_list.append(var) uninit_vars_tf = [v for v in tf.global_variables() if v.name.split(':')[0] in vars_list] self.sess.run(tf.variables_initializer(var_list=uninit_vars_tf))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _save_model(self, section): """ Save model in the logging directory """
checkpoint_name = self.flags['LOGGING_DIRECTORY'] + 'part_%d' % section + '.ckpt' save_path = self.saver.save(self.sess, checkpoint_name) print("Model saved in file: %s" % save_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 _record_training_step(self, summary): """ Adds summary to writer and increments the step. """
self.writer.add_summary(summary=summary, global_step=self.step) self.step += 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 _set_seed(self): """ Set random seed for numpy and tensorflow packages """
if self.flags['SEED'] is not None: tf.set_random_seed(self.flags['SEED']) np.random.seed(self.flags['SEED'])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _summaries(self): """ Print out summaries for every variable. Can be overriden in main function. """
for var in tf.trainable_variables(): tf.summary.histogram(var.name, var) print(var.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 check_str(obj): """ Returns a string for various input types """
if isinstance(obj, str): return obj if isinstance(obj, float): return str(int(obj)) else: return str(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 name_in_checkpoint(var): """ Removes 'model' scoping if it is present in order to properly restore weights. """
if var.op.name.startswith('model/'): return var.op.name[len('model/'):]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _merge_a_into_b(self, a, b): """Merge config dictionary a into config dictionary b, clobbering the options in b whenever they are also specified in a. """
from easydict import EasyDict as edict if type(a) is not edict: return for k, v in a.items(): # a must specify keys that are in b if k not in b: raise KeyError('{} is not a valid config key'.format(k)) # the types must match, too old_type = type(b[k]) if old_type is not type(v): if isinstance(b[k], np.ndarray): v = np.array(v, dtype=b[k].dtype) else: raise ValueError(('Type mismatch ({} vs. {}) ' 'for config key: {}').format(type(b[k]), type(v), k)) # recursively merge dicts if type(v) is edict: try: self._merge_a_into_b(a[k], b[k]) except: print('Error under config key: {}'.format(k)) raise else: b[k] = v return b
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _merge_a_into_b_simple(self, a, b): """Merge config dictionary a into config dictionary b, clobbering the options in b whenever they are also specified in a. Do not do any checking. """
for k, v in a.items(): b[k] = v return b
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cfg_from_file(self, yaml_filename, config_dict): """Load a config file and merge it into the default options."""
import yaml from easydict import EasyDict as edict with open(yaml_filename, 'r') as f: yaml_cfg = edict(yaml.load(f)) return self._merge_a_into_b(yaml_cfg, config_dict)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def xor(s, pad): '''XOR a given string ``s`` with the one-time-pad ``pad``''' from itertools import cycle s = bytearray(force_bytes(s, encoding='latin-1')) pad = bytearray(force_bytes(pad, encoding='latin-1')) return binary_type(bytearray(x ^ y for x, y in zip(s, cycle(pad))))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def encrypt_message(data_to_encrypt, enc_alg, encryption_cert): """Function encrypts data and returns the generated ASN.1 :param data_to_encrypt: A byte string of the data to be encrypted :param enc_alg: The algorithm to be used for encrypting the data :param encryption_cert: The certificate to be used for encrypting the data :return: A CMS ASN.1 byte string of the encrypted data. """
enc_alg_list = enc_alg.split('_') cipher, key_length, mode = enc_alg_list[0], enc_alg_list[1], enc_alg_list[2] enc_alg_asn1, key, encrypted_content = None, None, None # Generate the symmetric encryption key and encrypt the message if cipher == 'tripledes': key = util.rand_bytes(int(key_length)//8) iv, encrypted_content = symmetric.tripledes_cbc_pkcs5_encrypt( key, data_to_encrypt, None) enc_alg_asn1 = algos.EncryptionAlgorithm({ 'algorithm': algos.EncryptionAlgorithmId('tripledes_3key'), 'parameters': cms.OctetString(iv) }) # Encrypt the key and build the ASN.1 message encrypted_key = asymmetric.rsa_pkcs1v15_encrypt(encryption_cert, key) return cms.ContentInfo({ 'content_type': cms.ContentType('enveloped_data'), 'content': cms.EnvelopedData({ 'version': cms.CMSVersion('v0'), 'recipient_infos': [ cms.KeyTransRecipientInfo({ 'version': cms.CMSVersion('v0'), 'rid': cms.RecipientIdentifier({ 'issuer_and_serial_number': cms.IssuerAndSerialNumber({ 'issuer': encryption_cert.asn1[ 'tbs_certificate']['issuer'], 'serial_number': encryption_cert.asn1[ 'tbs_certificate']['serial_number'] }) }), 'key_encryption_algorithm': cms.KeyEncryptionAlgorithm({ 'algorithm': cms.KeyEncryptionAlgorithmId('rsa') }), 'encrypted_key': cms.OctetString(encrypted_key) }) ], 'encrypted_content_info': cms.EncryptedContentInfo({ 'content_type': cms.ContentType('data'), 'content_encryption_algorithm': enc_alg_asn1, 'encrypted_content': encrypted_content }) }) }).dump()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_key(key_str, key_pass): """ Function to load password protected key file in p12 or pem format"""
try: # First try to parse as a p12 file key, cert, _ = asymmetric.load_pkcs12(key_str, key_pass) except ValueError as e: # If it fails due to invalid password raise error here if e.args[0] == 'Password provided is invalid': raise AS2Exception('Password not valid for Private Key.') # if not try to parse as a pem file key, cert = None, None for kc in split_pem(key_str): try: cert = asymmetric.load_certificate(kc) except (ValueError, TypeError): try: key = asymmetric.load_private_key(kc, key_pass) except OSError: raise AS2Exception( 'Invalid Private Key or password is not correct.') if not key or not cert: raise AS2Exception( 'Invalid Private key file or Public key not included.') return key, cert
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def content(self): """Function returns the body of the as2 payload as a bytes object"""
if not self.payload: return '' if self.payload.is_multipart(): message_bytes = mime_to_bytes( self.payload, 0).replace(b'\n', b'\r\n') boundary = b'--' + self.payload.get_boundary().encode('utf-8') temp = message_bytes.split(boundary) temp.pop(0) return boundary + boundary.join(temp) else: content = self.payload.get_payload() if isinstance(content, str_cls): content = content.encode('utf-8') return content
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def content(self): """Function returns the body of the mdn message as a byte string"""
if self.payload: message_bytes = mime_to_bytes( self.payload, 0).replace(b'\n', b'\r\n') boundary = b'--' + self.payload.get_boundary().encode('utf-8') temp = message_bytes.split(boundary) temp.pop(0) return boundary + boundary.join(temp) 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 parse(self, raw_content, find_message_cb): """Function parses the RAW AS2 MDN, verifies it and extracts the processing status of the orginal AS2 message. :param raw_content: A byte string of the received HTTP headers followed by the body. :param find_message_cb: A callback the must returns the original Message Object. The original message-id and original recipient AS2 ID are passed as arguments to it. :returns: A two element tuple containing (status, detailed_status). The status is a string indicating the status of the transaction. The optional detailed_status gives additional information about the processing status. """
status, detailed_status = None, None self.payload = parse_mime(raw_content) self.orig_message_id, orig_recipient = self.detect_mdn() # Call the find message callback which should return a Message instance orig_message = find_message_cb(self.orig_message_id, orig_recipient) # Extract the headers and save it mdn_headers = {} for k, v in self.payload.items(): k = k.lower() if k == 'message-id': self.message_id = v.lstrip('<').rstrip('>') mdn_headers[k] = v if orig_message.receiver.mdn_digest_alg \ and self.payload.get_content_type() != 'multipart/signed': status = 'failed/Failure' detailed_status = 'Expected signed MDN but unsigned MDN returned' return status, detailed_status if self.payload.get_content_type() == 'multipart/signed': signature = None message_boundary = ( '--' + self.payload.get_boundary()).encode('utf-8') for part in self.payload.walk(): if part.get_content_type() == 'application/pkcs7-signature': signature = part.get_payload(decode=True) elif part.get_content_type() == 'multipart/report': self.payload = part # Verify the message, first using raw message and if it fails # then convert to canonical form and try again mic_content = extract_first_part(raw_content, message_boundary) verify_cert = orig_message.receiver.load_verify_cert() try: self.digest_alg = verify_message( mic_content, signature, verify_cert) except IntegrityError: mic_content = canonicalize(self.payload) self.digest_alg = verify_message( mic_content, signature, verify_cert) for part in self.payload.walk(): if part.get_content_type() == 'message/disposition-notification': # logger.debug('Found MDN report for message %s:\n%s' % ( # orig_message.message_id, part.as_string())) mdn = part.get_payload()[-1] mdn_status = mdn['Disposition'].split( ';').pop().strip().split(':') status = mdn_status[0] if status == 'processed': mdn_mic = mdn.get('Received-Content-MIC', '').split(',')[0] # TODO: Check MIC for all cases if mdn_mic and orig_message.mic \ and mdn_mic != orig_message.mic.decode(): status = 'processed/warning' detailed_status = 'Message Integrity check failed.' else: detailed_status = ' '.join(mdn_status[1:]).strip() return status, detailed_status
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def detect_mdn(self): """ Function checks if the received raw message is an AS2 MDN or not. :raises MDNNotFound: If the received payload is not an MDN then this exception is raised. :return: A two element tuple containing (message_id, message_recipient). The message_id is the original AS2 message id and the message_recipient is the original AS2 message recipient. """
mdn_message = None if self.payload.get_content_type() == 'multipart/report': mdn_message = self.payload elif self.payload.get_content_type() == 'multipart/signed': for part in self.payload.walk(): if part.get_content_type() == 'multipart/report': mdn_message = self.payload if not mdn_message: raise MDNNotFound('No MDN found in the received message') message_id, message_recipient = None, None for part in mdn_message.walk(): if part.get_content_type() == 'message/disposition-notification': mdn = part.get_payload()[0] message_id = mdn.get('Original-Message-ID').strip('<>') message_recipient = mdn.get( 'Original-Recipient').split(';')[1].strip() return message_id, message_recipient
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init_app(self, app): """Setup the logging handlers, level and formatters. Level (DEBUG, INFO, CRITICAL, etc) is determined by the app.config['FLASK_LOG_LEVEL'] setting, and defaults to ``None``/``logging.NOTSET``. """
config_log_level = app.config.get('FLASK_LOG_LEVEL', None) # Set up format for default logging hostname = platform.node().split('.')[0] formatter = ( '[%(asctime)s] %(levelname)s %(process)d [%(name)s] ' '%(filename)s:%(lineno)d - ' '[{hostname}] - %(message)s' ).format(hostname=hostname) config_log_int = None set_level = None if config_log_level: config_log_int = getattr(logging, config_log_level.upper(), None) if not isinstance(config_log_int, int): raise ValueError( 'Invalid log level: {0}'.format(config_log_level) ) set_level = config_log_int # Set to NotSet if we still aren't set yet if not set_level: set_level = config_log_int = logging.NOTSET self.log_level = set_level # Setup basic StreamHandler logging with format and level (do # setup in case we are main, or change root logger if we aren't. logging.basicConfig(format=formatter) root_logger = logging.getLogger() root_logger.setLevel(set_level) # Get everything ready to setup the syslog handlers address = None if os.path.exists('/dev/log'): address = '/dev/log' elif os.path.exists('/var/run/syslog'): address = '/var/run/syslog' else: address = ('127.0.0.1', 514) # Add syslog handler before adding formatters root_logger.addHandler( SysLogHandler(address=address, facility=SysLogHandler.LOG_LOCAL0) ) self.set_formatter(formatter) return config_log_int
<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_formatter(log_formatter): """Override the default log formatter with your own."""
# Add our formatter to all the handlers root_logger = logging.getLogger() for handler in root_logger.handlers: handler.setFormatter(logging.Formatter(log_formatter))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def api_request(path, **kwargs): """Make an API request to the Hub to reduce boilerplate repetition. """
url = url_path_join(os.environ['JUPYTERHUB_API_URL'], path) client = AsyncHTTPClient() headers = { 'Authorization': 'token %s' % os.environ['JUPYTERHUB_API_TOKEN'], } if kwargs.get('method') == 'POST': kwargs.setdefault('body', '') req = HTTPRequest(url, headers=headers, **kwargs) return client.fetch(req)
<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 delete_user(name): """Stop a user's server and delete the user"""
app_log.info("Deleting user %s", name) await api_request('users/{}/server'.format(name), method='DELETE') await api_request('users/{}'.format(name), method='DELETE')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dense_to_one_hot(labels_dense, num_classes): """Convert class labels from scalars to one-hot vectors."""
num_labels = labels_dense.shape[0] index_offset = np.arange(num_labels) * num_classes labels_one_hot = np.zeros((num_labels, num_classes)) labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1 return labels_one_hot
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _render_iteratable(iteratable, level): """Renders iteratable sequence of HTML elements."""
if isinstance(iteratable, basestring): return unicode(iteratable) return ''.join([render(element, level) for element in iteratable])
<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_attributes(attributes): """Serializes HTML element attributes in a name="value" pair form."""
result = '' for name, value in attributes.items(): if not value: continue result += ' ' + _unmangle_attribute_name(name) result += '="' + escape(value, True) + '"' 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 _unmangle_attribute_name(name): """Unmangles attribute names so that correct Python variable names are used for mapping attribute names."""
# Python keywords cannot be used as variable names, an underscore should # be appended at the end of each of them when defining attribute names. name = _PYTHON_KEYWORD_MAP.get(name, name) # Attribute names are mangled with double underscore, as colon cannot # be used as a variable character symbol in Python. Single underscore is # used for substituting dash. name = name.replace('__', ':').replace('_', '-') return 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 escape(string, quote=False): """Standard HTML text escaping, but protecting against the agressive behavior of Jinja 2 `Markup` and the like. """
if string is None: return '' elif hasattr(string, '__html__'): return unicode(string) string = string.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;') if quote: string = string.replace('"', "&quot;") return string
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def root_block(template_name=DEFAULT_TEMPLATE_NAME): """A decorator that is used to define that the decorated block function will be at the root of the block template hierarchy. In the usual case this will be the HTML skeleton of the document, unless the template is used to serve partial HTML rendering for Ajax. The :func:`root_block` decorator accepts the following arguments: :param template_name: The name of the block template hierarchy which is passed to the :func:`render_template` document rendering function. Different templates are useful for rendering documents with differing layouts (e.g. admin back-end vs. site front-end), or for partial HTML rendering for Ajax. """
def decorator(block_func): block = RootBlock(block_func, template_name) return block_func return decorator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def block(context_name, parent_block_func, view_func=None): """A decorator that is used for inserting the decorated block function in the block template hierarchy. The :func:`block` decorator accepts the following arguments: :param context_name: key in the `g.blocks` dictionary in which the result of the decorated block function will be stored for further processing by the parent block function `parent_block_func`. :param parent_block_func: parent block function in the template hierarchy which will use the stored result. :param view_func: the decorated block will take an effect only in the execution context of the specified view function. If the default value of `None` is used, then the block will be used as default for the specified `context_name`. Internally this parameter is converted to a Werkzeug endpoint in the same way Flask is doing that with the `Flask.route` decorator. """
def decorator(block_func): block = Block(block_func, view_func) parent_block = Block.block_mapping[parent_block_func] parent_block.append_context_block(context_name, block) return block_func return decorator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def entropy_bits( lst: Union[ List[Union[int, str, float, complex]], Tuple[Union[int, str, float, complex]] ] ) -> float: """Calculate the number of entropy bits in a list or tuple of elements."""
# Based on https://stackoverflow.com/a/45091961 if not isinstance(lst, (list, tuple)): raise TypeError('lst must be a list or a tuple') for num in lst: if not isinstance(num, (int, str, float, complex)): raise TypeError('lst can only be comprised of int, str, float, ' 'complex') n_lst = len(lst) if n_lst <= 1: return 0.0 # Some NumPy replacements counts = [lst.count(x) for x in lst] probs = [c / n_lst for c in counts] # Compute entropy entropy = 0.0 for prob in probs: entropy -= prob * log2(prob) return entropy
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def entropy_bits_nrange( minimum: Union[int, float], maximum: Union[int, float] ) -> float: """Calculate the number of entropy bits in a range of numbers."""
# Shannon: # d = fabs(maximum - minimum) # ent = -(1/d) * log(1/d, 2) * d # Aprox form: log10(digits) * log2(10) if not isinstance(minimum, (int, float)): raise TypeError('minimum can only be int or float') if not isinstance(maximum, (int, float)): raise TypeError('maximum can only be int or float') if minimum < 0: raise ValueError('minimum should be greater than 0') if maximum < 0: raise ValueError('maximum should be greater than 0') dif = fabs(maximum - minimum) if dif == 0: return 0.0 ent = log10(dif) * 3.321928 return ent
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def password_length_needed(entropybits: Union[int, float], chars: str) -> int: """Calculate the length of a password for a given entropy and chars."""
if not isinstance(entropybits, (int, float)): raise TypeError('entropybits can only be int or float') if entropybits < 0: raise ValueError('entropybits should be greater than 0') if not isinstance(chars, str): raise TypeError('chars can only be string') if not chars: raise ValueError("chars can't be null") # entropy_bits(list(characters)) = 6.554588 entropy_c = entropy_bits(list(chars)) return ceil(entropybits / entropy_c)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def words_amount_needed(entropybits: Union[int, float], entropy_w: Union[int, float], entropy_n: Union[int, float], amount_n: int) -> int: """Calculate words needed for a passphrase based on entropy."""
# Thanks to @julianor for this tip to calculate default amount of # entropy: minbitlen/log2(len(wordlist)). # I set the minimum entropy bits and calculate the amount of words # needed, cosidering the entropy of the wordlist. # Then: entropy_w * amount_w + entropy_n * amount_n >= ENTROPY_BITS_MIN if not isinstance(entropybits, (int, float)): raise TypeError('entropybits can only be int or float') if not isinstance(entropy_w, (int, float)): raise TypeError('entropy_w can only be int or float') if not isinstance(entropy_n, (int, float)): raise TypeError('entropy_n can only be int or float') if not isinstance(amount_n, int): raise TypeError('amount_n can only be int') if entropybits < 0: raise ValueError('entropybits should be greater than 0') if entropy_w <= 0: raise ValueError('entropy_w should be greater than 0') if entropy_n < 0: raise ValueError('entropy_n should be greater than 0') if amount_n < 0: raise ValueError('amount_n should be greater than 0') amount_w = (entropybits - entropy_n * amount_n) / entropy_w if amount_w > -1.0: return ceil(fabs(amount_w)) return 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 password_entropy(length: int, chars: str) -> float: """Calculate the entropy of a password with given length and chars."""
if not isinstance(length, int): raise TypeError('length can only be int') if length < 0: raise ValueError('length should be greater than 0') if not isinstance(chars, str): raise TypeError('chars can only be string') if not chars: raise ValueError("chars can't be null") if length == 0: return 0.0 entropy_c = entropy_bits(list(chars)) return float(length * entropy_c)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def passphrase_entropy(amount_w: int, entropy_w: Union[int, float], entropy_n: Union[int, float], amount_n: int) -> float: """Calculate the entropy of a passphrase with given words and numbers."""
if not isinstance(amount_w, int): raise TypeError('amount_w can only be int') if not isinstance(entropy_w, (int, float)): raise TypeError('entropy_w can only be int or float') if not isinstance(entropy_n, (int, float)): raise TypeError('entropy_n can only be int or float') if not isinstance(amount_n, int): raise TypeError('amount_n can only be int') if amount_w < 0: raise ValueError('amount_w should be greater than 0') if entropy_w < 0: raise ValueError('entropy_w should be greater than 0') if entropy_n < 0: raise ValueError('entropy_n should be greater than 0') if amount_n < 0: raise ValueError('amount_n should be greater than 0') return float(amount_w * entropy_w + amount_n * entropy_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 entropy_bits( lst: Union[ List[Union[int, str, float, complex]], Tuple[Union[int, str, float, complex]] ] ) -> float: """Calculate the entropy of a wordlist or a numerical range. Keyword arguments: lst -- A wordlist as list or tuple, or a numerical range as a list: (minimum, maximum) """
if not isinstance(lst, (tuple, list)): raise TypeError('lst must be a list or a tuple') size = len(lst) if ( size == 2 and isinstance(lst[0], (int, float)) and isinstance(lst[1], (int, float)) ): return calc_entropy_bits_nrange(lst[0], lst[1]) return calc_entropy_bits(lst)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def import_words_from_file(self, inputfile: str, is_diceware: bool) -> None: """Import words for the wordlist from a given file. The file can have a single column with words or be diceware-like (two columns). Keyword arguments: inputfile -- A string with the path to the wordlist file to load, or the value 'internal' to load the internal one. is_diceware -- True if the file is diceware-like. """
if not Aux.isfile_notempty(inputfile): raise FileNotFoundError('Input file does not exists, is not valid ' 'or is empty: {}'.format(inputfile)) self._wordlist_entropy_bits = None if is_diceware: self._wordlist = self._read_words_from_diceware(inputfile) else: self._wordlist = self._read_words_from_wordfile(inputfile)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def password_length_needed(self) -> int: """Calculate the needed password length to satisfy the entropy number. This is for the given character set. """
characters = self._get_password_characters() if ( self.entropy_bits_req is None or not characters ): raise ValueError("Can't calculate the password length needed: " "entropy_bits_req isn't set or the character " "set is empty") return calc_password_length_needed( self.entropy_bits_req, characters )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def words_amount_needed(self) -> int: """Calculate the needed amount of words to satisfy the entropy number. This is for the given wordlist. """
if ( self.entropy_bits_req is None or self.amount_n is None or not self.wordlist ): raise ValueError("Can't calculate the words amount needed: " "wordlist is empty or entropy_bits_req or " "amount_n isn't set") # Thanks to @julianor for this tip to calculate default amount of # entropy: minbitlen/log2(len(wordlist)). # I set the minimum entropy bits and calculate the amount of words # needed, cosidering the entropy of the wordlist. # Then: entropy_w * amount_w + entropy_n * amount_n >= ENTROPY_BITS_MIN entropy_n = self.entropy_bits((self.randnum_min, self.randnum_max)) # The entropy for EFF Large Wordlist is ~12.9, no need to calculate entropy_w = self._wordlist_entropy_bits \ if self._wordlist_entropy_bits \ else self.entropy_bits(self.wordlist) return calc_words_amount_needed( self.entropy_bits_req, entropy_w, entropy_n, self.amount_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 generated_password_entropy(self) -> float: """Calculate the entropy of a password that would be generated."""
characters = self._get_password_characters() if ( self.passwordlen is None or not characters ): raise ValueError("Can't calculate the password entropy: character" " set is empty or passwordlen isn't set") if self.passwordlen == 0: return 0.0 return calc_password_entropy(self.passwordlen, characters)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generated_passphrase_entropy(self) -> float: """Calculate the entropy of a passphrase that would be generated."""
if ( self.amount_w is None or self.amount_n is None or not self.wordlist ): raise ValueError("Can't calculate the passphrase entropy: " "wordlist is empty or amount_n or " "amount_w isn't set") if self.amount_n == 0 and self.amount_w == 0: return 0.0 entropy_n = self.entropy_bits((self.randnum_min, self.randnum_max)) # The entropy for EFF Large Wordlist is ~12.9, no need to calculate entropy_w = self._wordlist_entropy_bits \ if self._wordlist_entropy_bits \ else self.entropy_bits(self.wordlist) return calc_passphrase_entropy( self.amount_w, entropy_w, entropy_n, self.amount_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 generate(self, uppercase: int = None) -> list: """Generate a list of words randomly chosen from a wordlist. Keyword arguments: uppercase -- An integer number indicating how many uppercase characters are wanted: bigger than zero means that many characters and lower than zero means all uppercase except that many. Use 0 to make them all uppercase, and None for no one. """
if ( self.amount_n is None or self.amount_w is None or not self.wordlist ): raise ValueError("Can't generate passphrase: " "wordlist is empty or amount_n or " "amount_w isn't set") if uppercase is not None and not isinstance(uppercase, int): raise TypeError('uppercase must be an integer number') passphrase = [] for _ in range(0, self.amount_w): passphrase.append(randchoice(self.wordlist).lower()) # Handle uppercase lowercase = Aux.lowercase_count(passphrase) if passphrase and uppercase is not None: if ( uppercase < 0 and lowercase > (uppercase * -1) ): uppercase = lowercase + uppercase # If it's still negative, then means no uppercase if uppercase == 0 or uppercase > lowercase: # Make it all uppercase passphrase = Aux.make_all_uppercase(passphrase) elif uppercase > 0: passphrase = Aux.make_chars_uppercase( passphrase, uppercase ) # Handle numbers for _ in range(0, self.amount_n): passphrase.append(randbetween(MIN_NUM, MAX_NUM)) self.last_result = passphrase return passphrase
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_password(self) -> list: """Generate a list of random characters."""
characterset = self._get_password_characters() if ( self.passwordlen is None or not characterset ): raise ValueError("Can't generate password: character set is " "empty or passwordlen isn't set") password = [] for _ in range(0, self.passwordlen): password.append(randchoice(characterset)) self.last_result = password return password
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_uuid4(self) -> list: """Generate a list of parts of a UUID version 4 string. Usually, these parts are concatenated together using dashes. """
# uuid4: 8-4-4-4-12: xxxxxxxx-xxxx-4xxx-{8,9,a,b}xxx-xxxxxxxxxxxx # instead of requesting small amounts of bytes, it's better to do it # for the full amount of them. hexstr = randhex(30) uuid4 = [ hexstr[:8], hexstr[8:12], '4' + hexstr[12:15], '{:x}{}'.format(randbetween(8, 11), hexstr[15:18]), hexstr[18:] ] self.last_result = uuid4 return uuid4
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def default(self, line): ''' if no other commands was invoked ''' try: encoding, count = self._ks.asm(line) machine_code = "" for opcode in encoding: machine_code += "\\x" + hexlify(pack("B", opcode)).decode() print("\"" + machine_code + "\"") except KsError as e: print("Error: %s" %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 _bigger_than_zero(value: str) -> int: """Type evaluator for argparse."""
ivalue = int(value) if ivalue < 0: raise ArgumentTypeError( '{} should be bigger than 0'.format(ivalue) ) return ivalue
<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_fk_popup_field(cls, *args, **kwargs): """ generate fk field related to class wait popup crud """
kwargs['popup_name'] = cls.get_class_verbose_name() kwargs['permissions_required'] = cls.permissions_required if cls.template_name_fk is not None: kwargs['template_name'] = cls.template_name_fk return ForeignKeyWidget('{}_popup_create'.format(cls.get_class_name()), *args, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_m2m_popup_field(cls, *args, **kwargs): """ generate m2m field related to class wait popup crud """
kwargs['popup_name'] = cls.get_class_verbose_name() kwargs['permissions_required'] = cls.permissions_required if cls.template_name_m2m is not None: kwargs['template_name'] = cls.template_name_m2m return ManyToManyWidget('{}_popup_create'.format(cls.get_class_name()), *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 make_all_uppercase( lst: Union[list, tuple, str, set] ) -> Union[list, tuple, str, set]: """Make all characters uppercase. It supports characters in a (mix of) list, tuple, set or string. The return value is of the same type of the input value. """
if not isinstance(lst, (list, tuple, str, set)): raise TypeError('lst must be a list, a tuple, a set or a string') if isinstance(lst, str): return lst.upper() arr = list(lst) # enumerate is 70% slower than range # for i in range(len(lst)): # if isinstance(arr[i], (list, tuple, str, set)): # arr[i] = Aux.make_all_uppercase(arr[i]) arr[:] = [ Aux.make_all_uppercase(element) if ( isinstance(element, (list, tuple, str, set)) ) else element for element in arr ] if isinstance(lst, set): return set(arr) elif isinstance(lst, tuple): return tuple(arr) return arr
<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_one_char_uppercase(string: str) -> str: """Make a single char from the string uppercase."""
if not isinstance(string, str): raise TypeError('string must be a string') if Aux.lowercase_count(string) > 0: while True: cindex = randbelow(len(string)) if string[cindex].islower(): aux = list(string) aux[cindex] = aux[cindex].upper() string = ''.join(aux) break return string
<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_chars_uppercase( lst: Union[list, tuple, str, set], uppercase: int ) -> Union[list, tuple, str, set]: """Make uppercase some randomly selected characters. The characters can be in a (mix of) string, list, tuple or set. Keyword arguments: lst -- the object to make all chars uppercase, which can be a (mix of) list, tuple, string or set. uppercase -- Number of characters to be set as uppercase. """
if not isinstance(lst, (list, tuple, str, set)): raise TypeError('lst must be a list, a tuple, a set or a string') if not isinstance(uppercase, int): raise TypeError('uppercase must be an integer') if uppercase < 0: raise ValueError('uppercase must be bigger than zero') lowercase = Aux.lowercase_count(lst) if uppercase == 0 or lowercase == 0: return lst elif uppercase >= lowercase: # Make it all uppercase return Aux.make_all_uppercase(lst) arr = list(lst) # Check if at least an element is supported # This is required to avoid an infinite loop below supported = False for element in arr: if isinstance(element, (list, tuple, str, set)): supported = True break if supported: # Pick a word at random, then make a character uppercase count = 0 while count < uppercase: windex = randbelow(len(arr)) element = arr[windex] # Skip unsupported types or empty ones if element: aux = element if isinstance(element, str): aux = Aux._make_one_char_uppercase(element) elif isinstance(element, (list, tuple, set)): aux = Aux.make_chars_uppercase(element, 1) if aux != element: arr[windex] = aux count += 1 if isinstance(lst, set): return set(arr) elif isinstance(lst, str): return ''.join(arr) elif isinstance(lst, tuple): return tuple(arr) return arr
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def isfile_notempty(inputfile: str) -> bool: """Check if the input filename with path is a file and is not empty."""
try: return isfile(inputfile) and getsize(inputfile) > 0 except TypeError: raise TypeError('inputfile is not a valid type')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def system_entropy(): """Return the system's entropy bit count, or -1 if unknown."""
arg = ['cat', '/proc/sys/kernel/random/entropy_avail'] proc = Popen(arg, stdout=PIPE, stderr=DEVNULL) response = proc.communicate()[0] return int(response) if response else -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 issue(self, issuance_spec, metadata, fees): """ Creates a transaction for issuing an asset. :param TransferParameters issuance_spec: The parameters of the issuance. :param bytes metadata: The metadata to be embedded in the transaction. :param int fees: The fees to include in the transaction. :return: An unsigned transaction for issuing an asset. :rtype: CTransaction """
inputs, total_amount = self._collect_uncolored_outputs( issuance_spec.unspent_outputs, 2 * self._dust_amount + fees) return bitcoin.core.CTransaction( vin=[bitcoin.core.CTxIn(item.out_point, item.output.script) for item in inputs], vout=[ self._get_colored_output(issuance_spec.to_script), self._get_marker_output([issuance_spec.amount], metadata), self._get_uncolored_output(issuance_spec.change_script, total_amount - self._dust_amount - fees) ] )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def transfer(self, asset_transfer_specs, btc_transfer_spec, fees): """ Creates a transaction for sending assets and bitcoins. :param list[(bytes, TransferParameters)] asset_transfer_specs: A list of tuples. In each tuple: - The first element is the ID of an asset. - The second element is the parameters of the transfer. :param TransferParameters btc_transfer_spec: The parameters of the bitcoins being transferred. :param int fees: The fees to include in the transaction. :return: An unsigned transaction for sending assets and bitcoins. :rtype: CTransaction """
inputs = [] outputs = [] asset_quantities = [] for asset_id, transfer_spec in asset_transfer_specs: colored_outputs, collected_amount = self._collect_colored_outputs( transfer_spec.unspent_outputs, asset_id, transfer_spec.amount) inputs.extend(colored_outputs) outputs.append(self._get_colored_output(transfer_spec.to_script)) asset_quantities.append(transfer_spec.amount) if collected_amount > transfer_spec.amount: outputs.append(self._get_colored_output(transfer_spec.change_script)) asset_quantities.append(collected_amount - transfer_spec.amount) btc_excess = sum([input.output.value for input in inputs]) - sum([output.nValue for output in outputs]) if btc_excess < btc_transfer_spec.amount + fees: # Not enough bitcoin inputs uncolored_outputs, total_amount = self._collect_uncolored_outputs( btc_transfer_spec.unspent_outputs, btc_transfer_spec.amount + fees - btc_excess) inputs.extend(uncolored_outputs) btc_excess += total_amount change = btc_excess - btc_transfer_spec.amount - fees if change > 0: # Too much bitcoin in input, send it back as change outputs.append(self._get_uncolored_output(btc_transfer_spec.change_script, change)) if btc_transfer_spec.amount > 0: outputs.append(self._get_uncolored_output(btc_transfer_spec.to_script, btc_transfer_spec.amount)) if asset_quantities: outputs.insert(0, self._get_marker_output(asset_quantities, b'')) return bitcoin.core.CTransaction( vin=[bitcoin.core.CTxIn(item.out_point, item.output.script) for item in inputs], vout=outputs )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def transfer_assets(self, asset_id, transfer_spec, btc_change_script, fees): """ Creates a transaction for sending an asset. :param bytes asset_id: The ID of the asset being sent. :param TransferParameters transfer_spec: The parameters of the asset being transferred. :param bytes btc_change_script: The script where to send bitcoin change, if any. :param int fees: The fees to include in the transaction. :return: The resulting unsigned transaction. :rtype: CTransaction """
return self.transfer( [(asset_id, transfer_spec)], TransferParameters(transfer_spec.unspent_outputs, None, btc_change_script, 0), fees)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def btc_asset_swap(self, btc_transfer_spec, asset_id, asset_transfer_spec, fees): """ Creates a transaction for swapping assets for bitcoins. :param TransferParameters btc_transfer_spec: The parameters of the bitcoins being transferred. :param bytes asset_id: The ID of the asset being sent. :param TransferParameters asset_transfer_spec: The parameters of the asset being transferred. :param int fees: The fees to include in the transaction. :return: The resulting unsigned transaction. :rtype: CTransaction """
return self.transfer([(asset_id, asset_transfer_spec)], btc_transfer_spec, fees)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def asset_asset_swap( self, asset1_id, asset1_transfer_spec, asset2_id, asset2_transfer_spec, fees): """ Creates a transaction for swapping an asset for another asset. :param bytes asset1_id: The ID of the first asset. :param TransferParameters asset1_transfer_spec: The parameters of the first asset being transferred. It is also used for paying fees and/or receiving change if any. :param bytes asset2_id: The ID of the second asset. :param TransferDetails asset2_transfer_spec: The parameters of the second asset being transferred. :param int fees: The fees to include in the transaction. :return: The resulting unsigned transaction. :rtype: CTransaction """
btc_transfer_spec = TransferParameters( asset1_transfer_spec.unspent_outputs, asset1_transfer_spec.to_script, asset1_transfer_spec.change_script, 0) return self.transfer( [(asset1_id, asset1_transfer_spec), (asset2_id, asset2_transfer_spec)], btc_transfer_spec, fees)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _collect_uncolored_outputs(unspent_outputs, amount): """ Returns a list of uncolored outputs for the specified amount. :param list[SpendableOutput] unspent_outputs: The list of available outputs. :param int amount: The amount to collect. :return: A list of outputs, and the total amount collected. :rtype: (list[SpendableOutput], int) """
total_amount = 0 result = [] for output in unspent_outputs: if output.output.asset_id is None: result.append(output) total_amount += output.output.value if total_amount >= amount: return result, total_amount raise InsufficientFundsError
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _collect_colored_outputs(unspent_outputs, asset_id, asset_quantity): """ Returns a list of colored outputs for the specified quantity. :param list[SpendableOutput] unspent_outputs: The list of available outputs. :param bytes asset_id: The ID of the asset to collect. :param int asset_quantity: The asset quantity to collect. :return: A list of outputs, and the total asset quantity collected. :rtype: (list[SpendableOutput], int) """
total_amount = 0 result = [] for output in unspent_outputs: if output.output.asset_id == asset_id: result.append(output) total_amount += output.output.asset_quantity if total_amount >= asset_quantity: return result, total_amount raise InsufficientAssetQuantityError
<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_uncolored_output(self, script, value): """ Creates an uncolored output. :param bytes script: The output script. :param int value: The satoshi value of the output. :return: An object representing the uncolored output. :rtype: TransactionOutput """
if value < self._dust_amount: raise DustOutputError return bitcoin.core.CTxOut(value, bitcoin.core.CScript(script))
<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_colored_output(self, script): """ Creates a colored output. :param bytes script: The output script. :return: An object representing the colored output. :rtype: TransactionOutput """
return bitcoin.core.CTxOut(self._dust_amount, bitcoin.core.CScript(script))
<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_marker_output(self, asset_quantities, metadata): """ Creates a marker output. :param list[int] asset_quantities: The asset quantity list. :param bytes metadata: The metadata contained in the output. :return: An object representing the marker output. :rtype: TransactionOutput """
payload = openassets.protocol.MarkerOutput(asset_quantities, metadata).serialize_payload() script = openassets.protocol.MarkerOutput.build_script(payload) return bitcoin.core.CTxOut(0, script)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init_app(self, app): """Setup the 4 default routes."""
app.add_url_rule(self.request_token_url, view_func=self.request_token, methods=[u'POST']) app.add_url_rule(self.access_token_url, view_func=self.access_token, methods=[u'POST']) app.add_url_rule(self.register_url, view_func=self.register, methods=[u'GET', u'POST']) app.add_url_rule(self.authorize_url, view_func=self.authorize, methods=[u'GET', u'POST'])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def authorized(self, request_token): """Create a verifier for an user authorized client"""
verifier = generate_token(length=self.verifier_length[1]) self.save_verifier(request_token, verifier) response = [ (u'oauth_token', request_token), (u'oauth_verifier', verifier) ] callback = self.get_callback(request_token) return redirect(add_params_to_uri(callback, 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 request_token(self): """Create an OAuth request token for a valid client request. Defaults to /request_token. Invoked by client applications. """
client_key = request.oauth.client_key realm = request.oauth.realm # TODO: fallback on default realm? callback = request.oauth.callback_uri request_token = generate_token(length=self.request_token_length[1]) token_secret = generate_token(length=self.secret_length) self.save_request_token(client_key, request_token, callback, realm=realm, secret=token_secret) return urlencode([(u'oauth_token', request_token), (u'oauth_token_secret', token_secret), (u'oauth_callback_confirmed', u'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 access_token(self): """Create an OAuth access token for an authorized client. Defaults to /access_token. Invoked by client applications. """
access_token = generate_token(length=self.access_token_length[1]) token_secret = generate_token(self.secret_length) client_key = request.oauth.client_key self.save_access_token(client_key, access_token, request.oauth.resource_owner_key, secret=token_secret) return urlencode([(u'oauth_token', access_token), (u'oauth_token_secret', token_secret)])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def require_oauth(self, realm=None, require_resource_owner=True, require_verifier=False, require_realm=False): """Mark the view function f as a protected resource"""
def decorator(f): @wraps(f) def verify_request(*args, **kwargs): """Verify OAuth params before running view function f""" try: if request.form: body = request.form.to_dict() else: body = request.data.decode("utf-8") verify_result = self.verify_request(request.url.decode("utf-8"), http_method=request.method.decode("utf-8"), body=body, headers=request.headers, require_resource_owner=require_resource_owner, require_verifier=require_verifier, require_realm=require_realm or bool(realm), required_realm=realm) valid, oauth_request = verify_result if valid: request.oauth = self.collect_request_parameters(request) # Request tokens are only valid when a verifier is too token = {} if require_verifier: token[u'request_token'] = request.oauth.resource_owner_key else: token[u'access_token'] = request.oauth.resource_owner_key # All nonce/timestamp pairs must be stored to prevent # replay attacks, they may be connected to a specific # client and token to decrease collision probability. self.save_timestamp_and_nonce(request.oauth.client_key, request.oauth.timestamp, request.oauth.nonce, **token) # By this point, the request is fully authorized return f(*args, **kwargs) else: # Unauthorized requests should not diclose their cause raise Unauthorized() except ValueError as err: # Caused by missing of or badly formatted parameters raise BadRequest(err.message) return verify_request return decorator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def collect_request_parameters(self, request): """Collect parameters in an object for convenient access"""
class OAuthParameters(object): """Used as a parameter container since plain object()s can't""" pass # Collect parameters query = urlparse(request.url.decode("utf-8")).query content_type = request.headers.get('Content-Type', '') if request.form: body = request.form.to_dict() elif content_type == 'application/x-www-form-urlencoded': body = request.data.decode("utf-8") else: body = '' headers = dict(encode_params_utf8(request.headers.items())) params = dict(collect_parameters(uri_query=query, body=body, headers=headers)) # Extract params and store for convenient and predictable access oauth_params = OAuthParameters() oauth_params.client_key = params.get(u'oauth_consumer_key') oauth_params.resource_owner_key = params.get(u'oauth_token', None) oauth_params.nonce = params.get(u'oauth_nonce') oauth_params.timestamp = params.get(u'oauth_timestamp') oauth_params.verifier = params.get(u'oauth_verifier', None) oauth_params.callback_uri = params.get(u'oauth_callback', None) oauth_params.realm = params.get(u'realm', None) return oauth_params
<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_size(self, name: str) -> int: """Get a resource size from the RSTB."""
crc32 = binascii.crc32(name.encode()) if crc32 in self.crc32_map: return self.crc32_map[crc32] if name in self.name_map: return self.name_map[name] return 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 set_size(self, name: str, size: int): """Set the size of a resource in the RSTB."""
if self._needs_to_be_in_name_map(name): if len(name) >= 128: raise ValueError("Name is too long") self.name_map[name] = size else: crc32 = binascii.crc32(name.encode()) self.crc32_map[crc32] = size
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write(self, stream: typing.BinaryIO, be: bool) -> None: """Write the RSTB to the specified stream."""
stream.write(b'RSTB') stream.write(_to_u32(len(self.crc32_map), be)) stream.write(_to_u32(len(self.name_map), be)) # The CRC32 hashmap *must* be sorted because the game performs a binary search. for crc32, size in sorted(self.crc32_map.items()): stream.write(_to_u32(crc32, be)) stream.write(_to_u32(size, be)) # The name map does not have to be sorted, but Nintendo seems to do it, so let's sort too. for name, size in sorted(self.name_map.items()): stream.write(struct.pack('128s', name.encode())) stream.write(_to_u32(size, be))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def randint(nbits: int) -> int: """Generate an int with nbits random bits. Raises ValueError if nbits <= 0, and TypeError if it's not an integer. 1871 """
if not isinstance(nbits, int): raise TypeError('number of bits should be an integer') if nbits <= 0: raise ValueError('number of bits must be greater than zero') # https://github.com/python/cpython/blob/3.6/Lib/random.py#L676 nbytes = (nbits + 7) // 8 # bits / 8 and rounded up num = int.from_bytes(randbytes(nbytes), 'big') return num >> (nbytes * 8 - nbits)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def randchoice(seq: Union[str, list, tuple, dict, set]) -> any: """Return a randomly chosen element from the given sequence. Raises TypeError if *seq* is not str, list, tuple, dict, set and an IndexError if it is empty. 'a' """
if not isinstance(seq, (str, list, tuple, dict, set)): raise TypeError('seq must be str, list, tuple, dict or set') if len(seq) <= 0: raise IndexError('seq must have at least one element') if isinstance(seq, set): values = list(seq) return randchoice(values) elif isinstance(seq, dict): indexes = list(seq) index = randchoice(indexes) else: index = randbelow(len(seq)) return seq[index]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def randbelow(num: int) -> int: """Return a random int in the range [0,num). Raises ValueError if num <= 0, and TypeError if it's not an integer. 13 """
if not isinstance(num, int): raise TypeError('number must be an integer') if num <= 0: raise ValueError('number must be greater than zero') if num == 1: return 0 # https://github.com/python/cpython/blob/3.6/Lib/random.py#L223 nbits = num.bit_length() # don't use (n-1) here because n can be 1 randnum = random_randint(nbits) # 0 <= randnum < 2**nbits while randnum >= num: randnum = random_randint(nbits) return randnum
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def randhex(ndigits: int) -> str: """Return a random text string of hexadecimal characters. The string has *ndigits* random digits. Raises ValueError if ndigits <= 0, and TypeError if it's not an integer. '56054d728fc56f63' """
if not isinstance(ndigits, int): raise TypeError('number of digits must be an integer') if ndigits <= 0: raise ValueError('number of digits must be greater than zero') nbytes = ceil(ndigits / 2) rbytes = random_randbytes(nbytes) hexstr = rbytes.hex()[:ndigits] return hexstr
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def default(self, user_input): ''' if no other command was invoked ''' try: for i in self._cs.disasm(unhexlify(self.cleanup(user_input)), self.base_address): print("0x%08x:\t%s\t%s" %(i.address, i.mnemonic, i.op_str)) except CsError as e: print("Error: %s" %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 setMoveResizeWindow(self, win, gravity=0, x=None, y=None, w=None, h=None): """ Set the property _NET_MOVERESIZE_WINDOW to move or resize the given window. Flags are automatically calculated if x, y, w or h are defined. :param win: the window object :param gravity: gravity (one of the Xlib.X.*Gravity constant or 0) :param x: int or None :param y: int or None :param w: int or None :param h: int or None """
# indicate source (application) gravity_flags = gravity | 0b0000100000000000 if x is None: x = 0 else: gravity_flags = gravity_flags | 0b0000010000000000 if y is None: y = 0 else: gravity_flags = gravity_flags | 0b0000001000000000 if w is None: w = 0 else: gravity_flags = gravity_flags | 0b0000000100000000 if h is None: h = 0 else: gravity_flags = gravity_flags | 0b0000000010000000 self._setProperty('_NET_MOVERESIZE_WINDOW', [gravity_flags, x, y, w, h], win)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _setProperty(self, _type, data, win=None, mask=None): """ Send a ClientMessage event to the root window """
if not win: win = self.root if type(data) is str: dataSize = 8 else: data = (data+[0]*(5-len(data)))[:5] dataSize = 32 ev = protocol.event.ClientMessage( window=win, client_type=self.display.get_atom(_type), data=(dataSize, data)) if not mask: mask = (X.SubstructureRedirectMask | X.SubstructureNotifyMask) self.root.send_event(ev, event_mask=mask)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def scoreatpercentile(a, per, limit=(), interpolation_method='fraction', axis=None): """ Calculate the score at a given percentile of the input sequence. For example, the score at `per=50` is the median. If the desired quantile lies between two data points, we interpolate between them, according to the value of `interpolation`. If the parameter `limit` is provided, it should be a tuple (lower, upper) of two values. Parameters a : array_like A 1-D array of values from which to extract score. per : array_like Percentile(s) at which to extract score. Values should be in range [0,100]. limit : tuple, optional Tuple of two scalars, the lower and upper limits within which to compute the percentile. Values of `a` outside this (closed) interval will be ignored. interpolation : {'fraction', 'lower', 'higher'}, optional This optional parameter specifies the interpolation method to use, when the desired quantile lies between two data points `i` and `j` - fraction: ``i + (j - i) * fraction`` where ``fraction`` is the fractional part of the index surrounded by ``i`` and ``j``. - lower: ``i``. - higher: ``j``. axis : int, optional Axis along which the percentiles are computed. The default (None) is to compute the median along a flattened version of the array. Returns ------- score : float (or sequence of floats) Score at percentile. See Also -------- percentileofscore Examples -------- 49.5 """
# adapted from NumPy's percentile function a = np.asarray(a) if limit: a = a[(limit[0] <= a) & (a <= limit[1])] if per == 0: return a.min(axis=axis) elif per == 100: return a.max(axis=axis) sorted = np.sort(a, axis=axis) if axis is None: axis = 0 return _compute_qth_percentile(sorted, per, interpolation_method, axis)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def merge_equal_neighbors(self): """ Merge neighbors with same speaker. """
IDX_LENGTH = 3 merged = self.segs.copy() current_start = 0 j = 0 seg = self.segs.iloc[0] for i in range(1, self.num_segments): seg = self.segs.iloc[i] last = self.segs.iloc[i - 1] if seg.speaker == last.speaker: merged.iat[j, IDX_LENGTH] = seg.start + seg.length - current_start else: j += 1 merged.iloc[j] = seg current_start = seg.start merged = merged.iloc[:(j+1)] merged.sort_values('start', inplace = True) return self.update_segs(merged)
<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_arguments(*args): """ Converts a list of arguments from the command line into a list of positional arguments and a dictionary of keyword arguments. Handled formats for keyword arguments are: * --argument=value * --argument value Args: *args (list): a list of arguments Returns: ([positional_args], {kwargs}) """
positional_args = [] kwargs = {} split_key = None for arg in args: if arg.startswith('--'): arg = arg[2:] if '=' in arg: key, value = arg.split('=', 1) kwargs[key.replace('-', '_')] = value else: split_key = arg.replace('-', '_') elif split_key: kwargs[split_key] = arg split_key = None else: positional_args.append(arg) return positional_args, kwargs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_settings(section='gocd', settings_paths=('~/.gocd/gocd-cli.cfg', '/etc/go/gocd-cli.cfg')): """Returns a `gocd_cli.settings.Settings` configured for settings file The settings will be read from environment variables first, then it'll be read from the first config file found (if any). Environment variables are expected to be in UPPERCASE and to be prefixed with `GOCD_`. Args: section: The prefix to use for reading environment variables and the name of the section in the config file. Default: gocd settings_path: Possible paths for the configuration file. Default: `('~/.gocd/gocd-cli.cfg', '/etc/go/gocd-cli.cfg')` Returns: `gocd_cli.settings.Settings` instance """
if isinstance(settings_paths, basestring): settings_paths = (settings_paths,) config_file = next((path for path in settings_paths if is_file_readable(path)), None) if config_file: config_file = expand_user(config_file) return Settings(prefix=section, section=section, filename=config_file)
<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_go_server(settings=None): """Returns a `gocd.Server` configured by the `settings` object. Args: settings: a `gocd_cli.settings.Settings` object. Default: if falsey calls `get_settings`. Returns: gocd.Server: a configured gocd.Server instance """
if not settings: settings = get_settings() return gocd.Server( settings.get('server'), user=settings.get('user'), password=settings.get('password'), )
<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_standard_tc_matches(text, full_text, options): ''' get the standard tab completions. These are the options which could complete the full_text. ''' final_matches = [o for o in options if o.startswith(full_text)] return final_matches
<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_fuzzy_tc_matches(text, full_text, options): ''' Get the options that match the full text, then from each option return only the individual words which have not yet been matched which also match the text being tab-completed. ''' print("text: {}, full: {}, options: {}".format(text, full_text, options)) # get the options which match the full text matching_options = _get_fuzzy_matches(full_text, options) # need to only return the individual words which: # - match the 'text' # - are not exclusively matched by other input in full_text # - when matched, still allows all other input in full_text to be matched # get the input tokens input_tokens = full_text.split() # remove one instance of the text to be matched initial_tokens = input_tokens.remove(text) # track the final matches: final_matches = [] # find matches per option for option in options: option_tokens = option.split() # get tokens which match the text matches = [t for t in option_tokens if text in t] # get input tokens which match one of the matches input_tokens_which_match = [t for t in input_tokens for m in matches if t in m] # if any input token ONLY matches a match, remove that match for token in input_tokens_which_match: token_matches = [t for t in option_tokens if token in t] if len(token_matches) == 1: match = token_matches[0] if match in matches: matches.remove(match) # for the remaining matches, if the input tokens can be fuzzily matched without # the match, it's ok to return it. for match in matches: # copy option tokens option_tokens_minus_match = option_tokens[:] # remove the match option_tokens_minus_match.remove(match) option_minus_match = ' '.join(option_tokens_minus_match) if _get_fuzzy_matches(' '.join(input_tokens), [option_minus_match]): if match not in final_matches: final_matches.append(match) return final_matches