repo stringclasses 85
values | path stringlengths 8 121 | func_name stringlengths 1 82 | original_string stringlengths 112 65.5k | language stringclasses 1
value | code stringlengths 112 65.5k | code_tokens listlengths 20 4.09k | docstring stringlengths 3 46.3k | docstring_tokens listlengths 1 564 | sha stringclasses 85
values | url stringlengths 93 218 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
tensorflow/datasets | tensorflow_datasets/core/dataset_utils.py | build_dataset | def build_dataset(instruction_dicts,
dataset_from_file_fn,
shuffle_files=False,
parallel_reads=64):
"""Constructs a `tf.data.Dataset` from TFRecord files.
Args:
instruction_dicts: `list` of {'filepath':, 'mask':, 'offset_mask':}
containing the informa... | python | def build_dataset(instruction_dicts,
dataset_from_file_fn,
shuffle_files=False,
parallel_reads=64):
"""Constructs a `tf.data.Dataset` from TFRecord files.
Args:
instruction_dicts: `list` of {'filepath':, 'mask':, 'offset_mask':}
containing the informa... | [
"def",
"build_dataset",
"(",
"instruction_dicts",
",",
"dataset_from_file_fn",
",",
"shuffle_files",
"=",
"False",
",",
"parallel_reads",
"=",
"64",
")",
":",
"# First case: All examples are taken (No value skipped)",
"if",
"_no_examples_skipped",
"(",
"instruction_dicts",
... | Constructs a `tf.data.Dataset` from TFRecord files.
Args:
instruction_dicts: `list` of {'filepath':, 'mask':, 'offset_mask':}
containing the information about which files and which examples to use.
The boolean mask will be repeated and zipped with the examples from
filepath.
dataset_from_fi... | [
"Constructs",
"a",
"tf",
".",
"data",
".",
"Dataset",
"from",
"TFRecord",
"files",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/dataset_utils.py#L32-L76 | train |
tensorflow/datasets | tensorflow_datasets/core/dataset_utils.py | _build_instruction_ds | def _build_instruction_ds(instructions):
"""Create a dataset containing individual instruction for each shard.
Each instruction is a dict:
```
{
"filepath": tf.Tensor(shape=(), dtype=tf.string),
"mask_offset": tf.Tensor(shape=(), dtype=tf.int64),
"mask": tf.Tensor(shape=(100,), dtype=tf.bool)... | python | def _build_instruction_ds(instructions):
"""Create a dataset containing individual instruction for each shard.
Each instruction is a dict:
```
{
"filepath": tf.Tensor(shape=(), dtype=tf.string),
"mask_offset": tf.Tensor(shape=(), dtype=tf.int64),
"mask": tf.Tensor(shape=(100,), dtype=tf.bool)... | [
"def",
"_build_instruction_ds",
"(",
"instructions",
")",
":",
"# Transpose the list[dict] into dict[list]",
"tensor_inputs",
"=",
"{",
"# offset_mask need to be converted to int64 explicitly",
"k",
":",
"np",
".",
"array",
"(",
"vals",
",",
"dtype",
"=",
"np",
".",
"in... | Create a dataset containing individual instruction for each shard.
Each instruction is a dict:
```
{
"filepath": tf.Tensor(shape=(), dtype=tf.string),
"mask_offset": tf.Tensor(shape=(), dtype=tf.int64),
"mask": tf.Tensor(shape=(100,), dtype=tf.bool),
}
```
Args:
instructions: `list[d... | [
"Create",
"a",
"dataset",
"containing",
"individual",
"instruction",
"for",
"each",
"shard",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/dataset_utils.py#L84-L109 | train |
tensorflow/datasets | tensorflow_datasets/core/dataset_utils.py | _build_mask_ds | 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 following elements. This
mask should have a length 100.
mask_offset: `tf.Tensor`, Integer specifying from how much the mask
should be shifted ... | python | 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 following elements. This
mask should have a length 100.
mask_offset: `tf.Tensor`, Integer specifying from how much the mask
should be shifted ... | [
"def",
"_build_mask_ds",
"(",
"mask",
",",
"mask_offset",
")",
":",
"mask_ds",
"=",
"tf",
".",
"data",
".",
"Dataset",
".",
"from_tensor_slices",
"(",
"mask",
")",
"mask_ds",
"=",
"mask_ds",
".",
"repeat",
"(",
")",
"mask_ds",
"=",
"mask_ds",
".",
"skip"... | Build the mask dataset to indicate which element to skip.
Args:
mask: `tf.Tensor`, binary mask to apply to all following elements. This
mask should have a length 100.
mask_offset: `tf.Tensor`, Integer specifying from how much the mask
should be shifted for the first element.
Returns:
mask_... | [
"Build",
"the",
"mask",
"dataset",
"to",
"indicate",
"which",
"element",
"to",
"skip",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/dataset_utils.py#L112-L128 | train |
tensorflow/datasets | tensorflow_datasets/core/dataset_utils.py | _build_ds_from_instruction | 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 `tf.Tensor` containing the instruction to load
the particular shard (filename, mask,...)
ds_from_file_fn: `fct`, function which returns the d... | python | 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 `tf.Tensor` containing the instruction to load
the particular shard (filename, mask,...)
ds_from_file_fn: `fct`, function which returns the d... | [
"def",
"_build_ds_from_instruction",
"(",
"instruction",
",",
"ds_from_file_fn",
")",
":",
"# Create the example and mask ds for this particular shard",
"examples_ds",
"=",
"ds_from_file_fn",
"(",
"instruction",
"[",
"\"filepath\"",
"]",
")",
"mask_ds",
"=",
"_build_mask_ds",... | Map an instruction to a real datasets for one particular shard.
Args:
instruction: A `dict` of `tf.Tensor` containing the instruction to load
the particular shard (filename, mask,...)
ds_from_file_fn: `fct`, function which returns the dataset associated to
the filename
Returns:
dataset: `t... | [
"Map",
"an",
"instruction",
"to",
"a",
"real",
"datasets",
"for",
"one",
"particular",
"shard",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/dataset_utils.py#L131-L156 | train |
tensorflow/datasets | tensorflow_datasets/core/dataset_utils.py | as_numpy | 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.Dataset`s
and `tf.Tensor`s to iterables of NumPy arrays and NumPy arrays, respectively.
Args:
dataset: a possibly nested structure of `tf.data.Data... | python | 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.Dataset`s
and `tf.Tensor`s to iterables of NumPy arrays and NumPy arrays, respectively.
Args:
dataset: a possibly nested structure of `tf.data.Data... | [
"def",
"as_numpy",
"(",
"dataset",
",",
"graph",
"=",
"None",
")",
":",
"nested_ds",
"=",
"dataset",
"del",
"dataset",
"# Flatten",
"flat_ds",
"=",
"tf",
".",
"nest",
".",
"flatten",
"(",
"nested_ds",
")",
"flat_np",
"=",
"[",
"]",
"# Type check for Tensor... | Converts a `tf.data.Dataset` to an iterable of NumPy arrays.
`as_numpy` converts a possibly nested structure of `tf.data.Dataset`s
and `tf.Tensor`s to iterables of NumPy arrays and NumPy arrays, respectively.
Args:
dataset: a possibly nested structure of `tf.data.Dataset`s and/or
`tf.Tensor`s.
gra... | [
"Converts",
"a",
"tf",
".",
"data",
".",
"Dataset",
"to",
"an",
"iterable",
"of",
"NumPy",
"arrays",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/dataset_utils.py#L176-L242 | train |
tensorflow/datasets | tensorflow_datasets/image/shapes3d.py | _load_data | 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... | python | 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... | [
"def",
"_load_data",
"(",
"filepath",
")",
":",
"with",
"h5py",
".",
"File",
"(",
"filepath",
",",
"\"r\"",
")",
"as",
"h5dataset",
":",
"image_array",
"=",
"np",
".",
"array",
"(",
"h5dataset",
"[",
"\"images\"",
"]",
")",
"# The 'label' data set in the hdf... | Loads the images and latent values into Numpy arrays. | [
"Loads",
"the",
"images",
"and",
"latent",
"values",
"into",
"Numpy",
"arrays",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/image/shapes3d.py#L151-L158 | train |
tensorflow/datasets | tensorflow_datasets/image/shapes3d.py | _discretize | 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_... | python | 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_... | [
"def",
"_discretize",
"(",
"a",
")",
":",
"arr",
"=",
"np",
".",
"asarray",
"(",
"a",
")",
"index",
"=",
"np",
".",
"argsort",
"(",
"arr",
")",
"inverse_index",
"=",
"np",
".",
"zeros",
"(",
"arr",
".",
"size",
",",
"dtype",
"=",
"np",
".",
"in... | Discretizes array values to class labels. | [
"Discretizes",
"array",
"values",
"to",
"class",
"labels",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/image/shapes3d.py#L163-L171 | train |
tensorflow/datasets | tensorflow_datasets/image/shapes3d.py | Shapes3d._generate_examples | def _generate_examples(self, filepath):
"""Generate examples for the Shapes3d dataset.
Args:
filepath: path to the Shapes3d hdf5 file.
Yields:
Dictionaries with images and the different labels.
"""
# Simultaneously iterating through the different data sets in the hdf5
# file will b... | python | def _generate_examples(self, filepath):
"""Generate examples for the Shapes3d dataset.
Args:
filepath: path to the Shapes3d hdf5 file.
Yields:
Dictionaries with images and the different labels.
"""
# Simultaneously iterating through the different data sets in the hdf5
# file will b... | [
"def",
"_generate_examples",
"(",
"self",
",",
"filepath",
")",
":",
"# 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",
",",
"val... | Generate examples for the Shapes3d dataset.
Args:
filepath: path to the Shapes3d hdf5 file.
Yields:
Dictionaries with images and the different labels. | [
"Generate",
"examples",
"for",
"the",
"Shapes3d",
"dataset",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/image/shapes3d.py#L113-L148 | train |
tensorflow/datasets | tensorflow_datasets/text/wikipedia.py | _parse_and_clean_wikicode | 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.IG... | python | 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.IG... | [
"def",
"_parse_and_clean_wikicode",
"(",
"raw_content",
")",
":",
"wikicode",
"=",
"tfds",
".",
"core",
".",
"lazy_imports",
".",
"mwparserfromhell",
".",
"parse",
"(",
"raw_content",
")",
"# Filters for references, tables, and file/image links.",
"re_rm_wikilink",
"=",
... | Strips formatting and unwanted sections from raw page content. | [
"Strips",
"formatting",
"and",
"unwanted",
"sections",
"from",
"raw",
"page",
"content",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/text/wikipedia.py#L234-L269 | train |
tensorflow/datasets | tensorflow_datasets/text/wikipedia.py | Wikipedia._build_pcollection | def _build_pcollection(self, pipeline, filepaths, language):
"""Build PCollection of examples in the raw (text) form."""
beam = tfds.core.lazy_imports.apache_beam
def _extract_content(filepath):
"""Extracts article content from a single WikiMedia XML file."""
logging.info("generating examples ... | python | def _build_pcollection(self, pipeline, filepaths, language):
"""Build PCollection of examples in the raw (text) form."""
beam = tfds.core.lazy_imports.apache_beam
def _extract_content(filepath):
"""Extracts article content from a single WikiMedia XML file."""
logging.info("generating examples ... | [
"def",
"_build_pcollection",
"(",
"self",
",",
"pipeline",
",",
"filepaths",
",",
"language",
")",
":",
"beam",
"=",
"tfds",
".",
"core",
".",
"lazy_imports",
".",
"apache_beam",
"def",
"_extract_content",
"(",
"filepath",
")",
":",
"\"\"\"Extracts article conte... | Build PCollection of examples in the raw (text) form. | [
"Build",
"PCollection",
"of",
"examples",
"in",
"the",
"raw",
"(",
"text",
")",
"form",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/text/wikipedia.py#L176-L231 | train |
tensorflow/datasets | tensorflow_datasets/scripts/download_and_prepare.py | download_and_prepare | 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): Re... | python | 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): Re... | [
"def",
"download_and_prepare",
"(",
"builder",
")",
":",
"print",
"(",
"\"download_and_prepare for dataset {}...\"",
".",
"format",
"(",
"builder",
".",
"info",
".",
"full_name",
")",
")",
"dl_config",
"=",
"download_config",
"(",
")",
"if",
"isinstance",
"(",
"... | Generate data for a given dataset. | [
"Generate",
"data",
"for",
"a",
"given",
"dataset",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/scripts/download_and_prepare.py#L113-L135 | train |
tensorflow/datasets | tensorflow_datasets/core/features/bounding_boxes.py | BBoxFeature.encode_example | def encode_example(self, bbox):
"""See base class for details."""
# Validate the coordinates
for coordinate in bbox:
if not isinstance(coordinate, float):
raise ValueError(
'BBox coordinates should be float. Got {}.'.format(bbox))
if not 0.0 <= coordinate <= 1.0:
rais... | python | def encode_example(self, bbox):
"""See base class for details."""
# Validate the coordinates
for coordinate in bbox:
if not isinstance(coordinate, float):
raise ValueError(
'BBox coordinates should be float. Got {}.'.format(bbox))
if not 0.0 <= coordinate <= 1.0:
rais... | [
"def",
"encode_example",
"(",
"self",
",",
"bbox",
")",
":",
"# Validate the coordinates",
"for",
"coordinate",
"in",
"bbox",
":",
"if",
"not",
"isinstance",
"(",
"coordinate",
",",
"float",
")",
":",
"raise",
"ValueError",
"(",
"'BBox coordinates should be float.... | See base class for details. | [
"See",
"base",
"class",
"for",
"details",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/features/bounding_boxes.py#L60-L76 | train |
tensorflow/datasets | tensorflow_datasets/image/cifar.py | _load_data | def _load_data(path, labels_number=1):
"""Yields (labels, np_image) tuples."""
with tf.io.gfile.GFile(path, "rb") as f:
data = f.read()
offset = 0
max_offset = len(data) - 1
while offset < max_offset:
labels = np.frombuffer(data, dtype=np.uint8, count=labels_number,
offset=o... | python | def _load_data(path, labels_number=1):
"""Yields (labels, np_image) tuples."""
with tf.io.gfile.GFile(path, "rb") as f:
data = f.read()
offset = 0
max_offset = len(data) - 1
while offset < max_offset:
labels = np.frombuffer(data, dtype=np.uint8, count=labels_number,
offset=o... | [
"def",
"_load_data",
"(",
"path",
",",
"labels_number",
"=",
"1",
")",
":",
"with",
"tf",
".",
"io",
".",
"gfile",
".",
"GFile",
"(",
"path",
",",
"\"rb\"",
")",
"as",
"f",
":",
"data",
"=",
"f",
".",
"read",
"(",
")",
"offset",
"=",
"0",
"max_... | Yields (labels, np_image) tuples. | [
"Yields",
"(",
"labels",
"np_image",
")",
"tuples",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/image/cifar.py#L191-L207 | train |
tensorflow/datasets | tensorflow_datasets/image/cifar.py | Cifar10._split_generators | def _split_generators(self, dl_manager):
"""Returns SplitGenerators."""
cifar_path = dl_manager.download_and_extract(self._cifar_info.url)
cifar_info = self._cifar_info
cifar_path = os.path.join(cifar_path, cifar_info.prefix)
# Load the label names
for label_key, label_file in zip(cifar_info.l... | python | def _split_generators(self, dl_manager):
"""Returns SplitGenerators."""
cifar_path = dl_manager.download_and_extract(self._cifar_info.url)
cifar_info = self._cifar_info
cifar_path = os.path.join(cifar_path, cifar_info.prefix)
# Load the label names
for label_key, label_file in zip(cifar_info.l... | [
"def",
"_split_generators",
"(",
"self",
",",
"dl_manager",
")",
":",
"cifar_path",
"=",
"dl_manager",
".",
"download_and_extract",
"(",
"self",
".",
"_cifar_info",
".",
"url",
")",
"cifar_info",
"=",
"self",
".",
"_cifar_info",
"cifar_path",
"=",
"os",
".",
... | Returns SplitGenerators. | [
"Returns",
"SplitGenerators",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/image/cifar.py#L79-L108 | train |
tensorflow/datasets | tensorflow_datasets/image/cifar.py | Cifar10._generate_examples | def _generate_examples(self, filepaths):
"""Generate CIFAR examples as dicts.
Shared across CIFAR-{10, 100}. Uses self._cifar_info as
configuration.
Args:
filepaths (list[str]): The files to use to generate the data.
Yields:
The cifar examples, as defined in the dataset info features.... | python | def _generate_examples(self, filepaths):
"""Generate CIFAR examples as dicts.
Shared across CIFAR-{10, 100}. Uses self._cifar_info as
configuration.
Args:
filepaths (list[str]): The files to use to generate the data.
Yields:
The cifar examples, as defined in the dataset info features.... | [
"def",
"_generate_examples",
"(",
"self",
",",
"filepaths",
")",
":",
"label_keys",
"=",
"self",
".",
"_cifar_info",
".",
"label_keys",
"for",
"path",
"in",
"filepaths",
":",
"for",
"labels",
",",
"np_image",
"in",
"_load_data",
"(",
"path",
",",
"len",
"(... | Generate CIFAR examples as dicts.
Shared across CIFAR-{10, 100}. Uses self._cifar_info as
configuration.
Args:
filepaths (list[str]): The files to use to generate the data.
Yields:
The cifar examples, as defined in the dataset info features. | [
"Generate",
"CIFAR",
"examples",
"as",
"dicts",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/image/cifar.py#L110-L127 | train |
tensorflow/datasets | tensorflow_datasets/core/api_utils.py | disallow_positional_args | 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_positiona... | python | 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_positiona... | [
"def",
"disallow_positional_args",
"(",
"wrapped",
"=",
"None",
",",
"allowed",
"=",
"None",
")",
":",
"# See",
"# https://wrapt.readthedocs.io/en/latest/decorators.html#decorators-with-optional-arguments",
"# for decorator pattern.",
"if",
"wrapped",
"is",
"None",
":",
"retu... | Requires function to be called using keyword arguments. | [
"Requires",
"function",
"to",
"be",
"called",
"using",
"keyword",
"arguments",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/api_utils.py#L39-L54 | train |
tensorflow/datasets | tensorflow_datasets/core/api_utils.py | _required_args | 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] | python | 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] | [
"def",
"_required_args",
"(",
"fn",
")",
":",
"spec",
"=",
"getargspec",
"(",
"fn",
")",
"if",
"not",
"spec",
".",
"defaults",
":",
"return",
"[",
"]",
"arg_names",
"=",
"spec",
".",
"args",
"[",
"-",
"len",
"(",
"spec",
".",
"defaults",
")",
":",
... | Returns arguments of fn with default=REQUIRED_ARG. | [
"Returns",
"arguments",
"of",
"fn",
"with",
"default",
"=",
"REQUIRED_ARG",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/api_utils.py#L67-L75 | train |
tensorflow/datasets | tensorflow_datasets/core/utils/gcs_utils.py | download_gcs_file | 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 V... | python | 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 V... | [
"def",
"download_gcs_file",
"(",
"path",
",",
"out_fname",
"=",
"None",
",",
"prefix_filter",
"=",
"None",
")",
":",
"url",
"=",
"posixpath",
".",
"join",
"(",
"GCS_BUCKET",
",",
"path",
")",
"if",
"prefix_filter",
":",
"url",
"+=",
"\"?prefix=%s\"",
"%",
... | Download a file from GCS, optionally to a file. | [
"Download",
"a",
"file",
"from",
"GCS",
"optionally",
"to",
"a",
"file",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/utils/gcs_utils.py#L34-L48 | train |
tensorflow/datasets | tensorflow_datasets/core/utils/gcs_utils.py | gcs_files | 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 | python | 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 | [
"def",
"gcs_files",
"(",
"prefix_filter",
"=",
"None",
")",
":",
"top_level_xml_str",
"=",
"download_gcs_file",
"(",
"\"\"",
",",
"prefix_filter",
"=",
"prefix_filter",
")",
"xml_root",
"=",
"ElementTree",
".",
"fromstring",
"(",
"top_level_xml_str",
")",
"filenam... | List all files in GCS bucket. | [
"List",
"all",
"files",
"in",
"GCS",
"bucket",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/utils/gcs_utils.py#L52-L57 | train |
tensorflow/datasets | tensorflow_datasets/core/utils/gcs_utils.py | gcs_dataset_info_files | 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(pr... | python | 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(pr... | [
"def",
"gcs_dataset_info_files",
"(",
"dataset_dir",
")",
":",
"prefix",
"=",
"posixpath",
".",
"join",
"(",
"GCS_DATASET_INFO_DIR",
",",
"dataset_dir",
",",
"\"\"",
")",
"# Filter for this dataset",
"filenames",
"=",
"[",
"el",
"for",
"el",
"in",
"gcs_files",
"... | Return paths to GCS files in the given dataset directory. | [
"Return",
"paths",
"to",
"GCS",
"files",
"in",
"the",
"given",
"dataset",
"directory",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/utils/gcs_utils.py#L60-L66 | train |
tensorflow/datasets | tensorflow_datasets/core/utils/gcs_utils.py | is_dataset_on_gcs | def is_dataset_on_gcs(dataset_name):
"""If the dataset is available on the GCS bucket gs://tfds-data/datasets."""
dir_name = posixpath.join(GCS_DATASETS_DIR, dataset_name)
return len(gcs_files(prefix_filter=dir_name)) > 2 | python | def is_dataset_on_gcs(dataset_name):
"""If the dataset is available on the GCS bucket gs://tfds-data/datasets."""
dir_name = posixpath.join(GCS_DATASETS_DIR, dataset_name)
return len(gcs_files(prefix_filter=dir_name)) > 2 | [
"def",
"is_dataset_on_gcs",
"(",
"dataset_name",
")",
":",
"dir_name",
"=",
"posixpath",
".",
"join",
"(",
"GCS_DATASETS_DIR",
",",
"dataset_name",
")",
"return",
"len",
"(",
"gcs_files",
"(",
"prefix_filter",
"=",
"dir_name",
")",
")",
">",
"2"
] | If the dataset is available on the GCS bucket gs://tfds-data/datasets. | [
"If",
"the",
"dataset",
"is",
"available",
"on",
"the",
"GCS",
"bucket",
"gs",
":",
"//",
"tfds",
"-",
"data",
"/",
"datasets",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/utils/gcs_utils.py#L69-L72 | train |
tensorflow/datasets | tensorflow_datasets/core/download/kaggle.py | _run_kaggle_command | 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(... | python | 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(... | [
"def",
"_run_kaggle_command",
"(",
"command_args",
",",
"competition_name",
")",
":",
"try",
":",
"output",
"=",
"sp",
".",
"check_output",
"(",
"command_args",
")",
"return",
"tf",
".",
"compat",
".",
"as_text",
"(",
"output",
")",
"except",
"sp",
".",
"C... | Run kaggle command with subprocess. | [
"Run",
"kaggle",
"command",
"with",
"subprocess",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/download/kaggle.py#L138-L150 | train |
tensorflow/datasets | tensorflow_datasets/core/download/kaggle.py | KaggleCompetitionDownloader.competition_files | 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 s... | python | 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 s... | [
"def",
"competition_files",
"(",
"self",
")",
":",
"command",
"=",
"[",
"\"kaggle\"",
",",
"\"datasets\"",
"if",
"\"/\"",
"in",
"self",
".",
"_competition_name",
"else",
"\"competitions\"",
",",
"\"files\"",
",",
"\"-v\"",
",",
"self",
".",
"_competition_name",
... | List of competition files. | [
"List",
"of",
"competition",
"files",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/download/kaggle.py#L96-L108 | train |
tensorflow/datasets | tensorflow_datasets/core/download/kaggle.py | KaggleCompetitionDownloader.competition_urls | def competition_urls(self):
"""Returns 'kaggle://' urls."""
return [
KaggleFile(self._competition_name, fname).to_url()
for fname in self.competition_files # pylint: disable=not-an-iterable
] | python | def competition_urls(self):
"""Returns 'kaggle://' urls."""
return [
KaggleFile(self._competition_name, fname).to_url()
for fname in self.competition_files # pylint: disable=not-an-iterable
] | [
"def",
"competition_urls",
"(",
"self",
")",
":",
"return",
"[",
"KaggleFile",
"(",
"self",
".",
"_competition_name",
",",
"fname",
")",
".",
"to_url",
"(",
")",
"for",
"fname",
"in",
"self",
".",
"competition_files",
"# pylint: disable=not-an-iterable",
"]"
] | Returns 'kaggle://' urls. | [
"Returns",
"kaggle",
":",
"//",
"urls",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/download/kaggle.py#L111-L116 | train |
tensorflow/datasets | tensorflow_datasets/core/download/kaggle.py | KaggleCompetitionDownloader.download_file | 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))
... | python | 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))
... | [
"def",
"download_file",
"(",
"self",
",",
"fname",
",",
"output_dir",
")",
":",
"if",
"fname",
"not",
"in",
"self",
".",
"competition_files",
":",
"# pylint: disable=unsupported-membership-test",
"raise",
"ValueError",
"(",
"\"%s is not one of the competition's \"",
"\"... | Downloads competition file to output_dir. | [
"Downloads",
"competition",
"file",
"to",
"output_dir",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/download/kaggle.py#L118-L135 | train |
tensorflow/datasets | tensorflow_datasets/image/flowers.py | TFFlowers._generate_examples | 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 where the images are stored.
Yields:
The image path and its corresponding label.
"""
parent_dir = tf.io.gfile.listdir(images_... | python | 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 where the images are stored.
Yields:
The image path and its corresponding label.
"""
parent_dir = tf.io.gfile.listdir(images_... | [
"def",
"_generate_examples",
"(",
"self",
",",
"images_dir_path",
")",
":",
"parent_dir",
"=",
"tf",
".",
"io",
".",
"gfile",
".",
"listdir",
"(",
"images_dir_path",
")",
"[",
"0",
"]",
"walk_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"images_dir_pa... | Generate flower images and labels given the image directory path.
Args:
images_dir_path: path to the directory where the images are stored.
Yields:
The image path and its corresponding label. | [
"Generate",
"flower",
"images",
"and",
"labels",
"given",
"the",
"image",
"directory",
"path",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/image/flowers.py#L71-L93 | train |
tensorflow/datasets | tensorflow_datasets/core/download/checksums.py | _checksum_paths | def _checksum_paths():
"""Returns dict {'dataset_name': 'path/to/checksums/file'}."""
dataset2path = {}
for dir_path in _CHECKSUM_DIRS:
for fname in _list_dir(dir_path):
if not fname.endswith(_CHECKSUM_SUFFIX):
continue
fpath = os.path.join(dir_path, fname)
dataset_name = fname[:-len... | python | def _checksum_paths():
"""Returns dict {'dataset_name': 'path/to/checksums/file'}."""
dataset2path = {}
for dir_path in _CHECKSUM_DIRS:
for fname in _list_dir(dir_path):
if not fname.endswith(_CHECKSUM_SUFFIX):
continue
fpath = os.path.join(dir_path, fname)
dataset_name = fname[:-len... | [
"def",
"_checksum_paths",
"(",
")",
":",
"dataset2path",
"=",
"{",
"}",
"for",
"dir_path",
"in",
"_CHECKSUM_DIRS",
":",
"for",
"fname",
"in",
"_list_dir",
"(",
"dir_path",
")",
":",
"if",
"not",
"fname",
".",
"endswith",
"(",
"_CHECKSUM_SUFFIX",
")",
":",
... | Returns dict {'dataset_name': 'path/to/checksums/file'}. | [
"Returns",
"dict",
"{",
"dataset_name",
":",
"path",
"/",
"to",
"/",
"checksums",
"/",
"file",
"}",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/download/checksums.py#L46-L56 | train |
tensorflow/datasets | tensorflow_datasets/core/download/checksums.py | _get_path | 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_... | python | 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_... | [
"def",
"_get_path",
"(",
"dataset_name",
")",
":",
"path",
"=",
"_checksum_paths",
"(",
")",
".",
"get",
"(",
"dataset_name",
",",
"None",
")",
"if",
"path",
":",
"return",
"path",
"msg",
"=",
"(",
"'No checksums file could be find for dataset %s. Please create on... | Returns path to where checksums are stored for a given dataset. | [
"Returns",
"path",
"to",
"where",
"checksums",
"are",
"stored",
"for",
"a",
"given",
"dataset",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/download/checksums.py#L59-L66 | train |
tensorflow/datasets | tensorflow_datasets/core/download/checksums.py | _get_sizes_checksums | def _get_sizes_checksums(checksums_path):
"""Returns {URL: (size, checksum)}s stored within file."""
checksums = {}
for line in _read_file(checksums_path).split('\n'):
if not line:
continue
# URL might have spaces inside, but size and checksum will not.
url, size, checksum = line.rsplit(' ', 2)
... | python | def _get_sizes_checksums(checksums_path):
"""Returns {URL: (size, checksum)}s stored within file."""
checksums = {}
for line in _read_file(checksums_path).split('\n'):
if not line:
continue
# URL might have spaces inside, but size and checksum will not.
url, size, checksum = line.rsplit(' ', 2)
... | [
"def",
"_get_sizes_checksums",
"(",
"checksums_path",
")",
":",
"checksums",
"=",
"{",
"}",
"for",
"line",
"in",
"_read_file",
"(",
"checksums_path",
")",
".",
"split",
"(",
"'\\n'",
")",
":",
"if",
"not",
"line",
":",
"continue",
"# URL might have spaces insi... | Returns {URL: (size, checksum)}s stored within file. | [
"Returns",
"{",
"URL",
":",
"(",
"size",
"checksum",
")",
"}",
"s",
"stored",
"within",
"file",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/download/checksums.py#L75-L84 | train |
tensorflow/datasets | tensorflow_datasets/core/download/checksums.py | get_all_sizes_checksums | def get_all_sizes_checksums():
"""Returns dict associating URL to (size, sha256)."""
sizes_checksums = {}
for path in _checksum_paths().values():
data = _get_sizes_checksums(path)
for url, size_checksum in data.items():
if (url in sizes_checksums and
sizes_checksums[url] != size_checksum):... | python | def get_all_sizes_checksums():
"""Returns dict associating URL to (size, sha256)."""
sizes_checksums = {}
for path in _checksum_paths().values():
data = _get_sizes_checksums(path)
for url, size_checksum in data.items():
if (url in sizes_checksums and
sizes_checksums[url] != size_checksum):... | [
"def",
"get_all_sizes_checksums",
"(",
")",
":",
"sizes_checksums",
"=",
"{",
"}",
"for",
"path",
"in",
"_checksum_paths",
"(",
")",
".",
"values",
"(",
")",
":",
"data",
"=",
"_get_sizes_checksums",
"(",
"path",
")",
"for",
"url",
",",
"size_checksum",
"i... | Returns dict associating URL to (size, sha256). | [
"Returns",
"dict",
"associating",
"URL",
"to",
"(",
"size",
"sha256",
")",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/download/checksums.py#L88-L99 | train |
tensorflow/datasets | tensorflow_datasets/core/download/checksums.py | store_checksums | def store_checksums(dataset_name, sizes_checksums):
"""Store given checksums and sizes for specific dataset.
Content of file is never disgarded, only updated. This is to ensure that if
process is killed right after first download finishes, checksums registered
during previous runs aren't lost.
It is the res... | python | def store_checksums(dataset_name, sizes_checksums):
"""Store given checksums and sizes for specific dataset.
Content of file is never disgarded, only updated. This is to ensure that if
process is killed right after first download finishes, checksums registered
during previous runs aren't lost.
It is the res... | [
"def",
"store_checksums",
"(",
"dataset_name",
",",
"sizes_checksums",
")",
":",
"path",
"=",
"_get_path",
"(",
"dataset_name",
")",
"original_data",
"=",
"_get_sizes_checksums",
"(",
"path",
")",
"new_data",
"=",
"original_data",
".",
"copy",
"(",
")",
"new_dat... | Store given checksums and sizes for specific dataset.
Content of file is never disgarded, only updated. This is to ensure that if
process is killed right after first download finishes, checksums registered
during previous runs aren't lost.
It is the responsibility of the caller not to call function multiple t... | [
"Store",
"given",
"checksums",
"and",
"sizes",
"for",
"specific",
"dataset",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/download/checksums.py#L102-L127 | train |
tensorflow/datasets | tensorflow_datasets/core/download/resource.py | _guess_extract_method | def _guess_extract_method(fname):
"""Guess extraction method, given file name (or path)."""
for method, extensions in _EXTRACTION_METHOD_TO_EXTS:
for ext in extensions:
if fname.endswith(ext):
return method
return ExtractMethod.NO_EXTRACT | python | def _guess_extract_method(fname):
"""Guess extraction method, given file name (or path)."""
for method, extensions in _EXTRACTION_METHOD_TO_EXTS:
for ext in extensions:
if fname.endswith(ext):
return method
return ExtractMethod.NO_EXTRACT | [
"def",
"_guess_extract_method",
"(",
"fname",
")",
":",
"for",
"method",
",",
"extensions",
"in",
"_EXTRACTION_METHOD_TO_EXTS",
":",
"for",
"ext",
"in",
"extensions",
":",
"if",
"fname",
".",
"endswith",
"(",
"ext",
")",
":",
"return",
"method",
"return",
"E... | Guess extraction method, given file name (or path). | [
"Guess",
"extraction",
"method",
"given",
"file",
"name",
"(",
"or",
"path",
")",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/download/resource.py#L93-L99 | train |
tensorflow/datasets | tensorflow_datasets/core/download/resource.py | _sanitize_url | 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
in code as well. Different URLs might give same result.
As much as possible, the extension should be kept.
Heuristics are applied to only keep use... | python | 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
in code as well. Different URLs might give same result.
As much as possible, the extension should be kept.
Heuristics are applied to only keep use... | [
"def",
"_sanitize_url",
"(",
"url",
",",
"max_length",
")",
":",
"url",
"=",
"urllib",
".",
"parse",
".",
"urlparse",
"(",
"url",
")",
"netloc",
"=",
"url",
".",
"netloc",
"for",
"prefix",
"in",
"_NETLOC_COMMON_PREFIXES",
":",
"if",
"netloc",
".",
"start... | Sanitize and shorten url to fit in max_length.
Function is stable: same input MUST ALWAYS give same result, accros changes
in code as well. Different URLs might give same result.
As much as possible, the extension should be kept.
Heuristics are applied to only keep useful info from url.
1- Drop generic [su... | [
"Sanitize",
"and",
"shorten",
"url",
"to",
"fit",
"in",
"max_length",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/download/resource.py#L102-L166 | train |
tensorflow/datasets | tensorflow_datasets/core/download/resource.py | get_dl_fname | def get_dl_fname(url, checksum):
"""Returns name of file for (url, checksum).
The max length of linux and windows filenames is 255 chars.
Windows however expects short paths (260 chars), so we limit the file name
to an arbitrary 90 chars.
Naming pattern: '${url}${checksum}'.
- url: url sanitized and shor... | python | def get_dl_fname(url, checksum):
"""Returns name of file for (url, checksum).
The max length of linux and windows filenames is 255 chars.
Windows however expects short paths (260 chars), so we limit the file name
to an arbitrary 90 chars.
Naming pattern: '${url}${checksum}'.
- url: url sanitized and shor... | [
"def",
"get_dl_fname",
"(",
"url",
",",
"checksum",
")",
":",
"checksum",
"=",
"base64",
".",
"urlsafe_b64encode",
"(",
"_decode_hex",
"(",
"checksum",
")",
")",
"checksum",
"=",
"tf",
".",
"compat",
".",
"as_text",
"(",
"checksum",
")",
"[",
":",
"-",
... | Returns name of file for (url, checksum).
The max length of linux and windows filenames is 255 chars.
Windows however expects short paths (260 chars), so we limit the file name
to an arbitrary 90 chars.
Naming pattern: '${url}${checksum}'.
- url: url sanitized and shortened to 46 chars.
- checksum: base... | [
"Returns",
"name",
"of",
"file",
"for",
"(",
"url",
"checksum",
")",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/download/resource.py#L169-L190 | train |
tensorflow/datasets | tensorflow_datasets/core/download/resource.py | get_dl_dirname | 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) | python | 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) | [
"def",
"get_dl_dirname",
"(",
"url",
")",
":",
"checksum",
"=",
"hashlib",
".",
"sha256",
"(",
"tf",
".",
"compat",
".",
"as_bytes",
"(",
"url",
")",
")",
".",
"hexdigest",
"(",
")",
"return",
"get_dl_fname",
"(",
"url",
",",
"checksum",
")"
] | Returns name of temp dir for given url. | [
"Returns",
"name",
"of",
"temp",
"dir",
"for",
"given",
"url",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/download/resource.py#L193-L196 | train |
tensorflow/datasets | tensorflow_datasets/core/download/resource.py | _read_info | 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) | python | 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) | [
"def",
"_read_info",
"(",
"info_path",
")",
":",
"if",
"not",
"tf",
".",
"io",
".",
"gfile",
".",
"exists",
"(",
"info_path",
")",
":",
"return",
"None",
"with",
"tf",
".",
"io",
".",
"gfile",
".",
"GFile",
"(",
"info_path",
")",
"as",
"info_f",
":... | Returns info dict or None. | [
"Returns",
"info",
"dict",
"or",
"None",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/download/resource.py#L204-L209 | train |
tensorflow/datasets | tensorflow_datasets/core/download/resource.py | write_info_file | 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 a risk two processes
running at the same time overlap here. Risk accepted, since potentially lost
data (`dataset_name`) is only for human consumption... | python | 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 a risk two processes
running at the same time overlap here. Risk accepted, since potentially lost
data (`dataset_name`) is only for human consumption... | [
"def",
"write_info_file",
"(",
"resource",
",",
"path",
",",
"dataset_name",
",",
"original_fname",
")",
":",
"info_path",
"=",
"_get_info_path",
"(",
"path",
")",
"info",
"=",
"_read_info",
"(",
"info_path",
")",
"or",
"{",
"}",
"urls",
"=",
"set",
"(",
... | Write the INFO file next to local file.
Although the method is synchronized, there is still a risk two processes
running at the same time overlap here. Risk accepted, since potentially lost
data (`dataset_name`) is only for human consumption.
Args:
resource: resource for which to write the INFO file.
... | [
"Write",
"the",
"INFO",
"file",
"next",
"to",
"local",
"file",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/download/resource.py#L214-L240 | train |
tensorflow/datasets | tensorflow_datasets/core/download/resource.py | get_extract_method | 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) | python | 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) | [
"def",
"get_extract_method",
"(",
"path",
")",
":",
"info_path",
"=",
"_get_info_path",
"(",
"path",
")",
"info",
"=",
"_read_info",
"(",
"info_path",
")",
"fname",
"=",
"info",
".",
"get",
"(",
"'original_fname'",
",",
"path",
")",
"if",
"info",
"else",
... | Returns `ExtractMethod` to use on resource at path. Cannot be None. | [
"Returns",
"ExtractMethod",
"to",
"use",
"on",
"resource",
"at",
"path",
".",
"Cannot",
"be",
"None",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/download/resource.py#L243-L248 | train |
tensorflow/datasets | tensorflow_datasets/core/download/resource.py | Resource.exists_locally | 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(pa... | python | 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(pa... | [
"def",
"exists_locally",
"(",
"cls",
",",
"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",
"... | Returns whether the resource exists locally, at `resource.path`. | [
"Returns",
"whether",
"the",
"resource",
"exists",
"locally",
"at",
"resource",
".",
"path",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/download/resource.py#L273-L278 | train |
tensorflow/datasets | tensorflow_datasets/image/coco.py | Coco2014._split_generators | def _split_generators(self, dl_manager):
"""Returns SplitGenerators."""
root_url = "http://images.cocodataset.org/"
urls = {
# Train/validation set
"train_images": "zips/train2014.zip",
"val_images": "zips/val2014.zip",
"trainval_annotations": "annotations/annotations_trainva... | python | def _split_generators(self, dl_manager):
"""Returns SplitGenerators."""
root_url = "http://images.cocodataset.org/"
urls = {
# Train/validation set
"train_images": "zips/train2014.zip",
"val_images": "zips/val2014.zip",
"trainval_annotations": "annotations/annotations_trainva... | [
"def",
"_split_generators",
"(",
"self",
",",
"dl_manager",
")",
":",
"root_url",
"=",
"\"http://images.cocodataset.org/\"",
"urls",
"=",
"{",
"# Train/validation set",
"\"train_images\"",
":",
"\"zips/train2014.zip\"",
",",
"\"val_images\"",
":",
"\"zips/val2014.zip\"",
... | Returns SplitGenerators. | [
"Returns",
"SplitGenerators",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/image/coco.py#L94-L149 | train |
tensorflow/datasets | tensorflow_datasets/image/coco.py | Coco2014._generate_examples | def _generate_examples(
self, image_dir, annotation_dir, split_type, has_annotation=True):
"""Generate examples as dicts.
Args:
image_dir: `str`, directory containing the images
annotation_dir: `str`, directory containing
split_type: `str`, <split_name><year> (ex: train2014)
has_a... | python | def _generate_examples(
self, image_dir, annotation_dir, split_type, has_annotation=True):
"""Generate examples as dicts.
Args:
image_dir: `str`, directory containing the images
annotation_dir: `str`, directory containing
split_type: `str`, <split_name><year> (ex: train2014)
has_a... | [
"def",
"_generate_examples",
"(",
"self",
",",
"image_dir",
",",
"annotation_dir",
",",
"split_type",
",",
"has_annotation",
"=",
"True",
")",
":",
"if",
"has_annotation",
":",
"instance_filename",
"=",
"\"instances_{}.json\"",
"else",
":",
"instance_filename",
"=",... | Generate examples as dicts.
Args:
image_dir: `str`, directory containing the images
annotation_dir: `str`, directory containing
split_type: `str`, <split_name><year> (ex: train2014)
has_annotation: `bool`, when False (for the testing set), the annotations
are not recorded
Yield... | [
"Generate",
"examples",
"as",
"dicts",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/image/coco.py#L151-L252 | train |
tensorflow/datasets | tensorflow_datasets/core/features/text_feature.py | Text.str2ints | def str2ints(self, str_value):
"""Conversion string => encoded list[int]."""
if not self._encoder:
raise ValueError(
"Text.str2ints is not available because encoder hasn't been defined.")
return self._encoder.encode(str_value) | python | def str2ints(self, str_value):
"""Conversion string => encoded list[int]."""
if not self._encoder:
raise ValueError(
"Text.str2ints is not available because encoder hasn't been defined.")
return self._encoder.encode(str_value) | [
"def",
"str2ints",
"(",
"self",
",",
"str_value",
")",
":",
"if",
"not",
"self",
".",
"_encoder",
":",
"raise",
"ValueError",
"(",
"\"Text.str2ints is not available because encoder hasn't been defined.\"",
")",
"return",
"self",
".",
"_encoder",
".",
"encode",
"(",
... | Conversion string => encoded list[int]. | [
"Conversion",
"string",
"=",
">",
"encoded",
"list",
"[",
"int",
"]",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/features/text_feature.py#L83-L88 | train |
tensorflow/datasets | tensorflow_datasets/core/features/text_feature.py | Text.ints2str | def ints2str(self, int_values):
"""Conversion list[int] => decoded string."""
if not self._encoder:
raise ValueError(
"Text.ints2str is not available because encoder hasn't been defined.")
return self._encoder.decode(int_values) | python | def ints2str(self, int_values):
"""Conversion list[int] => decoded string."""
if not self._encoder:
raise ValueError(
"Text.ints2str is not available because encoder hasn't been defined.")
return self._encoder.decode(int_values) | [
"def",
"ints2str",
"(",
"self",
",",
"int_values",
")",
":",
"if",
"not",
"self",
".",
"_encoder",
":",
"raise",
"ValueError",
"(",
"\"Text.ints2str is not available because encoder hasn't been defined.\"",
")",
"return",
"self",
".",
"_encoder",
".",
"decode",
"(",... | Conversion list[int] => decoded string. | [
"Conversion",
"list",
"[",
"int",
"]",
"=",
">",
"decoded",
"string",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/features/text_feature.py#L90-L95 | train |
tensorflow/datasets | tensorflow_datasets/core/features/text_feature.py | Text.maybe_build_from_corpus | 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... | python | 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... | [
"def",
"maybe_build_from_corpus",
"(",
"self",
",",
"corpus_generator",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"_encoder_cls",
"is",
"not",
"text_lib",
".",
"SubwordTextEncoder",
":",
"return",
"if",
"self",
".",
"encoder",
":",
"return",
"voc... | Call SubwordTextEncoder.build_from_corpus is encoder_cls is such. | [
"Call",
"SubwordTextEncoder",
".",
"build_from_corpus",
"is",
"encoder_cls",
"is",
"such",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/features/text_feature.py#L137-L148 | train |
tensorflow/datasets | tensorflow_datasets/core/naming.py | sharded_filenames | 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)
] | python | 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)
] | [
"def",
"sharded_filenames",
"(",
"filename_prefix",
",",
"num_shards",
")",
":",
"shard_suffix",
"=",
"\"%05d-of-%05d\"",
"return",
"[",
"\"%s-%s\"",
"%",
"(",
"filename_prefix",
",",
"shard_suffix",
"%",
"(",
"i",
",",
"num_shards",
")",
")",
"for",
"i",
"in"... | Sharded filenames given prefix and number of shards. | [
"Sharded",
"filenames",
"given",
"prefix",
"and",
"number",
"of",
"shards",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/naming.py#L52-L58 | train |
tensorflow/datasets | tensorflow_datasets/image/omniglot.py | _walk_omniglot_dir | 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 = sorte... | python | 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 = sorte... | [
"def",
"_walk_omniglot_dir",
"(",
"directory",
")",
":",
"directory",
"=",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"tf",
".",
"io",
".",
"gfile",
".",
"listdir",
"(",
"directory",
")",
"[",
"0",
"]",
")",
"alphabets",
"=",
"sorted",
"(... | Walk an Omniglot directory and yield examples. | [
"Walk",
"an",
"Omniglot",
"directory",
"and",
"yield",
"examples",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/image/omniglot.py#L128-L143 | train |
tensorflow/datasets | tensorflow_datasets/image/omniglot.py | _get_names | 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... | python | 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... | [
"def",
"_get_names",
"(",
"dirs",
")",
":",
"alphabets",
"=",
"set",
"(",
")",
"label_names",
"=",
"{",
"}",
"for",
"d",
"in",
"dirs",
":",
"for",
"example",
"in",
"_walk_omniglot_dir",
"(",
"d",
")",
":",
"alphabet",
",",
"alphabet_char_id",
",",
"lab... | Get alphabet and label names, union across all dirs. | [
"Get",
"alphabet",
"and",
"label",
"names",
"union",
"across",
"all",
"dirs",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/image/omniglot.py#L146-L160 | train |
tensorflow/datasets | tensorflow_datasets/core/units.py | size_str | 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) == "1.50 GiB"`.
Args:
size_in_bytes: `int` or `None`, the size, in bytes, that we want to
format as a human-readable size string.
"""
... | python | 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) == "1.50 GiB"`.
Args:
size_in_bytes: `int` or `None`, the size, in bytes, that we want to
format as a human-readable size string.
"""
... | [
"def",
"size_str",
"(",
"size_in_bytes",
")",
":",
"if",
"not",
"size_in_bytes",
":",
"return",
"\"?? GiB\"",
"size_in_bytes",
"=",
"float",
"(",
"size_in_bytes",
")",
"for",
"(",
"name",
",",
"size_bytes",
")",
"in",
"_NAME_LIST",
":",
"value",
"=",
"size_i... | Returns a human readable size string.
If size_in_bytes is None, then returns "?? GiB".
For example `size_str(1.5 * tfds.units.GiB) == "1.50 GiB"`.
Args:
size_in_bytes: `int` or `None`, the size, in bytes, that we want to
format as a human-readable size string. | [
"Returns",
"a",
"human",
"readable",
"size",
"string",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/units.py#L34-L53 | train |
tensorflow/datasets | tensorflow_datasets/core/download/downloader.py | _Downloader.tqdm | 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_... | python | 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_... | [
"def",
"tqdm",
"(",
"self",
")",
":",
"async_tqdm",
"=",
"utils",
".",
"async_tqdm",
"with",
"async_tqdm",
"(",
"total",
"=",
"0",
",",
"desc",
"=",
"'Dl Completed...'",
",",
"unit",
"=",
"' url'",
")",
"as",
"pbar_url",
":",
"with",
"async_tqdm",
"(",
... | Add a progression bar for the current download. | [
"Add",
"a",
"progression",
"bar",
"for",
"the",
"current",
"download",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/download/downloader.py#L84-L91 | train |
tensorflow/datasets | tensorflow_datasets/core/download/downloader.py | _Downloader.download | def download(self, url, destination_path):
"""Download url to given path.
Returns Promise -> sha256 of downloaded file.
Args:
url: address of resource to download.
destination_path: `str`, path to directory where to download the resource.
Returns:
Promise obj -> (`str`, int): (downl... | python | def download(self, url, destination_path):
"""Download url to given path.
Returns Promise -> sha256 of downloaded file.
Args:
url: address of resource to download.
destination_path: `str`, path to directory where to download the resource.
Returns:
Promise obj -> (`str`, int): (downl... | [
"def",
"download",
"(",
"self",
",",
"url",
",",
"destination_path",
")",
":",
"self",
".",
"_pbar_url",
".",
"update_total",
"(",
"1",
")",
"future",
"=",
"self",
".",
"_executor",
".",
"submit",
"(",
"self",
".",
"_sync_download",
",",
"url",
",",
"d... | Download url to given path.
Returns Promise -> sha256 of downloaded file.
Args:
url: address of resource to download.
destination_path: `str`, path to directory where to download the resource.
Returns:
Promise obj -> (`str`, int): (downloaded object checksum, size in bytes). | [
"Download",
"url",
"to",
"given",
"path",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/download/downloader.py#L93-L107 | train |
tensorflow/datasets | tensorflow_datasets/core/download/downloader.py | _Downloader._sync_kaggle_download | 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.i... | python | 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.i... | [
"def",
"_sync_kaggle_download",
"(",
"self",
",",
"kaggle_url",
",",
"destination_path",
")",
":",
"kaggle_file",
"=",
"kaggle",
".",
"KaggleFile",
".",
"from_url",
"(",
"kaggle_url",
")",
"downloader",
"=",
"self",
".",
"kaggle_downloader",
"(",
"kaggle_file",
... | Download with Kaggle API. | [
"Download",
"with",
"Kaggle",
"API",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/download/downloader.py#L109-L123 | train |
tensorflow/datasets | tensorflow_datasets/core/download/downloader.py | _Downloader._get_drive_url | 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.it... | python | 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.it... | [
"def",
"_get_drive_url",
"(",
"self",
",",
"url",
",",
"session",
")",
":",
"response",
"=",
"session",
".",
"get",
"(",
"url",
",",
"stream",
"=",
"True",
")",
"if",
"response",
".",
"status_code",
"!=",
"200",
":",
"raise",
"DownloadError",
"(",
"'Fa... | Returns url, possibly with confirmation token. | [
"Returns",
"url",
"possibly",
"with",
"confirmation",
"token",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/download/downloader.py#L125-L135 | train |
tensorflow/datasets | tensorflow_datasets/core/download/downloader.py | _Downloader._sync_download | 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... | python | 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... | [
"def",
"_sync_download",
"(",
"self",
",",
"url",
",",
"destination_path",
")",
":",
"proxies",
"=",
"{",
"'http'",
":",
"os",
".",
"environ",
".",
"get",
"(",
"'TFDS_HTTP_PROXY'",
",",
"None",
")",
",",
"'https'",
":",
"os",
".",
"environ",
".",
"get"... | Synchronous version of `download` method. | [
"Synchronous",
"version",
"of",
"download",
"method",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/download/downloader.py#L144-L208 | train |
tensorflow/datasets | tensorflow_datasets/image/diabetic_retinopathy_detection.py | _resize_image_if_necessary | def _resize_image_if_necessary(image_fobj, target_pixels=None):
"""Resize an image to have (roughly) the given number of target pixels.
Args:
image_fobj: File object containing the original image.
target_pixels: If given, number of pixels that the image must have.
Returns:
A file object.
"""
if ... | python | def _resize_image_if_necessary(image_fobj, target_pixels=None):
"""Resize an image to have (roughly) the given number of target pixels.
Args:
image_fobj: File object containing the original image.
target_pixels: If given, number of pixels that the image must have.
Returns:
A file object.
"""
if ... | [
"def",
"_resize_image_if_necessary",
"(",
"image_fobj",
",",
"target_pixels",
"=",
"None",
")",
":",
"if",
"target_pixels",
"is",
"None",
":",
"return",
"image_fobj",
"cv2",
"=",
"tfds",
".",
"core",
".",
"lazy_imports",
".",
"cv2",
"# Decode image using OpenCV2."... | Resize an image to have (roughly) the given number of target pixels.
Args:
image_fobj: File object containing the original image.
target_pixels: If given, number of pixels that the image must have.
Returns:
A file object. | [
"Resize",
"an",
"image",
"to",
"have",
"(",
"roughly",
")",
"the",
"given",
"number",
"of",
"target",
"pixels",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/image/diabetic_retinopathy_detection.py#L181-L206 | train |
tensorflow/datasets | tensorflow_datasets/image/diabetic_retinopathy_detection.py | DiabeticRetinopathyDetection._generate_examples | 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 which images are stored.
csv_path: optional, path to csv file with two columns: name of image and
label. If not provided, just scan... | python | 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 which images are stored.
csv_path: optional, path to csv file with two columns: name of image and
label. If not provided, just scan... | [
"def",
"_generate_examples",
"(",
"self",
",",
"images_dir_path",
",",
"csv_path",
"=",
"None",
",",
"csv_usage",
"=",
"None",
")",
":",
"if",
"csv_path",
":",
"with",
"tf",
".",
"io",
".",
"gfile",
".",
"GFile",
"(",
"csv_path",
")",
"as",
"csv_f",
":... | Yields Example instances from given CSV.
Args:
images_dir_path: path to dir in which images are stored.
csv_path: optional, path to csv file with two columns: name of image and
label. If not provided, just scan image directory, don't set labels.
csv_usage: optional, subset of examples fro... | [
"Yields",
"Example",
"instances",
"from",
"given",
"CSV",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/image/diabetic_retinopathy_detection.py#L150-L178 | train |
tensorflow/datasets | tensorflow_datasets/core/dataset_builder.py | FileAdapterBuilder._slice_split_info_to_instruction_dicts | 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)
# Comput... | python | 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)
# Comput... | [
"def",
"_slice_split_info_to_instruction_dicts",
"(",
"self",
",",
"list_sliced_split_info",
")",
":",
"instruction_dicts",
"=",
"[",
"]",
"for",
"sliced_split_info",
"in",
"list_sliced_split_info",
":",
"mask",
"=",
"splits_lib",
".",
"slice_to_percent_mask",
"(",
"sli... | Return the list of files and reading mask of the files to read. | [
"Return",
"the",
"list",
"of",
"files",
"and",
"reading",
"mask",
"of",
"the",
"files",
"to",
"read",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/dataset_builder.py#L707-L739 | train |
tensorflow/datasets | tensorflow_datasets/core/dataset_builder.py | FileAdapterBuilder._build_split_filenames | def _build_split_filenames(self, split_info_list):
"""Construct the split filenames associated with the split info.
The filenames correspond to the pre-processed datasets files present in
the root directory of the dataset.
Args:
split_info_list: (list[SplitInfo]) List of split from which generat... | python | def _build_split_filenames(self, split_info_list):
"""Construct the split filenames associated with the split info.
The filenames correspond to the pre-processed datasets files present in
the root directory of the dataset.
Args:
split_info_list: (list[SplitInfo]) List of split from which generat... | [
"def",
"_build_split_filenames",
"(",
"self",
",",
"split_info_list",
")",
":",
"filenames",
"=",
"[",
"]",
"for",
"split_info",
"in",
"split_info_list",
":",
"filenames",
".",
"extend",
"(",
"naming",
".",
"filepaths_for_dataset_split",
"(",
"dataset_name",
"=",
... | Construct the split filenames associated with the split info.
The filenames correspond to the pre-processed datasets files present in
the root directory of the dataset.
Args:
split_info_list: (list[SplitInfo]) List of split from which generate the
filenames
Returns:
filenames: (li... | [
"Construct",
"the",
"split",
"filenames",
"associated",
"with",
"the",
"split",
"info",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/dataset_builder.py#L741-L765 | train |
tensorflow/datasets | tensorflow_datasets/video/moving_mnist.py | MovingMnist._generate_examples | 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 arrays
"""
with tf.io.gfile.GFile(data_path, "rb") as fp:
images = np.load(fp)
images = np.transpose(images, (1, 0, 2,... | python | 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 arrays
"""
with tf.io.gfile.GFile(data_path, "rb") as fp:
images = np.load(fp)
images = np.transpose(images, (1, 0, 2,... | [
"def",
"_generate_examples",
"(",
"self",
",",
"data_path",
")",
":",
"with",
"tf",
".",
"io",
".",
"gfile",
".",
"GFile",
"(",
"data_path",
",",
"\"rb\"",
")",
"as",
"fp",
":",
"images",
"=",
"np",
".",
"load",
"(",
"fp",
")",
"images",
"=",
"np",... | Generate MovingMnist sequences.
Args:
data_path (str): Path to the data file
Yields:
20 x 64 x 64 x 1 uint8 numpy arrays | [
"Generate",
"MovingMnist",
"sequences",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/video/moving_mnist.py#L85-L99 | train |
tensorflow/datasets | tensorflow_datasets/video/starcraft.py | StarcraftVideo._parse_single_video | def _parse_single_video(self, example_proto):
"""Parses single video from the input tfrecords.
Args:
example_proto: tfExample proto with a single video.
Returns:
dict with all frames, positions and actions.
"""
context_features = {
"game_duration_loops": tf.io.FixedLenFeature([... | python | def _parse_single_video(self, example_proto):
"""Parses single video from the input tfrecords.
Args:
example_proto: tfExample proto with a single video.
Returns:
dict with all frames, positions and actions.
"""
context_features = {
"game_duration_loops": tf.io.FixedLenFeature([... | [
"def",
"_parse_single_video",
"(",
"self",
",",
"example_proto",
")",
":",
"context_features",
"=",
"{",
"\"game_duration_loops\"",
":",
"tf",
".",
"io",
".",
"FixedLenFeature",
"(",
"[",
"1",
"]",
",",
"tf",
".",
"int64",
")",
",",
"\"game_duration_seconds\""... | Parses single video from the input tfrecords.
Args:
example_proto: tfExample proto with a single video.
Returns:
dict with all frames, positions and actions. | [
"Parses",
"single",
"video",
"from",
"the",
"input",
"tfrecords",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/video/starcraft.py#L181-L208 | train |
tensorflow/datasets | tensorflow_datasets/image/dsprites.py | Dsprites._generate_examples | def _generate_examples(self, filepath):
"""Generates examples for the dSprites data set.
Args:
filepath: path to the dSprites hdf5 file.
Yields:
Dictionaries with images, latent classes, and latent values.
"""
# Simultaneously iterating through the different data sets in the hdf5
#... | python | def _generate_examples(self, filepath):
"""Generates examples for the dSprites data set.
Args:
filepath: path to the dSprites hdf5 file.
Yields:
Dictionaries with images, latent classes, and latent values.
"""
# Simultaneously iterating through the different data sets in the hdf5
#... | [
"def",
"_generate_examples",
"(",
"self",
",",
"filepath",
")",
":",
"# 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_arra... | Generates examples for the dSprites data set.
Args:
filepath: path to the dSprites hdf5 file.
Yields:
Dictionaries with images, latent classes, and latent values. | [
"Generates",
"examples",
"for",
"the",
"dSprites",
"data",
"set",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/image/dsprites.py#L117-L143 | train |
tensorflow/datasets | tensorflow_datasets/image/oxford_iiit_pet.py | OxfordIIITPet._split_generators | def _split_generators(self, dl_manager):
"""Returns splits."""
# Download images and annotations that come in separate archives.
# Note, that the extension of archives is .tar.gz even though the actual
# archives format is uncompressed tar.
dl_paths = dl_manager.download_and_extract({
"image... | python | def _split_generators(self, dl_manager):
"""Returns splits."""
# Download images and annotations that come in separate archives.
# Note, that the extension of archives is .tar.gz even though the actual
# archives format is uncompressed tar.
dl_paths = dl_manager.download_and_extract({
"image... | [
"def",
"_split_generators",
"(",
"self",
",",
"dl_manager",
")",
":",
"# Download images and annotations that come in separate archives.",
"# Note, that the extension of archives is .tar.gz even though the actual",
"# archives format is uncompressed tar.",
"dl_paths",
"=",
"dl_manager",
... | Returns splits. | [
"Returns",
"splits",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/image/oxford_iiit_pet.py#L65-L102 | train |
tensorflow/datasets | tensorflow_datasets/image/open_images.py | _load_objects | 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... | python | 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... | [
"def",
"_load_objects",
"(",
"csv_paths",
",",
"csv_positions",
",",
"prefix",
")",
":",
"logging",
".",
"info",
"(",
"'Loading CSVs %s from positions %s with prefix %s'",
",",
"csv_paths",
",",
"csv_positions",
",",
"prefix",
")",
"objects",
"=",
"collections",
"."... | Returns objects listed within given CSV files. | [
"Returns",
"objects",
"listed",
"within",
"given",
"CSV",
"files",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/image/open_images.py#L322-L341 | train |
tensorflow/datasets | tensorflow_datasets/image/open_images.py | _load_bboxes | 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 cs... | python | 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 cs... | [
"def",
"_load_bboxes",
"(",
"csv_path",
",",
"csv_positions",
",",
"prefix",
")",
":",
"logging",
".",
"info",
"(",
"'Loading CSVs %s from positions %s with prefix %s'",
",",
"csv_path",
",",
"csv_positions",
",",
"prefix",
")",
"boxes",
"=",
"collections",
".",
"... | Returns bounded boxes listed within given CSV file. | [
"Returns",
"bounded",
"boxes",
"listed",
"within",
"given",
"CSV",
"file",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/image/open_images.py#L344-L369 | train |
tensorflow/datasets | tensorflow_datasets/image/open_images.py | OpenImagesV4._split_generators | def _split_generators(self, dl_manager):
"""Returns SplitGenerators."""
paths = dl_manager.download_and_extract(_URLS)
# Load labels from CSVs:
def load(names):
csv_positions = [0] * len(names)
return functools.partial(_load_objects, [paths[name] for name in names],
... | python | def _split_generators(self, dl_manager):
"""Returns SplitGenerators."""
paths = dl_manager.download_and_extract(_URLS)
# Load labels from CSVs:
def load(names):
csv_positions = [0] * len(names)
return functools.partial(_load_objects, [paths[name] for name in names],
... | [
"def",
"_split_generators",
"(",
"self",
",",
"dl_manager",
")",
":",
"paths",
"=",
"dl_manager",
".",
"download_and_extract",
"(",
"_URLS",
")",
"# Load labels from CSVs:",
"def",
"load",
"(",
"names",
")",
":",
"csv_positions",
"=",
"[",
"0",
"]",
"*",
"le... | Returns SplitGenerators. | [
"Returns",
"SplitGenerators",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/image/open_images.py#L221-L262 | train |
tensorflow/datasets | tensorflow_datasets/image/open_images.py | OpenImagesV4._generate_examples | def _generate_examples(self, archive_paths, objects_getter, bboxes_getter,
prefixes=None):
"""Yields examples."""
trainable_classes = set(
self.info.features['objects_trainable']['label'].names)
for i, archive_path in enumerate(archive_paths):
prefix = prefixes[i] if p... | python | def _generate_examples(self, archive_paths, objects_getter, bboxes_getter,
prefixes=None):
"""Yields examples."""
trainable_classes = set(
self.info.features['objects_trainable']['label'].names)
for i, archive_path in enumerate(archive_paths):
prefix = prefixes[i] if p... | [
"def",
"_generate_examples",
"(",
"self",
",",
"archive_paths",
",",
"objects_getter",
",",
"bboxes_getter",
",",
"prefixes",
"=",
"None",
")",
":",
"trainable_classes",
"=",
"set",
"(",
"self",
".",
"info",
".",
"features",
"[",
"'objects_trainable'",
"]",
"[... | Yields examples. | [
"Yields",
"examples",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/image/open_images.py#L264-L291 | train |
tensorflow/datasets | tensorflow_datasets/text/imdb.py | IMDBReviews._generate_examples | 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 {
"... | python | 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 {
"... | [
"def",
"_generate_examples",
"(",
"self",
",",
"archive",
",",
"directory",
")",
":",
"reg",
"=",
"re",
".",
"compile",
"(",
"os",
".",
"path",
".",
"join",
"(",
"\"^%s\"",
"%",
"directory",
",",
"\"(?P<label>neg|pos)\"",
",",
"\"\"",
")",
")",
"for",
... | Generate IMDB examples. | [
"Generate",
"IMDB",
"examples",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/text/imdb.py#L146-L157 | train |
tensorflow/datasets | tensorflow_datasets/text/cnn_dailymail.py | _get_url_hashes | 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 f... | python | 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 f... | [
"def",
"_get_url_hashes",
"(",
"path",
")",
":",
"urls",
"=",
"_read_text_file",
"(",
"path",
")",
"def",
"url_hash",
"(",
"u",
")",
":",
"h",
"=",
"hashlib",
".",
"sha1",
"(",
")",
"try",
":",
"u",
"=",
"u",
".",
"encode",
"(",
"'utf-8'",
")",
"... | Get hashes of urls in file. | [
"Get",
"hashes",
"of",
"urls",
"in",
"file",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/text/cnn_dailymail.py#L97-L108 | train |
tensorflow/datasets | tensorflow_datasets/text/cnn_dailymail.py | _find_files | 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('Unsuppo... | python | 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('Unsuppo... | [
"def",
"_find_files",
"(",
"dl_paths",
",",
"publisher",
",",
"url_dict",
")",
":",
"if",
"publisher",
"==",
"'cnn'",
":",
"top_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dl_paths",
"[",
"'cnn_stories'",
"]",
",",
"'cnn'",
",",
"'stories'",
")",
... | Find files corresponding to urls. | [
"Find",
"files",
"corresponding",
"to",
"urls",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/text/cnn_dailymail.py#L111-L126 | train |
tensorflow/datasets | tensorflow_datasets/text/cnn_dailymail.py | _subset_filenames | 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... | python | 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... | [
"def",
"_subset_filenames",
"(",
"dl_paths",
",",
"split",
")",
":",
"assert",
"isinstance",
"(",
"dl_paths",
",",
"dict",
")",
",",
"dl_paths",
"# Get filenames for a split.",
"if",
"split",
"==",
"tfds",
".",
"Split",
".",
"TRAIN",
":",
"urls",
"=",
"_get_... | Get filenames for a particular split. | [
"Get",
"filenames",
"for",
"a",
"particular",
"split",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/text/cnn_dailymail.py#L129-L143 | train |
tensorflow/datasets | tensorflow_datasets/text/cnn_dailymail.py | _get_art_abs | def _get_art_abs(story_file):
"""Get abstract (highlights) and article from a story file path."""
# Based on https://github.com/abisee/cnn-dailymail/blob/master/
# make_datafiles.py
lines = _read_text_file(story_file)
# Lowercase everything
lines = [line.lower() for line in lines]
# Put periods on ... | python | def _get_art_abs(story_file):
"""Get abstract (highlights) and article from a story file path."""
# Based on https://github.com/abisee/cnn-dailymail/blob/master/
# make_datafiles.py
lines = _read_text_file(story_file)
# Lowercase everything
lines = [line.lower() for line in lines]
# Put periods on ... | [
"def",
"_get_art_abs",
"(",
"story_file",
")",
":",
"# Based on https://github.com/abisee/cnn-dailymail/blob/master/",
"# make_datafiles.py",
"lines",
"=",
"_read_text_file",
"(",
"story_file",
")",
"# Lowercase everything",
"lines",
"=",
"[",
"line",
".",
"lower",
"(",... | Get abstract (highlights) and article from a story file path. | [
"Get",
"abstract",
"(",
"highlights",
")",
"and",
"article",
"from",
"a",
"story",
"file",
"path",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/text/cnn_dailymail.py#L163-L207 | train |
s0md3v/Photon | plugins/exporter.py | exporter | 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)
... | python | 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)
... | [
"def",
"exporter",
"(",
"directory",
",",
"method",
",",
"datasets",
")",
":",
"if",
"method",
".",
"lower",
"(",
")",
"==",
"'json'",
":",
"# Convert json_dict to a JSON styled string",
"json_string",
"=",
"json",
".",
"dumps",
"(",
"datasets",
",",
"indent",... | Export the results. | [
"Export",
"the",
"results",
"."
] | 6a29f2c9782ea9b3dc090db1774a259033600e39 | https://github.com/s0md3v/Photon/blob/6a29f2c9782ea9b3dc090db1774a259033600e39/plugins/exporter.py#L6-L24 | train |
s0md3v/Photon | plugins/wayback.py | time_machine | 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 = "htt... | python | 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 = "htt... | [
"def",
"time_machine",
"(",
"host",
",",
"mode",
")",
":",
"now",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"to",
"=",
"str",
"(",
"now",
".",
"year",
")",
"+",
"str",
"(",
"now",
".",
"day",
")",
"+",
"str",
"(",
"now",
".",
"m... | Query archive.org. | [
"Query",
"archive",
".",
"org",
"."
] | 6a29f2c9782ea9b3dc090db1774a259033600e39 | https://github.com/s0md3v/Photon/blob/6a29f2c9782ea9b3dc090db1774a259033600e39/plugins/wayback.py#L8-L22 | train |
s0md3v/Photon | core/zap.py | zap | 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 = t... | python | 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 = t... | [
"def",
"zap",
"(",
"input_url",
",",
"archive",
",",
"domain",
",",
"host",
",",
"internal",
",",
"robots",
",",
"proxies",
")",
":",
"if",
"archive",
":",
"print",
"(",
"'%s Fetching URLs from archive.org'",
"%",
"run",
")",
"if",
"False",
":",
"archived_... | Extract links from robots.txt and sitemap.xml. | [
"Extract",
"links",
"from",
"robots",
".",
"txt",
"and",
"sitemap",
".",
"xml",
"."
] | 6a29f2c9782ea9b3dc090db1774a259033600e39 | https://github.com/s0md3v/Photon/blob/6a29f2c9782ea9b3dc090db1774a259033600e39/core/zap.py#L10-L57 | train |
s0md3v/Photon | core/requester.py | requester | 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
):
"""Handle the requests and return the response body."""
cook ... | python | 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
):
"""Handle the requests and return the response body."""
cook ... | [
"def",
"requester",
"(",
"url",
",",
"main_url",
"=",
"None",
",",
"delay",
"=",
"0",
",",
"cook",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"timeout",
"=",
"10",
",",
"host",
"=",
"None",
",",
"proxies",
"=",
"[",
"None",
"]",
",",
"user_ag... | Handle the requests and return the response body. | [
"Handle",
"the",
"requests",
"and",
"return",
"the",
"response",
"body",
"."
] | 6a29f2c9782ea9b3dc090db1774a259033600e39 | https://github.com/s0md3v/Photon/blob/6a29f2c9782ea9b3dc090db1774a259033600e39/core/requester.py#L11-L72 | train |
s0md3v/Photon | photon.py | intel_extractor | 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:
... | python | 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:
... | [
"def",
"intel_extractor",
"(",
"url",
",",
"response",
")",
":",
"for",
"rintel",
"in",
"rintels",
":",
"res",
"=",
"re",
".",
"sub",
"(",
"r'<(script).*?</\\1>(?s)'",
",",
"''",
",",
"response",
")",
"res",
"=",
"re",
".",
"sub",
"(",
"r'<[^<]+?>'",
"... | Extract intel from the response body. | [
"Extract",
"intel",
"from",
"the",
"response",
"body",
"."
] | 6a29f2c9782ea9b3dc090db1774a259033600e39 | https://github.com/s0md3v/Photon/blob/6a29f2c9782ea9b3dc090db1774a259033600e39/photon.py#L208-L217 | train |
s0md3v/Photon | photon.py | js_extractor | 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) | python | 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) | [
"def",
"js_extractor",
"(",
"response",
")",
":",
"# Extract .js files\r",
"matches",
"=",
"rscript",
".",
"findall",
"(",
"response",
")",
"for",
"match",
"in",
"matches",
":",
"match",
"=",
"match",
"[",
"2",
"]",
".",
"replace",
"(",
"'\\''",
",",
"''... | Extract js files from the response body | [
"Extract",
"js",
"files",
"from",
"the",
"response",
"body"
] | 6a29f2c9782ea9b3dc090db1774a259033600e39 | https://github.com/s0md3v/Photon/blob/6a29f2c9782ea9b3dc090db1774a259033600e39/photon.py#L220-L227 | train |
s0md3v/Photon | photon.py | extractor | 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 e... | python | 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 e... | [
"def",
"extractor",
"(",
"url",
")",
":",
"response",
"=",
"requester",
"(",
"url",
",",
"main_url",
",",
"delay",
",",
"cook",
",",
"headers",
",",
"timeout",
",",
"host",
",",
"proxies",
",",
"user_agents",
",",
"failed",
",",
"processed",
")",
"if",... | Extract details from the response body. | [
"Extract",
"details",
"from",
"the",
"response",
"body",
"."
] | 6a29f2c9782ea9b3dc090db1774a259033600e39 | https://github.com/s0md3v/Photon/blob/6a29f2c9782ea9b3dc090db1774a259033600e39/photon.py#L239-L287 | train |
s0md3v/Photon | photon.py | jscanner | 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... | python | 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... | [
"def",
"jscanner",
"(",
"url",
")",
":",
"response",
"=",
"requester",
"(",
"url",
",",
"main_url",
",",
"delay",
",",
"cook",
",",
"headers",
",",
"timeout",
",",
"host",
",",
"proxies",
",",
"user_agents",
",",
"failed",
",",
"processed",
")",
"# Ext... | Extract endpoints from JavaScript code. | [
"Extract",
"endpoints",
"from",
"JavaScript",
"code",
"."
] | 6a29f2c9782ea9b3dc090db1774a259033600e39 | https://github.com/s0md3v/Photon/blob/6a29f2c9782ea9b3dc090db1774a259033600e39/photon.py#L290-L302 | train |
s0md3v/Photon | core/updater.py | updater | 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 outpu... | python | 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 outpu... | [
"def",
"updater",
"(",
")",
":",
"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",
"=... | Update the current installation.
git clones the latest version and merges it with the current directory. | [
"Update",
"the",
"current",
"installation",
"."
] | 6a29f2c9782ea9b3dc090db1774a259033600e39 | https://github.com/s0md3v/Photon/blob/6a29f2c9782ea9b3dc090db1774a259033600e39/core/updater.py#L8-L40 | train |
s0md3v/Photon | plugins/find_subdomains.py | find_subdomains | 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... | python | 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... | [
"def",
"find_subdomains",
"(",
"domain",
")",
":",
"result",
"=",
"set",
"(",
")",
"response",
"=",
"get",
"(",
"'https://findsubdomains.com/subdomains-of/'",
"+",
"domain",
")",
".",
"text",
"matches",
"=",
"findall",
"(",
"r'(?s)<div class=\"domains js-domain-name... | Find subdomains according to the TLD. | [
"Find",
"subdomains",
"according",
"to",
"the",
"TLD",
"."
] | 6a29f2c9782ea9b3dc090db1774a259033600e39 | https://github.com/s0md3v/Photon/blob/6a29f2c9782ea9b3dc090db1774a259033600e39/plugins/find_subdomains.py#L7-L14 | train |
s0md3v/Photon | core/flash.py | flash | 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 l... | python | 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 l... | [
"def",
"flash",
"(",
"function",
",",
"links",
",",
"thread_count",
")",
":",
"# Convert links (set) to list",
"links",
"=",
"list",
"(",
"links",
")",
"threadpool",
"=",
"concurrent",
".",
"futures",
".",
"ThreadPoolExecutor",
"(",
"max_workers",
"=",
"thread_c... | Process the URLs and uses a threadpool to execute a function. | [
"Process",
"the",
"URLs",
"and",
"uses",
"a",
"threadpool",
"to",
"execute",
"a",
"function",
"."
] | 6a29f2c9782ea9b3dc090db1774a259033600e39 | https://github.com/s0md3v/Photon/blob/6a29f2c9782ea9b3dc090db1774a259033600e39/core/flash.py#L6-L17 | train |
s0md3v/Photon | core/utils.py | regxy | 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 ... | python | 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 ... | [
"def",
"regxy",
"(",
"pattern",
",",
"response",
",",
"supress_regex",
",",
"custom",
")",
":",
"try",
":",
"matches",
"=",
"re",
".",
"findall",
"(",
"r'%s'",
"%",
"pattern",
",",
"response",
")",
"for",
"match",
"in",
"matches",
":",
"verb",
"(",
"... | Extract a string based on regex pattern supplied by user. | [
"Extract",
"a",
"string",
"based",
"on",
"regex",
"pattern",
"supplied",
"by",
"user",
"."
] | 6a29f2c9782ea9b3dc090db1774a259033600e39 | https://github.com/s0md3v/Photon/blob/6a29f2c9782ea9b3dc090db1774a259033600e39/core/utils.py#L15-L23 | train |
s0md3v/Photon | core/utils.py | is_link | 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 crawled
Args:
url: str Url to be processed
processed: list[str] List of urls that have already been crawled
Ret... | python | 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 crawled
Args:
url: str Url to be processed
processed: list[str] List of urls that have already been crawled
Ret... | [
"def",
"is_link",
"(",
"url",
",",
"processed",
",",
"files",
")",
":",
"if",
"url",
"not",
"in",
"processed",
":",
"is_file",
"=",
"url",
".",
"endswith",
"(",
"BAD_TYPES",
")",
"if",
"is_file",
":",
"files",
".",
"add",
"(",
"url",
")",
"return",
... | Determine whether or not a link should be crawled
A url should not be crawled if it
- Is a file
- Has already been crawled
Args:
url: str Url to be processed
processed: list[str] List of urls that have already been crawled
Returns:
bool If `url` should be crawled | [
"Determine",
"whether",
"or",
"not",
"a",
"link",
"should",
"be",
"crawled",
"A",
"url",
"should",
"not",
"be",
"crawled",
"if",
"it",
"-",
"Is",
"a",
"file",
"-",
"Has",
"already",
"been",
"crawled"
] | 6a29f2c9782ea9b3dc090db1774a259033600e39 | https://github.com/s0md3v/Photon/blob/6a29f2c9782ea9b3dc090db1774a259033600e39/core/utils.py#L26-L46 | train |
s0md3v/Photon | core/utils.py | remove_regex | 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 strings not matching regex
"""
if not regex:
return urls
# To avoid iterating over the characters... | python | 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 strings not matching regex
"""
if not regex:
return urls
# To avoid iterating over the characters... | [
"def",
"remove_regex",
"(",
"urls",
",",
"regex",
")",
":",
"if",
"not",
"regex",
":",
"return",
"urls",
"# To avoid iterating over the characters of a string",
"if",
"not",
"isinstance",
"(",
"urls",
",",
"(",
"list",
",",
"set",
",",
"tuple",
")",
")",
":"... | Parse a list for non-matches to a regex.
Args:
urls: iterable of urls
regex: string regex to be parsed for
Returns:
list of strings not matching regex | [
"Parse",
"a",
"list",
"for",
"non",
"-",
"matches",
"to",
"a",
"regex",
"."
] | 6a29f2c9782ea9b3dc090db1774a259033600e39 | https://github.com/s0md3v/Photon/blob/6a29f2c9782ea9b3dc090db1774a259033600e39/core/utils.py#L49-L73 | train |
s0md3v/Photon | core/utils.py | writer | 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)
... | python | 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)
... | [
"def",
"writer",
"(",
"datasets",
",",
"dataset_names",
",",
"output_dir",
")",
":",
"for",
"dataset",
",",
"dataset_name",
"in",
"zip",
"(",
"datasets",
",",
"dataset_names",
")",
":",
"if",
"dataset",
":",
"filepath",
"=",
"output_dir",
"+",
"'/'",
"+",
... | Write the results. | [
"Write",
"the",
"results",
"."
] | 6a29f2c9782ea9b3dc090db1774a259033600e39 | https://github.com/s0md3v/Photon/blob/6a29f2c9782ea9b3dc090db1774a259033600e39/core/utils.py#L76-L84 | train |
s0md3v/Photon | core/utils.py | timer | 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
... | python | 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
... | [
"def",
"timer",
"(",
"diff",
",",
"processed",
")",
":",
"# Changes seconds into minutes and seconds",
"minutes",
",",
"seconds",
"=",
"divmod",
"(",
"diff",
",",
"60",
")",
"try",
":",
"# Finds average time taken by requests",
"time_per_request",
"=",
"diff",
"/",
... | Return the passed time. | [
"Return",
"the",
"passed",
"time",
"."
] | 6a29f2c9782ea9b3dc090db1774a259033600e39 | https://github.com/s0md3v/Photon/blob/6a29f2c9782ea9b3dc090db1774a259033600e39/core/utils.py#L87-L96 | train |
s0md3v/Photon | core/utils.py | entropy | 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 ent... | python | 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 ent... | [
"def",
"entropy",
"(",
"string",
")",
":",
"entropy",
"=",
"0",
"for",
"number",
"in",
"range",
"(",
"256",
")",
":",
"result",
"=",
"float",
"(",
"string",
".",
"encode",
"(",
"'utf-8'",
")",
".",
"count",
"(",
"chr",
"(",
"number",
")",
")",
")... | Calculate the entropy of a string. | [
"Calculate",
"the",
"entropy",
"of",
"a",
"string",
"."
] | 6a29f2c9782ea9b3dc090db1774a259033600e39 | https://github.com/s0md3v/Photon/blob/6a29f2c9782ea9b3dc090db1774a259033600e39/core/utils.py#L99-L107 | train |
s0md3v/Photon | core/utils.py | extract_headers | 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 ... | python | 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 ... | [
"def",
"extract_headers",
"(",
"headers",
")",
":",
"sorted_headers",
"=",
"{",
"}",
"matches",
"=",
"re",
".",
"findall",
"(",
"r'(.*):\\s(.*)'",
",",
"headers",
")",
"for",
"match",
"in",
"matches",
":",
"header",
"=",
"match",
"[",
"0",
"]",
"value",
... | This function extracts valid headers from interactive input. | [
"This",
"function",
"extracts",
"valid",
"headers",
"from",
"interactive",
"input",
"."
] | 6a29f2c9782ea9b3dc090db1774a259033600e39 | https://github.com/s0md3v/Photon/blob/6a29f2c9782ea9b3dc090db1774a259033600e39/core/utils.py#L122-L135 | train |
s0md3v/Photon | core/utils.py | top_level | 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 | python | 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 | [
"def",
"top_level",
"(",
"url",
",",
"fix_protocol",
"=",
"True",
")",
":",
"ext",
"=",
"tld",
".",
"get_tld",
"(",
"url",
",",
"fix_protocol",
"=",
"fix_protocol",
")",
"toplevel",
"=",
"'.'",
".",
"join",
"(",
"urlparse",
"(",
"url",
")",
".",
"net... | Extract the top level domain from an URL. | [
"Extract",
"the",
"top",
"level",
"domain",
"from",
"an",
"URL",
"."
] | 6a29f2c9782ea9b3dc090db1774a259033600e39 | https://github.com/s0md3v/Photon/blob/6a29f2c9782ea9b3dc090db1774a259033600e39/core/utils.py#L138-L143 | train |
s0md3v/Photon | core/utils.py | proxy_type | def proxy_type(v):
""" Match IP:PORT or DOMAIN:PORT in a losse manner """
proxies = []
if re.match(r"((http|socks5):\/\/.)?(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d{1,5})", v):
proxies.append({"http": v,
"https": v})
return proxies
elif re.match(r"((http|socks5):\/... | python | def proxy_type(v):
""" Match IP:PORT or DOMAIN:PORT in a losse manner """
proxies = []
if re.match(r"((http|socks5):\/\/.)?(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d{1,5})", v):
proxies.append({"http": v,
"https": v})
return proxies
elif re.match(r"((http|socks5):\/... | [
"def",
"proxy_type",
"(",
"v",
")",
":",
"proxies",
"=",
"[",
"]",
"if",
"re",
".",
"match",
"(",
"r\"((http|socks5):\\/\\/.)?(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}):(\\d{1,5})\"",
",",
"v",
")",
":",
"proxies",
".",
"append",
"(",
"{",
"\"http\"",
":",
"v",... | Match IP:PORT or DOMAIN:PORT in a losse manner | [
"Match",
"IP",
":",
"PORT",
"or",
"DOMAIN",
":",
"PORT",
"in",
"a",
"losse",
"manner"
] | 6a29f2c9782ea9b3dc090db1774a259033600e39 | https://github.com/s0md3v/Photon/blob/6a29f2c9782ea9b3dc090db1774a259033600e39/core/utils.py#L162-L177 | train |
s0md3v/Photon | plugins/dnsdumpster.py | dnsdumpster | def dnsdumpster(domain, output_dir):
"""Query dnsdumpster.com."""
response = requests.Session().get('https://dnsdumpster.com/').text
csrf_token = re.search(
r"name='csrfmiddlewaretoken' value='(.*?)'", response).group(1)
cookies = {'csrftoken': csrf_token}
headers = {'Referer': 'https://dns... | python | def dnsdumpster(domain, output_dir):
"""Query dnsdumpster.com."""
response = requests.Session().get('https://dnsdumpster.com/').text
csrf_token = re.search(
r"name='csrfmiddlewaretoken' value='(.*?)'", response).group(1)
cookies = {'csrftoken': csrf_token}
headers = {'Referer': 'https://dns... | [
"def",
"dnsdumpster",
"(",
"domain",
",",
"output_dir",
")",
":",
"response",
"=",
"requests",
".",
"Session",
"(",
")",
".",
"get",
"(",
"'https://dnsdumpster.com/'",
")",
".",
"text",
"csrf_token",
"=",
"re",
".",
"search",
"(",
"r\"name='csrfmiddlewaretoken... | Query dnsdumpster.com. | [
"Query",
"dnsdumpster",
".",
"com",
"."
] | 6a29f2c9782ea9b3dc090db1774a259033600e39 | https://github.com/s0md3v/Photon/blob/6a29f2c9782ea9b3dc090db1774a259033600e39/plugins/dnsdumpster.py#L7-L22 | train |
s0md3v/Photon | core/prompt.py | prompt | 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:
... | python | 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:
... | [
"def",
"prompt",
"(",
"default",
"=",
"None",
")",
":",
"editor",
"=",
"'nano'",
"with",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"mode",
"=",
"'r+'",
")",
"as",
"tmpfile",
":",
"if",
"default",
":",
"tmpfile",
".",
"write",
"(",
"default",
")",
"tm... | Present the user a prompt. | [
"Present",
"the",
"user",
"a",
"prompt",
"."
] | 6a29f2c9782ea9b3dc090db1774a259033600e39 | https://github.com/s0md3v/Photon/blob/6a29f2c9782ea9b3dc090db1774a259033600e39/core/prompt.py#L6-L22 | train |
QUANTAXIS/QUANTAXIS | QUANTAXIS/QAApplication/QATradeRealtime.py | QA_RealTrade.start_market | def start_market(self):
"""
start the market thread and register backtest broker thread
QAMarket 继承QATrader, QATrader 中有 trade_engine属性 , trade_engine类型是QA_Engine从 QA_Thread继承
"""
# 启动 trade_engine 线程
self.market.start()
# 注册 backtest_broker ,并且启动和它关联线程QAThread 存... | python | def start_market(self):
"""
start the market thread and register backtest broker thread
QAMarket 继承QATrader, QATrader 中有 trade_engine属性 , trade_engine类型是QA_Engine从 QA_Thread继承
"""
# 启动 trade_engine 线程
self.market.start()
# 注册 backtest_broker ,并且启动和它关联线程QAThread 存... | [
"def",
"start_market",
"(",
"self",
")",
":",
"# 启动 trade_engine 线程",
"self",
".",
"market",
".",
"start",
"(",
")",
"# 注册 backtest_broker ,并且启动和它关联线程QAThread 存放在 kernels 词典中, { 'broker_name': QAThread }",
"#self.market.register(self.broker_name, self.broker)",
"self",
".",
"mark... | start the market thread and register backtest broker thread
QAMarket 继承QATrader, QATrader 中有 trade_engine属性 , trade_engine类型是QA_Engine从 QA_Thread继承 | [
"start",
"the",
"market",
"thread",
"and",
"register",
"backtest",
"broker",
"thread",
"QAMarket",
"继承QATrader,",
"QATrader",
"中有",
"trade_engine属性",
",",
"trade_engine类型是QA_Engine从",
"QA_Thread继承"
] | bb1fe424e4108b62a1f712b81a05cf829297a5c0 | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAApplication/QATradeRealtime.py#L72-L82 | train |
QUANTAXIS/QUANTAXIS | QUANTAXIS/QAApplication/QATradeRealtime.py | QA_RealTrade.run | 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'>
... | python | 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'>
... | [
"def",
"run",
"(",
"self",
")",
":",
"# 如果出现了日期的改变 才会进行结算的事件",
"_date",
"=",
"None",
"while",
"QA_util_if_tradetime",
"(",
"self",
".",
"now",
")",
":",
"for",
"data",
"in",
"self",
".",
"ingest_data",
":",
"# 对于在ingest_data中的数据",
"# <class 'QUANTAXIS.QAData.QADat... | generator driven data flow | [
"generator",
"driven",
"data",
"flow"
] | bb1fe424e4108b62a1f712b81a05cf829297a5c0 | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAApplication/QATradeRealtime.py#L84-L117 | train |
QUANTAXIS/QUANTAXIS | QUANTAXIS/QAARP/QAAccount.py | QA_Account.message | 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,
... | python | 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,
... | [
"def",
"message",
"(",
"self",
")",
":",
"return",
"{",
"'source'",
":",
"'account'",
",",
"'frequence'",
":",
"self",
".",
"frequence",
",",
"'account_cookie'",
":",
"self",
".",
"account_cookie",
",",
"'portfolio_cookie'",
":",
"self",
".",
"portfolio_cookie... | the standard message which can be transfer | [
"the",
"standard",
"message",
"which",
"can",
"be",
"transfer"
] | bb1fe424e4108b62a1f712b81a05cf829297a5c0 | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAARP/QAAccount.py#L429-L489 | train |
QUANTAXIS/QUANTAXIS | QUANTAXIS/QAARP/QAAccount.py | QA_Account.init_hold_with_account | def init_hold_with_account(self):
"""带account_cookie的初始化持仓
Returns:
[type] -- [description]
"""
return self.init_hold.reset_index().assign(
account_cookie=self.account_cookie
).set_index(['code',
'account_cookie']) | python | def init_hold_with_account(self):
"""带account_cookie的初始化持仓
Returns:
[type] -- [description]
"""
return self.init_hold.reset_index().assign(
account_cookie=self.account_cookie
).set_index(['code',
'account_cookie']) | [
"def",
"init_hold_with_account",
"(",
"self",
")",
":",
"return",
"self",
".",
"init_hold",
".",
"reset_index",
"(",
")",
".",
"assign",
"(",
"account_cookie",
"=",
"self",
".",
"account_cookie",
")",
".",
"set_index",
"(",
"[",
"'code'",
",",
"'account_cook... | 带account_cookie的初始化持仓
Returns:
[type] -- [description] | [
"带account_cookie的初始化持仓"
] | bb1fe424e4108b62a1f712b81a05cf829297a5c0 | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAARP/QAAccount.py#L508-L518 | train |
QUANTAXIS/QUANTAXIS | QUANTAXIS/QAARP/QAAccount.py | QA_Account.start_date | def start_date(self):
"""账户的起始交易日期(只在回测中使用)
Raises:
RuntimeWarning -- [description]
Returns:
[type] -- [description]
"""
if self.start_==None:
if len(self.time_index_max) > 0:
return str(min(self.time_index_max))[0:10]
... | python | def start_date(self):
"""账户的起始交易日期(只在回测中使用)
Raises:
RuntimeWarning -- [description]
Returns:
[type] -- [description]
"""
if self.start_==None:
if len(self.time_index_max) > 0:
return str(min(self.time_index_max))[0:10]
... | [
"def",
"start_date",
"(",
"self",
")",
":",
"if",
"self",
".",
"start_",
"==",
"None",
":",
"if",
"len",
"(",
"self",
".",
"time_index_max",
")",
">",
"0",
":",
"return",
"str",
"(",
"min",
"(",
"self",
".",
"time_index_max",
")",
")",
"[",
"0",
... | 账户的起始交易日期(只在回测中使用)
Raises:
RuntimeWarning -- [description]
Returns:
[type] -- [description] | [
"账户的起始交易日期",
"(",
"只在回测中使用",
")"
] | bb1fe424e4108b62a1f712b81a05cf829297a5c0 | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAARP/QAAccount.py#L558-L577 | train |
QUANTAXIS/QUANTAXIS | QUANTAXIS/QAARP/QAAccount.py | QA_Account.end_date | def end_date(self):
"""账户的交易结束日期(只在回测中使用)
Raises:
RuntimeWarning -- [description]
Returns:
[type] -- [description]
"""
if self.start_==None:
if len(self.time_index_max) > 0:
return str(max(self.time_index_max))[0:10]
... | python | def end_date(self):
"""账户的交易结束日期(只在回测中使用)
Raises:
RuntimeWarning -- [description]
Returns:
[type] -- [description]
"""
if self.start_==None:
if len(self.time_index_max) > 0:
return str(max(self.time_index_max))[0:10]
... | [
"def",
"end_date",
"(",
"self",
")",
":",
"if",
"self",
".",
"start_",
"==",
"None",
":",
"if",
"len",
"(",
"self",
".",
"time_index_max",
")",
">",
"0",
":",
"return",
"str",
"(",
"max",
"(",
"self",
".",
"time_index_max",
")",
")",
"[",
"0",
":... | 账户的交易结束日期(只在回测中使用)
Raises:
RuntimeWarning -- [description]
Returns:
[type] -- [description] | [
"账户的交易结束日期",
"(",
"只在回测中使用",
")"
] | bb1fe424e4108b62a1f712b81a05cf829297a5c0 | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAARP/QAAccount.py#L580-L599 | train |
QUANTAXIS/QUANTAXIS | QUANTAXIS/QAARP/QAAccount.py | QA_Account.history_table_min | def history_table_min(self):
'区间交易历史的table'
if len(self.history_min) > 0:
lens = len(self.history_min[0])
else:
lens = len(self._history_headers)
return pd.DataFrame(
data=self.history_min,
columns=self._history_headers[:lens]
).so... | python | def history_table_min(self):
'区间交易历史的table'
if len(self.history_min) > 0:
lens = len(self.history_min[0])
else:
lens = len(self._history_headers)
return pd.DataFrame(
data=self.history_min,
columns=self._history_headers[:lens]
).so... | [
"def",
"history_table_min",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"history_min",
")",
">",
"0",
":",
"lens",
"=",
"len",
"(",
"self",
".",
"history_min",
"[",
"0",
"]",
")",
"else",
":",
"lens",
"=",
"len",
"(",
"self",
".",
"_his... | 区间交易历史的table | [
"区间交易历史的table"
] | bb1fe424e4108b62a1f712b81a05cf829297a5c0 | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAARP/QAAccount.py#L639-L649 | train |
QUANTAXIS/QUANTAXIS | QUANTAXIS/QAARP/QAAccount.py | QA_Account.history_table | def history_table(self):
'交易历史的table'
if len(self.history) > 0:
lens = len(self.history[0])
else:
lens = len(self._history_headers)
return pd.DataFrame(
data=self.history,
columns=self._history_headers[:lens]
).sort_index() | python | def history_table(self):
'交易历史的table'
if len(self.history) > 0:
lens = len(self.history[0])
else:
lens = len(self._history_headers)
return pd.DataFrame(
data=self.history,
columns=self._history_headers[:lens]
).sort_index() | [
"def",
"history_table",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"history",
")",
">",
"0",
":",
"lens",
"=",
"len",
"(",
"self",
".",
"history",
"[",
"0",
"]",
")",
"else",
":",
"lens",
"=",
"len",
"(",
"self",
".",
"_history_headers... | 交易历史的table | [
"交易历史的table"
] | bb1fe424e4108b62a1f712b81a05cf829297a5c0 | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAARP/QAAccount.py#L670-L680 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.