repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1
value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 3
values | summary stringlengths 4 350 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
maljovec/topopy | topopy/MorseSmaleComplex.py | MorseSmaleComplex.get_label | def get_label(self, indices=None):
""" Returns the label pair indices requested by the user
@ In, indices, a list of non-negative integers specifying
the row indices to return
@ Out, a list of integer 2-tuples specifying the minimum and
maximum index of the specif... | python | def get_label(self, indices=None):
""" Returns the label pair indices requested by the user
@ In, indices, a list of non-negative integers specifying
the row indices to return
@ Out, a list of integer 2-tuples specifying the minimum and
maximum index of the specif... | [
"def",
"get_label",
"(",
"self",
",",
"indices",
"=",
"None",
")",
":",
"if",
"indices",
"is",
"None",
":",
"indices",
"=",
"list",
"(",
"range",
"(",
"0",
",",
"self",
".",
"get_sample_size",
"(",
")",
")",
")",
"elif",
"isinstance",
"(",
"indices",... | Returns the label pair indices requested by the user
@ In, indices, a list of non-negative integers specifying
the row indices to return
@ Out, a list of integer 2-tuples specifying the minimum and
maximum index of the specified rows. | [
"Returns",
"the",
"label",
"pair",
"indices",
"requested",
"by",
"the",
"user"
] | 4be598d51c4e4043b73d4ad44beed6d289e2f088 | https://github.com/maljovec/topopy/blob/4be598d51c4e4043b73d4ad44beed6d289e2f088/topopy/MorseSmaleComplex.py#L316-L341 | train | Returns the label pair indices requested by the user. |
maljovec/topopy | topopy/MorseSmaleComplex.py | MorseSmaleComplex.get_sample_size | def get_sample_size(self, key=None):
""" Returns the number of samples in the input data
@ In, key, an optional 2-tuple specifying a min-max id pair
used for determining which partition size should be
returned. If not specified then the size of the entire data
set... | python | def get_sample_size(self, key=None):
""" Returns the number of samples in the input data
@ In, key, an optional 2-tuple specifying a min-max id pair
used for determining which partition size should be
returned. If not specified then the size of the entire data
set... | [
"def",
"get_sample_size",
"(",
"self",
",",
"key",
"=",
"None",
")",
":",
"if",
"key",
"is",
"None",
":",
"return",
"len",
"(",
"self",
".",
"Y",
")",
"else",
":",
"return",
"len",
"(",
"self",
".",
"get_partitions",
"(",
"self",
".",
"persistence",
... | Returns the number of samples in the input data
@ In, key, an optional 2-tuple specifying a min-max id pair
used for determining which partition size should be
returned. If not specified then the size of the entire data
set will be returned.
@ Out, an integer ... | [
"Returns",
"the",
"number",
"of",
"samples",
"in",
"the",
"input",
"data"
] | 4be598d51c4e4043b73d4ad44beed6d289e2f088 | https://github.com/maljovec/topopy/blob/4be598d51c4e4043b73d4ad44beed6d289e2f088/topopy/MorseSmaleComplex.py#L354-L365 | train | Returns the number of samples in the input data
. |
maljovec/topopy | topopy/MorseSmaleComplex.py | MorseSmaleComplex.to_json | def to_json(self):
""" Writes the complete Morse-Smale merge hierarchy to a string
object.
@ Out, a string object storing the entire merge hierarchy of
all minima and maxima.
"""
capsule = {}
capsule["Hierarchy"] = []
for (
dying,
... | python | def to_json(self):
""" Writes the complete Morse-Smale merge hierarchy to a string
object.
@ Out, a string object storing the entire merge hierarchy of
all minima and maxima.
"""
capsule = {}
capsule["Hierarchy"] = []
for (
dying,
... | [
"def",
"to_json",
"(",
"self",
")",
":",
"capsule",
"=",
"{",
"}",
"capsule",
"[",
"\"Hierarchy\"",
"]",
"=",
"[",
"]",
"for",
"(",
"dying",
",",
"(",
"persistence",
",",
"surviving",
",",
"saddle",
")",
",",
")",
"in",
"self",
".",
"merge_sequence",... | Writes the complete Morse-Smale merge hierarchy to a string
object.
@ Out, a string object storing the entire merge hierarchy of
all minima and maxima. | [
"Writes",
"the",
"complete",
"Morse",
"-",
"Smale",
"merge",
"hierarchy",
"to",
"a",
"string",
"object",
"."
] | 4be598d51c4e4043b73d4ad44beed6d289e2f088 | https://github.com/maljovec/topopy/blob/4be598d51c4e4043b73d4ad44beed6d289e2f088/topopy/MorseSmaleComplex.py#L382-L408 | train | Writes the complete Morse - Smale merge hierarchy to a string object. |
yymao/generic-catalog-reader | GCR/utils.py | dict_to_numpy_array | def dict_to_numpy_array(d):
"""
Convert a dict of 1d array to a numpy recarray
"""
return fromarrays(d.values(), np.dtype([(str(k), v.dtype) for k, v in d.items()])) | python | def dict_to_numpy_array(d):
"""
Convert a dict of 1d array to a numpy recarray
"""
return fromarrays(d.values(), np.dtype([(str(k), v.dtype) for k, v in d.items()])) | [
"def",
"dict_to_numpy_array",
"(",
"d",
")",
":",
"return",
"fromarrays",
"(",
"d",
".",
"values",
"(",
")",
",",
"np",
".",
"dtype",
"(",
"[",
"(",
"str",
"(",
"k",
")",
",",
"v",
".",
"dtype",
")",
"for",
"k",
",",
"v",
"in",
"d",
".",
"ite... | Convert a dict of 1d array to a numpy recarray | [
"Convert",
"a",
"dict",
"of",
"1d",
"array",
"to",
"a",
"numpy",
"recarray"
] | bc6267ac41b9f68106ed6065184469ac13fdc0b6 | https://github.com/yymao/generic-catalog-reader/blob/bc6267ac41b9f68106ed6065184469ac13fdc0b6/GCR/utils.py#L23-L27 | train | Convert a dict of 1d array to a numpy recarray
|
yymao/generic-catalog-reader | GCR/utils.py | concatenate_1d | def concatenate_1d(arrays):
"""
Concatenate 1D numpy arrays.
Similar to np.concatenate but work with empty input and masked arrays.
"""
if len(arrays) == 0:
return np.array([])
if len(arrays) == 1:
return np.asanyarray(arrays[0])
if any(map(np.ma.is_masked, arrays)):
... | python | def concatenate_1d(arrays):
"""
Concatenate 1D numpy arrays.
Similar to np.concatenate but work with empty input and masked arrays.
"""
if len(arrays) == 0:
return np.array([])
if len(arrays) == 1:
return np.asanyarray(arrays[0])
if any(map(np.ma.is_masked, arrays)):
... | [
"def",
"concatenate_1d",
"(",
"arrays",
")",
":",
"if",
"len",
"(",
"arrays",
")",
"==",
"0",
":",
"return",
"np",
".",
"array",
"(",
"[",
"]",
")",
"if",
"len",
"(",
"arrays",
")",
"==",
"1",
":",
"return",
"np",
".",
"asanyarray",
"(",
"arrays"... | Concatenate 1D numpy arrays.
Similar to np.concatenate but work with empty input and masked arrays. | [
"Concatenate",
"1D",
"numpy",
"arrays",
".",
"Similar",
"to",
"np",
".",
"concatenate",
"but",
"work",
"with",
"empty",
"input",
"and",
"masked",
"arrays",
"."
] | bc6267ac41b9f68106ed6065184469ac13fdc0b6 | https://github.com/yymao/generic-catalog-reader/blob/bc6267ac41b9f68106ed6065184469ac13fdc0b6/GCR/utils.py#L29-L40 | train | Concatenate 1D numpy arrays. |
mojaie/chorus | chorus/model/atom.py | Atom.add_hydrogen | def add_hydrogen(self, num):
"""Adds hydrogens
Args:
num (int): number of hydrogens
"""
self.H_count = num
if num > 0 and self.symbol in ("N", "O"):
self.H_donor = 1
else:
self.H_donor = 0 | python | def add_hydrogen(self, num):
"""Adds hydrogens
Args:
num (int): number of hydrogens
"""
self.H_count = num
if num > 0 and self.symbol in ("N", "O"):
self.H_donor = 1
else:
self.H_donor = 0 | [
"def",
"add_hydrogen",
"(",
"self",
",",
"num",
")",
":",
"self",
".",
"H_count",
"=",
"num",
"if",
"num",
">",
"0",
"and",
"self",
".",
"symbol",
"in",
"(",
"\"N\"",
",",
"\"O\"",
")",
":",
"self",
".",
"H_donor",
"=",
"1",
"else",
":",
"self",
... | Adds hydrogens
Args:
num (int): number of hydrogens | [
"Adds",
"hydrogens"
] | fc7fe23a0272554c67671645ab07830b315eeb1b | https://github.com/mojaie/chorus/blob/fc7fe23a0272554c67671645ab07830b315eeb1b/chorus/model/atom.py#L111-L121 | train | Adds hydrogens to the log. |
mojaie/chorus | chorus/model/atom.py | Atom.formula_html | def formula_html(self, reversed_=False):
"""Chemical formula HTML
Args:
reversed (bool): reversed text for leftmost atom groups
"""
if self.H_count == 1:
text = "H"
elif self.H_count > 1:
text = "H<sub>{}</sub>".format(self.H_count)
el... | python | def formula_html(self, reversed_=False):
"""Chemical formula HTML
Args:
reversed (bool): reversed text for leftmost atom groups
"""
if self.H_count == 1:
text = "H"
elif self.H_count > 1:
text = "H<sub>{}</sub>".format(self.H_count)
el... | [
"def",
"formula_html",
"(",
"self",
",",
"reversed_",
"=",
"False",
")",
":",
"if",
"self",
".",
"H_count",
"==",
"1",
":",
"text",
"=",
"\"H\"",
"elif",
"self",
".",
"H_count",
">",
"1",
":",
"text",
"=",
"\"H<sub>{}</sub>\"",
".",
"format",
"(",
"s... | Chemical formula HTML
Args:
reversed (bool): reversed text for leftmost atom groups | [
"Chemical",
"formula",
"HTML"
] | fc7fe23a0272554c67671645ab07830b315eeb1b | https://github.com/mojaie/chorus/blob/fc7fe23a0272554c67671645ab07830b315eeb1b/chorus/model/atom.py#L123-L138 | train | Chemical formula HTML for the current object |
mojaie/chorus | chorus/model/atom.py | Atom.mw | def mw(self):
"""Molecular weight"""
m = P_TAB[self.symbol].get('std_weight')
mh = P_TAB['H'].get('std_weight')
return m + mh * self.H_count | python | def mw(self):
"""Molecular weight"""
m = P_TAB[self.symbol].get('std_weight')
mh = P_TAB['H'].get('std_weight')
return m + mh * self.H_count | [
"def",
"mw",
"(",
"self",
")",
":",
"m",
"=",
"P_TAB",
"[",
"self",
".",
"symbol",
"]",
".",
"get",
"(",
"'std_weight'",
")",
"mh",
"=",
"P_TAB",
"[",
"'H'",
"]",
".",
"get",
"(",
"'std_weight'",
")",
"return",
"m",
"+",
"mh",
"*",
"self",
".",... | Molecular weight | [
"Molecular",
"weight"
] | fc7fe23a0272554c67671645ab07830b315eeb1b | https://github.com/mojaie/chorus/blob/fc7fe23a0272554c67671645ab07830b315eeb1b/chorus/model/atom.py#L148-L152 | train | Molecular weight |
mojaie/chorus | chorus/model/atom.py | Atom.charge_sign | def charge_sign(self):
"""Charge sign text"""
if self.charge > 0:
sign = "+"
elif self.charge < 0:
sign = "–" # en dash, not hyphen-minus
else:
return ""
ab = abs(self.charge)
if ab > 1:
return str(ab) + sign
return... | python | def charge_sign(self):
"""Charge sign text"""
if self.charge > 0:
sign = "+"
elif self.charge < 0:
sign = "–" # en dash, not hyphen-minus
else:
return ""
ab = abs(self.charge)
if ab > 1:
return str(ab) + sign
return... | [
"def",
"charge_sign",
"(",
"self",
")",
":",
"if",
"self",
".",
"charge",
">",
"0",
":",
"sign",
"=",
"\"+\"",
"elif",
"self",
".",
"charge",
"<",
"0",
":",
"sign",
"=",
"\"–\" ",
"en dash, not hyphen-minus",
"else",
":",
"return",
"\"\"",
"ab",
"=",
... | Charge sign text | [
"Charge",
"sign",
"text"
] | fc7fe23a0272554c67671645ab07830b315eeb1b | https://github.com/mojaie/chorus/blob/fc7fe23a0272554c67671645ab07830b315eeb1b/chorus/model/atom.py#L154-L165 | train | Charge sign text |
mojaie/chorus | chorus/substructure.py | equal | def equal(mol, query, largest_only=True, ignore_hydrogen=True):
""" if mol is exactly same structure as the query, return True
Args:
mol: Compound
query: Compound
"""
m = molutil.clone(mol)
q = molutil.clone(query)
if largest_only:
m = molutil.largest_graph(m)
q = mol... | python | def equal(mol, query, largest_only=True, ignore_hydrogen=True):
""" if mol is exactly same structure as the query, return True
Args:
mol: Compound
query: Compound
"""
m = molutil.clone(mol)
q = molutil.clone(query)
if largest_only:
m = molutil.largest_graph(m)
q = mol... | [
"def",
"equal",
"(",
"mol",
",",
"query",
",",
"largest_only",
"=",
"True",
",",
"ignore_hydrogen",
"=",
"True",
")",
":",
"m",
"=",
"molutil",
".",
"clone",
"(",
"mol",
")",
"q",
"=",
"molutil",
".",
"clone",
"(",
"query",
")",
"if",
"largest_only",... | if mol is exactly same structure as the query, return True
Args:
mol: Compound
query: Compound | [
"if",
"mol",
"is",
"exactly",
"same",
"structure",
"as",
"the",
"query",
"return",
"True",
"Args",
":",
"mol",
":",
"Compound",
"query",
":",
"Compound"
] | fc7fe23a0272554c67671645ab07830b315eeb1b | https://github.com/mojaie/chorus/blob/fc7fe23a0272554c67671645ab07830b315eeb1b/chorus/substructure.py#L39-L56 | train | Returns True if the given molecule is exactly same structure as the query. |
mojaie/chorus | chorus/substructure.py | substructure | def substructure(mol, query, largest_only=True, ignore_hydrogen=True):
""" if mol is a substructure of the query, return True
Args:
mol: Compound
query: Compound
largest_only: compare only largest graph molecule
"""
def subset_filter(cnt1, cnt2):
diff = cnt2
diff.subtra... | python | def substructure(mol, query, largest_only=True, ignore_hydrogen=True):
""" if mol is a substructure of the query, return True
Args:
mol: Compound
query: Compound
largest_only: compare only largest graph molecule
"""
def subset_filter(cnt1, cnt2):
diff = cnt2
diff.subtra... | [
"def",
"substructure",
"(",
"mol",
",",
"query",
",",
"largest_only",
"=",
"True",
",",
"ignore_hydrogen",
"=",
"True",
")",
":",
"def",
"subset_filter",
"(",
"cnt1",
",",
"cnt2",
")",
":",
"diff",
"=",
"cnt2",
"diff",
".",
"subtract",
"(",
"cnt1",
")"... | if mol is a substructure of the query, return True
Args:
mol: Compound
query: Compound
largest_only: compare only largest graph molecule | [
"if",
"mol",
"is",
"a",
"substructure",
"of",
"the",
"query",
"return",
"True",
"Args",
":",
"mol",
":",
"Compound",
"query",
":",
"Compound",
"largest_only",
":",
"compare",
"only",
"largest",
"graph",
"molecule"
] | fc7fe23a0272554c67671645ab07830b315eeb1b | https://github.com/mojaie/chorus/blob/fc7fe23a0272554c67671645ab07830b315eeb1b/chorus/substructure.py#L59-L85 | train | Returns True if the molecule is a substructure of the query. |
mastro35/flows | flows/MessageDispatcher.py | MessageDispatcher.default_instance | def default_instance(cls):
"""
For use like a singleton, return the existing instance of the object
or a new instance
"""
if cls._instance is None:
with cls._instance_lock:
if cls._instance is None:
cls._instance = MessageDispatcher... | python | def default_instance(cls):
"""
For use like a singleton, return the existing instance of the object
or a new instance
"""
if cls._instance is None:
with cls._instance_lock:
if cls._instance is None:
cls._instance = MessageDispatcher... | [
"def",
"default_instance",
"(",
"cls",
")",
":",
"if",
"cls",
".",
"_instance",
"is",
"None",
":",
"with",
"cls",
".",
"_instance_lock",
":",
"if",
"cls",
".",
"_instance",
"is",
"None",
":",
"cls",
".",
"_instance",
"=",
"MessageDispatcher",
"(",
")",
... | For use like a singleton, return the existing instance of the object
or a new instance | [
"For",
"use",
"like",
"a",
"singleton",
"return",
"the",
"existing",
"instance",
"of",
"the",
"object",
"or",
"a",
"new",
"instance"
] | 05e488385673a69597b5b39c7728795aa4d5eb18 | https://github.com/mastro35/flows/blob/05e488385673a69597b5b39c7728795aa4d5eb18/flows/MessageDispatcher.py#L33-L43 | train | Returns the default instance of the class. |
mastro35/flows | flows/MessageDispatcher.py | MessageDispatcher.send_message | def send_message(self, message):
"""
Dispatch a message using 0mq
"""
with self._instance_lock:
if message is None:
Global.LOGGER.error("can't deliver a null messages")
return
if message.sender is None:
Global.LOGGE... | python | def send_message(self, message):
"""
Dispatch a message using 0mq
"""
with self._instance_lock:
if message is None:
Global.LOGGER.error("can't deliver a null messages")
return
if message.sender is None:
Global.LOGGE... | [
"def",
"send_message",
"(",
"self",
",",
"message",
")",
":",
"with",
"self",
".",
"_instance_lock",
":",
"if",
"message",
"is",
"None",
":",
"Global",
".",
"LOGGER",
".",
"error",
"(",
"\"can't deliver a null messages\"",
")",
"return",
"if",
"message",
"."... | Dispatch a message using 0mq | [
"Dispatch",
"a",
"message",
"using",
"0mq"
] | 05e488385673a69597b5b39c7728795aa4d5eb18 | https://github.com/mastro35/flows/blob/05e488385673a69597b5b39c7728795aa4d5eb18/flows/MessageDispatcher.py#L84-L118 | train | Dispatch a message using 0mq
|
auto-mat/django-webmap-corpus | webmap/models.py | update_properties_cache | def update_properties_cache(sender, instance, action, reverse, model, pk_set, **kwargs):
"Property cache actualization at POI save. It will not work yet after property removal."
if action == 'post_add':
instance.save_properties_cache() | python | def update_properties_cache(sender, instance, action, reverse, model, pk_set, **kwargs):
"Property cache actualization at POI save. It will not work yet after property removal."
if action == 'post_add':
instance.save_properties_cache() | [
"def",
"update_properties_cache",
"(",
"sender",
",",
"instance",
",",
"action",
",",
"reverse",
",",
"model",
",",
"pk_set",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"action",
"==",
"'post_add'",
":",
"instance",
".",
"save_properties_cache",
"(",
")"
] | Property cache actualization at POI save. It will not work yet after property removal. | [
"Property",
"cache",
"actualization",
"at",
"POI",
"save",
".",
"It",
"will",
"not",
"work",
"yet",
"after",
"property",
"removal",
"."
] | 1d8b7428d2bf3b1165985d767b19677bb6db9eae | https://github.com/auto-mat/django-webmap-corpus/blob/1d8b7428d2bf3b1165985d767b19677bb6db9eae/webmap/models.py#L236-L239 | train | Property cache actualization at POI save. It will not work yet after property removal. |
maljovec/topopy | topopy/MorseComplex.py | MorseComplex.reset | def reset(self):
"""
Empties all internal storage containers
"""
super(MorseComplex, self).reset()
self.base_partitions = {}
self.merge_sequence = {}
self.persistences = []
self.max_indices = []
# State properties
self.persistence = ... | python | def reset(self):
"""
Empties all internal storage containers
"""
super(MorseComplex, self).reset()
self.base_partitions = {}
self.merge_sequence = {}
self.persistences = []
self.max_indices = []
# State properties
self.persistence = ... | [
"def",
"reset",
"(",
"self",
")",
":",
"super",
"(",
"MorseComplex",
",",
"self",
")",
".",
"reset",
"(",
")",
"self",
".",
"base_partitions",
"=",
"{",
"}",
"self",
".",
"merge_sequence",
"=",
"{",
"}",
"self",
".",
"persistences",
"=",
"[",
"]",
... | Empties all internal storage containers | [
"Empties",
"all",
"internal",
"storage",
"containers"
] | 4be598d51c4e4043b73d4ad44beed6d289e2f088 | https://github.com/maljovec/topopy/blob/4be598d51c4e4043b73d4ad44beed6d289e2f088/topopy/MorseComplex.py#L88-L101 | train | Resets internal storage containers to empty state. |
maljovec/topopy | topopy/MorseComplex.py | MorseComplex.build | def build(self, X, Y, w=None, edges=None):
""" Assigns data to this object and builds the Morse-Smale
Complex
@ In, X, an m-by-n array of values specifying m
n-dimensional samples
@ In, Y, a m vector of values specifying the output
responses correspond... | python | def build(self, X, Y, w=None, edges=None):
""" Assigns data to this object and builds the Morse-Smale
Complex
@ In, X, an m-by-n array of values specifying m
n-dimensional samples
@ In, Y, a m vector of values specifying the output
responses correspond... | [
"def",
"build",
"(",
"self",
",",
"X",
",",
"Y",
",",
"w",
"=",
"None",
",",
"edges",
"=",
"None",
")",
":",
"super",
"(",
"MorseComplex",
",",
"self",
")",
".",
"build",
"(",
"X",
",",
"Y",
",",
"w",
",",
"edges",
")",
"if",
"self",
".",
"... | Assigns data to this object and builds the Morse-Smale
Complex
@ In, X, an m-by-n array of values specifying m
n-dimensional samples
@ In, Y, a m vector of values specifying the output
responses corresponding to the m samples specified by X
@ In, w... | [
"Assigns",
"data",
"to",
"this",
"object",
"and",
"builds",
"the",
"Morse",
"-",
"Smale",
"Complex"
] | 4be598d51c4e4043b73d4ad44beed6d289e2f088 | https://github.com/maljovec/topopy/blob/4be598d51c4e4043b73d4ad44beed6d289e2f088/topopy/MorseComplex.py#L103-L157 | train | Assigns data to this object and builds the Morse - Smale complex object. |
maljovec/topopy | topopy/MorseComplex.py | MorseComplex.get_partitions | def get_partitions(self, persistence=None):
""" Returns the partitioned data based on a specified
persistence level.
@ In, persistence, a floating point value specifying the
size of the smallest feature we want to track.
Default = None means consider all features.... | python | def get_partitions(self, persistence=None):
""" Returns the partitioned data based on a specified
persistence level.
@ In, persistence, a floating point value specifying the
size of the smallest feature we want to track.
Default = None means consider all features.... | [
"def",
"get_partitions",
"(",
"self",
",",
"persistence",
"=",
"None",
")",
":",
"if",
"persistence",
"is",
"None",
":",
"persistence",
"=",
"self",
".",
"persistence",
"partitions",
"=",
"{",
"}",
"# TODO: Possibly cache at the critical persistence values,",
"# pre... | Returns the partitioned data based on a specified
persistence level.
@ In, persistence, a floating point value specifying the
size of the smallest feature we want to track.
Default = None means consider all features.
@ Out, a dictionary lists where each key is... | [
"Returns",
"the",
"partitioned",
"data",
"based",
"on",
"a",
"specified",
"persistence",
"level",
"."
] | 4be598d51c4e4043b73d4ad44beed6d289e2f088 | https://github.com/maljovec/topopy/blob/4be598d51c4e4043b73d4ad44beed6d289e2f088/topopy/MorseComplex.py#L263-L298 | train | Returns the partitions of the base_partitions based on a specified persistence level. |
maljovec/topopy | topopy/MorseComplex.py | MorseComplex.to_json | def to_json(self):
""" Writes the complete Morse complex merge hierarchy to a
string object.
@ Out, a string object storing the entire merge hierarchy of
all maxima.
"""
capsule = {}
capsule["Hierarchy"] = []
for (
dying,
... | python | def to_json(self):
""" Writes the complete Morse complex merge hierarchy to a
string object.
@ Out, a string object storing the entire merge hierarchy of
all maxima.
"""
capsule = {}
capsule["Hierarchy"] = []
for (
dying,
... | [
"def",
"to_json",
"(",
"self",
")",
":",
"capsule",
"=",
"{",
"}",
"capsule",
"[",
"\"Hierarchy\"",
"]",
"=",
"[",
"]",
"for",
"(",
"dying",
",",
"(",
"persistence",
",",
"surviving",
",",
"saddle",
")",
",",
")",
"in",
"self",
".",
"merge_sequence",... | Writes the complete Morse complex merge hierarchy to a
string object.
@ Out, a string object storing the entire merge hierarchy of
all maxima. | [
"Writes",
"the",
"complete",
"Morse",
"complex",
"merge",
"hierarchy",
"to",
"a",
"string",
"object",
"."
] | 4be598d51c4e4043b73d4ad44beed6d289e2f088 | https://github.com/maljovec/topopy/blob/4be598d51c4e4043b73d4ad44beed6d289e2f088/topopy/MorseComplex.py#L380-L406 | train | Writes the complete Morse complex merge hierarchy to a
string object. |
redhat-cip/python-dciclient | dciclient/v1/api/jobs_events.py | iter | def iter(context, sequence, limit=10):
"""Iter to list all the jobs events."""
params = {'limit': limit,
'offset': 0}
uri = '%s/%s/%s' % (context.dci_cs_api, RESOURCE, sequence)
while True:
j = context.session.get(uri, params=params).json()
if len(j['jobs_events']):
... | python | def iter(context, sequence, limit=10):
"""Iter to list all the jobs events."""
params = {'limit': limit,
'offset': 0}
uri = '%s/%s/%s' % (context.dci_cs_api, RESOURCE, sequence)
while True:
j = context.session.get(uri, params=params).json()
if len(j['jobs_events']):
... | [
"def",
"iter",
"(",
"context",
",",
"sequence",
",",
"limit",
"=",
"10",
")",
":",
"params",
"=",
"{",
"'limit'",
":",
"limit",
",",
"'offset'",
":",
"0",
"}",
"uri",
"=",
"'%s/%s/%s'",
"%",
"(",
"context",
".",
"dci_cs_api",
",",
"RESOURCE",
",",
... | Iter to list all the jobs events. | [
"Iter",
"to",
"list",
"all",
"the",
"jobs",
"events",
"."
] | a4aa5899062802bbe4c30a075d8447f8d222d214 | https://github.com/redhat-cip/python-dciclient/blob/a4aa5899062802bbe4c30a075d8447f8d222d214/dciclient/v1/api/jobs_events.py#L30-L43 | train | Iter to list all the jobs events in a sequence. |
redhat-cip/python-dciclient | dciclient/v1/api/jobs_events.py | delete | def delete(context, sequence):
"""Delete jobs events from a given sequence"""
uri = '%s/%s/%s' % (context.dci_cs_api, RESOURCE, sequence)
return context.session.delete(uri) | python | def delete(context, sequence):
"""Delete jobs events from a given sequence"""
uri = '%s/%s/%s' % (context.dci_cs_api, RESOURCE, sequence)
return context.session.delete(uri) | [
"def",
"delete",
"(",
"context",
",",
"sequence",
")",
":",
"uri",
"=",
"'%s/%s/%s'",
"%",
"(",
"context",
".",
"dci_cs_api",
",",
"RESOURCE",
",",
"sequence",
")",
"return",
"context",
".",
"session",
".",
"delete",
"(",
"uri",
")"
] | Delete jobs events from a given sequence | [
"Delete",
"jobs",
"events",
"from",
"a",
"given",
"sequence"
] | a4aa5899062802bbe4c30a075d8447f8d222d214 | https://github.com/redhat-cip/python-dciclient/blob/a4aa5899062802bbe4c30a075d8447f8d222d214/dciclient/v1/api/jobs_events.py#L46-L49 | train | Delete jobs events from a given sequence |
DheerendraRathor/django-auth-ldap-ng | django_auth_ldap/config.py | _LDAPConfig.get_ldap | def get_ldap(cls, global_options=None):
"""
Returns the ldap module. The unit test harness will assign a mock object
to _LDAPConfig.ldap. It is imperative that the ldap module not be
imported anywhere else so that the unit tests will pass in the absence
of python-ldap.
""... | python | def get_ldap(cls, global_options=None):
"""
Returns the ldap module. The unit test harness will assign a mock object
to _LDAPConfig.ldap. It is imperative that the ldap module not be
imported anywhere else so that the unit tests will pass in the absence
of python-ldap.
""... | [
"def",
"get_ldap",
"(",
"cls",
",",
"global_options",
"=",
"None",
")",
":",
"if",
"cls",
".",
"ldap",
"is",
"None",
":",
"import",
"ldap",
".",
"filter",
"# Support for python-ldap < 2.0.6",
"try",
":",
"import",
"ldap",
".",
"dn",
"except",
"ImportError",
... | Returns the ldap module. The unit test harness will assign a mock object
to _LDAPConfig.ldap. It is imperative that the ldap module not be
imported anywhere else so that the unit tests will pass in the absence
of python-ldap. | [
"Returns",
"the",
"ldap",
"module",
".",
"The",
"unit",
"test",
"harness",
"will",
"assign",
"a",
"mock",
"object",
"to",
"_LDAPConfig",
".",
"ldap",
".",
"It",
"is",
"imperative",
"that",
"the",
"ldap",
"module",
"not",
"be",
"imported",
"anywhere",
"else... | 4d2458bd90c4539353c5bfd5ea793c1e59780ee8 | https://github.com/DheerendraRathor/django-auth-ldap-ng/blob/4d2458bd90c4539353c5bfd5ea793c1e59780ee8/django_auth_ldap/config.py#L52-L78 | train | Returns the ldap module. |
DheerendraRathor/django-auth-ldap-ng | django_auth_ldap/config.py | _LDAPConfig.get_logger | def get_logger(cls):
"""
Initializes and returns our logger instance.
"""
if cls.logger is None:
class NullHandler(logging.Handler):
def emit(self, record):
pass
cls.logger = logging.getLogger('django_auth_ldap')
cl... | python | def get_logger(cls):
"""
Initializes and returns our logger instance.
"""
if cls.logger is None:
class NullHandler(logging.Handler):
def emit(self, record):
pass
cls.logger = logging.getLogger('django_auth_ldap')
cl... | [
"def",
"get_logger",
"(",
"cls",
")",
":",
"if",
"cls",
".",
"logger",
"is",
"None",
":",
"class",
"NullHandler",
"(",
"logging",
".",
"Handler",
")",
":",
"def",
"emit",
"(",
"self",
",",
"record",
")",
":",
"pass",
"cls",
".",
"logger",
"=",
"log... | Initializes and returns our logger instance. | [
"Initializes",
"and",
"returns",
"our",
"logger",
"instance",
"."
] | 4d2458bd90c4539353c5bfd5ea793c1e59780ee8 | https://github.com/DheerendraRathor/django-auth-ldap-ng/blob/4d2458bd90c4539353c5bfd5ea793c1e59780ee8/django_auth_ldap/config.py#L81-L93 | train | Returns our logger instance. |
DheerendraRathor/django-auth-ldap-ng | django_auth_ldap/config.py | LDAPSearch.search_with_additional_term_string | def search_with_additional_term_string(self, filterstr):
"""
Returns a new search object with filterstr and-ed to the original filter
string. The caller is responsible for passing in a properly escaped
string.
"""
filterstr = u'(&%s%s)' % (self.filterstr, filterstr)
... | python | def search_with_additional_term_string(self, filterstr):
"""
Returns a new search object with filterstr and-ed to the original filter
string. The caller is responsible for passing in a properly escaped
string.
"""
filterstr = u'(&%s%s)' % (self.filterstr, filterstr)
... | [
"def",
"search_with_additional_term_string",
"(",
"self",
",",
"filterstr",
")",
":",
"filterstr",
"=",
"u'(&%s%s)'",
"%",
"(",
"self",
".",
"filterstr",
",",
"filterstr",
")",
"return",
"self",
".",
"__class__",
"(",
"self",
".",
"base_dn",
",",
"self",
"."... | Returns a new search object with filterstr and-ed to the original filter
string. The caller is responsible for passing in a properly escaped
string. | [
"Returns",
"a",
"new",
"search",
"object",
"with",
"filterstr",
"and",
"-",
"ed",
"to",
"the",
"original",
"filter",
"string",
".",
"The",
"caller",
"is",
"responsible",
"for",
"passing",
"in",
"a",
"properly",
"escaped",
"string",
"."
] | 4d2458bd90c4539353c5bfd5ea793c1e59780ee8 | https://github.com/DheerendraRathor/django-auth-ldap-ng/blob/4d2458bd90c4539353c5bfd5ea793c1e59780ee8/django_auth_ldap/config.py#L135-L143 | train | Returns a new search object with filterstr and - ed to the original filter
string. |
DheerendraRathor/django-auth-ldap-ng | django_auth_ldap/config.py | LDAPSearch.execute | def execute(self, connection, filterargs=(), escape=True):
"""
Executes the search on the given connection (an LDAPObject). filterargs
is an object that will be used for expansion of the filter string.
If escape is True, values in filterargs will be escaped.
The python-ldap libr... | python | def execute(self, connection, filterargs=(), escape=True):
"""
Executes the search on the given connection (an LDAPObject). filterargs
is an object that will be used for expansion of the filter string.
If escape is True, values in filterargs will be escaped.
The python-ldap libr... | [
"def",
"execute",
"(",
"self",
",",
"connection",
",",
"filterargs",
"=",
"(",
")",
",",
"escape",
"=",
"True",
")",
":",
"if",
"escape",
":",
"filterargs",
"=",
"self",
".",
"_escape_filterargs",
"(",
"filterargs",
")",
"try",
":",
"filterstr",
"=",
"... | Executes the search on the given connection (an LDAPObject). filterargs
is an object that will be used for expansion of the filter string.
If escape is True, values in filterargs will be escaped.
The python-ldap library returns utf8-encoded strings. For the sake of
sanity, this method w... | [
"Executes",
"the",
"search",
"on",
"the",
"given",
"connection",
"(",
"an",
"LDAPObject",
")",
".",
"filterargs",
"is",
"an",
"object",
"that",
"will",
"be",
"used",
"for",
"expansion",
"of",
"the",
"filter",
"string",
".",
"If",
"escape",
"is",
"True",
... | 4d2458bd90c4539353c5bfd5ea793c1e59780ee8 | https://github.com/DheerendraRathor/django-auth-ldap-ng/blob/4d2458bd90c4539353c5bfd5ea793c1e59780ee8/django_auth_ldap/config.py#L145-L168 | train | Executes the search on the given connection. |
DheerendraRathor/django-auth-ldap-ng | django_auth_ldap/config.py | LDAPSearch._begin | def _begin(self, connection, filterargs=(), escape=True):
"""
Begins an asynchronous search and returns the message id to retrieve
the results.
filterargs is an object that will be used for expansion of the filter
string. If escape is True, values in filterargs will be escaped.
... | python | def _begin(self, connection, filterargs=(), escape=True):
"""
Begins an asynchronous search and returns the message id to retrieve
the results.
filterargs is an object that will be used for expansion of the filter
string. If escape is True, values in filterargs will be escaped.
... | [
"def",
"_begin",
"(",
"self",
",",
"connection",
",",
"filterargs",
"=",
"(",
")",
",",
"escape",
"=",
"True",
")",
":",
"if",
"escape",
":",
"filterargs",
"=",
"self",
".",
"_escape_filterargs",
"(",
"filterargs",
")",
"try",
":",
"filterstr",
"=",
"s... | Begins an asynchronous search and returns the message id to retrieve
the results.
filterargs is an object that will be used for expansion of the filter
string. If escape is True, values in filterargs will be escaped. | [
"Begins",
"an",
"asynchronous",
"search",
"and",
"returns",
"the",
"message",
"id",
"to",
"retrieve",
"the",
"results",
"."
] | 4d2458bd90c4539353c5bfd5ea793c1e59780ee8 | https://github.com/DheerendraRathor/django-auth-ldap-ng/blob/4d2458bd90c4539353c5bfd5ea793c1e59780ee8/django_auth_ldap/config.py#L170-L191 | train | Starts an asynchronous search and returns the message id to retrieve
the results. |
DheerendraRathor/django-auth-ldap-ng | django_auth_ldap/config.py | LDAPSearch._results | def _results(self, connection, msgid):
"""
Returns the result of a previous asynchronous query.
"""
try:
kind, results = connection.result(msgid)
if kind != ldap.RES_SEARCH_RESULT:
results = []
except ldap.LDAPError as e:
result... | python | def _results(self, connection, msgid):
"""
Returns the result of a previous asynchronous query.
"""
try:
kind, results = connection.result(msgid)
if kind != ldap.RES_SEARCH_RESULT:
results = []
except ldap.LDAPError as e:
result... | [
"def",
"_results",
"(",
"self",
",",
"connection",
",",
"msgid",
")",
":",
"try",
":",
"kind",
",",
"results",
"=",
"connection",
".",
"result",
"(",
"msgid",
")",
"if",
"kind",
"!=",
"ldap",
".",
"RES_SEARCH_RESULT",
":",
"results",
"=",
"[",
"]",
"... | Returns the result of a previous asynchronous query. | [
"Returns",
"the",
"result",
"of",
"a",
"previous",
"asynchronous",
"query",
"."
] | 4d2458bd90c4539353c5bfd5ea793c1e59780ee8 | https://github.com/DheerendraRathor/django-auth-ldap-ng/blob/4d2458bd90c4539353c5bfd5ea793c1e59780ee8/django_auth_ldap/config.py#L193-L205 | train | Returns the result of a previous asynchronous query. |
DheerendraRathor/django-auth-ldap-ng | django_auth_ldap/config.py | LDAPSearch._escape_filterargs | def _escape_filterargs(self, filterargs):
"""
Escapes values in filterargs.
filterargs is a value suitable for Django's string formatting operator
(%), which means it's either a tuple or a dict. This return a new tuple
or dict with all values escaped for use in filter strings.
... | python | def _escape_filterargs(self, filterargs):
"""
Escapes values in filterargs.
filterargs is a value suitable for Django's string formatting operator
(%), which means it's either a tuple or a dict. This return a new tuple
or dict with all values escaped for use in filter strings.
... | [
"def",
"_escape_filterargs",
"(",
"self",
",",
"filterargs",
")",
":",
"if",
"isinstance",
"(",
"filterargs",
",",
"tuple",
")",
":",
"filterargs",
"=",
"tuple",
"(",
"self",
".",
"ldap",
".",
"filter",
".",
"escape_filter_chars",
"(",
"value",
")",
"for",... | Escapes values in filterargs.
filterargs is a value suitable for Django's string formatting operator
(%), which means it's either a tuple or a dict. This return a new tuple
or dict with all values escaped for use in filter strings. | [
"Escapes",
"values",
"in",
"filterargs",
"."
] | 4d2458bd90c4539353c5bfd5ea793c1e59780ee8 | https://github.com/DheerendraRathor/django-auth-ldap-ng/blob/4d2458bd90c4539353c5bfd5ea793c1e59780ee8/django_auth_ldap/config.py#L207-L225 | train | Escapes values in filterargs. |
DheerendraRathor/django-auth-ldap-ng | django_auth_ldap/config.py | LDAPSearch._process_results | def _process_results(self, results):
"""
Returns a sanitized copy of raw LDAP results. This scrubs out
references, decodes utf8, normalizes DNs, etc.
"""
results = [r for r in results if r[0] is not None]
results = _DeepStringCoder('utf-8').decode(results)
# The ... | python | def _process_results(self, results):
"""
Returns a sanitized copy of raw LDAP results. This scrubs out
references, decodes utf8, normalizes DNs, etc.
"""
results = [r for r in results if r[0] is not None]
results = _DeepStringCoder('utf-8').decode(results)
# The ... | [
"def",
"_process_results",
"(",
"self",
",",
"results",
")",
":",
"results",
"=",
"[",
"r",
"for",
"r",
"in",
"results",
"if",
"r",
"[",
"0",
"]",
"is",
"not",
"None",
"]",
"results",
"=",
"_DeepStringCoder",
"(",
"'utf-8'",
")",
".",
"decode",
"(",
... | Returns a sanitized copy of raw LDAP results. This scrubs out
references, decodes utf8, normalizes DNs, etc. | [
"Returns",
"a",
"sanitized",
"copy",
"of",
"raw",
"LDAP",
"results",
".",
"This",
"scrubs",
"out",
"references",
"decodes",
"utf8",
"normalizes",
"DNs",
"etc",
"."
] | 4d2458bd90c4539353c5bfd5ea793c1e59780ee8 | https://github.com/DheerendraRathor/django-auth-ldap-ng/blob/4d2458bd90c4539353c5bfd5ea793c1e59780ee8/django_auth_ldap/config.py#L227-L243 | train | Returns a sanitized copy of raw LDAP results. This scrubs out
references decodes utf8 normalizes DNs and normalizes DNs etc. |
ehansis/ozelot | ozelot/client.py | Client.store_password | def store_password(params, password):
"""Store the password for a database connection using :mod:`keyring`
Use the ``user`` field as the user name and ``<host>:<driver>`` as service name.
Args:
params (dict): database configuration, as defined in :mod:`ozelot.config`
pa... | python | def store_password(params, password):
"""Store the password for a database connection using :mod:`keyring`
Use the ``user`` field as the user name and ``<host>:<driver>`` as service name.
Args:
params (dict): database configuration, as defined in :mod:`ozelot.config`
pa... | [
"def",
"store_password",
"(",
"params",
",",
"password",
")",
":",
"user_name",
"=",
"params",
"[",
"'user'",
"]",
"service_name",
"=",
"params",
"[",
"'host'",
"]",
"+",
"':'",
"+",
"params",
"[",
"'driver'",
"]",
"keyring",
".",
"set_password",
"(",
"s... | Store the password for a database connection using :mod:`keyring`
Use the ``user`` field as the user name and ``<host>:<driver>`` as service name.
Args:
params (dict): database configuration, as defined in :mod:`ozelot.config`
password (str): password to store | [
"Store",
"the",
"password",
"for",
"a",
"database",
"connection",
"using",
":",
"mod",
":",
"keyring"
] | 948675e02eb6fca940450f5cb814f53e97159e5b | https://github.com/ehansis/ozelot/blob/948675e02eb6fca940450f5cb814f53e97159e5b/ozelot/client.py#L102-L115 | train | Store the password for a database connection using the keyring. |
ehansis/ozelot | ozelot/client.py | Client._get_password | def _get_password(params):
"""Get the password for a database connection from :mod:`keyring`
Args:
params (dict): database configuration, as defined in :mod:`ozelot.config`
Returns:
str: password
"""
user_name = params['user']
service_name = para... | python | def _get_password(params):
"""Get the password for a database connection from :mod:`keyring`
Args:
params (dict): database configuration, as defined in :mod:`ozelot.config`
Returns:
str: password
"""
user_name = params['user']
service_name = para... | [
"def",
"_get_password",
"(",
"params",
")",
":",
"user_name",
"=",
"params",
"[",
"'user'",
"]",
"service_name",
"=",
"params",
"[",
"'host'",
"]",
"+",
"':'",
"+",
"params",
"[",
"'driver'",
"]",
"return",
"keyring",
".",
"get_password",
"(",
"service_nam... | Get the password for a database connection from :mod:`keyring`
Args:
params (dict): database configuration, as defined in :mod:`ozelot.config`
Returns:
str: password | [
"Get",
"the",
"password",
"for",
"a",
"database",
"connection",
"from",
":",
"mod",
":",
"keyring"
] | 948675e02eb6fca940450f5cb814f53e97159e5b | https://github.com/ehansis/ozelot/blob/948675e02eb6fca940450f5cb814f53e97159e5b/ozelot/client.py#L118-L130 | train | Get the password for a database connection from keyring |
ehansis/ozelot | ozelot/client.py | Client.get_connection_string | def get_connection_string(params, hide_password=True):
"""Get a database connection string
Args:
params (dict): database configuration, as defined in :mod:`ozelot.config`
hide_password (bool): if True, the password is hidden in the returned string
(use this for l... | python | def get_connection_string(params, hide_password=True):
"""Get a database connection string
Args:
params (dict): database configuration, as defined in :mod:`ozelot.config`
hide_password (bool): if True, the password is hidden in the returned string
(use this for l... | [
"def",
"get_connection_string",
"(",
"params",
",",
"hide_password",
"=",
"True",
")",
":",
"connection_string",
"=",
"params",
"[",
"'driver'",
"]",
"+",
"'://'",
"user",
"=",
"params",
".",
"get",
"(",
"'user'",
",",
"None",
")",
"password",
"=",
"params... | Get a database connection string
Args:
params (dict): database configuration, as defined in :mod:`ozelot.config`
hide_password (bool): if True, the password is hidden in the returned string
(use this for logging purposes).
Returns:
str: connection st... | [
"Get",
"a",
"database",
"connection",
"string"
] | 948675e02eb6fca940450f5cb814f53e97159e5b | https://github.com/ehansis/ozelot/blob/948675e02eb6fca940450f5cb814f53e97159e5b/ozelot/client.py#L133-L187 | train | Get a database connection string from a dictionary of parameters. |
ehansis/ozelot | ozelot/client.py | Client.df_query | def df_query(self, query, with_labels=False):
"""
Run a :mod:`sqlalchemy` query and return result as a :class:`pandas.DataFrame`
Args:
query (sqlalchemy.orm.query.Query): query object, usually generated by :func:`session.query()` in
an :class:`sqlalchemy.orm.session... | python | def df_query(self, query, with_labels=False):
"""
Run a :mod:`sqlalchemy` query and return result as a :class:`pandas.DataFrame`
Args:
query (sqlalchemy.orm.query.Query): query object, usually generated by :func:`session.query()` in
an :class:`sqlalchemy.orm.session... | [
"def",
"df_query",
"(",
"self",
",",
"query",
",",
"with_labels",
"=",
"False",
")",
":",
"import",
"pandas",
"as",
"pd",
"if",
"with_labels",
":",
"query",
"=",
"query",
".",
"with_labels",
"(",
")",
"# compile sql statement, including arguments",
"statement",
... | Run a :mod:`sqlalchemy` query and return result as a :class:`pandas.DataFrame`
Args:
query (sqlalchemy.orm.query.Query): query object, usually generated by :func:`session.query()` in
an :class:`sqlalchemy.orm.session.Session`
with_labels (bool): A query for fields with... | [
"Run",
"a",
":",
"mod",
":",
"sqlalchemy",
"query",
"and",
"return",
"result",
"as",
"a",
":",
"class",
":",
"pandas",
".",
"DataFrame"
] | 948675e02eb6fca940450f5cb814f53e97159e5b | https://github.com/ehansis/ozelot/blob/948675e02eb6fca940450f5cb814f53e97159e5b/ozelot/client.py#L189-L215 | train | Run a sqlalchemy query and return a pandas. DataFrame |
zsimic/runez | src/runez/path.py | basename | def basename(path, extension_marker="."):
"""
:param str|None path: Path to consider
:param str|None extension_marker: Trim file extension based on specified character
:return str: Basename part of path, without extension (if 'extension_marker' provided)
"""
result = os.path.basename(path or "")... | python | def basename(path, extension_marker="."):
"""
:param str|None path: Path to consider
:param str|None extension_marker: Trim file extension based on specified character
:return str: Basename part of path, without extension (if 'extension_marker' provided)
"""
result = os.path.basename(path or "")... | [
"def",
"basename",
"(",
"path",
",",
"extension_marker",
"=",
"\".\"",
")",
":",
"result",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"path",
"or",
"\"\"",
")",
"if",
"extension_marker",
":",
"pre",
",",
"_",
",",
"post",
"=",
"result",
".",
"rpar... | :param str|None path: Path to consider
:param str|None extension_marker: Trim file extension based on specified character
:return str: Basename part of path, without extension (if 'extension_marker' provided) | [
":",
"param",
"str|None",
"path",
":",
"Path",
"to",
"consider",
":",
"param",
"str|None",
"extension_marker",
":",
"Trim",
"file",
"extension",
"based",
"on",
"specified",
"character",
":",
"return",
"str",
":",
"Basename",
"part",
"of",
"path",
"without",
... | 14363b719a1aae1528859a501a22d075ce0abfcc | https://github.com/zsimic/runez/blob/14363b719a1aae1528859a501a22d075ce0abfcc/src/runez/path.py#L15-L26 | train | Returns the basename of the path without the extension. |
zsimic/runez | src/runez/path.py | ensure_folder | def ensure_folder(path, folder=False, fatal=True, logger=LOG.debug, dryrun=None):
"""
:param str|None path: Path to file or folder
:param bool folder: If True, 'path' refers to a folder (file otherwise)
:param bool|None fatal: Abort execution on failure if True
:param callable|None logger: Logger to... | python | def ensure_folder(path, folder=False, fatal=True, logger=LOG.debug, dryrun=None):
"""
:param str|None path: Path to file or folder
:param bool folder: If True, 'path' refers to a folder (file otherwise)
:param bool|None fatal: Abort execution on failure if True
:param callable|None logger: Logger to... | [
"def",
"ensure_folder",
"(",
"path",
",",
"folder",
"=",
"False",
",",
"fatal",
"=",
"True",
",",
"logger",
"=",
"LOG",
".",
"debug",
",",
"dryrun",
"=",
"None",
")",
":",
"if",
"not",
"path",
":",
"return",
"0",
"if",
"folder",
":",
"folder",
"=",... | :param str|None path: Path to file or folder
:param bool folder: If True, 'path' refers to a folder (file otherwise)
:param bool|None fatal: Abort execution on failure if True
:param callable|None logger: Logger to use
:param bool|None dryrun: If specified, override global is_dryrun()
:return int: 1... | [
":",
"param",
"str|None",
"path",
":",
"Path",
"to",
"file",
"or",
"folder",
":",
"param",
"bool",
"folder",
":",
"If",
"True",
"path",
"refers",
"to",
"a",
"folder",
"(",
"file",
"otherwise",
")",
":",
"param",
"bool|None",
"fatal",
":",
"Abort",
"exe... | 14363b719a1aae1528859a501a22d075ce0abfcc | https://github.com/zsimic/runez/blob/14363b719a1aae1528859a501a22d075ce0abfcc/src/runez/path.py#L29-L67 | train | Ensures that the given path refers to a folder. |
zsimic/runez | src/runez/path.py | parent_folder | def parent_folder(path, base=None):
"""
:param str|None path: Path to file or folder
:param str|None base: Base folder to use for relative paths (default: current working dir)
:return str: Absolute path of parent folder of 'path'
"""
return path and os.path.dirname(resolved_path(path, base=base)... | python | def parent_folder(path, base=None):
"""
:param str|None path: Path to file or folder
:param str|None base: Base folder to use for relative paths (default: current working dir)
:return str: Absolute path of parent folder of 'path'
"""
return path and os.path.dirname(resolved_path(path, base=base)... | [
"def",
"parent_folder",
"(",
"path",
",",
"base",
"=",
"None",
")",
":",
"return",
"path",
"and",
"os",
".",
"path",
".",
"dirname",
"(",
"resolved_path",
"(",
"path",
",",
"base",
"=",
"base",
")",
")"
] | :param str|None path: Path to file or folder
:param str|None base: Base folder to use for relative paths (default: current working dir)
:return str: Absolute path of parent folder of 'path' | [
":",
"param",
"str|None",
"path",
":",
"Path",
"to",
"file",
"or",
"folder",
":",
"param",
"str|None",
"base",
":",
"Base",
"folder",
"to",
"use",
"for",
"relative",
"paths",
"(",
"default",
":",
"current",
"working",
"dir",
")",
":",
"return",
"str",
... | 14363b719a1aae1528859a501a22d075ce0abfcc | https://github.com/zsimic/runez/blob/14363b719a1aae1528859a501a22d075ce0abfcc/src/runez/path.py#L70-L76 | train | Returns the absolute path of the parent folder of path. |
geminipy/geminipy | geminipy/__init__.py | Geminipy.pubticker | def pubticker(self, symbol='btcusd'):
"""Send a request for latest ticker info, return the response."""
url = self.base_url + '/v1/pubticker/' + symbol
return requests.get(url) | python | def pubticker(self, symbol='btcusd'):
"""Send a request for latest ticker info, return the response."""
url = self.base_url + '/v1/pubticker/' + symbol
return requests.get(url) | [
"def",
"pubticker",
"(",
"self",
",",
"symbol",
"=",
"'btcusd'",
")",
":",
"url",
"=",
"self",
".",
"base_url",
"+",
"'/v1/pubticker/'",
"+",
"symbol",
"return",
"requests",
".",
"get",
"(",
"url",
")"
] | Send a request for latest ticker info, return the response. | [
"Send",
"a",
"request",
"for",
"latest",
"ticker",
"info",
"return",
"the",
"response",
"."
] | 0d83fe225b746ac4c8bb800aa6091e1b606231e8 | https://github.com/geminipy/geminipy/blob/0d83fe225b746ac4c8bb800aa6091e1b606231e8/geminipy/__init__.py#L50-L54 | train | Send a request for latest ticker info return the response. |
geminipy/geminipy | geminipy/__init__.py | Geminipy.book | def book(self, symbol='btcusd', limit_bids=0, limit_asks=0):
"""
Send a request to get the public order book, return the response.
Arguments:
symbol -- currency symbol (default 'btcusd')
limit_bids -- limit the number of bids returned (default 0)
limit_asks -- limit the ... | python | def book(self, symbol='btcusd', limit_bids=0, limit_asks=0):
"""
Send a request to get the public order book, return the response.
Arguments:
symbol -- currency symbol (default 'btcusd')
limit_bids -- limit the number of bids returned (default 0)
limit_asks -- limit the ... | [
"def",
"book",
"(",
"self",
",",
"symbol",
"=",
"'btcusd'",
",",
"limit_bids",
"=",
"0",
",",
"limit_asks",
"=",
"0",
")",
":",
"url",
"=",
"self",
".",
"base_url",
"+",
"'/v1/book/'",
"+",
"symbol",
"params",
"=",
"{",
"'limit_bids'",
":",
"limit_bids... | Send a request to get the public order book, return the response.
Arguments:
symbol -- currency symbol (default 'btcusd')
limit_bids -- limit the number of bids returned (default 0)
limit_asks -- limit the number of asks returned (default 0) | [
"Send",
"a",
"request",
"to",
"get",
"the",
"public",
"order",
"book",
"return",
"the",
"response",
"."
] | 0d83fe225b746ac4c8bb800aa6091e1b606231e8 | https://github.com/geminipy/geminipy/blob/0d83fe225b746ac4c8bb800aa6091e1b606231e8/geminipy/__init__.py#L56-L71 | train | Send a request to get the public order book |
geminipy/geminipy | geminipy/__init__.py | Geminipy.trades | def trades(self, symbol='btcusd', since=0, limit_trades=50,
include_breaks=0):
"""
Send a request to get all public trades, return the response.
Arguments:
symbol -- currency symbol (default 'btcusd')
since -- only return trades after this unix timestamp (default ... | python | def trades(self, symbol='btcusd', since=0, limit_trades=50,
include_breaks=0):
"""
Send a request to get all public trades, return the response.
Arguments:
symbol -- currency symbol (default 'btcusd')
since -- only return trades after this unix timestamp (default ... | [
"def",
"trades",
"(",
"self",
",",
"symbol",
"=",
"'btcusd'",
",",
"since",
"=",
"0",
",",
"limit_trades",
"=",
"50",
",",
"include_breaks",
"=",
"0",
")",
":",
"url",
"=",
"self",
".",
"base_url",
"+",
"'/v1/trades/'",
"+",
"symbol",
"params",
"=",
... | Send a request to get all public trades, return the response.
Arguments:
symbol -- currency symbol (default 'btcusd')
since -- only return trades after this unix timestamp (default 0)
limit_trades -- maximum number of trades to return (default 50).
include_breaks -- whether to d... | [
"Send",
"a",
"request",
"to",
"get",
"all",
"public",
"trades",
"return",
"the",
"response",
"."
] | 0d83fe225b746ac4c8bb800aa6091e1b606231e8 | https://github.com/geminipy/geminipy/blob/0d83fe225b746ac4c8bb800aa6091e1b606231e8/geminipy/__init__.py#L73-L91 | train | Send a request to get all public trades |
geminipy/geminipy | geminipy/__init__.py | Geminipy.auction | def auction(self, symbol='btcusd'):
"""Send a request for latest auction info, return the response."""
url = self.base_url + '/v1/auction/' + symbol
return requests.get(url) | python | def auction(self, symbol='btcusd'):
"""Send a request for latest auction info, return the response."""
url = self.base_url + '/v1/auction/' + symbol
return requests.get(url) | [
"def",
"auction",
"(",
"self",
",",
"symbol",
"=",
"'btcusd'",
")",
":",
"url",
"=",
"self",
".",
"base_url",
"+",
"'/v1/auction/'",
"+",
"symbol",
"return",
"requests",
".",
"get",
"(",
"url",
")"
] | Send a request for latest auction info, return the response. | [
"Send",
"a",
"request",
"for",
"latest",
"auction",
"info",
"return",
"the",
"response",
"."
] | 0d83fe225b746ac4c8bb800aa6091e1b606231e8 | https://github.com/geminipy/geminipy/blob/0d83fe225b746ac4c8bb800aa6091e1b606231e8/geminipy/__init__.py#L93-L97 | train | Send a request for latest auction info return the response |
geminipy/geminipy | geminipy/__init__.py | Geminipy.auction_history | def auction_history(self, symbol='btcusd', since=0,
limit_auction_results=50, include_indicative=1):
"""
Send a request for auction history info, return the response.
Arguments:
symbol -- currency symbol (default 'btcusd')
since -- only return auction eve... | python | def auction_history(self, symbol='btcusd', since=0,
limit_auction_results=50, include_indicative=1):
"""
Send a request for auction history info, return the response.
Arguments:
symbol -- currency symbol (default 'btcusd')
since -- only return auction eve... | [
"def",
"auction_history",
"(",
"self",
",",
"symbol",
"=",
"'btcusd'",
",",
"since",
"=",
"0",
",",
"limit_auction_results",
"=",
"50",
",",
"include_indicative",
"=",
"1",
")",
":",
"url",
"=",
"self",
".",
"base_url",
"+",
"'/v1/auction/'",
"+",
"symbol"... | Send a request for auction history info, return the response.
Arguments:
symbol -- currency symbol (default 'btcusd')
since -- only return auction events after this timestamp (default 0)
limit_auction_results -- maximum number of auction events to return
... | [
"Send",
"a",
"request",
"for",
"auction",
"history",
"info",
"return",
"the",
"response",
"."
] | 0d83fe225b746ac4c8bb800aa6091e1b606231e8 | https://github.com/geminipy/geminipy/blob/0d83fe225b746ac4c8bb800aa6091e1b606231e8/geminipy/__init__.py#L99-L119 | train | Send a request to get auction history info |
geminipy/geminipy | geminipy/__init__.py | Geminipy.new_order | def new_order(self, amount, price, side, client_order_id=None,
symbol='btcusd', type='exchange limit', options=None):
"""
Send a request to place an order, return the response.
Arguments:
amount -- quoted decimal amount of BTC to purchase
price -- quoted decima... | python | def new_order(self, amount, price, side, client_order_id=None,
symbol='btcusd', type='exchange limit', options=None):
"""
Send a request to place an order, return the response.
Arguments:
amount -- quoted decimal amount of BTC to purchase
price -- quoted decima... | [
"def",
"new_order",
"(",
"self",
",",
"amount",
",",
"price",
",",
"side",
",",
"client_order_id",
"=",
"None",
",",
"symbol",
"=",
"'btcusd'",
",",
"type",
"=",
"'exchange limit'",
",",
"options",
"=",
"None",
")",
":",
"request",
"=",
"'/v1/order/new'",
... | Send a request to place an order, return the response.
Arguments:
amount -- quoted decimal amount of BTC to purchase
price -- quoted decimal amount of USD to spend per BTC
side -- 'buy' or 'sell'
client_order_id -- an optional client-specified order id (default None)
sym... | [
"Send",
"a",
"request",
"to",
"place",
"an",
"order",
"return",
"the",
"response",
"."
] | 0d83fe225b746ac4c8bb800aa6091e1b606231e8 | https://github.com/geminipy/geminipy/blob/0d83fe225b746ac4c8bb800aa6091e1b606231e8/geminipy/__init__.py#L122-L153 | train | Send a request to place an order |
geminipy/geminipy | geminipy/__init__.py | Geminipy.cancel_order | def cancel_order(self, order_id):
"""
Send a request to cancel an order, return the response.
Arguments:
order_id - the order id to cancel
"""
request = '/v1/order/cancel'
url = self.base_url + request
params = {
'request': request,
... | python | def cancel_order(self, order_id):
"""
Send a request to cancel an order, return the response.
Arguments:
order_id - the order id to cancel
"""
request = '/v1/order/cancel'
url = self.base_url + request
params = {
'request': request,
... | [
"def",
"cancel_order",
"(",
"self",
",",
"order_id",
")",
":",
"request",
"=",
"'/v1/order/cancel'",
"url",
"=",
"self",
".",
"base_url",
"+",
"request",
"params",
"=",
"{",
"'request'",
":",
"request",
",",
"'nonce'",
":",
"self",
".",
"get_nonce",
"(",
... | Send a request to cancel an order, return the response.
Arguments:
order_id - the order id to cancel | [
"Send",
"a",
"request",
"to",
"cancel",
"an",
"order",
"return",
"the",
"response",
"."
] | 0d83fe225b746ac4c8bb800aa6091e1b606231e8 | https://github.com/geminipy/geminipy/blob/0d83fe225b746ac4c8bb800aa6091e1b606231e8/geminipy/__init__.py#L155-L170 | train | Send a request to cancel an order |
geminipy/geminipy | geminipy/__init__.py | Geminipy.past_trades | def past_trades(self, symbol='btcusd', limit_trades=50, timestamp=0):
"""
Send a trade history request, return the response.
Arguements:
symbol -- currency symbol (default 'btcusd')
limit_trades -- maximum number of trades to return (default 50)
timestamp -- only return ... | python | def past_trades(self, symbol='btcusd', limit_trades=50, timestamp=0):
"""
Send a trade history request, return the response.
Arguements:
symbol -- currency symbol (default 'btcusd')
limit_trades -- maximum number of trades to return (default 50)
timestamp -- only return ... | [
"def",
"past_trades",
"(",
"self",
",",
"symbol",
"=",
"'btcusd'",
",",
"limit_trades",
"=",
"50",
",",
"timestamp",
"=",
"0",
")",
":",
"request",
"=",
"'/v1/mytrades'",
"url",
"=",
"self",
".",
"base_url",
"+",
"request",
"params",
"=",
"{",
"'request'... | Send a trade history request, return the response.
Arguements:
symbol -- currency symbol (default 'btcusd')
limit_trades -- maximum number of trades to return (default 50)
timestamp -- only return trades after this unix timestamp (default 0) | [
"Send",
"a",
"trade",
"history",
"request",
"return",
"the",
"response",
"."
] | 0d83fe225b746ac4c8bb800aa6091e1b606231e8 | https://github.com/geminipy/geminipy/blob/0d83fe225b746ac4c8bb800aa6091e1b606231e8/geminipy/__init__.py#L222-L241 | train | Send a trade history request to get the next set of trades. |
geminipy/geminipy | geminipy/__init__.py | Geminipy.tradevolume | def tradevolume(self):
"""Send a request to get your trade volume, return the response."""
request = '/v1/tradevolume'
url = self.base_url + request
params = {
'request': request,
'nonce': self.get_nonce()
}
return requests.post(url, headers=self.... | python | def tradevolume(self):
"""Send a request to get your trade volume, return the response."""
request = '/v1/tradevolume'
url = self.base_url + request
params = {
'request': request,
'nonce': self.get_nonce()
}
return requests.post(url, headers=self.... | [
"def",
"tradevolume",
"(",
"self",
")",
":",
"request",
"=",
"'/v1/tradevolume'",
"url",
"=",
"self",
".",
"base_url",
"+",
"request",
"params",
"=",
"{",
"'request'",
":",
"request",
",",
"'nonce'",
":",
"self",
".",
"get_nonce",
"(",
")",
"}",
"return"... | Send a request to get your trade volume, return the response. | [
"Send",
"a",
"request",
"to",
"get",
"your",
"trade",
"volume",
"return",
"the",
"response",
"."
] | 0d83fe225b746ac4c8bb800aa6091e1b606231e8 | https://github.com/geminipy/geminipy/blob/0d83fe225b746ac4c8bb800aa6091e1b606231e8/geminipy/__init__.py#L243-L252 | train | Send a request to get your trade volume return the response. |
geminipy/geminipy | geminipy/__init__.py | Geminipy.newAddress | def newAddress(self, currency='btc', label=''):
"""
Send a request for a new cryptocurrency deposit address
with an optional label. Return the response.
Arguements:
currency -- a Gemini supported cryptocurrency (btc, eth)
label -- optional label for the deposit address
... | python | def newAddress(self, currency='btc', label=''):
"""
Send a request for a new cryptocurrency deposit address
with an optional label. Return the response.
Arguements:
currency -- a Gemini supported cryptocurrency (btc, eth)
label -- optional label for the deposit address
... | [
"def",
"newAddress",
"(",
"self",
",",
"currency",
"=",
"'btc'",
",",
"label",
"=",
"''",
")",
":",
"request",
"=",
"'/v1/deposit/'",
"+",
"currency",
"+",
"'/newAddress'",
"url",
"=",
"self",
".",
"base_url",
"+",
"request",
"params",
"=",
"{",
"'reques... | Send a request for a new cryptocurrency deposit address
with an optional label. Return the response.
Arguements:
currency -- a Gemini supported cryptocurrency (btc, eth)
label -- optional label for the deposit address | [
"Send",
"a",
"request",
"for",
"a",
"new",
"cryptocurrency",
"deposit",
"address",
"with",
"an",
"optional",
"label",
".",
"Return",
"the",
"response",
"."
] | 0d83fe225b746ac4c8bb800aa6091e1b606231e8 | https://github.com/geminipy/geminipy/blob/0d83fe225b746ac4c8bb800aa6091e1b606231e8/geminipy/__init__.py#L265-L284 | train | Send a request to create a new cryptocurrency deposit address |
geminipy/geminipy | geminipy/__init__.py | Geminipy.prepare | def prepare(self, params):
"""
Prepare, return the required HTTP headers.
Base 64 encode the parameters, sign it with the secret key,
create the HTTP headers, return the whole payload.
Arguments:
params -- a dictionary of parameters
"""
jsonparams = json... | python | def prepare(self, params):
"""
Prepare, return the required HTTP headers.
Base 64 encode the parameters, sign it with the secret key,
create the HTTP headers, return the whole payload.
Arguments:
params -- a dictionary of parameters
"""
jsonparams = json... | [
"def",
"prepare",
"(",
"self",
",",
"params",
")",
":",
"jsonparams",
"=",
"json",
".",
"dumps",
"(",
"params",
")",
"payload",
"=",
"base64",
".",
"b64encode",
"(",
"jsonparams",
".",
"encode",
"(",
")",
")",
"signature",
"=",
"hmac",
".",
"new",
"(... | Prepare, return the required HTTP headers.
Base 64 encode the parameters, sign it with the secret key,
create the HTTP headers, return the whole payload.
Arguments:
params -- a dictionary of parameters | [
"Prepare",
"return",
"the",
"required",
"HTTP",
"headers",
"."
] | 0d83fe225b746ac4c8bb800aa6091e1b606231e8 | https://github.com/geminipy/geminipy/blob/0d83fe225b746ac4c8bb800aa6091e1b606231e8/geminipy/__init__.py#L301-L318 | train | Prepare the parameters and return the required HTTP headers. |
kataev/flake8-rst | flake8_rst/sourceblock.py | SourceBlock.merge | def merge(cls, source_blocks):
"""Merge multiple SourceBlocks together"""
if len(source_blocks) == 1:
return source_blocks[0]
source_blocks.sort(key=operator.attrgetter('start_line_number'))
main_block = source_blocks[0]
boot_lines = main_block.boot_lines
so... | python | def merge(cls, source_blocks):
"""Merge multiple SourceBlocks together"""
if len(source_blocks) == 1:
return source_blocks[0]
source_blocks.sort(key=operator.attrgetter('start_line_number'))
main_block = source_blocks[0]
boot_lines = main_block.boot_lines
so... | [
"def",
"merge",
"(",
"cls",
",",
"source_blocks",
")",
":",
"if",
"len",
"(",
"source_blocks",
")",
"==",
"1",
":",
"return",
"source_blocks",
"[",
"0",
"]",
"source_blocks",
".",
"sort",
"(",
"key",
"=",
"operator",
".",
"attrgetter",
"(",
"'start_line_... | Merge multiple SourceBlocks together | [
"Merge",
"multiple",
"SourceBlocks",
"together"
] | ca6d41c7a309b9e8cd4fa6f428b82db96b6a986f | https://github.com/kataev/flake8-rst/blob/ca6d41c7a309b9e8cd4fa6f428b82db96b6a986f/flake8_rst/sourceblock.py#L72-L84 | train | Merge multiple SourceBlocks together |
kataev/flake8-rst | flake8_rst/sourceblock.py | SourceBlock.complete_block | def complete_block(self):
"""Return code lines **with** bootstrap"""
return "".join(line[SOURCE] for line in self._boot_lines + self._source_lines) | python | def complete_block(self):
"""Return code lines **with** bootstrap"""
return "".join(line[SOURCE] for line in self._boot_lines + self._source_lines) | [
"def",
"complete_block",
"(",
"self",
")",
":",
"return",
"\"\"",
".",
"join",
"(",
"line",
"[",
"SOURCE",
"]",
"for",
"line",
"in",
"self",
".",
"_boot_lines",
"+",
"self",
".",
"_source_lines",
")"
] | Return code lines **with** bootstrap | [
"Return",
"code",
"lines",
"**",
"with",
"**",
"bootstrap"
] | ca6d41c7a309b9e8cd4fa6f428b82db96b6a986f | https://github.com/kataev/flake8-rst/blob/ca6d41c7a309b9e8cd4fa6f428b82db96b6a986f/flake8_rst/sourceblock.py#L110-L112 | train | Return code lines with bootstrap and source lines |
ehansis/ozelot | examples/superheroes/superheroes/analysis.py | character_summary_table | def character_summary_table():
"""Export a table listing all characters and their data
Output is a CSV file and an Excel file, saved as 'characters.csv/.xlsx' in the output directory.
"""
# a database client/session to run queries in
cl = client.get_client()
session = cl.create_session()
#... | python | def character_summary_table():
"""Export a table listing all characters and their data
Output is a CSV file and an Excel file, saved as 'characters.csv/.xlsx' in the output directory.
"""
# a database client/session to run queries in
cl = client.get_client()
session = cl.create_session()
#... | [
"def",
"character_summary_table",
"(",
")",
":",
"# a database client/session to run queries in",
"cl",
"=",
"client",
".",
"get_client",
"(",
")",
"session",
"=",
"cl",
".",
"create_session",
"(",
")",
"# Define the query. Note that we need to rename the two joined-in name c... | Export a table listing all characters and their data
Output is a CSV file and an Excel file, saved as 'characters.csv/.xlsx' in the output directory. | [
"Export",
"a",
"table",
"listing",
"all",
"characters",
"and",
"their",
"data"
] | 948675e02eb6fca940450f5cb814f53e97159e5b | https://github.com/ehansis/ozelot/blob/948675e02eb6fca940450f5cb814f53e97159e5b/examples/superheroes/superheroes/analysis.py#L24-L63 | train | Export a table listing all characters and their data |
ehansis/ozelot | examples/superheroes/superheroes/analysis.py | fig_to_svg | def fig_to_svg(fig):
"""Helper function to convert matplotlib figure to SVG string
Returns:
str: figure as SVG string
"""
buf = io.StringIO()
fig.savefig(buf, format='svg')
buf.seek(0)
return buf.getvalue() | python | def fig_to_svg(fig):
"""Helper function to convert matplotlib figure to SVG string
Returns:
str: figure as SVG string
"""
buf = io.StringIO()
fig.savefig(buf, format='svg')
buf.seek(0)
return buf.getvalue() | [
"def",
"fig_to_svg",
"(",
"fig",
")",
":",
"buf",
"=",
"io",
".",
"StringIO",
"(",
")",
"fig",
".",
"savefig",
"(",
"buf",
",",
"format",
"=",
"'svg'",
")",
"buf",
".",
"seek",
"(",
"0",
")",
"return",
"buf",
".",
"getvalue",
"(",
")"
] | Helper function to convert matplotlib figure to SVG string
Returns:
str: figure as SVG string | [
"Helper",
"function",
"to",
"convert",
"matplotlib",
"figure",
"to",
"SVG",
"string"
] | 948675e02eb6fca940450f5cb814f53e97159e5b | https://github.com/ehansis/ozelot/blob/948675e02eb6fca940450f5cb814f53e97159e5b/examples/superheroes/superheroes/analysis.py#L66-L75 | train | Helper function to convert matplotlib figure to SVG string |
ehansis/ozelot | examples/superheroes/superheroes/analysis.py | plots_html_page | def plots_html_page():
"""Generate general statistics
Output is an html page, rendered to 'plots_html_page.html' in the output directory.
"""
# page template
template = jenv.get_template("plots_html_page.html")
# container for template context
context = dict()
# a database client/sess... | python | def plots_html_page():
"""Generate general statistics
Output is an html page, rendered to 'plots_html_page.html' in the output directory.
"""
# page template
template = jenv.get_template("plots_html_page.html")
# container for template context
context = dict()
# a database client/sess... | [
"def",
"plots_html_page",
"(",
")",
":",
"# page template",
"template",
"=",
"jenv",
".",
"get_template",
"(",
"\"plots_html_page.html\"",
")",
"# container for template context",
"context",
"=",
"dict",
"(",
")",
"# a database client/session to run queries in",
"cl",
"="... | Generate general statistics
Output is an html page, rendered to 'plots_html_page.html' in the output directory. | [
"Generate",
"general",
"statistics"
] | 948675e02eb6fca940450f5cb814f53e97159e5b | https://github.com/ehansis/ozelot/blob/948675e02eb6fca940450f5cb814f53e97159e5b/examples/superheroes/superheroes/analysis.py#L90-L201 | train | Generate general statistics of the current language. |
ehansis/ozelot | examples/superheroes/superheroes/analysis.py | movie_network | def movie_network():
"""Generate interactive network graph of movie appearances
Output is an html page, rendered to 'movie_network.html' in the output directory.
"""
# page template
template = jenv.get_template("movie_network.html")
# container for template context
context = dict()
# ... | python | def movie_network():
"""Generate interactive network graph of movie appearances
Output is an html page, rendered to 'movie_network.html' in the output directory.
"""
# page template
template = jenv.get_template("movie_network.html")
# container for template context
context = dict()
# ... | [
"def",
"movie_network",
"(",
")",
":",
"# page template",
"template",
"=",
"jenv",
".",
"get_template",
"(",
"\"movie_network.html\"",
")",
"# container for template context",
"context",
"=",
"dict",
"(",
")",
"# a database client/session to run queries in",
"cl",
"=",
... | Generate interactive network graph of movie appearances
Output is an html page, rendered to 'movie_network.html' in the output directory. | [
"Generate",
"interactive",
"network",
"graph",
"of",
"movie",
"appearances"
] | 948675e02eb6fca940450f5cb814f53e97159e5b | https://github.com/ehansis/ozelot/blob/948675e02eb6fca940450f5cb814f53e97159e5b/examples/superheroes/superheroes/analysis.py#L204-L298 | train | Generate interactive network of movie appearances |
potash/drain | drain/dedupe.py | follow | def follow(id, edges, directed=False, _visited=None):
"""
Follow the a graph to find the nodes connected to a given node.
Args:
id: the id of the starting node
edges: a pandas DataFrame of edges. Each row is an edge with two columns containing
the ids of the vertices.
dir... | python | def follow(id, edges, directed=False, _visited=None):
"""
Follow the a graph to find the nodes connected to a given node.
Args:
id: the id of the starting node
edges: a pandas DataFrame of edges. Each row is an edge with two columns containing
the ids of the vertices.
dir... | [
"def",
"follow",
"(",
"id",
",",
"edges",
",",
"directed",
"=",
"False",
",",
"_visited",
"=",
"None",
")",
":",
"if",
"_visited",
"is",
"None",
":",
"_visited",
"=",
"set",
"(",
")",
"_visited",
".",
"add",
"(",
"id",
")",
"for",
"row",
"in",
"e... | Follow the a graph to find the nodes connected to a given node.
Args:
id: the id of the starting node
edges: a pandas DataFrame of edges. Each row is an edge with two columns containing
the ids of the vertices.
directed: If True, edges are directed from first column to second col... | [
"Follow",
"the",
"a",
"graph",
"to",
"find",
"the",
"nodes",
"connected",
"to",
"a",
"given",
"node",
".",
"Args",
":",
"id",
":",
"the",
"id",
"of",
"the",
"starting",
"node",
"edges",
":",
"a",
"pandas",
"DataFrame",
"of",
"edges",
".",
"Each",
"ro... | ddd62081cb9317beb5d21f86c8b4bb196ca3d222 | https://github.com/potash/drain/blob/ddd62081cb9317beb5d21f86c8b4bb196ca3d222/drain/dedupe.py#L8-L34 | train | Follows a graph to find the nodes connected to a given node. |
potash/drain | drain/dedupe.py | get_components | def get_components(edges, vertices=None):
"""
Return connected components from graph determined by edges matrix
Args:
edges: DataFrame of (undirected) edges.
vertices: set of vertices in graph. Defaults to union of all vertices in edges.
Returns:
set of connected components, eac... | python | def get_components(edges, vertices=None):
"""
Return connected components from graph determined by edges matrix
Args:
edges: DataFrame of (undirected) edges.
vertices: set of vertices in graph. Defaults to union of all vertices in edges.
Returns:
set of connected components, eac... | [
"def",
"get_components",
"(",
"edges",
",",
"vertices",
"=",
"None",
")",
":",
"if",
"vertices",
"is",
"None",
":",
"vertices",
"=",
"set",
"(",
"chain",
"(",
"edges",
".",
"ix",
"[",
":",
",",
"0",
"]",
",",
"edges",
".",
"ix",
"[",
":",
",",
... | Return connected components from graph determined by edges matrix
Args:
edges: DataFrame of (undirected) edges.
vertices: set of vertices in graph. Defaults to union of all vertices in edges.
Returns:
set of connected components, each of which is a set of vertices. | [
"Return",
"connected",
"components",
"from",
"graph",
"determined",
"by",
"edges",
"matrix",
"Args",
":",
"edges",
":",
"DataFrame",
"of",
"(",
"undirected",
")",
"edges",
".",
"vertices",
":",
"set",
"of",
"vertices",
"in",
"graph",
".",
"Defaults",
"to",
... | ddd62081cb9317beb5d21f86c8b4bb196ca3d222 | https://github.com/potash/drain/blob/ddd62081cb9317beb5d21f86c8b4bb196ca3d222/drain/dedupe.py#L37-L60 | train | Returns connected components from graph determined by edges matrix
|
potash/drain | drain/dedupe.py | components_to_df | def components_to_df(components, id_func=None):
"""
Convert components to a join table with columns id1, id2
Args:
components: A collection of components, each of which is a set of vertex ids.
If a dictionary, then the key is the id for the component. Otherwise,
the component... | python | def components_to_df(components, id_func=None):
"""
Convert components to a join table with columns id1, id2
Args:
components: A collection of components, each of which is a set of vertex ids.
If a dictionary, then the key is the id for the component. Otherwise,
the component... | [
"def",
"components_to_df",
"(",
"components",
",",
"id_func",
"=",
"None",
")",
":",
"deduped",
"=",
"np",
".",
"empty",
"(",
"(",
"0",
",",
"2",
")",
",",
"dtype",
"=",
"int",
")",
"if",
"id_func",
"is",
"None",
":",
"if",
"isinstance",
"(",
"comp... | Convert components to a join table with columns id1, id2
Args:
components: A collection of components, each of which is a set of vertex ids.
If a dictionary, then the key is the id for the component. Otherwise,
the component id is determined by applying id_func to the component.
... | [
"Convert",
"components",
"to",
"a",
"join",
"table",
"with",
"columns",
"id1",
"id2",
"Args",
":",
"components",
":",
"A",
"collection",
"of",
"components",
"each",
"of",
"which",
"is",
"a",
"set",
"of",
"vertex",
"ids",
".",
"If",
"a",
"dictionary",
"th... | ddd62081cb9317beb5d21f86c8b4bb196ca3d222 | https://github.com/potash/drain/blob/ddd62081cb9317beb5d21f86c8b4bb196ca3d222/drain/dedupe.py#L63-L94 | train | Convert a collection of components into a dataframe with columns id1 and id2. |
maljovec/topopy | docs/_static/logo_generator.py | unpack2D | def unpack2D(_x):
"""
Helper function for splitting 2D data into x and y component to make
equations simpler
"""
_x = np.atleast_2d(_x)
x = _x[:, 0]
y = _x[:, 1]
return x, y | python | def unpack2D(_x):
"""
Helper function for splitting 2D data into x and y component to make
equations simpler
"""
_x = np.atleast_2d(_x)
x = _x[:, 0]
y = _x[:, 1]
return x, y | [
"def",
"unpack2D",
"(",
"_x",
")",
":",
"_x",
"=",
"np",
".",
"atleast_2d",
"(",
"_x",
")",
"x",
"=",
"_x",
"[",
":",
",",
"0",
"]",
"y",
"=",
"_x",
"[",
":",
",",
"1",
"]",
"return",
"x",
",",
"y"
] | Helper function for splitting 2D data into x and y component to make
equations simpler | [
"Helper",
"function",
"for",
"splitting",
"2D",
"data",
"into",
"x",
"and",
"y",
"component",
"to",
"make",
"equations",
"simpler"
] | 4be598d51c4e4043b73d4ad44beed6d289e2f088 | https://github.com/maljovec/topopy/blob/4be598d51c4e4043b73d4ad44beed6d289e2f088/docs/_static/logo_generator.py#L48-L56 | train | Unpacks a 2D array into x and y components. |
albertz/py_better_exchook | setup.py | parse_pkg_info | def parse_pkg_info(fn):
"""
:param str fn:
:rtype: dict[str,str]
"""
res = {}
for ln in open(fn).read().splitlines():
if not ln or not ln[:1].strip():
continue
key, value = ln.split(": ", 1)
res[key] = value
return res | python | def parse_pkg_info(fn):
"""
:param str fn:
:rtype: dict[str,str]
"""
res = {}
for ln in open(fn).read().splitlines():
if not ln or not ln[:1].strip():
continue
key, value = ln.split(": ", 1)
res[key] = value
return res | [
"def",
"parse_pkg_info",
"(",
"fn",
")",
":",
"res",
"=",
"{",
"}",
"for",
"ln",
"in",
"open",
"(",
"fn",
")",
".",
"read",
"(",
")",
".",
"splitlines",
"(",
")",
":",
"if",
"not",
"ln",
"or",
"not",
"ln",
"[",
":",
"1",
"]",
".",
"strip",
... | :param str fn:
:rtype: dict[str,str] | [
":",
"param",
"str",
"fn",
":",
":",
"rtype",
":",
"dict",
"[",
"str",
"str",
"]"
] | 3d524a027d7fc4e83e47e39a1978849561da69b3 | https://github.com/albertz/py_better_exchook/blob/3d524a027d7fc4e83e47e39a1978849561da69b3/setup.py#L55-L66 | train | Parse pkg_info file into a dict |
albertz/py_better_exchook | better_exchook.py | parse_py_statement | def parse_py_statement(line):
"""
:param str line:
:return: yields (type, value)
:rtype: typing.Iterator[typing.Tuple[str,str]]
"""
state = 0
cur_token = ""
spaces = " \t\n"
ops = ".,;:+-*/%&!=|(){}[]^<>"
i = 0
def _escape_char(_c):
if _c == "n":
return "... | python | def parse_py_statement(line):
"""
:param str line:
:return: yields (type, value)
:rtype: typing.Iterator[typing.Tuple[str,str]]
"""
state = 0
cur_token = ""
spaces = " \t\n"
ops = ".,;:+-*/%&!=|(){}[]^<>"
i = 0
def _escape_char(_c):
if _c == "n":
return "... | [
"def",
"parse_py_statement",
"(",
"line",
")",
":",
"state",
"=",
"0",
"cur_token",
"=",
"\"\"",
"spaces",
"=",
"\" \\t\\n\"",
"ops",
"=",
"\".,;:+-*/%&!=|(){}[]^<>\"",
"i",
"=",
"0",
"def",
"_escape_char",
"(",
"_c",
")",
":",
"if",
"_c",
"==",
"\"n\"",
... | :param str line:
:return: yields (type, value)
:rtype: typing.Iterator[typing.Tuple[str,str]] | [
":",
"param",
"str",
"line",
":",
":",
"return",
":",
"yields",
"(",
"type",
"value",
")",
":",
"rtype",
":",
"typing",
".",
"Iterator",
"[",
"typing",
".",
"Tuple",
"[",
"str",
"str",
"]]"
] | 3d524a027d7fc4e83e47e39a1978849561da69b3 | https://github.com/albertz/py_better_exchook/blob/3d524a027d7fc4e83e47e39a1978849561da69b3/better_exchook.py#L91-L165 | train | Parse a single line of text into a list of types and values. |
albertz/py_better_exchook | better_exchook.py | grep_full_py_identifiers | def grep_full_py_identifiers(tokens):
"""
:param typing.Iterable[(str,str)] tokens:
:rtype: typing.Iterator[str]
"""
global py_keywords
tokens = list(tokens)
i = 0
while i < len(tokens):
token_type, token = tokens[i]
i += 1
if token_type != "id":
conti... | python | def grep_full_py_identifiers(tokens):
"""
:param typing.Iterable[(str,str)] tokens:
:rtype: typing.Iterator[str]
"""
global py_keywords
tokens = list(tokens)
i = 0
while i < len(tokens):
token_type, token = tokens[i]
i += 1
if token_type != "id":
conti... | [
"def",
"grep_full_py_identifiers",
"(",
"tokens",
")",
":",
"global",
"py_keywords",
"tokens",
"=",
"list",
"(",
"tokens",
")",
"i",
"=",
"0",
"while",
"i",
"<",
"len",
"(",
"tokens",
")",
":",
"token_type",
",",
"token",
"=",
"tokens",
"[",
"i",
"]",
... | :param typing.Iterable[(str,str)] tokens:
:rtype: typing.Iterator[str] | [
":",
"param",
"typing",
".",
"Iterable",
"[",
"(",
"str",
"str",
")",
"]",
"tokens",
":",
":",
"rtype",
":",
"typing",
".",
"Iterator",
"[",
"str",
"]"
] | 3d524a027d7fc4e83e47e39a1978849561da69b3 | https://github.com/albertz/py_better_exchook/blob/3d524a027d7fc4e83e47e39a1978849561da69b3/better_exchook.py#L179-L201 | train | Yields all the full python identifiers in a single resource tree. |
albertz/py_better_exchook | better_exchook.py | simple_debug_shell | def simple_debug_shell(globals, locals):
"""
:param dict[str] globals:
:param dict[str] locals:
:return: nothing
"""
try:
import readline
except ImportError:
pass # ignore
compile_string_fn = "<simple_debug_shell input>"
while True:
try:
s = raw_i... | python | def simple_debug_shell(globals, locals):
"""
:param dict[str] globals:
:param dict[str] locals:
:return: nothing
"""
try:
import readline
except ImportError:
pass # ignore
compile_string_fn = "<simple_debug_shell input>"
while True:
try:
s = raw_i... | [
"def",
"simple_debug_shell",
"(",
"globals",
",",
"locals",
")",
":",
"try",
":",
"import",
"readline",
"except",
"ImportError",
":",
"pass",
"# ignore",
"compile_string_fn",
"=",
"\"<simple_debug_shell input>\"",
"while",
"True",
":",
"try",
":",
"s",
"=",
"raw... | :param dict[str] globals:
:param dict[str] locals:
:return: nothing | [
":",
"param",
"dict",
"[",
"str",
"]",
"globals",
":",
":",
"param",
"dict",
"[",
"str",
"]",
"locals",
":",
":",
"return",
":",
"nothing"
] | 3d524a027d7fc4e83e47e39a1978849561da69b3 | https://github.com/albertz/py_better_exchook/blob/3d524a027d7fc4e83e47e39a1978849561da69b3/better_exchook.py#L219-L260 | train | Simple debug shell. |
albertz/py_better_exchook | better_exchook.py | debug_shell | def debug_shell(user_ns, user_global_ns, traceback=None, execWrapper=None):
"""
Spawns some interactive shell. Tries to use IPython if available.
Falls back to :func:`pdb.post_mortem` or :func:`simple_debug_shell`.
:param dict[str] user_ns:
:param dict[str] user_global_ns:
:param traceback:
... | python | def debug_shell(user_ns, user_global_ns, traceback=None, execWrapper=None):
"""
Spawns some interactive shell. Tries to use IPython if available.
Falls back to :func:`pdb.post_mortem` or :func:`simple_debug_shell`.
:param dict[str] user_ns:
:param dict[str] user_global_ns:
:param traceback:
... | [
"def",
"debug_shell",
"(",
"user_ns",
",",
"user_global_ns",
",",
"traceback",
"=",
"None",
",",
"execWrapper",
"=",
"None",
")",
":",
"ipshell",
"=",
"None",
"try",
":",
"# noinspection PyPackageRequirements",
"import",
"IPython",
"have_ipython",
"=",
"True",
"... | Spawns some interactive shell. Tries to use IPython if available.
Falls back to :func:`pdb.post_mortem` or :func:`simple_debug_shell`.
:param dict[str] user_ns:
:param dict[str] user_global_ns:
:param traceback:
:param execWrapper:
:return: nothing | [
"Spawns",
"some",
"interactive",
"shell",
".",
"Tries",
"to",
"use",
"IPython",
"if",
"available",
".",
"Falls",
"back",
"to",
":",
"func",
":",
"pdb",
".",
"post_mortem",
"or",
":",
"func",
":",
"simple_debug_shell",
"."
] | 3d524a027d7fc4e83e47e39a1978849561da69b3 | https://github.com/albertz/py_better_exchook/blob/3d524a027d7fc4e83e47e39a1978849561da69b3/better_exchook.py#L265-L343 | train | Runs some interactive shell. |
albertz/py_better_exchook | better_exchook.py | fallback_findfile | def fallback_findfile(filename):
"""
:param str filename:
:return: try to find the full filename, e.g. in modules, etc
:rtype: str|None
"""
mods = [m for m in sys.modules.values() if m and hasattr(m, "__file__") and filename in m.__file__]
if len(mods) == 0:
return None
alt_fn = ... | python | def fallback_findfile(filename):
"""
:param str filename:
:return: try to find the full filename, e.g. in modules, etc
:rtype: str|None
"""
mods = [m for m in sys.modules.values() if m and hasattr(m, "__file__") and filename in m.__file__]
if len(mods) == 0:
return None
alt_fn = ... | [
"def",
"fallback_findfile",
"(",
"filename",
")",
":",
"mods",
"=",
"[",
"m",
"for",
"m",
"in",
"sys",
".",
"modules",
".",
"values",
"(",
")",
"if",
"m",
"and",
"hasattr",
"(",
"m",
",",
"\"__file__\"",
")",
"and",
"filename",
"in",
"m",
".",
"__f... | :param str filename:
:return: try to find the full filename, e.g. in modules, etc
:rtype: str|None | [
":",
"param",
"str",
"filename",
":",
":",
"return",
":",
"try",
"to",
"find",
"the",
"full",
"filename",
"e",
".",
"g",
".",
"in",
"modules",
"etc",
":",
"rtype",
":",
"str|None"
] | 3d524a027d7fc4e83e47e39a1978849561da69b3 | https://github.com/albertz/py_better_exchook/blob/3d524a027d7fc4e83e47e39a1978849561da69b3/better_exchook.py#L354-L377 | train | Try to find the full filename in sys. modules. |
albertz/py_better_exchook | better_exchook.py | is_source_code_missing_open_brackets | def is_source_code_missing_open_brackets(source_code):
"""
:param str source_code:
:return: whether this source code snippet (e.g. one line) is complete/even w.r.t. opening/closing brackets
:rtype: bool
"""
open_brackets = "[{("
close_brackets = "]})"
last_close_bracket = [-1] # stack
... | python | def is_source_code_missing_open_brackets(source_code):
"""
:param str source_code:
:return: whether this source code snippet (e.g. one line) is complete/even w.r.t. opening/closing brackets
:rtype: bool
"""
open_brackets = "[{("
close_brackets = "]})"
last_close_bracket = [-1] # stack
... | [
"def",
"is_source_code_missing_open_brackets",
"(",
"source_code",
")",
":",
"open_brackets",
"=",
"\"[{(\"",
"close_brackets",
"=",
"\"]})\"",
"last_close_bracket",
"=",
"[",
"-",
"1",
"]",
"# stack",
"counters",
"=",
"[",
"0",
"]",
"*",
"len",
"(",
"open_brack... | :param str source_code:
:return: whether this source code snippet (e.g. one line) is complete/even w.r.t. opening/closing brackets
:rtype: bool | [
":",
"param",
"str",
"source_code",
":",
":",
"return",
":",
"whether",
"this",
"source",
"code",
"snippet",
"(",
"e",
".",
"g",
".",
"one",
"line",
")",
"is",
"complete",
"/",
"even",
"w",
".",
"r",
".",
"t",
".",
"opening",
"/",
"closing",
"brack... | 3d524a027d7fc4e83e47e39a1978849561da69b3 | https://github.com/albertz/py_better_exchook/blob/3d524a027d7fc4e83e47e39a1978849561da69b3/better_exchook.py#L380-L404 | train | Check if source code snippet is complete and even w. r. t. opening brackets are not found. |
albertz/py_better_exchook | better_exchook.py | get_source_code | def get_source_code(filename, lineno, module_globals):
"""
:param str filename:
:param int lineno:
:param dict[str] module_globals:
:return: source code of that line
:rtype: str
"""
import linecache
linecache.checkcache(filename)
source_code = linecache.getline(filename, lineno, ... | python | def get_source_code(filename, lineno, module_globals):
"""
:param str filename:
:param int lineno:
:param dict[str] module_globals:
:return: source code of that line
:rtype: str
"""
import linecache
linecache.checkcache(filename)
source_code = linecache.getline(filename, lineno, ... | [
"def",
"get_source_code",
"(",
"filename",
",",
"lineno",
",",
"module_globals",
")",
":",
"import",
"linecache",
"linecache",
".",
"checkcache",
"(",
"filename",
")",
"source_code",
"=",
"linecache",
".",
"getline",
"(",
"filename",
",",
"lineno",
",",
"modul... | :param str filename:
:param int lineno:
:param dict[str] module_globals:
:return: source code of that line
:rtype: str | [
":",
"param",
"str",
"filename",
":",
":",
"param",
"int",
"lineno",
":",
":",
"param",
"dict",
"[",
"str",
"]",
"module_globals",
":",
":",
"return",
":",
"source",
"code",
"of",
"that",
"line",
":",
"rtype",
":",
"str"
] | 3d524a027d7fc4e83e47e39a1978849561da69b3 | https://github.com/albertz/py_better_exchook/blob/3d524a027d7fc4e83e47e39a1978849561da69b3/better_exchook.py#L407-L425 | train | Get the source code of a line. |
albertz/py_better_exchook | better_exchook.py | add_indent_lines | def add_indent_lines(prefix, s):
"""
:param str prefix:
:param str s:
:return: s with prefix indent added to all lines
:rtype: str
"""
if not s:
return prefix
prefix_len = str_visible_len(prefix)
lines = s.splitlines(True)
return "".join([prefix + lines[0]] + [" " * prefi... | python | def add_indent_lines(prefix, s):
"""
:param str prefix:
:param str s:
:return: s with prefix indent added to all lines
:rtype: str
"""
if not s:
return prefix
prefix_len = str_visible_len(prefix)
lines = s.splitlines(True)
return "".join([prefix + lines[0]] + [" " * prefi... | [
"def",
"add_indent_lines",
"(",
"prefix",
",",
"s",
")",
":",
"if",
"not",
"s",
":",
"return",
"prefix",
"prefix_len",
"=",
"str_visible_len",
"(",
"prefix",
")",
"lines",
"=",
"s",
".",
"splitlines",
"(",
"True",
")",
"return",
"\"\"",
".",
"join",
"(... | :param str prefix:
:param str s:
:return: s with prefix indent added to all lines
:rtype: str | [
":",
"param",
"str",
"prefix",
":",
":",
"param",
"str",
"s",
":",
":",
"return",
":",
"s",
"with",
"prefix",
"indent",
"added",
"to",
"all",
"lines",
":",
"rtype",
":",
"str"
] | 3d524a027d7fc4e83e47e39a1978849561da69b3 | https://github.com/albertz/py_better_exchook/blob/3d524a027d7fc4e83e47e39a1978849561da69b3/better_exchook.py#L440-L451 | train | Adds prefix to all lines of the ndata xml file |
albertz/py_better_exchook | better_exchook.py | get_same_indent_prefix | def get_same_indent_prefix(lines):
"""
:param list[] lines:
:rtype: str|None
"""
if not lines:
return ""
prefix = get_indent_prefix(lines[0])
if not prefix:
return ""
if all([l.startswith(prefix) for l in lines]):
return prefix
return None | python | def get_same_indent_prefix(lines):
"""
:param list[] lines:
:rtype: str|None
"""
if not lines:
return ""
prefix = get_indent_prefix(lines[0])
if not prefix:
return ""
if all([l.startswith(prefix) for l in lines]):
return prefix
return None | [
"def",
"get_same_indent_prefix",
"(",
"lines",
")",
":",
"if",
"not",
"lines",
":",
"return",
"\"\"",
"prefix",
"=",
"get_indent_prefix",
"(",
"lines",
"[",
"0",
"]",
")",
"if",
"not",
"prefix",
":",
"return",
"\"\"",
"if",
"all",
"(",
"[",
"l",
".",
... | :param list[] lines:
:rtype: str|None | [
":",
"param",
"list",
"[]",
"lines",
":",
":",
"rtype",
":",
"str|None"
] | 3d524a027d7fc4e83e47e39a1978849561da69b3 | https://github.com/albertz/py_better_exchook/blob/3d524a027d7fc4e83e47e39a1978849561da69b3/better_exchook.py#L463-L475 | train | Returns the prefix of the first line of the n - tuple that is the same as the indent prefix of the first line. |
albertz/py_better_exchook | better_exchook.py | remove_indent_lines | def remove_indent_lines(s):
"""
:param str s:
:return: remove as much indentation as possible
:rtype: str
"""
if not s:
return ""
lines = s.splitlines(True)
prefix = get_same_indent_prefix(lines)
if prefix is None: # not in expected format. just lstrip all lines
retu... | python | def remove_indent_lines(s):
"""
:param str s:
:return: remove as much indentation as possible
:rtype: str
"""
if not s:
return ""
lines = s.splitlines(True)
prefix = get_same_indent_prefix(lines)
if prefix is None: # not in expected format. just lstrip all lines
retu... | [
"def",
"remove_indent_lines",
"(",
"s",
")",
":",
"if",
"not",
"s",
":",
"return",
"\"\"",
"lines",
"=",
"s",
".",
"splitlines",
"(",
"True",
")",
"prefix",
"=",
"get_same_indent_prefix",
"(",
"lines",
")",
"if",
"prefix",
"is",
"None",
":",
"# not in ex... | :param str s:
:return: remove as much indentation as possible
:rtype: str | [
":",
"param",
"str",
"s",
":",
":",
"return",
":",
"remove",
"as",
"much",
"indentation",
"as",
"possible",
":",
"rtype",
":",
"str"
] | 3d524a027d7fc4e83e47e39a1978849561da69b3 | https://github.com/albertz/py_better_exchook/blob/3d524a027d7fc4e83e47e39a1978849561da69b3/better_exchook.py#L478-L490 | train | remove indentation from a string |
albertz/py_better_exchook | better_exchook.py | replace_tab_indent | def replace_tab_indent(s, replace=" "):
"""
:param str s: string with tabs
:param str replace: e.g. 4 spaces
:rtype: str
"""
prefix = get_indent_prefix(s)
return prefix.replace("\t", replace) + s[len(prefix):] | python | def replace_tab_indent(s, replace=" "):
"""
:param str s: string with tabs
:param str replace: e.g. 4 spaces
:rtype: str
"""
prefix = get_indent_prefix(s)
return prefix.replace("\t", replace) + s[len(prefix):] | [
"def",
"replace_tab_indent",
"(",
"s",
",",
"replace",
"=",
"\" \"",
")",
":",
"prefix",
"=",
"get_indent_prefix",
"(",
"s",
")",
"return",
"prefix",
".",
"replace",
"(",
"\"\\t\"",
",",
"replace",
")",
"+",
"s",
"[",
"len",
"(",
"prefix",
")",
":",... | :param str s: string with tabs
:param str replace: e.g. 4 spaces
:rtype: str | [
":",
"param",
"str",
"s",
":",
"string",
"with",
"tabs",
":",
"param",
"str",
"replace",
":",
"e",
".",
"g",
".",
"4",
"spaces",
":",
"rtype",
":",
"str"
] | 3d524a027d7fc4e83e47e39a1978849561da69b3 | https://github.com/albertz/py_better_exchook/blob/3d524a027d7fc4e83e47e39a1978849561da69b3/better_exchook.py#L493-L500 | train | Returns a string with tabs replaced with spaces. |
albertz/py_better_exchook | better_exchook.py | replace_tab_indents | def replace_tab_indents(s, replace=" "):
"""
:param str s: multi-line string with tabs
:param str replace: e.g. 4 spaces
:rtype: str
"""
lines = s.splitlines(True)
return "".join([replace_tab_indent(l, replace) for l in lines]) | python | def replace_tab_indents(s, replace=" "):
"""
:param str s: multi-line string with tabs
:param str replace: e.g. 4 spaces
:rtype: str
"""
lines = s.splitlines(True)
return "".join([replace_tab_indent(l, replace) for l in lines]) | [
"def",
"replace_tab_indents",
"(",
"s",
",",
"replace",
"=",
"\" \"",
")",
":",
"lines",
"=",
"s",
".",
"splitlines",
"(",
"True",
")",
"return",
"\"\"",
".",
"join",
"(",
"[",
"replace_tab_indent",
"(",
"l",
",",
"replace",
")",
"for",
"l",
"in",
... | :param str s: multi-line string with tabs
:param str replace: e.g. 4 spaces
:rtype: str | [
":",
"param",
"str",
"s",
":",
"multi",
"-",
"line",
"string",
"with",
"tabs",
":",
"param",
"str",
"replace",
":",
"e",
".",
"g",
".",
"4",
"spaces",
":",
"rtype",
":",
"str"
] | 3d524a027d7fc4e83e47e39a1978849561da69b3 | https://github.com/albertz/py_better_exchook/blob/3d524a027d7fc4e83e47e39a1978849561da69b3/better_exchook.py#L503-L510 | train | Returns a multi - line string with tabs replaced by spaces. |
albertz/py_better_exchook | better_exchook.py | to_bool | def to_bool(s, fallback=None):
"""
:param str s: str to be converted to bool, e.g. "1", "0", "true", "false"
:param T fallback: if s is not recognized as a bool
:return: boolean value, or fallback
:rtype: bool|T
"""
if not s:
return fallback
s = s.lower()
if s in ["1", "true"... | python | def to_bool(s, fallback=None):
"""
:param str s: str to be converted to bool, e.g. "1", "0", "true", "false"
:param T fallback: if s is not recognized as a bool
:return: boolean value, or fallback
:rtype: bool|T
"""
if not s:
return fallback
s = s.lower()
if s in ["1", "true"... | [
"def",
"to_bool",
"(",
"s",
",",
"fallback",
"=",
"None",
")",
":",
"if",
"not",
"s",
":",
"return",
"fallback",
"s",
"=",
"s",
".",
"lower",
"(",
")",
"if",
"s",
"in",
"[",
"\"1\"",
",",
"\"true\"",
",",
"\"yes\"",
",",
"\"y\"",
"]",
":",
"ret... | :param str s: str to be converted to bool, e.g. "1", "0", "true", "false"
:param T fallback: if s is not recognized as a bool
:return: boolean value, or fallback
:rtype: bool|T | [
":",
"param",
"str",
"s",
":",
"str",
"to",
"be",
"converted",
"to",
"bool",
"e",
".",
"g",
".",
"1",
"0",
"true",
"false",
":",
"param",
"T",
"fallback",
":",
"if",
"s",
"is",
"not",
"recognized",
"as",
"a",
"bool",
":",
"return",
":",
"boolean"... | 3d524a027d7fc4e83e47e39a1978849561da69b3 | https://github.com/albertz/py_better_exchook/blob/3d524a027d7fc4e83e47e39a1978849561da69b3/better_exchook.py#L513-L527 | train | Converts a string to a boolean value. |
albertz/py_better_exchook | better_exchook.py | is_at_exit | def is_at_exit():
"""
Some heuristics to figure out whether this is called at a stage where the Python interpreter is shutting down.
:return: whether the Python interpreter is currently in the process of shutting down
:rtype: bool
"""
if _threading_main_thread is not None:
if not hasatt... | python | def is_at_exit():
"""
Some heuristics to figure out whether this is called at a stage where the Python interpreter is shutting down.
:return: whether the Python interpreter is currently in the process of shutting down
:rtype: bool
"""
if _threading_main_thread is not None:
if not hasatt... | [
"def",
"is_at_exit",
"(",
")",
":",
"if",
"_threading_main_thread",
"is",
"not",
"None",
":",
"if",
"not",
"hasattr",
"(",
"threading",
",",
"\"main_thread\"",
")",
":",
"return",
"True",
"if",
"threading",
".",
"main_thread",
"(",
")",
"!=",
"_threading_mai... | Some heuristics to figure out whether this is called at a stage where the Python interpreter is shutting down.
:return: whether the Python interpreter is currently in the process of shutting down
:rtype: bool | [
"Some",
"heuristics",
"to",
"figure",
"out",
"whether",
"this",
"is",
"called",
"at",
"a",
"stage",
"where",
"the",
"Python",
"interpreter",
"is",
"shutting",
"down",
"."
] | 3d524a027d7fc4e83e47e39a1978849561da69b3 | https://github.com/albertz/py_better_exchook/blob/3d524a027d7fc4e83e47e39a1978849561da69b3/better_exchook.py#L836-L850 | train | This function is called at the end of a Python interpreter. |
albertz/py_better_exchook | better_exchook.py | format_tb | def format_tb(tb=None, limit=None, allLocals=None, allGlobals=None, withTitle=False, with_color=None, with_vars=None):
"""
:param types.TracebackType|types.FrameType|StackSummary tb: traceback. if None, will use sys._getframe
:param int|None limit: limit the traceback to this number of frames. by default, w... | python | def format_tb(tb=None, limit=None, allLocals=None, allGlobals=None, withTitle=False, with_color=None, with_vars=None):
"""
:param types.TracebackType|types.FrameType|StackSummary tb: traceback. if None, will use sys._getframe
:param int|None limit: limit the traceback to this number of frames. by default, w... | [
"def",
"format_tb",
"(",
"tb",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"allLocals",
"=",
"None",
",",
"allGlobals",
"=",
"None",
",",
"withTitle",
"=",
"False",
",",
"with_color",
"=",
"None",
",",
"with_vars",
"=",
"None",
")",
":",
"color",
"=... | :param types.TracebackType|types.FrameType|StackSummary tb: traceback. if None, will use sys._getframe
:param int|None limit: limit the traceback to this number of frames. by default, will look at sys.tracebacklimit
:param dict[str]|None allLocals: if set, will update it with all locals from all frames
:par... | [
":",
"param",
"types",
".",
"TracebackType|types",
".",
"FrameType|StackSummary",
"tb",
":",
"traceback",
".",
"if",
"None",
"will",
"use",
"sys",
".",
"_getframe",
":",
"param",
"int|None",
"limit",
":",
"limit",
"the",
"traceback",
"to",
"this",
"number",
... | 3d524a027d7fc4e83e47e39a1978849561da69b3 | https://github.com/albertz/py_better_exchook/blob/3d524a027d7fc4e83e47e39a1978849561da69b3/better_exchook.py#L958-L1157 | train | Returns a list of lines of source code from a traceback. |
albertz/py_better_exchook | better_exchook.py | print_tb | def print_tb(tb, file=None, **kwargs):
"""
:param types.TracebackType|types.FrameType|StackSummary tb:
:param io.TextIOBase|io.StringIO|None file: stderr by default
:return: nothing, prints to ``file``
"""
if file is None:
file = sys.stderr
for l in format_tb(tb=tb, **kwargs):
... | python | def print_tb(tb, file=None, **kwargs):
"""
:param types.TracebackType|types.FrameType|StackSummary tb:
:param io.TextIOBase|io.StringIO|None file: stderr by default
:return: nothing, prints to ``file``
"""
if file is None:
file = sys.stderr
for l in format_tb(tb=tb, **kwargs):
... | [
"def",
"print_tb",
"(",
"tb",
",",
"file",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"file",
"is",
"None",
":",
"file",
"=",
"sys",
".",
"stderr",
"for",
"l",
"in",
"format_tb",
"(",
"tb",
"=",
"tb",
",",
"*",
"*",
"kwargs",
")",
... | :param types.TracebackType|types.FrameType|StackSummary tb:
:param io.TextIOBase|io.StringIO|None file: stderr by default
:return: nothing, prints to ``file`` | [
":",
"param",
"types",
".",
"TracebackType|types",
".",
"FrameType|StackSummary",
"tb",
":",
":",
"param",
"io",
".",
"TextIOBase|io",
".",
"StringIO|None",
"file",
":",
"stderr",
"by",
"default",
":",
"return",
":",
"nothing",
"prints",
"to",
"file"
] | 3d524a027d7fc4e83e47e39a1978849561da69b3 | https://github.com/albertz/py_better_exchook/blob/3d524a027d7fc4e83e47e39a1978849561da69b3/better_exchook.py#L1160-L1170 | train | Prints a traceback to file |
albertz/py_better_exchook | better_exchook.py | better_exchook | def better_exchook(etype, value, tb, debugshell=False, autodebugshell=True, file=None, with_color=None):
"""
Replacement for sys.excepthook.
:param etype: exception type
:param value: exception value
:param tb: traceback
:param bool debugshell: spawn a debug shell at the context of the exceptio... | python | def better_exchook(etype, value, tb, debugshell=False, autodebugshell=True, file=None, with_color=None):
"""
Replacement for sys.excepthook.
:param etype: exception type
:param value: exception value
:param tb: traceback
:param bool debugshell: spawn a debug shell at the context of the exceptio... | [
"def",
"better_exchook",
"(",
"etype",
",",
"value",
",",
"tb",
",",
"debugshell",
"=",
"False",
",",
"autodebugshell",
"=",
"True",
",",
"file",
"=",
"None",
",",
"with_color",
"=",
"None",
")",
":",
"if",
"file",
"is",
"None",
":",
"file",
"=",
"sy... | Replacement for sys.excepthook.
:param etype: exception type
:param value: exception value
:param tb: traceback
:param bool debugshell: spawn a debug shell at the context of the exception
:param bool autodebugshell: if env DEBUG is an integer != 0, it will spawn a debug shell
:param io.TextIOBa... | [
"Replacement",
"for",
"sys",
".",
"excepthook",
"."
] | 3d524a027d7fc4e83e47e39a1978849561da69b3 | https://github.com/albertz/py_better_exchook/blob/3d524a027d7fc4e83e47e39a1978849561da69b3/better_exchook.py#L1173-L1244 | train | A better exception handler. |
albertz/py_better_exchook | better_exchook.py | dump_all_thread_tracebacks | def dump_all_thread_tracebacks(exclude_thread_ids=None, file=None):
"""
Prints the traceback of all threads.
:param set[int]|list[int]|None exclude_thread_ids: threads to exclude
:param io.TextIOBase|io.StringIO file: output stream
"""
if exclude_thread_ids is None:
exclude_thread_ids =... | python | def dump_all_thread_tracebacks(exclude_thread_ids=None, file=None):
"""
Prints the traceback of all threads.
:param set[int]|list[int]|None exclude_thread_ids: threads to exclude
:param io.TextIOBase|io.StringIO file: output stream
"""
if exclude_thread_ids is None:
exclude_thread_ids =... | [
"def",
"dump_all_thread_tracebacks",
"(",
"exclude_thread_ids",
"=",
"None",
",",
"file",
"=",
"None",
")",
":",
"if",
"exclude_thread_ids",
"is",
"None",
":",
"exclude_thread_ids",
"=",
"[",
"]",
"if",
"not",
"file",
":",
"file",
"=",
"sys",
".",
"stdout",
... | Prints the traceback of all threads.
:param set[int]|list[int]|None exclude_thread_ids: threads to exclude
:param io.TextIOBase|io.StringIO file: output stream | [
"Prints",
"the",
"traceback",
"of",
"all",
"threads",
"."
] | 3d524a027d7fc4e83e47e39a1978849561da69b3 | https://github.com/albertz/py_better_exchook/blob/3d524a027d7fc4e83e47e39a1978849561da69b3/better_exchook.py#L1247-L1289 | train | Prints the traceback of all threads. |
albertz/py_better_exchook | better_exchook.py | get_current_frame | def get_current_frame():
"""
:return: current frame object (excluding this function call)
:rtype: types.FrameType
Uses sys._getframe if available, otherwise some trickery with sys.exc_info and a dummy exception.
"""
if hasattr(sys, "_getframe"):
# noinspection PyProtectedMember
... | python | def get_current_frame():
"""
:return: current frame object (excluding this function call)
:rtype: types.FrameType
Uses sys._getframe if available, otherwise some trickery with sys.exc_info and a dummy exception.
"""
if hasattr(sys, "_getframe"):
# noinspection PyProtectedMember
... | [
"def",
"get_current_frame",
"(",
")",
":",
"if",
"hasattr",
"(",
"sys",
",",
"\"_getframe\"",
")",
":",
"# noinspection PyProtectedMember",
"return",
"sys",
".",
"_getframe",
"(",
"1",
")",
"try",
":",
"raise",
"ZeroDivisionError",
"except",
"ZeroDivisionError",
... | :return: current frame object (excluding this function call)
:rtype: types.FrameType
Uses sys._getframe if available, otherwise some trickery with sys.exc_info and a dummy exception. | [
":",
"return",
":",
"current",
"frame",
"object",
"(",
"excluding",
"this",
"function",
"call",
")",
":",
"rtype",
":",
"types",
".",
"FrameType"
] | 3d524a027d7fc4e83e47e39a1978849561da69b3 | https://github.com/albertz/py_better_exchook/blob/3d524a027d7fc4e83e47e39a1978849561da69b3/better_exchook.py#L1292-L1305 | train | Returns the current frame object. |
albertz/py_better_exchook | better_exchook.py | iter_traceback | def iter_traceback(tb=None, enforce_most_recent_call_first=False):
"""
Iterates a traceback of various formats:
- traceback (types.TracebackType)
- frame object (types.FrameType)
- stack summary (traceback.StackSummary)
:param types.TracebackType|types.FrameType|StackSummary|None tb: trac... | python | def iter_traceback(tb=None, enforce_most_recent_call_first=False):
"""
Iterates a traceback of various formats:
- traceback (types.TracebackType)
- frame object (types.FrameType)
- stack summary (traceback.StackSummary)
:param types.TracebackType|types.FrameType|StackSummary|None tb: trac... | [
"def",
"iter_traceback",
"(",
"tb",
"=",
"None",
",",
"enforce_most_recent_call_first",
"=",
"False",
")",
":",
"if",
"tb",
"is",
"None",
":",
"tb",
"=",
"get_current_frame",
"(",
")",
"def",
"is_stack_summary",
"(",
"_tb",
")",
":",
"\"\"\"\n :param St... | Iterates a traceback of various formats:
- traceback (types.TracebackType)
- frame object (types.FrameType)
- stack summary (traceback.StackSummary)
:param types.TracebackType|types.FrameType|StackSummary|None tb: traceback. if None, will use sys._getframe
:param bool enforce_most_recent_call... | [
"Iterates",
"a",
"traceback",
"of",
"various",
"formats",
":",
"-",
"traceback",
"(",
"types",
".",
"TracebackType",
")",
"-",
"frame",
"object",
"(",
"types",
".",
"FrameType",
")",
"-",
"stack",
"summary",
"(",
"traceback",
".",
"StackSummary",
")"
] | 3d524a027d7fc4e83e47e39a1978849561da69b3 | https://github.com/albertz/py_better_exchook/blob/3d524a027d7fc4e83e47e39a1978849561da69b3/better_exchook.py#L1308-L1363 | train | Iterate over the tracebacks in a list of basic types. |
albertz/py_better_exchook | better_exchook.py | _StackSummary_extract | def _StackSummary_extract(frame_gen, limit=None, lookup_lines=True, capture_locals=False):
"""
Replacement for :func:`StackSummary.extract`.
Create a StackSummary from a traceback or stack object.
Very simplified copy of the original StackSummary.extract().
We want always to capture locals, that is... | python | def _StackSummary_extract(frame_gen, limit=None, lookup_lines=True, capture_locals=False):
"""
Replacement for :func:`StackSummary.extract`.
Create a StackSummary from a traceback or stack object.
Very simplified copy of the original StackSummary.extract().
We want always to capture locals, that is... | [
"def",
"_StackSummary_extract",
"(",
"frame_gen",
",",
"limit",
"=",
"None",
",",
"lookup_lines",
"=",
"True",
",",
"capture_locals",
"=",
"False",
")",
":",
"result",
"=",
"StackSummary",
"(",
")",
"for",
"f",
",",
"lineno",
"in",
"frame_gen",
":",
"co",
... | Replacement for :func:`StackSummary.extract`.
Create a StackSummary from a traceback or stack object.
Very simplified copy of the original StackSummary.extract().
We want always to capture locals, that is why we overwrite it.
Additionally, we also capture the frame.
This is a bit hacky and also not... | [
"Replacement",
"for",
":",
"func",
":",
"StackSummary",
".",
"extract",
"."
] | 3d524a027d7fc4e83e47e39a1978849561da69b3 | https://github.com/albertz/py_better_exchook/blob/3d524a027d7fc4e83e47e39a1978849561da69b3/better_exchook.py#L1405-L1431 | train | Replace the original StackSummary. extract method with extendedFrameSummary. |
albertz/py_better_exchook | better_exchook.py | replace_traceback_format_tb | def replace_traceback_format_tb():
"""
Replaces these functions from the traceback module by our own:
- traceback.format_tb
- traceback.StackSummary.format
- traceback.StackSummary.extract
Note that this kind of monkey patching might not be safe under all circumstances
and is not officiall... | python | def replace_traceback_format_tb():
"""
Replaces these functions from the traceback module by our own:
- traceback.format_tb
- traceback.StackSummary.format
- traceback.StackSummary.extract
Note that this kind of monkey patching might not be safe under all circumstances
and is not officiall... | [
"def",
"replace_traceback_format_tb",
"(",
")",
":",
"import",
"traceback",
"traceback",
".",
"format_tb",
"=",
"format_tb",
"if",
"hasattr",
"(",
"traceback",
",",
"\"StackSummary\"",
")",
":",
"traceback",
".",
"StackSummary",
".",
"format",
"=",
"format_tb",
... | Replaces these functions from the traceback module by our own:
- traceback.format_tb
- traceback.StackSummary.format
- traceback.StackSummary.extract
Note that this kind of monkey patching might not be safe under all circumstances
and is not officially supported by Python. | [
"Replaces",
"these",
"functions",
"from",
"the",
"traceback",
"module",
"by",
"our",
"own",
":"
] | 3d524a027d7fc4e83e47e39a1978849561da69b3 | https://github.com/albertz/py_better_exchook/blob/3d524a027d7fc4e83e47e39a1978849561da69b3/better_exchook.py#L1441-L1456 | train | Replace the format_tb and extract functions in the traceback module by our own. |
albertz/py_better_exchook | better_exchook.py | _main | def _main():
"""
Some demo.
"""
if sys.argv[1:] == ["test"]:
for k, v in sorted(globals().items()):
if not k.startswith("test_"):
continue
print("running: %s()" % k)
v()
print("ok.")
sys.exit()
elif sys.argv[1:] == ["debug... | python | def _main():
"""
Some demo.
"""
if sys.argv[1:] == ["test"]:
for k, v in sorted(globals().items()):
if not k.startswith("test_"):
continue
print("running: %s()" % k)
v()
print("ok.")
sys.exit()
elif sys.argv[1:] == ["debug... | [
"def",
"_main",
"(",
")",
":",
"if",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
"==",
"[",
"\"test\"",
"]",
":",
"for",
"k",
",",
"v",
"in",
"sorted",
"(",
"globals",
"(",
")",
".",
"items",
"(",
")",
")",
":",
"if",
"not",
"k",
".",
"startswi... | Some demo. | [
"Some",
"demo",
"."
] | 3d524a027d7fc4e83e47e39a1978849561da69b3 | https://github.com/albertz/py_better_exchook/blob/3d524a027d7fc4e83e47e39a1978849561da69b3/better_exchook.py#L1502-L1586 | train | This is the main function for the demo. |
albertz/py_better_exchook | better_exchook.py | Color.is_dark_terminal_background | def is_dark_terminal_background(cls):
"""
:return: Whether we have a dark Terminal background color, or None if unknown.
We currently just check the env var COLORFGBG,
which some terminals define like "<foreground-color>:<background-color>",
and if <background-color> ... | python | def is_dark_terminal_background(cls):
"""
:return: Whether we have a dark Terminal background color, or None if unknown.
We currently just check the env var COLORFGBG,
which some terminals define like "<foreground-color>:<background-color>",
and if <background-color> ... | [
"def",
"is_dark_terminal_background",
"(",
"cls",
")",
":",
"if",
"os",
".",
"environ",
".",
"get",
"(",
"\"COLORFGBG\"",
",",
"None",
")",
":",
"parts",
"=",
"os",
".",
"environ",
"[",
"\"COLORFGBG\"",
"]",
".",
"split",
"(",
"\";\"",
")",
"try",
":",... | :return: Whether we have a dark Terminal background color, or None if unknown.
We currently just check the env var COLORFGBG,
which some terminals define like "<foreground-color>:<background-color>",
and if <background-color> in {0,1,2,3,4,5,6,8}, then we have some dark background.
... | [
":",
"return",
":",
"Whether",
"we",
"have",
"a",
"dark",
"Terminal",
"background",
"color",
"or",
"None",
"if",
"unknown",
".",
"We",
"currently",
"just",
"check",
"the",
"env",
"var",
"COLORFGBG",
"which",
"some",
"terminals",
"define",
"like",
"<foregroun... | 3d524a027d7fc4e83e47e39a1978849561da69b3 | https://github.com/albertz/py_better_exchook/blob/3d524a027d7fc4e83e47e39a1978849561da69b3/better_exchook.py#L546-L568 | train | Return True if we have a dark terminal background color or False if unknown. |
albertz/py_better_exchook | better_exchook.py | Color.color | def color(self, s, color=None, bold=False):
"""
:param str s:
:param str|None color: sth in self.ColorIdxTable
:param bool bold:
:return: s optionally wrapped with ansi escape codes
:rtype: str
"""
if not self.enable:
return s
code_seq ... | python | def color(self, s, color=None, bold=False):
"""
:param str s:
:param str|None color: sth in self.ColorIdxTable
:param bool bold:
:return: s optionally wrapped with ansi escape codes
:rtype: str
"""
if not self.enable:
return s
code_seq ... | [
"def",
"color",
"(",
"self",
",",
"s",
",",
"color",
"=",
"None",
",",
"bold",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"enable",
":",
"return",
"s",
"code_seq",
"=",
"[",
"]",
"if",
"color",
":",
"code_seq",
"+=",
"[",
"30",
"+",
"sel... | :param str s:
:param str|None color: sth in self.ColorIdxTable
:param bool bold:
:return: s optionally wrapped with ansi escape codes
:rtype: str | [
":",
"param",
"str",
"s",
":",
":",
"param",
"str|None",
"color",
":",
"sth",
"in",
"self",
".",
"ColorIdxTable",
":",
"param",
"bool",
"bold",
":",
":",
"return",
":",
"s",
"optionally",
"wrapped",
"with",
"ansi",
"escape",
"codes",
":",
"rtype",
":",... | 3d524a027d7fc4e83e47e39a1978849561da69b3 | https://github.com/albertz/py_better_exchook/blob/3d524a027d7fc4e83e47e39a1978849561da69b3/better_exchook.py#L587-L612 | train | Color the log entry. |
albertz/py_better_exchook | better_exchook.py | Color.py_syntax_highlight | def py_syntax_highlight(self, s):
"""
:param str s:
:rtype: str
"""
if not self.enable:
return s
state = 0
spaces = " \t\n"
ops = ".,;:+-*/%&!=|(){}[]^<>"
i = 0
cur_token = ""
color_args = {0: {}, len(s): {}} # type: ty... | python | def py_syntax_highlight(self, s):
"""
:param str s:
:rtype: str
"""
if not self.enable:
return s
state = 0
spaces = " \t\n"
ops = ".,;:+-*/%&!=|(){}[]^<>"
i = 0
cur_token = ""
color_args = {0: {}, len(s): {}} # type: ty... | [
"def",
"py_syntax_highlight",
"(",
"self",
",",
"s",
")",
":",
"if",
"not",
"self",
".",
"enable",
":",
"return",
"s",
"state",
"=",
"0",
"spaces",
"=",
"\" \\t\\n\"",
"ops",
"=",
"\".,;:+-*/%&!=|(){}[]^<>\"",
"i",
"=",
"0",
"cur_token",
"=",
"\"\"",
"co... | :param str s:
:rtype: str | [
":",
"param",
"str",
"s",
":",
":",
"rtype",
":",
"str"
] | 3d524a027d7fc4e83e47e39a1978849561da69b3 | https://github.com/albertz/py_better_exchook/blob/3d524a027d7fc4e83e47e39a1978849561da69b3/better_exchook.py#L617-L699 | train | Highlights the syntax of the current locale. |
albertz/py_better_exchook | better_exchook.py | DomTerm.is_domterm | def is_domterm(cls):
"""
:return: whether we are inside DomTerm
:rtype: bool
"""
import os
if cls._is_domterm is not None:
return cls._is_domterm
if not os.environ.get("DOMTERM"):
cls._is_domterm = False
return False
cls... | python | def is_domterm(cls):
"""
:return: whether we are inside DomTerm
:rtype: bool
"""
import os
if cls._is_domterm is not None:
return cls._is_domterm
if not os.environ.get("DOMTERM"):
cls._is_domterm = False
return False
cls... | [
"def",
"is_domterm",
"(",
"cls",
")",
":",
"import",
"os",
"if",
"cls",
".",
"_is_domterm",
"is",
"not",
"None",
":",
"return",
"cls",
".",
"_is_domterm",
"if",
"not",
"os",
".",
"environ",
".",
"get",
"(",
"\"DOMTERM\"",
")",
":",
"cls",
".",
"_is_d... | :return: whether we are inside DomTerm
:rtype: bool | [
":",
"return",
":",
"whether",
"we",
"are",
"inside",
"DomTerm",
":",
"rtype",
":",
"bool"
] | 3d524a027d7fc4e83e47e39a1978849561da69b3 | https://github.com/albertz/py_better_exchook/blob/3d524a027d7fc4e83e47e39a1978849561da69b3/better_exchook.py#L712-L724 | train | Returns True if we are inside DomTerm otherwise False. |
albertz/py_better_exchook | better_exchook.py | DomTerm.hide_button_span | def hide_button_span(self, mode, file=sys.stdout):
"""
:param int mode: 1 or 2
:param io.TextIOBase|io.StringIO file:
"""
file.write("\033[83;%iu" % mode)
yield
file.write("\033[83;0u") | python | def hide_button_span(self, mode, file=sys.stdout):
"""
:param int mode: 1 or 2
:param io.TextIOBase|io.StringIO file:
"""
file.write("\033[83;%iu" % mode)
yield
file.write("\033[83;0u") | [
"def",
"hide_button_span",
"(",
"self",
",",
"mode",
",",
"file",
"=",
"sys",
".",
"stdout",
")",
":",
"file",
".",
"write",
"(",
"\"\\033[83;%iu\"",
"%",
"mode",
")",
"yield",
"file",
".",
"write",
"(",
"\"\\033[83;0u\"",
")"
] | :param int mode: 1 or 2
:param io.TextIOBase|io.StringIO file: | [
":",
"param",
"int",
"mode",
":",
"1",
"or",
"2",
":",
"param",
"io",
".",
"TextIOBase|io",
".",
"StringIO",
"file",
":"
] | 3d524a027d7fc4e83e47e39a1978849561da69b3 | https://github.com/albertz/py_better_exchook/blob/3d524a027d7fc4e83e47e39a1978849561da69b3/better_exchook.py#L736-L743 | train | Hide button span. |
albertz/py_better_exchook | better_exchook.py | DomTerm.fold_text_stream | def fold_text_stream(self, prefix, postfix="", hidden_stream=None, **kwargs):
"""
:param str prefix: always visible
:param str postfix: always visible, right after.
:param io.TextIOBase|io.StringIO hidden_stream: sys.stdout by default.
If this is sys.stdout, it will replace t... | python | def fold_text_stream(self, prefix, postfix="", hidden_stream=None, **kwargs):
"""
:param str prefix: always visible
:param str postfix: always visible, right after.
:param io.TextIOBase|io.StringIO hidden_stream: sys.stdout by default.
If this is sys.stdout, it will replace t... | [
"def",
"fold_text_stream",
"(",
"self",
",",
"prefix",
",",
"postfix",
"=",
"\"\"",
",",
"hidden_stream",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"io",
"if",
"hidden_stream",
"is",
"None",
":",
"hidden_stream",
"=",
"sys",
".",
"stdout"... | :param str prefix: always visible
:param str postfix: always visible, right after.
:param io.TextIOBase|io.StringIO hidden_stream: sys.stdout by default.
If this is sys.stdout, it will replace that stream,
and collect the data during the context (in the `with` block). | [
":",
"param",
"str",
"prefix",
":",
"always",
"visible",
":",
"param",
"str",
"postfix",
":",
"always",
"visible",
"right",
"after",
".",
":",
"param",
"io",
".",
"TextIOBase|io",
".",
"StringIO",
"hidden_stream",
":",
"sys",
".",
"stdout",
"by",
"default"... | 3d524a027d7fc4e83e47e39a1978849561da69b3 | https://github.com/albertz/py_better_exchook/blob/3d524a027d7fc4e83e47e39a1978849561da69b3/better_exchook.py#L767-L783 | train | A context manager that folds the text of the current process into a stream. |
albertz/py_better_exchook | better_exchook.py | DomTerm.fold_text | def fold_text(self, prefix, hidden, postfix="", file=None, align=0):
"""
:param str prefix: always visible
:param str hidden: hidden
If this is sys.stdout, it will replace that stream,
and collect the data during the context (in the `with` block).
:param str postf... | python | def fold_text(self, prefix, hidden, postfix="", file=None, align=0):
"""
:param str prefix: always visible
:param str hidden: hidden
If this is sys.stdout, it will replace that stream,
and collect the data during the context (in the `with` block).
:param str postf... | [
"def",
"fold_text",
"(",
"self",
",",
"prefix",
",",
"hidden",
",",
"postfix",
"=",
"\"\"",
",",
"file",
"=",
"None",
",",
"align",
"=",
"0",
")",
":",
"if",
"file",
"is",
"None",
":",
"file",
"=",
"sys",
".",
"stdout",
"# Extra logic: Multi-line hidde... | :param str prefix: always visible
:param str hidden: hidden
If this is sys.stdout, it will replace that stream,
and collect the data during the context (in the `with` block).
:param str postfix: always visible, right after. "" by default.
:param io.TextIOBase|io.StringIO ... | [
":",
"param",
"str",
"prefix",
":",
"always",
"visible",
":",
"param",
"str",
"hidden",
":",
"hidden",
"If",
"this",
"is",
"sys",
".",
"stdout",
"it",
"will",
"replace",
"that",
"stream",
"and",
"collect",
"the",
"data",
"during",
"the",
"context",
"(",
... | 3d524a027d7fc4e83e47e39a1978849561da69b3 | https://github.com/albertz/py_better_exchook/blob/3d524a027d7fc4e83e47e39a1978849561da69b3/better_exchook.py#L785-L821 | train | Folds text in the context of the current element. |
albertz/py_better_exchook | better_exchook.py | DomTerm.fold_text_string | def fold_text_string(self, prefix, hidden, **kwargs):
"""
:param str prefix:
:param str hidden:
:param kwargs: passed to :func:`fold_text`
:rtype: str
"""
import io
output_buf = io.StringIO()
self.fold_text(prefix=prefix, hidden=hidden, file=output... | python | def fold_text_string(self, prefix, hidden, **kwargs):
"""
:param str prefix:
:param str hidden:
:param kwargs: passed to :func:`fold_text`
:rtype: str
"""
import io
output_buf = io.StringIO()
self.fold_text(prefix=prefix, hidden=hidden, file=output... | [
"def",
"fold_text_string",
"(",
"self",
",",
"prefix",
",",
"hidden",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"io",
"output_buf",
"=",
"io",
".",
"StringIO",
"(",
")",
"self",
".",
"fold_text",
"(",
"prefix",
"=",
"prefix",
",",
"hidden",
"=",
"... | :param str prefix:
:param str hidden:
:param kwargs: passed to :func:`fold_text`
:rtype: str | [
":",
"param",
"str",
"prefix",
":",
":",
"param",
"str",
"hidden",
":",
":",
"param",
"kwargs",
":",
"passed",
"to",
":",
"func",
":",
"fold_text",
":",
"rtype",
":",
"str"
] | 3d524a027d7fc4e83e47e39a1978849561da69b3 | https://github.com/albertz/py_better_exchook/blob/3d524a027d7fc4e83e47e39a1978849561da69b3/better_exchook.py#L823-L833 | train | Folds the text of the current locale into a string. |
albertz/py_better_exchook | better_exchook.py | _Output.fold_text_ctx | def fold_text_ctx(self, line):
"""
Folds text, via :class:`DomTerm`, if available.
Notes that this temporarily overwrites self.lines.
:param str line: always visible
"""
if not self.dom_term:
self.__call__(line)
yield
return
se... | python | def fold_text_ctx(self, line):
"""
Folds text, via :class:`DomTerm`, if available.
Notes that this temporarily overwrites self.lines.
:param str line: always visible
"""
if not self.dom_term:
self.__call__(line)
yield
return
se... | [
"def",
"fold_text_ctx",
"(",
"self",
",",
"line",
")",
":",
"if",
"not",
"self",
".",
"dom_term",
":",
"self",
".",
"__call__",
"(",
"line",
")",
"yield",
"return",
"self",
".",
"lines",
",",
"old_lines",
"=",
"[",
"]",
",",
"self",
".",
"lines",
"... | Folds text, via :class:`DomTerm`, if available.
Notes that this temporarily overwrites self.lines.
:param str line: always visible | [
"Folds",
"text",
"via",
":",
"class",
":",
"DomTerm",
"if",
"available",
".",
"Notes",
"that",
"this",
"temporarily",
"overwrites",
"self",
".",
"lines",
"."
] | 3d524a027d7fc4e83e47e39a1978849561da69b3 | https://github.com/albertz/py_better_exchook/blob/3d524a027d7fc4e83e47e39a1978849561da69b3/better_exchook.py#L878-L901 | train | Folds text via domterm. |
albertz/py_better_exchook | better_exchook.py | _Output.pretty_print | def pretty_print(self, obj):
"""
:param object obj:
:rtype: str
"""
s = repr(obj)
limit = output_limit()
if len(s) > limit:
if self.dom_term:
s = self.color.py_syntax_highlight(s)
s = self.dom_term.fold_text_string("", s... | python | def pretty_print(self, obj):
"""
:param object obj:
:rtype: str
"""
s = repr(obj)
limit = output_limit()
if len(s) > limit:
if self.dom_term:
s = self.color.py_syntax_highlight(s)
s = self.dom_term.fold_text_string("", s... | [
"def",
"pretty_print",
"(",
"self",
",",
"obj",
")",
":",
"s",
"=",
"repr",
"(",
"obj",
")",
"limit",
"=",
"output_limit",
"(",
")",
"if",
"len",
"(",
"s",
")",
">",
"limit",
":",
"if",
"self",
".",
"dom_term",
":",
"s",
"=",
"self",
".",
"colo... | :param object obj:
:rtype: str | [
":",
"param",
"object",
"obj",
":",
":",
"rtype",
":",
"str"
] | 3d524a027d7fc4e83e47e39a1978849561da69b3 | https://github.com/albertz/py_better_exchook/blob/3d524a027d7fc4e83e47e39a1978849561da69b3/better_exchook.py#L933-L953 | train | Pretty print the object. |
albertz/py_better_exchook | better_exchook.py | DummyFrame.from_frame_summary | def from_frame_summary(cls, f):
"""
:param FrameSummary f:
:rtype: DummyFrame
"""
return cls(filename=f.filename, lineno=f.lineno, name=f.name, f_locals=f.locals) | python | def from_frame_summary(cls, f):
"""
:param FrameSummary f:
:rtype: DummyFrame
"""
return cls(filename=f.filename, lineno=f.lineno, name=f.name, f_locals=f.locals) | [
"def",
"from_frame_summary",
"(",
"cls",
",",
"f",
")",
":",
"return",
"cls",
"(",
"filename",
"=",
"f",
".",
"filename",
",",
"lineno",
"=",
"f",
".",
"lineno",
",",
"name",
"=",
"f",
".",
"name",
",",
"f_locals",
"=",
"f",
".",
"locals",
")"
] | :param FrameSummary f:
:rtype: DummyFrame | [
":",
"param",
"FrameSummary",
"f",
":",
":",
"rtype",
":",
"DummyFrame"
] | 3d524a027d7fc4e83e47e39a1978849561da69b3 | https://github.com/albertz/py_better_exchook/blob/3d524a027d7fc4e83e47e39a1978849561da69b3/better_exchook.py#L1382-L1387 | train | Create a new object from a FrameSummary. |
thorgate/django-esteid | esteid/signature.py | verify_mid_signature | def verify_mid_signature(certificate_data, sp_challenge, response_challenge, signature):
""" Verify mobile id Authentication signature is valid
:param certificate_data: binary certificate data, from 'CertificateData' field
:param sp_challenge: binary challenge sent via 'SPChallenge' field
:param respon... | python | def verify_mid_signature(certificate_data, sp_challenge, response_challenge, signature):
""" Verify mobile id Authentication signature is valid
:param certificate_data: binary certificate data, from 'CertificateData' field
:param sp_challenge: binary challenge sent via 'SPChallenge' field
:param respon... | [
"def",
"verify_mid_signature",
"(",
"certificate_data",
",",
"sp_challenge",
",",
"response_challenge",
",",
"signature",
")",
":",
"if",
"not",
"response_challenge",
".",
"startswith",
"(",
"sp_challenge",
")",
":",
"return",
"False",
"try",
":",
"key",
"=",
"R... | Verify mobile id Authentication signature is valid
:param certificate_data: binary certificate data, from 'CertificateData' field
:param sp_challenge: binary challenge sent via 'SPChallenge' field
:param response_challenge: response challenge, from 'Challenge' field
:param signature: response signature... | [
"Verify",
"mobile",
"id",
"Authentication",
"signature",
"is",
"valid"
] | 407ae513e357fedea0e3e42198df8eb9d9ff0646 | https://github.com/thorgate/django-esteid/blob/407ae513e357fedea0e3e42198df8eb9d9ff0646/esteid/signature.py#L23-L52 | train | Verify mobile id Authentication signature is valid |
shafaua/visionary | visionary/client.py | GoogleCloudVision.make_request | def make_request(self, image, *features):
"""
Makes single image request
:param image: One of file object, path, or URL
:param features: Recognition features
:return:
"""
return {
"image": {
"content": self.image_to_base64(image)
... | python | def make_request(self, image, *features):
"""
Makes single image request
:param image: One of file object, path, or URL
:param features: Recognition features
:return:
"""
return {
"image": {
"content": self.image_to_base64(image)
... | [
"def",
"make_request",
"(",
"self",
",",
"image",
",",
"*",
"features",
")",
":",
"return",
"{",
"\"image\"",
":",
"{",
"\"content\"",
":",
"self",
".",
"image_to_base64",
"(",
"image",
")",
"}",
",",
"\"features\"",
":",
"[",
"{",
"\"type\"",
":",
"fe... | Makes single image request
:param image: One of file object, path, or URL
:param features: Recognition features
:return: | [
"Makes",
"single",
"image",
"request",
":",
"param",
"image",
":",
"One",
"of",
"file",
"object",
"path",
"or",
"URL",
":",
"param",
"features",
":",
"Recognition",
"features",
":",
"return",
":"
] | 5820c552c27407a7f99677c9190e691ceaa26880 | https://github.com/shafaua/visionary/blob/5820c552c27407a7f99677c9190e691ceaa26880/visionary/client.py#L17-L32 | train | Makes a single image request. |
shafaua/visionary | visionary/client.py | GoogleCloudVision.image_to_base64 | def image_to_base64(self, image):
"""
:param image: One of file object, path, or URL
:return: Base64 of image
"""
if isinstance(image, file_):
return base64.b64encode(image.read())
elif isinstance(image, basestring):
if image.startswith("http"):
... | python | def image_to_base64(self, image):
"""
:param image: One of file object, path, or URL
:return: Base64 of image
"""
if isinstance(image, file_):
return base64.b64encode(image.read())
elif isinstance(image, basestring):
if image.startswith("http"):
... | [
"def",
"image_to_base64",
"(",
"self",
",",
"image",
")",
":",
"if",
"isinstance",
"(",
"image",
",",
"file_",
")",
":",
"return",
"base64",
".",
"b64encode",
"(",
"image",
".",
"read",
"(",
")",
")",
"elif",
"isinstance",
"(",
"image",
",",
"basestrin... | :param image: One of file object, path, or URL
:return: Base64 of image | [
":",
"param",
"image",
":",
"One",
"of",
"file",
"object",
"path",
"or",
"URL",
":",
"return",
":",
"Base64",
"of",
"image"
] | 5820c552c27407a7f99677c9190e691ceaa26880 | https://github.com/shafaua/visionary/blob/5820c552c27407a7f99677c9190e691ceaa26880/visionary/client.py#L34-L50 | train | Converts an image to base64 |
shafaua/visionary | visionary/client.py | GoogleCloudVision.annotate | def annotate(self, image, *features):
"""
:param image: One of file object, path, or URL
:param features: list of Vision Features
:return: GoogleCloudVisionResponse
"""
body = self.make_body(image, *features)
try:
response = requests.post(self.api_url,... | python | def annotate(self, image, *features):
"""
:param image: One of file object, path, or URL
:param features: list of Vision Features
:return: GoogleCloudVisionResponse
"""
body = self.make_body(image, *features)
try:
response = requests.post(self.api_url,... | [
"def",
"annotate",
"(",
"self",
",",
"image",
",",
"*",
"features",
")",
":",
"body",
"=",
"self",
".",
"make_body",
"(",
"image",
",",
"*",
"features",
")",
"try",
":",
"response",
"=",
"requests",
".",
"post",
"(",
"self",
".",
"api_url",
",",
"j... | :param image: One of file object, path, or URL
:param features: list of Vision Features
:return: GoogleCloudVisionResponse | [
":",
"param",
"image",
":",
"One",
"of",
"file",
"object",
"path",
"or",
"URL",
":",
"param",
"features",
":",
"list",
"of",
"Vision",
"Features",
":",
"return",
":",
"GoogleCloudVisionResponse"
] | 5820c552c27407a7f99677c9190e691ceaa26880 | https://github.com/shafaua/visionary/blob/5820c552c27407a7f99677c9190e691ceaa26880/visionary/client.py#L62-L74 | train | Annotate the image with the features. |
untwisted/untwisted | untwisted/dispatcher.py | Dispatcher.drive | def drive(self, event, *args):
"""
Used to dispatch events.
"""
maps = self.base.get(event, self.step)
for handle, data in maps[:]:
params = args + data
try:
handle(self, *params)
except Stop:
break
... | python | def drive(self, event, *args):
"""
Used to dispatch events.
"""
maps = self.base.get(event, self.step)
for handle, data in maps[:]:
params = args + data
try:
handle(self, *params)
except Stop:
break
... | [
"def",
"drive",
"(",
"self",
",",
"event",
",",
"*",
"args",
")",
":",
"maps",
"=",
"self",
".",
"base",
".",
"get",
"(",
"event",
",",
"self",
".",
"step",
")",
"for",
"handle",
",",
"data",
"in",
"maps",
"[",
":",
"]",
":",
"params",
"=",
"... | Used to dispatch events. | [
"Used",
"to",
"dispatch",
"events",
"."
] | 8a8d9c8a8d0f3452d5de67cd760297bb5759f637 | https://github.com/untwisted/untwisted/blob/8a8d9c8a8d0f3452d5de67cd760297bb5759f637/untwisted/dispatcher.py#L16-L38 | train | This method is used to dispatch events. |
untwisted/untwisted | untwisted/dispatcher.py | Dispatcher.add_map | def add_map(self, event, handle, *args):
"""
Add a mapping like event -(arg0, arg1, arg2, ...)-> handle.
"""
item = self.base.setdefault(event, list())
item.append((handle, args)) | python | def add_map(self, event, handle, *args):
"""
Add a mapping like event -(arg0, arg1, arg2, ...)-> handle.
"""
item = self.base.setdefault(event, list())
item.append((handle, args)) | [
"def",
"add_map",
"(",
"self",
",",
"event",
",",
"handle",
",",
"*",
"args",
")",
":",
"item",
"=",
"self",
".",
"base",
".",
"setdefault",
"(",
"event",
",",
"list",
"(",
")",
")",
"item",
".",
"append",
"(",
"(",
"handle",
",",
"args",
")",
... | Add a mapping like event -(arg0, arg1, arg2, ...)-> handle. | [
"Add",
"a",
"mapping",
"like",
"event",
"-",
"(",
"arg0",
"arg1",
"arg2",
"...",
")",
"-",
">",
"handle",
"."
] | 8a8d9c8a8d0f3452d5de67cd760297bb5759f637 | https://github.com/untwisted/untwisted/blob/8a8d9c8a8d0f3452d5de67cd760297bb5759f637/untwisted/dispatcher.py#L40-L46 | train | Add a mapping like event - handle - arg0 arg1 arg2... |
untwisted/untwisted | untwisted/dispatcher.py | Dispatcher.del_map | def del_map(self, event, handle, *args):
"""
Remove a mapping like event -(arg0, arg1, arg2, ...)-> handle.
"""
if args:
self.base[event].remove((handle, args))
else:
self.base[event] = [ind for ind in self.base[event] if ind[0] != handle] | python | def del_map(self, event, handle, *args):
"""
Remove a mapping like event -(arg0, arg1, arg2, ...)-> handle.
"""
if args:
self.base[event].remove((handle, args))
else:
self.base[event] = [ind for ind in self.base[event] if ind[0] != handle] | [
"def",
"del_map",
"(",
"self",
",",
"event",
",",
"handle",
",",
"*",
"args",
")",
":",
"if",
"args",
":",
"self",
".",
"base",
"[",
"event",
"]",
".",
"remove",
"(",
"(",
"handle",
",",
"args",
")",
")",
"else",
":",
"self",
".",
"base",
"[",
... | Remove a mapping like event -(arg0, arg1, arg2, ...)-> handle. | [
"Remove",
"a",
"mapping",
"like",
"event",
"-",
"(",
"arg0",
"arg1",
"arg2",
"...",
")",
"-",
">",
"handle",
"."
] | 8a8d9c8a8d0f3452d5de67cd760297bb5759f637 | https://github.com/untwisted/untwisted/blob/8a8d9c8a8d0f3452d5de67cd760297bb5759f637/untwisted/dispatcher.py#L48-L55 | train | Removes a mapping like event - arg0 arg1 arg2... |
untwisted/untwisted | untwisted/expect.py | Expect.send | def send(self, data):
"""
Send data to the child process through.
"""
self.stdin.write(data)
self.stdin.flush() | python | def send(self, data):
"""
Send data to the child process through.
"""
self.stdin.write(data)
self.stdin.flush() | [
"def",
"send",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"stdin",
".",
"write",
"(",
"data",
")",
"self",
".",
"stdin",
".",
"flush",
"(",
")"
] | Send data to the child process through. | [
"Send",
"data",
"to",
"the",
"child",
"process",
"through",
"."
] | 8a8d9c8a8d0f3452d5de67cd760297bb5759f637 | https://github.com/untwisted/untwisted/blob/8a8d9c8a8d0f3452d5de67cd760297bb5759f637/untwisted/expect.py#L43-L48 | train | Send data to the child process through. |
untwisted/untwisted | untwisted/expect.py | Expect.destroy | def destroy(self):
"""
Unregister up from untwisted reactor. It is needed
to call self.terminate() first to kill the process.
"""
core.gear.pool.remove(self)
self.base.clear() | python | def destroy(self):
"""
Unregister up from untwisted reactor. It is needed
to call self.terminate() first to kill the process.
"""
core.gear.pool.remove(self)
self.base.clear() | [
"def",
"destroy",
"(",
"self",
")",
":",
"core",
".",
"gear",
".",
"pool",
".",
"remove",
"(",
"self",
")",
"self",
".",
"base",
".",
"clear",
"(",
")"
] | Unregister up from untwisted reactor. It is needed
to call self.terminate() first to kill the process. | [
"Unregister",
"up",
"from",
"untwisted",
"reactor",
".",
"It",
"is",
"needed",
"to",
"call",
"self",
".",
"terminate",
"()",
"first",
"to",
"kill",
"the",
"process",
"."
] | 8a8d9c8a8d0f3452d5de67cd760297bb5759f637 | https://github.com/untwisted/untwisted/blob/8a8d9c8a8d0f3452d5de67cd760297bb5759f637/untwisted/expect.py#L84-L90 | train | Unregister up from untwisted reactor. It is needed to terminate the process. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.