repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
rytilahti/python-eq3bt | eq3bt/eq3btsmart.py | Thermostat.mode_readable | def mode_readable(self):
"""Return a readable representation of the mode.."""
ret = ""
mode = self._raw_mode
if mode.MANUAL:
ret = "manual"
if self.target_temperature < self.min_temp:
ret += " off"
elif self.target_temperature >= self.max_temp:
ret += " on"
else:
ret += " (%sC)" % self.target_temperature
else:
ret = "auto"
if mode.AWAY:
ret += " holiday"
if mode.BOOST:
ret += " boost"
if mode.DST:
ret += " dst"
if mode.WINDOW:
ret += " window"
if mode.LOCKED:
ret += " locked"
if mode.LOW_BATTERY:
ret += " low battery"
return ret | python | def mode_readable(self):
"""Return a readable representation of the mode.."""
ret = ""
mode = self._raw_mode
if mode.MANUAL:
ret = "manual"
if self.target_temperature < self.min_temp:
ret += " off"
elif self.target_temperature >= self.max_temp:
ret += " on"
else:
ret += " (%sC)" % self.target_temperature
else:
ret = "auto"
if mode.AWAY:
ret += " holiday"
if mode.BOOST:
ret += " boost"
if mode.DST:
ret += " dst"
if mode.WINDOW:
ret += " window"
if mode.LOCKED:
ret += " locked"
if mode.LOW_BATTERY:
ret += " low battery"
return ret | [
"def",
"mode_readable",
"(",
"self",
")",
":",
"ret",
"=",
"\"\"",
"mode",
"=",
"self",
".",
"_raw_mode",
"if",
"mode",
".",
"MANUAL",
":",
"ret",
"=",
"\"manual\"",
"if",
"self",
".",
"target_temperature",
"<",
"self",
".",
"min_temp",
":",
"ret",
"+=... | Return a readable representation of the mode.. | [
"Return",
"a",
"readable",
"representation",
"of",
"the",
"mode",
".."
] | 595459d9885920cf13b7059a1edd2cf38cede1f0 | https://github.com/rytilahti/python-eq3bt/blob/595459d9885920cf13b7059a1edd2cf38cede1f0/eq3bt/eq3btsmart.py#L260-L289 | train | 34,400 |
rytilahti/python-eq3bt | eq3bt/eq3btsmart.py | Thermostat.boost | def boost(self, boost):
"""Sets boost mode."""
_LOGGER.debug("Setting boost mode: %s", boost)
value = struct.pack('BB', PROP_BOOST, bool(boost))
self._conn.make_request(PROP_WRITE_HANDLE, value) | python | def boost(self, boost):
"""Sets boost mode."""
_LOGGER.debug("Setting boost mode: %s", boost)
value = struct.pack('BB', PROP_BOOST, bool(boost))
self._conn.make_request(PROP_WRITE_HANDLE, value) | [
"def",
"boost",
"(",
"self",
",",
"boost",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Setting boost mode: %s\"",
",",
"boost",
")",
"value",
"=",
"struct",
".",
"pack",
"(",
"'BB'",
",",
"PROP_BOOST",
",",
"bool",
"(",
"boost",
")",
")",
"self",
".",
... | Sets boost mode. | [
"Sets",
"boost",
"mode",
"."
] | 595459d9885920cf13b7059a1edd2cf38cede1f0 | https://github.com/rytilahti/python-eq3bt/blob/595459d9885920cf13b7059a1edd2cf38cede1f0/eq3bt/eq3btsmart.py#L297-L301 | train | 34,401 |
rytilahti/python-eq3bt | eq3bt/eq3btsmart.py | Thermostat.window_open_config | def window_open_config(self, temperature, duration):
"""Configures the window open behavior. The duration is specified in
5 minute increments."""
_LOGGER.debug("Window open config, temperature: %s duration: %s", temperature, duration)
self._verify_temperature(temperature)
if duration.seconds < 0 and duration.seconds > 3600:
raise ValueError
value = struct.pack('BBB', PROP_WINDOW_OPEN_CONFIG,
int(temperature * 2), int(duration.seconds / 300))
self._conn.make_request(PROP_WRITE_HANDLE, value) | python | def window_open_config(self, temperature, duration):
"""Configures the window open behavior. The duration is specified in
5 minute increments."""
_LOGGER.debug("Window open config, temperature: %s duration: %s", temperature, duration)
self._verify_temperature(temperature)
if duration.seconds < 0 and duration.seconds > 3600:
raise ValueError
value = struct.pack('BBB', PROP_WINDOW_OPEN_CONFIG,
int(temperature * 2), int(duration.seconds / 300))
self._conn.make_request(PROP_WRITE_HANDLE, value) | [
"def",
"window_open_config",
"(",
"self",
",",
"temperature",
",",
"duration",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Window open config, temperature: %s duration: %s\"",
",",
"temperature",
",",
"duration",
")",
"self",
".",
"_verify_temperature",
"(",
"temperatu... | Configures the window open behavior. The duration is specified in
5 minute increments. | [
"Configures",
"the",
"window",
"open",
"behavior",
".",
"The",
"duration",
"is",
"specified",
"in",
"5",
"minute",
"increments",
"."
] | 595459d9885920cf13b7059a1edd2cf38cede1f0 | https://github.com/rytilahti/python-eq3bt/blob/595459d9885920cf13b7059a1edd2cf38cede1f0/eq3bt/eq3btsmart.py#L314-L324 | train | 34,402 |
rytilahti/python-eq3bt | eq3bt/eq3btsmart.py | Thermostat.locked | def locked(self, lock):
"""Locks or unlocks the thermostat."""
_LOGGER.debug("Setting the lock: %s", lock)
value = struct.pack('BB', PROP_LOCK, bool(lock))
self._conn.make_request(PROP_WRITE_HANDLE, value) | python | def locked(self, lock):
"""Locks or unlocks the thermostat."""
_LOGGER.debug("Setting the lock: %s", lock)
value = struct.pack('BB', PROP_LOCK, bool(lock))
self._conn.make_request(PROP_WRITE_HANDLE, value) | [
"def",
"locked",
"(",
"self",
",",
"lock",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Setting the lock: %s\"",
",",
"lock",
")",
"value",
"=",
"struct",
".",
"pack",
"(",
"'BB'",
",",
"PROP_LOCK",
",",
"bool",
"(",
"lock",
")",
")",
"self",
".",
"_co... | Locks or unlocks the thermostat. | [
"Locks",
"or",
"unlocks",
"the",
"thermostat",
"."
] | 595459d9885920cf13b7059a1edd2cf38cede1f0 | https://github.com/rytilahti/python-eq3bt/blob/595459d9885920cf13b7059a1edd2cf38cede1f0/eq3bt/eq3btsmart.py#L332-L336 | train | 34,403 |
rytilahti/python-eq3bt | eq3bt/eq3btsmart.py | Thermostat.temperature_offset | def temperature_offset(self, offset):
"""Sets the thermostat's temperature offset."""
_LOGGER.debug("Setting offset: %s", offset)
# [-3,5 .. 0 .. 3,5 ]
# [00 .. 07 .. 0e ]
if offset < -3.5 or offset > 3.5:
raise TemperatureException("Invalid value: %s" % offset)
current = -3.5
values = {}
for i in range(15):
values[current] = i
current += 0.5
value = struct.pack('BB', PROP_OFFSET, values[offset])
self._conn.make_request(PROP_WRITE_HANDLE, value) | python | def temperature_offset(self, offset):
"""Sets the thermostat's temperature offset."""
_LOGGER.debug("Setting offset: %s", offset)
# [-3,5 .. 0 .. 3,5 ]
# [00 .. 07 .. 0e ]
if offset < -3.5 or offset > 3.5:
raise TemperatureException("Invalid value: %s" % offset)
current = -3.5
values = {}
for i in range(15):
values[current] = i
current += 0.5
value = struct.pack('BB', PROP_OFFSET, values[offset])
self._conn.make_request(PROP_WRITE_HANDLE, value) | [
"def",
"temperature_offset",
"(",
"self",
",",
"offset",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Setting offset: %s\"",
",",
"offset",
")",
"# [-3,5 .. 0 .. 3,5 ]",
"# [00 .. 07 .. 0e ]",
"if",
"offset",
"<",
"-",
"3.5",
"or",
"offset",
">",
"3.5",
":",
... | Sets the thermostat's temperature offset. | [
"Sets",
"the",
"thermostat",
"s",
"temperature",
"offset",
"."
] | 595459d9885920cf13b7059a1edd2cf38cede1f0 | https://github.com/rytilahti/python-eq3bt/blob/595459d9885920cf13b7059a1edd2cf38cede1f0/eq3bt/eq3btsmart.py#L353-L368 | train | 34,404 |
exxeleron/qPython | qpython/qconnection.py | QConnection._init_socket | def _init_socket(self):
'''Initialises the socket used for communicating with a q service,'''
try:
self._connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._connection.connect((self.host, self.port))
self._connection.settimeout(self.timeout)
self._connection_file = self._connection.makefile('b')
except:
self._connection = None
self._connection_file = None
raise | python | def _init_socket(self):
'''Initialises the socket used for communicating with a q service,'''
try:
self._connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._connection.connect((self.host, self.port))
self._connection.settimeout(self.timeout)
self._connection_file = self._connection.makefile('b')
except:
self._connection = None
self._connection_file = None
raise | [
"def",
"_init_socket",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"_connection",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_STREAM",
")",
"self",
".",
"_connection",
".",
"connect",
"(",
"(",
"self",
"."... | Initialises the socket used for communicating with a q service, | [
"Initialises",
"the",
"socket",
"used",
"for",
"communicating",
"with",
"a",
"q",
"service"
] | 7e64a28b1e8814a8d6b9217ce79bb8de546e62f3 | https://github.com/exxeleron/qPython/blob/7e64a28b1e8814a8d6b9217ce79bb8de546e62f3/qpython/qconnection.py#L150-L160 | train | 34,405 |
exxeleron/qPython | qpython/qconnection.py | QConnection.close | def close(self):
'''Closes connection with the q service.'''
if self._connection:
self._connection_file.close()
self._connection_file = None
self._connection.close()
self._connection = None | python | def close(self):
'''Closes connection with the q service.'''
if self._connection:
self._connection_file.close()
self._connection_file = None
self._connection.close()
self._connection = None | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"_connection",
":",
"self",
".",
"_connection_file",
".",
"close",
"(",
")",
"self",
".",
"_connection_file",
"=",
"None",
"self",
".",
"_connection",
".",
"close",
"(",
")",
"self",
".",
"_conn... | Closes connection with the q service. | [
"Closes",
"connection",
"with",
"the",
"q",
"service",
"."
] | 7e64a28b1e8814a8d6b9217ce79bb8de546e62f3 | https://github.com/exxeleron/qPython/blob/7e64a28b1e8814a8d6b9217ce79bb8de546e62f3/qpython/qconnection.py#L163-L169 | train | 34,406 |
exxeleron/qPython | qpython/qconnection.py | QConnection._initialize | def _initialize(self):
'''Performs a IPC protocol handshake.'''
credentials = (self.username if self.username else '') + ':' + (self.password if self.password else '')
credentials = credentials.encode(self._encoding)
self._connection.send(credentials + b'\3\0')
response = self._connection.recv(1)
if len(response) != 1:
self.close()
self._init_socket()
self._connection.send(credentials + b'\0')
response = self._connection.recv(1)
if len(response) != 1:
self.close()
raise QAuthenticationException('Connection denied.')
self._protocol_version = min(struct.unpack('B', response)[0], 3) | python | def _initialize(self):
'''Performs a IPC protocol handshake.'''
credentials = (self.username if self.username else '') + ':' + (self.password if self.password else '')
credentials = credentials.encode(self._encoding)
self._connection.send(credentials + b'\3\0')
response = self._connection.recv(1)
if len(response) != 1:
self.close()
self._init_socket()
self._connection.send(credentials + b'\0')
response = self._connection.recv(1)
if len(response) != 1:
self.close()
raise QAuthenticationException('Connection denied.')
self._protocol_version = min(struct.unpack('B', response)[0], 3) | [
"def",
"_initialize",
"(",
"self",
")",
":",
"credentials",
"=",
"(",
"self",
".",
"username",
"if",
"self",
".",
"username",
"else",
"''",
")",
"+",
"':'",
"+",
"(",
"self",
".",
"password",
"if",
"self",
".",
"password",
"else",
"''",
")",
"credent... | Performs a IPC protocol handshake. | [
"Performs",
"a",
"IPC",
"protocol",
"handshake",
"."
] | 7e64a28b1e8814a8d6b9217ce79bb8de546e62f3 | https://github.com/exxeleron/qPython/blob/7e64a28b1e8814a8d6b9217ce79bb8de546e62f3/qpython/qconnection.py#L185-L202 | train | 34,407 |
exxeleron/qPython | qpython/qcollection.py | qlist | def qlist(array, adjust_dtype = True, **meta):
'''Converts an input array to q vector and enriches object instance with
meta data.
Returns a :class:`.QList` instance for non-datetime vectors. For datetime
vectors :class:`.QTemporalList` is returned instead.
If parameter `adjust_dtype` is `True` and q type retrieved via
:func:`.get_list_qtype` doesn't match one provided as a `qtype` parameter
guessed q type, underlying numpy.array is converted to correct data type.
`qPython` internally represents ``(0x01;0x02;0xff)`` q list as:
``<class 'qpython.qcollection.QList'> dtype: int8 qtype: -4: [ 1 2 -1]``.
This object can be created by calling the :func:`.qlist` with following
arguments:
- `byte numpy.array`:
>>> v = qlist(numpy.array([0x01, 0x02, 0xff], dtype=numpy.byte))
>>> print('%s dtype: %s qtype: %d: %s' % (type(v), v.dtype, v.meta.qtype, v))
<class 'qpython.qcollection.QList'> dtype: int8 qtype: -4: [ 1 2 -1]
- `int32 numpy.array` with explicit conversion to `QBYTE_LIST`:
>>> v = qlist(numpy.array([1, 2, -1]), qtype = QBYTE_LIST)
>>> print('%s dtype: %s qtype: %d: %s' % (type(v), v.dtype, v.meta.qtype, v))
<class 'qpython.qcollection.QList'> dtype: int8 qtype: -4: [ 1 2 -1]
- plain Python `integer` list with explicit conversion to `QBYTE_LIST`:
>>> v = qlist([1, 2, -1], qtype = QBYTE_LIST)
>>> print('%s dtype: %s qtype: %d: %s' % (type(v), v.dtype, v.meta.qtype, v))
<class 'qpython.qcollection.QList'> dtype: int8 qtype: -4: [ 1 2 -1]
- numpy datetime64 array with implicit conversion to `QDATE_LIST`:
>>> v = qlist(numpy.array([numpy.datetime64('2001-01-01'), numpy.datetime64('2000-05-01'), numpy.datetime64('NaT')], dtype='datetime64[D]'))
>>> print('%s dtype: %s qtype: %d: %s' % (type(v), v.dtype, v.meta.qtype, v))
<class 'qpython.qcollection.QList'> dtype: datetime64[D] qtype: -14: ['2001-01-01' '2000-05-01' 'NaT']
- numpy datetime64 array with explicit conversion to `QDATE_LIST`:
>>> v = qlist(numpy.array([numpy.datetime64('2001-01-01'), numpy.datetime64('2000-05-01'), numpy.datetime64('NaT')], dtype='datetime64[D]'), qtype = QDATE_LIST)
>>> print('%s dtype: %s qtype: %d: %s' % (type(v), v.dtype, v.meta.qtype, v))
<class 'qpython.qcollection.QList'> dtype: datetime64[D] qtype: -14: ['2001-01-01' '2000-05-01' 'NaT']
:Parameters:
- `array` (`tuple`, `list`, `numpy.array`) - input array to be converted
- `adjust_dtype` (`boolean`) - determine whether data type of vector should
be adjusted if it doesn't match default representation. **Default**: ``True``
.. note:: numpy `datetime64` and `timedelta64` arrays are not converted
to raw temporal vectors if `adjust_dtype` is ``True``
:Kwargs:
- `qtype` (`integer` or `None`) - qtype indicator
:returns: `QList` or `QTemporalList` - array representation of the list
:raises: `ValueError`
'''
if type(array) in (list, tuple):
if meta and 'qtype' in meta and meta['qtype'] == QGENERAL_LIST:
# force shape and dtype for generic lists
tarray = numpy.ndarray(shape = len(array), dtype = numpy.dtype('O'))
for i in range(len(array)):
tarray[i] = array[i]
array = tarray
else:
array = numpy.array(array)
if not isinstance(array, numpy.ndarray):
raise ValueError('array parameter is expected to be of type: numpy.ndarray, list or tuple. Was: %s' % type(array))
qtype = None
is_numpy_temporal = array.dtype.type in (numpy.datetime64, numpy.timedelta64)
if meta and 'qtype' in meta:
qtype = -abs(meta['qtype'])
dtype = PY_TYPE[qtype]
if adjust_dtype and dtype != array.dtype and not is_numpy_temporal:
array = array.astype(dtype = dtype)
qtype = get_list_qtype(array) if qtype is None else qtype
meta['qtype'] = qtype
is_raw_temporal = meta['qtype'] in [QMONTH, QDATE, QDATETIME, QMINUTE, QSECOND, QTIME, QTIMESTAMP, QTIMESPAN] \
and not is_numpy_temporal
vector = array.view(QList) if not is_raw_temporal else array.view(QTemporalList)
vector._meta_init(**meta)
return vector | python | def qlist(array, adjust_dtype = True, **meta):
'''Converts an input array to q vector and enriches object instance with
meta data.
Returns a :class:`.QList` instance for non-datetime vectors. For datetime
vectors :class:`.QTemporalList` is returned instead.
If parameter `adjust_dtype` is `True` and q type retrieved via
:func:`.get_list_qtype` doesn't match one provided as a `qtype` parameter
guessed q type, underlying numpy.array is converted to correct data type.
`qPython` internally represents ``(0x01;0x02;0xff)`` q list as:
``<class 'qpython.qcollection.QList'> dtype: int8 qtype: -4: [ 1 2 -1]``.
This object can be created by calling the :func:`.qlist` with following
arguments:
- `byte numpy.array`:
>>> v = qlist(numpy.array([0x01, 0x02, 0xff], dtype=numpy.byte))
>>> print('%s dtype: %s qtype: %d: %s' % (type(v), v.dtype, v.meta.qtype, v))
<class 'qpython.qcollection.QList'> dtype: int8 qtype: -4: [ 1 2 -1]
- `int32 numpy.array` with explicit conversion to `QBYTE_LIST`:
>>> v = qlist(numpy.array([1, 2, -1]), qtype = QBYTE_LIST)
>>> print('%s dtype: %s qtype: %d: %s' % (type(v), v.dtype, v.meta.qtype, v))
<class 'qpython.qcollection.QList'> dtype: int8 qtype: -4: [ 1 2 -1]
- plain Python `integer` list with explicit conversion to `QBYTE_LIST`:
>>> v = qlist([1, 2, -1], qtype = QBYTE_LIST)
>>> print('%s dtype: %s qtype: %d: %s' % (type(v), v.dtype, v.meta.qtype, v))
<class 'qpython.qcollection.QList'> dtype: int8 qtype: -4: [ 1 2 -1]
- numpy datetime64 array with implicit conversion to `QDATE_LIST`:
>>> v = qlist(numpy.array([numpy.datetime64('2001-01-01'), numpy.datetime64('2000-05-01'), numpy.datetime64('NaT')], dtype='datetime64[D]'))
>>> print('%s dtype: %s qtype: %d: %s' % (type(v), v.dtype, v.meta.qtype, v))
<class 'qpython.qcollection.QList'> dtype: datetime64[D] qtype: -14: ['2001-01-01' '2000-05-01' 'NaT']
- numpy datetime64 array with explicit conversion to `QDATE_LIST`:
>>> v = qlist(numpy.array([numpy.datetime64('2001-01-01'), numpy.datetime64('2000-05-01'), numpy.datetime64('NaT')], dtype='datetime64[D]'), qtype = QDATE_LIST)
>>> print('%s dtype: %s qtype: %d: %s' % (type(v), v.dtype, v.meta.qtype, v))
<class 'qpython.qcollection.QList'> dtype: datetime64[D] qtype: -14: ['2001-01-01' '2000-05-01' 'NaT']
:Parameters:
- `array` (`tuple`, `list`, `numpy.array`) - input array to be converted
- `adjust_dtype` (`boolean`) - determine whether data type of vector should
be adjusted if it doesn't match default representation. **Default**: ``True``
.. note:: numpy `datetime64` and `timedelta64` arrays are not converted
to raw temporal vectors if `adjust_dtype` is ``True``
:Kwargs:
- `qtype` (`integer` or `None`) - qtype indicator
:returns: `QList` or `QTemporalList` - array representation of the list
:raises: `ValueError`
'''
if type(array) in (list, tuple):
if meta and 'qtype' in meta and meta['qtype'] == QGENERAL_LIST:
# force shape and dtype for generic lists
tarray = numpy.ndarray(shape = len(array), dtype = numpy.dtype('O'))
for i in range(len(array)):
tarray[i] = array[i]
array = tarray
else:
array = numpy.array(array)
if not isinstance(array, numpy.ndarray):
raise ValueError('array parameter is expected to be of type: numpy.ndarray, list or tuple. Was: %s' % type(array))
qtype = None
is_numpy_temporal = array.dtype.type in (numpy.datetime64, numpy.timedelta64)
if meta and 'qtype' in meta:
qtype = -abs(meta['qtype'])
dtype = PY_TYPE[qtype]
if adjust_dtype and dtype != array.dtype and not is_numpy_temporal:
array = array.astype(dtype = dtype)
qtype = get_list_qtype(array) if qtype is None else qtype
meta['qtype'] = qtype
is_raw_temporal = meta['qtype'] in [QMONTH, QDATE, QDATETIME, QMINUTE, QSECOND, QTIME, QTIMESTAMP, QTIMESPAN] \
and not is_numpy_temporal
vector = array.view(QList) if not is_raw_temporal else array.view(QTemporalList)
vector._meta_init(**meta)
return vector | [
"def",
"qlist",
"(",
"array",
",",
"adjust_dtype",
"=",
"True",
",",
"*",
"*",
"meta",
")",
":",
"if",
"type",
"(",
"array",
")",
"in",
"(",
"list",
",",
"tuple",
")",
":",
"if",
"meta",
"and",
"'qtype'",
"in",
"meta",
"and",
"meta",
"[",
"'qtype... | Converts an input array to q vector and enriches object instance with
meta data.
Returns a :class:`.QList` instance for non-datetime vectors. For datetime
vectors :class:`.QTemporalList` is returned instead.
If parameter `adjust_dtype` is `True` and q type retrieved via
:func:`.get_list_qtype` doesn't match one provided as a `qtype` parameter
guessed q type, underlying numpy.array is converted to correct data type.
`qPython` internally represents ``(0x01;0x02;0xff)`` q list as:
``<class 'qpython.qcollection.QList'> dtype: int8 qtype: -4: [ 1 2 -1]``.
This object can be created by calling the :func:`.qlist` with following
arguments:
- `byte numpy.array`:
>>> v = qlist(numpy.array([0x01, 0x02, 0xff], dtype=numpy.byte))
>>> print('%s dtype: %s qtype: %d: %s' % (type(v), v.dtype, v.meta.qtype, v))
<class 'qpython.qcollection.QList'> dtype: int8 qtype: -4: [ 1 2 -1]
- `int32 numpy.array` with explicit conversion to `QBYTE_LIST`:
>>> v = qlist(numpy.array([1, 2, -1]), qtype = QBYTE_LIST)
>>> print('%s dtype: %s qtype: %d: %s' % (type(v), v.dtype, v.meta.qtype, v))
<class 'qpython.qcollection.QList'> dtype: int8 qtype: -4: [ 1 2 -1]
- plain Python `integer` list with explicit conversion to `QBYTE_LIST`:
>>> v = qlist([1, 2, -1], qtype = QBYTE_LIST)
>>> print('%s dtype: %s qtype: %d: %s' % (type(v), v.dtype, v.meta.qtype, v))
<class 'qpython.qcollection.QList'> dtype: int8 qtype: -4: [ 1 2 -1]
- numpy datetime64 array with implicit conversion to `QDATE_LIST`:
>>> v = qlist(numpy.array([numpy.datetime64('2001-01-01'), numpy.datetime64('2000-05-01'), numpy.datetime64('NaT')], dtype='datetime64[D]'))
>>> print('%s dtype: %s qtype: %d: %s' % (type(v), v.dtype, v.meta.qtype, v))
<class 'qpython.qcollection.QList'> dtype: datetime64[D] qtype: -14: ['2001-01-01' '2000-05-01' 'NaT']
- numpy datetime64 array with explicit conversion to `QDATE_LIST`:
>>> v = qlist(numpy.array([numpy.datetime64('2001-01-01'), numpy.datetime64('2000-05-01'), numpy.datetime64('NaT')], dtype='datetime64[D]'), qtype = QDATE_LIST)
>>> print('%s dtype: %s qtype: %d: %s' % (type(v), v.dtype, v.meta.qtype, v))
<class 'qpython.qcollection.QList'> dtype: datetime64[D] qtype: -14: ['2001-01-01' '2000-05-01' 'NaT']
:Parameters:
- `array` (`tuple`, `list`, `numpy.array`) - input array to be converted
- `adjust_dtype` (`boolean`) - determine whether data type of vector should
be adjusted if it doesn't match default representation. **Default**: ``True``
.. note:: numpy `datetime64` and `timedelta64` arrays are not converted
to raw temporal vectors if `adjust_dtype` is ``True``
:Kwargs:
- `qtype` (`integer` or `None`) - qtype indicator
:returns: `QList` or `QTemporalList` - array representation of the list
:raises: `ValueError` | [
"Converts",
"an",
"input",
"array",
"to",
"q",
"vector",
"and",
"enriches",
"object",
"instance",
"with",
"meta",
"data",
"."
] | 7e64a28b1e8814a8d6b9217ce79bb8de546e62f3 | https://github.com/exxeleron/qPython/blob/7e64a28b1e8814a8d6b9217ce79bb8de546e62f3/qpython/qcollection.py#L105-L196 | train | 34,408 |
wkentaro/gdown | gdown/parse_url.py | parse_url | def parse_url(url, warning=True):
"""Parse URLs especially for Google Drive links.
file_id: ID of file on Google Drive.
is_download_link: Flag if it is download link of Google Drive.
"""
parsed = urllib_parse.urlparse(url)
query = urllib_parse.parse_qs(parsed.query)
is_gdrive = parsed.hostname == 'drive.google.com'
is_download_link = parsed.path.endswith('/uc')
file_id = None
if is_gdrive and 'id' in query:
file_ids = query['id']
if len(file_ids) == 1:
file_id = file_ids[0]
match = re.match(r'^/file/d/(.*?)/view$', parsed.path)
if match:
file_id = match.groups()[0]
if is_gdrive and not is_download_link:
warnings.warn(
'You specified Google Drive Link but it is not the correct link '
"to download the file. Maybe you should try: {url}"
.format(url='https://drive.google.com/uc?id={}'.format(file_id))
)
return file_id, is_download_link | python | def parse_url(url, warning=True):
"""Parse URLs especially for Google Drive links.
file_id: ID of file on Google Drive.
is_download_link: Flag if it is download link of Google Drive.
"""
parsed = urllib_parse.urlparse(url)
query = urllib_parse.parse_qs(parsed.query)
is_gdrive = parsed.hostname == 'drive.google.com'
is_download_link = parsed.path.endswith('/uc')
file_id = None
if is_gdrive and 'id' in query:
file_ids = query['id']
if len(file_ids) == 1:
file_id = file_ids[0]
match = re.match(r'^/file/d/(.*?)/view$', parsed.path)
if match:
file_id = match.groups()[0]
if is_gdrive and not is_download_link:
warnings.warn(
'You specified Google Drive Link but it is not the correct link '
"to download the file. Maybe you should try: {url}"
.format(url='https://drive.google.com/uc?id={}'.format(file_id))
)
return file_id, is_download_link | [
"def",
"parse_url",
"(",
"url",
",",
"warning",
"=",
"True",
")",
":",
"parsed",
"=",
"urllib_parse",
".",
"urlparse",
"(",
"url",
")",
"query",
"=",
"urllib_parse",
".",
"parse_qs",
"(",
"parsed",
".",
"query",
")",
"is_gdrive",
"=",
"parsed",
".",
"h... | Parse URLs especially for Google Drive links.
file_id: ID of file on Google Drive.
is_download_link: Flag if it is download link of Google Drive. | [
"Parse",
"URLs",
"especially",
"for",
"Google",
"Drive",
"links",
"."
] | d2952b56f7da3dddceb096e27569b5375a76d267 | https://github.com/wkentaro/gdown/blob/d2952b56f7da3dddceb096e27569b5375a76d267/gdown/parse_url.py#L7-L34 | train | 34,409 |
wkentaro/gdown | gdown/extractall.py | extractall | def extractall(path, to=None):
"""Extract archive file.
Parameters
----------
path: str
Path of archive file to be extracted.
to: str, optional
Directory to which the archive file will be extracted.
If None, it will be set to the parent directory of the archive file.
"""
if to is None:
to = osp.dirname(path)
if path.endswith('.zip'):
opener, mode = zipfile.ZipFile, 'r'
elif path.endswith('.tar'):
opener, mode = tarfile.open, 'r'
elif path.endswith('.tar.gz') or path.endswith('.tgz'):
opener, mode = tarfile.open, 'r:gz'
elif path.endswith('.tar.bz2') or path.endswith('.tbz'):
opener, mode = tarfile.open, 'r:bz2'
else:
raise ValueError("Could not extract '%s' as no appropriate "
"extractor is found" % path)
def namelist(f):
if isinstance(f, zipfile.ZipFile):
return f.namelist()
return [m.path for m in f.members]
def filelist(f):
files = []
for fname in namelist(f):
fname = osp.join(to, fname)
files.append(fname)
return files
with opener(path, mode) as f:
f.extractall(path=to)
return filelist(f) | python | def extractall(path, to=None):
"""Extract archive file.
Parameters
----------
path: str
Path of archive file to be extracted.
to: str, optional
Directory to which the archive file will be extracted.
If None, it will be set to the parent directory of the archive file.
"""
if to is None:
to = osp.dirname(path)
if path.endswith('.zip'):
opener, mode = zipfile.ZipFile, 'r'
elif path.endswith('.tar'):
opener, mode = tarfile.open, 'r'
elif path.endswith('.tar.gz') or path.endswith('.tgz'):
opener, mode = tarfile.open, 'r:gz'
elif path.endswith('.tar.bz2') or path.endswith('.tbz'):
opener, mode = tarfile.open, 'r:bz2'
else:
raise ValueError("Could not extract '%s' as no appropriate "
"extractor is found" % path)
def namelist(f):
if isinstance(f, zipfile.ZipFile):
return f.namelist()
return [m.path for m in f.members]
def filelist(f):
files = []
for fname in namelist(f):
fname = osp.join(to, fname)
files.append(fname)
return files
with opener(path, mode) as f:
f.extractall(path=to)
return filelist(f) | [
"def",
"extractall",
"(",
"path",
",",
"to",
"=",
"None",
")",
":",
"if",
"to",
"is",
"None",
":",
"to",
"=",
"osp",
".",
"dirname",
"(",
"path",
")",
"if",
"path",
".",
"endswith",
"(",
"'.zip'",
")",
":",
"opener",
",",
"mode",
"=",
"zipfile",
... | Extract archive file.
Parameters
----------
path: str
Path of archive file to be extracted.
to: str, optional
Directory to which the archive file will be extracted.
If None, it will be set to the parent directory of the archive file. | [
"Extract",
"archive",
"file",
"."
] | d2952b56f7da3dddceb096e27569b5375a76d267 | https://github.com/wkentaro/gdown/blob/d2952b56f7da3dddceb096e27569b5375a76d267/gdown/extractall.py#L6-L47 | train | 34,410 |
benhoff/vexbot | vexbot/adapters/shell/interfaces.py | _add_word | def _add_word(completer):
"""
Used to add words to the completors
"""
def inner(word: str):
completer.words.add(word)
return inner | python | def _add_word(completer):
"""
Used to add words to the completors
"""
def inner(word: str):
completer.words.add(word)
return inner | [
"def",
"_add_word",
"(",
"completer",
")",
":",
"def",
"inner",
"(",
"word",
":",
"str",
")",
":",
"completer",
".",
"words",
".",
"add",
"(",
"word",
")",
"return",
"inner"
] | Used to add words to the completors | [
"Used",
"to",
"add",
"words",
"to",
"the",
"completors"
] | 9b844eb20e84eea92a0e7db7d86a90094956c38f | https://github.com/benhoff/vexbot/blob/9b844eb20e84eea92a0e7db7d86a90094956c38f/vexbot/adapters/shell/interfaces.py#L8-L14 | train | 34,411 |
benhoff/vexbot | vexbot/adapters/shell/interfaces.py | _remove_word | def _remove_word(completer):
"""
Used to remove words from the completors
"""
def inner(word: str):
try:
completer.words.remove(word)
except Exception:
pass
return inner | python | def _remove_word(completer):
"""
Used to remove words from the completors
"""
def inner(word: str):
try:
completer.words.remove(word)
except Exception:
pass
return inner | [
"def",
"_remove_word",
"(",
"completer",
")",
":",
"def",
"inner",
"(",
"word",
":",
"str",
")",
":",
"try",
":",
"completer",
".",
"words",
".",
"remove",
"(",
"word",
")",
"except",
"Exception",
":",
"pass",
"return",
"inner"
] | Used to remove words from the completors | [
"Used",
"to",
"remove",
"words",
"from",
"the",
"completors"
] | 9b844eb20e84eea92a0e7db7d86a90094956c38f | https://github.com/benhoff/vexbot/blob/9b844eb20e84eea92a0e7db7d86a90094956c38f/vexbot/adapters/shell/interfaces.py#L17-L26 | train | 34,412 |
benhoff/vexbot | vexbot/extensions/log.py | set_info | def set_info(self, *args, **kwargs) -> None:
"""
Sets the log level to `INFO`
"""
self.root_logger.setLevel(logging.INFO)
try:
self.messaging.pub_handler.setLevel(logging.INFO)
except Exception:
pass | python | def set_info(self, *args, **kwargs) -> None:
"""
Sets the log level to `INFO`
"""
self.root_logger.setLevel(logging.INFO)
try:
self.messaging.pub_handler.setLevel(logging.INFO)
except Exception:
pass | [
"def",
"set_info",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"->",
"None",
":",
"self",
".",
"root_logger",
".",
"setLevel",
"(",
"logging",
".",
"INFO",
")",
"try",
":",
"self",
".",
"messaging",
".",
"pub_handler",
".",
"setLevel... | Sets the log level to `INFO` | [
"Sets",
"the",
"log",
"level",
"to",
"INFO"
] | 9b844eb20e84eea92a0e7db7d86a90094956c38f | https://github.com/benhoff/vexbot/blob/9b844eb20e84eea92a0e7db7d86a90094956c38f/vexbot/extensions/log.py#L36-L44 | train | 34,413 |
benhoff/vexbot | vexbot/command_observer.py | CommandObserver.do_REMOTE | def do_REMOTE(self,
target: str,
remote_command: str,
source: list,
*args,
**kwargs) -> None:
"""
Send a remote command to a service. Used
Args:
target: The service that the command gets set to
remote_command: The command to do remotely.
source: the binary source of the zmq_socket. Packed to send to the
"""
if target == self.messaging._service_name:
info = 'target for remote command is the bot itself! Returning the function'
self.logger.info(info)
return self._handle_command(remote_command, source, *args, **kwargs)
try:
target = self.messaging._address_map[target]
except KeyError:
warn = ' Target %s, not found in addresses. Are you sure that %s sent an IDENT message?'
self.logger.warn(warn, target, target)
# TODO: raise an error instead of returning?
# NOTE: Bail here since there's no point in going forward
return
self.logger.info(' REMOTE %s, target: %s | %s, %s',
remote_command, target, args, kwargs)
# package the binary together
source = target + source
self.messaging.send_command_response(source,
remote_command,
*args,
**kwargs) | python | def do_REMOTE(self,
target: str,
remote_command: str,
source: list,
*args,
**kwargs) -> None:
"""
Send a remote command to a service. Used
Args:
target: The service that the command gets set to
remote_command: The command to do remotely.
source: the binary source of the zmq_socket. Packed to send to the
"""
if target == self.messaging._service_name:
info = 'target for remote command is the bot itself! Returning the function'
self.logger.info(info)
return self._handle_command(remote_command, source, *args, **kwargs)
try:
target = self.messaging._address_map[target]
except KeyError:
warn = ' Target %s, not found in addresses. Are you sure that %s sent an IDENT message?'
self.logger.warn(warn, target, target)
# TODO: raise an error instead of returning?
# NOTE: Bail here since there's no point in going forward
return
self.logger.info(' REMOTE %s, target: %s | %s, %s',
remote_command, target, args, kwargs)
# package the binary together
source = target + source
self.messaging.send_command_response(source,
remote_command,
*args,
**kwargs) | [
"def",
"do_REMOTE",
"(",
"self",
",",
"target",
":",
"str",
",",
"remote_command",
":",
"str",
",",
"source",
":",
"list",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"->",
"None",
":",
"if",
"target",
"==",
"self",
".",
"messaging",
".",
"_ser... | Send a remote command to a service. Used
Args:
target: The service that the command gets set to
remote_command: The command to do remotely.
source: the binary source of the zmq_socket. Packed to send to the | [
"Send",
"a",
"remote",
"command",
"to",
"a",
"service",
".",
"Used"
] | 9b844eb20e84eea92a0e7db7d86a90094956c38f | https://github.com/benhoff/vexbot/blob/9b844eb20e84eea92a0e7db7d86a90094956c38f/vexbot/command_observer.py#L125-L161 | train | 34,414 |
benhoff/vexbot | vexbot/command_observer.py | CommandObserver.do_IDENT | def do_IDENT(self, service_name: str, source: list, *args, **kwargs) -> None:
"""
Perform identification of a service to a binary representation.
Args:
service_name: human readable name for service
source: zmq representation for the socket source
"""
self.logger.info(' IDENT %s as %s', service_name, source)
self.messaging._address_map[service_name] = source | python | def do_IDENT(self, service_name: str, source: list, *args, **kwargs) -> None:
"""
Perform identification of a service to a binary representation.
Args:
service_name: human readable name for service
source: zmq representation for the socket source
"""
self.logger.info(' IDENT %s as %s', service_name, source)
self.messaging._address_map[service_name] = source | [
"def",
"do_IDENT",
"(",
"self",
",",
"service_name",
":",
"str",
",",
"source",
":",
"list",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"->",
"None",
":",
"self",
".",
"logger",
".",
"info",
"(",
"' IDENT %s as %s'",
",",
"service_name",
",",
"s... | Perform identification of a service to a binary representation.
Args:
service_name: human readable name for service
source: zmq representation for the socket source | [
"Perform",
"identification",
"of",
"a",
"service",
"to",
"a",
"binary",
"representation",
"."
] | 9b844eb20e84eea92a0e7db7d86a90094956c38f | https://github.com/benhoff/vexbot/blob/9b844eb20e84eea92a0e7db7d86a90094956c38f/vexbot/command_observer.py#L192-L201 | train | 34,415 |
benhoff/vexbot | vexbot/subprocess_manager.py | _name_helper | def _name_helper(name: str):
"""
default to returning a name with `.service`
"""
name = name.rstrip()
if name.endswith(('.service', '.socket', '.target')):
return name
return name + '.service' | python | def _name_helper(name: str):
"""
default to returning a name with `.service`
"""
name = name.rstrip()
if name.endswith(('.service', '.socket', '.target')):
return name
return name + '.service' | [
"def",
"_name_helper",
"(",
"name",
":",
"str",
")",
":",
"name",
"=",
"name",
".",
"rstrip",
"(",
")",
"if",
"name",
".",
"endswith",
"(",
"(",
"'.service'",
",",
"'.socket'",
",",
"'.target'",
")",
")",
":",
"return",
"name",
"return",
"name",
"+",... | default to returning a name with `.service` | [
"default",
"to",
"returning",
"a",
"name",
"with",
".",
"service"
] | 9b844eb20e84eea92a0e7db7d86a90094956c38f | https://github.com/benhoff/vexbot/blob/9b844eb20e84eea92a0e7db7d86a90094956c38f/vexbot/subprocess_manager.py#L12-L19 | train | 34,416 |
benhoff/vexbot | vexbot/util/get_certificate_filepath.py | get_vexbot_certificate_filepath | def get_vexbot_certificate_filepath() -> (str, bool):
"""
Returns the vexbot certificate filepath and the whether it is the private
filepath or not
"""
public_filepath, secret_filepath = _certificate_helper('vexbot.key','vexbot.key_secret')
if path.isfile(secret_filepath):
return secret_filepath, True
if not path.isfile(public_filepath):
err = ('certificates not found. Generate certificates from the '
'command line using `vexbot_generate_certificates`')
raise FileNotFoundError(err)
return public_filepath, False | python | def get_vexbot_certificate_filepath() -> (str, bool):
"""
Returns the vexbot certificate filepath and the whether it is the private
filepath or not
"""
public_filepath, secret_filepath = _certificate_helper('vexbot.key','vexbot.key_secret')
if path.isfile(secret_filepath):
return secret_filepath, True
if not path.isfile(public_filepath):
err = ('certificates not found. Generate certificates from the '
'command line using `vexbot_generate_certificates`')
raise FileNotFoundError(err)
return public_filepath, False | [
"def",
"get_vexbot_certificate_filepath",
"(",
")",
"->",
"(",
"str",
",",
"bool",
")",
":",
"public_filepath",
",",
"secret_filepath",
"=",
"_certificate_helper",
"(",
"'vexbot.key'",
",",
"'vexbot.key_secret'",
")",
"if",
"path",
".",
"isfile",
"(",
"secret_file... | Returns the vexbot certificate filepath and the whether it is the private
filepath or not | [
"Returns",
"the",
"vexbot",
"certificate",
"filepath",
"and",
"the",
"whether",
"it",
"is",
"the",
"private",
"filepath",
"or",
"not"
] | 9b844eb20e84eea92a0e7db7d86a90094956c38f | https://github.com/benhoff/vexbot/blob/9b844eb20e84eea92a0e7db7d86a90094956c38f/vexbot/util/get_certificate_filepath.py#L28-L40 | train | 34,417 |
benhoff/vexbot | vexbot/extensions/develop.py | get_code | def get_code(self, *args, **kwargs):
"""
get the python source code from callback
"""
# FIXME: Honestly should allow multiple commands
callback = self._commands[args[0]]
# TODO: syntax color would be nice
source = _inspect.getsourcelines(callback)[0]
"""
source_len = len(source)
source = PygmentsLexer(CythonLexer).lex_document(source)()
"""
# FIXME: formatting sucks
return "\n" + "".join(source) | python | def get_code(self, *args, **kwargs):
"""
get the python source code from callback
"""
# FIXME: Honestly should allow multiple commands
callback = self._commands[args[0]]
# TODO: syntax color would be nice
source = _inspect.getsourcelines(callback)[0]
"""
source_len = len(source)
source = PygmentsLexer(CythonLexer).lex_document(source)()
"""
# FIXME: formatting sucks
return "\n" + "".join(source) | [
"def",
"get_code",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# FIXME: Honestly should allow multiple commands",
"callback",
"=",
"self",
".",
"_commands",
"[",
"args",
"[",
"0",
"]",
"]",
"# TODO: syntax color would be nice",
"source",
"... | get the python source code from callback | [
"get",
"the",
"python",
"source",
"code",
"from",
"callback"
] | 9b844eb20e84eea92a0e7db7d86a90094956c38f | https://github.com/benhoff/vexbot/blob/9b844eb20e84eea92a0e7db7d86a90094956c38f/vexbot/extensions/develop.py#L4-L17 | train | 34,418 |
benhoff/vexbot | vexbot/adapters/messaging.py | _HeartbeatReciever._get_state | def _get_state(self) -> None:
"""
Internal method that accomplishes checking to make sure that the UUID
has not changed
"""
# Don't need to go any further if we don't have a message
if self.last_message is None:
return
# get the latest message UUID
uuid = self.last_message.uuid
# Check it against the stored UUID
if uuid != self._last_bot_uuid:
self.logger.info(' UUID message mismatch')
self.logger.debug(' Old UUID: %s | New UUID: %s',
self._last_bot_uuid,
uuid)
self.send_identity()
# Store the latest message UUID now that we've sent an IDENT
self._last_bot_uuid = uuid | python | def _get_state(self) -> None:
"""
Internal method that accomplishes checking to make sure that the UUID
has not changed
"""
# Don't need to go any further if we don't have a message
if self.last_message is None:
return
# get the latest message UUID
uuid = self.last_message.uuid
# Check it against the stored UUID
if uuid != self._last_bot_uuid:
self.logger.info(' UUID message mismatch')
self.logger.debug(' Old UUID: %s | New UUID: %s',
self._last_bot_uuid,
uuid)
self.send_identity()
# Store the latest message UUID now that we've sent an IDENT
self._last_bot_uuid = uuid | [
"def",
"_get_state",
"(",
"self",
")",
"->",
"None",
":",
"# Don't need to go any further if we don't have a message",
"if",
"self",
".",
"last_message",
"is",
"None",
":",
"return",
"# get the latest message UUID",
"uuid",
"=",
"self",
".",
"last_message",
".",
"uuid... | Internal method that accomplishes checking to make sure that the UUID
has not changed | [
"Internal",
"method",
"that",
"accomplishes",
"checking",
"to",
"make",
"sure",
"that",
"the",
"UUID",
"has",
"not",
"changed"
] | 9b844eb20e84eea92a0e7db7d86a90094956c38f | https://github.com/benhoff/vexbot/blob/9b844eb20e84eea92a0e7db7d86a90094956c38f/vexbot/adapters/messaging.py#L80-L100 | train | 34,419 |
benhoff/vexbot | vexbot/adapters/messaging.py | _HeartbeatReciever.send_identity | def send_identity(self):
"""
Send the identity of the service.
"""
service_name = {'service_name': self.messaging._service_name}
service_name = _json.dumps(service_name).encode('utf8')
identify_frame = (b'',
b'IDENT',
_json.dumps([]).encode('utf8'),
service_name)
# NOTE: Have to do this manually since we built the frame
if self.messaging._run_control_loop:
# pep8 alias
send = self.messaging.command_socket.send_multipart
self.messaging.add_callback(send, identify_frame)
else:
self.messaging.command_socket.send_multipart(identify_frame)
self.logger.info(' Service Identity sent: %s',
self.messaging._service_name)
if self.identity_callback:
self.identity_callback() | python | def send_identity(self):
"""
Send the identity of the service.
"""
service_name = {'service_name': self.messaging._service_name}
service_name = _json.dumps(service_name).encode('utf8')
identify_frame = (b'',
b'IDENT',
_json.dumps([]).encode('utf8'),
service_name)
# NOTE: Have to do this manually since we built the frame
if self.messaging._run_control_loop:
# pep8 alias
send = self.messaging.command_socket.send_multipart
self.messaging.add_callback(send, identify_frame)
else:
self.messaging.command_socket.send_multipart(identify_frame)
self.logger.info(' Service Identity sent: %s',
self.messaging._service_name)
if self.identity_callback:
self.identity_callback() | [
"def",
"send_identity",
"(",
"self",
")",
":",
"service_name",
"=",
"{",
"'service_name'",
":",
"self",
".",
"messaging",
".",
"_service_name",
"}",
"service_name",
"=",
"_json",
".",
"dumps",
"(",
"service_name",
")",
".",
"encode",
"(",
"'utf8'",
")",
"i... | Send the identity of the service. | [
"Send",
"the",
"identity",
"of",
"the",
"service",
"."
] | 9b844eb20e84eea92a0e7db7d86a90094956c38f | https://github.com/benhoff/vexbot/blob/9b844eb20e84eea92a0e7db7d86a90094956c38f/vexbot/adapters/messaging.py#L102-L126 | train | 34,420 |
benhoff/vexbot | vexbot/adapters/messaging.py | Messaging._config_convert_to_address_helper | def _config_convert_to_address_helper(self) -> None:
"""
converts the config from ports to zmq ip addresses
Operates on `self.config` using `self._socket_factory.to_address`
"""
to_address = self._socket_factory.to_address
for k, v in self.config.items():
if k == 'chatter_subscription_port':
continue
if k.endswith('port'):
self.config[k] = to_address(v) | python | def _config_convert_to_address_helper(self) -> None:
"""
converts the config from ports to zmq ip addresses
Operates on `self.config` using `self._socket_factory.to_address`
"""
to_address = self._socket_factory.to_address
for k, v in self.config.items():
if k == 'chatter_subscription_port':
continue
if k.endswith('port'):
self.config[k] = to_address(v) | [
"def",
"_config_convert_to_address_helper",
"(",
"self",
")",
"->",
"None",
":",
"to_address",
"=",
"self",
".",
"_socket_factory",
".",
"to_address",
"for",
"k",
",",
"v",
"in",
"self",
".",
"config",
".",
"items",
"(",
")",
":",
"if",
"k",
"==",
"'chat... | converts the config from ports to zmq ip addresses
Operates on `self.config` using `self._socket_factory.to_address` | [
"converts",
"the",
"config",
"from",
"ports",
"to",
"zmq",
"ip",
"addresses",
"Operates",
"on",
"self",
".",
"config",
"using",
"self",
".",
"_socket_factory",
".",
"to_address"
] | 9b844eb20e84eea92a0e7db7d86a90094956c38f | https://github.com/benhoff/vexbot/blob/9b844eb20e84eea92a0e7db7d86a90094956c38f/vexbot/adapters/messaging.py#L239-L249 | train | 34,421 |
benhoff/vexbot | vexbot/adapters/messaging.py | Messaging.add_callback | def add_callback(self, callback: _Callable, *args, **kwargs) -> None:
"""
Add a callback to the event loop
"""
self.loop.add_callback(callback, *args, **kwargs) | python | def add_callback(self, callback: _Callable, *args, **kwargs) -> None:
"""
Add a callback to the event loop
"""
self.loop.add_callback(callback, *args, **kwargs) | [
"def",
"add_callback",
"(",
"self",
",",
"callback",
":",
"_Callable",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"->",
"None",
":",
"self",
".",
"loop",
".",
"add_callback",
"(",
"callback",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Add a callback to the event loop | [
"Add",
"a",
"callback",
"to",
"the",
"event",
"loop"
] | 9b844eb20e84eea92a0e7db7d86a90094956c38f | https://github.com/benhoff/vexbot/blob/9b844eb20e84eea92a0e7db7d86a90094956c38f/vexbot/adapters/messaging.py#L251-L255 | train | 34,422 |
benhoff/vexbot | vexbot/adapters/messaging.py | Messaging.start | def start(self) -> None:
"""
Start the internal control loop. Potentially blocking, depending on
the value of `_run_control_loop` set by the initializer.
"""
self._setup()
if self._run_control_loop:
asyncio.set_event_loop(asyncio.new_event_loop())
self._heartbeat_reciever.start()
self._logger.info(' Start Loop')
return self.loop.start()
else:
self._logger.debug(' run_control_loop == False') | python | def start(self) -> None:
"""
Start the internal control loop. Potentially blocking, depending on
the value of `_run_control_loop` set by the initializer.
"""
self._setup()
if self._run_control_loop:
asyncio.set_event_loop(asyncio.new_event_loop())
self._heartbeat_reciever.start()
self._logger.info(' Start Loop')
return self.loop.start()
else:
self._logger.debug(' run_control_loop == False') | [
"def",
"start",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"_setup",
"(",
")",
"if",
"self",
".",
"_run_control_loop",
":",
"asyncio",
".",
"set_event_loop",
"(",
"asyncio",
".",
"new_event_loop",
"(",
")",
")",
"self",
".",
"_heartbeat_reciever",
... | Start the internal control loop. Potentially blocking, depending on
the value of `_run_control_loop` set by the initializer. | [
"Start",
"the",
"internal",
"control",
"loop",
".",
"Potentially",
"blocking",
"depending",
"on",
"the",
"value",
"of",
"_run_control_loop",
"set",
"by",
"the",
"initializer",
"."
] | 9b844eb20e84eea92a0e7db7d86a90094956c38f | https://github.com/benhoff/vexbot/blob/9b844eb20e84eea92a0e7db7d86a90094956c38f/vexbot/adapters/messaging.py#L257-L270 | train | 34,423 |
benhoff/vexbot | vexbot/adapters/messaging.py | Messaging.send_command | def send_command(self, command: str, *args, **kwargs):
"""
For request bot to perform some action
"""
info = 'send command `%s` to bot. Args: %s | Kwargs: %s'
self._messaging_logger.command.info(info, command, args, kwargs)
command = command.encode('utf8')
# target = target.encode('ascii')
args = _json.dumps(args).encode('utf8')
kwargs = _json.dumps(kwargs).encode('utf8')
frame = (b'', command, args, kwargs)
debug = ' send command run_control_loop: %s'
self._messaging_logger.command.debug(debug, self._run_control_loop)
if self._run_control_loop:
self.add_callback(self.command_socket.send_multipart, frame)
else:
self.command_socket.send_multipart(frame) | python | def send_command(self, command: str, *args, **kwargs):
"""
For request bot to perform some action
"""
info = 'send command `%s` to bot. Args: %s | Kwargs: %s'
self._messaging_logger.command.info(info, command, args, kwargs)
command = command.encode('utf8')
# target = target.encode('ascii')
args = _json.dumps(args).encode('utf8')
kwargs = _json.dumps(kwargs).encode('utf8')
frame = (b'', command, args, kwargs)
debug = ' send command run_control_loop: %s'
self._messaging_logger.command.debug(debug, self._run_control_loop)
if self._run_control_loop:
self.add_callback(self.command_socket.send_multipart, frame)
else:
self.command_socket.send_multipart(frame) | [
"def",
"send_command",
"(",
"self",
",",
"command",
":",
"str",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"info",
"=",
"'send command `%s` to bot. Args: %s | Kwargs: %s'",
"self",
".",
"_messaging_logger",
".",
"command",
".",
"info",
"(",
"info",
... | For request bot to perform some action | [
"For",
"request",
"bot",
"to",
"perform",
"some",
"action"
] | 9b844eb20e84eea92a0e7db7d86a90094956c38f | https://github.com/benhoff/vexbot/blob/9b844eb20e84eea92a0e7db7d86a90094956c38f/vexbot/adapters/messaging.py#L403-L421 | train | 34,424 |
benhoff/vexbot | vexbot/util/socket_factory.py | SocketFactory.to_address | def to_address(self, port: str):
"""
transforms the ports into addresses.
Will fall through if the port looks like an address
"""
# check to see if user passed in a string
# if they did, they want to use that instead
if isinstance(port, str) and len(port) > 6:
return port
zmq_address = '{}://{}:{}'
return zmq_address.format(self.protocol,
self.address,
port) | python | def to_address(self, port: str):
"""
transforms the ports into addresses.
Will fall through if the port looks like an address
"""
# check to see if user passed in a string
# if they did, they want to use that instead
if isinstance(port, str) and len(port) > 6:
return port
zmq_address = '{}://{}:{}'
return zmq_address.format(self.protocol,
self.address,
port) | [
"def",
"to_address",
"(",
"self",
",",
"port",
":",
"str",
")",
":",
"# check to see if user passed in a string",
"# if they did, they want to use that instead",
"if",
"isinstance",
"(",
"port",
",",
"str",
")",
"and",
"len",
"(",
"port",
")",
">",
"6",
":",
"re... | transforms the ports into addresses.
Will fall through if the port looks like an address | [
"transforms",
"the",
"ports",
"into",
"addresses",
".",
"Will",
"fall",
"through",
"if",
"the",
"port",
"looks",
"like",
"an",
"address"
] | 9b844eb20e84eea92a0e7db7d86a90094956c38f | https://github.com/benhoff/vexbot/blob/9b844eb20e84eea92a0e7db7d86a90094956c38f/vexbot/util/socket_factory.py#L148-L161 | train | 34,425 |
benhoff/vexbot | vexbot/util/socket_factory.py | SocketFactory.iterate_multiple_addresses | def iterate_multiple_addresses(self, ports: (str, list, tuple)):
"""
transforms an iterable, or the expectation of an iterable
into zmq addresses
"""
if isinstance(ports, (str, int)):
# TODO: verify this works.
ports = tuple(ports,)
result = []
for port in ports:
result.append(self.to_address(port))
return result | python | def iterate_multiple_addresses(self, ports: (str, list, tuple)):
"""
transforms an iterable, or the expectation of an iterable
into zmq addresses
"""
if isinstance(ports, (str, int)):
# TODO: verify this works.
ports = tuple(ports,)
result = []
for port in ports:
result.append(self.to_address(port))
return result | [
"def",
"iterate_multiple_addresses",
"(",
"self",
",",
"ports",
":",
"(",
"str",
",",
"list",
",",
"tuple",
")",
")",
":",
"if",
"isinstance",
"(",
"ports",
",",
"(",
"str",
",",
"int",
")",
")",
":",
"# TODO: verify this works.",
"ports",
"=",
"tuple",
... | transforms an iterable, or the expectation of an iterable
into zmq addresses | [
"transforms",
"an",
"iterable",
"or",
"the",
"expectation",
"of",
"an",
"iterable",
"into",
"zmq",
"addresses"
] | 9b844eb20e84eea92a0e7db7d86a90094956c38f | https://github.com/benhoff/vexbot/blob/9b844eb20e84eea92a0e7db7d86a90094956c38f/vexbot/util/socket_factory.py#L163-L176 | train | 34,426 |
benhoff/vexbot | vexbot/adapters/shell/shell.py | Shell.is_command | def is_command(self, text: str) -> bool:
"""
checks for presence of shebang in the first character of the text
"""
if text[0] in self.shebangs:
return True
return False | python | def is_command(self, text: str) -> bool:
"""
checks for presence of shebang in the first character of the text
"""
if text[0] in self.shebangs:
return True
return False | [
"def",
"is_command",
"(",
"self",
",",
"text",
":",
"str",
")",
"->",
"bool",
":",
"if",
"text",
"[",
"0",
"]",
"in",
"self",
".",
"shebangs",
":",
"return",
"True",
"return",
"False"
] | checks for presence of shebang in the first character of the text | [
"checks",
"for",
"presence",
"of",
"shebang",
"in",
"the",
"first",
"character",
"of",
"the",
"text"
] | 9b844eb20e84eea92a0e7db7d86a90094956c38f | https://github.com/benhoff/vexbot/blob/9b844eb20e84eea92a0e7db7d86a90094956c38f/vexbot/adapters/shell/shell.py#L147-L154 | train | 34,427 |
benhoff/vexbot | vexbot/adapters/shell/shell.py | Shell._handle_text | def _handle_text(self, text: str):
"""
Check to see if text is a command. Otherwise, check to see if the
second word is a command.
Commands get handeled by the `_handle_command` method
If not command, check to see if first word is a service or an author.
Default program is to send message replies. However, we will also
check to see if the second word is a command and handle approparitly
This method does simple string parsing and high level program control
"""
# If first word is command
if self.is_command(text):
self._logger.debug(' first word is a command')
# get the command, args, and kwargs out using `shlex`
command, args, kwargs = _get_cmd_args_kwargs(text)
self._logger.info(' command: %s, %s %s', command, args, kwargs)
# hand off to the `handle_command` method
result = self._handle_command(command, args, kwargs)
if result:
if isinstance(result, str):
print(result)
else:
_pprint.pprint(result)
# Exit the method here if in this block
return
# Else first word is not a command
else:
self._logger.debug(' first word is not a command')
# get the first word and then the rest of the text.
try:
first_word, second_word = text.split(' ', 1)
self._logger.debug(' first word: %s', first_word)
except ValueError:
self._logger.debug('No second word in chain!')
return self._handle_NLP(text)
# check if second word/string is a command
if self.is_command(second_word):
self._logger.info(' second word is a command')
# get the command, args, and kwargs out using `shlex`
command, args, kwargs = _get_cmd_args_kwargs(second_word)
self._logger.debug(' second word: %s', command)
self._logger.debug(' command %s', command)
self._logger.debug('args %s ', args)
self._logger.debug('kwargs %s', kwargs)
return self._first_word_not_cmd(first_word, command, args, kwargs)
# if second word is not a command, default to NLP
else:
self._logger.info(' defaulting to message since second word '
'isn\'t a command')
return self._handle_NLP(text) | python | def _handle_text(self, text: str):
"""
Check to see if text is a command. Otherwise, check to see if the
second word is a command.
Commands get handeled by the `_handle_command` method
If not command, check to see if first word is a service or an author.
Default program is to send message replies. However, we will also
check to see if the second word is a command and handle approparitly
This method does simple string parsing and high level program control
"""
# If first word is command
if self.is_command(text):
self._logger.debug(' first word is a command')
# get the command, args, and kwargs out using `shlex`
command, args, kwargs = _get_cmd_args_kwargs(text)
self._logger.info(' command: %s, %s %s', command, args, kwargs)
# hand off to the `handle_command` method
result = self._handle_command(command, args, kwargs)
if result:
if isinstance(result, str):
print(result)
else:
_pprint.pprint(result)
# Exit the method here if in this block
return
# Else first word is not a command
else:
self._logger.debug(' first word is not a command')
# get the first word and then the rest of the text.
try:
first_word, second_word = text.split(' ', 1)
self._logger.debug(' first word: %s', first_word)
except ValueError:
self._logger.debug('No second word in chain!')
return self._handle_NLP(text)
# check if second word/string is a command
if self.is_command(second_word):
self._logger.info(' second word is a command')
# get the command, args, and kwargs out using `shlex`
command, args, kwargs = _get_cmd_args_kwargs(second_word)
self._logger.debug(' second word: %s', command)
self._logger.debug(' command %s', command)
self._logger.debug('args %s ', args)
self._logger.debug('kwargs %s', kwargs)
return self._first_word_not_cmd(first_word, command, args, kwargs)
# if second word is not a command, default to NLP
else:
self._logger.info(' defaulting to message since second word '
'isn\'t a command')
return self._handle_NLP(text) | [
"def",
"_handle_text",
"(",
"self",
",",
"text",
":",
"str",
")",
":",
"# If first word is command",
"if",
"self",
".",
"is_command",
"(",
"text",
")",
":",
"self",
".",
"_logger",
".",
"debug",
"(",
"' first word is a command'",
")",
"# get the command, args, a... | Check to see if text is a command. Otherwise, check to see if the
second word is a command.
Commands get handeled by the `_handle_command` method
If not command, check to see if first word is a service or an author.
Default program is to send message replies. However, we will also
check to see if the second word is a command and handle approparitly
This method does simple string parsing and high level program control | [
"Check",
"to",
"see",
"if",
"text",
"is",
"a",
"command",
".",
"Otherwise",
"check",
"to",
"see",
"if",
"the",
"second",
"word",
"is",
"a",
"command",
"."
] | 9b844eb20e84eea92a0e7db7d86a90094956c38f | https://github.com/benhoff/vexbot/blob/9b844eb20e84eea92a0e7db7d86a90094956c38f/vexbot/adapters/shell/shell.py#L185-L239 | train | 34,428 |
benhoff/vexbot | vexbot/adapters/shell/shell.py | Shell._first_word_not_cmd | def _first_word_not_cmd(self,
first_word: str,
command: str,
args: tuple,
kwargs: dict) -> None:
"""
check to see if this is an author or service.
This method does high level control handling
"""
if self.service_interface.is_service(first_word):
self._logger.debug(' first word is a service')
kwargs = self.service_interface.get_metadata(first_word, kwargs)
self._logger.debug(' service transform kwargs: %s', kwargs)
elif self.author_interface.is_author(first_word):
self._logger.debug(' first word is an author')
kwargs = self.author_interface.get_metadata(first_word, kwargs)
self._logger.debug(' author transform kwargs: %s', kwargs)
if not kwargs.get('remote'):
kwargs['remote_command'] = command
command= 'REMOTE'
self.messaging.send_command(command, *args, **kwargs)
return
else:
self.messaging.send_command(command, *args, **kwargs) | python | def _first_word_not_cmd(self,
first_word: str,
command: str,
args: tuple,
kwargs: dict) -> None:
"""
check to see if this is an author or service.
This method does high level control handling
"""
if self.service_interface.is_service(first_word):
self._logger.debug(' first word is a service')
kwargs = self.service_interface.get_metadata(first_word, kwargs)
self._logger.debug(' service transform kwargs: %s', kwargs)
elif self.author_interface.is_author(first_word):
self._logger.debug(' first word is an author')
kwargs = self.author_interface.get_metadata(first_word, kwargs)
self._logger.debug(' author transform kwargs: %s', kwargs)
if not kwargs.get('remote'):
kwargs['remote_command'] = command
command= 'REMOTE'
self.messaging.send_command(command, *args, **kwargs)
return
else:
self.messaging.send_command(command, *args, **kwargs) | [
"def",
"_first_word_not_cmd",
"(",
"self",
",",
"first_word",
":",
"str",
",",
"command",
":",
"str",
",",
"args",
":",
"tuple",
",",
"kwargs",
":",
"dict",
")",
"->",
"None",
":",
"if",
"self",
".",
"service_interface",
".",
"is_service",
"(",
"first_wo... | check to see if this is an author or service.
This method does high level control handling | [
"check",
"to",
"see",
"if",
"this",
"is",
"an",
"author",
"or",
"service",
".",
"This",
"method",
"does",
"high",
"level",
"control",
"handling"
] | 9b844eb20e84eea92a0e7db7d86a90094956c38f | https://github.com/benhoff/vexbot/blob/9b844eb20e84eea92a0e7db7d86a90094956c38f/vexbot/adapters/shell/shell.py#L263-L286 | train | 34,429 |
benhoff/vexbot | vexbot/entity_extraction.py | EntityExtraction._sentence_to_features | def _sentence_to_features(self, sentence: list):
# type: (List[Tuple[Text, Text, Text, Text]]) -> List[Dict[Text, Any]]
"""Convert a word into discrete features in self.crf_features,
including word before and word after."""
sentence_features = []
prefixes = ('-1', '0', '+1')
for word_idx in range(len(sentence)):
# word before(-1), current word(0), next word(+1)
word_features = {}
for i in range(3):
if word_idx == len(sentence) - 1 and i == 2:
word_features['EOS'] = True
# End Of Sentence
elif word_idx == 0 and i == 0:
word_features['BOS'] = True
# Beginning Of Sentence
else:
word = sentence[word_idx - 1 + i]
prefix = prefixes[i]
features = self.crf_features[i]
for feature in features:
# append each feature to a feature vector
value = self.function_dict[feature](word)
word_features[prefix + ":" + feature] = value
sentence_features.append(word_features)
return sentence_features | python | def _sentence_to_features(self, sentence: list):
# type: (List[Tuple[Text, Text, Text, Text]]) -> List[Dict[Text, Any]]
"""Convert a word into discrete features in self.crf_features,
including word before and word after."""
sentence_features = []
prefixes = ('-1', '0', '+1')
for word_idx in range(len(sentence)):
# word before(-1), current word(0), next word(+1)
word_features = {}
for i in range(3):
if word_idx == len(sentence) - 1 and i == 2:
word_features['EOS'] = True
# End Of Sentence
elif word_idx == 0 and i == 0:
word_features['BOS'] = True
# Beginning Of Sentence
else:
word = sentence[word_idx - 1 + i]
prefix = prefixes[i]
features = self.crf_features[i]
for feature in features:
# append each feature to a feature vector
value = self.function_dict[feature](word)
word_features[prefix + ":" + feature] = value
sentence_features.append(word_features)
return sentence_features | [
"def",
"_sentence_to_features",
"(",
"self",
",",
"sentence",
":",
"list",
")",
":",
"# type: (List[Tuple[Text, Text, Text, Text]]) -> List[Dict[Text, Any]]",
"sentence_features",
"=",
"[",
"]",
"prefixes",
"=",
"(",
"'-1'",
",",
"'0'",
",",
"'+1'",
")",
"for",
"wor... | Convert a word into discrete features in self.crf_features,
including word before and word after. | [
"Convert",
"a",
"word",
"into",
"discrete",
"features",
"in",
"self",
".",
"crf_features",
"including",
"word",
"before",
"and",
"word",
"after",
"."
] | 9b844eb20e84eea92a0e7db7d86a90094956c38f | https://github.com/benhoff/vexbot/blob/9b844eb20e84eea92a0e7db7d86a90094956c38f/vexbot/entity_extraction.py#L70-L97 | train | 34,430 |
kblomqvist/yasha | yasha/yasha.py | find_template_companion | def find_template_companion(template, extension='', check=True):
"""
Returns the first found template companion file
"""
if check and not os.path.isfile(template):
yield ''
return # May be '<stdin>' (click)
template = os.path.abspath(template)
template_dirname = os.path.dirname(template)
template_basename = os.path.basename(template).split('.')
current_path = template_dirname
stop_path = os.path.commonprefix((os.getcwd(), current_path))
stop_path = os.path.dirname(stop_path)
token = template_basename[0] + '.'
while True:
for file in sorted(os.listdir(current_path)):
if not file.startswith(token):
continue
if not file.endswith(extension):
continue
file_parts = file.split('.')
for i in range(1, len(template_basename)):
if template_basename[:-i] != file_parts[:-1]:
continue
if current_path == template_dirname:
if file_parts == template_basename:
continue # Do not accept template itself
yield os.path.join(current_path, file)
if current_path == stop_path:
break
# cd ..
current_path = os.path.split(current_path)[0] | python | def find_template_companion(template, extension='', check=True):
"""
Returns the first found template companion file
"""
if check and not os.path.isfile(template):
yield ''
return # May be '<stdin>' (click)
template = os.path.abspath(template)
template_dirname = os.path.dirname(template)
template_basename = os.path.basename(template).split('.')
current_path = template_dirname
stop_path = os.path.commonprefix((os.getcwd(), current_path))
stop_path = os.path.dirname(stop_path)
token = template_basename[0] + '.'
while True:
for file in sorted(os.listdir(current_path)):
if not file.startswith(token):
continue
if not file.endswith(extension):
continue
file_parts = file.split('.')
for i in range(1, len(template_basename)):
if template_basename[:-i] != file_parts[:-1]:
continue
if current_path == template_dirname:
if file_parts == template_basename:
continue # Do not accept template itself
yield os.path.join(current_path, file)
if current_path == stop_path:
break
# cd ..
current_path = os.path.split(current_path)[0] | [
"def",
"find_template_companion",
"(",
"template",
",",
"extension",
"=",
"''",
",",
"check",
"=",
"True",
")",
":",
"if",
"check",
"and",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"template",
")",
":",
"yield",
"''",
"return",
"# May be '<stdin>' (cli... | Returns the first found template companion file | [
"Returns",
"the",
"first",
"found",
"template",
"companion",
"file"
] | aebda08f45458611a59497fb7505f0881b73fbd5 | https://github.com/kblomqvist/yasha/blob/aebda08f45458611a59497fb7505f0881b73fbd5/yasha/yasha.py#L35-L76 | train | 34,431 |
kblomqvist/yasha | yasha/cmsis.py | SvdElement.from_element | def from_element(self, element, defaults={}):
"""Populate object variables from SVD element"""
if isinstance(defaults, SvdElement):
defaults = vars(defaults)
for key in self.props:
try:
value = element.find(key).text
except AttributeError: # Maybe it's attribute?
default = defaults[key] if key in defaults else None
value = element.get(key, default)
if value is not None:
if key in self.props_to_integer:
try:
value = int(value)
except ValueError: # It has to be hex
value = int(value, 16)
elif key in self.props_to_boolean:
value = value.lower() in ("yes", "true", "t", "1")
setattr(self, key, value) | python | def from_element(self, element, defaults={}):
"""Populate object variables from SVD element"""
if isinstance(defaults, SvdElement):
defaults = vars(defaults)
for key in self.props:
try:
value = element.find(key).text
except AttributeError: # Maybe it's attribute?
default = defaults[key] if key in defaults else None
value = element.get(key, default)
if value is not None:
if key in self.props_to_integer:
try:
value = int(value)
except ValueError: # It has to be hex
value = int(value, 16)
elif key in self.props_to_boolean:
value = value.lower() in ("yes", "true", "t", "1")
setattr(self, key, value) | [
"def",
"from_element",
"(",
"self",
",",
"element",
",",
"defaults",
"=",
"{",
"}",
")",
":",
"if",
"isinstance",
"(",
"defaults",
",",
"SvdElement",
")",
":",
"defaults",
"=",
"vars",
"(",
"defaults",
")",
"for",
"key",
"in",
"self",
".",
"props",
"... | Populate object variables from SVD element | [
"Populate",
"object",
"variables",
"from",
"SVD",
"element"
] | aebda08f45458611a59497fb7505f0881b73fbd5 | https://github.com/kblomqvist/yasha/blob/aebda08f45458611a59497fb7505f0881b73fbd5/yasha/cmsis.py#L75-L94 | train | 34,432 |
kblomqvist/yasha | yasha/cmsis.py | SvdRegister.fold | def fold(self):
"""Folds the Register in accordance with it's dimensions.
If the register is dimensionless, the returned list just
contains the register itself unchanged. In case the register
name looks like a C array, the returned list contains the register
itself, where nothing else than the '%s' placeholder in it's name
has been replaced with value of the dim element.
"""
if self.dim is None:
return [self]
if self.name.endswith("[%s]"): # C array like
self.name = self.name.replace("%s", str(self.dim))
return [self]
registers = []
for offset, index in enumerate(self.dimIndex):
reg = self.copy()
reg.name = self.name.replace("%s", str(index))
reg.addressOffset += offset * reg.dimIncrement
reg.fields = [field.copy() for field in reg.fields]
for field in reg.fields:
field.parent = reg
reg.dim = reg.dimIndex = reg.dimIncrement = None # Dimensionless
registers.append(reg)
return registers | python | def fold(self):
"""Folds the Register in accordance with it's dimensions.
If the register is dimensionless, the returned list just
contains the register itself unchanged. In case the register
name looks like a C array, the returned list contains the register
itself, where nothing else than the '%s' placeholder in it's name
has been replaced with value of the dim element.
"""
if self.dim is None:
return [self]
if self.name.endswith("[%s]"): # C array like
self.name = self.name.replace("%s", str(self.dim))
return [self]
registers = []
for offset, index in enumerate(self.dimIndex):
reg = self.copy()
reg.name = self.name.replace("%s", str(index))
reg.addressOffset += offset * reg.dimIncrement
reg.fields = [field.copy() for field in reg.fields]
for field in reg.fields:
field.parent = reg
reg.dim = reg.dimIndex = reg.dimIncrement = None # Dimensionless
registers.append(reg)
return registers | [
"def",
"fold",
"(",
"self",
")",
":",
"if",
"self",
".",
"dim",
"is",
"None",
":",
"return",
"[",
"self",
"]",
"if",
"self",
".",
"name",
".",
"endswith",
"(",
"\"[%s]\"",
")",
":",
"# C array like",
"self",
".",
"name",
"=",
"self",
".",
"name",
... | Folds the Register in accordance with it's dimensions.
If the register is dimensionless, the returned list just
contains the register itself unchanged. In case the register
name looks like a C array, the returned list contains the register
itself, where nothing else than the '%s' placeholder in it's name
has been replaced with value of the dim element. | [
"Folds",
"the",
"Register",
"in",
"accordance",
"with",
"it",
"s",
"dimensions",
"."
] | aebda08f45458611a59497fb7505f0881b73fbd5 | https://github.com/kblomqvist/yasha/blob/aebda08f45458611a59497fb7505f0881b73fbd5/yasha/cmsis.py#L240-L268 | train | 34,433 |
thombashi/tcconfig | tcconfig/traffic_control.py | TrafficControl.get_tc_device | def get_tc_device(self):
"""
Return a device name that associated network communication direction.
"""
if self.direction == TrafficDirection.OUTGOING:
return self.device
if self.direction == TrafficDirection.INCOMING:
return self.ifb_device
raise ParameterError(
"unknown direction", expected=TrafficDirection.LIST, value=self.direction
) | python | def get_tc_device(self):
"""
Return a device name that associated network communication direction.
"""
if self.direction == TrafficDirection.OUTGOING:
return self.device
if self.direction == TrafficDirection.INCOMING:
return self.ifb_device
raise ParameterError(
"unknown direction", expected=TrafficDirection.LIST, value=self.direction
) | [
"def",
"get_tc_device",
"(",
"self",
")",
":",
"if",
"self",
".",
"direction",
"==",
"TrafficDirection",
".",
"OUTGOING",
":",
"return",
"self",
".",
"device",
"if",
"self",
".",
"direction",
"==",
"TrafficDirection",
".",
"INCOMING",
":",
"return",
"self",
... | Return a device name that associated network communication direction. | [
"Return",
"a",
"device",
"name",
"that",
"associated",
"network",
"communication",
"direction",
"."
] | 9612dcd6ac9c072e7aa9eb702a225c559936bad3 | https://github.com/thombashi/tcconfig/blob/9612dcd6ac9c072e7aa9eb702a225c559936bad3/tcconfig/traffic_control.py#L213-L226 | train | 34,434 |
thombashi/tcconfig | tcconfig/traffic_control.py | TrafficControl.delete_tc | def delete_tc(self):
"""
Delete a specific shaping rule.
"""
rule_finder = TcShapingRuleFinder(logger=logger, tc=self)
filter_param = rule_finder.find_filter_param()
if not filter_param:
message = "shaping rule not found ({}).".format(rule_finder.get_filter_string())
if rule_finder.is_empty_filter_condition():
message += " you can delete all of the shaping rules with --all option."
logger.error(message)
return 1
logger.info("delete a shaping rule: {}".format(dict(filter_param)))
filter_del_command = (
"{command:s} del dev {dev:s} protocol {protocol:s} "
"parent {parent:} handle {handle:s} prio {prio:} u32".format(
command=get_tc_base_command(TcSubCommand.FILTER),
dev=rule_finder.get_parsed_device(),
protocol=filter_param.get(Tc.Param.PROTOCOL),
parent="{:s}:".format(rule_finder.find_parent().split(":")[0]),
handle=filter_param.get(Tc.Param.FILTER_ID),
prio=filter_param.get(Tc.Param.PRIORITY),
)
)
result = run_command_helper(
command=filter_del_command, ignore_error_msg_regexp=None, notice_msg=None
)
rule_finder.clear()
if not rule_finder.is_any_filter():
logger.debug("there are no filters remain. delete qdiscs.")
self.delete_all_tc()
return result | python | def delete_tc(self):
"""
Delete a specific shaping rule.
"""
rule_finder = TcShapingRuleFinder(logger=logger, tc=self)
filter_param = rule_finder.find_filter_param()
if not filter_param:
message = "shaping rule not found ({}).".format(rule_finder.get_filter_string())
if rule_finder.is_empty_filter_condition():
message += " you can delete all of the shaping rules with --all option."
logger.error(message)
return 1
logger.info("delete a shaping rule: {}".format(dict(filter_param)))
filter_del_command = (
"{command:s} del dev {dev:s} protocol {protocol:s} "
"parent {parent:} handle {handle:s} prio {prio:} u32".format(
command=get_tc_base_command(TcSubCommand.FILTER),
dev=rule_finder.get_parsed_device(),
protocol=filter_param.get(Tc.Param.PROTOCOL),
parent="{:s}:".format(rule_finder.find_parent().split(":")[0]),
handle=filter_param.get(Tc.Param.FILTER_ID),
prio=filter_param.get(Tc.Param.PRIORITY),
)
)
result = run_command_helper(
command=filter_del_command, ignore_error_msg_regexp=None, notice_msg=None
)
rule_finder.clear()
if not rule_finder.is_any_filter():
logger.debug("there are no filters remain. delete qdiscs.")
self.delete_all_tc()
return result | [
"def",
"delete_tc",
"(",
"self",
")",
":",
"rule_finder",
"=",
"TcShapingRuleFinder",
"(",
"logger",
"=",
"logger",
",",
"tc",
"=",
"self",
")",
"filter_param",
"=",
"rule_finder",
".",
"find_filter_param",
"(",
")",
"if",
"not",
"filter_param",
":",
"messag... | Delete a specific shaping rule. | [
"Delete",
"a",
"specific",
"shaping",
"rule",
"."
] | 9612dcd6ac9c072e7aa9eb702a225c559936bad3 | https://github.com/thombashi/tcconfig/blob/9612dcd6ac9c072e7aa9eb702a225c559936bad3/tcconfig/traffic_control.py#L308-L347 | train | 34,435 |
mcs07/PubChemPy | pubchempy.py | request | def request(identifier, namespace='cid', domain='compound', operation=None, output='JSON', searchtype=None, **kwargs):
"""
Construct API request from parameters and return the response.
Full specification at http://pubchem.ncbi.nlm.nih.gov/pug_rest/PUG_REST.html
"""
if not identifier:
raise ValueError('identifier/cid cannot be None')
# If identifier is a list, join with commas into string
if isinstance(identifier, int):
identifier = str(identifier)
if not isinstance(identifier, text_types):
identifier = ','.join(str(x) for x in identifier)
# Filter None values from kwargs
kwargs = dict((k, v) for k, v in kwargs.items() if v is not None)
# Build API URL
urlid, postdata = None, None
if namespace == 'sourceid':
identifier = identifier.replace('/', '.')
if namespace in ['listkey', 'formula', 'sourceid'] \
or searchtype == 'xref' \
or (searchtype and namespace == 'cid') or domain == 'sources':
urlid = quote(identifier.encode('utf8'))
else:
postdata = urlencode([(namespace, identifier)]).encode('utf8')
comps = filter(None, [API_BASE, domain, searchtype, namespace, urlid, operation, output])
apiurl = '/'.join(comps)
if kwargs:
apiurl += '?%s' % urlencode(kwargs)
# Make request
try:
log.debug('Request URL: %s', apiurl)
log.debug('Request data: %s', postdata)
response = urlopen(apiurl, postdata)
return response
except HTTPError as e:
raise PubChemHTTPError(e) | python | def request(identifier, namespace='cid', domain='compound', operation=None, output='JSON', searchtype=None, **kwargs):
"""
Construct API request from parameters and return the response.
Full specification at http://pubchem.ncbi.nlm.nih.gov/pug_rest/PUG_REST.html
"""
if not identifier:
raise ValueError('identifier/cid cannot be None')
# If identifier is a list, join with commas into string
if isinstance(identifier, int):
identifier = str(identifier)
if not isinstance(identifier, text_types):
identifier = ','.join(str(x) for x in identifier)
# Filter None values from kwargs
kwargs = dict((k, v) for k, v in kwargs.items() if v is not None)
# Build API URL
urlid, postdata = None, None
if namespace == 'sourceid':
identifier = identifier.replace('/', '.')
if namespace in ['listkey', 'formula', 'sourceid'] \
or searchtype == 'xref' \
or (searchtype and namespace == 'cid') or domain == 'sources':
urlid = quote(identifier.encode('utf8'))
else:
postdata = urlencode([(namespace, identifier)]).encode('utf8')
comps = filter(None, [API_BASE, domain, searchtype, namespace, urlid, operation, output])
apiurl = '/'.join(comps)
if kwargs:
apiurl += '?%s' % urlencode(kwargs)
# Make request
try:
log.debug('Request URL: %s', apiurl)
log.debug('Request data: %s', postdata)
response = urlopen(apiurl, postdata)
return response
except HTTPError as e:
raise PubChemHTTPError(e) | [
"def",
"request",
"(",
"identifier",
",",
"namespace",
"=",
"'cid'",
",",
"domain",
"=",
"'compound'",
",",
"operation",
"=",
"None",
",",
"output",
"=",
"'JSON'",
",",
"searchtype",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"identif... | Construct API request from parameters and return the response.
Full specification at http://pubchem.ncbi.nlm.nih.gov/pug_rest/PUG_REST.html | [
"Construct",
"API",
"request",
"from",
"parameters",
"and",
"return",
"the",
"response",
"."
] | e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e | https://github.com/mcs07/PubChemPy/blob/e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e/pubchempy.py#L238-L274 | train | 34,436 |
mcs07/PubChemPy | pubchempy.py | get | def get(identifier, namespace='cid', domain='compound', operation=None, output='JSON', searchtype=None, **kwargs):
"""Request wrapper that automatically handles async requests."""
if (searchtype and searchtype != 'xref') or namespace in ['formula']:
response = request(identifier, namespace, domain, None, 'JSON', searchtype, **kwargs).read()
status = json.loads(response.decode())
if 'Waiting' in status and 'ListKey' in status['Waiting']:
identifier = status['Waiting']['ListKey']
namespace = 'listkey'
while 'Waiting' in status and 'ListKey' in status['Waiting']:
time.sleep(2)
response = request(identifier, namespace, domain, operation, 'JSON', **kwargs).read()
status = json.loads(response.decode())
if not output == 'JSON':
response = request(identifier, namespace, domain, operation, output, searchtype, **kwargs).read()
else:
response = request(identifier, namespace, domain, operation, output, searchtype, **kwargs).read()
return response | python | def get(identifier, namespace='cid', domain='compound', operation=None, output='JSON', searchtype=None, **kwargs):
"""Request wrapper that automatically handles async requests."""
if (searchtype and searchtype != 'xref') or namespace in ['formula']:
response = request(identifier, namespace, domain, None, 'JSON', searchtype, **kwargs).read()
status = json.loads(response.decode())
if 'Waiting' in status and 'ListKey' in status['Waiting']:
identifier = status['Waiting']['ListKey']
namespace = 'listkey'
while 'Waiting' in status and 'ListKey' in status['Waiting']:
time.sleep(2)
response = request(identifier, namespace, domain, operation, 'JSON', **kwargs).read()
status = json.loads(response.decode())
if not output == 'JSON':
response = request(identifier, namespace, domain, operation, output, searchtype, **kwargs).read()
else:
response = request(identifier, namespace, domain, operation, output, searchtype, **kwargs).read()
return response | [
"def",
"get",
"(",
"identifier",
",",
"namespace",
"=",
"'cid'",
",",
"domain",
"=",
"'compound'",
",",
"operation",
"=",
"None",
",",
"output",
"=",
"'JSON'",
",",
"searchtype",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"(",
"searchtype",
... | Request wrapper that automatically handles async requests. | [
"Request",
"wrapper",
"that",
"automatically",
"handles",
"async",
"requests",
"."
] | e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e | https://github.com/mcs07/PubChemPy/blob/e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e/pubchempy.py#L277-L293 | train | 34,437 |
mcs07/PubChemPy | pubchempy.py | get_json | def get_json(identifier, namespace='cid', domain='compound', operation=None, searchtype=None, **kwargs):
"""Request wrapper that automatically parses JSON response and supresses NotFoundError."""
try:
return json.loads(get(identifier, namespace, domain, operation, 'JSON', searchtype, **kwargs).decode())
except NotFoundError as e:
log.info(e)
return None | python | def get_json(identifier, namespace='cid', domain='compound', operation=None, searchtype=None, **kwargs):
"""Request wrapper that automatically parses JSON response and supresses NotFoundError."""
try:
return json.loads(get(identifier, namespace, domain, operation, 'JSON', searchtype, **kwargs).decode())
except NotFoundError as e:
log.info(e)
return None | [
"def",
"get_json",
"(",
"identifier",
",",
"namespace",
"=",
"'cid'",
",",
"domain",
"=",
"'compound'",
",",
"operation",
"=",
"None",
",",
"searchtype",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"json",
".",
"loads",
"(",
... | Request wrapper that automatically parses JSON response and supresses NotFoundError. | [
"Request",
"wrapper",
"that",
"automatically",
"parses",
"JSON",
"response",
"and",
"supresses",
"NotFoundError",
"."
] | e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e | https://github.com/mcs07/PubChemPy/blob/e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e/pubchempy.py#L296-L302 | train | 34,438 |
mcs07/PubChemPy | pubchempy.py | get_sdf | def get_sdf(identifier, namespace='cid', domain='compound',operation=None, searchtype=None, **kwargs):
"""Request wrapper that automatically parses SDF response and supresses NotFoundError."""
try:
return get(identifier, namespace, domain, operation, 'SDF', searchtype, **kwargs).decode()
except NotFoundError as e:
log.info(e)
return None | python | def get_sdf(identifier, namespace='cid', domain='compound',operation=None, searchtype=None, **kwargs):
"""Request wrapper that automatically parses SDF response and supresses NotFoundError."""
try:
return get(identifier, namespace, domain, operation, 'SDF', searchtype, **kwargs).decode()
except NotFoundError as e:
log.info(e)
return None | [
"def",
"get_sdf",
"(",
"identifier",
",",
"namespace",
"=",
"'cid'",
",",
"domain",
"=",
"'compound'",
",",
"operation",
"=",
"None",
",",
"searchtype",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"get",
"(",
"identifier",
","... | Request wrapper that automatically parses SDF response and supresses NotFoundError. | [
"Request",
"wrapper",
"that",
"automatically",
"parses",
"SDF",
"response",
"and",
"supresses",
"NotFoundError",
"."
] | e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e | https://github.com/mcs07/PubChemPy/blob/e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e/pubchempy.py#L304-L310 | train | 34,439 |
mcs07/PubChemPy | pubchempy.py | get_compounds | def get_compounds(identifier, namespace='cid', searchtype=None, as_dataframe=False, **kwargs):
"""Retrieve the specified compound records from PubChem.
:param identifier: The compound identifier to use as a search query.
:param namespace: (optional) The identifier type, one of cid, name, smiles, sdf, inchi, inchikey or formula.
:param searchtype: (optional) The advanced search type, one of substructure, superstructure or similarity.
:param as_dataframe: (optional) Automatically extract the :class:`~pubchempy.Compound` properties into a pandas
:class:`~pandas.DataFrame` and return that.
"""
results = get_json(identifier, namespace, searchtype=searchtype, **kwargs)
compounds = [Compound(r) for r in results['PC_Compounds']] if results else []
if as_dataframe:
return compounds_to_frame(compounds)
return compounds | python | def get_compounds(identifier, namespace='cid', searchtype=None, as_dataframe=False, **kwargs):
"""Retrieve the specified compound records from PubChem.
:param identifier: The compound identifier to use as a search query.
:param namespace: (optional) The identifier type, one of cid, name, smiles, sdf, inchi, inchikey or formula.
:param searchtype: (optional) The advanced search type, one of substructure, superstructure or similarity.
:param as_dataframe: (optional) Automatically extract the :class:`~pubchempy.Compound` properties into a pandas
:class:`~pandas.DataFrame` and return that.
"""
results = get_json(identifier, namespace, searchtype=searchtype, **kwargs)
compounds = [Compound(r) for r in results['PC_Compounds']] if results else []
if as_dataframe:
return compounds_to_frame(compounds)
return compounds | [
"def",
"get_compounds",
"(",
"identifier",
",",
"namespace",
"=",
"'cid'",
",",
"searchtype",
"=",
"None",
",",
"as_dataframe",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"results",
"=",
"get_json",
"(",
"identifier",
",",
"namespace",
",",
"searchty... | Retrieve the specified compound records from PubChem.
:param identifier: The compound identifier to use as a search query.
:param namespace: (optional) The identifier type, one of cid, name, smiles, sdf, inchi, inchikey or formula.
:param searchtype: (optional) The advanced search type, one of substructure, superstructure or similarity.
:param as_dataframe: (optional) Automatically extract the :class:`~pubchempy.Compound` properties into a pandas
:class:`~pandas.DataFrame` and return that. | [
"Retrieve",
"the",
"specified",
"compound",
"records",
"from",
"PubChem",
"."
] | e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e | https://github.com/mcs07/PubChemPy/blob/e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e/pubchempy.py#L312-L325 | train | 34,440 |
mcs07/PubChemPy | pubchempy.py | get_substances | def get_substances(identifier, namespace='sid', as_dataframe=False, **kwargs):
"""Retrieve the specified substance records from PubChem.
:param identifier: The substance identifier to use as a search query.
:param namespace: (optional) The identifier type, one of sid, name or sourceid/<source name>.
:param as_dataframe: (optional) Automatically extract the :class:`~pubchempy.Substance` properties into a pandas
:class:`~pandas.DataFrame` and return that.
"""
results = get_json(identifier, namespace, 'substance', **kwargs)
substances = [Substance(r) for r in results['PC_Substances']] if results else []
if as_dataframe:
return substances_to_frame(substances)
return substances | python | def get_substances(identifier, namespace='sid', as_dataframe=False, **kwargs):
"""Retrieve the specified substance records from PubChem.
:param identifier: The substance identifier to use as a search query.
:param namespace: (optional) The identifier type, one of sid, name or sourceid/<source name>.
:param as_dataframe: (optional) Automatically extract the :class:`~pubchempy.Substance` properties into a pandas
:class:`~pandas.DataFrame` and return that.
"""
results = get_json(identifier, namespace, 'substance', **kwargs)
substances = [Substance(r) for r in results['PC_Substances']] if results else []
if as_dataframe:
return substances_to_frame(substances)
return substances | [
"def",
"get_substances",
"(",
"identifier",
",",
"namespace",
"=",
"'sid'",
",",
"as_dataframe",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"results",
"=",
"get_json",
"(",
"identifier",
",",
"namespace",
",",
"'substance'",
",",
"*",
"*",
"kwargs",
... | Retrieve the specified substance records from PubChem.
:param identifier: The substance identifier to use as a search query.
:param namespace: (optional) The identifier type, one of sid, name or sourceid/<source name>.
:param as_dataframe: (optional) Automatically extract the :class:`~pubchempy.Substance` properties into a pandas
:class:`~pandas.DataFrame` and return that. | [
"Retrieve",
"the",
"specified",
"substance",
"records",
"from",
"PubChem",
"."
] | e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e | https://github.com/mcs07/PubChemPy/blob/e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e/pubchempy.py#L328-L340 | train | 34,441 |
mcs07/PubChemPy | pubchempy.py | get_assays | def get_assays(identifier, namespace='aid', **kwargs):
"""Retrieve the specified assay records from PubChem.
:param identifier: The assay identifier to use as a search query.
:param namespace: (optional) The identifier type.
"""
results = get_json(identifier, namespace, 'assay', 'description', **kwargs)
return [Assay(r) for r in results['PC_AssayContainer']] if results else [] | python | def get_assays(identifier, namespace='aid', **kwargs):
"""Retrieve the specified assay records from PubChem.
:param identifier: The assay identifier to use as a search query.
:param namespace: (optional) The identifier type.
"""
results = get_json(identifier, namespace, 'assay', 'description', **kwargs)
return [Assay(r) for r in results['PC_AssayContainer']] if results else [] | [
"def",
"get_assays",
"(",
"identifier",
",",
"namespace",
"=",
"'aid'",
",",
"*",
"*",
"kwargs",
")",
":",
"results",
"=",
"get_json",
"(",
"identifier",
",",
"namespace",
",",
"'assay'",
",",
"'description'",
",",
"*",
"*",
"kwargs",
")",
"return",
"[",... | Retrieve the specified assay records from PubChem.
:param identifier: The assay identifier to use as a search query.
:param namespace: (optional) The identifier type. | [
"Retrieve",
"the",
"specified",
"assay",
"records",
"from",
"PubChem",
"."
] | e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e | https://github.com/mcs07/PubChemPy/blob/e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e/pubchempy.py#L343-L350 | train | 34,442 |
mcs07/PubChemPy | pubchempy.py | get_properties | def get_properties(properties, identifier, namespace='cid', searchtype=None, as_dataframe=False, **kwargs):
"""Retrieve the specified properties from PubChem.
:param identifier: The compound, substance or assay identifier to use as a search query.
:param namespace: (optional) The identifier type.
:param searchtype: (optional) The advanced search type, one of substructure, superstructure or similarity.
:param as_dataframe: (optional) Automatically extract the properties into a pandas :class:`~pandas.DataFrame`.
"""
if isinstance(properties, text_types):
properties = properties.split(',')
properties = ','.join([PROPERTY_MAP.get(p, p) for p in properties])
properties = 'property/%s' % properties
results = get_json(identifier, namespace, 'compound', properties, searchtype=searchtype, **kwargs)
results = results['PropertyTable']['Properties'] if results else []
if as_dataframe:
import pandas as pd
return pd.DataFrame.from_records(results, index='CID')
return results | python | def get_properties(properties, identifier, namespace='cid', searchtype=None, as_dataframe=False, **kwargs):
"""Retrieve the specified properties from PubChem.
:param identifier: The compound, substance or assay identifier to use as a search query.
:param namespace: (optional) The identifier type.
:param searchtype: (optional) The advanced search type, one of substructure, superstructure or similarity.
:param as_dataframe: (optional) Automatically extract the properties into a pandas :class:`~pandas.DataFrame`.
"""
if isinstance(properties, text_types):
properties = properties.split(',')
properties = ','.join([PROPERTY_MAP.get(p, p) for p in properties])
properties = 'property/%s' % properties
results = get_json(identifier, namespace, 'compound', properties, searchtype=searchtype, **kwargs)
results = results['PropertyTable']['Properties'] if results else []
if as_dataframe:
import pandas as pd
return pd.DataFrame.from_records(results, index='CID')
return results | [
"def",
"get_properties",
"(",
"properties",
",",
"identifier",
",",
"namespace",
"=",
"'cid'",
",",
"searchtype",
"=",
"None",
",",
"as_dataframe",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"properties",
",",
"text_types",
"... | Retrieve the specified properties from PubChem.
:param identifier: The compound, substance or assay identifier to use as a search query.
:param namespace: (optional) The identifier type.
:param searchtype: (optional) The advanced search type, one of substructure, superstructure or similarity.
:param as_dataframe: (optional) Automatically extract the properties into a pandas :class:`~pandas.DataFrame`. | [
"Retrieve",
"the",
"specified",
"properties",
"from",
"PubChem",
"."
] | e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e | https://github.com/mcs07/PubChemPy/blob/e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e/pubchempy.py#L398-L415 | train | 34,443 |
mcs07/PubChemPy | pubchempy.py | deprecated | def deprecated(message=None):
"""Decorator to mark functions as deprecated. A warning will be emitted when the function is used."""
def deco(func):
@functools.wraps(func)
def wrapped(*args, **kwargs):
warnings.warn(
message or 'Call to deprecated function {}'.format(func.__name__),
category=PubChemPyDeprecationWarning,
stacklevel=2
)
return func(*args, **kwargs)
return wrapped
return deco | python | def deprecated(message=None):
"""Decorator to mark functions as deprecated. A warning will be emitted when the function is used."""
def deco(func):
@functools.wraps(func)
def wrapped(*args, **kwargs):
warnings.warn(
message or 'Call to deprecated function {}'.format(func.__name__),
category=PubChemPyDeprecationWarning,
stacklevel=2
)
return func(*args, **kwargs)
return wrapped
return deco | [
"def",
"deprecated",
"(",
"message",
"=",
"None",
")",
":",
"def",
"deco",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"warnings",
".",
"warn",
"(... | Decorator to mark functions as deprecated. A warning will be emitted when the function is used. | [
"Decorator",
"to",
"mark",
"functions",
"as",
"deprecated",
".",
"A",
"warning",
"will",
"be",
"emitted",
"when",
"the",
"function",
"is",
"used",
"."
] | e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e | https://github.com/mcs07/PubChemPy/blob/e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e/pubchempy.py#L485-L497 | train | 34,444 |
mcs07/PubChemPy | pubchempy.py | _parse_prop | def _parse_prop(search, proplist):
"""Extract property value from record using the given urn search filter."""
props = [i for i in proplist if all(item in i['urn'].items() for item in search.items())]
if len(props) > 0:
return props[0]['value'][list(props[0]['value'].keys())[0]] | python | def _parse_prop(search, proplist):
"""Extract property value from record using the given urn search filter."""
props = [i for i in proplist if all(item in i['urn'].items() for item in search.items())]
if len(props) > 0:
return props[0]['value'][list(props[0]['value'].keys())[0]] | [
"def",
"_parse_prop",
"(",
"search",
",",
"proplist",
")",
":",
"props",
"=",
"[",
"i",
"for",
"i",
"in",
"proplist",
"if",
"all",
"(",
"item",
"in",
"i",
"[",
"'urn'",
"]",
".",
"items",
"(",
")",
"for",
"item",
"in",
"search",
".",
"items",
"("... | Extract property value from record using the given urn search filter. | [
"Extract",
"property",
"value",
"from",
"record",
"using",
"the",
"given",
"urn",
"search",
"filter",
"."
] | e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e | https://github.com/mcs07/PubChemPy/blob/e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e/pubchempy.py#L1027-L1031 | train | 34,445 |
mcs07/PubChemPy | pubchempy.py | Atom.to_dict | def to_dict(self):
"""Return a dictionary containing Atom data."""
data = {'aid': self.aid, 'number': self.number, 'element': self.element}
for coord in {'x', 'y', 'z'}:
if getattr(self, coord) is not None:
data[coord] = getattr(self, coord)
if self.charge is not 0:
data['charge'] = self.charge
return data | python | def to_dict(self):
"""Return a dictionary containing Atom data."""
data = {'aid': self.aid, 'number': self.number, 'element': self.element}
for coord in {'x', 'y', 'z'}:
if getattr(self, coord) is not None:
data[coord] = getattr(self, coord)
if self.charge is not 0:
data['charge'] = self.charge
return data | [
"def",
"to_dict",
"(",
"self",
")",
":",
"data",
"=",
"{",
"'aid'",
":",
"self",
".",
"aid",
",",
"'number'",
":",
"self",
".",
"number",
",",
"'element'",
":",
"self",
".",
"element",
"}",
"for",
"coord",
"in",
"{",
"'x'",
",",
"'y'",
",",
"'z'"... | Return a dictionary containing Atom data. | [
"Return",
"a",
"dictionary",
"containing",
"Atom",
"data",
"."
] | e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e | https://github.com/mcs07/PubChemPy/blob/e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e/pubchempy.py#L557-L565 | train | 34,446 |
mcs07/PubChemPy | pubchempy.py | Atom.set_coordinates | def set_coordinates(self, x, y, z=None):
"""Set all coordinate dimensions at once."""
self.x = x
self.y = y
self.z = z | python | def set_coordinates(self, x, y, z=None):
"""Set all coordinate dimensions at once."""
self.x = x
self.y = y
self.z = z | [
"def",
"set_coordinates",
"(",
"self",
",",
"x",
",",
"y",
",",
"z",
"=",
"None",
")",
":",
"self",
".",
"x",
"=",
"x",
"self",
".",
"y",
"=",
"y",
"self",
".",
"z",
"=",
"z"
] | Set all coordinate dimensions at once. | [
"Set",
"all",
"coordinate",
"dimensions",
"at",
"once",
"."
] | e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e | https://github.com/mcs07/PubChemPy/blob/e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e/pubchempy.py#L567-L571 | train | 34,447 |
mcs07/PubChemPy | pubchempy.py | Bond.to_dict | def to_dict(self):
"""Return a dictionary containing Bond data."""
data = {'aid1': self.aid1, 'aid2': self.aid2, 'order': self.order}
if self.style is not None:
data['style'] = self.style
return data | python | def to_dict(self):
"""Return a dictionary containing Bond data."""
data = {'aid1': self.aid1, 'aid2': self.aid2, 'order': self.order}
if self.style is not None:
data['style'] = self.style
return data | [
"def",
"to_dict",
"(",
"self",
")",
":",
"data",
"=",
"{",
"'aid1'",
":",
"self",
".",
"aid1",
",",
"'aid2'",
":",
"self",
".",
"aid2",
",",
"'order'",
":",
"self",
".",
"order",
"}",
"if",
"self",
".",
"style",
"is",
"not",
"None",
":",
"data",
... | Return a dictionary containing Bond data. | [
"Return",
"a",
"dictionary",
"containing",
"Bond",
"data",
"."
] | e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e | https://github.com/mcs07/PubChemPy/blob/e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e/pubchempy.py#L631-L636 | train | 34,448 |
mcs07/PubChemPy | pubchempy.py | Compound._setup_atoms | def _setup_atoms(self):
"""Derive Atom objects from the record."""
# Delete existing atoms
self._atoms = {}
# Create atoms
aids = self.record['atoms']['aid']
elements = self.record['atoms']['element']
if not len(aids) == len(elements):
raise ResponseParseError('Error parsing atom elements')
for aid, element in zip(aids, elements):
self._atoms[aid] = Atom(aid=aid, number=element)
# Add coordinates
if 'coords' in self.record:
coord_ids = self.record['coords'][0]['aid']
xs = self.record['coords'][0]['conformers'][0]['x']
ys = self.record['coords'][0]['conformers'][0]['y']
zs = self.record['coords'][0]['conformers'][0].get('z', [])
if not len(coord_ids) == len(xs) == len(ys) == len(self._atoms) or (zs and not len(zs) == len(coord_ids)):
raise ResponseParseError('Error parsing atom coordinates')
for aid, x, y, z in zip_longest(coord_ids, xs, ys, zs):
self._atoms[aid].set_coordinates(x, y, z)
# Add charges
if 'charge' in self.record['atoms']:
for charge in self.record['atoms']['charge']:
self._atoms[charge['aid']].charge = charge['value'] | python | def _setup_atoms(self):
"""Derive Atom objects from the record."""
# Delete existing atoms
self._atoms = {}
# Create atoms
aids = self.record['atoms']['aid']
elements = self.record['atoms']['element']
if not len(aids) == len(elements):
raise ResponseParseError('Error parsing atom elements')
for aid, element in zip(aids, elements):
self._atoms[aid] = Atom(aid=aid, number=element)
# Add coordinates
if 'coords' in self.record:
coord_ids = self.record['coords'][0]['aid']
xs = self.record['coords'][0]['conformers'][0]['x']
ys = self.record['coords'][0]['conformers'][0]['y']
zs = self.record['coords'][0]['conformers'][0].get('z', [])
if not len(coord_ids) == len(xs) == len(ys) == len(self._atoms) or (zs and not len(zs) == len(coord_ids)):
raise ResponseParseError('Error parsing atom coordinates')
for aid, x, y, z in zip_longest(coord_ids, xs, ys, zs):
self._atoms[aid].set_coordinates(x, y, z)
# Add charges
if 'charge' in self.record['atoms']:
for charge in self.record['atoms']['charge']:
self._atoms[charge['aid']].charge = charge['value'] | [
"def",
"_setup_atoms",
"(",
"self",
")",
":",
"# Delete existing atoms",
"self",
".",
"_atoms",
"=",
"{",
"}",
"# Create atoms",
"aids",
"=",
"self",
".",
"record",
"[",
"'atoms'",
"]",
"[",
"'aid'",
"]",
"elements",
"=",
"self",
".",
"record",
"[",
"'at... | Derive Atom objects from the record. | [
"Derive",
"Atom",
"objects",
"from",
"the",
"record",
"."
] | e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e | https://github.com/mcs07/PubChemPy/blob/e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e/pubchempy.py#L669-L693 | train | 34,449 |
mcs07/PubChemPy | pubchempy.py | Compound._setup_bonds | def _setup_bonds(self):
"""Derive Bond objects from the record."""
self._bonds = {}
if 'bonds' not in self.record:
return
# Create bonds
aid1s = self.record['bonds']['aid1']
aid2s = self.record['bonds']['aid2']
orders = self.record['bonds']['order']
if not len(aid1s) == len(aid2s) == len(orders):
raise ResponseParseError('Error parsing bonds')
for aid1, aid2, order in zip(aid1s, aid2s, orders):
self._bonds[frozenset((aid1, aid2))] = Bond(aid1=aid1, aid2=aid2, order=order)
# Add styles
if 'coords' in self.record and 'style' in self.record['coords'][0]['conformers'][0]:
aid1s = self.record['coords'][0]['conformers'][0]['style']['aid1']
aid2s = self.record['coords'][0]['conformers'][0]['style']['aid2']
styles = self.record['coords'][0]['conformers'][0]['style']['annotation']
for aid1, aid2, style in zip(aid1s, aid2s, styles):
self._bonds[frozenset((aid1, aid2))].style = style | python | def _setup_bonds(self):
"""Derive Bond objects from the record."""
self._bonds = {}
if 'bonds' not in self.record:
return
# Create bonds
aid1s = self.record['bonds']['aid1']
aid2s = self.record['bonds']['aid2']
orders = self.record['bonds']['order']
if not len(aid1s) == len(aid2s) == len(orders):
raise ResponseParseError('Error parsing bonds')
for aid1, aid2, order in zip(aid1s, aid2s, orders):
self._bonds[frozenset((aid1, aid2))] = Bond(aid1=aid1, aid2=aid2, order=order)
# Add styles
if 'coords' in self.record and 'style' in self.record['coords'][0]['conformers'][0]:
aid1s = self.record['coords'][0]['conformers'][0]['style']['aid1']
aid2s = self.record['coords'][0]['conformers'][0]['style']['aid2']
styles = self.record['coords'][0]['conformers'][0]['style']['annotation']
for aid1, aid2, style in zip(aid1s, aid2s, styles):
self._bonds[frozenset((aid1, aid2))].style = style | [
"def",
"_setup_bonds",
"(",
"self",
")",
":",
"self",
".",
"_bonds",
"=",
"{",
"}",
"if",
"'bonds'",
"not",
"in",
"self",
".",
"record",
":",
"return",
"# Create bonds",
"aid1s",
"=",
"self",
".",
"record",
"[",
"'bonds'",
"]",
"[",
"'aid1'",
"]",
"a... | Derive Bond objects from the record. | [
"Derive",
"Bond",
"objects",
"from",
"the",
"record",
"."
] | e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e | https://github.com/mcs07/PubChemPy/blob/e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e/pubchempy.py#L695-L714 | train | 34,450 |
mcs07/PubChemPy | pubchempy.py | Compound.from_cid | def from_cid(cls, cid, **kwargs):
"""Retrieve the Compound record for the specified CID.
Usage::
c = Compound.from_cid(6819)
:param int cid: The PubChem Compound Identifier (CID).
"""
record = json.loads(request(cid, **kwargs).read().decode())['PC_Compounds'][0]
return cls(record) | python | def from_cid(cls, cid, **kwargs):
"""Retrieve the Compound record for the specified CID.
Usage::
c = Compound.from_cid(6819)
:param int cid: The PubChem Compound Identifier (CID).
"""
record = json.loads(request(cid, **kwargs).read().decode())['PC_Compounds'][0]
return cls(record) | [
"def",
"from_cid",
"(",
"cls",
",",
"cid",
",",
"*",
"*",
"kwargs",
")",
":",
"record",
"=",
"json",
".",
"loads",
"(",
"request",
"(",
"cid",
",",
"*",
"*",
"kwargs",
")",
".",
"read",
"(",
")",
".",
"decode",
"(",
")",
")",
"[",
"'PC_Compound... | Retrieve the Compound record for the specified CID.
Usage::
c = Compound.from_cid(6819)
:param int cid: The PubChem Compound Identifier (CID). | [
"Retrieve",
"the",
"Compound",
"record",
"for",
"the",
"specified",
"CID",
"."
] | e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e | https://github.com/mcs07/PubChemPy/blob/e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e/pubchempy.py#L717-L727 | train | 34,451 |
mcs07/PubChemPy | pubchempy.py | Compound.to_dict | def to_dict(self, properties=None):
"""Return a dictionary containing Compound data. Optionally specify a list of the desired properties.
synonyms, aids and sids are not included unless explicitly specified using the properties parameter. This is
because they each require an extra request.
"""
if not properties:
skip = {'aids', 'sids', 'synonyms'}
properties = [p for p in dir(Compound) if isinstance(getattr(Compound, p), property) and p not in skip]
return {p: [i.to_dict() for i in getattr(self, p)] if p in {'atoms', 'bonds'} else getattr(self, p) for p in properties} | python | def to_dict(self, properties=None):
"""Return a dictionary containing Compound data. Optionally specify a list of the desired properties.
synonyms, aids and sids are not included unless explicitly specified using the properties parameter. This is
because they each require an extra request.
"""
if not properties:
skip = {'aids', 'sids', 'synonyms'}
properties = [p for p in dir(Compound) if isinstance(getattr(Compound, p), property) and p not in skip]
return {p: [i.to_dict() for i in getattr(self, p)] if p in {'atoms', 'bonds'} else getattr(self, p) for p in properties} | [
"def",
"to_dict",
"(",
"self",
",",
"properties",
"=",
"None",
")",
":",
"if",
"not",
"properties",
":",
"skip",
"=",
"{",
"'aids'",
",",
"'sids'",
",",
"'synonyms'",
"}",
"properties",
"=",
"[",
"p",
"for",
"p",
"in",
"dir",
"(",
"Compound",
")",
... | Return a dictionary containing Compound data. Optionally specify a list of the desired properties.
synonyms, aids and sids are not included unless explicitly specified using the properties parameter. This is
because they each require an extra request. | [
"Return",
"a",
"dictionary",
"containing",
"Compound",
"data",
".",
"Optionally",
"specify",
"a",
"list",
"of",
"the",
"desired",
"properties",
"."
] | e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e | https://github.com/mcs07/PubChemPy/blob/e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e/pubchempy.py#L735-L744 | train | 34,452 |
mcs07/PubChemPy | pubchempy.py | Compound.synonyms | def synonyms(self):
"""A ranked list of all the names associated with this Compound.
Requires an extra request. Result is cached.
"""
if self.cid:
results = get_json(self.cid, operation='synonyms')
return results['InformationList']['Information'][0]['Synonym'] if results else [] | python | def synonyms(self):
"""A ranked list of all the names associated with this Compound.
Requires an extra request. Result is cached.
"""
if self.cid:
results = get_json(self.cid, operation='synonyms')
return results['InformationList']['Information'][0]['Synonym'] if results else [] | [
"def",
"synonyms",
"(",
"self",
")",
":",
"if",
"self",
".",
"cid",
":",
"results",
"=",
"get_json",
"(",
"self",
".",
"cid",
",",
"operation",
"=",
"'synonyms'",
")",
"return",
"results",
"[",
"'InformationList'",
"]",
"[",
"'Information'",
"]",
"[",
... | A ranked list of all the names associated with this Compound.
Requires an extra request. Result is cached. | [
"A",
"ranked",
"list",
"of",
"all",
"the",
"names",
"associated",
"with",
"this",
"Compound",
"."
] | e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e | https://github.com/mcs07/PubChemPy/blob/e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e/pubchempy.py#L785-L792 | train | 34,453 |
mcs07/PubChemPy | pubchempy.py | Substance.from_sid | def from_sid(cls, sid):
"""Retrieve the Substance record for the specified SID.
:param int sid: The PubChem Substance Identifier (SID).
"""
record = json.loads(request(sid, 'sid', 'substance').read().decode())['PC_Substances'][0]
return cls(record) | python | def from_sid(cls, sid):
"""Retrieve the Substance record for the specified SID.
:param int sid: The PubChem Substance Identifier (SID).
"""
record = json.loads(request(sid, 'sid', 'substance').read().decode())['PC_Substances'][0]
return cls(record) | [
"def",
"from_sid",
"(",
"cls",
",",
"sid",
")",
":",
"record",
"=",
"json",
".",
"loads",
"(",
"request",
"(",
"sid",
",",
"'sid'",
",",
"'substance'",
")",
".",
"read",
"(",
")",
".",
"decode",
"(",
")",
")",
"[",
"'PC_Substances'",
"]",
"[",
"0... | Retrieve the Substance record for the specified SID.
:param int sid: The PubChem Substance Identifier (SID). | [
"Retrieve",
"the",
"Substance",
"record",
"for",
"the",
"specified",
"SID",
"."
] | e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e | https://github.com/mcs07/PubChemPy/blob/e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e/pubchempy.py#L1047-L1053 | train | 34,454 |
mcs07/PubChemPy | pubchempy.py | Substance.to_dict | def to_dict(self, properties=None):
"""Return a dictionary containing Substance data.
If the properties parameter is not specified, everything except cids and aids is included. This is because the
aids and cids properties each require an extra request to retrieve.
:param properties: (optional) A list of the desired properties.
"""
if not properties:
skip = {'deposited_compound', 'standardized_compound', 'cids', 'aids'}
properties = [p for p in dir(Substance) if isinstance(getattr(Substance, p), property) and p not in skip]
return {p: getattr(self, p) for p in properties} | python | def to_dict(self, properties=None):
"""Return a dictionary containing Substance data.
If the properties parameter is not specified, everything except cids and aids is included. This is because the
aids and cids properties each require an extra request to retrieve.
:param properties: (optional) A list of the desired properties.
"""
if not properties:
skip = {'deposited_compound', 'standardized_compound', 'cids', 'aids'}
properties = [p for p in dir(Substance) if isinstance(getattr(Substance, p), property) and p not in skip]
return {p: getattr(self, p) for p in properties} | [
"def",
"to_dict",
"(",
"self",
",",
"properties",
"=",
"None",
")",
":",
"if",
"not",
"properties",
":",
"skip",
"=",
"{",
"'deposited_compound'",
",",
"'standardized_compound'",
",",
"'cids'",
",",
"'aids'",
"}",
"properties",
"=",
"[",
"p",
"for",
"p",
... | Return a dictionary containing Substance data.
If the properties parameter is not specified, everything except cids and aids is included. This is because the
aids and cids properties each require an extra request to retrieve.
:param properties: (optional) A list of the desired properties. | [
"Return",
"a",
"dictionary",
"containing",
"Substance",
"data",
"."
] | e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e | https://github.com/mcs07/PubChemPy/blob/e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e/pubchempy.py#L1065-L1076 | train | 34,455 |
mcs07/PubChemPy | pubchempy.py | Assay.from_aid | def from_aid(cls, aid):
"""Retrieve the Assay record for the specified AID.
:param int aid: The PubChem Assay Identifier (AID).
"""
record = json.loads(request(aid, 'aid', 'assay', 'description').read().decode())['PC_AssayContainer'][0]
return cls(record) | python | def from_aid(cls, aid):
"""Retrieve the Assay record for the specified AID.
:param int aid: The PubChem Assay Identifier (AID).
"""
record = json.loads(request(aid, 'aid', 'assay', 'description').read().decode())['PC_AssayContainer'][0]
return cls(record) | [
"def",
"from_aid",
"(",
"cls",
",",
"aid",
")",
":",
"record",
"=",
"json",
".",
"loads",
"(",
"request",
"(",
"aid",
",",
"'aid'",
",",
"'assay'",
",",
"'description'",
")",
".",
"read",
"(",
")",
".",
"decode",
"(",
")",
")",
"[",
"'PC_AssayConta... | Retrieve the Assay record for the specified AID.
:param int aid: The PubChem Assay Identifier (AID). | [
"Retrieve",
"the",
"Assay",
"record",
"for",
"the",
"specified",
"AID",
"."
] | e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e | https://github.com/mcs07/PubChemPy/blob/e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e/pubchempy.py#L1160-L1166 | train | 34,456 |
mcs07/PubChemPy | pubchempy.py | Assay.to_dict | def to_dict(self, properties=None):
"""Return a dictionary containing Assay data.
If the properties parameter is not specified, everything is included.
:param properties: (optional) A list of the desired properties.
"""
if not properties:
properties = [p for p in dir(Assay) if isinstance(getattr(Assay, p), property)]
return {p: getattr(self, p) for p in properties} | python | def to_dict(self, properties=None):
"""Return a dictionary containing Assay data.
If the properties parameter is not specified, everything is included.
:param properties: (optional) A list of the desired properties.
"""
if not properties:
properties = [p for p in dir(Assay) if isinstance(getattr(Assay, p), property)]
return {p: getattr(self, p) for p in properties} | [
"def",
"to_dict",
"(",
"self",
",",
"properties",
"=",
"None",
")",
":",
"if",
"not",
"properties",
":",
"properties",
"=",
"[",
"p",
"for",
"p",
"in",
"dir",
"(",
"Assay",
")",
"if",
"isinstance",
"(",
"getattr",
"(",
"Assay",
",",
"p",
")",
",",
... | Return a dictionary containing Assay data.
If the properties parameter is not specified, everything is included.
:param properties: (optional) A list of the desired properties. | [
"Return",
"a",
"dictionary",
"containing",
"Assay",
"data",
"."
] | e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e | https://github.com/mcs07/PubChemPy/blob/e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e/pubchempy.py#L1178-L1187 | train | 34,457 |
tadeck/onetimepass | onetimepass/__init__.py | _is_possible_token | def _is_possible_token(token, token_length=6):
"""Determines if given value is acceptable as a token. Used when validating
tokens.
Currently allows only numeric tokens no longer than 6 chars.
:param token: token value to be checked
:type token: int or str
:param token_length: allowed length of token
:type token_length: int
:return: True if can be a candidate for token, False otherwise
:rtype: bool
>>> _is_possible_token(123456)
True
>>> _is_possible_token(b'123456')
True
>>> _is_possible_token(b'abcdef')
False
>>> _is_possible_token(b'12345678')
False
"""
if not isinstance(token, bytes):
token = six.b(str(token))
return token.isdigit() and len(token) <= token_length | python | def _is_possible_token(token, token_length=6):
"""Determines if given value is acceptable as a token. Used when validating
tokens.
Currently allows only numeric tokens no longer than 6 chars.
:param token: token value to be checked
:type token: int or str
:param token_length: allowed length of token
:type token_length: int
:return: True if can be a candidate for token, False otherwise
:rtype: bool
>>> _is_possible_token(123456)
True
>>> _is_possible_token(b'123456')
True
>>> _is_possible_token(b'abcdef')
False
>>> _is_possible_token(b'12345678')
False
"""
if not isinstance(token, bytes):
token = six.b(str(token))
return token.isdigit() and len(token) <= token_length | [
"def",
"_is_possible_token",
"(",
"token",
",",
"token_length",
"=",
"6",
")",
":",
"if",
"not",
"isinstance",
"(",
"token",
",",
"bytes",
")",
":",
"token",
"=",
"six",
".",
"b",
"(",
"str",
"(",
"token",
")",
")",
"return",
"token",
".",
"isdigit",... | Determines if given value is acceptable as a token. Used when validating
tokens.
Currently allows only numeric tokens no longer than 6 chars.
:param token: token value to be checked
:type token: int or str
:param token_length: allowed length of token
:type token_length: int
:return: True if can be a candidate for token, False otherwise
:rtype: bool
>>> _is_possible_token(123456)
True
>>> _is_possible_token(b'123456')
True
>>> _is_possible_token(b'abcdef')
False
>>> _is_possible_token(b'12345678')
False | [
"Determines",
"if",
"given",
"value",
"is",
"acceptable",
"as",
"a",
"token",
".",
"Used",
"when",
"validating",
"tokens",
"."
] | ee4b4e1700089757594a5ffee5f24408c864ad00 | https://github.com/tadeck/onetimepass/blob/ee4b4e1700089757594a5ffee5f24408c864ad00/onetimepass/__init__.py#L44-L68 | train | 34,458 |
tadeck/onetimepass | onetimepass/__init__.py | get_hotp | def get_hotp(
secret,
intervals_no,
as_string=False,
casefold=True,
digest_method=hashlib.sha1,
token_length=6,
):
"""
Get HMAC-based one-time password on the basis of given secret and
interval number.
:param secret: the base32-encoded string acting as secret key
:type secret: str or unicode
:param intervals_no: interval number used for getting different tokens, it
is incremented with each use
:type intervals_no: int
:param as_string: True if result should be padded string, False otherwise
:type as_string: bool
:param casefold: True (default), if should accept also lowercase alphabet
:type casefold: bool
:param digest_method: method of generating digest (hashlib.sha1 by default)
:type digest_method: callable
:param token_length: length of the token (6 by default)
:type token_length: int
:return: generated HOTP token
:rtype: int or str
>>> get_hotp(b'MFRGGZDFMZTWQ2LK', intervals_no=1)
765705
>>> get_hotp(b'MFRGGZDFMZTWQ2LK', intervals_no=2)
816065
>>> result = get_hotp(b'MFRGGZDFMZTWQ2LK', intervals_no=2, as_string=True)
>>> result == b'816065'
True
"""
if isinstance(secret, six.string_types):
# It is unicode, convert it to bytes
secret = secret.encode('utf-8')
# Get rid of all the spacing:
secret = secret.replace(b' ', b'')
try:
key = base64.b32decode(secret, casefold=casefold)
except (TypeError):
raise TypeError('Incorrect secret')
msg = struct.pack('>Q', intervals_no)
hmac_digest = hmac.new(key, msg, digest_method).digest()
ob = hmac_digest[19] if six.PY3 else ord(hmac_digest[19])
o = ob & 15
token_base = struct.unpack('>I', hmac_digest[o:o + 4])[0] & 0x7fffffff
token = token_base % (10 ** token_length)
if as_string:
# TODO: should as_string=True return unicode, not bytes?
return six.b('{{:0{}d}}'.format(token_length).format(token))
else:
return token | python | def get_hotp(
secret,
intervals_no,
as_string=False,
casefold=True,
digest_method=hashlib.sha1,
token_length=6,
):
"""
Get HMAC-based one-time password on the basis of given secret and
interval number.
:param secret: the base32-encoded string acting as secret key
:type secret: str or unicode
:param intervals_no: interval number used for getting different tokens, it
is incremented with each use
:type intervals_no: int
:param as_string: True if result should be padded string, False otherwise
:type as_string: bool
:param casefold: True (default), if should accept also lowercase alphabet
:type casefold: bool
:param digest_method: method of generating digest (hashlib.sha1 by default)
:type digest_method: callable
:param token_length: length of the token (6 by default)
:type token_length: int
:return: generated HOTP token
:rtype: int or str
>>> get_hotp(b'MFRGGZDFMZTWQ2LK', intervals_no=1)
765705
>>> get_hotp(b'MFRGGZDFMZTWQ2LK', intervals_no=2)
816065
>>> result = get_hotp(b'MFRGGZDFMZTWQ2LK', intervals_no=2, as_string=True)
>>> result == b'816065'
True
"""
if isinstance(secret, six.string_types):
# It is unicode, convert it to bytes
secret = secret.encode('utf-8')
# Get rid of all the spacing:
secret = secret.replace(b' ', b'')
try:
key = base64.b32decode(secret, casefold=casefold)
except (TypeError):
raise TypeError('Incorrect secret')
msg = struct.pack('>Q', intervals_no)
hmac_digest = hmac.new(key, msg, digest_method).digest()
ob = hmac_digest[19] if six.PY3 else ord(hmac_digest[19])
o = ob & 15
token_base = struct.unpack('>I', hmac_digest[o:o + 4])[0] & 0x7fffffff
token = token_base % (10 ** token_length)
if as_string:
# TODO: should as_string=True return unicode, not bytes?
return six.b('{{:0{}d}}'.format(token_length).format(token))
else:
return token | [
"def",
"get_hotp",
"(",
"secret",
",",
"intervals_no",
",",
"as_string",
"=",
"False",
",",
"casefold",
"=",
"True",
",",
"digest_method",
"=",
"hashlib",
".",
"sha1",
",",
"token_length",
"=",
"6",
",",
")",
":",
"if",
"isinstance",
"(",
"secret",
",",
... | Get HMAC-based one-time password on the basis of given secret and
interval number.
:param secret: the base32-encoded string acting as secret key
:type secret: str or unicode
:param intervals_no: interval number used for getting different tokens, it
is incremented with each use
:type intervals_no: int
:param as_string: True if result should be padded string, False otherwise
:type as_string: bool
:param casefold: True (default), if should accept also lowercase alphabet
:type casefold: bool
:param digest_method: method of generating digest (hashlib.sha1 by default)
:type digest_method: callable
:param token_length: length of the token (6 by default)
:type token_length: int
:return: generated HOTP token
:rtype: int or str
>>> get_hotp(b'MFRGGZDFMZTWQ2LK', intervals_no=1)
765705
>>> get_hotp(b'MFRGGZDFMZTWQ2LK', intervals_no=2)
816065
>>> result = get_hotp(b'MFRGGZDFMZTWQ2LK', intervals_no=2, as_string=True)
>>> result == b'816065'
True | [
"Get",
"HMAC",
"-",
"based",
"one",
"-",
"time",
"password",
"on",
"the",
"basis",
"of",
"given",
"secret",
"and",
"interval",
"number",
"."
] | ee4b4e1700089757594a5ffee5f24408c864ad00 | https://github.com/tadeck/onetimepass/blob/ee4b4e1700089757594a5ffee5f24408c864ad00/onetimepass/__init__.py#L71-L126 | train | 34,459 |
tadeck/onetimepass | onetimepass/__init__.py | get_totp | def get_totp(
secret,
as_string=False,
digest_method=hashlib.sha1,
token_length=6,
interval_length=30,
clock=None,
):
"""Get time-based one-time password on the basis of given secret and time.
:param secret: the base32-encoded string acting as secret key
:type secret: str
:param as_string: True if result should be padded string, False otherwise
:type as_string: bool
:param digest_method: method of generating digest (hashlib.sha1 by default)
:type digest_method: callable
:param token_length: length of the token (6 by default)
:type token_length: int
:param interval_length: length of TOTP interval (30 seconds by default)
:type interval_length: int
:param clock: time in epoch seconds to generate totp for, default is now
:type clock: int
:return: generated TOTP token
:rtype: int or str
>>> get_hotp(b'MFRGGZDFMZTWQ2LK', int(time.time())//30) == \
get_totp(b'MFRGGZDFMZTWQ2LK')
True
>>> get_hotp(b'MFRGGZDFMZTWQ2LK', int(time.time())//30) == \
get_totp(b'MFRGGZDFMZTWQ2LK', as_string=True)
False
"""
if clock is None:
clock = time.time()
interv_no = int(clock) // interval_length
return get_hotp(
secret,
intervals_no=interv_no,
as_string=as_string,
digest_method=digest_method,
token_length=token_length,
) | python | def get_totp(
secret,
as_string=False,
digest_method=hashlib.sha1,
token_length=6,
interval_length=30,
clock=None,
):
"""Get time-based one-time password on the basis of given secret and time.
:param secret: the base32-encoded string acting as secret key
:type secret: str
:param as_string: True if result should be padded string, False otherwise
:type as_string: bool
:param digest_method: method of generating digest (hashlib.sha1 by default)
:type digest_method: callable
:param token_length: length of the token (6 by default)
:type token_length: int
:param interval_length: length of TOTP interval (30 seconds by default)
:type interval_length: int
:param clock: time in epoch seconds to generate totp for, default is now
:type clock: int
:return: generated TOTP token
:rtype: int or str
>>> get_hotp(b'MFRGGZDFMZTWQ2LK', int(time.time())//30) == \
get_totp(b'MFRGGZDFMZTWQ2LK')
True
>>> get_hotp(b'MFRGGZDFMZTWQ2LK', int(time.time())//30) == \
get_totp(b'MFRGGZDFMZTWQ2LK', as_string=True)
False
"""
if clock is None:
clock = time.time()
interv_no = int(clock) // interval_length
return get_hotp(
secret,
intervals_no=interv_no,
as_string=as_string,
digest_method=digest_method,
token_length=token_length,
) | [
"def",
"get_totp",
"(",
"secret",
",",
"as_string",
"=",
"False",
",",
"digest_method",
"=",
"hashlib",
".",
"sha1",
",",
"token_length",
"=",
"6",
",",
"interval_length",
"=",
"30",
",",
"clock",
"=",
"None",
",",
")",
":",
"if",
"clock",
"is",
"None"... | Get time-based one-time password on the basis of given secret and time.
:param secret: the base32-encoded string acting as secret key
:type secret: str
:param as_string: True if result should be padded string, False otherwise
:type as_string: bool
:param digest_method: method of generating digest (hashlib.sha1 by default)
:type digest_method: callable
:param token_length: length of the token (6 by default)
:type token_length: int
:param interval_length: length of TOTP interval (30 seconds by default)
:type interval_length: int
:param clock: time in epoch seconds to generate totp for, default is now
:type clock: int
:return: generated TOTP token
:rtype: int or str
>>> get_hotp(b'MFRGGZDFMZTWQ2LK', int(time.time())//30) == \
get_totp(b'MFRGGZDFMZTWQ2LK')
True
>>> get_hotp(b'MFRGGZDFMZTWQ2LK', int(time.time())//30) == \
get_totp(b'MFRGGZDFMZTWQ2LK', as_string=True)
False | [
"Get",
"time",
"-",
"based",
"one",
"-",
"time",
"password",
"on",
"the",
"basis",
"of",
"given",
"secret",
"and",
"time",
"."
] | ee4b4e1700089757594a5ffee5f24408c864ad00 | https://github.com/tadeck/onetimepass/blob/ee4b4e1700089757594a5ffee5f24408c864ad00/onetimepass/__init__.py#L129-L170 | train | 34,460 |
tadeck/onetimepass | onetimepass/__init__.py | valid_hotp | def valid_hotp(
token,
secret,
last=1,
trials=1000,
digest_method=hashlib.sha1,
token_length=6,
):
"""Check if given token is valid for given secret. Return interval number
that was successful, or False if not found.
:param token: token being checked
:type token: int or str
:param secret: secret for which token is checked
:type secret: str
:param last: last used interval (start checking with next one)
:type last: int
:param trials: number of intervals to check after 'last'
:type trials: int
:param digest_method: method of generating digest (hashlib.sha1 by default)
:type digest_method: callable
:param token_length: length of the token (6 by default)
:type token_length: int
:return: interval number, or False if check unsuccessful
:rtype: int or bool
>>> secret = b'MFRGGZDFMZTWQ2LK'
>>> valid_hotp(713385, secret, last=1, trials=5)
4
>>> valid_hotp(865438, secret, last=1, trials=5)
False
>>> valid_hotp(713385, secret, last=4, trials=5)
False
"""
if not _is_possible_token(token, token_length=token_length):
return False
for i in six.moves.xrange(last + 1, last + trials + 1):
token_candidate = get_hotp(
secret=secret,
intervals_no=i,
digest_method=digest_method,
token_length=token_length,
)
if token_candidate == int(token):
return i
return False | python | def valid_hotp(
token,
secret,
last=1,
trials=1000,
digest_method=hashlib.sha1,
token_length=6,
):
"""Check if given token is valid for given secret. Return interval number
that was successful, or False if not found.
:param token: token being checked
:type token: int or str
:param secret: secret for which token is checked
:type secret: str
:param last: last used interval (start checking with next one)
:type last: int
:param trials: number of intervals to check after 'last'
:type trials: int
:param digest_method: method of generating digest (hashlib.sha1 by default)
:type digest_method: callable
:param token_length: length of the token (6 by default)
:type token_length: int
:return: interval number, or False if check unsuccessful
:rtype: int or bool
>>> secret = b'MFRGGZDFMZTWQ2LK'
>>> valid_hotp(713385, secret, last=1, trials=5)
4
>>> valid_hotp(865438, secret, last=1, trials=5)
False
>>> valid_hotp(713385, secret, last=4, trials=5)
False
"""
if not _is_possible_token(token, token_length=token_length):
return False
for i in six.moves.xrange(last + 1, last + trials + 1):
token_candidate = get_hotp(
secret=secret,
intervals_no=i,
digest_method=digest_method,
token_length=token_length,
)
if token_candidate == int(token):
return i
return False | [
"def",
"valid_hotp",
"(",
"token",
",",
"secret",
",",
"last",
"=",
"1",
",",
"trials",
"=",
"1000",
",",
"digest_method",
"=",
"hashlib",
".",
"sha1",
",",
"token_length",
"=",
"6",
",",
")",
":",
"if",
"not",
"_is_possible_token",
"(",
"token",
",",
... | Check if given token is valid for given secret. Return interval number
that was successful, or False if not found.
:param token: token being checked
:type token: int or str
:param secret: secret for which token is checked
:type secret: str
:param last: last used interval (start checking with next one)
:type last: int
:param trials: number of intervals to check after 'last'
:type trials: int
:param digest_method: method of generating digest (hashlib.sha1 by default)
:type digest_method: callable
:param token_length: length of the token (6 by default)
:type token_length: int
:return: interval number, or False if check unsuccessful
:rtype: int or bool
>>> secret = b'MFRGGZDFMZTWQ2LK'
>>> valid_hotp(713385, secret, last=1, trials=5)
4
>>> valid_hotp(865438, secret, last=1, trials=5)
False
>>> valid_hotp(713385, secret, last=4, trials=5)
False | [
"Check",
"if",
"given",
"token",
"is",
"valid",
"for",
"given",
"secret",
".",
"Return",
"interval",
"number",
"that",
"was",
"successful",
"or",
"False",
"if",
"not",
"found",
"."
] | ee4b4e1700089757594a5ffee5f24408c864ad00 | https://github.com/tadeck/onetimepass/blob/ee4b4e1700089757594a5ffee5f24408c864ad00/onetimepass/__init__.py#L173-L218 | train | 34,461 |
tadeck/onetimepass | onetimepass/__init__.py | valid_totp | def valid_totp(
token,
secret,
digest_method=hashlib.sha1,
token_length=6,
interval_length=30,
clock=None,
window=0,
):
"""Check if given token is valid time-based one-time password for given
secret.
:param token: token which is being checked
:type token: int or str
:param secret: secret for which the token is being checked
:type secret: str
:param digest_method: method of generating digest (hashlib.sha1 by default)
:type digest_method: callable
:param token_length: length of the token (6 by default)
:type token_length: int
:param interval_length: length of TOTP interval (30 seconds by default)
:type interval_length: int
:param clock: time in epoch seconds to generate totp for, default is now
:type clock: int
:param window: compensate for clock skew, number of intervals to check on
each side of the current time. (default is 0 - only check the current
clock time)
:type window: int (positive)
:return: True, if is valid token, False otherwise
:rtype: bool
>>> secret = b'MFRGGZDFMZTWQ2LK'
>>> token = get_totp(secret)
>>> valid_totp(token, secret)
True
>>> valid_totp(token+1, secret)
False
>>> token = get_totp(secret, as_string=True)
>>> valid_totp(token, secret)
True
>>> valid_totp(token + b'1', secret)
False
"""
if _is_possible_token(token, token_length=token_length):
if clock is None:
clock = time.time()
for w in range(-window, window+1):
if int(token) == get_totp(
secret,
digest_method=digest_method,
token_length=token_length,
interval_length=interval_length,
clock=int(clock)+(w*interval_length)
):
return True
return False | python | def valid_totp(
token,
secret,
digest_method=hashlib.sha1,
token_length=6,
interval_length=30,
clock=None,
window=0,
):
"""Check if given token is valid time-based one-time password for given
secret.
:param token: token which is being checked
:type token: int or str
:param secret: secret for which the token is being checked
:type secret: str
:param digest_method: method of generating digest (hashlib.sha1 by default)
:type digest_method: callable
:param token_length: length of the token (6 by default)
:type token_length: int
:param interval_length: length of TOTP interval (30 seconds by default)
:type interval_length: int
:param clock: time in epoch seconds to generate totp for, default is now
:type clock: int
:param window: compensate for clock skew, number of intervals to check on
each side of the current time. (default is 0 - only check the current
clock time)
:type window: int (positive)
:return: True, if is valid token, False otherwise
:rtype: bool
>>> secret = b'MFRGGZDFMZTWQ2LK'
>>> token = get_totp(secret)
>>> valid_totp(token, secret)
True
>>> valid_totp(token+1, secret)
False
>>> token = get_totp(secret, as_string=True)
>>> valid_totp(token, secret)
True
>>> valid_totp(token + b'1', secret)
False
"""
if _is_possible_token(token, token_length=token_length):
if clock is None:
clock = time.time()
for w in range(-window, window+1):
if int(token) == get_totp(
secret,
digest_method=digest_method,
token_length=token_length,
interval_length=interval_length,
clock=int(clock)+(w*interval_length)
):
return True
return False | [
"def",
"valid_totp",
"(",
"token",
",",
"secret",
",",
"digest_method",
"=",
"hashlib",
".",
"sha1",
",",
"token_length",
"=",
"6",
",",
"interval_length",
"=",
"30",
",",
"clock",
"=",
"None",
",",
"window",
"=",
"0",
",",
")",
":",
"if",
"_is_possibl... | Check if given token is valid time-based one-time password for given
secret.
:param token: token which is being checked
:type token: int or str
:param secret: secret for which the token is being checked
:type secret: str
:param digest_method: method of generating digest (hashlib.sha1 by default)
:type digest_method: callable
:param token_length: length of the token (6 by default)
:type token_length: int
:param interval_length: length of TOTP interval (30 seconds by default)
:type interval_length: int
:param clock: time in epoch seconds to generate totp for, default is now
:type clock: int
:param window: compensate for clock skew, number of intervals to check on
each side of the current time. (default is 0 - only check the current
clock time)
:type window: int (positive)
:return: True, if is valid token, False otherwise
:rtype: bool
>>> secret = b'MFRGGZDFMZTWQ2LK'
>>> token = get_totp(secret)
>>> valid_totp(token, secret)
True
>>> valid_totp(token+1, secret)
False
>>> token = get_totp(secret, as_string=True)
>>> valid_totp(token, secret)
True
>>> valid_totp(token + b'1', secret)
False | [
"Check",
"if",
"given",
"token",
"is",
"valid",
"time",
"-",
"based",
"one",
"-",
"time",
"password",
"for",
"given",
"secret",
"."
] | ee4b4e1700089757594a5ffee5f24408c864ad00 | https://github.com/tadeck/onetimepass/blob/ee4b4e1700089757594a5ffee5f24408c864ad00/onetimepass/__init__.py#L221-L276 | train | 34,462 |
uber/multidimensional_urlencode | multidimensional_urlencode/urlencoder.py | parametrize | def parametrize(params):
"""Return list of params as params.
>>> parametrize(['a'])
'a'
>>> parametrize(['a', 'b'])
'a[b]'
>>> parametrize(['a', 'b', 'c'])
'a[b][c]'
"""
returned = str(params[0])
returned += "".join("[" + str(p) + "]" for p in params[1:])
return returned | python | def parametrize(params):
"""Return list of params as params.
>>> parametrize(['a'])
'a'
>>> parametrize(['a', 'b'])
'a[b]'
>>> parametrize(['a', 'b', 'c'])
'a[b][c]'
"""
returned = str(params[0])
returned += "".join("[" + str(p) + "]" for p in params[1:])
return returned | [
"def",
"parametrize",
"(",
"params",
")",
":",
"returned",
"=",
"str",
"(",
"params",
"[",
"0",
"]",
")",
"returned",
"+=",
"\"\"",
".",
"join",
"(",
"\"[\"",
"+",
"str",
"(",
"p",
")",
"+",
"\"]\"",
"for",
"p",
"in",
"params",
"[",
"1",
":",
"... | Return list of params as params.
>>> parametrize(['a'])
'a'
>>> parametrize(['a', 'b'])
'a[b]'
>>> parametrize(['a', 'b', 'c'])
'a[b][c]' | [
"Return",
"list",
"of",
"params",
"as",
"params",
"."
] | f626528bc3535503fa1557a53bbfacaa29920251 | https://github.com/uber/multidimensional_urlencode/blob/f626528bc3535503fa1557a53bbfacaa29920251/multidimensional_urlencode/urlencoder.py#L41-L54 | train | 34,463 |
uber/multidimensional_urlencode | multidimensional_urlencode/urlencoder.py | urlencode | def urlencode(params):
"""Urlencode a multidimensional dict."""
# Not doing duck typing here. Will make debugging easier.
if not isinstance(params, dict):
raise TypeError("Only dicts are supported.")
params = flatten(params)
url_params = OrderedDict()
for param in params:
value = param.pop()
name = parametrize(param)
if isinstance(value, (list, tuple)):
name += "[]"
url_params[name] = value
return urllib_urlencode(url_params, doseq=True) | python | def urlencode(params):
"""Urlencode a multidimensional dict."""
# Not doing duck typing here. Will make debugging easier.
if not isinstance(params, dict):
raise TypeError("Only dicts are supported.")
params = flatten(params)
url_params = OrderedDict()
for param in params:
value = param.pop()
name = parametrize(param)
if isinstance(value, (list, tuple)):
name += "[]"
url_params[name] = value
return urllib_urlencode(url_params, doseq=True) | [
"def",
"urlencode",
"(",
"params",
")",
":",
"# Not doing duck typing here. Will make debugging easier.",
"if",
"not",
"isinstance",
"(",
"params",
",",
"dict",
")",
":",
"raise",
"TypeError",
"(",
"\"Only dicts are supported.\"",
")",
"params",
"=",
"flatten",
"(",
... | Urlencode a multidimensional dict. | [
"Urlencode",
"a",
"multidimensional",
"dict",
"."
] | f626528bc3535503fa1557a53bbfacaa29920251 | https://github.com/uber/multidimensional_urlencode/blob/f626528bc3535503fa1557a53bbfacaa29920251/multidimensional_urlencode/urlencoder.py#L57-L76 | train | 34,464 |
mrkrd/matlab_wrapper | matlab_wrapper/matlab_session.py | find_matlab_root | def find_matlab_root():
"""Look for matlab binary and return root directory of MATLAB
installation.
"""
matlab_root = None
path_dirs = os.environ.get("PATH").split(os.pathsep)
for path_dir in path_dirs:
candidate = realpath(join(path_dir, 'matlab'))
if isfile(candidate) or isfile(candidate + '.exe'):
matlab_root = dirname(dirname(candidate))
break
return matlab_root | python | def find_matlab_root():
"""Look for matlab binary and return root directory of MATLAB
installation.
"""
matlab_root = None
path_dirs = os.environ.get("PATH").split(os.pathsep)
for path_dir in path_dirs:
candidate = realpath(join(path_dir, 'matlab'))
if isfile(candidate) or isfile(candidate + '.exe'):
matlab_root = dirname(dirname(candidate))
break
return matlab_root | [
"def",
"find_matlab_root",
"(",
")",
":",
"matlab_root",
"=",
"None",
"path_dirs",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"\"PATH\"",
")",
".",
"split",
"(",
"os",
".",
"pathsep",
")",
"for",
"path_dir",
"in",
"path_dirs",
":",
"candidate",
"=",
"... | Look for matlab binary and return root directory of MATLAB
installation. | [
"Look",
"for",
"matlab",
"binary",
"and",
"return",
"root",
"directory",
"of",
"MATLAB",
"installation",
"."
] | 9c42de0c379d7f07d9849b7d4770fba70ec8a6f4 | https://github.com/mrkrd/matlab_wrapper/blob/9c42de0c379d7f07d9849b7d4770fba70ec8a6f4/matlab_wrapper/matlab_session.py#L246-L260 | train | 34,465 |
mrkrd/matlab_wrapper | matlab_wrapper/matlab_session.py | load_engine_and_libs | def load_engine_and_libs(matlab_root, options):
"""Load and return `libeng` and `libmx`. Start and return MATLAB
engine.
Returns
-------
engine
libeng
libmx
"""
if sys.maxsize > 2**32:
bits = '64bit'
else:
bits = '32bit'
system = platform.system()
if system == 'Linux':
if bits == '64bit':
lib_dir = join(matlab_root, "bin", "glnxa64")
else:
lib_dir = join(matlab_root, "bin", "glnx86")
check_python_matlab_architecture(bits, lib_dir)
libeng = Library(
join(lib_dir, 'libeng.so')
)
libmx = Library(
join(lib_dir, 'libmx.so')
)
command = "{executable} {options}".format(
executable=join(matlab_root, 'bin', 'matlab'),
options=options
)
### Check for /bin/csh
if not os.path.exists("/bin/csh"):
warnings.warn("MATLAB engine requires /bin/csh. Please install it on your system or matlab_wrapper will not work properly.")
elif system == 'Windows':
if bits == '64bit':
lib_dir = join(matlab_root, "bin", "win64")
else:
lib_dir = join(matlab_root, "bin", "win32")
check_python_matlab_architecture(bits, lib_dir)
## We need to modify PATH, to find MATLAB libs
if lib_dir not in os.environ['PATH']:
os.environ['PATH'] = lib_dir + ';' + os.environ['PATH']
libeng = Library('libeng')
libmx = Library('libmx')
command = None
elif system == 'Darwin':
if bits == '64bit':
lib_dir = join(matlab_root, "bin", "maci64")
else:
unsupported_platform(system, bits)
check_python_matlab_architecture(bits, lib_dir)
libeng = Library(
join(lib_dir, 'libeng.dylib')
)
libmx = Library(
join(lib_dir, 'libmx.dylib')
)
command = "{executable} {options}".format(
executable=join(matlab_root, 'bin', 'matlab'),
options=options
)
else:
unsupported_platform(system, bits)
### Check MATLAB version
try:
version_str = c_char_p.in_dll(libeng, "libeng_version").value
version = tuple([int(v) for v in version_str.split('.')[:2]])
except ValueError:
warnings.warn("Unable to identify MATLAB (libeng) version.")
version = None
if (system == 'Linux') and (version == (8, 3)) and (bits == '64bit'):
warnings.warn("You are using MATLAB version 8.3 (R2014a) on Linux, which appears to have a bug in engGetVariable(). You will only be able to use arrays of type double.")
elif (system == 'Darwin') and (version == (8, 3)) and (bits == '64bit'):
warnings.warn("You are using MATLAB version 8.3 (R2014a) on OS X, which appears to have a bug in engGetVariable(). You will only be able to use arrays of type double.")
### Start the engine
engine = libeng.engOpen(command)
return engine, libeng, libmx, version | python | def load_engine_and_libs(matlab_root, options):
"""Load and return `libeng` and `libmx`. Start and return MATLAB
engine.
Returns
-------
engine
libeng
libmx
"""
if sys.maxsize > 2**32:
bits = '64bit'
else:
bits = '32bit'
system = platform.system()
if system == 'Linux':
if bits == '64bit':
lib_dir = join(matlab_root, "bin", "glnxa64")
else:
lib_dir = join(matlab_root, "bin", "glnx86")
check_python_matlab_architecture(bits, lib_dir)
libeng = Library(
join(lib_dir, 'libeng.so')
)
libmx = Library(
join(lib_dir, 'libmx.so')
)
command = "{executable} {options}".format(
executable=join(matlab_root, 'bin', 'matlab'),
options=options
)
### Check for /bin/csh
if not os.path.exists("/bin/csh"):
warnings.warn("MATLAB engine requires /bin/csh. Please install it on your system or matlab_wrapper will not work properly.")
elif system == 'Windows':
if bits == '64bit':
lib_dir = join(matlab_root, "bin", "win64")
else:
lib_dir = join(matlab_root, "bin", "win32")
check_python_matlab_architecture(bits, lib_dir)
## We need to modify PATH, to find MATLAB libs
if lib_dir not in os.environ['PATH']:
os.environ['PATH'] = lib_dir + ';' + os.environ['PATH']
libeng = Library('libeng')
libmx = Library('libmx')
command = None
elif system == 'Darwin':
if bits == '64bit':
lib_dir = join(matlab_root, "bin", "maci64")
else:
unsupported_platform(system, bits)
check_python_matlab_architecture(bits, lib_dir)
libeng = Library(
join(lib_dir, 'libeng.dylib')
)
libmx = Library(
join(lib_dir, 'libmx.dylib')
)
command = "{executable} {options}".format(
executable=join(matlab_root, 'bin', 'matlab'),
options=options
)
else:
unsupported_platform(system, bits)
### Check MATLAB version
try:
version_str = c_char_p.in_dll(libeng, "libeng_version").value
version = tuple([int(v) for v in version_str.split('.')[:2]])
except ValueError:
warnings.warn("Unable to identify MATLAB (libeng) version.")
version = None
if (system == 'Linux') and (version == (8, 3)) and (bits == '64bit'):
warnings.warn("You are using MATLAB version 8.3 (R2014a) on Linux, which appears to have a bug in engGetVariable(). You will only be able to use arrays of type double.")
elif (system == 'Darwin') and (version == (8, 3)) and (bits == '64bit'):
warnings.warn("You are using MATLAB version 8.3 (R2014a) on OS X, which appears to have a bug in engGetVariable(). You will only be able to use arrays of type double.")
### Start the engine
engine = libeng.engOpen(command)
return engine, libeng, libmx, version | [
"def",
"load_engine_and_libs",
"(",
"matlab_root",
",",
"options",
")",
":",
"if",
"sys",
".",
"maxsize",
">",
"2",
"**",
"32",
":",
"bits",
"=",
"'64bit'",
"else",
":",
"bits",
"=",
"'32bit'",
"system",
"=",
"platform",
".",
"system",
"(",
")",
"if",
... | Load and return `libeng` and `libmx`. Start and return MATLAB
engine.
Returns
-------
engine
libeng
libmx | [
"Load",
"and",
"return",
"libeng",
"and",
"libmx",
".",
"Start",
"and",
"return",
"MATLAB",
"engine",
"."
] | 9c42de0c379d7f07d9849b7d4770fba70ec8a6f4 | https://github.com/mrkrd/matlab_wrapper/blob/9c42de0c379d7f07d9849b7d4770fba70ec8a6f4/matlab_wrapper/matlab_session.py#L263-L363 | train | 34,466 |
mrkrd/matlab_wrapper | matlab_wrapper/matlab_session.py | check_python_matlab_architecture | def check_python_matlab_architecture(bits, lib_dir):
"""Make sure we can find corresponding installation of Python and MATLAB."""
if not os.path.isdir(lib_dir):
raise RuntimeError("It seem that you are using {bits} version of Python, but there's no matching MATLAB installation in {lib_dir}.".format(bits=bits, lib_dir=lib_dir)) | python | def check_python_matlab_architecture(bits, lib_dir):
"""Make sure we can find corresponding installation of Python and MATLAB."""
if not os.path.isdir(lib_dir):
raise RuntimeError("It seem that you are using {bits} version of Python, but there's no matching MATLAB installation in {lib_dir}.".format(bits=bits, lib_dir=lib_dir)) | [
"def",
"check_python_matlab_architecture",
"(",
"bits",
",",
"lib_dir",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"lib_dir",
")",
":",
"raise",
"RuntimeError",
"(",
"\"It seem that you are using {bits} version of Python, but there's no matching MATLAB i... | Make sure we can find corresponding installation of Python and MATLAB. | [
"Make",
"sure",
"we",
"can",
"find",
"corresponding",
"installation",
"of",
"Python",
"and",
"MATLAB",
"."
] | 9c42de0c379d7f07d9849b7d4770fba70ec8a6f4 | https://github.com/mrkrd/matlab_wrapper/blob/9c42de0c379d7f07d9849b7d4770fba70ec8a6f4/matlab_wrapper/matlab_session.py#L366-L369 | train | 34,467 |
mrkrd/matlab_wrapper | matlab_wrapper/matlab_session.py | MatlabSession.eval | def eval(self, expression):
"""Evaluate `expression` in MATLAB engine.
Parameters
----------
expression : str
Expression is passed to MATLAB engine and evaluated.
"""
expression_wrapped = wrap_script.format(expression)
### Evaluate the expression
self._libeng.engEvalString(self._ep, expression_wrapped)
### Check for exceptions in MATLAB
mxresult = self._libeng.engGetVariable(self._ep, 'ERRSTR__')
error_string = self._libmx.mxArrayToString(mxresult)
self._libmx.mxDestroyArray(mxresult)
if error_string != "":
raise RuntimeError("Error from MATLAB\n{0}".format(error_string)) | python | def eval(self, expression):
"""Evaluate `expression` in MATLAB engine.
Parameters
----------
expression : str
Expression is passed to MATLAB engine and evaluated.
"""
expression_wrapped = wrap_script.format(expression)
### Evaluate the expression
self._libeng.engEvalString(self._ep, expression_wrapped)
### Check for exceptions in MATLAB
mxresult = self._libeng.engGetVariable(self._ep, 'ERRSTR__')
error_string = self._libmx.mxArrayToString(mxresult)
self._libmx.mxDestroyArray(mxresult)
if error_string != "":
raise RuntimeError("Error from MATLAB\n{0}".format(error_string)) | [
"def",
"eval",
"(",
"self",
",",
"expression",
")",
":",
"expression_wrapped",
"=",
"wrap_script",
".",
"format",
"(",
"expression",
")",
"### Evaluate the expression",
"self",
".",
"_libeng",
".",
"engEvalString",
"(",
"self",
".",
"_ep",
",",
"expression_wrapp... | Evaluate `expression` in MATLAB engine.
Parameters
----------
expression : str
Expression is passed to MATLAB engine and evaluated. | [
"Evaluate",
"expression",
"in",
"MATLAB",
"engine",
"."
] | 9c42de0c379d7f07d9849b7d4770fba70ec8a6f4 | https://github.com/mrkrd/matlab_wrapper/blob/9c42de0c379d7f07d9849b7d4770fba70ec8a6f4/matlab_wrapper/matlab_session.py#L161-L184 | train | 34,468 |
mrkrd/matlab_wrapper | matlab_wrapper/matlab_session.py | MatlabSession.get | def get(self, name):
"""Get variable `name` from MATLAB workspace.
Parameters
----------
name : str
Name of the variable in MATLAB workspace.
Returns
-------
array_like
Value of the variable `name`.
"""
pm = self._libeng.engGetVariable(self._ep, name)
out = mxarray_to_ndarray(self._libmx, pm)
self._libmx.mxDestroyArray(pm)
return out | python | def get(self, name):
"""Get variable `name` from MATLAB workspace.
Parameters
----------
name : str
Name of the variable in MATLAB workspace.
Returns
-------
array_like
Value of the variable `name`.
"""
pm = self._libeng.engGetVariable(self._ep, name)
out = mxarray_to_ndarray(self._libmx, pm)
self._libmx.mxDestroyArray(pm)
return out | [
"def",
"get",
"(",
"self",
",",
"name",
")",
":",
"pm",
"=",
"self",
".",
"_libeng",
".",
"engGetVariable",
"(",
"self",
".",
"_ep",
",",
"name",
")",
"out",
"=",
"mxarray_to_ndarray",
"(",
"self",
".",
"_libmx",
",",
"pm",
")",
"self",
".",
"_libm... | Get variable `name` from MATLAB workspace.
Parameters
----------
name : str
Name of the variable in MATLAB workspace.
Returns
-------
array_like
Value of the variable `name`. | [
"Get",
"variable",
"name",
"from",
"MATLAB",
"workspace",
"."
] | 9c42de0c379d7f07d9849b7d4770fba70ec8a6f4 | https://github.com/mrkrd/matlab_wrapper/blob/9c42de0c379d7f07d9849b7d4770fba70ec8a6f4/matlab_wrapper/matlab_session.py#L188-L209 | train | 34,469 |
mrkrd/matlab_wrapper | matlab_wrapper/matlab_session.py | MatlabSession.put | def put(self, name, value):
"""Put a variable to MATLAB workspace.
"""
pm = ndarray_to_mxarray(self._libmx, value)
self._libeng.engPutVariable(self._ep, name, pm)
self._libmx.mxDestroyArray(pm) | python | def put(self, name, value):
"""Put a variable to MATLAB workspace.
"""
pm = ndarray_to_mxarray(self._libmx, value)
self._libeng.engPutVariable(self._ep, name, pm)
self._libmx.mxDestroyArray(pm) | [
"def",
"put",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"pm",
"=",
"ndarray_to_mxarray",
"(",
"self",
".",
"_libmx",
",",
"value",
")",
"self",
".",
"_libeng",
".",
"engPutVariable",
"(",
"self",
".",
"_ep",
",",
"name",
",",
"pm",
")",
"se... | Put a variable to MATLAB workspace. | [
"Put",
"a",
"variable",
"to",
"MATLAB",
"workspace",
"."
] | 9c42de0c379d7f07d9849b7d4770fba70ec8a6f4 | https://github.com/mrkrd/matlab_wrapper/blob/9c42de0c379d7f07d9849b7d4770fba70ec8a6f4/matlab_wrapper/matlab_session.py#L214-L223 | train | 34,470 |
mesosphere/deimos | deimos/cleanup.py | Cleanup.dirs | def dirs(self, before=time.time(), exited=True):
"""
Provider a generator of container state directories.
If exited is None, all are returned. If it is False, unexited
containers are returned. If it is True, only exited containers are
returned.
"""
timestamp = iso(before)
root = os.path.join(self.root, "start-time")
os.chdir(root)
by_t = (d for d in glob.iglob("????-??-??T*.*Z") if d < timestamp)
if exited is None:
def predicate(directory):
return True
else:
def predicate(directory):
exit = os.path.join(directory, "exit")
return os.path.exists(exit) is exited
return (os.path.join(root, d) for d in by_t if predicate(d)) | python | def dirs(self, before=time.time(), exited=True):
"""
Provider a generator of container state directories.
If exited is None, all are returned. If it is False, unexited
containers are returned. If it is True, only exited containers are
returned.
"""
timestamp = iso(before)
root = os.path.join(self.root, "start-time")
os.chdir(root)
by_t = (d for d in glob.iglob("????-??-??T*.*Z") if d < timestamp)
if exited is None:
def predicate(directory):
return True
else:
def predicate(directory):
exit = os.path.join(directory, "exit")
return os.path.exists(exit) is exited
return (os.path.join(root, d) for d in by_t if predicate(d)) | [
"def",
"dirs",
"(",
"self",
",",
"before",
"=",
"time",
".",
"time",
"(",
")",
",",
"exited",
"=",
"True",
")",
":",
"timestamp",
"=",
"iso",
"(",
"before",
")",
"root",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"root",
",",
"\"sta... | Provider a generator of container state directories.
If exited is None, all are returned. If it is False, unexited
containers are returned. If it is True, only exited containers are
returned. | [
"Provider",
"a",
"generator",
"of",
"container",
"state",
"directories",
"."
] | b4deead93b6e2ddf4e4a42e33777755942da0b7a | https://github.com/mesosphere/deimos/blob/b4deead93b6e2ddf4e4a42e33777755942da0b7a/deimos/cleanup.py#L21-L40 | train | 34,471 |
mesosphere/deimos | deimos/containerizer/__init__.py | methods | def methods():
"Names of operations provided by containerizers, as a set."
pairs = inspect.getmembers(Containerizer, predicate=inspect.ismethod)
return set(k for k, _ in pairs if k[0:1] != "_") | python | def methods():
"Names of operations provided by containerizers, as a set."
pairs = inspect.getmembers(Containerizer, predicate=inspect.ismethod)
return set(k for k, _ in pairs if k[0:1] != "_") | [
"def",
"methods",
"(",
")",
":",
"pairs",
"=",
"inspect",
".",
"getmembers",
"(",
"Containerizer",
",",
"predicate",
"=",
"inspect",
".",
"ismethod",
")",
"return",
"set",
"(",
"k",
"for",
"k",
",",
"_",
"in",
"pairs",
"if",
"k",
"[",
"0",
":",
"1"... | Names of operations provided by containerizers, as a set. | [
"Names",
"of",
"operations",
"provided",
"by",
"containerizers",
"as",
"a",
"set",
"."
] | b4deead93b6e2ddf4e4a42e33777755942da0b7a | https://github.com/mesosphere/deimos/blob/b4deead93b6e2ddf4e4a42e33777755942da0b7a/deimos/containerizer/__init__.py#L49-L52 | train | 34,472 |
mesosphere/deimos | deimos/containerizer/__init__.py | stdio | def stdio(containerizer, *args):
"""Connect containerizer class to command line args and STDIN
Dispatches to an appropriate containerizer method based on the first
argument and parses the input using an appropriate Protobuf type.
launch < containerizer::Launch
update < containerizer::Update
usage < containerizer::Usage > mesos::ResourceStatistics
wait < containerizer::Wait > containerizer::Termination
destroy < containerizer::Destroy
containers > containerizer::Containers
recover
Output serialization must be handled by the containerizer method (it
doesn't necessarily happen at the end).
Not really part of the containerizer protocol but exposed by Deimos as a
subcommand:
# Follows a Docker ID, PID, &c and exits with an appropriate, matching
# exit code, in a manner specific to the containerizer
observe <id>
"""
try:
name = args[0]
method, proto = {"launch": (containerizer.launch, Launch),
"update": (containerizer.update, Update),
"usage": (containerizer.usage, Usage),
"wait": (containerizer.wait, Wait),
"destroy": (containerizer.destroy, Destroy),
"containers": (containerizer.containers, None),
"recover": (containerizer.recover, None),
"observe": (containerizer.observe, None)}[name]
except IndexError:
raise Err("Please choose a subcommand")
except KeyError:
raise Err("Subcommand %s is not valid for containerizers" % name)
log.debug("%r", (method, proto))
if proto is not None:
return method(recordio.read(proto), *args[1:])
else:
return method(*args[1:]) | python | def stdio(containerizer, *args):
"""Connect containerizer class to command line args and STDIN
Dispatches to an appropriate containerizer method based on the first
argument and parses the input using an appropriate Protobuf type.
launch < containerizer::Launch
update < containerizer::Update
usage < containerizer::Usage > mesos::ResourceStatistics
wait < containerizer::Wait > containerizer::Termination
destroy < containerizer::Destroy
containers > containerizer::Containers
recover
Output serialization must be handled by the containerizer method (it
doesn't necessarily happen at the end).
Not really part of the containerizer protocol but exposed by Deimos as a
subcommand:
# Follows a Docker ID, PID, &c and exits with an appropriate, matching
# exit code, in a manner specific to the containerizer
observe <id>
"""
try:
name = args[0]
method, proto = {"launch": (containerizer.launch, Launch),
"update": (containerizer.update, Update),
"usage": (containerizer.usage, Usage),
"wait": (containerizer.wait, Wait),
"destroy": (containerizer.destroy, Destroy),
"containers": (containerizer.containers, None),
"recover": (containerizer.recover, None),
"observe": (containerizer.observe, None)}[name]
except IndexError:
raise Err("Please choose a subcommand")
except KeyError:
raise Err("Subcommand %s is not valid for containerizers" % name)
log.debug("%r", (method, proto))
if proto is not None:
return method(recordio.read(proto), *args[1:])
else:
return method(*args[1:]) | [
"def",
"stdio",
"(",
"containerizer",
",",
"*",
"args",
")",
":",
"try",
":",
"name",
"=",
"args",
"[",
"0",
"]",
"method",
",",
"proto",
"=",
"{",
"\"launch\"",
":",
"(",
"containerizer",
".",
"launch",
",",
"Launch",
")",
",",
"\"update\"",
":",
... | Connect containerizer class to command line args and STDIN
Dispatches to an appropriate containerizer method based on the first
argument and parses the input using an appropriate Protobuf type.
launch < containerizer::Launch
update < containerizer::Update
usage < containerizer::Usage > mesos::ResourceStatistics
wait < containerizer::Wait > containerizer::Termination
destroy < containerizer::Destroy
containers > containerizer::Containers
recover
Output serialization must be handled by the containerizer method (it
doesn't necessarily happen at the end).
Not really part of the containerizer protocol but exposed by Deimos as a
subcommand:
# Follows a Docker ID, PID, &c and exits with an appropriate, matching
# exit code, in a manner specific to the containerizer
observe <id> | [
"Connect",
"containerizer",
"class",
"to",
"command",
"line",
"args",
"and",
"STDIN"
] | b4deead93b6e2ddf4e4a42e33777755942da0b7a | https://github.com/mesosphere/deimos/blob/b4deead93b6e2ddf4e4a42e33777755942da0b7a/deimos/containerizer/__init__.py#L57-L100 | train | 34,473 |
mesosphere/deimos | deimos/cgroups.py | construct | def construct(path, name=None):
"Selects an appropriate CGroup subclass for the given CGroup path."
name = name if name else path.split("/")[4]
classes = {"memory": Memory,
"cpu": CPU,
"cpuacct": CPUAcct}
constructor = classes.get(name, CGroup)
log.debug("Chose %s for: %s", constructor.__name__, path)
return constructor(path, name) | python | def construct(path, name=None):
"Selects an appropriate CGroup subclass for the given CGroup path."
name = name if name else path.split("/")[4]
classes = {"memory": Memory,
"cpu": CPU,
"cpuacct": CPUAcct}
constructor = classes.get(name, CGroup)
log.debug("Chose %s for: %s", constructor.__name__, path)
return constructor(path, name) | [
"def",
"construct",
"(",
"path",
",",
"name",
"=",
"None",
")",
":",
"name",
"=",
"name",
"if",
"name",
"else",
"path",
".",
"split",
"(",
"\"/\"",
")",
"[",
"4",
"]",
"classes",
"=",
"{",
"\"memory\"",
":",
"Memory",
",",
"\"cpu\"",
":",
"CPU",
... | Selects an appropriate CGroup subclass for the given CGroup path. | [
"Selects",
"an",
"appropriate",
"CGroup",
"subclass",
"for",
"the",
"given",
"CGroup",
"path",
"."
] | b4deead93b6e2ddf4e4a42e33777755942da0b7a | https://github.com/mesosphere/deimos/blob/b4deead93b6e2ddf4e4a42e33777755942da0b7a/deimos/cgroups.py#L43-L51 | train | 34,474 |
mesosphere/deimos | deimos/proto.py | serialize | def serialize(cls, **properties):
"""
With a Protobuf class and properties as keyword arguments, sets all the
properties on a new instance of the class and serializes the resulting
value.
"""
obj = cls()
for k, v in properties.iteritems():
log.debug("%s.%s = %r", cls.__name__, k, v)
setattr(obj, k, v)
return obj.SerializeToString() | python | def serialize(cls, **properties):
"""
With a Protobuf class and properties as keyword arguments, sets all the
properties on a new instance of the class and serializes the resulting
value.
"""
obj = cls()
for k, v in properties.iteritems():
log.debug("%s.%s = %r", cls.__name__, k, v)
setattr(obj, k, v)
return obj.SerializeToString() | [
"def",
"serialize",
"(",
"cls",
",",
"*",
"*",
"properties",
")",
":",
"obj",
"=",
"cls",
"(",
")",
"for",
"k",
",",
"v",
"in",
"properties",
".",
"iteritems",
"(",
")",
":",
"log",
".",
"debug",
"(",
"\"%s.%s = %r\"",
",",
"cls",
".",
"__name__",
... | With a Protobuf class and properties as keyword arguments, sets all the
properties on a new instance of the class and serializes the resulting
value. | [
"With",
"a",
"Protobuf",
"class",
"and",
"properties",
"as",
"keyword",
"arguments",
"sets",
"all",
"the",
"properties",
"on",
"a",
"new",
"instance",
"of",
"the",
"class",
"and",
"serializes",
"the",
"resulting",
"value",
"."
] | b4deead93b6e2ddf4e4a42e33777755942da0b7a | https://github.com/mesosphere/deimos/blob/b4deead93b6e2ddf4e4a42e33777755942da0b7a/deimos/proto.py#L41-L51 | train | 34,475 |
mesosphere/deimos | deimos/logger.py | logger | def logger(height=1): # http://stackoverflow.com/a/900404/48251
"""
Obtain a function logger for the calling function. Uses the inspect module
to find the name of the calling function and its position in the module
hierarchy. With the optional height argument, logs for caller's caller, and
so forth.
"""
caller = inspect.stack()[height]
scope = caller[0].f_globals
function = caller[3]
path = scope["__name__"]
if path == "__main__" and scope["__package__"]:
path = scope["__package__"]
return logging.getLogger(path + "." + function + "()") | python | def logger(height=1): # http://stackoverflow.com/a/900404/48251
"""
Obtain a function logger for the calling function. Uses the inspect module
to find the name of the calling function and its position in the module
hierarchy. With the optional height argument, logs for caller's caller, and
so forth.
"""
caller = inspect.stack()[height]
scope = caller[0].f_globals
function = caller[3]
path = scope["__name__"]
if path == "__main__" and scope["__package__"]:
path = scope["__package__"]
return logging.getLogger(path + "." + function + "()") | [
"def",
"logger",
"(",
"height",
"=",
"1",
")",
":",
"# http://stackoverflow.com/a/900404/48251",
"caller",
"=",
"inspect",
".",
"stack",
"(",
")",
"[",
"height",
"]",
"scope",
"=",
"caller",
"[",
"0",
"]",
".",
"f_globals",
"function",
"=",
"caller",
"[",
... | Obtain a function logger for the calling function. Uses the inspect module
to find the name of the calling function and its position in the module
hierarchy. With the optional height argument, logs for caller's caller, and
so forth. | [
"Obtain",
"a",
"function",
"logger",
"for",
"the",
"calling",
"function",
".",
"Uses",
"the",
"inspect",
"module",
"to",
"find",
"the",
"name",
"of",
"the",
"calling",
"function",
"and",
"its",
"position",
"in",
"the",
"module",
"hierarchy",
".",
"With",
"... | b4deead93b6e2ddf4e4a42e33777755942da0b7a | https://github.com/mesosphere/deimos/blob/b4deead93b6e2ddf4e4a42e33777755942da0b7a/deimos/logger.py#L65-L78 | train | 34,476 |
googlecolab/jupyter_http_over_ws | jupyter_http_over_ws/__init__.py | load_jupyter_server_extension | def load_jupyter_server_extension(nb_server_app):
"""Called by Jupyter when this module is loaded as a server extension."""
app = nb_server_app.web_app
host_pattern = '.*$'
app.add_handlers(host_pattern, [
(utils.url_path_join(app.settings['base_url'], '/http_over_websocket'),
handlers.HttpOverWebSocketHandler),
(utils.url_path_join(app.settings['base_url'],
'/http_over_websocket/diagnose'),
handlers.HttpOverWebSocketDiagnosticHandler),
])
print('jupyter_http_over_ws extension initialized. Listening on '
'/http_over_websocket') | python | def load_jupyter_server_extension(nb_server_app):
"""Called by Jupyter when this module is loaded as a server extension."""
app = nb_server_app.web_app
host_pattern = '.*$'
app.add_handlers(host_pattern, [
(utils.url_path_join(app.settings['base_url'], '/http_over_websocket'),
handlers.HttpOverWebSocketHandler),
(utils.url_path_join(app.settings['base_url'],
'/http_over_websocket/diagnose'),
handlers.HttpOverWebSocketDiagnosticHandler),
])
print('jupyter_http_over_ws extension initialized. Listening on '
'/http_over_websocket') | [
"def",
"load_jupyter_server_extension",
"(",
"nb_server_app",
")",
":",
"app",
"=",
"nb_server_app",
".",
"web_app",
"host_pattern",
"=",
"'.*$'",
"app",
".",
"add_handlers",
"(",
"host_pattern",
",",
"[",
"(",
"utils",
".",
"url_path_join",
"(",
"app",
".",
"... | Called by Jupyter when this module is loaded as a server extension. | [
"Called",
"by",
"Jupyter",
"when",
"this",
"module",
"is",
"loaded",
"as",
"a",
"server",
"extension",
"."
] | 21fe278cae6fca4e6c92f92d6d786fae8fdea9b1 | https://github.com/googlecolab/jupyter_http_over_ws/blob/21fe278cae6fca4e6c92f92d6d786fae8fdea9b1/jupyter_http_over_ws/__init__.py#L30-L43 | train | 34,477 |
googlecolab/jupyter_http_over_ws | jupyter_http_over_ws/handlers.py | _validate_min_version | def _validate_min_version(min_version):
"""Validates the extension version matches the requested version.
Args:
min_version: Minimum version passed as a query param when establishing the
connection.
Returns:
An ExtensionVersionResult indicating validation status. If there is a
problem, the error_reason field will be non-empty.
"""
if min_version is not None:
try:
parsed_min_version = version.StrictVersion(min_version)
except ValueError:
return ExtensionVersionResult(
error_reason=ExtensionValidationError.UNPARSEABLE_REQUESTED_VERSION,
requested_extension_version=min_version)
if parsed_min_version > HANDLER_VERSION:
return ExtensionVersionResult(
error_reason=ExtensionValidationError.OUTDATED_VERSION,
requested_extension_version=str(parsed_min_version))
return ExtensionVersionResult(
error_reason=None, requested_extension_version=min_version) | python | def _validate_min_version(min_version):
"""Validates the extension version matches the requested version.
Args:
min_version: Minimum version passed as a query param when establishing the
connection.
Returns:
An ExtensionVersionResult indicating validation status. If there is a
problem, the error_reason field will be non-empty.
"""
if min_version is not None:
try:
parsed_min_version = version.StrictVersion(min_version)
except ValueError:
return ExtensionVersionResult(
error_reason=ExtensionValidationError.UNPARSEABLE_REQUESTED_VERSION,
requested_extension_version=min_version)
if parsed_min_version > HANDLER_VERSION:
return ExtensionVersionResult(
error_reason=ExtensionValidationError.OUTDATED_VERSION,
requested_extension_version=str(parsed_min_version))
return ExtensionVersionResult(
error_reason=None, requested_extension_version=min_version) | [
"def",
"_validate_min_version",
"(",
"min_version",
")",
":",
"if",
"min_version",
"is",
"not",
"None",
":",
"try",
":",
"parsed_min_version",
"=",
"version",
".",
"StrictVersion",
"(",
"min_version",
")",
"except",
"ValueError",
":",
"return",
"ExtensionVersionRe... | Validates the extension version matches the requested version.
Args:
min_version: Minimum version passed as a query param when establishing the
connection.
Returns:
An ExtensionVersionResult indicating validation status. If there is a
problem, the error_reason field will be non-empty. | [
"Validates",
"the",
"extension",
"version",
"matches",
"the",
"requested",
"version",
"."
] | 21fe278cae6fca4e6c92f92d6d786fae8fdea9b1 | https://github.com/googlecolab/jupyter_http_over_ws/blob/21fe278cae6fca4e6c92f92d6d786fae8fdea9b1/jupyter_http_over_ws/handlers.py#L76-L101 | train | 34,478 |
googlecolab/jupyter_http_over_ws | jupyter_http_over_ws/handlers.py | _StreamingResponseEmitter.streaming_callback | def streaming_callback(self, body_part):
"""Handles a streaming chunk of the response.
The streaming_response callback gives no indication about whether the
received chunk is the last in the stream. The "last_response" instance
variable allows us to keep track of the last received chunk of the
response. Each time this is called, the previous chunk is emitted. The
done() method is expected to be called after the response completes to
ensure that the last piece of data is sent.
Args:
body_part: A chunk of the streaming response.
"""
b64_body_string = base64.b64encode(body_part).decode('utf-8')
response = {
'message_id': self._message_id,
'data': b64_body_string,
}
if self._last_response is None:
# This represents the first chunk of data to be streamed to the caller.
# Attach status and header information to this item.
response.update(self._generate_metadata_body())
else:
self._last_response['done'] = False
self._write_message_func(self._last_response)
self._last_response = response | python | def streaming_callback(self, body_part):
"""Handles a streaming chunk of the response.
The streaming_response callback gives no indication about whether the
received chunk is the last in the stream. The "last_response" instance
variable allows us to keep track of the last received chunk of the
response. Each time this is called, the previous chunk is emitted. The
done() method is expected to be called after the response completes to
ensure that the last piece of data is sent.
Args:
body_part: A chunk of the streaming response.
"""
b64_body_string = base64.b64encode(body_part).decode('utf-8')
response = {
'message_id': self._message_id,
'data': b64_body_string,
}
if self._last_response is None:
# This represents the first chunk of data to be streamed to the caller.
# Attach status and header information to this item.
response.update(self._generate_metadata_body())
else:
self._last_response['done'] = False
self._write_message_func(self._last_response)
self._last_response = response | [
"def",
"streaming_callback",
"(",
"self",
",",
"body_part",
")",
":",
"b64_body_string",
"=",
"base64",
".",
"b64encode",
"(",
"body_part",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"response",
"=",
"{",
"'message_id'",
":",
"self",
".",
"_message_id",
",",
... | Handles a streaming chunk of the response.
The streaming_response callback gives no indication about whether the
received chunk is the last in the stream. The "last_response" instance
variable allows us to keep track of the last received chunk of the
response. Each time this is called, the previous chunk is emitted. The
done() method is expected to be called after the response completes to
ensure that the last piece of data is sent.
Args:
body_part: A chunk of the streaming response. | [
"Handles",
"a",
"streaming",
"chunk",
"of",
"the",
"response",
"."
] | 21fe278cae6fca4e6c92f92d6d786fae8fdea9b1 | https://github.com/googlecolab/jupyter_http_over_ws/blob/21fe278cae6fca4e6c92f92d6d786fae8fdea9b1/jupyter_http_over_ws/handlers.py#L261-L288 | train | 34,479 |
kennethreitz/env | env.py | lower_dict | def lower_dict(d):
"""Lower cases string keys in given dict."""
_d = {}
for k, v in d.items():
try:
_d[k.lower()] = v
except AttributeError:
_d[k] = v
return _d | python | def lower_dict(d):
"""Lower cases string keys in given dict."""
_d = {}
for k, v in d.items():
try:
_d[k.lower()] = v
except AttributeError:
_d[k] = v
return _d | [
"def",
"lower_dict",
"(",
"d",
")",
":",
"_d",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"d",
".",
"items",
"(",
")",
":",
"try",
":",
"_d",
"[",
"k",
".",
"lower",
"(",
")",
"]",
"=",
"v",
"except",
"AttributeError",
":",
"_d",
"[",
"k",
... | Lower cases string keys in given dict. | [
"Lower",
"cases",
"string",
"keys",
"in",
"given",
"dict",
"."
] | de639fe021c6a42a99f8458ebb90a01c0c4085d7 | https://github.com/kennethreitz/env/blob/de639fe021c6a42a99f8458ebb90a01c0c4085d7/env.py#L10-L21 | train | 34,480 |
kennethreitz/env | env.py | urlparse | def urlparse(d, keys=None):
"""Returns a copy of the given dictionary with url values parsed."""
d = d.copy()
if keys is None:
keys = d.keys()
for key in keys:
d[key] = _urlparse(d[key])
return d | python | def urlparse(d, keys=None):
"""Returns a copy of the given dictionary with url values parsed."""
d = d.copy()
if keys is None:
keys = d.keys()
for key in keys:
d[key] = _urlparse(d[key])
return d | [
"def",
"urlparse",
"(",
"d",
",",
"keys",
"=",
"None",
")",
":",
"d",
"=",
"d",
".",
"copy",
"(",
")",
"if",
"keys",
"is",
"None",
":",
"keys",
"=",
"d",
".",
"keys",
"(",
")",
"for",
"key",
"in",
"keys",
":",
"d",
"[",
"key",
"]",
"=",
"... | Returns a copy of the given dictionary with url values parsed. | [
"Returns",
"a",
"copy",
"of",
"the",
"given",
"dictionary",
"with",
"url",
"values",
"parsed",
"."
] | de639fe021c6a42a99f8458ebb90a01c0c4085d7 | https://github.com/kennethreitz/env/blob/de639fe021c6a42a99f8458ebb90a01c0c4085d7/env.py#L24-L35 | train | 34,481 |
kennethreitz/env | env.py | prefix | def prefix(prefix):
"""Returns a dictionary of all environment variables starting with
the given prefix, lower cased and stripped.
"""
d = {}
e = lower_dict(environ.copy())
prefix = prefix.lower()
for k, v in e.items():
try:
if k.startswith(prefix):
k = k[len(prefix):]
d[k] = v
except AttributeError:
pass
return d | python | def prefix(prefix):
"""Returns a dictionary of all environment variables starting with
the given prefix, lower cased and stripped.
"""
d = {}
e = lower_dict(environ.copy())
prefix = prefix.lower()
for k, v in e.items():
try:
if k.startswith(prefix):
k = k[len(prefix):]
d[k] = v
except AttributeError:
pass
return d | [
"def",
"prefix",
"(",
"prefix",
")",
":",
"d",
"=",
"{",
"}",
"e",
"=",
"lower_dict",
"(",
"environ",
".",
"copy",
"(",
")",
")",
"prefix",
"=",
"prefix",
".",
"lower",
"(",
")",
"for",
"k",
",",
"v",
"in",
"e",
".",
"items",
"(",
")",
":",
... | Returns a dictionary of all environment variables starting with
the given prefix, lower cased and stripped. | [
"Returns",
"a",
"dictionary",
"of",
"all",
"environment",
"variables",
"starting",
"with",
"the",
"given",
"prefix",
"lower",
"cased",
"and",
"stripped",
"."
] | de639fe021c6a42a99f8458ebb90a01c0c4085d7 | https://github.com/kennethreitz/env/blob/de639fe021c6a42a99f8458ebb90a01c0c4085d7/env.py#L38-L56 | train | 34,482 |
kennethreitz/env | env.py | map | def map(**kwargs):
"""Returns a dictionary of the given keyword arguments mapped to their
values from the environment, with input keys lower cased.
"""
d = {}
e = lower_dict(environ.copy())
for k, v in kwargs.items():
d[k] = e.get(v.lower())
return d | python | def map(**kwargs):
"""Returns a dictionary of the given keyword arguments mapped to their
values from the environment, with input keys lower cased.
"""
d = {}
e = lower_dict(environ.copy())
for k, v in kwargs.items():
d[k] = e.get(v.lower())
return d | [
"def",
"map",
"(",
"*",
"*",
"kwargs",
")",
":",
"d",
"=",
"{",
"}",
"e",
"=",
"lower_dict",
"(",
"environ",
".",
"copy",
"(",
")",
")",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"d",
"[",
"k",
"]",
"=",
"e",
".",... | Returns a dictionary of the given keyword arguments mapped to their
values from the environment, with input keys lower cased. | [
"Returns",
"a",
"dictionary",
"of",
"the",
"given",
"keyword",
"arguments",
"mapped",
"to",
"their",
"values",
"from",
"the",
"environment",
"with",
"input",
"keys",
"lower",
"cased",
"."
] | de639fe021c6a42a99f8458ebb90a01c0c4085d7 | https://github.com/kennethreitz/env/blob/de639fe021c6a42a99f8458ebb90a01c0c4085d7/env.py#L59-L70 | train | 34,483 |
masfaraud/BMSpy | bms/core.py | Load | def Load(file):
""" Loads a model from specified file """
with open(file, 'rb') as file:
model = dill.load(file)
return model | python | def Load(file):
""" Loads a model from specified file """
with open(file, 'rb') as file:
model = dill.load(file)
return model | [
"def",
"Load",
"(",
"file",
")",
":",
"with",
"open",
"(",
"file",
",",
"'rb'",
")",
"as",
"file",
":",
"model",
"=",
"dill",
".",
"load",
"(",
"file",
")",
"return",
"model"
] | Loads a model from specified file | [
"Loads",
"a",
"model",
"from",
"specified",
"file"
] | 5ac6b9539c1141dd955560afb532e6b915b77bdc | https://github.com/masfaraud/BMSpy/blob/5ac6b9539c1141dd955560afb532e6b915b77bdc/bms/core.py#L555-L559 | train | 34,484 |
masfaraud/BMSpy | bms/core.py | Block._AddInput | def _AddInput(self, variable):
"""
Add one more variable as an input of the block
:param variable: variable (or signal as it is also a variable)
"""
if isinstance(variable, Variable):
self.inputs.append(variable)
else:
print('Error: ', variable.name, variable,
' given is not a variable')
raise TypeError | python | def _AddInput(self, variable):
"""
Add one more variable as an input of the block
:param variable: variable (or signal as it is also a variable)
"""
if isinstance(variable, Variable):
self.inputs.append(variable)
else:
print('Error: ', variable.name, variable,
' given is not a variable')
raise TypeError | [
"def",
"_AddInput",
"(",
"self",
",",
"variable",
")",
":",
"if",
"isinstance",
"(",
"variable",
",",
"Variable",
")",
":",
"self",
".",
"inputs",
".",
"append",
"(",
"variable",
")",
"else",
":",
"print",
"(",
"'Error: '",
",",
"variable",
".",
"name"... | Add one more variable as an input of the block
:param variable: variable (or signal as it is also a variable) | [
"Add",
"one",
"more",
"variable",
"as",
"an",
"input",
"of",
"the",
"block"
] | 5ac6b9539c1141dd955560afb532e6b915b77bdc | https://github.com/masfaraud/BMSpy/blob/5ac6b9539c1141dd955560afb532e6b915b77bdc/bms/core.py#L118-L129 | train | 34,485 |
masfaraud/BMSpy | bms/core.py | Block._AddOutput | def _AddOutput(self, variable):
"""
Add one more variable as an output of the block
:param variable: variable (or signal as it is also a variable)
"""
if isinstance(variable, Variable):
self.outputs.append(variable)
else:
print(variable)
raise TypeError | python | def _AddOutput(self, variable):
"""
Add one more variable as an output of the block
:param variable: variable (or signal as it is also a variable)
"""
if isinstance(variable, Variable):
self.outputs.append(variable)
else:
print(variable)
raise TypeError | [
"def",
"_AddOutput",
"(",
"self",
",",
"variable",
")",
":",
"if",
"isinstance",
"(",
"variable",
",",
"Variable",
")",
":",
"self",
".",
"outputs",
".",
"append",
"(",
"variable",
")",
"else",
":",
"print",
"(",
"variable",
")",
"raise",
"TypeError"
] | Add one more variable as an output of the block
:param variable: variable (or signal as it is also a variable) | [
"Add",
"one",
"more",
"variable",
"as",
"an",
"output",
"of",
"the",
"block"
] | 5ac6b9539c1141dd955560afb532e6b915b77bdc | https://github.com/masfaraud/BMSpy/blob/5ac6b9539c1141dd955560afb532e6b915b77bdc/bms/core.py#L131-L141 | train | 34,486 |
masfaraud/BMSpy | bms/core.py | Block.InputValues | def InputValues(self, it, nsteps=None):
"""
Returns the input values at a given iteration for solving the block outputs
"""
if nsteps == None:
nsteps = self.max_input_order
# print(self,it)
# Provides values in inputs values for computing at iteration it
I = np.zeros((self.n_inputs, nsteps))
for iv, variable in enumerate(self.inputs):
# print(it-self.max_input_order+1,it+1)
# print(variable._values[it-self.max_input_order+1:it+1])
I[iv, :] = variable._values[it-nsteps+1:it+1]
return I | python | def InputValues(self, it, nsteps=None):
"""
Returns the input values at a given iteration for solving the block outputs
"""
if nsteps == None:
nsteps = self.max_input_order
# print(self,it)
# Provides values in inputs values for computing at iteration it
I = np.zeros((self.n_inputs, nsteps))
for iv, variable in enumerate(self.inputs):
# print(it-self.max_input_order+1,it+1)
# print(variable._values[it-self.max_input_order+1:it+1])
I[iv, :] = variable._values[it-nsteps+1:it+1]
return I | [
"def",
"InputValues",
"(",
"self",
",",
"it",
",",
"nsteps",
"=",
"None",
")",
":",
"if",
"nsteps",
"==",
"None",
":",
"nsteps",
"=",
"self",
".",
"max_input_order",
"# print(self,it)",
"# Provides values in inputs values for computing at iteration it",
"I",
... | Returns the input values at a given iteration for solving the block outputs | [
"Returns",
"the",
"input",
"values",
"at",
"a",
"given",
"iteration",
"for",
"solving",
"the",
"block",
"outputs"
] | 5ac6b9539c1141dd955560afb532e6b915b77bdc | https://github.com/masfaraud/BMSpy/blob/5ac6b9539c1141dd955560afb532e6b915b77bdc/bms/core.py#L143-L156 | train | 34,487 |
masfaraud/BMSpy | bms/core.py | DynamicSystem._AddVariable | def _AddVariable(self, variable):
"""
Add a variable to the model. Should not be used by end-user
"""
if isinstance(variable, Signal):
if not variable in self.signals:
self.signals.append(variable)
elif isinstance(variable, Variable):
if not variable in self.variables:
self.variables.append(variable)
else:
raise TypeError
self._utd_graph = False | python | def _AddVariable(self, variable):
"""
Add a variable to the model. Should not be used by end-user
"""
if isinstance(variable, Signal):
if not variable in self.signals:
self.signals.append(variable)
elif isinstance(variable, Variable):
if not variable in self.variables:
self.variables.append(variable)
else:
raise TypeError
self._utd_graph = False | [
"def",
"_AddVariable",
"(",
"self",
",",
"variable",
")",
":",
"if",
"isinstance",
"(",
"variable",
",",
"Signal",
")",
":",
"if",
"not",
"variable",
"in",
"self",
".",
"signals",
":",
"self",
".",
"signals",
".",
"append",
"(",
"variable",
")",
"elif"... | Add a variable to the model. Should not be used by end-user | [
"Add",
"a",
"variable",
"to",
"the",
"model",
".",
"Should",
"not",
"be",
"used",
"by",
"end",
"-",
"user"
] | 5ac6b9539c1141dd955560afb532e6b915b77bdc | https://github.com/masfaraud/BMSpy/blob/5ac6b9539c1141dd955560afb532e6b915b77bdc/bms/core.py#L222-L234 | train | 34,488 |
masfaraud/BMSpy | bms/core.py | DynamicSystem.VariablesValues | def VariablesValues(self, variables, t):
"""
Returns the value of given variables at time t.
Linear interpolation is performed between two time steps.
:param variables: one variable or a list of variables
:param t: time of evaluation
"""
# TODO: put interpolation in variables
if (t < self.te) | (t > 0):
i = t//self.ts # time step
ti = self.ts*i
if type(variables) == list:
values = []
for variable in variables:
# interpolation
values.append(
variables.values[i]*((ti-t)/self.ts+1)+variables.values[i+1]*(t-ti)/self.ts)
return values
else:
# interpolation
return variables.values[i]*((ti-t)/self.ts+1)+variables.values[i+1]*(t-ti)/self.ts
else:
raise ValueError | python | def VariablesValues(self, variables, t):
"""
Returns the value of given variables at time t.
Linear interpolation is performed between two time steps.
:param variables: one variable or a list of variables
:param t: time of evaluation
"""
# TODO: put interpolation in variables
if (t < self.te) | (t > 0):
i = t//self.ts # time step
ti = self.ts*i
if type(variables) == list:
values = []
for variable in variables:
# interpolation
values.append(
variables.values[i]*((ti-t)/self.ts+1)+variables.values[i+1]*(t-ti)/self.ts)
return values
else:
# interpolation
return variables.values[i]*((ti-t)/self.ts+1)+variables.values[i+1]*(t-ti)/self.ts
else:
raise ValueError | [
"def",
"VariablesValues",
"(",
"self",
",",
"variables",
",",
"t",
")",
":",
"# TODO: put interpolation in variables",
"if",
"(",
"t",
"<",
"self",
".",
"te",
")",
"|",
"(",
"t",
">",
"0",
")",
":",
"i",
"=",
"t",
"//",
"self",
".",
"ts",
"# time ste... | Returns the value of given variables at time t.
Linear interpolation is performed between two time steps.
:param variables: one variable or a list of variables
:param t: time of evaluation | [
"Returns",
"the",
"value",
"of",
"given",
"variables",
"at",
"time",
"t",
".",
"Linear",
"interpolation",
"is",
"performed",
"between",
"two",
"time",
"steps",
"."
] | 5ac6b9539c1141dd955560afb532e6b915b77bdc | https://github.com/masfaraud/BMSpy/blob/5ac6b9539c1141dd955560afb532e6b915b77bdc/bms/core.py#L488-L512 | train | 34,489 |
skorokithakis/django-annoying | annoying/fields.py | JSONField.to_python | def to_python(self, value):
"""
Convert a string from the database to a Python value.
"""
if value == "":
return None
try:
if isinstance(value, six.string_types):
return self.deserializer(value)
elif isinstance(value, bytes):
return self.deserializer(value.decode('utf8'))
except ValueError:
pass
return value | python | def to_python(self, value):
"""
Convert a string from the database to a Python value.
"""
if value == "":
return None
try:
if isinstance(value, six.string_types):
return self.deserializer(value)
elif isinstance(value, bytes):
return self.deserializer(value.decode('utf8'))
except ValueError:
pass
return value | [
"def",
"to_python",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"==",
"\"\"",
":",
"return",
"None",
"try",
":",
"if",
"isinstance",
"(",
"value",
",",
"six",
".",
"string_types",
")",
":",
"return",
"self",
".",
"deserializer",
"(",
"value",
... | Convert a string from the database to a Python value. | [
"Convert",
"a",
"string",
"from",
"the",
"database",
"to",
"a",
"Python",
"value",
"."
] | 712df5da610f654326d19bbe123726658a1a39c4 | https://github.com/skorokithakis/django-annoying/blob/712df5da610f654326d19bbe123726658a1a39c4/annoying/fields.py#L107-L121 | train | 34,490 |
skorokithakis/django-annoying | annoying/fields.py | JSONField.get_prep_value | def get_prep_value(self, value):
"""
Convert the value to a string so it can be stored in the database.
"""
if value == "":
return None
if isinstance(value, (dict, list)):
return self.serializer(value)
return super(JSONField, self).get_prep_value(value) | python | def get_prep_value(self, value):
"""
Convert the value to a string so it can be stored in the database.
"""
if value == "":
return None
if isinstance(value, (dict, list)):
return self.serializer(value)
return super(JSONField, self).get_prep_value(value) | [
"def",
"get_prep_value",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"==",
"\"\"",
":",
"return",
"None",
"if",
"isinstance",
"(",
"value",
",",
"(",
"dict",
",",
"list",
")",
")",
":",
"return",
"self",
".",
"serializer",
"(",
"value",
")",
... | Convert the value to a string so it can be stored in the database. | [
"Convert",
"the",
"value",
"to",
"a",
"string",
"so",
"it",
"can",
"be",
"stored",
"in",
"the",
"database",
"."
] | 712df5da610f654326d19bbe123726658a1a39c4 | https://github.com/skorokithakis/django-annoying/blob/712df5da610f654326d19bbe123726658a1a39c4/annoying/fields.py#L123-L131 | train | 34,491 |
skorokithakis/django-annoying | annoying/decorators.py | render_to | def render_to(template=None, content_type=None):
"""
Decorator for Django views that sends returned dict to render_to_response
function.
Template name can be decorator parameter or TEMPLATE item in returned
dictionary. RequestContext always added as context instance.
If view doesn't return dict then decorator simply returns output.
Parameters:
- template: template name to use
- content_type: content type to send in response headers
Examples:
# 1. Template name in decorator parameters
@render_to('template.html')
def foo(request):
bar = Bar.object.all()
return {'bar': bar}
# equals to
def foo(request):
bar = Bar.object.all()
return render_to_response('template.html',
{'bar': bar},
context_instance=RequestContext(request))
# 2. Template name as TEMPLATE item value in return dictionary.
if TEMPLATE is given then its value will have higher priority
than render_to argument.
@render_to()
def foo(request, category):
template_name = '%s.html' % category
return {'bar': bar, 'TEMPLATE': template_name}
#equals to
def foo(request, category):
template_name = '%s.html' % category
return render_to_response(template_name,
{'bar': bar},
context_instance=RequestContext(request))
"""
def renderer(function):
@wraps(function)
def wrapper(request, *args, **kwargs):
output = function(request, *args, **kwargs)
if not isinstance(output, dict):
return output
tmpl = output.pop('TEMPLATE', template)
if tmpl is None:
template_dir = os.path.join(*function.__module__.split('.')[:-1])
tmpl = os.path.join(template_dir, function.func_name + ".html")
# Explicit version check to avoid swallowing other exceptions
if DJANGO_VERSION >= (1, 9):
return render(request, tmpl, output,
content_type=content_type)
else:
return render_to_response(tmpl, output,
context_instance=RequestContext(request),
content_type=content_type)
return wrapper
return renderer | python | def render_to(template=None, content_type=None):
"""
Decorator for Django views that sends returned dict to render_to_response
function.
Template name can be decorator parameter or TEMPLATE item in returned
dictionary. RequestContext always added as context instance.
If view doesn't return dict then decorator simply returns output.
Parameters:
- template: template name to use
- content_type: content type to send in response headers
Examples:
# 1. Template name in decorator parameters
@render_to('template.html')
def foo(request):
bar = Bar.object.all()
return {'bar': bar}
# equals to
def foo(request):
bar = Bar.object.all()
return render_to_response('template.html',
{'bar': bar},
context_instance=RequestContext(request))
# 2. Template name as TEMPLATE item value in return dictionary.
if TEMPLATE is given then its value will have higher priority
than render_to argument.
@render_to()
def foo(request, category):
template_name = '%s.html' % category
return {'bar': bar, 'TEMPLATE': template_name}
#equals to
def foo(request, category):
template_name = '%s.html' % category
return render_to_response(template_name,
{'bar': bar},
context_instance=RequestContext(request))
"""
def renderer(function):
@wraps(function)
def wrapper(request, *args, **kwargs):
output = function(request, *args, **kwargs)
if not isinstance(output, dict):
return output
tmpl = output.pop('TEMPLATE', template)
if tmpl is None:
template_dir = os.path.join(*function.__module__.split('.')[:-1])
tmpl = os.path.join(template_dir, function.func_name + ".html")
# Explicit version check to avoid swallowing other exceptions
if DJANGO_VERSION >= (1, 9):
return render(request, tmpl, output,
content_type=content_type)
else:
return render_to_response(tmpl, output,
context_instance=RequestContext(request),
content_type=content_type)
return wrapper
return renderer | [
"def",
"render_to",
"(",
"template",
"=",
"None",
",",
"content_type",
"=",
"None",
")",
":",
"def",
"renderer",
"(",
"function",
")",
":",
"@",
"wraps",
"(",
"function",
")",
"def",
"wrapper",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs... | Decorator for Django views that sends returned dict to render_to_response
function.
Template name can be decorator parameter or TEMPLATE item in returned
dictionary. RequestContext always added as context instance.
If view doesn't return dict then decorator simply returns output.
Parameters:
- template: template name to use
- content_type: content type to send in response headers
Examples:
# 1. Template name in decorator parameters
@render_to('template.html')
def foo(request):
bar = Bar.object.all()
return {'bar': bar}
# equals to
def foo(request):
bar = Bar.object.all()
return render_to_response('template.html',
{'bar': bar},
context_instance=RequestContext(request))
# 2. Template name as TEMPLATE item value in return dictionary.
if TEMPLATE is given then its value will have higher priority
than render_to argument.
@render_to()
def foo(request, category):
template_name = '%s.html' % category
return {'bar': bar, 'TEMPLATE': template_name}
#equals to
def foo(request, category):
template_name = '%s.html' % category
return render_to_response(template_name,
{'bar': bar},
context_instance=RequestContext(request)) | [
"Decorator",
"for",
"Django",
"views",
"that",
"sends",
"returned",
"dict",
"to",
"render_to_response",
"function",
"."
] | 712df5da610f654326d19bbe123726658a1a39c4 | https://github.com/skorokithakis/django-annoying/blob/712df5da610f654326d19bbe123726658a1a39c4/annoying/decorators.py#L18-L83 | train | 34,492 |
skorokithakis/django-annoying | annoying/decorators.py | ajax_request | def ajax_request(func):
"""
If view returned serializable dict, returns response in a format requested
by HTTP_ACCEPT header. Defaults to JSON if none requested or match.
Currently supports JSON or YAML (if installed), but can easily be extended.
example:
@ajax_request
def my_view(request):
news = News.objects.all()
news_titles = [entry.title for entry in news]
return {'news_titles': news_titles}
"""
@wraps(func)
def wrapper(request, *args, **kwargs):
for accepted_type in request.META.get('HTTP_ACCEPT', '').split(','):
if accepted_type in FORMAT_TYPES.keys():
format_type = accepted_type
break
else:
format_type = 'application/json'
response = func(request, *args, **kwargs)
if not isinstance(response, HttpResponse):
if hasattr(settings, 'FORMAT_TYPES'):
format_type_handler = settings.FORMAT_TYPES[format_type]
if hasattr(format_type_handler, '__call__'):
data = format_type_handler(response)
elif isinstance(format_type_handler, six.string_types):
mod_name, func_name = format_type_handler.rsplit('.', 1)
module = __import__(mod_name, fromlist=[func_name])
function = getattr(module, func_name)
data = function(response)
else:
data = FORMAT_TYPES[format_type](response)
response = HttpResponse(data, content_type=format_type)
response['content-length'] = len(data)
return response
return wrapper | python | def ajax_request(func):
"""
If view returned serializable dict, returns response in a format requested
by HTTP_ACCEPT header. Defaults to JSON if none requested or match.
Currently supports JSON or YAML (if installed), but can easily be extended.
example:
@ajax_request
def my_view(request):
news = News.objects.all()
news_titles = [entry.title for entry in news]
return {'news_titles': news_titles}
"""
@wraps(func)
def wrapper(request, *args, **kwargs):
for accepted_type in request.META.get('HTTP_ACCEPT', '').split(','):
if accepted_type in FORMAT_TYPES.keys():
format_type = accepted_type
break
else:
format_type = 'application/json'
response = func(request, *args, **kwargs)
if not isinstance(response, HttpResponse):
if hasattr(settings, 'FORMAT_TYPES'):
format_type_handler = settings.FORMAT_TYPES[format_type]
if hasattr(format_type_handler, '__call__'):
data = format_type_handler(response)
elif isinstance(format_type_handler, six.string_types):
mod_name, func_name = format_type_handler.rsplit('.', 1)
module = __import__(mod_name, fromlist=[func_name])
function = getattr(module, func_name)
data = function(response)
else:
data = FORMAT_TYPES[format_type](response)
response = HttpResponse(data, content_type=format_type)
response['content-length'] = len(data)
return response
return wrapper | [
"def",
"ajax_request",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"accepted_type",
"in",
"request",
".",
"META",
".",
"get",
"(",
"'HTTP_ACCEPT'... | If view returned serializable dict, returns response in a format requested
by HTTP_ACCEPT header. Defaults to JSON if none requested or match.
Currently supports JSON or YAML (if installed), but can easily be extended.
example:
@ajax_request
def my_view(request):
news = News.objects.all()
news_titles = [entry.title for entry in news]
return {'news_titles': news_titles} | [
"If",
"view",
"returned",
"serializable",
"dict",
"returns",
"response",
"in",
"a",
"format",
"requested",
"by",
"HTTP_ACCEPT",
"header",
".",
"Defaults",
"to",
"JSON",
"if",
"none",
"requested",
"or",
"match",
"."
] | 712df5da610f654326d19bbe123726658a1a39c4 | https://github.com/skorokithakis/django-annoying/blob/712df5da610f654326d19bbe123726658a1a39c4/annoying/decorators.py#L167-L206 | train | 34,493 |
skorokithakis/django-annoying | annoying/decorators.py | autostrip | def autostrip(cls):
"""
strip text fields before validation
example:
@autostrip
class PersonForm(forms.Form):
name = forms.CharField(min_length=2, max_length=10)
email = forms.EmailField()
Author: nail.xx
"""
warnings.warn(
"django-annoying autostrip is deprecated and will be removed in a "
"future version. Django now has native support for stripping form "
"fields. "
"https://docs.djangoproject.com/en/stable/ref/forms/fields/#django.forms.CharField.strip",
DeprecationWarning,
stacklevel=2,
)
fields = [(key, value) for key, value in cls.base_fields.items() if isinstance(value, forms.CharField)]
for field_name, field_object in fields:
def get_clean_func(original_clean):
return lambda value: original_clean(value and value.strip())
clean_func = get_clean_func(getattr(field_object, 'clean'))
setattr(field_object, 'clean', clean_func)
return cls | python | def autostrip(cls):
"""
strip text fields before validation
example:
@autostrip
class PersonForm(forms.Form):
name = forms.CharField(min_length=2, max_length=10)
email = forms.EmailField()
Author: nail.xx
"""
warnings.warn(
"django-annoying autostrip is deprecated and will be removed in a "
"future version. Django now has native support for stripping form "
"fields. "
"https://docs.djangoproject.com/en/stable/ref/forms/fields/#django.forms.CharField.strip",
DeprecationWarning,
stacklevel=2,
)
fields = [(key, value) for key, value in cls.base_fields.items() if isinstance(value, forms.CharField)]
for field_name, field_object in fields:
def get_clean_func(original_clean):
return lambda value: original_clean(value and value.strip())
clean_func = get_clean_func(getattr(field_object, 'clean'))
setattr(field_object, 'clean', clean_func)
return cls | [
"def",
"autostrip",
"(",
"cls",
")",
":",
"warnings",
".",
"warn",
"(",
"\"django-annoying autostrip is deprecated and will be removed in a \"",
"\"future version. Django now has native support for stripping form \"",
"\"fields. \"",
"\"https://docs.djangoproject.com/en/stable/ref/forms/fi... | strip text fields before validation
example:
@autostrip
class PersonForm(forms.Form):
name = forms.CharField(min_length=2, max_length=10)
email = forms.EmailField()
Author: nail.xx | [
"strip",
"text",
"fields",
"before",
"validation"
] | 712df5da610f654326d19bbe123726658a1a39c4 | https://github.com/skorokithakis/django-annoying/blob/712df5da610f654326d19bbe123726658a1a39c4/annoying/decorators.py#L209-L235 | train | 34,494 |
xtacocorex/CHIP_IO | distribute_setup.py | _patch_file | def _patch_file(path, content):
"""Will backup the file then patch it"""
f = open(path)
existing_content = f.read()
f.close()
if existing_content == content:
# already patched
log.warn('Already patched.')
return False
log.warn('Patching...')
_rename_path(path)
f = open(path, 'w')
try:
f.write(content)
finally:
f.close()
return True | python | def _patch_file(path, content):
"""Will backup the file then patch it"""
f = open(path)
existing_content = f.read()
f.close()
if existing_content == content:
# already patched
log.warn('Already patched.')
return False
log.warn('Patching...')
_rename_path(path)
f = open(path, 'w')
try:
f.write(content)
finally:
f.close()
return True | [
"def",
"_patch_file",
"(",
"path",
",",
"content",
")",
":",
"f",
"=",
"open",
"(",
"path",
")",
"existing_content",
"=",
"f",
".",
"read",
"(",
")",
"f",
".",
"close",
"(",
")",
"if",
"existing_content",
"==",
"content",
":",
"# already patched",
"log... | Will backup the file then patch it | [
"Will",
"backup",
"the",
"file",
"then",
"patch",
"it"
] | 84df4376f83bb4de2b4e2f77447cb75704ebdaf4 | https://github.com/xtacocorex/CHIP_IO/blob/84df4376f83bb4de2b4e2f77447cb75704ebdaf4/distribute_setup.py#L250-L266 | train | 34,495 |
xtacocorex/CHIP_IO | CHIP_IO/OverlayManager.py | _set_overlay_verify | def _set_overlay_verify(name, overlay_path, config_path):
"""
_set_overlay_verify - Function to load the overlay and verify it was setup properly
"""
global DEBUG
# VERIFY PATH IS NOT THERE
if os.path.exists(config_path):
print("Config path already exists! Not moving forward")
print("config_path: {0}".format(config_path))
return -1
# MAKE THE CONFIGURATION PATH
os.makedirs(config_path)
# CAT THE OVERLAY INTO THE CONFIG FILESYSTEM
with open(config_path + "/dtbo", 'wb') as outfile:
with open(overlay_path, 'rb') as infile:
shutil.copyfileobj(infile, outfile)
# SLEEP TO ENABLE THE KERNEL TO DO ITS JOB
time.sleep(0.2)
# VERIFY
if name == "CUST":
# BLINDLY ACCEPT THAT IT LOADED
return 0
elif name == "PWM0":
if os.path.exists(PWMSYSFSPATH):
if DEBUG:
print("PWM IS LOADED!")
return 0
else:
if DEBUG:
print("ERROR LOAIDNG PWM0")
return 1
elif name == "SPI2":
if os.listdir(SPI2SYSFSPATH) != "":
if DEBUG:
print("SPI2 IS LOADED!")
return 0
else:
if DEBUG:
print("ERROR LOADING SPI2")
return 0 | python | def _set_overlay_verify(name, overlay_path, config_path):
"""
_set_overlay_verify - Function to load the overlay and verify it was setup properly
"""
global DEBUG
# VERIFY PATH IS NOT THERE
if os.path.exists(config_path):
print("Config path already exists! Not moving forward")
print("config_path: {0}".format(config_path))
return -1
# MAKE THE CONFIGURATION PATH
os.makedirs(config_path)
# CAT THE OVERLAY INTO THE CONFIG FILESYSTEM
with open(config_path + "/dtbo", 'wb') as outfile:
with open(overlay_path, 'rb') as infile:
shutil.copyfileobj(infile, outfile)
# SLEEP TO ENABLE THE KERNEL TO DO ITS JOB
time.sleep(0.2)
# VERIFY
if name == "CUST":
# BLINDLY ACCEPT THAT IT LOADED
return 0
elif name == "PWM0":
if os.path.exists(PWMSYSFSPATH):
if DEBUG:
print("PWM IS LOADED!")
return 0
else:
if DEBUG:
print("ERROR LOAIDNG PWM0")
return 1
elif name == "SPI2":
if os.listdir(SPI2SYSFSPATH) != "":
if DEBUG:
print("SPI2 IS LOADED!")
return 0
else:
if DEBUG:
print("ERROR LOADING SPI2")
return 0 | [
"def",
"_set_overlay_verify",
"(",
"name",
",",
"overlay_path",
",",
"config_path",
")",
":",
"global",
"DEBUG",
"# VERIFY PATH IS NOT THERE",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"config_path",
")",
":",
"print",
"(",
"\"Config path already exists! Not movi... | _set_overlay_verify - Function to load the overlay and verify it was setup properly | [
"_set_overlay_verify",
"-",
"Function",
"to",
"load",
"the",
"overlay",
"and",
"verify",
"it",
"was",
"setup",
"properly"
] | 84df4376f83bb4de2b4e2f77447cb75704ebdaf4 | https://github.com/xtacocorex/CHIP_IO/blob/84df4376f83bb4de2b4e2f77447cb75704ebdaf4/CHIP_IO/OverlayManager.py#L87-L130 | train | 34,496 |
xtacocorex/CHIP_IO | CHIP_IO/OverlayManager.py | load | def load(overlay, path=""):
"""
load - Load a DTB Overlay
Inputs:
overlay - Overlay Key: SPI2, PWM0, CUST
path - Full Path to where the custom overlay is stored
Returns:
0 - Successful Load
1 - Unsuccessful Load
2 - Overlay was previously set
"""
global DEBUG
global _LOADED
if DEBUG:
print("LOAD OVERLAY: {0} @ {1}".format(overlay,path))
# SEE IF OUR OVERLAY NAME IS IN THE KEYS
if overlay.upper() in _OVERLAYS.keys():
cpath = OVERLAYCONFIGPATH + "/" + _FOLDERS[overlay.upper()]
if DEBUG:
print("VALID OVERLAY")
print("CONFIG PATH: {0}".format(cpath))
# CHECK TO SEE IF WE HAVE A PATH FOR CUSTOM OVERLAY
if overlay.upper() == "CUST" and path == "":
raise ValueError("Path must be specified for Custom Overlay Choice")
elif overlay.upper() == "CUST" and _LOADED[overlay.upper()]:
print("Custom Overlay already loaded")
return 2
elif overlay.upper() == "CUST" and not os.path.exists(path):
print("Custom Overlay path does not exist")
return 1
# DETERMINE IF WE ARE A CHIP PRO AND WE ARE COMMANDED TO LOAD PWM0
if is_chip_pro() and overlay.upper() == "PWM0":
print("CHIP Pro supports PWM0 in base DTB, exiting")
return 1
# SET UP THE OVERLAY PATH FOR OUR USE
if overlay.upper() != "CUST":
opath = OVERLAYINSTALLPATH
opath += "/" + _OVERLAYS[overlay.upper()]
else:
opath = path
if DEBUG:
print("OVERLAY PATH: {0}".format(opath))
if overlay.upper() == "PWM0" and _LOADED[overlay.upper()]:
print("PWM0 Overlay already loaded")
return 2
if overlay.upper() == "SPI2" and _LOADED[overlay.upper()]:
print("SPI2 Overlay already loaded")
return 2
# LOAD THE OVERLAY
errc = _set_overlay_verify(overlay.upper(), opath, cpath)
if DEBUG:
print("_SET_OVERLAY_VERIFY ERRC: {0}".format(errc))
if errc == 0:
_LOADED[overlay.upper()] = True
else:
raise ValueError("Invalid Overlay name specified! Choose between: SPI2, PWM0, CUST") | python | def load(overlay, path=""):
"""
load - Load a DTB Overlay
Inputs:
overlay - Overlay Key: SPI2, PWM0, CUST
path - Full Path to where the custom overlay is stored
Returns:
0 - Successful Load
1 - Unsuccessful Load
2 - Overlay was previously set
"""
global DEBUG
global _LOADED
if DEBUG:
print("LOAD OVERLAY: {0} @ {1}".format(overlay,path))
# SEE IF OUR OVERLAY NAME IS IN THE KEYS
if overlay.upper() in _OVERLAYS.keys():
cpath = OVERLAYCONFIGPATH + "/" + _FOLDERS[overlay.upper()]
if DEBUG:
print("VALID OVERLAY")
print("CONFIG PATH: {0}".format(cpath))
# CHECK TO SEE IF WE HAVE A PATH FOR CUSTOM OVERLAY
if overlay.upper() == "CUST" and path == "":
raise ValueError("Path must be specified for Custom Overlay Choice")
elif overlay.upper() == "CUST" and _LOADED[overlay.upper()]:
print("Custom Overlay already loaded")
return 2
elif overlay.upper() == "CUST" and not os.path.exists(path):
print("Custom Overlay path does not exist")
return 1
# DETERMINE IF WE ARE A CHIP PRO AND WE ARE COMMANDED TO LOAD PWM0
if is_chip_pro() and overlay.upper() == "PWM0":
print("CHIP Pro supports PWM0 in base DTB, exiting")
return 1
# SET UP THE OVERLAY PATH FOR OUR USE
if overlay.upper() != "CUST":
opath = OVERLAYINSTALLPATH
opath += "/" + _OVERLAYS[overlay.upper()]
else:
opath = path
if DEBUG:
print("OVERLAY PATH: {0}".format(opath))
if overlay.upper() == "PWM0" and _LOADED[overlay.upper()]:
print("PWM0 Overlay already loaded")
return 2
if overlay.upper() == "SPI2" and _LOADED[overlay.upper()]:
print("SPI2 Overlay already loaded")
return 2
# LOAD THE OVERLAY
errc = _set_overlay_verify(overlay.upper(), opath, cpath)
if DEBUG:
print("_SET_OVERLAY_VERIFY ERRC: {0}".format(errc))
if errc == 0:
_LOADED[overlay.upper()] = True
else:
raise ValueError("Invalid Overlay name specified! Choose between: SPI2, PWM0, CUST") | [
"def",
"load",
"(",
"overlay",
",",
"path",
"=",
"\"\"",
")",
":",
"global",
"DEBUG",
"global",
"_LOADED",
"if",
"DEBUG",
":",
"print",
"(",
"\"LOAD OVERLAY: {0} @ {1}\"",
".",
"format",
"(",
"overlay",
",",
"path",
")",
")",
"# SEE IF OUR OVERLAY NAME IS IN T... | load - Load a DTB Overlay
Inputs:
overlay - Overlay Key: SPI2, PWM0, CUST
path - Full Path to where the custom overlay is stored
Returns:
0 - Successful Load
1 - Unsuccessful Load
2 - Overlay was previously set | [
"load",
"-",
"Load",
"a",
"DTB",
"Overlay"
] | 84df4376f83bb4de2b4e2f77447cb75704ebdaf4 | https://github.com/xtacocorex/CHIP_IO/blob/84df4376f83bb4de2b4e2f77447cb75704ebdaf4/CHIP_IO/OverlayManager.py#L132-L195 | train | 34,497 |
thieman/dagobah | dagobah/core/components.py | Scheduler.run | def run(self):
""" Continually monitors Jobs of the parent Dagobah. """
while not self.stopped:
now = datetime.utcnow()
for job in self.parent.jobs:
if not job.next_run:
continue
if job.next_run >= self.last_check and job.next_run <= now:
if job.state.allow_start:
job.start()
else:
job.next_run = job.cron_iter.get_next(datetime)
self.last_checked = now
time.sleep(1) | python | def run(self):
""" Continually monitors Jobs of the parent Dagobah. """
while not self.stopped:
now = datetime.utcnow()
for job in self.parent.jobs:
if not job.next_run:
continue
if job.next_run >= self.last_check and job.next_run <= now:
if job.state.allow_start:
job.start()
else:
job.next_run = job.cron_iter.get_next(datetime)
self.last_checked = now
time.sleep(1) | [
"def",
"run",
"(",
"self",
")",
":",
"while",
"not",
"self",
".",
"stopped",
":",
"now",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"for",
"job",
"in",
"self",
".",
"parent",
".",
"jobs",
":",
"if",
"not",
"job",
".",
"next_run",
":",
"continue",
... | Continually monitors Jobs of the parent Dagobah. | [
"Continually",
"monitors",
"Jobs",
"of",
"the",
"parent",
"Dagobah",
"."
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/core/components.py#L105-L118 | train | 34,498 |
thieman/dagobah | dagobah/core/core.py | Dagobah.set_backend | def set_backend(self, backend):
""" Manually set backend after construction. """
self.backend = backend
self.dagobah_id = self.backend.get_new_dagobah_id()
for job in self.jobs:
job.backend = backend
for task in job.tasks.values():
task.backend = backend
self.commit(cascade=True) | python | def set_backend(self, backend):
""" Manually set backend after construction. """
self.backend = backend
self.dagobah_id = self.backend.get_new_dagobah_id()
for job in self.jobs:
job.backend = backend
for task in job.tasks.values():
task.backend = backend
self.commit(cascade=True) | [
"def",
"set_backend",
"(",
"self",
",",
"backend",
")",
":",
"self",
".",
"backend",
"=",
"backend",
"self",
".",
"dagobah_id",
"=",
"self",
".",
"backend",
".",
"get_new_dagobah_id",
"(",
")",
"for",
"job",
"in",
"self",
".",
"jobs",
":",
"job",
".",
... | Manually set backend after construction. | [
"Manually",
"set",
"backend",
"after",
"construction",
"."
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/core/core.py#L56-L67 | train | 34,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.