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
5,500
log2timeline/plaso
plaso/cli/pinfo_tool.py
PinfoTool._CalculateStorageCounters
def _CalculateStorageCounters(self, storage_reader): """Calculates the counters of the entire storage. Args: storage_reader (StorageReader): storage reader. Returns: dict[str,collections.Counter]: storage counters. """ analysis_reports_counter = collections.Counter() analysis_repor...
python
def _CalculateStorageCounters(self, storage_reader): """Calculates the counters of the entire storage. Args: storage_reader (StorageReader): storage reader. Returns: dict[str,collections.Counter]: storage counters. """ analysis_reports_counter = collections.Counter() analysis_repor...
['def', '_CalculateStorageCounters', '(', 'self', ',', 'storage_reader', ')', ':', 'analysis_reports_counter', '=', 'collections', '.', 'Counter', '(', ')', 'analysis_reports_counter_error', '=', 'False', 'event_labels_counter', '=', 'collections', '.', 'Counter', '(', ')', 'event_labels_counter_error', '=', 'False', '...
Calculates the counters of the entire storage. Args: storage_reader (StorageReader): storage reader. Returns: dict[str,collections.Counter]: storage counters.
['Calculates', 'the', 'counters', 'of', 'the', 'entire', 'storage', '.']
train
https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/cli/pinfo_tool.py#L59-L123
5,501
msztolcman/versionner
versionner/vcs/git.py
VCSEngine._exec
def _exec(cmd): """Execute command using subprocess.Popen :param cmd: :return: (code, stdout, stderr) """ process = subprocess.Popen(cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE) # pylint: disable=unexpected-keyword-arg (stdout, stderr) = process.communica...
python
def _exec(cmd): """Execute command using subprocess.Popen :param cmd: :return: (code, stdout, stderr) """ process = subprocess.Popen(cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE) # pylint: disable=unexpected-keyword-arg (stdout, stderr) = process.communica...
['def', '_exec', '(', 'cmd', ')', ':', 'process', '=', 'subprocess', '.', 'Popen', '(', 'cmd', ',', 'stderr', '=', 'subprocess', '.', 'PIPE', ',', 'stdout', '=', 'subprocess', '.', 'PIPE', ')', '# pylint: disable=unexpected-keyword-arg', '(', 'stdout', ',', 'stderr', ')', '=', 'process', '.', 'communicate', '(', 'timeo...
Execute command using subprocess.Popen :param cmd: :return: (code, stdout, stderr)
['Execute', 'command', 'using', 'subprocess', '.', 'Popen', ':', 'param', 'cmd', ':', ':', 'return', ':', '(', 'code', 'stdout', 'stderr', ')']
train
https://github.com/msztolcman/versionner/blob/78fca02859e3e3eb71c9eb7ea230758944177c54/versionner/vcs/git.py#L66-L76
5,502
ssato/python-anyconfig
src/anyconfig/cli.py
_load_diff
def _load_diff(args, extra_opts): """ :param args: :class:`argparse.Namespace` object :param extra_opts: Map object given to API.load as extra options """ try: diff = API.load(args.inputs, args.itype, ac_ignore_missing=args.ignore_missing, ac_m...
python
def _load_diff(args, extra_opts): """ :param args: :class:`argparse.Namespace` object :param extra_opts: Map object given to API.load as extra options """ try: diff = API.load(args.inputs, args.itype, ac_ignore_missing=args.ignore_missing, ac_m...
['def', '_load_diff', '(', 'args', ',', 'extra_opts', ')', ':', 'try', ':', 'diff', '=', 'API', '.', 'load', '(', 'args', '.', 'inputs', ',', 'args', '.', 'itype', ',', 'ac_ignore_missing', '=', 'args', '.', 'ignore_missing', ',', 'ac_merge', '=', 'args', '.', 'merge', ',', 'ac_template', '=', 'args', '.', 'template', ...
:param args: :class:`argparse.Namespace` object :param extra_opts: Map object given to API.load as extra options
[':', 'param', 'args', ':', ':', 'class', ':', 'argparse', '.', 'Namespace', 'object', ':', 'param', 'extra_opts', ':', 'Map', 'object', 'given', 'to', 'API', '.', 'load', 'as', 'extra', 'options']
train
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/cli.py#L333-L353
5,503
pazz/urwidtrees
urwidtrees/lru_cache.py
lru_cache
def lru_cache(maxsize=100, typed=False): """Least-recently-used cache decorator. If *maxsize* is set to None, the LRU features are disabled and the cache can grow without bound. If *typed* is True, arguments of different types will be cached separately. For example, f(3.0) and f(3) will be treated...
python
def lru_cache(maxsize=100, typed=False): """Least-recently-used cache decorator. If *maxsize* is set to None, the LRU features are disabled and the cache can grow without bound. If *typed* is True, arguments of different types will be cached separately. For example, f(3.0) and f(3) will be treated...
['def', 'lru_cache', '(', 'maxsize', '=', '100', ',', 'typed', '=', 'False', ')', ':', '# Users should only access the lru_cache through its public API:', '# cache_info, cache_clear, and f.__wrapped__', '# The internals of the lru_cache are encapsulated for thread safety and', '# to allow the implementation to ch...
Least-recently-used cache decorator. If *maxsize* is set to None, the LRU features are disabled and the cache can grow without bound. If *typed* is True, arguments of different types will be cached separately. For example, f(3.0) and f(3) will be treated as distinct calls with distinct results. ...
['Least', '-', 'recently', '-', 'used', 'cache', 'decorator', '.']
train
https://github.com/pazz/urwidtrees/blob/d1fa38ce4f37db00bdfc574b856023b5db4c7ead/urwidtrees/lru_cache.py#L10-L141
5,504
hozn/coilmq
coilmq/queue.py
QueueManager.close
def close(self): """ Closes all resources/backends associated with this queue manager. """ self.log.info("Shutting down queue manager.") if hasattr(self.store, 'close'): self.store.close() if hasattr(self.subscriber_scheduler, 'close'): self.subsc...
python
def close(self): """ Closes all resources/backends associated with this queue manager. """ self.log.info("Shutting down queue manager.") if hasattr(self.store, 'close'): self.store.close() if hasattr(self.subscriber_scheduler, 'close'): self.subsc...
['def', 'close', '(', 'self', ')', ':', 'self', '.', 'log', '.', 'info', '(', '"Shutting down queue manager."', ')', 'if', 'hasattr', '(', 'self', '.', 'store', ',', "'close'", ')', ':', 'self', '.', 'store', '.', 'close', '(', ')', 'if', 'hasattr', '(', 'self', '.', 'subscriber_scheduler', ',', "'close'", ')', ':', 's...
Closes all resources/backends associated with this queue manager.
['Closes', 'all', 'resources', '/', 'backends', 'associated', 'with', 'this', 'queue', 'manager', '.']
train
https://github.com/hozn/coilmq/blob/76b7fcf347144b3a5746423a228bed121dc564b5/coilmq/queue.py#L99-L111
5,505
Groundworkstech/pybfd
pybfd/bfd.py
Bfd.archive_filenames
def archive_filenames(self): """Return the list of files inside an archive file.""" try: return _bfd.archive_list_filenames(self._ptr) except TypeError, err: raise BfdException(err)
python
def archive_filenames(self): """Return the list of files inside an archive file.""" try: return _bfd.archive_list_filenames(self._ptr) except TypeError, err: raise BfdException(err)
['def', 'archive_filenames', '(', 'self', ')', ':', 'try', ':', 'return', '_bfd', '.', 'archive_list_filenames', '(', 'self', '.', '_ptr', ')', 'except', 'TypeError', ',', 'err', ':', 'raise', 'BfdException', '(', 'err', ')']
Return the list of files inside an archive file.
['Return', 'the', 'list', 'of', 'files', 'inside', 'an', 'archive', 'file', '.']
train
https://github.com/Groundworkstech/pybfd/blob/9e722435929b4ad52212043a6f1e9e9ce60b5d72/pybfd/bfd.py#L239-L244
5,506
bhmm/bhmm
bhmm/hidden/api.py
transition_counts
def transition_counts(alpha, beta, A, pobs, T=None, out=None): """ Sum for all t the probability to transition from state i to state j. Parameters ---------- alpha : ndarray((T,N), dtype = float), optional, default = None alpha[t,i] is the ith forward coefficient of time t. beta : ndarray((...
python
def transition_counts(alpha, beta, A, pobs, T=None, out=None): """ Sum for all t the probability to transition from state i to state j. Parameters ---------- alpha : ndarray((T,N), dtype = float), optional, default = None alpha[t,i] is the ith forward coefficient of time t. beta : ndarray((...
['def', 'transition_counts', '(', 'alpha', ',', 'beta', ',', 'A', ',', 'pobs', ',', 'T', '=', 'None', ',', 'out', '=', 'None', ')', ':', 'if', '__impl__', '==', '__IMPL_PYTHON__', ':', 'return', 'ip', '.', 'transition_counts', '(', 'alpha', ',', 'beta', ',', 'A', ',', 'pobs', ',', 'T', '=', 'T', ',', 'out', '=', 'out',...
Sum for all t the probability to transition from state i to state j. Parameters ---------- alpha : ndarray((T,N), dtype = float), optional, default = None alpha[t,i] is the ith forward coefficient of time t. beta : ndarray((T,N), dtype = float), optional, default = None beta[t,i] is the...
['Sum', 'for', 'all', 't', 'the', 'probability', 'to', 'transition', 'from', 'state', 'i', 'to', 'state', 'j', '.']
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hidden/api.py#L214-L248
5,507
LogicalDash/LiSE
allegedb/allegedb/__init__.py
setedge
def setedge(delta, is_multigraph, graph, orig, dest, idx, exists): """Change a delta to say that an edge was created or deleted""" if is_multigraph(graph): delta.setdefault(graph, {}).setdefault('edges', {})\ .setdefault(orig, {}).setdefault(dest, {})[idx] = bool(exists) else: de...
python
def setedge(delta, is_multigraph, graph, orig, dest, idx, exists): """Change a delta to say that an edge was created or deleted""" if is_multigraph(graph): delta.setdefault(graph, {}).setdefault('edges', {})\ .setdefault(orig, {}).setdefault(dest, {})[idx] = bool(exists) else: de...
['def', 'setedge', '(', 'delta', ',', 'is_multigraph', ',', 'graph', ',', 'orig', ',', 'dest', ',', 'idx', ',', 'exists', ')', ':', 'if', 'is_multigraph', '(', 'graph', ')', ':', 'delta', '.', 'setdefault', '(', 'graph', ',', '{', '}', ')', '.', 'setdefault', '(', "'edges'", ',', '{', '}', ')', '.', 'setdefault', '(', ...
Change a delta to say that an edge was created or deleted
['Change', 'a', 'delta', 'to', 'say', 'that', 'an', 'edge', 'was', 'created', 'or', 'deleted']
train
https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/__init__.py#L242-L249
5,508
xmunoz/sodapy
sodapy/__init__.py
Socrata.download_attachments
def download_attachments(self, dataset_identifier, content_type="json", download_dir="~/sodapy_downloads"): ''' Download all of the attachments associated with a dataset. Return the paths of downloaded files. ''' metadata = self.get_metadata(dataset_i...
python
def download_attachments(self, dataset_identifier, content_type="json", download_dir="~/sodapy_downloads"): ''' Download all of the attachments associated with a dataset. Return the paths of downloaded files. ''' metadata = self.get_metadata(dataset_i...
['def', 'download_attachments', '(', 'self', ',', 'dataset_identifier', ',', 'content_type', '=', '"json"', ',', 'download_dir', '=', '"~/sodapy_downloads"', ')', ':', 'metadata', '=', 'self', '.', 'get_metadata', '(', 'dataset_identifier', ',', 'content_type', '=', 'content_type', ')', 'files', '=', '[', ']', 'attachm...
Download all of the attachments associated with a dataset. Return the paths of downloaded files.
['Download', 'all', 'of', 'the', 'attachments', 'associated', 'with', 'a', 'dataset', '.', 'Return', 'the', 'paths', 'of', 'downloaded', 'files', '.']
train
https://github.com/xmunoz/sodapy/blob/dad2ca9560cde0acb03bdb4423260e891ca40d7b/sodapy/__init__.py#L269-L304
5,509
saltstack/salt
salt/cloud/clouds/linode.py
get_password
def get_password(vm_): r''' Return the password to use for a VM. vm\_ The configuration to obtain the password from. ''' return config.get_cloud_config_value( 'password', vm_, __opts__, default=config.get_cloud_config_value( 'passwd', vm_, __opts__, s...
python
def get_password(vm_): r''' Return the password to use for a VM. vm\_ The configuration to obtain the password from. ''' return config.get_cloud_config_value( 'password', vm_, __opts__, default=config.get_cloud_config_value( 'passwd', vm_, __opts__, s...
['def', 'get_password', '(', 'vm_', ')', ':', 'return', 'config', '.', 'get_cloud_config_value', '(', "'password'", ',', 'vm_', ',', '__opts__', ',', 'default', '=', 'config', '.', 'get_cloud_config_value', '(', "'passwd'", ',', 'vm_', ',', '__opts__', ',', 'search_global', '=', 'False', ')', ',', 'search_global', '=',...
r''' Return the password to use for a VM. vm\_ The configuration to obtain the password from.
['r', 'Return', 'the', 'password', 'to', 'use', 'for', 'a', 'VM', '.']
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/linode.py#L979-L993
5,510
Yelp/kafka-utils
kafka_utils/kafka_cluster_manager/cluster_info/util.py
_smart_separate_groups
def _smart_separate_groups(groups, key, total): """Given a list of group objects, and a function to extract the number of elements for each of them, return the list of groups that have an excessive number of elements (when compared to a uniform distribution), a list of groups with insufficient elements,...
python
def _smart_separate_groups(groups, key, total): """Given a list of group objects, and a function to extract the number of elements for each of them, return the list of groups that have an excessive number of elements (when compared to a uniform distribution), a list of groups with insufficient elements,...
['def', '_smart_separate_groups', '(', 'groups', ',', 'key', ',', 'total', ')', ':', 'optimum', ',', 'extra', '=', 'compute_optimum', '(', 'len', '(', 'groups', ')', ',', 'total', ')', 'over_loaded', ',', 'under_loaded', ',', 'optimal', '=', '[', ']', ',', '[', ']', ',', '[', ']', 'for', 'group', 'in', 'sorted', '(', '...
Given a list of group objects, and a function to extract the number of elements for each of them, return the list of groups that have an excessive number of elements (when compared to a uniform distribution), a list of groups with insufficient elements, and a list of groups that already have the optimal...
['Given', 'a', 'list', 'of', 'group', 'objects', 'and', 'a', 'function', 'to', 'extract', 'the', 'number', 'of', 'elements', 'for', 'each', 'of', 'them', 'return', 'the', 'list', 'of', 'groups', 'that', 'have', 'an', 'excessive', 'number', 'of', 'elements', '(', 'when', 'compared', 'to', 'a', 'uniform', 'distribution',...
train
https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_cluster_manager/cluster_info/util.py#L26-L53
5,511
oisinmulvihill/stomper
lib/stomper/examples/stompbuffer-tx.py
StompProtocol.connected
def connected(self, msg): """Once I've connected I want to subscribe to my the message queue. """ stomper.Engine.connected(self, msg) self.log.info("Connected: session %s. Beginning say hello." % msg['headers']['session']) def setup_looping_call(): lc = Loop...
python
def connected(self, msg): """Once I've connected I want to subscribe to my the message queue. """ stomper.Engine.connected(self, msg) self.log.info("Connected: session %s. Beginning say hello." % msg['headers']['session']) def setup_looping_call(): lc = Loop...
['def', 'connected', '(', 'self', ',', 'msg', ')', ':', 'stomper', '.', 'Engine', '.', 'connected', '(', 'self', ',', 'msg', ')', 'self', '.', 'log', '.', 'info', '(', '"Connected: session %s. Beginning say hello."', '%', 'msg', '[', "'headers'", ']', '[', "'session'", ']', ')', 'def', 'setup_looping_call', '(', ')', '...
Once I've connected I want to subscribe to my the message queue.
['Once', 'I', 've', 'connected', 'I', 'want', 'to', 'subscribe', 'to', 'my', 'the', 'message', 'queue', '.']
train
https://github.com/oisinmulvihill/stomper/blob/842ed2353a4ddd638d35929ae5b7b70eb298305c/lib/stomper/examples/stompbuffer-tx.py#L35-L56
5,512
timgabets/bpc8583
bpc8583/tools.py
get_random_hex
def get_random_hex(length): """ Return random hex string of a given length """ if length <= 0: return '' return hexify(random.randint(pow(2, length*2), pow(2, length*4)))[0:length]
python
def get_random_hex(length): """ Return random hex string of a given length """ if length <= 0: return '' return hexify(random.randint(pow(2, length*2), pow(2, length*4)))[0:length]
['def', 'get_random_hex', '(', 'length', ')', ':', 'if', 'length', '<=', '0', ':', 'return', "''", 'return', 'hexify', '(', 'random', '.', 'randint', '(', 'pow', '(', '2', ',', 'length', '*', '2', ')', ',', 'pow', '(', '2', ',', 'length', '*', '4', ')', ')', ')', '[', '0', ':', 'length', ']']
Return random hex string of a given length
['Return', 'random', 'hex', 'string', 'of', 'a', 'given', 'length']
train
https://github.com/timgabets/bpc8583/blob/1b8e95d73ad273ad9d11bff40d1af3f06f0f3503/bpc8583/tools.py#L59-L65
5,513
KelSolaar/Umbra
umbra/ui/widgets/delayed_QSplashScreen.py
Delayed_QSplashScreen.wait_time
def wait_time(self, value): """ Setter for **self.__wait_time** attribute. :param value: Attribute value. :type value: int or float """ if value is not None: assert type(value) in (int, float), "'{0}' attribute: '{1}' type is not 'int' or 'float'!".format( ...
python
def wait_time(self, value): """ Setter for **self.__wait_time** attribute. :param value: Attribute value. :type value: int or float """ if value is not None: assert type(value) in (int, float), "'{0}' attribute: '{1}' type is not 'int' or 'float'!".format( ...
['def', 'wait_time', '(', 'self', ',', 'value', ')', ':', 'if', 'value', 'is', 'not', 'None', ':', 'assert', 'type', '(', 'value', ')', 'in', '(', 'int', ',', 'float', ')', ',', '"\'{0}\' attribute: \'{1}\' type is not \'int\' or \'float\'!"', '.', 'format', '(', '"wait_time"', ',', 'value', ')', 'assert', 'value', '>=...
Setter for **self.__wait_time** attribute. :param value: Attribute value. :type value: int or float
['Setter', 'for', '**', 'self', '.', '__wait_time', '**', 'attribute', '.']
train
https://github.com/KelSolaar/Umbra/blob/66f45f08d9d723787f1191989f8b0dda84b412ce/umbra/ui/widgets/delayed_QSplashScreen.py#L85-L97
5,514
mitsei/dlkit
dlkit/json_/learning/managers.py
LearningProxyManager.get_objective_requisite_assignment_session
def get_objective_requisite_assignment_session(self, proxy): """Gets the session for managing objective requisites. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.learning.ObjectiveRequisiteAssignmentSession) - an ``ObjectiveRequisiteAssignmentSession`` raise: ...
python
def get_objective_requisite_assignment_session(self, proxy): """Gets the session for managing objective requisites. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.learning.ObjectiveRequisiteAssignmentSession) - an ``ObjectiveRequisiteAssignmentSession`` raise: ...
['def', 'get_objective_requisite_assignment_session', '(', 'self', ',', 'proxy', ')', ':', 'if', 'not', 'self', '.', 'supports_objective_requisite_assignment', '(', ')', ':', 'raise', 'errors', '.', 'Unimplemented', '(', ')', '# pylint: disable=no-member', 'return', 'sessions', '.', 'ObjectiveRequisiteAssignmentSession...
Gets the session for managing objective requisites. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.learning.ObjectiveRequisiteAssignmentSession) - an ``ObjectiveRequisiteAssignmentSession`` raise: NullArgument - ``proxy`` is ``null`` raise: OperationFailed - u...
['Gets', 'the', 'session', 'for', 'managing', 'objective', 'requisites', '.']
train
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/learning/managers.py#L1859-L1877
5,515
saltstack/salt
salt/modules/mac_power.py
get_wake_on_network
def get_wake_on_network(): ''' Displays whether 'wake on network' is on or off if supported :return: A string value representing the "wake on network" settings :rtype: string CLI Example: .. code-block:: bash salt '*' power.get_wake_on_network ''' ret = salt.utils.mac_utils.e...
python
def get_wake_on_network(): ''' Displays whether 'wake on network' is on or off if supported :return: A string value representing the "wake on network" settings :rtype: string CLI Example: .. code-block:: bash salt '*' power.get_wake_on_network ''' ret = salt.utils.mac_utils.e...
['def', 'get_wake_on_network', '(', ')', ':', 'ret', '=', 'salt', '.', 'utils', '.', 'mac_utils', '.', 'execute_return_result', '(', "'systemsetup -getwakeonnetworkaccess'", ')', 'return', 'salt', '.', 'utils', '.', 'mac_utils', '.', 'validate_enabled', '(', 'salt', '.', 'utils', '.', 'mac_utils', '.', 'parse_return', ...
Displays whether 'wake on network' is on or off if supported :return: A string value representing the "wake on network" settings :rtype: string CLI Example: .. code-block:: bash salt '*' power.get_wake_on_network
['Displays', 'whether', 'wake', 'on', 'network', 'is', 'on', 'or', 'off', 'if', 'supported']
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_power.py#L313-L329
5,516
a1ezzz/wasp-general
wasp_general/network/web/service.py
WWebService.execute
def execute(self, request, target_route): """ :meth:`.WWebServiceProto.execute` method implementation """ presenter = self.create_presenter(request, target_route) presenter_name = target_route.presenter_name() action_name = target_route.presenter_action() presenter_args = target_route.presenter_args() if...
python
def execute(self, request, target_route): """ :meth:`.WWebServiceProto.execute` method implementation """ presenter = self.create_presenter(request, target_route) presenter_name = target_route.presenter_name() action_name = target_route.presenter_action() presenter_args = target_route.presenter_args() if...
['def', 'execute', '(', 'self', ',', 'request', ',', 'target_route', ')', ':', 'presenter', '=', 'self', '.', 'create_presenter', '(', 'request', ',', 'target_route', ')', 'presenter_name', '=', 'target_route', '.', 'presenter_name', '(', ')', 'action_name', '=', 'target_route', '.', 'presenter_action', '(', ')', 'pres...
:meth:`.WWebServiceProto.execute` method implementation
[':', 'meth', ':', '.', 'WWebServiceProto', '.', 'execute', 'method', 'implementation']
train
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/web/service.py#L735-L769
5,517
internetarchive/brozzler
brozzler/ydl.py
final_bounces
def final_bounces(fetches, url): """ Resolves redirect chains in `fetches` and returns a list of fetches representing the final redirect destinations of the given url. There could be more than one if for example youtube-dl hit the same url with HEAD and then GET requests. """ redirects = {} ...
python
def final_bounces(fetches, url): """ Resolves redirect chains in `fetches` and returns a list of fetches representing the final redirect destinations of the given url. There could be more than one if for example youtube-dl hit the same url with HEAD and then GET requests. """ redirects = {} ...
['def', 'final_bounces', '(', 'fetches', ',', 'url', ')', ':', 'redirects', '=', '{', '}', 'for', 'fetch', 'in', 'fetches', ':', '# XXX check http status 301,302,303,307? check for "uri" header', '# as well as "location"? see urllib.request.HTTPRedirectHandler', 'if', "'location'", 'in', 'fetch', '[', "'response_header...
Resolves redirect chains in `fetches` and returns a list of fetches representing the final redirect destinations of the given url. There could be more than one if for example youtube-dl hit the same url with HEAD and then GET requests.
['Resolves', 'redirect', 'chains', 'in', 'fetches', 'and', 'returns', 'a', 'list', 'of', 'fetches', 'representing', 'the', 'final', 'redirect', 'destinations', 'of', 'the', 'given', 'url', '.', 'There', 'could', 'be', 'more', 'than', 'one', 'if', 'for', 'example', 'youtube', '-', 'dl', 'hit', 'the', 'same', 'url', 'wit...
train
https://github.com/internetarchive/brozzler/blob/411b3f266a38b9bb942021c0121ebd8e5ca66447/brozzler/ydl.py#L91-L116
5,518
libyal/dtfabric
dtfabric/reader.py
DataTypeDefinitionsReader._ReadUUIDDataTypeDefinition
def _ReadUUIDDataTypeDefinition( self, definitions_registry, definition_values, definition_name, is_member=False): """Reads an UUID data type definition. Args: definitions_registry (DataTypeDefinitionsRegistry): data type definitions registry. definition_values (dict[str, obje...
python
def _ReadUUIDDataTypeDefinition( self, definitions_registry, definition_values, definition_name, is_member=False): """Reads an UUID data type definition. Args: definitions_registry (DataTypeDefinitionsRegistry): data type definitions registry. definition_values (dict[str, obje...
['def', '_ReadUUIDDataTypeDefinition', '(', 'self', ',', 'definitions_registry', ',', 'definition_values', ',', 'definition_name', ',', 'is_member', '=', 'False', ')', ':', 'return', 'self', '.', '_ReadFixedSizeDataTypeDefinition', '(', 'definitions_registry', ',', 'definition_values', ',', 'data_types', '.', 'UUIDDefi...
Reads an UUID data type definition. Args: definitions_registry (DataTypeDefinitionsRegistry): data type definitions registry. definition_values (dict[str, object]): definition values. definition_name (str): name of the definition. is_member (Optional[bool]): True if the data type ...
['Reads', 'an', 'UUID', 'data', 'type', 'definition', '.']
train
https://github.com/libyal/dtfabric/blob/0d2b5719fa257f6e5c661a406737ebcf8c8db266/dtfabric/reader.py#L1102-L1126
5,519
toumorokoshi/sprinter
sprinter/core/inputs.py
Inputs.get_unset_inputs
def get_unset_inputs(self): """ Return a set of unset inputs """ return set([k for k, v in self._inputs.items() if v.is_empty(False)])
python
def get_unset_inputs(self): """ Return a set of unset inputs """ return set([k for k, v in self._inputs.items() if v.is_empty(False)])
['def', 'get_unset_inputs', '(', 'self', ')', ':', 'return', 'set', '(', '[', 'k', 'for', 'k', ',', 'v', 'in', 'self', '.', '_inputs', '.', 'items', '(', ')', 'if', 'v', '.', 'is_empty', '(', 'False', ')', ']', ')']
Return a set of unset inputs
['Return', 'a', 'set', 'of', 'unset', 'inputs']
train
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/core/inputs.py#L135-L137
5,520
wummel/linkchecker
linkcheck/checker/urlbase.py
UrlBase.set_cache_url
def set_cache_url (self): """Set the URL to be used for caching.""" # remove anchor from cached target url since we assume # URLs with different anchors to have the same content self.cache_url = urlutil.urlunsplit(self.urlparts[:4]+[u'']) if self.cache_url is not None: ...
python
def set_cache_url (self): """Set the URL to be used for caching.""" # remove anchor from cached target url since we assume # URLs with different anchors to have the same content self.cache_url = urlutil.urlunsplit(self.urlparts[:4]+[u'']) if self.cache_url is not None: ...
['def', 'set_cache_url', '(', 'self', ')', ':', '# remove anchor from cached target url since we assume', '# URLs with different anchors to have the same content', 'self', '.', 'cache_url', '=', 'urlutil', '.', 'urlunsplit', '(', 'self', '.', 'urlparts', '[', ':', '4', ']', '+', '[', "u''", ']', ')', 'if', 'self', '.',...
Set the URL to be used for caching.
['Set', 'the', 'URL', 'to', 'be', 'used', 'for', 'caching', '.']
train
https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/checker/urlbase.py#L313-L319
5,521
benhoff/pluginmanager
pluginmanager/plugin_manager.py
PluginManager._instance_parser
def _instance_parser(self, plugins): """ internal method to parse instances of plugins. Determines if each class is a class instance or object instance and calls the appropiate handler method. """ plugins = util.return_list(plugins) for instance in plugin...
python
def _instance_parser(self, plugins): """ internal method to parse instances of plugins. Determines if each class is a class instance or object instance and calls the appropiate handler method. """ plugins = util.return_list(plugins) for instance in plugin...
['def', '_instance_parser', '(', 'self', ',', 'plugins', ')', ':', 'plugins', '=', 'util', '.', 'return_list', '(', 'plugins', ')', 'for', 'instance', 'in', 'plugins', ':', 'if', 'inspect', '.', 'isclass', '(', 'instance', ')', ':', 'self', '.', '_handle_class_instance', '(', 'instance', ')', 'else', ':', 'self', '.', ...
internal method to parse instances of plugins. Determines if each class is a class instance or object instance and calls the appropiate handler method.
['internal', 'method', 'to', 'parse', 'instances', 'of', 'plugins', '.']
train
https://github.com/benhoff/pluginmanager/blob/a8a184f9ebfbb521703492cb88c1dbda4cd04c06/pluginmanager/plugin_manager.py#L135-L148
5,522
odlgroup/odl
odl/discr/grid.py
RectGrid.stride
def stride(self): """Step per axis between neighboring points of a uniform grid. If the grid contains axes that are not uniform, ``stride`` has a ``NaN`` entry. For degenerate (length 1) axes, ``stride`` has value ``0.0``. Returns ------- stride : numpy.array ...
python
def stride(self): """Step per axis between neighboring points of a uniform grid. If the grid contains axes that are not uniform, ``stride`` has a ``NaN`` entry. For degenerate (length 1) axes, ``stride`` has value ``0.0``. Returns ------- stride : numpy.array ...
['def', 'stride', '(', 'self', ')', ':', '# Cache for efficiency instead of re-computing', 'if', 'self', '.', '__stride', 'is', 'None', ':', 'strd', '=', '[', ']', 'for', 'i', 'in', 'range', '(', 'self', '.', 'ndim', ')', ':', 'if', 'not', 'self', '.', 'is_uniform_byaxis', '[', 'i', ']', ':', 'strd', '.', 'append', '('...
Step per axis between neighboring points of a uniform grid. If the grid contains axes that are not uniform, ``stride`` has a ``NaN`` entry. For degenerate (length 1) axes, ``stride`` has value ``0.0``. Returns ------- stride : numpy.array Array of dtype ``f...
['Step', 'per', 'axis', 'between', 'neighboring', 'points', 'of', 'a', 'uniform', 'grid', '.']
train
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/discr/grid.py#L389-L432
5,523
rapidpro/expressions
python/temba_expressions/functions/excel.py
left
def left(ctx, text, num_chars): """ Returns the first characters in a text string """ num_chars = conversions.to_integer(num_chars, ctx) if num_chars < 0: raise ValueError("Number of chars can't be negative") return conversions.to_string(text, ctx)[0:num_chars]
python
def left(ctx, text, num_chars): """ Returns the first characters in a text string """ num_chars = conversions.to_integer(num_chars, ctx) if num_chars < 0: raise ValueError("Number of chars can't be negative") return conversions.to_string(text, ctx)[0:num_chars]
['def', 'left', '(', 'ctx', ',', 'text', ',', 'num_chars', ')', ':', 'num_chars', '=', 'conversions', '.', 'to_integer', '(', 'num_chars', ',', 'ctx', ')', 'if', 'num_chars', '<', '0', ':', 'raise', 'ValueError', '(', '"Number of chars can\'t be negative"', ')', 'return', 'conversions', '.', 'to_string', '(', 'text', '...
Returns the first characters in a text string
['Returns', 'the', 'first', 'characters', 'in', 'a', 'text', 'string']
train
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/functions/excel.py#L56-L63
5,524
ikegami-yukino/madoka-python
madoka/madoka.py
Sketch.shrink
def shrink(self, src, width=0, max_value=0, filter_method=None, path=None, flags=0): """Shrink sketch Params: <Sketch> src_sketch <int> width <int> max_value <lambda> | <function> filter <str> path <int> flags ...
python
def shrink(self, src, width=0, max_value=0, filter_method=None, path=None, flags=0): """Shrink sketch Params: <Sketch> src_sketch <int> width <int> max_value <lambda> | <function> filter <str> path <int> flags ...
['def', 'shrink', '(', 'self', ',', 'src', ',', 'width', '=', '0', ',', 'max_value', '=', '0', ',', 'filter_method', '=', 'None', ',', 'path', '=', 'None', ',', 'flags', '=', '0', ')', ':', 'if', 'filter_method', ':', 'get_', '=', '_madoka', '.', 'Sketch_get__', 'set_', '=', '_madoka', '.', 'Sketch_set__', 'new_sketch'...
Shrink sketch Params: <Sketch> src_sketch <int> width <int> max_value <lambda> | <function> filter <str> path <int> flags
['Shrink', 'sketch', 'Params', ':', '<Sketch', '>', 'src_sketch', '<int', '>', 'width', '<int', '>', 'max_value', '<lambda', '>', '|', '<function', '>', 'filter', '<str', '>', 'path', '<int', '>', 'flags']
train
https://github.com/ikegami-yukino/madoka-python/blob/a9a1efecbc85ac4a24a78cbb19f9aed77b7162d3/madoka/madoka.py#L611-L636
5,525
AntagonistHQ/openprovider.py
openprovider/modules/ssl.py
SSLModule.retrieve_order
def retrieve_order(self, order_id): """Retrieve details on a single order.""" response = self.request(E.retrieveOrderSslCertRequest( E.id(order_id) )) return response.as_model(SSLOrder)
python
def retrieve_order(self, order_id): """Retrieve details on a single order.""" response = self.request(E.retrieveOrderSslCertRequest( E.id(order_id) )) return response.as_model(SSLOrder)
['def', 'retrieve_order', '(', 'self', ',', 'order_id', ')', ':', 'response', '=', 'self', '.', 'request', '(', 'E', '.', 'retrieveOrderSslCertRequest', '(', 'E', '.', 'id', '(', 'order_id', ')', ')', ')', 'return', 'response', '.', 'as_model', '(', 'SSLOrder', ')']
Retrieve details on a single order.
['Retrieve', 'details', 'on', 'a', 'single', 'order', '.']
train
https://github.com/AntagonistHQ/openprovider.py/blob/5871c3d5b3661e23667f147f49f20389c817a0a4/openprovider/modules/ssl.py#L59-L66
5,526
zmathew/django-backbone
backbone/views.py
BackboneAPIView.delete
def delete(self, request, id=None): """ Handles delete requests. """ if id: obj = get_object_or_404(self.queryset(request), id=id) if not self.has_delete_permission(request, obj): return HttpResponseForbidden(_('You do not have permission to perfor...
python
def delete(self, request, id=None): """ Handles delete requests. """ if id: obj = get_object_or_404(self.queryset(request), id=id) if not self.has_delete_permission(request, obj): return HttpResponseForbidden(_('You do not have permission to perfor...
['def', 'delete', '(', 'self', ',', 'request', ',', 'id', '=', 'None', ')', ':', 'if', 'id', ':', 'obj', '=', 'get_object_or_404', '(', 'self', '.', 'queryset', '(', 'request', ')', ',', 'id', '=', 'id', ')', 'if', 'not', 'self', '.', 'has_delete_permission', '(', 'request', ',', 'obj', ')', ':', 'return', 'HttpRespons...
Handles delete requests.
['Handles', 'delete', 'requests', '.']
train
https://github.com/zmathew/django-backbone/blob/53505a247fb058e64a103c4f11da66993037bd6b/backbone/views.py#L185-L197
5,527
google/grr
grr/server/grr_response_server/databases/mysql_clients.py
MySQLDBClientMixin.ReadClientLastPings
def ReadClientLastPings(self, min_last_ping=None, max_last_ping=None, fleetspeak_enabled=None, cursor=None): """Reads client ids for all clients in the database.""" query = "SELECT client_id, UNIX_TIMESTAMP(l...
python
def ReadClientLastPings(self, min_last_ping=None, max_last_ping=None, fleetspeak_enabled=None, cursor=None): """Reads client ids for all clients in the database.""" query = "SELECT client_id, UNIX_TIMESTAMP(l...
['def', 'ReadClientLastPings', '(', 'self', ',', 'min_last_ping', '=', 'None', ',', 'max_last_ping', '=', 'None', ',', 'fleetspeak_enabled', '=', 'None', ',', 'cursor', '=', 'None', ')', ':', 'query', '=', '"SELECT client_id, UNIX_TIMESTAMP(last_ping) FROM clients "', 'query_values', '=', '[', ']', 'where_filters', '='...
Reads client ids for all clients in the database.
['Reads', 'client', 'ids', 'for', 'all', 'clients', 'in', 'the', 'database', '.']
train
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/databases/mysql_clients.py#L482-L512
5,528
facebook/pyre-check
sapp/sapp/cli_lib.py
require_option
def require_option(current_ctx: click.Context, param_name: str) -> None: """Throw an exception if an option wasn't required. This is useful when its optional in some contexts but required for a subcommand""" ctx = current_ctx param_definition = None while ctx is not None: # ctx.command.para...
python
def require_option(current_ctx: click.Context, param_name: str) -> None: """Throw an exception if an option wasn't required. This is useful when its optional in some contexts but required for a subcommand""" ctx = current_ctx param_definition = None while ctx is not None: # ctx.command.para...
['def', 'require_option', '(', 'current_ctx', ':', 'click', '.', 'Context', ',', 'param_name', ':', 'str', ')', '->', 'None', ':', 'ctx', '=', 'current_ctx', 'param_definition', '=', 'None', 'while', 'ctx', 'is', 'not', 'None', ':', '# ctx.command.params has the actual definition of the param. We use', '# this when rai...
Throw an exception if an option wasn't required. This is useful when its optional in some contexts but required for a subcommand
['Throw', 'an', 'exception', 'if', 'an', 'option', 'wasn', 't', 'required', '.', 'This', 'is', 'useful', 'when', 'its', 'optional', 'in', 'some', 'contexts', 'but', 'required', 'for', 'a', 'subcommand']
train
https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/sapp/sapp/cli_lib.py#L33-L52
5,529
box/flaky
flaky/_flaky_plugin.py
_FlakyPlugin._copy_flaky_attributes
def _copy_flaky_attributes(cls, test, test_class): """ Copy flaky attributes from the test callable or class to the test. :param test: The test that is being prepared to run :type test: :class:`nose.case.Test` """ test_callable = cls._get_test_cal...
python
def _copy_flaky_attributes(cls, test, test_class): """ Copy flaky attributes from the test callable or class to the test. :param test: The test that is being prepared to run :type test: :class:`nose.case.Test` """ test_callable = cls._get_test_cal...
['def', '_copy_flaky_attributes', '(', 'cls', ',', 'test', ',', 'test_class', ')', ':', 'test_callable', '=', 'cls', '.', '_get_test_callable', '(', 'test', ')', 'if', 'test_callable', 'is', 'None', ':', 'return', 'for', 'attr', ',', 'value', 'in', 'cls', '.', '_get_flaky_attributes', '(', 'test_class', ')', '.', 'item...
Copy flaky attributes from the test callable or class to the test. :param test: The test that is being prepared to run :type test: :class:`nose.case.Test`
['Copy', 'flaky', 'attributes', 'from', 'the', 'test', 'callable', 'or', 'class', 'to', 'the', 'test', '.']
train
https://github.com/box/flaky/blob/c23126f09b2cc5a4071cfa43a11272927e9c0fcd/flaky/_flaky_plugin.py#L398-L418
5,530
bunq/sdk_python
bunq/sdk/context.py
ApiContext._get_expiry_timestamp
def _get_expiry_timestamp(cls, session_server): """ :type session_server: core.SessionServer :rtype: datetime.datetime """ timeout_seconds = cls._get_session_timeout_seconds(session_server) time_now = datetime.datetime.now() return time_now + datetime.timedelta...
python
def _get_expiry_timestamp(cls, session_server): """ :type session_server: core.SessionServer :rtype: datetime.datetime """ timeout_seconds = cls._get_session_timeout_seconds(session_server) time_now = datetime.datetime.now() return time_now + datetime.timedelta...
['def', '_get_expiry_timestamp', '(', 'cls', ',', 'session_server', ')', ':', 'timeout_seconds', '=', 'cls', '.', '_get_session_timeout_seconds', '(', 'session_server', ')', 'time_now', '=', 'datetime', '.', 'datetime', '.', 'now', '(', ')', 'return', 'time_now', '+', 'datetime', '.', 'timedelta', '(', 'seconds', '=', ...
:type session_server: core.SessionServer :rtype: datetime.datetime
[':', 'type', 'session_server', ':', 'core', '.', 'SessionServer']
train
https://github.com/bunq/sdk_python/blob/da6c9b83e6d83ee8062617f53c6eb7293c0d863d/bunq/sdk/context.py#L145-L155
5,531
mabuchilab/QNET
src/qnet/convert/to_sympy_matrix.py
convert_to_sympy_matrix
def convert_to_sympy_matrix(expr, full_space=None): """Convert a QNET expression to an explicit ``n x n`` instance of `sympy.Matrix`, where ``n`` is the dimension of `full_space`. The entries of the matrix may contain symbols. Parameters: expr: a QNET expression full_space (qnet.algebra...
python
def convert_to_sympy_matrix(expr, full_space=None): """Convert a QNET expression to an explicit ``n x n`` instance of `sympy.Matrix`, where ``n`` is the dimension of `full_space`. The entries of the matrix may contain symbols. Parameters: expr: a QNET expression full_space (qnet.algebra...
['def', 'convert_to_sympy_matrix', '(', 'expr', ',', 'full_space', '=', 'None', ')', ':', 'if', 'full_space', 'is', 'None', ':', 'full_space', '=', 'expr', '.', 'space', 'if', 'not', 'expr', '.', 'space', '.', 'is_tensor_factor_of', '(', 'full_space', ')', ':', 'raise', 'ValueError', '(', '"expr must be in full_space"'...
Convert a QNET expression to an explicit ``n x n`` instance of `sympy.Matrix`, where ``n`` is the dimension of `full_space`. The entries of the matrix may contain symbols. Parameters: expr: a QNET expression full_space (qnet.algebra.hilbert_space_algebra.HilbertSpace): The Hilbe...
['Convert', 'a', 'QNET', 'expression', 'to', 'an', 'explicit', 'n', 'x', 'n', 'instance', 'of', 'sympy', '.', 'Matrix', 'where', 'n', 'is', 'the', 'dimension', 'of', 'full_space', '.', 'The', 'entries', 'of', 'the', 'matrix', 'may', 'contain', 'symbols', '.']
train
https://github.com/mabuchilab/QNET/blob/cc20d26dad78691d34c67173e5cd67dcac94208a/src/qnet/convert/to_sympy_matrix.py#L36-L149
5,532
zimeon/iiif
iiif/flask_utils.py
add_shared_configs
def add_shared_configs(p, base_dir=''): """Add configargparser/argparse configs for shared argument. Arguments: p - configargparse.ArgParser object base_dir - base directory for file/path defaults. """ p.add('--host', default='localhost', help="Service host") p.add('--port...
python
def add_shared_configs(p, base_dir=''): """Add configargparser/argparse configs for shared argument. Arguments: p - configargparse.ArgParser object base_dir - base directory for file/path defaults. """ p.add('--host', default='localhost', help="Service host") p.add('--port...
['def', 'add_shared_configs', '(', 'p', ',', 'base_dir', '=', "''", ')', ':', 'p', '.', 'add', '(', "'--host'", ',', 'default', '=', "'localhost'", ',', 'help', '=', '"Service host"', ')', 'p', '.', 'add', '(', "'--port'", ',', "'-p'", ',', 'type', '=', 'int', ',', 'default', '=', '8000', ',', 'help', '=', '"Service po...
Add configargparser/argparse configs for shared argument. Arguments: p - configargparse.ArgParser object base_dir - base directory for file/path defaults.
['Add', 'configargparser', '/', 'argparse', 'configs', 'for', 'shared', 'argument', '.']
train
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/flask_utils.py#L571-L611
5,533
brocade/pynos
pynos/versions/ver_7/ver_7_1_0/yang/brocade_policer.py
brocade_policer.policy_map_class_cl_name
def policy_map_class_cl_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") policy_map = ET.SubElement(config, "policy-map", xmlns="urn:brocade.com:mgmt:brocade-policer") po_name_key = ET.SubElement(policy_map, "po-name") po_name_key.text = kwar...
python
def policy_map_class_cl_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") policy_map = ET.SubElement(config, "policy-map", xmlns="urn:brocade.com:mgmt:brocade-policer") po_name_key = ET.SubElement(policy_map, "po-name") po_name_key.text = kwar...
['def', 'policy_map_class_cl_name', '(', 'self', ',', '*', '*', 'kwargs', ')', ':', 'config', '=', 'ET', '.', 'Element', '(', '"config"', ')', 'policy_map', '=', 'ET', '.', 'SubElement', '(', 'config', ',', '"policy-map"', ',', 'xmlns', '=', '"urn:brocade.com:mgmt:brocade-policer"', ')', 'po_name_key', '=', 'ET', '.', ...
Auto Generated Code
['Auto', 'Generated', 'Code']
train
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_7/ver_7_1_0/yang/brocade_policer.py#L284-L296
5,534
huggingface/pytorch-pretrained-BERT
pytorch_pretrained_bert/modeling_openai.py
load_tf_weights_in_openai_gpt
def load_tf_weights_in_openai_gpt(model, openai_checkpoint_folder_path): """ Load tf pre-trained weights in a pytorch model (from NumPy arrays here) """ import re import numpy as np print("Loading weights...") names = json.load(open(openai_checkpoint_folder_path + '/parameters_names.json', "r", ...
python
def load_tf_weights_in_openai_gpt(model, openai_checkpoint_folder_path): """ Load tf pre-trained weights in a pytorch model (from NumPy arrays here) """ import re import numpy as np print("Loading weights...") names = json.load(open(openai_checkpoint_folder_path + '/parameters_names.json', "r", ...
['def', 'load_tf_weights_in_openai_gpt', '(', 'model', ',', 'openai_checkpoint_folder_path', ')', ':', 'import', 're', 'import', 'numpy', 'as', 'np', 'print', '(', '"Loading weights..."', ')', 'names', '=', 'json', '.', 'load', '(', 'open', '(', 'openai_checkpoint_folder_path', '+', "'/parameters_names.json'", ',', '"r...
Load tf pre-trained weights in a pytorch model (from NumPy arrays here)
['Load', 'tf', 'pre', '-', 'trained', 'weights', 'in', 'a', 'pytorch', 'model', '(', 'from', 'NumPy', 'arrays', 'here', ')']
train
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/pytorch_pretrained_bert/modeling_openai.py#L46-L113
5,535
danielperna84/pyhomematic
pyhomematic/_hm.py
RPCFunctions.listDevices
def listDevices(self, interface_id): """The CCU / Homegear asks for devices known to our XML-RPC server. We respond to that request using this method.""" LOG.debug("RPCFunctions.listDevices: interface_id = %s, _devices_raw = %s" % ( interface_id, str(self._devices_raw))) remote = int...
python
def listDevices(self, interface_id): """The CCU / Homegear asks for devices known to our XML-RPC server. We respond to that request using this method.""" LOG.debug("RPCFunctions.listDevices: interface_id = %s, _devices_raw = %s" % ( interface_id, str(self._devices_raw))) remote = int...
['def', 'listDevices', '(', 'self', ',', 'interface_id', ')', ':', 'LOG', '.', 'debug', '(', '"RPCFunctions.listDevices: interface_id = %s, _devices_raw = %s"', '%', '(', 'interface_id', ',', 'str', '(', 'self', '.', '_devices_raw', ')', ')', ')', 'remote', '=', 'interface_id', '.', 'split', '(', "'-'", ')', '[', '-', ...
The CCU / Homegear asks for devices known to our XML-RPC server. We respond to that request using this method.
['The', 'CCU', '/', 'Homegear', 'asks', 'for', 'devices', 'known', 'to', 'our', 'XML', '-', 'RPC', 'server', '.', 'We', 'respond', 'to', 'that', 'request', 'using', 'this', 'method', '.']
train
https://github.com/danielperna84/pyhomematic/blob/8b91f3e84c83f05d289c740d507293a0d6759d8e/pyhomematic/_hm.py#L233-L242
5,536
diffeo/rejester
rejester/workers.py
ForkWorker.live_log_child
def live_log_child(self): '''Start the logging child process if it died.''' if not (self.log_child and self.pid_is_alive(self.log_child)): self.start_log_child()
python
def live_log_child(self): '''Start the logging child process if it died.''' if not (self.log_child and self.pid_is_alive(self.log_child)): self.start_log_child()
['def', 'live_log_child', '(', 'self', ')', ':', 'if', 'not', '(', 'self', '.', 'log_child', 'and', 'self', '.', 'pid_is_alive', '(', 'self', '.', 'log_child', ')', ')', ':', 'self', '.', 'start_log_child', '(', ')']
Start the logging child process if it died.
['Start', 'the', 'logging', 'child', 'process', 'if', 'it', 'died', '.']
train
https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/workers.py#L785-L788
5,537
bryanwweber/thermohw
thermohw/preprocessors.py
RawRemover.preprocess
def preprocess( self, nb: "NotebookNode", resources: dict ) -> Tuple["NotebookNode", dict]: """Remove any raw cells from the Notebook. By default, exclude raw cells from the output. Change this by including global_content_filter->include_raw = True in the resources dictionary. ...
python
def preprocess( self, nb: "NotebookNode", resources: dict ) -> Tuple["NotebookNode", dict]: """Remove any raw cells from the Notebook. By default, exclude raw cells from the output. Change this by including global_content_filter->include_raw = True in the resources dictionary. ...
['def', 'preprocess', '(', 'self', ',', 'nb', ':', '"NotebookNode"', ',', 'resources', ':', 'dict', ')', '->', 'Tuple', '[', '"NotebookNode"', ',', 'dict', ']', ':', 'if', 'not', 'resources', '.', 'get', '(', '"global_content_filter"', ',', '{', '}', ')', '.', 'get', '(', '"include_raw"', ',', 'False', ')', ':', 'keep_...
Remove any raw cells from the Notebook. By default, exclude raw cells from the output. Change this by including global_content_filter->include_raw = True in the resources dictionary. This preprocessor is necessary because the NotebookExporter doesn't include the exclude_raw config.
['Remove', 'any', 'raw', 'cells', 'from', 'the', 'Notebook', '.']
train
https://github.com/bryanwweber/thermohw/blob/b6be276c14f8adf6ae23f5498065de74f868ccaa/thermohw/preprocessors.py#L109-L126
5,538
codeinn/vcs
vcs/backends/git/config.py
ConfigFile.write_to_path
def write_to_path(self, path=None): """Write configuration to a file on disk.""" if path is None: path = self.path f = GitFile(path, 'wb') try: self.write_to_file(f) finally: f.close()
python
def write_to_path(self, path=None): """Write configuration to a file on disk.""" if path is None: path = self.path f = GitFile(path, 'wb') try: self.write_to_file(f) finally: f.close()
['def', 'write_to_path', '(', 'self', ',', 'path', '=', 'None', ')', ':', 'if', 'path', 'is', 'None', ':', 'path', '=', 'self', '.', 'path', 'f', '=', 'GitFile', '(', 'path', ',', "'wb'", ')', 'try', ':', 'self', '.', 'write_to_file', '(', 'f', ')', 'finally', ':', 'f', '.', 'close', '(', ')']
Write configuration to a file on disk.
['Write', 'configuration', 'to', 'a', 'file', 'on', 'disk', '.']
train
https://github.com/codeinn/vcs/blob/e6cd94188e9c36d273411bf3adc0584ac6ab92a0/vcs/backends/git/config.py#L277-L285
5,539
saltstack/salt
salt/modules/netbox.py
get_interfaces
def get_interfaces(device_name=None, **kwargs): ''' .. versionadded:: 2019.2.0 Returns interfaces for a specific device using arbitrary netbox filters device_name The name of the device, e.g., ``edge_router`` kwargs Optional arguments to be used for filtering CLI Example: ...
python
def get_interfaces(device_name=None, **kwargs): ''' .. versionadded:: 2019.2.0 Returns interfaces for a specific device using arbitrary netbox filters device_name The name of the device, e.g., ``edge_router`` kwargs Optional arguments to be used for filtering CLI Example: ...
['def', 'get_interfaces', '(', 'device_name', '=', 'None', ',', '*', '*', 'kwargs', ')', ':', 'if', 'not', 'device_name', ':', 'device_name', '=', '__opts__', '[', "'id'", ']', 'netbox_device', '=', 'get_', '(', "'dcim'", ',', "'devices'", ',', 'name', '=', 'device_name', ')', 'return', 'filter_', '(', "'dcim'", ',', "...
.. versionadded:: 2019.2.0 Returns interfaces for a specific device using arbitrary netbox filters device_name The name of the device, e.g., ``edge_router`` kwargs Optional arguments to be used for filtering CLI Example: .. code-block:: bash salt myminion netbox.get_inte...
['..', 'versionadded', '::', '2019', '.', '2', '.', '0']
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netbox.py#L522-L546
5,540
quantmind/pulsar
pulsar/utils/structures/skiplist.py
Skiplist.rank
def rank(self, score): '''Return the 0-based index (rank) of ``score``. If the score is not available it returns a negative integer which absolute score is the right most closest index with score less than ``score``. ''' node = self._head rank = 0 for i i...
python
def rank(self, score): '''Return the 0-based index (rank) of ``score``. If the score is not available it returns a negative integer which absolute score is the right most closest index with score less than ``score``. ''' node = self._head rank = 0 for i i...
['def', 'rank', '(', 'self', ',', 'score', ')', ':', 'node', '=', 'self', '.', '_head', 'rank', '=', '0', 'for', 'i', 'in', 'range', '(', 'self', '.', '_level', '-', '1', ',', '-', '1', ',', '-', '1', ')', ':', 'while', 'node', '.', 'next', '[', 'i', ']', 'and', 'node', '.', 'next', '[', 'i', ']', '.', 'score', '<', 's...
Return the 0-based index (rank) of ``score``. If the score is not available it returns a negative integer which absolute score is the right most closest index with score less than ``score``.
['Return', 'the', '0', '-', 'based', 'index', '(', 'rank', ')', 'of', 'score', '.']
train
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/structures/skiplist.py#L72-L89
5,541
tensorflow/tensorboard
tensorboard/backend/event_processing/sqlite_writer.py
SqliteWriter._maybe_init_tags
def _maybe_init_tags(self, run_id, tag_to_metadata): """Returns a tag-to-ID map for the given tags, creating rows if needed. Args: run_id: the ID of the run to which these tags belong. tag_to_metadata: map of tag name to SummaryMetadata for the tag. """ cursor = self._db.cursor() # TODO...
python
def _maybe_init_tags(self, run_id, tag_to_metadata): """Returns a tag-to-ID map for the given tags, creating rows if needed. Args: run_id: the ID of the run to which these tags belong. tag_to_metadata: map of tag name to SummaryMetadata for the tag. """ cursor = self._db.cursor() # TODO...
['def', '_maybe_init_tags', '(', 'self', ',', 'run_id', ',', 'tag_to_metadata', ')', ':', 'cursor', '=', 'self', '.', '_db', '.', 'cursor', '(', ')', '# TODO: for huge numbers of tags (e.g. 1000+), this is slower than just', '# querying for the known tag names explicitly; find a better tradeoff.', 'cursor', '.', 'execu...
Returns a tag-to-ID map for the given tags, creating rows if needed. Args: run_id: the ID of the run to which these tags belong. tag_to_metadata: map of tag name to SummaryMetadata for the tag.
['Returns', 'a', 'tag', '-', 'to', '-', 'ID', 'map', 'for', 'the', 'given', 'tags', 'creating', 'rows', 'if', 'needed', '.']
train
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/backend/event_processing/sqlite_writer.py#L143-L174
5,542
markuskiller/textblob-de
textblob_de/ext/_pattern/text/tree.py
chunked
def chunked(sentence): """ Returns a list of Chunk and Chink objects from the given sentence. Chink is a subclass of Chunk used for words that have Word.chunk == None (e.g., punctuation marks, conjunctions). """ # For example, to construct a training vector with the head of previous chunks a...
python
def chunked(sentence): """ Returns a list of Chunk and Chink objects from the given sentence. Chink is a subclass of Chunk used for words that have Word.chunk == None (e.g., punctuation marks, conjunctions). """ # For example, to construct a training vector with the head of previous chunks a...
['def', 'chunked', '(', 'sentence', ')', ':', '# For example, to construct a training vector with the head of previous chunks as a feature.', '# Doing this with Sentence.chunks would discard the punctuation marks and conjunctions', '# (Sentence.chunks only yields Chunk objects), which amy be useful features.', 'chunks'...
Returns a list of Chunk and Chink objects from the given sentence. Chink is a subclass of Chunk used for words that have Word.chunk == None (e.g., punctuation marks, conjunctions).
['Returns', 'a', 'list', 'of', 'Chunk', 'and', 'Chink', 'objects', 'from', 'the', 'given', 'sentence', '.', 'Chink', 'is', 'a', 'subclass', 'of', 'Chunk', 'used', 'for', 'words', 'that', 'have', 'Word', '.', 'chunk', '==', 'None', '(', 'e', '.', 'g', '.', 'punctuation', 'marks', 'conjunctions', ')', '.']
train
https://github.com/markuskiller/textblob-de/blob/1b427b2cdd7e5e9fd3697677a98358fae4aa6ad1/textblob_de/ext/_pattern/text/tree.py#L1100-L1117
5,543
awslabs/aws-sam-cli
samcli/local/lambdafn/env_vars.py
EnvironmentVariables._get_aws_variables
def _get_aws_variables(self): """ Returns the AWS specific environment variables that should be available in the Lambda runtime. They are prefixed it "AWS_*". :return dict: Name and value of AWS environment variable """ result = { # Variable that says this f...
python
def _get_aws_variables(self): """ Returns the AWS specific environment variables that should be available in the Lambda runtime. They are prefixed it "AWS_*". :return dict: Name and value of AWS environment variable """ result = { # Variable that says this f...
['def', '_get_aws_variables', '(', 'self', ')', ':', 'result', '=', '{', '# Variable that says this function is running in Local Lambda', '"AWS_SAM_LOCAL"', ':', '"true"', ',', '# Function configuration', '"AWS_LAMBDA_FUNCTION_MEMORY_SIZE"', ':', 'str', '(', 'self', '.', 'memory', ')', ',', '"AWS_LAMBDA_FUNCTION_TIMEOU...
Returns the AWS specific environment variables that should be available in the Lambda runtime. They are prefixed it "AWS_*". :return dict: Name and value of AWS environment variable
['Returns', 'the', 'AWS', 'specific', 'environment', 'variables', 'that', 'should', 'be', 'available', 'in', 'the', 'Lambda', 'runtime', '.', 'They', 'are', 'prefixed', 'it', 'AWS_', '*', '.']
train
https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/lambdafn/env_vars.py#L136-L173
5,544
gwastro/pycbc
pycbc/workflow/segment.py
setup_segment_generation
def setup_segment_generation(workflow, out_dir, tag=None): """ This function is the gateway for setting up the segment generation steps in a workflow. It is designed to be able to support multiple ways of obtaining these segments and to combine/edit such files as necessary for analysis. The current ...
python
def setup_segment_generation(workflow, out_dir, tag=None): """ This function is the gateway for setting up the segment generation steps in a workflow. It is designed to be able to support multiple ways of obtaining these segments and to combine/edit such files as necessary for analysis. The current ...
['def', 'setup_segment_generation', '(', 'workflow', ',', 'out_dir', ',', 'tag', '=', 'None', ')', ':', 'logging', '.', 'info', '(', '"Entering segment generation module"', ')', 'make_analysis_dir', '(', 'out_dir', ')', 'cp', '=', 'workflow', '.', 'cp', '# Parse for options in ini file', 'segmentsMethod', '=', 'cp', '....
This function is the gateway for setting up the segment generation steps in a workflow. It is designed to be able to support multiple ways of obtaining these segments and to combine/edit such files as necessary for analysis. The current modules have the capability to generate files at runtime or to gene...
['This', 'function', 'is', 'the', 'gateway', 'for', 'setting', 'up', 'the', 'segment', 'generation', 'steps', 'in', 'a', 'workflow', '.', 'It', 'is', 'designed', 'to', 'be', 'able', 'to', 'support', 'multiple', 'ways', 'of', 'obtaining', 'these', 'segments', 'and', 'to', 'combine', '/', 'edit', 'such', 'files', 'as', '...
train
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/segment.py#L342-L462
5,545
florianholzapfel/panasonic-viera
panasonic_viera/__init__.py
RemoteControl.send_key
def send_key(self, key): """Send a key command to the TV.""" if isinstance(key, Keys): key = key.value params = '<X_KeyEvent>{}</X_KeyEvent>'.format(key) self.soap_request(URL_CONTROL_NRC, URN_REMOTE_CONTROL, 'X_SendKey', params)
python
def send_key(self, key): """Send a key command to the TV.""" if isinstance(key, Keys): key = key.value params = '<X_KeyEvent>{}</X_KeyEvent>'.format(key) self.soap_request(URL_CONTROL_NRC, URN_REMOTE_CONTROL, 'X_SendKey', params)
['def', 'send_key', '(', 'self', ',', 'key', ')', ':', 'if', 'isinstance', '(', 'key', ',', 'Keys', ')', ':', 'key', '=', 'key', '.', 'value', 'params', '=', "'<X_KeyEvent>{}</X_KeyEvent>'", '.', 'format', '(', 'key', ')', 'self', '.', 'soap_request', '(', 'URL_CONTROL_NRC', ',', 'URN_REMOTE_CONTROL', ',', "'X_SendKey'...
Send a key command to the TV.
['Send', 'a', 'key', 'command', 'to', 'the', 'TV', '.']
train
https://github.com/florianholzapfel/panasonic-viera/blob/bf912ff6eb03b59e3dde30b994a0fb1d883eb873/panasonic_viera/__init__.py#L229-L235
5,546
Gorialis/jishaku
jishaku/cog.py
Jishaku.jsk_shutdown
async def jsk_shutdown(self, ctx: commands.Context): """ Logs this bot out. """ await ctx.send("Logging out now..") await ctx.bot.logout()
python
async def jsk_shutdown(self, ctx: commands.Context): """ Logs this bot out. """ await ctx.send("Logging out now..") await ctx.bot.logout()
['async', 'def', 'jsk_shutdown', '(', 'self', ',', 'ctx', ':', 'commands', '.', 'Context', ')', ':', 'await', 'ctx', '.', 'send', '(', '"Logging out now.."', ')', 'await', 'ctx', '.', 'bot', '.', 'logout', '(', ')']
Logs this bot out.
['Logs', 'this', 'bot', 'out', '.']
train
https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/cog.py#L301-L307
5,547
saltstack/salt
salt/modules/inspectlib/query.py
Query._identity
def _identity(self, *args, **kwargs): ''' Local users and groups. accounts Can be either 'local', 'remote' or 'all' (equal to "local,remote"). Remote accounts cannot be resolved on all systems, but only those, which supports 'passwd -S -a'. disabled ...
python
def _identity(self, *args, **kwargs): ''' Local users and groups. accounts Can be either 'local', 'remote' or 'all' (equal to "local,remote"). Remote accounts cannot be resolved on all systems, but only those, which supports 'passwd -S -a'. disabled ...
['def', '_identity', '(', 'self', ',', '*', 'args', ',', '*', '*', 'kwargs', ')', ':', 'LOCAL', '=', "'local accounts'", 'EXT', '=', "'external accounts'", 'data', '=', 'dict', '(', ')', 'data', '[', 'LOCAL', ']', '=', 'self', '.', '_get_local_users', '(', 'disabled', '=', 'kwargs', '.', 'get', '(', "'disabled'", ')', ...
Local users and groups. accounts Can be either 'local', 'remote' or 'all' (equal to "local,remote"). Remote accounts cannot be resolved on all systems, but only those, which supports 'passwd -S -a'. disabled True (or False, default) to return only disabl...
['Local', 'users', 'and', 'groups', '.']
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/inspectlib/query.py#L281-L301
5,548
mixmastamyk/console
console/detection.py
parse_vtrgb
def parse_vtrgb(path='/etc/vtrgb'): ''' Parse the color table for the Linux console. ''' palette = () table = [] try: with open(path) as infile: for i, line in enumerate(infile): row = tuple(int(val) for val in line.split(',')) table.append(row) ...
python
def parse_vtrgb(path='/etc/vtrgb'): ''' Parse the color table for the Linux console. ''' palette = () table = [] try: with open(path) as infile: for i, line in enumerate(infile): row = tuple(int(val) for val in line.split(',')) table.append(row) ...
['def', 'parse_vtrgb', '(', 'path', '=', "'/etc/vtrgb'", ')', ':', 'palette', '=', '(', ')', 'table', '=', '[', ']', 'try', ':', 'with', 'open', '(', 'path', ')', 'as', 'infile', ':', 'for', 'i', ',', 'line', 'in', 'enumerate', '(', 'infile', ')', ':', 'row', '=', 'tuple', '(', 'int', '(', 'val', ')', 'for', 'val', 'in...
Parse the color table for the Linux console.
['Parse', 'the', 'color', 'table', 'for', 'the', 'Linux', 'console', '.']
train
https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/detection.py#L378-L395
5,549
wilson-eft/wilson
wilson/run/smeft/classes.py
SMEFT._run_sm_scale_in
def _run_sm_scale_in(self, C_out, scale_sm=91.1876): """Get the SM parameters at the EW scale, using an estimate `C_out` of the Wilson coefficients at that scale, and run them to the input scale.""" # initialize an empty SMEFT instance smeft_sm = SMEFT(wc=None) C_in_sm = ...
python
def _run_sm_scale_in(self, C_out, scale_sm=91.1876): """Get the SM parameters at the EW scale, using an estimate `C_out` of the Wilson coefficients at that scale, and run them to the input scale.""" # initialize an empty SMEFT instance smeft_sm = SMEFT(wc=None) C_in_sm = ...
['def', '_run_sm_scale_in', '(', 'self', ',', 'C_out', ',', 'scale_sm', '=', '91.1876', ')', ':', '# initialize an empty SMEFT instance', 'smeft_sm', '=', 'SMEFT', '(', 'wc', '=', 'None', ')', 'C_in_sm', '=', 'smeftutil', '.', 'C_array2dict', '(', 'np', '.', 'zeros', '(', '9999', ')', ')', '# set the SM parameters to t...
Get the SM parameters at the EW scale, using an estimate `C_out` of the Wilson coefficients at that scale, and run them to the input scale.
['Get', 'the', 'SM', 'parameters', 'at', 'the', 'EW', 'scale', 'using', 'an', 'estimate', 'C_out', 'of', 'the', 'Wilson', 'coefficients', 'at', 'that', 'scale', 'and', 'run', 'them', 'to', 'the', 'input', 'scale', '.']
train
https://github.com/wilson-eft/wilson/blob/4164f55ff663d4f668c6e2b4575fd41562662cc9/wilson/run/smeft/classes.py#L144-L162
5,550
etgalloway/newtabmagic
newtabmagic.py
pydoc_cli_monkey_patched
def pydoc_cli_monkey_patched(port): """In Python 3, run pydoc.cli with builtins.input monkey-patched so that pydoc can be run as a process. """ # Monkey-patch input so that input does not raise EOFError when # called by pydoc.cli def input(_): # pylint: disable=W0622 """Monkey-patched ...
python
def pydoc_cli_monkey_patched(port): """In Python 3, run pydoc.cli with builtins.input monkey-patched so that pydoc can be run as a process. """ # Monkey-patch input so that input does not raise EOFError when # called by pydoc.cli def input(_): # pylint: disable=W0622 """Monkey-patched ...
['def', 'pydoc_cli_monkey_patched', '(', 'port', ')', ':', '# Monkey-patch input so that input does not raise EOFError when', '# called by pydoc.cli', 'def', 'input', '(', '_', ')', ':', '# pylint: disable=W0622', '"""Monkey-patched version of builtins.input"""', 'while', '1', ':', 'time', '.', 'sleep', '(', '1.0', ')'...
In Python 3, run pydoc.cli with builtins.input monkey-patched so that pydoc can be run as a process.
['In', 'Python', '3', 'run', 'pydoc', '.', 'cli', 'with', 'builtins', '.', 'input', 'monkey', '-', 'patched', 'so', 'that', 'pydoc', 'can', 'be', 'run', 'as', 'a', 'process', '.']
train
https://github.com/etgalloway/newtabmagic/blob/7d5e88654ed7dc564f42d4e6aadb0b6e92d38bd6/newtabmagic.py#L300-L315
5,551
numenta/htmresearch
htmresearch/algorithms/apical_dependent_temporal_memory.py
ApicalDependentTemporalMemory._calculateSegmentActivity
def _calculateSegmentActivity(connections, activeInput, connectedPermanence, activationThreshold, minThreshold, reducedThreshold, reducedThresholdCells = ()): """ Calculate the active and matching basal segments for ...
python
def _calculateSegmentActivity(connections, activeInput, connectedPermanence, activationThreshold, minThreshold, reducedThreshold, reducedThresholdCells = ()): """ Calculate the active and matching basal segments for ...
['def', '_calculateSegmentActivity', '(', 'connections', ',', 'activeInput', ',', 'connectedPermanence', ',', 'activationThreshold', ',', 'minThreshold', ',', 'reducedThreshold', ',', 'reducedThresholdCells', '=', '(', ')', ')', ':', '# Active apical segments lower the activation threshold for basal segments', 'overlap...
Calculate the active and matching basal segments for this timestep. @param connections (SparseMatrixConnections) @param activeInput (numpy array) @return (tuple) - activeSegments (numpy array) Dendrite segments with enough active connected synapses to cause a dendritic spike - matchin...
['Calculate', 'the', 'active', 'and', 'matching', 'basal', 'segments', 'for', 'this', 'timestep', '.']
train
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/algorithms/apical_dependent_temporal_memory.py#L441-L490
5,552
contentful/contentful.py
contentful/errors.py
get_error
def get_error(response): """Gets Error by HTTP Status Code""" errors = { 400: BadRequestError, 401: UnauthorizedError, 403: AccessDeniedError, 404: NotFoundError, 429: RateLimitExceededError, 500: ServerError, 502: BadGatewayError, 503: ServiceUna...
python
def get_error(response): """Gets Error by HTTP Status Code""" errors = { 400: BadRequestError, 401: UnauthorizedError, 403: AccessDeniedError, 404: NotFoundError, 429: RateLimitExceededError, 500: ServerError, 502: BadGatewayError, 503: ServiceUna...
['def', 'get_error', '(', 'response', ')', ':', 'errors', '=', '{', '400', ':', 'BadRequestError', ',', '401', ':', 'UnauthorizedError', ',', '403', ':', 'AccessDeniedError', ',', '404', ':', 'NotFoundError', ',', '429', ':', 'RateLimitExceededError', ',', '500', ':', 'ServerError', ',', '502', ':', 'BadGatewayError', ...
Gets Error by HTTP Status Code
['Gets', 'Error', 'by', 'HTTP', 'Status', 'Code']
train
https://github.com/contentful/contentful.py/blob/73fe01d6ae5a1f8818880da65199107b584681dd/contentful/errors.py#L203-L221
5,553
project-generator/project_generator
project_generator/tools/iar.py
IAREmbeddedWorkbench.build_project
def build_project(self): """ Build IAR project """ # > IarBuild [project_path] -build [project_name] proj_path = join(getcwd(), self.workspace['files']['ewp']) if proj_path.split('.')[-1] != 'ewp': proj_path += '.ewp' if not os.path.exists(proj_path): logg...
python
def build_project(self): """ Build IAR project """ # > IarBuild [project_path] -build [project_name] proj_path = join(getcwd(), self.workspace['files']['ewp']) if proj_path.split('.')[-1] != 'ewp': proj_path += '.ewp' if not os.path.exists(proj_path): logg...
['def', 'build_project', '(', 'self', ')', ':', '# > IarBuild [project_path] -build [project_name]', 'proj_path', '=', 'join', '(', 'getcwd', '(', ')', ',', 'self', '.', 'workspace', '[', "'files'", ']', '[', "'ewp'", ']', ')', 'if', 'proj_path', '.', 'split', '(', "'.'", ')', '[', '-', '1', ']', '!=', "'ewp'", ':', 'p...
Build IAR project
['Build', 'IAR', 'project']
train
https://github.com/project-generator/project_generator/blob/a361be16eeb5a8829ff5cd26850ddd4b264296fe/project_generator/tools/iar.py#L544-L575
5,554
wonambi-python/wonambi
wonambi/trans/math.py
get_descriptives
def get_descriptives(data): """Get mean, SD, and mean and SD of log values. Parameters ---------- data : ndarray Data with segment as first dimension and all other dimensions raveled into second dimension. Returns ------- dict of ndarray each entry is a 1-D vector o...
python
def get_descriptives(data): """Get mean, SD, and mean and SD of log values. Parameters ---------- data : ndarray Data with segment as first dimension and all other dimensions raveled into second dimension. Returns ------- dict of ndarray each entry is a 1-D vector o...
['def', 'get_descriptives', '(', 'data', ')', ':', 'output', '=', '{', '}', 'dat_log', '=', 'log', '(', 'abs', '(', 'data', ')', ')', 'output', '[', "'mean'", ']', '=', 'nanmean', '(', 'data', ',', 'axis', '=', '0', ')', 'output', '[', "'sd'", ']', '=', 'nanstd', '(', 'data', ',', 'axis', '=', '0', ')', 'output', '[', ...
Get mean, SD, and mean and SD of log values. Parameters ---------- data : ndarray Data with segment as first dimension and all other dimensions raveled into second dimension. Returns ------- dict of ndarray each entry is a 1-D vector of descriptives over segment dimensi...
['Get', 'mean', 'SD', 'and', 'mean', 'and', 'SD', 'of', 'log', 'values', '.']
train
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/trans/math.py#L211-L232
5,555
google/prettytensor
prettytensor/recurrent_networks.py
RecurrentResult.flatten
def flatten(self): """Create a flattened version by putting output first and then states.""" ls = [self.output] ls.extend(self.state) return ls
python
def flatten(self): """Create a flattened version by putting output first and then states.""" ls = [self.output] ls.extend(self.state) return ls
['def', 'flatten', '(', 'self', ')', ':', 'ls', '=', '[', 'self', '.', 'output', ']', 'ls', '.', 'extend', '(', 'self', '.', 'state', ')', 'return', 'ls']
Create a flattened version by putting output first and then states.
['Create', 'a', 'flattened', 'version', 'by', 'putting', 'output', 'first', 'and', 'then', 'states', '.']
train
https://github.com/google/prettytensor/blob/75daa0b11252590f548da5647addc0ea610c4c45/prettytensor/recurrent_networks.py#L51-L55
5,556
aiortc/aioice
aioice/ice.py
StunProtocol.send_stun
def send_stun(self, message, addr): """ Send a STUN message. """ self.__log_debug('> %s %s', addr, message) self.transport.sendto(bytes(message), addr)
python
def send_stun(self, message, addr): """ Send a STUN message. """ self.__log_debug('> %s %s', addr, message) self.transport.sendto(bytes(message), addr)
['def', 'send_stun', '(', 'self', ',', 'message', ',', 'addr', ')', ':', 'self', '.', '__log_debug', '(', "'> %s %s'", ',', 'addr', ',', 'message', ')', 'self', '.', 'transport', '.', 'sendto', '(', 'bytes', '(', 'message', ')', ',', 'addr', ')']
Send a STUN message.
['Send', 'a', 'STUN', 'message', '.']
train
https://github.com/aiortc/aioice/blob/a04d810d94ec2d00eca9ce01eacca74b3b086616/aioice/ice.py#L200-L205
5,557
tomislater/RandomWords
random_words/lorem_ipsum.py
LoremIpsum.make_sentence
def make_sentence(list_words): """ Return a sentence from list of words. :param list list_words: list of words :returns: sentence :rtype: str """ lw_len = len(list_words) if lw_len > 6: list_words.insert(lw_len // 2 + random.choice(range(-2, ...
python
def make_sentence(list_words): """ Return a sentence from list of words. :param list list_words: list of words :returns: sentence :rtype: str """ lw_len = len(list_words) if lw_len > 6: list_words.insert(lw_len // 2 + random.choice(range(-2, ...
['def', 'make_sentence', '(', 'list_words', ')', ':', 'lw_len', '=', 'len', '(', 'list_words', ')', 'if', 'lw_len', '>', '6', ':', 'list_words', '.', 'insert', '(', 'lw_len', '//', '2', '+', 'random', '.', 'choice', '(', 'range', '(', '-', '2', ',', '2', ')', ')', ',', "','", ')', 'sentence', '=', "' '", '.', 'join', '...
Return a sentence from list of words. :param list list_words: list of words :returns: sentence :rtype: str
['Return', 'a', 'sentence', 'from', 'list', 'of', 'words', '.']
train
https://github.com/tomislater/RandomWords/blob/601aa48732d3c389f4c17ba0ed98ffe0e4821d78/random_words/lorem_ipsum.py#L62-L77
5,558
watson-developer-cloud/python-sdk
ibm_watson/speech_to_text_v1.py
Corpora._from_dict
def _from_dict(cls, _dict): """Initialize a Corpora object from a json dictionary.""" args = {} if 'corpora' in _dict: args['corpora'] = [ Corpus._from_dict(x) for x in (_dict.get('corpora')) ] else: raise ValueError( 'R...
python
def _from_dict(cls, _dict): """Initialize a Corpora object from a json dictionary.""" args = {} if 'corpora' in _dict: args['corpora'] = [ Corpus._from_dict(x) for x in (_dict.get('corpora')) ] else: raise ValueError( 'R...
['def', '_from_dict', '(', 'cls', ',', '_dict', ')', ':', 'args', '=', '{', '}', 'if', "'corpora'", 'in', '_dict', ':', 'args', '[', "'corpora'", ']', '=', '[', 'Corpus', '.', '_from_dict', '(', 'x', ')', 'for', 'x', 'in', '(', '_dict', '.', 'get', '(', "'corpora'", ')', ')', ']', 'else', ':', 'raise', 'ValueError', '(...
Initialize a Corpora object from a json dictionary.
['Initialize', 'a', 'Corpora', 'object', 'from', 'a', 'json', 'dictionary', '.']
train
https://github.com/watson-developer-cloud/python-sdk/blob/4c2c9df4466fcde88975da9ecd834e6ba95eb353/ibm_watson/speech_to_text_v1.py#L3478-L3488
5,559
kyuupichan/aiorpcX
aiorpcx/curio.py
ignore_after
def ignore_after(seconds, coro=None, *args, timeout_result=None): '''Execute the specified coroutine and return its result. Issue a cancellation request after seconds have elapsed. When a timeout occurs, no exception is raised. Instead, timeout_result is returned. If coro is None, the result is an ...
python
def ignore_after(seconds, coro=None, *args, timeout_result=None): '''Execute the specified coroutine and return its result. Issue a cancellation request after seconds have elapsed. When a timeout occurs, no exception is raised. Instead, timeout_result is returned. If coro is None, the result is an ...
['def', 'ignore_after', '(', 'seconds', ',', 'coro', '=', 'None', ',', '*', 'args', ',', 'timeout_result', '=', 'None', ')', ':', 'if', 'coro', ':', 'return', '_ignore_after_func', '(', 'seconds', ',', 'False', ',', 'coro', ',', 'args', ',', 'timeout_result', ')', 'return', 'TimeoutAfter', '(', 'seconds', ',', 'ignore'...
Execute the specified coroutine and return its result. Issue a cancellation request after seconds have elapsed. When a timeout occurs, no exception is raised. Instead, timeout_result is returned. If coro is None, the result is an asynchronous context manager that applies a timeout to a block of sta...
['Execute', 'the', 'specified', 'coroutine', 'and', 'return', 'its', 'result', '.', 'Issue', 'a', 'cancellation', 'request', 'after', 'seconds', 'have', 'elapsed', '.', 'When', 'a', 'timeout', 'occurs', 'no', 'exception', 'is', 'raised', '.', 'Instead', 'timeout_result', 'is', 'returned', '.']
train
https://github.com/kyuupichan/aiorpcX/blob/707c989ed1c67ac9a40cd20b0161b1ce1f4d7db0/aiorpcx/curio.py#L392-L411
5,560
sporestack/bitcash
bitcash/wallet.py
PrivateKey.get_unspents
def get_unspents(self): """Fetches all available unspent transaction outputs. :rtype: ``list`` of :class:`~bitcash.network.meta.Unspent` """ self.unspents[:] = NetworkAPI.get_unspent(self.address) self.balance = sum(unspent.amount for unspent in self.unspents) return sel...
python
def get_unspents(self): """Fetches all available unspent transaction outputs. :rtype: ``list`` of :class:`~bitcash.network.meta.Unspent` """ self.unspents[:] = NetworkAPI.get_unspent(self.address) self.balance = sum(unspent.amount for unspent in self.unspents) return sel...
['def', 'get_unspents', '(', 'self', ')', ':', 'self', '.', 'unspents', '[', ':', ']', '=', 'NetworkAPI', '.', 'get_unspent', '(', 'self', '.', 'address', ')', 'self', '.', 'balance', '=', 'sum', '(', 'unspent', '.', 'amount', 'for', 'unspent', 'in', 'self', '.', 'unspents', ')', 'return', 'self', '.', 'unspents']
Fetches all available unspent transaction outputs. :rtype: ``list`` of :class:`~bitcash.network.meta.Unspent`
['Fetches', 'all', 'available', 'unspent', 'transaction', 'outputs', '.']
train
https://github.com/sporestack/bitcash/blob/c7a18b9d82af98f1000c456dd06131524c260b7f/bitcash/wallet.py#L191-L198
5,561
mbr/simplekv
simplekv/__init__.py
KeyValueStore._get_filename
def _get_filename(self, key, filename): """Write key to file. Either this method or :meth:`~simplekv.KeyValueStore._get_file` will be called by :meth:`~simplekv.KeyValueStore.get_file`. This method only accepts filenames and will open the file with a mode of ``wb``, then call :me...
python
def _get_filename(self, key, filename): """Write key to file. Either this method or :meth:`~simplekv.KeyValueStore._get_file` will be called by :meth:`~simplekv.KeyValueStore.get_file`. This method only accepts filenames and will open the file with a mode of ``wb``, then call :me...
['def', '_get_filename', '(', 'self', ',', 'key', ',', 'filename', ')', ':', 'with', 'open', '(', 'filename', ',', "'wb'", ')', 'as', 'dest', ':', 'return', 'self', '.', '_get_file', '(', 'key', ',', 'dest', ')']
Write key to file. Either this method or :meth:`~simplekv.KeyValueStore._get_file` will be called by :meth:`~simplekv.KeyValueStore.get_file`. This method only accepts filenames and will open the file with a mode of ``wb``, then call :meth:`~simplekv.KeyValueStore._get_file`. :p...
['Write', 'key', 'to', 'file', '.', 'Either', 'this', 'method', 'or', ':', 'meth', ':', '~simplekv', '.', 'KeyValueStore', '.', '_get_file', 'will', 'be', 'called', 'by', ':', 'meth', ':', '~simplekv', '.', 'KeyValueStore', '.', 'get_file', '.', 'This', 'method', 'only', 'accepts', 'filenames', 'and', 'will', 'open', '...
train
https://github.com/mbr/simplekv/blob/fc46ee0b8ca9b071d6699f3f0f18a8e599a5a2d6/simplekv/__init__.py#L240-L251
5,562
cuihantao/andes
andes/variables/call.py
Call._compile_int_f
def _compile_int_f(self): """Time Domain Simulation - update differential equations""" string = '"""\n' string += 'system.dae.init_f()\n' # evaluate differential equations f for fcall, call in zip(self.fcall, self.fcalls): if fcall: string += call ...
python
def _compile_int_f(self): """Time Domain Simulation - update differential equations""" string = '"""\n' string += 'system.dae.init_f()\n' # evaluate differential equations f for fcall, call in zip(self.fcall, self.fcalls): if fcall: string += call ...
['def', '_compile_int_f', '(', 'self', ')', ':', 'string', '=', '\'"""\\n\'', 'string', '+=', "'system.dae.init_f()\\n'", '# evaluate differential equations f', 'for', 'fcall', ',', 'call', 'in', 'zip', '(', 'self', '.', 'fcall', ',', 'self', '.', 'fcalls', ')', ':', 'if', 'fcall', ':', 'string', '+=', 'call', 'string'...
Time Domain Simulation - update differential equations
['Time', 'Domain', 'Simulation', '-', 'update', 'differential', 'equations']
train
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/variables/call.py#L252-L263
5,563
zyga/python-glibc
pyglibc/select.py
epoll.poll
def poll(self, timeout=-1, maxevents=-1): """ Poll for events :param timeout: The amount of seconds to wait for events before giving up. The default value, -1, represents infinity. Note that unlike the underlying ``epoll_wait()`` timeout is a fractional numbe...
python
def poll(self, timeout=-1, maxevents=-1): """ Poll for events :param timeout: The amount of seconds to wait for events before giving up. The default value, -1, represents infinity. Note that unlike the underlying ``epoll_wait()`` timeout is a fractional numbe...
['def', 'poll', '(', 'self', ',', 'timeout', '=', '-', '1', ',', 'maxevents', '=', '-', '1', ')', ':', 'if', 'self', '.', '_epfd', '<', '0', ':', '_err_closed', '(', ')', 'if', 'timeout', '!=', '-', '1', ':', '# 1000 because epoll_wait(2) uses milliseconds', 'timeout', '=', 'int', '(', 'timeout', '*', '1000', ')', 'if'...
Poll for events :param timeout: The amount of seconds to wait for events before giving up. The default value, -1, represents infinity. Note that unlike the underlying ``epoll_wait()`` timeout is a fractional number representing **seconds**. :param maxeven...
['Poll', 'for', 'events']
train
https://github.com/zyga/python-glibc/blob/d6fdb306b123a995471584a5201155c60a34448a/pyglibc/select.py#L256-L290
5,564
pyroscope/pyrocore
src/pyrocore/torrent/rtorrent.py
RtorrentItem.datapath
def datapath(self): """ Get an item's data path. """ path = self._fields['path'] if not path: # stopped item with no base_dir? path = self.fetch('directory') if path and not self._fields['is_multi_file']: path = os.path.join(path, self._fields['na...
python
def datapath(self): """ Get an item's data path. """ path = self._fields['path'] if not path: # stopped item with no base_dir? path = self.fetch('directory') if path and not self._fields['is_multi_file']: path = os.path.join(path, self._fields['na...
['def', 'datapath', '(', 'self', ')', ':', 'path', '=', 'self', '.', '_fields', '[', "'path'", ']', 'if', 'not', 'path', ':', '# stopped item with no base_dir?', 'path', '=', 'self', '.', 'fetch', '(', "'directory'", ')', 'if', 'path', 'and', 'not', 'self', '.', '_fields', '[', "'is_multi_file'", ']', ':', 'path', '=',...
Get an item's data path.
['Get', 'an', 'item', 's', 'data', 'path', '.']
train
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/torrent/rtorrent.py#L214-L222
5,565
astex/sequential
sequential/decorators.py
after
def after(f, chain=False): """Runs f with the result of the decorated function.""" def decorator(g): @wraps(g) def h(*args, **kargs): if chain: return f(g(*args, **kargs)) else: r = g(*args, **kargs) f(*args, **kargs) ...
python
def after(f, chain=False): """Runs f with the result of the decorated function.""" def decorator(g): @wraps(g) def h(*args, **kargs): if chain: return f(g(*args, **kargs)) else: r = g(*args, **kargs) f(*args, **kargs) ...
['def', 'after', '(', 'f', ',', 'chain', '=', 'False', ')', ':', 'def', 'decorator', '(', 'g', ')', ':', '@', 'wraps', '(', 'g', ')', 'def', 'h', '(', '*', 'args', ',', '*', '*', 'kargs', ')', ':', 'if', 'chain', ':', 'return', 'f', '(', 'g', '(', '*', 'args', ',', '*', '*', 'kargs', ')', ')', 'else', ':', 'r', '=', 'g...
Runs f with the result of the decorated function.
['Runs', 'f', 'with', 'the', 'result', 'of', 'the', 'decorated', 'function', '.']
train
https://github.com/astex/sequential/blob/8812d487c33a8f0f1c96336cd27ad2fa942175f6/sequential/decorators.py#L19-L31
5,566
saltstack/salt
salt/modules/boto_elb.py
get_attributes
def get_attributes(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if attributes are set on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_attributes myelb ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ret...
python
def get_attributes(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if attributes are set on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_attributes myelb ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ret...
['def', 'get_attributes', '(', 'name', ',', 'region', '=', 'None', ',', 'key', '=', 'None', ',', 'keyid', '=', 'None', ',', 'profile', '=', 'None', ')', ':', 'conn', '=', '_get_conn', '(', 'region', '=', 'region', ',', 'key', '=', 'key', ',', 'keyid', '=', 'keyid', ',', 'profile', '=', 'profile', ')', 'retries', '=', '...
Check to see if attributes are set on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_attributes myelb
['Check', 'to', 'see', 'if', 'attributes', 'are', 'set', 'on', 'an', 'ELB', '.']
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_elb.py#L482-L524
5,567
mdickinson/refcycle
refcycle/creators.py
garbage
def garbage(): """ Collect garbage and return an :class:`~refcycle.object_graph.ObjectGraph` based on collected garbage. The collected elements are removed from ``gc.garbage``, but are still kept alive by the references in the graph. Deleting the :class:`~refcycle.object_graph.ObjectGraph` ins...
python
def garbage(): """ Collect garbage and return an :class:`~refcycle.object_graph.ObjectGraph` based on collected garbage. The collected elements are removed from ``gc.garbage``, but are still kept alive by the references in the graph. Deleting the :class:`~refcycle.object_graph.ObjectGraph` ins...
['def', 'garbage', '(', ')', ':', 'with', 'restore_gc_state', '(', ')', ':', 'gc', '.', 'disable', '(', ')', 'gc', '.', 'set_debug', '(', 'gc', '.', 'DEBUG_SAVEALL', ')', 'collected_count', '=', 'gc', '.', 'collect', '(', ')', 'if', 'collected_count', ':', 'objects', '=', 'gc', '.', 'garbage', '[', '-', 'collected_coun...
Collect garbage and return an :class:`~refcycle.object_graph.ObjectGraph` based on collected garbage. The collected elements are removed from ``gc.garbage``, but are still kept alive by the references in the graph. Deleting the :class:`~refcycle.object_graph.ObjectGraph` instance and doing another ...
['Collect', 'garbage', 'and', 'return', 'an', ':', 'class', ':', '~refcycle', '.', 'object_graph', '.', 'ObjectGraph', 'based', 'on', 'collected', 'garbage', '.']
train
https://github.com/mdickinson/refcycle/blob/627fad74c74efc601209c96405f8118cd99b2241/refcycle/creators.py#L56-L76
5,568
bcbio/bcbio-nextgen
bcbio/structural/gatkcnv.py
_seg_to_vcf
def _seg_to_vcf(vals): """Convert GATK CNV calls seg output to a VCF line. """ call_to_cn = {"+": 3, "-": 1} call_to_type = {"+": "DUP", "-": "DEL"} if vals["CALL"] not in ["0"]: info = ["FOLD_CHANGE_LOG=%s" % vals["MEAN_LOG2_COPY_RATIO"], "PROBES=%s" % vals["NUM_POINTS_COPY_...
python
def _seg_to_vcf(vals): """Convert GATK CNV calls seg output to a VCF line. """ call_to_cn = {"+": 3, "-": 1} call_to_type = {"+": "DUP", "-": "DEL"} if vals["CALL"] not in ["0"]: info = ["FOLD_CHANGE_LOG=%s" % vals["MEAN_LOG2_COPY_RATIO"], "PROBES=%s" % vals["NUM_POINTS_COPY_...
['def', '_seg_to_vcf', '(', 'vals', ')', ':', 'call_to_cn', '=', '{', '"+"', ':', '3', ',', '"-"', ':', '1', '}', 'call_to_type', '=', '{', '"+"', ':', '"DUP"', ',', '"-"', ':', '"DEL"', '}', 'if', 'vals', '[', '"CALL"', ']', 'not', 'in', '[', '"0"', ']', ':', 'info', '=', '[', '"FOLD_CHANGE_LOG=%s"', '%', 'vals', '[',...
Convert GATK CNV calls seg output to a VCF line.
['Convert', 'GATK', 'CNV', 'calls', 'seg', 'output', 'to', 'a', 'VCF', 'line', '.']
train
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/gatkcnv.py#L313-L326
5,569
kytos/python-openflow
pyof/foundation/base.py
GenericStruct.pack
def pack(self, value=None): """Pack the struct in a binary representation. Iterate over the class attributes, according to the order of definition, and then convert each attribute to its byte representation using its own ``pack`` method. Returns: bytes: Binary repre...
python
def pack(self, value=None): """Pack the struct in a binary representation. Iterate over the class attributes, according to the order of definition, and then convert each attribute to its byte representation using its own ``pack`` method. Returns: bytes: Binary repre...
['def', 'pack', '(', 'self', ',', 'value', '=', 'None', ')', ':', 'if', 'value', 'is', 'None', ':', 'if', 'not', 'self', '.', 'is_valid', '(', ')', ':', 'error_msg', '=', '"Error on validation prior to pack() on class "', 'error_msg', '+=', '"{}."', '.', 'format', '(', 'type', '(', 'self', ')', '.', '__name__', ')', 'r...
Pack the struct in a binary representation. Iterate over the class attributes, according to the order of definition, and then convert each attribute to its byte representation using its own ``pack`` method. Returns: bytes: Binary representation of the struct object. ...
['Pack', 'the', 'struct', 'in', 'a', 'binary', 'representation', '.']
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/base.py#L666-L702
5,570
radjkarl/imgProcessor
imgProcessor/filters/removeSinglePixels.py
removeSinglePixels
def removeSinglePixels(img): ''' img - boolean array remove all pixels that have no neighbour ''' gx = img.shape[0] gy = img.shape[1] for i in range(gx): for j in range(gy): if img[i, j]: found_neighbour = False for ii in...
python
def removeSinglePixels(img): ''' img - boolean array remove all pixels that have no neighbour ''' gx = img.shape[0] gy = img.shape[1] for i in range(gx): for j in range(gy): if img[i, j]: found_neighbour = False for ii in...
['def', 'removeSinglePixels', '(', 'img', ')', ':', 'gx', '=', 'img', '.', 'shape', '[', '0', ']', 'gy', '=', 'img', '.', 'shape', '[', '1', ']', 'for', 'i', 'in', 'range', '(', 'gx', ')', ':', 'for', 'j', 'in', 'range', '(', 'gy', ')', ':', 'if', 'img', '[', 'i', ',', 'j', ']', ':', 'found_neighbour', '=', 'False', 'f...
img - boolean array remove all pixels that have no neighbour
['img', '-', 'boolean', 'array', 'remove', 'all', 'pixels', 'that', 'have', 'no', 'neighbour']
train
https://github.com/radjkarl/imgProcessor/blob/7c5a28718f81c01a430152c60a686ac50afbfd7c/imgProcessor/filters/removeSinglePixels.py#L5-L33
5,571
hubo1016/vlcp
vlcp/utils/redisclient.py
RedisClient.shutdown
async def shutdown(self, container, force=False): ''' Shutdown all connections. Exclusive connections created by get_connection will shutdown after release() ''' p = self._connpool self._connpool = [] self._shutdown = True if self._defaultconn: p.appen...
python
async def shutdown(self, container, force=False): ''' Shutdown all connections. Exclusive connections created by get_connection will shutdown after release() ''' p = self._connpool self._connpool = [] self._shutdown = True if self._defaultconn: p.appen...
['async', 'def', 'shutdown', '(', 'self', ',', 'container', ',', 'force', '=', 'False', ')', ':', 'p', '=', 'self', '.', '_connpool', 'self', '.', '_connpool', '=', '[', ']', 'self', '.', '_shutdown', '=', 'True', 'if', 'self', '.', '_defaultconn', ':', 'p', '.', 'append', '(', 'self', '.', '_defaultconn', ')', 'self',...
Shutdown all connections. Exclusive connections created by get_connection will shutdown after release()
['Shutdown', 'all', 'connections', '.', 'Exclusive', 'connections', 'created', 'by', 'get_connection', 'will', 'shutdown', 'after', 'release', '()']
train
https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/utils/redisclient.py#L399-L413
5,572
Vital-Fernandez/dazer
bin/lib/Astro_Libraries/old_versions/attributes_declaration.py
gaussian_filter1d_ppxf
def gaussian_filter1d_ppxf(spec, sig): """ Convolve a spectrum by a Gaussian with different sigma for every pixel. If all sigma are the same this routine produces the same output as scipy.ndimage.gaussian_filter1d, except for the border treatment. Here the first/last p pixels are filled with zeros. ...
python
def gaussian_filter1d_ppxf(spec, sig): """ Convolve a spectrum by a Gaussian with different sigma for every pixel. If all sigma are the same this routine produces the same output as scipy.ndimage.gaussian_filter1d, except for the border treatment. Here the first/last p pixels are filled with zeros. ...
['def', 'gaussian_filter1d_ppxf', '(', 'spec', ',', 'sig', ')', ':', 'sig', '=', 'sig', '.', 'clip', '(', '0.01', ')', '# forces zero sigmas to have 0.01 pixels', 'p', '=', 'int', '(', 'np', '.', 'ceil', '(', 'np', '.', 'max', '(', '3', '*', 'sig', ')', ')', ')', 'm', '=', '2', '*', 'p', '+', '1', '# kernel size', 'x2'...
Convolve a spectrum by a Gaussian with different sigma for every pixel. If all sigma are the same this routine produces the same output as scipy.ndimage.gaussian_filter1d, except for the border treatment. Here the first/last p pixels are filled with zeros. When creating a template library for SDSS data,...
['Convolve', 'a', 'spectrum', 'by', 'a', 'Gaussian', 'with', 'different', 'sigma', 'for', 'every', 'pixel', '.', 'If', 'all', 'sigma', 'are', 'the', 'same', 'this', 'routine', 'produces', 'the', 'same', 'output', 'as', 'scipy', '.', 'ndimage', '.', 'gaussian_filter1d', 'except', 'for', 'the', 'border', 'treatment', '.'...
train
https://github.com/Vital-Fernandez/dazer/blob/3c9ae8ae6d40ea33f22cc20dc11365d6d6e65244/bin/lib/Astro_Libraries/old_versions/attributes_declaration.py#L1-L40
5,573
jonathf/chaospy
chaospy/quad/collection/golub_welsch.py
_golbub_welsch
def _golbub_welsch(orders, coeff1, coeff2): """Recurrence coefficients to abscisas and weights.""" abscisas, weights = [], [] for dim, order in enumerate(orders): if order: bands = numpy.zeros((2, order)) bands[0] = coeff1[dim, :order] bands[1, :-1] = numpy.sqrt(...
python
def _golbub_welsch(orders, coeff1, coeff2): """Recurrence coefficients to abscisas and weights.""" abscisas, weights = [], [] for dim, order in enumerate(orders): if order: bands = numpy.zeros((2, order)) bands[0] = coeff1[dim, :order] bands[1, :-1] = numpy.sqrt(...
['def', '_golbub_welsch', '(', 'orders', ',', 'coeff1', ',', 'coeff2', ')', ':', 'abscisas', ',', 'weights', '=', '[', ']', ',', '[', ']', 'for', 'dim', ',', 'order', 'in', 'enumerate', '(', 'orders', ')', ':', 'if', 'order', ':', 'bands', '=', 'numpy', '.', 'zeros', '(', '(', '2', ',', 'order', ')', ')', 'bands', '[',...
Recurrence coefficients to abscisas and weights.
['Recurrence', 'coefficients', 'to', 'abscisas', 'and', 'weights', '.']
train
https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/quad/collection/golub_welsch.py#L150-L170
5,574
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/thread.py
_ThreadContainer._del_thread
def _del_thread(self, dwThreadId): """ Private method to remove a thread object from the snapshot. @type dwThreadId: int @param dwThreadId: Global thread ID. """ try: aThread = self.__threadDict[dwThreadId] del self.__threadDict[dwThreadId] ...
python
def _del_thread(self, dwThreadId): """ Private method to remove a thread object from the snapshot. @type dwThreadId: int @param dwThreadId: Global thread ID. """ try: aThread = self.__threadDict[dwThreadId] del self.__threadDict[dwThreadId] ...
['def', '_del_thread', '(', 'self', ',', 'dwThreadId', ')', ':', 'try', ':', 'aThread', '=', 'self', '.', '__threadDict', '[', 'dwThreadId', ']', 'del', 'self', '.', '__threadDict', '[', 'dwThreadId', ']', 'except', 'KeyError', ':', 'aThread', '=', 'None', 'msg', '=', '"Unknown thread ID %d"', '%', 'dwThreadId', 'warni...
Private method to remove a thread object from the snapshot. @type dwThreadId: int @param dwThreadId: Global thread ID.
['Private', 'method', 'to', 'remove', 'a', 'thread', 'object', 'from', 'the', 'snapshot', '.']
train
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/thread.py#L2026-L2041
5,575
brocade/pynos
pynos/versions/ver_6/ver_6_0_1/yang/brocade_interface_ext.py
brocade_interface_ext.get_vlan_brief_input_request_type_get_request_vlan_id
def get_vlan_brief_input_request_type_get_request_vlan_id(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_vlan_brief = ET.Element("get_vlan_brief") config = get_vlan_brief input = ET.SubElement(get_vlan_brief, "input") request_type = ...
python
def get_vlan_brief_input_request_type_get_request_vlan_id(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_vlan_brief = ET.Element("get_vlan_brief") config = get_vlan_brief input = ET.SubElement(get_vlan_brief, "input") request_type = ...
['def', 'get_vlan_brief_input_request_type_get_request_vlan_id', '(', 'self', ',', '*', '*', 'kwargs', ')', ':', 'config', '=', 'ET', '.', 'Element', '(', '"config"', ')', 'get_vlan_brief', '=', 'ET', '.', 'Element', '(', '"get_vlan_brief"', ')', 'config', '=', 'get_vlan_brief', 'input', '=', 'ET', '.', 'SubElement', '...
Auto Generated Code
['Auto', 'Generated', 'Code']
train
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_interface_ext.py#L12-L25
5,576
Skype4Py/Skype4Py
Skype4Py/application.py
Application.Connect
def Connect(self, Username, WaitConnected=False): """Connects application to user. :Parameters: Username : str Name of the user to connect to. WaitConnected : bool If True, causes the method to wait until the connection is established. :return: If ``...
python
def Connect(self, Username, WaitConnected=False): """Connects application to user. :Parameters: Username : str Name of the user to connect to. WaitConnected : bool If True, causes the method to wait until the connection is established. :return: If ``...
['def', 'Connect', '(', 'self', ',', 'Username', ',', 'WaitConnected', '=', 'False', ')', ':', 'if', 'WaitConnected', ':', 'self', '.', '_Connect_Event', '=', 'threading', '.', 'Event', '(', ')', 'self', '.', '_Connect_Stream', '=', '[', 'None', ']', 'self', '.', '_Connect_Username', '=', 'Username', 'self', '.', '_Con...
Connects application to user. :Parameters: Username : str Name of the user to connect to. WaitConnected : bool If True, causes the method to wait until the connection is established. :return: If ``WaitConnected`` is True, returns the stream which can be used...
['Connects', 'application', 'to', 'user', '.']
train
https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/application.py#L36-L63
5,577
xapple/plumbing
plumbing/common.py
count_string_diff
def count_string_diff(a,b): """Return the number of characters in two strings that don't exactly match""" shortest = min(len(a), len(b)) return sum(a[i] != b[i] for i in range(shortest))
python
def count_string_diff(a,b): """Return the number of characters in two strings that don't exactly match""" shortest = min(len(a), len(b)) return sum(a[i] != b[i] for i in range(shortest))
['def', 'count_string_diff', '(', 'a', ',', 'b', ')', ':', 'shortest', '=', 'min', '(', 'len', '(', 'a', ')', ',', 'len', '(', 'b', ')', ')', 'return', 'sum', '(', 'a', '[', 'i', ']', '!=', 'b', '[', 'i', ']', 'for', 'i', 'in', 'range', '(', 'shortest', ')', ')']
Return the number of characters in two strings that don't exactly match
['Return', 'the', 'number', 'of', 'characters', 'in', 'two', 'strings', 'that', 'don', 't', 'exactly', 'match']
train
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L137-L140
5,578
cltk/cltk
cltk/corpus/utils/importer.py
CorpusImporter._check_distributed_corpora_file
def _check_distributed_corpora_file(self): """Check '~/cltk_data/distributed_corpora.yaml' for any custom, distributed corpora that the user wants to load locally. TODO: write check or try if `cltk_data` dir is not present """ if self.testing: distributed_corpora_fp ...
python
def _check_distributed_corpora_file(self): """Check '~/cltk_data/distributed_corpora.yaml' for any custom, distributed corpora that the user wants to load locally. TODO: write check or try if `cltk_data` dir is not present """ if self.testing: distributed_corpora_fp ...
['def', '_check_distributed_corpora_file', '(', 'self', ')', ':', 'if', 'self', '.', 'testing', ':', 'distributed_corpora_fp', '=', 'os', '.', 'path', '.', 'expanduser', '(', "'~/cltk_data/test_distributed_corpora.yaml'", ')', 'else', ':', 'distributed_corpora_fp', '=', 'os', '.', 'path', '.', 'expanduser', '(', "'~/cl...
Check '~/cltk_data/distributed_corpora.yaml' for any custom, distributed corpora that the user wants to load locally. TODO: write check or try if `cltk_data` dir is not present
['Check', '~', '/', 'cltk_data', '/', 'distributed_corpora', '.', 'yaml', 'for', 'any', 'custom', 'distributed', 'corpora', 'that', 'the', 'user', 'wants', 'to', 'load', 'locally', '.']
train
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/corpus/utils/importer.py#L143-L176
5,579
mfcloud/python-zvm-sdk
smtLayer/generalUtils.py
parseCmdline
def parseCmdline(rh, posOpsList, keyOpsList): """ Parse the request command input. Input: Request Handle Positional Operands List. This is a dictionary that contains an array for each subfunction. The array contains a entry (itself an array) for each positional operand. ...
python
def parseCmdline(rh, posOpsList, keyOpsList): """ Parse the request command input. Input: Request Handle Positional Operands List. This is a dictionary that contains an array for each subfunction. The array contains a entry (itself an array) for each positional operand. ...
['def', 'parseCmdline', '(', 'rh', ',', 'posOpsList', ',', 'keyOpsList', ')', ':', 'rh', '.', 'printSysLog', '(', '"Enter generalUtils.parseCmdline"', ')', '# Handle any positional operands on the line.', 'if', 'rh', '.', 'results', '[', "'overallRC'", ']', '==', '0', 'and', 'rh', '.', 'subfunction', 'in', 'posOpsList'...
Parse the request command input. Input: Request Handle Positional Operands List. This is a dictionary that contains an array for each subfunction. The array contains a entry (itself an array) for each positional operand. That array contains: - Human readable name of t...
['Parse', 'the', 'request', 'command', 'input', '.']
train
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/smtLayer/generalUtils.py#L186-L336
5,580
collectiveacuity/labPack
labpack/platforms/aws/ec2.py
ec2Client.create_instance
def create_instance(self, image_id, pem_file, group_ids, instance_type, volume_type='gp2', ebs_optimized=False, instance_monitoring=False, iam_profile='', tag_list=None, auction_bid=0.0): ''' a method for starting an instance on AWS EC2 :param image_id: string with aws id of im...
python
def create_instance(self, image_id, pem_file, group_ids, instance_type, volume_type='gp2', ebs_optimized=False, instance_monitoring=False, iam_profile='', tag_list=None, auction_bid=0.0): ''' a method for starting an instance on AWS EC2 :param image_id: string with aws id of im...
['def', 'create_instance', '(', 'self', ',', 'image_id', ',', 'pem_file', ',', 'group_ids', ',', 'instance_type', ',', 'volume_type', '=', "'gp2'", ',', 'ebs_optimized', '=', 'False', ',', 'instance_monitoring', '=', 'False', ',', 'iam_profile', '=', "''", ',', 'tag_list', '=', 'None', ',', 'auction_bid', '=', '0.0', '...
a method for starting an instance on AWS EC2 :param image_id: string with aws id of image for instance :param pem_file: string with path to pem file to access image :param group_ids: list with aws id of security group(s) to attach to instance :param instance_type: string wi...
['a', 'method', 'for', 'starting', 'an', 'instance', 'on', 'AWS', 'EC2', ':', 'param', 'image_id', ':', 'string', 'with', 'aws', 'id', 'of', 'image', 'for', 'instance', ':', 'param', 'pem_file', ':', 'string', 'with', 'path', 'to', 'pem', 'file', 'to', 'access', 'image', ':', 'param', 'group_ids', ':', 'list', 'with', ...
train
https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/platforms/aws/ec2.py#L454-L611
5,581
pytroll/posttroll
posttroll/publisher.py
Publisher.stop
def stop(self): """Stop the publisher. """ self.publish.setsockopt(zmq.LINGER, 1) self.publish.close() return self
python
def stop(self): """Stop the publisher. """ self.publish.setsockopt(zmq.LINGER, 1) self.publish.close() return self
['def', 'stop', '(', 'self', ')', ':', 'self', '.', 'publish', '.', 'setsockopt', '(', 'zmq', '.', 'LINGER', ',', '1', ')', 'self', '.', 'publish', '.', 'close', '(', ')', 'return', 'self']
Stop the publisher.
['Stop', 'the', 'publisher', '.']
train
https://github.com/pytroll/posttroll/blob/8e811a0544b5182c4a72aed074b2ff8c4324e94d/posttroll/publisher.py#L126-L131
5,582
AndrewAnnex/SpiceyPy
spiceypy/utils/support_types.py
cVectorToPython
def cVectorToPython(x): """ Convert the c vector data into the correct python data type (numpy arrays or strings) :param x: :return: """ if isinstance(x[0], bool): return numpy.frombuffer(x, dtype=numpy.bool).copy() elif isinstance(x[0], int): return numpy.frombuffer(x, d...
python
def cVectorToPython(x): """ Convert the c vector data into the correct python data type (numpy arrays or strings) :param x: :return: """ if isinstance(x[0], bool): return numpy.frombuffer(x, dtype=numpy.bool).copy() elif isinstance(x[0], int): return numpy.frombuffer(x, d...
['def', 'cVectorToPython', '(', 'x', ')', ':', 'if', 'isinstance', '(', 'x', '[', '0', ']', ',', 'bool', ')', ':', 'return', 'numpy', '.', 'frombuffer', '(', 'x', ',', 'dtype', '=', 'numpy', '.', 'bool', ')', '.', 'copy', '(', ')', 'elif', 'isinstance', '(', 'x', '[', '0', ']', ',', 'int', ')', ':', 'return', 'numpy', ...
Convert the c vector data into the correct python data type (numpy arrays or strings) :param x: :return:
['Convert', 'the', 'c', 'vector', 'data', 'into', 'the', 'correct', 'python', 'data', 'type', '(', 'numpy', 'arrays', 'or', 'strings', ')', ':', 'param', 'x', ':', ':', 'return', ':']
train
https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/utils/support_types.py#L154-L168
5,583
alejandroautalan/pygubu
pygubu/builder/builderobject.py
BuilderObject._get_init_args
def _get_init_args(self): """Creates dict with properties marked as readonly""" args = {} for rop in self.ro_properties: if rop in self.properties: args[rop] = self.properties[rop] return args
python
def _get_init_args(self): """Creates dict with properties marked as readonly""" args = {} for rop in self.ro_properties: if rop in self.properties: args[rop] = self.properties[rop] return args
['def', '_get_init_args', '(', 'self', ')', ':', 'args', '=', '{', '}', 'for', 'rop', 'in', 'self', '.', 'ro_properties', ':', 'if', 'rop', 'in', 'self', '.', 'properties', ':', 'args', '[', 'rop', ']', '=', 'self', '.', 'properties', '[', 'rop', ']', 'return', 'args']
Creates dict with properties marked as readonly
['Creates', 'dict', 'with', 'properties', 'marked', 'as', 'readonly']
train
https://github.com/alejandroautalan/pygubu/blob/41c8fb37ef973736ec5d68cbe1cd4ecb78712e40/pygubu/builder/builderobject.py#L86-L93
5,584
log2timeline/plaso
plaso/containers/events.py
EventTag.CopyToDict
def CopyToDict(self): """Copies the event tag to a dictionary. Returns: dict[str, object]: event tag attributes. """ result_dict = { 'labels': self.labels } if self.comment: result_dict['comment'] = self.comment return result_dict
python
def CopyToDict(self): """Copies the event tag to a dictionary. Returns: dict[str, object]: event tag attributes. """ result_dict = { 'labels': self.labels } if self.comment: result_dict['comment'] = self.comment return result_dict
['def', 'CopyToDict', '(', 'self', ')', ':', 'result_dict', '=', '{', "'labels'", ':', 'self', '.', 'labels', '}', 'if', 'self', '.', 'comment', ':', 'result_dict', '[', "'comment'", ']', '=', 'self', '.', 'comment', 'return', 'result_dict']
Copies the event tag to a dictionary. Returns: dict[str, object]: event tag attributes.
['Copies', 'the', 'event', 'tag', 'to', 'a', 'dictionary', '.']
train
https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/containers/events.py#L205-L217
5,585
saltstack/salt
salt/modules/mac_keychain.py
install
def install(cert, password, keychain="/Library/Keychains/System.keychain", allow_any=False, keychain_password=None): ''' Install a certificate cert The certificate to install password The password for the certificate being installed forma...
python
def install(cert, password, keychain="/Library/Keychains/System.keychain", allow_any=False, keychain_password=None): ''' Install a certificate cert The certificate to install password The password for the certificate being installed forma...
['def', 'install', '(', 'cert', ',', 'password', ',', 'keychain', '=', '"/Library/Keychains/System.keychain"', ',', 'allow_any', '=', 'False', ',', 'keychain_password', '=', 'None', ')', ':', 'if', 'keychain_password', 'is', 'not', 'None', ':', 'unlock_keychain', '(', 'keychain', ',', 'keychain_password', ')', 'cmd', '...
Install a certificate cert The certificate to install password The password for the certificate being installed formatted in the way described for openssl command in the PASS PHRASE ARGUMENTS section. Note: The password given here will show up as plaintext in the job returned ...
['Install', 'a', 'certificate']
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_keychain.py#L44-L88
5,586
wonambi-python/wonambi
wonambi/attr/annotations.py
Annotations.event_types
def event_types(self): """ Raises ------ IndexError When there is no selected rater """ try: events = self.rater.find('events') except AttributeError: raise IndexError('You need to have at least one rater') return [x.ge...
python
def event_types(self): """ Raises ------ IndexError When there is no selected rater """ try: events = self.rater.find('events') except AttributeError: raise IndexError('You need to have at least one rater') return [x.ge...
['def', 'event_types', '(', 'self', ')', ':', 'try', ':', 'events', '=', 'self', '.', 'rater', '.', 'find', '(', "'events'", ')', 'except', 'AttributeError', ':', 'raise', 'IndexError', '(', "'You need to have at least one rater'", ')', 'return', '[', 'x', '.', 'get', '(', "'type'", ')', 'for', 'x', 'in', 'events', ']'...
Raises ------ IndexError When there is no selected rater
['Raises', '------', 'IndexError', 'When', 'there', 'is', 'no', 'selected', 'rater']
train
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/attr/annotations.py#L757-L769
5,587
bspaans/python-mingus
mingus/extra/fft.py
find_frequencies
def find_frequencies(data, freq=44100, bits=16): """Convert audio data into a frequency-amplitude table using fast fourier transformation. Return a list of tuples (frequency, amplitude). Data should only contain one channel of audio. """ # Fast fourier transform n = len(data) p = _fft(...
python
def find_frequencies(data, freq=44100, bits=16): """Convert audio data into a frequency-amplitude table using fast fourier transformation. Return a list of tuples (frequency, amplitude). Data should only contain one channel of audio. """ # Fast fourier transform n = len(data) p = _fft(...
['def', 'find_frequencies', '(', 'data', ',', 'freq', '=', '44100', ',', 'bits', '=', '16', ')', ':', '# Fast fourier transform', 'n', '=', 'len', '(', 'data', ')', 'p', '=', '_fft', '(', 'data', ')', 'uniquePts', '=', 'numpy', '.', 'ceil', '(', '(', 'n', '+', '1', ')', '/', '2.0', ')', '# Scale by the length (n) and s...
Convert audio data into a frequency-amplitude table using fast fourier transformation. Return a list of tuples (frequency, amplitude). Data should only contain one channel of audio.
['Convert', 'audio', 'data', 'into', 'a', 'frequency', '-', 'amplitude', 'table', 'using', 'fast', 'fourier', 'transformation', '.']
train
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/fft.py#L85-L107
5,588
django-danceschool/django-danceschool
danceschool/private_lessons/handlers.py
finalizePrivateLessonRegistration
def finalizePrivateLessonRegistration(sender,**kwargs): ''' Once a private lesson registration is finalized, mark the slots that were used to book the private lesson as booked and associate them with the final registration. No need to notify students in this instance because they are already r...
python
def finalizePrivateLessonRegistration(sender,**kwargs): ''' Once a private lesson registration is finalized, mark the slots that were used to book the private lesson as booked and associate them with the final registration. No need to notify students in this instance because they are already r...
['def', 'finalizePrivateLessonRegistration', '(', 'sender', ',', '*', '*', 'kwargs', ')', ':', 'finalReg', '=', 'kwargs', '.', 'pop', '(', "'registration'", ')', 'for', 'er', 'in', 'finalReg', '.', 'eventregistration_set', '.', 'filter', '(', 'event__privatelessonevent__isnull', '=', 'False', ')', ':', 'er', '.', 'even...
Once a private lesson registration is finalized, mark the slots that were used to book the private lesson as booked and associate them with the final registration. No need to notify students in this instance because they are already receiving a notification of their registration.
['Once', 'a', 'private', 'lesson', 'registration', 'is', 'finalized', 'mark', 'the', 'slots', 'that', 'were', 'used', 'to', 'book', 'the', 'private', 'lesson', 'as', 'booked', 'and', 'associate', 'them', 'with', 'the', 'final', 'registration', '.', 'No', 'need', 'to', 'notify', 'students', 'in', 'this', 'instance', 'be...
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/private_lessons/handlers.py#L6-L19
5,589
pvlib/pvlib-python
pvlib/irradiance.py
_delta_kt_prime_dirint
def _delta_kt_prime_dirint(kt_prime, use_delta_kt_prime, times): """ Calculate delta_kt_prime (Perez eqn 2 and eqn 3), or return a default value for use with :py:func:`_dirint_bins`. """ if use_delta_kt_prime: # Perez eqn 2 kt_next = kt_prime.shift(-1) kt_previous = kt_prime....
python
def _delta_kt_prime_dirint(kt_prime, use_delta_kt_prime, times): """ Calculate delta_kt_prime (Perez eqn 2 and eqn 3), or return a default value for use with :py:func:`_dirint_bins`. """ if use_delta_kt_prime: # Perez eqn 2 kt_next = kt_prime.shift(-1) kt_previous = kt_prime....
['def', '_delta_kt_prime_dirint', '(', 'kt_prime', ',', 'use_delta_kt_prime', ',', 'times', ')', ':', 'if', 'use_delta_kt_prime', ':', '# Perez eqn 2', 'kt_next', '=', 'kt_prime', '.', 'shift', '(', '-', '1', ')', 'kt_previous', '=', 'kt_prime', '.', 'shift', '(', '1', ')', '# replace nan with values that implement Per...
Calculate delta_kt_prime (Perez eqn 2 and eqn 3), or return a default value for use with :py:func:`_dirint_bins`.
['Calculate', 'delta_kt_prime', '(', 'Perez', 'eqn', '2', 'and', 'eqn', '3', ')', 'or', 'return', 'a', 'default', 'value', 'for', 'use', 'with', ':', 'py', ':', 'func', ':', '_dirint_bins', '.']
train
https://github.com/pvlib/pvlib-python/blob/2e844a595b820b43d1170269781fa66bd0ccc8a3/pvlib/irradiance.py#L1604-L1623
5,590
T-002/pycast
pycast/methods/exponentialsmoothing.py
HoltWintersMethod.initSeasonFactors
def initSeasonFactors(self, timeSeries): """ Computes the initial season smoothing factors. :return: Returns a list of season vectors of length "seasonLength". :rtype: list """ seasonLength = self.get_parameter("seasonLength") try: seasonValues = self.get...
python
def initSeasonFactors(self, timeSeries): """ Computes the initial season smoothing factors. :return: Returns a list of season vectors of length "seasonLength". :rtype: list """ seasonLength = self.get_parameter("seasonLength") try: seasonValues = self.get...
['def', 'initSeasonFactors', '(', 'self', ',', 'timeSeries', ')', ':', 'seasonLength', '=', 'self', '.', 'get_parameter', '(', '"seasonLength"', ')', 'try', ':', 'seasonValues', '=', 'self', '.', 'get_parameter', '(', '"seasonValues"', ')', 'assert', 'seasonLength', '==', 'len', '(', 'seasonValues', ')', ',', '"Preset ...
Computes the initial season smoothing factors. :return: Returns a list of season vectors of length "seasonLength". :rtype: list
['Computes', 'the', 'initial', 'season', 'smoothing', 'factors', '.']
train
https://github.com/T-002/pycast/blob/8a53505c6d8367e0ea572e8af768e80b29e1cc41/pycast/methods/exponentialsmoothing.py#L424-L451
5,591
apple/turicreate
src/unity/python/turicreate/data_structures/sframe.py
SFrame.apply
def apply(self, fn, dtype=None, seed=None): """ Transform each row to an :class:`~turicreate.SArray` according to a specified function. Returns a new SArray of ``dtype`` where each element in this SArray is transformed by `fn(x)` where `x` is a single row in the sframe represente...
python
def apply(self, fn, dtype=None, seed=None): """ Transform each row to an :class:`~turicreate.SArray` according to a specified function. Returns a new SArray of ``dtype`` where each element in this SArray is transformed by `fn(x)` where `x` is a single row in the sframe represente...
['def', 'apply', '(', 'self', ',', 'fn', ',', 'dtype', '=', 'None', ',', 'seed', '=', 'None', ')', ':', 'assert', 'callable', '(', 'fn', ')', ',', '"Input must be callable"', 'test_sf', '=', 'self', '[', ':', '10', ']', 'dryrun', '=', '[', 'fn', '(', 'row', ')', 'for', 'row', 'in', 'test_sf', ']', 'if', 'dtype', 'is', ...
Transform each row to an :class:`~turicreate.SArray` according to a specified function. Returns a new SArray of ``dtype`` where each element in this SArray is transformed by `fn(x)` where `x` is a single row in the sframe represented as a dictionary. The ``fn`` should return exactly one...
['Transform', 'each', 'row', 'to', 'an', ':', 'class', ':', '~turicreate', '.', 'SArray', 'according', 'to', 'a', 'specified', 'function', '.', 'Returns', 'a', 'new', 'SArray', 'of', 'dtype', 'where', 'each', 'element', 'in', 'this', 'SArray', 'is', 'transformed', 'by', 'fn', '(', 'x', ')', 'where', 'x', 'is', 'a', 'si...
train
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sframe.py#L2434-L2500
5,592
saltstack/salt
salt/sdb/consul.py
get_conn
def get_conn(profile): ''' Return a client object for accessing consul ''' params = {} for key in ('host', 'port', 'token', 'scheme', 'consistency', 'dc', 'verify'): if key in profile: params[key] = profile[key] if HAS_CONSUL: return consul.Consul(**params) else:...
python
def get_conn(profile): ''' Return a client object for accessing consul ''' params = {} for key in ('host', 'port', 'token', 'scheme', 'consistency', 'dc', 'verify'): if key in profile: params[key] = profile[key] if HAS_CONSUL: return consul.Consul(**params) else:...
['def', 'get_conn', '(', 'profile', ')', ':', 'params', '=', '{', '}', 'for', 'key', 'in', '(', "'host'", ',', "'port'", ',', "'token'", ',', "'scheme'", ',', "'consistency'", ',', "'dc'", ',', "'verify'", ')', ':', 'if', 'key', 'in', 'profile', ':', 'params', '[', 'key', ']', '=', 'profile', '[', 'key', ']', 'if', 'HA...
Return a client object for accessing consul
['Return', 'a', 'client', 'object', 'for', 'accessing', 'consul']
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/sdb/consul.py#L66-L81
5,593
apache/incubator-mxnet
python/mxnet/ndarray/ndarray.py
_get_indexing_dispatch_code
def _get_indexing_dispatch_code(key): """Returns a dispatch code for calling basic or advanced indexing functions.""" if isinstance(key, (NDArray, np.ndarray)): return _NDARRAY_ADVANCED_INDEXING elif isinstance(key, list): # TODO(junwu): Add support for nested lists besides integer list ...
python
def _get_indexing_dispatch_code(key): """Returns a dispatch code for calling basic or advanced indexing functions.""" if isinstance(key, (NDArray, np.ndarray)): return _NDARRAY_ADVANCED_INDEXING elif isinstance(key, list): # TODO(junwu): Add support for nested lists besides integer list ...
['def', '_get_indexing_dispatch_code', '(', 'key', ')', ':', 'if', 'isinstance', '(', 'key', ',', '(', 'NDArray', ',', 'np', '.', 'ndarray', ')', ')', ':', 'return', '_NDARRAY_ADVANCED_INDEXING', 'elif', 'isinstance', '(', 'key', ',', 'list', ')', ':', '# TODO(junwu): Add support for nested lists besides integer list',...
Returns a dispatch code for calling basic or advanced indexing functions.
['Returns', 'a', 'dispatch', 'code', 'for', 'calling', 'basic', 'or', 'advanced', 'indexing', 'functions', '.']
train
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/ndarray/ndarray.py#L2278-L2301
5,594
docker/docker-py
docker/models/containers.py
Container.attach_socket
def attach_socket(self, **kwargs): """ Like :py:meth:`attach`, but returns the underlying socket-like object for the HTTP request. Args: params (dict): Dictionary of request parameters (e.g. ``stdout``, ``stderr``, ``stream``). ws (bool): Use webs...
python
def attach_socket(self, **kwargs): """ Like :py:meth:`attach`, but returns the underlying socket-like object for the HTTP request. Args: params (dict): Dictionary of request parameters (e.g. ``stdout``, ``stderr``, ``stream``). ws (bool): Use webs...
['def', 'attach_socket', '(', 'self', ',', '*', '*', 'kwargs', ')', ':', 'return', 'self', '.', 'client', '.', 'api', '.', 'attach_socket', '(', 'self', '.', 'id', ',', '*', '*', 'kwargs', ')']
Like :py:meth:`attach`, but returns the underlying socket-like object for the HTTP request. Args: params (dict): Dictionary of request parameters (e.g. ``stdout``, ``stderr``, ``stream``). ws (bool): Use websockets instead of raw HTTP. Raises: ...
['Like', ':', 'py', ':', 'meth', ':', 'attach', 'but', 'returns', 'the', 'underlying', 'socket', '-', 'like', 'object', 'for', 'the', 'HTTP', 'request', '.']
train
https://github.com/docker/docker-py/blob/613d6aad83acc9931ff2ecfd6a6c7bd8061dc125/docker/models/containers.py#L98-L112
5,595
f3at/feat
src/feat/common/run.py
wait_for_term
def wait_for_term(): """ Wait until we get killed by a TERM signal (from someone else). """ class Waiter: def __init__(self): self.sleeping = True import signal #@Reimport self.oldhandler = signal.signal(signal.SIGTERM, ...
python
def wait_for_term(): """ Wait until we get killed by a TERM signal (from someone else). """ class Waiter: def __init__(self): self.sleeping = True import signal #@Reimport self.oldhandler = signal.signal(signal.SIGTERM, ...
['def', 'wait_for_term', '(', ')', ':', 'class', 'Waiter', ':', 'def', '__init__', '(', 'self', ')', ':', 'self', '.', 'sleeping', '=', 'True', 'import', 'signal', '#@Reimport', 'self', '.', 'oldhandler', '=', 'signal', '.', 'signal', '(', 'signal', '.', 'SIGTERM', ',', 'self', '.', '_SIGTERMHandler', ')', 'def', '_SIG...
Wait until we get killed by a TERM signal (from someone else).
['Wait', 'until', 'we', 'get', 'killed', 'by', 'a', 'TERM', 'signal', '(', 'from', 'someone', 'else', ')', '.']
train
https://github.com/f3at/feat/blob/15da93fc9d6ec8154f52a9172824e25821195ef8/src/feat/common/run.py#L210-L231
5,596
inveniosoftware/invenio-pidstore
invenio_pidstore/models.py
PersistentIdentifier.redirect
def redirect(self, pid): """Redirect persistent identifier to another persistent identifier. :param pid: The :class:`invenio_pidstore.models.PersistentIdentifier` where redirect the PID. :raises invenio_pidstore.errors.PIDInvalidAction: If the PID is not registered or is...
python
def redirect(self, pid): """Redirect persistent identifier to another persistent identifier. :param pid: The :class:`invenio_pidstore.models.PersistentIdentifier` where redirect the PID. :raises invenio_pidstore.errors.PIDInvalidAction: If the PID is not registered or is...
['def', 'redirect', '(', 'self', ',', 'pid', ')', ':', 'if', 'not', '(', 'self', '.', 'is_registered', '(', ')', 'or', 'self', '.', 'is_redirected', '(', ')', ')', ':', 'raise', 'PIDInvalidAction', '(', '"Persistent identifier is not registered."', ')', 'try', ':', 'with', 'db', '.', 'session', '.', 'begin_nested', '('...
Redirect persistent identifier to another persistent identifier. :param pid: The :class:`invenio_pidstore.models.PersistentIdentifier` where redirect the PID. :raises invenio_pidstore.errors.PIDInvalidAction: If the PID is not registered or is not already redirecting to another ...
['Redirect', 'persistent', 'identifier', 'to', 'another', 'persistent', 'identifier', '.']
train
https://github.com/inveniosoftware/invenio-pidstore/blob/8bf35f4e62d5dcaf1a2cfe5803245ba5220a9b78/invenio_pidstore/models.py#L331-L366
5,597
secdev/scapy
scapy/layers/tls/crypto/cipher_block.py
_BlockCipher.encrypt
def encrypt(self, data): """ Encrypt the data. Also, update the cipher iv. This is needed for SSLv3 and TLS 1.0. For TLS 1.1/1.2, it is overwritten in TLS.post_build(). """ if False in six.itervalues(self.ready): raise CipherError(data) encryptor = self._ciphe...
python
def encrypt(self, data): """ Encrypt the data. Also, update the cipher iv. This is needed for SSLv3 and TLS 1.0. For TLS 1.1/1.2, it is overwritten in TLS.post_build(). """ if False in six.itervalues(self.ready): raise CipherError(data) encryptor = self._ciphe...
['def', 'encrypt', '(', 'self', ',', 'data', ')', ':', 'if', 'False', 'in', 'six', '.', 'itervalues', '(', 'self', '.', 'ready', ')', ':', 'raise', 'CipherError', '(', 'data', ')', 'encryptor', '=', 'self', '.', '_cipher', '.', 'encryptor', '(', ')', 'tmp', '=', 'encryptor', '.', 'update', '(', 'data', ')', '+', 'encry...
Encrypt the data. Also, update the cipher iv. This is needed for SSLv3 and TLS 1.0. For TLS 1.1/1.2, it is overwritten in TLS.post_build().
['Encrypt', 'the', 'data', '.', 'Also', 'update', 'the', 'cipher', 'iv', '.', 'This', 'is', 'needed', 'for', 'SSLv3', 'and', 'TLS', '1', '.', '0', '.', 'For', 'TLS', '1', '.', '1', '/', '1', '.', '2', 'it', 'is', 'overwritten', 'in', 'TLS', '.', 'post_build', '()', '.']
train
https://github.com/secdev/scapy/blob/3ffe757c184017dd46464593a8f80f85abc1e79a/scapy/layers/tls/crypto/cipher_block.py#L77-L87
5,598
marshmallow-code/webargs
examples/schema_example.py
use_schema
def use_schema(schema, list_view=False, locations=None): """View decorator for using a marshmallow schema to (1) parse a request's input and (2) serializing the view's output to a JSON response. """ def decorator(func): @functools.wraps(func) def wrapped(*args, **kwargs): ...
python
def use_schema(schema, list_view=False, locations=None): """View decorator for using a marshmallow schema to (1) parse a request's input and (2) serializing the view's output to a JSON response. """ def decorator(func): @functools.wraps(func) def wrapped(*args, **kwargs): ...
['def', 'use_schema', '(', 'schema', ',', 'list_view', '=', 'False', ',', 'locations', '=', 'None', ')', ':', 'def', 'decorator', '(', 'func', ')', ':', '@', 'functools', '.', 'wraps', '(', 'func', ')', 'def', 'wrapped', '(', '*', 'args', ',', '*', '*', 'kwargs', ')', ':', 'use_args_wrapper', '=', 'parser', '.', 'use_a...
View decorator for using a marshmallow schema to (1) parse a request's input and (2) serializing the view's output to a JSON response.
['View', 'decorator', 'for', 'using', 'a', 'marshmallow', 'schema', 'to', '(', '1', ')', 'parse', 'a', 'request', 's', 'input', 'and', '(', '2', ')', 'serializing', 'the', 'view', 's', 'output', 'to', 'a', 'JSON', 'response', '.']
train
https://github.com/marshmallow-code/webargs/blob/40cc2d25421d15d9630b1a819f1dcefbbf01ed95/examples/schema_example.py#L62-L80
5,599
saltstack/salt
salt/runners/net.py
_find_interfaces_ip
def _find_interfaces_ip(mac): ''' Helper to search the interfaces IPs using the MAC address. ''' try: mac = napalm_helpers.convert(napalm_helpers.mac, mac) except AddrFormatError: return ('', '', []) all_interfaces = _get_mine('net.interfaces') all_ipaddrs = _get_mine('net.i...
python
def _find_interfaces_ip(mac): ''' Helper to search the interfaces IPs using the MAC address. ''' try: mac = napalm_helpers.convert(napalm_helpers.mac, mac) except AddrFormatError: return ('', '', []) all_interfaces = _get_mine('net.interfaces') all_ipaddrs = _get_mine('net.i...
['def', '_find_interfaces_ip', '(', 'mac', ')', ':', 'try', ':', 'mac', '=', 'napalm_helpers', '.', 'convert', '(', 'napalm_helpers', '.', 'mac', ',', 'mac', ')', 'except', 'AddrFormatError', ':', 'return', '(', "''", ',', "''", ',', '[', ']', ')', 'all_interfaces', '=', '_get_mine', '(', "'net.interfaces'", ')', 'all_...
Helper to search the interfaces IPs using the MAC address.
['Helper', 'to', 'search', 'the', 'interfaces', 'IPs', 'using', 'the', 'MAC', 'address', '.']
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/net.py#L183-L213