body_hash
stringlengths
64
64
body
stringlengths
23
109k
docstring
stringlengths
1
57k
path
stringlengths
4
198
name
stringlengths
1
115
repository_name
stringlengths
7
111
repository_stars
float64
0
191k
lang
stringclasses
1 value
body_without_docstring
stringlengths
14
108k
unified
stringlengths
45
133k
f657e64b72e7c3a4b11091303917ade794b2b449ec9b4c25475eb5673f6b8c9d
def clear_eeprom(self): '\n Clears EEPROM values such as Port Mode, Servo Disabled, Startup Mode\n and Default Positions.\n Serial command: \'!SCLEAR\r\'\n\n Returns\n -------\n out : str\n String equal to: "CLR".\n\n ' command = (b'!SCLEAR' + self.CR) self._write(command) retval = self.read(3) out = retval.decode('ascii') return out
Clears EEPROM values such as Port Mode, Servo Disabled, Startup Mode and Default Positions. Serial command: '!SCLEAR ' Returns ------- out : str String equal to: "CLR".
roytherobot/__init__.py
clear_eeprom
tuslisoftware/roytherobot
2
python
def clear_eeprom(self): '\n Clears EEPROM values such as Port Mode, Servo Disabled, Startup Mode\n and Default Positions.\n Serial command: \'!SCLEAR\r\'\n\n Returns\n -------\n out : str\n String equal to: "CLR".\n\n ' command = (b'!SCLEAR' + self.CR) self._write(command) retval = self.read(3) out = retval.decode('ascii') return out
def clear_eeprom(self): '\n Clears EEPROM values such as Port Mode, Servo Disabled, Startup Mode\n and Default Positions.\n Serial command: \'!SCLEAR\r\'\n\n Returns\n -------\n out : str\n String equal to: "CLR".\n\n ' command = (b'!SCLEAR' + self.CR) self._write(command) retval = self.read(3) out = retval.decode('ascii') return out<|docstring|>Clears EEPROM values such as Port Mode, Servo Disabled, Startup Mode and Default Positions. Serial command: '!SCLEAR ' Returns ------- out : str String equal to: "CLR".<|endoftext|>
84b707188e4d5da1c1d1eea6ac0df4e85f24886a31be5ba1080ec307f179c365
def disable_servo(self, channel): "\n Disables a servo.\n Serial command: '!SCPSD' + <channel> + '\r'\n\n Parameters\n ----------\n channel : int\n Servo channel, range 0-15.\n\n Raises\n ------\n PropellerError for invalid channel value.\n\n " if (not isinstance(channel, int)): raise PropellerError('Channel must be an integer.') if (channel not in range(16)): raise PropellerError('Channel must be between 0 and 15.') command = ((b'!SCPSD' + struct.pack(b'<b', channel)) + self.CR) self._write(command)
Disables a servo. Serial command: '!SCPSD' + <channel> + ' ' Parameters ---------- channel : int Servo channel, range 0-15. Raises ------ PropellerError for invalid channel value.
roytherobot/__init__.py
disable_servo
tuslisoftware/roytherobot
2
python
def disable_servo(self, channel): "\n Disables a servo.\n Serial command: '!SCPSD' + <channel> + '\r'\n\n Parameters\n ----------\n channel : int\n Servo channel, range 0-15.\n\n Raises\n ------\n PropellerError for invalid channel value.\n\n " if (not isinstance(channel, int)): raise PropellerError('Channel must be an integer.') if (channel not in range(16)): raise PropellerError('Channel must be between 0 and 15.') command = ((b'!SCPSD' + struct.pack(b'<b', channel)) + self.CR) self._write(command)
def disable_servo(self, channel): "\n Disables a servo.\n Serial command: '!SCPSD' + <channel> + '\r'\n\n Parameters\n ----------\n channel : int\n Servo channel, range 0-15.\n\n Raises\n ------\n PropellerError for invalid channel value.\n\n " if (not isinstance(channel, int)): raise PropellerError('Channel must be an integer.') if (channel not in range(16)): raise PropellerError('Channel must be between 0 and 15.') command = ((b'!SCPSD' + struct.pack(b'<b', channel)) + self.CR) self._write(command)<|docstring|>Disables a servo. Serial command: '!SCPSD' + <channel> + ' ' Parameters ---------- channel : int Servo channel, range 0-15. Raises ------ PropellerError for invalid channel value.<|endoftext|>
ed971ba4809c953e99f66b9a39ca01120a430ac221d9d8057cc770ede1c3b4f6
def set_startup_servo_mode(self, mode=0): '\n Sets whether the PSCU centers all servo channels on startup (mode 0)\n or uses custom startup positions stored in EEPROM (mode 1).\n Serial command: \'!SCEDD\' + <mode> + \'\r\'\n\n Parameters\n ----------\n mode : int, optional\n Center all servos on start up (mode 0, default) or use custom\n startup positions (mode 1).\n\n Returns\n -------\n out : str\n String equal to: "DL" + <mode>.\n\n Raises\n ------\n PropellerError for invalid mode value.\n\n ' if (mode not in range(2)): raise PropellerError('Mode must be 0 or 1.') command = ((b'!SCEDD' + struct.pack(b'<b', mode)) + self.CR) self._write(command) retval = self.read(3) retcmd = retval[:2].decode('ascii') if isinstance(retval[2], int): retmode = retval[2] else: retmode = struct.unpack(b'<b', retval[2])[0] out = (retcmd + str(retmode)) return out
Sets whether the PSCU centers all servo channels on startup (mode 0) or uses custom startup positions stored in EEPROM (mode 1). Serial command: '!SCEDD' + <mode> + ' ' Parameters ---------- mode : int, optional Center all servos on start up (mode 0, default) or use custom startup positions (mode 1). Returns ------- out : str String equal to: "DL" + <mode>. Raises ------ PropellerError for invalid mode value.
roytherobot/__init__.py
set_startup_servo_mode
tuslisoftware/roytherobot
2
python
def set_startup_servo_mode(self, mode=0): '\n Sets whether the PSCU centers all servo channels on startup (mode 0)\n or uses custom startup positions stored in EEPROM (mode 1).\n Serial command: \'!SCEDD\' + <mode> + \'\r\'\n\n Parameters\n ----------\n mode : int, optional\n Center all servos on start up (mode 0, default) or use custom\n startup positions (mode 1).\n\n Returns\n -------\n out : str\n String equal to: "DL" + <mode>.\n\n Raises\n ------\n PropellerError for invalid mode value.\n\n ' if (mode not in range(2)): raise PropellerError('Mode must be 0 or 1.') command = ((b'!SCEDD' + struct.pack(b'<b', mode)) + self.CR) self._write(command) retval = self.read(3) retcmd = retval[:2].decode('ascii') if isinstance(retval[2], int): retmode = retval[2] else: retmode = struct.unpack(b'<b', retval[2])[0] out = (retcmd + str(retmode)) return out
def set_startup_servo_mode(self, mode=0): '\n Sets whether the PSCU centers all servo channels on startup (mode 0)\n or uses custom startup positions stored in EEPROM (mode 1).\n Serial command: \'!SCEDD\' + <mode> + \'\r\'\n\n Parameters\n ----------\n mode : int, optional\n Center all servos on start up (mode 0, default) or use custom\n startup positions (mode 1).\n\n Returns\n -------\n out : str\n String equal to: "DL" + <mode>.\n\n Raises\n ------\n PropellerError for invalid mode value.\n\n ' if (mode not in range(2)): raise PropellerError('Mode must be 0 or 1.') command = ((b'!SCEDD' + struct.pack(b'<b', mode)) + self.CR) self._write(command) retval = self.read(3) retcmd = retval[:2].decode('ascii') if isinstance(retval[2], int): retmode = retval[2] else: retmode = struct.unpack(b'<b', retval[2])[0] out = (retcmd + str(retmode)) return out<|docstring|>Sets whether the PSCU centers all servo channels on startup (mode 0) or uses custom startup positions stored in EEPROM (mode 1). Serial command: '!SCEDD' + <mode> + ' ' Parameters ---------- mode : int, optional Center all servos on start up (mode 0, default) or use custom startup positions (mode 1). Returns ------- out : str String equal to: "DL" + <mode>. Raises ------ PropellerError for invalid mode value.<|endoftext|>
a8679bd48951592e03b892677c4d856d3eb43ec0fa95748d33021a0087c68c30
def set_default_position(self, channel, pulse_width): "\n Set a new default position for individual servos instead of center.\n Serial command: '!SCD' + <channel> + <pulse_width> + '\r'\n\n Parameters\n ----------\n channel : int\n Servo channel, range 0-15.\n pulse_width : int\n Pulse width in microseconds determines the position of the servo.\n The value ranges depend on the individual servo.\n\n Raises\n ------\n PropellerError for invalid channel and pulse_width values.\n\n " if (not isinstance(channel, int)): raise PropellerError('Channel must be an integer.') if (not isinstance(pulse_width, int)): raise PropellerError('Pulse width must be an integer.') if (channel not in range(16)): raise PropellerError('Channel must be between 0 and 15.') max_pw = self.MAX_PULSE_WIDTH if ((pulse_width < 0) or (pulse_width > max_pw)): msg = ('Pulse width must be between 0 and %d.' % max_pw) raise PropellerError(msg) ch = struct.pack(b'<b', channel) pw = struct.pack(b'<h', pulse_width) command = (((b'!SCD' + ch) + pw) + self.CR) self._write(command)
Set a new default position for individual servos instead of center. Serial command: '!SCD' + <channel> + <pulse_width> + ' ' Parameters ---------- channel : int Servo channel, range 0-15. pulse_width : int Pulse width in microseconds determines the position of the servo. The value ranges depend on the individual servo. Raises ------ PropellerError for invalid channel and pulse_width values.
roytherobot/__init__.py
set_default_position
tuslisoftware/roytherobot
2
python
def set_default_position(self, channel, pulse_width): "\n Set a new default position for individual servos instead of center.\n Serial command: '!SCD' + <channel> + <pulse_width> + '\r'\n\n Parameters\n ----------\n channel : int\n Servo channel, range 0-15.\n pulse_width : int\n Pulse width in microseconds determines the position of the servo.\n The value ranges depend on the individual servo.\n\n Raises\n ------\n PropellerError for invalid channel and pulse_width values.\n\n " if (not isinstance(channel, int)): raise PropellerError('Channel must be an integer.') if (not isinstance(pulse_width, int)): raise PropellerError('Pulse width must be an integer.') if (channel not in range(16)): raise PropellerError('Channel must be between 0 and 15.') max_pw = self.MAX_PULSE_WIDTH if ((pulse_width < 0) or (pulse_width > max_pw)): msg = ('Pulse width must be between 0 and %d.' % max_pw) raise PropellerError(msg) ch = struct.pack(b'<b', channel) pw = struct.pack(b'<h', pulse_width) command = (((b'!SCD' + ch) + pw) + self.CR) self._write(command)
def set_default_position(self, channel, pulse_width): "\n Set a new default position for individual servos instead of center.\n Serial command: '!SCD' + <channel> + <pulse_width> + '\r'\n\n Parameters\n ----------\n channel : int\n Servo channel, range 0-15.\n pulse_width : int\n Pulse width in microseconds determines the position of the servo.\n The value ranges depend on the individual servo.\n\n Raises\n ------\n PropellerError for invalid channel and pulse_width values.\n\n " if (not isinstance(channel, int)): raise PropellerError('Channel must be an integer.') if (not isinstance(pulse_width, int)): raise PropellerError('Pulse width must be an integer.') if (channel not in range(16)): raise PropellerError('Channel must be between 0 and 15.') max_pw = self.MAX_PULSE_WIDTH if ((pulse_width < 0) or (pulse_width > max_pw)): msg = ('Pulse width must be between 0 and %d.' % max_pw) raise PropellerError(msg) ch = struct.pack(b'<b', channel) pw = struct.pack(b'<h', pulse_width) command = (((b'!SCD' + ch) + pw) + self.CR) self._write(command)<|docstring|>Set a new default position for individual servos instead of center. Serial command: '!SCD' + <channel> + <pulse_width> + ' ' Parameters ---------- channel : int Servo channel, range 0-15. pulse_width : int Pulse width in microseconds determines the position of the servo. The value ranges depend on the individual servo. Raises ------ PropellerError for invalid channel and pulse_width values.<|endoftext|>
700aef22f9ea2bffe48eda3595ace8cedfb2840f71698b693b0104334b91f24a
def get_fw_version_number(self): "\n Returns the firmware version number.\n Serial command: '!SCVER?\r'\n\n Returns\n -------\n version : str\n Firmware version number string.\n\n " command = (b'!SCVER?' + self.CR) self._write(command) version = self.read(3).decode('ascii') return version
Returns the firmware version number. Serial command: '!SCVER? ' Returns ------- version : str Firmware version number string.
roytherobot/__init__.py
get_fw_version_number
tuslisoftware/roytherobot
2
python
def get_fw_version_number(self): "\n Returns the firmware version number.\n Serial command: '!SCVER?\r'\n\n Returns\n -------\n version : str\n Firmware version number string.\n\n " command = (b'!SCVER?' + self.CR) self._write(command) version = self.read(3).decode('ascii') return version
def get_fw_version_number(self): "\n Returns the firmware version number.\n Serial command: '!SCVER?\r'\n\n Returns\n -------\n version : str\n Firmware version number string.\n\n " command = (b'!SCVER?' + self.CR) self._write(command) version = self.read(3).decode('ascii') return version<|docstring|>Returns the firmware version number. Serial command: '!SCVER? ' Returns ------- version : str Firmware version number string.<|endoftext|>
d7cd6b332408377e29e4c5f998963db374f5ba1fbefd965904e4272b830c18e9
def __init__(self, port, write_sleep=0.05, controller='PROPELLER_28830', debug=False): "\n Initialization.\n\n Parameters\n ----------\n port : str\n The name of the serial port. Usually '/dev/ttyUSB0' for Linux,\n 'COM3' for Windows, etc.\n write_sleep : float, optional\n How long to wait in seconds after writing. For 2400 baud rate,\n less than 0.03 tends to cause communication errors.\n controller : str, optional\n Only one controller board is supported currently,\n 'PROPELLER_28830', but this board has been deprecated by the\n manufacturer and will likely be replaced in the future.\n debug : bool, optional\n Print debug messages.\n\n Raises\n ------\n RoyTheRobotError if controller is not implemented.\n\n " if (controller == 'PROPELLER_28830'): self.controller = Propeller28830(port, write_sleep=write_sleep) else: raise RoyTheRobotError('Invalid controller board.') self.write_sleep = write_sleep self.debug = debug self.enable_all_servos() self._debug('Initialized roytherobot.Arm.')
Initialization. Parameters ---------- port : str The name of the serial port. Usually '/dev/ttyUSB0' for Linux, 'COM3' for Windows, etc. write_sleep : float, optional How long to wait in seconds after writing. For 2400 baud rate, less than 0.03 tends to cause communication errors. controller : str, optional Only one controller board is supported currently, 'PROPELLER_28830', but this board has been deprecated by the manufacturer and will likely be replaced in the future. debug : bool, optional Print debug messages. Raises ------ RoyTheRobotError if controller is not implemented.
roytherobot/__init__.py
__init__
tuslisoftware/roytherobot
2
python
def __init__(self, port, write_sleep=0.05, controller='PROPELLER_28830', debug=False): "\n Initialization.\n\n Parameters\n ----------\n port : str\n The name of the serial port. Usually '/dev/ttyUSB0' for Linux,\n 'COM3' for Windows, etc.\n write_sleep : float, optional\n How long to wait in seconds after writing. For 2400 baud rate,\n less than 0.03 tends to cause communication errors.\n controller : str, optional\n Only one controller board is supported currently,\n 'PROPELLER_28830', but this board has been deprecated by the\n manufacturer and will likely be replaced in the future.\n debug : bool, optional\n Print debug messages.\n\n Raises\n ------\n RoyTheRobotError if controller is not implemented.\n\n " if (controller == 'PROPELLER_28830'): self.controller = Propeller28830(port, write_sleep=write_sleep) else: raise RoyTheRobotError('Invalid controller board.') self.write_sleep = write_sleep self.debug = debug self.enable_all_servos() self._debug('Initialized roytherobot.Arm.')
def __init__(self, port, write_sleep=0.05, controller='PROPELLER_28830', debug=False): "\n Initialization.\n\n Parameters\n ----------\n port : str\n The name of the serial port. Usually '/dev/ttyUSB0' for Linux,\n 'COM3' for Windows, etc.\n write_sleep : float, optional\n How long to wait in seconds after writing. For 2400 baud rate,\n less than 0.03 tends to cause communication errors.\n controller : str, optional\n Only one controller board is supported currently,\n 'PROPELLER_28830', but this board has been deprecated by the\n manufacturer and will likely be replaced in the future.\n debug : bool, optional\n Print debug messages.\n\n Raises\n ------\n RoyTheRobotError if controller is not implemented.\n\n " if (controller == 'PROPELLER_28830'): self.controller = Propeller28830(port, write_sleep=write_sleep) else: raise RoyTheRobotError('Invalid controller board.') self.write_sleep = write_sleep self.debug = debug self.enable_all_servos() self._debug('Initialized roytherobot.Arm.')<|docstring|>Initialization. Parameters ---------- port : str The name of the serial port. Usually '/dev/ttyUSB0' for Linux, 'COM3' for Windows, etc. write_sleep : float, optional How long to wait in seconds after writing. For 2400 baud rate, less than 0.03 tends to cause communication errors. controller : str, optional Only one controller board is supported currently, 'PROPELLER_28830', but this board has been deprecated by the manufacturer and will likely be replaced in the future. debug : bool, optional Print debug messages. Raises ------ RoyTheRobotError if controller is not implemented.<|endoftext|>
664e4b5d1f425637c6c3a149eafb3b2b4f59399cd0a9c5c15182fd1975007dbb
def __enter__(self): ' Enters a context manager. ' return self
Enters a context manager.
roytherobot/__init__.py
__enter__
tuslisoftware/roytherobot
2
python
def __enter__(self): ' ' return self
def __enter__(self): ' ' return self<|docstring|>Enters a context manager.<|endoftext|>
3555d7ac4da90430d9901107e723489bae7f46817c817170a1ff87f11845ebdb
def __exit__(self, error_type, value, traceback): ' Closes the serial connection when exiting a context manager. ' self.close() return False
Closes the serial connection when exiting a context manager.
roytherobot/__init__.py
__exit__
tuslisoftware/roytherobot
2
python
def __exit__(self, error_type, value, traceback): ' ' self.close() return False
def __exit__(self, error_type, value, traceback): ' ' self.close() return False<|docstring|>Closes the serial connection when exiting a context manager.<|endoftext|>
a9acddb61256827e1a569c13ca8f564583b8a59f0f3653b88e80af5690a0b249
def _debug(self, message): ' Prints message if the debug flag is True. ' if self.debug: print(message)
Prints message if the debug flag is True.
roytherobot/__init__.py
_debug
tuslisoftware/roytherobot
2
python
def _debug(self, message): ' ' if self.debug: print(message)
def _debug(self, message): ' ' if self.debug: print(message)<|docstring|>Prints message if the debug flag is True.<|endoftext|>
9c999add7dc2c102d935c8835afdb352ea579fb0339a0c00adc083bb9602dd60
def close(self): ' Close the servo controller. ' self._debug('Closing the servo controller.') self.controller.close()
Close the servo controller.
roytherobot/__init__.py
close
tuslisoftware/roytherobot
2
python
def close(self): ' ' self._debug('Closing the servo controller.') self.controller.close()
def close(self): ' ' self._debug('Closing the servo controller.') self.controller.close()<|docstring|>Close the servo controller.<|endoftext|>
a2c002b1eee4902803e29aa72c31e86765c73d49968d072b69334b9821710838
def enable_all_servos(self): ' Enables all servos. ' self._debug('Enabling all servos.') for i in range(9): self.enable_servo(i)
Enables all servos.
roytherobot/__init__.py
enable_all_servos
tuslisoftware/roytherobot
2
python
def enable_all_servos(self): ' ' self._debug('Enabling all servos.') for i in range(9): self.enable_servo(i)
def enable_all_servos(self): ' ' self._debug('Enabling all servos.') for i in range(9): self.enable_servo(i)<|docstring|>Enables all servos.<|endoftext|>
eb1eca64c66210361b7fca6da4f6dd80fe3dbe7a16a796497993f442e0e4d2fe
def disable_all_servos(self): ' Disables all servos. ' self._debug('Disabling all servos.') for i in range(9): self.disable_servo(i)
Disables all servos.
roytherobot/__init__.py
disable_all_servos
tuslisoftware/roytherobot
2
python
def disable_all_servos(self): ' ' self._debug('Disabling all servos.') for i in range(9): self.disable_servo(i)
def disable_all_servos(self): ' ' self._debug('Disabling all servos.') for i in range(9): self.disable_servo(i)<|docstring|>Disables all servos.<|endoftext|>
85fcaba471ea217d03e9c5c1c9260e943f08d2ae7ef189bf62ecb5c2551d3d86
def set_position(self, channel, pulse_width, ramp_speed=0): '\n Jump to a new position in one step.\n\n *WARNING*: the servo may refuse to move at all if the requested\n position is too far from its current position. Try splitting the motion\n into smaller steps instead of one large jump. The\n `move(channels, pulse_widths, duration)` method tries to do this\n unless `duration` is too short. In general, the `move` method is\n preferred over `set_position` for most use cases. Think of `move` as\n the high-level function and `set_position` as the low-level function\n that can both accomplish the same goal.\n\n Parameters\n ----------\n channel : int\n Servo channel, range 0-8.\n pulse_width : int\n Destination position, range depends on servo.\n ramp_speed : int, optional\n Speed to move to the new position, range 0-63. Strangely, this\n seems to have no observable effect, so far.\n\n Raises\n ------\n RoyTheRobotError for invalid channel or pulse_width values.\n\n ' self._debug(('Setting channel %d to %d.' % (channel, pulse_width))) if (channel not in range(9)): raise RoyTheRobotError('Channel must be between 0 and 8.') if (pulse_width < self.MIN_PULSE_WIDTH[channel]): min_pw = self.MIN_PULSE_WIDTH[channel] msg = ('Pulse width for channel %d must be greater than %d.' % (channel, min_pw)) raise RoyTheRobotError(msg) elif (pulse_width > self.MAX_PULSE_WIDTH[channel]): max_pw = self.MAX_PULSE_WIDTH[channel] msg = ('Pulse width for channel %d must be less than %d.' % (channel, max_pw)) raise RoyTheRobotError(msg) self.controller.set_position(channel, ramp_speed, pulse_width)
Jump to a new position in one step. *WARNING*: the servo may refuse to move at all if the requested position is too far from its current position. Try splitting the motion into smaller steps instead of one large jump. The `move(channels, pulse_widths, duration)` method tries to do this unless `duration` is too short. In general, the `move` method is preferred over `set_position` for most use cases. Think of `move` as the high-level function and `set_position` as the low-level function that can both accomplish the same goal. Parameters ---------- channel : int Servo channel, range 0-8. pulse_width : int Destination position, range depends on servo. ramp_speed : int, optional Speed to move to the new position, range 0-63. Strangely, this seems to have no observable effect, so far. Raises ------ RoyTheRobotError for invalid channel or pulse_width values.
roytherobot/__init__.py
set_position
tuslisoftware/roytherobot
2
python
def set_position(self, channel, pulse_width, ramp_speed=0): '\n Jump to a new position in one step.\n\n *WARNING*: the servo may refuse to move at all if the requested\n position is too far from its current position. Try splitting the motion\n into smaller steps instead of one large jump. The\n `move(channels, pulse_widths, duration)` method tries to do this\n unless `duration` is too short. In general, the `move` method is\n preferred over `set_position` for most use cases. Think of `move` as\n the high-level function and `set_position` as the low-level function\n that can both accomplish the same goal.\n\n Parameters\n ----------\n channel : int\n Servo channel, range 0-8.\n pulse_width : int\n Destination position, range depends on servo.\n ramp_speed : int, optional\n Speed to move to the new position, range 0-63. Strangely, this\n seems to have no observable effect, so far.\n\n Raises\n ------\n RoyTheRobotError for invalid channel or pulse_width values.\n\n ' self._debug(('Setting channel %d to %d.' % (channel, pulse_width))) if (channel not in range(9)): raise RoyTheRobotError('Channel must be between 0 and 8.') if (pulse_width < self.MIN_PULSE_WIDTH[channel]): min_pw = self.MIN_PULSE_WIDTH[channel] msg = ('Pulse width for channel %d must be greater than %d.' % (channel, min_pw)) raise RoyTheRobotError(msg) elif (pulse_width > self.MAX_PULSE_WIDTH[channel]): max_pw = self.MAX_PULSE_WIDTH[channel] msg = ('Pulse width for channel %d must be less than %d.' % (channel, max_pw)) raise RoyTheRobotError(msg) self.controller.set_position(channel, ramp_speed, pulse_width)
def set_position(self, channel, pulse_width, ramp_speed=0): '\n Jump to a new position in one step.\n\n *WARNING*: the servo may refuse to move at all if the requested\n position is too far from its current position. Try splitting the motion\n into smaller steps instead of one large jump. The\n `move(channels, pulse_widths, duration)` method tries to do this\n unless `duration` is too short. In general, the `move` method is\n preferred over `set_position` for most use cases. Think of `move` as\n the high-level function and `set_position` as the low-level function\n that can both accomplish the same goal.\n\n Parameters\n ----------\n channel : int\n Servo channel, range 0-8.\n pulse_width : int\n Destination position, range depends on servo.\n ramp_speed : int, optional\n Speed to move to the new position, range 0-63. Strangely, this\n seems to have no observable effect, so far.\n\n Raises\n ------\n RoyTheRobotError for invalid channel or pulse_width values.\n\n ' self._debug(('Setting channel %d to %d.' % (channel, pulse_width))) if (channel not in range(9)): raise RoyTheRobotError('Channel must be between 0 and 8.') if (pulse_width < self.MIN_PULSE_WIDTH[channel]): min_pw = self.MIN_PULSE_WIDTH[channel] msg = ('Pulse width for channel %d must be greater than %d.' % (channel, min_pw)) raise RoyTheRobotError(msg) elif (pulse_width > self.MAX_PULSE_WIDTH[channel]): max_pw = self.MAX_PULSE_WIDTH[channel] msg = ('Pulse width for channel %d must be less than %d.' % (channel, max_pw)) raise RoyTheRobotError(msg) self.controller.set_position(channel, ramp_speed, pulse_width)<|docstring|>Jump to a new position in one step. *WARNING*: the servo may refuse to move at all if the requested position is too far from its current position. Try splitting the motion into smaller steps instead of one large jump. The `move(channels, pulse_widths, duration)` method tries to do this unless `duration` is too short. In general, the `move` method is preferred over `set_position` for most use cases. Think of `move` as the high-level function and `set_position` as the low-level function that can both accomplish the same goal. Parameters ---------- channel : int Servo channel, range 0-8. pulse_width : int Destination position, range depends on servo. ramp_speed : int, optional Speed to move to the new position, range 0-63. Strangely, this seems to have no observable effect, so far. Raises ------ RoyTheRobotError for invalid channel or pulse_width values.<|endoftext|>
96a6628405bf7420043146bf3ea52a60caa04fe34527233764ae84e54590f2dd
def enable_servo(self, channel): '\n Adds additional restrictions to parent class function.\n\n Parameters\n ----------\n channel : int\n Servo channel, range 0-8.\n\n Raises\n ------\n RoyTheRobotError for invalid channel value.\n\n ' self._debug((('Channel ' + str(channel)) + ' enabled.')) if (channel not in range(9)): raise RoyTheRobotError('Channel must be between 0 and 8.') self.controller.enable_servo(channel)
Adds additional restrictions to parent class function. Parameters ---------- channel : int Servo channel, range 0-8. Raises ------ RoyTheRobotError for invalid channel value.
roytherobot/__init__.py
enable_servo
tuslisoftware/roytherobot
2
python
def enable_servo(self, channel): '\n Adds additional restrictions to parent class function.\n\n Parameters\n ----------\n channel : int\n Servo channel, range 0-8.\n\n Raises\n ------\n RoyTheRobotError for invalid channel value.\n\n ' self._debug((('Channel ' + str(channel)) + ' enabled.')) if (channel not in range(9)): raise RoyTheRobotError('Channel must be between 0 and 8.') self.controller.enable_servo(channel)
def enable_servo(self, channel): '\n Adds additional restrictions to parent class function.\n\n Parameters\n ----------\n channel : int\n Servo channel, range 0-8.\n\n Raises\n ------\n RoyTheRobotError for invalid channel value.\n\n ' self._debug((('Channel ' + str(channel)) + ' enabled.')) if (channel not in range(9)): raise RoyTheRobotError('Channel must be between 0 and 8.') self.controller.enable_servo(channel)<|docstring|>Adds additional restrictions to parent class function. Parameters ---------- channel : int Servo channel, range 0-8. Raises ------ RoyTheRobotError for invalid channel value.<|endoftext|>
918b90b9bf23c28e1cabe92dc3f98944dcfda225f4ba42b06730075c6c0ceb51
def disable_servo(self, channel): '\n Adds additional restrictions to parent class function.\n\n Parameters\n ----------\n channel : int\n Servo channel, range 0-8.\n\n Raises\n ------\n RoyTheRobotError for invalid channel value.\n\n ' self._debug((('Channel ' + str(channel)) + ' disabled.')) if (channel not in range(9)): raise RoyTheRobotError('Channel must be between 0 and 8.') self.controller.disable_servo(channel)
Adds additional restrictions to parent class function. Parameters ---------- channel : int Servo channel, range 0-8. Raises ------ RoyTheRobotError for invalid channel value.
roytherobot/__init__.py
disable_servo
tuslisoftware/roytherobot
2
python
def disable_servo(self, channel): '\n Adds additional restrictions to parent class function.\n\n Parameters\n ----------\n channel : int\n Servo channel, range 0-8.\n\n Raises\n ------\n RoyTheRobotError for invalid channel value.\n\n ' self._debug((('Channel ' + str(channel)) + ' disabled.')) if (channel not in range(9)): raise RoyTheRobotError('Channel must be between 0 and 8.') self.controller.disable_servo(channel)
def disable_servo(self, channel): '\n Adds additional restrictions to parent class function.\n\n Parameters\n ----------\n channel : int\n Servo channel, range 0-8.\n\n Raises\n ------\n RoyTheRobotError for invalid channel value.\n\n ' self._debug((('Channel ' + str(channel)) + ' disabled.')) if (channel not in range(9)): raise RoyTheRobotError('Channel must be between 0 and 8.') self.controller.disable_servo(channel)<|docstring|>Adds additional restrictions to parent class function. Parameters ---------- channel : int Servo channel, range 0-8. Raises ------ RoyTheRobotError for invalid channel value.<|endoftext|>
7a8ac38c39c42ec0ba2bcd7b7bf24d501037a112bfe67c77351acaaff58b76cc
def set_default_position(self, channel, pulse_width): ' Adds additional restrictions to parent class function.\n\n Parameters\n ----------\n channel : int\n Servo channel, range 0-8.\n pulse_width : int\n Pulse width in microseconds determines the position of the servo.\n The value ranges depend on the individual servo.\n\n Raises\n ------\n RoyTheRobotError for invalid channel or pulse_width values.\n\n ' self._debug(('Setting default position of channel %d to %d.' % (channel, pulse_width))) if (channel not in range(9)): raise RoyTheRobotError('Channel must be between 0 and 8.') min_pw = self.MIN_PULSE_WIDTH[channel] max_pw = self.MAX_PULSE_WIDTH[channel] if ((pulse_width < min_pw) or (pulse_width > max_pw)): msg = ('Pulse width for channel %d must be between %d and %d.' % (channel, min_pw, max_pw)) raise RoyTheRobotError(msg) self.controller.set_default_position(channel, pulse_width)
Adds additional restrictions to parent class function. Parameters ---------- channel : int Servo channel, range 0-8. pulse_width : int Pulse width in microseconds determines the position of the servo. The value ranges depend on the individual servo. Raises ------ RoyTheRobotError for invalid channel or pulse_width values.
roytherobot/__init__.py
set_default_position
tuslisoftware/roytherobot
2
python
def set_default_position(self, channel, pulse_width): ' Adds additional restrictions to parent class function.\n\n Parameters\n ----------\n channel : int\n Servo channel, range 0-8.\n pulse_width : int\n Pulse width in microseconds determines the position of the servo.\n The value ranges depend on the individual servo.\n\n Raises\n ------\n RoyTheRobotError for invalid channel or pulse_width values.\n\n ' self._debug(('Setting default position of channel %d to %d.' % (channel, pulse_width))) if (channel not in range(9)): raise RoyTheRobotError('Channel must be between 0 and 8.') min_pw = self.MIN_PULSE_WIDTH[channel] max_pw = self.MAX_PULSE_WIDTH[channel] if ((pulse_width < min_pw) or (pulse_width > max_pw)): msg = ('Pulse width for channel %d must be between %d and %d.' % (channel, min_pw, max_pw)) raise RoyTheRobotError(msg) self.controller.set_default_position(channel, pulse_width)
def set_default_position(self, channel, pulse_width): ' Adds additional restrictions to parent class function.\n\n Parameters\n ----------\n channel : int\n Servo channel, range 0-8.\n pulse_width : int\n Pulse width in microseconds determines the position of the servo.\n The value ranges depend on the individual servo.\n\n Raises\n ------\n RoyTheRobotError for invalid channel or pulse_width values.\n\n ' self._debug(('Setting default position of channel %d to %d.' % (channel, pulse_width))) if (channel not in range(9)): raise RoyTheRobotError('Channel must be between 0 and 8.') min_pw = self.MIN_PULSE_WIDTH[channel] max_pw = self.MAX_PULSE_WIDTH[channel] if ((pulse_width < min_pw) or (pulse_width > max_pw)): msg = ('Pulse width for channel %d must be between %d and %d.' % (channel, min_pw, max_pw)) raise RoyTheRobotError(msg) self.controller.set_default_position(channel, pulse_width)<|docstring|>Adds additional restrictions to parent class function. Parameters ---------- channel : int Servo channel, range 0-8. pulse_width : int Pulse width in microseconds determines the position of the servo. The value ranges depend on the individual servo. Raises ------ RoyTheRobotError for invalid channel or pulse_width values.<|endoftext|>
0c71fc26254d0014c8c3b912ffed283b8a3c48ac209235cc4367e23c12580b7b
def get_position(self, channel): '\n Adds additional restrictions to parent class function.\n\n Parameters\n ----------\n channel : int\n Servo channel, range 0-8.\n\n Returns\n -------\n pulse_width : int\n Pulse width in microseconds determines the position of the servo.\n The value ranges depend on the individual servo.\n\n Raises\n ------\n RoyTheRobotError for invalid channel value.\n\n ' if (channel not in range(9)): raise RoyTheRobotError('Channel must be between 0 and 8.') pulse_width = self.controller.get_position(channel) self._debug(('Position of channel %d: %d.' % (channel, pulse_width))) return pulse_width
Adds additional restrictions to parent class function. Parameters ---------- channel : int Servo channel, range 0-8. Returns ------- pulse_width : int Pulse width in microseconds determines the position of the servo. The value ranges depend on the individual servo. Raises ------ RoyTheRobotError for invalid channel value.
roytherobot/__init__.py
get_position
tuslisoftware/roytherobot
2
python
def get_position(self, channel): '\n Adds additional restrictions to parent class function.\n\n Parameters\n ----------\n channel : int\n Servo channel, range 0-8.\n\n Returns\n -------\n pulse_width : int\n Pulse width in microseconds determines the position of the servo.\n The value ranges depend on the individual servo.\n\n Raises\n ------\n RoyTheRobotError for invalid channel value.\n\n ' if (channel not in range(9)): raise RoyTheRobotError('Channel must be between 0 and 8.') pulse_width = self.controller.get_position(channel) self._debug(('Position of channel %d: %d.' % (channel, pulse_width))) return pulse_width
def get_position(self, channel): '\n Adds additional restrictions to parent class function.\n\n Parameters\n ----------\n channel : int\n Servo channel, range 0-8.\n\n Returns\n -------\n pulse_width : int\n Pulse width in microseconds determines the position of the servo.\n The value ranges depend on the individual servo.\n\n Raises\n ------\n RoyTheRobotError for invalid channel value.\n\n ' if (channel not in range(9)): raise RoyTheRobotError('Channel must be between 0 and 8.') pulse_width = self.controller.get_position(channel) self._debug(('Position of channel %d: %d.' % (channel, pulse_width))) return pulse_width<|docstring|>Adds additional restrictions to parent class function. Parameters ---------- channel : int Servo channel, range 0-8. Returns ------- pulse_width : int Pulse width in microseconds determines the position of the servo. The value ranges depend on the individual servo. Raises ------ RoyTheRobotError for invalid channel value.<|endoftext|>
8ea637fd1b915d42e21db8451f8dd8ffe5be4b2d58d14c3417b8e6f1f5402454
def move(self, channels, pulse_widths, duration=0.3): '\n Moves multiple servos at the same time (sort of). It moves each servo\n in a staggered fashion.\n\n *WARNING*: the servo may refuse to move at all if duration is too\n short.\n\n *NOTE*: duration does NOT include the time it takes to read the\n current pulse-width values of each servo. The time it takes to read\n all of the servos is len(channels)*self.write_sleep.\n\n Parameters\n ----------\n channels : int or sequence of int\n Servo channel(s), range 0-8.\n pulse_widths : int or sequence of int\n Pulse width(s), range depends on servos.\n duration : float, optional\n How long to move all of the servos in seconds. Minimum is\n self.write_sleep.\n\n Raises\n ------\n RoyTheRobotError for invalid channels, pulse_widths or duration values.\n\n ' self._debug((((('Moving channel ' + str(channels)) + ' to ') + str(pulse_widths)) + (' in %g seconds.' % duration))) if (not _iterable(channels)): channels = list([channels]) if (not _iterable(pulse_widths)): pulse_widths = list([pulse_widths]) if (len(channels) != len(pulse_widths)): msg = 'Number of channels and pulse widths must be equal.' raise RoyTheRobotError(msg) if (duration < self.write_sleep): msg = 'Duration must be greater than or equal to self.write_sleep.' raise RoyTheRobotError(msg) values = list(zip(channels, pulse_widths)) iterations = int((duration / self.write_sleep)) if (iterations != 0): starts = dict() pw_steps = dict() for (channel, pulse_width) in values: pos = self.get_position(channel) starts[channel] = pos diff = (pulse_width - pos) pw_steps[channel] = int((diff / iterations)) for i in range(1, iterations): for (channel, pulse_width) in values: start = starts[channel] self.set_position(channel, (start + (i * pw_steps[channel]))) for (channel, pulse_width) in values: self.set_position(channel, pulse_width)
Moves multiple servos at the same time (sort of). It moves each servo in a staggered fashion. *WARNING*: the servo may refuse to move at all if duration is too short. *NOTE*: duration does NOT include the time it takes to read the current pulse-width values of each servo. The time it takes to read all of the servos is len(channels)*self.write_sleep. Parameters ---------- channels : int or sequence of int Servo channel(s), range 0-8. pulse_widths : int or sequence of int Pulse width(s), range depends on servos. duration : float, optional How long to move all of the servos in seconds. Minimum is self.write_sleep. Raises ------ RoyTheRobotError for invalid channels, pulse_widths or duration values.
roytherobot/__init__.py
move
tuslisoftware/roytherobot
2
python
def move(self, channels, pulse_widths, duration=0.3): '\n Moves multiple servos at the same time (sort of). It moves each servo\n in a staggered fashion.\n\n *WARNING*: the servo may refuse to move at all if duration is too\n short.\n\n *NOTE*: duration does NOT include the time it takes to read the\n current pulse-width values of each servo. The time it takes to read\n all of the servos is len(channels)*self.write_sleep.\n\n Parameters\n ----------\n channels : int or sequence of int\n Servo channel(s), range 0-8.\n pulse_widths : int or sequence of int\n Pulse width(s), range depends on servos.\n duration : float, optional\n How long to move all of the servos in seconds. Minimum is\n self.write_sleep.\n\n Raises\n ------\n RoyTheRobotError for invalid channels, pulse_widths or duration values.\n\n ' self._debug((((('Moving channel ' + str(channels)) + ' to ') + str(pulse_widths)) + (' in %g seconds.' % duration))) if (not _iterable(channels)): channels = list([channels]) if (not _iterable(pulse_widths)): pulse_widths = list([pulse_widths]) if (len(channels) != len(pulse_widths)): msg = 'Number of channels and pulse widths must be equal.' raise RoyTheRobotError(msg) if (duration < self.write_sleep): msg = 'Duration must be greater than or equal to self.write_sleep.' raise RoyTheRobotError(msg) values = list(zip(channels, pulse_widths)) iterations = int((duration / self.write_sleep)) if (iterations != 0): starts = dict() pw_steps = dict() for (channel, pulse_width) in values: pos = self.get_position(channel) starts[channel] = pos diff = (pulse_width - pos) pw_steps[channel] = int((diff / iterations)) for i in range(1, iterations): for (channel, pulse_width) in values: start = starts[channel] self.set_position(channel, (start + (i * pw_steps[channel]))) for (channel, pulse_width) in values: self.set_position(channel, pulse_width)
def move(self, channels, pulse_widths, duration=0.3): '\n Moves multiple servos at the same time (sort of). It moves each servo\n in a staggered fashion.\n\n *WARNING*: the servo may refuse to move at all if duration is too\n short.\n\n *NOTE*: duration does NOT include the time it takes to read the\n current pulse-width values of each servo. The time it takes to read\n all of the servos is len(channels)*self.write_sleep.\n\n Parameters\n ----------\n channels : int or sequence of int\n Servo channel(s), range 0-8.\n pulse_widths : int or sequence of int\n Pulse width(s), range depends on servos.\n duration : float, optional\n How long to move all of the servos in seconds. Minimum is\n self.write_sleep.\n\n Raises\n ------\n RoyTheRobotError for invalid channels, pulse_widths or duration values.\n\n ' self._debug((((('Moving channel ' + str(channels)) + ' to ') + str(pulse_widths)) + (' in %g seconds.' % duration))) if (not _iterable(channels)): channels = list([channels]) if (not _iterable(pulse_widths)): pulse_widths = list([pulse_widths]) if (len(channels) != len(pulse_widths)): msg = 'Number of channels and pulse widths must be equal.' raise RoyTheRobotError(msg) if (duration < self.write_sleep): msg = 'Duration must be greater than or equal to self.write_sleep.' raise RoyTheRobotError(msg) values = list(zip(channels, pulse_widths)) iterations = int((duration / self.write_sleep)) if (iterations != 0): starts = dict() pw_steps = dict() for (channel, pulse_width) in values: pos = self.get_position(channel) starts[channel] = pos diff = (pulse_width - pos) pw_steps[channel] = int((diff / iterations)) for i in range(1, iterations): for (channel, pulse_width) in values: start = starts[channel] self.set_position(channel, (start + (i * pw_steps[channel]))) for (channel, pulse_width) in values: self.set_position(channel, pulse_width)<|docstring|>Moves multiple servos at the same time (sort of). It moves each servo in a staggered fashion. *WARNING*: the servo may refuse to move at all if duration is too short. *NOTE*: duration does NOT include the time it takes to read the current pulse-width values of each servo. The time it takes to read all of the servos is len(channels)*self.write_sleep. Parameters ---------- channels : int or sequence of int Servo channel(s), range 0-8. pulse_widths : int or sequence of int Pulse width(s), range depends on servos. duration : float, optional How long to move all of the servos in seconds. Minimum is self.write_sleep. Raises ------ RoyTheRobotError for invalid channels, pulse_widths or duration values.<|endoftext|>
c4c8935659609b0e790d90ab7d77836e688673b37aefcea8b78e21d1ab1966e0
def __init__(self, username: str, password: str) -> None: '\n Creates a session given login details\n ' self.__details = {'edEmailOrName': username, 'edPW': password} self._session = requests.Session() self._setup_cookies() self._login()
Creates a session given login details
bookrags/bookrags.py
__init__
qtKite/bookrags
3
python
def __init__(self, username: str, password: str) -> None: '\n \n ' self.__details = {'edEmailOrName': username, 'edPW': password} self._session = requests.Session() self._setup_cookies() self._login()
def __init__(self, username: str, password: str) -> None: '\n \n ' self.__details = {'edEmailOrName': username, 'edPW': password} self._session = requests.Session() self._setup_cookies() self._login()<|docstring|>Creates a session given login details<|endoftext|>
260d4db5cb1b0be18415a8553fabe57a18e5eee9d28f80e4de811ad61ab7fc66
def _setup_cookies(self) -> None: '\n Not required\n ' self._session.cookies['layout'] = 'desktop' self._session.get(Urls.WEBSITE_URL) self._session.get(Urls.SESSION_URL)
Not required
bookrags/bookrags.py
_setup_cookies
qtKite/bookrags
3
python
def _setup_cookies(self) -> None: '\n \n ' self._session.cookies['layout'] = 'desktop' self._session.get(Urls.WEBSITE_URL) self._session.get(Urls.SESSION_URL)
def _setup_cookies(self) -> None: '\n \n ' self._session.cookies['layout'] = 'desktop' self._session.get(Urls.WEBSITE_URL) self._session.get(Urls.SESSION_URL)<|docstring|>Not required<|endoftext|>
0dcb36464e026f821777751efe0eca6711fbcadda2aae59042ce6ca329f4e409
def _login(self) -> None: '\n Authenticates the current session using the given details\n ' self._session.post(Urls.LOGIN_URL, data=self.__details)
Authenticates the current session using the given details
bookrags/bookrags.py
_login
qtKite/bookrags
3
python
def _login(self) -> None: '\n \n ' self._session.post(Urls.LOGIN_URL, data=self.__details)
def _login(self) -> None: '\n \n ' self._session.post(Urls.LOGIN_URL, data=self.__details)<|docstring|>Authenticates the current session using the given details<|endoftext|>
8c971977c7c362d5f602aa63ff3b4583ae398261182852c8ff8f2af8f79cec9b
def is_logged_in(self) -> bool: '\n Checks if the current session is signed in\n ' check = self._session.get(Urls.ACCOUNT_URL, allow_redirects=False).text return (len(check) > 0)
Checks if the current session is signed in
bookrags/bookrags.py
is_logged_in
qtKite/bookrags
3
python
def is_logged_in(self) -> bool: '\n \n ' check = self._session.get(Urls.ACCOUNT_URL, allow_redirects=False).text return (len(check) > 0)
def is_logged_in(self) -> bool: '\n \n ' check = self._session.get(Urls.ACCOUNT_URL, allow_redirects=False).text return (len(check) > 0)<|docstring|>Checks if the current session is signed in<|endoftext|>
423fc9b7f897e8bd31510c2062f24ddb37eed334f45a459f56bbd573ffa673cb
def logout(self) -> None: '\n Signs out of the user account from the active session\n ' self._session.get(Urls.LOGOUT_URL)
Signs out of the user account from the active session
bookrags/bookrags.py
logout
qtKite/bookrags
3
python
def logout(self) -> None: '\n \n ' self._session.get(Urls.LOGOUT_URL)
def logout(self) -> None: '\n \n ' self._session.get(Urls.LOGOUT_URL)<|docstring|>Signs out of the user account from the active session<|endoftext|>
92427fb08aa3ee2affbf4095427ce5871892736e69a32483fb6d451c61ea4964
def resolve_product(self, link: str) -> Product: '\n Given a link, it will resolve into the product page\n ' type = resolve_type(self._session, link) if ((type == ProductType.UNKNOWN) or (type == ProductType.LESSON_PLAN) or (type == ProductType.LENS)): return None return Product(self._session, link, type)
Given a link, it will resolve into the product page
bookrags/bookrags.py
resolve_product
qtKite/bookrags
3
python
def resolve_product(self, link: str) -> Product: '\n \n ' type = resolve_type(self._session, link) if ((type == ProductType.UNKNOWN) or (type == ProductType.LESSON_PLAN) or (type == ProductType.LENS)): return None return Product(self._session, link, type)
def resolve_product(self, link: str) -> Product: '\n \n ' type = resolve_type(self._session, link) if ((type == ProductType.UNKNOWN) or (type == ProductType.LESSON_PLAN) or (type == ProductType.LENS)): return None return Product(self._session, link, type)<|docstring|>Given a link, it will resolve into the product page<|endoftext|>
4838ea093381354038ad4b2f76180b5c712558d12f07afc99fbd87ac54bbca8c
def resolve_study_plan(self, link: str) -> Lens: '\n Given a link, it will resolve it into the study guide page and return a Lens instance\n ' type = resolve_type(self._session, link) if (type == ProductType.UNKNOWN): return None if (type == ProductType.LENS): return Lens(self._session, link) page = self._session.get(link).text study_guide = re.search("href='(.*?)'", re.search("<div id='contentSPUpsellBlock'>(.*?)</div>", page, flags=re.DOTALL).group()).group(1) return Lens(self._session, study_guide)
Given a link, it will resolve it into the study guide page and return a Lens instance
bookrags/bookrags.py
resolve_study_plan
qtKite/bookrags
3
python
def resolve_study_plan(self, link: str) -> Lens: '\n \n ' type = resolve_type(self._session, link) if (type == ProductType.UNKNOWN): return None if (type == ProductType.LENS): return Lens(self._session, link) page = self._session.get(link).text study_guide = re.search("href='(.*?)'", re.search("<div id='contentSPUpsellBlock'>(.*?)</div>", page, flags=re.DOTALL).group()).group(1) return Lens(self._session, study_guide)
def resolve_study_plan(self, link: str) -> Lens: '\n \n ' type = resolve_type(self._session, link) if (type == ProductType.UNKNOWN): return None if (type == ProductType.LENS): return Lens(self._session, link) page = self._session.get(link).text study_guide = re.search("href='(.*?)'", re.search("<div id='contentSPUpsellBlock'>(.*?)</div>", page, flags=re.DOTALL).group()).group(1) return Lens(self._session, study_guide)<|docstring|>Given a link, it will resolve it into the study guide page and return a Lens instance<|endoftext|>
f0a26eeb1d103b0aa849e16e3daf134a9d10cbb0e5c80df49b5e64fe52670e5e
def search(self, query: str): '\n Perform a search query and return the results\n ' pass
Perform a search query and return the results
bookrags/bookrags.py
search
qtKite/bookrags
3
python
def search(self, query: str): '\n \n ' pass
def search(self, query: str): '\n \n ' pass<|docstring|>Perform a search query and return the results<|endoftext|>
b72be529741cced2edbc7b99c237a28d2be7c6e958878f0e96588b5dc0d5742e
def __init__(self, diagram: 'Diagram', name: Optional[ConnectorName], connector_type: ConnectorType): '\n Constructor\n\n :param diagram: Reference to the Diagram\n :param connector_type: Name of the Connector Type\n ' Connector.__init__(self, diagram=diagram, name=name, connector_type=connector_type)
Constructor :param diagram: Reference to the Diagram :param connector_type: Name of the Connector Type
flatland/connector_subsystem/binary_connector.py
__init__
lelandstarr/flatland-model-diagram-editor
10
python
def __init__(self, diagram: 'Diagram', name: Optional[ConnectorName], connector_type: ConnectorType): '\n Constructor\n\n :param diagram: Reference to the Diagram\n :param connector_type: Name of the Connector Type\n ' Connector.__init__(self, diagram=diagram, name=name, connector_type=connector_type)
def __init__(self, diagram: 'Diagram', name: Optional[ConnectorName], connector_type: ConnectorType): '\n Constructor\n\n :param diagram: Reference to the Diagram\n :param connector_type: Name of the Connector Type\n ' Connector.__init__(self, diagram=diagram, name=name, connector_type=connector_type)<|docstring|>Constructor :param diagram: Reference to the Diagram :param connector_type: Name of the Connector Type<|endoftext|>
294f13e790e317c01089cc48d324355bcfe6f831c4d7b2c827189f69e44e2146
def __init__(self, hass: HomeAssistant, update_interval: int=DEFAULT_UPDATE_INTERVAL): 'Construct new connection.\n\n Keyword arguments:\n hass -- instance of Home Assistant core\n host -- serial server ip or hostname\n port -- serial server port\n update_interval -- data update interval in seconds\n ' self.ecomax = EcoMAX() self._callbacks: set[Callable[([], Awaitable[None])]] = set() self._check_tries = 0 self._task = None self._hass = hass self._update_interval = update_interval self._connection = self.get_connection() self._uid = None self._model = None self._software = None self._capabilities: list[str] = []
Construct new connection. Keyword arguments: hass -- instance of Home Assistant core host -- serial server ip or hostname port -- serial server port update_interval -- data update interval in seconds
custom_components/plum_ecomax/connection.py
__init__
denpamusic/hassio-plum-ecomax
2
python
def __init__(self, hass: HomeAssistant, update_interval: int=DEFAULT_UPDATE_INTERVAL): 'Construct new connection.\n\n Keyword arguments:\n hass -- instance of Home Assistant core\n host -- serial server ip or hostname\n port -- serial server port\n update_interval -- data update interval in seconds\n ' self.ecomax = EcoMAX() self._callbacks: set[Callable[([], Awaitable[None])]] = set() self._check_tries = 0 self._task = None self._hass = hass self._update_interval = update_interval self._connection = self.get_connection() self._uid = None self._model = None self._software = None self._capabilities: list[str] = []
def __init__(self, hass: HomeAssistant, update_interval: int=DEFAULT_UPDATE_INTERVAL): 'Construct new connection.\n\n Keyword arguments:\n hass -- instance of Home Assistant core\n host -- serial server ip or hostname\n port -- serial server port\n update_interval -- data update interval in seconds\n ' self.ecomax = EcoMAX() self._callbacks: set[Callable[([], Awaitable[None])]] = set() self._check_tries = 0 self._task = None self._hass = hass self._update_interval = update_interval self._connection = self.get_connection() self._uid = None self._model = None self._software = None self._capabilities: list[str] = []<|docstring|>Construct new connection. Keyword arguments: hass -- instance of Home Assistant core host -- serial server ip or hostname port -- serial server port update_interval -- data update interval in seconds<|endoftext|>
ba6ae97e4e085dd7824c0193ce2a4201e080a597db9d4851fcef3e1fbe129009
async def _check_callback(self, devices: DeviceCollection, connection: Connection) -> None: 'Called when connection check succeeds.\n\n Keyword arguments:\n devices -- collection of available devices\n connection -- instance of current connection\n ' if (self._check_tries >= CONNECTION_CHECK_TRIES): _LOGGER.exception('Connection succeeded, but device failed to respond.') return connection.close() if (devices.has('ecomax') and (None not in [devices.ecomax.product.uid, devices.ecomax.product.model, devices.ecomax.modules.module_a]) and (len(devices.ecomax.data) > 1) and (len(devices.ecomax.parameters) > 1)): self._uid = devices.ecomax.product.uid self._model = devices.ecomax.product.model self._software = devices.ecomax.modules.module_a self._capabilities = ['fuel_burned'] self._capabilities += list(devices.ecomax.data.keys()) self._capabilities += list(devices.ecomax.parameters.keys()) if ('water_heater_temp' in self._capabilities): self._capabilities.append('water_heater') return connection.close() self._check_tries += 1
Called when connection check succeeds. Keyword arguments: devices -- collection of available devices connection -- instance of current connection
custom_components/plum_ecomax/connection.py
_check_callback
denpamusic/hassio-plum-ecomax
2
python
async def _check_callback(self, devices: DeviceCollection, connection: Connection) -> None: 'Called when connection check succeeds.\n\n Keyword arguments:\n devices -- collection of available devices\n connection -- instance of current connection\n ' if (self._check_tries >= CONNECTION_CHECK_TRIES): _LOGGER.exception('Connection succeeded, but device failed to respond.') return connection.close() if (devices.has('ecomax') and (None not in [devices.ecomax.product.uid, devices.ecomax.product.model, devices.ecomax.modules.module_a]) and (len(devices.ecomax.data) > 1) and (len(devices.ecomax.parameters) > 1)): self._uid = devices.ecomax.product.uid self._model = devices.ecomax.product.model self._software = devices.ecomax.modules.module_a self._capabilities = ['fuel_burned'] self._capabilities += list(devices.ecomax.data.keys()) self._capabilities += list(devices.ecomax.parameters.keys()) if ('water_heater_temp' in self._capabilities): self._capabilities.append('water_heater') return connection.close() self._check_tries += 1
async def _check_callback(self, devices: DeviceCollection, connection: Connection) -> None: 'Called when connection check succeeds.\n\n Keyword arguments:\n devices -- collection of available devices\n connection -- instance of current connection\n ' if (self._check_tries >= CONNECTION_CHECK_TRIES): _LOGGER.exception('Connection succeeded, but device failed to respond.') return connection.close() if (devices.has('ecomax') and (None not in [devices.ecomax.product.uid, devices.ecomax.product.model, devices.ecomax.modules.module_a]) and (len(devices.ecomax.data) > 1) and (len(devices.ecomax.parameters) > 1)): self._uid = devices.ecomax.product.uid self._model = devices.ecomax.product.model self._software = devices.ecomax.modules.module_a self._capabilities = ['fuel_burned'] self._capabilities += list(devices.ecomax.data.keys()) self._capabilities += list(devices.ecomax.parameters.keys()) if ('water_heater_temp' in self._capabilities): self._capabilities.append('water_heater') return connection.close() self._check_tries += 1<|docstring|>Called when connection check succeeds. Keyword arguments: devices -- collection of available devices connection -- instance of current connection<|endoftext|>
cfb04f90a08a33bc50010a41e8a0a25915e2f3757a7959477d13c45cda173326
async def check(self) -> None: 'Perform connection check.' (await self._connection.task(self._check_callback, interval=1, reconnect_on_failure=False))
Perform connection check.
custom_components/plum_ecomax/connection.py
check
denpamusic/hassio-plum-ecomax
2
python
async def check(self) -> None: (await self._connection.task(self._check_callback, interval=1, reconnect_on_failure=False))
async def check(self) -> None: (await self._connection.task(self._check_callback, interval=1, reconnect_on_failure=False))<|docstring|>Perform connection check.<|endoftext|>
261e6a5e0e7da48b73ef8f892f1eebe0d24e186526796ba12f20966363846afb
async def async_setup(self, entry: ConfigEntry) -> None: 'Setup connection and add hass stop handler.' self._connection.set_eth(ip=(await async_get_source_ip(self._hass, target_ip=IPV4_BROADCAST_ADDR))) self._connection.on_closed(self.connection_closed) self._task = self._hass.loop.create_task(self._connection.task(self.update_entities, self._update_interval)) self._hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, self.close) self._model = entry.data[CONF_MODEL] self._uid = entry.data[CONF_UID] self._software = entry.data[CONF_SOFTWARE] if (CONF_CAPABILITIES in entry.data): self._capabilities = entry.data[CONF_CAPABILITIES]
Setup connection and add hass stop handler.
custom_components/plum_ecomax/connection.py
async_setup
denpamusic/hassio-plum-ecomax
2
python
async def async_setup(self, entry: ConfigEntry) -> None: self._connection.set_eth(ip=(await async_get_source_ip(self._hass, target_ip=IPV4_BROADCAST_ADDR))) self._connection.on_closed(self.connection_closed) self._task = self._hass.loop.create_task(self._connection.task(self.update_entities, self._update_interval)) self._hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, self.close) self._model = entry.data[CONF_MODEL] self._uid = entry.data[CONF_UID] self._software = entry.data[CONF_SOFTWARE] if (CONF_CAPABILITIES in entry.data): self._capabilities = entry.data[CONF_CAPABILITIES]
async def async_setup(self, entry: ConfigEntry) -> None: self._connection.set_eth(ip=(await async_get_source_ip(self._hass, target_ip=IPV4_BROADCAST_ADDR))) self._connection.on_closed(self.connection_closed) self._task = self._hass.loop.create_task(self._connection.task(self.update_entities, self._update_interval)) self._hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, self.close) self._model = entry.data[CONF_MODEL] self._uid = entry.data[CONF_UID] self._software = entry.data[CONF_SOFTWARE] if (CONF_CAPABILITIES in entry.data): self._capabilities = entry.data[CONF_CAPABILITIES]<|docstring|>Setup connection and add hass stop handler.<|endoftext|>
0812ca760985a48af2ea57ec7eccc0ed580e3f0c1abe7f0a7325c6d045520f1a
async def async_unload(self) -> None: 'Close connection on entry unload.' (await self._hass.async_add_executor_job(self.close))
Close connection on entry unload.
custom_components/plum_ecomax/connection.py
async_unload
denpamusic/hassio-plum-ecomax
2
python
async def async_unload(self) -> None: (await self._hass.async_add_executor_job(self.close))
async def async_unload(self) -> None: (await self._hass.async_add_executor_job(self.close))<|docstring|>Close connection on entry unload.<|endoftext|>
83dde61b11c90b084691f5b85cd537366cb8f4e823f2aaf21d2a632c0afc6f87
async def update_entities(self, devices: DeviceCollection, connection: Connection) -> None: 'Update device instance.\n\n Keyword arguments:\n devices -- collection of available devices\n connection -- instance of current connection\n ' if (devices.has('ecomax') and devices.ecomax.data): self.ecomax = devices.ecomax for callback in self._callbacks: (await callback())
Update device instance. Keyword arguments: devices -- collection of available devices connection -- instance of current connection
custom_components/plum_ecomax/connection.py
update_entities
denpamusic/hassio-plum-ecomax
2
python
async def update_entities(self, devices: DeviceCollection, connection: Connection) -> None: 'Update device instance.\n\n Keyword arguments:\n devices -- collection of available devices\n connection -- instance of current connection\n ' if (devices.has('ecomax') and devices.ecomax.data): self.ecomax = devices.ecomax for callback in self._callbacks: (await callback())
async def update_entities(self, devices: DeviceCollection, connection: Connection) -> None: 'Update device instance.\n\n Keyword arguments:\n devices -- collection of available devices\n connection -- instance of current connection\n ' if (devices.has('ecomax') and devices.ecomax.data): self.ecomax = devices.ecomax for callback in self._callbacks: (await callback())<|docstring|>Update device instance. Keyword arguments: devices -- collection of available devices connection -- instance of current connection<|endoftext|>
b43db69e1a97af1a5881d02fbeeb2913d6cfa1d1751de8916033ceb0b78e1eca
async def connection_closed(self, connection: Connection) -> None: 'If connection is closed, set entities state to unknown.\n\n Keyword arguments:\n connection -- instance of current connection\n ' self.ecomax = EcoMAX() for callback in self._callbacks: (await callback())
If connection is closed, set entities state to unknown. Keyword arguments: connection -- instance of current connection
custom_components/plum_ecomax/connection.py
connection_closed
denpamusic/hassio-plum-ecomax
2
python
async def connection_closed(self, connection: Connection) -> None: 'If connection is closed, set entities state to unknown.\n\n Keyword arguments:\n connection -- instance of current connection\n ' self.ecomax = EcoMAX() for callback in self._callbacks: (await callback())
async def connection_closed(self, connection: Connection) -> None: 'If connection is closed, set entities state to unknown.\n\n Keyword arguments:\n connection -- instance of current connection\n ' self.ecomax = EcoMAX() for callback in self._callbacks: (await callback())<|docstring|>If connection is closed, set entities state to unknown. Keyword arguments: connection -- instance of current connection<|endoftext|>
2c7d0b8717cc324b1d51042de56a656d2c896153c66fe6964eeae613926902c5
def register_callback(self, callback: Callable[([], Awaitable[None])]) -> None: 'Register callback that are called on state change.\n\n Keyword arguments:\n callback -- callback for registration\n ' self._callbacks.add(callback)
Register callback that are called on state change. Keyword arguments: callback -- callback for registration
custom_components/plum_ecomax/connection.py
register_callback
denpamusic/hassio-plum-ecomax
2
python
def register_callback(self, callback: Callable[([], Awaitable[None])]) -> None: 'Register callback that are called on state change.\n\n Keyword arguments:\n callback -- callback for registration\n ' self._callbacks.add(callback)
def register_callback(self, callback: Callable[([], Awaitable[None])]) -> None: 'Register callback that are called on state change.\n\n Keyword arguments:\n callback -- callback for registration\n ' self._callbacks.add(callback)<|docstring|>Register callback that are called on state change. Keyword arguments: callback -- callback for registration<|endoftext|>
bd2e9564fa66ab3c82adb6810f7b5c58eed822221d80a0ff060f9701730a0138
def remove_callback(self, callback: Callable[([], Awaitable[None])]) -> None: 'Remove previously registered callback.\n\n Keyword arguments:\n callback -- callback for removal\n ' self._callbacks.discard(callback)
Remove previously registered callback. Keyword arguments: callback -- callback for removal
custom_components/plum_ecomax/connection.py
remove_callback
denpamusic/hassio-plum-ecomax
2
python
def remove_callback(self, callback: Callable[([], Awaitable[None])]) -> None: 'Remove previously registered callback.\n\n Keyword arguments:\n callback -- callback for removal\n ' self._callbacks.discard(callback)
def remove_callback(self, callback: Callable[([], Awaitable[None])]) -> None: 'Remove previously registered callback.\n\n Keyword arguments:\n callback -- callback for removal\n ' self._callbacks.discard(callback)<|docstring|>Remove previously registered callback. Keyword arguments: callback -- callback for removal<|endoftext|>
3cdc0b217f136352c4b20eb0c340f40bd58c65051661f1e017ab0fac2918229f
def close(self, event=None) -> None: 'Close connection and cancel connection coroutine.' self._connection.on_closed(callback=None) self._connection.close() if self._task: self._task.cancel()
Close connection and cancel connection coroutine.
custom_components/plum_ecomax/connection.py
close
denpamusic/hassio-plum-ecomax
2
python
def close(self, event=None) -> None: self._connection.on_closed(callback=None) self._connection.close() if self._task: self._task.cancel()
def close(self, event=None) -> None: self._connection.on_closed(callback=None) self._connection.close() if self._task: self._task.cancel()<|docstring|>Close connection and cancel connection coroutine.<|endoftext|>
a955fbb2196b60a5d3b2f07e3b50dde47602fdb92c8a558cd2d5d97c309db2a6
@property def model(self) -> Optional[str]: 'Return the product model.' if (self._model is None): return None return self._model.replace('EM', 'ecoMAX ')
Return the product model.
custom_components/plum_ecomax/connection.py
model
denpamusic/hassio-plum-ecomax
2
python
@property def model(self) -> Optional[str]: if (self._model is None): return None return self._model.replace('EM', 'ecoMAX ')
@property def model(self) -> Optional[str]: if (self._model is None): return None return self._model.replace('EM', 'ecoMAX ')<|docstring|>Return the product model.<|endoftext|>
e50ee2201e34214865b7698d23aee34d17f31b307cd3f92a070451c30b06cac2
@property def uid(self) -> Optional[str]: 'Return the product UID.' return self._uid
Return the product UID.
custom_components/plum_ecomax/connection.py
uid
denpamusic/hassio-plum-ecomax
2
python
@property def uid(self) -> Optional[str]: return self._uid
@property def uid(self) -> Optional[str]: return self._uid<|docstring|>Return the product UID.<|endoftext|>
deb104035e20f51e674b651f8d28a1219c20e020ecb1e5bead6acc82ccf05098
@property def software(self) -> Optional[str]: 'Return the product software version.' return self._software
Return the product software version.
custom_components/plum_ecomax/connection.py
software
denpamusic/hassio-plum-ecomax
2
python
@property def software(self) -> Optional[str]: return self._software
@property def software(self) -> Optional[str]: return self._software<|docstring|>Return the product software version.<|endoftext|>
1d8dc65621b077d1f0e268cd8ee202140b11f67b2849a052e2cb934cfe6aa0b8
@property def capabilities(self) -> list[str]: 'Return the product capabilities.' return self._capabilities
Return the product capabilities.
custom_components/plum_ecomax/connection.py
capabilities
denpamusic/hassio-plum-ecomax
2
python
@property def capabilities(self) -> list[str]: return self._capabilities
@property def capabilities(self) -> list[str]: return self._capabilities<|docstring|>Return the product capabilities.<|endoftext|>
fe6a64c6013d3e68adce7d3e6d2986e50101c992a5728e897c2e064ad23a9f7e
@property def update_interval(self) -> Optional[int]: 'Return update interval in seconds.' return self._update_interval
Return update interval in seconds.
custom_components/plum_ecomax/connection.py
update_interval
denpamusic/hassio-plum-ecomax
2
python
@property def update_interval(self) -> Optional[int]: return self._update_interval
@property def update_interval(self) -> Optional[int]: return self._update_interval<|docstring|>Return update interval in seconds.<|endoftext|>
64bb7a68fddfa20cd1118ff0ebfce6e580d2eeeb8e1c575bb67d76e7689ec268
@abstractmethod def get_connection(self) -> Connection: 'Return connection instance.'
Return connection instance.
custom_components/plum_ecomax/connection.py
get_connection
denpamusic/hassio-plum-ecomax
2
python
@abstractmethod def get_connection(self) -> Connection:
@abstractmethod def get_connection(self) -> Connection: <|docstring|>Return connection instance.<|endoftext|>
01b2d2b9fd51ae31be9d9e9f91eeaba95807761beaf7c6094b5fa1ff08de331b
@property @abstractmethod def name(self) -> str: 'Return connection name.'
Return connection name.
custom_components/plum_ecomax/connection.py
name
denpamusic/hassio-plum-ecomax
2
python
@property @abstractmethod def name(self) -> str:
@property @abstractmethod def name(self) -> str: <|docstring|>Return connection name.<|endoftext|>
13044fce4596365369032056388dc4c663809f446c6bb73967d770c9c645e11a
@property def device_info(self) -> DeviceInfo: 'Return device info.' return DeviceInfo(name=self.name, identifiers={(DOMAIN, self.uid)}, manufacturer='Plum Sp. z o.o.', model=f'{self.model} (uid: {self.uid})', sw_version=self.software)
Return device info.
custom_components/plum_ecomax/connection.py
device_info
denpamusic/hassio-plum-ecomax
2
python
@property def device_info(self) -> DeviceInfo: return DeviceInfo(name=self.name, identifiers={(DOMAIN, self.uid)}, manufacturer='Plum Sp. z o.o.', model=f'{self.model} (uid: {self.uid})', sw_version=self.software)
@property def device_info(self) -> DeviceInfo: return DeviceInfo(name=self.name, identifiers={(DOMAIN, self.uid)}, manufacturer='Plum Sp. z o.o.', model=f'{self.model} (uid: {self.uid})', sw_version=self.software)<|docstring|>Return device info.<|endoftext|>
53bd15f68535d3aa84936a551b42f51adf3e6b7ffde776cfcf3cb8d905520717
def __init__(self, host, port: int=DEFAULT_PORT, **kwargs): 'Construct new connection.\n\n Keyword arguments:\n host -- serial server ip or hostname\n port -- serial server port\n ' self._host = host self._port = port super().__init__(**kwargs)
Construct new connection. Keyword arguments: host -- serial server ip or hostname port -- serial server port
custom_components/plum_ecomax/connection.py
__init__
denpamusic/hassio-plum-ecomax
2
python
def __init__(self, host, port: int=DEFAULT_PORT, **kwargs): 'Construct new connection.\n\n Keyword arguments:\n host -- serial server ip or hostname\n port -- serial server port\n ' self._host = host self._port = port super().__init__(**kwargs)
def __init__(self, host, port: int=DEFAULT_PORT, **kwargs): 'Construct new connection.\n\n Keyword arguments:\n host -- serial server ip or hostname\n port -- serial server port\n ' self._host = host self._port = port super().__init__(**kwargs)<|docstring|>Construct new connection. Keyword arguments: host -- serial server ip or hostname port -- serial server port<|endoftext|>
a159f934aff3a17a7fefa2c894227ebdd8d9ad94da6e7bf37262dbaa83df15d7
def get_connection(self) -> Connection: 'Return connection instance.' if (hasattr(self, '_connection') and isinstance(self._connection, Connection)): return self._connection return pyplumio.TcpConnection(self._host, self._port)
Return connection instance.
custom_components/plum_ecomax/connection.py
get_connection
denpamusic/hassio-plum-ecomax
2
python
def get_connection(self) -> Connection: if (hasattr(self, '_connection') and isinstance(self._connection, Connection)): return self._connection return pyplumio.TcpConnection(self._host, self._port)
def get_connection(self) -> Connection: if (hasattr(self, '_connection') and isinstance(self._connection, Connection)): return self._connection return pyplumio.TcpConnection(self._host, self._port)<|docstring|>Return connection instance.<|endoftext|>
1c2d3cdb248b73a405ab6a377e6a82753ea823d9a76d3207f45e331d5e71c1ee
@property def name(self) -> str: 'Return connection name.' return self._host
Return connection name.
custom_components/plum_ecomax/connection.py
name
denpamusic/hassio-plum-ecomax
2
python
@property def name(self) -> str: return self._host
@property def name(self) -> str: return self._host<|docstring|>Return connection name.<|endoftext|>
2d480d6fe506bbeb4743f48747e020ac275f5d59f29f5d2a134ef902b8290fa2
@property def host(self) -> str: 'Return connection host.' return self._host
Return connection host.
custom_components/plum_ecomax/connection.py
host
denpamusic/hassio-plum-ecomax
2
python
@property def host(self) -> str: return self._host
@property def host(self) -> str: return self._host<|docstring|>Return connection host.<|endoftext|>
64ffa7199cb490e3670c5e8d49a2b8126f27c4f2796092a27589ee091e3e6182
@property def port(self) -> int: 'Return connection port.' return self._port
Return connection port.
custom_components/plum_ecomax/connection.py
port
denpamusic/hassio-plum-ecomax
2
python
@property def port(self) -> int: return self._port
@property def port(self) -> int: return self._port<|docstring|>Return connection port.<|endoftext|>
bfac62c96ef3d0518405ef09ba0817de668f768029a9654b699d16c9dfa707d1
def __init__(self, device: str=DEFAULT_DEVICE, **kwargs): 'Construct new connection.\n\n Keyword arguments:\n device -- serial device path, e. g. /dev/ttyUSB0\n ' self._device = device super().__init__(**kwargs)
Construct new connection. Keyword arguments: device -- serial device path, e. g. /dev/ttyUSB0
custom_components/plum_ecomax/connection.py
__init__
denpamusic/hassio-plum-ecomax
2
python
def __init__(self, device: str=DEFAULT_DEVICE, **kwargs): 'Construct new connection.\n\n Keyword arguments:\n device -- serial device path, e. g. /dev/ttyUSB0\n ' self._device = device super().__init__(**kwargs)
def __init__(self, device: str=DEFAULT_DEVICE, **kwargs): 'Construct new connection.\n\n Keyword arguments:\n device -- serial device path, e. g. /dev/ttyUSB0\n ' self._device = device super().__init__(**kwargs)<|docstring|>Construct new connection. Keyword arguments: device -- serial device path, e. g. /dev/ttyUSB0<|endoftext|>
7ef4948504f42222b40ddb802e849ca8c7a21e859541f4e03ea6a6e42311ce8a
def get_connection(self) -> Connection: 'Return connection instance.' if (hasattr(self, '_connection') and isinstance(self._connection, Connection)): return self._connection return pyplumio.SerialConnection(self._device)
Return connection instance.
custom_components/plum_ecomax/connection.py
get_connection
denpamusic/hassio-plum-ecomax
2
python
def get_connection(self) -> Connection: if (hasattr(self, '_connection') and isinstance(self._connection, Connection)): return self._connection return pyplumio.SerialConnection(self._device)
def get_connection(self) -> Connection: if (hasattr(self, '_connection') and isinstance(self._connection, Connection)): return self._connection return pyplumio.SerialConnection(self._device)<|docstring|>Return connection instance.<|endoftext|>
b8cafc8a9472b5817ea6158420466f31a01f665644817957ac0778760554f87c
@property def name(self) -> str: 'Return connection name.' return self._device
Return connection name.
custom_components/plum_ecomax/connection.py
name
denpamusic/hassio-plum-ecomax
2
python
@property def name(self) -> str: return self._device
@property def name(self) -> str: return self._device<|docstring|>Return connection name.<|endoftext|>
7e6482770e8bc536393f22b29eff04cf6a893a3892da918e74d274174aad53dd
@property def device(self) -> str: 'Return connection device.' return self._device
Return connection device.
custom_components/plum_ecomax/connection.py
device
denpamusic/hassio-plum-ecomax
2
python
@property def device(self) -> str: return self._device
@property def device(self) -> str: return self._device<|docstring|>Return connection device.<|endoftext|>
dc5e2b86332a642ebca84fede10db85f86acc5b38a505fcd944d964e69d03599
def is_elem_ref(elem_ref): '\n Returns true if the elem_ref is an element reference\n\n :param elem_ref:\n :return:\n ' return (elem_ref and isinstance(elem_ref, tuple) and (len(elem_ref) == 3) and ((elem_ref[0] == ElemRefObj) or (elem_ref[0] == ElemRefArr)))
Returns true if the elem_ref is an element reference :param elem_ref: :return:
monero_serialize/core/erefs.py
is_elem_ref
TheCharlatan/monero-serialize
8
python
def is_elem_ref(elem_ref): '\n Returns true if the elem_ref is an element reference\n\n :param elem_ref:\n :return:\n ' return (elem_ref and isinstance(elem_ref, tuple) and (len(elem_ref) == 3) and ((elem_ref[0] == ElemRefObj) or (elem_ref[0] == ElemRefArr)))
def is_elem_ref(elem_ref): '\n Returns true if the elem_ref is an element reference\n\n :param elem_ref:\n :return:\n ' return (elem_ref and isinstance(elem_ref, tuple) and (len(elem_ref) == 3) and ((elem_ref[0] == ElemRefObj) or (elem_ref[0] == ElemRefArr)))<|docstring|>Returns true if the elem_ref is an element reference :param elem_ref: :return:<|endoftext|>
9bc077cfee90f94c93ae82548632014769c3c6bb25e980448b7c18e6545dca21
def has_elem(elem_ref): '\n Has element?\n :param elem_ref:\n :return:\n ' if (not is_elem_ref(elem_ref)): return False elif (elem_ref[0] == ElemRefObj): return hasattr(elem_ref[1], elem_ref[2]) elif (elem_ref[0] == ElemRefArr): return (elem_ref[2] in elem_ref[1])
Has element? :param elem_ref: :return:
monero_serialize/core/erefs.py
has_elem
TheCharlatan/monero-serialize
8
python
def has_elem(elem_ref): '\n Has element?\n :param elem_ref:\n :return:\n ' if (not is_elem_ref(elem_ref)): return False elif (elem_ref[0] == ElemRefObj): return hasattr(elem_ref[1], elem_ref[2]) elif (elem_ref[0] == ElemRefArr): return (elem_ref[2] in elem_ref[1])
def has_elem(elem_ref): '\n Has element?\n :param elem_ref:\n :return:\n ' if (not is_elem_ref(elem_ref)): return False elif (elem_ref[0] == ElemRefObj): return hasattr(elem_ref[1], elem_ref[2]) elif (elem_ref[0] == ElemRefArr): return (elem_ref[2] in elem_ref[1])<|docstring|>Has element? :param elem_ref: :return:<|endoftext|>
cf95a31c5121f804c46f61f58cdf105cc95f752b4db79b3cc7672bbec68b0e3f
def get_elem(elem_ref, default=None): '\n Gets the element referenced by elem_ref or returns the elem_ref directly if its not a reference.\n\n :param elem_ref:\n :param default:\n :return:\n ' if (not is_elem_ref(elem_ref)): return elem_ref elif (elem_ref[0] == ElemRefObj): return getattr(elem_ref[1], elem_ref[2], default) elif (elem_ref[0] == ElemRefArr): return elem_ref[1][elem_ref[2]]
Gets the element referenced by elem_ref or returns the elem_ref directly if its not a reference. :param elem_ref: :param default: :return:
monero_serialize/core/erefs.py
get_elem
TheCharlatan/monero-serialize
8
python
def get_elem(elem_ref, default=None): '\n Gets the element referenced by elem_ref or returns the elem_ref directly if its not a reference.\n\n :param elem_ref:\n :param default:\n :return:\n ' if (not is_elem_ref(elem_ref)): return elem_ref elif (elem_ref[0] == ElemRefObj): return getattr(elem_ref[1], elem_ref[2], default) elif (elem_ref[0] == ElemRefArr): return elem_ref[1][elem_ref[2]]
def get_elem(elem_ref, default=None): '\n Gets the element referenced by elem_ref or returns the elem_ref directly if its not a reference.\n\n :param elem_ref:\n :param default:\n :return:\n ' if (not is_elem_ref(elem_ref)): return elem_ref elif (elem_ref[0] == ElemRefObj): return getattr(elem_ref[1], elem_ref[2], default) elif (elem_ref[0] == ElemRefArr): return elem_ref[1][elem_ref[2]]<|docstring|>Gets the element referenced by elem_ref or returns the elem_ref directly if its not a reference. :param elem_ref: :param default: :return:<|endoftext|>
d57c21ac6f5fb0abfb9f7c28c05a68c103de4b89216a4900461fb74e223bf81f
def set_elem(elem_ref, elem): '\n Sets element referenced by the elem_ref. Returns the elem.\n\n :param elem_ref:\n :param elem:\n :return:\n ' if ((elem_ref is None) or (elem_ref == elem) or (not is_elem_ref(elem_ref))): return elem elif (elem_ref[0] == ElemRefObj): setattr(elem_ref[1], elem_ref[2], elem) return elem elif (elem_ref[0] == ElemRefArr): elem_ref[1][elem_ref[2]] = elem return elem
Sets element referenced by the elem_ref. Returns the elem. :param elem_ref: :param elem: :return:
monero_serialize/core/erefs.py
set_elem
TheCharlatan/monero-serialize
8
python
def set_elem(elem_ref, elem): '\n Sets element referenced by the elem_ref. Returns the elem.\n\n :param elem_ref:\n :param elem:\n :return:\n ' if ((elem_ref is None) or (elem_ref == elem) or (not is_elem_ref(elem_ref))): return elem elif (elem_ref[0] == ElemRefObj): setattr(elem_ref[1], elem_ref[2], elem) return elem elif (elem_ref[0] == ElemRefArr): elem_ref[1][elem_ref[2]] = elem return elem
def set_elem(elem_ref, elem): '\n Sets element referenced by the elem_ref. Returns the elem.\n\n :param elem_ref:\n :param elem:\n :return:\n ' if ((elem_ref is None) or (elem_ref == elem) or (not is_elem_ref(elem_ref))): return elem elif (elem_ref[0] == ElemRefObj): setattr(elem_ref[1], elem_ref[2], elem) return elem elif (elem_ref[0] == ElemRefArr): elem_ref[1][elem_ref[2]] = elem return elem<|docstring|>Sets element referenced by the elem_ref. Returns the elem. :param elem_ref: :param elem: :return:<|endoftext|>
c2cf0b07327732913ebb20343c3214caa34eab54a2af14e751d787786b3608b7
def eref(obj, key, is_assoc=None): '\n Returns element reference\n :param obj:\n :param key:\n :param is_assoc:\n :return:\n ' if (obj is None): return None if (isinstance(key, int) or ((is_assoc is not None) and is_assoc)): return (ElemRefArr, get_elem(obj), key) else: return (ElemRefObj, get_elem(obj), key)
Returns element reference :param obj: :param key: :param is_assoc: :return:
monero_serialize/core/erefs.py
eref
TheCharlatan/monero-serialize
8
python
def eref(obj, key, is_assoc=None): '\n Returns element reference\n :param obj:\n :param key:\n :param is_assoc:\n :return:\n ' if (obj is None): return None if (isinstance(key, int) or ((is_assoc is not None) and is_assoc)): return (ElemRefArr, get_elem(obj), key) else: return (ElemRefObj, get_elem(obj), key)
def eref(obj, key, is_assoc=None): '\n Returns element reference\n :param obj:\n :param key:\n :param is_assoc:\n :return:\n ' if (obj is None): return None if (isinstance(key, int) or ((is_assoc is not None) and is_assoc)): return (ElemRefArr, get_elem(obj), key) else: return (ElemRefObj, get_elem(obj), key)<|docstring|>Returns element reference :param obj: :param key: :param is_assoc: :return:<|endoftext|>
d805c6183195bcfe4f7b86792fc976ca61205d5a18db8548cd8c9203f032ec6f
def test_split_raster(config, tmpdir): 'Split raster into crops with overlaps to maintain all annotations' raster = get_data('2019_YELL_2_528000_4978000_image_crop2.png') annotations = utilities.xml_to_annotations(get_data('2019_YELL_2_528000_4978000_image_crop2.xml')) annotations.to_csv('{}/example.csv'.format(tmpdir), index=False) annotations_file = preprocess.split_raster(path_to_raster=raster, annotations_file='{}/example.csv'.format(tmpdir), base_dir=tmpdir, patch_size=500, patch_overlap=0) assert (annotations_file.shape[1] == 6)
Split raster into crops with overlaps to maintain all annotations
tests/test_preprocess.py
test_split_raster
addiercv/DeepForest
249
python
def test_split_raster(config, tmpdir): raster = get_data('2019_YELL_2_528000_4978000_image_crop2.png') annotations = utilities.xml_to_annotations(get_data('2019_YELL_2_528000_4978000_image_crop2.xml')) annotations.to_csv('{}/example.csv'.format(tmpdir), index=False) annotations_file = preprocess.split_raster(path_to_raster=raster, annotations_file='{}/example.csv'.format(tmpdir), base_dir=tmpdir, patch_size=500, patch_overlap=0) assert (annotations_file.shape[1] == 6)
def test_split_raster(config, tmpdir): raster = get_data('2019_YELL_2_528000_4978000_image_crop2.png') annotations = utilities.xml_to_annotations(get_data('2019_YELL_2_528000_4978000_image_crop2.xml')) annotations.to_csv('{}/example.csv'.format(tmpdir), index=False) annotations_file = preprocess.split_raster(path_to_raster=raster, annotations_file='{}/example.csv'.format(tmpdir), base_dir=tmpdir, patch_size=500, patch_overlap=0) assert (annotations_file.shape[1] == 6)<|docstring|>Split raster into crops with overlaps to maintain all annotations<|endoftext|>
33e15a76069ab2ccbc551e974fac8fdbaeb1bb7eff65897cffdc984059a968dc
def test_split_raster_empty_crops(config, tmpdir): 'Split raster into crops with overlaps to maintain all annotations, allow empty crops' raster = get_data('2019_YELL_2_528000_4978000_image_crop2.png') annotations = utilities.xml_to_annotations(get_data('2019_YELL_2_528000_4978000_image_crop2.xml')) annotations.to_csv('{}/example.csv'.format(tmpdir), index=False) annotations_file = preprocess.split_raster(path_to_raster=raster, annotations_file='{}/example.csv'.format(tmpdir), base_dir=tmpdir, patch_size=100, patch_overlap=0, allow_empty=True) assert (not annotations_file[((annotations_file.xmin == 0) & (annotations_file.xmax == 0))].empty)
Split raster into crops with overlaps to maintain all annotations, allow empty crops
tests/test_preprocess.py
test_split_raster_empty_crops
addiercv/DeepForest
249
python
def test_split_raster_empty_crops(config, tmpdir): raster = get_data('2019_YELL_2_528000_4978000_image_crop2.png') annotations = utilities.xml_to_annotations(get_data('2019_YELL_2_528000_4978000_image_crop2.xml')) annotations.to_csv('{}/example.csv'.format(tmpdir), index=False) annotations_file = preprocess.split_raster(path_to_raster=raster, annotations_file='{}/example.csv'.format(tmpdir), base_dir=tmpdir, patch_size=100, patch_overlap=0, allow_empty=True) assert (not annotations_file[((annotations_file.xmin == 0) & (annotations_file.xmax == 0))].empty)
def test_split_raster_empty_crops(config, tmpdir): raster = get_data('2019_YELL_2_528000_4978000_image_crop2.png') annotations = utilities.xml_to_annotations(get_data('2019_YELL_2_528000_4978000_image_crop2.xml')) annotations.to_csv('{}/example.csv'.format(tmpdir), index=False) annotations_file = preprocess.split_raster(path_to_raster=raster, annotations_file='{}/example.csv'.format(tmpdir), base_dir=tmpdir, patch_size=100, patch_overlap=0, allow_empty=True) assert (not annotations_file[((annotations_file.xmin == 0) & (annotations_file.xmax == 0))].empty)<|docstring|>Split raster into crops with overlaps to maintain all annotations, allow empty crops<|endoftext|>
16ab4d34ecf1a724a3e7450dc5ee4726162948d997e6cd1de00d41ca0bcc92f3
@contextlib.contextmanager def cpmap(cores=1): 'Configurable parallel map context manager.\n\n Returns appropriate map compatible function based on configuration:\n - Local single core (the default)\n - Multiple local cores\n ' if (int(cores) == 1): (yield itertools.imap) else: if (multiprocessing is None): raise ImportError('multiprocessing not available') def wrapper(func): def wrap(self, timeout=None): return func(self, timeout=(timeout if (timeout is not None) else 1e+100)) return wrap IMapIterator.next = wrapper(IMapIterator.next) try: pool = multiprocessing.Pool(int(cores), maxtasksperchild=1) except TypeError: pool = multiprocessing.Pool(int(cores)) (yield pool.imap_unordered) pool.terminate()
Configurable parallel map context manager. Returns appropriate map compatible function based on configuration: - Local single core (the default) - Multiple local cores
nextgen/bcbio/utils.py
cpmap
bgruening/bcbb
339
python
@contextlib.contextmanager def cpmap(cores=1): 'Configurable parallel map context manager.\n\n Returns appropriate map compatible function based on configuration:\n - Local single core (the default)\n - Multiple local cores\n ' if (int(cores) == 1): (yield itertools.imap) else: if (multiprocessing is None): raise ImportError('multiprocessing not available') def wrapper(func): def wrap(self, timeout=None): return func(self, timeout=(timeout if (timeout is not None) else 1e+100)) return wrap IMapIterator.next = wrapper(IMapIterator.next) try: pool = multiprocessing.Pool(int(cores), maxtasksperchild=1) except TypeError: pool = multiprocessing.Pool(int(cores)) (yield pool.imap_unordered) pool.terminate()
@contextlib.contextmanager def cpmap(cores=1): 'Configurable parallel map context manager.\n\n Returns appropriate map compatible function based on configuration:\n - Local single core (the default)\n - Multiple local cores\n ' if (int(cores) == 1): (yield itertools.imap) else: if (multiprocessing is None): raise ImportError('multiprocessing not available') def wrapper(func): def wrap(self, timeout=None): return func(self, timeout=(timeout if (timeout is not None) else 1e+100)) return wrap IMapIterator.next = wrapper(IMapIterator.next) try: pool = multiprocessing.Pool(int(cores), maxtasksperchild=1) except TypeError: pool = multiprocessing.Pool(int(cores)) (yield pool.imap_unordered) pool.terminate()<|docstring|>Configurable parallel map context manager. Returns appropriate map compatible function based on configuration: - Local single core (the default) - Multiple local cores<|endoftext|>
252e76e0e9a84cdbf5ce531df7d5a0e3eaf93000f6980b24b70c30d40f3c4304
def map_wrap(f): "Wrap standard function to easily pass into 'map' processing.\n " @functools.wraps(f) def wrapper(*args, **kwargs): return apply(f, *args, **kwargs) return wrapper
Wrap standard function to easily pass into 'map' processing.
nextgen/bcbio/utils.py
map_wrap
bgruening/bcbb
339
python
def map_wrap(f): "\n " @functools.wraps(f) def wrapper(*args, **kwargs): return apply(f, *args, **kwargs) return wrapper
def map_wrap(f): "\n " @functools.wraps(f) def wrapper(*args, **kwargs): return apply(f, *args, **kwargs) return wrapper<|docstring|>Wrap standard function to easily pass into 'map' processing.<|endoftext|>
cbe34648baa9c8ab3584bc0b57c51b417757103a6aed467362093ad6bf60330b
def transform_to(ext): '\n Decorator to create an output filename from an output filename with\n the specified extension. Changes the extension, in_file is transformed\n to a new type.\n\n Takes functions like this to decorate:\n f(in_file, out_dir=None, out_file=None) or,\n f(in_file=in_file, out_dir=None, out_file=None)\n\n examples:\n @transform(".bam")\n f("the/input/path/file.sam") ->\n f("the/input/path/file.sam", out_file="the/input/path/file.bam")\n\n @transform(".bam")\n f("the/input/path/file.sam", out_dir="results") ->\n f("the/input/path/file.sam", out_file="results/file.bam")\n\n ' def decor(f): @functools.wraps(f) def wrapper(*args, **kwargs): out_file = kwargs.get('out_file', None) if (not out_file): in_path = kwargs.get('in_file', args[0]) out_dir = kwargs.get('out_dir', os.path.dirname(in_path)) if (out_dir is None): out_dir = os.path.dirname(in_path) if out_dir: safe_makedir(out_dir) out_name = replace_suffix(os.path.basename(in_path), ext) out_file = os.path.join(out_dir, out_name) kwargs['out_file'] = out_file if (not file_exists(out_file)): out_file = f(*args, **kwargs) return out_file return wrapper return decor
Decorator to create an output filename from an output filename with the specified extension. Changes the extension, in_file is transformed to a new type. Takes functions like this to decorate: f(in_file, out_dir=None, out_file=None) or, f(in_file=in_file, out_dir=None, out_file=None) examples: @transform(".bam") f("the/input/path/file.sam") -> f("the/input/path/file.sam", out_file="the/input/path/file.bam") @transform(".bam") f("the/input/path/file.sam", out_dir="results") -> f("the/input/path/file.sam", out_file="results/file.bam")
nextgen/bcbio/utils.py
transform_to
bgruening/bcbb
339
python
def transform_to(ext): '\n Decorator to create an output filename from an output filename with\n the specified extension. Changes the extension, in_file is transformed\n to a new type.\n\n Takes functions like this to decorate:\n f(in_file, out_dir=None, out_file=None) or,\n f(in_file=in_file, out_dir=None, out_file=None)\n\n examples:\n @transform(".bam")\n f("the/input/path/file.sam") ->\n f("the/input/path/file.sam", out_file="the/input/path/file.bam")\n\n @transform(".bam")\n f("the/input/path/file.sam", out_dir="results") ->\n f("the/input/path/file.sam", out_file="results/file.bam")\n\n ' def decor(f): @functools.wraps(f) def wrapper(*args, **kwargs): out_file = kwargs.get('out_file', None) if (not out_file): in_path = kwargs.get('in_file', args[0]) out_dir = kwargs.get('out_dir', os.path.dirname(in_path)) if (out_dir is None): out_dir = os.path.dirname(in_path) if out_dir: safe_makedir(out_dir) out_name = replace_suffix(os.path.basename(in_path), ext) out_file = os.path.join(out_dir, out_name) kwargs['out_file'] = out_file if (not file_exists(out_file)): out_file = f(*args, **kwargs) return out_file return wrapper return decor
def transform_to(ext): '\n Decorator to create an output filename from an output filename with\n the specified extension. Changes the extension, in_file is transformed\n to a new type.\n\n Takes functions like this to decorate:\n f(in_file, out_dir=None, out_file=None) or,\n f(in_file=in_file, out_dir=None, out_file=None)\n\n examples:\n @transform(".bam")\n f("the/input/path/file.sam") ->\n f("the/input/path/file.sam", out_file="the/input/path/file.bam")\n\n @transform(".bam")\n f("the/input/path/file.sam", out_dir="results") ->\n f("the/input/path/file.sam", out_file="results/file.bam")\n\n ' def decor(f): @functools.wraps(f) def wrapper(*args, **kwargs): out_file = kwargs.get('out_file', None) if (not out_file): in_path = kwargs.get('in_file', args[0]) out_dir = kwargs.get('out_dir', os.path.dirname(in_path)) if (out_dir is None): out_dir = os.path.dirname(in_path) if out_dir: safe_makedir(out_dir) out_name = replace_suffix(os.path.basename(in_path), ext) out_file = os.path.join(out_dir, out_name) kwargs['out_file'] = out_file if (not file_exists(out_file)): out_file = f(*args, **kwargs) return out_file return wrapper return decor<|docstring|>Decorator to create an output filename from an output filename with the specified extension. Changes the extension, in_file is transformed to a new type. Takes functions like this to decorate: f(in_file, out_dir=None, out_file=None) or, f(in_file=in_file, out_dir=None, out_file=None) examples: @transform(".bam") f("the/input/path/file.sam") -> f("the/input/path/file.sam", out_file="the/input/path/file.bam") @transform(".bam") f("the/input/path/file.sam", out_dir="results") -> f("the/input/path/file.sam", out_file="results/file.bam")<|endoftext|>
d0080282d002b4c13a16b5ff7cfeb5f79461e75327c8d8d899a89873933aa629
def filter_to(word): '\n Decorator to create an output filename from an input filename by\n adding a word onto the stem. in_file is filtered by the function\n and the results are written to out_file. You would want to use\n this over transform_to if you don\'t know the extension of the file\n going in. This also memoizes the output file.\n\n Takes functions like this to decorate:\n f(in_file, out_dir=None, out_file=None) or,\n f(in_file=in_file, out_dir=None, out_file=None)\n\n examples:\n @filter_to("foo")\n f("the/input/path/file.sam") ->\n f("the/input/path/file.sam", out_file="the/input/path/file_foo.bam")\n\n @filter_to("foo")\n f("the/input/path/file.sam", out_dir="results") ->\n f("the/input/path/file.sam", out_file="results/file_foo.bam")\n\n ' def decor(f): @functools.wraps(f) def wrapper(*args, **kwargs): out_file = kwargs.get('out_file', None) if (not out_file): in_path = kwargs.get('in_file', args[0]) out_dir = kwargs.get('out_dir', os.path.dirname(in_path)) if (out_dir is None): out_dir = os.path.dirname(in_path) if out_dir: safe_makedir(out_dir) out_name = append_stem(os.path.basename(in_path), word, '_') out_file = os.path.join(out_dir, out_name) kwargs['out_file'] = out_file if (not file_exists(out_file)): out_file = f(*args, **kwargs) return out_file return wrapper return decor
Decorator to create an output filename from an input filename by adding a word onto the stem. in_file is filtered by the function and the results are written to out_file. You would want to use this over transform_to if you don't know the extension of the file going in. This also memoizes the output file. Takes functions like this to decorate: f(in_file, out_dir=None, out_file=None) or, f(in_file=in_file, out_dir=None, out_file=None) examples: @filter_to("foo") f("the/input/path/file.sam") -> f("the/input/path/file.sam", out_file="the/input/path/file_foo.bam") @filter_to("foo") f("the/input/path/file.sam", out_dir="results") -> f("the/input/path/file.sam", out_file="results/file_foo.bam")
nextgen/bcbio/utils.py
filter_to
bgruening/bcbb
339
python
def filter_to(word): '\n Decorator to create an output filename from an input filename by\n adding a word onto the stem. in_file is filtered by the function\n and the results are written to out_file. You would want to use\n this over transform_to if you don\'t know the extension of the file\n going in. This also memoizes the output file.\n\n Takes functions like this to decorate:\n f(in_file, out_dir=None, out_file=None) or,\n f(in_file=in_file, out_dir=None, out_file=None)\n\n examples:\n @filter_to("foo")\n f("the/input/path/file.sam") ->\n f("the/input/path/file.sam", out_file="the/input/path/file_foo.bam")\n\n @filter_to("foo")\n f("the/input/path/file.sam", out_dir="results") ->\n f("the/input/path/file.sam", out_file="results/file_foo.bam")\n\n ' def decor(f): @functools.wraps(f) def wrapper(*args, **kwargs): out_file = kwargs.get('out_file', None) if (not out_file): in_path = kwargs.get('in_file', args[0]) out_dir = kwargs.get('out_dir', os.path.dirname(in_path)) if (out_dir is None): out_dir = os.path.dirname(in_path) if out_dir: safe_makedir(out_dir) out_name = append_stem(os.path.basename(in_path), word, '_') out_file = os.path.join(out_dir, out_name) kwargs['out_file'] = out_file if (not file_exists(out_file)): out_file = f(*args, **kwargs) return out_file return wrapper return decor
def filter_to(word): '\n Decorator to create an output filename from an input filename by\n adding a word onto the stem. in_file is filtered by the function\n and the results are written to out_file. You would want to use\n this over transform_to if you don\'t know the extension of the file\n going in. This also memoizes the output file.\n\n Takes functions like this to decorate:\n f(in_file, out_dir=None, out_file=None) or,\n f(in_file=in_file, out_dir=None, out_file=None)\n\n examples:\n @filter_to("foo")\n f("the/input/path/file.sam") ->\n f("the/input/path/file.sam", out_file="the/input/path/file_foo.bam")\n\n @filter_to("foo")\n f("the/input/path/file.sam", out_dir="results") ->\n f("the/input/path/file.sam", out_file="results/file_foo.bam")\n\n ' def decor(f): @functools.wraps(f) def wrapper(*args, **kwargs): out_file = kwargs.get('out_file', None) if (not out_file): in_path = kwargs.get('in_file', args[0]) out_dir = kwargs.get('out_dir', os.path.dirname(in_path)) if (out_dir is None): out_dir = os.path.dirname(in_path) if out_dir: safe_makedir(out_dir) out_name = append_stem(os.path.basename(in_path), word, '_') out_file = os.path.join(out_dir, out_name) kwargs['out_file'] = out_file if (not file_exists(out_file)): out_file = f(*args, **kwargs) return out_file return wrapper return decor<|docstring|>Decorator to create an output filename from an input filename by adding a word onto the stem. in_file is filtered by the function and the results are written to out_file. You would want to use this over transform_to if you don't know the extension of the file going in. This also memoizes the output file. Takes functions like this to decorate: f(in_file, out_dir=None, out_file=None) or, f(in_file=in_file, out_dir=None, out_file=None) examples: @filter_to("foo") f("the/input/path/file.sam") -> f("the/input/path/file.sam", out_file="the/input/path/file_foo.bam") @filter_to("foo") f("the/input/path/file.sam", out_dir="results") -> f("the/input/path/file.sam", out_file="results/file_foo.bam")<|endoftext|>
aa5a95ed5b484ad957a11c9276afbbffc20aae3fedece43841bac1716ef71977
def memoize_outfile(ext=None, stem=None): '\n Memoization decorator.\n\n See docstring for transform_to and filter_to for details.\n ' if ext: return transform_to(ext) if stem: return filter_to(stem)
Memoization decorator. See docstring for transform_to and filter_to for details.
nextgen/bcbio/utils.py
memoize_outfile
bgruening/bcbb
339
python
def memoize_outfile(ext=None, stem=None): '\n Memoization decorator.\n\n See docstring for transform_to and filter_to for details.\n ' if ext: return transform_to(ext) if stem: return filter_to(stem)
def memoize_outfile(ext=None, stem=None): '\n Memoization decorator.\n\n See docstring for transform_to and filter_to for details.\n ' if ext: return transform_to(ext) if stem: return filter_to(stem)<|docstring|>Memoization decorator. See docstring for transform_to and filter_to for details.<|endoftext|>
c1611921a9a5440f3164fc2898f7fa62dde9d2a5acf282cbebca96609664dec9
def safe_makedir(dname): "Make a directory if it doesn't exist, handling concurrent race conditions.\n " num_tries = 0 max_tries = 5 while (not os.path.exists(dname)): try: os.makedirs(dname) except OSError: if (num_tries > max_tries): raise num_tries += 1 time.sleep(2) return dname
Make a directory if it doesn't exist, handling concurrent race conditions.
nextgen/bcbio/utils.py
safe_makedir
bgruening/bcbb
339
python
def safe_makedir(dname): "\n " num_tries = 0 max_tries = 5 while (not os.path.exists(dname)): try: os.makedirs(dname) except OSError: if (num_tries > max_tries): raise num_tries += 1 time.sleep(2) return dname
def safe_makedir(dname): "\n " num_tries = 0 max_tries = 5 while (not os.path.exists(dname)): try: os.makedirs(dname) except OSError: if (num_tries > max_tries): raise num_tries += 1 time.sleep(2) return dname<|docstring|>Make a directory if it doesn't exist, handling concurrent race conditions.<|endoftext|>
3570ec103152dacfb5afb2701765e3f8fc31adc09dcdb268defe8e30f66776df
@contextlib.contextmanager def curdir_tmpdir(remove=True, base_dir=None): 'Context manager to create and remove a temporary directory.\n\n This can also handle a configured temporary directory to use.\n ' if (base_dir is not None): tmp_dir_base = os.path.join(base_dir, 'bcbiotmp') else: tmp_dir_base = os.path.join(os.getcwd(), 'tmp') safe_makedir(tmp_dir_base) tmp_dir = tempfile.mkdtemp(dir=tmp_dir_base) safe_makedir(tmp_dir) try: (yield tmp_dir) finally: if remove: try: shutil.rmtree(tmp_dir) except: pass
Context manager to create and remove a temporary directory. This can also handle a configured temporary directory to use.
nextgen/bcbio/utils.py
curdir_tmpdir
bgruening/bcbb
339
python
@contextlib.contextmanager def curdir_tmpdir(remove=True, base_dir=None): 'Context manager to create and remove a temporary directory.\n\n This can also handle a configured temporary directory to use.\n ' if (base_dir is not None): tmp_dir_base = os.path.join(base_dir, 'bcbiotmp') else: tmp_dir_base = os.path.join(os.getcwd(), 'tmp') safe_makedir(tmp_dir_base) tmp_dir = tempfile.mkdtemp(dir=tmp_dir_base) safe_makedir(tmp_dir) try: (yield tmp_dir) finally: if remove: try: shutil.rmtree(tmp_dir) except: pass
@contextlib.contextmanager def curdir_tmpdir(remove=True, base_dir=None): 'Context manager to create and remove a temporary directory.\n\n This can also handle a configured temporary directory to use.\n ' if (base_dir is not None): tmp_dir_base = os.path.join(base_dir, 'bcbiotmp') else: tmp_dir_base = os.path.join(os.getcwd(), 'tmp') safe_makedir(tmp_dir_base) tmp_dir = tempfile.mkdtemp(dir=tmp_dir_base) safe_makedir(tmp_dir) try: (yield tmp_dir) finally: if remove: try: shutil.rmtree(tmp_dir) except: pass<|docstring|>Context manager to create and remove a temporary directory. This can also handle a configured temporary directory to use.<|endoftext|>
05e084242c8541f6e9d6d4fac0c519412b4df37a07a8cbb73bff2f7055ba1181
@contextlib.contextmanager def chdir(new_dir): 'Context manager to temporarily change to a new directory.\n\n http://lucentbeing.com/blog/context-managers-and-the-with-statement-in-python/\n ' cur_dir = os.getcwd() safe_makedir(new_dir) os.chdir(new_dir) try: (yield) finally: os.chdir(cur_dir)
Context manager to temporarily change to a new directory. http://lucentbeing.com/blog/context-managers-and-the-with-statement-in-python/
nextgen/bcbio/utils.py
chdir
bgruening/bcbb
339
python
@contextlib.contextmanager def chdir(new_dir): 'Context manager to temporarily change to a new directory.\n\n http://lucentbeing.com/blog/context-managers-and-the-with-statement-in-python/\n ' cur_dir = os.getcwd() safe_makedir(new_dir) os.chdir(new_dir) try: (yield) finally: os.chdir(cur_dir)
@contextlib.contextmanager def chdir(new_dir): 'Context manager to temporarily change to a new directory.\n\n http://lucentbeing.com/blog/context-managers-and-the-with-statement-in-python/\n ' cur_dir = os.getcwd() safe_makedir(new_dir) os.chdir(new_dir) try: (yield) finally: os.chdir(cur_dir)<|docstring|>Context manager to temporarily change to a new directory. http://lucentbeing.com/blog/context-managers-and-the-with-statement-in-python/<|endoftext|>
78905502237c0cf0da3f34413e0cf07c39ad9f18cf95cc8f8f462f79ab9c09fa
@contextlib.contextmanager def tmpfile(*args, **kwargs): 'Make a tempfile, safely cleaning up file descriptors on completion.\n ' (fd, fname) = tempfile.mkstemp(*args, **kwargs) try: (yield fname) finally: os.close(fd) if os.path.exists(fname): os.remove(fname)
Make a tempfile, safely cleaning up file descriptors on completion.
nextgen/bcbio/utils.py
tmpfile
bgruening/bcbb
339
python
@contextlib.contextmanager def tmpfile(*args, **kwargs): '\n ' (fd, fname) = tempfile.mkstemp(*args, **kwargs) try: (yield fname) finally: os.close(fd) if os.path.exists(fname): os.remove(fname)
@contextlib.contextmanager def tmpfile(*args, **kwargs): '\n ' (fd, fname) = tempfile.mkstemp(*args, **kwargs) try: (yield fname) finally: os.close(fd) if os.path.exists(fname): os.remove(fname)<|docstring|>Make a tempfile, safely cleaning up file descriptors on completion.<|endoftext|>
7dd46dfab1b390c549ad0e7e62a41e4f19635948b245e6f64ca4998e033fe824
def file_exists(fname): 'Check if a file exists and is non-empty.\n ' return (os.path.exists(fname) and (os.path.getsize(fname) > 0))
Check if a file exists and is non-empty.
nextgen/bcbio/utils.py
file_exists
bgruening/bcbb
339
python
def file_exists(fname): '\n ' return (os.path.exists(fname) and (os.path.getsize(fname) > 0))
def file_exists(fname): '\n ' return (os.path.exists(fname) and (os.path.getsize(fname) > 0))<|docstring|>Check if a file exists and is non-empty.<|endoftext|>
09dd29b2f12d6e1aab6dfd375bfc71c76f323bce993462b7b3e0c2aa6563e74e
def save_diskspace(fname, reason, config): 'Overwrite a file in place with a short message to save disk.\n\n This keeps files as a sanity check on processes working, but saves\n disk by replacing them with a short message.\n ' if config['algorithm'].get('save_diskspace', False): with open(fname, 'w') as out_handle: out_handle.write(('File removed to save disk space: %s' % reason))
Overwrite a file in place with a short message to save disk. This keeps files as a sanity check on processes working, but saves disk by replacing them with a short message.
nextgen/bcbio/utils.py
save_diskspace
bgruening/bcbb
339
python
def save_diskspace(fname, reason, config): 'Overwrite a file in place with a short message to save disk.\n\n This keeps files as a sanity check on processes working, but saves\n disk by replacing them with a short message.\n ' if config['algorithm'].get('save_diskspace', False): with open(fname, 'w') as out_handle: out_handle.write(('File removed to save disk space: %s' % reason))
def save_diskspace(fname, reason, config): 'Overwrite a file in place with a short message to save disk.\n\n This keeps files as a sanity check on processes working, but saves\n disk by replacing them with a short message.\n ' if config['algorithm'].get('save_diskspace', False): with open(fname, 'w') as out_handle: out_handle.write(('File removed to save disk space: %s' % reason))<|docstring|>Overwrite a file in place with a short message to save disk. This keeps files as a sanity check on processes working, but saves disk by replacing them with a short message.<|endoftext|>
e643d11e35e7d81534491c5d7daaf68254e64fcc84fb9a092b246e132a33239f
def read_galaxy_amqp_config(galaxy_config, base_dir): 'Read connection information on the RabbitMQ server from Galaxy config.\n ' galaxy_config = add_full_path(galaxy_config, base_dir) config = ConfigParser.ConfigParser() config.read(galaxy_config) amqp_config = {} for option in config.options('galaxy_amqp'): amqp_config[option] = config.get('galaxy_amqp', option) return amqp_config
Read connection information on the RabbitMQ server from Galaxy config.
nextgen/bcbio/utils.py
read_galaxy_amqp_config
bgruening/bcbb
339
python
def read_galaxy_amqp_config(galaxy_config, base_dir): '\n ' galaxy_config = add_full_path(galaxy_config, base_dir) config = ConfigParser.ConfigParser() config.read(galaxy_config) amqp_config = {} for option in config.options('galaxy_amqp'): amqp_config[option] = config.get('galaxy_amqp', option) return amqp_config
def read_galaxy_amqp_config(galaxy_config, base_dir): '\n ' galaxy_config = add_full_path(galaxy_config, base_dir) config = ConfigParser.ConfigParser() config.read(galaxy_config) amqp_config = {} for option in config.options('galaxy_amqp'): amqp_config[option] = config.get('galaxy_amqp', option) return amqp_config<|docstring|>Read connection information on the RabbitMQ server from Galaxy config.<|endoftext|>
d7069cdfa9e7759263c17d1a79c9ab12d7fe8a5f693a2b4c54f1b02d9d9ffd51
def append_stem(filename, word, delim='_'): '\n returns a filename with \'word\' appended to the stem\n example: append_stem("/path/to/test.sam", "filtered") ->\n "/path/to/test_filtered.sam"\n\n ' (base, ext) = os.path.splitext(filename) return ''.join([base, delim, word, ext])
returns a filename with 'word' appended to the stem example: append_stem("/path/to/test.sam", "filtered") -> "/path/to/test_filtered.sam"
nextgen/bcbio/utils.py
append_stem
bgruening/bcbb
339
python
def append_stem(filename, word, delim='_'): '\n returns a filename with \'word\' appended to the stem\n example: append_stem("/path/to/test.sam", "filtered") ->\n "/path/to/test_filtered.sam"\n\n ' (base, ext) = os.path.splitext(filename) return .join([base, delim, word, ext])
def append_stem(filename, word, delim='_'): '\n returns a filename with \'word\' appended to the stem\n example: append_stem("/path/to/test.sam", "filtered") ->\n "/path/to/test_filtered.sam"\n\n ' (base, ext) = os.path.splitext(filename) return .join([base, delim, word, ext])<|docstring|>returns a filename with 'word' appended to the stem example: append_stem("/path/to/test.sam", "filtered") -> "/path/to/test_filtered.sam"<|endoftext|>
95266a1f01aa602d8622836aece38c75c1336d4fab5e7df1fd5419fdca293f50
def replace_suffix(filename, suffix): '\n replace the suffix of filename with suffix\n example: replace_suffix("/path/to/test.sam", ".bam") ->\n "/path/to/test.bam"\n\n ' (base, _) = os.path.splitext(filename) return (base + suffix)
replace the suffix of filename with suffix example: replace_suffix("/path/to/test.sam", ".bam") -> "/path/to/test.bam"
nextgen/bcbio/utils.py
replace_suffix
bgruening/bcbb
339
python
def replace_suffix(filename, suffix): '\n replace the suffix of filename with suffix\n example: replace_suffix("/path/to/test.sam", ".bam") ->\n "/path/to/test.bam"\n\n ' (base, _) = os.path.splitext(filename) return (base + suffix)
def replace_suffix(filename, suffix): '\n replace the suffix of filename with suffix\n example: replace_suffix("/path/to/test.sam", ".bam") ->\n "/path/to/test.bam"\n\n ' (base, _) = os.path.splitext(filename) return (base + suffix)<|docstring|>replace the suffix of filename with suffix example: replace_suffix("/path/to/test.sam", ".bam") -> "/path/to/test.bam"<|endoftext|>
98456503cddfb5f21bc22af4f752f1c57c8ef81bc7544a1b1e6de3061a8dfaab
def partition_all(n, iterable): 'Partition a list into equally sized pieces, including last smaller parts\n http://stackoverflow.com/questions/5129102/python-equivalent-to-clojures-partition-all\n ' it = iter(iterable) while True: chunk = list(itertools.islice(it, n)) if (not chunk): break (yield chunk)
Partition a list into equally sized pieces, including last smaller parts http://stackoverflow.com/questions/5129102/python-equivalent-to-clojures-partition-all
nextgen/bcbio/utils.py
partition_all
bgruening/bcbb
339
python
def partition_all(n, iterable): 'Partition a list into equally sized pieces, including last smaller parts\n http://stackoverflow.com/questions/5129102/python-equivalent-to-clojures-partition-all\n ' it = iter(iterable) while True: chunk = list(itertools.islice(it, n)) if (not chunk): break (yield chunk)
def partition_all(n, iterable): 'Partition a list into equally sized pieces, including last smaller parts\n http://stackoverflow.com/questions/5129102/python-equivalent-to-clojures-partition-all\n ' it = iter(iterable) while True: chunk = list(itertools.islice(it, n)) if (not chunk): break (yield chunk)<|docstring|>Partition a list into equally sized pieces, including last smaller parts http://stackoverflow.com/questions/5129102/python-equivalent-to-clojures-partition-all<|endoftext|>
bdb058746e1a9b53a7101a210b6dd6544721f6f6788c8bd31bd3a442bffb603f
def merge_config_files(fnames): 'Merge configuration files, preferring definitions in latter files.\n ' def _load_yaml(fname): with open(fname) as in_handle: config = yaml.load(in_handle) return config out = _load_yaml(fnames[0]) for fname in fnames[1:]: cur = _load_yaml(fname) for (k, v) in cur.iteritems(): if (out.has_key(k) and isinstance(out[k], dict)): out[k].update(v) else: out[k] = v return out
Merge configuration files, preferring definitions in latter files.
nextgen/bcbio/utils.py
merge_config_files
bgruening/bcbb
339
python
def merge_config_files(fnames): '\n ' def _load_yaml(fname): with open(fname) as in_handle: config = yaml.load(in_handle) return config out = _load_yaml(fnames[0]) for fname in fnames[1:]: cur = _load_yaml(fname) for (k, v) in cur.iteritems(): if (out.has_key(k) and isinstance(out[k], dict)): out[k].update(v) else: out[k] = v return out
def merge_config_files(fnames): '\n ' def _load_yaml(fname): with open(fname) as in_handle: config = yaml.load(in_handle) return config out = _load_yaml(fnames[0]) for fname in fnames[1:]: cur = _load_yaml(fname) for (k, v) in cur.iteritems(): if (out.has_key(k) and isinstance(out[k], dict)): out[k].update(v) else: out[k] = v return out<|docstring|>Merge configuration files, preferring definitions in latter files.<|endoftext|>
10121e04163f6e0fe1124a23a5b12ddf587d48f736c1b589581ca1a9ab777d50
def get_in(d, t, default=None): '\n look up if you can get a tuple of values from a nested dictionary,\n each item in the tuple a deeper layer\n\n example: get_in({1: {2: 3}}, (1, 2)) -> 3\n example: get_in({1: {2: 3}}, (2, 3)) -> {}\n ' result = reduce((lambda d, t: d.get(t, {})), t, d) if (not result): return default else: return result
look up if you can get a tuple of values from a nested dictionary, each item in the tuple a deeper layer example: get_in({1: {2: 3}}, (1, 2)) -> 3 example: get_in({1: {2: 3}}, (2, 3)) -> {}
nextgen/bcbio/utils.py
get_in
bgruening/bcbb
339
python
def get_in(d, t, default=None): '\n look up if you can get a tuple of values from a nested dictionary,\n each item in the tuple a deeper layer\n\n example: get_in({1: {2: 3}}, (1, 2)) -> 3\n example: get_in({1: {2: 3}}, (2, 3)) -> {}\n ' result = reduce((lambda d, t: d.get(t, {})), t, d) if (not result): return default else: return result
def get_in(d, t, default=None): '\n look up if you can get a tuple of values from a nested dictionary,\n each item in the tuple a deeper layer\n\n example: get_in({1: {2: 3}}, (1, 2)) -> 3\n example: get_in({1: {2: 3}}, (2, 3)) -> {}\n ' result = reduce((lambda d, t: d.get(t, {})), t, d) if (not result): return default else: return result<|docstring|>look up if you can get a tuple of values from a nested dictionary, each item in the tuple a deeper layer example: get_in({1: {2: 3}}, (1, 2)) -> 3 example: get_in({1: {2: 3}}, (2, 3)) -> {}<|endoftext|>
39b7dcda4b3bd85c86b380a80d2729aff396dce53c19a379c1e2a204be171c1a
def flatten(l): '\n flatten an irregular list of lists\n example: flatten([[[1, 2, 3], [4, 5]], 6]) -> [1, 2, 3, 4, 5, 6]\n lifted from: http://stackoverflow.com/questions/2158395/\n\n ' for el in l: if (isinstance(el, collections.Iterable) and (not isinstance(el, basestring))): for sub in flatten(el): (yield sub) else: (yield el)
flatten an irregular list of lists example: flatten([[[1, 2, 3], [4, 5]], 6]) -> [1, 2, 3, 4, 5, 6] lifted from: http://stackoverflow.com/questions/2158395/
nextgen/bcbio/utils.py
flatten
bgruening/bcbb
339
python
def flatten(l): '\n flatten an irregular list of lists\n example: flatten([[[1, 2, 3], [4, 5]], 6]) -> [1, 2, 3, 4, 5, 6]\n lifted from: http://stackoverflow.com/questions/2158395/\n\n ' for el in l: if (isinstance(el, collections.Iterable) and (not isinstance(el, basestring))): for sub in flatten(el): (yield sub) else: (yield el)
def flatten(l): '\n flatten an irregular list of lists\n example: flatten([[[1, 2, 3], [4, 5]], 6]) -> [1, 2, 3, 4, 5, 6]\n lifted from: http://stackoverflow.com/questions/2158395/\n\n ' for el in l: if (isinstance(el, collections.Iterable) and (not isinstance(el, basestring))): for sub in flatten(el): (yield sub) else: (yield el)<|docstring|>flatten an irregular list of lists example: flatten([[[1, 2, 3], [4, 5]], 6]) -> [1, 2, 3, 4, 5, 6] lifted from: http://stackoverflow.com/questions/2158395/<|endoftext|>
b1345ef2f4e0ce559104e75d2194842cd1e76c387d9c92671fee209d30031a10
def is_sequence(arg): '\n check if \'arg\' is a sequence\n\n example: arg([]) -> True\n example: arg("lol") -> False\n\n ' return (((not hasattr(arg, 'strip')) and hasattr(arg, '__getitem__')) or hasattr(arg, '__iter__'))
check if 'arg' is a sequence example: arg([]) -> True example: arg("lol") -> False
nextgen/bcbio/utils.py
is_sequence
bgruening/bcbb
339
python
def is_sequence(arg): '\n check if \'arg\' is a sequence\n\n example: arg([]) -> True\n example: arg("lol") -> False\n\n ' return (((not hasattr(arg, 'strip')) and hasattr(arg, '__getitem__')) or hasattr(arg, '__iter__'))
def is_sequence(arg): '\n check if \'arg\' is a sequence\n\n example: arg([]) -> True\n example: arg("lol") -> False\n\n ' return (((not hasattr(arg, 'strip')) and hasattr(arg, '__getitem__')) or hasattr(arg, '__iter__'))<|docstring|>check if 'arg' is a sequence example: arg([]) -> True example: arg("lol") -> False<|endoftext|>
9e23e830d313fb363d8220da7c54b6f5c3eb99720b67cb667d9d1afa9d452a1e
def is_pair(arg): "\n check if 'arg' is a two-item sequence\n\n " return (is_sequence(arg) and (len(arg) == 2))
check if 'arg' is a two-item sequence
nextgen/bcbio/utils.py
is_pair
bgruening/bcbb
339
python
def is_pair(arg): "\n \n\n " return (is_sequence(arg) and (len(arg) == 2))
def is_pair(arg): "\n \n\n " return (is_sequence(arg) and (len(arg) == 2))<|docstring|>check if 'arg' is a two-item sequence<|endoftext|>
908b7af6640e98ea7faa9063a33752e13c8f5a7e1ef30d6a51dca193f53916a1
def locate(pattern, root=os.curdir): 'Locate all files matching supplied filename pattern in and below\n supplied root directory.' for (path, dirs, files) in os.walk(os.path.abspath(root)): for filename in fnmatch.filter(files, pattern): (yield os.path.join(path, filename))
Locate all files matching supplied filename pattern in and below supplied root directory.
nextgen/bcbio/utils.py
locate
bgruening/bcbb
339
python
def locate(pattern, root=os.curdir): 'Locate all files matching supplied filename pattern in and below\n supplied root directory.' for (path, dirs, files) in os.walk(os.path.abspath(root)): for filename in fnmatch.filter(files, pattern): (yield os.path.join(path, filename))
def locate(pattern, root=os.curdir): 'Locate all files matching supplied filename pattern in and below\n supplied root directory.' for (path, dirs, files) in os.walk(os.path.abspath(root)): for filename in fnmatch.filter(files, pattern): (yield os.path.join(path, filename))<|docstring|>Locate all files matching supplied filename pattern in and below supplied root directory.<|endoftext|>
ac3cf778bfd73a08188d102c00f7871cc551bd0ebc2a87fdefafafba59189ee6
def get_name_from_configs(pkg_dir, assert_exists=True): 'Get name from local setup.cfg (metadata section)' configs = read_configs(pkg_dir=pkg_dir) name = configs.get('name', None) if assert_exists: assert (name is not None), 'No name was found in configs' return name
Get name from local setup.cfg (metadata section)
wads/pack.py
get_name_from_configs
i2mint/wads
0
python
def get_name_from_configs(pkg_dir, assert_exists=True): configs = read_configs(pkg_dir=pkg_dir) name = configs.get('name', None) if assert_exists: assert (name is not None), 'No name was found in configs' return name
def get_name_from_configs(pkg_dir, assert_exists=True): configs = read_configs(pkg_dir=pkg_dir) name = configs.get('name', None) if assert_exists: assert (name is not None), 'No name was found in configs' return name<|docstring|>Get name from local setup.cfg (metadata section)<|endoftext|>
bac682bccdbe957670aa49a446c5d01f2c061c5217e7b7e0a76ee3ecd228efad
def check_in(commit_message: str, work_tree='.', git_dir=None, auto_choose_default_action=False, bypass_docstring_validation=False, bypass_tests=False, bypass_code_formatting=False, verbose=False): 'Validate, normalize, stage, commit and push your local changes to a remote repository.\n\n :param commit_message: Your commit message\n :type commit_message: str\n :param work_tree: The relative or absolute path of the working directory. Defaults to \'.\'.\n :type work_tree: str, optional\n :param git_dir: The relative or absolute path of the git directory. If None, it will be taken to be "{work_tree}/.git/". Defaults to None.\n :type git_dir: str, optional\n :param auto_choose_default_action: Set to True if you don\'t want to be prompted and automatically select the default action. Defaults to False.\n :type auto_choose_default_action: bool, optional\n :param bypass_docstring_validation: Set to True if you don\'t want to check if a docstring exists for every module, class and function. Defaults to False.\n :type bypass_docstring_validation: bool, optional\n :param bypass_tests: Set to True if you don\'t want to run doctests and other tests. Defaults to False.\n :type bypass_tests: bool, optional\n :param bypass_code_formatting: Set to True if you don\'t want the code to be automatically formatted using axblack. Defaults to False.\n :type bypass_code_formatting: bool, optional\n :param verbose: Set to True if you want to log extra information during the process. Defaults to False.\n :type verbose: bool, optional\n ' def ggit(command): r = git(command, work_tree=work_tree, git_dir=git_dir) clog(verbose, r, log_func=print) return r def print_step_title(step_title): if verbose: print() print(f'============= {step_title.upper()} =============') else: print(f'-- {step_title}') def abort(): print('Aborting') sys.exit() def confirm(action, default): if auto_choose_default_action: return default return argh.interaction.confirm(action, default) def verify_current_changes(): print_step_title('Verify current changes') if ('nothing to commit, working tree clean' in ggit('status')): print('No changes to check in.') abort() def pull_remote_changes(): print_step_title('Pull remote changes') ggit('stash') result = ggit('pull') ggit('stash apply') if ((result != 'Already up to date.') and (not confirm('Your local repository was not up to date, but it is now. Do you want to continue', default=True))): abort() def validate_docstrings(): def run_pylint(current_dir): if os.path.exists(os.path.join(current_dir, '__init__.py')): result = pylint.lint.Run([current_dir, '--disable=all', '--enable=C0114,C0115,C0116'], do_exit=False) if ((result.linter.stats['global_note'] < 10) and (not confirm(f'Docstrings are missing in directory {current_dir}. Do you want to continue', default=True))): abort() else: for subdir in next(os.walk(current_dir))[1]: run_pylint(os.path.join(current_dir, subdir)) print_step_title('Validate docstrings') run_pylint('.') def run_tests(): print_step_title('Run tests') args = ['--doctest-modules'] if verbose: args.append('-v') else: args.extend(['-q', '--no-summary']) result = pytest.main(args) if ((result == pytest.ExitCode.TESTS_FAILED) and (not confirm('Tests have failed. Do you want to push anyway', default=False))): abort() elif (result not in [pytest.ExitCode.OK, pytest.ExitCode.NO_TESTS_COLLECTED]): print('Something went wrong when running tests. Please check the output.') abort() def format_code(): print_step_title('Format code') subprocess.run('black --line-length=88 .', shell=True, check=True, capture_output=(not verbose)) def stage_changes(): result = ggit('status') if ('Changes not staged for commit' in result): if ((not auto_choose_default_action) and (not verbose)): print(result) if confirm('Do you want to stage all your pending changes', default=True): print_step_title('Stage changes') git('add -A') def commit_changes(): print_step_title('Commit changes') if ('no changes added to commit' in ggit('status')): print('No changes to check in.') abort() ggit(f'commit --message="{commit_message}"') def push_changes(): if (not confirm('Your changes have been commited. Do you want to push', default=True)): abort() print_step_title('Push changes') ggit('push') try: verify_current_changes() pull_remote_changes() if (not bypass_docstring_validation): validate_docstrings() if (not bypass_tests): run_tests() if (not bypass_code_formatting): format_code() stage_changes() commit_changes() push_changes() except subprocess.CalledProcessError: print('An error occured. Please check the output.') abort() print('Your changes have been checked in successfully!')
Validate, normalize, stage, commit and push your local changes to a remote repository. :param commit_message: Your commit message :type commit_message: str :param work_tree: The relative or absolute path of the working directory. Defaults to '.'. :type work_tree: str, optional :param git_dir: The relative or absolute path of the git directory. If None, it will be taken to be "{work_tree}/.git/". Defaults to None. :type git_dir: str, optional :param auto_choose_default_action: Set to True if you don't want to be prompted and automatically select the default action. Defaults to False. :type auto_choose_default_action: bool, optional :param bypass_docstring_validation: Set to True if you don't want to check if a docstring exists for every module, class and function. Defaults to False. :type bypass_docstring_validation: bool, optional :param bypass_tests: Set to True if you don't want to run doctests and other tests. Defaults to False. :type bypass_tests: bool, optional :param bypass_code_formatting: Set to True if you don't want the code to be automatically formatted using axblack. Defaults to False. :type bypass_code_formatting: bool, optional :param verbose: Set to True if you want to log extra information during the process. Defaults to False. :type verbose: bool, optional
wads/pack.py
check_in
i2mint/wads
0
python
def check_in(commit_message: str, work_tree='.', git_dir=None, auto_choose_default_action=False, bypass_docstring_validation=False, bypass_tests=False, bypass_code_formatting=False, verbose=False): 'Validate, normalize, stage, commit and push your local changes to a remote repository.\n\n :param commit_message: Your commit message\n :type commit_message: str\n :param work_tree: The relative or absolute path of the working directory. Defaults to \'.\'.\n :type work_tree: str, optional\n :param git_dir: The relative or absolute path of the git directory. If None, it will be taken to be "{work_tree}/.git/". Defaults to None.\n :type git_dir: str, optional\n :param auto_choose_default_action: Set to True if you don\'t want to be prompted and automatically select the default action. Defaults to False.\n :type auto_choose_default_action: bool, optional\n :param bypass_docstring_validation: Set to True if you don\'t want to check if a docstring exists for every module, class and function. Defaults to False.\n :type bypass_docstring_validation: bool, optional\n :param bypass_tests: Set to True if you don\'t want to run doctests and other tests. Defaults to False.\n :type bypass_tests: bool, optional\n :param bypass_code_formatting: Set to True if you don\'t want the code to be automatically formatted using axblack. Defaults to False.\n :type bypass_code_formatting: bool, optional\n :param verbose: Set to True if you want to log extra information during the process. Defaults to False.\n :type verbose: bool, optional\n ' def ggit(command): r = git(command, work_tree=work_tree, git_dir=git_dir) clog(verbose, r, log_func=print) return r def print_step_title(step_title): if verbose: print() print(f'============= {step_title.upper()} =============') else: print(f'-- {step_title}') def abort(): print('Aborting') sys.exit() def confirm(action, default): if auto_choose_default_action: return default return argh.interaction.confirm(action, default) def verify_current_changes(): print_step_title('Verify current changes') if ('nothing to commit, working tree clean' in ggit('status')): print('No changes to check in.') abort() def pull_remote_changes(): print_step_title('Pull remote changes') ggit('stash') result = ggit('pull') ggit('stash apply') if ((result != 'Already up to date.') and (not confirm('Your local repository was not up to date, but it is now. Do you want to continue', default=True))): abort() def validate_docstrings(): def run_pylint(current_dir): if os.path.exists(os.path.join(current_dir, '__init__.py')): result = pylint.lint.Run([current_dir, '--disable=all', '--enable=C0114,C0115,C0116'], do_exit=False) if ((result.linter.stats['global_note'] < 10) and (not confirm(f'Docstrings are missing in directory {current_dir}. Do you want to continue', default=True))): abort() else: for subdir in next(os.walk(current_dir))[1]: run_pylint(os.path.join(current_dir, subdir)) print_step_title('Validate docstrings') run_pylint('.') def run_tests(): print_step_title('Run tests') args = ['--doctest-modules'] if verbose: args.append('-v') else: args.extend(['-q', '--no-summary']) result = pytest.main(args) if ((result == pytest.ExitCode.TESTS_FAILED) and (not confirm('Tests have failed. Do you want to push anyway', default=False))): abort() elif (result not in [pytest.ExitCode.OK, pytest.ExitCode.NO_TESTS_COLLECTED]): print('Something went wrong when running tests. Please check the output.') abort() def format_code(): print_step_title('Format code') subprocess.run('black --line-length=88 .', shell=True, check=True, capture_output=(not verbose)) def stage_changes(): result = ggit('status') if ('Changes not staged for commit' in result): if ((not auto_choose_default_action) and (not verbose)): print(result) if confirm('Do you want to stage all your pending changes', default=True): print_step_title('Stage changes') git('add -A') def commit_changes(): print_step_title('Commit changes') if ('no changes added to commit' in ggit('status')): print('No changes to check in.') abort() ggit(f'commit --message="{commit_message}"') def push_changes(): if (not confirm('Your changes have been commited. Do you want to push', default=True)): abort() print_step_title('Push changes') ggit('push') try: verify_current_changes() pull_remote_changes() if (not bypass_docstring_validation): validate_docstrings() if (not bypass_tests): run_tests() if (not bypass_code_formatting): format_code() stage_changes() commit_changes() push_changes() except subprocess.CalledProcessError: print('An error occured. Please check the output.') abort() print('Your changes have been checked in successfully!')
def check_in(commit_message: str, work_tree='.', git_dir=None, auto_choose_default_action=False, bypass_docstring_validation=False, bypass_tests=False, bypass_code_formatting=False, verbose=False): 'Validate, normalize, stage, commit and push your local changes to a remote repository.\n\n :param commit_message: Your commit message\n :type commit_message: str\n :param work_tree: The relative or absolute path of the working directory. Defaults to \'.\'.\n :type work_tree: str, optional\n :param git_dir: The relative or absolute path of the git directory. If None, it will be taken to be "{work_tree}/.git/". Defaults to None.\n :type git_dir: str, optional\n :param auto_choose_default_action: Set to True if you don\'t want to be prompted and automatically select the default action. Defaults to False.\n :type auto_choose_default_action: bool, optional\n :param bypass_docstring_validation: Set to True if you don\'t want to check if a docstring exists for every module, class and function. Defaults to False.\n :type bypass_docstring_validation: bool, optional\n :param bypass_tests: Set to True if you don\'t want to run doctests and other tests. Defaults to False.\n :type bypass_tests: bool, optional\n :param bypass_code_formatting: Set to True if you don\'t want the code to be automatically formatted using axblack. Defaults to False.\n :type bypass_code_formatting: bool, optional\n :param verbose: Set to True if you want to log extra information during the process. Defaults to False.\n :type verbose: bool, optional\n ' def ggit(command): r = git(command, work_tree=work_tree, git_dir=git_dir) clog(verbose, r, log_func=print) return r def print_step_title(step_title): if verbose: print() print(f'============= {step_title.upper()} =============') else: print(f'-- {step_title}') def abort(): print('Aborting') sys.exit() def confirm(action, default): if auto_choose_default_action: return default return argh.interaction.confirm(action, default) def verify_current_changes(): print_step_title('Verify current changes') if ('nothing to commit, working tree clean' in ggit('status')): print('No changes to check in.') abort() def pull_remote_changes(): print_step_title('Pull remote changes') ggit('stash') result = ggit('pull') ggit('stash apply') if ((result != 'Already up to date.') and (not confirm('Your local repository was not up to date, but it is now. Do you want to continue', default=True))): abort() def validate_docstrings(): def run_pylint(current_dir): if os.path.exists(os.path.join(current_dir, '__init__.py')): result = pylint.lint.Run([current_dir, '--disable=all', '--enable=C0114,C0115,C0116'], do_exit=False) if ((result.linter.stats['global_note'] < 10) and (not confirm(f'Docstrings are missing in directory {current_dir}. Do you want to continue', default=True))): abort() else: for subdir in next(os.walk(current_dir))[1]: run_pylint(os.path.join(current_dir, subdir)) print_step_title('Validate docstrings') run_pylint('.') def run_tests(): print_step_title('Run tests') args = ['--doctest-modules'] if verbose: args.append('-v') else: args.extend(['-q', '--no-summary']) result = pytest.main(args) if ((result == pytest.ExitCode.TESTS_FAILED) and (not confirm('Tests have failed. Do you want to push anyway', default=False))): abort() elif (result not in [pytest.ExitCode.OK, pytest.ExitCode.NO_TESTS_COLLECTED]): print('Something went wrong when running tests. Please check the output.') abort() def format_code(): print_step_title('Format code') subprocess.run('black --line-length=88 .', shell=True, check=True, capture_output=(not verbose)) def stage_changes(): result = ggit('status') if ('Changes not staged for commit' in result): if ((not auto_choose_default_action) and (not verbose)): print(result) if confirm('Do you want to stage all your pending changes', default=True): print_step_title('Stage changes') git('add -A') def commit_changes(): print_step_title('Commit changes') if ('no changes added to commit' in ggit('status')): print('No changes to check in.') abort() ggit(f'commit --message="{commit_message}"') def push_changes(): if (not confirm('Your changes have been commited. Do you want to push', default=True)): abort() print_step_title('Push changes') ggit('push') try: verify_current_changes() pull_remote_changes() if (not bypass_docstring_validation): validate_docstrings() if (not bypass_tests): run_tests() if (not bypass_code_formatting): format_code() stage_changes() commit_changes() push_changes() except subprocess.CalledProcessError: print('An error occured. Please check the output.') abort() print('Your changes have been checked in successfully!')<|docstring|>Validate, normalize, stage, commit and push your local changes to a remote repository. :param commit_message: Your commit message :type commit_message: str :param work_tree: The relative or absolute path of the working directory. Defaults to '.'. :type work_tree: str, optional :param git_dir: The relative or absolute path of the git directory. If None, it will be taken to be "{work_tree}/.git/". Defaults to None. :type git_dir: str, optional :param auto_choose_default_action: Set to True if you don't want to be prompted and automatically select the default action. Defaults to False. :type auto_choose_default_action: bool, optional :param bypass_docstring_validation: Set to True if you don't want to check if a docstring exists for every module, class and function. Defaults to False. :type bypass_docstring_validation: bool, optional :param bypass_tests: Set to True if you don't want to run doctests and other tests. Defaults to False. :type bypass_tests: bool, optional :param bypass_code_formatting: Set to True if you don't want the code to be automatically formatted using axblack. Defaults to False. :type bypass_code_formatting: bool, optional :param verbose: Set to True if you want to log extra information during the process. Defaults to False. :type verbose: bool, optional<|endoftext|>
a3f3592d78aba7860a91596a9e4bfc5ca2ba211653f9ef8367dbe969f02c20b2
def goo(pkg_dir, commit_message, git_dir=None, auto_choose_default_action=False, bypass_docstring_validation=False, bypass_tests=False, bypass_code_formatting=False, verbose=False): 'Validate, normalize, stage, commit and push your local changes to a remote repository.\n\n :param pkg_dir: The relative or absolute path of the working directory. Defaults to \'.\'.\n :type pkg_dir: str, optional\n :param commit_message: Your commit message\n :type commit_message: str\n :param git_dir: The relative or absolute path of the git directory. If None, it will be taken to be "{work_tree}/.git/". Defaults to None.\n :type git_dir: str, optional\n :param auto_choose_default_action: Set to True if you don\'t want to be prompted and automatically select the default action. Defaults to False.\n :type auto_choose_default_action: bool, optional\n :param bypass_docstring_validation: Set to True if you don\'t want to check if a docstring exists for every module, class and function. Defaults to False.\n :type bypass_docstring_validation: bool, optional\n :param bypass_tests: Set to True if you don\'t want to run doctests and other tests. Defaults to False.\n :type bypass_tests: bool, optional\n :param bypass_code_formatting: Set to True if you don\'t want the code to be automatically formatted using axblack. Defaults to False.\n :type bypass_code_formatting: bool, optional\n :param verbose: Set to True if you want to log extra information during the process. Defaults to False.\n :type verbose: bool, optional\n ' return check_in(commit_message=commit_message, work_tree=pkg_dir, git_dir=git_dir, auto_choose_default_action=auto_choose_default_action, bypass_docstring_validation=bypass_docstring_validation, bypass_tests=bypass_tests, bypass_code_formatting=bypass_code_formatting, verbose=verbose)
Validate, normalize, stage, commit and push your local changes to a remote repository. :param pkg_dir: The relative or absolute path of the working directory. Defaults to '.'. :type pkg_dir: str, optional :param commit_message: Your commit message :type commit_message: str :param git_dir: The relative or absolute path of the git directory. If None, it will be taken to be "{work_tree}/.git/". Defaults to None. :type git_dir: str, optional :param auto_choose_default_action: Set to True if you don't want to be prompted and automatically select the default action. Defaults to False. :type auto_choose_default_action: bool, optional :param bypass_docstring_validation: Set to True if you don't want to check if a docstring exists for every module, class and function. Defaults to False. :type bypass_docstring_validation: bool, optional :param bypass_tests: Set to True if you don't want to run doctests and other tests. Defaults to False. :type bypass_tests: bool, optional :param bypass_code_formatting: Set to True if you don't want the code to be automatically formatted using axblack. Defaults to False. :type bypass_code_formatting: bool, optional :param verbose: Set to True if you want to log extra information during the process. Defaults to False. :type verbose: bool, optional
wads/pack.py
goo
i2mint/wads
0
python
def goo(pkg_dir, commit_message, git_dir=None, auto_choose_default_action=False, bypass_docstring_validation=False, bypass_tests=False, bypass_code_formatting=False, verbose=False): 'Validate, normalize, stage, commit and push your local changes to a remote repository.\n\n :param pkg_dir: The relative or absolute path of the working directory. Defaults to \'.\'.\n :type pkg_dir: str, optional\n :param commit_message: Your commit message\n :type commit_message: str\n :param git_dir: The relative or absolute path of the git directory. If None, it will be taken to be "{work_tree}/.git/". Defaults to None.\n :type git_dir: str, optional\n :param auto_choose_default_action: Set to True if you don\'t want to be prompted and automatically select the default action. Defaults to False.\n :type auto_choose_default_action: bool, optional\n :param bypass_docstring_validation: Set to True if you don\'t want to check if a docstring exists for every module, class and function. Defaults to False.\n :type bypass_docstring_validation: bool, optional\n :param bypass_tests: Set to True if you don\'t want to run doctests and other tests. Defaults to False.\n :type bypass_tests: bool, optional\n :param bypass_code_formatting: Set to True if you don\'t want the code to be automatically formatted using axblack. Defaults to False.\n :type bypass_code_formatting: bool, optional\n :param verbose: Set to True if you want to log extra information during the process. Defaults to False.\n :type verbose: bool, optional\n ' return check_in(commit_message=commit_message, work_tree=pkg_dir, git_dir=git_dir, auto_choose_default_action=auto_choose_default_action, bypass_docstring_validation=bypass_docstring_validation, bypass_tests=bypass_tests, bypass_code_formatting=bypass_code_formatting, verbose=verbose)
def goo(pkg_dir, commit_message, git_dir=None, auto_choose_default_action=False, bypass_docstring_validation=False, bypass_tests=False, bypass_code_formatting=False, verbose=False): 'Validate, normalize, stage, commit and push your local changes to a remote repository.\n\n :param pkg_dir: The relative or absolute path of the working directory. Defaults to \'.\'.\n :type pkg_dir: str, optional\n :param commit_message: Your commit message\n :type commit_message: str\n :param git_dir: The relative or absolute path of the git directory. If None, it will be taken to be "{work_tree}/.git/". Defaults to None.\n :type git_dir: str, optional\n :param auto_choose_default_action: Set to True if you don\'t want to be prompted and automatically select the default action. Defaults to False.\n :type auto_choose_default_action: bool, optional\n :param bypass_docstring_validation: Set to True if you don\'t want to check if a docstring exists for every module, class and function. Defaults to False.\n :type bypass_docstring_validation: bool, optional\n :param bypass_tests: Set to True if you don\'t want to run doctests and other tests. Defaults to False.\n :type bypass_tests: bool, optional\n :param bypass_code_formatting: Set to True if you don\'t want the code to be automatically formatted using axblack. Defaults to False.\n :type bypass_code_formatting: bool, optional\n :param verbose: Set to True if you want to log extra information during the process. Defaults to False.\n :type verbose: bool, optional\n ' return check_in(commit_message=commit_message, work_tree=pkg_dir, git_dir=git_dir, auto_choose_default_action=auto_choose_default_action, bypass_docstring_validation=bypass_docstring_validation, bypass_tests=bypass_tests, bypass_code_formatting=bypass_code_formatting, verbose=verbose)<|docstring|>Validate, normalize, stage, commit and push your local changes to a remote repository. :param pkg_dir: The relative or absolute path of the working directory. Defaults to '.'. :type pkg_dir: str, optional :param commit_message: Your commit message :type commit_message: str :param git_dir: The relative or absolute path of the git directory. If None, it will be taken to be "{work_tree}/.git/". Defaults to None. :type git_dir: str, optional :param auto_choose_default_action: Set to True if you don't want to be prompted and automatically select the default action. Defaults to False. :type auto_choose_default_action: bool, optional :param bypass_docstring_validation: Set to True if you don't want to check if a docstring exists for every module, class and function. Defaults to False. :type bypass_docstring_validation: bool, optional :param bypass_tests: Set to True if you don't want to run doctests and other tests. Defaults to False. :type bypass_tests: bool, optional :param bypass_code_formatting: Set to True if you don't want the code to be automatically formatted using axblack. Defaults to False. :type bypass_code_formatting: bool, optional :param verbose: Set to True if you want to log extra information during the process. Defaults to False. :type verbose: bool, optional<|endoftext|>
249677e70f2121642e4e4a738b3d25feb14dec1c977c66c3b2cba30d3150c8ec
def go(pkg_dir, version=None, publish_docs_to=DFLT_PUBLISH_DOCS_TO, verbose: bool=True, skip_git_commit: bool=False, answer_yes_to_all_prompts: bool=False, twine_upload_options_str: str='', keep_dist_pkgs=False, commit_message=''): 'Update version, package and deploy:\n Runs in a sequence: increment_configs_version, update_setup_cfg, run_setup, twine_upload_dist\n\n :param version: The desired version (if not given, will increment the current version\n :param verbose: Whether to print stuff or not\n :param skip_git_commit: Whether to skip the git commit and push step\n :param answer_yes_to_all_prompts: If you do git commit and push, whether to ask confirmation after showing status\n\n ' version = increment_configs_version(pkg_dir, version) update_setup_cfg(pkg_dir, verbose=verbose) run_setup(pkg_dir) twine_upload_dist(pkg_dir, twine_upload_options_str) if (not keep_dist_pkgs): delete_pkg_directories(pkg_dir, verbose) if publish_docs_to: generate_and_publish_docs(pkg_dir, publish_docs_to) if (not skip_git_commit): git_commit_and_push(pkg_dir, version, verbose, answer_yes_to_all_prompts, commit_message)
Update version, package and deploy: Runs in a sequence: increment_configs_version, update_setup_cfg, run_setup, twine_upload_dist :param version: The desired version (if not given, will increment the current version :param verbose: Whether to print stuff or not :param skip_git_commit: Whether to skip the git commit and push step :param answer_yes_to_all_prompts: If you do git commit and push, whether to ask confirmation after showing status
wads/pack.py
go
i2mint/wads
0
python
def go(pkg_dir, version=None, publish_docs_to=DFLT_PUBLISH_DOCS_TO, verbose: bool=True, skip_git_commit: bool=False, answer_yes_to_all_prompts: bool=False, twine_upload_options_str: str=, keep_dist_pkgs=False, commit_message=): 'Update version, package and deploy:\n Runs in a sequence: increment_configs_version, update_setup_cfg, run_setup, twine_upload_dist\n\n :param version: The desired version (if not given, will increment the current version\n :param verbose: Whether to print stuff or not\n :param skip_git_commit: Whether to skip the git commit and push step\n :param answer_yes_to_all_prompts: If you do git commit and push, whether to ask confirmation after showing status\n\n ' version = increment_configs_version(pkg_dir, version) update_setup_cfg(pkg_dir, verbose=verbose) run_setup(pkg_dir) twine_upload_dist(pkg_dir, twine_upload_options_str) if (not keep_dist_pkgs): delete_pkg_directories(pkg_dir, verbose) if publish_docs_to: generate_and_publish_docs(pkg_dir, publish_docs_to) if (not skip_git_commit): git_commit_and_push(pkg_dir, version, verbose, answer_yes_to_all_prompts, commit_message)
def go(pkg_dir, version=None, publish_docs_to=DFLT_PUBLISH_DOCS_TO, verbose: bool=True, skip_git_commit: bool=False, answer_yes_to_all_prompts: bool=False, twine_upload_options_str: str=, keep_dist_pkgs=False, commit_message=): 'Update version, package and deploy:\n Runs in a sequence: increment_configs_version, update_setup_cfg, run_setup, twine_upload_dist\n\n :param version: The desired version (if not given, will increment the current version\n :param verbose: Whether to print stuff or not\n :param skip_git_commit: Whether to skip the git commit and push step\n :param answer_yes_to_all_prompts: If you do git commit and push, whether to ask confirmation after showing status\n\n ' version = increment_configs_version(pkg_dir, version) update_setup_cfg(pkg_dir, verbose=verbose) run_setup(pkg_dir) twine_upload_dist(pkg_dir, twine_upload_options_str) if (not keep_dist_pkgs): delete_pkg_directories(pkg_dir, verbose) if publish_docs_to: generate_and_publish_docs(pkg_dir, publish_docs_to) if (not skip_git_commit): git_commit_and_push(pkg_dir, version, verbose, answer_yes_to_all_prompts, commit_message)<|docstring|>Update version, package and deploy: Runs in a sequence: increment_configs_version, update_setup_cfg, run_setup, twine_upload_dist :param version: The desired version (if not given, will increment the current version :param verbose: Whether to print stuff or not :param skip_git_commit: Whether to skip the git commit and push step :param answer_yes_to_all_prompts: If you do git commit and push, whether to ask confirmation after showing status<|endoftext|>
644614b29eda237fa4b2953ddef6467a1ca09131e70d3987bc2622adcac7b97e
def validate_pkg_dir(pkg_dir): 'Asserts that the pkg_dir is actually one (has a pkg_name/__init__.py file)' (pkg_dir, pkg_dirname) = _get_pkg_dir_and_name(pkg_dir) assert os.path.isdir(pkg_dir), f"Directory {pkg_dir} wasn't found" assert (pkg_dirname in os.listdir(pkg_dir)), f"pkg_dir={pkg_dir} doesn't itself contain a dir named {pkg_dirname}" assert ('__init__.py' in os.listdir(os.path.join(pkg_dir, pkg_dirname))), f"pkg_dir={pkg_dir} contains a dir named {pkg_dirname}, but that dir isn't a package (does not have a __init__.py" return (pkg_dir, pkg_dirname)
Asserts that the pkg_dir is actually one (has a pkg_name/__init__.py file)
wads/pack.py
validate_pkg_dir
i2mint/wads
0
python
def validate_pkg_dir(pkg_dir): (pkg_dir, pkg_dirname) = _get_pkg_dir_and_name(pkg_dir) assert os.path.isdir(pkg_dir), f"Directory {pkg_dir} wasn't found" assert (pkg_dirname in os.listdir(pkg_dir)), f"pkg_dir={pkg_dir} doesn't itself contain a dir named {pkg_dirname}" assert ('__init__.py' in os.listdir(os.path.join(pkg_dir, pkg_dirname))), f"pkg_dir={pkg_dir} contains a dir named {pkg_dirname}, but that dir isn't a package (does not have a __init__.py" return (pkg_dir, pkg_dirname)
def validate_pkg_dir(pkg_dir): (pkg_dir, pkg_dirname) = _get_pkg_dir_and_name(pkg_dir) assert os.path.isdir(pkg_dir), f"Directory {pkg_dir} wasn't found" assert (pkg_dirname in os.listdir(pkg_dir)), f"pkg_dir={pkg_dir} doesn't itself contain a dir named {pkg_dirname}" assert ('__init__.py' in os.listdir(os.path.join(pkg_dir, pkg_dirname))), f"pkg_dir={pkg_dir} contains a dir named {pkg_dirname}, but that dir isn't a package (does not have a __init__.py" return (pkg_dir, pkg_dirname)<|docstring|>Asserts that the pkg_dir is actually one (has a pkg_name/__init__.py file)<|endoftext|>
8a5c6cc2548c23b48cabb1e36a0bf9179763c6647d3c926fa730b9145b5178b2
def update_setup_cfg(pkg_dir, new_deploy=False, version=None, verbose=True): 'Update setup.cfg (at this point, just updates the version).\n If version is not given, will ask pypi (via http request) what the current version is, and increment that.\n ' pkg_dir = _get_pkg_dir(pkg_dir) configs = read_and_resolve_setup_configs(pkg_dir=_get_pkg_dir(pkg_dir), new_deploy=new_deploy, version=version) pprint('\n{configs}\n') clog(verbose, pprint(configs)) write_configs(pkg_dir=pkg_dir, configs=configs)
Update setup.cfg (at this point, just updates the version). If version is not given, will ask pypi (via http request) what the current version is, and increment that.
wads/pack.py
update_setup_cfg
i2mint/wads
0
python
def update_setup_cfg(pkg_dir, new_deploy=False, version=None, verbose=True): 'Update setup.cfg (at this point, just updates the version).\n If version is not given, will ask pypi (via http request) what the current version is, and increment that.\n ' pkg_dir = _get_pkg_dir(pkg_dir) configs = read_and_resolve_setup_configs(pkg_dir=_get_pkg_dir(pkg_dir), new_deploy=new_deploy, version=version) pprint('\n{configs}\n') clog(verbose, pprint(configs)) write_configs(pkg_dir=pkg_dir, configs=configs)
def update_setup_cfg(pkg_dir, new_deploy=False, version=None, verbose=True): 'Update setup.cfg (at this point, just updates the version).\n If version is not given, will ask pypi (via http request) what the current version is, and increment that.\n ' pkg_dir = _get_pkg_dir(pkg_dir) configs = read_and_resolve_setup_configs(pkg_dir=_get_pkg_dir(pkg_dir), new_deploy=new_deploy, version=version) pprint('\n{configs}\n') clog(verbose, pprint(configs)) write_configs(pkg_dir=pkg_dir, configs=configs)<|docstring|>Update setup.cfg (at this point, just updates the version). If version is not given, will ask pypi (via http request) what the current version is, and increment that.<|endoftext|>
308d30a4e76393b5b99b55d9d3783289085a6e2e2ccb6d691d61483b1c47682e
def set_version(pkg_dir, version): 'Update setup.cfg (at this point, just updates the version).\n If version is not given, will ask pypi (via http request) what the current version is, and increment that.\n ' pkg_dir = _get_pkg_dir(pkg_dir) configs = read_configs(pkg_dir) assert isinstance(version, str), 'version should be a string' configs['version'] = version write_configs(pkg_dir=pkg_dir, configs=configs)
Update setup.cfg (at this point, just updates the version). If version is not given, will ask pypi (via http request) what the current version is, and increment that.
wads/pack.py
set_version
i2mint/wads
0
python
def set_version(pkg_dir, version): 'Update setup.cfg (at this point, just updates the version).\n If version is not given, will ask pypi (via http request) what the current version is, and increment that.\n ' pkg_dir = _get_pkg_dir(pkg_dir) configs = read_configs(pkg_dir) assert isinstance(version, str), 'version should be a string' configs['version'] = version write_configs(pkg_dir=pkg_dir, configs=configs)
def set_version(pkg_dir, version): 'Update setup.cfg (at this point, just updates the version).\n If version is not given, will ask pypi (via http request) what the current version is, and increment that.\n ' pkg_dir = _get_pkg_dir(pkg_dir) configs = read_configs(pkg_dir) assert isinstance(version, str), 'version should be a string' configs['version'] = version write_configs(pkg_dir=pkg_dir, configs=configs)<|docstring|>Update setup.cfg (at this point, just updates the version). If version is not given, will ask pypi (via http request) what the current version is, and increment that.<|endoftext|>
fa4a5b8ee3d665b67a49f7cb9a9a99b9af5854b732fe676248bf73ba3caee830
def increment_configs_version(pkg_dir, version=None): 'Update setup.cfg (at this point, just updates the version).\n If version is not given, will ask pypi (via http request) what the current version is, and increment that.\n ' pkg_dir = _get_pkg_dir(pkg_dir) configs = read_configs(pkg_dir=pkg_dir) version = _get_version(pkg_dir, version=version, configs=configs, new_deploy=False) version = increment_version(version) configs['version'] = version write_configs(pkg_dir=pkg_dir, configs=configs) return version
Update setup.cfg (at this point, just updates the version). If version is not given, will ask pypi (via http request) what the current version is, and increment that.
wads/pack.py
increment_configs_version
i2mint/wads
0
python
def increment_configs_version(pkg_dir, version=None): 'Update setup.cfg (at this point, just updates the version).\n If version is not given, will ask pypi (via http request) what the current version is, and increment that.\n ' pkg_dir = _get_pkg_dir(pkg_dir) configs = read_configs(pkg_dir=pkg_dir) version = _get_version(pkg_dir, version=version, configs=configs, new_deploy=False) version = increment_version(version) configs['version'] = version write_configs(pkg_dir=pkg_dir, configs=configs) return version
def increment_configs_version(pkg_dir, version=None): 'Update setup.cfg (at this point, just updates the version).\n If version is not given, will ask pypi (via http request) what the current version is, and increment that.\n ' pkg_dir = _get_pkg_dir(pkg_dir) configs = read_configs(pkg_dir=pkg_dir) version = _get_version(pkg_dir, version=version, configs=configs, new_deploy=False) version = increment_version(version) configs['version'] = version write_configs(pkg_dir=pkg_dir, configs=configs) return version<|docstring|>Update setup.cfg (at this point, just updates the version). If version is not given, will ask pypi (via http request) what the current version is, and increment that.<|endoftext|>
03d902e238627f789c98a63b67749208ae725ff6dac30220fae3c2eb46557b8e
def run_setup(pkg_dir): 'Run ``python setup.py sdist bdist_wheel``' print('--------------------------- setup_output ---------------------------') pkg_dir = _get_pkg_dir(pkg_dir) original_dir = os.getcwd() os.chdir(pkg_dir) setup_output = subprocess.run(f'{sys.executable} setup.py sdist bdist_wheel'.split(' ')) os.chdir(original_dir)
Run ``python setup.py sdist bdist_wheel``
wads/pack.py
run_setup
i2mint/wads
0
python
def run_setup(pkg_dir): print('--------------------------- setup_output ---------------------------') pkg_dir = _get_pkg_dir(pkg_dir) original_dir = os.getcwd() os.chdir(pkg_dir) setup_output = subprocess.run(f'{sys.executable} setup.py sdist bdist_wheel'.split(' ')) os.chdir(original_dir)
def run_setup(pkg_dir): print('--------------------------- setup_output ---------------------------') pkg_dir = _get_pkg_dir(pkg_dir) original_dir = os.getcwd() os.chdir(pkg_dir) setup_output = subprocess.run(f'{sys.executable} setup.py sdist bdist_wheel'.split(' ')) os.chdir(original_dir)<|docstring|>Run ``python setup.py sdist bdist_wheel``<|endoftext|>
ff6931e1ab065fd2e366fd769b2c1be534d00f7865f3c0731432bb7e73b206a1
def twine_upload_dist(pkg_dir, options_str=None): 'Publish to pypi. Runs ``python -m twine upload dist/*``' print('--------------------------- upload_output ---------------------------') pkg_dir = _get_pkg_dir(pkg_dir) original_dir = os.getcwd() os.chdir(pkg_dir) if options_str: command = f'{sys.executable} -m twine upload {options_str} dist/*' else: command = f'{sys.executable} -m twine upload dist/*' subprocess.run(command.split(' ')) os.chdir(original_dir)
Publish to pypi. Runs ``python -m twine upload dist/*``
wads/pack.py
twine_upload_dist
i2mint/wads
0
python
def twine_upload_dist(pkg_dir, options_str=None): print('--------------------------- upload_output ---------------------------') pkg_dir = _get_pkg_dir(pkg_dir) original_dir = os.getcwd() os.chdir(pkg_dir) if options_str: command = f'{sys.executable} -m twine upload {options_str} dist/*' else: command = f'{sys.executable} -m twine upload dist/*' subprocess.run(command.split(' ')) os.chdir(original_dir)
def twine_upload_dist(pkg_dir, options_str=None): print('--------------------------- upload_output ---------------------------') pkg_dir = _get_pkg_dir(pkg_dir) original_dir = os.getcwd() os.chdir(pkg_dir) if options_str: command = f'{sys.executable} -m twine upload {options_str} dist/*' else: command = f'{sys.executable} -m twine upload dist/*' subprocess.run(command.split(' ')) os.chdir(original_dir)<|docstring|>Publish to pypi. Runs ``python -m twine upload dist/*``<|endoftext|>
18dac6cafacdc4a4bec15f96070c9293010ad5116524eb0c2e7b4491a741409a
def postprocess_ini_section_items(items: Union[(Mapping, Iterable)]) -> Generator: "Transform newline-separated string values into actual list of strings (assuming that intent)\n\n >>> section_from_ini = {\n ... 'name': 'wads',\n ... 'keywords': '\\n\\tpackaging\\n\\tpublishing'\n ... }\n >>> section_for_python = dict(postprocess_ini_section_items(section_from_ini))\n >>> section_for_python\n {'name': 'wads', 'keywords': ['packaging', 'publishing']}\n\n " splitter_re = re.compile('[\n\r\t]+') if isinstance(items, Mapping): items = items.items() for (k, v) in items: if v.startswith('\n'): v = splitter_re.split(v[1:]) v = [vv.strip() for vv in v if vv.strip()] v = [vv for vv in v if (not vv.startswith('#'))] (yield (k, v))
Transform newline-separated string values into actual list of strings (assuming that intent) >>> section_from_ini = { ... 'name': 'wads', ... 'keywords': '\n\tpackaging\n\tpublishing' ... } >>> section_for_python = dict(postprocess_ini_section_items(section_from_ini)) >>> section_for_python {'name': 'wads', 'keywords': ['packaging', 'publishing']}
wads/pack.py
postprocess_ini_section_items
i2mint/wads
0
python
def postprocess_ini_section_items(items: Union[(Mapping, Iterable)]) -> Generator: "Transform newline-separated string values into actual list of strings (assuming that intent)\n\n >>> section_from_ini = {\n ... 'name': 'wads',\n ... 'keywords': '\\n\\tpackaging\\n\\tpublishing'\n ... }\n >>> section_for_python = dict(postprocess_ini_section_items(section_from_ini))\n >>> section_for_python\n {'name': 'wads', 'keywords': ['packaging', 'publishing']}\n\n " splitter_re = re.compile('[\n\r\t]+') if isinstance(items, Mapping): items = items.items() for (k, v) in items: if v.startswith('\n'): v = splitter_re.split(v[1:]) v = [vv.strip() for vv in v if vv.strip()] v = [vv for vv in v if (not vv.startswith('#'))] (yield (k, v))
def postprocess_ini_section_items(items: Union[(Mapping, Iterable)]) -> Generator: "Transform newline-separated string values into actual list of strings (assuming that intent)\n\n >>> section_from_ini = {\n ... 'name': 'wads',\n ... 'keywords': '\\n\\tpackaging\\n\\tpublishing'\n ... }\n >>> section_for_python = dict(postprocess_ini_section_items(section_from_ini))\n >>> section_for_python\n {'name': 'wads', 'keywords': ['packaging', 'publishing']}\n\n " splitter_re = re.compile('[\n\r\t]+') if isinstance(items, Mapping): items = items.items() for (k, v) in items: if v.startswith('\n'): v = splitter_re.split(v[1:]) v = [vv.strip() for vv in v if vv.strip()] v = [vv for vv in v if (not vv.startswith('#'))] (yield (k, v))<|docstring|>Transform newline-separated string values into actual list of strings (assuming that intent) >>> section_from_ini = { ... 'name': 'wads', ... 'keywords': '\n\tpackaging\n\tpublishing' ... } >>> section_for_python = dict(postprocess_ini_section_items(section_from_ini)) >>> section_for_python {'name': 'wads', 'keywords': ['packaging', 'publishing']}<|endoftext|>
4ab79f4a41ef136d7d7e2fa1550d0fd4139df57c5e74a5f5718e68d0a8dd6d39
def preprocess_ini_section_items(items: Union[(Mapping, Iterable)]) -> Generator: "Transform list values into newline-separated strings, in view of writing the value to a ini formatted section\n\n >>> section = {\n ... 'name': 'wads',\n ... 'keywords': ['documentation', 'packaging', 'publishing']\n ... }\n >>> for_ini = dict(preprocess_ini_section_items(section))\n >>> print('keywords =' + for_ini['keywords']) # doctest: +NORMALIZE_WHITESPACE\n keywords =\n documentation\n packaging\n publishing\n\n " if isinstance(items, Mapping): items = items.items() for (k, v) in items: if (isinstance(v, str) and (not v.startswith('"')) and (',' in v)): v = list(map(str.strip, v.split(','))) if isinstance(v, list): v = ('\n\t' + '\n\t'.join(v)) (yield (k, v))
Transform list values into newline-separated strings, in view of writing the value to a ini formatted section >>> section = { ... 'name': 'wads', ... 'keywords': ['documentation', 'packaging', 'publishing'] ... } >>> for_ini = dict(preprocess_ini_section_items(section)) >>> print('keywords =' + for_ini['keywords']) # doctest: +NORMALIZE_WHITESPACE keywords = documentation packaging publishing
wads/pack.py
preprocess_ini_section_items
i2mint/wads
0
python
def preprocess_ini_section_items(items: Union[(Mapping, Iterable)]) -> Generator: "Transform list values into newline-separated strings, in view of writing the value to a ini formatted section\n\n >>> section = {\n ... 'name': 'wads',\n ... 'keywords': ['documentation', 'packaging', 'publishing']\n ... }\n >>> for_ini = dict(preprocess_ini_section_items(section))\n >>> print('keywords =' + for_ini['keywords']) # doctest: +NORMALIZE_WHITESPACE\n keywords =\n documentation\n packaging\n publishing\n\n " if isinstance(items, Mapping): items = items.items() for (k, v) in items: if (isinstance(v, str) and (not v.startswith('"')) and (',' in v)): v = list(map(str.strip, v.split(','))) if isinstance(v, list): v = ('\n\t' + '\n\t'.join(v)) (yield (k, v))
def preprocess_ini_section_items(items: Union[(Mapping, Iterable)]) -> Generator: "Transform list values into newline-separated strings, in view of writing the value to a ini formatted section\n\n >>> section = {\n ... 'name': 'wads',\n ... 'keywords': ['documentation', 'packaging', 'publishing']\n ... }\n >>> for_ini = dict(preprocess_ini_section_items(section))\n >>> print('keywords =' + for_ini['keywords']) # doctest: +NORMALIZE_WHITESPACE\n keywords =\n documentation\n packaging\n publishing\n\n " if isinstance(items, Mapping): items = items.items() for (k, v) in items: if (isinstance(v, str) and (not v.startswith('"')) and (',' in v)): v = list(map(str.strip, v.split(','))) if isinstance(v, list): v = ('\n\t' + '\n\t'.join(v)) (yield (k, v))<|docstring|>Transform list values into newline-separated strings, in view of writing the value to a ini formatted section >>> section = { ... 'name': 'wads', ... 'keywords': ['documentation', 'packaging', 'publishing'] ... } >>> for_ini = dict(preprocess_ini_section_items(section)) >>> print('keywords =' + for_ini['keywords']) # doctest: +NORMALIZE_WHITESPACE keywords = documentation packaging publishing<|endoftext|>
0154f94437db64d1feee2acc6fdc0c971a3bcc26e46aa701a74a5c89024072fc
def http_get_json(url, use_requests=requests_is_installed) -> Union[(dict, None)]: 'Make ah http request to url and get json, and return as python dict' if use_requests: import requests r = requests.get(url) if (r.status_code == 200): return r.json() else: raise ValueError(f'response code was {r.status_code}') else: import urllib.request from urllib.error import HTTPError req = urllib.request.Request(url) try: r = urllib.request.urlopen(req) if (r.code == 200): return json.loads(r.read()) else: raise ValueError(f'response code was {r.code}') except HTTPError: return None except Exception: raise
Make ah http request to url and get json, and return as python dict
wads/pack.py
http_get_json
i2mint/wads
0
python
def http_get_json(url, use_requests=requests_is_installed) -> Union[(dict, None)]: if use_requests: import requests r = requests.get(url) if (r.status_code == 200): return r.json() else: raise ValueError(f'response code was {r.status_code}') else: import urllib.request from urllib.error import HTTPError req = urllib.request.Request(url) try: r = urllib.request.urlopen(req) if (r.code == 200): return json.loads(r.read()) else: raise ValueError(f'response code was {r.code}') except HTTPError: return None except Exception: raise
def http_get_json(url, use_requests=requests_is_installed) -> Union[(dict, None)]: if use_requests: import requests r = requests.get(url) if (r.status_code == 200): return r.json() else: raise ValueError(f'response code was {r.status_code}') else: import urllib.request from urllib.error import HTTPError req = urllib.request.Request(url) try: r = urllib.request.urlopen(req) if (r.code == 200): return json.loads(r.read()) else: raise ValueError(f'response code was {r.code}') except HTTPError: return None except Exception: raise<|docstring|>Make ah http request to url and get json, and return as python dict<|endoftext|>
71d0621919d4a9049e9af8ea09c92e0d7f3d4990c6241c8a723b99f341ecc787
def current_pypi_version(pkg_dir: Path, name: Union[(None, str)]=None, url_template=DLFT_PYPI_PACKAGE_JSON_URL_TEMPLATE, use_requests=requests_is_installed) -> Union[(str, None)]: "\n Return version of package on pypi.python.org using json.\n\n ::\n\n current_pypi_version('py2store')\n '0.0.7'\n\n\n :param package: Name of the package\n :return: A version (string) or None if there was an exception (usually means there\n " (pkg_dir, pkg_dirname) = validate_pkg_dir(pkg_dir) name = (name or get_name_from_configs(pkg_dir)) assert (pkg_dirname == name), f'pkg_dirname ({pkg_dirname}) and name ({name}) were not the same' url = url_template.format(package=name) t = http_get_json(url, use_requests=use_requests) releases = t.get('releases', []) if releases: return sorted(releases, key=(lambda r: tuple(map(int, r.split('.')))))[(- 1)]
Return version of package on pypi.python.org using json. :: current_pypi_version('py2store') '0.0.7' :param package: Name of the package :return: A version (string) or None if there was an exception (usually means there
wads/pack.py
current_pypi_version
i2mint/wads
0
python
def current_pypi_version(pkg_dir: Path, name: Union[(None, str)]=None, url_template=DLFT_PYPI_PACKAGE_JSON_URL_TEMPLATE, use_requests=requests_is_installed) -> Union[(str, None)]: "\n Return version of package on pypi.python.org using json.\n\n ::\n\n current_pypi_version('py2store')\n '0.0.7'\n\n\n :param package: Name of the package\n :return: A version (string) or None if there was an exception (usually means there\n " (pkg_dir, pkg_dirname) = validate_pkg_dir(pkg_dir) name = (name or get_name_from_configs(pkg_dir)) assert (pkg_dirname == name), f'pkg_dirname ({pkg_dirname}) and name ({name}) were not the same' url = url_template.format(package=name) t = http_get_json(url, use_requests=use_requests) releases = t.get('releases', []) if releases: return sorted(releases, key=(lambda r: tuple(map(int, r.split('.')))))[(- 1)]
def current_pypi_version(pkg_dir: Path, name: Union[(None, str)]=None, url_template=DLFT_PYPI_PACKAGE_JSON_URL_TEMPLATE, use_requests=requests_is_installed) -> Union[(str, None)]: "\n Return version of package on pypi.python.org using json.\n\n ::\n\n current_pypi_version('py2store')\n '0.0.7'\n\n\n :param package: Name of the package\n :return: A version (string) or None if there was an exception (usually means there\n " (pkg_dir, pkg_dirname) = validate_pkg_dir(pkg_dir) name = (name or get_name_from_configs(pkg_dir)) assert (pkg_dirname == name), f'pkg_dirname ({pkg_dirname}) and name ({name}) were not the same' url = url_template.format(package=name) t = http_get_json(url, use_requests=use_requests) releases = t.get('releases', []) if releases: return sorted(releases, key=(lambda r: tuple(map(int, r.split('.')))))[(- 1)]<|docstring|>Return version of package on pypi.python.org using json. :: current_pypi_version('py2store') '0.0.7' :param package: Name of the package :return: A version (string) or None if there was an exception (usually means there<|endoftext|>
2152ce095d98dcd0f07ffb7ce284278245d2a7dea85b061ed5ba44e0d80eeb25
def read_and_resolve_setup_configs(pkg_dir: Path, new_deploy=False, version=None, assert_names=True): 'make setup params and call setup\n\n :param pkg_dir: Directory where the pkg is (which is also where the setup.cfg is)\n :param new_deploy: whether this setup for a new deployment (publishing to pypi) or not\n :param version: The version number to set this up as.\n If not given will look at setup.cfg[metadata] for one,\n and if not found there will use the current version (requesting pypi.org)\n and bump it if the new_deploy flag is on\n ' (pkg_dir, pkg_dirname) = _get_pkg_dir_and_name(pkg_dir) if assert_names: validate_pkg_dir(pkg_dir) configs = read_configs(pkg_dir) assert (('root_url' in configs) or ('url' in configs)), "configs didn't have a root_url or url" name = (configs['name'] or pkg_dirname) if assert_names: assert (name == pkg_dirname), f'config name ({name}) and pkg_dirname ({pkg_dirname}) are not equal!' if ('root_url' in configs): root_url = configs['root_url'] if root_url.endswith('/'): root_url = root_url[:(- 1)] url = f'{root_url}/{name}' elif ('url' in configs): url = configs['url'] else: raise ValueError(f"configs didn't have a root_url or url. It should have at least one of these!") meta_data_dict = {k: v for (k, v) in configs.items()} setup_kwargs = dict(meta_data_dict) version = _get_version(pkg_dir, version, configs, name, new_deploy) def text_of_readme_md_file(): try: with open('README.md') as f: return f.read() except: return '' dflt_kwargs = dict(name=f'{name}', version=f'{version}', url=url, packages=find_packages(), include_package_data=True, platforms='any', description_file='README.md') configs = dict(dflt_kwargs, **setup_kwargs) return configs
make setup params and call setup :param pkg_dir: Directory where the pkg is (which is also where the setup.cfg is) :param new_deploy: whether this setup for a new deployment (publishing to pypi) or not :param version: The version number to set this up as. If not given will look at setup.cfg[metadata] for one, and if not found there will use the current version (requesting pypi.org) and bump it if the new_deploy flag is on
wads/pack.py
read_and_resolve_setup_configs
i2mint/wads
0
python
def read_and_resolve_setup_configs(pkg_dir: Path, new_deploy=False, version=None, assert_names=True): 'make setup params and call setup\n\n :param pkg_dir: Directory where the pkg is (which is also where the setup.cfg is)\n :param new_deploy: whether this setup for a new deployment (publishing to pypi) or not\n :param version: The version number to set this up as.\n If not given will look at setup.cfg[metadata] for one,\n and if not found there will use the current version (requesting pypi.org)\n and bump it if the new_deploy flag is on\n ' (pkg_dir, pkg_dirname) = _get_pkg_dir_and_name(pkg_dir) if assert_names: validate_pkg_dir(pkg_dir) configs = read_configs(pkg_dir) assert (('root_url' in configs) or ('url' in configs)), "configs didn't have a root_url or url" name = (configs['name'] or pkg_dirname) if assert_names: assert (name == pkg_dirname), f'config name ({name}) and pkg_dirname ({pkg_dirname}) are not equal!' if ('root_url' in configs): root_url = configs['root_url'] if root_url.endswith('/'): root_url = root_url[:(- 1)] url = f'{root_url}/{name}' elif ('url' in configs): url = configs['url'] else: raise ValueError(f"configs didn't have a root_url or url. It should have at least one of these!") meta_data_dict = {k: v for (k, v) in configs.items()} setup_kwargs = dict(meta_data_dict) version = _get_version(pkg_dir, version, configs, name, new_deploy) def text_of_readme_md_file(): try: with open('README.md') as f: return f.read() except: return dflt_kwargs = dict(name=f'{name}', version=f'{version}', url=url, packages=find_packages(), include_package_data=True, platforms='any', description_file='README.md') configs = dict(dflt_kwargs, **setup_kwargs) return configs
def read_and_resolve_setup_configs(pkg_dir: Path, new_deploy=False, version=None, assert_names=True): 'make setup params and call setup\n\n :param pkg_dir: Directory where the pkg is (which is also where the setup.cfg is)\n :param new_deploy: whether this setup for a new deployment (publishing to pypi) or not\n :param version: The version number to set this up as.\n If not given will look at setup.cfg[metadata] for one,\n and if not found there will use the current version (requesting pypi.org)\n and bump it if the new_deploy flag is on\n ' (pkg_dir, pkg_dirname) = _get_pkg_dir_and_name(pkg_dir) if assert_names: validate_pkg_dir(pkg_dir) configs = read_configs(pkg_dir) assert (('root_url' in configs) or ('url' in configs)), "configs didn't have a root_url or url" name = (configs['name'] or pkg_dirname) if assert_names: assert (name == pkg_dirname), f'config name ({name}) and pkg_dirname ({pkg_dirname}) are not equal!' if ('root_url' in configs): root_url = configs['root_url'] if root_url.endswith('/'): root_url = root_url[:(- 1)] url = f'{root_url}/{name}' elif ('url' in configs): url = configs['url'] else: raise ValueError(f"configs didn't have a root_url or url. It should have at least one of these!") meta_data_dict = {k: v for (k, v) in configs.items()} setup_kwargs = dict(meta_data_dict) version = _get_version(pkg_dir, version, configs, name, new_deploy) def text_of_readme_md_file(): try: with open('README.md') as f: return f.read() except: return dflt_kwargs = dict(name=f'{name}', version=f'{version}', url=url, packages=find_packages(), include_package_data=True, platforms='any', description_file='README.md') configs = dict(dflt_kwargs, **setup_kwargs) return configs<|docstring|>make setup params and call setup :param pkg_dir: Directory where the pkg is (which is also where the setup.cfg is) :param new_deploy: whether this setup for a new deployment (publishing to pypi) or not :param version: The version number to set this up as. If not given will look at setup.cfg[metadata] for one, and if not found there will use the current version (requesting pypi.org) and bump it if the new_deploy flag is on<|endoftext|>
2678ef8e0366cd1f0be97d1f8ed4588af1e92215feee60768c236f8038e9fe88
def process_missing_module_docstrings(pkg_dir: Path, action='input', exceptions=(), docstr_template='"""\n{user_input}\n"""\n'): "\n Goes through modules of package, sees which ones don't have docstrings,\n and gives you the option to write one.\n\n The function will go through all .py files (except those mentioned in exceptions),\n check if there's a module docstring (that is, that the first non-white characters are\n triple-quotes (double or single)).\n\n What happens with that depends on the ``action`` argument,\n\n If ``action='list'``, those modules missing docstrings will be listed.\n If ``action='count'``, the count of those modules missing docstrings will be returned.\n\n If ``action='input'``, for every module you'll be given the option to enter a\n SINGLE LINE module docstring (though you could include multi-lines with \\n).\n Just type the docstring you want and hit enter to go to the next module with missing docstring.\n Or, you can also:\n - type exit, or e: To exit this process\n - type skip, or s: To skip the module and go to the next\n - type funcs, or f: To see a print out of functions, classes, and methods\n - just hit enter, to get some lines of code (the first, then the next, etc.)\n - enter a number, or a number:number, to specify what lines you want to see printed\n Printing lines helps you write an informed module docstring\n\n :keyword module, docstr, docstrings, module doc strings\n " from py2store import LocalTextStore, filt_iter (pkg_dir, _) = _get_pkg_dir_and_name(pkg_dir) exceptions = set(exceptions) files = filt_iter(LocalTextStore((pkg_dir + '{}.py'), max_levels=None), filt=exceptions.isdisjoint) def files_and_contents_that_dont_have_docs(): for (file, file_contents) in files.items(): contents = file_contents.strip() if ((not contents.startswith('"""')) and (not contents.startswith("'''"))): (yield (file, file_contents)) if (action == 'list'): return [file for (file, file_contents) in files_and_contents_that_dont_have_docs()] elif (action == 'count'): return len(list(files_and_contents_that_dont_have_docs())) elif (action == 'input'): were_no_files = True for (file, file_contents) in files_and_contents_that_dont_have_docs(): were_no_files = False r = _ask_user_what_to_do_about_this_file(file, file_contents) if (r == 'exit'): return elif (r == 'skip'): continue files[file] = (docstr_template.format(user_input=r) + file_contents) if were_no_files: print('---> Seems like all your modules have docstrings! Congrads!') return True else: raise ValueError(f'Unknown action: {action}')
Goes through modules of package, sees which ones don't have docstrings, and gives you the option to write one. The function will go through all .py files (except those mentioned in exceptions), check if there's a module docstring (that is, that the first non-white characters are triple-quotes (double or single)). What happens with that depends on the ``action`` argument, If ``action='list'``, those modules missing docstrings will be listed. If ``action='count'``, the count of those modules missing docstrings will be returned. If ``action='input'``, for every module you'll be given the option to enter a SINGLE LINE module docstring (though you could include multi-lines with \n). Just type the docstring you want and hit enter to go to the next module with missing docstring. Or, you can also: - type exit, or e: To exit this process - type skip, or s: To skip the module and go to the next - type funcs, or f: To see a print out of functions, classes, and methods - just hit enter, to get some lines of code (the first, then the next, etc.) - enter a number, or a number:number, to specify what lines you want to see printed Printing lines helps you write an informed module docstring :keyword module, docstr, docstrings, module doc strings
wads/pack.py
process_missing_module_docstrings
i2mint/wads
0
python
def process_missing_module_docstrings(pkg_dir: Path, action='input', exceptions=(), docstr_template='"\n{user_input}\n"\n'): "\n Goes through modules of package, sees which ones don't have docstrings,\n and gives you the option to write one.\n\n The function will go through all .py files (except those mentioned in exceptions),\n check if there's a module docstring (that is, that the first non-white characters are\n triple-quotes (double or single)).\n\n What happens with that depends on the ``action`` argument,\n\n If ``action='list'``, those modules missing docstrings will be listed.\n If ``action='count'``, the count of those modules missing docstrings will be returned.\n\n If ``action='input'``, for every module you'll be given the option to enter a\n SINGLE LINE module docstring (though you could include multi-lines with \\n).\n Just type the docstring you want and hit enter to go to the next module with missing docstring.\n Or, you can also:\n - type exit, or e: To exit this process\n - type skip, or s: To skip the module and go to the next\n - type funcs, or f: To see a print out of functions, classes, and methods\n - just hit enter, to get some lines of code (the first, then the next, etc.)\n - enter a number, or a number:number, to specify what lines you want to see printed\n Printing lines helps you write an informed module docstring\n\n :keyword module, docstr, docstrings, module doc strings\n " from py2store import LocalTextStore, filt_iter (pkg_dir, _) = _get_pkg_dir_and_name(pkg_dir) exceptions = set(exceptions) files = filt_iter(LocalTextStore((pkg_dir + '{}.py'), max_levels=None), filt=exceptions.isdisjoint) def files_and_contents_that_dont_have_docs(): for (file, file_contents) in files.items(): contents = file_contents.strip() if ((not contents.startswith('"')) and (not contents.startswith("'"))): (yield (file, file_contents)) if (action == 'list'): return [file for (file, file_contents) in files_and_contents_that_dont_have_docs()] elif (action == 'count'): return len(list(files_and_contents_that_dont_have_docs())) elif (action == 'input'): were_no_files = True for (file, file_contents) in files_and_contents_that_dont_have_docs(): were_no_files = False r = _ask_user_what_to_do_about_this_file(file, file_contents) if (r == 'exit'): return elif (r == 'skip'): continue files[file] = (docstr_template.format(user_input=r) + file_contents) if were_no_files: print('---> Seems like all your modules have docstrings! Congrads!') return True else: raise ValueError(f'Unknown action: {action}')
def process_missing_module_docstrings(pkg_dir: Path, action='input', exceptions=(), docstr_template='"\n{user_input}\n"\n'): "\n Goes through modules of package, sees which ones don't have docstrings,\n and gives you the option to write one.\n\n The function will go through all .py files (except those mentioned in exceptions),\n check if there's a module docstring (that is, that the first non-white characters are\n triple-quotes (double or single)).\n\n What happens with that depends on the ``action`` argument,\n\n If ``action='list'``, those modules missing docstrings will be listed.\n If ``action='count'``, the count of those modules missing docstrings will be returned.\n\n If ``action='input'``, for every module you'll be given the option to enter a\n SINGLE LINE module docstring (though you could include multi-lines with \\n).\n Just type the docstring you want and hit enter to go to the next module with missing docstring.\n Or, you can also:\n - type exit, or e: To exit this process\n - type skip, or s: To skip the module and go to the next\n - type funcs, or f: To see a print out of functions, classes, and methods\n - just hit enter, to get some lines of code (the first, then the next, etc.)\n - enter a number, or a number:number, to specify what lines you want to see printed\n Printing lines helps you write an informed module docstring\n\n :keyword module, docstr, docstrings, module doc strings\n " from py2store import LocalTextStore, filt_iter (pkg_dir, _) = _get_pkg_dir_and_name(pkg_dir) exceptions = set(exceptions) files = filt_iter(LocalTextStore((pkg_dir + '{}.py'), max_levels=None), filt=exceptions.isdisjoint) def files_and_contents_that_dont_have_docs(): for (file, file_contents) in files.items(): contents = file_contents.strip() if ((not contents.startswith('"')) and (not contents.startswith("'"))): (yield (file, file_contents)) if (action == 'list'): return [file for (file, file_contents) in files_and_contents_that_dont_have_docs()] elif (action == 'count'): return len(list(files_and_contents_that_dont_have_docs())) elif (action == 'input'): were_no_files = True for (file, file_contents) in files_and_contents_that_dont_have_docs(): were_no_files = False r = _ask_user_what_to_do_about_this_file(file, file_contents) if (r == 'exit'): return elif (r == 'skip'): continue files[file] = (docstr_template.format(user_input=r) + file_contents) if were_no_files: print('---> Seems like all your modules have docstrings! Congrads!') return True else: raise ValueError(f'Unknown action: {action}')<|docstring|>Goes through modules of package, sees which ones don't have docstrings, and gives you the option to write one. The function will go through all .py files (except those mentioned in exceptions), check if there's a module docstring (that is, that the first non-white characters are triple-quotes (double or single)). What happens with that depends on the ``action`` argument, If ``action='list'``, those modules missing docstrings will be listed. If ``action='count'``, the count of those modules missing docstrings will be returned. If ``action='input'``, for every module you'll be given the option to enter a SINGLE LINE module docstring (though you could include multi-lines with \n). Just type the docstring you want and hit enter to go to the next module with missing docstring. Or, you can also: - type exit, or e: To exit this process - type skip, or s: To skip the module and go to the next - type funcs, or f: To see a print out of functions, classes, and methods - just hit enter, to get some lines of code (the first, then the next, etc.) - enter a number, or a number:number, to specify what lines you want to see printed Printing lines helps you write an informed module docstring :keyword module, docstr, docstrings, module doc strings<|endoftext|>
84410412779a3a7cb6b5b70fedead0ac57c4257b0bb0c3e994fd1a914fcc957b
def check_skelet3d_lib(): '\n Check if skelet3d libs (.so, .dll) are installed. Install it.\n :return:\n ' import skelet3d data = np.zeros([8, 9, 10], dtype=np.int8) data[(1:4, 3:7, 1:12)] = 1 skelet = skelet3d.skelet3d(data)
Check if skelet3d libs (.so, .dll) are installed. Install it. :return:
quantan/histology_analyser_gui.py
check_skelet3d_lib
mjirik/quanta
0
python
def check_skelet3d_lib(): '\n Check if skelet3d libs (.so, .dll) are installed. Install it.\n :return:\n ' import skelet3d data = np.zeros([8, 9, 10], dtype=np.int8) data[(1:4, 3:7, 1:12)] = 1 skelet = skelet3d.skelet3d(data)
def check_skelet3d_lib(): '\n Check if skelet3d libs (.so, .dll) are installed. Install it.\n :return:\n ' import skelet3d data = np.zeros([8, 9, 10], dtype=np.int8) data[(1:4, 3:7, 1:12)] = 1 skelet = skelet3d.skelet3d(data)<|docstring|>Check if skelet3d libs (.so, .dll) are installed. Install it. :return:<|endoftext|>
013d339c976d8f8f13c941987ff74303f60a5911afbac37e438660780ede0ec4
def closeEvent(self, event): '\n Runs when user tryes to close main window.\n\n sys.exit(0) - to fix wierd bug, where process is not terminated.\n ' sys.exit(0)
Runs when user tryes to close main window. sys.exit(0) - to fix wierd bug, where process is not terminated.
quantan/histology_analyser_gui.py
closeEvent
mjirik/quanta
0
python
def closeEvent(self, event): '\n Runs when user tryes to close main window.\n\n sys.exit(0) - to fix wierd bug, where process is not terminated.\n ' sys.exit(0)
def closeEvent(self, event): '\n Runs when user tryes to close main window.\n\n sys.exit(0) - to fix wierd bug, where process is not terminated.\n ' sys.exit(0)<|docstring|>Runs when user tryes to close main window. sys.exit(0) - to fix wierd bug, where process is not terminated.<|endoftext|>