Unnamed: 0
int64
0
10k
repository_name
stringlengths
7
54
func_path_in_repository
stringlengths
5
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
100
30.3k
language
stringclasses
1 value
func_code_string
stringlengths
100
30.3k
func_code_tokens
stringlengths
138
33.2k
func_documentation_string
stringlengths
1
15k
func_documentation_tokens
stringlengths
5
5.14k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
4,400
BlackEarth/bf
bf/css.py
CSS.cmyk_to_rgb
def cmyk_to_rgb(Class, c, m, y, k): """CMYK in % to RGB in 0-255 based on https://www.openprocessing.org/sketch/46231# """ c = float(c)/100.0 m = float(m)/100.0 y = float(y)/100.0 k = float(k)/100.0 nc = (c * (1-k)) + k nm = (m * (1-k)) ...
python
def cmyk_to_rgb(Class, c, m, y, k): """CMYK in % to RGB in 0-255 based on https://www.openprocessing.org/sketch/46231# """ c = float(c)/100.0 m = float(m)/100.0 y = float(y)/100.0 k = float(k)/100.0 nc = (c * (1-k)) + k nm = (m * (1-k)) ...
['def', 'cmyk_to_rgb', '(', 'Class', ',', 'c', ',', 'm', ',', 'y', ',', 'k', ')', ':', 'c', '=', 'float', '(', 'c', ')', '/', '100.0', 'm', '=', 'float', '(', 'm', ')', '/', '100.0', 'y', '=', 'float', '(', 'y', ')', '/', '100.0', 'k', '=', 'float', '(', 'k', ')', '/', '100.0', 'nc', '=', '(', 'c', '*', '(', '1', '-', ...
CMYK in % to RGB in 0-255 based on https://www.openprocessing.org/sketch/46231#
['CMYK', 'in', '%', 'to', 'RGB', 'in', '0', '-', '255', 'based', 'on', 'https', ':', '//', 'www', '.', 'openprocessing', '.', 'org', '/', 'sketch', '/', '46231#']
train
https://github.com/BlackEarth/bf/blob/376041168874bbd6dee5ccfeece4a9e553223316/bf/css.py#L134-L151
4,401
MillionIntegrals/vel
vel/api/train_phase.py
TrainPhase.epoch_info
def epoch_info(self, training_info: TrainingInfo, global_idx: int, local_idx: int) -> EpochInfo: """ Create Epoch info """ raise NotImplementedError
python
def epoch_info(self, training_info: TrainingInfo, global_idx: int, local_idx: int) -> EpochInfo: """ Create Epoch info """ raise NotImplementedError
['def', 'epoch_info', '(', 'self', ',', 'training_info', ':', 'TrainingInfo', ',', 'global_idx', ':', 'int', ',', 'local_idx', ':', 'int', ')', '->', 'EpochInfo', ':', 'raise', 'NotImplementedError']
Create Epoch info
['Create', 'Epoch', 'info']
train
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/api/train_phase.py#L24-L26
4,402
pytroll/posttroll
posttroll/listener.py
Listener.create_subscriber
def create_subscriber(self): '''Create a subscriber instance using specified addresses and message types. ''' if self.subscriber is None: if self.topics: self.subscriber = NSSubscriber(self.services, self.topics, ...
python
def create_subscriber(self): '''Create a subscriber instance using specified addresses and message types. ''' if self.subscriber is None: if self.topics: self.subscriber = NSSubscriber(self.services, self.topics, ...
['def', 'create_subscriber', '(', 'self', ')', ':', 'if', 'self', '.', 'subscriber', 'is', 'None', ':', 'if', 'self', '.', 'topics', ':', 'self', '.', 'subscriber', '=', 'NSSubscriber', '(', 'self', '.', 'services', ',', 'self', '.', 'topics', ',', 'addr_listener', '=', 'True', ',', 'addresses', '=', 'self', '.', 'addr...
Create a subscriber instance using specified addresses and message types.
['Create', 'a', 'subscriber', 'instance', 'using', 'specified', 'addresses', 'and', 'message', 'types', '.']
train
https://github.com/pytroll/posttroll/blob/8e811a0544b5182c4a72aed074b2ff8c4324e94d/posttroll/listener.py#L105-L115
4,403
pandas-dev/pandas
pandas/core/generic.py
NDFrame._consolidate
def _consolidate(self, inplace=False): """ Compute NDFrame with "consolidated" internals (data of each dtype grouped together in a single ndarray). Parameters ---------- inplace : boolean, default False If False return new object, otherwise modify existing ob...
python
def _consolidate(self, inplace=False): """ Compute NDFrame with "consolidated" internals (data of each dtype grouped together in a single ndarray). Parameters ---------- inplace : boolean, default False If False return new object, otherwise modify existing ob...
['def', '_consolidate', '(', 'self', ',', 'inplace', '=', 'False', ')', ':', 'inplace', '=', 'validate_bool_kwarg', '(', 'inplace', ',', "'inplace'", ')', 'if', 'inplace', ':', 'self', '.', '_consolidate_inplace', '(', ')', 'else', ':', 'f', '=', 'lambda', ':', 'self', '.', '_data', '.', 'consolidate', '(', ')', 'cons_...
Compute NDFrame with "consolidated" internals (data of each dtype grouped together in a single ndarray). Parameters ---------- inplace : boolean, default False If False return new object, otherwise modify existing object Returns ------- consolidated ...
['Compute', 'NDFrame', 'with', 'consolidated', 'internals', '(', 'data', 'of', 'each', 'dtype', 'grouped', 'together', 'in', 'a', 'single', 'ndarray', ')', '.']
train
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/generic.py#L5173-L5193
4,404
OzymandiasTheGreat/python-libinput
libinput/device.py
DeviceConfigCalibration.matrix
def matrix(self): """The current calibration matrix for this device. Returns: (bool, (float, float, float, float, float, float)): :obj:`False` if no calibration is set and the returned matrix is the identity matrix, :obj:`True` otherwise. :obj:`tuple` representing the first two rows of a 3x3 matrix ...
python
def matrix(self): """The current calibration matrix for this device. Returns: (bool, (float, float, float, float, float, float)): :obj:`False` if no calibration is set and the returned matrix is the identity matrix, :obj:`True` otherwise. :obj:`tuple` representing the first two rows of a 3x3 matrix ...
['def', 'matrix', '(', 'self', ')', ':', 'matrix', '=', '(', 'c_float', '*', '6', ')', '(', ')', 'rc', '=', 'self', '.', '_libinput', '.', 'libinput_device_config_calibration_get_matrix', '(', 'self', '.', '_handle', ',', 'matrix', ')', 'return', 'rc', ',', 'tuple', '(', 'matrix', ')']
The current calibration matrix for this device. Returns: (bool, (float, float, float, float, float, float)): :obj:`False` if no calibration is set and the returned matrix is the identity matrix, :obj:`True` otherwise. :obj:`tuple` representing the first two rows of a 3x3 matrix as described in :meth:`...
['The', 'current', 'calibration', 'matrix', 'for', 'this', 'device', '.']
train
https://github.com/OzymandiasTheGreat/python-libinput/blob/1f477ee9f1d56b284b20e0317ea8967c64ef1218/libinput/device.py#L540-L554
4,405
Crypto-toolbox/bitex
bitex/api/WSS/bitfinex.py
BitfinexWSS.restart
def restart(self, soft=False): """ Restarts client. If soft is True, the client attempts to re-subscribe to all channels which it was previously subscribed to. :return: """ log.info("BitfinexWSS.restart(): Restarting client..") super(BitfinexWSS, self).restart() ...
python
def restart(self, soft=False): """ Restarts client. If soft is True, the client attempts to re-subscribe to all channels which it was previously subscribed to. :return: """ log.info("BitfinexWSS.restart(): Restarting client..") super(BitfinexWSS, self).restart() ...
['def', 'restart', '(', 'self', ',', 'soft', '=', 'False', ')', ':', 'log', '.', 'info', '(', '"BitfinexWSS.restart(): Restarting client.."', ')', 'super', '(', 'BitfinexWSS', ',', 'self', ')', '.', 'restart', '(', ')', '# cache channel labels temporarily if soft == True', 'channel_labels', '=', '[', 'self', '.', 'chan...
Restarts client. If soft is True, the client attempts to re-subscribe to all channels which it was previously subscribed to. :return:
['Restarts', 'client', '.', 'If', 'soft', 'is', 'True', 'the', 'client', 'attempts', 'to', 're', '-', 'subscribe', 'to', 'all', 'channels', 'which', 'it', 'was', 'previously', 'subscribed', 'to', '.', ':', 'return', ':']
train
https://github.com/Crypto-toolbox/bitex/blob/56d46ea3db6de5219a72dad9b052fbabc921232f/bitex/api/WSS/bitfinex.py#L255-L275
4,406
pypa/pipenv
pipenv/vendor/distlib/database.py
DependencyGraph.add_edge
def add_edge(self, x, y, label=None): """Add an edge from distribution *x* to distribution *y* with the given *label*. :type x: :class:`distutils2.database.InstalledDistribution` or :class:`distutils2.database.EggInfoDistribution` :type y: :class:`distutils2.database.In...
python
def add_edge(self, x, y, label=None): """Add an edge from distribution *x* to distribution *y* with the given *label*. :type x: :class:`distutils2.database.InstalledDistribution` or :class:`distutils2.database.EggInfoDistribution` :type y: :class:`distutils2.database.In...
['def', 'add_edge', '(', 'self', ',', 'x', ',', 'y', ',', 'label', '=', 'None', ')', ':', 'self', '.', 'adjacency_list', '[', 'x', ']', '.', 'append', '(', '(', 'y', ',', 'label', ')', ')', '# multiple edges are allowed, so be careful', 'if', 'x', 'not', 'in', 'self', '.', 'reverse_list', '[', 'y', ']', ':', 'self', '....
Add an edge from distribution *x* to distribution *y* with the given *label*. :type x: :class:`distutils2.database.InstalledDistribution` or :class:`distutils2.database.EggInfoDistribution` :type y: :class:`distutils2.database.InstalledDistribution` or :class:`...
['Add', 'an', 'edge', 'from', 'distribution', '*', 'x', '*', 'to', 'distribution', '*', 'y', '*', 'with', 'the', 'given', '*', 'label', '*', '.']
train
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L1112-L1125
4,407
ArchiveTeam/wpull
wpull/stats.py
Statistics.increment
def increment(self, size: int): '''Increment the number of files downloaded. Args: size: The size of the file ''' assert size >= 0, size self.files += 1 self.size += size self.bandwidth_meter.feed(size)
python
def increment(self, size: int): '''Increment the number of files downloaded. Args: size: The size of the file ''' assert size >= 0, size self.files += 1 self.size += size self.bandwidth_meter.feed(size)
['def', 'increment', '(', 'self', ',', 'size', ':', 'int', ')', ':', 'assert', 'size', '>=', '0', ',', 'size', 'self', '.', 'files', '+=', '1', 'self', '.', 'size', '+=', 'size', 'self', '.', 'bandwidth_meter', '.', 'feed', '(', 'size', ')']
Increment the number of files downloaded. Args: size: The size of the file
['Increment', 'the', 'number', 'of', 'files', 'downloaded', '.']
train
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/stats.py#L56-L66
4,408
gccxml/pygccxml
pygccxml/parser/directory_cache.py
directory_cache_t._save
def _save(self): """ save the cache index, in case it was modified. Saves the index table and the file name repository in the file `index.dat` """ if self.__modified_flag: self.__filename_rep.update_id_counter() indexfilename = os.path.join(self....
python
def _save(self): """ save the cache index, in case it was modified. Saves the index table and the file name repository in the file `index.dat` """ if self.__modified_flag: self.__filename_rep.update_id_counter() indexfilename = os.path.join(self....
['def', '_save', '(', 'self', ')', ':', 'if', 'self', '.', '__modified_flag', ':', 'self', '.', '__filename_rep', '.', 'update_id_counter', '(', ')', 'indexfilename', '=', 'os', '.', 'path', '.', 'join', '(', 'self', '.', '__dir', ',', '"index.dat"', ')', 'self', '.', '_write_file', '(', 'indexfilename', ',', '(', 'sel...
save the cache index, in case it was modified. Saves the index table and the file name repository in the file `index.dat`
['save', 'the', 'cache', 'index', 'in', 'case', 'it', 'was', 'modified', '.']
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/directory_cache.py#L245-L261
4,409
chriso/gauged
gauged/writer.py
Writer.clear_from
def clear_from(self, timestamp): """Clear all data from `timestamp` onwards. Note that the timestamp is rounded down to the nearest block boundary""" block_size = self.config.block_size offset, remainder = timestamp // block_size, timestamp % block_size if remainder: ...
python
def clear_from(self, timestamp): """Clear all data from `timestamp` onwards. Note that the timestamp is rounded down to the nearest block boundary""" block_size = self.config.block_size offset, remainder = timestamp // block_size, timestamp % block_size if remainder: ...
['def', 'clear_from', '(', 'self', ',', 'timestamp', ')', ':', 'block_size', '=', 'self', '.', 'config', '.', 'block_size', 'offset', ',', 'remainder', '=', 'timestamp', '//', 'block_size', ',', 'timestamp', '%', 'block_size', 'if', 'remainder', ':', 'raise', 'ValueError', '(', "'Timestamp must be on a block boundary'"...
Clear all data from `timestamp` onwards. Note that the timestamp is rounded down to the nearest block boundary
['Clear', 'all', 'data', 'from', 'timestamp', 'onwards', '.', 'Note', 'that', 'the', 'timestamp', 'is', 'rounded', 'down', 'to', 'the', 'nearest', 'block', 'boundary']
train
https://github.com/chriso/gauged/blob/cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976/gauged/writer.py#L170-L177
4,410
linode/linode_api4-python
linode_api4/objects/linode.py
Instance.initiate_migration
def initiate_migration(self): """ Initiates a pending migration that is already scheduled for this Linode Instance """ self._client.post('{}/migrate'.format(Instance.api_endpoint), model=self)
python
def initiate_migration(self): """ Initiates a pending migration that is already scheduled for this Linode Instance """ self._client.post('{}/migrate'.format(Instance.api_endpoint), model=self)
['def', 'initiate_migration', '(', 'self', ')', ':', 'self', '.', '_client', '.', 'post', '(', "'{}/migrate'", '.', 'format', '(', 'Instance', '.', 'api_endpoint', ')', ',', 'model', '=', 'self', ')']
Initiates a pending migration that is already scheduled for this Linode Instance
['Initiates', 'a', 'pending', 'migration', 'that', 'is', 'already', 'scheduled', 'for', 'this', 'Linode', 'Instance']
train
https://github.com/linode/linode_api4-python/blob/1dd7318d2aed014c746d48c7957464c57af883ca/linode_api4/objects/linode.py#L643-L648
4,411
mikedh/trimesh
trimesh/triangles.py
cross
def cross(triangles): """ Returns the cross product of two edges from input triangles Parameters -------------- triangles: (n, 3, 3) float Vertices of triangles Returns -------------- crosses : (n, 3) float Cross product of two edge vectors """ vectors = np.diff(tri...
python
def cross(triangles): """ Returns the cross product of two edges from input triangles Parameters -------------- triangles: (n, 3, 3) float Vertices of triangles Returns -------------- crosses : (n, 3) float Cross product of two edge vectors """ vectors = np.diff(tri...
['def', 'cross', '(', 'triangles', ')', ':', 'vectors', '=', 'np', '.', 'diff', '(', 'triangles', ',', 'axis', '=', '1', ')', 'crosses', '=', 'np', '.', 'cross', '(', 'vectors', '[', ':', ',', '0', ']', ',', 'vectors', '[', ':', ',', '1', ']', ')', 'return', 'crosses']
Returns the cross product of two edges from input triangles Parameters -------------- triangles: (n, 3, 3) float Vertices of triangles Returns -------------- crosses : (n, 3) float Cross product of two edge vectors
['Returns', 'the', 'cross', 'product', 'of', 'two', 'edges', 'from', 'input', 'triangles']
train
https://github.com/mikedh/trimesh/blob/25e059bf6d4caa74f62ffd58ce4f61a90ee4e518/trimesh/triangles.py#L15-L31
4,412
hyperledger/indy-sdk
vcx/wrappers/python3/vcx/api/disclosed_proof.py
DisclosedProof.get_creds
async def get_creds(self) -> dict: """ Gets the credentials from a disclosed proof Example: msg_id = '1' phone_number = '8019119191' connection = await Connection.create(source_id) await connection.connect(phone_number) disclosed_proof = await DisclosedPro...
python
async def get_creds(self) -> dict: """ Gets the credentials from a disclosed proof Example: msg_id = '1' phone_number = '8019119191' connection = await Connection.create(source_id) await connection.connect(phone_number) disclosed_proof = await DisclosedPro...
['async', 'def', 'get_creds', '(', 'self', ')', '->', 'dict', ':', 'if', 'not', 'hasattr', '(', 'DisclosedProof', '.', 'get_creds', ',', '"cb"', ')', ':', 'self', '.', 'logger', '.', 'debug', '(', '"vcx_disclosed_proof_retrieve_credentials: Creating callback"', ')', 'DisclosedProof', '.', 'get_creds', '.', 'cb', '=', '...
Gets the credentials from a disclosed proof Example: msg_id = '1' phone_number = '8019119191' connection = await Connection.create(source_id) await connection.connect(phone_number) disclosed_proof = await DisclosedProof.create_with_msgid(source_id, connection, msg_id) ...
['Gets', 'the', 'credentials', 'from', 'a', 'disclosed', 'proof', 'Example', ':', 'msg_id', '=', '1', 'phone_number', '=', '8019119191', 'connection', '=', 'await', 'Connection', '.', 'create', '(', 'source_id', ')', 'await', 'connection', '.', 'connect', '(', 'phone_number', ')', 'disclosed_proof', '=', 'await', 'Disc...
train
https://github.com/hyperledger/indy-sdk/blob/55240dc170308d7883c48f03f308130a6d077be6/vcx/wrappers/python3/vcx/api/disclosed_proof.py#L204-L225
4,413
Sanji-IO/sanji
sanji/model_initiator.py
ModelInitiator.backup_db
def backup_db(self): """ " Generate a xxxxx.backup.json. """ with self.db_mutex: if os.path.exists(self.json_db_path): try: shutil.copy2(self.json_db_path, self.backup_json_db_path) except (IOError, OSError): ...
python
def backup_db(self): """ " Generate a xxxxx.backup.json. """ with self.db_mutex: if os.path.exists(self.json_db_path): try: shutil.copy2(self.json_db_path, self.backup_json_db_path) except (IOError, OSError): ...
['def', 'backup_db', '(', 'self', ')', ':', 'with', 'self', '.', 'db_mutex', ':', 'if', 'os', '.', 'path', '.', 'exists', '(', 'self', '.', 'json_db_path', ')', ':', 'try', ':', 'shutil', '.', 'copy2', '(', 'self', '.', 'json_db_path', ',', 'self', '.', 'backup_json_db_path', ')', 'except', '(', 'IOError', ',', 'OSErro...
" Generate a xxxxx.backup.json.
['Generate', 'a', 'xxxxx', '.', 'backup', '.', 'json', '.']
train
https://github.com/Sanji-IO/sanji/blob/5c54cc2772bdfeae3337f785de1957237b828b34/sanji/model_initiator.py#L112-L121
4,414
aws/aws-encryption-sdk-python
src/aws_encryption_sdk/key_providers/raw.py
RawMasterKey.owns_data_key
def owns_data_key(self, data_key): """Determines if data_key object is owned by this RawMasterKey. :param data_key: Data key to evaluate :type data_key: :class:`aws_encryption_sdk.structures.DataKey`, :class:`aws_encryption_sdk.structures.RawDataKey`, or :class:`aws_encr...
python
def owns_data_key(self, data_key): """Determines if data_key object is owned by this RawMasterKey. :param data_key: Data key to evaluate :type data_key: :class:`aws_encryption_sdk.structures.DataKey`, :class:`aws_encryption_sdk.structures.RawDataKey`, or :class:`aws_encr...
['def', 'owns_data_key', '(', 'self', ',', 'data_key', ')', ':', 'expected_key_info_len', '=', '-', '1', 'if', '(', 'self', '.', 'config', '.', 'wrapping_key', '.', 'wrapping_algorithm', '.', 'encryption_type', 'is', 'EncryptionType', '.', 'ASYMMETRIC', 'and', 'data_key', '.', 'key_provider', '==', 'self', '.', 'key_pr...
Determines if data_key object is owned by this RawMasterKey. :param data_key: Data key to evaluate :type data_key: :class:`aws_encryption_sdk.structures.DataKey`, :class:`aws_encryption_sdk.structures.RawDataKey`, or :class:`aws_encryption_sdk.structures.EncryptedDataKey` ...
['Determines', 'if', 'data_key', 'object', 'is', 'owned', 'by', 'this', 'RawMasterKey', '.']
train
https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/key_providers/raw.py#L75-L113
4,415
scopus-api/scopus
scopus/author_retrieval.py
AuthorRetrieval.get_documents
def get_documents(self, subtypes=None, refresh=False): """Return list of author's publications using ScopusSearch, which fit a specified set of document subtypes. """ search = ScopusSearch('au-id({})'.format(self.identifier), refresh) if subtypes: return [p for p in s...
python
def get_documents(self, subtypes=None, refresh=False): """Return list of author's publications using ScopusSearch, which fit a specified set of document subtypes. """ search = ScopusSearch('au-id({})'.format(self.identifier), refresh) if subtypes: return [p for p in s...
['def', 'get_documents', '(', 'self', ',', 'subtypes', '=', 'None', ',', 'refresh', '=', 'False', ')', ':', 'search', '=', 'ScopusSearch', '(', "'au-id({})'", '.', 'format', '(', 'self', '.', 'identifier', ')', ',', 'refresh', ')', 'if', 'subtypes', ':', 'return', '[', 'p', 'for', 'p', 'in', 'search', '.', 'results', '...
Return list of author's publications using ScopusSearch, which fit a specified set of document subtypes.
['Return', 'list', 'of', 'author', 's', 'publications', 'using', 'ScopusSearch', 'which', 'fit', 'a', 'specified', 'set', 'of', 'document', 'subtypes', '.']
train
https://github.com/scopus-api/scopus/blob/27ce02dd3095bfdab9d3e8475543d7c17767d1ab/scopus/author_retrieval.py#L280-L288
4,416
i3visio/osrframework
osrframework/searchengines/google.py
search
def search(query, tld='com', lang='en', num=10, start=0, stop=None, pause=2.0, only_standard=False): """ Search the given query string using Google. @type query: str @param query: Query string. Must NOT be url-encoded. @type tld: str @param tld: Top level domain. @...
python
def search(query, tld='com', lang='en', num=10, start=0, stop=None, pause=2.0, only_standard=False): """ Search the given query string using Google. @type query: str @param query: Query string. Must NOT be url-encoded. @type tld: str @param tld: Top level domain. @...
['def', 'search', '(', 'query', ',', 'tld', '=', "'com'", ',', 'lang', '=', "'en'", ',', 'num', '=', '10', ',', 'start', '=', '0', ',', 'stop', '=', 'None', ',', 'pause', '=', '2.0', ',', 'only_standard', '=', 'False', ')', ':', '# Lazy import of BeautifulSoup.\r', '# Try to use BeautifulSoup 4 if available, fall back ...
Search the given query string using Google. @type query: str @param query: Query string. Must NOT be url-encoded. @type tld: str @param tld: Top level domain. @type lang: str @param lang: Languaje. @type num: int @param num: Number of results per page. @type s...
['Search', 'the', 'given', 'query', 'string', 'using', 'Google', '.']
train
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/searchengines/google.py#L114-L234
4,417
estnltk/estnltk
estnltk/vabamorf/morf.py
get_group_tokens
def get_group_tokens(root): """Function to extract tokens in hyphenated groups (saunameheks-tallimeheks). Parameters ---------- root: str The root form. Returns ------- list of (list of str) List of grouped root tokens. """ global all_markers if root in all_mark...
python
def get_group_tokens(root): """Function to extract tokens in hyphenated groups (saunameheks-tallimeheks). Parameters ---------- root: str The root form. Returns ------- list of (list of str) List of grouped root tokens. """ global all_markers if root in all_mark...
['def', 'get_group_tokens', '(', 'root', ')', ':', 'global', 'all_markers', 'if', 'root', 'in', 'all_markers', 'or', 'root', 'in', '[', "'-'", ',', "'_'", ']', ':', '# special case', 'return', '[', '[', 'root', ']', ']', 'groups', '=', '[', ']', 'for', 'group', 'in', 'root', '.', 'split', '(', "'-'", ')', ':', 'toks', ...
Function to extract tokens in hyphenated groups (saunameheks-tallimeheks). Parameters ---------- root: str The root form. Returns ------- list of (list of str) List of grouped root tokens.
['Function', 'to', 'extract', 'tokens', 'in', 'hyphenated', 'groups', '(', 'saunameheks', '-', 'tallimeheks', ')', '.']
train
https://github.com/estnltk/estnltk/blob/28ae334a68a0673072febc318635f04da0dcc54a/estnltk/vabamorf/morf.py#L390-L410
4,418
PMEAL/OpenPNM
openpnm/io/Statoil.py
Statoil.load
def load(cls, path, prefix, network=None): r""" Load data from the \'dat\' files located in specified folder. Parameters ---------- path : string The full path to the folder containing the set of \'dat\' files. prefix : string The file name prefi...
python
def load(cls, path, prefix, network=None): r""" Load data from the \'dat\' files located in specified folder. Parameters ---------- path : string The full path to the folder containing the set of \'dat\' files. prefix : string The file name prefi...
['def', 'load', '(', 'cls', ',', 'path', ',', 'prefix', ',', 'network', '=', 'None', ')', ':', 'net', '=', '{', '}', '# ---------------------------------------------------------------------', '# Parse the link1 file', 'path', '=', 'Path', '(', 'path', ')', 'filename', '=', 'Path', '(', 'path', '.', 'resolve', '(', ')',...
r""" Load data from the \'dat\' files located in specified folder. Parameters ---------- path : string The full path to the folder containing the set of \'dat\' files. prefix : string The file name prefix on each file. The data files are stored ...
['r', 'Load', 'data', 'from', 'the', '\\', 'dat', '\\', 'files', 'located', 'in', 'specified', 'folder', '.']
train
https://github.com/PMEAL/OpenPNM/blob/0547b5724ffedc0a593aae48639d36fe10e0baed/openpnm/io/Statoil.py#L28-L143
4,419
openatx/facebook-wda
wda/__init__.py
Session.screenshot
def screenshot(self): """ Take screenshot with session check Returns: PIL.Image """ b64data = self.http.get('/screenshot').value raw_data = base64.b64decode(b64data) from PIL import Image buff = io.BytesIO(raw_data) return Image.open(b...
python
def screenshot(self): """ Take screenshot with session check Returns: PIL.Image """ b64data = self.http.get('/screenshot').value raw_data = base64.b64decode(b64data) from PIL import Image buff = io.BytesIO(raw_data) return Image.open(b...
['def', 'screenshot', '(', 'self', ')', ':', 'b64data', '=', 'self', '.', 'http', '.', 'get', '(', "'/screenshot'", ')', '.', 'value', 'raw_data', '=', 'base64', '.', 'b64decode', '(', 'b64data', ')', 'from', 'PIL', 'import', 'Image', 'buff', '=', 'io', '.', 'BytesIO', '(', 'raw_data', ')', 'return', 'Image', '.', 'ope...
Take screenshot with session check Returns: PIL.Image
['Take', 'screenshot', 'with', 'session', 'check']
train
https://github.com/openatx/facebook-wda/blob/aa644204620c6d5c7705a9c7452d8c0cc39330d5/wda/__init__.py#L463-L474
4,420
dingusdk/PythonIhcSdk
ihcsdk/ihccontroller.py
IHCController.set_runtime_value_bool
def set_runtime_value_bool(self, ihcid: int, value: bool) -> bool: """ Set bool runtime value with re-authenticate if needed""" if self.client.set_runtime_value_bool(ihcid, value): return True self.re_authenticate() return self.client.set_runtime_value_bool(ihcid, value)
python
def set_runtime_value_bool(self, ihcid: int, value: bool) -> bool: """ Set bool runtime value with re-authenticate if needed""" if self.client.set_runtime_value_bool(ihcid, value): return True self.re_authenticate() return self.client.set_runtime_value_bool(ihcid, value)
['def', 'set_runtime_value_bool', '(', 'self', ',', 'ihcid', ':', 'int', ',', 'value', ':', 'bool', ')', '->', 'bool', ':', 'if', 'self', '.', 'client', '.', 'set_runtime_value_bool', '(', 'ihcid', ',', 'value', ')', ':', 'return', 'True', 'self', '.', 're_authenticate', '(', ')', 'return', 'self', '.', 'client', '.', ...
Set bool runtime value with re-authenticate if needed
['Set', 'bool', 'runtime', 'value', 'with', 're', '-', 'authenticate', 'if', 'needed']
train
https://github.com/dingusdk/PythonIhcSdk/blob/7e2067e009fe7600b49f30bff1cf91dc72fc891e/ihcsdk/ihccontroller.py#L54-L59
4,421
mlperf/training
translation/tensorflow/transformer/utils/tokenizer.py
_unicode_to_native
def _unicode_to_native(s): """Convert string from unicode to native format (required in Python 2).""" if six.PY2: return s.encode("utf-8") if isinstance(s, unicode) else s else: return s
python
def _unicode_to_native(s): """Convert string from unicode to native format (required in Python 2).""" if six.PY2: return s.encode("utf-8") if isinstance(s, unicode) else s else: return s
['def', '_unicode_to_native', '(', 's', ')', ':', 'if', 'six', '.', 'PY2', ':', 'return', 's', '.', 'encode', '(', '"utf-8"', ')', 'if', 'isinstance', '(', 's', ',', 'unicode', ')', 'else', 's', 'else', ':', 'return', 's']
Convert string from unicode to native format (required in Python 2).
['Convert', 'string', 'from', 'unicode', 'to', 'native', 'format', '(', 'required', 'in', 'Python', '2', ')', '.']
train
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/utils/tokenizer.py#L216-L221
4,422
MLAB-project/pymlab
src/pymlab/sensors/clkgen.py
CLKGEN01.set_freq
def set_freq(self, fout, freq): """ Sets new output frequency, required parameters are real current frequency at output and new required frequency. """ hsdiv_tuple = (4, 5, 6, 7, 9, 11) # possible dividers n1div_tuple = (1,) + tuple(range(2,129,2)) # fdco_min =...
python
def set_freq(self, fout, freq): """ Sets new output frequency, required parameters are real current frequency at output and new required frequency. """ hsdiv_tuple = (4, 5, 6, 7, 9, 11) # possible dividers n1div_tuple = (1,) + tuple(range(2,129,2)) # fdco_min =...
['def', 'set_freq', '(', 'self', ',', 'fout', ',', 'freq', ')', ':', 'hsdiv_tuple', '=', '(', '4', ',', '5', ',', '6', ',', '7', ',', '9', ',', '11', ')', '# possible dividers', 'n1div_tuple', '=', '(', '1', ',', ')', '+', 'tuple', '(', 'range', '(', '2', ',', '129', ',', '2', ')', ')', '#', 'fdco_min', '=', '5670.0', ...
Sets new output frequency, required parameters are real current frequency at output and new required frequency.
['Sets', 'new', 'output', 'frequency', 'required', 'parameters', 'are', 'real', 'current', 'frequency', 'at', 'output', 'and', 'new', 'required', 'frequency', '.']
train
https://github.com/MLAB-project/pymlab/blob/d18d858ae83b203defcf2aead0dbd11b3c444658/src/pymlab/sensors/clkgen.py#L102-L139
4,423
allenai/allennlp
allennlp/state_machines/trainers/decoder_trainer.py
DecoderTrainer.decode
def decode(self, initial_state: State, transition_function: TransitionFunction, supervision: SupervisionType) -> Dict[str, torch.Tensor]: """ Takes an initial state object, a means of transitioning from state to state, and a supervision signal, and us...
python
def decode(self, initial_state: State, transition_function: TransitionFunction, supervision: SupervisionType) -> Dict[str, torch.Tensor]: """ Takes an initial state object, a means of transitioning from state to state, and a supervision signal, and us...
['def', 'decode', '(', 'self', ',', 'initial_state', ':', 'State', ',', 'transition_function', ':', 'TransitionFunction', ',', 'supervision', ':', 'SupervisionType', ')', '->', 'Dict', '[', 'str', ',', 'torch', '.', 'Tensor', ']', ':', 'raise', 'NotImplementedError']
Takes an initial state object, a means of transitioning from state to state, and a supervision signal, and uses the supervision to train the transition function to pick "good" states. This function should typically return a ``loss`` key during training, which the ``Model`` will use as i...
['Takes', 'an', 'initial', 'state', 'object', 'a', 'means', 'of', 'transitioning', 'from', 'state', 'to', 'state', 'and', 'a', 'supervision', 'signal', 'and', 'uses', 'the', 'supervision', 'to', 'train', 'the', 'transition', 'function', 'to', 'pick', 'good', 'states', '.']
train
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/state_machines/trainers/decoder_trainer.py#L24-L52
4,424
StackStorm/pybind
pybind/slxos/v17s_1_02/mpls_state/rsvp/__init__.py
rsvp._set_igp_sync
def _set_igp_sync(self, v, load=False): """ Setter method for igp_sync, mapped from YANG variable /mpls_state/rsvp/igp_sync (container) If this variable is read-only (config: false) in the source YANG file, then _set_igp_sync is considered as a private method. Backends looking to populate this varia...
python
def _set_igp_sync(self, v, load=False): """ Setter method for igp_sync, mapped from YANG variable /mpls_state/rsvp/igp_sync (container) If this variable is read-only (config: false) in the source YANG file, then _set_igp_sync is considered as a private method. Backends looking to populate this varia...
['def', '_set_igp_sync', '(', 'self', ',', 'v', ',', 'load', '=', 'False', ')', ':', 'if', 'hasattr', '(', 'v', ',', '"_utype"', ')', ':', 'v', '=', 'v', '.', '_utype', '(', 'v', ')', 'try', ':', 't', '=', 'YANGDynClass', '(', 'v', ',', 'base', '=', 'igp_sync', '.', 'igp_sync', ',', 'is_container', '=', "'container'", ...
Setter method for igp_sync, mapped from YANG variable /mpls_state/rsvp/igp_sync (container) If this variable is read-only (config: false) in the source YANG file, then _set_igp_sync is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_igp_sy...
['Setter', 'method', 'for', 'igp_sync', 'mapped', 'from', 'YANG', 'variable', '/', 'mpls_state', '/', 'rsvp', '/', 'igp_sync', '(', 'container', ')', 'If', 'this', 'variable', 'is', 'read', '-', 'only', '(', 'config', ':', 'false', ')', 'in', 'the', 'source', 'YANG', 'file', 'then', '_set_igp_sync', 'is', 'considered',...
train
https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17s_1_02/mpls_state/rsvp/__init__.py#L407-L430
4,425
IzunaDevs/SnekChek
snekchek/__main__.py
run_main
def run_main(args: argparse.Namespace, do_exit=True) -> None: """Runs the checks and exits. To extend this tool, use this function and set do_exit to False to get returned the status code. """ if args.init: generate() return None # exit after generate instead of starting to lint ...
python
def run_main(args: argparse.Namespace, do_exit=True) -> None: """Runs the checks and exits. To extend this tool, use this function and set do_exit to False to get returned the status code. """ if args.init: generate() return None # exit after generate instead of starting to lint ...
['def', 'run_main', '(', 'args', ':', 'argparse', '.', 'Namespace', ',', 'do_exit', '=', 'True', ')', '->', 'None', ':', 'if', 'args', '.', 'init', ':', 'generate', '(', ')', 'return', 'None', '# exit after generate instead of starting to lint', 'handler', '=', 'CheckHandler', '(', 'file', '=', 'args', '.', 'config_fil...
Runs the checks and exits. To extend this tool, use this function and set do_exit to False to get returned the status code.
['Runs', 'the', 'checks', 'and', 'exits', '.']
train
https://github.com/IzunaDevs/SnekChek/blob/fdb01bdf1ec8e79d9aae2a11d96bfb27e53a97a9/snekchek/__main__.py#L39-L72
4,426
rackerlabs/simpl
simpl/config.py
Config.validate_config
def validate_config(self, values, argv=None, strict=False): """Validate all config values through the command-line parser. This takes all supplied options (which could have been retrieved from a number of sources (such as CLI, env vars, etc...) and then validates them by running them th...
python
def validate_config(self, values, argv=None, strict=False): """Validate all config values through the command-line parser. This takes all supplied options (which could have been retrieved from a number of sources (such as CLI, env vars, etc...) and then validates them by running them th...
['def', 'validate_config', '(', 'self', ',', 'values', ',', 'argv', '=', 'None', ',', 'strict', '=', 'False', ')', ':', 'options', '=', '[', ']', 'for', 'option', 'in', 'self', '.', '_options', ':', 'kwargs', '=', 'option', '.', 'kwargs', '.', 'copy', '(', ')', 'if', 'option', '.', 'name', 'in', 'values', ':', 'if', "'...
Validate all config values through the command-line parser. This takes all supplied options (which could have been retrieved from a number of sources (such as CLI, env vars, etc...) and then validates them by running them through argparser (and raises SystemExit on failure). :r...
['Validate', 'all', 'config', 'values', 'through', 'the', 'command', '-', 'line', 'parser', '.']
train
https://github.com/rackerlabs/simpl/blob/60ed3336a931cd6a7a7246e60f26165d9dc7c99c/simpl/config.py#L511-L572
4,427
fitnr/twitter_bot_utils
twitter_bot_utils/helpers.py
has_entities
def has_entities(status): """ Returns true if a Status object has entities. Args: status: either a tweepy.Status object or a dict returned from Twitter API """ try: if sum(len(v) for v in status.entities.values()) > 0: return True except AttributeError: if s...
python
def has_entities(status): """ Returns true if a Status object has entities. Args: status: either a tweepy.Status object or a dict returned from Twitter API """ try: if sum(len(v) for v in status.entities.values()) > 0: return True except AttributeError: if s...
['def', 'has_entities', '(', 'status', ')', ':', 'try', ':', 'if', 'sum', '(', 'len', '(', 'v', ')', 'for', 'v', 'in', 'status', '.', 'entities', '.', 'values', '(', ')', ')', '>', '0', ':', 'return', 'True', 'except', 'AttributeError', ':', 'if', 'sum', '(', 'len', '(', 'v', ')', 'for', 'v', 'in', 'status', '[', "'ent...
Returns true if a Status object has entities. Args: status: either a tweepy.Status object or a dict returned from Twitter API
['Returns', 'true', 'if', 'a', 'Status', 'object', 'has', 'entities', '.']
train
https://github.com/fitnr/twitter_bot_utils/blob/21f35afa5048cd3efa54db8cb87d405f69a78a62/twitter_bot_utils/helpers.py#L54-L69
4,428
micha030201/aionationstates
aionationstates/region_.py
Region.officers
async def officers(self, root): """Regional Officers. Does not include the Founder or the Delegate, unless they have additional titles as Officers. In the correct order. Returns ------- an :class:`ApiQuery` of a list of :class:`Officer` """ officers = s...
python
async def officers(self, root): """Regional Officers. Does not include the Founder or the Delegate, unless they have additional titles as Officers. In the correct order. Returns ------- an :class:`ApiQuery` of a list of :class:`Officer` """ officers = s...
['async', 'def', 'officers', '(', 'self', ',', 'root', ')', ':', 'officers', '=', 'sorted', '(', 'root', '.', 'find', '(', "'OFFICERS'", ')', ',', '# I struggle to say what else this tag would be useful for.', 'key', '=', 'lambda', 'elem', ':', 'int', '(', 'elem', '.', 'find', '(', "'ORDER'", ')', '.', 'text', ')', ')'...
Regional Officers. Does not include the Founder or the Delegate, unless they have additional titles as Officers. In the correct order. Returns ------- an :class:`ApiQuery` of a list of :class:`Officer`
['Regional', 'Officers', '.', 'Does', 'not', 'include', 'the', 'Founder', 'or', 'the', 'Delegate', 'unless', 'they', 'have', 'additional', 'titles', 'as', 'Officers', '.']
train
https://github.com/micha030201/aionationstates/blob/dc86b86d994cbab830b69ab8023601c73e778b3a/aionationstates/region_.py#L451-L466
4,429
ejeschke/ginga
ginga/util/wcs.py
get_starsep_RaDecDeg
def get_starsep_RaDecDeg(ra1_deg, dec1_deg, ra2_deg, dec2_deg): """Calculate separation.""" sep = deltaStarsRaDecDeg(ra1_deg, dec1_deg, ra2_deg, dec2_deg) sgn, deg, mn, sec = degToDms(sep) if deg != 0: txt = '%02d:%02d:%06.3f' % (deg, mn, sec) else: txt = '%02d:%06.3f' % (mn, sec) ...
python
def get_starsep_RaDecDeg(ra1_deg, dec1_deg, ra2_deg, dec2_deg): """Calculate separation.""" sep = deltaStarsRaDecDeg(ra1_deg, dec1_deg, ra2_deg, dec2_deg) sgn, deg, mn, sec = degToDms(sep) if deg != 0: txt = '%02d:%02d:%06.3f' % (deg, mn, sec) else: txt = '%02d:%06.3f' % (mn, sec) ...
['def', 'get_starsep_RaDecDeg', '(', 'ra1_deg', ',', 'dec1_deg', ',', 'ra2_deg', ',', 'dec2_deg', ')', ':', 'sep', '=', 'deltaStarsRaDecDeg', '(', 'ra1_deg', ',', 'dec1_deg', ',', 'ra2_deg', ',', 'dec2_deg', ')', 'sgn', ',', 'deg', ',', 'mn', ',', 'sec', '=', 'degToDms', '(', 'sep', ')', 'if', 'deg', '!=', '0', ':', 't...
Calculate separation.
['Calculate', 'separation', '.']
train
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/util/wcs.py#L577-L585
4,430
Alignak-monitoring/alignak
alignak/brok.py
Brok.prepare
def prepare(self): """Un-serialize data from data attribute and add instance_id key if necessary :return: None """ # Maybe the Brok is a old daemon one or was already prepared # if so, the data is already ok if hasattr(self, 'prepared') and not self.prepared: ...
python
def prepare(self): """Un-serialize data from data attribute and add instance_id key if necessary :return: None """ # Maybe the Brok is a old daemon one or was already prepared # if so, the data is already ok if hasattr(self, 'prepared') and not self.prepared: ...
['def', 'prepare', '(', 'self', ')', ':', '# Maybe the Brok is a old daemon one or was already prepared', '# if so, the data is already ok', 'if', 'hasattr', '(', 'self', ',', "'prepared'", ')', 'and', 'not', 'self', '.', 'prepared', ':', 'self', '.', 'data', '=', 'unserialize', '(', 'self', '.', 'data', ')', 'if', 'se...
Un-serialize data from data attribute and add instance_id key if necessary :return: None
['Un', '-', 'serialize', 'data', 'from', 'data', 'attribute', 'and', 'add', 'instance_id', 'key', 'if', 'necessary']
train
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/brok.py#L144-L155
4,431
bitesofcode/projexui
projexui/dialogs/xwizardbrowserdialog/xwizardbrowserdialog.py
XWizardBrowserDialog.runWizard
def runWizard( self ): """ Runs the current wizard. """ plugin = self.currentPlugin() if ( plugin and plugin.runWizard(self) ): self.accept()
python
def runWizard( self ): """ Runs the current wizard. """ plugin = self.currentPlugin() if ( plugin and plugin.runWizard(self) ): self.accept()
['def', 'runWizard', '(', 'self', ')', ':', 'plugin', '=', 'self', '.', 'currentPlugin', '(', ')', 'if', '(', 'plugin', 'and', 'plugin', '.', 'runWizard', '(', 'self', ')', ')', ':', 'self', '.', 'accept', '(', ')']
Runs the current wizard.
['Runs', 'the', 'current', 'wizard', '.']
train
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/dialogs/xwizardbrowserdialog/xwizardbrowserdialog.py#L133-L139
4,432
brocade/pynos
pynos/versions/ver_6/ver_6_0_1/yang/brocade_mac_access_list.py
brocade_mac_access_list.get_mac_acl_for_intf_input_interface_type
def get_mac_acl_for_intf_input_interface_type(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_mac_acl_for_intf = ET.Element("get_mac_acl_for_intf") config = get_mac_acl_for_intf input = ET.SubElement(get_mac_acl_for_intf, "input") int...
python
def get_mac_acl_for_intf_input_interface_type(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_mac_acl_for_intf = ET.Element("get_mac_acl_for_intf") config = get_mac_acl_for_intf input = ET.SubElement(get_mac_acl_for_intf, "input") int...
['def', 'get_mac_acl_for_intf_input_interface_type', '(', 'self', ',', '*', '*', 'kwargs', ')', ':', 'config', '=', 'ET', '.', 'Element', '(', '"config"', ')', 'get_mac_acl_for_intf', '=', 'ET', '.', 'Element', '(', '"get_mac_acl_for_intf"', ')', 'config', '=', 'get_mac_acl_for_intf', 'input', '=', 'ET', '.', 'SubEleme...
Auto Generated Code
['Auto', 'Generated', 'Code']
train
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_mac_access_list.py#L391-L402
4,433
planetlabs/planet-client-python
planet/scripts/v1.py
mosaic_info
def mosaic_info(name, pretty): '''Get information for a specific mosaic''' cl = clientv1() echo_json_response(call_and_wrap(cl.get_mosaic_by_name, name), pretty)
python
def mosaic_info(name, pretty): '''Get information for a specific mosaic''' cl = clientv1() echo_json_response(call_and_wrap(cl.get_mosaic_by_name, name), pretty)
['def', 'mosaic_info', '(', 'name', ',', 'pretty', ')', ':', 'cl', '=', 'clientv1', '(', ')', 'echo_json_response', '(', 'call_and_wrap', '(', 'cl', '.', 'get_mosaic_by_name', ',', 'name', ')', ',', 'pretty', ')']
Get information for a specific mosaic
['Get', 'information', 'for', 'a', 'specific', 'mosaic']
train
https://github.com/planetlabs/planet-client-python/blob/1c62ce7d416819951dddee0c22068fef6d40b027/planet/scripts/v1.py#L259-L262
4,434
google/grr
grr/server/grr_response_server/aff4_objects/user_managers.py
FullAccessControlManager._IsHomeDir
def _IsHomeDir(self, subject, token): """Checks user access permissions for paths under aff4:/users.""" h = CheckAccessHelper("IsHomeDir") h.Allow("aff4:/users/%s" % token.username) h.Allow("aff4:/users/%s/*" % token.username) try: return h.CheckAccess(subject, token) except access_control...
python
def _IsHomeDir(self, subject, token): """Checks user access permissions for paths under aff4:/users.""" h = CheckAccessHelper("IsHomeDir") h.Allow("aff4:/users/%s" % token.username) h.Allow("aff4:/users/%s/*" % token.username) try: return h.CheckAccess(subject, token) except access_control...
['def', '_IsHomeDir', '(', 'self', ',', 'subject', ',', 'token', ')', ':', 'h', '=', 'CheckAccessHelper', '(', '"IsHomeDir"', ')', 'h', '.', 'Allow', '(', '"aff4:/users/%s"', '%', 'token', '.', 'username', ')', 'h', '.', 'Allow', '(', '"aff4:/users/%s/*"', '%', 'token', '.', 'username', ')', 'try', ':', 'return', 'h', ...
Checks user access permissions for paths under aff4:/users.
['Checks', 'user', 'access', 'permissions', 'for', 'paths', 'under', 'aff4', ':', '/', 'users', '.']
train
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/aff4_objects/user_managers.py#L329-L339
4,435
hatemile/hatemile-for-python
hatemile/implementation/css.py
AccessibleCSSImplementation._is_valid_inherit_element
def _is_valid_inherit_element(self, element): """ Check that the children of element can be manipulated to apply the CSS properties. :param element: The element. :type element: hatemile.util.html.htmldomelement.HTMLDOMElement :return: True if the children of element can ...
python
def _is_valid_inherit_element(self, element): """ Check that the children of element can be manipulated to apply the CSS properties. :param element: The element. :type element: hatemile.util.html.htmldomelement.HTMLDOMElement :return: True if the children of element can ...
['def', '_is_valid_inherit_element', '(', 'self', ',', 'element', ')', ':', '# pylint: disable=no-self-use', 'tag_name', '=', 'element', '.', 'get_tag_name', '(', ')', 'return', '(', '(', 'tag_name', 'in', 'AccessibleCSSImplementation', '.', 'VALID_INHERIT_TAGS', ')', 'and', '(', 'not', 'element', '.', 'has_attribute',...
Check that the children of element can be manipulated to apply the CSS properties. :param element: The element. :type element: hatemile.util.html.htmldomelement.HTMLDOMElement :return: True if the children of element can be manipulated to apply the CSS properties or Fal...
['Check', 'that', 'the', 'children', 'of', 'element', 'can', 'be', 'manipulated', 'to', 'apply', 'the', 'CSS', 'properties', '.']
train
https://github.com/hatemile/hatemile-for-python/blob/1e914f9aa09f6f8d78282af131311546ecba9fb8/hatemile/implementation/css.py#L445-L463
4,436
brainiak/brainiak
brainiak/fcma/classifier.py
Classifier._normalize_correlation_data
def _normalize_correlation_data(self, corr_data, norm_unit): """Normalize the correlation data if necessary. Fisher-transform and then z-score the data for every norm_unit samples if norm_unit > 1. Parameters ---------- corr_data: the correlation data ...
python
def _normalize_correlation_data(self, corr_data, norm_unit): """Normalize the correlation data if necessary. Fisher-transform and then z-score the data for every norm_unit samples if norm_unit > 1. Parameters ---------- corr_data: the correlation data ...
['def', '_normalize_correlation_data', '(', 'self', ',', 'corr_data', ',', 'norm_unit', ')', ':', '# normalize if necessary', 'if', 'norm_unit', '>', '1', ':', 'num_samples', '=', 'len', '(', 'corr_data', ')', '[', '_', ',', 'd2', ',', 'd3', ']', '=', 'corr_data', '.', 'shape', 'second_dimension', '=', 'd2', '*', 'd3',...
Normalize the correlation data if necessary. Fisher-transform and then z-score the data for every norm_unit samples if norm_unit > 1. Parameters ---------- corr_data: the correlation data in shape [num_samples, num_processed_voxels, num_voxels] norm_...
['Normalize', 'the', 'correlation', 'data', 'if', 'necessary', '.']
train
https://github.com/brainiak/brainiak/blob/408f12dec2ff56559a26873a848a09e4c8facfeb/brainiak/fcma/classifier.py#L184-L220
4,437
peshay/tpm
tpm.py
TpmApi.change_user_password
def change_user_password(self, ID, data): """Change password of a User.""" # http://teampasswordmanager.com/docs/api-users/#change_password log.info('Change user %s password' % ID) self.put('users/%s/change_password.json' % ID, data)
python
def change_user_password(self, ID, data): """Change password of a User.""" # http://teampasswordmanager.com/docs/api-users/#change_password log.info('Change user %s password' % ID) self.put('users/%s/change_password.json' % ID, data)
['def', 'change_user_password', '(', 'self', ',', 'ID', ',', 'data', ')', ':', '# http://teampasswordmanager.com/docs/api-users/#change_password', 'log', '.', 'info', '(', "'Change user %s password'", '%', 'ID', ')', 'self', '.', 'put', '(', "'users/%s/change_password.json'", '%', 'ID', ',', 'data', ')']
Change password of a User.
['Change', 'password', 'of', 'a', 'User', '.']
train
https://github.com/peshay/tpm/blob/8e64a4d8b89d54bdd2c92d965463a7508aa3d0bc/tpm.py#L510-L514
4,438
Robin8Put/pmes
storage/rpc_methods.py
StorageTable.set_review
async def set_review(self, **params): """Writes review for content Accepts: - cid - review - public_key - rating - txid - coinid """ if params.get("message"): params = json.loads(params.get("message", "{}")) if not params: return {"error":400, "reason":"Missed required fields"} cid = i...
python
async def set_review(self, **params): """Writes review for content Accepts: - cid - review - public_key - rating - txid - coinid """ if params.get("message"): params = json.loads(params.get("message", "{}")) if not params: return {"error":400, "reason":"Missed required fields"} cid = i...
['async', 'def', 'set_review', '(', 'self', ',', '*', '*', 'params', ')', ':', 'if', 'params', '.', 'get', '(', '"message"', ')', ':', 'params', '=', 'json', '.', 'loads', '(', 'params', '.', 'get', '(', '"message"', ',', '"{}"', ')', ')', 'if', 'not', 'params', ':', 'return', '{', '"error"', ':', '400', ',', '"reason"...
Writes review for content Accepts: - cid - review - public_key - rating - txid - coinid
['Writes', 'review', 'for', 'content', 'Accepts', ':', '-', 'cid', '-', 'review', '-', 'public_key', '-', 'rating', '-', 'txid', '-', 'coinid']
train
https://github.com/Robin8Put/pmes/blob/338bec94162098f05b75bad035417317e1252fd2/storage/rpc_methods.py#L750-L786
4,439
BreakingBytes/simkit
simkit/core/simulations.py
topological_sort
def topological_sort(dag): """ topological sort :param dag: directed acyclic graph :type dag: dict .. seealso:: `Topographical Sorting <http://en.wikipedia.org/wiki/Topological_sorting>`_, `Directed Acyclic Graph (DAG) <https://en.wikipedia.org/wiki/Directed_acyclic_graph>`...
python
def topological_sort(dag): """ topological sort :param dag: directed acyclic graph :type dag: dict .. seealso:: `Topographical Sorting <http://en.wikipedia.org/wiki/Topological_sorting>`_, `Directed Acyclic Graph (DAG) <https://en.wikipedia.org/wiki/Directed_acyclic_graph>`...
['def', 'topological_sort', '(', 'dag', ')', ':', '# find all edges of dag', 'topsort', '=', '[', 'node', 'for', 'node', ',', 'edge', 'in', 'dag', '.', 'iteritems', '(', ')', 'if', 'not', 'edge', ']', '# loop through nodes until topologically sorted', 'while', 'len', '(', 'topsort', ')', '<', 'len', '(', 'dag', ')', ':...
topological sort :param dag: directed acyclic graph :type dag: dict .. seealso:: `Topographical Sorting <http://en.wikipedia.org/wiki/Topological_sorting>`_, `Directed Acyclic Graph (DAG) <https://en.wikipedia.org/wiki/Directed_acyclic_graph>`_
['topological', 'sort']
train
https://github.com/BreakingBytes/simkit/blob/205163d879d3880b6c9ef609f1b723a58773026b/simkit/core/simulations.py#L69-L95
4,440
mitsei/dlkit
dlkit/json_/grading/sessions.py
GradeSystemGradebookSession.get_gradebook_ids_by_grade_system
def get_gradebook_ids_by_grade_system(self, grade_system_id): """Gets the list of ``Gradebook`` ``Ids`` mapped to a ``GradeSystem``. arg: grade_system_id (osid.id.Id): ``Id`` of a ``GradeSystem`` return: (osid.id.IdList) - list of gradebook ``Ids`` raise: NotFound -...
python
def get_gradebook_ids_by_grade_system(self, grade_system_id): """Gets the list of ``Gradebook`` ``Ids`` mapped to a ``GradeSystem``. arg: grade_system_id (osid.id.Id): ``Id`` of a ``GradeSystem`` return: (osid.id.IdList) - list of gradebook ``Ids`` raise: NotFound -...
['def', 'get_gradebook_ids_by_grade_system', '(', 'self', ',', 'grade_system_id', ')', ':', '# Implemented from template for', '# osid.resource.ResourceBinSession.get_bin_ids_by_resource', 'mgr', '=', 'self', '.', '_get_provider_manager', '(', "'GRADING'", ',', 'local', '=', 'True', ')', 'lookup_session', '=', 'mgr', '...
Gets the list of ``Gradebook`` ``Ids`` mapped to a ``GradeSystem``. arg: grade_system_id (osid.id.Id): ``Id`` of a ``GradeSystem`` return: (osid.id.IdList) - list of gradebook ``Ids`` raise: NotFound - ``grade_system_id`` is not found raise: NullArgument - ``grade_...
['Gets', 'the', 'list', 'of', 'Gradebook', 'Ids', 'mapped', 'to', 'a', 'GradeSystem', '.']
train
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/grading/sessions.py#L1477-L1499
4,441
SystemRDL/systemrdl-compiler
systemrdl/node.py
get_group_node_size
def get_group_node_size(node): """ Shared getter for AddrmapNode and RegfileNode's "size" property """ # After structural placement, children are sorted if( not node.inst.children or (not isinstance(node.inst.children[-1], comp.AddressableComponent)) ): # No addressable child exi...
python
def get_group_node_size(node): """ Shared getter for AddrmapNode and RegfileNode's "size" property """ # After structural placement, children are sorted if( not node.inst.children or (not isinstance(node.inst.children[-1], comp.AddressableComponent)) ): # No addressable child exi...
['def', 'get_group_node_size', '(', 'node', ')', ':', '# After structural placement, children are sorted', 'if', '(', 'not', 'node', '.', 'inst', '.', 'children', 'or', '(', 'not', 'isinstance', '(', 'node', '.', 'inst', '.', 'children', '[', '-', '1', ']', ',', 'comp', '.', 'AddressableComponent', ')', ')', ')', ':', ...
Shared getter for AddrmapNode and RegfileNode's "size" property
['Shared', 'getter', 'for', 'AddrmapNode', 'and', 'RegfileNode', 's', 'size', 'property']
train
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/node.py#L810-L826
4,442
bwesterb/py-seccure
src/__init__.py
mod_root
def mod_root(a, p): """ Return a root of `a' modulo p """ if a == 0: return 0 if not mod_issquare(a, p): raise ValueError n = 2 while mod_issquare(n, p): n += 1 q = p - 1 r = 0 while not q.getbit(r): r += 1 q = q >> r y = pow(n, q, p) h = q >> ...
python
def mod_root(a, p): """ Return a root of `a' modulo p """ if a == 0: return 0 if not mod_issquare(a, p): raise ValueError n = 2 while mod_issquare(n, p): n += 1 q = p - 1 r = 0 while not q.getbit(r): r += 1 q = q >> r y = pow(n, q, p) h = q >> ...
['def', 'mod_root', '(', 'a', ',', 'p', ')', ':', 'if', 'a', '==', '0', ':', 'return', '0', 'if', 'not', 'mod_issquare', '(', 'a', ',', 'p', ')', ':', 'raise', 'ValueError', 'n', '=', '2', 'while', 'mod_issquare', '(', 'n', ',', 'p', ')', ':', 'n', '+=', '1', 'q', '=', 'p', '-', '1', 'r', '=', '0', 'while', 'not', 'q',...
Return a root of `a' modulo p
['Return', 'a', 'root', 'of', 'a', 'modulo', 'p']
train
https://github.com/bwesterb/py-seccure/blob/944760744686dd0ad015bd90ecb13a3ce0d7c9c9/src/__init__.py#L122-L154
4,443
grahambell/pymoc
lib/pymoc/moc.py
MOC.cells
def cells(self): """The number of cells in the MOC. This gives the total number of cells at all orders, with cells from every order counted equally. >>> m = MOC(0, (1, 2)) >>> m.cells 2 """ n = 0 for (order, cells) in self: n += len...
python
def cells(self): """The number of cells in the MOC. This gives the total number of cells at all orders, with cells from every order counted equally. >>> m = MOC(0, (1, 2)) >>> m.cells 2 """ n = 0 for (order, cells) in self: n += len...
['def', 'cells', '(', 'self', ')', ':', 'n', '=', '0', 'for', '(', 'order', ',', 'cells', ')', 'in', 'self', ':', 'n', '+=', 'len', '(', 'cells', ')', 'return', 'n']
The number of cells in the MOC. This gives the total number of cells at all orders, with cells from every order counted equally. >>> m = MOC(0, (1, 2)) >>> m.cells 2
['The', 'number', 'of', 'cells', 'in', 'the', 'MOC', '.']
train
https://github.com/grahambell/pymoc/blob/0e2e57ce07ff3de6ac024627c1fb6ad30c2fde48/lib/pymoc/moc.py#L365-L381
4,444
numberoverzero/bloop
bloop/stream/buffer.py
RecordBuffer.push_all
def push_all(self, record_shard_pairs): """Push multiple (record, shard) pairs at once, with only one :meth:`heapq.heapify` call to maintain order. :param record_shard_pairs: list of ``(record, shard)`` tuples (see :func:`~bloop.stream.buffer.RecordBuffer.push`). """ # Faste...
python
def push_all(self, record_shard_pairs): """Push multiple (record, shard) pairs at once, with only one :meth:`heapq.heapify` call to maintain order. :param record_shard_pairs: list of ``(record, shard)`` tuples (see :func:`~bloop.stream.buffer.RecordBuffer.push`). """ # Faste...
['def', 'push_all', '(', 'self', ',', 'record_shard_pairs', ')', ':', '# Faster than inserting one at a time; the heap is sorted once after all inserts.', 'for', 'record', ',', 'shard', 'in', 'record_shard_pairs', ':', 'item', '=', 'heap_item', '(', 'self', '.', 'clock', ',', 'record', ',', 'shard', ')', 'self', '.', '...
Push multiple (record, shard) pairs at once, with only one :meth:`heapq.heapify` call to maintain order. :param record_shard_pairs: list of ``(record, shard)`` tuples (see :func:`~bloop.stream.buffer.RecordBuffer.push`).
['Push', 'multiple', '(', 'record', 'shard', ')', 'pairs', 'at', 'once', 'with', 'only', 'one', ':', 'meth', ':', 'heapq', '.', 'heapify', 'call', 'to', 'maintain', 'order', '.']
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/stream/buffer.py#L48-L58
4,445
fhcrc/nestly
nestly/scripts/nestrun.py
NestlyProcess.log_tail
def log_tail(self, nlines=10): """ Return the last ``nlines`` lines of the log file """ log_path = os.path.join(self.working_dir, self.log_name) with open(log_path) as fp: d = collections.deque(maxlen=nlines) d.extend(fp) return ''.join(d)
python
def log_tail(self, nlines=10): """ Return the last ``nlines`` lines of the log file """ log_path = os.path.join(self.working_dir, self.log_name) with open(log_path) as fp: d = collections.deque(maxlen=nlines) d.extend(fp) return ''.join(d)
['def', 'log_tail', '(', 'self', ',', 'nlines', '=', '10', ')', ':', 'log_path', '=', 'os', '.', 'path', '.', 'join', '(', 'self', '.', 'working_dir', ',', 'self', '.', 'log_name', ')', 'with', 'open', '(', 'log_path', ')', 'as', 'fp', ':', 'd', '=', 'collections', '.', 'deque', '(', 'maxlen', '=', 'nlines', ')', 'd', ...
Return the last ``nlines`` lines of the log file
['Return', 'the', 'last', 'nlines', 'lines', 'of', 'the', 'log', 'file']
train
https://github.com/fhcrc/nestly/blob/4d7818b5950f405d2067a6b8577d5afb7527c9ff/nestly/scripts/nestrun.py#L201-L209
4,446
arubertoson/maya-launcher
mayalauncher.py
Config._create_default_config_file
def _create_default_config_file(self): """ If config file does not exists create and set default values. """ logger.info('Initialize Maya launcher, creating config file...\n') self.add_section(self.DEFAULTS) self.add_section(self.PATTERNS) self.add_section(...
python
def _create_default_config_file(self): """ If config file does not exists create and set default values. """ logger.info('Initialize Maya launcher, creating config file...\n') self.add_section(self.DEFAULTS) self.add_section(self.PATTERNS) self.add_section(...
['def', '_create_default_config_file', '(', 'self', ')', ':', 'logger', '.', 'info', '(', "'Initialize Maya launcher, creating config file...\\n'", ')', 'self', '.', 'add_section', '(', 'self', '.', 'DEFAULTS', ')', 'self', '.', 'add_section', '(', 'self', '.', 'PATTERNS', ')', 'self', '.', 'add_section', '(', 'self', ...
If config file does not exists create and set default values.
['If', 'config', 'file', 'does', 'not', 'exists', 'create', 'and', 'set', 'default', 'values', '.']
train
https://github.com/arubertoson/maya-launcher/blob/9bd82cce7edf4afb803dd8044107a324e93f197f/mayalauncher.py#L113-L135
4,447
Yubico/python-pyhsm
pyhsm/tools/decrypt_aead.py
parse_args
def parse_args(): """ Parse the command line arguments """ parser = argparse.ArgumentParser(description = 'Decrypt AEADs', add_help = True, formatter_class = argparse.ArgumentDefaultsHelpFormatter, ...
python
def parse_args(): """ Parse the command line arguments """ parser = argparse.ArgumentParser(description = 'Decrypt AEADs', add_help = True, formatter_class = argparse.ArgumentDefaultsHelpFormatter, ...
['def', 'parse_args', '(', ')', ':', 'parser', '=', 'argparse', '.', 'ArgumentParser', '(', 'description', '=', "'Decrypt AEADs'", ',', 'add_help', '=', 'True', ',', 'formatter_class', '=', 'argparse', '.', 'ArgumentDefaultsHelpFormatter', ',', ')', 'parser', '.', 'add_argument', '(', "'-v'", ',', "'--verbose'", ',', '...
Parse the command line arguments
['Parse', 'the', 'command', 'line', 'arguments']
train
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/tools/decrypt_aead.py#L24-L139
4,448
onelogin/python-saml
src/onelogin/saml2/settings.py
OneLogin_Saml2_Settings.__load_settings_from_file
def __load_settings_from_file(self): """ Loads settings info from the settings json file :returns: True if the settings info is valid :rtype: boolean """ filename = self.get_base_path() + 'settings.json' if not exists(filename): raise OneLogin_Saml2_...
python
def __load_settings_from_file(self): """ Loads settings info from the settings json file :returns: True if the settings info is valid :rtype: boolean """ filename = self.get_base_path() + 'settings.json' if not exists(filename): raise OneLogin_Saml2_...
['def', '__load_settings_from_file', '(', 'self', ')', ':', 'filename', '=', 'self', '.', 'get_base_path', '(', ')', '+', "'settings.json'", 'if', 'not', 'exists', '(', 'filename', ')', ':', 'raise', 'OneLogin_Saml2_Error', '(', "'Settings file not found: %s'", ',', 'OneLogin_Saml2_Error', '.', 'SETTINGS_FILE_NOT_FOUND...
Loads settings info from the settings json file :returns: True if the settings info is valid :rtype: boolean
['Loads', 'settings', 'info', 'from', 'the', 'settings', 'json', 'file']
train
https://github.com/onelogin/python-saml/blob/9fe7a72da5b4caa1529c1640b52d2649447ce49b/src/onelogin/saml2/settings.py#L220-L248
4,449
pypa/pipenv
pipenv/vendor/distlib/_backport/tarfile.py
TarInfo._proc_gnusparse_00
def _proc_gnusparse_00(self, next, pax_headers, buf): """Process a GNU tar extended sparse header, version 0.0. """ offsets = [] for match in re.finditer(br"\d+ GNU.sparse.offset=(\d+)\n", buf): offsets.append(int(match.group(1))) numbytes = [] for match in re...
python
def _proc_gnusparse_00(self, next, pax_headers, buf): """Process a GNU tar extended sparse header, version 0.0. """ offsets = [] for match in re.finditer(br"\d+ GNU.sparse.offset=(\d+)\n", buf): offsets.append(int(match.group(1))) numbytes = [] for match in re...
['def', '_proc_gnusparse_00', '(', 'self', ',', 'next', ',', 'pax_headers', ',', 'buf', ')', ':', 'offsets', '=', '[', ']', 'for', 'match', 'in', 're', '.', 'finditer', '(', 'br"\\d+ GNU.sparse.offset=(\\d+)\\n"', ',', 'buf', ')', ':', 'offsets', '.', 'append', '(', 'int', '(', 'match', '.', 'group', '(', '1', ')', ')'...
Process a GNU tar extended sparse header, version 0.0.
['Process', 'a', 'GNU', 'tar', 'extended', 'sparse', 'header', 'version', '0', '.', '0', '.']
train
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L1485-L1494
4,450
bitesofcode/projexui
projexui/widgets/xviewwidget/xviewprofiletoolbar.py
XViewProfileToolBar.createProfile
def createProfile(self, profile=None, clearLayout=True): """ Prompts the user to create a new profile. """ if profile: prof = profile elif not self.viewWidget() or clearLayout: prof = XViewProfile() else: prof = self.viewWidget...
python
def createProfile(self, profile=None, clearLayout=True): """ Prompts the user to create a new profile. """ if profile: prof = profile elif not self.viewWidget() or clearLayout: prof = XViewProfile() else: prof = self.viewWidget...
['def', 'createProfile', '(', 'self', ',', 'profile', '=', 'None', ',', 'clearLayout', '=', 'True', ')', ':', 'if', 'profile', ':', 'prof', '=', 'profile', 'elif', 'not', 'self', '.', 'viewWidget', '(', ')', 'or', 'clearLayout', ':', 'prof', '=', 'XViewProfile', '(', ')', 'else', ':', 'prof', '=', 'self', '.', 'viewWid...
Prompts the user to create a new profile.
['Prompts', 'the', 'user', 'to', 'create', 'a', 'new', 'profile', '.']
train
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xviewwidget/xviewprofiletoolbar.py#L164-L192
4,451
tanghaibao/jcvi
jcvi/apps/vecscreen.py
mask
def mask(args): """ %prog mask fastafile Mask the contaminants. By default, this will compare against UniVec_Core and Ecoli.fasta. Merge the contaminant results, and use `maskFastaFromBed`. Can perform FASTA tidy if requested. """ p = OptionParser(mask.__doc__) p.add_option("--db", ...
python
def mask(args): """ %prog mask fastafile Mask the contaminants. By default, this will compare against UniVec_Core and Ecoli.fasta. Merge the contaminant results, and use `maskFastaFromBed`. Can perform FASTA tidy if requested. """ p = OptionParser(mask.__doc__) p.add_option("--db", ...
['def', 'mask', '(', 'args', ')', ':', 'p', '=', 'OptionParser', '(', 'mask', '.', '__doc__', ')', 'p', '.', 'add_option', '(', '"--db"', ',', 'help', '=', '"Contaminant db other than Ecoli K12 [default: %default]"', ')', 'opts', ',', 'args', '=', 'p', '.', 'parse_args', '(', 'args', ')', 'if', 'len', '(', 'args', ')',...
%prog mask fastafile Mask the contaminants. By default, this will compare against UniVec_Core and Ecoli.fasta. Merge the contaminant results, and use `maskFastaFromBed`. Can perform FASTA tidy if requested.
['%prog', 'mask', 'fastafile']
train
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/vecscreen.py#L29-L62
4,452
CZ-NIC/yangson
yangson/schemanode.py
ListNode.orphan_entry
def orphan_entry(self, rval: RawObject) -> "ArrayEntry": """Return an isolated entry of the receiver. Args: rval: Raw object to be used for the returned entry. """ val = self.entry_from_raw(rval) return ArrayEntry(0, EmptyList(), EmptyList(), val, None, self, ...
python
def orphan_entry(self, rval: RawObject) -> "ArrayEntry": """Return an isolated entry of the receiver. Args: rval: Raw object to be used for the returned entry. """ val = self.entry_from_raw(rval) return ArrayEntry(0, EmptyList(), EmptyList(), val, None, self, ...
['def', 'orphan_entry', '(', 'self', ',', 'rval', ':', 'RawObject', ')', '->', '"ArrayEntry"', ':', 'val', '=', 'self', '.', 'entry_from_raw', '(', 'rval', ')', 'return', 'ArrayEntry', '(', '0', ',', 'EmptyList', '(', ')', ',', 'EmptyList', '(', ')', ',', 'val', ',', 'None', ',', 'self', ',', 'val', '.', 'timestamp', '...
Return an isolated entry of the receiver. Args: rval: Raw object to be used for the returned entry.
['Return', 'an', 'isolated', 'entry', 'of', 'the', 'receiver', '.']
train
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/schemanode.py#L1096-L1104
4,453
mapillary/mapillary_tools
mapillary_tools/uploader.py
progress
def progress(count, total, suffix=''): ''' Display progress bar sources: https://gist.github.com/vladignatyev/06860ec2040cb497f0f3 ''' bar_len = 60 filled_len = int(round(bar_len * count / float(total))) percents = round(100.0 * count / float(total), 1) bar = '=' * filled_len + '-' * (ba...
python
def progress(count, total, suffix=''): ''' Display progress bar sources: https://gist.github.com/vladignatyev/06860ec2040cb497f0f3 ''' bar_len = 60 filled_len = int(round(bar_len * count / float(total))) percents = round(100.0 * count / float(total), 1) bar = '=' * filled_len + '-' * (ba...
['def', 'progress', '(', 'count', ',', 'total', ',', 'suffix', '=', "''", ')', ':', 'bar_len', '=', '60', 'filled_len', '=', 'int', '(', 'round', '(', 'bar_len', '*', 'count', '/', 'float', '(', 'total', ')', ')', ')', 'percents', '=', 'round', '(', '100.0', '*', 'count', '/', 'float', '(', 'total', ')', ',', '1', ')',...
Display progress bar sources: https://gist.github.com/vladignatyev/06860ec2040cb497f0f3
['Display', 'progress', 'bar', 'sources', ':', 'https', ':', '//', 'gist', '.', 'github', '.', 'com', '/', 'vladignatyev', '/', '06860ec2040cb497f0f3']
train
https://github.com/mapillary/mapillary_tools/blob/816785e90c589cae6e8e34a5530ce8417d29591c/mapillary_tools/uploader.py#L409-L419
4,454
mitsei/dlkit
dlkit/services/repository.py
Repository.use_plenary_composition_view
def use_plenary_composition_view(self): """Pass through to provider CompositionLookupSession.use_plenary_composition_view""" self._object_views['composition'] = PLENARY # self._get_provider_session('composition_lookup_session') # To make sure the session is tracked for session in self._g...
python
def use_plenary_composition_view(self): """Pass through to provider CompositionLookupSession.use_plenary_composition_view""" self._object_views['composition'] = PLENARY # self._get_provider_session('composition_lookup_session') # To make sure the session is tracked for session in self._g...
['def', 'use_plenary_composition_view', '(', 'self', ')', ':', 'self', '.', '_object_views', '[', "'composition'", ']', '=', 'PLENARY', "# self._get_provider_session('composition_lookup_session') # To make sure the session is tracked", 'for', 'session', 'in', 'self', '.', '_get_provider_sessions', '(', ')', ':', 'try',...
Pass through to provider CompositionLookupSession.use_plenary_composition_view
['Pass', 'through', 'to', 'provider', 'CompositionLookupSession', '.', 'use_plenary_composition_view']
train
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/services/repository.py#L1872-L1880
4,455
openeemeter/eemeter
eemeter/caltrack/usage_per_day.py
get_cdd_only_candidate_models
def get_cdd_only_candidate_models( data, minimum_non_zero_cdd, minimum_total_cdd, beta_cdd_maximum_p_value, weights_col ): """ Return a list of all possible candidate cdd-only models. Parameters ---------- data : :any:`pandas.DataFrame` A DataFrame containing at least the column ``meter_val...
python
def get_cdd_only_candidate_models( data, minimum_non_zero_cdd, minimum_total_cdd, beta_cdd_maximum_p_value, weights_col ): """ Return a list of all possible candidate cdd-only models. Parameters ---------- data : :any:`pandas.DataFrame` A DataFrame containing at least the column ``meter_val...
['def', 'get_cdd_only_candidate_models', '(', 'data', ',', 'minimum_non_zero_cdd', ',', 'minimum_total_cdd', ',', 'beta_cdd_maximum_p_value', ',', 'weights_col', ')', ':', 'balance_points', '=', '[', 'int', '(', 'col', '[', '4', ':', ']', ')', 'for', 'col', 'in', 'data', '.', 'columns', 'if', 'col', '.', 'startswith', ...
Return a list of all possible candidate cdd-only models. Parameters ---------- data : :any:`pandas.DataFrame` A DataFrame containing at least the column ``meter_value`` and 1 to n columns with names of the form ``cdd_<balance_point>``. All columns with names of this form will be use...
['Return', 'a', 'list', 'of', 'all', 'possible', 'candidate', 'cdd', '-', 'only', 'models', '.']
train
https://github.com/openeemeter/eemeter/blob/e03b1cc5f4906e8f4f7fd16183bc037107d1dfa0/eemeter/caltrack/usage_per_day.py#L1139-L1179
4,456
eaton-lab/toytree
toytree/etemini.py
TreeNode.remove_child
def remove_child(self, child): """ Removes a child from this node (parent and child nodes still exit but are no longer connected). """ try: self.children.remove(child) except ValueError as e: raise TreeError("child not found") else: ...
python
def remove_child(self, child): """ Removes a child from this node (parent and child nodes still exit but are no longer connected). """ try: self.children.remove(child) except ValueError as e: raise TreeError("child not found") else: ...
['def', 'remove_child', '(', 'self', ',', 'child', ')', ':', 'try', ':', 'self', '.', 'children', '.', 'remove', '(', 'child', ')', 'except', 'ValueError', 'as', 'e', ':', 'raise', 'TreeError', '(', '"child not found"', ')', 'else', ':', 'child', '.', 'up', '=', 'None', 'return', 'child']
Removes a child from this node (parent and child nodes still exit but are no longer connected).
['Removes', 'a', 'child', 'from', 'this', 'node', '(', 'parent', 'and', 'child', 'nodes', 'still', 'exit', 'but', 'are', 'no', 'longer', 'connected', ')', '.']
train
https://github.com/eaton-lab/toytree/blob/0347ed2098acc5f707fadf52a0ecd411a6d1859c/toytree/etemini.py#L277-L288
4,457
mitsei/dlkit
dlkit/services/logging_.py
LoggingManager.use_plenary_log_view
def use_plenary_log_view(self): """Pass through to provider LogEntryLogSession.use_plenary_log_view""" self._log_view = PLENARY # self._get_provider_session('log_entry_log_session') # To make sure the session is tracked for session in self._get_provider_sessions(): try: ...
python
def use_plenary_log_view(self): """Pass through to provider LogEntryLogSession.use_plenary_log_view""" self._log_view = PLENARY # self._get_provider_session('log_entry_log_session') # To make sure the session is tracked for session in self._get_provider_sessions(): try: ...
['def', 'use_plenary_log_view', '(', 'self', ')', ':', 'self', '.', '_log_view', '=', 'PLENARY', "# self._get_provider_session('log_entry_log_session') # To make sure the session is tracked", 'for', 'session', 'in', 'self', '.', '_get_provider_sessions', '(', ')', ':', 'try', ':', 'session', '.', 'use_plenary_log_view'...
Pass through to provider LogEntryLogSession.use_plenary_log_view
['Pass', 'through', 'to', 'provider', 'LogEntryLogSession', '.', 'use_plenary_log_view']
train
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/services/logging_.py#L424-L432
4,458
ray-project/ray
python/ray/worker.py
Worker.submit_task
def submit_task(self, function_descriptor, args, actor_id=None, actor_handle_id=None, actor_counter=0, actor_creation_id=None, actor_creation_dummy_object_id=None, ...
python
def submit_task(self, function_descriptor, args, actor_id=None, actor_handle_id=None, actor_counter=0, actor_creation_id=None, actor_creation_dummy_object_id=None, ...
['def', 'submit_task', '(', 'self', ',', 'function_descriptor', ',', 'args', ',', 'actor_id', '=', 'None', ',', 'actor_handle_id', '=', 'None', ',', 'actor_counter', '=', '0', ',', 'actor_creation_id', '=', 'None', ',', 'actor_creation_dummy_object_id', '=', 'None', ',', 'max_actor_reconstructions', '=', '0', ',', 'exe...
Submit a remote task to the scheduler. Tell the scheduler to schedule the execution of the function with function_descriptor with arguments args. Retrieve object IDs for the outputs of the function from the scheduler and immediately return them. Args: function_descriptor: T...
['Submit', 'a', 'remote', 'task', 'to', 'the', 'scheduler', '.']
train
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/worker.py#L561-L699
4,459
Microsoft/azure-devops-python-api
azure-devops/azure/devops/v5_1/git/git_client_base.py
GitClientBase.restore_repository_from_recycle_bin
def restore_repository_from_recycle_bin(self, repository_details, project, repository_id): """RestoreRepositoryFromRecycleBin. [Preview API] Recover a soft-deleted Git repository. Recently deleted repositories go into a soft-delete state for a period of time before they are hard deleted and become unrec...
python
def restore_repository_from_recycle_bin(self, repository_details, project, repository_id): """RestoreRepositoryFromRecycleBin. [Preview API] Recover a soft-deleted Git repository. Recently deleted repositories go into a soft-delete state for a period of time before they are hard deleted and become unrec...
['def', 'restore_repository_from_recycle_bin', '(', 'self', ',', 'repository_details', ',', 'project', ',', 'repository_id', ')', ':', 'route_values', '=', '{', '}', 'if', 'project', 'is', 'not', 'None', ':', 'route_values', '[', "'project'", ']', '=', 'self', '.', '_serialize', '.', 'url', '(', "'project'", ',', 'proj...
RestoreRepositoryFromRecycleBin. [Preview API] Recover a soft-deleted Git repository. Recently deleted repositories go into a soft-delete state for a period of time before they are hard deleted and become unrecoverable. :param :class:`<GitRecycleBinRepositoryDetails> <azure.devops.v5_1.git.models.GitRec...
['RestoreRepositoryFromRecycleBin', '.', '[', 'Preview', 'API', ']', 'Recover', 'a', 'soft', '-', 'deleted', 'Git', 'repository', '.', 'Recently', 'deleted', 'repositories', 'go', 'into', 'a', 'soft', '-', 'delete', 'state', 'for', 'a', 'period', 'of', 'time', 'before', 'they', 'are', 'hard', 'deleted', 'and', 'become'...
train
https://github.com/Microsoft/azure-devops-python-api/blob/4777ffda2f5052fabbaddb2abe9cb434e0cf1aa8/azure-devops/azure/devops/v5_1/git/git_client_base.py#L2701-L2720
4,460
pymc-devs/pymc
pymc/NormalApproximation.py
MAP.grad_and_hess
def grad_and_hess(self): """ Computes self's gradient and Hessian. Used if the optimization method for a NormApprox doesn't use gradients and hessians, for instance fmin. """ for i in xrange(self.len): di = self.diff(i) self.grad[i] = di ...
python
def grad_and_hess(self): """ Computes self's gradient and Hessian. Used if the optimization method for a NormApprox doesn't use gradients and hessians, for instance fmin. """ for i in xrange(self.len): di = self.diff(i) self.grad[i] = di ...
['def', 'grad_and_hess', '(', 'self', ')', ':', 'for', 'i', 'in', 'xrange', '(', 'self', '.', 'len', ')', ':', 'di', '=', 'self', '.', 'diff', '(', 'i', ')', 'self', '.', 'grad', '[', 'i', ']', '=', 'di', 'self', '.', 'hess', '[', 'i', ',', 'i', ']', '=', 'self', '.', 'diff', '(', 'i', ',', '2', ')', 'if', 'i', '<', 's...
Computes self's gradient and Hessian. Used if the optimization method for a NormApprox doesn't use gradients and hessians, for instance fmin.
['Computes', 'self', 's', 'gradient', 'and', 'Hessian', '.', 'Used', 'if', 'the', 'optimization', 'method', 'for', 'a', 'NormApprox', 'doesn', 't', 'use', 'gradients', 'and', 'hessians', 'for', 'instance', 'fmin', '.']
train
https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/NormalApproximation.py#L487-L505
4,461
nerdvegas/rez
src/rezplugins/package_repository/memory.py
MemoryPackageRepository.create_repository
def create_repository(cls, repository_data): """Create a standalone, in-memory repository. Using this function bypasses the `package_repository_manager` singleton. This is usually desired however, since in-memory repositories are for temporarily storing programmatically created packages...
python
def create_repository(cls, repository_data): """Create a standalone, in-memory repository. Using this function bypasses the `package_repository_manager` singleton. This is usually desired however, since in-memory repositories are for temporarily storing programmatically created packages...
['def', 'create_repository', '(', 'cls', ',', 'repository_data', ')', ':', 'location', '=', '"memory{%s}"', '%', 'hex', '(', 'id', '(', 'repository_data', ')', ')', 'resource_pool', '=', 'ResourcePool', '(', 'cache_size', '=', 'None', ')', 'repo', '=', 'MemoryPackageRepository', '(', 'location', ',', 'resource_pool', '...
Create a standalone, in-memory repository. Using this function bypasses the `package_repository_manager` singleton. This is usually desired however, since in-memory repositories are for temporarily storing programmatically created packages, which we do not want to cache and that do not ...
['Create', 'a', 'standalone', 'in', '-', 'memory', 'repository', '.']
train
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rezplugins/package_repository/memory.py#L134-L152
4,462
a1ezzz/wasp-general
wasp_general/uri.py
WURIComponentVerifier.validate
def validate(self, uri): """ Check an URI for compatibility with this specification. Return True if the URI is compatible. :param uri: an URI to check :return: bool """ requirement = self.requirement() uri_component = uri.component(self.component()) if uri_component is None: return requirement != WU...
python
def validate(self, uri): """ Check an URI for compatibility with this specification. Return True if the URI is compatible. :param uri: an URI to check :return: bool """ requirement = self.requirement() uri_component = uri.component(self.component()) if uri_component is None: return requirement != WU...
['def', 'validate', '(', 'self', ',', 'uri', ')', ':', 'requirement', '=', 'self', '.', 'requirement', '(', ')', 'uri_component', '=', 'uri', '.', 'component', '(', 'self', '.', 'component', '(', ')', ')', 'if', 'uri_component', 'is', 'None', ':', 'return', 'requirement', '!=', 'WURIComponentVerifier', '.', 'Requiremen...
Check an URI for compatibility with this specification. Return True if the URI is compatible. :param uri: an URI to check :return: bool
['Check', 'an', 'URI', 'for', 'compatibility', 'with', 'this', 'specification', '.', 'Return', 'True', 'if', 'the', 'URI', 'is', 'compatible', '.']
train
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/uri.py#L537-L555
4,463
pypa/pipenv
pipenv/vendor/urllib3/connection.py
HTTPConnection.request_chunked
def request_chunked(self, method, url, body=None, headers=None): """ Alternative to the common request method, which sends the body with chunked encoding and not as one block """ headers = HTTPHeaderDict(headers if headers is not None else {}) skip_accept_encoding = 'acce...
python
def request_chunked(self, method, url, body=None, headers=None): """ Alternative to the common request method, which sends the body with chunked encoding and not as one block """ headers = HTTPHeaderDict(headers if headers is not None else {}) skip_accept_encoding = 'acce...
['def', 'request_chunked', '(', 'self', ',', 'method', ',', 'url', ',', 'body', '=', 'None', ',', 'headers', '=', 'None', ')', ':', 'headers', '=', 'HTTPHeaderDict', '(', 'headers', 'if', 'headers', 'is', 'not', 'None', 'else', '{', '}', ')', 'skip_accept_encoding', '=', "'accept-encoding'", 'in', 'headers', 'skip_host...
Alternative to the common request method, which sends the body with chunked encoding and not as one block
['Alternative', 'to', 'the', 'common', 'request', 'method', 'which', 'sends', 'the', 'body', 'with', 'chunked', 'encoding', 'and', 'not', 'as', 'one', 'block']
train
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/connection.py#L184-L220
4,464
smarie/python-parsyfiles
parsyfiles/parsing_registries.py
insert_element_to_dict_of_dicts
def insert_element_to_dict_of_dicts(dict_of_dicts: Dict[str, Dict[str, str]], first_key: str, second_key: str, contents): """ Utility method :param dict_of_dicts: :param first_key: :param second_key: :param contents: :return: """ if first_key not in dict_of_dicts.keys(): di...
python
def insert_element_to_dict_of_dicts(dict_of_dicts: Dict[str, Dict[str, str]], first_key: str, second_key: str, contents): """ Utility method :param dict_of_dicts: :param first_key: :param second_key: :param contents: :return: """ if first_key not in dict_of_dicts.keys(): di...
['def', 'insert_element_to_dict_of_dicts', '(', 'dict_of_dicts', ':', 'Dict', '[', 'str', ',', 'Dict', '[', 'str', ',', 'str', ']', ']', ',', 'first_key', ':', 'str', ',', 'second_key', ':', 'str', ',', 'contents', ')', ':', 'if', 'first_key', 'not', 'in', 'dict_of_dicts', '.', 'keys', '(', ')', ':', 'dict_of_dicts', '...
Utility method :param dict_of_dicts: :param first_key: :param second_key: :param contents: :return:
['Utility', 'method']
train
https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/parsing_registries.py#L213-L231
4,465
peepall/FancyLogger
FancyLogger/__init__.py
FancyLogger.set_task_object
def set_task_object(self, task_id, task_progress_object): """ Defines a new progress bar with the given information using a TaskProgress object. :param task_id: Unique identifier for this progress bar. Will erase if already existing...
python
def set_task_object(self, task_id, task_progress_object): """ Defines a new progress bar with the given information using a TaskProgress object. :param task_id: Unique identifier for this progress bar. Will erase if already existing...
['def', 'set_task_object', '(', 'self', ',', 'task_id', ',', 'task_progress_object', ')', ':', 'self', '.', 'set_task', '(', 'task_id', '=', 'task_id', ',', 'total', '=', 'task_progress_object', '.', 'total', ',', 'prefix', '=', 'task_progress_object', '.', 'prefix', ',', 'suffix', '=', 'task_progress_object', '.', 'su...
Defines a new progress bar with the given information using a TaskProgress object. :param task_id: Unique identifier for this progress bar. Will erase if already existing. :param task_progress_object: TaskProgress object holding the progress bar information.
['Defines', 'a', 'new', 'progress', 'bar', 'with', 'the', 'given', 'information', 'using', 'a', 'TaskProgress', 'object', '.', ':', 'param', 'task_id', ':', 'Unique', 'identifier', 'for', 'this', 'progress', 'bar', '.', 'Will', 'erase', 'if', 'already', 'existing', '.', ':', 'param', 'task_progress_object', ':', 'TaskP...
train
https://github.com/peepall/FancyLogger/blob/7f13f1397e76ed768fb6b6358194118831fafc6d/FancyLogger/__init__.py#L288-L303
4,466
choderalab/pymbar
pymbar/utils.py
logsumexp
def logsumexp(a, axis=None, b=None, use_numexpr=True): """Compute the log of the sum of exponentials of input elements. Parameters ---------- a : array_like Input array. axis : None or int, optional, default=None Axis or axes over which the sum is taken. By default `axis` is None, ...
python
def logsumexp(a, axis=None, b=None, use_numexpr=True): """Compute the log of the sum of exponentials of input elements. Parameters ---------- a : array_like Input array. axis : None or int, optional, default=None Axis or axes over which the sum is taken. By default `axis` is None, ...
['def', 'logsumexp', '(', 'a', ',', 'axis', '=', 'None', ',', 'b', '=', 'None', ',', 'use_numexpr', '=', 'True', ')', ':', 'a', '=', 'np', '.', 'asarray', '(', 'a', ')', 'a_max', '=', 'np', '.', 'amax', '(', 'a', ',', 'axis', '=', 'axis', ',', 'keepdims', '=', 'True', ')', 'if', 'a_max', '.', 'ndim', '>', '0', ':', 'a_...
Compute the log of the sum of exponentials of input elements. Parameters ---------- a : array_like Input array. axis : None or int, optional, default=None Axis or axes over which the sum is taken. By default `axis` is None, and all elements are summed. b : array-like, option...
['Compute', 'the', 'log', 'of', 'the', 'sum', 'of', 'exponentials', 'of', 'input', 'elements', '.']
train
https://github.com/choderalab/pymbar/blob/69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740/pymbar/utils.py#L271-L329
4,467
tanghaibao/jcvi
jcvi/apps/phylo.py
smart_reroot
def smart_reroot(treefile, outgroupfile, outfile, format=0): """ simple function to reroot Newick format tree using ete2 Tree reading format options see here: http://packages.python.org/ete2/tutorial/tutorial_trees.html#reading-newick-trees """ tree = Tree(treefile, format=format) leaves = ...
python
def smart_reroot(treefile, outgroupfile, outfile, format=0): """ simple function to reroot Newick format tree using ete2 Tree reading format options see here: http://packages.python.org/ete2/tutorial/tutorial_trees.html#reading-newick-trees """ tree = Tree(treefile, format=format) leaves = ...
['def', 'smart_reroot', '(', 'treefile', ',', 'outgroupfile', ',', 'outfile', ',', 'format', '=', '0', ')', ':', 'tree', '=', 'Tree', '(', 'treefile', ',', 'format', '=', 'format', ')', 'leaves', '=', '[', 't', '.', 'name', 'for', 't', 'in', 'tree', '.', 'get_leaves', '(', ')', ']', '[', ':', ':', '-', '1', ']', 'outgr...
simple function to reroot Newick format tree using ete2 Tree reading format options see here: http://packages.python.org/ete2/tutorial/tutorial_trees.html#reading-newick-trees
['simple', 'function', 'to', 'reroot', 'Newick', 'format', 'tree', 'using', 'ete2']
train
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/phylo.py#L193-L224
4,468
geographika/mappyfile
mappyfile/pprint.py
PrettyPrinter.is_hidden_container
def is_hidden_container(self, key, val): """ The key is not one of the Mapfile keywords, and its values are a list """ if key in ("layers", "classes", "styles", "symbols", "labels", "outputformats", "features", "scaletokens", "composites") a...
python
def is_hidden_container(self, key, val): """ The key is not one of the Mapfile keywords, and its values are a list """ if key in ("layers", "classes", "styles", "symbols", "labels", "outputformats", "features", "scaletokens", "composites") a...
['def', 'is_hidden_container', '(', 'self', ',', 'key', ',', 'val', ')', ':', 'if', 'key', 'in', '(', '"layers"', ',', '"classes"', ',', '"styles"', ',', '"symbols"', ',', '"labels"', ',', '"outputformats"', ',', '"features"', ',', '"scaletokens"', ',', '"composites"', ')', 'and', 'isinstance', '(', 'val', ',', 'list',...
The key is not one of the Mapfile keywords, and its values are a list
['The', 'key', 'is', 'not', 'one', 'of', 'the', 'Mapfile', 'keywords', 'and', 'its', 'values', 'are', 'a', 'list']
train
https://github.com/geographika/mappyfile/blob/aecbc5e66ec06896bc4c5db41313503468829d00/mappyfile/pprint.py#L273-L284
4,469
PlaidWeb/Publ
publ/maintenance.py
Maintenance.run
def run(self, force=False): """ Run all pending tasks; 'force' will run all tasks whether they're pending or not. """ now = time.time() for func, spec in self.tasks.items(): if force or now >= spec.get('next_run', 0): func() spec['next_run'] = ...
python
def run(self, force=False): """ Run all pending tasks; 'force' will run all tasks whether they're pending or not. """ now = time.time() for func, spec in self.tasks.items(): if force or now >= spec.get('next_run', 0): func() spec['next_run'] = ...
['def', 'run', '(', 'self', ',', 'force', '=', 'False', ')', ':', 'now', '=', 'time', '.', 'time', '(', ')', 'for', 'func', ',', 'spec', 'in', 'self', '.', 'tasks', '.', 'items', '(', ')', ':', 'if', 'force', 'or', 'now', '>=', 'spec', '.', 'get', '(', "'next_run'", ',', '0', ')', ':', 'func', '(', ')', 'spec', '[', "'...
Run all pending tasks; 'force' will run all tasks whether they're pending or not.
['Run', 'all', 'pending', 'tasks', ';', 'force', 'will', 'run', 'all', 'tasks', 'whether', 'they', 're', 'pending', 'or', 'not', '.']
train
https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/maintenance.py#L16-L23
4,470
synw/dataswim
dataswim/data/clean.py
Clean.fdate
def fdate(self, *cols, precision: str="S", format: str=None): """ Convert column values to formated date string :param \*cols: names of the colums :type \*cols: str, at least one :param precision: time precision: Y, M, D, H, Min S, defaults to "S" :type precision: str, o...
python
def fdate(self, *cols, precision: str="S", format: str=None): """ Convert column values to formated date string :param \*cols: names of the colums :type \*cols: str, at least one :param precision: time precision: Y, M, D, H, Min S, defaults to "S" :type precision: str, o...
['def', 'fdate', '(', 'self', ',', '*', 'cols', ',', 'precision', ':', 'str', '=', '"S"', ',', 'format', ':', 'str', '=', 'None', ')', ':', 'def', 'formatdate', '(', 'row', ')', ':', 'return', 'row', '.', 'strftime', '(', 'format', ')', 'def', 'convert', '(', 'row', ')', ':', 'encoded', '=', "'%Y-%m-%d %H:%M:%S'", 'if'...
Convert column values to formated date string :param \*cols: names of the colums :type \*cols: str, at least one :param precision: time precision: Y, M, D, H, Min S, defaults to "S" :type precision: str, optional :param format: python date format, defaults to None :type ...
['Convert', 'column', 'values', 'to', 'formated', 'date', 'string']
train
https://github.com/synw/dataswim/blob/4a4a53f80daa7cd8e8409d76a19ce07296269da2/dataswim/data/clean.py#L200-L246
4,471
Mangopay/mangopay2-python-sdk
mangopay/compat.py
python_2_unicode_compatible
def python_2_unicode_compatible(klass): """ A decorator that defines __unicode__ and __str__ methods under Python 2. Under Python 3 it does nothing. To support Python 2 and 3 with a single code base, define a __str__ method returning text and apply this decorator to the class. """ if six.PY...
python
def python_2_unicode_compatible(klass): """ A decorator that defines __unicode__ and __str__ methods under Python 2. Under Python 3 it does nothing. To support Python 2 and 3 with a single code base, define a __str__ method returning text and apply this decorator to the class. """ if six.PY...
['def', 'python_2_unicode_compatible', '(', 'klass', ')', ':', 'if', 'six', '.', 'PY2', ':', 'klass', '.', '__unicode__', '=', 'klass', '.', '__str__', 'klass', '.', '__str__', '=', 'lambda', 'self', ':', 'self', '.', '__unicode__', '(', ')', '.', 'encode', '(', "'utf-8'", ')', 'return', 'klass']
A decorator that defines __unicode__ and __str__ methods under Python 2. Under Python 3 it does nothing. To support Python 2 and 3 with a single code base, define a __str__ method returning text and apply this decorator to the class.
['A', 'decorator', 'that', 'defines', '__unicode__', 'and', '__str__', 'methods', 'under', 'Python', '2', '.', 'Under', 'Python', '3', 'it', 'does', 'nothing', '.']
train
https://github.com/Mangopay/mangopay2-python-sdk/blob/9bbbc0f797581c9fdf7da5a70879bee6643024b7/mangopay/compat.py#L5-L16
4,472
mitsei/dlkit
dlkit/json_/osid/objects.py
OsidObjectForm._init_map
def _init_map(self, record_types=None): """Initialize map for form""" OsidForm._init_map(self) self._my_map['displayName'] = dict(self._display_name_default) self._my_map['description'] = dict(self._description_default) self._my_map['genusTypeId'] = self._genus_type_default ...
python
def _init_map(self, record_types=None): """Initialize map for form""" OsidForm._init_map(self) self._my_map['displayName'] = dict(self._display_name_default) self._my_map['description'] = dict(self._description_default) self._my_map['genusTypeId'] = self._genus_type_default ...
['def', '_init_map', '(', 'self', ',', 'record_types', '=', 'None', ')', ':', 'OsidForm', '.', '_init_map', '(', 'self', ')', 'self', '.', '_my_map', '[', "'displayName'", ']', '=', 'dict', '(', 'self', '.', '_display_name_default', ')', 'self', '.', '_my_map', '[', "'description'", ']', '=', 'dict', '(', 'self', '.', ...
Initialize map for form
['Initialize', 'map', 'for', 'form']
train
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/osid/objects.py#L1791-L1797
4,473
MillionIntegrals/vel
vel/rl/algo/policy_gradient/a2c.py
A2CPolicyGradient.process_rollout
def process_rollout(self, batch_info, rollout: Rollout): """ Process rollout for ALGO before any chunking/shuffling """ assert isinstance(rollout, Trajectories), "A2C requires trajectory rollouts" advantages = discount_bootstrap_gae( rewards_buffer=rollout.transition_tensors['rewar...
python
def process_rollout(self, batch_info, rollout: Rollout): """ Process rollout for ALGO before any chunking/shuffling """ assert isinstance(rollout, Trajectories), "A2C requires trajectory rollouts" advantages = discount_bootstrap_gae( rewards_buffer=rollout.transition_tensors['rewar...
['def', 'process_rollout', '(', 'self', ',', 'batch_info', ',', 'rollout', ':', 'Rollout', ')', ':', 'assert', 'isinstance', '(', 'rollout', ',', 'Trajectories', ')', ',', '"A2C requires trajectory rollouts"', 'advantages', '=', 'discount_bootstrap_gae', '(', 'rewards_buffer', '=', 'rollout', '.', 'transition_tensors',...
Process rollout for ALGO before any chunking/shuffling
['Process', 'rollout', 'for', 'ALGO', 'before', 'any', 'chunking', '/', 'shuffling']
train
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/algo/policy_gradient/a2c.py#L20-L39
4,474
codelv/enaml-native-cli
enamlnativecli/main.py
EnamlNativeCli.start
def start(self): """ Run the commands""" self.check_dependencies() self.args = self.parser.parse_args() # Python 3 doesn't set the cmd if no args are given if not hasattr(self.args, 'cmd'): self.parser.print_help() return cmd = self.args.cmd ...
python
def start(self): """ Run the commands""" self.check_dependencies() self.args = self.parser.parse_args() # Python 3 doesn't set the cmd if no args are given if not hasattr(self.args, 'cmd'): self.parser.print_help() return cmd = self.args.cmd ...
['def', 'start', '(', 'self', ')', ':', 'self', '.', 'check_dependencies', '(', ')', 'self', '.', 'args', '=', 'self', '.', 'parser', '.', 'parse_args', '(', ')', "# Python 3 doesn't set the cmd if no args are given", 'if', 'not', 'hasattr', '(', 'self', '.', 'args', ',', "'cmd'", ')', ':', 'self', '.', 'parser', '.', ...
Run the commands
['Run', 'the', 'commands']
train
https://github.com/codelv/enaml-native-cli/blob/81d6faa7e3dd437956f661c512031e49c0d44b63/enamlnativecli/main.py#L1741-L1759
4,475
estnltk/estnltk
estnltk/wordnet/eurown.py
Variant.addUsage_Label
def addUsage_Label(self,usage_label): '''Appends one Usage_Label to usage_labels ''' if isinstance(usage_label, Usage_Label): self.usage_labels.append(usage_label) else: raise (Usage_LabelError, 'usage_label Type should be Usage_Label, not %s' %...
python
def addUsage_Label(self,usage_label): '''Appends one Usage_Label to usage_labels ''' if isinstance(usage_label, Usage_Label): self.usage_labels.append(usage_label) else: raise (Usage_LabelError, 'usage_label Type should be Usage_Label, not %s' %...
['def', 'addUsage_Label', '(', 'self', ',', 'usage_label', ')', ':', 'if', 'isinstance', '(', 'usage_label', ',', 'Usage_Label', ')', ':', 'self', '.', 'usage_labels', '.', 'append', '(', 'usage_label', ')', 'else', ':', 'raise', '(', 'Usage_LabelError', ',', "'usage_label Type should be Usage_Label, not %s'", '%', 'ty...
Appends one Usage_Label to usage_labels
['Appends', 'one', 'Usage_Label', 'to', 'usage_labels']
train
https://github.com/estnltk/estnltk/blob/28ae334a68a0673072febc318635f04da0dcc54a/estnltk/wordnet/eurown.py#L1739-L1748
4,476
modin-project/modin
modin/backends/pandas/query_compiler.py
PandasQueryCompiler._list_like_func
def _list_like_func(self, func, axis, *args, **kwargs): """Apply list-like function across given axis. Args: func: The function to apply. axis: Target axis to apply the function along. Returns: A new PandasQueryCompiler. """ func_prepared = s...
python
def _list_like_func(self, func, axis, *args, **kwargs): """Apply list-like function across given axis. Args: func: The function to apply. axis: Target axis to apply the function along. Returns: A new PandasQueryCompiler. """ func_prepared = s...
['def', '_list_like_func', '(', 'self', ',', 'func', ',', 'axis', ',', '*', 'args', ',', '*', '*', 'kwargs', ')', ':', 'func_prepared', '=', 'self', '.', '_prepare_method', '(', 'lambda', 'df', ':', 'pandas', '.', 'DataFrame', '(', 'df', '.', 'apply', '(', 'func', ',', 'axis', ',', '*', 'args', ',', '*', '*', 'kwargs',...
Apply list-like function across given axis. Args: func: The function to apply. axis: Target axis to apply the function along. Returns: A new PandasQueryCompiler.
['Apply', 'list', '-', 'like', 'function', 'across', 'given', 'axis', '.']
train
https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/backends/pandas/query_compiler.py#L2200-L2225
4,477
openid/JWTConnect-Python-OidcMsg
src/oidcmsg/message.py
Message.serialize
def serialize(self, method="urlencoded", lev=0, **kwargs): """ Convert this instance to another representation. Which representation is given by the choice of serialization method. :param method: A serialization method. Presently 'urlencoded', 'json', 'jwt' and 'dic...
python
def serialize(self, method="urlencoded", lev=0, **kwargs): """ Convert this instance to another representation. Which representation is given by the choice of serialization method. :param method: A serialization method. Presently 'urlencoded', 'json', 'jwt' and 'dic...
['def', 'serialize', '(', 'self', ',', 'method', '=', '"urlencoded"', ',', 'lev', '=', '0', ',', '*', '*', 'kwargs', ')', ':', 'return', 'getattr', '(', 'self', ',', '"to_%s"', '%', 'method', ')', '(', 'lev', '=', 'lev', ',', '*', '*', 'kwargs', ')']
Convert this instance to another representation. Which representation is given by the choice of serialization method. :param method: A serialization method. Presently 'urlencoded', 'json', 'jwt' and 'dict' is supported. :param lev: :param kwargs: Extra key word arg...
['Convert', 'this', 'instance', 'to', 'another', 'representation', '.', 'Which', 'representation', 'is', 'given', 'by', 'the', 'choice', 'of', 'serialization', 'method', '.', ':', 'param', 'method', ':', 'A', 'serialization', 'method', '.', 'Presently', 'urlencoded', 'json', 'jwt', 'and', 'dict', 'is', 'supported', '.'...
train
https://github.com/openid/JWTConnect-Python-OidcMsg/blob/58ade5eb67131abfb99f38b6a92d43b697c9f2fa/src/oidcmsg/message.py#L146-L157
4,478
google/dotty
efilter/transforms/solve.py
solve_tuple
def solve_tuple(expr, vars): """Build a tuple from subexpressions.""" result = tuple(solve(x, vars).value for x in expr.children) return Result(result, ())
python
def solve_tuple(expr, vars): """Build a tuple from subexpressions.""" result = tuple(solve(x, vars).value for x in expr.children) return Result(result, ())
['def', 'solve_tuple', '(', 'expr', ',', 'vars', ')', ':', 'result', '=', 'tuple', '(', 'solve', '(', 'x', ',', 'vars', ')', '.', 'value', 'for', 'x', 'in', 'expr', '.', 'children', ')', 'return', 'Result', '(', 'result', ',', '(', ')', ')']
Build a tuple from subexpressions.
['Build', 'a', 'tuple', 'from', 'subexpressions', '.']
train
https://github.com/google/dotty/blob/b145131499be0c4b755fc2e2ac19be11a50bce6a/efilter/transforms/solve.py#L404-L407
4,479
pydata/xarray
xarray/core/groupby.py
GroupBy._iter_grouped
def _iter_grouped(self): """Iterate over each element in this group""" for indices in self._group_indices: yield self._obj.isel(**{self._group_dim: indices})
python
def _iter_grouped(self): """Iterate over each element in this group""" for indices in self._group_indices: yield self._obj.isel(**{self._group_dim: indices})
['def', '_iter_grouped', '(', 'self', ')', ':', 'for', 'indices', 'in', 'self', '.', '_group_indices', ':', 'yield', 'self', '.', '_obj', '.', 'isel', '(', '*', '*', '{', 'self', '.', '_group_dim', ':', 'indices', '}', ')']
Iterate over each element in this group
['Iterate', 'over', 'each', 'element', 'in', 'this', 'group']
train
https://github.com/pydata/xarray/blob/6d93a95d05bdbfc33fff24064f67d29dd891ab58/xarray/core/groupby.py#L322-L325
4,480
pandas-dev/pandas
pandas/util/_decorators.py
deprecate
def deprecate(name, alternative, version, alt_name=None, klass=None, stacklevel=2, msg=None): """ Return a new function that emits a deprecation warning on use. To use this method for a deprecated function, another function `alternative` with the same signature must exist. The deprecated ...
python
def deprecate(name, alternative, version, alt_name=None, klass=None, stacklevel=2, msg=None): """ Return a new function that emits a deprecation warning on use. To use this method for a deprecated function, another function `alternative` with the same signature must exist. The deprecated ...
['def', 'deprecate', '(', 'name', ',', 'alternative', ',', 'version', ',', 'alt_name', '=', 'None', ',', 'klass', '=', 'None', ',', 'stacklevel', '=', '2', ',', 'msg', '=', 'None', ')', ':', 'alt_name', '=', 'alt_name', 'or', 'alternative', '.', '__name__', 'klass', '=', 'klass', 'or', 'FutureWarning', 'warning_msg', '...
Return a new function that emits a deprecation warning on use. To use this method for a deprecated function, another function `alternative` with the same signature must exist. The deprecated function will emit a deprecation warning, and in the docstring it will contain the deprecation directive with th...
['Return', 'a', 'new', 'function', 'that', 'emits', 'a', 'deprecation', 'warning', 'on', 'use', '.']
train
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/util/_decorators.py#L9-L74
4,481
spotify/snakebite
snakebite/minicluster.py
MiniCluster.is_zero_bytes_file
def is_zero_bytes_file(self, path): """Return True if file <path> is zero bytes in size, else return False""" return self._getReturnCodeCmd([self._hadoop_cmd, 'fs', '-test', '-z', self._full_hdfs_path(path)]) == 0
python
def is_zero_bytes_file(self, path): """Return True if file <path> is zero bytes in size, else return False""" return self._getReturnCodeCmd([self._hadoop_cmd, 'fs', '-test', '-z', self._full_hdfs_path(path)]) == 0
['def', 'is_zero_bytes_file', '(', 'self', ',', 'path', ')', ':', 'return', 'self', '.', '_getReturnCodeCmd', '(', '[', 'self', '.', '_hadoop_cmd', ',', "'fs'", ',', "'-test'", ',', "'-z'", ',', 'self', '.', '_full_hdfs_path', '(', 'path', ')', ']', ')', '==', '0']
Return True if file <path> is zero bytes in size, else return False
['Return', 'True', 'if', 'file', '<path', '>', 'is', 'zero', 'bytes', 'in', 'size', 'else', 'return', 'False']
train
https://github.com/spotify/snakebite/blob/6a456e6100b0c1be66cc1f7f9d7f50494f369da3/snakebite/minicluster.py#L116-L118
4,482
IBMStreams/pypi.streamsx
streamsx/spl/op.py
Invoke.output
def output(self, stream, value): """SPL output port assignment expression. Arguments: stream(Stream): Output stream the assignment is for. value(str): SPL expression used for an output assignment. This can be a string, a constant, or an :py:class:`Expression`. Returns: ...
python
def output(self, stream, value): """SPL output port assignment expression. Arguments: stream(Stream): Output stream the assignment is for. value(str): SPL expression used for an output assignment. This can be a string, a constant, or an :py:class:`Expression`. Returns: ...
['def', 'output', '(', 'self', ',', 'stream', ',', 'value', ')', ':', 'if', 'stream', 'not', 'in', 'self', '.', 'outputs', ':', 'raise', 'ValueError', '(', '"Stream is not an output of this operator."', ')', 'e', '=', 'self', '.', 'expression', '(', 'value', ')', 'e', '.', '_stream', '=', 'stream', 'return', 'e']
SPL output port assignment expression. Arguments: stream(Stream): Output stream the assignment is for. value(str): SPL expression used for an output assignment. This can be a string, a constant, or an :py:class:`Expression`. Returns: Expression: Output assignment ex...
['SPL', 'output', 'port', 'assignment', 'expression', '.']
train
https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/spl/op.py#L240-L254
4,483
dshean/pygeotools
pygeotools/lib/timelib.py
getTimeZone
def getTimeZone(lat, lon): """Get timezone for a given lat/lon """ #Need to fix for Python 2.x and 3.X support import urllib.request, urllib.error, urllib.parse import xml.etree.ElementTree as ET #http://api.askgeo.com/v1/918/aa8292ec06199d1207ccc15be3180213c984832707f0cbf3d3859db279b4b324/query...
python
def getTimeZone(lat, lon): """Get timezone for a given lat/lon """ #Need to fix for Python 2.x and 3.X support import urllib.request, urllib.error, urllib.parse import xml.etree.ElementTree as ET #http://api.askgeo.com/v1/918/aa8292ec06199d1207ccc15be3180213c984832707f0cbf3d3859db279b4b324/query...
['def', 'getTimeZone', '(', 'lat', ',', 'lon', ')', ':', '#Need to fix for Python 2.x and 3.X support', 'import', 'urllib', '.', 'request', ',', 'urllib', '.', 'error', ',', 'urllib', '.', 'parse', 'import', 'xml', '.', 'etree', '.', 'ElementTree', 'as', 'ET', '#http://api.askgeo.com/v1/918/aa8292ec06199d1207ccc15be318...
Get timezone for a given lat/lon
['Get', 'timezone', 'for', 'a', 'given', 'lat', '/', 'lon']
train
https://github.com/dshean/pygeotools/blob/5ac745717c0098d01eb293ff1fe32fd7358c76ab/pygeotools/lib/timelib.py#L17-L35
4,484
hardbyte/python-can
can/interfaces/systec/ucan.py
UcanServer.init_hardware
def init_hardware(self, serial=None, device_number=ANY_MODULE): """ Initializes the device with the corresponding serial or device number. :param int or None serial: Serial number of the USB-CANmodul. :param int device_number: Device number (0 – 254, or :const:`ANY_MODULE` for the first...
python
def init_hardware(self, serial=None, device_number=ANY_MODULE): """ Initializes the device with the corresponding serial or device number. :param int or None serial: Serial number of the USB-CANmodul. :param int device_number: Device number (0 – 254, or :const:`ANY_MODULE` for the first...
['def', 'init_hardware', '(', 'self', ',', 'serial', '=', 'None', ',', 'device_number', '=', 'ANY_MODULE', ')', ':', 'if', 'not', 'self', '.', '_hw_is_initialized', ':', '# initialize hardware either by device number or serial', 'if', 'serial', 'is', 'None', ':', 'UcanInitHardwareEx', '(', 'byref', '(', 'self', '.', '_...
Initializes the device with the corresponding serial or device number. :param int or None serial: Serial number of the USB-CANmodul. :param int device_number: Device number (0 – 254, or :const:`ANY_MODULE` for the first device).
['Initializes', 'the', 'device', 'with', 'the', 'corresponding', 'serial', 'or', 'device', 'number', '.']
train
https://github.com/hardbyte/python-can/blob/cdc5254d96072df7739263623f3e920628a7d214/can/interfaces/systec/ucan.py#L358-L371
4,485
twilio/twilio-python
twilio/rest/preview/sync/service/sync_list/sync_list_item.py
SyncListItemList.get
def get(self, index): """ Constructs a SyncListItemContext :param index: The index :returns: twilio.rest.preview.sync.service.sync_list.sync_list_item.SyncListItemContext :rtype: twilio.rest.preview.sync.service.sync_list.sync_list_item.SyncListItemContext """ r...
python
def get(self, index): """ Constructs a SyncListItemContext :param index: The index :returns: twilio.rest.preview.sync.service.sync_list.sync_list_item.SyncListItemContext :rtype: twilio.rest.preview.sync.service.sync_list.sync_list_item.SyncListItemContext """ r...
['def', 'get', '(', 'self', ',', 'index', ')', ':', 'return', 'SyncListItemContext', '(', 'self', '.', '_version', ',', 'service_sid', '=', 'self', '.', '_solution', '[', "'service_sid'", ']', ',', 'list_sid', '=', 'self', '.', '_solution', '[', "'list_sid'", ']', ',', 'index', '=', 'index', ',', ')']
Constructs a SyncListItemContext :param index: The index :returns: twilio.rest.preview.sync.service.sync_list.sync_list_item.SyncListItemContext :rtype: twilio.rest.preview.sync.service.sync_list.sync_list_item.SyncListItemContext
['Constructs', 'a', 'SyncListItemContext']
train
https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/preview/sync/service/sync_list/sync_list_item.py#L164-L178
4,486
ray-project/ray
python/ray/experimental/state.py
GlobalState.error_messages
def error_messages(self, driver_id=None): """Get the error messages for all drivers or a specific driver. Args: driver_id: The specific driver to get the errors for. If this is None, then this method retrieves the errors for all drivers. Returns: A dicti...
python
def error_messages(self, driver_id=None): """Get the error messages for all drivers or a specific driver. Args: driver_id: The specific driver to get the errors for. If this is None, then this method retrieves the errors for all drivers. Returns: A dicti...
['def', 'error_messages', '(', 'self', ',', 'driver_id', '=', 'None', ')', ':', 'if', 'driver_id', 'is', 'not', 'None', ':', 'assert', 'isinstance', '(', 'driver_id', ',', 'ray', '.', 'DriverID', ')', 'return', 'self', '.', '_error_messages', '(', 'driver_id', ')', 'error_table_keys', '=', 'self', '.', 'redis_client', ...
Get the error messages for all drivers or a specific driver. Args: driver_id: The specific driver to get the errors for. If this is None, then this method retrieves the errors for all drivers. Returns: A dictionary mapping driver ID to a list of the error messag...
['Get', 'the', 'error', 'messages', 'for', 'all', 'drivers', 'or', 'a', 'specific', 'driver', '.']
train
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/state.py#L876-L902
4,487
UB-UNIBAS/simple-elastic
simple_elastic/index.py
ElasticIndex.scroll
def scroll(self, query=None, scroll='5m', size=100, unpack=True): """Scroll an index with the specified search query. Works as a generator. Will yield `size` results per iteration until all hits are returned. """ query = self.match_all if query is None else query response = self...
python
def scroll(self, query=None, scroll='5m', size=100, unpack=True): """Scroll an index with the specified search query. Works as a generator. Will yield `size` results per iteration until all hits are returned. """ query = self.match_all if query is None else query response = self...
['def', 'scroll', '(', 'self', ',', 'query', '=', 'None', ',', 'scroll', '=', "'5m'", ',', 'size', '=', '100', ',', 'unpack', '=', 'True', ')', ':', 'query', '=', 'self', '.', 'match_all', 'if', 'query', 'is', 'None', 'else', 'query', 'response', '=', 'self', '.', 'instance', '.', 'search', '(', 'index', '=', 'self', '...
Scroll an index with the specified search query. Works as a generator. Will yield `size` results per iteration until all hits are returned.
['Scroll', 'an', 'index', 'with', 'the', 'specified', 'search', 'query', '.']
train
https://github.com/UB-UNIBAS/simple-elastic/blob/54f2fdd3405a7eafbf8873f337da263b8d47532a/simple_elastic/index.py#L137-L151
4,488
iotile/coretools
transport_plugins/awsiot/iotile_transport_awsiot/device_adapter.py
AWSIOTDeviceAdapter._unbind_topics
def _unbind_topics(self, topics): """Unsubscribe to all of the topics we needed for communication with device Args: topics (MQTTTopicValidator): The topic validator for this device that we have connected to. """ self.client.unsubscribe(topics.status) ...
python
def _unbind_topics(self, topics): """Unsubscribe to all of the topics we needed for communication with device Args: topics (MQTTTopicValidator): The topic validator for this device that we have connected to. """ self.client.unsubscribe(topics.status) ...
['def', '_unbind_topics', '(', 'self', ',', 'topics', ')', ':', 'self', '.', 'client', '.', 'unsubscribe', '(', 'topics', '.', 'status', ')', 'self', '.', 'client', '.', 'unsubscribe', '(', 'topics', '.', 'tracing', ')', 'self', '.', 'client', '.', 'unsubscribe', '(', 'topics', '.', 'streaming', ')', 'self', '.', 'clie...
Unsubscribe to all of the topics we needed for communication with device Args: topics (MQTTTopicValidator): The topic validator for this device that we have connected to.
['Unsubscribe', 'to', 'all', 'of', 'the', 'topics', 'we', 'needed', 'for', 'communication', 'with', 'device']
train
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/device_adapter.py#L341-L352
4,489
materialsproject/pymatgen
pymatgen/analysis/adsorption.py
AdsorbateSiteFinder.generate_adsorption_structures
def generate_adsorption_structures(self, molecule, repeat=None, min_lw=5.0, reorient=True, find_args={}): """ Function that generates all adsorption structures for a given molecular adsorbate. Can take repeat argument or minimum length/width of pre...
python
def generate_adsorption_structures(self, molecule, repeat=None, min_lw=5.0, reorient=True, find_args={}): """ Function that generates all adsorption structures for a given molecular adsorbate. Can take repeat argument or minimum length/width of pre...
['def', 'generate_adsorption_structures', '(', 'self', ',', 'molecule', ',', 'repeat', '=', 'None', ',', 'min_lw', '=', '5.0', ',', 'reorient', '=', 'True', ',', 'find_args', '=', '{', '}', ')', ':', 'if', 'repeat', 'is', 'None', ':', 'xrep', '=', 'np', '.', 'ceil', '(', 'min_lw', '/', 'np', '.', 'linalg', '.', 'norm',...
Function that generates all adsorption structures for a given molecular adsorbate. Can take repeat argument or minimum length/width of precursor slab as an input Args: molecule (Molecule): molecule corresponding to adsorbate repeat (3-tuple or list): repeat argument for...
['Function', 'that', 'generates', 'all', 'adsorption', 'structures', 'for', 'a', 'given', 'molecular', 'adsorbate', '.', 'Can', 'take', 'repeat', 'argument', 'or', 'minimum', 'length', '/', 'width', 'of', 'precursor', 'slab', 'as', 'an', 'input']
train
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/analysis/adsorption.py#L423-L449
4,490
decryptus/sonicprobe
sonicprobe/helpers.py
linesubst
def linesubst(line, variables): """ In a string, substitute '{{varname}}' occurrences with the value of variables['varname'], '\\' being an escaping char... If at first you don't understand this function, draw its finite state machine and everything will become crystal clear :) """ # trivial...
python
def linesubst(line, variables): """ In a string, substitute '{{varname}}' occurrences with the value of variables['varname'], '\\' being an escaping char... If at first you don't understand this function, draw its finite state machine and everything will become crystal clear :) """ # trivial...
['def', 'linesubst', '(', 'line', ',', 'variables', ')', ':', '# trivial no substitution early detection:', 'if', "'{{'", 'not', 'in', 'line', 'and', "'\\\\'", 'not', 'in', 'line', ':', 'return', 'line', 'st', '=', 'NORM', 'out', '=', '""', 'curvar', '=', '""', 'for', 'c', 'in', 'line', ':', 'if', 'st', 'is', 'NORM', '...
In a string, substitute '{{varname}}' occurrences with the value of variables['varname'], '\\' being an escaping char... If at first you don't understand this function, draw its finite state machine and everything will become crystal clear :)
['In', 'a', 'string', 'substitute', '{{', 'varname', '}}', 'occurrences', 'with', 'the', 'value', 'of', 'variables', '[', 'varname', ']', '\\\\', 'being', 'an', 'escaping', 'char', '...', 'If', 'at', 'first', 'you', 'don', 't', 'understand', 'this', 'function', 'draw', 'its', 'finite', 'state', 'machine', 'and', 'every...
train
https://github.com/decryptus/sonicprobe/blob/72f73f3a40d2982d79ad68686e36aa31d94b76f8/sonicprobe/helpers.py#L357-L423
4,491
jameshilliard/hlk-sw16
hlk_sw16/protocol.py
SW16Protocol._reset_timeout
def _reset_timeout(self): """Reset timeout for date keep alive.""" if self._timeout: self._timeout.cancel() self._timeout = self.loop.call_later(self.client.timeout, self.transport.close)
python
def _reset_timeout(self): """Reset timeout for date keep alive.""" if self._timeout: self._timeout.cancel() self._timeout = self.loop.call_later(self.client.timeout, self.transport.close)
['def', '_reset_timeout', '(', 'self', ')', ':', 'if', 'self', '.', '_timeout', ':', 'self', '.', '_timeout', '.', 'cancel', '(', ')', 'self', '.', '_timeout', '=', 'self', '.', 'loop', '.', 'call_later', '(', 'self', '.', 'client', '.', 'timeout', ',', 'self', '.', 'transport', '.', 'close', ')']
Reset timeout for date keep alive.
['Reset', 'timeout', 'for', 'date', 'keep', 'alive', '.']
train
https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L30-L35
4,492
hobson/pug-dj
pug/dj/db.py
count_in_category
def count_in_category(x='call_type', filter_dict=None, model=DEFAULT_MODEL, app=DEFAULT_APP, sort=True, limit=1000): """ Count the number of records for each discrete (categorical) value of a field and return a dict of two lists, the field values and the counts. >>> x, y = count_in_category(x='call_type', ...
python
def count_in_category(x='call_type', filter_dict=None, model=DEFAULT_MODEL, app=DEFAULT_APP, sort=True, limit=1000): """ Count the number of records for each discrete (categorical) value of a field and return a dict of two lists, the field values and the counts. >>> x, y = count_in_category(x='call_type', ...
['def', 'count_in_category', '(', 'x', '=', "'call_type'", ',', 'filter_dict', '=', 'None', ',', 'model', '=', 'DEFAULT_MODEL', ',', 'app', '=', 'DEFAULT_APP', ',', 'sort', '=', 'True', ',', 'limit', '=', '1000', ')', ':', 'sort', '=', 'sort_prefix', '(', 'sort', ')', 'model', '=', 'get_model', '(', 'model', ',', 'app'...
Count the number of records for each discrete (categorical) value of a field and return a dict of two lists, the field values and the counts. >>> x, y = count_in_category(x='call_type', filter_dict={'model__startswith': 'LC60'}, limit=5, sort=1) >>> len(x) == len(y) == 5 True >>> y[1] >= y[0] True
['Count', 'the', 'number', 'of', 'records', 'for', 'each', 'discrete', '(', 'categorical', ')', 'value', 'of', 'a', 'field', 'and', 'return', 'a', 'dict', 'of', 'two', 'lists', 'the', 'field', 'values', 'and', 'the', 'counts', '.']
train
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L582-L612
4,493
MKLab-ITI/reveal-graph-embedding
reveal_graph_embedding/embedding/competing_methods.py
laplacian_eigenmaps
def laplacian_eigenmaps(adjacency_matrix, k): """ Performs spectral graph embedding using the graph symmetric normalized Laplacian matrix. Introduced in: Belkin, M., & Niyogi, P. (2003). Laplacian eigenmaps for dimensionality reduction and data representation. Neural c...
python
def laplacian_eigenmaps(adjacency_matrix, k): """ Performs spectral graph embedding using the graph symmetric normalized Laplacian matrix. Introduced in: Belkin, M., & Niyogi, P. (2003). Laplacian eigenmaps for dimensionality reduction and data representation. Neural c...
['def', 'laplacian_eigenmaps', '(', 'adjacency_matrix', ',', 'k', ')', ':', '# Calculate sparse graph Laplacian.', 'laplacian', '=', 'get_normalized_laplacian', '(', 'adjacency_matrix', ')', '# Calculate bottom k+1 eigenvalues and eigenvectors of normalized Laplacian.', 'try', ':', 'eigenvalues', ',', 'eigenvectors', '...
Performs spectral graph embedding using the graph symmetric normalized Laplacian matrix. Introduced in: Belkin, M., & Niyogi, P. (2003). Laplacian eigenmaps for dimensionality reduction and data representation. Neural computation, 15(6), 1373-1396. Inputs: - A in R^(nx...
['Performs', 'spectral', 'graph', 'embedding', 'using', 'the', 'graph', 'symmetric', 'normalized', 'Laplacian', 'matrix', '.']
train
https://github.com/MKLab-ITI/reveal-graph-embedding/blob/eda862687aa5a64b79c6b12de1b4dca6ce986dc8/reveal_graph_embedding/embedding/competing_methods.py#L264-L294
4,494
StanfordVL/robosuite
robosuite/environments/baxter.py
BaxterEnv._load_model
def _load_model(self): """Loads robot and optionally add grippers.""" super()._load_model() self.mujoco_robot = Baxter() if self.has_gripper_right: self.gripper_right = gripper_factory(self.gripper_right_name) if not self.gripper_visualization: sel...
python
def _load_model(self): """Loads robot and optionally add grippers.""" super()._load_model() self.mujoco_robot = Baxter() if self.has_gripper_right: self.gripper_right = gripper_factory(self.gripper_right_name) if not self.gripper_visualization: sel...
['def', '_load_model', '(', 'self', ')', ':', 'super', '(', ')', '.', '_load_model', '(', ')', 'self', '.', 'mujoco_robot', '=', 'Baxter', '(', ')', 'if', 'self', '.', 'has_gripper_right', ':', 'self', '.', 'gripper_right', '=', 'gripper_factory', '(', 'self', '.', 'gripper_right_name', ')', 'if', 'not', 'self', '.', '...
Loads robot and optionally add grippers.
['Loads', 'robot', 'and', 'optionally', 'add', 'grippers', '.']
train
https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/environments/baxter.py#L76-L90
4,495
openego/eDisGo
edisgo/tools/pypsa_io_lopf.py
lv_to_pypsa
def lv_to_pypsa(network): """ Convert LV grid topology to PyPSA representation Includes grid topology of all LV grids of :attr:`~.grid.grid.Grid.lv_grids` Parameters ---------- network : Network eDisGo grid container Returns ------- dict of :pandas:`pandas.DataFrame<datafr...
python
def lv_to_pypsa(network): """ Convert LV grid topology to PyPSA representation Includes grid topology of all LV grids of :attr:`~.grid.grid.Grid.lv_grids` Parameters ---------- network : Network eDisGo grid container Returns ------- dict of :pandas:`pandas.DataFrame<datafr...
['def', 'lv_to_pypsa', '(', 'network', ')', ':', 'generators', '=', '[', ']', 'loads', '=', '[', ']', 'branch_tees', '=', '[', ']', 'lines', '=', '[', ']', 'lv_stations', '=', '[', ']', 'storages', '=', '[', ']', 'for', 'lv_grid', 'in', 'network', '.', 'mv_grid', '.', 'lv_grids', ':', 'generators', '.', 'extend', '(', ...
Convert LV grid topology to PyPSA representation Includes grid topology of all LV grids of :attr:`~.grid.grid.Grid.lv_grids` Parameters ---------- network : Network eDisGo grid container Returns ------- dict of :pandas:`pandas.DataFrame<dataframe>` A DataFrame for each typ...
['Convert', 'LV', 'grid', 'topology', 'to', 'PyPSA', 'representation']
train
https://github.com/openego/eDisGo/blob/e6245bdaf236f9c49dbda5a18c1c458290f41e2b/edisgo/tools/pypsa_io_lopf.py#L436-L587
4,496
allenai/allennlp
allennlp/semparse/domain_languages/nlvr_language.py
NlvrLanguage.top
def top(self, objects: Set[Object]) -> Set[Object]: """ Return the topmost objects (i.e. minimum y_loc). The comparison is done separately for each box. """ objects_per_box = self._separate_objects_by_boxes(objects) return_set: Set[Object] = set() for _, box_objec...
python
def top(self, objects: Set[Object]) -> Set[Object]: """ Return the topmost objects (i.e. minimum y_loc). The comparison is done separately for each box. """ objects_per_box = self._separate_objects_by_boxes(objects) return_set: Set[Object] = set() for _, box_objec...
['def', 'top', '(', 'self', ',', 'objects', ':', 'Set', '[', 'Object', ']', ')', '->', 'Set', '[', 'Object', ']', ':', 'objects_per_box', '=', 'self', '.', '_separate_objects_by_boxes', '(', 'objects', ')', 'return_set', ':', 'Set', '[', 'Object', ']', '=', 'set', '(', ')', 'for', '_', ',', 'box_objects', 'in', 'object...
Return the topmost objects (i.e. minimum y_loc). The comparison is done separately for each box.
['Return', 'the', 'topmost', 'objects', '(', 'i', '.', 'e', '.', 'minimum', 'y_loc', ')', '.', 'The', 'comparison', 'is', 'done', 'separately', 'for', 'each', 'box', '.']
train
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/nlvr_language.py#L344-L354
4,497
theislab/scanpy
scanpy/preprocessing/_deprecated/highly_variable_genes.py
filter_genes_cv_deprecated
def filter_genes_cv_deprecated(X, Ecutoff, cvFilter): """Filter genes by coefficient of variance and mean. See `filter_genes_dispersion`. Reference: Weinreb et al. (2017). """ if issparse(X): raise ValueError('Not defined for sparse input. See `filter_genes_dispersion`.') mean_filter =...
python
def filter_genes_cv_deprecated(X, Ecutoff, cvFilter): """Filter genes by coefficient of variance and mean. See `filter_genes_dispersion`. Reference: Weinreb et al. (2017). """ if issparse(X): raise ValueError('Not defined for sparse input. See `filter_genes_dispersion`.') mean_filter =...
['def', 'filter_genes_cv_deprecated', '(', 'X', ',', 'Ecutoff', ',', 'cvFilter', ')', ':', 'if', 'issparse', '(', 'X', ')', ':', 'raise', 'ValueError', '(', "'Not defined for sparse input. See `filter_genes_dispersion`.'", ')', 'mean_filter', '=', 'np', '.', 'mean', '(', 'X', ',', 'axis', '=', '0', ')', '>', 'Ecutoff',...
Filter genes by coefficient of variance and mean. See `filter_genes_dispersion`. Reference: Weinreb et al. (2017).
['Filter', 'genes', 'by', 'coefficient', 'of', 'variance', 'and', 'mean', '.']
train
https://github.com/theislab/scanpy/blob/9e4e5ee02e04cf618872d9b098e24f0542e8b227/scanpy/preprocessing/_deprecated/highly_variable_genes.py#L196-L208
4,498
boriel/zxbasic
arch/zx48k/optimizer.py
Registers.reset_flags
def reset_flags(self): """ Resets flags to an "unknown state" """ self.C = None self.Z = None self.P = None self.S = None
python
def reset_flags(self): """ Resets flags to an "unknown state" """ self.C = None self.Z = None self.P = None self.S = None
['def', 'reset_flags', '(', 'self', ')', ':', 'self', '.', 'C', '=', 'None', 'self', '.', 'Z', '=', 'None', 'self', '.', 'P', '=', 'None', 'self', '.', 'S', '=', 'None']
Resets flags to an "unknown state"
['Resets', 'flags', 'to', 'an', 'unknown', 'state']
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/optimizer.py#L412-L418
4,499
cmbruns/pyopenvr
src/openvr/glframework/glfw_app.py
GlfwBaseApp.render_scene
def render_scene(self): "render scene one time" self.init_gl() # should be a no-op after the first frame is rendered glfw.make_context_current(self.window) self.renderer.render_scene() # Done rendering # glfw.swap_buffers(self.window) # avoid double buffering to avoid sta...
python
def render_scene(self): "render scene one time" self.init_gl() # should be a no-op after the first frame is rendered glfw.make_context_current(self.window) self.renderer.render_scene() # Done rendering # glfw.swap_buffers(self.window) # avoid double buffering to avoid sta...
['def', 'render_scene', '(', 'self', ')', ':', 'self', '.', 'init_gl', '(', ')', '# should be a no-op after the first frame is rendered', 'glfw', '.', 'make_context_current', '(', 'self', '.', 'window', ')', 'self', '.', 'renderer', '.', 'render_scene', '(', ')', '# Done rendering', '# glfw.swap_buffers(self.window) # ...
render scene one time
['render', 'scene', 'one', 'time']
train
https://github.com/cmbruns/pyopenvr/blob/68395d26bb3df6ab1f0f059c38d441f962938be6/src/openvr/glframework/glfw_app.py#L56-L64