repo
stringlengths
7
55
path
stringlengths
4
223
url
stringlengths
87
315
code
stringlengths
75
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
avg_line_len
float64
7.91
980
hMatoba/Piexif
piexif/_common.py
https://github.com/hMatoba/Piexif/blob/afd0d232cf05cf530423f4b2a82ab291f150601a/piexif/_common.py#L69-L94
def merge_segments(segments, exif=b""): """Merges Exif with APP0 and APP1 manipulations. """ if segments[1][0:2] == b"\xff\xe0" and \ segments[2][0:2] == b"\xff\xe1" and \ segments[2][4:10] == b"Exif\x00\x00": if exif: segments[2] = exif segments.pop(1) ...
[ "def", "merge_segments", "(", "segments", ",", "exif", "=", "b\"\"", ")", ":", "if", "segments", "[", "1", "]", "[", "0", ":", "2", "]", "==", "b\"\\xff\\xe0\"", "and", "segments", "[", "2", "]", "[", "0", ":", "2", "]", "==", "b\"\\xff\\xe1\"", "a...
Merges Exif with APP0 and APP1 manipulations.
[ "Merges", "Exif", "with", "APP0", "and", "APP1", "manipulations", "." ]
python
train
29.384615
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Tags.py
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Tags.py#L1898-L1919
def getParentElementCustomFilter(self, filterFunc): ''' getParentElementCustomFilter - Runs through parent on up to document root, returning the first tag which filterFunc(tag) returns True. @param filterFunc <function/lambda> - A funct...
[ "def", "getParentElementCustomFilter", "(", "self", ",", "filterFunc", ")", ":", "parentNode", "=", "self", ".", "parentNode", "while", "parentNode", ":", "if", "filterFunc", "(", "parentNode", ")", "is", "True", ":", "return", "parentNode", "parentNode", "=", ...
getParentElementCustomFilter - Runs through parent on up to document root, returning the first tag which filterFunc(tag) returns True. @param filterFunc <function/lambda> - A function or lambda expression that should return "True" if the passed node matche...
[ "getParentElementCustomFilter", "-", "Runs", "through", "parent", "on", "up", "to", "document", "root", "returning", "the" ]
python
train
34.5
quantopian/zipline
zipline/utils/preprocess.py
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/preprocess.py#L142-L247
def _build_preprocessed_function(func, processors, args_defaults, varargs, varkw): """ Build a preprocessed function with the same signature as `func`. Uses `exec` internally ...
[ "def", "_build_preprocessed_function", "(", "func", ",", "processors", ",", "args_defaults", ",", "varargs", ",", "varkw", ")", ":", "format_kwargs", "=", "{", "'func_name'", ":", "func", ".", "__name__", "}", "def", "mangle", "(", "name", ")", ":", "return"...
Build a preprocessed function with the same signature as `func`. Uses `exec` internally to build a function that actually has the same signature as `func.
[ "Build", "a", "preprocessed", "function", "with", "the", "same", "signature", "as", "func", "." ]
python
train
31.669811
mdickinson/refcycle
refcycle/i_directed_graph.py
https://github.com/mdickinson/refcycle/blob/627fad74c74efc601209c96405f8118cd99b2241/refcycle/i_directed_graph.py#L189-L209
def ancestors(self, start, generations=None): """ Return the subgraph of all nodes from which the given vertex is reachable, including that vertex. If specified, the optional `generations` argument specifies how many generations to limit to. """ visited = self.v...
[ "def", "ancestors", "(", "self", ",", "start", ",", "generations", "=", "None", ")", ":", "visited", "=", "self", ".", "vertex_set", "(", ")", "visited", ".", "add", "(", "start", ")", "to_visit", "=", "deque", "(", "[", "(", "start", ",", "0", ")"...
Return the subgraph of all nodes from which the given vertex is reachable, including that vertex. If specified, the optional `generations` argument specifies how many generations to limit to.
[ "Return", "the", "subgraph", "of", "all", "nodes", "from", "which", "the", "given", "vertex", "is", "reachable", "including", "that", "vertex", "." ]
python
train
35.142857
boriel/zxbasic
arch/zx48k/backend/__pload.py
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__pload.py#L368-L397
def _pstoref16(ins): """ Stores 2nd parameter at stack pointer (SP) + X, being X 1st parameter. 1st operand must be a SIGNED integer. """ value = ins.quad[2] offset = ins.quad[1] indirect = offset[0] == '*' if indirect: offset = offset[1:] I = int(offset) if I >= 0: ...
[ "def", "_pstoref16", "(", "ins", ")", ":", "value", "=", "ins", ".", "quad", "[", "2", "]", "offset", "=", "ins", ".", "quad", "[", "1", "]", "indirect", "=", "offset", "[", "0", "]", "==", "'*'", "if", "indirect", ":", "offset", "=", "offset", ...
Stores 2nd parameter at stack pointer (SP) + X, being X 1st parameter. 1st operand must be a SIGNED integer.
[ "Stores", "2nd", "parameter", "at", "stack", "pointer", "(", "SP", ")", "+", "X", "being", "X", "1st", "parameter", "." ]
python
train
22.2
Alignak-monitoring/alignak
alignak/objects/config.py
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/config.py#L1723-L1757
def apply_inheritance(self): """Apply inheritance over templates Template can be used in the following objects:: * hosts * contacts * services * servicedependencies * hostdependencies * timeperiods * hostsextinfo * servicesextinfo ...
[ "def", "apply_inheritance", "(", "self", ")", ":", "# inheritance properties by template", "self", ".", "hosts", ".", "apply_inheritance", "(", ")", "self", ".", "contacts", ".", "apply_inheritance", "(", ")", "self", ".", "services", ".", "apply_inheritance", "("...
Apply inheritance over templates Template can be used in the following objects:: * hosts * contacts * services * servicedependencies * hostdependencies * timeperiods * hostsextinfo * servicesextinfo * serviceescalations * hostescal...
[ "Apply", "inheritance", "over", "templates", "Template", "can", "be", "used", "in", "the", "following", "objects", "::" ]
python
train
30.428571
mitsei/dlkit
dlkit/json_/cataloging/searches.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/cataloging/searches.py#L97-L108
def get_catalogs(self): """Gets the catalog list resulting from the search. return: (osid.cataloging.CatalogList) - the catalogs list raise: IllegalState - list has already been retrieved *compliance: mandatory -- This method must be implemented.* """ if self.retrieved...
[ "def", "get_catalogs", "(", "self", ")", ":", "if", "self", ".", "retrieved", ":", "raise", "errors", ".", "IllegalState", "(", "'List has already been retrieved.'", ")", "self", ".", "retrieved", "=", "True", "return", "objects", ".", "CatalogList", "(", "sel...
Gets the catalog list resulting from the search. return: (osid.cataloging.CatalogList) - the catalogs list raise: IllegalState - list has already been retrieved *compliance: mandatory -- This method must be implemented.*
[ "Gets", "the", "catalog", "list", "resulting", "from", "the", "search", "." ]
python
train
40.583333
firecat53/urlscan
urlscan/urlscan.py
https://github.com/firecat53/urlscan/blob/2d10807d01167873733da3b478c784f8fa21bbc0/urlscan/urlscan.py#L30-L36
def get_charset(message, default="utf-8"): """Get the message charset""" if message.get_content_charset(): return message.get_content_charset() if message.get_charset(): return message.get_charset() return default
[ "def", "get_charset", "(", "message", ",", "default", "=", "\"utf-8\"", ")", ":", "if", "message", ".", "get_content_charset", "(", ")", ":", "return", "message", ".", "get_content_charset", "(", ")", "if", "message", ".", "get_charset", "(", ")", ":", "re...
Get the message charset
[ "Get", "the", "message", "charset" ]
python
train
34.142857
limpyd/redis-limpyd
limpyd/contrib/collection.py
https://github.com/limpyd/redis-limpyd/blob/3c745dde1390a0bd09690b77a089dcc08c6c7e43/limpyd/contrib/collection.py#L74-L98
def _collection(self): """ Effectively retrieve data according to lazy_collection. If we have a stored collection, without any result, return an empty list """ old_sort_limits_and_len_mode = None if self._sort_limits is None else self._sort_limits.copy(), self._len_mode o...
[ "def", "_collection", "(", "self", ")", ":", "old_sort_limits_and_len_mode", "=", "None", "if", "self", ".", "_sort_limits", "is", "None", "else", "self", ".", "_sort_limits", ".", "copy", "(", ")", ",", "self", ".", "_len_mode", "old_sorts", "=", "None", ...
Effectively retrieve data according to lazy_collection. If we have a stored collection, without any result, return an empty list
[ "Effectively", "retrieve", "data", "according", "to", "lazy_collection", ".", "If", "we", "have", "a", "stored", "collection", "without", "any", "result", "return", "an", "empty", "list" ]
python
train
49
frejanordsiek/GeminiMotorDrive
GeminiMotorDrive/__init__.py
https://github.com/frejanordsiek/GeminiMotorDrive/blob/8de347ffb91228fbfe3832098b4996fa0141d8f1/GeminiMotorDrive/__init__.py#L433-L480
def get_program(self, n, timeout=2.0, max_retries=2): """ Get a program from the drive. Gets program 'n' from the drive and returns its commands. Parameters ---------- n : int Which program to get. timeout : number, optional Optional timeout in s...
[ "def", "get_program", "(", "self", ",", "n", ",", "timeout", "=", "2.0", ",", "max_retries", "=", "2", ")", ":", "# Send the 'TPROG PROGn' command to read the program.", "response", "=", "self", ".", "driver", ".", "send_command", "(", "'TPROG PROG'", "+", "str"...
Get a program from the drive. Gets program 'n' from the drive and returns its commands. Parameters ---------- n : int Which program to get. timeout : number, optional Optional timeout in seconds to use when reading the response. A negative va...
[ "Get", "a", "program", "from", "the", "drive", "." ]
python
train
34.5625
fprimex/zdesk
zdesk/zdesk_api.py
https://github.com/fprimex/zdesk/blob/851611c13b4d530e9df31390b3ec709baf0a0188/zdesk/zdesk_api.py#L3083-L3087
def skill_delete(self, skill_id, **kwargs): "https://developer.zendesk.com/rest_api/docs/chat/skills#delete-skill-by-id" api_path = "/api/v2/skills/{skill_id}" api_path = api_path.format(skill_id=skill_id) return self.call(api_path, method="DELETE", **kwargs)
[ "def", "skill_delete", "(", "self", ",", "skill_id", ",", "*", "*", "kwargs", ")", ":", "api_path", "=", "\"/api/v2/skills/{skill_id}\"", "api_path", "=", "api_path", ".", "format", "(", "skill_id", "=", "skill_id", ")", "return", "self", ".", "call", "(", ...
https://developer.zendesk.com/rest_api/docs/chat/skills#delete-skill-by-id
[ "https", ":", "//", "developer", ".", "zendesk", ".", "com", "/", "rest_api", "/", "docs", "/", "chat", "/", "skills#delete", "-", "skill", "-", "by", "-", "id" ]
python
train
57.4
MKLab-ITI/reveal-user-annotation
reveal_user_annotation/twitter/user_annotate.py
https://github.com/MKLab-ITI/reveal-user-annotation/blob/ed019c031857b091e5601f53ba3f01a499a0e3ef/reveal_user_annotation/twitter/user_annotate.py#L21-L51
def extract_user_keywords_generator(twitter_lists_gen, lemmatizing="wordnet"): """ Based on the user-related lists I have downloaded, annotate the users. Inputs: - twitter_lists_gen: A python generator that yields a user Twitter id and a generator of Twitter lists. - lemmatizing: A string conta...
[ "def", "extract_user_keywords_generator", "(", "twitter_lists_gen", ",", "lemmatizing", "=", "\"wordnet\"", ")", ":", "####################################################################################################################", "# Extract keywords serially.", "#####################...
Based on the user-related lists I have downloaded, annotate the users. Inputs: - twitter_lists_gen: A python generator that yields a user Twitter id and a generator of Twitter lists. - lemmatizing: A string containing one of the following: "porter", "snowball" or "wordnet". Yields: - user_twitter_...
[ "Based", "on", "the", "user", "-", "related", "lists", "I", "have", "downloaded", "annotate", "the", "users", "." ]
python
train
54.419355
knagra/farnsworth
workshift/views.py
https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/workshift/views.py#L1663-L1695
def list_types_view(request, semester, profile=None): """ View the details of a particular WorkshiftType. """ page_name = "Workshift Types" full_management = utils.can_manage(request.user, semester) any_management = utils.can_manage(request.user, semester, any_pool=True) types = WorkshiftTy...
[ "def", "list_types_view", "(", "request", ",", "semester", ",", "profile", "=", "None", ")", ":", "page_name", "=", "\"Workshift Types\"", "full_management", "=", "utils", ".", "can_manage", "(", "request", ".", "user", ",", "semester", ")", "any_management", ...
View the details of a particular WorkshiftType.
[ "View", "the", "details", "of", "a", "particular", "WorkshiftType", "." ]
python
train
29.606061
Qiskit/qiskit-terra
qiskit/tools/qi/qi.py
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/tools/qi/qi.py#L311-L330
def outer(vector1, vector2=None): """ Construct the outer product of two vectors. The second vector argument is optional, if absent the projector of the first vector will be returned. Args: vector1 (ndarray): the first vector. vector2 (ndarray): the (optional) second vector. R...
[ "def", "outer", "(", "vector1", ",", "vector2", "=", "None", ")", ":", "if", "vector2", "is", "None", ":", "vector2", "=", "np", ".", "array", "(", "vector1", ")", ".", "conj", "(", ")", "else", ":", "vector2", "=", "np", ".", "array", "(", "vect...
Construct the outer product of two vectors. The second vector argument is optional, if absent the projector of the first vector will be returned. Args: vector1 (ndarray): the first vector. vector2 (ndarray): the (optional) second vector. Returns: np.array: The matrix |v1><v2|.
[ "Construct", "the", "outer", "product", "of", "two", "vectors", "." ]
python
test
25.7
saltstack/salt
salt/scripts.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/scripts.py#L333-L386
def salt_proxy(): ''' Start a proxy minion. ''' import salt.cli.daemons import salt.utils.platform import multiprocessing if '' in sys.path: sys.path.remove('') if salt.utils.platform.is_windows(): proxyminion = salt.cli.daemons.ProxyMinion() proxyminion.start() ...
[ "def", "salt_proxy", "(", ")", ":", "import", "salt", ".", "cli", ".", "daemons", "import", "salt", ".", "utils", ".", "platform", "import", "multiprocessing", "if", "''", "in", "sys", ".", "path", ":", "sys", ".", "path", ".", "remove", "(", "''", "...
Start a proxy minion.
[ "Start", "a", "proxy", "minion", "." ]
python
train
32.796296
Jammy2211/PyAutoLens
autolens/model/galaxy/util/galaxy_util.py
https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/model/galaxy/util/galaxy_util.py#L107-L127
def deflections_of_galaxies_from_sub_grid(sub_grid, galaxies): """Compute the deflections of a list of galaxies from an input sub-grid, by summing the individual deflections \ of each galaxy's mass profile. The deflections are calculated on the sub-grid and binned-up to the original regular grid by taking ...
[ "def", "deflections_of_galaxies_from_sub_grid", "(", "sub_grid", ",", "galaxies", ")", ":", "if", "galaxies", ":", "return", "sum", "(", "map", "(", "lambda", "galaxy", ":", "galaxy", ".", "deflections_from_grid", "(", "sub_grid", ")", ",", "galaxies", ")", ")...
Compute the deflections of a list of galaxies from an input sub-grid, by summing the individual deflections \ of each galaxy's mass profile. The deflections are calculated on the sub-grid and binned-up to the original regular grid by taking the mean value \ of every set of sub-pixels. If no galaxies a...
[ "Compute", "the", "deflections", "of", "a", "list", "of", "galaxies", "from", "an", "input", "sub", "-", "grid", "by", "summing", "the", "individual", "deflections", "\\", "of", "each", "galaxy", "s", "mass", "profile", "." ]
python
valid
44.666667
sosy-lab/benchexec
benchexec/tablegenerator/columns.py
https://github.com/sosy-lab/benchexec/blob/44428f67f41384c03aea13e7e25f884764653617/benchexec/tablegenerator/columns.py#L348-L364
def get_column_type(column, column_values): """ Returns the type of the given column based on its row values on the given RunSetResult. @param column: the column to return the correct ColumnType for @param column_values: the column values to consider @return: a tuple of a type object describing the ...
[ "def", "get_column_type", "(", "column", ",", "column_values", ")", ":", "try", ":", "return", "_get_column_type_heur", "(", "column", ",", "column_values", ")", "except", "util", ".", "TableDefinitionError", "as", "e", ":", "logging", ".", "error", "(", "\"Co...
Returns the type of the given column based on its row values on the given RunSetResult. @param column: the column to return the correct ColumnType for @param column_values: the column values to consider @return: a tuple of a type object describing the column - the concrete ColumnType is stored in the attrib...
[ "Returns", "the", "type", "of", "the", "given", "column", "based", "on", "its", "row", "values", "on", "the", "given", "RunSetResult", "." ]
python
train
52.176471
openstack/networking-arista
networking_arista/l3Plugin/arista_l3_driver.py
https://github.com/openstack/networking-arista/blob/07ce6b1fc62ff74308a6eabfc4cc0ee09fb7b0fe/networking_arista/l3Plugin/arista_l3_driver.py#L452-L455
def _get_ipv4_from_binary(self, bin_addr): """Converts binary address to Ipv4 format.""" return socket.inet_ntop(socket.AF_INET, struct.pack("!L", bin_addr))
[ "def", "_get_ipv4_from_binary", "(", "self", ",", "bin_addr", ")", ":", "return", "socket", ".", "inet_ntop", "(", "socket", ".", "AF_INET", ",", "struct", ".", "pack", "(", "\"!L\"", ",", "bin_addr", ")", ")" ]
Converts binary address to Ipv4 format.
[ "Converts", "binary", "address", "to", "Ipv4", "format", "." ]
python
train
42.75
ausaki/subfinder
subfinder/subfinder.py
https://github.com/ausaki/subfinder/blob/b74b79214f618c603a551b9334ebb110ccf9684c/subfinder/subfinder.py#L155-L176
def start(self): """ SubFinder 入口,开始函数 """ self.logger.info('开始') videofiles = self._filter_path(self.path) l = len(videofiles) if l == 0: self.logger.info( '在 {} 下没有发现视频文件'.format(self.path)) return else: self.l...
[ "def", "start", "(", "self", ")", ":", "self", ".", "logger", ".", "info", "(", "'开始')", "", "videofiles", "=", "self", ".", "_filter_path", "(", "self", ".", "path", ")", "l", "=", "len", "(", "videofiles", ")", "if", "l", "==", "0", ":", "self"...
SubFinder 入口,开始函数
[ "SubFinder", "入口,开始函数" ]
python
train
31.863636
Legobot/Legobot
Legobot/Utilities.py
https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Utilities.py#L24-L46
def truncate(text, length=255): """ Splits the message into a list of strings of of length `length` Args: text (str): The text to be divided length (int, optional): The length of the chunks of text. \ Defaults to 255. Returns: lis...
[ "def", "truncate", "(", "text", ",", "length", "=", "255", ")", ":", "lines", "=", "[", "]", "i", "=", "0", "while", "i", "<", "len", "(", "text", ")", "-", "1", ":", "try", ":", "lines", ".", "append", "(", "text", "[", "i", ":", "i", "+",...
Splits the message into a list of strings of of length `length` Args: text (str): The text to be divided length (int, optional): The length of the chunks of text. \ Defaults to 255. Returns: list: Text divided into chunks of length `length`
[ "Splits", "the", "message", "into", "a", "list", "of", "strings", "of", "of", "length", "length" ]
python
train
26.608696
gem/oq-engine
openquake/calculators/extract.py
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/extract.py#L139-L150
def extract_(dstore, dspath): """ Extracts an HDF5 path object from the datastore, for instance extract(dstore, 'sitecol'). """ obj = dstore[dspath] if isinstance(obj, Dataset): return ArrayWrapper(obj.value, obj.attrs) elif isinstance(obj, Group): return ArrayWrapper(numpy.a...
[ "def", "extract_", "(", "dstore", ",", "dspath", ")", ":", "obj", "=", "dstore", "[", "dspath", "]", "if", "isinstance", "(", "obj", ",", "Dataset", ")", ":", "return", "ArrayWrapper", "(", "obj", ".", "value", ",", "obj", ".", "attrs", ")", "elif", ...
Extracts an HDF5 path object from the datastore, for instance extract(dstore, 'sitecol').
[ "Extracts", "an", "HDF5", "path", "object", "from", "the", "datastore", "for", "instance", "extract", "(", "dstore", "sitecol", ")", "." ]
python
train
30.416667
agile-geoscience/striplog
striplog/legend.py
https://github.com/agile-geoscience/striplog/blob/8033b673a151f96c29802b43763e863519a3124c/striplog/legend.py#L842-L853
def plot(self, fmt=None): """ Make a simple plot of the legend. Simply calls Decor.plot() on all of its members. TODO: Build a more attractive plot. """ for d in self.__list: d.plot(fmt=fmt) return None
[ "def", "plot", "(", "self", ",", "fmt", "=", "None", ")", ":", "for", "d", "in", "self", ".", "__list", ":", "d", ".", "plot", "(", "fmt", "=", "fmt", ")", "return", "None" ]
Make a simple plot of the legend. Simply calls Decor.plot() on all of its members. TODO: Build a more attractive plot.
[ "Make", "a", "simple", "plot", "of", "the", "legend", "." ]
python
test
21.833333
CodeReclaimers/neat-python
examples/circuits/evolve.py
https://github.com/CodeReclaimers/neat-python/blob/e3dbe77c0d776eae41d598e6439e6ac02ab90b18/examples/circuits/evolve.py#L180-L200
def mutate_add_connection(self, config): ''' Attempt to add a new connection, the only restriction being that the output node cannot be one of the network input pins. ''' possible_outputs = list(iterkeys(self.nodes)) out_node = choice(possible_outputs) possible_i...
[ "def", "mutate_add_connection", "(", "self", ",", "config", ")", ":", "possible_outputs", "=", "list", "(", "iterkeys", "(", "self", ".", "nodes", ")", ")", "out_node", "=", "choice", "(", "possible_outputs", ")", "possible_inputs", "=", "possible_outputs", "+...
Attempt to add a new connection, the only restriction being that the output node cannot be one of the network input pins.
[ "Attempt", "to", "add", "a", "new", "connection", "the", "only", "restriction", "being", "that", "the", "output", "node", "cannot", "be", "one", "of", "the", "network", "input", "pins", "." ]
python
train
32.238095
rameshg87/pyremotevbox
pyremotevbox/ZSI/wstools/c14n.py
https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/wstools/c14n.py#L413-L433
def Canonicalize(node, output=None, **kw): '''Canonicalize(node, output=None, **kw) -> UTF-8 Canonicalize a DOM document/element node and all descendents. Return the text; if output is specified then output.write will be called to output the text and None will be returned Keyword parameters: ...
[ "def", "Canonicalize", "(", "node", ",", "output", "=", "None", ",", "*", "*", "kw", ")", ":", "if", "output", ":", "apply", "(", "_implementation", ",", "(", "node", ",", "output", ".", "write", ")", ",", "kw", ")", "else", ":", "s", "=", "Strin...
Canonicalize(node, output=None, **kw) -> UTF-8 Canonicalize a DOM document/element node and all descendents. Return the text; if output is specified then output.write will be called to output the text and None will be returned Keyword parameters: nsdict: a dictionary of prefix:uri namespace ent...
[ "Canonicalize", "(", "node", "output", "=", "None", "**", "kw", ")", "-", ">", "UTF", "-", "8" ]
python
train
42.47619
pbrady/fastcache
scripts/threadsafety.py
https://github.com/pbrady/fastcache/blob/c216def5d29808585123562b56a9a083ea337cad/scripts/threadsafety.py#L59-L67
def run_fib_with_clear(r): """ Run Fibonacci generator r times. """ for i in range(r): if randint(RAND_MIN, RAND_MAX) == RAND_MIN: fib.cache_clear() fib2.cache_clear() res = fib(PythonInt(FIB)) if RESULT != res: raise ValueError("Expected %d, Got %d" %...
[ "def", "run_fib_with_clear", "(", "r", ")", ":", "for", "i", "in", "range", "(", "r", ")", ":", "if", "randint", "(", "RAND_MIN", ",", "RAND_MAX", ")", "==", "RAND_MIN", ":", "fib", ".", "cache_clear", "(", ")", "fib2", ".", "cache_clear", "(", ")", ...
Run Fibonacci generator r times.
[ "Run", "Fibonacci", "generator", "r", "times", "." ]
python
train
36.333333
python-openxml/python-docx
docx/styles/style.py
https://github.com/python-openxml/python-docx/blob/6756f6cd145511d3eb6d1d188beea391b1ddfd53/docx/styles/style.py#L217-L230
def next_paragraph_style(self): """ |_ParagraphStyle| object representing the style to be applied automatically to a new paragraph inserted after a paragraph of this style. Returns self if no next paragraph style is defined. Assigning |None| or *self* removes the setting such tha...
[ "def", "next_paragraph_style", "(", "self", ")", ":", "next_style_elm", "=", "self", ".", "_element", ".", "next_style", "if", "next_style_elm", "is", "None", ":", "return", "self", "if", "next_style_elm", ".", "type", "!=", "WD_STYLE_TYPE", ".", "PARAGRAPH", ...
|_ParagraphStyle| object representing the style to be applied automatically to a new paragraph inserted after a paragraph of this style. Returns self if no next paragraph style is defined. Assigning |None| or *self* removes the setting such that new paragraphs are created using this same...
[ "|_ParagraphStyle|", "object", "representing", "the", "style", "to", "be", "applied", "automatically", "to", "a", "new", "paragraph", "inserted", "after", "a", "paragraph", "of", "this", "style", ".", "Returns", "self", "if", "no", "next", "paragraph", "style", ...
python
train
43.857143
ethan92429/onshapepy
onshapepy/document.py
https://github.com/ethan92429/onshapepy/blob/61dc7ccbdc6095fa6cc3b4a414e2f72d03d1c9df/onshapepy/document.py#L63-L81
def find_element(self, name, type=ElementType.ANY): """Find an elemnent in the document with the given name - could be a PartStudio, Assembly or blob. Args: name: str the name of the element. Returns: - onshapepy.uri of the element """ f...
[ "def", "find_element", "(", "self", ",", "name", ",", "type", "=", "ElementType", ".", "ANY", ")", ":", "for", "e", "in", "self", ".", "e_list", ":", "# if a type is specified and this isn't it, move to the next loop.", "if", "type", ".", "value", "and", "not", ...
Find an elemnent in the document with the given name - could be a PartStudio, Assembly or blob. Args: name: str the name of the element. Returns: - onshapepy.uri of the element
[ "Find", "an", "elemnent", "in", "the", "document", "with", "the", "given", "name", "-", "could", "be", "a", "PartStudio", "Assembly", "or", "blob", "." ]
python
train
32.210526
pkgw/pwkit
pwkit/synphot.py
https://github.com/pkgw/pwkit/blob/d40957a1c3d2ea34e7ceac2267ee9635135f2793/pwkit/synphot.py#L408-L431
def blackbody(self, T): """Calculate the contribution of a blackbody through this filter. *T* is the blackbody temperature in Kelvin. Returns a band-averaged spectrum in f_λ units. We use the composite Simpson's rule to integrate over the points at which the filter response is s...
[ "def", "blackbody", "(", "self", ",", "T", ")", ":", "from", "scipy", ".", "integrate", "import", "simps", "d", "=", "self", ".", "_ensure_data", "(", ")", "# factor of pi is going from specific intensity (sr^-1) to unidirectional", "# inner factor of 1e-8 is Å to cm", ...
Calculate the contribution of a blackbody through this filter. *T* is the blackbody temperature in Kelvin. Returns a band-averaged spectrum in f_λ units. We use the composite Simpson's rule to integrate over the points at which the filter response is sampled. Note that this is a differe...
[ "Calculate", "the", "contribution", "of", "a", "blackbody", "through", "this", "filter", ".", "*", "T", "*", "is", "the", "blackbody", "temperature", "in", "Kelvin", ".", "Returns", "a", "band", "-", "averaged", "spectrum", "in", "f_λ", "units", "." ]
python
train
39.25
silver-castle/mach9
mach9/router.py
https://github.com/silver-castle/mach9/blob/7a623aab3c70d89d36ade6901b6307e115400c5e/mach9/router.py#L253-L266
def find_route_by_view_name(self, view_name): """Find a route in the router based on the specified view name. :param view_name: string of view name to search by :return: tuple containing (uri, Route) """ if not view_name: return (None, None) for uri, route i...
[ "def", "find_route_by_view_name", "(", "self", ",", "view_name", ")", ":", "if", "not", "view_name", ":", "return", "(", "None", ",", "None", ")", "for", "uri", ",", "route", "in", "self", ".", "routes_all", ".", "items", "(", ")", ":", "if", "route", ...
Find a route in the router based on the specified view name. :param view_name: string of view name to search by :return: tuple containing (uri, Route)
[ "Find", "a", "route", "in", "the", "router", "based", "on", "the", "specified", "view", "name", "." ]
python
train
31.142857
bramwelt/field
field/__init__.py
https://github.com/bramwelt/field/blob/05f38170d080fb48e76aa984bf4aa6b3d05ea6dc/field/__init__.py#L99-L119
def main(): """ Main Entry Point """ args = parser.parse_args() filehandle = args.filename delim = args.delimiter columns = args.columns[0] if not columns: for line in filehandle: print line, exit(0) cs = list(chain.from_iterable(columns)) fields = (...
[ "def", "main", "(", ")", ":", "args", "=", "parser", ".", "parse_args", "(", ")", "filehandle", "=", "args", ".", "filename", "delim", "=", "args", ".", "delimiter", "columns", "=", "args", ".", "columns", "[", "0", "]", "if", "not", "columns", ":", ...
Main Entry Point
[ "Main", "Entry", "Point" ]
python
train
20.761905
eddiejessup/spatious
spatious/distance.py
https://github.com/eddiejessup/spatious/blob/b7ae91bec029e85a45a7f303ee184076433723cd/spatious/distance.py#L28-L53
def csep_close(ra, rb): """Return the closest separation vector between each point in one set, and every point in a second set. Parameters ---------- ra, rb: float array-like, shape (n, d) and (m, d) in d dimensions. Two sets of points. `ra` is the set of points from which the closest ...
[ "def", "csep_close", "(", "ra", ",", "rb", ")", ":", "seps", "=", "csep", "(", "ra", ",", "rb", ")", "seps_sq", "=", "np", ".", "sum", "(", "np", ".", "square", "(", "seps", ")", ",", "axis", "=", "-", "1", ")", "i_close", "=", "np", ".", "...
Return the closest separation vector between each point in one set, and every point in a second set. Parameters ---------- ra, rb: float array-like, shape (n, d) and (m, d) in d dimensions. Two sets of points. `ra` is the set of points from which the closest separation vectors to points...
[ "Return", "the", "closest", "separation", "vector", "between", "each", "point", "in", "one", "set", "and", "every", "point", "in", "a", "second", "set", "." ]
python
train
31.269231
saltstack/salt
salt/utils/path.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/path.py#L303-L314
def which_bin(exes): ''' Scan over some possible executables and return the first one that is found ''' if not isinstance(exes, Iterable): return None for exe in exes: path = which(exe) if not path: continue return path return None
[ "def", "which_bin", "(", "exes", ")", ":", "if", "not", "isinstance", "(", "exes", ",", "Iterable", ")", ":", "return", "None", "for", "exe", "in", "exes", ":", "path", "=", "which", "(", "exe", ")", "if", "not", "path", ":", "continue", "return", ...
Scan over some possible executables and return the first one that is found
[ "Scan", "over", "some", "possible", "executables", "and", "return", "the", "first", "one", "that", "is", "found" ]
python
train
24
dwavesystems/dimod
dimod/utilities.py
https://github.com/dwavesystems/dimod/blob/beff1b7f86b559d923ac653c1de6d593876d6d38/dimod/utilities.py#L147-L206
def ising_to_qubo(h, J, offset=0.0): """Convert an Ising problem to a QUBO problem. Map an Ising model defined on spins (variables with {-1, +1} values) to quadratic unconstrained binary optimization (QUBO) formulation :math:`x' Q x` defined over binary variables (0 or 1 values), where the linear ter...
[ "def", "ising_to_qubo", "(", "h", ",", "J", ",", "offset", "=", "0.0", ")", ":", "# the linear biases are the easiest", "q", "=", "{", "(", "v", ",", "v", ")", ":", "2.", "*", "bias", "for", "v", ",", "bias", "in", "iteritems", "(", "h", ")", "}", ...
Convert an Ising problem to a QUBO problem. Map an Ising model defined on spins (variables with {-1, +1} values) to quadratic unconstrained binary optimization (QUBO) formulation :math:`x' Q x` defined over binary variables (0 or 1 values), where the linear term is contained along the diagonal of Q. ...
[ "Convert", "an", "Ising", "problem", "to", "a", "QUBO", "problem", "." ]
python
train
34.966667
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py#L828-L863
def _AddClearFieldMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def ClearField(self, field_name): try: field = message_descriptor.fields_by_name[field_name] except KeyError: try: field = message_descriptor.oneofs_by_name[field_name] if field in self._one...
[ "def", "_AddClearFieldMethod", "(", "message_descriptor", ",", "cls", ")", ":", "def", "ClearField", "(", "self", ",", "field_name", ")", ":", "try", ":", "field", "=", "message_descriptor", ".", "fields_by_name", "[", "field_name", "]", "except", "KeyError", ...
Helper for _AddMessageMethods().
[ "Helper", "for", "_AddMessageMethods", "()", "." ]
python
train
38.638889
chaoss/grimoirelab-perceval
perceval/backends/core/git.py
https://github.com/chaoss/grimoirelab-perceval/blob/41c908605e88b7ebc3a536c643fa0f212eaf9e0e/perceval/backends/core/git.py#L984-L1041
def log(self, from_date=None, to_date=None, branches=None, encoding='utf-8'): """Read the commit log from the repository. The method returns the Git log of the repository using the following options: git log --raw --numstat --pretty=fuller --decorate=full --all --re...
[ "def", "log", "(", "self", ",", "from_date", "=", "None", ",", "to_date", "=", "None", ",", "branches", "=", "None", ",", "encoding", "=", "'utf-8'", ")", ":", "if", "self", ".", "is_empty", "(", ")", ":", "logger", ".", "warning", "(", "\"Git %s rep...
Read the commit log from the repository. The method returns the Git log of the repository using the following options: git log --raw --numstat --pretty=fuller --decorate=full --all --reverse --topo-order --parents -M -C -c --remotes=origin When `fro...
[ "Read", "the", "commit", "log", "from", "the", "repository", "." ]
python
test
39.603448
rbarrois/django_xworkflows
django_xworkflows/models.py
https://github.com/rbarrois/django_xworkflows/blob/7f6c3e54e7fd64d39541bffa654c7f2e28685270/django_xworkflows/models.py#L414-L423
def log_transition(self, transition, from_state, instance, *args, **kwargs): """Generic transition logging.""" save = kwargs.pop('save', True) log = kwargs.pop('log', True) super(Workflow, self).log_transition( transition, from_state, instance, *args, **kwargs) if sav...
[ "def", "log_transition", "(", "self", ",", "transition", ",", "from_state", ",", "instance", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "save", "=", "kwargs", ".", "pop", "(", "'save'", ",", "True", ")", "log", "=", "kwargs", ".", "pop", ...
Generic transition logging.
[ "Generic", "transition", "logging", "." ]
python
train
43.2
mitsei/dlkit
dlkit/json_/learning/sessions.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/learning/sessions.py#L2111-L2145
def get_requisite_objectives(self, objective_id): """Gets a list of ``Objectives`` that are the immediate requisites for the given ``Objective``. In plenary mode, the returned list contains all of the immediate requisites, or an error results if an ``Objective`` is not found or inaccess...
[ "def", "get_requisite_objectives", "(", "self", ",", "objective_id", ")", ":", "# Implemented from template for", "# osid.learning.ObjectiveRequisiteSession.get_requisite_objectives_template", "# NOTE: This implementation currently ignores plenary view", "requisite_type", "=", "Type", "(...
Gets a list of ``Objectives`` that are the immediate requisites for the given ``Objective``. In plenary mode, the returned list contains all of the immediate requisites, or an error results if an ``Objective`` is not found or inaccessible. Otherwise, inaccessible ``Objectives`` may be o...
[ "Gets", "a", "list", "of", "Objectives", "that", "are", "the", "immediate", "requisites", "for", "the", "given", "Objective", "." ]
python
train
57.914286
materialsproject/pymatgen
pymatgen/io/abinit/utils.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/abinit/utils.py#L412-L433
def find_1wf_files(self): """ Abinit adds the idir-ipert index at the end of the 1WF file and this breaks the extension e.g. out_1WF4. This method scans the files in the directories and returns a list of namedtuple Each named tuple gives the `path` of the 1FK file and the `pertcase` inde...
[ "def", "find_1wf_files", "(", "self", ")", ":", "regex", "=", "re", ".", "compile", "(", "r\"out_1WF(\\d+)(\\.nc)?$\"", ")", "wf_paths", "=", "[", "f", "for", "f", "in", "self", ".", "list_filepaths", "(", ")", "if", "regex", ".", "match", "(", "os", "...
Abinit adds the idir-ipert index at the end of the 1WF file and this breaks the extension e.g. out_1WF4. This method scans the files in the directories and returns a list of namedtuple Each named tuple gives the `path` of the 1FK file and the `pertcase` index.
[ "Abinit", "adds", "the", "idir", "-", "ipert", "index", "at", "the", "end", "of", "the", "1WF", "file", "and", "this", "breaks", "the", "extension", "e", ".", "g", ".", "out_1WF4", ".", "This", "method", "scans", "the", "files", "in", "the", "directori...
python
train
43.590909
resync/resync
resync/client.py
https://github.com/resync/resync/blob/98292c17b2c00f2d6f5191c6ab51fef8c292a018/resync/client.py#L93-L104
def read_resource_list(self, uri): """Read resource list from specified URI else raise exception.""" self.logger.info("Reading resource list %s" % (uri)) try: resource_list = ResourceList(allow_multifile=self.allow_multifile, mapper=self.mappe...
[ "def", "read_resource_list", "(", "self", ",", "uri", ")", ":", "self", ".", "logger", ".", "info", "(", "\"Reading resource list %s\"", "%", "(", "uri", ")", ")", "try", ":", "resource_list", "=", "ResourceList", "(", "allow_multifile", "=", "self", ".", ...
Read resource list from specified URI else raise exception.
[ "Read", "resource", "list", "from", "specified", "URI", "else", "raise", "exception", "." ]
python
train
49.666667
heitzmann/gdspy
gdspy/__init__.py
https://github.com/heitzmann/gdspy/blob/2c8d1313248c544e2066d19095b7ad7158c79bc9/gdspy/__init__.py#L4047-L4095
def inside(points, polygons, short_circuit='any', precision=0.001): """ Test whether each of the points is within the given set of polygons. Parameters ---------- points : array-like[N][2] or list of array-like[N][2] Coordinates of the points to be tested or groups of points to be t...
[ "def", "inside", "(", "points", ",", "polygons", ",", "short_circuit", "=", "'any'", ",", "precision", "=", "0.001", ")", ":", "poly", "=", "[", "]", "if", "isinstance", "(", "polygons", ",", "PolygonSet", ")", ":", "poly", ".", "extend", "(", "polygon...
Test whether each of the points is within the given set of polygons. Parameters ---------- points : array-like[N][2] or list of array-like[N][2] Coordinates of the points to be tested or groups of points to be tested together. polygons : polygon or array-like Polygons to be test...
[ "Test", "whether", "each", "of", "the", "points", "is", "within", "the", "given", "set", "of", "polygons", "." ]
python
train
38.204082
gem/oq-engine
openquake/risklib/scientific.py
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/scientific.py#L242-L255
def _cov_for(self, imls): """ Clip `imls` to the range associated with the support of the vulnerability function and returns the corresponding covariance values by linear interpolation. For instance if the range is [0.005, 0.0269] and the imls are [0.0049, 0.006, 0.027], ...
[ "def", "_cov_for", "(", "self", ",", "imls", ")", ":", "return", "self", ".", "_covs_i1d", "(", "numpy", ".", "piecewise", "(", "imls", ",", "[", "imls", ">", "self", ".", "imls", "[", "-", "1", "]", ",", "imls", "<", "self", ".", "imls", "[", ...
Clip `imls` to the range associated with the support of the vulnerability function and returns the corresponding covariance values by linear interpolation. For instance if the range is [0.005, 0.0269] and the imls are [0.0049, 0.006, 0.027], the clipped imls are [0.005, 0.006, 0...
[ "Clip", "imls", "to", "the", "range", "associated", "with", "the", "support", "of", "the", "vulnerability", "function", "and", "returns", "the", "corresponding", "covariance", "values", "by", "linear", "interpolation", ".", "For", "instance", "if", "the", "range...
python
train
41.142857
napalm-automation/napalm-junos
napalm_junos/junos.py
https://github.com/napalm-automation/napalm-junos/blob/78c0d161daf2abf26af5835b773f6db57c46efff/napalm_junos/junos.py#L255-L274
def get_facts(self): """Return facts of the device.""" output = self.device.facts uptime = self.device.uptime or -1 interfaces = junos_views.junos_iface_table(self.device) interfaces.get() interface_list = interfaces.keys() return { 'vendor': u'Juni...
[ "def", "get_facts", "(", "self", ")", ":", "output", "=", "self", ".", "device", ".", "facts", "uptime", "=", "self", ".", "device", ".", "uptime", "or", "-", "1", "interfaces", "=", "junos_views", ".", "junos_iface_table", "(", "self", ".", "device", ...
Return facts of the device.
[ "Return", "facts", "of", "the", "device", "." ]
python
train
36.1
mitsei/dlkit
dlkit/json_/relationship/sessions.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/relationship/sessions.py#L2065-L2085
def get_root_families(self): """Gets the root families in the family hierarchy. A node with no parents is an orphan. While all family ``Ids`` are known to the hierarchy, an orphan does not appear in the hierarchy unless explicitly added as a root node or child of another node. ...
[ "def", "get_root_families", "(", "self", ")", ":", "# Implemented from template for", "# osid.resource.BinHierarchySession.get_root_bins", "if", "self", ".", "_catalog_session", "is", "not", "None", ":", "return", "self", ".", "_catalog_session", ".", "get_root_catalogs", ...
Gets the root families in the family hierarchy. A node with no parents is an orphan. While all family ``Ids`` are known to the hierarchy, an orphan does not appear in the hierarchy unless explicitly added as a root node or child of another node. return: (osid.relationship.Famil...
[ "Gets", "the", "root", "families", "in", "the", "family", "hierarchy", "." ]
python
train
43.571429
disqus/django-mailviews
mailviews/previews.py
https://github.com/disqus/django-mailviews/blob/9993d5e911d545b3bc038433986c5f6812e7e965/mailviews/previews.py#L104-L112
def detail_view(self, request, module, preview): """ Looks up a preview in the index, returning a detail view response. """ try: preview = self.__previews[module][preview] except KeyError: raise Http404 # The provided module/preview does not exist in the ...
[ "def", "detail_view", "(", "self", ",", "request", ",", "module", ",", "preview", ")", ":", "try", ":", "preview", "=", "self", ".", "__previews", "[", "module", "]", "[", "preview", "]", "except", "KeyError", ":", "raise", "Http404", "# The provided modul...
Looks up a preview in the index, returning a detail view response.
[ "Looks", "up", "a", "preview", "in", "the", "index", "returning", "a", "detail", "view", "response", "." ]
python
valid
40.222222
hawkular/hawkular-client-python
hawkular/metrics.py
https://github.com/hawkular/hawkular-client-python/blob/52371f9ebabbe310efee2a8ff8eb735ccc0654bb/hawkular/metrics.py#L176-L212
def query_metric_stats(self, metric_type, metric_id=None, start=None, end=None, bucketDuration=None, **query_options): """ Query for metric aggregates from the server. This is called buckets in the Hawkular-Metrics documentation. :param metric_type: MetricType to be matched (required) :...
[ "def", "query_metric_stats", "(", "self", ",", "metric_type", ",", "metric_id", "=", "None", ",", "start", "=", "None", ",", "end", "=", "None", ",", "bucketDuration", "=", "None", ",", "*", "*", "query_options", ")", ":", "if", "start", "is", "not", "...
Query for metric aggregates from the server. This is called buckets in the Hawkular-Metrics documentation. :param metric_type: MetricType to be matched (required) :param metric_id: Exact string matching metric id or None for tags matching only :param start: Milliseconds since epoch or datetime ...
[ "Query", "for", "metric", "aggregates", "from", "the", "server", ".", "This", "is", "called", "buckets", "in", "the", "Hawkular", "-", "Metrics", "documentation", "." ]
python
train
48.324324
DataONEorg/d1_python
gmn/src/d1_gmn/app/views/assert_db.py
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/gmn/src/d1_gmn/app/views/assert_db.py#L139-L175
def post_has_mime_parts(request, parts): """Validate that a MMP POST contains all required sections. :param request: Django Request :param parts: [(part_type, part_name), ...] :return: None or raises exception. Where information is stored in the request: part_type header: request.META['HTTP_<U...
[ "def", "post_has_mime_parts", "(", "request", ",", "parts", ")", ":", "missing", "=", "[", "]", "for", "part_type", ",", "part_name", "in", "parts", ":", "if", "part_type", "==", "'header'", ":", "if", "'HTTP_'", "+", "part_name", ".", "upper", "(", ")",...
Validate that a MMP POST contains all required sections. :param request: Django Request :param parts: [(part_type, part_name), ...] :return: None or raises exception. Where information is stored in the request: part_type header: request.META['HTTP_<UPPER CASE NAME>'] part_type file: request.FI...
[ "Validate", "that", "a", "MMP", "POST", "contains", "all", "required", "sections", "." ]
python
train
36.486486
gitpython-developers/GitPython
git/util.py
https://github.com/gitpython-developers/GitPython/blob/1f66e25c25cde2423917ee18c4704fff83b837d1/git/util.py#L924-L935
def list_items(cls, repo, *args, **kwargs): """ Find all items of this type - subclasses can specify args and kwargs differently. If no args are given, subclasses are obliged to return all items if no additional arguments arg given. :note: Favor the iter_items method as it will ...
[ "def", "list_items", "(", "cls", ",", "repo", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "out_list", "=", "IterableList", "(", "cls", ".", "_id_attribute_", ")", "out_list", ".", "extend", "(", "cls", ".", "iter_items", "(", "repo", ",", "*...
Find all items of this type - subclasses can specify args and kwargs differently. If no args are given, subclasses are obliged to return all items if no additional arguments arg given. :note: Favor the iter_items method as it will :return:list(Item,...) list of item instances
[ "Find", "all", "items", "of", "this", "type", "-", "subclasses", "can", "specify", "args", "and", "kwargs", "differently", ".", "If", "no", "args", "are", "given", "subclasses", "are", "obliged", "to", "return", "all", "items", "if", "no", "additional", "a...
python
train
42.083333
decryptus/sonicprobe
sonicprobe/libs/urisup.py
https://github.com/decryptus/sonicprobe/blob/72f73f3a40d2982d79ad68686e36aa31d94b76f8/sonicprobe/libs/urisup.py#L589-L618
def uri_tree_encode(uri_tree, type_host = HOST_REG_NAME): """ Percent/Query encode a raw URI tree. """ scheme, authority, path, query, fragment = uri_tree if authority: user, passwd, host, port = authority if user: user = pct_encode(user, USER_ENCDCT) if passwd: ...
[ "def", "uri_tree_encode", "(", "uri_tree", ",", "type_host", "=", "HOST_REG_NAME", ")", ":", "scheme", ",", "authority", ",", "path", ",", "query", ",", "fragment", "=", "uri_tree", "if", "authority", ":", "user", ",", "passwd", ",", "host", ",", "port", ...
Percent/Query encode a raw URI tree.
[ "Percent", "/", "Query", "encode", "a", "raw", "URI", "tree", "." ]
python
train
39.033333
fastai/fastai
fastai/vision/image.py
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L27-L29
def bb2hw(a:Collection[int])->np.ndarray: "Convert bounding box points from (width,height,center) to (height,width,top,left)." return np.array([a[1],a[0],a[3]-a[1],a[2]-a[0]])
[ "def", "bb2hw", "(", "a", ":", "Collection", "[", "int", "]", ")", "->", "np", ".", "ndarray", ":", "return", "np", ".", "array", "(", "[", "a", "[", "1", "]", ",", "a", "[", "0", "]", ",", "a", "[", "3", "]", "-", "a", "[", "1", "]", "...
Convert bounding box points from (width,height,center) to (height,width,top,left).
[ "Convert", "bounding", "box", "points", "from", "(", "width", "height", "center", ")", "to", "(", "height", "width", "top", "left", ")", "." ]
python
train
60.333333
novopl/peltak
src/peltak/core/git.py
https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/core/git.py#L488-L502
def tags(): # type: () -> List[str] """ Returns all tags in the repo. Returns: list[str]: List of all tags in the repo, sorted as versions. All tags returned by this function will be parsed as if the contained versions (using ``v:refname`` sorting). """ return shell.run( 'g...
[ "def", "tags", "(", ")", ":", "# type: () -> List[str]", "return", "shell", ".", "run", "(", "'git tag --sort=v:refname'", ",", "capture", "=", "True", ",", "never_pretend", "=", "True", ")", ".", "stdout", ".", "strip", "(", ")", ".", "splitlines", "(", "...
Returns all tags in the repo. Returns: list[str]: List of all tags in the repo, sorted as versions. All tags returned by this function will be parsed as if the contained versions (using ``v:refname`` sorting).
[ "Returns", "all", "tags", "in", "the", "repo", "." ]
python
train
27.6
saltstack/salt
salt/matchers/nodegroup_match.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/matchers/nodegroup_match.py#L14-L30
def match(tgt, nodegroups=None, opts=None): ''' This is a compatibility matcher and is NOT called when using nodegroups for remote execution, but is called when the nodegroups matcher is used in states ''' if not opts: opts = __opts__ if not nodegroups: log.debug('Nodegroup m...
[ "def", "match", "(", "tgt", ",", "nodegroups", "=", "None", ",", "opts", "=", "None", ")", ":", "if", "not", "opts", ":", "opts", "=", "__opts__", "if", "not", "nodegroups", ":", "log", ".", "debug", "(", "'Nodegroup matcher called with no nodegroups.'", "...
This is a compatibility matcher and is NOT called when using nodegroups for remote execution, but is called when the nodegroups matcher is used in states
[ "This", "is", "a", "compatibility", "matcher", "and", "is", "NOT", "called", "when", "using", "nodegroups", "for", "remote", "execution", "but", "is", "called", "when", "the", "nodegroups", "matcher", "is", "used", "in", "states" ]
python
train
33.588235
cocagne/txdbus
txdbus/client.py
https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/client.py#L81-L89
def _cbGotHello(self, busName): """ Called in reply to the initial Hello remote method invocation """ self.busName = busName # print 'Connection Bus Name = ', self.busName self.factory._ok(self)
[ "def", "_cbGotHello", "(", "self", ",", "busName", ")", ":", "self", ".", "busName", "=", "busName", "# print 'Connection Bus Name = ', self.busName", "self", ".", "factory", ".", "_ok", "(", "self", ")" ]
Called in reply to the initial Hello remote method invocation
[ "Called", "in", "reply", "to", "the", "initial", "Hello", "remote", "method", "invocation" ]
python
train
26.222222
studionow/pybrightcove
pybrightcove/video.py
https://github.com/studionow/pybrightcove/blob/19c946b689a80156e070fe9bc35589c4b768e614/pybrightcove/video.py#L412-L438
def _load(self, data): """ Deserialize a dictionary of data into a ``pybrightcove.video.Video`` object. """ self.raw_data = data self.creation_date = _convert_tstamp(data['creationDate']) self.economics = data['economics'] self.id = data['id'] self...
[ "def", "_load", "(", "self", ",", "data", ")", ":", "self", ".", "raw_data", "=", "data", "self", ".", "creation_date", "=", "_convert_tstamp", "(", "data", "[", "'creationDate'", "]", ")", "self", ".", "economics", "=", "data", "[", "'economics'", "]", ...
Deserialize a dictionary of data into a ``pybrightcove.video.Video`` object.
[ "Deserialize", "a", "dictionary", "of", "data", "into", "a", "pybrightcove", ".", "video", ".", "Video", "object", "." ]
python
train
43.62963
metapensiero/metapensiero.signal
src/metapensiero/signal/utils.py
https://github.com/metapensiero/metapensiero.signal/blob/1cbbb2e4bff00bf4887163b08b70d278e472bfe3/src/metapensiero/signal/utils.py#L248-L274
def signal(*args, **kwargs): from .core import Signal """A signal decorator designed to work both in the simpler way, like: .. code:: python @signal def validation_function(arg1, ...): '''Some doc''' and also as a double-called decorator, like .. code:: python @signa...
[ "def", "signal", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "from", ".", "core", "import", "Signal", "if", "len", "(", "args", ")", "==", "1", "and", "len", "(", "kwargs", ")", "==", "0", "and", "callable", "(", "args", "[", "0", "]",...
A signal decorator designed to work both in the simpler way, like: .. code:: python @signal def validation_function(arg1, ...): '''Some doc''' and also as a double-called decorator, like .. code:: python @signal(SignalOptions.EXEC_CONCURRENT) def validation_function(ar...
[ "A", "signal", "decorator", "designed", "to", "work", "both", "in", "the", "simpler", "way", "like", ":" ]
python
train
25.37037
twisted/mantissa
xmantissa/prefs.py
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/prefs.py#L202-L219
def tabbedPane(self, req, tag): """ Render a tabbed pane tab for each top-level L{xmantissa.ixmantissa.IPreferenceCollection} tab """ navigation = webnav.getTabs(self.aggregator.getPreferenceCollections()) pages = list() for tab in navigation: f = inev...
[ "def", "tabbedPane", "(", "self", ",", "req", ",", "tag", ")", ":", "navigation", "=", "webnav", ".", "getTabs", "(", "self", ".", "aggregator", ".", "getPreferenceCollections", "(", ")", ")", "pages", "=", "list", "(", ")", "for", "tab", "in", "naviga...
Render a tabbed pane tab for each top-level L{xmantissa.ixmantissa.IPreferenceCollection} tab
[ "Render", "a", "tabbed", "pane", "tab", "for", "each", "top", "-", "level", "L", "{", "xmantissa", ".", "ixmantissa", ".", "IPreferenceCollection", "}", "tab" ]
python
train
36.944444
Xython/Linq.py
linq/standard/general.py
https://github.com/Xython/Linq.py/blob/ffb65f92f1df0d8161d5f835f5947554f6f33d72/linq/standard/general.py#L227-L239
def Shift(self, n): """ [ { 'self': [1, 2, 3, 4, 5], 'n': 3, 'assert': lambda ret: list(ret) == [4, 5, 1, 2, 3] } ] """ headn = tuple(Take(self, n)) yield from self yield from headn
[ "def", "Shift", "(", "self", ",", "n", ")", ":", "headn", "=", "tuple", "(", "Take", "(", "self", ",", "n", ")", ")", "yield", "from", "self", "yield", "from", "headn" ]
[ { 'self': [1, 2, 3, 4, 5], 'n': 3, 'assert': lambda ret: list(ret) == [4, 5, 1, 2, 3] } ]
[ "[", "{", "self", ":", "[", "1", "2", "3", "4", "5", "]", "n", ":", "3", "assert", ":", "lambda", "ret", ":", "list", "(", "ret", ")", "==", "[", "4", "5", "1", "2", "3", "]", "}", "]" ]
python
train
19.230769
vatlab/SoS
src/sos/substep_executor.py
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/substep_executor.py#L36-L116
def execute_substep(stmt, global_def, global_vars, task='', task_params='', proc_vars={}, shared_vars=[], config={}): '''Execute a substep with specific input etc Substep ...
[ "def", "execute_substep", "(", "stmt", ",", "global_def", ",", "global_vars", ",", "task", "=", "''", ",", "task_params", "=", "''", ",", "proc_vars", "=", "{", "}", ",", "shared_vars", "=", "[", "]", ",", "config", "=", "{", "}", ")", ":", "assert",...
Execute a substep with specific input etc Substep executed by this function should be self-contained. It can contain tasks (which will be sent to the master process) but not nested workflows. The executor checks step signatures and might skip the substep if it has been executed and the signature match...
[ "Execute", "a", "substep", "with", "specific", "input", "etc" ]
python
train
34.679012
saltstack/salt
salt/minion.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/minion.py#L2969-L2978
def _handle_decoded_payload(self, data): ''' Override this method if you wish to handle the decoded data differently. ''' # TODO: even do this?? data['to'] = int(data.get('to', self.opts['timeout'])) - 1 # Only forward the command if it didn't originate from ourse...
[ "def", "_handle_decoded_payload", "(", "self", ",", "data", ")", ":", "# TODO: even do this??", "data", "[", "'to'", "]", "=", "int", "(", "data", ".", "get", "(", "'to'", ",", "self", ".", "opts", "[", "'timeout'", "]", ")", ")", "-", "1", "# Only for...
Override this method if you wish to handle the decoded data differently.
[ "Override", "this", "method", "if", "you", "wish", "to", "handle", "the", "decoded", "data", "differently", "." ]
python
train
41.9
uw-it-aca/uw-restclients-canvas
uw_canvas/__init__.py
https://github.com/uw-it-aca/uw-restclients-canvas/blob/9845faf33d49a8f06908efc22640c001116d6ea2/uw_canvas/__init__.py#L194-L209
def _post_resource(self, url, body): """ Canvas POST method. """ params = {} self._set_as_user(params) headers = {'Content-Type': 'application/json', 'Accept': 'application/json', 'Connection': 'keep-alive'} url = url + self._...
[ "def", "_post_resource", "(", "self", ",", "url", ",", "body", ")", ":", "params", "=", "{", "}", "self", ".", "_set_as_user", "(", "params", ")", "headers", "=", "{", "'Content-Type'", ":", "'application/json'", ",", "'Accept'", ":", "'application/json'", ...
Canvas POST method.
[ "Canvas", "POST", "method", "." ]
python
test
35.5
FujiMakoto/AgentML
agentml/__init__.py
https://github.com/FujiMakoto/AgentML/blob/c8cb64b460d876666bf29ea2c682189874c7c403/agentml/__init__.py#L295-L321
def parse_substitutions(self, messages): """ Parse substitutions in a supplied message :param messages: A tuple messages being parsed (normalized, case preserved, raw) :type messages: tuple of (str, str, str) :return: Substituted messages (normalized, case preserved, raw) ...
[ "def", "parse_substitutions", "(", "self", ",", "messages", ")", ":", "# If no substitutions have been defined, just normalize the message", "if", "not", "self", ".", "_substitutions", ":", "self", ".", "_log", ".", "info", "(", "'No substitutions to process'", ")", "re...
Parse substitutions in a supplied message :param messages: A tuple messages being parsed (normalized, case preserved, raw) :type messages: tuple of (str, str, str) :return: Substituted messages (normalized, case preserved, raw) :rtype : tuple of (str, str, str)
[ "Parse", "substitutions", "in", "a", "supplied", "message", ":", "param", "messages", ":", "A", "tuple", "messages", "being", "parsed", "(", "normalized", "case", "preserved", "raw", ")", ":", "type", "messages", ":", "tuple", "of", "(", "str", "str", "str...
python
train
40.888889
blockstack/blockstack-core
blockstack/lib/operations/revoke.py
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/operations/revoke.py#L40-L102
def check( state_engine, nameop, block_id, checked_ops ): """ Revoke a name--make it available for registration. * it must be well-formed * its namespace must be ready. * the name must be registered * it must be sent by the name owner NAME_REVOKE isn't allowed during an import, so the name'...
[ "def", "check", "(", "state_engine", ",", "nameop", ",", "block_id", ",", "checked_ops", ")", ":", "name", "=", "nameop", "[", "'name'", "]", "sender", "=", "nameop", "[", "'sender'", "]", "namespace_id", "=", "get_namespace_from_name", "(", "name", ")", "...
Revoke a name--make it available for registration. * it must be well-formed * its namespace must be ready. * the name must be registered * it must be sent by the name owner NAME_REVOKE isn't allowed during an import, so the name's namespace must be ready. Return True if accepted Return Fal...
[ "Revoke", "a", "name", "--", "make", "it", "available", "for", "registration", ".", "*", "it", "must", "be", "well", "-", "formed", "*", "its", "namespace", "must", "be", "ready", ".", "*", "the", "name", "must", "be", "registered", "*", "it", "must", ...
python
train
32.206349
librosa/librosa
librosa/core/constantq.py
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/core/constantq.py#L756-L765
def __cqt_response(y, n_fft, hop_length, fft_basis, mode): '''Compute the filter response with a target STFT hop.''' # Compute the STFT matrix D = stft(y, n_fft=n_fft, hop_length=hop_length, window='ones', pad_mode=mode) # And filter response energy return fft_basis.dot(D...
[ "def", "__cqt_response", "(", "y", ",", "n_fft", ",", "hop_length", ",", "fft_basis", ",", "mode", ")", ":", "# Compute the STFT matrix", "D", "=", "stft", "(", "y", ",", "n_fft", "=", "n_fft", ",", "hop_length", "=", "hop_length", ",", "window", "=", "'...
Compute the filter response with a target STFT hop.
[ "Compute", "the", "filter", "response", "with", "a", "target", "STFT", "hop", "." ]
python
test
31.2
limix/limix-core
limix_core/util/preprocess.py
https://github.com/limix/limix-core/blob/5c590b4d351409f83ca320844b4897ce92203814/limix_core/util/preprocess.py#L33-L43
def covar_rescaling_factor_efficient(C): """ Returns the rescaling factor for the Gower normalizion on covariance matrix C the rescaled covariance matrix has sample variance of 1 """ n = C.shape[0] P = sp.eye(n) - sp.ones((n,n))/float(n) CP = C - C.mean(0)[:, sp.newaxis] trPCP = sp.sum(P...
[ "def", "covar_rescaling_factor_efficient", "(", "C", ")", ":", "n", "=", "C", ".", "shape", "[", "0", "]", "P", "=", "sp", ".", "eye", "(", "n", ")", "-", "sp", ".", "ones", "(", "(", "n", ",", "n", ")", ")", "/", "float", "(", "n", ")", "C...
Returns the rescaling factor for the Gower normalizion on covariance matrix C the rescaled covariance matrix has sample variance of 1
[ "Returns", "the", "rescaling", "factor", "for", "the", "Gower", "normalizion", "on", "covariance", "matrix", "C", "the", "rescaled", "covariance", "matrix", "has", "sample", "variance", "of", "1" ]
python
train
31.909091
apache/incubator-superset
superset/connectors/sqla/models.py
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/connectors/sqla/models.py#L302-L314
def make_sqla_column_compatible(self, sqla_col, label=None): """Takes a sql alchemy column object and adds label info if supported by engine. :param sqla_col: sql alchemy column instance :param label: alias/label that column is expected to have :return: either a sql alchemy column or lab...
[ "def", "make_sqla_column_compatible", "(", "self", ",", "sqla_col", ",", "label", "=", "None", ")", ":", "label_expected", "=", "label", "or", "sqla_col", ".", "name", "db_engine_spec", "=", "self", ".", "database", ".", "db_engine_spec", "if", "db_engine_spec",...
Takes a sql alchemy column object and adds label info if supported by engine. :param sqla_col: sql alchemy column instance :param label: alias/label that column is expected to have :return: either a sql alchemy column or label instance if supported by engine
[ "Takes", "a", "sql", "alchemy", "column", "object", "and", "adds", "label", "info", "if", "supported", "by", "engine", ".", ":", "param", "sqla_col", ":", "sql", "alchemy", "column", "instance", ":", "param", "label", ":", "alias", "/", "label", "that", ...
python
train
54
Yubico/python-pyhsm
pyhsm/yubikey.py
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/yubikey.py#L24-L48
def validate_otp(hsm, from_key): """ Try to validate an OTP from a YubiKey using the internal database on the YubiHSM. `from_key' is the modhex encoded string emitted when you press the button on your YubiKey. Will only return on succesfull validation. All failures will result in an L{pyhs...
[ "def", "validate_otp", "(", "hsm", ",", "from_key", ")", ":", "public_id", ",", "otp", "=", "split_id_otp", "(", "from_key", ")", "return", "hsm", ".", "db_validate_yubikey_otp", "(", "modhex_decode", "(", "public_id", ")", ".", "decode", "(", "'hex'", ")", ...
Try to validate an OTP from a YubiKey using the internal database on the YubiHSM. `from_key' is the modhex encoded string emitted when you press the button on your YubiKey. Will only return on succesfull validation. All failures will result in an L{pyhsm.exception.YHSM_CommandFailed}. @param ...
[ "Try", "to", "validate", "an", "OTP", "from", "a", "YubiKey", "using", "the", "internal", "database", "on", "the", "YubiHSM", "." ]
python
train
34.84
tango-controls/pytango
tango/databaseds/database.py
https://github.com/tango-controls/pytango/blob/9cf78c517c9cdc1081ff6d080a9646a740cc1d36/tango/databaseds/database.py#L1041-L1057
def DbPutClassProperty(self, argin): """ Create / Update class property(ies) :param argin: Str[0] = Tango class name Str[1] = Property number Str[2] = Property name Str[3] = Property value number Str[4] = Property value 1 Str[n] = Property value n .... ...
[ "def", "DbPutClassProperty", "(", "self", ",", "argin", ")", ":", "self", ".", "_log", ".", "debug", "(", "\"In DbPutClassProperty()\"", ")", "class_name", "=", "argin", "[", "0", "]", "nb_properties", "=", "int", "(", "argin", "[", "1", "]", ")", "self"...
Create / Update class property(ies) :param argin: Str[0] = Tango class name Str[1] = Property number Str[2] = Property name Str[3] = Property value number Str[4] = Property value 1 Str[n] = Property value n .... :type: tango.DevVarStringArray :ret...
[ "Create", "/", "Update", "class", "property", "(", "ies", ")" ]
python
train
34.294118
secdev/scapy
scapy/packet.py
https://github.com/secdev/scapy/blob/3ffe757c184017dd46464593a8f80f85abc1e79a/scapy/packet.py#L1539-L1553
def bind_bottom_up(lower, upper, __fval=None, **fval): """Bind 2 layers for dissection. The upper layer will be chosen for dissection on top of the lower layer, if ALL the passed arguments are validated. If multiple calls are made with the same # noqa: E501 layers, the last one will be used as default....
[ "def", "bind_bottom_up", "(", "lower", ",", "upper", ",", "__fval", "=", "None", ",", "*", "*", "fval", ")", ":", "if", "__fval", "is", "not", "None", ":", "fval", ".", "update", "(", "__fval", ")", "lower", ".", "payload_guess", "=", "lower", ".", ...
Bind 2 layers for dissection. The upper layer will be chosen for dissection on top of the lower layer, if ALL the passed arguments are validated. If multiple calls are made with the same # noqa: E501 layers, the last one will be used as default. ex: >>> bind_bottom_up(Ether, SNAP, type=0x1234)...
[ "Bind", "2", "layers", "for", "dissection", ".", "The", "upper", "layer", "will", "be", "chosen", "for", "dissection", "on", "top", "of", "the", "lower", "layer", "if", "ALL", "the", "passed", "arguments", "are", "validated", ".", "If", "multiple", "calls"...
python
train
49.666667
google/tangent
tangent/utils.py
https://github.com/google/tangent/blob/6533e83af09de7345d1b438512679992f080dcc9/tangent/utils.py#L41-L44
def array_size(x, axis): """Calculate the size of `x` along `axis` dimensions only.""" axis_shape = x.shape if axis is None else tuple(x.shape[a] for a in axis) return max(numpy.prod(axis_shape), 1)
[ "def", "array_size", "(", "x", ",", "axis", ")", ":", "axis_shape", "=", "x", ".", "shape", "if", "axis", "is", "None", "else", "tuple", "(", "x", ".", "shape", "[", "a", "]", "for", "a", "in", "axis", ")", "return", "max", "(", "numpy", ".", "...
Calculate the size of `x` along `axis` dimensions only.
[ "Calculate", "the", "size", "of", "x", "along", "axis", "dimensions", "only", "." ]
python
train
50.25
tgbugs/pyontutils
pyontutils/combinators.py
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/pyontutils/combinators.py#L17-L26
def make_predicate_object_combinator(function, p, o): """ Combinator to hold predicate object pairs until a subject is supplied and then call a function that accepts a subject, predicate, and object. Create a combinator to defer production of a triple until the missing pieces are supplied. ...
[ "def", "make_predicate_object_combinator", "(", "function", ",", "p", ",", "o", ")", ":", "def", "predicate_object_combinator", "(", "subject", ")", ":", "return", "function", "(", "subject", ",", "p", ",", "o", ")", "return", "predicate_object_combinator" ]
Combinator to hold predicate object pairs until a subject is supplied and then call a function that accepts a subject, predicate, and object. Create a combinator to defer production of a triple until the missing pieces are supplied. Note that the naming here tells you what is stored IN the comb...
[ "Combinator", "to", "hold", "predicate", "object", "pairs", "until", "a", "subject", "is", "supplied", "and", "then", "call", "a", "function", "that", "accepts", "a", "subject", "predicate", "and", "object", "." ]
python
train
57.7
mozilla/treeherder
treeherder/etl/text.py
https://github.com/mozilla/treeherder/blob/cc47bdec872e5c668d0f01df89517390a164cda3/treeherder/etl/text.py#L8-L22
def convert_unicode_character_to_ascii_repr(match_obj): """ Converts a matched pattern from a unicode character to an ASCII representation For example the emoji 🍆 would get converted to the literal <U+01F346> """ match = match_obj.group(0) code_point = ord(match) hex_repr = hex(code_point...
[ "def", "convert_unicode_character_to_ascii_repr", "(", "match_obj", ")", ":", "match", "=", "match_obj", ".", "group", "(", "0", ")", "code_point", "=", "ord", "(", "match", ")", "hex_repr", "=", "hex", "(", "code_point", ")", "hex_code_point", "=", "hex_repr"...
Converts a matched pattern from a unicode character to an ASCII representation For example the emoji 🍆 would get converted to the literal <U+01F346>
[ "Converts", "a", "matched", "pattern", "from", "a", "unicode", "character", "to", "an", "ASCII", "representation" ]
python
train
28.533333
pyviz/holoviews
holoviews/plotting/bokeh/callbacks.py
https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/plotting/bokeh/callbacks.py#L202-L242
def attributes_js(cls, attributes): """ Generates JS code to look up attributes on JS objects from an attributes specification dictionary. If the specification references a plotting particular plotting handle it will also generate JS code to get the ID of the object. Sim...
[ "def", "attributes_js", "(", "cls", ",", "attributes", ")", ":", "assign_template", "=", "'{assign}{{id: {obj_name}[\"id\"], value: {obj_name}{attr_getters}}};\\n'", "conditional_template", "=", "'if (({obj_name} != undefined)) {{ {assign} }}'", "code", "=", "''", "for", "key", ...
Generates JS code to look up attributes on JS objects from an attributes specification dictionary. If the specification references a plotting particular plotting handle it will also generate JS code to get the ID of the object. Simple example (when referencing cb_data or cb_obj): ...
[ "Generates", "JS", "code", "to", "look", "up", "attributes", "on", "JS", "objects", "from", "an", "attributes", "specification", "dictionary", ".", "If", "the", "specification", "references", "a", "plotting", "particular", "plotting", "handle", "it", "will", "al...
python
train
41.560976
note35/sinon
sinon/lib/assertion.py
https://github.com/note35/sinon/blob/f1d551b679b393d64d926a8a279320904c38d0f5/sinon/lib/assertion.py#L36-L43
def notCalled(cls, spy): #pylint: disable=invalid-name """ Checking the inspector is not called Args: SinonSpy """ cls.__is_spy(spy) if not (not spy.called): raise cls.failException(cls.message)
[ "def", "notCalled", "(", "cls", ",", "spy", ")", ":", "#pylint: disable=invalid-name", "cls", ".", "__is_spy", "(", "spy", ")", "if", "not", "(", "not", "spy", ".", "called", ")", ":", "raise", "cls", ".", "failException", "(", "cls", ".", "message", "...
Checking the inspector is not called Args: SinonSpy
[ "Checking", "the", "inspector", "is", "not", "called", "Args", ":", "SinonSpy" ]
python
train
30.875
PGower/PyCanvas
pycanvas/apis/conversations.py
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/conversations.py#L193-L244
def get_single_conversation(self, id, auto_mark_as_read=None, filter=None, filter_mode=None, interleave_submissions=None, scope=None): """ Get a single conversation. Returns information for a single conversation for the current user. Response includes all fields that are present in...
[ "def", "get_single_conversation", "(", "self", ",", "id", ",", "auto_mark_as_read", "=", "None", ",", "filter", "=", "None", ",", "filter_mode", "=", "None", ",", "interleave_submissions", "=", "None", ",", "scope", "=", "None", ")", ":", "path", "=", "{",...
Get a single conversation. Returns information for a single conversation for the current user. Response includes all fields that are present in the list/index action as well as messages and extended participant information.
[ "Get", "a", "single", "conversation", ".", "Returns", "information", "for", "a", "single", "conversation", "for", "the", "current", "user", ".", "Response", "includes", "all", "fields", "that", "are", "present", "in", "the", "list", "/", "index", "action", "...
python
train
46.384615
CitrineInformatics/python-citrination-client
citrination_client/search/client.py
https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/search/client.py#L140-L152
def pif_multi_search(self, multi_query): """ Run each in a list of PIF queries against Citrination. :param multi_query: :class:`MultiQuery` object to execute. :return: :class:`PifMultiSearchResult` object with the results of the query. """ failure_message = "Error while ...
[ "def", "pif_multi_search", "(", "self", ",", "multi_query", ")", ":", "failure_message", "=", "\"Error while making PIF multi search request\"", "response_dict", "=", "self", ".", "_get_success_json", "(", "self", ".", "_post", "(", "routes", ".", "pif_multi_search", ...
Run each in a list of PIF queries against Citrination. :param multi_query: :class:`MultiQuery` object to execute. :return: :class:`PifMultiSearchResult` object with the results of the query.
[ "Run", "each", "in", "a", "list", "of", "PIF", "queries", "against", "Citrination", "." ]
python
valid
48.153846
liminspace/dju-common
dju_common/file.py
https://github.com/liminspace/dju-common/blob/c68860bb84d454a35e66275841c20f38375c2135/dju_common/file.py#L6-L21
def truncate_file(f): """ Clear uploaded file and allow write to it. Only for not too big files!!! Also can clear simple opened file. Examples: truncate_file(request.FILES['file']) with open('/tmp/file', 'rb+') as f: truncate_file(f) """ if isinstance(f, InMemory...
[ "def", "truncate_file", "(", "f", ")", ":", "if", "isinstance", "(", "f", ",", "InMemoryUploadedFile", ")", ":", "f", ".", "file", "=", "StringIO", "(", ")", "else", ":", "f", ".", "seek", "(", "0", ")", "f", ".", "truncate", "(", "0", ")" ]
Clear uploaded file and allow write to it. Only for not too big files!!! Also can clear simple opened file. Examples: truncate_file(request.FILES['file']) with open('/tmp/file', 'rb+') as f: truncate_file(f)
[ "Clear", "uploaded", "file", "and", "allow", "write", "to", "it", ".", "Only", "for", "not", "too", "big", "files!!!", "Also", "can", "clear", "simple", "opened", "file", ".", "Examples", ":", "truncate_file", "(", "request", ".", "FILES", "[", "file", "...
python
train
24.8125
brocade/pynos
pynos/versions/ver_7/ver_7_1_0/yang/brocade_vswitch.py
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_7/ver_7_1_0/yang/brocade_vswitch.py#L860-L872
def get_vnetwork_portgroups_output_vnetwork_pgs_datacenter(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_vnetwork_portgroups = ET.Element("get_vnetwork_portgroups") config = get_vnetwork_portgroups output = ET.SubElement(get_vnetwork_portgr...
[ "def", "get_vnetwork_portgroups_output_vnetwork_pgs_datacenter", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "get_vnetwork_portgroups", "=", "ET", ".", "Element", "(", "\"get_vnetwork_portgroups\"", ")...
Auto Generated Code
[ "Auto", "Generated", "Code" ]
python
train
45.307692
rflamary/POT
ot/bregman.py
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/bregman.py#L1085-L1192
def convolutional_barycenter2d(A, reg, weights=None, numItermax=10000, stopThr=1e-9, stabThr=1e-30, verbose=False, log=False): """Compute the entropic regularized wasserstein barycenter of distributions A where A is a collection of 2D images. The function solves the following optimization problem: .....
[ "def", "convolutional_barycenter2d", "(", "A", ",", "reg", ",", "weights", "=", "None", ",", "numItermax", "=", "10000", ",", "stopThr", "=", "1e-9", ",", "stabThr", "=", "1e-30", ",", "verbose", "=", "False", ",", "log", "=", "False", ")", ":", "if", ...
Compute the entropic regularized wasserstein barycenter of distributions A where A is a collection of 2D images. The function solves the following optimization problem: .. math:: \mathbf{a} = arg\min_\mathbf{a} \sum_i W_{reg}(\mathbf{a},\mathbf{a}_i) where : - :math:`W_{reg}(\cdot,\cdot)...
[ "Compute", "the", "entropic", "regularized", "wasserstein", "barycenter", "of", "distributions", "A", "where", "A", "is", "a", "collection", "of", "2D", "images", "." ]
python
train
29.342593
banesullivan/gendocs
gendocs/generator.py
https://github.com/banesullivan/gendocs/blob/4ff6277370143ba698701beccc05d5eace43b632/gendocs/generator.py#L321-L401
def _MakePackagePages(self, package, showprivate=False, nested=False, showinh=False): """An internal helper to generate all of the pages for a given package Args: package (module): The top-level package to document showprivate (bool): A flag for whether or not to display private...
[ "def", "_MakePackagePages", "(", "self", ",", "package", ",", "showprivate", "=", "False", ",", "nested", "=", "False", ",", "showinh", "=", "False", ")", ":", "def", "checkNoNested", "(", "mod", ")", ":", "try", ":", "all", "=", "mod", ".", "__all__",...
An internal helper to generate all of the pages for a given package Args: package (module): The top-level package to document showprivate (bool): A flag for whether or not to display private members nested (bool): Foor internal use ONLY Returns: str: The...
[ "An", "internal", "helper", "to", "generate", "all", "of", "the", "pages", "for", "a", "given", "package" ]
python
train
36.592593
rueckstiess/mtools
mtools/util/grouping.py
https://github.com/rueckstiess/mtools/blob/a6a22910c3569c0c8a3908660ca218a4557e4249/mtools/util/grouping.py#L23-L50
def add(self, item, group_by=None): """General purpose class to group items by certain criteria.""" key = None if not group_by: group_by = self.group_by if group_by: # if group_by is a function, use it with item as argument if hasattr(group_by, '__ca...
[ "def", "add", "(", "self", ",", "item", ",", "group_by", "=", "None", ")", ":", "key", "=", "None", "if", "not", "group_by", ":", "group_by", "=", "self", ".", "group_by", "if", "group_by", ":", "# if group_by is a function, use it with item as argument", "if"...
General purpose class to group items by certain criteria.
[ "General", "purpose", "class", "to", "group", "items", "by", "certain", "criteria", "." ]
python
train
36.357143
qubole/qds-sdk-py
qds_sdk/template.py
https://github.com/qubole/qds-sdk-py/blob/77210fb64e5a7d567aedeea3b742a1d872fd0e5e/qds_sdk/template.py#L175-L186
def editTemplate(id, data): """ Edit an existing template. Args: `id`: ID of the template to edit `data`: json data to be updated Returns: Dictionary containing the updated details of the template. """ conn = Qubole.agent() r...
[ "def", "editTemplate", "(", "id", ",", "data", ")", ":", "conn", "=", "Qubole", ".", "agent", "(", ")", "return", "conn", ".", "put", "(", "Template", ".", "element_path", "(", "id", ")", ",", "data", ")" ]
Edit an existing template. Args: `id`: ID of the template to edit `data`: json data to be updated Returns: Dictionary containing the updated details of the template.
[ "Edit", "an", "existing", "template", "." ]
python
train
29.666667
wright-group/WrightTools
WrightTools/artists/_base.py
https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/artists/_base.py#L229-L262
def contour(self, *args, **kwargs): """Plot contours. If a 3D or higher Data object is passed, a lower dimensional channel can be plotted, provided the ``squeeze`` of the channel has ``ndim==2`` and the first two axes do not span dimensions other than those spanned by that chann...
[ "def", "contour", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "args", ",", "kwargs", "=", "self", ".", "_parse_plot_args", "(", "*", "args", ",", "*", "*", "kwargs", ",", "plot_type", "=", "\"contour\"", ")", "return", "super", ...
Plot contours. If a 3D or higher Data object is passed, a lower dimensional channel can be plotted, provided the ``squeeze`` of the channel has ``ndim==2`` and the first two axes do not span dimensions other than those spanned by that channel. Parameters ---------- ...
[ "Plot", "contours", "." ]
python
train
39.852941
fhamborg/news-please
newsplease/__main__.py
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/__main__.py#L328-L359
def get_abs_file_path(self, rel_file_path, quit_on_error=None, check_relative_to_path=True): """ Returns the absolute file path of the given [relative] file path to either this script or to the config file. May throw a RuntimeError if quit_on_error is True. ...
[ "def", "get_abs_file_path", "(", "self", ",", "rel_file_path", ",", "quit_on_error", "=", "None", ",", "check_relative_to_path", "=", "True", ")", ":", "if", "self", ".", "cfg_file_path", "is", "not", "None", "and", "check_relative_to_path", "and", "not", "self"...
Returns the absolute file path of the given [relative] file path to either this script or to the config file. May throw a RuntimeError if quit_on_error is True. :param str rel_file_path: relative file path :param bool quit_on_error: determines if the script may throw an ...
[ "Returns", "the", "absolute", "file", "path", "of", "the", "given", "[", "relative", "]", "file", "path", "to", "either", "this", "script", "or", "to", "the", "config", "file", "." ]
python
train
42.125
databio/pypiper
pypiper/manager.py
https://github.com/databio/pypiper/blob/00e6c2b94033c4187d47ff14c5580bbfc2ff097f/pypiper/manager.py#L1009-L1039
def _wait_for_lock(self, lock_file): """ Just sleep until the lock_file does not exist or a lock_file-related dynamic recovery flag is spotted :param str lock_file: Lock file to wait upon. """ sleeptime = .5 first_message_flag = False dot_count = 0 recove...
[ "def", "_wait_for_lock", "(", "self", ",", "lock_file", ")", ":", "sleeptime", "=", ".5", "first_message_flag", "=", "False", "dot_count", "=", "0", "recover_file", "=", "self", ".", "_recoverfile_from_lockfile", "(", "lock_file", ")", "while", "os", ".", "pat...
Just sleep until the lock_file does not exist or a lock_file-related dynamic recovery flag is spotted :param str lock_file: Lock file to wait upon.
[ "Just", "sleep", "until", "the", "lock_file", "does", "not", "exist", "or", "a", "lock_file", "-", "related", "dynamic", "recovery", "flag", "is", "spotted" ]
python
train
41.451613
itamarst/eliot
eliot/tai64n.py
https://github.com/itamarst/eliot/blob/c03c96520c5492fadfc438b4b0f6336e2785ba2d/eliot/tai64n.py#L33-L47
def decode(tai64n): """ Convert TAI64N string to seconds since epoch. Note that dates before 2013 may not decode accurately due to leap second issues. If you need correct decoding for earlier dates you can try the tai64n package available from PyPI (U{https://pypi.python.org/pypi/tai64n}). @pa...
[ "def", "decode", "(", "tai64n", ")", ":", "seconds", ",", "nanoseconds", "=", "struct", ".", "unpack", "(", "_STRUCTURE", ",", "a2b_hex", "(", "tai64n", "[", "1", ":", "]", ")", ")", "seconds", "-=", "_OFFSET", "return", "seconds", "+", "(", "nanosecon...
Convert TAI64N string to seconds since epoch. Note that dates before 2013 may not decode accurately due to leap second issues. If you need correct decoding for earlier dates you can try the tai64n package available from PyPI (U{https://pypi.python.org/pypi/tai64n}). @param tai64n: TAI64N-encoded time,...
[ "Convert", "TAI64N", "string", "to", "seconds", "since", "epoch", "." ]
python
train
37.6
ldomic/lintools
lintools/molecule.py
https://github.com/ldomic/lintools/blob/d825a4a7b35f3f857d3b81b46c9aee72b0ec697a/lintools/molecule.py#L221-L277
def make_new_projection_values(self,width=160): """Run do_step function until the diagramms have diverged from each other. Also determines how big the figure is going to be by calculating the borders from new residue coordinates. These are then added some buffer space. """ #Make...
[ "def", "make_new_projection_values", "(", "self", ",", "width", "=", "160", ")", ":", "#Make gap between residues bigger if plots have a lot of rings - each ring after the 4th", "#give extra 12.5px space", "start", "=", "timer", "(", ")", "if", "self", ".", "topology_data", ...
Run do_step function until the diagramms have diverged from each other. Also determines how big the figure is going to be by calculating the borders from new residue coordinates. These are then added some buffer space.
[ "Run", "do_step", "function", "until", "the", "diagramms", "have", "diverged", "from", "each", "other", ".", "Also", "determines", "how", "big", "the", "figure", "is", "going", "to", "be", "by", "calculating", "the", "borders", "from", "new", "residue", "coo...
python
train
51.736842
has2k1/plydata
plydata/dataframe/two_table.py
https://github.com/has2k1/plydata/blob/d8ca85ff70eee621e96f7c74034e90fec16e8b61/plydata/dataframe/two_table.py#L50-L59
def _join(verb): """ Join helper """ data = pd.merge(verb.x, verb.y, **verb.kwargs) # Preserve x groups if isinstance(verb.x, GroupedDataFrame): data.plydata_groups = list(verb.x.plydata_groups) return data
[ "def", "_join", "(", "verb", ")", ":", "data", "=", "pd", ".", "merge", "(", "verb", ".", "x", ",", "verb", ".", "y", ",", "*", "*", "verb", ".", "kwargs", ")", "# Preserve x groups", "if", "isinstance", "(", "verb", ".", "x", ",", "GroupedDataFram...
Join helper
[ "Join", "helper" ]
python
train
23.4
softlayer/softlayer-python
SoftLayer/CLI/securitygroup/detail.py
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/securitygroup/detail.py#L14-L73
def cli(env, identifier): """Get details about a security group.""" mgr = SoftLayer.NetworkManager(env.client) secgroup = mgr.get_securitygroup(identifier) table = formatting.KeyValueTable(['name', 'value']) table.align['name'] = 'r' table.align['value'] = 'l' table.add_row(['id', secgro...
[ "def", "cli", "(", "env", ",", "identifier", ")", ":", "mgr", "=", "SoftLayer", ".", "NetworkManager", "(", "env", ".", "client", ")", "secgroup", "=", "mgr", ".", "get_securitygroup", "(", "identifier", ")", "table", "=", "formatting", ".", "KeyValueTable...
Get details about a security group.
[ "Get", "details", "about", "a", "security", "group", "." ]
python
train
39.683333
AltSchool/dynamic-rest
dynamic_rest/serializers.py
https://github.com/AltSchool/dynamic-rest/blob/5b0338c3dd8bc638d60c3bb92645857c5b89c920/dynamic_rest/serializers.py#L330-L344
def get_name(cls): """Get the serializer name. The name can be defined on the Meta class or will be generated automatically from the model name. """ if not hasattr(cls.Meta, 'name'): class_name = getattr(cls.get_model(), '__name__', None) setattr( ...
[ "def", "get_name", "(", "cls", ")", ":", "if", "not", "hasattr", "(", "cls", ".", "Meta", ",", "'name'", ")", ":", "class_name", "=", "getattr", "(", "cls", ".", "get_model", "(", ")", ",", "'__name__'", ",", "None", ")", "setattr", "(", "cls", "."...
Get the serializer name. The name can be defined on the Meta class or will be generated automatically from the model name.
[ "Get", "the", "serializer", "name", "." ]
python
train
31.066667
ajslater/picopt
picopt/walk.py
https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/walk.py#L150-L184
def _walk_all_files(): """ Optimize the files from the arugments list in two batches. One for absolute paths which are probably outside the current working directory tree and one for relative files. """ # Init records record_dirs = set() result_set = set() for filename in Settings....
[ "def", "_walk_all_files", "(", ")", ":", "# Init records", "record_dirs", "=", "set", "(", ")", "result_set", "=", "set", "(", ")", "for", "filename", "in", "Settings", ".", "paths", ":", "# Record dirs to put timestamps in later", "filename_full", "=", "os", "....
Optimize the files from the arugments list in two batches. One for absolute paths which are probably outside the current working directory tree and one for relative files.
[ "Optimize", "the", "files", "from", "the", "arugments", "list", "in", "two", "batches", "." ]
python
train
31.771429
pymc-devs/pymc
pymc/distributions.py
https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L1323-L1330
def rgev(xi, mu=0, sigma=1, size=None): """ Random generalized extreme value (GEV) variates. """ q = np.random.uniform(size=size) z = flib.gev_ppf(q, xi) return z * sigma + mu
[ "def", "rgev", "(", "xi", ",", "mu", "=", "0", ",", "sigma", "=", "1", ",", "size", "=", "None", ")", ":", "q", "=", "np", ".", "random", ".", "uniform", "(", "size", "=", "size", ")", "z", "=", "flib", ".", "gev_ppf", "(", "q", ",", "xi", ...
Random generalized extreme value (GEV) variates.
[ "Random", "generalized", "extreme", "value", "(", "GEV", ")", "variates", "." ]
python
train
24.125
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/visuals/collections/agg_fast_path_collection.py
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/collections/agg_fast_path_collection.py#L179-L219
def bake(self, P, key='curr', closed=False, itemsize=None): """ Given a path P, return the baked vertices as they should be copied in the collection if the path has already been appended. Example: -------- paths.append(P) P *= 2 paths['prev'][0] = bake(P...
[ "def", "bake", "(", "self", ",", "P", ",", "key", "=", "'curr'", ",", "closed", "=", "False", ",", "itemsize", "=", "None", ")", ":", "itemsize", "=", "itemsize", "or", "len", "(", "P", ")", "itemcount", "=", "len", "(", "P", ")", "/", "itemsize"...
Given a path P, return the baked vertices as they should be copied in the collection if the path has already been appended. Example: -------- paths.append(P) P *= 2 paths['prev'][0] = bake(P,'prev') paths['curr'][0] = bake(P,'curr') paths['next'][0] = ba...
[ "Given", "a", "path", "P", "return", "the", "baked", "vertices", "as", "they", "should", "be", "copied", "in", "the", "collection", "if", "the", "path", "has", "already", "been", "appended", "." ]
python
train
29
Scoppio/RagnarokEngine3
RagnarokEngine3/RE3.py
https://github.com/Scoppio/RagnarokEngine3/blob/4395d419ccd64fe9327c41f200b72ee0176ad896/RagnarokEngine3/RE3.py#L1906-L1922
def copy(self): """Create a copy of the animation.""" animation = AnimationList() animation.set_frame_rate(self.frame_rate) animation.__coords = self.__coords animation.__horizontal_flip = self.__horizontal_flip animation.__vertical_flip = self.__vertical_flip ani...
[ "def", "copy", "(", "self", ")", ":", "animation", "=", "AnimationList", "(", ")", "animation", ".", "set_frame_rate", "(", "self", ".", "frame_rate", ")", "animation", ".", "__coords", "=", "self", ".", "__coords", "animation", ".", "__horizontal_flip", "="...
Create a copy of the animation.
[ "Create", "a", "copy", "of", "the", "animation", "." ]
python
train
39.764706
googleapis/google-cloud-python
monitoring/google/cloud/monitoring_v3/gapic/uptime_check_service_client.py
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/monitoring/google/cloud/monitoring_v3/gapic/uptime_check_service_client.py#L398-L479
def create_uptime_check_config( self, parent, uptime_check_config, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates a new uptime check configuration. Example: ...
[ "def", "create_uptime_check_config", "(", "self", ",", "parent", ",", "uptime_check_config", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "...
Creates a new uptime check configuration. Example: >>> from google.cloud import monitoring_v3 >>> >>> client = monitoring_v3.UptimeCheckServiceClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> # TODO: Initializ...
[ "Creates", "a", "new", "uptime", "check", "configuration", "." ]
python
train
42.134146
amol-/depot
depot/manager.py
https://github.com/amol-/depot/blob/82104d2ae54f8ef55f05fb5a3f148cdc9f928959/depot/manager.py#L84-L103
def configure(cls, name, config, prefix='depot.'): """Configures an application depot. This configures the application wide depot from a settings dictionary. The settings dictionary is usually loaded from an application configuration file where all the depot options are specified with a...
[ "def", "configure", "(", "cls", ",", "name", ",", "config", ",", "prefix", "=", "'depot.'", ")", ":", "if", "name", "in", "cls", ".", "_depots", ":", "raise", "RuntimeError", "(", "'Depot %s has already been configured'", "%", "(", "name", ",", ")", ")", ...
Configures an application depot. This configures the application wide depot from a settings dictionary. The settings dictionary is usually loaded from an application configuration file where all the depot options are specified with a given ``prefix``. The default ``prefix`` is *depot.*...
[ "Configures", "an", "application", "depot", "." ]
python
train
41.7
chimera0/accel-brain-code
Reinforcement-Learning/pyqlearning/qlearning/boltzmann_q_learning.py
https://github.com/chimera0/accel-brain-code/blob/03661f6f544bed656269fcd4b3c23c9061629daa/Reinforcement-Learning/pyqlearning/qlearning/boltzmann_q_learning.py#L43-L54
def set_time_rate(self, value): ''' setter Time rate. ''' if isinstance(value, float) is False: raise TypeError("The type of __time_rate must be float.") if value <= 0.0: raise ValueError("The value of __time_rate must be greater than 0.0") ...
[ "def", "set_time_rate", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "float", ")", "is", "False", ":", "raise", "TypeError", "(", "\"The type of __time_rate must be float.\"", ")", "if", "value", "<=", "0.0", ":", "raise", "Val...
setter Time rate.
[ "setter", "Time", "rate", "." ]
python
train
28
artisanofcode/python-broadway
broadway/whitenoise.py
https://github.com/artisanofcode/python-broadway/blob/a051ca5a922ecb38a541df59e8740e2a047d9a4a/broadway/whitenoise.py#L38-L59
def init_app(application): """ Initialise an application Set up whitenoise to handle static files. """ config = {k: v for k, v in application.config.items() if k in SCHEMA} kwargs = {'autorefresh': application.debug} kwargs.update((k[11:].lower(), v) for k, v in config.items()) insta...
[ "def", "init_app", "(", "application", ")", ":", "config", "=", "{", "k", ":", "v", "for", "k", ",", "v", "in", "application", ".", "config", ".", "items", "(", ")", "if", "k", "in", "SCHEMA", "}", "kwargs", "=", "{", "'autorefresh'", ":", "applica...
Initialise an application Set up whitenoise to handle static files.
[ "Initialise", "an", "application" ]
python
train
27.818182
xolox/python-coloredlogs
coloredlogs/converter/__init__.py
https://github.com/xolox/python-coloredlogs/blob/1cbf0c6bbee400c6ddbc43008143809934ec3e79/coloredlogs/converter/__init__.py#L303-L327
def parse_hex_color(value): """ Convert a CSS color in hexadecimal notation into its R, G, B components. :param value: A CSS color in hexadecimal notation (a string like '#000000'). :return: A tuple with three integers (with values between 0 and 255) corresponding to the R, G and B compone...
[ "def", "parse_hex_color", "(", "value", ")", ":", "if", "value", ".", "startswith", "(", "'#'", ")", ":", "value", "=", "value", "[", "1", ":", "]", "if", "len", "(", "value", ")", "==", "3", ":", "return", "(", "int", "(", "value", "[", "0", "...
Convert a CSS color in hexadecimal notation into its R, G, B components. :param value: A CSS color in hexadecimal notation (a string like '#000000'). :return: A tuple with three integers (with values between 0 and 255) corresponding to the R, G and B components of the color. :raises: :exc:`~ex...
[ "Convert", "a", "CSS", "color", "in", "hexadecimal", "notation", "into", "its", "R", "G", "B", "components", "." ]
python
train
31.88
tanghaibao/jcvi
jcvi/utils/iter.py
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/utils/iter.py#L22-L30
def consume(iterator, n): "Advance the iterator n-steps ahead. If n is none, consume entirely." # Use functions that consume iterators at C speed. if n is None: # feed the entire iterator into a zero-length deque collections.deque(iterator, maxlen=0) else: # advance to the empty ...
[ "def", "consume", "(", "iterator", ",", "n", ")", ":", "# Use functions that consume iterators at C speed.", "if", "n", "is", "None", ":", "# feed the entire iterator into a zero-length deque", "collections", ".", "deque", "(", "iterator", ",", "maxlen", "=", "0", ")"...
Advance the iterator n-steps ahead. If n is none, consume entirely.
[ "Advance", "the", "iterator", "n", "-", "steps", "ahead", ".", "If", "n", "is", "none", "consume", "entirely", "." ]
python
train
42.555556
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/schema.py
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/schema.py#L293-L323
def mssql_get_pk_index_name(engine: Engine, tablename: str, schemaname: str = MSSQL_DEFAULT_SCHEMA) -> str: """ For Microsoft SQL Server specifically: fetch the name of the PK index for the specified table (in the specified schema), or ``''`` if none i...
[ "def", "mssql_get_pk_index_name", "(", "engine", ":", "Engine", ",", "tablename", ":", "str", ",", "schemaname", ":", "str", "=", "MSSQL_DEFAULT_SCHEMA", ")", "->", "str", ":", "# http://docs.sqlalchemy.org/en/latest/core/connections.html#sqlalchemy.engine.Connection.execute ...
For Microsoft SQL Server specifically: fetch the name of the PK index for the specified table (in the specified schema), or ``''`` if none is found.
[ "For", "Microsoft", "SQL", "Server", "specifically", ":", "fetch", "the", "name", "of", "the", "PK", "index", "for", "the", "specified", "table", "(", "in", "the", "specified", "schema", ")", "or", "if", "none", "is", "found", "." ]
python
train
42.322581
huggingface/pytorch-pretrained-BERT
pytorch_pretrained_bert/tokenization.py
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/pytorch_pretrained_bert/tokenization.py#L137-L150
def save_vocabulary(self, vocab_path): """Save the tokenizer vocabulary to a directory or file.""" index = 0 if os.path.isdir(vocab_path): vocab_file = os.path.join(vocab_path, VOCAB_NAME) with open(vocab_file, "w", encoding="utf-8") as writer: for token, token_in...
[ "def", "save_vocabulary", "(", "self", ",", "vocab_path", ")", ":", "index", "=", "0", "if", "os", ".", "path", ".", "isdir", "(", "vocab_path", ")", ":", "vocab_file", "=", "os", ".", "path", ".", "join", "(", "vocab_path", ",", "VOCAB_NAME", ")", "...
Save the tokenizer vocabulary to a directory or file.
[ "Save", "the", "tokenizer", "vocabulary", "to", "a", "directory", "or", "file", "." ]
python
train
53.714286