hexsha
stringlengths
40
40
repo
stringlengths
7
114
path
stringlengths
4
124
license
listlengths
1
9
language
stringclasses
1 value
identifier
stringlengths
1
71
return_type
stringlengths
1
749
original_string
stringlengths
76
22.7k
original_docstring
stringlengths
16
7.61k
docstring
stringlengths
16
2.47k
docstring_tokens
listlengths
6
477
code
stringlengths
14
10.2k
code_tokens
listlengths
6
996
short_docstring
stringlengths
2
644
short_docstring_tokens
listlengths
1
116
comment
listlengths
1
89
parameters
listlengths
0
64
docstring_params
dict
6e94713c3f255e0b89163494beccb3cf534bf1de
SectorLabs/django-localized-fields
localized_fields/fields/integer_field.py
[ "MIT" ]
Python
to_python
LocalizedIntegerValue
def to_python( self, value: Union[Dict[str, int], int, None] ) -> LocalizedIntegerValue: """Converts the value from a database value into a Python value.""" db_value = super().to_python(value) return self._convert_localized_value(db_value)
Converts the value from a database value into a Python value.
Converts the value from a database value into a Python value.
[ "Converts", "the", "value", "from", "a", "database", "value", "into", "a", "Python", "value", "." ]
def to_python( self, value: Union[Dict[str, int], int, None] ) -> LocalizedIntegerValue: db_value = super().to_python(value) return self._convert_localized_value(db_value)
[ "def", "to_python", "(", "self", ",", "value", ":", "Union", "[", "Dict", "[", "str", ",", "int", "]", ",", "int", ",", "None", "]", ")", "->", "LocalizedIntegerValue", ":", "db_value", "=", "super", "(", ")", ".", "to_python", "(", "value", ")", "...
Converts the value from a database value into a Python value.
[ "Converts", "the", "value", "from", "a", "database", "value", "into", "a", "Python", "value", "." ]
[ "\"\"\"Converts the value from a database value into a Python value.\"\"\"" ]
[ { "param": "self", "type": null }, { "param": "value", "type": "Union[Dict[str, int], int, None]" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "value", "type": "Union[Dict[str, int], int, None]", "docstring": nu...
95e926c66a87ad7899bf20ffee7c3106c435ec99
andhus/data-mining-algorithms
python/data_mining/primes.py
[ "MIT" ]
Python
first
<not_specific>
def first(n): """Returns first n prime numbers. Args: n (int): the number of prime numbers ot return. Returns: ([int]): List of prime numbers. Source: Based on: https://www.daniweb.com/programming/software-development/threads/233730/to-find-first-n-prime-numbers """ if...
Returns first n prime numbers. Args: n (int): the number of prime numbers ot return. Returns: ([int]): List of prime numbers. Source: Based on: https://www.daniweb.com/programming/software-development/threads/233730/to-find-first-n-prime-numbers
Returns first n prime numbers.
[ "Returns", "first", "n", "prime", "numbers", "." ]
def first(n): if n > 10000: raise ValueError("n must be smaller than 10,000") if n == 0: return [] ten_thousandth_prime = 104729 primes = [] for a in xrange(1, ten_thousandth_prime): for b in range(2, a): if a % b == 0: break else: ...
[ "def", "first", "(", "n", ")", ":", "if", "n", ">", "10000", ":", "raise", "ValueError", "(", "\"n must be smaller than 10,000\"", ")", "if", "n", "==", "0", ":", "return", "[", "]", "ten_thousandth_prime", "=", "104729", "primes", "=", "[", "]", "for", ...
Returns first n prime numbers.
[ "Returns", "first", "n", "prime", "numbers", "." ]
[ "\"\"\"Returns first n prime numbers.\n\n Args:\n n (int): the number of prime numbers ot return.\n\n Returns:\n ([int]): List of prime numbers.\n\n Source: Based on:\n https://www.daniweb.com/programming/software-development/threads/233730/to-find-first-n-prime-numbers\n \"\"\"", ...
[ { "param": "n", "type": null } ]
{ "returns": [ { "docstring": "List of prime numbers.", "docstring_tokens": [ "List", "of", "prime", "numbers", "." ], "type": "([int])" } ], "raises": [], "params": [ { "identifier": "n", "type": null, "docstring": "t...
442718c6d61afee571c4ba3172141a96ed57adf7
andhus/data-mining-algorithms
python/scripts/homework_1/benchmark.py
[ "MIT" ]
Python
run_timing_job
<not_specific>
def run_timing_job( n_docs, n_rows, minhash_size, lsh_nbands ): """Times the execution of computing Min Hashes and running LSH. """ job_name = 'ndocs={}_nrows={}_minhash_size={}_lsh_nbands={}'.format( n_docs, n_rows, minhash_size, lsh_nbands ) job_path...
Times the execution of computing Min Hashes and running LSH.
Times the execution of computing Min Hashes and running LSH.
[ "Times", "the", "execution", "of", "computing", "Min", "Hashes", "and", "running", "LSH", "." ]
def run_timing_job( n_docs, n_rows, minhash_size, lsh_nbands ): job_name = 'ndocs={}_nrows={}_minhash_size={}_lsh_nbands={}'.format( n_docs, n_rows, minhash_size, lsh_nbands ) job_path = os.path.join(OUTPUT_PATH, job_name) mkdirp(job_path) result_path ...
[ "def", "run_timing_job", "(", "n_docs", ",", "n_rows", ",", "minhash_size", ",", "lsh_nbands", ")", ":", "job_name", "=", "'ndocs={}_nrows={}_minhash_size={}_lsh_nbands={}'", ".", "format", "(", "n_docs", ",", "n_rows", ",", "minhash_size", ",", "lsh_nbands", ")", ...
Times the execution of computing Min Hashes and running LSH.
[ "Times", "the", "execution", "of", "computing", "Min", "Hashes", "and", "running", "LSH", "." ]
[ "\"\"\"Times the execution of computing Min Hashes and running LSH.\n \"\"\"", "\"\"\"Pythons default hash(str) returns value in range\n [-(sys.maxint + 1):sys.maxint]\n \"\"\"" ]
[ { "param": "n_docs", "type": null }, { "param": "n_rows", "type": null }, { "param": "minhash_size", "type": null }, { "param": "lsh_nbands", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "n_docs", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "n_rows", "type": null, "docstring": null, "docstring_tokens...
442718c6d61afee571c4ba3172141a96ed57adf7
andhus/data-mining-algorithms
python/scripts/homework_1/benchmark.py
[ "MIT" ]
Python
measure_lsh_recall
<not_specific>
def measure_lsh_recall( n_docs=512, n_rows=1000003, minhash_size=100, lsh_nbands=20, jsim_threshold=0.7 ): """Computes the recall of the LSH algorithm by comparing to "brute force" calculation""" job_name = 'ndocs={}_nrows={}_minhash_size={}_lsh_nbands={}'.format( n_docs, ...
Computes the recall of the LSH algorithm by comparing to "brute force" calculation
Computes the recall of the LSH algorithm by comparing to "brute force" calculation
[ "Computes", "the", "recall", "of", "the", "LSH", "algorithm", "by", "comparing", "to", "\"", "brute", "force", "\"", "calculation" ]
def measure_lsh_recall( n_docs=512, n_rows=1000003, minhash_size=100, lsh_nbands=20, jsim_threshold=0.7 ): job_name = 'ndocs={}_nrows={}_minhash_size={}_lsh_nbands={}'.format( n_docs, n_rows, minhash_size, lsh_nbands ) job_path = os.path.join(OUTPUT_PATH, ...
[ "def", "measure_lsh_recall", "(", "n_docs", "=", "512", ",", "n_rows", "=", "1000003", ",", "minhash_size", "=", "100", ",", "lsh_nbands", "=", "20", ",", "jsim_threshold", "=", "0.7", ")", ":", "job_name", "=", "'ndocs={}_nrows={}_minhash_size={}_lsh_nbands={}'",...
Computes the recall of the LSH algorithm by comparing to "brute force" calculation
[ "Computes", "the", "recall", "of", "the", "LSH", "algorithm", "by", "comparing", "to", "\"", "brute", "force", "\"", "calculation" ]
[ "\"\"\"Computes the recall of the LSH algorithm by comparing to \"brute force\"\n calculation\"\"\"" ]
[ { "param": "n_docs", "type": null }, { "param": "n_rows", "type": null }, { "param": "minhash_size", "type": null }, { "param": "lsh_nbands", "type": null }, { "param": "jsim_threshold", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "n_docs", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "n_rows", "type": null, "docstring": null, "docstring_tokens...
3a57b8aadfe1279bf9df23707bccb2d8991a99b3
andhus/data-mining-algorithms
python/data_mining/graph.py
[ "MIT" ]
Python
binomial
<not_specific>
def binomial(n, k): """Computes the binomial coefficient "n over k". """ if k == n: return 1 if k == 1: return n if k > n: return 0 return math.factorial(n) // ( math.factorial(k) * math.factorial(n - k) )
Computes the binomial coefficient "n over k".
Computes the binomial coefficient "n over k".
[ "Computes", "the", "binomial", "coefficient", "\"", "n", "over", "k", "\"", "." ]
def binomial(n, k): if k == n: return 1 if k == 1: return n if k > n: return 0 return math.factorial(n) // ( math.factorial(k) * math.factorial(n - k) )
[ "def", "binomial", "(", "n", ",", "k", ")", ":", "if", "k", "==", "n", ":", "return", "1", "if", "k", "==", "1", ":", "return", "n", "if", "k", ">", "n", ":", "return", "0", "return", "math", ".", "factorial", "(", "n", ")", "//", "(", "mat...
Computes the binomial coefficient "n over k".
[ "Computes", "the", "binomial", "coefficient", "\"", "n", "over", "k", "\"", "." ]
[ "\"\"\"Computes the binomial coefficient \"n over k\".\n \"\"\"" ]
[ { "param": "n", "type": null }, { "param": "k", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "n", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "k", "type": null, "docstring": null, "docstring_tokens": [], ...
3a57b8aadfe1279bf9df23707bccb2d8991a99b3
andhus/data-mining-algorithms
python/data_mining/graph.py
[ "MIT" ]
Python
put_edge
null
def put_edge(self, edge): """Adds the edge to the graph. Args: edge ((int, int)): edge between nodes edge[0] and edge[1]. """ u, v = edge if v in self._node_neighbors[u]: raise ValueError('edge {} already exists'.format(edge)) self._node_neighbors...
Adds the edge to the graph. Args: edge ((int, int)): edge between nodes edge[0] and edge[1].
Adds the edge to the graph.
[ "Adds", "the", "edge", "to", "the", "graph", "." ]
def put_edge(self, edge): u, v = edge if v in self._node_neighbors[u]: raise ValueError('edge {} already exists'.format(edge)) self._node_neighbors[u].add(v) self._node_neighbors[v].add(u) self.edges.add(edge)
[ "def", "put_edge", "(", "self", ",", "edge", ")", ":", "u", ",", "v", "=", "edge", "if", "v", "in", "self", ".", "_node_neighbors", "[", "u", "]", ":", "raise", "ValueError", "(", "'edge {} already exists'", ".", "format", "(", "edge", ")", ")", "sel...
Adds the edge to the graph.
[ "Adds", "the", "edge", "to", "the", "graph", "." ]
[ "\"\"\"Adds the edge to the graph.\n\n Args:\n edge ((int, int)): edge between nodes edge[0] and edge[1].\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "edge", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "edge", "type": null, "docstring": null, "docstring_tokens": [...
3a57b8aadfe1279bf9df23707bccb2d8991a99b3
andhus/data-mining-algorithms
python/data_mining/graph.py
[ "MIT" ]
Python
pop_edge
null
def pop_edge(self, edge, remove_disconnected_nodes=False): """Removes the edge from the graph. Args: edge ((int, int)): edge between nodes edge[0] and edge[1]. """ if edge not in self.edges: raise ValueError('edge {} does not exist'.format(edge)) u, v = ...
Removes the edge from the graph. Args: edge ((int, int)): edge between nodes edge[0] and edge[1].
Removes the edge from the graph.
[ "Removes", "the", "edge", "from", "the", "graph", "." ]
def pop_edge(self, edge, remove_disconnected_nodes=False): if edge not in self.edges: raise ValueError('edge {} does not exist'.format(edge)) u, v = edge self._node_neighbors[u].remove(v) self._node_neighbors[v].remove(u) self.edges.remove(edge) if remove_disc...
[ "def", "pop_edge", "(", "self", ",", "edge", ",", "remove_disconnected_nodes", "=", "False", ")", ":", "if", "edge", "not", "in", "self", ".", "edges", ":", "raise", "ValueError", "(", "'edge {} does not exist'", ".", "format", "(", "edge", ")", ")", "u", ...
Removes the edge from the graph.
[ "Removes", "the", "edge", "from", "the", "graph", "." ]
[ "\"\"\"Removes the edge from the graph.\n\n Args:\n edge ((int, int)): edge between nodes edge[0] and edge[1].\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "edge", "type": null }, { "param": "remove_disconnected_nodes", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "edge", "type": null, "docstring": null, "docstring_tokens": [...
3a57b8aadfe1279bf9df23707bccb2d8991a99b3
andhus/data-mining-algorithms
python/data_mining/graph.py
[ "MIT" ]
Python
put_node
null
def put_node(self, node): """Adds a node to the graph. Args: node (int): the node (index) to add. """ if node in self._node_neighbors: raise ValueError('node {} exists'.format(node)) _ = self._node_neighbors[node]
Adds a node to the graph. Args: node (int): the node (index) to add.
Adds a node to the graph.
[ "Adds", "a", "node", "to", "the", "graph", "." ]
def put_node(self, node): if node in self._node_neighbors: raise ValueError('node {} exists'.format(node)) _ = self._node_neighbors[node]
[ "def", "put_node", "(", "self", ",", "node", ")", ":", "if", "node", "in", "self", ".", "_node_neighbors", ":", "raise", "ValueError", "(", "'node {} exists'", ".", "format", "(", "node", ")", ")", "_", "=", "self", ".", "_node_neighbors", "[", "node", ...
Adds a node to the graph.
[ "Adds", "a", "node", "to", "the", "graph", "." ]
[ "\"\"\"Adds a node to the graph.\n\n Args:\n node (int): the node (index) to add.\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "node", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "node", "type": null, "docstring": "the node (index) to add.", ...
3a57b8aadfe1279bf9df23707bccb2d8991a99b3
andhus/data-mining-algorithms
python/data_mining/graph.py
[ "MIT" ]
Python
pop_node
null
def pop_node(self, node): """Removes the node from the graph. Args: node (int): the node (index) to remove. """ if node not in self._node_neighbors: raise ValueError('node: {} does not exist'.format(node)) for neigh in self._node_neighbors[node]: ...
Removes the node from the graph. Args: node (int): the node (index) to remove.
Removes the node from the graph.
[ "Removes", "the", "node", "from", "the", "graph", "." ]
def pop_node(self, node): if node not in self._node_neighbors: raise ValueError('node: {} does not exist'.format(node)) for neigh in self._node_neighbors[node]: self._node_neighbors[neigh].remove(node) del self._node_neighbors[node]
[ "def", "pop_node", "(", "self", ",", "node", ")", ":", "if", "node", "not", "in", "self", ".", "_node_neighbors", ":", "raise", "ValueError", "(", "'node: {} does not exist'", ".", "format", "(", "node", ")", ")", "for", "neigh", "in", "self", ".", "_nod...
Removes the node from the graph.
[ "Removes", "the", "node", "from", "the", "graph", "." ]
[ "\"\"\"Removes the node from the graph.\n\n Args:\n node (int): the node (index) to remove.\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "node", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "node", "type": null, "docstring": "the node (index) to remove.", ...
3a57b8aadfe1279bf9df23707bccb2d8991a99b3
andhus/data-mining-algorithms
python/data_mining/graph.py
[ "MIT" ]
Python
put
null
def put(self, edge): """Process next item (graph edge) in the stream. Args: edge ((int, int)): an _added edge_ connecting nodes edge[0] and edge[1]. Combination of main loop and `SampleEdge` function in [1]: Algorithm 1. """ self.t += 1 if self.t <= self.siz...
Process next item (graph edge) in the stream. Args: edge ((int, int)): an _added edge_ connecting nodes edge[0] and edge[1]. Combination of main loop and `SampleEdge` function in [1]: Algorithm 1.
Process next item (graph edge) in the stream.
[ "Process", "next", "item", "(", "graph", "edge", ")", "in", "the", "stream", "." ]
def put(self, edge): self.t += 1 if self.t <= self.size: self.reservoir.put_edge(edge) self.update_counters(self.ADD, edge) elif with_probability(self.size / self.t): remove_edge = random.sample(self.reservoir.edges, 1)[0] self.reservoir.pop_edge(r...
[ "def", "put", "(", "self", ",", "edge", ")", ":", "self", ".", "t", "+=", "1", "if", "self", ".", "t", "<=", "self", ".", "size", ":", "self", ".", "reservoir", ".", "put_edge", "(", "edge", ")", "self", ".", "update_counters", "(", "self", ".", ...
Process next item (graph edge) in the stream.
[ "Process", "next", "item", "(", "graph", "edge", ")", "in", "the", "stream", "." ]
[ "\"\"\"Process next item (graph edge) in the stream.\n\n Args:\n edge ((int, int)): an _added edge_ connecting nodes edge[0] and edge[1].\n\n Combination of main loop and `SampleEdge` function in [1]: Algorithm 1.\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "edge", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "edge", "type": null, "docstring": "an _added edge_ connecting nodes...
3a57b8aadfe1279bf9df23707bccb2d8991a99b3
andhus/data-mining-algorithms
python/data_mining/graph.py
[ "MIT" ]
Python
put
null
def put(self, edge): """Process next item (graph edge) in the stream. Args: edge ((int, int)): an _added edge_ connecting nodes edge[0] and edge[1]. Combination of main loop and `SampleEdge` function in [1]: Algorithm 1. """ self.t += 1 self.update_counters(...
Process next item (graph edge) in the stream. Args: edge ((int, int)): an _added edge_ connecting nodes edge[0] and edge[1]. Combination of main loop and `SampleEdge` function in [1]: Algorithm 1.
Process next item (graph edge) in the stream.
[ "Process", "next", "item", "(", "graph", "edge", ")", "in", "the", "stream", "." ]
def put(self, edge): self.t += 1 self.update_counters(self.ADD, edge) if self.t <= self.size: self.reservoir.put_edge(edge) elif with_probability(self.size / self.t): remove_edge = random.sample(self.reservoir.edges, 1)[0] self.reservoir.pop_edge(remov...
[ "def", "put", "(", "self", ",", "edge", ")", ":", "self", ".", "t", "+=", "1", "self", ".", "update_counters", "(", "self", ".", "ADD", ",", "edge", ")", "if", "self", ".", "t", "<=", "self", ".", "size", ":", "self", ".", "reservoir", ".", "pu...
Process next item (graph edge) in the stream.
[ "Process", "next", "item", "(", "graph", "edge", ")", "in", "the", "stream", "." ]
[ "\"\"\"Process next item (graph edge) in the stream.\n\n Args:\n edge ((int, int)): an _added edge_ connecting nodes edge[0] and edge[1].\n\n Combination of main loop and `SampleEdge` function in [1]: Algorithm 1.\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "edge", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "edge", "type": null, "docstring": "an _added edge_ connecting nodes...
3a57b8aadfe1279bf9df23707bccb2d8991a99b3
andhus/data-mining-algorithms
python/data_mining/graph.py
[ "MIT" ]
Python
put
null
def put(self, (operation, edge)): """Process next item (graph edge) in the stream. Args: operation (int): Integer in {1, -1} for ADD, REMOVE respectively. edge ((int, int)): an _added edge_ connecting nodes edge[0] and edge[1]. Combination of main loop and `SampleEdge` ...
Process next item (graph edge) in the stream. Args: operation (int): Integer in {1, -1} for ADD, REMOVE respectively. edge ((int, int)): an _added edge_ connecting nodes edge[0] and edge[1]. Combination of main loop and `SampleEdge` function in [1]: Algorithm 1.
Process next item (graph edge) in the stream.
[ "Process", "next", "item", "(", "graph", "edge", ")", "in", "the", "stream", "." ]
def put(self, (operation, edge)): self.t += 1 self.s += operation if operation == self.ADD: if self.sample_edge(edge): self.update_counters(self.ADD, edge) elif edge in self.reservoir: self.update_counters(self.REMOVE, edge) self.reserv...
[ "def", "put", "(", "self", ",", "(", "operation", ",", "edge", ")", ")", ":", "self", ".", "t", "+=", "1", "self", ".", "s", "+=", "operation", "if", "operation", "==", "self", ".", "ADD", ":", "if", "self", ".", "sample_edge", "(", "edge", ")", ...
Process next item (graph edge) in the stream.
[ "Process", "next", "item", "(", "graph", "edge", ")", "in", "the", "stream", "." ]
[ "\"\"\"Process next item (graph edge) in the stream.\n\n Args:\n operation (int): Integer in {1, -1} for ADD, REMOVE respectively.\n edge ((int, int)): an _added edge_ connecting nodes edge[0] and edge[1].\n\n Combination of main loop and `SampleEdge` function in [1]: Algorithm 1...
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [ { "identifier": "operation", "type": null, "docstring": "I...
76e8d34c3ccdd1e39dce2c4138b163cdeb20955e
andhus/data-mining-algorithms
python/data_mining/script_utils.py
[ "MIT" ]
Python
mkdirp
null
def mkdirp(path): """Recursively creates directories to the specified path""" if os.path.exists(path): if not os.path.isdir(path): raise IOError('{} exists and is not a directory'.format(path)) else: os.makedirs(path)
Recursively creates directories to the specified path
Recursively creates directories to the specified path
[ "Recursively", "creates", "directories", "to", "the", "specified", "path" ]
def mkdirp(path): if os.path.exists(path): if not os.path.isdir(path): raise IOError('{} exists and is not a directory'.format(path)) else: os.makedirs(path)
[ "def", "mkdirp", "(", "path", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "raise", "IOError", "(", "'{} exists and is not a directory'", ".", "format", ...
Recursively creates directories to the specified path
[ "Recursively", "creates", "directories", "to", "the", "specified", "path" ]
[ "\"\"\"Recursively creates directories to the specified path\"\"\"" ]
[ { "param": "path", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "path", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
135ac0f900a3cb26ee762420e58224e4f5ac06c5
zs-liu/GOC-VRPTW-MAA
PGA/route.py
[ "MIT" ]
Python
refresh_state
null
def refresh_state(self, reset_window=True): """ refresh state of this route, i.e. recalculate all punish, cost and other parameters if the sequence and punish parameter of this route hasn't been changed, this method shouldn't be called :param reset_window: if time window is reset to the ...
refresh state of this route, i.e. recalculate all punish, cost and other parameters if the sequence and punish parameter of this route hasn't been changed, this method shouldn't be called :param reset_window: if time window is reset to the last serve time after time window punish :retur...
refresh state of this route, i.e. recalculate all punish, cost and other parameters if the sequence and punish parameter of this route hasn't been changed, this method shouldn't be called
[ "refresh", "state", "of", "this", "route", "i", ".", "e", ".", "recalculate", "all", "punish", "cost", "and", "other", "parameters", "if", "the", "sequence", "and", "punish", "parameter", "of", "this", "route", "hasn", "'", "t", "been", "changed", "this", ...
def refresh_state(self, reset_window=True): self.start_time = depot_open_time self.cost = 0 self.window_punish, self.capacity_punish, self.weight_punish, self.volume_punish = 0, 0, 0, 0 self.capacity_remain = driving_range self.capacity_waste = 0 self.served_w, self.serve...
[ "def", "refresh_state", "(", "self", ",", "reset_window", "=", "True", ")", ":", "self", ".", "start_time", "=", "depot_open_time", "self", ".", "cost", "=", "0", "self", ".", "window_punish", ",", "self", ".", "capacity_punish", ",", "self", ".", "weight_...
refresh state of this route, i.e.
[ "refresh", "state", "of", "this", "route", "i", ".", "e", "." ]
[ "\"\"\"\n refresh state of this route, i.e. recalculate all punish, cost and other parameters\n if the sequence and punish parameter of this route hasn't been changed, this method shouldn't be called\n :param reset_window: if time window is reset to the last serve time after time window punish\...
[ { "param": "self", "type": null }, { "param": "reset_window", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": null } ], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null ...
135ac0f900a3cb26ee762420e58224e4f5ac06c5
zs-liu/GOC-VRPTW-MAA
PGA/route.py
[ "MIT" ]
Python
has_customer
<not_specific>
def has_customer(self): """ get if this route has any customer (if none, this route absolutely needs to be removed) :return: whether this route has any customer """ for node in self.sequence: if node <= custom_number: return True return False
get if this route has any customer (if none, this route absolutely needs to be removed) :return: whether this route has any customer
get if this route has any customer (if none, this route absolutely needs to be removed)
[ "get", "if", "this", "route", "has", "any", "customer", "(", "if", "none", "this", "route", "absolutely", "needs", "to", "be", "removed", ")" ]
def has_customer(self): for node in self.sequence: if node <= custom_number: return True return False
[ "def", "has_customer", "(", "self", ")", ":", "for", "node", "in", "self", ".", "sequence", ":", "if", "node", "<=", "custom_number", ":", "return", "True", "return", "False" ]
get if this route has any customer (if none, this route absolutely needs to be removed)
[ "get", "if", "this", "route", "has", "any", "customer", "(", "if", "none", "this", "route", "absolutely", "needs", "to", "be", "removed", ")" ]
[ "\"\"\"\n get if this route has any customer (if none, this route absolutely needs to be removed)\n :return: whether this route has any customer\n \"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [ { "docstring": "whether this route has any customer", "docstring_tokens": [ "whether", "this", "route", "has", "any", "customer" ], "type": null } ], "raises": [], "params": [ { "identifier": "self", "...
135ac0f900a3cb26ee762420e58224e4f5ac06c5
zs-liu/GOC-VRPTW-MAA
PGA/route.py
[ "MIT" ]
Python
split_mutate
<not_specific>
def split_mutate(self, p=0.618): """ split this route into two routes :param p: the probability of put node into first route :return: route 1 and route 2 from this route """ sequence1 = [] sequence2 = [] for node in self.sequence: if random.ran...
split this route into two routes :param p: the probability of put node into first route :return: route 1 and route 2 from this route
split this route into two routes
[ "split", "this", "route", "into", "two", "routes" ]
def split_mutate(self, p=0.618): sequence1 = [] sequence2 = [] for node in self.sequence: if random.random() < p: sequence1.append(node) else: sequence2.append(node) route1 = Route(sequence=sequence1, g_map=self.g_map, punish=self.p...
[ "def", "split_mutate", "(", "self", ",", "p", "=", "0.618", ")", ":", "sequence1", "=", "[", "]", "sequence2", "=", "[", "]", "for", "node", "in", "self", ".", "sequence", ":", "if", "random", ".", "random", "(", ")", "<", "p", ":", "sequence1", ...
split this route into two routes
[ "split", "this", "route", "into", "two", "routes" ]
[ "\"\"\"\n split this route into two routes\n :param p: the probability of put node into first route\n :return: route 1 and route 2 from this route\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "p", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": null } ], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null ...
135ac0f900a3cb26ee762420e58224e4f5ac06c5
zs-liu/GOC-VRPTW-MAA
PGA/route.py
[ "MIT" ]
Python
delete_mutate
null
def delete_mutate(self): """ delete a station in this route if not increase punish :return: None """ idx = 0 while idx < len(self.sequence): node = self.sequence[idx] if node > custom_number: new_sequence = self.sequence.copy() ...
delete a station in this route if not increase punish :return: None
delete a station in this route if not increase punish
[ "delete", "a", "station", "in", "this", "route", "if", "not", "increase", "punish" ]
def delete_mutate(self): idx = 0 while idx < len(self.sequence): node = self.sequence[idx] if node > custom_number: new_sequence = self.sequence.copy() new_sequence.pop(idx) new_route = Route(g_map=self.g_map, punish=self.punish, se...
[ "def", "delete_mutate", "(", "self", ")", ":", "idx", "=", "0", "while", "idx", "<", "len", "(", "self", ".", "sequence", ")", ":", "node", "=", "self", ".", "sequence", "[", "idx", "]", "if", "node", ">", "custom_number", ":", "new_sequence", "=", ...
delete a station in this route if not increase punish
[ "delete", "a", "station", "in", "this", "route", "if", "not", "increase", "punish" ]
[ "\"\"\"\n delete a station in this route if not increase punish\n :return: None\n \"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": null } ], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null ...
135ac0f900a3cb26ee762420e58224e4f5ac06c5
zs-liu/GOC-VRPTW-MAA
PGA/route.py
[ "MIT" ]
Python
random_reverse_mutate
null
def random_reverse_mutate(self): """ randomly swap two node in this route :return: None """ copy_sequence = self.sequence.copy() copy_cost = self.cost pos1 = random.randint(0, len(self.sequence) - 1) pos2 = random.randint(0, len(self.sequence) - 1) ...
randomly swap two node in this route :return: None
randomly swap two node in this route
[ "randomly", "swap", "two", "node", "in", "this", "route" ]
def random_reverse_mutate(self): copy_sequence = self.sequence.copy() copy_cost = self.cost pos1 = random.randint(0, len(self.sequence) - 1) pos2 = random.randint(0, len(self.sequence) - 1) self.sequence[pos1], self.sequence[pos2] = self.sequence[pos2], self.sequence[pos1] ...
[ "def", "random_reverse_mutate", "(", "self", ")", ":", "copy_sequence", "=", "self", ".", "sequence", ".", "copy", "(", ")", "copy_cost", "=", "self", ".", "cost", "pos1", "=", "random", ".", "randint", "(", "0", ",", "len", "(", "self", ".", "sequence...
randomly swap two node in this route
[ "randomly", "swap", "two", "node", "in", "this", "route" ]
[ "\"\"\"\n randomly swap two node in this route\n :return: None\n \"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": null } ], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null ...
135ac0f900a3cb26ee762420e58224e4f5ac06c5
zs-liu/GOC-VRPTW-MAA
PGA/route.py
[ "MIT" ]
Python
deepcopy
<not_specific>
def deepcopy(self): """ return a deep copy of itself, copy all except g_map :return: copy route """ new_route = Route(sequence=self.sequence.copy(), g_map=self.g_map, punish=self.punish, refresh_im=False) new_route.start_time = self.start_time new_route.cost = sel...
return a deep copy of itself, copy all except g_map :return: copy route
return a deep copy of itself, copy all except g_map
[ "return", "a", "deep", "copy", "of", "itself", "copy", "all", "except", "g_map" ]
def deepcopy(self): new_route = Route(sequence=self.sequence.copy(), g_map=self.g_map, punish=self.punish, refresh_im=False) new_route.start_time = self.start_time new_route.cost = self.cost new_route.window_punish, new_route.capacity_punish, new_route.weight_punish, new_route.volume_pun...
[ "def", "deepcopy", "(", "self", ")", ":", "new_route", "=", "Route", "(", "sequence", "=", "self", ".", "sequence", ".", "copy", "(", ")", ",", "g_map", "=", "self", ".", "g_map", ",", "punish", "=", "self", ".", "punish", ",", "refresh_im", "=", "...
return a deep copy of itself, copy all except g_map
[ "return", "a", "deep", "copy", "of", "itself", "copy", "all", "except", "g_map" ]
[ "\"\"\"\n return a deep copy of itself, copy all except g_map\n :return: copy route\n \"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": null } ], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null ...
135ac0f900a3cb26ee762420e58224e4f5ac06c5
zs-liu/GOC-VRPTW-MAA
PGA/route.py
[ "MIT" ]
Python
is_equal
<not_specific>
def is_equal(self, route): """ examine whether this route is equal to another route :param route: another route :return: True if equal """ if len(self.sequence) != len(route.sequence) or self.cost != route.cost: return False for node1, node2 in zip(sel...
examine whether this route is equal to another route :param route: another route :return: True if equal
examine whether this route is equal to another route
[ "examine", "whether", "this", "route", "is", "equal", "to", "another", "route" ]
def is_equal(self, route): if len(self.sequence) != len(route.sequence) or self.cost != route.cost: return False for node1, node2 in zip(self.sequence, route.sequence): if node1 != node2: return False return True
[ "def", "is_equal", "(", "self", ",", "route", ")", ":", "if", "len", "(", "self", ".", "sequence", ")", "!=", "len", "(", "route", ".", "sequence", ")", "or", "self", ".", "cost", "!=", "route", ".", "cost", ":", "return", "False", "for", "node1", ...
examine whether this route is equal to another route
[ "examine", "whether", "this", "route", "is", "equal", "to", "another", "route" ]
[ "\"\"\"\n examine whether this route is equal to another route\n :param route: another route\n :return: True if equal\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "route", "type": null } ]
{ "returns": [ { "docstring": "True if equal", "docstring_tokens": [ "True", "if", "equal" ], "type": null } ], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "de...
135ac0f900a3cb26ee762420e58224e4f5ac06c5
zs-liu/GOC-VRPTW-MAA
PGA/route.py
[ "MIT" ]
Python
try_insert
<not_specific>
def try_insert(self, node: int): """ try to insert a node into this route, ensure no extra punish :param node: the node to be inserted :return: cost change, if cannot insert will return huge """ old_cost = self.cost old_punish = self.get_total_punish() try...
try to insert a node into this route, ensure no extra punish :param node: the node to be inserted :return: cost change, if cannot insert will return huge
try to insert a node into this route, ensure no extra punish
[ "try", "to", "insert", "a", "node", "into", "this", "route", "ensure", "no", "extra", "punish" ]
def try_insert(self, node: int): old_cost = self.cost old_punish = self.get_total_punish() try_route_list = [] nearby_station = self.g_map.get_nearby_station(node) for insert_pos in range(0, len(self.sequence) + 1): try_sequence = self.sequence.copy() try_...
[ "def", "try_insert", "(", "self", ",", "node", ":", "int", ")", ":", "old_cost", "=", "self", ".", "cost", "old_punish", "=", "self", ".", "get_total_punish", "(", ")", "try_route_list", "=", "[", "]", "nearby_station", "=", "self", ".", "g_map", ".", ...
try to insert a node into this route, ensure no extra punish
[ "try", "to", "insert", "a", "node", "into", "this", "route", "ensure", "no", "extra", "punish" ]
[ "\"\"\"\n try to insert a node into this route, ensure no extra punish\n :param node: the node to be inserted\n :return: cost change, if cannot insert will return huge\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "node", "type": "int" } ]
{ "returns": [ { "docstring": "cost change, if cannot insert will return huge", "docstring_tokens": [ "cost", "change", "if", "cannot", "insert", "will", "return", "huge" ], "type": null } ], "raises": [], "params": ...
4f1568a667a93268361cb9c7c125b1e160201ed1
zs-liu/GOC-VRPTW-MAA
tools/global_map.py
[ "MIT" ]
Python
initialize
null
def initialize(self): """ set nearby station of every customer set 'nearby' customer of every customer :return: None """ # set nearby station of every customer, evaluated by distance for i in range(0, 1001): temp_station_d = self.distance_table['distan...
set nearby station of every customer set 'nearby' customer of every customer :return: None
set nearby station of every customer set 'nearby' customer of every customer
[ "set", "nearby", "station", "of", "every", "customer", "set", "'", "nearby", "'", "customer", "of", "every", "customer" ]
def initialize(self): for i in range(0, 1001): temp_station_d = self.distance_table['distance'][self.__get_index__(i, 1001):self.__get_index__(i, 1100)] self.nearby_station_list.append(np.argmin(np.array(temp_station_d)) + 1001) for i in range(1001, 1101): min_d = 999...
[ "def", "initialize", "(", "self", ")", ":", "for", "i", "in", "range", "(", "0", ",", "1001", ")", ":", "temp_station_d", "=", "self", ".", "distance_table", "[", "'distance'", "]", "[", "self", ".", "__get_index__", "(", "i", ",", "1001", ")", ":", ...
set nearby station of every customer set 'nearby' customer of every customer
[ "set", "nearby", "station", "of", "every", "customer", "set", "'", "nearby", "'", "customer", "of", "every", "customer" ]
[ "\"\"\"\n set nearby station of every customer\n set 'nearby' customer of every customer\n :return: None\n \"\"\"", "# set nearby station of every customer, evaluated by distance", "# set 'nearby' customer of every customer, evaluated by distance, demand and time window" ]
[ { "param": "self", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": null } ], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null ...
7d9533f768eb820425ba2a9aa322aab9bf01c810
zs-liu/GOC-VRPTW-MAA
PGA/nature.py
[ "MIT" ]
Python
operate
null
def operate(self): """ operate the nature, include rank, select, cross, mutate, new add, experience apply :return: None """ self.__ranking__() print('Ranking OK.', end='\t') bad_chromo_list = [] for chromo in self.chromo_list[int(self.reserve * len(self.ch...
operate the nature, include rank, select, cross, mutate, new add, experience apply :return: None
operate the nature, include rank, select, cross, mutate, new add, experience apply
[ "operate", "the", "nature", "include", "rank", "select", "cross", "mutate", "new", "add", "experience", "apply" ]
def operate(self): self.__ranking__() print('Ranking OK.', end='\t') bad_chromo_list = [] for chromo in self.chromo_list[int(self.reserve * len(self.chromo_list)):]: if random.random() < self.bad_reserve_p: bad_chromo_list.append(chromo) self.chromo_li...
[ "def", "operate", "(", "self", ")", ":", "self", ".", "__ranking__", "(", ")", "print", "(", "'Ranking OK.'", ",", "end", "=", "'\\t'", ")", "bad_chromo_list", "=", "[", "]", "for", "chromo", "in", "self", ".", "chromo_list", "[", "int", "(", "self", ...
operate the nature, include rank, select, cross, mutate, new add, experience apply
[ "operate", "the", "nature", "include", "rank", "select", "cross", "mutate", "new", "add", "experience", "apply" ]
[ "\"\"\"\n operate the nature, include rank, select, cross, mutate, new add, experience apply\n :return: None\n \"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": null } ], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null ...
97fd9bd5b68c5fc1d7cf9e1ad01d4bb8bcb92881
ematthews/ubnt_airos
ubnt_collectd.py
[ "MIT" ]
Python
fetch_info
<not_specific>
def fetch_info(host, username, password): """ Connect to UBNT device and request info. """ try: station = AirOS(host=host, username=username, password=password) except: collectd.error('ubnt_info plugin: Error connecting to %s' % (host)) try: status = station.status except: ...
Connect to UBNT device and request info.
Connect to UBNT device and request info.
[ "Connect", "to", "UBNT", "device", "and", "request", "info", "." ]
def fetch_info(host, username, password): try: station = AirOS(host=host, username=username, password=password) except: collectd.error('ubnt_info plugin: Error connecting to %s' % (host)) try: status = station.status except: collectd.error('ubnt_info plugin: Unable to rea...
[ "def", "fetch_info", "(", "host", ",", "username", ",", "password", ")", ":", "try", ":", "station", "=", "AirOS", "(", "host", "=", "host", ",", "username", "=", "username", ",", "password", "=", "password", ")", "except", ":", "collectd", ".", "error...
Connect to UBNT device and request info.
[ "Connect", "to", "UBNT", "device", "and", "request", "info", "." ]
[ "\"\"\" Connect to UBNT device and request info. \"\"\"" ]
[ { "param": "host", "type": null }, { "param": "username", "type": null }, { "param": "password", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "host", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "username", "type": null, "docstring": null, "docstring_tokens...
d6114cdfda0e739b972f376e99ae40e02b18cefa
simplyblock/sb-python-sdk
simply_block/simply_sign.py
[ "MIT" ]
Python
generate_signature
<not_specific>
def generate_signature(self, data): """ Generate Signature from the Request. Files are not used for generating Signatures :param data: Request Data :return: Signed Data """ self.data = data print(str(data)) self.signed_data = hmac.new( ...
Generate Signature from the Request. Files are not used for generating Signatures :param data: Request Data :return: Signed Data
Generate Signature from the Request. Files are not used for generating Signatures
[ "Generate", "Signature", "from", "the", "Request", ".", "Files", "are", "not", "used", "for", "generating", "Signatures" ]
def generate_signature(self, data): self.data = data print(str(data)) self.signed_data = hmac.new( self.private_key.encode('utf-8'), str(data).encode('utf-8'), digestmod=hashlib.sha384 ).hexdigest() return self.signed_data
[ "def", "generate_signature", "(", "self", ",", "data", ")", ":", "self", ".", "data", "=", "data", "print", "(", "str", "(", "data", ")", ")", "self", ".", "signed_data", "=", "hmac", ".", "new", "(", "self", ".", "private_key", ".", "encode", "(", ...
Generate Signature from the Request.
[ "Generate", "Signature", "from", "the", "Request", "." ]
[ "\"\"\"\n Generate Signature from the Request.\n Files are not used for generating Signatures\n :param data: Request Data\n :return: Signed Data\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "data", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": null } ], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null ...
c7131b8de51d54b97932513200c274c371829ad4
nrhodes91/configsnap
test_configsnap.py
[ "Apache-2.0" ]
Python
run_command
<not_specific>
def run_command(self, command): """Run a command and return output and exit code Args: param1 (str): the command to run Returns: list: stdout, stderr, exitcode """ command_proc = subprocess.Popen( command, stdout=subprocess.PIPE, stderr=subp...
Run a command and return output and exit code Args: param1 (str): the command to run Returns: list: stdout, stderr, exitcode
Run a command and return output and exit code
[ "Run", "a", "command", "and", "return", "output", "and", "exit", "code" ]
def run_command(self, command): command_proc = subprocess.Popen( command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, cwd=self.cwd) output = command_proc.stdout.read() error = command_proc.stderr.read() returncode = command_proc.wait() return TestResul...
[ "def", "run_command", "(", "self", ",", "command", ")", ":", "command_proc", "=", "subprocess", ".", "Popen", "(", "command", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ",", "shell", "=", "True", ",", ...
Run a command and return output and exit code
[ "Run", "a", "command", "and", "return", "output", "and", "exit", "code" ]
[ "\"\"\"Run a command and return output and exit code\n\n Args:\n param1 (str): the command to run\n\n Returns:\n list: stdout, stderr, exitcode\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "command", "type": null } ]
{ "returns": [ { "docstring": "stdout, stderr, exitcode", "docstring_tokens": [ "stdout", "stderr", "exitcode" ], "type": "list" } ], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_...
c7131b8de51d54b97932513200c274c371829ad4
nrhodes91/configsnap
test_configsnap.py
[ "Apache-2.0" ]
Python
func1_customdir
null
def func1_customdir(self): """Customised output directory; -d commandline option""" test = self.whoami() o = self.run_command('./configsnap -d /tmp/test -t functests') if o.retcode != 0: self.failtest(test, "Exit code non-zero") else: print("%s PASS Exit c...
Customised output directory; -d commandline option
Customised output directory; -d commandline option
[ "Customised", "output", "directory", ";", "-", "d", "commandline", "option" ]
def func1_customdir(self): test = self.whoami() o = self.run_command('./configsnap -d /tmp/test -t functests') if o.retcode != 0: self.failtest(test, "Exit code non-zero") else: print("%s PASS Exit code zero" % test) if not os.path.isdir('/tmp/test'): ...
[ "def", "func1_customdir", "(", "self", ")", ":", "test", "=", "self", ".", "whoami", "(", ")", "o", "=", "self", ".", "run_command", "(", "'./configsnap -d /tmp/test -t functests'", ")", "if", "o", ".", "retcode", "!=", "0", ":", "self", ".", "failtest", ...
Customised output directory; -d commandline option
[ "Customised", "output", "directory", ";", "-", "d", "commandline", "option" ]
[ "\"\"\"Customised output directory; -d commandline option\"\"\"", "# Check that custom dir was created and has content" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
c7131b8de51d54b97932513200c274c371829ad4
nrhodes91/configsnap
test_configsnap.py
[ "Apache-2.0" ]
Python
func2_customtag
null
def func2_customtag(self): """Customised tag; -t command line option""" test = self.whoami() o = self.run_command('./configsnap -t randomalternativetag') if o.retcode != 0: self.failtest(test, "Exit code non-zero") else: print("%s PASS Exit code zero" % te...
Customised tag; -t command line option
Customised tag; -t command line option
[ "Customised", "tag", ";", "-", "t", "command", "line", "option" ]
def func2_customtag(self): test = self.whoami() o = self.run_command('./configsnap -t randomalternativetag') if o.retcode != 0: self.failtest(test, "Exit code non-zero") else: print("%s PASS Exit code zero" % test) if os.path.exists('/root/randomalternativ...
[ "def", "func2_customtag", "(", "self", ")", ":", "test", "=", "self", ".", "whoami", "(", ")", "o", "=", "self", ".", "run_command", "(", "'./configsnap -t randomalternativetag'", ")", "if", "o", ".", "retcode", "!=", "0", ":", "self", ".", "failtest", "...
Customised tag; -t command line option
[ "Customised", "tag", ";", "-", "t", "command", "line", "option" ]
[ "\"\"\"Customised tag; -t command line option\"\"\"", "# Check tag name on dir" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
c7131b8de51d54b97932513200c274c371829ad4
nrhodes91/configsnap
test_configsnap.py
[ "Apache-2.0" ]
Python
func3_overwrite
null
def func3_overwrite(self): """Overwrite workdir; -w command line option""" test = self.whoami() for i in range(1, 4): o = self.run_command('./configsnap -t overwrite -p pre -w') if o.retcode != 0: self.failtest(test, "Exit code non-zero, run %i" % i) ...
Overwrite workdir; -w command line option
Overwrite workdir; -w command line option
[ "Overwrite", "workdir", ";", "-", "w", "command", "line", "option" ]
def func3_overwrite(self): test = self.whoami() for i in range(1, 4): o = self.run_command('./configsnap -t overwrite -p pre -w') if o.retcode != 0: self.failtest(test, "Exit code non-zero, run %i" % i) else: print("%s PASS Exit code ze...
[ "def", "func3_overwrite", "(", "self", ")", ":", "test", "=", "self", ".", "whoami", "(", ")", "for", "i", "in", "range", "(", "1", ",", "4", ")", ":", "o", "=", "self", ".", "run_command", "(", "'./configsnap -t overwrite -p pre -w'", ")", "if", "o", ...
Overwrite workdir; -w command line option
[ "Overwrite", "workdir", ";", "-", "w", "command", "line", "option" ]
[ "\"\"\"Overwrite workdir; -w command line option\"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
c7131b8de51d54b97932513200c274c371829ad4
nrhodes91/configsnap
test_configsnap.py
[ "Apache-2.0" ]
Python
func4_error_handling_nooverwrite
null
def func4_error_handling_nooverwrite(self): """Don't overwrite by default""" test = self.whoami() o = self.run_command('./configsnap -t nooverwrite -p pre') if o.retcode != 0: self.failtest(test, "Exit code non-zero, initial run") else: print("%s PASS Exit...
Don't overwrite by default
Don't overwrite by default
[ "Don", "'", "t", "overwrite", "by", "default" ]
def func4_error_handling_nooverwrite(self): test = self.whoami() o = self.run_command('./configsnap -t nooverwrite -p pre') if o.retcode != 0: self.failtest(test, "Exit code non-zero, initial run") else: print("%s PASS Exit code zero, initial run" % test) ...
[ "def", "func4_error_handling_nooverwrite", "(", "self", ")", ":", "test", "=", "self", ".", "whoami", "(", ")", "o", "=", "self", ".", "run_command", "(", "'./configsnap -t nooverwrite -p pre'", ")", "if", "o", ".", "retcode", "!=", "0", ":", "self", ".", ...
Don't overwrite by default
[ "Don", "'", "t", "overwrite", "by", "default" ]
[ "\"\"\"Don't overwrite by default\"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
9d01e2d3babb7ee58db54155f6521eb0c3c5ab4d
SubhrajitPrusty/ITER-api
iterapi/iterapi.py
[ "MIT" ]
Python
login
<not_specific>
def login(self): """ Logs in the student portal to retrieve cookies self.cookies -> request.Response.cookies """ payload = str({"username": self.regdno, "password": self.password, "MemberType": "S"}) response = requests.pos...
Logs in the student portal to retrieve cookies self.cookies -> request.Response.cookies
Logs in the student portal to retrieve cookies self.cookies -> request.Response.cookies
[ "Logs", "in", "the", "student", "portal", "to", "retrieve", "cookies", "self", ".", "cookies", "-", ">", "request", ".", "Response", ".", "cookies" ]
def login(self): payload = str({"username": self.regdno, "password": self.password, "MemberType": "S"}) response = requests.post( Student.LOGIN_URL, data=payload, headers=Student.HEADERS) if response.status_code ==...
[ "def", "login", "(", "self", ")", ":", "payload", "=", "str", "(", "{", "\"username\"", ":", "self", ".", "regdno", ",", "\"password\"", ":", "self", ".", "password", ",", "\"MemberType\"", ":", "\"S\"", "}", ")", "response", "=", "requests", ".", "pos...
Logs in the student portal to retrieve cookies self.cookies -> request.Response.cookies
[ "Logs", "in", "the", "student", "portal", "to", "retrieve", "cookies", "self", ".", "cookies", "-", ">", "request", ".", "Response", ".", "cookies" ]
[ "\"\"\"\n Logs in the student portal to retrieve cookies\n\n self.cookies -> request.Response.cookies\n\n \"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
9d01e2d3babb7ee58db54155f6521eb0c3c5ab4d
SubhrajitPrusty/ITER-api
iterapi/iterapi.py
[ "MIT" ]
Python
updatePassword
<not_specific>
def updatePassword(self, new_password): """ Updates the current password to the given password """ payload = { "newpassword": new_password, "confirmpassword": new_password } response = requests.post( Student.LOGIN_URL, dat...
Updates the current password to the given password
Updates the current password to the given password
[ "Updates", "the", "current", "password", "to", "the", "given", "password" ]
def updatePassword(self, new_password): payload = { "newpassword": new_password, "confirmpassword": new_password } response = requests.post( Student.LOGIN_URL, data=str(payload), headers=Student.HEADERS, cookies=self.cookies...
[ "def", "updatePassword", "(", "self", ",", "new_password", ")", ":", "payload", "=", "{", "\"newpassword\"", ":", "new_password", ",", "\"confirmpassword\"", ":", "new_password", "}", "response", "=", "requests", ".", "post", "(", "Student", ".", "LOGIN_URL", ...
Updates the current password to the given password
[ "Updates", "the", "current", "password", "to", "the", "given", "password" ]
[ "\"\"\"\n Updates the current password to the given password\n\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "new_password", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "new_password", "type": null, "docstring": null, "docstring_to...
9d01e2d3babb7ee58db54155f6521eb0c3c5ab4d
SubhrajitPrusty/ITER-api
iterapi/iterapi.py
[ "MIT" ]
Python
downloadSemResult
<not_specific>
def downloadSemResult(self, sem): """ Gets result pdf downloaded self.result_path-> str # path to the store the Result pdf """ payload = {"stynumber": str(sem), "publish": "Y"} response = requests.post( Student.RESULTDOWNLOAD_URL, data=str(payloa...
Gets result pdf downloaded self.result_path-> str # path to the store the Result pdf
Gets result pdf downloaded self.result_path-> str # path to the store the Result pdf
[ "Gets", "result", "pdf", "downloaded", "self", ".", "result_path", "-", ">", "str", "#", "path", "to", "the", "store", "the", "Result", "pdf" ]
def downloadSemResult(self, sem): payload = {"stynumber": str(sem), "publish": "Y"} response = requests.post( Student.RESULTDOWNLOAD_URL, data=str(payload), headers=Student.HEADERS, cookies=self.cookies) if response.status_code == 200: ...
[ "def", "downloadSemResult", "(", "self", ",", "sem", ")", ":", "payload", "=", "{", "\"stynumber\"", ":", "str", "(", "sem", ")", ",", "\"publish\"", ":", "\"Y\"", "}", "response", "=", "requests", ".", "post", "(", "Student", ".", "RESULTDOWNLOAD_URL", ...
Gets result pdf downloaded self.result_path-> str # path to the store the Result pdf
[ "Gets", "result", "pdf", "downloaded", "self", ".", "result_path", "-", ">", "str", "#", "path", "to", "the", "store", "the", "Result", "pdf" ]
[ "\"\"\"\n Gets result pdf downloaded\n\n self.result_path-> str # path to the store the Result pdf\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "sem", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "sem", "type": null, "docstring": null, "docstring_tokens": []...
ab3d185ca9f09c7a60c5603d677d8271770f4e5b
CyberFlameGO/sushy
sushy/models.py
[ "MIT" ]
Python
add_wiki_links
<not_specific>
def add_wiki_links(links): """Adds a set of wiki links""" with db.atomic(): # deferring transactions gives us a nice speed boost for l in links: try: return Link.create(**l) except IntegrityError as e: log.debug(e)
Adds a set of wiki links
Adds a set of wiki links
[ "Adds", "a", "set", "of", "wiki", "links" ]
def add_wiki_links(links): with db.atomic(): for l in links: try: return Link.create(**l) except IntegrityError as e: log.debug(e)
[ "def", "add_wiki_links", "(", "links", ")", ":", "with", "db", ".", "atomic", "(", ")", ":", "for", "l", "in", "links", ":", "try", ":", "return", "Link", ".", "create", "(", "**", "l", ")", "except", "IntegrityError", "as", "e", ":", "log", ".", ...
Adds a set of wiki links
[ "Adds", "a", "set", "of", "wiki", "links" ]
[ "\"\"\"Adds a set of wiki links\"\"\"", "# deferring transactions gives us a nice speed boost" ]
[ { "param": "links", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "links", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
ab3d185ca9f09c7a60c5603d677d8271770f4e5b
CyberFlameGO/sushy
sushy/models.py
[ "MIT" ]
Python
delete_wiki_page
null
def delete_wiki_page(page): """Deletes all the entries for a page""" with db.atomic(): try: FTSPage.delete().where(FTSPage.page == page).execute() Page.delete().where(Page.name == page).execute() Link.delete().where(Link.page == page).execute() except Exceptio...
Deletes all the entries for a page
Deletes all the entries for a page
[ "Deletes", "all", "the", "entries", "for", "a", "page" ]
def delete_wiki_page(page): with db.atomic(): try: FTSPage.delete().where(FTSPage.page == page).execute() Page.delete().where(Page.name == page).execute() Link.delete().where(Link.page == page).execute() except Exception as e: log.warn(e)
[ "def", "delete_wiki_page", "(", "page", ")", ":", "with", "db", ".", "atomic", "(", ")", ":", "try", ":", "FTSPage", ".", "delete", "(", ")", ".", "where", "(", "FTSPage", ".", "page", "==", "page", ")", ".", "execute", "(", ")", "Page", ".", "de...
Deletes all the entries for a page
[ "Deletes", "all", "the", "entries", "for", "a", "page" ]
[ "\"\"\"Deletes all the entries for a page\"\"\"" ]
[ { "param": "page", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "page", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
ab3d185ca9f09c7a60c5603d677d8271770f4e5b
CyberFlameGO/sushy
sushy/models.py
[ "MIT" ]
Python
index_wiki_page
<not_specific>
def index_wiki_page(**kwargs): """Adds wiki page metatada and FTS data.""" with db.atomic(): values = {} for k in [u"name", u"title", u"tags", u"hash", u"mtime", u"pubtime", u"idxtime", u"readtime"]: values[k] = kwargs[k] log.debug(values) try: page = Page...
Adds wiki page metatada and FTS data.
Adds wiki page metatada and FTS data.
[ "Adds", "wiki", "page", "metatada", "and", "FTS", "data", "." ]
def index_wiki_page(**kwargs): with db.atomic(): values = {} for k in [u"name", u"title", u"tags", u"hash", u"mtime", u"pubtime", u"idxtime", u"readtime"]: values[k] = kwargs[k] log.debug(values) try: page = Page.create(**values) except IntegrityError:...
[ "def", "index_wiki_page", "(", "**", "kwargs", ")", ":", "with", "db", ".", "atomic", "(", ")", ":", "values", "=", "{", "}", "for", "k", "in", "[", "u\"name\"", ",", "u\"title\"", ",", "u\"tags\"", ",", "u\"hash\"", ",", "u\"mtime\"", ",", "u\"pubtime...
Adds wiki page metatada and FTS data.
[ "Adds", "wiki", "page", "metatada", "and", "FTS", "data", "." ]
[ "\"\"\"Adds wiki page metatada and FTS data.\"\"\"", "# Not too happy about this, but FTS update() seems to be buggy and indexes keep growing" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
04d61dcf3e13226e0d1234bbde79c559da76b14f
Vitalinsh/Sleep-Analysis-with-accelerometer
prepare_data.py
[ "MIT" ]
Python
save_statistic_features
null
def save_statistic_features(patient_list, sorce_path="ICHI14_dataset\data", save_path="features.csv", window_len=60, n_sleep_stages=1, scaler=False): """ Save .csv file with extracted statistic features for each windows and axis. List of all features: ["id", "sleep_sta...
Save .csv file with extracted statistic features for each windows and axis. List of all features: ["id", "sleep_stage", "gender", "age", "std_x", "std_y", "std_z", "ptp_x", "ptp_y", "ptp_z", "mean_x", "mean_y", "mean_z", "rms_x", "rms_y", "rms_z", "crest_factor_x", "crest_factor_y", "crest_factor_z", "max...
Save .csv file with extracted statistic features for each windows and axis.
[ "Save", ".", "csv", "file", "with", "extracted", "statistic", "features", "for", "each", "windows", "and", "axis", "." ]
def save_statistic_features(patient_list, sorce_path="ICHI14_dataset\data", save_path="features.csv", window_len=60, n_sleep_stages=1, scaler=False): columns = ["id", "sleep_stage", "gender", "age", "std_x", "std_y", "std_z", "ptp_x", "ptp_y", "ptp_z", "mean_x", "mean_y", ...
[ "def", "save_statistic_features", "(", "patient_list", ",", "sorce_path", "=", "\"ICHI14_dataset\\data\"", ",", "save_path", "=", "\"features.csv\"", ",", "window_len", "=", "60", ",", "n_sleep_stages", "=", "1", ",", "scaler", "=", "False", ")", ":", "columns", ...
Save .csv file with extracted statistic features for each windows and axis.
[ "Save", ".", "csv", "file", "with", "extracted", "statistic", "features", "for", "each", "windows", "and", "axis", "." ]
[ "\"\"\"\n Save .csv file with extracted statistic features for each windows and axis.\n \n List of all features: [\"id\", \"sleep_stage\", \"gender\", \"age\", \"std_x\", \"std_y\", \"std_z\", \"ptp_x\", \"ptp_y\", \"ptp_z\", \"mean_x\", \"mean_y\", \"mean_z\", \"rms_x\", \"rms_y\", \"rms_z\", \"crest_fact...
[ { "param": "patient_list", "type": null }, { "param": "sorce_path", "type": null }, { "param": "save_path", "type": null }, { "param": "window_len", "type": null }, { "param": "n_sleep_stages", "type": null }, { "param": "scaler", "type": null } ...
{ "returns": [], "raises": [], "params": [ { "identifier": "patient_list", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "sorce_path", "type": null, "docstring": null, "docstr...
4fe06d10000953a7c6e6eab7d76b7eb0abc92357
antalakas/carnd-term1-miniflow
miniflow/miniflow/miniflow.py
[ "MIT" ]
Python
forward
null
def forward(self): """ Set self.value to the value of the linear function output. Your code goes here! """ inputs = self.inbound_nodes[0].value weights = self.inbound_nodes[1].value bias = self.inbound_nodes[2].value self.value = bias for input_da...
Set self.value to the value of the linear function output. Your code goes here!
Set self.value to the value of the linear function output. Your code goes here!
[ "Set", "self", ".", "value", "to", "the", "value", "of", "the", "linear", "function", "output", ".", "Your", "code", "goes", "here!" ]
def forward(self): inputs = self.inbound_nodes[0].value weights = self.inbound_nodes[1].value bias = self.inbound_nodes[2].value self.value = bias for input_data, weight in zip(inputs, weights): self.value += input_data * weight
[ "def", "forward", "(", "self", ")", ":", "inputs", "=", "self", ".", "inbound_nodes", "[", "0", "]", ".", "value", "weights", "=", "self", ".", "inbound_nodes", "[", "1", "]", ".", "value", "bias", "=", "self", ".", "inbound_nodes", "[", "2", "]", ...
Set self.value to the value of the linear function output.
[ "Set", "self", ".", "value", "to", "the", "value", "of", "the", "linear", "function", "output", "." ]
[ "\"\"\"\n Set self.value to the value of the linear function output.\n\n Your code goes here!\n \"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
4fe06d10000953a7c6e6eab7d76b7eb0abc92357
antalakas/carnd-term1-miniflow
miniflow/miniflow/miniflow.py
[ "MIT" ]
Python
forward
null
def forward(self): """ Set the value of this node to the linear transform output. Your code goes here! """ Xmn = self.inbound_nodes[0].value Wnk = self.inbound_nodes[1].value bk = self.inbound_nodes[2].value self.value = np.dot(Xmn, Wnk) + bk
Set the value of this node to the linear transform output. Your code goes here!
Set the value of this node to the linear transform output. Your code goes here!
[ "Set", "the", "value", "of", "this", "node", "to", "the", "linear", "transform", "output", ".", "Your", "code", "goes", "here!" ]
def forward(self): Xmn = self.inbound_nodes[0].value Wnk = self.inbound_nodes[1].value bk = self.inbound_nodes[2].value self.value = np.dot(Xmn, Wnk) + bk
[ "def", "forward", "(", "self", ")", ":", "Xmn", "=", "self", ".", "inbound_nodes", "[", "0", "]", ".", "value", "Wnk", "=", "self", ".", "inbound_nodes", "[", "1", "]", ".", "value", "bk", "=", "self", ".", "inbound_nodes", "[", "2", "]", ".", "v...
Set the value of this node to the linear transform output.
[ "Set", "the", "value", "of", "this", "node", "to", "the", "linear", "transform", "output", "." ]
[ "\"\"\"\n Set the value of this node to the linear transform output.\n\n Your code goes here!\n \"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
3c8630a5007678e3e94cba2bd87c0cf00d53e41f
swingerman/ble_monitor
custom_components/ble_monitor/__init__.py
[ "MIT" ]
Python
async_setup_entry
<not_specific>
async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry): """Set up BLE Monitor from a config entry.""" _LOGGER.debug("Initializing BLE Monitor entry (config entry): %s", config_entry) # Prevent unload to be triggered each time we update the config entry global UPDATE_UNLISTENER ...
Set up BLE Monitor from a config entry.
Set up BLE Monitor from a config entry.
[ "Set", "up", "BLE", "Monitor", "from", "a", "config", "entry", "." ]
async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry): _LOGGER.debug("Initializing BLE Monitor entry (config entry): %s", config_entry) global UPDATE_UNLISTENER if UPDATE_UNLISTENER: UPDATE_UNLISTENER() if not config_entry.unique_id: hass.config_entries.async_update...
[ "async", "def", "async_setup_entry", "(", "hass", ":", "HomeAssistant", ",", "config_entry", ":", "ConfigEntry", ")", ":", "_LOGGER", ".", "debug", "(", "\"Initializing BLE Monitor entry (config entry): %s\"", ",", "config_entry", ")", "global", "UPDATE_UNLISTENER", "if...
Set up BLE Monitor from a config entry.
[ "Set", "up", "BLE", "Monitor", "from", "a", "config", "entry", "." ]
[ "\"\"\"Set up BLE Monitor from a config entry.\"\"\"", "# Prevent unload to be triggered each time we update the config entry", "# Configuration in UI", "# device configuration is taken from yaml, but yaml config already removed", "# save unique IDs (only once)", "# Configuration in YAML", "# Configurat...
[ { "param": "hass", "type": "HomeAssistant" }, { "param": "config_entry", "type": "ConfigEntry" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "hass", "type": "HomeAssistant", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "config_entry", "type": "ConfigEntry", "docstring": null,...
3c8630a5007678e3e94cba2bd87c0cf00d53e41f
swingerman/ble_monitor
custom_components/ble_monitor/__init__.py
[ "MIT" ]
Python
async_migrate_entry
<not_specific>
async def async_migrate_entry(hass, config_entry): """Migrate config entry to new version.""" if config_entry.version == 1: options = dict(config_entry.options) hci_list = options.get(CONF_HCI_INTERFACE) bt_mac_list = [] for hci in hci_list: try: bt_ma...
Migrate config entry to new version.
Migrate config entry to new version.
[ "Migrate", "config", "entry", "to", "new", "version", "." ]
async def async_migrate_entry(hass, config_entry): if config_entry.version == 1: options = dict(config_entry.options) hci_list = options.get(CONF_HCI_INTERFACE) bt_mac_list = [] for hci in hci_list: try: bt_mac = BT_INTERFACES.get(hci) if b...
[ "async", "def", "async_migrate_entry", "(", "hass", ",", "config_entry", ")", ":", "if", "config_entry", ".", "version", "==", "1", ":", "options", "=", "dict", "(", "config_entry", ".", "options", ")", "hci_list", "=", "options", ".", "get", "(", "CONF_HC...
Migrate config entry to new version.
[ "Migrate", "config", "entry", "to", "new", "version", "." ]
[ "\"\"\"Migrate config entry to new version.\"\"\"", "# Fall back in case no hci interfaces are added" ]
[ { "param": "hass", "type": null }, { "param": "config_entry", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "hass", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "config_entry", "type": null, "docstring": null, "docstring_to...
f3acbd5e0f10345daad2882209c0b4a9ca2410e3
Mikerah/GenreExplorer
genre_explorer/genres/genres_scraper.py
[ "MIT" ]
Python
_get_links_to_sections_of_genres
<not_specific>
def _get_links_to_sections_of_genres(): """ Returns a list of links to the different sections of genres in wikipedia """ page_text = requests.get("https://en.wikipedia.org/wiki/List_of_music_styles") try: page_text.raise_for_status except Exception as exc: print("There was a prob...
Returns a list of links to the different sections of genres in wikipedia
Returns a list of links to the different sections of genres in wikipedia
[ "Returns", "a", "list", "of", "links", "to", "the", "different", "sections", "of", "genres", "in", "wikipedia" ]
def _get_links_to_sections_of_genres(): page_text = requests.get("https://en.wikipedia.org/wiki/List_of_music_styles") try: page_text.raise_for_status except Exception as exc: print("There was a problem") page_text = page_text.text bs_obj = bs4.BeautifulSoup(page_text, "html.parser")...
[ "def", "_get_links_to_sections_of_genres", "(", ")", ":", "page_text", "=", "requests", ".", "get", "(", "\"https://en.wikipedia.org/wiki/List_of_music_styles\"", ")", "try", ":", "page_text", ".", "raise_for_status", "except", "Exception", "as", "exc", ":", "print", ...
Returns a list of links to the different sections of genres in wikipedia
[ "Returns", "a", "list", "of", "links", "to", "the", "different", "sections", "of", "genres", "in", "wikipedia" ]
[ "\"\"\"\n Returns a list of links to the different sections of genres in wikipedia\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
f3acbd5e0f10345daad2882209c0b4a9ca2410e3
Mikerah/GenreExplorer
genre_explorer/genres/genres_scraper.py
[ "MIT" ]
Python
_get_list_of_genre_from_links
<not_specific>
def _get_list_of_genre_from_links(): """ Returns the list of genres from the given list of links :params links - list """ links = _get_links_to_sections_of_genres() g = [] for i in links: wiki_genres_page = requests.get(i) try: wiki_genres_page.raise_for_status ...
Returns the list of genres from the given list of links :params links - list
Returns the list of genres from the given list of links :params links - list
[ "Returns", "the", "list", "of", "genres", "from", "the", "given", "list", "of", "links", ":", "params", "links", "-", "list" ]
def _get_list_of_genre_from_links(): links = _get_links_to_sections_of_genres() g = [] for i in links: wiki_genres_page = requests.get(i) try: wiki_genres_page.raise_for_status except Exception as exc: print("There was a problem") wiki_genres_page = wi...
[ "def", "_get_list_of_genre_from_links", "(", ")", ":", "links", "=", "_get_links_to_sections_of_genres", "(", ")", "g", "=", "[", "]", "for", "i", "in", "links", ":", "wiki_genres_page", "=", "requests", ".", "get", "(", "i", ")", "try", ":", "wiki_genres_pa...
Returns the list of genres from the given list of links :params links - list
[ "Returns", "the", "list", "of", "genres", "from", "the", "given", "list", "of", "links", ":", "params", "links", "-", "list" ]
[ "\"\"\"\n Returns the list of genres from the given list of links\n :params links - list\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
f3acbd5e0f10345daad2882209c0b4a9ca2410e3
Mikerah/GenreExplorer
genre_explorer/genres/genres_scraper.py
[ "MIT" ]
Python
create_genres_dictionary
<not_specific>
def create_genres_dictionary(): """ Returns a dictionary of genres where the keys are the alphabet and the values a list of genres :params list_of_genres - list """ list_of_genres = _get_list_of_genre_from_links() genres = {k: [] for k in LIST_OF_LETTERS} for genre in list_of_g...
Returns a dictionary of genres where the keys are the alphabet and the values a list of genres :params list_of_genres - list
Returns a dictionary of genres where the keys are the alphabet and the values a list of genres :params list_of_genres - list
[ "Returns", "a", "dictionary", "of", "genres", "where", "the", "keys", "are", "the", "alphabet", "and", "the", "values", "a", "list", "of", "genres", ":", "params", "list_of_genres", "-", "list" ]
def create_genres_dictionary(): list_of_genres = _get_list_of_genre_from_links() genres = {k: [] for k in LIST_OF_LETTERS} for genre in list_of_genres: if 'Sections' in genre or 'Section' in genre: list_of_genres.remove(genre) if genre[0] in genres: genres[genre[0]].a...
[ "def", "create_genres_dictionary", "(", ")", ":", "list_of_genres", "=", "_get_list_of_genre_from_links", "(", ")", "genres", "=", "{", "k", ":", "[", "]", "for", "k", "in", "LIST_OF_LETTERS", "}", "for", "genre", "in", "list_of_genres", ":", "if", "'Sections'...
Returns a dictionary of genres where the keys are the alphabet and the values a list of genres :params list_of_genres - list
[ "Returns", "a", "dictionary", "of", "genres", "where", "the", "keys", "are", "the", "alphabet", "and", "the", "values", "a", "list", "of", "genres", ":", "params", "list_of_genres", "-", "list" ]
[ "\"\"\"\n Returns a dictionary of genres where the keys are the alphabet and the values\n a list of genres\n :params list_of_genres - list\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
53fd42b1ab747afe36ac446011b0b07f6da1e899
Mikerah/GenreExplorer
genre_explorer/genres/genres_playlist.py
[ "MIT" ]
Python
create_genres_from_dictionary
<not_specific>
def create_genres_from_dictionary(): """ Returns a sorted list of Genre objects from the dictionary of genres """ youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, developerKey=API_KEY) dict_of_genre = create_genres_dictionary() list_of_genres = [] dict_keys = sorted(dict_o...
Returns a sorted list of Genre objects from the dictionary of genres
Returns a sorted list of Genre objects from the dictionary of genres
[ "Returns", "a", "sorted", "list", "of", "Genre", "objects", "from", "the", "dictionary", "of", "genres" ]
def create_genres_from_dictionary(): youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, developerKey=API_KEY) dict_of_genre = create_genres_dictionary() list_of_genres = [] dict_keys = sorted(dict_of_genre.keys()) for i in dict_keys: tmp = dict_of_genre[i] for j in tmp: ...
[ "def", "create_genres_from_dictionary", "(", ")", ":", "youtube", "=", "build", "(", "YOUTUBE_API_SERVICE_NAME", ",", "YOUTUBE_API_VERSION", ",", "developerKey", "=", "API_KEY", ")", "dict_of_genre", "=", "create_genres_dictionary", "(", ")", "list_of_genres", "=", "[...
Returns a sorted list of Genre objects from the dictionary of genres
[ "Returns", "a", "sorted", "list", "of", "Genre", "objects", "from", "the", "dictionary", "of", "genres" ]
[ "\"\"\"\n Returns a sorted list of Genre objects from the dictionary of genres\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
5e9bd27a4826ec8a4b85c296a4e26bb0b624d4f5
seandstewart/que
que/query.py
[ "MIT" ]
Python
for_fetch
str
def for_fetch(self) -> str: """Generate valid SQL for a ``Field`` if it is being used in a SELECT or RETURNING statement.""" return ( f"{self.name} AS {self.value}" if (self.value and self.name) else (self.name or self.value) )
Generate valid SQL for a ``Field`` if it is being used in a SELECT or RETURNING statement.
Generate valid SQL for a ``Field`` if it is being used in a SELECT or RETURNING statement.
[ "Generate", "valid", "SQL", "for", "a", "`", "`", "Field", "`", "`", "if", "it", "is", "being", "used", "in", "a", "SELECT", "or", "RETURNING", "statement", "." ]
def for_fetch(self) -> str: return ( f"{self.name} AS {self.value}" if (self.value and self.name) else (self.name or self.value) )
[ "def", "for_fetch", "(", "self", ")", "->", "str", ":", "return", "(", "f\"{self.name} AS {self.value}\"", "if", "(", "self", ".", "value", "and", "self", ".", "name", ")", "else", "(", "self", ".", "name", "or", "self", ".", "value", ")", ")" ]
Generate valid SQL for a ``Field`` if it is being used in a SELECT or RETURNING statement.
[ "Generate", "valid", "SQL", "for", "a", "`", "`", "Field", "`", "`", "if", "it", "is", "being", "used", "in", "a", "SELECT", "or", "RETURNING", "statement", "." ]
[ "\"\"\"Generate valid SQL for a ``Field`` if it is being used in a SELECT or RETURNING statement.\"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
5e9bd27a4826ec8a4b85c296a4e26bb0b624d4f5
seandstewart/que
que/query.py
[ "MIT" ]
Python
to_sql
Tuple[str, "ArgList"]
def to_sql( self, args: "ArgList" = None, style: ParamStyleType = DEFAULT_PARAM_STYLE ) -> Tuple[str, "ArgList"]: """Generate a single filter clause of a SQL Statement. Parameters ---------- args : optional The mutable, ordered list of arguments. style : ...
Generate a single filter clause of a SQL Statement. Parameters ---------- args : optional The mutable, ordered list of arguments. style : optional The DBAPI 2.0 compliant param-style you wish to use in the generated SQL. Returns ------- T...
Generate a single filter clause of a SQL Statement. Parameters args : optional The mutable, ordered list of arguments. style : optional The DBAPI 2.0 compliant param-style you wish to use in the generated SQL. Returns The SQL fragment, as str The :class:`ArgList` which will be passed on to the DB client for secure f...
[ "Generate", "a", "single", "filter", "clause", "of", "a", "SQL", "Statement", ".", "Parameters", "args", ":", "optional", "The", "mutable", "ordered", "list", "of", "arguments", ".", "style", ":", "optional", "The", "DBAPI", "2", ".", "0", "compliant", "pa...
def to_sql( self, args: "ArgList" = None, style: ParamStyleType = DEFAULT_PARAM_STYLE ) -> Tuple[str, "ArgList"]: args = args or ArgList() args.append(self.field) fmt = f"{style}" if style in NameParamStyle: name = f"{self.prefix}{self.field.name}" fmt...
[ "def", "to_sql", "(", "self", ",", "args", ":", "\"ArgList\"", "=", "None", ",", "style", ":", "ParamStyleType", "=", "DEFAULT_PARAM_STYLE", ")", "->", "Tuple", "[", "str", ",", "\"ArgList\"", "]", ":", "args", "=", "args", "or", "ArgList", "(", ")", "...
Generate a single filter clause of a SQL Statement.
[ "Generate", "a", "single", "filter", "clause", "of", "a", "SQL", "Statement", "." ]
[ "\"\"\"Generate a single filter clause of a SQL Statement.\n\n Parameters\n ----------\n args : optional\n The mutable, ordered list of arguments.\n style : optional\n The DBAPI 2.0 compliant param-style you wish to use in the generated SQL.\n\n Returns\n ...
[ { "param": "self", "type": null }, { "param": "args", "type": "\"ArgList\"" }, { "param": "style", "type": "ParamStyleType" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "args", "type": "\"ArgList\"", "docstring": null, "docstring_t...
5e9bd27a4826ec8a4b85c296a4e26bb0b624d4f5
seandstewart/que
que/query.py
[ "MIT" ]
Python
for_sql
Union[Dict[str, Any], List[Any]]
def for_sql( self, style: ParamStyleType = DEFAULT_PARAM_STYLE ) -> Union[Dict[str, Any], List[Any]]: """Output the list of args in the appropriate format for the param-style. Parameters ---------- style : The enum selection which matches your param-style. ...
Output the list of args in the appropriate format for the param-style. Parameters ---------- style : The enum selection which matches your param-style.
Output the list of args in the appropriate format for the param-style. Parameters style : The enum selection which matches your param-style.
[ "Output", "the", "list", "of", "args", "in", "the", "appropriate", "format", "for", "the", "param", "-", "style", ".", "Parameters", "style", ":", "The", "enum", "selection", "which", "matches", "your", "param", "-", "style", "." ]
def for_sql( self, style: ParamStyleType = DEFAULT_PARAM_STYLE ) -> Union[Dict[str, Any], List[Any]]: if style in NameParamStyle: return self.asdict() return self.aslist()
[ "def", "for_sql", "(", "self", ",", "style", ":", "ParamStyleType", "=", "DEFAULT_PARAM_STYLE", ")", "->", "Union", "[", "Dict", "[", "str", ",", "Any", "]", ",", "List", "[", "Any", "]", "]", ":", "if", "style", "in", "NameParamStyle", ":", "return", ...
Output the list of args in the appropriate format for the param-style.
[ "Output", "the", "list", "of", "args", "in", "the", "appropriate", "format", "for", "the", "param", "-", "style", "." ]
[ "\"\"\"Output the list of args in the appropriate format for the param-style.\n\n Parameters\n ----------\n style :\n The enum selection which matches your param-style.\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "style", "type": "ParamStyleType" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "style", "type": "ParamStyleType", "docstring": null, "docstri...
5e9bd27a4826ec8a4b85c296a4e26bb0b624d4f5
seandstewart/que
que/query.py
[ "MIT" ]
Python
to_sql
Tuple[str, ArgList]
def to_sql( self, args: ArgList = None, style: ParamStyleType = DEFAULT_PARAM_STYLE ) -> Tuple[str, ArgList]: """Generate the ``WHERE`` clause of a SQL statement. Parameters ---------- args : optional The list of :class:`Fields` which will serve as arguments for ...
Generate the ``WHERE`` clause of a SQL statement. Parameters ---------- args : optional The list of :class:`Fields` which will serve as arguments for formatting the SQL statement. style : defaults :class:`NumParamStyle.NUM` Returns ------- The WHERE ...
Generate the ``WHERE`` clause of a SQL statement. Parameters args : optional The list of :class:`Fields` which will serve as arguments for formatting the SQL statement. Returns The WHERE clause for your SQL statement. A list of args to pass on to the DB client when performing the query.
[ "Generate", "the", "`", "`", "WHERE", "`", "`", "clause", "of", "a", "SQL", "statement", ".", "Parameters", "args", ":", "optional", "The", "list", "of", ":", "class", ":", "`", "Fields", "`", "which", "will", "serve", "as", "arguments", "for", "format...
def to_sql( self, args: ArgList = None, style: ParamStyleType = DEFAULT_PARAM_STYLE ) -> Tuple[str, ArgList]: args = args or ArgList() where = [] for fylter in self: sql, args = fylter.to_sql(args, style) where.append(sql) where = "AND\n ".join(where)...
[ "def", "to_sql", "(", "self", ",", "args", ":", "ArgList", "=", "None", ",", "style", ":", "ParamStyleType", "=", "DEFAULT_PARAM_STYLE", ")", "->", "Tuple", "[", "str", ",", "ArgList", "]", ":", "args", "=", "args", "or", "ArgList", "(", ")", "where", ...
Generate the ``WHERE`` clause of a SQL statement.
[ "Generate", "the", "`", "`", "WHERE", "`", "`", "clause", "of", "a", "SQL", "statement", "." ]
[ "\"\"\"Generate the ``WHERE`` clause of a SQL statement.\n\n Parameters\n ----------\n args : optional\n The list of :class:`Fields` which will serve as arguments for formatting the SQL statement.\n style : defaults :class:`NumParamStyle.NUM`\n\n Returns\n ------...
[ { "param": "self", "type": null }, { "param": "args", "type": "ArgList" }, { "param": "style", "type": "ParamStyleType" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "args", "type": "ArgList", "docstring": null, "docstring_token...
5e9bd27a4826ec8a4b85c296a4e26bb0b624d4f5
seandstewart/que
que/query.py
[ "MIT" ]
Python
build_select
str
def build_select(self) -> str: """Build the SELECT clause of a SQL statement. If :attr:`Select.fields` is empty, default to selecting all columns. """ columns = [] for field in self.fields: columns.append(field.for_fetch()) columns = ",\n ".join(columns) if ...
Build the SELECT clause of a SQL statement. If :attr:`Select.fields` is empty, default to selecting all columns.
Build the SELECT clause of a SQL statement. If :attr:`Select.fields` is empty, default to selecting all columns.
[ "Build", "the", "SELECT", "clause", "of", "a", "SQL", "statement", ".", "If", ":", "attr", ":", "`", "Select", ".", "fields", "`", "is", "empty", "default", "to", "selecting", "all", "columns", "." ]
def build_select(self) -> str: columns = [] for field in self.fields: columns.append(field.for_fetch()) columns = ",\n ".join(columns) if columns else "*" return f"SELECT\n {columns}\nFROM\n {self.table_name}"
[ "def", "build_select", "(", "self", ")", "->", "str", ":", "columns", "=", "[", "]", "for", "field", "in", "self", ".", "fields", ":", "columns", ".", "append", "(", "field", ".", "for_fetch", "(", ")", ")", "columns", "=", "\",\\n \"", ".", "join",...
Build the SELECT clause of a SQL statement.
[ "Build", "the", "SELECT", "clause", "of", "a", "SQL", "statement", "." ]
[ "\"\"\"Build the SELECT clause of a SQL statement.\n\n If :attr:`Select.fields` is empty, default to selecting all columns.\n \"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
5e9bd27a4826ec8a4b85c296a4e26bb0b624d4f5
seandstewart/que
que/query.py
[ "MIT" ]
Python
to_sql
Tuple[str, Union[List, Dict]]
def to_sql( self, style: ParamStyleType = DEFAULT_PARAM_STYLE ) -> Tuple[str, Union[List, Dict]]: """Generate a valid SQL SELECT statement for a single table. Parameters -------- style : defaults :class:`NumParamStyle.NUM` The DBAPI 2.0 param-style. Retu...
Generate a valid SQL SELECT statement for a single table. Parameters -------- style : defaults :class:`NumParamStyle.NUM` The DBAPI 2.0 param-style. Returns ----- The generated SQL SELECT statement The arguments to pass to the DB client for secure fo...
Generate a valid SQL SELECT statement for a single table. Parameters Returns The generated SQL SELECT statement The arguments to pass to the DB client for secure formatting.
[ "Generate", "a", "valid", "SQL", "SELECT", "statement", "for", "a", "single", "table", ".", "Parameters", "Returns", "The", "generated", "SQL", "SELECT", "statement", "The", "arguments", "to", "pass", "to", "the", "DB", "client", "for", "secure", "formatting",...
def to_sql( self, style: ParamStyleType = DEFAULT_PARAM_STYLE ) -> Tuple[str, Union[List, Dict]]: select = self.build_select() where, args = self.filters.to_sql(style=style) return f"{select}\n{where}", args.for_sql(style)
[ "def", "to_sql", "(", "self", ",", "style", ":", "ParamStyleType", "=", "DEFAULT_PARAM_STYLE", ")", "->", "Tuple", "[", "str", ",", "Union", "[", "List", ",", "Dict", "]", "]", ":", "select", "=", "self", ".", "build_select", "(", ")", "where", ",", ...
Generate a valid SQL SELECT statement for a single table.
[ "Generate", "a", "valid", "SQL", "SELECT", "statement", "for", "a", "single", "table", "." ]
[ "\"\"\"Generate a valid SQL SELECT statement for a single table.\n\n Parameters\n --------\n style : defaults :class:`NumParamStyle.NUM`\n The DBAPI 2.0 param-style.\n\n Returns\n -----\n The generated SQL SELECT statement\n The arguments to pass to the DB...
[ { "param": "self", "type": null }, { "param": "style", "type": "ParamStyleType" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "style", "type": "ParamStyleType", "docstring": null, "docstri...
5e9bd27a4826ec8a4b85c296a4e26bb0b624d4f5
seandstewart/que
que/query.py
[ "MIT" ]
Python
build_update
Tuple[str, ArgList]
def build_update( self, style: ParamStyleType = DEFAULT_PARAM_STYLE ) -> Tuple[str, ArgList]: """Build the SQL UPDATE clause. Parameters -------- style : defaults :class:`NumParamStyle.NUM` The DBAPI 2.0 param-style. Returns ----- The gen...
Build the SQL UPDATE clause. Parameters -------- style : defaults :class:`NumParamStyle.NUM` The DBAPI 2.0 param-style. Returns ----- The generated UPDATE clause of a SQL statement The arguments to pass to the DB client for secure formatting. ...
Build the SQL UPDATE clause. Parameters Returns The generated UPDATE clause of a SQL statement The arguments to pass to the DB client for secure formatting.
[ "Build", "the", "SQL", "UPDATE", "clause", ".", "Parameters", "Returns", "The", "generated", "UPDATE", "clause", "of", "a", "SQL", "statement", "The", "arguments", "to", "pass", "to", "the", "DB", "client", "for", "secure", "formatting", "." ]
def build_update( self, style: ParamStyleType = DEFAULT_PARAM_STYLE ) -> Tuple[str, ArgList]: updates = [] args = ArgList() for field in self.fields: stmt, args = Filter(field, prefix="col").to_sql(args, style) updates.append(stmt) updates = ",\n ".jo...
[ "def", "build_update", "(", "self", ",", "style", ":", "ParamStyleType", "=", "DEFAULT_PARAM_STYLE", ")", "->", "Tuple", "[", "str", ",", "ArgList", "]", ":", "updates", "=", "[", "]", "args", "=", "ArgList", "(", ")", "for", "field", "in", "self", "."...
Build the SQL UPDATE clause.
[ "Build", "the", "SQL", "UPDATE", "clause", "." ]
[ "\"\"\"Build the SQL UPDATE clause.\n\n Parameters\n --------\n style : defaults :class:`NumParamStyle.NUM`\n The DBAPI 2.0 param-style.\n\n Returns\n -----\n The generated UPDATE clause of a SQL statement\n The arguments to pass to the DB client for secur...
[ { "param": "self", "type": null }, { "param": "style", "type": "ParamStyleType" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "style", "type": "ParamStyleType", "docstring": null, "docstri...
5e9bd27a4826ec8a4b85c296a4e26bb0b624d4f5
seandstewart/que
que/query.py
[ "MIT" ]
Python
to_sql
Tuple[str, Union[List, Dict]]
def to_sql( self, style: ParamStyleType = DEFAULT_PARAM_STYLE ) -> Tuple[str, Union[List, Dict]]: """Build the SQL UPDATE clause. Parameters -------- style : defaults :class:`NumParamStyle.NUM` The DBAPI 2.0 param-style. Returns ----- The...
Build the SQL UPDATE clause. Parameters -------- style : defaults :class:`NumParamStyle.NUM` The DBAPI 2.0 param-style. Returns ----- The generated SQL UPDATE statement The arguments to pass to the DB client for secure formatting.
Build the SQL UPDATE clause. Parameters Returns The generated SQL UPDATE statement The arguments to pass to the DB client for secure formatting.
[ "Build", "the", "SQL", "UPDATE", "clause", ".", "Parameters", "Returns", "The", "generated", "SQL", "UPDATE", "statement", "The", "arguments", "to", "pass", "to", "the", "DB", "client", "for", "secure", "formatting", "." ]
def to_sql( self, style: ParamStyleType = DEFAULT_PARAM_STYLE ) -> Tuple[str, Union[List, Dict]]: update, args = self.build_update(style) where, args = self.filters.to_sql(args, style) returning = self.get_returning() return f"{update}\n{where}\n{returning}", args.for_sql(sty...
[ "def", "to_sql", "(", "self", ",", "style", ":", "ParamStyleType", "=", "DEFAULT_PARAM_STYLE", ")", "->", "Tuple", "[", "str", ",", "Union", "[", "List", ",", "Dict", "]", "]", ":", "update", ",", "args", "=", "self", ".", "build_update", "(", "style",...
Build the SQL UPDATE clause.
[ "Build", "the", "SQL", "UPDATE", "clause", "." ]
[ "\"\"\"Build the SQL UPDATE clause.\n\n Parameters\n --------\n style : defaults :class:`NumParamStyle.NUM`\n The DBAPI 2.0 param-style.\n\n Returns\n -----\n The generated SQL UPDATE statement\n The arguments to pass to the DB client for secure formatting...
[ { "param": "self", "type": null }, { "param": "style", "type": "ParamStyleType" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "style", "type": "ParamStyleType", "docstring": null, "docstri...
5e9bd27a4826ec8a4b85c296a4e26bb0b624d4f5
seandstewart/que
que/query.py
[ "MIT" ]
Python
build_insert
Tuple[str, ArgList]
def build_insert( self, style: ParamStyleType = DEFAULT_PARAM_STYLE, *, inject_columns: bool = False, ) -> Tuple[str, ArgList]: """Build a SQL INSERT statement. We create two new :class:`FieldList` - one for column declaration and one for values declaration. ...
Build a SQL INSERT statement. We create two new :class:`FieldList` - one for column declaration and one for values declaration. We combine them as a single :class:`ArgList` (order is important!). We generate the SQL fragments for the INSERT INTO clause and the VALUES clause. We check fo...
Build a SQL INSERT statement. We create two new :class:`FieldList` - one for column declaration and one for values declaration. We combine them as a single :class:`ArgList` (order is important!). We generate the SQL fragments for the INSERT INTO clause and the VALUES clause. We check for a RETURNING clause. Finally, we...
[ "Build", "a", "SQL", "INSERT", "statement", ".", "We", "create", "two", "new", ":", "class", ":", "`", "FieldList", "`", "-", "one", "for", "column", "declaration", "and", "one", "for", "values", "declaration", ".", "We", "combine", "them", "as", "a", ...
def build_insert( self, style: ParamStyleType = DEFAULT_PARAM_STYLE, *, inject_columns: bool = False, ) -> Tuple[str, ArgList]: columns = FieldList([Field(f"col{x.name}", x.name) for x in self.fields]) values = FieldList([Field(f"val{x.name}", x.value) for x in self.f...
[ "def", "build_insert", "(", "self", ",", "style", ":", "ParamStyleType", "=", "DEFAULT_PARAM_STYLE", ",", "*", ",", "inject_columns", ":", "bool", "=", "False", ",", ")", "->", "Tuple", "[", "str", ",", "ArgList", "]", ":", "columns", "=", "FieldList", "...
Build a SQL INSERT statement.
[ "Build", "a", "SQL", "INSERT", "statement", "." ]
[ "\"\"\"Build a SQL INSERT statement.\n\n We create two new :class:`FieldList` - one for column declaration and one for values declaration.\n We combine them as a single :class:`ArgList` (order is important!).\n We generate the SQL fragments for the INSERT INTO clause and the VALUES clause.\n ...
[ { "param": "self", "type": null }, { "param": "style", "type": "ParamStyleType" }, { "param": "inject_columns", "type": "bool" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "style", "type": "ParamStyleType", "docstring": null, "docstri...
5e9bd27a4826ec8a4b85c296a4e26bb0b624d4f5
seandstewart/que
que/query.py
[ "MIT" ]
Python
to_sql
Tuple[str, Union[List, Dict]]
def to_sql( self, style: ParamStyleType = DEFAULT_PARAM_STYLE, inject_columns: bool = False ) -> Tuple[str, Union[List, Dict]]: """Build the SQL INSERT statement and format the list of arguments to pass to the DB client. Parameters -------- style : defaults :class:`NumParamS...
Build the SQL INSERT statement and format the list of arguments to pass to the DB client. Parameters -------- style : defaults :class:`NumParamStyle.NUM` The DBAPI 2.0 param-style. inject_columns: defaults False Inject the column names directly, rather than rely ...
Build the SQL INSERT statement and format the list of arguments to pass to the DB client. Parameters Returns The generated SQL INSERT statement The arguments to pass to the DB client for secure formatting.
[ "Build", "the", "SQL", "INSERT", "statement", "and", "format", "the", "list", "of", "arguments", "to", "pass", "to", "the", "DB", "client", ".", "Parameters", "Returns", "The", "generated", "SQL", "INSERT", "statement", "The", "arguments", "to", "pass", "to"...
def to_sql( self, style: ParamStyleType = DEFAULT_PARAM_STYLE, inject_columns: bool = False ) -> Tuple[str, Union[List, Dict]]: query, args = self.build_insert(style, inject_columns=inject_columns) return query, args.for_sql(style)
[ "def", "to_sql", "(", "self", ",", "style", ":", "ParamStyleType", "=", "DEFAULT_PARAM_STYLE", ",", "inject_columns", ":", "bool", "=", "False", ")", "->", "Tuple", "[", "str", ",", "Union", "[", "List", ",", "Dict", "]", "]", ":", "query", ",", "args"...
Build the SQL INSERT statement and format the list of arguments to pass to the DB client.
[ "Build", "the", "SQL", "INSERT", "statement", "and", "format", "the", "list", "of", "arguments", "to", "pass", "to", "the", "DB", "client", "." ]
[ "\"\"\"Build the SQL INSERT statement and format the list of arguments to pass to the DB client.\n\n Parameters\n --------\n style : defaults :class:`NumParamStyle.NUM`\n The DBAPI 2.0 param-style.\n inject_columns: defaults False\n Inject the column names directly,...
[ { "param": "self", "type": null }, { "param": "style", "type": "ParamStyleType" }, { "param": "inject_columns", "type": "bool" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "style", "type": "ParamStyleType", "docstring": null, "docstri...
5e9bd27a4826ec8a4b85c296a4e26bb0b624d4f5
seandstewart/que
que/query.py
[ "MIT" ]
Python
to_sql
Tuple[str, Union[List, Dict]]
def to_sql( self, style: ParamStyleType = DEFAULT_PARAM_STYLE ) -> Tuple[str, Union[List, Dict]]: """Generate a SQL DELETE statement. Parameters -------- style : defaults :class:`NumParamStyle.NUM` The DBAPI 2.0 param-style. Returns ----- ...
Generate a SQL DELETE statement. Parameters -------- style : defaults :class:`NumParamStyle.NUM` The DBAPI 2.0 param-style. Returns ----- The generated SQL DELETE statement The arguments to pass to the DB client for secure formatting.
Generate a SQL DELETE statement. Parameters Returns The generated SQL DELETE statement The arguments to pass to the DB client for secure formatting.
[ "Generate", "a", "SQL", "DELETE", "statement", ".", "Parameters", "Returns", "The", "generated", "SQL", "DELETE", "statement", "The", "arguments", "to", "pass", "to", "the", "DB", "client", "for", "secure", "formatting", "." ]
def to_sql( self, style: ParamStyleType = DEFAULT_PARAM_STYLE ) -> Tuple[str, Union[List, Dict]]: where, args = self.filters.to_sql(style=style) returning = self.get_returning() return ( f"DELETE FROM\n {self.table_name}\n{where}\n{returning}", args.for_sql(s...
[ "def", "to_sql", "(", "self", ",", "style", ":", "ParamStyleType", "=", "DEFAULT_PARAM_STYLE", ")", "->", "Tuple", "[", "str", ",", "Union", "[", "List", ",", "Dict", "]", "]", ":", "where", ",", "args", "=", "self", ".", "filters", ".", "to_sql", "(...
Generate a SQL DELETE statement.
[ "Generate", "a", "SQL", "DELETE", "statement", "." ]
[ "\"\"\"Generate a SQL DELETE statement.\n\n Parameters\n --------\n style : defaults :class:`NumParamStyle.NUM`\n The DBAPI 2.0 param-style.\n\n Returns\n -----\n The generated SQL DELETE statement\n The arguments to pass to the DB client for secure format...
[ { "param": "self", "type": null }, { "param": "style", "type": "ParamStyleType" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "style", "type": "ParamStyleType", "docstring": null, "docstri...
5e9bd27a4826ec8a4b85c296a4e26bb0b624d4f5
seandstewart/que
que/query.py
[ "MIT" ]
Python
data_to_fields
FieldList
def data_to_fields(data: FieldDataType, exclude: Any = Nothing) -> FieldList: """Convert a dataclass, NamedTuple, dict, or array of tuples to a FieldList. Parameters -------- data Any data-source which you wish to conver to a list of fields. exclude Any value or type which you wish ...
Convert a dataclass, NamedTuple, dict, or array of tuples to a FieldList. Parameters -------- data Any data-source which you wish to conver to a list of fields. exclude Any value or type which you wish to exclude
Convert a dataclass, NamedTuple, dict, or array of tuples to a FieldList. Parameters data Any data-source which you wish to conver to a list of fields. exclude Any value or type which you wish to exclude
[ "Convert", "a", "dataclass", "NamedTuple", "dict", "or", "array", "of", "tuples", "to", "a", "FieldList", ".", "Parameters", "data", "Any", "data", "-", "source", "which", "you", "wish", "to", "conver", "to", "a", "list", "of", "fields", ".", "exclude", ...
def data_to_fields(data: FieldDataType, exclude: Any = Nothing) -> FieldList: if data: dict_factory = DictFactory(exclude=exclude) if dataclasses.is_dataclass(data): data = dataclasses.asdict(data, dict_factory=dict_factory) elif isnamedtuple(data): data = dict_factor...
[ "def", "data_to_fields", "(", "data", ":", "FieldDataType", ",", "exclude", ":", "Any", "=", "Nothing", ")", "->", "FieldList", ":", "if", "data", ":", "dict_factory", "=", "DictFactory", "(", "exclude", "=", "exclude", ")", "if", "dataclasses", ".", "is_d...
Convert a dataclass, NamedTuple, dict, or array of tuples to a FieldList.
[ "Convert", "a", "dataclass", "NamedTuple", "dict", "or", "array", "of", "tuples", "to", "a", "FieldList", "." ]
[ "\"\"\"Convert a dataclass, NamedTuple, dict, or array of tuples to a FieldList.\n\n Parameters\n --------\n data\n Any data-source which you wish to conver to a list of fields.\n exclude\n Any value or type which you wish to exclude\n \"\"\"" ]
[ { "param": "data", "type": "FieldDataType" }, { "param": "exclude", "type": "Any" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "data", "type": "FieldDataType", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "exclude", "type": "Any", "docstring": null, "docst...
aae5575d269ff6b5466fb55e08a763147feb040d
seandstewart/que
que/util.py
[ "MIT" ]
Python
factory
Dict
def factory( obj: Union[Dict, Sequence[Tuple[Hashable, Any]]], exclude: Optional[Any] = Nothing, ) -> Dict: """Produce a dictionary from a supplied object. Optionally exclude a specific value or type from the output Examples -------- >>> DictFactory.factory({'x': 0, ...
Produce a dictionary from a supplied object. Optionally exclude a specific value or type from the output Examples -------- >>> DictFactory.factory({'x': 0, 'y': None}, exclude=None) {'x': 0} >>> DictFactory.factory([('x', 0), ('y', None)], exclude=int) {'y': None} ...
Produce a dictionary from a supplied object. Optionally exclude a specific value or type from the output Examples
[ "Produce", "a", "dictionary", "from", "a", "supplied", "object", ".", "Optionally", "exclude", "a", "specific", "value", "or", "type", "from", "the", "output", "Examples" ]
def factory( obj: Union[Dict, Sequence[Tuple[Hashable, Any]]], exclude: Optional[Any] = Nothing, ) -> Dict: if isinstance(obj, Dict) and exclude is Nothing: return obj obj = obj.items() if isinstance(obj, Dict) else obj def _cmp(val): return ( ...
[ "def", "factory", "(", "obj", ":", "Union", "[", "Dict", ",", "Sequence", "[", "Tuple", "[", "Hashable", ",", "Any", "]", "]", "]", ",", "exclude", ":", "Optional", "[", "Any", "]", "=", "Nothing", ",", ")", "->", "Dict", ":", "if", "isinstance", ...
Produce a dictionary from a supplied object.
[ "Produce", "a", "dictionary", "from", "a", "supplied", "object", "." ]
[ "\"\"\"Produce a dictionary from a supplied object. Optionally exclude a specific value or type from the output\n\n Examples\n --------\n >>> DictFactory.factory({'x': 0, 'y': None}, exclude=None)\n {'x': 0}\n >>> DictFactory.factory([('x', 0), ('y', None)], exclude=int)\n ...
[ { "param": "obj", "type": "Union[Dict, Sequence[Tuple[Hashable, Any]]]" }, { "param": "exclude", "type": "Optional[Any]" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "obj", "type": "Union[Dict, Sequence[Tuple[Hashable, Any]]]", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "exclude", "type": "Optional[Any]"...
aae5575d269ff6b5466fb55e08a763147feb040d
seandstewart/que
que/util.py
[ "MIT" ]
Python
isnamedtuple
bool
def isnamedtuple(x: Any) -> bool: """Test whether an object is a named-tuple. Named tuples are essentially extended tuples and instance checks don't work. The best thing you can do is just test if they have the special attributes that differentiate it from a standard tuple. Examples ------ ...
Test whether an object is a named-tuple. Named tuples are essentially extended tuples and instance checks don't work. The best thing you can do is just test if they have the special attributes that differentiate it from a standard tuple. Examples ------ >>> from collections import namedtuple ...
Test whether an object is a named-tuple. Named tuples are essentially extended tuples and instance checks don't work. The best thing you can do is just test if they have the special attributes that differentiate it from a standard tuple. Examples
[ "Test", "whether", "an", "object", "is", "a", "named", "-", "tuple", ".", "Named", "tuples", "are", "essentially", "extended", "tuples", "and", "instance", "checks", "don", "'", "t", "work", ".", "The", "best", "thing", "you", "can", "do", "is", "just", ...
def isnamedtuple(x: Any) -> bool: return isinstance(x, tuple) and hasattr(x, "_fields") and hasattr(x, "_asdict")
[ "def", "isnamedtuple", "(", "x", ":", "Any", ")", "->", "bool", ":", "return", "isinstance", "(", "x", ",", "tuple", ")", "and", "hasattr", "(", "x", ",", "\"_fields\"", ")", "and", "hasattr", "(", "x", ",", "\"_asdict\"", ")" ]
Test whether an object is a named-tuple.
[ "Test", "whether", "an", "object", "is", "a", "named", "-", "tuple", "." ]
[ "\"\"\"Test whether an object is a named-tuple.\n\n Named tuples are essentially extended tuples and instance checks don't work.\n The best thing you can do is just test if they have the special attributes that\n differentiate it from a standard tuple.\n\n Examples\n ------\n >>> from collections ...
[ { "param": "x", "type": "Any" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "x", "type": "Any", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
c8bcfb6f6c365c9b30ca359114615132c6946e13
90michaeltran/usbinfo
usbinfo/linux.py
[ "Apache-2.0" ]
Python
usbinfo
<not_specific>
def usbinfo(): """ Helper for usbinfo on Linux. """ info_list = [] _mounts = get_mounts() context = pyudev.Context() devices = context.list_devices().match_property('ID_BUS', 'usb') device_it = devices.__iter__() while True: try: # We need to manually get the...
Helper for usbinfo on Linux.
Helper for usbinfo on Linux.
[ "Helper", "for", "usbinfo", "on", "Linux", "." ]
def usbinfo(): info_list = [] _mounts = get_mounts() context = pyudev.Context() devices = context.list_devices().match_property('ID_BUS', 'usb') device_it = devices.__iter__() while True: try: device = next(device_it) except pyudev.device.DeviceNotFoundError: ...
[ "def", "usbinfo", "(", ")", ":", "info_list", "=", "[", "]", "_mounts", "=", "get_mounts", "(", ")", "context", "=", "pyudev", ".", "Context", "(", ")", "devices", "=", "context", ".", "list_devices", "(", ")", ".", "match_property", "(", "'ID_BUS'", "...
Helper for usbinfo on Linux.
[ "Helper", "for", "usbinfo", "on", "Linux", "." ]
[ "\"\"\"\n Helper for usbinfo on Linux.\n \"\"\"", "# We need to manually get the next item in the iterator because", "# pyudev.device may throw an exception" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
7f08451858894973273cd9466401c29b3c51eeca
90michaeltran/usbinfo
usbinfo/__init__.py
[ "Apache-2.0" ]
Python
usbinfo
<not_specific>
def usbinfo(): """ This returns a list of USB endpoints attached to the system. Each entry in this list contains a dictionary containing information pertaining to that endpoint. :returns: A list of dictionaries representing each USB endpoint containing the following keys: *...
This returns a list of USB endpoints attached to the system. Each entry in this list contains a dictionary containing information pertaining to that endpoint. :returns: A list of dictionaries representing each USB endpoint containing the following keys: * ``idVendor`` -- USB v...
This returns a list of USB endpoints attached to the system. Each entry in this list contains a dictionary containing information pertaining to that endpoint.
[ "This", "returns", "a", "list", "of", "USB", "endpoints", "attached", "to", "the", "system", ".", "Each", "entry", "in", "this", "list", "contains", "a", "dictionary", "containing", "information", "pertaining", "to", "that", "endpoint", "." ]
def usbinfo(): return __usbinfo()
[ "def", "usbinfo", "(", ")", ":", "return", "__usbinfo", "(", ")" ]
This returns a list of USB endpoints attached to the system.
[ "This", "returns", "a", "list", "of", "USB", "endpoints", "attached", "to", "the", "system", "." ]
[ "\"\"\"\n This returns a list of USB endpoints attached to the system. Each entry\n in this list contains a dictionary containing information pertaining to\n that endpoint.\n\n :returns:\n A list of dictionaries representing each USB endpoint containing the\n following keys:\n\n * `...
[]
{ "returns": [ { "docstring": "A list of dictionaries representing each USB endpoint containing the\nfollowing keys.\n\n``idVendor`` -- USB vendor ID of device.\n``idProduct`` -- USB product ID of device.\n``iManufacturer`` -- Name of manufacturer of device.\n``iProduct`` -- Common name of of device.\n``bIn...
09bf2b649e46f0c9bdf35fe28f587127cb147f10
90michaeltran/usbinfo
usbinfo/darwin.py
[ "Apache-2.0" ]
Python
_sanitize_xml
<not_specific>
def _sanitize_xml(data): """Takes an plist (xml) and checks <string> defintions for control characters. If a control character is found, the string is converted to hexidecimal. For ST-Link devices, this properly displays the serial number, which is eroneously encoded as binary data, which cau...
Takes an plist (xml) and checks <string> defintions for control characters. If a control character is found, the string is converted to hexidecimal. For ST-Link devices, this properly displays the serial number, which is eroneously encoded as binary data, which causes the plistlib XML parser ...
Takes an plist (xml) and checks defintions for control characters. If a control character is found, the string is converted to hexidecimal. For ST-Link devices, this properly displays the serial number, which is eroneously encoded as binary data, which causes the plistlib XML parser to crash. Returns the same documen...
[ "Takes", "an", "plist", "(", "xml", ")", "and", "checks", "defintions", "for", "control", "characters", ".", "If", "a", "control", "character", "is", "found", "the", "string", "is", "converted", "to", "hexidecimal", ".", "For", "ST", "-", "Link", "devices"...
def _sanitize_xml(data): output = [] data = data.decode('utf-8') for i, line in enumerate(data.split('\n')): chunk = line match = re.match(sanitize_pattern, chunk) if match: start = match.group(1) middle = match.group(2) end = match.group(3) ...
[ "def", "_sanitize_xml", "(", "data", ")", ":", "output", "=", "[", "]", "data", "=", "data", ".", "decode", "(", "'utf-8'", ")", "for", "i", ",", "line", "in", "enumerate", "(", "data", ".", "split", "(", "'\\n'", ")", ")", ":", "chunk", "=", "li...
Takes an plist (xml) and checks <string> defintions for control characters.
[ "Takes", "an", "plist", "(", "xml", ")", "and", "checks", "<string", ">", "defintions", "for", "control", "characters", "." ]
[ "\"\"\"Takes an plist (xml) and checks <string> defintions for control characters.\n\n If a control character is found, the string is converted to hexidecimal.\n For ST-Link devices, this properly displays the serial number, which \n is eroneously encoded as binary data, which causes the plistlib ...
[ { "param": "data", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "data", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
09bf2b649e46f0c9bdf35fe28f587127cb147f10
90michaeltran/usbinfo
usbinfo/darwin.py
[ "Apache-2.0" ]
Python
_ioreg_usb_devices
<not_specific>
def _ioreg_usb_devices(nodename=None): """Returns a list of USB device tree from ioreg""" import plistlib def _ioreg(nodename): """Run ioreg command on specific node name""" cmd = ['ioreg', '-a', '-l', '-r', '-n', nodename] output = subprocess.check_output(cmd) # ST-Link dev...
Returns a list of USB device tree from ioreg
Returns a list of USB device tree from ioreg
[ "Returns", "a", "list", "of", "USB", "device", "tree", "from", "ioreg" ]
def _ioreg_usb_devices(nodename=None): import plistlib def _ioreg(nodename): cmd = ['ioreg', '-a', '-l', '-r', '-n', nodename] output = subprocess.check_output(cmd) output = _sanitize_xml(output) plist_data = [] if output: try: plist_data = pli...
[ "def", "_ioreg_usb_devices", "(", "nodename", "=", "None", ")", ":", "import", "plistlib", "def", "_ioreg", "(", "nodename", ")", ":", "\"\"\"Run ioreg command on specific node name\"\"\"", "cmd", "=", "[", "'ioreg'", ",", "'-a'", ",", "'-l'", ",", "'-r'", ",", ...
Returns a list of USB device tree from ioreg
[ "Returns", "a", "list", "of", "USB", "device", "tree", "from", "ioreg" ]
[ "\"\"\"Returns a list of USB device tree from ioreg\"\"\"", "\"\"\"Run ioreg command on specific node name\"\"\"", "# ST-Link devices (and possibly others?) erroneously store binary data", "# in the <string> serial number, which causes plistlib to blow up.", "# This will convert that to hex and preserve con...
[ { "param": "nodename", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "nodename", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
09bf2b649e46f0c9bdf35fe28f587127cb147f10
90michaeltran/usbinfo
usbinfo/darwin.py
[ "Apache-2.0" ]
Python
_ioreg
<not_specific>
def _ioreg(nodename): """Run ioreg command on specific node name""" cmd = ['ioreg', '-a', '-l', '-r', '-n', nodename] output = subprocess.check_output(cmd) # ST-Link devices (and possibly others?) erroneously store binary data # in the <string> serial number, which causes plistli...
Run ioreg command on specific node name
Run ioreg command on specific node name
[ "Run", "ioreg", "command", "on", "specific", "node", "name" ]
def _ioreg(nodename): cmd = ['ioreg', '-a', '-l', '-r', '-n', nodename] output = subprocess.check_output(cmd) output = _sanitize_xml(output) plist_data = [] if output: try: plist_data = plistlib.readPlistFromString(output) except AttributeE...
[ "def", "_ioreg", "(", "nodename", ")", ":", "cmd", "=", "[", "'ioreg'", ",", "'-a'", ",", "'-l'", ",", "'-r'", ",", "'-n'", ",", "nodename", "]", "output", "=", "subprocess", ".", "check_output", "(", "cmd", ")", "output", "=", "_sanitize_xml", "(", ...
Run ioreg command on specific node name
[ "Run", "ioreg", "command", "on", "specific", "node", "name" ]
[ "\"\"\"Run ioreg command on specific node name\"\"\"", "# ST-Link devices (and possibly others?) erroneously store binary data", "# in the <string> serial number, which causes plistlib to blow up.", "# This will convert that to hex and preserve contents otherwise." ]
[ { "param": "nodename", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "nodename", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
09bf2b649e46f0c9bdf35fe28f587127cb147f10
90michaeltran/usbinfo
usbinfo/darwin.py
[ "Apache-2.0" ]
Python
usbinfo
<not_specific>
def usbinfo(): """Return a list of device and interface information for each USB device. """ info_list = [] _mounts = get_mounts() if OSX_VERSION_MINOR_INT >= 11: _el_capitan_extras = \ _ioreg_usb_devices('XHC1') + _ioreg_usb_devices('EHC1') for node in _ioreg_usb_devi...
Return a list of device and interface information for each USB device.
Return a list of device and interface information for each USB device.
[ "Return", "a", "list", "of", "device", "and", "interface", "information", "for", "each", "USB", "device", "." ]
def usbinfo(): info_list = [] _mounts = get_mounts() if OSX_VERSION_MINOR_INT >= 11: _el_capitan_extras = \ _ioreg_usb_devices('XHC1') + _ioreg_usb_devices('EHC1') for node in _ioreg_usb_devices(): try: vid = node['idVendor'] pid = node['idProduct'...
[ "def", "usbinfo", "(", ")", ":", "info_list", "=", "[", "]", "_mounts", "=", "get_mounts", "(", ")", "if", "OSX_VERSION_MINOR_INT", ">=", "11", ":", "_el_capitan_extras", "=", "_ioreg_usb_devices", "(", "'XHC1'", ")", "+", "_ioreg_usb_devices", "(", "'EHC1'", ...
Return a list of device and interface information for each USB device.
[ "Return", "a", "list", "of", "device", "and", "interface", "information", "for", "each", "USB", "device", "." ]
[ "\"\"\"Return a list of device and interface information for each USB device.\n \"\"\"", "# Capture device-level information", "# If idVendor or idProduct is not set, it's not a real USB device.", "# This really shouldn't happen.", "# Ignore Unicode characters", "# USB device, not interface", "# For ...
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
1f81df0d2af2b566a8c5deb6f76c603e368e13bc
MKolman/list-partiotioner
partitions.py
[ "MIT" ]
Python
make_partitions
<not_specific>
def make_partitions(data, min_size=2, max_size=-1, multiplier=0): """Partitions data into multiple bins. Args: data (list<float/int>): data to be partitioned min_size (int): Minimum number of elements in a single partition; must be at least 2 max_size (int): Maximum number of...
Partitions data into multiple bins. Args: data (list<float/int>): data to be partitioned min_size (int): Minimum number of elements in a single partition; must be at least 2 max_size (int): Maximum number of elements in a single partition; must be at least min_size or...
Partitions data into multiple bins.
[ "Partitions", "data", "into", "multiple", "bins", "." ]
def make_partitions(data, min_size=2, max_size=-1, multiplier=0): if max_size < 0: max_size = len(data) assert 2 <= min_size <= len(data), \ "min_size must be at least 2 but not bigger than all of data" assert min_size <= max_size, "max_size must be at least min_size" memo = [False for _...
[ "def", "make_partitions", "(", "data", ",", "min_size", "=", "2", ",", "max_size", "=", "-", "1", ",", "multiplier", "=", "0", ")", ":", "if", "max_size", "<", "0", ":", "max_size", "=", "len", "(", "data", ")", "assert", "2", "<=", "min_size", "<=...
Partitions data into multiple bins.
[ "Partitions", "data", "into", "multiple", "bins", "." ]
[ "\"\"\"Partitions data into multiple bins.\n Args:\n data (list<float/int>): data to be partitioned\n min_size (int): Minimum number of elements in a single partition; must\n be at least 2\n max_size (int): Maximum number of elements in a single partition; must\n be at ...
[ { "param": "data", "type": null }, { "param": "min_size", "type": null }, { "param": "max_size", "type": null }, { "param": "multiplier", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": "list<list<float/int>>" } ], "raises": [], "params": [ { "identifier": "data", "type": null, "docstring": "data to be partitioned", "docstring_tokens": [ "data"...
1ca68092101829c51ad61502a84476733374a3e6
rohanaras/bus_bunching
data_collection.py
[ "MIT" ]
Python
inputData
null
def inputData(): """ currently puts data in a localhost db """ import mysql.connector config = { 'user': 'testUser', 'password': 'anything', 'host': '127.0.0.1', 'database': 'TestOBA' } try: cnx = mysql.connector.connect(**config) test_sql(cn...
currently puts data in a localhost db
currently puts data in a localhost db
[ "currently", "puts", "data", "in", "a", "localhost", "db" ]
def inputData(): import mysql.connector config = { 'user': 'testUser', 'password': 'anything', 'host': '127.0.0.1', 'database': 'TestOBA' } try: cnx = mysql.connector.connect(**config) test_sql(cnx) except mysql.connector.Error as err: if err.e...
[ "def", "inputData", "(", ")", ":", "import", "mysql", ".", "connector", "config", "=", "{", "'user'", ":", "'testUser'", ",", "'password'", ":", "'anything'", ",", "'host'", ":", "'127.0.0.1'", ",", "'database'", ":", "'TestOBA'", "}", "try", ":", "cnx", ...
currently puts data in a localhost db
[ "currently", "puts", "data", "in", "a", "localhost", "db" ]
[ "\"\"\"\n currently puts data in a localhost db\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
d80da935a3e75714c4dd641a9ca01df9d13f71f2
giantoak/unicorn
app/views.py
[ "MIT" ]
Python
bulk_search_route
<not_specific>
def bulk_search_route(): """ Bulk search all of these queries :return: Excel file bundling query responses """ search_results = request.form['searches'] searches = search_results.split('\n') data = bulk_search(searches) return send_file(io.BytesIO(data.xls), as_attachment=True, ...
Bulk search all of these queries :return: Excel file bundling query responses
Bulk search all of these queries
[ "Bulk", "search", "all", "of", "these", "queries" ]
def bulk_search_route(): search_results = request.form['searches'] searches = search_results.split('\n') data = bulk_search(searches) return send_file(io.BytesIO(data.xls), as_attachment=True, attachment_filename='bulk_{}.xls'.format(time.time()))
[ "def", "bulk_search_route", "(", ")", ":", "search_results", "=", "request", ".", "form", "[", "'searches'", "]", "searches", "=", "search_results", ".", "split", "(", "'\\n'", ")", "data", "=", "bulk_search", "(", "searches", ")", "return", "send_file", "("...
Bulk search all of these queries
[ "Bulk", "search", "all", "of", "these", "queries" ]
[ "\"\"\"\n Bulk search all of these queries\n :return: Excel file bundling query responses\n \"\"\"" ]
[]
{ "returns": [ { "docstring": "Excel file bundling query responses", "docstring_tokens": [ "Excel", "file", "bundling", "query", "responses" ], "type": null } ], "raises": [], "params": [], "outlier_params": [], "others": [] }
d80da935a3e75714c4dd641a9ca01df9d13f71f2
giantoak/unicorn
app/views.py
[ "MIT" ]
Python
request_doc
<not_specific>
def request_doc(doc_id): """ Searches elastic index for a document matching a particular ID. :param str doc_id: A specific document ID :return: results of elastic search matching doc_id """ q = { "query": { "match": { "_id": doc_id } }, ...
Searches elastic index for a document matching a particular ID. :param str doc_id: A specific document ID :return: results of elastic search matching doc_id
Searches elastic index for a document matching a particular ID.
[ "Searches", "elastic", "index", "for", "a", "document", "matching", "a", "particular", "ID", "." ]
def request_doc(doc_id): q = { "query": { "match": { "_id": doc_id } }, } return es.search(body=q, index=es_index)
[ "def", "request_doc", "(", "doc_id", ")", ":", "q", "=", "{", "\"query\"", ":", "{", "\"match\"", ":", "{", "\"_id\"", ":", "doc_id", "}", "}", ",", "}", "return", "es", ".", "search", "(", "body", "=", "q", ",", "index", "=", "es_index", ")" ]
Searches elastic index for a document matching a particular ID.
[ "Searches", "elastic", "index", "for", "a", "document", "matching", "a", "particular", "ID", "." ]
[ "\"\"\"\n Searches elastic index for a document matching a particular ID.\n :param str doc_id: A specific document ID\n :return: results of elastic search matching doc_id\n \"\"\"" ]
[ { "param": "doc_id", "type": null } ]
{ "returns": [ { "docstring": "results of elastic search matching doc_id", "docstring_tokens": [ "results", "of", "elastic", "search", "matching", "doc_id" ], "type": null } ], "raises": [], "params": [ { "identifier": "do...
d80da935a3e75714c4dd641a9ca01df9d13f71f2
giantoak/unicorn
app/views.py
[ "MIT" ]
Python
view_doc
<not_specific>
def view_doc(doc_id): """ In-depth view of a particular document. Displays PDF version of document, extracted entities, and other analytics. :param str doc_id: A specific document ID :return: rendered template for the current document """ if is_owner_of_doc(doc_id): return render_tem...
In-depth view of a particular document. Displays PDF version of document, extracted entities, and other analytics. :param str doc_id: A specific document ID :return: rendered template for the current document
In-depth view of a particular document. Displays PDF version of document, extracted entities, and other analytics.
[ "In", "-", "depth", "view", "of", "a", "particular", "document", ".", "Displays", "PDF", "version", "of", "document", "extracted", "entities", "and", "other", "analytics", "." ]
def view_doc(doc_id): if is_owner_of_doc(doc_id): return render_template('doc-view.html', doc_id=doc_id) return abort(403)
[ "def", "view_doc", "(", "doc_id", ")", ":", "if", "is_owner_of_doc", "(", "doc_id", ")", ":", "return", "render_template", "(", "'doc-view.html'", ",", "doc_id", "=", "doc_id", ")", "return", "abort", "(", "403", ")" ]
In-depth view of a particular document.
[ "In", "-", "depth", "view", "of", "a", "particular", "document", "." ]
[ "\"\"\"\n In-depth view of a particular document. Displays PDF version of document,\n extracted entities, and other analytics.\n :param str doc_id: A specific document ID\n :return: rendered template for the current document\n \"\"\"" ]
[ { "param": "doc_id", "type": null } ]
{ "returns": [ { "docstring": "rendered template for the current document", "docstring_tokens": [ "rendered", "template", "for", "the", "current", "document" ], "type": null } ], "raises": [], "params": [ { "identifier": "...
d80da935a3e75714c4dd641a9ca01df9d13f71f2
giantoak/unicorn
app/views.py
[ "MIT" ]
Python
history_query
<not_specific>
def history_query(): """ AND query over all active history terms """ terms = active_history_terms(session['history']) body = { "_source": ["entity"], "fields": ["entities", "title"], "query": { "constant_score": { "filter": { "t...
AND query over all active history terms
AND query over all active history terms
[ "AND", "query", "over", "all", "active", "history", "terms" ]
def history_query(): terms = active_history_terms(session['history']) body = { "_source": ["entity"], "fields": ["entities", "title"], "query": { "constant_score": { "filter": { "terms": { "file": terms, ...
[ "def", "history_query", "(", ")", ":", "terms", "=", "active_history_terms", "(", "session", "[", "'history'", "]", ")", "body", "=", "{", "\"_source\"", ":", "[", "\"entity\"", "]", ",", "\"fields\"", ":", "[", "\"entities\"", ",", "\"title\"", "]", ",", ...
AND query over all active history terms
[ "AND", "query", "over", "all", "active", "history", "terms" ]
[ "\"\"\"\n AND query over all active history terms\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
d80da935a3e75714c4dd641a9ca01df9d13f71f2
giantoak/unicorn
app/views.py
[ "MIT" ]
Python
upload_endpoint
<not_specific>
def upload_endpoint(): """ Takes a document and stores it in the elasticsearch index """ files = request.files.getlist('file[]') d = {} for f in files: sf = secure_filename(f.filename) es_dict = { 'file': f.read().encode('base64'), 'title': sf, ...
Takes a document and stores it in the elasticsearch index
Takes a document and stores it in the elasticsearch index
[ "Takes", "a", "document", "and", "stores", "it", "in", "the", "elasticsearch", "index" ]
def upload_endpoint(): files = request.files.getlist('file[]') d = {} for f in files: sf = secure_filename(f.filename) es_dict = { 'file': f.read().encode('base64'), 'title': sf, 'owner': 'blank' } es.index(index=es_index, doc_type='attac...
[ "def", "upload_endpoint", "(", ")", ":", "files", "=", "request", ".", "files", ".", "getlist", "(", "'file[]'", ")", "d", "=", "{", "}", "for", "f", "in", "files", ":", "sf", "=", "secure_filename", "(", "f", ".", "filename", ")", "es_dict", "=", ...
Takes a document and stores it in the elasticsearch index
[ "Takes", "a", "document", "and", "stores", "it", "in", "the", "elasticsearch", "index" ]
[ "\"\"\"\n Takes a document and stores it in the elasticsearch index\n \"\"\"", "# current_owner.organization.organization" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
d80da935a3e75714c4dd641a9ca01df9d13f71f2
giantoak/unicorn
app/views.py
[ "MIT" ]
Python
is_owner_of_doc
<not_specific>
def is_owner_of_doc(doc): """ Function for checking document ownership. SINCE WE ARE KEEPING ACCESS CONTROL SIMPLE, WE ARE DEFAULTING THIS TO TRUE :param str doc: A specific document ID :return bool: whether the document's owner matches the current owner """ # owner = es.get(index=es_index, ...
Function for checking document ownership. SINCE WE ARE KEEPING ACCESS CONTROL SIMPLE, WE ARE DEFAULTING THIS TO TRUE :param str doc: A specific document ID :return bool: whether the document's owner matches the current owner
Function for checking document ownership.
[ "Function", "for", "checking", "document", "ownership", "." ]
def is_owner_of_doc(doc): return True
[ "def", "is_owner_of_doc", "(", "doc", ")", ":", "return", "True" ]
Function for checking document ownership.
[ "Function", "for", "checking", "document", "ownership", "." ]
[ "\"\"\"\n Function for checking document ownership.\n SINCE WE ARE KEEPING ACCESS CONTROL SIMPLE, WE ARE DEFAULTING THIS TO TRUE\n :param str doc: A specific document ID\n :return bool: whether the document's owner matches the current owner\n \"\"\"", "# owner = es.get(index=es_index, doc_type='att...
[ { "param": "doc", "type": null } ]
{ "returns": [ { "docstring": "whether the document's owner matches the current owner", "docstring_tokens": [ "whether", "the", "document", "'", "s", "owner", "matches", "the", "current", "owner" ], "type": "bo...
7433ce014a839c415206e6f066d3786441253b14
giantoak/unicorn
app/bulk.py
[ "MIT" ]
Python
bulk_download
<not_specific>
def bulk_download(ids): """ Construct ElasticSearch query for all files, return tablib Dataset. :param ids: :return tablib.Dataset: """ data = tablib.Dataset(headers=['title', 'text']) for doc_id in ids: # Grab file for doc_id r = es.get(index=es_index, doc_type="attachment"...
Construct ElasticSearch query for all files, return tablib Dataset. :param ids: :return tablib.Dataset:
Construct ElasticSearch query for all files, return tablib Dataset.
[ "Construct", "ElasticSearch", "query", "for", "all", "files", "return", "tablib", "Dataset", "." ]
def bulk_download(ids): data = tablib.Dataset(headers=['title', 'text']) for doc_id in ids: r = es.get(index=es_index, doc_type="attachment", id=doc_id, fields=['title', 'file']) f = r['fields'] data.append((f['title'][0], f['file'][0])) return data
[ "def", "bulk_download", "(", "ids", ")", ":", "data", "=", "tablib", ".", "Dataset", "(", "headers", "=", "[", "'title'", ",", "'text'", "]", ")", "for", "doc_id", "in", "ids", ":", "r", "=", "es", ".", "get", "(", "index", "=", "es_index", ",", ...
Construct ElasticSearch query for all files, return tablib Dataset.
[ "Construct", "ElasticSearch", "query", "for", "all", "files", "return", "tablib", "Dataset", "." ]
[ "\"\"\"\n Construct ElasticSearch query for all files, return tablib Dataset.\n :param ids:\n :return tablib.Dataset:\n \"\"\"", "# Grab file for doc_id", "# return file" ]
[ { "param": "ids", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": "tablib.Dataset" } ], "raises": [], "params": [ { "identifier": "ids", "type": null, "docstring": null, "docstring_tokens": [ "None" ], "default": n...
95953093d5e4f64f61fbdec0eb5fa61852910dad
giantoak/unicorn
app/corex.py
[ "MIT" ]
Python
events_from_samples
<not_specific>
def events_from_samples(self, X): """Transform data into event format. See event_from_sample docstring.""" n_samples, n_visible = X.shape events_to_transform = np.empty((self.n_events, n_samples), dtype=bool) for l, x in enumerate(X): events_to_transform[:, l] = self.event_fr...
Transform data into event format. See event_from_sample docstring.
Transform data into event format.
[ "Transform", "data", "into", "event", "format", "." ]
def events_from_samples(self, X): n_samples, n_visible = X.shape events_to_transform = np.empty((self.n_events, n_samples), dtype=bool) for l, x in enumerate(X): events_to_transform[:, l] = self.event_from_sample(x) return events_to_transform
[ "def", "events_from_samples", "(", "self", ",", "X", ")", ":", "n_samples", ",", "n_visible", "=", "X", ".", "shape", "events_to_transform", "=", "np", ".", "empty", "(", "(", "self", ".", "n_events", ",", "n_samples", ")", ",", "dtype", "=", "bool", "...
Transform data into event format.
[ "Transform", "data", "into", "event", "format", "." ]
[ "\"\"\"Transform data into event format. See event_from_sample docstring.\"\"\"" ]
[ { "param": "self", "type": null }, { "param": "X", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "X", "type": null, "docstring": null, "docstring_tokens": [], ...
95953093d5e4f64f61fbdec0eb5fa61852910dad
giantoak/unicorn
app/corex.py
[ "MIT" ]
Python
calculate_p_y_xi
<not_specific>
def calculate_p_y_xi(self, X_event, p_y_given_x): """Estimate log p(y_j|x_i) using a tiny bit of Laplace smoothing to avoid infinities.""" pseudo_counts = 0.001 + np.dot(X_event, p_y_given_x).transpose((1,0,2)) # n_hidden, n_events, dim_hidden log_marg = np.log(pseudo_counts) - np.log(np.sum(ps...
Estimate log p(y_j|x_i) using a tiny bit of Laplace smoothing to avoid infinities.
Estimate log p(y_j|x_i) using a tiny bit of Laplace smoothing to avoid infinities.
[ "Estimate", "log", "p", "(", "y_j|x_i", ")", "using", "a", "tiny", "bit", "of", "Laplace", "smoothing", "to", "avoid", "infinities", "." ]
def calculate_p_y_xi(self, X_event, p_y_given_x): pseudo_counts = 0.001 + np.dot(X_event, p_y_given_x).transpose((1,0,2)) log_marg = np.log(pseudo_counts) - np.log(np.sum(pseudo_counts, axis=2, keepdims=True)) return log_marg
[ "def", "calculate_p_y_xi", "(", "self", ",", "X_event", ",", "p_y_given_x", ")", ":", "pseudo_counts", "=", "0.001", "+", "np", ".", "dot", "(", "X_event", ",", "p_y_given_x", ")", ".", "transpose", "(", "(", "1", ",", "0", ",", "2", ")", ")", "log_m...
Estimate log p(y_j|x_i) using a tiny bit of Laplace smoothing to avoid infinities.
[ "Estimate", "log", "p", "(", "y_j|x_i", ")", "using", "a", "tiny", "bit", "of", "Laplace", "smoothing", "to", "avoid", "infinities", "." ]
[ "\"\"\"Estimate log p(y_j|x_i) using a tiny bit of Laplace smoothing to avoid infinities.\"\"\"", "# n_hidden, n_events, dim_hidden" ]
[ { "param": "self", "type": null }, { "param": "X_event", "type": null }, { "param": "p_y_given_x", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "X_event", "type": null, "docstring": null, "docstring_tokens"...
95953093d5e4f64f61fbdec0eb5fa61852910dad
giantoak/unicorn
app/corex.py
[ "MIT" ]
Python
calculate_latent
<not_specific>
def calculate_latent(self, X_event): """"Calculate the probability distribution for hidden factors for each sample.""" alpha_rep = np.repeat(self.alpha, self.dim_visible, axis=1) log_p_y_given_x_unnorm = (1. - self.balance) * self.log_p_y + np.transpose(np.dot(X_event.T, alpha_rep*self.log_marg)...
Calculate the probability distribution for hidden factors for each sample.
Calculate the probability distribution for hidden factors for each sample.
[ "Calculate", "the", "probability", "distribution", "for", "hidden", "factors", "for", "each", "sample", "." ]
def calculate_latent(self, X_event): alpha_rep = np.repeat(self.alpha, self.dim_visible, axis=1) log_p_y_given_x_unnorm = (1. - self.balance) * self.log_p_y + np.transpose(np.dot(X_event.T, alpha_rep*self.log_marg), (1, 0, 2)) return self.normalize_latent(log_p_y_given_x_unnorm)
[ "def", "calculate_latent", "(", "self", ",", "X_event", ")", ":", "alpha_rep", "=", "np", ".", "repeat", "(", "self", ".", "alpha", ",", "self", ".", "dim_visible", ",", "axis", "=", "1", ")", "log_p_y_given_x_unnorm", "=", "(", "1.", "-", "self", ".",...
Calculate the probability distribution for hidden factors for each sample.
[ "Calculate", "the", "probability", "distribution", "for", "hidden", "factors", "for", "each", "sample", "." ]
[ "\"\"\"\"Calculate the probability distribution for hidden factors for each sample.\"\"\"" ]
[ { "param": "self", "type": null }, { "param": "X_event", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "X_event", "type": null, "docstring": null, "docstring_tokens"...
50fb09e25262a6d12a59f768a2248daef21eb861
giantoak/unicorn
app/util/round_time.py
[ "MIT" ]
Python
round_month_up
<not_specific>
def round_month_up(origin_date): """ Takes a datetime object and rounds up to the nearest month. E.g. 2/14/2013 becomes 3/1/2013 :param datetime.datetime origin_date: :return datetime.datetime: """ from datetime import datetime from datetime import timedelta day = origin_date.day ...
Takes a datetime object and rounds up to the nearest month. E.g. 2/14/2013 becomes 3/1/2013 :param datetime.datetime origin_date: :return datetime.datetime:
Takes a datetime object and rounds up to the nearest month.
[ "Takes", "a", "datetime", "object", "and", "rounds", "up", "to", "the", "nearest", "month", "." ]
def round_month_up(origin_date): from datetime import datetime from datetime import timedelta day = origin_date.day month = origin_date.month year = origin_date.year if origin_date.month == 12: delta = datetime(year + 1, 1, day) - origin_date else: delta = datetime(year, mont...
[ "def", "round_month_up", "(", "origin_date", ")", ":", "from", "datetime", "import", "datetime", "from", "datetime", "import", "timedelta", "day", "=", "origin_date", ".", "day", "month", "=", "origin_date", ".", "month", "year", "=", "origin_date", ".", "year...
Takes a datetime object and rounds up to the nearest month.
[ "Takes", "a", "datetime", "object", "and", "rounds", "up", "to", "the", "nearest", "month", "." ]
[ "\"\"\"\n Takes a datetime object and rounds up to the nearest month.\n E.g. 2/14/2013 becomes 3/1/2013\n :param datetime.datetime origin_date:\n :return datetime.datetime:\n \"\"\"" ]
[ { "param": "origin_date", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": "datetime.datetime" } ], "raises": [], "params": [ { "identifier": "origin_date", "type": null, "docstring": null, "docstring_tokens": [ "None" ], "...
50fb09e25262a6d12a59f768a2248daef21eb861
giantoak/unicorn
app/util/round_time.py
[ "MIT" ]
Python
round_month_down
<not_specific>
def round_month_down(origin_date): """ Takes a datetime object and rounds down to the nearest month. E.g. 2/14/2013 becomes 2/1/2013 :param datetime.datetime origin_date: :return datetime.datetime: """ down_time = origin_date - timedelta(days=origin_date.day - 1) return down_time
Takes a datetime object and rounds down to the nearest month. E.g. 2/14/2013 becomes 2/1/2013 :param datetime.datetime origin_date: :return datetime.datetime:
Takes a datetime object and rounds down to the nearest month.
[ "Takes", "a", "datetime", "object", "and", "rounds", "down", "to", "the", "nearest", "month", "." ]
def round_month_down(origin_date): down_time = origin_date - timedelta(days=origin_date.day - 1) return down_time
[ "def", "round_month_down", "(", "origin_date", ")", ":", "down_time", "=", "origin_date", "-", "timedelta", "(", "days", "=", "origin_date", ".", "day", "-", "1", ")", "return", "down_time" ]
Takes a datetime object and rounds down to the nearest month.
[ "Takes", "a", "datetime", "object", "and", "rounds", "down", "to", "the", "nearest", "month", "." ]
[ "\"\"\"\n Takes a datetime object and rounds down to the nearest month.\n E.g. 2/14/2013 becomes 2/1/2013\n :param datetime.datetime origin_date:\n :return datetime.datetime:\n \"\"\"" ]
[ { "param": "origin_date", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": "datetime.datetime" } ], "raises": [], "params": [ { "identifier": "origin_date", "type": null, "docstring": null, "docstring_tokens": [ "None" ], "...
50fb09e25262a6d12a59f768a2248daef21eb861
giantoak/unicorn
app/util/round_time.py
[ "MIT" ]
Python
week_delta
<not_specific>
def week_delta(start, stop): """ Takes two datetime objects and returns number of weeks between them :param datetime.datetime start: :param datetime.datetime stop: :return int: """ delta = (stop - start) / 7 return delta.days
Takes two datetime objects and returns number of weeks between them :param datetime.datetime start: :param datetime.datetime stop: :return int:
Takes two datetime objects and returns number of weeks between them
[ "Takes", "two", "datetime", "objects", "and", "returns", "number", "of", "weeks", "between", "them" ]
def week_delta(start, stop): delta = (stop - start) / 7 return delta.days
[ "def", "week_delta", "(", "start", ",", "stop", ")", ":", "delta", "=", "(", "stop", "-", "start", ")", "/", "7", "return", "delta", ".", "days" ]
Takes two datetime objects and returns number of weeks between them
[ "Takes", "two", "datetime", "objects", "and", "returns", "number", "of", "weeks", "between", "them" ]
[ "\"\"\"\n Takes two datetime objects and returns number of weeks between them\n :param datetime.datetime start:\n :param datetime.datetime stop:\n :return int:\n \"\"\"" ]
[ { "param": "start", "type": null }, { "param": "stop", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": "int" } ], "raises": [], "params": [ { "identifier": "start", "type": null, "docstring": null, "docstring_tokens": [ "None" ], "default": null, ...
aef748cb0798cf4de4bd0553be76cbf74ef3fd45
giantoak/unicorn
util/bulk/entities/iterate_search.py
[ "MIT" ]
Python
iterate_over_query
null
def iterate_over_query(query, es, index=es_index, batch_size=10, count=None, count_args=None, **args): """ Uses `scroll` API to iterate over search results :param query: ...
Uses `scroll` API to iterate over search results :param query: :param elasticsearch.Elasticsearch es: :param str index: :param int batch_size: :param count: :param dict count_args:
Uses `scroll` API to iterate over search results
[ "Uses", "`", "scroll", "`", "API", "to", "iterate", "over", "search", "results" ]
def iterate_over_query(query, es, index=es_index, batch_size=10, count=None, count_args=None, **args): if count_args is None: count_args = {} if count is None: ...
[ "def", "iterate_over_query", "(", "query", ",", "es", ",", "index", "=", "es_index", ",", "batch_size", "=", "10", ",", "count", "=", "None", ",", "count_args", "=", "None", ",", "**", "args", ")", ":", "if", "count_args", "is", "None", ":", "count_arg...
Uses `scroll` API to iterate over search results
[ "Uses", "`", "scroll", "`", "API", "to", "iterate", "over", "search", "results" ]
[ "\"\"\"\n Uses `scroll` API to iterate over search results\n :param query:\n :param elasticsearch.Elasticsearch es:\n :param str index:\n :param int batch_size:\n :param count:\n :param dict count_args:\n \"\"\"", "# Initialize scroll scan" ]
[ { "param": "query", "type": null }, { "param": "es", "type": null }, { "param": "index", "type": null }, { "param": "batch_size", "type": null }, { "param": "count", "type": null }, { "param": "count_args", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "query", "type": null, "docstring": null, "docstring_tokens": [ "None" ], "default": null, "is_optional": null }, { "identifier": "es", "type": null, "docstring": null, ...
295daf3c73ae81f87904925b62bb6b58a2981eaf
harrydet/InstaPy
instapy/time_util.py
[ "MIT" ]
Python
rate_limited
<not_specific>
def rate_limited(max_per_hour: int): """Rate-limits the decorated function locally, for one process.""" lock = threading.Lock() min_interval = 3600 / max_per_hour def decorate(func): last_time_called = time.perf_counter() @wraps(func) def rate_limited_function(*args, **kwargs):...
Rate-limits the decorated function locally, for one process.
Rate-limits the decorated function locally, for one process.
[ "Rate", "-", "limits", "the", "decorated", "function", "locally", "for", "one", "process", "." ]
def rate_limited(max_per_hour: int): lock = threading.Lock() min_interval = 3600 / max_per_hour def decorate(func): last_time_called = time.perf_counter() @wraps(func) def rate_limited_function(*args, **kwargs): lock.acquire() nonlocal last_time_called ...
[ "def", "rate_limited", "(", "max_per_hour", ":", "int", ")", ":", "lock", "=", "threading", ".", "Lock", "(", ")", "min_interval", "=", "3600", "/", "max_per_hour", "def", "decorate", "(", "func", ")", ":", "last_time_called", "=", "time", ".", "perf_count...
Rate-limits the decorated function locally, for one process.
[ "Rate", "-", "limits", "the", "decorated", "function", "locally", "for", "one", "process", "." ]
[ "\"\"\"Rate-limits the decorated function locally, for one process.\"\"\"" ]
[ { "param": "max_per_hour", "type": "int" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "max_per_hour", "type": "int", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
efea6b0772662bdf53ffe3169e6e7fd7bf3598a9
c6supper/grpc
tools/run_tests/xds_k8s_test_driver/framework/helpers/skips.py
[ "BSD-3-Clause" ]
Python
version_ge
bool
def version_ge(self, another: str) -> bool: """Returns a bool for whether the version is >= another one. A version is greater than or equal to another version means its version number is greater than or equal to another version's number. Version "master" is always considered latest. E.g...
Returns a bool for whether the version is >= another one. A version is greater than or equal to another version means its version number is greater than or equal to another version's number. Version "master" is always considered latest. E.g., master >= v1.41.x >= v1.40.x >= v1.9.x. ...
Returns a bool for whether the version is >= another one. A version is greater than or equal to another version means its version number is greater than or equal to another version's number. Version "master" is always considered latest.
[ "Returns", "a", "bool", "for", "whether", "the", "version", "is", ">", "=", "another", "one", ".", "A", "version", "is", "greater", "than", "or", "equal", "to", "another", "version", "means", "its", "version", "number", "is", "greater", "than", "or", "eq...
def version_ge(self, another: str) -> bool: if self.version == 'master': return True return _parse_version(self.version) >= _parse_version(another)
[ "def", "version_ge", "(", "self", ",", "another", ":", "str", ")", "->", "bool", ":", "if", "self", ".", "version", "==", "'master'", ":", "return", "True", "return", "_parse_version", "(", "self", ".", "version", ")", ">=", "_parse_version", "(", "anoth...
Returns a bool for whether the version is >= another one.
[ "Returns", "a", "bool", "for", "whether", "the", "version", "is", ">", "=", "another", "one", "." ]
[ "\"\"\"Returns a bool for whether the version is >= another one.\n\n A version is greater than or equal to another version means its version\n number is greater than or equal to another version's number. Version\n \"master\" is always considered latest. E.g., master >= v1.41.x >= v1.40.x\n ...
[ { "param": "self", "type": null }, { "param": "another", "type": "str" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "another", "type": "str", "docstring": null, "docstring_tokens...
a39159aba121b249c9231d072ddfcf90aec4470d
c6supper/grpc
bazel/python_rules.bzl
[ "BSD-3-Clause" ]
Python
py_grpc_library
null
def py_grpc_library( name, srcs, deps, strip_prefixes = [], **kwargs): """Generate python code for gRPC services defined in a protobuf. Args: name: The name of the target. srcs: (List of `labels`) a single proto_library target containing the schema of...
Generate python code for gRPC services defined in a protobuf. Args: name: The name of the target. srcs: (List of `labels`) a single proto_library target containing the schema of the service. deps: (List of `labels`) a single py_proto_library target for the proto_library in `srcs`....
Generate python code for gRPC services defined in a protobuf.
[ "Generate", "python", "code", "for", "gRPC", "services", "defined", "in", "a", "protobuf", "." ]
def py_grpc_library( name, srcs, deps, strip_prefixes = [], **kwargs): if len(srcs) != 1: fail("Can only compile a single proto at a time.") if len(deps) != 1: fail("Deps must have length 1.") _generate_pb2_grpc_src( name = name, deps =...
[ "def", "py_grpc_library", "(", "name", ",", "srcs", ",", "deps", ",", "strip_prefixes", "=", "[", "]", ",", "**", "kwargs", ")", ":", "if", "len", "(", "srcs", ")", "!=", "1", ":", "fail", "(", "\"Can only compile a single proto at a time.\"", ")", "if", ...
Generate python code for gRPC services defined in a protobuf.
[ "Generate", "python", "code", "for", "gRPC", "services", "defined", "in", "a", "protobuf", "." ]
[ "\"\"\"Generate python code for gRPC services defined in a protobuf.\n\n Args:\n name: The name of the target.\n srcs: (List of `labels`) a single proto_library target containing the\n schema of the service.\n deps: (List of `labels`) a single py_proto_library target for the\n proto_...
[ { "param": "name", "type": null }, { "param": "srcs", "type": null }, { "param": "deps", "type": null }, { "param": "strip_prefixes", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "name", "type": null, "docstring": "The name of the target.", "docstring_tokens": [ "The", "name", "of", "the", "target", "." ], "default": null, "is_optional": ...
40e7f105deb049e2d7c92a7876ad3735fd2b48fd
c6supper/grpc
third_party/android/android_configure.bzl
[ "BSD-3-Clause" ]
Python
_escape_for_windows
<not_specific>
def _escape_for_windows(path): """Properly escape backslashes for Windows. Ideally, we would do this conditionally, but there is seemingly no way to determine whether or not this is being called from Windows. """ return path.replace("\\", "\\\\")
Properly escape backslashes for Windows. Ideally, we would do this conditionally, but there is seemingly no way to determine whether or not this is being called from Windows.
Properly escape backslashes for Windows. Ideally, we would do this conditionally, but there is seemingly no way to determine whether or not this is being called from Windows.
[ "Properly", "escape", "backslashes", "for", "Windows", ".", "Ideally", "we", "would", "do", "this", "conditionally", "but", "there", "is", "seemingly", "no", "way", "to", "determine", "whether", "or", "not", "this", "is", "being", "called", "from", "Windows", ...
def _escape_for_windows(path): return path.replace("\\", "\\\\")
[ "def", "_escape_for_windows", "(", "path", ")", ":", "return", "path", ".", "replace", "(", "\"\\\\\"", ",", "\"\\\\\\\\\"", ")" ]
Properly escape backslashes for Windows.
[ "Properly", "escape", "backslashes", "for", "Windows", "." ]
[ "\"\"\"Properly escape backslashes for Windows.\n\n Ideally, we would do this conditionally, but there is seemingly no way to\n determine whether or not this is being called from Windows.\n \"\"\"" ]
[ { "param": "path", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "path", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
4e2ad8e67c1ea35a5180a9f2734557956537dc19
strongit/NewhostInit
useful-scripts/pyutil/pygtail.py
[ "Apache-2.0" ]
Python
next
<not_specific>
def next(self): """ Return the next line in the file, updating the offset. """ try: line = self._get_next_line() except StopIteration: # we've reached the end of the file; if we're processing the # rotated log file or the file has been renamed,...
Return the next line in the file, updating the offset.
Return the next line in the file, updating the offset.
[ "Return", "the", "next", "line", "in", "the", "file", "updating", "the", "offset", "." ]
def next(self): try: line = self._get_next_line() except StopIteration: if self._is_new_file(): self._rotated_logfile = None self._fh.close() self._offset = 0 try: line = self._get_next_line() ...
[ "def", "next", "(", "self", ")", ":", "try", ":", "line", "=", "self", ".", "_get_next_line", "(", ")", "except", "StopIteration", ":", "if", "self", ".", "_is_new_file", "(", ")", ":", "self", ".", "_rotated_logfile", "=", "None", "self", ".", "_fh", ...
Return the next line in the file, updating the offset.
[ "Return", "the", "next", "line", "in", "the", "file", "updating", "the", "offset", "." ]
[ "\"\"\"\n Return the next line in the file, updating the offset.\n \"\"\"", "# we've reached the end of the file; if we're processing the", "# rotated log file or the file has been renamed, we can continue with the actual file; otherwise", "# update the offset file", "# open up current logfile...
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
4e2ad8e67c1ea35a5180a9f2734557956537dc19
strongit/NewhostInit
useful-scripts/pyutil/pygtail.py
[ "Apache-2.0" ]
Python
read
<not_specific>
def read(self): """ Read in all unread lines and return them as a single string. """ lines = self.readlines() if lines: try: return ''.join(lines) except TypeError: return ''.join(force_text(line) for line in lines) ...
Read in all unread lines and return them as a single string.
Read in all unread lines and return them as a single string.
[ "Read", "in", "all", "unread", "lines", "and", "return", "them", "as", "a", "single", "string", "." ]
def read(self): lines = self.readlines() if lines: try: return ''.join(lines) except TypeError: return ''.join(force_text(line) for line in lines) else: return None
[ "def", "read", "(", "self", ")", ":", "lines", "=", "self", ".", "readlines", "(", ")", "if", "lines", ":", "try", ":", "return", "''", ".", "join", "(", "lines", ")", "except", "TypeError", ":", "return", "''", ".", "join", "(", "force_text", "(",...
Read in all unread lines and return them as a single string.
[ "Read", "in", "all", "unread", "lines", "and", "return", "them", "as", "a", "single", "string", "." ]
[ "\"\"\"\n Read in all unread lines and return them as a single string.\n \"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
4e2ad8e67c1ea35a5180a9f2734557956537dc19
strongit/NewhostInit
useful-scripts/pyutil/pygtail.py
[ "Apache-2.0" ]
Python
_filehandle
<not_specific>
def _filehandle(self): """ Return a filehandle to the file being tailed, with the position set to the current offset. """ if not self._fh or self._is_closed(): filename = self._rotated_logfile or self.filename if filename.endswith('.gz'): s...
Return a filehandle to the file being tailed, with the position set to the current offset.
Return a filehandle to the file being tailed, with the position set to the current offset.
[ "Return", "a", "filehandle", "to", "the", "file", "being", "tailed", "with", "the", "position", "set", "to", "the", "current", "offset", "." ]
def _filehandle(self): if not self._fh or self._is_closed(): filename = self._rotated_logfile or self.filename if filename.endswith('.gz'): self._fh = gzip.open(filename, 'r') else: self._fh = open(filename, "r", 1) if self.read_fro...
[ "def", "_filehandle", "(", "self", ")", ":", "if", "not", "self", ".", "_fh", "or", "self", ".", "_is_closed", "(", ")", ":", "filename", "=", "self", ".", "_rotated_logfile", "or", "self", ".", "filename", "if", "filename", ".", "endswith", "(", "'.gz...
Return a filehandle to the file being tailed, with the position set to the current offset.
[ "Return", "a", "filehandle", "to", "the", "file", "being", "tailed", "with", "the", "position", "set", "to", "the", "current", "offset", "." ]
[ "\"\"\"\n Return a filehandle to the file being tailed, with the position set\n to the current offset.\n \"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
4e2ad8e67c1ea35a5180a9f2734557956537dc19
strongit/NewhostInit
useful-scripts/pyutil/pygtail.py
[ "Apache-2.0" ]
Python
_update_offset_file
null
def _update_offset_file(self): """ Update the offset file with the current inode and offset. """ if self.on_update: self.on_update() offset = self._filehandle().tell() inode = stat(self.filename).st_ino fh = open(self._offset_file, "w") fh.writ...
Update the offset file with the current inode and offset.
Update the offset file with the current inode and offset.
[ "Update", "the", "offset", "file", "with", "the", "current", "inode", "and", "offset", "." ]
def _update_offset_file(self): if self.on_update: self.on_update() offset = self._filehandle().tell() inode = stat(self.filename).st_ino fh = open(self._offset_file, "w") fh.write("%s\n%s\n" % (inode, offset)) fh.close() self._since_update = 0
[ "def", "_update_offset_file", "(", "self", ")", ":", "if", "self", ".", "on_update", ":", "self", ".", "on_update", "(", ")", "offset", "=", "self", ".", "_filehandle", "(", ")", ".", "tell", "(", ")", "inode", "=", "stat", "(", "self", ".", "filenam...
Update the offset file with the current inode and offset.
[ "Update", "the", "offset", "file", "with", "the", "current", "inode", "and", "offset", "." ]
[ "\"\"\"\n Update the offset file with the current inode and offset.\n \"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
4e2ad8e67c1ea35a5180a9f2734557956537dc19
strongit/NewhostInit
useful-scripts/pyutil/pygtail.py
[ "Apache-2.0" ]
Python
_determine_rotated_logfile
<not_specific>
def _determine_rotated_logfile(self): """ We suspect the logfile has been rotated, so try to guess what the rotated filename is, and return it. """ rotated_filename = self._check_rotated_filename_candidates() if rotated_filename and exists(rotated_filename): i...
We suspect the logfile has been rotated, so try to guess what the rotated filename is, and return it.
We suspect the logfile has been rotated, so try to guess what the rotated filename is, and return it.
[ "We", "suspect", "the", "logfile", "has", "been", "rotated", "so", "try", "to", "guess", "what", "the", "rotated", "filename", "is", "and", "return", "it", "." ]
def _determine_rotated_logfile(self): rotated_filename = self._check_rotated_filename_candidates() if rotated_filename and exists(rotated_filename): if stat(rotated_filename).st_ino == self._offset_file_inode: return rotated_filename if stat(self.filename).st_ino ...
[ "def", "_determine_rotated_logfile", "(", "self", ")", ":", "rotated_filename", "=", "self", ".", "_check_rotated_filename_candidates", "(", ")", "if", "rotated_filename", "and", "exists", "(", "rotated_filename", ")", ":", "if", "stat", "(", "rotated_filename", ")"...
We suspect the logfile has been rotated, so try to guess what the rotated filename is, and return it.
[ "We", "suspect", "the", "logfile", "has", "been", "rotated", "so", "try", "to", "guess", "what", "the", "rotated", "filename", "is", "and", "return", "it", "." ]
[ "\"\"\"\n We suspect the logfile has been rotated, so try to guess what the\n rotated filename is, and return it.\n \"\"\"", "# if the inode hasn't changed, then the file shrank; this is expected with copytruncate,", "# otherwise print a warning" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
4e2ad8e67c1ea35a5180a9f2734557956537dc19
strongit/NewhostInit
useful-scripts/pyutil/pygtail.py
[ "Apache-2.0" ]
Python
_check_rotated_filename_candidates
<not_specific>
def _check_rotated_filename_candidates(self): """ Check for various rotated logfile filename patterns and return the first match we find. """ # savelog(8) candidate = "%s.0" % self.filename if (exists(candidate) and exists("%s.1.gz" % self.filename) and ...
Check for various rotated logfile filename patterns and return the first match we find.
Check for various rotated logfile filename patterns and return the first match we find.
[ "Check", "for", "various", "rotated", "logfile", "filename", "patterns", "and", "return", "the", "first", "match", "we", "find", "." ]
def _check_rotated_filename_candidates(self): candidate = "%s.0" % self.filename if (exists(candidate) and exists("%s.1.gz" % self.filename) and (stat(candidate).st_mtime > stat("%s.1.gz" % self.filename).st_mtime)): return candidate candidate = "%s.1" % self.filename ...
[ "def", "_check_rotated_filename_candidates", "(", "self", ")", ":", "candidate", "=", "\"%s.0\"", "%", "self", ".", "filename", "if", "(", "exists", "(", "candidate", ")", "and", "exists", "(", "\"%s.1.gz\"", "%", "self", ".", "filename", ")", "and", "(", ...
Check for various rotated logfile filename patterns and return the first match we find.
[ "Check", "for", "various", "rotated", "logfile", "filename", "patterns", "and", "return", "the", "first", "match", "we", "find", "." ]
[ "\"\"\"\n Check for various rotated logfile filename patterns and return the first\n match we find.\n \"\"\"", "# savelog(8)", "# logrotate(8)", "# with delaycompress", "# without delaycompress", "# logrotate dateext rotation scheme - `dateformat -%Y%m%d` + with `delaycompress`", "#...
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
0da4e0be72e0855b8025fb55137d84a540aa0d59
Kiwoo/HVHRL
softqlearning/softqlearning/algorithms/rl_algorithm.py
[ "MIT" ]
Python
_evaluate
<not_specific>
def _evaluate(self, policy, evaluation_env): """Perform evaluation for the current policy.""" if self._eval_n_episodes < 1: return # TODO: max_path_length should be a property of environment. paths = rollouts(evaluation_env, policy, self.sampler._max_path_length, ...
Perform evaluation for the current policy.
Perform evaluation for the current policy.
[ "Perform", "evaluation", "for", "the", "current", "policy", "." ]
def _evaluate(self, policy, evaluation_env): if self._eval_n_episodes < 1: return paths = rollouts(evaluation_env, policy, self.sampler._max_path_length, self._eval_n_episodes) total_returns = [path['rewards'].sum() for path in paths] episode_lengths ...
[ "def", "_evaluate", "(", "self", ",", "policy", ",", "evaluation_env", ")", ":", "if", "self", ".", "_eval_n_episodes", "<", "1", ":", "return", "paths", "=", "rollouts", "(", "evaluation_env", ",", "policy", ",", "self", ".", "sampler", ".", "_max_path_le...
Perform evaluation for the current policy.
[ "Perform", "evaluation", "for", "the", "current", "policy", "." ]
[ "\"\"\"Perform evaluation for the current policy.\"\"\"", "# TODO: max_path_length should be a property of environment." ]
[ { "param": "self", "type": null }, { "param": "policy", "type": null }, { "param": "evaluation_env", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "policy", "type": null, "docstring": null, "docstring_tokens":...
1e41ab9cd5a11347f0955becab8a8e24fee9e426
Kiwoo/HVHRL
baselines/baselines/hybrid_boundary_seeking/simple.py
[ "MIT" ]
Python
load
<not_specific>
def load(path, exp_name): """Load act function that was returned by learn function. Parameters ---------- path: str path to the act function pickle Returns ------- act: ActWrapper function that takes a batch of observations and returns actions. """ return Ac...
Load act function that was returned by learn function. Parameters ---------- path: str path to the act function pickle Returns ------- act: ActWrapper function that takes a batch of observations and returns actions.
Load act function that was returned by learn function. Parameters str path to the act function pickle Returns ActWrapper function that takes a batch of observations and returns actions.
[ "Load", "act", "function", "that", "was", "returned", "by", "learn", "function", ".", "Parameters", "str", "path", "to", "the", "act", "function", "pickle", "Returns", "ActWrapper", "function", "that", "takes", "a", "batch", "of", "observations", "and", "retur...
def load(path, exp_name): return ActWrapper.load(path, exp_name)
[ "def", "load", "(", "path", ",", "exp_name", ")", ":", "return", "ActWrapper", ".", "load", "(", "path", ",", "exp_name", ")" ]
Load act function that was returned by learn function.
[ "Load", "act", "function", "that", "was", "returned", "by", "learn", "function", "." ]
[ "\"\"\"Load act function that was returned by learn function.\n\n Parameters\n ----------\n path: str\n path to the act function pickle\n\n Returns\n -------\n act: ActWrapper\n function that takes a batch of observations\n and returns actions.\n \"\"\"" ]
[ { "param": "path", "type": null }, { "param": "exp_name", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "path", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "exp_name", "type": null, "docstring": null, "docstring_tokens...
c5a975dee0564a999eeb9830d6ca3b9d3a880aa3
Kiwoo/HVHRL
softqlearning/softqlearning/misc/instrument.py
[ "MIT" ]
Python
_create_symlink
<not_specific>
def _create_symlink(folder): """Create a symbolic link that points to the sql folder.""" # Unique filename for the symlink. include_path = os.path.join('/tmp/', str(uuid.uuid4())) os.makedirs(include_path) os.symlink( os.path.join(PROJECT_PATH, folder), os.path.join(include_path, folder)) ...
Create a symbolic link that points to the sql folder.
Create a symbolic link that points to the sql folder.
[ "Create", "a", "symbolic", "link", "that", "points", "to", "the", "sql", "folder", "." ]
def _create_symlink(folder): include_path = os.path.join('/tmp/', str(uuid.uuid4())) os.makedirs(include_path) os.symlink( os.path.join(PROJECT_PATH, folder), os.path.join(include_path, folder)) return include_path
[ "def", "_create_symlink", "(", "folder", ")", ":", "include_path", "=", "os", ".", "path", ".", "join", "(", "'/tmp/'", ",", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", ")", "os", ".", "makedirs", "(", "include_path", ")", "os", ".", "symlink", ...
Create a symbolic link that points to the sql folder.
[ "Create", "a", "symbolic", "link", "that", "points", "to", "the", "sql", "folder", "." ]
[ "\"\"\"Create a symbolic link that points to the sql folder.\"\"\"", "# Unique filename for the symlink." ]
[ { "param": "folder", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "folder", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
8610fdedf9ef4e2901550db1435366c9fe2f00b5
Kiwoo/HVHRL
softqlearning/softqlearning/algorithms/sql.py
[ "MIT" ]
Python
_create_td_update
null
def _create_td_update(self): """Create a minimization operation for Q-function update.""" with tf.variable_scope('target'): # The value of the next state is approximated with uniform samples. target_actions = tf.random_uniform( (1, self._value_n_particles, self._...
Create a minimization operation for Q-function update.
Create a minimization operation for Q-function update.
[ "Create", "a", "minimization", "operation", "for", "Q", "-", "function", "update", "." ]
def _create_td_update(self): with tf.variable_scope('target'): target_actions = tf.random_uniform( (1, self._value_n_particles, self._action_dim), -1, 1) q_value_targets = self.qf.output_for( observations=self._next_observations_ph[:, None, :], ...
[ "def", "_create_td_update", "(", "self", ")", ":", "with", "tf", ".", "variable_scope", "(", "'target'", ")", ":", "target_actions", "=", "tf", ".", "random_uniform", "(", "(", "1", ",", "self", ".", "_value_n_particles", ",", "self", ".", "_action_dim", "...
Create a minimization operation for Q-function update.
[ "Create", "a", "minimization", "operation", "for", "Q", "-", "function", "update", "." ]
[ "\"\"\"Create a minimization operation for Q-function update.\"\"\"", "# The value of the next state is approximated with uniform samples.", "# Equation 10:", "# Importance weights add just a constant to the value.", "# \\hat Q in Equation 11:", "# Equation 11:" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
8610fdedf9ef4e2901550db1435366c9fe2f00b5
Kiwoo/HVHRL
softqlearning/softqlearning/algorithms/sql.py
[ "MIT" ]
Python
_create_svgd_update
null
def _create_svgd_update(self): """Create a minimization operation for policy update (SVGD).""" actions = self.policy.actions_for( observations=self._observations_ph, n_action_samples=self._kernel_n_particles, reuse=True) assert_shape(actions, ...
Create a minimization operation for policy update (SVGD).
Create a minimization operation for policy update (SVGD).
[ "Create", "a", "minimization", "operation", "for", "policy", "update", "(", "SVGD", ")", "." ]
def _create_svgd_update(self): actions = self.policy.actions_for( observations=self._observations_ph, n_action_samples=self._kernel_n_particles, reuse=True) assert_shape(actions, [None, self._kernel_n_particles, self._action_dim]) n_update...
[ "def", "_create_svgd_update", "(", "self", ")", ":", "actions", "=", "self", ".", "policy", ".", "actions_for", "(", "observations", "=", "self", ".", "_observations_ph", ",", "n_action_samples", "=", "self", ".", "_kernel_n_particles", ",", "reuse", "=", "Tru...
Create a minimization operation for policy update (SVGD).
[ "Create", "a", "minimization", "operation", "for", "policy", "update", "(", "SVGD", ")", "." ]
[ "\"\"\"Create a minimization operation for policy update (SVGD).\"\"\"", "# SVGD requires computing two empirical expectations over actions", "# (see Appendix C1.1.). To that end, we first sample a single set of", "# actions, and later split them into two sets: `fixed_actions` are used", "# to evaluate the ...
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
8610fdedf9ef4e2901550db1435366c9fe2f00b5
Kiwoo/HVHRL
softqlearning/softqlearning/algorithms/sql.py
[ "MIT" ]
Python
_create_target_ops
<not_specific>
def _create_target_ops(self): """Create tensorflow operation for updating the target Q-function.""" if not self._train_qf: return source_params = self.qf.get_params_internal() target_params = self.qf.get_params_internal(scope='target') self._target_ops = [ ...
Create tensorflow operation for updating the target Q-function.
Create tensorflow operation for updating the target Q-function.
[ "Create", "tensorflow", "operation", "for", "updating", "the", "target", "Q", "-", "function", "." ]
def _create_target_ops(self): if not self._train_qf: return source_params = self.qf.get_params_internal() target_params = self.qf.get_params_internal(scope='target') self._target_ops = [ tf.assign(tgt, src) for tgt, src in zip(target_params, source_par...
[ "def", "_create_target_ops", "(", "self", ")", ":", "if", "not", "self", ".", "_train_qf", ":", "return", "source_params", "=", "self", ".", "qf", ".", "get_params_internal", "(", ")", "target_params", "=", "self", ".", "qf", ".", "get_params_internal", "(",...
Create tensorflow operation for updating the target Q-function.
[ "Create", "tensorflow", "operation", "for", "updating", "the", "target", "Q", "-", "function", "." ]
[ "\"\"\"Create tensorflow operation for updating the target Q-function.\"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
8610fdedf9ef4e2901550db1435366c9fe2f00b5
Kiwoo/HVHRL
softqlearning/softqlearning/algorithms/sql.py
[ "MIT" ]
Python
_get_feed_dict
<not_specific>
def _get_feed_dict(self, batch): """Construct a TensorFlow feed dictionary from a sample batch.""" feeds = { self._observations_ph: batch['observations'], self._actions_pl: batch['actions'], self._next_observations_ph: batch['next_observations'], self._re...
Construct a TensorFlow feed dictionary from a sample batch.
Construct a TensorFlow feed dictionary from a sample batch.
[ "Construct", "a", "TensorFlow", "feed", "dictionary", "from", "a", "sample", "batch", "." ]
def _get_feed_dict(self, batch): feeds = { self._observations_ph: batch['observations'], self._actions_pl: batch['actions'], self._next_observations_ph: batch['next_observations'], self._rewards_pl: batch['rewards'], self._terminals_pl: batch['terminal...
[ "def", "_get_feed_dict", "(", "self", ",", "batch", ")", ":", "feeds", "=", "{", "self", ".", "_observations_ph", ":", "batch", "[", "'observations'", "]", ",", "self", ".", "_actions_pl", ":", "batch", "[", "'actions'", "]", ",", "self", ".", "_next_obs...
Construct a TensorFlow feed dictionary from a sample batch.
[ "Construct", "a", "TensorFlow", "feed", "dictionary", "from", "a", "sample", "batch", "." ]
[ "\"\"\"Construct a TensorFlow feed dictionary from a sample batch.\"\"\"" ]
[ { "param": "self", "type": null }, { "param": "batch", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "batch", "type": null, "docstring": null, "docstring_tokens": ...
8610fdedf9ef4e2901550db1435366c9fe2f00b5
Kiwoo/HVHRL
softqlearning/softqlearning/algorithms/sql.py
[ "MIT" ]
Python
log_diagnostics
null
def log_diagnostics(self, batch): """Record diagnostic information. Records the mean and standard deviation of Q-function and the squared Bellman residual of the s (mean squared Bellman error) for a sample batch. Also call the `draw` method of the plotter, if plotter is define...
Record diagnostic information. Records the mean and standard deviation of Q-function and the squared Bellman residual of the s (mean squared Bellman error) for a sample batch. Also call the `draw` method of the plotter, if plotter is defined.
Record diagnostic information. Records the mean and standard deviation of Q-function and the squared Bellman residual of the s (mean squared Bellman error) for a sample batch. Also call the `draw` method of the plotter, if plotter is defined.
[ "Record", "diagnostic", "information", ".", "Records", "the", "mean", "and", "standard", "deviation", "of", "Q", "-", "function", "and", "the", "squared", "Bellman", "residual", "of", "the", "s", "(", "mean", "squared", "Bellman", "error", ")", "for", "a", ...
def log_diagnostics(self, batch): feeds = self._get_feed_dict(batch) qf, bellman_residual = self._sess.run( [self._q_values, self._bellman_residual], feeds) logger.record_tabular('qf-avg', np.mean(qf)) logger.record_tabular('qf-std', np.std(qf)) logger.record_tabular(...
[ "def", "log_diagnostics", "(", "self", ",", "batch", ")", ":", "feeds", "=", "self", ".", "_get_feed_dict", "(", "batch", ")", "qf", ",", "bellman_residual", "=", "self", ".", "_sess", ".", "run", "(", "[", "self", ".", "_q_values", ",", "self", ".", ...
Record diagnostic information.
[ "Record", "diagnostic", "information", "." ]
[ "\"\"\"Record diagnostic information.\n\n Records the mean and standard deviation of Q-function and the\n squared Bellman residual of the s (mean squared Bellman error)\n for a sample batch.\n\n Also call the `draw` method of the plotter, if plotter is defined.\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "batch", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "batch", "type": null, "docstring": null, "docstring_tokens": ...
2580b4d6e82e9ad09fed787a338808af5b560045
Kiwoo/HVHRL
baselines/baselines/hybrid_boundary_seeking/experiments/train_boundary.py
[ "MIT" ]
Python
main
null
def main(): env = gym.make("Pendulum-v0") ''' we assume that we have actor_list, which is a list of pre-trained policies to be used as subpolicies ''' exp_name = 'boundary' actor_list = ["half_down", "half_up"] sub_policies = [] for actor in actor_list: print("=== Actor: ...
we assume that we have actor_list, which is a list of pre-trained policies to be used as subpolicies
we assume that we have actor_list, which is a list of pre-trained policies to be used as subpolicies
[ "we", "assume", "that", "we", "have", "actor_list", "which", "is", "a", "list", "of", "pre", "-", "trained", "policies", "to", "be", "used", "as", "subpolicies" ]
def main(): env = gym.make("Pendulum-v0") exp_name = 'boundary' actor_list = ["half_down", "half_up"] sub_policies = [] for actor in actor_list: print("=== Actor: {}".format(actor)) actor = HBS.load("pendulum_model_{}.pkl".format(actor), actor) sub_policies.append(actor) ...
[ "def", "main", "(", ")", ":", "env", "=", "gym", ".", "make", "(", "\"Pendulum-v0\"", ")", "exp_name", "=", "'boundary'", "actor_list", "=", "[", "\"half_down\"", ",", "\"half_up\"", "]", "sub_policies", "=", "[", "]", "for", "actor", "in", "actor_list", ...
we assume that we have actor_list, which is a list of pre-trained policies to be used as subpolicies
[ "we", "assume", "that", "we", "have", "actor_list", "which", "is", "a", "list", "of", "pre", "-", "trained", "policies", "to", "be", "used", "as", "subpolicies" ]
[ "'''\n we assume that we have actor_list, which is a list of pre-trained policies \n to be used as subpolicies\n '''" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }