repo
stringlengths
7
54
path
stringlengths
4
192
url
stringlengths
87
284
code
stringlengths
78
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
jay-johnson/network-pipeline
network_pipeline/record_packets_to_csv.py
https://github.com/jay-johnson/network-pipeline/blob/4e53ae13fe12085e0cf2e5e1aff947368f4f1ffa/network_pipeline/record_packets_to_csv.py#L713-L724
def write_to_file(self, data_dict, output_file_path): """write_to_file :param data_dict: :param output_file_path: """ log.info("saving={}".format(output_file_path)) with open(output_file_path, "w") as output_file: ...
[ "def", "write_to_file", "(", "self", ",", "data_dict", ",", "output_file_path", ")", ":", "log", ".", "info", "(", "\"saving={}\"", ".", "format", "(", "output_file_path", ")", ")", "with", "open", "(", "output_file_path", ",", "\"w\"", ")", "as", "output_fi...
write_to_file :param data_dict: :param output_file_path:
[ "write_to_file" ]
python
train
pyvisa/pyvisa
pyvisa/ctwrapper/functions.py
https://github.com/pyvisa/pyvisa/blob/b8b2d4371e1f00782856aa9176ff1ced6bcb3798/pyvisa/ctwrapper/functions.py#L1637-L1649
def set_attribute(library, session, attribute, attribute_state): """Sets the state of an attribute. Corresponds to viSetAttribute function of the VISA library. :param library: the visa library wrapped by ctypes. :param session: Unique logical identifier to a session. :param attribute: Attribute fo...
[ "def", "set_attribute", "(", "library", ",", "session", ",", "attribute", ",", "attribute_state", ")", ":", "return", "library", ".", "viSetAttribute", "(", "session", ",", "attribute", ",", "attribute_state", ")" ]
Sets the state of an attribute. Corresponds to viSetAttribute function of the VISA library. :param library: the visa library wrapped by ctypes. :param session: Unique logical identifier to a session. :param attribute: Attribute for which the state is to be modified. (Attributes.*) :param attribute...
[ "Sets", "the", "state", "of", "an", "attribute", "." ]
python
train
ianmiell/shutit
shutit_class.py
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L3338-L3379
def print_config(self, cfg, hide_password=True, history=False, module_id=None): """Returns a string representing the config of this ShutIt run. """ shutit_global.shutit_global_object.yield_to_draw() cp = self.config_parser s = '' keys1 = list(cfg.keys()) if keys1: keys1.sort() for k in keys1: if m...
[ "def", "print_config", "(", "self", ",", "cfg", ",", "hide_password", "=", "True", ",", "history", "=", "False", ",", "module_id", "=", "None", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "cp", "=", "self", ".", ...
Returns a string representing the config of this ShutIt run.
[ "Returns", "a", "string", "representing", "the", "config", "of", "this", "ShutIt", "run", "." ]
python
train
xflr6/bitsets
bitsets/transform.py
https://github.com/xflr6/bitsets/blob/ddcfe17e7c7a11f71f1c6764b2cecf7db05d9cdf/bitsets/transform.py#L69-L90
def unpack(n, r=32): """Yield r > 0 bit-length integers splitting n into chunks. >>> list(unpack(42, 1)) [0, 1, 0, 1, 0, 1] >>> list(unpack(256, 8)) [0, 1] >>> list(unpack(2, 0)) Traceback (most recent call last): ... ValueError: unpack needs r > 0 """ if r < 1: ...
[ "def", "unpack", "(", "n", ",", "r", "=", "32", ")", ":", "if", "r", "<", "1", ":", "raise", "ValueError", "(", "'unpack needs r > 0'", ")", "mask", "=", "(", "1", "<<", "r", ")", "-", "1", "while", "n", ":", "yield", "n", "&", "mask", "n", "...
Yield r > 0 bit-length integers splitting n into chunks. >>> list(unpack(42, 1)) [0, 1, 0, 1, 0, 1] >>> list(unpack(256, 8)) [0, 1] >>> list(unpack(2, 0)) Traceback (most recent call last): ... ValueError: unpack needs r > 0
[ "Yield", "r", ">", "0", "bit", "-", "length", "integers", "splitting", "n", "into", "chunks", "." ]
python
train
pdkit/pdkit
pdkit/gait_processor.py
https://github.com/pdkit/pdkit/blob/c7120263da2071bb139815fbdb56ca77b544f340/pdkit/gait_processor.py#L120-L175
def freeze_of_gait(self, x): """ This method assess freeze of gait following :cite:`g-BachlinPRMHGT10`. :param x: The time series to assess freeze of gait on. This could be x, y, z or mag_sum_acc. :type x: pandas.Series :return freeze_time: What times do freeze ...
[ "def", "freeze_of_gait", "(", "self", ",", "x", ")", ":", "data", "=", "self", ".", "resample_signal", "(", "x", ")", ".", "values", "f_res", "=", "self", ".", "sampling_frequency", "/", "self", ".", "window", "f_nr_LBs", "=", "int", "(", "self", ".", ...
This method assess freeze of gait following :cite:`g-BachlinPRMHGT10`. :param x: The time series to assess freeze of gait on. This could be x, y, z or mag_sum_acc. :type x: pandas.Series :return freeze_time: What times do freeze of gait events occur. [measured in time (h:m:s)] ...
[ "This", "method", "assess", "freeze", "of", "gait", "following", ":", "cite", ":", "g", "-", "BachlinPRMHGT10", "." ]
python
train
payplug/payplug-python
payplug/resources.py
https://github.com/payplug/payplug-python/blob/42dec9d6bff420dd0c26e51a84dd000adff04331/payplug/resources.py#L81-L91
def _initialize(self, **resource_attributes): """ Initialize a resource. Default behavior is just to set all the attributes. You may want to override this. :param resource_attributes: The resource attributes """ self._set_attributes(**resource_attributes) for att...
[ "def", "_initialize", "(", "self", ",", "*", "*", "resource_attributes", ")", ":", "self", ".", "_set_attributes", "(", "*", "*", "resource_attributes", ")", "for", "attribute", ",", "attribute_type", "in", "list", "(", "self", ".", "_mapper", ".", "items", ...
Initialize a resource. Default behavior is just to set all the attributes. You may want to override this. :param resource_attributes: The resource attributes
[ "Initialize", "a", "resource", ".", "Default", "behavior", "is", "just", "to", "set", "all", "the", "attributes", ".", "You", "may", "want", "to", "override", "this", "." ]
python
train
brainiak/brainiak
brainiak/utils/utils.py
https://github.com/brainiak/brainiak/blob/408f12dec2ff56559a26873a848a09e4c8facfeb/brainiak/utils/utils.py#L697-L777
def phase_randomize(data, voxelwise=False, random_state=None): """Randomize phase of time series across subjects For each subject, apply Fourier transform to voxel time series and then randomly shift the phase of each frequency before inverting back into the time domain. This yields time series with th...
[ "def", "phase_randomize", "(", "data", ",", "voxelwise", "=", "False", ",", "random_state", "=", "None", ")", ":", "# Check if input is 2-dimensional", "data_ndim", "=", "data", ".", "ndim", "# Get basic shape of data", "data", ",", "n_TRs", ",", "n_voxels", ",", ...
Randomize phase of time series across subjects For each subject, apply Fourier transform to voxel time series and then randomly shift the phase of each frequency before inverting back into the time domain. This yields time series with the same power spectrum (and thus the same autocorrelation) as the o...
[ "Randomize", "phase", "of", "time", "series", "across", "subjects" ]
python
train
mabuchilab/QNET
src/qnet/algebra/_rules.py
https://github.com/mabuchilab/QNET/blob/cc20d26dad78691d34c67173e5cd67dcac94208a/src/qnet/algebra/_rules.py#L823-L864
def _get_common_block_structure(lhs_bs, rhs_bs): """For two block structures ``aa = (a1, a2, ..., an)``, ``bb = (b1, b2, ..., bm)`` generate the maximal common block structure so that every block from aa and bb is contained in exactly one block of the resulting structure. This is useful for determining...
[ "def", "_get_common_block_structure", "(", "lhs_bs", ",", "rhs_bs", ")", ":", "# for convenience the arguments may also be Circuit objects", "if", "isinstance", "(", "lhs_bs", ",", "Circuit", ")", ":", "lhs_bs", "=", "lhs_bs", ".", "block_structure", "if", "isinstance",...
For two block structures ``aa = (a1, a2, ..., an)``, ``bb = (b1, b2, ..., bm)`` generate the maximal common block structure so that every block from aa and bb is contained in exactly one block of the resulting structure. This is useful for determining how to apply the distributive law when feeding two ...
[ "For", "two", "block", "structures", "aa", "=", "(", "a1", "a2", "...", "an", ")", "bb", "=", "(", "b1", "b2", "...", "bm", ")", "generate", "the", "maximal", "common", "block", "structure", "so", "that", "every", "block", "from", "aa", "and", "bb", ...
python
train
F5Networks/f5-common-python
f5-sdk-dist/scripts/configure.py
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5-sdk-dist/scripts/configure.py#L122-L131
def export_to_json(env): """export_to_json This function takes in a dictionary object and stores it within the config.JSON file. """ json_fl = env['scripts'] + "/config.JSON" with open(json_fl, 'w') as fh: fh.write(json.dumps(env, sort_keys=True, indent=4, separators...
[ "def", "export_to_json", "(", "env", ")", ":", "json_fl", "=", "env", "[", "'scripts'", "]", "+", "\"/config.JSON\"", "with", "open", "(", "json_fl", ",", "'w'", ")", "as", "fh", ":", "fh", ".", "write", "(", "json", ".", "dumps", "(", "env", ",", ...
export_to_json This function takes in a dictionary object and stores it within the config.JSON file.
[ "export_to_json" ]
python
train
fredRos/pypmc
pypmc/sampler/importance_sampling.py
https://github.com/fredRos/pypmc/blob/9138b67c976f0d58edd080353d16769a47794d09/pypmc/sampler/importance_sampling.py#L158-L195
def run(self, N=1, trace_sort=False): '''Run the sampler, store the history of visited points into the member variable ``self.samples`` and the importance weights into ``self.weights``. .. seealso:: :py:class:`pypmc.tools.History` :param N: Integer; the...
[ "def", "run", "(", "self", ",", "N", "=", "1", ",", "trace_sort", "=", "False", ")", ":", "if", "N", "==", "0", ":", "return", "0", "if", "trace_sort", ":", "this_samples", ",", "origin", "=", "self", ".", "_get_samples", "(", "N", ",", "trace_sort...
Run the sampler, store the history of visited points into the member variable ``self.samples`` and the importance weights into ``self.weights``. .. seealso:: :py:class:`pypmc.tools.History` :param N: Integer; the number of samples to be drawn. :param t...
[ "Run", "the", "sampler", "store", "the", "history", "of", "visited", "points", "into", "the", "member", "variable", "self", ".", "samples", "and", "the", "importance", "weights", "into", "self", ".", "weights", "." ]
python
train
click-contrib/sphinx-click
sphinx_click/ext.py
https://github.com/click-contrib/sphinx-click/blob/ec76d15697ec80e51486a6e3daa0aec60b04870f/sphinx_click/ext.py#L294-L329
def _load_module(self, module_path): """Load the module.""" # __import__ will fail on unicode, # so we ensure module path is a string here. module_path = str(module_path) try: module_name, attr_name = module_path.split(':', 1) except ValueError: # noqa ...
[ "def", "_load_module", "(", "self", ",", "module_path", ")", ":", "# __import__ will fail on unicode,", "# so we ensure module path is a string here.", "module_path", "=", "str", "(", "module_path", ")", "try", ":", "module_name", ",", "attr_name", "=", "module_path", "...
Load the module.
[ "Load", "the", "module", "." ]
python
train
veripress/veripress
veripress/model/storages.py
https://github.com/veripress/veripress/blob/9e3df3a10eb1db32da596bf52118fe6acbe4b14a/veripress/model/storages.py#L451-L479
def get_pages(self, include_draft=False): """ Get all custom pages (supported formats, excluding other files like '.js', '.css', '.html'). :param include_draft: return draft page or not :return: an iterable of Page objects """ def pages_generator(pages_root_path...
[ "def", "get_pages", "(", "self", ",", "include_draft", "=", "False", ")", ":", "def", "pages_generator", "(", "pages_root_path", ")", ":", "for", "file_path", "in", "traverse_directory", "(", "pages_root_path", ",", "yield_dir", "=", "False", ")", ":", "rel_pa...
Get all custom pages (supported formats, excluding other files like '.js', '.css', '.html'). :param include_draft: return draft page or not :return: an iterable of Page objects
[ "Get", "all", "custom", "pages", "(", "supported", "formats", "excluding", "other", "files", "like", ".", "js", ".", "css", ".", "html", ")", "." ]
python
train
tensorflow/probability
tensorflow_probability/python/vi/csiszar_divergence.py
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/vi/csiszar_divergence.py#L462-L503
def t_power(logu, t, self_normalized=False, name=None): """The T-Power Csiszar-function in log-space. A Csiszar-function is a member of, ```none F = { f:R_+ to R : f convex }. ``` When `self_normalized = True` the T-Power Csiszar-function is: ```none f(u) = s [ u**t - 1 - t(u - 1) ] s = { -1 0 <...
[ "def", "t_power", "(", "logu", ",", "t", ",", "self_normalized", "=", "False", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "compat", ".", "v1", ".", "name_scope", "(", "name", ",", "\"t_power\"", ",", "[", "logu", ",", "t", "]", ")", "...
The T-Power Csiszar-function in log-space. A Csiszar-function is a member of, ```none F = { f:R_+ to R : f convex }. ``` When `self_normalized = True` the T-Power Csiszar-function is: ```none f(u) = s [ u**t - 1 - t(u - 1) ] s = { -1 0 < t < 1 { +1 otherwise ``` When `self_normalized ...
[ "The", "T", "-", "Power", "Csiszar", "-", "function", "in", "log", "-", "space", "." ]
python
test
respondcreate/django-versatileimagefield
versatileimagefield/versatileimagefield.py
https://github.com/respondcreate/django-versatileimagefield/blob/d41e279c39cccffafbe876c67596184704ae8877/versatileimagefield/versatileimagefield.py#L30-L122
def crop_on_centerpoint(self, image, width, height, ppoi=(0.5, 0.5)): """ Return a PIL Image instance cropped from `image`. Image has an aspect ratio provided by dividing `width` / `height`), sized down to `width`x`height`. Any 'excess pixels' are trimmed away in respect to the ...
[ "def", "crop_on_centerpoint", "(", "self", ",", "image", ",", "width", ",", "height", ",", "ppoi", "=", "(", "0.5", ",", "0.5", ")", ")", ":", "ppoi_x_axis", "=", "int", "(", "image", ".", "size", "[", "0", "]", "*", "ppoi", "[", "0", "]", ")", ...
Return a PIL Image instance cropped from `image`. Image has an aspect ratio provided by dividing `width` / `height`), sized down to `width`x`height`. Any 'excess pixels' are trimmed away in respect to the pixel of `image` that corresponds to `ppoi` (Primary Point of Interest). ...
[ "Return", "a", "PIL", "Image", "instance", "cropped", "from", "image", "." ]
python
test
bitesofcode/projexui
projexui/widgets/xorbcolumnedit/xorbcolumnedit.py
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbcolumnedit/xorbcolumnedit.py#L229-L238
def setValue( self, value ): """ Sets the value for this edit to the inputed value. :param value | <variant> """ if ( self._editor ): self._editor.setValue(value) return True return False
[ "def", "setValue", "(", "self", ",", "value", ")", ":", "if", "(", "self", ".", "_editor", ")", ":", "self", ".", "_editor", ".", "setValue", "(", "value", ")", "return", "True", "return", "False" ]
Sets the value for this edit to the inputed value. :param value | <variant>
[ "Sets", "the", "value", "for", "this", "edit", "to", "the", "inputed", "value", ".", ":", "param", "value", "|", "<variant", ">" ]
python
train
annoviko/pyclustering
pyclustering/utils/__init__.py
https://github.com/annoviko/pyclustering/blob/98aa0dd89fd36f701668fb1eb29c8fb5662bf7d0/pyclustering/utils/__init__.py#L976-L1018
def draw_dynamics_set(dynamics, xtitle = None, ytitle = None, xlim = None, ylim = None, xlabels = False, ylabels = False): """! @brief Draw lists of dynamics of neurons (oscillators) in the network. @param[in] dynamics (list): List of network outputs that are represented by values of output of osci...
[ "def", "draw_dynamics_set", "(", "dynamics", ",", "xtitle", "=", "None", ",", "ytitle", "=", "None", ",", "xlim", "=", "None", ",", "ylim", "=", "None", ",", "xlabels", "=", "False", ",", "ylabels", "=", "False", ")", ":", "# Calculate edge for confortable...
! @brief Draw lists of dynamics of neurons (oscillators) in the network. @param[in] dynamics (list): List of network outputs that are represented by values of output of oscillators (used by y axis). @param[in] xtitle (string): Title for Y. @param[in] ytitle (string): Title for X. @param[i...
[ "!" ]
python
valid
dps/simplescheduler
simplescheduler/cli.py
https://github.com/dps/simplescheduler/blob/d633549a8b78d5c1ff37419f4970835f1c6a5947/simplescheduler/cli.py#L24-L42
def main(): """ SimpleScheduler redis parameters will be read from environment variables: REDIS_HOST, REDIS_PORT, REDIS_DB, REDIS_KEY (password) """ args = parser.parse_args() scheduler = Scheduler() print 'Start %s' % scheduler.scheduler_id scheduler.interval = args.interval if ar...
[ "def", "main", "(", ")", ":", "args", "=", "parser", ".", "parse_args", "(", ")", "scheduler", "=", "Scheduler", "(", ")", "print", "'Start %s'", "%", "scheduler", ".", "scheduler_id", "scheduler", ".", "interval", "=", "args", ".", "interval", "if", "ar...
SimpleScheduler redis parameters will be read from environment variables: REDIS_HOST, REDIS_PORT, REDIS_DB, REDIS_KEY (password)
[ "SimpleScheduler", "redis", "parameters", "will", "be", "read", "from", "environment", "variables", ":", "REDIS_HOST", "REDIS_PORT", "REDIS_DB", "REDIS_KEY", "(", "password", ")" ]
python
train
NaturalHistoryMuseum/pylibdmtx
pylibdmtx/pylibdmtx.py
https://github.com/NaturalHistoryMuseum/pylibdmtx/blob/a425ec36050500af4875bf94eda02feb26ea62ad/pylibdmtx/pylibdmtx.py#L109-L125
def _region(decoder, timeout): """A context manager for `DmtxRegion`, created and destroyed by `dmtxRegionFindNext` and `dmtxRegionDestroy`. Args: decoder (POINTER(DmtxDecode)): timeout (int or None): Yields: DmtxRegion: The next region or None, if all regions have been found. ...
[ "def", "_region", "(", "decoder", ",", "timeout", ")", ":", "region", "=", "dmtxRegionFindNext", "(", "decoder", ",", "timeout", ")", "try", ":", "yield", "region", "finally", ":", "if", "region", ":", "dmtxRegionDestroy", "(", "byref", "(", "region", ")",...
A context manager for `DmtxRegion`, created and destroyed by `dmtxRegionFindNext` and `dmtxRegionDestroy`. Args: decoder (POINTER(DmtxDecode)): timeout (int or None): Yields: DmtxRegion: The next region or None, if all regions have been found.
[ "A", "context", "manager", "for", "DmtxRegion", "created", "and", "destroyed", "by", "dmtxRegionFindNext", "and", "dmtxRegionDestroy", "." ]
python
train
proycon/pynlpl
pynlpl/statistics.py
https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/statistics.py#L64-L69
def save(self, filename, addnormalised=False): """Save a frequency list to file, can be loaded later using the load method""" f = io.open(filename,'w',encoding='utf-8') for line in self.output("\t", addnormalised): f.write(line + '\n') f.close()
[ "def", "save", "(", "self", ",", "filename", ",", "addnormalised", "=", "False", ")", ":", "f", "=", "io", ".", "open", "(", "filename", ",", "'w'", ",", "encoding", "=", "'utf-8'", ")", "for", "line", "in", "self", ".", "output", "(", "\"\\t\"", "...
Save a frequency list to file, can be loaded later using the load method
[ "Save", "a", "frequency", "list", "to", "file", "can", "be", "loaded", "later", "using", "the", "load", "method" ]
python
train
edx/edx-enterprise
enterprise/utils.py
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/utils.py#L114-L131
def get_identity_provider(provider_id): """ Get Identity Provider with given id. Return: Instance of ProviderConfig or None. """ try: from third_party_auth.provider import Registry # pylint: disable=redefined-outer-name except ImportError as exception: LOGGER.warning("...
[ "def", "get_identity_provider", "(", "provider_id", ")", ":", "try", ":", "from", "third_party_auth", ".", "provider", "import", "Registry", "# pylint: disable=redefined-outer-name", "except", "ImportError", "as", "exception", ":", "LOGGER", ".", "warning", "(", "\"Co...
Get Identity Provider with given id. Return: Instance of ProviderConfig or None.
[ "Get", "Identity", "Provider", "with", "given", "id", "." ]
python
valid
MrYsLab/pymata-aio
pymata_aio/pymata_iot.py
https://github.com/MrYsLab/pymata-aio/blob/015081a4628b9d47dfe3f8d6c698ff903f107810/pymata_aio/pymata_iot.py#L557-L566
async def stepper_step(self, command): """ This method activates a stepper motor motion. This is a FirmataPlus feature. :param command: {"method": "stepper_step", "params": [SPEED, NUMBER_OF_STEPS]} :returns:No message returned. """ speed = int(command[0]) ...
[ "async", "def", "stepper_step", "(", "self", ",", "command", ")", ":", "speed", "=", "int", "(", "command", "[", "0", "]", ")", "num_steps", "=", "int", "(", "command", "[", "1", "]", ")", "await", "self", ".", "core", ".", "stepper_step", "(", "sp...
This method activates a stepper motor motion. This is a FirmataPlus feature. :param command: {"method": "stepper_step", "params": [SPEED, NUMBER_OF_STEPS]} :returns:No message returned.
[ "This", "method", "activates", "a", "stepper", "motor", "motion", ".", "This", "is", "a", "FirmataPlus", "feature", ".", ":", "param", "command", ":", "{", "method", ":", "stepper_step", "params", ":", "[", "SPEED", "NUMBER_OF_STEPS", "]", "}", ":", "retur...
python
train
rameshg87/pyremotevbox
pyremotevbox/ZSI/address.py
https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/address.py#L32-L47
def setUp(self): '''Look for WS-Address ''' toplist = filter(lambda wsa: wsa.ADDRESS==self.wsAddressURI, WSA_LIST) epr = 'EndpointReferenceType' for WSA in toplist+WSA_LIST: if (self.wsAddressURI is not None and self.wsAddressURI != WSA.ADDRESS) or \ _...
[ "def", "setUp", "(", "self", ")", ":", "toplist", "=", "filter", "(", "lambda", "wsa", ":", "wsa", ".", "ADDRESS", "==", "self", ".", "wsAddressURI", ",", "WSA_LIST", ")", "epr", "=", "'EndpointReferenceType'", "for", "WSA", "in", "toplist", "+", "WSA_LI...
Look for WS-Address
[ "Look", "for", "WS", "-", "Address" ]
python
train
danpoland/pyramid-restful-framework
pyramid_restful/pagination/pagenumber.py
https://github.com/danpoland/pyramid-restful-framework/blob/4d8c9db44b1869c3d1fdd59ca304c3166473fcbb/pyramid_restful/pagination/pagenumber.py#L98-L109
def count(self): """ Returns the total number of objects, across all pages. """ try: return self.object_list.count() except (AttributeError, TypeError): # AttributeError if object_list has no count() method. # TypeError if object_list.count() ...
[ "def", "count", "(", "self", ")", ":", "try", ":", "return", "self", ".", "object_list", ".", "count", "(", ")", "except", "(", "AttributeError", ",", "TypeError", ")", ":", "# AttributeError if object_list has no count() method.", "# TypeError if object_list.count() ...
Returns the total number of objects, across all pages.
[ "Returns", "the", "total", "number", "of", "objects", "across", "all", "pages", "." ]
python
train
dpgaspar/Flask-AppBuilder
flask_appbuilder/baseviews.py
https://github.com/dpgaspar/Flask-AppBuilder/blob/c293734c1b86e176a3ba57ee2deab6676d125576/flask_appbuilder/baseviews.py#L705-L728
def _init_forms(self): """ Init forms for Add and Edit """ super(BaseCRUDView, self)._init_forms() conv = GeneralModelConverter(self.datamodel) if not self.add_form: self.add_form = conv.create_form( self.label_columns, self...
[ "def", "_init_forms", "(", "self", ")", ":", "super", "(", "BaseCRUDView", ",", "self", ")", ".", "_init_forms", "(", ")", "conv", "=", "GeneralModelConverter", "(", "self", ".", "datamodel", ")", "if", "not", "self", ".", "add_form", ":", "self", ".", ...
Init forms for Add and Edit
[ "Init", "forms", "for", "Add", "and", "Edit" ]
python
train
QUANTAXIS/QUANTAXIS
QUANTAXIS/QASU/main.py
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QASU/main.py#L273-L284
def QA_SU_save_index_min(engine, client=DATABASE): """save index_min Arguments: engine {[type]} -- [description] Keyword Arguments: client {[type]} -- [description] (default: {DATABASE}) """ engine = select_save_engine(engine) engine.QA_SU_save_index_min(client=client)
[ "def", "QA_SU_save_index_min", "(", "engine", ",", "client", "=", "DATABASE", ")", ":", "engine", "=", "select_save_engine", "(", "engine", ")", "engine", ".", "QA_SU_save_index_min", "(", "client", "=", "client", ")" ]
save index_min Arguments: engine {[type]} -- [description] Keyword Arguments: client {[type]} -- [description] (default: {DATABASE})
[ "save", "index_min" ]
python
train
fananimi/pyzk
zk/base.py
https://github.com/fananimi/pyzk/blob/1a765d616526efdcb4c9adfcc9b1d10f6ed8b938/zk/base.py#L1151-L1159
def reg_event(self, flags): """ reg events """ command = const.CMD_REG_EVENT command_string = pack ("I", flags) cmd_response = self.__send_command(command, command_string) if not cmd_response.get('status'): raise ZKErrorResponse("cant' reg events %i" %...
[ "def", "reg_event", "(", "self", ",", "flags", ")", ":", "command", "=", "const", ".", "CMD_REG_EVENT", "command_string", "=", "pack", "(", "\"I\"", ",", "flags", ")", "cmd_response", "=", "self", ".", "__send_command", "(", "command", ",", "command_string",...
reg events
[ "reg", "events" ]
python
train
nagius/snmp_passpersist
snmp_passpersist.py
https://github.com/nagius/snmp_passpersist/blob/8cc584d2e90c920ae98a318164a55bde209a18f7/snmp_passpersist.py#L152-L170
def get_next(self,oid): """Return snmp value for the next OID.""" try: # Nested try..except because of Python 2.4 self.lock.acquire() try: # remove trailing zeroes from the oid while len(oid) > 0 and oid[-2:] == ".0" and oid not in self.data: oid = oid[:-2]; return self.get(self.data_idx[self...
[ "def", "get_next", "(", "self", ",", "oid", ")", ":", "try", ":", "# Nested try..except because of Python 2.4", "self", ".", "lock", ".", "acquire", "(", ")", "try", ":", "# remove trailing zeroes from the oid", "while", "len", "(", "oid", ")", ">", "0", "and"...
Return snmp value for the next OID.
[ "Return", "snmp", "value", "for", "the", "next", "OID", "." ]
python
train
openpaperwork/paperwork-backend
paperwork_backend/pdf/page.py
https://github.com/openpaperwork/paperwork-backend/blob/114b831e94e039e68b339751fd18250877abad76/paperwork_backend/pdf/page.py#L150-L193
def __get_boxes(self): """ Get all the word boxes of this page. """ if self.__boxes is not None: return self.__boxes # Check first if there is an OCR file available boxfile = self.__get_box_path() if self.fs.exists(boxfile): box_builder = ...
[ "def", "__get_boxes", "(", "self", ")", ":", "if", "self", ".", "__boxes", "is", "not", "None", ":", "return", "self", ".", "__boxes", "# Check first if there is an OCR file available", "boxfile", "=", "self", ".", "__get_box_path", "(", ")", "if", "self", "."...
Get all the word boxes of this page.
[ "Get", "all", "the", "word", "boxes", "of", "this", "page", "." ]
python
train
DataDog/integrations-core
cisco_aci/datadog_checks/cisco_aci/helpers.py
https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/cisco_aci/datadog_checks/cisco_aci/helpers.py#L98-L122
def get_event_tags_from_dn(dn): """ This grabs the event tags from the dn designator. They look like this: uni/tn-DataDog/ap-DtDg-AP1-EcommerceApp/epg-DtDg-Ecomm/HDl2IngrPktsAg1h """ tags = [] node = get_node_from_dn(dn) if node: tags.append("node:" + node) app = get_app_from_dn(...
[ "def", "get_event_tags_from_dn", "(", "dn", ")", ":", "tags", "=", "[", "]", "node", "=", "get_node_from_dn", "(", "dn", ")", "if", "node", ":", "tags", ".", "append", "(", "\"node:\"", "+", "node", ")", "app", "=", "get_app_from_dn", "(", "dn", ")", ...
This grabs the event tags from the dn designator. They look like this: uni/tn-DataDog/ap-DtDg-AP1-EcommerceApp/epg-DtDg-Ecomm/HDl2IngrPktsAg1h
[ "This", "grabs", "the", "event", "tags", "from", "the", "dn", "designator", ".", "They", "look", "like", "this", ":", "uni", "/", "tn", "-", "DataDog", "/", "ap", "-", "DtDg", "-", "AP1", "-", "EcommerceApp", "/", "epg", "-", "DtDg", "-", "Ecomm", ...
python
train
ardydedase/pycouchbase
couchbase-python-cffi/couchbase_ffi/executors.py
https://github.com/ardydedase/pycouchbase/blob/6f010b4d2ef41aead2366878d0cf0b1284c0db0e/couchbase-python-cffi/couchbase_ffi/executors.py#L335-L382
def execute(self, kv, **kwargs): """ Execute the operation scheduling items as needed :param kv: An iterable of keys (or key-values, or Items) :param kwargs: Settings for the operation :return: A MultiResult object """ self._verify_iter(kv) if not len(kv):...
[ "def", "execute", "(", "self", ",", "kv", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_verify_iter", "(", "kv", ")", "if", "not", "len", "(", "kv", ")", ":", "raise", "ArgumentError", ".", "pyexc", "(", "obj", "=", "kv", ",", "message", "=",...
Execute the operation scheduling items as needed :param kv: An iterable of keys (or key-values, or Items) :param kwargs: Settings for the operation :return: A MultiResult object
[ "Execute", "the", "operation", "scheduling", "items", "as", "needed", ":", "param", "kv", ":", "An", "iterable", "of", "keys", "(", "or", "key", "-", "values", "or", "Items", ")", ":", "param", "kwargs", ":", "Settings", "for", "the", "operation", ":", ...
python
train
mitsei/dlkit
dlkit/json_/assessment/objects.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/assessment/objects.py#L1659-L1669
def _init_metadata(self, **kwargs): """Initialize form metadata""" osid_objects.OsidObjectForm._init_metadata(self, **kwargs) self._level_default = self._mdata['level']['default_id_values'][0] self._start_time_default = self._mdata['start_time']['default_date_time_values'][0] sel...
[ "def", "_init_metadata", "(", "self", ",", "*", "*", "kwargs", ")", ":", "osid_objects", ".", "OsidObjectForm", ".", "_init_metadata", "(", "self", ",", "*", "*", "kwargs", ")", "self", ".", "_level_default", "=", "self", ".", "_mdata", "[", "'level'", "...
Initialize form metadata
[ "Initialize", "form", "metadata" ]
python
train
yyuu/botornado
boto/s3/connection.py
https://github.com/yyuu/botornado/blob/fffb056f5ff2324d1d5c1304014cfb1d899f602e/boto/s3/connection.py#L180-L190
def build_post_policy(self, expiration_time, conditions): """ Taken from the AWS book Python examples and modified for use with boto """ assert type(expiration_time) == time.struct_time, \ 'Policy document must include a valid expiration Time object' # Convert condit...
[ "def", "build_post_policy", "(", "self", ",", "expiration_time", ",", "conditions", ")", ":", "assert", "type", "(", "expiration_time", ")", "==", "time", ".", "struct_time", ",", "'Policy document must include a valid expiration Time object'", "# Convert conditions object ...
Taken from the AWS book Python examples and modified for use with boto
[ "Taken", "from", "the", "AWS", "book", "Python", "examples", "and", "modified", "for", "use", "with", "boto" ]
python
train
saltstack/salt
salt/beacons/wtmp.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/wtmp.py#L174-L194
def _validate_time_range(trange, status, msg): ''' Check time range ''' # If trange is empty, just return the current status & msg if not trange: return status, msg if not isinstance(trange, dict): status = False msg = ('The time_range parameter for ' 'wtm...
[ "def", "_validate_time_range", "(", "trange", ",", "status", ",", "msg", ")", ":", "# If trange is empty, just return the current status & msg", "if", "not", "trange", ":", "return", "status", ",", "msg", "if", "not", "isinstance", "(", "trange", ",", "dict", ")",...
Check time range
[ "Check", "time", "range" ]
python
train
nickjj/ansigenome
ansigenome/scan.py
https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/scan.py#L236-L267
def gather_defaults(self): """ Return the number of default variables. """ total_defaults = 0 defaults_lines = [] if not os.path.exists(self.paths["defaults"]): # reset the defaults if no defaults were found self.defaults = "" return 0...
[ "def", "gather_defaults", "(", "self", ")", ":", "total_defaults", "=", "0", "defaults_lines", "=", "[", "]", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "paths", "[", "\"defaults\"", "]", ")", ":", "# reset the defaults if no defaults w...
Return the number of default variables.
[ "Return", "the", "number", "of", "default", "variables", "." ]
python
train
cloud9ers/gurumate
environment/lib/python2.7/site-packages/nose/util.py
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/util.py#L242-L288
def getpackage(filename): """ Find the full dotted package name for a given python source file name. Returns None if the file is not a python source file. >>> getpackage('foo.py') 'foo' >>> getpackage('biff/baf.py') 'baf' >>> getpackage('nose/util.py') 'nose.util' Works for dir...
[ "def", "getpackage", "(", "filename", ")", ":", "src_file", "=", "src", "(", "filename", ")", "if", "not", "src_file", ".", "endswith", "(", "'.py'", ")", "and", "not", "ispackage", "(", "src_file", ")", ":", "return", "None", "base", ",", "ext", "=", ...
Find the full dotted package name for a given python source file name. Returns None if the file is not a python source file. >>> getpackage('foo.py') 'foo' >>> getpackage('biff/baf.py') 'baf' >>> getpackage('nose/util.py') 'nose.util' Works for directories too. >>> getpackage('nos...
[ "Find", "the", "full", "dotted", "package", "name", "for", "a", "given", "python", "source", "file", "name", ".", "Returns", "None", "if", "the", "file", "is", "not", "a", "python", "source", "file", "." ]
python
test
angr/angr
angr/procedures/stubs/format_parser.py
https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/procedures/stubs/format_parser.py#L414-L424
def _all_spec(self): """ All specifiers and their lengths. """ base = self._mod_spec for spec in self.basic_spec: base[spec] = self.basic_spec[spec] return base
[ "def", "_all_spec", "(", "self", ")", ":", "base", "=", "self", ".", "_mod_spec", "for", "spec", "in", "self", ".", "basic_spec", ":", "base", "[", "spec", "]", "=", "self", ".", "basic_spec", "[", "spec", "]", "return", "base" ]
All specifiers and their lengths.
[ "All", "specifiers", "and", "their", "lengths", "." ]
python
train
SeattleTestbed/seash
pyreadline/modes/basemode.py
https://github.com/SeattleTestbed/seash/blob/40f9d2285662ff8b61e0468b4196acee089b273b/pyreadline/modes/basemode.py#L540-L549
def dump_functions(self, e): # () u"""Print all of the functions and their key bindings to the Readline output stream. If a numeric argument is supplied, the output is formatted in such a way that it can be made part of an inputrc file. This command is unbound by default.""" ...
[ "def", "dump_functions", "(", "self", ",", "e", ")", ":", "# ()\r", "print", "txt", "=", "\"\\n\"", ".", "join", "(", "self", ".", "rl_settings_to_string", "(", ")", ")", "print", "txt", "self", ".", "_print_prompt", "(", ")", "self", ".", "finalize", ...
u"""Print all of the functions and their key bindings to the Readline output stream. If a numeric argument is supplied, the output is formatted in such a way that it can be made part of an inputrc file. This command is unbound by default.
[ "u", "Print", "all", "of", "the", "functions", "and", "their", "key", "bindings", "to", "the", "Readline", "output", "stream", ".", "If", "a", "numeric", "argument", "is", "supplied", "the", "output", "is", "formatted", "in", "such", "a", "way", "that", ...
python
train
briancappello/flask-unchained
flask_unchained/bundles/security/services/security_service.py
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/services/security_service.py#L165-L186
def change_password(self, user, password, send_email=None): """ Service method to change a user's password. Sends signal `password_changed`. :param user: The :class:`User`'s password to change. :param password: The new password. :param send_email: Whether or not to over...
[ "def", "change_password", "(", "self", ",", "user", ",", "password", ",", "send_email", "=", "None", ")", ":", "user", ".", "password", "=", "password", "self", ".", "user_manager", ".", "save", "(", "user", ")", "if", "send_email", "or", "(", "app", "...
Service method to change a user's password. Sends signal `password_changed`. :param user: The :class:`User`'s password to change. :param password: The new password. :param send_email: Whether or not to override the config option ``SECURITY_SEND_PASSWORD_CHANG...
[ "Service", "method", "to", "change", "a", "user", "s", "password", "." ]
python
train
tamasgal/km3pipe
km3pipe/db.py
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/db.py#L356-L367
def _get_json(self, url): "Get JSON-type content" content = self._get_content('jsonds/' + url) try: json_content = json.loads(content.decode()) except AttributeError: json_content = json.loads(content) if json_content['Comment']: log.warning(js...
[ "def", "_get_json", "(", "self", ",", "url", ")", ":", "content", "=", "self", ".", "_get_content", "(", "'jsonds/'", "+", "url", ")", "try", ":", "json_content", "=", "json", ".", "loads", "(", "content", ".", "decode", "(", ")", ")", "except", "Att...
Get JSON-type content
[ "Get", "JSON", "-", "type", "content" ]
python
train
ralphbean/bugwarrior
bugwarrior/services/__init__.py
https://github.com/ralphbean/bugwarrior/blob/b2a5108f7b40cb0c437509b64eaa28f941f7ac8b/bugwarrior/services/__init__.py#L161-L174
def validate_config(cls, service_config, target): """ Validate generic options for a particular target """ if service_config.has_option(target, 'only_if_assigned'): die("[%s] has an 'only_if_assigned' option. Should be " "'%s.only_if_assigned'." % (target, cls.CONFIG_PREFIX)...
[ "def", "validate_config", "(", "cls", ",", "service_config", ",", "target", ")", ":", "if", "service_config", ".", "has_option", "(", "target", ",", "'only_if_assigned'", ")", ":", "die", "(", "\"[%s] has an 'only_if_assigned' option. Should be \"", "\"'%s.only_if_assi...
Validate generic options for a particular target
[ "Validate", "generic", "options", "for", "a", "particular", "target" ]
python
test
androguard/androguard
androguard/core/bytecodes/dvm.py
https://github.com/androguard/androguard/blob/984c0d981be2950cf0451e484f7b0d4d53bc4911/androguard/core/bytecodes/dvm.py#L113-L127
def get_access_flags_string(value): """ Transform an access flag field to the corresponding string :param value: the value of the access flags :type value: int :rtype: string """ flags = [] for k, v in ACCESS_FLAGS.items(): if (k & value) == k: flags.append(v) ...
[ "def", "get_access_flags_string", "(", "value", ")", ":", "flags", "=", "[", "]", "for", "k", ",", "v", "in", "ACCESS_FLAGS", ".", "items", "(", ")", ":", "if", "(", "k", "&", "value", ")", "==", "k", ":", "flags", ".", "append", "(", "v", ")", ...
Transform an access flag field to the corresponding string :param value: the value of the access flags :type value: int :rtype: string
[ "Transform", "an", "access", "flag", "field", "to", "the", "corresponding", "string" ]
python
train
Rapptz/discord.py
discord/channel.py
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/channel.py#L520-L528
def members(self): """Returns a list of :class:`Member` that are currently inside this voice channel.""" ret = [] for user_id, state in self.guild._voice_states.items(): if state.channel.id == self.id: member = self.guild.get_member(user_id) if member ...
[ "def", "members", "(", "self", ")", ":", "ret", "=", "[", "]", "for", "user_id", ",", "state", "in", "self", ".", "guild", ".", "_voice_states", ".", "items", "(", ")", ":", "if", "state", ".", "channel", ".", "id", "==", "self", ".", "id", ":", ...
Returns a list of :class:`Member` that are currently inside this voice channel.
[ "Returns", "a", "list", "of", ":", "class", ":", "Member", "that", "are", "currently", "inside", "this", "voice", "channel", "." ]
python
train
saltstack/salt
salt/modules/boto_elb.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_elb.py#L626-L659
def get_health_check(name, region=None, key=None, keyid=None, profile=None): ''' Get the health check configured for this ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_health_check myelb ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ...
[ "def", "get_health_check", "(", "name", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", "=", "key", ",", "key...
Get the health check configured for this ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_health_check myelb
[ "Get", "the", "health", "check", "configured", "for", "this", "ELB", "." ]
python
train
asphalt-framework/asphalt-sqlalchemy
asphalt/sqlalchemy/utils.py
https://github.com/asphalt-framework/asphalt-sqlalchemy/blob/5abb7d9977ee92299359b76496ff34624421de05/asphalt/sqlalchemy/utils.py#L8-L27
def clear_database(engine: Connectable, schemas: Iterable[str] = ()) -> None: """ Clear any tables from an existing database. :param engine: the engine or connection to use :param schemas: full list of schema names to expect (ignored for SQLite) """ assert check_argument_types() metadatas ...
[ "def", "clear_database", "(", "engine", ":", "Connectable", ",", "schemas", ":", "Iterable", "[", "str", "]", "=", "(", ")", ")", "->", "None", ":", "assert", "check_argument_types", "(", ")", "metadatas", "=", "[", "]", "all_schemas", "=", "(", "None", ...
Clear any tables from an existing database. :param engine: the engine or connection to use :param schemas: full list of schema names to expect (ignored for SQLite)
[ "Clear", "any", "tables", "from", "an", "existing", "database", "." ]
python
train
tensorflow/cleverhans
cleverhans/attacks/bapp.py
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/bapp.py#L522-L536
def select_delta(dist_post_update, current_iteration, clip_max, clip_min, d, theta, constraint): """ Choose the delta at the scale of distance between x and perturbed sample. """ if current_iteration == 1: delta = 0.1 * (clip_max - clip_min) else: if constraint == 'l2': delta...
[ "def", "select_delta", "(", "dist_post_update", ",", "current_iteration", ",", "clip_max", ",", "clip_min", ",", "d", ",", "theta", ",", "constraint", ")", ":", "if", "current_iteration", "==", "1", ":", "delta", "=", "0.1", "*", "(", "clip_max", "-", "cli...
Choose the delta at the scale of distance between x and perturbed sample.
[ "Choose", "the", "delta", "at", "the", "scale", "of", "distance", "between", "x", "and", "perturbed", "sample", "." ]
python
train
sorgerlab/indra
indra/sources/medscan/processor.py
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/medscan/processor.py#L683-L849
def agent_from_entity(self, relation, entity_id): """Create a (potentially grounded) INDRA Agent object from a given Medscan entity describing the subject or object. Uses helper functions to convert a Medscan URN to an INDRA db_refs grounding dictionary. If the entity has prope...
[ "def", "agent_from_entity", "(", "self", ",", "relation", ",", "entity_id", ")", ":", "# Extract sentence tags mapping ids to the text. We refer to this", "# mapping only if the entity doesn't appear in the grounded entity", "# list", "tags", "=", "_extract_sentence_tags", "(", "re...
Create a (potentially grounded) INDRA Agent object from a given Medscan entity describing the subject or object. Uses helper functions to convert a Medscan URN to an INDRA db_refs grounding dictionary. If the entity has properties indicating that it is a protein with a mutation...
[ "Create", "a", "(", "potentially", "grounded", ")", "INDRA", "Agent", "object", "from", "a", "given", "Medscan", "entity", "describing", "the", "subject", "or", "object", "." ]
python
train
openego/eDisGo
edisgo/data/import_data.py
https://github.com/openego/eDisGo/blob/e6245bdaf236f9c49dbda5a18c1c458290f41e2b/edisgo/data/import_data.py#L412-L601
def _determine_aggregated_nodes(la_centers): """Determine generation and load within load areas Parameters ---------- la_centers: list of LVLoadAreaCentre Load Area Centers are Ding0 implementations for representating areas of high population density with high demand compared to DG pote...
[ "def", "_determine_aggregated_nodes", "(", "la_centers", ")", ":", "def", "aggregate_generators", "(", "gen", ",", "aggr", ")", ":", "\"\"\"Aggregate generation capacity per voltage level\n\n Parameters\n ----------\n gen: ding0.core.GeneratorDing0\n Ding0...
Determine generation and load within load areas Parameters ---------- la_centers: list of LVLoadAreaCentre Load Area Centers are Ding0 implementations for representating areas of high population density with high demand compared to DG potential. Notes ----- Currently, MV grid l...
[ "Determine", "generation", "and", "load", "within", "load", "areas" ]
python
train
quantum5/2048
_2048/game.py
https://github.com/quantum5/2048/blob/93ada2e3026eaf154e1bbee943d0500c9253e66f/_2048/game.py#L313-L318
def get_tile_location(self, x, y): """Get the screen coordinate for the top-left corner of a tile.""" x1, y1 = self.origin x1 += self.BORDER + (self.BORDER + self.cell_width) * x y1 += self.BORDER + (self.BORDER + self.cell_height) * y return x1, y1
[ "def", "get_tile_location", "(", "self", ",", "x", ",", "y", ")", ":", "x1", ",", "y1", "=", "self", ".", "origin", "x1", "+=", "self", ".", "BORDER", "+", "(", "self", ".", "BORDER", "+", "self", ".", "cell_width", ")", "*", "x", "y1", "+=", "...
Get the screen coordinate for the top-left corner of a tile.
[ "Get", "the", "screen", "coordinate", "for", "the", "top", "-", "left", "corner", "of", "a", "tile", "." ]
python
train
Hackerfleet/hfos
modules/enrol/hfos/enrol/enrolmanager.py
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/modules/enrol/hfos/enrol/enrolmanager.py#L357-L385
def changepassword(self, event): """An enrolled user wants to change their password""" old = event.data['old'] new = event.data['new'] uuid = event.user.uuid # TODO: Write email to notify user of password change user = objectmodels['user'].find_one({'uuid': uuid}) ...
[ "def", "changepassword", "(", "self", ",", "event", ")", ":", "old", "=", "event", ".", "data", "[", "'old'", "]", "new", "=", "event", ".", "data", "[", "'new'", "]", "uuid", "=", "event", ".", "user", ".", "uuid", "# TODO: Write email to notify user of...
An enrolled user wants to change their password
[ "An", "enrolled", "user", "wants", "to", "change", "their", "password" ]
python
train
spyder-ide/spyder
spyder/plugins/onlinehelp/widgets.py
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/onlinehelp/widgets.py#L126-L130
def text_to_url(self, text): """Convert text address into QUrl object""" if text.startswith('/'): text = text[1:] return QUrl(self.home_url.toString()+text+'.html')
[ "def", "text_to_url", "(", "self", ",", "text", ")", ":", "if", "text", ".", "startswith", "(", "'/'", ")", ":", "text", "=", "text", "[", "1", ":", "]", "return", "QUrl", "(", "self", ".", "home_url", ".", "toString", "(", ")", "+", "text", "+",...
Convert text address into QUrl object
[ "Convert", "text", "address", "into", "QUrl", "object" ]
python
train
LLNL/scraper
scraper/doecode/__init__.py
https://github.com/LLNL/scraper/blob/881a316e4c04dfa5a9cf491b7c7f9f997a7c56ea/scraper/doecode/__init__.py#L23-L38
def process_url(url, key): """ Yields DOE CODE records from a DOE CODE .json URL response Converts a DOE CODE API .json URL response into DOE CODE projects """ logger.debug('Fetching DOE CODE JSON: %s', url) if key is None: raise ValueError('DOE CODE API Key value is missing!') re...
[ "def", "process_url", "(", "url", ",", "key", ")", ":", "logger", ".", "debug", "(", "'Fetching DOE CODE JSON: %s'", ",", "url", ")", "if", "key", "is", "None", ":", "raise", "ValueError", "(", "'DOE CODE API Key value is missing!'", ")", "response", "=", "req...
Yields DOE CODE records from a DOE CODE .json URL response Converts a DOE CODE API .json URL response into DOE CODE projects
[ "Yields", "DOE", "CODE", "records", "from", "a", "DOE", "CODE", ".", "json", "URL", "response", "Converts", "a", "DOE", "CODE", "API", ".", "json", "URL", "response", "into", "DOE", "CODE", "projects" ]
python
test
wbond/oscrypto
oscrypto/_tls.py
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_tls.py#L129-L148
def parse_alert(server_handshake_bytes): """ Parses the handshake for protocol alerts :param server_handshake_bytes: A byte string of the handshake data received from the server :return: None or an 2-element tuple of integers: 0: 1 (warning) or 2 (fatal) 1: The alert ...
[ "def", "parse_alert", "(", "server_handshake_bytes", ")", ":", "for", "record_type", ",", "_", ",", "record_data", "in", "parse_tls_records", "(", "server_handshake_bytes", ")", ":", "if", "record_type", "!=", "b'\\x15'", ":", "continue", "if", "len", "(", "reco...
Parses the handshake for protocol alerts :param server_handshake_bytes: A byte string of the handshake data received from the server :return: None or an 2-element tuple of integers: 0: 1 (warning) or 2 (fatal) 1: The alert description (see https://tools.ietf.org/html/rfc5246#...
[ "Parses", "the", "handshake", "for", "protocol", "alerts" ]
python
valid
dourvaris/nano-python
src/nano/rpc.py
https://github.com/dourvaris/nano-python/blob/f26b8bc895b997067780f925049a70e82c0c2479/src/nano/rpc.py#L182-L202
def account_block_count(self, account): """ Get number of blocks for a specific **account** :param account: Account to get number of blocks for :type account: str :raises: :py:exc:`nano.rpc.RPCException` >>> rpc.account_block_count(account="xrb_3t6k35gi95xu6tergt6p69ck...
[ "def", "account_block_count", "(", "self", ",", "account", ")", ":", "account", "=", "self", ".", "_process_value", "(", "account", ",", "'account'", ")", "payload", "=", "{", "\"account\"", ":", "account", "}", "resp", "=", "self", ".", "call", "(", "'a...
Get number of blocks for a specific **account** :param account: Account to get number of blocks for :type account: str :raises: :py:exc:`nano.rpc.RPCException` >>> rpc.account_block_count(account="xrb_3t6k35gi95xu6tergt6p69ck76ogmitsa8mnijtpxm9fkcm736xtoncuohr3") 19
[ "Get", "number", "of", "blocks", "for", "a", "specific", "**", "account", "**" ]
python
train
chrisspen/burlap
burlap/files.py
https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/files.py#L334-L340
def remove(self, path, recursive=False, use_sudo=False): """ Remove a file or directory """ func = use_sudo and run_as_root or self.run options = '-r ' if recursive else '' func('/bin/rm {0}{1}'.format(options, quote(path)))
[ "def", "remove", "(", "self", ",", "path", ",", "recursive", "=", "False", ",", "use_sudo", "=", "False", ")", ":", "func", "=", "use_sudo", "and", "run_as_root", "or", "self", ".", "run", "options", "=", "'-r '", "if", "recursive", "else", "''", "func...
Remove a file or directory
[ "Remove", "a", "file", "or", "directory" ]
python
valid
numenta/nupic
src/nupic/encoders/scalar.py
https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/encoders/scalar.py#L655-L674
def getBucketInfo(self, buckets): """ See the function description in base.py """ # Get/generate the topDown mapping table #NOTE: although variable topDownMappingM is unused, some (bad-style) actions #are executed during _getTopDownMapping() so this line must stay here topDownMappingM = self._getTo...
[ "def", "getBucketInfo", "(", "self", ",", "buckets", ")", ":", "# Get/generate the topDown mapping table", "#NOTE: although variable topDownMappingM is unused, some (bad-style) actions", "#are executed during _getTopDownMapping() so this line must stay here", "topDownMappingM", "=", "self"...
See the function description in base.py
[ "See", "the", "function", "description", "in", "base", ".", "py" ]
python
valid
swisscom/cleanerversion
versions/admin.py
https://github.com/swisscom/cleanerversion/blob/becadbab5d7b474a0e9a596b99e97682402d2f2c/versions/admin.py#L144-L152
def get_readonly_fields(self, request, obj=None): """ This is required a subclass of VersionedAdmin has readonly_fields ours won't be undone """ if obj: return list(self.readonly_fields) + ['id', 'identity', 'is_current...
[ "def", "get_readonly_fields", "(", "self", ",", "request", ",", "obj", "=", "None", ")", ":", "if", "obj", ":", "return", "list", "(", "self", ".", "readonly_fields", ")", "+", "[", "'id'", ",", "'identity'", ",", "'is_current'", "]", "return", "self", ...
This is required a subclass of VersionedAdmin has readonly_fields ours won't be undone
[ "This", "is", "required", "a", "subclass", "of", "VersionedAdmin", "has", "readonly_fields", "ours", "won", "t", "be", "undone" ]
python
train
jonathf/chaospy
chaospy/distributions/operators/joint.py
https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/distributions/operators/joint.py#L148-L169
def _ppf(self, qloc, cache, **kwargs): """ Example: >>> dist = chaospy.J(chaospy.Uniform(), chaospy.Normal()) >>> print(numpy.around(dist.inv([[0.1, 0.2, 0.3], [0.3, 0.3, 0.4]]), 4)) [[ 0.1 0.2 0.3 ] [-0.5244 -0.5244 -0.2533]] >>> d0...
[ "def", "_ppf", "(", "self", ",", "qloc", ",", "cache", ",", "*", "*", "kwargs", ")", ":", "xloc", "=", "numpy", ".", "zeros", "(", "qloc", ".", "shape", ")", "for", "dist", "in", "evaluation", ".", "sorted_dependencies", "(", "self", ",", "reverse", ...
Example: >>> dist = chaospy.J(chaospy.Uniform(), chaospy.Normal()) >>> print(numpy.around(dist.inv([[0.1, 0.2, 0.3], [0.3, 0.3, 0.4]]), 4)) [[ 0.1 0.2 0.3 ] [-0.5244 -0.5244 -0.2533]] >>> d0 = chaospy.Uniform() >>> dist = chaospy.J(d0, d...
[ "Example", ":", ">>>", "dist", "=", "chaospy", ".", "J", "(", "chaospy", ".", "Uniform", "()", "chaospy", ".", "Normal", "()", ")", ">>>", "print", "(", "numpy", ".", "around", "(", "dist", ".", "inv", "(", "[[", "0", ".", "1", "0", ".", "2", "...
python
train
log2timeline/plaso
plaso/formatters/winevt_rc.py
https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/formatters/winevt_rc.py#L246-L263
def _GetMessageFileKeys(self, event_log_provider_key): """Retrieves the message file keys. Args: event_log_provider_key (int): Event Log provider key. Yields: int: message file key. """ table_names = ['message_file_per_event_log_provider'] column_names = ['message_file_key'] co...
[ "def", "_GetMessageFileKeys", "(", "self", ",", "event_log_provider_key", ")", ":", "table_names", "=", "[", "'message_file_per_event_log_provider'", "]", "column_names", "=", "[", "'message_file_key'", "]", "condition", "=", "'event_log_provider_key == {0:d}'", ".", "for...
Retrieves the message file keys. Args: event_log_provider_key (int): Event Log provider key. Yields: int: message file key.
[ "Retrieves", "the", "message", "file", "keys", "." ]
python
train
cjdrake/pyeda
pyeda/parsing/dimacs.py
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/dimacs.py#L385-L421
def _sat_formula(lexer, varname, fmt, nvars): """Return a DIMACS SAT formula.""" types = {IntegerToken, LPAREN} | _SAT_TOKS[fmt] tok = _expect_token(lexer, types) # INT if isinstance(tok, IntegerToken): index = tok.value if not 0 < index <= nvars: fstr = "formula literal ...
[ "def", "_sat_formula", "(", "lexer", ",", "varname", ",", "fmt", ",", "nvars", ")", ":", "types", "=", "{", "IntegerToken", ",", "LPAREN", "}", "|", "_SAT_TOKS", "[", "fmt", "]", "tok", "=", "_expect_token", "(", "lexer", ",", "types", ")", "# INT", ...
Return a DIMACS SAT formula.
[ "Return", "a", "DIMACS", "SAT", "formula", "." ]
python
train
NuGrid/NuGridPy
nugridpy/utils.py
https://github.com/NuGrid/NuGridPy/blob/eee8047446e398be77362d82c1d8b3310054fab0/nugridpy/utils.py#L1163-L1435
def convert_specie_naming_from_h5_to_ppn(isotope_names): ''' read isotopes names from h5 files, and convert them according to standard scheme used inside ppn and mppnp. Also Z and A are recalculated, for these species. Isomers are excluded for now, since there were recent changes in isomers nam...
[ "def", "convert_specie_naming_from_h5_to_ppn", "(", "isotope_names", ")", ":", "spe_rude1", "=", "[", "]", "spe_rude2", "=", "[", "]", "spe_rude3", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "isotope_names", ")", ")", ":", "spe_rude1", ".",...
read isotopes names from h5 files, and convert them according to standard scheme used inside ppn and mppnp. Also Z and A are recalculated, for these species. Isomers are excluded for now, since there were recent changes in isomers name. As soon as the isomers names are settled, than Z and A provide...
[ "read", "isotopes", "names", "from", "h5", "files", "and", "convert", "them", "according", "to", "standard", "scheme", "used", "inside", "ppn", "and", "mppnp", ".", "Also", "Z", "and", "A", "are", "recalculated", "for", "these", "species", ".", "Isomers", ...
python
train
kkinder/NdbSearchableBase
NdbSearchableBase/SearchableModel.py
https://github.com/kkinder/NdbSearchableBase/blob/4f999336b464704a0929cec135c1f09fb1ddfb7c/NdbSearchableBase/SearchableModel.py#L188-L195
def _pre_delete_hook(cls, key): """ Removes instance from index. """ if cls.searching_enabled: doc_id = cls.search_get_document_id(key) index = cls.search_get_index() index.delete(doc_id)
[ "def", "_pre_delete_hook", "(", "cls", ",", "key", ")", ":", "if", "cls", ".", "searching_enabled", ":", "doc_id", "=", "cls", ".", "search_get_document_id", "(", "key", ")", "index", "=", "cls", ".", "search_get_index", "(", ")", "index", ".", "delete", ...
Removes instance from index.
[ "Removes", "instance", "from", "index", "." ]
python
train
ten10solutions/Geist
geist/match_position_finder_helpers.py
https://github.com/ten10solutions/Geist/blob/a1ef16d8b4c3777735008b671a50acfde3ce7bf1/geist/match_position_finder_helpers.py#L44-L57
def normalise_correlation(image_tile_dict, transformed_array, template, normed_tolerance=1): """Calculates the normalisation coefficients of potential match positions Then normalises the correlation at these positions, and returns them if they do indeed constitute a match """ template_norm = n...
[ "def", "normalise_correlation", "(", "image_tile_dict", ",", "transformed_array", ",", "template", ",", "normed_tolerance", "=", "1", ")", ":", "template_norm", "=", "np", ".", "linalg", ".", "norm", "(", "template", ")", "image_norms", "=", "{", "(", "x", "...
Calculates the normalisation coefficients of potential match positions Then normalises the correlation at these positions, and returns them if they do indeed constitute a match
[ "Calculates", "the", "normalisation", "coefficients", "of", "potential", "match", "positions", "Then", "normalises", "the", "correlation", "at", "these", "positions", "and", "returns", "them", "if", "they", "do", "indeed", "constitute", "a", "match" ]
python
train
cmap/cmapPy
cmapPy/pandasGEXpress/parse_gctx.py
https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/parse_gctx.py#L287-L299
def replace_666(meta_df, convert_neg_666): """ Replace -666, -666.0, and optionally "-666". Args: meta_df (pandas df): convert_neg_666 (bool): Returns: out_df (pandas df): updated meta_df """ if convert_neg_666: out_df = meta_df.replace([-666, "-666", -666.0], np.nan)...
[ "def", "replace_666", "(", "meta_df", ",", "convert_neg_666", ")", ":", "if", "convert_neg_666", ":", "out_df", "=", "meta_df", ".", "replace", "(", "[", "-", "666", ",", "\"-666\"", ",", "-", "666.0", "]", ",", "np", ".", "nan", ")", "else", ":", "o...
Replace -666, -666.0, and optionally "-666". Args: meta_df (pandas df): convert_neg_666 (bool): Returns: out_df (pandas df): updated meta_df
[ "Replace", "-", "666", "-", "666", ".", "0", "and", "optionally", "-", "666", ".", "Args", ":", "meta_df", "(", "pandas", "df", ")", ":", "convert_neg_666", "(", "bool", ")", ":", "Returns", ":", "out_df", "(", "pandas", "df", ")", ":", "updated", ...
python
train
vvangelovski/django-audit-log
audit_log/models/managers.py
https://github.com/vvangelovski/django-audit-log/blob/f1bee75360a67390fbef67c110e9a245b41ebb92/audit_log/models/managers.py#L190-L231
def get_logging_fields(self, model): """ Returns a dictionary mapping of the fields that are used for keeping the acutal audit log entries. """ rel_name = '_%s_audit_log_entry'%model._meta.object_name.lower() def entry_instance_to_unicode(log_entry): try: ...
[ "def", "get_logging_fields", "(", "self", ",", "model", ")", ":", "rel_name", "=", "'_%s_audit_log_entry'", "%", "model", ".", "_meta", ".", "object_name", ".", "lower", "(", ")", "def", "entry_instance_to_unicode", "(", "log_entry", ")", ":", "try", ":", "r...
Returns a dictionary mapping of the fields that are used for keeping the acutal audit log entries.
[ "Returns", "a", "dictionary", "mapping", "of", "the", "fields", "that", "are", "used", "for", "keeping", "the", "acutal", "audit", "log", "entries", "." ]
python
train
lk-geimfari/mimesis
mimesis/providers/generic.py
https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/generic.py#L126-L133
def add_providers(self, *providers: Type[BaseProvider]) -> None: """Add a lot of custom providers to Generic() object. :param providers: Custom providers. :return: None """ for provider in providers: self.add_provider(provider)
[ "def", "add_providers", "(", "self", ",", "*", "providers", ":", "Type", "[", "BaseProvider", "]", ")", "->", "None", ":", "for", "provider", "in", "providers", ":", "self", ".", "add_provider", "(", "provider", ")" ]
Add a lot of custom providers to Generic() object. :param providers: Custom providers. :return: None
[ "Add", "a", "lot", "of", "custom", "providers", "to", "Generic", "()", "object", "." ]
python
train
vaexio/vaex
packages/vaex-core/vaex/functions.py
https://github.com/vaexio/vaex/blob/a45b672f8287afca2ada8e36b74b604b9b28dd85/packages/vaex-core/vaex/functions.py#L1256-L1287
def str_rstrip(x, to_strip=None): """Remove trailing characters from a string sample. :param str to_strip: The string to be removed :returns: an expression containing the modified string column. Example: >>> import vaex >>> text = ['Something', 'very pretty', 'is coming', 'our', 'way.'] >...
[ "def", "str_rstrip", "(", "x", ",", "to_strip", "=", "None", ")", ":", "# in c++ we give empty string the same meaning as None", "sl", "=", "_to_string_sequence", "(", "x", ")", ".", "rstrip", "(", "''", "if", "to_strip", "is", "None", "else", "to_strip", ")", ...
Remove trailing characters from a string sample. :param str to_strip: The string to be removed :returns: an expression containing the modified string column. Example: >>> import vaex >>> text = ['Something', 'very pretty', 'is coming', 'our', 'way.'] >>> df = vaex.from_arrays(text=text) >...
[ "Remove", "trailing", "characters", "from", "a", "string", "sample", "." ]
python
test
coursera-dl/coursera-dl
coursera/api.py
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/api.py#L1310-L1329
def _extract_asset_urls(self, asset_ids): """ Extract asset URLs along with asset ids. @param asset_ids: List of ids to get URLs for. @type assertn: [str] @return: List of dictionaries with asset URLs and ids. @rtype: [{ 'id': '<id>', 'url': '<ur...
[ "def", "_extract_asset_urls", "(", "self", ",", "asset_ids", ")", ":", "dom", "=", "get_page", "(", "self", ".", "_session", ",", "OPENCOURSE_ASSET_URL", ",", "json", "=", "True", ",", "ids", "=", "quote_plus", "(", "','", ".", "join", "(", "asset_ids", ...
Extract asset URLs along with asset ids. @param asset_ids: List of ids to get URLs for. @type assertn: [str] @return: List of dictionaries with asset URLs and ids. @rtype: [{ 'id': '<id>', 'url': '<url>' }]
[ "Extract", "asset", "URLs", "along", "with", "asset", "ids", "." ]
python
train
joshourisman/django-tablib
django_tablib/views.py
https://github.com/joshourisman/django-tablib/blob/85b0751fa222a0498aa186714f840b1171a150f9/django_tablib/views.py#L39-L98
def generic_export(request, model_name=None): """ Generic view configured through settings.TABLIB_MODELS Usage: 1. Add the view to ``urlpatterns`` in ``urls.py``:: url(r'export/(?P<model_name>[^/]+)/$', "django_tablib.views.generic_export"), 2. Create the ``setti...
[ "def", "generic_export", "(", "request", ",", "model_name", "=", "None", ")", ":", "if", "model_name", "not", "in", "settings", ".", "TABLIB_MODELS", ":", "raise", "Http404", "(", ")", "model", "=", "get_model", "(", "*", "model_name", ".", "split", "(", ...
Generic view configured through settings.TABLIB_MODELS Usage: 1. Add the view to ``urlpatterns`` in ``urls.py``:: url(r'export/(?P<model_name>[^/]+)/$', "django_tablib.views.generic_export"), 2. Create the ``settings.TABLIB_MODELS`` dictionary using model names ...
[ "Generic", "view", "configured", "through", "settings", ".", "TABLIB_MODELS" ]
python
train
brainiak/brainiak
brainiak/funcalign/srm.py
https://github.com/brainiak/brainiak/blob/408f12dec2ff56559a26873a848a09e4c8facfeb/brainiak/funcalign/srm.py#L385-L413
def transform_subject(self, X): """Transform a new subject using the existing model. The subject is assumed to have recieved equivalent stimulation Parameters ---------- X : 2D array, shape=[voxels, timepoints] The fMRI data of the new subject. Returns ...
[ "def", "transform_subject", "(", "self", ",", "X", ")", ":", "# Check if the model exist", "if", "hasattr", "(", "self", ",", "'w_'", ")", "is", "False", ":", "raise", "NotFittedError", "(", "\"The model fit has not been run yet.\"", ")", "# Check the number of TRs in...
Transform a new subject using the existing model. The subject is assumed to have recieved equivalent stimulation Parameters ---------- X : 2D array, shape=[voxels, timepoints] The fMRI data of the new subject. Returns ------- w : 2D array, shape=[v...
[ "Transform", "a", "new", "subject", "using", "the", "existing", "model", ".", "The", "subject", "is", "assumed", "to", "have", "recieved", "equivalent", "stimulation" ]
python
train
lrq3000/pyFileFixity
pyFileFixity/lib/profilers/visual/kthread.py
https://github.com/lrq3000/pyFileFixity/blob/fd5ef23bb13835faf1e3baa773619b86a1cc9bdf/pyFileFixity/lib/profilers/visual/kthread.py#L49-L53
def __run(self): """Hacked run function, which installs the trace.""" sys.settrace(self.globaltrace) self.__run_backup() self.run = self.__run_backup
[ "def", "__run", "(", "self", ")", ":", "sys", ".", "settrace", "(", "self", ".", "globaltrace", ")", "self", ".", "__run_backup", "(", ")", "self", ".", "run", "=", "self", ".", "__run_backup" ]
Hacked run function, which installs the trace.
[ "Hacked", "run", "function", "which", "installs", "the", "trace", "." ]
python
train
SeabornGames/Table
seaborn_table/table.py
https://github.com/SeabornGames/Table/blob/0c474ef2fb00db0e7cf47e8af91e3556c2e7485a/seaborn_table/table.py#L1659-L1673
def _html_link_cells(self): """ This will return a new table with cell linked with their columns that have <Link> in the name :return: """ new_table = self.copy() for row in new_table: for c in new_table.columns: link = '%s <Link>' % c ...
[ "def", "_html_link_cells", "(", "self", ")", ":", "new_table", "=", "self", ".", "copy", "(", ")", "for", "row", "in", "new_table", ":", "for", "c", "in", "new_table", ".", "columns", ":", "link", "=", "'%s <Link>'", "%", "c", "if", "row", ".", "get"...
This will return a new table with cell linked with their columns that have <Link> in the name :return:
[ "This", "will", "return", "a", "new", "table", "with", "cell", "linked", "with", "their", "columns", "that", "have", "<Link", ">", "in", "the", "name", ":", "return", ":" ]
python
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/gcc.py
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/gcc.py#L66-L94
def detect_version(env, cc): """Return the version of the GNU compiler, or None if it is not a GNU compiler.""" cc = env.subst(cc) if not cc: return None version = None #pipe = SCons.Action._subproc(env, SCons.Util.CLVar(cc) + ['-dumpversion'], pipe = SCons.Action._subproc(env, SCons.Uti...
[ "def", "detect_version", "(", "env", ",", "cc", ")", ":", "cc", "=", "env", ".", "subst", "(", "cc", ")", "if", "not", "cc", ":", "return", "None", "version", "=", "None", "#pipe = SCons.Action._subproc(env, SCons.Util.CLVar(cc) + ['-dumpversion'],", "pipe", "="...
Return the version of the GNU compiler, or None if it is not a GNU compiler.
[ "Return", "the", "version", "of", "the", "GNU", "compiler", "or", "None", "if", "it", "is", "not", "a", "GNU", "compiler", "." ]
python
train
python-astrodynamics/spacetrack
spacetrack/base.py
https://github.com/python-astrodynamics/spacetrack/blob/18f63b7de989a31b983d140a11418e01bd6fd398/spacetrack/base.py#L632-L637
def get_predicates(self, class_): """Proxy ``get_predicates`` to client with stored request controller. """ return self.client.get_predicates( class_=class_, controller=self.controller)
[ "def", "get_predicates", "(", "self", ",", "class_", ")", ":", "return", "self", ".", "client", ".", "get_predicates", "(", "class_", "=", "class_", ",", "controller", "=", "self", ".", "controller", ")" ]
Proxy ``get_predicates`` to client with stored request controller.
[ "Proxy", "get_predicates", "to", "client", "with", "stored", "request", "controller", "." ]
python
train
urschrei/Circles
Circles/circles.py
https://github.com/urschrei/Circles/blob/5aab401b470935e816a28d7ba817eb72f9344672/Circles/circles.py#L30-L95
def _gccalc(lon, lat, azimuth, maxdist=None): """ Original javascript on http://williams.best.vwh.net/gccalc.htm Translated into python by Thomas Lecocq This function is a black box, because trigonometry is difficult """ glat1 = lat * np.pi / 180. glon1 = lon * np.pi / 180. s = maxd...
[ "def", "_gccalc", "(", "lon", ",", "lat", ",", "azimuth", ",", "maxdist", "=", "None", ")", ":", "glat1", "=", "lat", "*", "np", ".", "pi", "/", "180.", "glon1", "=", "lon", "*", "np", ".", "pi", "/", "180.", "s", "=", "maxdist", "/", "1.852243...
Original javascript on http://williams.best.vwh.net/gccalc.htm Translated into python by Thomas Lecocq This function is a black box, because trigonometry is difficult
[ "Original", "javascript", "on", "http", ":", "//", "williams", ".", "best", ".", "vwh", ".", "net", "/", "gccalc", ".", "htm", "Translated", "into", "python", "by", "Thomas", "Lecocq", "This", "function", "is", "a", "black", "box", "because", "trigonometry...
python
train
jsvine/tinyapi
tinyapi/session.py
https://github.com/jsvine/tinyapi/blob/ac2cf0400b2a9b22bd0b1f43b36be99f5d1a787c/tinyapi/session.py#L100-L104
def get_drafts(self, **kwargs): """Same as Session.get_messages, but where ``statuses=["draft"]``.""" default_kwargs = { "order": "updated_at desc" } default_kwargs.update(kwargs) return self.get_messages(statuses=["draft"], **default_kwargs)
[ "def", "get_drafts", "(", "self", ",", "*", "*", "kwargs", ")", ":", "default_kwargs", "=", "{", "\"order\"", ":", "\"updated_at desc\"", "}", "default_kwargs", ".", "update", "(", "kwargs", ")", "return", "self", ".", "get_messages", "(", "statuses", "=", ...
Same as Session.get_messages, but where ``statuses=["draft"]``.
[ "Same", "as", "Session", ".", "get_messages", "but", "where", "statuses", "=", "[", "draft", "]", "." ]
python
train
pycontribs/pyrax
pyrax/object_storage.py
https://github.com/pycontribs/pyrax/blob/9ddfd5064b3a292d7337906f3b2d5dce95b50b99/pyrax/object_storage.py#L2674-L2690
def store_object(self, container, obj_name, data, content_type=None, etag=None, content_encoding=None, ttl=None, return_none=False, chunk_size=None, headers=None, metadata=None, extra_info=None): """ Creates a new object in the specified container, and populates it with t...
[ "def", "store_object", "(", "self", ",", "container", ",", "obj_name", ",", "data", ",", "content_type", "=", "None", ",", "etag", "=", "None", ",", "content_encoding", "=", "None", ",", "ttl", "=", "None", ",", "return_none", "=", "False", ",", "chunk_s...
Creates a new object in the specified container, and populates it with the given data. A StorageObject reference to the uploaded file will be returned, unless 'return_none' is set to True. The 'extra_info' parameter is included for backwards compatibility. It is no longer used at all, a...
[ "Creates", "a", "new", "object", "in", "the", "specified", "container", "and", "populates", "it", "with", "the", "given", "data", ".", "A", "StorageObject", "reference", "to", "the", "uploaded", "file", "will", "be", "returned", "unless", "return_none", "is", ...
python
train
jilljenn/tryalgo
tryalgo/dfs.py
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/dfs.py#L110-L136
def find_cycle(graph): """find a cycle in an undirected graph :param graph: undirected graph in listlist or listdict format :returns: list of vertices in a cycle or None :complexity: `O(|V|+|E|)` """ n = len(graph) prec = [None] * n # ancestor marks for visited vertices for u in range(...
[ "def", "find_cycle", "(", "graph", ")", ":", "n", "=", "len", "(", "graph", ")", "prec", "=", "[", "None", "]", "*", "n", "# ancestor marks for visited vertices", "for", "u", "in", "range", "(", "n", ")", ":", "if", "prec", "[", "u", "]", "is", "No...
find a cycle in an undirected graph :param graph: undirected graph in listlist or listdict format :returns: list of vertices in a cycle or None :complexity: `O(|V|+|E|)`
[ "find", "a", "cycle", "in", "an", "undirected", "graph" ]
python
train
brocade/pynos
pynos/versions/ver_7/ver_7_1_0/yang/brocade_lldp_ext.py
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_7/ver_7_1_0/yang/brocade_lldp_ext.py#L194-L210
def get_lldp_neighbor_detail_output_lldp_neighbor_detail_remote_unnum_ip_address(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_lldp_neighbor_detail = ET.Element("get_lldp_neighbor_detail") config = get_lldp_neighbor_detail output = ET.SubEl...
[ "def", "get_lldp_neighbor_detail_output_lldp_neighbor_detail_remote_unnum_ip_address", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "get_lldp_neighbor_detail", "=", "ET", ".", "Element", "(", "\"get_lldp_...
Auto Generated Code
[ "Auto", "Generated", "Code" ]
python
train
openpaperwork/paperwork-backend
paperwork_backend/docsearch.py
https://github.com/openpaperwork/paperwork-backend/blob/114b831e94e039e68b339751fd18250877abad76/paperwork_backend/docsearch.py#L216-L222
def del_doc(self, doc): """ Delete a document """ logger.info("Removing doc from the index: %s" % doc) doc = doc.clone() # make sure it can be serialized safely self.docsearch.index.del_doc(doc)
[ "def", "del_doc", "(", "self", ",", "doc", ")", ":", "logger", ".", "info", "(", "\"Removing doc from the index: %s\"", "%", "doc", ")", "doc", "=", "doc", ".", "clone", "(", ")", "# make sure it can be serialized safely", "self", ".", "docsearch", ".", "index...
Delete a document
[ "Delete", "a", "document" ]
python
train
pantsbuild/pants
src/python/pants/engine/legacy/structs.py
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/engine/legacy/structs.py#L376-L381
def to_path_globs(self, relpath, conjunction): """Return a PathGlobs representing the included and excluded Files for these patterns.""" return PathGlobs( include=tuple(os.path.join(relpath, glob) for glob in self._file_globs), exclude=tuple(os.path.join(relpath, exclude) for exclude in self._exclud...
[ "def", "to_path_globs", "(", "self", ",", "relpath", ",", "conjunction", ")", ":", "return", "PathGlobs", "(", "include", "=", "tuple", "(", "os", ".", "path", ".", "join", "(", "relpath", ",", "glob", ")", "for", "glob", "in", "self", ".", "_file_glob...
Return a PathGlobs representing the included and excluded Files for these patterns.
[ "Return", "a", "PathGlobs", "representing", "the", "included", "and", "excluded", "Files", "for", "these", "patterns", "." ]
python
train
lrq3000/pyFileFixity
pyFileFixity/lib/profilers/visual/pympler/web.py
https://github.com/lrq3000/pyFileFixity/blob/fd5ef23bb13835faf1e3baa773619b86a1cc9bdf/pyFileFixity/lib/profilers/visual/pympler/web.py#L86-L89
def get_obj(ref): """Get object from string reference.""" oid = int(ref) return server.id2ref.get(oid) or server.id2obj[oid]
[ "def", "get_obj", "(", "ref", ")", ":", "oid", "=", "int", "(", "ref", ")", "return", "server", ".", "id2ref", ".", "get", "(", "oid", ")", "or", "server", ".", "id2obj", "[", "oid", "]" ]
Get object from string reference.
[ "Get", "object", "from", "string", "reference", "." ]
python
train
LeastAuthority/txkube
src/txkube/_swagger.py
https://github.com/LeastAuthority/txkube/blob/a7e555d00535ff787d4b1204c264780da40cf736/src/txkube/_swagger.py#L143-L155
def to_document(self): """ Serialize this specification to a JSON-compatible object representing a Swagger specification. """ return dict( info=thaw(self.info), paths=thaw(self.paths), definitions=thaw(self.definitions), securityDef...
[ "def", "to_document", "(", "self", ")", ":", "return", "dict", "(", "info", "=", "thaw", "(", "self", ".", "info", ")", ",", "paths", "=", "thaw", "(", "self", ".", "paths", ")", ",", "definitions", "=", "thaw", "(", "self", ".", "definitions", ")"...
Serialize this specification to a JSON-compatible object representing a Swagger specification.
[ "Serialize", "this", "specification", "to", "a", "JSON", "-", "compatible", "object", "representing", "a", "Swagger", "specification", "." ]
python
train
collectiveacuity/labPack
labpack/parsing/conversion.py
https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/parsing/conversion.py#L20-L30
def _to_python(input_string): ''' a helper method to convert camelcase to python''' python_string = '' for i in range(len(input_string)): if not python_string: python_string += input_string[i].lower() elif input_string[i].isupper(): python_string += '_%s' % input_stri...
[ "def", "_to_python", "(", "input_string", ")", ":", "python_string", "=", "''", "for", "i", "in", "range", "(", "len", "(", "input_string", ")", ")", ":", "if", "not", "python_string", ":", "python_string", "+=", "input_string", "[", "i", "]", ".", "lowe...
a helper method to convert camelcase to python
[ "a", "helper", "method", "to", "convert", "camelcase", "to", "python" ]
python
train
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/textio.py
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/textio.py#L1135-L1155
def justify(self, column, direction): """ Make the text in a column left or right justified. @type column: int @param column: Index of the column. @type direction: int @param direction: C{-1} to justify left, C{1} to justify right. @ra...
[ "def", "justify", "(", "self", ",", "column", ",", "direction", ")", ":", "if", "direction", "==", "-", "1", ":", "self", ".", "__width", "[", "column", "]", "=", "abs", "(", "self", ".", "__width", "[", "column", "]", ")", "elif", "direction", "==...
Make the text in a column left or right justified. @type column: int @param column: Index of the column. @type direction: int @param direction: C{-1} to justify left, C{1} to justify right. @raise IndexError: Bad column index. @raise ValueErro...
[ "Make", "the", "text", "in", "a", "column", "left", "or", "right", "justified", "." ]
python
train
Jaymon/endpoints
endpoints/http.py
https://github.com/Jaymon/endpoints/blob/2f1c4ae2c69a168e69447d3d8395ada7becaa5fb/endpoints/http.py#L840-L848
def access_token(self): """return an Oauth 2.0 Bearer access token if it can be found""" access_token = self.get_auth_bearer() if not access_token: access_token = self.query_kwargs.get('access_token', '') if not access_token: access_token = self.body_kwarg...
[ "def", "access_token", "(", "self", ")", ":", "access_token", "=", "self", ".", "get_auth_bearer", "(", ")", "if", "not", "access_token", ":", "access_token", "=", "self", ".", "query_kwargs", ".", "get", "(", "'access_token'", ",", "''", ")", "if", "not",...
return an Oauth 2.0 Bearer access token if it can be found
[ "return", "an", "Oauth", "2", ".", "0", "Bearer", "access", "token", "if", "it", "can", "be", "found" ]
python
train
numberly/appnexus-client
appnexus/cursor.py
https://github.com/numberly/appnexus-client/blob/d6a813449ab6fd93bfbceaa937a168fa9a78b890/appnexus/cursor.py#L74-L79
def first(self): """Extract the first AppNexus object present in the response""" page = self.get_page(num_elements=1) data = self.extract_data(page) if data: return data[0]
[ "def", "first", "(", "self", ")", ":", "page", "=", "self", ".", "get_page", "(", "num_elements", "=", "1", ")", "data", "=", "self", ".", "extract_data", "(", "page", ")", "if", "data", ":", "return", "data", "[", "0", "]" ]
Extract the first AppNexus object present in the response
[ "Extract", "the", "first", "AppNexus", "object", "present", "in", "the", "response" ]
python
train
totalgood/pugnlp
src/pugnlp/util.py
https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L460-L488
def generate_batches(sequence, batch_len=1, allow_partial=True, ignore_errors=True, verbosity=1): """Iterate through a sequence (or generator) in batches of length `batch_len` http://stackoverflow.com/a/761125/623735 >>> [batch for batch in generate_batches(range(7), 3)] [[0, 1, 2], [3, 4, 5], [6]] ...
[ "def", "generate_batches", "(", "sequence", ",", "batch_len", "=", "1", ",", "allow_partial", "=", "True", ",", "ignore_errors", "=", "True", ",", "verbosity", "=", "1", ")", ":", "it", "=", "iter", "(", "sequence", ")", "last_value", "=", "False", "# An...
Iterate through a sequence (or generator) in batches of length `batch_len` http://stackoverflow.com/a/761125/623735 >>> [batch for batch in generate_batches(range(7), 3)] [[0, 1, 2], [3, 4, 5], [6]]
[ "Iterate", "through", "a", "sequence", "(", "or", "generator", ")", "in", "batches", "of", "length", "batch_len" ]
python
train
proteanhq/protean
src/protean/core/repository/factory.py
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/repository/factory.py#L66-L83
def _find_entity_in_records_by_class_name(self, entity_name): """Fetch by Entity Name in values""" records = { key: value for (key, value) in self._registry.items() if value.name == entity_name } # If more than one record was found, we are dealing with...
[ "def", "_find_entity_in_records_by_class_name", "(", "self", ",", "entity_name", ")", ":", "records", "=", "{", "key", ":", "value", "for", "(", "key", ",", "value", ")", "in", "self", ".", "_registry", ".", "items", "(", ")", "if", "value", ".", "name",...
Fetch by Entity Name in values
[ "Fetch", "by", "Entity", "Name", "in", "values" ]
python
train
knipknap/SpiffWorkflow
SpiffWorkflow/specs/Join.py
https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/specs/Join.py#L187-L202
def _start(self, my_task, force=False): """ Checks whether the preconditions for going to READY state are met. Returns True if the threshold was reached, False otherwise. Also returns the list of tasks that yet need to be completed. """ # If the threshold was already reac...
[ "def", "_start", "(", "self", ",", "my_task", ",", "force", "=", "False", ")", ":", "# If the threshold was already reached, there is nothing else to do.", "if", "my_task", ".", "_has_state", "(", "Task", ".", "COMPLETED", ")", ":", "return", "True", ",", "None", ...
Checks whether the preconditions for going to READY state are met. Returns True if the threshold was reached, False otherwise. Also returns the list of tasks that yet need to be completed.
[ "Checks", "whether", "the", "preconditions", "for", "going", "to", "READY", "state", "are", "met", ".", "Returns", "True", "if", "the", "threshold", "was", "reached", "False", "otherwise", ".", "Also", "returns", "the", "list", "of", "tasks", "that", "yet", ...
python
valid
wonambi-python/wonambi
wonambi/attr/chan.py
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/attr/chan.py#L362-L395
def assign_region_to_channels(channels, anat, parc_type='aparc', max_approx=3, exclude_regions=None): """Assign a brain region based on the channel location. Parameters ---------- channels : instance of wonambi.attr.chan.Channels channels to assign regions to a...
[ "def", "assign_region_to_channels", "(", "channels", ",", "anat", ",", "parc_type", "=", "'aparc'", ",", "max_approx", "=", "3", ",", "exclude_regions", "=", "None", ")", ":", "for", "one_chan", "in", "channels", ".", "chan", ":", "one_region", ",", "approx"...
Assign a brain region based on the channel location. Parameters ---------- channels : instance of wonambi.attr.chan.Channels channels to assign regions to anat : instance of wonambi.attr.anat.Freesurfer anatomical information taken from freesurfer. parc_type : str 'aparc', '...
[ "Assign", "a", "brain", "region", "based", "on", "the", "channel", "location", "." ]
python
train
Metatab/metapack
metapack/package/core.py
https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/package/core.py#L325-L370
def _clean_doc(self, doc=None): """Clean the doc before writing it, removing unnecessary properties and doing other operations.""" if doc is None: doc = self.doc resources = doc['Resources'] # We don't need these anymore because all of the data written into the package is ...
[ "def", "_clean_doc", "(", "self", ",", "doc", "=", "None", ")", ":", "if", "doc", "is", "None", ":", "doc", "=", "self", ".", "doc", "resources", "=", "doc", "[", "'Resources'", "]", "# We don't need these anymore because all of the data written into the package i...
Clean the doc before writing it, removing unnecessary properties and doing other operations.
[ "Clean", "the", "doc", "before", "writing", "it", "removing", "unnecessary", "properties", "and", "doing", "other", "operations", "." ]
python
train
erichiggins/gaek
gaek/ndb_json.py
https://github.com/erichiggins/gaek/blob/eb6bbc2d2688302834f97fd97891592e8b9659f2/gaek/ndb_json.py#L162-L169
def decode(self, val): """Override of the default decode method that also uses decode_date.""" # First try the date decoder. new_val = self.decode_date(val) if val != new_val: return new_val # Fall back to the default decoder. return json.JSONDecoder.decode(self, val)
[ "def", "decode", "(", "self", ",", "val", ")", ":", "# First try the date decoder.", "new_val", "=", "self", ".", "decode_date", "(", "val", ")", "if", "val", "!=", "new_val", ":", "return", "new_val", "# Fall back to the default decoder.", "return", "json", "."...
Override of the default decode method that also uses decode_date.
[ "Override", "of", "the", "default", "decode", "method", "that", "also", "uses", "decode_date", "." ]
python
test
DataDog/integrations-core
yarn/datadog_checks/yarn/yarn.py
https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/yarn/datadog_checks/yarn/yarn.py#L310-L319
def _set_metric(self, metric_name, metric_type, value, tags=None, device_name=None): """ Set a metric """ if metric_type == GAUGE: self.gauge(metric_name, value, tags=tags, device_name=device_name) elif metric_type == INCREMENT: self.increment(metric_name,...
[ "def", "_set_metric", "(", "self", ",", "metric_name", ",", "metric_type", ",", "value", ",", "tags", "=", "None", ",", "device_name", "=", "None", ")", ":", "if", "metric_type", "==", "GAUGE", ":", "self", ".", "gauge", "(", "metric_name", ",", "value",...
Set a metric
[ "Set", "a", "metric" ]
python
train
mpdavis/python-jose
jose/jwt.py
https://github.com/mpdavis/python-jose/blob/deea7600eeea47aeb1bf5053a96de51cf2b9c639/jose/jwt.py#L294-L321
def _validate_exp(claims, leeway=0): """Validates that the 'exp' claim is valid. The "exp" (expiration time) claim identifies the expiration time on or after which the JWT MUST NOT be accepted for processing. The processing of the "exp" claim requires that the current date/time MUST be before the ...
[ "def", "_validate_exp", "(", "claims", ",", "leeway", "=", "0", ")", ":", "if", "'exp'", "not", "in", "claims", ":", "return", "try", ":", "exp", "=", "int", "(", "claims", "[", "'exp'", "]", ")", "except", "ValueError", ":", "raise", "JWTClaimsError",...
Validates that the 'exp' claim is valid. The "exp" (expiration time) claim identifies the expiration time on or after which the JWT MUST NOT be accepted for processing. The processing of the "exp" claim requires that the current date/time MUST be before the expiration date/time listed in the "exp" cla...
[ "Validates", "that", "the", "exp", "claim", "is", "valid", "." ]
python
train
santoshphilip/eppy
eppy/idf_helpers.py
https://github.com/santoshphilip/eppy/blob/55410ff7c11722f35bc4331ff5e00a0b86f787e1/eppy/idf_helpers.py#L44-L60
def getobject_use_prevfield(idf, idfobject, fieldname): """field=object_name, prev_field=object_type. Return the object""" if not fieldname.endswith("Name"): return None # test if prevfieldname ends with "Object_Type" fdnames = idfobject.fieldnames ifieldname = fdnames.index(fieldname) p...
[ "def", "getobject_use_prevfield", "(", "idf", ",", "idfobject", ",", "fieldname", ")", ":", "if", "not", "fieldname", ".", "endswith", "(", "\"Name\"", ")", ":", "return", "None", "# test if prevfieldname ends with \"Object_Type\"", "fdnames", "=", "idfobject", ".",...
field=object_name, prev_field=object_type. Return the object
[ "field", "=", "object_name", "prev_field", "=", "object_type", ".", "Return", "the", "object" ]
python
train
AmesCornish/buttersink
buttersink/BestDiffs.py
https://github.com/AmesCornish/buttersink/blob/5cc37e30d9f8071fcf3497dca8b8a91b910321ea/buttersink/BestDiffs.py#L313-L322
def _prune(self): """ Get rid of all intermediate nodes that aren't needed. """ done = False while not done: done = True for node in [node for node in self.nodes.values() if node.intermediate]: if not [dep for dep in self.nodes.values() if dep.previous == ...
[ "def", "_prune", "(", "self", ")", ":", "done", "=", "False", "while", "not", "done", ":", "done", "=", "True", "for", "node", "in", "[", "node", "for", "node", "in", "self", ".", "nodes", ".", "values", "(", ")", "if", "node", ".", "intermediate",...
Get rid of all intermediate nodes that aren't needed.
[ "Get", "rid", "of", "all", "intermediate", "nodes", "that", "aren", "t", "needed", "." ]
python
train
openstack/networking-cisco
networking_cisco/plugins/cisco/cfg_agent/cfg_agent.py
https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/cfg_agent/cfg_agent.py#L341-L351
def hosting_devices_unassigned_from_cfg_agent(self, context, payload): """Deal with hosting devices unassigned from this config agent.""" try: if payload['hosting_device_ids']: #TODO(hareeshp): implement unassignment of hosting devices pass except KeyE...
[ "def", "hosting_devices_unassigned_from_cfg_agent", "(", "self", ",", "context", ",", "payload", ")", ":", "try", ":", "if", "payload", "[", "'hosting_device_ids'", "]", ":", "#TODO(hareeshp): implement unassignment of hosting devices", "pass", "except", "KeyError", "as",...
Deal with hosting devices unassigned from this config agent.
[ "Deal", "with", "hosting", "devices", "unassigned", "from", "this", "config", "agent", "." ]
python
train
henzk/featuremonkey
featuremonkey/importhooks.py
https://github.com/henzk/featuremonkey/blob/e44414fc68427bcd71ad33ec2d816da0dd78eefa/featuremonkey/importhooks.py#L156-L170
def remove(cls, module_name): """ drop a previously created guard on ``module_name`` if the module is not guarded, then this is a no-op. """ module_guards = cls._guards.get(module_name, False) if module_guards: module_guards.pop() cls._num_entries ...
[ "def", "remove", "(", "cls", ",", "module_name", ")", ":", "module_guards", "=", "cls", ".", "_guards", ".", "get", "(", "module_name", ",", "False", ")", "if", "module_guards", ":", "module_guards", ".", "pop", "(", ")", "cls", ".", "_num_entries", "-="...
drop a previously created guard on ``module_name`` if the module is not guarded, then this is a no-op.
[ "drop", "a", "previously", "created", "guard", "on", "module_name", "if", "the", "module", "is", "not", "guarded", "then", "this", "is", "a", "no", "-", "op", "." ]
python
train
metagriffin/fso
fso/filesystemoverlay.py
https://github.com/metagriffin/fso/blob/c37701fbfdfde359a2044eb9420abe569a7b35e4/fso/filesystemoverlay.py#L390-L395
def fso_lexists(self, path): 'overlays os.path.lexists()' try: return self._lexists(self.deref(path, to_parent=True)) except os.error: return False
[ "def", "fso_lexists", "(", "self", ",", "path", ")", ":", "try", ":", "return", "self", ".", "_lexists", "(", "self", ".", "deref", "(", "path", ",", "to_parent", "=", "True", ")", ")", "except", "os", ".", "error", ":", "return", "False" ]
overlays os.path.lexists()
[ "overlays", "os", ".", "path", ".", "lexists", "()" ]
python
valid
eqcorrscan/EQcorrscan
eqcorrscan/core/match_filter.py
https://github.com/eqcorrscan/EQcorrscan/blob/3121b4aca801ee5d38f56ca297ce1c0f9515d9ff/eqcorrscan/core/match_filter.py#L3245-L3253
def _templates_match(t, family_file): """ Return True if a tribe matches a family file path. :type t: Tribe :type family_file: str :return: bool """ return t.name == family_file.split(os.sep)[-1].split('_detections.csv')[0]
[ "def", "_templates_match", "(", "t", ",", "family_file", ")", ":", "return", "t", ".", "name", "==", "family_file", ".", "split", "(", "os", ".", "sep", ")", "[", "-", "1", "]", ".", "split", "(", "'_detections.csv'", ")", "[", "0", "]" ]
Return True if a tribe matches a family file path. :type t: Tribe :type family_file: str :return: bool
[ "Return", "True", "if", "a", "tribe", "matches", "a", "family", "file", "path", "." ]
python
train