repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
bootphon/h5features | h5features/features.py | contains_empty | def contains_empty(features):
"""Check features data are not empty
:param features: The features data to check.
:type features: list of numpy arrays.
:return: True if one of the array is empty, False else.
"""
if not features:
return True
for feature in features:
if featur... | python | def contains_empty(features):
"""Check features data are not empty
:param features: The features data to check.
:type features: list of numpy arrays.
:return: True if one of the array is empty, False else.
"""
if not features:
return True
for feature in features:
if featur... | [
"def",
"contains_empty",
"(",
"features",
")",
":",
"if",
"not",
"features",
":",
"return",
"True",
"for",
"feature",
"in",
"features",
":",
"if",
"feature",
".",
"shape",
"[",
"0",
"]",
"==",
"0",
":",
"return",
"True",
"return",
"False"
] | Check features data are not empty
:param features: The features data to check.
:type features: list of numpy arrays.
:return: True if one of the array is empty, False else. | [
"Check",
"features",
"data",
"are",
"not",
"empty"
] | d5f95db0f1cee58ac1ba4575d1212e796c39e1f9 | https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/features.py#L27-L41 | train | 25,900 |
bootphon/h5features | h5features/features.py | parse_dformat | def parse_dformat(dformat, check=True):
"""Return `dformat` or raise if it is not 'dense' or 'sparse'"""
if check and dformat not in ['dense', 'sparse']:
raise IOError(
"{} is a bad features format, please choose 'dense' or 'sparse'"
.format(dformat))
return dformat | python | def parse_dformat(dformat, check=True):
"""Return `dformat` or raise if it is not 'dense' or 'sparse'"""
if check and dformat not in ['dense', 'sparse']:
raise IOError(
"{} is a bad features format, please choose 'dense' or 'sparse'"
.format(dformat))
return dformat | [
"def",
"parse_dformat",
"(",
"dformat",
",",
"check",
"=",
"True",
")",
":",
"if",
"check",
"and",
"dformat",
"not",
"in",
"[",
"'dense'",
",",
"'sparse'",
"]",
":",
"raise",
"IOError",
"(",
"\"{} is a bad features format, please choose 'dense' or 'sparse'\"",
"."... | Return `dformat` or raise if it is not 'dense' or 'sparse | [
"Return",
"dformat",
"or",
"raise",
"if",
"it",
"is",
"not",
"dense",
"or",
"sparse"
] | d5f95db0f1cee58ac1ba4575d1212e796c39e1f9 | https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/features.py#L44-L50 | train | 25,901 |
bootphon/h5features | h5features/features.py | parse_dtype | def parse_dtype(features, check=True):
"""Return the features scalar type, raise if error
Raise IOError if all features have not the same data type.
Return dtype, the features scalar type.
"""
dtype = features[0].dtype
if check:
types = [x.dtype for x in features]
if not all([t... | python | def parse_dtype(features, check=True):
"""Return the features scalar type, raise if error
Raise IOError if all features have not the same data type.
Return dtype, the features scalar type.
"""
dtype = features[0].dtype
if check:
types = [x.dtype for x in features]
if not all([t... | [
"def",
"parse_dtype",
"(",
"features",
",",
"check",
"=",
"True",
")",
":",
"dtype",
"=",
"features",
"[",
"0",
"]",
".",
"dtype",
"if",
"check",
":",
"types",
"=",
"[",
"x",
".",
"dtype",
"for",
"x",
"in",
"features",
"]",
"if",
"not",
"all",
"(... | Return the features scalar type, raise if error
Raise IOError if all features have not the same data type.
Return dtype, the features scalar type. | [
"Return",
"the",
"features",
"scalar",
"type",
"raise",
"if",
"error"
] | d5f95db0f1cee58ac1ba4575d1212e796c39e1f9 | https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/features.py#L53-L65 | train | 25,902 |
bootphon/h5features | h5features/features.py | parse_dim | def parse_dim(features, check=True):
"""Return the features dimension, raise if error
Raise IOError if features have not all the same positive
dimension. Return dim (int), the features dimension.
"""
# try:
dim = features[0].shape[1]
# except IndexError:
# dim = 1
if check an... | python | def parse_dim(features, check=True):
"""Return the features dimension, raise if error
Raise IOError if features have not all the same positive
dimension. Return dim (int), the features dimension.
"""
# try:
dim = features[0].shape[1]
# except IndexError:
# dim = 1
if check an... | [
"def",
"parse_dim",
"(",
"features",
",",
"check",
"=",
"True",
")",
":",
"# try:",
"dim",
"=",
"features",
"[",
"0",
"]",
".",
"shape",
"[",
"1",
"]",
"# except IndexError:",
"# dim = 1",
"if",
"check",
"and",
"not",
"dim",
">",
"0",
":",
"raise",... | Return the features dimension, raise if error
Raise IOError if features have not all the same positive
dimension. Return dim (int), the features dimension. | [
"Return",
"the",
"features",
"dimension",
"raise",
"if",
"error"
] | d5f95db0f1cee58ac1ba4575d1212e796c39e1f9 | https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/features.py#L68-L84 | train | 25,903 |
bootphon/h5features | h5features/features.py | Features.is_appendable_to | def is_appendable_to(self, group):
"""Return True if features are appendable to a HDF5 group"""
return (group.attrs['format'] == self.dformat and
group[self.name].dtype == self.dtype and
# We use a method because dim differs in dense and sparse.
self._grou... | python | def is_appendable_to(self, group):
"""Return True if features are appendable to a HDF5 group"""
return (group.attrs['format'] == self.dformat and
group[self.name].dtype == self.dtype and
# We use a method because dim differs in dense and sparse.
self._grou... | [
"def",
"is_appendable_to",
"(",
"self",
",",
"group",
")",
":",
"return",
"(",
"group",
".",
"attrs",
"[",
"'format'",
"]",
"==",
"self",
".",
"dformat",
"and",
"group",
"[",
"self",
".",
"name",
"]",
".",
"dtype",
"==",
"self",
".",
"dtype",
"and",
... | Return True if features are appendable to a HDF5 group | [
"Return",
"True",
"if",
"features",
"are",
"appendable",
"to",
"a",
"HDF5",
"group"
] | d5f95db0f1cee58ac1ba4575d1212e796c39e1f9 | https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/features.py#L139-L144 | train | 25,904 |
bootphon/h5features | h5features/features.py | Features.create_dataset | def create_dataset(
self, group, chunk_size, compression=None, compression_opts=None):
"""Initialize the features subgoup"""
group.attrs['format'] = self.dformat
super(Features, self)._create_dataset(
group, chunk_size, compression, compression_opts)
# TODO attri... | python | def create_dataset(
self, group, chunk_size, compression=None, compression_opts=None):
"""Initialize the features subgoup"""
group.attrs['format'] = self.dformat
super(Features, self)._create_dataset(
group, chunk_size, compression, compression_opts)
# TODO attri... | [
"def",
"create_dataset",
"(",
"self",
",",
"group",
",",
"chunk_size",
",",
"compression",
"=",
"None",
",",
"compression_opts",
"=",
"None",
")",
":",
"group",
".",
"attrs",
"[",
"'format'",
"]",
"=",
"self",
".",
"dformat",
"super",
"(",
"Features",
",... | Initialize the features subgoup | [
"Initialize",
"the",
"features",
"subgoup"
] | d5f95db0f1cee58ac1ba4575d1212e796c39e1f9 | https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/features.py#L153-L166 | train | 25,905 |
bootphon/h5features | h5features/features.py | Features.write_to | def write_to(self, group, append=False):
"""Write stored features to a given group"""
if self.sparsetodense:
self.data = [x.todense() if sp.issparse(x) else x
for x in self.data]
nframes = sum([d.shape[0] for d in self.data])
dim = self._group_dim(gr... | python | def write_to(self, group, append=False):
"""Write stored features to a given group"""
if self.sparsetodense:
self.data = [x.todense() if sp.issparse(x) else x
for x in self.data]
nframes = sum([d.shape[0] for d in self.data])
dim = self._group_dim(gr... | [
"def",
"write_to",
"(",
"self",
",",
"group",
",",
"append",
"=",
"False",
")",
":",
"if",
"self",
".",
"sparsetodense",
":",
"self",
".",
"data",
"=",
"[",
"x",
".",
"todense",
"(",
")",
"if",
"sp",
".",
"issparse",
"(",
"x",
")",
"else",
"x",
... | Write stored features to a given group | [
"Write",
"stored",
"features",
"to",
"a",
"given",
"group"
] | d5f95db0f1cee58ac1ba4575d1212e796c39e1f9 | https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/features.py#L168-L187 | train | 25,906 |
bootphon/h5features | h5features/features.py | SparseFeatures.create_dataset | def create_dataset(self, group, chunk_size):
"""Initializes sparse specific datasets"""
group.attrs['format'] = self.dformat
group.attrs['dim'] = self.dim
if chunk_size == 'auto':
group.create_dataset(
'coordinates', (0, 2), dtype=np.float64,
... | python | def create_dataset(self, group, chunk_size):
"""Initializes sparse specific datasets"""
group.attrs['format'] = self.dformat
group.attrs['dim'] = self.dim
if chunk_size == 'auto':
group.create_dataset(
'coordinates', (0, 2), dtype=np.float64,
... | [
"def",
"create_dataset",
"(",
"self",
",",
"group",
",",
"chunk_size",
")",
":",
"group",
".",
"attrs",
"[",
"'format'",
"]",
"=",
"self",
".",
"dformat",
"group",
".",
"attrs",
"[",
"'dim'",
"]",
"=",
"self",
".",
"dim",
"if",
"chunk_size",
"==",
"'... | Initializes sparse specific datasets | [
"Initializes",
"sparse",
"specific",
"datasets"
] | d5f95db0f1cee58ac1ba4575d1212e796c39e1f9 | https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/features.py#L215-L256 | train | 25,907 |
bootphon/h5features | h5features/properties.py | read_properties | def read_properties(group):
"""Returns properties loaded from a group"""
if 'properties' not in group:
raise IOError('no properties in group')
data = group['properties'][...][0].replace(b'__NULL__', b'\x00')
return pickle.loads(data) | python | def read_properties(group):
"""Returns properties loaded from a group"""
if 'properties' not in group:
raise IOError('no properties in group')
data = group['properties'][...][0].replace(b'__NULL__', b'\x00')
return pickle.loads(data) | [
"def",
"read_properties",
"(",
"group",
")",
":",
"if",
"'properties'",
"not",
"in",
"group",
":",
"raise",
"IOError",
"(",
"'no properties in group'",
")",
"data",
"=",
"group",
"[",
"'properties'",
"]",
"[",
"...",
"]",
"[",
"0",
"]",
".",
"replace",
"... | Returns properties loaded from a group | [
"Returns",
"properties",
"loaded",
"from",
"a",
"group"
] | d5f95db0f1cee58ac1ba4575d1212e796c39e1f9 | https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/properties.py#L24-L30 | train | 25,908 |
bootphon/h5features | h5features/properties.py | Properties._eq_dicts | def _eq_dicts(d1, d2):
"""Returns True if d1 == d2, False otherwise"""
if not d1.keys() == d2.keys():
return False
for k, v1 in d1.items():
v2 = d2[k]
if not type(v1) == type(v2):
return False
if isinstance(v1, np.ndarray):
... | python | def _eq_dicts(d1, d2):
"""Returns True if d1 == d2, False otherwise"""
if not d1.keys() == d2.keys():
return False
for k, v1 in d1.items():
v2 = d2[k]
if not type(v1) == type(v2):
return False
if isinstance(v1, np.ndarray):
... | [
"def",
"_eq_dicts",
"(",
"d1",
",",
"d2",
")",
":",
"if",
"not",
"d1",
".",
"keys",
"(",
")",
"==",
"d2",
".",
"keys",
"(",
")",
":",
"return",
"False",
"for",
"k",
",",
"v1",
"in",
"d1",
".",
"items",
"(",
")",
":",
"v2",
"=",
"d2",
"[",
... | Returns True if d1 == d2, False otherwise | [
"Returns",
"True",
"if",
"d1",
"==",
"d2",
"False",
"otherwise"
] | d5f95db0f1cee58ac1ba4575d1212e796c39e1f9 | https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/properties.py#L57-L72 | train | 25,909 |
bootphon/h5features | h5features/properties.py | Properties.write_to | def write_to(self, group, append=False):
"""Writes the properties to a `group`, or append it"""
data = self.data
if append is True:
try:
# concatenate original and new properties in a single list
original = read_properties(group)
data =... | python | def write_to(self, group, append=False):
"""Writes the properties to a `group`, or append it"""
data = self.data
if append is True:
try:
# concatenate original and new properties in a single list
original = read_properties(group)
data =... | [
"def",
"write_to",
"(",
"self",
",",
"group",
",",
"append",
"=",
"False",
")",
":",
"data",
"=",
"self",
".",
"data",
"if",
"append",
"is",
"True",
":",
"try",
":",
"# concatenate original and new properties in a single list",
"original",
"=",
"read_properties"... | Writes the properties to a `group`, or append it | [
"Writes",
"the",
"properties",
"to",
"a",
"group",
"or",
"append",
"it"
] | d5f95db0f1cee58ac1ba4575d1212e796c39e1f9 | https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/properties.py#L83-L96 | train | 25,910 |
bootphon/h5features | docs/exemple.py | generate_data | def generate_data(nitem, nfeat=2, dim=10, labeldim=1, base='item'):
"""Returns a randomly generated h5f.Data instance.
- nitem is the number of items to generate.
- nfeat is the number of features to generate for each item.
- dim is the dimension of the features vectors.
- base is the items basenam... | python | def generate_data(nitem, nfeat=2, dim=10, labeldim=1, base='item'):
"""Returns a randomly generated h5f.Data instance.
- nitem is the number of items to generate.
- nfeat is the number of features to generate for each item.
- dim is the dimension of the features vectors.
- base is the items basenam... | [
"def",
"generate_data",
"(",
"nitem",
",",
"nfeat",
"=",
"2",
",",
"dim",
"=",
"10",
",",
"labeldim",
"=",
"1",
",",
"base",
"=",
"'item'",
")",
":",
"import",
"numpy",
"as",
"np",
"# A list of item names",
"items",
"=",
"[",
"base",
"+",
"'_'",
"+",... | Returns a randomly generated h5f.Data instance.
- nitem is the number of items to generate.
- nfeat is the number of features to generate for each item.
- dim is the dimension of the features vectors.
- base is the items basename
- labeldim is the dimension of the labels vectors. | [
"Returns",
"a",
"randomly",
"generated",
"h5f",
".",
"Data",
"instance",
"."
] | d5f95db0f1cee58ac1ba4575d1212e796c39e1f9 | https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/docs/exemple.py#L7-L32 | train | 25,911 |
bootphon/h5features | h5features/index.py | create_index | def create_index(group, chunk_size, compression=None, compression_opts=None):
"""Create an empty index dataset in the given group."""
dtype = np.int64
if chunk_size == 'auto':
chunks = True
else:
chunks = (nb_per_chunk(np.dtype(dtype).itemsize, 1, chunk_size),)
group.create_dataset(... | python | def create_index(group, chunk_size, compression=None, compression_opts=None):
"""Create an empty index dataset in the given group."""
dtype = np.int64
if chunk_size == 'auto':
chunks = True
else:
chunks = (nb_per_chunk(np.dtype(dtype).itemsize, 1, chunk_size),)
group.create_dataset(... | [
"def",
"create_index",
"(",
"group",
",",
"chunk_size",
",",
"compression",
"=",
"None",
",",
"compression_opts",
"=",
"None",
")",
":",
"dtype",
"=",
"np",
".",
"int64",
"if",
"chunk_size",
"==",
"'auto'",
":",
"chunks",
"=",
"True",
"else",
":",
"chunk... | Create an empty index dataset in the given group. | [
"Create",
"an",
"empty",
"index",
"dataset",
"in",
"the",
"given",
"group",
"."
] | d5f95db0f1cee58ac1ba4575d1212e796c39e1f9 | https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/index.py#L37-L48 | train | 25,912 |
bootphon/h5features | h5features/index.py | write_index | def write_index(data, group, append):
"""Write the data index to the given group.
:param h5features.Data data: The that is being indexed.
:param h5py.Group group: The group where to write the index.
:param bool append: If True, append the created index to the
existing one in the `group`. Delete... | python | def write_index(data, group, append):
"""Write the data index to the given group.
:param h5features.Data data: The that is being indexed.
:param h5py.Group group: The group where to write the index.
:param bool append: If True, append the created index to the
existing one in the `group`. Delete... | [
"def",
"write_index",
"(",
"data",
",",
"group",
",",
"append",
")",
":",
"# build the index from data",
"nitems",
"=",
"group",
"[",
"'items'",
"]",
".",
"shape",
"[",
"0",
"]",
"if",
"'items'",
"in",
"group",
"else",
"0",
"last_index",
"=",
"group",
"[... | Write the data index to the given group.
:param h5features.Data data: The that is being indexed.
:param h5py.Group group: The group where to write the index.
:param bool append: If True, append the created index to the
existing one in the `group`. Delete any existing data in index
if False. | [
"Write",
"the",
"data",
"index",
"to",
"the",
"given",
"group",
"."
] | d5f95db0f1cee58ac1ba4575d1212e796c39e1f9 | https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/index.py#L51-L76 | train | 25,913 |
bootphon/h5features | h5features/index.py | read_index | def read_index(group, version='1.1'):
"""Return the index stored in a h5features group.
:param h5py.Group group: The group to read the index from.
:param str version: The h5features version of the `group`.
:return: a 1D numpy array of features indices.
"""
if version == '0.1':
return np... | python | def read_index(group, version='1.1'):
"""Return the index stored in a h5features group.
:param h5py.Group group: The group to read the index from.
:param str version: The h5features version of the `group`.
:return: a 1D numpy array of features indices.
"""
if version == '0.1':
return np... | [
"def",
"read_index",
"(",
"group",
",",
"version",
"=",
"'1.1'",
")",
":",
"if",
"version",
"==",
"'0.1'",
":",
"return",
"np",
".",
"int64",
"(",
"group",
"[",
"'index'",
"]",
"[",
"...",
"]",
")",
"elif",
"version",
"==",
"'1.0'",
":",
"return",
... | Return the index stored in a h5features group.
:param h5py.Group group: The group to read the index from.
:param str version: The h5features version of the `group`.
:return: a 1D numpy array of features indices. | [
"Return",
"the",
"index",
"stored",
"in",
"a",
"h5features",
"group",
"."
] | d5f95db0f1cee58ac1ba4575d1212e796c39e1f9 | https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/index.py#L79-L91 | train | 25,914 |
bootphon/h5features | h5features/entry.py | nb_per_chunk | def nb_per_chunk(item_size, item_dim, chunk_size):
"""Return the number of items that can be stored in one chunk.
:param int item_size: Size of an item's scalar componant in
Bytes (e.g. for np.float64 this is 8)
:param int item_dim: Items dimension (length of the second axis)
:param float chu... | python | def nb_per_chunk(item_size, item_dim, chunk_size):
"""Return the number of items that can be stored in one chunk.
:param int item_size: Size of an item's scalar componant in
Bytes (e.g. for np.float64 this is 8)
:param int item_dim: Items dimension (length of the second axis)
:param float chu... | [
"def",
"nb_per_chunk",
"(",
"item_size",
",",
"item_dim",
",",
"chunk_size",
")",
":",
"# from Mbytes to bytes",
"size",
"=",
"chunk_size",
"*",
"10.",
"**",
"6",
"ratio",
"=",
"int",
"(",
"round",
"(",
"size",
"/",
"(",
"item_size",
"*",
"item_dim",
")",
... | Return the number of items that can be stored in one chunk.
:param int item_size: Size of an item's scalar componant in
Bytes (e.g. for np.float64 this is 8)
:param int item_dim: Items dimension (length of the second axis)
:param float chunk_size: The size of a chunk given in MBytes. | [
"Return",
"the",
"number",
"of",
"items",
"that",
"can",
"be",
"stored",
"in",
"one",
"chunk",
"."
] | d5f95db0f1cee58ac1ba4575d1212e796c39e1f9 | https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/entry.py#L22-L36 | train | 25,915 |
bootphon/h5features | h5features/entry.py | Entry.is_appendable | def is_appendable(self, entry):
"""Return True if entry can be appended to self"""
try:
if (
self.name == entry.name and
self.dtype == entry.dtype and
self.dim == entry.dim
):
return True
except A... | python | def is_appendable(self, entry):
"""Return True if entry can be appended to self"""
try:
if (
self.name == entry.name and
self.dtype == entry.dtype and
self.dim == entry.dim
):
return True
except A... | [
"def",
"is_appendable",
"(",
"self",
",",
"entry",
")",
":",
"try",
":",
"if",
"(",
"self",
".",
"name",
"==",
"entry",
".",
"name",
"and",
"self",
".",
"dtype",
"==",
"entry",
".",
"dtype",
"and",
"self",
".",
"dim",
"==",
"entry",
".",
"dim",
"... | Return True if entry can be appended to self | [
"Return",
"True",
"if",
"entry",
"can",
"be",
"appended",
"to",
"self"
] | d5f95db0f1cee58ac1ba4575d1212e796c39e1f9 | https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/entry.py#L74-L85 | train | 25,916 |
bootphon/h5features | h5features/entry.py | Entry.append | def append(self, entry):
"""Append an entry to self"""
if not self.is_appendable(entry):
raise ValueError('entry not appendable')
self.data += entry.data | python | def append(self, entry):
"""Append an entry to self"""
if not self.is_appendable(entry):
raise ValueError('entry not appendable')
self.data += entry.data | [
"def",
"append",
"(",
"self",
",",
"entry",
")",
":",
"if",
"not",
"self",
".",
"is_appendable",
"(",
"entry",
")",
":",
"raise",
"ValueError",
"(",
"'entry not appendable'",
")",
"self",
".",
"data",
"+=",
"entry",
".",
"data"
] | Append an entry to self | [
"Append",
"an",
"entry",
"to",
"self"
] | d5f95db0f1cee58ac1ba4575d1212e796c39e1f9 | https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/entry.py#L87-L91 | train | 25,917 |
bootphon/h5features | h5features/writer.py | Writer.write | def write(self, data, groupname='h5features', append=False):
"""Write h5features data in a specified group of the file.
:param dict data: A `h5features.Data` instance to be writed on disk.
:param str groupname: Optional. The name of the group in which
to write the data.
:p... | python | def write(self, data, groupname='h5features', append=False):
"""Write h5features data in a specified group of the file.
:param dict data: A `h5features.Data` instance to be writed on disk.
:param str groupname: Optional. The name of the group in which
to write the data.
:p... | [
"def",
"write",
"(",
"self",
",",
"data",
",",
"groupname",
"=",
"'h5features'",
",",
"append",
"=",
"False",
")",
":",
"if",
"append",
"and",
"groupname",
"in",
"self",
".",
"h5file",
":",
"# append data to the group, raise if we cannot",
"group",
"=",
"self"... | Write h5features data in a specified group of the file.
:param dict data: A `h5features.Data` instance to be writed on disk.
:param str groupname: Optional. The name of the group in which
to write the data.
:param bool append: Optional. This parameter has no effect if
t... | [
"Write",
"h5features",
"data",
"in",
"a",
"specified",
"group",
"of",
"the",
"file",
"."
] | d5f95db0f1cee58ac1ba4575d1212e796c39e1f9 | https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/writer.py#L123-L154 | train | 25,918 |
bootphon/h5features | h5features/writer.py | Writer._prepare | def _prepare(self, data, groupname):
"""Clear the group if existing and initialize empty datasets."""
if groupname in self.h5file:
del self.h5file[groupname]
group = self.h5file.create_group(groupname)
group.attrs['version'] = self.version
data.init_group(
... | python | def _prepare(self, data, groupname):
"""Clear the group if existing and initialize empty datasets."""
if groupname in self.h5file:
del self.h5file[groupname]
group = self.h5file.create_group(groupname)
group.attrs['version'] = self.version
data.init_group(
... | [
"def",
"_prepare",
"(",
"self",
",",
"data",
",",
"groupname",
")",
":",
"if",
"groupname",
"in",
"self",
".",
"h5file",
":",
"del",
"self",
".",
"h5file",
"[",
"groupname",
"]",
"group",
"=",
"self",
".",
"h5file",
".",
"create_group",
"(",
"groupname... | Clear the group if existing and initialize empty datasets. | [
"Clear",
"the",
"group",
"if",
"existing",
"and",
"initialize",
"empty",
"datasets",
"."
] | d5f95db0f1cee58ac1ba4575d1212e796c39e1f9 | https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/writer.py#L156-L164 | train | 25,919 |
bootphon/h5features | h5features/items.py | read_items | def read_items(group, version='1.1', check=False):
"""Return an Items instance initialized from a h5features group."""
if version == '0.1':
# parse unicode to strings
return ''.join(
[unichr(int(c)) for c in group['files'][...]]
).replace('/-', '/').split('/\\')
elif vers... | python | def read_items(group, version='1.1', check=False):
"""Return an Items instance initialized from a h5features group."""
if version == '0.1':
# parse unicode to strings
return ''.join(
[unichr(int(c)) for c in group['files'][...]]
).replace('/-', '/').split('/\\')
elif vers... | [
"def",
"read_items",
"(",
"group",
",",
"version",
"=",
"'1.1'",
",",
"check",
"=",
"False",
")",
":",
"if",
"version",
"==",
"'0.1'",
":",
"# parse unicode to strings",
"return",
"''",
".",
"join",
"(",
"[",
"unichr",
"(",
"int",
"(",
"c",
")",
")",
... | Return an Items instance initialized from a h5features group. | [
"Return",
"an",
"Items",
"instance",
"initialized",
"from",
"a",
"h5features",
"group",
"."
] | d5f95db0f1cee58ac1ba4575d1212e796c39e1f9 | https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/items.py#L26-L36 | train | 25,920 |
bootphon/h5features | h5features/items.py | Items.write_to | def write_to(self, group):
"""Write stored items to the given HDF5 group.
We assume that self.create() has been called.
"""
# The HDF5 group where to write data
items_group = group[self.name]
nitems = items_group.shape[0]
items_group.resize((nitems + len(self.d... | python | def write_to(self, group):
"""Write stored items to the given HDF5 group.
We assume that self.create() has been called.
"""
# The HDF5 group where to write data
items_group = group[self.name]
nitems = items_group.shape[0]
items_group.resize((nitems + len(self.d... | [
"def",
"write_to",
"(",
"self",
",",
"group",
")",
":",
"# The HDF5 group where to write data",
"items_group",
"=",
"group",
"[",
"self",
".",
"name",
"]",
"nitems",
"=",
"items_group",
".",
"shape",
"[",
"0",
"]",
"items_group",
".",
"resize",
"(",
"(",
"... | Write stored items to the given HDF5 group.
We assume that self.create() has been called. | [
"Write",
"stored",
"items",
"to",
"the",
"given",
"HDF5",
"group",
"."
] | d5f95db0f1cee58ac1ba4575d1212e796c39e1f9 | https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/items.py#L68-L79 | train | 25,921 |
bootphon/h5features | h5features/items.py | Items._create_dataset | def _create_dataset(
self, group, chunk_size, compression, compression_opts):
"""Create an empty dataset in a group."""
if chunk_size == 'auto':
chunks = True
else:
# if dtype is a variable str, guess representative size is 20 bytes
per_chunk = (
... | python | def _create_dataset(
self, group, chunk_size, compression, compression_opts):
"""Create an empty dataset in a group."""
if chunk_size == 'auto':
chunks = True
else:
# if dtype is a variable str, guess representative size is 20 bytes
per_chunk = (
... | [
"def",
"_create_dataset",
"(",
"self",
",",
"group",
",",
"chunk_size",
",",
"compression",
",",
"compression_opts",
")",
":",
"if",
"chunk_size",
"==",
"'auto'",
":",
"chunks",
"=",
"True",
"else",
":",
"# if dtype is a variable str, guess representative size is 20 b... | Create an empty dataset in a group. | [
"Create",
"an",
"empty",
"dataset",
"in",
"a",
"group",
"."
] | d5f95db0f1cee58ac1ba4575d1212e796c39e1f9 | https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/items.py#L91-L111 | train | 25,922 |
bootphon/h5features | h5features/version.py | read_version | def read_version(group):
"""Return the h5features version of a given HDF5 `group`.
Look for a 'version' attribute in the `group` and return its
value. Return '0.1' if the version is not found. Raises an IOError
if it is not supported.
"""
version = ('0.1' if 'version' not in group.attrs
... | python | def read_version(group):
"""Return the h5features version of a given HDF5 `group`.
Look for a 'version' attribute in the `group` and return its
value. Return '0.1' if the version is not found. Raises an IOError
if it is not supported.
"""
version = ('0.1' if 'version' not in group.attrs
... | [
"def",
"read_version",
"(",
"group",
")",
":",
"version",
"=",
"(",
"'0.1'",
"if",
"'version'",
"not",
"in",
"group",
".",
"attrs",
"else",
"group",
".",
"attrs",
"[",
"'version'",
"]",
")",
"# decode from bytes to str if needed",
"if",
"isinstance",
"(",
"v... | Return the h5features version of a given HDF5 `group`.
Look for a 'version' attribute in the `group` and return its
value. Return '0.1' if the version is not found. Raises an IOError
if it is not supported. | [
"Return",
"the",
"h5features",
"version",
"of",
"a",
"given",
"HDF5",
"group",
"."
] | d5f95db0f1cee58ac1ba4575d1212e796c39e1f9 | https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/version.py#L46-L64 | train | 25,923 |
bootphon/h5features | h5features/reader.py | Reader.read | def read(self, from_item=None, to_item=None,
from_time=None, to_time=None):
"""Retrieve requested data coordinates from the h5features index.
:param str from_item: Optional. Read the data starting from
this item. (defaults to the first stored item)
:param str to_item: ... | python | def read(self, from_item=None, to_item=None,
from_time=None, to_time=None):
"""Retrieve requested data coordinates from the h5features index.
:param str from_item: Optional. Read the data starting from
this item. (defaults to the first stored item)
:param str to_item: ... | [
"def",
"read",
"(",
"self",
",",
"from_item",
"=",
"None",
",",
"to_item",
"=",
"None",
",",
"from_time",
"=",
"None",
",",
"to_time",
"=",
"None",
")",
":",
"# handling default arguments",
"if",
"to_item",
"is",
"None",
":",
"to_item",
"=",
"self",
".",... | Retrieve requested data coordinates from the h5features index.
:param str from_item: Optional. Read the data starting from
this item. (defaults to the first stored item)
:param str to_item: Optional. Read the data until reaching the
item. (defaults to from_item if it was specif... | [
"Retrieve",
"requested",
"data",
"coordinates",
"from",
"the",
"h5features",
"index",
"."
] | d5f95db0f1cee58ac1ba4575d1212e796c39e1f9 | https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/reader.py#L102-L171 | train | 25,924 |
openai/pachi-py | pachi_py/pachi/tools/twogtp.py | GTP_game.writesgf | def writesgf(self, sgffilename):
"Write the game to an SGF file after a game"
size = self.size
outfile = open(sgffilename, "w")
if not outfile:
print "Couldn't create " + sgffilename
return
black_name = self.blackplayer.get_program_name()
white_na... | python | def writesgf(self, sgffilename):
"Write the game to an SGF file after a game"
size = self.size
outfile = open(sgffilename, "w")
if not outfile:
print "Couldn't create " + sgffilename
return
black_name = self.blackplayer.get_program_name()
white_na... | [
"def",
"writesgf",
"(",
"self",
",",
"sgffilename",
")",
":",
"size",
"=",
"self",
".",
"size",
"outfile",
"=",
"open",
"(",
"sgffilename",
",",
"\"w\"",
")",
"if",
"not",
"outfile",
":",
"print",
"\"Couldn't create \"",
"+",
"sgffilename",
"return",
"blac... | Write the game to an SGF file after a game | [
"Write",
"the",
"game",
"to",
"an",
"SGF",
"file",
"after",
"a",
"game"
] | 65f29fdd28747d34f2c3001f4016913e4aaeb8fc | https://github.com/openai/pachi-py/blob/65f29fdd28747d34f2c3001f4016913e4aaeb8fc/pachi_py/pachi/tools/twogtp.py#L272-L310 | train | 25,925 |
openai/pachi-py | pachi_py/pachi/tools/sgflib/sgflib.py | _escapeText | def _escapeText(text):
""" Adds backslash-escapes to property value characters that need them."""
output = ""
index = 0
match = reCharsToEscape.search(text, index)
while match:
output = output + text[index:match.start()] + '\\' + text[match.start()]
index = match.end()
match = reCharsToEscape.search(text, in... | python | def _escapeText(text):
""" Adds backslash-escapes to property value characters that need them."""
output = ""
index = 0
match = reCharsToEscape.search(text, index)
while match:
output = output + text[index:match.start()] + '\\' + text[match.start()]
index = match.end()
match = reCharsToEscape.search(text, in... | [
"def",
"_escapeText",
"(",
"text",
")",
":",
"output",
"=",
"\"\"",
"index",
"=",
"0",
"match",
"=",
"reCharsToEscape",
".",
"search",
"(",
"text",
",",
"index",
")",
"while",
"match",
":",
"output",
"=",
"output",
"+",
"text",
"[",
"index",
":",
"ma... | Adds backslash-escapes to property value characters that need them. | [
"Adds",
"backslash",
"-",
"escapes",
"to",
"property",
"value",
"characters",
"that",
"need",
"them",
"."
] | 65f29fdd28747d34f2c3001f4016913e4aaeb8fc | https://github.com/openai/pachi-py/blob/65f29fdd28747d34f2c3001f4016913e4aaeb8fc/pachi_py/pachi/tools/sgflib/sgflib.py#L579-L589 | train | 25,926 |
openai/pachi-py | pachi_py/pachi/tools/sgflib/sgflib.py | SGFParser.parse | def parse(self):
""" Parses the SGF data stored in 'self.data', and returns a 'Collection'."""
c = Collection()
while self.index < self.datalen:
g = self.parseOneGame()
if g:
c.append(g)
else:
break
return c | python | def parse(self):
""" Parses the SGF data stored in 'self.data', and returns a 'Collection'."""
c = Collection()
while self.index < self.datalen:
g = self.parseOneGame()
if g:
c.append(g)
else:
break
return c | [
"def",
"parse",
"(",
"self",
")",
":",
"c",
"=",
"Collection",
"(",
")",
"while",
"self",
".",
"index",
"<",
"self",
".",
"datalen",
":",
"g",
"=",
"self",
".",
"parseOneGame",
"(",
")",
"if",
"g",
":",
"c",
".",
"append",
"(",
"g",
")",
"else"... | Parses the SGF data stored in 'self.data', and returns a 'Collection'. | [
"Parses",
"the",
"SGF",
"data",
"stored",
"in",
"self",
".",
"data",
"and",
"returns",
"a",
"Collection",
"."
] | 65f29fdd28747d34f2c3001f4016913e4aaeb8fc | https://github.com/openai/pachi-py/blob/65f29fdd28747d34f2c3001f4016913e4aaeb8fc/pachi_py/pachi/tools/sgflib/sgflib.py#L153-L162 | train | 25,927 |
openai/pachi-py | pachi_py/pachi/tools/sgflib/sgflib.py | SGFParser.parseOneGame | def parseOneGame(self):
""" Parses one game from 'self.data'. Returns a 'GameTree' containing
one game, or 'None' if the end of 'self.data' has been reached."""
if self.index < self.datalen:
match = self.reGameTreeStart.match(self.data, self.index)
if match:
self.index = match.end()
return self.par... | python | def parseOneGame(self):
""" Parses one game from 'self.data'. Returns a 'GameTree' containing
one game, or 'None' if the end of 'self.data' has been reached."""
if self.index < self.datalen:
match = self.reGameTreeStart.match(self.data, self.index)
if match:
self.index = match.end()
return self.par... | [
"def",
"parseOneGame",
"(",
"self",
")",
":",
"if",
"self",
".",
"index",
"<",
"self",
".",
"datalen",
":",
"match",
"=",
"self",
".",
"reGameTreeStart",
".",
"match",
"(",
"self",
".",
"data",
",",
"self",
".",
"index",
")",
"if",
"match",
":",
"s... | Parses one game from 'self.data'. Returns a 'GameTree' containing
one game, or 'None' if the end of 'self.data' has been reached. | [
"Parses",
"one",
"game",
"from",
"self",
".",
"data",
".",
"Returns",
"a",
"GameTree",
"containing",
"one",
"game",
"or",
"None",
"if",
"the",
"end",
"of",
"self",
".",
"data",
"has",
"been",
"reached",
"."
] | 65f29fdd28747d34f2c3001f4016913e4aaeb8fc | https://github.com/openai/pachi-py/blob/65f29fdd28747d34f2c3001f4016913e4aaeb8fc/pachi_py/pachi/tools/sgflib/sgflib.py#L164-L172 | train | 25,928 |
openai/pachi-py | pachi_py/pachi/tools/sgflib/sgflib.py | Cursor.reset | def reset(self):
""" Set 'Cursor' to point to the start of the root 'GameTree', 'self.game'."""
self.gametree = self.game
self.nodenum = 0
self.index = 0
self.stack = []
self.node = self.gametree[self.index]
self._setChildren()
self._setFlags() | python | def reset(self):
""" Set 'Cursor' to point to the start of the root 'GameTree', 'self.game'."""
self.gametree = self.game
self.nodenum = 0
self.index = 0
self.stack = []
self.node = self.gametree[self.index]
self._setChildren()
self._setFlags() | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"gametree",
"=",
"self",
".",
"game",
"self",
".",
"nodenum",
"=",
"0",
"self",
".",
"index",
"=",
"0",
"self",
".",
"stack",
"=",
"[",
"]",
"self",
".",
"node",
"=",
"self",
".",
"gametree",
... | Set 'Cursor' to point to the start of the root 'GameTree', 'self.game'. | [
"Set",
"Cursor",
"to",
"point",
"to",
"the",
"start",
"of",
"the",
"root",
"GameTree",
"self",
".",
"game",
"."
] | 65f29fdd28747d34f2c3001f4016913e4aaeb8fc | https://github.com/openai/pachi-py/blob/65f29fdd28747d34f2c3001f4016913e4aaeb8fc/pachi_py/pachi/tools/sgflib/sgflib.py#L511-L519 | train | 25,929 |
openai/pachi-py | pachi_py/pachi/tools/sgflib/sgflib.py | Cursor.previous | def previous(self):
""" Moves the 'Cursor' to & returns the previous 'Node'. Raises
'GameTreeEndError' if the start of a branch is exceeded."""
if self.index - 1 >= 0: # more main line?
self.index = self.index - 1
elif self.stack: # were we in a variation?
self.gametree = self.stack.pop()
sel... | python | def previous(self):
""" Moves the 'Cursor' to & returns the previous 'Node'. Raises
'GameTreeEndError' if the start of a branch is exceeded."""
if self.index - 1 >= 0: # more main line?
self.index = self.index - 1
elif self.stack: # were we in a variation?
self.gametree = self.stack.pop()
sel... | [
"def",
"previous",
"(",
"self",
")",
":",
"if",
"self",
".",
"index",
"-",
"1",
">=",
"0",
":",
"# more main line?",
"self",
".",
"index",
"=",
"self",
".",
"index",
"-",
"1",
"elif",
"self",
".",
"stack",
":",
"# were we in a variation?",
"self",
".",... | Moves the 'Cursor' to & returns the previous 'Node'. Raises
'GameTreeEndError' if the start of a branch is exceeded. | [
"Moves",
"the",
"Cursor",
"to",
"&",
"returns",
"the",
"previous",
"Node",
".",
"Raises",
"GameTreeEndError",
"if",
"the",
"start",
"of",
"a",
"branch",
"is",
"exceeded",
"."
] | 65f29fdd28747d34f2c3001f4016913e4aaeb8fc | https://github.com/openai/pachi-py/blob/65f29fdd28747d34f2c3001f4016913e4aaeb8fc/pachi_py/pachi/tools/sgflib/sgflib.py#L548-L562 | train | 25,930 |
openai/pachi-py | pachi_py/pachi/tools/sgflib/sgflib.py | Cursor._setChildren | def _setChildren(self):
""" Sets up 'self.children'."""
if self.index + 1 < len(self.gametree):
self.children = [self.gametree[self.index+1]]
else:
self.children = map(lambda list: list[0], self.gametree.variations) | python | def _setChildren(self):
""" Sets up 'self.children'."""
if self.index + 1 < len(self.gametree):
self.children = [self.gametree[self.index+1]]
else:
self.children = map(lambda list: list[0], self.gametree.variations) | [
"def",
"_setChildren",
"(",
"self",
")",
":",
"if",
"self",
".",
"index",
"+",
"1",
"<",
"len",
"(",
"self",
".",
"gametree",
")",
":",
"self",
".",
"children",
"=",
"[",
"self",
".",
"gametree",
"[",
"self",
".",
"index",
"+",
"1",
"]",
"]",
"... | Sets up 'self.children'. | [
"Sets",
"up",
"self",
".",
"children",
"."
] | 65f29fdd28747d34f2c3001f4016913e4aaeb8fc | https://github.com/openai/pachi-py/blob/65f29fdd28747d34f2c3001f4016913e4aaeb8fc/pachi_py/pachi/tools/sgflib/sgflib.py#L564-L569 | train | 25,931 |
openai/pachi-py | pachi_py/pachi/tools/sgflib/sgflib.py | Cursor._setFlags | def _setFlags(self):
""" Sets up the flags 'self.atEnd' and 'self.atStart'."""
self.atEnd = not self.gametree.variations and (self.index + 1 == len(self.gametree))
self.atStart = not self.stack and (self.index == 0) | python | def _setFlags(self):
""" Sets up the flags 'self.atEnd' and 'self.atStart'."""
self.atEnd = not self.gametree.variations and (self.index + 1 == len(self.gametree))
self.atStart = not self.stack and (self.index == 0) | [
"def",
"_setFlags",
"(",
"self",
")",
":",
"self",
".",
"atEnd",
"=",
"not",
"self",
".",
"gametree",
".",
"variations",
"and",
"(",
"self",
".",
"index",
"+",
"1",
"==",
"len",
"(",
"self",
".",
"gametree",
")",
")",
"self",
".",
"atStart",
"=",
... | Sets up the flags 'self.atEnd' and 'self.atStart'. | [
"Sets",
"up",
"the",
"flags",
"self",
".",
"atEnd",
"and",
"self",
".",
"atStart",
"."
] | 65f29fdd28747d34f2c3001f4016913e4aaeb8fc | https://github.com/openai/pachi-py/blob/65f29fdd28747d34f2c3001f4016913e4aaeb8fc/pachi_py/pachi/tools/sgflib/sgflib.py#L571-L574 | train | 25,932 |
cjdrake/pyeda | pyeda/logic/addition.py | ripple_carry_add | def ripple_carry_add(A, B, cin=0):
"""Return symbolic logic for an N-bit ripple carry adder."""
if len(A) != len(B):
raise ValueError("expected A and B to be equal length")
ss, cs = list(), list()
for i, a in enumerate(A):
c = (cin if i == 0 else cs[i-1])
ss.append(a ^ B[i] ^ c)
... | python | def ripple_carry_add(A, B, cin=0):
"""Return symbolic logic for an N-bit ripple carry adder."""
if len(A) != len(B):
raise ValueError("expected A and B to be equal length")
ss, cs = list(), list()
for i, a in enumerate(A):
c = (cin if i == 0 else cs[i-1])
ss.append(a ^ B[i] ^ c)
... | [
"def",
"ripple_carry_add",
"(",
"A",
",",
"B",
",",
"cin",
"=",
"0",
")",
":",
"if",
"len",
"(",
"A",
")",
"!=",
"len",
"(",
"B",
")",
":",
"raise",
"ValueError",
"(",
"\"expected A and B to be equal length\"",
")",
"ss",
",",
"cs",
"=",
"list",
"(",... | Return symbolic logic for an N-bit ripple carry adder. | [
"Return",
"symbolic",
"logic",
"for",
"an",
"N",
"-",
"bit",
"ripple",
"carry",
"adder",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/logic/addition.py#L21-L30 | train | 25,933 |
cjdrake/pyeda | pyeda/logic/addition.py | kogge_stone_add | def kogge_stone_add(A, B, cin=0):
"""Return symbolic logic for an N-bit Kogge-Stone adder."""
if len(A) != len(B):
raise ValueError("expected A and B to be equal length")
N = len(A)
# generate/propagate logic
gs = [A[i] & B[i] for i in range(N)]
ps = [A[i] ^ B[i] for i in range(N)]
f... | python | def kogge_stone_add(A, B, cin=0):
"""Return symbolic logic for an N-bit Kogge-Stone adder."""
if len(A) != len(B):
raise ValueError("expected A and B to be equal length")
N = len(A)
# generate/propagate logic
gs = [A[i] & B[i] for i in range(N)]
ps = [A[i] ^ B[i] for i in range(N)]
f... | [
"def",
"kogge_stone_add",
"(",
"A",
",",
"B",
",",
"cin",
"=",
"0",
")",
":",
"if",
"len",
"(",
"A",
")",
"!=",
"len",
"(",
"B",
")",
":",
"raise",
"ValueError",
"(",
"\"expected A and B to be equal length\"",
")",
"N",
"=",
"len",
"(",
"A",
")",
"... | Return symbolic logic for an N-bit Kogge-Stone adder. | [
"Return",
"symbolic",
"logic",
"for",
"an",
"N",
"-",
"bit",
"Kogge",
"-",
"Stone",
"adder",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/logic/addition.py#L33-L49 | train | 25,934 |
cjdrake/pyeda | pyeda/logic/addition.py | brent_kung_add | def brent_kung_add(A, B, cin=0):
"""Return symbolic logic for an N-bit Brent-Kung adder."""
if len(A) != len(B):
raise ValueError("expected A and B to be equal length")
N = len(A)
# generate/propagate logic
gs = [A[i] & B[i] for i in range(N)]
ps = [A[i] ^ B[i] for i in range(N)]
# c... | python | def brent_kung_add(A, B, cin=0):
"""Return symbolic logic for an N-bit Brent-Kung adder."""
if len(A) != len(B):
raise ValueError("expected A and B to be equal length")
N = len(A)
# generate/propagate logic
gs = [A[i] & B[i] for i in range(N)]
ps = [A[i] ^ B[i] for i in range(N)]
# c... | [
"def",
"brent_kung_add",
"(",
"A",
",",
"B",
",",
"cin",
"=",
"0",
")",
":",
"if",
"len",
"(",
"A",
")",
"!=",
"len",
"(",
"B",
")",
":",
"raise",
"ValueError",
"(",
"\"expected A and B to be equal length\"",
")",
"N",
"=",
"len",
"(",
"A",
")",
"#... | Return symbolic logic for an N-bit Brent-Kung adder. | [
"Return",
"symbolic",
"logic",
"for",
"an",
"N",
"-",
"bit",
"Brent",
"-",
"Kung",
"adder",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/logic/addition.py#L52-L77 | train | 25,935 |
cjdrake/pyeda | pyeda/parsing/dimacs.py | _expect_token | def _expect_token(lexer, types):
"""Return the next token, or raise an exception."""
tok = next(lexer)
if any(isinstance(tok, t) for t in types):
return tok
else:
raise Error("unexpected token: " + str(tok)) | python | def _expect_token(lexer, types):
"""Return the next token, or raise an exception."""
tok = next(lexer)
if any(isinstance(tok, t) for t in types):
return tok
else:
raise Error("unexpected token: " + str(tok)) | [
"def",
"_expect_token",
"(",
"lexer",
",",
"types",
")",
":",
"tok",
"=",
"next",
"(",
"lexer",
")",
"if",
"any",
"(",
"isinstance",
"(",
"tok",
",",
"t",
")",
"for",
"t",
"in",
"types",
")",
":",
"return",
"tok",
"else",
":",
"raise",
"Error",
"... | Return the next token, or raise an exception. | [
"Return",
"the",
"next",
"token",
"or",
"raise",
"an",
"exception",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/dimacs.py#L134-L140 | train | 25,936 |
cjdrake/pyeda | pyeda/parsing/dimacs.py | parse_cnf | def parse_cnf(s, varname='x'):
"""
Parse an input string in DIMACS CNF format,
and return an expression abstract syntax tree.
Parameters
----------
s : str
String containing a DIMACS CNF.
varname : str, optional
The variable name used for creating literals.
Defaults... | python | def parse_cnf(s, varname='x'):
"""
Parse an input string in DIMACS CNF format,
and return an expression abstract syntax tree.
Parameters
----------
s : str
String containing a DIMACS CNF.
varname : str, optional
The variable name used for creating literals.
Defaults... | [
"def",
"parse_cnf",
"(",
"s",
",",
"varname",
"=",
"'x'",
")",
":",
"lexer",
"=",
"iter",
"(",
"CNFLexer",
"(",
"s",
")",
")",
"try",
":",
"ast",
"=",
"_cnf",
"(",
"lexer",
",",
"varname",
")",
"except",
"lex",
".",
"RunError",
"as",
"exc",
":",
... | Parse an input string in DIMACS CNF format,
and return an expression abstract syntax tree.
Parameters
----------
s : str
String containing a DIMACS CNF.
varname : str, optional
The variable name used for creating literals.
Defaults to 'x'.
Returns
-------
An as... | [
"Parse",
"an",
"input",
"string",
"in",
"DIMACS",
"CNF",
"format",
"and",
"return",
"an",
"expression",
"abstract",
"syntax",
"tree",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/dimacs.py#L143-L181 | train | 25,937 |
cjdrake/pyeda | pyeda/parsing/dimacs.py | _cnf | def _cnf(lexer, varname):
"""Return a DIMACS CNF."""
_expect_token(lexer, {KW_p})
_expect_token(lexer, {KW_cnf})
nvars = _expect_token(lexer, {IntegerToken}).value
nclauses = _expect_token(lexer, {IntegerToken}).value
return _cnf_formula(lexer, varname, nvars, nclauses) | python | def _cnf(lexer, varname):
"""Return a DIMACS CNF."""
_expect_token(lexer, {KW_p})
_expect_token(lexer, {KW_cnf})
nvars = _expect_token(lexer, {IntegerToken}).value
nclauses = _expect_token(lexer, {IntegerToken}).value
return _cnf_formula(lexer, varname, nvars, nclauses) | [
"def",
"_cnf",
"(",
"lexer",
",",
"varname",
")",
":",
"_expect_token",
"(",
"lexer",
",",
"{",
"KW_p",
"}",
")",
"_expect_token",
"(",
"lexer",
",",
"{",
"KW_cnf",
"}",
")",
"nvars",
"=",
"_expect_token",
"(",
"lexer",
",",
"{",
"IntegerToken",
"}",
... | Return a DIMACS CNF. | [
"Return",
"a",
"DIMACS",
"CNF",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/dimacs.py#L184-L190 | train | 25,938 |
cjdrake/pyeda | pyeda/parsing/dimacs.py | _cnf_formula | def _cnf_formula(lexer, varname, nvars, nclauses):
"""Return a DIMACS CNF formula."""
clauses = _clauses(lexer, varname, nvars)
if len(clauses) < nclauses:
fstr = "formula has fewer than {} clauses"
raise Error(fstr.format(nclauses))
if len(clauses) > nclauses:
fstr = "formula h... | python | def _cnf_formula(lexer, varname, nvars, nclauses):
"""Return a DIMACS CNF formula."""
clauses = _clauses(lexer, varname, nvars)
if len(clauses) < nclauses:
fstr = "formula has fewer than {} clauses"
raise Error(fstr.format(nclauses))
if len(clauses) > nclauses:
fstr = "formula h... | [
"def",
"_cnf_formula",
"(",
"lexer",
",",
"varname",
",",
"nvars",
",",
"nclauses",
")",
":",
"clauses",
"=",
"_clauses",
"(",
"lexer",
",",
"varname",
",",
"nvars",
")",
"if",
"len",
"(",
"clauses",
")",
"<",
"nclauses",
":",
"fstr",
"=",
"\"formula h... | Return a DIMACS CNF formula. | [
"Return",
"a",
"DIMACS",
"CNF",
"formula",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/dimacs.py#L193-L204 | train | 25,939 |
cjdrake/pyeda | pyeda/parsing/dimacs.py | _clauses | def _clauses(lexer, varname, nvars):
"""Return a tuple of DIMACS CNF clauses."""
tok = next(lexer)
toktype = type(tok)
if toktype is OP_not or toktype is IntegerToken:
lexer.unpop_token(tok)
first = _clause(lexer, varname, nvars)
rest = _clauses(lexer, varname, nvars)
ret... | python | def _clauses(lexer, varname, nvars):
"""Return a tuple of DIMACS CNF clauses."""
tok = next(lexer)
toktype = type(tok)
if toktype is OP_not or toktype is IntegerToken:
lexer.unpop_token(tok)
first = _clause(lexer, varname, nvars)
rest = _clauses(lexer, varname, nvars)
ret... | [
"def",
"_clauses",
"(",
"lexer",
",",
"varname",
",",
"nvars",
")",
":",
"tok",
"=",
"next",
"(",
"lexer",
")",
"toktype",
"=",
"type",
"(",
"tok",
")",
"if",
"toktype",
"is",
"OP_not",
"or",
"toktype",
"is",
"IntegerToken",
":",
"lexer",
".",
"unpop... | Return a tuple of DIMACS CNF clauses. | [
"Return",
"a",
"tuple",
"of",
"DIMACS",
"CNF",
"clauses",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/dimacs.py#L207-L219 | train | 25,940 |
cjdrake/pyeda | pyeda/parsing/dimacs.py | _lits | def _lits(lexer, varname, nvars):
"""Return a tuple of DIMACS CNF clause literals."""
tok = _expect_token(lexer, {OP_not, IntegerToken})
if isinstance(tok, IntegerToken) and tok.value == 0:
return tuple()
else:
if isinstance(tok, OP_not):
neg = True
tok = _expect_... | python | def _lits(lexer, varname, nvars):
"""Return a tuple of DIMACS CNF clause literals."""
tok = _expect_token(lexer, {OP_not, IntegerToken})
if isinstance(tok, IntegerToken) and tok.value == 0:
return tuple()
else:
if isinstance(tok, OP_not):
neg = True
tok = _expect_... | [
"def",
"_lits",
"(",
"lexer",
",",
"varname",
",",
"nvars",
")",
":",
"tok",
"=",
"_expect_token",
"(",
"lexer",
",",
"{",
"OP_not",
",",
"IntegerToken",
"}",
")",
"if",
"isinstance",
"(",
"tok",
",",
"IntegerToken",
")",
"and",
"tok",
".",
"value",
... | Return a tuple of DIMACS CNF clause literals. | [
"Return",
"a",
"tuple",
"of",
"DIMACS",
"CNF",
"clause",
"literals",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/dimacs.py#L227-L248 | train | 25,941 |
cjdrake/pyeda | pyeda/parsing/dimacs.py | parse_sat | def parse_sat(s, varname='x'):
"""
Parse an input string in DIMACS SAT format,
and return an expression.
"""
lexer = iter(SATLexer(s))
try:
ast = _sat(lexer, varname)
except lex.RunError as exc:
fstr = ("{0.args[0]}: "
"(line: {0.lineno}, offset: {0.offset}, ... | python | def parse_sat(s, varname='x'):
"""
Parse an input string in DIMACS SAT format,
and return an expression.
"""
lexer = iter(SATLexer(s))
try:
ast = _sat(lexer, varname)
except lex.RunError as exc:
fstr = ("{0.args[0]}: "
"(line: {0.lineno}, offset: {0.offset}, ... | [
"def",
"parse_sat",
"(",
"s",
",",
"varname",
"=",
"'x'",
")",
":",
"lexer",
"=",
"iter",
"(",
"SATLexer",
"(",
"s",
")",
")",
"try",
":",
"ast",
"=",
"_sat",
"(",
"lexer",
",",
"varname",
")",
"except",
"lex",
".",
"RunError",
"as",
"exc",
":",
... | Parse an input string in DIMACS SAT format,
and return an expression. | [
"Parse",
"an",
"input",
"string",
"in",
"DIMACS",
"SAT",
"format",
"and",
"return",
"an",
"expression",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/dimacs.py#L357-L374 | train | 25,942 |
cjdrake/pyeda | pyeda/parsing/dimacs.py | _sat | def _sat(lexer, varname):
"""Return a DIMACS SAT."""
_expect_token(lexer, {KW_p})
fmt = _expect_token(lexer, {KW_sat, KW_satx, KW_sate, KW_satex}).value
nvars = _expect_token(lexer, {IntegerToken}).value
return _sat_formula(lexer, varname, fmt, nvars) | python | def _sat(lexer, varname):
"""Return a DIMACS SAT."""
_expect_token(lexer, {KW_p})
fmt = _expect_token(lexer, {KW_sat, KW_satx, KW_sate, KW_satex}).value
nvars = _expect_token(lexer, {IntegerToken}).value
return _sat_formula(lexer, varname, fmt, nvars) | [
"def",
"_sat",
"(",
"lexer",
",",
"varname",
")",
":",
"_expect_token",
"(",
"lexer",
",",
"{",
"KW_p",
"}",
")",
"fmt",
"=",
"_expect_token",
"(",
"lexer",
",",
"{",
"KW_sat",
",",
"KW_satx",
",",
"KW_sate",
",",
"KW_satex",
"}",
")",
".",
"value",
... | Return a DIMACS SAT. | [
"Return",
"a",
"DIMACS",
"SAT",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/dimacs.py#L377-L382 | train | 25,943 |
cjdrake/pyeda | pyeda/parsing/dimacs.py | _sat_formula | def _sat_formula(lexer, varname, fmt, nvars):
"""Return a DIMACS SAT formula."""
types = {IntegerToken, LPAREN} | _SAT_TOKS[fmt]
tok = _expect_token(lexer, types)
# INT
if isinstance(tok, IntegerToken):
index = tok.value
if not 0 < index <= nvars:
fstr = "formula literal ... | python | def _sat_formula(lexer, varname, fmt, nvars):
"""Return a DIMACS SAT formula."""
types = {IntegerToken, LPAREN} | _SAT_TOKS[fmt]
tok = _expect_token(lexer, types)
# INT
if isinstance(tok, IntegerToken):
index = tok.value
if not 0 < index <= nvars:
fstr = "formula literal ... | [
"def",
"_sat_formula",
"(",
"lexer",
",",
"varname",
",",
"fmt",
",",
"nvars",
")",
":",
"types",
"=",
"{",
"IntegerToken",
",",
"LPAREN",
"}",
"|",
"_SAT_TOKS",
"[",
"fmt",
"]",
"tok",
"=",
"_expect_token",
"(",
"lexer",
",",
"types",
")",
"# INT",
... | Return a DIMACS SAT formula. | [
"Return",
"a",
"DIMACS",
"SAT",
"formula",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/dimacs.py#L385-L421 | train | 25,944 |
cjdrake/pyeda | pyeda/parsing/dimacs.py | _formulas | def _formulas(lexer, varname, fmt, nvars):
"""Return a tuple of DIMACS SAT formulas."""
types = {IntegerToken, LPAREN} | _SAT_TOKS[fmt]
tok = lexer.peek_token()
if any(isinstance(tok, t) for t in types):
first = _sat_formula(lexer, varname, fmt, nvars)
rest = _formulas(lexer, varname, fm... | python | def _formulas(lexer, varname, fmt, nvars):
"""Return a tuple of DIMACS SAT formulas."""
types = {IntegerToken, LPAREN} | _SAT_TOKS[fmt]
tok = lexer.peek_token()
if any(isinstance(tok, t) for t in types):
first = _sat_formula(lexer, varname, fmt, nvars)
rest = _formulas(lexer, varname, fm... | [
"def",
"_formulas",
"(",
"lexer",
",",
"varname",
",",
"fmt",
",",
"nvars",
")",
":",
"types",
"=",
"{",
"IntegerToken",
",",
"LPAREN",
"}",
"|",
"_SAT_TOKS",
"[",
"fmt",
"]",
"tok",
"=",
"lexer",
".",
"peek_token",
"(",
")",
"if",
"any",
"(",
"isi... | Return a tuple of DIMACS SAT formulas. | [
"Return",
"a",
"tuple",
"of",
"DIMACS",
"SAT",
"formulas",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/dimacs.py#L424-L434 | train | 25,945 |
cjdrake/pyeda | pyeda/parsing/dimacs.py | CNFLexer.keyword | def keyword(self, text):
"""Push a keyword onto the token queue."""
cls = self.KEYWORDS[text]
self.push_token(cls(text, self.lineno, self.offset)) | python | def keyword(self, text):
"""Push a keyword onto the token queue."""
cls = self.KEYWORDS[text]
self.push_token(cls(text, self.lineno, self.offset)) | [
"def",
"keyword",
"(",
"self",
",",
"text",
")",
":",
"cls",
"=",
"self",
".",
"KEYWORDS",
"[",
"text",
"]",
"self",
".",
"push_token",
"(",
"cls",
"(",
"text",
",",
"self",
".",
"lineno",
",",
"self",
".",
"offset",
")",
")"
] | Push a keyword onto the token queue. | [
"Push",
"a",
"keyword",
"onto",
"the",
"token",
"queue",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/dimacs.py#L91-L94 | train | 25,946 |
cjdrake/pyeda | pyeda/parsing/dimacs.py | CNFLexer.operator | def operator(self, text):
"""Push an operator onto the token queue."""
cls = self.OPERATORS[text]
self.push_token(cls(text, self.lineno, self.offset)) | python | def operator(self, text):
"""Push an operator onto the token queue."""
cls = self.OPERATORS[text]
self.push_token(cls(text, self.lineno, self.offset)) | [
"def",
"operator",
"(",
"self",
",",
"text",
")",
":",
"cls",
"=",
"self",
".",
"OPERATORS",
"[",
"text",
"]",
"self",
".",
"push_token",
"(",
"cls",
"(",
"text",
",",
"self",
".",
"lineno",
",",
"self",
".",
"offset",
")",
")"
] | Push an operator onto the token queue. | [
"Push",
"an",
"operator",
"onto",
"the",
"token",
"queue",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/dimacs.py#L96-L99 | train | 25,947 |
cjdrake/pyeda | pyeda/parsing/dimacs.py | SATLexer.punct | def punct(self, text):
"""Push punctuation onto the token queue."""
cls = self.PUNCTUATION[text]
self.push_token(cls(text, self.lineno, self.offset)) | python | def punct(self, text):
"""Push punctuation onto the token queue."""
cls = self.PUNCTUATION[text]
self.push_token(cls(text, self.lineno, self.offset)) | [
"def",
"punct",
"(",
"self",
",",
"text",
")",
":",
"cls",
"=",
"self",
".",
"PUNCTUATION",
"[",
"text",
"]",
"self",
".",
"push_token",
"(",
"cls",
"(",
"text",
",",
"self",
".",
"lineno",
",",
"self",
".",
"offset",
")",
")"
] | Push punctuation onto the token queue. | [
"Push",
"punctuation",
"onto",
"the",
"token",
"queue",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/dimacs.py#L266-L269 | train | 25,948 |
cjdrake/pyeda | pyeda/parsing/pla.py | parse | def parse(s):
"""
Parse an input string in PLA format,
and return an intermediate representation dict.
Parameters
----------
s : str
String containing a PLA.
Returns
-------
A dict with all PLA information:
=============== ============ ===========================... | python | def parse(s):
"""
Parse an input string in PLA format,
and return an intermediate representation dict.
Parameters
----------
s : str
String containing a PLA.
Returns
-------
A dict with all PLA information:
=============== ============ ===========================... | [
"def",
"parse",
"(",
"s",
")",
":",
"d",
"=",
"dict",
"(",
"ninputs",
"=",
"None",
",",
"noutputs",
"=",
"None",
",",
"input_labels",
"=",
"None",
",",
"output_labels",
"=",
"None",
",",
"intype",
"=",
"None",
",",
"cover",
"=",
"set",
"(",
")",
... | Parse an input string in PLA format,
and return an intermediate representation dict.
Parameters
----------
s : str
String containing a PLA.
Returns
-------
A dict with all PLA information:
=============== ============ =================================
Key ... | [
"Parse",
"an",
"input",
"string",
"in",
"PLA",
"format",
"and",
"return",
"an",
"intermediate",
"representation",
"dict",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/pla.py#L50-L151 | train | 25,949 |
cjdrake/pyeda | pyeda/parsing/lex.py | action | def action(toktype):
"""Return a parser action property."""
def outer(func):
"""Return a function that pushes a token onto the token queue."""
def inner(lexer, text):
"""Push a token onto the token queue."""
value = func(lexer, text)
lexer.tokens.append(toktyp... | python | def action(toktype):
"""Return a parser action property."""
def outer(func):
"""Return a function that pushes a token onto the token queue."""
def inner(lexer, text):
"""Push a token onto the token queue."""
value = func(lexer, text)
lexer.tokens.append(toktyp... | [
"def",
"action",
"(",
"toktype",
")",
":",
"def",
"outer",
"(",
"func",
")",
":",
"\"\"\"Return a function that pushes a token onto the token queue.\"\"\"",
"def",
"inner",
"(",
"lexer",
",",
"text",
")",
":",
"\"\"\"Push a token onto the token queue.\"\"\"",
"value",
"... | Return a parser action property. | [
"Return",
"a",
"parser",
"action",
"property",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/lex.py#L174-L183 | train | 25,950 |
cjdrake/pyeda | pyeda/parsing/lex.py | RegexLexer._compile_rules | def _compile_rules(self):
"""Compile the rules into the internal lexer state."""
for state, table in self.RULES.items():
patterns = list()
actions = list()
nextstates = list()
for i, row in enumerate(table):
if len(row) == 2:
... | python | def _compile_rules(self):
"""Compile the rules into the internal lexer state."""
for state, table in self.RULES.items():
patterns = list()
actions = list()
nextstates = list()
for i, row in enumerate(table):
if len(row) == 2:
... | [
"def",
"_compile_rules",
"(",
"self",
")",
":",
"for",
"state",
",",
"table",
"in",
"self",
".",
"RULES",
".",
"items",
"(",
")",
":",
"patterns",
"=",
"list",
"(",
")",
"actions",
"=",
"list",
"(",
")",
"nextstates",
"=",
"list",
"(",
")",
"for",
... | Compile the rules into the internal lexer state. | [
"Compile",
"the",
"rules",
"into",
"the",
"internal",
"lexer",
"state",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/lex.py#L83-L102 | train | 25,951 |
cjdrake/pyeda | pyeda/parsing/lex.py | RegexLexer._iter_tokens | def _iter_tokens(self):
"""Iterate through all tokens in the input string."""
reobj, actions, nextstates = self._rules[self.states[-1]]
mobj = reobj.match(self.string, self.pos)
while mobj is not None:
text = mobj.group(0)
idx = mobj.lastindex - 1
next... | python | def _iter_tokens(self):
"""Iterate through all tokens in the input string."""
reobj, actions, nextstates = self._rules[self.states[-1]]
mobj = reobj.match(self.string, self.pos)
while mobj is not None:
text = mobj.group(0)
idx = mobj.lastindex - 1
next... | [
"def",
"_iter_tokens",
"(",
"self",
")",
":",
"reobj",
",",
"actions",
",",
"nextstates",
"=",
"self",
".",
"_rules",
"[",
"self",
".",
"states",
"[",
"-",
"1",
"]",
"]",
"mobj",
"=",
"reobj",
".",
"match",
"(",
"self",
".",
"string",
",",
"self",
... | Iterate through all tokens in the input string. | [
"Iterate",
"through",
"all",
"tokens",
"in",
"the",
"input",
"string",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/lex.py#L104-L138 | train | 25,952 |
cjdrake/pyeda | pyeda/util.py | parity | def parity(num: int) -> int:
"""Return the parity of a non-negative integer.
For example, here are the parities of the first ten integers:
>>> [parity(n) for n in range(10)]
[0, 1, 1, 0, 1, 0, 0, 1, 1, 0]
This function is undefined for negative integers:
>>> parity(-1)
Traceback (most re... | python | def parity(num: int) -> int:
"""Return the parity of a non-negative integer.
For example, here are the parities of the first ten integers:
>>> [parity(n) for n in range(10)]
[0, 1, 1, 0, 1, 0, 0, 1, 1, 0]
This function is undefined for negative integers:
>>> parity(-1)
Traceback (most re... | [
"def",
"parity",
"(",
"num",
":",
"int",
")",
"->",
"int",
":",
"if",
"num",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"expected num >= 0\"",
")",
"par",
"=",
"0",
"while",
"num",
":",
"par",
"^=",
"(",
"num",
"&",
"1",
")",
"num",
">>=",
"1",... | Return the parity of a non-negative integer.
For example, here are the parities of the first ten integers:
>>> [parity(n) for n in range(10)]
[0, 1, 1, 0, 1, 0, 0, 1, 1, 0]
This function is undefined for negative integers:
>>> parity(-1)
Traceback (most recent call last):
...
Val... | [
"Return",
"the",
"parity",
"of",
"a",
"non",
"-",
"negative",
"integer",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/util.py#L56-L77 | train | 25,953 |
cjdrake/pyeda | pyeda/util.py | cached_property | def cached_property(func):
"""Return a cached property calculated by the input function.
Unlike the ``property`` decorator builtin, this decorator will cache the
return value in order to avoid repeated calculations.
This is particularly useful when the property involves some non-trivial
computation... | python | def cached_property(func):
"""Return a cached property calculated by the input function.
Unlike the ``property`` decorator builtin, this decorator will cache the
return value in order to avoid repeated calculations.
This is particularly useful when the property involves some non-trivial
computation... | [
"def",
"cached_property",
"(",
"func",
")",
":",
"def",
"get",
"(",
"self",
")",
":",
"\"\"\"this docstring will be over-written by func.__doc__\"\"\"",
"try",
":",
"return",
"self",
".",
"_property_cache",
"[",
"func",
"]",
"except",
"AttributeError",
":",
"self",
... | Return a cached property calculated by the input function.
Unlike the ``property`` decorator builtin, this decorator will cache the
return value in order to avoid repeated calculations.
This is particularly useful when the property involves some non-trivial
computation.
For example, consider a cla... | [
"Return",
"a",
"cached",
"property",
"calculated",
"by",
"the",
"input",
"function",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/util.py#L80-L116 | train | 25,954 |
cjdrake/pyeda | pyeda/boolalg/boolfunc.py | var | def var(name, index=None):
"""Return a unique Variable instance.
.. note::
Do **NOT** call this function directly.
Instead, use one of the concrete implementations:
* :func:`pyeda.boolalg.bdd.bddvar`
* :func:`pyeda.boolalg.expr.exprvar`,
* :func:`pyeda.boolalg.table.ttvar`.
... | python | def var(name, index=None):
"""Return a unique Variable instance.
.. note::
Do **NOT** call this function directly.
Instead, use one of the concrete implementations:
* :func:`pyeda.boolalg.bdd.bddvar`
* :func:`pyeda.boolalg.expr.exprvar`,
* :func:`pyeda.boolalg.table.ttvar`.
... | [
"def",
"var",
"(",
"name",
",",
"index",
"=",
"None",
")",
":",
"tname",
"=",
"type",
"(",
"name",
")",
"if",
"tname",
"is",
"str",
":",
"names",
"=",
"(",
"name",
",",
")",
"elif",
"tname",
"is",
"tuple",
":",
"names",
"=",
"name",
"else",
":"... | Return a unique Variable instance.
.. note::
Do **NOT** call this function directly.
Instead, use one of the concrete implementations:
* :func:`pyeda.boolalg.bdd.bddvar`
* :func:`pyeda.boolalg.expr.exprvar`,
* :func:`pyeda.boolalg.table.ttvar`. | [
"Return",
"a",
"unique",
"Variable",
"instance",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/boolfunc.py#L65-L120 | train | 25,955 |
cjdrake/pyeda | pyeda/boolalg/boolfunc.py | Function.iter_cofactors | def iter_cofactors(self, vs=None):
r"""Iterate through the cofactors of a function over N variables.
The *vs* argument is a sequence of :math:`N` Boolean variables.
The *cofactor* of :math:`f(x_1, x_2, \dots, x_i, \dots, x_n)`
with respect to variable :math:`x_i` is:
:math:`f_{... | python | def iter_cofactors(self, vs=None):
r"""Iterate through the cofactors of a function over N variables.
The *vs* argument is a sequence of :math:`N` Boolean variables.
The *cofactor* of :math:`f(x_1, x_2, \dots, x_i, \dots, x_n)`
with respect to variable :math:`x_i` is:
:math:`f_{... | [
"def",
"iter_cofactors",
"(",
"self",
",",
"vs",
"=",
"None",
")",
":",
"vs",
"=",
"self",
".",
"_expect_vars",
"(",
"vs",
")",
"for",
"point",
"in",
"iter_points",
"(",
"vs",
")",
":",
"yield",
"self",
".",
"restrict",
"(",
"point",
")"
] | r"""Iterate through the cofactors of a function over N variables.
The *vs* argument is a sequence of :math:`N` Boolean variables.
The *cofactor* of :math:`f(x_1, x_2, \dots, x_i, \dots, x_n)`
with respect to variable :math:`x_i` is:
:math:`f_{x_i} = f(x_1, x_2, \dots, 1, \dots, x_n)`
... | [
"r",
"Iterate",
"through",
"the",
"cofactors",
"of",
"a",
"function",
"over",
"N",
"variables",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/boolfunc.py#L633-L648 | train | 25,956 |
cjdrake/pyeda | pyeda/boolalg/boolfunc.py | Function.smoothing | def smoothing(self, vs=None):
r"""Return the smoothing of a function over a sequence of N variables.
The *vs* argument is a sequence of :math:`N` Boolean variables.
The *smoothing* of :math:`f(x_1, x_2, \dots, x_i, \dots, x_n)` with
respect to variable :math:`x_i` is:
:math:`S_... | python | def smoothing(self, vs=None):
r"""Return the smoothing of a function over a sequence of N variables.
The *vs* argument is a sequence of :math:`N` Boolean variables.
The *smoothing* of :math:`f(x_1, x_2, \dots, x_i, \dots, x_n)` with
respect to variable :math:`x_i` is:
:math:`S_... | [
"def",
"smoothing",
"(",
"self",
",",
"vs",
"=",
"None",
")",
":",
"return",
"functools",
".",
"reduce",
"(",
"operator",
".",
"or_",
",",
"self",
".",
"iter_cofactors",
"(",
"vs",
")",
")"
] | r"""Return the smoothing of a function over a sequence of N variables.
The *vs* argument is a sequence of :math:`N` Boolean variables.
The *smoothing* of :math:`f(x_1, x_2, \dots, x_i, \dots, x_n)` with
respect to variable :math:`x_i` is:
:math:`S_{x_i}(f) = f_{x_i} + f_{x_i'}`
... | [
"r",
"Return",
"the",
"smoothing",
"of",
"a",
"function",
"over",
"a",
"sequence",
"of",
"N",
"variables",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/boolfunc.py#L665-L677 | train | 25,957 |
cjdrake/pyeda | pyeda/boolalg/boolfunc.py | Function.consensus | def consensus(self, vs=None):
r"""Return the consensus of a function over a sequence of N variables.
The *vs* argument is a sequence of :math:`N` Boolean variables.
The *consensus* of :math:`f(x_1, x_2, \dots, x_i, \dots, x_n)` with
respect to variable :math:`x_i` is:
:math:`C_... | python | def consensus(self, vs=None):
r"""Return the consensus of a function over a sequence of N variables.
The *vs* argument is a sequence of :math:`N` Boolean variables.
The *consensus* of :math:`f(x_1, x_2, \dots, x_i, \dots, x_n)` with
respect to variable :math:`x_i` is:
:math:`C_... | [
"def",
"consensus",
"(",
"self",
",",
"vs",
"=",
"None",
")",
":",
"return",
"functools",
".",
"reduce",
"(",
"operator",
".",
"and_",
",",
"self",
".",
"iter_cofactors",
"(",
"vs",
")",
")"
] | r"""Return the consensus of a function over a sequence of N variables.
The *vs* argument is a sequence of :math:`N` Boolean variables.
The *consensus* of :math:`f(x_1, x_2, \dots, x_i, \dots, x_n)` with
respect to variable :math:`x_i` is:
:math:`C_{x_i}(f) = f_{x_i} \cdot f_{x_i'}`
... | [
"r",
"Return",
"the",
"consensus",
"of",
"a",
"function",
"over",
"a",
"sequence",
"of",
"N",
"variables",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/boolfunc.py#L679-L691 | train | 25,958 |
cjdrake/pyeda | pyeda/boolalg/boolfunc.py | Function.derivative | def derivative(self, vs=None):
r"""Return the derivative of a function over a sequence of N variables.
The *vs* argument is a sequence of :math:`N` Boolean variables.
The *derivative* of :math:`f(x_1, x_2, \dots, x_i, \dots, x_n)` with
respect to variable :math:`x_i` is:
:math:... | python | def derivative(self, vs=None):
r"""Return the derivative of a function over a sequence of N variables.
The *vs* argument is a sequence of :math:`N` Boolean variables.
The *derivative* of :math:`f(x_1, x_2, \dots, x_i, \dots, x_n)` with
respect to variable :math:`x_i` is:
:math:... | [
"def",
"derivative",
"(",
"self",
",",
"vs",
"=",
"None",
")",
":",
"return",
"functools",
".",
"reduce",
"(",
"operator",
".",
"xor",
",",
"self",
".",
"iter_cofactors",
"(",
"vs",
")",
")"
] | r"""Return the derivative of a function over a sequence of N variables.
The *vs* argument is a sequence of :math:`N` Boolean variables.
The *derivative* of :math:`f(x_1, x_2, \dots, x_i, \dots, x_n)` with
respect to variable :math:`x_i` is:
:math:`\frac{\partial}{\partial x_i} f = f_{x... | [
"r",
"Return",
"the",
"derivative",
"of",
"a",
"function",
"over",
"a",
"sequence",
"of",
"N",
"variables",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/boolfunc.py#L693-L704 | train | 25,959 |
cjdrake/pyeda | pyeda/boolalg/boolfunc.py | Function._expect_vars | def _expect_vars(vs=None):
"""Verify the input type and return a list of Variables."""
if vs is None:
return list()
elif isinstance(vs, Variable):
return [vs]
else:
checked = list()
# Will raise TypeError if vs is not iterable
f... | python | def _expect_vars(vs=None):
"""Verify the input type and return a list of Variables."""
if vs is None:
return list()
elif isinstance(vs, Variable):
return [vs]
else:
checked = list()
# Will raise TypeError if vs is not iterable
f... | [
"def",
"_expect_vars",
"(",
"vs",
"=",
"None",
")",
":",
"if",
"vs",
"is",
"None",
":",
"return",
"list",
"(",
")",
"elif",
"isinstance",
"(",
"vs",
",",
"Variable",
")",
":",
"return",
"[",
"vs",
"]",
"else",
":",
"checked",
"=",
"list",
"(",
")... | Verify the input type and return a list of Variables. | [
"Verify",
"the",
"input",
"type",
"and",
"return",
"a",
"list",
"of",
"Variables",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/boolfunc.py#L739-L754 | train | 25,960 |
cjdrake/pyeda | pyeda/logic/sudoku.py | SudokuSolver.solve | def solve(self, grid):
"""Return a solution point for a Sudoku grid."""
soln = self.S.satisfy_one(assumptions=self._parse_grid(grid))
return self.S.soln2point(soln, self.litmap) | python | def solve(self, grid):
"""Return a solution point for a Sudoku grid."""
soln = self.S.satisfy_one(assumptions=self._parse_grid(grid))
return self.S.soln2point(soln, self.litmap) | [
"def",
"solve",
"(",
"self",
",",
"grid",
")",
":",
"soln",
"=",
"self",
".",
"S",
".",
"satisfy_one",
"(",
"assumptions",
"=",
"self",
".",
"_parse_grid",
"(",
"grid",
")",
")",
"return",
"self",
".",
"S",
".",
"soln2point",
"(",
"soln",
",",
"sel... | Return a solution point for a Sudoku grid. | [
"Return",
"a",
"solution",
"point",
"for",
"a",
"Sudoku",
"grid",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/logic/sudoku.py#L38-L41 | train | 25,961 |
cjdrake/pyeda | pyeda/logic/sudoku.py | SudokuSolver._parse_grid | def _parse_grid(self, grid):
"""Return the input constraints for a Sudoku grid."""
chars = [c for c in grid if c in DIGITS or c in "0."]
if len(chars) != 9**2:
raise ValueError("expected 9x9 grid")
return [self.litmap[self.X[i // 9 + 1, i % 9 + 1, int(c)]]
for... | python | def _parse_grid(self, grid):
"""Return the input constraints for a Sudoku grid."""
chars = [c for c in grid if c in DIGITS or c in "0."]
if len(chars) != 9**2:
raise ValueError("expected 9x9 grid")
return [self.litmap[self.X[i // 9 + 1, i % 9 + 1, int(c)]]
for... | [
"def",
"_parse_grid",
"(",
"self",
",",
"grid",
")",
":",
"chars",
"=",
"[",
"c",
"for",
"c",
"in",
"grid",
"if",
"c",
"in",
"DIGITS",
"or",
"c",
"in",
"\"0.\"",
"]",
"if",
"len",
"(",
"chars",
")",
"!=",
"9",
"**",
"2",
":",
"raise",
"ValueErr... | Return the input constraints for a Sudoku grid. | [
"Return",
"the",
"input",
"constraints",
"for",
"a",
"Sudoku",
"grid",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/logic/sudoku.py#L47-L53 | train | 25,962 |
cjdrake/pyeda | pyeda/logic/sudoku.py | SudokuSolver._soln2str | def _soln2str(self, soln, fancy=False):
"""Convert a Sudoku solution point to a string."""
chars = list()
for r in range(1, 10):
for c in range(1, 10):
if fancy and c in (4, 7):
chars.append("|")
chars.append(self._get_val(soln, r, ... | python | def _soln2str(self, soln, fancy=False):
"""Convert a Sudoku solution point to a string."""
chars = list()
for r in range(1, 10):
for c in range(1, 10):
if fancy and c in (4, 7):
chars.append("|")
chars.append(self._get_val(soln, r, ... | [
"def",
"_soln2str",
"(",
"self",
",",
"soln",
",",
"fancy",
"=",
"False",
")",
":",
"chars",
"=",
"list",
"(",
")",
"for",
"r",
"in",
"range",
"(",
"1",
",",
"10",
")",
":",
"for",
"c",
"in",
"range",
"(",
"1",
",",
"10",
")",
":",
"if",
"f... | Convert a Sudoku solution point to a string. | [
"Convert",
"a",
"Sudoku",
"solution",
"point",
"to",
"a",
"string",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/logic/sudoku.py#L55-L67 | train | 25,963 |
cjdrake/pyeda | pyeda/logic/sudoku.py | SudokuSolver._get_val | def _get_val(self, soln, r, c):
"""Return the string value for a solution coordinate."""
for v in range(1, 10):
if soln[self.X[r, c, v]]:
return DIGITS[v-1]
return "X" | python | def _get_val(self, soln, r, c):
"""Return the string value for a solution coordinate."""
for v in range(1, 10):
if soln[self.X[r, c, v]]:
return DIGITS[v-1]
return "X" | [
"def",
"_get_val",
"(",
"self",
",",
"soln",
",",
"r",
",",
"c",
")",
":",
"for",
"v",
"in",
"range",
"(",
"1",
",",
"10",
")",
":",
"if",
"soln",
"[",
"self",
".",
"X",
"[",
"r",
",",
"c",
",",
"v",
"]",
"]",
":",
"return",
"DIGITS",
"["... | Return the string value for a solution coordinate. | [
"Return",
"the",
"string",
"value",
"for",
"a",
"solution",
"coordinate",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/logic/sudoku.py#L69-L74 | train | 25,964 |
cjdrake/pyeda | pyeda/boolalg/table.py | ttvar | def ttvar(name, index=None):
"""Return a TruthTable variable.
Parameters
----------
name : str
The variable's identifier string.
index : int or tuple[int], optional
One or more integer suffixes for variables that are part of a
multi-dimensional bit-vector, eg x[1], x[1][2][3... | python | def ttvar(name, index=None):
"""Return a TruthTable variable.
Parameters
----------
name : str
The variable's identifier string.
index : int or tuple[int], optional
One or more integer suffixes for variables that are part of a
multi-dimensional bit-vector, eg x[1], x[1][2][3... | [
"def",
"ttvar",
"(",
"name",
",",
"index",
"=",
"None",
")",
":",
"bvar",
"=",
"boolfunc",
".",
"var",
"(",
"name",
",",
"index",
")",
"try",
":",
"var",
"=",
"_VARS",
"[",
"bvar",
".",
"uniqid",
"]",
"except",
"KeyError",
":",
"var",
"=",
"_VARS... | Return a TruthTable variable.
Parameters
----------
name : str
The variable's identifier string.
index : int or tuple[int], optional
One or more integer suffixes for variables that are part of a
multi-dimensional bit-vector, eg x[1], x[1][2][3] | [
"Return",
"a",
"TruthTable",
"variable",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/table.py#L43-L59 | train | 25,965 |
cjdrake/pyeda | pyeda/boolalg/table.py | expr2truthtable | def expr2truthtable(expr):
"""Convert an expression into a truth table."""
inputs = [ttvar(v.names, v.indices) for v in expr.inputs]
return truthtable(inputs, expr.iter_image()) | python | def expr2truthtable(expr):
"""Convert an expression into a truth table."""
inputs = [ttvar(v.names, v.indices) for v in expr.inputs]
return truthtable(inputs, expr.iter_image()) | [
"def",
"expr2truthtable",
"(",
"expr",
")",
":",
"inputs",
"=",
"[",
"ttvar",
"(",
"v",
".",
"names",
",",
"v",
".",
"indices",
")",
"for",
"v",
"in",
"expr",
".",
"inputs",
"]",
"return",
"truthtable",
"(",
"inputs",
",",
"expr",
".",
"iter_image",
... | Convert an expression into a truth table. | [
"Convert",
"an",
"expression",
"into",
"a",
"truth",
"table",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/table.py#L99-L102 | train | 25,966 |
cjdrake/pyeda | pyeda/boolalg/table.py | truthtable2expr | def truthtable2expr(tt, conj=False):
"""Convert a truth table into an expression."""
if conj:
outer, inner = (And, Or)
nums = tt.pcdata.iter_zeros()
else:
outer, inner = (Or, And)
nums = tt.pcdata.iter_ones()
inputs = [exprvar(v.names, v.indices) for v in tt.inputs]
t... | python | def truthtable2expr(tt, conj=False):
"""Convert a truth table into an expression."""
if conj:
outer, inner = (And, Or)
nums = tt.pcdata.iter_zeros()
else:
outer, inner = (Or, And)
nums = tt.pcdata.iter_ones()
inputs = [exprvar(v.names, v.indices) for v in tt.inputs]
t... | [
"def",
"truthtable2expr",
"(",
"tt",
",",
"conj",
"=",
"False",
")",
":",
"if",
"conj",
":",
"outer",
",",
"inner",
"=",
"(",
"And",
",",
"Or",
")",
"nums",
"=",
"tt",
".",
"pcdata",
".",
"iter_zeros",
"(",
")",
"else",
":",
"outer",
",",
"inner"... | Convert a truth table into an expression. | [
"Convert",
"a",
"truth",
"table",
"into",
"an",
"expression",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/table.py#L105-L115 | train | 25,967 |
cjdrake/pyeda | pyeda/boolalg/table.py | _bin_zfill | def _bin_zfill(num, width=None):
"""Convert a base-10 number to a binary string.
Parameters
num: int
width: int, optional
Zero-extend the string to this width.
Examples
--------
>>> _bin_zfill(42)
'101010'
>>> _bin_zfill(42, 8)
'00101010'
"""
s = bin(num)[2:]
... | python | def _bin_zfill(num, width=None):
"""Convert a base-10 number to a binary string.
Parameters
num: int
width: int, optional
Zero-extend the string to this width.
Examples
--------
>>> _bin_zfill(42)
'101010'
>>> _bin_zfill(42, 8)
'00101010'
"""
s = bin(num)[2:]
... | [
"def",
"_bin_zfill",
"(",
"num",
",",
"width",
"=",
"None",
")",
":",
"s",
"=",
"bin",
"(",
"num",
")",
"[",
"2",
":",
"]",
"return",
"s",
"if",
"width",
"is",
"None",
"else",
"s",
".",
"zfill",
"(",
"width",
")"
] | Convert a base-10 number to a binary string.
Parameters
num: int
width: int, optional
Zero-extend the string to this width.
Examples
--------
>>> _bin_zfill(42)
'101010'
>>> _bin_zfill(42, 8)
'00101010' | [
"Convert",
"a",
"base",
"-",
"10",
"number",
"to",
"a",
"binary",
"string",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/table.py#L481-L497 | train | 25,968 |
cjdrake/pyeda | pyeda/boolalg/table.py | PCData.zero_mask | def zero_mask(self):
"""Return a mask to determine whether an array chunk has any zeros."""
accum = 0
for i in range(self.data.itemsize):
accum += (0x55 << (i << 3))
return accum | python | def zero_mask(self):
"""Return a mask to determine whether an array chunk has any zeros."""
accum = 0
for i in range(self.data.itemsize):
accum += (0x55 << (i << 3))
return accum | [
"def",
"zero_mask",
"(",
"self",
")",
":",
"accum",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"data",
".",
"itemsize",
")",
":",
"accum",
"+=",
"(",
"0x55",
"<<",
"(",
"i",
"<<",
"3",
")",
")",
"return",
"accum"
] | Return a mask to determine whether an array chunk has any zeros. | [
"Return",
"a",
"mask",
"to",
"determine",
"whether",
"an",
"array",
"chunk",
"has",
"any",
"zeros",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/table.py#L161-L166 | train | 25,969 |
cjdrake/pyeda | pyeda/boolalg/table.py | PCData.one_mask | def one_mask(self):
"""Return a mask to determine whether an array chunk has any ones."""
accum = 0
for i in range(self.data.itemsize):
accum += (0xAA << (i << 3))
return accum | python | def one_mask(self):
"""Return a mask to determine whether an array chunk has any ones."""
accum = 0
for i in range(self.data.itemsize):
accum += (0xAA << (i << 3))
return accum | [
"def",
"one_mask",
"(",
"self",
")",
":",
"accum",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"data",
".",
"itemsize",
")",
":",
"accum",
"+=",
"(",
"0xAA",
"<<",
"(",
"i",
"<<",
"3",
")",
")",
"return",
"accum"
] | Return a mask to determine whether an array chunk has any ones. | [
"Return",
"a",
"mask",
"to",
"determine",
"whether",
"an",
"array",
"chunk",
"has",
"any",
"ones",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/table.py#L169-L174 | train | 25,970 |
cjdrake/pyeda | pyeda/boolalg/table.py | PCData.iter_zeros | def iter_zeros(self):
"""Iterate through the indices of all zero items."""
num = quotient = 0
while num < self._len:
chunk = self.data[quotient]
if chunk & self.zero_mask:
remainder = 0
while remainder < self.width and num < self._len:
... | python | def iter_zeros(self):
"""Iterate through the indices of all zero items."""
num = quotient = 0
while num < self._len:
chunk = self.data[quotient]
if chunk & self.zero_mask:
remainder = 0
while remainder < self.width and num < self._len:
... | [
"def",
"iter_zeros",
"(",
"self",
")",
":",
"num",
"=",
"quotient",
"=",
"0",
"while",
"num",
"<",
"self",
".",
"_len",
":",
"chunk",
"=",
"self",
".",
"data",
"[",
"quotient",
"]",
"if",
"chunk",
"&",
"self",
".",
"zero_mask",
":",
"remainder",
"=... | Iterate through the indices of all zero items. | [
"Iterate",
"through",
"the",
"indices",
"of",
"all",
"zero",
"items",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/table.py#L176-L191 | train | 25,971 |
cjdrake/pyeda | pyeda/boolalg/table.py | PCData.find_one | def find_one(self):
"""
Return the first index of an entry that is either one or DC.
If no item is found, return None.
"""
num = quotient = 0
while num < self._len:
chunk = self.data[quotient]
if chunk & self.one_mask:
remainder = 0... | python | def find_one(self):
"""
Return the first index of an entry that is either one or DC.
If no item is found, return None.
"""
num = quotient = 0
while num < self._len:
chunk = self.data[quotient]
if chunk & self.one_mask:
remainder = 0... | [
"def",
"find_one",
"(",
"self",
")",
":",
"num",
"=",
"quotient",
"=",
"0",
"while",
"num",
"<",
"self",
".",
"_len",
":",
"chunk",
"=",
"self",
".",
"data",
"[",
"quotient",
"]",
"if",
"chunk",
"&",
"self",
".",
"one_mask",
":",
"remainder",
"=",
... | Return the first index of an entry that is either one or DC.
If no item is found, return None. | [
"Return",
"the",
"first",
"index",
"of",
"an",
"entry",
"that",
"is",
"either",
"one",
"or",
"DC",
".",
"If",
"no",
"item",
"is",
"found",
"return",
"None",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/table.py#L193-L212 | train | 25,972 |
cjdrake/pyeda | pyeda/boolalg/table.py | TruthTable.is_neg_unate | def is_neg_unate(self, vs=None):
r"""Return whether a function is negative unate.
A function :math:`f(x_1, x_2, ..., x_i, ..., x_n)` is *negative unate*
in variable :math:`x_i` if :math:`f_{x_i'} \geq f_{xi}`.
"""
vs = self._expect_vars(vs)
basis = self.support - set(vs)... | python | def is_neg_unate(self, vs=None):
r"""Return whether a function is negative unate.
A function :math:`f(x_1, x_2, ..., x_i, ..., x_n)` is *negative unate*
in variable :math:`x_i` if :math:`f_{x_i'} \geq f_{xi}`.
"""
vs = self._expect_vars(vs)
basis = self.support - set(vs)... | [
"def",
"is_neg_unate",
"(",
"self",
",",
"vs",
"=",
"None",
")",
":",
"vs",
"=",
"self",
".",
"_expect_vars",
"(",
"vs",
")",
"basis",
"=",
"self",
".",
"support",
"-",
"set",
"(",
"vs",
")",
"maxcov",
"=",
"[",
"PC_ONE",
"]",
"*",
"(",
"1",
"<... | r"""Return whether a function is negative unate.
A function :math:`f(x_1, x_2, ..., x_i, ..., x_n)` is *negative unate*
in variable :math:`x_i` if :math:`f_{x_i'} \geq f_{xi}`. | [
"r",
"Return",
"whether",
"a",
"function",
"is",
"negative",
"unate",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/table.py#L389-L404 | train | 25,973 |
cjdrake/pyeda | pyeda/boolalg/table.py | TruthTable._iter_restrict | def _iter_restrict(self, zeros, ones):
"""Iterate through indices of all table entries that vary."""
inputs = list(self.inputs)
unmapped = dict()
for i, v in enumerate(self.inputs):
if v in zeros:
inputs[i] = 0
elif v in ones:
input... | python | def _iter_restrict(self, zeros, ones):
"""Iterate through indices of all table entries that vary."""
inputs = list(self.inputs)
unmapped = dict()
for i, v in enumerate(self.inputs):
if v in zeros:
inputs[i] = 0
elif v in ones:
input... | [
"def",
"_iter_restrict",
"(",
"self",
",",
"zeros",
",",
"ones",
")",
":",
"inputs",
"=",
"list",
"(",
"self",
".",
"inputs",
")",
"unmapped",
"=",
"dict",
"(",
")",
"for",
"i",
",",
"v",
"in",
"enumerate",
"(",
"self",
".",
"inputs",
")",
":",
"... | Iterate through indices of all table entries that vary. | [
"Iterate",
"through",
"indices",
"of",
"all",
"table",
"entries",
"that",
"vary",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/table.py#L432-L447 | train | 25,974 |
cjdrake/pyeda | pyeda/boolalg/bdd.py | bddvar | def bddvar(name, index=None):
r"""Return a unique BDD variable.
A Boolean *variable* is an abstract numerical quantity that may assume any
value in the set :math:`B = \{0, 1\}`.
The ``bddvar`` function returns a unique Boolean variable instance
represented by a binary decision diagram.
Variable... | python | def bddvar(name, index=None):
r"""Return a unique BDD variable.
A Boolean *variable* is an abstract numerical quantity that may assume any
value in the set :math:`B = \{0, 1\}`.
The ``bddvar`` function returns a unique Boolean variable instance
represented by a binary decision diagram.
Variable... | [
"def",
"bddvar",
"(",
"name",
",",
"index",
"=",
"None",
")",
":",
"bvar",
"=",
"boolfunc",
".",
"var",
"(",
"name",
",",
"index",
")",
"try",
":",
"var",
"=",
"_VARS",
"[",
"bvar",
".",
"uniqid",
"]",
"except",
"KeyError",
":",
"var",
"=",
"_VAR... | r"""Return a unique BDD variable.
A Boolean *variable* is an abstract numerical quantity that may assume any
value in the set :math:`B = \{0, 1\}`.
The ``bddvar`` function returns a unique Boolean variable instance
represented by a binary decision diagram.
Variable instances may be used to symbolic... | [
"r",
"Return",
"a",
"unique",
"BDD",
"variable",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bdd.py#L68-L113 | train | 25,975 |
cjdrake/pyeda | pyeda/boolalg/bdd.py | _expr2bddnode | def _expr2bddnode(expr):
"""Convert an expression into a BDD node."""
if expr.is_zero():
return BDDNODEZERO
elif expr.is_one():
return BDDNODEONE
else:
top = expr.top
# Register this variable
_ = bddvar(top.names, top.indices)
root = top.uniqid
l... | python | def _expr2bddnode(expr):
"""Convert an expression into a BDD node."""
if expr.is_zero():
return BDDNODEZERO
elif expr.is_one():
return BDDNODEONE
else:
top = expr.top
# Register this variable
_ = bddvar(top.names, top.indices)
root = top.uniqid
l... | [
"def",
"_expr2bddnode",
"(",
"expr",
")",
":",
"if",
"expr",
".",
"is_zero",
"(",
")",
":",
"return",
"BDDNODEZERO",
"elif",
"expr",
".",
"is_one",
"(",
")",
":",
"return",
"BDDNODEONE",
"else",
":",
"top",
"=",
"expr",
".",
"top",
"# Register this varia... | Convert an expression into a BDD node. | [
"Convert",
"an",
"expression",
"into",
"a",
"BDD",
"node",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bdd.py#L116-L131 | train | 25,976 |
cjdrake/pyeda | pyeda/boolalg/bdd.py | bdd2expr | def bdd2expr(bdd, conj=False):
"""Convert a binary decision diagram into an expression.
This function will always return an expression in two-level form.
If *conj* is ``False``, return a sum of products (SOP).
Otherwise, return a product of sums (POS).
For example::
>>> a, b = map(bddvar, ... | python | def bdd2expr(bdd, conj=False):
"""Convert a binary decision diagram into an expression.
This function will always return an expression in two-level form.
If *conj* is ``False``, return a sum of products (SOP).
Otherwise, return a product of sums (POS).
For example::
>>> a, b = map(bddvar, ... | [
"def",
"bdd2expr",
"(",
"bdd",
",",
"conj",
"=",
"False",
")",
":",
"if",
"conj",
":",
"outer",
",",
"inner",
"=",
"(",
"And",
",",
"Or",
")",
"paths",
"=",
"_iter_all_paths",
"(",
"bdd",
".",
"node",
",",
"BDDNODEZERO",
")",
"else",
":",
"outer",
... | Convert a binary decision diagram into an expression.
This function will always return an expression in two-level form.
If *conj* is ``False``, return a sum of products (SOP).
Otherwise, return a product of sums (POS).
For example::
>>> a, b = map(bddvar, 'ab')
>>> bdd2expr(~a | b)
... | [
"Convert",
"a",
"binary",
"decision",
"diagram",
"into",
"an",
"expression",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bdd.py#L139-L163 | train | 25,977 |
cjdrake/pyeda | pyeda/boolalg/bdd.py | upoint2bddpoint | def upoint2bddpoint(upoint):
"""Convert an untyped point into a BDD point.
.. seealso::
For definitions of points and untyped points,
see the :mod:`pyeda.boolalg.boolfunc` module.
"""
point = dict()
for uniqid in upoint[0]:
point[_VARS[uniqid]] = 0
for uniqid in upoint[1]:... | python | def upoint2bddpoint(upoint):
"""Convert an untyped point into a BDD point.
.. seealso::
For definitions of points and untyped points,
see the :mod:`pyeda.boolalg.boolfunc` module.
"""
point = dict()
for uniqid in upoint[0]:
point[_VARS[uniqid]] = 0
for uniqid in upoint[1]:... | [
"def",
"upoint2bddpoint",
"(",
"upoint",
")",
":",
"point",
"=",
"dict",
"(",
")",
"for",
"uniqid",
"in",
"upoint",
"[",
"0",
"]",
":",
"point",
"[",
"_VARS",
"[",
"uniqid",
"]",
"]",
"=",
"0",
"for",
"uniqid",
"in",
"upoint",
"[",
"1",
"]",
":",... | Convert an untyped point into a BDD point.
.. seealso::
For definitions of points and untyped points,
see the :mod:`pyeda.boolalg.boolfunc` module. | [
"Convert",
"an",
"untyped",
"point",
"into",
"a",
"BDD",
"point",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bdd.py#L166-L178 | train | 25,978 |
cjdrake/pyeda | pyeda/boolalg/bdd.py | _bddnode | def _bddnode(root, lo, hi):
"""Return a unique BDD node."""
if lo is hi:
node = lo
else:
key = (root, lo, hi)
try:
node = _NODES[key]
except KeyError:
node = _NODES[key] = BDDNode(*key)
return node | python | def _bddnode(root, lo, hi):
"""Return a unique BDD node."""
if lo is hi:
node = lo
else:
key = (root, lo, hi)
try:
node = _NODES[key]
except KeyError:
node = _NODES[key] = BDDNode(*key)
return node | [
"def",
"_bddnode",
"(",
"root",
",",
"lo",
",",
"hi",
")",
":",
"if",
"lo",
"is",
"hi",
":",
"node",
"=",
"lo",
"else",
":",
"key",
"=",
"(",
"root",
",",
"lo",
",",
"hi",
")",
"try",
":",
"node",
"=",
"_NODES",
"[",
"key",
"]",
"except",
"... | Return a unique BDD node. | [
"Return",
"a",
"unique",
"BDD",
"node",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bdd.py#L198-L208 | train | 25,979 |
cjdrake/pyeda | pyeda/boolalg/bdd.py | _bdd | def _bdd(node):
"""Return a unique BDD."""
try:
bdd = _BDDS[node]
except KeyError:
bdd = _BDDS[node] = BinaryDecisionDiagram(node)
return bdd | python | def _bdd(node):
"""Return a unique BDD."""
try:
bdd = _BDDS[node]
except KeyError:
bdd = _BDDS[node] = BinaryDecisionDiagram(node)
return bdd | [
"def",
"_bdd",
"(",
"node",
")",
":",
"try",
":",
"bdd",
"=",
"_BDDS",
"[",
"node",
"]",
"except",
"KeyError",
":",
"bdd",
"=",
"_BDDS",
"[",
"node",
"]",
"=",
"BinaryDecisionDiagram",
"(",
"node",
")",
"return",
"bdd"
] | Return a unique BDD. | [
"Return",
"a",
"unique",
"BDD",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bdd.py#L211-L217 | train | 25,980 |
cjdrake/pyeda | pyeda/boolalg/bdd.py | _path2point | def _path2point(path):
"""Convert a BDD path to a BDD point."""
return {_VARS[node.root]: int(node.hi is path[i+1])
for i, node in enumerate(path[:-1])} | python | def _path2point(path):
"""Convert a BDD path to a BDD point."""
return {_VARS[node.root]: int(node.hi is path[i+1])
for i, node in enumerate(path[:-1])} | [
"def",
"_path2point",
"(",
"path",
")",
":",
"return",
"{",
"_VARS",
"[",
"node",
".",
"root",
"]",
":",
"int",
"(",
"node",
".",
"hi",
"is",
"path",
"[",
"i",
"+",
"1",
"]",
")",
"for",
"i",
",",
"node",
"in",
"enumerate",
"(",
"path",
"[",
... | Convert a BDD path to a BDD point. | [
"Convert",
"a",
"BDD",
"path",
"to",
"a",
"BDD",
"point",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bdd.py#L220-L223 | train | 25,981 |
cjdrake/pyeda | pyeda/boolalg/bdd.py | _find_path | def _find_path(start, end, path=tuple()):
"""Return the path from start to end.
If no path exists, return None.
"""
path = path + (start, )
if start is end:
return path
else:
ret = None
if start.lo is not None:
ret = _find_path(start.lo, end, path)
if... | python | def _find_path(start, end, path=tuple()):
"""Return the path from start to end.
If no path exists, return None.
"""
path = path + (start, )
if start is end:
return path
else:
ret = None
if start.lo is not None:
ret = _find_path(start.lo, end, path)
if... | [
"def",
"_find_path",
"(",
"start",
",",
"end",
",",
"path",
"=",
"tuple",
"(",
")",
")",
":",
"path",
"=",
"path",
"+",
"(",
"start",
",",
")",
"if",
"start",
"is",
"end",
":",
"return",
"path",
"else",
":",
"ret",
"=",
"None",
"if",
"start",
"... | Return the path from start to end.
If no path exists, return None. | [
"Return",
"the",
"path",
"from",
"start",
"to",
"end",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bdd.py#L507-L521 | train | 25,982 |
cjdrake/pyeda | pyeda/boolalg/bdd.py | _iter_all_paths | def _iter_all_paths(start, end, rand=False, path=tuple()):
"""Iterate through all paths from start to end."""
path = path + (start, )
if start is end:
yield path
else:
nodes = [start.lo, start.hi]
if rand: # pragma: no cover
random.shuffle(nodes)
for node in n... | python | def _iter_all_paths(start, end, rand=False, path=tuple()):
"""Iterate through all paths from start to end."""
path = path + (start, )
if start is end:
yield path
else:
nodes = [start.lo, start.hi]
if rand: # pragma: no cover
random.shuffle(nodes)
for node in n... | [
"def",
"_iter_all_paths",
"(",
"start",
",",
"end",
",",
"rand",
"=",
"False",
",",
"path",
"=",
"tuple",
"(",
")",
")",
":",
"path",
"=",
"path",
"+",
"(",
"start",
",",
")",
"if",
"start",
"is",
"end",
":",
"yield",
"path",
"else",
":",
"nodes"... | Iterate through all paths from start to end. | [
"Iterate",
"through",
"all",
"paths",
"from",
"start",
"to",
"end",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bdd.py#L524-L535 | train | 25,983 |
cjdrake/pyeda | pyeda/boolalg/bdd.py | _dfs_preorder | def _dfs_preorder(node, visited):
"""Iterate through nodes in DFS pre-order."""
if node not in visited:
visited.add(node)
yield node
if node.lo is not None:
yield from _dfs_preorder(node.lo, visited)
if node.hi is not None:
yield from _dfs_preorder(node.hi, visited) | python | def _dfs_preorder(node, visited):
"""Iterate through nodes in DFS pre-order."""
if node not in visited:
visited.add(node)
yield node
if node.lo is not None:
yield from _dfs_preorder(node.lo, visited)
if node.hi is not None:
yield from _dfs_preorder(node.hi, visited) | [
"def",
"_dfs_preorder",
"(",
"node",
",",
"visited",
")",
":",
"if",
"node",
"not",
"in",
"visited",
":",
"visited",
".",
"add",
"(",
"node",
")",
"yield",
"node",
"if",
"node",
".",
"lo",
"is",
"not",
"None",
":",
"yield",
"from",
"_dfs_preorder",
"... | Iterate through nodes in DFS pre-order. | [
"Iterate",
"through",
"nodes",
"in",
"DFS",
"pre",
"-",
"order",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bdd.py#L538-L546 | train | 25,984 |
cjdrake/pyeda | pyeda/boolalg/bdd.py | _dfs_postorder | def _dfs_postorder(node, visited):
"""Iterate through nodes in DFS post-order."""
if node.lo is not None:
yield from _dfs_postorder(node.lo, visited)
if node.hi is not None:
yield from _dfs_postorder(node.hi, visited)
if node not in visited:
visited.add(node)
yield node | python | def _dfs_postorder(node, visited):
"""Iterate through nodes in DFS post-order."""
if node.lo is not None:
yield from _dfs_postorder(node.lo, visited)
if node.hi is not None:
yield from _dfs_postorder(node.hi, visited)
if node not in visited:
visited.add(node)
yield node | [
"def",
"_dfs_postorder",
"(",
"node",
",",
"visited",
")",
":",
"if",
"node",
".",
"lo",
"is",
"not",
"None",
":",
"yield",
"from",
"_dfs_postorder",
"(",
"node",
".",
"lo",
",",
"visited",
")",
"if",
"node",
".",
"hi",
"is",
"not",
"None",
":",
"y... | Iterate through nodes in DFS post-order. | [
"Iterate",
"through",
"nodes",
"in",
"DFS",
"post",
"-",
"order",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bdd.py#L549-L557 | train | 25,985 |
cjdrake/pyeda | pyeda/boolalg/bdd.py | _bfs | def _bfs(node, visited):
"""Iterate through nodes in BFS order."""
queue = collections.deque()
queue.appendleft(node)
while queue:
node = queue.pop()
if node not in visited:
if node.lo is not None:
queue.appendleft(node.lo)
if node.hi is not None:
... | python | def _bfs(node, visited):
"""Iterate through nodes in BFS order."""
queue = collections.deque()
queue.appendleft(node)
while queue:
node = queue.pop()
if node not in visited:
if node.lo is not None:
queue.appendleft(node.lo)
if node.hi is not None:
... | [
"def",
"_bfs",
"(",
"node",
",",
"visited",
")",
":",
"queue",
"=",
"collections",
".",
"deque",
"(",
")",
"queue",
".",
"appendleft",
"(",
"node",
")",
"while",
"queue",
":",
"node",
"=",
"queue",
".",
"pop",
"(",
")",
"if",
"node",
"not",
"in",
... | Iterate through nodes in BFS order. | [
"Iterate",
"through",
"nodes",
"in",
"BFS",
"order",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bdd.py#L560-L572 | train | 25,986 |
cjdrake/pyeda | pyeda/parsing/boolexpr.py | parse | def parse(s):
"""
Parse a Boolean expression string,
and return an expression abstract syntax tree.
Parameters
----------
s : str
String containing a Boolean expression.
See ``pyeda.parsing.boolexpr.GRAMMAR`` for details.
Examples
--------
>>> parse("a | b ^ c & d")... | python | def parse(s):
"""
Parse a Boolean expression string,
and return an expression abstract syntax tree.
Parameters
----------
s : str
String containing a Boolean expression.
See ``pyeda.parsing.boolexpr.GRAMMAR`` for details.
Examples
--------
>>> parse("a | b ^ c & d")... | [
"def",
"parse",
"(",
"s",
")",
":",
"lexer",
"=",
"iter",
"(",
"BoolExprLexer",
"(",
"s",
")",
")",
"try",
":",
"expr",
"=",
"_expr",
"(",
"lexer",
")",
"except",
"lex",
".",
"RunError",
"as",
"exc",
":",
"fstr",
"=",
"(",
"\"{0.args[0]}: \"",
"\"(... | Parse a Boolean expression string,
and return an expression abstract syntax tree.
Parameters
----------
s : str
String containing a Boolean expression.
See ``pyeda.parsing.boolexpr.GRAMMAR`` for details.
Examples
--------
>>> parse("a | b ^ c & d")
('or', ('var', ('a',)... | [
"Parse",
"a",
"Boolean",
"expression",
"string",
"and",
"return",
"an",
"expression",
"abstract",
"syntax",
"tree",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/boolexpr.py#L340-L393 | train | 25,987 |
cjdrake/pyeda | pyeda/parsing/boolexpr.py | _ite | def _ite(lexer):
"""Return an ITE expression."""
s = _impl(lexer)
tok = next(lexer)
# IMPL '?' ITE ':' ITE
if isinstance(tok, OP_question):
d1 = _ite(lexer)
_expect_token(lexer, {OP_colon})
d0 = _ite(lexer)
return ('ite', s, d1, d0)
# IMPL
else:
lexer... | python | def _ite(lexer):
"""Return an ITE expression."""
s = _impl(lexer)
tok = next(lexer)
# IMPL '?' ITE ':' ITE
if isinstance(tok, OP_question):
d1 = _ite(lexer)
_expect_token(lexer, {OP_colon})
d0 = _ite(lexer)
return ('ite', s, d1, d0)
# IMPL
else:
lexer... | [
"def",
"_ite",
"(",
"lexer",
")",
":",
"s",
"=",
"_impl",
"(",
"lexer",
")",
"tok",
"=",
"next",
"(",
"lexer",
")",
"# IMPL '?' ITE ':' ITE",
"if",
"isinstance",
"(",
"tok",
",",
"OP_question",
")",
":",
"d1",
"=",
"_ite",
"(",
"lexer",
")",
"_expect... | Return an ITE expression. | [
"Return",
"an",
"ITE",
"expression",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/boolexpr.py#L410-L424 | train | 25,988 |
cjdrake/pyeda | pyeda/parsing/boolexpr.py | _impl | def _impl(lexer):
"""Return an Implies expression."""
p = _sumterm(lexer)
tok = next(lexer)
# SUMTERM '=>' IMPL
if isinstance(tok, OP_rarrow):
q = _impl(lexer)
return ('implies', p, q)
# SUMTERM '<=>' IMPL
elif isinstance(tok, OP_lrarrow):
q = _impl(lexer)
re... | python | def _impl(lexer):
"""Return an Implies expression."""
p = _sumterm(lexer)
tok = next(lexer)
# SUMTERM '=>' IMPL
if isinstance(tok, OP_rarrow):
q = _impl(lexer)
return ('implies', p, q)
# SUMTERM '<=>' IMPL
elif isinstance(tok, OP_lrarrow):
q = _impl(lexer)
re... | [
"def",
"_impl",
"(",
"lexer",
")",
":",
"p",
"=",
"_sumterm",
"(",
"lexer",
")",
"tok",
"=",
"next",
"(",
"lexer",
")",
"# SUMTERM '=>' IMPL",
"if",
"isinstance",
"(",
"tok",
",",
"OP_rarrow",
")",
":",
"q",
"=",
"_impl",
"(",
"lexer",
")",
"return",... | Return an Implies expression. | [
"Return",
"an",
"Implies",
"expression",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/boolexpr.py#L427-L443 | train | 25,989 |
cjdrake/pyeda | pyeda/parsing/boolexpr.py | _sumterm | def _sumterm(lexer):
"""Return a sum term expresssion."""
xorterm = _xorterm(lexer)
sumterm_prime = _sumterm_prime(lexer)
if sumterm_prime is None:
return xorterm
else:
return ('or', xorterm, sumterm_prime) | python | def _sumterm(lexer):
"""Return a sum term expresssion."""
xorterm = _xorterm(lexer)
sumterm_prime = _sumterm_prime(lexer)
if sumterm_prime is None:
return xorterm
else:
return ('or', xorterm, sumterm_prime) | [
"def",
"_sumterm",
"(",
"lexer",
")",
":",
"xorterm",
"=",
"_xorterm",
"(",
"lexer",
")",
"sumterm_prime",
"=",
"_sumterm_prime",
"(",
"lexer",
")",
"if",
"sumterm_prime",
"is",
"None",
":",
"return",
"xorterm",
"else",
":",
"return",
"(",
"'or'",
",",
"... | Return a sum term expresssion. | [
"Return",
"a",
"sum",
"term",
"expresssion",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/boolexpr.py#L446-L453 | train | 25,990 |
cjdrake/pyeda | pyeda/parsing/boolexpr.py | _sumterm_prime | def _sumterm_prime(lexer):
"""Return a sum term' expression, eliminates left recursion."""
tok = next(lexer)
# '|' XORTERM SUMTERM'
if isinstance(tok, OP_or):
xorterm = _xorterm(lexer)
sumterm_prime = _sumterm_prime(lexer)
if sumterm_prime is None:
return xorterm
... | python | def _sumterm_prime(lexer):
"""Return a sum term' expression, eliminates left recursion."""
tok = next(lexer)
# '|' XORTERM SUMTERM'
if isinstance(tok, OP_or):
xorterm = _xorterm(lexer)
sumterm_prime = _sumterm_prime(lexer)
if sumterm_prime is None:
return xorterm
... | [
"def",
"_sumterm_prime",
"(",
"lexer",
")",
":",
"tok",
"=",
"next",
"(",
"lexer",
")",
"# '|' XORTERM SUMTERM'",
"if",
"isinstance",
"(",
"tok",
",",
"OP_or",
")",
":",
"xorterm",
"=",
"_xorterm",
"(",
"lexer",
")",
"sumterm_prime",
"=",
"_sumterm_prime",
... | Return a sum term' expression, eliminates left recursion. | [
"Return",
"a",
"sum",
"term",
"expression",
"eliminates",
"left",
"recursion",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/boolexpr.py#L456-L470 | train | 25,991 |
cjdrake/pyeda | pyeda/parsing/boolexpr.py | _xorterm | def _xorterm(lexer):
"""Return an xor term expresssion."""
prodterm = _prodterm(lexer)
xorterm_prime = _xorterm_prime(lexer)
if xorterm_prime is None:
return prodterm
else:
return ('xor', prodterm, xorterm_prime) | python | def _xorterm(lexer):
"""Return an xor term expresssion."""
prodterm = _prodterm(lexer)
xorterm_prime = _xorterm_prime(lexer)
if xorterm_prime is None:
return prodterm
else:
return ('xor', prodterm, xorterm_prime) | [
"def",
"_xorterm",
"(",
"lexer",
")",
":",
"prodterm",
"=",
"_prodterm",
"(",
"lexer",
")",
"xorterm_prime",
"=",
"_xorterm_prime",
"(",
"lexer",
")",
"if",
"xorterm_prime",
"is",
"None",
":",
"return",
"prodterm",
"else",
":",
"return",
"(",
"'xor'",
",",... | Return an xor term expresssion. | [
"Return",
"an",
"xor",
"term",
"expresssion",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/boolexpr.py#L473-L480 | train | 25,992 |
cjdrake/pyeda | pyeda/parsing/boolexpr.py | _xorterm_prime | def _xorterm_prime(lexer):
"""Return an xor term' expression, eliminates left recursion."""
tok = next(lexer)
# '^' PRODTERM XORTERM'
if isinstance(tok, OP_xor):
prodterm = _prodterm(lexer)
xorterm_prime = _xorterm_prime(lexer)
if xorterm_prime is None:
return prodter... | python | def _xorterm_prime(lexer):
"""Return an xor term' expression, eliminates left recursion."""
tok = next(lexer)
# '^' PRODTERM XORTERM'
if isinstance(tok, OP_xor):
prodterm = _prodterm(lexer)
xorterm_prime = _xorterm_prime(lexer)
if xorterm_prime is None:
return prodter... | [
"def",
"_xorterm_prime",
"(",
"lexer",
")",
":",
"tok",
"=",
"next",
"(",
"lexer",
")",
"# '^' PRODTERM XORTERM'",
"if",
"isinstance",
"(",
"tok",
",",
"OP_xor",
")",
":",
"prodterm",
"=",
"_prodterm",
"(",
"lexer",
")",
"xorterm_prime",
"=",
"_xorterm_prime... | Return an xor term' expression, eliminates left recursion. | [
"Return",
"an",
"xor",
"term",
"expression",
"eliminates",
"left",
"recursion",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/boolexpr.py#L483-L497 | train | 25,993 |
cjdrake/pyeda | pyeda/parsing/boolexpr.py | _prodterm | def _prodterm(lexer):
"""Return a product term expression."""
factor = _factor(lexer)
prodterm_prime = _prodterm_prime(lexer)
if prodterm_prime is None:
return factor
else:
return ('and', factor, prodterm_prime) | python | def _prodterm(lexer):
"""Return a product term expression."""
factor = _factor(lexer)
prodterm_prime = _prodterm_prime(lexer)
if prodterm_prime is None:
return factor
else:
return ('and', factor, prodterm_prime) | [
"def",
"_prodterm",
"(",
"lexer",
")",
":",
"factor",
"=",
"_factor",
"(",
"lexer",
")",
"prodterm_prime",
"=",
"_prodterm_prime",
"(",
"lexer",
")",
"if",
"prodterm_prime",
"is",
"None",
":",
"return",
"factor",
"else",
":",
"return",
"(",
"'and'",
",",
... | Return a product term expression. | [
"Return",
"a",
"product",
"term",
"expression",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/boolexpr.py#L500-L507 | train | 25,994 |
cjdrake/pyeda | pyeda/parsing/boolexpr.py | _prodterm_prime | def _prodterm_prime(lexer):
"""Return a product term' expression, eliminates left recursion."""
tok = next(lexer)
# '&' FACTOR PRODTERM'
if isinstance(tok, OP_and):
factor = _factor(lexer)
prodterm_prime = _prodterm_prime(lexer)
if prodterm_prime is None:
return facto... | python | def _prodterm_prime(lexer):
"""Return a product term' expression, eliminates left recursion."""
tok = next(lexer)
# '&' FACTOR PRODTERM'
if isinstance(tok, OP_and):
factor = _factor(lexer)
prodterm_prime = _prodterm_prime(lexer)
if prodterm_prime is None:
return facto... | [
"def",
"_prodterm_prime",
"(",
"lexer",
")",
":",
"tok",
"=",
"next",
"(",
"lexer",
")",
"# '&' FACTOR PRODTERM'",
"if",
"isinstance",
"(",
"tok",
",",
"OP_and",
")",
":",
"factor",
"=",
"_factor",
"(",
"lexer",
")",
"prodterm_prime",
"=",
"_prodterm_prime",... | Return a product term' expression, eliminates left recursion. | [
"Return",
"a",
"product",
"term",
"expression",
"eliminates",
"left",
"recursion",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/boolexpr.py#L510-L524 | train | 25,995 |
cjdrake/pyeda | pyeda/parsing/boolexpr.py | _factor | def _factor(lexer):
"""Return a factor expression."""
tok = _expect_token(lexer, FACTOR_TOKS)
# '~' F
toktype = type(tok)
if toktype is OP_not:
return ('not', _factor(lexer))
# '(' EXPR ')'
elif toktype is LPAREN:
expr = _expr(lexer)
_expect_token(lexer, {RPAREN})
... | python | def _factor(lexer):
"""Return a factor expression."""
tok = _expect_token(lexer, FACTOR_TOKS)
# '~' F
toktype = type(tok)
if toktype is OP_not:
return ('not', _factor(lexer))
# '(' EXPR ')'
elif toktype is LPAREN:
expr = _expr(lexer)
_expect_token(lexer, {RPAREN})
... | [
"def",
"_factor",
"(",
"lexer",
")",
":",
"tok",
"=",
"_expect_token",
"(",
"lexer",
",",
"FACTOR_TOKS",
")",
"# '~' F",
"toktype",
"=",
"type",
"(",
"tok",
")",
"if",
"toktype",
"is",
"OP_not",
":",
"return",
"(",
"'not'",
",",
"_factor",
"(",
"lexer"... | Return a factor expression. | [
"Return",
"a",
"factor",
"expression",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/boolexpr.py#L527-L585 | train | 25,996 |
cjdrake/pyeda | pyeda/parsing/boolexpr.py | _zom_arg | def _zom_arg(lexer):
"""Return zero or more arguments."""
tok = next(lexer)
# ',' EXPR ZOM_X
if isinstance(tok, COMMA):
return (_expr(lexer), ) + _zom_arg(lexer)
# null
else:
lexer.unpop_token(tok)
return tuple() | python | def _zom_arg(lexer):
"""Return zero or more arguments."""
tok = next(lexer)
# ',' EXPR ZOM_X
if isinstance(tok, COMMA):
return (_expr(lexer), ) + _zom_arg(lexer)
# null
else:
lexer.unpop_token(tok)
return tuple() | [
"def",
"_zom_arg",
"(",
"lexer",
")",
":",
"tok",
"=",
"next",
"(",
"lexer",
")",
"# ',' EXPR ZOM_X",
"if",
"isinstance",
"(",
"tok",
",",
"COMMA",
")",
":",
"return",
"(",
"_expr",
"(",
"lexer",
")",
",",
")",
"+",
"_zom_arg",
"(",
"lexer",
")",
"... | Return zero or more arguments. | [
"Return",
"zero",
"or",
"more",
"arguments",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/boolexpr.py#L593-L602 | train | 25,997 |
cjdrake/pyeda | pyeda/parsing/boolexpr.py | _variable | def _variable(lexer):
"""Return a variable expression."""
names = _names(lexer)
tok = next(lexer)
# NAMES '[' ... ']'
if isinstance(tok, LBRACK):
indices = _indices(lexer)
_expect_token(lexer, {RBRACK})
# NAMES
else:
lexer.unpop_token(tok)
indices = tuple()
... | python | def _variable(lexer):
"""Return a variable expression."""
names = _names(lexer)
tok = next(lexer)
# NAMES '[' ... ']'
if isinstance(tok, LBRACK):
indices = _indices(lexer)
_expect_token(lexer, {RBRACK})
# NAMES
else:
lexer.unpop_token(tok)
indices = tuple()
... | [
"def",
"_variable",
"(",
"lexer",
")",
":",
"names",
"=",
"_names",
"(",
"lexer",
")",
"tok",
"=",
"next",
"(",
"lexer",
")",
"# NAMES '[' ... ']'",
"if",
"isinstance",
"(",
"tok",
",",
"LBRACK",
")",
":",
"indices",
"=",
"_indices",
"(",
"lexer",
")",... | Return a variable expression. | [
"Return",
"a",
"variable",
"expression",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/boolexpr.py#L605-L619 | train | 25,998 |
cjdrake/pyeda | pyeda/parsing/boolexpr.py | _names | def _names(lexer):
"""Return a tuple of names."""
first = _expect_token(lexer, {NameToken}).value
rest = _zom_name(lexer)
rnames = (first, ) + rest
return rnames[::-1] | python | def _names(lexer):
"""Return a tuple of names."""
first = _expect_token(lexer, {NameToken}).value
rest = _zom_name(lexer)
rnames = (first, ) + rest
return rnames[::-1] | [
"def",
"_names",
"(",
"lexer",
")",
":",
"first",
"=",
"_expect_token",
"(",
"lexer",
",",
"{",
"NameToken",
"}",
")",
".",
"value",
"rest",
"=",
"_zom_name",
"(",
"lexer",
")",
"rnames",
"=",
"(",
"first",
",",
")",
"+",
"rest",
"return",
"rnames",
... | Return a tuple of names. | [
"Return",
"a",
"tuple",
"of",
"names",
"."
] | 554ee53aa678f4b61bcd7e07ba2c74ddc749d665 | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/boolexpr.py#L622-L627 | train | 25,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.