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
7,500
cloudera/cm_api
python/src/cm_api/endpoints/services.py
ApiService.disable_jt_ha
def disable_jt_ha(self, active_name): """ Disable high availability for a MR JobTracker active-standby pair. @param active_name: name of the JobTracker that will be active after the disable operation. The other JobTracker and Failover Controllers will be remo...
python
def disable_jt_ha(self, active_name): """ Disable high availability for a MR JobTracker active-standby pair. @param active_name: name of the JobTracker that will be active after the disable operation. The other JobTracker and Failover Controllers will be remo...
['def', 'disable_jt_ha', '(', 'self', ',', 'active_name', ')', ':', 'args', '=', 'dict', '(', 'activeName', '=', 'active_name', ',', ')', 'return', 'self', '.', '_cmd', '(', "'disableJtHa'", ',', 'data', '=', 'args', ')']
Disable high availability for a MR JobTracker active-standby pair. @param active_name: name of the JobTracker that will be active after the disable operation. The other JobTracker and Failover Controllers will be removed. @return: Reference to the submitted comma...
['Disable', 'high', 'availability', 'for', 'a', 'MR', 'JobTracker', 'active', '-', 'standby', 'pair', '.']
train
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/src/cm_api/endpoints/services.py#L1102-L1114
7,501
pazz/urwidtrees
urwidtrees/widgets.py
TreeBox.focus_next_sibling
def focus_next_sibling(self): """move focus to next sibling of currently focussed one""" w, focuspos = self.get_focus() sib = self._tree.next_sibling_position(focuspos) if sib is not None: self.set_focus(sib)
python
def focus_next_sibling(self): """move focus to next sibling of currently focussed one""" w, focuspos = self.get_focus() sib = self._tree.next_sibling_position(focuspos) if sib is not None: self.set_focus(sib)
['def', 'focus_next_sibling', '(', 'self', ')', ':', 'w', ',', 'focuspos', '=', 'self', '.', 'get_focus', '(', ')', 'sib', '=', 'self', '.', '_tree', '.', 'next_sibling_position', '(', 'focuspos', ')', 'if', 'sib', 'is', 'not', 'None', ':', 'self', '.', 'set_focus', '(', 'sib', ')']
move focus to next sibling of currently focussed one
['move', 'focus', 'to', 'next', 'sibling', 'of', 'currently', 'focussed', 'one']
train
https://github.com/pazz/urwidtrees/blob/d1fa38ce4f37db00bdfc574b856023b5db4c7ead/urwidtrees/widgets.py#L219-L224
7,502
aacanakin/glim
glim/command.py
CommandAdapter.retrieve_commands
def retrieve_commands(self, module): """ Function smartly imports Command type classes given module Args ---- module (module): The module which Command classes will be extracted from Returns ------- commands (list): A list of ...
python
def retrieve_commands(self, module): """ Function smartly imports Command type classes given module Args ---- module (module): The module which Command classes will be extracted from Returns ------- commands (list): A list of ...
['def', 'retrieve_commands', '(', 'self', ',', 'module', ')', ':', 'commands', '=', '[', ']', 'for', 'name', ',', 'obj', 'in', 'inspect', '.', 'getmembers', '(', 'module', ')', ':', 'if', 'name', '!=', "'Command'", 'and', "'Command'", 'in', 'name', ':', 'if', 'name', '!=', "'GlimCommand'", ':', 'cobject', '=', 'getattr...
Function smartly imports Command type classes given module Args ---- module (module): The module which Command classes will be extracted from Returns ------- commands (list): A list of Command instances Note: This function ...
['Function', 'smartly', 'imports', 'Command', 'type', 'classes', 'given', 'module']
train
https://github.com/aacanakin/glim/blob/71a20ac149a1292c0d6c1dc7414985ea51854f7a/glim/command.py#L33-L62
7,503
iotile/coretools
iotilegateway/iotilegateway/device.py
AggregatingDeviceAdapter.disconnect
async def disconnect(self, conn_id): """Disconnect from a connected device. See :meth:`AbstractDeviceAdapter.disconnect`. """ adapter_id = self._get_property(conn_id, 'adapter') await self.adapters[adapter_id].disconnect(conn_id) self._teardown_connection(conn_id)
python
async def disconnect(self, conn_id): """Disconnect from a connected device. See :meth:`AbstractDeviceAdapter.disconnect`. """ adapter_id = self._get_property(conn_id, 'adapter') await self.adapters[adapter_id].disconnect(conn_id) self._teardown_connection(conn_id)
['async', 'def', 'disconnect', '(', 'self', ',', 'conn_id', ')', ':', 'adapter_id', '=', 'self', '.', '_get_property', '(', 'conn_id', ',', "'adapter'", ')', 'await', 'self', '.', 'adapters', '[', 'adapter_id', ']', '.', 'disconnect', '(', 'conn_id', ')', 'self', '.', '_teardown_connection', '(', 'conn_id', ')']
Disconnect from a connected device. See :meth:`AbstractDeviceAdapter.disconnect`.
['Disconnect', 'from', 'a', 'connected', 'device', '.']
train
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/device.py#L245-L254
7,504
yamcs/yamcs-python
yamcs-client/yamcs/client.py
YamcsClient.create_event_subscription
def create_event_subscription(self, instance, on_data, timeout=60): """ Create a new subscription for receiving events of an instance. This method returns a future, then returns immediately. Stop the subscription by canceling the future. :param str instance: A Yamcs instance na...
python
def create_event_subscription(self, instance, on_data, timeout=60): """ Create a new subscription for receiving events of an instance. This method returns a future, then returns immediately. Stop the subscription by canceling the future. :param str instance: A Yamcs instance na...
['def', 'create_event_subscription', '(', 'self', ',', 'instance', ',', 'on_data', ',', 'timeout', '=', '60', ')', ':', 'manager', '=', 'WebSocketSubscriptionManager', '(', 'self', ',', 'resource', '=', "'events'", ')', '# Represent subscription as a future', 'subscription', '=', 'WebSocketSubscriptionFuture', '(', 'ma...
Create a new subscription for receiving events of an instance. This method returns a future, then returns immediately. Stop the subscription by canceling the future. :param str instance: A Yamcs instance name :param on_data: Function that gets called on each :class:`.Event`. :...
['Create', 'a', 'new', 'subscription', 'for', 'receiving', 'events', 'of', 'an', 'instance', '.']
train
https://github.com/yamcs/yamcs-python/blob/1082fee8a299010cc44416bbb7518fac0ef08b48/yamcs-client/yamcs/client.py#L556-L589
7,505
zhmcclient/python-zhmcclient
zhmcclient_mock/_hmc.py
FakedMetricsContext.get_metric_group_infos
def get_metric_group_infos(self): """ Get the faked metric group definitions for this context object that are to be returned from its create operation, in the format needed for the "Create Metrics Context" operation response. Returns: "metric-group-infos" JSON object ...
python
def get_metric_group_infos(self): """ Get the faked metric group definitions for this context object that are to be returned from its create operation, in the format needed for the "Create Metrics Context" operation response. Returns: "metric-group-infos" JSON object ...
['def', 'get_metric_group_infos', '(', 'self', ')', ':', 'mg_defs', '=', 'self', '.', 'get_metric_group_definitions', '(', ')', 'mg_infos', '=', '[', ']', 'for', 'mg_def', 'in', 'mg_defs', ':', 'metric_infos', '=', '[', ']', 'for', 'metric_name', ',', 'metric_type', 'in', 'mg_def', '.', 'types', ':', 'metric_infos', '....
Get the faked metric group definitions for this context object that are to be returned from its create operation, in the format needed for the "Create Metrics Context" operation response. Returns: "metric-group-infos" JSON object as described for the "Create Metrics Conte...
['Get', 'the', 'faked', 'metric', 'group', 'definitions', 'for', 'this', 'context', 'object', 'that', 'are', 'to', 'be', 'returned', 'from', 'its', 'create', 'operation', 'in', 'the', 'format', 'needed', 'for', 'the', 'Create', 'Metrics', 'Context', 'operation', 'response', '.']
train
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient_mock/_hmc.py#L3022-L3047
7,506
kodexlab/reliure
reliure/web.py
EngineView.add_output
def add_output(self, out_name, type_or_serialize=None, **kwargs): """ Declare an output """ if out_name not in self.engine.all_outputs(): raise ValueError("'%s' is not generated by the engine %s" % (out_name, self.engine.all_outputs())) if type_or_serialize is None: ...
python
def add_output(self, out_name, type_or_serialize=None, **kwargs): """ Declare an output """ if out_name not in self.engine.all_outputs(): raise ValueError("'%s' is not generated by the engine %s" % (out_name, self.engine.all_outputs())) if type_or_serialize is None: ...
['def', 'add_output', '(', 'self', ',', 'out_name', ',', 'type_or_serialize', '=', 'None', ',', '*', '*', 'kwargs', ')', ':', 'if', 'out_name', 'not', 'in', 'self', '.', 'engine', '.', 'all_outputs', '(', ')', ':', 'raise', 'ValueError', '(', '"\'%s\' is not generated by the engine %s"', '%', '(', 'out_name', ',', 'sel...
Declare an output
['Declare', 'an', 'output']
train
https://github.com/kodexlab/reliure/blob/0450c7a9254c5c003162738458bbe0c49e777ba5/reliure/web.py#L115-L130
7,507
googlefonts/fontbakery
Lib/fontbakery/profiles/googlefonts.py
com_google_fonts_check_metadata_canonical_weight_value
def com_google_fonts_check_metadata_canonical_weight_value(font_metadata): """METADATA.pb: Check that font weight has a canonical value.""" first_digit = font_metadata.weight / 100 if (font_metadata.weight % 100) != 0 or \ (first_digit < 1 or first_digit > 9): yield FAIL, ("METADATA.pb: The weight is decl...
python
def com_google_fonts_check_metadata_canonical_weight_value(font_metadata): """METADATA.pb: Check that font weight has a canonical value.""" first_digit = font_metadata.weight / 100 if (font_metadata.weight % 100) != 0 or \ (first_digit < 1 or first_digit > 9): yield FAIL, ("METADATA.pb: The weight is decl...
['def', 'com_google_fonts_check_metadata_canonical_weight_value', '(', 'font_metadata', ')', ':', 'first_digit', '=', 'font_metadata', '.', 'weight', '/', '100', 'if', '(', 'font_metadata', '.', 'weight', '%', '100', ')', '!=', '0', 'or', '(', 'first_digit', '<', '1', 'or', 'first_digit', '>', '9', ')', ':', 'yield', '...
METADATA.pb: Check that font weight has a canonical value.
['METADATA', '.', 'pb', ':', 'Check', 'that', 'font', 'weight', 'has', 'a', 'canonical', 'value', '.']
train
https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L2198-L2208
7,508
dagwieers/vmguestlib
vmguestlib.py
VMGuestLib.GetMemActiveMB
def GetMemActiveMB(self): '''Retrieves the amount of memory the virtual machine is actively using its estimated working set size.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetMemActiveMB(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGue...
python
def GetMemActiveMB(self): '''Retrieves the amount of memory the virtual machine is actively using its estimated working set size.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetMemActiveMB(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGue...
['def', 'GetMemActiveMB', '(', 'self', ')', ':', 'counter', '=', 'c_uint', '(', ')', 'ret', '=', 'vmGuestLib', '.', 'VMGuestLib_GetMemActiveMB', '(', 'self', '.', 'handle', '.', 'value', ',', 'byref', '(', 'counter', ')', ')', 'if', 'ret', '!=', 'VMGUESTLIB_ERROR_SUCCESS', ':', 'raise', 'VMGuestLibException', '(', 'ret...
Retrieves the amount of memory the virtual machine is actively using its estimated working set size.
['Retrieves', 'the', 'amount', 'of', 'memory', 'the', 'virtual', 'machine', 'is', 'actively', 'using', 'its', 'estimated', 'working', 'set', 'size', '.']
train
https://github.com/dagwieers/vmguestlib/blob/2ba9333a745628cf9e6b4c767427a5bd997a71ad/vmguestlib.py#L307-L313
7,509
limpyd/redis-limpyd-extensions
limpyd_extensions/dynamic/related.py
DynamicRelatedFieldMixin.get_name_for
def get_name_for(self, dynamic_part): """ Return the name for the current dynamic field, accepting a limpyd instance for the dynamic part """ dynamic_part = self.from_python(dynamic_part) return super(DynamicRelatedFieldMixin, self).get_name_for(dynamic_part)
python
def get_name_for(self, dynamic_part): """ Return the name for the current dynamic field, accepting a limpyd instance for the dynamic part """ dynamic_part = self.from_python(dynamic_part) return super(DynamicRelatedFieldMixin, self).get_name_for(dynamic_part)
['def', 'get_name_for', '(', 'self', ',', 'dynamic_part', ')', ':', 'dynamic_part', '=', 'self', '.', 'from_python', '(', 'dynamic_part', ')', 'return', 'super', '(', 'DynamicRelatedFieldMixin', ',', 'self', ')', '.', 'get_name_for', '(', 'dynamic_part', ')']
Return the name for the current dynamic field, accepting a limpyd instance for the dynamic part
['Return', 'the', 'name', 'for', 'the', 'current', 'dynamic', 'field', 'accepting', 'a', 'limpyd', 'instance', 'for', 'the', 'dynamic', 'part']
train
https://github.com/limpyd/redis-limpyd-extensions/blob/13f34e39efd2f802761457da30ab2a4213b63934/limpyd_extensions/dynamic/related.py#L67-L73
7,510
twilio/twilio-python
twilio/rest/__init__.py
Client.accounts
def accounts(self): """ Access the Accounts Twilio Domain :returns: Accounts Twilio Domain :rtype: twilio.rest.accounts.Accounts """ if self._accounts is None: from twilio.rest.accounts import Accounts self._accounts = Accounts(self) retur...
python
def accounts(self): """ Access the Accounts Twilio Domain :returns: Accounts Twilio Domain :rtype: twilio.rest.accounts.Accounts """ if self._accounts is None: from twilio.rest.accounts import Accounts self._accounts = Accounts(self) retur...
['def', 'accounts', '(', 'self', ')', ':', 'if', 'self', '.', '_accounts', 'is', 'None', ':', 'from', 'twilio', '.', 'rest', '.', 'accounts', 'import', 'Accounts', 'self', '.', '_accounts', '=', 'Accounts', '(', 'self', ')', 'return', 'self', '.', '_accounts']
Access the Accounts Twilio Domain :returns: Accounts Twilio Domain :rtype: twilio.rest.accounts.Accounts
['Access', 'the', 'Accounts', 'Twilio', 'Domain']
train
https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/__init__.py#L133-L143
7,511
corpusops/pdbclone
lib/pdb_clone/pdb.py
Pdb.do_break
def do_break(self, arg, temporary = 0): """b(reak) [ ([filename:]lineno | function) [, condition] ] Without argument, list all breaks. With a line number argument, set a break at this line in the current file. With a function name, set a break at the first executable line of th...
python
def do_break(self, arg, temporary = 0): """b(reak) [ ([filename:]lineno | function) [, condition] ] Without argument, list all breaks. With a line number argument, set a break at this line in the current file. With a function name, set a break at the first executable line of th...
['def', 'do_break', '(', 'self', ',', 'arg', ',', 'temporary', '=', '0', ')', ':', 'if', 'not', 'arg', ':', 'all_breaks', '=', "'\\n'", '.', 'join', '(', 'bp', '.', 'bpformat', '(', ')', 'for', 'bp', 'in', 'bdb', '.', 'Breakpoint', '.', 'bpbynumber', 'if', 'bp', ')', 'if', 'all_breaks', ':', 'self', '.', 'message', '('...
b(reak) [ ([filename:]lineno | function) [, condition] ] Without argument, list all breaks. With a line number argument, set a break at this line in the current file. With a function name, set a break at the first executable line of that function. If a second argument is prese...
['b', '(', 'reak', ')', '[', '(', '[', 'filename', ':', ']', 'lineno', '|', 'function', ')', '[', 'condition', ']', ']', 'Without', 'argument', 'list', 'all', 'breaks', '.']
train
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/pdb.py#L894-L970
7,512
ray-project/ray
python/ray/worker.py
register_custom_serializer
def register_custom_serializer(cls, use_pickle=False, use_dict=False, serializer=None, deserializer=None, local=False, driver_id=None,...
python
def register_custom_serializer(cls, use_pickle=False, use_dict=False, serializer=None, deserializer=None, local=False, driver_id=None,...
['def', 'register_custom_serializer', '(', 'cls', ',', 'use_pickle', '=', 'False', ',', 'use_dict', '=', 'False', ',', 'serializer', '=', 'None', ',', 'deserializer', '=', 'None', ',', 'local', '=', 'False', ',', 'driver_id', '=', 'None', ',', 'class_id', '=', 'None', ')', ':', 'worker', '=', 'global_worker', 'assert',...
Enable serialization and deserialization for a particular class. This method runs the register_class function defined below on every worker, which will enable ray to properly serialize and deserialize objects of this class. Args: cls (type): The class that ray should use this custom serializer...
['Enable', 'serialization', 'and', 'deserialization', 'for', 'a', 'particular', 'class', '.']
train
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/worker.py#L2048-L2148
7,513
fr33jc/bang
bang/providers/aws.py
EC2.find_servers
def find_servers(self, tags, running=True): """ Returns any servers in the region that have tags that match the key-value pairs in :attr:`tags`. :param Mapping tags: A mapping object in which the keys are the tag names and the values are the tag values. :param bool...
python
def find_servers(self, tags, running=True): """ Returns any servers in the region that have tags that match the key-value pairs in :attr:`tags`. :param Mapping tags: A mapping object in which the keys are the tag names and the values are the tag values. :param bool...
['def', 'find_servers', '(', 'self', ',', 'tags', ',', 'running', '=', 'True', ')', ':', 'filters', '=', 'dict', '(', '[', '(', "'tag:%s'", '%', 'key', ',', 'val', ')', 'for', 'key', ',', 'val', 'in', 'tags', '.', 'items', '(', ')', ']', ')', 'if', 'running', ':', 'filters', '[', "'instance-state-name'", ']', '=', "'ru...
Returns any servers in the region that have tags that match the key-value pairs in :attr:`tags`. :param Mapping tags: A mapping object in which the keys are the tag names and the values are the tag values. :param bool running: A flag to limit server list to instances that are ...
['Returns', 'any', 'servers', 'in', 'the', 'region', 'that', 'have', 'tags', 'that', 'match', 'the', 'key', '-', 'value', 'pairs', 'in', ':', 'attr', ':', 'tags', '.']
train
https://github.com/fr33jc/bang/blob/8f000713f88d2a9a8c1193b63ca10a6578560c16/bang/providers/aws.py#L133-L155
7,514
abnerjacobsen/tinydb-jsonorm
src/tinydb_jsonorm/cuid.py
_pad
def _pad(string, size): """ 'Pad' a string with leading zeroes to fit the given size, truncating if necessary. """ strlen = len(string) if strlen == size: return string if strlen < size: return _padding[0:size-strlen] + string return string[-size:]
python
def _pad(string, size): """ 'Pad' a string with leading zeroes to fit the given size, truncating if necessary. """ strlen = len(string) if strlen == size: return string if strlen < size: return _padding[0:size-strlen] + string return string[-size:]
['def', '_pad', '(', 'string', ',', 'size', ')', ':', 'strlen', '=', 'len', '(', 'string', ')', 'if', 'strlen', '==', 'size', ':', 'return', 'string', 'if', 'strlen', '<', 'size', ':', 'return', '_padding', '[', '0', ':', 'size', '-', 'strlen', ']', '+', 'string', 'return', 'string', '[', '-', 'size', ':', ']']
'Pad' a string with leading zeroes to fit the given size, truncating if necessary.
['Pad', 'a', 'string', 'with', 'leading', 'zeroes', 'to', 'fit', 'the', 'given', 'size', 'truncating', 'if', 'necessary', '.']
train
https://github.com/abnerjacobsen/tinydb-jsonorm/blob/704d3f887cc8963769ffbb116eb7e6909deeaecd/src/tinydb_jsonorm/cuid.py#L38-L48
7,515
brutasse/rache
rache/__init__.py
schedule_job
def schedule_job(job_id, schedule_in, connection=None, **kwargs): """Schedules a job. :param job_id: unique identifier for this job :param schedule_in: number of seconds from now in which to schedule the job or timedelta object. :param **kwargs: parameters to attach to the job, key-value structure...
python
def schedule_job(job_id, schedule_in, connection=None, **kwargs): """Schedules a job. :param job_id: unique identifier for this job :param schedule_in: number of seconds from now in which to schedule the job or timedelta object. :param **kwargs: parameters to attach to the job, key-value structure...
['def', 'schedule_job', '(', 'job_id', ',', 'schedule_in', ',', 'connection', '=', 'None', ',', '*', '*', 'kwargs', ')', ':', 'if', 'not', 'isinstance', '(', 'schedule_in', ',', 'int', ')', ':', '# assumed to be a timedelta', 'schedule_in', '=', 'schedule_in', '.', 'days', '*', '3600', '*', '24', '+', 'schedule_in', '....
Schedules a job. :param job_id: unique identifier for this job :param schedule_in: number of seconds from now in which to schedule the job or timedelta object. :param **kwargs: parameters to attach to the job, key-value structure. >>> schedule_job('http://example.com/test', schedule_in=10, num_re...
['Schedules', 'a', 'job', '.']
train
https://github.com/brutasse/rache/blob/fa9cf073376a8c731a13924b84fb8422a771a4ab/rache/__init__.py#L48-L87
7,516
facelessuser/bracex
bracex/__init__.py
ExpandBrace.get_escape
def get_escape(self, c, i): """Get an escape.""" try: escaped = next(i) except StopIteration: escaped = '' return c + escaped if self.keep_escapes else escaped
python
def get_escape(self, c, i): """Get an escape.""" try: escaped = next(i) except StopIteration: escaped = '' return c + escaped if self.keep_escapes else escaped
['def', 'get_escape', '(', 'self', ',', 'c', ',', 'i', ')', ':', 'try', ':', 'escaped', '=', 'next', '(', 'i', ')', 'except', 'StopIteration', ':', 'escaped', '=', "''", 'return', 'c', '+', 'escaped', 'if', 'self', '.', 'keep_escapes', 'else', 'escaped']
Get an escape.
['Get', 'an', 'escape', '.']
train
https://github.com/facelessuser/bracex/blob/1fdf83e2bdfb939e78ba9966bcef80cd7a5c8534/bracex/__init__.py#L159-L166
7,517
aio-libs/yarl
yarl/__init__.py
URL.is_default_port
def is_default_port(self): """A check for default port. Return True if port is default for specified scheme, e.g. 'http://python.org' or 'http://python.org:80', False otherwise. """ if self.port is None: return False default = DEFAULT_PORTS.get(self....
python
def is_default_port(self): """A check for default port. Return True if port is default for specified scheme, e.g. 'http://python.org' or 'http://python.org:80', False otherwise. """ if self.port is None: return False default = DEFAULT_PORTS.get(self....
['def', 'is_default_port', '(', 'self', ')', ':', 'if', 'self', '.', 'port', 'is', 'None', ':', 'return', 'False', 'default', '=', 'DEFAULT_PORTS', '.', 'get', '(', 'self', '.', 'scheme', ')', 'if', 'default', 'is', 'None', ':', 'return', 'False', 'return', 'self', '.', 'port', '==', 'default']
A check for default port. Return True if port is default for specified scheme, e.g. 'http://python.org' or 'http://python.org:80', False otherwise.
['A', 'check', 'for', 'default', 'port', '.']
train
https://github.com/aio-libs/yarl/blob/e47da02c00ad764e030ca7647a9565548c97d362/yarl/__init__.py#L332-L345
7,518
googlemaps/google-maps-services-python
googlemaps/geocoding.py
reverse_geocode
def reverse_geocode(client, latlng, result_type=None, location_type=None, language=None): """ Reverse geocoding is the process of converting geographic coordinates into a human-readable address. :param latlng: The latitude/longitude value or place_id for which you wish to ob...
python
def reverse_geocode(client, latlng, result_type=None, location_type=None, language=None): """ Reverse geocoding is the process of converting geographic coordinates into a human-readable address. :param latlng: The latitude/longitude value or place_id for which you wish to ob...
['def', 'reverse_geocode', '(', 'client', ',', 'latlng', ',', 'result_type', '=', 'None', ',', 'location_type', '=', 'None', ',', 'language', '=', 'None', ')', ':', '# Check if latlng param is a place_id string.', '# place_id strings do not contain commas; latlng strings do.', 'if', 'convert', '.', 'is_string', '(', '...
Reverse geocoding is the process of converting geographic coordinates into a human-readable address. :param latlng: The latitude/longitude value or place_id for which you wish to obtain the closest, human-readable address. :type latlng: string, dict, list, or tuple :param result_type: One or m...
['Reverse', 'geocoding', 'is', 'the', 'process', 'of', 'converting', 'geographic', 'coordinates', 'into', 'a', 'human', '-', 'readable', 'address', '.']
train
https://github.com/googlemaps/google-maps-services-python/blob/7ed40b4d8df63479794c46ce29d03ed6083071d7/googlemaps/geocoding.py#L71-L109
7,519
tkf/rash
rash/daemon.py
daemon_run
def daemon_run(no_error, restart, record_path, keep_json, check_duplicate, use_polling, log_level): """ Run RASH index daemon. This daemon watches the directory ``~/.config/rash/data/record`` and translate the JSON files dumped by ``record`` command into sqlite3 DB at ``~/.config/ras...
python
def daemon_run(no_error, restart, record_path, keep_json, check_duplicate, use_polling, log_level): """ Run RASH index daemon. This daemon watches the directory ``~/.config/rash/data/record`` and translate the JSON files dumped by ``record`` command into sqlite3 DB at ``~/.config/ras...
['def', 'daemon_run', '(', 'no_error', ',', 'restart', ',', 'record_path', ',', 'keep_json', ',', 'check_duplicate', ',', 'use_polling', ',', 'log_level', ')', ':', '# Probably it makes sense to use this daemon to provide search', '# API, so that this daemon is going to be the only process that', '# is connected to the...
Run RASH index daemon. This daemon watches the directory ``~/.config/rash/data/record`` and translate the JSON files dumped by ``record`` command into sqlite3 DB at ``~/.config/rash/data/db.sqlite``. ``rash init`` will start RASH automatically by default. But there are alternative ways to start da...
['Run', 'RASH', 'index', 'daemon', '.']
train
https://github.com/tkf/rash/blob/585da418ec37dd138f1a4277718b6f507e9536a2/rash/daemon.py#L20-L107
7,520
QuantEcon/QuantEcon.py
quantecon/optimize/root_finding.py
bisect
def bisect(f, a, b, args=(), xtol=_xtol, rtol=_rtol, maxiter=_iter, disp=True): """ Find root of a function within an interval adapted from Scipy's bisect. Basic bisection routine to find a zero of the function `f` between the arguments `a` and `b`. `f(a)` and `f(b)` cannot have the same sig...
python
def bisect(f, a, b, args=(), xtol=_xtol, rtol=_rtol, maxiter=_iter, disp=True): """ Find root of a function within an interval adapted from Scipy's bisect. Basic bisection routine to find a zero of the function `f` between the arguments `a` and `b`. `f(a)` and `f(b)` cannot have the same sig...
['def', 'bisect', '(', 'f', ',', 'a', ',', 'b', ',', 'args', '=', '(', ')', ',', 'xtol', '=', '_xtol', ',', 'rtol', '=', '_rtol', ',', 'maxiter', '=', '_iter', ',', 'disp', '=', 'True', ')', ':', 'if', 'xtol', '<=', '0', ':', 'raise', 'ValueError', '(', '"xtol is too small (<= 0)"', ')', 'if', 'maxiter', '<', '1', ':',...
Find root of a function within an interval adapted from Scipy's bisect. Basic bisection routine to find a zero of the function `f` between the arguments `a` and `b`. `f(a)` and `f(b)` cannot have the same signs. `f` must be jitted via numba. Parameters ---------- f : jitted and callable ...
['Find', 'root', 'of', 'a', 'function', 'within', 'an', 'interval', 'adapted', 'from', 'Scipy', 's', 'bisect', '.']
train
https://github.com/QuantEcon/QuantEcon.py/blob/26a66c552f2a73967d7efb6e1f4b4c4985a12643/quantecon/optimize/root_finding.py#L297-L374
7,521
LudovicRousseau/pyscard
smartcard/wx/ReaderToolbar.py
ReaderComboBox.update
def update(self, observable, handlers): """Toolbar ReaderObserver callback that is notified when readers are added or removed.""" addedreaders, removedreaders = handlers for reader in addedreaders: item = self.Append(str(reader)) self.SetClientData(item, reader) ...
python
def update(self, observable, handlers): """Toolbar ReaderObserver callback that is notified when readers are added or removed.""" addedreaders, removedreaders = handlers for reader in addedreaders: item = self.Append(str(reader)) self.SetClientData(item, reader) ...
['def', 'update', '(', 'self', ',', 'observable', ',', 'handlers', ')', ':', 'addedreaders', ',', 'removedreaders', '=', 'handlers', 'for', 'reader', 'in', 'addedreaders', ':', 'item', '=', 'self', '.', 'Append', '(', 'str', '(', 'reader', ')', ')', 'self', '.', 'SetClientData', '(', 'item', ',', 'reader', ')', 'for', ...
Toolbar ReaderObserver callback that is notified when readers are added or removed.
['Toolbar', 'ReaderObserver', 'callback', 'that', 'is', 'notified', 'when', 'readers', 'are', 'added', 'or', 'removed', '.']
train
https://github.com/LudovicRousseau/pyscard/blob/62e675028086c75656444cc21d563d9f08ebf8e7/smartcard/wx/ReaderToolbar.py#L45-L56
7,522
ultrabug/py3status
py3status/formatter.py
Block.render
def render(self, get_params, module, _if=None): """ render the block and return the output. """ enough = False output = [] valid = None if self.commands.show: valid = True if self.parent and self.commands.soft and _if is None: retu...
python
def render(self, get_params, module, _if=None): """ render the block and return the output. """ enough = False output = [] valid = None if self.commands.show: valid = True if self.parent and self.commands.soft and _if is None: retu...
['def', 'render', '(', 'self', ',', 'get_params', ',', 'module', ',', '_if', '=', 'None', ')', ':', 'enough', '=', 'False', 'output', '=', '[', ']', 'valid', '=', 'None', 'if', 'self', '.', 'commands', '.', 'show', ':', 'valid', '=', 'True', 'if', 'self', '.', 'parent', 'and', 'self', '.', 'commands', '.', 'soft', 'and...
render the block and return the output.
['render', 'the', 'block', 'and', 'return', 'the', 'output', '.']
train
https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/formatter.py#L591-L723
7,523
materialsproject/pymatgen
pymatgen/io/abinit/tasks.py
AbinitTask.temp_shell_task
def temp_shell_task(cls, inp, mpi_procs=1, workdir=None, manager=None): """ Build a Task with a temporary workdir. The task is executed via the shell with 1 MPI proc. Mainly used for invoking Abinit to get important parameters needed to prepare the real task. Args: mpi_procs...
python
def temp_shell_task(cls, inp, mpi_procs=1, workdir=None, manager=None): """ Build a Task with a temporary workdir. The task is executed via the shell with 1 MPI proc. Mainly used for invoking Abinit to get important parameters needed to prepare the real task. Args: mpi_procs...
['def', 'temp_shell_task', '(', 'cls', ',', 'inp', ',', 'mpi_procs', '=', '1', ',', 'workdir', '=', 'None', ',', 'manager', '=', 'None', ')', ':', '# Build a simple manager to run the job in a shell subprocess', 'import', 'tempfile', 'workdir', '=', 'tempfile', '.', 'mkdtemp', '(', ')', 'if', 'workdir', 'is', 'None', '...
Build a Task with a temporary workdir. The task is executed via the shell with 1 MPI proc. Mainly used for invoking Abinit to get important parameters needed to prepare the real task. Args: mpi_procs: Number of MPI processes to use.
['Build', 'a', 'Task', 'with', 'a', 'temporary', 'workdir', '.', 'The', 'task', 'is', 'executed', 'via', 'the', 'shell', 'with', '1', 'MPI', 'proc', '.', 'Mainly', 'used', 'for', 'invoking', 'Abinit', 'to', 'get', 'important', 'parameters', 'needed', 'to', 'prepare', 'the', 'real', 'task', '.']
train
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/abinit/tasks.py#L2608-L2624
7,524
jepegit/cellpy
cellpy/readers/cellreader.py
CellpyData.set_mass
def set_mass(self, masses, dataset_number=None, validated=None): """Sets the mass (masses) for the test (datasets). """ self._set_run_attribute("mass", masses, dataset_number=dataset_number, validated=validated)
python
def set_mass(self, masses, dataset_number=None, validated=None): """Sets the mass (masses) for the test (datasets). """ self._set_run_attribute("mass", masses, dataset_number=dataset_number, validated=validated)
['def', 'set_mass', '(', 'self', ',', 'masses', ',', 'dataset_number', '=', 'None', ',', 'validated', '=', 'None', ')', ':', 'self', '.', '_set_run_attribute', '(', '"mass"', ',', 'masses', ',', 'dataset_number', '=', 'dataset_number', ',', 'validated', '=', 'validated', ')']
Sets the mass (masses) for the test (datasets).
['Sets', 'the', 'mass', '(', 'masses', ')', 'for', 'the', 'test', '(', 'datasets', ')', '.']
train
https://github.com/jepegit/cellpy/blob/9f4a84cdd11f72cfa02cda8c2d7b5174abbb7370/cellpy/readers/cellreader.py#L3186-L3190
7,525
mvcisback/py-aiger-bv
aigerbv/common.py
kmodels
def kmodels(wordlen: int, k: int, input=None, output=None): """Return a circuit taking a wordlen bitvector where only k valuations return True. Uses encoding from [1]. Note that this is equivalent to (~x < k). - TODO: Add automated simplification so that the circuits are equiv. [1]: Ch...
python
def kmodels(wordlen: int, k: int, input=None, output=None): """Return a circuit taking a wordlen bitvector where only k valuations return True. Uses encoding from [1]. Note that this is equivalent to (~x < k). - TODO: Add automated simplification so that the circuits are equiv. [1]: Ch...
['def', 'kmodels', '(', 'wordlen', ':', 'int', ',', 'k', ':', 'int', ',', 'input', '=', 'None', ',', 'output', '=', 'None', ')', ':', 'assert', '0', '<=', 'k', '<', '2', '**', 'wordlen', 'if', 'output', 'is', 'None', ':', 'output', '=', '_fresh', '(', ')', 'if', 'input', 'is', 'None', ':', 'input', '=', '_fresh', '(', ...
Return a circuit taking a wordlen bitvector where only k valuations return True. Uses encoding from [1]. Note that this is equivalent to (~x < k). - TODO: Add automated simplification so that the circuits are equiv. [1]: Chakraborty, Supratik, et al. "From Weighted to Unweighted Model ...
['Return', 'a', 'circuit', 'taking', 'a', 'wordlen', 'bitvector', 'where', 'only', 'k', 'valuations', 'return', 'True', '.', 'Uses', 'encoding', 'from', '[', '1', ']', '.']
train
https://github.com/mvcisback/py-aiger-bv/blob/855819844c429c35cdd8dc0b134bcd11f7b2fda3/aigerbv/common.py#L430-L464
7,526
a1ezzz/wasp-general
wasp_general/network/web/cookies.py
WHTTPCookieJar.import_simple_cookie
def import_simple_cookie(cls, simple_cookie): """ Create cookie jar from SimpleCookie object :param simple_cookie: cookies to import :return: WHTTPCookieJar """ cookie_jar = WHTTPCookieJar() for cookie_name in simple_cookie.keys(): cookie_attrs = {} for attr_name in WHTTPCookie.cookie_attr_value_comp...
python
def import_simple_cookie(cls, simple_cookie): """ Create cookie jar from SimpleCookie object :param simple_cookie: cookies to import :return: WHTTPCookieJar """ cookie_jar = WHTTPCookieJar() for cookie_name in simple_cookie.keys(): cookie_attrs = {} for attr_name in WHTTPCookie.cookie_attr_value_comp...
['def', 'import_simple_cookie', '(', 'cls', ',', 'simple_cookie', ')', ':', 'cookie_jar', '=', 'WHTTPCookieJar', '(', ')', 'for', 'cookie_name', 'in', 'simple_cookie', '.', 'keys', '(', ')', ':', 'cookie_attrs', '=', '{', '}', 'for', 'attr_name', 'in', 'WHTTPCookie', '.', 'cookie_attr_value_compliance', '.', 'keys', '(...
Create cookie jar from SimpleCookie object :param simple_cookie: cookies to import :return: WHTTPCookieJar
['Create', 'cookie', 'jar', 'from', 'SimpleCookie', 'object']
train
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/web/cookies.py#L295-L312
7,527
slarse/pdfebc-core
pdfebc_core/compress.py
compress_multiple_pdfs
def compress_multiple_pdfs(source_directory, output_directory, ghostscript_binary): """Compress all PDF files in the current directory and place the output in the given output directory. This is a generator function that first yields the amount of files to be compressed, and then yields the output path of e...
python
def compress_multiple_pdfs(source_directory, output_directory, ghostscript_binary): """Compress all PDF files in the current directory and place the output in the given output directory. This is a generator function that first yields the amount of files to be compressed, and then yields the output path of e...
['def', 'compress_multiple_pdfs', '(', 'source_directory', ',', 'output_directory', ',', 'ghostscript_binary', ')', ':', 'source_paths', '=', '_get_pdf_filenames_at', '(', 'source_directory', ')', 'yield', 'len', '(', 'source_paths', ')', 'for', 'source_path', 'in', 'source_paths', ':', 'output', '=', 'os', '.', 'path'...
Compress all PDF files in the current directory and place the output in the given output directory. This is a generator function that first yields the amount of files to be compressed, and then yields the output path of each file. Args: source_directory (str): Filepath to the source directory. ...
['Compress', 'all', 'PDF', 'files', 'in', 'the', 'current', 'directory', 'and', 'place', 'the', 'output', 'in', 'the', 'given', 'output', 'directory', '.', 'This', 'is', 'a', 'generator', 'function', 'that', 'first', 'yields', 'the', 'amount', 'of', 'files', 'to', 'be', 'compressed', 'and', 'then', 'yields', 'the', 'ou...
train
https://github.com/slarse/pdfebc-core/blob/fc40857bc42365b7434714333e37d7a3487603a0/pdfebc_core/compress.py#L87-L105
7,528
wmayner/pyphi
pyphi/subsystem.py
Subsystem.phi_effect_mip
def phi_effect_mip(self, mechanism, purview): """Return the |small_phi| of the effect MIP. This is the distance between the unpartitioned effect repertoire and the MIP cause repertoire. """ mip = self.effect_mip(mechanism, purview) return mip.phi if mip else 0
python
def phi_effect_mip(self, mechanism, purview): """Return the |small_phi| of the effect MIP. This is the distance between the unpartitioned effect repertoire and the MIP cause repertoire. """ mip = self.effect_mip(mechanism, purview) return mip.phi if mip else 0
['def', 'phi_effect_mip', '(', 'self', ',', 'mechanism', ',', 'purview', ')', ':', 'mip', '=', 'self', '.', 'effect_mip', '(', 'mechanism', ',', 'purview', ')', 'return', 'mip', '.', 'phi', 'if', 'mip', 'else', '0']
Return the |small_phi| of the effect MIP. This is the distance between the unpartitioned effect repertoire and the MIP cause repertoire.
['Return', 'the', '|small_phi|', 'of', 'the', 'effect', 'MIP', '.']
train
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/subsystem.py#L623-L630
7,529
kvesteri/validators
validators/utils.py
func_args_as_dict
def func_args_as_dict(func, args, kwargs): """ Return given function's positional and key value arguments as an ordered dictionary. """ if six.PY2: _getargspec = inspect.getargspec else: _getargspec = inspect.getfullargspec arg_names = list( OrderedDict.fromkeys( ...
python
def func_args_as_dict(func, args, kwargs): """ Return given function's positional and key value arguments as an ordered dictionary. """ if six.PY2: _getargspec = inspect.getargspec else: _getargspec = inspect.getfullargspec arg_names = list( OrderedDict.fromkeys( ...
['def', 'func_args_as_dict', '(', 'func', ',', 'args', ',', 'kwargs', ')', ':', 'if', 'six', '.', 'PY2', ':', '_getargspec', '=', 'inspect', '.', 'getargspec', 'else', ':', '_getargspec', '=', 'inspect', '.', 'getfullargspec', 'arg_names', '=', 'list', '(', 'OrderedDict', '.', 'fromkeys', '(', 'itertools', '.', 'chain'...
Return given function's positional and key value arguments as an ordered dictionary.
['Return', 'given', 'function', 's', 'positional', 'and', 'key', 'value', 'arguments', 'as', 'an', 'ordered', 'dictionary', '.']
train
https://github.com/kvesteri/validators/blob/34d355e87168241e872b25811d245810df2bd430/validators/utils.py#L35-L56
7,530
kstaniek/condoor
condoor/utils.py
is_reachable
def is_reachable(host, port=23): """Check reachability for specified hostname/port. It tries to open TCP socket. It supports IPv6. :param host: hostname or ip address string :rtype: str :param port: tcp port number :rtype: number :return: True if host is reachable else false """ ...
python
def is_reachable(host, port=23): """Check reachability for specified hostname/port. It tries to open TCP socket. It supports IPv6. :param host: hostname or ip address string :rtype: str :param port: tcp port number :rtype: number :return: True if host is reachable else false """ ...
['def', 'is_reachable', '(', 'host', ',', 'port', '=', '23', ')', ':', 'try', ':', 'addresses', '=', 'socket', '.', 'getaddrinfo', '(', 'host', ',', 'port', ',', 'socket', '.', 'AF_UNSPEC', ',', 'socket', '.', 'SOCK_STREAM', ')', 'except', 'socket', '.', 'gaierror', ':', 'return', 'False', 'for', 'family', ',', '_', ',...
Check reachability for specified hostname/port. It tries to open TCP socket. It supports IPv6. :param host: hostname or ip address string :rtype: str :param port: tcp port number :rtype: number :return: True if host is reachable else false
['Check', 'reachability', 'for', 'specified', 'hostname', '/', 'port', '.']
train
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/utils.py#L49-L82
7,531
jsommers/switchyard
switchyard/lib/topo/topobuild.py
Topology.serialize
def serialize(self): ''' Return a JSON string of the serialized topology ''' return json.dumps(json_graph.node_link_data(self.__nxgraph), cls=Encoder)
python
def serialize(self): ''' Return a JSON string of the serialized topology ''' return json.dumps(json_graph.node_link_data(self.__nxgraph), cls=Encoder)
['def', 'serialize', '(', 'self', ')', ':', 'return', 'json', '.', 'dumps', '(', 'json_graph', '.', 'node_link_data', '(', 'self', '.', '__nxgraph', ')', ',', 'cls', '=', 'Encoder', ')']
Return a JSON string of the serialized topology
['Return', 'a', 'JSON', 'string', 'of', 'the', 'serialized', 'topology']
train
https://github.com/jsommers/switchyard/blob/fdcb3869c937dcedbd6ea7a7822ebd412bf1e2b0/switchyard/lib/topo/topobuild.py#L266-L270
7,532
senseobservationsystems/commonsense-python-lib
senseapi.py
SenseAPI.SensorsGet
def SensorsGet(self, parameters = None, sensor_id = -1): """ Retrieve sensors from CommonSense, according to parameters, or by sensor id. If successful, result can be obtained by a call to getResponse(), and should be a json string. @param parameters (dicti...
python
def SensorsGet(self, parameters = None, sensor_id = -1): """ Retrieve sensors from CommonSense, according to parameters, or by sensor id. If successful, result can be obtained by a call to getResponse(), and should be a json string. @param parameters (dicti...
['def', 'SensorsGet', '(', 'self', ',', 'parameters', '=', 'None', ',', 'sensor_id', '=', '-', '1', ')', ':', 'url', '=', "''", 'if', 'parameters', 'is', 'None', 'and', 'sensor_id', '<>', '-', '1', ':', 'url', '=', "'/sensors/{0}.json'", '.', 'format', '(', 'sensor_id', ')', 'else', ':', 'url', '=', "'/sensors.json'", ...
Retrieve sensors from CommonSense, according to parameters, or by sensor id. If successful, result can be obtained by a call to getResponse(), and should be a json string. @param parameters (dictionary) (optional) - Dictionary containing the parameters for the api-call. ...
['Retrieve', 'sensors', 'from', 'CommonSense', 'according', 'to', 'parameters', 'or', 'by', 'sensor', 'id', '.', 'If', 'successful', 'result', 'can', 'be', 'obtained', 'by', 'a', 'call', 'to', 'getResponse', '()', 'and', 'should', 'be', 'a', 'json', 'string', '.']
train
https://github.com/senseobservationsystems/commonsense-python-lib/blob/aac59a1751ef79eb830b3ca1fab6ef2c83931f87/senseapi.py#L551-L573
7,533
aio-libs/aioredis
aioredis/commands/hash.py
HashCommandsMixin.hincrbyfloat
def hincrbyfloat(self, key, field, increment=1.0): """Increment the float value of a hash field by the given number.""" fut = self.execute(b'HINCRBYFLOAT', key, field, increment) return wait_convert(fut, float)
python
def hincrbyfloat(self, key, field, increment=1.0): """Increment the float value of a hash field by the given number.""" fut = self.execute(b'HINCRBYFLOAT', key, field, increment) return wait_convert(fut, float)
['def', 'hincrbyfloat', '(', 'self', ',', 'key', ',', 'field', ',', 'increment', '=', '1.0', ')', ':', 'fut', '=', 'self', '.', 'execute', '(', "b'HINCRBYFLOAT'", ',', 'key', ',', 'field', ',', 'increment', ')', 'return', 'wait_convert', '(', 'fut', ',', 'float', ')']
Increment the float value of a hash field by the given number.
['Increment', 'the', 'float', 'value', 'of', 'a', 'hash', 'field', 'by', 'the', 'given', 'number', '.']
train
https://github.com/aio-libs/aioredis/blob/e8c33e39558d4cc91cf70dde490d8b330c97dc2e/aioredis/commands/hash.py#L40-L43
7,534
NYUCCL/psiTurk
psiturk/psiturk_org_services.py
PsiturkOrgServices.get_ad_url
def get_ad_url(self, ad_id, sandbox): """ get_ad_url: gets ad server thing """ if sandbox: return self.sandbox_ad_server + '/view/' + str(ad_id) else: return self.ad_server + '/view/' + str(ad_id)
python
def get_ad_url(self, ad_id, sandbox): """ get_ad_url: gets ad server thing """ if sandbox: return self.sandbox_ad_server + '/view/' + str(ad_id) else: return self.ad_server + '/view/' + str(ad_id)
['def', 'get_ad_url', '(', 'self', ',', 'ad_id', ',', 'sandbox', ')', ':', 'if', 'sandbox', ':', 'return', 'self', '.', 'sandbox_ad_server', '+', "'/view/'", '+', 'str', '(', 'ad_id', ')', 'else', ':', 'return', 'self', '.', 'ad_server', '+', "'/view/'", '+', 'str', '(', 'ad_id', ')']
get_ad_url: gets ad server thing
['get_ad_url', ':', 'gets', 'ad', 'server', 'thing']
train
https://github.com/NYUCCL/psiTurk/blob/7170b992a0b5f56c165929cf87b3d3a1f3336c36/psiturk/psiturk_org_services.py#L108-L116
7,535
fhcrc/taxtastic
taxtastic/ncbi.py
read_nodes
def read_nodes(rows, source_id=1): """ Return an iterator of rows ready to insert into table "nodes". * rows - iterator of lists (eg, output from read_archive or read_dmp) """ ncbi_keys = ['tax_id', 'parent_id', 'rank', 'embl_code', 'division_id'] extra_keys = ['source_id', 'is_valid'] is_...
python
def read_nodes(rows, source_id=1): """ Return an iterator of rows ready to insert into table "nodes". * rows - iterator of lists (eg, output from read_archive or read_dmp) """ ncbi_keys = ['tax_id', 'parent_id', 'rank', 'embl_code', 'division_id'] extra_keys = ['source_id', 'is_valid'] is_...
['def', 'read_nodes', '(', 'rows', ',', 'source_id', '=', '1', ')', ':', 'ncbi_keys', '=', '[', "'tax_id'", ',', "'parent_id'", ',', "'rank'", ',', "'embl_code'", ',', "'division_id'", ']', 'extra_keys', '=', '[', "'source_id'", ',', "'is_valid'", ']', 'is_valid', '=', 'True', 'ncbi_cols', '=', 'len', '(', 'ncbi_keys',...
Return an iterator of rows ready to insert into table "nodes". * rows - iterator of lists (eg, output from read_archive or read_dmp)
['Return', 'an', 'iterator', 'of', 'rows', 'ready', 'to', 'insert', 'into', 'table', 'nodes', '.']
train
https://github.com/fhcrc/taxtastic/blob/4e874b7f2cc146178828bfba386314f8c342722b/taxtastic/ncbi.py#L250-L280
7,536
wmayner/pyphi
pyphi/validate.py
blackbox
def blackbox(blackbox): """Validate a macro blackboxing.""" if tuple(sorted(blackbox.output_indices)) != blackbox.output_indices: raise ValueError('Output indices {} must be ordered'.format( blackbox.output_indices)) partition(blackbox.partition) for part in blackbox.partition: ...
python
def blackbox(blackbox): """Validate a macro blackboxing.""" if tuple(sorted(blackbox.output_indices)) != blackbox.output_indices: raise ValueError('Output indices {} must be ordered'.format( blackbox.output_indices)) partition(blackbox.partition) for part in blackbox.partition: ...
['def', 'blackbox', '(', 'blackbox', ')', ':', 'if', 'tuple', '(', 'sorted', '(', 'blackbox', '.', 'output_indices', ')', ')', '!=', 'blackbox', '.', 'output_indices', ':', 'raise', 'ValueError', '(', "'Output indices {} must be ordered'", '.', 'format', '(', 'blackbox', '.', 'output_indices', ')', ')', 'partition', '(...
Validate a macro blackboxing.
['Validate', 'a', 'macro', 'blackboxing', '.']
train
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/validate.py#L223-L235
7,537
inveniosoftware-attic/invenio-knowledge
docs/_ext/flask_app.py
setup
def setup(sphinx): """Setup Sphinx object.""" from flask import has_app_context from invenio_base.factory import create_app PACKAGES = ['invenio_base', 'invenio.modules.accounts', 'invenio.modules.records', 'invenio_knowledge'] if not has_app_context(): app = create_app(PACK...
python
def setup(sphinx): """Setup Sphinx object.""" from flask import has_app_context from invenio_base.factory import create_app PACKAGES = ['invenio_base', 'invenio.modules.accounts', 'invenio.modules.records', 'invenio_knowledge'] if not has_app_context(): app = create_app(PACK...
['def', 'setup', '(', 'sphinx', ')', ':', 'from', 'flask', 'import', 'has_app_context', 'from', 'invenio_base', '.', 'factory', 'import', 'create_app', 'PACKAGES', '=', '[', "'invenio_base'", ',', "'invenio.modules.accounts'", ',', "'invenio.modules.records'", ',', "'invenio_knowledge'", ']', 'if', 'not', 'has_app_cont...
Setup Sphinx object.
['Setup', 'Sphinx', 'object', '.']
train
https://github.com/inveniosoftware-attic/invenio-knowledge/blob/b31722dc14243ca8f626f8b3bce9718d0119de55/docs/_ext/flask_app.py#L23-L33
7,538
billy-yoyo/RainbowSixSiege-Python-API
r6sapi/r6sapi.py
Rank.get_charm_url
def get_charm_url(self): """Get charm URL for the bracket this rank is in Returns ------- :class:`str` the URL for the charm """ if self.rank_id <= 4: return self.RANK_CHARMS[0] if self.rank_id <= 8: return self.RANK_CHARMS[1] if self.rank_id...
python
def get_charm_url(self): """Get charm URL for the bracket this rank is in Returns ------- :class:`str` the URL for the charm """ if self.rank_id <= 4: return self.RANK_CHARMS[0] if self.rank_id <= 8: return self.RANK_CHARMS[1] if self.rank_id...
['def', 'get_charm_url', '(', 'self', ')', ':', 'if', 'self', '.', 'rank_id', '<=', '4', ':', 'return', 'self', '.', 'RANK_CHARMS', '[', '0', ']', 'if', 'self', '.', 'rank_id', '<=', '8', ':', 'return', 'self', '.', 'RANK_CHARMS', '[', '1', ']', 'if', 'self', '.', 'rank_id', '<=', '12', ':', 'return', 'self', '.', 'RAN...
Get charm URL for the bracket this rank is in Returns ------- :class:`str` the URL for the charm
['Get', 'charm', 'URL', 'for', 'the', 'bracket', 'this', 'rank', 'is', 'in']
train
https://github.com/billy-yoyo/RainbowSixSiege-Python-API/blob/9860fdfd9a78aabd977eaa71b0a4ab4ed69e94d0/r6sapi/r6sapi.py#L808-L822
7,539
NICTA/revrand
revrand/optimize/decorators.py
_logtrick_gen
def _logtrick_gen(bounds): """Generate warping functions and new bounds for the log trick.""" # Test which parameters we can apply the log trick too ispos = np.array([isinstance(b, bt.Positive) for b in bounds], dtype=bool) nispos = ~ispos # Functions that implement the log trick def logx(x): ...
python
def _logtrick_gen(bounds): """Generate warping functions and new bounds for the log trick.""" # Test which parameters we can apply the log trick too ispos = np.array([isinstance(b, bt.Positive) for b in bounds], dtype=bool) nispos = ~ispos # Functions that implement the log trick def logx(x): ...
['def', '_logtrick_gen', '(', 'bounds', ')', ':', '# Test which parameters we can apply the log trick too', 'ispos', '=', 'np', '.', 'array', '(', '[', 'isinstance', '(', 'b', ',', 'bt', '.', 'Positive', ')', 'for', 'b', 'in', 'bounds', ']', ',', 'dtype', '=', 'bool', ')', 'nispos', '=', '~', 'ispos', '# Functions that...
Generate warping functions and new bounds for the log trick.
['Generate', 'warping', 'functions', 'and', 'new', 'bounds', 'for', 'the', 'log', 'trick', '.']
train
https://github.com/NICTA/revrand/blob/4c1881b6c1772d2b988518e49dde954f165acfb6/revrand/optimize/decorators.py#L586-L617
7,540
pytroll/satpy
satpy/multiscene.py
MultiScene._get_animation_frames
def _get_animation_frames(self, all_datasets, shape, fill_value=None, ignore_missing=False): """Create enhanced image frames to save to a file.""" for idx, ds in enumerate(all_datasets): if ds is None and ignore_missing: continue elif...
python
def _get_animation_frames(self, all_datasets, shape, fill_value=None, ignore_missing=False): """Create enhanced image frames to save to a file.""" for idx, ds in enumerate(all_datasets): if ds is None and ignore_missing: continue elif...
['def', '_get_animation_frames', '(', 'self', ',', 'all_datasets', ',', 'shape', ',', 'fill_value', '=', 'None', ',', 'ignore_missing', '=', 'False', ')', ':', 'for', 'idx', ',', 'ds', 'in', 'enumerate', '(', 'all_datasets', ')', ':', 'if', 'ds', 'is', 'None', 'and', 'ignore_missing', ':', 'continue', 'elif', 'ds', 'is...
Create enhanced image frames to save to a file.
['Create', 'enhanced', 'image', 'frames', 'to', 'save', 'to', 'a', 'file', '.']
train
https://github.com/pytroll/satpy/blob/1f21d20ac686b745fb0da9b4030d139893e066dd/satpy/multiscene.py#L374-L392
7,541
mbedmicro/pyOCD
pyocd/flash/flash.py
Flash.program_page
def program_page(self, address, bytes): """! @brief Flash one or more pages. @exception FlashProgramFailure """ assert self._active_operation == self.Operation.PROGRAM # prevent security settings from locking the device bytes = self.override_security_bit...
python
def program_page(self, address, bytes): """! @brief Flash one or more pages. @exception FlashProgramFailure """ assert self._active_operation == self.Operation.PROGRAM # prevent security settings from locking the device bytes = self.override_security_bit...
['def', 'program_page', '(', 'self', ',', 'address', ',', 'bytes', ')', ':', 'assert', 'self', '.', '_active_operation', '==', 'self', '.', 'Operation', '.', 'PROGRAM', '# prevent security settings from locking the device', 'bytes', '=', 'self', '.', 'override_security_bits', '(', 'address', ',', 'bytes', ')', '# first...
! @brief Flash one or more pages. @exception FlashProgramFailure
['!']
train
https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/flash/flash.py#L355-L374
7,542
Unidata/MetPy
examples/meteogram_metpy.py
Meteogram.plot_rh
def plot_rh(self, rh, plot_range=None): """ Required input: RH: Relative humidity (%) Optional Input: plot_range: Data range for making figure (list of (min,max,step)) """ # PLOT RELATIVE HUMIDITY if not plot_range: plot_range = [0, 100...
python
def plot_rh(self, rh, plot_range=None): """ Required input: RH: Relative humidity (%) Optional Input: plot_range: Data range for making figure (list of (min,max,step)) """ # PLOT RELATIVE HUMIDITY if not plot_range: plot_range = [0, 100...
['def', 'plot_rh', '(', 'self', ',', 'rh', ',', 'plot_range', '=', 'None', ')', ':', '# PLOT RELATIVE HUMIDITY', 'if', 'not', 'plot_range', ':', 'plot_range', '=', '[', '0', ',', '100', ',', '4', ']', 'self', '.', 'ax3', '=', 'fig', '.', 'add_subplot', '(', '4', ',', '1', ',', '3', ',', 'sharex', '=', 'self', '.', 'ax1...
Required input: RH: Relative humidity (%) Optional Input: plot_range: Data range for making figure (list of (min,max,step))
['Required', 'input', ':', 'RH', ':', 'Relative', 'humidity', '(', '%', ')', 'Optional', 'Input', ':', 'plot_range', ':', 'Data', 'range', 'for', 'making', 'figure', '(', 'list', 'of', '(', 'min', 'max', 'step', '))']
train
https://github.com/Unidata/MetPy/blob/16f68a94919b9a82dcf9cada2169cf039129e67b/examples/meteogram_metpy.py#L121-L142
7,543
cloud-custodian/cloud-custodian
tools/sandbox/c7n_autodoc/c7n-autodoc.py
gather_file_data
def gather_file_data(config): """ Gather policy information from files """ file_regex = re.compile(config['file_regex']) category_regex = re.compile(config['category_regex']) policies = {} for root, dirs, files in os.walk(config['c7n_policy_directory']): for file in files: i...
python
def gather_file_data(config): """ Gather policy information from files """ file_regex = re.compile(config['file_regex']) category_regex = re.compile(config['category_regex']) policies = {} for root, dirs, files in os.walk(config['c7n_policy_directory']): for file in files: i...
['def', 'gather_file_data', '(', 'config', ')', ':', 'file_regex', '=', 're', '.', 'compile', '(', 'config', '[', "'file_regex'", ']', ')', 'category_regex', '=', 're', '.', 'compile', '(', 'config', '[', "'category_regex'", ']', ')', 'policies', '=', '{', '}', 'for', 'root', ',', 'dirs', ',', 'files', 'in', 'os', '.',...
Gather policy information from files
['Gather', 'policy', 'information', 'from', 'files']
train
https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/sandbox/c7n_autodoc/c7n-autodoc.py#L76-L108
7,544
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py
WebElementWrapper.has_class
def has_class(self, classname): """Test if an element has a specific classname @type classname: str @param classname: Classname to test for; cannot contain spaces @rtype: bool @return: True if classname exists; false otherwise """ def element_has_class(): ...
python
def has_class(self, classname): """Test if an element has a specific classname @type classname: str @param classname: Classname to test for; cannot contain spaces @rtype: bool @return: True if classname exists; false otherwise """ def element_has_class(): ...
['def', 'has_class', '(', 'self', ',', 'classname', ')', ':', 'def', 'element_has_class', '(', ')', ':', '"""Wrapper to test if element has a class"""', 'pattern', '=', 're', '.', 'compile', '(', "'(\\s|^){classname}(\\s|$)'", '.', 'format', '(', 'classname', '=', 'classname', ')', ')', 'classes', '=', 'self', '.', 'el...
Test if an element has a specific classname @type classname: str @param classname: Classname to test for; cannot contain spaces @rtype: bool @return: True if classname exists; false otherwise
['Test', 'if', 'an', 'element', 'has', 'a', 'specific', 'classname']
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py#L379-L400
7,545
rackerlabs/lambda-uploader
lambda_uploader/uploader.py
PackageUploader._upload_s3
def _upload_s3(self, zip_file): ''' Uploads the lambda package to s3 ''' s3_client = self._aws_session.client('s3') transfer = boto3.s3.transfer.S3Transfer(s3_client) transfer.upload_file(zip_file, self._config.s3_bucket, self._config.s3_packa...
python
def _upload_s3(self, zip_file): ''' Uploads the lambda package to s3 ''' s3_client = self._aws_session.client('s3') transfer = boto3.s3.transfer.S3Transfer(s3_client) transfer.upload_file(zip_file, self._config.s3_bucket, self._config.s3_packa...
['def', '_upload_s3', '(', 'self', ',', 'zip_file', ')', ':', 's3_client', '=', 'self', '.', '_aws_session', '.', 'client', '(', "'s3'", ')', 'transfer', '=', 'boto3', '.', 's3', '.', 'transfer', '.', 'S3Transfer', '(', 's3_client', ')', 'transfer', '.', 'upload_file', '(', 'zip_file', ',', 'self', '.', '_config', '.',...
Uploads the lambda package to s3
['Uploads', 'the', 'lambda', 'package', 'to', 's3']
train
https://github.com/rackerlabs/lambda-uploader/blob/a5036e60d45d1a4fdc07df071f5b6e3b113388d4/lambda_uploader/uploader.py#L219-L226
7,546
pypyr/pypyr-cli
pypyr/steps/pype.py
get_arguments
def get_arguments(context): """Parse arguments for pype from context and assign default values. Args: context: pypyr.context.Context. context is mandatory. Returns: tuple (pipeline_name, #str use_parent_context, #bool pipe_arg, #str skip_parse, ...
python
def get_arguments(context): """Parse arguments for pype from context and assign default values. Args: context: pypyr.context.Context. context is mandatory. Returns: tuple (pipeline_name, #str use_parent_context, #bool pipe_arg, #str skip_parse, ...
['def', 'get_arguments', '(', 'context', ')', ':', 'context', '.', 'assert_key_has_value', '(', 'key', '=', "'pype'", ',', 'caller', '=', '__name__', ')', 'pype', '=', 'context', '.', 'get_formatted', '(', "'pype'", ')', 'try', ':', 'pipeline_name', '=', 'pype', '[', "'name'", ']', 'if', 'pipeline_name', 'is', 'None', ...
Parse arguments for pype from context and assign default values. Args: context: pypyr.context.Context. context is mandatory. Returns: tuple (pipeline_name, #str use_parent_context, #bool pipe_arg, #str skip_parse, #bool raise_error #b...
['Parse', 'arguments', 'for', 'pype', 'from', 'context', 'and', 'assign', 'default', 'values', '.']
train
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/steps/pype.py#L96-L143
7,547
tsileo/globster
globster.py
normalize_pattern
def normalize_pattern(pattern): """Converts backslashes in path patterns to forward slashes. Doesn't normalize regular expressions - they may contain escapes. """ if not (pattern.startswith('RE:') or pattern.startswith('!RE:')): pattern = _slashes.sub('/', pattern) if len(pattern) > 1: ...
python
def normalize_pattern(pattern): """Converts backslashes in path patterns to forward slashes. Doesn't normalize regular expressions - they may contain escapes. """ if not (pattern.startswith('RE:') or pattern.startswith('!RE:')): pattern = _slashes.sub('/', pattern) if len(pattern) > 1: ...
['def', 'normalize_pattern', '(', 'pattern', ')', ':', 'if', 'not', '(', 'pattern', '.', 'startswith', '(', "'RE:'", ')', 'or', 'pattern', '.', 'startswith', '(', "'!RE:'", ')', ')', ':', 'pattern', '=', '_slashes', '.', 'sub', '(', "'/'", ',', 'pattern', ')', 'if', 'len', '(', 'pattern', ')', '>', '1', ':', 'pattern',...
Converts backslashes in path patterns to forward slashes. Doesn't normalize regular expressions - they may contain escapes.
['Converts', 'backslashes', 'in', 'path', 'patterns', 'to', 'forward', 'slashes', '.']
train
https://github.com/tsileo/globster/blob/9628bce60207b150d39b409cddc3fadb34e70841/globster.py#L366-L375
7,548
explosion/spaCy
spacy/language.py
Language.update
def update(self, docs, golds, drop=0.0, sgd=None, losses=None, component_cfg=None): """Update the models in the pipeline. docs (iterable): A batch of `Doc` objects. golds (iterable): A batch of `GoldParse` objects. drop (float): The droput rate. sgd (callable): An optimizer. ...
python
def update(self, docs, golds, drop=0.0, sgd=None, losses=None, component_cfg=None): """Update the models in the pipeline. docs (iterable): A batch of `Doc` objects. golds (iterable): A batch of `GoldParse` objects. drop (float): The droput rate. sgd (callable): An optimizer. ...
['def', 'update', '(', 'self', ',', 'docs', ',', 'golds', ',', 'drop', '=', '0.0', ',', 'sgd', '=', 'None', ',', 'losses', '=', 'None', ',', 'component_cfg', '=', 'None', ')', ':', 'if', 'len', '(', 'docs', ')', '!=', 'len', '(', 'golds', ')', ':', 'raise', 'IndexError', '(', 'Errors', '.', 'E009', '.', 'format', '(', ...
Update the models in the pipeline. docs (iterable): A batch of `Doc` objects. golds (iterable): A batch of `GoldParse` objects. drop (float): The droput rate. sgd (callable): An optimizer. RETURNS (dict): Results from the update. DOCS: https://spacy.io/api/language#upda...
['Update', 'the', 'models', 'in', 'the', 'pipeline', '.']
train
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/language.py#L408-L459
7,549
sosreport/sos
sos/utilities.py
find
def find(file_pattern, top_dir, max_depth=None, path_pattern=None): """Generator function to find files recursively. Usage:: for filename in find("*.properties", "/var/log/foobar"): print filename """ if max_depth: base_depth = os.path.dirname(top_dir).count(os.path.sep) ...
python
def find(file_pattern, top_dir, max_depth=None, path_pattern=None): """Generator function to find files recursively. Usage:: for filename in find("*.properties", "/var/log/foobar"): print filename """ if max_depth: base_depth = os.path.dirname(top_dir).count(os.path.sep) ...
['def', 'find', '(', 'file_pattern', ',', 'top_dir', ',', 'max_depth', '=', 'None', ',', 'path_pattern', '=', 'None', ')', ':', 'if', 'max_depth', ':', 'base_depth', '=', 'os', '.', 'path', '.', 'dirname', '(', 'top_dir', ')', '.', 'count', '(', 'os', '.', 'path', '.', 'sep', ')', 'max_depth', '+=', 'base_depth', 'for'...
Generator function to find files recursively. Usage:: for filename in find("*.properties", "/var/log/foobar"): print filename
['Generator', 'function', 'to', 'find', 'files', 'recursively', '.', 'Usage', '::']
train
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/utilities.py#L65-L84
7,550
urschrei/convertbng
convertbng/util.py
_void_array_to_list
def _void_array_to_list(restuple, _func, _args): """ Convert the FFI result to Python data structures """ shape = (restuple.e.len, 1) array_size = np.prod(shape) mem_size = 8 * array_size array_str_e = string_at(restuple.e.data, mem_size) array_str_n = string_at(restuple.n.data, mem_size) ...
python
def _void_array_to_list(restuple, _func, _args): """ Convert the FFI result to Python data structures """ shape = (restuple.e.len, 1) array_size = np.prod(shape) mem_size = 8 * array_size array_str_e = string_at(restuple.e.data, mem_size) array_str_n = string_at(restuple.n.data, mem_size) ...
['def', '_void_array_to_list', '(', 'restuple', ',', '_func', ',', '_args', ')', ':', 'shape', '=', '(', 'restuple', '.', 'e', '.', 'len', ',', '1', ')', 'array_size', '=', 'np', '.', 'prod', '(', 'shape', ')', 'mem_size', '=', '8', '*', 'array_size', 'array_str_e', '=', 'string_at', '(', 'restuple', '.', 'e', '.', 'da...
Convert the FFI result to Python data structures
['Convert', 'the', 'FFI', 'result', 'to', 'Python', 'data', 'structures']
train
https://github.com/urschrei/convertbng/blob/b0f5ca8b4942a835a834aed4c1fdb4d827c72342/convertbng/util.py#L122-L134
7,551
hannes-brt/hebel
hebel/layers/input_dropout.py
InputDropout.backprop
def backprop(self, input_data, df_output, cache=None): """ Backpropagate through the hidden layer **Parameters:** input_data : ``GPUArray`` Inpute data to perform dropout on. df_output : ``GPUArray`` Gradients with respect to the output of this layer ...
python
def backprop(self, input_data, df_output, cache=None): """ Backpropagate through the hidden layer **Parameters:** input_data : ``GPUArray`` Inpute data to perform dropout on. df_output : ``GPUArray`` Gradients with respect to the output of this layer ...
['def', 'backprop', '(', 'self', ',', 'input_data', ',', 'df_output', ',', 'cache', '=', 'None', ')', ':', 'if', 'self', '.', 'compute_input_gradients', ':', 'apply_dropout_mask', '(', 'df_output', ',', 'dropout_mask', ')', 'return', 'tuple', '(', ')', ',', 'df_output']
Backpropagate through the hidden layer **Parameters:** input_data : ``GPUArray`` Inpute data to perform dropout on. df_output : ``GPUArray`` Gradients with respect to the output of this layer (received from the layer above). cache : list of ``GPUAr...
['Backpropagate', 'through', 'the', 'hidden', 'layer']
train
https://github.com/hannes-brt/hebel/blob/1e2c3a9309c2646103901b26a55be4e312dd5005/hebel/layers/input_dropout.py#L91-L119
7,552
ranaroussi/qtpylib
qtpylib/tools.py
convert_timezone
def convert_timezone(date_str, tz_from, tz_to="UTC", fmt=None): """ get timezone as tz_offset """ tz_offset = datetime_to_timezone( datetime.datetime.now(), tz=tz_from).strftime('%z') tz_offset = tz_offset[:3] + ':' + tz_offset[3:] date = parse_date(str(date_str) + tz_offset) if tz_from != ...
python
def convert_timezone(date_str, tz_from, tz_to="UTC", fmt=None): """ get timezone as tz_offset """ tz_offset = datetime_to_timezone( datetime.datetime.now(), tz=tz_from).strftime('%z') tz_offset = tz_offset[:3] + ':' + tz_offset[3:] date = parse_date(str(date_str) + tz_offset) if tz_from != ...
['def', 'convert_timezone', '(', 'date_str', ',', 'tz_from', ',', 'tz_to', '=', '"UTC"', ',', 'fmt', '=', 'None', ')', ':', 'tz_offset', '=', 'datetime_to_timezone', '(', 'datetime', '.', 'datetime', '.', 'now', '(', ')', ',', 'tz', '=', 'tz_from', ')', '.', 'strftime', '(', "'%z'", ')', 'tz_offset', '=', 'tz_offset', ...
get timezone as tz_offset
['get', 'timezone', 'as', 'tz_offset']
train
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/tools.py#L487-L499
7,553
tamasgal/km3pipe
km3pipe/io/ch.py
CHPump.finish
def finish(self): """Clean up the JLigier controlhost connection""" log.debug("Disconnecting from JLigier.") self.client.socket.shutdown(socket.SHUT_RDWR) self.client._disconnect()
python
def finish(self): """Clean up the JLigier controlhost connection""" log.debug("Disconnecting from JLigier.") self.client.socket.shutdown(socket.SHUT_RDWR) self.client._disconnect()
['def', 'finish', '(', 'self', ')', ':', 'log', '.', 'debug', '(', '"Disconnecting from JLigier."', ')', 'self', '.', 'client', '.', 'socket', '.', 'shutdown', '(', 'socket', '.', 'SHUT_RDWR', ')', 'self', '.', 'client', '.', '_disconnect', '(', ')']
Clean up the JLigier controlhost connection
['Clean', 'up', 'the', 'JLigier', 'controlhost', 'connection']
train
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/io/ch.py#L176-L180
7,554
blubberdiblub/eztemplate
eztemplate/engines/string_formatter_engine.py
FormatterWrapper.format_field
def format_field(self, value, format_spec): """When field missing, return original spec.""" if isinstance(value, MissingField): if format_spec is not None: value.format_spec = format_spec return str(value) return super(FormatterWrapper, self).format_field...
python
def format_field(self, value, format_spec): """When field missing, return original spec.""" if isinstance(value, MissingField): if format_spec is not None: value.format_spec = format_spec return str(value) return super(FormatterWrapper, self).format_field...
['def', 'format_field', '(', 'self', ',', 'value', ',', 'format_spec', ')', ':', 'if', 'isinstance', '(', 'value', ',', 'MissingField', ')', ':', 'if', 'format_spec', 'is', 'not', 'None', ':', 'value', '.', 'format_spec', '=', 'format_spec', 'return', 'str', '(', 'value', ')', 'return', 'super', '(', 'FormatterWrapper'...
When field missing, return original spec.
['When', 'field', 'missing', 'return', 'original', 'spec', '.']
train
https://github.com/blubberdiblub/eztemplate/blob/ab5b2b4987c045116d130fd83e216704b8edfb5d/eztemplate/engines/string_formatter_engine.py#L81-L88
7,555
inveniosoftware/invenio-previewer
invenio_previewer/extensions/csv_dthreejs.py
preview
def preview(file): """Render appropiate template with embed flag.""" file_info = validate_csv(file) return render_template( 'invenio_previewer/csv_bar.html', file=file, delimiter=file_info['delimiter'], encoding=file_info['encoding'], js_bundles=current_previewer.js_b...
python
def preview(file): """Render appropiate template with embed flag.""" file_info = validate_csv(file) return render_template( 'invenio_previewer/csv_bar.html', file=file, delimiter=file_info['delimiter'], encoding=file_info['encoding'], js_bundles=current_previewer.js_b...
['def', 'preview', '(', 'file', ')', ':', 'file_info', '=', 'validate_csv', '(', 'file', ')', 'return', 'render_template', '(', "'invenio_previewer/csv_bar.html'", ',', 'file', '=', 'file', ',', 'delimiter', '=', 'file_info', '[', "'delimiter'", ']', ',', 'encoding', '=', 'file_info', '[', "'encoding'", ']', ',', 'js_b...
Render appropiate template with embed flag.
['Render', 'appropiate', 'template', 'with', 'embed', 'flag', '.']
train
https://github.com/inveniosoftware/invenio-previewer/blob/558fd22e0f29cc8cd7a6999abd4febcf6b248c49/invenio_previewer/extensions/csv_dthreejs.py#L54-L64
7,556
bslatkin/dpxdt
dpxdt/client/capture_worker.py
register
def register(coordinator): """Registers this module as a worker with the given coordinator.""" if FLAGS.phantomjs_script: utils.verify_binary('phantomjs_binary', ['--version']) assert os.path.exists(FLAGS.phantomjs_script) else: utils.verify_binary('capture_binary', ['--version']) ...
python
def register(coordinator): """Registers this module as a worker with the given coordinator.""" if FLAGS.phantomjs_script: utils.verify_binary('phantomjs_binary', ['--version']) assert os.path.exists(FLAGS.phantomjs_script) else: utils.verify_binary('capture_binary', ['--version']) ...
['def', 'register', '(', 'coordinator', ')', ':', 'if', 'FLAGS', '.', 'phantomjs_script', ':', 'utils', '.', 'verify_binary', '(', "'phantomjs_binary'", ',', '[', "'--version'", ']', ')', 'assert', 'os', '.', 'path', '.', 'exists', '(', 'FLAGS', '.', 'phantomjs_script', ')', 'else', ':', 'utils', '.', 'verify_binary', ...
Registers this module as a worker with the given coordinator.
['Registers', 'this', 'module', 'as', 'a', 'worker', 'with', 'the', 'given', 'coordinator', '.']
train
https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/client/capture_worker.py#L207-L227
7,557
QualiSystems/cloudshell-networking-devices
cloudshell/devices/standards/sdn/configuration_attributes_structure.py
GenericSDNResource.add_trunk_ports
def add_trunk_ports(self): """SDN Controller enable trunk ports :rtype: list[tuple[str, str]] """ ports = self.attributes.get("{}Enable Full Trunk Ports".format(self.namespace_prefix), None) return self._parse_ports(ports=ports)
python
def add_trunk_ports(self): """SDN Controller enable trunk ports :rtype: list[tuple[str, str]] """ ports = self.attributes.get("{}Enable Full Trunk Ports".format(self.namespace_prefix), None) return self._parse_ports(ports=ports)
['def', 'add_trunk_ports', '(', 'self', ')', ':', 'ports', '=', 'self', '.', 'attributes', '.', 'get', '(', '"{}Enable Full Trunk Ports"', '.', 'format', '(', 'self', '.', 'namespace_prefix', ')', ',', 'None', ')', 'return', 'self', '.', '_parse_ports', '(', 'ports', '=', 'ports', ')']
SDN Controller enable trunk ports :rtype: list[tuple[str, str]]
['SDN', 'Controller', 'enable', 'trunk', 'ports']
train
https://github.com/QualiSystems/cloudshell-networking-devices/blob/009aab33edb30035b52fe10dbb91db61c95ba4d9/cloudshell/devices/standards/sdn/configuration_attributes_structure.py#L68-L74
7,558
MacHu-GWU/uszipcode-project
uszipcode/pkg/sqlalchemy_mate/engine_creator.py
create_postgresql_psycopg2
def create_postgresql_psycopg2(username, password, host, port, database, **kwargs): # pragma: no cover """ create an engine connected to a postgresql database using psycopg2. """ return create_engine( _create_postgresql_psycopg2(username, password, host, port, database), **kwargs )
python
def create_postgresql_psycopg2(username, password, host, port, database, **kwargs): # pragma: no cover """ create an engine connected to a postgresql database using psycopg2. """ return create_engine( _create_postgresql_psycopg2(username, password, host, port, database), **kwargs )
['def', 'create_postgresql_psycopg2', '(', 'username', ',', 'password', ',', 'host', ',', 'port', ',', 'database', ',', '*', '*', 'kwargs', ')', ':', '# pragma: no cover', 'return', 'create_engine', '(', '_create_postgresql_psycopg2', '(', 'username', ',', 'password', ',', 'host', ',', 'port', ',', 'database', ')', ','...
create an engine connected to a postgresql database using psycopg2.
['create', 'an', 'engine', 'connected', 'to', 'a', 'postgresql', 'database', 'using', 'psycopg2', '.']
train
https://github.com/MacHu-GWU/uszipcode-project/blob/96282b779a3efb422802de83c48ca284598ba952/uszipcode/pkg/sqlalchemy_mate/engine_creator.py#L78-L85
7,559
praw-dev/prawtools
prawtools/stats.py
SubredditStats.publish_results
def publish_results(self, view, submitters, commenters): """Submit the results to the subreddit. Has no return value (None).""" def timef(timestamp, date_only=False): """Return a suitable string representaation of the timestamp.""" dtime = datetime.fromtimestamp(timestamp) ...
python
def publish_results(self, view, submitters, commenters): """Submit the results to the subreddit. Has no return value (None).""" def timef(timestamp, date_only=False): """Return a suitable string representaation of the timestamp.""" dtime = datetime.fromtimestamp(timestamp) ...
['def', 'publish_results', '(', 'self', ',', 'view', ',', 'submitters', ',', 'commenters', ')', ':', 'def', 'timef', '(', 'timestamp', ',', 'date_only', '=', 'False', ')', ':', '"""Return a suitable string representaation of the timestamp."""', 'dtime', '=', 'datetime', '.', 'fromtimestamp', '(', 'timestamp', ')', 'if'...
Submit the results to the subreddit. Has no return value (None).
['Submit', 'the', 'results', 'to', 'the', 'subreddit', '.', 'Has', 'no', 'return', 'value', '(', 'None', ')', '.']
train
https://github.com/praw-dev/prawtools/blob/571d5c28c2222f6f8dbbca8c815b8da0a776ab85/prawtools/stats.py#L227-L260
7,560
saltstack/salt
salt/modules/memcached.py
increment
def increment(key, delta=1, host=DEFAULT_HOST, port=DEFAULT_PORT): ''' Increment the value of a key CLI Example: .. code-block:: bash salt '*' memcached.increment <key> salt '*' memcached.increment <key> 2 ''' conn = _connect(host, port) _check_stats(conn) cur = get(ke...
python
def increment(key, delta=1, host=DEFAULT_HOST, port=DEFAULT_PORT): ''' Increment the value of a key CLI Example: .. code-block:: bash salt '*' memcached.increment <key> salt '*' memcached.increment <key> 2 ''' conn = _connect(host, port) _check_stats(conn) cur = get(ke...
['def', 'increment', '(', 'key', ',', 'delta', '=', '1', ',', 'host', '=', 'DEFAULT_HOST', ',', 'port', '=', 'DEFAULT_PORT', ')', ':', 'conn', '=', '_connect', '(', 'host', ',', 'port', ')', '_check_stats', '(', 'conn', ')', 'cur', '=', 'get', '(', 'key', ')', 'if', 'cur', 'is', 'None', ':', 'raise', 'CommandExecutionE...
Increment the value of a key CLI Example: .. code-block:: bash salt '*' memcached.increment <key> salt '*' memcached.increment <key> 2
['Increment', 'the', 'value', 'of', 'a', 'key']
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/memcached.py#L213-L239
7,561
bennylope/django-organizations
organizations/utils.py
model_field_attr
def model_field_attr(model, model_field, attr): """ Returns the specified attribute for the specified field on the model class. """ fields = dict([(field.name, field) for field in model._meta.fields]) return getattr(fields[model_field], attr)
python
def model_field_attr(model, model_field, attr): """ Returns the specified attribute for the specified field on the model class. """ fields = dict([(field.name, field) for field in model._meta.fields]) return getattr(fields[model_field], attr)
['def', 'model_field_attr', '(', 'model', ',', 'model_field', ',', 'attr', ')', ':', 'fields', '=', 'dict', '(', '[', '(', 'field', '.', 'name', ',', 'field', ')', 'for', 'field', 'in', 'model', '.', '_meta', '.', 'fields', ']', ')', 'return', 'getattr', '(', 'fields', '[', 'model_field', ']', ',', 'attr', ')']
Returns the specified attribute for the specified field on the model class.
['Returns', 'the', 'specified', 'attribute', 'for', 'the', 'specified', 'field', 'on', 'the', 'model', 'class', '.']
train
https://github.com/bennylope/django-organizations/blob/85f753a8f7a8f0f31636c9209fb69e7030a5c79a/organizations/utils.py#L115-L120
7,562
wummel/linkchecker
linkcheck/lock.py
get_lock
def get_lock (name, debug=False): """Get a new lock. @param debug: if True, acquire() and release() will have debug messages @ptype debug: boolean, default is False @return: a lock object @rtype: threading.Lock or DebugLock """ lock = threading.Lock() # for thread debugging, use the Debu...
python
def get_lock (name, debug=False): """Get a new lock. @param debug: if True, acquire() and release() will have debug messages @ptype debug: boolean, default is False @return: a lock object @rtype: threading.Lock or DebugLock """ lock = threading.Lock() # for thread debugging, use the Debu...
['def', 'get_lock', '(', 'name', ',', 'debug', '=', 'False', ')', ':', 'lock', '=', 'threading', '.', 'Lock', '(', ')', '# for thread debugging, use the DebugLock wrapper', 'if', 'debug', ':', 'lock', '=', 'DebugLock', '(', 'lock', ',', 'name', ')', 'return', 'lock']
Get a new lock. @param debug: if True, acquire() and release() will have debug messages @ptype debug: boolean, default is False @return: a lock object @rtype: threading.Lock or DebugLock
['Get', 'a', 'new', 'lock', '.']
train
https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/lock.py#L23-L34
7,563
seequent/properties
properties/extras/uid.py
HasUID.serialize
def serialize(self, include_class=True, save_dynamic=False, **kwargs): """Serialize nested HasUID instances to a flat dictionary **Parameters**: * **include_class** - If True (the default), the name of the class will also be saved to the serialized dictionary under key :cod...
python
def serialize(self, include_class=True, save_dynamic=False, **kwargs): """Serialize nested HasUID instances to a flat dictionary **Parameters**: * **include_class** - If True (the default), the name of the class will also be saved to the serialized dictionary under key :cod...
['def', 'serialize', '(', 'self', ',', 'include_class', '=', 'True', ',', 'save_dynamic', '=', 'False', ',', '*', '*', 'kwargs', ')', ':', 'registry', '=', 'kwargs', '.', 'pop', '(', "'registry'", ',', 'None', ')', 'if', 'registry', 'is', 'None', ':', 'registry', '=', 'dict', '(', ')', 'if', 'not', 'registry', ':', 'ro...
Serialize nested HasUID instances to a flat dictionary **Parameters**: * **include_class** - If True (the default), the name of the class will also be saved to the serialized dictionary under key :code:`'__class__'` * **save_dynamic** - If True, dynamic properties are writt...
['Serialize', 'nested', 'HasUID', 'instances', 'to', 'a', 'flat', 'dictionary']
train
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/extras/uid.py#L69-L104
7,564
blue-yonder/tsfresh
tsfresh/feature_extraction/feature_calculators.py
agg_autocorrelation
def agg_autocorrelation(x, param): r""" Calculates the value of an aggregation function :math:`f_{agg}` (e.g. the variance or the mean) over the autocorrelation :math:`R(l)` for different lags. The autocorrelation :math:`R(l)` for lag :math:`l` is defined as .. math:: R(l) = \frac{1}{(n-l)\sig...
python
def agg_autocorrelation(x, param): r""" Calculates the value of an aggregation function :math:`f_{agg}` (e.g. the variance or the mean) over the autocorrelation :math:`R(l)` for different lags. The autocorrelation :math:`R(l)` for lag :math:`l` is defined as .. math:: R(l) = \frac{1}{(n-l)\sig...
['def', 'agg_autocorrelation', '(', 'x', ',', 'param', ')', ':', '# if the time series is longer than the following threshold, we use fft to calculate the acf', 'THRESHOLD_TO_USE_FFT', '=', '1250', 'var', '=', 'np', '.', 'var', '(', 'x', ')', 'n', '=', 'len', '(', 'x', ')', 'max_maxlag', '=', 'max', '(', '[', 'config',...
r""" Calculates the value of an aggregation function :math:`f_{agg}` (e.g. the variance or the mean) over the autocorrelation :math:`R(l)` for different lags. The autocorrelation :math:`R(l)` for lag :math:`l` is defined as .. math:: R(l) = \frac{1}{(n-l)\sigma^{2}} \sum_{t=1}^{n-l}(X_{t}-\mu )(X_...
['r', 'Calculates', 'the', 'value', 'of', 'an', 'aggregation', 'function', ':', 'math', ':', 'f_', '{', 'agg', '}', '(', 'e', '.', 'g', '.', 'the', 'variance', 'or', 'the', 'mean', ')', 'over', 'the', 'autocorrelation', ':', 'math', ':', 'R', '(', 'l', ')', 'for', 'different', 'lags', '.', 'The', 'autocorrelation', ':'...
train
https://github.com/blue-yonder/tsfresh/blob/c72c9c574371cf7dd7d54e00a466792792e5d202/tsfresh/feature_extraction/feature_calculators.py#L324-L366
7,565
pjmark/NIMPA
niftypet/nimpa/prc/imio.py
list_dcm_datain
def list_dcm_datain(datain): ''' List all DICOM file paths in the datain dictionary of input data. ''' if not isinstance(datain, dict): raise ValueError('The input is not a dictionary!') dcmlst = [] # list of mu-map DICOM files if 'mumapDCM' in datain: dcmump = os.listdir(datai...
python
def list_dcm_datain(datain): ''' List all DICOM file paths in the datain dictionary of input data. ''' if not isinstance(datain, dict): raise ValueError('The input is not a dictionary!') dcmlst = [] # list of mu-map DICOM files if 'mumapDCM' in datain: dcmump = os.listdir(datai...
['def', 'list_dcm_datain', '(', 'datain', ')', ':', 'if', 'not', 'isinstance', '(', 'datain', ',', 'dict', ')', ':', 'raise', 'ValueError', '(', "'The input is not a dictionary!'", ')', 'dcmlst', '=', '[', ']', '# list of mu-map DICOM files', 'if', "'mumapDCM'", 'in', 'datain', ':', 'dcmump', '=', 'os', '.', 'listdir',...
List all DICOM file paths in the datain dictionary of input data.
['List', 'all', 'DICOM', 'file', 'paths', 'in', 'the', 'datain', 'dictionary', 'of', 'input', 'data', '.']
train
https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/imio.py#L358-L411
7,566
crdoconnor/strictyaml
strictyaml/representation.py
YAML.data
def data(self): """ Returns raw data representation of the document or document segment. Mappings are rendered as ordered dicts, sequences as lists and scalar values as whatever the validator returns (int, string, etc.). If no validators are used, scalar values are always retur...
python
def data(self): """ Returns raw data representation of the document or document segment. Mappings are rendered as ordered dicts, sequences as lists and scalar values as whatever the validator returns (int, string, etc.). If no validators are used, scalar values are always retur...
['def', 'data', '(', 'self', ')', ':', 'if', 'isinstance', '(', 'self', '.', '_value', ',', 'CommentedMap', ')', ':', 'mapping', '=', 'OrderedDict', '(', ')', 'for', 'key', ',', 'value', 'in', 'self', '.', '_value', '.', 'items', '(', ')', ':', 'mapping', '[', 'key', '.', 'data', ']', '=', 'value', '.', 'data', 'return...
Returns raw data representation of the document or document segment. Mappings are rendered as ordered dicts, sequences as lists and scalar values as whatever the validator returns (int, string, etc.). If no validators are used, scalar values are always returned as strings.
['Returns', 'raw', 'data', 'representation', 'of', 'the', 'document', 'or', 'document', 'segment', '.']
train
https://github.com/crdoconnor/strictyaml/blob/efdac7f89e81679fc95686288cd32b9563fde609/strictyaml/representation.py#L102-L119
7,567
cs50/check50
check50/flask.py
app.raw_content
def raw_content(self, output=None, str_output=None): """Searches for `output` regex match within content of page, regardless of mimetype.""" return self._search_page(output, str_output, self.response.data, lambda regex, content: regex.search(content.decode()))
python
def raw_content(self, output=None, str_output=None): """Searches for `output` regex match within content of page, regardless of mimetype.""" return self._search_page(output, str_output, self.response.data, lambda regex, content: regex.search(content.decode()))
['def', 'raw_content', '(', 'self', ',', 'output', '=', 'None', ',', 'str_output', '=', 'None', ')', ':', 'return', 'self', '.', '_search_page', '(', 'output', ',', 'str_output', ',', 'self', '.', 'response', '.', 'data', ',', 'lambda', 'regex', ',', 'content', ':', 'regex', '.', 'search', '(', 'content', '.', 'decode'...
Searches for `output` regex match within content of page, regardless of mimetype.
['Searches', 'for', 'output', 'regex', 'match', 'within', 'content', 'of', 'page', 'regardless', 'of', 'mimetype', '.']
train
https://github.com/cs50/check50/blob/42c1f0c36baa6a24f69742d74551a9ea7a5ceb33/check50/flask.py#L116-L118
7,568
chaoss/grimoirelab-manuscripts
manuscripts/report.py
Report.sec_project_community
def sec_project_community(self, project=None): """ Generate the data for the Communication section in a Project report :return: """ def create_csv(metric1, csv_labels, file_label): esfilters = None csv_labels = csv_labels.replace("_", "") # LaTeX not sup...
python
def sec_project_community(self, project=None): """ Generate the data for the Communication section in a Project report :return: """ def create_csv(metric1, csv_labels, file_label): esfilters = None csv_labels = csv_labels.replace("_", "") # LaTeX not sup...
['def', 'sec_project_community', '(', 'self', ',', 'project', '=', 'None', ')', ':', 'def', 'create_csv', '(', 'metric1', ',', 'csv_labels', ',', 'file_label', ')', ':', 'esfilters', '=', 'None', 'csv_labels', '=', 'csv_labels', '.', 'replace', '(', '"_"', ',', '""', ')', '# LaTeX not supports "_"', 'if', 'project', '!...
Generate the data for the Communication section in a Project report :return:
['Generate', 'the', 'data', 'for', 'the', 'Communication', 'section', 'in', 'a', 'Project', 'report', ':', 'return', ':']
train
https://github.com/chaoss/grimoirelab-manuscripts/blob/94a3ad4f11bfbcd6c5190e01cb5d3e47a5187cd9/manuscripts/report.py#L556-L616
7,569
markovmodel/PyEMMA
pyemma/datasets/potentials.py
AsymmetricDoubleWell.sample
def sample(self, x0, nsteps, nskip=1): r"""generate nsteps sample points""" x = np.zeros(shape=(nsteps + 1,)) x[0] = x0 for t in range(nsteps): q = x[t] for s in range(nskip): q = self.step(q) x[t + 1] = q return x
python
def sample(self, x0, nsteps, nskip=1): r"""generate nsteps sample points""" x = np.zeros(shape=(nsteps + 1,)) x[0] = x0 for t in range(nsteps): q = x[t] for s in range(nskip): q = self.step(q) x[t + 1] = q return x
['def', 'sample', '(', 'self', ',', 'x0', ',', 'nsteps', ',', 'nskip', '=', '1', ')', ':', 'x', '=', 'np', '.', 'zeros', '(', 'shape', '=', '(', 'nsteps', '+', '1', ',', ')', ')', 'x', '[', '0', ']', '=', 'x0', 'for', 't', 'in', 'range', '(', 'nsteps', ')', ':', 'q', '=', 'x', '[', 't', ']', 'for', 's', 'in', 'range', ...
r"""generate nsteps sample points
['r', 'generate', 'nsteps', 'sample', 'points']
train
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/datasets/potentials.py#L111-L120
7,570
santoshphilip/eppy
eppy/loops.py
extractfields
def extractfields(data, commdct, objkey, fieldlists): """get all the objects of objkey. fieldlists will have a fieldlist for each of those objects. return the contents of those fields""" # TODO : this assumes that the field list identical for # each instance of the object. This is not true. # So...
python
def extractfields(data, commdct, objkey, fieldlists): """get all the objects of objkey. fieldlists will have a fieldlist for each of those objects. return the contents of those fields""" # TODO : this assumes that the field list identical for # each instance of the object. This is not true. # So...
['def', 'extractfields', '(', 'data', ',', 'commdct', ',', 'objkey', ',', 'fieldlists', ')', ':', '# TODO : this assumes that the field list identical for', '# each instance of the object. This is not true.', '# So we should have a field list for each instance of the object', '# and map them with a zip', 'objindex', '=...
get all the objects of objkey. fieldlists will have a fieldlist for each of those objects. return the contents of those fields
['get', 'all', 'the', 'objects', 'of', 'objkey', '.', 'fieldlists', 'will', 'have', 'a', 'fieldlist', 'for', 'each', 'of', 'those', 'objects', '.', 'return', 'the', 'contents', 'of', 'those', 'fields']
train
https://github.com/santoshphilip/eppy/blob/55410ff7c11722f35bc4331ff5e00a0b86f787e1/eppy/loops.py#L21-L60
7,571
koszullab/instaGRAAL
instagraal/leastsqbound.py
external2internal
def external2internal(xe, bounds): """ Convert a series of external variables to internal variables""" xi = np.empty_like(xe) for i, (v, bound) in enumerate(zip(xe, bounds)): a = bound[0] # minimum b = bound[1] # maximum if a == None and b == None: # No constraints ...
python
def external2internal(xe, bounds): """ Convert a series of external variables to internal variables""" xi = np.empty_like(xe) for i, (v, bound) in enumerate(zip(xe, bounds)): a = bound[0] # minimum b = bound[1] # maximum if a == None and b == None: # No constraints ...
['def', 'external2internal', '(', 'xe', ',', 'bounds', ')', ':', 'xi', '=', 'np', '.', 'empty_like', '(', 'xe', ')', 'for', 'i', ',', '(', 'v', ',', 'bound', ')', 'in', 'enumerate', '(', 'zip', '(', 'xe', ',', 'bounds', ')', ')', ':', 'a', '=', 'bound', '[', '0', ']', '# minimum', 'b', '=', 'bound', '[', '1', ']', '# m...
Convert a series of external variables to internal variables
['Convert', 'a', 'series', 'of', 'external', 'variables', 'to', 'internal', 'variables']
train
https://github.com/koszullab/instaGRAAL/blob/1c02ca838e57d8178eec79f223644b2acd0153dd/instagraal/leastsqbound.py#L81-L103
7,572
CRS-support/ftw
ftw/http.py
HttpResponse.parse_content_encoding
def parse_content_encoding(self, response_headers, response_data): """ Parses a response that contains Content-Encoding to retrieve response_data """ if response_headers['content-encoding'] == 'gzip': buf = StringIO.StringIO(response_data) zipbuf = gzip.Gz...
python
def parse_content_encoding(self, response_headers, response_data): """ Parses a response that contains Content-Encoding to retrieve response_data """ if response_headers['content-encoding'] == 'gzip': buf = StringIO.StringIO(response_data) zipbuf = gzip.Gz...
['def', 'parse_content_encoding', '(', 'self', ',', 'response_headers', ',', 'response_data', ')', ':', 'if', 'response_headers', '[', "'content-encoding'", ']', '==', "'gzip'", ':', 'buf', '=', 'StringIO', '.', 'StringIO', '(', 'response_data', ')', 'zipbuf', '=', 'gzip', '.', 'GzipFile', '(', 'fileobj', '=', 'buf', '...
Parses a response that contains Content-Encoding to retrieve response_data
['Parses', 'a', 'response', 'that', 'contains', 'Content', '-', 'Encoding', 'to', 'retrieve', 'response_data']
train
https://github.com/CRS-support/ftw/blob/1bbfd9b702e7e65532c1fd52bc82960556cefae5/ftw/http.py#L41-L61
7,573
projectatomic/atomic-reactor
atomic_reactor/plugins/pre_pull_base_image.py
PullBaseImagePlugin._pull_and_tag_image
def _pull_and_tag_image(self, image, build_json, nonce): """Docker pull the image and tag it uniquely for use by this build""" image = image.copy() first_library_exc = None for _ in range(20): # retry until pull and tag is successful or definitively fails. # shoul...
python
def _pull_and_tag_image(self, image, build_json, nonce): """Docker pull the image and tag it uniquely for use by this build""" image = image.copy() first_library_exc = None for _ in range(20): # retry until pull and tag is successful or definitively fails. # shoul...
['def', '_pull_and_tag_image', '(', 'self', ',', 'image', ',', 'build_json', ',', 'nonce', ')', ':', 'image', '=', 'image', '.', 'copy', '(', ')', 'first_library_exc', '=', 'None', 'for', '_', 'in', 'range', '(', '20', ')', ':', '# retry until pull and tag is successful or definitively fails.', "# should never require ...
Docker pull the image and tag it uniquely for use by this build
['Docker', 'pull', 'the', 'image', 'and', 'tag', 'it', 'uniquely', 'for', 'use', 'by', 'this', 'build']
train
https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/pre_pull_base_image.py#L250-L303
7,574
TurboGears/gearbox
gearbox/commandmanager.py
CommandManager.find_command
def find_command(self, argv): """Given an argument list, find a command and return the processor and any remaining arguments. """ search_args = argv[:] name = '' while search_args: if search_args[0].startswith('-'): name = '%s %s' % (name, sear...
python
def find_command(self, argv): """Given an argument list, find a command and return the processor and any remaining arguments. """ search_args = argv[:] name = '' while search_args: if search_args[0].startswith('-'): name = '%s %s' % (name, sear...
['def', 'find_command', '(', 'self', ',', 'argv', ')', ':', 'search_args', '=', 'argv', '[', ':', ']', 'name', '=', "''", 'while', 'search_args', ':', 'if', 'search_args', '[', '0', ']', '.', 'startswith', '(', "'-'", ')', ':', 'name', '=', "'%s %s'", '%', '(', 'name', ',', 'search_args', '[', '0', ']', ')', 'raise', '...
Given an argument list, find a command and return the processor and any remaining arguments.
['Given', 'an', 'argument', 'list', 'find', 'a', 'command', 'and', 'return', 'the', 'processor', 'and', 'any', 'remaining', 'arguments', '.']
train
https://github.com/TurboGears/gearbox/blob/df496ab28050ce6a4cc4c502488f5c5812f2baff/gearbox/commandmanager.py#L63-L89
7,575
gem/oq-engine
openquake/risklib/asset.py
TagCollection.get_tag
def get_tag(self, tagname, tagidx): """ :returns: the tag associated to the given tagname and tag index """ return '%s=%s' % (tagname, decode(getattr(self, tagname)[tagidx]))
python
def get_tag(self, tagname, tagidx): """ :returns: the tag associated to the given tagname and tag index """ return '%s=%s' % (tagname, decode(getattr(self, tagname)[tagidx]))
['def', 'get_tag', '(', 'self', ',', 'tagname', ',', 'tagidx', ')', ':', 'return', "'%s=%s'", '%', '(', 'tagname', ',', 'decode', '(', 'getattr', '(', 'self', ',', 'tagname', ')', '[', 'tagidx', ']', ')', ')']
:returns: the tag associated to the given tagname and tag index
[':', 'returns', ':', 'the', 'tag', 'associated', 'to', 'the', 'given', 'tagname', 'and', 'tag', 'index']
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/asset.py#L332-L336
7,576
QUANTAXIS/QUANTAXIS
QUANTAXIS/QAFetch/QAQuery_Advance.py
QA_fetch_future_min_adv
def QA_fetch_future_min_adv( code, start, end=None, frequence='1min', if_drop_index=True, collections=DATABASE.future_min): ''' '获取股票分钟线' :param code: :param start: :param end: :param frequence: :param if_drop_index: :param collections: :return...
python
def QA_fetch_future_min_adv( code, start, end=None, frequence='1min', if_drop_index=True, collections=DATABASE.future_min): ''' '获取股票分钟线' :param code: :param start: :param end: :param frequence: :param if_drop_index: :param collections: :return...
['def', 'QA_fetch_future_min_adv', '(', 'code', ',', 'start', ',', 'end', '=', 'None', ',', 'frequence', '=', "'1min'", ',', 'if_drop_index', '=', 'True', ',', 'collections', '=', 'DATABASE', '.', 'future_min', ')', ':', 'if', 'frequence', 'in', '[', "'1min'", ',', "'1m'", ']', ':', 'frequence', '=', "'1min'", 'elif', ...
'获取股票分钟线' :param code: :param start: :param end: :param frequence: :param if_drop_index: :param collections: :return:
['获取股票分钟线', ':', 'param', 'code', ':', ':', 'param', 'start', ':', ':', 'param', 'end', ':', ':', 'param', 'frequence', ':', ':', 'param', 'if_drop_index', ':', ':', 'param', 'collections', ':', ':', 'return', ':']
train
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QAQuery_Advance.py#L378-L430
7,577
hatemile/hatemile-for-python
hatemile/implementation/css.py
AccessibleCSSImplementation._speak_as_literal_punctuation_inherit
def _speak_as_literal_punctuation_inherit(self, element): """ Speak the punctuation for elements and descendants. :param element: The element. :type element: hatemile.util.html.htmldomelement.HTMLDOMElement """ self._reverse_speak_as(element, 'literal-punctuation') ...
python
def _speak_as_literal_punctuation_inherit(self, element): """ Speak the punctuation for elements and descendants. :param element: The element. :type element: hatemile.util.html.htmldomelement.HTMLDOMElement """ self._reverse_speak_as(element, 'literal-punctuation') ...
['def', '_speak_as_literal_punctuation_inherit', '(', 'self', ',', 'element', ')', ':', 'self', '.', '_reverse_speak_as', '(', 'element', ',', "'literal-punctuation'", ')', 'self', '.', '_reverse_speak_as', '(', 'element', ',', "'no-punctuation'", ')', 'self', '.', '_isolate_text_node', '(', 'element', ')', 'self', '.'...
Speak the punctuation for elements and descendants. :param element: The element. :type element: hatemile.util.html.htmldomelement.HTMLDOMElement
['Speak', 'the', 'punctuation', 'for', 'elements', 'and', 'descendants', '.']
train
https://github.com/hatemile/hatemile-for-python/blob/1e914f9aa09f6f8d78282af131311546ecba9fb8/hatemile/implementation/css.py#L816-L829
7,578
googleapis/google-cloud-python
dataproc/google/cloud/dataproc_v1beta2/gapic/cluster_controller_client.py
ClusterControllerClient.list_clusters
def list_clusters( self, project_id, region, filter_=None, page_size=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Lists all regions/{region}/clusters in a pr...
python
def list_clusters( self, project_id, region, filter_=None, page_size=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Lists all regions/{region}/clusters in a pr...
['def', 'list_clusters', '(', 'self', ',', 'project_id', ',', 'region', ',', 'filter_', '=', 'None', ',', 'page_size', '=', 'None', ',', 'retry', '=', 'google', '.', 'api_core', '.', 'gapic_v1', '.', 'method', '.', 'DEFAULT', ',', 'timeout', '=', 'google', '.', 'api_core', '.', 'gapic_v1', '.', 'method', '.', 'DEFAULT'...
Lists all regions/{region}/clusters in a project. Example: >>> from google.cloud import dataproc_v1beta2 >>> >>> client = dataproc_v1beta2.ClusterControllerClient() >>> >>> # TODO: Initialize `project_id`: >>> project_id = '' >...
['Lists', 'all', 'regions', '/', '{', 'region', '}', '/', 'clusters', 'in', 'a', 'project', '.']
train
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/dataproc/google/cloud/dataproc_v1beta2/gapic/cluster_controller_client.py#L820-L936
7,579
bsolomon1124/pyfinance
pyfinance/ols.py
RollingOLS._predicted
def _predicted(self): """The predicted values of y ('yhat').""" return np.squeeze( np.matmul(self.xwins, np.expand_dims(self.solution, axis=-1)) )
python
def _predicted(self): """The predicted values of y ('yhat').""" return np.squeeze( np.matmul(self.xwins, np.expand_dims(self.solution, axis=-1)) )
['def', '_predicted', '(', 'self', ')', ':', 'return', 'np', '.', 'squeeze', '(', 'np', '.', 'matmul', '(', 'self', '.', 'xwins', ',', 'np', '.', 'expand_dims', '(', 'self', '.', 'solution', ',', 'axis', '=', '-', '1', ')', ')', ')']
The predicted values of y ('yhat').
['The', 'predicted', 'values', 'of', 'y', '(', 'yhat', ')', '.']
train
https://github.com/bsolomon1124/pyfinance/blob/c95925209a809b4e648e79cbeaf7711d8e5ff1a6/pyfinance/ols.py#L430-L434
7,580
maxcountryman/flask-login
flask_login/login_manager.py
LoginManager.unauthorized
def unauthorized(self): ''' This is called when the user is required to log in. If you register a callback with :meth:`LoginManager.unauthorized_handler`, then it will be called. Otherwise, it will take the following actions: - Flash :attr:`LoginManager.login_message` to the...
python
def unauthorized(self): ''' This is called when the user is required to log in. If you register a callback with :meth:`LoginManager.unauthorized_handler`, then it will be called. Otherwise, it will take the following actions: - Flash :attr:`LoginManager.login_message` to the...
['def', 'unauthorized', '(', 'self', ')', ':', 'user_unauthorized', '.', 'send', '(', 'current_app', '.', '_get_current_object', '(', ')', ')', 'if', 'self', '.', 'unauthorized_callback', ':', 'return', 'self', '.', 'unauthorized_callback', '(', ')', 'if', 'request', '.', 'blueprint', 'in', 'self', '.', 'blueprint_logi...
This is called when the user is required to log in. If you register a callback with :meth:`LoginManager.unauthorized_handler`, then it will be called. Otherwise, it will take the following actions: - Flash :attr:`LoginManager.login_message` to the user. - If the app is using bl...
['This', 'is', 'called', 'when', 'the', 'user', 'is', 'required', 'to', 'log', 'in', '.', 'If', 'you', 'register', 'a', 'callback', 'with', ':', 'meth', ':', 'LoginManager', '.', 'unauthorized_handler', 'then', 'it', 'will', 'be', 'called', '.', 'Otherwise', 'it', 'will', 'take', 'the', 'following', 'actions', ':']
train
https://github.com/maxcountryman/flask-login/blob/d22f80d166ee260d44e0d2d9ea973b784ef3621b/flask_login/login_manager.py#L122-L176
7,581
Alir3z4/django-databrowse
django_databrowse/sites.py
DatabrowseSite.unregister
def unregister(self, *model_list): """ Unregisters the given model(s). If a model isn't already registered, this will raise NotRegistered. """ for model in model_list: if model not in self.registry: raise NotRegistered('The model %s is not registered'...
python
def unregister(self, *model_list): """ Unregisters the given model(s). If a model isn't already registered, this will raise NotRegistered. """ for model in model_list: if model not in self.registry: raise NotRegistered('The model %s is not registered'...
['def', 'unregister', '(', 'self', ',', '*', 'model_list', ')', ':', 'for', 'model', 'in', 'model_list', ':', 'if', 'model', 'not', 'in', 'self', '.', 'registry', ':', 'raise', 'NotRegistered', '(', "'The model %s is not registered'", '%', 'model', '.', '__name__', ')', 'del', 'self', '.', 'registry', '[', 'model', ']'...
Unregisters the given model(s). If a model isn't already registered, this will raise NotRegistered.
['Unregisters', 'the', 'given', 'model', '(', 's', ')', '.']
train
https://github.com/Alir3z4/django-databrowse/blob/4469495cd47a0da506ddf4e8cc752c2f453e0339/django_databrowse/sites.py#L138-L148
7,582
houluy/chessboard
chessboard/__init__.py
Chessboard.set_pos
def set_pos(self, pos, check=False): '''Set a chess''' self.validate_pos(pos) x, y = pos user = self.get_player() self.history[self._game_round] = copy.deepcopy(self.pos) self.pos[x][y] = user pos_str = self._cal_key(pos) self._pos_dict[pos_str] = user ...
python
def set_pos(self, pos, check=False): '''Set a chess''' self.validate_pos(pos) x, y = pos user = self.get_player() self.history[self._game_round] = copy.deepcopy(self.pos) self.pos[x][y] = user pos_str = self._cal_key(pos) self._pos_dict[pos_str] = user ...
['def', 'set_pos', '(', 'self', ',', 'pos', ',', 'check', '=', 'False', ')', ':', 'self', '.', 'validate_pos', '(', 'pos', ')', 'x', ',', 'y', '=', 'pos', 'user', '=', 'self', '.', 'get_player', '(', ')', 'self', '.', 'history', '[', 'self', '.', '_game_round', ']', '=', 'copy', '.', 'deepcopy', '(', 'self', '.', 'pos'...
Set a chess
['Set', 'a', 'chess']
train
https://github.com/houluy/chessboard/blob/b834819d93d71b492f27780a58dfbb3a107d7e85/chessboard/__init__.py#L235-L250
7,583
agile4you/bottle-neck
bottle_neck/cbv.py
plugin_method
def plugin_method(*plugin_names): """Plugin Method decorator. Signs a web handler function with the plugins to be applied as attributes. Args: plugin_names (list): A list of plugin callable names Returns: A wrapped handler callable. Examples: >>> @plugin_method('json', 'bi...
python
def plugin_method(*plugin_names): """Plugin Method decorator. Signs a web handler function with the plugins to be applied as attributes. Args: plugin_names (list): A list of plugin callable names Returns: A wrapped handler callable. Examples: >>> @plugin_method('json', 'bi...
['def', 'plugin_method', '(', '*', 'plugin_names', ')', ':', 'def', 'wrapper', '(', 'callable_obj', ')', ':', 'for', 'plugin_name', 'in', 'plugin_names', ':', 'if', 'not', 'hasattr', '(', 'callable_obj', ',', 'plugin_name', ')', ':', 'setattr', '(', 'callable_obj', ',', 'plugin_name', ',', 'True', ')', 'return', 'calla...
Plugin Method decorator. Signs a web handler function with the plugins to be applied as attributes. Args: plugin_names (list): A list of plugin callable names Returns: A wrapped handler callable. Examples: >>> @plugin_method('json', 'bill') ... def method(): .....
['Plugin', 'Method', 'decorator', '.', 'Signs', 'a', 'web', 'handler', 'function', 'with', 'the', 'plugins', 'to', 'be', 'applied', 'as', 'attributes', '.']
train
https://github.com/agile4you/bottle-neck/blob/ebc670a4b178255473d68e9b4122ba04e38f4810/bottle_neck/cbv.py#L112-L138
7,584
sorgerlab/indra
rest_api/api.py
cwms_process_text
def cwms_process_text(): """Process text with CWMS and return INDRA Statements.""" if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) text = body.get('text') cp = cwms.process_text(text) return _stmts_from_proc(cp)
python
def cwms_process_text(): """Process text with CWMS and return INDRA Statements.""" if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) text = body.get('text') cp = cwms.process_text(text) return _stmts_from_proc(cp)
['def', 'cwms_process_text', '(', ')', ':', 'if', 'request', '.', 'method', '==', "'OPTIONS'", ':', 'return', '{', '}', 'response', '=', 'request', '.', 'body', '.', 'read', '(', ')', '.', 'decode', '(', "'utf-8'", ')', 'body', '=', 'json', '.', 'loads', '(', 'response', ')', 'text', '=', 'body', '.', 'get', '(', "'tex...
Process text with CWMS and return INDRA Statements.
['Process', 'text', 'with', 'CWMS', 'and', 'return', 'INDRA', 'Statements', '.']
train
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/rest_api/api.py#L246-L254
7,585
lappis-unb/salic-ml
tasks.py
update_data
def update_data(ctx, models=True, pickles=False, f=False): """ Updates local django db projects and pickle files using salic database from MinC Pickles are saved in /data/raw/ from sql queries in /data/scripts/ Models are created from /data/scripts/models/ """ if pickles: save_sql_to...
python
def update_data(ctx, models=True, pickles=False, f=False): """ Updates local django db projects and pickle files using salic database from MinC Pickles are saved in /data/raw/ from sql queries in /data/scripts/ Models are created from /data/scripts/models/ """ if pickles: save_sql_to...
['def', 'update_data', '(', 'ctx', ',', 'models', '=', 'True', ',', 'pickles', '=', 'False', ',', 'f', '=', 'False', ')', ':', 'if', 'pickles', ':', 'save_sql_to_files', '(', 'f', ')', 'if', 'models', ':', 'if', 'f', ':', 'manage', '(', 'ctx', ',', "'create_models_from_sql --force True'", ',', 'env', '=', '{', '}', ')'...
Updates local django db projects and pickle files using salic database from MinC Pickles are saved in /data/raw/ from sql queries in /data/scripts/ Models are created from /data/scripts/models/
['Updates', 'local', 'django', 'db', 'projects', 'and', 'pickle', 'files', 'using', 'salic', 'database', 'from', 'MinC', 'Pickles', 'are', 'saved', 'in', '/', 'data', '/', 'raw', '/', 'from', 'sql', 'queries', 'in', '/', 'data', '/', 'scripts', '/', 'Models', 'are', 'created', 'from', '/', 'data', '/', 'scripts', '/', ...
train
https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/tasks.py#L72-L85
7,586
thomasdelaet/python-velbus
velbus/module.py
Module.on_message
def on_message(self, message): """ Process received message """ if message.address != self._address: return if isinstance(message, velbus.ChannelNamePart1Message) or isinstance(message, velbus.ChannelNamePart1Message2): self._process_channel_name_message(1...
python
def on_message(self, message): """ Process received message """ if message.address != self._address: return if isinstance(message, velbus.ChannelNamePart1Message) or isinstance(message, velbus.ChannelNamePart1Message2): self._process_channel_name_message(1...
['def', 'on_message', '(', 'self', ',', 'message', ')', ':', 'if', 'message', '.', 'address', '!=', 'self', '.', '_address', ':', 'return', 'if', 'isinstance', '(', 'message', ',', 'velbus', '.', 'ChannelNamePart1Message', ')', 'or', 'isinstance', '(', 'message', ',', 'velbus', '.', 'ChannelNamePart1Message2', ')', ':'...
Process received message
['Process', 'received', 'message']
train
https://github.com/thomasdelaet/python-velbus/blob/af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd/velbus/module.py#L65-L80
7,587
JensAstrup/pyOutlook
pyOutlook/core/message.py
Message.move_to
def move_to(self, folder): """Moves the email to the folder specified by the folder parameter. Args: folder: A string containing the folder ID the message should be moved to, or a Folder instance """ if isinstance(folder, Folder): self.move_to(folder.id) ...
python
def move_to(self, folder): """Moves the email to the folder specified by the folder parameter. Args: folder: A string containing the folder ID the message should be moved to, or a Folder instance """ if isinstance(folder, Folder): self.move_to(folder.id) ...
['def', 'move_to', '(', 'self', ',', 'folder', ')', ':', 'if', 'isinstance', '(', 'folder', ',', 'Folder', ')', ':', 'self', '.', 'move_to', '(', 'folder', '.', 'id', ')', 'else', ':', 'self', '.', '_move_to', '(', 'folder', ')']
Moves the email to the folder specified by the folder parameter. Args: folder: A string containing the folder ID the message should be moved to, or a Folder instance
['Moves', 'the', 'email', 'to', 'the', 'folder', 'specified', 'by', 'the', 'folder', 'parameter', '.']
train
https://github.com/JensAstrup/pyOutlook/blob/f4ca9d4a8629c0a41f78102ce84fab702a841167/pyOutlook/core/message.py#L397-L407
7,588
rkhleics/wagtailmenus
wagtailmenus/models/menus.py
Menu.render_to_template
def render_to_template(self): """ Render the current menu instance to a template and return a string """ context_data = self.get_context_data() template = self.get_template() context_data['current_template'] = template.template.name return template.render(context...
python
def render_to_template(self): """ Render the current menu instance to a template and return a string """ context_data = self.get_context_data() template = self.get_template() context_data['current_template'] = template.template.name return template.render(context...
['def', 'render_to_template', '(', 'self', ')', ':', 'context_data', '=', 'self', '.', 'get_context_data', '(', ')', 'template', '=', 'self', '.', 'get_template', '(', ')', 'context_data', '[', "'current_template'", ']', '=', 'template', '.', 'template', '.', 'name', 'return', 'template', '.', 'render', '(', 'context_d...
Render the current menu instance to a template and return a string
['Render', 'the', 'current', 'menu', 'instance', 'to', 'a', 'template', 'and', 'return', 'a', 'string']
train
https://github.com/rkhleics/wagtailmenus/blob/a41f240bed0d362e0d4dd4ef04a230f2b1827a93/wagtailmenus/models/menus.py#L222-L230
7,589
linkedin/luminol
src/luminol/algorithms/anomaly_detector_algorithms/default_detector.py
DefaultDetector._set_scores
def _set_scores(self): """ Set anomaly scores using a weighted sum. """ anom_scores_ema = self.exp_avg_detector.run() anom_scores_deri = self.derivative_detector.run() anom_scores = {} for timestamp in anom_scores_ema.timestamps: # Compute a weighted a...
python
def _set_scores(self): """ Set anomaly scores using a weighted sum. """ anom_scores_ema = self.exp_avg_detector.run() anom_scores_deri = self.derivative_detector.run() anom_scores = {} for timestamp in anom_scores_ema.timestamps: # Compute a weighted a...
['def', '_set_scores', '(', 'self', ')', ':', 'anom_scores_ema', '=', 'self', '.', 'exp_avg_detector', '.', 'run', '(', ')', 'anom_scores_deri', '=', 'self', '.', 'derivative_detector', '.', 'run', '(', ')', 'anom_scores', '=', '{', '}', 'for', 'timestamp', 'in', 'anom_scores_ema', '.', 'timestamps', ':', '# Compute a ...
Set anomaly scores using a weighted sum.
['Set', 'anomaly', 'scores', 'using', 'a', 'weighted', 'sum', '.']
train
https://github.com/linkedin/luminol/blob/42e4ab969b774ff98f902d064cb041556017f635/src/luminol/algorithms/anomaly_detector_algorithms/default_detector.py#L35-L49
7,590
prthkms/alex
alex/duckduckgo.py
parse_result
def parse_result(result): """parse_result(json result) -- print the web query according to the type of result from duckduckgo. """ if(result['Type'] == 'D'): print """There is more than one answer for this. Try making your query\ more specific. For example, if you want to learn about apple the company\ and ...
python
def parse_result(result): """parse_result(json result) -- print the web query according to the type of result from duckduckgo. """ if(result['Type'] == 'D'): print """There is more than one answer for this. Try making your query\ more specific. For example, if you want to learn about apple the company\ and ...
['def', 'parse_result', '(', 'result', ')', ':', 'if', '(', 'result', '[', "'Type'", ']', '==', "'D'", ')', ':', 'print', '"""There is more than one answer for this. Try making your query\\\n\t\tmore specific. For example, if you want to learn about apple the company\\\n\t\tand not apple the fruit, try something like a...
parse_result(json result) -- print the web query according to the type of result from duckduckgo.
['parse_result', '(', 'json', 'result', ')', '--', 'print', 'the', 'web', 'query', 'according', 'to', 'the', 'type', 'of', 'result', 'from', 'duckduckgo', '.']
train
https://github.com/prthkms/alex/blob/79d3167c877e94cc07db0aab55a35857fac67ef7/alex/duckduckgo.py#L8-L28
7,591
saltstack/salt
salt/modules/file.py
blockreplace
def blockreplace(path, marker_start='#-- start managed zone --', marker_end='#-- end managed zone --', content='', append_if_not_found=False, prepend_if_not_found=False, backup='.bak', dry_run=False, show_changes=True, append_newline=False, ...
python
def blockreplace(path, marker_start='#-- start managed zone --', marker_end='#-- end managed zone --', content='', append_if_not_found=False, prepend_if_not_found=False, backup='.bak', dry_run=False, show_changes=True, append_newline=False, ...
['def', 'blockreplace', '(', 'path', ',', 'marker_start', '=', "'#-- start managed zone --'", ',', 'marker_end', '=', "'#-- end managed zone --'", ',', 'content', '=', "''", ',', 'append_if_not_found', '=', 'False', ',', 'prepend_if_not_found', '=', 'False', ',', 'backup', '=', "'.bak'", ',', 'dry_run', '=', 'False', '...
.. versionadded:: 2014.1.0 Replace content of a text block in a file, delimited by line markers A block of content delimited by comments can help you manage several lines entries without worrying about old entries removal. .. note:: This function will store two copies of the file in-memory (...
['..', 'versionadded', '::', '2014', '.', '1', '.', '0']
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/file.py#L2453-L2776
7,592
Huong-nt/flask-rak
flask_rak/core.py
RAK.intent
def intent(self, intent_name): """Decorator routes an Rogo IntentRequest. Functions decorated as an intent are registered as the view function for the Intent's URL, and provide the backend responses to give your Skill its functionality. @ask.intent('WeatherIntent') def weather(ci...
python
def intent(self, intent_name): """Decorator routes an Rogo IntentRequest. Functions decorated as an intent are registered as the view function for the Intent's URL, and provide the backend responses to give your Skill its functionality. @ask.intent('WeatherIntent') def weather(ci...
['def', 'intent', '(', 'self', ',', 'intent_name', ')', ':', 'def', 'decorator', '(', 'f', ')', ':', 'self', '.', '_intent_view_funcs', '[', 'intent_name', ']', '=', 'f', '@', 'wraps', '(', 'f', ')', 'def', 'wrapper', '(', '*', 'args', ',', '*', '*', 'kw', ')', ':', 'self', '.', '_flask_view_func', '(', '*', 'args', ',...
Decorator routes an Rogo IntentRequest. Functions decorated as an intent are registered as the view function for the Intent's URL, and provide the backend responses to give your Skill its functionality. @ask.intent('WeatherIntent') def weather(city): return statement('I predi...
['Decorator', 'routes', 'an', 'Rogo', 'IntentRequest', '.', 'Functions', 'decorated', 'as', 'an', 'intent', 'are', 'registered', 'as', 'the', 'view', 'function', 'for', 'the', 'Intent', 's', 'URL', 'and', 'provide', 'the', 'backend', 'responses', 'to', 'give', 'your', 'Skill', 'its', 'functionality', '.']
train
https://github.com/Huong-nt/flask-rak/blob/ffe16b0fc3d49e83c1d220c445ce14632219f69d/flask_rak/core.py#L155-L172
7,593
matthias-k/cyipopt
setup.py
pkgconfig
def pkgconfig(*packages, **kw): """Based on http://code.activestate.com/recipes/502261-python-distutils-pkg-config/#c2""" flag_map = {'-I': 'include_dirs', '-L': 'library_dirs', '-l': 'libraries'} output = sp.Popen(["pkg-config", "--libs", "--cflags"] + list(packages), stdout=sp.PIPE)...
python
def pkgconfig(*packages, **kw): """Based on http://code.activestate.com/recipes/502261-python-distutils-pkg-config/#c2""" flag_map = {'-I': 'include_dirs', '-L': 'library_dirs', '-l': 'libraries'} output = sp.Popen(["pkg-config", "--libs", "--cflags"] + list(packages), stdout=sp.PIPE)...
['def', 'pkgconfig', '(', '*', 'packages', ',', '*', '*', 'kw', ')', ':', 'flag_map', '=', '{', "'-I'", ':', "'include_dirs'", ',', "'-L'", ':', "'library_dirs'", ',', "'-l'", ':', "'libraries'", '}', 'output', '=', 'sp', '.', 'Popen', '(', '[', '"pkg-config"', ',', '"--libs"', ',', '"--cflags"', ']', '+', 'list', '(',...
Based on http://code.activestate.com/recipes/502261-python-distutils-pkg-config/#c2
['Based', 'on', 'http', ':', '//', 'code', '.', 'activestate', '.', 'com', '/', 'recipes', '/', '502261', '-', 'python', '-', 'distutils', '-', 'pkg', '-', 'config', '/', '#c2']
train
https://github.com/matthias-k/cyipopt/blob/ed03f54de2e0b8c8ba4c0aa18ab9ab6c8846bc19/setup.py#L48-L64
7,594
sighingnow/parsec.py
src/parsec/__init__.py
one_of
def one_of(s): '''Parser a char from specified string.''' @Parser def one_of_parser(text, index=0): if index < len(text) and text[index] in s: return Value.success(index + 1, text[index]) else: return Value.failure(index, 'one of {}'.format(s)) return one_of_parse...
python
def one_of(s): '''Parser a char from specified string.''' @Parser def one_of_parser(text, index=0): if index < len(text) and text[index] in s: return Value.success(index + 1, text[index]) else: return Value.failure(index, 'one of {}'.format(s)) return one_of_parse...
['def', 'one_of', '(', 's', ')', ':', '@', 'Parser', 'def', 'one_of_parser', '(', 'text', ',', 'index', '=', '0', ')', ':', 'if', 'index', '<', 'len', '(', 'text', ')', 'and', 'text', '[', 'index', ']', 'in', 's', ':', 'return', 'Value', '.', 'success', '(', 'index', '+', '1', ',', 'text', '[', 'index', ']', ')', 'else...
Parser a char from specified string.
['Parser', 'a', 'char', 'from', 'specified', 'string', '.']
train
https://github.com/sighingnow/parsec.py/blob/ed50e1e259142757470b925f8d20dfe5ad223af0/src/parsec/__init__.py#L567-L575
7,595
koszullab/metaTOR
metator/scripts/figures.py
draw_sparse_matrix
def draw_sparse_matrix( array_filename, output_image, vmax=DEFAULT_SATURATION_THRESHOLD, max_size_matrix=DEFAULT_MAX_SIZE_MATRIX, ): """Draw a quick preview of a sparse matrix with automated binning and normalization. """ matrix = np.loadtxt(array_filename, dtype=np.int32, skiprows=1) ...
python
def draw_sparse_matrix( array_filename, output_image, vmax=DEFAULT_SATURATION_THRESHOLD, max_size_matrix=DEFAULT_MAX_SIZE_MATRIX, ): """Draw a quick preview of a sparse matrix with automated binning and normalization. """ matrix = np.loadtxt(array_filename, dtype=np.int32, skiprows=1) ...
['def', 'draw_sparse_matrix', '(', 'array_filename', ',', 'output_image', ',', 'vmax', '=', 'DEFAULT_SATURATION_THRESHOLD', ',', 'max_size_matrix', '=', 'DEFAULT_MAX_SIZE_MATRIX', ',', ')', ':', 'matrix', '=', 'np', '.', 'loadtxt', '(', 'array_filename', ',', 'dtype', '=', 'np', '.', 'int32', ',', 'skiprows', '=', '1',...
Draw a quick preview of a sparse matrix with automated binning and normalization.
['Draw', 'a', 'quick', 'preview', 'of', 'a', 'sparse', 'matrix', 'with', 'automated', 'binning', 'and', 'normalization', '.']
train
https://github.com/koszullab/metaTOR/blob/0c1203d1dffedfa5ea380c0335b4baa9cfb7e89a/metator/scripts/figures.py#L75-L100
7,596
protream/iquery
iquery/lyrics.py
query
def query(song_name): """CLI: $ iquery -l song_name """ r = requests_get(SONG_SEARCH_URL.format(song_name)) try: # Get the first result. song_url = re.search(r'(http://www.xiami.com/song/\d+)', r.text).group(0) except AttributeError: exit_after_echo(SONG_NOT_FOUND) ...
python
def query(song_name): """CLI: $ iquery -l song_name """ r = requests_get(SONG_SEARCH_URL.format(song_name)) try: # Get the first result. song_url = re.search(r'(http://www.xiami.com/song/\d+)', r.text).group(0) except AttributeError: exit_after_echo(SONG_NOT_FOUND) ...
['def', 'query', '(', 'song_name', ')', ':', 'r', '=', 'requests_get', '(', 'SONG_SEARCH_URL', '.', 'format', '(', 'song_name', ')', ')', 'try', ':', '# Get the first result.', 'song_url', '=', 're', '.', 'search', '(', "r'(http://www.xiami.com/song/\\d+)'", ',', 'r', '.', 'text', ')', '.', 'group', '(', '0', ')', 'exc...
CLI: $ iquery -l song_name
['CLI', ':']
train
https://github.com/protream/iquery/blob/7272e68af610f1dd63cf695209cfa44b75adc0e6/iquery/lyrics.py#L58-L71
7,597
estnltk/estnltk
estnltk/text.py
Text.timex_starts
def timex_starts(self): """The list of start positions of ``timexes`` layer elements.""" if not self.is_tagged(TIMEXES): self.tag_timexes() return self.starts(TIMEXES)
python
def timex_starts(self): """The list of start positions of ``timexes`` layer elements.""" if not self.is_tagged(TIMEXES): self.tag_timexes() return self.starts(TIMEXES)
['def', 'timex_starts', '(', 'self', ')', ':', 'if', 'not', 'self', '.', 'is_tagged', '(', 'TIMEXES', ')', ':', 'self', '.', 'tag_timexes', '(', ')', 'return', 'self', '.', 'starts', '(', 'TIMEXES', ')']
The list of start positions of ``timexes`` layer elements.
['The', 'list', 'of', 'start', 'positions', 'of', 'timexes', 'layer', 'elements', '.']
train
https://github.com/estnltk/estnltk/blob/28ae334a68a0673072febc318635f04da0dcc54a/estnltk/text.py#L923-L927
7,598
kevin-brown/drf-json-api
rest_framework_json_api/renderers.py
JsonApiMixin.render
def render(self, data, accepted_media_type=None, renderer_context=None): """Convert native data to JSON API Tries each of the methods in `wrappers`, using the first successful one, or raises `WrapperNotApplicable`. """ wrapper = None success = False for wrapper...
python
def render(self, data, accepted_media_type=None, renderer_context=None): """Convert native data to JSON API Tries each of the methods in `wrappers`, using the first successful one, or raises `WrapperNotApplicable`. """ wrapper = None success = False for wrapper...
['def', 'render', '(', 'self', ',', 'data', ',', 'accepted_media_type', '=', 'None', ',', 'renderer_context', '=', 'None', ')', ':', 'wrapper', '=', 'None', 'success', '=', 'False', 'for', 'wrapper_name', 'in', 'self', '.', 'wrappers', ':', 'wrapper_method', '=', 'getattr', '(', 'self', ',', 'wrapper_name', ')', 'try',...
Convert native data to JSON API Tries each of the methods in `wrappers`, using the first successful one, or raises `WrapperNotApplicable`.
['Convert', 'native', 'data', 'to', 'JSON', 'API']
train
https://github.com/kevin-brown/drf-json-api/blob/664643bd02c0d92eadbd1f8c9d8507adf0538df6/rest_framework_json_api/renderers.py#L47-L77
7,599
pandas-dev/pandas
pandas/core/indexing.py
_NDFrameIndexer._multi_take
def _multi_take(self, tup): """ Create the indexers for the passed tuple of keys, and execute the take operation. This allows the take operation to be executed all at once - rather than once for each dimension - improving efficiency. Parameters ---------- tup : t...
python
def _multi_take(self, tup): """ Create the indexers for the passed tuple of keys, and execute the take operation. This allows the take operation to be executed all at once - rather than once for each dimension - improving efficiency. Parameters ---------- tup : t...
['def', '_multi_take', '(', 'self', ',', 'tup', ')', ':', '# GH 836', 'o', '=', 'self', '.', 'obj', 'd', '=', '{', 'axis', ':', 'self', '.', '_get_listlike_indexer', '(', 'key', ',', 'axis', ')', 'for', '(', 'key', ',', 'axis', ')', 'in', 'zip', '(', 'tup', ',', 'o', '.', '_AXIS_ORDERS', ')', '}', 'return', 'o', '.', '...
Create the indexers for the passed tuple of keys, and execute the take operation. This allows the take operation to be executed all at once - rather than once for each dimension - improving efficiency. Parameters ---------- tup : tuple Tuple of indexers, one per axis...
['Create', 'the', 'indexers', 'for', 'the', 'passed', 'tuple', 'of', 'keys', 'and', 'execute', 'the', 'take', 'operation', '.', 'This', 'allows', 'the', 'take', 'operation', 'to', 'be', 'executed', 'all', 'at', 'once', '-', 'rather', 'than', 'once', 'for', 'each', 'dimension', '-', 'improving', 'efficiency', '.']
train
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexing.py#L914-L933