repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
GiulioRossetti/dynetx | dynetx/classes/dyndigraph.py | DynDiGraph.number_of_interactions | def number_of_interactions(self, u=None, v=None, t=None):
"""Return the number of interaction between two nodes at time t.
Parameters
----------
u, v : nodes, optional (default=all interaction)
If u and v are specified, return the number of interaction between
u ... | python | def number_of_interactions(self, u=None, v=None, t=None):
"""Return the number of interaction between two nodes at time t.
Parameters
----------
u, v : nodes, optional (default=all interaction)
If u and v are specified, return the number of interaction between
u ... | [
"def",
"number_of_interactions",
"(",
"self",
",",
"u",
"=",
"None",
",",
"v",
"=",
"None",
",",
"t",
"=",
"None",
")",
":",
"if",
"t",
"is",
"None",
":",
"if",
"u",
"is",
"None",
":",
"return",
"int",
"(",
"self",
".",
"size",
"(",
")",
")",
... | Return the number of interaction between two nodes at time t.
Parameters
----------
u, v : nodes, optional (default=all interaction)
If u and v are specified, return the number of interaction between
u and v. Otherwise return the total number of all interaction.
... | [
"Return",
"the",
"number",
"of",
"interaction",
"between",
"two",
"nodes",
"at",
"time",
"t",
"."
] | train | https://github.com/GiulioRossetti/dynetx/blob/634e2b38f8950885aebfa079dad7d5e8d7563f1d/dynetx/classes/dyndigraph.py#L767-L816 |
GiulioRossetti/dynetx | dynetx/classes/dyndigraph.py | DynDiGraph.has_interaction | def has_interaction(self, u, v, t=None):
"""Return True if the interaction (u,v) is in the graph at time t.
Parameters
----------
u, v : nodes
Nodes can be, for example, strings or numbers.
Nodes must be hashable (and not None) Python objects.
t : snapsho... | python | def has_interaction(self, u, v, t=None):
"""Return True if the interaction (u,v) is in the graph at time t.
Parameters
----------
u, v : nodes
Nodes can be, for example, strings or numbers.
Nodes must be hashable (and not None) Python objects.
t : snapsho... | [
"def",
"has_interaction",
"(",
"self",
",",
"u",
",",
"v",
",",
"t",
"=",
"None",
")",
":",
"try",
":",
"if",
"t",
"is",
"None",
":",
"return",
"v",
"in",
"self",
".",
"_succ",
"[",
"u",
"]",
"else",
":",
"return",
"v",
"in",
"self",
".",
"_s... | Return True if the interaction (u,v) is in the graph at time t.
Parameters
----------
u, v : nodes
Nodes can be, for example, strings or numbers.
Nodes must be hashable (and not None) Python objects.
t : snapshot id (default=None)
If None will be retu... | [
"Return",
"True",
"if",
"the",
"interaction",
"(",
"u",
"v",
")",
"is",
"in",
"the",
"graph",
"at",
"time",
"t",
"."
] | train | https://github.com/GiulioRossetti/dynetx/blob/634e2b38f8950885aebfa079dad7d5e8d7563f1d/dynetx/classes/dyndigraph.py#L818-L854 |
GiulioRossetti/dynetx | dynetx/classes/dyndigraph.py | DynDiGraph.has_successor | def has_successor(self, u, v, t=None):
"""Return True if node u has successor v at time t (optional).
This is true if graph has the edge u->v.
Parameters
----------
u, v : nodes
Nodes can be, for example, strings or numbers.
Nodes must be hashable (and n... | python | def has_successor(self, u, v, t=None):
"""Return True if node u has successor v at time t (optional).
This is true if graph has the edge u->v.
Parameters
----------
u, v : nodes
Nodes can be, for example, strings or numbers.
Nodes must be hashable (and n... | [
"def",
"has_successor",
"(",
"self",
",",
"u",
",",
"v",
",",
"t",
"=",
"None",
")",
":",
"return",
"self",
".",
"has_interaction",
"(",
"u",
",",
"v",
",",
"t",
")"
] | Return True if node u has successor v at time t (optional).
This is true if graph has the edge u->v.
Parameters
----------
u, v : nodes
Nodes can be, for example, strings or numbers.
Nodes must be hashable (and not None) Python objects.
t : snapshot id (... | [
"Return",
"True",
"if",
"node",
"u",
"has",
"successor",
"v",
"at",
"time",
"t",
"(",
"optional",
")",
"."
] | train | https://github.com/GiulioRossetti/dynetx/blob/634e2b38f8950885aebfa079dad7d5e8d7563f1d/dynetx/classes/dyndigraph.py#L856-L870 |
GiulioRossetti/dynetx | dynetx/classes/dyndigraph.py | DynDiGraph.has_predecessor | def has_predecessor(self, u, v, t=None):
"""Return True if node u has predecessor v at time t (optional).
This is true if graph has the edge u<-v.
Parameters
----------
u, v : nodes
Nodes can be, for example, strings or numbers.
Nodes must be hashable (a... | python | def has_predecessor(self, u, v, t=None):
"""Return True if node u has predecessor v at time t (optional).
This is true if graph has the edge u<-v.
Parameters
----------
u, v : nodes
Nodes can be, for example, strings or numbers.
Nodes must be hashable (a... | [
"def",
"has_predecessor",
"(",
"self",
",",
"u",
",",
"v",
",",
"t",
"=",
"None",
")",
":",
"return",
"self",
".",
"has_interaction",
"(",
"v",
",",
"u",
",",
"t",
")"
] | Return True if node u has predecessor v at time t (optional).
This is true if graph has the edge u<-v.
Parameters
----------
u, v : nodes
Nodes can be, for example, strings or numbers.
Nodes must be hashable (and not None) Python objects.
t : snapshot id... | [
"Return",
"True",
"if",
"node",
"u",
"has",
"predecessor",
"v",
"at",
"time",
"t",
"(",
"optional",
")",
"."
] | train | https://github.com/GiulioRossetti/dynetx/blob/634e2b38f8950885aebfa079dad7d5e8d7563f1d/dynetx/classes/dyndigraph.py#L872-L886 |
GiulioRossetti/dynetx | dynetx/classes/dyndigraph.py | DynDiGraph.successors_iter | def successors_iter(self, n, t=None):
"""Return an iterator over successor nodes of n at time t (optional).
Parameters
----------
n : node
Nodes can be, for example, strings or numbers.
Nodes must be hashable (and not None) Python objects.
t : snapshot id ... | python | def successors_iter(self, n, t=None):
"""Return an iterator over successor nodes of n at time t (optional).
Parameters
----------
n : node
Nodes can be, for example, strings or numbers.
Nodes must be hashable (and not None) Python objects.
t : snapshot id ... | [
"def",
"successors_iter",
"(",
"self",
",",
"n",
",",
"t",
"=",
"None",
")",
":",
"try",
":",
"if",
"t",
"is",
"None",
":",
"return",
"iter",
"(",
"self",
".",
"_succ",
"[",
"n",
"]",
")",
"else",
":",
"return",
"iter",
"(",
"[",
"i",
"for",
... | Return an iterator over successor nodes of n at time t (optional).
Parameters
----------
n : node
Nodes can be, for example, strings or numbers.
Nodes must be hashable (and not None) Python objects.
t : snapshot id (default=None)
If None will be return... | [
"Return",
"an",
"iterator",
"over",
"successor",
"nodes",
"of",
"n",
"at",
"time",
"t",
"(",
"optional",
")",
".",
"Parameters",
"----------",
"n",
":",
"node",
"Nodes",
"can",
"be",
"for",
"example",
"strings",
"or",
"numbers",
".",
"Nodes",
"must",
"be... | train | https://github.com/GiulioRossetti/dynetx/blob/634e2b38f8950885aebfa079dad7d5e8d7563f1d/dynetx/classes/dyndigraph.py#L888-L906 |
GiulioRossetti/dynetx | dynetx/classes/dyndigraph.py | DynDiGraph.predecessors_iter | def predecessors_iter(self, n, t=None):
"""Return an iterator over predecessors nodes of n at time t (optional).
Parameters
----------
n : node
Nodes can be, for example, strings or numbers.
Nodes must be hashable (and not None) Python objects.
t : snapsh... | python | def predecessors_iter(self, n, t=None):
"""Return an iterator over predecessors nodes of n at time t (optional).
Parameters
----------
n : node
Nodes can be, for example, strings or numbers.
Nodes must be hashable (and not None) Python objects.
t : snapsh... | [
"def",
"predecessors_iter",
"(",
"self",
",",
"n",
",",
"t",
"=",
"None",
")",
":",
"try",
":",
"if",
"t",
"is",
"None",
":",
"return",
"iter",
"(",
"self",
".",
"_pred",
"[",
"n",
"]",
")",
"else",
":",
"return",
"iter",
"(",
"[",
"i",
"for",
... | Return an iterator over predecessors nodes of n at time t (optional).
Parameters
----------
n : node
Nodes can be, for example, strings or numbers.
Nodes must be hashable (and not None) Python objects.
t : snapshot id (default=None)
If None will be re... | [
"Return",
"an",
"iterator",
"over",
"predecessors",
"nodes",
"of",
"n",
"at",
"time",
"t",
"(",
"optional",
")",
"."
] | train | https://github.com/GiulioRossetti/dynetx/blob/634e2b38f8950885aebfa079dad7d5e8d7563f1d/dynetx/classes/dyndigraph.py#L908-L927 |
GiulioRossetti/dynetx | dynetx/classes/dyndigraph.py | DynDiGraph.in_degree | def in_degree(self, nbunch=None, t=None):
"""Return the in degree of a node or nodes at time t.
The node in degree is the number of incoming interaction to that node in a given time frame.
Parameters
----------
nbunch : iterable container, optional (default=all nodes)
... | python | def in_degree(self, nbunch=None, t=None):
"""Return the in degree of a node or nodes at time t.
The node in degree is the number of incoming interaction to that node in a given time frame.
Parameters
----------
nbunch : iterable container, optional (default=all nodes)
... | [
"def",
"in_degree",
"(",
"self",
",",
"nbunch",
"=",
"None",
",",
"t",
"=",
"None",
")",
":",
"if",
"nbunch",
"in",
"self",
":",
"# return a single node",
"return",
"next",
"(",
"self",
".",
"in_degree_iter",
"(",
"nbunch",
",",
"t",
")",
")",
"[",
"... | Return the in degree of a node or nodes at time t.
The node in degree is the number of incoming interaction to that node in a given time frame.
Parameters
----------
nbunch : iterable container, optional (default=all nodes)
A container of nodes. The container will be itera... | [
"Return",
"the",
"in",
"degree",
"of",
"a",
"node",
"or",
"nodes",
"at",
"time",
"t",
"."
] | train | https://github.com/GiulioRossetti/dynetx/blob/634e2b38f8950885aebfa079dad7d5e8d7563f1d/dynetx/classes/dyndigraph.py#L961-L998 |
GiulioRossetti/dynetx | dynetx/classes/dyndigraph.py | DynDiGraph.in_degree_iter | def in_degree_iter(self, nbunch=None, t=None):
"""Return an iterator for (node, in_degree) at time t.
The node degree is the number of edges incoming to the node in a given timeframe.
Parameters
----------
nbunch : iterable container, optional (default=all nodes)
A ... | python | def in_degree_iter(self, nbunch=None, t=None):
"""Return an iterator for (node, in_degree) at time t.
The node degree is the number of edges incoming to the node in a given timeframe.
Parameters
----------
nbunch : iterable container, optional (default=all nodes)
A ... | [
"def",
"in_degree_iter",
"(",
"self",
",",
"nbunch",
"=",
"None",
",",
"t",
"=",
"None",
")",
":",
"if",
"nbunch",
"is",
"None",
":",
"nodes_nbrs",
"=",
"self",
".",
"_pred",
".",
"items",
"(",
")",
"else",
":",
"nodes_nbrs",
"=",
"(",
"(",
"n",
... | Return an iterator for (node, in_degree) at time t.
The node degree is the number of edges incoming to the node in a given timeframe.
Parameters
----------
nbunch : iterable container, optional (default=all nodes)
A container of nodes. The container will be iterated
... | [
"Return",
"an",
"iterator",
"for",
"(",
"node",
"in_degree",
")",
"at",
"time",
"t",
"."
] | train | https://github.com/GiulioRossetti/dynetx/blob/634e2b38f8950885aebfa079dad7d5e8d7563f1d/dynetx/classes/dyndigraph.py#L1000-L1048 |
GiulioRossetti/dynetx | dynetx/classes/dyndigraph.py | DynDiGraph.out_degree | def out_degree(self, nbunch=None, t=None):
"""Return the out degree of a node or nodes at time t.
The node degree is the number of interaction outgoing from that node in a given time frame.
Parameters
----------
nbunch : iterable container, optional (default=all nodes)
... | python | def out_degree(self, nbunch=None, t=None):
"""Return the out degree of a node or nodes at time t.
The node degree is the number of interaction outgoing from that node in a given time frame.
Parameters
----------
nbunch : iterable container, optional (default=all nodes)
... | [
"def",
"out_degree",
"(",
"self",
",",
"nbunch",
"=",
"None",
",",
"t",
"=",
"None",
")",
":",
"if",
"nbunch",
"in",
"self",
":",
"# return a single node",
"return",
"next",
"(",
"self",
".",
"out_degree_iter",
"(",
"nbunch",
",",
"t",
")",
")",
"[",
... | Return the out degree of a node or nodes at time t.
The node degree is the number of interaction outgoing from that node in a given time frame.
Parameters
----------
nbunch : iterable container, optional (default=all nodes)
A container of nodes. The container will be itera... | [
"Return",
"the",
"out",
"degree",
"of",
"a",
"node",
"or",
"nodes",
"at",
"time",
"t",
"."
] | train | https://github.com/GiulioRossetti/dynetx/blob/634e2b38f8950885aebfa079dad7d5e8d7563f1d/dynetx/classes/dyndigraph.py#L1050-L1087 |
GiulioRossetti/dynetx | dynetx/classes/dyndigraph.py | DynDiGraph.out_degree_iter | def out_degree_iter(self, nbunch=None, t=None):
"""Return an iterator for (node, out_degree) at time t.
The node out degree is the number of interactions outgoing from the node in a given timeframe.
Parameters
----------
nbunch : iterable container, optional (default=all nodes)... | python | def out_degree_iter(self, nbunch=None, t=None):
"""Return an iterator for (node, out_degree) at time t.
The node out degree is the number of interactions outgoing from the node in a given timeframe.
Parameters
----------
nbunch : iterable container, optional (default=all nodes)... | [
"def",
"out_degree_iter",
"(",
"self",
",",
"nbunch",
"=",
"None",
",",
"t",
"=",
"None",
")",
":",
"if",
"nbunch",
"is",
"None",
":",
"nodes_nbrs",
"=",
"self",
".",
"_succ",
".",
"items",
"(",
")",
"else",
":",
"nodes_nbrs",
"=",
"(",
"(",
"n",
... | Return an iterator for (node, out_degree) at time t.
The node out degree is the number of interactions outgoing from the node in a given timeframe.
Parameters
----------
nbunch : iterable container, optional (default=all nodes)
A container of nodes. The container will be i... | [
"Return",
"an",
"iterator",
"for",
"(",
"node",
"out_degree",
")",
"at",
"time",
"t",
"."
] | train | https://github.com/GiulioRossetti/dynetx/blob/634e2b38f8950885aebfa079dad7d5e8d7563f1d/dynetx/classes/dyndigraph.py#L1089-L1137 |
GiulioRossetti/dynetx | dynetx/classes/dyndigraph.py | DynDiGraph.to_undirected | def to_undirected(self, reciprocal=False):
"""Return an undirected representation of the dyndigraph.
Parameters
----------
reciprocal : bool (optional)
If True only keep edges that appear in both directions
in the original dyndigraph.
Returns
-------... | python | def to_undirected(self, reciprocal=False):
"""Return an undirected representation of the dyndigraph.
Parameters
----------
reciprocal : bool (optional)
If True only keep edges that appear in both directions
in the original dyndigraph.
Returns
-------... | [
"def",
"to_undirected",
"(",
"self",
",",
"reciprocal",
"=",
"False",
")",
":",
"from",
".",
"dyngraph",
"import",
"DynGraph",
"H",
"=",
"DynGraph",
"(",
")",
"H",
".",
"name",
"=",
"self",
".",
"name",
"H",
".",
"add_nodes_from",
"(",
"self",
")",
"... | Return an undirected representation of the dyndigraph.
Parameters
----------
reciprocal : bool (optional)
If True only keep edges that appear in both directions
in the original dyndigraph.
Returns
-------
G : DynGraph
An undirected dynami... | [
"Return",
"an",
"undirected",
"representation",
"of",
"the",
"dyndigraph",
"."
] | train | https://github.com/GiulioRossetti/dynetx/blob/634e2b38f8950885aebfa079dad7d5e8d7563f1d/dynetx/classes/dyndigraph.py#L1602-L1675 |
GiulioRossetti/dynetx | dynetx/readwrite/edgelist.py | write_interactions | def write_interactions(G, path, delimiter=' ', encoding='utf-8'):
"""Write a DyNetx graph in interaction list format.
Parameters
----------
G : graph
A DyNetx graph.
path : basestring
The desired output filename
delimiter : character
... | python | def write_interactions(G, path, delimiter=' ', encoding='utf-8'):
"""Write a DyNetx graph in interaction list format.
Parameters
----------
G : graph
A DyNetx graph.
path : basestring
The desired output filename
delimiter : character
... | [
"def",
"write_interactions",
"(",
"G",
",",
"path",
",",
"delimiter",
"=",
"' '",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"for",
"line",
"in",
"generate_interactions",
"(",
"G",
",",
"delimiter",
")",
":",
"line",
"+=",
"'\\n'",
"path",
".",
"write",
... | Write a DyNetx graph in interaction list format.
Parameters
----------
G : graph
A DyNetx graph.
path : basestring
The desired output filename
delimiter : character
Column delimiter | [
"Write",
"a",
"DyNetx",
"graph",
"in",
"interaction",
"list",
"format",
"."
] | train | https://github.com/GiulioRossetti/dynetx/blob/634e2b38f8950885aebfa079dad7d5e8d7563f1d/dynetx/readwrite/edgelist.py#L49-L67 |
GiulioRossetti/dynetx | dynetx/readwrite/edgelist.py | read_interactions | def read_interactions(path, comments="#", directed=False, delimiter=None,
nodetype=None, timestamptype=None, encoding='utf-8', keys=False):
"""Read a DyNetx graph from interaction list format.
Parameters
----------
path : basestring
The desired output filenam... | python | def read_interactions(path, comments="#", directed=False, delimiter=None,
nodetype=None, timestamptype=None, encoding='utf-8', keys=False):
"""Read a DyNetx graph from interaction list format.
Parameters
----------
path : basestring
The desired output filenam... | [
"def",
"read_interactions",
"(",
"path",
",",
"comments",
"=",
"\"#\"",
",",
"directed",
"=",
"False",
",",
"delimiter",
"=",
"None",
",",
"nodetype",
"=",
"None",
",",
"timestamptype",
"=",
"None",
",",
"encoding",
"=",
"'utf-8'",
",",
"keys",
"=",
"Fal... | Read a DyNetx graph from interaction list format.
Parameters
----------
path : basestring
The desired output filename
delimiter : character
Column delimiter | [
"Read",
"a",
"DyNetx",
"graph",
"from",
"interaction",
"list",
"format",
"."
] | train | https://github.com/GiulioRossetti/dynetx/blob/634e2b38f8950885aebfa079dad7d5e8d7563f1d/dynetx/readwrite/edgelist.py#L71-L91 |
GiulioRossetti/dynetx | dynetx/readwrite/edgelist.py | write_snapshots | def write_snapshots(G, path, delimiter=' ', encoding='utf-8'):
"""Write a DyNetx graph in snapshot graph list format.
Parameters
----------
G : graph
A DyNetx graph.
path : basestring
The desired output filename
delimiter : character
C... | python | def write_snapshots(G, path, delimiter=' ', encoding='utf-8'):
"""Write a DyNetx graph in snapshot graph list format.
Parameters
----------
G : graph
A DyNetx graph.
path : basestring
The desired output filename
delimiter : character
C... | [
"def",
"write_snapshots",
"(",
"G",
",",
"path",
",",
"delimiter",
"=",
"' '",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"for",
"line",
"in",
"generate_snapshots",
"(",
"G",
",",
"delimiter",
")",
":",
"line",
"+=",
"'\\n'",
"path",
".",
"write",
"(",... | Write a DyNetx graph in snapshot graph list format.
Parameters
----------
G : graph
A DyNetx graph.
path : basestring
The desired output filename
delimiter : character
Column delimiter | [
"Write",
"a",
"DyNetx",
"graph",
"in",
"snapshot",
"graph",
"list",
"format",
"."
] | train | https://github.com/GiulioRossetti/dynetx/blob/634e2b38f8950885aebfa079dad7d5e8d7563f1d/dynetx/readwrite/edgelist.py#L164-L182 |
GiulioRossetti/dynetx | dynetx/readwrite/edgelist.py | read_snapshots | def read_snapshots(path, comments="#", directed=False, delimiter=None,
nodetype=None, timestamptype=None, encoding='utf-8', keys=False):
"""Read a DyNetx graph from snapshot graph list format.
Parameters
----------
path : basestring
The desired output filena... | python | def read_snapshots(path, comments="#", directed=False, delimiter=None,
nodetype=None, timestamptype=None, encoding='utf-8', keys=False):
"""Read a DyNetx graph from snapshot graph list format.
Parameters
----------
path : basestring
The desired output filena... | [
"def",
"read_snapshots",
"(",
"path",
",",
"comments",
"=",
"\"#\"",
",",
"directed",
"=",
"False",
",",
"delimiter",
"=",
"None",
",",
"nodetype",
"=",
"None",
",",
"timestamptype",
"=",
"None",
",",
"encoding",
"=",
"'utf-8'",
",",
"keys",
"=",
"False"... | Read a DyNetx graph from snapshot graph list format.
Parameters
----------
path : basestring
The desired output filename
delimiter : character
Column delimiter | [
"Read",
"a",
"DyNetx",
"graph",
"from",
"snapshot",
"graph",
"list",
"format",
"."
] | train | https://github.com/GiulioRossetti/dynetx/blob/634e2b38f8950885aebfa079dad7d5e8d7563f1d/dynetx/readwrite/edgelist.py#L237-L257 |
GiulioRossetti/dynetx | dynetx/utils/decorators.py | open_file | def open_file(path_arg, mode='r'):
"""Decorator to ensure clean opening and closing of files.
Parameters
----------
path_arg : int
Location of the path argument in args. Even if the argument is a
named positional argument (with a default value), you must specify its
index as a ... | python | def open_file(path_arg, mode='r'):
"""Decorator to ensure clean opening and closing of files.
Parameters
----------
path_arg : int
Location of the path argument in args. Even if the argument is a
named positional argument (with a default value), you must specify its
index as a ... | [
"def",
"open_file",
"(",
"path_arg",
",",
"mode",
"=",
"'r'",
")",
":",
"# Note that this decorator solves the problem when a path argument is",
"# specified as a string, but it does not handle the situation when the",
"# function wants to accept a default of None (and then handle it).",
"... | Decorator to ensure clean opening and closing of files.
Parameters
----------
path_arg : int
Location of the path argument in args. Even if the argument is a
named positional argument (with a default value), you must specify its
index as a positional argument.
mode : str
... | [
"Decorator",
"to",
"ensure",
"clean",
"opening",
"and",
"closing",
"of",
"files",
"."
] | train | https://github.com/GiulioRossetti/dynetx/blob/634e2b38f8950885aebfa079dad7d5e8d7563f1d/dynetx/utils/decorators.py#L62-L201 |
GiulioRossetti/dynetx | dynetx/classes/function.py | number_of_interactions | def number_of_interactions(G, u=None, v=None, t=None):
"""Return the number of edges between two nodes at time t.
Parameters
----------
u, v : nodes, optional (default=all edges)
If u and v are specified, return the number of edges between
u and v. Otherwise return t... | python | def number_of_interactions(G, u=None, v=None, t=None):
"""Return the number of edges between two nodes at time t.
Parameters
----------
u, v : nodes, optional (default=all edges)
If u and v are specified, return the number of edges between
u and v. Otherwise return t... | [
"def",
"number_of_interactions",
"(",
"G",
",",
"u",
"=",
"None",
",",
"v",
"=",
"None",
",",
"t",
"=",
"None",
")",
":",
"return",
"G",
".",
"number_of_interactions",
"(",
"u",
",",
"v",
",",
"t",
")"
] | Return the number of edges between two nodes at time t.
Parameters
----------
u, v : nodes, optional (default=all edges)
If u and v are specified, return the number of edges between
u and v. Otherwise return the total number of all edges.
t : snapshot id (default... | [
"Return",
"the",
"number",
"of",
"edges",
"between",
"two",
"nodes",
"at",
"time",
"t",
"."
] | train | https://github.com/GiulioRossetti/dynetx/blob/634e2b38f8950885aebfa079dad7d5e8d7563f1d/dynetx/classes/function.py#L211-L235 |
GiulioRossetti/dynetx | dynetx/classes/function.py | density | def density(G, t=None):
r"""Return the density of a graph at timestamp t.
The density for undirected graphs is
.. math::
d = \frac{2m}{n(n-1)},
and for directed graphs is
.. math::
d = \frac{m}{n(n-1)},
where `n` is the number of nodes and `m` is th... | python | def density(G, t=None):
r"""Return the density of a graph at timestamp t.
The density for undirected graphs is
.. math::
d = \frac{2m}{n(n-1)},
and for directed graphs is
.. math::
d = \frac{m}{n(n-1)},
where `n` is the number of nodes and `m` is th... | [
"def",
"density",
"(",
"G",
",",
"t",
"=",
"None",
")",
":",
"n",
"=",
"number_of_nodes",
"(",
"G",
",",
"t",
")",
"m",
"=",
"number_of_interactions",
"(",
"G",
",",
"t",
")",
"if",
"m",
"==",
"0",
"or",
"m",
"is",
"None",
"or",
"n",
"<=",
"1... | r"""Return the density of a graph at timestamp t.
The density for undirected graphs is
.. math::
d = \frac{2m}{n(n-1)},
and for directed graphs is
.. math::
d = \frac{m}{n(n-1)},
where `n` is the number of nodes and `m` is the number of edges in `G`.
... | [
"r",
"Return",
"the",
"density",
"of",
"a",
"graph",
"at",
"timestamp",
"t",
".",
"The",
"density",
"for",
"undirected",
"graphs",
"is"
] | train | https://github.com/GiulioRossetti/dynetx/blob/634e2b38f8950885aebfa079dad7d5e8d7563f1d/dynetx/classes/function.py#L238-L279 |
GiulioRossetti/dynetx | dynetx/classes/function.py | degree_histogram | def degree_histogram(G, t=None):
"""Return a list of the frequency of each degree value.
Parameters
----------
G : Graph opject
DyNetx graph object
t : snapshot id (default=None)
snapshot id
Returns
-------
hist : list
... | python | def degree_histogram(G, t=None):
"""Return a list of the frequency of each degree value.
Parameters
----------
G : Graph opject
DyNetx graph object
t : snapshot id (default=None)
snapshot id
Returns
-------
hist : list
... | [
"def",
"degree_histogram",
"(",
"G",
",",
"t",
"=",
"None",
")",
":",
"counts",
"=",
"Counter",
"(",
"d",
"for",
"n",
",",
"d",
"in",
"G",
".",
"degree",
"(",
"t",
"=",
"t",
")",
".",
"items",
"(",
")",
")",
"return",
"[",
"counts",
".",
"get... | Return a list of the frequency of each degree value.
Parameters
----------
G : Graph opject
DyNetx graph object
t : snapshot id (default=None)
snapshot id
Returns
-------
hist : list
A list of frequencies of degrees.
... | [
"Return",
"a",
"list",
"of",
"the",
"frequency",
"of",
"each",
"degree",
"value",
"."
] | train | https://github.com/GiulioRossetti/dynetx/blob/634e2b38f8950885aebfa079dad7d5e8d7563f1d/dynetx/classes/function.py#L282-L308 |
GiulioRossetti/dynetx | dynetx/classes/function.py | freeze | def freeze(G):
"""Modify graph to prevent further change by adding or removing nodes or edges.
Node and edge data can still be modified.
Parameters
----------
G : graph
A NetworkX graph
Notes
-----
To "unfreeze" a graph you must make a... | python | def freeze(G):
"""Modify graph to prevent further change by adding or removing nodes or edges.
Node and edge data can still be modified.
Parameters
----------
G : graph
A NetworkX graph
Notes
-----
To "unfreeze" a graph you must make a... | [
"def",
"freeze",
"(",
"G",
")",
":",
"G",
".",
"add_node",
"=",
"frozen",
"G",
".",
"add_nodes_from",
"=",
"frozen",
"G",
".",
"remove_node",
"=",
"frozen",
"G",
".",
"remove_nodes_from",
"=",
"frozen",
"G",
".",
"add_edge",
"=",
"frozen",
"G",
".",
... | Modify graph to prevent further change by adding or removing nodes or edges.
Node and edge data can still be modified.
Parameters
----------
G : graph
A NetworkX graph
Notes
-----
To "unfreeze" a graph you must make a copy by creating a ne... | [
"Modify",
"graph",
"to",
"prevent",
"further",
"change",
"by",
"adding",
"or",
"removing",
"nodes",
"or",
"edges",
"."
] | train | https://github.com/GiulioRossetti/dynetx/blob/634e2b38f8950885aebfa079dad7d5e8d7563f1d/dynetx/classes/function.py#L321-L351 |
GiulioRossetti/dynetx | dynetx/classes/function.py | add_star | def add_star(G, nodes, t, **attr):
"""Add a star at time t.
The first node in nodes is the middle of the star. It is connected
to all other nodes.
Parameters
----------
G : graph
A DyNetx graph
nodes : iterable container
... | python | def add_star(G, nodes, t, **attr):
"""Add a star at time t.
The first node in nodes is the middle of the star. It is connected
to all other nodes.
Parameters
----------
G : graph
A DyNetx graph
nodes : iterable container
... | [
"def",
"add_star",
"(",
"G",
",",
"nodes",
",",
"t",
",",
"*",
"*",
"attr",
")",
":",
"nlist",
"=",
"iter",
"(",
"nodes",
")",
"v",
"=",
"next",
"(",
"nlist",
")",
"edges",
"=",
"(",
"(",
"v",
",",
"n",
")",
"for",
"n",
"in",
"nlist",
")",
... | Add a star at time t.
The first node in nodes is the middle of the star. It is connected
to all other nodes.
Parameters
----------
G : graph
A DyNetx graph
nodes : iterable container
A container of nodes.
... | [
"Add",
"a",
"star",
"at",
"time",
"t",
"."
] | train | https://github.com/GiulioRossetti/dynetx/blob/634e2b38f8950885aebfa079dad7d5e8d7563f1d/dynetx/classes/function.py#L372-L401 |
GiulioRossetti/dynetx | dynetx/classes/function.py | add_path | def add_path(G, nodes, t, **attr):
"""Add a path at time t.
Parameters
----------
G : graph
A DyNetx graph
nodes : iterable container
A container of nodes.
t : snapshot id (default=None)
snapshot id
... | python | def add_path(G, nodes, t, **attr):
"""Add a path at time t.
Parameters
----------
G : graph
A DyNetx graph
nodes : iterable container
A container of nodes.
t : snapshot id (default=None)
snapshot id
... | [
"def",
"add_path",
"(",
"G",
",",
"nodes",
",",
"t",
",",
"*",
"*",
"attr",
")",
":",
"nlist",
"=",
"list",
"(",
"nodes",
")",
"edges",
"=",
"zip",
"(",
"nlist",
"[",
":",
"-",
"1",
"]",
",",
"nlist",
"[",
"1",
":",
"]",
")",
"G",
".",
"a... | Add a path at time t.
Parameters
----------
G : graph
A DyNetx graph
nodes : iterable container
A container of nodes.
t : snapshot id (default=None)
snapshot id
See Also
--------
... | [
"Add",
"a",
"path",
"at",
"time",
"t",
"."
] | train | https://github.com/GiulioRossetti/dynetx/blob/634e2b38f8950885aebfa079dad7d5e8d7563f1d/dynetx/classes/function.py#L404-L429 |
GiulioRossetti/dynetx | dynetx/classes/function.py | create_empty_copy | def create_empty_copy(G, with_data=True):
"""Return a copy of the graph G with all of the edges removed.
Parameters
----------
G : graph
A DyNetx graph
with_data : bool (default=True)
Include data.
Notes
-----
Graph and edge data is n... | python | def create_empty_copy(G, with_data=True):
"""Return a copy of the graph G with all of the edges removed.
Parameters
----------
G : graph
A DyNetx graph
with_data : bool (default=True)
Include data.
Notes
-----
Graph and edge data is n... | [
"def",
"create_empty_copy",
"(",
"G",
",",
"with_data",
"=",
"True",
")",
":",
"H",
"=",
"G",
".",
"__class__",
"(",
")",
"H",
".",
"add_nodes_from",
"(",
"G",
".",
"nodes",
"(",
"data",
"=",
"with_data",
")",
")",
"if",
"with_data",
":",
"H",
".",... | Return a copy of the graph G with all of the edges removed.
Parameters
----------
G : graph
A DyNetx graph
with_data : bool (default=True)
Include data.
Notes
-----
Graph and edge data is not propagated to the new graph. | [
"Return",
"a",
"copy",
"of",
"the",
"graph",
"G",
"with",
"all",
"of",
"the",
"edges",
"removed",
".",
"Parameters",
"----------"
] | train | https://github.com/GiulioRossetti/dynetx/blob/634e2b38f8950885aebfa079dad7d5e8d7563f1d/dynetx/classes/function.py#L481-L500 |
GiulioRossetti/dynetx | dynetx/classes/function.py | set_node_attributes | def set_node_attributes(G, values, name=None):
"""Set node attributes from dictionary of nodes and values
Parameters
----------
G : DyNetx Graph
name : string
Attribute name
values: dict
Dictionary of attribute values keyed by node. If `values` is not... | python | def set_node_attributes(G, values, name=None):
"""Set node attributes from dictionary of nodes and values
Parameters
----------
G : DyNetx Graph
name : string
Attribute name
values: dict
Dictionary of attribute values keyed by node. If `values` is not... | [
"def",
"set_node_attributes",
"(",
"G",
",",
"values",
",",
"name",
"=",
"None",
")",
":",
"# Set node attributes based on type of `values`",
"if",
"name",
"is",
"not",
"None",
":",
"# `values` must not be a dict of dict",
"try",
":",
"# `values` is a dict",
"for",
"n... | Set node attributes from dictionary of nodes and values
Parameters
----------
G : DyNetx Graph
name : string
Attribute name
values: dict
Dictionary of attribute values keyed by node. If `values` is not a
dictionary, then it is treated as a sing... | [
"Set",
"node",
"attributes",
"from",
"dictionary",
"of",
"nodes",
"and",
"values"
] | train | https://github.com/GiulioRossetti/dynetx/blob/634e2b38f8950885aebfa079dad7d5e8d7563f1d/dynetx/classes/function.py#L503-L535 |
GiulioRossetti/dynetx | dynetx/classes/function.py | get_node_attributes | def get_node_attributes(G, name):
"""Get node attributes from graph
Parameters
----------
G : DyNetx Graph
name : string
Attribute name
Returns
-------
Dictionary of attributes keyed by node.
"""
return {n: d[name] for n, d in G.node.item... | python | def get_node_attributes(G, name):
"""Get node attributes from graph
Parameters
----------
G : DyNetx Graph
name : string
Attribute name
Returns
-------
Dictionary of attributes keyed by node.
"""
return {n: d[name] for n, d in G.node.item... | [
"def",
"get_node_attributes",
"(",
"G",
",",
"name",
")",
":",
"return",
"{",
"n",
":",
"d",
"[",
"name",
"]",
"for",
"n",
",",
"d",
"in",
"G",
".",
"node",
".",
"items",
"(",
")",
"if",
"name",
"in",
"d",
"}"
] | Get node attributes from graph
Parameters
----------
G : DyNetx Graph
name : string
Attribute name
Returns
-------
Dictionary of attributes keyed by node. | [
"Get",
"node",
"attributes",
"from",
"graph"
] | train | https://github.com/GiulioRossetti/dynetx/blob/634e2b38f8950885aebfa079dad7d5e8d7563f1d/dynetx/classes/function.py#L538-L552 |
GiulioRossetti/dynetx | dynetx/classes/function.py | all_neighbors | def all_neighbors(graph, node, t=None):
""" Returns all of the neighbors of a node in the graph at time t.
If the graph is directed returns predecessors as well as successors.
Parameters
----------
graph : DyNetx graph
Graph to find neighbors.
node : node
... | python | def all_neighbors(graph, node, t=None):
""" Returns all of the neighbors of a node in the graph at time t.
If the graph is directed returns predecessors as well as successors.
Parameters
----------
graph : DyNetx graph
Graph to find neighbors.
node : node
... | [
"def",
"all_neighbors",
"(",
"graph",
",",
"node",
",",
"t",
"=",
"None",
")",
":",
"if",
"graph",
".",
"is_directed",
"(",
")",
":",
"values",
"=",
"chain",
"(",
"graph",
".",
"predecessors",
"(",
"node",
",",
"t",
"=",
"t",
")",
",",
"graph",
"... | Returns all of the neighbors of a node in the graph at time t.
If the graph is directed returns predecessors as well as successors.
Parameters
----------
graph : DyNetx graph
Graph to find neighbors.
node : node
The node whose neighbors will be returne... | [
"Returns",
"all",
"of",
"the",
"neighbors",
"of",
"a",
"node",
"in",
"the",
"graph",
"at",
"time",
"t",
"."
] | train | https://github.com/GiulioRossetti/dynetx/blob/634e2b38f8950885aebfa079dad7d5e8d7563f1d/dynetx/classes/function.py#L565-L592 |
GiulioRossetti/dynetx | dynetx/classes/function.py | non_neighbors | def non_neighbors(graph, node, t=None):
"""Returns the non-neighbors of the node in the graph at time t.
Parameters
----------
graph : DyNetx graph
Graph to find neighbors.
node : node
The node whose neighbors will be returned.
t : snapshot id (defa... | python | def non_neighbors(graph, node, t=None):
"""Returns the non-neighbors of the node in the graph at time t.
Parameters
----------
graph : DyNetx graph
Graph to find neighbors.
node : node
The node whose neighbors will be returned.
t : snapshot id (defa... | [
"def",
"non_neighbors",
"(",
"graph",
",",
"node",
",",
"t",
"=",
"None",
")",
":",
"if",
"graph",
".",
"is_directed",
"(",
")",
":",
"values",
"=",
"chain",
"(",
"graph",
".",
"predecessors",
"(",
"node",
",",
"t",
"=",
"t",
")",
",",
"graph",
"... | Returns the non-neighbors of the node in the graph at time t.
Parameters
----------
graph : DyNetx graph
Graph to find neighbors.
node : node
The node whose neighbors will be returned.
t : snapshot id (default=None)
If None the non-neighbors... | [
"Returns",
"the",
"non",
"-",
"neighbors",
"of",
"the",
"node",
"in",
"the",
"graph",
"at",
"time",
"t",
"."
] | train | https://github.com/GiulioRossetti/dynetx/blob/634e2b38f8950885aebfa079dad7d5e8d7563f1d/dynetx/classes/function.py#L595-L621 |
GiulioRossetti/dynetx | dynetx/classes/function.py | non_interactions | def non_interactions(graph, t=None):
"""Returns the non-existent edges in the graph at time t.
Parameters
----------
graph : NetworkX graph.
Graph to find non-existent edges.
t : snapshot id (default=None)
If None the non-existent edges are identified on th... | python | def non_interactions(graph, t=None):
"""Returns the non-existent edges in the graph at time t.
Parameters
----------
graph : NetworkX graph.
Graph to find non-existent edges.
t : snapshot id (default=None)
If None the non-existent edges are identified on th... | [
"def",
"non_interactions",
"(",
"graph",
",",
"t",
"=",
"None",
")",
":",
"# if graph.is_directed():",
"# for u in graph:",
"# for v in non_neighbors(graph, u, t):",
"# yield (u, v)",
"#else:",
"nodes",
"=",
"set",
"(",
"graph",
")",
"while",
"nodes",... | Returns the non-existent edges in the graph at time t.
Parameters
----------
graph : NetworkX graph.
Graph to find non-existent edges.
t : snapshot id (default=None)
If None the non-existent edges are identified on the flattened graph.
Returns
... | [
"Returns",
"the",
"non",
"-",
"existent",
"edges",
"in",
"the",
"graph",
"at",
"time",
"t",
"."
] | train | https://github.com/GiulioRossetti/dynetx/blob/634e2b38f8950885aebfa079dad7d5e8d7563f1d/dynetx/classes/function.py#L624-L651 |
kata198/func_timeout | func_timeout/exceptions.py | FunctionTimedOut.getMsg | def getMsg(self):
'''
getMsg - Generate a default message based on parameters to FunctionTimedOut exception'
@return <str> - Message
'''
return 'Function %s (args=%s) (kwargs=%s) timed out after %f seconds.\n' %(self.timedOutFunction.__name__, repr(self.timedOutArgs), re... | python | def getMsg(self):
'''
getMsg - Generate a default message based on parameters to FunctionTimedOut exception'
@return <str> - Message
'''
return 'Function %s (args=%s) (kwargs=%s) timed out after %f seconds.\n' %(self.timedOutFunction.__name__, repr(self.timedOutArgs), re... | [
"def",
"getMsg",
"(",
"self",
")",
":",
"return",
"'Function %s (args=%s) (kwargs=%s) timed out after %f seconds.\\n'",
"%",
"(",
"self",
".",
"timedOutFunction",
".",
"__name__",
",",
"repr",
"(",
"self",
".",
"timedOutArgs",
")",
",",
"repr",
"(",
"self",
".",
... | getMsg - Generate a default message based on parameters to FunctionTimedOut exception'
@return <str> - Message | [
"getMsg",
"-",
"Generate",
"a",
"default",
"message",
"based",
"on",
"parameters",
"to",
"FunctionTimedOut",
"exception"
] | train | https://github.com/kata198/func_timeout/blob/b427da2517266b31aa0d17c46e9cbeb5add8ef73/func_timeout/exceptions.py#L43-L49 |
kata198/func_timeout | func_timeout/exceptions.py | FunctionTimedOut.retry | def retry(self, timeout=RETRY_SAME_TIMEOUT):
'''
retry - Retry the timed-out function with same arguments.
@param timeout <float/RETRY_SAME_TIMEOUT/None> Default RETRY_SAME_TIMEOUT
If RETRY_SAME_TIMEOUT : Will retry the function same args, same timeout
... | python | def retry(self, timeout=RETRY_SAME_TIMEOUT):
'''
retry - Retry the timed-out function with same arguments.
@param timeout <float/RETRY_SAME_TIMEOUT/None> Default RETRY_SAME_TIMEOUT
If RETRY_SAME_TIMEOUT : Will retry the function same args, same timeout
... | [
"def",
"retry",
"(",
"self",
",",
"timeout",
"=",
"RETRY_SAME_TIMEOUT",
")",
":",
"if",
"timeout",
"is",
"None",
":",
"return",
"self",
".",
"timedOutFunction",
"(",
"*",
"(",
"self",
".",
"timedOutArgs",
")",
",",
"*",
"*",
"self",
".",
"timedOutKwargs"... | retry - Retry the timed-out function with same arguments.
@param timeout <float/RETRY_SAME_TIMEOUT/None> Default RETRY_SAME_TIMEOUT
If RETRY_SAME_TIMEOUT : Will retry the function same args, same timeout
If a float/int : Will retry the function same args wit... | [
"retry",
"-",
"Retry",
"the",
"timed",
"-",
"out",
"function",
"with",
"same",
"arguments",
"."
] | train | https://github.com/kata198/func_timeout/blob/b427da2517266b31aa0d17c46e9cbeb5add8ef73/func_timeout/exceptions.py#L51-L71 |
kata198/func_timeout | func_timeout/dafunc.py | func_timeout | def func_timeout(timeout, func, args=(), kwargs=None):
'''
func_timeout - Runs the given function for up to #timeout# seconds.
Raises any exceptions #func# would raise, returns what #func# would return (unless timeout is exceeded), in which case it raises FunctionTimedOut
@param timeout <f... | python | def func_timeout(timeout, func, args=(), kwargs=None):
'''
func_timeout - Runs the given function for up to #timeout# seconds.
Raises any exceptions #func# would raise, returns what #func# would return (unless timeout is exceeded), in which case it raises FunctionTimedOut
@param timeout <f... | [
"def",
"func_timeout",
"(",
"timeout",
",",
"func",
",",
"args",
"=",
"(",
")",
",",
"kwargs",
"=",
"None",
")",
":",
"if",
"not",
"kwargs",
":",
"kwargs",
"=",
"{",
"}",
"if",
"not",
"args",
":",
"args",
"=",
"(",
")",
"ret",
"=",
"[",
"]",
... | func_timeout - Runs the given function for up to #timeout# seconds.
Raises any exceptions #func# would raise, returns what #func# would return (unless timeout is exceeded), in which case it raises FunctionTimedOut
@param timeout <float> - Maximum number of seconds to run #func# before terminating
... | [
"func_timeout",
"-",
"Runs",
"the",
"given",
"function",
"for",
"up",
"to",
"#timeout#",
"seconds",
"."
] | train | https://github.com/kata198/func_timeout/blob/b427da2517266b31aa0d17c46e9cbeb5add8ef73/func_timeout/dafunc.py#L33-L111 |
kata198/func_timeout | func_timeout/dafunc.py | func_set_timeout | def func_set_timeout(timeout, allowOverride=False):
'''
func_set_timeout - Decorator to run a function with a given/calculated timeout (max execution time).
Optionally (if #allowOverride is True), adds a paramater, "forceTimeout", to the
function which, if provided, will override the... | python | def func_set_timeout(timeout, allowOverride=False):
'''
func_set_timeout - Decorator to run a function with a given/calculated timeout (max execution time).
Optionally (if #allowOverride is True), adds a paramater, "forceTimeout", to the
function which, if provided, will override the... | [
"def",
"func_set_timeout",
"(",
"timeout",
",",
"allowOverride",
"=",
"False",
")",
":",
"# Try to be as efficent as possible... don't compare the args more than once",
"# Helps closure issue on some versions of python",
"defaultTimeout",
"=",
"copy",
".",
"copy",
"(",
"timeout"... | func_set_timeout - Decorator to run a function with a given/calculated timeout (max execution time).
Optionally (if #allowOverride is True), adds a paramater, "forceTimeout", to the
function which, if provided, will override the default timeout for that invocation.
If #timeout is pr... | [
"func_set_timeout",
"-",
"Decorator",
"to",
"run",
"a",
"function",
"with",
"a",
"given",
"/",
"calculated",
"timeout",
"(",
"max",
"execution",
"time",
")",
".",
"Optionally",
"(",
"if",
"#allowOverride",
"is",
"True",
")",
"adds",
"a",
"paramater",
"forceT... | train | https://github.com/kata198/func_timeout/blob/b427da2517266b31aa0d17c46e9cbeb5add8ef73/func_timeout/dafunc.py#L114-L233 |
gplepage/vegas | examples/path-integral.py | analyze_theory | def analyze_theory(V, x0list=[], plot=False):
""" Extract ground-state energy E0 and psi**2 for potential V. """
# initialize path integral
T = 4.
ndT = 8. # use larger ndT to reduce discretization error (goes like 1/ndT**2)
neval = 3e5 # should probably use more evaluations (10x?)
nit... | python | def analyze_theory(V, x0list=[], plot=False):
""" Extract ground-state energy E0 and psi**2 for potential V. """
# initialize path integral
T = 4.
ndT = 8. # use larger ndT to reduce discretization error (goes like 1/ndT**2)
neval = 3e5 # should probably use more evaluations (10x?)
nit... | [
"def",
"analyze_theory",
"(",
"V",
",",
"x0list",
"=",
"[",
"]",
",",
"plot",
"=",
"False",
")",
":",
"# initialize path integral",
"T",
"=",
"4.",
"ndT",
"=",
"8.",
"# use larger ndT to reduce discretization error (goes like 1/ndT**2)",
"neval",
"=",
"3e5",
"# sh... | Extract ground-state energy E0 and psi**2 for potential V. | [
"Extract",
"ground",
"-",
"state",
"energy",
"E0",
"and",
"psi",
"**",
"2",
"for",
"potential",
"V",
"."
] | train | https://github.com/gplepage/vegas/blob/537aaa35938d521bbf7479b2be69170b9282f544/examples/path-integral.py#L82-L116 |
kata198/func_timeout | func_timeout/StoppableThread.py | StoppableThread._stopThread | def _stopThread(self, exception, raiseEvery=2.0):
'''
_stopThread - @see StoppableThread.stop
'''
if self.isAlive() is False:
return True
self._stderr = open(os.devnull, 'w')
# Create "joining" thread which will raise the provided exception
# on... | python | def _stopThread(self, exception, raiseEvery=2.0):
'''
_stopThread - @see StoppableThread.stop
'''
if self.isAlive() is False:
return True
self._stderr = open(os.devnull, 'w')
# Create "joining" thread which will raise the provided exception
# on... | [
"def",
"_stopThread",
"(",
"self",
",",
"exception",
",",
"raiseEvery",
"=",
"2.0",
")",
":",
"if",
"self",
".",
"isAlive",
"(",
")",
"is",
"False",
":",
"return",
"True",
"self",
".",
"_stderr",
"=",
"open",
"(",
"os",
".",
"devnull",
",",
"'w'",
... | _stopThread - @see StoppableThread.stop | [
"_stopThread",
"-"
] | train | https://github.com/kata198/func_timeout/blob/b427da2517266b31aa0d17c46e9cbeb5add8ef73/func_timeout/StoppableThread.py#L37-L53 |
kata198/func_timeout | func_timeout/StoppableThread.py | JoinThread.run | def run(self):
'''
run - The thread main. Will attempt to stop and join the attached thread.
'''
# Try to silence default exception printing.
self.otherThread._Thread__stderr = self._stderr
if hasattr(self.otherThread, '_Thread__stop'):
# If py2, call thi... | python | def run(self):
'''
run - The thread main. Will attempt to stop and join the attached thread.
'''
# Try to silence default exception printing.
self.otherThread._Thread__stderr = self._stderr
if hasattr(self.otherThread, '_Thread__stop'):
# If py2, call thi... | [
"def",
"run",
"(",
"self",
")",
":",
"# Try to silence default exception printing.",
"self",
".",
"otherThread",
".",
"_Thread__stderr",
"=",
"self",
".",
"_stderr",
"if",
"hasattr",
"(",
"self",
".",
"otherThread",
",",
"'_Thread__stop'",
")",
":",
"# If py2, cal... | run - The thread main. Will attempt to stop and join the attached thread. | [
"run",
"-",
"The",
"thread",
"main",
".",
"Will",
"attempt",
"to",
"stop",
"and",
"join",
"the",
"attached",
"thread",
"."
] | train | https://github.com/kata198/func_timeout/blob/b427da2517266b31aa0d17c46e9cbeb5add8ef73/func_timeout/StoppableThread.py#L94-L113 |
gplepage/vegas | setup.py | build_py.run | def run(self):
""" Append version number to vegas/__init__.py """
with open('src/vegas/__init__.py', 'a') as vfile:
vfile.write("\n__version__ = '%s'\n" % VEGAS_VERSION)
_build_py.run(self) | python | def run(self):
""" Append version number to vegas/__init__.py """
with open('src/vegas/__init__.py', 'a') as vfile:
vfile.write("\n__version__ = '%s'\n" % VEGAS_VERSION)
_build_py.run(self) | [
"def",
"run",
"(",
"self",
")",
":",
"with",
"open",
"(",
"'src/vegas/__init__.py'",
",",
"'a'",
")",
"as",
"vfile",
":",
"vfile",
".",
"write",
"(",
"\"\\n__version__ = '%s'\\n\"",
"%",
"VEGAS_VERSION",
")",
"_build_py",
".",
"run",
"(",
"self",
")"
] | Append version number to vegas/__init__.py | [
"Append",
"version",
"number",
"to",
"vegas",
"/",
"__init__",
".",
"py"
] | train | https://github.com/gplepage/vegas/blob/537aaa35938d521bbf7479b2be69170b9282f544/setup.py#L43-L47 |
gplepage/vegas | src/vegas/__init__.py | PDFIntegrator._make_map | def _make_map(self, limit):
""" Make vegas grid that is adapted to the pdf. """
ny = 2000
y = numpy.random.uniform(0., 1., (ny,1))
limit = numpy.arctan(limit)
m = AdaptiveMap([[-limit, limit]], ninc=100)
theta = numpy.empty(y.shape, float)
jac = numpy.empty(y.shap... | python | def _make_map(self, limit):
""" Make vegas grid that is adapted to the pdf. """
ny = 2000
y = numpy.random.uniform(0., 1., (ny,1))
limit = numpy.arctan(limit)
m = AdaptiveMap([[-limit, limit]], ninc=100)
theta = numpy.empty(y.shape, float)
jac = numpy.empty(y.shap... | [
"def",
"_make_map",
"(",
"self",
",",
"limit",
")",
":",
"ny",
"=",
"2000",
"y",
"=",
"numpy",
".",
"random",
".",
"uniform",
"(",
"0.",
",",
"1.",
",",
"(",
"ny",
",",
"1",
")",
")",
"limit",
"=",
"numpy",
".",
"arctan",
"(",
"limit",
")",
"... | Make vegas grid that is adapted to the pdf. | [
"Make",
"vegas",
"grid",
"that",
"is",
"adapted",
"to",
"the",
"pdf",
"."
] | train | https://github.com/gplepage/vegas/blob/537aaa35938d521bbf7479b2be69170b9282f544/src/vegas/__init__.py#L200-L215 |
gplepage/vegas | src/vegas/__init__.py | PDFIntegrator._expval | def _expval(self, f, nopdf):
""" Return integrand using the tan mapping. """
def ff(theta, nopdf=nopdf):
tan_theta = numpy.tan(theta)
x = self.scale * tan_theta
jac = self.scale * (tan_theta ** 2 + 1.)
if nopdf:
pdf = jac * self.pdf.pjac[No... | python | def _expval(self, f, nopdf):
""" Return integrand using the tan mapping. """
def ff(theta, nopdf=nopdf):
tan_theta = numpy.tan(theta)
x = self.scale * tan_theta
jac = self.scale * (tan_theta ** 2 + 1.)
if nopdf:
pdf = jac * self.pdf.pjac[No... | [
"def",
"_expval",
"(",
"self",
",",
"f",
",",
"nopdf",
")",
":",
"def",
"ff",
"(",
"theta",
",",
"nopdf",
"=",
"nopdf",
")",
":",
"tan_theta",
"=",
"numpy",
".",
"tan",
"(",
"theta",
")",
"x",
"=",
"self",
".",
"scale",
"*",
"tan_theta",
"jac",
... | Return integrand using the tan mapping. | [
"Return",
"integrand",
"using",
"the",
"tan",
"mapping",
"."
] | train | https://github.com/gplepage/vegas/blob/537aaa35938d521bbf7479b2be69170b9282f544/src/vegas/__init__.py#L249-L306 |
audreyr/binaryornot | binaryornot/helpers.py | get_starting_chunk | def get_starting_chunk(filename, length=1024):
"""
:param filename: File to open and get the first little chunk of.
:param length: Number of bytes to read, default 1024.
:returns: Starting chunk of bytes.
"""
# Ensure we open the file in binary mode
try:
with open(filename, 'rb') as ... | python | def get_starting_chunk(filename, length=1024):
"""
:param filename: File to open and get the first little chunk of.
:param length: Number of bytes to read, default 1024.
:returns: Starting chunk of bytes.
"""
# Ensure we open the file in binary mode
try:
with open(filename, 'rb') as ... | [
"def",
"get_starting_chunk",
"(",
"filename",
",",
"length",
"=",
"1024",
")",
":",
"# Ensure we open the file in binary mode",
"try",
":",
"with",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"f",
":",
"chunk",
"=",
"f",
".",
"read",
"(",
"length",
")... | :param filename: File to open and get the first little chunk of.
:param length: Number of bytes to read, default 1024.
:returns: Starting chunk of bytes. | [
":",
"param",
"filename",
":",
"File",
"to",
"open",
"and",
"get",
"the",
"first",
"little",
"chunk",
"of",
".",
":",
"param",
"length",
":",
"Number",
"of",
"bytes",
"to",
"read",
"default",
"1024",
".",
":",
"returns",
":",
"Starting",
"chunk",
"of",... | train | https://github.com/audreyr/binaryornot/blob/16d9702d49e45daa27f10a681129e42211ed0d92/binaryornot/helpers.py#L25-L37 |
Magnetic/cycy | cycy/repl.py | REPL.dump | def dump(self, function_name):
"""
Pretty-dump the bytecode for the function with the given name.
"""
assert isinstance(function_name, str)
self.stdout.write(function_name)
self.stdout.write("\n")
self.stdout.write("-" * len(function_name))
self.stdout.w... | python | def dump(self, function_name):
"""
Pretty-dump the bytecode for the function with the given name.
"""
assert isinstance(function_name, str)
self.stdout.write(function_name)
self.stdout.write("\n")
self.stdout.write("-" * len(function_name))
self.stdout.w... | [
"def",
"dump",
"(",
"self",
",",
"function_name",
")",
":",
"assert",
"isinstance",
"(",
"function_name",
",",
"str",
")",
"self",
".",
"stdout",
".",
"write",
"(",
"function_name",
")",
"self",
".",
"stdout",
".",
"write",
"(",
"\"\\n\"",
")",
"self",
... | Pretty-dump the bytecode for the function with the given name. | [
"Pretty",
"-",
"dump",
"the",
"bytecode",
"for",
"the",
"function",
"with",
"the",
"given",
"name",
"."
] | train | https://github.com/Magnetic/cycy/blob/494282a37b5f7d1eaa17b8d01796df8302da2a81/cycy/repl.py#L76-L90 |
jmfederico/django-use-email-as-username | django_use_email_as_username/management/commands/create_custom_user_app.py | Command.handle | def handle(self, **options):
"""Call "startapp" to generate app with custom user model."""
template = os.path.dirname(os.path.abspath(__file__)) + "/app_template"
name = options.pop("name")
call_command("startapp", name, template=template, **options) | python | def handle(self, **options):
"""Call "startapp" to generate app with custom user model."""
template = os.path.dirname(os.path.abspath(__file__)) + "/app_template"
name = options.pop("name")
call_command("startapp", name, template=template, **options) | [
"def",
"handle",
"(",
"self",
",",
"*",
"*",
"options",
")",
":",
"template",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"__file__",
")",
")",
"+",
"\"/app_template\"",
"name",
"=",
"options",
".",
"pop",
"... | Call "startapp" to generate app with custom user model. | [
"Call",
"startapp",
"to",
"generate",
"app",
"with",
"custom",
"user",
"model",
"."
] | train | https://github.com/jmfederico/django-use-email-as-username/blob/401e404b822f7ba5b3ef34b06ce095e564f32912/django_use_email_as_username/management/commands/create_custom_user_app.py#L26-L30 |
jmfederico/django-use-email-as-username | django_use_email_as_username/models.py | BaseUserManager._create_user | def _create_user(self, email, password, **extra_fields):
"""Create and save a User with the given email and password."""
if not email:
raise ValueError("The given email must be set")
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
us... | python | def _create_user(self, email, password, **extra_fields):
"""Create and save a User with the given email and password."""
if not email:
raise ValueError("The given email must be set")
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
us... | [
"def",
"_create_user",
"(",
"self",
",",
"email",
",",
"password",
",",
"*",
"*",
"extra_fields",
")",
":",
"if",
"not",
"email",
":",
"raise",
"ValueError",
"(",
"\"The given email must be set\"",
")",
"email",
"=",
"self",
".",
"normalize_email",
"(",
"ema... | Create and save a User with the given email and password. | [
"Create",
"and",
"save",
"a",
"User",
"with",
"the",
"given",
"email",
"and",
"password",
"."
] | train | https://github.com/jmfederico/django-use-email-as-username/blob/401e404b822f7ba5b3ef34b06ce095e564f32912/django_use_email_as_username/models.py#L14-L22 |
Mapkin/osmgraph | osmgraph/tools.py | nwise | def nwise(iterable, n):
"""
Iterate through a sequence with a defined length window
>>> list(nwise(range(8), 3))
[(0, 1, 2), (1, 2, 3), (2, 3, 4), (3, 4, 5), (5, 6, 7)]
>>> list(nwise(range(3), 5))
[]
Parameters
----------
iterable
n : length of each sequence
Yields
... | python | def nwise(iterable, n):
"""
Iterate through a sequence with a defined length window
>>> list(nwise(range(8), 3))
[(0, 1, 2), (1, 2, 3), (2, 3, 4), (3, 4, 5), (5, 6, 7)]
>>> list(nwise(range(3), 5))
[]
Parameters
----------
iterable
n : length of each sequence
Yields
... | [
"def",
"nwise",
"(",
"iterable",
",",
"n",
")",
":",
"iters",
"=",
"itertools",
".",
"tee",
"(",
"iterable",
",",
"n",
")",
"iters",
"=",
"(",
"itertools",
".",
"islice",
"(",
"it",
",",
"i",
",",
"None",
")",
"for",
"i",
",",
"it",
"in",
"enum... | Iterate through a sequence with a defined length window
>>> list(nwise(range(8), 3))
[(0, 1, 2), (1, 2, 3), (2, 3, 4), (3, 4, 5), (5, 6, 7)]
>>> list(nwise(range(3), 5))
[]
Parameters
----------
iterable
n : length of each sequence
Yields
------
Tuples of length n | [
"Iterate",
"through",
"a",
"sequence",
"with",
"a",
"defined",
"length",
"window"
] | train | https://github.com/Mapkin/osmgraph/blob/4f8e6466c11edbe30f1bbefc939e5613860a43b4/osmgraph/tools.py#L6-L29 |
Mapkin/osmgraph | osmgraph/tools.py | coordinates | def coordinates(g, nodes):
"""
Extract (lon, lat) coordinate pairs from nodes in an osmgraph
osmgraph nodes have a 'coordinate' property on each node. This is
a shortcut for extracting a coordinate list from an iterable of nodes
>>> g = osmgraph.parse_file(filename)
>>> node_ids = g.nodes()[:3... | python | def coordinates(g, nodes):
"""
Extract (lon, lat) coordinate pairs from nodes in an osmgraph
osmgraph nodes have a 'coordinate' property on each node. This is
a shortcut for extracting a coordinate list from an iterable of nodes
>>> g = osmgraph.parse_file(filename)
>>> node_ids = g.nodes()[:3... | [
"def",
"coordinates",
"(",
"g",
",",
"nodes",
")",
":",
"c",
"=",
"[",
"g",
".",
"node",
"[",
"n",
"]",
"[",
"'coordinate'",
"]",
"for",
"n",
"in",
"nodes",
"]",
"return",
"c"
] | Extract (lon, lat) coordinate pairs from nodes in an osmgraph
osmgraph nodes have a 'coordinate' property on each node. This is
a shortcut for extracting a coordinate list from an iterable of nodes
>>> g = osmgraph.parse_file(filename)
>>> node_ids = g.nodes()[:3] # Grab 3 nodes
[61341696, 613416... | [
"Extract",
"(",
"lon",
"lat",
")",
"coordinate",
"pairs",
"from",
"nodes",
"in",
"an",
"osmgraph"
] | train | https://github.com/Mapkin/osmgraph/blob/4f8e6466c11edbe30f1bbefc939e5613860a43b4/osmgraph/tools.py#L45-L72 |
Mapkin/osmgraph | osmgraph/tools.py | step | def step(g, n1, n2, inbound=False, backward=False, continue_fn=None):
"""
Step along a path through a directed graph unless there is an intersection
Example graph:
Note that edge (1, 2) and (2, 3) are bidirectional, i.e., (2, 1) and
(3, 2) are also edges
1 -- 2 -- 3 -->-- 5 -->-- 7
... | python | def step(g, n1, n2, inbound=False, backward=False, continue_fn=None):
"""
Step along a path through a directed graph unless there is an intersection
Example graph:
Note that edge (1, 2) and (2, 3) are bidirectional, i.e., (2, 1) and
(3, 2) are also edges
1 -- 2 -- 3 -->-- 5 -->-- 7
... | [
"def",
"step",
"(",
"g",
",",
"n1",
",",
"n2",
",",
"inbound",
"=",
"False",
",",
"backward",
"=",
"False",
",",
"continue_fn",
"=",
"None",
")",
":",
"forw",
"=",
"g",
".",
"successors",
"back",
"=",
"g",
".",
"predecessors",
"if",
"backward",
":"... | Step along a path through a directed graph unless there is an intersection
Example graph:
Note that edge (1, 2) and (2, 3) are bidirectional, i.e., (2, 1) and
(3, 2) are also edges
1 -- 2 -- 3 -->-- 5 -->-- 7
| |
^ v
| |
4 ... | [
"Step",
"along",
"a",
"path",
"through",
"a",
"directed",
"graph",
"unless",
"there",
"is",
"an",
"intersection"
] | train | https://github.com/Mapkin/osmgraph/blob/4f8e6466c11edbe30f1bbefc939e5613860a43b4/osmgraph/tools.py#L75-L151 |
Mapkin/osmgraph | osmgraph/tools.py | move | def move(g, n1, n2, **kwargs):
"""
Step along a graph until it ends or reach an intersection
Example graph:
Note that edge (1, 2) and (2, 3) are bidirectional, i.e., (2, 1) and
(3, 2) are also edges
1 -- 2 -- 3 -->-- 5 -->-- 7
| |
^ v
| ... | python | def move(g, n1, n2, **kwargs):
"""
Step along a graph until it ends or reach an intersection
Example graph:
Note that edge (1, 2) and (2, 3) are bidirectional, i.e., (2, 1) and
(3, 2) are also edges
1 -- 2 -- 3 -->-- 5 -->-- 7
| |
^ v
| ... | [
"def",
"move",
"(",
"g",
",",
"n1",
",",
"n2",
",",
"*",
"*",
"kwargs",
")",
":",
"prev",
"=",
"n1",
"curr",
"=",
"n2",
"_next",
"=",
"step",
"(",
"g",
",",
"prev",
",",
"curr",
",",
"*",
"*",
"kwargs",
")",
"yield",
"prev",
"yield",
"curr",
... | Step along a graph until it ends or reach an intersection
Example graph:
Note that edge (1, 2) and (2, 3) are bidirectional, i.e., (2, 1) and
(3, 2) are also edges
1 -- 2 -- 3 -->-- 5 -->-- 7
| |
^ v
| |
4 6
>>> list(... | [
"Step",
"along",
"a",
"graph",
"until",
"it",
"ends",
"or",
"reach",
"an",
"intersection"
] | train | https://github.com/Mapkin/osmgraph/blob/4f8e6466c11edbe30f1bbefc939e5613860a43b4/osmgraph/tools.py#L154-L200 |
Mapkin/osmgraph | osmgraph/tools.py | is_intersection | def is_intersection(g, n):
"""
Determine if a node is an intersection
graph: 1 -->-- 2 -->-- 3
>>> is_intersection(g, 2)
False
graph:
1 -- 2 -- 3
|
4
>>> is_intersection(g, 2)
True
Parameters
----------
g : networkx DiGraph
n : node id
R... | python | def is_intersection(g, n):
"""
Determine if a node is an intersection
graph: 1 -->-- 2 -->-- 3
>>> is_intersection(g, 2)
False
graph:
1 -- 2 -- 3
|
4
>>> is_intersection(g, 2)
True
Parameters
----------
g : networkx DiGraph
n : node id
R... | [
"def",
"is_intersection",
"(",
"g",
",",
"n",
")",
":",
"return",
"len",
"(",
"set",
"(",
"g",
".",
"predecessors",
"(",
"n",
")",
"+",
"g",
".",
"successors",
"(",
"n",
")",
")",
")",
">",
"2"
] | Determine if a node is an intersection
graph: 1 -->-- 2 -->-- 3
>>> is_intersection(g, 2)
False
graph:
1 -- 2 -- 3
|
4
>>> is_intersection(g, 2)
True
Parameters
----------
g : networkx DiGraph
n : node id
Returns
-------
bool | [
"Determine",
"if",
"a",
"node",
"is",
"an",
"intersection"
] | train | https://github.com/Mapkin/osmgraph/blob/4f8e6466c11edbe30f1bbefc939e5613860a43b4/osmgraph/tools.py#L203-L230 |
lamenezes/simple-model | simple_model/models.py | LazyModel.as_dict | def as_dict(self):
"""
Returns the model as a dict
"""
if not self._is_valid:
self.validate()
from .converters import to_dict
return to_dict(self) | python | def as_dict(self):
"""
Returns the model as a dict
"""
if not self._is_valid:
self.validate()
from .converters import to_dict
return to_dict(self) | [
"def",
"as_dict",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_is_valid",
":",
"self",
".",
"validate",
"(",
")",
"from",
".",
"converters",
"import",
"to_dict",
"return",
"to_dict",
"(",
"self",
")"
] | Returns the model as a dict | [
"Returns",
"the",
"model",
"as",
"a",
"dict"
] | train | https://github.com/lamenezes/simple-model/blob/05138edd022db642ef5611ac660832993e2af0d4/simple_model/models.py#L172-L180 |
Mapkin/osmgraph | osmgraph/importer.py | GraphImporter.coords_callback | def coords_callback(self, data):
""" Callback for nodes that have no tags """
for node_id, lon, lat in data:
self.coords[node_id] = (lon, lat) | python | def coords_callback(self, data):
""" Callback for nodes that have no tags """
for node_id, lon, lat in data:
self.coords[node_id] = (lon, lat) | [
"def",
"coords_callback",
"(",
"self",
",",
"data",
")",
":",
"for",
"node_id",
",",
"lon",
",",
"lat",
"in",
"data",
":",
"self",
".",
"coords",
"[",
"node_id",
"]",
"=",
"(",
"lon",
",",
"lat",
")"
] | Callback for nodes that have no tags | [
"Callback",
"for",
"nodes",
"that",
"have",
"no",
"tags"
] | train | https://github.com/Mapkin/osmgraph/blob/4f8e6466c11edbe30f1bbefc939e5613860a43b4/osmgraph/importer.py#L14-L17 |
Mapkin/osmgraph | osmgraph/importer.py | GraphImporter.nodes_callback | def nodes_callback(self, data):
""" Callback for nodes with tags """
for node_id, tags, coords in data:
# Discard the coords because they go into add_coords
self.nodes[node_id] = tags | python | def nodes_callback(self, data):
""" Callback for nodes with tags """
for node_id, tags, coords in data:
# Discard the coords because they go into add_coords
self.nodes[node_id] = tags | [
"def",
"nodes_callback",
"(",
"self",
",",
"data",
")",
":",
"for",
"node_id",
",",
"tags",
",",
"coords",
"in",
"data",
":",
"# Discard the coords because they go into add_coords",
"self",
".",
"nodes",
"[",
"node_id",
"]",
"=",
"tags"
] | Callback for nodes with tags | [
"Callback",
"for",
"nodes",
"with",
"tags"
] | train | https://github.com/Mapkin/osmgraph/blob/4f8e6466c11edbe30f1bbefc939e5613860a43b4/osmgraph/importer.py#L19-L23 |
Mapkin/osmgraph | osmgraph/importer.py | GraphImporter.ways_callback | def ways_callback(self, data):
""" Callback for all ways """
for way_id, tags, nodes in data:
# Imposm passes all ways through regardless of whether the tags
# have been filtered or not. It needs to do this in order to
# handle relations, but we don't care about relat... | python | def ways_callback(self, data):
""" Callback for all ways """
for way_id, tags, nodes in data:
# Imposm passes all ways through regardless of whether the tags
# have been filtered or not. It needs to do this in order to
# handle relations, but we don't care about relat... | [
"def",
"ways_callback",
"(",
"self",
",",
"data",
")",
":",
"for",
"way_id",
",",
"tags",
",",
"nodes",
"in",
"data",
":",
"# Imposm passes all ways through regardless of whether the tags",
"# have been filtered or not. It needs to do this in order to",
"# handle relations, but... | Callback for all ways | [
"Callback",
"for",
"all",
"ways"
] | train | https://github.com/Mapkin/osmgraph/blob/4f8e6466c11edbe30f1bbefc939e5613860a43b4/osmgraph/importer.py#L25-L33 |
Mapkin/osmgraph | osmgraph/importer.py | GraphImporter.get_graph | def get_graph(self, parse_direction=False):
""" Return the networkx directed graph of received data """
g = nx.DiGraph()
for way_id, (tags, nodes) in self.ways.items():
# If oneway is '-1', reverse the way and treat as a normal oneway
if tags.get('oneway') == '-1':
... | python | def get_graph(self, parse_direction=False):
""" Return the networkx directed graph of received data """
g = nx.DiGraph()
for way_id, (tags, nodes) in self.ways.items():
# If oneway is '-1', reverse the way and treat as a normal oneway
if tags.get('oneway') == '-1':
... | [
"def",
"get_graph",
"(",
"self",
",",
"parse_direction",
"=",
"False",
")",
":",
"g",
"=",
"nx",
".",
"DiGraph",
"(",
")",
"for",
"way_id",
",",
"(",
"tags",
",",
"nodes",
")",
"in",
"self",
".",
"ways",
".",
"items",
"(",
")",
":",
"# If oneway is... | Return the networkx directed graph of received data | [
"Return",
"the",
"networkx",
"directed",
"graph",
"of",
"received",
"data"
] | train | https://github.com/Mapkin/osmgraph/blob/4f8e6466c11edbe30f1bbefc939e5613860a43b4/osmgraph/importer.py#L35-L58 |
Mapkin/osmgraph | osmgraph/main.py | parse_file | def parse_file(filename, parse_direction=False, **kwargs):
"""
Return an OSM networkx graph from the input OSM file
Only works with OSM xml, xml.bz2 and pbf files. This function cannot take
OSM QA tile files. Use parse_qa_tile() for QA tiles.
>>> graph = parse_file(filename)
"""
importer,... | python | def parse_file(filename, parse_direction=False, **kwargs):
"""
Return an OSM networkx graph from the input OSM file
Only works with OSM xml, xml.bz2 and pbf files. This function cannot take
OSM QA tile files. Use parse_qa_tile() for QA tiles.
>>> graph = parse_file(filename)
"""
importer,... | [
"def",
"parse_file",
"(",
"filename",
",",
"parse_direction",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"importer",
",",
"parser",
"=",
"make_importer_parser",
"(",
"OSMParser",
",",
"*",
"*",
"kwargs",
")",
"parser",
".",
"parse",
"(",
"filename",
... | Return an OSM networkx graph from the input OSM file
Only works with OSM xml, xml.bz2 and pbf files. This function cannot take
OSM QA tile files. Use parse_qa_tile() for QA tiles.
>>> graph = parse_file(filename) | [
"Return",
"an",
"OSM",
"networkx",
"graph",
"from",
"the",
"input",
"OSM",
"file"
] | train | https://github.com/Mapkin/osmgraph/blob/4f8e6466c11edbe30f1bbefc939e5613860a43b4/osmgraph/main.py#L10-L23 |
Mapkin/osmgraph | osmgraph/main.py | parse_data | def parse_data(data, type, **kwargs):
"""
Return an OSM networkx graph from the input OSM data
Parameters
----------
data : string
type : string ('xml' or 'pbf')
>>> graph = parse_data(data, 'xml')
"""
suffixes = {
'xml': '.osm',
'pbf': '.pbf',
}
try:
... | python | def parse_data(data, type, **kwargs):
"""
Return an OSM networkx graph from the input OSM data
Parameters
----------
data : string
type : string ('xml' or 'pbf')
>>> graph = parse_data(data, 'xml')
"""
suffixes = {
'xml': '.osm',
'pbf': '.pbf',
}
try:
... | [
"def",
"parse_data",
"(",
"data",
",",
"type",
",",
"*",
"*",
"kwargs",
")",
":",
"suffixes",
"=",
"{",
"'xml'",
":",
"'.osm'",
",",
"'pbf'",
":",
"'.pbf'",
",",
"}",
"try",
":",
"suffix",
"=",
"suffixes",
"[",
"type",
"]",
"except",
"KeyError",
":... | Return an OSM networkx graph from the input OSM data
Parameters
----------
data : string
type : string ('xml' or 'pbf')
>>> graph = parse_data(data, 'xml') | [
"Return",
"an",
"OSM",
"networkx",
"graph",
"from",
"the",
"input",
"OSM",
"data"
] | train | https://github.com/Mapkin/osmgraph/blob/4f8e6466c11edbe30f1bbefc939e5613860a43b4/osmgraph/main.py#L26-L53 |
Mapkin/osmgraph | osmgraph/main.py | parse_qa_tile | def parse_qa_tile(x, y, zoom, data, parse_direction=False, **kwargs):
"""
Return an OSM networkx graph from the input OSM QA tile data
Parameters
----------
data : string
x : int
tile's x coordinate
y : int
tile's y coordinate
zoom : int
tile's zoom level
>>... | python | def parse_qa_tile(x, y, zoom, data, parse_direction=False, **kwargs):
"""
Return an OSM networkx graph from the input OSM QA tile data
Parameters
----------
data : string
x : int
tile's x coordinate
y : int
tile's y coordinate
zoom : int
tile's zoom level
>>... | [
"def",
"parse_qa_tile",
"(",
"x",
",",
"y",
",",
"zoom",
",",
"data",
",",
"parse_direction",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"osmqa",
"importer",
",",
"parser",
"=",
"make_importer_parser",
"(",
"osmqa",
".",
"QATileParser",
"... | Return an OSM networkx graph from the input OSM QA tile data
Parameters
----------
data : string
x : int
tile's x coordinate
y : int
tile's y coordinate
zoom : int
tile's zoom level
>>> graph = parse_qa_tile(data, 1239, 1514, 12) | [
"Return",
"an",
"OSM",
"networkx",
"graph",
"from",
"the",
"input",
"OSM",
"QA",
"tile",
"data"
] | train | https://github.com/Mapkin/osmgraph/blob/4f8e6466c11edbe30f1bbefc939e5613860a43b4/osmgraph/main.py#L56-L76 |
pyoceans/python-ctd | ctd/read.py | _basename | def _basename(fname):
"""Return file name without path."""
if not isinstance(fname, Path):
fname = Path(fname)
path, name, ext = fname.parent, fname.stem, fname.suffix
return path, name, ext | python | def _basename(fname):
"""Return file name without path."""
if not isinstance(fname, Path):
fname = Path(fname)
path, name, ext = fname.parent, fname.stem, fname.suffix
return path, name, ext | [
"def",
"_basename",
"(",
"fname",
")",
":",
"if",
"not",
"isinstance",
"(",
"fname",
",",
"Path",
")",
":",
"fname",
"=",
"Path",
"(",
"fname",
")",
"path",
",",
"name",
",",
"ext",
"=",
"fname",
".",
"parent",
",",
"fname",
".",
"stem",
",",
"fn... | Return file name without path. | [
"Return",
"file",
"name",
"without",
"path",
"."
] | train | https://github.com/pyoceans/python-ctd/blob/fa9a9d02da3dfed6d1d60db0e52bbab52adfe666/ctd/read.py#L15-L20 |
pyoceans/python-ctd | ctd/read.py | from_bl | def from_bl(fname):
"""Read Seabird bottle-trip (bl) file
Example
-------
>>> from pathlib import Path
>>> import ctd
>>> data_path = Path(__file__).parents[1].joinpath("tests", "data")
>>> df = ctd.from_bl(str(data_path.joinpath('bl', 'bottletest.bl')))
>>> df._metadata["time_of_reset"... | python | def from_bl(fname):
"""Read Seabird bottle-trip (bl) file
Example
-------
>>> from pathlib import Path
>>> import ctd
>>> data_path = Path(__file__).parents[1].joinpath("tests", "data")
>>> df = ctd.from_bl(str(data_path.joinpath('bl', 'bottletest.bl')))
>>> df._metadata["time_of_reset"... | [
"def",
"from_bl",
"(",
"fname",
")",
":",
"df",
"=",
"pd",
".",
"read_csv",
"(",
"fname",
",",
"skiprows",
"=",
"2",
",",
"parse_dates",
"=",
"[",
"1",
"]",
",",
"index_col",
"=",
"0",
",",
"names",
"=",
"[",
"\"bottle_number\"",
",",
"\"time\"",
"... | Read Seabird bottle-trip (bl) file
Example
-------
>>> from pathlib import Path
>>> import ctd
>>> data_path = Path(__file__).parents[1].joinpath("tests", "data")
>>> df = ctd.from_bl(str(data_path.joinpath('bl', 'bottletest.bl')))
>>> df._metadata["time_of_reset"]
datetime.datetime(201... | [
"Read",
"Seabird",
"bottle",
"-",
"trip",
"(",
"bl",
")",
"file"
] | train | https://github.com/pyoceans/python-ctd/blob/fa9a9d02da3dfed6d1d60db0e52bbab52adfe666/ctd/read.py#L157-L182 |
pyoceans/python-ctd | ctd/read.py | from_btl | def from_btl(fname):
"""
DataFrame constructor to open Seabird CTD BTL-ASCII format.
Examples
--------
>>> from pathlib import Path
>>> import ctd
>>> data_path = Path(__file__).parents[1].joinpath("tests", "data")
>>> bottles = ctd.from_btl(data_path.joinpath('btl', 'bottletest.btl'))
... | python | def from_btl(fname):
"""
DataFrame constructor to open Seabird CTD BTL-ASCII format.
Examples
--------
>>> from pathlib import Path
>>> import ctd
>>> data_path = Path(__file__).parents[1].joinpath("tests", "data")
>>> bottles = ctd.from_btl(data_path.joinpath('btl', 'bottletest.btl'))
... | [
"def",
"from_btl",
"(",
"fname",
")",
":",
"f",
"=",
"_read_file",
"(",
"fname",
")",
"metadata",
"=",
"_parse_seabird",
"(",
"f",
".",
"readlines",
"(",
")",
",",
"ftype",
"=",
"\"btl\"",
")",
"f",
".",
"seek",
"(",
"0",
")",
"df",
"=",
"pd",
".... | DataFrame constructor to open Seabird CTD BTL-ASCII format.
Examples
--------
>>> from pathlib import Path
>>> import ctd
>>> data_path = Path(__file__).parents[1].joinpath("tests", "data")
>>> bottles = ctd.from_btl(data_path.joinpath('btl', 'bottletest.btl')) | [
"DataFrame",
"constructor",
"to",
"open",
"Seabird",
"CTD",
"BTL",
"-",
"ASCII",
"format",
"."
] | train | https://github.com/pyoceans/python-ctd/blob/fa9a9d02da3dfed6d1d60db0e52bbab52adfe666/ctd/read.py#L185-L256 |
pyoceans/python-ctd | ctd/read.py | from_edf | def from_edf(fname):
"""
DataFrame constructor to open XBT EDF ASCII format.
Examples
--------
>>> from pathlib import Path
>>> import ctd
>>> data_path = Path(__file__).parents[1].joinpath("tests", "data")
>>> cast = ctd.from_edf(data_path.joinpath('XBT.EDF.gz'))
>>> ax = cast['tem... | python | def from_edf(fname):
"""
DataFrame constructor to open XBT EDF ASCII format.
Examples
--------
>>> from pathlib import Path
>>> import ctd
>>> data_path = Path(__file__).parents[1].joinpath("tests", "data")
>>> cast = ctd.from_edf(data_path.joinpath('XBT.EDF.gz'))
>>> ax = cast['tem... | [
"def",
"from_edf",
"(",
"fname",
")",
":",
"f",
"=",
"_read_file",
"(",
"fname",
")",
"header",
",",
"names",
"=",
"[",
"]",
",",
"[",
"]",
"for",
"k",
",",
"line",
"in",
"enumerate",
"(",
"f",
".",
"readlines",
"(",
")",
")",
":",
"line",
"=",... | DataFrame constructor to open XBT EDF ASCII format.
Examples
--------
>>> from pathlib import Path
>>> import ctd
>>> data_path = Path(__file__).parents[1].joinpath("tests", "data")
>>> cast = ctd.from_edf(data_path.joinpath('XBT.EDF.gz'))
>>> ax = cast['temperature'].plot_cast() | [
"DataFrame",
"constructor",
"to",
"open",
"XBT",
"EDF",
"ASCII",
"format",
"."
] | train | https://github.com/pyoceans/python-ctd/blob/fa9a9d02da3dfed6d1d60db0e52bbab52adfe666/ctd/read.py#L259-L332 |
pyoceans/python-ctd | ctd/read.py | from_cnv | def from_cnv(fname):
"""
DataFrame constructor to open Seabird CTD CNV-ASCII format.
Examples
--------
>>> from pathlib import Path
>>> import ctd
>>> data_path = Path(__file__).parents[1].joinpath("tests", "data")
>>> cast = ctd.from_cnv(data_path.joinpath('CTD_big.cnv.bz2'))
>>> d... | python | def from_cnv(fname):
"""
DataFrame constructor to open Seabird CTD CNV-ASCII format.
Examples
--------
>>> from pathlib import Path
>>> import ctd
>>> data_path = Path(__file__).parents[1].joinpath("tests", "data")
>>> cast = ctd.from_cnv(data_path.joinpath('CTD_big.cnv.bz2'))
>>> d... | [
"def",
"from_cnv",
"(",
"fname",
")",
":",
"f",
"=",
"_read_file",
"(",
"fname",
")",
"metadata",
"=",
"_parse_seabird",
"(",
"f",
".",
"readlines",
"(",
")",
",",
"ftype",
"=",
"\"cnv\"",
")",
"f",
".",
"seek",
"(",
"0",
")",
"df",
"=",
"pd",
".... | DataFrame constructor to open Seabird CTD CNV-ASCII format.
Examples
--------
>>> from pathlib import Path
>>> import ctd
>>> data_path = Path(__file__).parents[1].joinpath("tests", "data")
>>> cast = ctd.from_cnv(data_path.joinpath('CTD_big.cnv.bz2'))
>>> downcast, upcast = cast.split()
... | [
"DataFrame",
"constructor",
"to",
"open",
"Seabird",
"CTD",
"CNV",
"-",
"ASCII",
"format",
"."
] | train | https://github.com/pyoceans/python-ctd/blob/fa9a9d02da3dfed6d1d60db0e52bbab52adfe666/ctd/read.py#L335-L392 |
pyoceans/python-ctd | ctd/read.py | from_fsi | def from_fsi(fname, skiprows=9):
"""
DataFrame constructor to open Falmouth Scientific, Inc. (FSI) CTD
ASCII format.
Examples
--------
>>> from pathlib import Path
>>> import ctd
>>> data_path = Path(__file__).parents[1].joinpath("tests", "data")
>>> cast = ctd.from_fsi(data_path.jo... | python | def from_fsi(fname, skiprows=9):
"""
DataFrame constructor to open Falmouth Scientific, Inc. (FSI) CTD
ASCII format.
Examples
--------
>>> from pathlib import Path
>>> import ctd
>>> data_path = Path(__file__).parents[1].joinpath("tests", "data")
>>> cast = ctd.from_fsi(data_path.jo... | [
"def",
"from_fsi",
"(",
"fname",
",",
"skiprows",
"=",
"9",
")",
":",
"f",
"=",
"_read_file",
"(",
"fname",
")",
"df",
"=",
"pd",
".",
"read_csv",
"(",
"f",
",",
"header",
"=",
"\"infer\"",
",",
"index_col",
"=",
"None",
",",
"skiprows",
"=",
"skip... | DataFrame constructor to open Falmouth Scientific, Inc. (FSI) CTD
ASCII format.
Examples
--------
>>> from pathlib import Path
>>> import ctd
>>> data_path = Path(__file__).parents[1].joinpath("tests", "data")
>>> cast = ctd.from_fsi(data_path.joinpath('FSI.txt.gz'))
>>> downcast, upcas... | [
"DataFrame",
"constructor",
"to",
"open",
"Falmouth",
"Scientific",
"Inc",
".",
"(",
"FSI",
")",
"CTD",
"ASCII",
"format",
"."
] | train | https://github.com/pyoceans/python-ctd/blob/fa9a9d02da3dfed6d1d60db0e52bbab52adfe666/ctd/read.py#L395-L425 |
pyoceans/python-ctd | ctd/read.py | rosette_summary | def rosette_summary(fname):
"""
Make a BTL (bottle) file from a ROS (bottle log) file.
More control for the averaging process and at which step we want to
perform this averaging eliminating the need to read the data into SBE
Software again after pre-processing.
NOTE: Do not run LoopEdit on the ... | python | def rosette_summary(fname):
"""
Make a BTL (bottle) file from a ROS (bottle log) file.
More control for the averaging process and at which step we want to
perform this averaging eliminating the need to read the data into SBE
Software again after pre-processing.
NOTE: Do not run LoopEdit on the ... | [
"def",
"rosette_summary",
"(",
"fname",
")",
":",
"ros",
"=",
"from_cnv",
"(",
"fname",
")",
"ros",
"[",
"\"pressure\"",
"]",
"=",
"ros",
".",
"index",
".",
"values",
".",
"astype",
"(",
"float",
")",
"ros",
"[",
"\"nbf\"",
"]",
"=",
"ros",
"[",
"\... | Make a BTL (bottle) file from a ROS (bottle log) file.
More control for the averaging process and at which step we want to
perform this averaging eliminating the need to read the data into SBE
Software again after pre-processing.
NOTE: Do not run LoopEdit on the upcast!
Examples
--------
>... | [
"Make",
"a",
"BTL",
"(",
"bottle",
")",
"file",
"from",
"a",
"ROS",
"(",
"bottle",
"log",
")",
"file",
"."
] | train | https://github.com/pyoceans/python-ctd/blob/fa9a9d02da3dfed6d1d60db0e52bbab52adfe666/ctd/read.py#L428-L453 |
pyoceans/python-ctd | ctd/extras.py | _extrap1d | def _extrap1d(interpolator):
"""
http://stackoverflow.com/questions/2745329/
How to make scipy.interpolate return an extrapolated result beyond the
input range.
"""
xs, ys = interpolator.x, interpolator.y
def pointwise(x):
if x < xs[0]:
return ys[0] + (x - xs[0]) * (ys[... | python | def _extrap1d(interpolator):
"""
http://stackoverflow.com/questions/2745329/
How to make scipy.interpolate return an extrapolated result beyond the
input range.
"""
xs, ys = interpolator.x, interpolator.y
def pointwise(x):
if x < xs[0]:
return ys[0] + (x - xs[0]) * (ys[... | [
"def",
"_extrap1d",
"(",
"interpolator",
")",
":",
"xs",
",",
"ys",
"=",
"interpolator",
".",
"x",
",",
"interpolator",
".",
"y",
"def",
"pointwise",
"(",
"x",
")",
":",
"if",
"x",
"<",
"xs",
"[",
"0",
"]",
":",
"return",
"ys",
"[",
"0",
"]",
"... | http://stackoverflow.com/questions/2745329/
How to make scipy.interpolate return an extrapolated result beyond the
input range. | [
"http",
":",
"//",
"stackoverflow",
".",
"com",
"/",
"questions",
"/",
"2745329",
"/",
"How",
"to",
"make",
"scipy",
".",
"interpolate",
"return",
"an",
"extrapolated",
"result",
"beyond",
"the",
"input",
"range",
"."
] | train | https://github.com/pyoceans/python-ctd/blob/fa9a9d02da3dfed6d1d60db0e52bbab52adfe666/ctd/extras.py#L7-L29 |
pyoceans/python-ctd | ctd/extras.py | extrap_sec | def extrap_sec(data, dist, depth, w1=1.0, w2=0):
"""
Extrapolates `data` to zones where the shallow stations are shadowed by
the deep stations. The shadow region usually cannot be extrapolates via
linear interpolation.
The extrapolation is applied using the gradients of the `data` at a certain
... | python | def extrap_sec(data, dist, depth, w1=1.0, w2=0):
"""
Extrapolates `data` to zones where the shallow stations are shadowed by
the deep stations. The shadow region usually cannot be extrapolates via
linear interpolation.
The extrapolation is applied using the gradients of the `data` at a certain
... | [
"def",
"extrap_sec",
"(",
"data",
",",
"dist",
",",
"depth",
",",
"w1",
"=",
"1.0",
",",
"w2",
"=",
"0",
")",
":",
"from",
"scipy",
".",
"interpolate",
"import",
"interp1d",
"new_data1",
"=",
"[",
"]",
"for",
"row",
"in",
"data",
":",
"mask",
"=",
... | Extrapolates `data` to zones where the shallow stations are shadowed by
the deep stations. The shadow region usually cannot be extrapolates via
linear interpolation.
The extrapolation is applied using the gradients of the `data` at a certain
level.
Parameters
----------
data : array_like
... | [
"Extrapolates",
"data",
"to",
"zones",
"where",
"the",
"shallow",
"stations",
"are",
"shadowed",
"by",
"the",
"deep",
"stations",
".",
"The",
"shadow",
"region",
"usually",
"cannot",
"be",
"extrapolates",
"via",
"linear",
"interpolation",
"."
] | train | https://github.com/pyoceans/python-ctd/blob/fa9a9d02da3dfed6d1d60db0e52bbab52adfe666/ctd/extras.py#L37-L93 |
pyoceans/python-ctd | ctd/extras.py | gen_topomask | def gen_topomask(h, lon, lat, dx=1.0, kind="linear", plot=False):
"""
Generates a topography mask from an oceanographic transect taking the
deepest CTD scan as the depth of each station.
Inputs
------
h : array
Pressure of the deepest CTD scan for each station [dbar].
lons : array
... | python | def gen_topomask(h, lon, lat, dx=1.0, kind="linear", plot=False):
"""
Generates a topography mask from an oceanographic transect taking the
deepest CTD scan as the depth of each station.
Inputs
------
h : array
Pressure of the deepest CTD scan for each station [dbar].
lons : array
... | [
"def",
"gen_topomask",
"(",
"h",
",",
"lon",
",",
"lat",
",",
"dx",
"=",
"1.0",
",",
"kind",
"=",
"\"linear\"",
",",
"plot",
"=",
"False",
")",
":",
"import",
"gsw",
"from",
"scipy",
".",
"interpolate",
"import",
"interp1d",
"h",
",",
"lon",
",",
"... | Generates a topography mask from an oceanographic transect taking the
deepest CTD scan as the depth of each station.
Inputs
------
h : array
Pressure of the deepest CTD scan for each station [dbar].
lons : array
Longitude of each station [decimal degrees east].
lat : Latitude... | [
"Generates",
"a",
"topography",
"mask",
"from",
"an",
"oceanographic",
"transect",
"taking",
"the",
"deepest",
"CTD",
"scan",
"as",
"the",
"depth",
"of",
"each",
"station",
"."
] | train | https://github.com/pyoceans/python-ctd/blob/fa9a9d02da3dfed6d1d60db0e52bbab52adfe666/ctd/extras.py#L96-L140 |
pyoceans/python-ctd | ctd/extras.py | cell_thermal_mass | def cell_thermal_mass(temperature, conductivity):
"""
Sample interval is measured in seconds.
Temperature in degrees.
CTM is calculated in S/m.
"""
alpha = 0.03 # Thermal anomaly amplitude.
beta = 1.0 / 7 # Thermal anomaly time constant (1/beta).
sample_interval = 1 / 15.0
a = 2... | python | def cell_thermal_mass(temperature, conductivity):
"""
Sample interval is measured in seconds.
Temperature in degrees.
CTM is calculated in S/m.
"""
alpha = 0.03 # Thermal anomaly amplitude.
beta = 1.0 / 7 # Thermal anomaly time constant (1/beta).
sample_interval = 1 / 15.0
a = 2... | [
"def",
"cell_thermal_mass",
"(",
"temperature",
",",
"conductivity",
")",
":",
"alpha",
"=",
"0.03",
"# Thermal anomaly amplitude.",
"beta",
"=",
"1.0",
"/",
"7",
"# Thermal anomaly time constant (1/beta).",
"sample_interval",
"=",
"1",
"/",
"15.0",
"a",
"=",
"2",
... | Sample interval is measured in seconds.
Temperature in degrees.
CTM is calculated in S/m. | [
"Sample",
"interval",
"is",
"measured",
"in",
"seconds",
".",
"Temperature",
"in",
"degrees",
".",
"CTM",
"is",
"calculated",
"in",
"S",
"/",
"m",
"."
] | train | https://github.com/pyoceans/python-ctd/blob/fa9a9d02da3dfed6d1d60db0e52bbab52adfe666/ctd/extras.py#L243-L260 |
pyoceans/python-ctd | ctd/extras.py | barrier_layer_thickness | def barrier_layer_thickness(SA, CT):
"""
Compute the thickness of water separating the mixed surface layer from the
thermocline. A more precise definition would be the difference between
mixed layer depth (MLD) calculated from temperature minus the mixed layer
depth calculated using density.
"... | python | def barrier_layer_thickness(SA, CT):
"""
Compute the thickness of water separating the mixed surface layer from the
thermocline. A more precise definition would be the difference between
mixed layer depth (MLD) calculated from temperature minus the mixed layer
depth calculated using density.
"... | [
"def",
"barrier_layer_thickness",
"(",
"SA",
",",
"CT",
")",
":",
"import",
"gsw",
"sigma_theta",
"=",
"gsw",
".",
"sigma0",
"(",
"SA",
",",
"CT",
")",
"mask",
"=",
"mixed_layer_depth",
"(",
"CT",
")",
"mld",
"=",
"np",
".",
"where",
"(",
"mask",
")"... | Compute the thickness of water separating the mixed surface layer from the
thermocline. A more precise definition would be the difference between
mixed layer depth (MLD) calculated from temperature minus the mixed layer
depth calculated using density. | [
"Compute",
"the",
"thickness",
"of",
"water",
"separating",
"the",
"mixed",
"surface",
"layer",
"from",
"the",
"thermocline",
".",
"A",
"more",
"precise",
"definition",
"would",
"be",
"the",
"difference",
"between",
"mixed",
"layer",
"depth",
"(",
"MLD",
")",
... | train | https://github.com/pyoceans/python-ctd/blob/fa9a9d02da3dfed6d1d60db0e52bbab52adfe666/ctd/extras.py#L271-L289 |
pyoceans/python-ctd | ctd/plotting.py | plot_cast | def plot_cast(df, secondary_y=False, label=None, *args, **kwargs):
"""
Plot a CTD variable with the index in the y-axis instead of x-axis.
"""
ax = kwargs.pop("ax", None)
fignums = plt.get_fignums()
if ax is None and not fignums:
ax = plt.axes()
fig = ax.get_figure()
fi... | python | def plot_cast(df, secondary_y=False, label=None, *args, **kwargs):
"""
Plot a CTD variable with the index in the y-axis instead of x-axis.
"""
ax = kwargs.pop("ax", None)
fignums = plt.get_fignums()
if ax is None and not fignums:
ax = plt.axes()
fig = ax.get_figure()
fi... | [
"def",
"plot_cast",
"(",
"df",
",",
"secondary_y",
"=",
"False",
",",
"label",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"ax",
"=",
"kwargs",
".",
"pop",
"(",
"\"ax\"",
",",
"None",
")",
"fignums",
"=",
"plt",
".",
"get_fi... | Plot a CTD variable with the index in the y-axis instead of x-axis. | [
"Plot",
"a",
"CTD",
"variable",
"with",
"the",
"index",
"in",
"the",
"y",
"-",
"axis",
"instead",
"of",
"x",
"-",
"axis",
"."
] | train | https://github.com/pyoceans/python-ctd/blob/fa9a9d02da3dfed6d1d60db0e52bbab52adfe666/ctd/plotting.py#L8-L50 |
pyoceans/python-ctd | ctd/processing.py | _rolling_window | def _rolling_window(data, block):
"""
http://stackoverflow.com/questions/4936620/
Using strides for an efficient moving average filter.
"""
shape = data.shape[:-1] + (data.shape[-1] - block + 1, block)
strides = data.strides + (data.strides[-1],)
return np.lib.stride_tricks.as_strided(data,... | python | def _rolling_window(data, block):
"""
http://stackoverflow.com/questions/4936620/
Using strides for an efficient moving average filter.
"""
shape = data.shape[:-1] + (data.shape[-1] - block + 1, block)
strides = data.strides + (data.strides[-1],)
return np.lib.stride_tricks.as_strided(data,... | [
"def",
"_rolling_window",
"(",
"data",
",",
"block",
")",
":",
"shape",
"=",
"data",
".",
"shape",
"[",
":",
"-",
"1",
"]",
"+",
"(",
"data",
".",
"shape",
"[",
"-",
"1",
"]",
"-",
"block",
"+",
"1",
",",
"block",
")",
"strides",
"=",
"data",
... | http://stackoverflow.com/questions/4936620/
Using strides for an efficient moving average filter. | [
"http",
":",
"//",
"stackoverflow",
".",
"com",
"/",
"questions",
"/",
"4936620",
"/",
"Using",
"strides",
"for",
"an",
"efficient",
"moving",
"average",
"filter",
"."
] | train | https://github.com/pyoceans/python-ctd/blob/fa9a9d02da3dfed6d1d60db0e52bbab52adfe666/ctd/processing.py#L7-L15 |
pyoceans/python-ctd | ctd/processing.py | split | def split(df):
"""Returns a tuple with down/up-cast."""
idx = df.index.argmax() + 1
down = df.iloc[:idx]
# Reverse index to orient it as a CTD cast.
up = df.iloc[idx:][::-1]
return down, up | python | def split(df):
"""Returns a tuple with down/up-cast."""
idx = df.index.argmax() + 1
down = df.iloc[:idx]
# Reverse index to orient it as a CTD cast.
up = df.iloc[idx:][::-1]
return down, up | [
"def",
"split",
"(",
"df",
")",
":",
"idx",
"=",
"df",
".",
"index",
".",
"argmax",
"(",
")",
"+",
"1",
"down",
"=",
"df",
".",
"iloc",
"[",
":",
"idx",
"]",
"# Reverse index to orient it as a CTD cast.",
"up",
"=",
"df",
".",
"iloc",
"[",
"idx",
"... | Returns a tuple with down/up-cast. | [
"Returns",
"a",
"tuple",
"with",
"down",
"/",
"up",
"-",
"cast",
"."
] | train | https://github.com/pyoceans/python-ctd/blob/fa9a9d02da3dfed6d1d60db0e52bbab52adfe666/ctd/processing.py#L27-L33 |
pyoceans/python-ctd | ctd/processing.py | lp_filter | def lp_filter(df, sample_rate=24.0, time_constant=0.15):
"""
Filter a series with `time_constant` (use 0.15 s for pressure), and for
a signal of `sample_rate` in Hertz (24 Hz for 911+).
NOTE: 911+ systems do not require filter for temperature nor salinity.
Examples
--------
>>> from pathlib... | python | def lp_filter(df, sample_rate=24.0, time_constant=0.15):
"""
Filter a series with `time_constant` (use 0.15 s for pressure), and for
a signal of `sample_rate` in Hertz (24 Hz for 911+).
NOTE: 911+ systems do not require filter for temperature nor salinity.
Examples
--------
>>> from pathlib... | [
"def",
"lp_filter",
"(",
"df",
",",
"sample_rate",
"=",
"24.0",
",",
"time_constant",
"=",
"0.15",
")",
":",
"from",
"scipy",
"import",
"signal",
"# Butter is closer to what SBE is doing with their cosine filter.",
"Wn",
"=",
"(",
"1.0",
"/",
"time_constant",
")",
... | Filter a series with `time_constant` (use 0.15 s for pressure), and for
a signal of `sample_rate` in Hertz (24 Hz for 911+).
NOTE: 911+ systems do not require filter for temperature nor salinity.
Examples
--------
>>> from pathlib import Path
>>> import matplotlib.pyplot as plt
>>> import c... | [
"Filter",
"a",
"series",
"with",
"time_constant",
"(",
"use",
"0",
".",
"15",
"s",
"for",
"pressure",
")",
"and",
"for",
"a",
"signal",
"of",
"sample_rate",
"in",
"Hertz",
"(",
"24",
"Hz",
"for",
"911",
"+",
")",
".",
"NOTE",
":",
"911",
"+",
"syst... | train | https://github.com/pyoceans/python-ctd/blob/fa9a9d02da3dfed6d1d60db0e52bbab52adfe666/ctd/processing.py#L38-L75 |
pyoceans/python-ctd | ctd/processing.py | press_check | def press_check(df):
"""
Remove pressure reversals from the index.
"""
new_df = df.copy()
press = new_df.copy().index.values
ref = press[0]
inversions = np.diff(np.r_[press, press[-1]]) < 0
mask = np.zeros_like(inversions)
for k, p in enumerate(inversions):
if p:
... | python | def press_check(df):
"""
Remove pressure reversals from the index.
"""
new_df = df.copy()
press = new_df.copy().index.values
ref = press[0]
inversions = np.diff(np.r_[press, press[-1]]) < 0
mask = np.zeros_like(inversions)
for k, p in enumerate(inversions):
if p:
... | [
"def",
"press_check",
"(",
"df",
")",
":",
"new_df",
"=",
"df",
".",
"copy",
"(",
")",
"press",
"=",
"new_df",
".",
"copy",
"(",
")",
".",
"index",
".",
"values",
"ref",
"=",
"press",
"[",
"0",
"]",
"inversions",
"=",
"np",
".",
"diff",
"(",
"n... | Remove pressure reversals from the index. | [
"Remove",
"pressure",
"reversals",
"from",
"the",
"index",
"."
] | train | https://github.com/pyoceans/python-ctd/blob/fa9a9d02da3dfed6d1d60db0e52bbab52adfe666/ctd/processing.py#L80-L97 |
pyoceans/python-ctd | ctd/processing.py | bindata | def bindata(df, delta=1.0, method="average"):
"""
Bin average the index (usually pressure) to a given interval (default
delta = 1).
"""
start = np.floor(df.index[0])
stop = np.ceil(df.index[-1])
new_index = np.arange(start, stop, delta)
binned = pd.cut(df.index, bins=new_index)
if m... | python | def bindata(df, delta=1.0, method="average"):
"""
Bin average the index (usually pressure) to a given interval (default
delta = 1).
"""
start = np.floor(df.index[0])
stop = np.ceil(df.index[-1])
new_index = np.arange(start, stop, delta)
binned = pd.cut(df.index, bins=new_index)
if m... | [
"def",
"bindata",
"(",
"df",
",",
"delta",
"=",
"1.0",
",",
"method",
"=",
"\"average\"",
")",
":",
"start",
"=",
"np",
".",
"floor",
"(",
"df",
".",
"index",
"[",
"0",
"]",
")",
"stop",
"=",
"np",
".",
"ceil",
"(",
"df",
".",
"index",
"[",
"... | Bin average the index (usually pressure) to a given interval (default
delta = 1). | [
"Bin",
"average",
"the",
"index",
"(",
"usually",
"pressure",
")",
"to",
"a",
"given",
"interval",
"(",
"default",
"delta",
"=",
"1",
")",
"."
] | train | https://github.com/pyoceans/python-ctd/blob/fa9a9d02da3dfed6d1d60db0e52bbab52adfe666/ctd/processing.py#L102-L123 |
pyoceans/python-ctd | ctd/processing.py | _despike | def _despike(series, n1, n2, block, keep):
"""
Wild Edit Seabird-like function. Passes with Standard deviation
`n1` and `n2` with window size `block`.
"""
data = series.values.astype(float).copy()
roll = _rolling_window(data, block)
roll = ma.masked_invalid(roll)
std = n1 * roll.std(a... | python | def _despike(series, n1, n2, block, keep):
"""
Wild Edit Seabird-like function. Passes with Standard deviation
`n1` and `n2` with window size `block`.
"""
data = series.values.astype(float).copy()
roll = _rolling_window(data, block)
roll = ma.masked_invalid(roll)
std = n1 * roll.std(a... | [
"def",
"_despike",
"(",
"series",
",",
"n1",
",",
"n2",
",",
"block",
",",
"keep",
")",
":",
"data",
"=",
"series",
".",
"values",
".",
"astype",
"(",
"float",
")",
".",
"copy",
"(",
")",
"roll",
"=",
"_rolling_window",
"(",
"data",
",",
"block",
... | Wild Edit Seabird-like function. Passes with Standard deviation
`n1` and `n2` with window size `block`. | [
"Wild",
"Edit",
"Seabird",
"-",
"like",
"function",
".",
"Passes",
"with",
"Standard",
"deviation",
"n1",
"and",
"n2",
"with",
"window",
"size",
"block",
"."
] | train | https://github.com/pyoceans/python-ctd/blob/fa9a9d02da3dfed6d1d60db0e52bbab52adfe666/ctd/processing.py#L126-L162 |
pyoceans/python-ctd | ctd/processing.py | despike | def despike(df, n1=2, n2=20, block=100, keep=0):
"""
Wild Edit Seabird-like function. Passes with Standard deviation
`n1` and `n2` with window size `block`.
"""
if isinstance(df, pd.Series):
new_df = _despike(df, n1=n1, n2=n2, block=block, keep=keep)
else:
new_df = df.apply(_de... | python | def despike(df, n1=2, n2=20, block=100, keep=0):
"""
Wild Edit Seabird-like function. Passes with Standard deviation
`n1` and `n2` with window size `block`.
"""
if isinstance(df, pd.Series):
new_df = _despike(df, n1=n1, n2=n2, block=block, keep=keep)
else:
new_df = df.apply(_de... | [
"def",
"despike",
"(",
"df",
",",
"n1",
"=",
"2",
",",
"n2",
"=",
"20",
",",
"block",
"=",
"100",
",",
"keep",
"=",
"0",
")",
":",
"if",
"isinstance",
"(",
"df",
",",
"pd",
".",
"Series",
")",
":",
"new_df",
"=",
"_despike",
"(",
"df",
",",
... | Wild Edit Seabird-like function. Passes with Standard deviation
`n1` and `n2` with window size `block`. | [
"Wild",
"Edit",
"Seabird",
"-",
"like",
"function",
".",
"Passes",
"with",
"Standard",
"deviation",
"n1",
"and",
"n2",
"with",
"window",
"size",
"block",
"."
] | train | https://github.com/pyoceans/python-ctd/blob/fa9a9d02da3dfed6d1d60db0e52bbab52adfe666/ctd/processing.py#L167-L177 |
pyoceans/python-ctd | ctd/processing.py | _smooth | def _smooth(series, window_len, window):
"""Smooth the data using a window with requested size."""
windows = {
"flat": np.ones,
"hanning": np.hanning,
"hamming": np.hamming,
"bartlett": np.bartlett,
"blackman": np.blackman,
}
data = series.values.copy()
if w... | python | def _smooth(series, window_len, window):
"""Smooth the data using a window with requested size."""
windows = {
"flat": np.ones,
"hanning": np.hanning,
"hamming": np.hamming,
"bartlett": np.bartlett,
"blackman": np.blackman,
}
data = series.values.copy()
if w... | [
"def",
"_smooth",
"(",
"series",
",",
"window_len",
",",
"window",
")",
":",
"windows",
"=",
"{",
"\"flat\"",
":",
"np",
".",
"ones",
",",
"\"hanning\"",
":",
"np",
".",
"hanning",
",",
"\"hamming\"",
":",
"np",
".",
"hamming",
",",
"\"bartlett\"",
":"... | Smooth the data using a window with requested size. | [
"Smooth",
"the",
"data",
"using",
"a",
"window",
"with",
"requested",
"size",
"."
] | train | https://github.com/pyoceans/python-ctd/blob/fa9a9d02da3dfed6d1d60db0e52bbab52adfe666/ctd/processing.py#L180-L211 |
pyoceans/python-ctd | ctd/processing.py | smooth | def smooth(df, window_len=11, window="hanning"):
"""Smooth the data using a window with requested size."""
if isinstance(df, pd.Series):
new_df = _smooth(df, window_len=window_len, window=window)
else:
new_df = df.apply(_smooth, window_len=window_len, window=window)
return new_df | python | def smooth(df, window_len=11, window="hanning"):
"""Smooth the data using a window with requested size."""
if isinstance(df, pd.Series):
new_df = _smooth(df, window_len=window_len, window=window)
else:
new_df = df.apply(_smooth, window_len=window_len, window=window)
return new_df | [
"def",
"smooth",
"(",
"df",
",",
"window_len",
"=",
"11",
",",
"window",
"=",
"\"hanning\"",
")",
":",
"if",
"isinstance",
"(",
"df",
",",
"pd",
".",
"Series",
")",
":",
"new_df",
"=",
"_smooth",
"(",
"df",
",",
"window_len",
"=",
"window_len",
",",
... | Smooth the data using a window with requested size. | [
"Smooth",
"the",
"data",
"using",
"a",
"window",
"with",
"requested",
"size",
"."
] | train | https://github.com/pyoceans/python-ctd/blob/fa9a9d02da3dfed6d1d60db0e52bbab52adfe666/ctd/processing.py#L216-L222 |
mayhewj/greenstalk | greenstalk.py | Client.put | def put(self,
body: Body,
priority: int = DEFAULT_PRIORITY,
delay: int = DEFAULT_DELAY,
ttr: int = DEFAULT_TTR) -> int:
"""Inserts a job into the currently used tube and returns the job ID.
:param body: The data representing the job.
:param priori... | python | def put(self,
body: Body,
priority: int = DEFAULT_PRIORITY,
delay: int = DEFAULT_DELAY,
ttr: int = DEFAULT_TTR) -> int:
"""Inserts a job into the currently used tube and returns the job ID.
:param body: The data representing the job.
:param priori... | [
"def",
"put",
"(",
"self",
",",
"body",
":",
"Body",
",",
"priority",
":",
"int",
"=",
"DEFAULT_PRIORITY",
",",
"delay",
":",
"int",
"=",
"DEFAULT_DELAY",
",",
"ttr",
":",
"int",
"=",
"DEFAULT_TTR",
")",
"->",
"int",
":",
"if",
"isinstance",
"(",
"bo... | Inserts a job into the currently used tube and returns the job ID.
:param body: The data representing the job.
:param priority: An integer between 0 and 4,294,967,295 where 0 is the
most urgent.
:param delay: The number of seconds to delay the job for.
:param tt... | [
"Inserts",
"a",
"job",
"into",
"the",
"currently",
"used",
"tube",
"and",
"returns",
"the",
"job",
"ID",
"."
] | train | https://github.com/mayhewj/greenstalk/blob/765a5e7321a101a08e400a66e88df06c57406f58/greenstalk.py#L199-L218 |
mayhewj/greenstalk | greenstalk.py | Client.use | def use(self, tube: str) -> None:
"""Changes the currently used tube.
:param tube: The tube to use.
"""
self._send_cmd(b'use %b' % tube.encode('ascii'), b'USING') | python | def use(self, tube: str) -> None:
"""Changes the currently used tube.
:param tube: The tube to use.
"""
self._send_cmd(b'use %b' % tube.encode('ascii'), b'USING') | [
"def",
"use",
"(",
"self",
",",
"tube",
":",
"str",
")",
"->",
"None",
":",
"self",
".",
"_send_cmd",
"(",
"b'use %b'",
"%",
"tube",
".",
"encode",
"(",
"'ascii'",
")",
",",
"b'USING'",
")"
] | Changes the currently used tube.
:param tube: The tube to use. | [
"Changes",
"the",
"currently",
"used",
"tube",
"."
] | train | https://github.com/mayhewj/greenstalk/blob/765a5e7321a101a08e400a66e88df06c57406f58/greenstalk.py#L220-L225 |
mayhewj/greenstalk | greenstalk.py | Client.reserve | def reserve(self, timeout: Optional[int] = None) -> Job:
"""Reserves a job from a tube on the watch list, giving this client
exclusive access to it for the TTR. Returns the reserved job.
This blocks until a job is reserved unless a ``timeout`` is given,
which will raise a :class:`TimedO... | python | def reserve(self, timeout: Optional[int] = None) -> Job:
"""Reserves a job from a tube on the watch list, giving this client
exclusive access to it for the TTR. Returns the reserved job.
This blocks until a job is reserved unless a ``timeout`` is given,
which will raise a :class:`TimedO... | [
"def",
"reserve",
"(",
"self",
",",
"timeout",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
")",
"->",
"Job",
":",
"if",
"timeout",
"is",
"None",
":",
"cmd",
"=",
"b'reserve'",
"else",
":",
"cmd",
"=",
"b'reserve-with-timeout %d'",
"%",
"timeout",
"r... | Reserves a job from a tube on the watch list, giving this client
exclusive access to it for the TTR. Returns the reserved job.
This blocks until a job is reserved unless a ``timeout`` is given,
which will raise a :class:`TimedOutError <greenstalk.TimedOutError>` if
a job cannot be reser... | [
"Reserves",
"a",
"job",
"from",
"a",
"tube",
"on",
"the",
"watch",
"list",
"giving",
"this",
"client",
"exclusive",
"access",
"to",
"it",
"for",
"the",
"TTR",
".",
"Returns",
"the",
"reserved",
"job",
"."
] | train | https://github.com/mayhewj/greenstalk/blob/765a5e7321a101a08e400a66e88df06c57406f58/greenstalk.py#L227-L241 |
mayhewj/greenstalk | greenstalk.py | Client.delete | def delete(self, job: JobOrID) -> None:
"""Deletes a job.
:param job: The job or job ID to delete.
"""
self._send_cmd(b'delete %d' % _to_id(job), b'DELETED') | python | def delete(self, job: JobOrID) -> None:
"""Deletes a job.
:param job: The job or job ID to delete.
"""
self._send_cmd(b'delete %d' % _to_id(job), b'DELETED') | [
"def",
"delete",
"(",
"self",
",",
"job",
":",
"JobOrID",
")",
"->",
"None",
":",
"self",
".",
"_send_cmd",
"(",
"b'delete %d'",
"%",
"_to_id",
"(",
"job",
")",
",",
"b'DELETED'",
")"
] | Deletes a job.
:param job: The job or job ID to delete. | [
"Deletes",
"a",
"job",
"."
] | train | https://github.com/mayhewj/greenstalk/blob/765a5e7321a101a08e400a66e88df06c57406f58/greenstalk.py#L243-L248 |
mayhewj/greenstalk | greenstalk.py | Client.release | def release(self,
job: Job,
priority: int = DEFAULT_PRIORITY,
delay: int = DEFAULT_DELAY) -> None:
"""Releases a reserved job.
:param job: The job to release.
:param priority: An integer between 0 and 4,294,967,295 where 0 is the
... | python | def release(self,
job: Job,
priority: int = DEFAULT_PRIORITY,
delay: int = DEFAULT_DELAY) -> None:
"""Releases a reserved job.
:param job: The job to release.
:param priority: An integer between 0 and 4,294,967,295 where 0 is the
... | [
"def",
"release",
"(",
"self",
",",
"job",
":",
"Job",
",",
"priority",
":",
"int",
"=",
"DEFAULT_PRIORITY",
",",
"delay",
":",
"int",
"=",
"DEFAULT_DELAY",
")",
"->",
"None",
":",
"self",
".",
"_send_cmd",
"(",
"b'release %d %d %d'",
"%",
"(",
"job",
... | Releases a reserved job.
:param job: The job to release.
:param priority: An integer between 0 and 4,294,967,295 where 0 is the
most urgent.
:param delay: The number of seconds to delay the job for. | [
"Releases",
"a",
"reserved",
"job",
"."
] | train | https://github.com/mayhewj/greenstalk/blob/765a5e7321a101a08e400a66e88df06c57406f58/greenstalk.py#L250-L261 |
mayhewj/greenstalk | greenstalk.py | Client.bury | def bury(self, job: Job, priority: int = DEFAULT_PRIORITY) -> None:
"""Buries a reserved job.
:param job: The job to bury.
:param priority: An integer between 0 and 4,294,967,295 where 0 is the
most urgent.
"""
self._send_cmd(b'bury %d %d' % (job.id, pri... | python | def bury(self, job: Job, priority: int = DEFAULT_PRIORITY) -> None:
"""Buries a reserved job.
:param job: The job to bury.
:param priority: An integer between 0 and 4,294,967,295 where 0 is the
most urgent.
"""
self._send_cmd(b'bury %d %d' % (job.id, pri... | [
"def",
"bury",
"(",
"self",
",",
"job",
":",
"Job",
",",
"priority",
":",
"int",
"=",
"DEFAULT_PRIORITY",
")",
"->",
"None",
":",
"self",
".",
"_send_cmd",
"(",
"b'bury %d %d'",
"%",
"(",
"job",
".",
"id",
",",
"priority",
")",
",",
"b'BURIED'",
")"
... | Buries a reserved job.
:param job: The job to bury.
:param priority: An integer between 0 and 4,294,967,295 where 0 is the
most urgent. | [
"Buries",
"a",
"reserved",
"job",
"."
] | train | https://github.com/mayhewj/greenstalk/blob/765a5e7321a101a08e400a66e88df06c57406f58/greenstalk.py#L263-L270 |
mayhewj/greenstalk | greenstalk.py | Client.touch | def touch(self, job: Job) -> None:
"""Refreshes the TTR of a reserved job.
:param job: The job to touch.
"""
self._send_cmd(b'touch %d' % job.id, b'TOUCHED') | python | def touch(self, job: Job) -> None:
"""Refreshes the TTR of a reserved job.
:param job: The job to touch.
"""
self._send_cmd(b'touch %d' % job.id, b'TOUCHED') | [
"def",
"touch",
"(",
"self",
",",
"job",
":",
"Job",
")",
"->",
"None",
":",
"self",
".",
"_send_cmd",
"(",
"b'touch %d'",
"%",
"job",
".",
"id",
",",
"b'TOUCHED'",
")"
] | Refreshes the TTR of a reserved job.
:param job: The job to touch. | [
"Refreshes",
"the",
"TTR",
"of",
"a",
"reserved",
"job",
"."
] | train | https://github.com/mayhewj/greenstalk/blob/765a5e7321a101a08e400a66e88df06c57406f58/greenstalk.py#L272-L277 |
mayhewj/greenstalk | greenstalk.py | Client.watch | def watch(self, tube: str) -> int:
"""Adds a tube to the watch list. Returns the number of tubes this
client is watching.
:param tube: The tube to watch.
"""
return self._int_cmd(b'watch %b' % tube.encode('ascii'), b'WATCHING') | python | def watch(self, tube: str) -> int:
"""Adds a tube to the watch list. Returns the number of tubes this
client is watching.
:param tube: The tube to watch.
"""
return self._int_cmd(b'watch %b' % tube.encode('ascii'), b'WATCHING') | [
"def",
"watch",
"(",
"self",
",",
"tube",
":",
"str",
")",
"->",
"int",
":",
"return",
"self",
".",
"_int_cmd",
"(",
"b'watch %b'",
"%",
"tube",
".",
"encode",
"(",
"'ascii'",
")",
",",
"b'WATCHING'",
")"
] | Adds a tube to the watch list. Returns the number of tubes this
client is watching.
:param tube: The tube to watch. | [
"Adds",
"a",
"tube",
"to",
"the",
"watch",
"list",
".",
"Returns",
"the",
"number",
"of",
"tubes",
"this",
"client",
"is",
"watching",
"."
] | train | https://github.com/mayhewj/greenstalk/blob/765a5e7321a101a08e400a66e88df06c57406f58/greenstalk.py#L279-L285 |
mayhewj/greenstalk | greenstalk.py | Client.ignore | def ignore(self, tube: str) -> int:
"""Removes a tube from the watch list. Returns the number of tubes this
client is watching.
:param tube: The tube to ignore.
"""
return self._int_cmd(b'ignore %b' % tube.encode('ascii'), b'WATCHING') | python | def ignore(self, tube: str) -> int:
"""Removes a tube from the watch list. Returns the number of tubes this
client is watching.
:param tube: The tube to ignore.
"""
return self._int_cmd(b'ignore %b' % tube.encode('ascii'), b'WATCHING') | [
"def",
"ignore",
"(",
"self",
",",
"tube",
":",
"str",
")",
"->",
"int",
":",
"return",
"self",
".",
"_int_cmd",
"(",
"b'ignore %b'",
"%",
"tube",
".",
"encode",
"(",
"'ascii'",
")",
",",
"b'WATCHING'",
")"
] | Removes a tube from the watch list. Returns the number of tubes this
client is watching.
:param tube: The tube to ignore. | [
"Removes",
"a",
"tube",
"from",
"the",
"watch",
"list",
".",
"Returns",
"the",
"number",
"of",
"tubes",
"this",
"client",
"is",
"watching",
"."
] | train | https://github.com/mayhewj/greenstalk/blob/765a5e7321a101a08e400a66e88df06c57406f58/greenstalk.py#L287-L293 |
mayhewj/greenstalk | greenstalk.py | Client.kick | def kick(self, bound: int) -> int:
"""Moves delayed and buried jobs into the ready queue and returns the
number of jobs effected.
Only jobs from the currently used tube are moved.
A kick will only move jobs in a single state. If there are any buried
jobs, only those will be mov... | python | def kick(self, bound: int) -> int:
"""Moves delayed and buried jobs into the ready queue and returns the
number of jobs effected.
Only jobs from the currently used tube are moved.
A kick will only move jobs in a single state. If there are any buried
jobs, only those will be mov... | [
"def",
"kick",
"(",
"self",
",",
"bound",
":",
"int",
")",
"->",
"int",
":",
"return",
"self",
".",
"_int_cmd",
"(",
"b'kick %d'",
"%",
"bound",
",",
"b'KICKED'",
")"
] | Moves delayed and buried jobs into the ready queue and returns the
number of jobs effected.
Only jobs from the currently used tube are moved.
A kick will only move jobs in a single state. If there are any buried
jobs, only those will be moved. Otherwise delayed jobs will be moved.
... | [
"Moves",
"delayed",
"and",
"buried",
"jobs",
"into",
"the",
"ready",
"queue",
"and",
"returns",
"the",
"number",
"of",
"jobs",
"effected",
"."
] | train | https://github.com/mayhewj/greenstalk/blob/765a5e7321a101a08e400a66e88df06c57406f58/greenstalk.py#L314-L325 |
mayhewj/greenstalk | greenstalk.py | Client.kick_job | def kick_job(self, job: JobOrID) -> None:
"""Moves a delayed or buried job into the ready queue.
:param job: The job or job ID to kick.
"""
self._send_cmd(b'kick-job %d' % _to_id(job), b'KICKED') | python | def kick_job(self, job: JobOrID) -> None:
"""Moves a delayed or buried job into the ready queue.
:param job: The job or job ID to kick.
"""
self._send_cmd(b'kick-job %d' % _to_id(job), b'KICKED') | [
"def",
"kick_job",
"(",
"self",
",",
"job",
":",
"JobOrID",
")",
"->",
"None",
":",
"self",
".",
"_send_cmd",
"(",
"b'kick-job %d'",
"%",
"_to_id",
"(",
"job",
")",
",",
"b'KICKED'",
")"
] | Moves a delayed or buried job into the ready queue.
:param job: The job or job ID to kick. | [
"Moves",
"a",
"delayed",
"or",
"buried",
"job",
"into",
"the",
"ready",
"queue",
"."
] | train | https://github.com/mayhewj/greenstalk/blob/765a5e7321a101a08e400a66e88df06c57406f58/greenstalk.py#L327-L332 |
mayhewj/greenstalk | greenstalk.py | Client.stats_job | def stats_job(self, job: JobOrID) -> Stats:
"""Returns job statistics.
:param job: The job or job ID to return statistics for.
"""
return self._stats_cmd(b'stats-job %d' % _to_id(job)) | python | def stats_job(self, job: JobOrID) -> Stats:
"""Returns job statistics.
:param job: The job or job ID to return statistics for.
"""
return self._stats_cmd(b'stats-job %d' % _to_id(job)) | [
"def",
"stats_job",
"(",
"self",
",",
"job",
":",
"JobOrID",
")",
"->",
"Stats",
":",
"return",
"self",
".",
"_stats_cmd",
"(",
"b'stats-job %d'",
"%",
"_to_id",
"(",
"job",
")",
")"
] | Returns job statistics.
:param job: The job or job ID to return statistics for. | [
"Returns",
"job",
"statistics",
"."
] | train | https://github.com/mayhewj/greenstalk/blob/765a5e7321a101a08e400a66e88df06c57406f58/greenstalk.py#L334-L339 |
mayhewj/greenstalk | greenstalk.py | Client.stats_tube | def stats_tube(self, tube: str) -> Stats:
"""Returns tube statistics.
:param tube: The tube to return statistics for.
"""
return self._stats_cmd(b'stats-tube %b' % tube.encode('ascii')) | python | def stats_tube(self, tube: str) -> Stats:
"""Returns tube statistics.
:param tube: The tube to return statistics for.
"""
return self._stats_cmd(b'stats-tube %b' % tube.encode('ascii')) | [
"def",
"stats_tube",
"(",
"self",
",",
"tube",
":",
"str",
")",
"->",
"Stats",
":",
"return",
"self",
".",
"_stats_cmd",
"(",
"b'stats-tube %b'",
"%",
"tube",
".",
"encode",
"(",
"'ascii'",
")",
")"
] | Returns tube statistics.
:param tube: The tube to return statistics for. | [
"Returns",
"tube",
"statistics",
"."
] | train | https://github.com/mayhewj/greenstalk/blob/765a5e7321a101a08e400a66e88df06c57406f58/greenstalk.py#L341-L346 |
mayhewj/greenstalk | greenstalk.py | Client.pause_tube | def pause_tube(self, tube: str, delay: int) -> None:
"""Prevents jobs from being reserved from a tube for a period of time.
:param tube: The tube to pause.
:param delay: The number of seconds to pause the tube for.
"""
self._send_cmd(b'pause-tube %b %d' % (tube.encode('ascii'), ... | python | def pause_tube(self, tube: str, delay: int) -> None:
"""Prevents jobs from being reserved from a tube for a period of time.
:param tube: The tube to pause.
:param delay: The number of seconds to pause the tube for.
"""
self._send_cmd(b'pause-tube %b %d' % (tube.encode('ascii'), ... | [
"def",
"pause_tube",
"(",
"self",
",",
"tube",
":",
"str",
",",
"delay",
":",
"int",
")",
"->",
"None",
":",
"self",
".",
"_send_cmd",
"(",
"b'pause-tube %b %d'",
"%",
"(",
"tube",
".",
"encode",
"(",
"'ascii'",
")",
",",
"delay",
")",
",",
"b'PAUSED... | Prevents jobs from being reserved from a tube for a period of time.
:param tube: The tube to pause.
:param delay: The number of seconds to pause the tube for. | [
"Prevents",
"jobs",
"from",
"being",
"reserved",
"from",
"a",
"tube",
"for",
"a",
"period",
"of",
"time",
"."
] | train | https://github.com/mayhewj/greenstalk/blob/765a5e7321a101a08e400a66e88df06c57406f58/greenstalk.py#L352-L358 |
fedora-infra/fedora-messaging | fedora_messaging/cli.py | cli | def cli(conf):
"""The fedora-messaging command line interface."""
if conf:
if not os.path.isfile(conf):
raise click.exceptions.BadParameter("{} is not a file".format(conf))
try:
config.conf.load_config(config_path=conf)
except exceptions.ConfigurationException as ... | python | def cli(conf):
"""The fedora-messaging command line interface."""
if conf:
if not os.path.isfile(conf):
raise click.exceptions.BadParameter("{} is not a file".format(conf))
try:
config.conf.load_config(config_path=conf)
except exceptions.ConfigurationException as ... | [
"def",
"cli",
"(",
"conf",
")",
":",
"if",
"conf",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"conf",
")",
":",
"raise",
"click",
".",
"exceptions",
".",
"BadParameter",
"(",
"\"{} is not a file\"",
".",
"format",
"(",
"conf",
")",
")",... | The fedora-messaging command line interface. | [
"The",
"fedora",
"-",
"messaging",
"command",
"line",
"interface",
"."
] | train | https://github.com/fedora-infra/fedora-messaging/blob/be3e88534e2b15d579bcd24f9c4b7e795cb7e0b7/fedora_messaging/cli.py#L78-L89 |
fedora-infra/fedora-messaging | fedora_messaging/cli.py | consume | def consume(exchange, queue_name, routing_key, callback, app_name):
"""Consume messages from an AMQP queue using a Python callback."""
# The configuration validates these are not null and contain all required keys
# when it is loaded.
bindings = config.conf["bindings"]
queues = config.conf["queues"... | python | def consume(exchange, queue_name, routing_key, callback, app_name):
"""Consume messages from an AMQP queue using a Python callback."""
# The configuration validates these are not null and contain all required keys
# when it is loaded.
bindings = config.conf["bindings"]
queues = config.conf["queues"... | [
"def",
"consume",
"(",
"exchange",
",",
"queue_name",
",",
"routing_key",
",",
"callback",
",",
"app_name",
")",
":",
"# The configuration validates these are not null and contain all required keys",
"# when it is loaded.",
"bindings",
"=",
"config",
".",
"conf",
"[",
"\"... | Consume messages from an AMQP queue using a Python callback. | [
"Consume",
"messages",
"from",
"an",
"AMQP",
"queue",
"using",
"a",
"Python",
"callback",
"."
] | train | https://github.com/fedora-infra/fedora-messaging/blob/be3e88534e2b15d579bcd24f9c4b7e795cb7e0b7/fedora_messaging/cli.py#L98-L178 |
fedora-infra/fedora-messaging | fedora_messaging/cli.py | _consume_errback | def _consume_errback(failure):
"""Handle any errors that occur during consumer registration."""
global _exit_code
if failure.check(exceptions.BadDeclaration):
_log.error(
"Unable to declare the %s object on the AMQP broker. The "
"broker responded with %s. Check permissions f... | python | def _consume_errback(failure):
"""Handle any errors that occur during consumer registration."""
global _exit_code
if failure.check(exceptions.BadDeclaration):
_log.error(
"Unable to declare the %s object on the AMQP broker. The "
"broker responded with %s. Check permissions f... | [
"def",
"_consume_errback",
"(",
"failure",
")",
":",
"global",
"_exit_code",
"if",
"failure",
".",
"check",
"(",
"exceptions",
".",
"BadDeclaration",
")",
":",
"_log",
".",
"error",
"(",
"\"Unable to declare the %s object on the AMQP broker. The \"",
"\"broker responded... | Handle any errors that occur during consumer registration. | [
"Handle",
"any",
"errors",
"that",
"occur",
"during",
"consumer",
"registration",
"."
] | train | https://github.com/fedora-infra/fedora-messaging/blob/be3e88534e2b15d579bcd24f9c4b7e795cb7e0b7/fedora_messaging/cli.py#L181-L211 |
fedora-infra/fedora-messaging | fedora_messaging/cli.py | _consume_callback | def _consume_callback(consumers):
"""
Callback when consumers are successfully registered.
This simply registers callbacks for consumer.result deferred object which
fires when the consumer stops.
Args
consumers (list of fedora_messaging.api.Consumer):
The list of consumers that... | python | def _consume_callback(consumers):
"""
Callback when consumers are successfully registered.
This simply registers callbacks for consumer.result deferred object which
fires when the consumer stops.
Args
consumers (list of fedora_messaging.api.Consumer):
The list of consumers that... | [
"def",
"_consume_callback",
"(",
"consumers",
")",
":",
"for",
"consumer",
"in",
"consumers",
":",
"def",
"errback",
"(",
"failure",
")",
":",
"global",
"_exit_code",
"if",
"failure",
".",
"check",
"(",
"exceptions",
".",
"HaltConsumer",
")",
":",
"_exit_cod... | Callback when consumers are successfully registered.
This simply registers callbacks for consumer.result deferred object which
fires when the consumer stops.
Args
consumers (list of fedora_messaging.api.Consumer):
The list of consumers that were successfully created. | [
"Callback",
"when",
"consumers",
"are",
"successfully",
"registered",
"."
] | train | https://github.com/fedora-infra/fedora-messaging/blob/be3e88534e2b15d579bcd24f9c4b7e795cb7e0b7/fedora_messaging/cli.py#L214-L268 |
fedora-infra/fedora-messaging | fedora_messaging/twisted/protocol.py | _add_timeout | def _add_timeout(deferred, timeout):
"""
Add a timeout to the given deferred. This is designed to work with both old
Twisted and versions of Twisted with the addTimeout API. This is
exclusively to support EL7.
The deferred will errback with a :class:`defer.CancelledError` if the
version of Twis... | python | def _add_timeout(deferred, timeout):
"""
Add a timeout to the given deferred. This is designed to work with both old
Twisted and versions of Twisted with the addTimeout API. This is
exclusively to support EL7.
The deferred will errback with a :class:`defer.CancelledError` if the
version of Twis... | [
"def",
"_add_timeout",
"(",
"deferred",
",",
"timeout",
")",
":",
"try",
":",
"deferred",
".",
"addTimeout",
"(",
"timeout",
",",
"reactor",
")",
"except",
"AttributeError",
":",
"# Twisted 12.2 (in EL7) does not have the addTimeout API, so make do with",
"# the slightly ... | Add a timeout to the given deferred. This is designed to work with both old
Twisted and versions of Twisted with the addTimeout API. This is
exclusively to support EL7.
The deferred will errback with a :class:`defer.CancelledError` if the
version of Twisted being used doesn't have the
``defer.Defer... | [
"Add",
"a",
"timeout",
"to",
"the",
"given",
"deferred",
".",
"This",
"is",
"designed",
"to",
"work",
"with",
"both",
"old",
"Twisted",
"and",
"versions",
"of",
"Twisted",
"with",
"the",
"addTimeout",
"API",
".",
"This",
"is",
"exclusively",
"to",
"support... | train | https://github.com/fedora-infra/fedora-messaging/blob/be3e88534e2b15d579bcd24f9c4b7e795cb7e0b7/fedora_messaging/twisted/protocol.py#L72-L97 |
fedora-infra/fedora-messaging | fedora_messaging/twisted/protocol.py | FedoraMessagingProtocolV2._allocate_channel | def _allocate_channel(self):
"""
Allocate a new AMQP channel.
Raises:
NoFreeChannels: If this connection has reached its maximum number of channels.
"""
try:
channel = yield self.channel()
except pika.exceptions.NoFreeChannels:
raise N... | python | def _allocate_channel(self):
"""
Allocate a new AMQP channel.
Raises:
NoFreeChannels: If this connection has reached its maximum number of channels.
"""
try:
channel = yield self.channel()
except pika.exceptions.NoFreeChannels:
raise N... | [
"def",
"_allocate_channel",
"(",
"self",
")",
":",
"try",
":",
"channel",
"=",
"yield",
"self",
".",
"channel",
"(",
")",
"except",
"pika",
".",
"exceptions",
".",
"NoFreeChannels",
":",
"raise",
"NoFreeChannels",
"(",
")",
"_std_log",
".",
"debug",
"(",
... | Allocate a new AMQP channel.
Raises:
NoFreeChannels: If this connection has reached its maximum number of channels. | [
"Allocate",
"a",
"new",
"AMQP",
"channel",
"."
] | train | https://github.com/fedora-infra/fedora-messaging/blob/be3e88534e2b15d579bcd24f9c4b7e795cb7e0b7/fedora_messaging/twisted/protocol.py#L131-L145 |
fedora-infra/fedora-messaging | fedora_messaging/twisted/protocol.py | FedoraMessagingProtocolV2.connectionReady | def connectionReady(self, res=None):
"""
Callback invoked when the AMQP connection is ready (when self.ready fires).
This API is not meant for users.
Args:
res: This is an unused argument that provides compatibility with Pika
versions lower than 1.0.0.
... | python | def connectionReady(self, res=None):
"""
Callback invoked when the AMQP connection is ready (when self.ready fires).
This API is not meant for users.
Args:
res: This is an unused argument that provides compatibility with Pika
versions lower than 1.0.0.
... | [
"def",
"connectionReady",
"(",
"self",
",",
"res",
"=",
"None",
")",
":",
"self",
".",
"_channel",
"=",
"yield",
"self",
".",
"_allocate_channel",
"(",
")",
"if",
"_pika_version",
"<",
"pkg_resources",
".",
"parse_version",
"(",
"\"1.0.0b1\"",
")",
":",
"e... | Callback invoked when the AMQP connection is ready (when self.ready fires).
This API is not meant for users.
Args:
res: This is an unused argument that provides compatibility with Pika
versions lower than 1.0.0. | [
"Callback",
"invoked",
"when",
"the",
"AMQP",
"connection",
"is",
"ready",
"(",
"when",
"self",
".",
"ready",
"fires",
")",
"."
] | train | https://github.com/fedora-infra/fedora-messaging/blob/be3e88534e2b15d579bcd24f9c4b7e795cb7e0b7/fedora_messaging/twisted/protocol.py#L148-L169 |
fedora-infra/fedora-messaging | fedora_messaging/twisted/protocol.py | FedoraMessagingProtocolV2._read | def _read(self, queue_object, consumer):
"""
The loop that reads from the message queue and calls the consumer callback
wrapper.
Serialized Processing
---------------------
This loop processes messages serially. This is because a second
``queue_object.get()`` ope... | python | def _read(self, queue_object, consumer):
"""
The loop that reads from the message queue and calls the consumer callback
wrapper.
Serialized Processing
---------------------
This loop processes messages serially. This is because a second
``queue_object.get()`` ope... | [
"def",
"_read",
"(",
"self",
",",
"queue_object",
",",
"consumer",
")",
":",
"while",
"consumer",
".",
"_running",
":",
"try",
":",
"deferred_get",
"=",
"queue_object",
".",
"get",
"(",
")",
"_add_timeout",
"(",
"deferred_get",
",",
"1",
")",
"channel",
... | The loop that reads from the message queue and calls the consumer callback
wrapper.
Serialized Processing
---------------------
This loop processes messages serially. This is because a second
``queue_object.get()`` operation can only occur after the Deferred from
``self.... | [
"The",
"loop",
"that",
"reads",
"from",
"the",
"message",
"queue",
"and",
"calls",
"the",
"consumer",
"callback",
"wrapper",
"."
] | train | https://github.com/fedora-infra/fedora-messaging/blob/be3e88534e2b15d579bcd24f9c4b7e795cb7e0b7/fedora_messaging/twisted/protocol.py#L172-L277 |
fedora-infra/fedora-messaging | fedora_messaging/twisted/protocol.py | FedoraMessagingProtocolV2.publish | def publish(self, message, exchange):
"""
Publish a :class:`fedora_messaging.message.Message` to an `exchange`_
on the message broker.
Args:
message (message.Message): The message to publish.
exchange (str): The name of the AMQP exchange to publish to
Ra... | python | def publish(self, message, exchange):
"""
Publish a :class:`fedora_messaging.message.Message` to an `exchange`_
on the message broker.
Args:
message (message.Message): The message to publish.
exchange (str): The name of the AMQP exchange to publish to
Ra... | [
"def",
"publish",
"(",
"self",
",",
"message",
",",
"exchange",
")",
":",
"message",
".",
"validate",
"(",
")",
"try",
":",
"yield",
"self",
".",
"_channel",
".",
"basic_publish",
"(",
"exchange",
"=",
"exchange",
",",
"routing_key",
"=",
"message",
".",... | Publish a :class:`fedora_messaging.message.Message` to an `exchange`_
on the message broker.
Args:
message (message.Message): The message to publish.
exchange (str): The name of the AMQP exchange to publish to
Raises:
NoFreeChannels: If there are no availabl... | [
"Publish",
"a",
":",
"class",
":",
"fedora_messaging",
".",
"message",
".",
"Message",
"to",
"an",
"exchange",
"_",
"on",
"the",
"message",
"broker",
"."
] | train | https://github.com/fedora-infra/fedora-messaging/blob/be3e88534e2b15d579bcd24f9c4b7e795cb7e0b7/fedora_messaging/twisted/protocol.py#L280-L315 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.