repo
stringlengths
7
55
path
stringlengths
4
223
url
stringlengths
87
315
code
stringlengths
75
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
avg_line_len
float64
7.91
980
nickpandolfi/Cyther
cyther/instructions.py
https://github.com/nickpandolfi/Cyther/blob/9fb0bd77af594008aa6ee8af460aa8c953abf5bc/cyther/instructions.py#L53-L82
def processAndSetDefaults(self): """ The heart of the 'Instruction' object. This method will make sure that all fields not entered will be defaulted to a correct value. Also checks for incongruities in the data entered, if it was by the user. """ # INPUT, OUTPUT, GIVEN + ...
[ "def", "processAndSetDefaults", "(", "self", ")", ":", "# INPUT, OUTPUT, GIVEN + BUILDABLE DEPS", "if", "not", "self", ".", "input", ":", "raise", "ValueError", "(", "NO_INPUT_FILE", ")", "if", "not", "self", ".", "output", ":", "# Build directory must exist, right?",...
The heart of the 'Instruction' object. This method will make sure that all fields not entered will be defaulted to a correct value. Also checks for incongruities in the data entered, if it was by the user.
[ "The", "heart", "of", "the", "Instruction", "object", ".", "This", "method", "will", "make", "sure", "that", "all", "fields", "not", "entered", "will", "be", "defaulted", "to", "a", "correct", "value", ".", "Also", "checks", "for", "incongruities", "in", "...
python
train
36.9
LudovicRousseau/pyscard
smartcard/wx/CardAndReaderTreePanel.py
https://github.com/LudovicRousseau/pyscard/blob/62e675028086c75656444cc21d563d9f08ebf8e7/smartcard/wx/CardAndReaderTreePanel.py#L177-L190
def GetATR(self, reader): """Return the ATR of the card inserted into the reader.""" atr = "no card inserted" try: if not type(reader) is str: connection = reader.createConnection() connection.connect() atr = toHexString(connection.getA...
[ "def", "GetATR", "(", "self", ",", "reader", ")", ":", "atr", "=", "\"no card inserted\"", "try", ":", "if", "not", "type", "(", "reader", ")", "is", "str", ":", "connection", "=", "reader", ".", "createConnection", "(", ")", "connection", ".", "connect"...
Return the ATR of the card inserted into the reader.
[ "Return", "the", "ATR", "of", "the", "card", "inserted", "into", "the", "reader", "." ]
python
train
34.071429
gplepage/lsqfit
src/lsqfit/_extras.py
https://github.com/gplepage/lsqfit/blob/6a57fd687632c175fccb47d8e8e943cda5e9ce9d/src/lsqfit/_extras.py#L1394-L1412
def process_dataset(dataset, models, **kargs): """ Convert ``dataset`` to processed data using ``models``. :class:`gvar.dataset.Dataset` (or similar dictionary) object ``dataset`` is processed by each model in list ``models``, and the results collected into a new dictionary ``pdata`` fo...
[ "def", "process_dataset", "(", "dataset", ",", "models", ",", "*", "*", "kargs", ")", ":", "dset", "=", "collections", ".", "OrderedDict", "(", ")", "for", "m", "in", "MultiFitter", ".", "flatten_models", "(", "models", ")", ":", "dset", "[", "m", ".",...
Convert ``dataset`` to processed data using ``models``. :class:`gvar.dataset.Dataset` (or similar dictionary) object ``dataset`` is processed by each model in list ``models``, and the results collected into a new dictionary ``pdata`` for use in :meth:`MultiFitter.lsqfit` and :meth:`Mult...
[ "Convert", "dataset", "to", "processed", "data", "using", "models", "." ]
python
train
49.631579
jmcgeheeiv/pyfakefs
pyfakefs/fake_filesystem.py
https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/fake_filesystem.py#L1311-L1329
def _add_open_file(self, file_obj): """Add file_obj to the list of open files on the filesystem. Used internally to manage open files. The position in the open_files array is the file descriptor number. Args: file_obj: File object to be added to open files list. Re...
[ "def", "_add_open_file", "(", "self", ",", "file_obj", ")", ":", "if", "self", ".", "_free_fd_heap", ":", "open_fd", "=", "heapq", ".", "heappop", "(", "self", ".", "_free_fd_heap", ")", "self", ".", "open_files", "[", "open_fd", "]", "=", "[", "file_obj...
Add file_obj to the list of open files on the filesystem. Used internally to manage open files. The position in the open_files array is the file descriptor number. Args: file_obj: File object to be added to open files list. Returns: File descriptor number for t...
[ "Add", "file_obj", "to", "the", "list", "of", "open", "files", "on", "the", "filesystem", ".", "Used", "internally", "to", "manage", "open", "files", "." ]
python
train
32.842105
google/grr
grr/server/grr_response_server/gui/api_plugins/config.py
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/gui/api_plugins/config.py#L102-L127
def Handle(self, unused_args, token=None): """Build the data structure representing the config.""" sections = {} for descriptor in config.CONFIG.type_infos: if descriptor.section in sections: continue section_data = {} for parameter in self._ListParametersInSection(descriptor.sec...
[ "def", "Handle", "(", "self", ",", "unused_args", ",", "token", "=", "None", ")", ":", "sections", "=", "{", "}", "for", "descriptor", "in", "config", ".", "CONFIG", ".", "type_infos", ":", "if", "descriptor", ".", "section", "in", "sections", ":", "co...
Build the data structure representing the config.
[ "Build", "the", "data", "structure", "representing", "the", "config", "." ]
python
train
31.192308
Azure/azure-storage-python
azure-storage-file/azure/storage/file/fileservice.py
https://github.com/Azure/azure-storage-python/blob/52327354b192cbcf6b7905118ec6b5d57fa46275/azure-storage-file/azure/storage/file/fileservice.py#L2336-L2391
def update_range(self, share_name, directory_name, file_name, data, start_range, end_range, validate_content=False, timeout=None): ''' Writes the bytes specified by the request body into the specified range. :param str share_name: Name of existing share...
[ "def", "update_range", "(", "self", ",", "share_name", ",", "directory_name", ",", "file_name", ",", "data", ",", "start_range", ",", "end_range", ",", "validate_content", "=", "False", ",", "timeout", "=", "None", ")", ":", "_validate_not_none", "(", "'share_...
Writes the bytes specified by the request body into the specified range. :param str share_name: Name of existing share. :param str directory_name: The path to the directory. :param str file_name: Name of existing file. :param bytes data: ...
[ "Writes", "the", "bytes", "specified", "by", "the", "request", "body", "into", "the", "specified", "range", ".", ":", "param", "str", "share_name", ":", "Name", "of", "existing", "share", ".", ":", "param", "str", "directory_name", ":", "The", "path", "to"...
python
train
44.482143
zsimic/runez
src/runez/click.py
https://github.com/zsimic/runez/blob/14363b719a1aae1528859a501a22d075ce0abfcc/src/runez/click.py#L42-L46
def config(*args, **attrs): """Override configuration""" attrs.setdefault("metavar", "KEY=VALUE") attrs.setdefault("multiple", True) return option(config, *args, **attrs)
[ "def", "config", "(", "*", "args", ",", "*", "*", "attrs", ")", ":", "attrs", ".", "setdefault", "(", "\"metavar\"", ",", "\"KEY=VALUE\"", ")", "attrs", ".", "setdefault", "(", "\"multiple\"", ",", "True", ")", "return", "option", "(", "config", ",", "...
Override configuration
[ "Override", "configuration" ]
python
train
36.4
esheldon/fitsio
fitsio/fitslib.py
https://github.com/esheldon/fitsio/blob/a6f07919f457a282fe240adad9d2c30906b71a15/fitsio/fitslib.py#L1356-L1406
def descr2tabledef(descr, table_type='binary', write_bitcols=False): """ Create a FITS table def from the input numpy descriptor. parameters ---------- descr: list A numpy recarray type descriptor array.dtype.descr returns ------- names, formats, dims: tuple of lists T...
[ "def", "descr2tabledef", "(", "descr", ",", "table_type", "=", "'binary'", ",", "write_bitcols", "=", "False", ")", ":", "names", "=", "[", "]", "formats", "=", "[", "]", "dims", "=", "[", "]", "for", "d", "in", "descr", ":", "\"\"\"\n npy_dtype =...
Create a FITS table def from the input numpy descriptor. parameters ---------- descr: list A numpy recarray type descriptor array.dtype.descr returns ------- names, formats, dims: tuple of lists These are the ttyp, tform and tdim header entries for each field. dim ent...
[ "Create", "a", "FITS", "table", "def", "from", "the", "input", "numpy", "descriptor", "." ]
python
train
26.333333
wummel/linkchecker
linkcheck/parser/__init__.py
https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/parser/__init__.py#L138-L142
def parse_firefox (url_data): """Parse a Firefox3 bookmark file.""" filename = url_data.get_os_filename() for url, name in firefox.parse_bookmark_file(filename): url_data.add_url(url, name=name)
[ "def", "parse_firefox", "(", "url_data", ")", ":", "filename", "=", "url_data", ".", "get_os_filename", "(", ")", "for", "url", ",", "name", "in", "firefox", ".", "parse_bookmark_file", "(", "filename", ")", ":", "url_data", ".", "add_url", "(", "url", ","...
Parse a Firefox3 bookmark file.
[ "Parse", "a", "Firefox3", "bookmark", "file", "." ]
python
train
42
Arubacloud/pyArubaCloud
ArubaCloud/ReverseDns/ReverseDns.py
https://github.com/Arubacloud/pyArubaCloud/blob/ec4aecd8ca342b1e1a4f16b7cc87cb5e697cfcd4/ArubaCloud/ReverseDns/ReverseDns.py#L36-L45
def reset(self, addresses): """ Remove all PTR records from the given address :type addresses: List[str] :param addresses: (List[str]) The IP Address to reset :return: (bool) True in case of success, False in case of failure """ request = self._call(SetEnqueueRese...
[ "def", "reset", "(", "self", ",", "addresses", ")", ":", "request", "=", "self", ".", "_call", "(", "SetEnqueueResetReverseDns", ".", "SetEnqueueResetReverseDns", ",", "IPs", "=", "addresses", ")", "response", "=", "request", ".", "commit", "(", ")", "return...
Remove all PTR records from the given address :type addresses: List[str] :param addresses: (List[str]) The IP Address to reset :return: (bool) True in case of success, False in case of failure
[ "Remove", "all", "PTR", "records", "from", "the", "given", "address", ":", "type", "addresses", ":", "List", "[", "str", "]", ":", "param", "addresses", ":", "(", "List", "[", "str", "]", ")", "The", "IP", "Address", "to", "reset", ":", "return", ":"...
python
train
43.5
jkitzes/macroeco
macroeco/empirical/_empirical.py
https://github.com/jkitzes/macroeco/blob/ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e/macroeco/empirical/_empirical.py#L807-L860
def _yield_spatial_table(patch, div, spp_col, count_col, x_col, y_col): """ Calculates an empirical spatial table Yields ------- DataFrame Spatial table for each division. See Notes. Notes ----- The spatial table is the precursor to the SAR, EAR, and grid-based commonality ...
[ "def", "_yield_spatial_table", "(", "patch", ",", "div", ",", "spp_col", ",", "count_col", ",", "x_col", ",", "y_col", ")", ":", "# Catch error if you don't use ; after divs in comm_grid in MacroecoDesktop", "try", ":", "div_split_list", "=", "div", ".", "replace", "(...
Calculates an empirical spatial table Yields ------- DataFrame Spatial table for each division. See Notes. Notes ----- The spatial table is the precursor to the SAR, EAR, and grid-based commonality metrics. Each row in the table corresponds to a cell created by a given division...
[ "Calculates", "an", "empirical", "spatial", "table" ]
python
train
35.259259
DataBiosphere/toil
src/toil/job.py
https://github.com/DataBiosphere/toil/blob/a8252277ff814e7bee0971139c2344f88e44b644/src/toil/job.py#L643-L670
def checkJobGraphAcylic(self): """ :raises toil.job.JobGraphDeadlockException: if the connected component \ of jobs containing this job contains any cycles of child/followOn dependencies \ in the *augmented job graph* (see below). Such cycles are not allowed \ in valid job graphs...
[ "def", "checkJobGraphAcylic", "(", "self", ")", ":", "#Get the root jobs", "roots", "=", "self", ".", "getRootJobs", "(", ")", "if", "len", "(", "roots", ")", "==", "0", ":", "raise", "JobGraphDeadlockException", "(", "\"Graph contains no root jobs due to cycles\"",...
:raises toil.job.JobGraphDeadlockException: if the connected component \ of jobs containing this job contains any cycles of child/followOn dependencies \ in the *augmented job graph* (see below). Such cycles are not allowed \ in valid job graphs. A follow-on edge (A, B) between two jobs...
[ ":", "raises", "toil", ".", "job", ".", "JobGraphDeadlockException", ":", "if", "the", "connected", "component", "\\", "of", "jobs", "containing", "this", "job", "contains", "any", "cycles", "of", "child", "/", "followOn", "dependencies", "\\", "in", "the", ...
python
train
45.142857
Skype4Py/Skype4Py
Skype4Py/client.py
https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/client.py#L62-L99
def CreateMenuItem(self, MenuItemId, PluginContext, CaptionText, HintText=u'', IconPath='', Enabled=True, ContactType=pluginContactTypeAll, MultipleContacts=False): """Creates custom menu item in Skype client's "Do More" menus. :Parameters: MenuItemId : unicode ...
[ "def", "CreateMenuItem", "(", "self", ",", "MenuItemId", ",", "PluginContext", ",", "CaptionText", ",", "HintText", "=", "u''", ",", "IconPath", "=", "''", ",", "Enabled", "=", "True", ",", "ContactType", "=", "pluginContactTypeAll", ",", "MultipleContacts", "...
Creates custom menu item in Skype client's "Do More" menus. :Parameters: MenuItemId : unicode Unique identifier for the menu item. PluginContext : `enums`.pluginContext* Menu item context. Allows to choose in which client windows will the menu item appear. ...
[ "Creates", "custom", "menu", "item", "in", "Skype", "client", "s", "Do", "More", "menus", "." ]
python
train
49.105263
saltstack/salt
salt/modules/azurearm_network.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_network.py#L604-L634
def network_security_groups_list(resource_group, **kwargs): ''' .. versionadded:: 2019.2.0 List all network security groups within a resource group. :param resource_group: The resource group name to list network security \ groups within. CLI Example: .. code-block:: bash sal...
[ "def", "network_security_groups_list", "(", "resource_group", ",", "*", "*", "kwargs", ")", ":", "result", "=", "{", "}", "netconn", "=", "__utils__", "[", "'azurearm.get_client'", "]", "(", "'network'", ",", "*", "*", "kwargs", ")", "try", ":", "secgroups",...
.. versionadded:: 2019.2.0 List all network security groups within a resource group. :param resource_group: The resource group name to list network security \ groups within. CLI Example: .. code-block:: bash salt-call azurearm_network.network_security_groups_list testgroup
[ "..", "versionadded", "::", "2019", ".", "2", ".", "0" ]
python
train
28.677419
Genida/django-meerkat
src/meerkat/utils/geolocation.py
https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/utils/geolocation.py#L8-L30
def ip_geoloc(ip, hit_api=True): """ Get IP geolocation. Args: ip (str): IP address to use if no data provided. hit_api (bool): whether to hit api if info not found. Returns: str: latitude and longitude, comma-separated. """ from ..logs.models import IPInfoCheck try...
[ "def", "ip_geoloc", "(", "ip", ",", "hit_api", "=", "True", ")", ":", "from", ".", ".", "logs", ".", "models", "import", "IPInfoCheck", "try", ":", "obj", "=", "IPInfoCheck", ".", "objects", ".", "get", "(", "ip_address", "=", "ip", ")", ".", "ip_inf...
Get IP geolocation. Args: ip (str): IP address to use if no data provided. hit_api (bool): whether to hit api if info not found. Returns: str: latitude and longitude, comma-separated.
[ "Get", "IP", "geolocation", "." ]
python
train
27.130435
AkihikoITOH/capybara
capybara/virtualenv/lib/python2.7/site-packages/setuptools/package_index.py
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/setuptools/package_index.py#L279-L325
def process_url(self, url, retrieve=False): """Evaluate a URL as a possible download, and maybe retrieve it""" if url in self.scanned_urls and not retrieve: return self.scanned_urls[url] = True if not URL_SCHEME(url): self.process_filename(url) return ...
[ "def", "process_url", "(", "self", ",", "url", ",", "retrieve", "=", "False", ")", ":", "if", "url", "in", "self", ".", "scanned_urls", "and", "not", "retrieve", ":", "return", "self", ".", "scanned_urls", "[", "url", "]", "=", "True", "if", "not", "...
Evaluate a URL as a possible download, and maybe retrieve it
[ "Evaluate", "a", "URL", "as", "a", "possible", "download", "and", "maybe", "retrieve", "it" ]
python
test
39.425532
googleapis/google-cloud-python
logging/google/cloud/logging_v2/gapic/config_service_v2_client.py
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging_v2/gapic/config_service_v2_client.py#L88-L92
def sink_path(cls, project, sink): """Return a fully-qualified sink string.""" return google.api_core.path_template.expand( "projects/{project}/sinks/{sink}", project=project, sink=sink )
[ "def", "sink_path", "(", "cls", ",", "project", ",", "sink", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "\"projects/{project}/sinks/{sink}\"", ",", "project", "=", "project", ",", "sink", "=", "sink", ")" ]
Return a fully-qualified sink string.
[ "Return", "a", "fully", "-", "qualified", "sink", "string", "." ]
python
train
43.8
gmdzy2010/dingtalk_sdk_gmdzy2010
dingtalk_sdk_gmdzy2010/base_request.py
https://github.com/gmdzy2010/dingtalk_sdk_gmdzy2010/blob/b06cb1f78f89be9554dcb6101af8bc72718a9ecd/dingtalk_sdk_gmdzy2010/base_request.py#L22-L35
def set_logger(self): """Method to build the base logging system. By default, logging level is set to INFO.""" logger = logging.getLogger(__name__) logger.setLevel(level=logging.INFO) logger_file = os.path.join(self.logs_path, 'dingtalk_sdk.logs') logger_handler = l...
[ "def", "set_logger", "(", "self", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "logger", ".", "setLevel", "(", "level", "=", "logging", ".", "INFO", ")", "logger_file", "=", "os", ".", "path", ".", "join", "(", "self", ...
Method to build the base logging system. By default, logging level is set to INFO.
[ "Method", "to", "build", "the", "base", "logging", "system", ".", "By", "default", "logging", "level", "is", "set", "to", "INFO", "." ]
python
train
45.142857
mohabusama/pyguacamole
guacamole/client.py
https://github.com/mohabusama/pyguacamole/blob/344dccc6cb3a9a045afeaf337677e5d0001aa83a/guacamole/client.py#L117-L122
def send(self, data): """ Send encoded instructions to Guacamole guacd server. """ self.logger.debug('Sending data: %s' % data) self.client.sendall(data.encode())
[ "def", "send", "(", "self", ",", "data", ")", ":", "self", ".", "logger", ".", "debug", "(", "'Sending data: %s'", "%", "data", ")", "self", ".", "client", ".", "sendall", "(", "data", ".", "encode", "(", ")", ")" ]
Send encoded instructions to Guacamole guacd server.
[ "Send", "encoded", "instructions", "to", "Guacamole", "guacd", "server", "." ]
python
test
32.833333
Ehco1996/lazySpider
lazyspider/lazyheaders.py
https://github.com/Ehco1996/lazySpider/blob/6ae43fec7f784d7e515379e79bcaff06b7fd5ade/lazyspider/lazyheaders.py#L46-L60
def _stripStrList(self, raw_str, stop_strs): ''' 去除字符串中的所有指定字符串 args: raw_str 源字符串 stop_strs 指定字符串 列表 return str 筛选后的字符串 ''' if type(stop_strs) == list: for word in stop_strs: raw_str = self._stripStr(raw_str...
[ "def", "_stripStrList", "(", "self", ",", "raw_str", ",", "stop_strs", ")", ":", "if", "type", "(", "stop_strs", ")", "==", "list", ":", "for", "word", "in", "stop_strs", ":", "raw_str", "=", "self", ".", "_stripStr", "(", "raw_str", ",", "word", ")", ...
去除字符串中的所有指定字符串 args: raw_str 源字符串 stop_strs 指定字符串 列表 return str 筛选后的字符串
[ "去除字符串中的所有指定字符串", "args:", "raw_str", "源字符串", "stop_strs", "指定字符串", "列表", "return", "str", "筛选后的字符串" ]
python
train
27.333333
deep-compute/deeputil
deeputil/misc.py
https://github.com/deep-compute/deeputil/blob/9af5702bc3fd990688bf2aed16c20fa104be66df/deeputil/misc.py#L16-L31
def generate_random_string(length=6): ''' Returns a random string of a specified length. >>> len(generate_random_string(length=25)) 25 Test randomness. Try N times and observe no duplicaton >>> N = 100 >>> len(set(generate_random_string(10) for i in range(N))) == N True ''' n =...
[ "def", "generate_random_string", "(", "length", "=", "6", ")", ":", "n", "=", "int", "(", "length", "/", "2", "+", "1", ")", "x", "=", "binascii", ".", "hexlify", "(", "os", ".", "urandom", "(", "n", ")", ")", "s", "=", "x", "[", ":", "length",...
Returns a random string of a specified length. >>> len(generate_random_string(length=25)) 25 Test randomness. Try N times and observe no duplicaton >>> N = 100 >>> len(set(generate_random_string(10) for i in range(N))) == N True
[ "Returns", "a", "random", "string", "of", "a", "specified", "length", "." ]
python
train
25.8125
vmlaker/coils
coils/SortedList.py
https://github.com/vmlaker/coils/blob/a3a613b3d661dec010e5879c86e62cbff2519dd0/coils/SortedList.py#L23-L26
def getCountGT(self, item): """Return number of elements greater than *item*.""" index = bisect.bisect_right(self._list, item) return len(self._list) - index
[ "def", "getCountGT", "(", "self", ",", "item", ")", ":", "index", "=", "bisect", ".", "bisect_right", "(", "self", ".", "_list", ",", "item", ")", "return", "len", "(", "self", ".", "_list", ")", "-", "index" ]
Return number of elements greater than *item*.
[ "Return", "number", "of", "elements", "greater", "than", "*", "item", "*", "." ]
python
train
44.5
MediaFire/mediafire-python-open-sdk
mediafire/api.py
https://github.com/MediaFire/mediafire-python-open-sdk/blob/8f1f23db1b16f16e026f5c6777aec32d00baa05f/mediafire/api.py#L430-L439
def user_set_avatar(self, action=None, quick_key=None, url=None): """user/set_avatar http://www.mediafire.com/developers/core_api/1.3/user/#set_avatar """ return self.request("user/set_avatar", QueryParams({ "action": action, "quick_key": quick_key, "...
[ "def", "user_set_avatar", "(", "self", ",", "action", "=", "None", ",", "quick_key", "=", "None", ",", "url", "=", "None", ")", ":", "return", "self", ".", "request", "(", "\"user/set_avatar\"", ",", "QueryParams", "(", "{", "\"action\"", ":", "action", ...
user/set_avatar http://www.mediafire.com/developers/core_api/1.3/user/#set_avatar
[ "user", "/", "set_avatar" ]
python
train
33.2
Ex-Mente/auxi.0
auxi/tools/chemistry/stoichiometry.py
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/stoichiometry.py#L330-L344
def elements(compounds): """ Determine the set of elements present in a list of chemical compounds. The list of elements is sorted alphabetically. :param compounds: List of compound formulas and phases, e.g. ['Fe2O3[S1]', 'Al2O3[S1]']. :returns: List of elements. """ elementlist = ...
[ "def", "elements", "(", "compounds", ")", ":", "elementlist", "=", "[", "parse_compound", "(", "compound", ")", ".", "count", "(", ")", ".", "keys", "(", ")", "for", "compound", "in", "compounds", "]", "return", "set", "(", ")", ".", "union", "(", "*...
Determine the set of elements present in a list of chemical compounds. The list of elements is sorted alphabetically. :param compounds: List of compound formulas and phases, e.g. ['Fe2O3[S1]', 'Al2O3[S1]']. :returns: List of elements.
[ "Determine", "the", "set", "of", "elements", "present", "in", "a", "list", "of", "chemical", "compounds", "." ]
python
valid
28.6
AkihikoITOH/capybara
capybara/virtualenv/lib/python2.7/site-packages/setuptools/package_index.py
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/setuptools/package_index.py#L184-L199
def find_external_links(url, page): """Find rel="homepage" and rel="download" links in `page`, yielding URLs""" for match in REL.finditer(page): tag, rel = match.groups() rels = set(map(str.strip, rel.lower().split(','))) if 'homepage' in rels or 'download' in rels: for matc...
[ "def", "find_external_links", "(", "url", ",", "page", ")", ":", "for", "match", "in", "REL", ".", "finditer", "(", "page", ")", ":", "tag", ",", "rel", "=", "match", ".", "groups", "(", ")", "rels", "=", "set", "(", "map", "(", "str", ".", "stri...
Find rel="homepage" and rel="download" links in `page`, yielding URLs
[ "Find", "rel", "=", "homepage", "and", "rel", "=", "download", "links", "in", "page", "yielding", "URLs" ]
python
test
38.9375
tensorflow/hub
examples/image_retraining/retrain.py
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/examples/image_retraining/retrain.py#L437-L478
def cache_bottlenecks(sess, image_lists, image_dir, bottleneck_dir, jpeg_data_tensor, decoded_image_tensor, resized_input_tensor, bottleneck_tensor, module_name): """Ensures all the training, testing, and validation bottlenecks are cached. Because we're likely to read th...
[ "def", "cache_bottlenecks", "(", "sess", ",", "image_lists", ",", "image_dir", ",", "bottleneck_dir", ",", "jpeg_data_tensor", ",", "decoded_image_tensor", ",", "resized_input_tensor", ",", "bottleneck_tensor", ",", "module_name", ")", ":", "how_many_bottlenecks", "=", ...
Ensures all the training, testing, and validation bottlenecks are cached. Because we're likely to read the same image multiple times (if there are no distortions applied during training) it can speed things up a lot if we calculate the bottleneck layer values once for each image during preprocessing, and then ...
[ "Ensures", "all", "the", "training", "testing", "and", "validation", "bottlenecks", "are", "cached", "." ]
python
train
47.238095
hamelsmu/ktext
ktext/preprocess.py
https://github.com/hamelsmu/ktext/blob/221f09f5b1762705075fd1bd914881c0724d5e02/ktext/preprocess.py#L254-L305
def fit(self, data: List[str], return_tokenized_data: bool = False) -> Union[None, List[List[str]]]: """ TODO: update docs Apply cleaner and tokenzier to raw data and build vocabulary. Parameters ---------- data : List[str] These are ...
[ "def", "fit", "(", "self", ",", "data", ":", "List", "[", "str", "]", ",", "return_tokenized_data", ":", "bool", "=", "False", ")", "->", "Union", "[", "None", ",", "List", "[", "List", "[", "str", "]", "]", "]", ":", "self", ".", "__clear_data", ...
TODO: update docs Apply cleaner and tokenzier to raw data and build vocabulary. Parameters ---------- data : List[str] These are raw documents, which are a list of strings. ex: [["The quick brown fox"], ["jumps over the lazy dog"]] return_tokenized_data ...
[ "TODO", ":", "update", "docs" ]
python
test
38
inveniosoftware/invenio-deposit
invenio_deposit/serializers.py
https://github.com/inveniosoftware/invenio-deposit/blob/f243ea1d01ab0a3bc92ade3262d1abdd2bc32447/invenio_deposit/serializers.py#L89-L106
def json_file_response(obj=None, pid=None, record=None, status=None): """JSON Files/File serializer. :param obj: A :class:`invenio_files_rest.models.ObjectVersion` instance or a :class:`invenio_records_files.api.FilesIterator` if it's a list of files. :param pid: PID value. (not used) :...
[ "def", "json_file_response", "(", "obj", "=", "None", ",", "pid", "=", "None", ",", "record", "=", "None", ",", "status", "=", "None", ")", ":", "from", "invenio_records_files", ".", "api", "import", "FilesIterator", "if", "isinstance", "(", "obj", ",", ...
JSON Files/File serializer. :param obj: A :class:`invenio_files_rest.models.ObjectVersion` instance or a :class:`invenio_records_files.api.FilesIterator` if it's a list of files. :param pid: PID value. (not used) :param record: The record metadata. (not used) :param status: The HTTP sta...
[ "JSON", "Files", "/", "File", "serializer", "." ]
python
valid
39.055556
picklepete/pyicloud
pyicloud/services/findmyiphone.py
https://github.com/picklepete/pyicloud/blob/9bb6d750662ce24c8febc94807ddbdcdf3cadaa2/pyicloud/services/findmyiphone.py#L128-L144
def play_sound(self, subject='Find My iPhone Alert'): """ Send a request to the device to play a sound. It's possible to pass a custom message by changing the `subject`. """ data = json.dumps({ 'device': self.content['id'], 'subject': subject, 'client...
[ "def", "play_sound", "(", "self", ",", "subject", "=", "'Find My iPhone Alert'", ")", ":", "data", "=", "json", ".", "dumps", "(", "{", "'device'", ":", "self", ".", "content", "[", "'id'", "]", ",", "'subject'", ":", "subject", ",", "'clientContext'", "...
Send a request to the device to play a sound. It's possible to pass a custom message by changing the `subject`.
[ "Send", "a", "request", "to", "the", "device", "to", "play", "a", "sound", "." ]
python
train
28.705882
PyCQA/astroid
astroid/inference.py
https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/inference.py#L526-L531
def infer_unaryop(self, context=None): """Infer what an UnaryOp should return when evaluated.""" yield from _filter_operation_errors( self, _infer_unaryop, context, util.BadUnaryOperationMessage ) return dict(node=self, context=context)
[ "def", "infer_unaryop", "(", "self", ",", "context", "=", "None", ")", ":", "yield", "from", "_filter_operation_errors", "(", "self", ",", "_infer_unaryop", ",", "context", ",", "util", ".", "BadUnaryOperationMessage", ")", "return", "dict", "(", "node", "=", ...
Infer what an UnaryOp should return when evaluated.
[ "Infer", "what", "an", "UnaryOp", "should", "return", "when", "evaluated", "." ]
python
train
42.5
apple/turicreate
deps/src/libxml2-2.9.1/python/libxml2.py
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L5288-L5311
def parseEntityRef(self): """parse ENTITY references declarations [68] EntityRef ::= '&' Name ';' [ WFC: Entity Declared ] In a document without any DTD, a document with only an internal DTD subset which contains no parameter entity references, or a document with "stand...
[ "def", "parseEntityRef", "(", "self", ")", ":", "ret", "=", "libxml2mod", ".", "xmlParseEntityRef", "(", "self", ".", "_o", ")", "if", "ret", "is", "None", ":", "raise", "parserError", "(", "'xmlParseEntityRef() failed'", ")", "__tmp", "=", "xmlEntity", "(",...
parse ENTITY references declarations [68] EntityRef ::= '&' Name ';' [ WFC: Entity Declared ] In a document without any DTD, a document with only an internal DTD subset which contains no parameter entity references, or a document with "standalone='yes'", the Name given in the ...
[ "parse", "ENTITY", "references", "declarations", "[", "68", "]", "EntityRef", "::", "=", "&", "Name", ";", "[", "WFC", ":", "Entity", "Declared", "]", "In", "a", "document", "without", "any", "DTD", "a", "document", "with", "only", "an", "internal", "DTD...
python
train
59.666667
delfick/harpoon
harpoon/dockerpty/pty.py
https://github.com/delfick/harpoon/blob/a2d39311d6127b7da2e15f40468bf320d598e461/harpoon/dockerpty/pty.py#L202-L220
def resize(self, size=None): """ Resize the container's PTY. If `size` is not None, it must be a tuple of (height,width), otherwise it will be determined by the size of the current TTY. """ if not self.israw(): return size = size or tty.size(self.st...
[ "def", "resize", "(", "self", ",", "size", "=", "None", ")", ":", "if", "not", "self", ".", "israw", "(", ")", ":", "return", "size", "=", "size", "or", "tty", ".", "size", "(", "self", ".", "stdout", ")", "if", "size", "is", "not", "None", ":"...
Resize the container's PTY. If `size` is not None, it must be a tuple of (height,width), otherwise it will be determined by the size of the current TTY.
[ "Resize", "the", "container", "s", "PTY", "." ]
python
train
28.210526
onnx/onnx-mxnet
onnx_mxnet/import_onnx.py
https://github.com/onnx/onnx-mxnet/blob/b602d75c5a01f5ed8f68b11150a06374f058a86b/onnx_mxnet/import_onnx.py#L187-L199
def _fix_squeeze(self, inputs, new_attr): """ MXNet doesnt have a squeeze operator. Using "split" to perform similar operation. "split" can be slower compared to "reshape". This can have performance impact. TODO: Remove this implementation once mxnet adds the support. ...
[ "def", "_fix_squeeze", "(", "self", ",", "inputs", ",", "new_attr", ")", ":", "axes", "=", "new_attr", ".", "get", "(", "'axis'", ")", "op", "=", "mx", ".", "sym", ".", "split", "(", "inputs", "[", "0", "]", ",", "axis", "=", "axes", "[", "0", ...
MXNet doesnt have a squeeze operator. Using "split" to perform similar operation. "split" can be slower compared to "reshape". This can have performance impact. TODO: Remove this implementation once mxnet adds the support.
[ "MXNet", "doesnt", "have", "a", "squeeze", "operator", ".", "Using", "split", "to", "perform", "similar", "operation", ".", "split", "can", "be", "slower", "compared", "to", "reshape", ".", "This", "can", "have", "performance", "impact", ".", "TODO", ":", ...
python
train
42.769231
IdentityPython/pysaml2
src/saml2/response.py
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/response.py#L914-L1030
def parse_assertion(self, keys=None): """ Parse the assertions for a saml response. :param keys: A string representing a RSA key or a list of strings containing RSA keys. :return: True if the assertions are parsed otherwise False. """ if self.context == "AuthnQuery": ...
[ "def", "parse_assertion", "(", "self", ",", "keys", "=", "None", ")", ":", "if", "self", ".", "context", "==", "\"AuthnQuery\"", ":", "# can contain one or more assertions", "pass", "else", ":", "# This is a saml2int limitation", "try", ":", "assert", "(", "len", ...
Parse the assertions for a saml response. :param keys: A string representing a RSA key or a list of strings containing RSA keys. :return: True if the assertions are parsed otherwise False.
[ "Parse", "the", "assertions", "for", "a", "saml", "response", "." ]
python
train
40.717949
joerick/pyinstrument
pyinstrument/util.py
https://github.com/joerick/pyinstrument/blob/cc4f3f6fc1b493d7cd058ecf41ad012e0030a512/pyinstrument/util.py#L18-L25
def deprecated(func, *args, **kwargs): ''' Marks a function as deprecated. ''' warnings.warn( '{} is deprecated and should no longer be used.'.format(func), DeprecationWarning, stacklevel=3 ) return func(*args, **kwargs)
[ "def", "deprecated", "(", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "warnings", ".", "warn", "(", "'{} is deprecated and should no longer be used.'", ".", "format", "(", "func", ")", ",", "DeprecationWarning", ",", "stacklevel", "=", "3", ...
Marks a function as deprecated.
[ "Marks", "a", "function", "as", "deprecated", "." ]
python
train
31.625
reingart/pyafipws
wslpg.py
https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/wslpg.py#L1746-L1760
def AgregarCalidad(self, analisis_muestra=None, nro_boletin=None, cod_grado=None, valor_grado=None, valor_contenido_proteico=None, valor_factor=None, **kwargs): "Agrega la información sobre la calidad, al autorizar o poster...
[ "def", "AgregarCalidad", "(", "self", ",", "analisis_muestra", "=", "None", ",", "nro_boletin", "=", "None", ",", "cod_grado", "=", "None", ",", "valor_grado", "=", "None", ",", "valor_contenido_proteico", "=", "None", ",", "valor_factor", "=", "None", ",", ...
Agrega la información sobre la calidad, al autorizar o posteriormente
[ "Agrega", "la", "información", "sobre", "la", "calidad", "al", "autorizar", "o", "posteriormente" ]
python
train
55.533333
cjdrake/pyeda
pyeda/parsing/boolexpr.py
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/boolexpr.py#L427-L443
def _impl(lexer): """Return an Implies expression.""" p = _sumterm(lexer) tok = next(lexer) # SUMTERM '=>' IMPL if isinstance(tok, OP_rarrow): q = _impl(lexer) return ('implies', p, q) # SUMTERM '<=>' IMPL elif isinstance(tok, OP_lrarrow): q = _impl(lexer) re...
[ "def", "_impl", "(", "lexer", ")", ":", "p", "=", "_sumterm", "(", "lexer", ")", "tok", "=", "next", "(", "lexer", ")", "# SUMTERM '=>' IMPL", "if", "isinstance", "(", "tok", ",", "OP_rarrow", ")", ":", "q", "=", "_impl", "(", "lexer", ")", "return",...
Return an Implies expression.
[ "Return", "an", "Implies", "expression", "." ]
python
train
23.294118
City-of-Helsinki/django-helusers
helusers/authz.py
https://github.com/City-of-Helsinki/django-helusers/blob/9064979f6f990987358e2bca3c24a80fad201bdb/helusers/authz.py#L15-L29
def has_api_scopes(self, *api_scopes): """ Test if all given API scopes are authorized. :type api_scopes: list[str] :param api_scopes: The API scopes to test :rtype: bool|None :return: True or False, if the API Token has the API scopes field set, oth...
[ "def", "has_api_scopes", "(", "self", ",", "*", "api_scopes", ")", ":", "if", "self", ".", "_authorized_api_scopes", "is", "None", ":", "return", "None", "return", "all", "(", "(", "x", "in", "self", ".", "_authorized_api_scopes", ")", "for", "x", "in", ...
Test if all given API scopes are authorized. :type api_scopes: list[str] :param api_scopes: The API scopes to test :rtype: bool|None :return: True or False, if the API Token has the API scopes field set, otherwise None
[ "Test", "if", "all", "given", "API", "scopes", "are", "authorized", "." ]
python
train
31.733333
frostming/atoml
atoml/encoder.py
https://github.com/frostming/atoml/blob/85414ef77777366887a819a05b496d5279296cd2/atoml/encoder.py#L193-L201
def dumps(obj, preserve=False): """Stringifies a dict as toml :param obj: the object to be dumped into toml :param preserve: optional flag to preserve the inline table in result """ f = StringIO() dump(obj, f, preserve) return f.getvalue()
[ "def", "dumps", "(", "obj", ",", "preserve", "=", "False", ")", ":", "f", "=", "StringIO", "(", ")", "dump", "(", "obj", ",", "f", ",", "preserve", ")", "return", "f", ".", "getvalue", "(", ")" ]
Stringifies a dict as toml :param obj: the object to be dumped into toml :param preserve: optional flag to preserve the inline table in result
[ "Stringifies", "a", "dict", "as", "toml" ]
python
train
28.888889
explosion/spaCy
spacy/util.py
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/util.py#L252-L262
def get_entry_point(key, value): """Check if registered entry point is available for a given name and load it. Otherwise, return None. key (unicode): Entry point name. value (unicode): Name of entry point to load. RETURNS: The loaded entry point or None. """ for entry_point in pkg_resources...
[ "def", "get_entry_point", "(", "key", ",", "value", ")", ":", "for", "entry_point", "in", "pkg_resources", ".", "iter_entry_points", "(", "key", ")", ":", "if", "entry_point", ".", "name", "==", "value", ":", "return", "entry_point", ".", "load", "(", ")" ...
Check if registered entry point is available for a given name and load it. Otherwise, return None. key (unicode): Entry point name. value (unicode): Name of entry point to load. RETURNS: The loaded entry point or None.
[ "Check", "if", "registered", "entry", "point", "is", "available", "for", "a", "given", "name", "and", "load", "it", ".", "Otherwise", "return", "None", "." ]
python
train
37.272727
Nagasaki45/bibo
bibo/internals.py
https://github.com/Nagasaki45/bibo/blob/e6afb28711e78eb11475834d3f9455252ac9f347/bibo/internals.py#L26-L36
def open_file(filepath): """ Open file with the default system app. Copied from https://stackoverflow.com/a/435669/1224456 """ if sys.platform.startswith('darwin'): subprocess.Popen(('open', filepath)) elif os.name == 'nt': os.startfile(filepath) elif os.name == 'posix': ...
[ "def", "open_file", "(", "filepath", ")", ":", "if", "sys", ".", "platform", ".", "startswith", "(", "'darwin'", ")", ":", "subprocess", ".", "Popen", "(", "(", "'open'", ",", "filepath", ")", ")", "elif", "os", ".", "name", "==", "'nt'", ":", "os", ...
Open file with the default system app. Copied from https://stackoverflow.com/a/435669/1224456
[ "Open", "file", "with", "the", "default", "system", "app", ".", "Copied", "from", "https", ":", "//", "stackoverflow", ".", "com", "/", "a", "/", "435669", "/", "1224456" ]
python
train
32.181818
consbio/ncdjango
ncdjango/geoprocessing/params.py
https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoprocessing/params.py#L275-L281
def clean(self, value): """Cleans and returns the given value, or raises a ParameterNotValidError exception""" if isinstance(value, six.string_types) and value.lower() == 'false': return False return bool(value)
[ "def", "clean", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "six", ".", "string_types", ")", "and", "value", ".", "lower", "(", ")", "==", "'false'", ":", "return", "False", "return", "bool", "(", "value", ")" ]
Cleans and returns the given value, or raises a ParameterNotValidError exception
[ "Cleans", "and", "returns", "the", "given", "value", "or", "raises", "a", "ParameterNotValidError", "exception" ]
python
train
34.714286
twilio/twilio-python
twilio/rest/autopilot/v1/assistant/task/__init__.py
https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/autopilot/v1/assistant/task/__init__.py#L124-L150
def create(self, unique_name, friendly_name=values.unset, actions=values.unset, actions_url=values.unset): """ Create a new TaskInstance :param unicode unique_name: An application-defined string that uniquely identifies the resource :param unicode friendly_name: descript...
[ "def", "create", "(", "self", ",", "unique_name", ",", "friendly_name", "=", "values", ".", "unset", ",", "actions", "=", "values", ".", "unset", ",", "actions_url", "=", "values", ".", "unset", ")", ":", "data", "=", "values", ".", "of", "(", "{", "...
Create a new TaskInstance :param unicode unique_name: An application-defined string that uniquely identifies the resource :param unicode friendly_name: descriptive string that you create to describe the new resource :param dict actions: The JSON string that specifies the actions that instruct ...
[ "Create", "a", "new", "TaskInstance" ]
python
train
41.407407
materialsproject/pymatgen
pymatgen/apps/borg/queen.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/apps/borg/queen.py#L131-L143
def order_assimilation(args): """ Internal helper method for BorgQueen to process assimilation """ (path, drone, data, status) = args newdata = drone.assimilate(path) if newdata: data.append(json.dumps(newdata, cls=MontyEncoder)) status['count'] += 1 count = status['count'] t...
[ "def", "order_assimilation", "(", "args", ")", ":", "(", "path", ",", "drone", ",", "data", ",", "status", ")", "=", "args", "newdata", "=", "drone", ".", "assimilate", "(", "path", ")", "if", "newdata", ":", "data", ".", "append", "(", "json", ".", ...
Internal helper method for BorgQueen to process assimilation
[ "Internal", "helper", "method", "for", "BorgQueen", "to", "process", "assimilation" ]
python
train
35.230769
andy-z/ged4py
ged4py/model.py
https://github.com/andy-z/ged4py/blob/d0e0cceaadf0a84cbf052705e3c27303b12e1757/ged4py/model.py#L295-L321
def order(self, order): """Returns name order key. Returns tuple with two strings that can be compared to other such tuple obtained from different name. Note that if you want locale-dependent ordering then you need to compare strings using locale-aware method (e.g. ``locale.strx...
[ "def", "order", "(", "self", ",", "order", ")", ":", "given", "=", "self", ".", "given", "surname", "=", "self", ".", "surname", "if", "order", "in", "(", "ORDER_MAIDEN_GIVEN", ",", "ORDER_GIVEN_MAIDEN", ")", ":", "surname", "=", "self", ".", "maiden", ...
Returns name order key. Returns tuple with two strings that can be compared to other such tuple obtained from different name. Note that if you want locale-dependent ordering then you need to compare strings using locale-aware method (e.g. ``locale.strxfrm``). :param order: One ...
[ "Returns", "name", "order", "key", "." ]
python
train
40.740741
GetmeUK/MongoFrames
snippets/comparable.py
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/snippets/comparable.py#L310-L323
def logged_delete(self, user): """Delete the document and log the event in the change log""" self.delete() # Log the change entry = ChangeLogEntry({ 'type': 'DELETED', 'documents': [self], 'user': user }) entry.insert() r...
[ "def", "logged_delete", "(", "self", ",", "user", ")", ":", "self", ".", "delete", "(", ")", "# Log the change", "entry", "=", "ChangeLogEntry", "(", "{", "'type'", ":", "'DELETED'", ",", "'documents'", ":", "[", "self", "]", ",", "'user'", ":", "user", ...
Delete the document and log the event in the change log
[ "Delete", "the", "document", "and", "log", "the", "event", "in", "the", "change", "log" ]
python
train
22.714286
raiden-network/raiden
raiden/messages.py
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/messages.py#L1726-L1733
def sign(self, signer: Signer): """This method signs twice: - the `non_closing_signature` for the balance proof update - the `reward_proof_signature` for the monitoring request """ self.non_closing_signature = self.balance_proof._sign(signer) message_data = self._...
[ "def", "sign", "(", "self", ",", "signer", ":", "Signer", ")", ":", "self", ".", "non_closing_signature", "=", "self", ".", "balance_proof", ".", "_sign", "(", "signer", ")", "message_data", "=", "self", ".", "_data_to_sign", "(", ")", "self", ".", "sign...
This method signs twice: - the `non_closing_signature` for the balance proof update - the `reward_proof_signature` for the monitoring request
[ "This", "method", "signs", "twice", ":", "-", "the", "non_closing_signature", "for", "the", "balance", "proof", "update", "-", "the", "reward_proof_signature", "for", "the", "monitoring", "request" ]
python
train
47.875
mitsei/dlkit
dlkit/json_/repository/objects.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/repository/objects.py#L290-L316
def get_source_id(self): """Gets the ``Resource Id`` of the source of this asset. The source is the original owner of the copyright of this asset and may differ from the creator of this asset. The source for a published book written by Margaret Mitchell would be Macmillan. The s...
[ "def", "get_source_id", "(", "self", ")", ":", "# Implemented from template for osid.resource.Resource.get_avatar_id_template", "if", "not", "bool", "(", "self", ".", "_my_map", "[", "'sourceId'", "]", ")", ":", "raise", "errors", ".", "IllegalState", "(", "'this Asse...
Gets the ``Resource Id`` of the source of this asset. The source is the original owner of the copyright of this asset and may differ from the creator of this asset. The source for a published book written by Margaret Mitchell would be Macmillan. The source for an unpublished painting by...
[ "Gets", "the", "Resource", "Id", "of", "the", "source", "of", "this", "asset", "." ]
python
train
49.333333
allenai/allennlp
allennlp/predictors/open_information_extraction.py
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/predictors/open_information_extraction.py#L76-L86
def predicates_overlap(tags1: List[str], tags2: List[str]) -> bool: """ Tests whether the predicate in BIO tags1 overlap with those of tags2. """ # Get predicate word indices from both predictions pred_ind1 = get_predicate_indices(tags1) pred_ind2 = get_predicate_indices(tags2) # Return...
[ "def", "predicates_overlap", "(", "tags1", ":", "List", "[", "str", "]", ",", "tags2", ":", "List", "[", "str", "]", ")", "->", "bool", ":", "# Get predicate word indices from both predictions", "pred_ind1", "=", "get_predicate_indices", "(", "tags1", ")", "pred...
Tests whether the predicate in BIO tags1 overlap with those of tags2.
[ "Tests", "whether", "the", "predicate", "in", "BIO", "tags1", "overlap", "with", "those", "of", "tags2", "." ]
python
train
36.909091
kvesteri/validators
validators/email.py
https://github.com/kvesteri/validators/blob/34d355e87168241e872b25811d245810df2bd430/validators/email.py#L26-L72
def email(value, whitelist=None): """ Validate an email address. This validator is based on `Django's email validator`_. Returns ``True`` on success and :class:`~validators.utils.ValidationFailure` when validation fails. Examples:: >>> email('someone@example.com') True ...
[ "def", "email", "(", "value", ",", "whitelist", "=", "None", ")", ":", "if", "whitelist", "is", "None", ":", "whitelist", "=", "domain_whitelist", "if", "not", "value", "or", "'@'", "not", "in", "value", ":", "return", "False", "user_part", ",", "domain_...
Validate an email address. This validator is based on `Django's email validator`_. Returns ``True`` on success and :class:`~validators.utils.ValidationFailure` when validation fails. Examples:: >>> email('someone@example.com') True >>> email('bogus@@') ValidationFailu...
[ "Validate", "an", "email", "address", "." ]
python
train
26.12766
cmck/pybrowserstack-screenshots
browserstack_screenshots/__init__.py
https://github.com/cmck/pybrowserstack-screenshots/blob/598358fc5b9a41678b3f913f2c082a288011322d/browserstack_screenshots/__init__.py#L89-L95
def screenshots_done(self, jobid): """ Return true if the screenshots job is done """ resp = self.session.get(os.path.join(self.api_url, '{0}.json'.format(jobid))) resp = self._process_response(resp) return True if resp.json()['state'] == 'done' else False
[ "def", "screenshots_done", "(", "self", ",", "jobid", ")", ":", "resp", "=", "self", ".", "session", ".", "get", "(", "os", ".", "path", ".", "join", "(", "self", ".", "api_url", ",", "'{0}.json'", ".", "format", "(", "jobid", ")", ")", ")", "resp"...
Return true if the screenshots job is done
[ "Return", "true", "if", "the", "screenshots", "job", "is", "done" ]
python
train
42.571429
saltstack/salt
salt/modules/systemd_service.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L311-L320
def _strip_scope(msg): ''' Strip unnecessary message about running the command with --scope from stderr so that we can raise an exception with the remaining stderr text. ''' ret = [] for line in msg.splitlines(): if not line.endswith('.scope'): ret.append(line) return '\n...
[ "def", "_strip_scope", "(", "msg", ")", ":", "ret", "=", "[", "]", "for", "line", "in", "msg", ".", "splitlines", "(", ")", ":", "if", "not", "line", ".", "endswith", "(", "'.scope'", ")", ":", "ret", ".", "append", "(", "line", ")", "return", "'...
Strip unnecessary message about running the command with --scope from stderr so that we can raise an exception with the remaining stderr text.
[ "Strip", "unnecessary", "message", "about", "running", "the", "command", "with", "--", "scope", "from", "stderr", "so", "that", "we", "can", "raise", "an", "exception", "with", "the", "remaining", "stderr", "text", "." ]
python
train
33
inveniosoftware-contrib/record-recommender
record_recommender/storage.py
https://github.com/inveniosoftware-contrib/record-recommender/blob/07f71e783369e6373218b5e6ba0bf15901e9251a/record_recommender/storage.py#L152-L155
def add_user(self, uid, nodes, weights): """Add a user.""" for i, node in enumerate(nodes): self.file.write("{},{},{}\n".format(uid, node, weights[i]))
[ "def", "add_user", "(", "self", ",", "uid", ",", "nodes", ",", "weights", ")", ":", "for", "i", ",", "node", "in", "enumerate", "(", "nodes", ")", ":", "self", ".", "file", ".", "write", "(", "\"{},{},{}\\n\"", ".", "format", "(", "uid", ",", "node...
Add a user.
[ "Add", "a", "user", "." ]
python
train
44
neo4j/neo4j-python-driver
neo4j/types/temporal.py
https://github.com/neo4j/neo4j-python-driver/blob/0c641e826765e86ff5454dae57c99521db8ca45c/neo4j/types/temporal.py#L80-L97
def dehydrate_time(value): """ Dehydrator for `time` values. :param value: :type value: Time :return: """ if isinstance(value, Time): nanoseconds = int(value.ticks * 1000000000) elif isinstance(value, time): nanoseconds = (3600000000000 * value.hour + 60000000000 * value.min...
[ "def", "dehydrate_time", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "Time", ")", ":", "nanoseconds", "=", "int", "(", "value", ".", "ticks", "*", "1000000000", ")", "elif", "isinstance", "(", "value", ",", "time", ")", ":", "nanosec...
Dehydrator for `time` values. :param value: :type value: Time :return:
[ "Dehydrator", "for", "time", "values", "." ]
python
train
34.888889
WZBSocialScienceCenter/tmtoolkit
tmtoolkit/topicmod/visualize.py
https://github.com/WZBSocialScienceCenter/tmtoolkit/blob/ca8b9d072e37ccc82b533f47d48bd9755722305b/tmtoolkit/topicmod/visualize.py#L235-L306
def plot_heatmap(fig, ax, data, xaxislabel=None, yaxislabel=None, xticklabels=None, yticklabels=None, title=None, grid=True, values_in_cells=True, round_values_in_cells=2, legend=False, fontsize_axislabel=None, ...
[ "def", "plot_heatmap", "(", "fig", ",", "ax", ",", "data", ",", "xaxislabel", "=", "None", ",", "yaxislabel", "=", "None", ",", "xticklabels", "=", "None", ",", "yticklabels", "=", "None", ",", "title", "=", "None", ",", "grid", "=", "True", ",", "va...
helper function to plot a heatmap for a 2D matrix `data` using matplotlib's "matshow" function
[ "helper", "function", "to", "plot", "a", "heatmap", "for", "a", "2D", "matrix", "data", "using", "matplotlib", "s", "matshow", "function" ]
python
train
32.958333
tnkteja/myhelp
virtualEnvironment/lib/python2.7/site-packages/coverage/cmdline.py
https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/coverage/cmdline.py#L474-L487
def help(self, error=None, topic=None, parser=None): """Display an error message, or the named topic.""" assert error or topic or parser if error: print(error) print("Use 'coverage help' for help.") elif parser: print(parser.format_help().strip()) ...
[ "def", "help", "(", "self", ",", "error", "=", "None", ",", "topic", "=", "None", ",", "parser", "=", "None", ")", ":", "assert", "error", "or", "topic", "or", "parser", "if", "error", ":", "print", "(", "error", ")", "print", "(", "\"Use 'coverage h...
Display an error message, or the named topic.
[ "Display", "an", "error", "message", "or", "the", "named", "topic", "." ]
python
test
37.5
Riminder/python-riminder-api
riminder/webhook.py
https://github.com/Riminder/python-riminder-api/blob/01279f0ece08cf3d1dd45f76de6d9edf7fafec90/riminder/webhook.py#L59-L65
def setHandler(self, event_name, callback): """Set an handler for given event.""" if event_name not in self.handlers: raise ValueError('{} is not a valid event'.format(event_name)) if callable(event_name): raise TypeError('{} is not callable'.format(callback)) sel...
[ "def", "setHandler", "(", "self", ",", "event_name", ",", "callback", ")", ":", "if", "event_name", "not", "in", "self", ".", "handlers", ":", "raise", "ValueError", "(", "'{} is not a valid event'", ".", "format", "(", "event_name", ")", ")", "if", "callabl...
Set an handler for given event.
[ "Set", "an", "handler", "for", "given", "event", "." ]
python
train
49.571429
limpyd/redis-limpyd
limpyd/fields.py
https://github.com/limpyd/redis-limpyd/blob/3c745dde1390a0bd09690b77a089dcc08c6c7e43/limpyd/fields.py#L640-L647
def _del(self, command, *args, **kwargs): """ Shortcut for commands that remove all values of the field. All will be deindexed. """ if self.indexable: self.deindex() return self._traverse_command(command, *args, **kwargs)
[ "def", "_del", "(", "self", ",", "command", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "indexable", ":", "self", ".", "deindex", "(", ")", "return", "self", ".", "_traverse_command", "(", "command", ",", "*", "args", ",...
Shortcut for commands that remove all values of the field. All will be deindexed.
[ "Shortcut", "for", "commands", "that", "remove", "all", "values", "of", "the", "field", ".", "All", "will", "be", "deindexed", "." ]
python
train
34.25
richardchien/nonebot
nonebot/__init__.py
https://github.com/richardchien/nonebot/blob/13ed9e4e87d9824b61592520aabda6d2737c8848/nonebot/__init__.py#L102-L105
def run(host: Optional[str] = None, port: Optional[int] = None, *args, **kwargs) -> None: """Run the NoneBot instance.""" get_bot().run(host=host, port=port, *args, **kwargs)
[ "def", "run", "(", "host", ":", "Optional", "[", "str", "]", "=", "None", ",", "port", ":", "Optional", "[", "int", "]", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", "->", "None", ":", "get_bot", "(", ")", ".", "run", "(", "ho...
Run the NoneBot instance.
[ "Run", "the", "NoneBot", "instance", "." ]
python
train
46.75
juju/charm-helpers
charmhelpers/contrib/hardening/audits/__init__.py
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/audits/__init__.py#L36-L54
def _take_action(self): """Determines whether to perform the action or not. Checks whether or not an action should be taken. This is determined by the truthy value for the unless parameter. If unless is a callback method, it will be invoked with no parameters in order to determine ...
[ "def", "_take_action", "(", "self", ")", ":", "# Do the action if there isn't an unless override.", "if", "self", ".", "unless", "is", "None", ":", "return", "True", "# Invoke the callback if there is one.", "if", "hasattr", "(", "self", ".", "unless", ",", "'__call__...
Determines whether to perform the action or not. Checks whether or not an action should be taken. This is determined by the truthy value for the unless parameter. If unless is a callback method, it will be invoked with no parameters in order to determine whether or not the action should...
[ "Determines", "whether", "to", "perform", "the", "action", "or", "not", "." ]
python
train
39.684211
odlgroup/odl
odl/util/vectorization.py
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/util/vectorization.py#L22-L29
def is_valid_input_array(x, ndim=None): """Test if ``x`` is a correctly shaped point array in R^d.""" x = np.asarray(x) if ndim is None or ndim == 1: return x.ndim == 1 and x.size > 1 or x.ndim == 2 and x.shape[0] == 1 else: return x.ndim == 2 and x.shape[0] == ndim
[ "def", "is_valid_input_array", "(", "x", ",", "ndim", "=", "None", ")", ":", "x", "=", "np", ".", "asarray", "(", "x", ")", "if", "ndim", "is", "None", "or", "ndim", "==", "1", ":", "return", "x", ".", "ndim", "==", "1", "and", "x", ".", "size"...
Test if ``x`` is a correctly shaped point array in R^d.
[ "Test", "if", "x", "is", "a", "correctly", "shaped", "point", "array", "in", "R^d", "." ]
python
train
36.5
aamalev/aiohttp_apiset
aiohttp_apiset/compat.py
https://github.com/aamalev/aiohttp_apiset/blob/ba3492ce929e39be1325d506b727a8bfb34e7b33/aiohttp_apiset/compat.py#L364-L368
def add_put(self, *args, **kwargs): """ Shortcut for add_route with method PUT """ return self.add_route(hdrs.METH_PUT, *args, **kwargs)
[ "def", "add_put", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "add_route", "(", "hdrs", ".", "METH_PUT", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Shortcut for add_route with method PUT
[ "Shortcut", "for", "add_route", "with", "method", "PUT" ]
python
train
32.8
peri-source/peri
peri/opt/optimize.py
https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/opt/optimize.py#L2380-L2406
def do_levmarq_all_particle_groups(s, region_size=40, max_iter=2, damping=1.0, decrease_damp_factor=10., run_length=4, collect_stats=False, **kwargs): """ Levenberg-Marquardt optimization for every particle in the state. Convenience wrapper for LMParticleGroupCollection. Same keyword args, but ...
[ "def", "do_levmarq_all_particle_groups", "(", "s", ",", "region_size", "=", "40", ",", "max_iter", "=", "2", ",", "damping", "=", "1.0", ",", "decrease_damp_factor", "=", "10.", ",", "run_length", "=", "4", ",", "collect_stats", "=", "False", ",", "*", "*"...
Levenberg-Marquardt optimization for every particle in the state. Convenience wrapper for LMParticleGroupCollection. Same keyword args, but I've set the defaults to what I've found to be useful values for optimizing particles. See LMParticleGroupCollection for documentation. See Also -------- ...
[ "Levenberg", "-", "Marquardt", "optimization", "for", "every", "particle", "in", "the", "state", "." ]
python
valid
41.481481
FulcrumTechnologies/pyconfluence
pyconfluence/actions.py
https://github.com/FulcrumTechnologies/pyconfluence/blob/a999726dbc1cbdd3d9062234698eeae799ce84ce/pyconfluence/actions.py#L151-L162
def get_page_id(name, space): """Return id of a page based on passed page name and space. Parameters: - name: name of a Confluence page. - space: space the Confluence page is in. """ data = _json.loads(_api.rest("?title=" + name.replace(" ", "%20") + "&" "spaceKey=" + spac...
[ "def", "get_page_id", "(", "name", ",", "space", ")", ":", "data", "=", "_json", ".", "loads", "(", "_api", ".", "rest", "(", "\"?title=\"", "+", "name", ".", "replace", "(", "\" \"", ",", "\"%20\"", ")", "+", "\"&\"", "\"spaceKey=\"", "+", "space", ...
Return id of a page based on passed page name and space. Parameters: - name: name of a Confluence page. - space: space the Confluence page is in.
[ "Return", "id", "of", "a", "page", "based", "on", "passed", "page", "name", "and", "space", ".", "Parameters", ":", "-", "name", ":", "name", "of", "a", "Confluence", "page", ".", "-", "space", ":", "space", "the", "Confluence", "page", "is", "in", "...
python
train
35.666667
shoebot/shoebot
shoebot/grammar/bot.py
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/bot.py#L324-L360
def snapshot(self, target=None, defer=None, autonumber=False): '''Save the contents of current surface into a file or cairo surface/context :param filename: Can be a filename or a Cairo surface. :param defer: If true, buffering/threading may be employed however output will not be immediate. ...
[ "def", "snapshot", "(", "self", ",", "target", "=", "None", ",", "defer", "=", "None", ",", "autonumber", "=", "False", ")", ":", "if", "autonumber", ":", "file_number", "=", "self", ".", "_frame", "else", ":", "file_number", "=", "None", "if", "isinst...
Save the contents of current surface into a file or cairo surface/context :param filename: Can be a filename or a Cairo surface. :param defer: If true, buffering/threading may be employed however output will not be immediate. :param autonumber: If true then a number will be appended to the file...
[ "Save", "the", "contents", "of", "current", "surface", "into", "a", "file", "or", "cairo", "surface", "/", "context" ]
python
valid
42.378378
SBRG/ssbio
ssbio/protein/sequence/properties/scratch.py
https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/protein/sequence/properties/scratch.py#L222-L244
def read_accpro20(infile): """Read the accpro20 output (.acc20) and return the parsed FASTA records. Keeps the spaces between the accessibility numbers. Args: infile: Path to .acc20 file Returns: dict: Dictionary of accessibilities with keys as the ID """ with open(infile) as...
[ "def", "read_accpro20", "(", "infile", ")", ":", "with", "open", "(", "infile", ")", "as", "f", ":", "records", "=", "f", ".", "read", "(", ")", ".", "splitlines", "(", ")", "accpro20_dict", "=", "{", "}", "for", "i", ",", "r", "in", "enumerate", ...
Read the accpro20 output (.acc20) and return the parsed FASTA records. Keeps the spaces between the accessibility numbers. Args: infile: Path to .acc20 file Returns: dict: Dictionary of accessibilities with keys as the ID
[ "Read", "the", "accpro20", "output", "(", ".", "acc20", ")", "and", "return", "the", "parsed", "FASTA", "records", "." ]
python
train
30.956522
googleapis/google-cloud-python
spanner/google/cloud/spanner_v1/gapic/spanner_client.py
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/gapic/spanner_client.py#L94-L102
def session_path(cls, project, instance, database, session): """Return a fully-qualified session string.""" return google.api_core.path_template.expand( "projects/{project}/instances/{instance}/databases/{database}/sessions/{session}", project=project, instance=instan...
[ "def", "session_path", "(", "cls", ",", "project", ",", "instance", ",", "database", ",", "session", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "\"projects/{project}/instances/{instance}/databases/{database}/sessions/{sessio...
Return a fully-qualified session string.
[ "Return", "a", "fully", "-", "qualified", "session", "string", "." ]
python
train
42.777778
henrysher/kotocore
kotocore/session.py
https://github.com/henrysher/kotocore/blob/c52d2f3878b924ceabca07f61c91abcb1b230ecc/kotocore/session.py#L97-L131
def get_resource(self, service_name, resource_name, base_class=None): """ Returns a ``Resource`` **class** for a given service. :param service_name: A string that specifies the name of the desired service. Ex. ``sqs``, ``sns``, ``dynamodb``, etc. :type service_name: string ...
[ "def", "get_resource", "(", "self", ",", "service_name", ",", "resource_name", ",", "base_class", "=", "None", ")", ":", "try", ":", "return", "self", ".", "cache", ".", "get_resource", "(", "service_name", ",", "resource_name", ",", "base_class", "=", "base...
Returns a ``Resource`` **class** for a given service. :param service_name: A string that specifies the name of the desired service. Ex. ``sqs``, ``sns``, ``dynamodb``, etc. :type service_name: string :param resource_name: A string that specifies the name of the desired ...
[ "Returns", "a", "Resource", "**", "class", "**", "for", "a", "given", "service", "." ]
python
train
35.142857
craffel/mir_eval
mir_eval/util.py
https://github.com/craffel/mir_eval/blob/f41c8dafaea04b411252a516d1965af43c7d531b/mir_eval/util.py#L13-L52
def index_labels(labels, case_sensitive=False): """Convert a list of string identifiers into numerical indices. Parameters ---------- labels : list of strings, shape=(n,) A list of annotations, e.g., segment or chord labels from an annotation file. case_sensitive : bool Set...
[ "def", "index_labels", "(", "labels", ",", "case_sensitive", "=", "False", ")", ":", "label_to_index", "=", "{", "}", "index_to_label", "=", "{", "}", "# If we're not case-sensitive,", "if", "not", "case_sensitive", ":", "labels", "=", "[", "str", "(", "s", ...
Convert a list of string identifiers into numerical indices. Parameters ---------- labels : list of strings, shape=(n,) A list of annotations, e.g., segment or chord labels from an annotation file. case_sensitive : bool Set to True to enable case-sensitive label indexing ...
[ "Convert", "a", "list", "of", "string", "identifiers", "into", "numerical", "indices", "." ]
python
train
27.975
obriencj/python-javatools
javatools/report.py
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/report.py#L388-L398
def _indent(stream, indent, *msgs): """ write a message to a text stream, with indentation. Also ensures that the output encoding of the messages is safe for writing. """ for x in range(0, indent): stream.write(" ") for x in msgs: # Any nicer way? In Py2 x can be 'str' or 'unicode'. ...
[ "def", "_indent", "(", "stream", ",", "indent", ",", "*", "msgs", ")", ":", "for", "x", "in", "range", "(", "0", ",", "indent", ")", ":", "stream", ".", "write", "(", "\" \"", ")", "for", "x", "in", "msgs", ":", "# Any nicer way? In Py2 x can be 'str'...
write a message to a text stream, with indentation. Also ensures that the output encoding of the messages is safe for writing.
[ "write", "a", "message", "to", "a", "text", "stream", "with", "indentation", ".", "Also", "ensures", "that", "the", "output", "encoding", "of", "the", "messages", "is", "safe", "for", "writing", "." ]
python
train
37
inasafe/inasafe
safe/gui/tools/wizard/step_kw40_classify.py
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_kw40_classify.py#L148-L277
def set_widgets(self): """Set widgets on the Classify tab.""" purpose = self.parent.step_kw_purpose.selected_purpose() subcategory = self.parent.step_kw_subcategory.selected_subcategory() classification = self.parent.step_kw_classification.\ selected_classification() ...
[ "def", "set_widgets", "(", "self", ")", ":", "purpose", "=", "self", ".", "parent", ".", "step_kw_purpose", ".", "selected_purpose", "(", ")", "subcategory", "=", "self", ".", "parent", ".", "step_kw_subcategory", ".", "selected_subcategory", "(", ")", "classi...
Set widgets on the Classify tab.
[ "Set", "widgets", "on", "the", "Classify", "tab", "." ]
python
train
45.307692
timgabets/pynblock
pynblock/tools.py
https://github.com/timgabets/pynblock/blob/dbdb6d06bd7741e1138bed09d874b47b23d8d200/pynblock/tools.py#L149-L167
def get_clear_pin(pinblock, account_number): """ Calculate the clear PIN from provided PIN block and account_number, which is the 12 right-most digits of card account number, excluding check digit """ raw_pinblock = bytes.fromhex(pinblock.decode('utf-8')) raw_acct_num = bytes.fromhex((b'0000' + acco...
[ "def", "get_clear_pin", "(", "pinblock", ",", "account_number", ")", ":", "raw_pinblock", "=", "bytes", ".", "fromhex", "(", "pinblock", ".", "decode", "(", "'utf-8'", ")", ")", "raw_acct_num", "=", "bytes", ".", "fromhex", "(", "(", "b'0000'", "+", "accou...
Calculate the clear PIN from provided PIN block and account_number, which is the 12 right-most digits of card account number, excluding check digit
[ "Calculate", "the", "clear", "PIN", "from", "provided", "PIN", "block", "and", "account_number", "which", "is", "the", "12", "right", "-", "most", "digits", "of", "card", "account", "number", "excluding", "check", "digit" ]
python
train
41.947368
Kane610/axis
axis/port_cgi.py
https://github.com/Kane610/axis/blob/b2b44ce595c7b722b5e13eabcab7b91f048e1808/axis/port_cgi.py#L42-L58
def process_raw(self, raw: dict) -> None: """Pre-process raw dict. Prepare parameters to work with APIItems. """ raw_ports = {} for param in raw: port_index = REGEX_PORT_INDEX.search(param).group(0) if port_index not in raw_ports: raw_po...
[ "def", "process_raw", "(", "self", ",", "raw", ":", "dict", ")", "->", "None", ":", "raw_ports", "=", "{", "}", "for", "param", "in", "raw", ":", "port_index", "=", "REGEX_PORT_INDEX", ".", "search", "(", "param", ")", ".", "group", "(", "0", ")", ...
Pre-process raw dict. Prepare parameters to work with APIItems.
[ "Pre", "-", "process", "raw", "dict", "." ]
python
train
28.764706
globocom/GloboNetworkAPI-client-python
networkapiclient/ClientFactory.py
https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/ClientFactory.py#L181-L188
def create_api_ipv4(self): """Get an instance of Api IPv4 services facade.""" return ApiIPv4( self.networkapi_url, self.user, self.password, self.user_ldap)
[ "def", "create_api_ipv4", "(", "self", ")", ":", "return", "ApiIPv4", "(", "self", ".", "networkapi_url", ",", "self", ".", "user", ",", "self", ".", "password", ",", "self", ".", "user_ldap", ")" ]
Get an instance of Api IPv4 services facade.
[ "Get", "an", "instance", "of", "Api", "IPv4", "services", "facade", "." ]
python
train
26.75
jay-johnson/spylunking
spylunking/wait_for_exit.py
https://github.com/jay-johnson/spylunking/blob/95cc86776f04ec5935cf04e291cf18798345d6cb/spylunking/wait_for_exit.py#L6-L70
def wait_for_exit( log, debug=False): """wait_for_exit Sleep to allow the thread to pick up final messages before exiting and stopping the Splunk HTTP publisher. You can decrease this delay (in seconds) by reducing the splunk_sleep_interval or by exporting the env var: export S...
[ "def", "wait_for_exit", "(", "log", ",", "debug", "=", "False", ")", ":", "debug", "=", "SPLUNK_DEBUG", "for", "i", "in", "log", ".", "root", ".", "handlers", ":", "handler_class_name", "=", "i", ".", "__class__", ".", "__name__", ".", "lower", "(", ")...
wait_for_exit Sleep to allow the thread to pick up final messages before exiting and stopping the Splunk HTTP publisher. You can decrease this delay (in seconds) by reducing the splunk_sleep_interval or by exporting the env var: export SPLUNK_SLEEP_INTERVAL=0.5 If you set the timer to 0 then ...
[ "wait_for_exit" ]
python
train
38.261538
saltstack/salt
salt/modules/postgres.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L1335-L1359
def _role_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a role from the Postgres Server ''' # check if user exists if not user_exists(name, user, host, port, maintenance_db, password=password, runas...
[ "def", "_role_remove", "(", "name", ",", "user", "=", "None", ",", "host", "=", "None", ",", "port", "=", "None", ",", "maintenance_db", "=", "None", ",", "password", "=", "None", ",", "runas", "=", "None", ")", ":", "# check if user exists", "if", "no...
Removes a role from the Postgres Server
[ "Removes", "a", "role", "from", "the", "Postgres", "Server" ]
python
train
33.68
rcbops/osa_differ
osa_differ/osa_differ.py
https://github.com/rcbops/osa_differ/blob/b3452436655ba3db8cc6602390fd7fdf4ef30f01/osa_differ/osa_differ.py#L399-L405
def prepare_storage_dir(storage_directory): """Prepare the storage directory.""" storage_directory = os.path.expanduser(storage_directory) if not os.path.exists(storage_directory): os.mkdir(storage_directory) return storage_directory
[ "def", "prepare_storage_dir", "(", "storage_directory", ")", ":", "storage_directory", "=", "os", ".", "path", ".", "expanduser", "(", "storage_directory", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "storage_directory", ")", ":", "os", ".", "mk...
Prepare the storage directory.
[ "Prepare", "the", "storage", "directory", "." ]
python
train
36
last-partizan/pytils
pytils/typo.py
https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/typo.py#L26-L44
def rl_cleanspaces(x): """ Clean double spaces, trailing spaces, heading spaces, spaces before punctuations """ patterns = ( # arguments for re.sub: pattern and repl # удаляем пробел перед знаками препинания (r' +([\.,?!\)]+)', r'\1'), # добавляем пробел после знака п...
[ "def", "rl_cleanspaces", "(", "x", ")", ":", "patterns", "=", "(", "# arguments for re.sub: pattern and repl", "# удаляем пробел перед знаками препинания", "(", "r' +([\\.,?!\\)]+)'", ",", "r'\\1'", ")", ",", "# добавляем пробел после знака препинания, если только за ним нет другог...
Clean double spaces, trailing spaces, heading spaces, spaces before punctuations
[ "Clean", "double", "spaces", "trailing", "spaces", "heading", "spaces", "spaces", "before", "punctuations" ]
python
train
37.105263
radjkarl/fancyTools
fancytools/math/line.py
https://github.com/radjkarl/fancyTools/blob/4c4d961003dc4ed6e46429a0c24f7e2bb52caa8b/fancytools/math/line.py#L212-L221
def resize(line, factor): """ factor: relative length (1->no change, 2-> double, 0.5:half) """ a = angle(line) mx, my = middle(line) d = length(line) * factor * 0.5 dx = cos(a) * d dy = sin(a) * d return mx - dx, my - dy, mx + dx, my + dy
[ "def", "resize", "(", "line", ",", "factor", ")", ":", "a", "=", "angle", "(", "line", ")", "mx", ",", "my", "=", "middle", "(", "line", ")", "d", "=", "length", "(", "line", ")", "*", "factor", "*", "0.5", "dx", "=", "cos", "(", "a", ")", ...
factor: relative length (1->no change, 2-> double, 0.5:half)
[ "factor", ":", "relative", "length", "(", "1", "-", ">", "no", "change", "2", "-", ">", "double", "0", ".", "5", ":", "half", ")" ]
python
train
26.5
materialsproject/pymatgen
pymatgen/io/adf.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/adf.py#L305-L325
def has_option(self, option): """ Return True if the option is included in this key. Parameters ---------- option : str The option. Returns ------- has : bool True if the option can be found. Otherwise False will be returned. ...
[ "def", "has_option", "(", "self", ",", "option", ")", ":", "if", "len", "(", "self", ".", "options", ")", "==", "0", ":", "return", "False", "for", "op", "in", "self", ".", "options", ":", "if", "(", "self", ".", "_sized_op", "and", "op", "[", "0...
Return True if the option is included in this key. Parameters ---------- option : str The option. Returns ------- has : bool True if the option can be found. Otherwise False will be returned.
[ "Return", "True", "if", "the", "option", "is", "included", "in", "this", "key", "." ]
python
train
24.761905
valhallasw/flask-mwoauth
flask_mwoauth/__init__.py
https://github.com/valhallasw/flask-mwoauth/blob/216aa9c1ead07d99a9e11deb7642e33a70aa59d7/flask_mwoauth/__init__.py#L124-L158
def request(self, api_query, url=None): """ e.g. {'action': 'query', 'meta': 'userinfo'}. format=json not required function returns a python dict that resembles the api's json response """ api_query['format'] = 'json' if url is not None: api_url = url + "/api....
[ "def", "request", "(", "self", ",", "api_query", ",", "url", "=", "None", ")", ":", "api_query", "[", "'format'", "]", "=", "'json'", "if", "url", "is", "not", "None", ":", "api_url", "=", "url", "+", "\"/api.php\"", "else", ":", "api_url", "=", "sel...
e.g. {'action': 'query', 'meta': 'userinfo'}. format=json not required function returns a python dict that resembles the api's json response
[ "e", ".", "g", ".", "{", "action", ":", "query", "meta", ":", "userinfo", "}", ".", "format", "=", "json", "not", "required", "function", "returns", "a", "python", "dict", "that", "resembles", "the", "api", "s", "json", "response" ]
python
train
40.942857
andreafioraldi/angrdbg
angrdbg/brk.py
https://github.com/andreafioraldi/angrdbg/blob/939b20fb9b341aee695d2db12142b1eddc5b555a/angrdbg/brk.py#L11-L52
def get_dbg_brk_linux64(): ''' Return the current brk value in the debugged process (only x86_64 Linux) ''' # TODO this method is so weird, find a unused address to inject code not # the base address debugger = get_debugger() code = b'\x0f\x05' # syscall rax = debugger.get_reg("rax")...
[ "def", "get_dbg_brk_linux64", "(", ")", ":", "# TODO this method is so weird, find a unused address to inject code not", "# the base address", "debugger", "=", "get_debugger", "(", ")", "code", "=", "b'\\x0f\\x05'", "# syscall", "rax", "=", "debugger", ".", "get_reg", "(", ...
Return the current brk value in the debugged process (only x86_64 Linux)
[ "Return", "the", "current", "brk", "value", "in", "the", "debugged", "process", "(", "only", "x86_64", "Linux", ")" ]
python
train
21.452381
andymccurdy/redis-py
redis/client.py
https://github.com/andymccurdy/redis-py/blob/cdfe2befbe00db4a3c48c9ddd6d64dea15f6f0db/redis/client.py#L3050-L3069
def psubscribe(self, *args, **kwargs): """ Subscribe to channel patterns. Patterns supplied as keyword arguments expect a pattern name as the key and a callable as the value. A pattern's callable will be invoked automatically when a message is received on that pattern rather than...
[ "def", "psubscribe", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "args", ":", "args", "=", "list_or_args", "(", "args", "[", "0", "]", ",", "args", "[", "1", ":", "]", ")", "new_patterns", "=", "dict", ".", "fromkeys",...
Subscribe to channel patterns. Patterns supplied as keyword arguments expect a pattern name as the key and a callable as the value. A pattern's callable will be invoked automatically when a message is received on that pattern rather than producing a message via ``listen()``.
[ "Subscribe", "to", "channel", "patterns", ".", "Patterns", "supplied", "as", "keyword", "arguments", "expect", "a", "pattern", "name", "as", "the", "key", "and", "a", "callable", "as", "the", "value", ".", "A", "pattern", "s", "callable", "will", "be", "in...
python
train
48.45
Genida/archan
src/archan/logging.py
https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/logging.py#L31-L56
def get_logger(name, level=None, fmt=':%(lineno)d: %(message)s'): """ Return a logger. Args: name (str): name to pass to the logging module. level (int): level of logging. fmt (str): format string. Returns: logging.Logger: logger from ``l...
[ "def", "get_logger", "(", "name", ",", "level", "=", "None", ",", "fmt", "=", "':%(lineno)d: %(message)s'", ")", ":", "if", "name", "not", "in", "Logger", ".", "loggers", ":", "if", "Logger", ".", "level", "is", "None", "and", "level", "is", "None", ":...
Return a logger. Args: name (str): name to pass to the logging module. level (int): level of logging. fmt (str): format string. Returns: logging.Logger: logger from ``logging.getLogger``.
[ "Return", "a", "logger", "." ]
python
train
36.5
ronniedada/tabula
tabula/section.py
https://github.com/ronniedada/tabula/blob/ba18bb2f7db75972256b950711415031dc5421c7/tabula/section.py#L109-L138
def align(self, arr): """ Align columns, including column headers """ if arr is None: return arr c_hdrs = self._get_col_hdrs() if self.show_col_hdr_in_cell: for hdr in c_hdrs: arr[hdr] = map(lambda col: ":".join([hdr, str(col)]), ...
[ "def", "align", "(", "self", ",", "arr", ")", ":", "if", "arr", "is", "None", ":", "return", "arr", "c_hdrs", "=", "self", ".", "_get_col_hdrs", "(", ")", "if", "self", ".", "show_col_hdr_in_cell", ":", "for", "hdr", "in", "c_hdrs", ":", "arr", "[", ...
Align columns, including column headers
[ "Align", "columns", "including", "column", "headers" ]
python
train
31.5
adaptive-learning/proso-apps
proso_models/models.py
https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso_models/models.py#L539-L575
def translate_identifiers(self, identifiers, language): """ Translate a list of identifiers to item ids. Identifier is a string of the following form: <model_prefix>/<model_identifier> where <model_prefix> is any suffix of database table of the given model which uniquel...
[ "def", "translate_identifiers", "(", "self", ",", "identifiers", ",", "language", ")", ":", "result", "=", "{", "}", "identifiers", "=", "set", "(", "identifiers", ")", "item_types", "=", "ItemType", ".", "objects", ".", "get_all_types", "(", ")", "for", "...
Translate a list of identifiers to item ids. Identifier is a string of the following form: <model_prefix>/<model_identifier> where <model_prefix> is any suffix of database table of the given model which uniquely specifies the table, and <model_identifier> is identifier of the o...
[ "Translate", "a", "list", "of", "identifiers", "to", "item", "ids", ".", "Identifier", "is", "a", "string", "of", "the", "following", "form", ":" ]
python
train
48.810811
StackStorm/pybind
pybind/nos/v6_0_2f/brocade_firmware_rpc/firmware_download/input/__init__.py
https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/nos/v6_0_2f/brocade_firmware_rpc/firmware_download/input/__init__.py#L167-L188
def _set_sftp(self, v, load=False): """ Setter method for sftp, mapped from YANG variable /brocade_firmware_rpc/firmware_download/input/sftp (container) If this variable is read-only (config: false) in the source YANG file, then _set_sftp is considered as a private method. Backends looking to popula...
[ "def", "_set_sftp", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "base", ...
Setter method for sftp, mapped from YANG variable /brocade_firmware_rpc/firmware_download/input/sftp (container) If this variable is read-only (config: false) in the source YANG file, then _set_sftp is considered as a private method. Backends looking to populate this variable should do so via calling th...
[ "Setter", "method", "for", "sftp", "mapped", "from", "YANG", "variable", "/", "brocade_firmware_rpc", "/", "firmware_download", "/", "input", "/", "sftp", "(", "container", ")", "If", "this", "variable", "is", "read", "-", "only", "(", "config", ":", "false"...
python
train
69.590909
CivicSpleen/ambry
ambry/bundle/bundle.py
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L3029-L3034
def is_installed(self): """Return True if the bundle is installed.""" r = self.library.resolve(self.identity.vid) return r is not None
[ "def", "is_installed", "(", "self", ")", ":", "r", "=", "self", ".", "library", ".", "resolve", "(", "self", ".", "identity", ".", "vid", ")", "return", "r", "is", "not", "None" ]
Return True if the bundle is installed.
[ "Return", "True", "if", "the", "bundle", "is", "installed", "." ]
python
train
25.833333
google/prettytensor
prettytensor/recurrent_networks.py
https://github.com/google/prettytensor/blob/75daa0b11252590f548da5647addc0ea610c4c45/prettytensor/recurrent_networks.py#L250-L322
def gru_cell(input_layer, state, num_units, bias=tf.zeros_initializer(), weights=None, phase=prettytensor.Phase.train, parameter_modifier=parameters.identity): """Gated recurrent unit memory cell (GRU). Args: input_layer: The input l...
[ "def", "gru_cell", "(", "input_layer", ",", "state", ",", "num_units", ",", "bias", "=", "tf", ".", "zeros_initializer", "(", ")", ",", "weights", "=", "None", ",", "phase", "=", "prettytensor", ".", "Phase", ".", "train", ",", "parameter_modifier", "=", ...
Gated recurrent unit memory cell (GRU). Args: input_layer: The input layer. state: The current state of the network. For GRUs, this is a list with one element (tensor) of shape [batch, num_units]. num_units: How big is the hidden state. bias: An initializer for the bias or a Tensor. No bias if ...
[ "Gated", "recurrent", "unit", "memory", "cell", "(", "GRU", ")", "." ]
python
train
36.671233
pandas-dev/pandas
pandas/core/sparse/frame.py
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/sparse/frame.py#L809-L817
def transpose(self, *args, **kwargs): """ Returns a DataFrame with the rows/columns switched. """ nv.validate_transpose(args, kwargs) return self._constructor( self.values.T, index=self.columns, columns=self.index, default_fill_value=self._default_fill_val...
[ "def", "transpose", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "nv", ".", "validate_transpose", "(", "args", ",", "kwargs", ")", "return", "self", ".", "_constructor", "(", "self", ".", "values", ".", "T", ",", "index", "=", ...
Returns a DataFrame with the rows/columns switched.
[ "Returns", "a", "DataFrame", "with", "the", "rows", "/", "columns", "switched", "." ]
python
train
42.111111
wandb/client
wandb/vendor/prompt_toolkit/eventloop/asyncio_posix.py
https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/eventloop/asyncio_posix.py#L28-L86
def run_as_coroutine(self, stdin, callbacks): """ The input 'event loop'. """ assert isinstance(callbacks, EventLoopCallbacks) # Create reader class. stdin_reader = PosixStdinReader(stdin.fileno()) if self.closed: raise Exception('Event loop already ...
[ "def", "run_as_coroutine", "(", "self", ",", "stdin", ",", "callbacks", ")", ":", "assert", "isinstance", "(", "callbacks", ",", "EventLoopCallbacks", ")", "# Create reader class.", "stdin_reader", "=", "PosixStdinReader", "(", "stdin", ".", "fileno", "(", ")", ...
The input 'event loop'.
[ "The", "input", "event", "loop", "." ]
python
train
30.661017
pmacosta/peng
peng/functions.py
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/functions.py#L804-L1051
def pprint_vector(vector, limit=False, width=None, indent=0, eng=False, frac_length=3): r""" Format a list of numbers (vector) or a Numpy vector for printing. If the argument **vector** is :code:`None` the string :code:`'None'` is returned :param vector: Vector to pretty print or None :type v...
[ "def", "pprint_vector", "(", "vector", ",", "limit", "=", "False", ",", "width", "=", "None", ",", "indent", "=", "0", ",", "eng", "=", "False", ",", "frac_length", "=", "3", ")", ":", "# pylint: disable=R0912,R0913", "num_digits", "=", "12", "approx", "...
r""" Format a list of numbers (vector) or a Numpy vector for printing. If the argument **vector** is :code:`None` the string :code:`'None'` is returned :param vector: Vector to pretty print or None :type vector: list of integers or floats, Numpy vector or None :param limit: Flag that indicat...
[ "r", "Format", "a", "list", "of", "numbers", "(", "vector", ")", "or", "a", "Numpy", "vector", "for", "printing", "." ]
python
test
36.447581
NoviceLive/intellicoder
intellicoder/converters.py
https://github.com/NoviceLive/intellicoder/blob/6cac5ebfce65c370dbebe47756a1789b120ef982/intellicoder/converters.py#L64-L69
def from_section(cls, stream, section_name='.pic'): """Construct a Converter object from the specified section of the specified binary stream.""" binary = Executable(stream) section_data = binary.get_section_data(section_name) return cls(section_data, binary.system)
[ "def", "from_section", "(", "cls", ",", "stream", ",", "section_name", "=", "'.pic'", ")", ":", "binary", "=", "Executable", "(", "stream", ")", "section_data", "=", "binary", ".", "get_section_data", "(", "section_name", ")", "return", "cls", "(", "section_...
Construct a Converter object from the specified section of the specified binary stream.
[ "Construct", "a", "Converter", "object", "from", "the", "specified", "section", "of", "the", "specified", "binary", "stream", "." ]
python
train
50.166667
tensorpack/tensorpack
tensorpack/tfutils/tower.py
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/tower.py#L429-L442
def get_variable(self, name): """ Get a variable used in this tower. The name should not contain the variable scope prefix of the tower. When the tower has the same variable scope and name scope, this is equivalent to :meth:`get_tensor`. """ name = get_op_tensor_...
[ "def", "get_variable", "(", "self", ",", "name", ")", ":", "name", "=", "get_op_tensor_name", "(", "name", ")", "[", "1", "]", "if", "len", "(", "self", ".", "vs_name", ")", ":", "name_with_vs", "=", "self", ".", "vs_name", "+", "\"/\"", "+", "name",...
Get a variable used in this tower. The name should not contain the variable scope prefix of the tower. When the tower has the same variable scope and name scope, this is equivalent to :meth:`get_tensor`.
[ "Get", "a", "variable", "used", "in", "this", "tower", ".", "The", "name", "should", "not", "contain", "the", "variable", "scope", "prefix", "of", "the", "tower", "." ]
python
train
35.928571
openstack/networking-cisco
networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py
https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py#L1525-L1557
def run_delete_sm(self, tenant_id, fw_dict, is_fw_virt): """Runs the delete State Machine. Goes through every state function until the end or when one state returns failure. """ # Read the current state from the DB ret = True serv_obj = self.get_service_obj(tenan...
[ "def", "run_delete_sm", "(", "self", ",", "tenant_id", ",", "fw_dict", ",", "is_fw_virt", ")", ":", "# Read the current state from the DB", "ret", "=", "True", "serv_obj", "=", "self", ".", "get_service_obj", "(", "tenant_id", ")", "state", "=", "serv_obj", ".",...
Runs the delete State Machine. Goes through every state function until the end or when one state returns failure.
[ "Runs", "the", "delete", "State", "Machine", "." ]
python
train
42.606061
michael-lazar/rtv
rtv/packages/praw/__init__.py
https://github.com/michael-lazar/rtv/blob/ccef2af042566ad384977028cf0bde01bc524dda/rtv/packages/praw/__init__.py#L2199-L2207
def leave_moderator(self, subreddit): """Abdicate moderator status in a subreddit. Use with care. :param subreddit: The name of the subreddit to leave `status` from. :returns: the json response from the server. """ self.evict(self.config['my_mod_subreddits']) return sel...
[ "def", "leave_moderator", "(", "self", ",", "subreddit", ")", ":", "self", ".", "evict", "(", "self", ".", "config", "[", "'my_mod_subreddits'", "]", ")", "return", "self", ".", "_leave_status", "(", "subreddit", ",", "self", ".", "config", "[", "'leavemod...
Abdicate moderator status in a subreddit. Use with care. :param subreddit: The name of the subreddit to leave `status` from. :returns: the json response from the server.
[ "Abdicate", "moderator", "status", "in", "a", "subreddit", ".", "Use", "with", "care", "." ]
python
train
41
project-rig/rig
rig/machine_control/machine_controller.py
https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/machine_control/machine_controller.py#L1127-L1170
def sdram_alloc_as_filelike(self, size, tag=0, x=Required, y=Required, app_id=Required, clear=False): """Like :py:meth:`.sdram_alloc` but returns a :py:class:`file-like object <.MemoryIO>` which allows safe reading and writing to the block that is allocated. ...
[ "def", "sdram_alloc_as_filelike", "(", "self", ",", "size", ",", "tag", "=", "0", ",", "x", "=", "Required", ",", "y", "=", "Required", ",", "app_id", "=", "Required", ",", "clear", "=", "False", ")", ":", "# Perform the malloc", "start_address", "=", "s...
Like :py:meth:`.sdram_alloc` but returns a :py:class:`file-like object <.MemoryIO>` which allows safe reading and writing to the block that is allocated. Returns ------- :py:class:`.MemoryIO` File-like object which allows accessing the newly allocated region ...
[ "Like", ":", "py", ":", "meth", ":", ".", "sdram_alloc", "but", "returns", "a", ":", "py", ":", "class", ":", "file", "-", "like", "object", "<", ".", "MemoryIO", ">", "which", "allows", "safe", "reading", "and", "writing", "to", "the", "block", "tha...
python
train
46.25
bslatkin/dpxdt
dpxdt/client/workers.py
https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/client/workers.py#L553-L559
def get_coordinator(): """Creates a coordinator and returns it.""" workflow_queue = Queue.Queue() complete_queue = Queue.Queue() coordinator = WorkflowThread(workflow_queue, complete_queue) coordinator.register(WorkflowItem, workflow_queue) return coordinator
[ "def", "get_coordinator", "(", ")", ":", "workflow_queue", "=", "Queue", ".", "Queue", "(", ")", "complete_queue", "=", "Queue", ".", "Queue", "(", ")", "coordinator", "=", "WorkflowThread", "(", "workflow_queue", ",", "complete_queue", ")", "coordinator", "."...
Creates a coordinator and returns it.
[ "Creates", "a", "coordinator", "and", "returns", "it", "." ]
python
train
39.571429
eaton-lab/toytree
toytree/Drawing.py
https://github.com/eaton-lab/toytree/blob/0347ed2098acc5f707fadf52a0ecd411a6d1859c/toytree/Drawing.py#L90-L132
def add_tip_labels_to_axes(self): """ Add text offset from tips of tree with correction for orientation, and fixed_order which is usually used in multitree plotting. """ # get tip-coords and replace if using fixed_order xpos = self.ttree.get_tip_coordinates('x') ...
[ "def", "add_tip_labels_to_axes", "(", "self", ")", ":", "# get tip-coords and replace if using fixed_order", "xpos", "=", "self", ".", "ttree", ".", "get_tip_coordinates", "(", "'x'", ")", "ypos", "=", "self", ".", "ttree", ".", "get_tip_coordinates", "(", "'y'", ...
Add text offset from tips of tree with correction for orientation, and fixed_order which is usually used in multitree plotting.
[ "Add", "text", "offset", "from", "tips", "of", "tree", "with", "correction", "for", "orientation", "and", "fixed_order", "which", "is", "usually", "used", "in", "multitree", "plotting", "." ]
python
train
39.55814
keenlabs/KeenClient-Python
keen/saved_queries.py
https://github.com/keenlabs/KeenClient-Python/blob/266387c3376d1e000d117e17c45045ae3439d43f/keen/saved_queries.py#L93-L139
def update(self, query_name, saved_query_attributes): """ Given a dict of attributes to be updated, update only those attributes in the Saved Query at the resource given by 'query_name'. This will perform two HTTP requests--one to fetch the query definition, and one to set the ne...
[ "def", "update", "(", "self", ",", "query_name", ",", "saved_query_attributes", ")", ":", "query_name_attr_name", "=", "\"query_name\"", "refresh_rate_attr_name", "=", "\"refresh_rate\"", "query_attr_name", "=", "\"query\"", "metadata_attr_name", "=", "\"metadata\"", "old...
Given a dict of attributes to be updated, update only those attributes in the Saved Query at the resource given by 'query_name'. This will perform two HTTP requests--one to fetch the query definition, and one to set the new attributes. This method will intend to preserve any other proper...
[ "Given", "a", "dict", "of", "attributes", "to", "be", "updated", "update", "only", "those", "attributes", "in", "the", "Saved", "Query", "at", "the", "resource", "given", "by", "query_name", ".", "This", "will", "perform", "two", "HTTP", "requests", "--", ...
python
train
43.617021