partition
stringclasses 3
values | func_name
stringlengths 1
134
| docstring
stringlengths 1
46.9k
| path
stringlengths 4
223
| original_string
stringlengths 75
104k
| code
stringlengths 75
104k
| docstring_tokens
listlengths 1
1.97k
| repo
stringlengths 7
55
| language
stringclasses 1
value | url
stringlengths 87
315
| code_tokens
listlengths 19
28.4k
| sha
stringlengths 40
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|
test
|
Striplog.find
|
Look for a regex expression in the descriptions of the striplog.
If there's no description, it looks in the summaries.
If you pass a Component, then it will search the components, not the
descriptions or summaries.
Case insensitive.
Args:
search_term (string or Component): The thing you want to search
for. Strings are treated as regular expressions.
index (bool): Whether to return the index instead of the interval.
Returns:
Striplog: A striplog that contains only the 'hit' Intervals.
However, if ``index`` was ``True``, then that's what you get.
|
striplog/striplog.py
|
def find(self, search_term, index=False):
"""
Look for a regex expression in the descriptions of the striplog.
If there's no description, it looks in the summaries.
If you pass a Component, then it will search the components, not the
descriptions or summaries.
Case insensitive.
Args:
search_term (string or Component): The thing you want to search
for. Strings are treated as regular expressions.
index (bool): Whether to return the index instead of the interval.
Returns:
Striplog: A striplog that contains only the 'hit' Intervals.
However, if ``index`` was ``True``, then that's what you get.
"""
hits = []
for i, iv in enumerate(self):
try:
search_text = iv.description or iv.primary.summary()
pattern = re.compile(search_term, flags=re.IGNORECASE)
if pattern.search(search_text):
hits.append(i)
except TypeError:
if search_term in iv.components:
hits.append(i)
if hits and index:
return hits
elif hits:
return self[hits]
else:
return
|
def find(self, search_term, index=False):
"""
Look for a regex expression in the descriptions of the striplog.
If there's no description, it looks in the summaries.
If you pass a Component, then it will search the components, not the
descriptions or summaries.
Case insensitive.
Args:
search_term (string or Component): The thing you want to search
for. Strings are treated as regular expressions.
index (bool): Whether to return the index instead of the interval.
Returns:
Striplog: A striplog that contains only the 'hit' Intervals.
However, if ``index`` was ``True``, then that's what you get.
"""
hits = []
for i, iv in enumerate(self):
try:
search_text = iv.description or iv.primary.summary()
pattern = re.compile(search_term, flags=re.IGNORECASE)
if pattern.search(search_text):
hits.append(i)
except TypeError:
if search_term in iv.components:
hits.append(i)
if hits and index:
return hits
elif hits:
return self[hits]
else:
return
|
[
"Look",
"for",
"a",
"regex",
"expression",
"in",
"the",
"descriptions",
"of",
"the",
"striplog",
".",
"If",
"there",
"s",
"no",
"description",
"it",
"looks",
"in",
"the",
"summaries",
"."
] |
agile-geoscience/striplog
|
python
|
https://github.com/agile-geoscience/striplog/blob/8033b673a151f96c29802b43763e863519a3124c/striplog/striplog.py#L1637-L1670
|
[
"def",
"find",
"(",
"self",
",",
"search_term",
",",
"index",
"=",
"False",
")",
":",
"hits",
"=",
"[",
"]",
"for",
"i",
",",
"iv",
"in",
"enumerate",
"(",
"self",
")",
":",
"try",
":",
"search_text",
"=",
"iv",
".",
"description",
"or",
"iv",
".",
"primary",
".",
"summary",
"(",
")",
"pattern",
"=",
"re",
".",
"compile",
"(",
"search_term",
",",
"flags",
"=",
"re",
".",
"IGNORECASE",
")",
"if",
"pattern",
".",
"search",
"(",
"search_text",
")",
":",
"hits",
".",
"append",
"(",
"i",
")",
"except",
"TypeError",
":",
"if",
"search_term",
"in",
"iv",
".",
"components",
":",
"hits",
".",
"append",
"(",
"i",
")",
"if",
"hits",
"and",
"index",
":",
"return",
"hits",
"elif",
"hits",
":",
"return",
"self",
"[",
"hits",
"]",
"else",
":",
"return"
] |
8033b673a151f96c29802b43763e863519a3124c
|
test
|
Striplog.__find_incongruities
|
Private method. Finds gaps and overlaps in a striplog. Called by
find_gaps() and find_overlaps().
Args:
op (operator): ``operator.gt`` or ``operator.lt``
index (bool): If ``True``, returns indices of intervals with
gaps after them.
Returns:
Striplog: A striplog of all the gaps. A sort of anti-striplog.
|
striplog/striplog.py
|
def __find_incongruities(self, op, index):
"""
Private method. Finds gaps and overlaps in a striplog. Called by
find_gaps() and find_overlaps().
Args:
op (operator): ``operator.gt`` or ``operator.lt``
index (bool): If ``True``, returns indices of intervals with
gaps after them.
Returns:
Striplog: A striplog of all the gaps. A sort of anti-striplog.
"""
if len(self) == 1:
return
hits = []
intervals = []
if self.order == 'depth':
one, two = 'base', 'top'
else:
one, two = 'top', 'base'
for i, iv in enumerate(self[:-1]):
next_iv = self[i+1]
if op(getattr(iv, one), getattr(next_iv, two)):
hits.append(i)
top = getattr(iv, one)
base = getattr(next_iv, two)
iv_gap = Interval(top, base)
intervals.append(iv_gap)
if index and hits:
return hits
elif intervals:
return Striplog(intervals)
else:
return
|
def __find_incongruities(self, op, index):
"""
Private method. Finds gaps and overlaps in a striplog. Called by
find_gaps() and find_overlaps().
Args:
op (operator): ``operator.gt`` or ``operator.lt``
index (bool): If ``True``, returns indices of intervals with
gaps after them.
Returns:
Striplog: A striplog of all the gaps. A sort of anti-striplog.
"""
if len(self) == 1:
return
hits = []
intervals = []
if self.order == 'depth':
one, two = 'base', 'top'
else:
one, two = 'top', 'base'
for i, iv in enumerate(self[:-1]):
next_iv = self[i+1]
if op(getattr(iv, one), getattr(next_iv, two)):
hits.append(i)
top = getattr(iv, one)
base = getattr(next_iv, two)
iv_gap = Interval(top, base)
intervals.append(iv_gap)
if index and hits:
return hits
elif intervals:
return Striplog(intervals)
else:
return
|
[
"Private",
"method",
".",
"Finds",
"gaps",
"and",
"overlaps",
"in",
"a",
"striplog",
".",
"Called",
"by",
"find_gaps",
"()",
"and",
"find_overlaps",
"()",
"."
] |
agile-geoscience/striplog
|
python
|
https://github.com/agile-geoscience/striplog/blob/8033b673a151f96c29802b43763e863519a3124c/striplog/striplog.py#L1672-L1711
|
[
"def",
"__find_incongruities",
"(",
"self",
",",
"op",
",",
"index",
")",
":",
"if",
"len",
"(",
"self",
")",
"==",
"1",
":",
"return",
"hits",
"=",
"[",
"]",
"intervals",
"=",
"[",
"]",
"if",
"self",
".",
"order",
"==",
"'depth'",
":",
"one",
",",
"two",
"=",
"'base'",
",",
"'top'",
"else",
":",
"one",
",",
"two",
"=",
"'top'",
",",
"'base'",
"for",
"i",
",",
"iv",
"in",
"enumerate",
"(",
"self",
"[",
":",
"-",
"1",
"]",
")",
":",
"next_iv",
"=",
"self",
"[",
"i",
"+",
"1",
"]",
"if",
"op",
"(",
"getattr",
"(",
"iv",
",",
"one",
")",
",",
"getattr",
"(",
"next_iv",
",",
"two",
")",
")",
":",
"hits",
".",
"append",
"(",
"i",
")",
"top",
"=",
"getattr",
"(",
"iv",
",",
"one",
")",
"base",
"=",
"getattr",
"(",
"next_iv",
",",
"two",
")",
"iv_gap",
"=",
"Interval",
"(",
"top",
",",
"base",
")",
"intervals",
".",
"append",
"(",
"iv_gap",
")",
"if",
"index",
"and",
"hits",
":",
"return",
"hits",
"elif",
"intervals",
":",
"return",
"Striplog",
"(",
"intervals",
")",
"else",
":",
"return"
] |
8033b673a151f96c29802b43763e863519a3124c
|
test
|
Striplog.find_overlaps
|
Find overlaps in a striplog.
Args:
index (bool): If True, returns indices of intervals with
gaps after them.
Returns:
Striplog: A striplog of all the overlaps as intervals.
|
striplog/striplog.py
|
def find_overlaps(self, index=False):
"""
Find overlaps in a striplog.
Args:
index (bool): If True, returns indices of intervals with
gaps after them.
Returns:
Striplog: A striplog of all the overlaps as intervals.
"""
return self.__find_incongruities(op=operator.gt, index=index)
|
def find_overlaps(self, index=False):
"""
Find overlaps in a striplog.
Args:
index (bool): If True, returns indices of intervals with
gaps after them.
Returns:
Striplog: A striplog of all the overlaps as intervals.
"""
return self.__find_incongruities(op=operator.gt, index=index)
|
[
"Find",
"overlaps",
"in",
"a",
"striplog",
"."
] |
agile-geoscience/striplog
|
python
|
https://github.com/agile-geoscience/striplog/blob/8033b673a151f96c29802b43763e863519a3124c/striplog/striplog.py#L1713-L1724
|
[
"def",
"find_overlaps",
"(",
"self",
",",
"index",
"=",
"False",
")",
":",
"return",
"self",
".",
"__find_incongruities",
"(",
"op",
"=",
"operator",
".",
"gt",
",",
"index",
"=",
"index",
")"
] |
8033b673a151f96c29802b43763e863519a3124c
|
test
|
Striplog.find_gaps
|
Finds gaps in a striplog.
Args:
index (bool): If True, returns indices of intervals with
gaps after them.
Returns:
Striplog: A striplog of all the gaps. A sort of anti-striplog.
|
striplog/striplog.py
|
def find_gaps(self, index=False):
"""
Finds gaps in a striplog.
Args:
index (bool): If True, returns indices of intervals with
gaps after them.
Returns:
Striplog: A striplog of all the gaps. A sort of anti-striplog.
"""
return self.__find_incongruities(op=operator.lt, index=index)
|
def find_gaps(self, index=False):
"""
Finds gaps in a striplog.
Args:
index (bool): If True, returns indices of intervals with
gaps after them.
Returns:
Striplog: A striplog of all the gaps. A sort of anti-striplog.
"""
return self.__find_incongruities(op=operator.lt, index=index)
|
[
"Finds",
"gaps",
"in",
"a",
"striplog",
"."
] |
agile-geoscience/striplog
|
python
|
https://github.com/agile-geoscience/striplog/blob/8033b673a151f96c29802b43763e863519a3124c/striplog/striplog.py#L1726-L1737
|
[
"def",
"find_gaps",
"(",
"self",
",",
"index",
"=",
"False",
")",
":",
"return",
"self",
".",
"__find_incongruities",
"(",
"op",
"=",
"operator",
".",
"lt",
",",
"index",
"=",
"index",
")"
] |
8033b673a151f96c29802b43763e863519a3124c
|
test
|
Striplog.prune
|
Remove intervals below a certain limit thickness. In place.
Args:
limit (float): Anything thinner than this will be pruned.
n (int): The n thinnest beds will be pruned.
percentile (float): The thinnest specified percentile will be
pruned.
keep_ends (bool): Whether to keep the first and last, regardless
of whether they meet the pruning criteria.
|
striplog/striplog.py
|
def prune(self, limit=None, n=None, percentile=None, keep_ends=False):
"""
Remove intervals below a certain limit thickness. In place.
Args:
limit (float): Anything thinner than this will be pruned.
n (int): The n thinnest beds will be pruned.
percentile (float): The thinnest specified percentile will be
pruned.
keep_ends (bool): Whether to keep the first and last, regardless
of whether they meet the pruning criteria.
"""
strip = self.copy()
if not (limit or n or percentile):
m = "You must provide a limit or n or percentile for pruning."
raise StriplogError(m)
if limit:
prune = [i for i, iv in enumerate(strip) if iv.thickness < limit]
if n:
prune = strip.thinnest(n=n, index=True)
if percentile:
n = np.floor(len(strip)*percentile/100)
prune = strip.thinnest(n=n, index=True)
if keep_ends:
first, last = 0, len(strip) - 1
if first in prune:
prune.remove(first)
if last in prune:
prune.remove(last)
del strip[prune]
return strip
|
def prune(self, limit=None, n=None, percentile=None, keep_ends=False):
"""
Remove intervals below a certain limit thickness. In place.
Args:
limit (float): Anything thinner than this will be pruned.
n (int): The n thinnest beds will be pruned.
percentile (float): The thinnest specified percentile will be
pruned.
keep_ends (bool): Whether to keep the first and last, regardless
of whether they meet the pruning criteria.
"""
strip = self.copy()
if not (limit or n or percentile):
m = "You must provide a limit or n or percentile for pruning."
raise StriplogError(m)
if limit:
prune = [i for i, iv in enumerate(strip) if iv.thickness < limit]
if n:
prune = strip.thinnest(n=n, index=True)
if percentile:
n = np.floor(len(strip)*percentile/100)
prune = strip.thinnest(n=n, index=True)
if keep_ends:
first, last = 0, len(strip) - 1
if first in prune:
prune.remove(first)
if last in prune:
prune.remove(last)
del strip[prune]
return strip
|
[
"Remove",
"intervals",
"below",
"a",
"certain",
"limit",
"thickness",
".",
"In",
"place",
"."
] |
agile-geoscience/striplog
|
python
|
https://github.com/agile-geoscience/striplog/blob/8033b673a151f96c29802b43763e863519a3124c/striplog/striplog.py#L1739-L1773
|
[
"def",
"prune",
"(",
"self",
",",
"limit",
"=",
"None",
",",
"n",
"=",
"None",
",",
"percentile",
"=",
"None",
",",
"keep_ends",
"=",
"False",
")",
":",
"strip",
"=",
"self",
".",
"copy",
"(",
")",
"if",
"not",
"(",
"limit",
"or",
"n",
"or",
"percentile",
")",
":",
"m",
"=",
"\"You must provide a limit or n or percentile for pruning.\"",
"raise",
"StriplogError",
"(",
"m",
")",
"if",
"limit",
":",
"prune",
"=",
"[",
"i",
"for",
"i",
",",
"iv",
"in",
"enumerate",
"(",
"strip",
")",
"if",
"iv",
".",
"thickness",
"<",
"limit",
"]",
"if",
"n",
":",
"prune",
"=",
"strip",
".",
"thinnest",
"(",
"n",
"=",
"n",
",",
"index",
"=",
"True",
")",
"if",
"percentile",
":",
"n",
"=",
"np",
".",
"floor",
"(",
"len",
"(",
"strip",
")",
"*",
"percentile",
"/",
"100",
")",
"prune",
"=",
"strip",
".",
"thinnest",
"(",
"n",
"=",
"n",
",",
"index",
"=",
"True",
")",
"if",
"keep_ends",
":",
"first",
",",
"last",
"=",
"0",
",",
"len",
"(",
"strip",
")",
"-",
"1",
"if",
"first",
"in",
"prune",
":",
"prune",
".",
"remove",
"(",
"first",
")",
"if",
"last",
"in",
"prune",
":",
"prune",
".",
"remove",
"(",
"last",
")",
"del",
"strip",
"[",
"prune",
"]",
"return",
"strip"
] |
8033b673a151f96c29802b43763e863519a3124c
|
test
|
Striplog.anneal
|
Fill in empty intervals by growing from top and base.
Note that this operation happens in-place and destroys any information
about the ``Position`` (e.g. metadata associated with the top or base).
See GitHub issue #54.
|
striplog/striplog.py
|
def anneal(self):
"""
Fill in empty intervals by growing from top and base.
Note that this operation happens in-place and destroys any information
about the ``Position`` (e.g. metadata associated with the top or base).
See GitHub issue #54.
"""
strip = self.copy()
gaps = strip.find_gaps(index=True)
if not gaps:
return
for gap in gaps:
before = strip[gap]
after = strip[gap + 1]
if strip.order == 'depth':
t = (after.top.z-before.base.z)/2
before.base = before.base.z + t
after.top = after.top.z - t
else:
t = (after.base-before.top)/2
before.top = before.top.z + t
after.base = after.base.z - t
return strip
|
def anneal(self):
"""
Fill in empty intervals by growing from top and base.
Note that this operation happens in-place and destroys any information
about the ``Position`` (e.g. metadata associated with the top or base).
See GitHub issue #54.
"""
strip = self.copy()
gaps = strip.find_gaps(index=True)
if not gaps:
return
for gap in gaps:
before = strip[gap]
after = strip[gap + 1]
if strip.order == 'depth':
t = (after.top.z-before.base.z)/2
before.base = before.base.z + t
after.top = after.top.z - t
else:
t = (after.base-before.top)/2
before.top = before.top.z + t
after.base = after.base.z - t
return strip
|
[
"Fill",
"in",
"empty",
"intervals",
"by",
"growing",
"from",
"top",
"and",
"base",
"."
] |
agile-geoscience/striplog
|
python
|
https://github.com/agile-geoscience/striplog/blob/8033b673a151f96c29802b43763e863519a3124c/striplog/striplog.py#L1775-L1803
|
[
"def",
"anneal",
"(",
"self",
")",
":",
"strip",
"=",
"self",
".",
"copy",
"(",
")",
"gaps",
"=",
"strip",
".",
"find_gaps",
"(",
"index",
"=",
"True",
")",
"if",
"not",
"gaps",
":",
"return",
"for",
"gap",
"in",
"gaps",
":",
"before",
"=",
"strip",
"[",
"gap",
"]",
"after",
"=",
"strip",
"[",
"gap",
"+",
"1",
"]",
"if",
"strip",
".",
"order",
"==",
"'depth'",
":",
"t",
"=",
"(",
"after",
".",
"top",
".",
"z",
"-",
"before",
".",
"base",
".",
"z",
")",
"/",
"2",
"before",
".",
"base",
"=",
"before",
".",
"base",
".",
"z",
"+",
"t",
"after",
".",
"top",
"=",
"after",
".",
"top",
".",
"z",
"-",
"t",
"else",
":",
"t",
"=",
"(",
"after",
".",
"base",
"-",
"before",
".",
"top",
")",
"/",
"2",
"before",
".",
"top",
"=",
"before",
".",
"top",
".",
"z",
"+",
"t",
"after",
".",
"base",
"=",
"after",
".",
"base",
".",
"z",
"-",
"t",
"return",
"strip"
] |
8033b673a151f96c29802b43763e863519a3124c
|
test
|
Striplog.fill
|
Fill gaps with the component provided.
Example
t = s.fill(Component({'lithology': 'cheese'}))
|
striplog/striplog.py
|
def fill(self, component=None):
"""
Fill gaps with the component provided.
Example
t = s.fill(Component({'lithology': 'cheese'}))
"""
c = [component] if component is not None else []
# Make the intervals to go in the gaps.
gaps = self.find_gaps()
if not gaps:
return self
for iv in gaps:
iv.components = c
return deepcopy(self) + gaps
|
def fill(self, component=None):
"""
Fill gaps with the component provided.
Example
t = s.fill(Component({'lithology': 'cheese'}))
"""
c = [component] if component is not None else []
# Make the intervals to go in the gaps.
gaps = self.find_gaps()
if not gaps:
return self
for iv in gaps:
iv.components = c
return deepcopy(self) + gaps
|
[
"Fill",
"gaps",
"with",
"the",
"component",
"provided",
"."
] |
agile-geoscience/striplog
|
python
|
https://github.com/agile-geoscience/striplog/blob/8033b673a151f96c29802b43763e863519a3124c/striplog/striplog.py#L1805-L1821
|
[
"def",
"fill",
"(",
"self",
",",
"component",
"=",
"None",
")",
":",
"c",
"=",
"[",
"component",
"]",
"if",
"component",
"is",
"not",
"None",
"else",
"[",
"]",
"# Make the intervals to go in the gaps.",
"gaps",
"=",
"self",
".",
"find_gaps",
"(",
")",
"if",
"not",
"gaps",
":",
"return",
"self",
"for",
"iv",
"in",
"gaps",
":",
"iv",
".",
"components",
"=",
"c",
"return",
"deepcopy",
"(",
"self",
")",
"+",
"gaps"
] |
8033b673a151f96c29802b43763e863519a3124c
|
test
|
Striplog.union
|
Makes a striplog of all unions.
Args:
Striplog. The striplog instance to union with.
Returns:
Striplog. The result of the union.
|
striplog/striplog.py
|
def union(self, other):
"""
Makes a striplog of all unions.
Args:
Striplog. The striplog instance to union with.
Returns:
Striplog. The result of the union.
"""
if not isinstance(other, self.__class__):
m = "You can only union striplogs with each other."
raise StriplogError(m)
result = []
for iv in deepcopy(self):
for jv in other:
if iv.any_overlaps(jv):
iv = iv.union(jv)
result.append(iv)
return Striplog(result)
|
def union(self, other):
"""
Makes a striplog of all unions.
Args:
Striplog. The striplog instance to union with.
Returns:
Striplog. The result of the union.
"""
if not isinstance(other, self.__class__):
m = "You can only union striplogs with each other."
raise StriplogError(m)
result = []
for iv in deepcopy(self):
for jv in other:
if iv.any_overlaps(jv):
iv = iv.union(jv)
result.append(iv)
return Striplog(result)
|
[
"Makes",
"a",
"striplog",
"of",
"all",
"unions",
"."
] |
agile-geoscience/striplog
|
python
|
https://github.com/agile-geoscience/striplog/blob/8033b673a151f96c29802b43763e863519a3124c/striplog/striplog.py#L1823-L1843
|
[
"def",
"union",
"(",
"self",
",",
"other",
")",
":",
"if",
"not",
"isinstance",
"(",
"other",
",",
"self",
".",
"__class__",
")",
":",
"m",
"=",
"\"You can only union striplogs with each other.\"",
"raise",
"StriplogError",
"(",
"m",
")",
"result",
"=",
"[",
"]",
"for",
"iv",
"in",
"deepcopy",
"(",
"self",
")",
":",
"for",
"jv",
"in",
"other",
":",
"if",
"iv",
".",
"any_overlaps",
"(",
"jv",
")",
":",
"iv",
"=",
"iv",
".",
"union",
"(",
"jv",
")",
"result",
".",
"append",
"(",
"iv",
")",
"return",
"Striplog",
"(",
"result",
")"
] |
8033b673a151f96c29802b43763e863519a3124c
|
test
|
Striplog.intersect
|
Makes a striplog of all intersections.
Args:
Striplog. The striplog instance to intersect with.
Returns:
Striplog. The result of the intersection.
|
striplog/striplog.py
|
def intersect(self, other):
"""
Makes a striplog of all intersections.
Args:
Striplog. The striplog instance to intersect with.
Returns:
Striplog. The result of the intersection.
"""
if not isinstance(other, self.__class__):
m = "You can only intersect striplogs with each other."
raise StriplogError(m)
result = []
for iv in self:
for jv in other:
try:
result.append(iv.intersect(jv))
except IntervalError:
# The intervals don't overlap
pass
return Striplog(result)
|
def intersect(self, other):
"""
Makes a striplog of all intersections.
Args:
Striplog. The striplog instance to intersect with.
Returns:
Striplog. The result of the intersection.
"""
if not isinstance(other, self.__class__):
m = "You can only intersect striplogs with each other."
raise StriplogError(m)
result = []
for iv in self:
for jv in other:
try:
result.append(iv.intersect(jv))
except IntervalError:
# The intervals don't overlap
pass
return Striplog(result)
|
[
"Makes",
"a",
"striplog",
"of",
"all",
"intersections",
"."
] |
agile-geoscience/striplog
|
python
|
https://github.com/agile-geoscience/striplog/blob/8033b673a151f96c29802b43763e863519a3124c/striplog/striplog.py#L1845-L1867
|
[
"def",
"intersect",
"(",
"self",
",",
"other",
")",
":",
"if",
"not",
"isinstance",
"(",
"other",
",",
"self",
".",
"__class__",
")",
":",
"m",
"=",
"\"You can only intersect striplogs with each other.\"",
"raise",
"StriplogError",
"(",
"m",
")",
"result",
"=",
"[",
"]",
"for",
"iv",
"in",
"self",
":",
"for",
"jv",
"in",
"other",
":",
"try",
":",
"result",
".",
"append",
"(",
"iv",
".",
"intersect",
"(",
"jv",
")",
")",
"except",
"IntervalError",
":",
"# The intervals don't overlap",
"pass",
"return",
"Striplog",
"(",
"result",
")"
] |
8033b673a151f96c29802b43763e863519a3124c
|
test
|
Striplog.merge_overlaps
|
Merges overlaps by merging overlapping Intervals.
The function takes no arguments and returns ``None``. It operates on
the striplog 'in place'
TODO: This function will not work if any interval overlaps more than
one other intervals at either its base or top.
|
striplog/striplog.py
|
def merge_overlaps(self):
"""
Merges overlaps by merging overlapping Intervals.
The function takes no arguments and returns ``None``. It operates on
the striplog 'in place'
TODO: This function will not work if any interval overlaps more than
one other intervals at either its base or top.
"""
overlaps = np.array(self.find_overlaps(index=True))
if not overlaps.any():
return
for overlap in overlaps:
before = self[overlap].copy()
after = self[overlap + 1].copy()
# Get rid of the before and after pieces.
del self[overlap]
del self[overlap]
# Make the new piece.
new_segment = before.merge(after)
# Insert it.
self.__insert(overlap, new_segment)
overlaps += 1
return
|
def merge_overlaps(self):
"""
Merges overlaps by merging overlapping Intervals.
The function takes no arguments and returns ``None``. It operates on
the striplog 'in place'
TODO: This function will not work if any interval overlaps more than
one other intervals at either its base or top.
"""
overlaps = np.array(self.find_overlaps(index=True))
if not overlaps.any():
return
for overlap in overlaps:
before = self[overlap].copy()
after = self[overlap + 1].copy()
# Get rid of the before and after pieces.
del self[overlap]
del self[overlap]
# Make the new piece.
new_segment = before.merge(after)
# Insert it.
self.__insert(overlap, new_segment)
overlaps += 1
return
|
[
"Merges",
"overlaps",
"by",
"merging",
"overlapping",
"Intervals",
"."
] |
agile-geoscience/striplog
|
python
|
https://github.com/agile-geoscience/striplog/blob/8033b673a151f96c29802b43763e863519a3124c/striplog/striplog.py#L1869-L1900
|
[
"def",
"merge_overlaps",
"(",
"self",
")",
":",
"overlaps",
"=",
"np",
".",
"array",
"(",
"self",
".",
"find_overlaps",
"(",
"index",
"=",
"True",
")",
")",
"if",
"not",
"overlaps",
".",
"any",
"(",
")",
":",
"return",
"for",
"overlap",
"in",
"overlaps",
":",
"before",
"=",
"self",
"[",
"overlap",
"]",
".",
"copy",
"(",
")",
"after",
"=",
"self",
"[",
"overlap",
"+",
"1",
"]",
".",
"copy",
"(",
")",
"# Get rid of the before and after pieces.",
"del",
"self",
"[",
"overlap",
"]",
"del",
"self",
"[",
"overlap",
"]",
"# Make the new piece.",
"new_segment",
"=",
"before",
".",
"merge",
"(",
"after",
")",
"# Insert it.",
"self",
".",
"__insert",
"(",
"overlap",
",",
"new_segment",
")",
"overlaps",
"+=",
"1",
"return"
] |
8033b673a151f96c29802b43763e863519a3124c
|
test
|
Striplog.merge_neighbours
|
Makes a new striplog in which matching neighbours (for which the
components are the same) are unioned. That is, they are replaced by
a new Interval with the same top as the uppermost and the same bottom
as the lowermost.
Args
strict (bool): If True, then all of the components must match.
If False, then only the primary must match.
Returns:
Striplog. A new striplog.
TODO:
Might need to be tweaked to deal with 'binary striplogs' if those
aren't implemented with components.
|
striplog/striplog.py
|
def merge_neighbours(self, strict=True):
"""
Makes a new striplog in which matching neighbours (for which the
components are the same) are unioned. That is, they are replaced by
a new Interval with the same top as the uppermost and the same bottom
as the lowermost.
Args
strict (bool): If True, then all of the components must match.
If False, then only the primary must match.
Returns:
Striplog. A new striplog.
TODO:
Might need to be tweaked to deal with 'binary striplogs' if those
aren't implemented with components.
"""
new_strip = [self[0].copy()]
for lower in self[1:]:
# Determine if touching.
touching = new_strip[-1].touches(lower)
# Decide if match.
if strict:
similar = new_strip[-1].components == lower.components
else:
similar = new_strip[-1].primary == lower.primary
# Union if both criteria met.
if touching and similar:
new_strip[-1] = new_strip[-1].union(lower)
else:
new_strip.append(lower.copy())
return Striplog(new_strip)
|
def merge_neighbours(self, strict=True):
"""
Makes a new striplog in which matching neighbours (for which the
components are the same) are unioned. That is, they are replaced by
a new Interval with the same top as the uppermost and the same bottom
as the lowermost.
Args
strict (bool): If True, then all of the components must match.
If False, then only the primary must match.
Returns:
Striplog. A new striplog.
TODO:
Might need to be tweaked to deal with 'binary striplogs' if those
aren't implemented with components.
"""
new_strip = [self[0].copy()]
for lower in self[1:]:
# Determine if touching.
touching = new_strip[-1].touches(lower)
# Decide if match.
if strict:
similar = new_strip[-1].components == lower.components
else:
similar = new_strip[-1].primary == lower.primary
# Union if both criteria met.
if touching and similar:
new_strip[-1] = new_strip[-1].union(lower)
else:
new_strip.append(lower.copy())
return Striplog(new_strip)
|
[
"Makes",
"a",
"new",
"striplog",
"in",
"which",
"matching",
"neighbours",
"(",
"for",
"which",
"the",
"components",
"are",
"the",
"same",
")",
"are",
"unioned",
".",
"That",
"is",
"they",
"are",
"replaced",
"by",
"a",
"new",
"Interval",
"with",
"the",
"same",
"top",
"as",
"the",
"uppermost",
"and",
"the",
"same",
"bottom",
"as",
"the",
"lowermost",
"."
] |
agile-geoscience/striplog
|
python
|
https://github.com/agile-geoscience/striplog/blob/8033b673a151f96c29802b43763e863519a3124c/striplog/striplog.py#L1902-L1939
|
[
"def",
"merge_neighbours",
"(",
"self",
",",
"strict",
"=",
"True",
")",
":",
"new_strip",
"=",
"[",
"self",
"[",
"0",
"]",
".",
"copy",
"(",
")",
"]",
"for",
"lower",
"in",
"self",
"[",
"1",
":",
"]",
":",
"# Determine if touching.",
"touching",
"=",
"new_strip",
"[",
"-",
"1",
"]",
".",
"touches",
"(",
"lower",
")",
"# Decide if match.",
"if",
"strict",
":",
"similar",
"=",
"new_strip",
"[",
"-",
"1",
"]",
".",
"components",
"==",
"lower",
".",
"components",
"else",
":",
"similar",
"=",
"new_strip",
"[",
"-",
"1",
"]",
".",
"primary",
"==",
"lower",
".",
"primary",
"# Union if both criteria met.",
"if",
"touching",
"and",
"similar",
":",
"new_strip",
"[",
"-",
"1",
"]",
"=",
"new_strip",
"[",
"-",
"1",
"]",
".",
"union",
"(",
"lower",
")",
"else",
":",
"new_strip",
".",
"append",
"(",
"lower",
".",
"copy",
"(",
")",
")",
"return",
"Striplog",
"(",
"new_strip",
")"
] |
8033b673a151f96c29802b43763e863519a3124c
|
test
|
Striplog.thickest
|
Returns the thickest interval(s) as a striplog.
Args:
n (int): The number of thickest intervals to return. Default: 1.
index (bool): If True, only the indices of the intervals are
returned. You can use this to index into the striplog.
Returns:
Interval. The thickest interval. Or, if ``index`` was ``True``,
the index of the thickest interval.
|
striplog/striplog.py
|
def thickest(self, n=1, index=False):
"""
Returns the thickest interval(s) as a striplog.
Args:
n (int): The number of thickest intervals to return. Default: 1.
index (bool): If True, only the indices of the intervals are
returned. You can use this to index into the striplog.
Returns:
Interval. The thickest interval. Or, if ``index`` was ``True``,
the index of the thickest interval.
"""
s = sorted(range(len(self)), key=lambda k: self[k].thickness)
indices = s[-n:]
if index:
return indices
else:
if n == 1:
# Then return an interval.
i = indices[0]
return self[i]
else:
return self[indices]
|
def thickest(self, n=1, index=False):
"""
Returns the thickest interval(s) as a striplog.
Args:
n (int): The number of thickest intervals to return. Default: 1.
index (bool): If True, only the indices of the intervals are
returned. You can use this to index into the striplog.
Returns:
Interval. The thickest interval. Or, if ``index`` was ``True``,
the index of the thickest interval.
"""
s = sorted(range(len(self)), key=lambda k: self[k].thickness)
indices = s[-n:]
if index:
return indices
else:
if n == 1:
# Then return an interval.
i = indices[0]
return self[i]
else:
return self[indices]
|
[
"Returns",
"the",
"thickest",
"interval",
"(",
"s",
")",
"as",
"a",
"striplog",
"."
] |
agile-geoscience/striplog
|
python
|
https://github.com/agile-geoscience/striplog/blob/8033b673a151f96c29802b43763e863519a3124c/striplog/striplog.py#L1941-L1964
|
[
"def",
"thickest",
"(",
"self",
",",
"n",
"=",
"1",
",",
"index",
"=",
"False",
")",
":",
"s",
"=",
"sorted",
"(",
"range",
"(",
"len",
"(",
"self",
")",
")",
",",
"key",
"=",
"lambda",
"k",
":",
"self",
"[",
"k",
"]",
".",
"thickness",
")",
"indices",
"=",
"s",
"[",
"-",
"n",
":",
"]",
"if",
"index",
":",
"return",
"indices",
"else",
":",
"if",
"n",
"==",
"1",
":",
"# Then return an interval.",
"i",
"=",
"indices",
"[",
"0",
"]",
"return",
"self",
"[",
"i",
"]",
"else",
":",
"return",
"self",
"[",
"indices",
"]"
] |
8033b673a151f96c29802b43763e863519a3124c
|
test
|
Striplog.hist
|
Plots a histogram and returns the data for it.
Args:
lumping (str): If given, the bins will be lumped based on this
attribute of the primary components of the intervals
encountered.
summary (bool): If True, the summaries of the components are
returned as the bins. Otherwise, the default behaviour is to
return the Components themselves.
sort (bool): If True (default), the histogram is sorted by value,
starting with the largest.
plot (bool): If True (default), produce a bar plot.
legend (Legend): The legend with which to colour the bars.
ax (axis): An axis object, which will be returned if provided.
If you don't provide one, it will be created but not returned.
Returns:
Tuple: A tuple of tuples of entities and counts.
TODO:
Deal with numeric properties, so I can histogram 'Vp' values, say.
|
striplog/striplog.py
|
def hist(self,
lumping=None,
summary=False,
sort=True,
plot=True,
legend=None,
ax=None
):
"""
Plots a histogram and returns the data for it.
Args:
lumping (str): If given, the bins will be lumped based on this
attribute of the primary components of the intervals
encountered.
summary (bool): If True, the summaries of the components are
returned as the bins. Otherwise, the default behaviour is to
return the Components themselves.
sort (bool): If True (default), the histogram is sorted by value,
starting with the largest.
plot (bool): If True (default), produce a bar plot.
legend (Legend): The legend with which to colour the bars.
ax (axis): An axis object, which will be returned if provided.
If you don't provide one, it will be created but not returned.
Returns:
Tuple: A tuple of tuples of entities and counts.
TODO:
Deal with numeric properties, so I can histogram 'Vp' values, say.
"""
# This seems like overkill, but collecting all this stuff gives
# the user some choice about what they get back.
comps = []
labels = []
entries = defaultdict(int)
for i in self:
if lumping:
k = i.primary[lumping]
else:
if summary:
k = i.primary.summary()
else:
k = i.primary
comps.append(i.primary)
labels.append(i.primary.summary())
entries[k] += i.thickness
if sort:
allitems = sorted(entries.items(), key=lambda i: i[1], reverse=True)
ents, counts = zip(*allitems)
else:
ents, counts = tuple(entries.keys()), tuple(entries.values())
# Make plot.
if plot:
if ax is None:
fig, ax = plt.subplots()
return_ax = False
else:
return_ax = True
ind = np.arange(len(ents))
bars = ax.bar(ind, counts, align='center')
ax.set_xticks(ind)
ax.set_xticklabels(labels)
if legend:
colours = [legend.get_colour(c) for c in comps]
for b, c in zip(bars, colours):
b.set_color(c)
ax.set_ylabel('Thickness [m]')
else:
bars = []
if plot and return_ax:
return counts, ents, ax
return counts, ents, bars
|
def hist(self,
lumping=None,
summary=False,
sort=True,
plot=True,
legend=None,
ax=None
):
"""
Plots a histogram and returns the data for it.
Args:
lumping (str): If given, the bins will be lumped based on this
attribute of the primary components of the intervals
encountered.
summary (bool): If True, the summaries of the components are
returned as the bins. Otherwise, the default behaviour is to
return the Components themselves.
sort (bool): If True (default), the histogram is sorted by value,
starting with the largest.
plot (bool): If True (default), produce a bar plot.
legend (Legend): The legend with which to colour the bars.
ax (axis): An axis object, which will be returned if provided.
If you don't provide one, it will be created but not returned.
Returns:
Tuple: A tuple of tuples of entities and counts.
TODO:
Deal with numeric properties, so I can histogram 'Vp' values, say.
"""
# This seems like overkill, but collecting all this stuff gives
# the user some choice about what they get back.
comps = []
labels = []
entries = defaultdict(int)
for i in self:
if lumping:
k = i.primary[lumping]
else:
if summary:
k = i.primary.summary()
else:
k = i.primary
comps.append(i.primary)
labels.append(i.primary.summary())
entries[k] += i.thickness
if sort:
allitems = sorted(entries.items(), key=lambda i: i[1], reverse=True)
ents, counts = zip(*allitems)
else:
ents, counts = tuple(entries.keys()), tuple(entries.values())
# Make plot.
if plot:
if ax is None:
fig, ax = plt.subplots()
return_ax = False
else:
return_ax = True
ind = np.arange(len(ents))
bars = ax.bar(ind, counts, align='center')
ax.set_xticks(ind)
ax.set_xticklabels(labels)
if legend:
colours = [legend.get_colour(c) for c in comps]
for b, c in zip(bars, colours):
b.set_color(c)
ax.set_ylabel('Thickness [m]')
else:
bars = []
if plot and return_ax:
return counts, ents, ax
return counts, ents, bars
|
[
"Plots",
"a",
"histogram",
"and",
"returns",
"the",
"data",
"for",
"it",
"."
] |
agile-geoscience/striplog
|
python
|
https://github.com/agile-geoscience/striplog/blob/8033b673a151f96c29802b43763e863519a3124c/striplog/striplog.py#L1994-L2070
|
[
"def",
"hist",
"(",
"self",
",",
"lumping",
"=",
"None",
",",
"summary",
"=",
"False",
",",
"sort",
"=",
"True",
",",
"plot",
"=",
"True",
",",
"legend",
"=",
"None",
",",
"ax",
"=",
"None",
")",
":",
"# This seems like overkill, but collecting all this stuff gives",
"# the user some choice about what they get back.",
"comps",
"=",
"[",
"]",
"labels",
"=",
"[",
"]",
"entries",
"=",
"defaultdict",
"(",
"int",
")",
"for",
"i",
"in",
"self",
":",
"if",
"lumping",
":",
"k",
"=",
"i",
".",
"primary",
"[",
"lumping",
"]",
"else",
":",
"if",
"summary",
":",
"k",
"=",
"i",
".",
"primary",
".",
"summary",
"(",
")",
"else",
":",
"k",
"=",
"i",
".",
"primary",
"comps",
".",
"append",
"(",
"i",
".",
"primary",
")",
"labels",
".",
"append",
"(",
"i",
".",
"primary",
".",
"summary",
"(",
")",
")",
"entries",
"[",
"k",
"]",
"+=",
"i",
".",
"thickness",
"if",
"sort",
":",
"allitems",
"=",
"sorted",
"(",
"entries",
".",
"items",
"(",
")",
",",
"key",
"=",
"lambda",
"i",
":",
"i",
"[",
"1",
"]",
",",
"reverse",
"=",
"True",
")",
"ents",
",",
"counts",
"=",
"zip",
"(",
"*",
"allitems",
")",
"else",
":",
"ents",
",",
"counts",
"=",
"tuple",
"(",
"entries",
".",
"keys",
"(",
")",
")",
",",
"tuple",
"(",
"entries",
".",
"values",
"(",
")",
")",
"# Make plot.",
"if",
"plot",
":",
"if",
"ax",
"is",
"None",
":",
"fig",
",",
"ax",
"=",
"plt",
".",
"subplots",
"(",
")",
"return_ax",
"=",
"False",
"else",
":",
"return_ax",
"=",
"True",
"ind",
"=",
"np",
".",
"arange",
"(",
"len",
"(",
"ents",
")",
")",
"bars",
"=",
"ax",
".",
"bar",
"(",
"ind",
",",
"counts",
",",
"align",
"=",
"'center'",
")",
"ax",
".",
"set_xticks",
"(",
"ind",
")",
"ax",
".",
"set_xticklabels",
"(",
"labels",
")",
"if",
"legend",
":",
"colours",
"=",
"[",
"legend",
".",
"get_colour",
"(",
"c",
")",
"for",
"c",
"in",
"comps",
"]",
"for",
"b",
",",
"c",
"in",
"zip",
"(",
"bars",
",",
"colours",
")",
":",
"b",
".",
"set_color",
"(",
"c",
")",
"ax",
".",
"set_ylabel",
"(",
"'Thickness [m]'",
")",
"else",
":",
"bars",
"=",
"[",
"]",
"if",
"plot",
"and",
"return_ax",
":",
"return",
"counts",
",",
"ents",
",",
"ax",
"return",
"counts",
",",
"ents",
",",
"bars"
] |
8033b673a151f96c29802b43763e863519a3124c
|
test
|
Striplog.bar
|
Make a bar plot of thickness per interval.
Args:
height (str): The property of the primary component to plot.
sort (bool or function): Either pass a boolean indicating whether
to reverse sort by thickness, or pass a function to be used as
the sort key.
reverse (bool): Reverses the sort order.
legend (Legend): The legend to plot with.
ax (axis): Optional axis to plot to.
figsize (tuple): A figure size, (width, height), optional.
**kwargs: passed to the matplotlib bar plot command, ax.bar().
Returns:
axis: If you sent an axis in, you get it back.
|
striplog/striplog.py
|
def bar(self, height='thickness', sort=False, reverse=False,
legend=None, ax=None, figsize=None, **kwargs):
"""
Make a bar plot of thickness per interval.
Args:
height (str): The property of the primary component to plot.
sort (bool or function): Either pass a boolean indicating whether
to reverse sort by thickness, or pass a function to be used as
the sort key.
reverse (bool): Reverses the sort order.
legend (Legend): The legend to plot with.
ax (axis): Optional axis to plot to.
figsize (tuple): A figure size, (width, height), optional.
**kwargs: passed to the matplotlib bar plot command, ax.bar().
Returns:
axis: If you sent an axis in, you get it back.
"""
if sort:
if sort is True:
def func(x): return x.thickness
reverse = True
data = sorted(self, key=func, reverse=reverse)
else:
data = self[:]
if ax is None:
fig, ax = plt.subplots(figsize=figsize)
heights = [getattr(i, height) for i in data]
comps = [i[0] for i in self.unique]
if legend is None:
legend = Legend.random(comps)
colors = [legend.get_colour(i.primary) for i in data]
bars = ax.bar(range(len(data)), height=heights, color=colors, **kwargs)
# Legend.
colourables = [i.primary.summary() for i in data]
unique_bars = dict(zip(colourables, bars))
ax.legend(unique_bars.values(), unique_bars.keys())
ax.set_ylabel(height.title())
return ax
|
def bar(self, height='thickness', sort=False, reverse=False,
legend=None, ax=None, figsize=None, **kwargs):
"""
Make a bar plot of thickness per interval.
Args:
height (str): The property of the primary component to plot.
sort (bool or function): Either pass a boolean indicating whether
to reverse sort by thickness, or pass a function to be used as
the sort key.
reverse (bool): Reverses the sort order.
legend (Legend): The legend to plot with.
ax (axis): Optional axis to plot to.
figsize (tuple): A figure size, (width, height), optional.
**kwargs: passed to the matplotlib bar plot command, ax.bar().
Returns:
axis: If you sent an axis in, you get it back.
"""
if sort:
if sort is True:
def func(x): return x.thickness
reverse = True
data = sorted(self, key=func, reverse=reverse)
else:
data = self[:]
if ax is None:
fig, ax = plt.subplots(figsize=figsize)
heights = [getattr(i, height) for i in data]
comps = [i[0] for i in self.unique]
if legend is None:
legend = Legend.random(comps)
colors = [legend.get_colour(i.primary) for i in data]
bars = ax.bar(range(len(data)), height=heights, color=colors, **kwargs)
# Legend.
colourables = [i.primary.summary() for i in data]
unique_bars = dict(zip(colourables, bars))
ax.legend(unique_bars.values(), unique_bars.keys())
ax.set_ylabel(height.title())
return ax
|
[
"Make",
"a",
"bar",
"plot",
"of",
"thickness",
"per",
"interval",
".",
"Args",
":",
"height",
"(",
"str",
")",
":",
"The",
"property",
"of",
"the",
"primary",
"component",
"to",
"plot",
".",
"sort",
"(",
"bool",
"or",
"function",
")",
":",
"Either",
"pass",
"a",
"boolean",
"indicating",
"whether",
"to",
"reverse",
"sort",
"by",
"thickness",
"or",
"pass",
"a",
"function",
"to",
"be",
"used",
"as",
"the",
"sort",
"key",
".",
"reverse",
"(",
"bool",
")",
":",
"Reverses",
"the",
"sort",
"order",
".",
"legend",
"(",
"Legend",
")",
":",
"The",
"legend",
"to",
"plot",
"with",
".",
"ax",
"(",
"axis",
")",
":",
"Optional",
"axis",
"to",
"plot",
"to",
".",
"figsize",
"(",
"tuple",
")",
":",
"A",
"figure",
"size",
"(",
"width",
"height",
")",
"optional",
".",
"**",
"kwargs",
":",
"passed",
"to",
"the",
"matplotlib",
"bar",
"plot",
"command",
"ax",
".",
"bar",
"()",
".",
"Returns",
":",
"axis",
":",
"If",
"you",
"sent",
"an",
"axis",
"in",
"you",
"get",
"it",
"back",
"."
] |
agile-geoscience/striplog
|
python
|
https://github.com/agile-geoscience/striplog/blob/8033b673a151f96c29802b43763e863519a3124c/striplog/striplog.py#L2074-L2122
|
[
"def",
"bar",
"(",
"self",
",",
"height",
"=",
"'thickness'",
",",
"sort",
"=",
"False",
",",
"reverse",
"=",
"False",
",",
"legend",
"=",
"None",
",",
"ax",
"=",
"None",
",",
"figsize",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"sort",
":",
"if",
"sort",
"is",
"True",
":",
"def",
"func",
"(",
"x",
")",
":",
"return",
"x",
".",
"thickness",
"reverse",
"=",
"True",
"data",
"=",
"sorted",
"(",
"self",
",",
"key",
"=",
"func",
",",
"reverse",
"=",
"reverse",
")",
"else",
":",
"data",
"=",
"self",
"[",
":",
"]",
"if",
"ax",
"is",
"None",
":",
"fig",
",",
"ax",
"=",
"plt",
".",
"subplots",
"(",
"figsize",
"=",
"figsize",
")",
"heights",
"=",
"[",
"getattr",
"(",
"i",
",",
"height",
")",
"for",
"i",
"in",
"data",
"]",
"comps",
"=",
"[",
"i",
"[",
"0",
"]",
"for",
"i",
"in",
"self",
".",
"unique",
"]",
"if",
"legend",
"is",
"None",
":",
"legend",
"=",
"Legend",
".",
"random",
"(",
"comps",
")",
"colors",
"=",
"[",
"legend",
".",
"get_colour",
"(",
"i",
".",
"primary",
")",
"for",
"i",
"in",
"data",
"]",
"bars",
"=",
"ax",
".",
"bar",
"(",
"range",
"(",
"len",
"(",
"data",
")",
")",
",",
"height",
"=",
"heights",
",",
"color",
"=",
"colors",
",",
"*",
"*",
"kwargs",
")",
"# Legend.",
"colourables",
"=",
"[",
"i",
".",
"primary",
".",
"summary",
"(",
")",
"for",
"i",
"in",
"data",
"]",
"unique_bars",
"=",
"dict",
"(",
"zip",
"(",
"colourables",
",",
"bars",
")",
")",
"ax",
".",
"legend",
"(",
"unique_bars",
".",
"values",
"(",
")",
",",
"unique_bars",
".",
"keys",
"(",
")",
")",
"ax",
".",
"set_ylabel",
"(",
"height",
".",
"title",
"(",
")",
")",
"return",
"ax"
] |
8033b673a151f96c29802b43763e863519a3124c
|
test
|
Striplog.invert
|
Inverts the striplog, changing its order and the order of its contents.
Operates in place by default.
Args:
copy (bool): Whether to operate in place or make a copy.
Returns:
None if operating in-place, or an inverted copy of the striplog
if not.
|
striplog/striplog.py
|
def invert(self, copy=False):
"""
Inverts the striplog, changing its order and the order of its contents.
Operates in place by default.
Args:
copy (bool): Whether to operate in place or make a copy.
Returns:
None if operating in-place, or an inverted copy of the striplog
if not.
"""
if copy:
return Striplog([i.invert(copy=True) for i in self])
else:
for i in self:
i.invert()
self.__sort()
o = self.order
self.order = {'depth': 'elevation', 'elevation': 'depth'}[o]
return
|
def invert(self, copy=False):
"""
Inverts the striplog, changing its order and the order of its contents.
Operates in place by default.
Args:
copy (bool): Whether to operate in place or make a copy.
Returns:
None if operating in-place, or an inverted copy of the striplog
if not.
"""
if copy:
return Striplog([i.invert(copy=True) for i in self])
else:
for i in self:
i.invert()
self.__sort()
o = self.order
self.order = {'depth': 'elevation', 'elevation': 'depth'}[o]
return
|
[
"Inverts",
"the",
"striplog",
"changing",
"its",
"order",
"and",
"the",
"order",
"of",
"its",
"contents",
"."
] |
agile-geoscience/striplog
|
python
|
https://github.com/agile-geoscience/striplog/blob/8033b673a151f96c29802b43763e863519a3124c/striplog/striplog.py#L2124-L2145
|
[
"def",
"invert",
"(",
"self",
",",
"copy",
"=",
"False",
")",
":",
"if",
"copy",
":",
"return",
"Striplog",
"(",
"[",
"i",
".",
"invert",
"(",
"copy",
"=",
"True",
")",
"for",
"i",
"in",
"self",
"]",
")",
"else",
":",
"for",
"i",
"in",
"self",
":",
"i",
".",
"invert",
"(",
")",
"self",
".",
"__sort",
"(",
")",
"o",
"=",
"self",
".",
"order",
"self",
".",
"order",
"=",
"{",
"'depth'",
":",
"'elevation'",
",",
"'elevation'",
":",
"'depth'",
"}",
"[",
"o",
"]",
"return"
] |
8033b673a151f96c29802b43763e863519a3124c
|
test
|
Striplog.crop
|
Crop to a new depth range.
Args:
extent (tuple): The new start and stop depth. Must be 'inside'
existing striplog.
copy (bool): Whether to operate in place or make a copy.
Returns:
Operates in place by deault; if copy is True, returns a striplog.
|
striplog/striplog.py
|
def crop(self, extent, copy=False):
"""
Crop to a new depth range.
Args:
extent (tuple): The new start and stop depth. Must be 'inside'
existing striplog.
copy (bool): Whether to operate in place or make a copy.
Returns:
Operates in place by deault; if copy is True, returns a striplog.
"""
try:
if extent[0] is None:
extent = (self.start.z, extent[1])
if extent[1] is None:
extent = (extent[0], self.stop.z)
except:
m = "You must provide a 2-tuple for the new extents. Use None for"
m += " the existing start or stop."
raise StriplogError(m)
first_ix = self.read_at(extent[0], index=True)
last_ix = self.read_at(extent[1], index=True)
first = self[first_ix].split_at(extent[0])[1]
last = self[last_ix].split_at(extent[1])[0]
new_list = self.__list[first_ix:last_ix+1].copy()
new_list[0] = first
new_list[-1] = last
if copy:
return Striplog(new_list)
else:
self.__list = new_list
return
|
def crop(self, extent, copy=False):
"""
Crop to a new depth range.
Args:
extent (tuple): The new start and stop depth. Must be 'inside'
existing striplog.
copy (bool): Whether to operate in place or make a copy.
Returns:
Operates in place by deault; if copy is True, returns a striplog.
"""
try:
if extent[0] is None:
extent = (self.start.z, extent[1])
if extent[1] is None:
extent = (extent[0], self.stop.z)
except:
m = "You must provide a 2-tuple for the new extents. Use None for"
m += " the existing start or stop."
raise StriplogError(m)
first_ix = self.read_at(extent[0], index=True)
last_ix = self.read_at(extent[1], index=True)
first = self[first_ix].split_at(extent[0])[1]
last = self[last_ix].split_at(extent[1])[0]
new_list = self.__list[first_ix:last_ix+1].copy()
new_list[0] = first
new_list[-1] = last
if copy:
return Striplog(new_list)
else:
self.__list = new_list
return
|
[
"Crop",
"to",
"a",
"new",
"depth",
"range",
"."
] |
agile-geoscience/striplog
|
python
|
https://github.com/agile-geoscience/striplog/blob/8033b673a151f96c29802b43763e863519a3124c/striplog/striplog.py#L2147-L2183
|
[
"def",
"crop",
"(",
"self",
",",
"extent",
",",
"copy",
"=",
"False",
")",
":",
"try",
":",
"if",
"extent",
"[",
"0",
"]",
"is",
"None",
":",
"extent",
"=",
"(",
"self",
".",
"start",
".",
"z",
",",
"extent",
"[",
"1",
"]",
")",
"if",
"extent",
"[",
"1",
"]",
"is",
"None",
":",
"extent",
"=",
"(",
"extent",
"[",
"0",
"]",
",",
"self",
".",
"stop",
".",
"z",
")",
"except",
":",
"m",
"=",
"\"You must provide a 2-tuple for the new extents. Use None for\"",
"m",
"+=",
"\" the existing start or stop.\"",
"raise",
"StriplogError",
"(",
"m",
")",
"first_ix",
"=",
"self",
".",
"read_at",
"(",
"extent",
"[",
"0",
"]",
",",
"index",
"=",
"True",
")",
"last_ix",
"=",
"self",
".",
"read_at",
"(",
"extent",
"[",
"1",
"]",
",",
"index",
"=",
"True",
")",
"first",
"=",
"self",
"[",
"first_ix",
"]",
".",
"split_at",
"(",
"extent",
"[",
"0",
"]",
")",
"[",
"1",
"]",
"last",
"=",
"self",
"[",
"last_ix",
"]",
".",
"split_at",
"(",
"extent",
"[",
"1",
"]",
")",
"[",
"0",
"]",
"new_list",
"=",
"self",
".",
"__list",
"[",
"first_ix",
":",
"last_ix",
"+",
"1",
"]",
".",
"copy",
"(",
")",
"new_list",
"[",
"0",
"]",
"=",
"first",
"new_list",
"[",
"-",
"1",
"]",
"=",
"last",
"if",
"copy",
":",
"return",
"Striplog",
"(",
"new_list",
")",
"else",
":",
"self",
".",
"__list",
"=",
"new_list",
"return"
] |
8033b673a151f96c29802b43763e863519a3124c
|
test
|
Striplog.quality
|
Run a series of tests and return the corresponding results.
Based on curve testing for ``welly``.
Args:
tests (list): a list of functions.
Returns:
list. The results. Stick to booleans (True = pass) or ints.
|
striplog/striplog.py
|
def quality(self, tests, alias=None):
"""
Run a series of tests and return the corresponding results.
Based on curve testing for ``welly``.
Args:
tests (list): a list of functions.
Returns:
list. The results. Stick to booleans (True = pass) or ints.
"""
# This is hacky... striplog should probably merge with welly...
# Ignore aliases
alias = alias or {}
alias = alias.get('striplog', alias.get('Striplog', []))
# Gather the tests.
# First, anything called 'all', 'All', or 'ALL'.
# Second, anything with the name of the curve we're in now.
# Third, anything that the alias list has for this curve.
# (This requires a reverse look-up so it's a bit messy.)
this_tests =\
tests.get('all', [])+tests.get('All', [])+tests.get('ALL', [])\
+ tests.get('striplog', tests.get('Striplog', []))\
+ utils.flatten_list([tests.get(a) for a in alias])
this_tests = filter(None, this_tests)
# If we explicitly set zero tests for a particular key, then this
# overrides the 'all' tests.
if not tests.get('striplog', tests.get('Striplog', 1)):
this_tests = []
return {test.__name__: test(self) for test in this_tests}
|
def quality(self, tests, alias=None):
"""
Run a series of tests and return the corresponding results.
Based on curve testing for ``welly``.
Args:
tests (list): a list of functions.
Returns:
list. The results. Stick to booleans (True = pass) or ints.
"""
# This is hacky... striplog should probably merge with welly...
# Ignore aliases
alias = alias or {}
alias = alias.get('striplog', alias.get('Striplog', []))
# Gather the tests.
# First, anything called 'all', 'All', or 'ALL'.
# Second, anything with the name of the curve we're in now.
# Third, anything that the alias list has for this curve.
# (This requires a reverse look-up so it's a bit messy.)
this_tests =\
tests.get('all', [])+tests.get('All', [])+tests.get('ALL', [])\
+ tests.get('striplog', tests.get('Striplog', []))\
+ utils.flatten_list([tests.get(a) for a in alias])
this_tests = filter(None, this_tests)
# If we explicitly set zero tests for a particular key, then this
# overrides the 'all' tests.
if not tests.get('striplog', tests.get('Striplog', 1)):
this_tests = []
return {test.__name__: test(self) for test in this_tests}
|
[
"Run",
"a",
"series",
"of",
"tests",
"and",
"return",
"the",
"corresponding",
"results",
"."
] |
agile-geoscience/striplog
|
python
|
https://github.com/agile-geoscience/striplog/blob/8033b673a151f96c29802b43763e863519a3124c/striplog/striplog.py#L2185-L2219
|
[
"def",
"quality",
"(",
"self",
",",
"tests",
",",
"alias",
"=",
"None",
")",
":",
"# This is hacky... striplog should probably merge with welly...",
"# Ignore aliases",
"alias",
"=",
"alias",
"or",
"{",
"}",
"alias",
"=",
"alias",
".",
"get",
"(",
"'striplog'",
",",
"alias",
".",
"get",
"(",
"'Striplog'",
",",
"[",
"]",
")",
")",
"# Gather the tests.",
"# First, anything called 'all', 'All', or 'ALL'.",
"# Second, anything with the name of the curve we're in now.",
"# Third, anything that the alias list has for this curve.",
"# (This requires a reverse look-up so it's a bit messy.)",
"this_tests",
"=",
"tests",
".",
"get",
"(",
"'all'",
",",
"[",
"]",
")",
"+",
"tests",
".",
"get",
"(",
"'All'",
",",
"[",
"]",
")",
"+",
"tests",
".",
"get",
"(",
"'ALL'",
",",
"[",
"]",
")",
"+",
"tests",
".",
"get",
"(",
"'striplog'",
",",
"tests",
".",
"get",
"(",
"'Striplog'",
",",
"[",
"]",
")",
")",
"+",
"utils",
".",
"flatten_list",
"(",
"[",
"tests",
".",
"get",
"(",
"a",
")",
"for",
"a",
"in",
"alias",
"]",
")",
"this_tests",
"=",
"filter",
"(",
"None",
",",
"this_tests",
")",
"# If we explicitly set zero tests for a particular key, then this",
"# overrides the 'all' tests.",
"if",
"not",
"tests",
".",
"get",
"(",
"'striplog'",
",",
"tests",
".",
"get",
"(",
"'Striplog'",
",",
"1",
")",
")",
":",
"this_tests",
"=",
"[",
"]",
"return",
"{",
"test",
".",
"__name__",
":",
"test",
"(",
"self",
")",
"for",
"test",
"in",
"this_tests",
"}"
] |
8033b673a151f96c29802b43763e863519a3124c
|
test
|
dict_repr_html
|
Jupyter Notebook magic repr function.
|
striplog/utils.py
|
def dict_repr_html(dictionary):
"""
Jupyter Notebook magic repr function.
"""
rows = ''
s = '<tr><td><strong>{k}</strong></td><td>{v}</td></tr>'
for k, v in dictionary.items():
rows += s.format(k=k, v=v)
html = '<table>{}</table>'.format(rows)
return html
|
def dict_repr_html(dictionary):
"""
Jupyter Notebook magic repr function.
"""
rows = ''
s = '<tr><td><strong>{k}</strong></td><td>{v}</td></tr>'
for k, v in dictionary.items():
rows += s.format(k=k, v=v)
html = '<table>{}</table>'.format(rows)
return html
|
[
"Jupyter",
"Notebook",
"magic",
"repr",
"function",
"."
] |
agile-geoscience/striplog
|
python
|
https://github.com/agile-geoscience/striplog/blob/8033b673a151f96c29802b43763e863519a3124c/striplog/utils.py#L123-L132
|
[
"def",
"dict_repr_html",
"(",
"dictionary",
")",
":",
"rows",
"=",
"''",
"s",
"=",
"'<tr><td><strong>{k}</strong></td><td>{v}</td></tr>'",
"for",
"k",
",",
"v",
"in",
"dictionary",
".",
"items",
"(",
")",
":",
"rows",
"+=",
"s",
".",
"format",
"(",
"k",
"=",
"k",
",",
"v",
"=",
"v",
")",
"html",
"=",
"'<table>{}</table>'",
".",
"format",
"(",
"rows",
")",
"return",
"html"
] |
8033b673a151f96c29802b43763e863519a3124c
|
test
|
hex_to_name
|
Convert hex to a color name, using matplotlib's colour names.
Args:
hexx (str): A hexadecimal colour, starting with '#'.
Returns:
str: The name of the colour, or None if not found.
|
striplog/utils.py
|
def hex_to_name(hexx):
"""
Convert hex to a color name, using matplotlib's colour names.
Args:
hexx (str): A hexadecimal colour, starting with '#'.
Returns:
str: The name of the colour, or None if not found.
"""
for n, h in defaults.COLOURS.items():
if (len(n) > 1) and (h == hexx.upper()):
return n.lower()
return None
|
def hex_to_name(hexx):
"""
Convert hex to a color name, using matplotlib's colour names.
Args:
hexx (str): A hexadecimal colour, starting with '#'.
Returns:
str: The name of the colour, or None if not found.
"""
for n, h in defaults.COLOURS.items():
if (len(n) > 1) and (h == hexx.upper()):
return n.lower()
return None
|
[
"Convert",
"hex",
"to",
"a",
"color",
"name",
"using",
"matplotlib",
"s",
"colour",
"names",
"."
] |
agile-geoscience/striplog
|
python
|
https://github.com/agile-geoscience/striplog/blob/8033b673a151f96c29802b43763e863519a3124c/striplog/utils.py#L179-L192
|
[
"def",
"hex_to_name",
"(",
"hexx",
")",
":",
"for",
"n",
",",
"h",
"in",
"defaults",
".",
"COLOURS",
".",
"items",
"(",
")",
":",
"if",
"(",
"len",
"(",
"n",
")",
">",
"1",
")",
"and",
"(",
"h",
"==",
"hexx",
".",
"upper",
"(",
")",
")",
":",
"return",
"n",
".",
"lower",
"(",
")",
"return",
"None"
] |
8033b673a151f96c29802b43763e863519a3124c
|
test
|
rgb_to_hex
|
Utility function to convert (r,g,b) triples to hex.
http://ageo.co/1CFxXpO
Args:
rgb (tuple): A sequence of RGB values in the
range 0-255 or 0-1.
Returns:
str: The hex code for the colour.
|
striplog/utils.py
|
def rgb_to_hex(rgb):
"""
Utility function to convert (r,g,b) triples to hex.
http://ageo.co/1CFxXpO
Args:
rgb (tuple): A sequence of RGB values in the
range 0-255 or 0-1.
Returns:
str: The hex code for the colour.
"""
r, g, b = rgb[:3]
if (r < 0) or (g < 0) or (b < 0):
raise Exception("RGB values must all be 0-255 or 0-1")
if (r > 255) or (g > 255) or (b > 255):
raise Exception("RGB values must all be 0-255 or 0-1")
if (0 < r < 1) or (0 < g < 1) or (0 < b < 1):
if (r > 1) or (g > 1) or (b > 1):
raise Exception("RGB values must all be 0-255 or 0-1")
if (0 <= r <= 1) and (0 <= g <= 1) and (0 <= b <= 1):
rgb = tuple([int(round(val * 255)) for val in [r, g, b]])
else:
rgb = (int(r), int(g), int(b))
result = '#%02x%02x%02x' % rgb
return result.lower()
|
def rgb_to_hex(rgb):
"""
Utility function to convert (r,g,b) triples to hex.
http://ageo.co/1CFxXpO
Args:
rgb (tuple): A sequence of RGB values in the
range 0-255 or 0-1.
Returns:
str: The hex code for the colour.
"""
r, g, b = rgb[:3]
if (r < 0) or (g < 0) or (b < 0):
raise Exception("RGB values must all be 0-255 or 0-1")
if (r > 255) or (g > 255) or (b > 255):
raise Exception("RGB values must all be 0-255 or 0-1")
if (0 < r < 1) or (0 < g < 1) or (0 < b < 1):
if (r > 1) or (g > 1) or (b > 1):
raise Exception("RGB values must all be 0-255 or 0-1")
if (0 <= r <= 1) and (0 <= g <= 1) and (0 <= b <= 1):
rgb = tuple([int(round(val * 255)) for val in [r, g, b]])
else:
rgb = (int(r), int(g), int(b))
result = '#%02x%02x%02x' % rgb
return result.lower()
|
[
"Utility",
"function",
"to",
"convert",
"(",
"r",
"g",
"b",
")",
"triples",
"to",
"hex",
".",
"http",
":",
"//",
"ageo",
".",
"co",
"/",
"1CFxXpO",
"Args",
":",
"rgb",
"(",
"tuple",
")",
":",
"A",
"sequence",
"of",
"RGB",
"values",
"in",
"the",
"range",
"0",
"-",
"255",
"or",
"0",
"-",
"1",
".",
"Returns",
":",
"str",
":",
"The",
"hex",
"code",
"for",
"the",
"colour",
"."
] |
agile-geoscience/striplog
|
python
|
https://github.com/agile-geoscience/striplog/blob/8033b673a151f96c29802b43763e863519a3124c/striplog/utils.py#L208-L231
|
[
"def",
"rgb_to_hex",
"(",
"rgb",
")",
":",
"r",
",",
"g",
",",
"b",
"=",
"rgb",
"[",
":",
"3",
"]",
"if",
"(",
"r",
"<",
"0",
")",
"or",
"(",
"g",
"<",
"0",
")",
"or",
"(",
"b",
"<",
"0",
")",
":",
"raise",
"Exception",
"(",
"\"RGB values must all be 0-255 or 0-1\"",
")",
"if",
"(",
"r",
">",
"255",
")",
"or",
"(",
"g",
">",
"255",
")",
"or",
"(",
"b",
">",
"255",
")",
":",
"raise",
"Exception",
"(",
"\"RGB values must all be 0-255 or 0-1\"",
")",
"if",
"(",
"0",
"<",
"r",
"<",
"1",
")",
"or",
"(",
"0",
"<",
"g",
"<",
"1",
")",
"or",
"(",
"0",
"<",
"b",
"<",
"1",
")",
":",
"if",
"(",
"r",
">",
"1",
")",
"or",
"(",
"g",
">",
"1",
")",
"or",
"(",
"b",
">",
"1",
")",
":",
"raise",
"Exception",
"(",
"\"RGB values must all be 0-255 or 0-1\"",
")",
"if",
"(",
"0",
"<=",
"r",
"<=",
"1",
")",
"and",
"(",
"0",
"<=",
"g",
"<=",
"1",
")",
"and",
"(",
"0",
"<=",
"b",
"<=",
"1",
")",
":",
"rgb",
"=",
"tuple",
"(",
"[",
"int",
"(",
"round",
"(",
"val",
"*",
"255",
")",
")",
"for",
"val",
"in",
"[",
"r",
",",
"g",
",",
"b",
"]",
"]",
")",
"else",
":",
"rgb",
"=",
"(",
"int",
"(",
"r",
")",
",",
"int",
"(",
"g",
")",
",",
"int",
"(",
"b",
")",
")",
"result",
"=",
"'#%02x%02x%02x'",
"%",
"rgb",
"return",
"result",
".",
"lower",
"(",
")"
] |
8033b673a151f96c29802b43763e863519a3124c
|
test
|
loglike_from_image
|
Get a log-like stream of RGB values from an image.
Args:
filename (str): The filename of a PNG image.
offset (Number): If < 1, interpreted as proportion of way across
the image. If > 1, interpreted as pixels from left.
Returns:
ndarray: A 2d array (a column of RGB triples) at the specified
offset.
TODO:
Generalize this to extract 'logs' from images in other ways, such
as giving the mean of a range of pixel columns, or an array of
columns. See also a similar routine in pythonanywhere/freqbot.
|
striplog/utils.py
|
def loglike_from_image(filename, offset):
"""
Get a log-like stream of RGB values from an image.
Args:
filename (str): The filename of a PNG image.
offset (Number): If < 1, interpreted as proportion of way across
the image. If > 1, interpreted as pixels from left.
Returns:
ndarray: A 2d array (a column of RGB triples) at the specified
offset.
TODO:
Generalize this to extract 'logs' from images in other ways, such
as giving the mean of a range of pixel columns, or an array of
columns. See also a similar routine in pythonanywhere/freqbot.
"""
im = plt.imread(filename)
if offset < 1:
col = int(im.shape[1] * offset)
else:
col = offset
return im[:, col, :3]
|
def loglike_from_image(filename, offset):
"""
Get a log-like stream of RGB values from an image.
Args:
filename (str): The filename of a PNG image.
offset (Number): If < 1, interpreted as proportion of way across
the image. If > 1, interpreted as pixels from left.
Returns:
ndarray: A 2d array (a column of RGB triples) at the specified
offset.
TODO:
Generalize this to extract 'logs' from images in other ways, such
as giving the mean of a range of pixel columns, or an array of
columns. See also a similar routine in pythonanywhere/freqbot.
"""
im = plt.imread(filename)
if offset < 1:
col = int(im.shape[1] * offset)
else:
col = offset
return im[:, col, :3]
|
[
"Get",
"a",
"log",
"-",
"like",
"stream",
"of",
"RGB",
"values",
"from",
"an",
"image",
"."
] |
agile-geoscience/striplog
|
python
|
https://github.com/agile-geoscience/striplog/blob/8033b673a151f96c29802b43763e863519a3124c/striplog/utils.py#L280-L303
|
[
"def",
"loglike_from_image",
"(",
"filename",
",",
"offset",
")",
":",
"im",
"=",
"plt",
".",
"imread",
"(",
"filename",
")",
"if",
"offset",
"<",
"1",
":",
"col",
"=",
"int",
"(",
"im",
".",
"shape",
"[",
"1",
"]",
"*",
"offset",
")",
"else",
":",
"col",
"=",
"offset",
"return",
"im",
"[",
":",
",",
"col",
",",
":",
"3",
"]"
] |
8033b673a151f96c29802b43763e863519a3124c
|
test
|
tops_from_loglike
|
Take a log-like stream of numbers or strings, and return two arrays:
one of the tops (changes), and one of the values from the stream.
Args:
loglike (array-like): The input stream of loglike data.
offset (int): Offset (down) from top at which to get lithology,
to be sure of getting 'clean' pixels.
Returns:
ndarray: Two arrays, tops and values.
|
striplog/utils.py
|
def tops_from_loglike(a, offset=0, null=None):
"""
Take a log-like stream of numbers or strings, and return two arrays:
one of the tops (changes), and one of the values from the stream.
Args:
loglike (array-like): The input stream of loglike data.
offset (int): Offset (down) from top at which to get lithology,
to be sure of getting 'clean' pixels.
Returns:
ndarray: Two arrays, tops and values.
"""
a = np.copy(a)
try:
contains_nans = np.isnan(a).any()
except:
contains_nans = False
if contains_nans:
# Find a null value that's not in the log, and apply it if possible.
_null = null or -1
while _null in a:
_null -= 1
try:
a[np.isnan(a)] = _null
transformed = True
except:
transformed = False
edges = a[1:] == a[:-1]
edges = np.append(True, edges)
tops = np.where(~edges)[0]
tops = np.append(0, tops)
values = a[tops + offset]
if contains_nans and transformed:
values[values == _null] = np.nan
return tops, values
|
def tops_from_loglike(a, offset=0, null=None):
"""
Take a log-like stream of numbers or strings, and return two arrays:
one of the tops (changes), and one of the values from the stream.
Args:
loglike (array-like): The input stream of loglike data.
offset (int): Offset (down) from top at which to get lithology,
to be sure of getting 'clean' pixels.
Returns:
ndarray: Two arrays, tops and values.
"""
a = np.copy(a)
try:
contains_nans = np.isnan(a).any()
except:
contains_nans = False
if contains_nans:
# Find a null value that's not in the log, and apply it if possible.
_null = null or -1
while _null in a:
_null -= 1
try:
a[np.isnan(a)] = _null
transformed = True
except:
transformed = False
edges = a[1:] == a[:-1]
edges = np.append(True, edges)
tops = np.where(~edges)[0]
tops = np.append(0, tops)
values = a[tops + offset]
if contains_nans and transformed:
values[values == _null] = np.nan
return tops, values
|
[
"Take",
"a",
"log",
"-",
"like",
"stream",
"of",
"numbers",
"or",
"strings",
"and",
"return",
"two",
"arrays",
":",
"one",
"of",
"the",
"tops",
"(",
"changes",
")",
"and",
"one",
"of",
"the",
"values",
"from",
"the",
"stream",
"."
] |
agile-geoscience/striplog
|
python
|
https://github.com/agile-geoscience/striplog/blob/8033b673a151f96c29802b43763e863519a3124c/striplog/utils.py#L306-L349
|
[
"def",
"tops_from_loglike",
"(",
"a",
",",
"offset",
"=",
"0",
",",
"null",
"=",
"None",
")",
":",
"a",
"=",
"np",
".",
"copy",
"(",
"a",
")",
"try",
":",
"contains_nans",
"=",
"np",
".",
"isnan",
"(",
"a",
")",
".",
"any",
"(",
")",
"except",
":",
"contains_nans",
"=",
"False",
"if",
"contains_nans",
":",
"# Find a null value that's not in the log, and apply it if possible.",
"_null",
"=",
"null",
"or",
"-",
"1",
"while",
"_null",
"in",
"a",
":",
"_null",
"-=",
"1",
"try",
":",
"a",
"[",
"np",
".",
"isnan",
"(",
"a",
")",
"]",
"=",
"_null",
"transformed",
"=",
"True",
"except",
":",
"transformed",
"=",
"False",
"edges",
"=",
"a",
"[",
"1",
":",
"]",
"==",
"a",
"[",
":",
"-",
"1",
"]",
"edges",
"=",
"np",
".",
"append",
"(",
"True",
",",
"edges",
")",
"tops",
"=",
"np",
".",
"where",
"(",
"~",
"edges",
")",
"[",
"0",
"]",
"tops",
"=",
"np",
".",
"append",
"(",
"0",
",",
"tops",
")",
"values",
"=",
"a",
"[",
"tops",
"+",
"offset",
"]",
"if",
"contains_nans",
"and",
"transformed",
":",
"values",
"[",
"values",
"==",
"_null",
"]",
"=",
"np",
".",
"nan",
"return",
"tops",
",",
"values"
] |
8033b673a151f96c29802b43763e863519a3124c
|
test
|
axis_transform
|
http://stackoverflow.com/questions/29107800
inverse = False : Axis => Data
= True : Data => Axis
|
striplog/utils.py
|
def axis_transform(ax, x, y, xlim=None, ylim=None, inverse=False):
"""
http://stackoverflow.com/questions/29107800
inverse = False : Axis => Data
= True : Data => Axis
"""
xlim = xlim or ax.get_xlim()
ylim = ylim or ax.get_ylim()
xdelta = xlim[1] - xlim[0]
ydelta = ylim[1] - ylim[0]
if not inverse:
xout = xlim[0] + x * xdelta
yout = ylim[0] + y * ydelta
else:
xdelta2 = x - xlim[0]
ydelta2 = y - ylim[0]
xout = xdelta2 / xdelta
yout = ydelta2 / ydelta
return xout, yout
|
def axis_transform(ax, x, y, xlim=None, ylim=None, inverse=False):
"""
http://stackoverflow.com/questions/29107800
inverse = False : Axis => Data
= True : Data => Axis
"""
xlim = xlim or ax.get_xlim()
ylim = ylim or ax.get_ylim()
xdelta = xlim[1] - xlim[0]
ydelta = ylim[1] - ylim[0]
if not inverse:
xout = xlim[0] + x * xdelta
yout = ylim[0] + y * ydelta
else:
xdelta2 = x - xlim[0]
ydelta2 = y - ylim[0]
xout = xdelta2 / xdelta
yout = ydelta2 / ydelta
return xout, yout
|
[
"http",
":",
"//",
"stackoverflow",
".",
"com",
"/",
"questions",
"/",
"29107800"
] |
agile-geoscience/striplog
|
python
|
https://github.com/agile-geoscience/striplog/blob/8033b673a151f96c29802b43763e863519a3124c/striplog/utils.py#L389-L411
|
[
"def",
"axis_transform",
"(",
"ax",
",",
"x",
",",
"y",
",",
"xlim",
"=",
"None",
",",
"ylim",
"=",
"None",
",",
"inverse",
"=",
"False",
")",
":",
"xlim",
"=",
"xlim",
"or",
"ax",
".",
"get_xlim",
"(",
")",
"ylim",
"=",
"ylim",
"or",
"ax",
".",
"get_ylim",
"(",
")",
"xdelta",
"=",
"xlim",
"[",
"1",
"]",
"-",
"xlim",
"[",
"0",
"]",
"ydelta",
"=",
"ylim",
"[",
"1",
"]",
"-",
"ylim",
"[",
"0",
"]",
"if",
"not",
"inverse",
":",
"xout",
"=",
"xlim",
"[",
"0",
"]",
"+",
"x",
"*",
"xdelta",
"yout",
"=",
"ylim",
"[",
"0",
"]",
"+",
"y",
"*",
"ydelta",
"else",
":",
"xdelta2",
"=",
"x",
"-",
"xlim",
"[",
"0",
"]",
"ydelta2",
"=",
"y",
"-",
"ylim",
"[",
"0",
"]",
"xout",
"=",
"xdelta2",
"/",
"xdelta",
"yout",
"=",
"ydelta2",
"/",
"ydelta",
"return",
"xout",
",",
"yout"
] |
8033b673a151f96c29802b43763e863519a3124c
|
test
|
CustomFormatter.get_field
|
Return an underscore if the attribute is absent.
Not all components have the same attributes.
|
striplog/utils.py
|
def get_field(self, field_name, args, kwargs):
"""
Return an underscore if the attribute is absent.
Not all components have the same attributes.
"""
try:
s = super(CustomFormatter, self)
return s.get_field(field_name, args, kwargs)
except KeyError: # Key is missing
return ("_", field_name)
except IndexError: # Value is missing
return ("_", field_name)
|
def get_field(self, field_name, args, kwargs):
"""
Return an underscore if the attribute is absent.
Not all components have the same attributes.
"""
try:
s = super(CustomFormatter, self)
return s.get_field(field_name, args, kwargs)
except KeyError: # Key is missing
return ("_", field_name)
except IndexError: # Value is missing
return ("_", field_name)
|
[
"Return",
"an",
"underscore",
"if",
"the",
"attribute",
"is",
"absent",
".",
"Not",
"all",
"components",
"have",
"the",
"same",
"attributes",
"."
] |
agile-geoscience/striplog
|
python
|
https://github.com/agile-geoscience/striplog/blob/8033b673a151f96c29802b43763e863519a3124c/striplog/utils.py#L84-L95
|
[
"def",
"get_field",
"(",
"self",
",",
"field_name",
",",
"args",
",",
"kwargs",
")",
":",
"try",
":",
"s",
"=",
"super",
"(",
"CustomFormatter",
",",
"self",
")",
"return",
"s",
".",
"get_field",
"(",
"field_name",
",",
"args",
",",
"kwargs",
")",
"except",
"KeyError",
":",
"# Key is missing",
"return",
"(",
"\"_\"",
",",
"field_name",
")",
"except",
"IndexError",
":",
"# Value is missing",
"return",
"(",
"\"_\"",
",",
"field_name",
")"
] |
8033b673a151f96c29802b43763e863519a3124c
|
test
|
CustomFormatter.convert_field
|
Define some extra field conversion functions.
|
striplog/utils.py
|
def convert_field(self, value, conversion):
"""
Define some extra field conversion functions.
"""
try: # If the normal behaviour works, do it.
s = super(CustomFormatter, self)
return s.convert_field(value, conversion)
except ValueError:
funcs = {'s': str, # Default.
'r': repr, # Default.
'a': ascii, # Default.
'u': str.upper,
'l': str.lower,
'c': str.capitalize,
't': str.title,
'm': np.mean,
'µ': np.mean,
'v': np.var,
'd': np.std,
'+': np.sum,
'∑': np.sum,
'x': np.product,
}
return funcs.get(conversion)(value)
|
def convert_field(self, value, conversion):
"""
Define some extra field conversion functions.
"""
try: # If the normal behaviour works, do it.
s = super(CustomFormatter, self)
return s.convert_field(value, conversion)
except ValueError:
funcs = {'s': str, # Default.
'r': repr, # Default.
'a': ascii, # Default.
'u': str.upper,
'l': str.lower,
'c': str.capitalize,
't': str.title,
'm': np.mean,
'µ': np.mean,
'v': np.var,
'd': np.std,
'+': np.sum,
'∑': np.sum,
'x': np.product,
}
return funcs.get(conversion)(value)
|
[
"Define",
"some",
"extra",
"field",
"conversion",
"functions",
"."
] |
agile-geoscience/striplog
|
python
|
https://github.com/agile-geoscience/striplog/blob/8033b673a151f96c29802b43763e863519a3124c/striplog/utils.py#L97-L120
|
[
"def",
"convert_field",
"(",
"self",
",",
"value",
",",
"conversion",
")",
":",
"try",
":",
"# If the normal behaviour works, do it.",
"s",
"=",
"super",
"(",
"CustomFormatter",
",",
"self",
")",
"return",
"s",
".",
"convert_field",
"(",
"value",
",",
"conversion",
")",
"except",
"ValueError",
":",
"funcs",
"=",
"{",
"'s'",
":",
"str",
",",
"# Default.",
"'r'",
":",
"repr",
",",
"# Default.",
"'a'",
":",
"ascii",
",",
"# Default.",
"'u'",
":",
"str",
".",
"upper",
",",
"'l'",
":",
"str",
".",
"lower",
",",
"'c'",
":",
"str",
".",
"capitalize",
",",
"'t'",
":",
"str",
".",
"title",
",",
"'m'",
":",
"np",
".",
"mean",
",",
"'µ':",
" ",
"p.",
"m",
"ean,",
"",
"'v'",
":",
"np",
".",
"var",
",",
"'d'",
":",
"np",
".",
"std",
",",
"'+'",
":",
"np",
".",
"sum",
",",
"'∑': ",
"n",
".s",
"u",
"m,",
"",
"'x'",
":",
"np",
".",
"product",
",",
"}",
"return",
"funcs",
".",
"get",
"(",
"conversion",
")",
"(",
"value",
")"
] |
8033b673a151f96c29802b43763e863519a3124c
|
test
|
Jobs.get_jobs
|
Lists all the jobs registered with Nomad.
https://www.nomadproject.io/docs/http/jobs.html
arguments:
- prefix :(str) optional, specifies a string to filter jobs on based on an prefix.
This is specified as a querystring parameter.
returns: list
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
|
nomad/api/jobs.py
|
def get_jobs(self, prefix=None):
""" Lists all the jobs registered with Nomad.
https://www.nomadproject.io/docs/http/jobs.html
arguments:
- prefix :(str) optional, specifies a string to filter jobs on based on an prefix.
This is specified as a querystring parameter.
returns: list
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
params = {"prefix": prefix}
return self.request(method="get", params=params).json()
|
def get_jobs(self, prefix=None):
""" Lists all the jobs registered with Nomad.
https://www.nomadproject.io/docs/http/jobs.html
arguments:
- prefix :(str) optional, specifies a string to filter jobs on based on an prefix.
This is specified as a querystring parameter.
returns: list
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
params = {"prefix": prefix}
return self.request(method="get", params=params).json()
|
[
"Lists",
"all",
"the",
"jobs",
"registered",
"with",
"Nomad",
"."
] |
jrxFive/python-nomad
|
python
|
https://github.com/jrxFive/python-nomad/blob/37df37e4de21e6f8ac41c6154e7f1f44f1800020/nomad/api/jobs.py#L66-L79
|
[
"def",
"get_jobs",
"(",
"self",
",",
"prefix",
"=",
"None",
")",
":",
"params",
"=",
"{",
"\"prefix\"",
":",
"prefix",
"}",
"return",
"self",
".",
"request",
"(",
"method",
"=",
"\"get\"",
",",
"params",
"=",
"params",
")",
".",
"json",
"(",
")"
] |
37df37e4de21e6f8ac41c6154e7f1f44f1800020
|
test
|
Jobs.parse
|
Parse a HCL Job file. Returns a dict with the JSON formatted job.
This API endpoint is only supported from Nomad version 0.8.3.
https://www.nomadproject.io/api/jobs.html#parse-job
returns: dict
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
|
nomad/api/jobs.py
|
def parse(self, hcl, canonicalize=False):
""" Parse a HCL Job file. Returns a dict with the JSON formatted job.
This API endpoint is only supported from Nomad version 0.8.3.
https://www.nomadproject.io/api/jobs.html#parse-job
returns: dict
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
return self.request("parse", json={"JobHCL": hcl, "Canonicalize": canonicalize}, method="post", allow_redirects=True).json()
|
def parse(self, hcl, canonicalize=False):
""" Parse a HCL Job file. Returns a dict with the JSON formatted job.
This API endpoint is only supported from Nomad version 0.8.3.
https://www.nomadproject.io/api/jobs.html#parse-job
returns: dict
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
return self.request("parse", json={"JobHCL": hcl, "Canonicalize": canonicalize}, method="post", allow_redirects=True).json()
|
[
"Parse",
"a",
"HCL",
"Job",
"file",
".",
"Returns",
"a",
"dict",
"with",
"the",
"JSON",
"formatted",
"job",
".",
"This",
"API",
"endpoint",
"is",
"only",
"supported",
"from",
"Nomad",
"version",
"0",
".",
"8",
".",
"3",
"."
] |
jrxFive/python-nomad
|
python
|
https://github.com/jrxFive/python-nomad/blob/37df37e4de21e6f8ac41c6154e7f1f44f1800020/nomad/api/jobs.py#L93-L104
|
[
"def",
"parse",
"(",
"self",
",",
"hcl",
",",
"canonicalize",
"=",
"False",
")",
":",
"return",
"self",
".",
"request",
"(",
"\"parse\"",
",",
"json",
"=",
"{",
"\"JobHCL\"",
":",
"hcl",
",",
"\"Canonicalize\"",
":",
"canonicalize",
"}",
",",
"method",
"=",
"\"post\"",
",",
"allow_redirects",
"=",
"True",
")",
".",
"json",
"(",
")"
] |
37df37e4de21e6f8ac41c6154e7f1f44f1800020
|
test
|
Acl.update_token
|
Update token.
https://www.nomadproject.io/api/acl-tokens.html
arguments:
- AccdesorID
- token
returns: dict
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
|
nomad/api/acl.py
|
def update_token(self, id, token):
""" Update token.
https://www.nomadproject.io/api/acl-tokens.html
arguments:
- AccdesorID
- token
returns: dict
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
return self.request("token", id, json=token, method="post").json()
|
def update_token(self, id, token):
""" Update token.
https://www.nomadproject.io/api/acl-tokens.html
arguments:
- AccdesorID
- token
returns: dict
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
return self.request("token", id, json=token, method="post").json()
|
[
"Update",
"token",
"."
] |
jrxFive/python-nomad
|
python
|
https://github.com/jrxFive/python-nomad/blob/37df37e4de21e6f8ac41c6154e7f1f44f1800020/nomad/api/acl.py#L108-L122
|
[
"def",
"update_token",
"(",
"self",
",",
"id",
",",
"token",
")",
":",
"return",
"self",
".",
"request",
"(",
"\"token\"",
",",
"id",
",",
"json",
"=",
"token",
",",
"method",
"=",
"\"post\"",
")",
".",
"json",
"(",
")"
] |
37df37e4de21e6f8ac41c6154e7f1f44f1800020
|
test
|
Acl.create_policy
|
Create policy.
https://www.nomadproject.io/api/acl-policies.html
arguments:
- policy
returns: request.Response
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
|
nomad/api/acl.py
|
def create_policy(self, id, policy):
""" Create policy.
https://www.nomadproject.io/api/acl-policies.html
arguments:
- policy
returns: request.Response
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
return self.request("policy", id, json=policy, method="post")
|
def create_policy(self, id, policy):
""" Create policy.
https://www.nomadproject.io/api/acl-policies.html
arguments:
- policy
returns: request.Response
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
return self.request("policy", id, json=policy, method="post")
|
[
"Create",
"policy",
"."
] |
jrxFive/python-nomad
|
python
|
https://github.com/jrxFive/python-nomad/blob/37df37e4de21e6f8ac41c6154e7f1f44f1800020/nomad/api/acl.py#L137-L150
|
[
"def",
"create_policy",
"(",
"self",
",",
"id",
",",
"policy",
")",
":",
"return",
"self",
".",
"request",
"(",
"\"policy\"",
",",
"id",
",",
"json",
"=",
"policy",
",",
"method",
"=",
"\"post\"",
")"
] |
37df37e4de21e6f8ac41c6154e7f1f44f1800020
|
test
|
Acl.update_policy
|
Create policy.
https://www.nomadproject.io/api/acl-policies.html
arguments:
- name
- policy
returns: request.Response
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
|
nomad/api/acl.py
|
def update_policy(self, id, policy):
""" Create policy.
https://www.nomadproject.io/api/acl-policies.html
arguments:
- name
- policy
returns: request.Response
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
return self.request("policy", id, json=policy, method="post")
|
def update_policy(self, id, policy):
""" Create policy.
https://www.nomadproject.io/api/acl-policies.html
arguments:
- name
- policy
returns: request.Response
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
return self.request("policy", id, json=policy, method="post")
|
[
"Create",
"policy",
"."
] |
jrxFive/python-nomad
|
python
|
https://github.com/jrxFive/python-nomad/blob/37df37e4de21e6f8ac41c6154e7f1f44f1800020/nomad/api/acl.py#L165-L179
|
[
"def",
"update_policy",
"(",
"self",
",",
"id",
",",
"policy",
")",
":",
"return",
"self",
".",
"request",
"(",
"\"policy\"",
",",
"id",
",",
"json",
"=",
"policy",
",",
"method",
"=",
"\"post\"",
")"
] |
37df37e4de21e6f8ac41c6154e7f1f44f1800020
|
test
|
Allocations.get_allocations
|
Lists all the allocations.
https://www.nomadproject.io/docs/http/allocs.html
arguments:
- prefix :(str) optional, specifies a string to filter allocations on based on an prefix.
This is specified as a querystring parameter.
returns: list
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
|
nomad/api/allocations.py
|
def get_allocations(self, prefix=None):
""" Lists all the allocations.
https://www.nomadproject.io/docs/http/allocs.html
arguments:
- prefix :(str) optional, specifies a string to filter allocations on based on an prefix.
This is specified as a querystring parameter.
returns: list
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
params = {"prefix": prefix}
return self.request(method="get", params=params).json()
|
def get_allocations(self, prefix=None):
""" Lists all the allocations.
https://www.nomadproject.io/docs/http/allocs.html
arguments:
- prefix :(str) optional, specifies a string to filter allocations on based on an prefix.
This is specified as a querystring parameter.
returns: list
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
params = {"prefix": prefix}
return self.request(method="get", params=params).json()
|
[
"Lists",
"all",
"the",
"allocations",
"."
] |
jrxFive/python-nomad
|
python
|
https://github.com/jrxFive/python-nomad/blob/37df37e4de21e6f8ac41c6154e7f1f44f1800020/nomad/api/allocations.py#L35-L48
|
[
"def",
"get_allocations",
"(",
"self",
",",
"prefix",
"=",
"None",
")",
":",
"params",
"=",
"{",
"\"prefix\"",
":",
"prefix",
"}",
"return",
"self",
".",
"request",
"(",
"method",
"=",
"\"get\"",
",",
"params",
"=",
"params",
")",
".",
"json",
"(",
")"
] |
37df37e4de21e6f8ac41c6154e7f1f44f1800020
|
test
|
Deployment.fail_deployment
|
This endpoint is used to mark a deployment as failed. This should be done to force the scheduler to stop
creating allocations as part of the deployment or to cause a rollback to a previous job version.
https://www.nomadproject.io/docs/http/deployments.html
arguments:
- id
returns: dict
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
|
nomad/api/deployment.py
|
def fail_deployment(self, id):
""" This endpoint is used to mark a deployment as failed. This should be done to force the scheduler to stop
creating allocations as part of the deployment or to cause a rollback to a previous job version.
https://www.nomadproject.io/docs/http/deployments.html
arguments:
- id
returns: dict
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
fail_json = {"DeploymentID": id}
return self.request("fail", id, json=fail_json, method="post").json()
|
def fail_deployment(self, id):
""" This endpoint is used to mark a deployment as failed. This should be done to force the scheduler to stop
creating allocations as part of the deployment or to cause a rollback to a previous job version.
https://www.nomadproject.io/docs/http/deployments.html
arguments:
- id
returns: dict
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
fail_json = {"DeploymentID": id}
return self.request("fail", id, json=fail_json, method="post").json()
|
[
"This",
"endpoint",
"is",
"used",
"to",
"mark",
"a",
"deployment",
"as",
"failed",
".",
"This",
"should",
"be",
"done",
"to",
"force",
"the",
"scheduler",
"to",
"stop",
"creating",
"allocations",
"as",
"part",
"of",
"the",
"deployment",
"or",
"to",
"cause",
"a",
"rollback",
"to",
"a",
"previous",
"job",
"version",
"."
] |
jrxFive/python-nomad
|
python
|
https://github.com/jrxFive/python-nomad/blob/37df37e4de21e6f8ac41c6154e7f1f44f1800020/nomad/api/deployment.py#L74-L88
|
[
"def",
"fail_deployment",
"(",
"self",
",",
"id",
")",
":",
"fail_json",
"=",
"{",
"\"DeploymentID\"",
":",
"id",
"}",
"return",
"self",
".",
"request",
"(",
"\"fail\"",
",",
"id",
",",
"json",
"=",
"fail_json",
",",
"method",
"=",
"\"post\"",
")",
".",
"json",
"(",
")"
] |
37df37e4de21e6f8ac41c6154e7f1f44f1800020
|
test
|
Deployment.pause_deployment
|
This endpoint is used to pause or unpause a deployment.
This is done to pause a rolling upgrade or resume it.
https://www.nomadproject.io/docs/http/deployments.html
arguments:
- id
- pause, Specifies whether to pause or resume the deployment.
returns: dict
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
|
nomad/api/deployment.py
|
def pause_deployment(self, id, pause):
""" This endpoint is used to pause or unpause a deployment.
This is done to pause a rolling upgrade or resume it.
https://www.nomadproject.io/docs/http/deployments.html
arguments:
- id
- pause, Specifies whether to pause or resume the deployment.
returns: dict
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
pause_json = {"Pause": pause,
"DeploymentID": id}
return self.request("pause", id, json=pause_json, method="post").json()
|
def pause_deployment(self, id, pause):
""" This endpoint is used to pause or unpause a deployment.
This is done to pause a rolling upgrade or resume it.
https://www.nomadproject.io/docs/http/deployments.html
arguments:
- id
- pause, Specifies whether to pause or resume the deployment.
returns: dict
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
pause_json = {"Pause": pause,
"DeploymentID": id}
return self.request("pause", id, json=pause_json, method="post").json()
|
[
"This",
"endpoint",
"is",
"used",
"to",
"pause",
"or",
"unpause",
"a",
"deployment",
".",
"This",
"is",
"done",
"to",
"pause",
"a",
"rolling",
"upgrade",
"or",
"resume",
"it",
"."
] |
jrxFive/python-nomad
|
python
|
https://github.com/jrxFive/python-nomad/blob/37df37e4de21e6f8ac41c6154e7f1f44f1800020/nomad/api/deployment.py#L90-L106
|
[
"def",
"pause_deployment",
"(",
"self",
",",
"id",
",",
"pause",
")",
":",
"pause_json",
"=",
"{",
"\"Pause\"",
":",
"pause",
",",
"\"DeploymentID\"",
":",
"id",
"}",
"return",
"self",
".",
"request",
"(",
"\"pause\"",
",",
"id",
",",
"json",
"=",
"pause_json",
",",
"method",
"=",
"\"post\"",
")",
".",
"json",
"(",
")"
] |
37df37e4de21e6f8ac41c6154e7f1f44f1800020
|
test
|
Deployment.promote_deployment_all
|
This endpoint is used to promote task groups that have canaries for a deployment. This should be done when
the placed canaries are healthy and the rolling upgrade of the remaining allocations should begin.
https://www.nomadproject.io/docs/http/deployments.html
arguments:
- id
- all, Specifies whether all task groups should be promoted.
returns: dict
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
|
nomad/api/deployment.py
|
def promote_deployment_all(self, id, all=True):
""" This endpoint is used to promote task groups that have canaries for a deployment. This should be done when
the placed canaries are healthy and the rolling upgrade of the remaining allocations should begin.
https://www.nomadproject.io/docs/http/deployments.html
arguments:
- id
- all, Specifies whether all task groups should be promoted.
returns: dict
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
promote_all_json = {"All": all,
"DeploymentID": id}
return self.request("promote", id, json=promote_all_json, method="post").json()
|
def promote_deployment_all(self, id, all=True):
""" This endpoint is used to promote task groups that have canaries for a deployment. This should be done when
the placed canaries are healthy and the rolling upgrade of the remaining allocations should begin.
https://www.nomadproject.io/docs/http/deployments.html
arguments:
- id
- all, Specifies whether all task groups should be promoted.
returns: dict
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
promote_all_json = {"All": all,
"DeploymentID": id}
return self.request("promote", id, json=promote_all_json, method="post").json()
|
[
"This",
"endpoint",
"is",
"used",
"to",
"promote",
"task",
"groups",
"that",
"have",
"canaries",
"for",
"a",
"deployment",
".",
"This",
"should",
"be",
"done",
"when",
"the",
"placed",
"canaries",
"are",
"healthy",
"and",
"the",
"rolling",
"upgrade",
"of",
"the",
"remaining",
"allocations",
"should",
"begin",
"."
] |
jrxFive/python-nomad
|
python
|
https://github.com/jrxFive/python-nomad/blob/37df37e4de21e6f8ac41c6154e7f1f44f1800020/nomad/api/deployment.py#L108-L124
|
[
"def",
"promote_deployment_all",
"(",
"self",
",",
"id",
",",
"all",
"=",
"True",
")",
":",
"promote_all_json",
"=",
"{",
"\"All\"",
":",
"all",
",",
"\"DeploymentID\"",
":",
"id",
"}",
"return",
"self",
".",
"request",
"(",
"\"promote\"",
",",
"id",
",",
"json",
"=",
"promote_all_json",
",",
"method",
"=",
"\"post\"",
")",
".",
"json",
"(",
")"
] |
37df37e4de21e6f8ac41c6154e7f1f44f1800020
|
test
|
Deployment.promote_deployment_groups
|
This endpoint is used to promote task groups that have canaries for a deployment. This should be done when
the placed canaries are healthy and the rolling upgrade of the remaining allocations should begin.
https://www.nomadproject.io/docs/http/deployments.html
arguments:
- id
- groups, (list) Specifies a particular set of task groups that should be promoted
returns: dict
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
|
nomad/api/deployment.py
|
def promote_deployment_groups(self, id, groups=list()):
""" This endpoint is used to promote task groups that have canaries for a deployment. This should be done when
the placed canaries are healthy and the rolling upgrade of the remaining allocations should begin.
https://www.nomadproject.io/docs/http/deployments.html
arguments:
- id
- groups, (list) Specifies a particular set of task groups that should be promoted
returns: dict
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
promote_groups_json = {"Groups": groups,
"DeploymentID": id}
return self.request("promote", id, json=promote_groups_json, method="post").json()
|
def promote_deployment_groups(self, id, groups=list()):
""" This endpoint is used to promote task groups that have canaries for a deployment. This should be done when
the placed canaries are healthy and the rolling upgrade of the remaining allocations should begin.
https://www.nomadproject.io/docs/http/deployments.html
arguments:
- id
- groups, (list) Specifies a particular set of task groups that should be promoted
returns: dict
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
promote_groups_json = {"Groups": groups,
"DeploymentID": id}
return self.request("promote", id, json=promote_groups_json, method="post").json()
|
[
"This",
"endpoint",
"is",
"used",
"to",
"promote",
"task",
"groups",
"that",
"have",
"canaries",
"for",
"a",
"deployment",
".",
"This",
"should",
"be",
"done",
"when",
"the",
"placed",
"canaries",
"are",
"healthy",
"and",
"the",
"rolling",
"upgrade",
"of",
"the",
"remaining",
"allocations",
"should",
"begin",
"."
] |
jrxFive/python-nomad
|
python
|
https://github.com/jrxFive/python-nomad/blob/37df37e4de21e6f8ac41c6154e7f1f44f1800020/nomad/api/deployment.py#L126-L142
|
[
"def",
"promote_deployment_groups",
"(",
"self",
",",
"id",
",",
"groups",
"=",
"list",
"(",
")",
")",
":",
"promote_groups_json",
"=",
"{",
"\"Groups\"",
":",
"groups",
",",
"\"DeploymentID\"",
":",
"id",
"}",
"return",
"self",
".",
"request",
"(",
"\"promote\"",
",",
"id",
",",
"json",
"=",
"promote_groups_json",
",",
"method",
"=",
"\"post\"",
")",
".",
"json",
"(",
")"
] |
37df37e4de21e6f8ac41c6154e7f1f44f1800020
|
test
|
Deployment.deployment_allocation_health
|
This endpoint is used to set the health of an allocation that is in the deployment manually. In some use
cases, automatic detection of allocation health may not be desired. As such those task groups can be marked
with an upgrade policy that uses health_check = "manual". Those allocations must have their health marked
manually using this endpoint. Marking an allocation as healthy will allow the rolling upgrade to proceed.
Marking it as failed will cause the deployment to fail.
https://www.nomadproject.io/docs/http/deployments.html
arguments:
- id
- healthy_allocations, Specifies the set of allocation that should be marked as healthy.
- unhealthy_allocations, Specifies the set of allocation that should be marked as unhealthy.
returns: dict
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
|
nomad/api/deployment.py
|
def deployment_allocation_health(self, id, healthy_allocations=list(), unhealthy_allocations=list()):
""" This endpoint is used to set the health of an allocation that is in the deployment manually. In some use
cases, automatic detection of allocation health may not be desired. As such those task groups can be marked
with an upgrade policy that uses health_check = "manual". Those allocations must have their health marked
manually using this endpoint. Marking an allocation as healthy will allow the rolling upgrade to proceed.
Marking it as failed will cause the deployment to fail.
https://www.nomadproject.io/docs/http/deployments.html
arguments:
- id
- healthy_allocations, Specifies the set of allocation that should be marked as healthy.
- unhealthy_allocations, Specifies the set of allocation that should be marked as unhealthy.
returns: dict
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
allocations = {"HealthyAllocationIDs": healthy_allocations,
"UnHealthyAllocationIDs": unhealthy_allocations,
"DeploymentID": id}
return self.request("allocation-health", id, json=allocations, method="post").json()
|
def deployment_allocation_health(self, id, healthy_allocations=list(), unhealthy_allocations=list()):
""" This endpoint is used to set the health of an allocation that is in the deployment manually. In some use
cases, automatic detection of allocation health may not be desired. As such those task groups can be marked
with an upgrade policy that uses health_check = "manual". Those allocations must have their health marked
manually using this endpoint. Marking an allocation as healthy will allow the rolling upgrade to proceed.
Marking it as failed will cause the deployment to fail.
https://www.nomadproject.io/docs/http/deployments.html
arguments:
- id
- healthy_allocations, Specifies the set of allocation that should be marked as healthy.
- unhealthy_allocations, Specifies the set of allocation that should be marked as unhealthy.
returns: dict
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
allocations = {"HealthyAllocationIDs": healthy_allocations,
"UnHealthyAllocationIDs": unhealthy_allocations,
"DeploymentID": id}
return self.request("allocation-health", id, json=allocations, method="post").json()
|
[
"This",
"endpoint",
"is",
"used",
"to",
"set",
"the",
"health",
"of",
"an",
"allocation",
"that",
"is",
"in",
"the",
"deployment",
"manually",
".",
"In",
"some",
"use",
"cases",
"automatic",
"detection",
"of",
"allocation",
"health",
"may",
"not",
"be",
"desired",
".",
"As",
"such",
"those",
"task",
"groups",
"can",
"be",
"marked",
"with",
"an",
"upgrade",
"policy",
"that",
"uses",
"health_check",
"=",
"manual",
".",
"Those",
"allocations",
"must",
"have",
"their",
"health",
"marked",
"manually",
"using",
"this",
"endpoint",
".",
"Marking",
"an",
"allocation",
"as",
"healthy",
"will",
"allow",
"the",
"rolling",
"upgrade",
"to",
"proceed",
".",
"Marking",
"it",
"as",
"failed",
"will",
"cause",
"the",
"deployment",
"to",
"fail",
"."
] |
jrxFive/python-nomad
|
python
|
https://github.com/jrxFive/python-nomad/blob/37df37e4de21e6f8ac41c6154e7f1f44f1800020/nomad/api/deployment.py#L144-L165
|
[
"def",
"deployment_allocation_health",
"(",
"self",
",",
"id",
",",
"healthy_allocations",
"=",
"list",
"(",
")",
",",
"unhealthy_allocations",
"=",
"list",
"(",
")",
")",
":",
"allocations",
"=",
"{",
"\"HealthyAllocationIDs\"",
":",
"healthy_allocations",
",",
"\"UnHealthyAllocationIDs\"",
":",
"unhealthy_allocations",
",",
"\"DeploymentID\"",
":",
"id",
"}",
"return",
"self",
".",
"request",
"(",
"\"allocation-health\"",
",",
"id",
",",
"json",
"=",
"allocations",
",",
"method",
"=",
"\"post\"",
")",
".",
"json",
"(",
")"
] |
37df37e4de21e6f8ac41c6154e7f1f44f1800020
|
test
|
Node.drain_node
|
Toggle the drain mode of the node.
When enabled, no further allocations will be
assigned and existing allocations will be migrated.
https://www.nomadproject.io/docs/http/node.html
arguments:
- id (str uuid): node id
- enable (bool): enable node drain or not to enable node drain
returns: dict
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
|
nomad/api/node.py
|
def drain_node(self, id, enable=False):
""" Toggle the drain mode of the node.
When enabled, no further allocations will be
assigned and existing allocations will be migrated.
https://www.nomadproject.io/docs/http/node.html
arguments:
- id (str uuid): node id
- enable (bool): enable node drain or not to enable node drain
returns: dict
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
return self.request(id, "drain", params={"enable": enable}, method="post").json()
|
def drain_node(self, id, enable=False):
""" Toggle the drain mode of the node.
When enabled, no further allocations will be
assigned and existing allocations will be migrated.
https://www.nomadproject.io/docs/http/node.html
arguments:
- id (str uuid): node id
- enable (bool): enable node drain or not to enable node drain
returns: dict
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
return self.request(id, "drain", params={"enable": enable}, method="post").json()
|
[
"Toggle",
"the",
"drain",
"mode",
"of",
"the",
"node",
".",
"When",
"enabled",
"no",
"further",
"allocations",
"will",
"be",
"assigned",
"and",
"existing",
"allocations",
"will",
"be",
"migrated",
"."
] |
jrxFive/python-nomad
|
python
|
https://github.com/jrxFive/python-nomad/blob/37df37e4de21e6f8ac41c6154e7f1f44f1800020/nomad/api/node.py#L89-L105
|
[
"def",
"drain_node",
"(",
"self",
",",
"id",
",",
"enable",
"=",
"False",
")",
":",
"return",
"self",
".",
"request",
"(",
"id",
",",
"\"drain\"",
",",
"params",
"=",
"{",
"\"enable\"",
":",
"enable",
"}",
",",
"method",
"=",
"\"post\"",
")",
".",
"json",
"(",
")"
] |
37df37e4de21e6f8ac41c6154e7f1f44f1800020
|
test
|
Node.drain_node_with_spec
|
This endpoint toggles the drain mode of the node. When draining is enabled,
no further allocations will be assigned to this node, and existing allocations
will be migrated to new nodes.
If an empty dictionary is given as drain_spec this will disable/toggle the drain.
https://www.nomadproject.io/docs/http/node.html
arguments:
- id (str uuid): node id
- drain_spec (dict): https://www.nomadproject.io/api/nodes.html#drainspec
- mark_eligible (bool): https://www.nomadproject.io/api/nodes.html#markeligible
returns: dict
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
|
nomad/api/node.py
|
def drain_node_with_spec(self, id, drain_spec, mark_eligible=None):
""" This endpoint toggles the drain mode of the node. When draining is enabled,
no further allocations will be assigned to this node, and existing allocations
will be migrated to new nodes.
If an empty dictionary is given as drain_spec this will disable/toggle the drain.
https://www.nomadproject.io/docs/http/node.html
arguments:
- id (str uuid): node id
- drain_spec (dict): https://www.nomadproject.io/api/nodes.html#drainspec
- mark_eligible (bool): https://www.nomadproject.io/api/nodes.html#markeligible
returns: dict
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
payload = {}
if drain_spec and mark_eligible is not None:
payload = {
"NodeID": id,
"DrainSpec": drain_spec,
"MarkEligible": mark_eligible
}
elif drain_spec and mark_eligible is None:
payload = {
"NodeID": id,
"DrainSpec": drain_spec
}
elif not drain_spec and mark_eligible is not None:
payload = {
"NodeID": id,
"DrainSpec": None,
"MarkEligible": mark_eligible
}
elif not drain_spec and mark_eligible is None:
payload = {
"NodeID": id,
"DrainSpec": None,
}
return self.request(id, "drain", json=payload, method="post").json()
|
def drain_node_with_spec(self, id, drain_spec, mark_eligible=None):
""" This endpoint toggles the drain mode of the node. When draining is enabled,
no further allocations will be assigned to this node, and existing allocations
will be migrated to new nodes.
If an empty dictionary is given as drain_spec this will disable/toggle the drain.
https://www.nomadproject.io/docs/http/node.html
arguments:
- id (str uuid): node id
- drain_spec (dict): https://www.nomadproject.io/api/nodes.html#drainspec
- mark_eligible (bool): https://www.nomadproject.io/api/nodes.html#markeligible
returns: dict
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
payload = {}
if drain_spec and mark_eligible is not None:
payload = {
"NodeID": id,
"DrainSpec": drain_spec,
"MarkEligible": mark_eligible
}
elif drain_spec and mark_eligible is None:
payload = {
"NodeID": id,
"DrainSpec": drain_spec
}
elif not drain_spec and mark_eligible is not None:
payload = {
"NodeID": id,
"DrainSpec": None,
"MarkEligible": mark_eligible
}
elif not drain_spec and mark_eligible is None:
payload = {
"NodeID": id,
"DrainSpec": None,
}
return self.request(id, "drain", json=payload, method="post").json()
|
[
"This",
"endpoint",
"toggles",
"the",
"drain",
"mode",
"of",
"the",
"node",
".",
"When",
"draining",
"is",
"enabled",
"no",
"further",
"allocations",
"will",
"be",
"assigned",
"to",
"this",
"node",
"and",
"existing",
"allocations",
"will",
"be",
"migrated",
"to",
"new",
"nodes",
"."
] |
jrxFive/python-nomad
|
python
|
https://github.com/jrxFive/python-nomad/blob/37df37e4de21e6f8ac41c6154e7f1f44f1800020/nomad/api/node.py#L107-L150
|
[
"def",
"drain_node_with_spec",
"(",
"self",
",",
"id",
",",
"drain_spec",
",",
"mark_eligible",
"=",
"None",
")",
":",
"payload",
"=",
"{",
"}",
"if",
"drain_spec",
"and",
"mark_eligible",
"is",
"not",
"None",
":",
"payload",
"=",
"{",
"\"NodeID\"",
":",
"id",
",",
"\"DrainSpec\"",
":",
"drain_spec",
",",
"\"MarkEligible\"",
":",
"mark_eligible",
"}",
"elif",
"drain_spec",
"and",
"mark_eligible",
"is",
"None",
":",
"payload",
"=",
"{",
"\"NodeID\"",
":",
"id",
",",
"\"DrainSpec\"",
":",
"drain_spec",
"}",
"elif",
"not",
"drain_spec",
"and",
"mark_eligible",
"is",
"not",
"None",
":",
"payload",
"=",
"{",
"\"NodeID\"",
":",
"id",
",",
"\"DrainSpec\"",
":",
"None",
",",
"\"MarkEligible\"",
":",
"mark_eligible",
"}",
"elif",
"not",
"drain_spec",
"and",
"mark_eligible",
"is",
"None",
":",
"payload",
"=",
"{",
"\"NodeID\"",
":",
"id",
",",
"\"DrainSpec\"",
":",
"None",
",",
"}",
"return",
"self",
".",
"request",
"(",
"id",
",",
"\"drain\"",
",",
"json",
"=",
"payload",
",",
"method",
"=",
"\"post\"",
")",
".",
"json",
"(",
")"
] |
37df37e4de21e6f8ac41c6154e7f1f44f1800020
|
test
|
Node.eligible_node
|
Toggle the eligibility of the node.
https://www.nomadproject.io/docs/http/node.html
arguments:
- id (str uuid): node id
- eligible (bool): Set to True to mark node eligible
- ineligible (bool): Set to True to mark node ineligible
returns: dict
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
|
nomad/api/node.py
|
def eligible_node(self, id, eligible=None, ineligible=None):
""" Toggle the eligibility of the node.
https://www.nomadproject.io/docs/http/node.html
arguments:
- id (str uuid): node id
- eligible (bool): Set to True to mark node eligible
- ineligible (bool): Set to True to mark node ineligible
returns: dict
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
payload = {}
if eligible is not None and ineligible is not None:
raise nomad.api.exceptions.InvalidParameters
if eligible is None and ineligible is None:
raise nomad.api.exceptions.InvalidParameters
if eligible is not None and eligible:
payload = {"Eligibility": "eligible", "NodeID": id}
elif eligible is not None and not eligible:
payload = {"Eligibility": "ineligible", "NodeID": id}
elif ineligible is not None:
payload = {"Eligibility": "ineligible", "NodeID": id}
elif ineligible is not None and not ineligible:
payload = {"Eligibility": "eligible", "NodeID": id}
return self.request(id, "eligibility", json=payload, method="post").json()
|
def eligible_node(self, id, eligible=None, ineligible=None):
""" Toggle the eligibility of the node.
https://www.nomadproject.io/docs/http/node.html
arguments:
- id (str uuid): node id
- eligible (bool): Set to True to mark node eligible
- ineligible (bool): Set to True to mark node ineligible
returns: dict
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
payload = {}
if eligible is not None and ineligible is not None:
raise nomad.api.exceptions.InvalidParameters
if eligible is None and ineligible is None:
raise nomad.api.exceptions.InvalidParameters
if eligible is not None and eligible:
payload = {"Eligibility": "eligible", "NodeID": id}
elif eligible is not None and not eligible:
payload = {"Eligibility": "ineligible", "NodeID": id}
elif ineligible is not None:
payload = {"Eligibility": "ineligible", "NodeID": id}
elif ineligible is not None and not ineligible:
payload = {"Eligibility": "eligible", "NodeID": id}
return self.request(id, "eligibility", json=payload, method="post").json()
|
[
"Toggle",
"the",
"eligibility",
"of",
"the",
"node",
"."
] |
jrxFive/python-nomad
|
python
|
https://github.com/jrxFive/python-nomad/blob/37df37e4de21e6f8ac41c6154e7f1f44f1800020/nomad/api/node.py#L152-L182
|
[
"def",
"eligible_node",
"(",
"self",
",",
"id",
",",
"eligible",
"=",
"None",
",",
"ineligible",
"=",
"None",
")",
":",
"payload",
"=",
"{",
"}",
"if",
"eligible",
"is",
"not",
"None",
"and",
"ineligible",
"is",
"not",
"None",
":",
"raise",
"nomad",
".",
"api",
".",
"exceptions",
".",
"InvalidParameters",
"if",
"eligible",
"is",
"None",
"and",
"ineligible",
"is",
"None",
":",
"raise",
"nomad",
".",
"api",
".",
"exceptions",
".",
"InvalidParameters",
"if",
"eligible",
"is",
"not",
"None",
"and",
"eligible",
":",
"payload",
"=",
"{",
"\"Eligibility\"",
":",
"\"eligible\"",
",",
"\"NodeID\"",
":",
"id",
"}",
"elif",
"eligible",
"is",
"not",
"None",
"and",
"not",
"eligible",
":",
"payload",
"=",
"{",
"\"Eligibility\"",
":",
"\"ineligible\"",
",",
"\"NodeID\"",
":",
"id",
"}",
"elif",
"ineligible",
"is",
"not",
"None",
":",
"payload",
"=",
"{",
"\"Eligibility\"",
":",
"\"ineligible\"",
",",
"\"NodeID\"",
":",
"id",
"}",
"elif",
"ineligible",
"is",
"not",
"None",
"and",
"not",
"ineligible",
":",
"payload",
"=",
"{",
"\"Eligibility\"",
":",
"\"eligible\"",
",",
"\"NodeID\"",
":",
"id",
"}",
"return",
"self",
".",
"request",
"(",
"id",
",",
"\"eligibility\"",
",",
"json",
"=",
"payload",
",",
"method",
"=",
"\"post\"",
")",
".",
"json",
"(",
")"
] |
37df37e4de21e6f8ac41c6154e7f1f44f1800020
|
test
|
ls.list_files
|
List files in an allocation directory.
https://www.nomadproject.io/docs/http/client-fs-ls.html
arguments:
- id
- path
returns: list
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
|
nomad/api/client.py
|
def list_files(self, id=None, path="/"):
""" List files in an allocation directory.
https://www.nomadproject.io/docs/http/client-fs-ls.html
arguments:
- id
- path
returns: list
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
if id:
return self.request(id, params={"path": path}, method="get").json()
else:
return self.request(params={"path": path}, method="get").json()
|
def list_files(self, id=None, path="/"):
""" List files in an allocation directory.
https://www.nomadproject.io/docs/http/client-fs-ls.html
arguments:
- id
- path
returns: list
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
if id:
return self.request(id, params={"path": path}, method="get").json()
else:
return self.request(params={"path": path}, method="get").json()
|
[
"List",
"files",
"in",
"an",
"allocation",
"directory",
"."
] |
jrxFive/python-nomad
|
python
|
https://github.com/jrxFive/python-nomad/blob/37df37e4de21e6f8ac41c6154e7f1f44f1800020/nomad/api/client.py#L43-L59
|
[
"def",
"list_files",
"(",
"self",
",",
"id",
"=",
"None",
",",
"path",
"=",
"\"/\"",
")",
":",
"if",
"id",
":",
"return",
"self",
".",
"request",
"(",
"id",
",",
"params",
"=",
"{",
"\"path\"",
":",
"path",
"}",
",",
"method",
"=",
"\"get\"",
")",
".",
"json",
"(",
")",
"else",
":",
"return",
"self",
".",
"request",
"(",
"params",
"=",
"{",
"\"path\"",
":",
"path",
"}",
",",
"method",
"=",
"\"get\"",
")",
".",
"json",
"(",
")"
] |
37df37e4de21e6f8ac41c6154e7f1f44f1800020
|
test
|
cat.read_file
|
Read contents of a file in an allocation directory.
https://www.nomadproject.io/docs/http/client-fs-cat.html
arguments:
- id
- path
returns: (str) text
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
|
nomad/api/client.py
|
def read_file(self, id=None, path="/"):
""" Read contents of a file in an allocation directory.
https://www.nomadproject.io/docs/http/client-fs-cat.html
arguments:
- id
- path
returns: (str) text
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
if id:
return self.request(id, params={"path": path}, method="get").text
else:
return self.request(params={"path": path}, method="get").text
|
def read_file(self, id=None, path="/"):
""" Read contents of a file in an allocation directory.
https://www.nomadproject.io/docs/http/client-fs-cat.html
arguments:
- id
- path
returns: (str) text
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
if id:
return self.request(id, params={"path": path}, method="get").text
else:
return self.request(params={"path": path}, method="get").text
|
[
"Read",
"contents",
"of",
"a",
"file",
"in",
"an",
"allocation",
"directory",
"."
] |
jrxFive/python-nomad
|
python
|
https://github.com/jrxFive/python-nomad/blob/37df37e4de21e6f8ac41c6154e7f1f44f1800020/nomad/api/client.py#L78-L94
|
[
"def",
"read_file",
"(",
"self",
",",
"id",
"=",
"None",
",",
"path",
"=",
"\"/\"",
")",
":",
"if",
"id",
":",
"return",
"self",
".",
"request",
"(",
"id",
",",
"params",
"=",
"{",
"\"path\"",
":",
"path",
"}",
",",
"method",
"=",
"\"get\"",
")",
".",
"text",
"else",
":",
"return",
"self",
".",
"request",
"(",
"params",
"=",
"{",
"\"path\"",
":",
"path",
"}",
",",
"method",
"=",
"\"get\"",
")",
".",
"text"
] |
37df37e4de21e6f8ac41c6154e7f1f44f1800020
|
test
|
read_at.read_file_offset
|
Read contents of a file in an allocation directory.
https://www.nomadproject.io/docs/http/client-fs-cat.html
arguments:
- id: (str) allocation_id required
- offset: (int) required
- limit: (int) required
- path: (str) optional
returns: (str) text
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.BadRequestNomadException
|
nomad/api/client.py
|
def read_file_offset(self, id, offset, limit, path="/"):
""" Read contents of a file in an allocation directory.
https://www.nomadproject.io/docs/http/client-fs-cat.html
arguments:
- id: (str) allocation_id required
- offset: (int) required
- limit: (int) required
- path: (str) optional
returns: (str) text
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.BadRequestNomadException
"""
params = {
"path": path,
"offset": offset,
"limit": limit
}
return self.request(id, params=params, method="get").text
|
def read_file_offset(self, id, offset, limit, path="/"):
""" Read contents of a file in an allocation directory.
https://www.nomadproject.io/docs/http/client-fs-cat.html
arguments:
- id: (str) allocation_id required
- offset: (int) required
- limit: (int) required
- path: (str) optional
returns: (str) text
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.BadRequestNomadException
"""
params = {
"path": path,
"offset": offset,
"limit": limit
}
return self.request(id, params=params, method="get").text
|
[
"Read",
"contents",
"of",
"a",
"file",
"in",
"an",
"allocation",
"directory",
"."
] |
jrxFive/python-nomad
|
python
|
https://github.com/jrxFive/python-nomad/blob/37df37e4de21e6f8ac41c6154e7f1f44f1800020/nomad/api/client.py#L110-L130
|
[
"def",
"read_file_offset",
"(",
"self",
",",
"id",
",",
"offset",
",",
"limit",
",",
"path",
"=",
"\"/\"",
")",
":",
"params",
"=",
"{",
"\"path\"",
":",
"path",
",",
"\"offset\"",
":",
"offset",
",",
"\"limit\"",
":",
"limit",
"}",
"return",
"self",
".",
"request",
"(",
"id",
",",
"params",
"=",
"params",
",",
"method",
"=",
"\"get\"",
")",
".",
"text"
] |
37df37e4de21e6f8ac41c6154e7f1f44f1800020
|
test
|
stream_file.stream
|
This endpoint streams the contents of a file in an allocation directory.
https://www.nomadproject.io/api/client.html#stream-file
arguments:
- id: (str) allocation_id required
- offset: (int) required
- origin: (str) either start|end
- path: (str) optional
returns: (str) text
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.BadRequestNomadException
|
nomad/api/client.py
|
def stream(self, id, offset, origin, path="/"):
""" This endpoint streams the contents of a file in an allocation directory.
https://www.nomadproject.io/api/client.html#stream-file
arguments:
- id: (str) allocation_id required
- offset: (int) required
- origin: (str) either start|end
- path: (str) optional
returns: (str) text
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.BadRequestNomadException
"""
params = {
"path": path,
"offset": offset,
"origin": origin
}
return self.request(id, params=params, method="get").text
|
def stream(self, id, offset, origin, path="/"):
""" This endpoint streams the contents of a file in an allocation directory.
https://www.nomadproject.io/api/client.html#stream-file
arguments:
- id: (str) allocation_id required
- offset: (int) required
- origin: (str) either start|end
- path: (str) optional
returns: (str) text
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.BadRequestNomadException
"""
params = {
"path": path,
"offset": offset,
"origin": origin
}
return self.request(id, params=params, method="get").text
|
[
"This",
"endpoint",
"streams",
"the",
"contents",
"of",
"a",
"file",
"in",
"an",
"allocation",
"directory",
"."
] |
jrxFive/python-nomad
|
python
|
https://github.com/jrxFive/python-nomad/blob/37df37e4de21e6f8ac41c6154e7f1f44f1800020/nomad/api/client.py#L146-L166
|
[
"def",
"stream",
"(",
"self",
",",
"id",
",",
"offset",
",",
"origin",
",",
"path",
"=",
"\"/\"",
")",
":",
"params",
"=",
"{",
"\"path\"",
":",
"path",
",",
"\"offset\"",
":",
"offset",
",",
"\"origin\"",
":",
"origin",
"}",
"return",
"self",
".",
"request",
"(",
"id",
",",
"params",
"=",
"params",
",",
"method",
"=",
"\"get\"",
")",
".",
"text"
] |
37df37e4de21e6f8ac41c6154e7f1f44f1800020
|
test
|
stream_logs.stream
|
This endpoint streams a task's stderr/stdout logs.
https://www.nomadproject.io/api/client.html#stream-logs
arguments:
- id: (str) allocation_id required
- task: (str) name of the task inside the allocation to stream logs from
- type: (str) Specifies the stream to stream. Either "stderr|stdout"
- follow: (bool) default false
- offset: (int) default 0
- origin: (str) either start|end, default "start"
- plain: (bool) Return just the plain text without framing. default False
returns: (str) text
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.BadRequestNomadException
|
nomad/api/client.py
|
def stream(self, id, task, type, follow=False, offset=0, origin="start", plain=False):
""" This endpoint streams a task's stderr/stdout logs.
https://www.nomadproject.io/api/client.html#stream-logs
arguments:
- id: (str) allocation_id required
- task: (str) name of the task inside the allocation to stream logs from
- type: (str) Specifies the stream to stream. Either "stderr|stdout"
- follow: (bool) default false
- offset: (int) default 0
- origin: (str) either start|end, default "start"
- plain: (bool) Return just the plain text without framing. default False
returns: (str) text
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.BadRequestNomadException
"""
params = {
"task": task,
"type": type,
"follow": follow,
"offset": offset,
"origin": origin,
"plain": plain
}
return self.request(id, params=params, method="get").text
|
def stream(self, id, task, type, follow=False, offset=0, origin="start", plain=False):
""" This endpoint streams a task's stderr/stdout logs.
https://www.nomadproject.io/api/client.html#stream-logs
arguments:
- id: (str) allocation_id required
- task: (str) name of the task inside the allocation to stream logs from
- type: (str) Specifies the stream to stream. Either "stderr|stdout"
- follow: (bool) default false
- offset: (int) default 0
- origin: (str) either start|end, default "start"
- plain: (bool) Return just the plain text without framing. default False
returns: (str) text
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.BadRequestNomadException
"""
params = {
"task": task,
"type": type,
"follow": follow,
"offset": offset,
"origin": origin,
"plain": plain
}
return self.request(id, params=params, method="get").text
|
[
"This",
"endpoint",
"streams",
"a",
"task",
"s",
"stderr",
"/",
"stdout",
"logs",
"."
] |
jrxFive/python-nomad
|
python
|
https://github.com/jrxFive/python-nomad/blob/37df37e4de21e6f8ac41c6154e7f1f44f1800020/nomad/api/client.py#L182-L208
|
[
"def",
"stream",
"(",
"self",
",",
"id",
",",
"task",
",",
"type",
",",
"follow",
"=",
"False",
",",
"offset",
"=",
"0",
",",
"origin",
"=",
"\"start\"",
",",
"plain",
"=",
"False",
")",
":",
"params",
"=",
"{",
"\"task\"",
":",
"task",
",",
"\"type\"",
":",
"type",
",",
"\"follow\"",
":",
"follow",
",",
"\"offset\"",
":",
"offset",
",",
"\"origin\"",
":",
"origin",
",",
"\"plain\"",
":",
"plain",
"}",
"return",
"self",
".",
"request",
"(",
"id",
",",
"params",
"=",
"params",
",",
"method",
"=",
"\"get\"",
")",
".",
"text"
] |
37df37e4de21e6f8ac41c6154e7f1f44f1800020
|
test
|
stat.stat_file
|
Stat a file in an allocation directory.
https://www.nomadproject.io/docs/http/client-fs-stat.html
arguments:
- id
- path
returns: dict
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
|
nomad/api/client.py
|
def stat_file(self, id=None, path="/"):
""" Stat a file in an allocation directory.
https://www.nomadproject.io/docs/http/client-fs-stat.html
arguments:
- id
- path
returns: dict
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
if id:
return self.request(id, params={"path": path}, method="get").json()
else:
return self.request(params={"path": path}, method="get").json()
|
def stat_file(self, id=None, path="/"):
""" Stat a file in an allocation directory.
https://www.nomadproject.io/docs/http/client-fs-stat.html
arguments:
- id
- path
returns: dict
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
if id:
return self.request(id, params={"path": path}, method="get").json()
else:
return self.request(params={"path": path}, method="get").json()
|
[
"Stat",
"a",
"file",
"in",
"an",
"allocation",
"directory",
"."
] |
jrxFive/python-nomad
|
python
|
https://github.com/jrxFive/python-nomad/blob/37df37e4de21e6f8ac41c6154e7f1f44f1800020/nomad/api/client.py#L226-L242
|
[
"def",
"stat_file",
"(",
"self",
",",
"id",
"=",
"None",
",",
"path",
"=",
"\"/\"",
")",
":",
"if",
"id",
":",
"return",
"self",
".",
"request",
"(",
"id",
",",
"params",
"=",
"{",
"\"path\"",
":",
"path",
"}",
",",
"method",
"=",
"\"get\"",
")",
".",
"json",
"(",
")",
"else",
":",
"return",
"self",
".",
"request",
"(",
"params",
"=",
"{",
"\"path\"",
":",
"path",
"}",
",",
"method",
"=",
"\"get\"",
")",
".",
"json",
"(",
")"
] |
37df37e4de21e6f8ac41c6154e7f1f44f1800020
|
test
|
Agent.join_agent
|
Initiate a join between the agent and target peers.
https://www.nomadproject.io/docs/http/agent-join.html
returns: dict
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
|
nomad/api/agent.py
|
def join_agent(self, addresses):
"""Initiate a join between the agent and target peers.
https://www.nomadproject.io/docs/http/agent-join.html
returns: dict
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
params = {"address": addresses}
return self.request("join", params=params, method="post").json()
|
def join_agent(self, addresses):
"""Initiate a join between the agent and target peers.
https://www.nomadproject.io/docs/http/agent-join.html
returns: dict
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
params = {"address": addresses}
return self.request("join", params=params, method="post").json()
|
[
"Initiate",
"a",
"join",
"between",
"the",
"agent",
"and",
"target",
"peers",
"."
] |
jrxFive/python-nomad
|
python
|
https://github.com/jrxFive/python-nomad/blob/37df37e4de21e6f8ac41c6154e7f1f44f1800020/nomad/api/agent.py#L60-L71
|
[
"def",
"join_agent",
"(",
"self",
",",
"addresses",
")",
":",
"params",
"=",
"{",
"\"address\"",
":",
"addresses",
"}",
"return",
"self",
".",
"request",
"(",
"\"join\"",
",",
"params",
"=",
"params",
",",
"method",
"=",
"\"post\"",
")",
".",
"json",
"(",
")"
] |
37df37e4de21e6f8ac41c6154e7f1f44f1800020
|
test
|
Agent.update_servers
|
Updates the list of known servers to the provided list.
Replaces all previous server addresses with the new list.
https://www.nomadproject.io/docs/http/agent-servers.html
returns: 200 status code
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
|
nomad/api/agent.py
|
def update_servers(self, addresses):
"""Updates the list of known servers to the provided list.
Replaces all previous server addresses with the new list.
https://www.nomadproject.io/docs/http/agent-servers.html
returns: 200 status code
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
params = {"address": addresses}
return self.request("servers", params=params, method="post").status_code
|
def update_servers(self, addresses):
"""Updates the list of known servers to the provided list.
Replaces all previous server addresses with the new list.
https://www.nomadproject.io/docs/http/agent-servers.html
returns: 200 status code
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
params = {"address": addresses}
return self.request("servers", params=params, method="post").status_code
|
[
"Updates",
"the",
"list",
"of",
"known",
"servers",
"to",
"the",
"provided",
"list",
".",
"Replaces",
"all",
"previous",
"server",
"addresses",
"with",
"the",
"new",
"list",
"."
] |
jrxFive/python-nomad
|
python
|
https://github.com/jrxFive/python-nomad/blob/37df37e4de21e6f8ac41c6154e7f1f44f1800020/nomad/api/agent.py#L73-L85
|
[
"def",
"update_servers",
"(",
"self",
",",
"addresses",
")",
":",
"params",
"=",
"{",
"\"address\"",
":",
"addresses",
"}",
"return",
"self",
".",
"request",
"(",
"\"servers\"",
",",
"params",
"=",
"params",
",",
"method",
"=",
"\"post\"",
")",
".",
"status_code"
] |
37df37e4de21e6f8ac41c6154e7f1f44f1800020
|
test
|
Agent.force_leave
|
Force a failed gossip member into the left state.
https://www.nomadproject.io/docs/http/agent-force-leave.html
returns: 200 status code
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
|
nomad/api/agent.py
|
def force_leave(self, node):
"""Force a failed gossip member into the left state.
https://www.nomadproject.io/docs/http/agent-force-leave.html
returns: 200 status code
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
params = {"node": node}
return self.request("force-leave", params=params, method="post").status_code
|
def force_leave(self, node):
"""Force a failed gossip member into the left state.
https://www.nomadproject.io/docs/http/agent-force-leave.html
returns: 200 status code
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
params = {"node": node}
return self.request("force-leave", params=params, method="post").status_code
|
[
"Force",
"a",
"failed",
"gossip",
"member",
"into",
"the",
"left",
"state",
"."
] |
jrxFive/python-nomad
|
python
|
https://github.com/jrxFive/python-nomad/blob/37df37e4de21e6f8ac41c6154e7f1f44f1800020/nomad/api/agent.py#L87-L98
|
[
"def",
"force_leave",
"(",
"self",
",",
"node",
")",
":",
"params",
"=",
"{",
"\"node\"",
":",
"node",
"}",
"return",
"self",
".",
"request",
"(",
"\"force-leave\"",
",",
"params",
"=",
"params",
",",
"method",
"=",
"\"post\"",
")",
".",
"status_code"
] |
37df37e4de21e6f8ac41c6154e7f1f44f1800020
|
test
|
Nodes.get_nodes
|
Lists all the client nodes registered with Nomad.
https://www.nomadproject.io/docs/http/nodes.html
arguments:
- prefix :(str) optional, specifies a string to filter nodes on based on an prefix.
This is specified as a querystring parameter.
returns: list
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
|
nomad/api/nodes.py
|
def get_nodes(self, prefix=None):
""" Lists all the client nodes registered with Nomad.
https://www.nomadproject.io/docs/http/nodes.html
arguments:
- prefix :(str) optional, specifies a string to filter nodes on based on an prefix.
This is specified as a querystring parameter.
returns: list
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
params = {"prefix": prefix}
return self.request(method="get", params=params).json()
|
def get_nodes(self, prefix=None):
""" Lists all the client nodes registered with Nomad.
https://www.nomadproject.io/docs/http/nodes.html
arguments:
- prefix :(str) optional, specifies a string to filter nodes on based on an prefix.
This is specified as a querystring parameter.
returns: list
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
params = {"prefix": prefix}
return self.request(method="get", params=params).json()
|
[
"Lists",
"all",
"the",
"client",
"nodes",
"registered",
"with",
"Nomad",
"."
] |
jrxFive/python-nomad
|
python
|
https://github.com/jrxFive/python-nomad/blob/37df37e4de21e6f8ac41c6154e7f1f44f1800020/nomad/api/nodes.py#L64-L77
|
[
"def",
"get_nodes",
"(",
"self",
",",
"prefix",
"=",
"None",
")",
":",
"params",
"=",
"{",
"\"prefix\"",
":",
"prefix",
"}",
"return",
"self",
".",
"request",
"(",
"method",
"=",
"\"get\"",
",",
"params",
"=",
"params",
")",
".",
"json",
"(",
")"
] |
37df37e4de21e6f8ac41c6154e7f1f44f1800020
|
test
|
Evaluations.get_evaluations
|
Lists all the evaluations.
https://www.nomadproject.io/docs/http/evals.html
arguments:
- prefix :(str) optional, specifies a string to filter evaluations on based on an prefix.
This is specified as a querystring parameter.
returns: list
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
|
nomad/api/evaluations.py
|
def get_evaluations(self, prefix=None):
""" Lists all the evaluations.
https://www.nomadproject.io/docs/http/evals.html
arguments:
- prefix :(str) optional, specifies a string to filter evaluations on based on an prefix.
This is specified as a querystring parameter.
returns: list
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
params = {"prefix": prefix}
return self.request(method="get", params=params).json()
|
def get_evaluations(self, prefix=None):
""" Lists all the evaluations.
https://www.nomadproject.io/docs/http/evals.html
arguments:
- prefix :(str) optional, specifies a string to filter evaluations on based on an prefix.
This is specified as a querystring parameter.
returns: list
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
params = {"prefix": prefix}
return self.request(method="get", params=params).json()
|
[
"Lists",
"all",
"the",
"evaluations",
"."
] |
jrxFive/python-nomad
|
python
|
https://github.com/jrxFive/python-nomad/blob/37df37e4de21e6f8ac41c6154e7f1f44f1800020/nomad/api/evaluations.py#L60-L73
|
[
"def",
"get_evaluations",
"(",
"self",
",",
"prefix",
"=",
"None",
")",
":",
"params",
"=",
"{",
"\"prefix\"",
":",
"prefix",
"}",
"return",
"self",
".",
"request",
"(",
"method",
"=",
"\"get\"",
",",
"params",
"=",
"params",
")",
".",
"json",
"(",
")"
] |
37df37e4de21e6f8ac41c6154e7f1f44f1800020
|
test
|
Namespaces.get_namespaces
|
Lists all the namespaces registered with Nomad.
https://www.nomadproject.io/docs/enterprise/namespaces/index.html
arguments:
- prefix :(str) optional, specifies a string to filter namespaces on based on an prefix.
This is specified as a querystring parameter.
returns: list
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
|
nomad/api/namespaces.py
|
def get_namespaces(self, prefix=None):
""" Lists all the namespaces registered with Nomad.
https://www.nomadproject.io/docs/enterprise/namespaces/index.html
arguments:
- prefix :(str) optional, specifies a string to filter namespaces on based on an prefix.
This is specified as a querystring parameter.
returns: list
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
params = {"prefix": prefix}
return self.request(method="get", params=params).json()
|
def get_namespaces(self, prefix=None):
""" Lists all the namespaces registered with Nomad.
https://www.nomadproject.io/docs/enterprise/namespaces/index.html
arguments:
- prefix :(str) optional, specifies a string to filter namespaces on based on an prefix.
This is specified as a querystring parameter.
returns: list
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
params = {"prefix": prefix}
return self.request(method="get", params=params).json()
|
[
"Lists",
"all",
"the",
"namespaces",
"registered",
"with",
"Nomad",
"."
] |
jrxFive/python-nomad
|
python
|
https://github.com/jrxFive/python-nomad/blob/37df37e4de21e6f8ac41c6154e7f1f44f1800020/nomad/api/namespaces.py#L60-L73
|
[
"def",
"get_namespaces",
"(",
"self",
",",
"prefix",
"=",
"None",
")",
":",
"params",
"=",
"{",
"\"prefix\"",
":",
"prefix",
"}",
"return",
"self",
".",
"request",
"(",
"method",
"=",
"\"get\"",
",",
"params",
"=",
"params",
")",
".",
"json",
"(",
")"
] |
37df37e4de21e6f8ac41c6154e7f1f44f1800020
|
test
|
Job.register_job
|
Registers a new job or updates an existing job
https://www.nomadproject.io/docs/http/job.html
arguments:
- id
returns: dict
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
|
nomad/api/job.py
|
def register_job(self, id, job):
""" Registers a new job or updates an existing job
https://www.nomadproject.io/docs/http/job.html
arguments:
- id
returns: dict
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
return self.request(id, json=job, method="post").json()
|
def register_job(self, id, job):
""" Registers a new job or updates an existing job
https://www.nomadproject.io/docs/http/job.html
arguments:
- id
returns: dict
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
return self.request(id, json=job, method="post").json()
|
[
"Registers",
"a",
"new",
"job",
"or",
"updates",
"an",
"existing",
"job"
] |
jrxFive/python-nomad
|
python
|
https://github.com/jrxFive/python-nomad/blob/37df37e4de21e6f8ac41c6154e7f1f44f1800020/nomad/api/job.py#L149-L161
|
[
"def",
"register_job",
"(",
"self",
",",
"id",
",",
"job",
")",
":",
"return",
"self",
".",
"request",
"(",
"id",
",",
"json",
"=",
"job",
",",
"method",
"=",
"\"post\"",
")",
".",
"json",
"(",
")"
] |
37df37e4de21e6f8ac41c6154e7f1f44f1800020
|
test
|
Job.plan_job
|
Invoke a dry-run of the scheduler for the job.
https://www.nomadproject.io/docs/http/job.html
arguments:
- id
- job, dict
- diff, boolean
- policy_override, boolean
returns: dict
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
|
nomad/api/job.py
|
def plan_job(self, id, job, diff=False, policy_override=False):
""" Invoke a dry-run of the scheduler for the job.
https://www.nomadproject.io/docs/http/job.html
arguments:
- id
- job, dict
- diff, boolean
- policy_override, boolean
returns: dict
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
json_dict = {}
json_dict.update(job)
json_dict.setdefault('Diff', diff)
json_dict.setdefault('PolicyOverride', policy_override)
return self.request(id, "plan", json=json_dict, method="post").json()
|
def plan_job(self, id, job, diff=False, policy_override=False):
""" Invoke a dry-run of the scheduler for the job.
https://www.nomadproject.io/docs/http/job.html
arguments:
- id
- job, dict
- diff, boolean
- policy_override, boolean
returns: dict
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
json_dict = {}
json_dict.update(job)
json_dict.setdefault('Diff', diff)
json_dict.setdefault('PolicyOverride', policy_override)
return self.request(id, "plan", json=json_dict, method="post").json()
|
[
"Invoke",
"a",
"dry",
"-",
"run",
"of",
"the",
"scheduler",
"for",
"the",
"job",
"."
] |
jrxFive/python-nomad
|
python
|
https://github.com/jrxFive/python-nomad/blob/37df37e4de21e6f8ac41c6154e7f1f44f1800020/nomad/api/job.py#L178-L197
|
[
"def",
"plan_job",
"(",
"self",
",",
"id",
",",
"job",
",",
"diff",
"=",
"False",
",",
"policy_override",
"=",
"False",
")",
":",
"json_dict",
"=",
"{",
"}",
"json_dict",
".",
"update",
"(",
"job",
")",
"json_dict",
".",
"setdefault",
"(",
"'Diff'",
",",
"diff",
")",
"json_dict",
".",
"setdefault",
"(",
"'PolicyOverride'",
",",
"policy_override",
")",
"return",
"self",
".",
"request",
"(",
"id",
",",
"\"plan\"",
",",
"json",
"=",
"json_dict",
",",
"method",
"=",
"\"post\"",
")",
".",
"json",
"(",
")"
] |
37df37e4de21e6f8ac41c6154e7f1f44f1800020
|
test
|
Job.dispatch_job
|
Dispatches a new instance of a parameterized job.
https://www.nomadproject.io/docs/http/job.html
arguments:
- id
- payload
- meta
returns: dict
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
|
nomad/api/job.py
|
def dispatch_job(self, id, payload=None, meta=None):
""" Dispatches a new instance of a parameterized job.
https://www.nomadproject.io/docs/http/job.html
arguments:
- id
- payload
- meta
returns: dict
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
dispatch_json = {"Meta": meta, "Payload": payload}
return self.request(id, "dispatch", json=dispatch_json, method="post").json()
|
def dispatch_job(self, id, payload=None, meta=None):
""" Dispatches a new instance of a parameterized job.
https://www.nomadproject.io/docs/http/job.html
arguments:
- id
- payload
- meta
returns: dict
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
dispatch_json = {"Meta": meta, "Payload": payload}
return self.request(id, "dispatch", json=dispatch_json, method="post").json()
|
[
"Dispatches",
"a",
"new",
"instance",
"of",
"a",
"parameterized",
"job",
"."
] |
jrxFive/python-nomad
|
python
|
https://github.com/jrxFive/python-nomad/blob/37df37e4de21e6f8ac41c6154e7f1f44f1800020/nomad/api/job.py#L216-L231
|
[
"def",
"dispatch_job",
"(",
"self",
",",
"id",
",",
"payload",
"=",
"None",
",",
"meta",
"=",
"None",
")",
":",
"dispatch_json",
"=",
"{",
"\"Meta\"",
":",
"meta",
",",
"\"Payload\"",
":",
"payload",
"}",
"return",
"self",
".",
"request",
"(",
"id",
",",
"\"dispatch\"",
",",
"json",
"=",
"dispatch_json",
",",
"method",
"=",
"\"post\"",
")",
".",
"json",
"(",
")"
] |
37df37e4de21e6f8ac41c6154e7f1f44f1800020
|
test
|
Job.revert_job
|
This endpoint reverts the job to an older version.
https://www.nomadproject.io/docs/http/job.html
arguments:
- id
- version, Specifies the job version to revert to.
optional_arguments:
- enforce_prior_version, Optional value specifying the current job's version.
This is checked and acts as a check-and-set value before reverting to the
specified job.
returns: dict
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
|
nomad/api/job.py
|
def revert_job(self, id, version, enforce_prior_version=None):
""" This endpoint reverts the job to an older version.
https://www.nomadproject.io/docs/http/job.html
arguments:
- id
- version, Specifies the job version to revert to.
optional_arguments:
- enforce_prior_version, Optional value specifying the current job's version.
This is checked and acts as a check-and-set value before reverting to the
specified job.
returns: dict
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
revert_json = {"JobID": id,
"JobVersion": version,
"EnforcePriorVersion": enforce_prior_version}
return self.request(id, "revert", json=revert_json, method="post").json()
|
def revert_job(self, id, version, enforce_prior_version=None):
""" This endpoint reverts the job to an older version.
https://www.nomadproject.io/docs/http/job.html
arguments:
- id
- version, Specifies the job version to revert to.
optional_arguments:
- enforce_prior_version, Optional value specifying the current job's version.
This is checked and acts as a check-and-set value before reverting to the
specified job.
returns: dict
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
revert_json = {"JobID": id,
"JobVersion": version,
"EnforcePriorVersion": enforce_prior_version}
return self.request(id, "revert", json=revert_json, method="post").json()
|
[
"This",
"endpoint",
"reverts",
"the",
"job",
"to",
"an",
"older",
"version",
"."
] |
jrxFive/python-nomad
|
python
|
https://github.com/jrxFive/python-nomad/blob/37df37e4de21e6f8ac41c6154e7f1f44f1800020/nomad/api/job.py#L233-L253
|
[
"def",
"revert_job",
"(",
"self",
",",
"id",
",",
"version",
",",
"enforce_prior_version",
"=",
"None",
")",
":",
"revert_json",
"=",
"{",
"\"JobID\"",
":",
"id",
",",
"\"JobVersion\"",
":",
"version",
",",
"\"EnforcePriorVersion\"",
":",
"enforce_prior_version",
"}",
"return",
"self",
".",
"request",
"(",
"id",
",",
"\"revert\"",
",",
"json",
"=",
"revert_json",
",",
"method",
"=",
"\"post\"",
")",
".",
"json",
"(",
")"
] |
37df37e4de21e6f8ac41c6154e7f1f44f1800020
|
test
|
Job.stable_job
|
This endpoint sets the job's stability.
https://www.nomadproject.io/docs/http/job.html
arguments:
- id
- version, Specifies the job version to revert to.
- stable, Specifies whether the job should be marked as stable or not.
returns: dict
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
|
nomad/api/job.py
|
def stable_job(self, id, version, stable):
""" This endpoint sets the job's stability.
https://www.nomadproject.io/docs/http/job.html
arguments:
- id
- version, Specifies the job version to revert to.
- stable, Specifies whether the job should be marked as stable or not.
returns: dict
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
revert_json = {"JobID": id,
"JobVersion": version,
"Stable": stable}
return self.request(id, "stable", json=revert_json, method="post").json()
|
def stable_job(self, id, version, stable):
""" This endpoint sets the job's stability.
https://www.nomadproject.io/docs/http/job.html
arguments:
- id
- version, Specifies the job version to revert to.
- stable, Specifies whether the job should be marked as stable or not.
returns: dict
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
revert_json = {"JobID": id,
"JobVersion": version,
"Stable": stable}
return self.request(id, "stable", json=revert_json, method="post").json()
|
[
"This",
"endpoint",
"sets",
"the",
"job",
"s",
"stability",
"."
] |
jrxFive/python-nomad
|
python
|
https://github.com/jrxFive/python-nomad/blob/37df37e4de21e6f8ac41c6154e7f1f44f1800020/nomad/api/job.py#L255-L272
|
[
"def",
"stable_job",
"(",
"self",
",",
"id",
",",
"version",
",",
"stable",
")",
":",
"revert_json",
"=",
"{",
"\"JobID\"",
":",
"id",
",",
"\"JobVersion\"",
":",
"version",
",",
"\"Stable\"",
":",
"stable",
"}",
"return",
"self",
".",
"request",
"(",
"id",
",",
"\"stable\"",
",",
"json",
"=",
"revert_json",
",",
"method",
"=",
"\"post\"",
")",
".",
"json",
"(",
")"
] |
37df37e4de21e6f8ac41c6154e7f1f44f1800020
|
test
|
Job.deregister_job
|
Deregisters a job, and stops all allocations part of it.
https://www.nomadproject.io/docs/http/job.html
arguments:
- id
- purge (bool), optionally specifies whether the job should be
stopped and purged immediately (`purge=True`) or deferred to the
Nomad garbage collector (`purge=False`).
returns: dict
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
- nomad.api.exceptions.InvalidParameters
|
nomad/api/job.py
|
def deregister_job(self, id, purge=None):
""" Deregisters a job, and stops all allocations part of it.
https://www.nomadproject.io/docs/http/job.html
arguments:
- id
- purge (bool), optionally specifies whether the job should be
stopped and purged immediately (`purge=True`) or deferred to the
Nomad garbage collector (`purge=False`).
returns: dict
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
- nomad.api.exceptions.InvalidParameters
"""
params = None
if purge is not None:
if not isinstance(purge, bool):
raise nomad.api.exceptions.InvalidParameters("purge is invalid "
"(expected type %s but got %s)"%(type(bool()), type(purge)))
params = {"purge": purge}
return self.request(id, params=params, method="delete").json()
|
def deregister_job(self, id, purge=None):
""" Deregisters a job, and stops all allocations part of it.
https://www.nomadproject.io/docs/http/job.html
arguments:
- id
- purge (bool), optionally specifies whether the job should be
stopped and purged immediately (`purge=True`) or deferred to the
Nomad garbage collector (`purge=False`).
returns: dict
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
- nomad.api.exceptions.InvalidParameters
"""
params = None
if purge is not None:
if not isinstance(purge, bool):
raise nomad.api.exceptions.InvalidParameters("purge is invalid "
"(expected type %s but got %s)"%(type(bool()), type(purge)))
params = {"purge": purge}
return self.request(id, params=params, method="delete").json()
|
[
"Deregisters",
"a",
"job",
"and",
"stops",
"all",
"allocations",
"part",
"of",
"it",
"."
] |
jrxFive/python-nomad
|
python
|
https://github.com/jrxFive/python-nomad/blob/37df37e4de21e6f8ac41c6154e7f1f44f1800020/nomad/api/job.py#L274-L297
|
[
"def",
"deregister_job",
"(",
"self",
",",
"id",
",",
"purge",
"=",
"None",
")",
":",
"params",
"=",
"None",
"if",
"purge",
"is",
"not",
"None",
":",
"if",
"not",
"isinstance",
"(",
"purge",
",",
"bool",
")",
":",
"raise",
"nomad",
".",
"api",
".",
"exceptions",
".",
"InvalidParameters",
"(",
"\"purge is invalid \"",
"\"(expected type %s but got %s)\"",
"%",
"(",
"type",
"(",
"bool",
"(",
")",
")",
",",
"type",
"(",
"purge",
")",
")",
")",
"params",
"=",
"{",
"\"purge\"",
":",
"purge",
"}",
"return",
"self",
".",
"request",
"(",
"id",
",",
"params",
"=",
"params",
",",
"method",
"=",
"\"delete\"",
")",
".",
"json",
"(",
")"
] |
37df37e4de21e6f8ac41c6154e7f1f44f1800020
|
test
|
Operator.get_configuration
|
Query the status of a client node registered with Nomad.
https://www.nomadproject.io/docs/http/operator.html
returns: dict
optional arguments:
- stale, (defaults to False), Specifies if the cluster should respond without an active leader.
This is specified as a querystring parameter.
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
|
nomad/api/operator.py
|
def get_configuration(self, stale=False):
""" Query the status of a client node registered with Nomad.
https://www.nomadproject.io/docs/http/operator.html
returns: dict
optional arguments:
- stale, (defaults to False), Specifies if the cluster should respond without an active leader.
This is specified as a querystring parameter.
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
params = {"stale": stale}
return self.request("raft", "configuration", params=params, method="get").json()
|
def get_configuration(self, stale=False):
""" Query the status of a client node registered with Nomad.
https://www.nomadproject.io/docs/http/operator.html
returns: dict
optional arguments:
- stale, (defaults to False), Specifies if the cluster should respond without an active leader.
This is specified as a querystring parameter.
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
params = {"stale": stale}
return self.request("raft", "configuration", params=params, method="get").json()
|
[
"Query",
"the",
"status",
"of",
"a",
"client",
"node",
"registered",
"with",
"Nomad",
"."
] |
jrxFive/python-nomad
|
python
|
https://github.com/jrxFive/python-nomad/blob/37df37e4de21e6f8ac41c6154e7f1f44f1800020/nomad/api/operator.py#L27-L42
|
[
"def",
"get_configuration",
"(",
"self",
",",
"stale",
"=",
"False",
")",
":",
"params",
"=",
"{",
"\"stale\"",
":",
"stale",
"}",
"return",
"self",
".",
"request",
"(",
"\"raft\"",
",",
"\"configuration\"",
",",
"params",
"=",
"params",
",",
"method",
"=",
"\"get\"",
")",
".",
"json",
"(",
")"
] |
37df37e4de21e6f8ac41c6154e7f1f44f1800020
|
test
|
Operator.delete_peer
|
Remove the Nomad server with given address from the Raft configuration.
The return code signifies success or failure.
https://www.nomadproject.io/docs/http/operator.html
arguments:
- peer_address, The address specifies the server to remove and is given as an IP:port
optional arguments:
- stale, (defaults to False), Specifies if the cluster should respond without an active leader.
This is specified as a querystring parameter.
returns: Boolean
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
|
nomad/api/operator.py
|
def delete_peer(self, peer_address, stale=False):
""" Remove the Nomad server with given address from the Raft configuration.
The return code signifies success or failure.
https://www.nomadproject.io/docs/http/operator.html
arguments:
- peer_address, The address specifies the server to remove and is given as an IP:port
optional arguments:
- stale, (defaults to False), Specifies if the cluster should respond without an active leader.
This is specified as a querystring parameter.
returns: Boolean
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
params = {"address": peer_address, "stale": stale}
return self.request("raft", "peer", params=params, method="delete").ok
|
def delete_peer(self, peer_address, stale=False):
""" Remove the Nomad server with given address from the Raft configuration.
The return code signifies success or failure.
https://www.nomadproject.io/docs/http/operator.html
arguments:
- peer_address, The address specifies the server to remove and is given as an IP:port
optional arguments:
- stale, (defaults to False), Specifies if the cluster should respond without an active leader.
This is specified as a querystring parameter.
returns: Boolean
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
params = {"address": peer_address, "stale": stale}
return self.request("raft", "peer", params=params, method="delete").ok
|
[
"Remove",
"the",
"Nomad",
"server",
"with",
"given",
"address",
"from",
"the",
"Raft",
"configuration",
".",
"The",
"return",
"code",
"signifies",
"success",
"or",
"failure",
"."
] |
jrxFive/python-nomad
|
python
|
https://github.com/jrxFive/python-nomad/blob/37df37e4de21e6f8ac41c6154e7f1f44f1800020/nomad/api/operator.py#L44-L62
|
[
"def",
"delete_peer",
"(",
"self",
",",
"peer_address",
",",
"stale",
"=",
"False",
")",
":",
"params",
"=",
"{",
"\"address\"",
":",
"peer_address",
",",
"\"stale\"",
":",
"stale",
"}",
"return",
"self",
".",
"request",
"(",
"\"raft\"",
",",
"\"peer\"",
",",
"params",
"=",
"params",
",",
"method",
"=",
"\"delete\"",
")",
".",
"ok"
] |
37df37e4de21e6f8ac41c6154e7f1f44f1800020
|
test
|
Deployments.get_deployments
|
This endpoint lists all deployments.
https://www.nomadproject.io/docs/http/deployments.html
optional_arguments:
- prefix, (default "") Specifies a string to filter deployments on based on an index prefix.
This is specified as a querystring parameter.
returns: list of dicts
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
|
nomad/api/deployments.py
|
def get_deployments(self, prefix=""):
""" This endpoint lists all deployments.
https://www.nomadproject.io/docs/http/deployments.html
optional_arguments:
- prefix, (default "") Specifies a string to filter deployments on based on an index prefix.
This is specified as a querystring parameter.
returns: list of dicts
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
params = {"prefix": prefix}
return self.request(params=params, method="get").json()
|
def get_deployments(self, prefix=""):
""" This endpoint lists all deployments.
https://www.nomadproject.io/docs/http/deployments.html
optional_arguments:
- prefix, (default "") Specifies a string to filter deployments on based on an index prefix.
This is specified as a querystring parameter.
returns: list of dicts
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
params = {"prefix": prefix}
return self.request(params=params, method="get").json()
|
[
"This",
"endpoint",
"lists",
"all",
"deployments",
"."
] |
jrxFive/python-nomad
|
python
|
https://github.com/jrxFive/python-nomad/blob/37df37e4de21e6f8ac41c6154e7f1f44f1800020/nomad/api/deployments.py#L59-L74
|
[
"def",
"get_deployments",
"(",
"self",
",",
"prefix",
"=",
"\"\"",
")",
":",
"params",
"=",
"{",
"\"prefix\"",
":",
"prefix",
"}",
"return",
"self",
".",
"request",
"(",
"params",
"=",
"params",
",",
"method",
"=",
"\"get\"",
")",
".",
"json",
"(",
")"
] |
37df37e4de21e6f8ac41c6154e7f1f44f1800020
|
test
|
Namespace.update_namespace
|
Update namespace
https://www.nomadproject.io/api/namespaces.html
arguments:
- id
- namespace (dict)
returns: requests.Response
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
|
nomad/api/namespace.py
|
def update_namespace(self, id, namespace):
""" Update namespace
https://www.nomadproject.io/api/namespaces.html
arguments:
- id
- namespace (dict)
returns: requests.Response
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
return self.request(id, json=namespace, method="post")
|
def update_namespace(self, id, namespace):
""" Update namespace
https://www.nomadproject.io/api/namespaces.html
arguments:
- id
- namespace (dict)
returns: requests.Response
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.URLNotFoundNomadException
"""
return self.request(id, json=namespace, method="post")
|
[
"Update",
"namespace"
] |
jrxFive/python-nomad
|
python
|
https://github.com/jrxFive/python-nomad/blob/37df37e4de21e6f8ac41c6154e7f1f44f1800020/nomad/api/namespace.py#L80-L93
|
[
"def",
"update_namespace",
"(",
"self",
",",
"id",
",",
"namespace",
")",
":",
"return",
"self",
".",
"request",
"(",
"id",
",",
"json",
"=",
"namespace",
",",
"method",
"=",
"\"post\"",
")"
] |
37df37e4de21e6f8ac41c6154e7f1f44f1800020
|
test
|
PJFMutators._get_random
|
Get a random mutator from a list of mutators
|
pyjfuzz/core/pjf_mutators.py
|
def _get_random(self, obj_type):
"""
Get a random mutator from a list of mutators
"""
return self.mutator[obj_type][random.randint(0, self.config.level)]
|
def _get_random(self, obj_type):
"""
Get a random mutator from a list of mutators
"""
return self.mutator[obj_type][random.randint(0, self.config.level)]
|
[
"Get",
"a",
"random",
"mutator",
"from",
"a",
"list",
"of",
"mutators"
] |
mseclab/PyJFuzz
|
python
|
https://github.com/mseclab/PyJFuzz/blob/f777067076f62c9ab74ffea6e90fd54402b7a1b4/pyjfuzz/core/pjf_mutators.py#L127-L131
|
[
"def",
"_get_random",
"(",
"self",
",",
"obj_type",
")",
":",
"return",
"self",
".",
"mutator",
"[",
"obj_type",
"]",
"[",
"random",
".",
"randint",
"(",
"0",
",",
"self",
".",
"config",
".",
"level",
")",
"]"
] |
f777067076f62c9ab74ffea6e90fd54402b7a1b4
|
test
|
PJFMutators.get_mutator
|
Get a random mutator for the given type
|
pyjfuzz/core/pjf_mutators.py
|
def get_mutator(self, obj, obj_type):
"""
Get a random mutator for the given type
"""
if obj_type == unicode:
obj_type = str
obj = str(obj)
return self._get_random(obj_type)(obj)
|
def get_mutator(self, obj, obj_type):
"""
Get a random mutator for the given type
"""
if obj_type == unicode:
obj_type = str
obj = str(obj)
return self._get_random(obj_type)(obj)
|
[
"Get",
"a",
"random",
"mutator",
"for",
"the",
"given",
"type"
] |
mseclab/PyJFuzz
|
python
|
https://github.com/mseclab/PyJFuzz/blob/f777067076f62c9ab74ffea6e90fd54402b7a1b4/pyjfuzz/core/pjf_mutators.py#L133-L140
|
[
"def",
"get_mutator",
"(",
"self",
",",
"obj",
",",
"obj_type",
")",
":",
"if",
"obj_type",
"==",
"unicode",
":",
"obj_type",
"=",
"str",
"obj",
"=",
"str",
"(",
"obj",
")",
"return",
"self",
".",
"_get_random",
"(",
"obj_type",
")",
"(",
"obj",
")"
] |
f777067076f62c9ab74ffea6e90fd54402b7a1b4
|
test
|
PJFMutators.get_string_polyglot_attack
|
Return a polyglot attack containing the original object
|
pyjfuzz/core/pjf_mutators.py
|
def get_string_polyglot_attack(self, obj):
"""
Return a polyglot attack containing the original object
"""
return self.polyglot_attacks[random.choice(self.config.techniques)] % obj
|
def get_string_polyglot_attack(self, obj):
"""
Return a polyglot attack containing the original object
"""
return self.polyglot_attacks[random.choice(self.config.techniques)] % obj
|
[
"Return",
"a",
"polyglot",
"attack",
"containing",
"the",
"original",
"object"
] |
mseclab/PyJFuzz
|
python
|
https://github.com/mseclab/PyJFuzz/blob/f777067076f62c9ab74ffea6e90fd54402b7a1b4/pyjfuzz/core/pjf_mutators.py#L142-L146
|
[
"def",
"get_string_polyglot_attack",
"(",
"self",
",",
"obj",
")",
":",
"return",
"self",
".",
"polyglot_attacks",
"[",
"random",
".",
"choice",
"(",
"self",
".",
"config",
".",
"techniques",
")",
"]",
"%",
"obj"
] |
f777067076f62c9ab74ffea6e90fd54402b7a1b4
|
test
|
PJFMutators.fuzz
|
Perform the fuzzing
|
pyjfuzz/core/pjf_mutators.py
|
def fuzz(self, obj):
"""
Perform the fuzzing
"""
buf = list(obj)
FuzzFactor = random.randrange(1, len(buf))
numwrites=random.randrange(math.ceil((float(len(buf)) / FuzzFactor)))+1
for j in range(numwrites):
self.random_action(buf)
return self.safe_unicode(buf)
|
def fuzz(self, obj):
"""
Perform the fuzzing
"""
buf = list(obj)
FuzzFactor = random.randrange(1, len(buf))
numwrites=random.randrange(math.ceil((float(len(buf)) / FuzzFactor)))+1
for j in range(numwrites):
self.random_action(buf)
return self.safe_unicode(buf)
|
[
"Perform",
"the",
"fuzzing"
] |
mseclab/PyJFuzz
|
python
|
https://github.com/mseclab/PyJFuzz/blob/f777067076f62c9ab74ffea6e90fd54402b7a1b4/pyjfuzz/core/pjf_mutators.py#L148-L157
|
[
"def",
"fuzz",
"(",
"self",
",",
"obj",
")",
":",
"buf",
"=",
"list",
"(",
"obj",
")",
"FuzzFactor",
"=",
"random",
".",
"randrange",
"(",
"1",
",",
"len",
"(",
"buf",
")",
")",
"numwrites",
"=",
"random",
".",
"randrange",
"(",
"math",
".",
"ceil",
"(",
"(",
"float",
"(",
"len",
"(",
"buf",
")",
")",
"/",
"FuzzFactor",
")",
")",
")",
"+",
"1",
"for",
"j",
"in",
"range",
"(",
"numwrites",
")",
":",
"self",
".",
"random_action",
"(",
"buf",
")",
"return",
"self",
".",
"safe_unicode",
"(",
"buf",
")"
] |
f777067076f62c9ab74ffea6e90fd54402b7a1b4
|
test
|
PJFMutators.random_action
|
Perform the actual fuzzing using random strategies
|
pyjfuzz/core/pjf_mutators.py
|
def random_action(self, b):
"""
Perform the actual fuzzing using random strategies
"""
action = random.choice([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
if len(b) >= 3:
pos = random.randint(0, len(b)-2)
if action == 1:
rbyte = random.randrange(256)
rn = random.randrange(len(b))
b[rn] = "%c" % rbyte
elif action == 2:
howmany = random.randint(1, 100)
curpos = pos
for _ in range(0, howmany):
b.insert(curpos, b[pos])
pos += 1
elif action == 3:
n = random.choice([1, 2, 4])
for _ in range(0, n):
if len(b) > pos+1:
tmp = b[pos]
b[pos] = b[pos+1]
b[pos+1] = tmp
pos += 1
else:
pos -= 2
tmp = b[pos]
b[pos] = b[pos+1]
b[pos+1] = tmp
pos += 1
elif action in [4, 5]:
op = {
4: lambda x, y: ord(x) << y,
5: lambda x, y: ord(x) >> y,
}
n = random.choice([1, 2, 4])
if len(b) < pos+n:
pos = len(b) - (pos+n)
if n == 1:
f = "<B"
s = op[action](b[pos], n) % 0xff
elif n == 2:
f = "<H"
s = op[action](b[pos], n) % 0xffff
elif n == 4:
f = "<I"
s = op[action](b[pos], n) % 0xffffff
val = struct.pack(f, s)
for v in val:
if isinstance(v, int):
v = chr(v)
b[pos] = v
pos += 1
elif action == 6:
b.insert(random.randint(0, len(b)-1), random.choice(["\"", "[", "]", "+", "-", "}", "{"]))
elif action == 7:
del b[random.randint(0, len(b)-1)]
elif action in [8, 9]:
block = random.choice([
(r"\"", r"\""),
(r"\[", r"\]"),
(r"\{", r"\}")
])
b_str = self.safe_join(b)
block_re = re.compile(str(".+({0}[^{2}{3}]+{1}).+").format(block[0], block[1], block[0], block[1]))
if block_re.search(b_str):
r = random.choice(block_re.findall(b_str))
random_re = re.compile("({0})".format(re.escape(r)))
if random_re.search(b_str):
if action == 8:
newarr = list(random_re.sub("", b_str))
b[:] = newarr
else:
newarr = list(random_re.sub("\\1" * random.randint(1, 10), b_str, 1))
b[:] = newarr
elif action == 10:
b_str = self.safe_join(b)
limit_choice = random.choice([
0x7FFFFFFF,
-0x80000000,
0xff,
-0xff,
])
block_re = re.compile("(\-?[0-9]+)")
if block_re.search(b_str):
block = random.choice([m for m in block_re.finditer(b_str)])
new = b_str[0:block.start()] + str(int(block.group())*limit_choice) + b_str[block.start() +
len(block.group()):]
b[:] = list(new)
|
def random_action(self, b):
"""
Perform the actual fuzzing using random strategies
"""
action = random.choice([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
if len(b) >= 3:
pos = random.randint(0, len(b)-2)
if action == 1:
rbyte = random.randrange(256)
rn = random.randrange(len(b))
b[rn] = "%c" % rbyte
elif action == 2:
howmany = random.randint(1, 100)
curpos = pos
for _ in range(0, howmany):
b.insert(curpos, b[pos])
pos += 1
elif action == 3:
n = random.choice([1, 2, 4])
for _ in range(0, n):
if len(b) > pos+1:
tmp = b[pos]
b[pos] = b[pos+1]
b[pos+1] = tmp
pos += 1
else:
pos -= 2
tmp = b[pos]
b[pos] = b[pos+1]
b[pos+1] = tmp
pos += 1
elif action in [4, 5]:
op = {
4: lambda x, y: ord(x) << y,
5: lambda x, y: ord(x) >> y,
}
n = random.choice([1, 2, 4])
if len(b) < pos+n:
pos = len(b) - (pos+n)
if n == 1:
f = "<B"
s = op[action](b[pos], n) % 0xff
elif n == 2:
f = "<H"
s = op[action](b[pos], n) % 0xffff
elif n == 4:
f = "<I"
s = op[action](b[pos], n) % 0xffffff
val = struct.pack(f, s)
for v in val:
if isinstance(v, int):
v = chr(v)
b[pos] = v
pos += 1
elif action == 6:
b.insert(random.randint(0, len(b)-1), random.choice(["\"", "[", "]", "+", "-", "}", "{"]))
elif action == 7:
del b[random.randint(0, len(b)-1)]
elif action in [8, 9]:
block = random.choice([
(r"\"", r"\""),
(r"\[", r"\]"),
(r"\{", r"\}")
])
b_str = self.safe_join(b)
block_re = re.compile(str(".+({0}[^{2}{3}]+{1}).+").format(block[0], block[1], block[0], block[1]))
if block_re.search(b_str):
r = random.choice(block_re.findall(b_str))
random_re = re.compile("({0})".format(re.escape(r)))
if random_re.search(b_str):
if action == 8:
newarr = list(random_re.sub("", b_str))
b[:] = newarr
else:
newarr = list(random_re.sub("\\1" * random.randint(1, 10), b_str, 1))
b[:] = newarr
elif action == 10:
b_str = self.safe_join(b)
limit_choice = random.choice([
0x7FFFFFFF,
-0x80000000,
0xff,
-0xff,
])
block_re = re.compile("(\-?[0-9]+)")
if block_re.search(b_str):
block = random.choice([m for m in block_re.finditer(b_str)])
new = b_str[0:block.start()] + str(int(block.group())*limit_choice) + b_str[block.start() +
len(block.group()):]
b[:] = list(new)
|
[
"Perform",
"the",
"actual",
"fuzzing",
"using",
"random",
"strategies"
] |
mseclab/PyJFuzz
|
python
|
https://github.com/mseclab/PyJFuzz/blob/f777067076f62c9ab74ffea6e90fd54402b7a1b4/pyjfuzz/core/pjf_mutators.py#L159-L248
|
[
"def",
"random_action",
"(",
"self",
",",
"b",
")",
":",
"action",
"=",
"random",
".",
"choice",
"(",
"[",
"1",
",",
"2",
",",
"3",
",",
"4",
",",
"5",
",",
"6",
",",
"7",
",",
"8",
",",
"9",
",",
"10",
"]",
")",
"if",
"len",
"(",
"b",
")",
">=",
"3",
":",
"pos",
"=",
"random",
".",
"randint",
"(",
"0",
",",
"len",
"(",
"b",
")",
"-",
"2",
")",
"if",
"action",
"==",
"1",
":",
"rbyte",
"=",
"random",
".",
"randrange",
"(",
"256",
")",
"rn",
"=",
"random",
".",
"randrange",
"(",
"len",
"(",
"b",
")",
")",
"b",
"[",
"rn",
"]",
"=",
"\"%c\"",
"%",
"rbyte",
"elif",
"action",
"==",
"2",
":",
"howmany",
"=",
"random",
".",
"randint",
"(",
"1",
",",
"100",
")",
"curpos",
"=",
"pos",
"for",
"_",
"in",
"range",
"(",
"0",
",",
"howmany",
")",
":",
"b",
".",
"insert",
"(",
"curpos",
",",
"b",
"[",
"pos",
"]",
")",
"pos",
"+=",
"1",
"elif",
"action",
"==",
"3",
":",
"n",
"=",
"random",
".",
"choice",
"(",
"[",
"1",
",",
"2",
",",
"4",
"]",
")",
"for",
"_",
"in",
"range",
"(",
"0",
",",
"n",
")",
":",
"if",
"len",
"(",
"b",
")",
">",
"pos",
"+",
"1",
":",
"tmp",
"=",
"b",
"[",
"pos",
"]",
"b",
"[",
"pos",
"]",
"=",
"b",
"[",
"pos",
"+",
"1",
"]",
"b",
"[",
"pos",
"+",
"1",
"]",
"=",
"tmp",
"pos",
"+=",
"1",
"else",
":",
"pos",
"-=",
"2",
"tmp",
"=",
"b",
"[",
"pos",
"]",
"b",
"[",
"pos",
"]",
"=",
"b",
"[",
"pos",
"+",
"1",
"]",
"b",
"[",
"pos",
"+",
"1",
"]",
"=",
"tmp",
"pos",
"+=",
"1",
"elif",
"action",
"in",
"[",
"4",
",",
"5",
"]",
":",
"op",
"=",
"{",
"4",
":",
"lambda",
"x",
",",
"y",
":",
"ord",
"(",
"x",
")",
"<<",
"y",
",",
"5",
":",
"lambda",
"x",
",",
"y",
":",
"ord",
"(",
"x",
")",
">>",
"y",
",",
"}",
"n",
"=",
"random",
".",
"choice",
"(",
"[",
"1",
",",
"2",
",",
"4",
"]",
")",
"if",
"len",
"(",
"b",
")",
"<",
"pos",
"+",
"n",
":",
"pos",
"=",
"len",
"(",
"b",
")",
"-",
"(",
"pos",
"+",
"n",
")",
"if",
"n",
"==",
"1",
":",
"f",
"=",
"\"<B\"",
"s",
"=",
"op",
"[",
"action",
"]",
"(",
"b",
"[",
"pos",
"]",
",",
"n",
")",
"%",
"0xff",
"elif",
"n",
"==",
"2",
":",
"f",
"=",
"\"<H\"",
"s",
"=",
"op",
"[",
"action",
"]",
"(",
"b",
"[",
"pos",
"]",
",",
"n",
")",
"%",
"0xffff",
"elif",
"n",
"==",
"4",
":",
"f",
"=",
"\"<I\"",
"s",
"=",
"op",
"[",
"action",
"]",
"(",
"b",
"[",
"pos",
"]",
",",
"n",
")",
"%",
"0xffffff",
"val",
"=",
"struct",
".",
"pack",
"(",
"f",
",",
"s",
")",
"for",
"v",
"in",
"val",
":",
"if",
"isinstance",
"(",
"v",
",",
"int",
")",
":",
"v",
"=",
"chr",
"(",
"v",
")",
"b",
"[",
"pos",
"]",
"=",
"v",
"pos",
"+=",
"1",
"elif",
"action",
"==",
"6",
":",
"b",
".",
"insert",
"(",
"random",
".",
"randint",
"(",
"0",
",",
"len",
"(",
"b",
")",
"-",
"1",
")",
",",
"random",
".",
"choice",
"(",
"[",
"\"\\\"\"",
",",
"\"[\"",
",",
"\"]\"",
",",
"\"+\"",
",",
"\"-\"",
",",
"\"}\"",
",",
"\"{\"",
"]",
")",
")",
"elif",
"action",
"==",
"7",
":",
"del",
"b",
"[",
"random",
".",
"randint",
"(",
"0",
",",
"len",
"(",
"b",
")",
"-",
"1",
")",
"]",
"elif",
"action",
"in",
"[",
"8",
",",
"9",
"]",
":",
"block",
"=",
"random",
".",
"choice",
"(",
"[",
"(",
"r\"\\\"\"",
",",
"r\"\\\"\"",
")",
",",
"(",
"r\"\\[\"",
",",
"r\"\\]\"",
")",
",",
"(",
"r\"\\{\"",
",",
"r\"\\}\"",
")",
"]",
")",
"b_str",
"=",
"self",
".",
"safe_join",
"(",
"b",
")",
"block_re",
"=",
"re",
".",
"compile",
"(",
"str",
"(",
"\".+({0}[^{2}{3}]+{1}).+\"",
")",
".",
"format",
"(",
"block",
"[",
"0",
"]",
",",
"block",
"[",
"1",
"]",
",",
"block",
"[",
"0",
"]",
",",
"block",
"[",
"1",
"]",
")",
")",
"if",
"block_re",
".",
"search",
"(",
"b_str",
")",
":",
"r",
"=",
"random",
".",
"choice",
"(",
"block_re",
".",
"findall",
"(",
"b_str",
")",
")",
"random_re",
"=",
"re",
".",
"compile",
"(",
"\"({0})\"",
".",
"format",
"(",
"re",
".",
"escape",
"(",
"r",
")",
")",
")",
"if",
"random_re",
".",
"search",
"(",
"b_str",
")",
":",
"if",
"action",
"==",
"8",
":",
"newarr",
"=",
"list",
"(",
"random_re",
".",
"sub",
"(",
"\"\"",
",",
"b_str",
")",
")",
"b",
"[",
":",
"]",
"=",
"newarr",
"else",
":",
"newarr",
"=",
"list",
"(",
"random_re",
".",
"sub",
"(",
"\"\\\\1\"",
"*",
"random",
".",
"randint",
"(",
"1",
",",
"10",
")",
",",
"b_str",
",",
"1",
")",
")",
"b",
"[",
":",
"]",
"=",
"newarr",
"elif",
"action",
"==",
"10",
":",
"b_str",
"=",
"self",
".",
"safe_join",
"(",
"b",
")",
"limit_choice",
"=",
"random",
".",
"choice",
"(",
"[",
"0x7FFFFFFF",
",",
"-",
"0x80000000",
",",
"0xff",
",",
"-",
"0xff",
",",
"]",
")",
"block_re",
"=",
"re",
".",
"compile",
"(",
"\"(\\-?[0-9]+)\"",
")",
"if",
"block_re",
".",
"search",
"(",
"b_str",
")",
":",
"block",
"=",
"random",
".",
"choice",
"(",
"[",
"m",
"for",
"m",
"in",
"block_re",
".",
"finditer",
"(",
"b_str",
")",
"]",
")",
"new",
"=",
"b_str",
"[",
"0",
":",
"block",
".",
"start",
"(",
")",
"]",
"+",
"str",
"(",
"int",
"(",
"block",
".",
"group",
"(",
")",
")",
"*",
"limit_choice",
")",
"+",
"b_str",
"[",
"block",
".",
"start",
"(",
")",
"+",
"len",
"(",
"block",
".",
"group",
"(",
")",
")",
":",
"]",
"b",
"[",
":",
"]",
"=",
"list",
"(",
"new",
")"
] |
f777067076f62c9ab74ffea6e90fd54402b7a1b4
|
test
|
PJFMutators.safe_unicode
|
Safely return an unicode encoded string
|
pyjfuzz/core/pjf_mutators.py
|
def safe_unicode(self, buf):
"""
Safely return an unicode encoded string
"""
tmp = ""
buf = "".join(b for b in buf)
for character in buf:
tmp += character
return tmp
|
def safe_unicode(self, buf):
"""
Safely return an unicode encoded string
"""
tmp = ""
buf = "".join(b for b in buf)
for character in buf:
tmp += character
return tmp
|
[
"Safely",
"return",
"an",
"unicode",
"encoded",
"string"
] |
mseclab/PyJFuzz
|
python
|
https://github.com/mseclab/PyJFuzz/blob/f777067076f62c9ab74ffea6e90fd54402b7a1b4/pyjfuzz/core/pjf_mutators.py#L259-L267
|
[
"def",
"safe_unicode",
"(",
"self",
",",
"buf",
")",
":",
"tmp",
"=",
"\"\"",
"buf",
"=",
"\"\"",
".",
"join",
"(",
"b",
"for",
"b",
"in",
"buf",
")",
"for",
"character",
"in",
"buf",
":",
"tmp",
"+=",
"character",
"return",
"tmp"
] |
f777067076f62c9ab74ffea6e90fd54402b7a1b4
|
test
|
PJFServer.run
|
Start the servers
|
pyjfuzz/core/pjf_server.py
|
def run(self):
"""
Start the servers
"""
route("/")(self.serve)
if self.config.html:
route("/<filepath:path>")(self.custom_html)
if self.config.fuzz_web:
self.request_checker.start()
self.httpd.start()
self.httpsd.start()
|
def run(self):
"""
Start the servers
"""
route("/")(self.serve)
if self.config.html:
route("/<filepath:path>")(self.custom_html)
if self.config.fuzz_web:
self.request_checker.start()
self.httpd.start()
self.httpsd.start()
|
[
"Start",
"the",
"servers"
] |
mseclab/PyJFuzz
|
python
|
https://github.com/mseclab/PyJFuzz/blob/f777067076f62c9ab74ffea6e90fd54402b7a1b4/pyjfuzz/core/pjf_server.py#L104-L114
|
[
"def",
"run",
"(",
"self",
")",
":",
"route",
"(",
"\"/\"",
")",
"(",
"self",
".",
"serve",
")",
"if",
"self",
".",
"config",
".",
"html",
":",
"route",
"(",
"\"/<filepath:path>\"",
")",
"(",
"self",
".",
"custom_html",
")",
"if",
"self",
".",
"config",
".",
"fuzz_web",
":",
"self",
".",
"request_checker",
".",
"start",
"(",
")",
"self",
".",
"httpd",
".",
"start",
"(",
")",
"self",
".",
"httpsd",
".",
"start",
"(",
")"
] |
f777067076f62c9ab74ffea6e90fd54402b7a1b4
|
test
|
PJFServer.stop
|
Kill the servers
|
pyjfuzz/core/pjf_server.py
|
def stop(self):
"""
Kill the servers
"""
os.kill(self.httpd.pid, signal.SIGKILL)
os.kill(self.httpsd.pid, signal.SIGKILL)
self.client_queue.put((0,0))
if self.config.fuzz_web:
self.request_checker.join()
self.logger.debug("[{0}] - PJFServer successfully completed".format(time.strftime("%H:%M:%S")))
|
def stop(self):
"""
Kill the servers
"""
os.kill(self.httpd.pid, signal.SIGKILL)
os.kill(self.httpsd.pid, signal.SIGKILL)
self.client_queue.put((0,0))
if self.config.fuzz_web:
self.request_checker.join()
self.logger.debug("[{0}] - PJFServer successfully completed".format(time.strftime("%H:%M:%S")))
|
[
"Kill",
"the",
"servers"
] |
mseclab/PyJFuzz
|
python
|
https://github.com/mseclab/PyJFuzz/blob/f777067076f62c9ab74ffea6e90fd54402b7a1b4/pyjfuzz/core/pjf_server.py#L162-L171
|
[
"def",
"stop",
"(",
"self",
")",
":",
"os",
".",
"kill",
"(",
"self",
".",
"httpd",
".",
"pid",
",",
"signal",
".",
"SIGKILL",
")",
"os",
".",
"kill",
"(",
"self",
".",
"httpsd",
".",
"pid",
",",
"signal",
".",
"SIGKILL",
")",
"self",
".",
"client_queue",
".",
"put",
"(",
"(",
"0",
",",
"0",
")",
")",
"if",
"self",
".",
"config",
".",
"fuzz_web",
":",
"self",
".",
"request_checker",
".",
"join",
"(",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"\"[{0}] - PJFServer successfully completed\"",
".",
"format",
"(",
"time",
".",
"strftime",
"(",
"\"%H:%M:%S\"",
")",
")",
")"
] |
f777067076f62c9ab74ffea6e90fd54402b7a1b4
|
test
|
PJFServer.custom_html
|
Serve custom HTML page
|
pyjfuzz/core/pjf_server.py
|
def custom_html(self, filepath):
"""
Serve custom HTML page
"""
try:
response.headers.append("Access-Control-Allow-Origin", "*")
response.headers.append("Accept-Encoding", "identity")
response.headers.append("Content-Type", "text/html")
return static_file(filepath, root=self.config.html)
except Exception as e:
raise PJFBaseException(e.message if hasattr(e, "message") else str(e))
|
def custom_html(self, filepath):
"""
Serve custom HTML page
"""
try:
response.headers.append("Access-Control-Allow-Origin", "*")
response.headers.append("Accept-Encoding", "identity")
response.headers.append("Content-Type", "text/html")
return static_file(filepath, root=self.config.html)
except Exception as e:
raise PJFBaseException(e.message if hasattr(e, "message") else str(e))
|
[
"Serve",
"custom",
"HTML",
"page"
] |
mseclab/PyJFuzz
|
python
|
https://github.com/mseclab/PyJFuzz/blob/f777067076f62c9ab74ffea6e90fd54402b7a1b4/pyjfuzz/core/pjf_server.py#L173-L183
|
[
"def",
"custom_html",
"(",
"self",
",",
"filepath",
")",
":",
"try",
":",
"response",
".",
"headers",
".",
"append",
"(",
"\"Access-Control-Allow-Origin\"",
",",
"\"*\"",
")",
"response",
".",
"headers",
".",
"append",
"(",
"\"Accept-Encoding\"",
",",
"\"identity\"",
")",
"response",
".",
"headers",
".",
"append",
"(",
"\"Content-Type\"",
",",
"\"text/html\"",
")",
"return",
"static_file",
"(",
"filepath",
",",
"root",
"=",
"self",
".",
"config",
".",
"html",
")",
"except",
"Exception",
"as",
"e",
":",
"raise",
"PJFBaseException",
"(",
"e",
".",
"message",
"if",
"hasattr",
"(",
"e",
",",
"\"message\"",
")",
"else",
"str",
"(",
"e",
")",
")"
] |
f777067076f62c9ab74ffea6e90fd54402b7a1b4
|
test
|
PJFServer.serve
|
Serve fuzzed JSON object
|
pyjfuzz/core/pjf_server.py
|
def serve(self):
"""
Serve fuzzed JSON object
"""
try:
fuzzed = self.json.fuzzed
if self.config.fuzz_web:
self.client_queue.put((request.environ.get('REMOTE_ADDR'), fuzzed))
response.headers.append("Access-Control-Allow-Origin", "*")
response.headers.append("Accept-Encoding", "identity")
response.headers.append("Content-Type", self.config.content_type)
if self.config.notify:
PJFTestcaseServer.send_testcase(fuzzed, '127.0.0.1', self.config.ports["servers"]["TCASE_PORT"])
yield fuzzed
except Exception as e:
raise PJFBaseException(e.message if hasattr(e, "message") else str(e))
|
def serve(self):
"""
Serve fuzzed JSON object
"""
try:
fuzzed = self.json.fuzzed
if self.config.fuzz_web:
self.client_queue.put((request.environ.get('REMOTE_ADDR'), fuzzed))
response.headers.append("Access-Control-Allow-Origin", "*")
response.headers.append("Accept-Encoding", "identity")
response.headers.append("Content-Type", self.config.content_type)
if self.config.notify:
PJFTestcaseServer.send_testcase(fuzzed, '127.0.0.1', self.config.ports["servers"]["TCASE_PORT"])
yield fuzzed
except Exception as e:
raise PJFBaseException(e.message if hasattr(e, "message") else str(e))
|
[
"Serve",
"fuzzed",
"JSON",
"object"
] |
mseclab/PyJFuzz
|
python
|
https://github.com/mseclab/PyJFuzz/blob/f777067076f62c9ab74ffea6e90fd54402b7a1b4/pyjfuzz/core/pjf_server.py#L185-L200
|
[
"def",
"serve",
"(",
"self",
")",
":",
"try",
":",
"fuzzed",
"=",
"self",
".",
"json",
".",
"fuzzed",
"if",
"self",
".",
"config",
".",
"fuzz_web",
":",
"self",
".",
"client_queue",
".",
"put",
"(",
"(",
"request",
".",
"environ",
".",
"get",
"(",
"'REMOTE_ADDR'",
")",
",",
"fuzzed",
")",
")",
"response",
".",
"headers",
".",
"append",
"(",
"\"Access-Control-Allow-Origin\"",
",",
"\"*\"",
")",
"response",
".",
"headers",
".",
"append",
"(",
"\"Accept-Encoding\"",
",",
"\"identity\"",
")",
"response",
".",
"headers",
".",
"append",
"(",
"\"Content-Type\"",
",",
"self",
".",
"config",
".",
"content_type",
")",
"if",
"self",
".",
"config",
".",
"notify",
":",
"PJFTestcaseServer",
".",
"send_testcase",
"(",
"fuzzed",
",",
"'127.0.0.1'",
",",
"self",
".",
"config",
".",
"ports",
"[",
"\"servers\"",
"]",
"[",
"\"TCASE_PORT\"",
"]",
")",
"yield",
"fuzzed",
"except",
"Exception",
"as",
"e",
":",
"raise",
"PJFBaseException",
"(",
"e",
".",
"message",
"if",
"hasattr",
"(",
"e",
",",
"\"message\"",
")",
"else",
"str",
"(",
"e",
")",
")"
] |
f777067076f62c9ab74ffea6e90fd54402b7a1b4
|
test
|
PJFServer.apply_patch
|
Fix default socket lib to handle client disconnection while receiving data (Broken pipe)
|
pyjfuzz/core/pjf_server.py
|
def apply_patch(self):
"""
Fix default socket lib to handle client disconnection while receiving data (Broken pipe)
"""
if sys.version_info >= (3, 0):
# No patch for python >= 3.0
pass
else:
from .patch.socket import socket as patch
socket.socket = patch
|
def apply_patch(self):
"""
Fix default socket lib to handle client disconnection while receiving data (Broken pipe)
"""
if sys.version_info >= (3, 0):
# No patch for python >= 3.0
pass
else:
from .patch.socket import socket as patch
socket.socket = patch
|
[
"Fix",
"default",
"socket",
"lib",
"to",
"handle",
"client",
"disconnection",
"while",
"receiving",
"data",
"(",
"Broken",
"pipe",
")"
] |
mseclab/PyJFuzz
|
python
|
https://github.com/mseclab/PyJFuzz/blob/f777067076f62c9ab74ffea6e90fd54402b7a1b4/pyjfuzz/core/pjf_server.py#L208-L217
|
[
"def",
"apply_patch",
"(",
"self",
")",
":",
"if",
"sys",
".",
"version_info",
">=",
"(",
"3",
",",
"0",
")",
":",
"# No patch for python >= 3.0",
"pass",
"else",
":",
"from",
".",
"patch",
".",
"socket",
"import",
"socket",
"as",
"patch",
"socket",
".",
"socket",
"=",
"patch"
] |
f777067076f62c9ab74ffea6e90fd54402b7a1b4
|
test
|
PJFMutation.fuzz
|
Generic fuzz mutator, use a decorator for the given type
|
pyjfuzz/core/pjf_mutation.py
|
def fuzz(self, obj):
"""
Generic fuzz mutator, use a decorator for the given type
"""
decorators = self.decorators
@decorators.mutate_object_decorate
def mutate():
return obj
return mutate()
|
def fuzz(self, obj):
"""
Generic fuzz mutator, use a decorator for the given type
"""
decorators = self.decorators
@decorators.mutate_object_decorate
def mutate():
return obj
return mutate()
|
[
"Generic",
"fuzz",
"mutator",
"use",
"a",
"decorator",
"for",
"the",
"given",
"type"
] |
mseclab/PyJFuzz
|
python
|
https://github.com/mseclab/PyJFuzz/blob/f777067076f62c9ab74ffea6e90fd54402b7a1b4/pyjfuzz/core/pjf_mutation.py#L35-L44
|
[
"def",
"fuzz",
"(",
"self",
",",
"obj",
")",
":",
"decorators",
"=",
"self",
".",
"decorators",
"@",
"decorators",
".",
"mutate_object_decorate",
"def",
"mutate",
"(",
")",
":",
"return",
"obj",
"return",
"mutate",
"(",
")"
] |
f777067076f62c9ab74ffea6e90fd54402b7a1b4
|
test
|
PJFExecutor.spawn
|
Spawn a new process using subprocess
|
pyjfuzz/core/pjf_executor.py
|
def spawn(self, cmd, stdin_content="", stdin=False, shell=False, timeout=2):
"""
Spawn a new process using subprocess
"""
try:
if type(cmd) != list:
raise PJFInvalidType(type(cmd), list)
if type(stdin_content) != str:
raise PJFInvalidType(type(stdin_content), str)
if type(stdin) != bool:
raise PJFInvalidType(type(stdin), bool)
self._in = stdin_content
try:
self.process = subprocess.Popen(cmd, stdout=PIPE, stderr=PIPE, stdin=PIPE, shell=shell)
self.finish_read(timeout, stdin_content, stdin)
if self.process.poll() is not None:
self.close()
except KeyboardInterrupt:
return
except OSError:
raise PJFProcessExecutionError("Binary <%s> does not exist" % cmd[0])
except Exception as e:
raise PJFBaseException(e.message if hasattr(e, "message") else str(e))
|
def spawn(self, cmd, stdin_content="", stdin=False, shell=False, timeout=2):
"""
Spawn a new process using subprocess
"""
try:
if type(cmd) != list:
raise PJFInvalidType(type(cmd), list)
if type(stdin_content) != str:
raise PJFInvalidType(type(stdin_content), str)
if type(stdin) != bool:
raise PJFInvalidType(type(stdin), bool)
self._in = stdin_content
try:
self.process = subprocess.Popen(cmd, stdout=PIPE, stderr=PIPE, stdin=PIPE, shell=shell)
self.finish_read(timeout, stdin_content, stdin)
if self.process.poll() is not None:
self.close()
except KeyboardInterrupt:
return
except OSError:
raise PJFProcessExecutionError("Binary <%s> does not exist" % cmd[0])
except Exception as e:
raise PJFBaseException(e.message if hasattr(e, "message") else str(e))
|
[
"Spawn",
"a",
"new",
"process",
"using",
"subprocess"
] |
mseclab/PyJFuzz
|
python
|
https://github.com/mseclab/PyJFuzz/blob/f777067076f62c9ab74ffea6e90fd54402b7a1b4/pyjfuzz/core/pjf_executor.py#L51-L73
|
[
"def",
"spawn",
"(",
"self",
",",
"cmd",
",",
"stdin_content",
"=",
"\"\"",
",",
"stdin",
"=",
"False",
",",
"shell",
"=",
"False",
",",
"timeout",
"=",
"2",
")",
":",
"try",
":",
"if",
"type",
"(",
"cmd",
")",
"!=",
"list",
":",
"raise",
"PJFInvalidType",
"(",
"type",
"(",
"cmd",
")",
",",
"list",
")",
"if",
"type",
"(",
"stdin_content",
")",
"!=",
"str",
":",
"raise",
"PJFInvalidType",
"(",
"type",
"(",
"stdin_content",
")",
",",
"str",
")",
"if",
"type",
"(",
"stdin",
")",
"!=",
"bool",
":",
"raise",
"PJFInvalidType",
"(",
"type",
"(",
"stdin",
")",
",",
"bool",
")",
"self",
".",
"_in",
"=",
"stdin_content",
"try",
":",
"self",
".",
"process",
"=",
"subprocess",
".",
"Popen",
"(",
"cmd",
",",
"stdout",
"=",
"PIPE",
",",
"stderr",
"=",
"PIPE",
",",
"stdin",
"=",
"PIPE",
",",
"shell",
"=",
"shell",
")",
"self",
".",
"finish_read",
"(",
"timeout",
",",
"stdin_content",
",",
"stdin",
")",
"if",
"self",
".",
"process",
".",
"poll",
"(",
")",
"is",
"not",
"None",
":",
"self",
".",
"close",
"(",
")",
"except",
"KeyboardInterrupt",
":",
"return",
"except",
"OSError",
":",
"raise",
"PJFProcessExecutionError",
"(",
"\"Binary <%s> does not exist\"",
"%",
"cmd",
"[",
"0",
"]",
")",
"except",
"Exception",
"as",
"e",
":",
"raise",
"PJFBaseException",
"(",
"e",
".",
"message",
"if",
"hasattr",
"(",
"e",
",",
"\"message\"",
")",
"else",
"str",
"(",
"e",
")",
")"
] |
f777067076f62c9ab74ffea6e90fd54402b7a1b4
|
test
|
PJFExecutor.get_output
|
Try to get output in a separate thread
|
pyjfuzz/core/pjf_executor.py
|
def get_output(self, stdin_content, stdin):
"""
Try to get output in a separate thread
"""
try:
if stdin:
if sys.version_info >= (3, 0):
self.process.stdin.write(bytes(stdin_content, "utf-8"))
else:
self.process.stdin.write(stdin_content)
self._out = self.process.communicate()[0]
except (error, IOError):
self._out = self._in
pass
|
def get_output(self, stdin_content, stdin):
"""
Try to get output in a separate thread
"""
try:
if stdin:
if sys.version_info >= (3, 0):
self.process.stdin.write(bytes(stdin_content, "utf-8"))
else:
self.process.stdin.write(stdin_content)
self._out = self.process.communicate()[0]
except (error, IOError):
self._out = self._in
pass
|
[
"Try",
"to",
"get",
"output",
"in",
"a",
"separate",
"thread"
] |
mseclab/PyJFuzz
|
python
|
https://github.com/mseclab/PyJFuzz/blob/f777067076f62c9ab74ffea6e90fd54402b7a1b4/pyjfuzz/core/pjf_executor.py#L75-L88
|
[
"def",
"get_output",
"(",
"self",
",",
"stdin_content",
",",
"stdin",
")",
":",
"try",
":",
"if",
"stdin",
":",
"if",
"sys",
".",
"version_info",
">=",
"(",
"3",
",",
"0",
")",
":",
"self",
".",
"process",
".",
"stdin",
".",
"write",
"(",
"bytes",
"(",
"stdin_content",
",",
"\"utf-8\"",
")",
")",
"else",
":",
"self",
".",
"process",
".",
"stdin",
".",
"write",
"(",
"stdin_content",
")",
"self",
".",
"_out",
"=",
"self",
".",
"process",
".",
"communicate",
"(",
")",
"[",
"0",
"]",
"except",
"(",
"error",
",",
"IOError",
")",
":",
"self",
".",
"_out",
"=",
"self",
".",
"_in",
"pass"
] |
f777067076f62c9ab74ffea6e90fd54402b7a1b4
|
test
|
PJFExecutor.finish_read
|
Wait until we got output or until timeout is over
|
pyjfuzz/core/pjf_executor.py
|
def finish_read(self, timeout=2, stdin_content="", stdin=False):
"""
Wait until we got output or until timeout is over
"""
process = Thread(target=self.get_output, args=(stdin_content, stdin))
process.start()
if timeout > 0:
process.join(timeout)
else:
process.join()
if process.is_alive():
self.close()
self.return_code = -signal.SIGHUP
else:
self.return_code = self.process.returncode
|
def finish_read(self, timeout=2, stdin_content="", stdin=False):
"""
Wait until we got output or until timeout is over
"""
process = Thread(target=self.get_output, args=(stdin_content, stdin))
process.start()
if timeout > 0:
process.join(timeout)
else:
process.join()
if process.is_alive():
self.close()
self.return_code = -signal.SIGHUP
else:
self.return_code = self.process.returncode
|
[
"Wait",
"until",
"we",
"got",
"output",
"or",
"until",
"timeout",
"is",
"over"
] |
mseclab/PyJFuzz
|
python
|
https://github.com/mseclab/PyJFuzz/blob/f777067076f62c9ab74ffea6e90fd54402b7a1b4/pyjfuzz/core/pjf_executor.py#L90-L104
|
[
"def",
"finish_read",
"(",
"self",
",",
"timeout",
"=",
"2",
",",
"stdin_content",
"=",
"\"\"",
",",
"stdin",
"=",
"False",
")",
":",
"process",
"=",
"Thread",
"(",
"target",
"=",
"self",
".",
"get_output",
",",
"args",
"=",
"(",
"stdin_content",
",",
"stdin",
")",
")",
"process",
".",
"start",
"(",
")",
"if",
"timeout",
">",
"0",
":",
"process",
".",
"join",
"(",
"timeout",
")",
"else",
":",
"process",
".",
"join",
"(",
")",
"if",
"process",
".",
"is_alive",
"(",
")",
":",
"self",
".",
"close",
"(",
")",
"self",
".",
"return_code",
"=",
"-",
"signal",
".",
"SIGHUP",
"else",
":",
"self",
".",
"return_code",
"=",
"self",
".",
"process",
".",
"returncode"
] |
f777067076f62c9ab74ffea6e90fd54402b7a1b4
|
test
|
PJFExecutor.close
|
Terminate the newly created process
|
pyjfuzz/core/pjf_executor.py
|
def close(self):
"""
Terminate the newly created process
"""
try:
self.process.terminate()
self.return_code = self.process.returncode
except OSError:
pass
self.process.stdin.close()
self.process.stdout.close()
self.process.stderr.close()
self.logger.debug("[{0}] - PJFExecutor successfully completed".format(time.strftime("%H:%M:%S")))
|
def close(self):
"""
Terminate the newly created process
"""
try:
self.process.terminate()
self.return_code = self.process.returncode
except OSError:
pass
self.process.stdin.close()
self.process.stdout.close()
self.process.stderr.close()
self.logger.debug("[{0}] - PJFExecutor successfully completed".format(time.strftime("%H:%M:%S")))
|
[
"Terminate",
"the",
"newly",
"created",
"process"
] |
mseclab/PyJFuzz
|
python
|
https://github.com/mseclab/PyJFuzz/blob/f777067076f62c9ab74ffea6e90fd54402b7a1b4/pyjfuzz/core/pjf_executor.py#L106-L118
|
[
"def",
"close",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"process",
".",
"terminate",
"(",
")",
"self",
".",
"return_code",
"=",
"self",
".",
"process",
".",
"returncode",
"except",
"OSError",
":",
"pass",
"self",
".",
"process",
".",
"stdin",
".",
"close",
"(",
")",
"self",
".",
"process",
".",
"stdout",
".",
"close",
"(",
")",
"self",
".",
"process",
".",
"stderr",
".",
"close",
"(",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"\"[{0}] - PJFExecutor successfully completed\"",
".",
"format",
"(",
"time",
".",
"strftime",
"(",
"\"%H:%M:%S\"",
")",
")",
")"
] |
f777067076f62c9ab74ffea6e90fd54402b7a1b4
|
test
|
PJFConfiguration.start
|
Parse the command line and start PyJFuzz
|
pyjfuzz/core/pjf_configuration.py
|
def start(self):
"""
Parse the command line and start PyJFuzz
"""
from .pjf_worker import PJFWorker
worker = PJFWorker(self)
if self.update_pjf:
worker.update_library()
elif self.browser_auto:
worker.browser_autopwn()
elif self.fuzz_web:
worker.web_fuzzer()
elif self.json:
if not self.web_server and not self.ext_fuzz and not self.cmd_fuzz:
worker.fuzz()
elif self.ext_fuzz:
if self.stdin:
worker.fuzz_stdin()
else:
worker.fuzz_command_line()
elif self.cmd_fuzz:
if self.stdin:
worker.fuzz_external(True)
else:
worker.fuzz_external()
else:
worker.start_http_server()
elif self.json_file:
worker.start_file_fuzz()
elif self.process_to_monitor:
worker.start_process_monitor()
|
def start(self):
"""
Parse the command line and start PyJFuzz
"""
from .pjf_worker import PJFWorker
worker = PJFWorker(self)
if self.update_pjf:
worker.update_library()
elif self.browser_auto:
worker.browser_autopwn()
elif self.fuzz_web:
worker.web_fuzzer()
elif self.json:
if not self.web_server and not self.ext_fuzz and not self.cmd_fuzz:
worker.fuzz()
elif self.ext_fuzz:
if self.stdin:
worker.fuzz_stdin()
else:
worker.fuzz_command_line()
elif self.cmd_fuzz:
if self.stdin:
worker.fuzz_external(True)
else:
worker.fuzz_external()
else:
worker.start_http_server()
elif self.json_file:
worker.start_file_fuzz()
elif self.process_to_monitor:
worker.start_process_monitor()
|
[
"Parse",
"the",
"command",
"line",
"and",
"start",
"PyJFuzz"
] |
mseclab/PyJFuzz
|
python
|
https://github.com/mseclab/PyJFuzz/blob/f777067076f62c9ab74ffea6e90fd54402b7a1b4/pyjfuzz/core/pjf_configuration.py#L125-L155
|
[
"def",
"start",
"(",
"self",
")",
":",
"from",
".",
"pjf_worker",
"import",
"PJFWorker",
"worker",
"=",
"PJFWorker",
"(",
"self",
")",
"if",
"self",
".",
"update_pjf",
":",
"worker",
".",
"update_library",
"(",
")",
"elif",
"self",
".",
"browser_auto",
":",
"worker",
".",
"browser_autopwn",
"(",
")",
"elif",
"self",
".",
"fuzz_web",
":",
"worker",
".",
"web_fuzzer",
"(",
")",
"elif",
"self",
".",
"json",
":",
"if",
"not",
"self",
".",
"web_server",
"and",
"not",
"self",
".",
"ext_fuzz",
"and",
"not",
"self",
".",
"cmd_fuzz",
":",
"worker",
".",
"fuzz",
"(",
")",
"elif",
"self",
".",
"ext_fuzz",
":",
"if",
"self",
".",
"stdin",
":",
"worker",
".",
"fuzz_stdin",
"(",
")",
"else",
":",
"worker",
".",
"fuzz_command_line",
"(",
")",
"elif",
"self",
".",
"cmd_fuzz",
":",
"if",
"self",
".",
"stdin",
":",
"worker",
".",
"fuzz_external",
"(",
"True",
")",
"else",
":",
"worker",
".",
"fuzz_external",
"(",
")",
"else",
":",
"worker",
".",
"start_http_server",
"(",
")",
"elif",
"self",
".",
"json_file",
":",
"worker",
".",
"start_file_fuzz",
"(",
")",
"elif",
"self",
".",
"process_to_monitor",
":",
"worker",
".",
"start_process_monitor",
"(",
")"
] |
f777067076f62c9ab74ffea6e90fd54402b7a1b4
|
test
|
val
|
Build the provided value, while properly handling
native Python types, :any:`gramfuzz.fields.Field` instances, and :any:`gramfuzz.fields.Field`
subclasses.
:param list pre: The prerequisites list
:returns: str
|
gramfuzz/gramfuzz/utils.py
|
def val(val, pre=None, shortest=False):
"""Build the provided value, while properly handling
native Python types, :any:`gramfuzz.fields.Field` instances, and :any:`gramfuzz.fields.Field`
subclasses.
:param list pre: The prerequisites list
:returns: str
"""
if pre is None:
pre = []
fields = gramfuzz.fields
MF = fields.MetaField
F = fields.Field
if type(val) is MF:
val = val()
if isinstance(val, F):
val = str(val.build(pre, shortest=shortest))
return str(val)
|
def val(val, pre=None, shortest=False):
"""Build the provided value, while properly handling
native Python types, :any:`gramfuzz.fields.Field` instances, and :any:`gramfuzz.fields.Field`
subclasses.
:param list pre: The prerequisites list
:returns: str
"""
if pre is None:
pre = []
fields = gramfuzz.fields
MF = fields.MetaField
F = fields.Field
if type(val) is MF:
val = val()
if isinstance(val, F):
val = str(val.build(pre, shortest=shortest))
return str(val)
|
[
"Build",
"the",
"provided",
"value",
"while",
"properly",
"handling",
"native",
"Python",
"types",
":",
"any",
":",
"gramfuzz",
".",
"fields",
".",
"Field",
"instances",
"and",
":",
"any",
":",
"gramfuzz",
".",
"fields",
".",
"Field",
"subclasses",
"."
] |
mseclab/PyJFuzz
|
python
|
https://github.com/mseclab/PyJFuzz/blob/f777067076f62c9ab74ffea6e90fd54402b7a1b4/gramfuzz/gramfuzz/utils.py#L13-L33
|
[
"def",
"val",
"(",
"val",
",",
"pre",
"=",
"None",
",",
"shortest",
"=",
"False",
")",
":",
"if",
"pre",
"is",
"None",
":",
"pre",
"=",
"[",
"]",
"fields",
"=",
"gramfuzz",
".",
"fields",
"MF",
"=",
"fields",
".",
"MetaField",
"F",
"=",
"fields",
".",
"Field",
"if",
"type",
"(",
"val",
")",
"is",
"MF",
":",
"val",
"=",
"val",
"(",
")",
"if",
"isinstance",
"(",
"val",
",",
"F",
")",
":",
"val",
"=",
"str",
"(",
"val",
".",
"build",
"(",
"pre",
",",
"shortest",
"=",
"shortest",
")",
")",
"return",
"str",
"(",
"val",
")"
] |
f777067076f62c9ab74ffea6e90fd54402b7a1b4
|
test
|
PJFExternalFuzzer.execute
|
Perform the actual external fuzzing, you may replace this method in order to increase performance
|
pyjfuzz/core/pjf_external_fuzzer.py
|
def execute(self, obj):
"""
Perform the actual external fuzzing, you may replace this method in order to increase performance
"""
try:
if self.config.stdin:
self.spawn(self.config.command, stdin_content=obj, stdin=True, timeout=1)
else:
if "@@" not in self.config.command:
raise PJFMissingArgument("Missing @@ filename indicator while using non-stdin fuzzing method")
for x in self.config.command:
if "@@" in x:
self.config.command[self.config.command.index(x)] = x.replace("@@", obj)
self.spawn(self.config.command, timeout=2)
self.logger.debug("[{0}] - PJFExternalFuzzer successfully completed".format(time.strftime("%H:%M:%S")))
return self._out
except KeyboardInterrupt:
return ""
except Exception as e:
raise PJFBaseException(e.message if hasattr(e, "message") else str(e))
|
def execute(self, obj):
"""
Perform the actual external fuzzing, you may replace this method in order to increase performance
"""
try:
if self.config.stdin:
self.spawn(self.config.command, stdin_content=obj, stdin=True, timeout=1)
else:
if "@@" not in self.config.command:
raise PJFMissingArgument("Missing @@ filename indicator while using non-stdin fuzzing method")
for x in self.config.command:
if "@@" in x:
self.config.command[self.config.command.index(x)] = x.replace("@@", obj)
self.spawn(self.config.command, timeout=2)
self.logger.debug("[{0}] - PJFExternalFuzzer successfully completed".format(time.strftime("%H:%M:%S")))
return self._out
except KeyboardInterrupt:
return ""
except Exception as e:
raise PJFBaseException(e.message if hasattr(e, "message") else str(e))
|
[
"Perform",
"the",
"actual",
"external",
"fuzzing",
"you",
"may",
"replace",
"this",
"method",
"in",
"order",
"to",
"increase",
"performance"
] |
mseclab/PyJFuzz
|
python
|
https://github.com/mseclab/PyJFuzz/blob/f777067076f62c9ab74ffea6e90fd54402b7a1b4/pyjfuzz/core/pjf_external_fuzzer.py#L53-L72
|
[
"def",
"execute",
"(",
"self",
",",
"obj",
")",
":",
"try",
":",
"if",
"self",
".",
"config",
".",
"stdin",
":",
"self",
".",
"spawn",
"(",
"self",
".",
"config",
".",
"command",
",",
"stdin_content",
"=",
"obj",
",",
"stdin",
"=",
"True",
",",
"timeout",
"=",
"1",
")",
"else",
":",
"if",
"\"@@\"",
"not",
"in",
"self",
".",
"config",
".",
"command",
":",
"raise",
"PJFMissingArgument",
"(",
"\"Missing @@ filename indicator while using non-stdin fuzzing method\"",
")",
"for",
"x",
"in",
"self",
".",
"config",
".",
"command",
":",
"if",
"\"@@\"",
"in",
"x",
":",
"self",
".",
"config",
".",
"command",
"[",
"self",
".",
"config",
".",
"command",
".",
"index",
"(",
"x",
")",
"]",
"=",
"x",
".",
"replace",
"(",
"\"@@\"",
",",
"obj",
")",
"self",
".",
"spawn",
"(",
"self",
".",
"config",
".",
"command",
",",
"timeout",
"=",
"2",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"\"[{0}] - PJFExternalFuzzer successfully completed\"",
".",
"format",
"(",
"time",
".",
"strftime",
"(",
"\"%H:%M:%S\"",
")",
")",
")",
"return",
"self",
".",
"_out",
"except",
"KeyboardInterrupt",
":",
"return",
"\"\"",
"except",
"Exception",
"as",
"e",
":",
"raise",
"PJFBaseException",
"(",
"e",
".",
"message",
"if",
"hasattr",
"(",
"e",
",",
"\"message\"",
")",
"else",
"str",
"(",
"e",
")",
")"
] |
f777067076f62c9ab74ffea6e90fd54402b7a1b4
|
test
|
PJFEncoder.json_encode
|
Decorator used to change the return value from PJFFactory.fuzzed, it makes the structure printable
|
pyjfuzz/core/pjf_encoder.py
|
def json_encode(func):
"""
Decorator used to change the return value from PJFFactory.fuzzed, it makes the structure printable
"""
def func_wrapper(self, indent, utf8):
if utf8:
encoding = "\\x%02x"
else:
encoding = "\\u%04x"
hex_regex = re.compile(r"(\\\\x[a-fA-F0-9]{2})")
unicode_regex = re.compile(r"(\\u[a-fA-F0-9]{4})")
def encode_decode_all(d, _decode=True):
if type(d) == dict:
for k in d:
if type(d[k]) in [dict, list]:
if _decode:
d[k] = encode_decode_all(d[k])
else:
d[k] = encode_decode_all(d[k], _decode=False)
elif type(d[k]) == str:
if _decode:
d[k] = decode(d[k])
else:
d[k] = encode(d[k])
elif type(d) == list:
arr = []
for e in d:
if type(e) == str:
if _decode:
arr.append(decode(e))
else:
arr.append(encode(e))
elif type(e) in [dict, list]:
if _decode:
arr.append(encode_decode_all(e))
else:
arr.append(encode_decode_all(e, _decode=False))
else:
arr.append(e)
return arr
else:
if _decode:
return decode(d)
else:
return encode(d)
return d
def decode(x):
tmp = "".join(encoding % ord(c) if c not in p else c for c in x)
if sys.version_info >= (3, 0):
return str(tmp)
else:
for encoded in unicode_regex.findall(tmp):
tmp = tmp.replace(encoded, encoded.decode("unicode_escape"))
return unicode(tmp)
def encode(x):
for encoded in hex_regex.findall(x):
if sys.version_info >= (3, 0):
x = x.replace(encoded, bytes(str(encoded).replace("\\\\x", "\\x"),"utf-8").decode("unicode_escape"))
else:
x = x.replace(encoded, str(encoded).replace("\\\\x", "\\x").decode("string_escape"))
return x
if indent:
return encode_decode_all("{0}".format(json.dumps(encode_decode_all(func(self)), indent=5)),
_decode=False)
else:
return encode_decode_all("{0}".format(json.dumps(encode_decode_all(func(self)))), _decode=False)
return func_wrapper
|
def json_encode(func):
"""
Decorator used to change the return value from PJFFactory.fuzzed, it makes the structure printable
"""
def func_wrapper(self, indent, utf8):
if utf8:
encoding = "\\x%02x"
else:
encoding = "\\u%04x"
hex_regex = re.compile(r"(\\\\x[a-fA-F0-9]{2})")
unicode_regex = re.compile(r"(\\u[a-fA-F0-9]{4})")
def encode_decode_all(d, _decode=True):
if type(d) == dict:
for k in d:
if type(d[k]) in [dict, list]:
if _decode:
d[k] = encode_decode_all(d[k])
else:
d[k] = encode_decode_all(d[k], _decode=False)
elif type(d[k]) == str:
if _decode:
d[k] = decode(d[k])
else:
d[k] = encode(d[k])
elif type(d) == list:
arr = []
for e in d:
if type(e) == str:
if _decode:
arr.append(decode(e))
else:
arr.append(encode(e))
elif type(e) in [dict, list]:
if _decode:
arr.append(encode_decode_all(e))
else:
arr.append(encode_decode_all(e, _decode=False))
else:
arr.append(e)
return arr
else:
if _decode:
return decode(d)
else:
return encode(d)
return d
def decode(x):
tmp = "".join(encoding % ord(c) if c not in p else c for c in x)
if sys.version_info >= (3, 0):
return str(tmp)
else:
for encoded in unicode_regex.findall(tmp):
tmp = tmp.replace(encoded, encoded.decode("unicode_escape"))
return unicode(tmp)
def encode(x):
for encoded in hex_regex.findall(x):
if sys.version_info >= (3, 0):
x = x.replace(encoded, bytes(str(encoded).replace("\\\\x", "\\x"),"utf-8").decode("unicode_escape"))
else:
x = x.replace(encoded, str(encoded).replace("\\\\x", "\\x").decode("string_escape"))
return x
if indent:
return encode_decode_all("{0}".format(json.dumps(encode_decode_all(func(self)), indent=5)),
_decode=False)
else:
return encode_decode_all("{0}".format(json.dumps(encode_decode_all(func(self)))), _decode=False)
return func_wrapper
|
[
"Decorator",
"used",
"to",
"change",
"the",
"return",
"value",
"from",
"PJFFactory",
".",
"fuzzed",
"it",
"makes",
"the",
"structure",
"printable"
] |
mseclab/PyJFuzz
|
python
|
https://github.com/mseclab/PyJFuzz/blob/f777067076f62c9ab74ffea6e90fd54402b7a1b4/pyjfuzz/core/pjf_encoder.py#L35-L106
|
[
"def",
"json_encode",
"(",
"func",
")",
":",
"def",
"func_wrapper",
"(",
"self",
",",
"indent",
",",
"utf8",
")",
":",
"if",
"utf8",
":",
"encoding",
"=",
"\"\\\\x%02x\"",
"else",
":",
"encoding",
"=",
"\"\\\\u%04x\"",
"hex_regex",
"=",
"re",
".",
"compile",
"(",
"r\"(\\\\\\\\x[a-fA-F0-9]{2})\"",
")",
"unicode_regex",
"=",
"re",
".",
"compile",
"(",
"r\"(\\\\u[a-fA-F0-9]{4})\"",
")",
"def",
"encode_decode_all",
"(",
"d",
",",
"_decode",
"=",
"True",
")",
":",
"if",
"type",
"(",
"d",
")",
"==",
"dict",
":",
"for",
"k",
"in",
"d",
":",
"if",
"type",
"(",
"d",
"[",
"k",
"]",
")",
"in",
"[",
"dict",
",",
"list",
"]",
":",
"if",
"_decode",
":",
"d",
"[",
"k",
"]",
"=",
"encode_decode_all",
"(",
"d",
"[",
"k",
"]",
")",
"else",
":",
"d",
"[",
"k",
"]",
"=",
"encode_decode_all",
"(",
"d",
"[",
"k",
"]",
",",
"_decode",
"=",
"False",
")",
"elif",
"type",
"(",
"d",
"[",
"k",
"]",
")",
"==",
"str",
":",
"if",
"_decode",
":",
"d",
"[",
"k",
"]",
"=",
"decode",
"(",
"d",
"[",
"k",
"]",
")",
"else",
":",
"d",
"[",
"k",
"]",
"=",
"encode",
"(",
"d",
"[",
"k",
"]",
")",
"elif",
"type",
"(",
"d",
")",
"==",
"list",
":",
"arr",
"=",
"[",
"]",
"for",
"e",
"in",
"d",
":",
"if",
"type",
"(",
"e",
")",
"==",
"str",
":",
"if",
"_decode",
":",
"arr",
".",
"append",
"(",
"decode",
"(",
"e",
")",
")",
"else",
":",
"arr",
".",
"append",
"(",
"encode",
"(",
"e",
")",
")",
"elif",
"type",
"(",
"e",
")",
"in",
"[",
"dict",
",",
"list",
"]",
":",
"if",
"_decode",
":",
"arr",
".",
"append",
"(",
"encode_decode_all",
"(",
"e",
")",
")",
"else",
":",
"arr",
".",
"append",
"(",
"encode_decode_all",
"(",
"e",
",",
"_decode",
"=",
"False",
")",
")",
"else",
":",
"arr",
".",
"append",
"(",
"e",
")",
"return",
"arr",
"else",
":",
"if",
"_decode",
":",
"return",
"decode",
"(",
"d",
")",
"else",
":",
"return",
"encode",
"(",
"d",
")",
"return",
"d",
"def",
"decode",
"(",
"x",
")",
":",
"tmp",
"=",
"\"\"",
".",
"join",
"(",
"encoding",
"%",
"ord",
"(",
"c",
")",
"if",
"c",
"not",
"in",
"p",
"else",
"c",
"for",
"c",
"in",
"x",
")",
"if",
"sys",
".",
"version_info",
">=",
"(",
"3",
",",
"0",
")",
":",
"return",
"str",
"(",
"tmp",
")",
"else",
":",
"for",
"encoded",
"in",
"unicode_regex",
".",
"findall",
"(",
"tmp",
")",
":",
"tmp",
"=",
"tmp",
".",
"replace",
"(",
"encoded",
",",
"encoded",
".",
"decode",
"(",
"\"unicode_escape\"",
")",
")",
"return",
"unicode",
"(",
"tmp",
")",
"def",
"encode",
"(",
"x",
")",
":",
"for",
"encoded",
"in",
"hex_regex",
".",
"findall",
"(",
"x",
")",
":",
"if",
"sys",
".",
"version_info",
">=",
"(",
"3",
",",
"0",
")",
":",
"x",
"=",
"x",
".",
"replace",
"(",
"encoded",
",",
"bytes",
"(",
"str",
"(",
"encoded",
")",
".",
"replace",
"(",
"\"\\\\\\\\x\"",
",",
"\"\\\\x\"",
")",
",",
"\"utf-8\"",
")",
".",
"decode",
"(",
"\"unicode_escape\"",
")",
")",
"else",
":",
"x",
"=",
"x",
".",
"replace",
"(",
"encoded",
",",
"str",
"(",
"encoded",
")",
".",
"replace",
"(",
"\"\\\\\\\\x\"",
",",
"\"\\\\x\"",
")",
".",
"decode",
"(",
"\"string_escape\"",
")",
")",
"return",
"x",
"if",
"indent",
":",
"return",
"encode_decode_all",
"(",
"\"{0}\"",
".",
"format",
"(",
"json",
".",
"dumps",
"(",
"encode_decode_all",
"(",
"func",
"(",
"self",
")",
")",
",",
"indent",
"=",
"5",
")",
")",
",",
"_decode",
"=",
"False",
")",
"else",
":",
"return",
"encode_decode_all",
"(",
"\"{0}\"",
".",
"format",
"(",
"json",
".",
"dumps",
"(",
"encode_decode_all",
"(",
"func",
"(",
"self",
")",
")",
")",
")",
",",
"_decode",
"=",
"False",
")",
"return",
"func_wrapper"
] |
f777067076f62c9ab74ffea6e90fd54402b7a1b4
|
test
|
Field._odds_val
|
Determine a new random value derived from the
defined :any:`gramfuzz.fields.Field.odds` value.
:returns: The derived value
|
gramfuzz/gramfuzz/fields.py
|
def _odds_val(self):
"""Determine a new random value derived from the
defined :any:`gramfuzz.fields.Field.odds` value.
:returns: The derived value
"""
if len(self.odds) == 0:
self.odds = [(1.00, [self.min, self.max])]
rand_val = rand.random()
total = 0
for percent,v in self.odds:
if total <= rand_val < total+percent:
found_v = v
break
total += percent
res = None
if isinstance(v, (tuple,list)):
rand_func = rand.randfloat if type(v[0]) is float else rand.randint
if len(v) == 2:
res = rand_func(v[0], v[1])
elif len(v) == 1:
res = v[0]
else:
res = v
return res
|
def _odds_val(self):
"""Determine a new random value derived from the
defined :any:`gramfuzz.fields.Field.odds` value.
:returns: The derived value
"""
if len(self.odds) == 0:
self.odds = [(1.00, [self.min, self.max])]
rand_val = rand.random()
total = 0
for percent,v in self.odds:
if total <= rand_val < total+percent:
found_v = v
break
total += percent
res = None
if isinstance(v, (tuple,list)):
rand_func = rand.randfloat if type(v[0]) is float else rand.randint
if len(v) == 2:
res = rand_func(v[0], v[1])
elif len(v) == 1:
res = v[0]
else:
res = v
return res
|
[
"Determine",
"a",
"new",
"random",
"value",
"derived",
"from",
"the",
"defined",
":",
"any",
":",
"gramfuzz",
".",
"fields",
".",
"Field",
".",
"odds",
"value",
"."
] |
mseclab/PyJFuzz
|
python
|
https://github.com/mseclab/PyJFuzz/blob/f777067076f62c9ab74ffea6e90fd54402b7a1b4/gramfuzz/gramfuzz/fields.py#L164-L192
|
[
"def",
"_odds_val",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"odds",
")",
"==",
"0",
":",
"self",
".",
"odds",
"=",
"[",
"(",
"1.00",
",",
"[",
"self",
".",
"min",
",",
"self",
".",
"max",
"]",
")",
"]",
"rand_val",
"=",
"rand",
".",
"random",
"(",
")",
"total",
"=",
"0",
"for",
"percent",
",",
"v",
"in",
"self",
".",
"odds",
":",
"if",
"total",
"<=",
"rand_val",
"<",
"total",
"+",
"percent",
":",
"found_v",
"=",
"v",
"break",
"total",
"+=",
"percent",
"res",
"=",
"None",
"if",
"isinstance",
"(",
"v",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"rand_func",
"=",
"rand",
".",
"randfloat",
"if",
"type",
"(",
"v",
"[",
"0",
"]",
")",
"is",
"float",
"else",
"rand",
".",
"randint",
"if",
"len",
"(",
"v",
")",
"==",
"2",
":",
"res",
"=",
"rand_func",
"(",
"v",
"[",
"0",
"]",
",",
"v",
"[",
"1",
"]",
")",
"elif",
"len",
"(",
"v",
")",
"==",
"1",
":",
"res",
"=",
"v",
"[",
"0",
"]",
"else",
":",
"res",
"=",
"v",
"return",
"res"
] |
f777067076f62c9ab74ffea6e90fd54402b7a1b4
|
test
|
Int.build
|
Build the integer, optionally providing a ``pre`` list
that *may* be used to define prerequisites for a Field being built.
:param list pre: A list of prerequisites to be collected during the building of a Field.
:param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated.
|
gramfuzz/gramfuzz/fields.py
|
def build(self, pre=None, shortest=False):
"""Build the integer, optionally providing a ``pre`` list
that *may* be used to define prerequisites for a Field being built.
:param list pre: A list of prerequisites to be collected during the building of a Field.
:param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated.
"""
if pre is None:
pre = []
if self.value is not None and rand.maybe():
return utils.val(self.value, pre, shortest=shortest)
if self.min == self.max:
return self.min
res = self._odds_val()
if self.neg and rand.maybe():
res = -res
return res
|
def build(self, pre=None, shortest=False):
"""Build the integer, optionally providing a ``pre`` list
that *may* be used to define prerequisites for a Field being built.
:param list pre: A list of prerequisites to be collected during the building of a Field.
:param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated.
"""
if pre is None:
pre = []
if self.value is not None and rand.maybe():
return utils.val(self.value, pre, shortest=shortest)
if self.min == self.max:
return self.min
res = self._odds_val()
if self.neg and rand.maybe():
res = -res
return res
|
[
"Build",
"the",
"integer",
"optionally",
"providing",
"a",
"pre",
"list",
"that",
"*",
"may",
"*",
"be",
"used",
"to",
"define",
"prerequisites",
"for",
"a",
"Field",
"being",
"built",
"."
] |
mseclab/PyJFuzz
|
python
|
https://github.com/mseclab/PyJFuzz/blob/f777067076f62c9ab74ffea6e90fd54402b7a1b4/gramfuzz/gramfuzz/fields.py#L239-L258
|
[
"def",
"build",
"(",
"self",
",",
"pre",
"=",
"None",
",",
"shortest",
"=",
"False",
")",
":",
"if",
"pre",
"is",
"None",
":",
"pre",
"=",
"[",
"]",
"if",
"self",
".",
"value",
"is",
"not",
"None",
"and",
"rand",
".",
"maybe",
"(",
")",
":",
"return",
"utils",
".",
"val",
"(",
"self",
".",
"value",
",",
"pre",
",",
"shortest",
"=",
"shortest",
")",
"if",
"self",
".",
"min",
"==",
"self",
".",
"max",
":",
"return",
"self",
".",
"min",
"res",
"=",
"self",
".",
"_odds_val",
"(",
")",
"if",
"self",
".",
"neg",
"and",
"rand",
".",
"maybe",
"(",
")",
":",
"res",
"=",
"-",
"res",
"return",
"res"
] |
f777067076f62c9ab74ffea6e90fd54402b7a1b4
|
test
|
String.build
|
Build the String instance
:param list pre: The prerequisites list (optional, default=None)
:param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated.
|
gramfuzz/gramfuzz/fields.py
|
def build(self, pre=None, shortest=False):
"""Build the String instance
:param list pre: The prerequisites list (optional, default=None)
:param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated.
"""
if pre is None:
pre = []
if self.value is not None and rand.maybe():
return utils.val(self.value, pre, shortest=shortest)
length = super(String, self).build(pre, shortest=shortest)
res = rand.data(length, self.charset)
return res
|
def build(self, pre=None, shortest=False):
"""Build the String instance
:param list pre: The prerequisites list (optional, default=None)
:param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated.
"""
if pre is None:
pre = []
if self.value is not None and rand.maybe():
return utils.val(self.value, pre, shortest=shortest)
length = super(String, self).build(pre, shortest=shortest)
res = rand.data(length, self.charset)
return res
|
[
"Build",
"the",
"String",
"instance"
] |
mseclab/PyJFuzz
|
python
|
https://github.com/mseclab/PyJFuzz/blob/f777067076f62c9ab74ffea6e90fd54402b7a1b4/gramfuzz/gramfuzz/fields.py#L346-L360
|
[
"def",
"build",
"(",
"self",
",",
"pre",
"=",
"None",
",",
"shortest",
"=",
"False",
")",
":",
"if",
"pre",
"is",
"None",
":",
"pre",
"=",
"[",
"]",
"if",
"self",
".",
"value",
"is",
"not",
"None",
"and",
"rand",
".",
"maybe",
"(",
")",
":",
"return",
"utils",
".",
"val",
"(",
"self",
".",
"value",
",",
"pre",
",",
"shortest",
"=",
"shortest",
")",
"length",
"=",
"super",
"(",
"String",
",",
"self",
")",
".",
"build",
"(",
"pre",
",",
"shortest",
"=",
"shortest",
")",
"res",
"=",
"rand",
".",
"data",
"(",
"length",
",",
"self",
".",
"charset",
")",
"return",
"res"
] |
f777067076f62c9ab74ffea6e90fd54402b7a1b4
|
test
|
Join.build
|
Build the ``Join`` field instance.
:param list pre: The prerequisites list
:param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated.
|
gramfuzz/gramfuzz/fields.py
|
def build(self, pre=None, shortest=False):
"""Build the ``Join`` field instance.
:param list pre: The prerequisites list
:param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated.
"""
if pre is None:
pre = []
if self.max is not None:
if shortest:
vals = [self.values[0]]
else:
# +1 to make it inclusive
vals = [self.values[0]] * rand.randint(1, self.max+1)
else:
vals = self.values
joins = []
for val in vals:
try:
v = utils.val(val, pre, shortest=shortest)
joins.append(v)
except errors.OptGram as e:
continue
return self.sep.join(joins)
|
def build(self, pre=None, shortest=False):
"""Build the ``Join`` field instance.
:param list pre: The prerequisites list
:param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated.
"""
if pre is None:
pre = []
if self.max is not None:
if shortest:
vals = [self.values[0]]
else:
# +1 to make it inclusive
vals = [self.values[0]] * rand.randint(1, self.max+1)
else:
vals = self.values
joins = []
for val in vals:
try:
v = utils.val(val, pre, shortest=shortest)
joins.append(v)
except errors.OptGram as e:
continue
return self.sep.join(joins)
|
[
"Build",
"the",
"Join",
"field",
"instance",
".",
":",
"param",
"list",
"pre",
":",
"The",
"prerequisites",
"list",
":",
"param",
"bool",
"shortest",
":",
"Whether",
"or",
"not",
"the",
"shortest",
"reference",
"-",
"chain",
"(",
"most",
"minimal",
")",
"version",
"of",
"the",
"field",
"should",
"be",
"generated",
"."
] |
mseclab/PyJFuzz
|
python
|
https://github.com/mseclab/PyJFuzz/blob/f777067076f62c9ab74ffea6e90fd54402b7a1b4/gramfuzz/gramfuzz/fields.py#L385-L411
|
[
"def",
"build",
"(",
"self",
",",
"pre",
"=",
"None",
",",
"shortest",
"=",
"False",
")",
":",
"if",
"pre",
"is",
"None",
":",
"pre",
"=",
"[",
"]",
"if",
"self",
".",
"max",
"is",
"not",
"None",
":",
"if",
"shortest",
":",
"vals",
"=",
"[",
"self",
".",
"values",
"[",
"0",
"]",
"]",
"else",
":",
"# +1 to make it inclusive",
"vals",
"=",
"[",
"self",
".",
"values",
"[",
"0",
"]",
"]",
"*",
"rand",
".",
"randint",
"(",
"1",
",",
"self",
".",
"max",
"+",
"1",
")",
"else",
":",
"vals",
"=",
"self",
".",
"values",
"joins",
"=",
"[",
"]",
"for",
"val",
"in",
"vals",
":",
"try",
":",
"v",
"=",
"utils",
".",
"val",
"(",
"val",
",",
"pre",
",",
"shortest",
"=",
"shortest",
")",
"joins",
".",
"append",
"(",
"v",
")",
"except",
"errors",
".",
"OptGram",
"as",
"e",
":",
"continue",
"return",
"self",
".",
"sep",
".",
"join",
"(",
"joins",
")"
] |
f777067076f62c9ab74ffea6e90fd54402b7a1b4
|
test
|
And.build
|
Build the ``And`` instance
:param list pre: The prerequisites list
:param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated.
|
gramfuzz/gramfuzz/fields.py
|
def build(self, pre=None, shortest=False):
"""Build the ``And`` instance
:param list pre: The prerequisites list
:param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated.
"""
if pre is None:
pre = []
res = deque()
for x in self.values:
try:
res.append(utils.val(x, pre, shortest=shortest))
except errors.OptGram as e:
continue
except errors.FlushGrams as e:
prev = "".join(res)
res.clear()
# this is assuming a scope was pushed!
if len(self.fuzzer._scope_stack) == 1:
pre.append(prev)
else:
stmts = self.fuzzer._curr_scope.setdefault("prev_append", deque())
stmts.extend(pre)
stmts.append(prev)
pre.clear()
continue
return self.sep.join(res)
|
def build(self, pre=None, shortest=False):
"""Build the ``And`` instance
:param list pre: The prerequisites list
:param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated.
"""
if pre is None:
pre = []
res = deque()
for x in self.values:
try:
res.append(utils.val(x, pre, shortest=shortest))
except errors.OptGram as e:
continue
except errors.FlushGrams as e:
prev = "".join(res)
res.clear()
# this is assuming a scope was pushed!
if len(self.fuzzer._scope_stack) == 1:
pre.append(prev)
else:
stmts = self.fuzzer._curr_scope.setdefault("prev_append", deque())
stmts.extend(pre)
stmts.append(prev)
pre.clear()
continue
return self.sep.join(res)
|
[
"Build",
"the",
"And",
"instance"
] |
mseclab/PyJFuzz
|
python
|
https://github.com/mseclab/PyJFuzz/blob/f777067076f62c9ab74ffea6e90fd54402b7a1b4/gramfuzz/gramfuzz/fields.py#L432-L460
|
[
"def",
"build",
"(",
"self",
",",
"pre",
"=",
"None",
",",
"shortest",
"=",
"False",
")",
":",
"if",
"pre",
"is",
"None",
":",
"pre",
"=",
"[",
"]",
"res",
"=",
"deque",
"(",
")",
"for",
"x",
"in",
"self",
".",
"values",
":",
"try",
":",
"res",
".",
"append",
"(",
"utils",
".",
"val",
"(",
"x",
",",
"pre",
",",
"shortest",
"=",
"shortest",
")",
")",
"except",
"errors",
".",
"OptGram",
"as",
"e",
":",
"continue",
"except",
"errors",
".",
"FlushGrams",
"as",
"e",
":",
"prev",
"=",
"\"\"",
".",
"join",
"(",
"res",
")",
"res",
".",
"clear",
"(",
")",
"# this is assuming a scope was pushed!",
"if",
"len",
"(",
"self",
".",
"fuzzer",
".",
"_scope_stack",
")",
"==",
"1",
":",
"pre",
".",
"append",
"(",
"prev",
")",
"else",
":",
"stmts",
"=",
"self",
".",
"fuzzer",
".",
"_curr_scope",
".",
"setdefault",
"(",
"\"prev_append\"",
",",
"deque",
"(",
")",
")",
"stmts",
".",
"extend",
"(",
"pre",
")",
"stmts",
".",
"append",
"(",
"prev",
")",
"pre",
".",
"clear",
"(",
")",
"continue",
"return",
"self",
".",
"sep",
".",
"join",
"(",
"res",
")"
] |
f777067076f62c9ab74ffea6e90fd54402b7a1b4
|
test
|
Q.build
|
Build the ``Quote`` instance
:param list pre: The prerequisites list
:param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated.
|
gramfuzz/gramfuzz/fields.py
|
def build(self, pre=None, shortest=False):
"""Build the ``Quote`` instance
:param list pre: The prerequisites list
:param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated.
"""
res = super(Q, self).build(pre, shortest=shortest)
if self.escape:
return repr(res)
elif self.html_js_escape:
return ("'" + res.encode("string_escape").replace("<", "\\x3c").replace(">", "\\x3e") + "'")
else:
return "{q}{r}{q}".format(q=self.quote, r=res)
|
def build(self, pre=None, shortest=False):
"""Build the ``Quote`` instance
:param list pre: The prerequisites list
:param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated.
"""
res = super(Q, self).build(pre, shortest=shortest)
if self.escape:
return repr(res)
elif self.html_js_escape:
return ("'" + res.encode("string_escape").replace("<", "\\x3c").replace(">", "\\x3e") + "'")
else:
return "{q}{r}{q}".format(q=self.quote, r=res)
|
[
"Build",
"the",
"Quote",
"instance"
] |
mseclab/PyJFuzz
|
python
|
https://github.com/mseclab/PyJFuzz/blob/f777067076f62c9ab74ffea6e90fd54402b7a1b4/gramfuzz/gramfuzz/fields.py#L491-L504
|
[
"def",
"build",
"(",
"self",
",",
"pre",
"=",
"None",
",",
"shortest",
"=",
"False",
")",
":",
"res",
"=",
"super",
"(",
"Q",
",",
"self",
")",
".",
"build",
"(",
"pre",
",",
"shortest",
"=",
"shortest",
")",
"if",
"self",
".",
"escape",
":",
"return",
"repr",
"(",
"res",
")",
"elif",
"self",
".",
"html_js_escape",
":",
"return",
"(",
"\"'\"",
"+",
"res",
".",
"encode",
"(",
"\"string_escape\"",
")",
".",
"replace",
"(",
"\"<\"",
",",
"\"\\\\x3c\"",
")",
".",
"replace",
"(",
"\">\"",
",",
"\"\\\\x3e\"",
")",
"+",
"\"'\"",
")",
"else",
":",
"return",
"\"{q}{r}{q}\"",
".",
"format",
"(",
"q",
"=",
"self",
".",
"quote",
",",
"r",
"=",
"res",
")"
] |
f777067076f62c9ab74ffea6e90fd54402b7a1b4
|
test
|
Or.build
|
Build the ``Or`` instance
:param list pre: The prerequisites list
:param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated.
|
gramfuzz/gramfuzz/fields.py
|
def build(self, pre=None, shortest=False):
"""Build the ``Or`` instance
:param list pre: The prerequisites list
:param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated.
"""
if pre is None:
pre = []
# self.shortest_vals will be set by the GramFuzzer and will
# contain a list of value options that have a minimal reference
# chain
if shortest and self.shortest_vals is not None:
return utils.val(rand.choice(self.shortest_vals), pre, shortest=shortest)
else:
return utils.val(rand.choice(self.values), pre, shortest=shortest)
|
def build(self, pre=None, shortest=False):
"""Build the ``Or`` instance
:param list pre: The prerequisites list
:param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated.
"""
if pre is None:
pre = []
# self.shortest_vals will be set by the GramFuzzer and will
# contain a list of value options that have a minimal reference
# chain
if shortest and self.shortest_vals is not None:
return utils.val(rand.choice(self.shortest_vals), pre, shortest=shortest)
else:
return utils.val(rand.choice(self.values), pre, shortest=shortest)
|
[
"Build",
"the",
"Or",
"instance"
] |
mseclab/PyJFuzz
|
python
|
https://github.com/mseclab/PyJFuzz/blob/f777067076f62c9ab74ffea6e90fd54402b7a1b4/gramfuzz/gramfuzz/fields.py#L526-L541
|
[
"def",
"build",
"(",
"self",
",",
"pre",
"=",
"None",
",",
"shortest",
"=",
"False",
")",
":",
"if",
"pre",
"is",
"None",
":",
"pre",
"=",
"[",
"]",
"# self.shortest_vals will be set by the GramFuzzer and will",
"# contain a list of value options that have a minimal reference",
"# chain",
"if",
"shortest",
"and",
"self",
".",
"shortest_vals",
"is",
"not",
"None",
":",
"return",
"utils",
".",
"val",
"(",
"rand",
".",
"choice",
"(",
"self",
".",
"shortest_vals",
")",
",",
"pre",
",",
"shortest",
"=",
"shortest",
")",
"else",
":",
"return",
"utils",
".",
"val",
"(",
"rand",
".",
"choice",
"(",
"self",
".",
"values",
")",
",",
"pre",
",",
"shortest",
"=",
"shortest",
")"
] |
f777067076f62c9ab74ffea6e90fd54402b7a1b4
|
test
|
Opt.build
|
Build the current ``Opt`` instance
:param list pre: The prerequisites list
:param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated.
|
gramfuzz/gramfuzz/fields.py
|
def build(self, pre=None, shortest=False):
"""Build the current ``Opt`` instance
:param list pre: The prerequisites list
:param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated.
"""
if pre is None:
pre = []
if shortest or rand.maybe(self.prob):
raise errors.OptGram
return super(Opt, self).build(pre, shortest=shortest)
|
def build(self, pre=None, shortest=False):
"""Build the current ``Opt`` instance
:param list pre: The prerequisites list
:param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated.
"""
if pre is None:
pre = []
if shortest or rand.maybe(self.prob):
raise errors.OptGram
return super(Opt, self).build(pre, shortest=shortest)
|
[
"Build",
"the",
"current",
"Opt",
"instance"
] |
mseclab/PyJFuzz
|
python
|
https://github.com/mseclab/PyJFuzz/blob/f777067076f62c9ab74ffea6e90fd54402b7a1b4/gramfuzz/gramfuzz/fields.py#L570-L582
|
[
"def",
"build",
"(",
"self",
",",
"pre",
"=",
"None",
",",
"shortest",
"=",
"False",
")",
":",
"if",
"pre",
"is",
"None",
":",
"pre",
"=",
"[",
"]",
"if",
"shortest",
"or",
"rand",
".",
"maybe",
"(",
"self",
".",
"prob",
")",
":",
"raise",
"errors",
".",
"OptGram",
"return",
"super",
"(",
"Opt",
",",
"self",
")",
".",
"build",
"(",
"pre",
",",
"shortest",
"=",
"shortest",
")"
] |
f777067076f62c9ab74ffea6e90fd54402b7a1b4
|
test
|
Def.build
|
Build this rule definition
:param list pre: The prerequisites list
:param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated.
|
gramfuzz/gramfuzz/fields.py
|
def build(self, pre=None, shortest=False):
"""Build this rule definition
:param list pre: The prerequisites list
:param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated.
"""
if pre is None:
pre = []
res = deque()
for value in self.values:
try:
res.append(utils.val(value, pre, shortest=shortest))
except errors.FlushGrams as e:
prev = "".join(res)
res.clear()
# this is assuming a scope was pushed!
if len(self.fuzzer._scope_stack) == 1:
pre.append(prev)
else:
stmts = self.fuzzer._curr_scope.setdefault("prev_append", deque())
stmts.extend(pre)
stmts.append(prev)
pre.clear()
continue
except errors.OptGram as e:
continue
except errors.GramFuzzError as e:
print("{} : {}".format(self.name, str(e)))
raise
return self.sep.join(res)
|
def build(self, pre=None, shortest=False):
"""Build this rule definition
:param list pre: The prerequisites list
:param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated.
"""
if pre is None:
pre = []
res = deque()
for value in self.values:
try:
res.append(utils.val(value, pre, shortest=shortest))
except errors.FlushGrams as e:
prev = "".join(res)
res.clear()
# this is assuming a scope was pushed!
if len(self.fuzzer._scope_stack) == 1:
pre.append(prev)
else:
stmts = self.fuzzer._curr_scope.setdefault("prev_append", deque())
stmts.extend(pre)
stmts.append(prev)
pre.clear()
continue
except errors.OptGram as e:
continue
except errors.GramFuzzError as e:
print("{} : {}".format(self.name, str(e)))
raise
return self.sep.join(res)
|
[
"Build",
"this",
"rule",
"definition",
":",
"param",
"list",
"pre",
":",
"The",
"prerequisites",
"list",
":",
"param",
"bool",
"shortest",
":",
"Whether",
"or",
"not",
"the",
"shortest",
"reference",
"-",
"chain",
"(",
"most",
"minimal",
")",
"version",
"of",
"the",
"field",
"should",
"be",
"generated",
"."
] |
mseclab/PyJFuzz
|
python
|
https://github.com/mseclab/PyJFuzz/blob/f777067076f62c9ab74ffea6e90fd54402b7a1b4/gramfuzz/gramfuzz/fields.py#L654-L685
|
[
"def",
"build",
"(",
"self",
",",
"pre",
"=",
"None",
",",
"shortest",
"=",
"False",
")",
":",
"if",
"pre",
"is",
"None",
":",
"pre",
"=",
"[",
"]",
"res",
"=",
"deque",
"(",
")",
"for",
"value",
"in",
"self",
".",
"values",
":",
"try",
":",
"res",
".",
"append",
"(",
"utils",
".",
"val",
"(",
"value",
",",
"pre",
",",
"shortest",
"=",
"shortest",
")",
")",
"except",
"errors",
".",
"FlushGrams",
"as",
"e",
":",
"prev",
"=",
"\"\"",
".",
"join",
"(",
"res",
")",
"res",
".",
"clear",
"(",
")",
"# this is assuming a scope was pushed!",
"if",
"len",
"(",
"self",
".",
"fuzzer",
".",
"_scope_stack",
")",
"==",
"1",
":",
"pre",
".",
"append",
"(",
"prev",
")",
"else",
":",
"stmts",
"=",
"self",
".",
"fuzzer",
".",
"_curr_scope",
".",
"setdefault",
"(",
"\"prev_append\"",
",",
"deque",
"(",
")",
")",
"stmts",
".",
"extend",
"(",
"pre",
")",
"stmts",
".",
"append",
"(",
"prev",
")",
"pre",
".",
"clear",
"(",
")",
"continue",
"except",
"errors",
".",
"OptGram",
"as",
"e",
":",
"continue",
"except",
"errors",
".",
"GramFuzzError",
"as",
"e",
":",
"print",
"(",
"\"{} : {}\"",
".",
"format",
"(",
"self",
".",
"name",
",",
"str",
"(",
"e",
")",
")",
")",
"raise",
"return",
"self",
".",
"sep",
".",
"join",
"(",
"res",
")"
] |
f777067076f62c9ab74ffea6e90fd54402b7a1b4
|
test
|
Ref.build
|
Build the ``Ref`` instance by fetching the rule from
the GramFuzzer instance and building it
:param list pre: The prerequisites list
:param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated.
|
gramfuzz/gramfuzz/fields.py
|
def build(self, pre=None, shortest=False):
"""Build the ``Ref`` instance by fetching the rule from
the GramFuzzer instance and building it
:param list pre: The prerequisites list
:param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated.
"""
global REF_LEVEL
REF_LEVEL += 1
try:
if pre is None:
pre = []
#print("{:04d} - {} - {}:{}".format(REF_LEVEL, shortest, self.cat, self.refname))
definition = self.fuzzer.get_ref(self.cat, self.refname)
res = utils.val(
definition,
pre,
shortest=(shortest or REF_LEVEL >= self.max_recursion)
)
return res
# this needs to happen no matter what
finally:
REF_LEVEL -= 1
|
def build(self, pre=None, shortest=False):
"""Build the ``Ref`` instance by fetching the rule from
the GramFuzzer instance and building it
:param list pre: The prerequisites list
:param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated.
"""
global REF_LEVEL
REF_LEVEL += 1
try:
if pre is None:
pre = []
#print("{:04d} - {} - {}:{}".format(REF_LEVEL, shortest, self.cat, self.refname))
definition = self.fuzzer.get_ref(self.cat, self.refname)
res = utils.val(
definition,
pre,
shortest=(shortest or REF_LEVEL >= self.max_recursion)
)
return res
# this needs to happen no matter what
finally:
REF_LEVEL -= 1
|
[
"Build",
"the",
"Ref",
"instance",
"by",
"fetching",
"the",
"rule",
"from",
"the",
"GramFuzzer",
"instance",
"and",
"building",
"it"
] |
mseclab/PyJFuzz
|
python
|
https://github.com/mseclab/PyJFuzz/blob/f777067076f62c9ab74ffea6e90fd54402b7a1b4/gramfuzz/gramfuzz/fields.py#L726-L753
|
[
"def",
"build",
"(",
"self",
",",
"pre",
"=",
"None",
",",
"shortest",
"=",
"False",
")",
":",
"global",
"REF_LEVEL",
"REF_LEVEL",
"+=",
"1",
"try",
":",
"if",
"pre",
"is",
"None",
":",
"pre",
"=",
"[",
"]",
"#print(\"{:04d} - {} - {}:{}\".format(REF_LEVEL, shortest, self.cat, self.refname))",
"definition",
"=",
"self",
".",
"fuzzer",
".",
"get_ref",
"(",
"self",
".",
"cat",
",",
"self",
".",
"refname",
")",
"res",
"=",
"utils",
".",
"val",
"(",
"definition",
",",
"pre",
",",
"shortest",
"=",
"(",
"shortest",
"or",
"REF_LEVEL",
">=",
"self",
".",
"max_recursion",
")",
")",
"return",
"res",
"# this needs to happen no matter what",
"finally",
":",
"REF_LEVEL",
"-=",
"1"
] |
f777067076f62c9ab74ffea6e90fd54402b7a1b4
|
test
|
STAR.build
|
Build the STAR field.
:param list pre: The prerequisites list
:param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated.
|
gramfuzz/gramfuzz/fields.py
|
def build(self, pre=None, shortest=False):
"""Build the STAR field.
:param list pre: The prerequisites list
:param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated.
"""
if pre is None:
pre = []
if shortest:
raise errors.OptGram
elif rand.maybe():
return super(STAR, self).build(pre, shortest=shortest)
else:
raise errors.OptGram
|
def build(self, pre=None, shortest=False):
"""Build the STAR field.
:param list pre: The prerequisites list
:param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated.
"""
if pre is None:
pre = []
if shortest:
raise errors.OptGram
elif rand.maybe():
return super(STAR, self).build(pre, shortest=shortest)
else:
raise errors.OptGram
|
[
"Build",
"the",
"STAR",
"field",
"."
] |
mseclab/PyJFuzz
|
python
|
https://github.com/mseclab/PyJFuzz/blob/f777067076f62c9ab74ffea6e90fd54402b7a1b4/gramfuzz/gramfuzz/fields.py#L785-L799
|
[
"def",
"build",
"(",
"self",
",",
"pre",
"=",
"None",
",",
"shortest",
"=",
"False",
")",
":",
"if",
"pre",
"is",
"None",
":",
"pre",
"=",
"[",
"]",
"if",
"shortest",
":",
"raise",
"errors",
".",
"OptGram",
"elif",
"rand",
".",
"maybe",
"(",
")",
":",
"return",
"super",
"(",
"STAR",
",",
"self",
")",
".",
"build",
"(",
"pre",
",",
"shortest",
"=",
"shortest",
")",
"else",
":",
"raise",
"errors",
".",
"OptGram"
] |
f777067076f62c9ab74ffea6e90fd54402b7a1b4
|
test
|
PJFProcessMonitor.shutdown
|
Shutdown the running process and the monitor
|
pyjfuzz/core/pjf_process_monitor.py
|
def shutdown(self, *args):
"""
Shutdown the running process and the monitor
"""
try:
self._shutdown()
if self.process:
self.process.wait()
self.process.stdout.close()
self.process.stdin.close()
self.process.stderr.close()
self.finished = True
self.send_testcase('', '127.0.0.1', self.config.ports["servers"]["TCASE_PORT"])
self.logger.debug("[{0}] - PJFProcessMonitor successfully completed".format(time.strftime("%H:%M:%S")))
except Exception as e:
raise PJFBaseException(e.message if hasattr(e, "message") else str(e))
|
def shutdown(self, *args):
"""
Shutdown the running process and the monitor
"""
try:
self._shutdown()
if self.process:
self.process.wait()
self.process.stdout.close()
self.process.stdin.close()
self.process.stderr.close()
self.finished = True
self.send_testcase('', '127.0.0.1', self.config.ports["servers"]["TCASE_PORT"])
self.logger.debug("[{0}] - PJFProcessMonitor successfully completed".format(time.strftime("%H:%M:%S")))
except Exception as e:
raise PJFBaseException(e.message if hasattr(e, "message") else str(e))
|
[
"Shutdown",
"the",
"running",
"process",
"and",
"the",
"monitor"
] |
mseclab/PyJFuzz
|
python
|
https://github.com/mseclab/PyJFuzz/blob/f777067076f62c9ab74ffea6e90fd54402b7a1b4/pyjfuzz/core/pjf_process_monitor.py#L56-L71
|
[
"def",
"shutdown",
"(",
"self",
",",
"*",
"args",
")",
":",
"try",
":",
"self",
".",
"_shutdown",
"(",
")",
"if",
"self",
".",
"process",
":",
"self",
".",
"process",
".",
"wait",
"(",
")",
"self",
".",
"process",
".",
"stdout",
".",
"close",
"(",
")",
"self",
".",
"process",
".",
"stdin",
".",
"close",
"(",
")",
"self",
".",
"process",
".",
"stderr",
".",
"close",
"(",
")",
"self",
".",
"finished",
"=",
"True",
"self",
".",
"send_testcase",
"(",
"''",
",",
"'127.0.0.1'",
",",
"self",
".",
"config",
".",
"ports",
"[",
"\"servers\"",
"]",
"[",
"\"TCASE_PORT\"",
"]",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"\"[{0}] - PJFProcessMonitor successfully completed\"",
".",
"format",
"(",
"time",
".",
"strftime",
"(",
"\"%H:%M:%S\"",
")",
")",
")",
"except",
"Exception",
"as",
"e",
":",
"raise",
"PJFBaseException",
"(",
"e",
".",
"message",
"if",
"hasattr",
"(",
"e",
",",
"\"message\"",
")",
"else",
"str",
"(",
"e",
")",
")"
] |
f777067076f62c9ab74ffea6e90fd54402b7a1b4
|
test
|
PJFProcessMonitor.run_and_monitor
|
Run command once and check exit code
|
pyjfuzz/core/pjf_process_monitor.py
|
def run_and_monitor(self):
"""
Run command once and check exit code
"""
signal.signal(signal.SIGINT, self.shutdown)
self.spawn(self.config.process_to_monitor, timeout=0)
return self._is_sigsegv(self.return_code)
|
def run_and_monitor(self):
"""
Run command once and check exit code
"""
signal.signal(signal.SIGINT, self.shutdown)
self.spawn(self.config.process_to_monitor, timeout=0)
return self._is_sigsegv(self.return_code)
|
[
"Run",
"command",
"once",
"and",
"check",
"exit",
"code"
] |
mseclab/PyJFuzz
|
python
|
https://github.com/mseclab/PyJFuzz/blob/f777067076f62c9ab74ffea6e90fd54402b7a1b4/pyjfuzz/core/pjf_process_monitor.py#L93-L99
|
[
"def",
"run_and_monitor",
"(",
"self",
")",
":",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGINT",
",",
"self",
".",
"shutdown",
")",
"self",
".",
"spawn",
"(",
"self",
".",
"config",
".",
"process_to_monitor",
",",
"timeout",
"=",
"0",
")",
"return",
"self",
".",
"_is_sigsegv",
"(",
"self",
".",
"return_code",
")"
] |
f777067076f62c9ab74ffea6e90fd54402b7a1b4
|
test
|
PJFProcessMonitor.start_monitor
|
Run command in a loop and check exit status plus restart process when needed
|
pyjfuzz/core/pjf_process_monitor.py
|
def start_monitor(self, standalone=True):
"""
Run command in a loop and check exit status plus restart process when needed
"""
try:
self.start()
cmdline = shlex.split(self.config.process_to_monitor)
if standalone:
signal.signal(signal.SIGINT, self.shutdown)
self.process = subprocess.Popen(cmdline, stdin=PIPE, stdout=PIPE, stderr=PIPE)
while self.process and not self.finished:
self.process.wait()
if self._is_sigsegv(self.process.returncode):
if self.config.debug:
print("[\033[92mINFO\033[0m] Process crashed with \033[91mSIGSEGV\033[0m, waiting for testcase...")
while not self.got_testcase():
time.sleep(1)
self.save_testcase(self.testcase[-10:]) # just take last 10 testcases
if self.process:
self.process = subprocess.Popen(cmdline, stdin=PIPE, stdout=PIPE, stderr=PIPE)
except OSError:
self.shutdown()
self.process = False
self.got_testcase = lambda: True
raise PJFProcessExecutionError("Binary <%s> does not exist" % cmdline[0])
except Exception as e:
raise PJFBaseException("Unknown error please send log to author")
|
def start_monitor(self, standalone=True):
"""
Run command in a loop and check exit status plus restart process when needed
"""
try:
self.start()
cmdline = shlex.split(self.config.process_to_monitor)
if standalone:
signal.signal(signal.SIGINT, self.shutdown)
self.process = subprocess.Popen(cmdline, stdin=PIPE, stdout=PIPE, stderr=PIPE)
while self.process and not self.finished:
self.process.wait()
if self._is_sigsegv(self.process.returncode):
if self.config.debug:
print("[\033[92mINFO\033[0m] Process crashed with \033[91mSIGSEGV\033[0m, waiting for testcase...")
while not self.got_testcase():
time.sleep(1)
self.save_testcase(self.testcase[-10:]) # just take last 10 testcases
if self.process:
self.process = subprocess.Popen(cmdline, stdin=PIPE, stdout=PIPE, stderr=PIPE)
except OSError:
self.shutdown()
self.process = False
self.got_testcase = lambda: True
raise PJFProcessExecutionError("Binary <%s> does not exist" % cmdline[0])
except Exception as e:
raise PJFBaseException("Unknown error please send log to author")
|
[
"Run",
"command",
"in",
"a",
"loop",
"and",
"check",
"exit",
"status",
"plus",
"restart",
"process",
"when",
"needed"
] |
mseclab/PyJFuzz
|
python
|
https://github.com/mseclab/PyJFuzz/blob/f777067076f62c9ab74ffea6e90fd54402b7a1b4/pyjfuzz/core/pjf_process_monitor.py#L101-L127
|
[
"def",
"start_monitor",
"(",
"self",
",",
"standalone",
"=",
"True",
")",
":",
"try",
":",
"self",
".",
"start",
"(",
")",
"cmdline",
"=",
"shlex",
".",
"split",
"(",
"self",
".",
"config",
".",
"process_to_monitor",
")",
"if",
"standalone",
":",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGINT",
",",
"self",
".",
"shutdown",
")",
"self",
".",
"process",
"=",
"subprocess",
".",
"Popen",
"(",
"cmdline",
",",
"stdin",
"=",
"PIPE",
",",
"stdout",
"=",
"PIPE",
",",
"stderr",
"=",
"PIPE",
")",
"while",
"self",
".",
"process",
"and",
"not",
"self",
".",
"finished",
":",
"self",
".",
"process",
".",
"wait",
"(",
")",
"if",
"self",
".",
"_is_sigsegv",
"(",
"self",
".",
"process",
".",
"returncode",
")",
":",
"if",
"self",
".",
"config",
".",
"debug",
":",
"print",
"(",
"\"[\\033[92mINFO\\033[0m] Process crashed with \\033[91mSIGSEGV\\033[0m, waiting for testcase...\"",
")",
"while",
"not",
"self",
".",
"got_testcase",
"(",
")",
":",
"time",
".",
"sleep",
"(",
"1",
")",
"self",
".",
"save_testcase",
"(",
"self",
".",
"testcase",
"[",
"-",
"10",
":",
"]",
")",
"# just take last 10 testcases",
"if",
"self",
".",
"process",
":",
"self",
".",
"process",
"=",
"subprocess",
".",
"Popen",
"(",
"cmdline",
",",
"stdin",
"=",
"PIPE",
",",
"stdout",
"=",
"PIPE",
",",
"stderr",
"=",
"PIPE",
")",
"except",
"OSError",
":",
"self",
".",
"shutdown",
"(",
")",
"self",
".",
"process",
"=",
"False",
"self",
".",
"got_testcase",
"=",
"lambda",
":",
"True",
"raise",
"PJFProcessExecutionError",
"(",
"\"Binary <%s> does not exist\"",
"%",
"cmdline",
"[",
"0",
"]",
")",
"except",
"Exception",
"as",
"e",
":",
"raise",
"PJFBaseException",
"(",
"\"Unknown error please send log to author\"",
")"
] |
f777067076f62c9ab74ffea6e90fd54402b7a1b4
|
test
|
randfloat
|
Return a random float
:param float a: Either the minimum value (inclusive) if ``b`` is set, or
the maximum value if ``b`` is not set (non-inclusive, in which case the minimum
is implicitly 0.0)
:param float b: The maximum value to generate (non-inclusive)
:returns: float
|
gramfuzz/gramfuzz/rand.py
|
def randfloat(a, b=None):
"""Return a random float
:param float a: Either the minimum value (inclusive) if ``b`` is set, or
the maximum value if ``b`` is not set (non-inclusive, in which case the minimum
is implicitly 0.0)
:param float b: The maximum value to generate (non-inclusive)
:returns: float
"""
if b is None:
max_ = a
min_ = 0.0
else:
min_ = a
max_ = b
diff = max_ - min_
res = _random()
res *= diff
res += min_
return res
|
def randfloat(a, b=None):
"""Return a random float
:param float a: Either the minimum value (inclusive) if ``b`` is set, or
the maximum value if ``b`` is not set (non-inclusive, in which case the minimum
is implicitly 0.0)
:param float b: The maximum value to generate (non-inclusive)
:returns: float
"""
if b is None:
max_ = a
min_ = 0.0
else:
min_ = a
max_ = b
diff = max_ - min_
res = _random()
res *= diff
res += min_
return res
|
[
"Return",
"a",
"random",
"float"
] |
mseclab/PyJFuzz
|
python
|
https://github.com/mseclab/PyJFuzz/blob/f777067076f62c9ab74ffea6e90fd54402b7a1b4/gramfuzz/gramfuzz/rand.py#L50-L70
|
[
"def",
"randfloat",
"(",
"a",
",",
"b",
"=",
"None",
")",
":",
"if",
"b",
"is",
"None",
":",
"max_",
"=",
"a",
"min_",
"=",
"0.0",
"else",
":",
"min_",
"=",
"a",
"max_",
"=",
"b",
"diff",
"=",
"max_",
"-",
"min_",
"res",
"=",
"_random",
"(",
")",
"res",
"*=",
"diff",
"res",
"+=",
"min_",
"return",
"res"
] |
f777067076f62c9ab74ffea6e90fd54402b7a1b4
|
test
|
GramFuzzer.load_grammar
|
Load a grammar file (python file containing grammar definitions) by
file path. When loaded, the global variable ``GRAMFUZZER`` will be set
within the module. This is not always needed, but can be useful.
:param str path: The path to the grammar file
|
gramfuzz/gramfuzz/__init__.py
|
def load_grammar(self, path):
"""Load a grammar file (python file containing grammar definitions) by
file path. When loaded, the global variable ``GRAMFUZZER`` will be set
within the module. This is not always needed, but can be useful.
:param str path: The path to the grammar file
"""
if not os.path.exists(path):
raise Exception("path does not exist: {!r}".format(path))
# this will let grammars reference eachother with relative
# imports.
#
# E.g.:
# grams/
# gram1.py
# gram2.py
#
# gram1.py can do "import gram2" to require rules in gram2.py to
# be loaded
grammar_path = os.path.dirname(path)
if grammar_path not in sys.path:
sys.path.append(grammar_path)
with open(path, "r") as f:
data = f.read()
code = compile(data, path, "exec")
locals_ = {"GRAMFUZZER": self, "__file__": path}
exec(code) in locals_
if "TOP_CAT" in locals_:
cat_group = os.path.basename(path).replace(".py", "")
self.set_cat_group_top_level_cat(cat_group, locals_["TOP_CAT"])
|
def load_grammar(self, path):
"""Load a grammar file (python file containing grammar definitions) by
file path. When loaded, the global variable ``GRAMFUZZER`` will be set
within the module. This is not always needed, but can be useful.
:param str path: The path to the grammar file
"""
if not os.path.exists(path):
raise Exception("path does not exist: {!r}".format(path))
# this will let grammars reference eachother with relative
# imports.
#
# E.g.:
# grams/
# gram1.py
# gram2.py
#
# gram1.py can do "import gram2" to require rules in gram2.py to
# be loaded
grammar_path = os.path.dirname(path)
if grammar_path not in sys.path:
sys.path.append(grammar_path)
with open(path, "r") as f:
data = f.read()
code = compile(data, path, "exec")
locals_ = {"GRAMFUZZER": self, "__file__": path}
exec(code) in locals_
if "TOP_CAT" in locals_:
cat_group = os.path.basename(path).replace(".py", "")
self.set_cat_group_top_level_cat(cat_group, locals_["TOP_CAT"])
|
[
"Load",
"a",
"grammar",
"file",
"(",
"python",
"file",
"containing",
"grammar",
"definitions",
")",
"by",
"file",
"path",
".",
"When",
"loaded",
"the",
"global",
"variable",
"GRAMFUZZER",
"will",
"be",
"set",
"within",
"the",
"module",
".",
"This",
"is",
"not",
"always",
"needed",
"but",
"can",
"be",
"useful",
"."
] |
mseclab/PyJFuzz
|
python
|
https://github.com/mseclab/PyJFuzz/blob/f777067076f62c9ab74ffea6e90fd54402b7a1b4/gramfuzz/gramfuzz/__init__.py#L98-L131
|
[
"def",
"load_grammar",
"(",
"self",
",",
"path",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"raise",
"Exception",
"(",
"\"path does not exist: {!r}\"",
".",
"format",
"(",
"path",
")",
")",
"# this will let grammars reference eachother with relative",
"# imports.",
"#",
"# E.g.:",
"# grams/",
"# gram1.py",
"# gram2.py",
"#",
"# gram1.py can do \"import gram2\" to require rules in gram2.py to",
"# be loaded",
"grammar_path",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"path",
")",
"if",
"grammar_path",
"not",
"in",
"sys",
".",
"path",
":",
"sys",
".",
"path",
".",
"append",
"(",
"grammar_path",
")",
"with",
"open",
"(",
"path",
",",
"\"r\"",
")",
"as",
"f",
":",
"data",
"=",
"f",
".",
"read",
"(",
")",
"code",
"=",
"compile",
"(",
"data",
",",
"path",
",",
"\"exec\"",
")",
"locals_",
"=",
"{",
"\"GRAMFUZZER\"",
":",
"self",
",",
"\"__file__\"",
":",
"path",
"}",
"exec",
"(",
"code",
")",
"in",
"locals_",
"if",
"\"TOP_CAT\"",
"in",
"locals_",
":",
"cat_group",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"path",
")",
".",
"replace",
"(",
"\".py\"",
",",
"\"\"",
")",
"self",
".",
"set_cat_group_top_level_cat",
"(",
"cat_group",
",",
"locals_",
"[",
"\"TOP_CAT\"",
"]",
")"
] |
f777067076f62c9ab74ffea6e90fd54402b7a1b4
|
test
|
GramFuzzer.set_max_recursion
|
Set the maximum reference-recursion depth (not the Python system maximum stack
recursion level). This controls how many levels deep of nested references are allowed
before gramfuzz attempts to generate the shortest (reference-wise) rules possible.
:param int level: The new maximum reference level
|
gramfuzz/gramfuzz/__init__.py
|
def set_max_recursion(self, level):
"""Set the maximum reference-recursion depth (not the Python system maximum stack
recursion level). This controls how many levels deep of nested references are allowed
before gramfuzz attempts to generate the shortest (reference-wise) rules possible.
:param int level: The new maximum reference level
"""
import gramfuzz.fields
gramfuzz.fields.Ref.max_recursion = level
|
def set_max_recursion(self, level):
"""Set the maximum reference-recursion depth (not the Python system maximum stack
recursion level). This controls how many levels deep of nested references are allowed
before gramfuzz attempts to generate the shortest (reference-wise) rules possible.
:param int level: The new maximum reference level
"""
import gramfuzz.fields
gramfuzz.fields.Ref.max_recursion = level
|
[
"Set",
"the",
"maximum",
"reference",
"-",
"recursion",
"depth",
"(",
"not",
"the",
"Python",
"system",
"maximum",
"stack",
"recursion",
"level",
")",
".",
"This",
"controls",
"how",
"many",
"levels",
"deep",
"of",
"nested",
"references",
"are",
"allowed",
"before",
"gramfuzz",
"attempts",
"to",
"generate",
"the",
"shortest",
"(",
"reference",
"-",
"wise",
")",
"rules",
"possible",
"."
] |
mseclab/PyJFuzz
|
python
|
https://github.com/mseclab/PyJFuzz/blob/f777067076f62c9ab74ffea6e90fd54402b7a1b4/gramfuzz/gramfuzz/__init__.py#L133-L141
|
[
"def",
"set_max_recursion",
"(",
"self",
",",
"level",
")",
":",
"import",
"gramfuzz",
".",
"fields",
"gramfuzz",
".",
"fields",
".",
"Ref",
".",
"max_recursion",
"=",
"level"
] |
f777067076f62c9ab74ffea6e90fd54402b7a1b4
|
test
|
GramFuzzer.preprocess_rules
|
Calculate shortest reference-paths of each rule (and Or field),
and prune all unreachable rules.
|
gramfuzz/gramfuzz/__init__.py
|
def preprocess_rules(self):
"""Calculate shortest reference-paths of each rule (and Or field),
and prune all unreachable rules.
"""
to_prune = self._find_shortest_paths()
self._prune_rules(to_prune)
self._rules_processed = True
|
def preprocess_rules(self):
"""Calculate shortest reference-paths of each rule (and Or field),
and prune all unreachable rules.
"""
to_prune = self._find_shortest_paths()
self._prune_rules(to_prune)
self._rules_processed = True
|
[
"Calculate",
"shortest",
"reference",
"-",
"paths",
"of",
"each",
"rule",
"(",
"and",
"Or",
"field",
")",
"and",
"prune",
"all",
"unreachable",
"rules",
"."
] |
mseclab/PyJFuzz
|
python
|
https://github.com/mseclab/PyJFuzz/blob/f777067076f62c9ab74ffea6e90fd54402b7a1b4/gramfuzz/gramfuzz/__init__.py#L143-L150
|
[
"def",
"preprocess_rules",
"(",
"self",
")",
":",
"to_prune",
"=",
"self",
".",
"_find_shortest_paths",
"(",
")",
"self",
".",
"_prune_rules",
"(",
"to_prune",
")",
"self",
".",
"_rules_processed",
"=",
"True"
] |
f777067076f62c9ab74ffea6e90fd54402b7a1b4
|
test
|
GramFuzzer.add_definition
|
Add a new rule definition named ``def_name`` having value ``def_value`` to
the category ``cat``.
:param str cat: The category to add the rule to
:param str def_name: The name of the rule definition
:param def_val: The value of the rule definition
:param bool no_prune: If the rule should explicitly *NOT*
be pruned even if it has been determined to be unreachable (default=``False``)
:param str gram_file: The file the rule was defined in (default=``"default"``).
|
gramfuzz/gramfuzz/__init__.py
|
def add_definition(self, cat, def_name, def_val, no_prune=False, gram_file="default"):
"""Add a new rule definition named ``def_name`` having value ``def_value`` to
the category ``cat``.
:param str cat: The category to add the rule to
:param str def_name: The name of the rule definition
:param def_val: The value of the rule definition
:param bool no_prune: If the rule should explicitly *NOT*
be pruned even if it has been determined to be unreachable (default=``False``)
:param str gram_file: The file the rule was defined in (default=``"default"``).
"""
self._rules_processed = False
self.add_to_cat_group(cat, gram_file, def_name)
if no_prune:
self.no_prunes.setdefault(cat, {}).setdefault(def_name, True)
if self._staged_defs is not None:
# if we're tracking changes during rule generation, add any new rules
# to _staged_defs so they can be reverted if something goes wrong
self._staged_defs.append((cat, def_name, def_val))
else:
self.defs.setdefault(cat, {}).setdefault(def_name, deque()).append(def_val)
|
def add_definition(self, cat, def_name, def_val, no_prune=False, gram_file="default"):
"""Add a new rule definition named ``def_name`` having value ``def_value`` to
the category ``cat``.
:param str cat: The category to add the rule to
:param str def_name: The name of the rule definition
:param def_val: The value of the rule definition
:param bool no_prune: If the rule should explicitly *NOT*
be pruned even if it has been determined to be unreachable (default=``False``)
:param str gram_file: The file the rule was defined in (default=``"default"``).
"""
self._rules_processed = False
self.add_to_cat_group(cat, gram_file, def_name)
if no_prune:
self.no_prunes.setdefault(cat, {}).setdefault(def_name, True)
if self._staged_defs is not None:
# if we're tracking changes during rule generation, add any new rules
# to _staged_defs so they can be reverted if something goes wrong
self._staged_defs.append((cat, def_name, def_val))
else:
self.defs.setdefault(cat, {}).setdefault(def_name, deque()).append(def_val)
|
[
"Add",
"a",
"new",
"rule",
"definition",
"named",
"def_name",
"having",
"value",
"def_value",
"to",
"the",
"category",
"cat",
"."
] |
mseclab/PyJFuzz
|
python
|
https://github.com/mseclab/PyJFuzz/blob/f777067076f62c9ab74ffea6e90fd54402b7a1b4/gramfuzz/gramfuzz/__init__.py#L315-L338
|
[
"def",
"add_definition",
"(",
"self",
",",
"cat",
",",
"def_name",
",",
"def_val",
",",
"no_prune",
"=",
"False",
",",
"gram_file",
"=",
"\"default\"",
")",
":",
"self",
".",
"_rules_processed",
"=",
"False",
"self",
".",
"add_to_cat_group",
"(",
"cat",
",",
"gram_file",
",",
"def_name",
")",
"if",
"no_prune",
":",
"self",
".",
"no_prunes",
".",
"setdefault",
"(",
"cat",
",",
"{",
"}",
")",
".",
"setdefault",
"(",
"def_name",
",",
"True",
")",
"if",
"self",
".",
"_staged_defs",
"is",
"not",
"None",
":",
"# if we're tracking changes during rule generation, add any new rules",
"# to _staged_defs so they can be reverted if something goes wrong",
"self",
".",
"_staged_defs",
".",
"append",
"(",
"(",
"cat",
",",
"def_name",
",",
"def_val",
")",
")",
"else",
":",
"self",
".",
"defs",
".",
"setdefault",
"(",
"cat",
",",
"{",
"}",
")",
".",
"setdefault",
"(",
"def_name",
",",
"deque",
"(",
")",
")",
".",
"append",
"(",
"def_val",
")"
] |
f777067076f62c9ab74ffea6e90fd54402b7a1b4
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.