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 _load_chunk(dat_path, cat_path, info_path): """Loads a data chunk as specified by the paths. Args: dat_path: Path to dat file of the chunk. cat_path: Path to...
dat_array = read_binary_matrix(dat_path) # Even if the image is gray scale, we need to add an extra channel dimension # to be compatible with tfds.features.Image. dat_array = np.expand_dims(dat_array, -1) cat_array = read_binary_matrix(cat_path) info_array = read_binary_matrix(info_path) info_array = 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 read_binary_matrix(filename): """Reads and returns binary formatted matrix stored in filename. The file format is described on the data set page: https://cs....
with tf.io.gfile.GFile(filename, "rb") as f: s = f.read() # Data is stored in little-endian byte order. int32_dtype = np.dtype("int32").newbyteorder("<") # The first 4 bytes contain a magic code that specifies the data type. magic = int(np.frombuffer(s, dtype=int32_dtype, count=1)) if magic...
<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_examples(self, dat_path, cat_path, info_path): """Generate examples for the Smallnorb dataset. Args: dat_path: Path to dat file of the chunk. cat_p...
dat_arr, cat_arr, info_arr = _load_chunk(dat_path, cat_path, info_path) for image, category, info_vec in moves.zip(dat_arr, cat_arr, info_arr): yield { "image": image[0], "image2": image[1], "label_category": category, "instance": info_vec[0], "label_ele...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_dataset(instruction_dicts, dataset_from_file_fn, shuffle_files=False, parallel_reads=64): """Constructs a `tf.data.Dataset` from TFRecord files. Args: ...
# First case: All examples are taken (No value skipped) if _no_examples_skipped(instruction_dicts): # Only use the filenames as instruction instruction_ds = tf.data.Dataset.from_tensor_slices([ d["filepath"] for d in instruction_dicts ]) build_ds_from_instruction = dataset_from_file_fn #...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _build_instruction_ds(instructions): """Create a dataset containing individual instruction for each shard. Each instruction is a dict: ``` { "filepath": tf.T...
# Transpose the list[dict] into dict[list] tensor_inputs = { # offset_mask need to be converted to int64 explicitly k: np.array(vals, dtype=np.int64) if k == "mask_offset" else list(vals) for k, vals in utils.zip_dict(*instructions) } return tf.data.Dataset.from_tensor_slices(tensor_inputs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _build_mask_ds(mask, mask_offset): """Build the mask dataset to indicate which element to skip. Args: mask: `tf.Tensor`, binary mask to apply to all followin...
mask_ds = tf.data.Dataset.from_tensor_slices(mask) mask_ds = mask_ds.repeat() mask_ds = mask_ds.skip(mask_offset) return mask_ds
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _build_ds_from_instruction(instruction, ds_from_file_fn): """Map an instruction to a real datasets for one particular shard. Args: instruction: A `dict` of `...
# Create the example and mask ds for this particular shard examples_ds = ds_from_file_fn(instruction["filepath"]) mask_ds = _build_mask_ds( mask_offset=instruction["mask_offset"], mask=instruction["mask"], ) # Zip the mask and real examples ds = tf.data.Dataset.zip((examples_ds, mask_ds)) # ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def as_numpy(dataset, graph=None): """Converts a `tf.data.Dataset` to an iterable of NumPy arrays. `as_numpy` converts a possibly nested structure of `tf.data.Da...
nested_ds = dataset del dataset # Flatten flat_ds = tf.nest.flatten(nested_ds) flat_np = [] # Type check for Tensors and Datasets for ds_el in flat_ds: types = [type(el) for el in flat_ds] types = tf.nest.pack_sequence_as(nested_ds, types) if not (isinstance(ds_el, tf.Tensor) or tf_compat.i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _load_data(filepath): """Loads the images and latent values into Numpy arrays."""
with h5py.File(filepath, "r") as h5dataset: image_array = np.array(h5dataset["images"]) # The 'label' data set in the hdf5 file actually contains the float values # and not the class labels. values_array = np.array(h5dataset["labels"]) return image_array, values_array
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _discretize(a): """Discretizes array values to class labels."""
arr = np.asarray(a) index = np.argsort(arr) inverse_index = np.zeros(arr.size, dtype=np.intp) inverse_index[index] = np.arange(arr.size, dtype=np.intp) arr = arr[index] obs = np.r_[True, arr[1:] != arr[:-1]] return obs.cumsum()[inverse_index] - 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 _generate_examples(self, filepath): """Generate examples for the Shapes3d dataset. Args: filepath: path to the Shapes3d hdf5 file. Yields: Dictionaries with ...
# Simultaneously iterating through the different data sets in the hdf5 # file will be slow with a single file. Instead, we first load everything # into memory before yielding the samples. image_array, values_array = _load_data(filepath) # We need to calculate the class labels from the float 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 _parse_and_clean_wikicode(raw_content): """Strips formatting and unwanted sections from raw page content."""
wikicode = tfds.core.lazy_imports.mwparserfromhell.parse(raw_content) # Filters for references, tables, and file/image links. re_rm_wikilink = re.compile( "^(?:File|Image|Media):", flags=re.IGNORECASE | re.UNICODE) def rm_wikilink(obj): return bool(re_rm_wikilink.match(six.text_type(obj.title))) 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 download_and_prepare(builder): """Generate data for a given dataset."""
print("download_and_prepare for dataset {}...".format(builder.info.full_name)) dl_config = download_config() if isinstance(builder, tfds.core.BeamBasedBuilder): beam = tfds.core.lazy_imports.apache_beam # TODO(b/129149715): Restore compute stats. Currently skipped because not # beam supported. ...
<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_examples(self, filepaths): """Generate CIFAR examples as dicts. Shared across CIFAR-{10, 100}. Uses self._cifar_info as configuration. Args: filepa...
label_keys = self._cifar_info.label_keys for path in filepaths: for labels, np_image in _load_data(path, len(label_keys)): row = dict(zip(label_keys, labels)) row["image"] = np_image yield row
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def disallow_positional_args(wrapped=None, allowed=None): """Requires function to be called using keyword arguments."""
# See # https://wrapt.readthedocs.io/en/latest/decorators.html#decorators-with-optional-arguments # for decorator pattern. if wrapped is None: return functools.partial(disallow_positional_args, allowed=allowed) @wrapt.decorator def disallow_positional_args_dec(fn, instance, args, kwargs): ismethod...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _required_args(fn): """Returns arguments of fn with default=REQUIRED_ARG."""
spec = getargspec(fn) if not spec.defaults: return [] arg_names = spec.args[-len(spec.defaults):] return [name for name, val in zip(arg_names, spec.defaults) if val is REQUIRED_ARG]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download_gcs_file(path, out_fname=None, prefix_filter=None): """Download a file from GCS, optionally to a file."""
url = posixpath.join(GCS_BUCKET, path) if prefix_filter: url += "?prefix=%s" % prefix_filter stream = bool(out_fname) resp = requests.get(url, stream=stream) if not resp.ok: raise ValueError("GCS bucket inaccessible") if out_fname: with tf.io.gfile.GFile(out_fname, "wb") as f: for chunk i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gcs_files(prefix_filter=None): """List all files in GCS bucket."""
top_level_xml_str = download_gcs_file("", prefix_filter=prefix_filter) xml_root = ElementTree.fromstring(top_level_xml_str) filenames = [el[0].text for el in xml_root if el.tag.endswith("Contents")] return filenames
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gcs_dataset_info_files(dataset_dir): """Return paths to GCS files in the given dataset directory."""
prefix = posixpath.join(GCS_DATASET_INFO_DIR, dataset_dir, "") # Filter for this dataset filenames = [el for el in gcs_files(prefix_filter=prefix) if el.startswith(prefix) and len(el) > len(prefix)] return filenames
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _run_kaggle_command(command_args, competition_name): """Run kaggle command with subprocess."""
try: output = sp.check_output(command_args) return tf.compat.as_text(output) except sp.CalledProcessError as err: output = err.output _log_command_output(output, error=True) if output.startswith(b"404"): logging.error(_NOT_FOUND_ERR_MSG, competition_name) raise logging.error(_ER...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def competition_files(self): """List of competition files."""
command = [ "kaggle", "datasets" if "/" in self._competition_name else "competitions", "files", "-v", self._competition_name, ] output = _run_kaggle_command(command, self._competition_name) return sorted([ line.split(",")[0] for line in output.split("\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 download_file(self, fname, output_dir): """Downloads competition file to output_dir."""
if fname not in self.competition_files: # pylint: disable=unsupported-membership-test raise ValueError("%s is not one of the competition's " "files: %s" % (fname, self.competition_files)) command = [ "kaggle", "competitions", "download", "--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 _generate_examples(self, images_dir_path): """Generate flower images and labels given the image directory path. Args: images_dir_path: path to the directory ...
parent_dir = tf.io.gfile.listdir(images_dir_path)[0] walk_dir = os.path.join(images_dir_path, parent_dir) dirs = tf.io.gfile.listdir(walk_dir) for d in dirs: if tf.io.gfile.isdir(os.path.join(walk_dir, d)): for full_path, _, fname in tf.io.gfile.walk(os.path.join(walk_dir, d)): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_path(dataset_name): """Returns path to where checksums are stored for a given dataset."""
path = _checksum_paths().get(dataset_name, None) if path: return path msg = ('No checksums file could be find for dataset %s. Please create one in ' 'one of: %s') % (dataset_name, ', '.join(_CHECKSUM_DIRS)) raise AssertionError(msg)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def store_checksums(dataset_name, sizes_checksums): """Store given checksums and sizes for specific dataset. Content of file is never disgarded, only updated. Th...
path = _get_path(dataset_name) original_data = _get_sizes_checksums(path) new_data = original_data.copy() new_data.update(sizes_checksums) if original_data == new_data: return with tf.io.gfile.GFile(path, 'w') as f: for url, (size, checksum) in sorted(new_data.items()): f.write('%s %s %s\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 _sanitize_url(url, max_length): """Sanitize and shorten url to fit in max_length. Function is stable: same input MUST ALWAYS give same result, accros changes...
url = urllib.parse.urlparse(url) netloc = url.netloc for prefix in _NETLOC_COMMON_PREFIXES: if netloc.startswith(prefix): netloc = netloc[len(prefix):] for suffix in _NETLOC_COMMON_SUFFIXES: if netloc.endswith(suffix): netloc = netloc[:-len(suffix)] url = '%s%s%s%s' % (netloc, url.path, u...
<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_dl_dirname(url): """Returns name of temp dir for given url."""
checksum = hashlib.sha256(tf.compat.as_bytes(url)).hexdigest() return get_dl_fname(url, checksum)
<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_info(info_path): """Returns info dict or None."""
if not tf.io.gfile.exists(info_path): return None with tf.io.gfile.GFile(info_path) as info_f: return json.load(info_f)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_info_file(resource, path, dataset_name, original_fname): """Write the INFO file next to local file. Although the method is synchronized, there is still...
info_path = _get_info_path(path) info = _read_info(info_path) or {} urls = set(info.get('urls', []) + [resource.url]) dataset_names = info.get('dataset_names', []) if dataset_name: dataset_names.append(dataset_name) if 'original_fname' in info and info['original_fname'] != original_fname: raise Ass...
<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_extract_method(path): """Returns `ExtractMethod` to use on resource at path. Cannot be None."""
info_path = _get_info_path(path) info = _read_info(info_path) fname = info.get('original_fname', path) if info else path return _guess_extract_method(fname)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def exists_locally(cls, path): """Returns whether the resource exists locally, at `resource.path`."""
# If INFO file doesn't exist, consider resource does NOT exist, as it would # prevent guessing the `extract_method`. return (tf.io.gfile.exists(path) and tf.io.gfile.exists(_get_info_path(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 maybe_build_from_corpus(self, corpus_generator, **kwargs): """Call SubwordTextEncoder.build_from_corpus is encoder_cls is such."""
if self._encoder_cls is not text_lib.SubwordTextEncoder: return if self.encoder: return vocab_size = self._encoder_config.vocab_size self.encoder = text_lib.SubwordTextEncoder.build_from_corpus( corpus_generator=corpus_generator, target_vocab_size=vocab_size, **kwar...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sharded_filenames(filename_prefix, num_shards): """Sharded filenames given prefix and number of shards."""
shard_suffix = "%05d-of-%05d" return [ "%s-%s" % (filename_prefix, shard_suffix % (i, num_shards)) for i in range(num_shards) ]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _walk_omniglot_dir(directory): """Walk an Omniglot directory and yield examples."""
directory = os.path.join(directory, tf.io.gfile.listdir(directory)[0]) alphabets = sorted(tf.io.gfile.listdir(directory)) for alphabet in alphabets: alphabet_dir = os.path.join(directory, alphabet) characters = sorted(tf.io.gfile.listdir(alphabet_dir)) for character in characters: character_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 _get_names(dirs): """Get alphabet and label names, union across all dirs."""
alphabets = set() label_names = {} for d in dirs: for example in _walk_omniglot_dir(d): alphabet, alphabet_char_id, label, _ = example alphabets.add(alphabet) label_name = "%s_%d" % (alphabet, alphabet_char_id) if label in label_names: assert label_names[label] == label_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 size_str(size_in_bytes): """Returns a human readable size string. If size_in_bytes is None, then returns "?? GiB". For example `size_str(1.5 * tfds.units.GiB...
if not size_in_bytes: return "?? GiB" size_in_bytes = float(size_in_bytes) for (name, size_bytes) in _NAME_LIST: value = size_in_bytes / size_bytes if value >= 1.0: return "{:.2f} {}".format(value, name) return "{} {}".format(int(size_in_bytes), "bytes")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tqdm(self): """Add a progression bar for the current download."""
async_tqdm = utils.async_tqdm with async_tqdm(total=0, desc='Dl Completed...', unit=' url') as pbar_url: with async_tqdm(total=0, desc='Dl Size...', unit=' MiB') as pbar_dl_size: self._pbar_url = pbar_url self._pbar_dl_size = pbar_dl_size yield
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download(self, url, destination_path): """Download url to given path. Returns Promise -> sha256 of downloaded file. Args: url: address of resource to downloa...
self._pbar_url.update_total(1) future = self._executor.submit(self._sync_download, url, destination_path) return promise.Promise.resolve(future)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _sync_kaggle_download(self, kaggle_url, destination_path): """Download with Kaggle API."""
kaggle_file = kaggle.KaggleFile.from_url(kaggle_url) downloader = self.kaggle_downloader(kaggle_file.competition) filepath = downloader.download_file(kaggle_file.filename, destination_path) dl_size = tf.io.gfile.stat(filepath).length checksum = self._checksumer() with tf.io.gfile.GFile(filepat...
<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_drive_url(self, url, session): """Returns url, possibly with confirmation token."""
response = session.get(url, stream=True) if response.status_code != 200: raise DownloadError( 'Failed to get url %s. HTTP code: %d.' % (url, response.status_code)) for k, v in response.cookies.items(): if k.startswith('download_warning'): return url + '&confirm=' + v # v is t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _sync_download(self, url, destination_path): """Synchronous version of `download` method."""
proxies = { 'http': os.environ.get('TFDS_HTTP_PROXY', None), 'https': os.environ.get('TFDS_HTTPS_PROXY', None), 'ftp': os.environ.get('TFDS_FTP_PROXY', None) } if kaggle.KaggleFile.is_kaggle_url(url): if proxies['http']: os.environ['KAGGLE_PROXY'] = proxies['http'] ...
<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_examples(self, images_dir_path, csv_path=None, csv_usage=None): """Yields Example instances from given CSV. Args: images_dir_path: path to dir in w...
if csv_path: with tf.io.gfile.GFile(csv_path) as csv_f: reader = csv.DictReader(csv_f) data = [(row["image"], int(row["level"])) for row in reader if csv_usage is None or row["Usage"] == csv_usage] else: data = [(fname[:-5], -1) for fnam...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _slice_split_info_to_instruction_dicts(self, list_sliced_split_info): """Return the list of files and reading mask of the files to read."""
instruction_dicts = [] for sliced_split_info in list_sliced_split_info: mask = splits_lib.slice_to_percent_mask(sliced_split_info.slice_value) # Compute filenames from the given split filepaths = list(sorted(self._build_split_filenames( split_info_list=[sliced_split_info.split_info...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _build_split_filenames(self, split_info_list): """Construct the split filenames associated with the split info. The filenames correspond to the pre-processed...
filenames = [] for split_info in split_info_list: filenames.extend(naming.filepaths_for_dataset_split( dataset_name=self.name, split=split_info.name, num_shards=split_info.num_shards, data_dir=self._data_dir, filetype_suffix=self._file_format_adapter.fil...
<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_examples(self, data_path): """Generate MovingMnist sequences. Args: data_path (str): Path to the data file Yields: 20 x 64 x 64 x 1 uint8 numpy ar...
with tf.io.gfile.GFile(data_path, "rb") as fp: images = np.load(fp) images = np.transpose(images, (1, 0, 2, 3)) images = np.expand_dims(images, axis=-1) for sequence in images: yield dict(image_sequence=sequence)
<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_single_video(self, example_proto): """Parses single video from the input tfrecords. Args: example_proto: tfExample proto with a single video. Returns:...
context_features = { "game_duration_loops": tf.io.FixedLenFeature([1], tf.int64), "game_duration_seconds": tf.io.FixedLenFeature([1], tf.float32), "n_steps": tf.io.FixedLenFeature([1], tf.int64), "screen_size": tf.io.FixedLenFeature([2], tf.int64), } sequence_features = { ...
<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_examples(self, filepath): """Generates examples for the dSprites data set. Args: filepath: path to the dSprites hdf5 file. Yields: Dictionaries wit...
# Simultaneously iterating through the different data sets in the hdf5 # file is >100x slower and the data set is small (26.7MB). Hence, we first # load everything into memory before yielding the samples. image_array, class_array, values_array = _load_data(filepath) for image, classes, values in mo...
<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_objects(csv_paths, csv_positions, prefix): """Returns objects listed within given CSV files."""
logging.info('Loading CSVs %s from positions %s with prefix %s', csv_paths, csv_positions, prefix) objects = collections.defaultdict(list) for i, labels_path in enumerate(csv_paths): with tf.io.gfile.GFile(labels_path) as csv_f: if csv_positions[i] > 0: csv_f.seek(csv_positions[i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _load_bboxes(csv_path, csv_positions, prefix): """Returns bounded boxes listed within given CSV file."""
logging.info('Loading CSVs %s from positions %s with prefix %s', csv_path, csv_positions, prefix) boxes = collections.defaultdict(list) with tf.io.gfile.GFile(csv_path) as csv_f: if csv_positions[0] > 0: csv_f.seek(csv_positions[0]) else: csv_f.readline() # Drop headers re...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _generate_examples(self, archive, directory): """Generate IMDB examples."""
reg = re.compile(os.path.join("^%s" % directory, "(?P<label>neg|pos)", "")) for path, imdb_f in archive: res = reg.match(path) if not res: continue text = imdb_f.read().strip() yield { "text": text, "label": res.groupdict()["label"], }
<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_url_hashes(path): """Get hashes of urls in file."""
urls = _read_text_file(path) def url_hash(u): h = hashlib.sha1() try: u = u.encode('utf-8') except UnicodeDecodeError: logging.error('Cannot hash url: %s', u) h.update(u) return h.hexdigest() return {url_hash(u): True for u in urls}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _find_files(dl_paths, publisher, url_dict): """Find files corresponding to urls."""
if publisher == 'cnn': top_dir = os.path.join(dl_paths['cnn_stories'], 'cnn', 'stories') elif publisher == 'dm': top_dir = os.path.join(dl_paths['dm_stories'], 'dailymail', 'stories') else: logging.fatal('Unsupported publisher: %s', publisher) files = tf.io.gfile.listdir(top_dir) ret_files = [] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _subset_filenames(dl_paths, split): """Get filenames for a particular split."""
assert isinstance(dl_paths, dict), dl_paths # Get filenames for a split. if split == tfds.Split.TRAIN: urls = _get_url_hashes(dl_paths['train_urls']) elif split == tfds.Split.VALIDATION: urls = _get_url_hashes(dl_paths['val_urls']) elif split == tfds.Split.TEST: urls = _get_url_hashes(dl_paths['t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def exporter(directory, method, datasets): """Export the results."""
if method.lower() == 'json': # Convert json_dict to a JSON styled string json_string = json.dumps(datasets, indent=4) savefile = open('{}/exported.json'.format(directory), 'w+') savefile.write(json_string) savefile.close() if method.lower() == 'csv': with open('...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def time_machine(host, mode): """Query archive.org."""
now = datetime.datetime.now() to = str(now.year) + str(now.day) + str(now.month) if now.month > 6: fro = str(now.year) + str(now.day) + str(now.month - 6) else: fro = str(now.year - 1) + str(now.day) + str(now.month + 6) url = "http://web.archive.org/cdx/search?url=%s&matchType=%s&collaps...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def zap(input_url, archive, domain, host, internal, robots, proxies): """Extract links from robots.txt and sitemap.xml."""
if archive: print('%s Fetching URLs from archive.org' % run) if False: archived_urls = time_machine(domain, 'domain') else: archived_urls = time_machine(host, 'host') print('%s Retrieved %i URLs from archive.org' % ( good, len(archived_urls) - 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 requester( url, main_url=None, delay=0, cook=None, headers=None, timeout=10, host=None, proxies=[None], user_agents=[None], failed=None, processed=None ): ""...
cook = cook or set() headers = headers or set() user_agents = user_agents or ['Photon'] failed = failed or set() processed = processed or set() # Mark the URL as crawled processed.add(url) # Pause/sleep the program for specified time time.sleep(delay) def make_request(url): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def intel_extractor(url, response): """Extract intel from the response body."""
for rintel in rintels: res = re.sub(r'<(script).*?</\1>(?s)', '', response) res = re.sub(r'<[^<]+?>', '', res) matches = rintel[0].findall(res) if matches: for match in matches: verb('Intel', match) bad_intel.add((match, rintel[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 js_extractor(response): """Extract js files from the response body"""
# Extract .js files matches = rscript.findall(response) for match in matches: match = match[2].replace('\'', '').replace('"', '') verb('JS file', match) bad_scripts.add(match)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extractor(url): """Extract details from the response body."""
response = requester(url, main_url, delay, cook, headers, timeout, host, proxies, user_agents, failed, processed) if clone: mirror(url, response) matches = rhref.findall(response) for link in matches: # Remove everything after a "#" to deal with in-page anchors link = lin...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def jscanner(url): """Extract endpoints from JavaScript code."""
response = requester(url, main_url, delay, cook, headers, timeout, host, proxies, user_agents, failed, processed) # Extract URLs/endpoints matches = rendpoint.findall(response) # Iterate over the matches, match is a tuple for match in matches: # Combining the items because one of them...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def updater(): """Update the current installation. git clones the latest version and merges it with the current directory. """
print('%s Checking for updates' % run) # Changes must be separated by ; changes = '''major bug fixes;removed ninja mode;dropped python < 3.2 support;fixed unicode output;proxy support;more intels''' latest_commit = requester('https://raw.githubusercontent.com/s0md3v/Photon/master/core/updater.py', host...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_subdomains(domain): """Find subdomains according to the TLD."""
result = set() response = get('https://findsubdomains.com/subdomains-of/' + domain).text matches = findall(r'(?s)<div class="domains js-domain-name">(.*?)</div>', response) for match in matches: result.add(match.replace(' ', '').replace('\n', '')) return list(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 flash(function, links, thread_count): """Process the URLs and uses a threadpool to execute a function."""
# Convert links (set) to list links = list(links) threadpool = concurrent.futures.ThreadPoolExecutor( max_workers=thread_count) futures = (threadpool.submit(function, link) for link in links) for i, _ in enumerate(concurrent.futures.as_completed(futures)): if i + 1 == len(links)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def regxy(pattern, response, supress_regex, custom): """Extract a string based on regex pattern supplied by user."""
try: matches = re.findall(r'%s' % pattern, response) for match in matches: verb('Custom regex', match) custom.add(match) except: supress_regex = 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 is_link(url, processed, files): """ Determine whether or not a link should be crawled A url should not be crawled if it - Is a file - Has already been crawle...
if url not in processed: is_file = url.endswith(BAD_TYPES) if is_file: files.add(url) return False return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_regex(urls, regex): """ Parse a list for non-matches to a regex. Args: urls: iterable of urls regex: string regex to be parsed for Returns: list of st...
if not regex: return urls # To avoid iterating over the characters of a string if not isinstance(urls, (list, set, tuple)): urls = [urls] try: non_matching_urls = [url for url in urls if not re.search(regex, url)] except TypeError: return [] return non_matchi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def writer(datasets, dataset_names, output_dir): """Write the results."""
for dataset, dataset_name in zip(datasets, dataset_names): if dataset: filepath = output_dir + '/' + dataset_name + '.txt' with open(filepath, 'w+') as out_file: joined = '\n'.join(dataset) out_file.write(str(joined.encode('utf-8').decode('utf-8'))) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def timer(diff, processed): """Return the passed time."""
# Changes seconds into minutes and seconds minutes, seconds = divmod(diff, 60) try: # Finds average time taken by requests time_per_request = diff / float(len(processed)) except ZeroDivisionError: time_per_request = 0 return minutes, seconds, time_per_request
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def entropy(string): """Calculate the entropy of a string."""
entropy = 0 for number in range(256): result = float(string.encode('utf-8').count( chr(number))) / len(string.encode('utf-8')) if result != 0: entropy = entropy - result * math.log(result, 2) 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 extract_headers(headers): """This function extracts valid headers from interactive input."""
sorted_headers = {} matches = re.findall(r'(.*):\s(.*)', headers) for match in matches: header = match[0] value = match[1] try: if value[-1] == ',': value = value[:-1] sorted_headers[header] = value except IndexError: 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 top_level(url, fix_protocol=True): """Extract the top level domain from an URL."""
ext = tld.get_tld(url, fix_protocol=fix_protocol) toplevel = '.'.join(urlparse(url).netloc.split('.')[-2:]).split( ext)[0] + ext return toplevel
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prompt(default=None): """Present the user a prompt."""
editor = 'nano' with tempfile.NamedTemporaryFile(mode='r+') as tmpfile: if default: tmpfile.write(default) tmpfile.flush() child_pid = os.fork() is_child = child_pid == 0 if is_child: os.execvp(editor, [editor, tmpfile.name]) else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self): """generator driven data flow """
# 如果出现了日期的改变 才会进行结算的事件 _date = None while QA_util_if_tradetime(self.now): for data in self.ingest_data: # 对于在ingest_data中的数据 # <class 'QUANTAXIS.QAData.QADataStruct.QA_DataStruct_Stock_day'> date = data.date[0] if self.market_type is...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def message(self): 'the standard message which can be transfer' return { 'source': 'account', 'frequence': self.frequence, 'account_cookie': self.account_cookie, 'portfolio_cookie': self.portfolio_cookie, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def QA_fetch_get_sh_margin(date): """return shanghai margin data Arguments: date {str YYYY-MM-DD} -- date format Returns: pandas.DataFrame -- res for margin data...
if date in trade_date_sse: data= pd.read_excel(_sh_url.format(QA_util_date_str2int (date)), 1).assign(date=date).assign(sse='sh') data.columns=['code','name','leveraged_balance','leveraged_buyout','leveraged_payoff','margin_left','margin_sell...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def QA_fetch_get_sz_margin(date): """return shenzhen margin data Arguments: date {str YYYY-MM-DD} -- date format Returns: pandas.DataFrame -- res for margin data...
if date in trade_date_sse: return pd.read_excel(_sz_url.format(date)).assign(date=date).assign(sse='sz')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def kline_echarts(self, code=None): def kline_formater(param): return param.name + ':' + vars(param) """plot the market_data"""
if code is None: path_name = '.' + os.sep + 'QA_' + self.type + \ '_codepackage_' + self.if_fq + '.html' kline = Kline( 'CodePackage_' + self.if_fq + '_' + self.type, width=1360, height=700, page_title='QUAN...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_tushare(dataframe, dtype='day'): """dataframe from tushare Arguments: dataframe {[type]} -- [description] Returns: [type] -- [description] """
if dtype in ['day']: return QA_DataStruct_Stock_day( dataframe.assign(date=pd.to_datetime(dataframe.date) ).set_index(['date', 'code'], drop=False), dtype='stock_day' ...
<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, cache_file): """Create the tables needed to store the information."""
conn = sqlite3.connect(cache_file) cur = conn.cursor() cur.execute("PRAGMA foreign_keys = ON") cur.execute(''' CREATE TABLE jobs( hash TEXT NOT NULL UNIQUE PRIMARY KEY, description TEXT NOT NULL, last_run REAL, next_run REAL, last_run_result I...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def QA_SU_save_stock_info(engine, client=DATABASE): """save stock info Arguments: engine {[type]} -- [description] Keyword Arguments: client {[type]} -- [descrip...
engine = select_save_engine(engine) engine.QA_SU_save_stock_info(client=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 QA_fetch_risk(message={}, params={"_id": 0, 'assets': 0, 'timeindex': 0, 'totaltimeindex': 0, 'benchmark_assets': 0, 'month_profit': 0}, db=DATABASE): """get...
collection = DATABASE.risk return [res for res in collection.find(message, 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 QA_fetch_user(user_cookie, db=DATABASE): """ get the user Arguments: user_cookie : str the unique cookie_id for a user Keyword Arguments: db: database for qu...
collection = DATABASE.account return [res for res in collection.find({'user_cookie': user_cookie}, {"_id": 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 do_shell(self, arg): "run a shell commad" print(">", arg) sub_cmd = subprocess.Popen(arg, shell=True, stdout=subprocess.PIPE) print(sub_cmd.communicate()[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 get_response(self, statement=None, **kwargs): """ Return the bot's response based on the input. :param statement: An statement object or string. :returns: A ...
Statement = self.storage.get_object('statement') additional_response_selection_parameters = kwargs.pop('additional_response_selection_parameters', {}) persist_values_to_response = kwargs.pop('persist_values_to_response', {}) if isinstance(statement, str): kwargs['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 generate_response(self, input_statement, additional_response_selection_parameters=None): """ Return a response based on a given input statement. :param input...
Statement = self.storage.get_object('statement') results = [] result = None max_confidence = -1 for adapter in self.logic_adapters: if adapter.can_process(input_statement): output = adapter.process(input_statement, additional_response_selection_par...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def learn_response(self, statement, previous_statement=None): """ Learn that the statement provided is a valid response. """
if not previous_statement: previous_statement = statement.in_response_to if not previous_statement: previous_statement = self.get_latest_response(statement.conversation) if previous_statement: previous_statement = previous_statement.text pre...
<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_module(dotted_path): """ Imports the specified module based on the dot notated import path for the module. """
import importlib module_parts = dotted_path.split('.') module_path = '.'.join(module_parts[:-1]) module = importlib.import_module(module_path) return getattr(module, module_parts[-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 validate_adapter_class(validate_class, adapter_class): """ Raises an exception if validate_class is not a subclass of adapter_class. :param validate_class: T...
from chatterbot.adapters import Adapter # If a dictionary was passed in, check if it has an import_path attribute if isinstance(validate_class, dict): if 'import_path' not in validate_class: raise Adapter.InvalidAdapterTypeException( 'The dictionary {} must contain a 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 get_response_time(chatbot, statement='Hello'): """ Returns the amount of time taken for a given chat bot to return a response. :param chatbot: A chat bot ins...
import time start_time = time.time() chatbot.get_response(statement) return time.time() - start_time
<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_valid_units(self, ureg, from_unit, target_unit): """ Returns the firt match `pint.unit.Unit` object for from_unit and target_unit strings from a possible...
from_unit_variations = [from_unit.lower(), from_unit.upper()] target_unit_variations = [target_unit.lower(), target_unit.upper()] from_unit = self.get_unit(ureg, from_unit_variations) target_unit = self.get_unit(ureg, target_unit_variations) return from_unit, target_unit
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle_matches(self, match): """ Returns a response statement from a matched input statement. :param match: It is a valid matched pattern from the input stat...
response = Statement(text='') from_parsed = match.group("from") target_parsed = match.group("target") n_statement = match.group("number") if n_statement == 'a' or n_statement == 'an': n_statement = '1.0' n = mathparse.parse(n_statement, self.language.ISO_6...
<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_default_response(self, input_statement): """ This method is called when a logic adapter is unable to generate any other meaningful response. """
from random import choice if self.default_responses: response = choice(self.default_responses) else: try: response = self.chatbot.storage.get_random() except StorageAdapter.EmptyDatabaseException: response = input_statement ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def time_question_features(self, text): """ Provide an analysis of significant features in the string. """
features = {} # A list of all words from the known sentences all_words = " ".join(self.positive + self.negative).split() # A list of the first word in each of the known sentence all_first_words = [] for sentence in self.positive + self.negative: all_first_w...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def can_process(self, statement): """ Determines whether it is appropriate for this adapter to respond to the user input. """
response = self.process(statement) self.cache[statement.text] = response return response.confidence == 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 process(self, statement, additional_response_selection_parameters=None): """ Takes a statement string. Returns the equation from the statement with the mathe...
from mathparse import mathparse input_text = statement.text # Use the result cached by the process method if it exists if input_text in self.cache: cached_result = self.cache[input_text] self.cache = {} return cached_result # Getting the ma...
<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_recent_repeated_responses(chatbot, conversation, sample=10, threshold=3, quantity=3): """ A filter that eliminates possibly repetitive responses to preve...
from collections import Counter # Get the most recent statements from the conversation conversation_statements = list(chatbot.storage.filter( conversation=conversation, order_by=['id'] ))[sample * -1:] text_of_recent_responses = [ statement.text for statement in conversati...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compare(self, statement_a, statement_b): """ Return the calculated similarity of two statements based on the Jaccard index. """
# Make both strings lowercase document_a = self.nlp(statement_a.text.lower()) document_b = self.nlp(statement_b.text.lower()) statement_a_lemmas = set([ token.lemma_ for token in document_a if not token.is_stop ]) statement_b_lemmas = set([ token...
<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_statement_model(self): """ Return the class for the statement model. """
from chatterbot.conversation import Statement # Create a storage-aware statement statement = Statement statement.storage = self return statement
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mongo_to_object(self, statement_data): """ Return Statement object when given data returned from Mongo DB. """
Statement = self.get_model('statement') statement_data['id'] = statement_data['_id'] return Statement(**statement_data)