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
9,200
edx/pa11ycrawler
pa11ycrawler/pipelines/pa11y.py
write_pa11y_results
def write_pa11y_results(item, pa11y_results, data_dir): """ Write the output from pa11y into a data file. """ data = dict(item) data['pa11y'] = pa11y_results # it would be nice to use the URL as the filename, # but that gets complicated (long URLs, special characters, etc) # so we'll ma...
python
def write_pa11y_results(item, pa11y_results, data_dir): """ Write the output from pa11y into a data file. """ data = dict(item) data['pa11y'] = pa11y_results # it would be nice to use the URL as the filename, # but that gets complicated (long URLs, special characters, etc) # so we'll ma...
['def', 'write_pa11y_results', '(', 'item', ',', 'pa11y_results', ',', 'data_dir', ')', ':', 'data', '=', 'dict', '(', 'item', ')', 'data', '[', "'pa11y'", ']', '=', 'pa11y_results', '# it would be nice to use the URL as the filename,', '# but that gets complicated (long URLs, special characters, etc)', "# so we'll mak...
Write the output from pa11y into a data file.
['Write', 'the', 'output', 'from', 'pa11y', 'into', 'a', 'data', 'file', '.']
train
https://github.com/edx/pa11ycrawler/blob/fc672d4524463bc050ade4c7c97801c0d5bf8c9e/pa11ycrawler/pipelines/pa11y.py#L141-L161
9,201
fermiPy/fermipy
fermipy/diffuse/name_policy.py
NameFactory._replace_none
def _replace_none(self, aDict): """ Replace all None values in a dict with 'none' """ for k, v in aDict.items(): if v is None: aDict[k] = 'none'
python
def _replace_none(self, aDict): """ Replace all None values in a dict with 'none' """ for k, v in aDict.items(): if v is None: aDict[k] = 'none'
['def', '_replace_none', '(', 'self', ',', 'aDict', ')', ':', 'for', 'k', ',', 'v', 'in', 'aDict', '.', 'items', '(', ')', ':', 'if', 'v', 'is', 'None', ':', 'aDict', '[', 'k', ']', '=', "'none'"]
Replace all None values in a dict with 'none'
['Replace', 'all', 'None', 'values', 'in', 'a', 'dict', 'with', 'none']
train
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/diffuse/name_policy.py#L136-L140
9,202
reingart/pyafipws
wslpg.py
WSLPG.CrearAjusteBase
def CrearAjusteBase(self, pto_emision=1, nro_orden=None, # unificado, contrato, papel coe_ajustado=None, # unificado nro_contrato=None, # contrato tipo_formulario=None, # papel nro_formul...
python
def CrearAjusteBase(self, pto_emision=1, nro_orden=None, # unificado, contrato, papel coe_ajustado=None, # unificado nro_contrato=None, # contrato tipo_formulario=None, # papel nro_formul...
['def', 'CrearAjusteBase', '(', 'self', ',', 'pto_emision', '=', '1', ',', 'nro_orden', '=', 'None', ',', '# unificado, contrato, papel', 'coe_ajustado', '=', 'None', ',', '# unificado', 'nro_contrato', '=', 'None', ',', '# contrato', 'tipo_formulario', '=', 'None', ',', '# papel', 'nro_formulario', '=', 'None', ',', '...
Inicializa internamente los datos de una liquidación para ajustar
['Inicializa', 'internamente', 'los', 'datos', 'de', 'una', 'liquidación', 'para', 'ajustar']
train
https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/wslpg.py#L1188-L1279
9,203
ArchiveTeam/wpull
wpull/writer.py
BaseFileWriterSession.set_timestamp
def set_timestamp(cls, filename: str, response: HTTPResponse): '''Set the Last-Modified timestamp onto the given file. Args: filename: The path of the file response: Response ''' last_modified = response.fields.get('Last-Modified') if not last_modified: ...
python
def set_timestamp(cls, filename: str, response: HTTPResponse): '''Set the Last-Modified timestamp onto the given file. Args: filename: The path of the file response: Response ''' last_modified = response.fields.get('Last-Modified') if not last_modified: ...
['def', 'set_timestamp', '(', 'cls', ',', 'filename', ':', 'str', ',', 'response', ':', 'HTTPResponse', ')', ':', 'last_modified', '=', 'response', '.', 'fields', '.', 'get', '(', "'Last-Modified'", ')', 'if', 'not', 'last_modified', ':', 'return', 'try', ':', 'last_modified', '=', 'email', '.', 'utils', '.', 'parsedat...
Set the Last-Modified timestamp onto the given file. Args: filename: The path of the file response: Response
['Set', 'the', 'Last', '-', 'Modified', 'timestamp', 'onto', 'the', 'given', 'file', '.']
train
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/writer.py#L126-L146
9,204
log2timeline/dfvfs
dfvfs/file_io/lvm_file_io.py
LVMFile._Open
def _Open(self, path_spec=None, mode='rb'): """Opens the file-like object defined by path specification. Args: path_spec (PathSpec): path specification. mode (Optional[str]): file access mode. Raises: AccessError: if the access to open the file was denied. IOError: if the file-like...
python
def _Open(self, path_spec=None, mode='rb'): """Opens the file-like object defined by path specification. Args: path_spec (PathSpec): path specification. mode (Optional[str]): file access mode. Raises: AccessError: if the access to open the file was denied. IOError: if the file-like...
['def', '_Open', '(', 'self', ',', 'path_spec', '=', 'None', ',', 'mode', '=', "'rb'", ')', ':', 'if', 'not', 'path_spec', ':', 'raise', 'ValueError', '(', "'Missing path specfication.'", ')', 'volume_index', '=', 'lvm', '.', 'LVMPathSpecGetVolumeIndex', '(', 'path_spec', ')', 'if', 'volume_index', 'is', 'None', ':', '...
Opens the file-like object defined by path specification. Args: path_spec (PathSpec): path specification. mode (Optional[str]): file access mode. Raises: AccessError: if the access to open the file was denied. IOError: if the file-like object could not be opened. OSError: if the ...
['Opens', 'the', 'file', '-', 'like', 'object', 'defined', 'by', 'path', 'specification', '.']
train
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/file_io/lvm_file_io.py#L34-L67
9,205
hozn/stravalib
stravalib/attributes.py
EntityAttribute.unmarshal
def unmarshal(self, value, bind_client=None): """ Cast the specified value to the entity type. """ #self.log.debug("Unmarshall {0!r}: {1!r}".format(self, value)) if not isinstance(value, self.type): o = self.type() if bind_client is not None and hasattr(o....
python
def unmarshal(self, value, bind_client=None): """ Cast the specified value to the entity type. """ #self.log.debug("Unmarshall {0!r}: {1!r}".format(self, value)) if not isinstance(value, self.type): o = self.type() if bind_client is not None and hasattr(o....
['def', 'unmarshal', '(', 'self', ',', 'value', ',', 'bind_client', '=', 'None', ')', ':', '#self.log.debug("Unmarshall {0!r}: {1!r}".format(self, value))', 'if', 'not', 'isinstance', '(', 'value', ',', 'self', '.', 'type', ')', ':', 'o', '=', 'self', '.', 'type', '(', ')', 'if', 'bind_client', 'is', 'not', 'None', 'an...
Cast the specified value to the entity type.
['Cast', 'the', 'specified', 'value', 'to', 'the', 'entity', 'type', '.']
train
https://github.com/hozn/stravalib/blob/5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f/stravalib/attributes.py#L337-L357
9,206
mlperf/training
image_classification/tensorflow/official/resnet/imagenet_main.py
parse_record
def parse_record(raw_record, is_training, dtype): """Parses a record containing a training example of an image. The input record is parsed into a label and image, and the image is passed through preprocessing steps (cropping, flipping, and so on). Args: raw_record: scalar Tensor tf.string containing a ser...
python
def parse_record(raw_record, is_training, dtype): """Parses a record containing a training example of an image. The input record is parsed into a label and image, and the image is passed through preprocessing steps (cropping, flipping, and so on). Args: raw_record: scalar Tensor tf.string containing a ser...
['def', 'parse_record', '(', 'raw_record', ',', 'is_training', ',', 'dtype', ')', ':', 'image_buffer', ',', 'label', '=', '_parse_example_proto', '(', 'raw_record', ')', 'image', '=', 'imagenet_preprocessing', '.', 'preprocess_image', '(', 'image_buffer', '=', 'image_buffer', ',', 'output_height', '=', '_DEFAULT_IMAGE_...
Parses a record containing a training example of an image. The input record is parsed into a label and image, and the image is passed through preprocessing steps (cropping, flipping, and so on). Args: raw_record: scalar Tensor tf.string containing a serialized Example protocol buffer. is_training:...
['Parses', 'a', 'record', 'containing', 'a', 'training', 'example', 'of', 'an', 'image', '.']
train
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/image_classification/tensorflow/official/resnet/imagenet_main.py#L120-L145
9,207
flatangle/flatlib
flatlib/angle.py
slistStr
def slistStr(slist): """ Converts signed list to angle string. """ slist = _fixSlist(slist) string = ':'.join(['%02d' % x for x in slist[1:]]) return slist[0] + string
python
def slistStr(slist): """ Converts signed list to angle string. """ slist = _fixSlist(slist) string = ':'.join(['%02d' % x for x in slist[1:]]) return slist[0] + string
['def', 'slistStr', '(', 'slist', ')', ':', 'slist', '=', '_fixSlist', '(', 'slist', ')', 'string', '=', "':'", '.', 'join', '(', '[', "'%02d'", '%', 'x', 'for', 'x', 'in', 'slist', '[', '1', ':', ']', ']', ')', 'return', 'slist', '[', '0', ']', '+', 'string']
Converts signed list to angle string.
['Converts', 'signed', 'list', 'to', 'angle', 'string', '.']
train
https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/angle.py#L76-L80
9,208
horazont/aioxmpp
aioxmpp/im/service.py
ConversationService._add_conversation
def _add_conversation(self, conversation): """ Add the conversation and fire the :meth:`on_conversation_added` event. :param conversation: The conversation object to add. :type conversation: :class:`~.AbstractConversation` The conversation is added to the internal list of conve...
python
def _add_conversation(self, conversation): """ Add the conversation and fire the :meth:`on_conversation_added` event. :param conversation: The conversation object to add. :type conversation: :class:`~.AbstractConversation` The conversation is added to the internal list of conve...
['def', '_add_conversation', '(', 'self', ',', 'conversation', ')', ':', 'handler', '=', 'functools', '.', 'partial', '(', 'self', '.', '_handle_conversation_exit', ',', 'conversation', ')', 'tokens', '=', '[', ']', 'def', 'linked_token', '(', 'signal', ',', 'handler', ')', ':', 'return', 'signal', ',', 'signal', '.', ...
Add the conversation and fire the :meth:`on_conversation_added` event. :param conversation: The conversation object to add. :type conversation: :class:`~.AbstractConversation` The conversation is added to the internal list of conversations which can be queried at :attr:`conversations`....
['Add', 'the', 'conversation', 'and', 'fire', 'the', ':', 'meth', ':', 'on_conversation_added', 'event', '.']
train
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/im/service.py#L99-L135
9,209
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/decoder.py
StringDecoder
def StringDecoder(field_number, is_repeated, is_packed, key, new_default): """Returns a decoder for a string field.""" local_DecodeVarint = _DecodeVarint local_unicode = six.text_type def _ConvertToUnicode(byte_str): try: return local_unicode(byte_str, 'utf-8') except UnicodeDecodeError as e: ...
python
def StringDecoder(field_number, is_repeated, is_packed, key, new_default): """Returns a decoder for a string field.""" local_DecodeVarint = _DecodeVarint local_unicode = six.text_type def _ConvertToUnicode(byte_str): try: return local_unicode(byte_str, 'utf-8') except UnicodeDecodeError as e: ...
['def', 'StringDecoder', '(', 'field_number', ',', 'is_repeated', ',', 'is_packed', ',', 'key', ',', 'new_default', ')', ':', 'local_DecodeVarint', '=', '_DecodeVarint', 'local_unicode', '=', 'six', '.', 'text_type', 'def', '_ConvertToUnicode', '(', 'byte_str', ')', ':', 'try', ':', 'return', 'local_unicode', '(', 'byt...
Returns a decoder for a string field.
['Returns', 'a', 'decoder', 'for', 'a', 'string', 'field', '.']
train
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/decoder.py#L461-L504
9,210
crs4/hl7apy
hl7apy/validation.py
Validator.validate
def validate(element, reference=None, report_file=None): """ Checks if the :class:`Element <hl7apy.core.Element>` is a valid HL7 message according to the reference specified. If the reference is not specified, it will be used the official HL7 structures for the elements. In parti...
python
def validate(element, reference=None, report_file=None): """ Checks if the :class:`Element <hl7apy.core.Element>` is a valid HL7 message according to the reference specified. If the reference is not specified, it will be used the official HL7 structures for the elements. In parti...
['def', 'validate', '(', 'element', ',', 'reference', '=', 'None', ',', 'report_file', '=', 'None', ')', ':', 'from', 'hl7apy', '.', 'core', 'import', 'is_base_datatype', 'def', '_check_z_element', '(', 'el', ',', 'errs', ',', 'warns', ')', ':', 'if', 'el', '.', 'classname', '==', "'Field'", ':', 'if', 'is_base_datatyp...
Checks if the :class:`Element <hl7apy.core.Element>` is a valid HL7 message according to the reference specified. If the reference is not specified, it will be used the official HL7 structures for the elements. In particular it checks: * the maximum and minimum number of occurrences for...
['Checks', 'if', 'the', ':', 'class', ':', 'Element', '<hl7apy', '.', 'core', '.', 'Element', '>', 'is', 'a', 'valid', 'HL7', 'message', 'according', 'to', 'the', 'reference', 'specified', '.', 'If', 'the', 'reference', 'is', 'not', 'specified', 'it', 'will', 'be', 'used', 'the', 'official', 'HL7', 'structures', 'for',...
train
https://github.com/crs4/hl7apy/blob/91be488e9274f6ec975519a1d9c17045bc91bf74/hl7apy/validation.py#L40-L210
9,211
burnash/gspread
gspread/models.py
Spreadsheet.worksheets
def worksheets(self): """Returns a list of all :class:`worksheets <gsperad.models.Worksheet>` in a spreadsheet. """ sheet_data = self.fetch_sheet_metadata() return [Worksheet(self, x['properties']) for x in sheet_data['sheets']]
python
def worksheets(self): """Returns a list of all :class:`worksheets <gsperad.models.Worksheet>` in a spreadsheet. """ sheet_data = self.fetch_sheet_metadata() return [Worksheet(self, x['properties']) for x in sheet_data['sheets']]
['def', 'worksheets', '(', 'self', ')', ':', 'sheet_data', '=', 'self', '.', 'fetch_sheet_metadata', '(', ')', 'return', '[', 'Worksheet', '(', 'self', ',', 'x', '[', "'properties'", ']', ')', 'for', 'x', 'in', 'sheet_data', '[', "'sheets'", ']', ']']
Returns a list of all :class:`worksheets <gsperad.models.Worksheet>` in a spreadsheet.
['Returns', 'a', 'list', 'of', 'all', ':', 'class', ':', 'worksheets', '<gsperad', '.', 'models', '.', 'Worksheet', '>', 'in', 'a', 'spreadsheet', '.']
train
https://github.com/burnash/gspread/blob/0e8debe208095aeed3e3e7136c2fa5cd74090946/gspread/models.py#L211-L217
9,212
esterhui/pypu
pypu/pusher.py
status._computeStatus
def _computeStatus(self, dfile, service): """Computes status for file, basically this means if more than one service handles the file, it will place a 'C' (for complicated) otherwise if status matches between all services, will place that status""" # If only one service request...
python
def _computeStatus(self, dfile, service): """Computes status for file, basically this means if more than one service handles the file, it will place a 'C' (for complicated) otherwise if status matches between all services, will place that status""" # If only one service request...
['def', '_computeStatus', '(', 'self', ',', 'dfile', ',', 'service', ')', ':', '# If only one service requested', 'if', 'service', ':', 'if', 'not', 'dfile', '[', "'services'", ']', '.', 'has_key', '(', 'service', ')', ':', 'return', 'self', '.', 'ST_UNTRACKED', 'else', ':', 'return', 'dfile', '[', "'services'", ']', '...
Computes status for file, basically this means if more than one service handles the file, it will place a 'C' (for complicated) otherwise if status matches between all services, will place that status
['Computes', 'status', 'for', 'file', 'basically', 'this', 'means', 'if', 'more', 'than', 'one', 'service', 'handles', 'the', 'file', 'it', 'will', 'place', 'a', 'C', '(', 'for', 'complicated', ')', 'otherwise', 'if', 'status', 'matches', 'between', 'all', 'services', 'will', 'place', 'that', 'status']
train
https://github.com/esterhui/pypu/blob/cc3e259d59f024c2c4c0fbb9c8a1547e51de75ec/pypu/pusher.py#L89-L118
9,213
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/configuration.py
Config.validate
def validate(self): """Validate / fix up the current config""" if not self.get('api_key'): raise ValueError("api_key not found in config. Please see documentation.") host = self.get('host') or DEFAULT_CLOUD_HOST if host: # remove extraneous slashes and force to by...
python
def validate(self): """Validate / fix up the current config""" if not self.get('api_key'): raise ValueError("api_key not found in config. Please see documentation.") host = self.get('host') or DEFAULT_CLOUD_HOST if host: # remove extraneous slashes and force to by...
['def', 'validate', '(', 'self', ')', ':', 'if', 'not', 'self', '.', 'get', '(', "'api_key'", ')', ':', 'raise', 'ValueError', '(', '"api_key not found in config. Please see documentation."', ')', 'host', '=', 'self', '.', 'get', '(', "'host'", ')', 'or', 'DEFAULT_CLOUD_HOST', 'if', 'host', ':', '# remove extraneous sl...
Validate / fix up the current config
['Validate', '/', 'fix', 'up', 'the', 'current', 'config']
train
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/configuration.py#L108-L126
9,214
Stewori/pytypes
pytypes/type_util.py
is_Union
def is_Union(tp): """Python version independent check if a type is typing.Union. Tested with CPython 2.7, 3.5, 3.6 and Jython 2.7.1. """ if tp is Union: return True try: # Python 3.6 return tp.__origin__ is Union except AttributeError: try: return isin...
python
def is_Union(tp): """Python version independent check if a type is typing.Union. Tested with CPython 2.7, 3.5, 3.6 and Jython 2.7.1. """ if tp is Union: return True try: # Python 3.6 return tp.__origin__ is Union except AttributeError: try: return isin...
['def', 'is_Union', '(', 'tp', ')', ':', 'if', 'tp', 'is', 'Union', ':', 'return', 'True', 'try', ':', '# Python 3.6', 'return', 'tp', '.', '__origin__', 'is', 'Union', 'except', 'AttributeError', ':', 'try', ':', 'return', 'isinstance', '(', 'tp', ',', 'typing', '.', 'UnionMeta', ')', 'except', 'AttributeError', ':', ...
Python version independent check if a type is typing.Union. Tested with CPython 2.7, 3.5, 3.6 and Jython 2.7.1.
['Python', 'version', 'independent', 'check', 'if', 'a', 'type', 'is', 'typing', '.', 'Union', '.', 'Tested', 'with', 'CPython', '2', '.', '7', '3', '.', '5', '3', '.', '6', 'and', 'Jython', '2', '.', '7', '.', '1', '.']
train
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/type_util.py#L336-L349
9,215
awslabs/aws-shell
awsshell/config.py
Config.load
def load(self, config_template, config_file=None): """Read the config file if it exists, else read the default config. Creates the user config file if it doesn't exist using the template. :type config_template: str :param config_template: The config template file name. :type c...
python
def load(self, config_template, config_file=None): """Read the config file if it exists, else read the default config. Creates the user config file if it doesn't exist using the template. :type config_template: str :param config_template: The config template file name. :type c...
['def', 'load', '(', 'self', ',', 'config_template', ',', 'config_file', '=', 'None', ')', ':', 'if', 'config_file', 'is', 'None', ':', 'config_file', '=', 'config_template', 'config_path', '=', 'build_config_file_path', '(', 'config_file', ')', 'template_path', '=', 'os', '.', 'path', '.', 'join', '(', 'os', '.', 'pat...
Read the config file if it exists, else read the default config. Creates the user config file if it doesn't exist using the template. :type config_template: str :param config_template: The config template file name. :type config_file: str :param config_file: (Optional) The con...
['Read', 'the', 'config', 'file', 'if', 'it', 'exists', 'else', 'read', 'the', 'default', 'config', '.']
train
https://github.com/awslabs/aws-shell/blob/8950f03d9d720879890af6c11537b8f9789ce5a9/awsshell/config.py#L24-L45
9,216
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/pymavlink/mavextra.py
gps_velocity_old
def gps_velocity_old(GPS_RAW_INT): '''return GPS velocity vector''' return Vector3(GPS_RAW_INT.vel*0.01*cos(radians(GPS_RAW_INT.cog*0.01)), GPS_RAW_INT.vel*0.01*sin(radians(GPS_RAW_INT.cog*0.01)), 0)
python
def gps_velocity_old(GPS_RAW_INT): '''return GPS velocity vector''' return Vector3(GPS_RAW_INT.vel*0.01*cos(radians(GPS_RAW_INT.cog*0.01)), GPS_RAW_INT.vel*0.01*sin(radians(GPS_RAW_INT.cog*0.01)), 0)
['def', 'gps_velocity_old', '(', 'GPS_RAW_INT', ')', ':', 'return', 'Vector3', '(', 'GPS_RAW_INT', '.', 'vel', '*', '0.01', '*', 'cos', '(', 'radians', '(', 'GPS_RAW_INT', '.', 'cog', '*', '0.01', ')', ')', ',', 'GPS_RAW_INT', '.', 'vel', '*', '0.01', '*', 'sin', '(', 'radians', '(', 'GPS_RAW_INT', '.', 'cog', '*', '0....
return GPS velocity vector
['return', 'GPS', 'velocity', 'vector']
train
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/mavextra.py#L630-L633
9,217
hovren/crisp
crisp/imu.py
IMU.from_mat_file
def from_mat_file(cls, matfilename): """Load gyro data from .mat file The MAT file should contain the following two arrays gyro : (3, N) float ndarray The angular velocity measurements. timestamps : (N, ) float ndarray Timestamps of the m...
python
def from_mat_file(cls, matfilename): """Load gyro data from .mat file The MAT file should contain the following two arrays gyro : (3, N) float ndarray The angular velocity measurements. timestamps : (N, ) float ndarray Timestamps of the m...
['def', 'from_mat_file', '(', 'cls', ',', 'matfilename', ')', ':', 'M', '=', 'scipy', '.', 'io', '.', 'loadmat', '(', 'matfilename', ')', 'instance', '=', 'cls', '(', ')', 'instance', '.', 'gyro_data', '=', 'M', '[', "'gyro'", ']', 'instance', '.', 'timestamps', '=', 'M', '[', "'timestamps'", ']', 'return', 'instance']
Load gyro data from .mat file The MAT file should contain the following two arrays gyro : (3, N) float ndarray The angular velocity measurements. timestamps : (N, ) float ndarray Timestamps of the measurements. Parameters...
['Load', 'gyro', 'data', 'from', '.', 'mat', 'file', 'The', 'MAT', 'file', 'should', 'contain', 'the', 'following', 'two', 'arrays', 'gyro', ':', '(', '3', 'N', ')', 'float', 'ndarray', 'The', 'angular', 'velocity', 'measurements', '.', 'timestamps', ':', '(', 'N', ')', 'float', 'ndarray', 'Timestamps', 'of', 'the', 'm...
train
https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/imu.py#L39-L62
9,218
mbj4668/pyang
pyang/translators/schemanode.py
SchemaNode.subnode
def subnode(self, node): """Make `node` receiver's child.""" self.children.append(node) node.parent = self node.adjust_interleave(node.interleave)
python
def subnode(self, node): """Make `node` receiver's child.""" self.children.append(node) node.parent = self node.adjust_interleave(node.interleave)
['def', 'subnode', '(', 'self', ',', 'node', ')', ':', 'self', '.', 'children', '.', 'append', '(', 'node', ')', 'node', '.', 'parent', '=', 'self', 'node', '.', 'adjust_interleave', '(', 'node', '.', 'interleave', ')']
Make `node` receiver's child.
['Make', 'node', 'receiver', 's', 'child', '.']
train
https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/translators/schemanode.py#L146-L150
9,219
Jaymon/prom
prom/model.py
Orm.insert
def insert(self): """persist the field values of this orm""" ret = True schema = self.schema fields = self.depopulate(False) q = self.query q.set_fields(fields) pk = q.insert() if pk: fields = q.fields fields[schema.pk.name] = pk ...
python
def insert(self): """persist the field values of this orm""" ret = True schema = self.schema fields = self.depopulate(False) q = self.query q.set_fields(fields) pk = q.insert() if pk: fields = q.fields fields[schema.pk.name] = pk ...
['def', 'insert', '(', 'self', ')', ':', 'ret', '=', 'True', 'schema', '=', 'self', '.', 'schema', 'fields', '=', 'self', '.', 'depopulate', '(', 'False', ')', 'q', '=', 'self', '.', 'query', 'q', '.', 'set_fields', '(', 'fields', ')', 'pk', '=', 'q', '.', 'insert', '(', ')', 'if', 'pk', ':', 'fields', '=', 'q', '.', '...
persist the field values of this orm
['persist', 'the', 'field', 'values', 'of', 'this', 'orm']
train
https://github.com/Jaymon/prom/blob/b7ad2c259eca198da03e1e4bc7d95014c168c361/prom/model.py#L296-L314
9,220
bitesofcode/projexui
projexui/widgets/xganttwidget/xganttwidgetitem.py
XGanttWidgetItem.takeChild
def takeChild(self, index): """ Removes the child at the given index from this item. :param index | <int> """ item = super(XGanttWidgetItem, self).takeChild(index) if item: item.removeFromScene() return it...
python
def takeChild(self, index): """ Removes the child at the given index from this item. :param index | <int> """ item = super(XGanttWidgetItem, self).takeChild(index) if item: item.removeFromScene() return it...
['def', 'takeChild', '(', 'self', ',', 'index', ')', ':', 'item', '=', 'super', '(', 'XGanttWidgetItem', ',', 'self', ')', '.', 'takeChild', '(', 'index', ')', 'if', 'item', ':', 'item', '.', 'removeFromScene', '(', ')', 'return', 'item']
Removes the child at the given index from this item. :param index | <int>
['Removes', 'the', 'child', 'at', 'the', 'given', 'index', 'from', 'this', 'item', '.', ':', 'param', 'index', '|', '<int', '>']
train
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xganttwidget/xganttwidgetitem.py#L664-L675
9,221
bcbio/bcbio-nextgen
bcbio/pipeline/shared.py
subset_bed_by_chrom
def subset_bed_by_chrom(in_file, chrom, data, out_dir=None): """Subset a BED file to only have items from the specified chromosome. """ if out_dir is None: out_dir = os.path.dirname(in_file) base, ext = os.path.splitext(os.path.basename(in_file)) out_file = os.path.join(out_dir, "%s-%s%s" % ...
python
def subset_bed_by_chrom(in_file, chrom, data, out_dir=None): """Subset a BED file to only have items from the specified chromosome. """ if out_dir is None: out_dir = os.path.dirname(in_file) base, ext = os.path.splitext(os.path.basename(in_file)) out_file = os.path.join(out_dir, "%s-%s%s" % ...
['def', 'subset_bed_by_chrom', '(', 'in_file', ',', 'chrom', ',', 'data', ',', 'out_dir', '=', 'None', ')', ':', 'if', 'out_dir', 'is', 'None', ':', 'out_dir', '=', 'os', '.', 'path', '.', 'dirname', '(', 'in_file', ')', 'base', ',', 'ext', '=', 'os', '.', 'path', '.', 'splitext', '(', 'os', '.', 'path', '.', 'basename...
Subset a BED file to only have items from the specified chromosome.
['Subset', 'a', 'BED', 'file', 'to', 'only', 'have', 'items', 'from', 'the', 'specified', 'chromosome', '.']
train
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/shared.py#L111-L121
9,222
alvarogzp/telegram-bot-framework
bot/action/standard/info/formatter/user.py
UserInfoFormatter.format
def format(self, member_info: bool = False): """ :param member_info: If True, adds also chat member info. Please, note that this additional info requires to make ONE api call. """ user = self.api_object self.__format_user(user) if member_info and self.chat.typ...
python
def format(self, member_info: bool = False): """ :param member_info: If True, adds also chat member info. Please, note that this additional info requires to make ONE api call. """ user = self.api_object self.__format_user(user) if member_info and self.chat.typ...
['def', 'format', '(', 'self', ',', 'member_info', ':', 'bool', '=', 'False', ')', ':', 'user', '=', 'self', '.', 'api_object', 'self', '.', '__format_user', '(', 'user', ')', 'if', 'member_info', 'and', 'self', '.', 'chat', '.', 'type', '!=', 'CHAT_TYPE_PRIVATE', ':', 'self', '.', '_add_empty', '(', ')', 'self', '.', ...
:param member_info: If True, adds also chat member info. Please, note that this additional info requires to make ONE api call.
[':', 'param', 'member_info', ':', 'If', 'True', 'adds', 'also', 'chat', 'member', 'info', '.', 'Please', 'note', 'that', 'this', 'additional', 'info', 'requires', 'to', 'make', 'ONE', 'api', 'call', '.']
train
https://github.com/alvarogzp/telegram-bot-framework/blob/7b597a415c1901901c677976cb13100fc3083107/bot/action/standard/info/formatter/user.py#L19-L28
9,223
5monkeys/content-io
cio/node.py
Node.namespace_uri
def namespace_uri(self): """ Finds and returns first applied URI of this node that has a namespace. :return str: uri """ try: return next( iter(filter(lambda uri: URI(uri).namespace, self._uri)) ) except StopIteration: ...
python
def namespace_uri(self): """ Finds and returns first applied URI of this node that has a namespace. :return str: uri """ try: return next( iter(filter(lambda uri: URI(uri).namespace, self._uri)) ) except StopIteration: ...
['def', 'namespace_uri', '(', 'self', ')', ':', 'try', ':', 'return', 'next', '(', 'iter', '(', 'filter', '(', 'lambda', 'uri', ':', 'URI', '(', 'uri', ')', '.', 'namespace', ',', 'self', '.', '_uri', ')', ')', ')', 'except', 'StopIteration', ':', 'return', 'None']
Finds and returns first applied URI of this node that has a namespace. :return str: uri
['Finds', 'and', 'returns', 'first', 'applied', 'URI', 'of', 'this', 'node', 'that', 'has', 'a', 'namespace', '.']
train
https://github.com/5monkeys/content-io/blob/8c8519c74cbadab871f7151c0e02252cb5753759/cio/node.py#L70-L81
9,224
pallets/werkzeug
src/werkzeug/formparser.py
exhaust_stream
def exhaust_stream(f): """Helper decorator for methods that exhausts the stream on return.""" def wrapper(self, stream, *args, **kwargs): try: return f(self, stream, *args, **kwargs) finally: exhaust = getattr(stream, "exhaust", None) if exhaust is not None: ...
python
def exhaust_stream(f): """Helper decorator for methods that exhausts the stream on return.""" def wrapper(self, stream, *args, **kwargs): try: return f(self, stream, *args, **kwargs) finally: exhaust = getattr(stream, "exhaust", None) if exhaust is not None: ...
['def', 'exhaust_stream', '(', 'f', ')', ':', 'def', 'wrapper', '(', 'self', ',', 'stream', ',', '*', 'args', ',', '*', '*', 'kwargs', ')', ':', 'try', ':', 'return', 'f', '(', 'self', ',', 'stream', ',', '*', 'args', ',', '*', '*', 'kwargs', ')', 'finally', ':', 'exhaust', '=', 'getattr', '(', 'stream', ',', '"exhaust...
Helper decorator for methods that exhausts the stream on return.
['Helper', 'decorator', 'for', 'methods', 'that', 'exhausts', 'the', 'stream', 'on', 'return', '.']
train
https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/formparser.py#L125-L141
9,225
apache/spark
python/pyspark/rdd.py
RDD.lookup
def lookup(self, key): """ Return the list of values in the RDD for key `key`. This operation is done efficiently if the RDD has a known partitioner by only searching the partition that the key maps to. >>> l = range(1000) >>> rdd = sc.parallelize(zip(l, l), 10) ...
python
def lookup(self, key): """ Return the list of values in the RDD for key `key`. This operation is done efficiently if the RDD has a known partitioner by only searching the partition that the key maps to. >>> l = range(1000) >>> rdd = sc.parallelize(zip(l, l), 10) ...
['def', 'lookup', '(', 'self', ',', 'key', ')', ':', 'values', '=', 'self', '.', 'filter', '(', 'lambda', 'kv', ':', 'kv', '[', '0', ']', '==', 'key', ')', '.', 'values', '(', ')', 'if', 'self', '.', 'partitioner', 'is', 'not', 'None', ':', 'return', 'self', '.', 'ctx', '.', 'runJob', '(', 'values', ',', 'lambda', 'x',...
Return the list of values in the RDD for key `key`. This operation is done efficiently if the RDD has a known partitioner by only searching the partition that the key maps to. >>> l = range(1000) >>> rdd = sc.parallelize(zip(l, l), 10) >>> rdd.lookup(42) # slow [42] ...
['Return', 'the', 'list', 'of', 'values', 'in', 'the', 'RDD', 'for', 'key', 'key', '.', 'This', 'operation', 'is', 'done', 'efficiently', 'if', 'the', 'RDD', 'has', 'a', 'known', 'partitioner', 'by', 'only', 'searching', 'the', 'partition', 'that', 'the', 'key', 'maps', 'to', '.']
train
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L2267-L2291
9,226
python-rope/rope
rope/base/oi/type_hinting/providers/pep0484_type_comments.py
AssignmentProvider._search_type_in_type_comment
def _search_type_in_type_comment(self, code): """ For more info see: https://www.python.org/dev/peps/pep-0484/#type-comments >>> AssignmentProvider()._search_type_in_type_comment('type: int') ['int'] """ for p in self.PEP0484_TYPE_COMMENT_PATTERNS: match = p....
python
def _search_type_in_type_comment(self, code): """ For more info see: https://www.python.org/dev/peps/pep-0484/#type-comments >>> AssignmentProvider()._search_type_in_type_comment('type: int') ['int'] """ for p in self.PEP0484_TYPE_COMMENT_PATTERNS: match = p....
['def', '_search_type_in_type_comment', '(', 'self', ',', 'code', ')', ':', 'for', 'p', 'in', 'self', '.', 'PEP0484_TYPE_COMMENT_PATTERNS', ':', 'match', '=', 'p', '.', 'search', '(', 'code', ')', 'if', 'match', ':', 'return', '[', 'match', '.', 'group', '(', '1', ')', ']']
For more info see: https://www.python.org/dev/peps/pep-0484/#type-comments >>> AssignmentProvider()._search_type_in_type_comment('type: int') ['int']
['For', 'more', 'info', 'see', ':', 'https', ':', '//', 'www', '.', 'python', '.', 'org', '/', 'dev', '/', 'peps', '/', 'pep', '-', '0484', '/', '#type', '-', 'comments']
train
https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/base/oi/type_hinting/providers/pep0484_type_comments.py#L32-L42
9,227
rckclmbr/pyportify
pyportify/pkcs1/primes.py
jacobi
def jacobi(a, b): '''Calculates the value of the Jacobi symbol (a/b) where both a and b are positive integers, and b is odd :returns: -1, 0 or 1 ''' assert a > 0 assert b > 0 if a == 0: return 0 result = 1 while a > 1: if a & 1: if ((a-1)*(b-1) >> 2) & ...
python
def jacobi(a, b): '''Calculates the value of the Jacobi symbol (a/b) where both a and b are positive integers, and b is odd :returns: -1, 0 or 1 ''' assert a > 0 assert b > 0 if a == 0: return 0 result = 1 while a > 1: if a & 1: if ((a-1)*(b-1) >> 2) & ...
['def', 'jacobi', '(', 'a', ',', 'b', ')', ':', 'assert', 'a', '>', '0', 'assert', 'b', '>', '0', 'if', 'a', '==', '0', ':', 'return', '0', 'result', '=', '1', 'while', 'a', '>', '1', ':', 'if', 'a', '&', '1', ':', 'if', '(', '(', 'a', '-', '1', ')', '*', '(', 'b', '-', '1', ')', '>>', '2', ')', '&', '1', ':', 'result'...
Calculates the value of the Jacobi symbol (a/b) where both a and b are positive integers, and b is odd :returns: -1, 0 or 1
['Calculates', 'the', 'value', 'of', 'the', 'Jacobi', 'symbol', '(', 'a', '/', 'b', ')', 'where', 'both', 'a', 'and', 'b', 'are', 'positive', 'integers', 'and', 'b', 'is', 'odd']
train
https://github.com/rckclmbr/pyportify/blob/696a1caad8a47b191f3bec44cc8fc3c437779512/pyportify/pkcs1/primes.py#L73-L97
9,228
talkincode/toughlib
toughlib/btforms/net.py
validipaddr
def validipaddr(address): """ Returns True if `address` is a valid IPv4 address. >>> validipaddr('192.168.1.1') True >>> validipaddr('192.168.1.800') False >>> validipaddr('192.168.1') False """ try: octets = address.split('.') if len(...
python
def validipaddr(address): """ Returns True if `address` is a valid IPv4 address. >>> validipaddr('192.168.1.1') True >>> validipaddr('192.168.1.800') False >>> validipaddr('192.168.1') False """ try: octets = address.split('.') if len(...
['def', 'validipaddr', '(', 'address', ')', ':', 'try', ':', 'octets', '=', 'address', '.', 'split', '(', "'.'", ')', 'if', 'len', '(', 'octets', ')', '!=', '4', ':', 'return', 'False', 'for', 'x', 'in', 'octets', ':', 'if', 'not', '(', '0', '<=', 'int', '(', 'x', ')', '<=', '255', ')', ':', 'return', 'False', 'except'...
Returns True if `address` is a valid IPv4 address. >>> validipaddr('192.168.1.1') True >>> validipaddr('192.168.1.800') False >>> validipaddr('192.168.1') False
['Returns', 'True', 'if', 'address', 'is', 'a', 'valid', 'IPv4', 'address', '.', '>>>', 'validipaddr', '(', '192', '.', '168', '.', '1', '.', '1', ')', 'True', '>>>', 'validipaddr', '(', '192', '.', '168', '.', '1', '.', '800', ')', 'False', '>>>', 'validipaddr', '(', '192', '.', '168', '.', '1', ')', 'False']
train
https://github.com/talkincode/toughlib/blob/1c2f7dde3a7f101248f1b5f5d428cc85466995cf/toughlib/btforms/net.py#L14-L34
9,229
tgbugs/pyontutils
ilxutils/ilxutils/simple_rdflib.py
SimpleGraph.remove_triple
def remove_triple( self, subj: URIRef, pred: URIRef, obj: Union[URIRef, Literal] ) -> None: """ Removes triple from rdflib Graph You must input the triple in its URIRef or Literal form for each node exactly the way it was inputed or it wil...
python
def remove_triple( self, subj: URIRef, pred: URIRef, obj: Union[URIRef, Literal] ) -> None: """ Removes triple from rdflib Graph You must input the triple in its URIRef or Literal form for each node exactly the way it was inputed or it wil...
['def', 'remove_triple', '(', 'self', ',', 'subj', ':', 'URIRef', ',', 'pred', ':', 'URIRef', ',', 'obj', ':', 'Union', '[', 'URIRef', ',', 'Literal', ']', ')', '->', 'None', ':', 'self', '.', 'g', '.', 'remove', '(', '(', 'subj', ',', 'pred', ',', 'obj', ')', ')']
Removes triple from rdflib Graph You must input the triple in its URIRef or Literal form for each node exactly the way it was inputed or it will not delete the triple. Args: subj: Entity subject to be removed it its the only node with this subject; else this is just...
['Removes', 'triple', 'from', 'rdflib', 'Graph']
train
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/simple_rdflib.py#L291-L308
9,230
nok/sklearn-porter
sklearn_porter/Template.py
Template.indent
def indent(self, text, n_indents=1, skipping=False): """ Indent text with single spaces. Parameters ---------- :param text : string The text which get a specific indentation. :param n_indents : int, default: 1 The number of indentations. :...
python
def indent(self, text, n_indents=1, skipping=False): """ Indent text with single spaces. Parameters ---------- :param text : string The text which get a specific indentation. :param n_indents : int, default: 1 The number of indentations. :...
['def', 'indent', '(', 'self', ',', 'text', ',', 'n_indents', '=', '1', ',', 'skipping', '=', 'False', ')', ':', 'lines', '=', 'text', '.', 'splitlines', '(', ')', 'space', '=', 'self', '.', 'TEMPLATES', '.', 'get', '(', 'self', '.', 'target_language', ')', '.', 'get', '(', "'indent'", ',', "' '", ')', '# Single line:'...
Indent text with single spaces. Parameters ---------- :param text : string The text which get a specific indentation. :param n_indents : int, default: 1 The number of indentations. :param skipping : boolean, default: False Whether to skip the ...
['Indent', 'text', 'with', 'single', 'spaces', '.']
train
https://github.com/nok/sklearn-porter/blob/04673f768310bde31f9747a68a5e070592441ef2/sklearn_porter/Template.py#L25-L61
9,231
rm-hull/luma.oled
luma/oled/device/__init__.py
ssd1306.display
def display(self, image): """ Takes a 1-bit :py:mod:`PIL.Image` and dumps it to the OLED display. :param image: Image to display. :type image: :py:mod:`PIL.Image` """ assert(image.mode == self.mode) assert(image.size == self.size) image = self.pr...
python
def display(self, image): """ Takes a 1-bit :py:mod:`PIL.Image` and dumps it to the OLED display. :param image: Image to display. :type image: :py:mod:`PIL.Image` """ assert(image.mode == self.mode) assert(image.size == self.size) image = self.pr...
['def', 'display', '(', 'self', ',', 'image', ')', ':', 'assert', '(', 'image', '.', 'mode', '==', 'self', '.', 'mode', ')', 'assert', '(', 'image', '.', 'size', '==', 'self', '.', 'size', ')', 'image', '=', 'self', '.', 'preprocess', '(', 'image', ')', 'self', '.', 'command', '(', '# Column start/end address', 'self',...
Takes a 1-bit :py:mod:`PIL.Image` and dumps it to the OLED display. :param image: Image to display. :type image: :py:mod:`PIL.Image`
['Takes', 'a', '1', '-', 'bit', ':', 'py', ':', 'mod', ':', 'PIL', '.', 'Image', 'and', 'dumps', 'it', 'to', 'the', 'OLED', 'display', '.']
train
https://github.com/rm-hull/luma.oled/blob/76055aa2ca486dc2f9def49754b74ffbccdc5491/luma/oled/device/__init__.py#L191-L220
9,232
wakatime/wakatime
wakatime/packages/pygments/lexers/__init__.py
load_lexer_from_file
def load_lexer_from_file(filename, lexername="CustomLexer", **options): """Load a lexer from a file. This method expects a file located relative to the current working directory, which contains a Lexer class. By default, it expects the Lexer to be name CustomLexer; you can specify your own class name ...
python
def load_lexer_from_file(filename, lexername="CustomLexer", **options): """Load a lexer from a file. This method expects a file located relative to the current working directory, which contains a Lexer class. By default, it expects the Lexer to be name CustomLexer; you can specify your own class name ...
['def', 'load_lexer_from_file', '(', 'filename', ',', 'lexername', '=', '"CustomLexer"', ',', '*', '*', 'options', ')', ':', 'try', ':', "# This empty dict will contain the namespace for the exec'd file", 'custom_namespace', '=', '{', '}', 'exec', '(', 'open', '(', 'filename', ',', "'rb'", ')', '.', 'read', '(', ')', '...
Load a lexer from a file. This method expects a file located relative to the current working directory, which contains a Lexer class. By default, it expects the Lexer to be name CustomLexer; you can specify your own class name as the second argument to this function. Users should be very careful w...
['Load', 'a', 'lexer', 'from', 'a', 'file', '.']
train
https://github.com/wakatime/wakatime/blob/74519ace04e8472f3a3993269963732b9946a01d/wakatime/packages/pygments/lexers/__init__.py#L118-L149
9,233
mwouts/jupytext
jupytext/formats.py
short_form_one_format
def short_form_one_format(jupytext_format): """Represent one jupytext format as a string""" if not isinstance(jupytext_format, dict): return jupytext_format fmt = jupytext_format['extension'] if 'suffix' in jupytext_format: fmt = jupytext_format['suffix'] + fmt elif fmt.startswith('....
python
def short_form_one_format(jupytext_format): """Represent one jupytext format as a string""" if not isinstance(jupytext_format, dict): return jupytext_format fmt = jupytext_format['extension'] if 'suffix' in jupytext_format: fmt = jupytext_format['suffix'] + fmt elif fmt.startswith('....
['def', 'short_form_one_format', '(', 'jupytext_format', ')', ':', 'if', 'not', 'isinstance', '(', 'jupytext_format', ',', 'dict', ')', ':', 'return', 'jupytext_format', 'fmt', '=', 'jupytext_format', '[', "'extension'", ']', 'if', "'suffix'", 'in', 'jupytext_format', ':', 'fmt', '=', 'jupytext_format', '[', "'suffix'"...
Represent one jupytext format as a string
['Represent', 'one', 'jupytext', 'format', 'as', 'a', 'string']
train
https://github.com/mwouts/jupytext/blob/eb7d6aee889f80ad779cfc53441c648f0db9246d/jupytext/formats.py#L483-L500
9,234
wdbm/megaparsex
megaparsex.py
trigger_keyphrases
def trigger_keyphrases( text = None, # input text to parse keyphrases = None, # keyphrases for parsing input text response = None, # optional text response on trigger function = None, # optional function on trigger...
python
def trigger_keyphrases( text = None, # input text to parse keyphrases = None, # keyphrases for parsing input text response = None, # optional text response on trigger function = None, # optional function on trigger...
['def', 'trigger_keyphrases', '(', 'text', '=', 'None', ',', '# input text to parse', 'keyphrases', '=', 'None', ',', '# keyphrases for parsing input text', 'response', '=', 'None', ',', '# optional text response on trigger', 'function', '=', 'None', ',', '# optional function on trigger', 'kwargs', '=', 'None', ',', '#...
Parse input text for keyphrases. If any keyphrases are found, respond with text or by seeking confirmation or by engaging a function with optional keyword arguments. Return text or True if triggered and return False if not triggered. If confirmation is required, a confirmation object is returned, encaps...
['Parse', 'input', 'text', 'for', 'keyphrases', '.', 'If', 'any', 'keyphrases', 'are', 'found', 'respond', 'with', 'text', 'or', 'by', 'seeking', 'confirmation', 'or', 'by', 'engaging', 'a', 'function', 'with', 'optional', 'keyword', 'arguments', '.', 'Return', 'text', 'or', 'True', 'if', 'triggered', 'and', 'return', ...
train
https://github.com/wdbm/megaparsex/blob/59da05410aa1cf8682dcee2bf0bd0572fa42bd29/megaparsex.py#L51-L91
9,235
slundberg/shap
shap/benchmark/metrics.py
batch_remove_absolute_retrain__r2
def batch_remove_absolute_retrain__r2(X, y, model_generator, method_name, num_fcounts=11): """ Batch Remove Absolute (retrain) xlabel = "Fraction of features removed" ylabel = "1 - R^2" transform = "one_minus" sort_order = 13 """ return __run_batch_abs_metric(measures.batch_remove_retrain, X...
python
def batch_remove_absolute_retrain__r2(X, y, model_generator, method_name, num_fcounts=11): """ Batch Remove Absolute (retrain) xlabel = "Fraction of features removed" ylabel = "1 - R^2" transform = "one_minus" sort_order = 13 """ return __run_batch_abs_metric(measures.batch_remove_retrain, X...
['def', 'batch_remove_absolute_retrain__r2', '(', 'X', ',', 'y', ',', 'model_generator', ',', 'method_name', ',', 'num_fcounts', '=', '11', ')', ':', 'return', '__run_batch_abs_metric', '(', 'measures', '.', 'batch_remove_retrain', ',', 'X', ',', 'y', ',', 'model_generator', ',', 'method_name', ',', 'sklearn', '.', 'me...
Batch Remove Absolute (retrain) xlabel = "Fraction of features removed" ylabel = "1 - R^2" transform = "one_minus" sort_order = 13
['Batch', 'Remove', 'Absolute', '(', 'retrain', ')', 'xlabel', '=', 'Fraction', 'of', 'features', 'removed', 'ylabel', '=', '1', '-', 'R^2', 'transform', '=', 'one_minus', 'sort_order', '=', '13']
train
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/benchmark/metrics.py#L394-L401
9,236
praekeltfoundation/molo.polls
molo/polls/admin.py
ParentListFilter.lookups
def lookups(self, request, model_admin): """ Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL query. The second element is the human-readable name for the option that will appear in the right sidebar. ...
python
def lookups(self, request, model_admin): """ Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL query. The second element is the human-readable name for the option that will appear in the right sidebar. ...
['def', 'lookups', '(', 'self', ',', 'request', ',', 'model_admin', ')', ':', 'return', '[', '(', 'q', '.', 'slug', ',', 'q', '.', 'title', ')', 'for', 'q', 'in', 'Question', '.', 'objects', '.', 'all', '(', ')', ']']
Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL query. The second element is the human-readable name for the option that will appear in the right sidebar.
['Returns', 'a', 'list', 'of', 'tuples', '.', 'The', 'first', 'element', 'in', 'each', 'tuple', 'is', 'the', 'coded', 'value', 'for', 'the', 'option', 'that', 'will', 'appear', 'in', 'the', 'URL', 'query', '.', 'The', 'second', 'element', 'is', 'the', 'human', '-', 'readable', 'name', 'for', 'the', 'option', 'that', 'w...
train
https://github.com/praekeltfoundation/molo.polls/blob/7b3e0e8908b2674ea297d2118c89c49333c84703/molo/polls/admin.py#L15-L23
9,237
Vagrants/blackbird
blackbird/utils/logger.py
get_handler_fp
def get_handler_fp(logger): """ Get handler_fp. This method is integrated to LoggerFactory Object in the future. :param logging.Logger logger: Python logging.Logger. logger instance. :rtype: logging.Logger.handlers.BaseRotatingHandler :return: Handler or Handler's stream. We call it `handler_fp`...
python
def get_handler_fp(logger): """ Get handler_fp. This method is integrated to LoggerFactory Object in the future. :param logging.Logger logger: Python logging.Logger. logger instance. :rtype: logging.Logger.handlers.BaseRotatingHandler :return: Handler or Handler's stream. We call it `handler_fp`...
['def', 'get_handler_fp', '(', 'logger', ')', ':', 'if', 'not', 'hasattr', '(', 'logger', ',', "'handlers'", ')', ':', 'raise', 'blackbird', '.', 'utils', '.', 'error', '.', 'BlackbirdError', '(', "'Given logger is not logging.Logger instance!'", ')', 'if', 'len', '(', 'logger', '.', 'handlers', ')', '!=', '1', ':', 'r...
Get handler_fp. This method is integrated to LoggerFactory Object in the future. :param logging.Logger logger: Python logging.Logger. logger instance. :rtype: logging.Logger.handlers.BaseRotatingHandler :return: Handler or Handler's stream. We call it `handler_fp`.
['Get', 'handler_fp', '.', 'This', 'method', 'is', 'integrated', 'to', 'LoggerFactory', 'Object', 'in', 'the', 'future', '.', ':', 'param', 'logging', '.', 'Logger', 'logger', ':', 'Python', 'logging', '.', 'Logger', '.', 'logger', 'instance', '.', ':', 'rtype', ':', 'logging', '.', 'Logger', '.', 'handlers', '.', 'Bas...
train
https://github.com/Vagrants/blackbird/blob/3b38cd5650caae362e0668dbd38bf8f88233e079/blackbird/utils/logger.py#L69-L91
9,238
markuskiller/textblob-de
textblob_de/ext/_pattern/text/search.py
Pattern.fromstring
def fromstring(cls, s, *args, **kwargs): """ Returns a new Pattern from the given string. Constraints are separated by a space. If a constraint contains a space, it must be wrapped in []. """ s = s.replace("\(", "&lparen;") s = s.replace("\)", "&rparen;") ...
python
def fromstring(cls, s, *args, **kwargs): """ Returns a new Pattern from the given string. Constraints are separated by a space. If a constraint contains a space, it must be wrapped in []. """ s = s.replace("\(", "&lparen;") s = s.replace("\)", "&rparen;") ...
['def', 'fromstring', '(', 'cls', ',', 's', ',', '*', 'args', ',', '*', '*', 'kwargs', ')', ':', 's', '=', 's', '.', 'replace', '(', '"\\("', ',', '"&lparen;"', ')', 's', '=', 's', '.', 'replace', '(', '"\\)"', ',', '"&rparen;"', ')', 's', '=', 's', '.', 'replace', '(', '"\\["', ',', '"&lbrack;"', ')', 's', '=', 's', '...
Returns a new Pattern from the given string. Constraints are separated by a space. If a constraint contains a space, it must be wrapped in [].
['Returns', 'a', 'new', 'Pattern', 'from', 'the', 'given', 'string', '.', 'Constraints', 'are', 'separated', 'by', 'a', 'space', '.', 'If', 'a', 'constraint', 'contains', 'a', 'space', 'it', 'must', 'be', 'wrapped', 'in', '[]', '.']
train
https://github.com/markuskiller/textblob-de/blob/1b427b2cdd7e5e9fd3697677a98358fae4aa6ad1/textblob_de/ext/_pattern/text/search.py#L718-L767
9,239
wummel/linkchecker
third_party/dnspython/dns/update.py
Update.present
def present(self, name, *args): """Require that an owner name (and optionally an rdata type, or specific rdataset) exists as a prerequisite to the execution of the update. The first argument is always a name. The other arguments can be: - rdataset... - ...
python
def present(self, name, *args): """Require that an owner name (and optionally an rdata type, or specific rdataset) exists as a prerequisite to the execution of the update. The first argument is always a name. The other arguments can be: - rdataset... - ...
['def', 'present', '(', 'self', ',', 'name', ',', '*', 'args', ')', ':', 'if', 'isinstance', '(', 'name', ',', '(', 'str', ',', 'unicode', ')', ')', ':', 'name', '=', 'dns', '.', 'name', '.', 'from_text', '(', 'name', ',', 'None', ')', 'if', 'len', '(', 'args', ')', '==', '0', ':', 'rrset', '=', 'self', '.', 'find_rrse...
Require that an owner name (and optionally an rdata type, or specific rdataset) exists as a prerequisite to the execution of the update. The first argument is always a name. The other arguments can be: - rdataset... - rdata... - rdtype, string....
['Require', 'that', 'an', 'owner', 'name', '(', 'and', 'optionally', 'an', 'rdata', 'type', 'or', 'specific', 'rdataset', ')', 'exists', 'as', 'a', 'prerequisite', 'to', 'the', 'execution', 'of', 'the', 'update', '.', 'The', 'first', 'argument', 'is', 'always', 'a', 'name', '.', 'The', 'other', 'arguments', 'can', 'be'...
train
https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/third_party/dnspython/dns/update.py#L184-L218
9,240
molmod/molmod
molmod/molecular_graphs.py
NRingPattern.complete
def complete(self, match, subject_graph): """Check the completeness of the ring match""" if not CustomPattern.complete(self, match, subject_graph): return False if self.strong: # If the ring is not strong, return False if self.size % 2 == 0: # ...
python
def complete(self, match, subject_graph): """Check the completeness of the ring match""" if not CustomPattern.complete(self, match, subject_graph): return False if self.strong: # If the ring is not strong, return False if self.size % 2 == 0: # ...
['def', 'complete', '(', 'self', ',', 'match', ',', 'subject_graph', ')', ':', 'if', 'not', 'CustomPattern', '.', 'complete', '(', 'self', ',', 'match', ',', 'subject_graph', ')', ':', 'return', 'False', 'if', 'self', '.', 'strong', ':', '# If the ring is not strong, return False', 'if', 'self', '.', 'size', '%', '2', ...
Check the completeness of the ring match
['Check', 'the', 'completeness', 'of', 'the', 'ring', 'match']
train
https://github.com/molmod/molmod/blob/a7b5b4364ed514ad4c465856c05b5eda1cb561e0/molmod/molecular_graphs.py#L605-L640
9,241
Ffisegydd/whatis
whatis/_util.py
get_types
def get_types(obj, **kwargs): """Get the types of an iterable.""" max_iterable_length = kwargs.get('max_iterable_length', 100000) it, = itertools.tee(obj, 1) s = set() too_big = False for i, v in enumerate(it): if i <= max_iterable_length: s.add(type(v)) else: ...
python
def get_types(obj, **kwargs): """Get the types of an iterable.""" max_iterable_length = kwargs.get('max_iterable_length', 100000) it, = itertools.tee(obj, 1) s = set() too_big = False for i, v in enumerate(it): if i <= max_iterable_length: s.add(type(v)) else: ...
['def', 'get_types', '(', 'obj', ',', '*', '*', 'kwargs', ')', ':', 'max_iterable_length', '=', 'kwargs', '.', 'get', '(', "'max_iterable_length'", ',', '100000', ')', 'it', ',', '=', 'itertools', '.', 'tee', '(', 'obj', ',', '1', ')', 's', '=', 'set', '(', ')', 'too_big', '=', 'False', 'for', 'i', ',', 'v', 'in', 'enu...
Get the types of an iterable.
['Get', 'the', 'types', 'of', 'an', 'iterable', '.']
train
https://github.com/Ffisegydd/whatis/blob/eef780ced61aae6d001aeeef7574e5e27e613583/whatis/_util.py#L28-L44
9,242
offu/WeRoBot
werobot/session/mongodbstorage.py
MongoDBStorage.get
def get(self, id): """ 根据 id 获取数据。 :param id: 要获取的数据的 id :return: 返回取到的数据,如果是空则返回一个空的 ``dict`` 对象 """ document = self._get_document(id) if document: session_json = document["session"] return json_loads(session_json) return {}
python
def get(self, id): """ 根据 id 获取数据。 :param id: 要获取的数据的 id :return: 返回取到的数据,如果是空则返回一个空的 ``dict`` 对象 """ document = self._get_document(id) if document: session_json = document["session"] return json_loads(session_json) return {}
['def', 'get', '(', 'self', ',', 'id', ')', ':', 'document', '=', 'self', '.', '_get_document', '(', 'id', ')', 'if', 'document', ':', 'session_json', '=', 'document', '[', '"session"', ']', 'return', 'json_loads', '(', 'session_json', ')', 'return', '{', '}']
根据 id 获取数据。 :param id: 要获取的数据的 id :return: 返回取到的数据,如果是空则返回一个空的 ``dict`` 对象
['根据', 'id', '获取数据。']
train
https://github.com/offu/WeRoBot/blob/fd42109105b03f9acf45ebd9dcabb9d5cff98f3c/werobot/session/mongodbstorage.py#L33-L44
9,243
manns/pyspread
pyspread/src/gui/_grid.py
GridEventHandlers.OnFind
def OnFind(self, event): """Find functionality, called from toolbar, returns find position""" # Search starts in next cell after the current one gridpos = list(self.grid.actions.cursor) text, flags = event.text, event.flags findpos = self.grid.actions.find(gridpos, text, flags) ...
python
def OnFind(self, event): """Find functionality, called from toolbar, returns find position""" # Search starts in next cell after the current one gridpos = list(self.grid.actions.cursor) text, flags = event.text, event.flags findpos = self.grid.actions.find(gridpos, text, flags) ...
['def', 'OnFind', '(', 'self', ',', 'event', ')', ':', '# Search starts in next cell after the current one', 'gridpos', '=', 'list', '(', 'self', '.', 'grid', '.', 'actions', '.', 'cursor', ')', 'text', ',', 'flags', '=', 'event', '.', 'text', ',', 'event', '.', 'flags', 'findpos', '=', 'self', '.', 'grid', '.', 'actio...
Find functionality, called from toolbar, returns find position
['Find', 'functionality', 'called', 'from', 'toolbar', 'returns', 'find', 'position']
train
https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/gui/_grid.py#L1188-L1212
9,244
pyQode/pyqode.core
pyqode/core/widgets/filesystem_treeview.py
FileSystemHelper.paste_from_clipboard
def paste_from_clipboard(self): """ Pastes files from clipboard. """ to = self.get_current_path() if os.path.isfile(to): to = os.path.abspath(os.path.join(to, os.pardir)) mime = QtWidgets.QApplication.clipboard().mimeData() paste_operation = None ...
python
def paste_from_clipboard(self): """ Pastes files from clipboard. """ to = self.get_current_path() if os.path.isfile(to): to = os.path.abspath(os.path.join(to, os.pardir)) mime = QtWidgets.QApplication.clipboard().mimeData() paste_operation = None ...
['def', 'paste_from_clipboard', '(', 'self', ')', ':', 'to', '=', 'self', '.', 'get_current_path', '(', ')', 'if', 'os', '.', 'path', '.', 'isfile', '(', 'to', ')', ':', 'to', '=', 'os', '.', 'path', '.', 'abspath', '(', 'os', '.', 'path', '.', 'join', '(', 'to', ',', 'os', '.', 'pardir', ')', ')', 'mime', '=', 'QtWidg...
Pastes files from clipboard.
['Pastes', 'files', 'from', 'clipboard', '.']
train
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/filesystem_treeview.py#L372-L389
9,245
fake-name/ChromeController
ChromeController/Generator/Generated.py
ChromeRemoteDebugInterface.DOM_setOuterHTML
def DOM_setOuterHTML(self, nodeId, outerHTML): """ Function path: DOM.setOuterHTML Domain: DOM Method name: setOuterHTML Parameters: Required arguments: 'nodeId' (type: NodeId) -> Id of the node to set markup for. 'outerHTML' (type: string) -> Outer HTML markup to set. No return value. ...
python
def DOM_setOuterHTML(self, nodeId, outerHTML): """ Function path: DOM.setOuterHTML Domain: DOM Method name: setOuterHTML Parameters: Required arguments: 'nodeId' (type: NodeId) -> Id of the node to set markup for. 'outerHTML' (type: string) -> Outer HTML markup to set. No return value. ...
['def', 'DOM_setOuterHTML', '(', 'self', ',', 'nodeId', ',', 'outerHTML', ')', ':', 'assert', 'isinstance', '(', 'outerHTML', ',', '(', 'str', ',', ')', ')', ',', '"Argument \'outerHTML\' must be of type \'[\'str\']\'. Received type: \'%s\'"', '%', 'type', '(', 'outerHTML', ')', 'subdom_funcs', '=', 'self', '.', 'synch...
Function path: DOM.setOuterHTML Domain: DOM Method name: setOuterHTML Parameters: Required arguments: 'nodeId' (type: NodeId) -> Id of the node to set markup for. 'outerHTML' (type: string) -> Outer HTML markup to set. No return value. Description: Sets node HTML markup, returns new n...
['Function', 'path', ':', 'DOM', '.', 'setOuterHTML', 'Domain', ':', 'DOM', 'Method', 'name', ':', 'setOuterHTML', 'Parameters', ':', 'Required', 'arguments', ':', 'nodeId', '(', 'type', ':', 'NodeId', ')', '-', '>', 'Id', 'of', 'the', 'node', 'to', 'set', 'markup', 'for', '.', 'outerHTML', '(', 'type', ':', 'string', ...
train
https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/Generator/Generated.py#L3440-L3459
9,246
thiagopbueno/tf-rddlsim
tfrddlsim/simulation/policy_simulator.py
PolicySimulationCell.initial_state
def initial_state(self) -> StateTensor: '''Returns the initial state tensor.''' s0 = [] for fluent in self._compiler.compile_initial_state(self._batch_size): s0.append(self._output_size(fluent)) s0 = tuple(s0) return s0
python
def initial_state(self) -> StateTensor: '''Returns the initial state tensor.''' s0 = [] for fluent in self._compiler.compile_initial_state(self._batch_size): s0.append(self._output_size(fluent)) s0 = tuple(s0) return s0
['def', 'initial_state', '(', 'self', ')', '->', 'StateTensor', ':', 's0', '=', '[', ']', 'for', 'fluent', 'in', 'self', '.', '_compiler', '.', 'compile_initial_state', '(', 'self', '.', '_batch_size', ')', ':', 's0', '.', 'append', '(', 'self', '.', '_output_size', '(', 'fluent', ')', ')', 's0', '=', 'tuple', '(', 's0...
Returns the initial state tensor.
['Returns', 'the', 'initial', 'state', 'tensor', '.']
train
https://github.com/thiagopbueno/tf-rddlsim/blob/d7102a0ad37d179dbb23141640254ea383d3b43f/tfrddlsim/simulation/policy_simulator.py#L96-L102
9,247
danielperna84/pyhomematic
pyhomematic/devicetypes/helper.py
HelperActorLevel.set_level
def set_level(self, position, channel=None): """Seek a specific value by specifying a float() from 0.0 to 1.0.""" try: position = float(position) except Exception as err: LOG.debug("HelperLevel.set_level: Exception %s" % (err,)) return False self.writ...
python
def set_level(self, position, channel=None): """Seek a specific value by specifying a float() from 0.0 to 1.0.""" try: position = float(position) except Exception as err: LOG.debug("HelperLevel.set_level: Exception %s" % (err,)) return False self.writ...
['def', 'set_level', '(', 'self', ',', 'position', ',', 'channel', '=', 'None', ')', ':', 'try', ':', 'position', '=', 'float', '(', 'position', ')', 'except', 'Exception', 'as', 'err', ':', 'LOG', '.', 'debug', '(', '"HelperLevel.set_level: Exception %s"', '%', '(', 'err', ',', ')', ')', 'return', 'False', 'self', '.'...
Seek a specific value by specifying a float() from 0.0 to 1.0.
['Seek', 'a', 'specific', 'value', 'by', 'specifying', 'a', 'float', '()', 'from', '0', '.', '0', 'to', '1', '.', '0', '.']
train
https://github.com/danielperna84/pyhomematic/blob/8b91f3e84c83f05d289c740d507293a0d6759d8e/pyhomematic/devicetypes/helper.py#L158-L166
9,248
SeattleTestbed/seash
modules/uploaddir/__init__.py
upload_directory_contents
def upload_directory_contents(input_dict, environment_dict): """This function serves to upload every file in a user-supplied source directory to all of the vessels in the current target group. It essentially calls seash's `upload` function repeatedly, each time with a file name taken from the source directory...
python
def upload_directory_contents(input_dict, environment_dict): """This function serves to upload every file in a user-supplied source directory to all of the vessels in the current target group. It essentially calls seash's `upload` function repeatedly, each time with a file name taken from the source directory...
['def', 'upload_directory_contents', '(', 'input_dict', ',', 'environment_dict', ')', ':', '# Check user input and seash state:', '# 1, Make sure there is an active user key.', 'if', 'environment_dict', '[', '"currentkeyname"', ']', 'is', 'None', ':', 'raise', 'seash_exceptions', '.', 'UserError', '(', '"""Error: Pleas...
This function serves to upload every file in a user-supplied source directory to all of the vessels in the current target group. It essentially calls seash's `upload` function repeatedly, each time with a file name taken from the source directory. A note on the input_dict argument: `input_dict` contains ou...
['This', 'function', 'serves', 'to', 'upload', 'every', 'file', 'in', 'a', 'user', '-', 'supplied', 'source', 'directory', 'to', 'all', 'of', 'the', 'vessels', 'in', 'the', 'current', 'target', 'group', '.', 'It', 'essentially', 'calls', 'seash', 's', 'upload', 'function', 'repeatedly', 'each', 'time', 'with', 'a', 'fi...
train
https://github.com/SeattleTestbed/seash/blob/40f9d2285662ff8b61e0468b4196acee089b273b/modules/uploaddir/__init__.py#L26-L95
9,249
cslarsen/crianza
crianza/genetic.py
randomize
def randomize(vm, length=(10,10), ints=(0,999), strs=(1,10), chars=(32,126), instruction_ratio=0.5, number_string_ratio=0.8, exclude=map(crianza.instructions.lookup, [".", "exit", "read", "write", "str"]), restrict_to=None): """Replaces existing code ...
python
def randomize(vm, length=(10,10), ints=(0,999), strs=(1,10), chars=(32,126), instruction_ratio=0.5, number_string_ratio=0.8, exclude=map(crianza.instructions.lookup, [".", "exit", "read", "write", "str"]), restrict_to=None): """Replaces existing code ...
['def', 'randomize', '(', 'vm', ',', 'length', '=', '(', '10', ',', '10', ')', ',', 'ints', '=', '(', '0', ',', '999', ')', ',', 'strs', '=', '(', '1', ',', '10', ')', ',', 'chars', '=', '(', '32', ',', '126', ')', ',', 'instruction_ratio', '=', '0.5', ',', 'number_string_ratio', '=', '0.8', ',', 'exclude', '=', 'map',...
Replaces existing code with completely random instructions. Does not optimize code after generating it. Args: length: Tuple of minimum and maximum code lengths. Code length will be a random number between these two, inclusive values. ints: Integers in the code will be selected at rando...
['Replaces', 'existing', 'code', 'with', 'completely', 'random', 'instructions', '.', 'Does', 'not', 'optimize', 'code', 'after', 'generating', 'it', '.']
train
https://github.com/cslarsen/crianza/blob/fa044f9d491f37cc06892bad14b2c80b8ac5a7cd/crianza/genetic.py#L67-L127
9,250
mdiener/grace
grace/py27/cssmin.py
remove_unnecessary_whitespace
def remove_unnecessary_whitespace(css): """Remove unnecessary whitespace characters.""" def pseudoclasscolon(css): """ Prevents 'p :link' from becoming 'p:link'. Translates 'p :link' into 'p ___PSEUDOCLASSCOLON___link'; this is translated back again later. """ ...
python
def remove_unnecessary_whitespace(css): """Remove unnecessary whitespace characters.""" def pseudoclasscolon(css): """ Prevents 'p :link' from becoming 'p:link'. Translates 'p :link' into 'p ___PSEUDOCLASSCOLON___link'; this is translated back again later. """ ...
['def', 'remove_unnecessary_whitespace', '(', 'css', ')', ':', 'def', 'pseudoclasscolon', '(', 'css', ')', ':', '"""\n Prevents \'p :link\' from becoming \'p:link\'.\n\n Translates \'p :link\' into \'p ___PSEUDOCLASSCOLON___link\'; this is\n translated back again later.\n """', 'regex', '=',...
Remove unnecessary whitespace characters.
['Remove', 'unnecessary', 'whitespace', 'characters', '.']
train
https://github.com/mdiener/grace/blob/2dab13a2cf636da5da989904c5885166fc94d36d/grace/py27/cssmin.py#L53-L93
9,251
aws/sagemaker-containers
src/sagemaker_containers/_modules.py
prepare
def prepare(path, name): # type: (str, str) -> None """Prepare a Python script (or module) to be imported as a module. If the script does not contain a setup.py file, it creates a minimal setup. Args: path (str): path to directory with the script or module. name (str): name of the script or...
python
def prepare(path, name): # type: (str, str) -> None """Prepare a Python script (or module) to be imported as a module. If the script does not contain a setup.py file, it creates a minimal setup. Args: path (str): path to directory with the script or module. name (str): name of the script or...
['def', 'prepare', '(', 'path', ',', 'name', ')', ':', '# type: (str, str) -> None', 'setup_path', '=', 'os', '.', 'path', '.', 'join', '(', 'path', ',', "'setup.py'", ')', 'if', 'not', 'os', '.', 'path', '.', 'exists', '(', 'setup_path', ')', ':', 'data', '=', 'textwrap', '.', 'dedent', '(', '"""\n from setupto...
Prepare a Python script (or module) to be imported as a module. If the script does not contain a setup.py file, it creates a minimal setup. Args: path (str): path to directory with the script or module. name (str): name of the script or module.
['Prepare', 'a', 'Python', 'script', '(', 'or', 'module', ')', 'to', 'be', 'imported', 'as', 'a', 'module', '.', 'If', 'the', 'script', 'does', 'not', 'contain', 'a', 'setup', '.', 'py', 'file', 'it', 'creates', 'a', 'minimal', 'setup', '.', 'Args', ':', 'path', '(', 'str', ')', ':', 'path', 'to', 'directory', 'with', ...
train
https://github.com/aws/sagemaker-containers/blob/0030f07abbaf22a55d986d97274d7a8d1aa1f10c/src/sagemaker_containers/_modules.py#L54-L93
9,252
grycap/RADL
radl/radl.py
Features.hasFeature
def hasFeature(self, prop, check_softs=False): """Return if there is a property with that name.""" return prop in self.props or (check_softs and any([fs.hasFeature(prop) for fs in self.props.get(SoftFeatures.SOFT, [])]))
python
def hasFeature(self, prop, check_softs=False): """Return if there is a property with that name.""" return prop in self.props or (check_softs and any([fs.hasFeature(prop) for fs in self.props.get(SoftFeatures.SOFT, [])]))
['def', 'hasFeature', '(', 'self', ',', 'prop', ',', 'check_softs', '=', 'False', ')', ':', 'return', 'prop', 'in', 'self', '.', 'props', 'or', '(', 'check_softs', 'and', 'any', '(', '[', 'fs', '.', 'hasFeature', '(', 'prop', ')', 'for', 'fs', 'in', 'self', '.', 'props', '.', 'get', '(', 'SoftFeatures', '.', 'SOFT', ',...
Return if there is a property with that name.
['Return', 'if', 'there', 'is', 'a', 'property', 'with', 'that', 'name', '.']
train
https://github.com/grycap/RADL/blob/03ccabb0313a48a5aa0e20c1f7983fddcb95e9cb/radl/radl.py#L312-L316
9,253
dhylands/rshell
rshell/main.py
rm
def rm(filename, recursive=False, force=False): """Removes a file or directory tree.""" return auto(remove_file, filename, recursive, force)
python
def rm(filename, recursive=False, force=False): """Removes a file or directory tree.""" return auto(remove_file, filename, recursive, force)
['def', 'rm', '(', 'filename', ',', 'recursive', '=', 'False', ',', 'force', '=', 'False', ')', ':', 'return', 'auto', '(', 'remove_file', ',', 'filename', ',', 'recursive', ',', 'force', ')']
Removes a file or directory tree.
['Removes', 'a', 'file', 'or', 'directory', 'tree', '.']
train
https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L834-L836
9,254
camptocamp/Studio
studio/controllers/mapfiles.py
MapfilesController._get_map_from_user_by_id
def _get_map_from_user_by_id(self, user, map_id): """ Get a mapfile owned by a user from the database by map_id. """ req = Session.query(Map).select_from(join(Map, User)) try: return req.filter(and_(User.login==user, Map.id==map_id)).one() except Exception, e: ...
python
def _get_map_from_user_by_id(self, user, map_id): """ Get a mapfile owned by a user from the database by map_id. """ req = Session.query(Map).select_from(join(Map, User)) try: return req.filter(and_(User.login==user, Map.id==map_id)).one() except Exception, e: ...
['def', '_get_map_from_user_by_id', '(', 'self', ',', 'user', ',', 'map_id', ')', ':', 'req', '=', 'Session', '.', 'query', '(', 'Map', ')', '.', 'select_from', '(', 'join', '(', 'Map', ',', 'User', ')', ')', 'try', ':', 'return', 'req', '.', 'filter', '(', 'and_', '(', 'User', '.', 'login', '==', 'user', ',', 'Map', '...
Get a mapfile owned by a user from the database by map_id.
['Get', 'a', 'mapfile', 'owned', 'by', 'a', 'user', 'from', 'the', 'database', 'by', 'map_id', '.']
train
https://github.com/camptocamp/Studio/blob/43cb7298434fb606b15136801b79b03571a2f27e/studio/controllers/mapfiles.py#L197-L204
9,255
f3at/feat
src/feat/common/reflect.py
named_module
def named_module(name): """Returns a module given its name.""" module = __import__(name) packages = name.split(".")[1:] m = module for p in packages: m = getattr(m, p) return m
python
def named_module(name): """Returns a module given its name.""" module = __import__(name) packages = name.split(".")[1:] m = module for p in packages: m = getattr(m, p) return m
['def', 'named_module', '(', 'name', ')', ':', 'module', '=', '__import__', '(', 'name', ')', 'packages', '=', 'name', '.', 'split', '(', '"."', ')', '[', '1', ':', ']', 'm', '=', 'module', 'for', 'p', 'in', 'packages', ':', 'm', '=', 'getattr', '(', 'm', ',', 'p', ')', 'return', 'm']
Returns a module given its name.
['Returns', 'a', 'module', 'given', 'its', 'name', '.']
train
https://github.com/f3at/feat/blob/15da93fc9d6ec8154f52a9172824e25821195ef8/src/feat/common/reflect.py#L55-L62
9,256
Shizmob/pydle
pydle/features/isupport.py
ISUPPORTSupport.on_isupport_maxbans
async def on_isupport_maxbans(self, value): """ Maximum entries in ban list. Replaced by MAXLIST. """ if 'MAXLIST' not in self._isupport: if not self._list_limits: self._list_limits = {} self._list_limits['b'] = int(value)
python
async def on_isupport_maxbans(self, value): """ Maximum entries in ban list. Replaced by MAXLIST. """ if 'MAXLIST' not in self._isupport: if not self._list_limits: self._list_limits = {} self._list_limits['b'] = int(value)
['async', 'def', 'on_isupport_maxbans', '(', 'self', ',', 'value', ')', ':', 'if', "'MAXLIST'", 'not', 'in', 'self', '.', '_isupport', ':', 'if', 'not', 'self', '.', '_list_limits', ':', 'self', '.', '_list_limits', '=', '{', '}', 'self', '.', '_list_limits', '[', "'b'", ']', '=', 'int', '(', 'value', ')']
Maximum entries in ban list. Replaced by MAXLIST.
['Maximum', 'entries', 'in', 'ban', 'list', '.', 'Replaced', 'by', 'MAXLIST', '.']
train
https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/isupport.py#L144-L149
9,257
ArtoLabs/SimpleSteem
simplesteem/simplesteem.py
SimpleSteem.rshares_to_steem
def rshares_to_steem (self, rshares): ''' Gets the reward pool balances then calculates rshares to steem ''' self.reward_pool_balances() return round( rshares * self.reward_balance / self.recent_claims * self.base, 4)
python
def rshares_to_steem (self, rshares): ''' Gets the reward pool balances then calculates rshares to steem ''' self.reward_pool_balances() return round( rshares * self.reward_balance / self.recent_claims * self.base, 4)
['def', 'rshares_to_steem', '(', 'self', ',', 'rshares', ')', ':', 'self', '.', 'reward_pool_balances', '(', ')', 'return', 'round', '(', 'rshares', '*', 'self', '.', 'reward_balance', '/', 'self', '.', 'recent_claims', '*', 'self', '.', 'base', ',', '4', ')']
Gets the reward pool balances then calculates rshares to steem
['Gets', 'the', 'reward', 'pool', 'balances', 'then', 'calculates', 'rshares', 'to', 'steem']
train
https://github.com/ArtoLabs/SimpleSteem/blob/ce8be0ae81f8878b460bc156693f1957f7dd34a3/simplesteem/simplesteem.py#L202-L211
9,258
peterbrittain/asciimatics
asciimatics/particles.py
ParticleEmitter.update
def update(self): """ The function to draw a new frame for the particle system. """ # Spawn new particles if required if self.time_left > 0: self.time_left -= 1 for _ in range(self._count): new_particle = self._new_particle() ...
python
def update(self): """ The function to draw a new frame for the particle system. """ # Spawn new particles if required if self.time_left > 0: self.time_left -= 1 for _ in range(self._count): new_particle = self._new_particle() ...
['def', 'update', '(', 'self', ')', ':', '# Spawn new particles if required', 'if', 'self', '.', 'time_left', '>', '0', ':', 'self', '.', 'time_left', '-=', '1', 'for', '_', 'in', 'range', '(', 'self', '.', '_count', ')', ':', 'new_particle', '=', 'self', '.', '_new_particle', '(', ')', 'if', 'new_particle', 'is', 'not...
The function to draw a new frame for the particle system.
['The', 'function', 'to', 'draw', 'a', 'new', 'frame', 'for', 'the', 'particle', 'system', '.']
train
https://github.com/peterbrittain/asciimatics/blob/f471427d7786ce2d5f1eeb2dae0e67d19e46e085/asciimatics/particles.py#L167-L201
9,259
dreipol/django-collectfaster
collectfaster/management/commands/collectstatic.py
Command.gevent_worker
def gevent_worker(self): """ Process one task after another by calling the handler (`copy_file` or `copy_link`) method of the super class. """ while not self.task_queue.empty(): task_kwargs = self.task_queue.get() handler_type = task_kwargs.pop('handler_type') ...
python
def gevent_worker(self): """ Process one task after another by calling the handler (`copy_file` or `copy_link`) method of the super class. """ while not self.task_queue.empty(): task_kwargs = self.task_queue.get() handler_type = task_kwargs.pop('handler_type') ...
['def', 'gevent_worker', '(', 'self', ')', ':', 'while', 'not', 'self', '.', 'task_queue', '.', 'empty', '(', ')', ':', 'task_kwargs', '=', 'self', '.', 'task_queue', '.', 'get', '(', ')', 'handler_type', '=', 'task_kwargs', '.', 'pop', '(', "'handler_type'", ')', 'if', 'handler_type', '==', "'link'", ':', 'super', '('...
Process one task after another by calling the handler (`copy_file` or `copy_link`) method of the super class.
['Process', 'one', 'task', 'after', 'another', 'by', 'calling', 'the', 'handler', '(', 'copy_file', 'or', 'copy_link', ')', 'method', 'of', 'the', 'super', 'class', '.']
train
https://github.com/dreipol/django-collectfaster/blob/13ac0df7d153a49b8c3596692741dcab441d57ce/collectfaster/management/commands/collectstatic.py#L128-L139
9,260
b3j0f/schema
b3j0f/schema/lang/factory.py
getresource
def getresource(self, schemacls, name): """Get a resource from a builder name. :param type schemacls: waited schema class. :param str name: builder name to use. :return: resource returned by the right builder.getresource(schema). """ return _SCHEMAFACTORY.getresource(schemacls=schemacls, name=n...
python
def getresource(self, schemacls, name): """Get a resource from a builder name. :param type schemacls: waited schema class. :param str name: builder name to use. :return: resource returned by the right builder.getresource(schema). """ return _SCHEMAFACTORY.getresource(schemacls=schemacls, name=n...
['def', 'getresource', '(', 'self', ',', 'schemacls', ',', 'name', ')', ':', 'return', '_SCHEMAFACTORY', '.', 'getresource', '(', 'schemacls', '=', 'schemacls', ',', 'name', '=', 'name', ')']
Get a resource from a builder name. :param type schemacls: waited schema class. :param str name: builder name to use. :return: resource returned by the right builder.getresource(schema).
['Get', 'a', 'resource', 'from', 'a', 'builder', 'name', '.']
train
https://github.com/b3j0f/schema/blob/1c88c23337f5fef50254e65bd407112c43396dd9/b3j0f/schema/lang/factory.py#L216-L223
9,261
gwastro/pycbc
pycbc/inference/option_utils.py
data_from_cli
def data_from_cli(opts): """Loads the data needed for a model from the given command-line options. Gates specifed on the command line are also applied. Parameters ---------- opts : ArgumentParser parsed args Argument options parsed from a command line string (the sort of thing retur...
python
def data_from_cli(opts): """Loads the data needed for a model from the given command-line options. Gates specifed on the command line are also applied. Parameters ---------- opts : ArgumentParser parsed args Argument options parsed from a command line string (the sort of thing retur...
['def', 'data_from_cli', '(', 'opts', ')', ':', '# get gates to apply', 'gates', '=', 'gates_from_cli', '(', 'opts', ')', 'psd_gates', '=', 'psd_gates_from_cli', '(', 'opts', ')', '# get strain time series', 'instruments', '=', 'opts', '.', 'instruments', 'if', 'opts', '.', 'instruments', 'is', 'not', 'None', 'else', '...
Loads the data needed for a model from the given command-line options. Gates specifed on the command line are also applied. Parameters ---------- opts : ArgumentParser parsed args Argument options parsed from a command line string (the sort of thing returned by `parser.parse_args`). ...
['Loads', 'the', 'data', 'needed', 'for', 'a', 'model', 'from', 'the', 'given', 'command', '-', 'line', 'options', '.', 'Gates', 'specifed', 'on', 'the', 'command', 'line', 'are', 'also', 'applied', '.']
train
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inference/option_utils.py#L63-L141
9,262
espenak/djangosenchatools
djangosenchatools/management/commands/senchatoolsbuild.py
get_installed_extjs_apps
def get_installed_extjs_apps(): """ Get all installed extjs apps. :return: List of ``(appdir, module, appname)``. """ installed_apps = [] checked = set() for app in settings.INSTALLED_APPS: if not app.startswith('django.') and not app in checked: checked.add(app) ...
python
def get_installed_extjs_apps(): """ Get all installed extjs apps. :return: List of ``(appdir, module, appname)``. """ installed_apps = [] checked = set() for app in settings.INSTALLED_APPS: if not app.startswith('django.') and not app in checked: checked.add(app) ...
['def', 'get_installed_extjs_apps', '(', ')', ':', 'installed_apps', '=', '[', ']', 'checked', '=', 'set', '(', ')', 'for', 'app', 'in', 'settings', '.', 'INSTALLED_APPS', ':', 'if', 'not', 'app', '.', 'startswith', '(', "'django.'", ')', 'and', 'not', 'app', 'in', 'checked', ':', 'checked', '.', 'add', '(', 'app', ')'...
Get all installed extjs apps. :return: List of ``(appdir, module, appname)``.
['Get', 'all', 'installed', 'extjs', 'apps', '.']
train
https://github.com/espenak/djangosenchatools/blob/da1bca9365300de303e833de4b4bd57671c1d11a/djangosenchatools/management/commands/senchatoolsbuild.py#L34-L49
9,263
UCL-INGI/INGInious
inginious/frontend/accessible_time.py
parse_date
def parse_date(date, default=None): """ Parse a valid date """ if date == "": if default is not None: return default else: raise Exception("Unknown format for " + date) for format_type in ["%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M", "%Y-%m-%d %H", "%Y-%m-%d", "%d/%m/%Y %H...
python
def parse_date(date, default=None): """ Parse a valid date """ if date == "": if default is not None: return default else: raise Exception("Unknown format for " + date) for format_type in ["%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M", "%Y-%m-%d %H", "%Y-%m-%d", "%d/%m/%Y %H...
['def', 'parse_date', '(', 'date', ',', 'default', '=', 'None', ')', ':', 'if', 'date', '==', '""', ':', 'if', 'default', 'is', 'not', 'None', ':', 'return', 'default', 'else', ':', 'raise', 'Exception', '(', '"Unknown format for "', '+', 'date', ')', 'for', 'format_type', 'in', '[', '"%Y-%m-%d %H:%M:%S"', ',', '"%Y-%m...
Parse a valid date
['Parse', 'a', 'valid', 'date']
train
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/accessible_time.py#L11-L25
9,264
CamDavidsonPilon/lifelines
lifelines/fitters/log_logistic_aft_fitter.py
LogLogisticAFTFitter.predict_cumulative_hazard
def predict_cumulative_hazard(self, X, times=None, ancillary_X=None): """ Return the cumulative hazard rate of subjects in X at time points. Parameters ---------- X: numpy array or DataFrame a (n,d) covariate numpy array or DataFrame. If a DataFrame, columns ...
python
def predict_cumulative_hazard(self, X, times=None, ancillary_X=None): """ Return the cumulative hazard rate of subjects in X at time points. Parameters ---------- X: numpy array or DataFrame a (n,d) covariate numpy array or DataFrame. If a DataFrame, columns ...
['def', 'predict_cumulative_hazard', '(', 'self', ',', 'X', ',', 'times', '=', 'None', ',', 'ancillary_X', '=', 'None', ')', ':', 'times', '=', 'coalesce', '(', 'times', ',', 'self', '.', 'timeline', ',', 'np', '.', 'unique', '(', 'self', '.', 'durations', ')', ')', 'alpha_', ',', 'beta_', '=', 'self', '.', '_prep_inpu...
Return the cumulative hazard rate of subjects in X at time points. Parameters ---------- X: numpy array or DataFrame a (n,d) covariate numpy array or DataFrame. If a DataFrame, columns can be in any order. If a numpy array, columns must be in the same order a...
['Return', 'the', 'cumulative', 'hazard', 'rate', 'of', 'subjects', 'in', 'X', 'at', 'time', 'points', '.']
train
https://github.com/CamDavidsonPilon/lifelines/blob/bdf6be6f1d10eea4c46365ee0ee6a47d8c30edf8/lifelines/fitters/log_logistic_aft_fitter.py#L157-L183
9,265
dylanaraps/bum
bum/song.py
get_art
def get_art(cache_dir, size, client): """Get the album art.""" song = client.currentsong() if len(song) < 2: print("album: Nothing currently playing.") return file_name = f"{song['artist']}_{song['album']}_{size}.jpg".replace("/", "") file_name = cache_dir / file_name if file_...
python
def get_art(cache_dir, size, client): """Get the album art.""" song = client.currentsong() if len(song) < 2: print("album: Nothing currently playing.") return file_name = f"{song['artist']}_{song['album']}_{size}.jpg".replace("/", "") file_name = cache_dir / file_name if file_...
['def', 'get_art', '(', 'cache_dir', ',', 'size', ',', 'client', ')', ':', 'song', '=', 'client', '.', 'currentsong', '(', ')', 'if', 'len', '(', 'song', ')', '<', '2', ':', 'print', '(', '"album: Nothing currently playing."', ')', 'return', 'file_name', '=', 'f"{song[\'artist\']}_{song[\'album\']}_{size}.jpg"', '.', '...
Get the album art.
['Get', 'the', 'album', 'art', '.']
train
https://github.com/dylanaraps/bum/blob/004d795a67398e79f2c098d7775e9cd97231646b/bum/song.py#L25-L50
9,266
unitedstack/steth
stetho/agent/common/utils.py
get_interface
def get_interface(interface): """Support Centos standard physical interface, such as eth0. """ # Supported CentOS Version supported_dists = ['7.0', '6.5'] def format_centos_7_0(inf): pattern = r'<([A-Z]+)' state = re.search(pattern, stdout[0]).groups()[0] state = 'UP'...
python
def get_interface(interface): """Support Centos standard physical interface, such as eth0. """ # Supported CentOS Version supported_dists = ['7.0', '6.5'] def format_centos_7_0(inf): pattern = r'<([A-Z]+)' state = re.search(pattern, stdout[0]).groups()[0] state = 'UP'...
['def', 'get_interface', '(', 'interface', ')', ':', '# Supported CentOS Version', 'supported_dists', '=', '[', "'7.0'", ',', "'6.5'", ']', 'def', 'format_centos_7_0', '(', 'inf', ')', ':', 'pattern', '=', "r'<([A-Z]+)'", 'state', '=', 're', '.', 'search', '(', 'pattern', ',', 'stdout', '[', '0', ']', ')', '.', 'groups...
Support Centos standard physical interface, such as eth0.
['Support', 'Centos', 'standard', 'physical', 'interface', 'such', 'as', 'eth0', '.']
train
https://github.com/unitedstack/steth/blob/955884ceebf3bdc474c93cc5cf555e67d16458f1/stetho/agent/common/utils.py#L84-L147
9,267
trevisanj/a99
a99/fileio.py
crunch_dir
def crunch_dir(name, n=50): """Puts "..." in the middle of a directory name if lengh > n.""" if len(name) > n + 3: name = "..." + name[-n:] return name
python
def crunch_dir(name, n=50): """Puts "..." in the middle of a directory name if lengh > n.""" if len(name) > n + 3: name = "..." + name[-n:] return name
['def', 'crunch_dir', '(', 'name', ',', 'n', '=', '50', ')', ':', 'if', 'len', '(', 'name', ')', '>', 'n', '+', '3', ':', 'name', '=', '"..."', '+', 'name', '[', '-', 'n', ':', ']', 'return', 'name']
Puts "..." in the middle of a directory name if lengh > n.
['Puts', '...', 'in', 'the', 'middle', 'of', 'a', 'directory', 'name', 'if', 'lengh', '>', 'n', '.']
train
https://github.com/trevisanj/a99/blob/193e6e3c9b3e4f4a0ba7eb3eece846fe7045c539/a99/fileio.py#L32-L36
9,268
michael-lazar/rtv
rtv/packages/praw/decorators.py
alias_function
def alias_function(function, class_name): """Create a RedditContentObject function mapped to a BaseReddit function. The BaseReddit classes define the majority of the API's functions. The first argument for many of these functions is the RedditContentObject that they operate on. This factory returns fun...
python
def alias_function(function, class_name): """Create a RedditContentObject function mapped to a BaseReddit function. The BaseReddit classes define the majority of the API's functions. The first argument for many of these functions is the RedditContentObject that they operate on. This factory returns fun...
['def', 'alias_function', '(', 'function', ',', 'class_name', ')', ':', '@', 'wraps', '(', 'function', ')', 'def', 'wrapped', '(', 'self', ',', '*', 'args', ',', '*', '*', 'kwargs', ')', ':', 'func_args', '=', '_make_func_args', '(', 'function', ')', 'if', "'subreddit'", 'in', 'func_args', 'and', 'func_args', '.', 'ind...
Create a RedditContentObject function mapped to a BaseReddit function. The BaseReddit classes define the majority of the API's functions. The first argument for many of these functions is the RedditContentObject that they operate on. This factory returns functions appropriate to be called on a RedditCo...
['Create', 'a', 'RedditContentObject', 'function', 'mapped', 'to', 'a', 'BaseReddit', 'function', '.']
train
https://github.com/michael-lazar/rtv/blob/ccef2af042566ad384977028cf0bde01bc524dda/rtv/packages/praw/decorators.py#L44-L70
9,269
robhowley/nhlscrapi
nhlscrapi/games/faceoffcomp.py
FaceOffComparison.fo_pct_by_zone
def fo_pct_by_zone(self): """ Get the by team face-off win % by zone. Format is :returns: dict ``{ 'home/away': { 'off/def/neut': % } }`` """ bz = self.by_zone return { t: { z: bz[t][z]['won']/(1.0*bz[t][z]['total']) if bz[t][z]['t...
python
def fo_pct_by_zone(self): """ Get the by team face-off win % by zone. Format is :returns: dict ``{ 'home/away': { 'off/def/neut': % } }`` """ bz = self.by_zone return { t: { z: bz[t][z]['won']/(1.0*bz[t][z]['total']) if bz[t][z]['t...
['def', 'fo_pct_by_zone', '(', 'self', ')', ':', 'bz', '=', 'self', '.', 'by_zone', 'return', '{', 't', ':', '{', 'z', ':', 'bz', '[', 't', ']', '[', 'z', ']', '[', "'won'", ']', '/', '(', '1.0', '*', 'bz', '[', 't', ']', '[', 'z', ']', '[', "'total'", ']', ')', 'if', 'bz', '[', 't', ']', '[', 'z', ']', '[', "'total'",...
Get the by team face-off win % by zone. Format is :returns: dict ``{ 'home/away': { 'off/def/neut': % } }``
['Get', 'the', 'by', 'team', 'face', '-', 'off', 'win', '%', 'by', 'zone', '.', 'Format', 'is', ':', 'returns', ':', 'dict', '{', 'home', '/', 'away', ':', '{', 'off', '/', 'def', '/', 'neut', ':', '%', '}', '}']
train
https://github.com/robhowley/nhlscrapi/blob/2273683497ff27b0e92c8d1557ff0ce962dbf43b/nhlscrapi/games/faceoffcomp.py#L129-L144
9,270
collectiveacuity/labPack
labpack/events/meetup.py
meetupClient.update_member_profile
def update_member_profile(self, brief_details, profile_details): ''' a method to update user profile details on meetup :param brief_details: dictionary with member brief details with updated values :param profile_details: dictionary with member profile details with updated values ...
python
def update_member_profile(self, brief_details, profile_details): ''' a method to update user profile details on meetup :param brief_details: dictionary with member brief details with updated values :param profile_details: dictionary with member profile details with updated values ...
['def', 'update_member_profile', '(', 'self', ',', 'brief_details', ',', 'profile_details', ')', ':', '# https://www.meetup.com/meetup_api/docs/members/:member_id/#edit\r', 'title', '=', "'%s.update_member_profile'", '%', 'self', '.', '__class__', '.', '__name__', '# validate permissions\r', 'if', 'not', "'profile_edit...
a method to update user profile details on meetup :param brief_details: dictionary with member brief details with updated values :param profile_details: dictionary with member profile details with updated values :return: dictionary with partial profile details inside [json] key
['a', 'method', 'to', 'update', 'user', 'profile', 'details', 'on', 'meetup', ':', 'param', 'brief_details', ':', 'dictionary', 'with', 'member', 'brief', 'details', 'with', 'updated', 'values', ':', 'param', 'profile_details', ':', 'dictionary', 'with', 'member', 'profile', 'details', 'with', 'updated', 'values', ':',...
train
https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/events/meetup.py#L1178-L1242
9,271
saltstack/salt
salt/states/zpool.py
present
def present(name, properties=None, filesystem_properties=None, layout=None, config=None): ''' ensure storage pool is present on the system name : string name of storage pool properties : dict optional set of properties to set for the storage pool filesystem_properties : dict ...
python
def present(name, properties=None, filesystem_properties=None, layout=None, config=None): ''' ensure storage pool is present on the system name : string name of storage pool properties : dict optional set of properties to set for the storage pool filesystem_properties : dict ...
['def', 'present', '(', 'name', ',', 'properties', '=', 'None', ',', 'filesystem_properties', '=', 'None', ',', 'layout', '=', 'None', ',', 'config', '=', 'None', ')', ':', 'ret', '=', '{', "'name'", ':', 'name', ',', "'changes'", ':', '{', '}', ',', "'result'", ':', 'None', ',', "'comment'", ':', "''", '}', '# config ...
ensure storage pool is present on the system name : string name of storage pool properties : dict optional set of properties to set for the storage pool filesystem_properties : dict optional set of filesystem properties to set for the storage pool (creation only) layout: dict ...
['ensure', 'storage', 'pool', 'is', 'present', 'on', 'the', 'system']
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/zpool.py#L170-L381
9,272
gwastro/pycbc
pycbc/waveform/bank.py
sigma_cached
def sigma_cached(self, psd): """ Cache sigma calculate for use in tandem with the FilterBank class """ if not hasattr(self, '_sigmasq'): from pycbc.opt import LimitedSizeDict self._sigmasq = LimitedSizeDict(size_limit=2**5) key = id(psd) if not hasattr(psd, '_sigma_cached_key'): ...
python
def sigma_cached(self, psd): """ Cache sigma calculate for use in tandem with the FilterBank class """ if not hasattr(self, '_sigmasq'): from pycbc.opt import LimitedSizeDict self._sigmasq = LimitedSizeDict(size_limit=2**5) key = id(psd) if not hasattr(psd, '_sigma_cached_key'): ...
['def', 'sigma_cached', '(', 'self', ',', 'psd', ')', ':', 'if', 'not', 'hasattr', '(', 'self', ',', "'_sigmasq'", ')', ':', 'from', 'pycbc', '.', 'opt', 'import', 'LimitedSizeDict', 'self', '.', '_sigmasq', '=', 'LimitedSizeDict', '(', 'size_limit', '=', '2', '**', '5', ')', 'key', '=', 'id', '(', 'psd', ')', 'if', 'n...
Cache sigma calculate for use in tandem with the FilterBank class
['Cache', 'sigma', 'calculate', 'for', 'use', 'in', 'tandem', 'with', 'the', 'FilterBank', 'class']
train
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/waveform/bank.py#L42-L89
9,273
spyder-ide/spyder
spyder/config/user.py
UserConfig.get
def get(self, section, option, default=NoDefault): """ Get an option section=None: attribute a default section name default: default value (if not specified, an exception will be raised if option doesn't exist) """ section = self._check_section_option(secti...
python
def get(self, section, option, default=NoDefault): """ Get an option section=None: attribute a default section name default: default value (if not specified, an exception will be raised if option doesn't exist) """ section = self._check_section_option(secti...
['def', 'get', '(', 'self', ',', 'section', ',', 'option', ',', 'default', '=', 'NoDefault', ')', ':', 'section', '=', 'self', '.', '_check_section_option', '(', 'section', ',', 'option', ')', 'if', 'not', 'self', '.', 'has_section', '(', 'section', ')', ':', 'if', 'default', 'is', 'NoDefault', ':', 'raise', 'cp', '.',...
Get an option section=None: attribute a default section name default: default value (if not specified, an exception will be raised if option doesn't exist)
['Get', 'an', 'option', 'section', '=', 'None', ':', 'attribute', 'a', 'default', 'section', 'name', 'default', ':', 'default', 'value', '(', 'if', 'not', 'specified', 'an', 'exception', 'will', 'be', 'raised', 'if', 'option', 'doesn', 't', 'exist', ')']
train
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/config/user.py#L365-L415
9,274
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/worker.py
EvaluationWorker.run_attacks
def run_attacks(self): """Method which evaluates all attack work. In a loop this method queries not completed attack work, picks one attack work and runs it. """ logging.info('******** Start evaluation of attacks ********') prev_submission_id = None while True: # wait until work is av...
python
def run_attacks(self): """Method which evaluates all attack work. In a loop this method queries not completed attack work, picks one attack work and runs it. """ logging.info('******** Start evaluation of attacks ********') prev_submission_id = None while True: # wait until work is av...
['def', 'run_attacks', '(', 'self', ')', ':', 'logging', '.', 'info', '(', "'******** Start evaluation of attacks ********'", ')', 'prev_submission_id', '=', 'None', 'while', 'True', ':', '# wait until work is available', 'self', '.', 'attack_work', '.', 'read_all_from_datastore', '(', ')', 'if', 'not', 'self', '.', 'a...
Method which evaluates all attack work. In a loop this method queries not completed attack work, picks one attack work and runs it.
['Method', 'which', 'evaluates', 'all', 'attack', 'work', '.']
train
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/worker.py#L689-L732
9,275
saltstack/salt
salt/modules/napalm_network.py
_filter_dict
def _filter_dict(input_dict, search_key, search_value): ''' Filters a dictionary of dictionaries by a key-value pair. :param input_dict: is a dictionary whose values are lists of dictionaries :param search_key: is the key in the leaf dictionaries :param search_values: is the value in the lea...
python
def _filter_dict(input_dict, search_key, search_value): ''' Filters a dictionary of dictionaries by a key-value pair. :param input_dict: is a dictionary whose values are lists of dictionaries :param search_key: is the key in the leaf dictionaries :param search_values: is the value in the lea...
['def', '_filter_dict', '(', 'input_dict', ',', 'search_key', ',', 'search_value', ')', ':', 'output_dict', '=', 'dict', '(', ')', 'for', 'key', ',', 'key_list', 'in', 'six', '.', 'iteritems', '(', 'input_dict', ')', ':', 'key_list_filtered', '=', '_filter_list', '(', 'key_list', ',', 'search_key', ',', 'search_value',...
Filters a dictionary of dictionaries by a key-value pair. :param input_dict: is a dictionary whose values are lists of dictionaries :param search_key: is the key in the leaf dictionaries :param search_values: is the value in the leaf dictionaries :return: filtered dictionary
['Filters', 'a', 'dictionary', 'of', 'dictionaries', 'by', 'a', 'key', '-', 'value', 'pair', '.']
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_network.py#L90-L108
9,276
kageurufu/AsyncIRC
asyncirc/ircclient.py
IRCClient._async_recv
def _async_recv(self): """No raw bytes should escape from this, all byte encoding and decoding should be handling inside this function""" logging.info("Receive loop started") recbuffer = b"" while not self._stop_event.is_set(): time.sleep(0.01) try: ...
python
def _async_recv(self): """No raw bytes should escape from this, all byte encoding and decoding should be handling inside this function""" logging.info("Receive loop started") recbuffer = b"" while not self._stop_event.is_set(): time.sleep(0.01) try: ...
['def', '_async_recv', '(', 'self', ')', ':', 'logging', '.', 'info', '(', '"Receive loop started"', ')', 'recbuffer', '=', 'b""', 'while', 'not', 'self', '.', '_stop_event', '.', 'is_set', '(', ')', ':', 'time', '.', 'sleep', '(', '0.01', ')', 'try', ':', 'recbuffer', '=', 'recbuffer', '+', 'self', '.', '_socket', '.'...
No raw bytes should escape from this, all byte encoding and decoding should be handling inside this function
['No', 'raw', 'bytes', 'should', 'escape', 'from', 'this', 'all', 'byte', 'encoding', 'and', 'decoding', 'should', 'be', 'handling', 'inside', 'this', 'function']
train
https://github.com/kageurufu/AsyncIRC/blob/73e2c14ad87a2e86a64c7e79fc5289b0333246f9/asyncirc/ircclient.py#L111-L129
9,277
ramses-tech/ramses
ramses/utils.py
get_static_parent
def get_static_parent(raml_resource, method=None): """ Get static parent resource of :raml_resource: with HTTP method :method:. :param raml_resource:Instance of ramlfications.raml.ResourceNode. :param method: HTTP method name which matching static resource must have. """ parent = raml_r...
python
def get_static_parent(raml_resource, method=None): """ Get static parent resource of :raml_resource: with HTTP method :method:. :param raml_resource:Instance of ramlfications.raml.ResourceNode. :param method: HTTP method name which matching static resource must have. """ parent = raml_r...
['def', 'get_static_parent', '(', 'raml_resource', ',', 'method', '=', 'None', ')', ':', 'parent', '=', 'raml_resource', '.', 'parent', 'while', 'is_dynamic_resource', '(', 'parent', ')', ':', 'parent', '=', 'parent', '.', 'parent', 'if', 'parent', 'is', 'None', ':', 'return', 'parent', 'match_method', '=', 'method', '...
Get static parent resource of :raml_resource: with HTTP method :method:. :param raml_resource:Instance of ramlfications.raml.ResourceNode. :param method: HTTP method name which matching static resource must have.
['Get', 'static', 'parent', 'resource', 'of', ':', 'raml_resource', ':', 'with', 'HTTP', 'method', ':', 'method', ':', '.']
train
https://github.com/ramses-tech/ramses/blob/ea2e1e896325b7256cdf5902309e05fd98e0c14c/ramses/utils.py#L189-L214
9,278
pantsbuild/pants
contrib/go/src/python/pants/contrib/go/tasks/go_compile.py
GoCompile._sync_binary_dep_links
def _sync_binary_dep_links(self, target, gopath, lib_binary_map): """Syncs symlinks under gopath to the library binaries of target's transitive dependencies. :param Target target: Target whose transitive dependencies must be linked. :param str gopath: $GOPATH of target whose "pkg/" directory must be popula...
python
def _sync_binary_dep_links(self, target, gopath, lib_binary_map): """Syncs symlinks under gopath to the library binaries of target's transitive dependencies. :param Target target: Target whose transitive dependencies must be linked. :param str gopath: $GOPATH of target whose "pkg/" directory must be popula...
['def', '_sync_binary_dep_links', '(', 'self', ',', 'target', ',', 'gopath', ',', 'lib_binary_map', ')', ':', 'required_links', '=', 'set', '(', ')', 'for', 'dep', 'in', 'target', '.', 'closure', '(', ')', ':', 'if', 'dep', '==', 'target', ':', 'continue', 'if', 'not', 'isinstance', '(', 'dep', ',', 'GoTarget', ')', ':...
Syncs symlinks under gopath to the library binaries of target's transitive dependencies. :param Target target: Target whose transitive dependencies must be linked. :param str gopath: $GOPATH of target whose "pkg/" directory must be populated with links to library binaries. :param dic...
['Syncs', 'symlinks', 'under', 'gopath', 'to', 'the', 'library', 'binaries', 'of', 'target', 's', 'transitive', 'dependencies', '.']
train
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/contrib/go/src/python/pants/contrib/go/tasks/go_compile.py#L110-L144
9,279
napalm-automation/napalm
napalm/base/helpers.py
canonical_interface_name
def canonical_interface_name(interface, addl_name_map=None): """Function to return an interface's canonical name (fully expanded name). Use of explicit matches used to indicate a clear understanding on any potential match. Regex and other looser matching methods were not implmented to avoid false posit...
python
def canonical_interface_name(interface, addl_name_map=None): """Function to return an interface's canonical name (fully expanded name). Use of explicit matches used to indicate a clear understanding on any potential match. Regex and other looser matching methods were not implmented to avoid false posit...
['def', 'canonical_interface_name', '(', 'interface', ',', 'addl_name_map', '=', 'None', ')', ':', 'name_map', '=', '{', '}', 'name_map', '.', 'update', '(', 'base_interfaces', ')', 'interface_type', ',', 'interface_number', '=', 'split_interface', '(', 'interface', ')', 'if', 'isinstance', '(', 'addl_name_map', ',', '...
Function to return an interface's canonical name (fully expanded name). Use of explicit matches used to indicate a clear understanding on any potential match. Regex and other looser matching methods were not implmented to avoid false positive matches. As an example, it would make sense to do "[P|p][O|o]" w...
['Function', 'to', 'return', 'an', 'interface', 's', 'canonical', 'name', '(', 'fully', 'expanded', 'name', ')', '.']
train
https://github.com/napalm-automation/napalm/blob/c11ae8bb5ce395698704a0051cdf8d144fbb150d/napalm/base/helpers.py#L353-L380
9,280
apache/incubator-mxnet
python/mxnet/contrib/onnx/mx2onnx/_op_translations.py
convert_clip
def convert_clip(node, **kwargs): """Map MXNet's Clip operator attributes to onnx's Clip operator and return the created node. """ name, input_nodes, attrs = get_inputs(node, kwargs) a_min = np.float(attrs.get('a_min', -np.inf)) a_max = np.float(attrs.get('a_max', np.inf)) clip_node = onnx...
python
def convert_clip(node, **kwargs): """Map MXNet's Clip operator attributes to onnx's Clip operator and return the created node. """ name, input_nodes, attrs = get_inputs(node, kwargs) a_min = np.float(attrs.get('a_min', -np.inf)) a_max = np.float(attrs.get('a_max', np.inf)) clip_node = onnx...
['def', 'convert_clip', '(', 'node', ',', '*', '*', 'kwargs', ')', ':', 'name', ',', 'input_nodes', ',', 'attrs', '=', 'get_inputs', '(', 'node', ',', 'kwargs', ')', 'a_min', '=', 'np', '.', 'float', '(', 'attrs', '.', 'get', '(', "'a_min'", ',', '-', 'np', '.', 'inf', ')', ')', 'a_max', '=', 'np', '.', 'float', '(', '...
Map MXNet's Clip operator attributes to onnx's Clip operator and return the created node.
['Map', 'MXNet', 's', 'Clip', 'operator', 'attributes', 'to', 'onnx', 's', 'Clip', 'operator', 'and', 'return', 'the', 'created', 'node', '.']
train
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/onnx/mx2onnx/_op_translations.py#L972-L989
9,281
datastax/python-driver
cassandra/cluster.py
Session.on_down
def on_down(self, host): """ Called by the parent Cluster instance when a node is marked down. Only intended for internal use. """ future = self.remove_pool(host) if future: future.add_done_callback(lambda f: self.update_created_pools())
python
def on_down(self, host): """ Called by the parent Cluster instance when a node is marked down. Only intended for internal use. """ future = self.remove_pool(host) if future: future.add_done_callback(lambda f: self.update_created_pools())
['def', 'on_down', '(', 'self', ',', 'host', ')', ':', 'future', '=', 'self', '.', 'remove_pool', '(', 'host', ')', 'if', 'future', ':', 'future', '.', 'add_done_callback', '(', 'lambda', 'f', ':', 'self', '.', 'update_created_pools', '(', ')', ')']
Called by the parent Cluster instance when a node is marked down. Only intended for internal use.
['Called', 'by', 'the', 'parent', 'Cluster', 'instance', 'when', 'a', 'node', 'is', 'marked', 'down', '.', 'Only', 'intended', 'for', 'internal', 'use', '.']
train
https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cluster.py#L2674-L2681
9,282
yyuu/botornado
boto/mturk/connection.py
MTurkConnection._get_pages
def _get_pages(page_size, total_records): """ Given a page size (records per page) and a total number of records, return the page numbers to be retrieved. """ pages = total_records/page_size+bool(total_records%page_size) return range(1, pages+1)
python
def _get_pages(page_size, total_records): """ Given a page size (records per page) and a total number of records, return the page numbers to be retrieved. """ pages = total_records/page_size+bool(total_records%page_size) return range(1, pages+1)
['def', '_get_pages', '(', 'page_size', ',', 'total_records', ')', ':', 'pages', '=', 'total_records', '/', 'page_size', '+', 'bool', '(', 'total_records', '%', 'page_size', ')', 'return', 'range', '(', '1', ',', 'pages', '+', '1', ')']
Given a page size (records per page) and a total number of records, return the page numbers to be retrieved.
['Given', 'a', 'page', 'size', '(', 'records', 'per', 'page', ')', 'and', 'a', 'total', 'number', 'of', 'records', 'return', 'the', 'page', 'numbers', 'to', 'be', 'retrieved', '.']
train
https://github.com/yyuu/botornado/blob/fffb056f5ff2324d1d5c1304014cfb1d899f602e/boto/mturk/connection.py#L261-L267
9,283
mjj4791/python-buienradar
buienradar/buienradar_xml.py
parse_xml_data
def parse_xml_data(content, raincontent, latitude=52.091579, longitude=5.119734, timeframe=60): """Parse the raw data and return as data dictionary.""" result = {SUCCESS: False, MESSAGE: None, DATA: None} if timeframe < 5 or timeframe > 120: raise ValueError("Timeframe must be >=...
python
def parse_xml_data(content, raincontent, latitude=52.091579, longitude=5.119734, timeframe=60): """Parse the raw data and return as data dictionary.""" result = {SUCCESS: False, MESSAGE: None, DATA: None} if timeframe < 5 or timeframe > 120: raise ValueError("Timeframe must be >=...
['def', 'parse_xml_data', '(', 'content', ',', 'raincontent', ',', 'latitude', '=', '52.091579', ',', 'longitude', '=', '5.119734', ',', 'timeframe', '=', '60', ')', ':', 'result', '=', '{', 'SUCCESS', ':', 'False', ',', 'MESSAGE', ':', 'None', ',', 'DATA', ':', 'None', '}', 'if', 'timeframe', '<', '5', 'or', 'timefram...
Parse the raw data and return as data dictionary.
['Parse', 'the', 'raw', 'data', 'and', 'return', 'as', 'data', 'dictionary', '.']
train
https://github.com/mjj4791/python-buienradar/blob/a70436f54e007ce921d5210cb296cf3e4adf9d09/buienradar/buienradar_xml.py#L186-L202
9,284
iotile/coretools
iotilecore/iotile/core/utilities/intelhex/__init__.py
Record.data
def data(offset, bytes): """Return Data record. This constructs the full record, including the length information, the record type (0x00), the checksum, and the offset. @param offset load offset of first byte. @param bytes list of byte values to pack into record. @...
python
def data(offset, bytes): """Return Data record. This constructs the full record, including the length information, the record type (0x00), the checksum, and the offset. @param offset load offset of first byte. @param bytes list of byte values to pack into record. @...
['def', 'data', '(', 'offset', ',', 'bytes', ')', ':', 'assert', '0', '<=', 'offset', '<', '65536', 'assert', '0', '<', 'len', '(', 'bytes', ')', '<', '256', 'b', '=', '[', 'len', '(', 'bytes', ')', ',', '(', 'offset', '>>', '8', ')', '&', '0x0FF', ',', 'offset', '&', '0x0FF', ',', '0x00', ']', '+', 'bytes', 'return', ...
Return Data record. This constructs the full record, including the length information, the record type (0x00), the checksum, and the offset. @param offset load offset of first byte. @param bytes list of byte values to pack into record. @return String representation...
['Return', 'Data', 'record', '.', 'This', 'constructs', 'the', 'full', 'record', 'including', 'the', 'length', 'information', 'the', 'record', 'type', '(', '0x00', ')', 'the', 'checksum', 'and', 'the', 'offset', '.']
train
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/intelhex/__init__.py#L1145-L1158
9,285
alixnovosi/botskeleton
botskeleton/botskeleton.py
BotSkeleton.store_extra_info
def store_extra_info(self, key: str, value: Any) -> None: """ Store some extra value in the messaging storage. :param key: key of dictionary entry to add. :param value: value of dictionary entry to add. :returns: None """ self.extra_keys[key] = value
python
def store_extra_info(self, key: str, value: Any) -> None: """ Store some extra value in the messaging storage. :param key: key of dictionary entry to add. :param value: value of dictionary entry to add. :returns: None """ self.extra_keys[key] = value
['def', 'store_extra_info', '(', 'self', ',', 'key', ':', 'str', ',', 'value', ':', 'Any', ')', '->', 'None', ':', 'self', '.', 'extra_keys', '[', 'key', ']', '=', 'value']
Store some extra value in the messaging storage. :param key: key of dictionary entry to add. :param value: value of dictionary entry to add. :returns: None
['Store', 'some', 'extra', 'value', 'in', 'the', 'messaging', 'storage', '.']
train
https://github.com/alixnovosi/botskeleton/blob/55bfc1b8a3623c10437e4ab2cd0b0ec8d35907a9/botskeleton/botskeleton.py#L353-L361
9,286
hydraplatform/hydra-base
hydra_base/lib/template.py
validate_attrs
def validate_attrs(resource_attr_ids, scenario_id, template_id=None): """ Check that multiple resource attribute satisfy the requirements of the types of resources to which the they are attached. """ multi_rs = db.DBSession.query(ResourceScenario).\ filter(Resourc...
python
def validate_attrs(resource_attr_ids, scenario_id, template_id=None): """ Check that multiple resource attribute satisfy the requirements of the types of resources to which the they are attached. """ multi_rs = db.DBSession.query(ResourceScenario).\ filter(Resourc...
['def', 'validate_attrs', '(', 'resource_attr_ids', ',', 'scenario_id', ',', 'template_id', '=', 'None', ')', ':', 'multi_rs', '=', 'db', '.', 'DBSession', '.', 'query', '(', 'ResourceScenario', ')', '.', 'filter', '(', 'ResourceScenario', '.', 'resource_attr_id', '.', 'in_', '(', 'resource_attr_ids', ')', ',', 'Resour...
Check that multiple resource attribute satisfy the requirements of the types of resources to which the they are attached.
['Check', 'that', 'multiple', 'resource', 'attribute', 'satisfy', 'the', 'requirements', 'of', 'the', 'types', 'of', 'resources', 'to', 'which', 'the', 'they', 'are', 'attached', '.']
train
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/template.py#L1755-L1786
9,287
qubell/contrib-python-qubell-client
qubell/api/private/organization.py
Organization.instance
def instance(self, id=None, application=None, name=None, revision=None, environment=None, parameters=None, submodules=None, destroyInterval=None): """ Smart method. It does everything, to return Instance with given parameters within the application. If instance found running and given parameters are act...
python
def instance(self, id=None, application=None, name=None, revision=None, environment=None, parameters=None, submodules=None, destroyInterval=None): """ Smart method. It does everything, to return Instance with given parameters within the application. If instance found running and given parameters are act...
['def', 'instance', '(', 'self', ',', 'id', '=', 'None', ',', 'application', '=', 'None', ',', 'name', '=', 'None', ',', 'revision', '=', 'None', ',', 'environment', '=', 'None', ',', 'parameters', '=', 'None', ',', 'submodules', '=', 'None', ',', 'destroyInterval', '=', 'None', ')', ':', 'instance', '=', 'self', '.', ...
Smart method. It does everything, to return Instance with given parameters within the application. If instance found running and given parameters are actual: return it. If instance found, but parameters differs - reconfigure instance with new parameters. If instance not found: launch instance wi...
['Smart', 'method', '.', 'It', 'does', 'everything', 'to', 'return', 'Instance', 'with', 'given', 'parameters', 'within', 'the', 'application', '.', 'If', 'instance', 'found', 'running', 'and', 'given', 'parameters', 'are', 'actual', ':', 'return', 'it', '.', 'If', 'instance', 'found', 'but', 'parameters', 'differs', '...
train
https://github.com/qubell/contrib-python-qubell-client/blob/4586ea11d5103c2ff9607d3ed922b5a0991b8845/qubell/api/private/organization.py#L309-L329
9,288
PythonCharmers/python-future
src/future/backports/urllib/request.py
URLopener._open_generic_http
def _open_generic_http(self, connection_factory, url, data): """Make an HTTP connection using connection_class. This is an internal method that should be called from open_http() or open_https(). Arguments: - connection_factory should take a host name and return an HTT...
python
def _open_generic_http(self, connection_factory, url, data): """Make an HTTP connection using connection_class. This is an internal method that should be called from open_http() or open_https(). Arguments: - connection_factory should take a host name and return an HTT...
['def', '_open_generic_http', '(', 'self', ',', 'connection_factory', ',', 'url', ',', 'data', ')', ':', 'user_passwd', '=', 'None', 'proxy_passwd', '=', 'None', 'if', 'isinstance', '(', 'url', ',', 'str', ')', ':', 'host', ',', 'selector', '=', 'splithost', '(', 'url', ')', 'if', 'host', ':', 'user_passwd', ',', 'host...
Make an HTTP connection using connection_class. This is an internal method that should be called from open_http() or open_https(). Arguments: - connection_factory should take a host name and return an HTTPConnection instance. - url is the url to retrieval or a host, r...
['Make', 'an', 'HTTP', 'connection', 'using', 'connection_class', '.']
train
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/urllib/request.py#L1782-L1872
9,289
ewels/MultiQC
multiqc/modules/hicpro/hicpro.py
MultiqcModule.hicpro_capture_chart
def hicpro_capture_chart (self): """ Generate Capture Hi-C plot""" keys = OrderedDict() keys['valid_pairs_on_target_cap_cap'] = { 'color': '#0039e6', 'name': 'Capture-Capture interactions' } keys['valid_pairs_on_target_cap_rep'] = { 'color': '#809fff', 'name': 'Capture-Reporter interac...
python
def hicpro_capture_chart (self): """ Generate Capture Hi-C plot""" keys = OrderedDict() keys['valid_pairs_on_target_cap_cap'] = { 'color': '#0039e6', 'name': 'Capture-Capture interactions' } keys['valid_pairs_on_target_cap_rep'] = { 'color': '#809fff', 'name': 'Capture-Reporter interac...
['def', 'hicpro_capture_chart', '(', 'self', ')', ':', 'keys', '=', 'OrderedDict', '(', ')', 'keys', '[', "'valid_pairs_on_target_cap_cap'", ']', '=', '{', "'color'", ':', "'#0039e6'", ',', "'name'", ':', "'Capture-Capture interactions'", '}', 'keys', '[', "'valid_pairs_on_target_cap_rep'", ']', '=', '{', "'color'", ':...
Generate Capture Hi-C plot
['Generate', 'Capture', 'Hi', '-', 'C', 'plot']
train
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/hicpro/hicpro.py#L399-L423
9,290
snare/voltron
voltron/core.py
Server.dispatch_request
def dispatch_request(self, req): """ Dispatch a request object. """ log.debug("Dispatching request: {}".format(str(req))) # make sure it's valid res = None try: req.validate() except MissingFieldError as e: res = APIMissingFieldErr...
python
def dispatch_request(self, req): """ Dispatch a request object. """ log.debug("Dispatching request: {}".format(str(req))) # make sure it's valid res = None try: req.validate() except MissingFieldError as e: res = APIMissingFieldErr...
['def', 'dispatch_request', '(', 'self', ',', 'req', ')', ':', 'log', '.', 'debug', '(', '"Dispatching request: {}"', '.', 'format', '(', 'str', '(', 'req', ')', ')', ')', "# make sure it's valid", 'res', '=', 'None', 'try', ':', 'req', '.', 'validate', '(', ')', 'except', 'MissingFieldError', 'as', 'e', ':', 'res', '=...
Dispatch a request object.
['Dispatch', 'a', 'request', 'object', '.']
train
https://github.com/snare/voltron/blob/4ee3cbe6f7c1e38303f5dc6114c48b60217253c3/voltron/core.py#L279-L303
9,291
OnroerendErfgoed/crabpy_pyramid
crabpy_pyramid/renderers/crab.py
list_gebouwen_adapter
def list_gebouwen_adapter(obj, request): """ Adapter for rendering a list of :class:`crabpy.gateway.crab.Gebouw` to json. """ return { 'id': obj.id, 'aard': { 'id': obj.aard.id, 'naam': obj.aard.naam, 'definitie': obj.aard.definitie }, ...
python
def list_gebouwen_adapter(obj, request): """ Adapter for rendering a list of :class:`crabpy.gateway.crab.Gebouw` to json. """ return { 'id': obj.id, 'aard': { 'id': obj.aard.id, 'naam': obj.aard.naam, 'definitie': obj.aard.definitie }, ...
['def', 'list_gebouwen_adapter', '(', 'obj', ',', 'request', ')', ':', 'return', '{', "'id'", ':', 'obj', '.', 'id', ',', "'aard'", ':', '{', "'id'", ':', 'obj', '.', 'aard', '.', 'id', ',', "'naam'", ':', 'obj', '.', 'aard', '.', 'naam', ',', "'definitie'", ':', 'obj', '.', 'aard', '.', 'definitie', '}', ',', "'status...
Adapter for rendering a list of :class:`crabpy.gateway.crab.Gebouw` to json.
['Adapter', 'for', 'rendering', 'a', 'list', 'of', ':', 'class', ':', 'crabpy', '.', 'gateway', '.', 'crab', '.', 'Gebouw', 'to', 'json', '.']
train
https://github.com/OnroerendErfgoed/crabpy_pyramid/blob/b727ea55838d71575db96e987b536a0bac9f6a7a/crabpy_pyramid/renderers/crab.py#L111-L128
9,292
python-cmd2/cmd2
cmd2/cmd2.py
Cmd.pfeedback
def pfeedback(self, msg: str) -> None: """For printing nonessential feedback. Can be silenced with `quiet`. Inclusion in redirected output is controlled by `feedback_to_output`.""" if not self.quiet: if self.feedback_to_output: self.poutput(msg) else: ...
python
def pfeedback(self, msg: str) -> None: """For printing nonessential feedback. Can be silenced with `quiet`. Inclusion in redirected output is controlled by `feedback_to_output`.""" if not self.quiet: if self.feedback_to_output: self.poutput(msg) else: ...
['def', 'pfeedback', '(', 'self', ',', 'msg', ':', 'str', ')', '->', 'None', ':', 'if', 'not', 'self', '.', 'quiet', ':', 'if', 'self', '.', 'feedback_to_output', ':', 'self', '.', 'poutput', '(', 'msg', ')', 'else', ':', 'self', '.', 'decolorized_write', '(', 'sys', '.', 'stderr', ',', '"{}\\n"', '.', 'format', '(', '...
For printing nonessential feedback. Can be silenced with `quiet`. Inclusion in redirected output is controlled by `feedback_to_output`.
['For', 'printing', 'nonessential', 'feedback', '.', 'Can', 'be', 'silenced', 'with', 'quiet', '.', 'Inclusion', 'in', 'redirected', 'output', 'is', 'controlled', 'by', 'feedback_to_output', '.']
train
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L646-L653
9,293
annayqho/TheCannon
code/aaomega/aaomega_munge_data.py
load_data
def load_data(): data_dir = "/Users/annaho/Data/AAOmega" out_dir = "%s/%s" %(data_dir, "Run_13_July") """ Use all the above functions to set data up for The Cannon """ ff, wl, tr_flux, tr_ivar = load_ref_spectra() """ pick one that doesn't have extra dead pixels """ skylines = tr_ivar[4,:] # s...
python
def load_data(): data_dir = "/Users/annaho/Data/AAOmega" out_dir = "%s/%s" %(data_dir, "Run_13_July") """ Use all the above functions to set data up for The Cannon """ ff, wl, tr_flux, tr_ivar = load_ref_spectra() """ pick one that doesn't have extra dead pixels """ skylines = tr_ivar[4,:] # s...
['def', 'load_data', '(', ')', ':', 'data_dir', '=', '"/Users/annaho/Data/AAOmega"', 'out_dir', '=', '"%s/%s"', '%', '(', 'data_dir', ',', '"Run_13_July"', ')', 'ff', ',', 'wl', ',', 'tr_flux', ',', 'tr_ivar', '=', 'load_ref_spectra', '(', ')', '""" pick one that doesn\'t have extra dead pixels """', 'skylines', '=', '...
Use all the above functions to set data up for The Cannon
['Use', 'all', 'the', 'above', 'functions', 'to', 'set', 'data', 'up', 'for', 'The', 'Cannon']
train
https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/code/aaomega/aaomega_munge_data.py#L109-L157
9,294
briney/abutils
abutils/utils/s3.py
configure
def configure(access_key=None, secret_key=None, logger=None): ''' Configures s3cmd prior to first use. If no arguments are provided, you will be prompted to enter the access key and secret key interactively. Args: access_key (str): AWS access key secret_key (str): AWS secret key ...
python
def configure(access_key=None, secret_key=None, logger=None): ''' Configures s3cmd prior to first use. If no arguments are provided, you will be prompted to enter the access key and secret key interactively. Args: access_key (str): AWS access key secret_key (str): AWS secret key ...
['def', 'configure', '(', 'access_key', '=', 'None', ',', 'secret_key', '=', 'None', ',', 'logger', '=', 'None', ')', ':', 'if', 'not', 'logger', ':', 'logger', '=', 'log', '.', 'get_logger', '(', "'s3'", ')', 'if', 'not', 'all', '(', '[', 'access_key', ',', 'secret_key', ']', ')', ':', 'logger', '.', 'info', '(', "''"...
Configures s3cmd prior to first use. If no arguments are provided, you will be prompted to enter the access key and secret key interactively. Args: access_key (str): AWS access key secret_key (str): AWS secret key
['Configures', 's3cmd', 'prior', 'to', 'first', 'use', '.']
train
https://github.com/briney/abutils/blob/944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b/abutils/utils/s3.py#L201-L223
9,295
pantsbuild/pants
src/python/pants/backend/native/tasks/native_compile.py
NativeCompile.get_sources_headers_for_target
def get_sources_headers_for_target(self, target): """Return a list of file arguments to provide to the compiler. NB: result list will contain both header and source files! :raises: :class:`NativeCompile.NativeCompileError` if there is an error processing the sources. """ # Get source paths relativ...
python
def get_sources_headers_for_target(self, target): """Return a list of file arguments to provide to the compiler. NB: result list will contain both header and source files! :raises: :class:`NativeCompile.NativeCompileError` if there is an error processing the sources. """ # Get source paths relativ...
['def', 'get_sources_headers_for_target', '(', 'self', ',', 'target', ')', ':', '# Get source paths relative to the target base so the exception message with the target and', '# paths makes sense.', 'target_relative_sources', '=', 'target', '.', 'sources_relative_to_target_base', '(', ')', 'rel_root', '=', 'target_rela...
Return a list of file arguments to provide to the compiler. NB: result list will contain both header and source files! :raises: :class:`NativeCompile.NativeCompileError` if there is an error processing the sources.
['Return', 'a', 'list', 'of', 'file', 'arguments', 'to', 'provide', 'to', 'the', 'compiler', '.']
train
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/native/tasks/native_compile.py#L96-L126
9,296
phaethon/kamene
kamene/layers/inet.py
defrag
def defrag(plist): """defrag(plist) -> ([not fragmented], [defragmented], [ [bad fragments], [bad fragments], ... ])""" frags = defaultdict(PacketList) nofrag = PacketList() for p in plist: ip = p[IP] if IP not in p: nofrag.append(p) continue ...
python
def defrag(plist): """defrag(plist) -> ([not fragmented], [defragmented], [ [bad fragments], [bad fragments], ... ])""" frags = defaultdict(PacketList) nofrag = PacketList() for p in plist: ip = p[IP] if IP not in p: nofrag.append(p) continue ...
['def', 'defrag', '(', 'plist', ')', ':', 'frags', '=', 'defaultdict', '(', 'PacketList', ')', 'nofrag', '=', 'PacketList', '(', ')', 'for', 'p', 'in', 'plist', ':', 'ip', '=', 'p', '[', 'IP', ']', 'if', 'IP', 'not', 'in', 'p', ':', 'nofrag', '.', 'append', '(', 'p', ')', 'continue', 'if', 'ip', '.', 'frag', '==', '0',...
defrag(plist) -> ([not fragmented], [defragmented], [ [bad fragments], [bad fragments], ... ])
['defrag', '(', 'plist', ')', '-', '>', '(', '[', 'not', 'fragmented', ']', '[', 'defragmented', ']', '[', '[', 'bad', 'fragments', ']', '[', 'bad', 'fragments', ']', '...', ']', ')']
train
https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/layers/inet.py#L901-L956
9,297
globality-corp/microcosm
microcosm/hooks.py
_invoke_hook
def _invoke_hook(hook_name, target): """ Generic hook invocation. """ try: for value in getattr(target, hook_name): func, args, kwargs = value func(target, *args, **kwargs) except AttributeError: # no hook defined pass except (TypeError, ValueErro...
python
def _invoke_hook(hook_name, target): """ Generic hook invocation. """ try: for value in getattr(target, hook_name): func, args, kwargs = value func(target, *args, **kwargs) except AttributeError: # no hook defined pass except (TypeError, ValueErro...
['def', '_invoke_hook', '(', 'hook_name', ',', 'target', ')', ':', 'try', ':', 'for', 'value', 'in', 'getattr', '(', 'target', ',', 'hook_name', ')', ':', 'func', ',', 'args', ',', 'kwargs', '=', 'value', 'func', '(', 'target', ',', '*', 'args', ',', '*', '*', 'kwargs', ')', 'except', 'AttributeError', ':', '# no hook ...
Generic hook invocation.
['Generic', 'hook', 'invocation', '.']
train
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/hooks.py#L45-L59
9,298
ArduPilot/MAVProxy
MAVProxy/modules/mavproxy_genobstacles.py
GenobstaclesModule.mavlink_packet
def mavlink_packet(self, m): '''trigger sends from ATTITUDE packets''' if not self.have_home and m.get_type() == 'GPS_RAW_INT' and m.fix_type >= 3: gen_settings.home_lat = m.lat * 1.0e-7 gen_settings.home_lon = m.lon * 1.0e-7 self.have_home = True if self....
python
def mavlink_packet(self, m): '''trigger sends from ATTITUDE packets''' if not self.have_home and m.get_type() == 'GPS_RAW_INT' and m.fix_type >= 3: gen_settings.home_lat = m.lat * 1.0e-7 gen_settings.home_lon = m.lon * 1.0e-7 self.have_home = True if self....
['def', 'mavlink_packet', '(', 'self', ',', 'm', ')', ':', 'if', 'not', 'self', '.', 'have_home', 'and', 'm', '.', 'get_type', '(', ')', '==', "'GPS_RAW_INT'", 'and', 'm', '.', 'fix_type', '>=', '3', ':', 'gen_settings', '.', 'home_lat', '=', 'm', '.', 'lat', '*', '1.0e-7', 'gen_settings', '.', 'home_lon', '=', 'm', '....
trigger sends from ATTITUDE packets
['trigger', 'sends', 'from', 'ATTITUDE', 'packets']
train
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_genobstacles.py#L409-L436
9,299
twilio/twilio-python
twilio/rest/taskrouter/v1/workspace/task/__init__.py
TaskList.create
def create(self, timeout=values.unset, priority=values.unset, task_channel=values.unset, workflow_sid=values.unset, attributes=values.unset): """ Create a new TaskInstance :param unicode timeout: The amount of time in seconds the task is allowed to live up to a max...
python
def create(self, timeout=values.unset, priority=values.unset, task_channel=values.unset, workflow_sid=values.unset, attributes=values.unset): """ Create a new TaskInstance :param unicode timeout: The amount of time in seconds the task is allowed to live up to a max...
['def', 'create', '(', 'self', ',', 'timeout', '=', 'values', '.', 'unset', ',', 'priority', '=', 'values', '.', 'unset', ',', 'task_channel', '=', 'values', '.', 'unset', ',', 'workflow_sid', '=', 'values', '.', 'unset', ',', 'attributes', '=', 'values', '.', 'unset', ')', ':', 'data', '=', 'values', '.', 'of', '(', '...
Create a new TaskInstance :param unicode timeout: The amount of time in seconds the task is allowed to live up to a maximum of 2 weeks. :param unicode priority: Override priority for the Task. :param unicode task_channel: When MultiTasking is enabled specify the type of the task by passing eith...
['Create', 'a', 'new', 'TaskInstance']
train
https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/taskrouter/v1/workspace/task/__init__.py#L194-L223