hexsha stringlengths 40 40 | repo stringlengths 7 114 | path stringlengths 4 124 | license listlengths 1 9 | language stringclasses 1
value | identifier stringlengths 1 71 | return_type stringlengths 1 749 ⌀ | original_string stringlengths 76 22.7k | original_docstring stringlengths 16 7.61k | docstring stringlengths 16 2.47k | docstring_tokens listlengths 6 477 | code stringlengths 14 10.2k | code_tokens listlengths 6 996 | short_docstring stringlengths 2 644 | short_docstring_tokens listlengths 1 116 | comment listlengths 1 89 | parameters listlengths 0 64 | docstring_params dict |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
fa27bd78a3a1643ee8493c82bb94d5e94f1a7685 | callumparr/TALON-paper-2020 | ebv/talon_GTF_2_transcript_bed.py | [
"MIT"
] | Python | create_metadata_entry | <not_specific> | def create_metadata_entry(gtf_transcript):
""" Given a GTF transcript (in list form), determine which novelty types
the transcript has. """
meta = gtf_transcript[-1]
transcript_ID = parse_out_transcript_ID(meta)
known = 0
ISM = 0
prefix_ISM = 0
suffix_ISM = 0
NIC = 0
NNC = ... | Given a GTF transcript (in list form), determine which novelty types
the transcript has. | Given a GTF transcript (in list form), determine which novelty types
the transcript has. | [
"Given",
"a",
"GTF",
"transcript",
"(",
"in",
"list",
"form",
")",
"determine",
"which",
"novelty",
"types",
"the",
"transcript",
"has",
"."
] | def create_metadata_entry(gtf_transcript):
meta = gtf_transcript[-1]
transcript_ID = parse_out_transcript_ID(meta)
known = 0
ISM = 0
prefix_ISM = 0
suffix_ISM = 0
NIC = 0
NNC = 0
genomic = 0
antisense = 0
intergenic = 0
if "ISM_transcript" in meta: ISM = 1
if "ISM-pre... | [
"def",
"create_metadata_entry",
"(",
"gtf_transcript",
")",
":",
"meta",
"=",
"gtf_transcript",
"[",
"-",
"1",
"]",
"transcript_ID",
"=",
"parse_out_transcript_ID",
"(",
"meta",
")",
"known",
"=",
"0",
"ISM",
"=",
"0",
"prefix_ISM",
"=",
"0",
"suffix_ISM",
"... | Given a GTF transcript (in list form), determine which novelty types
the transcript has. | [
"Given",
"a",
"GTF",
"transcript",
"(",
"in",
"list",
"form",
")",
"determine",
"which",
"novelty",
"types",
"the",
"transcript",
"has",
"."
] | [
"\"\"\" Given a GTF transcript (in list form), determine which novelty types\n the transcript has. \"\"\""
] | [
{
"param": "gtf_transcript",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "gtf_transcript",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
1762c6b3f10644b6153a8853d1edbe4b2e19dc02 | callumparr/TALON-paper-2020 | plotting_scripts/plot_read_length_distributions.py | [
"MIT"
] | Python | density_plot_with_mapping | null | def density_plot_with_mapping(data, outdir):
""" Plot read length distribution for each dataset"""
fname = outdir + "/read_lengths.png"
g = sns.FacetGrid(data, row = 'name', hue = 'celltype')
g.map(sns.distplot, "read_length")
g.savefig(fname, dpi = 600) | Plot read length distribution for each dataset | Plot read length distribution for each dataset | [
"Plot",
"read",
"length",
"distribution",
"for",
"each",
"dataset"
] | def density_plot_with_mapping(data, outdir):
fname = outdir + "/read_lengths.png"
g = sns.FacetGrid(data, row = 'name', hue = 'celltype')
g.map(sns.distplot, "read_length")
g.savefig(fname, dpi = 600) | [
"def",
"density_plot_with_mapping",
"(",
"data",
",",
"outdir",
")",
":",
"fname",
"=",
"outdir",
"+",
"\"/read_lengths.png\"",
"g",
"=",
"sns",
".",
"FacetGrid",
"(",
"data",
",",
"row",
"=",
"'name'",
",",
"hue",
"=",
"'celltype'",
")",
"g",
".",
"map"... | Plot read length distribution for each dataset | [
"Plot",
"read",
"length",
"distribution",
"for",
"each",
"dataset"
] | [
"\"\"\" Plot read length distribution for each dataset\"\"\""
] | [
{
"param": "data",
"type": null
},
{
"param": "outdir",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "data",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "outdir",
"type": null,
"docstring": null,
"docstring_tokens":... |
2fff85dfd2ce3b35eb831551f6a5e5ff559e97ab | callumparr/TALON-paper-2020 | ebv/create_intervals.py | [
"MIT"
] | Python | create_end_piece | <not_specific> | def create_end_piece(pos, strand, dist):
""" Creates a zero based interval of length 'dist' that starts inside the
transcript and ends with the transcript end."""
if strand == "+":
interval_start = pos - dist
interval_end = pos
elif strand == "-":
interval_start = pos
... | Creates a zero based interval of length 'dist' that starts inside the
transcript and ends with the transcript end. | Creates a zero based interval of length 'dist' that starts inside the
transcript and ends with the transcript end. | [
"Creates",
"a",
"zero",
"based",
"interval",
"of",
"length",
"'",
"dist",
"'",
"that",
"starts",
"inside",
"the",
"transcript",
"and",
"ends",
"with",
"the",
"transcript",
"end",
"."
] | def create_end_piece(pos, strand, dist):
if strand == "+":
interval_start = pos - dist
interval_end = pos
elif strand == "-":
interval_start = pos
interval_end = pos + dist
else:
raise ValueError("Strand must be '+' or '-'.")
return interval_start, interval_end | [
"def",
"create_end_piece",
"(",
"pos",
",",
"strand",
",",
"dist",
")",
":",
"if",
"strand",
"==",
"\"+\"",
":",
"interval_start",
"=",
"pos",
"-",
"dist",
"interval_end",
"=",
"pos",
"elif",
"strand",
"==",
"\"-\"",
":",
"interval_start",
"=",
"pos",
"i... | Creates a zero based interval of length 'dist' that starts inside the
transcript and ends with the transcript end. | [
"Creates",
"a",
"zero",
"based",
"interval",
"of",
"length",
"'",
"dist",
"'",
"that",
"starts",
"inside",
"the",
"transcript",
"and",
"ends",
"with",
"the",
"transcript",
"end",
"."
] | [
"\"\"\" Creates a zero based interval of length 'dist' that starts inside the\n transcript and ends with the transcript end.\"\"\""
] | [
{
"param": "pos",
"type": null
},
{
"param": "strand",
"type": null
},
{
"param": "dist",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "pos",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "strand",
"type": null,
"docstring": null,
"docstring_tokens": ... |
2fff85dfd2ce3b35eb831551f6a5e5ff559e97ab | callumparr/TALON-paper-2020 | ebv/create_intervals.py | [
"MIT"
] | Python | create_interval | <not_specific> | def create_interval(pos, pos_type, dist):
""" Creates a zero-based interval around the provided position (must also be
zero-based) of size dist on either side. """
if pos_type == "left":
start = pos - dist
end = pos + dist + 1
elif pos_type == "right":
start = pos - dist - ... | Creates a zero-based interval around the provided position (must also be
zero-based) of size dist on either side. | Creates a zero-based interval around the provided position (must also be
zero-based) of size dist on either side. | [
"Creates",
"a",
"zero",
"-",
"based",
"interval",
"around",
"the",
"provided",
"position",
"(",
"must",
"also",
"be",
"zero",
"-",
"based",
")",
"of",
"size",
"dist",
"on",
"either",
"side",
"."
] | def create_interval(pos, pos_type, dist):
if pos_type == "left":
start = pos - dist
end = pos + dist + 1
elif pos_type == "right":
start = pos - dist - 1
end = pos + dist
return start, end | [
"def",
"create_interval",
"(",
"pos",
",",
"pos_type",
",",
"dist",
")",
":",
"if",
"pos_type",
"==",
"\"left\"",
":",
"start",
"=",
"pos",
"-",
"dist",
"end",
"=",
"pos",
"+",
"dist",
"+",
"1",
"elif",
"pos_type",
"==",
"\"right\"",
":",
"start",
"=... | Creates a zero-based interval around the provided position (must also be
zero-based) of size dist on either side. | [
"Creates",
"a",
"zero",
"-",
"based",
"interval",
"around",
"the",
"provided",
"position",
"(",
"must",
"also",
"be",
"zero",
"-",
"based",
")",
"of",
"size",
"dist",
"on",
"either",
"side",
"."
] | [
"\"\"\" Creates a zero-based interval around the provided position (must also be \n zero-based) of size dist on either side. \"\"\""
] | [
{
"param": "pos",
"type": null
},
{
"param": "pos_type",
"type": null
},
{
"param": "dist",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "pos",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "pos_type",
"type": null,
"docstring": null,
"docstring_tokens"... |
344752f30434ee140448c41178bb369c152c2924 | callumparr/TALON-paper-2020 | plotting_scripts/plot_GC_content_by_DE.py | [
"MIT"
] | Python | violin_plot | null | def violin_plot(data, colname, ymax, fname):
""" Plot a violin plot with the length of each read by novelty category"""
sns.set_context("paper", font_scale=1.3)
ax = sns.stripplot(x='DE_type', y=colname, data=data, color="black",
alpha = 0.5, size = 1.5, jitter = True)
ax = sns... | Plot a violin plot with the length of each read by novelty category | Plot a violin plot with the length of each read by novelty category | [
"Plot",
"a",
"violin",
"plot",
"with",
"the",
"length",
"of",
"each",
"read",
"by",
"novelty",
"category"
] | def violin_plot(data, colname, ymax, fname):
sns.set_context("paper", font_scale=1.3)
ax = sns.stripplot(x='DE_type', y=colname, data=data, color="black",
alpha = 0.5, size = 1.5, jitter = True)
ax = sns.boxplot(x='DE_type', y=colname, data=data, palette = "Blues")
add_stat_annot... | [
"def",
"violin_plot",
"(",
"data",
",",
"colname",
",",
"ymax",
",",
"fname",
")",
":",
"sns",
".",
"set_context",
"(",
"\"paper\"",
",",
"font_scale",
"=",
"1.3",
")",
"ax",
"=",
"sns",
".",
"stripplot",
"(",
"x",
"=",
"'DE_type'",
",",
"y",
"=",
... | Plot a violin plot with the length of each read by novelty category | [
"Plot",
"a",
"violin",
"plot",
"with",
"the",
"length",
"of",
"each",
"read",
"by",
"novelty",
"category"
] | [
"\"\"\" Plot a violin plot with the length of each read by novelty category\"\"\"",
"#ax = sns.violinplot(x='DE_type', y=colname, legend = False,",
"# data=data,",
"# #order=cat_order,",
"# linewidth = 1,",
"# inner = 'box', cut =... | [
{
"param": "data",
"type": null
},
{
"param": "colname",
"type": null
},
{
"param": "ymax",
"type": null
},
{
"param": "fname",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "data",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "colname",
"type": null,
"docstring": null,
"docstring_tokens"... |
344752f30434ee140448c41178bb369c152c2924 | callumparr/TALON-paper-2020 | plotting_scripts/plot_GC_content_by_DE.py | [
"MIT"
] | Python | compute_all_GCs | <not_specific> | def compute_all_GCs(fasta):
""" For each fasta transcript:
1) Extract gene name
2) Compute GC content of sequence
3) Record gene name, transcript ID, and GC content in pandas df.
"""
gene_names = []
transcript_IDs = []
GC_content = []
try:
with gzip.open(fa... | For each fasta transcript:
1) Extract gene name
2) Compute GC content of sequence
3) Record gene name, transcript ID, and GC content in pandas df.
| For each fasta transcript:
1) Extract gene name
2) Compute GC content of sequence
3) Record gene name, transcript ID, and GC content in pandas df. | [
"For",
"each",
"fasta",
"transcript",
":",
"1",
")",
"Extract",
"gene",
"name",
"2",
")",
"Compute",
"GC",
"content",
"of",
"sequence",
"3",
")",
"Record",
"gene",
"name",
"transcript",
"ID",
"and",
"GC",
"content",
"in",
"pandas",
"df",
"."
] | def compute_all_GCs(fasta):
gene_names = []
transcript_IDs = []
GC_content = []
try:
with gzip.open(fasta, "rt") as handle:
for record in SeqIO.parse(handle, "fasta"):
split_ID = (record.id).split("|")
gene_name = split_ID[5]
transcript... | [
"def",
"compute_all_GCs",
"(",
"fasta",
")",
":",
"gene_names",
"=",
"[",
"]",
"transcript_IDs",
"=",
"[",
"]",
"GC_content",
"=",
"[",
"]",
"try",
":",
"with",
"gzip",
".",
"open",
"(",
"fasta",
",",
"\"rt\"",
")",
"as",
"handle",
":",
"for",
"recor... | For each fasta transcript:
1) Extract gene name
2) Compute GC content of sequence
3) Record gene name, transcript ID, and GC content in pandas df. | [
"For",
"each",
"fasta",
"transcript",
":",
"1",
")",
"Extract",
"gene",
"name",
"2",
")",
"Compute",
"GC",
"content",
"of",
"sequence",
"3",
")",
"Record",
"gene",
"name",
"transcript",
"ID",
"and",
"GC",
"content",
"in",
"pandas",
"df",
"."
] | [
"\"\"\" For each fasta transcript:\n 1) Extract gene name\n 2) Compute GC content of sequence\n 3) Record gene name, transcript ID, and GC content in pandas df.\n \"\"\"",
"# Convert lists into a pandas data frame"
] | [
{
"param": "fasta",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "fasta",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
a1c48b37d0181d84876a1e5487600f23318a1d9b | callumparr/TALON-paper-2020 | Figure_4/analysis_utils/parse_RNA-PET_bedtools_output.py | [
"MIT"
] | Python | make_transcript_PET_dict | <not_specific> | def make_transcript_PET_dict(infile):
""" Given a bedtools intersect file, this function creates a dictionary
mapping each transcript_ID to a set containing the RNA-PET IDs that
it matched to. """
transcript_2_pet = {}
with open(infile, 'r') as f:
for line in f:
line... | Given a bedtools intersect file, this function creates a dictionary
mapping each transcript_ID to a set containing the RNA-PET IDs that
it matched to. | Given a bedtools intersect file, this function creates a dictionary
mapping each transcript_ID to a set containing the RNA-PET IDs that
it matched to. | [
"Given",
"a",
"bedtools",
"intersect",
"file",
"this",
"function",
"creates",
"a",
"dictionary",
"mapping",
"each",
"transcript_ID",
"to",
"a",
"set",
"containing",
"the",
"RNA",
"-",
"PET",
"IDs",
"that",
"it",
"matched",
"to",
"."
] | def make_transcript_PET_dict(infile):
transcript_2_pet = {}
with open(infile, 'r') as f:
for line in f:
line = line.strip()
entry = line.split("\t")
transcript_ID = entry[3]
rna_pet_ID = entry[9]
if transcript_ID in transcript_2_pet:
... | [
"def",
"make_transcript_PET_dict",
"(",
"infile",
")",
":",
"transcript_2_pet",
"=",
"{",
"}",
"with",
"open",
"(",
"infile",
",",
"'r'",
")",
"as",
"f",
":",
"for",
"line",
"in",
"f",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"entry",
"=",
... | Given a bedtools intersect file, this function creates a dictionary
mapping each transcript_ID to a set containing the RNA-PET IDs that
it matched to. | [
"Given",
"a",
"bedtools",
"intersect",
"file",
"this",
"function",
"creates",
"a",
"dictionary",
"mapping",
"each",
"transcript_ID",
"to",
"a",
"set",
"containing",
"the",
"RNA",
"-",
"PET",
"IDs",
"that",
"it",
"matched",
"to",
"."
] | [
"\"\"\" Given a bedtools intersect file, this function creates a dictionary\n mapping each transcript_ID to a set containing the RNA-PET IDs that\n it matched to. \"\"\""
] | [
{
"param": "infile",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "infile",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
a8c56e0033cc1007b27d512e4cd4bc9e8587fe7a | callumparr/TALON-paper-2020 | ebv/get_transcript_start_end_intervals.py | [
"MIT"
] | Python | make_intervals | <not_specific> | def make_intervals(entry, dist):
""" Extract start and end position of entry and return each as bed interval
"""
strand = entry[5]
transcript_start = int(entry[1])
transcript_end = int(entry[2])
# Set start and end based on strand
if strand == "+":
start_interval_1, start_interval_2... | Extract start and end position of entry and return each as bed interval
| Extract start and end position of entry and return each as bed interval | [
"Extract",
"start",
"and",
"end",
"position",
"of",
"entry",
"and",
"return",
"each",
"as",
"bed",
"interval"
] | def make_intervals(entry, dist):
strand = entry[5]
transcript_start = int(entry[1])
transcript_end = int(entry[2])
if strand == "+":
start_interval_1, start_interval_2 = cI.create_interval(transcript_start,
"left", dist)
end... | [
"def",
"make_intervals",
"(",
"entry",
",",
"dist",
")",
":",
"strand",
"=",
"entry",
"[",
"5",
"]",
"transcript_start",
"=",
"int",
"(",
"entry",
"[",
"1",
"]",
")",
"transcript_end",
"=",
"int",
"(",
"entry",
"[",
"2",
"]",
")",
"if",
"strand",
"... | Extract start and end position of entry and return each as bed interval | [
"Extract",
"start",
"and",
"end",
"position",
"of",
"entry",
"and",
"return",
"each",
"as",
"bed",
"interval"
] | [
"\"\"\" Extract start and end position of entry and return each as bed interval\n \"\"\"",
"# Set start and end based on strand"
] | [
{
"param": "entry",
"type": null
},
{
"param": "dist",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "entry",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "dist",
"type": null,
"docstring": null,
"docstring_tokens": ... |
d4bf3201b359b7022baff1dd0d6f1ecf44867e41 | callumparr/TALON-paper-2020 | ebv/check_last_n_transcript_seq_for_PA_motif.py | [
"MIT"
] | Python | make_end_interval | <not_specific> | def make_end_interval(entry, dist):
""" Extract end position of entry and return interval of size dist
"""
strand = entry[5]
if strand == "+":
transcript_end = int(entry[2])
else:
transcript_end = int(entry[1])
interval_start, interval_end = cI.create_end_piece(transcript_end, st... | Extract end position of entry and return interval of size dist
| Extract end position of entry and return interval of size dist | [
"Extract",
"end",
"position",
"of",
"entry",
"and",
"return",
"interval",
"of",
"size",
"dist"
] | def make_end_interval(entry, dist):
strand = entry[5]
if strand == "+":
transcript_end = int(entry[2])
else:
transcript_end = int(entry[1])
interval_start, interval_end = cI.create_end_piece(transcript_end, strand, dist)
return interval_start, interval_end | [
"def",
"make_end_interval",
"(",
"entry",
",",
"dist",
")",
":",
"strand",
"=",
"entry",
"[",
"5",
"]",
"if",
"strand",
"==",
"\"+\"",
":",
"transcript_end",
"=",
"int",
"(",
"entry",
"[",
"2",
"]",
")",
"else",
":",
"transcript_end",
"=",
"int",
"("... | Extract end position of entry and return interval of size dist | [
"Extract",
"end",
"position",
"of",
"entry",
"and",
"return",
"interval",
"of",
"size",
"dist"
] | [
"\"\"\" Extract end position of entry and return interval of size dist\n \"\"\""
] | [
{
"param": "entry",
"type": null
},
{
"param": "dist",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "entry",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "dist",
"type": null,
"docstring": null,
"docstring_tokens": ... |
d4bf3201b359b7022baff1dd0d6f1ecf44867e41 | callumparr/TALON-paper-2020 | ebv/check_last_n_transcript_seq_for_PA_motif.py | [
"MIT"
] | Python | fetch_sequence | <not_specific> | def fetch_sequence(chrom, start, end, strand, genome):
""" Given a BED region, fetch its sequence. If it is on the minus strand,
then reverse-complement the sequence. """
seq = genome.sequence({'chr': chrom, 'start': start, 'stop': end,
'strand': strand}, one_based=False)
re... | Given a BED region, fetch its sequence. If it is on the minus strand,
then reverse-complement the sequence. | Given a BED region, fetch its sequence. If it is on the minus strand,
then reverse-complement the sequence. | [
"Given",
"a",
"BED",
"region",
"fetch",
"its",
"sequence",
".",
"If",
"it",
"is",
"on",
"the",
"minus",
"strand",
"then",
"reverse",
"-",
"complement",
"the",
"sequence",
"."
] | def fetch_sequence(chrom, start, end, strand, genome):
seq = genome.sequence({'chr': chrom, 'start': start, 'stop': end,
'strand': strand}, one_based=False)
return seq | [
"def",
"fetch_sequence",
"(",
"chrom",
",",
"start",
",",
"end",
",",
"strand",
",",
"genome",
")",
":",
"seq",
"=",
"genome",
".",
"sequence",
"(",
"{",
"'chr'",
":",
"chrom",
",",
"'start'",
":",
"start",
",",
"'stop'",
":",
"end",
",",
"'strand'",... | Given a BED region, fetch its sequence. | [
"Given",
"a",
"BED",
"region",
"fetch",
"its",
"sequence",
"."
] | [
"\"\"\" Given a BED region, fetch its sequence. If it is on the minus strand,\n then reverse-complement the sequence. \"\"\""
] | [
{
"param": "chrom",
"type": null
},
{
"param": "start",
"type": null
},
{
"param": "end",
"type": null
},
{
"param": "strand",
"type": null
},
{
"param": "genome",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "chrom",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "start",
"type": null,
"docstring": null,
"docstring_tokens":... |
4b715e1a54333433f421338cd9d6afffef08e04c | callumparr/TALON-paper-2020 | TSS_and_TES/make_read_start_bed_file.py | [
"MIT"
] | Python | starts2bed | <not_specific> | def starts2bed(data, outprefix):
""" Converts start positions from SAM read annot file to BED format.
Returns name of outfile """
bed_file = outprefix + "_known_read_starts.bed"
bed_data = data[["chrom", "read_start"]].copy()
bed_data["end"] = bed_data["read_start"]
bed_data["read_start"] ... | Converts start positions from SAM read annot file to BED format.
Returns name of outfile | Converts start positions from SAM read annot file to BED format.
Returns name of outfile | [
"Converts",
"start",
"positions",
"from",
"SAM",
"read",
"annot",
"file",
"to",
"BED",
"format",
".",
"Returns",
"name",
"of",
"outfile"
] | def starts2bed(data, outprefix):
bed_file = outprefix + "_known_read_starts.bed"
bed_data = data[["chrom", "read_start"]].copy()
bed_data["end"] = bed_data["read_start"]
bed_data["read_start"] -= 1
bed_data["name"] = data["read_name"]
bed_data["score"] = "."
bed_data["strand"] = data["strand... | [
"def",
"starts2bed",
"(",
"data",
",",
"outprefix",
")",
":",
"bed_file",
"=",
"outprefix",
"+",
"\"_known_read_starts.bed\"",
"bed_data",
"=",
"data",
"[",
"[",
"\"chrom\"",
",",
"\"read_start\"",
"]",
"]",
".",
"copy",
"(",
")",
"bed_data",
"[",
"\"end\"",... | Converts start positions from SAM read annot file to BED format. | [
"Converts",
"start",
"positions",
"from",
"SAM",
"read",
"annot",
"file",
"to",
"BED",
"format",
"."
] | [
"\"\"\" Converts start positions from SAM read annot file to BED format.\n Returns name of outfile \"\"\""
] | [
{
"param": "data",
"type": null
},
{
"param": "outprefix",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "data",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "outprefix",
"type": null,
"docstring": null,
"docstring_token... |
86a03e93a25314896894b8960f53fafdb69d773f | callumparr/TALON-paper-2020 | Figure_4/analysis_utils/get_RNA_PET_starts_and_ends.py | [
"MIT"
] | Python | make_intervals | <not_specific> | def make_intervals(entry):
""" Extract start and end position of entry and return each as bed interval
"""
strand = entry[5]
rna_pet_start = int(entry[1])
rna_pet_end = int(entry[2])
# Set start and end based on strand
if strand == "+":
start_interval_1, start_interval_2 = cI.creat... | Extract start and end position of entry and return each as bed interval
| Extract start and end position of entry and return each as bed interval | [
"Extract",
"start",
"and",
"end",
"position",
"of",
"entry",
"and",
"return",
"each",
"as",
"bed",
"interval"
] | def make_intervals(entry):
strand = entry[5]
rna_pet_start = int(entry[1])
rna_pet_end = int(entry[2])
if strand == "+":
start_interval_1, start_interval_2 = cI.create_interval(rna_pet_start,
"left", 0)
end_interval_1, end_i... | [
"def",
"make_intervals",
"(",
"entry",
")",
":",
"strand",
"=",
"entry",
"[",
"5",
"]",
"rna_pet_start",
"=",
"int",
"(",
"entry",
"[",
"1",
"]",
")",
"rna_pet_end",
"=",
"int",
"(",
"entry",
"[",
"2",
"]",
")",
"if",
"strand",
"==",
"\"+\"",
":",
... | Extract start and end position of entry and return each as bed interval | [
"Extract",
"start",
"and",
"end",
"position",
"of",
"entry",
"and",
"return",
"each",
"as",
"bed",
"interval"
] | [
"\"\"\" Extract start and end position of entry and return each as bed interval \n \"\"\"",
"# Set start and end based on strand"
] | [
{
"param": "entry",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "entry",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
ad43007a7ba62112f265b92d8d88f528a740d228 | callumparr/TALON-paper-2020 | splicing_analyses/extract_SJs_from_sam.py | [
"MIT"
] | Python | fetch_splice_motif_code | <not_specific> | def fetch_splice_motif_code(chrom, start_pos, end_pos, strand, genome):
""" Use Pyfasta to extract the splice motif sequence based on the start
and end of the splice junction. Then, convert this sequence motif
to a numeric code. """
start_motif = get_splice_seq(chrom, start_pos, 0, genome)
... | Use Pyfasta to extract the splice motif sequence based on the start
and end of the splice junction. Then, convert this sequence motif
to a numeric code. | Use Pyfasta to extract the splice motif sequence based on the start
and end of the splice junction. Then, convert this sequence motif
to a numeric code. | [
"Use",
"Pyfasta",
"to",
"extract",
"the",
"splice",
"motif",
"sequence",
"based",
"on",
"the",
"start",
"and",
"end",
"of",
"the",
"splice",
"junction",
".",
"Then",
"convert",
"this",
"sequence",
"motif",
"to",
"a",
"numeric",
"code",
"."
] | def fetch_splice_motif_code(chrom, start_pos, end_pos, strand, genome):
start_motif = get_splice_seq(chrom, start_pos, 0, genome)
end_motif = get_splice_seq(chrom, end_pos, 1, genome)
motif_code = getSJMotifCode(start_motif, end_motif)
return motif_code | [
"def",
"fetch_splice_motif_code",
"(",
"chrom",
",",
"start_pos",
",",
"end_pos",
",",
"strand",
",",
"genome",
")",
":",
"start_motif",
"=",
"get_splice_seq",
"(",
"chrom",
",",
"start_pos",
",",
"0",
",",
"genome",
")",
"end_motif",
"=",
"get_splice_seq",
... | Use Pyfasta to extract the splice motif sequence based on the start
and end of the splice junction. | [
"Use",
"Pyfasta",
"to",
"extract",
"the",
"splice",
"motif",
"sequence",
"based",
"on",
"the",
"start",
"and",
"end",
"of",
"the",
"splice",
"junction",
"."
] | [
"\"\"\" Use Pyfasta to extract the splice motif sequence based on the start\n and end of the splice junction. Then, convert this sequence motif \n to a numeric code. \"\"\""
] | [
{
"param": "chrom",
"type": null
},
{
"param": "start_pos",
"type": null
},
{
"param": "end_pos",
"type": null
},
{
"param": "strand",
"type": null
},
{
"param": "genome",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "chrom",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "start_pos",
"type": null,
"docstring": null,
"docstring_toke... |
ad43007a7ba62112f265b92d8d88f528a740d228 | callumparr/TALON-paper-2020 | splicing_analyses/extract_SJs_from_sam.py | [
"MIT"
] | Python | create_sj_tuples | <not_specific> | def create_sj_tuples(chrom, strand, intron_coords, genome):
""" Walk through intron coord pairs to assemble SJ tuples for each:
(chr, start, end, strand, splice_motif)
Since we want the smallest coordinate first in each case, we do not
need to orient based on strand."""
sj_tuples =... | Walk through intron coord pairs to assemble SJ tuples for each:
(chr, start, end, strand, splice_motif)
Since we want the smallest coordinate first in each case, we do not
need to orient based on strand. | Walk through intron coord pairs to assemble SJ tuples for each:
(chr, start, end, strand, splice_motif)
Since we want the smallest coordinate first in each case, we do not
need to orient based on strand. | [
"Walk",
"through",
"intron",
"coord",
"pairs",
"to",
"assemble",
"SJ",
"tuples",
"for",
"each",
":",
"(",
"chr",
"start",
"end",
"strand",
"splice_motif",
")",
"Since",
"we",
"want",
"the",
"smallest",
"coordinate",
"first",
"in",
"each",
"case",
"we",
"do... | def create_sj_tuples(chrom, strand, intron_coords, genome):
sj_tuples = []
start_index = 0
while start_index < len(intron_coords) -1 :
end_index = start_index + 1
start_pos = intron_coords[start_index]
end_pos = intron_coords[end_index]
motif = fetch_splice_motif_code(chrom, ... | [
"def",
"create_sj_tuples",
"(",
"chrom",
",",
"strand",
",",
"intron_coords",
",",
"genome",
")",
":",
"sj_tuples",
"=",
"[",
"]",
"start_index",
"=",
"0",
"while",
"start_index",
"<",
"len",
"(",
"intron_coords",
")",
"-",
"1",
":",
"end_index",
"=",
"s... | Walk through intron coord pairs to assemble SJ tuples for each:
(chr, start, end, strand, splice_motif)
Since we want the smallest coordinate first in each case, we do not
need to orient based on strand. | [
"Walk",
"through",
"intron",
"coord",
"pairs",
"to",
"assemble",
"SJ",
"tuples",
"for",
"each",
":",
"(",
"chr",
"start",
"end",
"strand",
"splice_motif",
")",
"Since",
"we",
"want",
"the",
"smallest",
"coordinate",
"first",
"in",
"each",
"case",
"we",
"do... | [
"\"\"\" Walk through intron coord pairs to assemble SJ tuples for each:\n (chr, start, end, strand, splice_motif)\n Since we want the smallest coordinate first in each case, we do not \n need to orient based on strand.\"\"\"",
"# Assemble the tuple"
] | [
{
"param": "chrom",
"type": null
},
{
"param": "strand",
"type": null
},
{
"param": "intron_coords",
"type": null
},
{
"param": "genome",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "chrom",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "strand",
"type": null,
"docstring": null,
"docstring_tokens"... |
7f3a92147d869b351922a38d168a7826426fbb2d | Ashwin4RC/api | app.py | [
"Apache-2.0"
] | Python | show_files | <not_specific> | def show_files():
"""
Render the template with ZIP info
"""
zips = get_zips(DIR)
devices = get_devices()
build_dates = {}
for zip in zips:
zip = os.path.splitext(zip)[0]
device = zip.split('-')[3]
if device not in devices:
devices[device] = device
... |
Render the template with ZIP info
| Render the template with ZIP info | [
"Render",
"the",
"template",
"with",
"ZIP",
"info"
] | def show_files():
zips = get_zips(DIR)
devices = get_devices()
build_dates = {}
for zip in zips:
zip = os.path.splitext(zip)[0]
device = zip.split('-')[3]
if device not in devices:
devices[device] = device
build_date = zip.split('-')[4]
if device not i... | [
"def",
"show_files",
"(",
")",
":",
"zips",
"=",
"get_zips",
"(",
"DIR",
")",
"devices",
"=",
"get_devices",
"(",
")",
"build_dates",
"=",
"{",
"}",
"for",
"zip",
"in",
"zips",
":",
"zip",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"zip",
")",
... | Render the template with ZIP info | [
"Render",
"the",
"template",
"with",
"ZIP",
"info"
] | [
"\"\"\"\n Render the template with ZIP info\n \"\"\""
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
3dfdfd60cdb7e6bb2243a032205a09a9f2f47c0e | leopon55/twi_word_count | full_archive_tweet_counts.py | [
"MIT"
] | Python | bearer_oauth | <not_specific> | def bearer_oauth(r):
"""
Method required by bearer token authentication.
"""
r.headers["Authorization"] = f"Bearer {bearer_token}"
r.headers["User-Agent"] = "v2FullArchiveTweetCountsPython"
return r |
Method required by bearer token authentication.
| Method required by bearer token authentication. | [
"Method",
"required",
"by",
"bearer",
"token",
"authentication",
"."
] | def bearer_oauth(r):
r.headers["Authorization"] = f"Bearer {bearer_token}"
r.headers["User-Agent"] = "v2FullArchiveTweetCountsPython"
return r | [
"def",
"bearer_oauth",
"(",
"r",
")",
":",
"r",
".",
"headers",
"[",
"\"Authorization\"",
"]",
"=",
"f\"Bearer {bearer_token}\"",
"r",
".",
"headers",
"[",
"\"User-Agent\"",
"]",
"=",
"\"v2FullArchiveTweetCountsPython\"",
"return",
"r"
] | Method required by bearer token authentication. | [
"Method",
"required",
"by",
"bearer",
"token",
"authentication",
"."
] | [
"\"\"\"\n Method required by bearer token authentication.\n \"\"\""
] | [
{
"param": "r",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "r",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
293f796cc6b4c806e912d82d8f225a066cd5ead1 | alttch/pyaltt2 | pyaltt2/db.py | [
"MIT"
] | Python | list | <not_specific> | def list(self, *args, json_fields=[], **kwargs):
"""
get self.execute result as list of dicts
Args:
json_fields: decode json fields if required
other: passed as-is
"""
return self._format_list(
[dict(row) for row in self.execute(*args, **kwarg... |
get self.execute result as list of dicts
Args:
json_fields: decode json fields if required
other: passed as-is
| get self.execute result as list of dicts | [
"get",
"self",
".",
"execute",
"result",
"as",
"list",
"of",
"dicts"
] | def list(self, *args, json_fields=[], **kwargs):
return self._format_list(
[dict(row) for row in self.execute(*args, **kwargs).fetchall()],
json_fields=json_fields) | [
"def",
"list",
"(",
"self",
",",
"*",
"args",
",",
"json_fields",
"=",
"[",
"]",
",",
"**",
"kwargs",
")",
":",
"return",
"self",
".",
"_format_list",
"(",
"[",
"dict",
"(",
"row",
")",
"for",
"row",
"in",
"self",
".",
"execute",
"(",
"*",
"args"... | get self.execute result as list of dicts | [
"get",
"self",
".",
"execute",
"result",
"as",
"list",
"of",
"dicts"
] | [
"\"\"\"\n get self.execute result as list of dicts\n\n Args:\n json_fields: decode json fields if required\n other: passed as-is\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "json_fields",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "json_fields",
"type": null,
"docstring": "decode json fields if req... |
293f796cc6b4c806e912d82d8f225a066cd5ead1 | alttch/pyaltt2 | pyaltt2/db.py | [
"MIT"
] | Python | qlist | <not_specific> | def qlist(self, *args, json_fields=[], **kwargs):
"""
get self.query result as list of dicts
Args:
json_fields: decode json fields if required
other: passed as-is
"""
return self._format_list(
[dict(row) for row in self.query(*args, **kwargs).... |
get self.query result as list of dicts
Args:
json_fields: decode json fields if required
other: passed as-is
| get self.query result as list of dicts | [
"get",
"self",
".",
"query",
"result",
"as",
"list",
"of",
"dicts"
] | def qlist(self, *args, json_fields=[], **kwargs):
return self._format_list(
[dict(row) for row in self.query(*args, **kwargs).fetchall()],
json_fields=json_fields) | [
"def",
"qlist",
"(",
"self",
",",
"*",
"args",
",",
"json_fields",
"=",
"[",
"]",
",",
"**",
"kwargs",
")",
":",
"return",
"self",
".",
"_format_list",
"(",
"[",
"dict",
"(",
"row",
")",
"for",
"row",
"in",
"self",
".",
"query",
"(",
"*",
"args",... | get self.query result as list of dicts | [
"get",
"self",
".",
"query",
"result",
"as",
"list",
"of",
"dicts"
] | [
"\"\"\"\n get self.query result as list of dicts\n\n Args:\n json_fields: decode json fields if required\n other: passed as-is\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "json_fields",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "json_fields",
"type": null,
"docstring": "decode json fields if req... |
293f796cc6b4c806e912d82d8f225a066cd5ead1 | alttch/pyaltt2 | pyaltt2/db.py | [
"MIT"
] | Python | connect | <not_specific> | def connect(self):
"""
Get thread-safe db connection
"""
with self.db_lock:
try:
self.g.conn.execute('select 1')
return self.g.conn
except:
self.g.conn = self.db.connect()
return self.g.conn |
Get thread-safe db connection
| Get thread-safe db connection | [
"Get",
"thread",
"-",
"safe",
"db",
"connection"
] | def connect(self):
with self.db_lock:
try:
self.g.conn.execute('select 1')
return self.g.conn
except:
self.g.conn = self.db.connect()
return self.g.conn | [
"def",
"connect",
"(",
"self",
")",
":",
"with",
"self",
".",
"db_lock",
":",
"try",
":",
"self",
".",
"g",
".",
"conn",
".",
"execute",
"(",
"'select 1'",
")",
"return",
"self",
".",
"g",
".",
"conn",
"except",
":",
"self",
".",
"g",
".",
"conn"... | Get thread-safe db connection | [
"Get",
"thread",
"-",
"safe",
"db",
"connection"
] | [
"\"\"\"\n Get thread-safe db connection\n \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
293f796cc6b4c806e912d82d8f225a066cd5ead1 | alttch/pyaltt2 | pyaltt2/db.py | [
"MIT"
] | Python | create | <not_specific> | def create(self, q, *args, **kwargs):
"""
Execute (usually INSERT) query with self.execute and return row id
row id must be in "id" field
"""
if not self.use_lastrowid:
q += ' RETURNING id'
result = self.execute(q, *args, **kwargs)
return result.lastr... |
Execute (usually INSERT) query with self.execute and return row id
row id must be in "id" field
| Execute (usually INSERT) query with self.execute and return row id
row id must be in "id" field | [
"Execute",
"(",
"usually",
"INSERT",
")",
"query",
"with",
"self",
".",
"execute",
"and",
"return",
"row",
"id",
"row",
"id",
"must",
"be",
"in",
"\"",
"id",
"\"",
"field"
] | def create(self, q, *args, **kwargs):
if not self.use_lastrowid:
q += ' RETURNING id'
result = self.execute(q, *args, **kwargs)
return result.lastrowid if self.use_lastrowid else result.fetchone().id | [
"def",
"create",
"(",
"self",
",",
"q",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"use_lastrowid",
":",
"q",
"+=",
"' RETURNING id'",
"result",
"=",
"self",
".",
"execute",
"(",
"q",
",",
"*",
"args",
",",
"**",
"... | Execute (usually INSERT) query with self.execute and return row id
row id must be in "id" field | [
"Execute",
"(",
"usually",
"INSERT",
")",
"query",
"with",
"self",
".",
"execute",
"and",
"return",
"row",
"id",
"row",
"id",
"must",
"be",
"in",
"\"",
"id",
"\"",
"field"
] | [
"\"\"\"\n Execute (usually INSERT) query with self.execute and return row id\n\n row id must be in \"id\" field\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "q",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "q",
"type": null,
"docstring": null,
"docstring_tokens": [],
... |
293f796cc6b4c806e912d82d8f225a066cd5ead1 | alttch/pyaltt2 | pyaltt2/db.py | [
"MIT"
] | Python | qcreate | <not_specific> | def qcreate(self, q, *args, **kwargs):
"""
Execute (usually INSERT) query with self.query and return row id
row id must be in "id" field
"""
result = self.query(q, _create=True, *args, **kwargs)
return result.lastrowid if self.use_lastrowid else result.fetchone().id |
Execute (usually INSERT) query with self.query and return row id
row id must be in "id" field
| Execute (usually INSERT) query with self.query and return row id
row id must be in "id" field | [
"Execute",
"(",
"usually",
"INSERT",
")",
"query",
"with",
"self",
".",
"query",
"and",
"return",
"row",
"id",
"row",
"id",
"must",
"be",
"in",
"\"",
"id",
"\"",
"field"
] | def qcreate(self, q, *args, **kwargs):
result = self.query(q, _create=True, *args, **kwargs)
return result.lastrowid if self.use_lastrowid else result.fetchone().id | [
"def",
"qcreate",
"(",
"self",
",",
"q",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"result",
"=",
"self",
".",
"query",
"(",
"q",
",",
"_create",
"=",
"True",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
"return",
"result",
".",
"lastrowid"... | Execute (usually INSERT) query with self.query and return row id
row id must be in "id" field | [
"Execute",
"(",
"usually",
"INSERT",
")",
"query",
"with",
"self",
".",
"query",
"and",
"return",
"row",
"id",
"row",
"id",
"must",
"be",
"in",
"\"",
"id",
"\"",
"field"
] | [
"\"\"\"\n Execute (usually INSERT) query with self.query and return row id\n\n row id must be in \"id\" field\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "q",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "q",
"type": null,
"docstring": null,
"docstring_tokens": [],
... |
293f796cc6b4c806e912d82d8f225a066cd5ead1 | alttch/pyaltt2 | pyaltt2/db.py | [
"MIT"
] | Python | lookup | <not_specific> | def lookup(self, *args, json_fields=[], **kwargs):
"""
Get single db row, use self.execute
Args:
json_fields: decode json fields if required
other: passed as-is
Returns:
single row as a dict
Raises:
LookupError: if nothing found
... |
Get single db row, use self.execute
Args:
json_fields: decode json fields if required
other: passed as-is
Returns:
single row as a dict
Raises:
LookupError: if nothing found
| Get single db row, use self.execute | [
"Get",
"single",
"db",
"row",
"use",
"self",
".",
"execute"
] | def lookup(self, *args, json_fields=[], **kwargs):
result = self._format_result(self.execute(*args, **kwargs).fetchone(),
json_fields=json_fields)
if result:
return result
else:
raise LookupError | [
"def",
"lookup",
"(",
"self",
",",
"*",
"args",
",",
"json_fields",
"=",
"[",
"]",
",",
"**",
"kwargs",
")",
":",
"result",
"=",
"self",
".",
"_format_result",
"(",
"self",
".",
"execute",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
".",
"fetchone"... | Get single db row, use self.execute | [
"Get",
"single",
"db",
"row",
"use",
"self",
".",
"execute"
] | [
"\"\"\"\n Get single db row, use self.execute\n\n Args:\n json_fields: decode json fields if required\n other: passed as-is\n\n Returns:\n single row as a dict\n Raises:\n LookupError: if nothing found\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "json_fields",
"type": null
}
] | {
"returns": [
{
"docstring": "single row as a dict",
"docstring_tokens": [
"single",
"row",
"as",
"a",
"dict"
],
"type": null
}
],
"raises": [
{
"docstring": "if nothing found",
"docstring_tokens": [
"if",
"no... |
293f796cc6b4c806e912d82d8f225a066cd5ead1 | alttch/pyaltt2 | pyaltt2/db.py | [
"MIT"
] | Python | qlookup | <not_specific> | def qlookup(self, *args, json_fields=[], **kwargs):
"""
Get single db row, use self.query
Returns:
single row as a dict
Raises:
LookupError: if nothing found
"""
result = self._format_result(self.query(*args, **kwargs).fetchone(),
... |
Get single db row, use self.query
Returns:
single row as a dict
Raises:
LookupError: if nothing found
| Get single db row, use self.query | [
"Get",
"single",
"db",
"row",
"use",
"self",
".",
"query"
] | def qlookup(self, *args, json_fields=[], **kwargs):
result = self._format_result(self.query(*args, **kwargs).fetchone(),
json_fields=json_fields)
if result:
return result
else:
raise LookupError | [
"def",
"qlookup",
"(",
"self",
",",
"*",
"args",
",",
"json_fields",
"=",
"[",
"]",
",",
"**",
"kwargs",
")",
":",
"result",
"=",
"self",
".",
"_format_result",
"(",
"self",
".",
"query",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
".",
"fetchone",... | Get single db row, use self.query | [
"Get",
"single",
"db",
"row",
"use",
"self",
".",
"query"
] | [
"\"\"\"\n Get single db row, use self.query\n\n Returns:\n single row as a dict\n Raises:\n LookupError: if nothing found\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "json_fields",
"type": null
}
] | {
"returns": [
{
"docstring": "single row as a dict",
"docstring_tokens": [
"single",
"row",
"as",
"a",
"dict"
],
"type": null
}
],
"raises": [
{
"docstring": "if nothing found",
"docstring_tokens": [
"if",
"no... |
293f796cc6b4c806e912d82d8f225a066cd5ead1 | alttch/pyaltt2 | pyaltt2/db.py | [
"MIT"
] | Python | put | <not_specific> | def put(self, key=None, value=None, expires=None, override=True):
"""
Put object to key-value storage
If no key specified, random 64-char key is generated
Args:
key: string key (1-255 chars)
value: value to put
expires: expiration either in seconds o... |
Put object to key-value storage
If no key specified, random 64-char key is generated
Args:
key: string key (1-255 chars)
value: value to put
expires: expiration either in seconds or datetime.timedelta
override: replace existing object
Re... | Put object to key-value storage
If no key specified, random 64-char key is generated | [
"Put",
"object",
"to",
"key",
"-",
"value",
"storage",
"If",
"no",
"key",
"specified",
"random",
"64",
"-",
"char",
"key",
"is",
"generated"
] | def put(self, key=None, value=None, expires=None, override=True):
from msgpack import dumps
if key is None:
key = gen_random_str(length=64)
elif override:
try:
self.delete(key)
except LookupError:
pass
value = dumps(valu... | [
"def",
"put",
"(",
"self",
",",
"key",
"=",
"None",
",",
"value",
"=",
"None",
",",
"expires",
"=",
"None",
",",
"override",
"=",
"True",
")",
":",
"from",
"msgpack",
"import",
"dumps",
"if",
"key",
"is",
"None",
":",
"key",
"=",
"gen_random_str",
... | Put object to key-value storage
If no key specified, random 64-char key is generated | [
"Put",
"object",
"to",
"key",
"-",
"value",
"storage",
"If",
"no",
"key",
"specified",
"random",
"64",
"-",
"char",
"key",
"is",
"generated"
] | [
"\"\"\"\n Put object to key-value storage\n\n If no key specified, random 64-char key is generated\n\n Args:\n key: string key (1-255 chars)\n value: value to put\n expires: expiration either in seconds or datetime.timedelta\n override: replace existi... | [
{
"param": "self",
"type": null
},
{
"param": "key",
"type": null
},
{
"param": "value",
"type": null
},
{
"param": "expires",
"type": null
},
{
"param": "override",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
... |
293f796cc6b4c806e912d82d8f225a066cd5ead1 | alttch/pyaltt2 | pyaltt2/db.py | [
"MIT"
] | Python | delete | null | def delete(self, key):
"""
Delete object in key-value storage
Args:
key: object key
Raises:
LookupError: object not found
"""
if not self.db.query('kv.delete', qargs=[self.table_name],
id=key).rowcount:
rai... |
Delete object in key-value storage
Args:
key: object key
Raises:
LookupError: object not found
| Delete object in key-value storage | [
"Delete",
"object",
"in",
"key",
"-",
"value",
"storage"
] | def delete(self, key):
if not self.db.query('kv.delete', qargs=[self.table_name],
id=key).rowcount:
raise LookupError | [
"def",
"delete",
"(",
"self",
",",
"key",
")",
":",
"if",
"not",
"self",
".",
"db",
".",
"query",
"(",
"'kv.delete'",
",",
"qargs",
"=",
"[",
"self",
".",
"table_name",
"]",
",",
"id",
"=",
"key",
")",
".",
"rowcount",
":",
"raise",
"LookupError"
] | Delete object in key-value storage | [
"Delete",
"object",
"in",
"key",
"-",
"value",
"storage"
] | [
"\"\"\"\n Delete object in key-value storage\n\n Args:\n key: object key\n Raises:\n LookupError: object not found\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "key",
"type": null
}
] | {
"returns": [],
"raises": [
{
"docstring": "object not found",
"docstring_tokens": [
"object",
"not",
"found"
],
"type": "LookupError"
}
],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens"... |
cf7dc7ba7f60603d6d4259579aa227116ef536e7 | alttch/pyaltt2 | pyaltt2/config.py | [
"MIT"
] | Python | load_yaml | <not_specific> | def load_yaml(fname, schema=None):
"""
Load config from YAML/JSON file
Args:
fname: file name to load
schema: JSON schema for validation
"""
with open(fname) as fh:
data = yaml.load(fh.read())
if schema:
import jsonschema
jsonschema.validate(data, schema=... |
Load config from YAML/JSON file
Args:
fname: file name to load
schema: JSON schema for validation
| Load config from YAML/JSON file | [
"Load",
"config",
"from",
"YAML",
"/",
"JSON",
"file"
] | def load_yaml(fname, schema=None):
with open(fname) as fh:
data = yaml.load(fh.read())
if schema:
import jsonschema
jsonschema.validate(data, schema=schema)
return data | [
"def",
"load_yaml",
"(",
"fname",
",",
"schema",
"=",
"None",
")",
":",
"with",
"open",
"(",
"fname",
")",
"as",
"fh",
":",
"data",
"=",
"yaml",
".",
"load",
"(",
"fh",
".",
"read",
"(",
")",
")",
"if",
"schema",
":",
"import",
"jsonschema",
"jso... | Load config from YAML/JSON file | [
"Load",
"config",
"from",
"YAML",
"/",
"JSON",
"file"
] | [
"\"\"\"\n Load config from YAML/JSON file\n\n Args:\n fname: file name to load\n schema: JSON schema for validation\n \"\"\""
] | [
{
"param": "fname",
"type": null
},
{
"param": "schema",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "fname",
"type": null,
"docstring": "file name to load",
"docstring_tokens": [
"file",
"name",
"to",
"load"
],
"default": null,
"is_optional": null
},
{
"identifie... |
cf7dc7ba7f60603d6d4259579aa227116ef536e7 | alttch/pyaltt2 | pyaltt2/config.py | [
"MIT"
] | Python | choose_file | <not_specific> | def choose_file(fname=None, env=None, choices=[]):
"""
Chooise existing file
Returned file path is user-expanded
Args:
fname: if specified, has top priority and others are not chechked
env: if specified and set, has second-top priority and choices are not
inspected
... |
Chooise existing file
Returned file path is user-expanded
Args:
fname: if specified, has top priority and others are not chechked
env: if specified and set, has second-top priority and choices are not
inspected
choices: if env is not set or not specified, choose existi... | Chooise existing file
Returned file path is user-expanded | [
"Chooise",
"existing",
"file",
"Returned",
"file",
"path",
"is",
"user",
"-",
"expanded"
] | def choose_file(fname=None, env=None, choices=[]):
if fname:
fname = os.path.expanduser(fname)
if os.path.exists(fname):
return fname
else:
raise LookupError(f'No such file {fname}')
elif env and env in os.environ:
fname = os.path.expanduser(os.environ[env... | [
"def",
"choose_file",
"(",
"fname",
"=",
"None",
",",
"env",
"=",
"None",
",",
"choices",
"=",
"[",
"]",
")",
":",
"if",
"fname",
":",
"fname",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"fname",
")",
"if",
"os",
".",
"path",
".",
"exists",
... | Chooise existing file
Returned file path is user-expanded | [
"Chooise",
"existing",
"file",
"Returned",
"file",
"path",
"is",
"user",
"-",
"expanded"
] | [
"\"\"\"\n Chooise existing file\n\n Returned file path is user-expanded\n\n Args:\n fname: if specified, has top priority and others are not chechked\n env: if specified and set, has second-top priority and choices are not\n inspected\n choices: if env is not set or not spec... | [
{
"param": "fname",
"type": null
},
{
"param": "env",
"type": null
},
{
"param": "choices",
"type": null
}
] | {
"returns": [],
"raises": [
{
"docstring": "if file doesn't exists",
"docstring_tokens": [
"if",
"file",
"doesn",
"'",
"t",
"exists"
],
"type": "LookupError"
}
],
"params": [
{
"identifier": "fname",
"type": null,
... |
34156eff7a93a1c14e85121adc02f83e00376371 | michaelbaluja/openml-python | openml/datasets/functions.py | [
"BSD-3-Clause"
] | Python | list_qualities | List[str] | def list_qualities() -> List[str]:
""" Return list of data qualities available.
The function performs an API call to retrieve the entire list of
data qualities that are computed on the datasets uploaded.
Returns
-------
list
"""
api_call = "data/qualities/list"
xml_string = openml.... | Return list of data qualities available.
The function performs an API call to retrieve the entire list of
data qualities that are computed on the datasets uploaded.
Returns
-------
list
| Return list of data qualities available.
The function performs an API call to retrieve the entire list of
data qualities that are computed on the datasets uploaded.
Returns
list | [
"Return",
"list",
"of",
"data",
"qualities",
"available",
".",
"The",
"function",
"performs",
"an",
"API",
"call",
"to",
"retrieve",
"the",
"entire",
"list",
"of",
"data",
"qualities",
"that",
"are",
"computed",
"on",
"the",
"datasets",
"uploaded",
".",
"Ret... | def list_qualities() -> List[str]:
api_call = "data/qualities/list"
xml_string = openml._api_calls._perform_api_call(api_call, "get")
qualities = xmltodict.parse(xml_string, force_list=("oml:quality"))
if "oml:data_qualities_list" not in qualities:
raise ValueError("Error in return XML, does not... | [
"def",
"list_qualities",
"(",
")",
"->",
"List",
"[",
"str",
"]",
":",
"api_call",
"=",
"\"data/qualities/list\"",
"xml_string",
"=",
"openml",
".",
"_api_calls",
".",
"_perform_api_call",
"(",
"api_call",
",",
"\"get\"",
")",
"qualities",
"=",
"xmltodict",
".... | Return list of data qualities available. | [
"Return",
"list",
"of",
"data",
"qualities",
"available",
"."
] | [
"\"\"\" Return list of data qualities available.\n\n The function performs an API call to retrieve the entire list of\n data qualities that are computed on the datasets uploaded.\n\n Returns\n -------\n list\n \"\"\"",
"# Minimalistic check if the XML is useful"
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
34156eff7a93a1c14e85121adc02f83e00376371 | michaelbaluja/openml-python | openml/datasets/functions.py | [
"BSD-3-Clause"
] | Python | check_datasets_active | Dict[int, bool] | def check_datasets_active(
dataset_ids: List[int], raise_error_if_not_exist: bool = True,
) -> Dict[int, bool]:
"""
Check if the dataset ids provided are active.
Raises an error if a dataset_id in the given list
of dataset_ids does not exist on the server.
Parameters
----------
dataset... |
Check if the dataset ids provided are active.
Raises an error if a dataset_id in the given list
of dataset_ids does not exist on the server.
Parameters
----------
dataset_ids : List[int]
A list of integers representing dataset ids.
raise_error_if_not_exist : bool (default=True)
... | Check if the dataset ids provided are active.
Raises an error if a dataset_id in the given list
of dataset_ids does not exist on the server.
Parameters
dataset_ids : List[int]
A list of integers representing dataset ids.
raise_error_if_not_exist : bool (default=True)
Flag that if activated can raise an error, if one ... | [
"Check",
"if",
"the",
"dataset",
"ids",
"provided",
"are",
"active",
".",
"Raises",
"an",
"error",
"if",
"a",
"dataset_id",
"in",
"the",
"given",
"list",
"of",
"dataset_ids",
"does",
"not",
"exist",
"on",
"the",
"server",
".",
"Parameters",
"dataset_ids",
... | def check_datasets_active(
dataset_ids: List[int], raise_error_if_not_exist: bool = True,
) -> Dict[int, bool]:
dataset_list = list_datasets(status="all", data_id=dataset_ids)
active = {}
for did in dataset_ids:
dataset = dataset_list.get(did, None)
if dataset is None:
if rai... | [
"def",
"check_datasets_active",
"(",
"dataset_ids",
":",
"List",
"[",
"int",
"]",
",",
"raise_error_if_not_exist",
":",
"bool",
"=",
"True",
",",
")",
"->",
"Dict",
"[",
"int",
",",
"bool",
"]",
":",
"dataset_list",
"=",
"list_datasets",
"(",
"status",
"="... | Check if the dataset ids provided are active. | [
"Check",
"if",
"the",
"dataset",
"ids",
"provided",
"are",
"active",
"."
] | [
"\"\"\"\n Check if the dataset ids provided are active.\n\n Raises an error if a dataset_id in the given list\n of dataset_ids does not exist on the server.\n\n Parameters\n ----------\n dataset_ids : List[int]\n A list of integers representing dataset ids.\n raise_error_if_not_exist : b... | [
{
"param": "dataset_ids",
"type": "List[int]"
},
{
"param": "raise_error_if_not_exist",
"type": "bool"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "dataset_ids",
"type": "List[int]",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "raise_error_if_not_exist",
"type": "bool",
"docstring... |
34156eff7a93a1c14e85121adc02f83e00376371 | michaelbaluja/openml-python | openml/datasets/functions.py | [
"BSD-3-Clause"
] | Python | _name_to_id | int | def _name_to_id(
dataset_name: str, version: Optional[int] = None, error_if_multiple: bool = False
) -> int:
""" Attempt to find the dataset id of the dataset with the given name.
If multiple datasets with the name exist, and ``error_if_multiple`` is ``False``,
then return the least recent still active... | Attempt to find the dataset id of the dataset with the given name.
If multiple datasets with the name exist, and ``error_if_multiple`` is ``False``,
then return the least recent still active dataset.
Raises an error if no dataset with the name is found.
Raises an error if a version is specified but i... | Attempt to find the dataset id of the dataset with the given name.
Raises an error if no dataset with the name is found.
Raises an error if a version is specified but it could not be found.
Parameters
dataset_name : str
The name of the dataset for which to find its id.
version : int
Version to retrieve. If not speci... | [
"Attempt",
"to",
"find",
"the",
"dataset",
"id",
"of",
"the",
"dataset",
"with",
"the",
"given",
"name",
".",
"Raises",
"an",
"error",
"if",
"no",
"dataset",
"with",
"the",
"name",
"is",
"found",
".",
"Raises",
"an",
"error",
"if",
"a",
"version",
"is"... | def _name_to_id(
dataset_name: str, version: Optional[int] = None, error_if_multiple: bool = False
) -> int:
status = None if version is not None else "active"
candidates = list_datasets(data_name=dataset_name, status=status, data_version=version)
if error_if_multiple and len(candidates) > 1:
ra... | [
"def",
"_name_to_id",
"(",
"dataset_name",
":",
"str",
",",
"version",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
"error_if_multiple",
":",
"bool",
"=",
"False",
")",
"->",
"int",
":",
"status",
"=",
"None",
"if",
"version",
"is",
"not",
"None... | Attempt to find the dataset id of the dataset with the given name. | [
"Attempt",
"to",
"find",
"the",
"dataset",
"id",
"of",
"the",
"dataset",
"with",
"the",
"given",
"name",
"."
] | [
"\"\"\" Attempt to find the dataset id of the dataset with the given name.\n\n If multiple datasets with the name exist, and ``error_if_multiple`` is ``False``,\n then return the least recent still active dataset.\n\n Raises an error if no dataset with the name is found.\n Raises an error if a version i... | [
{
"param": "dataset_name",
"type": "str"
},
{
"param": "version",
"type": "Optional[int]"
},
{
"param": "error_if_multiple",
"type": "bool"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "dataset_name",
"type": "str",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "version",
"type": "Optional[int]",
"docstring": null,
... |
34156eff7a93a1c14e85121adc02f83e00376371 | michaelbaluja/openml-python | openml/datasets/functions.py | [
"BSD-3-Clause"
] | Python | attributes_arff_from_df | <not_specific> | def attributes_arff_from_df(df):
""" Describe attributes of the dataframe according to ARFF specification.
Parameters
----------
df : DataFrame, shape (n_samples, n_features)
The dataframe containing the data set.
Returns
-------
attributes_arff : str
The data set attribute... | Describe attributes of the dataframe according to ARFF specification.
Parameters
----------
df : DataFrame, shape (n_samples, n_features)
The dataframe containing the data set.
Returns
-------
attributes_arff : str
The data set attributes as required by the ARFF format.
| Describe attributes of the dataframe according to ARFF specification.
Parameters
df : DataFrame, shape (n_samples, n_features)
The dataframe containing the data set.
Returns
attributes_arff : str
The data set attributes as required by the ARFF format. | [
"Describe",
"attributes",
"of",
"the",
"dataframe",
"according",
"to",
"ARFF",
"specification",
".",
"Parameters",
"df",
":",
"DataFrame",
"shape",
"(",
"n_samples",
"n_features",
")",
"The",
"dataframe",
"containing",
"the",
"data",
"set",
".",
"Returns",
"attr... | def attributes_arff_from_df(df):
PD_DTYPES_TO_ARFF_DTYPE = {"integer": "INTEGER", "floating": "REAL", "string": "STRING"}
attributes_arff = []
if not all([isinstance(column_name, str) for column_name in df.columns]):
logger.warning("Converting non-str column names to str.")
df.columns = [str... | [
"def",
"attributes_arff_from_df",
"(",
"df",
")",
":",
"PD_DTYPES_TO_ARFF_DTYPE",
"=",
"{",
"\"integer\"",
":",
"\"INTEGER\"",
",",
"\"floating\"",
":",
"\"REAL\"",
",",
"\"string\"",
":",
"\"STRING\"",
"}",
"attributes_arff",
"=",
"[",
"]",
"if",
"not",
"all",
... | Describe attributes of the dataframe according to ARFF specification. | [
"Describe",
"attributes",
"of",
"the",
"dataframe",
"according",
"to",
"ARFF",
"specification",
"."
] | [
"\"\"\" Describe attributes of the dataframe according to ARFF specification.\n\n Parameters\n ----------\n df : DataFrame, shape (n_samples, n_features)\n The dataframe containing the data set.\n\n Returns\n -------\n attributes_arff : str\n The data set attributes as required by th... | [
{
"param": "df",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "df",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
34156eff7a93a1c14e85121adc02f83e00376371 | michaelbaluja/openml-python | openml/datasets/functions.py | [
"BSD-3-Clause"
] | Python | create_dataset | <not_specific> | def create_dataset(
name,
description,
creator,
contributor,
collection_date,
language,
licence,
attributes,
data,
default_target_attribute,
ignore_attribute,
citation,
row_id_attribute=None,
original_data_url=None,
paper_url=None,
update_comment=None,
... | Create a dataset.
This function creates an OpenMLDataset object.
The OpenMLDataset object contains information related to the dataset
and the actual data file.
Parameters
----------
name : str
Name of the dataset.
description : str
Description of the dataset.
creator : ... | Create a dataset.
This function creates an OpenMLDataset object.
The OpenMLDataset object contains information related to the dataset
and the actual data file.
Parameters
name : str
Name of the dataset.
description : str
Description of the dataset.
creator : str
The person who created the dataset.
contributor : str
P... | [
"Create",
"a",
"dataset",
".",
"This",
"function",
"creates",
"an",
"OpenMLDataset",
"object",
".",
"The",
"OpenMLDataset",
"object",
"contains",
"information",
"related",
"to",
"the",
"dataset",
"and",
"the",
"actual",
"data",
"file",
".",
"Parameters",
"name",... | def create_dataset(
name,
description,
creator,
contributor,
collection_date,
language,
licence,
attributes,
data,
default_target_attribute,
ignore_attribute,
citation,
row_id_attribute=None,
original_data_url=None,
paper_url=None,
update_comment=None,
... | [
"def",
"create_dataset",
"(",
"name",
",",
"description",
",",
"creator",
",",
"contributor",
",",
"collection_date",
",",
"language",
",",
"licence",
",",
"attributes",
",",
"data",
",",
"default_target_attribute",
",",
"ignore_attribute",
",",
"citation",
",",
... | Create a dataset. | [
"Create",
"a",
"dataset",
"."
] | [
"\"\"\"Create a dataset.\n\n This function creates an OpenMLDataset object.\n The OpenMLDataset object contains information related to the dataset\n and the actual data file.\n\n Parameters\n ----------\n name : str\n Name of the dataset.\n description : str\n Description of the d... | [
{
"param": "name",
"type": null
},
{
"param": "description",
"type": null
},
{
"param": "creator",
"type": null
},
{
"param": "contributor",
"type": null
},
{
"param": "collection_date",
"type": null
},
{
"param": "language",
"type": null
},
{
... | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "name",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "description",
"type": null,
"docstring": null,
"docstring_tok... |
34156eff7a93a1c14e85121adc02f83e00376371 | michaelbaluja/openml-python | openml/datasets/functions.py | [
"BSD-3-Clause"
] | Python | edit_dataset | int | def edit_dataset(
data_id,
description=None,
creator=None,
contributor=None,
collection_date=None,
language=None,
default_target_attribute=None,
ignore_attribute=None,
citation=None,
row_id_attribute=None,
original_data_url=None,
paper_url=None,
) -> int:
""" Edits an... | Edits an OpenMLDataset.
In addition to providing the dataset id of the dataset to edit (through data_id),
you must specify a value for at least one of the optional function arguments,
i.e. one value for a field to edit.
This function allows editing of both non-critical and critical fields.
Critic... |
This function allows editing of both non-critical and critical fields.
Editing non-critical data fields is allowed for all authenticated users.
Editing critical fields is allowed only for the owner, provided there are no tasks
associated with this dataset.
If dataset has tasks or if the user is not the owner, the o... | [
"This",
"function",
"allows",
"editing",
"of",
"both",
"non",
"-",
"critical",
"and",
"critical",
"fields",
".",
"Editing",
"non",
"-",
"critical",
"data",
"fields",
"is",
"allowed",
"for",
"all",
"authenticated",
"users",
".",
"Editing",
"critical",
"fields",... | def edit_dataset(
data_id,
description=None,
creator=None,
contributor=None,
collection_date=None,
language=None,
default_target_attribute=None,
ignore_attribute=None,
citation=None,
row_id_attribute=None,
original_data_url=None,
paper_url=None,
) -> int:
if not isins... | [
"def",
"edit_dataset",
"(",
"data_id",
",",
"description",
"=",
"None",
",",
"creator",
"=",
"None",
",",
"contributor",
"=",
"None",
",",
"collection_date",
"=",
"None",
",",
"language",
"=",
"None",
",",
"default_target_attribute",
"=",
"None",
",",
"ignor... | Edits an OpenMLDataset. | [
"Edits",
"an",
"OpenMLDataset",
"."
] | [
"\"\"\" Edits an OpenMLDataset.\n\n In addition to providing the dataset id of the dataset to edit (through data_id),\n you must specify a value for at least one of the optional function arguments,\n i.e. one value for a field to edit.\n\n This function allows editing of both non-critical and critical f... | [
{
"param": "data_id",
"type": null
},
{
"param": "description",
"type": null
},
{
"param": "creator",
"type": null
},
{
"param": "contributor",
"type": null
},
{
"param": "collection_date",
"type": null
},
{
"param": "language",
"type": null
},
... | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "data_id",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "description",
"type": null,
"docstring": null,
"docstring_... |
34156eff7a93a1c14e85121adc02f83e00376371 | michaelbaluja/openml-python | openml/datasets/functions.py | [
"BSD-3-Clause"
] | Python | fork_dataset | int | def fork_dataset(data_id: int) -> int:
"""
Creates a new dataset version, with the authenticated user as the new owner.
The forked dataset can have distinct dataset meta-data,
but the actual data itself is shared with the original version.
This API is intended for use when a user is unable to e... |
Creates a new dataset version, with the authenticated user as the new owner.
The forked dataset can have distinct dataset meta-data,
but the actual data itself is shared with the original version.
This API is intended for use when a user is unable to edit the critical fields of a dataset
thro... | Creates a new dataset version, with the authenticated user as the new owner.
The forked dataset can have distinct dataset meta-data,
but the actual data itself is shared with the original version.
This API is intended for use when a user is unable to edit the critical fields of a dataset
through the edit_dataset API.
... | [
"Creates",
"a",
"new",
"dataset",
"version",
"with",
"the",
"authenticated",
"user",
"as",
"the",
"new",
"owner",
".",
"The",
"forked",
"dataset",
"can",
"have",
"distinct",
"dataset",
"meta",
"-",
"data",
"but",
"the",
"actual",
"data",
"itself",
"is",
"s... | def fork_dataset(data_id: int) -> int:
if not isinstance(data_id, int):
raise TypeError("`data_id` must be of type `int`, not {}.".format(type(data_id)))
form_data = {"data_id": data_id}
result_xml = openml._api_calls._perform_api_call("data/fork", "post", data=form_data)
result = xmltodict.pars... | [
"def",
"fork_dataset",
"(",
"data_id",
":",
"int",
")",
"->",
"int",
":",
"if",
"not",
"isinstance",
"(",
"data_id",
",",
"int",
")",
":",
"raise",
"TypeError",
"(",
"\"`data_id` must be of type `int`, not {}.\"",
".",
"format",
"(",
"type",
"(",
"data_id",
... | Creates a new dataset version, with the authenticated user as the new owner. | [
"Creates",
"a",
"new",
"dataset",
"version",
"with",
"the",
"authenticated",
"user",
"as",
"the",
"new",
"owner",
"."
] | [
"\"\"\"\n Creates a new dataset version, with the authenticated user as the new owner.\n The forked dataset can have distinct dataset meta-data,\n but the actual data itself is shared with the original version.\n\n This API is intended for use when a user is unable to edit the critical fields of a d... | [
{
"param": "data_id",
"type": "int"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "data_id",
"type": "int",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
34156eff7a93a1c14e85121adc02f83e00376371 | michaelbaluja/openml-python | openml/datasets/functions.py | [
"BSD-3-Clause"
] | Python | _topic_add_dataset | <not_specific> | def _topic_add_dataset(data_id: int, topic: str):
"""
Adds a topic for a dataset.
This API is not available for all OpenML users and is accessible only by admins.
Parameters
----------
data_id : int
id of the dataset for which the topic needs to be added
topic : str
Topic to ... |
Adds a topic for a dataset.
This API is not available for all OpenML users and is accessible only by admins.
Parameters
----------
data_id : int
id of the dataset for which the topic needs to be added
topic : str
Topic to be added for the dataset
| Adds a topic for a dataset.
This API is not available for all OpenML users and is accessible only by admins.
Parameters
data_id : int
id of the dataset for which the topic needs to be added
topic : str
Topic to be added for the dataset | [
"Adds",
"a",
"topic",
"for",
"a",
"dataset",
".",
"This",
"API",
"is",
"not",
"available",
"for",
"all",
"OpenML",
"users",
"and",
"is",
"accessible",
"only",
"by",
"admins",
".",
"Parameters",
"data_id",
":",
"int",
"id",
"of",
"the",
"dataset",
"for",
... | def _topic_add_dataset(data_id: int, topic: str):
if not isinstance(data_id, int):
raise TypeError("`data_id` must be of type `int`, not {}.".format(type(data_id)))
form_data = {"data_id": data_id, "topic": topic}
result_xml = openml._api_calls._perform_api_call("data/topicadd", "post", data=form_da... | [
"def",
"_topic_add_dataset",
"(",
"data_id",
":",
"int",
",",
"topic",
":",
"str",
")",
":",
"if",
"not",
"isinstance",
"(",
"data_id",
",",
"int",
")",
":",
"raise",
"TypeError",
"(",
"\"`data_id` must be of type `int`, not {}.\"",
".",
"format",
"(",
"type",... | Adds a topic for a dataset. | [
"Adds",
"a",
"topic",
"for",
"a",
"dataset",
"."
] | [
"\"\"\"\n Adds a topic for a dataset.\n This API is not available for all OpenML users and is accessible only by admins.\n Parameters\n ----------\n data_id : int\n id of the dataset for which the topic needs to be added\n topic : str\n Topic to be added for the dataset\n \"\"\""
] | [
{
"param": "data_id",
"type": "int"
},
{
"param": "topic",
"type": "str"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "data_id",
"type": "int",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "topic",
"type": "str",
"docstring": null,
"docstring_toke... |
34156eff7a93a1c14e85121adc02f83e00376371 | michaelbaluja/openml-python | openml/datasets/functions.py | [
"BSD-3-Clause"
] | Python | _topic_delete_dataset | <not_specific> | def _topic_delete_dataset(data_id: int, topic: str):
"""
Removes a topic from a dataset.
This API is not available for all OpenML users and is accessible only by admins.
Parameters
----------
data_id : int
id of the dataset to be forked
topic : str
Topic to be deleted
"""... |
Removes a topic from a dataset.
This API is not available for all OpenML users and is accessible only by admins.
Parameters
----------
data_id : int
id of the dataset to be forked
topic : str
Topic to be deleted
| Removes a topic from a dataset.
This API is not available for all OpenML users and is accessible only by admins.
Parameters
data_id : int
id of the dataset to be forked
topic : str
Topic to be deleted | [
"Removes",
"a",
"topic",
"from",
"a",
"dataset",
".",
"This",
"API",
"is",
"not",
"available",
"for",
"all",
"OpenML",
"users",
"and",
"is",
"accessible",
"only",
"by",
"admins",
".",
"Parameters",
"data_id",
":",
"int",
"id",
"of",
"the",
"dataset",
"to... | def _topic_delete_dataset(data_id: int, topic: str):
if not isinstance(data_id, int):
raise TypeError("`data_id` must be of type `int`, not {}.".format(type(data_id)))
form_data = {"data_id": data_id, "topic": topic}
result_xml = openml._api_calls._perform_api_call("data/topicdelete", "post", data=f... | [
"def",
"_topic_delete_dataset",
"(",
"data_id",
":",
"int",
",",
"topic",
":",
"str",
")",
":",
"if",
"not",
"isinstance",
"(",
"data_id",
",",
"int",
")",
":",
"raise",
"TypeError",
"(",
"\"`data_id` must be of type `int`, not {}.\"",
".",
"format",
"(",
"typ... | Removes a topic from a dataset. | [
"Removes",
"a",
"topic",
"from",
"a",
"dataset",
"."
] | [
"\"\"\"\n Removes a topic from a dataset.\n This API is not available for all OpenML users and is accessible only by admins.\n Parameters\n ----------\n data_id : int\n id of the dataset to be forked\n topic : str\n Topic to be deleted\n\n \"\"\""
] | [
{
"param": "data_id",
"type": "int"
},
{
"param": "topic",
"type": "str"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "data_id",
"type": "int",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "topic",
"type": "str",
"docstring": null,
"docstring_toke... |
34156eff7a93a1c14e85121adc02f83e00376371 | michaelbaluja/openml-python | openml/datasets/functions.py | [
"BSD-3-Clause"
] | Python | _get_dataset_parquet | Optional[str] | def _get_dataset_parquet(
description: Union[Dict, OpenMLDataset], cache_directory: str = None
) -> Optional[str]:
""" Return the path to the local parquet file of the dataset. If is not cached, it is downloaded.
Checks if the file is in the cache, if yes, return the path to the file.
If not, downloads... | Return the path to the local parquet file of the dataset. If is not cached, it is downloaded.
Checks if the file is in the cache, if yes, return the path to the file.
If not, downloads the file and caches it, then returns the file path.
The cache directory is generated based on dataset information, but ca... | Return the path to the local parquet file of the dataset. If is not cached, it is downloaded.
Checks if the file is in the cache, if yes, return the path to the file.
If not, downloads the file and caches it, then returns the file path.
The cache directory is generated based on dataset information, but can also be spec... | [
"Return",
"the",
"path",
"to",
"the",
"local",
"parquet",
"file",
"of",
"the",
"dataset",
".",
"If",
"is",
"not",
"cached",
"it",
"is",
"downloaded",
".",
"Checks",
"if",
"the",
"file",
"is",
"in",
"the",
"cache",
"if",
"yes",
"return",
"the",
"path",
... | def _get_dataset_parquet(
description: Union[Dict, OpenMLDataset], cache_directory: str = None
) -> Optional[str]:
if isinstance(description, dict):
url = description.get("oml:minio_url")
did = description.get("oml:id")
elif isinstance(description, OpenMLDataset):
url = description._... | [
"def",
"_get_dataset_parquet",
"(",
"description",
":",
"Union",
"[",
"Dict",
",",
"OpenMLDataset",
"]",
",",
"cache_directory",
":",
"str",
"=",
"None",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"if",
"isinstance",
"(",
"description",
",",
"dict",
")",... | Return the path to the local parquet file of the dataset. | [
"Return",
"the",
"path",
"to",
"the",
"local",
"parquet",
"file",
"of",
"the",
"dataset",
"."
] | [
"\"\"\" Return the path to the local parquet file of the dataset. If is not cached, it is downloaded.\n\n Checks if the file is in the cache, if yes, return the path to the file.\n If not, downloads the file and caches it, then returns the file path.\n The cache directory is generated based on dataset info... | [
{
"param": "description",
"type": "Union[Dict, OpenMLDataset]"
},
{
"param": "cache_directory",
"type": "str"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "description",
"type": "Union[Dict, OpenMLDataset]",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "cache_directory",
"type": "str",
"do... |
34156eff7a93a1c14e85121adc02f83e00376371 | michaelbaluja/openml-python | openml/datasets/functions.py | [
"BSD-3-Clause"
] | Python | _get_dataset_arff | str | def _get_dataset_arff(description: Union[Dict, OpenMLDataset], cache_directory: str = None) -> str:
""" Return the path to the local arff file of the dataset. If is not cached, it is downloaded.
Checks if the file is in the cache, if yes, return the path to the file.
If not, downloads the file and caches i... | Return the path to the local arff file of the dataset. If is not cached, it is downloaded.
Checks if the file is in the cache, if yes, return the path to the file.
If not, downloads the file and caches it, then returns the file path.
The cache directory is generated based on dataset information, but can a... | Return the path to the local arff file of the dataset. If is not cached, it is downloaded.
Checks if the file is in the cache, if yes, return the path to the file.
If not, downloads the file and caches it, then returns the file path.
The cache directory is generated based on dataset information, but can also be specifi... | [
"Return",
"the",
"path",
"to",
"the",
"local",
"arff",
"file",
"of",
"the",
"dataset",
".",
"If",
"is",
"not",
"cached",
"it",
"is",
"downloaded",
".",
"Checks",
"if",
"the",
"file",
"is",
"in",
"the",
"cache",
"if",
"yes",
"return",
"the",
"path",
"... | def _get_dataset_arff(description: Union[Dict, OpenMLDataset], cache_directory: str = None) -> str:
if isinstance(description, dict):
md5_checksum_fixture = description.get("oml:md5_checksum")
url = description["oml:url"]
did = description.get("oml:id")
elif isinstance(description, OpenM... | [
"def",
"_get_dataset_arff",
"(",
"description",
":",
"Union",
"[",
"Dict",
",",
"OpenMLDataset",
"]",
",",
"cache_directory",
":",
"str",
"=",
"None",
")",
"->",
"str",
":",
"if",
"isinstance",
"(",
"description",
",",
"dict",
")",
":",
"md5_checksum_fixture... | Return the path to the local arff file of the dataset. | [
"Return",
"the",
"path",
"to",
"the",
"local",
"arff",
"file",
"of",
"the",
"dataset",
"."
] | [
"\"\"\" Return the path to the local arff file of the dataset. If is not cached, it is downloaded.\n\n Checks if the file is in the cache, if yes, return the path to the file.\n If not, downloads the file and caches it, then returns the file path.\n The cache directory is generated based on dataset informa... | [
{
"param": "description",
"type": "Union[Dict, OpenMLDataset]"
},
{
"param": "cache_directory",
"type": "str"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "description",
"type": "Union[Dict, OpenMLDataset]",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "cache_directory",
"type": "str",
"do... |
34156eff7a93a1c14e85121adc02f83e00376371 | michaelbaluja/openml-python | openml/datasets/functions.py | [
"BSD-3-Clause"
] | Python | _create_dataset_from_description | OpenMLDataset | def _create_dataset_from_description(
description: Dict[str, str],
features_file: str,
qualities_file: str,
arff_file: str = None,
parquet_file: str = None,
cache_format: str = "pickle",
) -> OpenMLDataset:
"""Create a dataset object from a description dict.
Parameters
----------
... | Create a dataset object from a description dict.
Parameters
----------
description : dict
Description of a dataset in xml dict.
featuresfile : str
Path of the dataset features as xml file.
qualities : list
Path of the dataset qualities as xml file.
arff_file : string, op... | Create a dataset object from a description dict.
Parameters
description : dict
Description of a dataset in xml dict.
featuresfile : str
Path of the dataset features as xml file.
qualities : list
Path of the dataset qualities as xml file.
arff_file : string, optional
Path of dataset ARFF file.
parquet_file : string, op... | [
"Create",
"a",
"dataset",
"object",
"from",
"a",
"description",
"dict",
".",
"Parameters",
"description",
":",
"dict",
"Description",
"of",
"a",
"dataset",
"in",
"xml",
"dict",
".",
"featuresfile",
":",
"str",
"Path",
"of",
"the",
"dataset",
"features",
"as"... | def _create_dataset_from_description(
description: Dict[str, str],
features_file: str,
qualities_file: str,
arff_file: str = None,
parquet_file: str = None,
cache_format: str = "pickle",
) -> OpenMLDataset:
return OpenMLDataset(
description["oml:name"],
description.get("oml:d... | [
"def",
"_create_dataset_from_description",
"(",
"description",
":",
"Dict",
"[",
"str",
",",
"str",
"]",
",",
"features_file",
":",
"str",
",",
"qualities_file",
":",
"str",
",",
"arff_file",
":",
"str",
"=",
"None",
",",
"parquet_file",
":",
"str",
"=",
"... | Create a dataset object from a description dict. | [
"Create",
"a",
"dataset",
"object",
"from",
"a",
"description",
"dict",
"."
] | [
"\"\"\"Create a dataset object from a description dict.\n\n Parameters\n ----------\n description : dict\n Description of a dataset in xml dict.\n featuresfile : str\n Path of the dataset features as xml file.\n qualities : list\n Path of the dataset qualities as xml file.\n a... | [
{
"param": "description",
"type": "Dict[str, str]"
},
{
"param": "features_file",
"type": "str"
},
{
"param": "qualities_file",
"type": "str"
},
{
"param": "arff_file",
"type": "str"
},
{
"param": "parquet_file",
"type": "str"
},
{
"param": "cache_form... | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "description",
"type": "Dict[str, str]",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "features_file",
"type": "str",
"docstring": null... |
122e2e697a96ea852c7691068bff1271c15e04bf | michaelbaluja/openml-python | openml/datasets/dataset.py | [
"BSD-3-Clause"
] | Python | _download_data | None | def _download_data(self) -> None:
""" Download ARFF data file to standard cache directory. Set `self.data_file`. """
# import required here to avoid circular import.
from .functions import _get_dataset_arff, _get_dataset_parquet
self.data_file = _get_dataset_arff(self)
if self._... | Download ARFF data file to standard cache directory. Set `self.data_file`. | Download ARFF data file to standard cache directory. | [
"Download",
"ARFF",
"data",
"file",
"to",
"standard",
"cache",
"directory",
"."
] | def _download_data(self) -> None:
from .functions import _get_dataset_arff, _get_dataset_parquet
self.data_file = _get_dataset_arff(self)
if self._minio_url is not None:
self.parquet_file = _get_dataset_parquet(self) | [
"def",
"_download_data",
"(",
"self",
")",
"->",
"None",
":",
"from",
".",
"functions",
"import",
"_get_dataset_arff",
",",
"_get_dataset_parquet",
"self",
".",
"data_file",
"=",
"_get_dataset_arff",
"(",
"self",
")",
"if",
"self",
".",
"_minio_url",
"is",
"no... | Download ARFF data file to standard cache directory. | [
"Download",
"ARFF",
"data",
"file",
"to",
"standard",
"cache",
"directory",
"."
] | [
"\"\"\" Download ARFF data file to standard cache directory. Set `self.data_file`. \"\"\"",
"# import required here to avoid circular import."
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
122e2e697a96ea852c7691068bff1271c15e04bf | michaelbaluja/openml-python | openml/datasets/dataset.py | [
"BSD-3-Clause"
] | Python | _cache_compressed_file_from_file | Tuple[Union[pd.DataFrame, scipy.sparse.csr_matrix], List[bool], List[str]] | def _cache_compressed_file_from_file(
self, data_file: str
) -> Tuple[Union[pd.DataFrame, scipy.sparse.csr_matrix], List[bool], List[str]]:
""" Store data from the local file in compressed format.
If a local parquet file is present it will be used instead of the arff file.
Sets cach... | Store data from the local file in compressed format.
If a local parquet file is present it will be used instead of the arff file.
Sets cache_format to 'pickle' if data is sparse.
| Store data from the local file in compressed format.
If a local parquet file is present it will be used instead of the arff file.
Sets cache_format to 'pickle' if data is sparse. | [
"Store",
"data",
"from",
"the",
"local",
"file",
"in",
"compressed",
"format",
".",
"If",
"a",
"local",
"parquet",
"file",
"is",
"present",
"it",
"will",
"be",
"used",
"instead",
"of",
"the",
"arff",
"file",
".",
"Sets",
"cache_format",
"to",
"'",
"pickl... | def _cache_compressed_file_from_file(
self, data_file: str
) -> Tuple[Union[pd.DataFrame, scipy.sparse.csr_matrix], List[bool], List[str]]:
(
data_pickle_file,
data_feather_file,
feather_attribute_file,
) = self._compressed_cache_file_paths(data_file)
... | [
"def",
"_cache_compressed_file_from_file",
"(",
"self",
",",
"data_file",
":",
"str",
")",
"->",
"Tuple",
"[",
"Union",
"[",
"pd",
".",
"DataFrame",
",",
"scipy",
".",
"sparse",
".",
"csr_matrix",
"]",
",",
"List",
"[",
"bool",
"]",
",",
"List",
"[",
"... | Store data from the local file in compressed format. | [
"Store",
"data",
"from",
"the",
"local",
"file",
"in",
"compressed",
"format",
"."
] | [
"\"\"\" Store data from the local file in compressed format.\n\n If a local parquet file is present it will be used instead of the arff file.\n Sets cache_format to 'pickle' if data is sparse.\n \"\"\"",
"# Feather format does not work for sparse datasets, so we use pickle for sparse datasets... | [
{
"param": "self",
"type": null
},
{
"param": "data_file",
"type": "str"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "data_file",
"type": "str",
"docstring": null,
"docstring_toke... |
122e2e697a96ea852c7691068bff1271c15e04bf | michaelbaluja/openml-python | openml/datasets/dataset.py | [
"BSD-3-Clause"
] | Python | _load_data | <not_specific> | def _load_data(self):
""" Load data from compressed format or arff. Download data if not present on disk. """
need_to_create_pickle = self.cache_format == "pickle" and self.data_pickle_file is None
need_to_create_feather = self.cache_format == "feather" and self.data_feather_file is None
... | Load data from compressed format or arff. Download data if not present on disk. | Load data from compressed format or arff. Download data if not present on disk. | [
"Load",
"data",
"from",
"compressed",
"format",
"or",
"arff",
".",
"Download",
"data",
"if",
"not",
"present",
"on",
"disk",
"."
] | def _load_data(self):
need_to_create_pickle = self.cache_format == "pickle" and self.data_pickle_file is None
need_to_create_feather = self.cache_format == "feather" and self.data_feather_file is None
if need_to_create_pickle or need_to_create_feather:
if self.data_file is None:
... | [
"def",
"_load_data",
"(",
"self",
")",
":",
"need_to_create_pickle",
"=",
"self",
".",
"cache_format",
"==",
"\"pickle\"",
"and",
"self",
".",
"data_pickle_file",
"is",
"None",
"need_to_create_feather",
"=",
"self",
".",
"cache_format",
"==",
"\"feather\"",
"and",... | Load data from compressed format or arff. | [
"Load",
"data",
"from",
"compressed",
"format",
"or",
"arff",
"."
] | [
"\"\"\" Load data from compressed format or arff. Download data if not present on disk. \"\"\"",
"# helper variable to help identify where errors occur",
"# noqa: 501",
"# an unknown ValueError is raised, should crash and file bug report"
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
122e2e697a96ea852c7691068bff1271c15e04bf | michaelbaluja/openml-python | openml/datasets/dataset.py | [
"BSD-3-Clause"
] | Python | _convert_array_format | <not_specific> | def _convert_array_format(data, array_format, attribute_names):
"""Convert a dataset to a given array format.
Converts to numpy array if data is non-sparse.
Converts to a sparse dataframe if data is sparse.
Parameters
----------
array_format : str {'array', 'dataframe'}... | Convert a dataset to a given array format.
Converts to numpy array if data is non-sparse.
Converts to a sparse dataframe if data is sparse.
Parameters
----------
array_format : str {'array', 'dataframe'}
Desired data type of the output
- If array_format=... | Convert a dataset to a given array format.
Converts to numpy array if data is non-sparse.
Converts to a sparse dataframe if data is sparse.
Parameters
| [
"Convert",
"a",
"dataset",
"to",
"a",
"given",
"array",
"format",
".",
"Converts",
"to",
"numpy",
"array",
"if",
"data",
"is",
"non",
"-",
"sparse",
".",
"Converts",
"to",
"a",
"sparse",
"dataframe",
"if",
"data",
"is",
"sparse",
".",
"Parameters"
] | def _convert_array_format(data, array_format, attribute_names):
if array_format == "array" and not scipy.sparse.issparse(data):
def _encode_if_category(column):
if column.dtype.name == "category":
column = column.cat.codes.astype(np.float32)
ma... | [
"def",
"_convert_array_format",
"(",
"data",
",",
"array_format",
",",
"attribute_names",
")",
":",
"if",
"array_format",
"==",
"\"array\"",
"and",
"not",
"scipy",
".",
"sparse",
".",
"issparse",
"(",
"data",
")",
":",
"def",
"_encode_if_category",
"(",
"colum... | Convert a dataset to a given array format. | [
"Convert",
"a",
"dataset",
"to",
"a",
"given",
"array",
"format",
"."
] | [
"\"\"\"Convert a dataset to a given array format.\n\n Converts to numpy array if data is non-sparse.\n Converts to a sparse dataframe if data is sparse.\n\n Parameters\n ----------\n array_format : str {'array', 'dataframe'}\n Desired data type of the output\n ... | [
{
"param": "data",
"type": null
},
{
"param": "array_format",
"type": null
},
{
"param": "attribute_names",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "data",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "array_format",
"type": null,
"docstring": null,
"docstring_to... |
122e2e697a96ea852c7691068bff1271c15e04bf | michaelbaluja/openml-python | openml/datasets/dataset.py | [
"BSD-3-Clause"
] | Python | retrieve_class_labels | Union[None, List[str]] | def retrieve_class_labels(self, target_name: str = "class") -> Union[None, List[str]]:
"""Reads the datasets arff to determine the class-labels.
If the task has no class labels (for example a regression problem)
it returns None. Necessary because the data returned by get_data
only conta... | Reads the datasets arff to determine the class-labels.
If the task has no class labels (for example a regression problem)
it returns None. Necessary because the data returned by get_data
only contains the indices of the classes, while OpenML needs the real
classname when uploading the r... | Reads the datasets arff to determine the class-labels.
If the task has no class labels (for example a regression problem)
it returns None. Necessary because the data returned by get_data
only contains the indices of the classes, while OpenML needs the real
classname when uploading the results of a run.
Parameters
tar... | [
"Reads",
"the",
"datasets",
"arff",
"to",
"determine",
"the",
"class",
"-",
"labels",
".",
"If",
"the",
"task",
"has",
"no",
"class",
"labels",
"(",
"for",
"example",
"a",
"regression",
"problem",
")",
"it",
"returns",
"None",
".",
"Necessary",
"because",
... | def retrieve_class_labels(self, target_name: str = "class") -> Union[None, List[str]]:
if self.features is None:
raise ValueError(
"retrieve_class_labels can only be called if feature information is available."
)
for feature in self.features.values():
... | [
"def",
"retrieve_class_labels",
"(",
"self",
",",
"target_name",
":",
"str",
"=",
"\"class\"",
")",
"->",
"Union",
"[",
"None",
",",
"List",
"[",
"str",
"]",
"]",
":",
"if",
"self",
".",
"features",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"ret... | Reads the datasets arff to determine the class-labels. | [
"Reads",
"the",
"datasets",
"arff",
"to",
"determine",
"the",
"class",
"-",
"labels",
"."
] | [
"\"\"\"Reads the datasets arff to determine the class-labels.\n\n If the task has no class labels (for example a regression problem)\n it returns None. Necessary because the data returned by get_data\n only contains the indices of the classes, while OpenML needs the real\n classname when... | [
{
"param": "self",
"type": null
},
{
"param": "target_name",
"type": "str"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "target_name",
"type": "str",
"docstring": null,
"docstring_to... |
122e2e697a96ea852c7691068bff1271c15e04bf | michaelbaluja/openml-python | openml/datasets/dataset.py | [
"BSD-3-Clause"
] | Python | _get_file_elements | Dict | def _get_file_elements(self) -> Dict:
""" Adds the 'dataset' to file elements. """
file_elements = {}
path = None if self.data_file is None else os.path.abspath(self.data_file)
if self._dataset is not None:
file_elements["dataset"] = self._dataset
elif path is not No... | Adds the 'dataset' to file elements. | Adds the 'dataset' to file elements. | [
"Adds",
"the",
"'",
"dataset",
"'",
"to",
"file",
"elements",
"."
] | def _get_file_elements(self) -> Dict:
file_elements = {}
path = None if self.data_file is None else os.path.abspath(self.data_file)
if self._dataset is not None:
file_elements["dataset"] = self._dataset
elif path is not None and os.path.exists(path):
with open(pat... | [
"def",
"_get_file_elements",
"(",
"self",
")",
"->",
"Dict",
":",
"file_elements",
"=",
"{",
"}",
"path",
"=",
"None",
"if",
"self",
".",
"data_file",
"is",
"None",
"else",
"os",
".",
"path",
".",
"abspath",
"(",
"self",
".",
"data_file",
")",
"if",
... | Adds the 'dataset' to file elements. | [
"Adds",
"the",
"'",
"dataset",
"'",
"to",
"file",
"elements",
"."
] | [
"\"\"\" Adds the 'dataset' to file elements. \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
122e2e697a96ea852c7691068bff1271c15e04bf | michaelbaluja/openml-python | openml/datasets/dataset.py | [
"BSD-3-Clause"
] | Python | _to_dict | "OrderedDict[str, OrderedDict]" | def _to_dict(self) -> "OrderedDict[str, OrderedDict]":
""" Creates a dictionary representation of self. """
props = [
"id",
"name",
"version",
"description",
"format",
"creator",
"contributor",
"collection_da... | Creates a dictionary representation of self. | Creates a dictionary representation of self. | [
"Creates",
"a",
"dictionary",
"representation",
"of",
"self",
"."
] | def _to_dict(self) -> "OrderedDict[str, OrderedDict]":
props = [
"id",
"name",
"version",
"description",
"format",
"creator",
"contributor",
"collection_date",
"upload_date",
"language",
... | [
"def",
"_to_dict",
"(",
"self",
")",
"->",
"\"OrderedDict[str, OrderedDict]\"",
":",
"props",
"=",
"[",
"\"id\"",
",",
"\"name\"",
",",
"\"version\"",
",",
"\"description\"",
",",
"\"format\"",
",",
"\"creator\"",
",",
"\"contributor\"",
",",
"\"collection_date\"",
... | Creates a dictionary representation of self. | [
"Creates",
"a",
"dictionary",
"representation",
"of",
"self",
"."
] | [
"\"\"\" Creates a dictionary representation of self. \"\"\"",
"# type: 'OrderedDict[str, OrderedDict]'"
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
d9435f70a9d1dffbcdd726abfeeea6fad071352c | rob-dalton/fantasy-football-analytics | etc/roster_scraper.py | [
"MIT"
] | Python | _extract_page_content | <not_specific> | def _extract_page_content(self, content):
"""
INPUT: String
RETURN: List of list of strings
Take in string of HTML content. Find table of player data, parse each td
element for individual player data. Return list of player data.
"""
data = None
soup = bs... |
INPUT: String
RETURN: List of list of strings
Take in string of HTML content. Find table of player data, parse each td
element for individual player data. Return list of player data.
| String
RETURN: List of list of strings
Take in string of HTML content. Find table of player data, parse each td
element for individual player data. Return list of player data. | [
"String",
"RETURN",
":",
"List",
"of",
"list",
"of",
"strings",
"Take",
"in",
"string",
"of",
"HTML",
"content",
".",
"Find",
"table",
"of",
"player",
"data",
"parse",
"each",
"td",
"element",
"for",
"individual",
"player",
"data",
".",
"Return",
"list",
... | def _extract_page_content(self, content):
data = None
soup = bs4.BeautifulSoup(content, 'html.parser')
table = soup.find('div',
class_=re.compile('wisbb_playersTable'))
if table:
rows = table.find("tbody").findAll("tr")
num_pos = [[el.text... | [
"def",
"_extract_page_content",
"(",
"self",
",",
"content",
")",
":",
"data",
"=",
"None",
"soup",
"=",
"bs4",
".",
"BeautifulSoup",
"(",
"content",
",",
"'html.parser'",
")",
"table",
"=",
"soup",
".",
"find",
"(",
"'div'",
",",
"class_",
"=",
"re",
... | INPUT: String
RETURN: List of list of strings | [
"INPUT",
":",
"String",
"RETURN",
":",
"List",
"of",
"list",
"of",
"strings"
] | [
"\"\"\"\n INPUT: String\n RETURN: List of list of strings\n\n Take in string of HTML content. Find table of player data, parse each td\n element for individual player data. Return list of player data.\n\n \"\"\"",
"# get raw strings for content of each td",
"# split num_pos",
... | [
{
"param": "self",
"type": null
},
{
"param": "content",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "content",
"type": null,
"docstring": null,
"docstring_tokens"... |
78eab4f10a2fffe44ad52c93e1ee08690f98a4a6 | rob-dalton/fantasy-football-analytics | etc/career_extractor.py | [
"MIT"
] | Python | _get_seasons | DataFrame | def _get_seasons(self)->DataFrame:
""" get list of seasons played from csv files """
# setup data
players_df = pd.read_csv(self.players_fpath)
old_rosters_df = pd.read_csv(self.old_rosters_fpath)
# get pre 2009 seasons
df_old_seasons = pd.DataFrame(old_rosters_df.drop(['... | get list of seasons played from csv files | get list of seasons played from csv files | [
"get",
"list",
"of",
"seasons",
"played",
"from",
"csv",
"files"
] | def _get_seasons(self)->DataFrame:
players_df = pd.read_csv(self.players_fpath)
old_rosters_df = pd.read_csv(self.old_rosters_fpath)
df_old_seasons = pd.DataFrame(old_rosters_df.drop(['Team', 'Number'], axis=1)\
.groupby(['Full_Name',
... | [
"def",
"_get_seasons",
"(",
"self",
")",
"->",
"DataFrame",
":",
"players_df",
"=",
"pd",
".",
"read_csv",
"(",
"self",
".",
"players_fpath",
")",
"old_rosters_df",
"=",
"pd",
".",
"read_csv",
"(",
"self",
".",
"old_rosters_fpath",
")",
"df_old_seasons",
"="... | get list of seasons played from csv files | [
"get",
"list",
"of",
"seasons",
"played",
"from",
"csv",
"files"
] | [
"\"\"\" get list of seasons played from csv files \"\"\"",
"# setup data",
"# get pre 2009 seasons",
"# get seasons 2009 onwards",
"# join old and new seasons"
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
78eab4f10a2fffe44ad52c93e1ee08690f98a4a6 | rob-dalton/fantasy-football-analytics | etc/career_extractor.py | [
"MIT"
] | Python | _apply_corrections | None | def _apply_corrections(self,
df_seasons: DataFrame,
corrections: dict)->None:
""" apply corrections to season data inplace """
df_seasons.set_index('Player_ID', inplace=True)
for p_id, p_corrections in corrections.items():
for col... | apply corrections to season data inplace | apply corrections to season data inplace | [
"apply",
"corrections",
"to",
"season",
"data",
"inplace"
] | def _apply_corrections(self,
df_seasons: DataFrame,
corrections: dict)->None:
df_seasons.set_index('Player_ID', inplace=True)
for p_id, p_corrections in corrections.items():
for col, val in p_corrections.items():
df_season... | [
"def",
"_apply_corrections",
"(",
"self",
",",
"df_seasons",
":",
"DataFrame",
",",
"corrections",
":",
"dict",
")",
"->",
"None",
":",
"df_seasons",
".",
"set_index",
"(",
"'Player_ID'",
",",
"inplace",
"=",
"True",
")",
"for",
"p_id",
",",
"p_corrections",... | apply corrections to season data inplace | [
"apply",
"corrections",
"to",
"season",
"data",
"inplace"
] | [
"\"\"\" apply corrections to season data inplace \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "df_seasons",
"type": "DataFrame"
},
{
"param": "corrections",
"type": "dict"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "df_seasons",
"type": "DataFrame",
"docstring": null,
"docstri... |
78eab4f10a2fffe44ad52c93e1ee08690f98a4a6 | rob-dalton/fantasy-football-analytics | etc/career_extractor.py | [
"MIT"
] | Python | _combine_seasons | List | def _combine_seasons(self, row: Series)->List:
""" given row, return combined list of seasons played """
if type(row['Seasons_old'])==float and np.isnan(row['Seasons_old']):
return sorted(row['Seasons'])
else:
return sorted(row['Seasons']+row['Seasons_old']) | given row, return combined list of seasons played | given row, return combined list of seasons played | [
"given",
"row",
"return",
"combined",
"list",
"of",
"seasons",
"played"
] | def _combine_seasons(self, row: Series)->List:
if type(row['Seasons_old'])==float and np.isnan(row['Seasons_old']):
return sorted(row['Seasons'])
else:
return sorted(row['Seasons']+row['Seasons_old']) | [
"def",
"_combine_seasons",
"(",
"self",
",",
"row",
":",
"Series",
")",
"->",
"List",
":",
"if",
"type",
"(",
"row",
"[",
"'Seasons_old'",
"]",
")",
"==",
"float",
"and",
"np",
".",
"isnan",
"(",
"row",
"[",
"'Seasons_old'",
"]",
")",
":",
"return",
... | given row, return combined list of seasons played | [
"given",
"row",
"return",
"combined",
"list",
"of",
"seasons",
"played"
] | [
"\"\"\" given row, return combined list of seasons played \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "row",
"type": "Series"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "row",
"type": "Series",
"docstring": null,
"docstring_tokens"... |
fb6b1d5256e35422d2a2ad4d952ed2185cf1c744 | rob-dalton/fantasy-football-analytics | aggregators/base.py | [
"MIT"
] | Python | _score | DataFrame | def _score(self, point_system: str = None) -> DataFrame:
""" Add fantasy points to aggregated DataFrame """
#TODO: Add additional point systems for _score and scorers
scorer = None
if point_system is None:
scorer = StandardScorer()
scorer.score(self._aggregated_data... | Add fantasy points to aggregated DataFrame | Add fantasy points to aggregated DataFrame | [
"Add",
"fantasy",
"points",
"to",
"aggregated",
"DataFrame"
] | def _score(self, point_system: str = None) -> DataFrame:
scorer = None
if point_system is None:
scorer = StandardScorer()
scorer.score(self._aggregated_data_frame, inplace=True) | [
"def",
"_score",
"(",
"self",
",",
"point_system",
":",
"str",
"=",
"None",
")",
"->",
"DataFrame",
":",
"scorer",
"=",
"None",
"if",
"point_system",
"is",
"None",
":",
"scorer",
"=",
"StandardScorer",
"(",
")",
"scorer",
".",
"score",
"(",
"self",
"."... | Add fantasy points to aggregated DataFrame | [
"Add",
"fantasy",
"points",
"to",
"aggregated",
"DataFrame"
] | [
"\"\"\" Add fantasy points to aggregated DataFrame \"\"\"",
"#TODO: Add additional point systems for _score and scorers"
] | [
{
"param": "self",
"type": null
},
{
"param": "point_system",
"type": "str"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "point_system",
"type": "str",
"docstring": null,
"docstring_t... |
fb6b1d5256e35422d2a2ad4d952ed2185cf1c744 | rob-dalton/fantasy-football-analytics | aggregators/base.py | [
"MIT"
] | Python | _clean_data | None | def _clean_data(self) -> None:
""" Rename Player_ID columns, clean data as needed """
for df in self._data_frames.values():
df.drop(['Team', 'Player_Name'], axis=1, inplace=True)
df.rename(columns={'Passer_ID': 'Player_ID',
'Rusher_ID': 'Player_ID',... | Rename Player_ID columns, clean data as needed | Rename Player_ID columns, clean data as needed | [
"Rename",
"Player_ID",
"columns",
"clean",
"data",
"as",
"needed"
] | def _clean_data(self) -> None:
for df in self._data_frames.values():
df.drop(['Team', 'Player_Name'], axis=1, inplace=True)
df.rename(columns={'Passer_ID': 'Player_ID',
'Rusher_ID': 'Player_ID',
'Receiver_ID': 'Player_ID'},
... | [
"def",
"_clean_data",
"(",
"self",
")",
"->",
"None",
":",
"for",
"df",
"in",
"self",
".",
"_data_frames",
".",
"values",
"(",
")",
":",
"df",
".",
"drop",
"(",
"[",
"'Team'",
",",
"'Player_Name'",
"]",
",",
"axis",
"=",
"1",
",",
"inplace",
"=",
... | Rename Player_ID columns, clean data as needed | [
"Rename",
"Player_ID",
"columns",
"clean",
"data",
"as",
"needed"
] | [
"\"\"\" Rename Player_ID columns, clean data as needed \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
514bf64648c20ea91fc1b60c4abe902e797612a7 | rob-dalton/fantasy-football-analytics | aggregators/game_player.py | [
"MIT"
] | Python | _clean_data | None | def _clean_data(self) -> None:
""" Rename ID columns and set IDs as multi-index """
super(GamePlayerAggregator, self)._clean_data()
for df in self._data_frames.values():
df.set_index(['GameID', 'Player_ID'], inplace=True) | Rename ID columns and set IDs as multi-index | Rename ID columns and set IDs as multi-index | [
"Rename",
"ID",
"columns",
"and",
"set",
"IDs",
"as",
"multi",
"-",
"index"
] | def _clean_data(self) -> None:
super(GamePlayerAggregator, self)._clean_data()
for df in self._data_frames.values():
df.set_index(['GameID', 'Player_ID'], inplace=True) | [
"def",
"_clean_data",
"(",
"self",
")",
"->",
"None",
":",
"super",
"(",
"GamePlayerAggregator",
",",
"self",
")",
".",
"_clean_data",
"(",
")",
"for",
"df",
"in",
"self",
".",
"_data_frames",
".",
"values",
"(",
")",
":",
"df",
".",
"set_index",
"(",
... | Rename ID columns and set IDs as multi-index | [
"Rename",
"ID",
"columns",
"and",
"set",
"IDs",
"as",
"multi",
"-",
"index"
] | [
"\"\"\" Rename ID columns and set IDs as multi-index \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
6019301e31bcd48f172da7186b9457958ce6d3cf | rob-dalton/fantasy-football-analytics | etc/scorers.py | [
"MIT"
] | Python | score | Optional[DataFrame] | def score(self, df: DataFrame, inplace: bool = False) -> Optional[DataFrame]:
"""
Add score to DataFrame
:param inplace: add score column inplace instead of returning new DataFrame
"""
raise NotImplementedError |
Add score to DataFrame
:param inplace: add score column inplace instead of returning new DataFrame
| Add score to DataFrame
:param inplace: add score column inplace instead of returning new DataFrame | [
"Add",
"score",
"to",
"DataFrame",
":",
"param",
"inplace",
":",
"add",
"score",
"column",
"inplace",
"instead",
"of",
"returning",
"new",
"DataFrame"
] | def score(self, df: DataFrame, inplace: bool = False) -> Optional[DataFrame]:
raise NotImplementedError | [
"def",
"score",
"(",
"self",
",",
"df",
":",
"DataFrame",
",",
"inplace",
":",
"bool",
"=",
"False",
")",
"->",
"Optional",
"[",
"DataFrame",
"]",
":",
"raise",
"NotImplementedError"
] | Add score to DataFrame
:param inplace: add score column inplace instead of returning new DataFrame | [
"Add",
"score",
"to",
"DataFrame",
":",
"param",
"inplace",
":",
"add",
"score",
"column",
"inplace",
"instead",
"of",
"returning",
"new",
"DataFrame"
] | [
"\"\"\"\n Add score to DataFrame\n :param inplace: add score column inplace instead of returning new DataFrame\n\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "df",
"type": "DataFrame"
},
{
"param": "inplace",
"type": "bool"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "df",
"type": "DataFrame",
"docstring": null,
"docstring_token... |
7a08a2caa32fe5c68fbd75d38d86cb0bd10eef61 | rob-dalton/fantasy-football-analytics | aggregators/season_player.py | [
"MIT"
] | Python | _clean_data | None | def _clean_data(self) -> None:
""" Rename ID columns and set IDs as multi-index """
super(SeasonPlayerAggregator, self)._clean_data()
for df in self._data_frames.values():
df.set_index(['Player_ID', 'Season'], inplace=True) | Rename ID columns and set IDs as multi-index | Rename ID columns and set IDs as multi-index | [
"Rename",
"ID",
"columns",
"and",
"set",
"IDs",
"as",
"multi",
"-",
"index"
] | def _clean_data(self) -> None:
super(SeasonPlayerAggregator, self)._clean_data()
for df in self._data_frames.values():
df.set_index(['Player_ID', 'Season'], inplace=True) | [
"def",
"_clean_data",
"(",
"self",
")",
"->",
"None",
":",
"super",
"(",
"SeasonPlayerAggregator",
",",
"self",
")",
".",
"_clean_data",
"(",
")",
"for",
"df",
"in",
"self",
".",
"_data_frames",
".",
"values",
"(",
")",
":",
"df",
".",
"set_index",
"("... | Rename ID columns and set IDs as multi-index | [
"Rename",
"ID",
"columns",
"and",
"set",
"IDs",
"as",
"multi",
"-",
"index"
] | [
"\"\"\" Rename ID columns and set IDs as multi-index \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
d300c533cf4ebcc57e7fa134f3355802b71343ea | Joukahainen/sample-market-maker | market_maker/ws/ws_thread.py | [
"Apache-2.0"
] | Python | connect | null | def connect(self, endpoint="", symbol="XBTN15", shouldAuth=True):
'''Connect to the websocket and initialize data stores.'''
logger.debug("Connecting WebSocket.")
self.symbol = symbol
self.shouldAuth = shouldAuth
# We can subscribe right in the connection querystring, so let's ... | Connect to the websocket and initialize data stores. | Connect to the websocket and initialize data stores. | [
"Connect",
"to",
"the",
"websocket",
"and",
"initialize",
"data",
"stores",
"."
] | def connect(self, endpoint="", symbol="XBTN15", shouldAuth=True):
logger.debug("Connecting WebSocket.")
self.symbol = symbol
self.shouldAuth = shouldAuth
subscriptions = [sub + ':' + symbol for sub in ["quote", "trade"]]
subscriptions += ["instrument"]
if self.shouldAut... | [
"def",
"connect",
"(",
"self",
",",
"endpoint",
"=",
"\"\"",
",",
"symbol",
"=",
"\"XBTN15\"",
",",
"shouldAuth",
"=",
"True",
")",
":",
"logger",
".",
"debug",
"(",
"\"Connecting WebSocket.\"",
")",
"self",
".",
"symbol",
"=",
"symbol",
"self",
".",
"sh... | Connect to the websocket and initialize data stores. | [
"Connect",
"to",
"the",
"websocket",
"and",
"initialize",
"data",
"stores",
"."
] | [
"'''Connect to the websocket and initialize data stores.'''",
"# We can subscribe right in the connection querystring, so let's build that.",
"# Subscribe to all pertinent endpoints",
"# We want all of them",
"# Get WS URL and connect.",
"# Connected. Wait for partials"
] | [
{
"param": "self",
"type": null
},
{
"param": "endpoint",
"type": null
},
{
"param": "symbol",
"type": null
},
{
"param": "shouldAuth",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "endpoint",
"type": null,
"docstring": null,
"docstring_tokens... |
d300c533cf4ebcc57e7fa134f3355802b71343ea | Joukahainen/sample-market-maker | market_maker/ws/ws_thread.py | [
"Apache-2.0"
] | Python | __connect | null | def __connect(self, wsURL):
'''Connect to the websocket in a thread.'''
logger.debug("Starting thread")
ssl_defaults = ssl.get_default_verify_paths()
sslopt_ca_certs = {'ca_certs': ssl_defaults.cafile}
self.ws = websocket.WebSocketApp(wsURL,
... | Connect to the websocket in a thread. | Connect to the websocket in a thread. | [
"Connect",
"to",
"the",
"websocket",
"in",
"a",
"thread",
"."
] | def __connect(self, wsURL):
logger.debug("Starting thread")
ssl_defaults = ssl.get_default_verify_paths()
sslopt_ca_certs = {'ca_certs': ssl_defaults.cafile}
self.ws = websocket.WebSocketApp(wsURL,
on_message=self.__on_message,
... | [
"def",
"__connect",
"(",
"self",
",",
"wsURL",
")",
":",
"logger",
".",
"debug",
"(",
"\"Starting thread\"",
")",
"ssl_defaults",
"=",
"ssl",
".",
"get_default_verify_paths",
"(",
")",
"sslopt_ca_certs",
"=",
"{",
"'ca_certs'",
":",
"ssl_defaults",
".",
"cafil... | Connect to the websocket in a thread. | [
"Connect",
"to",
"the",
"websocket",
"in",
"a",
"thread",
"."
] | [
"'''Connect to the websocket in a thread.'''",
"# Wait for connect before continuing"
] | [
{
"param": "self",
"type": null
},
{
"param": "wsURL",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "wsURL",
"type": null,
"docstring": null,
"docstring_tokens": ... |
d300c533cf4ebcc57e7fa134f3355802b71343ea | Joukahainen/sample-market-maker | market_maker/ws/ws_thread.py | [
"Apache-2.0"
] | Python | __get_auth | <not_specific> | def __get_auth(self):
'''Return auth headers. Will use API Keys if present in settings.'''
if self.shouldAuth is False:
return []
logger.info("Authenticating with API Key.")
# To auth to the WS using an API key, we generate a signature of a nonce and
# the WS API en... | Return auth headers. Will use API Keys if present in settings. | Return auth headers. Will use API Keys if present in settings. | [
"Return",
"auth",
"headers",
".",
"Will",
"use",
"API",
"Keys",
"if",
"present",
"in",
"settings",
"."
] | def __get_auth(self):
if self.shouldAuth is False:
return []
logger.info("Authenticating with API Key.")
nonce = generate_expires()
return [
"api-expires: " + str(nonce),
"api-signature: " + generate_signature(settings.API_SECRET, 'GET', '/realtime', n... | [
"def",
"__get_auth",
"(",
"self",
")",
":",
"if",
"self",
".",
"shouldAuth",
"is",
"False",
":",
"return",
"[",
"]",
"logger",
".",
"info",
"(",
"\"Authenticating with API Key.\"",
")",
"nonce",
"=",
"generate_expires",
"(",
")",
"return",
"[",
"\"api-expire... | Return auth headers. | [
"Return",
"auth",
"headers",
"."
] | [
"'''Return auth headers. Will use API Keys if present in settings.'''",
"# To auth to the WS using an API key, we generate a signature of a nonce and",
"# the WS API endpoint."
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
d300c533cf4ebcc57e7fa134f3355802b71343ea | Joukahainen/sample-market-maker | market_maker/ws/ws_thread.py | [
"Apache-2.0"
] | Python | __on_message | null | def __on_message(self, message):
'''Handler for parsing WS messages.'''
message = json.loads(message)
logger.debug(json.dumps(message))
table = message['table'] if 'table' in message else None
action = message['action'] if 'action' in message else None
try:
i... | Handler for parsing WS messages. | Handler for parsing WS messages. | [
"Handler",
"for",
"parsing",
"WS",
"messages",
"."
] | def __on_message(self, message):
message = json.loads(message)
logger.debug(json.dumps(message))
table = message['table'] if 'table' in message else None
action = message['action'] if 'action' in message else None
try:
if 'subscribe' in message:
if mes... | [
"def",
"__on_message",
"(",
"self",
",",
"message",
")",
":",
"message",
"=",
"json",
".",
"loads",
"(",
"message",
")",
"logger",
".",
"debug",
"(",
"json",
".",
"dumps",
"(",
"message",
")",
")",
"table",
"=",
"message",
"[",
"'table'",
"]",
"if",
... | Handler for parsing WS messages. | [
"Handler",
"for",
"parsing",
"WS",
"messages",
"."
] | [
"'''Handler for parsing WS messages.'''",
"# There are four possible actions from the WS:",
"# 'partial' - full table image",
"# 'insert' - new row",
"# 'update' - update row",
"# 'delete' - delete row",
"# Keys are communicated on partials to let you know how to uniquely identify",
"# an item. We ... | [
{
"param": "self",
"type": null
},
{
"param": "message",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "message",
"type": null,
"docstring": null,
"docstring_tokens"... |
cb97a350b8ff86c0ec4c788ae97a6d83be78c685 | dgarske/trustedfirmware | bl2/ext/mcuboot/scripts/imgtool_lib/image.py | [
"BSD-3-Clause"
] | Python | add | null | def add(self, kind, payload):
"""Add a TLV record. Kind should be a string found in TLV_VALUES above."""
buf = struct.pack('<BBH', TLV_VALUES[kind], 0, len(payload))
self.buf += buf
self.buf += payload | Add a TLV record. Kind should be a string found in TLV_VALUES above. | Add a TLV record. Kind should be a string found in TLV_VALUES above. | [
"Add",
"a",
"TLV",
"record",
".",
"Kind",
"should",
"be",
"a",
"string",
"found",
"in",
"TLV_VALUES",
"above",
"."
] | def add(self, kind, payload):
buf = struct.pack('<BBH', TLV_VALUES[kind], 0, len(payload))
self.buf += buf
self.buf += payload | [
"def",
"add",
"(",
"self",
",",
"kind",
",",
"payload",
")",
":",
"buf",
"=",
"struct",
".",
"pack",
"(",
"'<BBH'",
",",
"TLV_VALUES",
"[",
"kind",
"]",
",",
"0",
",",
"len",
"(",
"payload",
")",
")",
"self",
".",
"buf",
"+=",
"buf",
"self",
".... | Add a TLV record. | [
"Add",
"a",
"TLV",
"record",
"."
] | [
"\"\"\"Add a TLV record. Kind should be a string found in TLV_VALUES above.\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "kind",
"type": null
},
{
"param": "payload",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "kind",
"type": null,
"docstring": null,
"docstring_tokens": [... |
cb97a350b8ff86c0ec4c788ae97a6d83be78c685 | dgarske/trustedfirmware | bl2/ext/mcuboot/scripts/imgtool_lib/image.py | [
"BSD-3-Clause"
] | Python | load | <not_specific> | def load(cls, path, included_header=False, **kwargs):
"""Load an image from a given file"""
with open(path, 'rb') as f:
payload = f.read()
obj = cls(**kwargs)
obj.payload = payload
# Add the image header if needed.
if not included_header and obj.header_size >... | Load an image from a given file | Load an image from a given file | [
"Load",
"an",
"image",
"from",
"a",
"given",
"file"
] | def load(cls, path, included_header=False, **kwargs):
with open(path, 'rb') as f:
payload = f.read()
obj = cls(**kwargs)
obj.payload = payload
if not included_header and obj.header_size > 0:
obj.payload = (b'\000' * obj.header_size) + obj.payload
obj.check... | [
"def",
"load",
"(",
"cls",
",",
"path",
",",
"included_header",
"=",
"False",
",",
"**",
"kwargs",
")",
":",
"with",
"open",
"(",
"path",
",",
"'rb'",
")",
"as",
"f",
":",
"payload",
"=",
"f",
".",
"read",
"(",
")",
"obj",
"=",
"cls",
"(",
"**"... | Load an image from a given file | [
"Load",
"an",
"image",
"from",
"a",
"given",
"file"
] | [
"\"\"\"Load an image from a given file\"\"\"",
"# Add the image header if needed."
] | [
{
"param": "cls",
"type": null
},
{
"param": "path",
"type": null
},
{
"param": "included_header",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "cls",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "path",
"type": null,
"docstring": null,
"docstring_tokens": []... |
cb97a350b8ff86c0ec4c788ae97a6d83be78c685 | dgarske/trustedfirmware | bl2/ext/mcuboot/scripts/imgtool_lib/image.py | [
"BSD-3-Clause"
] | Python | check | null | def check(self):
"""Perform some sanity checking of the image."""
# If there is a header requested, make sure that the image
# starts with all zeros.
if self.header_size > 0:
if any(v != 0 and v != b'\000' for v in self.payload[0:self.header_size]):
raise Exce... | Perform some sanity checking of the image. | Perform some sanity checking of the image. | [
"Perform",
"some",
"sanity",
"checking",
"of",
"the",
"image",
"."
] | def check(self):
if self.header_size > 0:
if any(v != 0 and v != b'\000' for v in self.payload[0:self.header_size]):
raise Exception("Padding requested, but image does not start with zeros") | [
"def",
"check",
"(",
"self",
")",
":",
"if",
"self",
".",
"header_size",
">",
"0",
":",
"if",
"any",
"(",
"v",
"!=",
"0",
"and",
"v",
"!=",
"b'\\000'",
"for",
"v",
"in",
"self",
".",
"payload",
"[",
"0",
":",
"self",
".",
"header_size",
"]",
")... | Perform some sanity checking of the image. | [
"Perform",
"some",
"sanity",
"checking",
"of",
"the",
"image",
"."
] | [
"\"\"\"Perform some sanity checking of the image.\"\"\"",
"# If there is a header requested, make sure that the image",
"# starts with all zeros."
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
cb97a350b8ff86c0ec4c788ae97a6d83be78c685 | dgarske/trustedfirmware | bl2/ext/mcuboot/scripts/imgtool_lib/image.py | [
"BSD-3-Clause"
] | Python | add_header | null | def add_header(self, key, protected_tlv_size, ramLoadAddress):
"""Install the image header.
The key is needed to know the type of signature, and
approximate the size of the signature."""
flags = 0
if ramLoadAddress is not None:
# add the load address flag to the hea... | Install the image header.
The key is needed to know the type of signature, and
approximate the size of the signature. | Install the image header.
The key is needed to know the type of signature, and
approximate the size of the signature. | [
"Install",
"the",
"image",
"header",
".",
"The",
"key",
"is",
"needed",
"to",
"know",
"the",
"type",
"of",
"signature",
"and",
"approximate",
"the",
"size",
"of",
"the",
"signature",
"."
] | def add_header(self, key, protected_tlv_size, ramLoadAddress):
flags = 0
if ramLoadAddress is not None:
flags |= IMAGE_F["RAM_LOAD"]
fmt = ('<' +
'I' +
'I' +
'H' +
'H' +
'I' +
'I' +
... | [
"def",
"add_header",
"(",
"self",
",",
"key",
",",
"protected_tlv_size",
",",
"ramLoadAddress",
")",
":",
"flags",
"=",
"0",
"if",
"ramLoadAddress",
"is",
"not",
"None",
":",
"flags",
"|=",
"IMAGE_F",
"[",
"\"RAM_LOAD\"",
"]",
"fmt",
"=",
"(",
"'<'",
"+"... | Install the image header. | [
"Install",
"the",
"image",
"header",
"."
] | [
"\"\"\"Install the image header.\n\n The key is needed to know the type of signature, and\n approximate the size of the signature.\"\"\"",
"# add the load address flag to the header to indicate that an SRAM",
"# load address macro has been defined",
"# type ImageHdr struct {",
"# Magic uint... | [
{
"param": "self",
"type": null
},
{
"param": "key",
"type": null
},
{
"param": "protected_tlv_size",
"type": null
},
{
"param": "ramLoadAddress",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "key",
"type": null,
"docstring": null,
"docstring_tokens": []... |
cb97a350b8ff86c0ec4c788ae97a6d83be78c685 | dgarske/trustedfirmware | bl2/ext/mcuboot/scripts/imgtool_lib/image.py | [
"BSD-3-Clause"
] | Python | pad_to | null | def pad_to(self, size, align):
"""Pad the image to the given size, with the given flash alignment."""
tsize = trailer_sizes[align]
padding = size - (len(self.payload) + tsize)
if padding < 0:
msg = "Image size (0x{:x}) + trailer (0x{:x}) exceeds requested size 0x{:x}".format(... | Pad the image to the given size, with the given flash alignment. | Pad the image to the given size, with the given flash alignment. | [
"Pad",
"the",
"image",
"to",
"the",
"given",
"size",
"with",
"the",
"given",
"flash",
"alignment",
"."
] | def pad_to(self, size, align):
tsize = trailer_sizes[align]
padding = size - (len(self.payload) + tsize)
if padding < 0:
msg = "Image size (0x{:x}) + trailer (0x{:x}) exceeds requested size 0x{:x}".format(
len(self.payload), tsize, size)
raise Exceptio... | [
"def",
"pad_to",
"(",
"self",
",",
"size",
",",
"align",
")",
":",
"tsize",
"=",
"trailer_sizes",
"[",
"align",
"]",
"padding",
"=",
"size",
"-",
"(",
"len",
"(",
"self",
".",
"payload",
")",
"+",
"tsize",
")",
"if",
"padding",
"<",
"0",
":",
"ms... | Pad the image to the given size, with the given flash alignment. | [
"Pad",
"the",
"image",
"to",
"the",
"given",
"size",
"with",
"the",
"given",
"flash",
"alignment",
"."
] | [
"\"\"\"Pad the image to the given size, with the given flash alignment.\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "size",
"type": null
},
{
"param": "align",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "size",
"type": null,
"docstring": null,
"docstring_tokens": [... |
a71b6789766f5366ace0996fcb560ae18c0804a9 | Spectre5/nox | nox/sessions.py | [
"Apache-2.0"
] | Python | _normalize_path | str | def _normalize_path(envdir: str, path: Union[str, bytes]) -> str:
"""Normalizes a string to be a "safe" filesystem path for a virtualenv."""
if isinstance(path, bytes):
path = path.decode("utf-8")
path = unicodedata.normalize("NFKD", path).encode("ascii", "ignore")
path = path.decode("ascii")
... | Normalizes a string to be a "safe" filesystem path for a virtualenv. | Normalizes a string to be a "safe" filesystem path for a virtualenv. | [
"Normalizes",
"a",
"string",
"to",
"be",
"a",
"\"",
"safe",
"\"",
"filesystem",
"path",
"for",
"a",
"virtualenv",
"."
] | def _normalize_path(envdir: str, path: Union[str, bytes]) -> str:
if isinstance(path, bytes):
path = path.decode("utf-8")
path = unicodedata.normalize("NFKD", path).encode("ascii", "ignore")
path = path.decode("ascii")
path = re.sub(r"[^\w\s-]", "-", path).strip().lower()
path = re.sub(r"[-\... | [
"def",
"_normalize_path",
"(",
"envdir",
":",
"str",
",",
"path",
":",
"Union",
"[",
"str",
",",
"bytes",
"]",
")",
"->",
"str",
":",
"if",
"isinstance",
"(",
"path",
",",
"bytes",
")",
":",
"path",
"=",
"path",
".",
"decode",
"(",
"\"utf-8\"",
")"... | Normalizes a string to be a "safe" filesystem path for a virtualenv. | [
"Normalizes",
"a",
"string",
"to",
"be",
"a",
"\"",
"safe",
"\"",
"filesystem",
"path",
"for",
"a",
"virtualenv",
"."
] | [
"\"\"\"Normalizes a string to be a \"safe\" filesystem path for a virtualenv.\"\"\""
] | [
{
"param": "envdir",
"type": "str"
},
{
"param": "path",
"type": "Union[str, bytes]"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "envdir",
"type": "str",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "path",
"type": "Union[str, bytes]",
"docstring": null,
"do... |
a71b6789766f5366ace0996fcb560ae18c0804a9 | Spectre5/nox | nox/sessions.py | [
"Apache-2.0"
] | Python | virtualenv | ProcessEnv | def virtualenv(self) -> ProcessEnv:
"""The virtualenv that all commands are run in."""
venv = self._runner.venv
if venv is None:
raise ValueError("A virtualenv has not been created for this session")
return venv | The virtualenv that all commands are run in. | The virtualenv that all commands are run in. | [
"The",
"virtualenv",
"that",
"all",
"commands",
"are",
"run",
"in",
"."
] | def virtualenv(self) -> ProcessEnv:
venv = self._runner.venv
if venv is None:
raise ValueError("A virtualenv has not been created for this session")
return venv | [
"def",
"virtualenv",
"(",
"self",
")",
"->",
"ProcessEnv",
":",
"venv",
"=",
"self",
".",
"_runner",
".",
"venv",
"if",
"venv",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"A virtualenv has not been created for this session\"",
")",
"return",
"venv"
] | The virtualenv that all commands are run in. | [
"The",
"virtualenv",
"that",
"all",
"commands",
"are",
"run",
"in",
"."
] | [
"\"\"\"The virtualenv that all commands are run in.\"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
a71b6789766f5366ace0996fcb560ae18c0804a9 | Spectre5/nox | nox/sessions.py | [
"Apache-2.0"
] | Python | create_tmp | str | def create_tmp(self) -> str:
"""Create, and return, a temporary directory."""
tmpdir = os.path.join(self._runner.envdir, "tmp")
os.makedirs(tmpdir, exist_ok=True)
self.env["TMPDIR"] = tmpdir
return tmpdir | Create, and return, a temporary directory. | Create, and return, a temporary directory. | [
"Create",
"and",
"return",
"a",
"temporary",
"directory",
"."
] | def create_tmp(self) -> str:
tmpdir = os.path.join(self._runner.envdir, "tmp")
os.makedirs(tmpdir, exist_ok=True)
self.env["TMPDIR"] = tmpdir
return tmpdir | [
"def",
"create_tmp",
"(",
"self",
")",
"->",
"str",
":",
"tmpdir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_runner",
".",
"envdir",
",",
"\"tmp\"",
")",
"os",
".",
"makedirs",
"(",
"tmpdir",
",",
"exist_ok",
"=",
"True",
")",
"self"... | Create, and return, a temporary directory. | [
"Create",
"and",
"return",
"a",
"temporary",
"directory",
"."
] | [
"\"\"\"Create, and return, a temporary directory.\"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
a71b6789766f5366ace0996fcb560ae18c0804a9 | Spectre5/nox | nox/sessions.py | [
"Apache-2.0"
] | Python | cache_dir | pathlib.Path | def cache_dir(self) -> pathlib.Path:
"""Create and return a 'shared cache' directory to be used across sessions."""
path = pathlib.Path(self._runner.global_config.envdir).joinpath(".cache")
path.mkdir(exist_ok=True)
return path | Create and return a 'shared cache' directory to be used across sessions. | Create and return a 'shared cache' directory to be used across sessions. | [
"Create",
"and",
"return",
"a",
"'",
"shared",
"cache",
"'",
"directory",
"to",
"be",
"used",
"across",
"sessions",
"."
] | def cache_dir(self) -> pathlib.Path:
path = pathlib.Path(self._runner.global_config.envdir).joinpath(".cache")
path.mkdir(exist_ok=True)
return path | [
"def",
"cache_dir",
"(",
"self",
")",
"->",
"pathlib",
".",
"Path",
":",
"path",
"=",
"pathlib",
".",
"Path",
"(",
"self",
".",
"_runner",
".",
"global_config",
".",
"envdir",
")",
".",
"joinpath",
"(",
"\".cache\"",
")",
"path",
".",
"mkdir",
"(",
"... | Create and return a 'shared cache' directory to be used across sessions. | [
"Create",
"and",
"return",
"a",
"'",
"shared",
"cache",
"'",
"directory",
"to",
"be",
"used",
"across",
"sessions",
"."
] | [
"\"\"\"Create and return a 'shared cache' directory to be used across sessions.\"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
a71b6789766f5366ace0996fcb560ae18c0804a9 | Spectre5/nox | nox/sessions.py | [
"Apache-2.0"
] | Python | invoked_from | str | def invoked_from(self) -> str:
"""The directory that Nox was originally invoked from.
Since you can use the ``--noxfile / -f`` command-line
argument to run a Noxfile in a location different from your shell's
current working directory, Nox automatically changes the working directory
... | The directory that Nox was originally invoked from.
Since you can use the ``--noxfile / -f`` command-line
argument to run a Noxfile in a location different from your shell's
current working directory, Nox automatically changes the working directory
to the Noxfile's directory before runn... | The directory that Nox was originally invoked from.
Since you can use the ``--noxfile / -f`` command-line
argument to run a Noxfile in a location different from your shell's
current working directory, Nox automatically changes the working directory
to the Noxfile's directory before running any sessions. This gives
you ... | [
"The",
"directory",
"that",
"Nox",
"was",
"originally",
"invoked",
"from",
".",
"Since",
"you",
"can",
"use",
"the",
"`",
"`",
"--",
"noxfile",
"/",
"-",
"f",
"`",
"`",
"command",
"-",
"line",
"argument",
"to",
"run",
"a",
"Noxfile",
"in",
"a",
"loca... | def invoked_from(self) -> str:
return self._runner.global_config.invoked_from | [
"def",
"invoked_from",
"(",
"self",
")",
"->",
"str",
":",
"return",
"self",
".",
"_runner",
".",
"global_config",
".",
"invoked_from"
] | The directory that Nox was originally invoked from. | [
"The",
"directory",
"that",
"Nox",
"was",
"originally",
"invoked",
"from",
"."
] | [
"\"\"\"The directory that Nox was originally invoked from.\n\n Since you can use the ``--noxfile / -f`` command-line\n argument to run a Noxfile in a location different from your shell's\n current working directory, Nox automatically changes the working directory\n to the Noxfile's direc... | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
a71b6789766f5366ace0996fcb560ae18c0804a9 | Spectre5/nox | nox/sessions.py | [
"Apache-2.0"
] | Python | chdir | _WorkingDirContext | def chdir(self, dir: Union[str, os.PathLike]) -> _WorkingDirContext:
"""Change the current working directory.
Can be used as a context manager to automatically restore the working directory::
with session.chdir("somewhere/deep/in/monorepo"):
# Runs in "/somewhere/deep/in/mo... | Change the current working directory.
Can be used as a context manager to automatically restore the working directory::
with session.chdir("somewhere/deep/in/monorepo"):
# Runs in "/somewhere/deep/in/monorepo"
session.run("pytest")
# Runs in original wo... | Change the current working directory.
Can be used as a context manager to automatically restore the working directory:.
Runs in original working directory
session.run("flake8") | [
"Change",
"the",
"current",
"working",
"directory",
".",
"Can",
"be",
"used",
"as",
"a",
"context",
"manager",
"to",
"automatically",
"restore",
"the",
"working",
"directory",
":",
".",
"Runs",
"in",
"original",
"working",
"directory",
"session",
".",
"run",
... | def chdir(self, dir: Union[str, os.PathLike]) -> _WorkingDirContext:
self.log(f"cd {dir}")
return _WorkingDirContext(dir) | [
"def",
"chdir",
"(",
"self",
",",
"dir",
":",
"Union",
"[",
"str",
",",
"os",
".",
"PathLike",
"]",
")",
"->",
"_WorkingDirContext",
":",
"self",
".",
"log",
"(",
"f\"cd {dir}\"",
")",
"return",
"_WorkingDirContext",
"(",
"dir",
")"
] | Change the current working directory. | [
"Change",
"the",
"current",
"working",
"directory",
"."
] | [
"\"\"\"Change the current working directory.\n\n Can be used as a context manager to automatically restore the working directory::\n\n with session.chdir(\"somewhere/deep/in/monorepo\"):\n # Runs in \"/somewhere/deep/in/monorepo\"\n session.run(\"pytest\")\n\n ... | [
{
"param": "self",
"type": null
},
{
"param": "dir",
"type": "Union[str, os.PathLike]"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "dir",
"type": "Union[str, os.PathLike]",
"docstring": null,
"... |
a71b6789766f5366ace0996fcb560ae18c0804a9 | Spectre5/nox | nox/sessions.py | [
"Apache-2.0"
] | Python | _run_func | Any | def _run_func(
self, func: Callable, args: Iterable[Any], kwargs: Mapping[str, Any]
) -> Any:
"""Legacy support for running a function through :func`run`."""
self.log(f"{func}(args={args!r}, kwargs={kwargs!r})")
try:
return func(*args, **kwargs)
except Exception a... | Legacy support for running a function through :func`run`. | Legacy support for running a function through :func`run`. | [
"Legacy",
"support",
"for",
"running",
"a",
"function",
"through",
":",
"func",
"`",
"run",
"`",
"."
] | def _run_func(
self, func: Callable, args: Iterable[Any], kwargs: Mapping[str, Any]
) -> Any:
self.log(f"{func}(args={args!r}, kwargs={kwargs!r})")
try:
return func(*args, **kwargs)
except Exception as e:
logger.exception(f"Function {func!r} raised {e!r}.")
... | [
"def",
"_run_func",
"(",
"self",
",",
"func",
":",
"Callable",
",",
"args",
":",
"Iterable",
"[",
"Any",
"]",
",",
"kwargs",
":",
"Mapping",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"Any",
":",
"self",
".",
"log",
"(",
"f\"{func}(args={args!r}, kwargs={... | Legacy support for running a function through :func`run`. | [
"Legacy",
"support",
"for",
"running",
"a",
"function",
"through",
":",
"func",
"`",
"run",
"`",
"."
] | [
"\"\"\"Legacy support for running a function through :func`run`.\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "func",
"type": "Callable"
},
{
"param": "args",
"type": "Iterable[Any]"
},
{
"param": "kwargs",
"type": "Mapping[str, Any]"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "func",
"type": "Callable",
"docstring": null,
"docstring_toke... |
a71b6789766f5366ace0996fcb560ae18c0804a9 | Spectre5/nox | nox/sessions.py | [
"Apache-2.0"
] | Python | notify | None | def notify(
self,
target: "Union[str, SessionRunner]",
posargs: Optional[Iterable[str]] = None,
) -> None:
"""Place the given session at the end of the queue.
This method is idempotent; multiple notifications to the same session
have no effect.
A common use ... | Place the given session at the end of the queue.
This method is idempotent; multiple notifications to the same session
have no effect.
A common use case is to notify a code coverage analysis session
from a test session::
@nox.session
def test(session):
... | Place the given session at the end of the queue.
This method is idempotent; multiple notifications to the same session
have no effect.
A common use case is to notify a code coverage analysis session
from a test session:.
Now if you run `nox -s test`, the coverage session will run afterwards. | [
"Place",
"the",
"given",
"session",
"at",
"the",
"end",
"of",
"the",
"queue",
".",
"This",
"method",
"is",
"idempotent",
";",
"multiple",
"notifications",
"to",
"the",
"same",
"session",
"have",
"no",
"effect",
".",
"A",
"common",
"use",
"case",
"is",
"t... | def notify(
self,
target: "Union[str, SessionRunner]",
posargs: Optional[Iterable[str]] = None,
) -> None:
if posargs is not None:
posargs = list(posargs)
self._runner.manifest.notify(target, posargs) | [
"def",
"notify",
"(",
"self",
",",
"target",
":",
"\"Union[str, SessionRunner]\"",
",",
"posargs",
":",
"Optional",
"[",
"Iterable",
"[",
"str",
"]",
"]",
"=",
"None",
",",
")",
"->",
"None",
":",
"if",
"posargs",
"is",
"not",
"None",
":",
"posargs",
"... | Place the given session at the end of the queue. | [
"Place",
"the",
"given",
"session",
"at",
"the",
"end",
"of",
"the",
"queue",
"."
] | [
"\"\"\"Place the given session at the end of the queue.\n\n This method is idempotent; multiple notifications to the same session\n have no effect.\n\n A common use case is to notify a code coverage analysis session\n from a test session::\n\n @nox.session\n def tes... | [
{
"param": "self",
"type": null
},
{
"param": "target",
"type": "\"Union[str, SessionRunner]\""
},
{
"param": "posargs",
"type": "Optional[Iterable[str]]"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "target",
"type": "\"Union[str, SessionRunner]\"",
"docstring": "The... |
a71b6789766f5366ace0996fcb560ae18c0804a9 | Spectre5/nox | nox/sessions.py | [
"Apache-2.0"
] | Python | imperfect | str | def imperfect(self) -> str:
"""Return the English imperfect tense for the status.
Returns:
str: A word or phrase representing the status.
"""
if self.status == Status.SUCCESS:
return "was successful"
status = self.status.name.lower()
if self.reaso... | Return the English imperfect tense for the status.
Returns:
str: A word or phrase representing the status.
| Return the English imperfect tense for the status. | [
"Return",
"the",
"English",
"imperfect",
"tense",
"for",
"the",
"status",
"."
] | def imperfect(self) -> str:
if self.status == Status.SUCCESS:
return "was successful"
status = self.status.name.lower()
if self.reason:
return f"{status}: {self.reason}"
else:
return status | [
"def",
"imperfect",
"(",
"self",
")",
"->",
"str",
":",
"if",
"self",
".",
"status",
"==",
"Status",
".",
"SUCCESS",
":",
"return",
"\"was successful\"",
"status",
"=",
"self",
".",
"status",
".",
"name",
".",
"lower",
"(",
")",
"if",
"self",
".",
"r... | Return the English imperfect tense for the status. | [
"Return",
"the",
"English",
"imperfect",
"tense",
"for",
"the",
"status",
"."
] | [
"\"\"\"Return the English imperfect tense for the status.\n\n Returns:\n str: A word or phrase representing the status.\n \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [
{
"docstring": "A word or phrase representing the status.",
"docstring_tokens": [
"A",
"word",
"or",
"phrase",
"representing",
"the",
"status",
"."
],
"type": "str"
}
],
"raises": [],
"params": [
{... |
a71b6789766f5366ace0996fcb560ae18c0804a9 | Spectre5/nox | nox/sessions.py | [
"Apache-2.0"
] | Python | log | None | def log(self, message: str) -> None:
"""Log a message using the appropriate log function.
Args:
message (str): The message to be logged.
"""
log_function = logger.info
if self.status == Status.SUCCESS:
log_function = logger.success
if self.status ... | Log a message using the appropriate log function.
Args:
message (str): The message to be logged.
| Log a message using the appropriate log function. | [
"Log",
"a",
"message",
"using",
"the",
"appropriate",
"log",
"function",
"."
] | def log(self, message: str) -> None:
log_function = logger.info
if self.status == Status.SUCCESS:
log_function = logger.success
if self.status == Status.SKIPPED:
log_function = logger.warning
if self.status.value <= 0:
log_function = logger.error
... | [
"def",
"log",
"(",
"self",
",",
"message",
":",
"str",
")",
"->",
"None",
":",
"log_function",
"=",
"logger",
".",
"info",
"if",
"self",
".",
"status",
"==",
"Status",
".",
"SUCCESS",
":",
"log_function",
"=",
"logger",
".",
"success",
"if",
"self",
... | Log a message using the appropriate log function. | [
"Log",
"a",
"message",
"using",
"the",
"appropriate",
"log",
"function",
"."
] | [
"\"\"\"Log a message using the appropriate log function.\n\n Args:\n message (str): The message to be logged.\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "message",
"type": "str"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "message",
"type": "str",
"docstring": "The message to be logged.",
... |
a71b6789766f5366ace0996fcb560ae18c0804a9 | Spectre5/nox | nox/sessions.py | [
"Apache-2.0"
] | Python | serialize | Dict[str, Any] | def serialize(self) -> Dict[str, Any]:
"""Return a serialized representation of this result.
Returns:
dict: The serialized result.
"""
return {
"args": getattr(self.session.func, "call_spec", {}),
"name": self.session.name,
"result": self.... | Return a serialized representation of this result.
Returns:
dict: The serialized result.
| Return a serialized representation of this result. | [
"Return",
"a",
"serialized",
"representation",
"of",
"this",
"result",
"."
] | def serialize(self) -> Dict[str, Any]:
return {
"args": getattr(self.session.func, "call_spec", {}),
"name": self.session.name,
"result": self.status.name.lower(),
"result_code": self.status.value,
"signatures": self.session.signatures,
} | [
"def",
"serialize",
"(",
"self",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"return",
"{",
"\"args\"",
":",
"getattr",
"(",
"self",
".",
"session",
".",
"func",
",",
"\"call_spec\"",
",",
"{",
"}",
")",
",",
"\"name\"",
":",
"self",
".",
... | Return a serialized representation of this result. | [
"Return",
"a",
"serialized",
"representation",
"of",
"this",
"result",
"."
] | [
"\"\"\"Return a serialized representation of this result.\n\n Returns:\n dict: The serialized result.\n \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [
{
"docstring": "The serialized result.",
"docstring_tokens": [
"The",
"serialized",
"result",
"."
],
"type": "dict"
}
],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"... |
12988ca55d98e5c65b8236fae8833d2cfc31f976 | margulies/congrads | bayesreg.py | [
"Apache-2.0"
] | Python | post | <not_specific> | def post(self, hyp, X, y):
""" Generic function to compute posterior distribution.
This function will save the posterior mean and precision matrix as
self.m and self.A and will also update internal parameters (e.g.
N, D and the prior covariance (Sigma) and precision (iSigma).... | Generic function to compute posterior distribution.
This function will save the posterior mean and precision matrix as
self.m and self.A and will also update internal parameters (e.g.
N, D and the prior covariance (Sigma) and precision (iSigma).
| Generic function to compute posterior distribution.
This function will save the posterior mean and precision matrix as
self.m and self.A and will also update internal parameters and precision (iSigma). | [
"Generic",
"function",
"to",
"compute",
"posterior",
"distribution",
".",
"This",
"function",
"will",
"save",
"the",
"posterior",
"mean",
"and",
"precision",
"matrix",
"as",
"self",
".",
"m",
"and",
"self",
".",
"A",
"and",
"will",
"also",
"update",
"interna... | def post(self, hyp, X, y):
N = X.shape[0]
if len(X.shape) == 1:
D = 1
else:
D = X.shape[1]
if (hyp == self.hyp).all() and hasattr(self, 'N'):
print("hyperparameters have not changed, exiting")
return
beta = np.exp(hyp[0])
... | [
"def",
"post",
"(",
"self",
",",
"hyp",
",",
"X",
",",
"y",
")",
":",
"N",
"=",
"X",
".",
"shape",
"[",
"0",
"]",
"if",
"len",
"(",
"X",
".",
"shape",
")",
"==",
"1",
":",
"D",
"=",
"1",
"else",
":",
"D",
"=",
"X",
".",
"shape",
"[",
... | Generic function to compute posterior distribution. | [
"Generic",
"function",
"to",
"compute",
"posterior",
"distribution",
"."
] | [
"\"\"\" Generic function to compute posterior distribution.\n This function will save the posterior mean and precision matrix as\n self.m and self.A and will also update internal parameters (e.g.\n N, D and the prior covariance (Sigma) and precision (iSigma).\n \"\"\"",
"# ... | [
{
"param": "self",
"type": null
},
{
"param": "hyp",
"type": null
},
{
"param": "X",
"type": null
},
{
"param": "y",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "hyp",
"type": null,
"docstring": null,
"docstring_tokens": []... |
12988ca55d98e5c65b8236fae8833d2cfc31f976 | margulies/congrads | bayesreg.py | [
"Apache-2.0"
] | Python | loglik | <not_specific> | def loglik(self, hyp, X, y):
""" Function to compute compute log (marginal) likelihood """
# hyperparameters (only beta needed)
beta = np.exp(hyp[0]) # noise precision
# load posterior and prior covariance
if (hyp != self.hyp).all() or not(hasattr(self, 'A')):
try:... | Function to compute compute log (marginal) likelihood | Function to compute compute log (marginal) likelihood | [
"Function",
"to",
"compute",
"compute",
"log",
"(",
"marginal",
")",
"likelihood"
] | def loglik(self, hyp, X, y):
beta = np.exp(hyp[0])
if (hyp != self.hyp).all() or not(hasattr(self, 'A')):
try:
self.post(hyp, X, y)
except ValueError:
print("Warning: Estimation of posterior distribution failed")
nlZ = 1/np.finfo(... | [
"def",
"loglik",
"(",
"self",
",",
"hyp",
",",
"X",
",",
"y",
")",
":",
"beta",
"=",
"np",
".",
"exp",
"(",
"hyp",
"[",
"0",
"]",
")",
"if",
"(",
"hyp",
"!=",
"self",
".",
"hyp",
")",
".",
"all",
"(",
")",
"or",
"not",
"(",
"hasattr",
"("... | Function to compute compute log (marginal) likelihood | [
"Function",
"to",
"compute",
"compute",
"log",
"(",
"marginal",
")",
"likelihood"
] | [
"\"\"\" Function to compute compute log (marginal) likelihood \"\"\"",
"# hyperparameters (only beta needed)",
"# noise precision",
"# load posterior and prior covariance",
"# compute the log determinants in a numerically stable way",
"# Sigma is diagonal",
"# compute negative marginal log likelihood",
... | [
{
"param": "self",
"type": null
},
{
"param": "hyp",
"type": null
},
{
"param": "X",
"type": null
},
{
"param": "y",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "hyp",
"type": null,
"docstring": null,
"docstring_tokens": []... |
12988ca55d98e5c65b8236fae8833d2cfc31f976 | margulies/congrads | bayesreg.py | [
"Apache-2.0"
] | Python | predict | <not_specific> | def predict(self, hyp, X, y, Xs):
""" Function to make predictions from the model """
if (hyp != self.hyp).all() or not(hasattr(self, 'A')):
self.post(hyp, X, y)
# hyperparameters
beta = np.exp(hyp[0])
ys = Xs.dot(self.m)
# compute xs.dot(S).dot(xs.T) avoid... | Function to make predictions from the model | Function to make predictions from the model | [
"Function",
"to",
"make",
"predictions",
"from",
"the",
"model"
] | def predict(self, hyp, X, y, Xs):
if (hyp != self.hyp).all() or not(hasattr(self, 'A')):
self.post(hyp, X, y)
beta = np.exp(hyp[0])
ys = Xs.dot(self.m)
s2 = 1/beta + np.sum(Xs*linalg.solve(self.A, Xs.T).T, axis=1)
return ys, s2 | [
"def",
"predict",
"(",
"self",
",",
"hyp",
",",
"X",
",",
"y",
",",
"Xs",
")",
":",
"if",
"(",
"hyp",
"!=",
"self",
".",
"hyp",
")",
".",
"all",
"(",
")",
"or",
"not",
"(",
"hasattr",
"(",
"self",
",",
"'A'",
")",
")",
":",
"self",
".",
"... | Function to make predictions from the model | [
"Function",
"to",
"make",
"predictions",
"from",
"the",
"model"
] | [
"\"\"\" Function to make predictions from the model \"\"\"",
"# hyperparameters",
"# compute xs.dot(S).dot(xs.T) avoiding computing off-diagonal entries"
] | [
{
"param": "self",
"type": null
},
{
"param": "hyp",
"type": null
},
{
"param": "X",
"type": null
},
{
"param": "y",
"type": null
},
{
"param": "Xs",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "hyp",
"type": null,
"docstring": null,
"docstring_tokens": []... |
fa429c67e29326ca7cc7a0304e854a873225c489 | pooyagheyami/Employee3 | Config/Init.py | [
"Unlicense"
] | Python | opj | <not_specific> | def opj(path):
"""Convert paths to the platform-specific separator"""
st = SLASH+path
# HACK: on Linux, a leading / gets lost...
if path.startswith('/'):
st = '/' + st
#print(st)
return st | Convert paths to the platform-specific separator | Convert paths to the platform-specific separator | [
"Convert",
"paths",
"to",
"the",
"platform",
"-",
"specific",
"separator"
] | def opj(path):
st = SLASH+path
if path.startswith('/'):
st = '/' + st
return st | [
"def",
"opj",
"(",
"path",
")",
":",
"st",
"=",
"SLASH",
"+",
"path",
"if",
"path",
".",
"startswith",
"(",
"'/'",
")",
":",
"st",
"=",
"'/'",
"+",
"st",
"return",
"st"
] | Convert paths to the platform-specific separator | [
"Convert",
"paths",
"to",
"the",
"platform",
"-",
"specific",
"separator"
] | [
"\"\"\"Convert paths to the platform-specific separator\"\"\"",
"# HACK: on Linux, a leading / gets lost...\r",
"#print(st)\r"
] | [
{
"param": "path",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "path",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
c656286424b112b7ce0aa5f7a633659a3bab118b | dagisky/CBM_NEWSQA | main2.py | [
"FTL",
"CNRI-Python"
] | Python | make_model | <not_specific> | def make_model(model_config, N=3, d_ff=128, h=8, dropout=0.1):
"Helper: Construct a model from hyperparameters."
c = copy.deepcopy
attn = MultiHeadedAttention(h, model_config['input']['symbol_size'], model_config['relational'])
ff = PositionwiseFeedForward(model_config['input']['symbol_size'], d_ff, d... | Helper: Construct a model from hyperparameters. | Construct a model from hyperparameters. | [
"Construct",
"a",
"model",
"from",
"hyperparameters",
"."
] | def make_model(model_config, N=3, d_ff=128, h=8, dropout=0.1):
c = copy.deepcopy
attn = MultiHeadedAttention(h, model_config['input']['symbol_size'], model_config['relational'])
ff = PositionwiseFeedForward(model_config['input']['symbol_size'], d_ff, dropout)
position = PositionalEncoding(model_config... | [
"def",
"make_model",
"(",
"model_config",
",",
"N",
"=",
"3",
",",
"d_ff",
"=",
"128",
",",
"h",
"=",
"8",
",",
"dropout",
"=",
"0.1",
")",
":",
"c",
"=",
"copy",
".",
"deepcopy",
"attn",
"=",
"MultiHeadedAttention",
"(",
"h",
",",
"model_config",
... | Helper: Construct a model from hyperparameters. | [
"Helper",
":",
"Construct",
"a",
"model",
"from",
"hyperparameters",
"."
] | [
"\"Helper: Construct a model from hyperparameters.\"",
"# This was important from their code. ",
"# Initialize parameters with Glorot / fan_avg."
] | [
{
"param": "model_config",
"type": null
},
{
"param": "N",
"type": null
},
{
"param": "d_ff",
"type": null
},
{
"param": "h",
"type": null
},
{
"param": "dropout",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "model_config",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "N",
"type": null,
"docstring": null,
"docstring_token... |
38dc89044f908b62482d805aeb0b801a6469e001 | dagisky/CBM_NEWSQA | data.py | [
"FTL",
"CNRI-Python"
] | Python | load_data | <not_specific> | def load_data(story_path = "data/", question_filename="newsqa-data-v1", size=None):
"""Loads the NewsQA data with the respective [CNN story](https://cs.nyu.edu/~kcho/DMQA/)
The function makes custom tokenization that creates character to word answer index offset
Input: NewsQA dataset file (csv)
Output:... | Loads the NewsQA data with the respective [CNN story](https://cs.nyu.edu/~kcho/DMQA/)
The function makes custom tokenization that creates character to word answer index offset
Input: NewsQA dataset file (csv)
Output: None
| Loads the NewsQA data with the respective [CNN story]
The function makes custom tokenization that creates character to word answer index offset
Input: NewsQA dataset file (csv)
Output: None | [
"Loads",
"the",
"NewsQA",
"data",
"with",
"the",
"respective",
"[",
"CNN",
"story",
"]",
"The",
"function",
"makes",
"custom",
"tokenization",
"that",
"creates",
"character",
"to",
"word",
"answer",
"index",
"offset",
"Input",
":",
"NewsQA",
"dataset",
"file",... | def load_data(story_path = "data/", question_filename="newsqa-data-v1", size=None):
if path.exists(question_filename+".pkl"):
df = pd.read_pickle(question_filename+".pkl")
else:
df = pd.read_csv(question_filename+".csv")
if size != None:
df = df.head(size)
df = df.dro... | [
"def",
"load_data",
"(",
"story_path",
"=",
"\"data/\"",
",",
"question_filename",
"=",
"\"newsqa-data-v1\"",
",",
"size",
"=",
"None",
")",
":",
"if",
"path",
".",
"exists",
"(",
"question_filename",
"+",
"\".pkl\"",
")",
":",
"df",
"=",
"pd",
".",
"read_... | Loads the NewsQA data with the respective [CNN story](https://cs.nyu.edu/~kcho/DMQA/)
The function makes custom tokenization that creates character to word answer index offset
Input: NewsQA dataset file (csv)
Output: None | [
"Loads",
"the",
"NewsQA",
"data",
"with",
"the",
"respective",
"[",
"CNN",
"story",
"]",
"(",
"https",
":",
"//",
"cs",
".",
"nyu",
".",
"edu",
"/",
"~kcho",
"/",
"DMQA",
"/",
")",
"The",
"function",
"makes",
"custom",
"tokenization",
"that",
"creates"... | [
"\"\"\"Loads the NewsQA data with the respective [CNN story](https://cs.nyu.edu/~kcho/DMQA/)\n The function makes custom tokenization that creates character to word answer index offset \n Input: NewsQA dataset file (csv)\n Output: None \n \"\"\"",
"# df.to_pickle(question_filename+\".pkl\")"
] | [
{
"param": "story_path",
"type": null
},
{
"param": "question_filename",
"type": null
},
{
"param": "size",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "story_path",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "question_filename",
"type": null,
"docstring": null,
"d... |
0875150bba1029274ac955bce36a72de2e441c3a | dagisky/CBM_NEWSQA | Utils/utils.py | [
"FTL",
"CNRI-Python"
] | Python | image_summary | null | def image_summary(self, tag, images, step):
"""Log a list of images."""
tag=self.tag(tag)
img_summaries = []
for i, img in enumerate(images):
# Write the image to a string
s = BytesIO()
scipy.misc.toimage(img).save(s, format="png")
# Crea... | Log a list of images. | Log a list of images. | [
"Log",
"a",
"list",
"of",
"images",
"."
] | def image_summary(self, tag, images, step):
tag=self.tag(tag)
img_summaries = []
for i, img in enumerate(images):
s = BytesIO()
scipy.misc.toimage(img).save(s, format="png")
img_sum = tf.compat.v1.Summary.Image(encoded_image_string=s.getvalue(),
... | [
"def",
"image_summary",
"(",
"self",
",",
"tag",
",",
"images",
",",
"step",
")",
":",
"tag",
"=",
"self",
".",
"tag",
"(",
"tag",
")",
"img_summaries",
"=",
"[",
"]",
"for",
"i",
",",
"img",
"in",
"enumerate",
"(",
"images",
")",
":",
"s",
"=",
... | Log a list of images. | [
"Log",
"a",
"list",
"of",
"images",
"."
] | [
"\"\"\"Log a list of images.\"\"\"",
"# Write the image to a string",
"# Create an Image object",
"# Create a Summary value",
"# Create and write Summary"
] | [
{
"param": "self",
"type": null
},
{
"param": "tag",
"type": null
},
{
"param": "images",
"type": null
},
{
"param": "step",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "tag",
"type": null,
"docstring": null,
"docstring_tokens": []... |
0875150bba1029274ac955bce36a72de2e441c3a | dagisky/CBM_NEWSQA | Utils/utils.py | [
"FTL",
"CNRI-Python"
] | Python | histo_summary | null | def histo_summary(self, tag, values, step, bins=1000):
"""Log a histogram of the tensor of values."""
tag=self.tag(tag)
# Create a histogram using numpy
counts, bin_edges = np.histogram(values, bins=bins)
# Fill the fields of the histogram proto
hist = tf.HistogramProto... | Log a histogram of the tensor of values. | Log a histogram of the tensor of values. | [
"Log",
"a",
"histogram",
"of",
"the",
"tensor",
"of",
"values",
"."
] | def histo_summary(self, tag, values, step, bins=1000):
tag=self.tag(tag)
counts, bin_edges = np.histogram(values, bins=bins)
hist = tf.HistogramProto()
hist.min = float(np.min(values))
hist.max = float(np.max(values))
hist.num = int(np.prod(values.shape))
hist.sum... | [
"def",
"histo_summary",
"(",
"self",
",",
"tag",
",",
"values",
",",
"step",
",",
"bins",
"=",
"1000",
")",
":",
"tag",
"=",
"self",
".",
"tag",
"(",
"tag",
")",
"counts",
",",
"bin_edges",
"=",
"np",
".",
"histogram",
"(",
"values",
",",
"bins",
... | Log a histogram of the tensor of values. | [
"Log",
"a",
"histogram",
"of",
"the",
"tensor",
"of",
"values",
"."
] | [
"\"\"\"Log a histogram of the tensor of values.\"\"\"",
"# Create a histogram using numpy",
"# Fill the fields of the histogram proto",
"# Drop the start of the first bin",
"# Add bin edges and counts",
"# Create and write Summary",
"# self.writer.flush()"
] | [
{
"param": "self",
"type": null
},
{
"param": "tag",
"type": null
},
{
"param": "values",
"type": null
},
{
"param": "step",
"type": null
},
{
"param": "bins",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "tag",
"type": null,
"docstring": null,
"docstring_tokens": []... |
bc9a3ce8c1f8f15c1de4dea6e979897849c473ac | dagisky/CBM_NEWSQA | relational.py | [
"FTL",
"CNRI-Python"
] | Python | forward | <not_specific> | def forward(self, x):
"""
Implements the forward method of nn.Module Class
Args:
x(Tensor): batch_size x seqence_size x feature_size
Returns:
Tensor
"""
b, d, k = x.size()
# cast all pairs against each other
x_i = torch.unsqueez... |
Implements the forward method of nn.Module Class
Args:
x(Tensor): batch_size x seqence_size x feature_size
Returns:
Tensor
| Implements the forward method of nn.Module Class | [
"Implements",
"the",
"forward",
"method",
"of",
"nn",
".",
"Module",
"Class"
] | def forward(self, x):
b, d, k = x.size()
x_i = torch.unsqueeze(x, 1)
x_i = x_i.repeat(1, d, 1, 1)
x_j = torch.unsqueeze(x, 2)
x_j = x_j.repeat(1, 1, d, 1)
x_full = torch.cat([x_i, x_j], 3) ... | [
"def",
"forward",
"(",
"self",
",",
"x",
")",
":",
"b",
",",
"d",
",",
"k",
"=",
"x",
".",
"size",
"(",
")",
"x_i",
"=",
"torch",
".",
"unsqueeze",
"(",
"x",
",",
"1",
")",
"x_i",
"=",
"x_i",
".",
"repeat",
"(",
"1",
",",
"d",
",",
"1",
... | Implements the forward method of nn.Module Class | [
"Implements",
"the",
"forward",
"method",
"of",
"nn",
".",
"Module",
"Class"
] | [
"\"\"\"\n Implements the forward method of nn.Module Class\n Args:\n x(Tensor): batch_size x seqence_size x feature_size\n Returns:\n Tensor\n \"\"\"",
"# cast all pairs against each other",
"# (B x 1 x 64 x 26)",
"# (B x 64 x 64 x 26)",
"# (B x 64 x 1 x 26)... | [
{
"param": "self",
"type": null
},
{
"param": "x",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
... |
25a08273dc3ebfe1c7ee28cf172caeee1952435c | dagisky/CBM_NEWSQA | CBM/transformers.py | [
"FTL",
"CNRI-Python"
] | Python | forward | <not_specific> | def forward(self, src, src_mask, query):
"Take in and process masked src and target sequences."
src_embed, query_embed = self.embedding(src, query)
src_embed = self.position(src_embed)
out = self.encode(src_embed, None)
return self.decode(out, query_embed) | Take in and process masked src and target sequences. | Take in and process masked src and target sequences. | [
"Take",
"in",
"and",
"process",
"masked",
"src",
"and",
"target",
"sequences",
"."
] | def forward(self, src, src_mask, query):
src_embed, query_embed = self.embedding(src, query)
src_embed = self.position(src_embed)
out = self.encode(src_embed, None)
return self.decode(out, query_embed) | [
"def",
"forward",
"(",
"self",
",",
"src",
",",
"src_mask",
",",
"query",
")",
":",
"src_embed",
",",
"query_embed",
"=",
"self",
".",
"embedding",
"(",
"src",
",",
"query",
")",
"src_embed",
"=",
"self",
".",
"position",
"(",
"src_embed",
")",
"out",
... | Take in and process masked src and target sequences. | [
"Take",
"in",
"and",
"process",
"masked",
"src",
"and",
"target",
"sequences",
"."
] | [
"\"Take in and process masked src and target sequences.\""
] | [
{
"param": "self",
"type": null
},
{
"param": "src",
"type": null
},
{
"param": "src_mask",
"type": null
},
{
"param": "query",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "src",
"type": null,
"docstring": null,
"docstring_tokens": []... |
530c5342ab3501bf259ccfcbf534a7459be0e692 | ianjosephwilson/basic_shopify_api | basic_shopify_api/deferrer.py | [
"MIT"
] | Python | current_time | int | def current_time(self) -> int:
"""
Get the current time in ms.
"""
return int(round(time.time() * 1000)) |
Get the current time in ms.
| Get the current time in ms. | [
"Get",
"the",
"current",
"time",
"in",
"ms",
"."
] | def current_time(self) -> int:
return int(round(time.time() * 1000)) | [
"def",
"current_time",
"(",
"self",
")",
"->",
"int",
":",
"return",
"int",
"(",
"round",
"(",
"time",
".",
"time",
"(",
")",
"*",
"1000",
")",
")"
] | Get the current time in ms. | [
"Get",
"the",
"current",
"time",
"in",
"ms",
"."
] | [
"\"\"\"\n Get the current time in ms.\n \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
37448021f79035c4cb8f8c7431fc9472a257c396 | ianjosephwilson/basic_shopify_api | basic_shopify_api/utils.py | [
"MIT"
] | Python | create_hmac | str | def create_hmac(
data: Union[dict, str],
raw: bool = False,
build_query: bool = False,
build_query_with_join: bool = False,
encode: bool = False,
secret: str = None
) -> str:
"""
Create an HMAC string based on inputted values.
"""
if build_query:
# Query building is requ... |
Create an HMAC string based on inputted values.
| Create an HMAC string based on inputted values. | [
"Create",
"an",
"HMAC",
"string",
"based",
"on",
"inputted",
"values",
"."
] | def create_hmac(
data: Union[dict, str],
raw: bool = False,
build_query: bool = False,
build_query_with_join: bool = False,
encode: bool = False,
secret: str = None
) -> str:
if build_query:
sorted_keys = sorted(data.keys())
query_string = []
for key in sorted_keys:
... | [
"def",
"create_hmac",
"(",
"data",
":",
"Union",
"[",
"dict",
",",
"str",
"]",
",",
"raw",
":",
"bool",
"=",
"False",
",",
"build_query",
":",
"bool",
"=",
"False",
",",
"build_query_with_join",
":",
"bool",
"=",
"False",
",",
"encode",
":",
"bool",
... | Create an HMAC string based on inputted values. | [
"Create",
"an",
"HMAC",
"string",
"based",
"on",
"inputted",
"values",
"."
] | [
"\"\"\"\n Create an HMAC string based on inputted values.\n \"\"\"",
"# Query building is required, sort the keys alphabetically",
"# Join arrays together by \",\"",
"# Optionally join result by \"&\"",
"# Generate the HMAC value",
"# For webhooks",
"# For 0Auth and proxy"
] | [
{
"param": "data",
"type": "Union[dict, str]"
},
{
"param": "raw",
"type": "bool"
},
{
"param": "build_query",
"type": "bool"
},
{
"param": "build_query_with_join",
"type": "bool"
},
{
"param": "encode",
"type": "bool"
},
{
"param": "secret",
"type... | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "data",
"type": "Union[dict, str]",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "raw",
"type": "bool",
"docstring": null,
"docst... |
37448021f79035c4cb8f8c7431fc9472a257c396 | ianjosephwilson/basic_shopify_api | basic_shopify_api/utils.py | [
"MIT"
] | Python | hmac_verify | bool | def hmac_verify(source: str, secret: str, params: dict, hmac_header: str = None) -> bool:
"""
Verify if the HMAC is correct.
"""
if source == "standard":
# Standard 0Auth/URL method
hmac_param = params["hmac"].encode(e)
params.pop("hmac", None)
kwargs = {
"da... |
Verify if the HMAC is correct.
| Verify if the HMAC is correct. | [
"Verify",
"if",
"the",
"HMAC",
"is",
"correct",
"."
] | def hmac_verify(source: str, secret: str, params: dict, hmac_header: str = None) -> bool:
if source == "standard":
hmac_param = params["hmac"].encode(e)
params.pop("hmac", None)
kwargs = {
"data": params,
"build_query": True,
"build_query_with_join": True,... | [
"def",
"hmac_verify",
"(",
"source",
":",
"str",
",",
"secret",
":",
"str",
",",
"params",
":",
"dict",
",",
"hmac_header",
":",
"str",
"=",
"None",
")",
"->",
"bool",
":",
"if",
"source",
"==",
"\"standard\"",
":",
"hmac_param",
"=",
"params",
"[",
... | Verify if the HMAC is correct. | [
"Verify",
"if",
"the",
"HMAC",
"is",
"correct",
"."
] | [
"\"\"\"\n Verify if the HMAC is correct.\n \"\"\"",
"# Standard 0Auth/URL method",
"# Proxy app request method",
"# Webhook data method",
"# Create the HMAC and compare to what was supplied"
] | [
{
"param": "source",
"type": "str"
},
{
"param": "secret",
"type": "str"
},
{
"param": "params",
"type": "dict"
},
{
"param": "hmac_header",
"type": "str"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "source",
"type": "str",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "secret",
"type": "str",
"docstring": null,
"docstring_toke... |
a3d79ea3b2dc07337d2ad82cceba8b9a7027f712 | shubhadeepb14/Python-Socket-Echo-Client-Server | server.py | [
"MIT"
] | Python | start | null | def start(self):
"""creates a thread and starts the handler
"""
t1 = threading.Thread(target=self.handle, args=[])
t1.daemon = True
t1.start() | creates a thread and starts the handler
| creates a thread and starts the handler | [
"creates",
"a",
"thread",
"and",
"starts",
"the",
"handler"
] | def start(self):
t1 = threading.Thread(target=self.handle, args=[])
t1.daemon = True
t1.start() | [
"def",
"start",
"(",
"self",
")",
":",
"t1",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"self",
".",
"handle",
",",
"args",
"=",
"[",
"]",
")",
"t1",
".",
"daemon",
"=",
"True",
"t1",
".",
"start",
"(",
")"
] | creates a thread and starts the handler | [
"creates",
"a",
"thread",
"and",
"starts",
"the",
"handler"
] | [
"\"\"\"creates a thread and starts the handler\n \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
f3ae7ddfb065c312eadff131b60c3f9846027d05 | karamfil/saphe | alfred/Alfred.alfredpreferences/workflows/user.workflow.99DE3F5C-7CB4-4E0B-9195-7782AADC167B/converter/convert.py | [
"MIT"
] | Python | convert | <not_specific> | def convert(self, query):
'''Convert a query to a list of units with quantities
:rtype: list of (Unit, decimal.Decimal, Unit)
'''
match = constants.FULL_RE.match(query)
source_match = constants.SOURCE_RE.match(query)
tos = None
from_ = None
quantity = pa... | Convert a query to a list of units with quantities
:rtype: list of (Unit, decimal.Decimal, Unit)
| Convert a query to a list of units with quantities | [
"Convert",
"a",
"query",
"to",
"a",
"list",
"of",
"units",
"with",
"quantities"
] | def convert(self, query):
match = constants.FULL_RE.match(query)
source_match = constants.SOURCE_RE.match(query)
tos = None
from_ = None
quantity = parse_quantity('0')
try:
try:
if match:
from_ = self.get(match.group('from')... | [
"def",
"convert",
"(",
"self",
",",
"query",
")",
":",
"match",
"=",
"constants",
".",
"FULL_RE",
".",
"match",
"(",
"query",
")",
"source_match",
"=",
"constants",
".",
"SOURCE_RE",
".",
"match",
"(",
"query",
")",
"tos",
"=",
"None",
"from_",
"=",
... | Convert a query to a list of units with quantities | [
"Convert",
"a",
"query",
"to",
"a",
"list",
"of",
"units",
"with",
"quantities"
] | [
"'''Convert a query to a list of units with quantities\n\n :rtype: list of (Unit, decimal.Decimal, Unit)\n '''"
] | [
{
"param": "self",
"type": null
},
{
"param": "query",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": "list of (Unit, decimal.Decimal, Unit)"
}
],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default":... |
0ce0e0e69789584329c1e7c436f7eb9828673f91 | karamfil/saphe | alfred/Alfred.alfredpreferences/workflows/user.workflow.99DE3F5C-7CB4-4E0B-9195-7782AADC167B/converter/safe_math.py | [
"MIT"
] | Python | safe_eval | <not_specific> | def safe_eval(query):
'''safely evaluate a query while automatically evaluating some mathematical
functions
>>> safe_eval('.1 * 0.01')
Decimal('0.001')
>>> safe_eval('0x10')
Decimal('16')
>>> safe_eval('10')
Decimal('10')
>>> safe_eval('010')
Decimal('8')
>>> safe_eval('0b10... | safely evaluate a query while automatically evaluating some mathematical
functions
>>> safe_eval('.1 * 0.01')
Decimal('0.001')
>>> safe_eval('0x10')
Decimal('16')
>>> safe_eval('10')
Decimal('10')
>>> safe_eval('010')
Decimal('8')
>>> safe_eval('0b10')
Decimal('2')
| safely evaluate a query while automatically evaluating some mathematical
functions
| [
"safely",
"evaluate",
"a",
"query",
"while",
"automatically",
"evaluating",
"some",
"mathematical",
"functions"
] | def safe_eval(query):
query = HEX_RE.sub(HEX_REPLACE, query)
query = BIN_RE.sub(BIN_REPLACE, query)
query = OCT_RE.sub(OCT_REPLACE, query)
query = DECIMAL_RE.sub(DECIMAL_REPLACE, query)
query = AUTOMUL_RE.sub(AUTOMUL_REPLACE, query)
query = fix_partial_queries(query)
query = fix_parentheses(... | [
"def",
"safe_eval",
"(",
"query",
")",
":",
"query",
"=",
"HEX_RE",
".",
"sub",
"(",
"HEX_REPLACE",
",",
"query",
")",
"query",
"=",
"BIN_RE",
".",
"sub",
"(",
"BIN_REPLACE",
",",
"query",
")",
"query",
"=",
"OCT_RE",
".",
"sub",
"(",
"OCT_REPLACE",
... | safely evaluate a query while automatically evaluating some mathematical
functions | [
"safely",
"evaluate",
"a",
"query",
"while",
"automatically",
"evaluating",
"some",
"mathematical",
"functions"
] | [
"'''safely evaluate a query while automatically evaluating some mathematical\n functions\n\n >>> safe_eval('.1 * 0.01')\n Decimal('0.001')\n >>> safe_eval('0x10')\n Decimal('16')\n >>> safe_eval('10')\n Decimal('10')\n >>> safe_eval('010')\n Decimal('8')\n >>> safe_eval('0b10')\n De... | [
{
"param": "query",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "query",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
106b001697c1f23b1a6253f52065d698dfada408 | elliotsegler/aws-aad-creds | aws_aad_creds/aad.py | [
"Apache-2.0"
] | Python | _get_device_code_session | <not_specific> | def _get_device_code_session(self):
""" Connect to AzureAD and start a Device Code flow """
device_code = self._adal_context.acquire_user_code(
self._middleware_client_id, self._cli_client_id) # noqa: E126,E501
return device_code | Connect to AzureAD and start a Device Code flow | Connect to AzureAD and start a Device Code flow | [
"Connect",
"to",
"AzureAD",
"and",
"start",
"a",
"Device",
"Code",
"flow"
] | def _get_device_code_session(self):
device_code = self._adal_context.acquire_user_code(
self._middleware_client_id, self._cli_client_id)
return device_code | [
"def",
"_get_device_code_session",
"(",
"self",
")",
":",
"device_code",
"=",
"self",
".",
"_adal_context",
".",
"acquire_user_code",
"(",
"self",
".",
"_middleware_client_id",
",",
"self",
".",
"_cli_client_id",
")",
"return",
"device_code"
] | Connect to AzureAD and start a Device Code flow | [
"Connect",
"to",
"AzureAD",
"and",
"start",
"a",
"Device",
"Code",
"flow"
] | [
"\"\"\" Connect to AzureAD and start a Device Code flow \"\"\"",
"# noqa: E126,E501\r"
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
106b001697c1f23b1a6253f52065d698dfada408 | elliotsegler/aws-aad-creds | aws_aad_creds/aad.py | [
"Apache-2.0"
] | Python | _block_and_wait_for_signin | <not_specific> | def _block_and_wait_for_signin(self, device_code):
""" Waits for the user to sign in """
# Block the thread, until we get confirmation that the token has
# been claimed or we time out
tpe = ThreadPoolExecutor(max_workers=1)
futures = []
# Add our poll job promise ... | Waits for the user to sign in | Waits for the user to sign in | [
"Waits",
"for",
"the",
"user",
"to",
"sign",
"in"
] | def _block_and_wait_for_signin(self, device_code):
tpe = ThreadPoolExecutor(max_workers=1)
futures = []
futures.append(tpe.submit(
self._adal_context.acquire_token_with_device_code,
self._middleware_client_id, device_code, self._cli_client_id
))
result = c... | [
"def",
"_block_and_wait_for_signin",
"(",
"self",
",",
"device_code",
")",
":",
"tpe",
"=",
"ThreadPoolExecutor",
"(",
"max_workers",
"=",
"1",
")",
"futures",
"=",
"[",
"]",
"futures",
".",
"append",
"(",
"tpe",
".",
"submit",
"(",
"self",
".",
"_adal_con... | Waits for the user to sign in | [
"Waits",
"for",
"the",
"user",
"to",
"sign",
"in"
] | [
"\"\"\" Waits for the user to sign in \"\"\"",
"# Block the thread, until we get confirmation that the token has\r",
"# been claimed or we time out\r",
"# Add our poll job promise to the queue\r",
"# Store the result if we get one inside 10 seconds, otherwise bail\r",
"# Blocking starts here...\r",
"# n... | [
{
"param": "self",
"type": null
},
{
"param": "device_code",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "device_code",
"type": null,
"docstring": null,
"docstring_tok... |
4b76a5c2ab224f3d3c18798d006c747a46a38c38 | mitchgrout/COMPX592 | ne/data/timestamp/__init__.py | [
"MIT"
] | Python | load_data | <not_specific> | def load_data(num=64, hi=6, lo=2):
"""
num = number of heartbeats sent in total
hi = maximum number of packets between two heartbeats
lo = minimum number ^
returns an iterator
"""
from collections import namedtuple
from random import randint, uniform
Packet = namedtuple('Packet... |
num = number of heartbeats sent in total
hi = maximum number of packets between two heartbeats
lo = minimum number ^
returns an iterator
| num = number of heartbeats sent in total
hi = maximum number of packets between two heartbeats
lo = minimum number ^
returns an iterator | [
"num",
"=",
"number",
"of",
"heartbeats",
"sent",
"in",
"total",
"hi",
"=",
"maximum",
"number",
"of",
"packets",
"between",
"two",
"heartbeats",
"lo",
"=",
"minimum",
"number",
"^",
"returns",
"an",
"iterator"
] | def load_data(num=64, hi=6, lo=2):
from collections import namedtuple
from random import randint, uniform
Packet = namedtuple('Packet', ['timestamp', 'length'])
current_time = uniform(0,1)
HEARTBEAT_LEN = 5
xs, ys = [], []
for _ in range(num):
xs.append(Packet(timestamp=current_tim... | [
"def",
"load_data",
"(",
"num",
"=",
"64",
",",
"hi",
"=",
"6",
",",
"lo",
"=",
"2",
")",
":",
"from",
"collections",
"import",
"namedtuple",
"from",
"random",
"import",
"randint",
",",
"uniform",
"Packet",
"=",
"namedtuple",
"(",
"'Packet'",
",",
"[",... | num = number of heartbeats sent in total
hi = maximum number of packets between two heartbeats
lo = minimum number ^
returns an iterator | [
"num",
"=",
"number",
"of",
"heartbeats",
"sent",
"in",
"total",
"hi",
"=",
"maximum",
"number",
"of",
"packets",
"between",
"two",
"heartbeats",
"lo",
"=",
"minimum",
"number",
"^",
"returns",
"an",
"iterator"
] | [
"\"\"\"\n num = number of heartbeats sent in total\n hi = maximum number of packets between two heartbeats\n lo = minimum number ^\n returns an iterator\n \"\"\""
] | [
{
"param": "num",
"type": null
},
{
"param": "hi",
"type": null
},
{
"param": "lo",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "num",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "hi",
"type": null,
"docstring": null,
"docstring_tokens": [],
... |
21679e769801edf207eadfcd100a2d37baf56d19 | agt-ucsd/nbresuse | nbresuse/__init__.py | [
"BSD-2-Clause"
] | Python | _jupyter_nbextension_paths | <not_specific> | def _jupyter_nbextension_paths():
"""
Set up the notebook extension for displaying metrics
"""
return [
{
"section": "notebook",
"dest": "nbresuse",
"src": "static",
"require": "nbresuse/main"
}
] |
Set up the notebook extension for displaying metrics
| Set up the notebook extension for displaying metrics | [
"Set",
"up",
"the",
"notebook",
"extension",
"for",
"displaying",
"metrics"
] | def _jupyter_nbextension_paths():
return [
{
"section": "notebook",
"dest": "nbresuse",
"src": "static",
"require": "nbresuse/main"
}
] | [
"def",
"_jupyter_nbextension_paths",
"(",
")",
":",
"return",
"[",
"{",
"\"section\"",
":",
"\"notebook\"",
",",
"\"dest\"",
":",
"\"nbresuse\"",
",",
"\"src\"",
":",
"\"static\"",
",",
"\"require\"",
":",
"\"nbresuse/main\"",
"}",
"]"
] | Set up the notebook extension for displaying metrics | [
"Set",
"up",
"the",
"notebook",
"extension",
"for",
"displaying",
"metrics"
] | [
"\"\"\"\n Set up the notebook extension for displaying metrics\n \"\"\""
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
491da0254645748c01aa94927aa96b02799ce809 | NZR/PublicDiscourseMiner-COVID | src/analyse/db_updater.py | [
"MIT"
] | Python | db_update | null | def db_update(stopwords=True, bigrams=True):
'''
Clean up articles from the database, remove stopwords, extract bigrams and add a bigram column
'''
#get rows, per row ID and full text
db = dbconnect()
#Get all rows
cur_all_rows = db.query("SELECT id, full_text, full_without_stop FROM artikel... |
Clean up articles from the database, remove stopwords, extract bigrams and add a bigram column
| Clean up articles from the database, remove stopwords, extract bigrams and add a bigram column | [
"Clean",
"up",
"articles",
"from",
"the",
"database",
"remove",
"stopwords",
"extract",
"bigrams",
"and",
"add",
"a",
"bigram",
"column"
] | def db_update(stopwords=True, bigrams=True):
db = dbconnect()
cur_all_rows = db.query("SELECT id, full_text, full_without_stop FROM artikelen", (), True)
for row in tqdm(cur_all_rows):
id = row[0]
full = row[1]
full_without_stop = row[2]
if stopwords:
counter = Co... | [
"def",
"db_update",
"(",
"stopwords",
"=",
"True",
",",
"bigrams",
"=",
"True",
")",
":",
"db",
"=",
"dbconnect",
"(",
")",
"cur_all_rows",
"=",
"db",
".",
"query",
"(",
"\"SELECT id, full_text, full_without_stop FROM artikelen\"",
",",
"(",
")",
",",
"True",
... | Clean up articles from the database, remove stopwords, extract bigrams and add a bigram column | [
"Clean",
"up",
"articles",
"from",
"the",
"database",
"remove",
"stopwords",
"extract",
"bigrams",
"and",
"add",
"a",
"bigram",
"column"
] | [
"'''\n Clean up articles from the database, remove stopwords, extract bigrams and add a bigram column\n '''",
"#get rows, per row ID and full text",
"#Get all rows",
"#remove stop words if wanted",
"#Create bigrams if wanted"
] | [
{
"param": "stopwords",
"type": null
},
{
"param": "bigrams",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "stopwords",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "bigrams",
"type": null,
"docstring": null,
"docstring_to... |
ca5bc2f7b853c1dab725297ba685a89c3bb45a2c | guoyuxin1984/machine-learning-examples | utils.py | [
"MIT"
] | Python | standardize | <not_specific> | def standardize(x):
"""
standardize the input to have mean 0 and L2 norm 1
:param x:
:return: standardize the input to have mean 0 and L2 norm 1
"""
cen = centralize(x)
std = np.std(cen, axis=0) * np.sqrt(x.shape[0])
std = cen/std
return std |
standardize the input to have mean 0 and L2 norm 1
:param x:
:return: standardize the input to have mean 0 and L2 norm 1
| standardize the input to have mean 0 and L2 norm 1 | [
"standardize",
"the",
"input",
"to",
"have",
"mean",
"0",
"and",
"L2",
"norm",
"1"
] | def standardize(x):
cen = centralize(x)
std = np.std(cen, axis=0) * np.sqrt(x.shape[0])
std = cen/std
return std | [
"def",
"standardize",
"(",
"x",
")",
":",
"cen",
"=",
"centralize",
"(",
"x",
")",
"std",
"=",
"np",
".",
"std",
"(",
"cen",
",",
"axis",
"=",
"0",
")",
"*",
"np",
".",
"sqrt",
"(",
"x",
".",
"shape",
"[",
"0",
"]",
")",
"std",
"=",
"cen",
... | standardize the input to have mean 0 and L2 norm 1 | [
"standardize",
"the",
"input",
"to",
"have",
"mean",
"0",
"and",
"L2",
"norm",
"1"
] | [
"\"\"\"\r\n standardize the input to have mean 0 and L2 norm 1\r\n :param x:\r\n :return: standardize the input to have mean 0 and L2 norm 1\r\n \"\"\""
] | [
{
"param": "x",
"type": null
}
] | {
"returns": [
{
"docstring": "standardize the input to have mean 0 and L2 norm 1",
"docstring_tokens": [
"standardize",
"the",
"input",
"to",
"have",
"mean",
"0",
"and",
"L2",
"norm",
"1"
],
"type": nu... |
ca5bc2f7b853c1dab725297ba685a89c3bb45a2c | guoyuxin1984/machine-learning-examples | utils.py | [
"MIT"
] | Python | standardize_z_score | <not_specific> | def standardize_z_score(x):
"""
standardize the input to have mean 0 and std 1
:param x:
:return: standardize the input to have mean 0 and std 1
"""
cen = centralize(x)
std = np.std(cen, axis=0)
std = cen / std
return std |
standardize the input to have mean 0 and std 1
:param x:
:return: standardize the input to have mean 0 and std 1
| standardize the input to have mean 0 and std 1 | [
"standardize",
"the",
"input",
"to",
"have",
"mean",
"0",
"and",
"std",
"1"
] | def standardize_z_score(x):
cen = centralize(x)
std = np.std(cen, axis=0)
std = cen / std
return std | [
"def",
"standardize_z_score",
"(",
"x",
")",
":",
"cen",
"=",
"centralize",
"(",
"x",
")",
"std",
"=",
"np",
".",
"std",
"(",
"cen",
",",
"axis",
"=",
"0",
")",
"std",
"=",
"cen",
"/",
"std",
"return",
"std"
] | standardize the input to have mean 0 and std 1 | [
"standardize",
"the",
"input",
"to",
"have",
"mean",
"0",
"and",
"std",
"1"
] | [
"\"\"\"\r\n standardize the input to have mean 0 and std 1\r\n :param x:\r\n :return: standardize the input to have mean 0 and std 1\r\n \"\"\""
] | [
{
"param": "x",
"type": null
}
] | {
"returns": [
{
"docstring": "standardize the input to have mean 0 and std 1",
"docstring_tokens": [
"standardize",
"the",
"input",
"to",
"have",
"mean",
"0",
"and",
"std",
"1"
],
"type": null
}
],
"ra... |
ca5bc2f7b853c1dab725297ba685a89c3bb45a2c | guoyuxin1984/machine-learning-examples | utils.py | [
"MIT"
] | Python | load_data_diabetes | <not_specific> | def load_data_diabetes():
"""
load the diabetes data with 10 predictors and 1 response
:return: return input matrix x and response vector y
"""
x = np.genfromtxt('data/diabetes.data', skip_header=1, dtype=float, usecols=range(10))
y = np.genfromtxt('data/diabetes.data', skip_header=1, dtyp... |
load the diabetes data with 10 predictors and 1 response
:return: return input matrix x and response vector y
| load the diabetes data with 10 predictors and 1 response | [
"load",
"the",
"diabetes",
"data",
"with",
"10",
"predictors",
"and",
"1",
"response"
] | def load_data_diabetes():
x = np.genfromtxt('data/diabetes.data', skip_header=1, dtype=float, usecols=range(10))
y = np.genfromtxt('data/diabetes.data', skip_header=1, dtype=float, usecols=[10])
return x, y | [
"def",
"load_data_diabetes",
"(",
")",
":",
"x",
"=",
"np",
".",
"genfromtxt",
"(",
"'data/diabetes.data'",
",",
"skip_header",
"=",
"1",
",",
"dtype",
"=",
"float",
",",
"usecols",
"=",
"range",
"(",
"10",
")",
")",
"y",
"=",
"np",
".",
"genfromtxt",
... | load the diabetes data with 10 predictors and 1 response | [
"load",
"the",
"diabetes",
"data",
"with",
"10",
"predictors",
"and",
"1",
"response"
] | [
"\"\"\"\r\n load the diabetes data with 10 predictors and 1 response\r\n :return: return input matrix x and response vector y\r\n \"\"\""
] | [] | {
"returns": [
{
"docstring": "return input matrix x and response vector y",
"docstring_tokens": [
"return",
"input",
"matrix",
"x",
"and",
"response",
"vector",
"y"
],
"type": null
}
],
"raises": [],
"params": [],
... |
0a678d8ba8986aa3adb90ad49402f8484b064476 | kilrau/lnbits-legend | lnbits/extensions/streamalerts/views_api.py | [
"MIT"
] | Python | api_create_service | <not_specific> | async def api_create_service(
data: CreateService, wallet: WalletTypeInfo = Depends(get_key_type)
):
"""Create a service, which holds data about how/where to post donations"""
try:
service = await create_service(data=data)
except Exception as e:
raise HTTPException(status_code=HTTPStatus... | Create a service, which holds data about how/where to post donations | Create a service, which holds data about how/where to post donations | [
"Create",
"a",
"service",
"which",
"holds",
"data",
"about",
"how",
"/",
"where",
"to",
"post",
"donations"
] | async def api_create_service(
data: CreateService, wallet: WalletTypeInfo = Depends(get_key_type)
):
try:
service = await create_service(data=data)
except Exception as e:
raise HTTPException(status_code=HTTPStatus.INTERNAL_SERVER_ERROR, detail=str(e))
return service.dict() | [
"async",
"def",
"api_create_service",
"(",
"data",
":",
"CreateService",
",",
"wallet",
":",
"WalletTypeInfo",
"=",
"Depends",
"(",
"get_key_type",
")",
")",
":",
"try",
":",
"service",
"=",
"await",
"create_service",
"(",
"data",
"=",
"data",
")",
"except",... | Create a service, which holds data about how/where to post donations | [
"Create",
"a",
"service",
"which",
"holds",
"data",
"about",
"how",
"/",
"where",
"to",
"post",
"donations"
] | [
"\"\"\"Create a service, which holds data about how/where to post donations\"\"\""
] | [
{
"param": "data",
"type": "CreateService"
},
{
"param": "wallet",
"type": "WalletTypeInfo"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "data",
"type": "CreateService",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "wallet",
"type": "WalletTypeInfo",
"docstring": null,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.