repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
pyhys/minimalmodbus
minimalmodbus.py
_createBitpattern
def _createBitpattern(functioncode, value): """Create the bit pattern that is used for writing single bits. This is basically a storage of numerical constants. Args: * functioncode (int): can be 5 or 15 * value (int): can be 0 or 1 Returns: The bit pattern (string). Raise...
python
def _createBitpattern(functioncode, value): """Create the bit pattern that is used for writing single bits. This is basically a storage of numerical constants. Args: * functioncode (int): can be 5 or 15 * value (int): can be 0 or 1 Returns: The bit pattern (string). Raise...
[ "def", "_createBitpattern", "(", "functioncode", ",", "value", ")", ":", "_checkFunctioncode", "(", "functioncode", ",", "[", "5", ",", "15", "]", ")", "_checkInt", "(", "value", ",", "minvalue", "=", "0", ",", "maxvalue", "=", "1", ",", "description", "...
Create the bit pattern that is used for writing single bits. This is basically a storage of numerical constants. Args: * functioncode (int): can be 5 or 15 * value (int): can be 0 or 1 Returns: The bit pattern (string). Raises: TypeError, ValueError
[ "Create", "the", "bit", "pattern", "that", "is", "used", "for", "writing", "single", "bits", "." ]
e99f4d74c83258c6039073082955ac9bed3f2155
https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L1773-L1802
train
pyhys/minimalmodbus
minimalmodbus.py
_twosComplement
def _twosComplement(x, bits=16): """Calculate the two's complement of an integer. Then also negative values can be represented by an upper range of positive values. See https://en.wikipedia.org/wiki/Two%27s_complement Args: * x (int): input integer. * bits (int): number of bits, must b...
python
def _twosComplement(x, bits=16): """Calculate the two's complement of an integer. Then also negative values can be represented by an upper range of positive values. See https://en.wikipedia.org/wiki/Two%27s_complement Args: * x (int): input integer. * bits (int): number of bits, must b...
[ "def", "_twosComplement", "(", "x", ",", "bits", "=", "16", ")", ":", "_checkInt", "(", "bits", ",", "minvalue", "=", "0", ",", "description", "=", "'number of bits'", ")", "_checkInt", "(", "x", ",", "description", "=", "'input'", ")", "upperlimit", "="...
Calculate the two's complement of an integer. Then also negative values can be represented by an upper range of positive values. See https://en.wikipedia.org/wiki/Two%27s_complement Args: * x (int): input integer. * bits (int): number of bits, must be > 0. Returns: An int, tha...
[ "Calculate", "the", "two", "s", "complement", "of", "an", "integer", "." ]
e99f4d74c83258c6039073082955ac9bed3f2155
https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L1809-L1847
train
pyhys/minimalmodbus
minimalmodbus.py
_setBitOn
def _setBitOn(x, bitNum): """Set bit 'bitNum' to True. Args: * x (int): The value before. * bitNum (int): The bit number that should be set to True. Returns: The value after setting the bit. This is an integer. For example: For x = 4 (dec) = 0100 (bin), setting bit num...
python
def _setBitOn(x, bitNum): """Set bit 'bitNum' to True. Args: * x (int): The value before. * bitNum (int): The bit number that should be set to True. Returns: The value after setting the bit. This is an integer. For example: For x = 4 (dec) = 0100 (bin), setting bit num...
[ "def", "_setBitOn", "(", "x", ",", "bitNum", ")", ":", "_checkInt", "(", "x", ",", "minvalue", "=", "0", ",", "description", "=", "'input value'", ")", "_checkInt", "(", "bitNum", ",", "minvalue", "=", "0", ",", "description", "=", "'bitnumber'", ")", ...
Set bit 'bitNum' to True. Args: * x (int): The value before. * bitNum (int): The bit number that should be set to True. Returns: The value after setting the bit. This is an integer. For example: For x = 4 (dec) = 0100 (bin), setting bit number 0 results in 0101 (bin) = 5 (...
[ "Set", "bit", "bitNum", "to", "True", "." ]
e99f4d74c83258c6039073082955ac9bed3f2155
https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L1893-L1910
train
pyhys/minimalmodbus
minimalmodbus.py
_calculateCrcString
def _calculateCrcString(inputstring): """Calculate CRC-16 for Modbus. Args: inputstring (str): An arbitrary-length message (without the CRC). Returns: A two-byte CRC string, where the least significant byte is first. """ _checkString(inputstring, description='input CRC string') ...
python
def _calculateCrcString(inputstring): """Calculate CRC-16 for Modbus. Args: inputstring (str): An arbitrary-length message (without the CRC). Returns: A two-byte CRC string, where the least significant byte is first. """ _checkString(inputstring, description='input CRC string') ...
[ "def", "_calculateCrcString", "(", "inputstring", ")", ":", "_checkString", "(", "inputstring", ",", "description", "=", "'input CRC string'", ")", "register", "=", "0xFFFF", "for", "char", "in", "inputstring", ":", "register", "=", "(", "register", ">>", "8", ...
Calculate CRC-16 for Modbus. Args: inputstring (str): An arbitrary-length message (without the CRC). Returns: A two-byte CRC string, where the least significant byte is first.
[ "Calculate", "CRC", "-", "16", "for", "Modbus", "." ]
e99f4d74c83258c6039073082955ac9bed3f2155
https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L1965-L1983
train
pyhys/minimalmodbus
minimalmodbus.py
_calculateLrcString
def _calculateLrcString(inputstring): """Calculate LRC for Modbus. Args: inputstring (str): An arbitrary-length message (without the beginning colon and terminating CRLF). It should already be decoded from hex-string. Returns: A one-byte LRC bytestring (not encoded to hex-string) ...
python
def _calculateLrcString(inputstring): """Calculate LRC for Modbus. Args: inputstring (str): An arbitrary-length message (without the beginning colon and terminating CRLF). It should already be decoded from hex-string. Returns: A one-byte LRC bytestring (not encoded to hex-string) ...
[ "def", "_calculateLrcString", "(", "inputstring", ")", ":", "_checkString", "(", "inputstring", ",", "description", "=", "'input LRC string'", ")", "register", "=", "0", "for", "character", "in", "inputstring", ":", "register", "+=", "ord", "(", "character", ")"...
Calculate LRC for Modbus. Args: inputstring (str): An arbitrary-length message (without the beginning colon and terminating CRLF). It should already be decoded from hex-string. Returns: A one-byte LRC bytestring (not encoded to hex-string) Algorithm from the document 'MODBUS over ...
[ "Calculate", "LRC", "for", "Modbus", "." ]
e99f4d74c83258c6039073082955ac9bed3f2155
https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L1986-L2016
train
pyhys/minimalmodbus
minimalmodbus.py
_checkMode
def _checkMode(mode): """Check that the Modbus mode is valie. Args: mode (string): The Modbus mode (MODE_RTU or MODE_ASCII) Raises: TypeError, ValueError """ if not isinstance(mode, str): raise TypeError('The {0} should be a string. Given: {1!r}'.format("mode", mode)) ...
python
def _checkMode(mode): """Check that the Modbus mode is valie. Args: mode (string): The Modbus mode (MODE_RTU or MODE_ASCII) Raises: TypeError, ValueError """ if not isinstance(mode, str): raise TypeError('The {0} should be a string. Given: {1!r}'.format("mode", mode)) ...
[ "def", "_checkMode", "(", "mode", ")", ":", "if", "not", "isinstance", "(", "mode", ",", "str", ")", ":", "raise", "TypeError", "(", "'The {0} should be a string. Given: {1!r}'", ".", "format", "(", "\"mode\"", ",", "mode", ")", ")", "if", "mode", "not", "...
Check that the Modbus mode is valie. Args: mode (string): The Modbus mode (MODE_RTU or MODE_ASCII) Raises: TypeError, ValueError
[ "Check", "that", "the", "Modbus", "mode", "is", "valie", "." ]
e99f4d74c83258c6039073082955ac9bed3f2155
https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L2019-L2034
train
pyhys/minimalmodbus
minimalmodbus.py
_checkFunctioncode
def _checkFunctioncode(functioncode, listOfAllowedValues=[]): """Check that the given functioncode is in the listOfAllowedValues. Also verifies that 1 <= function code <= 127. Args: * functioncode (int): The function code * listOfAllowedValues (list of int): Allowed values. Use *None* to b...
python
def _checkFunctioncode(functioncode, listOfAllowedValues=[]): """Check that the given functioncode is in the listOfAllowedValues. Also verifies that 1 <= function code <= 127. Args: * functioncode (int): The function code * listOfAllowedValues (list of int): Allowed values. Use *None* to b...
[ "def", "_checkFunctioncode", "(", "functioncode", ",", "listOfAllowedValues", "=", "[", "]", ")", ":", "FUNCTIONCODE_MIN", "=", "1", "FUNCTIONCODE_MAX", "=", "127", "_checkInt", "(", "functioncode", ",", "FUNCTIONCODE_MIN", ",", "FUNCTIONCODE_MAX", ",", "description...
Check that the given functioncode is in the listOfAllowedValues. Also verifies that 1 <= function code <= 127. Args: * functioncode (int): The function code * listOfAllowedValues (list of int): Allowed values. Use *None* to bypass this part of the checking. Raises: TypeError, Valu...
[ "Check", "that", "the", "given", "functioncode", "is", "in", "the", "listOfAllowedValues", "." ]
e99f4d74c83258c6039073082955ac9bed3f2155
https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L2037-L2065
train
pyhys/minimalmodbus
minimalmodbus.py
_checkResponseByteCount
def _checkResponseByteCount(payload): """Check that the number of bytes as given in the response is correct. The first byte in the payload indicates the length of the payload (first byte not counted). Args: payload (string): The payload Raises: TypeError, ValueError """ POSIT...
python
def _checkResponseByteCount(payload): """Check that the number of bytes as given in the response is correct. The first byte in the payload indicates the length of the payload (first byte not counted). Args: payload (string): The payload Raises: TypeError, ValueError """ POSIT...
[ "def", "_checkResponseByteCount", "(", "payload", ")", ":", "POSITION_FOR_GIVEN_NUMBER", "=", "0", "NUMBER_OF_BYTES_TO_SKIP", "=", "1", "_checkString", "(", "payload", ",", "minlength", "=", "1", ",", "description", "=", "'payload'", ")", "givenNumberOfDatabytes", "...
Check that the number of bytes as given in the response is correct. The first byte in the payload indicates the length of the payload (first byte not counted). Args: payload (string): The payload Raises: TypeError, ValueError
[ "Check", "that", "the", "number", "of", "bytes", "as", "given", "in", "the", "response", "is", "correct", "." ]
e99f4d74c83258c6039073082955ac9bed3f2155
https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L2100-L2124
train
pyhys/minimalmodbus
minimalmodbus.py
_checkResponseRegisterAddress
def _checkResponseRegisterAddress(payload, registeraddress): """Check that the start adress as given in the response is correct. The first two bytes in the payload holds the address value. Args: * payload (string): The payload * registeraddress (int): The register address (use decimal numb...
python
def _checkResponseRegisterAddress(payload, registeraddress): """Check that the start adress as given in the response is correct. The first two bytes in the payload holds the address value. Args: * payload (string): The payload * registeraddress (int): The register address (use decimal numb...
[ "def", "_checkResponseRegisterAddress", "(", "payload", ",", "registeraddress", ")", ":", "_checkString", "(", "payload", ",", "minlength", "=", "2", ",", "description", "=", "'payload'", ")", "_checkRegisteraddress", "(", "registeraddress", ")", "BYTERANGE_FOR_STARTA...
Check that the start adress as given in the response is correct. The first two bytes in the payload holds the address value. Args: * payload (string): The payload * registeraddress (int): The register address (use decimal numbers, not hex). Raises: TypeError, ValueError
[ "Check", "that", "the", "start", "adress", "as", "given", "in", "the", "response", "is", "correct", "." ]
e99f4d74c83258c6039073082955ac9bed3f2155
https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L2127-L2150
train
pyhys/minimalmodbus
minimalmodbus.py
_checkResponseNumberOfRegisters
def _checkResponseNumberOfRegisters(payload, numberOfRegisters): """Check that the number of written registers as given in the response is correct. The bytes 2 and 3 (zero based counting) in the payload holds the value. Args: * payload (string): The payload * numberOfRegisters (int): Numbe...
python
def _checkResponseNumberOfRegisters(payload, numberOfRegisters): """Check that the number of written registers as given in the response is correct. The bytes 2 and 3 (zero based counting) in the payload holds the value. Args: * payload (string): The payload * numberOfRegisters (int): Numbe...
[ "def", "_checkResponseNumberOfRegisters", "(", "payload", ",", "numberOfRegisters", ")", ":", "_checkString", "(", "payload", ",", "minlength", "=", "4", ",", "description", "=", "'payload'", ")", "_checkInt", "(", "numberOfRegisters", ",", "minvalue", "=", "1", ...
Check that the number of written registers as given in the response is correct. The bytes 2 and 3 (zero based counting) in the payload holds the value. Args: * payload (string): The payload * numberOfRegisters (int): Number of registers that have been written Raises: TypeError, Va...
[ "Check", "that", "the", "number", "of", "written", "registers", "as", "given", "in", "the", "response", "is", "correct", "." ]
e99f4d74c83258c6039073082955ac9bed3f2155
https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L2153-L2176
train
pyhys/minimalmodbus
minimalmodbus.py
_checkResponseWriteData
def _checkResponseWriteData(payload, writedata): """Check that the write data as given in the response is correct. The bytes 2 and 3 (zero based counting) in the payload holds the write data. Args: * payload (string): The payload * writedata (string): The data to write, length should be 2 ...
python
def _checkResponseWriteData(payload, writedata): """Check that the write data as given in the response is correct. The bytes 2 and 3 (zero based counting) in the payload holds the write data. Args: * payload (string): The payload * writedata (string): The data to write, length should be 2 ...
[ "def", "_checkResponseWriteData", "(", "payload", ",", "writedata", ")", ":", "_checkString", "(", "payload", ",", "minlength", "=", "4", ",", "description", "=", "'payload'", ")", "_checkString", "(", "writedata", ",", "minlength", "=", "2", ",", "maxlength",...
Check that the write data as given in the response is correct. The bytes 2 and 3 (zero based counting) in the payload holds the write data. Args: * payload (string): The payload * writedata (string): The data to write, length should be 2 bytes. Raises: TypeError, ValueError
[ "Check", "that", "the", "write", "data", "as", "given", "in", "the", "response", "is", "correct", "." ]
e99f4d74c83258c6039073082955ac9bed3f2155
https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L2179-L2201
train
pyhys/minimalmodbus
minimalmodbus.py
_checkString
def _checkString(inputstring, description, minlength=0, maxlength=None): """Check that the given string is valid. Args: * inputstring (string): The string to be checked * description (string): Used in error messages for the checked inputstring * minlength (int): Minimum length of the st...
python
def _checkString(inputstring, description, minlength=0, maxlength=None): """Check that the given string is valid. Args: * inputstring (string): The string to be checked * description (string): Used in error messages for the checked inputstring * minlength (int): Minimum length of the st...
[ "def", "_checkString", "(", "inputstring", ",", "description", ",", "minlength", "=", "0", ",", "maxlength", "=", "None", ")", ":", "if", "not", "isinstance", "(", "description", ",", "str", ")", ":", "raise", "TypeError", "(", "'The description should be a st...
Check that the given string is valid. Args: * inputstring (string): The string to be checked * description (string): Used in error messages for the checked inputstring * minlength (int): Minimum length of the string * maxlength (int or None): Maximum length of the string Raises...
[ "Check", "that", "the", "given", "string", "is", "valid", "." ]
e99f4d74c83258c6039073082955ac9bed3f2155
https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L2204-L2246
train
pyhys/minimalmodbus
minimalmodbus.py
_checkInt
def _checkInt(inputvalue, minvalue=None, maxvalue=None, description='inputvalue'): """Check that the given integer is valid. Args: * inputvalue (int or long): The integer to be checked * minvalue (int or long, or None): Minimum value of the integer * maxvalue (int or long, or None): Max...
python
def _checkInt(inputvalue, minvalue=None, maxvalue=None, description='inputvalue'): """Check that the given integer is valid. Args: * inputvalue (int or long): The integer to be checked * minvalue (int or long, or None): Minimum value of the integer * maxvalue (int or long, or None): Max...
[ "def", "_checkInt", "(", "inputvalue", ",", "minvalue", "=", "None", ",", "maxvalue", "=", "None", ",", "description", "=", "'inputvalue'", ")", ":", "if", "not", "isinstance", "(", "description", ",", "str", ")", ":", "raise", "TypeError", "(", "'The desc...
Check that the given integer is valid. Args: * inputvalue (int or long): The integer to be checked * minvalue (int or long, or None): Minimum value of the integer * maxvalue (int or long, or None): Maximum value of the integer * description (string): Used in error messages for the c...
[ "Check", "that", "the", "given", "integer", "is", "valid", "." ]
e99f4d74c83258c6039073082955ac9bed3f2155
https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L2249-L2276
train
pyhys/minimalmodbus
minimalmodbus.py
_checkNumerical
def _checkNumerical(inputvalue, minvalue=None, maxvalue=None, description='inputvalue'): """Check that the given numerical value is valid. Args: * inputvalue (numerical): The value to be checked. * minvalue (numerical): Minimum value Use None to skip this part of the test. * maxvalue (...
python
def _checkNumerical(inputvalue, minvalue=None, maxvalue=None, description='inputvalue'): """Check that the given numerical value is valid. Args: * inputvalue (numerical): The value to be checked. * minvalue (numerical): Minimum value Use None to skip this part of the test. * maxvalue (...
[ "def", "_checkNumerical", "(", "inputvalue", ",", "minvalue", "=", "None", ",", "maxvalue", "=", "None", ",", "description", "=", "'inputvalue'", ")", ":", "if", "not", "isinstance", "(", "description", ",", "str", ")", ":", "raise", "TypeError", "(", "'Th...
Check that the given numerical value is valid. Args: * inputvalue (numerical): The value to be checked. * minvalue (numerical): Minimum value Use None to skip this part of the test. * maxvalue (numerical): Maximum value. Use None to skip this part of the test. * description (string...
[ "Check", "that", "the", "given", "numerical", "value", "is", "valid", "." ]
e99f4d74c83258c6039073082955ac9bed3f2155
https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L2279-L2322
train
pyhys/minimalmodbus
minimalmodbus.py
_checkBool
def _checkBool(inputvalue, description='inputvalue'): """Check that the given inputvalue is a boolean. Args: * inputvalue (boolean): The value to be checked. * description (string): Used in error messages for the checked inputvalue. Raises: TypeError, ValueError """ _check...
python
def _checkBool(inputvalue, description='inputvalue'): """Check that the given inputvalue is a boolean. Args: * inputvalue (boolean): The value to be checked. * description (string): Used in error messages for the checked inputvalue. Raises: TypeError, ValueError """ _check...
[ "def", "_checkBool", "(", "inputvalue", ",", "description", "=", "'inputvalue'", ")", ":", "_checkString", "(", "description", ",", "minlength", "=", "1", ",", "description", "=", "'description string'", ")", "if", "not", "isinstance", "(", "inputvalue", ",", ...
Check that the given inputvalue is a boolean. Args: * inputvalue (boolean): The value to be checked. * description (string): Used in error messages for the checked inputvalue. Raises: TypeError, ValueError
[ "Check", "that", "the", "given", "inputvalue", "is", "a", "boolean", "." ]
e99f4d74c83258c6039073082955ac9bed3f2155
https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L2325-L2338
train
pyhys/minimalmodbus
minimalmodbus.py
_getDiagnosticString
def _getDiagnosticString(): """Generate a diagnostic string, showing the module version, the platform, current directory etc. Returns: A descriptive string. """ text = '\n## Diagnostic output from minimalmodbus ## \n\n' text += 'Minimalmodbus version: ' + __version__ + '\n' text += 'Mi...
python
def _getDiagnosticString(): """Generate a diagnostic string, showing the module version, the platform, current directory etc. Returns: A descriptive string. """ text = '\n## Diagnostic output from minimalmodbus ## \n\n' text += 'Minimalmodbus version: ' + __version__ + '\n' text += 'Mi...
[ "def", "_getDiagnosticString", "(", ")", ":", "text", "=", "'\\n## Diagnostic output from minimalmodbus ## \\n\\n'", "text", "+=", "'Minimalmodbus version: '", "+", "__version__", "+", "'\\n'", "text", "+=", "'Minimalmodbus status: '", "+", "__status__", "+", "'\\n'", "te...
Generate a diagnostic string, showing the module version, the platform, current directory etc. Returns: A descriptive string.
[ "Generate", "a", "diagnostic", "string", "showing", "the", "module", "version", "the", "platform", "current", "directory", "etc", "." ]
e99f4d74c83258c6039073082955ac9bed3f2155
https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L2513-L2550
train
pyhys/minimalmodbus
minimalmodbus.py
Instrument.read_bit
def read_bit(self, registeraddress, functioncode=2): """Read one bit from the slave. Args: * registeraddress (int): The slave register address (use decimal numbers, not hex). * functioncode (int): Modbus function code. Can be 1 or 2. Returns: The bit value 0...
python
def read_bit(self, registeraddress, functioncode=2): """Read one bit from the slave. Args: * registeraddress (int): The slave register address (use decimal numbers, not hex). * functioncode (int): Modbus function code. Can be 1 or 2. Returns: The bit value 0...
[ "def", "read_bit", "(", "self", ",", "registeraddress", ",", "functioncode", "=", "2", ")", ":", "_checkFunctioncode", "(", "functioncode", ",", "[", "1", ",", "2", "]", ")", "return", "self", ".", "_genericCommand", "(", "functioncode", ",", "registeraddres...
Read one bit from the slave. Args: * registeraddress (int): The slave register address (use decimal numbers, not hex). * functioncode (int): Modbus function code. Can be 1 or 2. Returns: The bit value 0 or 1 (int). Raises: ValueError, TypeError,...
[ "Read", "one", "bit", "from", "the", "slave", "." ]
e99f4d74c83258c6039073082955ac9bed3f2155
https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L178-L193
train
pyhys/minimalmodbus
minimalmodbus.py
Instrument.write_bit
def write_bit(self, registeraddress, value, functioncode=5): """Write one bit to the slave. Args: * registeraddress (int): The slave register address (use decimal numbers, not hex). * value (int): 0 or 1 * functioncode (int): Modbus function code. Can be 5 or 15. ...
python
def write_bit(self, registeraddress, value, functioncode=5): """Write one bit to the slave. Args: * registeraddress (int): The slave register address (use decimal numbers, not hex). * value (int): 0 or 1 * functioncode (int): Modbus function code. Can be 5 or 15. ...
[ "def", "write_bit", "(", "self", ",", "registeraddress", ",", "value", ",", "functioncode", "=", "5", ")", ":", "_checkFunctioncode", "(", "functioncode", ",", "[", "5", ",", "15", "]", ")", "_checkInt", "(", "value", ",", "minvalue", "=", "0", ",", "m...
Write one bit to the slave. Args: * registeraddress (int): The slave register address (use decimal numbers, not hex). * value (int): 0 or 1 * functioncode (int): Modbus function code. Can be 5 or 15. Returns: None Raises: ValueError,...
[ "Write", "one", "bit", "to", "the", "slave", "." ]
e99f4d74c83258c6039073082955ac9bed3f2155
https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L196-L213
train
pyhys/minimalmodbus
minimalmodbus.py
Instrument.read_register
def read_register(self, registeraddress, numberOfDecimals=0, functioncode=3, signed=False): """Read an integer from one 16-bit register in the slave, possibly scaling it. The slave register can hold integer values in the range 0 to 65535 ("Unsigned INT16"). Args: * registeraddress ...
python
def read_register(self, registeraddress, numberOfDecimals=0, functioncode=3, signed=False): """Read an integer from one 16-bit register in the slave, possibly scaling it. The slave register can hold integer values in the range 0 to 65535 ("Unsigned INT16"). Args: * registeraddress ...
[ "def", "read_register", "(", "self", ",", "registeraddress", ",", "numberOfDecimals", "=", "0", ",", "functioncode", "=", "3", ",", "signed", "=", "False", ")", ":", "_checkFunctioncode", "(", "functioncode", ",", "[", "3", ",", "4", "]", ")", "_checkInt",...
Read an integer from one 16-bit register in the slave, possibly scaling it. The slave register can hold integer values in the range 0 to 65535 ("Unsigned INT16"). Args: * registeraddress (int): The slave register address (use decimal numbers, not hex). * numberOfDecimals (int):...
[ "Read", "an", "integer", "from", "one", "16", "-", "bit", "register", "in", "the", "slave", "possibly", "scaling", "it", "." ]
e99f4d74c83258c6039073082955ac9bed3f2155
https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L216-L258
train
pyhys/minimalmodbus
minimalmodbus.py
Instrument.write_register
def write_register(self, registeraddress, value, numberOfDecimals=0, functioncode=16, signed=False): """Write an integer to one 16-bit register in the slave, possibly scaling it. The slave register can hold integer values in the range 0 to 65535 ("Unsigned INT16"). Args: * register...
python
def write_register(self, registeraddress, value, numberOfDecimals=0, functioncode=16, signed=False): """Write an integer to one 16-bit register in the slave, possibly scaling it. The slave register can hold integer values in the range 0 to 65535 ("Unsigned INT16"). Args: * register...
[ "def", "write_register", "(", "self", ",", "registeraddress", ",", "value", ",", "numberOfDecimals", "=", "0", ",", "functioncode", "=", "16", ",", "signed", "=", "False", ")", ":", "_checkFunctioncode", "(", "functioncode", ",", "[", "6", ",", "16", "]", ...
Write an integer to one 16-bit register in the slave, possibly scaling it. The slave register can hold integer values in the range 0 to 65535 ("Unsigned INT16"). Args: * registeraddress (int): The slave register address (use decimal numbers, not hex). * value (int or float): T...
[ "Write", "an", "integer", "to", "one", "16", "-", "bit", "register", "in", "the", "slave", "possibly", "scaling", "it", "." ]
e99f4d74c83258c6039073082955ac9bed3f2155
https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L261-L296
train
pyhys/minimalmodbus
minimalmodbus.py
Instrument.read_float
def read_float(self, registeraddress, functioncode=3, numberOfRegisters=2): """Read a floating point number from the slave. Floats are stored in two or more consecutive 16-bit registers in the slave. The encoding is according to the standard IEEE 754. There are differences in the byte ...
python
def read_float(self, registeraddress, functioncode=3, numberOfRegisters=2): """Read a floating point number from the slave. Floats are stored in two or more consecutive 16-bit registers in the slave. The encoding is according to the standard IEEE 754. There are differences in the byte ...
[ "def", "read_float", "(", "self", ",", "registeraddress", ",", "functioncode", "=", "3", ",", "numberOfRegisters", "=", "2", ")", ":", "_checkFunctioncode", "(", "functioncode", ",", "[", "3", ",", "4", "]", ")", "_checkInt", "(", "numberOfRegisters", ",", ...
Read a floating point number from the slave. Floats are stored in two or more consecutive 16-bit registers in the slave. The encoding is according to the standard IEEE 754. There are differences in the byte order used by different manufacturers. A floating point value of 1.0 is encoded...
[ "Read", "a", "floating", "point", "number", "from", "the", "slave", "." ]
e99f4d74c83258c6039073082955ac9bed3f2155
https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L358-L392
train
pyhys/minimalmodbus
minimalmodbus.py
Instrument.write_float
def write_float(self, registeraddress, value, numberOfRegisters=2): """Write a floating point number to the slave. Floats are stored in two or more consecutive 16-bit registers in the slave. Uses Modbus function code 16. For discussion on precision, number of registers and on byte ord...
python
def write_float(self, registeraddress, value, numberOfRegisters=2): """Write a floating point number to the slave. Floats are stored in two or more consecutive 16-bit registers in the slave. Uses Modbus function code 16. For discussion on precision, number of registers and on byte ord...
[ "def", "write_float", "(", "self", ",", "registeraddress", ",", "value", ",", "numberOfRegisters", "=", "2", ")", ":", "_checkNumerical", "(", "value", ",", "description", "=", "'input value'", ")", "_checkInt", "(", "numberOfRegisters", ",", "minvalue", "=", ...
Write a floating point number to the slave. Floats are stored in two or more consecutive 16-bit registers in the slave. Uses Modbus function code 16. For discussion on precision, number of registers and on byte order, see :meth:`.read_float`. Args: * registeraddress (int)...
[ "Write", "a", "floating", "point", "number", "to", "the", "slave", "." ]
e99f4d74c83258c6039073082955ac9bed3f2155
https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L395-L419
train
pyhys/minimalmodbus
minimalmodbus.py
Instrument.read_string
def read_string(self, registeraddress, numberOfRegisters=16, functioncode=3): """Read a string from the slave. Each 16-bit register in the slave are interpreted as two characters (1 byte = 8 bits). For example 16 consecutive registers can hold 32 characters (32 bytes). Args: ...
python
def read_string(self, registeraddress, numberOfRegisters=16, functioncode=3): """Read a string from the slave. Each 16-bit register in the slave are interpreted as two characters (1 byte = 8 bits). For example 16 consecutive registers can hold 32 characters (32 bytes). Args: ...
[ "def", "read_string", "(", "self", ",", "registeraddress", ",", "numberOfRegisters", "=", "16", ",", "functioncode", "=", "3", ")", ":", "_checkFunctioncode", "(", "functioncode", ",", "[", "3", ",", "4", "]", ")", "_checkInt", "(", "numberOfRegisters", ",",...
Read a string from the slave. Each 16-bit register in the slave are interpreted as two characters (1 byte = 8 bits). For example 16 consecutive registers can hold 32 characters (32 bytes). Args: * registeraddress (int): The slave register start address (use decimal numbers, not hex...
[ "Read", "a", "string", "from", "the", "slave", "." ]
e99f4d74c83258c6039073082955ac9bed3f2155
https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L422-L443
train
pyhys/minimalmodbus
minimalmodbus.py
Instrument.write_string
def write_string(self, registeraddress, textstring, numberOfRegisters=16): """Write a string to the slave. Each 16-bit register in the slave are interpreted as two characters (1 byte = 8 bits). For example 16 consecutive registers can hold 32 characters (32 bytes). Uses Modbus function...
python
def write_string(self, registeraddress, textstring, numberOfRegisters=16): """Write a string to the slave. Each 16-bit register in the slave are interpreted as two characters (1 byte = 8 bits). For example 16 consecutive registers can hold 32 characters (32 bytes). Uses Modbus function...
[ "def", "write_string", "(", "self", ",", "registeraddress", ",", "textstring", ",", "numberOfRegisters", "=", "16", ")", ":", "_checkInt", "(", "numberOfRegisters", ",", "minvalue", "=", "1", ",", "description", "=", "'number of registers for write string'", ")", ...
Write a string to the slave. Each 16-bit register in the slave are interpreted as two characters (1 byte = 8 bits). For example 16 consecutive registers can hold 32 characters (32 bytes). Uses Modbus function code 16. Args: * registeraddress (int): The slave register start...
[ "Write", "a", "string", "to", "the", "slave", "." ]
e99f4d74c83258c6039073082955ac9bed3f2155
https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L446-L472
train
pyhys/minimalmodbus
minimalmodbus.py
Instrument.write_registers
def write_registers(self, registeraddress, values): """Write integers to 16-bit registers in the slave. The slave register can hold integer values in the range 0 to 65535 ("Unsigned INT16"). Uses Modbus function code 16. The number of registers that will be written is defined by the l...
python
def write_registers(self, registeraddress, values): """Write integers to 16-bit registers in the slave. The slave register can hold integer values in the range 0 to 65535 ("Unsigned INT16"). Uses Modbus function code 16. The number of registers that will be written is defined by the l...
[ "def", "write_registers", "(", "self", ",", "registeraddress", ",", "values", ")", ":", "if", "not", "isinstance", "(", "values", ",", "list", ")", ":", "raise", "TypeError", "(", "'The \"values parameter\" must be a list. Given: {0!r}'", ".", "format", "(", "valu...
Write integers to 16-bit registers in the slave. The slave register can hold integer values in the range 0 to 65535 ("Unsigned INT16"). Uses Modbus function code 16. The number of registers that will be written is defined by the length of the ``values`` list. Args: * regi...
[ "Write", "integers", "to", "16", "-", "bit", "registers", "in", "the", "slave", "." ]
e99f4d74c83258c6039073082955ac9bed3f2155
https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L501-L529
train
pyhys/minimalmodbus
minimalmodbus.py
Instrument._communicate
def _communicate(self, request, number_of_bytes_to_read): """Talk to the slave via a serial port. Args: request (str): The raw request that is to be sent to the slave. number_of_bytes_to_read (int): number of bytes to read Returns: The raw data (string) retu...
python
def _communicate(self, request, number_of_bytes_to_read): """Talk to the slave via a serial port. Args: request (str): The raw request that is to be sent to the slave. number_of_bytes_to_read (int): number of bytes to read Returns: The raw data (string) retu...
[ "def", "_communicate", "(", "self", ",", "request", ",", "number_of_bytes_to_read", ")", ":", "_checkString", "(", "request", ",", "minlength", "=", "1", ",", "description", "=", "'request'", ")", "_checkInt", "(", "number_of_bytes_to_read", ")", "if", "self", ...
Talk to the slave via a serial port. Args: request (str): The raw request that is to be sent to the slave. number_of_bytes_to_read (int): number of bytes to read Returns: The raw data (string) returned from the slave. Raises: TypeError, ValueErr...
[ "Talk", "to", "the", "slave", "via", "a", "serial", "port", "." ]
e99f4d74c83258c6039073082955ac9bed3f2155
https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L802-L932
train
TaylorSMarks/playsound
playsound.py
_playsoundWin
def _playsoundWin(sound, block = True): ''' Utilizes windll.winmm. Tested and known to work with MP3 and WAVE on Windows 7 with Python 2.7. Probably works with more file formats. Probably works on Windows XP thru Windows 10. Probably works with all versions of Python. Inspired by (but not copie...
python
def _playsoundWin(sound, block = True): ''' Utilizes windll.winmm. Tested and known to work with MP3 and WAVE on Windows 7 with Python 2.7. Probably works with more file formats. Probably works on Windows XP thru Windows 10. Probably works with all versions of Python. Inspired by (but not copie...
[ "def", "_playsoundWin", "(", "sound", ",", "block", "=", "True", ")", ":", "from", "ctypes", "import", "c_buffer", ",", "windll", "from", "random", "import", "random", "from", "time", "import", "sleep", "from", "sys", "import", "getfilesystemencoding", "def", ...
Utilizes windll.winmm. Tested and known to work with MP3 and WAVE on Windows 7 with Python 2.7. Probably works with more file formats. Probably works on Windows XP thru Windows 10. Probably works with all versions of Python. Inspired by (but not copied from) Michael Gundlach <gundlach@gmail.com>'s mp3p...
[ "Utilizes", "windll", ".", "winmm", ".", "Tested", "and", "known", "to", "work", "with", "MP3", "and", "WAVE", "on", "Windows", "7", "with", "Python", "2", ".", "7", ".", "Probably", "works", "with", "more", "file", "formats", ".", "Probably", "works", ...
907f1fe73375a2156f7e0900c4b42c0a60fa1d00
https://github.com/TaylorSMarks/playsound/blob/907f1fe73375a2156f7e0900c4b42c0a60fa1d00/playsound.py#L4-L41
train
TaylorSMarks/playsound
playsound.py
_playsoundOSX
def _playsoundOSX(sound, block = True): ''' Utilizes AppKit.NSSound. Tested and known to work with MP3 and WAVE on OS X 10.11 with Python 2.7. Probably works with anything QuickTime supports. Probably works on OS X 10.5 and newer. Probably works with all versions of Python. Inspired by (but not...
python
def _playsoundOSX(sound, block = True): ''' Utilizes AppKit.NSSound. Tested and known to work with MP3 and WAVE on OS X 10.11 with Python 2.7. Probably works with anything QuickTime supports. Probably works on OS X 10.5 and newer. Probably works with all versions of Python. Inspired by (but not...
[ "def", "_playsoundOSX", "(", "sound", ",", "block", "=", "True", ")", ":", "from", "AppKit", "import", "NSSound", "from", "Foundation", "import", "NSURL", "from", "time", "import", "sleep", "if", "'://'", "not", "in", "sound", ":", "if", "not", "sound", ...
Utilizes AppKit.NSSound. Tested and known to work with MP3 and WAVE on OS X 10.11 with Python 2.7. Probably works with anything QuickTime supports. Probably works on OS X 10.5 and newer. Probably works with all versions of Python. Inspired by (but not copied from) Aaron's Stack Overflow answer here: ...
[ "Utilizes", "AppKit", ".", "NSSound", ".", "Tested", "and", "known", "to", "work", "with", "MP3", "and", "WAVE", "on", "OS", "X", "10", ".", "11", "with", "Python", "2", ".", "7", ".", "Probably", "works", "with", "anything", "QuickTime", "supports", "...
907f1fe73375a2156f7e0900c4b42c0a60fa1d00
https://github.com/TaylorSMarks/playsound/blob/907f1fe73375a2156f7e0900c4b42c0a60fa1d00/playsound.py#L43-L71
train
TaylorSMarks/playsound
playsound.py
_playsoundNix
def _playsoundNix(sound, block=True): """Play a sound using GStreamer. Inspired by this: https://gstreamer.freedesktop.org/documentation/tutorials/playback/playbin-usage.html """ if not block: raise NotImplementedError( "block=False cannot be used on this platform yet") # p...
python
def _playsoundNix(sound, block=True): """Play a sound using GStreamer. Inspired by this: https://gstreamer.freedesktop.org/documentation/tutorials/playback/playbin-usage.html """ if not block: raise NotImplementedError( "block=False cannot be used on this platform yet") # p...
[ "def", "_playsoundNix", "(", "sound", ",", "block", "=", "True", ")", ":", "if", "not", "block", ":", "raise", "NotImplementedError", "(", "\"block=False cannot be used on this platform yet\"", ")", "import", "os", "try", ":", "from", "urllib", ".", "request", "...
Play a sound using GStreamer. Inspired by this: https://gstreamer.freedesktop.org/documentation/tutorials/playback/playbin-usage.html
[ "Play", "a", "sound", "using", "GStreamer", "." ]
907f1fe73375a2156f7e0900c4b42c0a60fa1d00
https://github.com/TaylorSMarks/playsound/blob/907f1fe73375a2156f7e0900c4b42c0a60fa1d00/playsound.py#L73-L112
train
mfitzp/padua
padua/filters.py
remove_rows_matching
def remove_rows_matching(df, column, match): """ Return a ``DataFrame`` with rows where `column` values match `match` are removed. The selected `column` series of values from the supplied Pandas ``DataFrame`` is compared to `match`, and those rows that match are removed from the DataFrame. :param ...
python
def remove_rows_matching(df, column, match): """ Return a ``DataFrame`` with rows where `column` values match `match` are removed. The selected `column` series of values from the supplied Pandas ``DataFrame`` is compared to `match`, and those rows that match are removed from the DataFrame. :param ...
[ "def", "remove_rows_matching", "(", "df", ",", "column", ",", "match", ")", ":", "df", "=", "df", ".", "copy", "(", ")", "mask", "=", "df", "[", "column", "]", ".", "values", "!=", "match", "return", "df", ".", "iloc", "[", "mask", ",", ":", "]" ...
Return a ``DataFrame`` with rows where `column` values match `match` are removed. The selected `column` series of values from the supplied Pandas ``DataFrame`` is compared to `match`, and those rows that match are removed from the DataFrame. :param df: Pandas ``DataFrame`` :param column: Column indexe...
[ "Return", "a", "DataFrame", "with", "rows", "where", "column", "values", "match", "match", "are", "removed", "." ]
8b14bf4d2f895da6aea5d7885d409315bd303ec6
https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/filters.py#L4-L18
train
mfitzp/padua
padua/filters.py
remove_rows_containing
def remove_rows_containing(df, column, match): """ Return a ``DataFrame`` with rows where `column` values containing `match` are removed. The selected `column` series of values from the supplied Pandas ``DataFrame`` is compared to `match`, and those rows that contain it are removed from the DataFrame. ...
python
def remove_rows_containing(df, column, match): """ Return a ``DataFrame`` with rows where `column` values containing `match` are removed. The selected `column` series of values from the supplied Pandas ``DataFrame`` is compared to `match`, and those rows that contain it are removed from the DataFrame. ...
[ "def", "remove_rows_containing", "(", "df", ",", "column", ",", "match", ")", ":", "df", "=", "df", ".", "copy", "(", ")", "mask", "=", "[", "match", "not", "in", "str", "(", "v", ")", "for", "v", "in", "df", "[", "column", "]", ".", "values", ...
Return a ``DataFrame`` with rows where `column` values containing `match` are removed. The selected `column` series of values from the supplied Pandas ``DataFrame`` is compared to `match`, and those rows that contain it are removed from the DataFrame. :param df: Pandas ``DataFrame`` :param column: Col...
[ "Return", "a", "DataFrame", "with", "rows", "where", "column", "values", "containing", "match", "are", "removed", "." ]
8b14bf4d2f895da6aea5d7885d409315bd303ec6
https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/filters.py#L21-L35
train
mfitzp/padua
padua/filters.py
filter_localization_probability
def filter_localization_probability(df, threshold=0.75): """ Remove rows with a localization probability below 0.75 Return a ``DataFrame`` where the rows with a value < `threshold` (default 0.75) in column 'Localization prob' are removed. Filters data to remove poorly localized peptides (non Class-I by...
python
def filter_localization_probability(df, threshold=0.75): """ Remove rows with a localization probability below 0.75 Return a ``DataFrame`` where the rows with a value < `threshold` (default 0.75) in column 'Localization prob' are removed. Filters data to remove poorly localized peptides (non Class-I by...
[ "def", "filter_localization_probability", "(", "df", ",", "threshold", "=", "0.75", ")", ":", "df", "=", "df", ".", "copy", "(", ")", "localization_probability_mask", "=", "df", "[", "'Localization prob'", "]", ".", "values", ">=", "threshold", "return", "df",...
Remove rows with a localization probability below 0.75 Return a ``DataFrame`` where the rows with a value < `threshold` (default 0.75) in column 'Localization prob' are removed. Filters data to remove poorly localized peptides (non Class-I by default). :param df: Pandas ``DataFrame`` :param threshold:...
[ "Remove", "rows", "with", "a", "localization", "probability", "below", "0", ".", "75" ]
8b14bf4d2f895da6aea5d7885d409315bd303ec6
https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/filters.py#L77-L90
train
mfitzp/padua
padua/filters.py
minimum_valid_values_in_any_group
def minimum_valid_values_in_any_group(df, levels=None, n=1, invalid=np.nan): """ Filter ``DataFrame`` by at least n valid values in at least one group. Taking a Pandas ``DataFrame`` with a ``MultiIndex`` column index, filters rows to remove rows where there are less than `n` valid values per group. Gro...
python
def minimum_valid_values_in_any_group(df, levels=None, n=1, invalid=np.nan): """ Filter ``DataFrame`` by at least n valid values in at least one group. Taking a Pandas ``DataFrame`` with a ``MultiIndex`` column index, filters rows to remove rows where there are less than `n` valid values per group. Gro...
[ "def", "minimum_valid_values_in_any_group", "(", "df", ",", "levels", "=", "None", ",", "n", "=", "1", ",", "invalid", "=", "np", ".", "nan", ")", ":", "df", "=", "df", ".", "copy", "(", ")", "if", "levels", "is", "None", ":", "if", "'Group'", "in"...
Filter ``DataFrame`` by at least n valid values in at least one group. Taking a Pandas ``DataFrame`` with a ``MultiIndex`` column index, filters rows to remove rows where there are less than `n` valid values per group. Groups are defined by the `levels` parameter indexing into the column index. For example...
[ "Filter", "DataFrame", "by", "at", "least", "n", "valid", "values", "in", "at", "least", "one", "group", "." ]
8b14bf4d2f895da6aea5d7885d409315bd303ec6
https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/filters.py#L93-L129
train
mfitzp/padua
padua/filters.py
search
def search(df, match, columns=['Proteins','Protein names','Gene names']): """ Search for a given string in a set of columns in a processed ``DataFrame``. Returns a filtered ``DataFrame`` where `match` is contained in one of the `columns`. :param df: Pandas ``DataFrame`` :param match: ``str`` to se...
python
def search(df, match, columns=['Proteins','Protein names','Gene names']): """ Search for a given string in a set of columns in a processed ``DataFrame``. Returns a filtered ``DataFrame`` where `match` is contained in one of the `columns`. :param df: Pandas ``DataFrame`` :param match: ``str`` to se...
[ "def", "search", "(", "df", ",", "match", ",", "columns", "=", "[", "'Proteins'", ",", "'Protein names'", ",", "'Gene names'", "]", ")", ":", "df", "=", "df", ".", "copy", "(", ")", "dft", "=", "df", ".", "reset_index", "(", ")", "mask", "=", "np",...
Search for a given string in a set of columns in a processed ``DataFrame``. Returns a filtered ``DataFrame`` where `match` is contained in one of the `columns`. :param df: Pandas ``DataFrame`` :param match: ``str`` to search for in columns :param columns: ``list`` of ``str`` to search for match :r...
[ "Search", "for", "a", "given", "string", "in", "a", "set", "of", "columns", "in", "a", "processed", "DataFrame", "." ]
8b14bf4d2f895da6aea5d7885d409315bd303ec6
https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/filters.py#L132-L152
train
mfitzp/padua
padua/filters.py
filter_select_columns_intensity
def filter_select_columns_intensity(df, prefix, columns): """ Filter dataframe to include specified columns, retaining any Intensity columns. """ # Note: I use %s.+ (not %s.*) so it forces a match with the prefix string, ONLY if it is followed by something. return df.filter(regex='^(%s.+|%s)$' % (pr...
python
def filter_select_columns_intensity(df, prefix, columns): """ Filter dataframe to include specified columns, retaining any Intensity columns. """ # Note: I use %s.+ (not %s.*) so it forces a match with the prefix string, ONLY if it is followed by something. return df.filter(regex='^(%s.+|%s)$' % (pr...
[ "def", "filter_select_columns_intensity", "(", "df", ",", "prefix", ",", "columns", ")", ":", "return", "df", ".", "filter", "(", "regex", "=", "'^(%s.+|%s)$'", "%", "(", "prefix", ",", "'|'", ".", "join", "(", "columns", ")", ")", ")" ]
Filter dataframe to include specified columns, retaining any Intensity columns.
[ "Filter", "dataframe", "to", "include", "specified", "columns", "retaining", "any", "Intensity", "columns", "." ]
8b14bf4d2f895da6aea5d7885d409315bd303ec6
https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/filters.py#L163-L168
train
mfitzp/padua
padua/filters.py
filter_intensity
def filter_intensity(df, label="", with_multiplicity=False): """ Filter to include only the Intensity values with optional specified label, excluding other Intensity measurements, but retaining all other columns. """ label += ".*__\d" if with_multiplicity else "" dft = df.filter(regex="^(?!Int...
python
def filter_intensity(df, label="", with_multiplicity=False): """ Filter to include only the Intensity values with optional specified label, excluding other Intensity measurements, but retaining all other columns. """ label += ".*__\d" if with_multiplicity else "" dft = df.filter(regex="^(?!Int...
[ "def", "filter_intensity", "(", "df", ",", "label", "=", "\"\"", ",", "with_multiplicity", "=", "False", ")", ":", "label", "+=", "\".*__\\d\"", "if", "with_multiplicity", "else", "\"\"", "dft", "=", "df", ".", "filter", "(", "regex", "=", "\"^(?!Intensity)....
Filter to include only the Intensity values with optional specified label, excluding other Intensity measurements, but retaining all other columns.
[ "Filter", "to", "include", "only", "the", "Intensity", "values", "with", "optional", "specified", "label", "excluding", "other", "Intensity", "measurements", "but", "retaining", "all", "other", "columns", "." ]
8b14bf4d2f895da6aea5d7885d409315bd303ec6
https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/filters.py#L177-L187
train
mfitzp/padua
padua/filters.py
filter_ratio
def filter_ratio(df, label="", with_multiplicity=False): """ Filter to include only the Ratio values with optional specified label, excluding other Intensity measurements, but retaining all other columns. """ label += ".*__\d" if with_multiplicity else "" dft = df.filter(regex="^(?!Ratio).*$") ...
python
def filter_ratio(df, label="", with_multiplicity=False): """ Filter to include only the Ratio values with optional specified label, excluding other Intensity measurements, but retaining all other columns. """ label += ".*__\d" if with_multiplicity else "" dft = df.filter(regex="^(?!Ratio).*$") ...
[ "def", "filter_ratio", "(", "df", ",", "label", "=", "\"\"", ",", "with_multiplicity", "=", "False", ")", ":", "label", "+=", "\".*__\\d\"", "if", "with_multiplicity", "else", "\"\"", "dft", "=", "df", ".", "filter", "(", "regex", "=", "\"^(?!Ratio).*$\"", ...
Filter to include only the Ratio values with optional specified label, excluding other Intensity measurements, but retaining all other columns.
[ "Filter", "to", "include", "only", "the", "Ratio", "values", "with", "optional", "specified", "label", "excluding", "other", "Intensity", "measurements", "but", "retaining", "all", "other", "columns", "." ]
8b14bf4d2f895da6aea5d7885d409315bd303ec6
https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/filters.py#L201-L211
train
mfitzp/padua
padua/io.py
read_perseus
def read_perseus(f): """ Load a Perseus processed data table :param f: Source file :return: Pandas dataframe of imported data """ df = pd.read_csv(f, delimiter='\t', header=[0,1,2,3], low_memory=False) df.columns = pd.MultiIndex.from_tuples([(x,) for x in df.columns.get_level_values(0)]) ...
python
def read_perseus(f): """ Load a Perseus processed data table :param f: Source file :return: Pandas dataframe of imported data """ df = pd.read_csv(f, delimiter='\t', header=[0,1,2,3], low_memory=False) df.columns = pd.MultiIndex.from_tuples([(x,) for x in df.columns.get_level_values(0)]) ...
[ "def", "read_perseus", "(", "f", ")", ":", "df", "=", "pd", ".", "read_csv", "(", "f", ",", "delimiter", "=", "'\\t'", ",", "header", "=", "[", "0", ",", "1", ",", "2", ",", "3", "]", ",", "low_memory", "=", "False", ")", "df", ".", "columns", ...
Load a Perseus processed data table :param f: Source file :return: Pandas dataframe of imported data
[ "Load", "a", "Perseus", "processed", "data", "table" ]
8b14bf4d2f895da6aea5d7885d409315bd303ec6
https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/io.py#L21-L30
train
mfitzp/padua
padua/io.py
write_perseus
def write_perseus(f, df): """ Export a dataframe to Perseus; recreating the format :param f: :param df: :return: """ ### Generate the Perseus like type index FIELD_TYPE_MAP = { 'Amino acid':'C', 'Charge':'C', 'Reverse':'C', 'Potential contaminant':'C', ...
python
def write_perseus(f, df): """ Export a dataframe to Perseus; recreating the format :param f: :param df: :return: """ ### Generate the Perseus like type index FIELD_TYPE_MAP = { 'Amino acid':'C', 'Charge':'C', 'Reverse':'C', 'Potential contaminant':'C', ...
[ "def", "write_perseus", "(", "f", ",", "df", ")", ":", "FIELD_TYPE_MAP", "=", "{", "'Amino acid'", ":", "'C'", ",", "'Charge'", ":", "'C'", ",", "'Reverse'", ":", "'C'", ",", "'Potential contaminant'", ":", "'C'", ",", "'Multiplicity'", ":", "'C'", ",", ...
Export a dataframe to Perseus; recreating the format :param f: :param df: :return:
[ "Export", "a", "dataframe", "to", "Perseus", ";", "recreating", "the", "format" ]
8b14bf4d2f895da6aea5d7885d409315bd303ec6
https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/io.py#L33-L82
train
mfitzp/padua
padua/io.py
write_phosphopath_ratio
def write_phosphopath_ratio(df, f, a, *args, **kwargs): """ Write out the data frame ratio between two groups protein-Rsite-multiplicity-timepoint ID Ratio Q13619-S10-1-1 0.5 Q9H3Z4-S10-1-1 0.502 Q6GQQ9-S100-1-1 0.504 Q86YP4-S100-1-1 0.506 Q9H307-S100-1-1 0.508 Q8NEY1-S1000-1-1 0...
python
def write_phosphopath_ratio(df, f, a, *args, **kwargs): """ Write out the data frame ratio between two groups protein-Rsite-multiplicity-timepoint ID Ratio Q13619-S10-1-1 0.5 Q9H3Z4-S10-1-1 0.502 Q6GQQ9-S100-1-1 0.504 Q86YP4-S100-1-1 0.506 Q9H307-S100-1-1 0.508 Q8NEY1-S1000-1-1 0...
[ "def", "write_phosphopath_ratio", "(", "df", ",", "f", ",", "a", ",", "*", "args", ",", "**", "kwargs", ")", ":", "timepoint_idx", "=", "kwargs", ".", "get", "(", "'timepoint_idx'", ",", "None", ")", "proteins", "=", "[", "get_protein_id", "(", "k", ")...
Write out the data frame ratio between two groups protein-Rsite-multiplicity-timepoint ID Ratio Q13619-S10-1-1 0.5 Q9H3Z4-S10-1-1 0.502 Q6GQQ9-S100-1-1 0.504 Q86YP4-S100-1-1 0.506 Q9H307-S100-1-1 0.508 Q8NEY1-S1000-1-1 0.51 Q13541-S101-1-1 0.512 O95785-S1012-2-1 0.514 O95785-...
[ "Write", "out", "the", "data", "frame", "ratio", "between", "two", "groups", "protein", "-", "Rsite", "-", "multiplicity", "-", "timepoint", "ID", "Ratio", "Q13619", "-", "S10", "-", "1", "-", "1", "0", ".", "5", "Q9H3Z4", "-", "S10", "-", "1", "-", ...
8b14bf4d2f895da6aea5d7885d409315bd303ec6
https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/io.py#L129-L185
train
mfitzp/padua
padua/io.py
write_r
def write_r(df, f, sep=",", index_join="@", columns_join="."): """ Export dataframe in a format easily importable to R Index fields are joined with "@" and column fields by "." by default. :param df: :param f: :param index_join: :param columns_join: :return: """ df = df.copy() ...
python
def write_r(df, f, sep=",", index_join="@", columns_join="."): """ Export dataframe in a format easily importable to R Index fields are joined with "@" and column fields by "." by default. :param df: :param f: :param index_join: :param columns_join: :return: """ df = df.copy() ...
[ "def", "write_r", "(", "df", ",", "f", ",", "sep", "=", "\",\"", ",", "index_join", "=", "\"@\"", ",", "columns_join", "=", "\".\"", ")", ":", "df", "=", "df", ".", "copy", "(", ")", "df", ".", "index", "=", "[", "\"@\"", ".", "join", "(", "[",...
Export dataframe in a format easily importable to R Index fields are joined with "@" and column fields by "." by default. :param df: :param f: :param index_join: :param columns_join: :return:
[ "Export", "dataframe", "in", "a", "format", "easily", "importable", "to", "R" ]
8b14bf4d2f895da6aea5d7885d409315bd303ec6
https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/io.py#L188-L203
train
mfitzp/padua
padua/imputation.py
gaussian
def gaussian(df, width=0.3, downshift=-1.8, prefix=None): """ Impute missing values by drawing from a normal distribution :param df: :param width: Scale factor for the imputed distribution relative to the standard deviation of measured values. Can be a single number or list of one per column. :para...
python
def gaussian(df, width=0.3, downshift=-1.8, prefix=None): """ Impute missing values by drawing from a normal distribution :param df: :param width: Scale factor for the imputed distribution relative to the standard deviation of measured values. Can be a single number or list of one per column. :para...
[ "def", "gaussian", "(", "df", ",", "width", "=", "0.3", ",", "downshift", "=", "-", "1.8", ",", "prefix", "=", "None", ")", ":", "df", "=", "df", ".", "copy", "(", ")", "imputed", "=", "df", ".", "isnull", "(", ")", "if", "prefix", ":", "mask",...
Impute missing values by drawing from a normal distribution :param df: :param width: Scale factor for the imputed distribution relative to the standard deviation of measured values. Can be a single number or list of one per column. :param downshift: Shift the imputed values down, in units of std. dev. Can ...
[ "Impute", "missing", "values", "by", "drawing", "from", "a", "normal", "distribution" ]
8b14bf4d2f895da6aea5d7885d409315bd303ec6
https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/imputation.py#L14-L63
train
mfitzp/padua
padua/visualize.py
_pca_scores
def _pca_scores( scores, pc1=0, pc2=1, fcol=None, ecol=None, marker='o', markersize=30, label_scores=None, show_covariance_ellipse=True, optimize_label_iter=OPTIMIZE_LABEL_ITER_DEFAULT, **kwargs ): """ Plot a scores plot...
python
def _pca_scores( scores, pc1=0, pc2=1, fcol=None, ecol=None, marker='o', markersize=30, label_scores=None, show_covariance_ellipse=True, optimize_label_iter=OPTIMIZE_LABEL_ITER_DEFAULT, **kwargs ): """ Plot a scores plot...
[ "def", "_pca_scores", "(", "scores", ",", "pc1", "=", "0", ",", "pc2", "=", "1", ",", "fcol", "=", "None", ",", "ecol", "=", "None", ",", "marker", "=", "'o'", ",", "markersize", "=", "30", ",", "label_scores", "=", "None", ",", "show_covariance_elli...
Plot a scores plot for two principal components as AxB scatter plot. Returns the plotted axis. :param scores: DataFrame containing scores :param pc1: Column indexer into scores for PC1 :param pc2: Column indexer into scores for PC2 :param fcol: Face (fill) color definition :param ecol: Edge co...
[ "Plot", "a", "scores", "plot", "for", "two", "principal", "components", "as", "AxB", "scatter", "plot", "." ]
8b14bf4d2f895da6aea5d7885d409315bd303ec6
https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/visualize.py#L117-L200
train
mfitzp/padua
padua/visualize.py
modifiedaminoacids
def modifiedaminoacids(df, kind='pie'): """ Generate a plot of relative numbers of modified amino acids in source DataFrame. Plot a pie or bar chart showing the number and percentage of modified amino acids in the supplied data frame. The amino acids displayed will be determined from the supplied d...
python
def modifiedaminoacids(df, kind='pie'): """ Generate a plot of relative numbers of modified amino acids in source DataFrame. Plot a pie or bar chart showing the number and percentage of modified amino acids in the supplied data frame. The amino acids displayed will be determined from the supplied d...
[ "def", "modifiedaminoacids", "(", "df", ",", "kind", "=", "'pie'", ")", ":", "colors", "=", "[", "'#6baed6'", ",", "'#c6dbef'", ",", "'#bdbdbd'", "]", "total_aas", ",", "quants", "=", "analysis", ".", "modifiedaminoacids", "(", "df", ")", "df", "=", "pd"...
Generate a plot of relative numbers of modified amino acids in source DataFrame. Plot a pie or bar chart showing the number and percentage of modified amino acids in the supplied data frame. The amino acids displayed will be determined from the supplied data/modification type. :param df: processed Dat...
[ "Generate", "a", "plot", "of", "relative", "numbers", "of", "modified", "amino", "acids", "in", "source", "DataFrame", "." ]
8b14bf4d2f895da6aea5d7885d409315bd303ec6
https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/visualize.py#L697-L748
train
mfitzp/padua
padua/visualize.py
venn
def venn(df1, df2, df3=None, labels=None, ix1=None, ix2=None, ix3=None, return_intersection=False, fcols=None): """ Plot a 2 or 3-part venn diagram showing the overlap between 2 or 3 pandas DataFrames. Provided with two or three Pandas DataFrames, this will return a venn diagram showing the overlap calcula...
python
def venn(df1, df2, df3=None, labels=None, ix1=None, ix2=None, ix3=None, return_intersection=False, fcols=None): """ Plot a 2 or 3-part venn diagram showing the overlap between 2 or 3 pandas DataFrames. Provided with two or three Pandas DataFrames, this will return a venn diagram showing the overlap calcula...
[ "def", "venn", "(", "df1", ",", "df2", ",", "df3", "=", "None", ",", "labels", "=", "None", ",", "ix1", "=", "None", ",", "ix2", "=", "None", ",", "ix3", "=", "None", ",", "return_intersection", "=", "False", ",", "fcols", "=", "None", ")", ":", ...
Plot a 2 or 3-part venn diagram showing the overlap between 2 or 3 pandas DataFrames. Provided with two or three Pandas DataFrames, this will return a venn diagram showing the overlap calculated between the DataFrame indexes provided as ix1, ix2, ix3. Labels for each DataFrame can be provided as a list in the ...
[ "Plot", "a", "2", "or", "3", "-", "part", "venn", "diagram", "showing", "the", "overlap", "between", "2", "or", "3", "pandas", "DataFrames", "." ]
8b14bf4d2f895da6aea5d7885d409315bd303ec6
https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/visualize.py#L979-L1033
train
mfitzp/padua
padua/visualize.py
sitespeptidesproteins
def sitespeptidesproteins(df, labels=None, colors=None, site_localization_probability=0.75): """ Plot the number of sites, peptides and proteins in the dataset. Generates a plot with sites, peptides and proteins displayed hierarchically in chevrons. The site count is limited to Class I (<=0.75 site loc...
python
def sitespeptidesproteins(df, labels=None, colors=None, site_localization_probability=0.75): """ Plot the number of sites, peptides and proteins in the dataset. Generates a plot with sites, peptides and proteins displayed hierarchically in chevrons. The site count is limited to Class I (<=0.75 site loc...
[ "def", "sitespeptidesproteins", "(", "df", ",", "labels", "=", "None", ",", "colors", "=", "None", ",", "site_localization_probability", "=", "0.75", ")", ":", "fig", "=", "plt", ".", "figure", "(", "figsize", "=", "(", "4", ",", "6", ")", ")", "ax", ...
Plot the number of sites, peptides and proteins in the dataset. Generates a plot with sites, peptides and proteins displayed hierarchically in chevrons. The site count is limited to Class I (<=0.75 site localization probability) by default but may be altered using the `site_localization_probability` parame...
[ "Plot", "the", "number", "of", "sites", "peptides", "and", "proteins", "in", "the", "dataset", "." ]
8b14bf4d2f895da6aea5d7885d409315bd303ec6
https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/visualize.py#L1036-L1071
train
mfitzp/padua
padua/visualize.py
_areadist
def _areadist(ax, v, xr, c, bins=100, by=None, alpha=1, label=None): """ Plot the histogram distribution but as an area plot """ y, x = np.histogram(v[~np.isnan(v)], bins) x = x[:-1] if by is None: by = np.zeros((bins,)) ax.fill_between(x, y, by, facecolor=c, alpha=alpha, label=lab...
python
def _areadist(ax, v, xr, c, bins=100, by=None, alpha=1, label=None): """ Plot the histogram distribution but as an area plot """ y, x = np.histogram(v[~np.isnan(v)], bins) x = x[:-1] if by is None: by = np.zeros((bins,)) ax.fill_between(x, y, by, facecolor=c, alpha=alpha, label=lab...
[ "def", "_areadist", "(", "ax", ",", "v", ",", "xr", ",", "c", ",", "bins", "=", "100", ",", "by", "=", "None", ",", "alpha", "=", "1", ",", "label", "=", "None", ")", ":", "y", ",", "x", "=", "np", ".", "histogram", "(", "v", "[", "~", "n...
Plot the histogram distribution but as an area plot
[ "Plot", "the", "histogram", "distribution", "but", "as", "an", "area", "plot" ]
8b14bf4d2f895da6aea5d7885d409315bd303ec6
https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/visualize.py#L1374-L1385
train
mfitzp/padua
padua/visualize.py
hierarchical_timecourse
def hierarchical_timecourse( df, cluster_cols=True, cluster_rows=False, n_col_clusters=False, n_row_clusters=False, fcol=None, z_score=0, method='ward', cmap=cm.PuOr_r, return_clusters=False, rdistance_fn=distance.pdist, cdi...
python
def hierarchical_timecourse( df, cluster_cols=True, cluster_rows=False, n_col_clusters=False, n_row_clusters=False, fcol=None, z_score=0, method='ward', cmap=cm.PuOr_r, return_clusters=False, rdistance_fn=distance.pdist, cdi...
[ "def", "hierarchical_timecourse", "(", "df", ",", "cluster_cols", "=", "True", ",", "cluster_rows", "=", "False", ",", "n_col_clusters", "=", "False", ",", "n_row_clusters", "=", "False", ",", "fcol", "=", "None", ",", "z_score", "=", "0", ",", "method", "...
Hierarchical clustering of samples across timecourse experiment. Peform a hiearchical clustering on a pandas DataFrame and display the resulting clustering as a timecourse density plot. Samples are z-scored along the 0-axis (y) by default. To override this use the `z_score` param with the axis to `z_score...
[ "Hierarchical", "clustering", "of", "samples", "across", "timecourse", "experiment", "." ]
8b14bf4d2f895da6aea5d7885d409315bd303ec6
https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/visualize.py#L1872-L1965
train
mfitzp/padua
padua/normalization.py
subtract_column_median
def subtract_column_median(df, prefix='Intensity '): """ Apply column-wise normalisation to expression columns. Default is median transform to expression columns beginning with Intensity :param df: :param prefix: The column prefix for expression columns :return: """ df = df.copy() ...
python
def subtract_column_median(df, prefix='Intensity '): """ Apply column-wise normalisation to expression columns. Default is median transform to expression columns beginning with Intensity :param df: :param prefix: The column prefix for expression columns :return: """ df = df.copy() ...
[ "def", "subtract_column_median", "(", "df", ",", "prefix", "=", "'Intensity '", ")", ":", "df", "=", "df", ".", "copy", "(", ")", "df", ".", "replace", "(", "[", "np", ".", "inf", ",", "-", "np", ".", "inf", "]", ",", "np", ".", "nan", ",", "in...
Apply column-wise normalisation to expression columns. Default is median transform to expression columns beginning with Intensity :param df: :param prefix: The column prefix for expression columns :return:
[ "Apply", "column", "-", "wise", "normalisation", "to", "expression", "columns", "." ]
8b14bf4d2f895da6aea5d7885d409315bd303ec6
https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/normalization.py#L4-L22
train
mfitzp/padua
padua/utils.py
get_protein_id_list
def get_protein_id_list(df, level=0): """ Return a complete list of shortform IDs from a DataFrame Extract all protein IDs from a dataframe from multiple rows containing protein IDs in MaxQuant output format: e.g. P07830;P63267;Q54A44;P63268 Long names (containing species information) are eliminat...
python
def get_protein_id_list(df, level=0): """ Return a complete list of shortform IDs from a DataFrame Extract all protein IDs from a dataframe from multiple rows containing protein IDs in MaxQuant output format: e.g. P07830;P63267;Q54A44;P63268 Long names (containing species information) are eliminat...
[ "def", "get_protein_id_list", "(", "df", ",", "level", "=", "0", ")", ":", "protein_list", "=", "[", "]", "for", "s", "in", "df", ".", "index", ".", "get_level_values", "(", "level", ")", ":", "protein_list", ".", "extend", "(", "get_protein_ids", "(", ...
Return a complete list of shortform IDs from a DataFrame Extract all protein IDs from a dataframe from multiple rows containing protein IDs in MaxQuant output format: e.g. P07830;P63267;Q54A44;P63268 Long names (containing species information) are eliminated (split on ' ') and isoforms are removed (sp...
[ "Return", "a", "complete", "list", "of", "shortform", "IDs", "from", "a", "DataFrame" ]
8b14bf4d2f895da6aea5d7885d409315bd303ec6
https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/utils.py#L142-L162
train
mfitzp/padua
padua/utils.py
hierarchical_match
def hierarchical_match(d, k, default=None): """ Match a key against a dict, simplifying element at a time :param df: DataFrame :type df: pandas.DataFrame :param level: Level of DataFrame index to extract IDs from :type level: int or str :return: hiearchically matched value or default "...
python
def hierarchical_match(d, k, default=None): """ Match a key against a dict, simplifying element at a time :param df: DataFrame :type df: pandas.DataFrame :param level: Level of DataFrame index to extract IDs from :type level: int or str :return: hiearchically matched value or default "...
[ "def", "hierarchical_match", "(", "d", ",", "k", ",", "default", "=", "None", ")", ":", "if", "d", "is", "None", ":", "return", "default", "if", "type", "(", "k", ")", "!=", "list", "and", "type", "(", "k", ")", "!=", "tuple", ":", "k", "=", "[...
Match a key against a dict, simplifying element at a time :param df: DataFrame :type df: pandas.DataFrame :param level: Level of DataFrame index to extract IDs from :type level: int or str :return: hiearchically matched value or default
[ "Match", "a", "key", "against", "a", "dict", "simplifying", "element", "at", "a", "time" ]
8b14bf4d2f895da6aea5d7885d409315bd303ec6
https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/utils.py#L228-L256
train
mfitzp/padua
padua/utils.py
calculate_s0_curve
def calculate_s0_curve(s0, minpval, maxpval, minratio, maxratio, curve_interval=0.1): """ Calculate s0 curve for volcano plot. Taking an min and max p value, and a min and max ratio, calculate an smooth curve starting from parameter `s0` in each direction. The `curve_interval` parameter defines th...
python
def calculate_s0_curve(s0, minpval, maxpval, minratio, maxratio, curve_interval=0.1): """ Calculate s0 curve for volcano plot. Taking an min and max p value, and a min and max ratio, calculate an smooth curve starting from parameter `s0` in each direction. The `curve_interval` parameter defines th...
[ "def", "calculate_s0_curve", "(", "s0", ",", "minpval", ",", "maxpval", ",", "minratio", ",", "maxratio", ",", "curve_interval", "=", "0.1", ")", ":", "mminpval", "=", "-", "np", ".", "log10", "(", "minpval", ")", "mmaxpval", "=", "-", "np", ".", "log1...
Calculate s0 curve for volcano plot. Taking an min and max p value, and a min and max ratio, calculate an smooth curve starting from parameter `s0` in each direction. The `curve_interval` parameter defines the smoothness of the resulting curve. :param s0: `float` offset of curve from interset :pa...
[ "Calculate", "s0", "curve", "for", "volcano", "plot", "." ]
8b14bf4d2f895da6aea5d7885d409315bd303ec6
https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/utils.py#L282-L317
train
mfitzp/padua
padua/analysis.py
correlation
def correlation(df, rowvar=False): """ Calculate column-wise Pearson correlations using ``numpy.ma.corrcoef`` Input data is masked to ignore NaNs when calculating correlations. Data is returned as a Pandas ``DataFrame`` of column_n x column_n dimensions, with column index copied to both axes. ...
python
def correlation(df, rowvar=False): """ Calculate column-wise Pearson correlations using ``numpy.ma.corrcoef`` Input data is masked to ignore NaNs when calculating correlations. Data is returned as a Pandas ``DataFrame`` of column_n x column_n dimensions, with column index copied to both axes. ...
[ "def", "correlation", "(", "df", ",", "rowvar", "=", "False", ")", ":", "df", "=", "df", ".", "copy", "(", ")", "maskv", "=", "np", ".", "ma", ".", "masked_where", "(", "np", ".", "isnan", "(", "df", ".", "values", ")", ",", "df", ".", "values"...
Calculate column-wise Pearson correlations using ``numpy.ma.corrcoef`` Input data is masked to ignore NaNs when calculating correlations. Data is returned as a Pandas ``DataFrame`` of column_n x column_n dimensions, with column index copied to both axes. :param df: Pandas DataFrame :return: Pandas...
[ "Calculate", "column", "-", "wise", "Pearson", "correlations", "using", "numpy", ".", "ma", ".", "corrcoef" ]
8b14bf4d2f895da6aea5d7885d409315bd303ec6
https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/analysis.py#L26-L48
train
mfitzp/padua
padua/analysis.py
pca
def pca(df, n_components=2, mean_center=False, **kwargs): """ Principal Component Analysis, based on `sklearn.decomposition.PCA` Performs a principal component analysis (PCA) on the supplied dataframe, selecting the first ``n_components`` components in the resulting model. The model scores and weights ...
python
def pca(df, n_components=2, mean_center=False, **kwargs): """ Principal Component Analysis, based on `sklearn.decomposition.PCA` Performs a principal component analysis (PCA) on the supplied dataframe, selecting the first ``n_components`` components in the resulting model. The model scores and weights ...
[ "def", "pca", "(", "df", ",", "n_components", "=", "2", ",", "mean_center", "=", "False", ",", "**", "kwargs", ")", ":", "if", "not", "sklearn", ":", "assert", "(", "'This library depends on scikit-learn (sklearn) to perform PCA analysis'", ")", "from", "sklearn",...
Principal Component Analysis, based on `sklearn.decomposition.PCA` Performs a principal component analysis (PCA) on the supplied dataframe, selecting the first ``n_components`` components in the resulting model. The model scores and weights are returned. For more information on PCA and the algorithm used,...
[ "Principal", "Component", "Analysis", "based", "on", "sklearn", ".", "decomposition", ".", "PCA" ]
8b14bf4d2f895da6aea5d7885d409315bd303ec6
https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/analysis.py#L51-L93
train
mfitzp/padua
padua/analysis.py
plsda
def plsda(df, a, b, n_components=2, mean_center=False, scale=True, **kwargs): """ Partial Least Squares Discriminant Analysis, based on `sklearn.cross_decomposition.PLSRegression` Performs a binary group partial least squares discriminant analysis (PLS-DA) on the supplied dataframe, selecting the first...
python
def plsda(df, a, b, n_components=2, mean_center=False, scale=True, **kwargs): """ Partial Least Squares Discriminant Analysis, based on `sklearn.cross_decomposition.PLSRegression` Performs a binary group partial least squares discriminant analysis (PLS-DA) on the supplied dataframe, selecting the first...
[ "def", "plsda", "(", "df", ",", "a", ",", "b", ",", "n_components", "=", "2", ",", "mean_center", "=", "False", ",", "scale", "=", "True", ",", "**", "kwargs", ")", ":", "if", "not", "sklearn", ":", "assert", "(", "'This library depends on scikit-learn (...
Partial Least Squares Discriminant Analysis, based on `sklearn.cross_decomposition.PLSRegression` Performs a binary group partial least squares discriminant analysis (PLS-DA) on the supplied dataframe, selecting the first ``n_components``. Sample groups are defined by the selectors ``a`` and ``b`` which a...
[ "Partial", "Least", "Squares", "Discriminant", "Analysis", "based", "on", "sklearn", ".", "cross_decomposition", ".", "PLSRegression" ]
8b14bf4d2f895da6aea5d7885d409315bd303ec6
https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/analysis.py#L96-L161
train
mfitzp/padua
padua/analysis.py
enrichment_from_evidence
def enrichment_from_evidence(dfe, modification="Phospho (STY)"): """ Calculate relative enrichment of peptide modifications from evidence.txt. Taking a modifiedsitepeptides ``DataFrame`` returns the relative enrichment of the specified modification in the table. The returned data columns are gener...
python
def enrichment_from_evidence(dfe, modification="Phospho (STY)"): """ Calculate relative enrichment of peptide modifications from evidence.txt. Taking a modifiedsitepeptides ``DataFrame`` returns the relative enrichment of the specified modification in the table. The returned data columns are gener...
[ "def", "enrichment_from_evidence", "(", "dfe", ",", "modification", "=", "\"Phospho (STY)\"", ")", ":", "dfe", "=", "dfe", ".", "reset_index", "(", ")", ".", "set_index", "(", "'Experiment'", ")", "dfe", "[", "'Modifications'", "]", "=", "np", ".", "array", ...
Calculate relative enrichment of peptide modifications from evidence.txt. Taking a modifiedsitepeptides ``DataFrame`` returns the relative enrichment of the specified modification in the table. The returned data columns are generated from the input data columns. :param df: Pandas ``DataFrame`` of evi...
[ "Calculate", "relative", "enrichment", "of", "peptide", "modifications", "from", "evidence", ".", "txt", "." ]
8b14bf4d2f895da6aea5d7885d409315bd303ec6
https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/analysis.py#L232-L258
train
mfitzp/padua
padua/analysis.py
enrichment_from_msp
def enrichment_from_msp(dfmsp, modification="Phospho (STY)"): """ Calculate relative enrichment of peptide modifications from modificationSpecificPeptides.txt. Taking a modifiedsitepeptides ``DataFrame`` returns the relative enrichment of the specified modification in the table. The returned data ...
python
def enrichment_from_msp(dfmsp, modification="Phospho (STY)"): """ Calculate relative enrichment of peptide modifications from modificationSpecificPeptides.txt. Taking a modifiedsitepeptides ``DataFrame`` returns the relative enrichment of the specified modification in the table. The returned data ...
[ "def", "enrichment_from_msp", "(", "dfmsp", ",", "modification", "=", "\"Phospho (STY)\"", ")", ":", "dfmsp", "[", "'Modifications'", "]", "=", "np", ".", "array", "(", "[", "modification", "in", "m", "for", "m", "in", "dfmsp", "[", "'Modifications'", "]", ...
Calculate relative enrichment of peptide modifications from modificationSpecificPeptides.txt. Taking a modifiedsitepeptides ``DataFrame`` returns the relative enrichment of the specified modification in the table. The returned data columns are generated from the input data columns. :param df: Pandas ...
[ "Calculate", "relative", "enrichment", "of", "peptide", "modifications", "from", "modificationSpecificPeptides", ".", "txt", "." ]
8b14bf4d2f895da6aea5d7885d409315bd303ec6
https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/analysis.py#L263-L287
train
mfitzp/padua
padua/analysis.py
sitespeptidesproteins
def sitespeptidesproteins(df, site_localization_probability=0.75): """ Generate summary count of modified sites, peptides and proteins in a processed dataset ``DataFrame``. Returns the number of sites, peptides and proteins as calculated as follows: - `sites` (>0.75; or specified site localization pro...
python
def sitespeptidesproteins(df, site_localization_probability=0.75): """ Generate summary count of modified sites, peptides and proteins in a processed dataset ``DataFrame``. Returns the number of sites, peptides and proteins as calculated as follows: - `sites` (>0.75; or specified site localization pro...
[ "def", "sitespeptidesproteins", "(", "df", ",", "site_localization_probability", "=", "0.75", ")", ":", "sites", "=", "filters", ".", "filter_localization_probability", "(", "df", ",", "site_localization_probability", ")", "[", "'Sequence window'", "]", "peptides", "=...
Generate summary count of modified sites, peptides and proteins in a processed dataset ``DataFrame``. Returns the number of sites, peptides and proteins as calculated as follows: - `sites` (>0.75; or specified site localization probability) count of all sites > threshold - `peptides` the set of `Sequence ...
[ "Generate", "summary", "count", "of", "modified", "sites", "peptides", "and", "proteins", "in", "a", "processed", "dataset", "DataFrame", "." ]
8b14bf4d2f895da6aea5d7885d409315bd303ec6
https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/analysis.py#L291-L309
train
mfitzp/padua
padua/analysis.py
modifiedaminoacids
def modifiedaminoacids(df): """ Calculate the number of modified amino acids in supplied ``DataFrame``. Returns the total of all modifications and the total for each amino acid individually, as an ``int`` and a ``dict`` of ``int``, keyed by amino acid, respectively. :param df: Pandas ``DataFrame``...
python
def modifiedaminoacids(df): """ Calculate the number of modified amino acids in supplied ``DataFrame``. Returns the total of all modifications and the total for each amino acid individually, as an ``int`` and a ``dict`` of ``int``, keyed by amino acid, respectively. :param df: Pandas ``DataFrame``...
[ "def", "modifiedaminoacids", "(", "df", ")", ":", "amino_acids", "=", "list", "(", "df", "[", "'Amino acid'", "]", ".", "values", ")", "aas", "=", "set", "(", "amino_acids", ")", "quants", "=", "{", "}", "for", "aa", "in", "aas", ":", "quants", "[", ...
Calculate the number of modified amino acids in supplied ``DataFrame``. Returns the total of all modifications and the total for each amino acid individually, as an ``int`` and a ``dict`` of ``int``, keyed by amino acid, respectively. :param df: Pandas ``DataFrame`` containing processed data. :return:...
[ "Calculate", "the", "number", "of", "modified", "amino", "acids", "in", "supplied", "DataFrame", "." ]
8b14bf4d2f895da6aea5d7885d409315bd303ec6
https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/analysis.py#L312-L333
train
mfitzp/padua
padua/process.py
build_index_from_design
def build_index_from_design(df, design, remove_prefix=None, types=None, axis=1, auto_convert_numeric=True, unmatched_columns='index'): """ Build a MultiIndex from a design table. Supply with a table with column headings for the new multiindex and a index containing the labels to search for in the data....
python
def build_index_from_design(df, design, remove_prefix=None, types=None, axis=1, auto_convert_numeric=True, unmatched_columns='index'): """ Build a MultiIndex from a design table. Supply with a table with column headings for the new multiindex and a index containing the labels to search for in the data....
[ "def", "build_index_from_design", "(", "df", ",", "design", ",", "remove_prefix", "=", "None", ",", "types", "=", "None", ",", "axis", "=", "1", ",", "auto_convert_numeric", "=", "True", ",", "unmatched_columns", "=", "'index'", ")", ":", "df", "=", "df", ...
Build a MultiIndex from a design table. Supply with a table with column headings for the new multiindex and a index containing the labels to search for in the data. :param df: :param design: :param remove: :param types: :param axis: :param auto_convert_numeric: :return:
[ "Build", "a", "MultiIndex", "from", "a", "design", "table", "." ]
8b14bf4d2f895da6aea5d7885d409315bd303ec6
https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/process.py#L23-L111
train
mfitzp/padua
padua/process.py
build_index_from_labels
def build_index_from_labels(df, indices, remove_prefix=None, types=None, axis=1): """ Build a MultiIndex from a list of labels and matching regex Supply with a dictionary of Hierarchy levels and matching regex to extract this level from the sample label :param df: :param indices: Tuples of ind...
python
def build_index_from_labels(df, indices, remove_prefix=None, types=None, axis=1): """ Build a MultiIndex from a list of labels and matching regex Supply with a dictionary of Hierarchy levels and matching regex to extract this level from the sample label :param df: :param indices: Tuples of ind...
[ "def", "build_index_from_labels", "(", "df", ",", "indices", ",", "remove_prefix", "=", "None", ",", "types", "=", "None", ",", "axis", "=", "1", ")", ":", "df", "=", "df", ".", "copy", "(", ")", "if", "remove_prefix", "is", "None", ":", "remove_prefix...
Build a MultiIndex from a list of labels and matching regex Supply with a dictionary of Hierarchy levels and matching regex to extract this level from the sample label :param df: :param indices: Tuples of indices ('label','regex') matches :param strip: Strip these strings from labels before matchi...
[ "Build", "a", "MultiIndex", "from", "a", "list", "of", "labels", "and", "matching", "regex" ]
8b14bf4d2f895da6aea5d7885d409315bd303ec6
https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/process.py#L114-L165
train
mfitzp/padua
padua/process.py
combine_expression_columns
def combine_expression_columns(df, columns_to_combine, remove_combined=True): """ Combine expression columns, calculating the mean for 2 columns :param df: Pandas dataframe :param columns_to_combine: A list of tuples containing the column names to combine :return: """ df = df.copy() ...
python
def combine_expression_columns(df, columns_to_combine, remove_combined=True): """ Combine expression columns, calculating the mean for 2 columns :param df: Pandas dataframe :param columns_to_combine: A list of tuples containing the column names to combine :return: """ df = df.copy() ...
[ "def", "combine_expression_columns", "(", "df", ",", "columns_to_combine", ",", "remove_combined", "=", "True", ")", ":", "df", "=", "df", ".", "copy", "(", ")", "for", "ca", ",", "cb", "in", "columns_to_combine", ":", "df", "[", "\"%s_(x+y)/2_%s\"", "%", ...
Combine expression columns, calculating the mean for 2 columns :param df: Pandas dataframe :param columns_to_combine: A list of tuples containing the column names to combine :return:
[ "Combine", "expression", "columns", "calculating", "the", "mean", "for", "2", "columns" ]
8b14bf4d2f895da6aea5d7885d409315bd303ec6
https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/process.py#L198-L218
train
mfitzp/padua
padua/process.py
expand_side_table
def expand_side_table(df): """ Perform equivalent of 'expand side table' in Perseus by folding Multiplicity columns down onto duplicate rows The id is remapped to UID___Multiplicity, which is different to Perseus behaviour, but prevents accidental of non-matching rows from occurring later in an...
python
def expand_side_table(df): """ Perform equivalent of 'expand side table' in Perseus by folding Multiplicity columns down onto duplicate rows The id is remapped to UID___Multiplicity, which is different to Perseus behaviour, but prevents accidental of non-matching rows from occurring later in an...
[ "def", "expand_side_table", "(", "df", ")", ":", "df", "=", "df", ".", "copy", "(", ")", "idx", "=", "df", ".", "index", ".", "names", "df", ".", "reset_index", "(", "inplace", "=", "True", ")", "def", "strip_multiplicity", "(", "df", ")", ":", "df...
Perform equivalent of 'expand side table' in Perseus by folding Multiplicity columns down onto duplicate rows The id is remapped to UID___Multiplicity, which is different to Perseus behaviour, but prevents accidental of non-matching rows from occurring later in analysis. :param df: :return:
[ "Perform", "equivalent", "of", "expand", "side", "table", "in", "Perseus", "by", "folding", "Multiplicity", "columns", "down", "onto", "duplicate", "rows" ]
8b14bf4d2f895da6aea5d7885d409315bd303ec6
https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/process.py#L221-L277
train
mfitzp/padua
padua/process.py
apply_experimental_design
def apply_experimental_design(df, f, prefix='Intensity '): """ Load the experimental design template from MaxQuant and use it to apply the label names to the data columns. :param df: :param f: File path for the experimental design template :param prefix: :return: dt """ df = df.copy() ...
python
def apply_experimental_design(df, f, prefix='Intensity '): """ Load the experimental design template from MaxQuant and use it to apply the label names to the data columns. :param df: :param f: File path for the experimental design template :param prefix: :return: dt """ df = df.copy() ...
[ "def", "apply_experimental_design", "(", "df", ",", "f", ",", "prefix", "=", "'Intensity '", ")", ":", "df", "=", "df", ".", "copy", "(", ")", "edt", "=", "pd", ".", "read_csv", "(", "f", ",", "sep", "=", "'\\t'", ",", "header", "=", "0", ")", "e...
Load the experimental design template from MaxQuant and use it to apply the label names to the data columns. :param df: :param f: File path for the experimental design template :param prefix: :return: dt
[ "Load", "the", "experimental", "design", "template", "from", "MaxQuant", "and", "use", "it", "to", "apply", "the", "label", "names", "to", "the", "data", "columns", "." ]
8b14bf4d2f895da6aea5d7885d409315bd303ec6
https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/process.py#L280-L306
train
mfitzp/padua
padua/process.py
transform_expression_columns
def transform_expression_columns(df, fn=np.log2, prefix='Intensity '): """ Apply transformation to expression columns. Default is log2 transform to expression columns beginning with Intensity :param df: :param prefix: The column prefix for expression columns :return: """ df = df.copy(...
python
def transform_expression_columns(df, fn=np.log2, prefix='Intensity '): """ Apply transformation to expression columns. Default is log2 transform to expression columns beginning with Intensity :param df: :param prefix: The column prefix for expression columns :return: """ df = df.copy(...
[ "def", "transform_expression_columns", "(", "df", ",", "fn", "=", "np", ".", "log2", ",", "prefix", "=", "'Intensity '", ")", ":", "df", "=", "df", ".", "copy", "(", ")", "mask", "=", "np", ".", "array", "(", "[", "l", ".", "startswith", "(", "pref...
Apply transformation to expression columns. Default is log2 transform to expression columns beginning with Intensity :param df: :param prefix: The column prefix for expression columns :return:
[ "Apply", "transformation", "to", "expression", "columns", "." ]
8b14bf4d2f895da6aea5d7885d409315bd303ec6
https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/process.py#L309-L327
train
mfitzp/padua
padua/process.py
fold_columns_to_rows
def fold_columns_to_rows(df, levels_from=2): """ Take a levels from the columns and fold down into the row index. This destroys the existing index; existing rows will appear as columns under the new column index :param df: :param levels_from: The level (inclusive) from which column index will b...
python
def fold_columns_to_rows(df, levels_from=2): """ Take a levels from the columns and fold down into the row index. This destroys the existing index; existing rows will appear as columns under the new column index :param df: :param levels_from: The level (inclusive) from which column index will b...
[ "def", "fold_columns_to_rows", "(", "df", ",", "levels_from", "=", "2", ")", ":", "df", "=", "df", ".", "copy", "(", ")", "df", ".", "reset_index", "(", "inplace", "=", "True", ",", "drop", "=", "True", ")", "df", "=", "df", ".", "T", "a", "=", ...
Take a levels from the columns and fold down into the row index. This destroys the existing index; existing rows will appear as columns under the new column index :param df: :param levels_from: The level (inclusive) from which column index will be folded :return:
[ "Take", "a", "levels", "from", "the", "columns", "and", "fold", "down", "into", "the", "row", "index", ".", "This", "destroys", "the", "existing", "index", ";", "existing", "rows", "will", "appear", "as", "columns", "under", "the", "new", "column", "index"...
8b14bf4d2f895da6aea5d7885d409315bd303ec6
https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/process.py#L330-L377
train
ECRL/ecabc
ecabc/abc.py
ABC.args
def args(self, args): '''Set additional arguments to be passed to the fitness function Args: args (dict): additional arguments ''' self._args = args self._logger.log('debug', 'Args set to {}'.format(args))
python
def args(self, args): '''Set additional arguments to be passed to the fitness function Args: args (dict): additional arguments ''' self._args = args self._logger.log('debug', 'Args set to {}'.format(args))
[ "def", "args", "(", "self", ",", "args", ")", ":", "self", ".", "_args", "=", "args", "self", ".", "_logger", ".", "log", "(", "'debug'", ",", "'Args set to {}'", ".", "format", "(", "args", ")", ")" ]
Set additional arguments to be passed to the fitness function Args: args (dict): additional arguments
[ "Set", "additional", "arguments", "to", "be", "passed", "to", "the", "fitness", "function" ]
4e73125ff90bfeeae359a5ab1badba8894d70eaa
https://github.com/ECRL/ecabc/blob/4e73125ff90bfeeae359a5ab1badba8894d70eaa/ecabc/abc.py#L147-L154
train
ECRL/ecabc
ecabc/abc.py
ABC.minimize
def minimize(self, minimize): '''Configures the ABC to minimize fitness function return value or derived score Args: minimize (bool): if True, minimizes fitness function return value; if False, minimizes derived score ''' self._minimize = minimize ...
python
def minimize(self, minimize): '''Configures the ABC to minimize fitness function return value or derived score Args: minimize (bool): if True, minimizes fitness function return value; if False, minimizes derived score ''' self._minimize = minimize ...
[ "def", "minimize", "(", "self", ",", "minimize", ")", ":", "self", ".", "_minimize", "=", "minimize", "self", ".", "_logger", ".", "log", "(", "'debug'", ",", "'Minimize set to {}'", ".", "format", "(", "minimize", ")", ")" ]
Configures the ABC to minimize fitness function return value or derived score Args: minimize (bool): if True, minimizes fitness function return value; if False, minimizes derived score
[ "Configures", "the", "ABC", "to", "minimize", "fitness", "function", "return", "value", "or", "derived", "score" ]
4e73125ff90bfeeae359a5ab1badba8894d70eaa
https://github.com/ECRL/ecabc/blob/4e73125ff90bfeeae359a5ab1badba8894d70eaa/ecabc/abc.py#L165-L175
train
ECRL/ecabc
ecabc/abc.py
ABC.num_employers
def num_employers(self, num_employers): '''Sets the number of employer bees; at least two are required Args: num_employers (int): number of employer bees ''' if num_employers < 2: self._logger.log( 'warn', 'Two employers are neede...
python
def num_employers(self, num_employers): '''Sets the number of employer bees; at least two are required Args: num_employers (int): number of employer bees ''' if num_employers < 2: self._logger.log( 'warn', 'Two employers are neede...
[ "def", "num_employers", "(", "self", ",", "num_employers", ")", ":", "if", "num_employers", "<", "2", ":", "self", ".", "_logger", ".", "log", "(", "'warn'", ",", "'Two employers are needed: setting to two'", ")", "num_employers", "=", "2", "self", ".", "_num_...
Sets the number of employer bees; at least two are required Args: num_employers (int): number of employer bees
[ "Sets", "the", "number", "of", "employer", "bees", ";", "at", "least", "two", "are", "required" ]
4e73125ff90bfeeae359a5ab1badba8894d70eaa
https://github.com/ECRL/ecabc/blob/4e73125ff90bfeeae359a5ab1badba8894d70eaa/ecabc/abc.py#L184-L202
train
ECRL/ecabc
ecabc/abc.py
ABC.processes
def processes(self, processes): '''Set the number of concurrent processes the ABC will utilize for fitness function evaluation; if <= 1, single process is used Args: processes (int): number of concurrent processes ''' if self._processes > 1: self._pool.c...
python
def processes(self, processes): '''Set the number of concurrent processes the ABC will utilize for fitness function evaluation; if <= 1, single process is used Args: processes (int): number of concurrent processes ''' if self._processes > 1: self._pool.c...
[ "def", "processes", "(", "self", ",", "processes", ")", ":", "if", "self", ".", "_processes", ">", "1", ":", "self", ".", "_pool", ".", "close", "(", ")", "self", ".", "_pool", ".", "join", "(", ")", "self", ".", "_pool", "=", "multiprocessing", "....
Set the number of concurrent processes the ABC will utilize for fitness function evaluation; if <= 1, single process is used Args: processes (int): number of concurrent processes
[ "Set", "the", "number", "of", "concurrent", "processes", "the", "ABC", "will", "utilize", "for", "fitness", "function", "evaluation", ";", "if", "<", "=", "1", "single", "process", "is", "used" ]
4e73125ff90bfeeae359a5ab1badba8894d70eaa
https://github.com/ECRL/ecabc/blob/4e73125ff90bfeeae359a5ab1badba8894d70eaa/ecabc/abc.py#L268-L284
train
ECRL/ecabc
ecabc/abc.py
ABC.infer_process_count
def infer_process_count(self): '''Infers the number of CPU cores in the current system, sets the number of concurrent processes accordingly ''' try: self.processes = multiprocessing.cpu_count() except NotImplementedError: self._logger.log( ...
python
def infer_process_count(self): '''Infers the number of CPU cores in the current system, sets the number of concurrent processes accordingly ''' try: self.processes = multiprocessing.cpu_count() except NotImplementedError: self._logger.log( ...
[ "def", "infer_process_count", "(", "self", ")", ":", "try", ":", "self", ".", "processes", "=", "multiprocessing", ".", "cpu_count", "(", ")", "except", "NotImplementedError", ":", "self", ".", "_logger", ".", "log", "(", "'error'", ",", "'Could infer CPU coun...
Infers the number of CPU cores in the current system, sets the number of concurrent processes accordingly
[ "Infers", "the", "number", "of", "CPU", "cores", "in", "the", "current", "system", "sets", "the", "number", "of", "concurrent", "processes", "accordingly" ]
4e73125ff90bfeeae359a5ab1badba8894d70eaa
https://github.com/ECRL/ecabc/blob/4e73125ff90bfeeae359a5ab1badba8894d70eaa/ecabc/abc.py#L286-L298
train
ECRL/ecabc
ecabc/abc.py
ABC.create_employers
def create_employers(self): '''Generate employer bees. This should be called directly after the ABC is initialized. ''' self.__verify_ready(True) employers = [] for i in range(self._num_employers): employer = EmployerBee(self.__gen_random_values()) ...
python
def create_employers(self): '''Generate employer bees. This should be called directly after the ABC is initialized. ''' self.__verify_ready(True) employers = [] for i in range(self._num_employers): employer = EmployerBee(self.__gen_random_values()) ...
[ "def", "create_employers", "(", "self", ")", ":", "self", ".", "__verify_ready", "(", "True", ")", "employers", "=", "[", "]", "for", "i", "in", "range", "(", "self", ".", "_num_employers", ")", ":", "employer", "=", "EmployerBee", "(", "self", ".", "_...
Generate employer bees. This should be called directly after the ABC is initialized.
[ "Generate", "employer", "bees", ".", "This", "should", "be", "called", "directly", "after", "the", "ABC", "is", "initialized", "." ]
4e73125ff90bfeeae359a5ab1badba8894d70eaa
https://github.com/ECRL/ecabc/blob/4e73125ff90bfeeae359a5ab1badba8894d70eaa/ecabc/abc.py#L300-L344
train
ECRL/ecabc
ecabc/abc.py
ABC.run_iteration
def run_iteration(self): '''Runs a single iteration of the ABC; employer phase -> probability calculation -> onlooker phase -> check positions ''' self._employer_phase() self._calc_probability() self._onlooker_phase() self._check_positions()
python
def run_iteration(self): '''Runs a single iteration of the ABC; employer phase -> probability calculation -> onlooker phase -> check positions ''' self._employer_phase() self._calc_probability() self._onlooker_phase() self._check_positions()
[ "def", "run_iteration", "(", "self", ")", ":", "self", ".", "_employer_phase", "(", ")", "self", ".", "_calc_probability", "(", ")", "self", ".", "_onlooker_phase", "(", ")", "self", ".", "_check_positions", "(", ")" ]
Runs a single iteration of the ABC; employer phase -> probability calculation -> onlooker phase -> check positions
[ "Runs", "a", "single", "iteration", "of", "the", "ABC", ";", "employer", "phase", "-", ">", "probability", "calculation", "-", ">", "onlooker", "phase", "-", ">", "check", "positions" ]
4e73125ff90bfeeae359a5ab1badba8894d70eaa
https://github.com/ECRL/ecabc/blob/4e73125ff90bfeeae359a5ab1badba8894d70eaa/ecabc/abc.py#L346-L354
train
ECRL/ecabc
ecabc/abc.py
ABC._calc_probability
def _calc_probability(self): '''Determines the probability that each bee will be chosen during the onlooker phase; also determines if a new best-performing bee is found ''' self._logger.log('debug', 'Calculating bee probabilities') self.__verify_ready() self._total_score...
python
def _calc_probability(self): '''Determines the probability that each bee will be chosen during the onlooker phase; also determines if a new best-performing bee is found ''' self._logger.log('debug', 'Calculating bee probabilities') self.__verify_ready() self._total_score...
[ "def", "_calc_probability", "(", "self", ")", ":", "self", ".", "_logger", ".", "log", "(", "'debug'", ",", "'Calculating bee probabilities'", ")", "self", ".", "__verify_ready", "(", ")", "self", ".", "_total_score", "=", "0", "for", "employer", "in", "self...
Determines the probability that each bee will be chosen during the onlooker phase; also determines if a new best-performing bee is found
[ "Determines", "the", "probability", "that", "each", "bee", "will", "be", "chosen", "during", "the", "onlooker", "phase", ";", "also", "determines", "if", "a", "new", "best", "-", "performing", "bee", "is", "found" ]
4e73125ff90bfeeae359a5ab1badba8894d70eaa
https://github.com/ECRL/ecabc/blob/4e73125ff90bfeeae359a5ab1badba8894d70eaa/ecabc/abc.py#L377-L398
train
ECRL/ecabc
ecabc/abc.py
ABC._merge_bee
def _merge_bee(self, bee): '''Shifts a random value for a supplied bee with in accordance with another random bee's value Args: bee (EmployerBee): supplied bee to merge Returns: tuple: (score of new position, values of new position, fitness funct...
python
def _merge_bee(self, bee): '''Shifts a random value for a supplied bee with in accordance with another random bee's value Args: bee (EmployerBee): supplied bee to merge Returns: tuple: (score of new position, values of new position, fitness funct...
[ "def", "_merge_bee", "(", "self", ",", "bee", ")", ":", "random_dimension", "=", "randint", "(", "0", ",", "len", "(", "self", ".", "_value_ranges", ")", "-", "1", ")", "second_bee", "=", "randint", "(", "0", ",", "self", ".", "_num_employers", "-", ...
Shifts a random value for a supplied bee with in accordance with another random bee's value Args: bee (EmployerBee): supplied bee to merge Returns: tuple: (score of new position, values of new position, fitness function return value of new position)
[ "Shifts", "a", "random", "value", "for", "a", "supplied", "bee", "with", "in", "accordance", "with", "another", "random", "bee", "s", "value" ]
4e73125ff90bfeeae359a5ab1badba8894d70eaa
https://github.com/ECRL/ecabc/blob/4e73125ff90bfeeae359a5ab1badba8894d70eaa/ecabc/abc.py#L452-L478
train
ECRL/ecabc
ecabc/abc.py
ABC._move_bee
def _move_bee(self, bee, new_values): '''Moves a bee to a new position if new fitness score is better than the bee's current fitness score Args: bee (EmployerBee): bee to move new_values (tuple): (new score, new values, new fitness function return value) ...
python
def _move_bee(self, bee, new_values): '''Moves a bee to a new position if new fitness score is better than the bee's current fitness score Args: bee (EmployerBee): bee to move new_values (tuple): (new score, new values, new fitness function return value) ...
[ "def", "_move_bee", "(", "self", ",", "bee", ",", "new_values", ")", ":", "score", "=", "np", ".", "nan_to_num", "(", "new_values", "[", "0", "]", ")", "if", "bee", ".", "score", ">", "score", ":", "bee", ".", "failed_trials", "+=", "1", "else", ":...
Moves a bee to a new position if new fitness score is better than the bee's current fitness score Args: bee (EmployerBee): bee to move new_values (tuple): (new score, new values, new fitness function return value)
[ "Moves", "a", "bee", "to", "a", "new", "position", "if", "new", "fitness", "score", "is", "better", "than", "the", "bee", "s", "current", "fitness", "score" ]
4e73125ff90bfeeae359a5ab1badba8894d70eaa
https://github.com/ECRL/ecabc/blob/4e73125ff90bfeeae359a5ab1badba8894d70eaa/ecabc/abc.py#L480-L498
train
ECRL/ecabc
ecabc/abc.py
ABC.__update
def __update(self, score, values, error): '''Update the best score and values if the given score is better than the current best score Args: score (float): new score to evaluate values (list): new value ranges to evaluate error (float): new fitness function r...
python
def __update(self, score, values, error): '''Update the best score and values if the given score is better than the current best score Args: score (float): new score to evaluate values (list): new value ranges to evaluate error (float): new fitness function r...
[ "def", "__update", "(", "self", ",", "score", ",", "values", ",", "error", ")", ":", "if", "self", ".", "_minimize", ":", "if", "self", ".", "_best_score", "is", "None", "or", "score", ">", "self", ".", "_best_score", ":", "self", ".", "_best_score", ...
Update the best score and values if the given score is better than the current best score Args: score (float): new score to evaluate values (list): new value ranges to evaluate error (float): new fitness function return value to evaluate Returns: ...
[ "Update", "the", "best", "score", "and", "values", "if", "the", "given", "score", "is", "better", "than", "the", "current", "best", "score" ]
4e73125ff90bfeeae359a5ab1badba8894d70eaa
https://github.com/ECRL/ecabc/blob/4e73125ff90bfeeae359a5ab1badba8894d70eaa/ecabc/abc.py#L500-L537
train
ECRL/ecabc
ecabc/abc.py
ABC.__gen_random_values
def __gen_random_values(self): '''Generate random values based on supplied value ranges Returns: list: random values, one per tunable variable ''' values = [] if self._value_ranges is None: self._logger.log( 'crit', 'Must ...
python
def __gen_random_values(self): '''Generate random values based on supplied value ranges Returns: list: random values, one per tunable variable ''' values = [] if self._value_ranges is None: self._logger.log( 'crit', 'Must ...
[ "def", "__gen_random_values", "(", "self", ")", ":", "values", "=", "[", "]", "if", "self", ".", "_value_ranges", "is", "None", ":", "self", ".", "_logger", ".", "log", "(", "'crit'", ",", "'Must set the type/range of possible values'", ")", "raise", "RuntimeE...
Generate random values based on supplied value ranges Returns: list: random values, one per tunable variable
[ "Generate", "random", "values", "based", "on", "supplied", "value", "ranges" ]
4e73125ff90bfeeae359a5ab1badba8894d70eaa
https://github.com/ECRL/ecabc/blob/4e73125ff90bfeeae359a5ab1badba8894d70eaa/ecabc/abc.py#L539-L567
train
ECRL/ecabc
ecabc/abc.py
ABC.__verify_ready
def __verify_ready(self, creating=False): '''Some cleanup, ensures that everything is set up properly to avoid random errors during execution Args: creating (bool): True if currently creating employer bees, False for checking all other operations ''' ...
python
def __verify_ready(self, creating=False): '''Some cleanup, ensures that everything is set up properly to avoid random errors during execution Args: creating (bool): True if currently creating employer bees, False for checking all other operations ''' ...
[ "def", "__verify_ready", "(", "self", ",", "creating", "=", "False", ")", ":", "if", "len", "(", "self", ".", "_value_ranges", ")", "==", "0", ":", "self", ".", "_logger", ".", "log", "(", "'crit'", ",", "'Attribute value_ranges must have at least one value'",...
Some cleanup, ensures that everything is set up properly to avoid random errors during execution Args: creating (bool): True if currently creating employer bees, False for checking all other operations
[ "Some", "cleanup", "ensures", "that", "everything", "is", "set", "up", "properly", "to", "avoid", "random", "errors", "during", "execution" ]
4e73125ff90bfeeae359a5ab1badba8894d70eaa
https://github.com/ECRL/ecabc/blob/4e73125ff90bfeeae359a5ab1badba8894d70eaa/ecabc/abc.py#L569-L588
train
ECRL/ecabc
ecabc/abc.py
ABC.import_settings
def import_settings(self, filename): '''Import settings from a JSON file Args: filename (string): name of the file to import from ''' if not os.path.isfile(filename): self._logger.log( 'error', 'File: {} not found, continuing with...
python
def import_settings(self, filename): '''Import settings from a JSON file Args: filename (string): name of the file to import from ''' if not os.path.isfile(filename): self._logger.log( 'error', 'File: {} not found, continuing with...
[ "def", "import_settings", "(", "self", ",", "filename", ")", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "filename", ")", ":", "self", ".", "_logger", ".", "log", "(", "'error'", ",", "'File: {} not found, continuing with default settings'", ".", ...
Import settings from a JSON file Args: filename (string): name of the file to import from
[ "Import", "settings", "from", "a", "JSON", "file" ]
4e73125ff90bfeeae359a5ab1badba8894d70eaa
https://github.com/ECRL/ecabc/blob/4e73125ff90bfeeae359a5ab1badba8894d70eaa/ecabc/abc.py#L590-L618
train
ECRL/ecabc
ecabc/abc.py
ABC.save_settings
def save_settings(self, filename): '''Save settings to a JSON file Arge: filename (string): name of the file to save to ''' data = dict() data['valueRanges'] = self._value_ranges data['best_values'] = [str(value) for value in self._best_values] data[...
python
def save_settings(self, filename): '''Save settings to a JSON file Arge: filename (string): name of the file to save to ''' data = dict() data['valueRanges'] = self._value_ranges data['best_values'] = [str(value) for value in self._best_values] data[...
[ "def", "save_settings", "(", "self", ",", "filename", ")", ":", "data", "=", "dict", "(", ")", "data", "[", "'valueRanges'", "]", "=", "self", ".", "_value_ranges", "data", "[", "'best_values'", "]", "=", "[", "str", "(", "value", ")", "for", "value", ...
Save settings to a JSON file Arge: filename (string): name of the file to save to
[ "Save", "settings", "to", "a", "JSON", "file" ]
4e73125ff90bfeeae359a5ab1badba8894d70eaa
https://github.com/ECRL/ecabc/blob/4e73125ff90bfeeae359a5ab1badba8894d70eaa/ecabc/abc.py#L620-L636
train
ECRL/ecabc
ecabc/bees.py
EmployerBee.get_score
def get_score(self, error=None): '''Calculate bee's fitness score given a value returned by the fitness function Args: error (float): value returned by the fitness function Returns: float: derived fitness score ''' if error is not None: ...
python
def get_score(self, error=None): '''Calculate bee's fitness score given a value returned by the fitness function Args: error (float): value returned by the fitness function Returns: float: derived fitness score ''' if error is not None: ...
[ "def", "get_score", "(", "self", ",", "error", "=", "None", ")", ":", "if", "error", "is", "not", "None", ":", "self", ".", "error", "=", "error", "if", "self", ".", "error", ">=", "0", ":", "return", "1", "/", "(", "self", ".", "error", "+", "...
Calculate bee's fitness score given a value returned by the fitness function Args: error (float): value returned by the fitness function Returns: float: derived fitness score
[ "Calculate", "bee", "s", "fitness", "score", "given", "a", "value", "returned", "by", "the", "fitness", "function" ]
4e73125ff90bfeeae359a5ab1badba8894d70eaa
https://github.com/ECRL/ecabc/blob/4e73125ff90bfeeae359a5ab1badba8894d70eaa/ecabc/bees.py#L40-L56
train
foremast/foremast
src/foremast/dns/create_dns.py
SpinnakerDns.create_elb_dns
def create_elb_dns(self, regionspecific=False): """Create dns entries in route53. Args: regionspecific (bool): The DNS entry should have region on it Returns: str: Auto-generated DNS name for the Elastic Load Balancer. """ if regionspecific: ...
python
def create_elb_dns(self, regionspecific=False): """Create dns entries in route53. Args: regionspecific (bool): The DNS entry should have region on it Returns: str: Auto-generated DNS name for the Elastic Load Balancer. """ if regionspecific: ...
[ "def", "create_elb_dns", "(", "self", ",", "regionspecific", "=", "False", ")", ":", "if", "regionspecific", ":", "dns_elb", "=", "self", ".", "generated", ".", "dns", "(", ")", "[", "'elb_region'", "]", "else", ":", "dns_elb", "=", "self", ".", "generat...
Create dns entries in route53. Args: regionspecific (bool): The DNS entry should have region on it Returns: str: Auto-generated DNS name for the Elastic Load Balancer.
[ "Create", "dns", "entries", "in", "route53", "." ]
fb70f29b8ce532f061685a17d120486e47b215ba
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/dns/create_dns.py#L55-L85
train
foremast/foremast
src/foremast/dns/create_dns.py
SpinnakerDns.create_failover_dns
def create_failover_dns(self, primary_region='us-east-1'): """Create dns entries in route53 for multiregion failover setups. Args: primary_region (str): primary AWS region for failover Returns: Auto-generated DNS name. """ dns_record = self.generated.dns(...
python
def create_failover_dns(self, primary_region='us-east-1'): """Create dns entries in route53 for multiregion failover setups. Args: primary_region (str): primary AWS region for failover Returns: Auto-generated DNS name. """ dns_record = self.generated.dns(...
[ "def", "create_failover_dns", "(", "self", ",", "primary_region", "=", "'us-east-1'", ")", ":", "dns_record", "=", "self", ".", "generated", ".", "dns", "(", ")", "[", "'global'", "]", "zone_ids", "=", "get_dns_zone_ids", "(", "env", "=", "self", ".", "env...
Create dns entries in route53 for multiregion failover setups. Args: primary_region (str): primary AWS region for failover Returns: Auto-generated DNS name.
[ "Create", "dns", "entries", "in", "route53", "for", "multiregion", "failover", "setups", "." ]
fb70f29b8ce532f061685a17d120486e47b215ba
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/dns/create_dns.py#L87-L121
train
foremast/foremast
src/foremast/elb/format_listeners.py
format_listeners
def format_listeners(elb_settings=None, env='dev', region='us-east-1'): """Format ELB Listeners into standard list. Args: elb_settings (dict): ELB settings including ELB Listeners to add, e.g.:: # old { "certificate": null, ...
python
def format_listeners(elb_settings=None, env='dev', region='us-east-1'): """Format ELB Listeners into standard list. Args: elb_settings (dict): ELB settings including ELB Listeners to add, e.g.:: # old { "certificate": null, ...
[ "def", "format_listeners", "(", "elb_settings", "=", "None", ",", "env", "=", "'dev'", ",", "region", "=", "'us-east-1'", ")", ":", "LOG", ".", "debug", "(", "'ELB settings:\\n%s'", ",", "elb_settings", ")", "credential", "=", "get_env_credential", "(", "env",...
Format ELB Listeners into standard list. Args: elb_settings (dict): ELB settings including ELB Listeners to add, e.g.:: # old { "certificate": null, "i_port": 8080, "lb_port": 80, "s...
[ "Format", "ELB", "Listeners", "into", "standard", "list", "." ]
fb70f29b8ce532f061685a17d120486e47b215ba
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/elb/format_listeners.py#L26-L128
train
foremast/foremast
src/foremast/elb/format_listeners.py
format_cert_name
def format_cert_name(env='', account='', region='', certificate=None): """Format the SSL certificate name into ARN for ELB. Args: env (str): Account environment name account (str): Account number for ARN region (str): AWS Region. certificate (str): Name of SSL certificate R...
python
def format_cert_name(env='', account='', region='', certificate=None): """Format the SSL certificate name into ARN for ELB. Args: env (str): Account environment name account (str): Account number for ARN region (str): AWS Region. certificate (str): Name of SSL certificate R...
[ "def", "format_cert_name", "(", "env", "=", "''", ",", "account", "=", "''", ",", "region", "=", "''", ",", "certificate", "=", "None", ")", ":", "cert_name", "=", "None", "if", "certificate", ":", "if", "certificate", ".", "startswith", "(", "'arn'", ...
Format the SSL certificate name into ARN for ELB. Args: env (str): Account environment name account (str): Account number for ARN region (str): AWS Region. certificate (str): Name of SSL certificate Returns: str: Fully qualified ARN for SSL certificate None: Cer...
[ "Format", "the", "SSL", "certificate", "name", "into", "ARN", "for", "ELB", "." ]
fb70f29b8ce532f061685a17d120486e47b215ba
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/elb/format_listeners.py#L131-L161
train
foremast/foremast
src/foremast/elb/format_listeners.py
generate_custom_cert_name
def generate_custom_cert_name(env='', region='', account='', certificate=None): """Generate a custom TLS Cert name based on a template. Args: env (str): Account environment name region (str): AWS Region. account (str): Account number for ARN. certificate (str): Name of SSL certi...
python
def generate_custom_cert_name(env='', region='', account='', certificate=None): """Generate a custom TLS Cert name based on a template. Args: env (str): Account environment name region (str): AWS Region. account (str): Account number for ARN. certificate (str): Name of SSL certi...
[ "def", "generate_custom_cert_name", "(", "env", "=", "''", ",", "region", "=", "''", ",", "account", "=", "''", ",", "certificate", "=", "None", ")", ":", "cert_name", "=", "None", "template_kwargs", "=", "{", "'account'", ":", "account", ",", "'name'", ...
Generate a custom TLS Cert name based on a template. Args: env (str): Account environment name region (str): AWS Region. account (str): Account number for ARN. certificate (str): Name of SSL certificate. Returns: str: Fully qualified ARN for SSL certificate. Non...
[ "Generate", "a", "custom", "TLS", "Cert", "name", "based", "on", "a", "template", "." ]
fb70f29b8ce532f061685a17d120486e47b215ba
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/elb/format_listeners.py#L164-L213
train
foremast/foremast
src/foremast/slacknotify/__main__.py
main
def main(): """Send Slack notification to a configured channel.""" logging.basicConfig(format=LOGGING_FORMAT) log = logging.getLogger(__name__) parser = argparse.ArgumentParser() add_debug(parser) add_app(parser) add_env(parser) add_properties(parser) args = parser.parse_args() ...
python
def main(): """Send Slack notification to a configured channel.""" logging.basicConfig(format=LOGGING_FORMAT) log = logging.getLogger(__name__) parser = argparse.ArgumentParser() add_debug(parser) add_app(parser) add_env(parser) add_properties(parser) args = parser.parse_args() ...
[ "def", "main", "(", ")", ":", "logging", ".", "basicConfig", "(", "format", "=", "LOGGING_FORMAT", ")", "log", "=", "logging", ".", "getLogger", "(", "__name__", ")", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "add_debug", "(", "parser", ...
Send Slack notification to a configured channel.
[ "Send", "Slack", "notification", "to", "a", "configured", "channel", "." ]
fb70f29b8ce532f061685a17d120486e47b215ba
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/slacknotify/__main__.py#L28-L49
train
foremast/foremast
src/foremast/destroyer.py
main
def main(): # noqa """Attempt to fully destroy AWS Resources for a Spinnaker Application.""" logging.basicConfig(format=LOGGING_FORMAT) parser = argparse.ArgumentParser(description=main.__doc__) add_debug(parser) add_app(parser) args = parser.parse_args() if args.debug == logging.DEBUG: ...
python
def main(): # noqa """Attempt to fully destroy AWS Resources for a Spinnaker Application.""" logging.basicConfig(format=LOGGING_FORMAT) parser = argparse.ArgumentParser(description=main.__doc__) add_debug(parser) add_app(parser) args = parser.parse_args() if args.debug == logging.DEBUG: ...
[ "def", "main", "(", ")", ":", "logging", ".", "basicConfig", "(", "format", "=", "LOGGING_FORMAT", ")", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "main", ".", "__doc__", ")", "add_debug", "(", "parser", ")", "add_app", "(",...
Attempt to fully destroy AWS Resources for a Spinnaker Application.
[ "Attempt", "to", "fully", "destroy", "AWS", "Resources", "for", "a", "Spinnaker", "Application", "." ]
fb70f29b8ce532f061685a17d120486e47b215ba
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/destroyer.py#L34-L79
train
foremast/foremast
src/foremast/pipeline/construct_pipeline_block.py
check_provider_healthcheck
def check_provider_healthcheck(settings, default_provider='Discovery'): """Set Provider Health Check when specified. Returns: collections.namedtuple: **ProviderHealthCheck** with attributes: * providers (list): Providers set to use native Health Check. * has_healthcheck (bool):...
python
def check_provider_healthcheck(settings, default_provider='Discovery'): """Set Provider Health Check when specified. Returns: collections.namedtuple: **ProviderHealthCheck** with attributes: * providers (list): Providers set to use native Health Check. * has_healthcheck (bool):...
[ "def", "check_provider_healthcheck", "(", "settings", ",", "default_provider", "=", "'Discovery'", ")", ":", "ProviderHealthCheck", "=", "collections", ".", "namedtuple", "(", "'ProviderHealthCheck'", ",", "[", "'providers'", ",", "'has_healthcheck'", "]", ")", "eurek...
Set Provider Health Check when specified. Returns: collections.namedtuple: **ProviderHealthCheck** with attributes: * providers (list): Providers set to use native Health Check. * has_healthcheck (bool): If any native Health Checks requested.
[ "Set", "Provider", "Health", "Check", "when", "specified", "." ]
fb70f29b8ce532f061685a17d120486e47b215ba
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/pipeline/construct_pipeline_block.py#L29-L70
train
foremast/foremast
src/foremast/pipeline/construct_pipeline_block.py
get_template_name
def get_template_name(env, pipeline_type): """Generates the correct template name based on pipeline type Args: env (str): environment to generate templates for pipeline_type (str): Type of pipeline like ec2 or lambda Returns: str: Name of template """ pipeline_base = 'pipel...
python
def get_template_name(env, pipeline_type): """Generates the correct template name based on pipeline type Args: env (str): environment to generate templates for pipeline_type (str): Type of pipeline like ec2 or lambda Returns: str: Name of template """ pipeline_base = 'pipel...
[ "def", "get_template_name", "(", "env", ",", "pipeline_type", ")", ":", "pipeline_base", "=", "'pipeline/pipeline'", "template_name_format", "=", "'{pipeline_base}'", "if", "env", ".", "startswith", "(", "'prod'", ")", ":", "template_name_format", "=", "template_name_...
Generates the correct template name based on pipeline type Args: env (str): environment to generate templates for pipeline_type (str): Type of pipeline like ec2 or lambda Returns: str: Name of template
[ "Generates", "the", "correct", "template", "name", "based", "on", "pipeline", "type" ]
fb70f29b8ce532f061685a17d120486e47b215ba
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/pipeline/construct_pipeline_block.py#L73-L96
train
foremast/foremast
src/foremast/pipeline/construct_pipeline_block.py
ec2_pipeline_setup
def ec2_pipeline_setup( generated=None, project='', settings=None, env='', pipeline_type='', region='', region_subnets=None, ): """Handles ec2 pipeline data setup Args: generated (gogoutils.Generator): Generated naming formats. project (st...
python
def ec2_pipeline_setup( generated=None, project='', settings=None, env='', pipeline_type='', region='', region_subnets=None, ): """Handles ec2 pipeline data setup Args: generated (gogoutils.Generator): Generated naming formats. project (st...
[ "def", "ec2_pipeline_setup", "(", "generated", "=", "None", ",", "project", "=", "''", ",", "settings", "=", "None", ",", "env", "=", "''", ",", "pipeline_type", "=", "''", ",", "region", "=", "''", ",", "region_subnets", "=", "None", ",", ")", ":", ...
Handles ec2 pipeline data setup Args: generated (gogoutils.Generator): Generated naming formats. project (str): Group name of application settings (dict): Environment settings from configurations. env (str): Deploy environment name, e.g. dev, stage, prod. pipeline_type (str)...
[ "Handles", "ec2", "pipeline", "data", "setup" ]
fb70f29b8ce532f061685a17d120486e47b215ba
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/pipeline/construct_pipeline_block.py#L169-L275
train
foremast/foremast
src/foremast/pipeline/create_pipeline_manual.py
SpinnakerPipelineManual.create_pipeline
def create_pipeline(self): """Use JSON files to create Pipelines.""" pipelines = self.settings['pipeline']['pipeline_files'] self.log.info('Uploading manual Pipelines: %s', pipelines) lookup = FileLookup(git_short=self.generated.gitlab()['main'], runway_dir=self.runway_dir) for...
python
def create_pipeline(self): """Use JSON files to create Pipelines.""" pipelines = self.settings['pipeline']['pipeline_files'] self.log.info('Uploading manual Pipelines: %s', pipelines) lookup = FileLookup(git_short=self.generated.gitlab()['main'], runway_dir=self.runway_dir) for...
[ "def", "create_pipeline", "(", "self", ")", ":", "pipelines", "=", "self", ".", "settings", "[", "'pipeline'", "]", "[", "'pipeline_files'", "]", "self", ".", "log", ".", "info", "(", "'Uploading manual Pipelines: %s'", ",", "pipelines", ")", "lookup", "=", ...
Use JSON files to create Pipelines.
[ "Use", "JSON", "files", "to", "create", "Pipelines", "." ]
fb70f29b8ce532f061685a17d120486e47b215ba
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/pipeline/create_pipeline_manual.py#L25-L42
train
foremast/foremast
src/foremast/pipeline/__main__.py
main
def main(): """Creates a pipeline in Spinnaker""" logging.basicConfig(format=LOGGING_FORMAT) log = logging.getLogger(__name__) parser = argparse.ArgumentParser() add_debug(parser) add_app(parser) add_properties(parser) parser.add_argument('-b', '--base', help='Base AMI name to use, e.g....
python
def main(): """Creates a pipeline in Spinnaker""" logging.basicConfig(format=LOGGING_FORMAT) log = logging.getLogger(__name__) parser = argparse.ArgumentParser() add_debug(parser) add_app(parser) add_properties(parser) parser.add_argument('-b', '--base', help='Base AMI name to use, e.g....
[ "def", "main", "(", ")", ":", "logging", ".", "basicConfig", "(", "format", "=", "LOGGING_FORMAT", ")", "log", "=", "logging", ".", "getLogger", "(", "__name__", ")", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "add_debug", "(", "parser", ...
Creates a pipeline in Spinnaker
[ "Creates", "a", "pipeline", "in", "Spinnaker" ]
fb70f29b8ce532f061685a17d120486e47b215ba
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/pipeline/__main__.py#L31-L71
train
foremast/foremast
src/foremast/configs/outputs.py
convert_ini
def convert_ini(config_dict): """Convert _config_dict_ into a list of INI formatted strings. Args: config_dict (dict): Configuration dictionary to be flattened. Returns: (list) Lines to be written to a file in the format of KEY1_KEY2=value. """ config_lines = [] for env, confi...
python
def convert_ini(config_dict): """Convert _config_dict_ into a list of INI formatted strings. Args: config_dict (dict): Configuration dictionary to be flattened. Returns: (list) Lines to be written to a file in the format of KEY1_KEY2=value. """ config_lines = [] for env, confi...
[ "def", "convert_ini", "(", "config_dict", ")", ":", "config_lines", "=", "[", "]", "for", "env", ",", "configs", "in", "sorted", "(", "config_dict", ".", "items", "(", ")", ")", ":", "for", "resource", ",", "app_properties", "in", "sorted", "(", "configs...
Convert _config_dict_ into a list of INI formatted strings. Args: config_dict (dict): Configuration dictionary to be flattened. Returns: (list) Lines to be written to a file in the format of KEY1_KEY2=value.
[ "Convert", "_config_dict_", "into", "a", "list", "of", "INI", "formatted", "strings", "." ]
fb70f29b8ce532f061685a17d120486e47b215ba
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/configs/outputs.py#L29-L63
train
foremast/foremast
src/foremast/configs/outputs.py
write_variables
def write_variables(app_configs=None, out_file='', git_short=''): """Append _application.json_ configs to _out_file_, .exports, and .json. Variables are written in INI style, e.g. UPPER_CASE=value. The .exports file contains 'export' prepended to each line for easy sourcing. The .json file is a minifie...
python
def write_variables(app_configs=None, out_file='', git_short=''): """Append _application.json_ configs to _out_file_, .exports, and .json. Variables are written in INI style, e.g. UPPER_CASE=value. The .exports file contains 'export' prepended to each line for easy sourcing. The .json file is a minifie...
[ "def", "write_variables", "(", "app_configs", "=", "None", ",", "out_file", "=", "''", ",", "git_short", "=", "''", ")", ":", "generated", "=", "gogoutils", ".", "Generator", "(", "*", "gogoutils", ".", "Parser", "(", "git_short", ")", ".", "parse_url", ...
Append _application.json_ configs to _out_file_, .exports, and .json. Variables are written in INI style, e.g. UPPER_CASE=value. The .exports file contains 'export' prepended to each line for easy sourcing. The .json file is a minified representation of the combined configurations. Args: app_c...
[ "Append", "_application", ".", "json_", "configs", "to", "_out_file_", ".", "exports", "and", ".", "json", "." ]
fb70f29b8ce532f061685a17d120486e47b215ba
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/configs/outputs.py#L66-L122
train
foremast/foremast
src/foremast/utils/get_sns_subscriptions.py
get_sns_subscriptions
def get_sns_subscriptions(app_name, env, region): """List SNS lambda subscriptions. Returns: list: List of Lambda subscribed SNS ARNs. """ session = boto3.Session(profile_name=env, region_name=region) sns_client = session.client('sns') lambda_alias_arn = get_lambda_alias_arn(app=app_n...
python
def get_sns_subscriptions(app_name, env, region): """List SNS lambda subscriptions. Returns: list: List of Lambda subscribed SNS ARNs. """ session = boto3.Session(profile_name=env, region_name=region) sns_client = session.client('sns') lambda_alias_arn = get_lambda_alias_arn(app=app_n...
[ "def", "get_sns_subscriptions", "(", "app_name", ",", "env", ",", "region", ")", ":", "session", "=", "boto3", ".", "Session", "(", "profile_name", "=", "env", ",", "region_name", "=", "region", ")", "sns_client", "=", "session", ".", "client", "(", "'sns'...
List SNS lambda subscriptions. Returns: list: List of Lambda subscribed SNS ARNs.
[ "List", "SNS", "lambda", "subscriptions", "." ]
fb70f29b8ce532f061685a17d120486e47b215ba
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/utils/get_sns_subscriptions.py#L11-L33
train
foremast/foremast
src/foremast/awslambda/cloudwatch_log_event/destroy_cloudwatch_log_event/destroy_cloudwatch_log_event.py
destroy_cloudwatch_log_event
def destroy_cloudwatch_log_event(app='', env='dev', region=''): """Destroy Cloudwatch log event. Args: app (str): Spinnaker Application name. env (str): Deployment environment. region (str): AWS region. Returns: bool: True upon successful completion. """ session = b...
python
def destroy_cloudwatch_log_event(app='', env='dev', region=''): """Destroy Cloudwatch log event. Args: app (str): Spinnaker Application name. env (str): Deployment environment. region (str): AWS region. Returns: bool: True upon successful completion. """ session = b...
[ "def", "destroy_cloudwatch_log_event", "(", "app", "=", "''", ",", "env", "=", "'dev'", ",", "region", "=", "''", ")", ":", "session", "=", "boto3", ".", "Session", "(", "profile_name", "=", "env", ",", "region_name", "=", "region", ")", "cloudwatch_client...
Destroy Cloudwatch log event. Args: app (str): Spinnaker Application name. env (str): Deployment environment. region (str): AWS region. Returns: bool: True upon successful completion.
[ "Destroy", "Cloudwatch", "log", "event", "." ]
fb70f29b8ce532f061685a17d120486e47b215ba
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/awslambda/cloudwatch_log_event/destroy_cloudwatch_log_event/destroy_cloudwatch_log_event.py#L24-L42
train
foremast/foremast
src/foremast/app/create_app.py
SpinnakerApp.get_accounts
def get_accounts(self, provider='aws'): """Get Accounts added to Spinnaker. Args: provider (str): What provider to find accounts for. Returns: list: list of dicts of Spinnaker credentials matching _provider_. Raises: AssertionError: Failure getting ...
python
def get_accounts(self, provider='aws'): """Get Accounts added to Spinnaker. Args: provider (str): What provider to find accounts for. Returns: list: list of dicts of Spinnaker credentials matching _provider_. Raises: AssertionError: Failure getting ...
[ "def", "get_accounts", "(", "self", ",", "provider", "=", "'aws'", ")", ":", "url", "=", "'{gate}/credentials'", ".", "format", "(", "gate", "=", "API_URL", ")", "response", "=", "requests", ".", "get", "(", "url", ",", "verify", "=", "GATE_CA_BUNDLE", "...
Get Accounts added to Spinnaker. Args: provider (str): What provider to find accounts for. Returns: list: list of dicts of Spinnaker credentials matching _provider_. Raises: AssertionError: Failure getting accounts from Spinnaker.
[ "Get", "Accounts", "added", "to", "Spinnaker", "." ]
fb70f29b8ce532f061685a17d120486e47b215ba
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/app/create_app.py#L55-L82
train
foremast/foremast
src/foremast/app/create_app.py
SpinnakerApp.create_app
def create_app(self): """Send a POST to spinnaker to create a new application with class variables. Raises: AssertionError: Application creation failed. """ self.appinfo['accounts'] = self.get_accounts() self.log.debug('Pipeline Config\n%s', pformat(self.pipeline_con...
python
def create_app(self): """Send a POST to spinnaker to create a new application with class variables. Raises: AssertionError: Application creation failed. """ self.appinfo['accounts'] = self.get_accounts() self.log.debug('Pipeline Config\n%s', pformat(self.pipeline_con...
[ "def", "create_app", "(", "self", ")", ":", "self", ".", "appinfo", "[", "'accounts'", "]", "=", "self", ".", "get_accounts", "(", ")", "self", ".", "log", ".", "debug", "(", "'Pipeline Config\\n%s'", ",", "pformat", "(", "self", ".", "pipeline_config", ...
Send a POST to spinnaker to create a new application with class variables. Raises: AssertionError: Application creation failed.
[ "Send", "a", "POST", "to", "spinnaker", "to", "create", "a", "new", "application", "with", "class", "variables", "." ]
fb70f29b8ce532f061685a17d120486e47b215ba
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/app/create_app.py#L84-L97
train