repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
DEIB-GECO/PyGMQL | gmql/ml/genometric_space.py | GenometricSpace.best_descriptive_meta_dict | def best_descriptive_meta_dict(path_to_bag_of_genomes, cluster_no):
"""
Computes the importance of each metadata by using tf * coverage (the percentage of the term occuring in a cluster)
:param path_to_bag_of_genomes: The directory path
:param cluster_no: cluster number
:param preprocess: to remove the redundant information from the metadata
:return: returns the computed dictionary
"""
from nltk.corpus import stopwords
clusters = []
for file in Parser._get_files('.bag_of_genome', path_to_bag_of_genomes):
f = open(file, 'r')
text = f.read()
# process the text
word_list = []
for line in text.split('\n'):
try:
# take the right hand side of the = character
rhs = line.split('=')[1]
# omit the numbers
if not (len(rhs) < 3 or rhs[0].isdigit() or any([x in rhs for x in ['.','//','tcga']]) or GenometricSpace.validate_uuid(rhs)):
word_list.append(rhs)
except Exception as e:
# logging.exception(e)
pass
english_stopwords = stopwords.words('english')
genomic_stopwords = ['tcga']
extra_stopwords = ['yes','no', 'normal', 'low', 'high']
all_stopwords = english_stopwords + genomic_stopwords + extra_stopwords
filtered_words = [word for word in word_list if word not in all_stopwords]
new_text = ""
for word in filtered_words:
new_text += word
new_text += ' '
clusters.append(new_text)
all_clusters = ""
for c in clusters:
all_clusters += c
all_clusters_tf = GenometricSpace.tf(all_clusters)
cluster_dict = GenometricSpace.tf(clusters[cluster_no])
for key, value in cluster_dict.items():
new_val = cluster_dict[key] * (cluster_dict[key] / all_clusters_tf[key])
cluster_dict[key] = new_val
return cluster_dict | python | def best_descriptive_meta_dict(path_to_bag_of_genomes, cluster_no):
"""
Computes the importance of each metadata by using tf * coverage (the percentage of the term occuring in a cluster)
:param path_to_bag_of_genomes: The directory path
:param cluster_no: cluster number
:param preprocess: to remove the redundant information from the metadata
:return: returns the computed dictionary
"""
from nltk.corpus import stopwords
clusters = []
for file in Parser._get_files('.bag_of_genome', path_to_bag_of_genomes):
f = open(file, 'r')
text = f.read()
# process the text
word_list = []
for line in text.split('\n'):
try:
# take the right hand side of the = character
rhs = line.split('=')[1]
# omit the numbers
if not (len(rhs) < 3 or rhs[0].isdigit() or any([x in rhs for x in ['.','//','tcga']]) or GenometricSpace.validate_uuid(rhs)):
word_list.append(rhs)
except Exception as e:
# logging.exception(e)
pass
english_stopwords = stopwords.words('english')
genomic_stopwords = ['tcga']
extra_stopwords = ['yes','no', 'normal', 'low', 'high']
all_stopwords = english_stopwords + genomic_stopwords + extra_stopwords
filtered_words = [word for word in word_list if word not in all_stopwords]
new_text = ""
for word in filtered_words:
new_text += word
new_text += ' '
clusters.append(new_text)
all_clusters = ""
for c in clusters:
all_clusters += c
all_clusters_tf = GenometricSpace.tf(all_clusters)
cluster_dict = GenometricSpace.tf(clusters[cluster_no])
for key, value in cluster_dict.items():
new_val = cluster_dict[key] * (cluster_dict[key] / all_clusters_tf[key])
cluster_dict[key] = new_val
return cluster_dict | [
"def",
"best_descriptive_meta_dict",
"(",
"path_to_bag_of_genomes",
",",
"cluster_no",
")",
":",
"from",
"nltk",
".",
"corpus",
"import",
"stopwords",
"clusters",
"=",
"[",
"]",
"for",
"file",
"in",
"Parser",
".",
"_get_files",
"(",
"'.bag_of_genome'",
",",
"pat... | Computes the importance of each metadata by using tf * coverage (the percentage of the term occuring in a cluster)
:param path_to_bag_of_genomes: The directory path
:param cluster_no: cluster number
:param preprocess: to remove the redundant information from the metadata
:return: returns the computed dictionary | [
"Computes",
"the",
"importance",
"of",
"each",
"metadata",
"by",
"using",
"tf",
"*",
"coverage",
"(",
"the",
"percentage",
"of",
"the",
"term",
"occuring",
"in",
"a",
"cluster",
")"
] | train | https://github.com/DEIB-GECO/PyGMQL/blob/e58b2f9402a86056dcda484a32e3de0bb06ed991/gmql/ml/genometric_space.py#L251-L301 |
DEIB-GECO/PyGMQL | gmql/ml/genometric_space.py | GenometricSpace.visualize_cloud_of_words | def visualize_cloud_of_words(dictionary, image_path=None):
"""
Renders the cloud of words representation for a given dictionary of frequencies
:param dictionary: the dictionary object that contains key-frequency pairs
:param image_path: the path to the image mask, None if no masking is needed
"""
from PIL import Image
if image_path is not None:
mask = np.array(Image.open(image_path))
wc = WordCloud(mask=mask, background_color='white', width=1600, height=1200, prefer_horizontal=0.8)
wc = wc.generate_from_frequencies(dictionary)
else:
# Generate a word cloud image
wc = WordCloud(background_color='white', width=1600, height=1200, prefer_horizontal=0.8)
wc = wc.generate_from_frequencies(dictionary)
# Display the generated image:
# the matplotlib way:
import matplotlib.pyplot as plt
plt.rcParams['figure.figsize'] = (15, 15)
plt.imshow(wc, interpolation='bilinear')
plt.axis("off")
plt.show() | python | def visualize_cloud_of_words(dictionary, image_path=None):
"""
Renders the cloud of words representation for a given dictionary of frequencies
:param dictionary: the dictionary object that contains key-frequency pairs
:param image_path: the path to the image mask, None if no masking is needed
"""
from PIL import Image
if image_path is not None:
mask = np.array(Image.open(image_path))
wc = WordCloud(mask=mask, background_color='white', width=1600, height=1200, prefer_horizontal=0.8)
wc = wc.generate_from_frequencies(dictionary)
else:
# Generate a word cloud image
wc = WordCloud(background_color='white', width=1600, height=1200, prefer_horizontal=0.8)
wc = wc.generate_from_frequencies(dictionary)
# Display the generated image:
# the matplotlib way:
import matplotlib.pyplot as plt
plt.rcParams['figure.figsize'] = (15, 15)
plt.imshow(wc, interpolation='bilinear')
plt.axis("off")
plt.show() | [
"def",
"visualize_cloud_of_words",
"(",
"dictionary",
",",
"image_path",
"=",
"None",
")",
":",
"from",
"PIL",
"import",
"Image",
"if",
"image_path",
"is",
"not",
"None",
":",
"mask",
"=",
"np",
".",
"array",
"(",
"Image",
".",
"open",
"(",
"image_path",
... | Renders the cloud of words representation for a given dictionary of frequencies
:param dictionary: the dictionary object that contains key-frequency pairs
:param image_path: the path to the image mask, None if no masking is needed | [
"Renders",
"the",
"cloud",
"of",
"words",
"representation",
"for",
"a",
"given",
"dictionary",
"of",
"frequencies"
] | train | https://github.com/DEIB-GECO/PyGMQL/blob/e58b2f9402a86056dcda484a32e3de0bb06ed991/gmql/ml/genometric_space.py#L304-L329 |
DEIB-GECO/PyGMQL | gmql/ml/genometric_space.py | GenometricSpace.cloud_of_words | def cloud_of_words(path_to_bog, cluster_no, image_path=None):
"""
Draws the cloud of words representation
:param path_to_bog: path to bag of words
:param cluster_no: the number of document to be visualized
:param image_path: path to the image file for the masking, None if no masking is needed
"""
dictionary = GenometricSpace.best_descriptive_meta_dict(path_to_bog, cluster_no)
GenometricSpace.visualize_cloud_of_words(dictionary, image_path) | python | def cloud_of_words(path_to_bog, cluster_no, image_path=None):
"""
Draws the cloud of words representation
:param path_to_bog: path to bag of words
:param cluster_no: the number of document to be visualized
:param image_path: path to the image file for the masking, None if no masking is needed
"""
dictionary = GenometricSpace.best_descriptive_meta_dict(path_to_bog, cluster_no)
GenometricSpace.visualize_cloud_of_words(dictionary, image_path) | [
"def",
"cloud_of_words",
"(",
"path_to_bog",
",",
"cluster_no",
",",
"image_path",
"=",
"None",
")",
":",
"dictionary",
"=",
"GenometricSpace",
".",
"best_descriptive_meta_dict",
"(",
"path_to_bog",
",",
"cluster_no",
")",
"GenometricSpace",
".",
"visualize_cloud_of_w... | Draws the cloud of words representation
:param path_to_bog: path to bag of words
:param cluster_no: the number of document to be visualized
:param image_path: path to the image file for the masking, None if no masking is needed | [
"Draws",
"the",
"cloud",
"of",
"words",
"representation"
] | train | https://github.com/DEIB-GECO/PyGMQL/blob/e58b2f9402a86056dcda484a32e3de0bb06ed991/gmql/ml/genometric_space.py#L332-L342 |
DEIB-GECO/PyGMQL | gmql/ml/dataset/parser/parser.py | Parser._get_files | def _get_files(extension, path):
"""
Returns a sorted list of all of the files having the same extension under the same directory
:param extension: the extension of the data files such as 'gdm'
:param path: path to the folder containing the files
:return: sorted list of files
"""
# retrieves the files sharing the same extension
files = []
for file in os.listdir(path):
if file.endswith(extension):
files.append(os.path.join(path, file))
return sorted(files) | python | def _get_files(extension, path):
"""
Returns a sorted list of all of the files having the same extension under the same directory
:param extension: the extension of the data files such as 'gdm'
:param path: path to the folder containing the files
:return: sorted list of files
"""
# retrieves the files sharing the same extension
files = []
for file in os.listdir(path):
if file.endswith(extension):
files.append(os.path.join(path, file))
return sorted(files) | [
"def",
"_get_files",
"(",
"extension",
",",
"path",
")",
":",
"# retrieves the files sharing the same extension",
"files",
"=",
"[",
"]",
"for",
"file",
"in",
"os",
".",
"listdir",
"(",
"path",
")",
":",
"if",
"file",
".",
"endswith",
"(",
"extension",
")",
... | Returns a sorted list of all of the files having the same extension under the same directory
:param extension: the extension of the data files such as 'gdm'
:param path: path to the folder containing the files
:return: sorted list of files | [
"Returns",
"a",
"sorted",
"list",
"of",
"all",
"of",
"the",
"files",
"having",
"the",
"same",
"extension",
"under",
"the",
"same",
"directory",
":",
"param",
"extension",
":",
"the",
"extension",
"of",
"the",
"data",
"files",
"such",
"as",
"gdm",
":",
"p... | train | https://github.com/DEIB-GECO/PyGMQL/blob/e58b2f9402a86056dcda484a32e3de0bb06ed991/gmql/ml/dataset/parser/parser.py#L32-L44 |
DEIB-GECO/PyGMQL | gmql/ml/dataset/parser/parser.py | Parser._get_schema_file | def _get_schema_file(extension, path):
"""
Returns the schema file
:param extension: extension of the schema file usually .schema
:param path: path to the folder containing the schema file
:return: the path to the schema file
"""
for file in os.listdir(path):
if file.endswith(extension):
return os.path.join(path, file) | python | def _get_schema_file(extension, path):
"""
Returns the schema file
:param extension: extension of the schema file usually .schema
:param path: path to the folder containing the schema file
:return: the path to the schema file
"""
for file in os.listdir(path):
if file.endswith(extension):
return os.path.join(path, file) | [
"def",
"_get_schema_file",
"(",
"extension",
",",
"path",
")",
":",
"for",
"file",
"in",
"os",
".",
"listdir",
"(",
"path",
")",
":",
"if",
"file",
".",
"endswith",
"(",
"extension",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"path",
... | Returns the schema file
:param extension: extension of the schema file usually .schema
:param path: path to the folder containing the schema file
:return: the path to the schema file | [
"Returns",
"the",
"schema",
"file",
":",
"param",
"extension",
":",
"extension",
"of",
"the",
"schema",
"file",
"usually",
".",
"schema",
":",
"param",
"path",
":",
"path",
"to",
"the",
"folder",
"containing",
"the",
"schema",
"file",
":",
"return",
":",
... | train | https://github.com/DEIB-GECO/PyGMQL/blob/e58b2f9402a86056dcda484a32e3de0bb06ed991/gmql/ml/dataset/parser/parser.py#L47-L56 |
DEIB-GECO/PyGMQL | gmql/ml/dataset/parser/parser.py | Parser.parse_schema | def parse_schema(schema_file):
"""
parses the schema file and returns the columns that are later going to represent the columns of the genometric space dataframe
:param schema_file: the path to the schema file
:return: the columns of the schema file
"""
e = xml.etree.ElementTree.parse(schema_file)
root = e.getroot()
cols = []
for elem in root.findall(".//{http://genomic.elet.polimi.it/entities}field"): # XPATH
cols.append(elem.text)
return cols | python | def parse_schema(schema_file):
"""
parses the schema file and returns the columns that are later going to represent the columns of the genometric space dataframe
:param schema_file: the path to the schema file
:return: the columns of the schema file
"""
e = xml.etree.ElementTree.parse(schema_file)
root = e.getroot()
cols = []
for elem in root.findall(".//{http://genomic.elet.polimi.it/entities}field"): # XPATH
cols.append(elem.text)
return cols | [
"def",
"parse_schema",
"(",
"schema_file",
")",
":",
"e",
"=",
"xml",
".",
"etree",
".",
"ElementTree",
".",
"parse",
"(",
"schema_file",
")",
"root",
"=",
"e",
".",
"getroot",
"(",
")",
"cols",
"=",
"[",
"]",
"for",
"elem",
"in",
"root",
".",
"fin... | parses the schema file and returns the columns that are later going to represent the columns of the genometric space dataframe
:param schema_file: the path to the schema file
:return: the columns of the schema file | [
"parses",
"the",
"schema",
"file",
"and",
"returns",
"the",
"columns",
"that",
"are",
"later",
"going",
"to",
"represent",
"the",
"columns",
"of",
"the",
"genometric",
"space",
"dataframe",
":",
"param",
"schema_file",
":",
"the",
"path",
"to",
"the",
"schem... | train | https://github.com/DEIB-GECO/PyGMQL/blob/e58b2f9402a86056dcda484a32e3de0bb06ed991/gmql/ml/dataset/parser/parser.py#L59-L70 |
DEIB-GECO/PyGMQL | gmql/ml/dataset/parser/parser.py | Parser.parse_single_meta | def parse_single_meta(self, fname, selected_meta_data):
"""
Parses a single meta data file
:param fname: name of the file
:param selected_meta_data: If not none then only the specified columns of metadata are parsed
:return: the resulting pandas series
"""
# reads a meta data file into a dataframe
columns = []
data = []
with open(fname) as f:
for line in f:
splitted = line.split('\t')
columns.append(splitted[0])
data.append(splitted[1].split('\n')[0]) # to remove the \n values
df = pd.DataFrame(data=data, index=columns)
df = df.T
sample = self._get_sample_name(fname)
if selected_meta_data: # if null then keep all the columns
try:
df = df[selected_meta_data]
except:
pass
df['sample'] = sample
return df | python | def parse_single_meta(self, fname, selected_meta_data):
"""
Parses a single meta data file
:param fname: name of the file
:param selected_meta_data: If not none then only the specified columns of metadata are parsed
:return: the resulting pandas series
"""
# reads a meta data file into a dataframe
columns = []
data = []
with open(fname) as f:
for line in f:
splitted = line.split('\t')
columns.append(splitted[0])
data.append(splitted[1].split('\n')[0]) # to remove the \n values
df = pd.DataFrame(data=data, index=columns)
df = df.T
sample = self._get_sample_name(fname)
if selected_meta_data: # if null then keep all the columns
try:
df = df[selected_meta_data]
except:
pass
df['sample'] = sample
return df | [
"def",
"parse_single_meta",
"(",
"self",
",",
"fname",
",",
"selected_meta_data",
")",
":",
"# reads a meta data file into a dataframe",
"columns",
"=",
"[",
"]",
"data",
"=",
"[",
"]",
"with",
"open",
"(",
"fname",
")",
"as",
"f",
":",
"for",
"line",
"in",
... | Parses a single meta data file
:param fname: name of the file
:param selected_meta_data: If not none then only the specified columns of metadata are parsed
:return: the resulting pandas series | [
"Parses",
"a",
"single",
"meta",
"data",
"file",
":",
"param",
"fname",
":",
"name",
"of",
"the",
"file",
":",
"param",
"selected_meta_data",
":",
"If",
"not",
"none",
"then",
"only",
"the",
"specified",
"columns",
"of",
"metadata",
"are",
"parsed",
":",
... | train | https://github.com/DEIB-GECO/PyGMQL/blob/e58b2f9402a86056dcda484a32e3de0bb06ed991/gmql/ml/dataset/parser/parser.py#L83-L107 |
DEIB-GECO/PyGMQL | gmql/ml/dataset/parser/parser.py | Parser.parse_meta | def parse_meta(self, selected_meta_data):
"""
Parses all of the metadata files
:param selected_meta_data: if specified then only the columns that are contained here are going to be parsed
:return:
"""
# reads all meta data files
files = self._get_files("meta", self.path)
df = pd.DataFrame()
print("Parsing the metadata files...")
for f in tqdm(files):
data = self.parse_single_meta(f, selected_meta_data)
if data is not None:
df = pd.concat([df, data], axis=0)
df.index = df['sample']
#
# df = df.drop('sample', 1) # 1 for the columns
return df | python | def parse_meta(self, selected_meta_data):
"""
Parses all of the metadata files
:param selected_meta_data: if specified then only the columns that are contained here are going to be parsed
:return:
"""
# reads all meta data files
files = self._get_files("meta", self.path)
df = pd.DataFrame()
print("Parsing the metadata files...")
for f in tqdm(files):
data = self.parse_single_meta(f, selected_meta_data)
if data is not None:
df = pd.concat([df, data], axis=0)
df.index = df['sample']
#
# df = df.drop('sample', 1) # 1 for the columns
return df | [
"def",
"parse_meta",
"(",
"self",
",",
"selected_meta_data",
")",
":",
"# reads all meta data files",
"files",
"=",
"self",
".",
"_get_files",
"(",
"\"meta\"",
",",
"self",
".",
"path",
")",
"df",
"=",
"pd",
".",
"DataFrame",
"(",
")",
"print",
"(",
"\"Par... | Parses all of the metadata files
:param selected_meta_data: if specified then only the columns that are contained here are going to be parsed
:return: | [
"Parses",
"all",
"of",
"the",
"metadata",
"files",
":",
"param",
"selected_meta_data",
":",
"if",
"specified",
"then",
"only",
"the",
"columns",
"that",
"are",
"contained",
"here",
"are",
"going",
"to",
"be",
"parsed",
":",
"return",
":"
] | train | https://github.com/DEIB-GECO/PyGMQL/blob/e58b2f9402a86056dcda484a32e3de0bb06ed991/gmql/ml/dataset/parser/parser.py#L109-L126 |
DEIB-GECO/PyGMQL | gmql/ml/dataset/parser/parser.py | Parser.parse_single_data | def parse_single_data(self, path, cols, selected_region_data, selected_values, full_load):
"""
Parses a single region data file
:param path: path to the file
:param cols: the column names coming from the schema file
:param selected_region_data: the selected of the region data to be parsed
In most cases the analyst only needs a small subset of the region data
:param selected_values: the selected values to be put in the matrix cells
:param full_load: Specifies the method of parsing the data. If False then parser omits the parsing of zero(0)
values in order to speed up and save memory. However, while creating the matrix, those zero values are going to be put into the matrix.
(unless a row contains "all zero columns". This parsing is strongly recommended for sparse datasets.
If the full_load parameter is True then all the zero(0) data are going to be read.
:return: the dataframe containing the region data
"""
# reads a sample file
df = pd.read_table(path, engine='c', sep="\t", lineterminator="\n", header=None)
df.columns = cols # column names from schema
df = df[selected_region_data]
if not full_load:
if type(selected_values) is list:
df_2 = pd.DataFrame(dtype=float)
for value in selected_values:
df_3 = df.loc[df[value] != 0]
df_2 = pd.concat([df_2, df_3], axis=0)
df = df_2
else:
df = df.loc[df[selected_values] != 0]
sample = self._get_sample_name(path)
df['sample'] = sample
return df | python | def parse_single_data(self, path, cols, selected_region_data, selected_values, full_load):
"""
Parses a single region data file
:param path: path to the file
:param cols: the column names coming from the schema file
:param selected_region_data: the selected of the region data to be parsed
In most cases the analyst only needs a small subset of the region data
:param selected_values: the selected values to be put in the matrix cells
:param full_load: Specifies the method of parsing the data. If False then parser omits the parsing of zero(0)
values in order to speed up and save memory. However, while creating the matrix, those zero values are going to be put into the matrix.
(unless a row contains "all zero columns". This parsing is strongly recommended for sparse datasets.
If the full_load parameter is True then all the zero(0) data are going to be read.
:return: the dataframe containing the region data
"""
# reads a sample file
df = pd.read_table(path, engine='c', sep="\t", lineterminator="\n", header=None)
df.columns = cols # column names from schema
df = df[selected_region_data]
if not full_load:
if type(selected_values) is list:
df_2 = pd.DataFrame(dtype=float)
for value in selected_values:
df_3 = df.loc[df[value] != 0]
df_2 = pd.concat([df_2, df_3], axis=0)
df = df_2
else:
df = df.loc[df[selected_values] != 0]
sample = self._get_sample_name(path)
df['sample'] = sample
return df | [
"def",
"parse_single_data",
"(",
"self",
",",
"path",
",",
"cols",
",",
"selected_region_data",
",",
"selected_values",
",",
"full_load",
")",
":",
"# reads a sample file",
"df",
"=",
"pd",
".",
"read_table",
"(",
"path",
",",
"engine",
"=",
"'c'",
",",
"sep... | Parses a single region data file
:param path: path to the file
:param cols: the column names coming from the schema file
:param selected_region_data: the selected of the region data to be parsed
In most cases the analyst only needs a small subset of the region data
:param selected_values: the selected values to be put in the matrix cells
:param full_load: Specifies the method of parsing the data. If False then parser omits the parsing of zero(0)
values in order to speed up and save memory. However, while creating the matrix, those zero values are going to be put into the matrix.
(unless a row contains "all zero columns". This parsing is strongly recommended for sparse datasets.
If the full_load parameter is True then all the zero(0) data are going to be read.
:return: the dataframe containing the region data | [
"Parses",
"a",
"single",
"region",
"data",
"file",
":",
"param",
"path",
":",
"path",
"to",
"the",
"file",
":",
"param",
"cols",
":",
"the",
"column",
"names",
"coming",
"from",
"the",
"schema",
"file",
":",
"param",
"selected_region_data",
":",
"the",
"... | train | https://github.com/DEIB-GECO/PyGMQL/blob/e58b2f9402a86056dcda484a32e3de0bb06ed991/gmql/ml/dataset/parser/parser.py#L128-L159 |
DEIB-GECO/PyGMQL | gmql/ml/dataset/parser/parser.py | Parser.parse_data | def parse_data(self, selected_region_data, selected_values, full_load=False, extension="gdm"):
"""
Parses all of the region data
:param selected_region_data: the columns of region data that are needed
:param selected_values: the selected values to be put in the matrix cells
:param full_load: Specifies the method of parsing the data. If False then parser omits the parsing of zero(0)
values in order to speed up and save memory. However, while creating the matrix, those zero values are going to be put into the matrix.
(unless a row contains "all zero columns". This parsing is strongly recommended for sparse datasets.
If the full_load parameter is True then all the zero(0) data are going to be read.
:param extension: the extension of the region data files that are going to be parsed.
:return: the resulting region dataframe
"""
regions = list(selected_region_data)
if type(selected_values) is list:
regions.extend(selected_values)
else:
regions.append(selected_values)
files = self._get_files(extension, self.path)
df = pd.DataFrame(dtype=float)
cols = self.parse_schema(self.schema)
print("Parsing the data files...")
list_of_data = []
for f in tqdm(files):
data = self.parse_single_data(f, cols, regions, selected_values, full_load)
list_of_data.append(data)
print("pre-concat")
df = pd.concat(list_of_data)
return df | python | def parse_data(self, selected_region_data, selected_values, full_load=False, extension="gdm"):
"""
Parses all of the region data
:param selected_region_data: the columns of region data that are needed
:param selected_values: the selected values to be put in the matrix cells
:param full_load: Specifies the method of parsing the data. If False then parser omits the parsing of zero(0)
values in order to speed up and save memory. However, while creating the matrix, those zero values are going to be put into the matrix.
(unless a row contains "all zero columns". This parsing is strongly recommended for sparse datasets.
If the full_load parameter is True then all the zero(0) data are going to be read.
:param extension: the extension of the region data files that are going to be parsed.
:return: the resulting region dataframe
"""
regions = list(selected_region_data)
if type(selected_values) is list:
regions.extend(selected_values)
else:
regions.append(selected_values)
files = self._get_files(extension, self.path)
df = pd.DataFrame(dtype=float)
cols = self.parse_schema(self.schema)
print("Parsing the data files...")
list_of_data = []
for f in tqdm(files):
data = self.parse_single_data(f, cols, regions, selected_values, full_load)
list_of_data.append(data)
print("pre-concat")
df = pd.concat(list_of_data)
return df | [
"def",
"parse_data",
"(",
"self",
",",
"selected_region_data",
",",
"selected_values",
",",
"full_load",
"=",
"False",
",",
"extension",
"=",
"\"gdm\"",
")",
":",
"regions",
"=",
"list",
"(",
"selected_region_data",
")",
"if",
"type",
"(",
"selected_values",
"... | Parses all of the region data
:param selected_region_data: the columns of region data that are needed
:param selected_values: the selected values to be put in the matrix cells
:param full_load: Specifies the method of parsing the data. If False then parser omits the parsing of zero(0)
values in order to speed up and save memory. However, while creating the matrix, those zero values are going to be put into the matrix.
(unless a row contains "all zero columns". This parsing is strongly recommended for sparse datasets.
If the full_load parameter is True then all the zero(0) data are going to be read.
:param extension: the extension of the region data files that are going to be parsed.
:return: the resulting region dataframe | [
"Parses",
"all",
"of",
"the",
"region",
"data",
":",
"param",
"selected_region_data",
":",
"the",
"columns",
"of",
"region",
"data",
"that",
"are",
"needed",
":",
"param",
"selected_values",
":",
"the",
"selected",
"values",
"to",
"be",
"put",
"in",
"the",
... | train | https://github.com/DEIB-GECO/PyGMQL/blob/e58b2f9402a86056dcda484a32e3de0bb06ed991/gmql/ml/dataset/parser/parser.py#L161-L190 |
DEIB-GECO/PyGMQL | gmql/dataset/GDataframe.py | from_pandas | def from_pandas(regs, meta=None, chr_name=None, start_name=None, stop_name=None,
strand_name=None, sample_name=None):
""" Creates a GDataframe from a pandas dataframe of region and a pandas dataframe of metadata
:param regs: a pandas Dataframe of regions that is coherent with the GMQL data model
:param meta: (optional) a pandas Dataframe of metadata that is coherent with the regions
:param chr_name: (optional) which column of :attr:`~.regs` is the chromosome
:param start_name: (optional) which column of :attr:`~.regs` is the start
:param stop_name: (optional) which column of :attr:`~.regs` is the stop
:param strand_name: (optional) which column of :attr:`~.regs` is the strand
:param sample_name: (optional) which column of :attr:`~.regs` represents the sample name
of that region. If nothing is provided, all the region will be put in a single sample.
:return: a GDataframe
"""
regs = check_regs(regs, chr_name, start_name, stop_name, strand_name, sample_name)
regs = to_gmql_regions(regs)
if meta is not None:
if not check_meta(meta, regs):
raise ValueError("Error. Meta dataframe is not GMQL standard")
else:
meta = empty_meta(regs)
return GDataframe(regs, meta) | python | def from_pandas(regs, meta=None, chr_name=None, start_name=None, stop_name=None,
strand_name=None, sample_name=None):
""" Creates a GDataframe from a pandas dataframe of region and a pandas dataframe of metadata
:param regs: a pandas Dataframe of regions that is coherent with the GMQL data model
:param meta: (optional) a pandas Dataframe of metadata that is coherent with the regions
:param chr_name: (optional) which column of :attr:`~.regs` is the chromosome
:param start_name: (optional) which column of :attr:`~.regs` is the start
:param stop_name: (optional) which column of :attr:`~.regs` is the stop
:param strand_name: (optional) which column of :attr:`~.regs` is the strand
:param sample_name: (optional) which column of :attr:`~.regs` represents the sample name
of that region. If nothing is provided, all the region will be put in a single sample.
:return: a GDataframe
"""
regs = check_regs(regs, chr_name, start_name, stop_name, strand_name, sample_name)
regs = to_gmql_regions(regs)
if meta is not None:
if not check_meta(meta, regs):
raise ValueError("Error. Meta dataframe is not GMQL standard")
else:
meta = empty_meta(regs)
return GDataframe(regs, meta) | [
"def",
"from_pandas",
"(",
"regs",
",",
"meta",
"=",
"None",
",",
"chr_name",
"=",
"None",
",",
"start_name",
"=",
"None",
",",
"stop_name",
"=",
"None",
",",
"strand_name",
"=",
"None",
",",
"sample_name",
"=",
"None",
")",
":",
"regs",
"=",
"check_re... | Creates a GDataframe from a pandas dataframe of region and a pandas dataframe of metadata
:param regs: a pandas Dataframe of regions that is coherent with the GMQL data model
:param meta: (optional) a pandas Dataframe of metadata that is coherent with the regions
:param chr_name: (optional) which column of :attr:`~.regs` is the chromosome
:param start_name: (optional) which column of :attr:`~.regs` is the start
:param stop_name: (optional) which column of :attr:`~.regs` is the stop
:param strand_name: (optional) which column of :attr:`~.regs` is the strand
:param sample_name: (optional) which column of :attr:`~.regs` represents the sample name
of that region. If nothing is provided, all the region will be put in a single sample.
:return: a GDataframe | [
"Creates",
"a",
"GDataframe",
"from",
"a",
"pandas",
"dataframe",
"of",
"region",
"and",
"a",
"pandas",
"dataframe",
"of",
"metadata"
] | train | https://github.com/DEIB-GECO/PyGMQL/blob/e58b2f9402a86056dcda484a32e3de0bb06ed991/gmql/dataset/GDataframe.py#L146-L167 |
DEIB-GECO/PyGMQL | gmql/dataset/GDataframe.py | check_regs | def check_regs(region_df, chr_name=None, start_name=None, stop_name=None,
strand_name=None, sample_name=None):
""" Modifies a region dataframe to be coherent with the GMQL data model
:param region_df: a pandas Dataframe of regions that is coherent with the GMQL data model
:param chr_name: (optional) which column of :attr:`~.region_df` is the chromosome
:param start_name: (optional) which column of :attr:`~.region_df` is the start
:param stop_name: (optional) which column of :attr:`~.region_df` is the stop
:param strand_name: (optional) which column of :attr:`~.region_df` is the strand
:return: a modified pandas Dataframe
"""
if sample_name is None:
region_df.index = np.repeat(default_id_sample, len(region_df))
else:
region_df = search_column(region_df, id_sample_aliases,
id_sample_types, 'id_sample', sample_name)
region_df = region_df.set_index("id_sample", drop=True)
region_df = region_df.sort_index()
region_df = search_column(region_df, chr_aliases, chr_types, 'chr', chr_name)
region_df = search_column(region_df, start_aliases, start_types, 'start', start_name)
region_df = search_column(region_df, stop_aliases, stop_types, 'stop', stop_name)
region_df = search_column(region_df, strand_aliases, strand_types, 'strand', strand_name)
return region_df | python | def check_regs(region_df, chr_name=None, start_name=None, stop_name=None,
strand_name=None, sample_name=None):
""" Modifies a region dataframe to be coherent with the GMQL data model
:param region_df: a pandas Dataframe of regions that is coherent with the GMQL data model
:param chr_name: (optional) which column of :attr:`~.region_df` is the chromosome
:param start_name: (optional) which column of :attr:`~.region_df` is the start
:param stop_name: (optional) which column of :attr:`~.region_df` is the stop
:param strand_name: (optional) which column of :attr:`~.region_df` is the strand
:return: a modified pandas Dataframe
"""
if sample_name is None:
region_df.index = np.repeat(default_id_sample, len(region_df))
else:
region_df = search_column(region_df, id_sample_aliases,
id_sample_types, 'id_sample', sample_name)
region_df = region_df.set_index("id_sample", drop=True)
region_df = region_df.sort_index()
region_df = search_column(region_df, chr_aliases, chr_types, 'chr', chr_name)
region_df = search_column(region_df, start_aliases, start_types, 'start', start_name)
region_df = search_column(region_df, stop_aliases, stop_types, 'stop', stop_name)
region_df = search_column(region_df, strand_aliases, strand_types, 'strand', strand_name)
return region_df | [
"def",
"check_regs",
"(",
"region_df",
",",
"chr_name",
"=",
"None",
",",
"start_name",
"=",
"None",
",",
"stop_name",
"=",
"None",
",",
"strand_name",
"=",
"None",
",",
"sample_name",
"=",
"None",
")",
":",
"if",
"sample_name",
"is",
"None",
":",
"regio... | Modifies a region dataframe to be coherent with the GMQL data model
:param region_df: a pandas Dataframe of regions that is coherent with the GMQL data model
:param chr_name: (optional) which column of :attr:`~.region_df` is the chromosome
:param start_name: (optional) which column of :attr:`~.region_df` is the start
:param stop_name: (optional) which column of :attr:`~.region_df` is the stop
:param strand_name: (optional) which column of :attr:`~.region_df` is the strand
:return: a modified pandas Dataframe | [
"Modifies",
"a",
"region",
"dataframe",
"to",
"be",
"coherent",
"with",
"the",
"GMQL",
"data",
"model"
] | train | https://github.com/DEIB-GECO/PyGMQL/blob/e58b2f9402a86056dcda484a32e3de0bb06ed991/gmql/dataset/GDataframe.py#L170-L194 |
DEIB-GECO/PyGMQL | gmql/dataset/GDataframe.py | GDataframe.to_dataset_files | def to_dataset_files(self, local_path=None, remote_path=None):
""" Save the GDataframe to a local or remote location
:param local_path: a local path to the folder in which the data must be saved
:param remote_path: a remote dataset name that wants to be used for these data
:return: None
"""
return FrameToGMQL.to_dataset_files(self, path_local=local_path, path_remote=remote_path) | python | def to_dataset_files(self, local_path=None, remote_path=None):
""" Save the GDataframe to a local or remote location
:param local_path: a local path to the folder in which the data must be saved
:param remote_path: a remote dataset name that wants to be used for these data
:return: None
"""
return FrameToGMQL.to_dataset_files(self, path_local=local_path, path_remote=remote_path) | [
"def",
"to_dataset_files",
"(",
"self",
",",
"local_path",
"=",
"None",
",",
"remote_path",
"=",
"None",
")",
":",
"return",
"FrameToGMQL",
".",
"to_dataset_files",
"(",
"self",
",",
"path_local",
"=",
"local_path",
",",
"path_remote",
"=",
"remote_path",
")"
... | Save the GDataframe to a local or remote location
:param local_path: a local path to the folder in which the data must be saved
:param remote_path: a remote dataset name that wants to be used for these data
:return: None | [
"Save",
"the",
"GDataframe",
"to",
"a",
"local",
"or",
"remote",
"location"
] | train | https://github.com/DEIB-GECO/PyGMQL/blob/e58b2f9402a86056dcda484a32e3de0bb06ed991/gmql/dataset/GDataframe.py#L50-L57 |
DEIB-GECO/PyGMQL | gmql/dataset/GDataframe.py | GDataframe.to_GMQLDataset | def to_GMQLDataset(self, local_path=None, remote_path=None):
""" Converts the GDataframe in a GMQLDataset for later local or remote computation
:return: a GMQLDataset
"""
local = None
remote = None
if (local_path is None) and (remote_path is None):
# get a temporary path
local = TempFileManager.get_new_dataset_tmp_folder()
if local_path is not None:
local = local_path
if remote_path is not None:
remote = remote_path
self.to_dataset_files(local, remote)
if local is not None:
return Loader.load_from_path(local_path=local)
elif remote is not None:
raise NotImplementedError("The remote loading is not implemented yet!") | python | def to_GMQLDataset(self, local_path=None, remote_path=None):
""" Converts the GDataframe in a GMQLDataset for later local or remote computation
:return: a GMQLDataset
"""
local = None
remote = None
if (local_path is None) and (remote_path is None):
# get a temporary path
local = TempFileManager.get_new_dataset_tmp_folder()
if local_path is not None:
local = local_path
if remote_path is not None:
remote = remote_path
self.to_dataset_files(local, remote)
if local is not None:
return Loader.load_from_path(local_path=local)
elif remote is not None:
raise NotImplementedError("The remote loading is not implemented yet!") | [
"def",
"to_GMQLDataset",
"(",
"self",
",",
"local_path",
"=",
"None",
",",
"remote_path",
"=",
"None",
")",
":",
"local",
"=",
"None",
"remote",
"=",
"None",
"if",
"(",
"local_path",
"is",
"None",
")",
"and",
"(",
"remote_path",
"is",
"None",
")",
":",... | Converts the GDataframe in a GMQLDataset for later local or remote computation
:return: a GMQLDataset | [
"Converts",
"the",
"GDataframe",
"in",
"a",
"GMQLDataset",
"for",
"later",
"local",
"or",
"remote",
"computation"
] | train | https://github.com/DEIB-GECO/PyGMQL/blob/e58b2f9402a86056dcda484a32e3de0bb06ed991/gmql/dataset/GDataframe.py#L59-L78 |
DEIB-GECO/PyGMQL | gmql/dataset/GDataframe.py | GDataframe.project_meta | def project_meta(self, attributes):
""" Projects the specified metadata attributes to new region fields
:param attributes: a list of metadata attributes
:return: a new GDataframe with additional region fields
"""
if not isinstance(attributes, list):
raise TypeError('attributes must be a list')
meta_to_project = self.meta[attributes].applymap(lambda l: ", ".join(l))
new_regs = self.regs.merge(meta_to_project, left_index=True, right_index=True)
return GDataframe(regs=new_regs, meta=self.meta) | python | def project_meta(self, attributes):
""" Projects the specified metadata attributes to new region fields
:param attributes: a list of metadata attributes
:return: a new GDataframe with additional region fields
"""
if not isinstance(attributes, list):
raise TypeError('attributes must be a list')
meta_to_project = self.meta[attributes].applymap(lambda l: ", ".join(l))
new_regs = self.regs.merge(meta_to_project, left_index=True, right_index=True)
return GDataframe(regs=new_regs, meta=self.meta) | [
"def",
"project_meta",
"(",
"self",
",",
"attributes",
")",
":",
"if",
"not",
"isinstance",
"(",
"attributes",
",",
"list",
")",
":",
"raise",
"TypeError",
"(",
"'attributes must be a list'",
")",
"meta_to_project",
"=",
"self",
".",
"meta",
"[",
"attributes",... | Projects the specified metadata attributes to new region fields
:param attributes: a list of metadata attributes
:return: a new GDataframe with additional region fields | [
"Projects",
"the",
"specified",
"metadata",
"attributes",
"to",
"new",
"region",
"fields"
] | train | https://github.com/DEIB-GECO/PyGMQL/blob/e58b2f9402a86056dcda484a32e3de0bb06ed991/gmql/dataset/GDataframe.py#L85-L95 |
DEIB-GECO/PyGMQL | gmql/dataset/GDataframe.py | GDataframe.to_matrix | def to_matrix(self, index_regs=None, index_meta=None,
columns_regs=None, columns_meta=None,
values_regs=None, values_meta=None, **kwargs):
""" Transforms the GDataframe to a pivot matrix having as index and columns the
ones specified. This function is a wrapper around the pivot_table function of Pandas.
:param index_regs: list of region fields to use as index
:param index_meta: list of metadata attributes to use as index
:param columns_regs: list of region fields to use as columns
:param columns_meta: list of metadata attributes to use as columns
:param values_regs: list of region fields to use as values
:param values_meta: list of metadata attributes to use as values
:param kwargs: other parameters to pass to the pivot_table function
:return: a Pandas dataframe having as index the union of index_regs and index_meta, as
columns the union of columns_regs and columns_meta and as values ths union
of values_regs and values_meta
"""
index_regs = index_regs if index_regs is not None else []
index_meta = index_meta if index_meta is not None else []
columns_regs = columns_regs if columns_regs is not None else []
columns_meta = columns_meta if columns_meta is not None else []
values_regs = values_regs if values_regs is not None else []
values_meta = values_meta if values_meta is not None else []
index_meta_s = set(index_meta)
columns_meta_s = set(columns_meta)
values_meta_s = set(values_meta)
meta_to_project = list(index_meta_s.union(columns_meta_s)\
.union(values_meta_s)\
.difference(set(self.regs.columns)))
res = self.project_meta(meta_to_project)
pivot_columns = columns_meta + columns_regs
pivot_index = index_meta + index_regs
pivot_values = values_regs + values_meta
return res.regs.pivot_table(index=pivot_index, columns=pivot_columns, values=pivot_values, **kwargs) | python | def to_matrix(self, index_regs=None, index_meta=None,
columns_regs=None, columns_meta=None,
values_regs=None, values_meta=None, **kwargs):
""" Transforms the GDataframe to a pivot matrix having as index and columns the
ones specified. This function is a wrapper around the pivot_table function of Pandas.
:param index_regs: list of region fields to use as index
:param index_meta: list of metadata attributes to use as index
:param columns_regs: list of region fields to use as columns
:param columns_meta: list of metadata attributes to use as columns
:param values_regs: list of region fields to use as values
:param values_meta: list of metadata attributes to use as values
:param kwargs: other parameters to pass to the pivot_table function
:return: a Pandas dataframe having as index the union of index_regs and index_meta, as
columns the union of columns_regs and columns_meta and as values ths union
of values_regs and values_meta
"""
index_regs = index_regs if index_regs is not None else []
index_meta = index_meta if index_meta is not None else []
columns_regs = columns_regs if columns_regs is not None else []
columns_meta = columns_meta if columns_meta is not None else []
values_regs = values_regs if values_regs is not None else []
values_meta = values_meta if values_meta is not None else []
index_meta_s = set(index_meta)
columns_meta_s = set(columns_meta)
values_meta_s = set(values_meta)
meta_to_project = list(index_meta_s.union(columns_meta_s)\
.union(values_meta_s)\
.difference(set(self.regs.columns)))
res = self.project_meta(meta_to_project)
pivot_columns = columns_meta + columns_regs
pivot_index = index_meta + index_regs
pivot_values = values_regs + values_meta
return res.regs.pivot_table(index=pivot_index, columns=pivot_columns, values=pivot_values, **kwargs) | [
"def",
"to_matrix",
"(",
"self",
",",
"index_regs",
"=",
"None",
",",
"index_meta",
"=",
"None",
",",
"columns_regs",
"=",
"None",
",",
"columns_meta",
"=",
"None",
",",
"values_regs",
"=",
"None",
",",
"values_meta",
"=",
"None",
",",
"*",
"*",
"kwargs"... | Transforms the GDataframe to a pivot matrix having as index and columns the
ones specified. This function is a wrapper around the pivot_table function of Pandas.
:param index_regs: list of region fields to use as index
:param index_meta: list of metadata attributes to use as index
:param columns_regs: list of region fields to use as columns
:param columns_meta: list of metadata attributes to use as columns
:param values_regs: list of region fields to use as values
:param values_meta: list of metadata attributes to use as values
:param kwargs: other parameters to pass to the pivot_table function
:return: a Pandas dataframe having as index the union of index_regs and index_meta, as
columns the union of columns_regs and columns_meta and as values ths union
of values_regs and values_meta | [
"Transforms",
"the",
"GDataframe",
"to",
"a",
"pivot",
"matrix",
"having",
"as",
"index",
"and",
"columns",
"the",
"ones",
"specified",
".",
"This",
"function",
"is",
"a",
"wrapper",
"around",
"the",
"pivot_table",
"function",
"of",
"Pandas",
"."
] | train | https://github.com/DEIB-GECO/PyGMQL/blob/e58b2f9402a86056dcda484a32e3de0bb06ed991/gmql/dataset/GDataframe.py#L97-L134 |
huffpostdata/python-pollster | pollster/api.py | Api.charts_get | def charts_get(self, **kwargs):
"""
Charts
Returns a list of Charts, ordered by creation date (newest first). A Chart is chosen by Pollster editors. One example is \"Obama job approval - Democrats\". It is always based upon a single Question. Users should strongly consider basing their analysis on Questions instead. Charts are derived data; Pollster editors publish them and change them as editorial priorities change.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.charts_get(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str cursor: Special string to index into the Array
:param str tags: Comma-separated list of tag slugs. Only Charts with one or more of these tags and Charts based on Questions with one or more of these tags will be returned.
:param date election_date: Date of an election, in YYYY-MM-DD format. Only Charts based on Questions pertaining to an election on this date will be returned.
:return: InlineResponse200
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.charts_get_with_http_info(**kwargs)
else:
(data) = self.charts_get_with_http_info(**kwargs)
return data | python | def charts_get(self, **kwargs):
"""
Charts
Returns a list of Charts, ordered by creation date (newest first). A Chart is chosen by Pollster editors. One example is \"Obama job approval - Democrats\". It is always based upon a single Question. Users should strongly consider basing their analysis on Questions instead. Charts are derived data; Pollster editors publish them and change them as editorial priorities change.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.charts_get(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str cursor: Special string to index into the Array
:param str tags: Comma-separated list of tag slugs. Only Charts with one or more of these tags and Charts based on Questions with one or more of these tags will be returned.
:param date election_date: Date of an election, in YYYY-MM-DD format. Only Charts based on Questions pertaining to an election on this date will be returned.
:return: InlineResponse200
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.charts_get_with_http_info(**kwargs)
else:
(data) = self.charts_get_with_http_info(**kwargs)
return data | [
"def",
"charts_get",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"charts_get_with_http_info",
"(",
"*",
"*",
... | Charts
Returns a list of Charts, ordered by creation date (newest first). A Chart is chosen by Pollster editors. One example is \"Obama job approval - Democrats\". It is always based upon a single Question. Users should strongly consider basing their analysis on Questions instead. Charts are derived data; Pollster editors publish them and change them as editorial priorities change.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.charts_get(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str cursor: Special string to index into the Array
:param str tags: Comma-separated list of tag slugs. Only Charts with one or more of these tags and Charts based on Questions with one or more of these tags will be returned.
:param date election_date: Date of an election, in YYYY-MM-DD format. Only Charts based on Questions pertaining to an election on this date will be returned.
:return: InlineResponse200
If the method is called asynchronously,
returns the request thread. | [
"Charts",
"Returns",
"a",
"list",
"of",
"Charts",
"ordered",
"by",
"creation",
"date",
"(",
"newest",
"first",
")",
".",
"A",
"Chart",
"is",
"chosen",
"by",
"Pollster",
"editors",
".",
"One",
"example",
"is",
"\\",
"Obama",
"job",
"approval",
"-",
"Democ... | train | https://github.com/huffpostdata/python-pollster/blob/276de8d66a92577b1143fd92a70cff9c35a1dfcf/pollster/api.py#L23-L50 |
huffpostdata/python-pollster | pollster/api.py | Api.charts_slug_get | def charts_slug_get(self, slug, **kwargs):
"""
Chart
A Chart is chosen by Pollster editors. One example is \"Obama job approval - Democrats\". It is always based upon a single Question. Users should strongly consider basing their analysis on Questions instead. Charts are derived data; Pollster editors publish them and change them as editorial priorities change.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.charts_slug_get(slug, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str slug: Unique identifier for a Chart (required)
:return: Chart
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.charts_slug_get_with_http_info(slug, **kwargs)
else:
(data) = self.charts_slug_get_with_http_info(slug, **kwargs)
return data | python | def charts_slug_get(self, slug, **kwargs):
"""
Chart
A Chart is chosen by Pollster editors. One example is \"Obama job approval - Democrats\". It is always based upon a single Question. Users should strongly consider basing their analysis on Questions instead. Charts are derived data; Pollster editors publish them and change them as editorial priorities change.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.charts_slug_get(slug, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str slug: Unique identifier for a Chart (required)
:return: Chart
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.charts_slug_get_with_http_info(slug, **kwargs)
else:
(data) = self.charts_slug_get_with_http_info(slug, **kwargs)
return data | [
"def",
"charts_slug_get",
"(",
"self",
",",
"slug",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"charts_slug_get_with_http_inf... | Chart
A Chart is chosen by Pollster editors. One example is \"Obama job approval - Democrats\". It is always based upon a single Question. Users should strongly consider basing their analysis on Questions instead. Charts are derived data; Pollster editors publish them and change them as editorial priorities change.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.charts_slug_get(slug, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str slug: Unique identifier for a Chart (required)
:return: Chart
If the method is called asynchronously,
returns the request thread. | [
"Chart",
"A",
"Chart",
"is",
"chosen",
"by",
"Pollster",
"editors",
".",
"One",
"example",
"is",
"\\",
"Obama",
"job",
"approval",
"-",
"Democrats",
"\\",
".",
"It",
"is",
"always",
"based",
"upon",
"a",
"single",
"Question",
".",
"Users",
"should",
"str... | train | https://github.com/huffpostdata/python-pollster/blob/276de8d66a92577b1143fd92a70cff9c35a1dfcf/pollster/api.py#L140-L165 |
huffpostdata/python-pollster | pollster/api.py | Api.charts_slug_pollster_chart_poll_questions_tsv_get | def charts_slug_pollster_chart_poll_questions_tsv_get(self, slug, **kwargs):
"""
One row per poll plotted on a Chart
Derived data presented on a Pollster Chart. Rules for which polls and responses are plotted on a chart can shift over time. Here are some examples of behaviors Pollster has used in the past: * We've omitted \"Registered Voters\" from a chart when \"Likely Voters\" responded to the same poll question. * We've omitted poll questions that asked about Gary Johnson on a chart about Trump v Clinton. * We've omitted polls when their date ranges overlapped. * We've omitted labels (and their responses) for dark-horse candidates. In short: this endpoint is about Pollster, not the polls. For complete data, use a TSV from the Questions API. The response follows the exact same format as `questions/{slug}/poll-responses-clean.tsv`, which you should strongly consider before settling on the Chart TSV.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.charts_slug_pollster_chart_poll_questions_tsv_get(slug, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str slug: Unique Chart identifier. For example: `obama-job-approval` (required)
:return: InlineResponse2001
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.charts_slug_pollster_chart_poll_questions_tsv_get_with_http_info(slug, **kwargs)
else:
(data) = self.charts_slug_pollster_chart_poll_questions_tsv_get_with_http_info(slug, **kwargs)
return data | python | def charts_slug_pollster_chart_poll_questions_tsv_get(self, slug, **kwargs):
"""
One row per poll plotted on a Chart
Derived data presented on a Pollster Chart. Rules for which polls and responses are plotted on a chart can shift over time. Here are some examples of behaviors Pollster has used in the past: * We've omitted \"Registered Voters\" from a chart when \"Likely Voters\" responded to the same poll question. * We've omitted poll questions that asked about Gary Johnson on a chart about Trump v Clinton. * We've omitted polls when their date ranges overlapped. * We've omitted labels (and their responses) for dark-horse candidates. In short: this endpoint is about Pollster, not the polls. For complete data, use a TSV from the Questions API. The response follows the exact same format as `questions/{slug}/poll-responses-clean.tsv`, which you should strongly consider before settling on the Chart TSV.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.charts_slug_pollster_chart_poll_questions_tsv_get(slug, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str slug: Unique Chart identifier. For example: `obama-job-approval` (required)
:return: InlineResponse2001
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.charts_slug_pollster_chart_poll_questions_tsv_get_with_http_info(slug, **kwargs)
else:
(data) = self.charts_slug_pollster_chart_poll_questions_tsv_get_with_http_info(slug, **kwargs)
return data | [
"def",
"charts_slug_pollster_chart_poll_questions_tsv_get",
"(",
"self",
",",
"slug",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
"."... | One row per poll plotted on a Chart
Derived data presented on a Pollster Chart. Rules for which polls and responses are plotted on a chart can shift over time. Here are some examples of behaviors Pollster has used in the past: * We've omitted \"Registered Voters\" from a chart when \"Likely Voters\" responded to the same poll question. * We've omitted poll questions that asked about Gary Johnson on a chart about Trump v Clinton. * We've omitted polls when their date ranges overlapped. * We've omitted labels (and their responses) for dark-horse candidates. In short: this endpoint is about Pollster, not the polls. For complete data, use a TSV from the Questions API. The response follows the exact same format as `questions/{slug}/poll-responses-clean.tsv`, which you should strongly consider before settling on the Chart TSV.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.charts_slug_pollster_chart_poll_questions_tsv_get(slug, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str slug: Unique Chart identifier. For example: `obama-job-approval` (required)
:return: InlineResponse2001
If the method is called asynchronously,
returns the request thread. | [
"One",
"row",
"per",
"poll",
"plotted",
"on",
"a",
"Chart",
"Derived",
"data",
"presented",
"on",
"a",
"Pollster",
"Chart",
".",
"Rules",
"for",
"which",
"polls",
"and",
"responses",
"are",
"plotted",
"on",
"a",
"chart",
"can",
"shift",
"over",
"time",
"... | train | https://github.com/huffpostdata/python-pollster/blob/276de8d66a92577b1143fd92a70cff9c35a1dfcf/pollster/api.py#L252-L277 |
huffpostdata/python-pollster | pollster/api.py | Api.charts_slug_pollster_trendlines_tsv_get | def charts_slug_pollster_trendlines_tsv_get(self, slug, **kwargs):
"""
Estimates of what the polls suggest about trends
Derived data presented on a Pollster Chart. The trendlines on a Pollster chart don't add up to 100: we calculate each label's trendline separately. Use the `charts/{slug}` response's `chart.pollster_estimates[0].algorithm` to find the algorithm Pollster used to generate these estimates. Pollster recalculates trendlines every time a new poll is entered. It also recalculates trendlines daily if they use the `bayesian-kallman` algorithm, because that algorithm's output changes depending on the end date.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.charts_slug_pollster_trendlines_tsv_get(slug, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str slug: Unique Chart identifier. For example: `obama-job-approval` (required)
:return: InlineResponse2002
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.charts_slug_pollster_trendlines_tsv_get_with_http_info(slug, **kwargs)
else:
(data) = self.charts_slug_pollster_trendlines_tsv_get_with_http_info(slug, **kwargs)
return data | python | def charts_slug_pollster_trendlines_tsv_get(self, slug, **kwargs):
"""
Estimates of what the polls suggest about trends
Derived data presented on a Pollster Chart. The trendlines on a Pollster chart don't add up to 100: we calculate each label's trendline separately. Use the `charts/{slug}` response's `chart.pollster_estimates[0].algorithm` to find the algorithm Pollster used to generate these estimates. Pollster recalculates trendlines every time a new poll is entered. It also recalculates trendlines daily if they use the `bayesian-kallman` algorithm, because that algorithm's output changes depending on the end date.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.charts_slug_pollster_trendlines_tsv_get(slug, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str slug: Unique Chart identifier. For example: `obama-job-approval` (required)
:return: InlineResponse2002
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.charts_slug_pollster_trendlines_tsv_get_with_http_info(slug, **kwargs)
else:
(data) = self.charts_slug_pollster_trendlines_tsv_get_with_http_info(slug, **kwargs)
return data | [
"def",
"charts_slug_pollster_trendlines_tsv_get",
"(",
"self",
",",
"slug",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"chart... | Estimates of what the polls suggest about trends
Derived data presented on a Pollster Chart. The trendlines on a Pollster chart don't add up to 100: we calculate each label's trendline separately. Use the `charts/{slug}` response's `chart.pollster_estimates[0].algorithm` to find the algorithm Pollster used to generate these estimates. Pollster recalculates trendlines every time a new poll is entered. It also recalculates trendlines daily if they use the `bayesian-kallman` algorithm, because that algorithm's output changes depending on the end date.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.charts_slug_pollster_trendlines_tsv_get(slug, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str slug: Unique Chart identifier. For example: `obama-job-approval` (required)
:return: InlineResponse2002
If the method is called asynchronously,
returns the request thread. | [
"Estimates",
"of",
"what",
"the",
"polls",
"suggest",
"about",
"trends",
"Derived",
"data",
"presented",
"on",
"a",
"Pollster",
"Chart",
".",
"The",
"trendlines",
"on",
"a",
"Pollster",
"chart",
"don",
"t",
"add",
"up",
"to",
"100",
":",
"we",
"calculate",... | train | https://github.com/huffpostdata/python-pollster/blob/276de8d66a92577b1143fd92a70cff9c35a1dfcf/pollster/api.py#L379-L404 |
huffpostdata/python-pollster | pollster/api.py | Api.polls_get | def polls_get(self, **kwargs):
"""
Polls
A Poll on Pollster is a collection of questions and responses published by a reputable survey house. This endpoint provides raw data from the survey house, plus Pollster-provided metadata about each question. Pollster editors don't include every question when they enter Polls, and they don't necessarily enter every subpopulation for the responses they _do_ enter. They make editorial decisions about which questions belong in the database. The response will contain a maximum of 25 Poll objects, even if the database contains more than 25 polls. Use the `next_cursor` parameter to fetch the rest, 25 Polls at a time.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.polls_get(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str cursor: Special string to index into the Array
:param str tags: Comma-separated list of Question tag names; only Polls containing Questions with any of the given tags will be returned.
:param str question: Question slug; only Polls that ask that Question will be returned.
:param str sort: If `updated_at`, sort the most recently updated Poll first. (This can cause race conditions when used with `cursor`.) Otherwise, sort by most recently _entered_ Poll first.
:return: InlineResponse2003
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.polls_get_with_http_info(**kwargs)
else:
(data) = self.polls_get_with_http_info(**kwargs)
return data | python | def polls_get(self, **kwargs):
"""
Polls
A Poll on Pollster is a collection of questions and responses published by a reputable survey house. This endpoint provides raw data from the survey house, plus Pollster-provided metadata about each question. Pollster editors don't include every question when they enter Polls, and they don't necessarily enter every subpopulation for the responses they _do_ enter. They make editorial decisions about which questions belong in the database. The response will contain a maximum of 25 Poll objects, even if the database contains more than 25 polls. Use the `next_cursor` parameter to fetch the rest, 25 Polls at a time.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.polls_get(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str cursor: Special string to index into the Array
:param str tags: Comma-separated list of Question tag names; only Polls containing Questions with any of the given tags will be returned.
:param str question: Question slug; only Polls that ask that Question will be returned.
:param str sort: If `updated_at`, sort the most recently updated Poll first. (This can cause race conditions when used with `cursor`.) Otherwise, sort by most recently _entered_ Poll first.
:return: InlineResponse2003
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.polls_get_with_http_info(**kwargs)
else:
(data) = self.polls_get_with_http_info(**kwargs)
return data | [
"def",
"polls_get",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"polls_get_with_http_info",
"(",
"*",
"*",
"k... | Polls
A Poll on Pollster is a collection of questions and responses published by a reputable survey house. This endpoint provides raw data from the survey house, plus Pollster-provided metadata about each question. Pollster editors don't include every question when they enter Polls, and they don't necessarily enter every subpopulation for the responses they _do_ enter. They make editorial decisions about which questions belong in the database. The response will contain a maximum of 25 Poll objects, even if the database contains more than 25 polls. Use the `next_cursor` parameter to fetch the rest, 25 Polls at a time.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.polls_get(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str cursor: Special string to index into the Array
:param str tags: Comma-separated list of Question tag names; only Polls containing Questions with any of the given tags will be returned.
:param str question: Question slug; only Polls that ask that Question will be returned.
:param str sort: If `updated_at`, sort the most recently updated Poll first. (This can cause race conditions when used with `cursor`.) Otherwise, sort by most recently _entered_ Poll first.
:return: InlineResponse2003
If the method is called asynchronously,
returns the request thread. | [
"Polls",
"A",
"Poll",
"on",
"Pollster",
"is",
"a",
"collection",
"of",
"questions",
"and",
"responses",
"published",
"by",
"a",
"reputable",
"survey",
"house",
".",
"This",
"endpoint",
"provides",
"raw",
"data",
"from",
"the",
"survey",
"house",
"plus",
"Pol... | train | https://github.com/huffpostdata/python-pollster/blob/276de8d66a92577b1143fd92a70cff9c35a1dfcf/pollster/api.py#L500-L528 |
huffpostdata/python-pollster | pollster/api.py | Api.polls_slug_get | def polls_slug_get(self, slug, **kwargs):
"""
Poll
A Poll on Pollster is a collection of questions and responses published by a reputable survey house. This endpoint provides raw data from the survey house, plus Pollster-provided metadata about each question. Pollster editors don't include every question when they enter Polls, and they don't necessarily enter every subpopulation for the responses they _do_ enter. They make editorial decisions about which questions belong in the database.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.polls_slug_get(slug, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str slug: Unique Poll identifier. For example: `gallup-26892`. (required)
:return: Poll
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.polls_slug_get_with_http_info(slug, **kwargs)
else:
(data) = self.polls_slug_get_with_http_info(slug, **kwargs)
return data | python | def polls_slug_get(self, slug, **kwargs):
"""
Poll
A Poll on Pollster is a collection of questions and responses published by a reputable survey house. This endpoint provides raw data from the survey house, plus Pollster-provided metadata about each question. Pollster editors don't include every question when they enter Polls, and they don't necessarily enter every subpopulation for the responses they _do_ enter. They make editorial decisions about which questions belong in the database.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.polls_slug_get(slug, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str slug: Unique Poll identifier. For example: `gallup-26892`. (required)
:return: Poll
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.polls_slug_get_with_http_info(slug, **kwargs)
else:
(data) = self.polls_slug_get_with_http_info(slug, **kwargs)
return data | [
"def",
"polls_slug_get",
"(",
"self",
",",
"slug",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"polls_slug_get_with_http_info"... | Poll
A Poll on Pollster is a collection of questions and responses published by a reputable survey house. This endpoint provides raw data from the survey house, plus Pollster-provided metadata about each question. Pollster editors don't include every question when they enter Polls, and they don't necessarily enter every subpopulation for the responses they _do_ enter. They make editorial decisions about which questions belong in the database.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.polls_slug_get(slug, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str slug: Unique Poll identifier. For example: `gallup-26892`. (required)
:return: Poll
If the method is called asynchronously,
returns the request thread. | [
"Poll",
"A",
"Poll",
"on",
"Pollster",
"is",
"a",
"collection",
"of",
"questions",
"and",
"responses",
"published",
"by",
"a",
"reputable",
"survey",
"house",
".",
"This",
"endpoint",
"provides",
"raw",
"data",
"from",
"the",
"survey",
"house",
"plus",
"Poll... | train | https://github.com/huffpostdata/python-pollster/blob/276de8d66a92577b1143fd92a70cff9c35a1dfcf/pollster/api.py#L621-L646 |
huffpostdata/python-pollster | pollster/api.py | Api.questions_get | def questions_get(self, **kwargs):
"""
Questions
Returns a list of Questions. A Question is chosen by Pollster editors. One example is \"Obama job approval\". Different survey houses may publish varying phrasings (\"Do you approve or disapprove\" vs \"What do you think of the job\") and prompt readers with varying responses (one poll might have \"Approve\" and \"Disapprove\"; another poll might have \"Strongly approve\" and \"Somewhat approve\"). Those variations do not appear in this API endpoint.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.questions_get(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str cursor: Special string to index into the Array
:param str tags: Comma-separated list of Question tag names. Only Questions with one or more of these tags will be returned.
:param date election_date: Date of an election, in YYYY-MM-DD format. Only Questions pertaining to an election on this date will be returned.
:return: InlineResponse2004
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.questions_get_with_http_info(**kwargs)
else:
(data) = self.questions_get_with_http_info(**kwargs)
return data | python | def questions_get(self, **kwargs):
"""
Questions
Returns a list of Questions. A Question is chosen by Pollster editors. One example is \"Obama job approval\". Different survey houses may publish varying phrasings (\"Do you approve or disapprove\" vs \"What do you think of the job\") and prompt readers with varying responses (one poll might have \"Approve\" and \"Disapprove\"; another poll might have \"Strongly approve\" and \"Somewhat approve\"). Those variations do not appear in this API endpoint.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.questions_get(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str cursor: Special string to index into the Array
:param str tags: Comma-separated list of Question tag names. Only Questions with one or more of these tags will be returned.
:param date election_date: Date of an election, in YYYY-MM-DD format. Only Questions pertaining to an election on this date will be returned.
:return: InlineResponse2004
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.questions_get_with_http_info(**kwargs)
else:
(data) = self.questions_get_with_http_info(**kwargs)
return data | [
"def",
"questions_get",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"questions_get_with_http_info",
"(",
"*",
"... | Questions
Returns a list of Questions. A Question is chosen by Pollster editors. One example is \"Obama job approval\". Different survey houses may publish varying phrasings (\"Do you approve or disapprove\" vs \"What do you think of the job\") and prompt readers with varying responses (one poll might have \"Approve\" and \"Disapprove\"; another poll might have \"Strongly approve\" and \"Somewhat approve\"). Those variations do not appear in this API endpoint.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.questions_get(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str cursor: Special string to index into the Array
:param str tags: Comma-separated list of Question tag names. Only Questions with one or more of these tags will be returned.
:param date election_date: Date of an election, in YYYY-MM-DD format. Only Questions pertaining to an election on this date will be returned.
:return: InlineResponse2004
If the method is called asynchronously,
returns the request thread. | [
"Questions",
"Returns",
"a",
"list",
"of",
"Questions",
".",
"A",
"Question",
"is",
"chosen",
"by",
"Pollster",
"editors",
".",
"One",
"example",
"is",
"\\",
"Obama",
"job",
"approval",
"\\",
".",
"Different",
"survey",
"houses",
"may",
"publish",
"varying",... | train | https://github.com/huffpostdata/python-pollster/blob/276de8d66a92577b1143fd92a70cff9c35a1dfcf/pollster/api.py#L733-L760 |
huffpostdata/python-pollster | pollster/api.py | Api.questions_slug_get | def questions_slug_get(self, slug, **kwargs):
"""
Question
A Question is chosen by Pollster editors. One example is \"Obama job approval\". Different survey houses may publish varying phrasings (\"Do you approve or disapprove\" vs \"What do you think of the job\") and prompt readers with varying responses (one poll might have \"Approve\" and \"Disapprove\"; another poll might have \"Strongly approve\" and \"Somewhat approve\"). Those variations do not appear in this API endpoint.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.questions_slug_get(slug, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str slug: Unique Question identifier. For example: `00c -Pres (44) Obama - Job Approval - National`. (Remember to URL-encode this parameter when querying.) (required)
:return: Question
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.questions_slug_get_with_http_info(slug, **kwargs)
else:
(data) = self.questions_slug_get_with_http_info(slug, **kwargs)
return data | python | def questions_slug_get(self, slug, **kwargs):
"""
Question
A Question is chosen by Pollster editors. One example is \"Obama job approval\". Different survey houses may publish varying phrasings (\"Do you approve or disapprove\" vs \"What do you think of the job\") and prompt readers with varying responses (one poll might have \"Approve\" and \"Disapprove\"; another poll might have \"Strongly approve\" and \"Somewhat approve\"). Those variations do not appear in this API endpoint.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.questions_slug_get(slug, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str slug: Unique Question identifier. For example: `00c -Pres (44) Obama - Job Approval - National`. (Remember to URL-encode this parameter when querying.) (required)
:return: Question
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.questions_slug_get_with_http_info(slug, **kwargs)
else:
(data) = self.questions_slug_get_with_http_info(slug, **kwargs)
return data | [
"def",
"questions_slug_get",
"(",
"self",
",",
"slug",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"questions_slug_get_with_ht... | Question
A Question is chosen by Pollster editors. One example is \"Obama job approval\". Different survey houses may publish varying phrasings (\"Do you approve or disapprove\" vs \"What do you think of the job\") and prompt readers with varying responses (one poll might have \"Approve\" and \"Disapprove\"; another poll might have \"Strongly approve\" and \"Somewhat approve\"). Those variations do not appear in this API endpoint.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.questions_slug_get(slug, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str slug: Unique Question identifier. For example: `00c -Pres (44) Obama - Job Approval - National`. (Remember to URL-encode this parameter when querying.) (required)
:return: Question
If the method is called asynchronously,
returns the request thread. | [
"Question",
"A",
"Question",
"is",
"chosen",
"by",
"Pollster",
"editors",
".",
"One",
"example",
"is",
"\\",
"Obama",
"job",
"approval",
"\\",
".",
"Different",
"survey",
"houses",
"may",
"publish",
"varying",
"phrasings",
"(",
"\\",
"Do",
"you",
"approve",
... | train | https://github.com/huffpostdata/python-pollster/blob/276de8d66a92577b1143fd92a70cff9c35a1dfcf/pollster/api.py#L850-L875 |
huffpostdata/python-pollster | pollster/api.py | Api.questions_slug_poll_responses_clean_tsv_get | def questions_slug_poll_responses_clean_tsv_get(self, slug, **kwargs):
"""
One row of response values per PollQuestion+Subpopulation concerning the given Question
We include one TSV column per response label. See `questions/{slug}` for the Question's list of response labels, which are chosen by Pollster editors. Each row represents a single PollQuestion+Subpopulation. The value for each label column is the sum of the PollQuestion+Subpopulation responses that map to that `pollster_label`. For instance, on a hypothetical row, the `Approve` column might be the sum of that poll's `Strongly Approve` and `Somewhat Approve`. After the first TSV columns -- which are always response labels -- the next column will be `poll_slug`. `poll_slug` and subsequent columns are described in this API documentation. During the lifetime of a Question, Pollster editors may add, rename or reorder response labels. Such edits will change the TSV column headers. Column headers after `poll_slug` are never reordered or edited (but we may add new column headers). Sometimes a Poll may ask the same Question twice, leading to two similar rows with different values. Those rows will differ by `question_text` or by the set of response labels that have values.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.questions_slug_poll_responses_clean_tsv_get(slug, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str slug: Unique Question identifier. For example: `00c -Pres (44) Obama - Job Approval - National`. (Remember to URL-encode this parameter when querying.) (required)
:return: InlineResponse2001
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.questions_slug_poll_responses_clean_tsv_get_with_http_info(slug, **kwargs)
else:
(data) = self.questions_slug_poll_responses_clean_tsv_get_with_http_info(slug, **kwargs)
return data | python | def questions_slug_poll_responses_clean_tsv_get(self, slug, **kwargs):
"""
One row of response values per PollQuestion+Subpopulation concerning the given Question
We include one TSV column per response label. See `questions/{slug}` for the Question's list of response labels, which are chosen by Pollster editors. Each row represents a single PollQuestion+Subpopulation. The value for each label column is the sum of the PollQuestion+Subpopulation responses that map to that `pollster_label`. For instance, on a hypothetical row, the `Approve` column might be the sum of that poll's `Strongly Approve` and `Somewhat Approve`. After the first TSV columns -- which are always response labels -- the next column will be `poll_slug`. `poll_slug` and subsequent columns are described in this API documentation. During the lifetime of a Question, Pollster editors may add, rename or reorder response labels. Such edits will change the TSV column headers. Column headers after `poll_slug` are never reordered or edited (but we may add new column headers). Sometimes a Poll may ask the same Question twice, leading to two similar rows with different values. Those rows will differ by `question_text` or by the set of response labels that have values.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.questions_slug_poll_responses_clean_tsv_get(slug, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str slug: Unique Question identifier. For example: `00c -Pres (44) Obama - Job Approval - National`. (Remember to URL-encode this parameter when querying.) (required)
:return: InlineResponse2001
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.questions_slug_poll_responses_clean_tsv_get_with_http_info(slug, **kwargs)
else:
(data) = self.questions_slug_poll_responses_clean_tsv_get_with_http_info(slug, **kwargs)
return data | [
"def",
"questions_slug_poll_responses_clean_tsv_get",
"(",
"self",
",",
"slug",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"q... | One row of response values per PollQuestion+Subpopulation concerning the given Question
We include one TSV column per response label. See `questions/{slug}` for the Question's list of response labels, which are chosen by Pollster editors. Each row represents a single PollQuestion+Subpopulation. The value for each label column is the sum of the PollQuestion+Subpopulation responses that map to that `pollster_label`. For instance, on a hypothetical row, the `Approve` column might be the sum of that poll's `Strongly Approve` and `Somewhat Approve`. After the first TSV columns -- which are always response labels -- the next column will be `poll_slug`. `poll_slug` and subsequent columns are described in this API documentation. During the lifetime of a Question, Pollster editors may add, rename or reorder response labels. Such edits will change the TSV column headers. Column headers after `poll_slug` are never reordered or edited (but we may add new column headers). Sometimes a Poll may ask the same Question twice, leading to two similar rows with different values. Those rows will differ by `question_text` or by the set of response labels that have values.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.questions_slug_poll_responses_clean_tsv_get(slug, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str slug: Unique Question identifier. For example: `00c -Pres (44) Obama - Job Approval - National`. (Remember to URL-encode this parameter when querying.) (required)
:return: InlineResponse2001
If the method is called asynchronously,
returns the request thread. | [
"One",
"row",
"of",
"response",
"values",
"per",
"PollQuestion",
"+",
"Subpopulation",
"concerning",
"the",
"given",
"Question",
"We",
"include",
"one",
"TSV",
"column",
"per",
"response",
"label",
".",
"See",
"questions",
"/",
"{",
"slug",
"}",
"for",
"the"... | train | https://github.com/huffpostdata/python-pollster/blob/276de8d66a92577b1143fd92a70cff9c35a1dfcf/pollster/api.py#L962-L987 |
huffpostdata/python-pollster | pollster/api.py | Api.questions_slug_poll_responses_raw_tsv_get | def questions_slug_poll_responses_raw_tsv_get(self, slug, **kwargs):
"""
One row per PollQuestion+Subpopulation+Response concerning the given Question (Large)
Raw data from which we derived `poll-responses-clean.tsv`. Each row represents a single PollQuestion+Subpopulation+Response. See the Poll API for a description of these terms. Group results by `(poll_slug, subpopulation, question_text)`: that's how the survey houses group them. This response can be several megabytes large. We encourage you to consider `poll-responses-clean.tsv` instead.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.questions_slug_poll_responses_raw_tsv_get(slug, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str slug: Unique Question identifier. For example: `00c -Pres (44) Obama - Job Approval - National`. (Remember to URL-encode this parameter when querying.) (required)
:return: InlineResponse2005
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.questions_slug_poll_responses_raw_tsv_get_with_http_info(slug, **kwargs)
else:
(data) = self.questions_slug_poll_responses_raw_tsv_get_with_http_info(slug, **kwargs)
return data | python | def questions_slug_poll_responses_raw_tsv_get(self, slug, **kwargs):
"""
One row per PollQuestion+Subpopulation+Response concerning the given Question (Large)
Raw data from which we derived `poll-responses-clean.tsv`. Each row represents a single PollQuestion+Subpopulation+Response. See the Poll API for a description of these terms. Group results by `(poll_slug, subpopulation, question_text)`: that's how the survey houses group them. This response can be several megabytes large. We encourage you to consider `poll-responses-clean.tsv` instead.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.questions_slug_poll_responses_raw_tsv_get(slug, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str slug: Unique Question identifier. For example: `00c -Pres (44) Obama - Job Approval - National`. (Remember to URL-encode this parameter when querying.) (required)
:return: InlineResponse2005
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.questions_slug_poll_responses_raw_tsv_get_with_http_info(slug, **kwargs)
else:
(data) = self.questions_slug_poll_responses_raw_tsv_get_with_http_info(slug, **kwargs)
return data | [
"def",
"questions_slug_poll_responses_raw_tsv_get",
"(",
"self",
",",
"slug",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"que... | One row per PollQuestion+Subpopulation+Response concerning the given Question (Large)
Raw data from which we derived `poll-responses-clean.tsv`. Each row represents a single PollQuestion+Subpopulation+Response. See the Poll API for a description of these terms. Group results by `(poll_slug, subpopulation, question_text)`: that's how the survey houses group them. This response can be several megabytes large. We encourage you to consider `poll-responses-clean.tsv` instead.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.questions_slug_poll_responses_raw_tsv_get(slug, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str slug: Unique Question identifier. For example: `00c -Pres (44) Obama - Job Approval - National`. (Remember to URL-encode this parameter when querying.) (required)
:return: InlineResponse2005
If the method is called asynchronously,
returns the request thread. | [
"One",
"row",
"per",
"PollQuestion",
"+",
"Subpopulation",
"+",
"Response",
"concerning",
"the",
"given",
"Question",
"(",
"Large",
")",
"Raw",
"data",
"from",
"which",
"we",
"derived",
"poll",
"-",
"responses",
"-",
"clean",
".",
"tsv",
".",
"Each",
"row"... | train | https://github.com/huffpostdata/python-pollster/blob/276de8d66a92577b1143fd92a70cff9c35a1dfcf/pollster/api.py#L1089-L1114 |
huffpostdata/python-pollster | pollster/api.py | Api.tags_get | def tags_get(self, **kwargs):
"""
Tags
Returns the list of Tags. A Tag can apply to any number of Charts and Questions; Charts and Questions, in turn, can have any number of Tags. Tags all look `like-this`: lowercase letters, numbers and hyphens.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.tags_get(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:return: list[Tag]
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.tags_get_with_http_info(**kwargs)
else:
(data) = self.tags_get_with_http_info(**kwargs)
return data | python | def tags_get(self, **kwargs):
"""
Tags
Returns the list of Tags. A Tag can apply to any number of Charts and Questions; Charts and Questions, in turn, can have any number of Tags. Tags all look `like-this`: lowercase letters, numbers and hyphens.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.tags_get(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:return: list[Tag]
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.tags_get_with_http_info(**kwargs)
else:
(data) = self.tags_get_with_http_info(**kwargs)
return data | [
"def",
"tags_get",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"tags_get_with_http_info",
"(",
"*",
"*",
"kwa... | Tags
Returns the list of Tags. A Tag can apply to any number of Charts and Questions; Charts and Questions, in turn, can have any number of Tags. Tags all look `like-this`: lowercase letters, numbers and hyphens.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.tags_get(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:return: list[Tag]
If the method is called asynchronously,
returns the request thread. | [
"Tags",
"Returns",
"the",
"list",
"of",
"Tags",
".",
"A",
"Tag",
"can",
"apply",
"to",
"any",
"number",
"of",
"Charts",
"and",
"Questions",
";",
"Charts",
"and",
"Questions",
"in",
"turn",
"can",
"have",
"any",
"number",
"of",
"Tags",
".",
"Tags",
"all... | train | https://github.com/huffpostdata/python-pollster/blob/276de8d66a92577b1143fd92a70cff9c35a1dfcf/pollster/api.py#L1218-L1242 |
huffpostdata/python-pollster | pollster/api_client.py | ApiClient.sanitize_for_serialization | def sanitize_for_serialization(self, obj):
"""
Builds a JSON POST object.
If obj is None, return None.
If obj is str, int, long, float, bool, return directly.
If obj is datetime.datetime, datetime.date
convert to string in iso8601 format.
If obj is list, sanitize each element in the list.
If obj is dict, return the dict.
If obj is swagger model, return the properties dict.
:param obj: The data to serialize.
:return: The serialized form of data.
"""
types = (str, float, bool, bytes) + tuple(integer_types) + (text_type,)
if isinstance(obj, type(None)):
return None
elif isinstance(obj, types):
return obj
elif isinstance(obj, list):
return [self.sanitize_for_serialization(sub_obj)
for sub_obj in obj]
elif isinstance(obj, tuple):
return tuple(self.sanitize_for_serialization(sub_obj)
for sub_obj in obj)
elif isinstance(obj, (datetime, date)):
return obj.isoformat()
else:
if isinstance(obj, dict):
obj_dict = obj
else:
# Convert model obj to dict except
# attributes `swagger_types`, `attribute_map`
# and attributes which value is not None.
# Convert attribute name to json key in
# model definition for request.
obj_dict = {obj.attribute_map[attr]: getattr(obj, attr)
for attr, _ in iteritems(obj.swagger_types)
if getattr(obj, attr) is not None}
return {key: self.sanitize_for_serialization(val)
for key, val in iteritems(obj_dict)} | python | def sanitize_for_serialization(self, obj):
"""
Builds a JSON POST object.
If obj is None, return None.
If obj is str, int, long, float, bool, return directly.
If obj is datetime.datetime, datetime.date
convert to string in iso8601 format.
If obj is list, sanitize each element in the list.
If obj is dict, return the dict.
If obj is swagger model, return the properties dict.
:param obj: The data to serialize.
:return: The serialized form of data.
"""
types = (str, float, bool, bytes) + tuple(integer_types) + (text_type,)
if isinstance(obj, type(None)):
return None
elif isinstance(obj, types):
return obj
elif isinstance(obj, list):
return [self.sanitize_for_serialization(sub_obj)
for sub_obj in obj]
elif isinstance(obj, tuple):
return tuple(self.sanitize_for_serialization(sub_obj)
for sub_obj in obj)
elif isinstance(obj, (datetime, date)):
return obj.isoformat()
else:
if isinstance(obj, dict):
obj_dict = obj
else:
# Convert model obj to dict except
# attributes `swagger_types`, `attribute_map`
# and attributes which value is not None.
# Convert attribute name to json key in
# model definition for request.
obj_dict = {obj.attribute_map[attr]: getattr(obj, attr)
for attr, _ in iteritems(obj.swagger_types)
if getattr(obj, attr) is not None}
return {key: self.sanitize_for_serialization(val)
for key, val in iteritems(obj_dict)} | [
"def",
"sanitize_for_serialization",
"(",
"self",
",",
"obj",
")",
":",
"types",
"=",
"(",
"str",
",",
"float",
",",
"bool",
",",
"bytes",
")",
"+",
"tuple",
"(",
"integer_types",
")",
"+",
"(",
"text_type",
",",
")",
"if",
"isinstance",
"(",
"obj",
... | Builds a JSON POST object.
If obj is None, return None.
If obj is str, int, long, float, bool, return directly.
If obj is datetime.datetime, datetime.date
convert to string in iso8601 format.
If obj is list, sanitize each element in the list.
If obj is dict, return the dict.
If obj is swagger model, return the properties dict.
:param obj: The data to serialize.
:return: The serialized form of data. | [
"Builds",
"a",
"JSON",
"POST",
"object",
"."
] | train | https://github.com/huffpostdata/python-pollster/blob/276de8d66a92577b1143fd92a70cff9c35a1dfcf/pollster/api_client.py#L177-L219 |
huffpostdata/python-pollster | pollster/api_client.py | ApiClient.select_header_content_type | def select_header_content_type(self, content_types):
"""
Returns `Content-Type` based on an array of content_types provided.
:param content_types: List of content-types.
:return: Content-Type (e.g. application/json).
"""
if not content_types:
return 'application/json'
content_types = list(map(lambda x: x.lower(), content_types))
if 'application/json' in content_types or '*/*' in content_types:
return 'application/json'
else:
return content_types[0] | python | def select_header_content_type(self, content_types):
"""
Returns `Content-Type` based on an array of content_types provided.
:param content_types: List of content-types.
:return: Content-Type (e.g. application/json).
"""
if not content_types:
return 'application/json'
content_types = list(map(lambda x: x.lower(), content_types))
if 'application/json' in content_types or '*/*' in content_types:
return 'application/json'
else:
return content_types[0] | [
"def",
"select_header_content_type",
"(",
"self",
",",
"content_types",
")",
":",
"if",
"not",
"content_types",
":",
"return",
"'application/json'",
"content_types",
"=",
"list",
"(",
"map",
"(",
"lambda",
"x",
":",
"x",
".",
"lower",
"(",
")",
",",
"content... | Returns `Content-Type` based on an array of content_types provided.
:param content_types: List of content-types.
:return: Content-Type (e.g. application/json). | [
"Returns",
"Content",
"-",
"Type",
"based",
"on",
"an",
"array",
"of",
"content_types",
"provided",
"."
] | train | https://github.com/huffpostdata/python-pollster/blob/276de8d66a92577b1143fd92a70cff9c35a1dfcf/pollster/api_client.py#L491-L506 |
huffpostdata/python-pollster | pollster/api_client.py | ApiClient.__deserialize_model | def __deserialize_model(self, data, klass):
"""
Deserializes list or dict to model.
:param data: dict, list.
:param klass: class literal.
:return: model object.
"""
instance = klass()
if not instance.swagger_types:
return data
for attr, attr_type in iteritems(instance.swagger_types):
if data is not None \
and instance.attribute_map[attr] in data\
and isinstance(data, (list, dict)):
value = data[instance.attribute_map[attr]]
setattr(instance, '_' + attr, self.__deserialize(value, attr_type))
return instance | python | def __deserialize_model(self, data, klass):
"""
Deserializes list or dict to model.
:param data: dict, list.
:param klass: class literal.
:return: model object.
"""
instance = klass()
if not instance.swagger_types:
return data
for attr, attr_type in iteritems(instance.swagger_types):
if data is not None \
and instance.attribute_map[attr] in data\
and isinstance(data, (list, dict)):
value = data[instance.attribute_map[attr]]
setattr(instance, '_' + attr, self.__deserialize(value, attr_type))
return instance | [
"def",
"__deserialize_model",
"(",
"self",
",",
"data",
",",
"klass",
")",
":",
"instance",
"=",
"klass",
"(",
")",
"if",
"not",
"instance",
".",
"swagger_types",
":",
"return",
"data",
"for",
"attr",
",",
"attr_type",
"in",
"iteritems",
"(",
"instance",
... | Deserializes list or dict to model.
:param data: dict, list.
:param klass: class literal.
:return: model object. | [
"Deserializes",
"list",
"or",
"dict",
"to",
"model",
"."
] | train | https://github.com/huffpostdata/python-pollster/blob/276de8d66a92577b1143fd92a70cff9c35a1dfcf/pollster/api_client.py#L626-L646 |
PragmaticMates/django-flatpages-i18n | flatpages_i18n/views.py | flatpage | def flatpage(request, url):
"""
Public interface to the flat page view.
Models: `flatpages.flatpages`
Templates: Uses the template defined by the ``template_name`` field,
or `flatpages/default.html` if template_name is not defined.
Context:
flatpage
`flatpages.flatpages` object
"""
if not url.startswith('/'):
url = '/' + url
language = request.LANGUAGE_CODE
language_prefix = '/%s' % language
language_db_field = language.replace('-', '_')
if url.startswith(language_prefix):
url = url[len(language_prefix):]
kwargs = {
'{0}__{1}'.format('url_%s' % language_db_field, 'exact'): url,
'{0}__{1}'.format('sites__id', 'exact'): settings.SITE_ID
}
try:
f = get_object_or_404(FlatPage_i18n, **kwargs)
except Http404:
if not url.endswith('/') and settings.APPEND_SLASH:
url += '/'
f = get_object_or_404(FlatPage_i18n, **kwargs)
return HttpResponsePermanentRedirect('%s/' % request.path)
else:
raise
return render_flatpage(request, f) | python | def flatpage(request, url):
"""
Public interface to the flat page view.
Models: `flatpages.flatpages`
Templates: Uses the template defined by the ``template_name`` field,
or `flatpages/default.html` if template_name is not defined.
Context:
flatpage
`flatpages.flatpages` object
"""
if not url.startswith('/'):
url = '/' + url
language = request.LANGUAGE_CODE
language_prefix = '/%s' % language
language_db_field = language.replace('-', '_')
if url.startswith(language_prefix):
url = url[len(language_prefix):]
kwargs = {
'{0}__{1}'.format('url_%s' % language_db_field, 'exact'): url,
'{0}__{1}'.format('sites__id', 'exact'): settings.SITE_ID
}
try:
f = get_object_or_404(FlatPage_i18n, **kwargs)
except Http404:
if not url.endswith('/') and settings.APPEND_SLASH:
url += '/'
f = get_object_or_404(FlatPage_i18n, **kwargs)
return HttpResponsePermanentRedirect('%s/' % request.path)
else:
raise
return render_flatpage(request, f) | [
"def",
"flatpage",
"(",
"request",
",",
"url",
")",
":",
"if",
"not",
"url",
".",
"startswith",
"(",
"'/'",
")",
":",
"url",
"=",
"'/'",
"+",
"url",
"language",
"=",
"request",
".",
"LANGUAGE_CODE",
"language_prefix",
"=",
"'/%s'",
"%",
"language",
"la... | Public interface to the flat page view.
Models: `flatpages.flatpages`
Templates: Uses the template defined by the ``template_name`` field,
or `flatpages/default.html` if template_name is not defined.
Context:
flatpage
`flatpages.flatpages` object | [
"Public",
"interface",
"to",
"the",
"flat",
"page",
"view",
"."
] | train | https://github.com/PragmaticMates/django-flatpages-i18n/blob/2d3ed45c14fb0c7fd6ff5263c84f501c6a0c3e9a/flatpages_i18n/views.py#L28-L65 |
PragmaticMates/django-flatpages-i18n | flatpages_i18n/views.py | render_flatpage | def render_flatpage(request, f):
"""
Internal interface to the flat page view.
"""
# If registration is required for accessing this page, and the user isn't
# logged in, redirect to the login page.
if f.registration_required and not request.user.is_authenticated():
from django.contrib.auth.views import redirect_to_login
return redirect_to_login(request.path)
if f.template_name:
t = loader.select_template((f.template_name, DEFAULT_TEMPLATE))
else:
t = loader.get_template(DEFAULT_TEMPLATE)
# To avoid having to always use the "|safe" filter in flatpage templates,
# mark the title and content as already safe (since they are raw HTML
# content in the first place).
f.title = mark_safe(f.title)
f.content = mark_safe(f.content)
response = HttpResponse(t.render({
'flatpage': f
}, request))
try:
from django.core.xheaders import populate_xheaders
populate_xheaders(request, response, FlatPage_i18n, f.id)
except ImportError:
pass
return response | python | def render_flatpage(request, f):
"""
Internal interface to the flat page view.
"""
# If registration is required for accessing this page, and the user isn't
# logged in, redirect to the login page.
if f.registration_required and not request.user.is_authenticated():
from django.contrib.auth.views import redirect_to_login
return redirect_to_login(request.path)
if f.template_name:
t = loader.select_template((f.template_name, DEFAULT_TEMPLATE))
else:
t = loader.get_template(DEFAULT_TEMPLATE)
# To avoid having to always use the "|safe" filter in flatpage templates,
# mark the title and content as already safe (since they are raw HTML
# content in the first place).
f.title = mark_safe(f.title)
f.content = mark_safe(f.content)
response = HttpResponse(t.render({
'flatpage': f
}, request))
try:
from django.core.xheaders import populate_xheaders
populate_xheaders(request, response, FlatPage_i18n, f.id)
except ImportError:
pass
return response | [
"def",
"render_flatpage",
"(",
"request",
",",
"f",
")",
":",
"# If registration is required for accessing this page, and the user isn't",
"# logged in, redirect to the login page.",
"if",
"f",
".",
"registration_required",
"and",
"not",
"request",
".",
"user",
".",
"is_authe... | Internal interface to the flat page view. | [
"Internal",
"interface",
"to",
"the",
"flat",
"page",
"view",
"."
] | train | https://github.com/PragmaticMates/django-flatpages-i18n/blob/2d3ed45c14fb0c7fd6ff5263c84f501c6a0c3e9a/flatpages_i18n/views.py#L69-L98 |
kevinconway/daemons | daemons/interfaces/pid.py | PidManager.pidfile | def pidfile(self):
"""Get the absolute path of the pidfile."""
return os.path.abspath(
os.path.expandvars(
os.path.expanduser(
self._pidfile,
),
),
) | python | def pidfile(self):
"""Get the absolute path of the pidfile."""
return os.path.abspath(
os.path.expandvars(
os.path.expanduser(
self._pidfile,
),
),
) | [
"def",
"pidfile",
"(",
"self",
")",
":",
"return",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"expandvars",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"self",
".",
"_pidfile",
",",
")",
",",
")",
",",
")"
] | Get the absolute path of the pidfile. | [
"Get",
"the",
"absolute",
"path",
"of",
"the",
"pidfile",
"."
] | train | https://github.com/kevinconway/daemons/blob/b0fe0db5821171a35aa9078596d19d630c570b38/daemons/interfaces/pid.py#L25-L33 |
DEIB-GECO/PyGMQL | gmql/dataset/DataStructures/ExpressionNodes.py | SQRT | def SQRT(argument):
""" Computes the square matrix of the argument
:param argument: a dataset region field (dataset.field) or metadata (dataset['field'])
"""
if isinstance(argument, MetaField):
return argument._unary_expression("SQRT")
elif isinstance(argument, RegField):
return argument._unary_expression("SQRT")
else:
raise TypeError("You have to give as input a RegField (dataset.field)"
"or a MetaField (dataset['field']") | python | def SQRT(argument):
""" Computes the square matrix of the argument
:param argument: a dataset region field (dataset.field) or metadata (dataset['field'])
"""
if isinstance(argument, MetaField):
return argument._unary_expression("SQRT")
elif isinstance(argument, RegField):
return argument._unary_expression("SQRT")
else:
raise TypeError("You have to give as input a RegField (dataset.field)"
"or a MetaField (dataset['field']") | [
"def",
"SQRT",
"(",
"argument",
")",
":",
"if",
"isinstance",
"(",
"argument",
",",
"MetaField",
")",
":",
"return",
"argument",
".",
"_unary_expression",
"(",
"\"SQRT\"",
")",
"elif",
"isinstance",
"(",
"argument",
",",
"RegField",
")",
":",
"return",
"ar... | Computes the square matrix of the argument
:param argument: a dataset region field (dataset.field) or metadata (dataset['field']) | [
"Computes",
"the",
"square",
"matrix",
"of",
"the",
"argument"
] | train | https://github.com/DEIB-GECO/PyGMQL/blob/e58b2f9402a86056dcda484a32e3de0bb06ed991/gmql/dataset/DataStructures/ExpressionNodes.py#L5-L16 |
DEIB-GECO/PyGMQL | gmql/managers.py | login | def login():
""" Enables the user to login to the remote GMQL service.
If both username and password are None, the user will be connected as guest.
"""
from .RemoteConnection.RemoteManager import RemoteManager
global __remote_manager, __session_manager
logger = logging.getLogger()
remote_address = get_remote_address()
res = __session_manager.get_session(remote_address)
if res is None:
# there is no session for this address, let's login as guest
warnings.warn("There is no active session for address {}. Logging as Guest user".format(remote_address))
rm = RemoteManager(address=remote_address)
rm.login()
session_type = "guest"
else:
# there is a previous session for this address, let's do an auto login
# using that access token
logger.info("Logging using stored authentication token")
rm = RemoteManager(address=remote_address, auth_token=res[1])
# if the access token is not valid anymore (therefore we are in guest mode)
# the auto_login function will perform a guest login from scratch
session_type = rm.auto_login(how=res[2])
# store the new session
__remote_manager = rm
access_time = int(time.time())
auth_token = rm.auth_token
__session_manager.add_session(remote_address, auth_token, access_time, session_type) | python | def login():
""" Enables the user to login to the remote GMQL service.
If both username and password are None, the user will be connected as guest.
"""
from .RemoteConnection.RemoteManager import RemoteManager
global __remote_manager, __session_manager
logger = logging.getLogger()
remote_address = get_remote_address()
res = __session_manager.get_session(remote_address)
if res is None:
# there is no session for this address, let's login as guest
warnings.warn("There is no active session for address {}. Logging as Guest user".format(remote_address))
rm = RemoteManager(address=remote_address)
rm.login()
session_type = "guest"
else:
# there is a previous session for this address, let's do an auto login
# using that access token
logger.info("Logging using stored authentication token")
rm = RemoteManager(address=remote_address, auth_token=res[1])
# if the access token is not valid anymore (therefore we are in guest mode)
# the auto_login function will perform a guest login from scratch
session_type = rm.auto_login(how=res[2])
# store the new session
__remote_manager = rm
access_time = int(time.time())
auth_token = rm.auth_token
__session_manager.add_session(remote_address, auth_token, access_time, session_type) | [
"def",
"login",
"(",
")",
":",
"from",
".",
"RemoteConnection",
".",
"RemoteManager",
"import",
"RemoteManager",
"global",
"__remote_manager",
",",
"__session_manager",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
")",
"remote_address",
"=",
"get_remote_address"... | Enables the user to login to the remote GMQL service.
If both username and password are None, the user will be connected as guest. | [
"Enables",
"the",
"user",
"to",
"login",
"to",
"the",
"remote",
"GMQL",
"service",
".",
"If",
"both",
"username",
"and",
"password",
"are",
"None",
"the",
"user",
"will",
"be",
"connected",
"as",
"guest",
"."
] | train | https://github.com/DEIB-GECO/PyGMQL/blob/e58b2f9402a86056dcda484a32e3de0bb06ed991/gmql/managers.py#L205-L233 |
kevinconway/daemons | samples/wrapper.py | main | def main(idle):
"""Any normal python logic which runs a loop. Can take arguments."""
while True:
LOG.debug("Sleeping for {0} seconds.".format(idle))
time.sleep(idle) | python | def main(idle):
"""Any normal python logic which runs a loop. Can take arguments."""
while True:
LOG.debug("Sleeping for {0} seconds.".format(idle))
time.sleep(idle) | [
"def",
"main",
"(",
"idle",
")",
":",
"while",
"True",
":",
"LOG",
".",
"debug",
"(",
"\"Sleeping for {0} seconds.\"",
".",
"format",
"(",
"idle",
")",
")",
"time",
".",
"sleep",
"(",
"idle",
")"
] | Any normal python logic which runs a loop. Can take arguments. | [
"Any",
"normal",
"python",
"logic",
"which",
"runs",
"a",
"loop",
".",
"Can",
"take",
"arguments",
"."
] | train | https://github.com/kevinconway/daemons/blob/b0fe0db5821171a35aa9078596d19d630c570b38/samples/wrapper.py#L28-L33 |
DEIB-GECO/PyGMQL | gmql/dataset/GMQLDataset.py | GMQLDataset.get_metadata | def get_metadata(self):
""" Returns the metadata related to the current GMQLDataset. This function can be used only
when a local dataset is loaded using the :meth:`~gmql.dataset.loaders.Loader.load_from_path` and no other
operation has been called on the GMQLDataset.
The metadata are returned in the form of a Pandas Dataframe having as index the sample ids and as columns
the metadata attributes.
:return: a Pandas Dataframe
"""
if self.path_or_name is None:
raise ValueError("You cannot explore the metadata of an intermediate query."
"You can get metadata only after a load_from_local or load_from_remote")
if self.location == 'local':
return self.__get_metadata_local()
elif self.location == 'remote':
return self.__get_metadata_remote() | python | def get_metadata(self):
""" Returns the metadata related to the current GMQLDataset. This function can be used only
when a local dataset is loaded using the :meth:`~gmql.dataset.loaders.Loader.load_from_path` and no other
operation has been called on the GMQLDataset.
The metadata are returned in the form of a Pandas Dataframe having as index the sample ids and as columns
the metadata attributes.
:return: a Pandas Dataframe
"""
if self.path_or_name is None:
raise ValueError("You cannot explore the metadata of an intermediate query."
"You can get metadata only after a load_from_local or load_from_remote")
if self.location == 'local':
return self.__get_metadata_local()
elif self.location == 'remote':
return self.__get_metadata_remote() | [
"def",
"get_metadata",
"(",
"self",
")",
":",
"if",
"self",
".",
"path_or_name",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"You cannot explore the metadata of an intermediate query.\"",
"\"You can get metadata only after a load_from_local or load_from_remote\"",
")",
"if... | Returns the metadata related to the current GMQLDataset. This function can be used only
when a local dataset is loaded using the :meth:`~gmql.dataset.loaders.Loader.load_from_path` and no other
operation has been called on the GMQLDataset.
The metadata are returned in the form of a Pandas Dataframe having as index the sample ids and as columns
the metadata attributes.
:return: a Pandas Dataframe | [
"Returns",
"the",
"metadata",
"related",
"to",
"the",
"current",
"GMQLDataset",
".",
"This",
"function",
"can",
"be",
"used",
"only",
"when",
"a",
"local",
"dataset",
"is",
"loaded",
"using",
"the",
":",
"meth",
":",
"~gmql",
".",
"dataset",
".",
"loaders"... | train | https://github.com/DEIB-GECO/PyGMQL/blob/e58b2f9402a86056dcda484a32e3de0bb06ed991/gmql/dataset/GMQLDataset.py#L88-L104 |
DEIB-GECO/PyGMQL | gmql/dataset/GMQLDataset.py | GMQLDataset.MetaField | def MetaField(self, name, t=None):
"""
Creates an instance of a metadata field of the dataset. It can be used in building expressions
or conditions for projection or selection.
Notice that this function is equivalent to call::
dataset["name"]
If the MetaField is used in a region projection (:meth:`~.reg_project`), the user has also to specify the type
of the metadata attribute that is selected::
dataset.reg_project(new_field_dict={'new_field': dataset['name', 'string']})
:param name: the name of the metadata that is considered
:param t: the type of the metadata attribute {string, int, boolean, double}
:return: a MetaField instance
"""
return MetaField(name=name, index=self.__index, t=t) | python | def MetaField(self, name, t=None):
"""
Creates an instance of a metadata field of the dataset. It can be used in building expressions
or conditions for projection or selection.
Notice that this function is equivalent to call::
dataset["name"]
If the MetaField is used in a region projection (:meth:`~.reg_project`), the user has also to specify the type
of the metadata attribute that is selected::
dataset.reg_project(new_field_dict={'new_field': dataset['name', 'string']})
:param name: the name of the metadata that is considered
:param t: the type of the metadata attribute {string, int, boolean, double}
:return: a MetaField instance
"""
return MetaField(name=name, index=self.__index, t=t) | [
"def",
"MetaField",
"(",
"self",
",",
"name",
",",
"t",
"=",
"None",
")",
":",
"return",
"MetaField",
"(",
"name",
"=",
"name",
",",
"index",
"=",
"self",
".",
"__index",
",",
"t",
"=",
"t",
")"
] | Creates an instance of a metadata field of the dataset. It can be used in building expressions
or conditions for projection or selection.
Notice that this function is equivalent to call::
dataset["name"]
If the MetaField is used in a region projection (:meth:`~.reg_project`), the user has also to specify the type
of the metadata attribute that is selected::
dataset.reg_project(new_field_dict={'new_field': dataset['name', 'string']})
:param name: the name of the metadata that is considered
:param t: the type of the metadata attribute {string, int, boolean, double}
:return: a MetaField instance | [
"Creates",
"an",
"instance",
"of",
"a",
"metadata",
"field",
"of",
"the",
"dataset",
".",
"It",
"can",
"be",
"used",
"in",
"building",
"expressions",
"or",
"conditions",
"for",
"projection",
"or",
"selection",
".",
"Notice",
"that",
"this",
"function",
"is",... | train | https://github.com/DEIB-GECO/PyGMQL/blob/e58b2f9402a86056dcda484a32e3de0bb06ed991/gmql/dataset/GMQLDataset.py#L121-L139 |
DEIB-GECO/PyGMQL | gmql/dataset/GMQLDataset.py | GMQLDataset.select | def select(self, meta_predicate=None, region_predicate=None,
semiJoinDataset=None, semiJoinMeta=None):
""" *Wrapper of* ``SELECT``
Selection operation. Enables to filter datasets on the basis of region features or metadata attributes. In
addition it is possibile to perform a selection based on the existence of certain metadata
:attr:`~.semiJoinMeta` attributes and the matching of their values with those associated with at
least one sample in an external dataset :attr:`~.semiJoinDataset`.
Therefore, the selection can be based on:
* *Metadata predicates*: selection based on the existence and values of certain
metadata attributes in each sample. In predicates, attribute-value conditions
can be composed using logical predicates & (and), | (or) and ~ (not)
* *Region predicates*: selection based on region attributes. Conditions
can be composed using logical predicates & (and), | (or) and ~ (not)
* *SemiJoin clauses*: selection based on the existence of certain metadata :attr:`~.semiJoinMeta`
attributes and the matching of their values with those associated with at
least one sample in an external dataset :attr:`~.semiJoinDataset`
In the following example we select all the samples from Example_Dataset_1 regarding antibody CTCF.
From these samples we select only the regions on chromosome 6. Finally we select only the samples which have
a matching antibody_targetClass in Example_Dataset_2::
import gmql as gl
d1 = gl.get_example_dataset("Example_Dataset_1")
d2 = gl.get_example_dataset("Example_Dataset_2")
d_select = d.select(meta_predicate = d['antibody'] == "CTCF",
region_predicate = d.chr == "chr6",
semiJoinDataset=d2, semiJoinMeta=["antibody_targetClass"])
:param meta_predicate: logical predicate on the metadata <attribute, value> pairs
:param region_predicate: logical predicate on the region feature values
:param semiJoinDataset: an other GMQLDataset
:param semiJoinMeta: a list of metadata attributes (strings)
:return: a new GMQLDataset
"""
semiJoinDataset_exists = False
if isinstance(meta_predicate, MetaField):
meta_condition = Some(meta_predicate.getMetaCondition())
elif meta_predicate is None:
meta_condition = none()
else:
raise TypeError("meta_predicate must be a MetaField or None."
" {} was provided".format(type(meta_predicate)))
if isinstance(region_predicate, RegField):
region_condition = Some(region_predicate.getRegionCondition())
elif region_predicate is None:
region_condition = none()
else:
raise TypeError("region_predicate must be a RegField or None."
" {} was provided".format(type(region_predicate)))
new_location = self.location
new_local_sources, new_remote_sources = self._local_sources, self._remote_sources
if isinstance(semiJoinDataset, GMQLDataset):
other_dataset = Some(semiJoinDataset.__index)
semiJoinDataset_exists = True
elif semiJoinDataset is None:
other_dataset = none()
else:
raise TypeError("semiJoinDataset must be a GMQLDataset or None."
" {} was provided".format(type(semiJoinDataset)))
if isinstance(semiJoinMeta, list) and \
all([isinstance(x, str) for x in semiJoinMeta]):
if semiJoinDataset_exists:
semi_join = Some(self.opmng.getMetaJoinCondition(semiJoinMeta))
new_local_sources, new_remote_sources = self.__combine_sources(self, semiJoinDataset)
new_location = self.__combine_locations(self, semiJoinDataset)
else:
raise ValueError("semiJoinDataset and semiJoinMeta must be present at the "
"same time or totally absent")
elif semiJoinMeta is None:
semi_join = none()
else:
raise TypeError("semiJoinMeta must be a list of strings or None."
" {} was provided".format(type(semiJoinMeta)))
new_index = self.opmng.select(self.__index, other_dataset,
semi_join, meta_condition, region_condition)
return GMQLDataset(index=new_index, location=new_location, local_sources=new_local_sources,
remote_sources=new_remote_sources, meta_profile=self.meta_profile) | python | def select(self, meta_predicate=None, region_predicate=None,
semiJoinDataset=None, semiJoinMeta=None):
""" *Wrapper of* ``SELECT``
Selection operation. Enables to filter datasets on the basis of region features or metadata attributes. In
addition it is possibile to perform a selection based on the existence of certain metadata
:attr:`~.semiJoinMeta` attributes and the matching of their values with those associated with at
least one sample in an external dataset :attr:`~.semiJoinDataset`.
Therefore, the selection can be based on:
* *Metadata predicates*: selection based on the existence and values of certain
metadata attributes in each sample. In predicates, attribute-value conditions
can be composed using logical predicates & (and), | (or) and ~ (not)
* *Region predicates*: selection based on region attributes. Conditions
can be composed using logical predicates & (and), | (or) and ~ (not)
* *SemiJoin clauses*: selection based on the existence of certain metadata :attr:`~.semiJoinMeta`
attributes and the matching of their values with those associated with at
least one sample in an external dataset :attr:`~.semiJoinDataset`
In the following example we select all the samples from Example_Dataset_1 regarding antibody CTCF.
From these samples we select only the regions on chromosome 6. Finally we select only the samples which have
a matching antibody_targetClass in Example_Dataset_2::
import gmql as gl
d1 = gl.get_example_dataset("Example_Dataset_1")
d2 = gl.get_example_dataset("Example_Dataset_2")
d_select = d.select(meta_predicate = d['antibody'] == "CTCF",
region_predicate = d.chr == "chr6",
semiJoinDataset=d2, semiJoinMeta=["antibody_targetClass"])
:param meta_predicate: logical predicate on the metadata <attribute, value> pairs
:param region_predicate: logical predicate on the region feature values
:param semiJoinDataset: an other GMQLDataset
:param semiJoinMeta: a list of metadata attributes (strings)
:return: a new GMQLDataset
"""
semiJoinDataset_exists = False
if isinstance(meta_predicate, MetaField):
meta_condition = Some(meta_predicate.getMetaCondition())
elif meta_predicate is None:
meta_condition = none()
else:
raise TypeError("meta_predicate must be a MetaField or None."
" {} was provided".format(type(meta_predicate)))
if isinstance(region_predicate, RegField):
region_condition = Some(region_predicate.getRegionCondition())
elif region_predicate is None:
region_condition = none()
else:
raise TypeError("region_predicate must be a RegField or None."
" {} was provided".format(type(region_predicate)))
new_location = self.location
new_local_sources, new_remote_sources = self._local_sources, self._remote_sources
if isinstance(semiJoinDataset, GMQLDataset):
other_dataset = Some(semiJoinDataset.__index)
semiJoinDataset_exists = True
elif semiJoinDataset is None:
other_dataset = none()
else:
raise TypeError("semiJoinDataset must be a GMQLDataset or None."
" {} was provided".format(type(semiJoinDataset)))
if isinstance(semiJoinMeta, list) and \
all([isinstance(x, str) for x in semiJoinMeta]):
if semiJoinDataset_exists:
semi_join = Some(self.opmng.getMetaJoinCondition(semiJoinMeta))
new_local_sources, new_remote_sources = self.__combine_sources(self, semiJoinDataset)
new_location = self.__combine_locations(self, semiJoinDataset)
else:
raise ValueError("semiJoinDataset and semiJoinMeta must be present at the "
"same time or totally absent")
elif semiJoinMeta is None:
semi_join = none()
else:
raise TypeError("semiJoinMeta must be a list of strings or None."
" {} was provided".format(type(semiJoinMeta)))
new_index = self.opmng.select(self.__index, other_dataset,
semi_join, meta_condition, region_condition)
return GMQLDataset(index=new_index, location=new_location, local_sources=new_local_sources,
remote_sources=new_remote_sources, meta_profile=self.meta_profile) | [
"def",
"select",
"(",
"self",
",",
"meta_predicate",
"=",
"None",
",",
"region_predicate",
"=",
"None",
",",
"semiJoinDataset",
"=",
"None",
",",
"semiJoinMeta",
"=",
"None",
")",
":",
"semiJoinDataset_exists",
"=",
"False",
"if",
"isinstance",
"(",
"meta_pred... | *Wrapper of* ``SELECT``
Selection operation. Enables to filter datasets on the basis of region features or metadata attributes. In
addition it is possibile to perform a selection based on the existence of certain metadata
:attr:`~.semiJoinMeta` attributes and the matching of their values with those associated with at
least one sample in an external dataset :attr:`~.semiJoinDataset`.
Therefore, the selection can be based on:
* *Metadata predicates*: selection based on the existence and values of certain
metadata attributes in each sample. In predicates, attribute-value conditions
can be composed using logical predicates & (and), | (or) and ~ (not)
* *Region predicates*: selection based on region attributes. Conditions
can be composed using logical predicates & (and), | (or) and ~ (not)
* *SemiJoin clauses*: selection based on the existence of certain metadata :attr:`~.semiJoinMeta`
attributes and the matching of their values with those associated with at
least one sample in an external dataset :attr:`~.semiJoinDataset`
In the following example we select all the samples from Example_Dataset_1 regarding antibody CTCF.
From these samples we select only the regions on chromosome 6. Finally we select only the samples which have
a matching antibody_targetClass in Example_Dataset_2::
import gmql as gl
d1 = gl.get_example_dataset("Example_Dataset_1")
d2 = gl.get_example_dataset("Example_Dataset_2")
d_select = d.select(meta_predicate = d['antibody'] == "CTCF",
region_predicate = d.chr == "chr6",
semiJoinDataset=d2, semiJoinMeta=["antibody_targetClass"])
:param meta_predicate: logical predicate on the metadata <attribute, value> pairs
:param region_predicate: logical predicate on the region feature values
:param semiJoinDataset: an other GMQLDataset
:param semiJoinMeta: a list of metadata attributes (strings)
:return: a new GMQLDataset | [
"*",
"Wrapper",
"of",
"*",
"SELECT"
] | train | https://github.com/DEIB-GECO/PyGMQL/blob/e58b2f9402a86056dcda484a32e3de0bb06ed991/gmql/dataset/GMQLDataset.py#L154-L243 |
DEIB-GECO/PyGMQL | gmql/dataset/GMQLDataset.py | GMQLDataset.meta_select | def meta_select(self, predicate=None, semiJoinDataset=None, semiJoinMeta=None):
"""
*Wrapper of* ``SELECT``
Wrapper of the :meth:`~.select` function filtering samples only based on metadata.
:param predicate: logical predicate on the values of the rows
:param semiJoinDataset: an other GMQLDataset
:param semiJoinMeta: a list of metadata
:return: a new GMQLDataset
Example 1::
output_dataset = dataset.meta_select(dataset['patient_age'] < 70)
# This statement can be written also as
output_dataset = dataset[ dataset['patient_age'] < 70 ]
Example 2::
output_dataset = dataset.meta_select( (dataset['tissue_status'] == 'tumoral') &
(tumor_tag != 'gbm') | (tumor_tag == 'brca'))
# This statement can be written also as
output_dataset = dataset[ (dataset['tissue_status'] == 'tumoral') &
(tumor_tag != 'gbm') | (tumor_tag == 'brca') ]
Example 3::
JUN_POLR2A_TF = HG19_ENCODE_NARROW.meta_select( JUN_POLR2A_TF['antibody_target'] == 'JUN',
semiJoinDataset=POLR2A_TF, semiJoinMeta=['cell'])
The meta selection predicate can use all the classical equalities and disequalities
{>, <, >=, <=, ==, !=} and predicates can be connected by the classical logical symbols
{& (AND), | (OR), ~ (NOT)} plus the *isin* function.
"""
return self.select(meta_predicate=predicate, semiJoinDataset=semiJoinDataset, semiJoinMeta=semiJoinMeta) | python | def meta_select(self, predicate=None, semiJoinDataset=None, semiJoinMeta=None):
"""
*Wrapper of* ``SELECT``
Wrapper of the :meth:`~.select` function filtering samples only based on metadata.
:param predicate: logical predicate on the values of the rows
:param semiJoinDataset: an other GMQLDataset
:param semiJoinMeta: a list of metadata
:return: a new GMQLDataset
Example 1::
output_dataset = dataset.meta_select(dataset['patient_age'] < 70)
# This statement can be written also as
output_dataset = dataset[ dataset['patient_age'] < 70 ]
Example 2::
output_dataset = dataset.meta_select( (dataset['tissue_status'] == 'tumoral') &
(tumor_tag != 'gbm') | (tumor_tag == 'brca'))
# This statement can be written also as
output_dataset = dataset[ (dataset['tissue_status'] == 'tumoral') &
(tumor_tag != 'gbm') | (tumor_tag == 'brca') ]
Example 3::
JUN_POLR2A_TF = HG19_ENCODE_NARROW.meta_select( JUN_POLR2A_TF['antibody_target'] == 'JUN',
semiJoinDataset=POLR2A_TF, semiJoinMeta=['cell'])
The meta selection predicate can use all the classical equalities and disequalities
{>, <, >=, <=, ==, !=} and predicates can be connected by the classical logical symbols
{& (AND), | (OR), ~ (NOT)} plus the *isin* function.
"""
return self.select(meta_predicate=predicate, semiJoinDataset=semiJoinDataset, semiJoinMeta=semiJoinMeta) | [
"def",
"meta_select",
"(",
"self",
",",
"predicate",
"=",
"None",
",",
"semiJoinDataset",
"=",
"None",
",",
"semiJoinMeta",
"=",
"None",
")",
":",
"return",
"self",
".",
"select",
"(",
"meta_predicate",
"=",
"predicate",
",",
"semiJoinDataset",
"=",
"semiJoi... | *Wrapper of* ``SELECT``
Wrapper of the :meth:`~.select` function filtering samples only based on metadata.
:param predicate: logical predicate on the values of the rows
:param semiJoinDataset: an other GMQLDataset
:param semiJoinMeta: a list of metadata
:return: a new GMQLDataset
Example 1::
output_dataset = dataset.meta_select(dataset['patient_age'] < 70)
# This statement can be written also as
output_dataset = dataset[ dataset['patient_age'] < 70 ]
Example 2::
output_dataset = dataset.meta_select( (dataset['tissue_status'] == 'tumoral') &
(tumor_tag != 'gbm') | (tumor_tag == 'brca'))
# This statement can be written also as
output_dataset = dataset[ (dataset['tissue_status'] == 'tumoral') &
(tumor_tag != 'gbm') | (tumor_tag == 'brca') ]
Example 3::
JUN_POLR2A_TF = HG19_ENCODE_NARROW.meta_select( JUN_POLR2A_TF['antibody_target'] == 'JUN',
semiJoinDataset=POLR2A_TF, semiJoinMeta=['cell'])
The meta selection predicate can use all the classical equalities and disequalities
{>, <, >=, <=, ==, !=} and predicates can be connected by the classical logical symbols
{& (AND), | (OR), ~ (NOT)} plus the *isin* function. | [
"*",
"Wrapper",
"of",
"*",
"SELECT"
] | train | https://github.com/DEIB-GECO/PyGMQL/blob/e58b2f9402a86056dcda484a32e3de0bb06ed991/gmql/dataset/GMQLDataset.py#L245-L282 |
DEIB-GECO/PyGMQL | gmql/dataset/GMQLDataset.py | GMQLDataset.reg_select | def reg_select(self, predicate=None, semiJoinDataset=None, semiJoinMeta=None):
"""
*Wrapper of* ``SELECT``
Wrapper of the :meth:`~.select` function filtering regions only based on region attributes.
:param predicate: logical predicate on the values of the regions
:param semiJoinDataset: an other GMQLDataset
:param semiJoinMeta: a list of metadata
:return: a new GMQLDataset
An example of usage::
new_dataset = dataset.reg_select((dataset.chr == 'chr1') | (dataset.pValue < 0.9))
You can also use Metadata attributes in selection::
new_dataset = dataset.reg_select(dataset.score > dataset['size'])
This statement selects all the regions whose field score is strictly higher than the sample
metadata attribute size.
The region selection predicate can use all the classical equalities and disequalities
{>, <, >=, <=, ==, !=} and predicates can be connected by the classical logical symbols
{& (AND), | (OR), ~ (NOT)} plus the *isin* function.
In order to be sure about the correctness of the expression, please use parenthesis to delimit
the various predicates.
"""
return self.select(region_predicate=predicate, semiJoinMeta=semiJoinMeta, semiJoinDataset=semiJoinDataset) | python | def reg_select(self, predicate=None, semiJoinDataset=None, semiJoinMeta=None):
"""
*Wrapper of* ``SELECT``
Wrapper of the :meth:`~.select` function filtering regions only based on region attributes.
:param predicate: logical predicate on the values of the regions
:param semiJoinDataset: an other GMQLDataset
:param semiJoinMeta: a list of metadata
:return: a new GMQLDataset
An example of usage::
new_dataset = dataset.reg_select((dataset.chr == 'chr1') | (dataset.pValue < 0.9))
You can also use Metadata attributes in selection::
new_dataset = dataset.reg_select(dataset.score > dataset['size'])
This statement selects all the regions whose field score is strictly higher than the sample
metadata attribute size.
The region selection predicate can use all the classical equalities and disequalities
{>, <, >=, <=, ==, !=} and predicates can be connected by the classical logical symbols
{& (AND), | (OR), ~ (NOT)} plus the *isin* function.
In order to be sure about the correctness of the expression, please use parenthesis to delimit
the various predicates.
"""
return self.select(region_predicate=predicate, semiJoinMeta=semiJoinMeta, semiJoinDataset=semiJoinDataset) | [
"def",
"reg_select",
"(",
"self",
",",
"predicate",
"=",
"None",
",",
"semiJoinDataset",
"=",
"None",
",",
"semiJoinMeta",
"=",
"None",
")",
":",
"return",
"self",
".",
"select",
"(",
"region_predicate",
"=",
"predicate",
",",
"semiJoinMeta",
"=",
"semiJoinM... | *Wrapper of* ``SELECT``
Wrapper of the :meth:`~.select` function filtering regions only based on region attributes.
:param predicate: logical predicate on the values of the regions
:param semiJoinDataset: an other GMQLDataset
:param semiJoinMeta: a list of metadata
:return: a new GMQLDataset
An example of usage::
new_dataset = dataset.reg_select((dataset.chr == 'chr1') | (dataset.pValue < 0.9))
You can also use Metadata attributes in selection::
new_dataset = dataset.reg_select(dataset.score > dataset['size'])
This statement selects all the regions whose field score is strictly higher than the sample
metadata attribute size.
The region selection predicate can use all the classical equalities and disequalities
{>, <, >=, <=, ==, !=} and predicates can be connected by the classical logical symbols
{& (AND), | (OR), ~ (NOT)} plus the *isin* function.
In order to be sure about the correctness of the expression, please use parenthesis to delimit
the various predicates. | [
"*",
"Wrapper",
"of",
"*",
"SELECT"
] | train | https://github.com/DEIB-GECO/PyGMQL/blob/e58b2f9402a86056dcda484a32e3de0bb06ed991/gmql/dataset/GMQLDataset.py#L284-L313 |
DEIB-GECO/PyGMQL | gmql/dataset/GMQLDataset.py | GMQLDataset.project | def project(self, projected_meta=None, new_attr_dict=None, all_but_meta=None,
projected_regs=None, new_field_dict=None, all_but_regs=None):
"""
*Wrapper of* ``PROJECT``
The PROJECT operator creates, from an existing dataset, a new dataset with all the samples
(with their regions and region values) in the input one, but keeping for each sample in the input
dataset only those metadata and/or region attributes expressed in the operator parameter list.
Region coordinates and values of the remaining metadata and region attributes remain equal
to those in the input dataset. Differently from the SELECT operator, PROJECT allows to:
* Remove existing metadata and/or region attributes from a dataset;
* Create new metadata and/or region attributes to be added to the result.
:param projected_meta: list of metadata attributes to project on
:param new_attr_dict: an optional dictionary of the form {'new_meta_1': function1,
'new_meta_2': function2, ...} in which every function computes
the new metadata attribute based on the values of the others
:param all_but_meta: list of metadata attributes that must be excluded from the projection
:param projected_regs: list of the region fields to select
:param new_field_dict: an optional dictionary of the form {'new_field_1':
function1, 'new_field_2': function2, ...} in which every function
computes the new region field based on the values of the others
:param all_but_regs: list of region fields that must be excluded from the projection
:return: a new GMQLDataset
"""
projected_meta_exists = False
if isinstance(projected_meta, list) and \
all([isinstance(x, str) for x in projected_meta]):
projected_meta = Some(projected_meta)
projected_meta_exists = True
elif projected_meta is None:
projected_meta = none()
else:
raise TypeError("projected_meta must be a list of strings or None."
" {} was provided".format(type(projected_meta)))
if isinstance(new_attr_dict, dict):
meta_ext = []
expBuild = self.pmg.getNewExpressionBuilder(self.__index)
for k in new_attr_dict.keys():
item = new_attr_dict[k]
if isinstance(k, str):
if isinstance(item, MetaField):
me = expBuild.createMetaExtension(k, item.getMetaExpression())
elif isinstance(item, int):
me = expBuild.createMetaExtension(k, expBuild.getMEType("int", str(item)))
elif isinstance(item, str):
me = expBuild.createMetaExtension(k, expBuild.getMEType("string", item))
elif isinstance(item, float):
me = expBuild.createMetaExtension(k, expBuild.getMEType("float", str(item)))
else:
raise TypeError("Type {} of item of new_attr_dict is not valid".format(type(item)))
meta_ext.append(me)
else:
raise TypeError("The key of new_attr_dict must be a string. "
"{} was provided".format(type(k)))
meta_ext = Some(meta_ext)
elif new_attr_dict is None:
meta_ext = none()
else:
raise TypeError("new_attr_dict must be a dictionary."
" {} was provided".format(type(new_attr_dict)))
if isinstance(all_but_meta, list) and \
all([isinstance(x, str) for x in all_but_meta]):
if not projected_meta_exists:
all_but_meta = Some(all_but_meta)
all_but_value = True
else:
raise ValueError("all_but_meta and projected_meta are mutually exclusive")
elif all_but_meta is None:
all_but_meta = none()
all_but_value = False
else:
raise TypeError("all_but_meta must be a list of strings."
" {} was provided".format(type(all_but_meta)))
projected_meta = all_but_meta if all_but_value else projected_meta
projected_regs_exists = False
if isinstance(projected_regs, list) and \
all([isinstance(x, str) for x in projected_regs]):
projected_regs = Some(projected_regs)
projected_regs_exists = True
elif projected_regs is None:
projected_regs = none()
else:
raise TypeError("projected_regs must be a list of strings or None."
" {} was provided".format(type(projected_regs)))
if isinstance(new_field_dict, dict):
regs_ext = []
expBuild = self.pmg.getNewExpressionBuilder(self.__index)
for k in new_field_dict.keys():
item = new_field_dict[k]
if isinstance(k, str):
if isinstance(item, RegField):
re = expBuild.createRegionExtension(k, item.getRegionExpression())
elif isinstance(item, MetaField):
re = expBuild.createRegionExtension(k, item.reMetaNode)
elif isinstance(item, int):
re = expBuild.createRegionExtension(k, expBuild.getREType("float", str(item)))
elif isinstance(item, str):
re = expBuild.createRegionExtension(k, expBuild.getREType("string", item))
elif isinstance(item, float):
re = expBuild.createRegionExtension(k, expBuild.getREType("float", str(item)))
else:
raise TypeError("Type {} of item of new_field_dict is not valid".format(type(item)))
regs_ext.append(re)
else:
raise TypeError("The key of new_field_dict must be a string. "
"{} was provided".format(type(k)))
regs_ext = Some(regs_ext)
elif new_field_dict is None:
regs_ext = none()
else:
raise TypeError("new_field_dict must be a dictionary."
" {} was provided".format(type(new_field_dict)))
if isinstance(all_but_regs, list) and \
all([isinstance(x, str) for x in all_but_regs]):
if not projected_regs_exists:
all_but_regs = Some(all_but_regs)
else:
raise ValueError("all_but_meta and projected_meta are mutually exclusive")
elif all_but_regs is None:
all_but_regs = none()
else:
raise TypeError("all_but_regs must be a list of strings."
" {} was provided".format(type(all_but_regs)))
new_index = self.opmng.project(self.__index, projected_meta, meta_ext, all_but_value,
projected_regs, all_but_regs, regs_ext)
return GMQLDataset(index=new_index, location=self.location,
local_sources=self._local_sources, remote_sources=self._remote_sources,
meta_profile=self.meta_profile) | python | def project(self, projected_meta=None, new_attr_dict=None, all_but_meta=None,
projected_regs=None, new_field_dict=None, all_but_regs=None):
"""
*Wrapper of* ``PROJECT``
The PROJECT operator creates, from an existing dataset, a new dataset with all the samples
(with their regions and region values) in the input one, but keeping for each sample in the input
dataset only those metadata and/or region attributes expressed in the operator parameter list.
Region coordinates and values of the remaining metadata and region attributes remain equal
to those in the input dataset. Differently from the SELECT operator, PROJECT allows to:
* Remove existing metadata and/or region attributes from a dataset;
* Create new metadata and/or region attributes to be added to the result.
:param projected_meta: list of metadata attributes to project on
:param new_attr_dict: an optional dictionary of the form {'new_meta_1': function1,
'new_meta_2': function2, ...} in which every function computes
the new metadata attribute based on the values of the others
:param all_but_meta: list of metadata attributes that must be excluded from the projection
:param projected_regs: list of the region fields to select
:param new_field_dict: an optional dictionary of the form {'new_field_1':
function1, 'new_field_2': function2, ...} in which every function
computes the new region field based on the values of the others
:param all_but_regs: list of region fields that must be excluded from the projection
:return: a new GMQLDataset
"""
projected_meta_exists = False
if isinstance(projected_meta, list) and \
all([isinstance(x, str) for x in projected_meta]):
projected_meta = Some(projected_meta)
projected_meta_exists = True
elif projected_meta is None:
projected_meta = none()
else:
raise TypeError("projected_meta must be a list of strings or None."
" {} was provided".format(type(projected_meta)))
if isinstance(new_attr_dict, dict):
meta_ext = []
expBuild = self.pmg.getNewExpressionBuilder(self.__index)
for k in new_attr_dict.keys():
item = new_attr_dict[k]
if isinstance(k, str):
if isinstance(item, MetaField):
me = expBuild.createMetaExtension(k, item.getMetaExpression())
elif isinstance(item, int):
me = expBuild.createMetaExtension(k, expBuild.getMEType("int", str(item)))
elif isinstance(item, str):
me = expBuild.createMetaExtension(k, expBuild.getMEType("string", item))
elif isinstance(item, float):
me = expBuild.createMetaExtension(k, expBuild.getMEType("float", str(item)))
else:
raise TypeError("Type {} of item of new_attr_dict is not valid".format(type(item)))
meta_ext.append(me)
else:
raise TypeError("The key of new_attr_dict must be a string. "
"{} was provided".format(type(k)))
meta_ext = Some(meta_ext)
elif new_attr_dict is None:
meta_ext = none()
else:
raise TypeError("new_attr_dict must be a dictionary."
" {} was provided".format(type(new_attr_dict)))
if isinstance(all_but_meta, list) and \
all([isinstance(x, str) for x in all_but_meta]):
if not projected_meta_exists:
all_but_meta = Some(all_but_meta)
all_but_value = True
else:
raise ValueError("all_but_meta and projected_meta are mutually exclusive")
elif all_but_meta is None:
all_but_meta = none()
all_but_value = False
else:
raise TypeError("all_but_meta must be a list of strings."
" {} was provided".format(type(all_but_meta)))
projected_meta = all_but_meta if all_but_value else projected_meta
projected_regs_exists = False
if isinstance(projected_regs, list) and \
all([isinstance(x, str) for x in projected_regs]):
projected_regs = Some(projected_regs)
projected_regs_exists = True
elif projected_regs is None:
projected_regs = none()
else:
raise TypeError("projected_regs must be a list of strings or None."
" {} was provided".format(type(projected_regs)))
if isinstance(new_field_dict, dict):
regs_ext = []
expBuild = self.pmg.getNewExpressionBuilder(self.__index)
for k in new_field_dict.keys():
item = new_field_dict[k]
if isinstance(k, str):
if isinstance(item, RegField):
re = expBuild.createRegionExtension(k, item.getRegionExpression())
elif isinstance(item, MetaField):
re = expBuild.createRegionExtension(k, item.reMetaNode)
elif isinstance(item, int):
re = expBuild.createRegionExtension(k, expBuild.getREType("float", str(item)))
elif isinstance(item, str):
re = expBuild.createRegionExtension(k, expBuild.getREType("string", item))
elif isinstance(item, float):
re = expBuild.createRegionExtension(k, expBuild.getREType("float", str(item)))
else:
raise TypeError("Type {} of item of new_field_dict is not valid".format(type(item)))
regs_ext.append(re)
else:
raise TypeError("The key of new_field_dict must be a string. "
"{} was provided".format(type(k)))
regs_ext = Some(regs_ext)
elif new_field_dict is None:
regs_ext = none()
else:
raise TypeError("new_field_dict must be a dictionary."
" {} was provided".format(type(new_field_dict)))
if isinstance(all_but_regs, list) and \
all([isinstance(x, str) for x in all_but_regs]):
if not projected_regs_exists:
all_but_regs = Some(all_but_regs)
else:
raise ValueError("all_but_meta and projected_meta are mutually exclusive")
elif all_but_regs is None:
all_but_regs = none()
else:
raise TypeError("all_but_regs must be a list of strings."
" {} was provided".format(type(all_but_regs)))
new_index = self.opmng.project(self.__index, projected_meta, meta_ext, all_but_value,
projected_regs, all_but_regs, regs_ext)
return GMQLDataset(index=new_index, location=self.location,
local_sources=self._local_sources, remote_sources=self._remote_sources,
meta_profile=self.meta_profile) | [
"def",
"project",
"(",
"self",
",",
"projected_meta",
"=",
"None",
",",
"new_attr_dict",
"=",
"None",
",",
"all_but_meta",
"=",
"None",
",",
"projected_regs",
"=",
"None",
",",
"new_field_dict",
"=",
"None",
",",
"all_but_regs",
"=",
"None",
")",
":",
"pro... | *Wrapper of* ``PROJECT``
The PROJECT operator creates, from an existing dataset, a new dataset with all the samples
(with their regions and region values) in the input one, but keeping for each sample in the input
dataset only those metadata and/or region attributes expressed in the operator parameter list.
Region coordinates and values of the remaining metadata and region attributes remain equal
to those in the input dataset. Differently from the SELECT operator, PROJECT allows to:
* Remove existing metadata and/or region attributes from a dataset;
* Create new metadata and/or region attributes to be added to the result.
:param projected_meta: list of metadata attributes to project on
:param new_attr_dict: an optional dictionary of the form {'new_meta_1': function1,
'new_meta_2': function2, ...} in which every function computes
the new metadata attribute based on the values of the others
:param all_but_meta: list of metadata attributes that must be excluded from the projection
:param projected_regs: list of the region fields to select
:param new_field_dict: an optional dictionary of the form {'new_field_1':
function1, 'new_field_2': function2, ...} in which every function
computes the new region field based on the values of the others
:param all_but_regs: list of region fields that must be excluded from the projection
:return: a new GMQLDataset | [
"*",
"Wrapper",
"of",
"*",
"PROJECT"
] | train | https://github.com/DEIB-GECO/PyGMQL/blob/e58b2f9402a86056dcda484a32e3de0bb06ed991/gmql/dataset/GMQLDataset.py#L315-L449 |
DEIB-GECO/PyGMQL | gmql/dataset/GMQLDataset.py | GMQLDataset.meta_project | def meta_project(self, attr_list=None, all_but=None, new_attr_dict=None):
"""
*Wrapper of* ``PROJECT``
Project the metadata based on a list of attribute names
:param attr_list: list of the metadata fields to select
:param all_but: list of metadata that must be excluded from the projection.
:param new_attr_dict: an optional dictionary of the form {'new_field_1': function1,
'new_field_2': function2, ...} in which every function computes
the new field based on the values of the others
:return: a new GMQLDataset
Notice that if attr_list is specified, all_but cannot be specified and viceversa.
Examples::
new_dataset = dataset.meta_project(attr_list=['antibody', 'ID'],
new_attr_dict={'new_meta': dataset['ID'] + 100})
"""
return self.project(projected_meta=attr_list, new_attr_dict=new_attr_dict, all_but_meta=all_but) | python | def meta_project(self, attr_list=None, all_but=None, new_attr_dict=None):
"""
*Wrapper of* ``PROJECT``
Project the metadata based on a list of attribute names
:param attr_list: list of the metadata fields to select
:param all_but: list of metadata that must be excluded from the projection.
:param new_attr_dict: an optional dictionary of the form {'new_field_1': function1,
'new_field_2': function2, ...} in which every function computes
the new field based on the values of the others
:return: a new GMQLDataset
Notice that if attr_list is specified, all_but cannot be specified and viceversa.
Examples::
new_dataset = dataset.meta_project(attr_list=['antibody', 'ID'],
new_attr_dict={'new_meta': dataset['ID'] + 100})
"""
return self.project(projected_meta=attr_list, new_attr_dict=new_attr_dict, all_but_meta=all_but) | [
"def",
"meta_project",
"(",
"self",
",",
"attr_list",
"=",
"None",
",",
"all_but",
"=",
"None",
",",
"new_attr_dict",
"=",
"None",
")",
":",
"return",
"self",
".",
"project",
"(",
"projected_meta",
"=",
"attr_list",
",",
"new_attr_dict",
"=",
"new_attr_dict"... | *Wrapper of* ``PROJECT``
Project the metadata based on a list of attribute names
:param attr_list: list of the metadata fields to select
:param all_but: list of metadata that must be excluded from the projection.
:param new_attr_dict: an optional dictionary of the form {'new_field_1': function1,
'new_field_2': function2, ...} in which every function computes
the new field based on the values of the others
:return: a new GMQLDataset
Notice that if attr_list is specified, all_but cannot be specified and viceversa.
Examples::
new_dataset = dataset.meta_project(attr_list=['antibody', 'ID'],
new_attr_dict={'new_meta': dataset['ID'] + 100}) | [
"*",
"Wrapper",
"of",
"*",
"PROJECT"
] | train | https://github.com/DEIB-GECO/PyGMQL/blob/e58b2f9402a86056dcda484a32e3de0bb06ed991/gmql/dataset/GMQLDataset.py#L451-L472 |
DEIB-GECO/PyGMQL | gmql/dataset/GMQLDataset.py | GMQLDataset.reg_project | def reg_project(self, field_list=None, all_but=None, new_field_dict=None):
"""
*Wrapper of* ``PROJECT``
Project the region data based on a list of field names
:param field_list: list of the fields to select
:param all_but: keep only the region fields different from the ones
specified
:param new_field_dict: an optional dictionary of the form {'new_field_1':
function1, 'new_field_2': function2, ...} in which every function
computes the new field based on the values of the others
:return: a new GMQLDataset
An example of usage::
new_dataset = dataset.reg_project(['pValue', 'name'],
{'new_field': dataset.pValue / 2})
new_dataset = dataset.reg_project(field_list=['peak', 'pvalue'],
new_field_dict={'new_field': dataset.pvalue * dataset['cell_age', 'float']})
Notice that you can use metadata attributes for building new region fields.
The only thing to remember when doing so is to define also the type of the output region field
in the metadata attribute definition (for example, :code:`dataset['cell_age', 'float']` is
required for defining the new attribute :code:`new_field` as float).
In particular, the following type names are accepted: 'string', 'char', 'long', 'integer',
'boolean', 'float', 'double'.
"""
return self.project(projected_regs=field_list, all_but_regs=all_but, new_field_dict=new_field_dict) | python | def reg_project(self, field_list=None, all_but=None, new_field_dict=None):
"""
*Wrapper of* ``PROJECT``
Project the region data based on a list of field names
:param field_list: list of the fields to select
:param all_but: keep only the region fields different from the ones
specified
:param new_field_dict: an optional dictionary of the form {'new_field_1':
function1, 'new_field_2': function2, ...} in which every function
computes the new field based on the values of the others
:return: a new GMQLDataset
An example of usage::
new_dataset = dataset.reg_project(['pValue', 'name'],
{'new_field': dataset.pValue / 2})
new_dataset = dataset.reg_project(field_list=['peak', 'pvalue'],
new_field_dict={'new_field': dataset.pvalue * dataset['cell_age', 'float']})
Notice that you can use metadata attributes for building new region fields.
The only thing to remember when doing so is to define also the type of the output region field
in the metadata attribute definition (for example, :code:`dataset['cell_age', 'float']` is
required for defining the new attribute :code:`new_field` as float).
In particular, the following type names are accepted: 'string', 'char', 'long', 'integer',
'boolean', 'float', 'double'.
"""
return self.project(projected_regs=field_list, all_but_regs=all_but, new_field_dict=new_field_dict) | [
"def",
"reg_project",
"(",
"self",
",",
"field_list",
"=",
"None",
",",
"all_but",
"=",
"None",
",",
"new_field_dict",
"=",
"None",
")",
":",
"return",
"self",
".",
"project",
"(",
"projected_regs",
"=",
"field_list",
",",
"all_but_regs",
"=",
"all_but",
"... | *Wrapper of* ``PROJECT``
Project the region data based on a list of field names
:param field_list: list of the fields to select
:param all_but: keep only the region fields different from the ones
specified
:param new_field_dict: an optional dictionary of the form {'new_field_1':
function1, 'new_field_2': function2, ...} in which every function
computes the new field based on the values of the others
:return: a new GMQLDataset
An example of usage::
new_dataset = dataset.reg_project(['pValue', 'name'],
{'new_field': dataset.pValue / 2})
new_dataset = dataset.reg_project(field_list=['peak', 'pvalue'],
new_field_dict={'new_field': dataset.pvalue * dataset['cell_age', 'float']})
Notice that you can use metadata attributes for building new region fields.
The only thing to remember when doing so is to define also the type of the output region field
in the metadata attribute definition (for example, :code:`dataset['cell_age', 'float']` is
required for defining the new attribute :code:`new_field` as float).
In particular, the following type names are accepted: 'string', 'char', 'long', 'integer',
'boolean', 'float', 'double'. | [
"*",
"Wrapper",
"of",
"*",
"PROJECT"
] | train | https://github.com/DEIB-GECO/PyGMQL/blob/e58b2f9402a86056dcda484a32e3de0bb06ed991/gmql/dataset/GMQLDataset.py#L474-L504 |
DEIB-GECO/PyGMQL | gmql/dataset/GMQLDataset.py | GMQLDataset.extend | def extend(self, new_attr_dict):
"""
*Wrapper of* ``EXTEND``
For each sample in an input dataset, the EXTEND operator builds new metadata attributes,
assigns their values as the result of arithmetic and/or aggregate functions calculated on
sample region attributes, and adds them to the existing metadata attribute-value pairs of
the sample. Sample number and their genomic regions, with their attributes and values,
remain unchanged in the output dataset.
:param new_attr_dict: a dictionary of the type {'new_metadata' : AGGREGATE_FUNCTION('field'), ...}
:return: new GMQLDataset
An example of usage, in which we count the number of regions in each sample and the minimum
value of the `pValue` field and export it respectively as metadata attributes `regionCount` and `minPValue`::
import gmql as gl
dataset = gl.get_example_dataset("Example_Dataset_1")
new_dataset = dataset.extend({'regionCount' : gl.COUNT(),
'minPValue' : gl.MIN('pValue')})
"""
if isinstance(new_attr_dict, dict):
expBuild = self.pmg.getNewExpressionBuilder(self.__index)
aggregates = []
for k in new_attr_dict.keys():
if isinstance(k, str):
item = new_attr_dict[k]
if isinstance(item, Aggregate):
op_name = item.get_aggregate_name()
op_argument = Some(item.get_argument()) if item.is_unary() else none()
regsToMeta = expBuild.getRegionsToMeta(op_name, k, op_argument)
aggregates.append(regsToMeta)
else:
raise TypeError("The items in new_reg_fields must be Aggregates."
" {} was provided".format(type(item)))
else:
raise TypeError("The key of new_attr_dict must be a string. "
"{} was provided".format(type(k)))
else:
raise TypeError("new_attr_dict must be a dictionary. "
"{} was provided".format(type(new_attr_dict)))
new_index = self.opmng.extend(self.__index, aggregates)
return GMQLDataset(index=new_index, location=self.location,
local_sources=self._local_sources,
remote_sources=self._remote_sources, meta_profile=self.meta_profile) | python | def extend(self, new_attr_dict):
"""
*Wrapper of* ``EXTEND``
For each sample in an input dataset, the EXTEND operator builds new metadata attributes,
assigns their values as the result of arithmetic and/or aggregate functions calculated on
sample region attributes, and adds them to the existing metadata attribute-value pairs of
the sample. Sample number and their genomic regions, with their attributes and values,
remain unchanged in the output dataset.
:param new_attr_dict: a dictionary of the type {'new_metadata' : AGGREGATE_FUNCTION('field'), ...}
:return: new GMQLDataset
An example of usage, in which we count the number of regions in each sample and the minimum
value of the `pValue` field and export it respectively as metadata attributes `regionCount` and `minPValue`::
import gmql as gl
dataset = gl.get_example_dataset("Example_Dataset_1")
new_dataset = dataset.extend({'regionCount' : gl.COUNT(),
'minPValue' : gl.MIN('pValue')})
"""
if isinstance(new_attr_dict, dict):
expBuild = self.pmg.getNewExpressionBuilder(self.__index)
aggregates = []
for k in new_attr_dict.keys():
if isinstance(k, str):
item = new_attr_dict[k]
if isinstance(item, Aggregate):
op_name = item.get_aggregate_name()
op_argument = Some(item.get_argument()) if item.is_unary() else none()
regsToMeta = expBuild.getRegionsToMeta(op_name, k, op_argument)
aggregates.append(regsToMeta)
else:
raise TypeError("The items in new_reg_fields must be Aggregates."
" {} was provided".format(type(item)))
else:
raise TypeError("The key of new_attr_dict must be a string. "
"{} was provided".format(type(k)))
else:
raise TypeError("new_attr_dict must be a dictionary. "
"{} was provided".format(type(new_attr_dict)))
new_index = self.opmng.extend(self.__index, aggregates)
return GMQLDataset(index=new_index, location=self.location,
local_sources=self._local_sources,
remote_sources=self._remote_sources, meta_profile=self.meta_profile) | [
"def",
"extend",
"(",
"self",
",",
"new_attr_dict",
")",
":",
"if",
"isinstance",
"(",
"new_attr_dict",
",",
"dict",
")",
":",
"expBuild",
"=",
"self",
".",
"pmg",
".",
"getNewExpressionBuilder",
"(",
"self",
".",
"__index",
")",
"aggregates",
"=",
"[",
... | *Wrapper of* ``EXTEND``
For each sample in an input dataset, the EXTEND operator builds new metadata attributes,
assigns their values as the result of arithmetic and/or aggregate functions calculated on
sample region attributes, and adds them to the existing metadata attribute-value pairs of
the sample. Sample number and their genomic regions, with their attributes and values,
remain unchanged in the output dataset.
:param new_attr_dict: a dictionary of the type {'new_metadata' : AGGREGATE_FUNCTION('field'), ...}
:return: new GMQLDataset
An example of usage, in which we count the number of regions in each sample and the minimum
value of the `pValue` field and export it respectively as metadata attributes `regionCount` and `minPValue`::
import gmql as gl
dataset = gl.get_example_dataset("Example_Dataset_1")
new_dataset = dataset.extend({'regionCount' : gl.COUNT(),
'minPValue' : gl.MIN('pValue')}) | [
"*",
"Wrapper",
"of",
"*",
"EXTEND"
] | train | https://github.com/DEIB-GECO/PyGMQL/blob/e58b2f9402a86056dcda484a32e3de0bb06ed991/gmql/dataset/GMQLDataset.py#L506-L552 |
DEIB-GECO/PyGMQL | gmql/dataset/GMQLDataset.py | GMQLDataset.cover | def cover(self, minAcc, maxAcc, groupBy=None, new_reg_fields=None, cover_type="normal"):
"""
*Wrapper of* ``COVER``
COVER is a GMQL operator that takes as input a dataset (of usually,
but not necessarily, multiple samples) and returns another dataset
(with a single sample, if no groupby option is specified) by “collapsing”
the input samples and their regions according to certain rules
specified by the COVER parameters. The attributes of the output regions
are only the region coordinates, plus in case, when aggregate functions
are specified, new attributes with aggregate values over attribute values
of the contributing input regions; output metadata are the union of the
input ones, plus the metadata attributes JaccardIntersect and
JaccardResult, representing global Jaccard Indexes for the considered
dataset, computed as the correspondent region Jaccard Indexes but on
the whole sample regions.
:param cover_type: the kind of cover variant you want ['normal', 'flat', 'summit', 'histogram']
:param minAcc: minimum accumulation value, i.e. the minimum number
of overlapping regions to be considered during COVER execution. It can be any positive
number or the strings {'ALL', 'ANY'}.
:param maxAcc: maximum accumulation value, i.e. the maximum number
of overlapping regions to be considered during COVER execution. It can be any positive
number or the strings {'ALL', 'ANY'}.
:param groupBy: optional list of metadata attributes
:param new_reg_fields: dictionary of the type
{'new_region_attribute' : AGGREGATE_FUNCTION('field'), ...}
:return: a new GMQLDataset
An example of usage::
cell_tf = narrow_peak.cover("normal", minAcc=1, maxAcc="Any",
groupBy=['cell', 'antibody_target'])
"""
if isinstance(cover_type, str):
coverFlag = self.opmng.getCoverTypes(cover_type)
else:
raise TypeError("type must be a string. "
"{} was provided".format(type(cover_type)))
if isinstance(minAcc, str):
minAccParam = self.opmng.getCoverParam(minAcc.lower())
elif isinstance(minAcc, int):
minAccParam = self.opmng.getCoverParam(str(minAcc).lower())
else:
raise TypeError("minAcc must be a string or an integer. "
"{} was provided".format(type(minAcc)))
if isinstance(maxAcc, str):
maxAccParam = self.opmng.getCoverParam(maxAcc.lower())
elif isinstance(maxAcc, int):
maxAccParam = self.opmng.getCoverParam(str(maxAcc).lower())
else:
raise TypeError("maxAcc must be a string or an integer. "
"{} was provided".format(type(minAcc)))
if isinstance(groupBy, list) and \
all([isinstance(x, str) for x in groupBy]):
groupBy_result = Some(groupBy)
elif groupBy is None:
groupBy_result = none()
else:
raise TypeError("groupBy must be a list of string. "
"{} was provided".format(type(groupBy)))
aggregates = []
if isinstance(new_reg_fields, dict):
expBuild = self.pmg.getNewExpressionBuilder(self.__index)
for k in new_reg_fields.keys():
if isinstance(k, str):
item = new_reg_fields[k]
if isinstance(item, (SUM, MIN, MAX, AVG, BAG, BAGD,
MEDIAN, COUNT)):
op_name = item.get_aggregate_name()
op_argument = item.get_argument()
if op_argument is None:
op_argument = none()
else:
op_argument = Some(op_argument)
regsToReg = expBuild.getRegionsToRegion(op_name, k, op_argument)
aggregates.append(regsToReg)
else:
raise TypeError("The items in new_reg_fields must be Aggregates (SUM, MIN, MAX, AVG, BAG, "
"BAGD, MEDIAN, COUNT)"
" {} was provided".format(type(item)))
else:
raise TypeError("The key of new_reg_fields must be a string. "
"{} was provided".format(type(k)))
elif new_reg_fields is None:
pass
else:
raise TypeError("new_reg_fields must be a list of dictionary. "
"{} was provided".format(type(new_reg_fields)))
new_index = self.opmng.cover(self.__index, coverFlag, minAccParam, maxAccParam,
groupBy_result, aggregates)
return GMQLDataset(index=new_index, location=self.location,
local_sources=self._local_sources,
remote_sources=self._remote_sources, meta_profile=self.meta_profile) | python | def cover(self, minAcc, maxAcc, groupBy=None, new_reg_fields=None, cover_type="normal"):
"""
*Wrapper of* ``COVER``
COVER is a GMQL operator that takes as input a dataset (of usually,
but not necessarily, multiple samples) and returns another dataset
(with a single sample, if no groupby option is specified) by “collapsing”
the input samples and their regions according to certain rules
specified by the COVER parameters. The attributes of the output regions
are only the region coordinates, plus in case, when aggregate functions
are specified, new attributes with aggregate values over attribute values
of the contributing input regions; output metadata are the union of the
input ones, plus the metadata attributes JaccardIntersect and
JaccardResult, representing global Jaccard Indexes for the considered
dataset, computed as the correspondent region Jaccard Indexes but on
the whole sample regions.
:param cover_type: the kind of cover variant you want ['normal', 'flat', 'summit', 'histogram']
:param minAcc: minimum accumulation value, i.e. the minimum number
of overlapping regions to be considered during COVER execution. It can be any positive
number or the strings {'ALL', 'ANY'}.
:param maxAcc: maximum accumulation value, i.e. the maximum number
of overlapping regions to be considered during COVER execution. It can be any positive
number or the strings {'ALL', 'ANY'}.
:param groupBy: optional list of metadata attributes
:param new_reg_fields: dictionary of the type
{'new_region_attribute' : AGGREGATE_FUNCTION('field'), ...}
:return: a new GMQLDataset
An example of usage::
cell_tf = narrow_peak.cover("normal", minAcc=1, maxAcc="Any",
groupBy=['cell', 'antibody_target'])
"""
if isinstance(cover_type, str):
coverFlag = self.opmng.getCoverTypes(cover_type)
else:
raise TypeError("type must be a string. "
"{} was provided".format(type(cover_type)))
if isinstance(minAcc, str):
minAccParam = self.opmng.getCoverParam(minAcc.lower())
elif isinstance(minAcc, int):
minAccParam = self.opmng.getCoverParam(str(minAcc).lower())
else:
raise TypeError("minAcc must be a string or an integer. "
"{} was provided".format(type(minAcc)))
if isinstance(maxAcc, str):
maxAccParam = self.opmng.getCoverParam(maxAcc.lower())
elif isinstance(maxAcc, int):
maxAccParam = self.opmng.getCoverParam(str(maxAcc).lower())
else:
raise TypeError("maxAcc must be a string or an integer. "
"{} was provided".format(type(minAcc)))
if isinstance(groupBy, list) and \
all([isinstance(x, str) for x in groupBy]):
groupBy_result = Some(groupBy)
elif groupBy is None:
groupBy_result = none()
else:
raise TypeError("groupBy must be a list of string. "
"{} was provided".format(type(groupBy)))
aggregates = []
if isinstance(new_reg_fields, dict):
expBuild = self.pmg.getNewExpressionBuilder(self.__index)
for k in new_reg_fields.keys():
if isinstance(k, str):
item = new_reg_fields[k]
if isinstance(item, (SUM, MIN, MAX, AVG, BAG, BAGD,
MEDIAN, COUNT)):
op_name = item.get_aggregate_name()
op_argument = item.get_argument()
if op_argument is None:
op_argument = none()
else:
op_argument = Some(op_argument)
regsToReg = expBuild.getRegionsToRegion(op_name, k, op_argument)
aggregates.append(regsToReg)
else:
raise TypeError("The items in new_reg_fields must be Aggregates (SUM, MIN, MAX, AVG, BAG, "
"BAGD, MEDIAN, COUNT)"
" {} was provided".format(type(item)))
else:
raise TypeError("The key of new_reg_fields must be a string. "
"{} was provided".format(type(k)))
elif new_reg_fields is None:
pass
else:
raise TypeError("new_reg_fields must be a list of dictionary. "
"{} was provided".format(type(new_reg_fields)))
new_index = self.opmng.cover(self.__index, coverFlag, minAccParam, maxAccParam,
groupBy_result, aggregates)
return GMQLDataset(index=new_index, location=self.location,
local_sources=self._local_sources,
remote_sources=self._remote_sources, meta_profile=self.meta_profile) | [
"def",
"cover",
"(",
"self",
",",
"minAcc",
",",
"maxAcc",
",",
"groupBy",
"=",
"None",
",",
"new_reg_fields",
"=",
"None",
",",
"cover_type",
"=",
"\"normal\"",
")",
":",
"if",
"isinstance",
"(",
"cover_type",
",",
"str",
")",
":",
"coverFlag",
"=",
"... | *Wrapper of* ``COVER``
COVER is a GMQL operator that takes as input a dataset (of usually,
but not necessarily, multiple samples) and returns another dataset
(with a single sample, if no groupby option is specified) by “collapsing”
the input samples and their regions according to certain rules
specified by the COVER parameters. The attributes of the output regions
are only the region coordinates, plus in case, when aggregate functions
are specified, new attributes with aggregate values over attribute values
of the contributing input regions; output metadata are the union of the
input ones, plus the metadata attributes JaccardIntersect and
JaccardResult, representing global Jaccard Indexes for the considered
dataset, computed as the correspondent region Jaccard Indexes but on
the whole sample regions.
:param cover_type: the kind of cover variant you want ['normal', 'flat', 'summit', 'histogram']
:param minAcc: minimum accumulation value, i.e. the minimum number
of overlapping regions to be considered during COVER execution. It can be any positive
number or the strings {'ALL', 'ANY'}.
:param maxAcc: maximum accumulation value, i.e. the maximum number
of overlapping regions to be considered during COVER execution. It can be any positive
number or the strings {'ALL', 'ANY'}.
:param groupBy: optional list of metadata attributes
:param new_reg_fields: dictionary of the type
{'new_region_attribute' : AGGREGATE_FUNCTION('field'), ...}
:return: a new GMQLDataset
An example of usage::
cell_tf = narrow_peak.cover("normal", minAcc=1, maxAcc="Any",
groupBy=['cell', 'antibody_target']) | [
"*",
"Wrapper",
"of",
"*",
"COVER"
] | train | https://github.com/DEIB-GECO/PyGMQL/blob/e58b2f9402a86056dcda484a32e3de0bb06ed991/gmql/dataset/GMQLDataset.py#L554-L650 |
DEIB-GECO/PyGMQL | gmql/dataset/GMQLDataset.py | GMQLDataset.normal_cover | def normal_cover(self, minAcc, maxAcc, groupBy=None, new_reg_fields=None):
"""
*Wrapper of* ``COVER``
The normal cover operation as described in :meth:`~.cover`.
Equivalent to calling::
dataset.cover("normal", ...)
"""
return self.cover(minAcc, maxAcc, groupBy, new_reg_fields, cover_type="normal") | python | def normal_cover(self, minAcc, maxAcc, groupBy=None, new_reg_fields=None):
"""
*Wrapper of* ``COVER``
The normal cover operation as described in :meth:`~.cover`.
Equivalent to calling::
dataset.cover("normal", ...)
"""
return self.cover(minAcc, maxAcc, groupBy, new_reg_fields, cover_type="normal") | [
"def",
"normal_cover",
"(",
"self",
",",
"minAcc",
",",
"maxAcc",
",",
"groupBy",
"=",
"None",
",",
"new_reg_fields",
"=",
"None",
")",
":",
"return",
"self",
".",
"cover",
"(",
"minAcc",
",",
"maxAcc",
",",
"groupBy",
",",
"new_reg_fields",
",",
"cover_... | *Wrapper of* ``COVER``
The normal cover operation as described in :meth:`~.cover`.
Equivalent to calling::
dataset.cover("normal", ...) | [
"*",
"Wrapper",
"of",
"*",
"COVER"
] | train | https://github.com/DEIB-GECO/PyGMQL/blob/e58b2f9402a86056dcda484a32e3de0bb06ed991/gmql/dataset/GMQLDataset.py#L652-L661 |
DEIB-GECO/PyGMQL | gmql/dataset/GMQLDataset.py | GMQLDataset.flat_cover | def flat_cover(self, minAcc, maxAcc, groupBy=None, new_reg_fields=None):
"""
*Wrapper of* ``COVER``
Variant of the function :meth:`~.cover` that returns the union of all the regions
which contribute to the COVER. More precisely, it returns the contiguous regions
that start from the first end and stop at the last end of the regions which would
contribute to each region of a COVER.
Equivalent to calling::
cover("flat", ...)
"""
return self.cover(minAcc, maxAcc, groupBy, new_reg_fields, cover_type="flat") | python | def flat_cover(self, minAcc, maxAcc, groupBy=None, new_reg_fields=None):
"""
*Wrapper of* ``COVER``
Variant of the function :meth:`~.cover` that returns the union of all the regions
which contribute to the COVER. More precisely, it returns the contiguous regions
that start from the first end and stop at the last end of the regions which would
contribute to each region of a COVER.
Equivalent to calling::
cover("flat", ...)
"""
return self.cover(minAcc, maxAcc, groupBy, new_reg_fields, cover_type="flat") | [
"def",
"flat_cover",
"(",
"self",
",",
"minAcc",
",",
"maxAcc",
",",
"groupBy",
"=",
"None",
",",
"new_reg_fields",
"=",
"None",
")",
":",
"return",
"self",
".",
"cover",
"(",
"minAcc",
",",
"maxAcc",
",",
"groupBy",
",",
"new_reg_fields",
",",
"cover_ty... | *Wrapper of* ``COVER``
Variant of the function :meth:`~.cover` that returns the union of all the regions
which contribute to the COVER. More precisely, it returns the contiguous regions
that start from the first end and stop at the last end of the regions which would
contribute to each region of a COVER.
Equivalent to calling::
cover("flat", ...) | [
"*",
"Wrapper",
"of",
"*",
"COVER"
] | train | https://github.com/DEIB-GECO/PyGMQL/blob/e58b2f9402a86056dcda484a32e3de0bb06ed991/gmql/dataset/GMQLDataset.py#L663-L676 |
DEIB-GECO/PyGMQL | gmql/dataset/GMQLDataset.py | GMQLDataset.summit_cover | def summit_cover(self, minAcc, maxAcc, groupBy=None, new_reg_fields=None):
"""
*Wrapper of* ``COVER``
Variant of the function :meth:`~.cover` that returns only those portions of the COVER
result where the maximum number of regions overlap (this is done by returning only
regions that start from a position after which the number of overlaps does not
increase, and stop at a position where either the number of overlapping regions decreases
or violates the maximum accumulation index).
Equivalent to calling::
cover("summit", ...)
"""
return self.cover(minAcc, maxAcc, groupBy, new_reg_fields, cover_type="summit") | python | def summit_cover(self, minAcc, maxAcc, groupBy=None, new_reg_fields=None):
"""
*Wrapper of* ``COVER``
Variant of the function :meth:`~.cover` that returns only those portions of the COVER
result where the maximum number of regions overlap (this is done by returning only
regions that start from a position after which the number of overlaps does not
increase, and stop at a position where either the number of overlapping regions decreases
or violates the maximum accumulation index).
Equivalent to calling::
cover("summit", ...)
"""
return self.cover(minAcc, maxAcc, groupBy, new_reg_fields, cover_type="summit") | [
"def",
"summit_cover",
"(",
"self",
",",
"minAcc",
",",
"maxAcc",
",",
"groupBy",
"=",
"None",
",",
"new_reg_fields",
"=",
"None",
")",
":",
"return",
"self",
".",
"cover",
"(",
"minAcc",
",",
"maxAcc",
",",
"groupBy",
",",
"new_reg_fields",
",",
"cover_... | *Wrapper of* ``COVER``
Variant of the function :meth:`~.cover` that returns only those portions of the COVER
result where the maximum number of regions overlap (this is done by returning only
regions that start from a position after which the number of overlaps does not
increase, and stop at a position where either the number of overlapping regions decreases
or violates the maximum accumulation index).
Equivalent to calling::
cover("summit", ...) | [
"*",
"Wrapper",
"of",
"*",
"COVER"
] | train | https://github.com/DEIB-GECO/PyGMQL/blob/e58b2f9402a86056dcda484a32e3de0bb06ed991/gmql/dataset/GMQLDataset.py#L678-L692 |
DEIB-GECO/PyGMQL | gmql/dataset/GMQLDataset.py | GMQLDataset.histogram_cover | def histogram_cover(self, minAcc, maxAcc, groupBy=None, new_reg_fields=None):
"""
*Wrapper of* ``COVER``
Variant of the function :meth:`~.cover` that returns all regions contributing to
the COVER divided in different (contiguous) parts according to their accumulation
index value (one part for each different accumulation value), which is assigned to
the AccIndex region attribute.
Equivalent to calling::
cover("histogram", ...)
"""
return self.cover(minAcc, maxAcc, groupBy, new_reg_fields, cover_type="histogram") | python | def histogram_cover(self, minAcc, maxAcc, groupBy=None, new_reg_fields=None):
"""
*Wrapper of* ``COVER``
Variant of the function :meth:`~.cover` that returns all regions contributing to
the COVER divided in different (contiguous) parts according to their accumulation
index value (one part for each different accumulation value), which is assigned to
the AccIndex region attribute.
Equivalent to calling::
cover("histogram", ...)
"""
return self.cover(minAcc, maxAcc, groupBy, new_reg_fields, cover_type="histogram") | [
"def",
"histogram_cover",
"(",
"self",
",",
"minAcc",
",",
"maxAcc",
",",
"groupBy",
"=",
"None",
",",
"new_reg_fields",
"=",
"None",
")",
":",
"return",
"self",
".",
"cover",
"(",
"minAcc",
",",
"maxAcc",
",",
"groupBy",
",",
"new_reg_fields",
",",
"cov... | *Wrapper of* ``COVER``
Variant of the function :meth:`~.cover` that returns all regions contributing to
the COVER divided in different (contiguous) parts according to their accumulation
index value (one part for each different accumulation value), which is assigned to
the AccIndex region attribute.
Equivalent to calling::
cover("histogram", ...) | [
"*",
"Wrapper",
"of",
"*",
"COVER"
] | train | https://github.com/DEIB-GECO/PyGMQL/blob/e58b2f9402a86056dcda484a32e3de0bb06ed991/gmql/dataset/GMQLDataset.py#L694-L707 |
DEIB-GECO/PyGMQL | gmql/dataset/GMQLDataset.py | GMQLDataset.join | def join(self, experiment, genometric_predicate, output="LEFT", joinBy=None,
refName="REF", expName="EXP", left_on=None, right_on=None):
"""
*Wrapper of* ``JOIN``
The JOIN operator takes in input two datasets, respectively known as anchor
(the first/left one) and experiment (the second/right one) and returns a
dataset of samples consisting of regions extracted from the operands
according to the specified condition (known as genometric predicate).
The number of generated output samples is the Cartesian product of the number
of samples in the anchor and in the experiment dataset (if no joinby close
if specified). The attributes (and their values) of the regions in the output
dataset are the union of the region attributes (with their values) in the input
datasets; homonymous attributes are disambiguated by prefixing their name with
their dataset name. The output metadata are the union of the input metadata,
with their attribute names prefixed with their input dataset name.
:param experiment: an other GMQLDataset
:param genometric_predicate: a list of Genometric atomic conditions. For an explanation of each of them
go to the respective page.
:param output: one of four different values that declare which region is given in output
for each input pair of anchor and experiment regions satisfying the genometric predicate:
* 'LEFT': outputs the anchor regions from the anchor dataset that satisfy the genometric predicate
* 'RIGHT': outputs the anchor regions from the experiment dataset that satisfy the genometric predicate
* 'INT': outputs the overlapping part (intersection) of the anchor and experiment regions that satisfy
the genometric predicate; if the intersection is empty, no output is produced
* 'CONTIG': outputs the concatenation between the anchor and experiment regions that satisfy the
genometric predicate, i.e. the output region is defined as having left (right) coordinates
equal to the minimum (maximum) of the corresponding coordinate values in the anchor and
experiment regions satisfying the genometric predicate
:param joinBy: list of metadata attributes
:param refName: name that you want to assign to the reference dataset
:param expName: name that you want to assign to the experiment dataset
:param left_on: list of region fields of the reference on which the join must be performed
:param right_on: list of region fields of the experiment on which the join must be performed
:return: a new GMQLDataset
An example of usage, in which we perform the join operation between Example_Dataset_1 and Example_Dataset_2
specifying than we want to join the regions of the former with the first regions at a minimim distance of 120Kb
of the latter and finally we want to output the regions of Example_Dataset_2 matching the criteria::
import gmql as gl
d1 = gl.get_example_dataset("Example_Dataset_1")
d2 = gl.get_example_dataset("Example_Dataset_2")
result_dataset = d1.join(experiment=d2,
genometric_predicate=[gl.MD(1), gl.DGE(120000)],
output="right")
"""
if isinstance(experiment, GMQLDataset):
other_idx = experiment.__index
else:
raise TypeError("experiment must be a GMQLDataset. "
"{} was provided".format(type(experiment)))
if isinstance(genometric_predicate, list) and \
all([isinstance(x, GenometricCondition) for x in genometric_predicate]):
regionJoinCondition = self.opmng.getRegionJoinCondition(list(map(lambda x: x.get_gen_condition(),
genometric_predicate)))
else:
raise TypeError("genometric_predicate must be a list og GenometricCondition. "
"{} was found".format(type(genometric_predicate)))
if isinstance(output, str):
regionBuilder = self.opmng.getRegionBuilderJoin(output)
else:
raise TypeError("output must be a string. "
"{} was provided".format(type(output)))
if not isinstance(expName, str):
raise TypeError("expName must be a string. {} was provided".format(type(expName)))
if not isinstance(refName, str):
raise TypeError("refName must be a string. {} was provided".format(type(expName)))
if isinstance(joinBy, list) and \
all([isinstance(x, str) for x in joinBy]):
metaJoinCondition = Some(self.opmng.getMetaJoinCondition(joinBy))
elif joinBy is None:
metaJoinCondition = none()
else:
raise TypeError("joinBy must be a list of strings. "
"{} was found".format(type(joinBy)))
left_on_exists = False
left_on_len = 0
if isinstance(left_on, list) and \
all([isinstance(x, str) for x in left_on]):
left_on_len = len(left_on)
left_on = Some(left_on)
left_on_exists = True
elif left_on is None:
left_on = none()
else:
raise TypeError("left_on must be a list of strings. "
"{} was provided".format(type(left_on)))
if isinstance(right_on, list) and \
all([isinstance(x, str)] for x in right_on) and \
left_on_exists and len(right_on) == left_on_len:
right_on = Some(right_on)
elif right_on is None and not left_on_exists:
right_on = none()
else:
raise TypeError("right_on must be a list of strings. "
"{} was provided".format(type(right_on)))
new_index = self.opmng.join(self.__index, other_idx,
metaJoinCondition, regionJoinCondition, regionBuilder,
refName, expName, left_on, right_on)
new_local_sources, new_remote_sources = self.__combine_sources(self, experiment)
new_location = self.__combine_locations(self, experiment)
return GMQLDataset(index=new_index, location=new_location,
local_sources=new_local_sources,
remote_sources=new_remote_sources, meta_profile=self.meta_profile) | python | def join(self, experiment, genometric_predicate, output="LEFT", joinBy=None,
refName="REF", expName="EXP", left_on=None, right_on=None):
"""
*Wrapper of* ``JOIN``
The JOIN operator takes in input two datasets, respectively known as anchor
(the first/left one) and experiment (the second/right one) and returns a
dataset of samples consisting of regions extracted from the operands
according to the specified condition (known as genometric predicate).
The number of generated output samples is the Cartesian product of the number
of samples in the anchor and in the experiment dataset (if no joinby close
if specified). The attributes (and their values) of the regions in the output
dataset are the union of the region attributes (with their values) in the input
datasets; homonymous attributes are disambiguated by prefixing their name with
their dataset name. The output metadata are the union of the input metadata,
with their attribute names prefixed with their input dataset name.
:param experiment: an other GMQLDataset
:param genometric_predicate: a list of Genometric atomic conditions. For an explanation of each of them
go to the respective page.
:param output: one of four different values that declare which region is given in output
for each input pair of anchor and experiment regions satisfying the genometric predicate:
* 'LEFT': outputs the anchor regions from the anchor dataset that satisfy the genometric predicate
* 'RIGHT': outputs the anchor regions from the experiment dataset that satisfy the genometric predicate
* 'INT': outputs the overlapping part (intersection) of the anchor and experiment regions that satisfy
the genometric predicate; if the intersection is empty, no output is produced
* 'CONTIG': outputs the concatenation between the anchor and experiment regions that satisfy the
genometric predicate, i.e. the output region is defined as having left (right) coordinates
equal to the minimum (maximum) of the corresponding coordinate values in the anchor and
experiment regions satisfying the genometric predicate
:param joinBy: list of metadata attributes
:param refName: name that you want to assign to the reference dataset
:param expName: name that you want to assign to the experiment dataset
:param left_on: list of region fields of the reference on which the join must be performed
:param right_on: list of region fields of the experiment on which the join must be performed
:return: a new GMQLDataset
An example of usage, in which we perform the join operation between Example_Dataset_1 and Example_Dataset_2
specifying than we want to join the regions of the former with the first regions at a minimim distance of 120Kb
of the latter and finally we want to output the regions of Example_Dataset_2 matching the criteria::
import gmql as gl
d1 = gl.get_example_dataset("Example_Dataset_1")
d2 = gl.get_example_dataset("Example_Dataset_2")
result_dataset = d1.join(experiment=d2,
genometric_predicate=[gl.MD(1), gl.DGE(120000)],
output="right")
"""
if isinstance(experiment, GMQLDataset):
other_idx = experiment.__index
else:
raise TypeError("experiment must be a GMQLDataset. "
"{} was provided".format(type(experiment)))
if isinstance(genometric_predicate, list) and \
all([isinstance(x, GenometricCondition) for x in genometric_predicate]):
regionJoinCondition = self.opmng.getRegionJoinCondition(list(map(lambda x: x.get_gen_condition(),
genometric_predicate)))
else:
raise TypeError("genometric_predicate must be a list og GenometricCondition. "
"{} was found".format(type(genometric_predicate)))
if isinstance(output, str):
regionBuilder = self.opmng.getRegionBuilderJoin(output)
else:
raise TypeError("output must be a string. "
"{} was provided".format(type(output)))
if not isinstance(expName, str):
raise TypeError("expName must be a string. {} was provided".format(type(expName)))
if not isinstance(refName, str):
raise TypeError("refName must be a string. {} was provided".format(type(expName)))
if isinstance(joinBy, list) and \
all([isinstance(x, str) for x in joinBy]):
metaJoinCondition = Some(self.opmng.getMetaJoinCondition(joinBy))
elif joinBy is None:
metaJoinCondition = none()
else:
raise TypeError("joinBy must be a list of strings. "
"{} was found".format(type(joinBy)))
left_on_exists = False
left_on_len = 0
if isinstance(left_on, list) and \
all([isinstance(x, str) for x in left_on]):
left_on_len = len(left_on)
left_on = Some(left_on)
left_on_exists = True
elif left_on is None:
left_on = none()
else:
raise TypeError("left_on must be a list of strings. "
"{} was provided".format(type(left_on)))
if isinstance(right_on, list) and \
all([isinstance(x, str)] for x in right_on) and \
left_on_exists and len(right_on) == left_on_len:
right_on = Some(right_on)
elif right_on is None and not left_on_exists:
right_on = none()
else:
raise TypeError("right_on must be a list of strings. "
"{} was provided".format(type(right_on)))
new_index = self.opmng.join(self.__index, other_idx,
metaJoinCondition, regionJoinCondition, regionBuilder,
refName, expName, left_on, right_on)
new_local_sources, new_remote_sources = self.__combine_sources(self, experiment)
new_location = self.__combine_locations(self, experiment)
return GMQLDataset(index=new_index, location=new_location,
local_sources=new_local_sources,
remote_sources=new_remote_sources, meta_profile=self.meta_profile) | [
"def",
"join",
"(",
"self",
",",
"experiment",
",",
"genometric_predicate",
",",
"output",
"=",
"\"LEFT\"",
",",
"joinBy",
"=",
"None",
",",
"refName",
"=",
"\"REF\"",
",",
"expName",
"=",
"\"EXP\"",
",",
"left_on",
"=",
"None",
",",
"right_on",
"=",
"No... | *Wrapper of* ``JOIN``
The JOIN operator takes in input two datasets, respectively known as anchor
(the first/left one) and experiment (the second/right one) and returns a
dataset of samples consisting of regions extracted from the operands
according to the specified condition (known as genometric predicate).
The number of generated output samples is the Cartesian product of the number
of samples in the anchor and in the experiment dataset (if no joinby close
if specified). The attributes (and their values) of the regions in the output
dataset are the union of the region attributes (with their values) in the input
datasets; homonymous attributes are disambiguated by prefixing their name with
their dataset name. The output metadata are the union of the input metadata,
with their attribute names prefixed with their input dataset name.
:param experiment: an other GMQLDataset
:param genometric_predicate: a list of Genometric atomic conditions. For an explanation of each of them
go to the respective page.
:param output: one of four different values that declare which region is given in output
for each input pair of anchor and experiment regions satisfying the genometric predicate:
* 'LEFT': outputs the anchor regions from the anchor dataset that satisfy the genometric predicate
* 'RIGHT': outputs the anchor regions from the experiment dataset that satisfy the genometric predicate
* 'INT': outputs the overlapping part (intersection) of the anchor and experiment regions that satisfy
the genometric predicate; if the intersection is empty, no output is produced
* 'CONTIG': outputs the concatenation between the anchor and experiment regions that satisfy the
genometric predicate, i.e. the output region is defined as having left (right) coordinates
equal to the minimum (maximum) of the corresponding coordinate values in the anchor and
experiment regions satisfying the genometric predicate
:param joinBy: list of metadata attributes
:param refName: name that you want to assign to the reference dataset
:param expName: name that you want to assign to the experiment dataset
:param left_on: list of region fields of the reference on which the join must be performed
:param right_on: list of region fields of the experiment on which the join must be performed
:return: a new GMQLDataset
An example of usage, in which we perform the join operation between Example_Dataset_1 and Example_Dataset_2
specifying than we want to join the regions of the former with the first regions at a minimim distance of 120Kb
of the latter and finally we want to output the regions of Example_Dataset_2 matching the criteria::
import gmql as gl
d1 = gl.get_example_dataset("Example_Dataset_1")
d2 = gl.get_example_dataset("Example_Dataset_2")
result_dataset = d1.join(experiment=d2,
genometric_predicate=[gl.MD(1), gl.DGE(120000)],
output="right") | [
"*",
"Wrapper",
"of",
"*",
"JOIN"
] | train | https://github.com/DEIB-GECO/PyGMQL/blob/e58b2f9402a86056dcda484a32e3de0bb06ed991/gmql/dataset/GMQLDataset.py#L709-L827 |
DEIB-GECO/PyGMQL | gmql/dataset/GMQLDataset.py | GMQLDataset.map | def map(self, experiment, new_reg_fields=None, joinBy=None, refName="REF", expName="EXP"):
"""
*Wrapper of* ``MAP``
MAP is a non-symmetric operator over two datasets, respectively called
reference and experiment. The operation computes, for each sample in
the experiment dataset, aggregates over the values of the experiment
regions that intersect with a region in a reference sample, for each
region of each sample in the reference dataset; we say that experiment
regions are mapped to the reference regions.
The number of generated output samples is the Cartesian product of the samples
in the two input datasets; each output sample has the same regions as the related
input reference sample, with their attributes and values, plus the attributes
computed as aggregates over experiment region values. Output sample metadata
are the union of the related input sample metadata, whose attribute names are
prefixed with their input dataset name.
For each reference sample, the MAP operation produces a matrix like structure,
called genomic space, where each experiment sample is associated with a row,
each reference region with a column, and each matrix row is a vector of numbers
- the aggregates computed during MAP execution. When the features of the reference
regions are unknown, the MAP helps in extracting the most interesting regions
out of many candidates.
:param experiment: a GMQLDataset
:param new_reg_fields: an optional dictionary of the form
{'new_field_1': AGGREGATE_FUNCTION(field), ...}
:param joinBy: optional list of metadata
:param refName: name that you want to assign to the reference dataset
:param expName: name that you want to assign to the experiment dataset
:return: a new GMQLDataset
In the following example, we map the regions of Example_Dataset_2 on the ones of Example_Dataset_1 and for
each region of Example_Dataset_1 we ouput the average Pvalue and number of mapped regions of Example_Dataset_2.
In addition we specify that the output region fields and metadata attributes will have the `D1` and `D2` suffixes
respectively for attributes and fields belonging the Example_Dataset_1 and Example_Dataset_2::
import gmql as gl
d1 = gl.get_example_dataset("Example_Dataset_1")
d2 = gl.get_example_dataset("Example_Dataset_2")
result = d1.map(experiment=d2, refName="D1", expName="D2",
new_reg_fields={"avg_pValue": gl.AVG("pvalue")})
"""
if isinstance(experiment, GMQLDataset):
other_idx = experiment.__index
else:
raise TypeError("experiment must be a GMQLDataset. "
"{} was provided".format(type(experiment)))
aggregates = []
if isinstance(new_reg_fields, dict):
expBuild = self.pmg.getNewExpressionBuilder(experiment.__index)
for k in new_reg_fields.keys():
if isinstance(k, str):
item = new_reg_fields[k]
if isinstance(item, (SUM, MIN, MAX, AVG, BAG, BAGD,
MEDIAN, COUNT)):
op_name = item.get_aggregate_name()
op_argument = item.get_argument()
if op_argument is None:
op_argument = none()
else:
op_argument = Some(op_argument)
regsToReg = expBuild.getRegionsToRegion(op_name, k, op_argument)
aggregates.append(regsToReg)
else:
raise TypeError("The items in new_reg_fields must be Aggregates (SUM, MIN, MAX, AVG, BAG, BAGD, "
"MEDIAN, COUNT)"
" {} was provided".format(type(item)))
else:
raise TypeError("The key of new_reg_fields must be a string. "
"{} was provided".format(type(k)))
elif new_reg_fields is None:
pass
else:
raise TypeError("new_reg_fields must be a list of dictionary. "
"{} was provided".format(type(new_reg_fields)))
if isinstance(joinBy, list) and \
all([isinstance(x, str) for x in joinBy]):
metaJoinCondition = Some(self.opmng.getMetaJoinCondition(joinBy))
elif joinBy is None:
metaJoinCondition = none()
else:
raise TypeError("joinBy must be a list of strings. "
"{} was found".format(type(joinBy)))
if not isinstance(expName, str):
raise TypeError("expName must be a string. {} was provided".format(type(expName)))
if not isinstance(refName, str):
raise TypeError("refName must be a string. {} was provided".format(type(expName)))
new_index = self.opmng.map(self.__index, other_idx, metaJoinCondition,
aggregates, refName, expName)
new_local_sources, new_remote_sources = self.__combine_sources(self, experiment)
new_location = self.__combine_locations(self, experiment)
return GMQLDataset(index=new_index, location=new_location,
local_sources=new_local_sources,
remote_sources=new_remote_sources,
meta_profile=self.meta_profile) | python | def map(self, experiment, new_reg_fields=None, joinBy=None, refName="REF", expName="EXP"):
"""
*Wrapper of* ``MAP``
MAP is a non-symmetric operator over two datasets, respectively called
reference and experiment. The operation computes, for each sample in
the experiment dataset, aggregates over the values of the experiment
regions that intersect with a region in a reference sample, for each
region of each sample in the reference dataset; we say that experiment
regions are mapped to the reference regions.
The number of generated output samples is the Cartesian product of the samples
in the two input datasets; each output sample has the same regions as the related
input reference sample, with their attributes and values, plus the attributes
computed as aggregates over experiment region values. Output sample metadata
are the union of the related input sample metadata, whose attribute names are
prefixed with their input dataset name.
For each reference sample, the MAP operation produces a matrix like structure,
called genomic space, where each experiment sample is associated with a row,
each reference region with a column, and each matrix row is a vector of numbers
- the aggregates computed during MAP execution. When the features of the reference
regions are unknown, the MAP helps in extracting the most interesting regions
out of many candidates.
:param experiment: a GMQLDataset
:param new_reg_fields: an optional dictionary of the form
{'new_field_1': AGGREGATE_FUNCTION(field), ...}
:param joinBy: optional list of metadata
:param refName: name that you want to assign to the reference dataset
:param expName: name that you want to assign to the experiment dataset
:return: a new GMQLDataset
In the following example, we map the regions of Example_Dataset_2 on the ones of Example_Dataset_1 and for
each region of Example_Dataset_1 we ouput the average Pvalue and number of mapped regions of Example_Dataset_2.
In addition we specify that the output region fields and metadata attributes will have the `D1` and `D2` suffixes
respectively for attributes and fields belonging the Example_Dataset_1 and Example_Dataset_2::
import gmql as gl
d1 = gl.get_example_dataset("Example_Dataset_1")
d2 = gl.get_example_dataset("Example_Dataset_2")
result = d1.map(experiment=d2, refName="D1", expName="D2",
new_reg_fields={"avg_pValue": gl.AVG("pvalue")})
"""
if isinstance(experiment, GMQLDataset):
other_idx = experiment.__index
else:
raise TypeError("experiment must be a GMQLDataset. "
"{} was provided".format(type(experiment)))
aggregates = []
if isinstance(new_reg_fields, dict):
expBuild = self.pmg.getNewExpressionBuilder(experiment.__index)
for k in new_reg_fields.keys():
if isinstance(k, str):
item = new_reg_fields[k]
if isinstance(item, (SUM, MIN, MAX, AVG, BAG, BAGD,
MEDIAN, COUNT)):
op_name = item.get_aggregate_name()
op_argument = item.get_argument()
if op_argument is None:
op_argument = none()
else:
op_argument = Some(op_argument)
regsToReg = expBuild.getRegionsToRegion(op_name, k, op_argument)
aggregates.append(regsToReg)
else:
raise TypeError("The items in new_reg_fields must be Aggregates (SUM, MIN, MAX, AVG, BAG, BAGD, "
"MEDIAN, COUNT)"
" {} was provided".format(type(item)))
else:
raise TypeError("The key of new_reg_fields must be a string. "
"{} was provided".format(type(k)))
elif new_reg_fields is None:
pass
else:
raise TypeError("new_reg_fields must be a list of dictionary. "
"{} was provided".format(type(new_reg_fields)))
if isinstance(joinBy, list) and \
all([isinstance(x, str) for x in joinBy]):
metaJoinCondition = Some(self.opmng.getMetaJoinCondition(joinBy))
elif joinBy is None:
metaJoinCondition = none()
else:
raise TypeError("joinBy must be a list of strings. "
"{} was found".format(type(joinBy)))
if not isinstance(expName, str):
raise TypeError("expName must be a string. {} was provided".format(type(expName)))
if not isinstance(refName, str):
raise TypeError("refName must be a string. {} was provided".format(type(expName)))
new_index = self.opmng.map(self.__index, other_idx, metaJoinCondition,
aggregates, refName, expName)
new_local_sources, new_remote_sources = self.__combine_sources(self, experiment)
new_location = self.__combine_locations(self, experiment)
return GMQLDataset(index=new_index, location=new_location,
local_sources=new_local_sources,
remote_sources=new_remote_sources,
meta_profile=self.meta_profile) | [
"def",
"map",
"(",
"self",
",",
"experiment",
",",
"new_reg_fields",
"=",
"None",
",",
"joinBy",
"=",
"None",
",",
"refName",
"=",
"\"REF\"",
",",
"expName",
"=",
"\"EXP\"",
")",
":",
"if",
"isinstance",
"(",
"experiment",
",",
"GMQLDataset",
")",
":",
... | *Wrapper of* ``MAP``
MAP is a non-symmetric operator over two datasets, respectively called
reference and experiment. The operation computes, for each sample in
the experiment dataset, aggregates over the values of the experiment
regions that intersect with a region in a reference sample, for each
region of each sample in the reference dataset; we say that experiment
regions are mapped to the reference regions.
The number of generated output samples is the Cartesian product of the samples
in the two input datasets; each output sample has the same regions as the related
input reference sample, with their attributes and values, plus the attributes
computed as aggregates over experiment region values. Output sample metadata
are the union of the related input sample metadata, whose attribute names are
prefixed with their input dataset name.
For each reference sample, the MAP operation produces a matrix like structure,
called genomic space, where each experiment sample is associated with a row,
each reference region with a column, and each matrix row is a vector of numbers
- the aggregates computed during MAP execution. When the features of the reference
regions are unknown, the MAP helps in extracting the most interesting regions
out of many candidates.
:param experiment: a GMQLDataset
:param new_reg_fields: an optional dictionary of the form
{'new_field_1': AGGREGATE_FUNCTION(field), ...}
:param joinBy: optional list of metadata
:param refName: name that you want to assign to the reference dataset
:param expName: name that you want to assign to the experiment dataset
:return: a new GMQLDataset
In the following example, we map the regions of Example_Dataset_2 on the ones of Example_Dataset_1 and for
each region of Example_Dataset_1 we ouput the average Pvalue and number of mapped regions of Example_Dataset_2.
In addition we specify that the output region fields and metadata attributes will have the `D1` and `D2` suffixes
respectively for attributes and fields belonging the Example_Dataset_1 and Example_Dataset_2::
import gmql as gl
d1 = gl.get_example_dataset("Example_Dataset_1")
d2 = gl.get_example_dataset("Example_Dataset_2")
result = d1.map(experiment=d2, refName="D1", expName="D2",
new_reg_fields={"avg_pValue": gl.AVG("pvalue")}) | [
"*",
"Wrapper",
"of",
"*",
"MAP"
] | train | https://github.com/DEIB-GECO/PyGMQL/blob/e58b2f9402a86056dcda484a32e3de0bb06ed991/gmql/dataset/GMQLDataset.py#L829-L932 |
DEIB-GECO/PyGMQL | gmql/dataset/GMQLDataset.py | GMQLDataset.order | def order(self, meta=None, meta_ascending=None, meta_top=None, meta_k=None,
regs=None, regs_ascending=None, region_top=None, region_k=None):
"""
*Wrapper of* ``ORDER``
The ORDER operator is used to order either samples, sample regions, or both,
in a dataset according to a set of metadata and/or region attributes, and/or
region coordinates. The number of samples and their regions in the output dataset
is as in the input dataset, as well as their metadata and region attributes
and values, but a new ordering metadata and/or region attribute is added with
the sample or region ordering value, respectively.
:param meta: list of metadata attributes
:param meta_ascending: list of boolean values (True = ascending, False = descending)
:param meta_top: "top", "topq" or "topp" or None
:param meta_k: a number specifying how many results to be retained
:param regs: list of region attributes
:param regs_ascending: list of boolean values (True = ascending, False = descending)
:param region_top: "top", "topq" or "topp" or None
:param region_k: a number specifying how many results to be retained
:return: a new GMQLDataset
Example of usage. We order Example_Dataset_1 metadata by ascending `antibody` and descending `antibody_class`
keeping only the first sample. We also order the resulting regions based on the `score` field in descending
order, keeping only the first one also in this case::
import gmql as gl
d1 = gl.get_example_dataset("Example_Dataset_1")
result = d1.order(meta=["antibody", "antibody_targetClass"],
meta_ascending=[True, False], meta_top="top", meta_k=1,
regs=['score'], regs_ascending=[False],
region_top="top", region_k=1)
"""
meta_exists = False
meta_len = 0
if isinstance(meta, list) and \
all([isinstance(x, str) for x in meta]):
meta_exists = True
meta_len = len(meta)
meta = Some(meta)
elif meta is None:
meta = none()
else:
raise TypeError("meta must be a list of strings. "
"{} was provided".format(type(meta)))
if isinstance(meta_ascending, list) and \
all([isinstance(x, bool) for x in meta_ascending]) and \
meta_exists and meta_len == len(meta_ascending):
meta_ascending = Some(meta_ascending)
elif meta_ascending is None:
if meta_exists:
# by default meta_ascending is all True
meta_ascending = Some([True for _ in range(meta_len)])
else:
meta_ascending = none()
else:
raise TypeError("meta ascending must be a list of booleans having the same size "
"of meta. {} was provided".format(type(meta_ascending)))
regs_exists = False
regs_len = 0
if isinstance(regs, list) and \
all([isinstance(x, str) for x in regs]):
regs_exists = True
regs_len = len(regs)
regs = Some(regs)
elif regs is None:
regs = none()
else:
raise TypeError("regs must be a list of strings. "
"{} was provided".format(type(regs)))
if isinstance(regs_ascending, list) and \
all([isinstance(x, bool) for x in regs_ascending]) and \
regs_exists and regs_len == len(regs_ascending):
regs_ascending = Some(regs_ascending)
elif regs_ascending is None:
if regs_exists:
# by default regs_ascending is all True
regs_ascending = Some([True for _ in range(regs_len)])
else:
regs_ascending = none()
else:
raise TypeError("meta regs_ascending must be a list of booleans having the same size "
"of regs. {} was provided".format(type(regs_ascending)))
meta_top_exists = False
if isinstance(meta_top, str):
if meta_exists:
meta_top = Some(meta_top)
meta_top_exists = True
else:
raise ValueError("meta_top must be defined only when meta is defined")
elif meta_top is None:
meta_top = none()
else:
raise TypeError("meta_top must be a string. {} was provided".format(type(meta_top)))
if isinstance(meta_k, int) and \
meta_top_exists:
meta_k = Some(meta_k)
elif meta_k is None and \
not meta_top_exists:
meta_k = none()
else:
raise TypeError("meta_k must be an integer and should be provided together with a "
"value of meta_top. {} was provided".format(type(meta_k)))
region_top_exists = False
if isinstance(region_top, str):
if regs_exists:
region_top = Some(region_top)
region_top_exists = True
else:
raise ValueError("region_top must be defined only when regs is defined")
elif region_top is None:
region_top = none()
else:
raise TypeError("region_top must be a string. {} was provided".format(type(region_top)))
if isinstance(region_k, int) and \
region_top_exists:
region_k = Some(region_k)
elif region_k is None and \
not region_top_exists:
region_k = none()
else:
raise TypeError("region_k must be an integer and should be provided together with a "
"value of region_top. {} was provided".format(type(region_k)))
new_index = self.opmng.order(self.__index, meta, meta_ascending, meta_top, meta_k,
regs, regs_ascending, region_top, region_k)
return GMQLDataset(index=new_index, location=self.location,
local_sources=self._local_sources,
remote_sources=self._remote_sources,
meta_profile=self.meta_profile) | python | def order(self, meta=None, meta_ascending=None, meta_top=None, meta_k=None,
regs=None, regs_ascending=None, region_top=None, region_k=None):
"""
*Wrapper of* ``ORDER``
The ORDER operator is used to order either samples, sample regions, or both,
in a dataset according to a set of metadata and/or region attributes, and/or
region coordinates. The number of samples and their regions in the output dataset
is as in the input dataset, as well as their metadata and region attributes
and values, but a new ordering metadata and/or region attribute is added with
the sample or region ordering value, respectively.
:param meta: list of metadata attributes
:param meta_ascending: list of boolean values (True = ascending, False = descending)
:param meta_top: "top", "topq" or "topp" or None
:param meta_k: a number specifying how many results to be retained
:param regs: list of region attributes
:param regs_ascending: list of boolean values (True = ascending, False = descending)
:param region_top: "top", "topq" or "topp" or None
:param region_k: a number specifying how many results to be retained
:return: a new GMQLDataset
Example of usage. We order Example_Dataset_1 metadata by ascending `antibody` and descending `antibody_class`
keeping only the first sample. We also order the resulting regions based on the `score` field in descending
order, keeping only the first one also in this case::
import gmql as gl
d1 = gl.get_example_dataset("Example_Dataset_1")
result = d1.order(meta=["antibody", "antibody_targetClass"],
meta_ascending=[True, False], meta_top="top", meta_k=1,
regs=['score'], regs_ascending=[False],
region_top="top", region_k=1)
"""
meta_exists = False
meta_len = 0
if isinstance(meta, list) and \
all([isinstance(x, str) for x in meta]):
meta_exists = True
meta_len = len(meta)
meta = Some(meta)
elif meta is None:
meta = none()
else:
raise TypeError("meta must be a list of strings. "
"{} was provided".format(type(meta)))
if isinstance(meta_ascending, list) and \
all([isinstance(x, bool) for x in meta_ascending]) and \
meta_exists and meta_len == len(meta_ascending):
meta_ascending = Some(meta_ascending)
elif meta_ascending is None:
if meta_exists:
# by default meta_ascending is all True
meta_ascending = Some([True for _ in range(meta_len)])
else:
meta_ascending = none()
else:
raise TypeError("meta ascending must be a list of booleans having the same size "
"of meta. {} was provided".format(type(meta_ascending)))
regs_exists = False
regs_len = 0
if isinstance(regs, list) and \
all([isinstance(x, str) for x in regs]):
regs_exists = True
regs_len = len(regs)
regs = Some(regs)
elif regs is None:
regs = none()
else:
raise TypeError("regs must be a list of strings. "
"{} was provided".format(type(regs)))
if isinstance(regs_ascending, list) and \
all([isinstance(x, bool) for x in regs_ascending]) and \
regs_exists and regs_len == len(regs_ascending):
regs_ascending = Some(regs_ascending)
elif regs_ascending is None:
if regs_exists:
# by default regs_ascending is all True
regs_ascending = Some([True for _ in range(regs_len)])
else:
regs_ascending = none()
else:
raise TypeError("meta regs_ascending must be a list of booleans having the same size "
"of regs. {} was provided".format(type(regs_ascending)))
meta_top_exists = False
if isinstance(meta_top, str):
if meta_exists:
meta_top = Some(meta_top)
meta_top_exists = True
else:
raise ValueError("meta_top must be defined only when meta is defined")
elif meta_top is None:
meta_top = none()
else:
raise TypeError("meta_top must be a string. {} was provided".format(type(meta_top)))
if isinstance(meta_k, int) and \
meta_top_exists:
meta_k = Some(meta_k)
elif meta_k is None and \
not meta_top_exists:
meta_k = none()
else:
raise TypeError("meta_k must be an integer and should be provided together with a "
"value of meta_top. {} was provided".format(type(meta_k)))
region_top_exists = False
if isinstance(region_top, str):
if regs_exists:
region_top = Some(region_top)
region_top_exists = True
else:
raise ValueError("region_top must be defined only when regs is defined")
elif region_top is None:
region_top = none()
else:
raise TypeError("region_top must be a string. {} was provided".format(type(region_top)))
if isinstance(region_k, int) and \
region_top_exists:
region_k = Some(region_k)
elif region_k is None and \
not region_top_exists:
region_k = none()
else:
raise TypeError("region_k must be an integer and should be provided together with a "
"value of region_top. {} was provided".format(type(region_k)))
new_index = self.opmng.order(self.__index, meta, meta_ascending, meta_top, meta_k,
regs, regs_ascending, region_top, region_k)
return GMQLDataset(index=new_index, location=self.location,
local_sources=self._local_sources,
remote_sources=self._remote_sources,
meta_profile=self.meta_profile) | [
"def",
"order",
"(",
"self",
",",
"meta",
"=",
"None",
",",
"meta_ascending",
"=",
"None",
",",
"meta_top",
"=",
"None",
",",
"meta_k",
"=",
"None",
",",
"regs",
"=",
"None",
",",
"regs_ascending",
"=",
"None",
",",
"region_top",
"=",
"None",
",",
"r... | *Wrapper of* ``ORDER``
The ORDER operator is used to order either samples, sample regions, or both,
in a dataset according to a set of metadata and/or region attributes, and/or
region coordinates. The number of samples and their regions in the output dataset
is as in the input dataset, as well as their metadata and region attributes
and values, but a new ordering metadata and/or region attribute is added with
the sample or region ordering value, respectively.
:param meta: list of metadata attributes
:param meta_ascending: list of boolean values (True = ascending, False = descending)
:param meta_top: "top", "topq" or "topp" or None
:param meta_k: a number specifying how many results to be retained
:param regs: list of region attributes
:param regs_ascending: list of boolean values (True = ascending, False = descending)
:param region_top: "top", "topq" or "topp" or None
:param region_k: a number specifying how many results to be retained
:return: a new GMQLDataset
Example of usage. We order Example_Dataset_1 metadata by ascending `antibody` and descending `antibody_class`
keeping only the first sample. We also order the resulting regions based on the `score` field in descending
order, keeping only the first one also in this case::
import gmql as gl
d1 = gl.get_example_dataset("Example_Dataset_1")
result = d1.order(meta=["antibody", "antibody_targetClass"],
meta_ascending=[True, False], meta_top="top", meta_k=1,
regs=['score'], regs_ascending=[False],
region_top="top", region_k=1) | [
"*",
"Wrapper",
"of",
"*",
"ORDER"
] | train | https://github.com/DEIB-GECO/PyGMQL/blob/e58b2f9402a86056dcda484a32e3de0bb06ed991/gmql/dataset/GMQLDataset.py#L934-L1073 |
DEIB-GECO/PyGMQL | gmql/dataset/GMQLDataset.py | GMQLDataset.difference | def difference(self, other, joinBy=None, exact=False):
"""
*Wrapper of* ``DIFFERENCE``
DIFFERENCE is a binary, non-symmetric operator that produces one sample
in the result for each sample of the first operand, by keeping the same
metadata of the first operand sample and only those regions (with their
schema and values) of the first operand sample which do not intersect with
any region in the second operand sample (also known as negative regions)
:param other: GMQLDataset
:param joinBy: (optional) list of metadata attributes. It is used to extract subsets of samples on which
to apply the operator: only those samples in the current and other dataset that have the same
value for each specified attribute are considered when performing the operation
:param exact: boolean. If true, the the regions are considered as intersecting only if their coordinates
are exactly the same
:return: a new GMQLDataset
Example of usage. We compute the exact difference between Example_Dataset_1 and Example_Dataset_2,
considering only the samples with same `antibody`::
import gmql as gl
d1 = gl.get_example_dataset("Example_Dataset_1")
d2 = gl.get_example_dataset("Example_Dataset_2")
result = d1.difference(other=d2, exact=True, joinBy=['antibody'])
"""
if isinstance(other, GMQLDataset):
other_idx = other.__index
else:
raise TypeError("other must be a GMQLDataset. "
"{} was provided".format(type(other)))
if isinstance(joinBy, list) and \
all([isinstance(x, str) for x in joinBy]):
metaJoinCondition = Some(self.opmng.getMetaJoinCondition(joinBy))
elif joinBy is None:
metaJoinCondition = none()
else:
raise TypeError("joinBy must be a list of strings. "
"{} was provided".format(type(joinBy)))
if not isinstance(exact, bool):
raise TypeError("exact must be a boolean. "
"{} was provided".format(type(exact)))
new_index = self.opmng.difference(self.__index, other_idx, metaJoinCondition, exact)
new_local_sources, new_remote_sources = self.__combine_sources(self, other)
new_location = self.__combine_locations(self, other)
return GMQLDataset(index=new_index, location=new_location,
local_sources=new_local_sources,
remote_sources=new_remote_sources,
meta_profile=self.meta_profile) | python | def difference(self, other, joinBy=None, exact=False):
"""
*Wrapper of* ``DIFFERENCE``
DIFFERENCE is a binary, non-symmetric operator that produces one sample
in the result for each sample of the first operand, by keeping the same
metadata of the first operand sample and only those regions (with their
schema and values) of the first operand sample which do not intersect with
any region in the second operand sample (also known as negative regions)
:param other: GMQLDataset
:param joinBy: (optional) list of metadata attributes. It is used to extract subsets of samples on which
to apply the operator: only those samples in the current and other dataset that have the same
value for each specified attribute are considered when performing the operation
:param exact: boolean. If true, the the regions are considered as intersecting only if their coordinates
are exactly the same
:return: a new GMQLDataset
Example of usage. We compute the exact difference between Example_Dataset_1 and Example_Dataset_2,
considering only the samples with same `antibody`::
import gmql as gl
d1 = gl.get_example_dataset("Example_Dataset_1")
d2 = gl.get_example_dataset("Example_Dataset_2")
result = d1.difference(other=d2, exact=True, joinBy=['antibody'])
"""
if isinstance(other, GMQLDataset):
other_idx = other.__index
else:
raise TypeError("other must be a GMQLDataset. "
"{} was provided".format(type(other)))
if isinstance(joinBy, list) and \
all([isinstance(x, str) for x in joinBy]):
metaJoinCondition = Some(self.opmng.getMetaJoinCondition(joinBy))
elif joinBy is None:
metaJoinCondition = none()
else:
raise TypeError("joinBy must be a list of strings. "
"{} was provided".format(type(joinBy)))
if not isinstance(exact, bool):
raise TypeError("exact must be a boolean. "
"{} was provided".format(type(exact)))
new_index = self.opmng.difference(self.__index, other_idx, metaJoinCondition, exact)
new_local_sources, new_remote_sources = self.__combine_sources(self, other)
new_location = self.__combine_locations(self, other)
return GMQLDataset(index=new_index, location=new_location,
local_sources=new_local_sources,
remote_sources=new_remote_sources,
meta_profile=self.meta_profile) | [
"def",
"difference",
"(",
"self",
",",
"other",
",",
"joinBy",
"=",
"None",
",",
"exact",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"GMQLDataset",
")",
":",
"other_idx",
"=",
"other",
".",
"__index",
"else",
":",
"raise",
"TypeErro... | *Wrapper of* ``DIFFERENCE``
DIFFERENCE is a binary, non-symmetric operator that produces one sample
in the result for each sample of the first operand, by keeping the same
metadata of the first operand sample and only those regions (with their
schema and values) of the first operand sample which do not intersect with
any region in the second operand sample (also known as negative regions)
:param other: GMQLDataset
:param joinBy: (optional) list of metadata attributes. It is used to extract subsets of samples on which
to apply the operator: only those samples in the current and other dataset that have the same
value for each specified attribute are considered when performing the operation
:param exact: boolean. If true, the the regions are considered as intersecting only if their coordinates
are exactly the same
:return: a new GMQLDataset
Example of usage. We compute the exact difference between Example_Dataset_1 and Example_Dataset_2,
considering only the samples with same `antibody`::
import gmql as gl
d1 = gl.get_example_dataset("Example_Dataset_1")
d2 = gl.get_example_dataset("Example_Dataset_2")
result = d1.difference(other=d2, exact=True, joinBy=['antibody']) | [
"*",
"Wrapper",
"of",
"*",
"DIFFERENCE"
] | train | https://github.com/DEIB-GECO/PyGMQL/blob/e58b2f9402a86056dcda484a32e3de0bb06ed991/gmql/dataset/GMQLDataset.py#L1075-L1131 |
DEIB-GECO/PyGMQL | gmql/dataset/GMQLDataset.py | GMQLDataset.union | def union(self, other, left_name="LEFT", right_name="RIGHT"):
"""
*Wrapper of* ``UNION``
The UNION operation is used to integrate homogeneous or heterogeneous samples of two
datasets within a single dataset; for each sample of either one of the input datasets, a
sample is created in the result as follows:
* its metadata are the same as in the original sample;
* its schema is the schema of the first (left) input dataset; new
identifiers are assigned to each output sample;
* its regions are the same (in coordinates and attribute values) as in the original
sample. Region attributes which are missing in an input dataset sample
(w.r.t. the merged schema) are set to null.
:param other: a GMQLDataset
:param left_name: name that you want to assign to the left dataset
:param right_name: name tha t you want to assign to the right dataset
:return: a new GMQLDataset
Example of usage::
import gmql as gl
d1 = gl.get_example_dataset("Example_Dataset_1")
d2 = gl.get_example_dataset("Example_Dataset_2")
result = d1.union(other=d2, left_name="D1", right_name="D2")
"""
if not isinstance(left_name, str) or \
not isinstance(right_name, str):
raise TypeError("left_name and right_name must be strings. "
"{} - {} was provided".format(type(left_name), type(right_name)))
if isinstance(other, GMQLDataset):
other_idx = other.__index
else:
raise TypeError("other must be a GMQLDataset. "
"{} was provided".format(type(other)))
if len(left_name) == 0 or len(right_name) == 0:
raise ValueError("left_name and right_name must not be empty")
new_index = self.opmng.union(self.__index, other_idx, left_name, right_name)
new_local_sources, new_remote_sources = self.__combine_sources(self, other)
new_location = self.__combine_locations(self, other)
return GMQLDataset(index=new_index, location=new_location,
local_sources=new_local_sources,
remote_sources=new_remote_sources,
meta_profile=self.meta_profile) | python | def union(self, other, left_name="LEFT", right_name="RIGHT"):
"""
*Wrapper of* ``UNION``
The UNION operation is used to integrate homogeneous or heterogeneous samples of two
datasets within a single dataset; for each sample of either one of the input datasets, a
sample is created in the result as follows:
* its metadata are the same as in the original sample;
* its schema is the schema of the first (left) input dataset; new
identifiers are assigned to each output sample;
* its regions are the same (in coordinates and attribute values) as in the original
sample. Region attributes which are missing in an input dataset sample
(w.r.t. the merged schema) are set to null.
:param other: a GMQLDataset
:param left_name: name that you want to assign to the left dataset
:param right_name: name tha t you want to assign to the right dataset
:return: a new GMQLDataset
Example of usage::
import gmql as gl
d1 = gl.get_example_dataset("Example_Dataset_1")
d2 = gl.get_example_dataset("Example_Dataset_2")
result = d1.union(other=d2, left_name="D1", right_name="D2")
"""
if not isinstance(left_name, str) or \
not isinstance(right_name, str):
raise TypeError("left_name and right_name must be strings. "
"{} - {} was provided".format(type(left_name), type(right_name)))
if isinstance(other, GMQLDataset):
other_idx = other.__index
else:
raise TypeError("other must be a GMQLDataset. "
"{} was provided".format(type(other)))
if len(left_name) == 0 or len(right_name) == 0:
raise ValueError("left_name and right_name must not be empty")
new_index = self.opmng.union(self.__index, other_idx, left_name, right_name)
new_local_sources, new_remote_sources = self.__combine_sources(self, other)
new_location = self.__combine_locations(self, other)
return GMQLDataset(index=new_index, location=new_location,
local_sources=new_local_sources,
remote_sources=new_remote_sources,
meta_profile=self.meta_profile) | [
"def",
"union",
"(",
"self",
",",
"other",
",",
"left_name",
"=",
"\"LEFT\"",
",",
"right_name",
"=",
"\"RIGHT\"",
")",
":",
"if",
"not",
"isinstance",
"(",
"left_name",
",",
"str",
")",
"or",
"not",
"isinstance",
"(",
"right_name",
",",
"str",
")",
":... | *Wrapper of* ``UNION``
The UNION operation is used to integrate homogeneous or heterogeneous samples of two
datasets within a single dataset; for each sample of either one of the input datasets, a
sample is created in the result as follows:
* its metadata are the same as in the original sample;
* its schema is the schema of the first (left) input dataset; new
identifiers are assigned to each output sample;
* its regions are the same (in coordinates and attribute values) as in the original
sample. Region attributes which are missing in an input dataset sample
(w.r.t. the merged schema) are set to null.
:param other: a GMQLDataset
:param left_name: name that you want to assign to the left dataset
:param right_name: name tha t you want to assign to the right dataset
:return: a new GMQLDataset
Example of usage::
import gmql as gl
d1 = gl.get_example_dataset("Example_Dataset_1")
d2 = gl.get_example_dataset("Example_Dataset_2")
result = d1.union(other=d2, left_name="D1", right_name="D2") | [
"*",
"Wrapper",
"of",
"*",
"UNION"
] | train | https://github.com/DEIB-GECO/PyGMQL/blob/e58b2f9402a86056dcda484a32e3de0bb06ed991/gmql/dataset/GMQLDataset.py#L1133-L1182 |
DEIB-GECO/PyGMQL | gmql/dataset/GMQLDataset.py | GMQLDataset.merge | def merge(self, groupBy=None):
"""
*Wrapper of* ``MERGE``
The MERGE operator builds a new dataset consisting of a single sample having
* as regions all the regions of all the input samples, with the
same attributes and values
* as metadata the union of all the metadata attribute-values
of the input samples.
A groupby clause can be specified on metadata: the samples are then
partitioned in groups, each with a distinct value of the grouping metadata
attributes, and the MERGE operation is applied to each group separately,
yielding to one sample in the result dataset for each group.
Samples without the grouping metadata attributes are disregarded
:param groupBy: list of metadata attributes
:return: a new GMQLDataset
Example of usage::
import gmql as gl
d1 = gl.get_example_dataset("Example_Dataset_1")
result = d1.merge(['antibody'])
"""
if isinstance(groupBy, list) and \
all([isinstance(x, str) for x in groupBy]):
groupBy = Some(groupBy)
elif groupBy is None:
groupBy = none()
else:
raise TypeError("groupBy must be a list of strings. "
"{} was provided".format(type(groupBy)))
new_index = self.opmng.merge(self.__index, groupBy)
return GMQLDataset(index=new_index, location=self.location,
local_sources=self._local_sources,
remote_sources=self._remote_sources,
meta_profile=self.meta_profile) | python | def merge(self, groupBy=None):
"""
*Wrapper of* ``MERGE``
The MERGE operator builds a new dataset consisting of a single sample having
* as regions all the regions of all the input samples, with the
same attributes and values
* as metadata the union of all the metadata attribute-values
of the input samples.
A groupby clause can be specified on metadata: the samples are then
partitioned in groups, each with a distinct value of the grouping metadata
attributes, and the MERGE operation is applied to each group separately,
yielding to one sample in the result dataset for each group.
Samples without the grouping metadata attributes are disregarded
:param groupBy: list of metadata attributes
:return: a new GMQLDataset
Example of usage::
import gmql as gl
d1 = gl.get_example_dataset("Example_Dataset_1")
result = d1.merge(['antibody'])
"""
if isinstance(groupBy, list) and \
all([isinstance(x, str) for x in groupBy]):
groupBy = Some(groupBy)
elif groupBy is None:
groupBy = none()
else:
raise TypeError("groupBy must be a list of strings. "
"{} was provided".format(type(groupBy)))
new_index = self.opmng.merge(self.__index, groupBy)
return GMQLDataset(index=new_index, location=self.location,
local_sources=self._local_sources,
remote_sources=self._remote_sources,
meta_profile=self.meta_profile) | [
"def",
"merge",
"(",
"self",
",",
"groupBy",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"groupBy",
",",
"list",
")",
"and",
"all",
"(",
"[",
"isinstance",
"(",
"x",
",",
"str",
")",
"for",
"x",
"in",
"groupBy",
"]",
")",
":",
"groupBy",
"=",... | *Wrapper of* ``MERGE``
The MERGE operator builds a new dataset consisting of a single sample having
* as regions all the regions of all the input samples, with the
same attributes and values
* as metadata the union of all the metadata attribute-values
of the input samples.
A groupby clause can be specified on metadata: the samples are then
partitioned in groups, each with a distinct value of the grouping metadata
attributes, and the MERGE operation is applied to each group separately,
yielding to one sample in the result dataset for each group.
Samples without the grouping metadata attributes are disregarded
:param groupBy: list of metadata attributes
:return: a new GMQLDataset
Example of usage::
import gmql as gl
d1 = gl.get_example_dataset("Example_Dataset_1")
result = d1.merge(['antibody']) | [
"*",
"Wrapper",
"of",
"*",
"MERGE"
] | train | https://github.com/DEIB-GECO/PyGMQL/blob/e58b2f9402a86056dcda484a32e3de0bb06ed991/gmql/dataset/GMQLDataset.py#L1184-L1225 |
DEIB-GECO/PyGMQL | gmql/dataset/GMQLDataset.py | GMQLDataset.group | def group(self, meta=None, meta_aggregates=None, regs=None,
regs_aggregates=None, meta_group_name="_group"):
"""
*Wrapper of* ``GROUP``
The GROUP operator is used for grouping both regions and/or metadata of input
dataset samples according to distinct values of certain attributes (known as grouping
attributes); new grouping attributes are added to samples in the output dataset,
storing the results of aggregate function evaluations over metadata and/or regions
in each group of samples.
Samples having missing values for any of the grouping attributes are discarded.
:param meta: (optional) a list of metadata attributes
:param meta_aggregates: (optional) {'new_attr': fun}
:param regs: (optional) a list of region fields
:param regs_aggregates: {'new_attr': fun}
:param meta_group_name: (optional) the name to give to the group attribute in the
metadata
:return: a new GMQLDataset
Example of usage. We group samples by `antibody` and we aggregate the region pvalues taking the maximum value
calling the new region field `maxPvalue`::
import gmql as gl
d1 = gl.get_example_dataset("Example_Dataset_1")
result = d1.group(meta=['antibody'], regs_aggregates={'maxPvalue': gl.MAX("pvalue")})
"""
if isinstance(meta, list) and \
all([isinstance(x, str) for x in meta]):
meta = Some(meta)
elif meta is None:
meta = none()
else:
raise TypeError("meta must be a list of strings. "
"{} was provided".format(type(meta)))
expBuild = self.pmg.getNewExpressionBuilder(self.__index)
if isinstance(meta_aggregates, dict):
metaAggregates = []
for k in meta_aggregates:
if isinstance(k, str):
item = meta_aggregates[k]
if isinstance(item, (SUM, MIN, MAX, AVG, BAG,
BAGD, STD, MEDIAN, COUNTSAMP)):
functionName = item.get_aggregate_name()
argument = item.get_argument()
if argument is None:
argument = none()
else:
argument = Some(argument)
metaAggregates.append(expBuild.createMetaAggregateFunction(functionName,
k, argument))
else:
raise TypeError("the item of the dictionary must be an Aggregate of the following: "
"SUM, MIN, MAX, AVG, BAG, BAGD, STD, COUNTSAMP. "
"{} was provided".format(type(item)))
else:
raise TypeError("keys of meta_aggregates must be string. "
"{} was provided".format(type(k)))
metaAggregates = Some(metaAggregates)
elif meta_aggregates is None:
metaAggregates = none()
else:
raise TypeError("meta_aggregates must be a dictionary of Aggregate functions. "
"{} was provided".format(type(meta_aggregates)))
if isinstance(regs, list) and \
all([isinstance(x, str) for x in regs]):
regs = Some(regs)
elif regs is None:
regs = none()
else:
raise TypeError("regs must be a list of strings. "
"{} was provided".format(type(regs)))
if isinstance(regs_aggregates, dict):
regionAggregates = []
for k in regs_aggregates.keys():
if isinstance(k, str):
item = regs_aggregates[k]
if isinstance(item, (SUM, MIN, MAX, AVG, BAG, BAGD,
MEDIAN, COUNT)):
op_name = item.get_aggregate_name()
op_argument = item.get_argument()
if op_argument is None:
op_argument = none()
else:
op_argument = Some(op_argument)
regsToReg = expBuild.getRegionsToRegion(op_name, k, op_argument)
regionAggregates.append(regsToReg)
else:
raise TypeError("the item of the dictionary must be an Aggregate of the following: "
"SUM, MIN, MAX, AVG, BAG, BAGD, MEDIAN, COUNT. "
"{} was provided".format(type(item)))
else:
raise TypeError("The key of new_reg_fields must be a string. "
"{} was provided".format(type(k)))
regionAggregates = Some(regionAggregates)
elif regs_aggregates is None:
regionAggregates = none()
else:
raise TypeError("new_reg_fields must be a list of dictionary. "
"{} was provided".format(type(regs_aggregates)))
if isinstance(meta_group_name, str):
pass
else:
raise TypeError("meta_group_name must be a string. "
"{} was provided".format(type(meta_group_name)))
new_index = self.opmng.group(self.__index, meta, metaAggregates, meta_group_name, regs, regionAggregates)
return GMQLDataset(index=new_index, location=self.location,
local_sources=self._local_sources,
remote_sources=self._remote_sources,
meta_profile=self.meta_profile) | python | def group(self, meta=None, meta_aggregates=None, regs=None,
regs_aggregates=None, meta_group_name="_group"):
"""
*Wrapper of* ``GROUP``
The GROUP operator is used for grouping both regions and/or metadata of input
dataset samples according to distinct values of certain attributes (known as grouping
attributes); new grouping attributes are added to samples in the output dataset,
storing the results of aggregate function evaluations over metadata and/or regions
in each group of samples.
Samples having missing values for any of the grouping attributes are discarded.
:param meta: (optional) a list of metadata attributes
:param meta_aggregates: (optional) {'new_attr': fun}
:param regs: (optional) a list of region fields
:param regs_aggregates: {'new_attr': fun}
:param meta_group_name: (optional) the name to give to the group attribute in the
metadata
:return: a new GMQLDataset
Example of usage. We group samples by `antibody` and we aggregate the region pvalues taking the maximum value
calling the new region field `maxPvalue`::
import gmql as gl
d1 = gl.get_example_dataset("Example_Dataset_1")
result = d1.group(meta=['antibody'], regs_aggregates={'maxPvalue': gl.MAX("pvalue")})
"""
if isinstance(meta, list) and \
all([isinstance(x, str) for x in meta]):
meta = Some(meta)
elif meta is None:
meta = none()
else:
raise TypeError("meta must be a list of strings. "
"{} was provided".format(type(meta)))
expBuild = self.pmg.getNewExpressionBuilder(self.__index)
if isinstance(meta_aggregates, dict):
metaAggregates = []
for k in meta_aggregates:
if isinstance(k, str):
item = meta_aggregates[k]
if isinstance(item, (SUM, MIN, MAX, AVG, BAG,
BAGD, STD, MEDIAN, COUNTSAMP)):
functionName = item.get_aggregate_name()
argument = item.get_argument()
if argument is None:
argument = none()
else:
argument = Some(argument)
metaAggregates.append(expBuild.createMetaAggregateFunction(functionName,
k, argument))
else:
raise TypeError("the item of the dictionary must be an Aggregate of the following: "
"SUM, MIN, MAX, AVG, BAG, BAGD, STD, COUNTSAMP. "
"{} was provided".format(type(item)))
else:
raise TypeError("keys of meta_aggregates must be string. "
"{} was provided".format(type(k)))
metaAggregates = Some(metaAggregates)
elif meta_aggregates is None:
metaAggregates = none()
else:
raise TypeError("meta_aggregates must be a dictionary of Aggregate functions. "
"{} was provided".format(type(meta_aggregates)))
if isinstance(regs, list) and \
all([isinstance(x, str) for x in regs]):
regs = Some(regs)
elif regs is None:
regs = none()
else:
raise TypeError("regs must be a list of strings. "
"{} was provided".format(type(regs)))
if isinstance(regs_aggregates, dict):
regionAggregates = []
for k in regs_aggregates.keys():
if isinstance(k, str):
item = regs_aggregates[k]
if isinstance(item, (SUM, MIN, MAX, AVG, BAG, BAGD,
MEDIAN, COUNT)):
op_name = item.get_aggregate_name()
op_argument = item.get_argument()
if op_argument is None:
op_argument = none()
else:
op_argument = Some(op_argument)
regsToReg = expBuild.getRegionsToRegion(op_name, k, op_argument)
regionAggregates.append(regsToReg)
else:
raise TypeError("the item of the dictionary must be an Aggregate of the following: "
"SUM, MIN, MAX, AVG, BAG, BAGD, MEDIAN, COUNT. "
"{} was provided".format(type(item)))
else:
raise TypeError("The key of new_reg_fields must be a string. "
"{} was provided".format(type(k)))
regionAggregates = Some(regionAggregates)
elif regs_aggregates is None:
regionAggregates = none()
else:
raise TypeError("new_reg_fields must be a list of dictionary. "
"{} was provided".format(type(regs_aggregates)))
if isinstance(meta_group_name, str):
pass
else:
raise TypeError("meta_group_name must be a string. "
"{} was provided".format(type(meta_group_name)))
new_index = self.opmng.group(self.__index, meta, metaAggregates, meta_group_name, regs, regionAggregates)
return GMQLDataset(index=new_index, location=self.location,
local_sources=self._local_sources,
remote_sources=self._remote_sources,
meta_profile=self.meta_profile) | [
"def",
"group",
"(",
"self",
",",
"meta",
"=",
"None",
",",
"meta_aggregates",
"=",
"None",
",",
"regs",
"=",
"None",
",",
"regs_aggregates",
"=",
"None",
",",
"meta_group_name",
"=",
"\"_group\"",
")",
":",
"if",
"isinstance",
"(",
"meta",
",",
"list",
... | *Wrapper of* ``GROUP``
The GROUP operator is used for grouping both regions and/or metadata of input
dataset samples according to distinct values of certain attributes (known as grouping
attributes); new grouping attributes are added to samples in the output dataset,
storing the results of aggregate function evaluations over metadata and/or regions
in each group of samples.
Samples having missing values for any of the grouping attributes are discarded.
:param meta: (optional) a list of metadata attributes
:param meta_aggregates: (optional) {'new_attr': fun}
:param regs: (optional) a list of region fields
:param regs_aggregates: {'new_attr': fun}
:param meta_group_name: (optional) the name to give to the group attribute in the
metadata
:return: a new GMQLDataset
Example of usage. We group samples by `antibody` and we aggregate the region pvalues taking the maximum value
calling the new region field `maxPvalue`::
import gmql as gl
d1 = gl.get_example_dataset("Example_Dataset_1")
result = d1.group(meta=['antibody'], regs_aggregates={'maxPvalue': gl.MAX("pvalue")}) | [
"*",
"Wrapper",
"of",
"*",
"GROUP"
] | train | https://github.com/DEIB-GECO/PyGMQL/blob/e58b2f9402a86056dcda484a32e3de0bb06ed991/gmql/dataset/GMQLDataset.py#L1227-L1343 |
DEIB-GECO/PyGMQL | gmql/dataset/GMQLDataset.py | GMQLDataset.meta_group | def meta_group(self, meta, meta_aggregates=None):
"""
*Wrapper of* ``GROUP``
Group operation only for metadata. For further information check :meth:`~.group`
"""
return self.group(meta=meta, meta_aggregates=meta_aggregates) | python | def meta_group(self, meta, meta_aggregates=None):
"""
*Wrapper of* ``GROUP``
Group operation only for metadata. For further information check :meth:`~.group`
"""
return self.group(meta=meta, meta_aggregates=meta_aggregates) | [
"def",
"meta_group",
"(",
"self",
",",
"meta",
",",
"meta_aggregates",
"=",
"None",
")",
":",
"return",
"self",
".",
"group",
"(",
"meta",
"=",
"meta",
",",
"meta_aggregates",
"=",
"meta_aggregates",
")"
] | *Wrapper of* ``GROUP``
Group operation only for metadata. For further information check :meth:`~.group` | [
"*",
"Wrapper",
"of",
"*",
"GROUP"
] | train | https://github.com/DEIB-GECO/PyGMQL/blob/e58b2f9402a86056dcda484a32e3de0bb06ed991/gmql/dataset/GMQLDataset.py#L1345-L1351 |
DEIB-GECO/PyGMQL | gmql/dataset/GMQLDataset.py | GMQLDataset.regs_group | def regs_group(self, regs, regs_aggregates=None):
"""
*Wrapper of* ``GROUP``
Group operation only for region data. For further information check :meth:`~.group`
"""
return self.group(regs=regs, regs_aggregates=regs_aggregates) | python | def regs_group(self, regs, regs_aggregates=None):
"""
*Wrapper of* ``GROUP``
Group operation only for region data. For further information check :meth:`~.group`
"""
return self.group(regs=regs, regs_aggregates=regs_aggregates) | [
"def",
"regs_group",
"(",
"self",
",",
"regs",
",",
"regs_aggregates",
"=",
"None",
")",
":",
"return",
"self",
".",
"group",
"(",
"regs",
"=",
"regs",
",",
"regs_aggregates",
"=",
"regs_aggregates",
")"
] | *Wrapper of* ``GROUP``
Group operation only for region data. For further information check :meth:`~.group` | [
"*",
"Wrapper",
"of",
"*",
"GROUP"
] | train | https://github.com/DEIB-GECO/PyGMQL/blob/e58b2f9402a86056dcda484a32e3de0bb06ed991/gmql/dataset/GMQLDataset.py#L1353-L1359 |
DEIB-GECO/PyGMQL | gmql/dataset/GMQLDataset.py | GMQLDataset.materialize | def materialize(self, output_path=None, output_name=None, all_load=True):
"""
*Wrapper of* ``MATERIALIZE``
Starts the execution of the operations for the GMQLDataset. PyGMQL implements lazy execution
and no operation is performed until the materialization of the results is requestd.
This operation can happen both locally or remotely.
* Local mode: if the GMQLDataset is local (based on local data) the user can specify the
:param output_path: (Optional) If specified, the user can say where to locally save the results
of the computations.
:param output_name: (Optional) Can be used only if the dataset is remote. It represents the name that
the user wants to give to the resulting dataset on the server
:param all_load: (Optional) It specifies if the result dataset should be directly converted to a GDataframe (True) or to a
GMQLDataset (False) for future local queries.
:return: A GDataframe or a GMQLDataset
"""
current_mode = get_mode()
new_index = self.__modify_dag(current_mode)
if current_mode == 'local':
return Materializations.materialize_local(new_index, output_path, all_load)
elif current_mode == 'remote':
return Materializations.materialize_remote(new_index, output_name, output_path, all_load)
else:
raise ValueError("Current mode is not defined. {} given".format(current_mode)) | python | def materialize(self, output_path=None, output_name=None, all_load=True):
"""
*Wrapper of* ``MATERIALIZE``
Starts the execution of the operations for the GMQLDataset. PyGMQL implements lazy execution
and no operation is performed until the materialization of the results is requestd.
This operation can happen both locally or remotely.
* Local mode: if the GMQLDataset is local (based on local data) the user can specify the
:param output_path: (Optional) If specified, the user can say where to locally save the results
of the computations.
:param output_name: (Optional) Can be used only if the dataset is remote. It represents the name that
the user wants to give to the resulting dataset on the server
:param all_load: (Optional) It specifies if the result dataset should be directly converted to a GDataframe (True) or to a
GMQLDataset (False) for future local queries.
:return: A GDataframe or a GMQLDataset
"""
current_mode = get_mode()
new_index = self.__modify_dag(current_mode)
if current_mode == 'local':
return Materializations.materialize_local(new_index, output_path, all_load)
elif current_mode == 'remote':
return Materializations.materialize_remote(new_index, output_name, output_path, all_load)
else:
raise ValueError("Current mode is not defined. {} given".format(current_mode)) | [
"def",
"materialize",
"(",
"self",
",",
"output_path",
"=",
"None",
",",
"output_name",
"=",
"None",
",",
"all_load",
"=",
"True",
")",
":",
"current_mode",
"=",
"get_mode",
"(",
")",
"new_index",
"=",
"self",
".",
"__modify_dag",
"(",
"current_mode",
")",... | *Wrapper of* ``MATERIALIZE``
Starts the execution of the operations for the GMQLDataset. PyGMQL implements lazy execution
and no operation is performed until the materialization of the results is requestd.
This operation can happen both locally or remotely.
* Local mode: if the GMQLDataset is local (based on local data) the user can specify the
:param output_path: (Optional) If specified, the user can say where to locally save the results
of the computations.
:param output_name: (Optional) Can be used only if the dataset is remote. It represents the name that
the user wants to give to the resulting dataset on the server
:param all_load: (Optional) It specifies if the result dataset should be directly converted to a GDataframe (True) or to a
GMQLDataset (False) for future local queries.
:return: A GDataframe or a GMQLDataset | [
"*",
"Wrapper",
"of",
"*",
"MATERIALIZE"
] | train | https://github.com/DEIB-GECO/PyGMQL/blob/e58b2f9402a86056dcda484a32e3de0bb06ed991/gmql/dataset/GMQLDataset.py#L1363-L1388 |
kevinconway/daemons | daemons/interfaces/message.py | MessageManager.step | def step(self):
"""Grab a new message and dispatch it to the handler.
This method should not be extended or overwritten. Instead,
implementations of this daemon should implement the 'get_message()'
and 'handle_message()' methods.
"""
message = self.get_message()
if message is None:
self.sleep(self.idle_time)
return None
self.dispatch(message)
# In non-greenthread environments this does nothing. In green-thread
# environments this yields the context so messages can be acted upon
# before exhausting the threadpool.
self.sleep(0) | python | def step(self):
"""Grab a new message and dispatch it to the handler.
This method should not be extended or overwritten. Instead,
implementations of this daemon should implement the 'get_message()'
and 'handle_message()' methods.
"""
message = self.get_message()
if message is None:
self.sleep(self.idle_time)
return None
self.dispatch(message)
# In non-greenthread environments this does nothing. In green-thread
# environments this yields the context so messages can be acted upon
# before exhausting the threadpool.
self.sleep(0) | [
"def",
"step",
"(",
"self",
")",
":",
"message",
"=",
"self",
".",
"get_message",
"(",
")",
"if",
"message",
"is",
"None",
":",
"self",
".",
"sleep",
"(",
"self",
".",
"idle_time",
")",
"return",
"None",
"self",
".",
"dispatch",
"(",
"message",
")",
... | Grab a new message and dispatch it to the handler.
This method should not be extended or overwritten. Instead,
implementations of this daemon should implement the 'get_message()'
and 'handle_message()' methods. | [
"Grab",
"a",
"new",
"message",
"and",
"dispatch",
"it",
"to",
"the",
"handler",
"."
] | train | https://github.com/kevinconway/daemons/blob/b0fe0db5821171a35aa9078596d19d630c570b38/daemons/interfaces/message.py#L35-L52 |
VeryCB/flask-slack | flask_slack/slack.py | Slack.init_app | def init_app(self, app=None):
"""Initialize application configuration"""
config = getattr(app, 'config', app)
self.team_id = config.get('TEAM_ID') | python | def init_app(self, app=None):
"""Initialize application configuration"""
config = getattr(app, 'config', app)
self.team_id = config.get('TEAM_ID') | [
"def",
"init_app",
"(",
"self",
",",
"app",
"=",
"None",
")",
":",
"config",
"=",
"getattr",
"(",
"app",
",",
"'config'",
",",
"app",
")",
"self",
".",
"team_id",
"=",
"config",
".",
"get",
"(",
"'TEAM_ID'",
")"
] | Initialize application configuration | [
"Initialize",
"application",
"configuration"
] | train | https://github.com/VeryCB/flask-slack/blob/ec7e08e6603f0d2d06cfbaff6699df02ee507077/flask_slack/slack.py#L15-L19 |
VeryCB/flask-slack | flask_slack/slack.py | Slack.command | def command(self, command, token, team_id=None, methods=['GET'], **kwargs):
"""A decorator used to register a command.
Example::
@slack.command('your_command', token='your_token',
team_id='your_team_id', methods=['POST'])
def your_method(**kwargs):
text = kwargs.get('text')
return slack.response(text)
:param command: the command to register
:param token: your command token provided by slack
:param team_id: optional. your team_id provided by slack.
You can also specify the "TEAM_ID" in app
configuration file for one-team project
:param methods: optional. HTTP methods which are accepted to
execute the command
:param kwargs: optional. the optional arguments which will be passed
to your register method
"""
if team_id is None:
team_id = self.team_id
if team_id is None:
raise RuntimeError('TEAM_ID is not found in your configuration!')
def deco(func):
self._commands[(team_id, command)] = (func, token, methods, kwargs)
return func
return deco | python | def command(self, command, token, team_id=None, methods=['GET'], **kwargs):
"""A decorator used to register a command.
Example::
@slack.command('your_command', token='your_token',
team_id='your_team_id', methods=['POST'])
def your_method(**kwargs):
text = kwargs.get('text')
return slack.response(text)
:param command: the command to register
:param token: your command token provided by slack
:param team_id: optional. your team_id provided by slack.
You can also specify the "TEAM_ID" in app
configuration file for one-team project
:param methods: optional. HTTP methods which are accepted to
execute the command
:param kwargs: optional. the optional arguments which will be passed
to your register method
"""
if team_id is None:
team_id = self.team_id
if team_id is None:
raise RuntimeError('TEAM_ID is not found in your configuration!')
def deco(func):
self._commands[(team_id, command)] = (func, token, methods, kwargs)
return func
return deco | [
"def",
"command",
"(",
"self",
",",
"command",
",",
"token",
",",
"team_id",
"=",
"None",
",",
"methods",
"=",
"[",
"'GET'",
"]",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"team_id",
"is",
"None",
":",
"team_id",
"=",
"self",
".",
"team_id",
"if",
... | A decorator used to register a command.
Example::
@slack.command('your_command', token='your_token',
team_id='your_team_id', methods=['POST'])
def your_method(**kwargs):
text = kwargs.get('text')
return slack.response(text)
:param command: the command to register
:param token: your command token provided by slack
:param team_id: optional. your team_id provided by slack.
You can also specify the "TEAM_ID" in app
configuration file for one-team project
:param methods: optional. HTTP methods which are accepted to
execute the command
:param kwargs: optional. the optional arguments which will be passed
to your register method | [
"A",
"decorator",
"used",
"to",
"register",
"a",
"command",
".",
"Example",
"::"
] | train | https://github.com/VeryCB/flask-slack/blob/ec7e08e6603f0d2d06cfbaff6699df02ee507077/flask_slack/slack.py#L21-L49 |
VeryCB/flask-slack | flask_slack/slack.py | Slack.dispatch | def dispatch(self):
"""Dispatch http request to registerd commands.
Example::
slack = Slack(app)
app.add_url_rule('/', view_func=slack.dispatch)
"""
from flask import request
method = request.method
data = request.args
if method == 'POST':
data = request.form
token = data.get('token')
team_id = data.get('team_id')
command = data.get('command') or data.get('trigger_word')
if isinstance(command, string_types):
command = command.strip().lstrip('/')
try:
self.validate(command, token, team_id, method)
except SlackError as e:
return self.response(e.msg)
func, _, _, kwargs = self._commands[(team_id, command)]
kwargs.update(data.to_dict())
return func(**kwargs) | python | def dispatch(self):
"""Dispatch http request to registerd commands.
Example::
slack = Slack(app)
app.add_url_rule('/', view_func=slack.dispatch)
"""
from flask import request
method = request.method
data = request.args
if method == 'POST':
data = request.form
token = data.get('token')
team_id = data.get('team_id')
command = data.get('command') or data.get('trigger_word')
if isinstance(command, string_types):
command = command.strip().lstrip('/')
try:
self.validate(command, token, team_id, method)
except SlackError as e:
return self.response(e.msg)
func, _, _, kwargs = self._commands[(team_id, command)]
kwargs.update(data.to_dict())
return func(**kwargs) | [
"def",
"dispatch",
"(",
"self",
")",
":",
"from",
"flask",
"import",
"request",
"method",
"=",
"request",
".",
"method",
"data",
"=",
"request",
".",
"args",
"if",
"method",
"==",
"'POST'",
":",
"data",
"=",
"request",
".",
"form",
"token",
"=",
"data"... | Dispatch http request to registerd commands.
Example::
slack = Slack(app)
app.add_url_rule('/', view_func=slack.dispatch) | [
"Dispatch",
"http",
"request",
"to",
"registerd",
"commands",
".",
"Example",
"::"
] | train | https://github.com/VeryCB/flask-slack/blob/ec7e08e6603f0d2d06cfbaff6699df02ee507077/flask_slack/slack.py#L51-L81 |
VeryCB/flask-slack | flask_slack/slack.py | Slack.validate | def validate(self, command, token, team_id, method):
"""Validate request queries with registerd commands
:param command: command parameter from request
:param token: token parameter from request
:param team_id: team_id parameter from request
:param method: the request method
"""
if (team_id, command) not in self._commands:
raise SlackError('Command {0} is not found in team {1}'.format(
command, team_id))
func, _token, methods, kwargs = self._commands[(team_id, command)]
if method not in methods:
raise SlackError('{} request is not allowed'.format(method))
if token != _token:
raise SlackError('Your token {} is invalid'.format(token)) | python | def validate(self, command, token, team_id, method):
"""Validate request queries with registerd commands
:param command: command parameter from request
:param token: token parameter from request
:param team_id: team_id parameter from request
:param method: the request method
"""
if (team_id, command) not in self._commands:
raise SlackError('Command {0} is not found in team {1}'.format(
command, team_id))
func, _token, methods, kwargs = self._commands[(team_id, command)]
if method not in methods:
raise SlackError('{} request is not allowed'.format(method))
if token != _token:
raise SlackError('Your token {} is invalid'.format(token)) | [
"def",
"validate",
"(",
"self",
",",
"command",
",",
"token",
",",
"team_id",
",",
"method",
")",
":",
"if",
"(",
"team_id",
",",
"command",
")",
"not",
"in",
"self",
".",
"_commands",
":",
"raise",
"SlackError",
"(",
"'Command {0} is not found in team {1}'"... | Validate request queries with registerd commands
:param command: command parameter from request
:param token: token parameter from request
:param team_id: team_id parameter from request
:param method: the request method | [
"Validate",
"request",
"queries",
"with",
"registerd",
"commands"
] | train | https://github.com/VeryCB/flask-slack/blob/ec7e08e6603f0d2d06cfbaff6699df02ee507077/flask_slack/slack.py#L85-L103 |
VeryCB/flask-slack | flask_slack/slack.py | Slack.response | def response(self, text, response_type='ephemeral', attachments=None):
"""Return a response with json format
:param text: the text returned to the client
:param response_type: optional. When `in_channel` is assigned,
both the response message and the initial
message typed by the user will be shared
in the channel.
When `ephemeral` is assigned, the response
message will be visible only to the user
that issued the command.
:param attachments: optional. A list of additional messages
for rich response.
"""
from flask import jsonify
if attachments is None:
attachments = []
data = {
'response_type': response_type,
'text': text,
'attachments': attachments,
}
return jsonify(**data) | python | def response(self, text, response_type='ephemeral', attachments=None):
"""Return a response with json format
:param text: the text returned to the client
:param response_type: optional. When `in_channel` is assigned,
both the response message and the initial
message typed by the user will be shared
in the channel.
When `ephemeral` is assigned, the response
message will be visible only to the user
that issued the command.
:param attachments: optional. A list of additional messages
for rich response.
"""
from flask import jsonify
if attachments is None:
attachments = []
data = {
'response_type': response_type,
'text': text,
'attachments': attachments,
}
return jsonify(**data) | [
"def",
"response",
"(",
"self",
",",
"text",
",",
"response_type",
"=",
"'ephemeral'",
",",
"attachments",
"=",
"None",
")",
":",
"from",
"flask",
"import",
"jsonify",
"if",
"attachments",
"is",
"None",
":",
"attachments",
"=",
"[",
"]",
"data",
"=",
"{"... | Return a response with json format
:param text: the text returned to the client
:param response_type: optional. When `in_channel` is assigned,
both the response message and the initial
message typed by the user will be shared
in the channel.
When `ephemeral` is assigned, the response
message will be visible only to the user
that issued the command.
:param attachments: optional. A list of additional messages
for rich response. | [
"Return",
"a",
"response",
"with",
"json",
"format"
] | train | https://github.com/VeryCB/flask-slack/blob/ec7e08e6603f0d2d06cfbaff6699df02ee507077/flask_slack/slack.py#L105-L128 |
kevinconway/daemons | daemons/pid/simple.py | SimplePidManager.pid | def pid(self):
"""Get the pid which represents a daemonized process.
The result should be None if the process is not running.
"""
try:
with open(self.pidfile, 'r') as pidfile:
try:
pid = int(pidfile.read().strip())
except ValueError:
return None
try:
os.kill(pid, 0)
except OSError as e:
if e.errno == errno.EPERM:
return pid
elif e.errno == errno.ESRCH:
return None
LOG.exception(
"os.kill returned unhandled error "
"{0}".format(e.strerror)
)
sys.exit(exit.PIDFILE_ERROR)
return pid
except IOError:
if not os.path.isfile(self.pidfile):
return None
LOG.exception("Failed to read pidfile {0}.".format(self.pidfile))
sys.exit(exit.PIDFILE_INACCESSIBLE) | python | def pid(self):
"""Get the pid which represents a daemonized process.
The result should be None if the process is not running.
"""
try:
with open(self.pidfile, 'r') as pidfile:
try:
pid = int(pidfile.read().strip())
except ValueError:
return None
try:
os.kill(pid, 0)
except OSError as e:
if e.errno == errno.EPERM:
return pid
elif e.errno == errno.ESRCH:
return None
LOG.exception(
"os.kill returned unhandled error "
"{0}".format(e.strerror)
)
sys.exit(exit.PIDFILE_ERROR)
return pid
except IOError:
if not os.path.isfile(self.pidfile):
return None
LOG.exception("Failed to read pidfile {0}.".format(self.pidfile))
sys.exit(exit.PIDFILE_INACCESSIBLE) | [
"def",
"pid",
"(",
"self",
")",
":",
"try",
":",
"with",
"open",
"(",
"self",
".",
"pidfile",
",",
"'r'",
")",
"as",
"pidfile",
":",
"try",
":",
"pid",
"=",
"int",
"(",
"pidfile",
".",
"read",
"(",
")",
".",
"strip",
"(",
")",
")",
"except",
... | Get the pid which represents a daemonized process.
The result should be None if the process is not running. | [
"Get",
"the",
"pid",
"which",
"represents",
"a",
"daemonized",
"process",
"."
] | train | https://github.com/kevinconway/daemons/blob/b0fe0db5821171a35aa9078596d19d630c570b38/daemons/pid/simple.py#L25-L71 |
kevinconway/daemons | daemons/pid/simple.py | SimplePidManager.pid | def pid(self, pidnum):
"""Set the pid for a running process."""
try:
with open(self.pidfile, "w+") as pidfile:
pidfile.write("{0}\n".format(pidnum))
except IOError:
LOG.exception("Failed to write pidfile {0}).".format(self.pidfile))
sys.exit(exit.PIDFILE_INACCESSIBLE) | python | def pid(self, pidnum):
"""Set the pid for a running process."""
try:
with open(self.pidfile, "w+") as pidfile:
pidfile.write("{0}\n".format(pidnum))
except IOError:
LOG.exception("Failed to write pidfile {0}).".format(self.pidfile))
sys.exit(exit.PIDFILE_INACCESSIBLE) | [
"def",
"pid",
"(",
"self",
",",
"pidnum",
")",
":",
"try",
":",
"with",
"open",
"(",
"self",
".",
"pidfile",
",",
"\"w+\"",
")",
"as",
"pidfile",
":",
"pidfile",
".",
"write",
"(",
"\"{0}\\n\"",
".",
"format",
"(",
"pidnum",
")",
")",
"except",
"IO... | Set the pid for a running process. | [
"Set",
"the",
"pid",
"for",
"a",
"running",
"process",
"."
] | train | https://github.com/kevinconway/daemons/blob/b0fe0db5821171a35aa9078596d19d630c570b38/daemons/pid/simple.py#L74-L85 |
kevinconway/daemons | daemons/pid/simple.py | SimplePidManager.pid | def pid(self):
"""Stop managing the current pid."""
try:
os.remove(self.pidfile)
except IOError:
if not os.path.isfile(self.pidfile):
return None
LOG.exception("Failed to clear pidfile {0}).".format(self.pidfile))
sys.exit(exit.PIDFILE_INACCESSIBLE) | python | def pid(self):
"""Stop managing the current pid."""
try:
os.remove(self.pidfile)
except IOError:
if not os.path.isfile(self.pidfile):
return None
LOG.exception("Failed to clear pidfile {0}).".format(self.pidfile))
sys.exit(exit.PIDFILE_INACCESSIBLE) | [
"def",
"pid",
"(",
"self",
")",
":",
"try",
":",
"os",
".",
"remove",
"(",
"self",
".",
"pidfile",
")",
"except",
"IOError",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"self",
".",
"pidfile",
")",
":",
"return",
"None",
"LOG",
".",
... | Stop managing the current pid. | [
"Stop",
"managing",
"the",
"current",
"pid",
"."
] | train | https://github.com/kevinconway/daemons/blob/b0fe0db5821171a35aa9078596d19d630c570b38/daemons/pid/simple.py#L88-L101 |
kevinconway/daemons | daemons/message/gevent.py | GeventMessageManager.pool | def pool(self):
"""Get an gevent pool used to dispatch requests."""
self._pool = self._pool or gevent.pool.Pool(size=self.pool_size)
return self._pool | python | def pool(self):
"""Get an gevent pool used to dispatch requests."""
self._pool = self._pool or gevent.pool.Pool(size=self.pool_size)
return self._pool | [
"def",
"pool",
"(",
"self",
")",
":",
"self",
".",
"_pool",
"=",
"self",
".",
"_pool",
"or",
"gevent",
".",
"pool",
".",
"Pool",
"(",
"size",
"=",
"self",
".",
"pool_size",
")",
"return",
"self",
".",
"_pool"
] | Get an gevent pool used to dispatch requests. | [
"Get",
"an",
"gevent",
"pool",
"used",
"to",
"dispatch",
"requests",
"."
] | train | https://github.com/kevinconway/daemons/blob/b0fe0db5821171a35aa9078596d19d630c570b38/daemons/message/gevent.py#L18-L21 |
nathan-hoad/python-iwlib | iwlib/iwconfig.py | set_essid | def set_essid(interface, essid):
"""
Set the ESSID of a given interface
Arguments:
interface - device to work on (e.g. eth1, wlan0).
essid - ESSID to set. Must be no longer than IW_ESSID_MAX_SIZE (typically 32 characters).
"""
interface = _get_bytes(interface)
essid = _get_bytes(essid)
wrq = ffi.new('struct iwreq*')
with iwlib_socket() as sock:
if essid.lower() in (b'off', b'any'):
wrq.u.essid.flags = 0
essid = b''
elif essid.lower() == b'on':
buf = ffi.new('char []', iwlib.IW_ESSID_MAX_SIZE+1)
wrq.u.essid.pointer = buf
wrq.u.essid.length = iwlib.IW_ESSID_MAX_SIZE + 1
wrq.u.essid.flags = 0
if iwlib.iw_get_ext(sock, interface, iwlib.SIOCGIWESSID, wrq) < 0:
raise ValueError("Error retrieving previous ESSID: %s" % (os.strerror(ffi.errno)))
wrq.u.essid.flags = 1
elif len(essid) > iwlib.IW_ESSID_MAX_SIZE:
raise ValueError("ESSID '%s' is longer than the maximum %d" % (essid, iwlib.IW_ESSID_MAX_SIZE))
else:
wrq.u.essid.pointer = ffi.new_handle(essid)
wrq.u.essid.length = len(essid)
wrq.u.essid.flags = 1
if iwlib.iw_get_kernel_we_version() < 21:
wrq.u.essid.length += 1
if iwlib.iw_set_ext(sock, interface, iwlib.SIOCSIWESSID, wrq) < 0:
errno = ffi.errno
strerror = "Couldn't set essid on device '%s': %s" % (interface.decode('utf8'), os.strerror(errno))
raise OSError(errno, strerror) | python | def set_essid(interface, essid):
"""
Set the ESSID of a given interface
Arguments:
interface - device to work on (e.g. eth1, wlan0).
essid - ESSID to set. Must be no longer than IW_ESSID_MAX_SIZE (typically 32 characters).
"""
interface = _get_bytes(interface)
essid = _get_bytes(essid)
wrq = ffi.new('struct iwreq*')
with iwlib_socket() as sock:
if essid.lower() in (b'off', b'any'):
wrq.u.essid.flags = 0
essid = b''
elif essid.lower() == b'on':
buf = ffi.new('char []', iwlib.IW_ESSID_MAX_SIZE+1)
wrq.u.essid.pointer = buf
wrq.u.essid.length = iwlib.IW_ESSID_MAX_SIZE + 1
wrq.u.essid.flags = 0
if iwlib.iw_get_ext(sock, interface, iwlib.SIOCGIWESSID, wrq) < 0:
raise ValueError("Error retrieving previous ESSID: %s" % (os.strerror(ffi.errno)))
wrq.u.essid.flags = 1
elif len(essid) > iwlib.IW_ESSID_MAX_SIZE:
raise ValueError("ESSID '%s' is longer than the maximum %d" % (essid, iwlib.IW_ESSID_MAX_SIZE))
else:
wrq.u.essid.pointer = ffi.new_handle(essid)
wrq.u.essid.length = len(essid)
wrq.u.essid.flags = 1
if iwlib.iw_get_kernel_we_version() < 21:
wrq.u.essid.length += 1
if iwlib.iw_set_ext(sock, interface, iwlib.SIOCSIWESSID, wrq) < 0:
errno = ffi.errno
strerror = "Couldn't set essid on device '%s': %s" % (interface.decode('utf8'), os.strerror(errno))
raise OSError(errno, strerror) | [
"def",
"set_essid",
"(",
"interface",
",",
"essid",
")",
":",
"interface",
"=",
"_get_bytes",
"(",
"interface",
")",
"essid",
"=",
"_get_bytes",
"(",
"essid",
")",
"wrq",
"=",
"ffi",
".",
"new",
"(",
"'struct iwreq*'",
")",
"with",
"iwlib_socket",
"(",
"... | Set the ESSID of a given interface
Arguments:
interface - device to work on (e.g. eth1, wlan0).
essid - ESSID to set. Must be no longer than IW_ESSID_MAX_SIZE (typically 32 characters). | [
"Set",
"the",
"ESSID",
"of",
"a",
"given",
"interface"
] | train | https://github.com/nathan-hoad/python-iwlib/blob/f7604de0a27709fca139c4bada58263bdce4f08e/iwlib/iwconfig.py#L126-L165 |
MKLab-ITI/reveal-graph-embedding | reveal_graph_embedding/datautil/asu_datautil/asu_read_data.py | read_adjacency_matrix | def read_adjacency_matrix(file_path, separator):
"""
Reads an edge list in csv format and returns the adjacency matrix in SciPy Sparse COOrdinate format.
Inputs: - file_path: The path where the adjacency matrix is stored.
- separator: The delimiter among values (e.g. ",", "\t", " ")
Outputs: - adjacency_matrix: The adjacency matrix in SciPy Sparse COOrdinate format.
"""
# Open file
file_row_generator = get_file_row_generator(file_path, separator)
# Initialize lists for row and column sparse matrix arguments
row = list()
col = list()
append_row = row.append
append_col = col.append
# Read all file rows
for file_row in file_row_generator:
source_node = np.int64(file_row[0])
target_node = np.int64(file_row[1])
# Add edge
append_row(source_node)
append_col(target_node)
# Since this is an undirected network also add the reciprocal edge
append_row(target_node)
append_col(source_node)
row = np.array(row, dtype=np.int64)
col = np.array(col, dtype=np.int64)
data = np.ones_like(row, dtype=np.float64)
number_of_nodes = np.max(row) # I assume that there are no missing nodes at the end.
# Array count should start from 0.
row -= 1
col -= 1
# Form sparse adjacency matrix
adjacency_matrix = sparse.coo_matrix((data, (row, col)), shape=(number_of_nodes, number_of_nodes))
return adjacency_matrix | python | def read_adjacency_matrix(file_path, separator):
"""
Reads an edge list in csv format and returns the adjacency matrix in SciPy Sparse COOrdinate format.
Inputs: - file_path: The path where the adjacency matrix is stored.
- separator: The delimiter among values (e.g. ",", "\t", " ")
Outputs: - adjacency_matrix: The adjacency matrix in SciPy Sparse COOrdinate format.
"""
# Open file
file_row_generator = get_file_row_generator(file_path, separator)
# Initialize lists for row and column sparse matrix arguments
row = list()
col = list()
append_row = row.append
append_col = col.append
# Read all file rows
for file_row in file_row_generator:
source_node = np.int64(file_row[0])
target_node = np.int64(file_row[1])
# Add edge
append_row(source_node)
append_col(target_node)
# Since this is an undirected network also add the reciprocal edge
append_row(target_node)
append_col(source_node)
row = np.array(row, dtype=np.int64)
col = np.array(col, dtype=np.int64)
data = np.ones_like(row, dtype=np.float64)
number_of_nodes = np.max(row) # I assume that there are no missing nodes at the end.
# Array count should start from 0.
row -= 1
col -= 1
# Form sparse adjacency matrix
adjacency_matrix = sparse.coo_matrix((data, (row, col)), shape=(number_of_nodes, number_of_nodes))
return adjacency_matrix | [
"def",
"read_adjacency_matrix",
"(",
"file_path",
",",
"separator",
")",
":",
"# Open file",
"file_row_generator",
"=",
"get_file_row_generator",
"(",
"file_path",
",",
"separator",
")",
"# Initialize lists for row and column sparse matrix arguments",
"row",
"=",
"list",
"(... | Reads an edge list in csv format and returns the adjacency matrix in SciPy Sparse COOrdinate format.
Inputs: - file_path: The path where the adjacency matrix is stored.
- separator: The delimiter among values (e.g. ",", "\t", " ")
Outputs: - adjacency_matrix: The adjacency matrix in SciPy Sparse COOrdinate format. | [
"Reads",
"an",
"edge",
"list",
"in",
"csv",
"format",
"and",
"returns",
"the",
"adjacency",
"matrix",
"in",
"SciPy",
"Sparse",
"COOrdinate",
"format",
"."
] | train | https://github.com/MKLab-ITI/reveal-graph-embedding/blob/eda862687aa5a64b79c6b12de1b4dca6ce986dc8/reveal_graph_embedding/datautil/asu_datautil/asu_read_data.py#L9-L53 |
MKLab-ITI/reveal-graph-embedding | reveal_graph_embedding/datautil/asu_datautil/asu_read_data.py | read_node_label_matrix | def read_node_label_matrix(file_path, separator, number_of_nodes):
"""
Reads node-label pairs in csv format and returns a list of tuples and a node-label matrix.
Inputs: - file_path: The path where the node-label matrix is stored.
- separator: The delimiter among values (e.g. ",", "\t", " ")
- number_of_nodes: The number of nodes of the full graph. It is possible that not all nodes are labelled.
Outputs: - node_label_matrix: The node-label associations in a NumPy array of tuples format.
- number_of_categories: The number of categories/classes the nodes may belong to.
- labelled_node_indices: A NumPy array containing the labelled node indices.
"""
# Open file
file_row_generator = get_file_row_generator(file_path, separator)
# Initialize lists for row and column sparse matrix arguments
row = list()
col = list()
append_row = row.append
append_col = col.append
# Populate the arrays
for file_row in file_row_generator:
node = np.int64(file_row[0])
label = np.int64(file_row[1])
# Add label
append_row(node)
append_col(label)
number_of_categories = len(set(col)) # I assume that there are no missing labels. There may be missing nodes.
labelled_node_indices = np.array(list(set(row)))
row = np.array(row, dtype=np.int64)
col = np.array(col, dtype=np.int64)
data = np.ones_like(row, dtype=np.float64)
# Array count should start from 0.
row -= 1
col -= 1
labelled_node_indices -= 1
# Form sparse adjacency matrix
node_label_matrix = sparse.coo_matrix((data, (row, col)), shape=(number_of_nodes, number_of_categories))
node_label_matrix = node_label_matrix.tocsr()
return node_label_matrix, number_of_categories, labelled_node_indices | python | def read_node_label_matrix(file_path, separator, number_of_nodes):
"""
Reads node-label pairs in csv format and returns a list of tuples and a node-label matrix.
Inputs: - file_path: The path where the node-label matrix is stored.
- separator: The delimiter among values (e.g. ",", "\t", " ")
- number_of_nodes: The number of nodes of the full graph. It is possible that not all nodes are labelled.
Outputs: - node_label_matrix: The node-label associations in a NumPy array of tuples format.
- number_of_categories: The number of categories/classes the nodes may belong to.
- labelled_node_indices: A NumPy array containing the labelled node indices.
"""
# Open file
file_row_generator = get_file_row_generator(file_path, separator)
# Initialize lists for row and column sparse matrix arguments
row = list()
col = list()
append_row = row.append
append_col = col.append
# Populate the arrays
for file_row in file_row_generator:
node = np.int64(file_row[0])
label = np.int64(file_row[1])
# Add label
append_row(node)
append_col(label)
number_of_categories = len(set(col)) # I assume that there are no missing labels. There may be missing nodes.
labelled_node_indices = np.array(list(set(row)))
row = np.array(row, dtype=np.int64)
col = np.array(col, dtype=np.int64)
data = np.ones_like(row, dtype=np.float64)
# Array count should start from 0.
row -= 1
col -= 1
labelled_node_indices -= 1
# Form sparse adjacency matrix
node_label_matrix = sparse.coo_matrix((data, (row, col)), shape=(number_of_nodes, number_of_categories))
node_label_matrix = node_label_matrix.tocsr()
return node_label_matrix, number_of_categories, labelled_node_indices | [
"def",
"read_node_label_matrix",
"(",
"file_path",
",",
"separator",
",",
"number_of_nodes",
")",
":",
"# Open file",
"file_row_generator",
"=",
"get_file_row_generator",
"(",
"file_path",
",",
"separator",
")",
"# Initialize lists for row and column sparse matrix arguments",
... | Reads node-label pairs in csv format and returns a list of tuples and a node-label matrix.
Inputs: - file_path: The path where the node-label matrix is stored.
- separator: The delimiter among values (e.g. ",", "\t", " ")
- number_of_nodes: The number of nodes of the full graph. It is possible that not all nodes are labelled.
Outputs: - node_label_matrix: The node-label associations in a NumPy array of tuples format.
- number_of_categories: The number of categories/classes the nodes may belong to.
- labelled_node_indices: A NumPy array containing the labelled node indices. | [
"Reads",
"node",
"-",
"label",
"pairs",
"in",
"csv",
"format",
"and",
"returns",
"a",
"list",
"of",
"tuples",
"and",
"a",
"node",
"-",
"label",
"matrix",
"."
] | train | https://github.com/MKLab-ITI/reveal-graph-embedding/blob/eda862687aa5a64b79c6b12de1b4dca6ce986dc8/reveal_graph_embedding/datautil/asu_datautil/asu_read_data.py#L56-L102 |
dhilipsiva/garuda | garuda/management/commands/garuda.py | ensure_data | def ensure_data():
'''
Ensure that the Garuda directory and files
'''
if not os.path.exists(GARUDA_DIR):
os.makedirs(GARUDA_DIR)
Path(f'{GARUDA_DIR}/__init__.py').touch() | python | def ensure_data():
'''
Ensure that the Garuda directory and files
'''
if not os.path.exists(GARUDA_DIR):
os.makedirs(GARUDA_DIR)
Path(f'{GARUDA_DIR}/__init__.py').touch() | [
"def",
"ensure_data",
"(",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"GARUDA_DIR",
")",
":",
"os",
".",
"makedirs",
"(",
"GARUDA_DIR",
")",
"Path",
"(",
"f'{GARUDA_DIR}/__init__.py'",
")",
".",
"touch",
"(",
")"
] | Ensure that the Garuda directory and files | [
"Ensure",
"that",
"the",
"Garuda",
"directory",
"and",
"files"
] | train | https://github.com/dhilipsiva/garuda/blob/b8188f5d6141be9f3f9e3fddd0494143c2066184/garuda/management/commands/garuda.py#L27-L33 |
dhilipsiva/garuda | garuda/management/commands/garuda.py | protoc_arguments | def protoc_arguments():
'''
Construct protobuf compiler arguments
'''
proto_include = resource_filename('grpc_tools', '_proto')
return [
protoc.__file__, '-I', GARUDA_DIR, f'--python_out={GARUDA_DIR}',
f'--grpc_python_out={GARUDA_DIR}', GARUDA_PROTO_PATH,
f'-I{proto_include}'] | python | def protoc_arguments():
'''
Construct protobuf compiler arguments
'''
proto_include = resource_filename('grpc_tools', '_proto')
return [
protoc.__file__, '-I', GARUDA_DIR, f'--python_out={GARUDA_DIR}',
f'--grpc_python_out={GARUDA_DIR}', GARUDA_PROTO_PATH,
f'-I{proto_include}'] | [
"def",
"protoc_arguments",
"(",
")",
":",
"proto_include",
"=",
"resource_filename",
"(",
"'grpc_tools'",
",",
"'_proto'",
")",
"return",
"[",
"protoc",
".",
"__file__",
",",
"'-I'",
",",
"GARUDA_DIR",
",",
"f'--python_out={GARUDA_DIR}'",
",",
"f'--grpc_python_out={... | Construct protobuf compiler arguments | [
"Construct",
"protobuf",
"compiler",
"arguments"
] | train | https://github.com/dhilipsiva/garuda/blob/b8188f5d6141be9f3f9e3fddd0494143c2066184/garuda/management/commands/garuda.py#L270-L278 |
dhilipsiva/garuda | garuda/management/commands/garuda.py | fix_grpc_import | def fix_grpc_import():
'''
Snippet to fix the gRPC import path
'''
with open(GARUDA_GRPC_PATH, 'r') as f:
filedata = f.read()
filedata = filedata.replace(
'import garuda_pb2 as garuda__pb2',
f'import {GARUDA_DIR}.garuda_pb2 as garuda__pb2')
with open(GARUDA_GRPC_PATH, 'w') as f:
f.write(filedata) | python | def fix_grpc_import():
'''
Snippet to fix the gRPC import path
'''
with open(GARUDA_GRPC_PATH, 'r') as f:
filedata = f.read()
filedata = filedata.replace(
'import garuda_pb2 as garuda__pb2',
f'import {GARUDA_DIR}.garuda_pb2 as garuda__pb2')
with open(GARUDA_GRPC_PATH, 'w') as f:
f.write(filedata) | [
"def",
"fix_grpc_import",
"(",
")",
":",
"with",
"open",
"(",
"GARUDA_GRPC_PATH",
",",
"'r'",
")",
"as",
"f",
":",
"filedata",
"=",
"f",
".",
"read",
"(",
")",
"filedata",
"=",
"filedata",
".",
"replace",
"(",
"'import garuda_pb2 as garuda__pb2'",
",",
"f'... | Snippet to fix the gRPC import path | [
"Snippet",
"to",
"fix",
"the",
"gRPC",
"import",
"path"
] | train | https://github.com/dhilipsiva/garuda/blob/b8188f5d6141be9f3f9e3fddd0494143c2066184/garuda/management/commands/garuda.py#L281-L291 |
MKLab-ITI/reveal-graph-embedding | reveal_graph_embedding/datautil/score_rw_util.py | write_average_score_row | def write_average_score_row(fp, score_name, scores):
"""
Simple utility function that writes an average score row in a file designated by a file pointer.
Inputs: - fp: A file pointer.
- score_name: What it says on the tin.
- scores: An array of average score values corresponding to each of the training set percentages.
"""
row = "--" + score_name + "--"
fp.write(row)
for vector in scores:
row = list(vector)
row = [str(score) for score in row]
row = "\n" + "\t".join(row)
fp.write(row) | python | def write_average_score_row(fp, score_name, scores):
"""
Simple utility function that writes an average score row in a file designated by a file pointer.
Inputs: - fp: A file pointer.
- score_name: What it says on the tin.
- scores: An array of average score values corresponding to each of the training set percentages.
"""
row = "--" + score_name + "--"
fp.write(row)
for vector in scores:
row = list(vector)
row = [str(score) for score in row]
row = "\n" + "\t".join(row)
fp.write(row) | [
"def",
"write_average_score_row",
"(",
"fp",
",",
"score_name",
",",
"scores",
")",
":",
"row",
"=",
"\"--\"",
"+",
"score_name",
"+",
"\"--\"",
"fp",
".",
"write",
"(",
"row",
")",
"for",
"vector",
"in",
"scores",
":",
"row",
"=",
"list",
"(",
"vector... | Simple utility function that writes an average score row in a file designated by a file pointer.
Inputs: - fp: A file pointer.
- score_name: What it says on the tin.
- scores: An array of average score values corresponding to each of the training set percentages. | [
"Simple",
"utility",
"function",
"that",
"writes",
"an",
"average",
"score",
"row",
"in",
"a",
"file",
"designated",
"by",
"a",
"file",
"pointer",
"."
] | train | https://github.com/MKLab-ITI/reveal-graph-embedding/blob/eda862687aa5a64b79c6b12de1b4dca6ce986dc8/reveal_graph_embedding/datautil/score_rw_util.py#L76-L90 |
WhyNotHugo/django-afip | django_afip/admin.py | catch_errors | def catch_errors(f):
"""
Catches specific errors in admin actions and shows a friendly error.
"""
@functools.wraps(f)
def wrapper(self, request, *args, **kwargs):
try:
return f(self, request, *args, **kwargs)
except exceptions.CertificateExpired:
self.message_user(
request,
_('The AFIP Taxpayer certificate has expired.'),
messages.ERROR,
)
except exceptions.UntrustedCertificate:
self.message_user(
request,
_('The AFIP Taxpayer certificate is untrusted.'),
messages.ERROR,
)
except exceptions.CorruptCertificate:
self.message_user(
request,
_('The AFIP Taxpayer certificate is corrupt.'),
messages.ERROR,
)
except exceptions.AuthenticationError as e:
logger.exception('AFIP auth failed')
self.message_user(
request,
_('An unknown authentication error has ocurred: %s') % e,
messages.ERROR,
)
return wrapper | python | def catch_errors(f):
"""
Catches specific errors in admin actions and shows a friendly error.
"""
@functools.wraps(f)
def wrapper(self, request, *args, **kwargs):
try:
return f(self, request, *args, **kwargs)
except exceptions.CertificateExpired:
self.message_user(
request,
_('The AFIP Taxpayer certificate has expired.'),
messages.ERROR,
)
except exceptions.UntrustedCertificate:
self.message_user(
request,
_('The AFIP Taxpayer certificate is untrusted.'),
messages.ERROR,
)
except exceptions.CorruptCertificate:
self.message_user(
request,
_('The AFIP Taxpayer certificate is corrupt.'),
messages.ERROR,
)
except exceptions.AuthenticationError as e:
logger.exception('AFIP auth failed')
self.message_user(
request,
_('An unknown authentication error has ocurred: %s') % e,
messages.ERROR,
)
return wrapper | [
"def",
"catch_errors",
"(",
"f",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"wrapper",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"f",
"(",
"self",
",",
"request",
... | Catches specific errors in admin actions and shows a friendly error. | [
"Catches",
"specific",
"errors",
"in",
"admin",
"actions",
"and",
"shows",
"a",
"friendly",
"error",
"."
] | train | https://github.com/WhyNotHugo/django-afip/blob/5fb73213f1fe86ca52b501ffd0737911ef26ddb3/django_afip/admin.py#L24-L59 |
MKLab-ITI/reveal-graph-embedding | reveal_graph_embedding/embedding/text_graph.py | augmented_tf_idf | def augmented_tf_idf(attribute_matrix):
"""
Performs augmented TF-IDF normalization on a bag-of-words vector representation of data.
Augmented TF-IDF introduced in: Manning, C. D., Raghavan, P., & Schütze, H. (2008).
Introduction to information retrieval (Vol. 1, p. 6).
Cambridge: Cambridge university press.
Input: - attribute_matrix: A bag-of-words vector representation in SciPy sparse matrix format.
Output: - attribute_matrix: The same matrix after augmented tf-idf normalization.
"""
number_of_documents = attribute_matrix.shape[0]
max_term_frequencies = np.ones(number_of_documents, dtype=np.float64)
idf_array = np.ones(attribute_matrix.shape[1], dtype=np.float64)
# Calculate inverse document frequency
attribute_matrix = attribute_matrix.tocsc()
for j in range(attribute_matrix.shape[1]):
document_frequency = attribute_matrix.getcol(j).data.size
if document_frequency > 1:
idf_array[j] = np.log(number_of_documents/document_frequency)
# Calculate maximum term frequencies for a user
attribute_matrix = attribute_matrix.tocsr()
for i in range(attribute_matrix.shape[0]):
max_term_frequency = attribute_matrix.getrow(i).data
if max_term_frequency.size > 0:
max_term_frequency = max_term_frequency.max()
if max_term_frequency > 0.0:
max_term_frequencies[i] = max_term_frequency
# Do augmented tf-idf normalization
attribute_matrix = attribute_matrix.tocoo()
attribute_matrix.data = 0.5 + np.divide(0.5*attribute_matrix.data, np.multiply((max_term_frequencies[attribute_matrix.row]), (idf_array[attribute_matrix.col])))
attribute_matrix = attribute_matrix.tocsr()
return attribute_matrix | python | def augmented_tf_idf(attribute_matrix):
"""
Performs augmented TF-IDF normalization on a bag-of-words vector representation of data.
Augmented TF-IDF introduced in: Manning, C. D., Raghavan, P., & Schütze, H. (2008).
Introduction to information retrieval (Vol. 1, p. 6).
Cambridge: Cambridge university press.
Input: - attribute_matrix: A bag-of-words vector representation in SciPy sparse matrix format.
Output: - attribute_matrix: The same matrix after augmented tf-idf normalization.
"""
number_of_documents = attribute_matrix.shape[0]
max_term_frequencies = np.ones(number_of_documents, dtype=np.float64)
idf_array = np.ones(attribute_matrix.shape[1], dtype=np.float64)
# Calculate inverse document frequency
attribute_matrix = attribute_matrix.tocsc()
for j in range(attribute_matrix.shape[1]):
document_frequency = attribute_matrix.getcol(j).data.size
if document_frequency > 1:
idf_array[j] = np.log(number_of_documents/document_frequency)
# Calculate maximum term frequencies for a user
attribute_matrix = attribute_matrix.tocsr()
for i in range(attribute_matrix.shape[0]):
max_term_frequency = attribute_matrix.getrow(i).data
if max_term_frequency.size > 0:
max_term_frequency = max_term_frequency.max()
if max_term_frequency > 0.0:
max_term_frequencies[i] = max_term_frequency
# Do augmented tf-idf normalization
attribute_matrix = attribute_matrix.tocoo()
attribute_matrix.data = 0.5 + np.divide(0.5*attribute_matrix.data, np.multiply((max_term_frequencies[attribute_matrix.row]), (idf_array[attribute_matrix.col])))
attribute_matrix = attribute_matrix.tocsr()
return attribute_matrix | [
"def",
"augmented_tf_idf",
"(",
"attribute_matrix",
")",
":",
"number_of_documents",
"=",
"attribute_matrix",
".",
"shape",
"[",
"0",
"]",
"max_term_frequencies",
"=",
"np",
".",
"ones",
"(",
"number_of_documents",
",",
"dtype",
"=",
"np",
".",
"float64",
")",
... | Performs augmented TF-IDF normalization on a bag-of-words vector representation of data.
Augmented TF-IDF introduced in: Manning, C. D., Raghavan, P., & Schütze, H. (2008).
Introduction to information retrieval (Vol. 1, p. 6).
Cambridge: Cambridge university press.
Input: - attribute_matrix: A bag-of-words vector representation in SciPy sparse matrix format.
Output: - attribute_matrix: The same matrix after augmented tf-idf normalization. | [
"Performs",
"augmented",
"TF",
"-",
"IDF",
"normalization",
"on",
"a",
"bag",
"-",
"of",
"-",
"words",
"vector",
"representation",
"of",
"data",
"."
] | train | https://github.com/MKLab-ITI/reveal-graph-embedding/blob/eda862687aa5a64b79c6b12de1b4dca6ce986dc8/reveal_graph_embedding/embedding/text_graph.py#L48-L86 |
MKLab-ITI/reveal-graph-embedding | reveal_graph_embedding/common.py | get_file_row_generator | def get_file_row_generator(file_path, separator, encoding=None):
"""
Reads an separated value file row by row.
Inputs: - file_path: The path of the separated value format file.
- separator: The delimiter among values (e.g. ",", "\t", " ")
- encoding: The encoding used in the stored text.
Yields: - words: A list of strings corresponding to each of the file's rows.
"""
with open(file_path, encoding=encoding) as file_object:
for line in file_object:
words = line.strip().split(separator)
yield words | python | def get_file_row_generator(file_path, separator, encoding=None):
"""
Reads an separated value file row by row.
Inputs: - file_path: The path of the separated value format file.
- separator: The delimiter among values (e.g. ",", "\t", " ")
- encoding: The encoding used in the stored text.
Yields: - words: A list of strings corresponding to each of the file's rows.
"""
with open(file_path, encoding=encoding) as file_object:
for line in file_object:
words = line.strip().split(separator)
yield words | [
"def",
"get_file_row_generator",
"(",
"file_path",
",",
"separator",
",",
"encoding",
"=",
"None",
")",
":",
"with",
"open",
"(",
"file_path",
",",
"encoding",
"=",
"encoding",
")",
"as",
"file_object",
":",
"for",
"line",
"in",
"file_object",
":",
"words",
... | Reads an separated value file row by row.
Inputs: - file_path: The path of the separated value format file.
- separator: The delimiter among values (e.g. ",", "\t", " ")
- encoding: The encoding used in the stored text.
Yields: - words: A list of strings corresponding to each of the file's rows. | [
"Reads",
"an",
"separated",
"value",
"file",
"row",
"by",
"row",
"."
] | train | https://github.com/MKLab-ITI/reveal-graph-embedding/blob/eda862687aa5a64b79c6b12de1b4dca6ce986dc8/reveal_graph_embedding/common.py#L36-L49 |
MKLab-ITI/reveal-graph-embedding | reveal_graph_embedding/common.py | store_pickle | def store_pickle(file_path, data):
"""
Pickle some data to a given path.
Inputs: - file_path: Target file path.
- data: The python object to be serialized via pickle.
"""
pkl_file = open(file_path, 'wb')
pickle.dump(data, pkl_file)
pkl_file.close() | python | def store_pickle(file_path, data):
"""
Pickle some data to a given path.
Inputs: - file_path: Target file path.
- data: The python object to be serialized via pickle.
"""
pkl_file = open(file_path, 'wb')
pickle.dump(data, pkl_file)
pkl_file.close() | [
"def",
"store_pickle",
"(",
"file_path",
",",
"data",
")",
":",
"pkl_file",
"=",
"open",
"(",
"file_path",
",",
"'wb'",
")",
"pickle",
".",
"dump",
"(",
"data",
",",
"pkl_file",
")",
"pkl_file",
".",
"close",
"(",
")"
] | Pickle some data to a given path.
Inputs: - file_path: Target file path.
- data: The python object to be serialized via pickle. | [
"Pickle",
"some",
"data",
"to",
"a",
"given",
"path",
"."
] | train | https://github.com/MKLab-ITI/reveal-graph-embedding/blob/eda862687aa5a64b79c6b12de1b4dca6ce986dc8/reveal_graph_embedding/common.py#L52-L61 |
MKLab-ITI/reveal-graph-embedding | reveal_graph_embedding/common.py | load_pickle | def load_pickle(file_path):
"""
Unpickle some data from a given path.
Input: - file_path: Target file path.
Output: - data: The python object that was serialized and stored in disk.
"""
pkl_file = open(file_path, 'rb')
data = pickle.load(pkl_file)
pkl_file.close()
return data | python | def load_pickle(file_path):
"""
Unpickle some data from a given path.
Input: - file_path: Target file path.
Output: - data: The python object that was serialized and stored in disk.
"""
pkl_file = open(file_path, 'rb')
data = pickle.load(pkl_file)
pkl_file.close()
return data | [
"def",
"load_pickle",
"(",
"file_path",
")",
":",
"pkl_file",
"=",
"open",
"(",
"file_path",
",",
"'rb'",
")",
"data",
"=",
"pickle",
".",
"load",
"(",
"pkl_file",
")",
"pkl_file",
".",
"close",
"(",
")",
"return",
"data"
] | Unpickle some data from a given path.
Input: - file_path: Target file path.
Output: - data: The python object that was serialized and stored in disk. | [
"Unpickle",
"some",
"data",
"from",
"a",
"given",
"path",
"."
] | train | https://github.com/MKLab-ITI/reveal-graph-embedding/blob/eda862687aa5a64b79c6b12de1b4dca6ce986dc8/reveal_graph_embedding/common.py#L64-L75 |
MultipedRobotics/pyxl320 | bin/set_id.py | makeServoIDPacket | def makeServoIDPacket(curr_id, new_id):
"""
Given the current ID, returns a packet to set the servo to a new ID
"""
pkt = Packet.makeWritePacket(curr_id, xl320.XL320_ID, [new_id])
return pkt | python | def makeServoIDPacket(curr_id, new_id):
"""
Given the current ID, returns a packet to set the servo to a new ID
"""
pkt = Packet.makeWritePacket(curr_id, xl320.XL320_ID, [new_id])
return pkt | [
"def",
"makeServoIDPacket",
"(",
"curr_id",
",",
"new_id",
")",
":",
"pkt",
"=",
"Packet",
".",
"makeWritePacket",
"(",
"curr_id",
",",
"xl320",
".",
"XL320_ID",
",",
"[",
"new_id",
"]",
")",
"return",
"pkt"
] | Given the current ID, returns a packet to set the servo to a new ID | [
"Given",
"the",
"current",
"ID",
"returns",
"a",
"packet",
"to",
"set",
"the",
"servo",
"to",
"a",
"new",
"ID"
] | train | https://github.com/MultipedRobotics/pyxl320/blob/1a56540e208b028ee47d5fa0a7c7babcee0d9214/bin/set_id.py#L28-L33 |
MKLab-ITI/reveal-graph-embedding | reveal_graph_embedding/embedding/common.py | normalize_rows | def normalize_rows(features):
"""
This performs row normalization to 1 of community embedding features.
Input: - X in R^(nxC_n): The community indicator matrix.
Output: - X_norm in R^(nxC_n): The row normalized community indicator matrix.
"""
# Normalize each row of term frequencies to 1
features = features.tocsr()
features = normalize(features, norm="l2")
# for i in range(features.shape[0]):
# term_frequency = features.getrow(i).data
# if term_frequency.size > 0:
# features.data[features.indptr[i]: features.indptr[i + 1]] =\
# features.data[features.indptr[i]: features.indptr[i + 1]]/np.sqrt(np.sum(np.power(term_frequency, 2)))
return features | python | def normalize_rows(features):
"""
This performs row normalization to 1 of community embedding features.
Input: - X in R^(nxC_n): The community indicator matrix.
Output: - X_norm in R^(nxC_n): The row normalized community indicator matrix.
"""
# Normalize each row of term frequencies to 1
features = features.tocsr()
features = normalize(features, norm="l2")
# for i in range(features.shape[0]):
# term_frequency = features.getrow(i).data
# if term_frequency.size > 0:
# features.data[features.indptr[i]: features.indptr[i + 1]] =\
# features.data[features.indptr[i]: features.indptr[i + 1]]/np.sqrt(np.sum(np.power(term_frequency, 2)))
return features | [
"def",
"normalize_rows",
"(",
"features",
")",
":",
"# Normalize each row of term frequencies to 1",
"features",
"=",
"features",
".",
"tocsr",
"(",
")",
"features",
"=",
"normalize",
"(",
"features",
",",
"norm",
"=",
"\"l2\"",
")",
"# for i in range(features.shape[0... | This performs row normalization to 1 of community embedding features.
Input: - X in R^(nxC_n): The community indicator matrix.
Output: - X_norm in R^(nxC_n): The row normalized community indicator matrix. | [
"This",
"performs",
"row",
"normalization",
"to",
"1",
"of",
"community",
"embedding",
"features",
"."
] | train | https://github.com/MKLab-ITI/reveal-graph-embedding/blob/eda862687aa5a64b79c6b12de1b4dca6ce986dc8/reveal_graph_embedding/embedding/common.py#L29-L46 |
MKLab-ITI/reveal-graph-embedding | reveal_graph_embedding/embedding/common.py | normalize_columns | def normalize_columns(features):
"""
This performs column normalization of community embedding features.
Input: - X in R^(nxC_n): The community indicator matrix.
Output: - X_norm in R^(nxC_n): The tf-idf + row normalized community indicator matrix.
"""
# Calculate inverse document frequency.
features = features.tocsc()
for j in range(features.shape[1]):
document_frequency = features.getcol(j).data.size
if document_frequency > 1:
features.data[features.indptr[j]: features.indptr[j + 1]] =\
features.data[features.indptr[j]: features.indptr[j + 1]]/np.sqrt(np.log(document_frequency))
features = features.tocsr()
return features | python | def normalize_columns(features):
"""
This performs column normalization of community embedding features.
Input: - X in R^(nxC_n): The community indicator matrix.
Output: - X_norm in R^(nxC_n): The tf-idf + row normalized community indicator matrix.
"""
# Calculate inverse document frequency.
features = features.tocsc()
for j in range(features.shape[1]):
document_frequency = features.getcol(j).data.size
if document_frequency > 1:
features.data[features.indptr[j]: features.indptr[j + 1]] =\
features.data[features.indptr[j]: features.indptr[j + 1]]/np.sqrt(np.log(document_frequency))
features = features.tocsr()
return features | [
"def",
"normalize_columns",
"(",
"features",
")",
":",
"# Calculate inverse document frequency.",
"features",
"=",
"features",
".",
"tocsc",
"(",
")",
"for",
"j",
"in",
"range",
"(",
"features",
".",
"shape",
"[",
"1",
"]",
")",
":",
"document_frequency",
"=",... | This performs column normalization of community embedding features.
Input: - X in R^(nxC_n): The community indicator matrix.
Output: - X_norm in R^(nxC_n): The tf-idf + row normalized community indicator matrix. | [
"This",
"performs",
"column",
"normalization",
"of",
"community",
"embedding",
"features",
"."
] | train | https://github.com/MKLab-ITI/reveal-graph-embedding/blob/eda862687aa5a64b79c6b12de1b4dca6ce986dc8/reveal_graph_embedding/embedding/common.py#L49-L67 |
MKLab-ITI/reveal-graph-embedding | reveal_graph_embedding/eps_randomwalk/push.py | pagerank_limit_push | def pagerank_limit_push(s, r, w_i, a_i, push_node, rho):
"""
Performs a random step without a self-loop.
"""
# Calculate the A and B quantities to infinity
A_inf = rho*r[push_node]
B_inf = (1-rho)*r[push_node]
# Update approximate Pagerank and residual vectors
s[push_node] += A_inf
r[push_node] = 0.0
# Update residual vector at push node's adjacent nodes
r[a_i] += B_inf * w_i | python | def pagerank_limit_push(s, r, w_i, a_i, push_node, rho):
"""
Performs a random step without a self-loop.
"""
# Calculate the A and B quantities to infinity
A_inf = rho*r[push_node]
B_inf = (1-rho)*r[push_node]
# Update approximate Pagerank and residual vectors
s[push_node] += A_inf
r[push_node] = 0.0
# Update residual vector at push node's adjacent nodes
r[a_i] += B_inf * w_i | [
"def",
"pagerank_limit_push",
"(",
"s",
",",
"r",
",",
"w_i",
",",
"a_i",
",",
"push_node",
",",
"rho",
")",
":",
"# Calculate the A and B quantities to infinity",
"A_inf",
"=",
"rho",
"*",
"r",
"[",
"push_node",
"]",
"B_inf",
"=",
"(",
"1",
"-",
"rho",
... | Performs a random step without a self-loop. | [
"Performs",
"a",
"random",
"step",
"without",
"a",
"self",
"-",
"loop",
"."
] | train | https://github.com/MKLab-ITI/reveal-graph-embedding/blob/eda862687aa5a64b79c6b12de1b4dca6ce986dc8/reveal_graph_embedding/eps_randomwalk/push.py#L4-L17 |
MKLab-ITI/reveal-graph-embedding | reveal_graph_embedding/eps_randomwalk/push.py | pagerank_lazy_push | def pagerank_lazy_push(s, r, w_i, a_i, push_node, rho, lazy):
"""
Performs a random step with a self-loop.
Introduced in: Andersen, R., Chung, F., & Lang, K. (2006, October).
Local graph partitioning using pagerank vectors.
In Foundations of Computer Science, 2006. FOCS'06. 47th Annual IEEE Symposium on (pp. 475-486). IEEE.
"""
# Calculate the A, B and C quantities
A = rho*r[push_node]
B = (1-rho)*(1 - lazy)*r[push_node]
C = (1-rho)*lazy*(r[push_node])
# Update approximate Pagerank and residual vectors
s[push_node] += A
r[push_node] = C
# Update residual vector at push node's adjacent nodes
r[a_i] += B * w_i | python | def pagerank_lazy_push(s, r, w_i, a_i, push_node, rho, lazy):
"""
Performs a random step with a self-loop.
Introduced in: Andersen, R., Chung, F., & Lang, K. (2006, October).
Local graph partitioning using pagerank vectors.
In Foundations of Computer Science, 2006. FOCS'06. 47th Annual IEEE Symposium on (pp. 475-486). IEEE.
"""
# Calculate the A, B and C quantities
A = rho*r[push_node]
B = (1-rho)*(1 - lazy)*r[push_node]
C = (1-rho)*lazy*(r[push_node])
# Update approximate Pagerank and residual vectors
s[push_node] += A
r[push_node] = C
# Update residual vector at push node's adjacent nodes
r[a_i] += B * w_i | [
"def",
"pagerank_lazy_push",
"(",
"s",
",",
"r",
",",
"w_i",
",",
"a_i",
",",
"push_node",
",",
"rho",
",",
"lazy",
")",
":",
"# Calculate the A, B and C quantities",
"A",
"=",
"rho",
"*",
"r",
"[",
"push_node",
"]",
"B",
"=",
"(",
"1",
"-",
"rho",
"... | Performs a random step with a self-loop.
Introduced in: Andersen, R., Chung, F., & Lang, K. (2006, October).
Local graph partitioning using pagerank vectors.
In Foundations of Computer Science, 2006. FOCS'06. 47th Annual IEEE Symposium on (pp. 475-486). IEEE. | [
"Performs",
"a",
"random",
"step",
"with",
"a",
"self",
"-",
"loop",
"."
] | train | https://github.com/MKLab-ITI/reveal-graph-embedding/blob/eda862687aa5a64b79c6b12de1b4dca6ce986dc8/reveal_graph_embedding/eps_randomwalk/push.py#L20-L38 |
MKLab-ITI/reveal-graph-embedding | reveal_graph_embedding/eps_randomwalk/push.py | cumulative_pagerank_difference_limit_push | def cumulative_pagerank_difference_limit_push(s, r, w_i, a_i, push_node, rho):
"""
Performs a random step without a self-loop.
Inputs: - s: A NumPy array that contains the approximate absorbing random walk cumulative probabilities.
- r: A NumPy array that contains the residual probability distribution.
- w_i: A NumPy array of probability transition weights from the seed nodes to its adjacent nodes.
- a_i: A NumPy array of the nodes adjacent to the push node.
- push_node: The node from which the residual probability is pushed to its adjacent nodes.
- rho: The restart probability.
Outputs: - s in 1xn: A NumPy array that contains the approximate absorbing random walk cumulative probabilities.
- r in 1xn: A NumPy array that contains the residual probability distribution.
"""
# Calculate the commute quantity
commute = (1-rho)*r[push_node]
# Update approximate regularized commute and residual vectors
r[push_node] = 0.0
# Update residual vector at push node's adjacent nodes
commute_probabilities = commute * w_i
s[a_i] += commute_probabilities
r[a_i] += commute_probabilities | python | def cumulative_pagerank_difference_limit_push(s, r, w_i, a_i, push_node, rho):
"""
Performs a random step without a self-loop.
Inputs: - s: A NumPy array that contains the approximate absorbing random walk cumulative probabilities.
- r: A NumPy array that contains the residual probability distribution.
- w_i: A NumPy array of probability transition weights from the seed nodes to its adjacent nodes.
- a_i: A NumPy array of the nodes adjacent to the push node.
- push_node: The node from which the residual probability is pushed to its adjacent nodes.
- rho: The restart probability.
Outputs: - s in 1xn: A NumPy array that contains the approximate absorbing random walk cumulative probabilities.
- r in 1xn: A NumPy array that contains the residual probability distribution.
"""
# Calculate the commute quantity
commute = (1-rho)*r[push_node]
# Update approximate regularized commute and residual vectors
r[push_node] = 0.0
# Update residual vector at push node's adjacent nodes
commute_probabilities = commute * w_i
s[a_i] += commute_probabilities
r[a_i] += commute_probabilities | [
"def",
"cumulative_pagerank_difference_limit_push",
"(",
"s",
",",
"r",
",",
"w_i",
",",
"a_i",
",",
"push_node",
",",
"rho",
")",
":",
"# Calculate the commute quantity",
"commute",
"=",
"(",
"1",
"-",
"rho",
")",
"*",
"r",
"[",
"push_node",
"]",
"# Update ... | Performs a random step without a self-loop.
Inputs: - s: A NumPy array that contains the approximate absorbing random walk cumulative probabilities.
- r: A NumPy array that contains the residual probability distribution.
- w_i: A NumPy array of probability transition weights from the seed nodes to its adjacent nodes.
- a_i: A NumPy array of the nodes adjacent to the push node.
- push_node: The node from which the residual probability is pushed to its adjacent nodes.
- rho: The restart probability.
Outputs: - s in 1xn: A NumPy array that contains the approximate absorbing random walk cumulative probabilities.
- r in 1xn: A NumPy array that contains the residual probability distribution. | [
"Performs",
"a",
"random",
"step",
"without",
"a",
"self",
"-",
"loop",
"."
] | train | https://github.com/MKLab-ITI/reveal-graph-embedding/blob/eda862687aa5a64b79c6b12de1b4dca6ce986dc8/reveal_graph_embedding/eps_randomwalk/push.py#L41-L64 |
mozilla-services/pyramid_multiauth | pyramid_multiauth/__init__.py | includeme | def includeme(config):
"""Include pyramid_multiauth into a pyramid configurator.
This function provides a hook for pyramid to include the default settings
for auth via pyramid_multiauth. Activate it like so:
config.include("pyramid_multiauth")
This will pull the list of registered authn policies from the deployment
settings, and configure and install each policy in order. The policies to
use can be specified in one of two ways:
* as the name of a module to be included.
* as the name of a callable along with a set of parameters.
Here's an example suite of settings:
multiauth.policies = ipauth1 ipauth2 pyramid_browserid
multiauth.policy.ipauth1.use = pyramid_ipauth.IPAuthentictionPolicy
multiauth.policy.ipauth1.ipaddrs = 123.123.0.0/16
multiauth.policy.ipauth1.userid = local1
multiauth.policy.ipauth2.use = pyramid_ipauth.IPAuthentictionPolicy
multiauth.policy.ipauth2.ipaddrs = 124.124.0.0/16
multiauth.policy.ipauth2.userid = local2
This will configure a MultiAuthenticationPolicy with three policy objects.
The first two will be IPAuthenticationPolicy objects created by passing
in the specified keyword arguments. The third will be a BrowserID
authentication policy just like you would get from executing:
config.include("pyramid_browserid")
As a side-effect, the configuration will also get the additional views
that pyramid_browserid sets up by default.
The *group finder function* and the *authorization policy* are also read
from configuration if specified:
multiauth.authorization_policy = mypyramidapp.acl.Custom
multiauth.groupfinder = mypyramidapp.acl.groupfinder
"""
# Grab the pyramid-wide settings, to look for any auth config.
settings = config.get_settings()
# Hook up a default AuthorizationPolicy.
# Get the authorization policy from config if present.
# Default ACLAuthorizationPolicy is usually what you want.
authz_class = settings.get("multiauth.authorization_policy",
"pyramid.authorization.ACLAuthorizationPolicy")
authz_policy = config.maybe_dotted(authz_class)()
# If the app configures one explicitly then this will get overridden.
# In autocommit mode this needs to be done before setting the authn policy.
config.set_authorization_policy(authz_policy)
# Get the groupfinder from config if present.
groupfinder = settings.get("multiauth.groupfinder", None)
groupfinder = config.maybe_dotted(groupfinder)
# Look for callable policy definitions.
# Suck them all out at once and store them in a dict for later use.
policy_definitions = get_policy_definitions(settings)
# Read and process the list of policies to load.
# We build up a list of callables which can be executed at config commit
# time to obtain the final list of policies.
# Yeah, it's complicated. But we want to be able to inherit any default
# views or other config added by the sub-policies when they're included.
# Process policies in reverse order so that things at the front of the
# list can override things at the back of the list.
policy_factories = []
policy_names = settings.get("multiauth.policies", "").split()
for policy_name in reversed(policy_names):
if policy_name in policy_definitions:
# It's a policy defined using a callable.
# Just append it straight to the list.
definition = policy_definitions[policy_name]
factory = config.maybe_dotted(definition.pop("use"))
policy_factories.append((factory, policy_name, definition))
else:
# It's a module to be directly included.
try:
factory = policy_factory_from_module(config, policy_name)
except ImportError:
err = "pyramid_multiauth: policy %r has no settings "\
"and is not importable" % (policy_name,)
raise ValueError(err)
policy_factories.append((factory, policy_name, {}))
# OK. We now have a list of callbacks which need to be called at
# commit time, and will return the policies in reverse order.
# Register a special action to pull them into our list of policies.
policies = []
def grab_policies():
for factory, name, kwds in policy_factories:
policy = factory(**kwds)
if policy:
policy._pyramid_multiauth_name = name
if not policies or policy is not policies[0]:
# Remember, they're being processed in reverse order.
# So each new policy needs to go at the front.
policies.insert(0, policy)
config.action(None, grab_policies, order=PHASE2_CONFIG)
authn_policy = MultiAuthenticationPolicy(policies, groupfinder)
config.set_authentication_policy(authn_policy) | python | def includeme(config):
"""Include pyramid_multiauth into a pyramid configurator.
This function provides a hook for pyramid to include the default settings
for auth via pyramid_multiauth. Activate it like so:
config.include("pyramid_multiauth")
This will pull the list of registered authn policies from the deployment
settings, and configure and install each policy in order. The policies to
use can be specified in one of two ways:
* as the name of a module to be included.
* as the name of a callable along with a set of parameters.
Here's an example suite of settings:
multiauth.policies = ipauth1 ipauth2 pyramid_browserid
multiauth.policy.ipauth1.use = pyramid_ipauth.IPAuthentictionPolicy
multiauth.policy.ipauth1.ipaddrs = 123.123.0.0/16
multiauth.policy.ipauth1.userid = local1
multiauth.policy.ipauth2.use = pyramid_ipauth.IPAuthentictionPolicy
multiauth.policy.ipauth2.ipaddrs = 124.124.0.0/16
multiauth.policy.ipauth2.userid = local2
This will configure a MultiAuthenticationPolicy with three policy objects.
The first two will be IPAuthenticationPolicy objects created by passing
in the specified keyword arguments. The third will be a BrowserID
authentication policy just like you would get from executing:
config.include("pyramid_browserid")
As a side-effect, the configuration will also get the additional views
that pyramid_browserid sets up by default.
The *group finder function* and the *authorization policy* are also read
from configuration if specified:
multiauth.authorization_policy = mypyramidapp.acl.Custom
multiauth.groupfinder = mypyramidapp.acl.groupfinder
"""
# Grab the pyramid-wide settings, to look for any auth config.
settings = config.get_settings()
# Hook up a default AuthorizationPolicy.
# Get the authorization policy from config if present.
# Default ACLAuthorizationPolicy is usually what you want.
authz_class = settings.get("multiauth.authorization_policy",
"pyramid.authorization.ACLAuthorizationPolicy")
authz_policy = config.maybe_dotted(authz_class)()
# If the app configures one explicitly then this will get overridden.
# In autocommit mode this needs to be done before setting the authn policy.
config.set_authorization_policy(authz_policy)
# Get the groupfinder from config if present.
groupfinder = settings.get("multiauth.groupfinder", None)
groupfinder = config.maybe_dotted(groupfinder)
# Look for callable policy definitions.
# Suck them all out at once and store them in a dict for later use.
policy_definitions = get_policy_definitions(settings)
# Read and process the list of policies to load.
# We build up a list of callables which can be executed at config commit
# time to obtain the final list of policies.
# Yeah, it's complicated. But we want to be able to inherit any default
# views or other config added by the sub-policies when they're included.
# Process policies in reverse order so that things at the front of the
# list can override things at the back of the list.
policy_factories = []
policy_names = settings.get("multiauth.policies", "").split()
for policy_name in reversed(policy_names):
if policy_name in policy_definitions:
# It's a policy defined using a callable.
# Just append it straight to the list.
definition = policy_definitions[policy_name]
factory = config.maybe_dotted(definition.pop("use"))
policy_factories.append((factory, policy_name, definition))
else:
# It's a module to be directly included.
try:
factory = policy_factory_from_module(config, policy_name)
except ImportError:
err = "pyramid_multiauth: policy %r has no settings "\
"and is not importable" % (policy_name,)
raise ValueError(err)
policy_factories.append((factory, policy_name, {}))
# OK. We now have a list of callbacks which need to be called at
# commit time, and will return the policies in reverse order.
# Register a special action to pull them into our list of policies.
policies = []
def grab_policies():
for factory, name, kwds in policy_factories:
policy = factory(**kwds)
if policy:
policy._pyramid_multiauth_name = name
if not policies or policy is not policies[0]:
# Remember, they're being processed in reverse order.
# So each new policy needs to go at the front.
policies.insert(0, policy)
config.action(None, grab_policies, order=PHASE2_CONFIG)
authn_policy = MultiAuthenticationPolicy(policies, groupfinder)
config.set_authentication_policy(authn_policy) | [
"def",
"includeme",
"(",
"config",
")",
":",
"# Grab the pyramid-wide settings, to look for any auth config.",
"settings",
"=",
"config",
".",
"get_settings",
"(",
")",
"# Hook up a default AuthorizationPolicy.",
"# Get the authorization policy from config if present.",
"# Default AC... | Include pyramid_multiauth into a pyramid configurator.
This function provides a hook for pyramid to include the default settings
for auth via pyramid_multiauth. Activate it like so:
config.include("pyramid_multiauth")
This will pull the list of registered authn policies from the deployment
settings, and configure and install each policy in order. The policies to
use can be specified in one of two ways:
* as the name of a module to be included.
* as the name of a callable along with a set of parameters.
Here's an example suite of settings:
multiauth.policies = ipauth1 ipauth2 pyramid_browserid
multiauth.policy.ipauth1.use = pyramid_ipauth.IPAuthentictionPolicy
multiauth.policy.ipauth1.ipaddrs = 123.123.0.0/16
multiauth.policy.ipauth1.userid = local1
multiauth.policy.ipauth2.use = pyramid_ipauth.IPAuthentictionPolicy
multiauth.policy.ipauth2.ipaddrs = 124.124.0.0/16
multiauth.policy.ipauth2.userid = local2
This will configure a MultiAuthenticationPolicy with three policy objects.
The first two will be IPAuthenticationPolicy objects created by passing
in the specified keyword arguments. The third will be a BrowserID
authentication policy just like you would get from executing:
config.include("pyramid_browserid")
As a side-effect, the configuration will also get the additional views
that pyramid_browserid sets up by default.
The *group finder function* and the *authorization policy* are also read
from configuration if specified:
multiauth.authorization_policy = mypyramidapp.acl.Custom
multiauth.groupfinder = mypyramidapp.acl.groupfinder | [
"Include",
"pyramid_multiauth",
"into",
"a",
"pyramid",
"configurator",
"."
] | train | https://github.com/mozilla-services/pyramid_multiauth/blob/9548aa55f726920a666791d7c89ac2b9779d2bc1/pyramid_multiauth/__init__.py#L188-L290 |
mozilla-services/pyramid_multiauth | pyramid_multiauth/__init__.py | policy_factory_from_module | def policy_factory_from_module(config, module):
"""Create a policy factory that works by config.include()'ing a module.
This function does some trickery with the Pyramid config system. Loosely,
it does config.include(module), and then sucks out information about the
authn policy that was registered. It's complicated by pyramid's delayed-
commit system, which means we have to do the work via callbacks.
"""
# Remember the policy that's active before including the module, if any.
orig_policy = config.registry.queryUtility(IAuthenticationPolicy)
# Include the module, so we get any default views etc.
config.include(module)
# That might have registered and commited a new policy object.
policy = config.registry.queryUtility(IAuthenticationPolicy)
if policy is not None and policy is not orig_policy:
return lambda: policy
# Or it might have set up a pending action to register one later.
# Find the most recent IAuthenticationPolicy action, and grab
# out the registering function so we can call it ourselves.
for action in reversed(config.action_state.actions):
# Extract the discriminator and callable. This is complicated by
# Pyramid 1.3 changing action from a tuple to a dict.
try:
discriminator = action["discriminator"]
callable = action["callable"]
except TypeError: # pragma: nocover
discriminator = action[0] # pragma: nocover
callable = action[1] # pragma: nocover
# If it's not setting the authn policy, keep looking.
if discriminator is not IAuthenticationPolicy:
continue
# Otherwise, wrap it up so we can extract the registered object.
def grab_policy(register=callable):
old_policy = config.registry.queryUtility(IAuthenticationPolicy)
register()
new_policy = config.registry.queryUtility(IAuthenticationPolicy)
config.registry.registerUtility(old_policy, IAuthenticationPolicy)
return new_policy
return grab_policy
# Or it might not have done *anything*.
# So return a null policy factory.
return lambda: None | python | def policy_factory_from_module(config, module):
"""Create a policy factory that works by config.include()'ing a module.
This function does some trickery with the Pyramid config system. Loosely,
it does config.include(module), and then sucks out information about the
authn policy that was registered. It's complicated by pyramid's delayed-
commit system, which means we have to do the work via callbacks.
"""
# Remember the policy that's active before including the module, if any.
orig_policy = config.registry.queryUtility(IAuthenticationPolicy)
# Include the module, so we get any default views etc.
config.include(module)
# That might have registered and commited a new policy object.
policy = config.registry.queryUtility(IAuthenticationPolicy)
if policy is not None and policy is not orig_policy:
return lambda: policy
# Or it might have set up a pending action to register one later.
# Find the most recent IAuthenticationPolicy action, and grab
# out the registering function so we can call it ourselves.
for action in reversed(config.action_state.actions):
# Extract the discriminator and callable. This is complicated by
# Pyramid 1.3 changing action from a tuple to a dict.
try:
discriminator = action["discriminator"]
callable = action["callable"]
except TypeError: # pragma: nocover
discriminator = action[0] # pragma: nocover
callable = action[1] # pragma: nocover
# If it's not setting the authn policy, keep looking.
if discriminator is not IAuthenticationPolicy:
continue
# Otherwise, wrap it up so we can extract the registered object.
def grab_policy(register=callable):
old_policy = config.registry.queryUtility(IAuthenticationPolicy)
register()
new_policy = config.registry.queryUtility(IAuthenticationPolicy)
config.registry.registerUtility(old_policy, IAuthenticationPolicy)
return new_policy
return grab_policy
# Or it might not have done *anything*.
# So return a null policy factory.
return lambda: None | [
"def",
"policy_factory_from_module",
"(",
"config",
",",
"module",
")",
":",
"# Remember the policy that's active before including the module, if any.",
"orig_policy",
"=",
"config",
".",
"registry",
".",
"queryUtility",
"(",
"IAuthenticationPolicy",
")",
"# Include the module,... | Create a policy factory that works by config.include()'ing a module.
This function does some trickery with the Pyramid config system. Loosely,
it does config.include(module), and then sucks out information about the
authn policy that was registered. It's complicated by pyramid's delayed-
commit system, which means we have to do the work via callbacks. | [
"Create",
"a",
"policy",
"factory",
"that",
"works",
"by",
"config",
".",
"include",
"()",
"ing",
"a",
"module",
"."
] | train | https://github.com/mozilla-services/pyramid_multiauth/blob/9548aa55f726920a666791d7c89ac2b9779d2bc1/pyramid_multiauth/__init__.py#L293-L336 |
mozilla-services/pyramid_multiauth | pyramid_multiauth/__init__.py | get_policy_definitions | def get_policy_definitions(settings):
"""Find all multiauth policy definitions from the settings dict.
This function processes the paster deployment settings looking for items
that start with "multiauth.policy.<policyname>.". It pulls them all out
into a dict indexed by the policy name.
"""
policy_definitions = {}
for name in settings:
if not name.startswith("multiauth.policy."):
continue
value = settings[name]
name = name[len("multiauth.policy."):]
policy_name, setting_name = name.split(".", 1)
if policy_name not in policy_definitions:
policy_definitions[policy_name] = {}
policy_definitions[policy_name][setting_name] = value
return policy_definitions | python | def get_policy_definitions(settings):
"""Find all multiauth policy definitions from the settings dict.
This function processes the paster deployment settings looking for items
that start with "multiauth.policy.<policyname>.". It pulls them all out
into a dict indexed by the policy name.
"""
policy_definitions = {}
for name in settings:
if not name.startswith("multiauth.policy."):
continue
value = settings[name]
name = name[len("multiauth.policy."):]
policy_name, setting_name = name.split(".", 1)
if policy_name not in policy_definitions:
policy_definitions[policy_name] = {}
policy_definitions[policy_name][setting_name] = value
return policy_definitions | [
"def",
"get_policy_definitions",
"(",
"settings",
")",
":",
"policy_definitions",
"=",
"{",
"}",
"for",
"name",
"in",
"settings",
":",
"if",
"not",
"name",
".",
"startswith",
"(",
"\"multiauth.policy.\"",
")",
":",
"continue",
"value",
"=",
"settings",
"[",
... | Find all multiauth policy definitions from the settings dict.
This function processes the paster deployment settings looking for items
that start with "multiauth.policy.<policyname>.". It pulls them all out
into a dict indexed by the policy name. | [
"Find",
"all",
"multiauth",
"policy",
"definitions",
"from",
"the",
"settings",
"dict",
"."
] | train | https://github.com/mozilla-services/pyramid_multiauth/blob/9548aa55f726920a666791d7c89ac2b9779d2bc1/pyramid_multiauth/__init__.py#L339-L356 |
Robpol86/flake8-pydocstyle | flake8_pydocstyle.py | load_file | def load_file(filename):
"""Read file to memory.
For stdin sourced files, this function does something super duper incredibly hacky and shameful. So so shameful. I'm
obtaining the original source code of the target module from the only instance of pycodestyle.Checker through the
Python garbage collector. Flake8's API doesn't give me the original source code of the module we are checking.
Instead it has pycodestyle give me an AST object of the module (already parsed). This unfortunately loses valuable
information like the kind of quotes used for strings (no way to know if a docstring was surrounded by triple double
quotes or just one single quote, thereby rendering pydocstyle's D300 error as unusable).
This will break one day. I'm sure of it. For now it fixes https://github.com/Robpol86/flake8-pydocstyle/issues/2
:param str filename: File path or 'stdin'. From Main().filename.
:return: First item is the filename or 'stdin', second are the contents of the file.
:rtype: tuple
"""
if filename in ('stdin', '-', None):
instances = [i for i in gc.get_objects() if isinstance(i, pycodestyle.Checker) or isinstance(i, pep8.Checker)]
if len(instances) != 1:
raise ValueError('Expected only 1 instance of pycodestyle.Checker, got {0} instead.'.format(len(instances)))
return 'stdin', ''.join(instances[0].lines)
with codecs.open(filename, encoding='utf-8') as handle:
return filename, handle.read() | python | def load_file(filename):
"""Read file to memory.
For stdin sourced files, this function does something super duper incredibly hacky and shameful. So so shameful. I'm
obtaining the original source code of the target module from the only instance of pycodestyle.Checker through the
Python garbage collector. Flake8's API doesn't give me the original source code of the module we are checking.
Instead it has pycodestyle give me an AST object of the module (already parsed). This unfortunately loses valuable
information like the kind of quotes used for strings (no way to know if a docstring was surrounded by triple double
quotes or just one single quote, thereby rendering pydocstyle's D300 error as unusable).
This will break one day. I'm sure of it. For now it fixes https://github.com/Robpol86/flake8-pydocstyle/issues/2
:param str filename: File path or 'stdin'. From Main().filename.
:return: First item is the filename or 'stdin', second are the contents of the file.
:rtype: tuple
"""
if filename in ('stdin', '-', None):
instances = [i for i in gc.get_objects() if isinstance(i, pycodestyle.Checker) or isinstance(i, pep8.Checker)]
if len(instances) != 1:
raise ValueError('Expected only 1 instance of pycodestyle.Checker, got {0} instead.'.format(len(instances)))
return 'stdin', ''.join(instances[0].lines)
with codecs.open(filename, encoding='utf-8') as handle:
return filename, handle.read() | [
"def",
"load_file",
"(",
"filename",
")",
":",
"if",
"filename",
"in",
"(",
"'stdin'",
",",
"'-'",
",",
"None",
")",
":",
"instances",
"=",
"[",
"i",
"for",
"i",
"in",
"gc",
".",
"get_objects",
"(",
")",
"if",
"isinstance",
"(",
"i",
",",
"pycodest... | Read file to memory.
For stdin sourced files, this function does something super duper incredibly hacky and shameful. So so shameful. I'm
obtaining the original source code of the target module from the only instance of pycodestyle.Checker through the
Python garbage collector. Flake8's API doesn't give me the original source code of the module we are checking.
Instead it has pycodestyle give me an AST object of the module (already parsed). This unfortunately loses valuable
information like the kind of quotes used for strings (no way to know if a docstring was surrounded by triple double
quotes or just one single quote, thereby rendering pydocstyle's D300 error as unusable).
This will break one day. I'm sure of it. For now it fixes https://github.com/Robpol86/flake8-pydocstyle/issues/2
:param str filename: File path or 'stdin'. From Main().filename.
:return: First item is the filename or 'stdin', second are the contents of the file.
:rtype: tuple | [
"Read",
"file",
"to",
"memory",
"."
] | train | https://github.com/Robpol86/flake8-pydocstyle/blob/657425541e1d868a6a5241a83c3a16a9a715d6b5/flake8_pydocstyle.py#L20-L43 |
Robpol86/flake8-pydocstyle | flake8_pydocstyle.py | ignore | def ignore(code):
"""Should this code be ignored.
:param str code: Error code (e.g. D201).
:return: True if code should be ignored, False otherwise.
:rtype: bool
"""
if code in Main.options['ignore']:
return True
if any(c in code for c in Main.options['ignore']):
return True
return False | python | def ignore(code):
"""Should this code be ignored.
:param str code: Error code (e.g. D201).
:return: True if code should be ignored, False otherwise.
:rtype: bool
"""
if code in Main.options['ignore']:
return True
if any(c in code for c in Main.options['ignore']):
return True
return False | [
"def",
"ignore",
"(",
"code",
")",
":",
"if",
"code",
"in",
"Main",
".",
"options",
"[",
"'ignore'",
"]",
":",
"return",
"True",
"if",
"any",
"(",
"c",
"in",
"code",
"for",
"c",
"in",
"Main",
".",
"options",
"[",
"'ignore'",
"]",
")",
":",
"retur... | Should this code be ignored.
:param str code: Error code (e.g. D201).
:return: True if code should be ignored, False otherwise.
:rtype: bool | [
"Should",
"this",
"code",
"be",
"ignored",
"."
] | train | https://github.com/Robpol86/flake8-pydocstyle/blob/657425541e1d868a6a5241a83c3a16a9a715d6b5/flake8_pydocstyle.py#L46-L58 |
Robpol86/flake8-pydocstyle | flake8_pydocstyle.py | Main.add_options | def add_options(cls, parser):
"""Add options to flake8.
:param parser: optparse.OptionParser from pycodestyle.
"""
parser.add_option('--show-pydocstyle', action='store_true', help='show explanation of each PEP 257 error')
parser.config_options.append('show-pydocstyle') | python | def add_options(cls, parser):
"""Add options to flake8.
:param parser: optparse.OptionParser from pycodestyle.
"""
parser.add_option('--show-pydocstyle', action='store_true', help='show explanation of each PEP 257 error')
parser.config_options.append('show-pydocstyle') | [
"def",
"add_options",
"(",
"cls",
",",
"parser",
")",
":",
"parser",
".",
"add_option",
"(",
"'--show-pydocstyle'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"'show explanation of each PEP 257 error'",
")",
"parser",
".",
"config_options",
".",
"append... | Add options to flake8.
:param parser: optparse.OptionParser from pycodestyle. | [
"Add",
"options",
"to",
"flake8",
"."
] | train | https://github.com/Robpol86/flake8-pydocstyle/blob/657425541e1d868a6a5241a83c3a16a9a715d6b5/flake8_pydocstyle.py#L78-L84 |
Robpol86/flake8-pydocstyle | flake8_pydocstyle.py | Main.parse_options | def parse_options(cls, options):
"""Read parsed options from flake8.
:param options: Options to add to flake8's command line options.
"""
# Handle flake8 options.
cls.options['explain'] = bool(options.show_pydocstyle)
cls.options['ignore'] = options.ignore
# Handle pydocstyle options.
config = pydocstyle.RawConfigParser()
for file_name in pydocstyle.ConfigurationParser.PROJECT_CONFIG_FILES:
if config.read(os.path.join(os.path.abspath('.'), file_name)):
break
if not config.has_section('pydocstyle'):
return
native_options = dict()
for option in config.options('pydocstyle'):
if option == 'ignore':
native_options['ignore'] = config.get('pydocstyle', option)
if option in ('explain', 'source'):
native_options[option] = config.getboolean('pydocstyle', option)
native_options['show-source'] = native_options.pop('source', None)
if native_options.get('ignore'):
native_options['ignore'] = native_options['ignore'].split(',')
cls.options.update(dict((k, v) for k, v in native_options.items() if v)) | python | def parse_options(cls, options):
"""Read parsed options from flake8.
:param options: Options to add to flake8's command line options.
"""
# Handle flake8 options.
cls.options['explain'] = bool(options.show_pydocstyle)
cls.options['ignore'] = options.ignore
# Handle pydocstyle options.
config = pydocstyle.RawConfigParser()
for file_name in pydocstyle.ConfigurationParser.PROJECT_CONFIG_FILES:
if config.read(os.path.join(os.path.abspath('.'), file_name)):
break
if not config.has_section('pydocstyle'):
return
native_options = dict()
for option in config.options('pydocstyle'):
if option == 'ignore':
native_options['ignore'] = config.get('pydocstyle', option)
if option in ('explain', 'source'):
native_options[option] = config.getboolean('pydocstyle', option)
native_options['show-source'] = native_options.pop('source', None)
if native_options.get('ignore'):
native_options['ignore'] = native_options['ignore'].split(',')
cls.options.update(dict((k, v) for k, v in native_options.items() if v)) | [
"def",
"parse_options",
"(",
"cls",
",",
"options",
")",
":",
"# Handle flake8 options.",
"cls",
".",
"options",
"[",
"'explain'",
"]",
"=",
"bool",
"(",
"options",
".",
"show_pydocstyle",
")",
"cls",
".",
"options",
"[",
"'ignore'",
"]",
"=",
"options",
"... | Read parsed options from flake8.
:param options: Options to add to flake8's command line options. | [
"Read",
"parsed",
"options",
"from",
"flake8",
"."
] | train | https://github.com/Robpol86/flake8-pydocstyle/blob/657425541e1d868a6a5241a83c3a16a9a715d6b5/flake8_pydocstyle.py#L87-L112 |
Robpol86/flake8-pydocstyle | flake8_pydocstyle.py | Main.run | def run(self):
"""Run analysis on a single file."""
pydocstyle.Error.explain = self.options['explain']
filename, source = load_file(self.filename)
for error in pydocstyle.PEP257Checker().check_source(source, filename):
if not hasattr(error, 'code') or ignore(error.code):
continue
lineno = error.line
offset = 0 # Column number starting from 0.
explanation = error.explanation if pydocstyle.Error.explain else ''
text = '{0} {1}{2}'.format(error.code, error.message.split(': ', 1)[1], explanation)
yield lineno, offset, text, Main | python | def run(self):
"""Run analysis on a single file."""
pydocstyle.Error.explain = self.options['explain']
filename, source = load_file(self.filename)
for error in pydocstyle.PEP257Checker().check_source(source, filename):
if not hasattr(error, 'code') or ignore(error.code):
continue
lineno = error.line
offset = 0 # Column number starting from 0.
explanation = error.explanation if pydocstyle.Error.explain else ''
text = '{0} {1}{2}'.format(error.code, error.message.split(': ', 1)[1], explanation)
yield lineno, offset, text, Main | [
"def",
"run",
"(",
"self",
")",
":",
"pydocstyle",
".",
"Error",
".",
"explain",
"=",
"self",
".",
"options",
"[",
"'explain'",
"]",
"filename",
",",
"source",
"=",
"load_file",
"(",
"self",
".",
"filename",
")",
"for",
"error",
"in",
"pydocstyle",
"."... | Run analysis on a single file. | [
"Run",
"analysis",
"on",
"a",
"single",
"file",
"."
] | train | https://github.com/Robpol86/flake8-pydocstyle/blob/657425541e1d868a6a5241a83c3a16a9a715d6b5/flake8_pydocstyle.py#L114-L125 |
WhyNotHugo/django-afip | django_afip/pdf.py | ReceiptBarcodeGenerator.numbers | def numbers(self):
""""
Returns the barcode's number without the verification digit.
:return: list(int)
"""
numstring = '{:011d}{:02d}{:04d}{}{}'.format(
self._receipt.point_of_sales.owner.cuit, # 11 digits
int(self._receipt.receipt_type.code), # 2 digits
self._receipt.point_of_sales.number, # point of sales
self._receipt.validation.cae, # 14 digits
self._receipt.validation.cae_expiration.strftime('%Y%m%d'), # 8
)
return [int(num) for num in numstring] | python | def numbers(self):
""""
Returns the barcode's number without the verification digit.
:return: list(int)
"""
numstring = '{:011d}{:02d}{:04d}{}{}'.format(
self._receipt.point_of_sales.owner.cuit, # 11 digits
int(self._receipt.receipt_type.code), # 2 digits
self._receipt.point_of_sales.number, # point of sales
self._receipt.validation.cae, # 14 digits
self._receipt.validation.cae_expiration.strftime('%Y%m%d'), # 8
)
return [int(num) for num in numstring] | [
"def",
"numbers",
"(",
"self",
")",
":",
"numstring",
"=",
"'{:011d}{:02d}{:04d}{}{}'",
".",
"format",
"(",
"self",
".",
"_receipt",
".",
"point_of_sales",
".",
"owner",
".",
"cuit",
",",
"# 11 digits",
"int",
"(",
"self",
".",
"_receipt",
".",
"receipt_type... | Returns the barcode's number without the verification digit.
:return: list(int) | [
"Returns",
"the",
"barcode",
"s",
"number",
"without",
"the",
"verification",
"digit",
"."
] | train | https://github.com/WhyNotHugo/django-afip/blob/5fb73213f1fe86ca52b501ffd0737911ef26ddb3/django_afip/pdf.py#L22-L35 |
WhyNotHugo/django-afip | django_afip/pdf.py | ReceiptBarcodeGenerator.verification_digit | def verification_digit(numbers):
"""
Returns the verification digit for a given numbre.
The verification digit is calculated as follows:
* A = sum of all even-positioned numbers
* B = A * 3
* C = sum of all odd-positioned numbers
* D = B + C
* The results is the smallset number N, such that (D + N) % 10 == 0
NOTE: Afip's documentation seems to have odd an even mixed up in the
explanation, but all examples follow the above algorithm.
:param list(int) numbers): The numbers for which the digits is to be
calculated.
:return: int
"""
a = sum(numbers[::2])
b = a * 3
c = sum(numbers[1::2])
d = b + c
e = d % 10
if e == 0:
return e
return 10 - e | python | def verification_digit(numbers):
"""
Returns the verification digit for a given numbre.
The verification digit is calculated as follows:
* A = sum of all even-positioned numbers
* B = A * 3
* C = sum of all odd-positioned numbers
* D = B + C
* The results is the smallset number N, such that (D + N) % 10 == 0
NOTE: Afip's documentation seems to have odd an even mixed up in the
explanation, but all examples follow the above algorithm.
:param list(int) numbers): The numbers for which the digits is to be
calculated.
:return: int
"""
a = sum(numbers[::2])
b = a * 3
c = sum(numbers[1::2])
d = b + c
e = d % 10
if e == 0:
return e
return 10 - e | [
"def",
"verification_digit",
"(",
"numbers",
")",
":",
"a",
"=",
"sum",
"(",
"numbers",
"[",
":",
":",
"2",
"]",
")",
"b",
"=",
"a",
"*",
"3",
"c",
"=",
"sum",
"(",
"numbers",
"[",
"1",
":",
":",
"2",
"]",
")",
"d",
"=",
"b",
"+",
"c",
"e... | Returns the verification digit for a given numbre.
The verification digit is calculated as follows:
* A = sum of all even-positioned numbers
* B = A * 3
* C = sum of all odd-positioned numbers
* D = B + C
* The results is the smallset number N, such that (D + N) % 10 == 0
NOTE: Afip's documentation seems to have odd an even mixed up in the
explanation, but all examples follow the above algorithm.
:param list(int) numbers): The numbers for which the digits is to be
calculated.
:return: int | [
"Returns",
"the",
"verification",
"digit",
"for",
"a",
"given",
"numbre",
"."
] | train | https://github.com/WhyNotHugo/django-afip/blob/5fb73213f1fe86ca52b501ffd0737911ef26ddb3/django_afip/pdf.py#L38-L64 |
WhyNotHugo/django-afip | django_afip/pdf.py | ReceiptBarcodeGenerator.full_number | def full_number(self):
"""
Returns the full number including the verification digit.
:return: str
"""
return '{}{}'.format(
''.join(str(n) for n in self.numbers),
ReceiptBarcodeGenerator.verification_digit(self.numbers),
) | python | def full_number(self):
"""
Returns the full number including the verification digit.
:return: str
"""
return '{}{}'.format(
''.join(str(n) for n in self.numbers),
ReceiptBarcodeGenerator.verification_digit(self.numbers),
) | [
"def",
"full_number",
"(",
"self",
")",
":",
"return",
"'{}{}'",
".",
"format",
"(",
"''",
".",
"join",
"(",
"str",
"(",
"n",
")",
"for",
"n",
"in",
"self",
".",
"numbers",
")",
",",
"ReceiptBarcodeGenerator",
".",
"verification_digit",
"(",
"self",
".... | Returns the full number including the verification digit.
:return: str | [
"Returns",
"the",
"full",
"number",
"including",
"the",
"verification",
"digit",
"."
] | train | https://github.com/WhyNotHugo/django-afip/blob/5fb73213f1fe86ca52b501ffd0737911ef26ddb3/django_afip/pdf.py#L67-L76 |
MKLab-ITI/reveal-graph-embedding | reveal_graph_embedding/datautil/snow_datautil/snow_read_data.py | read_adjacency_matrix | def read_adjacency_matrix(file_path, separator, numbering="matlab"):
"""
Reads an edge list in csv format and returns the adjacency matrix in SciPy Sparse COOrdinate format.
Inputs: - file_path: The path where the adjacency matrix is stored.
- separator: The delimiter among values (e.g. ",", "\t", " ")
- numbering: Array numbering style: * "matlab"
* "c"
Outputs: - adjacency_matrix: The adjacency matrix in SciPy Sparse COOrdinate format.
"""
# Open file
file_row_generator = get_file_row_generator(file_path, separator)
file_row = next(file_row_generator)
number_of_rows = file_row[1]
number_of_columns = file_row[3]
directed = file_row[7]
if directed == "True":
directed = True
elif directed == "False":
directed = False
else:
print("Invalid metadata.")
raise RuntimeError
# Initialize lists for row and column sparse matrix arguments
row = list()
col = list()
data = list()
append_row = row.append
append_col = col.append
append_data = data.append
# Read all file rows
for file_row in file_row_generator:
source_node = np.int64(file_row[0])
target_node = np.int64(file_row[1])
edge_weight = np.float64(file_row[2])
# Add edge
append_row(source_node)
append_col(target_node)
append_data(edge_weight)
# Since this is an undirected network also add the reciprocal edge
if not directed:
if source_node != target_node:
append_row(target_node)
append_col(source_node)
append_data(edge_weight)
row = np.array(row, dtype=np.int64)
col = np.array(col, dtype=np.int64)
data = np.array(data, dtype=np.float64)
if numbering == "matlab":
row -= 1
col -= 1
elif numbering == "c":
pass
else:
print("Invalid numbering style.")
raise RuntimeError
# Form sparse adjacency matrix
adjacency_matrix = spsp.coo_matrix((data, (row, col)), shape=(number_of_rows, number_of_columns))
return adjacency_matrix | python | def read_adjacency_matrix(file_path, separator, numbering="matlab"):
"""
Reads an edge list in csv format and returns the adjacency matrix in SciPy Sparse COOrdinate format.
Inputs: - file_path: The path where the adjacency matrix is stored.
- separator: The delimiter among values (e.g. ",", "\t", " ")
- numbering: Array numbering style: * "matlab"
* "c"
Outputs: - adjacency_matrix: The adjacency matrix in SciPy Sparse COOrdinate format.
"""
# Open file
file_row_generator = get_file_row_generator(file_path, separator)
file_row = next(file_row_generator)
number_of_rows = file_row[1]
number_of_columns = file_row[3]
directed = file_row[7]
if directed == "True":
directed = True
elif directed == "False":
directed = False
else:
print("Invalid metadata.")
raise RuntimeError
# Initialize lists for row and column sparse matrix arguments
row = list()
col = list()
data = list()
append_row = row.append
append_col = col.append
append_data = data.append
# Read all file rows
for file_row in file_row_generator:
source_node = np.int64(file_row[0])
target_node = np.int64(file_row[1])
edge_weight = np.float64(file_row[2])
# Add edge
append_row(source_node)
append_col(target_node)
append_data(edge_weight)
# Since this is an undirected network also add the reciprocal edge
if not directed:
if source_node != target_node:
append_row(target_node)
append_col(source_node)
append_data(edge_weight)
row = np.array(row, dtype=np.int64)
col = np.array(col, dtype=np.int64)
data = np.array(data, dtype=np.float64)
if numbering == "matlab":
row -= 1
col -= 1
elif numbering == "c":
pass
else:
print("Invalid numbering style.")
raise RuntimeError
# Form sparse adjacency matrix
adjacency_matrix = spsp.coo_matrix((data, (row, col)), shape=(number_of_rows, number_of_columns))
return adjacency_matrix | [
"def",
"read_adjacency_matrix",
"(",
"file_path",
",",
"separator",
",",
"numbering",
"=",
"\"matlab\"",
")",
":",
"# Open file",
"file_row_generator",
"=",
"get_file_row_generator",
"(",
"file_path",
",",
"separator",
")",
"file_row",
"=",
"next",
"(",
"file_row_ge... | Reads an edge list in csv format and returns the adjacency matrix in SciPy Sparse COOrdinate format.
Inputs: - file_path: The path where the adjacency matrix is stored.
- separator: The delimiter among values (e.g. ",", "\t", " ")
- numbering: Array numbering style: * "matlab"
* "c"
Outputs: - adjacency_matrix: The adjacency matrix in SciPy Sparse COOrdinate format. | [
"Reads",
"an",
"edge",
"list",
"in",
"csv",
"format",
"and",
"returns",
"the",
"adjacency",
"matrix",
"in",
"SciPy",
"Sparse",
"COOrdinate",
"format",
"."
] | train | https://github.com/MKLab-ITI/reveal-graph-embedding/blob/eda862687aa5a64b79c6b12de1b4dca6ce986dc8/reveal_graph_embedding/datautil/snow_datautil/snow_read_data.py#L10-L78 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.