repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
tanghaibao/jcvi | jcvi/compara/fractionation.py | diff | def diff(args):
"""
%prog diff simplefile
Calculate difference of pairwise syntenic regions.
"""
from jcvi.utils.cbook import SummaryStats
p = OptionParser(diff.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
simplefile, = args
fp = open(simplefile)
data = [x.split() for x in fp]
spans = []
for block_id, ab in groupby(data[1:], key=lambda x: x[0]):
a, b = list(ab)
aspan, bspan = a[4], b[4]
aspan, bspan = int(aspan), int(bspan)
spans.append((aspan, bspan))
aspans, bspans = zip(*spans)
dspans = [b - a for a, b, in spans]
s = SummaryStats(dspans)
print("For a total of {0} blocks:".format(len(dspans)), file=sys.stderr)
print("Sum of A: {0}".format(sum(aspans)), file=sys.stderr)
print("Sum of B: {0}".format(sum(bspans)), file=sys.stderr)
print("Sum of Delta: {0} ({1})".format(sum(dspans), s), file=sys.stderr) | python | def diff(args):
"""
%prog diff simplefile
Calculate difference of pairwise syntenic regions.
"""
from jcvi.utils.cbook import SummaryStats
p = OptionParser(diff.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
simplefile, = args
fp = open(simplefile)
data = [x.split() for x in fp]
spans = []
for block_id, ab in groupby(data[1:], key=lambda x: x[0]):
a, b = list(ab)
aspan, bspan = a[4], b[4]
aspan, bspan = int(aspan), int(bspan)
spans.append((aspan, bspan))
aspans, bspans = zip(*spans)
dspans = [b - a for a, b, in spans]
s = SummaryStats(dspans)
print("For a total of {0} blocks:".format(len(dspans)), file=sys.stderr)
print("Sum of A: {0}".format(sum(aspans)), file=sys.stderr)
print("Sum of B: {0}".format(sum(bspans)), file=sys.stderr)
print("Sum of Delta: {0} ({1})".format(sum(dspans), s), file=sys.stderr) | [
"def",
"diff",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"utils",
".",
"cbook",
"import",
"SummaryStats",
"p",
"=",
"OptionParser",
"(",
"diff",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
... | %prog diff simplefile
Calculate difference of pairwise syntenic regions. | [
"%prog",
"diff",
"simplefile"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/compara/fractionation.py#L90-L119 | train | 201,100 |
tanghaibao/jcvi | jcvi/compara/fractionation.py | estimate_size | def estimate_size(accns, bed, order, conservative=True):
"""
Estimate the bp length for the deletion tracks, indicated by the gene accns.
True different levels of estimates vary on conservativeness.
"""
accns = [order[x] for x in accns]
ii, bb = zip(*accns)
mini, maxi = min(ii), max(ii)
if not conservative: # extend one gene
mini -= 1
maxi += 1
minb = bed[mini]
maxb = bed[maxi]
assert minb.seqid == maxb.seqid
distmode = "ss" if conservative else "ee"
ra = (minb.seqid, minb.start, minb.end, "+")
rb = (maxb.seqid, maxb.start, maxb.end, "+")
dist, orientation = range_distance(ra, rb, distmode=distmode)
assert dist != -1
return dist | python | def estimate_size(accns, bed, order, conservative=True):
"""
Estimate the bp length for the deletion tracks, indicated by the gene accns.
True different levels of estimates vary on conservativeness.
"""
accns = [order[x] for x in accns]
ii, bb = zip(*accns)
mini, maxi = min(ii), max(ii)
if not conservative: # extend one gene
mini -= 1
maxi += 1
minb = bed[mini]
maxb = bed[maxi]
assert minb.seqid == maxb.seqid
distmode = "ss" if conservative else "ee"
ra = (minb.seqid, minb.start, minb.end, "+")
rb = (maxb.seqid, maxb.start, maxb.end, "+")
dist, orientation = range_distance(ra, rb, distmode=distmode)
assert dist != -1
return dist | [
"def",
"estimate_size",
"(",
"accns",
",",
"bed",
",",
"order",
",",
"conservative",
"=",
"True",
")",
":",
"accns",
"=",
"[",
"order",
"[",
"x",
"]",
"for",
"x",
"in",
"accns",
"]",
"ii",
",",
"bb",
"=",
"zip",
"(",
"*",
"accns",
")",
"mini",
... | Estimate the bp length for the deletion tracks, indicated by the gene accns.
True different levels of estimates vary on conservativeness. | [
"Estimate",
"the",
"bp",
"length",
"for",
"the",
"deletion",
"tracks",
"indicated",
"by",
"the",
"gene",
"accns",
".",
"True",
"different",
"levels",
"of",
"estimates",
"vary",
"on",
"conservativeness",
"."
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/compara/fractionation.py#L122-L142 | train | 201,101 |
tanghaibao/jcvi | jcvi/compara/fractionation.py | merge | def merge(args):
"""
%prog merge protein-quartets registry LOST
Merge protein quartets table with dna quartets registry. This is specific
to the napus project.
"""
from jcvi.formats.base import DictFile
p = OptionParser(merge.__doc__)
opts, args = p.parse_args(args)
if len(args) != 3:
sys.exit(not p.print_help())
quartets, registry, lost = args
qq = DictFile(registry, keypos=1, valuepos=3)
lost = DictFile(lost, keypos=1, valuepos=0, delimiter='|')
qq.update(lost)
fp = open(quartets)
cases = {
"AN,CN": 4,
"BO,AN,CN": 8,
"BO,CN": 2,
"BR,AN": 1,
"BR,AN,CN": 6,
"BR,BO": 3,
"BR,BO,AN": 5,
"BR,BO,AN,CN": 9,
"BR,BO,CN": 7,
}
ip = {
"syntenic_model": "Syntenic_model_excluded_by_OMG",
"complete": "Predictable",
"partial": "Truncated",
"pseudogene": "Pseudogene",
"random": "Match_random",
"real_ns": "Transposed",
"gmap_fail": "GMAP_fail",
"AN LOST": "AN_LOST",
"CN LOST": "CN_LOST",
"BR LOST": "BR_LOST",
"BO LOST": "BO_LOST",
"outside": "Outside_synteny_blocks",
"[NF]": "Not_found",
}
for row in fp:
atoms = row.strip().split("\t")
genes = atoms[:4]
tag = atoms[4]
a, b, c, d = [qq.get(x, ".").rsplit("-", 1)[-1] for x in genes]
qqs = [c, d, a, b]
for i, q in enumerate(qqs):
if atoms[i] != '.':
qqs[i] = "syntenic_model"
# Make comment
comment = "Case{0}".format(cases[tag])
dots = sum([1 for x in genes if x == '.'])
if dots == 1:
idx = genes.index(".")
status = qqs[idx]
status = ip[status]
comment += "-" + status
print(row.strip() + "\t" + "\t".join(qqs + [comment])) | python | def merge(args):
"""
%prog merge protein-quartets registry LOST
Merge protein quartets table with dna quartets registry. This is specific
to the napus project.
"""
from jcvi.formats.base import DictFile
p = OptionParser(merge.__doc__)
opts, args = p.parse_args(args)
if len(args) != 3:
sys.exit(not p.print_help())
quartets, registry, lost = args
qq = DictFile(registry, keypos=1, valuepos=3)
lost = DictFile(lost, keypos=1, valuepos=0, delimiter='|')
qq.update(lost)
fp = open(quartets)
cases = {
"AN,CN": 4,
"BO,AN,CN": 8,
"BO,CN": 2,
"BR,AN": 1,
"BR,AN,CN": 6,
"BR,BO": 3,
"BR,BO,AN": 5,
"BR,BO,AN,CN": 9,
"BR,BO,CN": 7,
}
ip = {
"syntenic_model": "Syntenic_model_excluded_by_OMG",
"complete": "Predictable",
"partial": "Truncated",
"pseudogene": "Pseudogene",
"random": "Match_random",
"real_ns": "Transposed",
"gmap_fail": "GMAP_fail",
"AN LOST": "AN_LOST",
"CN LOST": "CN_LOST",
"BR LOST": "BR_LOST",
"BO LOST": "BO_LOST",
"outside": "Outside_synteny_blocks",
"[NF]": "Not_found",
}
for row in fp:
atoms = row.strip().split("\t")
genes = atoms[:4]
tag = atoms[4]
a, b, c, d = [qq.get(x, ".").rsplit("-", 1)[-1] for x in genes]
qqs = [c, d, a, b]
for i, q in enumerate(qqs):
if atoms[i] != '.':
qqs[i] = "syntenic_model"
# Make comment
comment = "Case{0}".format(cases[tag])
dots = sum([1 for x in genes if x == '.'])
if dots == 1:
idx = genes.index(".")
status = qqs[idx]
status = ip[status]
comment += "-" + status
print(row.strip() + "\t" + "\t".join(qqs + [comment])) | [
"def",
"merge",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"formats",
".",
"base",
"import",
"DictFile",
"p",
"=",
"OptionParser",
"(",
"merge",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
... | %prog merge protein-quartets registry LOST
Merge protein quartets table with dna quartets registry. This is specific
to the napus project. | [
"%prog",
"merge",
"protein",
"-",
"quartets",
"registry",
"LOST"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/compara/fractionation.py#L222-L285 | train | 201,102 |
tanghaibao/jcvi | jcvi/compara/fractionation.py | gffselect | def gffselect(args):
"""
%prog gffselect gmaplocation.bed expectedlocation.bed translated.ids tag
Try to match up the expected location and gmap locations for particular
genes. translated.ids was generated by fasta.translate --ids. tag must be
one of "complete|pseudogene|partial".
"""
from jcvi.formats.bed import intersectBed_wao
p = OptionParser(gffselect.__doc__)
opts, args = p.parse_args(args)
if len(args) != 4:
sys.exit(not p.print_help())
gmapped, expected, idsfile, tag = args
data = get_tags(idsfile)
completeness = dict((a.replace("mrna", "path"), c) \
for (a, b, c) in data)
seen = set()
idsfile = expected.rsplit(".", 1)[0] + ".ids"
fw = open(idsfile, "w")
cnt = 0
for a, b in intersectBed_wao(expected, gmapped):
if b is None:
continue
aname, bbname = a.accn, b.accn
bname = bbname.split(".")[0]
if completeness[bbname] != tag:
continue
if aname == bname:
if bname in seen:
continue
seen.add(bname)
print(bbname, file=fw)
cnt += 1
fw.close()
logging.debug("Total {0} records written to `{1}`.".format(cnt, idsfile)) | python | def gffselect(args):
"""
%prog gffselect gmaplocation.bed expectedlocation.bed translated.ids tag
Try to match up the expected location and gmap locations for particular
genes. translated.ids was generated by fasta.translate --ids. tag must be
one of "complete|pseudogene|partial".
"""
from jcvi.formats.bed import intersectBed_wao
p = OptionParser(gffselect.__doc__)
opts, args = p.parse_args(args)
if len(args) != 4:
sys.exit(not p.print_help())
gmapped, expected, idsfile, tag = args
data = get_tags(idsfile)
completeness = dict((a.replace("mrna", "path"), c) \
for (a, b, c) in data)
seen = set()
idsfile = expected.rsplit(".", 1)[0] + ".ids"
fw = open(idsfile, "w")
cnt = 0
for a, b in intersectBed_wao(expected, gmapped):
if b is None:
continue
aname, bbname = a.accn, b.accn
bname = bbname.split(".")[0]
if completeness[bbname] != tag:
continue
if aname == bname:
if bname in seen:
continue
seen.add(bname)
print(bbname, file=fw)
cnt += 1
fw.close()
logging.debug("Total {0} records written to `{1}`.".format(cnt, idsfile)) | [
"def",
"gffselect",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"formats",
".",
"bed",
"import",
"intersectBed_wao",
"p",
"=",
"OptionParser",
"(",
"gffselect",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"i... | %prog gffselect gmaplocation.bed expectedlocation.bed translated.ids tag
Try to match up the expected location and gmap locations for particular
genes. translated.ids was generated by fasta.translate --ids. tag must be
one of "complete|pseudogene|partial". | [
"%prog",
"gffselect",
"gmaplocation",
".",
"bed",
"expectedlocation",
".",
"bed",
"translated",
".",
"ids",
"tag"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/compara/fractionation.py#L288-L328 | train | 201,103 |
tanghaibao/jcvi | jcvi/compara/fractionation.py | gaps | def gaps(args):
"""
%prog gaps idsfile fractionationfile gapsbed
Check gene locations against gaps. `idsfile` contains a list of IDs to query
into `fractionationfile` in order to get expected locations.
"""
from jcvi.formats.base import DictFile
from jcvi.apps.base import popen
from jcvi.utils.cbook import percentage
p = OptionParser(gaps.__doc__)
p.add_option("--bdist", default=0, type="int",
help="Base pair distance [default: %default]")
opts, args = p.parse_args(args)
if len(args) != 3:
sys.exit(not p.print_help())
idsfile, frfile, gapsbed = args
bdist = opts.bdist
d = DictFile(frfile, keypos=1, valuepos=2)
bedfile = idsfile + ".bed"
fw = open(bedfile, "w")
fp = open(idsfile)
total = 0
for row in fp:
id = row.strip()
hit = d[id]
tag, pos = get_tag(hit, None)
seqid, start, end = pos
start, end = max(start - bdist, 1), end + bdist
print("\t".join(str(x) for x in (seqid, start - 1, end, id)), file=fw)
total += 1
fw.close()
cmd = "intersectBed -a {0} -b {1} -v | wc -l".format(bedfile, gapsbed)
not_in_gaps = popen(cmd).read()
not_in_gaps = int(not_in_gaps)
in_gaps = total - not_in_gaps
print("Ids in gaps: {1}".\
format(total, percentage(in_gaps, total)), file=sys.stderr) | python | def gaps(args):
"""
%prog gaps idsfile fractionationfile gapsbed
Check gene locations against gaps. `idsfile` contains a list of IDs to query
into `fractionationfile` in order to get expected locations.
"""
from jcvi.formats.base import DictFile
from jcvi.apps.base import popen
from jcvi.utils.cbook import percentage
p = OptionParser(gaps.__doc__)
p.add_option("--bdist", default=0, type="int",
help="Base pair distance [default: %default]")
opts, args = p.parse_args(args)
if len(args) != 3:
sys.exit(not p.print_help())
idsfile, frfile, gapsbed = args
bdist = opts.bdist
d = DictFile(frfile, keypos=1, valuepos=2)
bedfile = idsfile + ".bed"
fw = open(bedfile, "w")
fp = open(idsfile)
total = 0
for row in fp:
id = row.strip()
hit = d[id]
tag, pos = get_tag(hit, None)
seqid, start, end = pos
start, end = max(start - bdist, 1), end + bdist
print("\t".join(str(x) for x in (seqid, start - 1, end, id)), file=fw)
total += 1
fw.close()
cmd = "intersectBed -a {0} -b {1} -v | wc -l".format(bedfile, gapsbed)
not_in_gaps = popen(cmd).read()
not_in_gaps = int(not_in_gaps)
in_gaps = total - not_in_gaps
print("Ids in gaps: {1}".\
format(total, percentage(in_gaps, total)), file=sys.stderr) | [
"def",
"gaps",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"formats",
".",
"base",
"import",
"DictFile",
"from",
"jcvi",
".",
"apps",
".",
"base",
"import",
"popen",
"from",
"jcvi",
".",
"utils",
".",
"cbook",
"import",
"percentage",
"p",
"=",
"OptionP... | %prog gaps idsfile fractionationfile gapsbed
Check gene locations against gaps. `idsfile` contains a list of IDs to query
into `fractionationfile` in order to get expected locations. | [
"%prog",
"gaps",
"idsfile",
"fractionationfile",
"gapsbed"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/compara/fractionation.py#L331-L372 | train | 201,104 |
tanghaibao/jcvi | jcvi/compara/fractionation.py | genestatus | def genestatus(args):
"""
%prog genestatus diploid.gff3.exon.ids
Tag genes based on translation from GMAP models, using fasta.translate()
--ids.
"""
p = OptionParser(genestatus.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
idsfile, = args
data = get_tags(idsfile)
key = lambda x: x[0].split(".")[0]
for gene, cc in groupby(data, key=key):
cc = list(cc)
tags = [x[-1] for x in cc]
if "complete" in tags:
tag = "complete"
elif "partial" in tags:
tag = "partial"
else:
tag = "pseudogene"
print("\t".join((gene, tag))) | python | def genestatus(args):
"""
%prog genestatus diploid.gff3.exon.ids
Tag genes based on translation from GMAP models, using fasta.translate()
--ids.
"""
p = OptionParser(genestatus.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
idsfile, = args
data = get_tags(idsfile)
key = lambda x: x[0].split(".")[0]
for gene, cc in groupby(data, key=key):
cc = list(cc)
tags = [x[-1] for x in cc]
if "complete" in tags:
tag = "complete"
elif "partial" in tags:
tag = "partial"
else:
tag = "pseudogene"
print("\t".join((gene, tag))) | [
"def",
"genestatus",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"genestatus",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"!=",
"1",
":",
"sys",
".",
"exit",
"... | %prog genestatus diploid.gff3.exon.ids
Tag genes based on translation from GMAP models, using fasta.translate()
--ids. | [
"%prog",
"genestatus",
"diploid",
".",
"gff3",
".",
"exon",
".",
"ids"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/compara/fractionation.py#L392-L417 | train | 201,105 |
tanghaibao/jcvi | jcvi/compara/fractionation.py | validate | def validate(args):
"""
%prog validate diploid.napus.fractionation cds.bed
Check whether [S] intervals overlap with CDS.
"""
from jcvi.formats.bed import intersectBed_wao
p = OptionParser(validate.__doc__)
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
fractionation, cdsbed = args
fp = open(fractionation)
sbed = "S.bed"
fw = open(sbed, "w")
for row in fp:
a, b, c = row.split()
if not c.startswith("[S]"):
continue
tag, (seqid, start, end) = get_tag(c, None)
print("\t".join(str(x) for x in (seqid, start - 1, end, b)), file=fw)
fw.close()
pairs = {}
for a, b in intersectBed_wao(sbed, cdsbed):
if b is None:
continue
pairs[a.accn] = b.accn
validated = fractionation + ".validated"
fw = open(validated, "w")
fp.seek(0)
fixed = 0
for row in fp:
a, b, c = row.split()
if b in pairs:
assert c.startswith("[S]")
c = pairs[b]
fixed += 1
print("\t".join((a, b, c)), file=fw)
logging.debug("Fixed {0} [S] cases in `{1}`.".format(fixed, validated))
fw.close() | python | def validate(args):
"""
%prog validate diploid.napus.fractionation cds.bed
Check whether [S] intervals overlap with CDS.
"""
from jcvi.formats.bed import intersectBed_wao
p = OptionParser(validate.__doc__)
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
fractionation, cdsbed = args
fp = open(fractionation)
sbed = "S.bed"
fw = open(sbed, "w")
for row in fp:
a, b, c = row.split()
if not c.startswith("[S]"):
continue
tag, (seqid, start, end) = get_tag(c, None)
print("\t".join(str(x) for x in (seqid, start - 1, end, b)), file=fw)
fw.close()
pairs = {}
for a, b in intersectBed_wao(sbed, cdsbed):
if b is None:
continue
pairs[a.accn] = b.accn
validated = fractionation + ".validated"
fw = open(validated, "w")
fp.seek(0)
fixed = 0
for row in fp:
a, b, c = row.split()
if b in pairs:
assert c.startswith("[S]")
c = pairs[b]
fixed += 1
print("\t".join((a, b, c)), file=fw)
logging.debug("Fixed {0} [S] cases in `{1}`.".format(fixed, validated))
fw.close() | [
"def",
"validate",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"formats",
".",
"bed",
"import",
"intersectBed_wao",
"p",
"=",
"OptionParser",
"(",
"validate",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if"... | %prog validate diploid.napus.fractionation cds.bed
Check whether [S] intervals overlap with CDS. | [
"%prog",
"validate",
"diploid",
".",
"napus",
".",
"fractionation",
"cds",
".",
"bed"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/compara/fractionation.py#L785-L834 | train | 201,106 |
tanghaibao/jcvi | jcvi/annotation/pasa.py | longest | def longest(args):
"""
%prog longest pasa.fasta output.subclusters.out
Find the longest PASA assembly and label it as full-length. Also removes
transcripts shorter than half the length of the longest, or shorter than
200bp. The assemblies for the same locus is found in
`output.subclusters.out`. In particular the lines that look like:
sub-cluster: asmbl_25 asmbl_26 asmbl_27
"""
from jcvi.formats.fasta import Fasta, SeqIO
from jcvi.formats.sizes import Sizes
p = OptionParser(longest.__doc__)
p.add_option("--prefix", default="pasa",
help="Replace asmbl_ with prefix [default: %default]")
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
fastafile, subclusters = args
prefix = fastafile.rsplit(".", 1)[0]
idsfile = prefix + ".fl.ids"
fw = open(idsfile, "w")
sizes = Sizes(fastafile).mapping
name_convert = lambda x: x.replace("asmbl", opts.prefix)
keep = set() # List of IDs to write
fp = open(subclusters)
nrecs = 0
for row in fp:
if not row.startswith("sub-cluster:"):
continue
asmbls = row.split()[1:]
longest_asmbl = max(asmbls, key=lambda x: sizes[x])
longest_size = sizes[longest_asmbl]
print(name_convert(longest_asmbl), file=fw)
nrecs += 1
cutoff = max(longest_size / 2, 200)
keep.update(set(x for x in asmbls if sizes[x] >= cutoff))
fw.close()
logging.debug("{0} fl-cDNA records written to `{1}`.".format(nrecs, idsfile))
f = Fasta(fastafile, lazy=True)
newfastafile = prefix + ".clean.fasta"
fw = open(newfastafile, "w")
nrecs = 0
for name, rec in f.iteritems_ordered():
if name not in keep:
continue
rec.id = name_convert(name)
rec.description = ""
SeqIO.write([rec], fw, "fasta")
nrecs += 1
fw.close()
logging.debug("{0} valid records written to `{1}`.".format(nrecs, newfastafile)) | python | def longest(args):
"""
%prog longest pasa.fasta output.subclusters.out
Find the longest PASA assembly and label it as full-length. Also removes
transcripts shorter than half the length of the longest, or shorter than
200bp. The assemblies for the same locus is found in
`output.subclusters.out`. In particular the lines that look like:
sub-cluster: asmbl_25 asmbl_26 asmbl_27
"""
from jcvi.formats.fasta import Fasta, SeqIO
from jcvi.formats.sizes import Sizes
p = OptionParser(longest.__doc__)
p.add_option("--prefix", default="pasa",
help="Replace asmbl_ with prefix [default: %default]")
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
fastafile, subclusters = args
prefix = fastafile.rsplit(".", 1)[0]
idsfile = prefix + ".fl.ids"
fw = open(idsfile, "w")
sizes = Sizes(fastafile).mapping
name_convert = lambda x: x.replace("asmbl", opts.prefix)
keep = set() # List of IDs to write
fp = open(subclusters)
nrecs = 0
for row in fp:
if not row.startswith("sub-cluster:"):
continue
asmbls = row.split()[1:]
longest_asmbl = max(asmbls, key=lambda x: sizes[x])
longest_size = sizes[longest_asmbl]
print(name_convert(longest_asmbl), file=fw)
nrecs += 1
cutoff = max(longest_size / 2, 200)
keep.update(set(x for x in asmbls if sizes[x] >= cutoff))
fw.close()
logging.debug("{0} fl-cDNA records written to `{1}`.".format(nrecs, idsfile))
f = Fasta(fastafile, lazy=True)
newfastafile = prefix + ".clean.fasta"
fw = open(newfastafile, "w")
nrecs = 0
for name, rec in f.iteritems_ordered():
if name not in keep:
continue
rec.id = name_convert(name)
rec.description = ""
SeqIO.write([rec], fw, "fasta")
nrecs += 1
fw.close()
logging.debug("{0} valid records written to `{1}`.".format(nrecs, newfastafile)) | [
"def",
"longest",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"formats",
".",
"fasta",
"import",
"Fasta",
",",
"SeqIO",
"from",
"jcvi",
".",
"formats",
".",
"sizes",
"import",
"Sizes",
"p",
"=",
"OptionParser",
"(",
"longest",
".",
"__doc__",
")",
"p",... | %prog longest pasa.fasta output.subclusters.out
Find the longest PASA assembly and label it as full-length. Also removes
transcripts shorter than half the length of the longest, or shorter than
200bp. The assemblies for the same locus is found in
`output.subclusters.out`. In particular the lines that look like:
sub-cluster: asmbl_25 asmbl_26 asmbl_27 | [
"%prog",
"longest",
"pasa",
".",
"fasta",
"output",
".",
"subclusters",
".",
"out"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/annotation/pasa.py#L271-L333 | train | 201,107 |
tanghaibao/jcvi | jcvi/apps/cdhit.py | ids | def ids(args):
"""
%prog ids cdhit.clstr
Get the representative ids from clstr file.
"""
p = OptionParser(ids.__doc__)
p.add_option("--prefix", type="int",
help="Find rep id for prefix of len [default: %default]")
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
clstrfile, = args
cf = ClstrFile(clstrfile)
prefix = opts.prefix
if prefix:
reads = list(cf.iter_reps_prefix(prefix=prefix))
else:
reads = list(cf.iter_reps())
nreads = len(reads)
idsfile = clstrfile.replace(".clstr", ".ids")
fw = open(idsfile, "w")
for i, name in reads:
print("\t".join(str(x) for x in (i, name)), file=fw)
logging.debug("A total of {0} unique reads written to `{1}`.".\
format(nreads, idsfile))
fw.close()
return idsfile | python | def ids(args):
"""
%prog ids cdhit.clstr
Get the representative ids from clstr file.
"""
p = OptionParser(ids.__doc__)
p.add_option("--prefix", type="int",
help="Find rep id for prefix of len [default: %default]")
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
clstrfile, = args
cf = ClstrFile(clstrfile)
prefix = opts.prefix
if prefix:
reads = list(cf.iter_reps_prefix(prefix=prefix))
else:
reads = list(cf.iter_reps())
nreads = len(reads)
idsfile = clstrfile.replace(".clstr", ".ids")
fw = open(idsfile, "w")
for i, name in reads:
print("\t".join(str(x) for x in (i, name)), file=fw)
logging.debug("A total of {0} unique reads written to `{1}`.".\
format(nreads, idsfile))
fw.close()
return idsfile | [
"def",
"ids",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"ids",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--prefix\"",
",",
"type",
"=",
"\"int\"",
",",
"help",
"=",
"\"Find rep id for prefix of len [default: %default]\"",
")",
"opts",
... | %prog ids cdhit.clstr
Get the representative ids from clstr file. | [
"%prog",
"ids",
"cdhit",
".",
"clstr"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/cdhit.py#L133-L165 | train | 201,108 |
tanghaibao/jcvi | jcvi/apps/cdhit.py | summary | def summary(args):
"""
%prog summary cdhit.clstr
Parse cdhit.clstr file to get distribution of cluster sizes.
"""
from jcvi.graphics.histogram import loghistogram
p = OptionParser(summary.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
clstrfile, = args
cf = ClstrFile(clstrfile)
data = list(cf.iter_sizes())
loghistogram(data, summary=True) | python | def summary(args):
"""
%prog summary cdhit.clstr
Parse cdhit.clstr file to get distribution of cluster sizes.
"""
from jcvi.graphics.histogram import loghistogram
p = OptionParser(summary.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
clstrfile, = args
cf = ClstrFile(clstrfile)
data = list(cf.iter_sizes())
loghistogram(data, summary=True) | [
"def",
"summary",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"graphics",
".",
"histogram",
"import",
"loghistogram",
"p",
"=",
"OptionParser",
"(",
"summary",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if... | %prog summary cdhit.clstr
Parse cdhit.clstr file to get distribution of cluster sizes. | [
"%prog",
"summary",
"cdhit",
".",
"clstr"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/cdhit.py#L168-L185 | train | 201,109 |
tanghaibao/jcvi | jcvi/apps/cdhit.py | deduplicate | def deduplicate(args):
"""
%prog deduplicate fastafile
Wraps `cd-hit-est` to remove duplicate sequences.
"""
p = OptionParser(deduplicate.__doc__)
p.set_align(pctid=96, pctcov=0)
p.add_option("--fast", default=False, action="store_true",
help="Place sequence in the first cluster")
p.add_option("--consensus", default=False, action="store_true",
help="Compute consensus sequences")
p.add_option("--reads", default=False, action="store_true",
help="Use `cd-hit-454` to deduplicate [default: %default]")
p.add_option("--samestrand", default=False, action="store_true",
help="Enforce same strand alignment")
p.set_home("cdhit")
p.set_cpus()
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
fastafile, = args
identity = opts.pctid / 100.
fastafile, qualfile = fasta([fastafile, "--seqtk"])
ocmd = "cd-hit-454" if opts.reads else "cd-hit-est"
cmd = op.join(opts.cdhit_home, ocmd)
cmd += " -c {0}".format(identity)
if ocmd == "cd-hit-est":
cmd += " -d 0" # include complete defline
if opts.samestrand:
cmd += " -r 0"
if not opts.fast:
cmd += " -g 1"
if opts.pctcov != 0:
cmd += " -aL {0} -aS {0}".format(opts.pctcov / 100.)
dd = fastafile + ".P{0}.cdhit".format(opts.pctid)
clstr = dd + ".clstr"
cmd += " -M 0 -T {0} -i {1} -o {2}".format(opts.cpus, fastafile, dd)
if need_update(fastafile, (dd, clstr)):
sh(cmd)
if opts.consensus:
cons = dd + ".consensus"
cmd = op.join(opts.cdhit_home, "cdhit-cluster-consensus")
cmd += " clustfile={0} fastafile={1} output={2} maxlen=1".\
format(clstr, fastafile, cons)
if need_update((clstr, fastafile), cons):
sh(cmd)
return dd | python | def deduplicate(args):
"""
%prog deduplicate fastafile
Wraps `cd-hit-est` to remove duplicate sequences.
"""
p = OptionParser(deduplicate.__doc__)
p.set_align(pctid=96, pctcov=0)
p.add_option("--fast", default=False, action="store_true",
help="Place sequence in the first cluster")
p.add_option("--consensus", default=False, action="store_true",
help="Compute consensus sequences")
p.add_option("--reads", default=False, action="store_true",
help="Use `cd-hit-454` to deduplicate [default: %default]")
p.add_option("--samestrand", default=False, action="store_true",
help="Enforce same strand alignment")
p.set_home("cdhit")
p.set_cpus()
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
fastafile, = args
identity = opts.pctid / 100.
fastafile, qualfile = fasta([fastafile, "--seqtk"])
ocmd = "cd-hit-454" if opts.reads else "cd-hit-est"
cmd = op.join(opts.cdhit_home, ocmd)
cmd += " -c {0}".format(identity)
if ocmd == "cd-hit-est":
cmd += " -d 0" # include complete defline
if opts.samestrand:
cmd += " -r 0"
if not opts.fast:
cmd += " -g 1"
if opts.pctcov != 0:
cmd += " -aL {0} -aS {0}".format(opts.pctcov / 100.)
dd = fastafile + ".P{0}.cdhit".format(opts.pctid)
clstr = dd + ".clstr"
cmd += " -M 0 -T {0} -i {1} -o {2}".format(opts.cpus, fastafile, dd)
if need_update(fastafile, (dd, clstr)):
sh(cmd)
if opts.consensus:
cons = dd + ".consensus"
cmd = op.join(opts.cdhit_home, "cdhit-cluster-consensus")
cmd += " clustfile={0} fastafile={1} output={2} maxlen=1".\
format(clstr, fastafile, cons)
if need_update((clstr, fastafile), cons):
sh(cmd)
return dd | [
"def",
"deduplicate",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"deduplicate",
".",
"__doc__",
")",
"p",
".",
"set_align",
"(",
"pctid",
"=",
"96",
",",
"pctcov",
"=",
"0",
")",
"p",
".",
"add_option",
"(",
"\"--fast\"",
",",
"default",
"... | %prog deduplicate fastafile
Wraps `cd-hit-est` to remove duplicate sequences. | [
"%prog",
"deduplicate",
"fastafile"
] | d2e31a77b6ade7f41f3b321febc2b4744d1cdeca | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/cdhit.py#L188-L242 | train | 201,110 |
jrspruitt/ubi_reader | ubireader/ubi/block/__init__.py | extract_blocks | def extract_blocks(ubi):
"""Get a list of UBI block objects from file
Arguments:.
Obj:ubi -- UBI object.
Returns:
Dict -- Of block objects keyed by PEB number.
"""
blocks = {}
ubi.file.seek(ubi.file.start_offset)
peb_count = 0
cur_offset = 0
bad_blocks = []
# range instead of xrange, as xrange breaks > 4GB end_offset.
for i in range(ubi.file.start_offset, ubi.file.end_offset, ubi.file.block_size):
try:
buf = ubi.file.read(ubi.file.block_size)
except Exception as e:
if settings.warn_only_block_read_errors:
error(extract_blocks, 'Error', 'PEB: %s: %s' % (ubi.first_peb_num + peb_count, str(e)))
continue
else:
error(extract_blocks, 'Fatal', 'PEB: %s: %s' % (ubi.first_peb_num + peb_count, str(e)))
if buf.startswith(UBI_EC_HDR_MAGIC):
blk = description(buf)
blk.file_offset = i
blk.peb_num = ubi.first_peb_num + peb_count
blk.size = ubi.file.block_size
blocks[blk.peb_num] = blk
peb_count += 1
log(extract_blocks, blk)
verbose_log(extract_blocks, 'file addr: %s' % (ubi.file.last_read_addr()))
ec_hdr_errors = ''
vid_hdr_errors = ''
if blk.ec_hdr.errors:
ec_hdr_errors = ','.join(blk.ec_hdr.errors)
if blk.vid_hdr and blk.vid_hdr.errors:
vid_hdr_errors = ','.join(blk.vid_hdr.errors)
if ec_hdr_errors or vid_hdr_errors:
if blk.peb_num not in bad_blocks:
bad_blocks.append(blk.peb_num)
log(extract_blocks, 'PEB: %s has possible issue EC_HDR [%s], VID_HDR [%s]' % (blk.peb_num, ec_hdr_errors, vid_hdr_errors))
verbose_display(blk)
else:
cur_offset += ubi.file.block_size
ubi.first_peb_num = cur_offset/ubi.file.block_size
ubi.file.start_offset = cur_offset
return blocks | python | def extract_blocks(ubi):
"""Get a list of UBI block objects from file
Arguments:.
Obj:ubi -- UBI object.
Returns:
Dict -- Of block objects keyed by PEB number.
"""
blocks = {}
ubi.file.seek(ubi.file.start_offset)
peb_count = 0
cur_offset = 0
bad_blocks = []
# range instead of xrange, as xrange breaks > 4GB end_offset.
for i in range(ubi.file.start_offset, ubi.file.end_offset, ubi.file.block_size):
try:
buf = ubi.file.read(ubi.file.block_size)
except Exception as e:
if settings.warn_only_block_read_errors:
error(extract_blocks, 'Error', 'PEB: %s: %s' % (ubi.first_peb_num + peb_count, str(e)))
continue
else:
error(extract_blocks, 'Fatal', 'PEB: %s: %s' % (ubi.first_peb_num + peb_count, str(e)))
if buf.startswith(UBI_EC_HDR_MAGIC):
blk = description(buf)
blk.file_offset = i
blk.peb_num = ubi.first_peb_num + peb_count
blk.size = ubi.file.block_size
blocks[blk.peb_num] = blk
peb_count += 1
log(extract_blocks, blk)
verbose_log(extract_blocks, 'file addr: %s' % (ubi.file.last_read_addr()))
ec_hdr_errors = ''
vid_hdr_errors = ''
if blk.ec_hdr.errors:
ec_hdr_errors = ','.join(blk.ec_hdr.errors)
if blk.vid_hdr and blk.vid_hdr.errors:
vid_hdr_errors = ','.join(blk.vid_hdr.errors)
if ec_hdr_errors or vid_hdr_errors:
if blk.peb_num not in bad_blocks:
bad_blocks.append(blk.peb_num)
log(extract_blocks, 'PEB: %s has possible issue EC_HDR [%s], VID_HDR [%s]' % (blk.peb_num, ec_hdr_errors, vid_hdr_errors))
verbose_display(blk)
else:
cur_offset += ubi.file.block_size
ubi.first_peb_num = cur_offset/ubi.file.block_size
ubi.file.start_offset = cur_offset
return blocks | [
"def",
"extract_blocks",
"(",
"ubi",
")",
":",
"blocks",
"=",
"{",
"}",
"ubi",
".",
"file",
".",
"seek",
"(",
"ubi",
".",
"file",
".",
"start_offset",
")",
"peb_count",
"=",
"0",
"cur_offset",
"=",
"0",
"bad_blocks",
"=",
"[",
"]",
"# range instead of ... | Get a list of UBI block objects from file
Arguments:.
Obj:ubi -- UBI object.
Returns:
Dict -- Of block objects keyed by PEB number. | [
"Get",
"a",
"list",
"of",
"UBI",
"block",
"objects",
"from",
"file"
] | 7079dd380c1c9896bced30d6d34e8780b9181597 | https://github.com/jrspruitt/ubi_reader/blob/7079dd380c1c9896bced30d6d34e8780b9181597/ubireader/ubi/block/__init__.py#L105-L162 | train | 201,111 |
jrspruitt/ubi_reader | ubireader/ubi/block/sort.py | by_image_seq | def by_image_seq(blocks, image_seq):
"""Filter blocks to return only those associated with the provided image_seq number.
Argument:
List:blocks -- List of block objects to sort.
Int:image_seq -- image_seq number found in ec_hdr.
Returns:
List -- List of block indexes matching image_seq number.
"""
return list(filter(lambda block: blocks[block].ec_hdr.image_seq == image_seq, blocks)) | python | def by_image_seq(blocks, image_seq):
"""Filter blocks to return only those associated with the provided image_seq number.
Argument:
List:blocks -- List of block objects to sort.
Int:image_seq -- image_seq number found in ec_hdr.
Returns:
List -- List of block indexes matching image_seq number.
"""
return list(filter(lambda block: blocks[block].ec_hdr.image_seq == image_seq, blocks)) | [
"def",
"by_image_seq",
"(",
"blocks",
",",
"image_seq",
")",
":",
"return",
"list",
"(",
"filter",
"(",
"lambda",
"block",
":",
"blocks",
"[",
"block",
"]",
".",
"ec_hdr",
".",
"image_seq",
"==",
"image_seq",
",",
"blocks",
")",
")"
] | Filter blocks to return only those associated with the provided image_seq number.
Argument:
List:blocks -- List of block objects to sort.
Int:image_seq -- image_seq number found in ec_hdr.
Returns:
List -- List of block indexes matching image_seq number. | [
"Filter",
"blocks",
"to",
"return",
"only",
"those",
"associated",
"with",
"the",
"provided",
"image_seq",
"number",
"."
] | 7079dd380c1c9896bced30d6d34e8780b9181597 | https://github.com/jrspruitt/ubi_reader/blob/7079dd380c1c9896bced30d6d34e8780b9181597/ubireader/ubi/block/sort.py#L20-L30 | train | 201,112 |
jrspruitt/ubi_reader | ubireader/ubi/block/sort.py | by_vol_id | def by_vol_id(blocks, slist=None):
"""Sort blocks by volume id
Arguments:
Obj:blocks -- List of block objects.
List:slist -- (optional) List of block indexes.
Return:
Dict -- blocks grouped in lists with dict key as volume id.
"""
vol_blocks = {}
# sort block by volume
# not reliable with multiple partitions (fifo)
for i in blocks:
if slist and i not in slist:
continue
elif not blocks[i].is_valid:
continue
if blocks[i].vid_hdr.vol_id not in vol_blocks:
vol_blocks[blocks[i].vid_hdr.vol_id] = []
vol_blocks[blocks[i].vid_hdr.vol_id].append(blocks[i].peb_num)
return vol_blocks | python | def by_vol_id(blocks, slist=None):
"""Sort blocks by volume id
Arguments:
Obj:blocks -- List of block objects.
List:slist -- (optional) List of block indexes.
Return:
Dict -- blocks grouped in lists with dict key as volume id.
"""
vol_blocks = {}
# sort block by volume
# not reliable with multiple partitions (fifo)
for i in blocks:
if slist and i not in slist:
continue
elif not blocks[i].is_valid:
continue
if blocks[i].vid_hdr.vol_id not in vol_blocks:
vol_blocks[blocks[i].vid_hdr.vol_id] = []
vol_blocks[blocks[i].vid_hdr.vol_id].append(blocks[i].peb_num)
return vol_blocks | [
"def",
"by_vol_id",
"(",
"blocks",
",",
"slist",
"=",
"None",
")",
":",
"vol_blocks",
"=",
"{",
"}",
"# sort block by volume",
"# not reliable with multiple partitions (fifo)",
"for",
"i",
"in",
"blocks",
":",
"if",
"slist",
"and",
"i",
"not",
"in",
"slist",
"... | Sort blocks by volume id
Arguments:
Obj:blocks -- List of block objects.
List:slist -- (optional) List of block indexes.
Return:
Dict -- blocks grouped in lists with dict key as volume id. | [
"Sort",
"blocks",
"by",
"volume",
"id"
] | 7079dd380c1c9896bced30d6d34e8780b9181597 | https://github.com/jrspruitt/ubi_reader/blob/7079dd380c1c9896bced30d6d34e8780b9181597/ubireader/ubi/block/sort.py#L55-L82 | train | 201,113 |
jrspruitt/ubi_reader | ubireader/ubi/block/sort.py | by_type | def by_type(blocks, slist=None):
"""Sort blocks into layout, internal volume, data or unknown
Arguments:
Obj:blocks -- List of block objects.
List:slist -- (optional) List of block indexes.
Returns:
List:layout -- List of block indexes of blocks containing the
volume table records.
List:data -- List of block indexes containing filesystem data.
List:int_vol -- List of block indexes containing volume ids
greater than UBI_INTERNAL_VOL_START that are not
layout volumes.
List:unknown -- List of block indexes of blocks that failed validation
of crc in ed_hdr or vid_hdr.
"""
layout = []
data = []
int_vol = []
unknown = []
for i in blocks:
if slist and i not in slist:
continue
if blocks[i].is_vtbl and blocks[i].is_valid:
layout.append(i)
elif blocks[i].is_internal_vol and blocks[i].is_valid:
int_vol.append(i)
elif blocks[i].is_valid:
data.append(i)
else:
unknown.append(i)
return layout, data, int_vol, unknown | python | def by_type(blocks, slist=None):
"""Sort blocks into layout, internal volume, data or unknown
Arguments:
Obj:blocks -- List of block objects.
List:slist -- (optional) List of block indexes.
Returns:
List:layout -- List of block indexes of blocks containing the
volume table records.
List:data -- List of block indexes containing filesystem data.
List:int_vol -- List of block indexes containing volume ids
greater than UBI_INTERNAL_VOL_START that are not
layout volumes.
List:unknown -- List of block indexes of blocks that failed validation
of crc in ed_hdr or vid_hdr.
"""
layout = []
data = []
int_vol = []
unknown = []
for i in blocks:
if slist and i not in slist:
continue
if blocks[i].is_vtbl and blocks[i].is_valid:
layout.append(i)
elif blocks[i].is_internal_vol and blocks[i].is_valid:
int_vol.append(i)
elif blocks[i].is_valid:
data.append(i)
else:
unknown.append(i)
return layout, data, int_vol, unknown | [
"def",
"by_type",
"(",
"blocks",
",",
"slist",
"=",
"None",
")",
":",
"layout",
"=",
"[",
"]",
"data",
"=",
"[",
"]",
"int_vol",
"=",
"[",
"]",
"unknown",
"=",
"[",
"]",
"for",
"i",
"in",
"blocks",
":",
"if",
"slist",
"and",
"i",
"not",
"in",
... | Sort blocks into layout, internal volume, data or unknown
Arguments:
Obj:blocks -- List of block objects.
List:slist -- (optional) List of block indexes.
Returns:
List:layout -- List of block indexes of blocks containing the
volume table records.
List:data -- List of block indexes containing filesystem data.
List:int_vol -- List of block indexes containing volume ids
greater than UBI_INTERNAL_VOL_START that are not
layout volumes.
List:unknown -- List of block indexes of blocks that failed validation
of crc in ed_hdr or vid_hdr. | [
"Sort",
"blocks",
"into",
"layout",
"internal",
"volume",
"data",
"or",
"unknown"
] | 7079dd380c1c9896bced30d6d34e8780b9181597 | https://github.com/jrspruitt/ubi_reader/blob/7079dd380c1c9896bced30d6d34e8780b9181597/ubireader/ubi/block/sort.py#L84-L123 | train | 201,114 |
jrspruitt/ubi_reader | ubireader/ubi/block/layout.py | get_newest | def get_newest(blocks, layout_blocks):
"""Filter out old layout blocks from list
Arguments:
List:blocks -- List of block objects
List:layout_blocks -- List of layout block indexes
Returns:
List -- Newest layout blocks in list
"""
layout_temp = list(layout_blocks)
for i in range(0, len(layout_temp)):
for k in range(0, len(layout_blocks)):
if blocks[layout_temp[i]].ec_hdr.image_seq != blocks[layout_blocks[k]].ec_hdr.image_seq:
continue
if blocks[layout_temp[i]].leb_num != blocks[layout_blocks[k]].leb_num:
continue
if blocks[layout_temp[i]].vid_hdr.sqnum > blocks[layout_blocks[k]].vid_hdr.sqnum:
del layout_blocks[k]
break
return layout_blocks | python | def get_newest(blocks, layout_blocks):
"""Filter out old layout blocks from list
Arguments:
List:blocks -- List of block objects
List:layout_blocks -- List of layout block indexes
Returns:
List -- Newest layout blocks in list
"""
layout_temp = list(layout_blocks)
for i in range(0, len(layout_temp)):
for k in range(0, len(layout_blocks)):
if blocks[layout_temp[i]].ec_hdr.image_seq != blocks[layout_blocks[k]].ec_hdr.image_seq:
continue
if blocks[layout_temp[i]].leb_num != blocks[layout_blocks[k]].leb_num:
continue
if blocks[layout_temp[i]].vid_hdr.sqnum > blocks[layout_blocks[k]].vid_hdr.sqnum:
del layout_blocks[k]
break
return layout_blocks | [
"def",
"get_newest",
"(",
"blocks",
",",
"layout_blocks",
")",
":",
"layout_temp",
"=",
"list",
"(",
"layout_blocks",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"layout_temp",
")",
")",
":",
"for",
"k",
"in",
"range",
"(",
"0",
",",
... | Filter out old layout blocks from list
Arguments:
List:blocks -- List of block objects
List:layout_blocks -- List of layout block indexes
Returns:
List -- Newest layout blocks in list | [
"Filter",
"out",
"old",
"layout",
"blocks",
"from",
"list"
] | 7079dd380c1c9896bced30d6d34e8780b9181597 | https://github.com/jrspruitt/ubi_reader/blob/7079dd380c1c9896bced30d6d34e8780b9181597/ubireader/ubi/block/layout.py#L23-L47 | train | 201,115 |
jrspruitt/ubi_reader | ubireader/ubi/block/layout.py | group_pairs | def group_pairs(blocks, layout_blocks_list):
"""Sort a list of layout blocks into pairs
Arguments:
List:blocks -- List of block objects
List:layout_blocks -- List of layout block indexes
Returns:
List -- Layout block pair indexes grouped in a list
"""
image_dict={}
for block_id in layout_blocks_list:
image_seq=blocks[block_id].ec_hdr.image_seq
if image_seq not in image_dict:
image_dict[image_seq]=[block_id]
else:
image_dict[image_seq].append(block_id)
log(group_pairs, 'Layout blocks found at PEBs: %s' % list(image_dict.values()))
return list(image_dict.values()) | python | def group_pairs(blocks, layout_blocks_list):
"""Sort a list of layout blocks into pairs
Arguments:
List:blocks -- List of block objects
List:layout_blocks -- List of layout block indexes
Returns:
List -- Layout block pair indexes grouped in a list
"""
image_dict={}
for block_id in layout_blocks_list:
image_seq=blocks[block_id].ec_hdr.image_seq
if image_seq not in image_dict:
image_dict[image_seq]=[block_id]
else:
image_dict[image_seq].append(block_id)
log(group_pairs, 'Layout blocks found at PEBs: %s' % list(image_dict.values()))
return list(image_dict.values()) | [
"def",
"group_pairs",
"(",
"blocks",
",",
"layout_blocks_list",
")",
":",
"image_dict",
"=",
"{",
"}",
"for",
"block_id",
"in",
"layout_blocks_list",
":",
"image_seq",
"=",
"blocks",
"[",
"block_id",
"]",
".",
"ec_hdr",
".",
"image_seq",
"if",
"image_seq",
"... | Sort a list of layout blocks into pairs
Arguments:
List:blocks -- List of block objects
List:layout_blocks -- List of layout block indexes
Returns:
List -- Layout block pair indexes grouped in a list | [
"Sort",
"a",
"list",
"of",
"layout",
"blocks",
"into",
"pairs"
] | 7079dd380c1c9896bced30d6d34e8780b9181597 | https://github.com/jrspruitt/ubi_reader/blob/7079dd380c1c9896bced30d6d34e8780b9181597/ubireader/ubi/block/layout.py#L50-L71 | train | 201,116 |
jrspruitt/ubi_reader | ubireader/ubi/block/layout.py | associate_blocks | def associate_blocks(blocks, layout_pairs, start_peb_num):
"""Group block indexes with appropriate layout pairs
Arguments:
List:blocks -- List of block objects
List:layout_pairs -- List of grouped layout blocks
Int:start_peb_num -- Number of the PEB to start from.
Returns:
List -- Layout block pairs grouped with associated block ranges.
"""
seq_blocks = []
for layout_pair in layout_pairs:
seq_blocks = sort.by_image_seq(blocks, blocks[layout_pair[0]].ec_hdr.image_seq)
layout_pair.append(seq_blocks)
return layout_pairs | python | def associate_blocks(blocks, layout_pairs, start_peb_num):
"""Group block indexes with appropriate layout pairs
Arguments:
List:blocks -- List of block objects
List:layout_pairs -- List of grouped layout blocks
Int:start_peb_num -- Number of the PEB to start from.
Returns:
List -- Layout block pairs grouped with associated block ranges.
"""
seq_blocks = []
for layout_pair in layout_pairs:
seq_blocks = sort.by_image_seq(blocks, blocks[layout_pair[0]].ec_hdr.image_seq)
layout_pair.append(seq_blocks)
return layout_pairs | [
"def",
"associate_blocks",
"(",
"blocks",
",",
"layout_pairs",
",",
"start_peb_num",
")",
":",
"seq_blocks",
"=",
"[",
"]",
"for",
"layout_pair",
"in",
"layout_pairs",
":",
"seq_blocks",
"=",
"sort",
".",
"by_image_seq",
"(",
"blocks",
",",
"blocks",
"[",
"l... | Group block indexes with appropriate layout pairs
Arguments:
List:blocks -- List of block objects
List:layout_pairs -- List of grouped layout blocks
Int:start_peb_num -- Number of the PEB to start from.
Returns:
List -- Layout block pairs grouped with associated block ranges. | [
"Group",
"block",
"indexes",
"with",
"appropriate",
"layout",
"pairs"
] | 7079dd380c1c9896bced30d6d34e8780b9181597 | https://github.com/jrspruitt/ubi_reader/blob/7079dd380c1c9896bced30d6d34e8780b9181597/ubireader/ubi/block/layout.py#L74-L91 | train | 201,117 |
jrspruitt/ubi_reader | ubireader/ubi/volume.py | get_volumes | def get_volumes(blocks, layout_info):
"""Get a list of UBI volume objects from list of blocks
Arguments:
List:blocks -- List of layout block objects
List:layout_info -- Layout info (indexes of layout blocks and
associated data blocks.)
Returns:
Dict -- Of Volume objects by volume name, including any
relevant blocks.
"""
volumes = {}
vol_blocks_lists = sort.by_vol_id(blocks, layout_info[2])
for vol_rec in blocks[layout_info[0]].vtbl_recs:
vol_name = vol_rec.name.strip(b'\x00').decode('utf-8')
if vol_rec.rec_index not in vol_blocks_lists:
vol_blocks_lists[vol_rec.rec_index] = []
volumes[vol_name] = description(vol_rec.rec_index, vol_rec, vol_blocks_lists[vol_rec.rec_index])
return volumes | python | def get_volumes(blocks, layout_info):
"""Get a list of UBI volume objects from list of blocks
Arguments:
List:blocks -- List of layout block objects
List:layout_info -- Layout info (indexes of layout blocks and
associated data blocks.)
Returns:
Dict -- Of Volume objects by volume name, including any
relevant blocks.
"""
volumes = {}
vol_blocks_lists = sort.by_vol_id(blocks, layout_info[2])
for vol_rec in blocks[layout_info[0]].vtbl_recs:
vol_name = vol_rec.name.strip(b'\x00').decode('utf-8')
if vol_rec.rec_index not in vol_blocks_lists:
vol_blocks_lists[vol_rec.rec_index] = []
volumes[vol_name] = description(vol_rec.rec_index, vol_rec, vol_blocks_lists[vol_rec.rec_index])
return volumes | [
"def",
"get_volumes",
"(",
"blocks",
",",
"layout_info",
")",
":",
"volumes",
"=",
"{",
"}",
"vol_blocks_lists",
"=",
"sort",
".",
"by_vol_id",
"(",
"blocks",
",",
"layout_info",
"[",
"2",
"]",
")",
"for",
"vol_rec",
"in",
"blocks",
"[",
"layout_info",
"... | Get a list of UBI volume objects from list of blocks
Arguments:
List:blocks -- List of layout block objects
List:layout_info -- Layout info (indexes of layout blocks and
associated data blocks.)
Returns:
Dict -- Of Volume objects by volume name, including any
relevant blocks. | [
"Get",
"a",
"list",
"of",
"UBI",
"volume",
"objects",
"from",
"list",
"of",
"blocks"
] | 7079dd380c1c9896bced30d6d34e8780b9181597 | https://github.com/jrspruitt/ubi_reader/blob/7079dd380c1c9896bced30d6d34e8780b9181597/ubireader/ubi/volume.py#L98-L120 | train | 201,118 |
jrspruitt/ubi_reader | ubireader/ubifs/misc.py | parse_key | def parse_key(key):
"""Parse node key
Arguments:
Str:key -- Hex string literal of node key.
Returns:
Int:key_type -- Type of key, data, ino, dent, etc.
Int:ino_num -- Inode number.
Int:khash -- Key hash.
"""
hkey, lkey = struct.unpack('<II',key[0:UBIFS_SK_LEN])
ino_num = hkey & UBIFS_S_KEY_HASH_MASK
key_type = lkey >> UBIFS_S_KEY_BLOCK_BITS
khash = lkey
#if key_type < UBIFS_KEY_TYPES_CNT:
return {'type':key_type, 'ino_num':ino_num, 'khash': khash} | python | def parse_key(key):
"""Parse node key
Arguments:
Str:key -- Hex string literal of node key.
Returns:
Int:key_type -- Type of key, data, ino, dent, etc.
Int:ino_num -- Inode number.
Int:khash -- Key hash.
"""
hkey, lkey = struct.unpack('<II',key[0:UBIFS_SK_LEN])
ino_num = hkey & UBIFS_S_KEY_HASH_MASK
key_type = lkey >> UBIFS_S_KEY_BLOCK_BITS
khash = lkey
#if key_type < UBIFS_KEY_TYPES_CNT:
return {'type':key_type, 'ino_num':ino_num, 'khash': khash} | [
"def",
"parse_key",
"(",
"key",
")",
":",
"hkey",
",",
"lkey",
"=",
"struct",
".",
"unpack",
"(",
"'<II'",
",",
"key",
"[",
"0",
":",
"UBIFS_SK_LEN",
"]",
")",
"ino_num",
"=",
"hkey",
"&",
"UBIFS_S_KEY_HASH_MASK",
"key_type",
"=",
"lkey",
">>",
"UBIFS_... | Parse node key
Arguments:
Str:key -- Hex string literal of node key.
Returns:
Int:key_type -- Type of key, data, ino, dent, etc.
Int:ino_num -- Inode number.
Int:khash -- Key hash. | [
"Parse",
"node",
"key"
] | 7079dd380c1c9896bced30d6d34e8780b9181597 | https://github.com/jrspruitt/ubi_reader/blob/7079dd380c1c9896bced30d6d34e8780b9181597/ubireader/ubifs/misc.py#L31-L48 | train | 201,119 |
jrspruitt/ubi_reader | ubireader/ubifs/misc.py | decompress | def decompress(ctype, unc_len, data):
"""Decompress data.
Arguments:
Int:ctype -- Compression type LZO, ZLIB (*currently unused*).
Int:unc_len -- Uncompressed data lenth.
Str:data -- Data to be uncompessed.
Returns:
Uncompressed Data.
"""
if ctype == UBIFS_COMPR_LZO:
try:
return lzo.decompress(b''.join((b'\xf0', struct.pack('>I', unc_len), data)))
except Exception as e:
error(decompress, 'Warn', 'LZO Error: %s' % e)
elif ctype == UBIFS_COMPR_ZLIB:
try:
return zlib.decompress(data, -11)
except Exception as e:
error(decompress, 'Warn', 'ZLib Error: %s' % e)
else:
return data | python | def decompress(ctype, unc_len, data):
"""Decompress data.
Arguments:
Int:ctype -- Compression type LZO, ZLIB (*currently unused*).
Int:unc_len -- Uncompressed data lenth.
Str:data -- Data to be uncompessed.
Returns:
Uncompressed Data.
"""
if ctype == UBIFS_COMPR_LZO:
try:
return lzo.decompress(b''.join((b'\xf0', struct.pack('>I', unc_len), data)))
except Exception as e:
error(decompress, 'Warn', 'LZO Error: %s' % e)
elif ctype == UBIFS_COMPR_ZLIB:
try:
return zlib.decompress(data, -11)
except Exception as e:
error(decompress, 'Warn', 'ZLib Error: %s' % e)
else:
return data | [
"def",
"decompress",
"(",
"ctype",
",",
"unc_len",
",",
"data",
")",
":",
"if",
"ctype",
"==",
"UBIFS_COMPR_LZO",
":",
"try",
":",
"return",
"lzo",
".",
"decompress",
"(",
"b''",
".",
"join",
"(",
"(",
"b'\\xf0'",
",",
"struct",
".",
"pack",
"(",
"'>... | Decompress data.
Arguments:
Int:ctype -- Compression type LZO, ZLIB (*currently unused*).
Int:unc_len -- Uncompressed data lenth.
Str:data -- Data to be uncompessed.
Returns:
Uncompressed Data. | [
"Decompress",
"data",
"."
] | 7079dd380c1c9896bced30d6d34e8780b9181597 | https://github.com/jrspruitt/ubi_reader/blob/7079dd380c1c9896bced30d6d34e8780b9181597/ubireader/ubifs/misc.py#L51-L73 | train | 201,120 |
jrspruitt/ubi_reader | ubireader/utils.py | guess_leb_size | def guess_leb_size(path):
"""Get LEB size from superblock
Arguments:
Str:path -- Path to file.
Returns:
Int -- LEB size.
Searches file for superblock and retrieves leb size.
"""
f = open(path, 'rb')
f.seek(0,2)
file_size = f.tell()+1
f.seek(0)
block_size = None
for _ in range(0, file_size, FILE_CHUNK_SZ):
buf = f.read(FILE_CHUNK_SZ)
for m in re.finditer(UBIFS_NODE_MAGIC, buf):
start = m.start()
chdr = nodes.common_hdr(buf[start:start+UBIFS_COMMON_HDR_SZ])
if chdr and chdr.node_type == UBIFS_SB_NODE:
sb_start = start + UBIFS_COMMON_HDR_SZ
sb_end = sb_start + UBIFS_SB_NODE_SZ
if chdr.len != len(buf[sb_start:sb_end]):
f.seek(sb_start)
buf = f.read(UBIFS_SB_NODE_SZ)
else:
buf = buf[sb_start:sb_end]
sbn = nodes.sb_node(buf)
block_size = sbn.leb_size
f.close()
return block_size
f.close()
return block_size | python | def guess_leb_size(path):
"""Get LEB size from superblock
Arguments:
Str:path -- Path to file.
Returns:
Int -- LEB size.
Searches file for superblock and retrieves leb size.
"""
f = open(path, 'rb')
f.seek(0,2)
file_size = f.tell()+1
f.seek(0)
block_size = None
for _ in range(0, file_size, FILE_CHUNK_SZ):
buf = f.read(FILE_CHUNK_SZ)
for m in re.finditer(UBIFS_NODE_MAGIC, buf):
start = m.start()
chdr = nodes.common_hdr(buf[start:start+UBIFS_COMMON_HDR_SZ])
if chdr and chdr.node_type == UBIFS_SB_NODE:
sb_start = start + UBIFS_COMMON_HDR_SZ
sb_end = sb_start + UBIFS_SB_NODE_SZ
if chdr.len != len(buf[sb_start:sb_end]):
f.seek(sb_start)
buf = f.read(UBIFS_SB_NODE_SZ)
else:
buf = buf[sb_start:sb_end]
sbn = nodes.sb_node(buf)
block_size = sbn.leb_size
f.close()
return block_size
f.close()
return block_size | [
"def",
"guess_leb_size",
"(",
"path",
")",
":",
"f",
"=",
"open",
"(",
"path",
",",
"'rb'",
")",
"f",
".",
"seek",
"(",
"0",
",",
"2",
")",
"file_size",
"=",
"f",
".",
"tell",
"(",
")",
"+",
"1",
"f",
".",
"seek",
"(",
"0",
")",
"block_size",... | Get LEB size from superblock
Arguments:
Str:path -- Path to file.
Returns:
Int -- LEB size.
Searches file for superblock and retrieves leb size. | [
"Get",
"LEB",
"size",
"from",
"superblock"
] | 7079dd380c1c9896bced30d6d34e8780b9181597 | https://github.com/jrspruitt/ubi_reader/blob/7079dd380c1c9896bced30d6d34e8780b9181597/ubireader/utils.py#L86-L127 | train | 201,121 |
jrspruitt/ubi_reader | ubireader/utils.py | guess_peb_size | def guess_peb_size(path):
"""Determine the most likely block size
Arguments:
Str:path -- Path to file.
Returns:
Int -- PEB size.
Searches file for Magic Number, picks most
common length between them.
"""
file_offset = 0
offsets = []
f = open(path, 'rb')
f.seek(0,2)
file_size = f.tell()+1
f.seek(0)
for _ in range(0, file_size, FILE_CHUNK_SZ):
buf = f.read(FILE_CHUNK_SZ)
for m in re.finditer(UBI_EC_HDR_MAGIC, buf):
start = m.start()
if not file_offset:
file_offset = start
idx = start
else:
idx = start+file_offset
offsets.append(idx)
file_offset += FILE_CHUNK_SZ
f.close()
occurances = {}
for i in range(0, len(offsets)):
try:
diff = offsets[i] - offsets[i-1]
except:
diff = offsets[i]
if diff not in occurances:
occurances[diff] = 0
occurances[diff] += 1
most_frequent = 0
block_size = None
for offset in occurances:
if occurances[offset] > most_frequent:
most_frequent = occurances[offset]
block_size = offset
return block_size | python | def guess_peb_size(path):
"""Determine the most likely block size
Arguments:
Str:path -- Path to file.
Returns:
Int -- PEB size.
Searches file for Magic Number, picks most
common length between them.
"""
file_offset = 0
offsets = []
f = open(path, 'rb')
f.seek(0,2)
file_size = f.tell()+1
f.seek(0)
for _ in range(0, file_size, FILE_CHUNK_SZ):
buf = f.read(FILE_CHUNK_SZ)
for m in re.finditer(UBI_EC_HDR_MAGIC, buf):
start = m.start()
if not file_offset:
file_offset = start
idx = start
else:
idx = start+file_offset
offsets.append(idx)
file_offset += FILE_CHUNK_SZ
f.close()
occurances = {}
for i in range(0, len(offsets)):
try:
diff = offsets[i] - offsets[i-1]
except:
diff = offsets[i]
if diff not in occurances:
occurances[diff] = 0
occurances[diff] += 1
most_frequent = 0
block_size = None
for offset in occurances:
if occurances[offset] > most_frequent:
most_frequent = occurances[offset]
block_size = offset
return block_size | [
"def",
"guess_peb_size",
"(",
"path",
")",
":",
"file_offset",
"=",
"0",
"offsets",
"=",
"[",
"]",
"f",
"=",
"open",
"(",
"path",
",",
"'rb'",
")",
"f",
".",
"seek",
"(",
"0",
",",
"2",
")",
"file_size",
"=",
"f",
".",
"tell",
"(",
")",
"+",
... | Determine the most likely block size
Arguments:
Str:path -- Path to file.
Returns:
Int -- PEB size.
Searches file for Magic Number, picks most
common length between them. | [
"Determine",
"the",
"most",
"likely",
"block",
"size"
] | 7079dd380c1c9896bced30d6d34e8780b9181597 | https://github.com/jrspruitt/ubi_reader/blob/7079dd380c1c9896bced30d6d34e8780b9181597/ubireader/utils.py#L131-L186 | train | 201,122 |
michaelhelmick/lassie | lassie/utils.py | convert_to_int | def convert_to_int(value):
"""Attempts to convert a specified value to an integer
:param value: Content to be converted into an integer
:type value: string or int
"""
if not value:
return None
# Apart from numbers also accept values that end with px
if isinstance(value, str):
value = value.strip(' px')
try:
return int(value)
except (TypeError, ValueError):
return None | python | def convert_to_int(value):
"""Attempts to convert a specified value to an integer
:param value: Content to be converted into an integer
:type value: string or int
"""
if not value:
return None
# Apart from numbers also accept values that end with px
if isinstance(value, str):
value = value.strip(' px')
try:
return int(value)
except (TypeError, ValueError):
return None | [
"def",
"convert_to_int",
"(",
"value",
")",
":",
"if",
"not",
"value",
":",
"return",
"None",
"# Apart from numbers also accept values that end with px",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"value",
"=",
"value",
".",
"strip",
"(",
"' px'",
... | Attempts to convert a specified value to an integer
:param value: Content to be converted into an integer
:type value: string or int | [
"Attempts",
"to",
"convert",
"a",
"specified",
"value",
"to",
"an",
"integer"
] | b929f78d7e545cff5fb42eb5edfcaf396456f1ee | https://github.com/michaelhelmick/lassie/blob/b929f78d7e545cff5fb42eb5edfcaf396456f1ee/lassie/utils.py#L31-L48 | train | 201,123 |
michaelhelmick/lassie | lassie/filters/oembed/providers.py | parse_oembed_data | def parse_oembed_data(oembed_data, data):
"""Parse OEmbed resposne data to inject into lassie's response dict.
:param oembed_data: OEmbed response data.
:type oembed_data: dict
:param data: Refrence to data variable being updated.
:type data: dict
"""
data.update({
'oembed': oembed_data,
})
_type = oembed_data.get('type')
provider_name = oembed_data.get('provider_name')
if not _type:
return data
if oembed_data.get('title'):
data.update({
'title': oembed_data.get('title'),
})
if _type == 'video':
try:
item = {
'width': convert_to_int(oembed_data.get('width')),
'height': convert_to_int(oembed_data.get('height'))
}
if provider_name in ['YouTube', ]:
item['src'] = HYPERLINK_PATTERN.search(oembed_data.get('html')).group(0)
data['videos'].append(item)
except Exception:
pass
if oembed_data.get('thumbnail_url'):
item = {
'width': convert_to_int(oembed_data.get('thumbnail_width')),
'height': convert_to_int(oembed_data.get('thumbnail_height')),
'src': oembed_data.get('thumbnail_url')
}
data['images'].append(item)
return data | python | def parse_oembed_data(oembed_data, data):
"""Parse OEmbed resposne data to inject into lassie's response dict.
:param oembed_data: OEmbed response data.
:type oembed_data: dict
:param data: Refrence to data variable being updated.
:type data: dict
"""
data.update({
'oembed': oembed_data,
})
_type = oembed_data.get('type')
provider_name = oembed_data.get('provider_name')
if not _type:
return data
if oembed_data.get('title'):
data.update({
'title': oembed_data.get('title'),
})
if _type == 'video':
try:
item = {
'width': convert_to_int(oembed_data.get('width')),
'height': convert_to_int(oembed_data.get('height'))
}
if provider_name in ['YouTube', ]:
item['src'] = HYPERLINK_PATTERN.search(oembed_data.get('html')).group(0)
data['videos'].append(item)
except Exception:
pass
if oembed_data.get('thumbnail_url'):
item = {
'width': convert_to_int(oembed_data.get('thumbnail_width')),
'height': convert_to_int(oembed_data.get('thumbnail_height')),
'src': oembed_data.get('thumbnail_url')
}
data['images'].append(item)
return data | [
"def",
"parse_oembed_data",
"(",
"oembed_data",
",",
"data",
")",
":",
"data",
".",
"update",
"(",
"{",
"'oembed'",
":",
"oembed_data",
",",
"}",
")",
"_type",
"=",
"oembed_data",
".",
"get",
"(",
"'type'",
")",
"provider_name",
"=",
"oembed_data",
".",
... | Parse OEmbed resposne data to inject into lassie's response dict.
:param oembed_data: OEmbed response data.
:type oembed_data: dict
:param data: Refrence to data variable being updated.
:type data: dict | [
"Parse",
"OEmbed",
"resposne",
"data",
"to",
"inject",
"into",
"lassie",
"s",
"response",
"dict",
"."
] | b929f78d7e545cff5fb42eb5edfcaf396456f1ee | https://github.com/michaelhelmick/lassie/blob/b929f78d7e545cff5fb42eb5edfcaf396456f1ee/lassie/filters/oembed/providers.py#L39-L83 | train | 201,124 |
michaelhelmick/lassie | lassie/core.py | Lassie._filter_meta_data | def _filter_meta_data(self, source, soup, data, url=None):
"""This method filters the web page content for meta tags that match patterns given in the ``FILTER_MAPS``
:param source: The key of the meta dictionary in ``FILTER_MAPS['meta']``
:type source: string
:param soup: BeautifulSoup instance to find meta tags
:type soup: instance
:param data: The response dictionary to manipulate
:type data: (dict)
"""
meta = FILTER_MAPS['meta'][source]
meta_map = meta['map']
html = soup.find_all('meta', {meta['key']: meta['pattern']})
image = {}
video = {}
for line in html:
prop = line.get(meta['key'])
value = line.get('content')
_prop = meta_map.get(prop)
if prop in meta_map and _prop and not data.get(_prop):
# this could be bad in cases where any values that the property
# is mapped up to (i.e. "src", "type", etc) are found in ``data``
# TODO: Figure out a smoother way to prevent conflicts ^^^^^^^^
image_prop = meta['image_key']
video_prop = meta['video_key']
if prop.startswith((image_prop, video_prop)) and \
prop.endswith(('width', 'height')):
if prop.endswith(('width', 'height')):
value = convert_to_int(value)
if meta_map[prop] == 'locale':
locale = normalize_locale(value)
if locale:
data['locale'] = locale
if prop == 'keywords':
if isinstance(value, str):
value = [v.strip() for v in value.split(',')]
else:
value = []
if image_prop and prop.startswith(image_prop) and value:
# og:image URLs can be relative
if prop == 'og:image' and url:
value = urljoin(url, value)
image[meta_map[prop]] = value
elif video_prop and prop.startswith(video_prop) and value:
video[meta_map[prop]] = value
else:
data[meta_map[prop]] = value
if image:
image['type'] = image_prop
data['images'].append(image)
if video:
data['videos'].append(video) | python | def _filter_meta_data(self, source, soup, data, url=None):
"""This method filters the web page content for meta tags that match patterns given in the ``FILTER_MAPS``
:param source: The key of the meta dictionary in ``FILTER_MAPS['meta']``
:type source: string
:param soup: BeautifulSoup instance to find meta tags
:type soup: instance
:param data: The response dictionary to manipulate
:type data: (dict)
"""
meta = FILTER_MAPS['meta'][source]
meta_map = meta['map']
html = soup.find_all('meta', {meta['key']: meta['pattern']})
image = {}
video = {}
for line in html:
prop = line.get(meta['key'])
value = line.get('content')
_prop = meta_map.get(prop)
if prop in meta_map and _prop and not data.get(_prop):
# this could be bad in cases where any values that the property
# is mapped up to (i.e. "src", "type", etc) are found in ``data``
# TODO: Figure out a smoother way to prevent conflicts ^^^^^^^^
image_prop = meta['image_key']
video_prop = meta['video_key']
if prop.startswith((image_prop, video_prop)) and \
prop.endswith(('width', 'height')):
if prop.endswith(('width', 'height')):
value = convert_to_int(value)
if meta_map[prop] == 'locale':
locale = normalize_locale(value)
if locale:
data['locale'] = locale
if prop == 'keywords':
if isinstance(value, str):
value = [v.strip() for v in value.split(',')]
else:
value = []
if image_prop and prop.startswith(image_prop) and value:
# og:image URLs can be relative
if prop == 'og:image' and url:
value = urljoin(url, value)
image[meta_map[prop]] = value
elif video_prop and prop.startswith(video_prop) and value:
video[meta_map[prop]] = value
else:
data[meta_map[prop]] = value
if image:
image['type'] = image_prop
data['images'].append(image)
if video:
data['videos'].append(video) | [
"def",
"_filter_meta_data",
"(",
"self",
",",
"source",
",",
"soup",
",",
"data",
",",
"url",
"=",
"None",
")",
":",
"meta",
"=",
"FILTER_MAPS",
"[",
"'meta'",
"]",
"[",
"source",
"]",
"meta_map",
"=",
"meta",
"[",
"'map'",
"]",
"html",
"=",
"soup",
... | This method filters the web page content for meta tags that match patterns given in the ``FILTER_MAPS``
:param source: The key of the meta dictionary in ``FILTER_MAPS['meta']``
:type source: string
:param soup: BeautifulSoup instance to find meta tags
:type soup: instance
:param data: The response dictionary to manipulate
:type data: (dict) | [
"This",
"method",
"filters",
"the",
"web",
"page",
"content",
"for",
"meta",
"tags",
"that",
"match",
"patterns",
"given",
"in",
"the",
"FILTER_MAPS"
] | b929f78d7e545cff5fb42eb5edfcaf396456f1ee | https://github.com/michaelhelmick/lassie/blob/b929f78d7e545cff5fb42eb5edfcaf396456f1ee/lassie/core.py#L280-L341 | train | 201,125 |
michaelhelmick/lassie | lassie/core.py | Lassie._filter_link_tag_data | def _filter_link_tag_data(self, source, soup, data, url):
"""This method filters the web page content for link tags that match patterns given in the ``FILTER_MAPS``
:param source: The key of the meta dictionary in ``FILTER_MAPS['link']``
:type source: string
:param soup: BeautifulSoup instance to find meta tags
:type soup: instance
:param data: The response dictionary to manipulate
:type data: (dict)
:param url: URL used for making an absolute url
:type url: string
"""
link = FILTER_MAPS['link'][source]
html = soup.find_all('link', {link['key']: link['pattern']})
if link['type'] == 'url':
for line in html:
data['url'] = line.get('href')
else:
for line in html:
data['images'].append({
'src': urljoin(url, line.get('href')),
'type': link['type'],
}) | python | def _filter_link_tag_data(self, source, soup, data, url):
"""This method filters the web page content for link tags that match patterns given in the ``FILTER_MAPS``
:param source: The key of the meta dictionary in ``FILTER_MAPS['link']``
:type source: string
:param soup: BeautifulSoup instance to find meta tags
:type soup: instance
:param data: The response dictionary to manipulate
:type data: (dict)
:param url: URL used for making an absolute url
:type url: string
"""
link = FILTER_MAPS['link'][source]
html = soup.find_all('link', {link['key']: link['pattern']})
if link['type'] == 'url':
for line in html:
data['url'] = line.get('href')
else:
for line in html:
data['images'].append({
'src': urljoin(url, line.get('href')),
'type': link['type'],
}) | [
"def",
"_filter_link_tag_data",
"(",
"self",
",",
"source",
",",
"soup",
",",
"data",
",",
"url",
")",
":",
"link",
"=",
"FILTER_MAPS",
"[",
"'link'",
"]",
"[",
"source",
"]",
"html",
"=",
"soup",
".",
"find_all",
"(",
"'link'",
",",
"{",
"link",
"["... | This method filters the web page content for link tags that match patterns given in the ``FILTER_MAPS``
:param source: The key of the meta dictionary in ``FILTER_MAPS['link']``
:type source: string
:param soup: BeautifulSoup instance to find meta tags
:type soup: instance
:param data: The response dictionary to manipulate
:type data: (dict)
:param url: URL used for making an absolute url
:type url: string | [
"This",
"method",
"filters",
"the",
"web",
"page",
"content",
"for",
"link",
"tags",
"that",
"match",
"patterns",
"given",
"in",
"the",
"FILTER_MAPS"
] | b929f78d7e545cff5fb42eb5edfcaf396456f1ee | https://github.com/michaelhelmick/lassie/blob/b929f78d7e545cff5fb42eb5edfcaf396456f1ee/lassie/core.py#L343-L368 | train | 201,126 |
michaelhelmick/lassie | lassie/core.py | Lassie._find_all_images | def _find_all_images(self, soup, data, url):
"""This method finds all images in the web page content
:param soup: BeautifulSoup instance to find meta tags
:type soup: instance
:param data: The response dictionary to manipulate
:type data: (dict)
"""
all_images = soup.find_all('img')
for image in all_images:
item = normalize_image_data(image, url)
data['images'].append(item) | python | def _find_all_images(self, soup, data, url):
"""This method finds all images in the web page content
:param soup: BeautifulSoup instance to find meta tags
:type soup: instance
:param data: The response dictionary to manipulate
:type data: (dict)
"""
all_images = soup.find_all('img')
for image in all_images:
item = normalize_image_data(image, url)
data['images'].append(item) | [
"def",
"_find_all_images",
"(",
"self",
",",
"soup",
",",
"data",
",",
"url",
")",
":",
"all_images",
"=",
"soup",
".",
"find_all",
"(",
"'img'",
")",
"for",
"image",
"in",
"all_images",
":",
"item",
"=",
"normalize_image_data",
"(",
"image",
",",
"url",... | This method finds all images in the web page content
:param soup: BeautifulSoup instance to find meta tags
:type soup: instance
:param data: The response dictionary to manipulate
:type data: (dict) | [
"This",
"method",
"finds",
"all",
"images",
"in",
"the",
"web",
"page",
"content"
] | b929f78d7e545cff5fb42eb5edfcaf396456f1ee | https://github.com/michaelhelmick/lassie/blob/b929f78d7e545cff5fb42eb5edfcaf396456f1ee/lassie/core.py#L473-L486 | train | 201,127 |
martinrusev/imbox | imbox/parser.py | decode_mail_header | def decode_mail_header(value, default_charset='us-ascii'):
"""
Decode a header value into a unicode string.
"""
try:
headers = decode_header(value)
except email.errors.HeaderParseError:
return str_decode(str_encode(value, default_charset, 'replace'), default_charset)
else:
for index, (text, charset) in enumerate(headers):
logger.debug("Mail header no. {index}: {data} encoding {charset}".format(
index=index,
data=str_decode(text, charset or 'utf-8', 'replace'),
charset=charset))
try:
headers[index] = str_decode(text, charset or default_charset,
'replace')
except LookupError:
# if the charset is unknown, force default
headers[index] = str_decode(text, default_charset, 'replace')
return ''.join(headers) | python | def decode_mail_header(value, default_charset='us-ascii'):
"""
Decode a header value into a unicode string.
"""
try:
headers = decode_header(value)
except email.errors.HeaderParseError:
return str_decode(str_encode(value, default_charset, 'replace'), default_charset)
else:
for index, (text, charset) in enumerate(headers):
logger.debug("Mail header no. {index}: {data} encoding {charset}".format(
index=index,
data=str_decode(text, charset or 'utf-8', 'replace'),
charset=charset))
try:
headers[index] = str_decode(text, charset or default_charset,
'replace')
except LookupError:
# if the charset is unknown, force default
headers[index] = str_decode(text, default_charset, 'replace')
return ''.join(headers) | [
"def",
"decode_mail_header",
"(",
"value",
",",
"default_charset",
"=",
"'us-ascii'",
")",
":",
"try",
":",
"headers",
"=",
"decode_header",
"(",
"value",
")",
"except",
"email",
".",
"errors",
".",
"HeaderParseError",
":",
"return",
"str_decode",
"(",
"str_en... | Decode a header value into a unicode string. | [
"Decode",
"a",
"header",
"value",
"into",
"a",
"unicode",
"string",
"."
] | bf24410981736eb266559a280ffb8d1f922d032d | https://github.com/martinrusev/imbox/blob/bf24410981736eb266559a280ffb8d1f922d032d/imbox/parser.py#L29-L50 | train | 201,128 |
martinrusev/imbox | imbox/parser.py | get_mail_addresses | def get_mail_addresses(message, header_name):
"""
Retrieve all email addresses from one message header.
"""
headers = [h for h in message.get_all(header_name, [])]
addresses = email.utils.getaddresses(headers)
for index, (address_name, address_email) in enumerate(addresses):
addresses[index] = {'name': decode_mail_header(address_name),
'email': address_email}
logger.debug("{} Mail address in message: <{}> {}".format(
header_name.upper(), address_name, address_email))
return addresses | python | def get_mail_addresses(message, header_name):
"""
Retrieve all email addresses from one message header.
"""
headers = [h for h in message.get_all(header_name, [])]
addresses = email.utils.getaddresses(headers)
for index, (address_name, address_email) in enumerate(addresses):
addresses[index] = {'name': decode_mail_header(address_name),
'email': address_email}
logger.debug("{} Mail address in message: <{}> {}".format(
header_name.upper(), address_name, address_email))
return addresses | [
"def",
"get_mail_addresses",
"(",
"message",
",",
"header_name",
")",
":",
"headers",
"=",
"[",
"h",
"for",
"h",
"in",
"message",
".",
"get_all",
"(",
"header_name",
",",
"[",
"]",
")",
"]",
"addresses",
"=",
"email",
".",
"utils",
".",
"getaddresses",
... | Retrieve all email addresses from one message header. | [
"Retrieve",
"all",
"email",
"addresses",
"from",
"one",
"message",
"header",
"."
] | bf24410981736eb266559a280ffb8d1f922d032d | https://github.com/martinrusev/imbox/blob/bf24410981736eb266559a280ffb8d1f922d032d/imbox/parser.py#L53-L65 | train | 201,129 |
MozillaSecurity/dharma | dharma/core/dharma.py | DharmaVariable.generate | def generate(self, state):
"""Return a random variable if any, otherwise create a new default variable."""
if self.count >= random.randint(DharmaConst.VARIABLE_MIN, DharmaConst.VARIABLE_MAX):
return "%s%d" % (self.var, random.randint(1, self.count))
var = random.choice(self)
prefix = self.eval(var[0], state)
suffix = self.eval(var[1], state)
self.count += 1
element_name = "%s%d" % (self.var, self.count)
self.default += "%s%s%s\n" % (prefix, element_name, suffix)
return element_name | python | def generate(self, state):
"""Return a random variable if any, otherwise create a new default variable."""
if self.count >= random.randint(DharmaConst.VARIABLE_MIN, DharmaConst.VARIABLE_MAX):
return "%s%d" % (self.var, random.randint(1, self.count))
var = random.choice(self)
prefix = self.eval(var[0], state)
suffix = self.eval(var[1], state)
self.count += 1
element_name = "%s%d" % (self.var, self.count)
self.default += "%s%s%s\n" % (prefix, element_name, suffix)
return element_name | [
"def",
"generate",
"(",
"self",
",",
"state",
")",
":",
"if",
"self",
".",
"count",
">=",
"random",
".",
"randint",
"(",
"DharmaConst",
".",
"VARIABLE_MIN",
",",
"DharmaConst",
".",
"VARIABLE_MAX",
")",
":",
"return",
"\"%s%d\"",
"%",
"(",
"self",
".",
... | Return a random variable if any, otherwise create a new default variable. | [
"Return",
"a",
"random",
"variable",
"if",
"any",
"otherwise",
"create",
"a",
"new",
"default",
"variable",
"."
] | 34247464fdda51b92790ad6693566a453d198e0b | https://github.com/MozillaSecurity/dharma/blob/34247464fdda51b92790ad6693566a453d198e0b/dharma/core/dharma.py#L187-L197 | train | 201,130 |
MozillaSecurity/dharma | dharma/core/dharma.py | DharmaMachine.process_settings | def process_settings(self, settings):
"""A lazy way of feeding Dharma with configuration settings."""
logging.debug("Using configuration from: %s", settings.name)
exec(compile(settings.read(), settings.name, 'exec'), globals(), locals()) | python | def process_settings(self, settings):
"""A lazy way of feeding Dharma with configuration settings."""
logging.debug("Using configuration from: %s", settings.name)
exec(compile(settings.read(), settings.name, 'exec'), globals(), locals()) | [
"def",
"process_settings",
"(",
"self",
",",
"settings",
")",
":",
"logging",
".",
"debug",
"(",
"\"Using configuration from: %s\"",
",",
"settings",
".",
"name",
")",
"exec",
"(",
"compile",
"(",
"settings",
".",
"read",
"(",
")",
",",
"settings",
".",
"n... | A lazy way of feeding Dharma with configuration settings. | [
"A",
"lazy",
"way",
"of",
"feeding",
"Dharma",
"with",
"configuration",
"settings",
"."
] | 34247464fdda51b92790ad6693566a453d198e0b | https://github.com/MozillaSecurity/dharma/blob/34247464fdda51b92790ad6693566a453d198e0b/dharma/core/dharma.py#L239-L242 | train | 201,131 |
MozillaSecurity/dharma | dharma/core/dharma.py | DharmaMachine.parse_xrefs | def parse_xrefs(self, token):
"""Search token for +value+ and !variable! style references. Be careful to not xref a new variable.
"""
out, end = [], 0
token = token.replace("\\n", "\n")
for m in re.finditer(self.xref_registry, token, re.VERBOSE | re.DOTALL):
if m.start(0) > end:
out.append(String(token[end:m.start(0)], self.current_obj))
end = m.end(0)
if m.group("type"):
xref_type = {"+": ValueXRef,
"!": VariableXRef,
"@": ElementXRef}[m.group("type")]
out.append(xref_type(m.group("xref"), self.current_obj))
elif m.group("uri") is not None:
path = m.group("uri")
out.append(MetaURI(path, self.current_obj))
elif m.group("repeat") is not None:
repeat, separator, nodups = m.group("repeat", "separator", "nodups")
if separator is None:
separator = ""
if nodups is None:
nodups = ""
out.append(MetaRepeat(self.parse_xrefs(repeat), separator, nodups, self.current_obj))
elif m.group("block") is not None:
path = m.group("block")
out.append(MetaBlock(path, self.current_obj))
elif m.group("choices") is not None:
choices = m.group("choices")
out.append(MetaChoice(choices, self.current_obj))
else:
startval, endval = m.group("start", "end")
out.append(MetaRange(startval, endval, self.current_obj))
if end < len(token):
out.append(String(token[end:], self.current_obj))
return out | python | def parse_xrefs(self, token):
"""Search token for +value+ and !variable! style references. Be careful to not xref a new variable.
"""
out, end = [], 0
token = token.replace("\\n", "\n")
for m in re.finditer(self.xref_registry, token, re.VERBOSE | re.DOTALL):
if m.start(0) > end:
out.append(String(token[end:m.start(0)], self.current_obj))
end = m.end(0)
if m.group("type"):
xref_type = {"+": ValueXRef,
"!": VariableXRef,
"@": ElementXRef}[m.group("type")]
out.append(xref_type(m.group("xref"), self.current_obj))
elif m.group("uri") is not None:
path = m.group("uri")
out.append(MetaURI(path, self.current_obj))
elif m.group("repeat") is not None:
repeat, separator, nodups = m.group("repeat", "separator", "nodups")
if separator is None:
separator = ""
if nodups is None:
nodups = ""
out.append(MetaRepeat(self.parse_xrefs(repeat), separator, nodups, self.current_obj))
elif m.group("block") is not None:
path = m.group("block")
out.append(MetaBlock(path, self.current_obj))
elif m.group("choices") is not None:
choices = m.group("choices")
out.append(MetaChoice(choices, self.current_obj))
else:
startval, endval = m.group("start", "end")
out.append(MetaRange(startval, endval, self.current_obj))
if end < len(token):
out.append(String(token[end:], self.current_obj))
return out | [
"def",
"parse_xrefs",
"(",
"self",
",",
"token",
")",
":",
"out",
",",
"end",
"=",
"[",
"]",
",",
"0",
"token",
"=",
"token",
".",
"replace",
"(",
"\"\\\\n\"",
",",
"\"\\n\"",
")",
"for",
"m",
"in",
"re",
".",
"finditer",
"(",
"self",
".",
"xref_... | Search token for +value+ and !variable! style references. Be careful to not xref a new variable. | [
"Search",
"token",
"for",
"+",
"value",
"+",
"and",
"!variable!",
"style",
"references",
".",
"Be",
"careful",
"to",
"not",
"xref",
"a",
"new",
"variable",
"."
] | 34247464fdda51b92790ad6693566a453d198e0b | https://github.com/MozillaSecurity/dharma/blob/34247464fdda51b92790ad6693566a453d198e0b/dharma/core/dharma.py#L333-L368 | train | 201,132 |
MozillaSecurity/dharma | dharma/core/dharma.py | DharmaMachine.calculate_leaf_paths | def calculate_leaf_paths(self):
"""Build map of reverse xrefs then traverse backwards marking path to leaf for all leaves.
"""
reverse_xref = {}
leaves = set()
for v in self.value.values():
if v.leaf:
leaves.add(v)
for xref in v.value_xref:
reverse_xref.setdefault(xref, []).append(v.ident)
for leaf in leaves:
self.calculate_leaf_path(leaf, reverse_xref) | python | def calculate_leaf_paths(self):
"""Build map of reverse xrefs then traverse backwards marking path to leaf for all leaves.
"""
reverse_xref = {}
leaves = set()
for v in self.value.values():
if v.leaf:
leaves.add(v)
for xref in v.value_xref:
reverse_xref.setdefault(xref, []).append(v.ident)
for leaf in leaves:
self.calculate_leaf_path(leaf, reverse_xref) | [
"def",
"calculate_leaf_paths",
"(",
"self",
")",
":",
"reverse_xref",
"=",
"{",
"}",
"leaves",
"=",
"set",
"(",
")",
"for",
"v",
"in",
"self",
".",
"value",
".",
"values",
"(",
")",
":",
"if",
"v",
".",
"leaf",
":",
"leaves",
".",
"add",
"(",
"v"... | Build map of reverse xrefs then traverse backwards marking path to leaf for all leaves. | [
"Build",
"map",
"of",
"reverse",
"xrefs",
"then",
"traverse",
"backwards",
"marking",
"path",
"to",
"leaf",
"for",
"all",
"leaves",
"."
] | 34247464fdda51b92790ad6693566a453d198e0b | https://github.com/MozillaSecurity/dharma/blob/34247464fdda51b92790ad6693566a453d198e0b/dharma/core/dharma.py#L433-L444 | train | 201,133 |
MozillaSecurity/dharma | dharma/core/dharma.py | DharmaMachine.generate_content | def generate_content(self):
"""Generates a test case as a string."""
# Setup pre-conditions.
if not self.variance:
logging.error("%s: No variance information %s", self.id(), self.variance)
sys.exit(-1)
for var in self.variable.values():
var.clear()
# Handle variances
variances = []
for _ in range(random.randint(DharmaConst.VARIANCE_MIN, DharmaConst.VARIANCE_MAX)):
var = random.choice(list(self.variance.values()))
variances.append(DharmaConst.VARIANCE_TEMPLATE % var.generate(GenState()))
variances.append("\n")
# Handle variables
variables = []
for var in self.variable.values():
if var.default:
variables.append(DharmaConst.VARIANCE_TEMPLATE % var.default)
variables.append("\n")
# Build content
content = "".join(chain([self.prefix], variables, variances, [self.suffix]))
if self.template:
return Template(self.template).safe_substitute(testcase_content=content)
return content | python | def generate_content(self):
"""Generates a test case as a string."""
# Setup pre-conditions.
if not self.variance:
logging.error("%s: No variance information %s", self.id(), self.variance)
sys.exit(-1)
for var in self.variable.values():
var.clear()
# Handle variances
variances = []
for _ in range(random.randint(DharmaConst.VARIANCE_MIN, DharmaConst.VARIANCE_MAX)):
var = random.choice(list(self.variance.values()))
variances.append(DharmaConst.VARIANCE_TEMPLATE % var.generate(GenState()))
variances.append("\n")
# Handle variables
variables = []
for var in self.variable.values():
if var.default:
variables.append(DharmaConst.VARIANCE_TEMPLATE % var.default)
variables.append("\n")
# Build content
content = "".join(chain([self.prefix], variables, variances, [self.suffix]))
if self.template:
return Template(self.template).safe_substitute(testcase_content=content)
return content | [
"def",
"generate_content",
"(",
"self",
")",
":",
"# Setup pre-conditions.",
"if",
"not",
"self",
".",
"variance",
":",
"logging",
".",
"error",
"(",
"\"%s: No variance information %s\"",
",",
"self",
".",
"id",
"(",
")",
",",
"self",
".",
"variance",
")",
"... | Generates a test case as a string. | [
"Generates",
"a",
"test",
"case",
"as",
"a",
"string",
"."
] | 34247464fdda51b92790ad6693566a453d198e0b | https://github.com/MozillaSecurity/dharma/blob/34247464fdda51b92790ad6693566a453d198e0b/dharma/core/dharma.py#L467-L495 | train | 201,134 |
MozillaSecurity/dharma | dharma/core/dharma.py | DharmaMachine.process_grammars | def process_grammars(self, grammars):
"""Process provided grammars by parsing them into Python objects."""
for path in self.default_grammars:
grammars.insert(0, open(os.path.relpath(os.path.join(os.path.dirname(os.path.abspath(__file__)),
os.path.normcase(path)))))
for fo in grammars:
logging.debug("Processing grammar content of %s", fo.name)
self.set_namespace(os.path.splitext(os.path.basename(fo.name))[0])
for line in fo:
self.parse_line(line)
self.handle_empty_line()
self.resolve_xref()
self.calculate_leaf_paths() | python | def process_grammars(self, grammars):
"""Process provided grammars by parsing them into Python objects."""
for path in self.default_grammars:
grammars.insert(0, open(os.path.relpath(os.path.join(os.path.dirname(os.path.abspath(__file__)),
os.path.normcase(path)))))
for fo in grammars:
logging.debug("Processing grammar content of %s", fo.name)
self.set_namespace(os.path.splitext(os.path.basename(fo.name))[0])
for line in fo:
self.parse_line(line)
self.handle_empty_line()
self.resolve_xref()
self.calculate_leaf_paths() | [
"def",
"process_grammars",
"(",
"self",
",",
"grammars",
")",
":",
"for",
"path",
"in",
"self",
".",
"default_grammars",
":",
"grammars",
".",
"insert",
"(",
"0",
",",
"open",
"(",
"os",
".",
"path",
".",
"relpath",
"(",
"os",
".",
"path",
".",
"join... | Process provided grammars by parsing them into Python objects. | [
"Process",
"provided",
"grammars",
"by",
"parsing",
"them",
"into",
"Python",
"objects",
"."
] | 34247464fdda51b92790ad6693566a453d198e0b | https://github.com/MozillaSecurity/dharma/blob/34247464fdda51b92790ad6693566a453d198e0b/dharma/core/dharma.py#L514-L526 | train | 201,135 |
django-admin-tools/django-admin-tools | admin_tools/dashboard/views.py | set_preferences | def set_preferences(request, dashboard_id):
"""
This view serves and validates a preferences form.
"""
try:
preferences = DashboardPreferences.objects.get(
user=request.user,
dashboard_id=dashboard_id
)
except DashboardPreferences.DoesNotExist:
preferences = None
if request.method == "POST":
form = DashboardPreferencesForm(
user=request.user,
dashboard_id=dashboard_id,
data=request.POST,
instance=preferences
)
if form.is_valid():
preferences = form.save()
if request.is_ajax():
return HttpResponse('true')
messages.success(request, 'Preferences saved')
elif request.is_ajax():
return HttpResponse('false')
else:
form = DashboardPreferencesForm(
user=request.user,
dashboard_id=dashboard_id,
instance=preferences
)
return render_to_response(
'admin_tools/dashboard/preferences_form.html',
{'form': form}
) | python | def set_preferences(request, dashboard_id):
"""
This view serves and validates a preferences form.
"""
try:
preferences = DashboardPreferences.objects.get(
user=request.user,
dashboard_id=dashboard_id
)
except DashboardPreferences.DoesNotExist:
preferences = None
if request.method == "POST":
form = DashboardPreferencesForm(
user=request.user,
dashboard_id=dashboard_id,
data=request.POST,
instance=preferences
)
if form.is_valid():
preferences = form.save()
if request.is_ajax():
return HttpResponse('true')
messages.success(request, 'Preferences saved')
elif request.is_ajax():
return HttpResponse('false')
else:
form = DashboardPreferencesForm(
user=request.user,
dashboard_id=dashboard_id,
instance=preferences
)
return render_to_response(
'admin_tools/dashboard/preferences_form.html',
{'form': form}
) | [
"def",
"set_preferences",
"(",
"request",
",",
"dashboard_id",
")",
":",
"try",
":",
"preferences",
"=",
"DashboardPreferences",
".",
"objects",
".",
"get",
"(",
"user",
"=",
"request",
".",
"user",
",",
"dashboard_id",
"=",
"dashboard_id",
")",
"except",
"D... | This view serves and validates a preferences form. | [
"This",
"view",
"serves",
"and",
"validates",
"a",
"preferences",
"form",
"."
] | ba6f46f51ebd84fcf84f2f79ec9487f45452d79b | https://github.com/django-admin-tools/django-admin-tools/blob/ba6f46f51ebd84fcf84f2f79ec9487f45452d79b/admin_tools/dashboard/views.py#L17-L51 | train | 201,136 |
django-admin-tools/django-admin-tools | admin_tools/menu/templatetags/admin_tools_menu_tags.py | admin_tools_render_menu | def admin_tools_render_menu(context, menu=None):
"""
Template tag that renders the menu, it takes an optional ``Menu`` instance
as unique argument, if not given, the menu will be retrieved with the
``get_admin_menu`` function.
"""
if menu is None:
menu = get_admin_menu(context)
menu.init_with_context(context)
has_bookmark_item = False
bookmark = None
if len([c for c in menu.children if isinstance(c, items.Bookmarks)]) > 0:
has_bookmark_item = True
url = context['request'].get_full_path()
try:
bookmark = Bookmark.objects.filter(
user=context['request'].user, url=url
)[0]
except:
pass
context.update({
'template': menu.template,
'menu': menu,
'has_bookmark_item': has_bookmark_item,
'bookmark': bookmark,
'admin_url': reverse('%s:index' % get_admin_site_name(context)),
})
return context | python | def admin_tools_render_menu(context, menu=None):
"""
Template tag that renders the menu, it takes an optional ``Menu`` instance
as unique argument, if not given, the menu will be retrieved with the
``get_admin_menu`` function.
"""
if menu is None:
menu = get_admin_menu(context)
menu.init_with_context(context)
has_bookmark_item = False
bookmark = None
if len([c for c in menu.children if isinstance(c, items.Bookmarks)]) > 0:
has_bookmark_item = True
url = context['request'].get_full_path()
try:
bookmark = Bookmark.objects.filter(
user=context['request'].user, url=url
)[0]
except:
pass
context.update({
'template': menu.template,
'menu': menu,
'has_bookmark_item': has_bookmark_item,
'bookmark': bookmark,
'admin_url': reverse('%s:index' % get_admin_site_name(context)),
})
return context | [
"def",
"admin_tools_render_menu",
"(",
"context",
",",
"menu",
"=",
"None",
")",
":",
"if",
"menu",
"is",
"None",
":",
"menu",
"=",
"get_admin_menu",
"(",
"context",
")",
"menu",
".",
"init_with_context",
"(",
"context",
")",
"has_bookmark_item",
"=",
"False... | Template tag that renders the menu, it takes an optional ``Menu`` instance
as unique argument, if not given, the menu will be retrieved with the
``get_admin_menu`` function. | [
"Template",
"tag",
"that",
"renders",
"the",
"menu",
"it",
"takes",
"an",
"optional",
"Menu",
"instance",
"as",
"unique",
"argument",
"if",
"not",
"given",
"the",
"menu",
"will",
"be",
"retrieved",
"with",
"the",
"get_admin_menu",
"function",
"."
] | ba6f46f51ebd84fcf84f2f79ec9487f45452d79b | https://github.com/django-admin-tools/django-admin-tools/blob/ba6f46f51ebd84fcf84f2f79ec9487f45452d79b/admin_tools/menu/templatetags/admin_tools_menu_tags.py#L29-L58 | train | 201,137 |
django-admin-tools/django-admin-tools | admin_tools/menu/templatetags/admin_tools_menu_tags.py | admin_tools_render_menu_item | def admin_tools_render_menu_item(context, item, index=None):
"""
Template tag that renders a given menu item, it takes a ``MenuItem``
instance as unique parameter.
"""
item.init_with_context(context)
context.update({
'template': item.template,
'item': item,
'index': index,
'selected': item.is_selected(context['request']),
'admin_url': reverse('%s:index' % get_admin_site_name(context)),
})
return context | python | def admin_tools_render_menu_item(context, item, index=None):
"""
Template tag that renders a given menu item, it takes a ``MenuItem``
instance as unique parameter.
"""
item.init_with_context(context)
context.update({
'template': item.template,
'item': item,
'index': index,
'selected': item.is_selected(context['request']),
'admin_url': reverse('%s:index' % get_admin_site_name(context)),
})
return context | [
"def",
"admin_tools_render_menu_item",
"(",
"context",
",",
"item",
",",
"index",
"=",
"None",
")",
":",
"item",
".",
"init_with_context",
"(",
"context",
")",
"context",
".",
"update",
"(",
"{",
"'template'",
":",
"item",
".",
"template",
",",
"'item'",
"... | Template tag that renders a given menu item, it takes a ``MenuItem``
instance as unique parameter. | [
"Template",
"tag",
"that",
"renders",
"a",
"given",
"menu",
"item",
"it",
"takes",
"a",
"MenuItem",
"instance",
"as",
"unique",
"parameter",
"."
] | ba6f46f51ebd84fcf84f2f79ec9487f45452d79b | https://github.com/django-admin-tools/django-admin-tools/blob/ba6f46f51ebd84fcf84f2f79ec9487f45452d79b/admin_tools/menu/templatetags/admin_tools_menu_tags.py#L62-L76 | train | 201,138 |
django-admin-tools/django-admin-tools | admin_tools/menu/templatetags/admin_tools_menu_tags.py | admin_tools_render_menu_css | def admin_tools_render_menu_css(context, menu=None):
"""
Template tag that renders the menu css files,, it takes an optional
``Menu`` instance as unique argument, if not given, the menu will be
retrieved with the ``get_admin_menu`` function.
"""
if menu is None:
menu = get_admin_menu(context)
context.update({
'template': 'admin_tools/menu/css.html',
'css_files': menu.Media.css,
})
return context | python | def admin_tools_render_menu_css(context, menu=None):
"""
Template tag that renders the menu css files,, it takes an optional
``Menu`` instance as unique argument, if not given, the menu will be
retrieved with the ``get_admin_menu`` function.
"""
if menu is None:
menu = get_admin_menu(context)
context.update({
'template': 'admin_tools/menu/css.html',
'css_files': menu.Media.css,
})
return context | [
"def",
"admin_tools_render_menu_css",
"(",
"context",
",",
"menu",
"=",
"None",
")",
":",
"if",
"menu",
"is",
"None",
":",
"menu",
"=",
"get_admin_menu",
"(",
"context",
")",
"context",
".",
"update",
"(",
"{",
"'template'",
":",
"'admin_tools/menu/css.html'",... | Template tag that renders the menu css files,, it takes an optional
``Menu`` instance as unique argument, if not given, the menu will be
retrieved with the ``get_admin_menu`` function. | [
"Template",
"tag",
"that",
"renders",
"the",
"menu",
"css",
"files",
"it",
"takes",
"an",
"optional",
"Menu",
"instance",
"as",
"unique",
"argument",
"if",
"not",
"given",
"the",
"menu",
"will",
"be",
"retrieved",
"with",
"the",
"get_admin_menu",
"function",
... | ba6f46f51ebd84fcf84f2f79ec9487f45452d79b | https://github.com/django-admin-tools/django-admin-tools/blob/ba6f46f51ebd84fcf84f2f79ec9487f45452d79b/admin_tools/menu/templatetags/admin_tools_menu_tags.py#L80-L93 | train | 201,139 |
django-admin-tools/django-admin-tools | admin_tools/theming/templatetags/theming_tags.py | render_theming_css | def render_theming_css():
"""
Template tag that renders the needed css files for the theming app.
"""
css = getattr(settings, 'ADMIN_TOOLS_THEMING_CSS', False)
if not css:
css = '/'.join(['admin_tools', 'css', 'theming.css'])
return mark_safe(
'<link rel="stylesheet" type="text/css" media="screen" href="%s" />' %
staticfiles_storage.url(css)
) | python | def render_theming_css():
"""
Template tag that renders the needed css files for the theming app.
"""
css = getattr(settings, 'ADMIN_TOOLS_THEMING_CSS', False)
if not css:
css = '/'.join(['admin_tools', 'css', 'theming.css'])
return mark_safe(
'<link rel="stylesheet" type="text/css" media="screen" href="%s" />' %
staticfiles_storage.url(css)
) | [
"def",
"render_theming_css",
"(",
")",
":",
"css",
"=",
"getattr",
"(",
"settings",
",",
"'ADMIN_TOOLS_THEMING_CSS'",
",",
"False",
")",
"if",
"not",
"css",
":",
"css",
"=",
"'/'",
".",
"join",
"(",
"[",
"'admin_tools'",
",",
"'css'",
",",
"'theming.css'",... | Template tag that renders the needed css files for the theming app. | [
"Template",
"tag",
"that",
"renders",
"the",
"needed",
"css",
"files",
"for",
"the",
"theming",
"app",
"."
] | ba6f46f51ebd84fcf84f2f79ec9487f45452d79b | https://github.com/django-admin-tools/django-admin-tools/blob/ba6f46f51ebd84fcf84f2f79ec9487f45452d79b/admin_tools/theming/templatetags/theming_tags.py#L15-L25 | train | 201,140 |
django-admin-tools/django-admin-tools | admin_tools/menu/views.py | add_bookmark | def add_bookmark(request):
"""
This view serves and validates a bookmark form.
If requested via ajax it also returns the drop bookmark form to replace the
add bookmark form.
"""
if request.method == "POST":
form = BookmarkForm(user=request.user, data=request.POST)
if form.is_valid():
bookmark = form.save()
if not request.is_ajax():
messages.success(request, 'Bookmark added')
if request.POST.get('next'):
return HttpResponseRedirect(request.POST.get('next'))
return HttpResponse('Added')
return render_to_response(
'admin_tools/menu/remove_bookmark_form.html',
{'bookmark': bookmark, 'url': bookmark.url}
)
else:
form = BookmarkForm(user=request.user)
return render_to_response(
'admin_tools/menu/form.html',
{'form': form, 'title': 'Add Bookmark'}
) | python | def add_bookmark(request):
"""
This view serves and validates a bookmark form.
If requested via ajax it also returns the drop bookmark form to replace the
add bookmark form.
"""
if request.method == "POST":
form = BookmarkForm(user=request.user, data=request.POST)
if form.is_valid():
bookmark = form.save()
if not request.is_ajax():
messages.success(request, 'Bookmark added')
if request.POST.get('next'):
return HttpResponseRedirect(request.POST.get('next'))
return HttpResponse('Added')
return render_to_response(
'admin_tools/menu/remove_bookmark_form.html',
{'bookmark': bookmark, 'url': bookmark.url}
)
else:
form = BookmarkForm(user=request.user)
return render_to_response(
'admin_tools/menu/form.html',
{'form': form, 'title': 'Add Bookmark'}
) | [
"def",
"add_bookmark",
"(",
"request",
")",
":",
"if",
"request",
".",
"method",
"==",
"\"POST\"",
":",
"form",
"=",
"BookmarkForm",
"(",
"user",
"=",
"request",
".",
"user",
",",
"data",
"=",
"request",
".",
"POST",
")",
"if",
"form",
".",
"is_valid",... | This view serves and validates a bookmark form.
If requested via ajax it also returns the drop bookmark form to replace the
add bookmark form. | [
"This",
"view",
"serves",
"and",
"validates",
"a",
"bookmark",
"form",
".",
"If",
"requested",
"via",
"ajax",
"it",
"also",
"returns",
"the",
"drop",
"bookmark",
"form",
"to",
"replace",
"the",
"add",
"bookmark",
"form",
"."
] | ba6f46f51ebd84fcf84f2f79ec9487f45452d79b | https://github.com/django-admin-tools/django-admin-tools/blob/ba6f46f51ebd84fcf84f2f79ec9487f45452d79b/admin_tools/menu/views.py#L18-L42 | train | 201,141 |
django-admin-tools/django-admin-tools | admin_tools/menu/views.py | remove_bookmark | def remove_bookmark(request, id):
"""
This view deletes a bookmark.
If requested via ajax it also returns the add bookmark form to replace the
drop bookmark form.
"""
bookmark = get_object_or_404(Bookmark, id=id, user=request.user)
if request.method == "POST":
bookmark.delete()
if not request.is_ajax():
messages.success(request, 'Bookmark removed')
if request.POST.get('next'):
return HttpResponseRedirect(request.POST.get('next'))
return HttpResponse('Deleted')
return render_to_response(
'admin_tools/menu/add_bookmark_form.html',
{
'url': request.POST.get('next'),
'title': '**title**' # replaced on the javascript side
}
)
return render_to_response(
'admin_tools/menu/delete_confirm.html',
{'bookmark': bookmark, 'title': 'Delete Bookmark'}
) | python | def remove_bookmark(request, id):
"""
This view deletes a bookmark.
If requested via ajax it also returns the add bookmark form to replace the
drop bookmark form.
"""
bookmark = get_object_or_404(Bookmark, id=id, user=request.user)
if request.method == "POST":
bookmark.delete()
if not request.is_ajax():
messages.success(request, 'Bookmark removed')
if request.POST.get('next'):
return HttpResponseRedirect(request.POST.get('next'))
return HttpResponse('Deleted')
return render_to_response(
'admin_tools/menu/add_bookmark_form.html',
{
'url': request.POST.get('next'),
'title': '**title**' # replaced on the javascript side
}
)
return render_to_response(
'admin_tools/menu/delete_confirm.html',
{'bookmark': bookmark, 'title': 'Delete Bookmark'}
) | [
"def",
"remove_bookmark",
"(",
"request",
",",
"id",
")",
":",
"bookmark",
"=",
"get_object_or_404",
"(",
"Bookmark",
",",
"id",
"=",
"id",
",",
"user",
"=",
"request",
".",
"user",
")",
"if",
"request",
".",
"method",
"==",
"\"POST\"",
":",
"bookmark",
... | This view deletes a bookmark.
If requested via ajax it also returns the add bookmark form to replace the
drop bookmark form. | [
"This",
"view",
"deletes",
"a",
"bookmark",
".",
"If",
"requested",
"via",
"ajax",
"it",
"also",
"returns",
"the",
"add",
"bookmark",
"form",
"to",
"replace",
"the",
"drop",
"bookmark",
"form",
"."
] | ba6f46f51ebd84fcf84f2f79ec9487f45452d79b | https://github.com/django-admin-tools/django-admin-tools/blob/ba6f46f51ebd84fcf84f2f79ec9487f45452d79b/admin_tools/menu/views.py#L72-L96 | train | 201,142 |
django-admin-tools/django-admin-tools | admin_tools/dashboard/registry.py | autodiscover | def autodiscover(blacklist=[]):
"""
Automagically discover custom dashboards and menus for installed apps.
Optionally you can pass a ``blacklist`` of apps that you don't want to
provide their own app index dashboard.
"""
import imp
from django.conf import settings
try:
from importlib import import_module
except ImportError:
# Django < 1.9 and Python < 2.7
from django.utils.importlib import import_module
blacklist.append('admin_tools.dashboard')
blacklist.append('admin_tools.menu')
blacklist.append('admin_tools.theming')
for app in settings.INSTALLED_APPS:
# skip blacklisted apps
if app in blacklist:
continue
# try to import the app
try:
app_path = import_module(app).__path__
except AttributeError:
continue
# try to find a app.dashboard module
try:
imp.find_module('dashboard', app_path)
except ImportError:
continue
# looks like we found it so import it !
import_module('%s.dashboard' % app) | python | def autodiscover(blacklist=[]):
"""
Automagically discover custom dashboards and menus for installed apps.
Optionally you can pass a ``blacklist`` of apps that you don't want to
provide their own app index dashboard.
"""
import imp
from django.conf import settings
try:
from importlib import import_module
except ImportError:
# Django < 1.9 and Python < 2.7
from django.utils.importlib import import_module
blacklist.append('admin_tools.dashboard')
blacklist.append('admin_tools.menu')
blacklist.append('admin_tools.theming')
for app in settings.INSTALLED_APPS:
# skip blacklisted apps
if app in blacklist:
continue
# try to import the app
try:
app_path = import_module(app).__path__
except AttributeError:
continue
# try to find a app.dashboard module
try:
imp.find_module('dashboard', app_path)
except ImportError:
continue
# looks like we found it so import it !
import_module('%s.dashboard' % app) | [
"def",
"autodiscover",
"(",
"blacklist",
"=",
"[",
"]",
")",
":",
"import",
"imp",
"from",
"django",
".",
"conf",
"import",
"settings",
"try",
":",
"from",
"importlib",
"import",
"import_module",
"except",
"ImportError",
":",
"# Django < 1.9 and Python < 2.7",
"... | Automagically discover custom dashboards and menus for installed apps.
Optionally you can pass a ``blacklist`` of apps that you don't want to
provide their own app index dashboard. | [
"Automagically",
"discover",
"custom",
"dashboards",
"and",
"menus",
"for",
"installed",
"apps",
".",
"Optionally",
"you",
"can",
"pass",
"a",
"blacklist",
"of",
"apps",
"that",
"you",
"don",
"t",
"want",
"to",
"provide",
"their",
"own",
"app",
"index",
"das... | ba6f46f51ebd84fcf84f2f79ec9487f45452d79b | https://github.com/django-admin-tools/django-admin-tools/blob/ba6f46f51ebd84fcf84f2f79ec9487f45452d79b/admin_tools/dashboard/registry.py#L32-L68 | train | 201,143 |
django-admin-tools/django-admin-tools | admin_tools/dashboard/modules.py | DashboardModule.render_css_classes | def render_css_classes(self):
"""
Return a string containing the css classes for the module.
>>> mod = DashboardModule(enabled=False, draggable=True,
... collapsible=True, deletable=True)
>>> mod.render_css_classes()
'dashboard-module disabled draggable collapsible deletable'
>>> mod.css_classes.append('foo')
>>> mod.render_css_classes()
'dashboard-module disabled draggable collapsible deletable foo'
>>> mod.enabled = True
>>> mod.render_css_classes()
'dashboard-module draggable collapsible deletable foo'
"""
ret = ['dashboard-module']
if not self.enabled:
ret.append('disabled')
if self.draggable:
ret.append('draggable')
if self.collapsible:
ret.append('collapsible')
if self.deletable:
ret.append('deletable')
ret += self.css_classes
return ' '.join(ret) | python | def render_css_classes(self):
"""
Return a string containing the css classes for the module.
>>> mod = DashboardModule(enabled=False, draggable=True,
... collapsible=True, deletable=True)
>>> mod.render_css_classes()
'dashboard-module disabled draggable collapsible deletable'
>>> mod.css_classes.append('foo')
>>> mod.render_css_classes()
'dashboard-module disabled draggable collapsible deletable foo'
>>> mod.enabled = True
>>> mod.render_css_classes()
'dashboard-module draggable collapsible deletable foo'
"""
ret = ['dashboard-module']
if not self.enabled:
ret.append('disabled')
if self.draggable:
ret.append('draggable')
if self.collapsible:
ret.append('collapsible')
if self.deletable:
ret.append('deletable')
ret += self.css_classes
return ' '.join(ret) | [
"def",
"render_css_classes",
"(",
"self",
")",
":",
"ret",
"=",
"[",
"'dashboard-module'",
"]",
"if",
"not",
"self",
".",
"enabled",
":",
"ret",
".",
"append",
"(",
"'disabled'",
")",
"if",
"self",
".",
"draggable",
":",
"ret",
".",
"append",
"(",
"'dr... | Return a string containing the css classes for the module.
>>> mod = DashboardModule(enabled=False, draggable=True,
... collapsible=True, deletable=True)
>>> mod.render_css_classes()
'dashboard-module disabled draggable collapsible deletable'
>>> mod.css_classes.append('foo')
>>> mod.render_css_classes()
'dashboard-module disabled draggable collapsible deletable foo'
>>> mod.enabled = True
>>> mod.render_css_classes()
'dashboard-module draggable collapsible deletable foo' | [
"Return",
"a",
"string",
"containing",
"the",
"css",
"classes",
"for",
"the",
"module",
"."
] | ba6f46f51ebd84fcf84f2f79ec9487f45452d79b | https://github.com/django-admin-tools/django-admin-tools/blob/ba6f46f51ebd84fcf84f2f79ec9487f45452d79b/admin_tools/dashboard/modules.py#L156-L181 | train | 201,144 |
django-admin-tools/django-admin-tools | admin_tools/dashboard/modules.py | Group.is_empty | def is_empty(self):
"""
A group of modules is considered empty if it has no children or if
all its children are empty.
>>> from admin_tools.dashboard.modules import DashboardModule, LinkList
>>> mod = Group()
>>> mod.is_empty()
True
>>> mod.children.append(DashboardModule())
>>> mod.is_empty()
True
>>> mod.children.append(LinkList('links', children=[
... {'title': 'example1', 'url': 'http://example.com'},
... {'title': 'example2', 'url': 'http://example.com'},
... ]))
>>> mod.is_empty()
False
"""
if super(Group, self).is_empty():
return True
for child in self.children:
if not child.is_empty():
return False
return True | python | def is_empty(self):
"""
A group of modules is considered empty if it has no children or if
all its children are empty.
>>> from admin_tools.dashboard.modules import DashboardModule, LinkList
>>> mod = Group()
>>> mod.is_empty()
True
>>> mod.children.append(DashboardModule())
>>> mod.is_empty()
True
>>> mod.children.append(LinkList('links', children=[
... {'title': 'example1', 'url': 'http://example.com'},
... {'title': 'example2', 'url': 'http://example.com'},
... ]))
>>> mod.is_empty()
False
"""
if super(Group, self).is_empty():
return True
for child in self.children:
if not child.is_empty():
return False
return True | [
"def",
"is_empty",
"(",
"self",
")",
":",
"if",
"super",
"(",
"Group",
",",
"self",
")",
".",
"is_empty",
"(",
")",
":",
"return",
"True",
"for",
"child",
"in",
"self",
".",
"children",
":",
"if",
"not",
"child",
".",
"is_empty",
"(",
")",
":",
"... | A group of modules is considered empty if it has no children or if
all its children are empty.
>>> from admin_tools.dashboard.modules import DashboardModule, LinkList
>>> mod = Group()
>>> mod.is_empty()
True
>>> mod.children.append(DashboardModule())
>>> mod.is_empty()
True
>>> mod.children.append(LinkList('links', children=[
... {'title': 'example1', 'url': 'http://example.com'},
... {'title': 'example2', 'url': 'http://example.com'},
... ]))
>>> mod.is_empty()
False | [
"A",
"group",
"of",
"modules",
"is",
"considered",
"empty",
"if",
"it",
"has",
"no",
"children",
"or",
"if",
"all",
"its",
"children",
"are",
"empty",
"."
] | ba6f46f51ebd84fcf84f2f79ec9487f45452d79b | https://github.com/django-admin-tools/django-admin-tools/blob/ba6f46f51ebd84fcf84f2f79ec9487f45452d79b/admin_tools/dashboard/modules.py#L251-L275 | train | 201,145 |
django-admin-tools/django-admin-tools | admin_tools/dashboard/utils.py | get_app_index_dashboard | def get_app_index_dashboard(context):
"""
Returns the admin dashboard defined by the user or the default one.
"""
# this is a mess, needs cleanup !
app = context['app_list'][0]
model_list = []
app_label = None
app_title = app['name']
admin_site = get_admin_site(context=context)
for model, model_admin in admin_site._registry.items():
if app['app_label'] == model._meta.app_label:
split = model.__module__.find(model._meta.app_label)
app_label = model.__module__[0:split] + model._meta.app_label
for m in app['models']:
if m['name'] == capfirst(model._meta.verbose_name_plural):
mod = '%s.%s' % (model.__module__, model.__name__)
model_list.append(mod)
# if an app has registered its own dashboard, use it
if app_label is not None and app_label in Registry.registry:
return Registry.registry[app_label](app_title, model_list)
# try to discover a general app_index dashboard (with fallback to the
# default dashboard)
return _get_dashboard_cls(getattr(
settings,
'ADMIN_TOOLS_APP_INDEX_DASHBOARD',
'admin_tools.dashboard.dashboards.DefaultAppIndexDashboard'
), context)(app_title, model_list) | python | def get_app_index_dashboard(context):
"""
Returns the admin dashboard defined by the user or the default one.
"""
# this is a mess, needs cleanup !
app = context['app_list'][0]
model_list = []
app_label = None
app_title = app['name']
admin_site = get_admin_site(context=context)
for model, model_admin in admin_site._registry.items():
if app['app_label'] == model._meta.app_label:
split = model.__module__.find(model._meta.app_label)
app_label = model.__module__[0:split] + model._meta.app_label
for m in app['models']:
if m['name'] == capfirst(model._meta.verbose_name_plural):
mod = '%s.%s' % (model.__module__, model.__name__)
model_list.append(mod)
# if an app has registered its own dashboard, use it
if app_label is not None and app_label in Registry.registry:
return Registry.registry[app_label](app_title, model_list)
# try to discover a general app_index dashboard (with fallback to the
# default dashboard)
return _get_dashboard_cls(getattr(
settings,
'ADMIN_TOOLS_APP_INDEX_DASHBOARD',
'admin_tools.dashboard.dashboards.DefaultAppIndexDashboard'
), context)(app_title, model_list) | [
"def",
"get_app_index_dashboard",
"(",
"context",
")",
":",
"# this is a mess, needs cleanup !",
"app",
"=",
"context",
"[",
"'app_list'",
"]",
"[",
"0",
"]",
"model_list",
"=",
"[",
"]",
"app_label",
"=",
"None",
"app_title",
"=",
"app",
"[",
"'name'",
"]",
... | Returns the admin dashboard defined by the user or the default one. | [
"Returns",
"the",
"admin",
"dashboard",
"defined",
"by",
"the",
"user",
"or",
"the",
"default",
"one",
"."
] | ba6f46f51ebd84fcf84f2f79ec9487f45452d79b | https://github.com/django-admin-tools/django-admin-tools/blob/ba6f46f51ebd84fcf84f2f79ec9487f45452d79b/admin_tools/dashboard/utils.py#L62-L92 | train | 201,146 |
django-admin-tools/django-admin-tools | admin_tools/dashboard/dashboards.py | AppIndexDashboard.get_app_model_classes | def get_app_model_classes(self):
"""
Helper method that returns a list of model classes for the current app.
"""
models = []
for m in self.models:
mod, cls = m.rsplit('.', 1)
mod = import_module(mod)
models.append(getattr(mod, cls))
return models | python | def get_app_model_classes(self):
"""
Helper method that returns a list of model classes for the current app.
"""
models = []
for m in self.models:
mod, cls = m.rsplit('.', 1)
mod = import_module(mod)
models.append(getattr(mod, cls))
return models | [
"def",
"get_app_model_classes",
"(",
"self",
")",
":",
"models",
"=",
"[",
"]",
"for",
"m",
"in",
"self",
".",
"models",
":",
"mod",
",",
"cls",
"=",
"m",
".",
"rsplit",
"(",
"'.'",
",",
"1",
")",
"mod",
"=",
"import_module",
"(",
"mod",
")",
"mo... | Helper method that returns a list of model classes for the current app. | [
"Helper",
"method",
"that",
"returns",
"a",
"list",
"of",
"model",
"classes",
"for",
"the",
"current",
"app",
"."
] | ba6f46f51ebd84fcf84f2f79ec9487f45452d79b | https://github.com/django-admin-tools/django-admin-tools/blob/ba6f46f51ebd84fcf84f2f79ec9487f45452d79b/admin_tools/dashboard/dashboards.py#L193-L202 | train | 201,147 |
django-admin-tools/django-admin-tools | admin_tools/dashboard/dashboards.py | AppIndexDashboard.get_app_content_types | def get_app_content_types(self):
"""
Return a list of all content_types for this app.
"""
# Import this here to silence RemovedInDjango19Warning. See #15
from django.contrib.contenttypes.models import ContentType
return [ContentType.objects.get_for_model(c) for c
in self.get_app_model_classes()] | python | def get_app_content_types(self):
"""
Return a list of all content_types for this app.
"""
# Import this here to silence RemovedInDjango19Warning. See #15
from django.contrib.contenttypes.models import ContentType
return [ContentType.objects.get_for_model(c) for c
in self.get_app_model_classes()] | [
"def",
"get_app_content_types",
"(",
"self",
")",
":",
"# Import this here to silence RemovedInDjango19Warning. See #15",
"from",
"django",
".",
"contrib",
".",
"contenttypes",
".",
"models",
"import",
"ContentType",
"return",
"[",
"ContentType",
".",
"objects",
".",
"g... | Return a list of all content_types for this app. | [
"Return",
"a",
"list",
"of",
"all",
"content_types",
"for",
"this",
"app",
"."
] | ba6f46f51ebd84fcf84f2f79ec9487f45452d79b | https://github.com/django-admin-tools/django-admin-tools/blob/ba6f46f51ebd84fcf84f2f79ec9487f45452d79b/admin_tools/dashboard/dashboards.py#L204-L212 | train | 201,148 |
django-admin-tools/django-admin-tools | admin_tools/dashboard/templatetags/admin_tools_dashboard_tags.py | admin_tools_render_dashboard_module | def admin_tools_render_dashboard_module(context, module):
"""
Template tag that renders a given dashboard module, it takes a
``DashboardModule`` instance as first parameter.
"""
module.init_with_context(context)
context.update({
'template': module.template,
'module': module,
'admin_url': reverse('%s:index' % get_admin_site_name(context)),
})
return context | python | def admin_tools_render_dashboard_module(context, module):
"""
Template tag that renders a given dashboard module, it takes a
``DashboardModule`` instance as first parameter.
"""
module.init_with_context(context)
context.update({
'template': module.template,
'module': module,
'admin_url': reverse('%s:index' % get_admin_site_name(context)),
})
return context | [
"def",
"admin_tools_render_dashboard_module",
"(",
"context",
",",
"module",
")",
":",
"module",
".",
"init_with_context",
"(",
"context",
")",
"context",
".",
"update",
"(",
"{",
"'template'",
":",
"module",
".",
"template",
",",
"'module'",
":",
"module",
",... | Template tag that renders a given dashboard module, it takes a
``DashboardModule`` instance as first parameter. | [
"Template",
"tag",
"that",
"renders",
"a",
"given",
"dashboard",
"module",
"it",
"takes",
"a",
"DashboardModule",
"instance",
"as",
"first",
"parameter",
"."
] | ba6f46f51ebd84fcf84f2f79ec9487f45452d79b | https://github.com/django-admin-tools/django-admin-tools/blob/ba6f46f51ebd84fcf84f2f79ec9487f45452d79b/admin_tools/dashboard/templatetags/admin_tools_dashboard_tags.py#L83-L94 | train | 201,149 |
django-admin-tools/django-admin-tools | admin_tools/menu/items.py | MenuItem.is_selected | def is_selected(self, request):
"""
Helper method that returns ``True`` if the menu item is active.
A menu item is considered as active if it's URL or one of its
descendants URL is equals to the current URL.
"""
current_url = request.get_full_path()
return self.url == current_url or \
len([c for c in self.children if c.is_selected(request)]) > 0 | python | def is_selected(self, request):
"""
Helper method that returns ``True`` if the menu item is active.
A menu item is considered as active if it's URL or one of its
descendants URL is equals to the current URL.
"""
current_url = request.get_full_path()
return self.url == current_url or \
len([c for c in self.children if c.is_selected(request)]) > 0 | [
"def",
"is_selected",
"(",
"self",
",",
"request",
")",
":",
"current_url",
"=",
"request",
".",
"get_full_path",
"(",
")",
"return",
"self",
".",
"url",
"==",
"current_url",
"or",
"len",
"(",
"[",
"c",
"for",
"c",
"in",
"self",
".",
"children",
"if",
... | Helper method that returns ``True`` if the menu item is active.
A menu item is considered as active if it's URL or one of its
descendants URL is equals to the current URL. | [
"Helper",
"method",
"that",
"returns",
"True",
"if",
"the",
"menu",
"item",
"is",
"active",
".",
"A",
"menu",
"item",
"is",
"considered",
"as",
"active",
"if",
"it",
"s",
"URL",
"or",
"one",
"of",
"its",
"descendants",
"URL",
"is",
"equals",
"to",
"the... | ba6f46f51ebd84fcf84f2f79ec9487f45452d79b | https://github.com/django-admin-tools/django-admin-tools/blob/ba6f46f51ebd84fcf84f2f79ec9487f45452d79b/admin_tools/menu/items.py#L111-L119 | train | 201,150 |
django-admin-tools/django-admin-tools | admin_tools/utils.py | uniquify | def uniquify(value, seen_values):
""" Adds value to seen_values set and ensures it is unique """
id = 1
new_value = value
while new_value in seen_values:
new_value = "%s%s" % (value, id)
id += 1
seen_values.add(new_value)
return new_value | python | def uniquify(value, seen_values):
""" Adds value to seen_values set and ensures it is unique """
id = 1
new_value = value
while new_value in seen_values:
new_value = "%s%s" % (value, id)
id += 1
seen_values.add(new_value)
return new_value | [
"def",
"uniquify",
"(",
"value",
",",
"seen_values",
")",
":",
"id",
"=",
"1",
"new_value",
"=",
"value",
"while",
"new_value",
"in",
"seen_values",
":",
"new_value",
"=",
"\"%s%s\"",
"%",
"(",
"value",
",",
"id",
")",
"id",
"+=",
"1",
"seen_values",
"... | Adds value to seen_values set and ensures it is unique | [
"Adds",
"value",
"to",
"seen_values",
"set",
"and",
"ensures",
"it",
"is",
"unique"
] | ba6f46f51ebd84fcf84f2f79ec9487f45452d79b | https://github.com/django-admin-tools/django-admin-tools/blob/ba6f46f51ebd84fcf84f2f79ec9487f45452d79b/admin_tools/utils.py#L20-L28 | train | 201,151 |
jasonrbriggs/stomp.py | stomp/utils.py | default_create_thread | def default_create_thread(callback):
"""
Default thread creation - used to create threads when the client doesn't want to provide their
own thread creation.
:param function callback: the callback function provided to threading.Thread
"""
thread = threading.Thread(None, callback)
thread.daemon = True # Don't let thread prevent termination
thread.start()
return thread | python | def default_create_thread(callback):
"""
Default thread creation - used to create threads when the client doesn't want to provide their
own thread creation.
:param function callback: the callback function provided to threading.Thread
"""
thread = threading.Thread(None, callback)
thread.daemon = True # Don't let thread prevent termination
thread.start()
return thread | [
"def",
"default_create_thread",
"(",
"callback",
")",
":",
"thread",
"=",
"threading",
".",
"Thread",
"(",
"None",
",",
"callback",
")",
"thread",
".",
"daemon",
"=",
"True",
"# Don't let thread prevent termination",
"thread",
".",
"start",
"(",
")",
"return",
... | Default thread creation - used to create threads when the client doesn't want to provide their
own thread creation.
:param function callback: the callback function provided to threading.Thread | [
"Default",
"thread",
"creation",
"-",
"used",
"to",
"create",
"threads",
"when",
"the",
"client",
"doesn",
"t",
"want",
"to",
"provide",
"their",
"own",
"thread",
"creation",
"."
] | 643843c5fbf25fd24339dd0e69a9411c3d8b94c7 | https://github.com/jasonrbriggs/stomp.py/blob/643843c5fbf25fd24339dd0e69a9411c3d8b94c7/stomp/utils.py#L56-L66 | train | 201,152 |
jasonrbriggs/stomp.py | stomp/utils.py | parse_headers | def parse_headers(lines, offset=0):
"""
Parse the headers in a STOMP response
:param list(str) lines: the lines received in the message response
:param int offset: the starting line number
:rtype: dict(str,str)
"""
headers = {}
for header_line in lines[offset:]:
header_match = HEADER_LINE_RE.match(header_line)
if header_match:
key = header_match.group('key')
key = re.sub(r'\\.', _unescape_header, key)
if key not in headers:
value = header_match.group('value')
value = re.sub(r'\\.', _unescape_header, value)
headers[key] = value
return headers | python | def parse_headers(lines, offset=0):
"""
Parse the headers in a STOMP response
:param list(str) lines: the lines received in the message response
:param int offset: the starting line number
:rtype: dict(str,str)
"""
headers = {}
for header_line in lines[offset:]:
header_match = HEADER_LINE_RE.match(header_line)
if header_match:
key = header_match.group('key')
key = re.sub(r'\\.', _unescape_header, key)
if key not in headers:
value = header_match.group('value')
value = re.sub(r'\\.', _unescape_header, value)
headers[key] = value
return headers | [
"def",
"parse_headers",
"(",
"lines",
",",
"offset",
"=",
"0",
")",
":",
"headers",
"=",
"{",
"}",
"for",
"header_line",
"in",
"lines",
"[",
"offset",
":",
"]",
":",
"header_match",
"=",
"HEADER_LINE_RE",
".",
"match",
"(",
"header_line",
")",
"if",
"h... | Parse the headers in a STOMP response
:param list(str) lines: the lines received in the message response
:param int offset: the starting line number
:rtype: dict(str,str) | [
"Parse",
"the",
"headers",
"in",
"a",
"STOMP",
"response"
] | 643843c5fbf25fd24339dd0e69a9411c3d8b94c7 | https://github.com/jasonrbriggs/stomp.py/blob/643843c5fbf25fd24339dd0e69a9411c3d8b94c7/stomp/utils.py#L103-L122 | train | 201,153 |
jasonrbriggs/stomp.py | stomp/utils.py | parse_frame | def parse_frame(frame):
"""
Parse a STOMP frame into a Frame object.
:param bytes frame: the frame received from the server (as a byte string)
:rtype: Frame
"""
f = Frame()
if frame == b'\x0a':
f.cmd = 'heartbeat'
return f
mat = PREAMBLE_END_RE.search(frame)
if mat:
preamble_end = mat.start()
body_start = mat.end()
else:
preamble_end = len(frame)
body_start = preamble_end
preamble = decode(frame[0:preamble_end])
preamble_lines = LINE_END_RE.split(preamble)
preamble_len = len(preamble_lines)
f.body = frame[body_start:]
# Skip any leading newlines
first_line = 0
while first_line < preamble_len and len(preamble_lines[first_line]) == 0:
first_line += 1
if first_line >= preamble_len:
return None
# Extract frame type/command
f.cmd = preamble_lines[first_line]
# Put headers into a key/value map
f.headers = parse_headers(preamble_lines, first_line + 1)
return f | python | def parse_frame(frame):
"""
Parse a STOMP frame into a Frame object.
:param bytes frame: the frame received from the server (as a byte string)
:rtype: Frame
"""
f = Frame()
if frame == b'\x0a':
f.cmd = 'heartbeat'
return f
mat = PREAMBLE_END_RE.search(frame)
if mat:
preamble_end = mat.start()
body_start = mat.end()
else:
preamble_end = len(frame)
body_start = preamble_end
preamble = decode(frame[0:preamble_end])
preamble_lines = LINE_END_RE.split(preamble)
preamble_len = len(preamble_lines)
f.body = frame[body_start:]
# Skip any leading newlines
first_line = 0
while first_line < preamble_len and len(preamble_lines[first_line]) == 0:
first_line += 1
if first_line >= preamble_len:
return None
# Extract frame type/command
f.cmd = preamble_lines[first_line]
# Put headers into a key/value map
f.headers = parse_headers(preamble_lines, first_line + 1)
return f | [
"def",
"parse_frame",
"(",
"frame",
")",
":",
"f",
"=",
"Frame",
"(",
")",
"if",
"frame",
"==",
"b'\\x0a'",
":",
"f",
".",
"cmd",
"=",
"'heartbeat'",
"return",
"f",
"mat",
"=",
"PREAMBLE_END_RE",
".",
"search",
"(",
"frame",
")",
"if",
"mat",
":",
... | Parse a STOMP frame into a Frame object.
:param bytes frame: the frame received from the server (as a byte string)
:rtype: Frame | [
"Parse",
"a",
"STOMP",
"frame",
"into",
"a",
"Frame",
"object",
"."
] | 643843c5fbf25fd24339dd0e69a9411c3d8b94c7 | https://github.com/jasonrbriggs/stomp.py/blob/643843c5fbf25fd24339dd0e69a9411c3d8b94c7/stomp/utils.py#L125-L164 | train | 201,154 |
jasonrbriggs/stomp.py | stomp/utils.py | merge_headers | def merge_headers(header_map_list):
"""
Helper function for combining multiple header maps into one.
:param list(dict) header_map_list: list of maps
:rtype: dict
"""
headers = {}
for header_map in header_map_list:
if header_map:
headers.update(header_map)
return headers | python | def merge_headers(header_map_list):
"""
Helper function for combining multiple header maps into one.
:param list(dict) header_map_list: list of maps
:rtype: dict
"""
headers = {}
for header_map in header_map_list:
if header_map:
headers.update(header_map)
return headers | [
"def",
"merge_headers",
"(",
"header_map_list",
")",
":",
"headers",
"=",
"{",
"}",
"for",
"header_map",
"in",
"header_map_list",
":",
"if",
"header_map",
":",
"headers",
".",
"update",
"(",
"header_map",
")",
"return",
"headers"
] | Helper function for combining multiple header maps into one.
:param list(dict) header_map_list: list of maps
:rtype: dict | [
"Helper",
"function",
"for",
"combining",
"multiple",
"header",
"maps",
"into",
"one",
"."
] | 643843c5fbf25fd24339dd0e69a9411c3d8b94c7 | https://github.com/jasonrbriggs/stomp.py/blob/643843c5fbf25fd24339dd0e69a9411c3d8b94c7/stomp/utils.py#L167-L179 | train | 201,155 |
jasonrbriggs/stomp.py | stomp/utils.py | calculate_heartbeats | def calculate_heartbeats(shb, chb):
"""
Given a heartbeat string from the server, and a heartbeat tuple from the client,
calculate what the actual heartbeat settings should be.
:param (str,str) shb: server heartbeat numbers
:param (int,int) chb: client heartbeat numbers
:rtype: (int,int)
"""
(sx, sy) = shb
(cx, cy) = chb
x = 0
y = 0
if cx != 0 and sy != '0':
x = max(cx, int(sy))
if cy != 0 and sx != '0':
y = max(cy, int(sx))
return x, y | python | def calculate_heartbeats(shb, chb):
"""
Given a heartbeat string from the server, and a heartbeat tuple from the client,
calculate what the actual heartbeat settings should be.
:param (str,str) shb: server heartbeat numbers
:param (int,int) chb: client heartbeat numbers
:rtype: (int,int)
"""
(sx, sy) = shb
(cx, cy) = chb
x = 0
y = 0
if cx != 0 and sy != '0':
x = max(cx, int(sy))
if cy != 0 and sx != '0':
y = max(cy, int(sx))
return x, y | [
"def",
"calculate_heartbeats",
"(",
"shb",
",",
"chb",
")",
":",
"(",
"sx",
",",
"sy",
")",
"=",
"shb",
"(",
"cx",
",",
"cy",
")",
"=",
"chb",
"x",
"=",
"0",
"y",
"=",
"0",
"if",
"cx",
"!=",
"0",
"and",
"sy",
"!=",
"'0'",
":",
"x",
"=",
"... | Given a heartbeat string from the server, and a heartbeat tuple from the client,
calculate what the actual heartbeat settings should be.
:param (str,str) shb: server heartbeat numbers
:param (int,int) chb: client heartbeat numbers
:rtype: (int,int) | [
"Given",
"a",
"heartbeat",
"string",
"from",
"the",
"server",
"and",
"a",
"heartbeat",
"tuple",
"from",
"the",
"client",
"calculate",
"what",
"the",
"actual",
"heartbeat",
"settings",
"should",
"be",
"."
] | 643843c5fbf25fd24339dd0e69a9411c3d8b94c7 | https://github.com/jasonrbriggs/stomp.py/blob/643843c5fbf25fd24339dd0e69a9411c3d8b94c7/stomp/utils.py#L190-L208 | train | 201,156 |
jasonrbriggs/stomp.py | stomp/utils.py | convert_frame | def convert_frame(frame, body_encoding=None):
"""
Convert a frame to a list of lines separated by newlines.
:param Frame frame: the Frame object to convert
:rtype: list(str)
"""
lines = []
body = None
if frame.body:
if body_encoding:
body = encode(frame.body, body_encoding)
else:
body = encode(frame.body)
if HDR_CONTENT_LENGTH in frame.headers:
frame.headers[HDR_CONTENT_LENGTH] = len(body)
if frame.cmd:
lines.append(encode(frame.cmd))
lines.append(ENC_NEWLINE)
for key, vals in sorted(frame.headers.items()):
if vals is None:
continue
if type(vals) != tuple:
vals = (vals,)
for val in vals:
lines.append(encode("%s:%s\n" % (key, val)))
lines.append(ENC_NEWLINE)
if body:
lines.append(body)
if frame.cmd:
lines.append(ENC_NULL)
return lines | python | def convert_frame(frame, body_encoding=None):
"""
Convert a frame to a list of lines separated by newlines.
:param Frame frame: the Frame object to convert
:rtype: list(str)
"""
lines = []
body = None
if frame.body:
if body_encoding:
body = encode(frame.body, body_encoding)
else:
body = encode(frame.body)
if HDR_CONTENT_LENGTH in frame.headers:
frame.headers[HDR_CONTENT_LENGTH] = len(body)
if frame.cmd:
lines.append(encode(frame.cmd))
lines.append(ENC_NEWLINE)
for key, vals in sorted(frame.headers.items()):
if vals is None:
continue
if type(vals) != tuple:
vals = (vals,)
for val in vals:
lines.append(encode("%s:%s\n" % (key, val)))
lines.append(ENC_NEWLINE)
if body:
lines.append(body)
if frame.cmd:
lines.append(ENC_NULL)
return lines | [
"def",
"convert_frame",
"(",
"frame",
",",
"body_encoding",
"=",
"None",
")",
":",
"lines",
"=",
"[",
"]",
"body",
"=",
"None",
"if",
"frame",
".",
"body",
":",
"if",
"body_encoding",
":",
"body",
"=",
"encode",
"(",
"frame",
".",
"body",
",",
"body_... | Convert a frame to a list of lines separated by newlines.
:param Frame frame: the Frame object to convert
:rtype: list(str) | [
"Convert",
"a",
"frame",
"to",
"a",
"list",
"of",
"lines",
"separated",
"by",
"newlines",
"."
] | 643843c5fbf25fd24339dd0e69a9411c3d8b94c7 | https://github.com/jasonrbriggs/stomp.py/blob/643843c5fbf25fd24339dd0e69a9411c3d8b94c7/stomp/utils.py#L211-L247 | train | 201,157 |
jasonrbriggs/stomp.py | stomp/listener.py | HeartbeatListener.on_send | def on_send(self, frame):
"""
Add the heartbeat header to the frame when connecting, and bump
next outbound heartbeat timestamp.
:param Frame frame: the Frame object
"""
if frame.cmd == CMD_CONNECT or frame.cmd == CMD_STOMP:
if self.heartbeats != (0, 0):
frame.headers[HDR_HEARTBEAT] = '%s,%s' % self.heartbeats
if self.next_outbound_heartbeat is not None:
self.next_outbound_heartbeat = monotonic() + self.send_sleep | python | def on_send(self, frame):
"""
Add the heartbeat header to the frame when connecting, and bump
next outbound heartbeat timestamp.
:param Frame frame: the Frame object
"""
if frame.cmd == CMD_CONNECT or frame.cmd == CMD_STOMP:
if self.heartbeats != (0, 0):
frame.headers[HDR_HEARTBEAT] = '%s,%s' % self.heartbeats
if self.next_outbound_heartbeat is not None:
self.next_outbound_heartbeat = monotonic() + self.send_sleep | [
"def",
"on_send",
"(",
"self",
",",
"frame",
")",
":",
"if",
"frame",
".",
"cmd",
"==",
"CMD_CONNECT",
"or",
"frame",
".",
"cmd",
"==",
"CMD_STOMP",
":",
"if",
"self",
".",
"heartbeats",
"!=",
"(",
"0",
",",
"0",
")",
":",
"frame",
".",
"headers",
... | Add the heartbeat header to the frame when connecting, and bump
next outbound heartbeat timestamp.
:param Frame frame: the Frame object | [
"Add",
"the",
"heartbeat",
"header",
"to",
"the",
"frame",
"when",
"connecting",
"and",
"bump",
"next",
"outbound",
"heartbeat",
"timestamp",
"."
] | 643843c5fbf25fd24339dd0e69a9411c3d8b94c7 | https://github.com/jasonrbriggs/stomp.py/blob/643843c5fbf25fd24339dd0e69a9411c3d8b94c7/stomp/listener.py#L229-L240 | train | 201,158 |
jasonrbriggs/stomp.py | stomp/listener.py | WaitingListener.on_receipt | def on_receipt(self, headers, body):
"""
If the receipt id can be found in the headers, then notify the waiting thread.
:param dict headers: headers in the message
:param body: the message content
"""
if 'receipt-id' in headers and headers['receipt-id'] == self.receipt:
with self.receipt_condition:
self.received = True
self.receipt_condition.notify() | python | def on_receipt(self, headers, body):
"""
If the receipt id can be found in the headers, then notify the waiting thread.
:param dict headers: headers in the message
:param body: the message content
"""
if 'receipt-id' in headers and headers['receipt-id'] == self.receipt:
with self.receipt_condition:
self.received = True
self.receipt_condition.notify() | [
"def",
"on_receipt",
"(",
"self",
",",
"headers",
",",
"body",
")",
":",
"if",
"'receipt-id'",
"in",
"headers",
"and",
"headers",
"[",
"'receipt-id'",
"]",
"==",
"self",
".",
"receipt",
":",
"with",
"self",
".",
"receipt_condition",
":",
"self",
".",
"re... | If the receipt id can be found in the headers, then notify the waiting thread.
:param dict headers: headers in the message
:param body: the message content | [
"If",
"the",
"receipt",
"id",
"can",
"be",
"found",
"in",
"the",
"headers",
"then",
"notify",
"the",
"waiting",
"thread",
"."
] | 643843c5fbf25fd24339dd0e69a9411c3d8b94c7 | https://github.com/jasonrbriggs/stomp.py/blob/643843c5fbf25fd24339dd0e69a9411c3d8b94c7/stomp/listener.py#L323-L333 | train | 201,159 |
jasonrbriggs/stomp.py | stomp/listener.py | WaitingListener.wait_on_receipt | def wait_on_receipt(self):
"""
Wait until we receive a message receipt.
"""
with self.receipt_condition:
while not self.received:
self.receipt_condition.wait()
self.received = False | python | def wait_on_receipt(self):
"""
Wait until we receive a message receipt.
"""
with self.receipt_condition:
while not self.received:
self.receipt_condition.wait()
self.received = False | [
"def",
"wait_on_receipt",
"(",
"self",
")",
":",
"with",
"self",
".",
"receipt_condition",
":",
"while",
"not",
"self",
".",
"received",
":",
"self",
".",
"receipt_condition",
".",
"wait",
"(",
")",
"self",
".",
"received",
"=",
"False"
] | Wait until we receive a message receipt. | [
"Wait",
"until",
"we",
"receive",
"a",
"message",
"receipt",
"."
] | 643843c5fbf25fd24339dd0e69a9411c3d8b94c7 | https://github.com/jasonrbriggs/stomp.py/blob/643843c5fbf25fd24339dd0e69a9411c3d8b94c7/stomp/listener.py#L340-L347 | train | 201,160 |
jasonrbriggs/stomp.py | stomp/protocol.py | Protocol10.send_frame | def send_frame(self, cmd, headers=None, body=''):
"""
Encode and send a stomp frame
through the underlying transport.
:param str cmd: the protocol command
:param dict headers: a map of headers to include in the frame
:param body: the content of the message
"""
frame = utils.Frame(cmd, headers, body)
self.transport.transmit(frame) | python | def send_frame(self, cmd, headers=None, body=''):
"""
Encode and send a stomp frame
through the underlying transport.
:param str cmd: the protocol command
:param dict headers: a map of headers to include in the frame
:param body: the content of the message
"""
frame = utils.Frame(cmd, headers, body)
self.transport.transmit(frame) | [
"def",
"send_frame",
"(",
"self",
",",
"cmd",
",",
"headers",
"=",
"None",
",",
"body",
"=",
"''",
")",
":",
"frame",
"=",
"utils",
".",
"Frame",
"(",
"cmd",
",",
"headers",
",",
"body",
")",
"self",
".",
"transport",
".",
"transmit",
"(",
"frame",... | Encode and send a stomp frame
through the underlying transport.
:param str cmd: the protocol command
:param dict headers: a map of headers to include in the frame
:param body: the content of the message | [
"Encode",
"and",
"send",
"a",
"stomp",
"frame",
"through",
"the",
"underlying",
"transport",
"."
] | 643843c5fbf25fd24339dd0e69a9411c3d8b94c7 | https://github.com/jasonrbriggs/stomp.py/blob/643843c5fbf25fd24339dd0e69a9411c3d8b94c7/stomp/protocol.py#L28-L38 | train | 201,161 |
jasonrbriggs/stomp.py | stomp/protocol.py | Protocol10.abort | def abort(self, transaction, headers=None, **keyword_headers):
"""
Abort a transaction.
:param str transaction: the identifier of the transaction
:param dict headers: a map of any additional headers the broker requires
:param keyword_headers: any additional headers the broker requires
"""
assert transaction is not None, "'transaction' is required"
headers = utils.merge_headers([headers, keyword_headers])
headers[HDR_TRANSACTION] = transaction
self.send_frame(CMD_ABORT, headers) | python | def abort(self, transaction, headers=None, **keyword_headers):
"""
Abort a transaction.
:param str transaction: the identifier of the transaction
:param dict headers: a map of any additional headers the broker requires
:param keyword_headers: any additional headers the broker requires
"""
assert transaction is not None, "'transaction' is required"
headers = utils.merge_headers([headers, keyword_headers])
headers[HDR_TRANSACTION] = transaction
self.send_frame(CMD_ABORT, headers) | [
"def",
"abort",
"(",
"self",
",",
"transaction",
",",
"headers",
"=",
"None",
",",
"*",
"*",
"keyword_headers",
")",
":",
"assert",
"transaction",
"is",
"not",
"None",
",",
"\"'transaction' is required\"",
"headers",
"=",
"utils",
".",
"merge_headers",
"(",
... | Abort a transaction.
:param str transaction: the identifier of the transaction
:param dict headers: a map of any additional headers the broker requires
:param keyword_headers: any additional headers the broker requires | [
"Abort",
"a",
"transaction",
"."
] | 643843c5fbf25fd24339dd0e69a9411c3d8b94c7 | https://github.com/jasonrbriggs/stomp.py/blob/643843c5fbf25fd24339dd0e69a9411c3d8b94c7/stomp/protocol.py#L40-L51 | train | 201,162 |
jasonrbriggs/stomp.py | stomp/protocol.py | Protocol10.ack | def ack(self, id, transaction=None, receipt=None):
"""
Acknowledge 'consumption' of a message by id.
:param str id: identifier of the message
:param str transaction: include the acknowledgement in the specified transaction
"""
assert id is not None, "'id' is required"
headers = {HDR_MESSAGE_ID: id}
if transaction:
headers[HDR_TRANSACTION] = transaction
if receipt:
headers[HDR_RECEIPT] = receipt
self.send_frame(CMD_ACK, headers) | python | def ack(self, id, transaction=None, receipt=None):
"""
Acknowledge 'consumption' of a message by id.
:param str id: identifier of the message
:param str transaction: include the acknowledgement in the specified transaction
"""
assert id is not None, "'id' is required"
headers = {HDR_MESSAGE_ID: id}
if transaction:
headers[HDR_TRANSACTION] = transaction
if receipt:
headers[HDR_RECEIPT] = receipt
self.send_frame(CMD_ACK, headers) | [
"def",
"ack",
"(",
"self",
",",
"id",
",",
"transaction",
"=",
"None",
",",
"receipt",
"=",
"None",
")",
":",
"assert",
"id",
"is",
"not",
"None",
",",
"\"'id' is required\"",
"headers",
"=",
"{",
"HDR_MESSAGE_ID",
":",
"id",
"}",
"if",
"transaction",
... | Acknowledge 'consumption' of a message by id.
:param str id: identifier of the message
:param str transaction: include the acknowledgement in the specified transaction | [
"Acknowledge",
"consumption",
"of",
"a",
"message",
"by",
"id",
"."
] | 643843c5fbf25fd24339dd0e69a9411c3d8b94c7 | https://github.com/jasonrbriggs/stomp.py/blob/643843c5fbf25fd24339dd0e69a9411c3d8b94c7/stomp/protocol.py#L53-L66 | train | 201,163 |
jasonrbriggs/stomp.py | stomp/protocol.py | Protocol10.commit | def commit(self, transaction=None, headers=None, **keyword_headers):
"""
Commit a transaction.
:param str transaction: the identifier for the transaction
:param dict headers: a map of any additional headers the broker requires
:param keyword_headers: any additional headers the broker requires
"""
assert transaction is not None, "'transaction' is required"
headers = utils.merge_headers([headers, keyword_headers])
headers[HDR_TRANSACTION] = transaction
self.send_frame(CMD_COMMIT, headers) | python | def commit(self, transaction=None, headers=None, **keyword_headers):
"""
Commit a transaction.
:param str transaction: the identifier for the transaction
:param dict headers: a map of any additional headers the broker requires
:param keyword_headers: any additional headers the broker requires
"""
assert transaction is not None, "'transaction' is required"
headers = utils.merge_headers([headers, keyword_headers])
headers[HDR_TRANSACTION] = transaction
self.send_frame(CMD_COMMIT, headers) | [
"def",
"commit",
"(",
"self",
",",
"transaction",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"*",
"*",
"keyword_headers",
")",
":",
"assert",
"transaction",
"is",
"not",
"None",
",",
"\"'transaction' is required\"",
"headers",
"=",
"utils",
".",
"merge_h... | Commit a transaction.
:param str transaction: the identifier for the transaction
:param dict headers: a map of any additional headers the broker requires
:param keyword_headers: any additional headers the broker requires | [
"Commit",
"a",
"transaction",
"."
] | 643843c5fbf25fd24339dd0e69a9411c3d8b94c7 | https://github.com/jasonrbriggs/stomp.py/blob/643843c5fbf25fd24339dd0e69a9411c3d8b94c7/stomp/protocol.py#L87-L98 | train | 201,164 |
jasonrbriggs/stomp.py | stomp/protocol.py | Protocol10.send | def send(self, destination, body, content_type=None, headers=None, **keyword_headers):
"""
Send a message to a destination.
:param str destination: the destination of the message (e.g. queue or topic name)
:param body: the content of the message
:param str content_type: the content type of the message
:param dict headers: a map of any additional headers the broker requires
:param keyword_headers: any additional headers the broker requires
"""
assert destination is not None, "'destination' is required"
assert body is not None, "'body' is required"
headers = utils.merge_headers([headers, keyword_headers])
headers[HDR_DESTINATION] = destination
if content_type:
headers[HDR_CONTENT_TYPE] = content_type
if self.auto_content_length and body and HDR_CONTENT_LENGTH not in headers:
headers[HDR_CONTENT_LENGTH] = len(body)
self.send_frame(CMD_SEND, headers, body) | python | def send(self, destination, body, content_type=None, headers=None, **keyword_headers):
"""
Send a message to a destination.
:param str destination: the destination of the message (e.g. queue or topic name)
:param body: the content of the message
:param str content_type: the content type of the message
:param dict headers: a map of any additional headers the broker requires
:param keyword_headers: any additional headers the broker requires
"""
assert destination is not None, "'destination' is required"
assert body is not None, "'body' is required"
headers = utils.merge_headers([headers, keyword_headers])
headers[HDR_DESTINATION] = destination
if content_type:
headers[HDR_CONTENT_TYPE] = content_type
if self.auto_content_length and body and HDR_CONTENT_LENGTH not in headers:
headers[HDR_CONTENT_LENGTH] = len(body)
self.send_frame(CMD_SEND, headers, body) | [
"def",
"send",
"(",
"self",
",",
"destination",
",",
"body",
",",
"content_type",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"*",
"*",
"keyword_headers",
")",
":",
"assert",
"destination",
"is",
"not",
"None",
",",
"\"'destination' is required\"",
"asser... | Send a message to a destination.
:param str destination: the destination of the message (e.g. queue or topic name)
:param body: the content of the message
:param str content_type: the content type of the message
:param dict headers: a map of any additional headers the broker requires
:param keyword_headers: any additional headers the broker requires | [
"Send",
"a",
"message",
"to",
"a",
"destination",
"."
] | 643843c5fbf25fd24339dd0e69a9411c3d8b94c7 | https://github.com/jasonrbriggs/stomp.py/blob/643843c5fbf25fd24339dd0e69a9411c3d8b94c7/stomp/protocol.py#L146-L164 | train | 201,165 |
jasonrbriggs/stomp.py | stomp/protocol.py | Protocol10.subscribe | def subscribe(self, destination, id=None, ack='auto', headers=None, **keyword_headers):
"""
Subscribe to a destination.
:param str destination: the topic or queue to subscribe to
:param str id: a unique id to represent the subscription
:param str ack: acknowledgement mode, either auto, client, or client-individual
(see http://stomp.github.io/stomp-specification-1.2.html#SUBSCRIBE_ack_Header)
for more information
:param dict headers: a map of any additional headers the broker requires
:param keyword_headers: any additional headers the broker requires
"""
assert destination is not None, "'destination' is required"
headers = utils.merge_headers([headers, keyword_headers])
headers[HDR_DESTINATION] = destination
if id:
headers[HDR_ID] = id
headers[HDR_ACK] = ack
self.send_frame(CMD_SUBSCRIBE, headers) | python | def subscribe(self, destination, id=None, ack='auto', headers=None, **keyword_headers):
"""
Subscribe to a destination.
:param str destination: the topic or queue to subscribe to
:param str id: a unique id to represent the subscription
:param str ack: acknowledgement mode, either auto, client, or client-individual
(see http://stomp.github.io/stomp-specification-1.2.html#SUBSCRIBE_ack_Header)
for more information
:param dict headers: a map of any additional headers the broker requires
:param keyword_headers: any additional headers the broker requires
"""
assert destination is not None, "'destination' is required"
headers = utils.merge_headers([headers, keyword_headers])
headers[HDR_DESTINATION] = destination
if id:
headers[HDR_ID] = id
headers[HDR_ACK] = ack
self.send_frame(CMD_SUBSCRIBE, headers) | [
"def",
"subscribe",
"(",
"self",
",",
"destination",
",",
"id",
"=",
"None",
",",
"ack",
"=",
"'auto'",
",",
"headers",
"=",
"None",
",",
"*",
"*",
"keyword_headers",
")",
":",
"assert",
"destination",
"is",
"not",
"None",
",",
"\"'destination' is required... | Subscribe to a destination.
:param str destination: the topic or queue to subscribe to
:param str id: a unique id to represent the subscription
:param str ack: acknowledgement mode, either auto, client, or client-individual
(see http://stomp.github.io/stomp-specification-1.2.html#SUBSCRIBE_ack_Header)
for more information
:param dict headers: a map of any additional headers the broker requires
:param keyword_headers: any additional headers the broker requires | [
"Subscribe",
"to",
"a",
"destination",
"."
] | 643843c5fbf25fd24339dd0e69a9411c3d8b94c7 | https://github.com/jasonrbriggs/stomp.py/blob/643843c5fbf25fd24339dd0e69a9411c3d8b94c7/stomp/protocol.py#L166-L184 | train | 201,166 |
jasonrbriggs/stomp.py | stomp/protocol.py | Protocol10.unsubscribe | def unsubscribe(self, destination=None, id=None, headers=None, **keyword_headers):
"""
Unsubscribe from a destination by either id or the destination name.
:param str destination: the name of the topic or queue to unsubscribe from
:param str id: the unique identifier of the topic or queue to unsubscribe from
:param dict headers: a map of any additional headers the broker requires
:param keyword_headers: any additional headers the broker requires
"""
assert id is not None or destination is not None, "'id' or 'destination' is required"
headers = utils.merge_headers([headers, keyword_headers])
if id:
headers[HDR_ID] = id
if destination:
headers[HDR_DESTINATION] = destination
self.send_frame(CMD_UNSUBSCRIBE, headers) | python | def unsubscribe(self, destination=None, id=None, headers=None, **keyword_headers):
"""
Unsubscribe from a destination by either id or the destination name.
:param str destination: the name of the topic or queue to unsubscribe from
:param str id: the unique identifier of the topic or queue to unsubscribe from
:param dict headers: a map of any additional headers the broker requires
:param keyword_headers: any additional headers the broker requires
"""
assert id is not None or destination is not None, "'id' or 'destination' is required"
headers = utils.merge_headers([headers, keyword_headers])
if id:
headers[HDR_ID] = id
if destination:
headers[HDR_DESTINATION] = destination
self.send_frame(CMD_UNSUBSCRIBE, headers) | [
"def",
"unsubscribe",
"(",
"self",
",",
"destination",
"=",
"None",
",",
"id",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"*",
"*",
"keyword_headers",
")",
":",
"assert",
"id",
"is",
"not",
"None",
"or",
"destination",
"is",
"not",
"None",
",",
"... | Unsubscribe from a destination by either id or the destination name.
:param str destination: the name of the topic or queue to unsubscribe from
:param str id: the unique identifier of the topic or queue to unsubscribe from
:param dict headers: a map of any additional headers the broker requires
:param keyword_headers: any additional headers the broker requires | [
"Unsubscribe",
"from",
"a",
"destination",
"by",
"either",
"id",
"or",
"the",
"destination",
"name",
"."
] | 643843c5fbf25fd24339dd0e69a9411c3d8b94c7 | https://github.com/jasonrbriggs/stomp.py/blob/643843c5fbf25fd24339dd0e69a9411c3d8b94c7/stomp/protocol.py#L186-L201 | train | 201,167 |
jasonrbriggs/stomp.py | stomp/protocol.py | Protocol11.connect | def connect(self, username=None, passcode=None, wait=False, headers=None, **keyword_headers):
"""
Start a connection.
:param str username: the username to connect with
:param str passcode: the password used to authenticate with
:param bool wait: if True, wait for the connection to be established/acknowledged
:param dict headers: a map of any additional headers the broker requires
:param keyword_headers: any additional headers the broker requires
"""
cmd = CMD_STOMP
headers = utils.merge_headers([headers, keyword_headers])
headers[HDR_ACCEPT_VERSION] = self.version
if self.transport.vhost:
headers[HDR_HOST] = self.transport.vhost
if username is not None:
headers[HDR_LOGIN] = username
if passcode is not None:
headers[HDR_PASSCODE] = passcode
self.send_frame(cmd, headers)
if wait:
self.transport.wait_for_connection()
if self.transport.connection_error:
raise ConnectFailedException() | python | def connect(self, username=None, passcode=None, wait=False, headers=None, **keyword_headers):
"""
Start a connection.
:param str username: the username to connect with
:param str passcode: the password used to authenticate with
:param bool wait: if True, wait for the connection to be established/acknowledged
:param dict headers: a map of any additional headers the broker requires
:param keyword_headers: any additional headers the broker requires
"""
cmd = CMD_STOMP
headers = utils.merge_headers([headers, keyword_headers])
headers[HDR_ACCEPT_VERSION] = self.version
if self.transport.vhost:
headers[HDR_HOST] = self.transport.vhost
if username is not None:
headers[HDR_LOGIN] = username
if passcode is not None:
headers[HDR_PASSCODE] = passcode
self.send_frame(cmd, headers)
if wait:
self.transport.wait_for_connection()
if self.transport.connection_error:
raise ConnectFailedException() | [
"def",
"connect",
"(",
"self",
",",
"username",
"=",
"None",
",",
"passcode",
"=",
"None",
",",
"wait",
"=",
"False",
",",
"headers",
"=",
"None",
",",
"*",
"*",
"keyword_headers",
")",
":",
"cmd",
"=",
"CMD_STOMP",
"headers",
"=",
"utils",
".",
"mer... | Start a connection.
:param str username: the username to connect with
:param str passcode: the password used to authenticate with
:param bool wait: if True, wait for the connection to be established/acknowledged
:param dict headers: a map of any additional headers the broker requires
:param keyword_headers: any additional headers the broker requires | [
"Start",
"a",
"connection",
"."
] | 643843c5fbf25fd24339dd0e69a9411c3d8b94c7 | https://github.com/jasonrbriggs/stomp.py/blob/643843c5fbf25fd24339dd0e69a9411c3d8b94c7/stomp/protocol.py#L312-L340 | train | 201,168 |
jasonrbriggs/stomp.py | stomp/backwardsock25.py | get_socket | def get_socket(host, port, timeout=None):
"""
Return a socket.
:param str host: the hostname to connect to
:param int port: the port number to connect to
:param timeout: if specified, set the socket timeout
"""
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
af, socktype, proto, canonname, sa = res
sock = None
try:
sock = socket(af, socktype, proto)
if timeout is not None:
sock.settimeout(timeout)
sock.connect(sa)
return sock
except error:
if sock is not None:
sock.close()
raise error | python | def get_socket(host, port, timeout=None):
"""
Return a socket.
:param str host: the hostname to connect to
:param int port: the port number to connect to
:param timeout: if specified, set the socket timeout
"""
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
af, socktype, proto, canonname, sa = res
sock = None
try:
sock = socket(af, socktype, proto)
if timeout is not None:
sock.settimeout(timeout)
sock.connect(sa)
return sock
except error:
if sock is not None:
sock.close()
raise error | [
"def",
"get_socket",
"(",
"host",
",",
"port",
",",
"timeout",
"=",
"None",
")",
":",
"for",
"res",
"in",
"getaddrinfo",
"(",
"host",
",",
"port",
",",
"0",
",",
"SOCK_STREAM",
")",
":",
"af",
",",
"socktype",
",",
"proto",
",",
"canonname",
",",
"... | Return a socket.
:param str host: the hostname to connect to
:param int port: the port number to connect to
:param timeout: if specified, set the socket timeout | [
"Return",
"a",
"socket",
"."
] | 643843c5fbf25fd24339dd0e69a9411c3d8b94c7 | https://github.com/jasonrbriggs/stomp.py/blob/643843c5fbf25fd24339dd0e69a9411c3d8b94c7/stomp/backwardsock25.py#L8-L30 | train | 201,169 |
jasonrbriggs/stomp.py | stomp/transport.py | BaseTransport.start | def start(self):
"""
Start the connection. This should be called after all
listeners have been registered. If this method is not called,
no frames will be received by the connection.
"""
self.running = True
self.attempt_connection()
receiver_thread = self.create_thread_fc(self.__receiver_loop)
receiver_thread.name = "StompReceiver%s" % getattr(receiver_thread, "name", "Thread")
self.notify('connecting') | python | def start(self):
"""
Start the connection. This should be called after all
listeners have been registered. If this method is not called,
no frames will be received by the connection.
"""
self.running = True
self.attempt_connection()
receiver_thread = self.create_thread_fc(self.__receiver_loop)
receiver_thread.name = "StompReceiver%s" % getattr(receiver_thread, "name", "Thread")
self.notify('connecting') | [
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"running",
"=",
"True",
"self",
".",
"attempt_connection",
"(",
")",
"receiver_thread",
"=",
"self",
".",
"create_thread_fc",
"(",
"self",
".",
"__receiver_loop",
")",
"receiver_thread",
".",
"name",
"=",
... | Start the connection. This should be called after all
listeners have been registered. If this method is not called,
no frames will be received by the connection. | [
"Start",
"the",
"connection",
".",
"This",
"should",
"be",
"called",
"after",
"all",
"listeners",
"have",
"been",
"registered",
".",
"If",
"this",
"method",
"is",
"not",
"called",
"no",
"frames",
"will",
"be",
"received",
"by",
"the",
"connection",
"."
] | 643843c5fbf25fd24339dd0e69a9411c3d8b94c7 | https://github.com/jasonrbriggs/stomp.py/blob/643843c5fbf25fd24339dd0e69a9411c3d8b94c7/stomp/transport.py#L103-L113 | train | 201,170 |
jasonrbriggs/stomp.py | stomp/transport.py | BaseTransport.stop | def stop(self):
"""
Stop the connection. Performs a clean shutdown by waiting for the
receiver thread to exit.
"""
with self.__receiver_thread_exit_condition:
while not self.__receiver_thread_exited and self.is_connected():
self.__receiver_thread_exit_condition.wait() | python | def stop(self):
"""
Stop the connection. Performs a clean shutdown by waiting for the
receiver thread to exit.
"""
with self.__receiver_thread_exit_condition:
while not self.__receiver_thread_exited and self.is_connected():
self.__receiver_thread_exit_condition.wait() | [
"def",
"stop",
"(",
"self",
")",
":",
"with",
"self",
".",
"__receiver_thread_exit_condition",
":",
"while",
"not",
"self",
".",
"__receiver_thread_exited",
"and",
"self",
".",
"is_connected",
"(",
")",
":",
"self",
".",
"__receiver_thread_exit_condition",
".",
... | Stop the connection. Performs a clean shutdown by waiting for the
receiver thread to exit. | [
"Stop",
"the",
"connection",
".",
"Performs",
"a",
"clean",
"shutdown",
"by",
"waiting",
"for",
"the",
"receiver",
"thread",
"to",
"exit",
"."
] | 643843c5fbf25fd24339dd0e69a9411c3d8b94c7 | https://github.com/jasonrbriggs/stomp.py/blob/643843c5fbf25fd24339dd0e69a9411c3d8b94c7/stomp/transport.py#L115-L122 | train | 201,171 |
jasonrbriggs/stomp.py | stomp/transport.py | BaseTransport.notify | def notify(self, frame_type, headers=None, body=None):
"""
Utility function for notifying listeners of incoming and outgoing messages
:param str frame_type: the type of message
:param dict headers: the map of headers associated with the message
:param body: the content of the message
"""
if frame_type == 'receipt':
# logic for wait-on-receipt notification
receipt = headers['receipt-id']
receipt_value = self.__receipts.get(receipt)
with self.__send_wait_condition:
self.set_receipt(receipt, None)
self.__send_wait_condition.notify()
if receipt_value == CMD_DISCONNECT:
self.set_connected(False)
# received a stomp 1.1+ disconnect receipt
if receipt == self.__disconnect_receipt:
self.disconnect_socket()
self.__disconnect_receipt = None
elif frame_type == 'connected':
self.set_connected(True)
elif frame_type == 'disconnected':
self.set_connected(False)
with self.__listeners_change_condition:
listeners = sorted(self.listeners.items())
for (_, listener) in listeners:
if not listener:
continue
notify_func = getattr(listener, 'on_%s' % frame_type, None)
if not notify_func:
log.debug("listener %s has no method on_%s", listener, frame_type)
continue
if frame_type in ('heartbeat', 'disconnected'):
notify_func()
continue
if frame_type == 'connecting':
notify_func(self.current_host_and_port)
continue
if frame_type == 'error' and not self.connected:
with self.__connect_wait_condition:
self.connection_error = True
self.__connect_wait_condition.notify()
rtn = notify_func(headers, body)
if rtn:
(headers, body) = rtn
return (headers, body) | python | def notify(self, frame_type, headers=None, body=None):
"""
Utility function for notifying listeners of incoming and outgoing messages
:param str frame_type: the type of message
:param dict headers: the map of headers associated with the message
:param body: the content of the message
"""
if frame_type == 'receipt':
# logic for wait-on-receipt notification
receipt = headers['receipt-id']
receipt_value = self.__receipts.get(receipt)
with self.__send_wait_condition:
self.set_receipt(receipt, None)
self.__send_wait_condition.notify()
if receipt_value == CMD_DISCONNECT:
self.set_connected(False)
# received a stomp 1.1+ disconnect receipt
if receipt == self.__disconnect_receipt:
self.disconnect_socket()
self.__disconnect_receipt = None
elif frame_type == 'connected':
self.set_connected(True)
elif frame_type == 'disconnected':
self.set_connected(False)
with self.__listeners_change_condition:
listeners = sorted(self.listeners.items())
for (_, listener) in listeners:
if not listener:
continue
notify_func = getattr(listener, 'on_%s' % frame_type, None)
if not notify_func:
log.debug("listener %s has no method on_%s", listener, frame_type)
continue
if frame_type in ('heartbeat', 'disconnected'):
notify_func()
continue
if frame_type == 'connecting':
notify_func(self.current_host_and_port)
continue
if frame_type == 'error' and not self.connected:
with self.__connect_wait_condition:
self.connection_error = True
self.__connect_wait_condition.notify()
rtn = notify_func(headers, body)
if rtn:
(headers, body) = rtn
return (headers, body) | [
"def",
"notify",
"(",
"self",
",",
"frame_type",
",",
"headers",
"=",
"None",
",",
"body",
"=",
"None",
")",
":",
"if",
"frame_type",
"==",
"'receipt'",
":",
"# logic for wait-on-receipt notification",
"receipt",
"=",
"headers",
"[",
"'receipt-id'",
"]",
"rece... | Utility function for notifying listeners of incoming and outgoing messages
:param str frame_type: the type of message
:param dict headers: the map of headers associated with the message
:param body: the content of the message | [
"Utility",
"function",
"for",
"notifying",
"listeners",
"of",
"incoming",
"and",
"outgoing",
"messages"
] | 643843c5fbf25fd24339dd0e69a9411c3d8b94c7 | https://github.com/jasonrbriggs/stomp.py/blob/643843c5fbf25fd24339dd0e69a9411c3d8b94c7/stomp/transport.py#L196-L251 | train | 201,172 |
jasonrbriggs/stomp.py | stomp/transport.py | BaseTransport.transmit | def transmit(self, frame):
"""
Convert a frame object to a frame string and transmit to the server.
:param Frame frame: the Frame object to transmit
"""
with self.__listeners_change_condition:
listeners = sorted(self.listeners.items())
for (_, listener) in listeners:
if not listener:
continue
try:
listener.on_send(frame)
except AttributeError:
continue
if frame.cmd == CMD_DISCONNECT and HDR_RECEIPT in frame.headers:
self.__disconnect_receipt = frame.headers[HDR_RECEIPT]
lines = utils.convert_frame(frame)
packed_frame = pack(lines)
if log.isEnabledFor(logging.DEBUG):
log.debug("Sending frame: %s", lines)
else:
log.info("Sending frame: %r", frame.cmd or "heartbeat")
self.send(packed_frame) | python | def transmit(self, frame):
"""
Convert a frame object to a frame string and transmit to the server.
:param Frame frame: the Frame object to transmit
"""
with self.__listeners_change_condition:
listeners = sorted(self.listeners.items())
for (_, listener) in listeners:
if not listener:
continue
try:
listener.on_send(frame)
except AttributeError:
continue
if frame.cmd == CMD_DISCONNECT and HDR_RECEIPT in frame.headers:
self.__disconnect_receipt = frame.headers[HDR_RECEIPT]
lines = utils.convert_frame(frame)
packed_frame = pack(lines)
if log.isEnabledFor(logging.DEBUG):
log.debug("Sending frame: %s", lines)
else:
log.info("Sending frame: %r", frame.cmd or "heartbeat")
self.send(packed_frame) | [
"def",
"transmit",
"(",
"self",
",",
"frame",
")",
":",
"with",
"self",
".",
"__listeners_change_condition",
":",
"listeners",
"=",
"sorted",
"(",
"self",
".",
"listeners",
".",
"items",
"(",
")",
")",
"for",
"(",
"_",
",",
"listener",
")",
"in",
"list... | Convert a frame object to a frame string and transmit to the server.
:param Frame frame: the Frame object to transmit | [
"Convert",
"a",
"frame",
"object",
"to",
"a",
"frame",
"string",
"and",
"transmit",
"to",
"the",
"server",
"."
] | 643843c5fbf25fd24339dd0e69a9411c3d8b94c7 | https://github.com/jasonrbriggs/stomp.py/blob/643843c5fbf25fd24339dd0e69a9411c3d8b94c7/stomp/transport.py#L253-L280 | train | 201,173 |
jasonrbriggs/stomp.py | stomp/transport.py | BaseTransport.wait_for_connection | def wait_for_connection(self, timeout=None):
"""
Wait until we've established a connection with the server.
:param float timeout: how long to wait, in seconds
"""
if timeout is not None:
wait_time = timeout / 10.0
else:
wait_time = None
with self.__connect_wait_condition:
while self.running and not self.is_connected() and not self.connection_error:
self.__connect_wait_condition.wait(wait_time)
if not self.running or not self.is_connected():
raise exception.ConnectFailedException() | python | def wait_for_connection(self, timeout=None):
"""
Wait until we've established a connection with the server.
:param float timeout: how long to wait, in seconds
"""
if timeout is not None:
wait_time = timeout / 10.0
else:
wait_time = None
with self.__connect_wait_condition:
while self.running and not self.is_connected() and not self.connection_error:
self.__connect_wait_condition.wait(wait_time)
if not self.running or not self.is_connected():
raise exception.ConnectFailedException() | [
"def",
"wait_for_connection",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"timeout",
"is",
"not",
"None",
":",
"wait_time",
"=",
"timeout",
"/",
"10.0",
"else",
":",
"wait_time",
"=",
"None",
"with",
"self",
".",
"__connect_wait_condition",
"... | Wait until we've established a connection with the server.
:param float timeout: how long to wait, in seconds | [
"Wait",
"until",
"we",
"ve",
"established",
"a",
"connection",
"with",
"the",
"server",
"."
] | 643843c5fbf25fd24339dd0e69a9411c3d8b94c7 | https://github.com/jasonrbriggs/stomp.py/blob/643843c5fbf25fd24339dd0e69a9411c3d8b94c7/stomp/transport.py#L315-L329 | train | 201,174 |
jasonrbriggs/stomp.py | stomp/transport.py | BaseTransport.__receiver_loop | def __receiver_loop(self):
"""
Main loop listening for incoming data.
"""
log.info("Starting receiver loop")
notify_disconnected = True
try:
while self.running:
try:
while self.running:
frames = self.__read()
for frame in frames:
f = utils.parse_frame(frame)
if f is None:
continue
if self.__auto_decode:
f.body = decode(f.body)
self.process_frame(f, frame)
except exception.ConnectionClosedException:
if self.running:
#
# Clear out any half-received messages after losing connection
#
self.__recvbuf = b''
self.running = False
notify_disconnected = True
break
finally:
self.cleanup()
finally:
with self.__receiver_thread_exit_condition:
self.__receiver_thread_exited = True
self.__receiver_thread_exit_condition.notifyAll()
log.info("Receiver loop ended")
self.notify('receiver_loop_completed')
if notify_disconnected:
self.notify('disconnected')
with self.__connect_wait_condition:
self.__connect_wait_condition.notifyAll() | python | def __receiver_loop(self):
"""
Main loop listening for incoming data.
"""
log.info("Starting receiver loop")
notify_disconnected = True
try:
while self.running:
try:
while self.running:
frames = self.__read()
for frame in frames:
f = utils.parse_frame(frame)
if f is None:
continue
if self.__auto_decode:
f.body = decode(f.body)
self.process_frame(f, frame)
except exception.ConnectionClosedException:
if self.running:
#
# Clear out any half-received messages after losing connection
#
self.__recvbuf = b''
self.running = False
notify_disconnected = True
break
finally:
self.cleanup()
finally:
with self.__receiver_thread_exit_condition:
self.__receiver_thread_exited = True
self.__receiver_thread_exit_condition.notifyAll()
log.info("Receiver loop ended")
self.notify('receiver_loop_completed')
if notify_disconnected:
self.notify('disconnected')
with self.__connect_wait_condition:
self.__connect_wait_condition.notifyAll() | [
"def",
"__receiver_loop",
"(",
"self",
")",
":",
"log",
".",
"info",
"(",
"\"Starting receiver loop\"",
")",
"notify_disconnected",
"=",
"True",
"try",
":",
"while",
"self",
".",
"running",
":",
"try",
":",
"while",
"self",
".",
"running",
":",
"frames",
"... | Main loop listening for incoming data. | [
"Main",
"loop",
"listening",
"for",
"incoming",
"data",
"."
] | 643843c5fbf25fd24339dd0e69a9411c3d8b94c7 | https://github.com/jasonrbriggs/stomp.py/blob/643843c5fbf25fd24339dd0e69a9411c3d8b94c7/stomp/transport.py#L331-L370 | train | 201,175 |
jasonrbriggs/stomp.py | stomp/transport.py | Transport.is_connected | def is_connected(self):
"""
Return true if the socket managed by this connection is connected
:rtype: bool
"""
try:
return self.socket is not None and self.socket.getsockname()[1] != 0 and BaseTransport.is_connected(self)
except socket.error:
return False | python | def is_connected(self):
"""
Return true if the socket managed by this connection is connected
:rtype: bool
"""
try:
return self.socket is not None and self.socket.getsockname()[1] != 0 and BaseTransport.is_connected(self)
except socket.error:
return False | [
"def",
"is_connected",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"socket",
"is",
"not",
"None",
"and",
"self",
".",
"socket",
".",
"getsockname",
"(",
")",
"[",
"1",
"]",
"!=",
"0",
"and",
"BaseTransport",
".",
"is_connected",
"(",
"s... | Return true if the socket managed by this connection is connected
:rtype: bool | [
"Return",
"true",
"if",
"the",
"socket",
"managed",
"by",
"this",
"connection",
"is",
"connected"
] | 643843c5fbf25fd24339dd0e69a9411c3d8b94c7 | https://github.com/jasonrbriggs/stomp.py/blob/643843c5fbf25fd24339dd0e69a9411c3d8b94c7/stomp/transport.py#L578-L587 | train | 201,176 |
jasonrbriggs/stomp.py | stomp/transport.py | Transport.disconnect_socket | def disconnect_socket(self):
"""
Disconnect the underlying socket connection
"""
self.running = False
if self.socket is not None:
if self.__need_ssl():
#
# Even though we don't want to use the socket, unwrap is the only API method which does a proper SSL
# shutdown
#
try:
self.socket = self.socket.unwrap()
except Exception:
#
# unwrap seems flaky on Win with the back-ported ssl mod, so catch any exception and log it
#
_, e, _ = sys.exc_info()
log.warning(e)
elif hasattr(socket, 'SHUT_RDWR'):
try:
self.socket.shutdown(socket.SHUT_RDWR)
except socket.error:
_, e, _ = sys.exc_info()
# ignore when socket already closed
if get_errno(e) != errno.ENOTCONN:
log.warning("Unable to issue SHUT_RDWR on socket because of error '%s'", e)
#
# split this into a separate check, because sometimes the socket is nulled between shutdown and this call
#
if self.socket is not None:
try:
self.socket.close()
except socket.error:
_, e, _ = sys.exc_info()
log.warning("Unable to close socket because of error '%s'", e)
self.current_host_and_port = None
self.socket = None
self.notify('disconnected') | python | def disconnect_socket(self):
"""
Disconnect the underlying socket connection
"""
self.running = False
if self.socket is not None:
if self.__need_ssl():
#
# Even though we don't want to use the socket, unwrap is the only API method which does a proper SSL
# shutdown
#
try:
self.socket = self.socket.unwrap()
except Exception:
#
# unwrap seems flaky on Win with the back-ported ssl mod, so catch any exception and log it
#
_, e, _ = sys.exc_info()
log.warning(e)
elif hasattr(socket, 'SHUT_RDWR'):
try:
self.socket.shutdown(socket.SHUT_RDWR)
except socket.error:
_, e, _ = sys.exc_info()
# ignore when socket already closed
if get_errno(e) != errno.ENOTCONN:
log.warning("Unable to issue SHUT_RDWR on socket because of error '%s'", e)
#
# split this into a separate check, because sometimes the socket is nulled between shutdown and this call
#
if self.socket is not None:
try:
self.socket.close()
except socket.error:
_, e, _ = sys.exc_info()
log.warning("Unable to close socket because of error '%s'", e)
self.current_host_and_port = None
self.socket = None
self.notify('disconnected') | [
"def",
"disconnect_socket",
"(",
"self",
")",
":",
"self",
".",
"running",
"=",
"False",
"if",
"self",
".",
"socket",
"is",
"not",
"None",
":",
"if",
"self",
".",
"__need_ssl",
"(",
")",
":",
"#",
"# Even though we don't want to use the socket, unwrap is the onl... | Disconnect the underlying socket connection | [
"Disconnect",
"the",
"underlying",
"socket",
"connection"
] | 643843c5fbf25fd24339dd0e69a9411c3d8b94c7 | https://github.com/jasonrbriggs/stomp.py/blob/643843c5fbf25fd24339dd0e69a9411c3d8b94c7/stomp/transport.py#L589-L628 | train | 201,177 |
jasonrbriggs/stomp.py | stomp/transport.py | Transport.set_ssl | def set_ssl(self,
for_hosts=[],
key_file=None,
cert_file=None,
ca_certs=None,
cert_validator=None,
ssl_version=DEFAULT_SSL_VERSION,
password=None):
"""
Sets up SSL configuration for the given hosts. This ensures socket is wrapped in a SSL connection, raising an
exception if the SSL module can't be found.
:param for_hosts: a list of tuples describing hosts this SSL configuration should be applied to
:param cert_file: the path to a X509 certificate
:param key_file: the path to a X509 key file
:param ca_certs: the path to the a file containing CA certificates to validate the server against.
If this is not set, server side certificate validation is not done.
:param cert_validator: function which performs extra validation on the client certificate, for example
checking the returned certificate has a commonName attribute equal to the
hostname (to avoid man in the middle attacks).
The signature is: (OK, err_msg) = validation_function(cert, hostname)
where OK is a boolean, and cert is a certificate structure
as returned by ssl.SSLSocket.getpeercert()
:param ssl_version: SSL protocol to use for the connection. This should be one of the PROTOCOL_x
constants provided by the ssl module. The default is ssl.PROTOCOL_TLSv1
"""
if not ssl:
raise Exception("SSL connection requested, but SSL library not found")
for host_port in for_hosts:
self.__ssl_params[host_port] = dict(key_file=key_file,
cert_file=cert_file,
ca_certs=ca_certs,
cert_validator=cert_validator,
ssl_version=ssl_version,
password=password) | python | def set_ssl(self,
for_hosts=[],
key_file=None,
cert_file=None,
ca_certs=None,
cert_validator=None,
ssl_version=DEFAULT_SSL_VERSION,
password=None):
"""
Sets up SSL configuration for the given hosts. This ensures socket is wrapped in a SSL connection, raising an
exception if the SSL module can't be found.
:param for_hosts: a list of tuples describing hosts this SSL configuration should be applied to
:param cert_file: the path to a X509 certificate
:param key_file: the path to a X509 key file
:param ca_certs: the path to the a file containing CA certificates to validate the server against.
If this is not set, server side certificate validation is not done.
:param cert_validator: function which performs extra validation on the client certificate, for example
checking the returned certificate has a commonName attribute equal to the
hostname (to avoid man in the middle attacks).
The signature is: (OK, err_msg) = validation_function(cert, hostname)
where OK is a boolean, and cert is a certificate structure
as returned by ssl.SSLSocket.getpeercert()
:param ssl_version: SSL protocol to use for the connection. This should be one of the PROTOCOL_x
constants provided by the ssl module. The default is ssl.PROTOCOL_TLSv1
"""
if not ssl:
raise Exception("SSL connection requested, but SSL library not found")
for host_port in for_hosts:
self.__ssl_params[host_port] = dict(key_file=key_file,
cert_file=cert_file,
ca_certs=ca_certs,
cert_validator=cert_validator,
ssl_version=ssl_version,
password=password) | [
"def",
"set_ssl",
"(",
"self",
",",
"for_hosts",
"=",
"[",
"]",
",",
"key_file",
"=",
"None",
",",
"cert_file",
"=",
"None",
",",
"ca_certs",
"=",
"None",
",",
"cert_validator",
"=",
"None",
",",
"ssl_version",
"=",
"DEFAULT_SSL_VERSION",
",",
"password",
... | Sets up SSL configuration for the given hosts. This ensures socket is wrapped in a SSL connection, raising an
exception if the SSL module can't be found.
:param for_hosts: a list of tuples describing hosts this SSL configuration should be applied to
:param cert_file: the path to a X509 certificate
:param key_file: the path to a X509 key file
:param ca_certs: the path to the a file containing CA certificates to validate the server against.
If this is not set, server side certificate validation is not done.
:param cert_validator: function which performs extra validation on the client certificate, for example
checking the returned certificate has a commonName attribute equal to the
hostname (to avoid man in the middle attacks).
The signature is: (OK, err_msg) = validation_function(cert, hostname)
where OK is a boolean, and cert is a certificate structure
as returned by ssl.SSLSocket.getpeercert()
:param ssl_version: SSL protocol to use for the connection. This should be one of the PROTOCOL_x
constants provided by the ssl module. The default is ssl.PROTOCOL_TLSv1 | [
"Sets",
"up",
"SSL",
"configuration",
"for",
"the",
"given",
"hosts",
".",
"This",
"ensures",
"socket",
"is",
"wrapped",
"in",
"a",
"SSL",
"connection",
"raising",
"an",
"exception",
"if",
"the",
"SSL",
"module",
"can",
"t",
"be",
"found",
"."
] | 643843c5fbf25fd24339dd0e69a9411c3d8b94c7 | https://github.com/jasonrbriggs/stomp.py/blob/643843c5fbf25fd24339dd0e69a9411c3d8b94c7/stomp/transport.py#L809-L844 | train | 201,178 |
jasonrbriggs/stomp.py | stomp/transport.py | Transport.__need_ssl | def __need_ssl(self, host_and_port=None):
"""
Whether current host needs SSL or not.
:param (str,int) host_and_port: the host/port pair to check, default current_host_and_port
"""
if not host_and_port:
host_and_port = self.current_host_and_port
return host_and_port in self.__ssl_params | python | def __need_ssl(self, host_and_port=None):
"""
Whether current host needs SSL or not.
:param (str,int) host_and_port: the host/port pair to check, default current_host_and_port
"""
if not host_and_port:
host_and_port = self.current_host_and_port
return host_and_port in self.__ssl_params | [
"def",
"__need_ssl",
"(",
"self",
",",
"host_and_port",
"=",
"None",
")",
":",
"if",
"not",
"host_and_port",
":",
"host_and_port",
"=",
"self",
".",
"current_host_and_port",
"return",
"host_and_port",
"in",
"self",
".",
"__ssl_params"
] | Whether current host needs SSL or not.
:param (str,int) host_and_port: the host/port pair to check, default current_host_and_port | [
"Whether",
"current",
"host",
"needs",
"SSL",
"or",
"not",
"."
] | 643843c5fbf25fd24339dd0e69a9411c3d8b94c7 | https://github.com/jasonrbriggs/stomp.py/blob/643843c5fbf25fd24339dd0e69a9411c3d8b94c7/stomp/transport.py#L846-L855 | train | 201,179 |
jasonrbriggs/stomp.py | stomp/transport.py | Transport.get_ssl | def get_ssl(self, host_and_port=None):
"""
Get SSL params for the given host.
:param (str,int) host_and_port: the host/port pair we want SSL params for, default current_host_and_port
"""
if not host_and_port:
host_and_port = self.current_host_and_port
return self.__ssl_params.get(host_and_port) | python | def get_ssl(self, host_and_port=None):
"""
Get SSL params for the given host.
:param (str,int) host_and_port: the host/port pair we want SSL params for, default current_host_and_port
"""
if not host_and_port:
host_and_port = self.current_host_and_port
return self.__ssl_params.get(host_and_port) | [
"def",
"get_ssl",
"(",
"self",
",",
"host_and_port",
"=",
"None",
")",
":",
"if",
"not",
"host_and_port",
":",
"host_and_port",
"=",
"self",
".",
"current_host_and_port",
"return",
"self",
".",
"__ssl_params",
".",
"get",
"(",
"host_and_port",
")"
] | Get SSL params for the given host.
:param (str,int) host_and_port: the host/port pair we want SSL params for, default current_host_and_port | [
"Get",
"SSL",
"params",
"for",
"the",
"given",
"host",
"."
] | 643843c5fbf25fd24339dd0e69a9411c3d8b94c7 | https://github.com/jasonrbriggs/stomp.py/blob/643843c5fbf25fd24339dd0e69a9411c3d8b94c7/stomp/transport.py#L857-L866 | train | 201,180 |
jasonrbriggs/stomp.py | stomp/__main__.py | StompCLI.__print_async | def __print_async(self, frame_type, headers, body):
"""
Utility function to print a message and setup the command prompt
for the next input
"""
if self.__quit:
return
if self.verbose:
self.__sysout(frame_type)
for k, v in headers.items():
self.__sysout('%s: %s' % (k, v))
else:
if 'message-id' in headers:
self.__sysout('message-id: %s' % headers['message-id'])
if 'subscription' in headers:
self.__sysout('subscription: %s' % headers['subscription'])
if self.prompt != '':
self.__sysout('')
self.__sysout(body)
if not self.__start:
self.__sysout(self.prompt, end='')
else:
self.__start = False
self.stdout.flush() | python | def __print_async(self, frame_type, headers, body):
"""
Utility function to print a message and setup the command prompt
for the next input
"""
if self.__quit:
return
if self.verbose:
self.__sysout(frame_type)
for k, v in headers.items():
self.__sysout('%s: %s' % (k, v))
else:
if 'message-id' in headers:
self.__sysout('message-id: %s' % headers['message-id'])
if 'subscription' in headers:
self.__sysout('subscription: %s' % headers['subscription'])
if self.prompt != '':
self.__sysout('')
self.__sysout(body)
if not self.__start:
self.__sysout(self.prompt, end='')
else:
self.__start = False
self.stdout.flush() | [
"def",
"__print_async",
"(",
"self",
",",
"frame_type",
",",
"headers",
",",
"body",
")",
":",
"if",
"self",
".",
"__quit",
":",
"return",
"if",
"self",
".",
"verbose",
":",
"self",
".",
"__sysout",
"(",
"frame_type",
")",
"for",
"k",
",",
"v",
"in",... | Utility function to print a message and setup the command prompt
for the next input | [
"Utility",
"function",
"to",
"print",
"a",
"message",
"and",
"setup",
"the",
"command",
"prompt",
"for",
"the",
"next",
"input"
] | 643843c5fbf25fd24339dd0e69a9411c3d8b94c7 | https://github.com/jasonrbriggs/stomp.py/blob/643843c5fbf25fd24339dd0e69a9411c3d8b94c7/stomp/__main__.py#L105-L128 | train | 201,181 |
LuminosoInsight/wordfreq | wordfreq/tokens.py | simple_tokenize | def simple_tokenize(text, include_punctuation=False):
"""
Tokenize the given text using a straightforward, Unicode-aware token
expression.
The expression mostly implements the rules of Unicode Annex #29 that
are contained in the `regex` module's word boundary matching, including
the refinement that splits words between apostrophes and vowels in order
to separate tokens such as the French article «l'».
It makes sure not to split in the middle of a grapheme, so that zero-width
joiners and marks on Devanagari words work correctly.
Our customizations to the expression are:
- It leaves sequences of Chinese or Japanese characters (specifically, Han
ideograms and hiragana) relatively untokenized, instead of splitting each
character into its own token.
- If `include_punctuation` is False (the default), it outputs only the
tokens that start with a word-like character, or miscellaneous symbols
such as emoji. If `include_punctuation` is True, it outputs all non-space
tokens.
- It keeps Southeast Asian scripts, such as Thai, glued together. This yields
tokens that are much too long, but the alternative is that every grapheme
would end up in its own token, which is worse.
"""
text = unicodedata.normalize('NFC', text)
if include_punctuation:
return [
token.casefold()
for token in TOKEN_RE_WITH_PUNCTUATION.findall(text)
]
else:
return [
token.strip("'").casefold()
for token in TOKEN_RE.findall(text)
] | python | def simple_tokenize(text, include_punctuation=False):
"""
Tokenize the given text using a straightforward, Unicode-aware token
expression.
The expression mostly implements the rules of Unicode Annex #29 that
are contained in the `regex` module's word boundary matching, including
the refinement that splits words between apostrophes and vowels in order
to separate tokens such as the French article «l'».
It makes sure not to split in the middle of a grapheme, so that zero-width
joiners and marks on Devanagari words work correctly.
Our customizations to the expression are:
- It leaves sequences of Chinese or Japanese characters (specifically, Han
ideograms and hiragana) relatively untokenized, instead of splitting each
character into its own token.
- If `include_punctuation` is False (the default), it outputs only the
tokens that start with a word-like character, or miscellaneous symbols
such as emoji. If `include_punctuation` is True, it outputs all non-space
tokens.
- It keeps Southeast Asian scripts, such as Thai, glued together. This yields
tokens that are much too long, but the alternative is that every grapheme
would end up in its own token, which is worse.
"""
text = unicodedata.normalize('NFC', text)
if include_punctuation:
return [
token.casefold()
for token in TOKEN_RE_WITH_PUNCTUATION.findall(text)
]
else:
return [
token.strip("'").casefold()
for token in TOKEN_RE.findall(text)
] | [
"def",
"simple_tokenize",
"(",
"text",
",",
"include_punctuation",
"=",
"False",
")",
":",
"text",
"=",
"unicodedata",
".",
"normalize",
"(",
"'NFC'",
",",
"text",
")",
"if",
"include_punctuation",
":",
"return",
"[",
"token",
".",
"casefold",
"(",
")",
"f... | Tokenize the given text using a straightforward, Unicode-aware token
expression.
The expression mostly implements the rules of Unicode Annex #29 that
are contained in the `regex` module's word boundary matching, including
the refinement that splits words between apostrophes and vowels in order
to separate tokens such as the French article «l'».
It makes sure not to split in the middle of a grapheme, so that zero-width
joiners and marks on Devanagari words work correctly.
Our customizations to the expression are:
- It leaves sequences of Chinese or Japanese characters (specifically, Han
ideograms and hiragana) relatively untokenized, instead of splitting each
character into its own token.
- If `include_punctuation` is False (the default), it outputs only the
tokens that start with a word-like character, or miscellaneous symbols
such as emoji. If `include_punctuation` is True, it outputs all non-space
tokens.
- It keeps Southeast Asian scripts, such as Thai, glued together. This yields
tokens that are much too long, but the alternative is that every grapheme
would end up in its own token, which is worse. | [
"Tokenize",
"the",
"given",
"text",
"using",
"a",
"straightforward",
"Unicode",
"-",
"aware",
"token",
"expression",
"."
] | 170e3c6536854b06dc63da8d873e8cc4f9ef6180 | https://github.com/LuminosoInsight/wordfreq/blob/170e3c6536854b06dc63da8d873e8cc4f9ef6180/wordfreq/tokens.py#L148-L186 | train | 201,182 |
LuminosoInsight/wordfreq | wordfreq/tokens.py | tokenize | def tokenize(text, lang, include_punctuation=False, external_wordlist=False):
"""
Tokenize this text in a way that's relatively simple but appropriate for
the language. Strings that are looked up in wordfreq will be run through
this function first, so that they can be expected to match the data.
The text will be run through a number of pre-processing steps that vary
by language; see the docstring of `wordfreq.preprocess.preprocess_text`.
If `include_punctuation` is True, punctuation will be included as separate
tokens. Otherwise, punctuation will be omitted in the output.
CJK scripts
-----------
In the CJK languages, word boundaries can't usually be identified by a
regular expression. Instead, there needs to be some language-specific
handling. In Chinese, we use the Jieba tokenizer, with a custom word list
to match the words whose frequencies we can look up. In Japanese and
Korean, we use the MeCab tokenizer.
The `external_wordlist` option only affects Chinese tokenization. If it's
True, then wordfreq will not use its own Chinese wordlist for tokenization.
Instead, it will use the large wordlist packaged with the Jieba tokenizer,
and it will leave Traditional Chinese characters as is. This will probably
give more accurate tokenization, but the resulting tokens won't necessarily
have word frequencies that can be looked up.
If you end up seeing tokens that are entire phrases or sentences glued
together, that probably means you passed in CJK text with the wrong
language code.
"""
# Use globals to load CJK tokenizers on demand, so that we can still run
# in environments that lack the CJK dependencies
global _mecab_tokenize, _jieba_tokenize
language = langcodes.get(lang)
info = get_language_info(language)
text = preprocess_text(text, language)
if info['tokenizer'] == 'mecab':
from wordfreq.mecab import mecab_tokenize as _mecab_tokenize
# Get just the language code out of the Language object, so we can
# use it to select a MeCab dictionary
tokens = _mecab_tokenize(text, language.language)
if not include_punctuation:
tokens = [token for token in tokens if not PUNCT_RE.match(token)]
elif info['tokenizer'] == 'jieba':
from wordfreq.chinese import jieba_tokenize as _jieba_tokenize
tokens = _jieba_tokenize(text, external_wordlist=external_wordlist)
if not include_punctuation:
tokens = [token for token in tokens if not PUNCT_RE.match(token)]
else:
# This is the default case where we use the regex tokenizer. First
# let's complain a bit if we ended up here because we don't have an
# appropriate tokenizer.
if info['tokenizer'] != 'regex' and lang not in _WARNED_LANGUAGES:
logger.warning(
"The language '{}' is in the '{}' script, which we don't "
"have a tokenizer for. The results will be bad."
.format(lang, info['script'])
)
_WARNED_LANGUAGES.add(lang)
tokens = simple_tokenize(text, include_punctuation=include_punctuation)
return tokens | python | def tokenize(text, lang, include_punctuation=False, external_wordlist=False):
"""
Tokenize this text in a way that's relatively simple but appropriate for
the language. Strings that are looked up in wordfreq will be run through
this function first, so that they can be expected to match the data.
The text will be run through a number of pre-processing steps that vary
by language; see the docstring of `wordfreq.preprocess.preprocess_text`.
If `include_punctuation` is True, punctuation will be included as separate
tokens. Otherwise, punctuation will be omitted in the output.
CJK scripts
-----------
In the CJK languages, word boundaries can't usually be identified by a
regular expression. Instead, there needs to be some language-specific
handling. In Chinese, we use the Jieba tokenizer, with a custom word list
to match the words whose frequencies we can look up. In Japanese and
Korean, we use the MeCab tokenizer.
The `external_wordlist` option only affects Chinese tokenization. If it's
True, then wordfreq will not use its own Chinese wordlist for tokenization.
Instead, it will use the large wordlist packaged with the Jieba tokenizer,
and it will leave Traditional Chinese characters as is. This will probably
give more accurate tokenization, but the resulting tokens won't necessarily
have word frequencies that can be looked up.
If you end up seeing tokens that are entire phrases or sentences glued
together, that probably means you passed in CJK text with the wrong
language code.
"""
# Use globals to load CJK tokenizers on demand, so that we can still run
# in environments that lack the CJK dependencies
global _mecab_tokenize, _jieba_tokenize
language = langcodes.get(lang)
info = get_language_info(language)
text = preprocess_text(text, language)
if info['tokenizer'] == 'mecab':
from wordfreq.mecab import mecab_tokenize as _mecab_tokenize
# Get just the language code out of the Language object, so we can
# use it to select a MeCab dictionary
tokens = _mecab_tokenize(text, language.language)
if not include_punctuation:
tokens = [token for token in tokens if not PUNCT_RE.match(token)]
elif info['tokenizer'] == 'jieba':
from wordfreq.chinese import jieba_tokenize as _jieba_tokenize
tokens = _jieba_tokenize(text, external_wordlist=external_wordlist)
if not include_punctuation:
tokens = [token for token in tokens if not PUNCT_RE.match(token)]
else:
# This is the default case where we use the regex tokenizer. First
# let's complain a bit if we ended up here because we don't have an
# appropriate tokenizer.
if info['tokenizer'] != 'regex' and lang not in _WARNED_LANGUAGES:
logger.warning(
"The language '{}' is in the '{}' script, which we don't "
"have a tokenizer for. The results will be bad."
.format(lang, info['script'])
)
_WARNED_LANGUAGES.add(lang)
tokens = simple_tokenize(text, include_punctuation=include_punctuation)
return tokens | [
"def",
"tokenize",
"(",
"text",
",",
"lang",
",",
"include_punctuation",
"=",
"False",
",",
"external_wordlist",
"=",
"False",
")",
":",
"# Use globals to load CJK tokenizers on demand, so that we can still run",
"# in environments that lack the CJK dependencies",
"global",
"_m... | Tokenize this text in a way that's relatively simple but appropriate for
the language. Strings that are looked up in wordfreq will be run through
this function first, so that they can be expected to match the data.
The text will be run through a number of pre-processing steps that vary
by language; see the docstring of `wordfreq.preprocess.preprocess_text`.
If `include_punctuation` is True, punctuation will be included as separate
tokens. Otherwise, punctuation will be omitted in the output.
CJK scripts
-----------
In the CJK languages, word boundaries can't usually be identified by a
regular expression. Instead, there needs to be some language-specific
handling. In Chinese, we use the Jieba tokenizer, with a custom word list
to match the words whose frequencies we can look up. In Japanese and
Korean, we use the MeCab tokenizer.
The `external_wordlist` option only affects Chinese tokenization. If it's
True, then wordfreq will not use its own Chinese wordlist for tokenization.
Instead, it will use the large wordlist packaged with the Jieba tokenizer,
and it will leave Traditional Chinese characters as is. This will probably
give more accurate tokenization, but the resulting tokens won't necessarily
have word frequencies that can be looked up.
If you end up seeing tokens that are entire phrases or sentences glued
together, that probably means you passed in CJK text with the wrong
language code. | [
"Tokenize",
"this",
"text",
"in",
"a",
"way",
"that",
"s",
"relatively",
"simple",
"but",
"appropriate",
"for",
"the",
"language",
".",
"Strings",
"that",
"are",
"looked",
"up",
"in",
"wordfreq",
"will",
"be",
"run",
"through",
"this",
"function",
"first",
... | 170e3c6536854b06dc63da8d873e8cc4f9ef6180 | https://github.com/LuminosoInsight/wordfreq/blob/170e3c6536854b06dc63da8d873e8cc4f9ef6180/wordfreq/tokens.py#L189-L254 | train | 201,183 |
LuminosoInsight/wordfreq | wordfreq/tokens.py | lossy_tokenize | def lossy_tokenize(text, lang, include_punctuation=False, external_wordlist=False):
"""
Get a list of tokens for this text, with largely the same results and
options as `tokenize`, but aggressively normalize some text in a lossy way
that's good for counting word frequencies.
In particular:
- Any sequence of 2 or more adjacent digits, possibly with intervening
punctuation such as a decimal point, will replace each digit with '0'
so that frequencies for numbers don't have to be counted separately.
This is similar to but not quite identical to the word2vec Google News
data, which replaces digits with '#' in tokens with more than one digit.
- In Chinese, unless Traditional Chinese is specifically requested using
'zh-Hant', all characters will be converted to Simplified Chinese.
"""
global _simplify_chinese
info = get_language_info(lang)
tokens = tokenize(text, lang, include_punctuation, external_wordlist)
if info['lookup_transliteration'] == 'zh-Hans':
from wordfreq.chinese import simplify_chinese as _simplify_chinese
tokens = [_simplify_chinese(token) for token in tokens]
return [smash_numbers(token) for token in tokens] | python | def lossy_tokenize(text, lang, include_punctuation=False, external_wordlist=False):
"""
Get a list of tokens for this text, with largely the same results and
options as `tokenize`, but aggressively normalize some text in a lossy way
that's good for counting word frequencies.
In particular:
- Any sequence of 2 or more adjacent digits, possibly with intervening
punctuation such as a decimal point, will replace each digit with '0'
so that frequencies for numbers don't have to be counted separately.
This is similar to but not quite identical to the word2vec Google News
data, which replaces digits with '#' in tokens with more than one digit.
- In Chinese, unless Traditional Chinese is specifically requested using
'zh-Hant', all characters will be converted to Simplified Chinese.
"""
global _simplify_chinese
info = get_language_info(lang)
tokens = tokenize(text, lang, include_punctuation, external_wordlist)
if info['lookup_transliteration'] == 'zh-Hans':
from wordfreq.chinese import simplify_chinese as _simplify_chinese
tokens = [_simplify_chinese(token) for token in tokens]
return [smash_numbers(token) for token in tokens] | [
"def",
"lossy_tokenize",
"(",
"text",
",",
"lang",
",",
"include_punctuation",
"=",
"False",
",",
"external_wordlist",
"=",
"False",
")",
":",
"global",
"_simplify_chinese",
"info",
"=",
"get_language_info",
"(",
"lang",
")",
"tokens",
"=",
"tokenize",
"(",
"t... | Get a list of tokens for this text, with largely the same results and
options as `tokenize`, but aggressively normalize some text in a lossy way
that's good for counting word frequencies.
In particular:
- Any sequence of 2 or more adjacent digits, possibly with intervening
punctuation such as a decimal point, will replace each digit with '0'
so that frequencies for numbers don't have to be counted separately.
This is similar to but not quite identical to the word2vec Google News
data, which replaces digits with '#' in tokens with more than one digit.
- In Chinese, unless Traditional Chinese is specifically requested using
'zh-Hant', all characters will be converted to Simplified Chinese. | [
"Get",
"a",
"list",
"of",
"tokens",
"for",
"this",
"text",
"with",
"largely",
"the",
"same",
"results",
"and",
"options",
"as",
"tokenize",
"but",
"aggressively",
"normalize",
"some",
"text",
"in",
"a",
"lossy",
"way",
"that",
"s",
"good",
"for",
"counting... | 170e3c6536854b06dc63da8d873e8cc4f9ef6180 | https://github.com/LuminosoInsight/wordfreq/blob/170e3c6536854b06dc63da8d873e8cc4f9ef6180/wordfreq/tokens.py#L257-L284 | train | 201,184 |
LuminosoInsight/wordfreq | wordfreq/__init__.py | read_cBpack | def read_cBpack(filename):
"""
Read a file from an idiosyncratic format that we use for storing
approximate word frequencies, called "cBpack".
The cBpack format is as follows:
- The file on disk is a gzipped file in msgpack format, which decodes to a
list whose first element is a header, and whose remaining elements are
lists of words.
- The header is a dictionary with 'format' and 'version' keys that make
sure that we're reading the right thing.
- Each inner list of words corresponds to a particular word frequency,
rounded to the nearest centibel -- that is, one tenth of a decibel, or
a factor of 10 ** .01.
0 cB represents a word that occurs with probability 1, so it is the only
word in the data (this of course doesn't happen). -200 cB represents a
word that occurs once per 100 tokens, -300 cB represents a word that
occurs once per 1000 tokens, and so on.
- The index of each list within the overall list (without the header) is
the negative of its frequency in centibels.
- Each inner list is sorted in alphabetical order.
As an example, consider a corpus consisting only of the words "red fish
blue fish". The word "fish" occurs as 50% of tokens (-30 cB), while "red"
and "blue" occur as 25% of tokens (-60 cB). The cBpack file of their word
frequencies would decode to this:
[
{'format': 'cB', 'version': 1},
[], [], [], ... # 30 empty lists
['fish'],
[], [], [], ... # 29 more empty lists
['blue', 'red']
]
"""
with gzip.open(filename, 'rb') as infile:
data = msgpack.load(infile, raw=False)
header = data[0]
if (
not isinstance(header, dict) or header.get('format') != 'cB'
or header.get('version') != 1
):
raise ValueError("Unexpected header: %r" % header)
return data[1:] | python | def read_cBpack(filename):
"""
Read a file from an idiosyncratic format that we use for storing
approximate word frequencies, called "cBpack".
The cBpack format is as follows:
- The file on disk is a gzipped file in msgpack format, which decodes to a
list whose first element is a header, and whose remaining elements are
lists of words.
- The header is a dictionary with 'format' and 'version' keys that make
sure that we're reading the right thing.
- Each inner list of words corresponds to a particular word frequency,
rounded to the nearest centibel -- that is, one tenth of a decibel, or
a factor of 10 ** .01.
0 cB represents a word that occurs with probability 1, so it is the only
word in the data (this of course doesn't happen). -200 cB represents a
word that occurs once per 100 tokens, -300 cB represents a word that
occurs once per 1000 tokens, and so on.
- The index of each list within the overall list (without the header) is
the negative of its frequency in centibels.
- Each inner list is sorted in alphabetical order.
As an example, consider a corpus consisting only of the words "red fish
blue fish". The word "fish" occurs as 50% of tokens (-30 cB), while "red"
and "blue" occur as 25% of tokens (-60 cB). The cBpack file of their word
frequencies would decode to this:
[
{'format': 'cB', 'version': 1},
[], [], [], ... # 30 empty lists
['fish'],
[], [], [], ... # 29 more empty lists
['blue', 'red']
]
"""
with gzip.open(filename, 'rb') as infile:
data = msgpack.load(infile, raw=False)
header = data[0]
if (
not isinstance(header, dict) or header.get('format') != 'cB'
or header.get('version') != 1
):
raise ValueError("Unexpected header: %r" % header)
return data[1:] | [
"def",
"read_cBpack",
"(",
"filename",
")",
":",
"with",
"gzip",
".",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"infile",
":",
"data",
"=",
"msgpack",
".",
"load",
"(",
"infile",
",",
"raw",
"=",
"False",
")",
"header",
"=",
"data",
"[",
"0"... | Read a file from an idiosyncratic format that we use for storing
approximate word frequencies, called "cBpack".
The cBpack format is as follows:
- The file on disk is a gzipped file in msgpack format, which decodes to a
list whose first element is a header, and whose remaining elements are
lists of words.
- The header is a dictionary with 'format' and 'version' keys that make
sure that we're reading the right thing.
- Each inner list of words corresponds to a particular word frequency,
rounded to the nearest centibel -- that is, one tenth of a decibel, or
a factor of 10 ** .01.
0 cB represents a word that occurs with probability 1, so it is the only
word in the data (this of course doesn't happen). -200 cB represents a
word that occurs once per 100 tokens, -300 cB represents a word that
occurs once per 1000 tokens, and so on.
- The index of each list within the overall list (without the header) is
the negative of its frequency in centibels.
- Each inner list is sorted in alphabetical order.
As an example, consider a corpus consisting only of the words "red fish
blue fish". The word "fish" occurs as 50% of tokens (-30 cB), while "red"
and "blue" occur as 25% of tokens (-60 cB). The cBpack file of their word
frequencies would decode to this:
[
{'format': 'cB', 'version': 1},
[], [], [], ... # 30 empty lists
['fish'],
[], [], [], ... # 29 more empty lists
['blue', 'red']
] | [
"Read",
"a",
"file",
"from",
"an",
"idiosyncratic",
"format",
"that",
"we",
"use",
"for",
"storing",
"approximate",
"word",
"frequencies",
"called",
"cBpack",
"."
] | 170e3c6536854b06dc63da8d873e8cc4f9ef6180 | https://github.com/LuminosoInsight/wordfreq/blob/170e3c6536854b06dc63da8d873e8cc4f9ef6180/wordfreq/__init__.py#L35-L84 | train | 201,185 |
LuminosoInsight/wordfreq | wordfreq/__init__.py | available_languages | def available_languages(wordlist='best'):
"""
Given a wordlist name, return a dictionary of language codes to filenames,
representing all the languages in which that wordlist is available.
"""
if wordlist == 'best':
available = available_languages('small')
available.update(available_languages('large'))
return available
elif wordlist == 'combined':
logger.warning(
"The 'combined' wordlists have been renamed to 'small'."
)
wordlist = 'small'
available = {}
for path in DATA_PATH.glob('*.msgpack.gz'):
if not path.name.startswith('_'):
list_name = path.name.split('.')[0]
name, lang = list_name.split('_')
if name == wordlist:
available[lang] = str(path)
return available | python | def available_languages(wordlist='best'):
"""
Given a wordlist name, return a dictionary of language codes to filenames,
representing all the languages in which that wordlist is available.
"""
if wordlist == 'best':
available = available_languages('small')
available.update(available_languages('large'))
return available
elif wordlist == 'combined':
logger.warning(
"The 'combined' wordlists have been renamed to 'small'."
)
wordlist = 'small'
available = {}
for path in DATA_PATH.glob('*.msgpack.gz'):
if not path.name.startswith('_'):
list_name = path.name.split('.')[0]
name, lang = list_name.split('_')
if name == wordlist:
available[lang] = str(path)
return available | [
"def",
"available_languages",
"(",
"wordlist",
"=",
"'best'",
")",
":",
"if",
"wordlist",
"==",
"'best'",
":",
"available",
"=",
"available_languages",
"(",
"'small'",
")",
"available",
".",
"update",
"(",
"available_languages",
"(",
"'large'",
")",
")",
"retu... | Given a wordlist name, return a dictionary of language codes to filenames,
representing all the languages in which that wordlist is available. | [
"Given",
"a",
"wordlist",
"name",
"return",
"a",
"dictionary",
"of",
"language",
"codes",
"to",
"filenames",
"representing",
"all",
"the",
"languages",
"in",
"which",
"that",
"wordlist",
"is",
"available",
"."
] | 170e3c6536854b06dc63da8d873e8cc4f9ef6180 | https://github.com/LuminosoInsight/wordfreq/blob/170e3c6536854b06dc63da8d873e8cc4f9ef6180/wordfreq/__init__.py#L87-L109 | train | 201,186 |
LuminosoInsight/wordfreq | wordfreq/__init__.py | get_frequency_dict | def get_frequency_dict(lang, wordlist='best', match_cutoff=30):
"""
Get a word frequency list as a dictionary, mapping tokens to
frequencies as floating-point probabilities.
"""
freqs = {}
pack = get_frequency_list(lang, wordlist, match_cutoff)
for index, bucket in enumerate(pack):
freq = cB_to_freq(-index)
for word in bucket:
freqs[word] = freq
return freqs | python | def get_frequency_dict(lang, wordlist='best', match_cutoff=30):
"""
Get a word frequency list as a dictionary, mapping tokens to
frequencies as floating-point probabilities.
"""
freqs = {}
pack = get_frequency_list(lang, wordlist, match_cutoff)
for index, bucket in enumerate(pack):
freq = cB_to_freq(-index)
for word in bucket:
freqs[word] = freq
return freqs | [
"def",
"get_frequency_dict",
"(",
"lang",
",",
"wordlist",
"=",
"'best'",
",",
"match_cutoff",
"=",
"30",
")",
":",
"freqs",
"=",
"{",
"}",
"pack",
"=",
"get_frequency_list",
"(",
"lang",
",",
"wordlist",
",",
"match_cutoff",
")",
"for",
"index",
",",
"b... | Get a word frequency list as a dictionary, mapping tokens to
frequencies as floating-point probabilities. | [
"Get",
"a",
"word",
"frequency",
"list",
"as",
"a",
"dictionary",
"mapping",
"tokens",
"to",
"frequencies",
"as",
"floating",
"-",
"point",
"probabilities",
"."
] | 170e3c6536854b06dc63da8d873e8cc4f9ef6180 | https://github.com/LuminosoInsight/wordfreq/blob/170e3c6536854b06dc63da8d873e8cc4f9ef6180/wordfreq/__init__.py#L195-L206 | train | 201,187 |
LuminosoInsight/wordfreq | wordfreq/__init__.py | word_frequency | def word_frequency(word, lang, wordlist='best', minimum=0.):
"""
Get the frequency of `word` in the language with code `lang`, from the
specified `wordlist`.
These wordlists can be specified:
- 'large': a wordlist built from at least 5 sources, containing word
frequencies of 10^-8 and higher
- 'small': a wordlist built from at least 3 sources, containing word
frquencies of 10^-6 and higher
- 'best': uses 'large' if available, and 'small' otherwise
The value returned will always be at least as large as `minimum`.
You could set this value to 10^-8, for example, to return 10^-8 for
unknown words in the 'large' list instead of 0, avoiding a discontinuity.
"""
args = (word, lang, wordlist, minimum)
try:
return _wf_cache[args]
except KeyError:
if len(_wf_cache) >= CACHE_SIZE:
_wf_cache.clear()
_wf_cache[args] = _word_frequency(*args)
return _wf_cache[args] | python | def word_frequency(word, lang, wordlist='best', minimum=0.):
"""
Get the frequency of `word` in the language with code `lang`, from the
specified `wordlist`.
These wordlists can be specified:
- 'large': a wordlist built from at least 5 sources, containing word
frequencies of 10^-8 and higher
- 'small': a wordlist built from at least 3 sources, containing word
frquencies of 10^-6 and higher
- 'best': uses 'large' if available, and 'small' otherwise
The value returned will always be at least as large as `minimum`.
You could set this value to 10^-8, for example, to return 10^-8 for
unknown words in the 'large' list instead of 0, avoiding a discontinuity.
"""
args = (word, lang, wordlist, minimum)
try:
return _wf_cache[args]
except KeyError:
if len(_wf_cache) >= CACHE_SIZE:
_wf_cache.clear()
_wf_cache[args] = _word_frequency(*args)
return _wf_cache[args] | [
"def",
"word_frequency",
"(",
"word",
",",
"lang",
",",
"wordlist",
"=",
"'best'",
",",
"minimum",
"=",
"0.",
")",
":",
"args",
"=",
"(",
"word",
",",
"lang",
",",
"wordlist",
",",
"minimum",
")",
"try",
":",
"return",
"_wf_cache",
"[",
"args",
"]",
... | Get the frequency of `word` in the language with code `lang`, from the
specified `wordlist`.
These wordlists can be specified:
- 'large': a wordlist built from at least 5 sources, containing word
frequencies of 10^-8 and higher
- 'small': a wordlist built from at least 3 sources, containing word
frquencies of 10^-6 and higher
- 'best': uses 'large' if available, and 'small' otherwise
The value returned will always be at least as large as `minimum`.
You could set this value to 10^-8, for example, to return 10^-8 for
unknown words in the 'large' list instead of 0, avoiding a discontinuity. | [
"Get",
"the",
"frequency",
"of",
"word",
"in",
"the",
"language",
"with",
"code",
"lang",
"from",
"the",
"specified",
"wordlist",
"."
] | 170e3c6536854b06dc63da8d873e8cc4f9ef6180 | https://github.com/LuminosoInsight/wordfreq/blob/170e3c6536854b06dc63da8d873e8cc4f9ef6180/wordfreq/__init__.py#L262-L286 | train | 201,188 |
LuminosoInsight/wordfreq | wordfreq/__init__.py | zipf_frequency | def zipf_frequency(word, lang, wordlist='best', minimum=0.):
"""
Get the frequency of `word`, in the language with code `lang`, on the Zipf
scale.
The Zipf scale is a logarithmic frequency scale proposed by Marc Brysbaert,
who compiled the SUBTLEX data. The goal of the Zipf scale is to map
reasonable word frequencies to understandable, small positive numbers.
A word rates as x on the Zipf scale when it occurs 10**x times per billion
words. For example, a word that occurs once per million words is at 3.0 on
the Zipf scale.
Zipf values for reasonable words are between 0 and 8. The value this
function returns will always be at last as large as `minimum`, even for a
word that never appears. The default minimum is 0, representing words
that appear once per billion words or less.
wordfreq internally quantizes its frequencies to centibels, which are
1/100 of a Zipf unit. The output of `zipf_frequency` will be rounded to
the nearest hundredth to match this quantization.
"""
freq_min = zipf_to_freq(minimum)
freq = word_frequency(word, lang, wordlist, freq_min)
return round(freq_to_zipf(freq), 2) | python | def zipf_frequency(word, lang, wordlist='best', minimum=0.):
"""
Get the frequency of `word`, in the language with code `lang`, on the Zipf
scale.
The Zipf scale is a logarithmic frequency scale proposed by Marc Brysbaert,
who compiled the SUBTLEX data. The goal of the Zipf scale is to map
reasonable word frequencies to understandable, small positive numbers.
A word rates as x on the Zipf scale when it occurs 10**x times per billion
words. For example, a word that occurs once per million words is at 3.0 on
the Zipf scale.
Zipf values for reasonable words are between 0 and 8. The value this
function returns will always be at last as large as `minimum`, even for a
word that never appears. The default minimum is 0, representing words
that appear once per billion words or less.
wordfreq internally quantizes its frequencies to centibels, which are
1/100 of a Zipf unit. The output of `zipf_frequency` will be rounded to
the nearest hundredth to match this quantization.
"""
freq_min = zipf_to_freq(minimum)
freq = word_frequency(word, lang, wordlist, freq_min)
return round(freq_to_zipf(freq), 2) | [
"def",
"zipf_frequency",
"(",
"word",
",",
"lang",
",",
"wordlist",
"=",
"'best'",
",",
"minimum",
"=",
"0.",
")",
":",
"freq_min",
"=",
"zipf_to_freq",
"(",
"minimum",
")",
"freq",
"=",
"word_frequency",
"(",
"word",
",",
"lang",
",",
"wordlist",
",",
... | Get the frequency of `word`, in the language with code `lang`, on the Zipf
scale.
The Zipf scale is a logarithmic frequency scale proposed by Marc Brysbaert,
who compiled the SUBTLEX data. The goal of the Zipf scale is to map
reasonable word frequencies to understandable, small positive numbers.
A word rates as x on the Zipf scale when it occurs 10**x times per billion
words. For example, a word that occurs once per million words is at 3.0 on
the Zipf scale.
Zipf values for reasonable words are between 0 and 8. The value this
function returns will always be at last as large as `minimum`, even for a
word that never appears. The default minimum is 0, representing words
that appear once per billion words or less.
wordfreq internally quantizes its frequencies to centibels, which are
1/100 of a Zipf unit. The output of `zipf_frequency` will be rounded to
the nearest hundredth to match this quantization. | [
"Get",
"the",
"frequency",
"of",
"word",
"in",
"the",
"language",
"with",
"code",
"lang",
"on",
"the",
"Zipf",
"scale",
"."
] | 170e3c6536854b06dc63da8d873e8cc4f9ef6180 | https://github.com/LuminosoInsight/wordfreq/blob/170e3c6536854b06dc63da8d873e8cc4f9ef6180/wordfreq/__init__.py#L289-L313 | train | 201,189 |
LuminosoInsight/wordfreq | wordfreq/__init__.py | top_n_list | def top_n_list(lang, n, wordlist='best', ascii_only=False):
"""
Return a frequency list of length `n` in descending order of frequency.
This list contains words from `wordlist`, of the given language.
If `ascii_only`, then only ascii words are considered.
"""
results = []
for word in iter_wordlist(lang, wordlist):
if (not ascii_only) or max(word) <= '~':
results.append(word)
if len(results) >= n:
break
return results | python | def top_n_list(lang, n, wordlist='best', ascii_only=False):
"""
Return a frequency list of length `n` in descending order of frequency.
This list contains words from `wordlist`, of the given language.
If `ascii_only`, then only ascii words are considered.
"""
results = []
for word in iter_wordlist(lang, wordlist):
if (not ascii_only) or max(word) <= '~':
results.append(word)
if len(results) >= n:
break
return results | [
"def",
"top_n_list",
"(",
"lang",
",",
"n",
",",
"wordlist",
"=",
"'best'",
",",
"ascii_only",
"=",
"False",
")",
":",
"results",
"=",
"[",
"]",
"for",
"word",
"in",
"iter_wordlist",
"(",
"lang",
",",
"wordlist",
")",
":",
"if",
"(",
"not",
"ascii_on... | Return a frequency list of length `n` in descending order of frequency.
This list contains words from `wordlist`, of the given language.
If `ascii_only`, then only ascii words are considered. | [
"Return",
"a",
"frequency",
"list",
"of",
"length",
"n",
"in",
"descending",
"order",
"of",
"frequency",
".",
"This",
"list",
"contains",
"words",
"from",
"wordlist",
"of",
"the",
"given",
"language",
".",
"If",
"ascii_only",
"then",
"only",
"ascii",
"words"... | 170e3c6536854b06dc63da8d873e8cc4f9ef6180 | https://github.com/LuminosoInsight/wordfreq/blob/170e3c6536854b06dc63da8d873e8cc4f9ef6180/wordfreq/__init__.py#L317-L329 | train | 201,190 |
LuminosoInsight/wordfreq | wordfreq/__init__.py | random_words | def random_words(lang='en', wordlist='best', nwords=5, bits_per_word=12,
ascii_only=False):
"""
Returns a string of random, space separated words.
These words are of the given language and from the given wordlist.
There will be `nwords` words in the string.
`bits_per_word` determines the amount of entropy provided by each word;
when it's higher, this function will choose from a larger list of
words, some of which are more rare.
You can restrict the selection of words to those written in ASCII
characters by setting `ascii_only` to True.
"""
n_choices = 2 ** bits_per_word
choices = top_n_list(lang, n_choices, wordlist, ascii_only=ascii_only)
if len(choices) < n_choices:
raise ValueError(
"There aren't enough words in the wordlist to provide %d bits of "
"entropy per word." % bits_per_word
)
return ' '.join([random.choice(choices) for i in range(nwords)]) | python | def random_words(lang='en', wordlist='best', nwords=5, bits_per_word=12,
ascii_only=False):
"""
Returns a string of random, space separated words.
These words are of the given language and from the given wordlist.
There will be `nwords` words in the string.
`bits_per_word` determines the amount of entropy provided by each word;
when it's higher, this function will choose from a larger list of
words, some of which are more rare.
You can restrict the selection of words to those written in ASCII
characters by setting `ascii_only` to True.
"""
n_choices = 2 ** bits_per_word
choices = top_n_list(lang, n_choices, wordlist, ascii_only=ascii_only)
if len(choices) < n_choices:
raise ValueError(
"There aren't enough words in the wordlist to provide %d bits of "
"entropy per word." % bits_per_word
)
return ' '.join([random.choice(choices) for i in range(nwords)]) | [
"def",
"random_words",
"(",
"lang",
"=",
"'en'",
",",
"wordlist",
"=",
"'best'",
",",
"nwords",
"=",
"5",
",",
"bits_per_word",
"=",
"12",
",",
"ascii_only",
"=",
"False",
")",
":",
"n_choices",
"=",
"2",
"**",
"bits_per_word",
"choices",
"=",
"top_n_lis... | Returns a string of random, space separated words.
These words are of the given language and from the given wordlist.
There will be `nwords` words in the string.
`bits_per_word` determines the amount of entropy provided by each word;
when it's higher, this function will choose from a larger list of
words, some of which are more rare.
You can restrict the selection of words to those written in ASCII
characters by setting `ascii_only` to True. | [
"Returns",
"a",
"string",
"of",
"random",
"space",
"separated",
"words",
"."
] | 170e3c6536854b06dc63da8d873e8cc4f9ef6180 | https://github.com/LuminosoInsight/wordfreq/blob/170e3c6536854b06dc63da8d873e8cc4f9ef6180/wordfreq/__init__.py#L332-L354 | train | 201,191 |
LuminosoInsight/wordfreq | wordfreq/__init__.py | random_ascii_words | def random_ascii_words(lang='en', wordlist='best', nwords=5,
bits_per_word=12):
"""
Returns a string of random, space separated, ASCII words.
These words are of the given language and from the given wordlist.
There will be `nwords` words in the string.
`bits_per_word` determines the amount of entropy provided by each word;
when it's higher, this function will choose from a larger list of
words, some of which are more rare.
"""
return random_words(lang, wordlist, nwords, bits_per_word, ascii_only=True) | python | def random_ascii_words(lang='en', wordlist='best', nwords=5,
bits_per_word=12):
"""
Returns a string of random, space separated, ASCII words.
These words are of the given language and from the given wordlist.
There will be `nwords` words in the string.
`bits_per_word` determines the amount of entropy provided by each word;
when it's higher, this function will choose from a larger list of
words, some of which are more rare.
"""
return random_words(lang, wordlist, nwords, bits_per_word, ascii_only=True) | [
"def",
"random_ascii_words",
"(",
"lang",
"=",
"'en'",
",",
"wordlist",
"=",
"'best'",
",",
"nwords",
"=",
"5",
",",
"bits_per_word",
"=",
"12",
")",
":",
"return",
"random_words",
"(",
"lang",
",",
"wordlist",
",",
"nwords",
",",
"bits_per_word",
",",
"... | Returns a string of random, space separated, ASCII words.
These words are of the given language and from the given wordlist.
There will be `nwords` words in the string.
`bits_per_word` determines the amount of entropy provided by each word;
when it's higher, this function will choose from a larger list of
words, some of which are more rare. | [
"Returns",
"a",
"string",
"of",
"random",
"space",
"separated",
"ASCII",
"words",
"."
] | 170e3c6536854b06dc63da8d873e8cc4f9ef6180 | https://github.com/LuminosoInsight/wordfreq/blob/170e3c6536854b06dc63da8d873e8cc4f9ef6180/wordfreq/__init__.py#L357-L369 | train | 201,192 |
LuminosoInsight/wordfreq | wordfreq/chinese.py | jieba_tokenize | def jieba_tokenize(text, external_wordlist=False):
"""
Tokenize the given text into tokens whose word frequencies can probably
be looked up. This uses Jieba, a word-frequency-based tokenizer.
If `external_wordlist` is False, we tell Jieba to default to using
wordfreq's own Chinese wordlist, and not to infer unknown words using a
hidden Markov model. This ensures that the multi-character tokens that it
outputs will be ones whose word frequencies we can look up.
If `external_wordlist` is True, this will use the largest version of
Jieba's original dictionary, with HMM enabled, so its results will be
independent of the data in wordfreq. These results will be better optimized
for purposes that aren't looking up word frequencies, such as general-
purpose tokenization, or collecting word frequencies in the first place.
"""
global jieba_tokenizer, jieba_orig_tokenizer
if external_wordlist:
if jieba_orig_tokenizer is None:
jieba_orig_tokenizer = jieba.Tokenizer(dictionary=ORIG_DICT_FILENAME)
return jieba_orig_tokenizer.lcut(text)
else:
if jieba_tokenizer is None:
jieba_tokenizer = jieba.Tokenizer(dictionary=DICT_FILENAME)
# Tokenize the Simplified Chinese version of the text, but return
# those spans from the original text, even if it's in Traditional
# Chinese
tokens = []
for _token, start, end in jieba_tokenizer.tokenize(simplify_chinese(text), HMM=False):
tokens.append(text[start:end])
return tokens | python | def jieba_tokenize(text, external_wordlist=False):
"""
Tokenize the given text into tokens whose word frequencies can probably
be looked up. This uses Jieba, a word-frequency-based tokenizer.
If `external_wordlist` is False, we tell Jieba to default to using
wordfreq's own Chinese wordlist, and not to infer unknown words using a
hidden Markov model. This ensures that the multi-character tokens that it
outputs will be ones whose word frequencies we can look up.
If `external_wordlist` is True, this will use the largest version of
Jieba's original dictionary, with HMM enabled, so its results will be
independent of the data in wordfreq. These results will be better optimized
for purposes that aren't looking up word frequencies, such as general-
purpose tokenization, or collecting word frequencies in the first place.
"""
global jieba_tokenizer, jieba_orig_tokenizer
if external_wordlist:
if jieba_orig_tokenizer is None:
jieba_orig_tokenizer = jieba.Tokenizer(dictionary=ORIG_DICT_FILENAME)
return jieba_orig_tokenizer.lcut(text)
else:
if jieba_tokenizer is None:
jieba_tokenizer = jieba.Tokenizer(dictionary=DICT_FILENAME)
# Tokenize the Simplified Chinese version of the text, but return
# those spans from the original text, even if it's in Traditional
# Chinese
tokens = []
for _token, start, end in jieba_tokenizer.tokenize(simplify_chinese(text), HMM=False):
tokens.append(text[start:end])
return tokens | [
"def",
"jieba_tokenize",
"(",
"text",
",",
"external_wordlist",
"=",
"False",
")",
":",
"global",
"jieba_tokenizer",
",",
"jieba_orig_tokenizer",
"if",
"external_wordlist",
":",
"if",
"jieba_orig_tokenizer",
"is",
"None",
":",
"jieba_orig_tokenizer",
"=",
"jieba",
"... | Tokenize the given text into tokens whose word frequencies can probably
be looked up. This uses Jieba, a word-frequency-based tokenizer.
If `external_wordlist` is False, we tell Jieba to default to using
wordfreq's own Chinese wordlist, and not to infer unknown words using a
hidden Markov model. This ensures that the multi-character tokens that it
outputs will be ones whose word frequencies we can look up.
If `external_wordlist` is True, this will use the largest version of
Jieba's original dictionary, with HMM enabled, so its results will be
independent of the data in wordfreq. These results will be better optimized
for purposes that aren't looking up word frequencies, such as general-
purpose tokenization, or collecting word frequencies in the first place. | [
"Tokenize",
"the",
"given",
"text",
"into",
"tokens",
"whose",
"word",
"frequencies",
"can",
"probably",
"be",
"looked",
"up",
".",
"This",
"uses",
"Jieba",
"a",
"word",
"-",
"frequency",
"-",
"based",
"tokenizer",
"."
] | 170e3c6536854b06dc63da8d873e8cc4f9ef6180 | https://github.com/LuminosoInsight/wordfreq/blob/170e3c6536854b06dc63da8d873e8cc4f9ef6180/wordfreq/chinese.py#L28-L59 | train | 201,193 |
LuminosoInsight/wordfreq | wordfreq/preprocess.py | preprocess_text | def preprocess_text(text, language):
"""
This function applies pre-processing steps that convert forms of words
considered equivalent into one standardized form.
As one straightforward step, it case-folds the text. For the purposes of
wordfreq and related tools, a capitalized word shouldn't have a different
frequency from its lowercase version.
The steps that are applied in order, only some of which apply to each
language, are:
- NFC or NFKC normalization, as needed for the language
- Transliteration of multi-script languages
- Abjad mark removal
- Case folding
- Fixing of diacritics
We'll describe these steps out of order, to start with the more obvious
steps.
Case folding
------------
The most common effect of this function is that it case-folds alphabetic
text to lowercase:
>>> preprocess_text('Word', 'en')
'word'
This is proper Unicode-aware case-folding, so it eliminates distinctions
in lowercase letters that would not appear in uppercase. This accounts for
the German ß and the Greek final sigma:
>>> preprocess_text('groß', 'de')
'gross'
>>> preprocess_text('λέξις', 'el')
'λέξισ'
In Turkish (and Azerbaijani), case-folding is different, because the
uppercase and lowercase I come in two variants, one with a dot and one
without. They are matched in a way that preserves the number of dots, which
the usual pair of "I" and "i" do not.
>>> preprocess_text('HAKKINDA İSTANBUL', 'tr')
'hakkında istanbul'
Fixing of diacritics
--------------------
While we're talking about Turkish: the Turkish alphabet contains letters
with cedillas attached to the bottom. In the case of "ş" and "ţ", these
letters are very similar to two Romanian letters, "ș" and "ț", which have
separate _commas_ below them.
(Did you know that a cedilla is not the same as a comma under a letter? I
didn't until I started dealing with text normalization. My keyboard layout
even inputs a letter with a cedilla when you hit Compose+comma.)
Because these letters look so similar, and because some fonts only include
one pair of letters and not the other, there are many cases where the
letters are confused with each other. Our preprocessing normalizes these
Turkish and Romanian letters to the letters each language prefers.
>>> preprocess_text('kișinin', 'tr') # comma to cedilla
'kişinin'
>>> preprocess_text('ACELAŞI', 'ro') # cedilla to comma
'același'
Unicode normalization
---------------------
Unicode text is NFC normalized in most languages, removing trivial
distinctions between strings that should be considered equivalent in all
cases:
>>> word = preprocess_text('natu\N{COMBINING DIAERESIS}rlich', 'de')
>>> word
'natürlich'
>>> '\N{LATIN SMALL LETTER U WITH DIAERESIS}' in word
True
NFC normalization is sufficient (and NFKC normalization is a bit too strong)
for many languages that are written in cased, alphabetic scripts.
Languages in other scripts tend to need stronger normalization to properly
compare text. So we use NFC normalization when the language's script is
Latin, Greek, or Cyrillic, and we use NFKC normalization for all other
languages.
Here's an example in Japanese, where preprocessing changes the width (and
the case) of a Latin letter that's used as part of a word:
>>> preprocess_text('Uターン', 'ja')
'uターン'
In Korean, NFKC normalization is important because it aligns two different
ways of encoding text -- as individual letters that are grouped together
into square characters, or as the entire syllables that those characters
represent:
>>> word = '\u1102\u1161\u11c0\u1106\u1161\u11af'
>>> word
'낱말'
>>> len(word)
6
>>> word = preprocess_text(word, 'ko')
>>> word
'낱말'
>>> len(word)
2
Abjad mark removal
------------------
There are many abjad languages, such as Arabic, Hebrew, Persian, and Urdu,
where words can be marked with vowel points but rarely are. In languages
that use abjad scripts, we remove all modifiers that are classified by
Unicode as "marks". We also remove an Arabic character called the tatweel,
which is used to visually lengthen a word.
>>> preprocess_text("كَلِمَة", 'ar')
'كلمة'
>>> preprocess_text("الحمــــــد", 'ar')
'الحمد'
Transliteration of multi-script languages
-----------------------------------------
Some languages are written in multiple scripts, and require special care.
These languages include Chinese, Serbian, and Azerbaijani.
In Serbian, there is a well-established mapping from Cyrillic letters to
Latin letters. We apply this mapping so that Serbian is always represented
in Latin letters.
>>> preprocess_text('схваташ', 'sr')
'shvataš'
The transliteration is more complete than it needs to be to cover just
Serbian, so that -- for example -- borrowings from Russian can be
transliterated, instead of coming out in a mixed script.
>>> preprocess_text('культуры', 'sr')
"kul'tury"
Azerbaijani (Azeri) has a similar transliteration step to Serbian,
and then the Latin-alphabet text is handled similarly to Turkish.
>>> preprocess_text('бағырты', 'az')
'bağırtı'
We don't transliterate Traditional to Simplified Chinese in this step.
There are some steps where we unify them internally: see chinese.py
for more information.
"""
# NFC or NFKC normalization, as needed for the language
info = get_language_info(language)
text = unicodedata.normalize(info['normal_form'], text)
# Transliteration of multi-script languages
if info['transliteration'] is not None:
text = transliterate(info['transliteration'], text)
# Abjad mark removal
if info['remove_marks']:
text = remove_marks(text)
# Case folding
if info['dotless_i']:
text = casefold_with_i_dots(text)
else:
text = text.casefold()
# Fixing of diacritics
if info['diacritics_under'] == 'commas':
text = cedillas_to_commas(text)
elif info['diacritics_under'] == 'cedillas':
text = commas_to_cedillas(text)
return text | python | def preprocess_text(text, language):
"""
This function applies pre-processing steps that convert forms of words
considered equivalent into one standardized form.
As one straightforward step, it case-folds the text. For the purposes of
wordfreq and related tools, a capitalized word shouldn't have a different
frequency from its lowercase version.
The steps that are applied in order, only some of which apply to each
language, are:
- NFC or NFKC normalization, as needed for the language
- Transliteration of multi-script languages
- Abjad mark removal
- Case folding
- Fixing of diacritics
We'll describe these steps out of order, to start with the more obvious
steps.
Case folding
------------
The most common effect of this function is that it case-folds alphabetic
text to lowercase:
>>> preprocess_text('Word', 'en')
'word'
This is proper Unicode-aware case-folding, so it eliminates distinctions
in lowercase letters that would not appear in uppercase. This accounts for
the German ß and the Greek final sigma:
>>> preprocess_text('groß', 'de')
'gross'
>>> preprocess_text('λέξις', 'el')
'λέξισ'
In Turkish (and Azerbaijani), case-folding is different, because the
uppercase and lowercase I come in two variants, one with a dot and one
without. They are matched in a way that preserves the number of dots, which
the usual pair of "I" and "i" do not.
>>> preprocess_text('HAKKINDA İSTANBUL', 'tr')
'hakkında istanbul'
Fixing of diacritics
--------------------
While we're talking about Turkish: the Turkish alphabet contains letters
with cedillas attached to the bottom. In the case of "ş" and "ţ", these
letters are very similar to two Romanian letters, "ș" and "ț", which have
separate _commas_ below them.
(Did you know that a cedilla is not the same as a comma under a letter? I
didn't until I started dealing with text normalization. My keyboard layout
even inputs a letter with a cedilla when you hit Compose+comma.)
Because these letters look so similar, and because some fonts only include
one pair of letters and not the other, there are many cases where the
letters are confused with each other. Our preprocessing normalizes these
Turkish and Romanian letters to the letters each language prefers.
>>> preprocess_text('kișinin', 'tr') # comma to cedilla
'kişinin'
>>> preprocess_text('ACELAŞI', 'ro') # cedilla to comma
'același'
Unicode normalization
---------------------
Unicode text is NFC normalized in most languages, removing trivial
distinctions between strings that should be considered equivalent in all
cases:
>>> word = preprocess_text('natu\N{COMBINING DIAERESIS}rlich', 'de')
>>> word
'natürlich'
>>> '\N{LATIN SMALL LETTER U WITH DIAERESIS}' in word
True
NFC normalization is sufficient (and NFKC normalization is a bit too strong)
for many languages that are written in cased, alphabetic scripts.
Languages in other scripts tend to need stronger normalization to properly
compare text. So we use NFC normalization when the language's script is
Latin, Greek, or Cyrillic, and we use NFKC normalization for all other
languages.
Here's an example in Japanese, where preprocessing changes the width (and
the case) of a Latin letter that's used as part of a word:
>>> preprocess_text('Uターン', 'ja')
'uターン'
In Korean, NFKC normalization is important because it aligns two different
ways of encoding text -- as individual letters that are grouped together
into square characters, or as the entire syllables that those characters
represent:
>>> word = '\u1102\u1161\u11c0\u1106\u1161\u11af'
>>> word
'낱말'
>>> len(word)
6
>>> word = preprocess_text(word, 'ko')
>>> word
'낱말'
>>> len(word)
2
Abjad mark removal
------------------
There are many abjad languages, such as Arabic, Hebrew, Persian, and Urdu,
where words can be marked with vowel points but rarely are. In languages
that use abjad scripts, we remove all modifiers that are classified by
Unicode as "marks". We also remove an Arabic character called the tatweel,
which is used to visually lengthen a word.
>>> preprocess_text("كَلِمَة", 'ar')
'كلمة'
>>> preprocess_text("الحمــــــد", 'ar')
'الحمد'
Transliteration of multi-script languages
-----------------------------------------
Some languages are written in multiple scripts, and require special care.
These languages include Chinese, Serbian, and Azerbaijani.
In Serbian, there is a well-established mapping from Cyrillic letters to
Latin letters. We apply this mapping so that Serbian is always represented
in Latin letters.
>>> preprocess_text('схваташ', 'sr')
'shvataš'
The transliteration is more complete than it needs to be to cover just
Serbian, so that -- for example -- borrowings from Russian can be
transliterated, instead of coming out in a mixed script.
>>> preprocess_text('культуры', 'sr')
"kul'tury"
Azerbaijani (Azeri) has a similar transliteration step to Serbian,
and then the Latin-alphabet text is handled similarly to Turkish.
>>> preprocess_text('бағырты', 'az')
'bağırtı'
We don't transliterate Traditional to Simplified Chinese in this step.
There are some steps where we unify them internally: see chinese.py
for more information.
"""
# NFC or NFKC normalization, as needed for the language
info = get_language_info(language)
text = unicodedata.normalize(info['normal_form'], text)
# Transliteration of multi-script languages
if info['transliteration'] is not None:
text = transliterate(info['transliteration'], text)
# Abjad mark removal
if info['remove_marks']:
text = remove_marks(text)
# Case folding
if info['dotless_i']:
text = casefold_with_i_dots(text)
else:
text = text.casefold()
# Fixing of diacritics
if info['diacritics_under'] == 'commas':
text = cedillas_to_commas(text)
elif info['diacritics_under'] == 'cedillas':
text = commas_to_cedillas(text)
return text | [
"def",
"preprocess_text",
"(",
"text",
",",
"language",
")",
":",
"# NFC or NFKC normalization, as needed for the language",
"info",
"=",
"get_language_info",
"(",
"language",
")",
"text",
"=",
"unicodedata",
".",
"normalize",
"(",
"info",
"[",
"'normal_form'",
"]",
... | This function applies pre-processing steps that convert forms of words
considered equivalent into one standardized form.
As one straightforward step, it case-folds the text. For the purposes of
wordfreq and related tools, a capitalized word shouldn't have a different
frequency from its lowercase version.
The steps that are applied in order, only some of which apply to each
language, are:
- NFC or NFKC normalization, as needed for the language
- Transliteration of multi-script languages
- Abjad mark removal
- Case folding
- Fixing of diacritics
We'll describe these steps out of order, to start with the more obvious
steps.
Case folding
------------
The most common effect of this function is that it case-folds alphabetic
text to lowercase:
>>> preprocess_text('Word', 'en')
'word'
This is proper Unicode-aware case-folding, so it eliminates distinctions
in lowercase letters that would not appear in uppercase. This accounts for
the German ß and the Greek final sigma:
>>> preprocess_text('groß', 'de')
'gross'
>>> preprocess_text('λέξις', 'el')
'λέξισ'
In Turkish (and Azerbaijani), case-folding is different, because the
uppercase and lowercase I come in two variants, one with a dot and one
without. They are matched in a way that preserves the number of dots, which
the usual pair of "I" and "i" do not.
>>> preprocess_text('HAKKINDA İSTANBUL', 'tr')
'hakkında istanbul'
Fixing of diacritics
--------------------
While we're talking about Turkish: the Turkish alphabet contains letters
with cedillas attached to the bottom. In the case of "ş" and "ţ", these
letters are very similar to two Romanian letters, "ș" and "ț", which have
separate _commas_ below them.
(Did you know that a cedilla is not the same as a comma under a letter? I
didn't until I started dealing with text normalization. My keyboard layout
even inputs a letter with a cedilla when you hit Compose+comma.)
Because these letters look so similar, and because some fonts only include
one pair of letters and not the other, there are many cases where the
letters are confused with each other. Our preprocessing normalizes these
Turkish and Romanian letters to the letters each language prefers.
>>> preprocess_text('kișinin', 'tr') # comma to cedilla
'kişinin'
>>> preprocess_text('ACELAŞI', 'ro') # cedilla to comma
'același'
Unicode normalization
---------------------
Unicode text is NFC normalized in most languages, removing trivial
distinctions between strings that should be considered equivalent in all
cases:
>>> word = preprocess_text('natu\N{COMBINING DIAERESIS}rlich', 'de')
>>> word
'natürlich'
>>> '\N{LATIN SMALL LETTER U WITH DIAERESIS}' in word
True
NFC normalization is sufficient (and NFKC normalization is a bit too strong)
for many languages that are written in cased, alphabetic scripts.
Languages in other scripts tend to need stronger normalization to properly
compare text. So we use NFC normalization when the language's script is
Latin, Greek, or Cyrillic, and we use NFKC normalization for all other
languages.
Here's an example in Japanese, where preprocessing changes the width (and
the case) of a Latin letter that's used as part of a word:
>>> preprocess_text('Uターン', 'ja')
'uターン'
In Korean, NFKC normalization is important because it aligns two different
ways of encoding text -- as individual letters that are grouped together
into square characters, or as the entire syllables that those characters
represent:
>>> word = '\u1102\u1161\u11c0\u1106\u1161\u11af'
>>> word
'낱말'
>>> len(word)
6
>>> word = preprocess_text(word, 'ko')
>>> word
'낱말'
>>> len(word)
2
Abjad mark removal
------------------
There are many abjad languages, such as Arabic, Hebrew, Persian, and Urdu,
where words can be marked with vowel points but rarely are. In languages
that use abjad scripts, we remove all modifiers that are classified by
Unicode as "marks". We also remove an Arabic character called the tatweel,
which is used to visually lengthen a word.
>>> preprocess_text("كَلِمَة", 'ar')
'كلمة'
>>> preprocess_text("الحمــــــد", 'ar')
'الحمد'
Transliteration of multi-script languages
-----------------------------------------
Some languages are written in multiple scripts, and require special care.
These languages include Chinese, Serbian, and Azerbaijani.
In Serbian, there is a well-established mapping from Cyrillic letters to
Latin letters. We apply this mapping so that Serbian is always represented
in Latin letters.
>>> preprocess_text('схваташ', 'sr')
'shvataš'
The transliteration is more complete than it needs to be to cover just
Serbian, so that -- for example -- borrowings from Russian can be
transliterated, instead of coming out in a mixed script.
>>> preprocess_text('культуры', 'sr')
"kul'tury"
Azerbaijani (Azeri) has a similar transliteration step to Serbian,
and then the Latin-alphabet text is handled similarly to Turkish.
>>> preprocess_text('бағырты', 'az')
'bağırtı'
We don't transliterate Traditional to Simplified Chinese in this step.
There are some steps where we unify them internally: see chinese.py
for more information. | [
"This",
"function",
"applies",
"pre",
"-",
"processing",
"steps",
"that",
"convert",
"forms",
"of",
"words",
"considered",
"equivalent",
"into",
"one",
"standardized",
"form",
"."
] | 170e3c6536854b06dc63da8d873e8cc4f9ef6180 | https://github.com/LuminosoInsight/wordfreq/blob/170e3c6536854b06dc63da8d873e8cc4f9ef6180/wordfreq/preprocess.py#L13-L196 | train | 201,194 |
LuminosoInsight/wordfreq | wordfreq/language_info.py | _language_in_list | def _language_in_list(language, targets, min_score=80):
"""
A helper function to determine whether this language matches one of the
target languages, with a match score above a certain threshold.
The languages can be given as strings (language tags) or as Language
objects. `targets` can be any iterable of such languages.
"""
matched = best_match(language, targets, min_score=min_score)
return matched[1] > 0 | python | def _language_in_list(language, targets, min_score=80):
"""
A helper function to determine whether this language matches one of the
target languages, with a match score above a certain threshold.
The languages can be given as strings (language tags) or as Language
objects. `targets` can be any iterable of such languages.
"""
matched = best_match(language, targets, min_score=min_score)
return matched[1] > 0 | [
"def",
"_language_in_list",
"(",
"language",
",",
"targets",
",",
"min_score",
"=",
"80",
")",
":",
"matched",
"=",
"best_match",
"(",
"language",
",",
"targets",
",",
"min_score",
"=",
"min_score",
")",
"return",
"matched",
"[",
"1",
"]",
">",
"0"
] | A helper function to determine whether this language matches one of the
target languages, with a match score above a certain threshold.
The languages can be given as strings (language tags) or as Language
objects. `targets` can be any iterable of such languages. | [
"A",
"helper",
"function",
"to",
"determine",
"whether",
"this",
"language",
"matches",
"one",
"of",
"the",
"target",
"languages",
"with",
"a",
"match",
"score",
"above",
"a",
"certain",
"threshold",
"."
] | 170e3c6536854b06dc63da8d873e8cc4f9ef6180 | https://github.com/LuminosoInsight/wordfreq/blob/170e3c6536854b06dc63da8d873e8cc4f9ef6180/wordfreq/language_info.py#L48-L57 | train | 201,195 |
LuminosoInsight/wordfreq | wordfreq/mecab.py | mecab_tokenize | def mecab_tokenize(text, lang):
"""
Use the mecab-python3 package to tokenize the given text. The `lang`
must be 'ja' for Japanese or 'ko' for Korean.
The simplest output from mecab-python3 is the single-string form, which
contains the same table that the command-line version of MeCab would output.
We find the tokens in the first column of this table.
"""
if lang not in MECAB_DICTIONARY_NAMES:
raise ValueError("Can't run MeCab on language %r" % lang)
if lang not in MECAB_ANALYZERS:
MECAB_ANALYZERS[lang] = make_mecab_analyzer(MECAB_DICTIONARY_NAMES[lang])
analyzer = MECAB_ANALYZERS[lang]
text = unicodedata.normalize('NFKC', text.strip())
analyzed = analyzer.parse(text)
if not analyzed:
return []
return [line.split('\t')[0]
for line in analyzed.split('\n')
if line != '' and line != 'EOS'] | python | def mecab_tokenize(text, lang):
"""
Use the mecab-python3 package to tokenize the given text. The `lang`
must be 'ja' for Japanese or 'ko' for Korean.
The simplest output from mecab-python3 is the single-string form, which
contains the same table that the command-line version of MeCab would output.
We find the tokens in the first column of this table.
"""
if lang not in MECAB_DICTIONARY_NAMES:
raise ValueError("Can't run MeCab on language %r" % lang)
if lang not in MECAB_ANALYZERS:
MECAB_ANALYZERS[lang] = make_mecab_analyzer(MECAB_DICTIONARY_NAMES[lang])
analyzer = MECAB_ANALYZERS[lang]
text = unicodedata.normalize('NFKC', text.strip())
analyzed = analyzer.parse(text)
if not analyzed:
return []
return [line.split('\t')[0]
for line in analyzed.split('\n')
if line != '' and line != 'EOS'] | [
"def",
"mecab_tokenize",
"(",
"text",
",",
"lang",
")",
":",
"if",
"lang",
"not",
"in",
"MECAB_DICTIONARY_NAMES",
":",
"raise",
"ValueError",
"(",
"\"Can't run MeCab on language %r\"",
"%",
"lang",
")",
"if",
"lang",
"not",
"in",
"MECAB_ANALYZERS",
":",
"MECAB_A... | Use the mecab-python3 package to tokenize the given text. The `lang`
must be 'ja' for Japanese or 'ko' for Korean.
The simplest output from mecab-python3 is the single-string form, which
contains the same table that the command-line version of MeCab would output.
We find the tokens in the first column of this table. | [
"Use",
"the",
"mecab",
"-",
"python3",
"package",
"to",
"tokenize",
"the",
"given",
"text",
".",
"The",
"lang",
"must",
"be",
"ja",
"for",
"Japanese",
"or",
"ko",
"for",
"Korean",
"."
] | 170e3c6536854b06dc63da8d873e8cc4f9ef6180 | https://github.com/LuminosoInsight/wordfreq/blob/170e3c6536854b06dc63da8d873e8cc4f9ef6180/wordfreq/mecab.py#L65-L86 | train | 201,196 |
LuminosoInsight/wordfreq | wordfreq/transliterate.py | transliterate | def transliterate(table, text):
"""
Transliterate text according to one of the tables above.
`table` chooses the table. It looks like a language code but comes from a
very restricted set:
- 'sr-Latn' means to convert Serbian, which may be in Cyrillic, into the
Latin alphabet.
- 'az-Latn' means the same for Azerbaijani Cyrillic to Latn.
"""
if table == 'sr-Latn':
return text.translate(SR_LATN_TABLE)
elif table == 'az-Latn':
return text.translate(AZ_LATN_TABLE)
else:
raise ValueError("Unknown transliteration table: {!r}".format(table)) | python | def transliterate(table, text):
"""
Transliterate text according to one of the tables above.
`table` chooses the table. It looks like a language code but comes from a
very restricted set:
- 'sr-Latn' means to convert Serbian, which may be in Cyrillic, into the
Latin alphabet.
- 'az-Latn' means the same for Azerbaijani Cyrillic to Latn.
"""
if table == 'sr-Latn':
return text.translate(SR_LATN_TABLE)
elif table == 'az-Latn':
return text.translate(AZ_LATN_TABLE)
else:
raise ValueError("Unknown transliteration table: {!r}".format(table)) | [
"def",
"transliterate",
"(",
"table",
",",
"text",
")",
":",
"if",
"table",
"==",
"'sr-Latn'",
":",
"return",
"text",
".",
"translate",
"(",
"SR_LATN_TABLE",
")",
"elif",
"table",
"==",
"'az-Latn'",
":",
"return",
"text",
".",
"translate",
"(",
"AZ_LATN_TA... | Transliterate text according to one of the tables above.
`table` chooses the table. It looks like a language code but comes from a
very restricted set:
- 'sr-Latn' means to convert Serbian, which may be in Cyrillic, into the
Latin alphabet.
- 'az-Latn' means the same for Azerbaijani Cyrillic to Latn. | [
"Transliterate",
"text",
"according",
"to",
"one",
"of",
"the",
"tables",
"above",
"."
] | 170e3c6536854b06dc63da8d873e8cc4f9ef6180 | https://github.com/LuminosoInsight/wordfreq/blob/170e3c6536854b06dc63da8d873e8cc4f9ef6180/wordfreq/transliterate.py#L92-L108 | train | 201,197 |
ArchiveTeam/wpull | wpull/application/tasks/shutdown.py | AppStopTask._update_exit_code_from_stats | def _update_exit_code_from_stats(cls, statistics: Statistics,
app: Application):
'''Set the current exit code based on the Statistics.'''
for error_type in statistics.errors:
exit_code = app.ERROR_CODE_MAP.get(error_type)
if exit_code:
app.update_exit_code(exit_code) | python | def _update_exit_code_from_stats(cls, statistics: Statistics,
app: Application):
'''Set the current exit code based on the Statistics.'''
for error_type in statistics.errors:
exit_code = app.ERROR_CODE_MAP.get(error_type)
if exit_code:
app.update_exit_code(exit_code) | [
"def",
"_update_exit_code_from_stats",
"(",
"cls",
",",
"statistics",
":",
"Statistics",
",",
"app",
":",
"Application",
")",
":",
"for",
"error_type",
"in",
"statistics",
".",
"errors",
":",
"exit_code",
"=",
"app",
".",
"ERROR_CODE_MAP",
".",
"get",
"(",
"... | Set the current exit code based on the Statistics. | [
"Set",
"the",
"current",
"exit",
"code",
"based",
"on",
"the",
"Statistics",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/application/tasks/shutdown.py#L54-L60 | train | 201,198 |
ArchiveTeam/wpull | wpull/document/sitemap.py | SitemapReader.is_response | def is_response(cls, response):
'''Return whether the document is likely to be a Sitemap.'''
if response.body:
if cls.is_file(response.body):
return True | python | def is_response(cls, response):
'''Return whether the document is likely to be a Sitemap.'''
if response.body:
if cls.is_file(response.body):
return True | [
"def",
"is_response",
"(",
"cls",
",",
"response",
")",
":",
"if",
"response",
".",
"body",
":",
"if",
"cls",
".",
"is_file",
"(",
"response",
".",
"body",
")",
":",
"return",
"True"
] | Return whether the document is likely to be a Sitemap. | [
"Return",
"whether",
"the",
"document",
"is",
"likely",
"to",
"be",
"a",
"Sitemap",
"."
] | ddf051aa3322479325ba20aa778cb2cb97606bf5 | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/document/sitemap.py#L37-L41 | train | 201,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.