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
LudovicRousseau/pyscard
smartcard/ReaderMonitoring.py
https://github.com/LudovicRousseau/pyscard/blob/62e675028086c75656444cc21d563d9f08ebf8e7/smartcard/ReaderMonitoring.py#L121-L130
def deleteObserver(self, observer): """Remove an observer.""" Observable.deleteObserver(self, observer) # If self.startOnDemand is True, the reader monitoring # thread is stopped when there are no more observers. if self.startOnDemand: if 0 == self.countObservers(): ...
[ "def", "deleteObserver", "(", "self", ",", "observer", ")", ":", "Observable", ".", "deleteObserver", "(", "self", ",", "observer", ")", "# If self.startOnDemand is True, the reader monitoring", "# thread is stopped when there are no more observers.", "if", "self", ".", "st...
Remove an observer.
[ "Remove", "an", "observer", "." ]
python
train
41.7
openego/eDisGo
edisgo/grid/network.py
https://github.com/openego/eDisGo/blob/e6245bdaf236f9c49dbda5a18c1c458290f41e2b/edisgo/grid/network.py#L2892-L2938
def s_res(self, components=None): """ Get resulting apparent power in kVA at line(s) and transformer(s). The apparent power at a line (or transformer) is determined from the maximum values of active power P and reactive power Q. .. math:: S = max(\sqrt{p_0^2 + q_0^...
[ "def", "s_res", "(", "self", ",", "components", "=", "None", ")", ":", "if", "components", "is", "not", "None", ":", "labels_included", "=", "[", "]", "labels_not_included", "=", "[", "]", "labels", "=", "[", "repr", "(", "l", ")", "for", "l", "in", ...
Get resulting apparent power in kVA at line(s) and transformer(s). The apparent power at a line (or transformer) is determined from the maximum values of active power P and reactive power Q. .. math:: S = max(\sqrt{p_0^2 + q_0^2}, \sqrt{p_1^2 + q_1^2}) Parameters ...
[ "Get", "resulting", "apparent", "power", "in", "kVA", "at", "line", "(", "s", ")", "and", "transformer", "(", "s", ")", "." ]
python
train
34.957447
bcbio/bcbio-nextgen
bcbio/ngsalign/alignprep.py
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/ngsalign/alignprep.py#L319-L331
def _ready_gzip_fastq(in_files, data, require_bgzip=False): """Check if we have gzipped fastq and don't need format conversion or splitting. Avoid forcing bgzip if we don't need indexed files. """ all_gzipped = all([not x or x.endswith(".gz") for x in in_files]) if require_bgzip and all_gzipped: ...
[ "def", "_ready_gzip_fastq", "(", "in_files", ",", "data", ",", "require_bgzip", "=", "False", ")", ":", "all_gzipped", "=", "all", "(", "[", "not", "x", "or", "x", ".", "endswith", "(", "\".gz\"", ")", "for", "x", "in", "in_files", "]", ")", "if", "r...
Check if we have gzipped fastq and don't need format conversion or splitting. Avoid forcing bgzip if we don't need indexed files.
[ "Check", "if", "we", "have", "gzipped", "fastq", "and", "don", "t", "need", "format", "conversion", "or", "splitting", "." ]
python
train
57.538462
fastai/fastai
fastai/basic_data.py
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/basic_data.py#L239-L270
def sanity_check(self): "Check the underlying data in the training set can be properly loaded." final_message = "You can deactivate this warning by passing `no_check=True`." if not hasattr(self.train_ds, 'items') or len(self.train_ds.items) == 0 or not hasattr(self.train_dl, 'batch_sampler'): re...
[ "def", "sanity_check", "(", "self", ")", ":", "final_message", "=", "\"You can deactivate this warning by passing `no_check=True`.\"", "if", "not", "hasattr", "(", "self", ".", "train_ds", ",", "'items'", ")", "or", "len", "(", "self", ".", "train_ds", ".", "items...
Check the underlying data in the training set can be properly loaded.
[ "Check", "the", "underlying", "data", "in", "the", "training", "set", "can", "be", "properly", "loaded", "." ]
python
train
52.1875
annoviko/pyclustering
pyclustering/cluster/silhouette.py
https://github.com/annoviko/pyclustering/blob/98aa0dd89fd36f701668fb1eb29c8fb5662bf7d0/pyclustering/cluster/silhouette.py#L471-L482
def __calculate_clusters(self, k): """! @brief Performs cluster analysis using specified K value. @param[in] k (uint): Amount of clusters that should be allocated. @return (array_like) Allocated clusters. """ initial_values = kmeans_plusplus_initializer(self._...
[ "def", "__calculate_clusters", "(", "self", ",", "k", ")", ":", "initial_values", "=", "kmeans_plusplus_initializer", "(", "self", ".", "__data", ",", "k", ")", ".", "initialize", "(", "return_index", "=", "self", ".", "__return_index", ")", "algorithm_type", ...
! @brief Performs cluster analysis using specified K value. @param[in] k (uint): Amount of clusters that should be allocated. @return (array_like) Allocated clusters.
[ "!" ]
python
valid
41.833333
hyperledger/sawtooth-core
validator/sawtooth_validator/gossip/gossip.py
https://github.com/hyperledger/sawtooth-core/blob/8cf473bc2207e51f02bd182d825158a57d72b098/validator/sawtooth_validator/gossip/gossip.py#L221-L247
def register_peer(self, connection_id, endpoint): """Registers a connected connection_id. Args: connection_id (str): A unique identifier which identifies an connection on the network server socket. endpoint (str): The publically reachable endpoint of the new ...
[ "def", "register_peer", "(", "self", ",", "connection_id", ",", "endpoint", ")", ":", "with", "self", ".", "_lock", ":", "if", "len", "(", "self", ".", "_peers", ")", "<", "self", ".", "_maximum_peer_connectivity", ":", "self", ".", "_peers", "[", "conne...
Registers a connected connection_id. Args: connection_id (str): A unique identifier which identifies an connection on the network server socket. endpoint (str): The publically reachable endpoint of the new peer
[ "Registers", "a", "connected", "connection_id", "." ]
python
train
46.111111
amol-/depot
depot/manager.py
https://github.com/amol-/depot/blob/82104d2ae54f8ef55f05fb5a3f148cdc9f928959/depot/manager.py#L163-L173
def _clear(cls): """This is only for testing pourposes, resets the DepotManager status This is to simplify writing test fixtures, resets the DepotManager global status and removes the informations related to the current configured depots and middleware. """ cls._default_...
[ "def", "_clear", "(", "cls", ")", ":", "cls", ".", "_default_depot", "=", "None", "cls", ".", "_depots", "=", "{", "}", "cls", ".", "_middleware", "=", "None", "cls", ".", "_aliases", "=", "{", "}" ]
This is only for testing pourposes, resets the DepotManager status This is to simplify writing test fixtures, resets the DepotManager global status and removes the informations related to the current configured depots and middleware.
[ "This", "is", "only", "for", "testing", "pourposes", "resets", "the", "DepotManager", "status" ]
python
train
36.727273
hydpy-dev/hydpy
hydpy/exe/servertools.py
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/exe/servertools.py#L1147-L1159
def start_server(socket, projectname, xmlfilename: str) -> None: """Start the *HydPy* server using the given socket. The folder with the given `projectname` must be available within the current working directory. The XML configuration file must be placed within the project folder unless `xmlfilename` ...
[ "def", "start_server", "(", "socket", ",", "projectname", ",", "xmlfilename", ":", "str", ")", "->", "None", ":", "state", ".", "initialise", "(", "projectname", ",", "xmlfilename", ")", "server", "=", "http", ".", "server", ".", "HTTPServer", "(", "(", ...
Start the *HydPy* server using the given socket. The folder with the given `projectname` must be available within the current working directory. The XML configuration file must be placed within the project folder unless `xmlfilename` is an absolute file path. The XML configuration file must be valid c...
[ "Start", "the", "*", "HydPy", "*", "server", "using", "the", "given", "socket", "." ]
python
train
50.461538
i3visio/entify
entify/lib/processing.py
https://github.com/i3visio/entify/blob/51c5b89cebee3a39d44d0918e2798739361f337c/entify/lib/processing.py#L126-L148
def scanResource(uri = None, listRegexp = None, verbosity=1, logFolder= "./logs"): ''' [Optionally] recursive method to scan the files in a given folder. :param uri: the URI to be scanned. :param listRegexp: listRegexp is an array of <RegexpObject>. :return: a dictionary where the key is the name of the fil...
[ "def", "scanResource", "(", "uri", "=", "None", ",", "listRegexp", "=", "None", ",", "verbosity", "=", "1", ",", "logFolder", "=", "\"./logs\"", ")", ":", "i3visiotools", ".", "logger", ".", "setupLogger", "(", "loggerName", "=", "\"entify\"", ",", "verbos...
[Optionally] recursive method to scan the files in a given folder. :param uri: the URI to be scanned. :param listRegexp: listRegexp is an array of <RegexpObject>. :return: a dictionary where the key is the name of the file.
[ "[", "Optionally", "]", "recursive", "method", "to", "scan", "the", "files", "in", "a", "given", "folder", "." ]
python
train
32.913043
klen/zeta-library
zetalibrary/scss/__init__.py
https://github.com/klen/zeta-library/blob/b76f89000f467e10ddcc94aded3f6c6bf4a0e5bd/zetalibrary/scss/__init__.py#L1396-L1404
def _get_variables(self, rule, p_selectors, p_parents, p_children, scope, media, c_lineno, c_property, c_codestr): """ Implements @variables and @vars """ _rule = list(rule) _rule[CODESTR] = c_codestr _rule[PROPERTIES] = rule[CONTEXT] self.manage_children( ...
[ "def", "_get_variables", "(", "self", ",", "rule", ",", "p_selectors", ",", "p_parents", ",", "p_children", ",", "scope", ",", "media", ",", "c_lineno", ",", "c_property", ",", "c_codestr", ")", ":", "_rule", "=", "list", "(", "rule", ")", "_rule", "[", ...
Implements @variables and @vars
[ "Implements" ]
python
train
41.444444
djgagne/hagelslag
hagelslag/processing/EnhancedWatershedSegmenter.py
https://github.com/djgagne/hagelslag/blob/6fb6c3df90bf4867e13a97d3460b14471d107df1/hagelslag/processing/EnhancedWatershedSegmenter.py#L168-L221
def set_maximum(self, q_data, marked, center, bin_lower, foothills): """ Grow a region at a certain bin level and check if the region has reached the maximum size. Args: q_data: Quantized data array marked: Array marking points that are objects center: Coordi...
[ "def", "set_maximum", "(", "self", ",", "q_data", ",", "marked", ",", "center", ",", "bin_lower", ",", "foothills", ")", ":", "as_bin", "=", "[", "]", "# pixels to be included in peak", "as_glob", "=", "[", "]", "# pixels to be globbed up as part of foothills", "m...
Grow a region at a certain bin level and check if the region has reached the maximum size. Args: q_data: Quantized data array marked: Array marking points that are objects center: Coordinates of the center pixel of the region being grown bin_lower: Intensity leve...
[ "Grow", "a", "region", "at", "a", "certain", "bin", "level", "and", "check", "if", "the", "region", "has", "reached", "the", "maximum", "size", "." ]
python
train
49.62963
ergoithz/browsepy
browsepy/compat.py
https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/compat.py#L100-L110
def getdebug(environ=os.environ, true_values=TRUE_VALUES): ''' Get if app is expected to be ran in debug mode looking at environment variables. :param environ: environment dict-like object :type environ: collections.abc.Mapping :returns: True if debug contains a true-like string, False otherwis...
[ "def", "getdebug", "(", "environ", "=", "os", ".", "environ", ",", "true_values", "=", "TRUE_VALUES", ")", ":", "return", "environ", ".", "get", "(", "'DEBUG'", ",", "''", ")", ".", "lower", "(", ")", "in", "true_values" ]
Get if app is expected to be ran in debug mode looking at environment variables. :param environ: environment dict-like object :type environ: collections.abc.Mapping :returns: True if debug contains a true-like string, False otherwise :rtype: bool
[ "Get", "if", "app", "is", "expected", "to", "be", "ran", "in", "debug", "mode", "looking", "at", "environment", "variables", "." ]
python
train
35.909091
limpyd/redis-limpyd
limpyd/fields.py
https://github.com/limpyd/redis-limpyd/blob/3c745dde1390a0bd09690b77a089dcc08c6c7e43/limpyd/fields.py#L330-L341
def post_command(self, sender, name, result, args, kwargs): """ Call after we got the result of a redis command. By default, let the instance manage the post_modify signal """ return self._instance.post_command( sender=self, name=name, ...
[ "def", "post_command", "(", "self", ",", "sender", ",", "name", ",", "result", ",", "args", ",", "kwargs", ")", ":", "return", "self", ".", "_instance", ".", "post_command", "(", "sender", "=", "self", ",", "name", "=", "name", ",", "result", "=", "r...
Call after we got the result of a redis command. By default, let the instance manage the post_modify signal
[ "Call", "after", "we", "got", "the", "result", "of", "a", "redis", "command", ".", "By", "default", "let", "the", "instance", "manage", "the", "post_modify", "signal" ]
python
train
34.666667
chinapnr/fishbase
fishbase/fish_common.py
https://github.com/chinapnr/fishbase/blob/23c5147a6bc0d8ed36409e55352ffb2c5b0edc82/fishbase/fish_common.py#L1098-L1149
def yaml_conf_as_dict(file_path, encoding=None): """ 读入 yaml 配置文件,返回根据配置文件内容生成的字典类型变量 :param: * file_path: (string) 需要读入的 yaml 配置文件长文件名 * encoding: (string) 文件编码 * msg: (string) 读取配置信息 :return: * flag: (bool) 读取配置文件是否正确,正确返回 True,错误返回 False * d: (dict) 如果读取配置文件正...
[ "def", "yaml_conf_as_dict", "(", "file_path", ",", "encoding", "=", "None", ")", ":", "if", "not", "pathlib", ".", "Path", "(", "file_path", ")", ".", "is_file", "(", ")", ":", "return", "False", ",", "{", "}", ",", "'File not exist'", "try", ":", "if"...
读入 yaml 配置文件,返回根据配置文件内容生成的字典类型变量 :param: * file_path: (string) 需要读入的 yaml 配置文件长文件名 * encoding: (string) 文件编码 * msg: (string) 读取配置信息 :return: * flag: (bool) 读取配置文件是否正确,正确返回 True,错误返回 False * d: (dict) 如果读取配置文件正确返回的包含配置文件内容的字典,字典内容顺序与配置文件顺序保持一致 举例如下:: print(...
[ "读入", "yaml", "配置文件,返回根据配置文件内容生成的字典类型变量" ]
python
train
28.807692
google/python-gflags
gflags/exceptions.py
https://github.com/google/python-gflags/blob/4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6/gflags/exceptions.py#L71-L98
def from_flag(cls, flagname, flag_values, other_flag_values=None): """Create a DuplicateFlagError by providing flag name and values. Args: flagname: Name of the flag being redefined. flag_values: FlagValues object containing the first definition of flagname. other_flag_values: If th...
[ "def", "from_flag", "(", "cls", ",", "flagname", ",", "flag_values", ",", "other_flag_values", "=", "None", ")", ":", "first_module", "=", "flag_values", ".", "FindModuleDefiningFlag", "(", "flagname", ",", "default", "=", "'<unknown>'", ")", "if", "other_flag_v...
Create a DuplicateFlagError by providing flag name and values. Args: flagname: Name of the flag being redefined. flag_values: FlagValues object containing the first definition of flagname. other_flag_values: If this argument is not None, it should be the FlagValues object wher...
[ "Create", "a", "DuplicateFlagError", "by", "providing", "flag", "name", "and", "values", "." ]
python
train
44.357143
obskyr/puush.py
puush/puush.py
https://github.com/obskyr/puush.py/blob/a0e4fe424c43a7758d8aaf1b31659ab51266f6d1/puush/puush.py#L109-L151
def upload(self, f): """Upload a file to the Puush account. Parameters: * f: The file. Either a path to a file or a file-like object. """ if hasattr(f, 'read'): needs_closing = False else: f = open(f, 'rb') needs_closing = ...
[ "def", "upload", "(", "self", ",", "f", ")", ":", "if", "hasattr", "(", "f", ",", "'read'", ")", ":", "needs_closing", "=", "False", "else", ":", "f", "=", "open", "(", "f", ",", "'rb'", ")", "needs_closing", "=", "True", "# The Puush server can't hand...
Upload a file to the Puush account. Parameters: * f: The file. Either a path to a file or a file-like object.
[ "Upload", "a", "file", "to", "the", "Puush", "account", ".", "Parameters", ":", "*", "f", ":", "The", "file", ".", "Either", "a", "path", "to", "a", "file", "or", "a", "file", "-", "like", "object", "." ]
python
train
37.27907
vlukes/dicom2fem
dicom2fem/meshio.py
https://github.com/vlukes/dicom2fem/blob/3056c977ca7119e01984d3aa0c4448a1c6c2430f/dicom2fem/meshio.py#L977-L1008
def getnodes(fnods, up=None, verbose=False): """ Reads t.1.nodes, returns a list of nodes. Example: >>> self.getnodes("t.1.node", MyBar("nodes:")) [(0.0, 0.0, 0.0), (4.0, 0.0, 0.0), (0.0, 4.0, 0.0), (-4.0, 0.0, 0.0), (0.0, 0.0, 4.0), (0.0, -4.0, 0.0), (0.0, -0.0, -4.0),...
[ "def", "getnodes", "(", "fnods", ",", "up", "=", "None", ",", "verbose", "=", "False", ")", ":", "f", "=", "open", "(", "fnods", ")", "l", "=", "[", "int", "(", "x", ")", "for", "x", "in", "f", ".", "readline", "(", ")", ".", "split", "(", ...
Reads t.1.nodes, returns a list of nodes. Example: >>> self.getnodes("t.1.node", MyBar("nodes:")) [(0.0, 0.0, 0.0), (4.0, 0.0, 0.0), (0.0, 4.0, 0.0), (-4.0, 0.0, 0.0), (0.0, 0.0, 4.0), (0.0, -4.0, 0.0), (0.0, -0.0, -4.0), (-2.0, 0.0, -2.0), (-2.0, 2.0, 0.0), (0.0, 2.0, -2.0), (...
[ "Reads", "t", ".", "1", ".", "nodes", "returns", "a", "list", "of", "nodes", "." ]
python
train
33.53125
fabiobatalha/crossrefapi
crossref/restful.py
https://github.com/fabiobatalha/crossrefapi/blob/53f84ee0d8a8fc6ad9b2493f51c5151e66d2faf7/crossref/restful.py#L995-L1032
def doi_exists(self, doi): """ This method retrieve a boolean according to the existence of a crossref DOI number. It returns False if the API results a 404 status code. args: Crossref DOI id (String) return: Boolean Example 1: >>> from crossref.restful imp...
[ "def", "doi_exists", "(", "self", ",", "doi", ")", ":", "request_url", "=", "build_url_endpoint", "(", "'/'", ".", "join", "(", "[", "self", ".", "ENDPOINT", ",", "doi", "]", ")", ")", "request_params", "=", "{", "}", "result", "=", "self", ".", "do_...
This method retrieve a boolean according to the existence of a crossref DOI number. It returns False if the API results a 404 status code. args: Crossref DOI id (String) return: Boolean Example 1: >>> from crossref.restful import Works >>> works = Works() ...
[ "This", "method", "retrieve", "a", "boolean", "according", "to", "the", "existence", "of", "a", "crossref", "DOI", "number", ".", "It", "returns", "False", "if", "the", "API", "results", "a", "404", "status", "code", "." ]
python
train
27.210526
SmartTeleMax/iktomi
iktomi/unstable/utils/functools.py
https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/unstable/utils/functools.py#L6-L38
def return_locals(func): '''Modifies decorated function to return its locals''' @functools.wraps(func) def wrap(*args, **kwargs): frames = [] def tracer(frame, event, arg): # pragma: no cover # coverage does not work in this function because the tracer # is deactiva...
[ "def", "return_locals", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrap", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "frames", "=", "[", "]", "def", "tracer", "(", "frame", ",", "event", ",", "arg",...
Modifies decorated function to return its locals
[ "Modifies", "decorated", "function", "to", "return", "its", "locals" ]
python
train
33.636364
gebn/wood
wood/comparison.py
https://github.com/gebn/wood/blob/efc71879890dbd2f2d7a0b1a65ed22a0843139dd/wood/comparison.py#L191-L202
def print_hierarchy(self, level: int = 0, file: IO[str] = sys.stdout) \ -> None: """ Print this comparison and its children with indentation to represent nesting. :param level: The level of indentation to use. This is mostly for internal use, but you ca...
[ "def", "print_hierarchy", "(", "self", ",", "level", ":", "int", "=", "0", ",", "file", ":", "IO", "[", "str", "]", "=", "sys", ".", "stdout", ")", "->", "None", ":", "print", "(", "' '", "*", "self", ".", "_INDENT_SIZE", "*", "level", "+", "str"...
Print this comparison and its children with indentation to represent nesting. :param level: The level of indentation to use. This is mostly for internal use, but you can use it to inset the root comparison. :param file: The stream to print to. Default...
[ "Print", "this", "comparison", "and", "its", "children", "with", "indentation", "to", "represent", "nesting", "." ]
python
train
43
boriel/zxbasic
ast_/tree.py
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/ast_/tree.py#L101-L113
def inorder(self, funct, stopOn=None): """ Iterates in order, calling the function with the current node. If stopOn is set to True or False, it will stop on true or false. """ if stopOn is None: for i in self.children: i.inorder(funct) else: ...
[ "def", "inorder", "(", "self", ",", "funct", ",", "stopOn", "=", "None", ")", ":", "if", "stopOn", "is", "None", ":", "for", "i", "in", "self", ".", "children", ":", "i", ".", "inorder", "(", "funct", ")", "else", ":", "for", "i", "in", "self", ...
Iterates in order, calling the function with the current node. If stopOn is set to True or False, it will stop on true or false.
[ "Iterates", "in", "order", "calling", "the", "function", "with", "the", "current", "node", ".", "If", "stopOn", "is", "set", "to", "True", "or", "False", "it", "will", "stop", "on", "true", "or", "false", "." ]
python
train
34
kislyuk/ensure
ensure/main.py
https://github.com/kislyuk/ensure/blob/0a562a4b469ffbaf71c75dc4d394e94334c831f0/ensure/main.py#L198-L203
def equals(self, other): """ Ensures :attr:`subject` is equal to *other*. """ self._run(unittest_case.assertEqual, (self._subject, other)) return ChainInspector(self._subject)
[ "def", "equals", "(", "self", ",", "other", ")", ":", "self", ".", "_run", "(", "unittest_case", ".", "assertEqual", ",", "(", "self", ".", "_subject", ",", "other", ")", ")", "return", "ChainInspector", "(", "self", ".", "_subject", ")" ]
Ensures :attr:`subject` is equal to *other*.
[ "Ensures", ":", "attr", ":", "subject", "is", "equal", "to", "*", "other", "*", "." ]
python
train
35
observermedia/django-wordpress-rest
wordpress/loading.py
https://github.com/observermedia/django-wordpress-rest/blob/f0d96891d8ac5a69c8ba90e044876e756fad1bfe/wordpress/loading.py#L736-L762
def process_post_tag(self, bulk_mode, api_tag): """ Create or update a Tag related to a post. :param bulk_mode: If True, minimize db operations by bulk creating post objects :param api_tag: the API data for the Tag :return: the Tag object """ tag = None ...
[ "def", "process_post_tag", "(", "self", ",", "bulk_mode", ",", "api_tag", ")", ":", "tag", "=", "None", "# try to get from the ref data map if in bulk mode", "if", "bulk_mode", ":", "tag", "=", "self", ".", "ref_data_map", "[", "\"tags\"", "]", ".", "get", "(", ...
Create or update a Tag related to a post. :param bulk_mode: If True, minimize db operations by bulk creating post objects :param api_tag: the API data for the Tag :return: the Tag object
[ "Create", "or", "update", "a", "Tag", "related", "to", "a", "post", "." ]
python
train
38.444444
fr33jc/bang
bang/providers/openstack/__init__.py
https://github.com/fr33jc/bang/blob/8f000713f88d2a9a8c1193b63ca10a6578560c16/bang/providers/openstack/__init__.py#L276-L284
def create_secgroup(self, name, desc): """ Creates a new server security group. :param str name: The name of the security group to create. :param str desc: A short description of the group. """ self.nova.security_groups.create(name, desc)
[ "def", "create_secgroup", "(", "self", ",", "name", ",", "desc", ")", ":", "self", ".", "nova", ".", "security_groups", ".", "create", "(", "name", ",", "desc", ")" ]
Creates a new server security group. :param str name: The name of the security group to create. :param str desc: A short description of the group.
[ "Creates", "a", "new", "server", "security", "group", "." ]
python
train
31.333333
HewlettPackard/python-hpOneView
hpOneView/resources/resource.py
https://github.com/HewlettPackard/python-hpOneView/blob/3c6219723ef25e6e0c83d44a89007f89bc325b89/hpOneView/resources/resource.py#L209-L232
def update(self, data=None, timeout=-1, custom_headers=None, force=False): """Makes a PUT request to update a resource when a request body is required. Args: data: Data to update the resource. timeout: Timeout in seconds. Wait for task completion by default. The timeout does not...
[ "def", "update", "(", "self", ",", "data", "=", "None", ",", "timeout", "=", "-", "1", ",", "custom_headers", "=", "None", ",", "force", "=", "False", ")", ":", "uri", "=", "self", ".", "data", "[", "'uri'", "]", "resource", "=", "deepcopy", "(", ...
Makes a PUT request to update a resource when a request body is required. Args: data: Data to update the resource. timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneView; it just stops waiting for its complet...
[ "Makes", "a", "PUT", "request", "to", "update", "a", "resource", "when", "a", "request", "body", "is", "required", "." ]
python
train
37.333333
yandex/yandex-tank
yandextank/api/apiworker.py
https://github.com/yandex/yandex-tank/blob/d71d63b6ab5de8b8a5ea2b728b6ab9ac0b1ba71b/yandextank/api/apiworker.py#L154-L161
def __graceful_shutdown(self): """ call shutdown routines """ retcode = 1 self.log.info("Trying to shutdown gracefully...") retcode = self.core.plugins_end_test(retcode) retcode = self.core.plugins_post_process(retcode) self.log.info("Done graceful shutdown") retu...
[ "def", "__graceful_shutdown", "(", "self", ")", ":", "retcode", "=", "1", "self", ".", "log", ".", "info", "(", "\"Trying to shutdown gracefully...\"", ")", "retcode", "=", "self", ".", "core", ".", "plugins_end_test", "(", "retcode", ")", "retcode", "=", "s...
call shutdown routines
[ "call", "shutdown", "routines" ]
python
test
40.375
qiniu/python-sdk
qiniu/services/compute/qcos_api.py
https://github.com/qiniu/python-sdk/blob/a69fbef4e3e6ea1ebe09f4610a5b18bb2c17de59/qiniu/services/compute/qcos_api.py#L319-L336
def extend_service_volume(self, stack, service, volume, args): """扩容存储卷 为指定名称的服务增加存储卷资源,并挂载到部署的容器中。 Args: - stack: 服务所属的服务组名称 - service: 服务名 - volume: 存储卷名 - args: 请求参数(json),参考 http://kirk-docs.qiniu.com/apidocs/ Returns: ...
[ "def", "extend_service_volume", "(", "self", ",", "stack", ",", "service", ",", "volume", ",", "args", ")", ":", "url", "=", "'{0}/v3/stacks/{1}/services/{2}/volumes/{3}/extend'", ".", "format", "(", "self", ".", "host", ",", "stack", ",", "service", ",", "vol...
扩容存储卷 为指定名称的服务增加存储卷资源,并挂载到部署的容器中。 Args: - stack: 服务所属的服务组名称 - service: 服务名 - volume: 存储卷名 - args: 请求参数(json),参考 http://kirk-docs.qiniu.com/apidocs/ Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result ...
[ "扩容存储卷" ]
python
train
35
pebble/libpebble2
libpebble2/communication/__init__.py
https://github.com/pebble/libpebble2/blob/23e2eb92cfc084e6f9e8c718711ac994ef606d18/libpebble2/communication/__init__.py#L105-L142
def _handle_watch_message(self, message): """ Processes a binary message received from the watch and broadcasts the relevant events. :param message: A raw message from the watch, without any transport framing. :type message: bytes """ if self.log_protocol_level is not No...
[ "def", "_handle_watch_message", "(", "self", ",", "message", ")", ":", "if", "self", ".", "log_protocol_level", "is", "not", "None", ":", "logger", ".", "log", "(", "self", ".", "log_protocol_level", ",", "\"<- %s\"", ",", "hexlify", "(", "message", ")", "...
Processes a binary message received from the watch and broadcasts the relevant events. :param message: A raw message from the watch, without any transport framing. :type message: bytes
[ "Processes", "a", "binary", "message", "received", "from", "the", "watch", "and", "broadcasts", "the", "relevant", "events", "." ]
python
train
48.342105
rh-marketingops/dwm
dwm/helpers.py
https://github.com/rh-marketingops/dwm/blob/66c7d18db857afbe5d574478ceaaad6159ae7469/dwm/helpers.py#L29-L44
def _CollectHistoryAgg_(contactHist, fieldHistObj, fieldName): """ Return updated history dictionary with new field change :param dict contactHist: Existing contact history dictionary :param dict fieldHistObj: Output of _CollectHistory_ :param string fieldName: field name """ if fieldHistO...
[ "def", "_CollectHistoryAgg_", "(", "contactHist", ",", "fieldHistObj", ",", "fieldName", ")", ":", "if", "fieldHistObj", "!=", "{", "}", ":", "if", "fieldName", "not", "in", "contactHist", ".", "keys", "(", ")", ":", "contactHist", "[", "fieldName", "]", "...
Return updated history dictionary with new field change :param dict contactHist: Existing contact history dictionary :param dict fieldHistObj: Output of _CollectHistory_ :param string fieldName: field name
[ "Return", "updated", "history", "dictionary", "with", "new", "field", "change" ]
python
train
34.0625
CyberZHG/keras-transformer
keras_transformer/transformer.py
https://github.com/CyberZHG/keras-transformer/blob/4c42baa030539c62ef5ace92df0408b13f26d928/keras_transformer/transformer.py#L246-L281
def get_decoders(decoder_num, input_layer, encoded_layer, head_num, hidden_dim, attention_activation=None, feed_forward_activation='relu', dropout_rate=0.0, trainable=True): """Get...
[ "def", "get_decoders", "(", "decoder_num", ",", "input_layer", ",", "encoded_layer", ",", "head_num", ",", "hidden_dim", ",", "attention_activation", "=", "None", ",", "feed_forward_activation", "=", "'relu'", ",", "dropout_rate", "=", "0.0", ",", "trainable", "="...
Get decoders. :param decoder_num: Number of decoder components. :param input_layer: Input layer. :param encoded_layer: Encoded layer from encoder. :param head_num: Number of heads in multi-head self-attention. :param hidden_dim: Hidden dimension of feed forward layer. :param attention_activatio...
[ "Get", "decoders", "." ]
python
train
37.694444
getsentry/libsourcemap
libsourcemap/highlevel.py
https://github.com/getsentry/libsourcemap/blob/94b5a34814fafee9dc23da8ec0ccca77f30e3370/libsourcemap/highlevel.py#L221-L224
def iter_sources(self): """Iterates over all source names and IDs.""" for src_id in xrange(self.get_source_count()): yield src_id, self.get_source_name(src_id)
[ "def", "iter_sources", "(", "self", ")", ":", "for", "src_id", "in", "xrange", "(", "self", ".", "get_source_count", "(", ")", ")", ":", "yield", "src_id", ",", "self", ".", "get_source_name", "(", "src_id", ")" ]
Iterates over all source names and IDs.
[ "Iterates", "over", "all", "source", "names", "and", "IDs", "." ]
python
train
46
tgbugs/pyontutils
ilxutils/ilxutils/interlex_sql.py
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/interlex_sql.py#L67-L82
def get_terms(self): ''' GROUP BY is a shortcut to only getting the first in every list of group ''' if not self.terms.empty: return self.terms if self.from_backup: self.terms = open_pickle(TERMS_BACKUP_PATH) return self.terms engine = create_engine(se...
[ "def", "get_terms", "(", "self", ")", ":", "if", "not", "self", ".", "terms", ".", "empty", ":", "return", "self", ".", "terms", "if", "self", ".", "from_backup", ":", "self", ".", "terms", "=", "open_pickle", "(", "TERMS_BACKUP_PATH", ")", "return", "...
GROUP BY is a shortcut to only getting the first in every list of group
[ "GROUP", "BY", "is", "a", "shortcut", "to", "only", "getting", "the", "first", "in", "every", "list", "of", "group" ]
python
train
38.4375
globocom/GloboNetworkAPI-client-python
networkapiclient/Ambiente.py
https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/Ambiente.py#L228-L259
def listar_por_equip(self, equip_id): """Lista todos os ambientes por equipamento especifico. :return: Dicionário com a seguinte estrutura: :: {'ambiente': {'id': < id_ambiente >, 'link': < link >, 'id_divisao': < id_divisao >, 'nome_divisao': <...
[ "def", "listar_por_equip", "(", "self", ",", "equip_id", ")", ":", "if", "equip_id", "is", "None", ":", "raise", "InvalidParameterError", "(", "u'O id do equipamento não foi informado.')", "", "url", "=", "'ambiente/equip/'", "+", "str", "(", "equip_id", ")", "+",...
Lista todos os ambientes por equipamento especifico. :return: Dicionário com a seguinte estrutura: :: {'ambiente': {'id': < id_ambiente >, 'link': < link >, 'id_divisao': < id_divisao >, 'nome_divisao': < nome_divisao >, 'id_ambiente_logico'...
[ "Lista", "todos", "os", "ambientes", "por", "equipamento", "especifico", "." ]
python
train
34.125
pkgw/pwkit
pwkit/colormaps.py
https://github.com/pkgw/pwkit/blob/d40957a1c3d2ea34e7ceac2267ee9635135f2793/pwkit/colormaps.py#L322-L339
def moreland_adjusthue (msh, m_unsat): """Moreland's AdjustHue procedure to adjust the hue value of an Msh color based on ... some criterion. *msh* should be of of shape (3, ). *m_unsat* is a scalar. Return value is the adjusted h (hue) value. """ if msh[M] >= m_unsat: return msh[H] #...
[ "def", "moreland_adjusthue", "(", "msh", ",", "m_unsat", ")", ":", "if", "msh", "[", "M", "]", ">=", "m_unsat", ":", "return", "msh", "[", "H", "]", "# \"Best we can do\"", "hspin", "=", "(", "msh", "[", "S", "]", "*", "np", ".", "sqrt", "(", "m_un...
Moreland's AdjustHue procedure to adjust the hue value of an Msh color based on ... some criterion. *msh* should be of of shape (3, ). *m_unsat* is a scalar. Return value is the adjusted h (hue) value.
[ "Moreland", "s", "AdjustHue", "procedure", "to", "adjust", "the", "hue", "value", "of", "an", "Msh", "color", "based", "on", "...", "some", "criterion", "." ]
python
train
29.444444
ejeschke/ginga
ginga/rv/plugins/PlotTable.py
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/PlotTable.py#L378-L401
def set_xlim_cb(self, redraw=True): """Set plot limit based on user values.""" try: xmin = float(self.w.x_lo.get_text()) except Exception: set_min = True else: set_min = False try: xmax = float(self.w.x_hi.get_text()) excep...
[ "def", "set_xlim_cb", "(", "self", ",", "redraw", "=", "True", ")", ":", "try", ":", "xmin", "=", "float", "(", "self", ".", "w", ".", "x_lo", ".", "get_text", "(", ")", ")", "except", "Exception", ":", "set_min", "=", "True", "else", ":", "set_min...
Set plot limit based on user values.
[ "Set", "plot", "limit", "based", "on", "user", "values", "." ]
python
train
27.625
richardchien/python-cqhttp
cqhttp_helper.py
https://github.com/richardchien/python-cqhttp/blob/1869819a8f89001e3f70668e31afc6c78f7f5bc2/cqhttp_helper.py#L321-L338
def send_msg_async(self, *, message_type, user_id=None, group_id=None, discuss_id=None, message, auto_escape=False): """ 发送消息 (异步版本) ------------ :param str message_type: 消息类型,支持 `private`、`group`、`discuss`,分别对应私聊、群组、讨论组 :param int user_id: 对方 QQ 号(消息类型为 `private` 时需要) ...
[ "def", "send_msg_async", "(", "self", ",", "*", ",", "message_type", ",", "user_id", "=", "None", ",", "group_id", "=", "None", ",", "discuss_id", "=", "None", ",", "message", ",", "auto_escape", "=", "False", ")", ":", "return", "super", "(", ")", "."...
发送消息 (异步版本) ------------ :param str message_type: 消息类型,支持 `private`、`group`、`discuss`,分别对应私聊、群组、讨论组 :param int user_id: 对方 QQ 号(消息类型为 `private` 时需要) :param int group_id: 群号(消息类型为 `group` 时需要) :param int discuss_id: 讨论组 ID(需要从上报消息中获取,消息类型为 `discuss` 时需要) :param str | lis...
[ "发送消息", "(", "异步版本", ")" ]
python
valid
46.111111
QuantEcon/QuantEcon.py
quantecon/gridtools.py
https://github.com/QuantEcon/QuantEcon.py/blob/26a66c552f2a73967d7efb6e1f4b4c4985a12643/quantecon/gridtools.py#L13-L51
def cartesian(nodes, order='C'): ''' Cartesian product of a list of arrays Parameters ---------- nodes : list(array_like(ndim=1)) order : str, optional(default='C') ('C' or 'F') order in which the product is enumerated Returns ------- out : ndarray(ndim=2) each lin...
[ "def", "cartesian", "(", "nodes", ",", "order", "=", "'C'", ")", ":", "nodes", "=", "[", "np", ".", "array", "(", "e", ")", "for", "e", "in", "nodes", "]", "shapes", "=", "[", "e", ".", "shape", "[", "0", "]", "for", "e", "in", "nodes", "]", ...
Cartesian product of a list of arrays Parameters ---------- nodes : list(array_like(ndim=1)) order : str, optional(default='C') ('C' or 'F') order in which the product is enumerated Returns ------- out : ndarray(ndim=2) each line corresponds to one point of the product spa...
[ "Cartesian", "product", "of", "a", "list", "of", "arrays" ]
python
train
22.512821
gem/oq-engine
openquake/hazardlib/geo/surface/multi.py
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/multi.py#L174-L216
def get_closest_points(self, mesh): """ For each point in ``mesh`` find the closest surface element, and return the corresponding closest point. See :meth:`superclass method <.base.BaseSurface.get_closest_points>` for spec of input and result values. """ ...
[ "def", "get_closest_points", "(", "self", ",", "mesh", ")", ":", "# first, for each point in mesh compute minimum distance to each", "# surface. The distance matrix is flattend, because mesh can be of", "# an arbitrary shape. By flattening we obtain a ``distances`` matrix", "# for which the fi...
For each point in ``mesh`` find the closest surface element, and return the corresponding closest point. See :meth:`superclass method <.base.BaseSurface.get_closest_points>` for spec of input and result values.
[ "For", "each", "point", "in", "mesh", "find", "the", "closest", "surface", "element", "and", "return", "the", "corresponding", "closest", "point", "." ]
python
train
45.325581
pytroll/pyspectral
pyspectral/utils.py
https://github.com/pytroll/pyspectral/blob/fd296c0e0bdf5364fa180134a1292665d6bc50a3/pyspectral/utils.py#L343-L382
def download_rsr(**kwargs): """Download the pre-compiled hdf5 formatet relative spectral response functions from the internet """ # import tarfile import requests TQDM_LOADED = True try: from tqdm import tqdm except ImportError: TQDM_LOADED = False dest_dir = k...
[ "def", "download_rsr", "(", "*", "*", "kwargs", ")", ":", "#", "import", "tarfile", "import", "requests", "TQDM_LOADED", "=", "True", "try", ":", "from", "tqdm", "import", "tqdm", "except", "ImportError", ":", "TQDM_LOADED", "=", "False", "dest_dir", "=", ...
Download the pre-compiled hdf5 formatet relative spectral response functions from the internet
[ "Download", "the", "pre", "-", "compiled", "hdf5", "formatet", "relative", "spectral", "response", "functions", "from", "the", "internet" ]
python
train
26.9
Capitains/Nautilus
capitains_nautilus/collections/sparql.py
https://github.com/Capitains/Nautilus/blob/6be453fe0cc0e2c1b89ff06e5af1409165fc1411/capitains_nautilus/collections/sparql.py#L50-L67
def generate_sleepy_cat_graph(filepath, prefixes=None, identifier="NautilusSparql"): """ Generate a graph and change the global graph to this one :param filepath: A Uri for the graph :param prefixes: A dictionary of prefixes and namespaces to bind to the graph :param identifier: An identifier that will...
[ "def", "generate_sleepy_cat_graph", "(", "filepath", ",", "prefixes", "=", "None", ",", "identifier", "=", "\"NautilusSparql\"", ")", ":", "registerplugins", "(", ")", "ident", "=", "URIRef", "(", "identifier", ")", "graph", "=", "Graph", "(", "'Sleepycat'", "...
Generate a graph and change the global graph to this one :param filepath: A Uri for the graph :param prefixes: A dictionary of prefixes and namespaces to bind to the graph :param identifier: An identifier that will identify the Graph root
[ "Generate", "a", "graph", "and", "change", "the", "global", "graph", "to", "this", "one" ]
python
train
39.388889
iopipe/iopipe-python
iopipe/plugins.py
https://github.com/iopipe/iopipe-python/blob/4eb653977341bc67f8b1b87aedb3aaaefc25af61/iopipe/plugins.py#L4-L22
def get_plugin_meta(plugins): """ Returns meta data about plugins. :param plugins: A list of plugins. :type plugins: list :returns: A list of dicts containing plugin meta data. :rtype: list """ return [ { "name": p.name, "version": p.version, ...
[ "def", "get_plugin_meta", "(", "plugins", ")", ":", "return", "[", "{", "\"name\"", ":", "p", ".", "name", ",", "\"version\"", ":", "p", ".", "version", ",", "\"homepage\"", ":", "p", ".", "homepage", ",", "\"enabled\"", ":", "p", ".", "enabled", ",", ...
Returns meta data about plugins. :param plugins: A list of plugins. :type plugins: list :returns: A list of dicts containing plugin meta data. :rtype: list
[ "Returns", "meta", "data", "about", "plugins", "." ]
python
train
22.315789
saltstack/salt
salt/modules/boto_apigateway.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L523-L529
def _api_key_patch_replace(conn, apiKey, path, value): ''' the replace patch operation on an ApiKey resource ''' response = conn.update_api_key(apiKey=apiKey, patchOperations=[{'op': 'replace', 'path': path, 'value': value}]) return response
[ "def", "_api_key_patch_replace", "(", "conn", ",", "apiKey", ",", "path", ",", "value", ")", ":", "response", "=", "conn", ".", "update_api_key", "(", "apiKey", "=", "apiKey", ",", "patchOperations", "=", "[", "{", "'op'", ":", "'replace'", ",", "'path'", ...
the replace patch operation on an ApiKey resource
[ "the", "replace", "patch", "operation", "on", "an", "ApiKey", "resource" ]
python
train
41.428571
Kitware/tangelo
tangelo/tangelo/pkgdata/plugin/watch/python/__init__.py
https://github.com/Kitware/tangelo/blob/470034ee9b3d7a01becc1ce5fddc7adc1d5263ef/tangelo/tangelo/pkgdata/plugin/watch/python/__init__.py#L123-L148
def reload_including_local(module): """ Reload a module. If it isn"t found, try to include the local service directory. This must be called from a thread that has acquired the import lock. :param module: the module to reload. """ try: reload(module) except ImportError: ...
[ "def", "reload_including_local", "(", "module", ")", ":", "try", ":", "reload", "(", "module", ")", "except", "ImportError", ":", "# This can happen if the module was loaded in the immediate script", "# directory. Add the service path and try again.", "if", "not", "hasattr", ...
Reload a module. If it isn"t found, try to include the local service directory. This must be called from a thread that has acquired the import lock. :param module: the module to reload.
[ "Reload", "a", "module", ".", "If", "it", "isn", "t", "found", "try", "to", "include", "the", "local", "service", "directory", ".", "This", "must", "be", "called", "from", "a", "thread", "that", "has", "acquired", "the", "import", "lock", "." ]
python
train
35.692308
marshmallow-code/marshmallow
src/marshmallow/schema.py
https://github.com/marshmallow-code/marshmallow/blob/a6b6c4151f1fbf16f3774d4052ca2bddf6903750/src/marshmallow/schema.py#L435-L489
def _serialize( self, obj, fields_dict, error_store, many=False, accessor=None, dict_class=dict, index_errors=True, index=None, ): """Takes raw data (a dict, list, or other object) and a dict of fields to output and serializes the data based on those fields. :param o...
[ "def", "_serialize", "(", "self", ",", "obj", ",", "fields_dict", ",", "error_store", ",", "many", "=", "False", ",", "accessor", "=", "None", ",", "dict_class", "=", "dict", ",", "index_errors", "=", "True", ",", "index", "=", "None", ",", ")", ":", ...
Takes raw data (a dict, list, or other object) and a dict of fields to output and serializes the data based on those fields. :param obj: The actual object(s) from which the fields are taken from :param dict fields_dict: Mapping of field names to :class:`Field` objects. :param ErrorStore...
[ "Takes", "raw", "data", "(", "a", "dict", "list", "or", "other", "object", ")", "and", "a", "dict", "of", "fields", "to", "output", "and", "serializes", "the", "data", "based", "on", "those", "fields", "." ]
python
train
41.727273
kynikos/lib.py.cmenu
cmenu.py
https://github.com/kynikos/lib.py.cmenu/blob/eb1e806f0b674c4deb24730cbd7cf4604150c461/cmenu.py#L331-L341
def iter_walk_menus(self): """ Useful for example to spread changes to the prompt, e.g. enabling or disabling colors. """ yield self for item in self.name_to_command.values(): if isinstance(item, _Menu): # "Generator delegation" ;) ...
[ "def", "iter_walk_menus", "(", "self", ")", ":", "yield", "self", "for", "item", "in", "self", ".", "name_to_command", ".", "values", "(", ")", ":", "if", "isinstance", "(", "item", ",", "_Menu", ")", ":", "# \"Generator delegation\" ;)", "# https://docs.pytho...
Useful for example to spread changes to the prompt, e.g. enabling or disabling colors.
[ "Useful", "for", "example", "to", "spread", "changes", "to", "the", "prompt", "e", ".", "g", ".", "enabling", "or", "disabling", "colors", "." ]
python
train
37.909091
globality-corp/microcosm-postgres
microcosm_postgres/temporary/copy.py
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/temporary/copy.py#L18-L33
def should_copy(column): """ Determine if a column should be copied. """ if not isinstance(column.type, Serial): return True if column.nullable: return True if not column.server_default: return True # do not create temporary serial values; they will be defaulted o...
[ "def", "should_copy", "(", "column", ")", ":", "if", "not", "isinstance", "(", "column", ".", "type", ",", "Serial", ")", ":", "return", "True", "if", "column", ".", "nullable", ":", "return", "True", "if", "not", "column", ".", "server_default", ":", ...
Determine if a column should be copied.
[ "Determine", "if", "a", "column", "should", "be", "copied", "." ]
python
train
21.0625
buzzfeed/caliendo
caliendo/pickling.py
https://github.com/buzzfeed/caliendo/blob/1628a10f7782ad67c0422b5cbc9bf4979ac40abc/caliendo/pickling.py#L61-L85
def setattr_at_path( obj, path, val ): """ Traverses a set of nested attributes to the value on an object :param mixed obj: The object to set the attribute on :param tuple path: The path to the attribute on the object :param mixed val: The value at the attribute :rtype None: """ target...
[ "def", "setattr_at_path", "(", "obj", ",", "path", ",", "val", ")", ":", "target", "=", "obj", "last_attr", "=", "path", "[", "-", "1", "]", "for", "attr", "in", "path", "[", "0", ":", "-", "1", "]", ":", "try", ":", "if", "type", "(", "attr", ...
Traverses a set of nested attributes to the value on an object :param mixed obj: The object to set the attribute on :param tuple path: The path to the attribute on the object :param mixed val: The value at the attribute :rtype None:
[ "Traverses", "a", "set", "of", "nested", "attributes", "to", "the", "value", "on", "an", "object" ]
python
train
28.84
carlospalol/money
money/exchange.py
https://github.com/carlospalol/money/blob/1e51f651f93edd62c16eb3d7aa034fec03096046/money/exchange.py#L119-L123
def quotation(self, origin, target): """Return quotation between two currencies (origin, target)""" if not self._backend: raise ExchangeBackendNotInstalled() return self._backend.quotation(origin, target)
[ "def", "quotation", "(", "self", ",", "origin", ",", "target", ")", ":", "if", "not", "self", ".", "_backend", ":", "raise", "ExchangeBackendNotInstalled", "(", ")", "return", "self", ".", "_backend", ".", "quotation", "(", "origin", ",", "target", ")" ]
Return quotation between two currencies (origin, target)
[ "Return", "quotation", "between", "two", "currencies", "(", "origin", "target", ")" ]
python
train
47.2
bapakode/OmMongo
ommongo/document.py
https://github.com/bapakode/OmMongo/blob/52b5a5420516dc709f2d2eb065818c7973991ce3/ommongo/document.py#L625-L631
def descending(self, name): ''' Add a descending index for ``name`` to this index. :param name: Name to be used in the index ''' self.components.append((name, Index.DESCENDING)) return self
[ "def", "descending", "(", "self", ",", "name", ")", ":", "self", ".", "components", ".", "append", "(", "(", "name", ",", "Index", ".", "DESCENDING", ")", ")", "return", "self" ]
Add a descending index for ``name`` to this index. :param name: Name to be used in the index
[ "Add", "a", "descending", "index", "for", "name", "to", "this", "index", "." ]
python
train
32.571429
jtwhite79/pyemu
pyemu/pst/pst_utils.py
https://github.com/jtwhite79/pyemu/blob/c504d8e7a4097cec07655a6318d275739bd8148a/pyemu/pst/pst_utils.py#L751-L783
def clean_missing_exponent(pst_filename,clean_filename="clean.pst"): """fixes the issue where some terrible fortran program may have written a floating point format without the 'e' - like 1.0-3, really?! Parameters ---------- pst_filename : str the pest control file clean_filename : str...
[ "def", "clean_missing_exponent", "(", "pst_filename", ",", "clean_filename", "=", "\"clean.pst\"", ")", ":", "lines", "=", "[", "]", "with", "open", "(", "pst_filename", ",", "'r'", ")", "as", "f", ":", "for", "line", "in", "f", ":", "line", "=", "line",...
fixes the issue where some terrible fortran program may have written a floating point format without the 'e' - like 1.0-3, really?! Parameters ---------- pst_filename : str the pest control file clean_filename : str the new pest control file to write. Default is "clean.pst" Ret...
[ "fixes", "the", "issue", "where", "some", "terrible", "fortran", "program", "may", "have", "written", "a", "floating", "point", "format", "without", "the", "e", "-", "like", "1", ".", "0", "-", "3", "really?!" ]
python
train
28.121212
StackStorm/pybind
pybind/slxos/v17s_1_02/routing_system/interface/loopback/ip/__init__.py
https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17s_1_02/routing_system/interface/loopback/ip/__init__.py#L164-L185
def _set_interface_loopback_ospf_conf(self, v, load=False): """ Setter method for interface_loopback_ospf_conf, mapped from YANG variable /routing_system/interface/loopback/ip/interface_loopback_ospf_conf (container) If this variable is read-only (config: false) in the source YANG file, then _set_interf...
[ "def", "_set_interface_loopback_ospf_conf", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", ...
Setter method for interface_loopback_ospf_conf, mapped from YANG variable /routing_system/interface/loopback/ip/interface_loopback_ospf_conf (container) If this variable is read-only (config: false) in the source YANG file, then _set_interface_loopback_ospf_conf is considered as a private method. Backends l...
[ "Setter", "method", "for", "interface_loopback_ospf_conf", "mapped", "from", "YANG", "variable", "/", "routing_system", "/", "interface", "/", "loopback", "/", "ip", "/", "interface_loopback_ospf_conf", "(", "container", ")", "If", "this", "variable", "is", "read", ...
python
train
86.590909
google/tangent
tangent/utils.py
https://github.com/google/tangent/blob/6533e83af09de7345d1b438512679992f080dcc9/tangent/utils.py#L151-L164
def unreduce(array, shape, axis, keepdims): """Reverse summing over a dimension. Args: array: The array that was reduced. shape: The original shape of the array before reduction. axis: The axis or axes that were summed. keepdims: Whether these axes were kept as singleton axes. Returns: An ar...
[ "def", "unreduce", "(", "array", ",", "shape", ",", "axis", ",", "keepdims", ")", ":", "unreducer", "=", "unreducers", "[", "type", "(", "array", ")", "]", "return", "unreducer", "(", "array", ",", "shape", ",", "axis", ",", "keepdims", ")" ]
Reverse summing over a dimension. Args: array: The array that was reduced. shape: The original shape of the array before reduction. axis: The axis or axes that were summed. keepdims: Whether these axes were kept as singleton axes. Returns: An array with axes broadcast to match the shape of the...
[ "Reverse", "summing", "over", "a", "dimension", "." ]
python
train
33.214286
chimera0/accel-brain-code
Generative-Adversarial-Networks/pygan/discriminativemodel/lstm_model.py
https://github.com/chimera0/accel-brain-code/blob/03661f6f544bed656269fcd4b3c23c9061629daa/Generative-Adversarial-Networks/pygan/discriminativemodel/lstm_model.py#L218-L245
def learn(self, grad_arr, fix_opt_flag=False): ''' Update this Discriminator by ascending its stochastic gradient. Args: grad_arr: `np.ndarray` of gradients. fix_opt_flag: If `False`, no optimization in this model will be done. Returns: ...
[ "def", "learn", "(", "self", ",", "grad_arr", ",", "fix_opt_flag", "=", "False", ")", ":", "if", "grad_arr", ".", "ndim", ">", "3", ":", "grad_arr", "=", "grad_arr", ".", "reshape", "(", "(", "grad_arr", ".", "shape", "[", "0", "]", ",", "grad_arr", ...
Update this Discriminator by ascending its stochastic gradient. Args: grad_arr: `np.ndarray` of gradients. fix_opt_flag: If `False`, no optimization in this model will be done. Returns: `np.ndarray` of delta or gradients.
[ "Update", "this", "Discriminator", "by", "ascending", "its", "stochastic", "gradient", ".", "Args", ":", "grad_arr", ":", "np", ".", "ndarray", "of", "gradients", ".", "fix_opt_flag", ":", "If", "False", "no", "optimization", "in", "this", "model", "will", "...
python
train
30
python-astrodynamics/spacetrack
spacetrack/base.py
https://github.com/python-astrodynamics/spacetrack/blob/18f63b7de989a31b983d140a11418e01bd6fd398/spacetrack/base.py#L686-L719
def _raise_for_status(response): """Raises stored :class:`HTTPError`, if one occurred. This is the :meth:`requests.models.Response.raise_for_status` method, modified to add the response from Space-Track, if given. """ http_error_msg = '' if 400 <= response.status_code < 500: http_erro...
[ "def", "_raise_for_status", "(", "response", ")", ":", "http_error_msg", "=", "''", "if", "400", "<=", "response", ".", "status_code", "<", "500", ":", "http_error_msg", "=", "'%s Client Error: %s for url: %s'", "%", "(", "response", ".", "status_code", ",", "re...
Raises stored :class:`HTTPError`, if one occurred. This is the :meth:`requests.models.Response.raise_for_status` method, modified to add the response from Space-Track, if given.
[ "Raises", "stored", ":", "class", ":", "HTTPError", "if", "one", "occurred", "." ]
python
train
32.382353
apache/airflow
airflow/models/dagbag.py
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/models/dagbag.py#L112-L143
def get_dag(self, dag_id): """ Gets the DAG out of the dictionary, and refreshes it if expired """ from airflow.models.dag import DagModel # Avoid circular import # If asking for a known subdag, we want to refresh the parent root_dag_id = dag_id if dag_id in sel...
[ "def", "get_dag", "(", "self", ",", "dag_id", ")", ":", "from", "airflow", ".", "models", ".", "dag", "import", "DagModel", "# Avoid circular import", "# If asking for a known subdag, we want to refresh the parent", "root_dag_id", "=", "dag_id", "if", "dag_id", "in", ...
Gets the DAG out of the dictionary, and refreshes it if expired
[ "Gets", "the", "DAG", "out", "of", "the", "dictionary", "and", "refreshes", "it", "if", "expired" ]
python
test
38.625
mozillazg/baidu-pcs-python-sdk
baidupcs/api.py
https://github.com/mozillazg/baidu-pcs-python-sdk/blob/12fe3f13b2ecda8f8bdcc5334c876e934776a5cc/baidupcs/api.py#L103-L135
def upload(self, remote_path, file_content, ondup=None, **kwargs): """上传单个文件(<2G). | 百度PCS服务目前支持最大2G的单个文件上传。 | 如需支持超大文件(>2G)的断点续传,请参考下面的“分片文件上传”方法。 :param remote_path: 网盘中文件的保存路径(包含文件名)。 必须以 /apps/ 开头。 .. warning:: ...
[ "def", "upload", "(", "self", ",", "remote_path", ",", "file_content", ",", "ondup", "=", "None", ",", "*", "*", "kwargs", ")", ":", "params", "=", "{", "'path'", ":", "remote_path", ",", "'ondup'", ":", "ondup", "}", "files", "=", "{", "'file'", ":"...
上传单个文件(<2G). | 百度PCS服务目前支持最大2G的单个文件上传。 | 如需支持超大文件(>2G)的断点续传,请参考下面的“分片文件上传”方法。 :param remote_path: 网盘中文件的保存路径(包含文件名)。 必须以 /apps/ 开头。 .. warning:: * 路径长度限制为1000; * 径中不能包含以下字符:...
[ "上传单个文件(<2G)", "." ]
python
train
36.515152
apache/incubator-superset
superset/views/core.py
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/views/core.py#L1900-L1903
def fave_dashboards_by_username(self, username): """This lets us use a user's username to pull favourite dashboards""" user = security_manager.find_user(username=username) return self.fave_dashboards(user.get_id())
[ "def", "fave_dashboards_by_username", "(", "self", ",", "username", ")", ":", "user", "=", "security_manager", ".", "find_user", "(", "username", "=", "username", ")", "return", "self", ".", "fave_dashboards", "(", "user", ".", "get_id", "(", ")", ")" ]
This lets us use a user's username to pull favourite dashboards
[ "This", "lets", "us", "use", "a", "user", "s", "username", "to", "pull", "favourite", "dashboards" ]
python
train
58.75
Kortemme-Lab/klab
klab/scripting.py
https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/scripting.py#L57-L65
def relative_symlink(target, link_name): """Make a symlink to target using the shortest possible relative path.""" link_name = os.path.abspath(link_name) abs_target = os.path.abspath(target) rel_target = os.path.relpath(target, os.path.dirname(link_name)) if os.path.exists(link_name): os.re...
[ "def", "relative_symlink", "(", "target", ",", "link_name", ")", ":", "link_name", "=", "os", ".", "path", ".", "abspath", "(", "link_name", ")", "abs_target", "=", "os", ".", "path", ".", "abspath", "(", "target", ")", "rel_target", "=", "os", ".", "p...
Make a symlink to target using the shortest possible relative path.
[ "Make", "a", "symlink", "to", "target", "using", "the", "shortest", "possible", "relative", "path", "." ]
python
train
40.555556
saltstack/salt
salt/transport/zeromq.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/zeromq.py#L1002-L1009
def pub_close(self): ''' Disconnect an existing publisher socket and remove it from the local thread's cache. ''' if hasattr(self._sock_data, 'sock'): self._sock_data.sock.close() delattr(self._sock_data, 'sock')
[ "def", "pub_close", "(", "self", ")", ":", "if", "hasattr", "(", "self", ".", "_sock_data", ",", "'sock'", ")", ":", "self", ".", "_sock_data", ".", "sock", ".", "close", "(", ")", "delattr", "(", "self", ".", "_sock_data", ",", "'sock'", ")" ]
Disconnect an existing publisher socket and remove it from the local thread's cache.
[ "Disconnect", "an", "existing", "publisher", "socket", "and", "remove", "it", "from", "the", "local", "thread", "s", "cache", "." ]
python
train
33.625
cvxopt/chompack
src/python/pfcholesky.py
https://github.com/cvxopt/chompack/blob/e07106b58b8055c34f6201e8c954482f86987833/src/python/pfcholesky.py#L188-L209
def trmm(self,B,trans='N'): r""" Multiplication with product-form Cholesky factor. Computes .. math:: B &:= L B \text{ if trans is 'N'} B &:= L^T B \text{ if trans is 'T'} """ if trans=='N': pftrmm(self._V,self._L,self._...
[ "def", "trmm", "(", "self", ",", "B", ",", "trans", "=", "'N'", ")", ":", "if", "trans", "==", "'N'", ":", "pftrmm", "(", "self", ".", "_V", ",", "self", ".", "_L", ",", "self", ".", "_B", ",", "B", ",", "trans", "=", "'N'", ")", "cp", ".",...
r""" Multiplication with product-form Cholesky factor. Computes .. math:: B &:= L B \text{ if trans is 'N'} B &:= L^T B \text{ if trans is 'T'}
[ "r", "Multiplication", "with", "product", "-", "form", "Cholesky", "factor", ".", "Computes", "..", "math", "::", "B", "&", ":", "=", "L", "B", "\\", "text", "{", "if", "trans", "is", "N", "}" ]
python
train
29.772727
icgood/pymap
pymap/mime/parsed.py
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/mime/parsed.py#L168-L173
def content_location(self) -> Optional[UnstructuredHeader]: """The ``Content-Location`` header.""" try: return cast(UnstructuredHeader, self[b'content-location'][0]) except (KeyError, IndexError): return None
[ "def", "content_location", "(", "self", ")", "->", "Optional", "[", "UnstructuredHeader", "]", ":", "try", ":", "return", "cast", "(", "UnstructuredHeader", ",", "self", "[", "b'content-location'", "]", "[", "0", "]", ")", "except", "(", "KeyError", ",", "...
The ``Content-Location`` header.
[ "The", "Content", "-", "Location", "header", "." ]
python
train
41.833333
saltstack/salt
salt/sdb/memcached.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/sdb/memcached.py#L71-L76
def get(key, profile=None): ''' Get a value from memcached ''' conn = salt.utils.memcached.get_conn(profile) return salt.utils.memcached.get(conn, key)
[ "def", "get", "(", "key", ",", "profile", "=", "None", ")", ":", "conn", "=", "salt", ".", "utils", ".", "memcached", ".", "get_conn", "(", "profile", ")", "return", "salt", ".", "utils", ".", "memcached", ".", "get", "(", "conn", ",", "key", ")" ]
Get a value from memcached
[ "Get", "a", "value", "from", "memcached" ]
python
train
27.666667
mathandy/svgpathtools
svgpathtools/path.py
https://github.com/mathandy/svgpathtools/blob/fd7348a1dfd88b65ea61da02325c6605aedf8c4f/svgpathtools/path.py#L1676-L1680
def unit_tangent(self, t): """returns the unit tangent vector of the segment at t (centered at the origin and expressed as a complex number).""" dseg = self.derivative(t) return dseg/abs(dseg)
[ "def", "unit_tangent", "(", "self", ",", "t", ")", ":", "dseg", "=", "self", ".", "derivative", "(", "t", ")", "return", "dseg", "/", "abs", "(", "dseg", ")" ]
returns the unit tangent vector of the segment at t (centered at the origin and expressed as a complex number).
[ "returns", "the", "unit", "tangent", "vector", "of", "the", "segment", "at", "t", "(", "centered", "at", "the", "origin", "and", "expressed", "as", "a", "complex", "number", ")", "." ]
python
train
44
timothydmorton/VESPA
vespa/stars/populations.py
https://github.com/timothydmorton/VESPA/blob/0446b54d48009f3655cfd1a3957ceea21d3adcaa/vespa/stars/populations.py#L1239-L1267
def rsky_distribution(self,rmax=None,smooth=0.1,nbins=100): """ Distribution of projected separations Returns a :class:`simpledists.Hist_Distribution` object. :param rmax: (optional) Maximum radius to calculate distribution. :param dr: (optional) Bin wi...
[ "def", "rsky_distribution", "(", "self", ",", "rmax", "=", "None", ",", "smooth", "=", "0.1", ",", "nbins", "=", "100", ")", ":", "if", "rmax", "is", "None", ":", "if", "hasattr", "(", "self", ",", "'maxrad'", ")", ":", "rmax", "=", "self", ".", ...
Distribution of projected separations Returns a :class:`simpledists.Hist_Distribution` object. :param rmax: (optional) Maximum radius to calculate distribution. :param dr: (optional) Bin width for histogram :param smooth: (optional) Smoothing param...
[ "Distribution", "of", "projected", "separations" ]
python
train
30.551724
cebel/pyctd
src/pyctd/manager/query.py
https://github.com/cebel/pyctd/blob/38ba02adaddb60cef031d3b75516773fe8a046b5/src/pyctd/manager/query.py#L56-L81
def _join_chemical(query, cas_rn, chemical_id, chemical_name, chemical_definition): """helper function to add a query join to Chemical model :param `sqlalchemy.orm.query.Query` query: SQL Alchemy query :param cas_rn: :param chemical_id: :param chemical_name: ...
[ "def", "_join_chemical", "(", "query", ",", "cas_rn", ",", "chemical_id", ",", "chemical_name", ",", "chemical_definition", ")", ":", "if", "cas_rn", "or", "chemical_id", "or", "chemical_name", "or", "chemical_definition", ":", "query", "=", "query", ".", "join"...
helper function to add a query join to Chemical model :param `sqlalchemy.orm.query.Query` query: SQL Alchemy query :param cas_rn: :param chemical_id: :param chemical_name: :param chemical_definition: :return: `sqlalchemy.orm.query.Query` object
[ "helper", "function", "to", "add", "a", "query", "join", "to", "Chemical", "model", ":", "param", "sqlalchemy", ".", "orm", ".", "query", ".", "Query", "query", ":", "SQL", "Alchemy", "query", ":", "param", "cas_rn", ":", ":", "param", "chemical_id", ":"...
python
train
38
koordinates/python-client
koordinates/client.py
https://github.com/koordinates/python-client/blob/f3dc7cd164f5a9499b2454cd1d4516e9d4b3c252/koordinates/client.py#L102-L116
def get_manager(self, model): """ Return the active manager for the given model. :param model: Model class to look up the manager instance for. :return: Manager instance for the model associated with this client. """ if isinstance(model, six.string_types): # u...
[ "def", "get_manager", "(", "self", ",", "model", ")", ":", "if", "isinstance", "(", "model", ",", "six", ".", "string_types", ")", ":", "# undocumented string lookup", "for", "k", ",", "m", "in", "self", ".", "_manager_map", ".", "items", "(", ")", ":", ...
Return the active manager for the given model. :param model: Model class to look up the manager instance for. :return: Manager instance for the model associated with this client.
[ "Return", "the", "active", "manager", "for", "the", "given", "model", ".", ":", "param", "model", ":", "Model", "class", "to", "look", "up", "the", "manager", "instance", "for", ".", ":", "return", ":", "Manager", "instance", "for", "the", "model", "asso...
python
train
36.533333
aouyar/PyMunin
pymunin/__init__.py
https://github.com/aouyar/PyMunin/blob/4f58a64b6b37c85a84cc7e1e07aafaa0321b249d/pymunin/__init__.py#L836-L869
def addField(self, name, label, type=None, draw=None, info=None, #@ReservedAssignment extinfo=None, colour=None, negative=None, graph=None, min=None, max=None, cdef=None, line=None, #@ReservedAssignment warning=None, critical=None): """Add field to Munin Grap...
[ "def", "addField", "(", "self", ",", "name", ",", "label", ",", "type", "=", "None", ",", "draw", "=", "None", ",", "info", "=", "None", ",", "#@ReservedAssignment", "extinfo", "=", "None", ",", "colour", "=", "None", ",", "negative", "=", "None", ",...
Add field to Munin Graph @param name: Field Name @param label: Field Label @param type: Stat Type: 'COUNTER' / 'ABSOLUTE' / 'DERIVE' / 'GAUGE' @param draw: Graph Type: 'AREA' / 'LINE{1,2,3}'...
[ "Add", "field", "to", "Munin", "Graph" ]
python
train
48.5
dshean/pygeotools
pygeotools/lib/iolib.py
https://github.com/dshean/pygeotools/blob/5ac745717c0098d01eb293ff1fe32fd7358c76ab/pygeotools/lib/iolib.py#L164-L196
def get_sub_dim(src_ds, scale=None, maxdim=1024): """Compute dimensions of subsampled dataset Parameters ---------- ds : gdal.Dataset Input GDAL Datset scale : int, optional Scaling factor maxdim : int, optional Maximum dimension along either axis, in pixels ...
[ "def", "get_sub_dim", "(", "src_ds", ",", "scale", "=", "None", ",", "maxdim", "=", "1024", ")", ":", "ns", "=", "src_ds", ".", "RasterXSize", "nl", "=", "src_ds", ".", "RasterYSize", "maxdim", "=", "float", "(", "maxdim", ")", "if", "scale", "is", "...
Compute dimensions of subsampled dataset Parameters ---------- ds : gdal.Dataset Input GDAL Datset scale : int, optional Scaling factor maxdim : int, optional Maximum dimension along either axis, in pixels Returns ------- ns Numper of samples in s...
[ "Compute", "dimensions", "of", "subsampled", "dataset" ]
python
train
25.181818
SCIP-Interfaces/PySCIPOpt
examples/finished/transp.py
https://github.com/SCIP-Interfaces/PySCIPOpt/blob/9c960b40d94a48b0304d73dbe28b467b9c065abe/examples/finished/transp.py#L49-L59
def make_inst1(): """creates example data set 1""" I,d = multidict({1:80, 2:270, 3:250 , 4:160, 5:180}) # demand J,M = multidict({1:500, 2:500, 3:500}) # capacity c = {(1,1):4, (1,2):6, (1,3):9, # cost (2,1):5, (2,2):4, (2,3):7, (3,1):6, (3,2):3, (3,3):...
[ "def", "make_inst1", "(", ")", ":", "I", ",", "d", "=", "multidict", "(", "{", "1", ":", "80", ",", "2", ":", "270", ",", "3", ":", "250", ",", "4", ":", "160", ",", "5", ":", "180", "}", ")", "# demand", "J", ",", "M", "=", "multidict", ...
creates example data set 1
[ "creates", "example", "data", "set", "1" ]
python
train
38.909091
zhanglab/psamm
psamm/command.py
https://github.com/zhanglab/psamm/blob/dc427848c4f9d109ca590f0afa024c63b685b3f4/psamm/command.py#L231-L235
def _get_solver(self, **kwargs): """Return a new :class:`psamm.lpsolver.lp.Solver` instance""" solver_args = dict(kwargs) solver_args.update(self._solver_args) return generic.Solver(**solver_args)
[ "def", "_get_solver", "(", "self", ",", "*", "*", "kwargs", ")", ":", "solver_args", "=", "dict", "(", "kwargs", ")", "solver_args", ".", "update", "(", "self", ".", "_solver_args", ")", "return", "generic", ".", "Solver", "(", "*", "*", "solver_args", ...
Return a new :class:`psamm.lpsolver.lp.Solver` instance
[ "Return", "a", "new", ":", "class", ":", "psamm", ".", "lpsolver", ".", "lp", ".", "Solver", "instance" ]
python
train
44.8
linode/linode_api4-python
linode_api4/linode_client.py
https://github.com/linode/linode_api4-python/blob/1dd7318d2aed014c746d48c7957464c57af883ca/linode_api4/linode_client.py#L950-L981
def image_create(self, disk, label=None, description=None): """ Creates a new Image from a disk you own. :param disk: The Disk to imagize. :type disk: Disk or int :param label: The label for the resulting Image (defaults to the disk's label. :type l...
[ "def", "image_create", "(", "self", ",", "disk", ",", "label", "=", "None", ",", "description", "=", "None", ")", ":", "params", "=", "{", "\"disk_id\"", ":", "disk", ".", "id", "if", "issubclass", "(", "type", "(", "disk", ")", ",", "Base", ")", "...
Creates a new Image from a disk you own. :param disk: The Disk to imagize. :type disk: Disk or int :param label: The label for the resulting Image (defaults to the disk's label. :type label: str :param description: The description for the new Image. ...
[ "Creates", "a", "new", "Image", "from", "a", "disk", "you", "own", "." ]
python
train
31.5
nerdvegas/rez
src/rez/vendor/pydot/pydot.py
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pydot/pydot.py#L974-L1019
def to_string(self): """Returns a string representation of the edge in dot language. """ src = self.parse_node_ref( self.get_source() ) dst = self.parse_node_ref( self.get_destination() ) if isinstance(src, frozendict): edge = [ Subgraph(obj_dict=src).to_str...
[ "def", "to_string", "(", "self", ")", ":", "src", "=", "self", ".", "parse_node_ref", "(", "self", ".", "get_source", "(", ")", ")", "dst", "=", "self", ".", "parse_node_ref", "(", "self", ".", "get_destination", "(", ")", ")", "if", "isinstance", "(",...
Returns a string representation of the edge in dot language.
[ "Returns", "a", "string", "representation", "of", "the", "edge", "in", "dot", "language", "." ]
python
train
29.586957
nugget/python-insteonplm
insteonplm/tools.py
https://github.com/nugget/python-insteonplm/blob/65548041f1b0729ae1ae904443dd81b0c6cbf1bf/insteonplm/tools.py#L311-L316
def add_device_override(self, addr, cat, subcat, firmware=None): """Add a device override to the PLM.""" self.plm.devices.add_override(addr, 'cat', cat) self.plm.devices.add_override(addr, 'subcat', subcat) if firmware: self.plm.devices.add_override(addr, 'firmware', firmware...
[ "def", "add_device_override", "(", "self", ",", "addr", ",", "cat", ",", "subcat", ",", "firmware", "=", "None", ")", ":", "self", ".", "plm", ".", "devices", ".", "add_override", "(", "addr", ",", "'cat'", ",", "cat", ")", "self", ".", "plm", ".", ...
Add a device override to the PLM.
[ "Add", "a", "device", "override", "to", "the", "PLM", "." ]
python
train
52.666667
ralphje/imagemounter
imagemounter/volume.py
https://github.com/ralphje/imagemounter/blob/86213781c366cad65096447d91f522f0a3fb4b93/imagemounter/volume.py#L274-L285
def get_safe_label(self): """Returns a label that is safe to add to a path in the mountpoint for this volume.""" if self.info.get('label') == '/': return 'root' suffix = re.sub(r"[/ \(\)]+", "_", self.info.get('label')) if self.info.get('label') else "" if suffix and suffix...
[ "def", "get_safe_label", "(", "self", ")", ":", "if", "self", ".", "info", ".", "get", "(", "'label'", ")", "==", "'/'", ":", "return", "'root'", "suffix", "=", "re", ".", "sub", "(", "r\"[/ \\(\\)]+\"", ",", "\"_\"", ",", "self", ".", "info", ".", ...
Returns a label that is safe to add to a path in the mountpoint for this volume.
[ "Returns", "a", "label", "that", "is", "safe", "to", "add", "to", "a", "path", "in", "the", "mountpoint", "for", "this", "volume", "." ]
python
train
38.083333
mdickinson/refcycle
refcycle/creators.py
https://github.com/mdickinson/refcycle/blob/627fad74c74efc601209c96405f8118cd99b2241/refcycle/creators.py#L79-L99
def objects_reachable_from(obj): """ Return graph of objects reachable from *obj* via ``gc.get_referrers``. Returns an :class:`~refcycle.object_graph.ObjectGraph` object holding all objects reachable from the given one by following the output of ``gc.get_referrers``. Note that unlike the :func...
[ "def", "objects_reachable_from", "(", "obj", ")", ":", "# Depth-first search.", "found", "=", "ObjectGraph", ".", "vertex_set", "(", ")", "to_process", "=", "[", "obj", "]", "while", "to_process", ":", "obj", "=", "to_process", ".", "pop", "(", ")", "found",...
Return graph of objects reachable from *obj* via ``gc.get_referrers``. Returns an :class:`~refcycle.object_graph.ObjectGraph` object holding all objects reachable from the given one by following the output of ``gc.get_referrers``. Note that unlike the :func:`~refcycle.creators.snapshot` function, the ...
[ "Return", "graph", "of", "objects", "reachable", "from", "*", "obj", "*", "via", "gc", ".", "get_referrers", "." ]
python
train
34.619048
closeio/tasktiger
tasktiger/redis_scripts.py
https://github.com/closeio/tasktiger/blob/59f893152d6eb4b7f1f62fc4b35aeeca7f26c07a/tasktiger/redis_scripts.py#L339-L423
def zpoppush(self, source, destination, count, score, new_score, client=None, withscores=False, on_success=None, if_exists=None): """ Pops the first ``count`` members from the ZSET ``source`` and adds them to the ZSET ``destination`` with a score of ``new_score`...
[ "def", "zpoppush", "(", "self", ",", "source", ",", "destination", ",", "count", ",", "score", ",", "new_score", ",", "client", "=", "None", ",", "withscores", "=", "False", ",", "on_success", "=", "None", ",", "if_exists", "=", "None", ")", ":", "if",...
Pops the first ``count`` members from the ZSET ``source`` and adds them to the ZSET ``destination`` with a score of ``new_score``. If ``score`` is not None, only members up to a score of ``score`` are used. Returns the members that were moved and, if ``withscores`` is True, their origina...
[ "Pops", "the", "first", "count", "members", "from", "the", "ZSET", "source", "and", "adds", "them", "to", "the", "ZSET", "destination", "with", "a", "score", "of", "new_score", ".", "If", "score", "is", "not", "None", "only", "members", "up", "to", "a", ...
python
train
49.588235
robmarkcole/HASS-data-detective
detective/config.py
https://github.com/robmarkcole/HASS-data-detective/blob/f67dfde9dd63a3af411944d1857b0835632617c5/detective/config.py#L89-L101
def load_yaml(fname): """Load a YAML file.""" yaml = YAML(typ="safe") # Compat with HASS yaml.allow_duplicate_keys = True # Stub HASS constructors HassSafeConstructor.name = fname yaml.Constructor = HassSafeConstructor with open(fname, encoding="utf-8") as conf_file: # If config...
[ "def", "load_yaml", "(", "fname", ")", ":", "yaml", "=", "YAML", "(", "typ", "=", "\"safe\"", ")", "# Compat with HASS", "yaml", ".", "allow_duplicate_keys", "=", "True", "# Stub HASS constructors", "HassSafeConstructor", ".", "name", "=", "fname", "yaml", ".", ...
Load a YAML file.
[ "Load", "a", "YAML", "file", "." ]
python
train
33.230769
QUANTAXIS/QUANTAXIS
QUANTAXIS/QAFetch/QATdx.py
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QATdx.py#L1258-L1282
def QA_fetch_get_globalfuture_list(ip=None, port=None): """[summary] Keyword Arguments: ip {[type]} -- [description] (default: {None}) port {[type]} -- [description] (default: {None}) 14 3 伦敦金属 LM 15 3 伦敦石油 IP 16 3 纽约商...
[ "def", "QA_fetch_get_globalfuture_list", "(", "ip", "=", "None", ",", "port", "=", "None", ")", ":", "global", "extension_market_list", "extension_market_list", "=", "QA_fetch_get_extensionmarket_list", "(", ")", "if", "extension_market_list", "is", "None", "else", "e...
[summary] Keyword Arguments: ip {[type]} -- [description] (default: {None}) port {[type]} -- [description] (default: {None}) 14 3 伦敦金属 LM 15 3 伦敦石油 IP 16 3 纽约商品 CO 17 3 纽约石油 NY 18...
[ "[", "summary", "]" ]
python
train
36.04
RudolfCardinal/pythonlib
cardinal_pythonlib/ui.py
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/ui.py#L44-L53
def ask_user(prompt: str, default: str = None) -> Optional[str]: """ Prompts the user, with a default. Returns user input from ``stdin``. """ if default is None: prompt += ": " else: prompt += " [" + default + "]: " result = input(prompt) return result if len(result) > 0 else...
[ "def", "ask_user", "(", "prompt", ":", "str", ",", "default", ":", "str", "=", "None", ")", "->", "Optional", "[", "str", "]", ":", "if", "default", "is", "None", ":", "prompt", "+=", "\": \"", "else", ":", "prompt", "+=", "\" [\"", "+", "default", ...
Prompts the user, with a default. Returns user input from ``stdin``.
[ "Prompts", "the", "user", "with", "a", "default", ".", "Returns", "user", "input", "from", "stdin", "." ]
python
train
31.9
noahbenson/pimms
pimms/util.py
https://github.com/noahbenson/pimms/blob/9051b86d6b858a7a13511b72c48dc21bc903dab2/pimms/util.py#L533-L542
def is_real(arg): ''' is_real(x) yields True if x is a non-complex numeric object and False otherwise. Note that is_real(i) will yield True for an integer or bool i; to check for floating-point representations of numbers, use is_array(x, numpy.floating) or similar. ''' return (is_real(mag(arg))...
[ "def", "is_real", "(", "arg", ")", ":", "return", "(", "is_real", "(", "mag", "(", "arg", ")", ")", "if", "is_quantity", "(", "arg", ")", "else", "True", "if", "isinstance", "(", "arg", ",", "float", ")", "else", "is_npscalar", "(", "arg", ",", "'r...
is_real(x) yields True if x is a non-complex numeric object and False otherwise. Note that is_real(i) will yield True for an integer or bool i; to check for floating-point representations of numbers, use is_array(x, numpy.floating) or similar.
[ "is_real", "(", "x", ")", "yields", "True", "if", "x", "is", "a", "non", "-", "complex", "numeric", "object", "and", "False", "otherwise", "." ]
python
train
46.8
rdireen/spherepy
spherepy/spherepy.py
https://github.com/rdireen/spherepy/blob/241521401d4d76851d4a1a564a365cfab8e98496/spherepy/spherepy.py#L542-L562
def _scalar_coef_op_left(func): """decorator for operator overloading when ScalarCoef is on the left""" @wraps(func) def verif(self, scoef): if isinstance(scoef, ScalarCoefs): if len(self._vec) == len(scoef._vec): return ScalarCoefs(...
[ "def", "_scalar_coef_op_left", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "verif", "(", "self", ",", "scoef", ")", ":", "if", "isinstance", "(", "scoef", ",", "ScalarCoefs", ")", ":", "if", "len", "(", "self", ".", "_vec", ")", "...
decorator for operator overloading when ScalarCoef is on the left
[ "decorator", "for", "operator", "overloading", "when", "ScalarCoef", "is", "on", "the", "left" ]
python
train
44.52381
saltstack/salt
salt/cloud/clouds/proxmox.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/proxmox.py#L292-L316
def get_resources_nodes(call=None, resFilter=None): ''' Retrieve all hypervisors (nodes) available on this environment CLI Example: .. code-block:: bash salt-cloud -f get_resources_nodes my-proxmox-config ''' log.debug('Getting resource: nodes.. (filter: %s)', resFilter) resources ...
[ "def", "get_resources_nodes", "(", "call", "=", "None", ",", "resFilter", "=", "None", ")", ":", "log", ".", "debug", "(", "'Getting resource: nodes.. (filter: %s)'", ",", "resFilter", ")", "resources", "=", "query", "(", "'get'", ",", "'cluster/resources'", ")"...
Retrieve all hypervisors (nodes) available on this environment CLI Example: .. code-block:: bash salt-cloud -f get_resources_nodes my-proxmox-config
[ "Retrieve", "all", "hypervisors", "(", "nodes", ")", "available", "on", "this", "environment", "CLI", "Example", ":" ]
python
train
30.6
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/encoder.py
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/encoder.py#L645-L679
def BoolEncoder(field_number, is_repeated, is_packed): """Returns an encoder for a boolean field.""" false_byte = b'\x00' true_byte = b'\x01' if is_packed: tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED) local_EncodeVarint = _EncodeVarint def EncodePackedField(write, value...
[ "def", "BoolEncoder", "(", "field_number", ",", "is_repeated", ",", "is_packed", ")", ":", "false_byte", "=", "b'\\x00'", "true_byte", "=", "b'\\x01'", "if", "is_packed", ":", "tag_bytes", "=", "TagBytes", "(", "field_number", ",", "wire_format", ".", "WIRETYPE_...
Returns an encoder for a boolean field.
[ "Returns", "an", "encoder", "for", "a", "boolean", "field", "." ]
python
train
29.742857
collectiveacuity/labPack
labpack/storage/aws/s3.py
https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/storage/aws/s3.py#L1398-L1488
def export_records(self, bucket_name, export_path='', overwrite=True): ''' a method to export all the records from a bucket to local files :param bucket_name: string with name of bucket :param export_path: [optional] string with path to root directory for record dump :param...
[ "def", "export_records", "(", "self", ",", "bucket_name", ",", "export_path", "=", "''", ",", "overwrite", "=", "True", ")", ":", "title", "=", "'%s.export_records'", "%", "self", ".", "__class__", ".", "__name__", "# validate inputs", "input_fields", "=", "{"...
a method to export all the records from a bucket to local files :param bucket_name: string with name of bucket :param export_path: [optional] string with path to root directory for record dump :param overwrite: [optional] boolean to overwrite existing files matching records :return: Tru...
[ "a", "method", "to", "export", "all", "the", "records", "from", "a", "bucket", "to", "local", "files" ]
python
train
42.56044
gccxml/pygccxml
pygccxml/declarations/calldef.py
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/calldef.py#L333-L341
def calling_convention(self): """function calling convention. See :class:CALLING_CONVENTION_TYPES class for possible values""" if self._calling_convention is None: self._calling_convention = \ calldef_types.CALLING_CONVENTION_TYPES.extract(self.attributes) ...
[ "def", "calling_convention", "(", "self", ")", ":", "if", "self", ".", "_calling_convention", "is", "None", ":", "self", ".", "_calling_convention", "=", "calldef_types", ".", "CALLING_CONVENTION_TYPES", ".", "extract", "(", "self", ".", "attributes", ")", "if",...
function calling convention. See :class:CALLING_CONVENTION_TYPES class for possible values
[ "function", "calling", "convention", ".", "See", ":", "class", ":", "CALLING_CONVENTION_TYPES", "class", "for", "possible", "values" ]
python
train
51.555556
openai/universe
universe/rewarder/merge.py
https://github.com/openai/universe/blob/cc9ce6ec241821bfb0f3b85dd455bd36e4ee7a8c/universe/rewarder/merge.py#L4-L28
def merge_infos(info1, info2): """We often need to aggregate together multiple infos. Most keys can just be clobbered by the new info, but e.g. any keys which contain counts should be added. The merge schema is indicated by the key namespace. Namespaces: - stats.timers: Timing - stats.gaug...
[ "def", "merge_infos", "(", "info1", ",", "info2", ")", ":", "for", "key", ",", "value", "in", "six", ".", "iteritems", "(", "info2", ")", ":", "if", "key", "in", "info1", "and", "key", ".", "startswith", "(", "'stats'", ")", ":", "if", "key", ".", ...
We often need to aggregate together multiple infos. Most keys can just be clobbered by the new info, but e.g. any keys which contain counts should be added. The merge schema is indicated by the key namespace. Namespaces: - stats.timers: Timing - stats.gauges: Gauge values - stats.*: Counts...
[ "We", "often", "need", "to", "aggregate", "together", "multiple", "infos", ".", "Most", "keys", "can", "just", "be", "clobbered", "by", "the", "new", "info", "but", "e", ".", "g", ".", "any", "keys", "which", "contain", "counts", "should", "be", "added",...
python
train
31.72
classam/silly
silly/main.py
https://github.com/classam/silly/blob/f3202e997d5ebc9e4f98370b08665fd1178a9556/silly/main.py#L691-L730
def datetime(past=True, random=random): """ Returns a random datetime from the past... or the future! >>> mock_random.seed(0) >>> datetime(random=mock_random).isoformat() '1950-02-03T03:04:05' """ def year(): if past: return random.choice(range(1950,2005)) else...
[ "def", "datetime", "(", "past", "=", "True", ",", "random", "=", "random", ")", ":", "def", "year", "(", ")", ":", "if", "past", ":", "return", "random", ".", "choice", "(", "range", "(", "1950", ",", "2005", ")", ")", "else", ":", "return", "_da...
Returns a random datetime from the past... or the future! >>> mock_random.seed(0) >>> datetime(random=mock_random).isoformat() '1950-02-03T03:04:05'
[ "Returns", "a", "random", "datetime", "from", "the", "past", "...", "or", "the", "future!" ]
python
train
25.45
blockstack/zone-file-py
blockstack_zones/parse_zone_file.py
https://github.com/blockstack/zone-file-py/blob/c1078c8c3c28f0881bc9a3af53d4972c4a6862d0/blockstack_zones/parse_zone_file.py#L60-L94
def make_parser(): """ Make an ArgumentParser that accepts DNS RRs """ line_parser = ZonefileLineParser() subparsers = line_parser.add_subparsers() # parse $ORIGIN sp = subparsers.add_parser("$ORIGIN") sp.add_argument("$ORIGIN", type=str) # parse $TTL sp = subparsers.add_parser...
[ "def", "make_parser", "(", ")", ":", "line_parser", "=", "ZonefileLineParser", "(", ")", "subparsers", "=", "line_parser", ".", "add_subparsers", "(", ")", "# parse $ORIGIN", "sp", "=", "subparsers", ".", "add_parser", "(", "\"$ORIGIN\"", ")", "sp", ".", "add_...
Make an ArgumentParser that accepts DNS RRs
[ "Make", "an", "ArgumentParser", "that", "accepts", "DNS", "RRs" ]
python
test
37.771429
Rediker-Software/doac
doac/decorators.py
https://github.com/Rediker-Software/doac/blob/398fdd64452e4ff8662297b0381926addd77505a/doac/decorators.py#L7-L77
def scope_required(*scopes): """ Test for specific scopes that the access token has been authenticated for before processing the request and eventual response. The scopes that are passed in determine how the decorator will respond to incoming requests: - If no scopes are passed in the argument...
[ "def", "scope_required", "(", "*", "scopes", ")", ":", "def", "decorator", "(", "view_func", ")", ":", "@", "wraps", "(", "view_func", ",", "assigned", "=", "available_attrs", "(", "view_func", ")", ")", "def", "_wrapped_view", "(", "request", ",", "*", ...
Test for specific scopes that the access token has been authenticated for before processing the request and eventual response. The scopes that are passed in determine how the decorator will respond to incoming requests: - If no scopes are passed in the arguments, the decorator will test for any availa...
[ "Test", "for", "specific", "scopes", "that", "the", "access", "token", "has", "been", "authenticated", "for", "before", "processing", "the", "request", "and", "eventual", "response", "." ]
python
train
39.056338
mattja/nsim
nsim/timeseries.py
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/timeseries.py#L119-L155
def add_analyses(cls, source): """Dynamically add new analysis methods to the Timeseries class. Args: source: Can be a function, module or the filename of a python file. If a filename or a module is given, then all functions defined inside not starting with _ will be a...
[ "def", "add_analyses", "(", "cls", ",", "source", ")", ":", "if", "isinstance", "(", "source", ",", "types", ".", "FunctionType", ")", ":", "_add_single_method", "(", "source", ".", "__name__", ",", "source", ")", "else", ":", "if", "isinstance", "(", "s...
Dynamically add new analysis methods to the Timeseries class. Args: source: Can be a function, module or the filename of a python file. If a filename or a module is given, then all functions defined inside not starting with _ will be added as methods. The only restric...
[ "Dynamically", "add", "new", "analysis", "methods", "to", "the", "Timeseries", "class", ".", "Args", ":", "source", ":", "Can", "be", "a", "function", "module", "or", "the", "filename", "of", "a", "python", "file", ".", "If", "a", "filename", "or", "a", ...
python
train
50
mushkevych/scheduler
synergy/system/decorator.py
https://github.com/mushkevych/scheduler/blob/6740331360f49083c208085fb5a60ce80ebf418b/synergy/system/decorator.py#L9-L29
def thread_safe(method): """ wraps method with lock acquire/release cycle decorator requires class instance to have field self.lock of type threading.Lock or threading.RLock """ @functools.wraps(method) def _locker(self, *args, **kwargs): assert hasattr(self, 'lock'), \ 'thread_saf...
[ "def", "thread_safe", "(", "method", ")", ":", "@", "functools", ".", "wraps", "(", "method", ")", "def", "_locker", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "assert", "hasattr", "(", "self", ",", "'lock'", ")", ",", "'thre...
wraps method with lock acquire/release cycle decorator requires class instance to have field self.lock of type threading.Lock or threading.RLock
[ "wraps", "method", "with", "lock", "acquire", "/", "release", "cycle", "decorator", "requires", "class", "instance", "to", "have", "field", "self", ".", "lock", "of", "type", "threading", ".", "Lock", "or", "threading", ".", "RLock" ]
python
train
37.809524
chrisnorman7/confmanager
confmanager/confframe.py
https://github.com/chrisnorman7/confmanager/blob/54a3ce0b596f9da32ae82fd4ff4cb46bb1cf23b1/confmanager/confframe.py#L55-L78
def apply(self, event = None): """Before self.onOk closes the window, it calls this function to sync the config changes from the GUI back to self.config.""" for section in self.config.sections(): # Run through the sections to check all the option values: for option, o in self.config.config[section].items(...
[ "def", "apply", "(", "self", ",", "event", "=", "None", ")", ":", "for", "section", "in", "self", ".", "config", ".", "sections", "(", ")", ":", "# Run through the sections to check all the option values:\r", "for", "option", ",", "o", "in", "self", ".", "co...
Before self.onOk closes the window, it calls this function to sync the config changes from the GUI back to self.config.
[ "Before", "self", ".", "onOk", "closes", "the", "window", "it", "calls", "this", "function", "to", "sync", "the", "config", "changes", "from", "the", "GUI", "back", "to", "self", ".", "config", "." ]
python
train
51.875
pavlov99/jsonapi
jsonapi/api.py
https://github.com/pavlov99/jsonapi/blob/c27943f22f1f1d30d651fe267a99d2b38f69d604/jsonapi/api.py#L258-L312
def handler_view(self, request, resource_name, ids=None): """ Handler for resources. .. versionadded:: 0.5.7 Content-Type check :return django.http.HttpResponse """ signal_request.send(sender=self, request=request) time_start = time.time() self.upda...
[ "def", "handler_view", "(", "self", ",", "request", ",", "resource_name", ",", "ids", "=", "None", ")", ":", "signal_request", ".", "send", "(", "sender", "=", "self", ",", "request", "=", "request", ")", "time_start", "=", "time", ".", "time", "(", ")...
Handler for resources. .. versionadded:: 0.5.7 Content-Type check :return django.http.HttpResponse
[ "Handler", "for", "resources", "." ]
python
train
41.036364
saltstack/salt
salt/pillar/nsot.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/nsot.py#L123-L147
def _query_nsot(url, headers, device=None): ''' if a device is given, query nsot for that specific device, otherwise return all devices :param url: str :param headers: dict :param device: None or str :return: ''' url = urlparse.urljoin(url, 'devices') ret = {} if not device:...
[ "def", "_query_nsot", "(", "url", ",", "headers", ",", "device", "=", "None", ")", ":", "url", "=", "urlparse", ".", "urljoin", "(", "url", ",", "'devices'", ")", "ret", "=", "{", "}", "if", "not", "device", ":", "query", "=", "salt", ".", "utils",...
if a device is given, query nsot for that specific device, otherwise return all devices :param url: str :param headers: dict :param device: None or str :return:
[ "if", "a", "device", "is", "given", "query", "nsot", "for", "that", "specific", "device", "otherwise", "return", "all", "devices" ]
python
train
28.48
ScatterHQ/machinist
machinist/_fsm.py
https://github.com/ScatterHQ/machinist/blob/1d1c017ac03be8e737d50af0dfabf31722ddc621/machinist/_fsm.py#L389-L407
def trivialInput(symbol): """ Create a new L{IRichInput} implementation for the given input symbol. This creates a new type object and is intended to be used at module scope to define rich input types. Generally, only one use per symbol should be required. For example:: Apple = trivialIn...
[ "def", "trivialInput", "(", "symbol", ")", ":", "return", "implementer", "(", "IRichInput", ")", "(", "type", "(", "symbol", ".", "name", ".", "title", "(", ")", ",", "(", "FancyStrMixin", ",", "object", ")", ",", "{", "\"symbol\"", ":", "_symbol", "("...
Create a new L{IRichInput} implementation for the given input symbol. This creates a new type object and is intended to be used at module scope to define rich input types. Generally, only one use per symbol should be required. For example:: Apple = trivialInput(Fruit.apple) @param symbol: A...
[ "Create", "a", "new", "L", "{", "IRichInput", "}", "implementation", "for", "the", "given", "input", "symbol", "." ]
python
train
34.631579
pypyr/pypyr-cli
pypyr/dsl.py
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/dsl.py#L253-L283
def foreach_loop(self, context): """Run step once for each item in foreach_items. On each iteration, the invoked step can use context['i'] to get the current iterator value. Args: context: (pypyr.context.Context) The pypyr context. This arg will mutate....
[ "def", "foreach_loop", "(", "self", ",", "context", ")", ":", "logger", ".", "debug", "(", "\"starting\"", ")", "# Loop decorators only evaluated once, not for every step repeat", "# execution.", "foreach", "=", "context", ".", "get_formatted_iterable", "(", "self", "."...
Run step once for each item in foreach_items. On each iteration, the invoked step can use context['i'] to get the current iterator value. Args: context: (pypyr.context.Context) The pypyr context. This arg will mutate.
[ "Run", "step", "once", "for", "each", "item", "in", "foreach_items", "." ]
python
train
36.516129
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/pymavlink/mavextra.py
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/mavextra.py#L724-L745
def mixer(servo1, servo2, mixtype=1, gain=0.5): '''mix two servos''' s1 = servo1 - 1500 s2 = servo2 - 1500 v1 = (s1-s2)*gain v2 = (s1+s2)*gain if mixtype == 2: v2 = -v2 elif mixtype == 3: v1 = -v1 elif mixtype == 4: v1 = -v1 v2 = -v2 if v1 > 600: ...
[ "def", "mixer", "(", "servo1", ",", "servo2", ",", "mixtype", "=", "1", ",", "gain", "=", "0.5", ")", ":", "s1", "=", "servo1", "-", "1500", "s2", "=", "servo2", "-", "1500", "v1", "=", "(", "s1", "-", "s2", ")", "*", "gain", "v2", "=", "(", ...
mix two servos
[ "mix", "two", "servos" ]
python
train
20.409091
bxlab/bx-python
lib/bx_extras/stats.py
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/stats.py#L837-L858
def lspearmanr(x,y): """ Calculates a Spearman rank-order correlation coefficient. Taken from Heiman's Basic Statistics for the Behav. Sci (1st), p.192. Usage: lspearmanr(x,y) where x and y are equal-length lists Returns: Spearman's r, two-tailed p-value """ TINY = 1e-30 if len(x) != len(y): ...
[ "def", "lspearmanr", "(", "x", ",", "y", ")", ":", "TINY", "=", "1e-30", "if", "len", "(", "x", ")", "!=", "len", "(", "y", ")", ":", "raise", "ValueError", "(", "'Input values not paired in spearmanr. Aborting.'", ")", "n", "=", "len", "(", "x", ")",...
Calculates a Spearman rank-order correlation coefficient. Taken from Heiman's Basic Statistics for the Behav. Sci (1st), p.192. Usage: lspearmanr(x,y) where x and y are equal-length lists Returns: Spearman's r, two-tailed p-value
[ "Calculates", "a", "Spearman", "rank", "-", "order", "correlation", "coefficient", ".", "Taken", "from", "Heiman", "s", "Basic", "Statistics", "for", "the", "Behav", ".", "Sci", "(", "1st", ")", "p", ".", "192", "." ]
python
train
36.681818
BBVA/patton-cli
patton_client/model.py
https://github.com/BBVA/patton-cli/blob/b31d9a134158d4c15eeeefde305f193d3f01a2de/patton_client/model.py#L173-L206
def dump(self): """Dump to file""" # NO Dump file selected -> DO NOTHING if self.running_config.output_file: # Determinate file format _, extension = op.splitext(self.running_config.output_file) extension = extension.replace(".", "") if extensio...
[ "def", "dump", "(", "self", ")", ":", "# NO Dump file selected -> DO NOTHING", "if", "self", ".", "running_config", ".", "output_file", ":", "# Determinate file format", "_", ",", "extension", "=", "op", ".", "splitext", "(", "self", ".", "running_config", ".", ...
Dump to file
[ "Dump", "to", "file" ]
python
train
37.852941
johnbywater/eventsourcing
eventsourcing/infrastructure/base.py
https://github.com/johnbywater/eventsourcing/blob/de2c22c653fdccf2f5ee96faea74453ff1847e42/eventsourcing/infrastructure/base.py#L112-L117
def from_record(self, record): """ Constructs and returns a sequenced item object, from given ORM object. """ kwargs = self.get_field_kwargs(record) return self.sequenced_item_class(**kwargs)
[ "def", "from_record", "(", "self", ",", "record", ")", ":", "kwargs", "=", "self", ".", "get_field_kwargs", "(", "record", ")", "return", "self", ".", "sequenced_item_class", "(", "*", "*", "kwargs", ")" ]
Constructs and returns a sequenced item object, from given ORM object.
[ "Constructs", "and", "returns", "a", "sequenced", "item", "object", "from", "given", "ORM", "object", "." ]
python
train
37.666667