docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Get video frame at the specified index. Args: index (int): Positional index of the desired frame.
def get_frame(self, index): frame_num = self.frame_index[index] onset = float(frame_num) / self.fps if index < self.n_frames - 1: next_frame_num = self.frame_index[index + 1] end = float(next_frame_num) / self.fps else: end = float(self.dura...
440,127
Save source video to file. Args: path (str): Filename to save to. Notes: Saves entire source video to file, not just currently selected frames.
def save(self, path): # IMPORTANT WARNING: saves entire source video self.clip.write_videofile(path, audio_fps=self.clip.audio.fps)
440,128
Overrides the default behavior by giving access to the onset argument. Args: index (int): Positional index of the desired frame. onset (float): Onset (in seconds) of the desired frame.
def get_frame(self, index=None, onset=None): if onset: index = int(onset * self.fps) return super(VideoStim, self).get_frame(index)
440,130
Run transformers through a battery of stimuli, and check if output has changed. Store results in csv file for comparison. Args: transformers (list): A list of tuples of transformer names and dictionary of parameters to instantiate with (or empty dict). datastore (str): Filepath of C...
def check_updates(transformers, datastore=None, stimuli=None): # Find datastore file datastore = datastore or expanduser('~/.pliers_updates') prior_data = pd.read_csv(datastore) if exists(datastore) else None # Load stimuli stimuli = stimuli or glob.glob( join(dirname(realpath(__file__...
440,160
r"""Strip padding from decrypted value. Remove number indicated by padding e.g. if last is '\x0e' then ord('\x0e') == 14, so take off 14. Args: decrypted: decrypted value Returns: Decrypted stripped of junk padding
def clean(decrypted: bytes) -> str: r last = decrypted[-1] if isinstance(last, int): return decrypted[:-last].decode('utf8') return decrypted[:-ord(last)].decode('utf8')
440,533
Decrypt Chrome/Chromium's encrypted cookies. Args: encrypted_value: Encrypted cookie from Chrome/Chromium's cookie file key: Key to decrypt encrypted_value init_vector: Initialization vector for decrypting encrypted_value Returns: Decrypted value of encrypted_value
def chrome_decrypt(encrypted_value: bytes, key: bytes, init_vector: bytes) \ -> str: # Encrypted cookies should be prefixed with 'v10' or 'v11' according to the # Chromium code. Strip it off. encrypted_value = encrypted_value[3:] cipher = AES.new(key, AES.MODE_CBC, IV=init_vector) decr...
440,534
Get settings for getting Chrome/Chromium cookies on OSX. Args: browser: Either "Chrome" or "Chromium" Returns: Config dictionary for Chrome/Chromium cookie decryption
def get_osx_config(browser: str) -> dict: # Verify supported browser, fail early otherwise if browser.lower() == 'chrome': cookie_file = ('~/Library/Application Support/Google/Chrome/Default/' 'Cookies') elif browser.lower() == "chromium": cookie_file = '~/Library...
440,535
Get the settings for Chrome/Chromium cookies on Linux. Args: browser: Either "Chrome" or "Chromium" Returns: Config dictionary for Chrome/Chromium cookie decryption
def get_linux_config(browser: str) -> dict: # Verify supported browser, fail early otherwise if browser.lower() == 'chrome': cookie_file = '~/.config/google-chrome/Default/Cookies' elif browser.lower() == "chromium": cookie_file = '~/.config/chromium/Default/Cookies' else: r...
440,536
Retrieve cookies from Chrome/Chromium on OSX or Linux. Args: url: Domain from which to retrieve cookies, starting with http(s) cookie_file: Path to alternate file to search for cookies browser: Name of the browser's cookies to read ('Chrome' or 'Chromium') curl_cookie_file: Path to ...
def chrome_cookies( url: str, cookie_file: str = None, browser: str = "Chrome", curl_cookie_file: str = None, ) -> dict: # If running Chrome on OSX if sys.platform == 'darwin': config = get_osx_config(browser) elif sys.platform.startswith('linux'): ...
440,537
Check that the given setpointvalue is valid. Args: * setpointvalue (numerical): The setpoint value to be checked. Must be positive. * maxvalue (numerical): Upper limit for setpoint value. Must be positive. Raises: TypeError, ValueError
def _checkSetpointValue( setpointvalue, maxvalue ): if maxvalue is None: raise TypeError('The maxvalue (for the setpoint) must not be None!') minimalmodbus._checkNumerical(setpointvalue, minvalue=0, maxvalue=maxvalue, description='setpoint value')
440,557
Check that the given timevalue is valid. Args: * timevalue (numerical): The time value to be checked. Must be positive. * maxvalue (numerical): Upper limit for time value. Must be positive. Raises: TypeError, ValueError
def _checkTimeValue( timevalue, maxvalue ): if maxvalue is None: raise TypeError('The maxvalue (for the time value) must not be None!') minimalmodbus._checkNumerical(timevalue, minvalue=0, maxvalue=maxvalue, description='time value')
440,558
Calculate the register address for pattern related parameters. Args: * registertype (string): The type of parameter, for example 'cycles'. Allowed are the keys from :data:`REGISTER_START`. * patternnumber (int): The pattern number. * stepnumber (int): The step number. Use Non...
def _calculateRegisterAddress( registertype, patternnumber, stepnumber = None): if stepnumber is None: stepnumber = 0 # Argument checking _checkPatternNumber( patternnumber ) _checkStepNumber( stepnumber ) if not registertype in list(REGISTER_START.keys()): # To comply with bo...
440,559
Set the setpoint. Args: setpointvalue (float): Setpoint [most often in degrees]
def set_setpoint(self, setpointvalue): _checkSetpointValue( setpointvalue, self.setpoint_max ) self.write_register( 4097, setpointvalue, 1)
440,561
Set the control method using the corresponding integer value. Args: modevalue(int): 0-3 The modevalue is one of the keys in :data:`CONTROL_MODES`.
def set_control_mode(self, modevalue): minimalmodbus._checkInt(modevalue, minvalue=0, maxvalue=3, description='control mode') self.write_register(4101, modevalue)
440,563
Set the setpoint value for a step. Args: * patternnumber (integer): 0-7 * stepnumber (integer): 0-7 * setpointvalue (float): Setpoint value
def set_pattern_step_setpoint(self, patternnumber, stepnumber, setpointvalue): _checkPatternNumber(patternnumber) _checkStepNumber(stepnumber) _checkSetpointValue(setpointvalue, self.setpoint_max) address = _calculateRegisterAddress('setpoint', patternnumber, stepnumber...
440,564
Get the step time. Args: * patternnumber (integer): 0-7 * stepnumber (integer): 0-7 Returns: The step time (int??).
def get_pattern_step_time(self, patternnumber, stepnumber): _checkPatternNumber(patternnumber) _checkStepNumber(stepnumber) address = _calculateRegisterAddress('time', patternnumber, stepnumber) return self.read_register(address, 0)
440,565
Set the step time. Args: * patternnumber (integer): 0-7 * stepnumber (integer): 0-7 * timevalue (integer??): 0-900
def set_pattern_step_time(self, patternnumber, stepnumber, timevalue): _checkPatternNumber(patternnumber) _checkStepNumber(stepnumber) _checkTimeValue(timevalue, self.time_max) address = _calculateRegisterAddress('time', patternnumber, stepnumber) self.write_reg...
440,566
Get the 'actual step' parameter for a given pattern. Args: patternnumber (integer): 0-7 Returns: The 'actual step' parameter (int).
def get_pattern_actual_step(self, patternnumber): _checkPatternNumber(patternnumber) address = _calculateRegisterAddress('actualstep', patternnumber) return self.read_register(address, 0)
440,567
Set the 'actual step' parameter for a given pattern. Args: * patternnumber (integer): 0-7 * value (integer): 0-7
def set_pattern_actual_step(self, patternnumber, value): _checkPatternNumber(patternnumber) _checkStepNumber(value) address = _calculateRegisterAddress('actualstep', patternnumber) self.write_register(address, value, 0)
440,568
Get the number of additional cycles for a given pattern. Args: patternnumber (integer): 0-7 Returns: The number of additional cycles (int).
def get_pattern_additional_cycles(self, patternnumber): _checkPatternNumber(patternnumber) address = _calculateRegisterAddress('cycles', patternnumber) return self.read_register(address)
440,569
Set the number of additional cycles for a given pattern. Args: * patternnumber (integer): 0-7 * value (integer): 0-99
def set_pattern_additional_cycles(self, patternnumber, value): _checkPatternNumber(patternnumber) minimalmodbus._checkInt(value, minvalue=0, maxvalue=99, description='number of additional cycles') address = _calculateRegisterAddress('cycles', patternnumber) self.wr...
440,570
Get the 'linked pattern' value for a given pattern. Args: patternnumber (integer): From 0-7 Returns: The 'linked pattern' value (int).
def get_pattern_link_topattern(self, patternnumber): _checkPatternNumber(patternnumber) address = _calculateRegisterAddress('linkpattern', patternnumber) return self.read_register(address)
440,571
Get all variables for a given pattern at one time. Args: patternnumber (integer): 0-7 Returns: A descriptive multiline string.
def get_all_pattern_variables(self, patternnumber): _checkPatternNumber(patternnumber) outputstring = '' for stepnumber in range(8): outputstring += 'SP{0}: {1} Time{0}: {2}\n'.format(stepnumber, \ self.get_pattern_step_setpoint( patternnumber, step...
440,572
Set all variables for a given pattern at one time. Args: * patternnumber (integer): 0-7 * sp[*n*] (float): setpoint value for step *n* * ti[*n*] (integer??): step time for step *n*, 0-900 * actual_step (int): ? * additional_cycles(int): ? ...
def set_all_pattern_variables(self, patternnumber, \ sp0, ti0, sp1, ti1, sp2, ti2, sp3, ti3, sp4, ti4, sp5, ti5, sp6, ti6, sp7, ti7, \ actual_step, additional_cycles, link_pattern): _checkPatternNumber(patternnumber) self.set_pattern_step_setpoint(patternnumber, 0, sp0)...
440,573
Write to a port on dummy_serial. Args: inputdata (string/bytes): data for sending to the port on dummy_serial. Will affect the response for subsequent read operations. Note that for Python2, the inputdata should be a **string**. For Python3 it should be of type **bytes**.
def write(self, inputdata): if VERBOSE: _print_out('\nDummy_serial: Writing to port. Given:' + repr(inputdata) + '\n') if sys.version_info[0] > 2: if not type(inputdata) == bytes: raise TypeError('The input must be type bytes. Given:' + repr(...
440,579
Calculate the number of bytes that should be received from the slave. Args: * mode (str): The modbus protcol mode (MODE_RTU or MODE_ASCII) * functioncode (int): Modbus function code. * payloadToSlave (str): The raw request that is to be sent to the slave (not hex encoded string) Returns: ...
def _predictResponseSize(mode, functioncode, payloadToSlave): MIN_PAYLOAD_LENGTH = 4 # For implemented functioncodes here BYTERANGE_FOR_GIVEN_SIZE = slice(2, 4) # Within the payload NUMBER_OF_PAYLOAD_BYTES_IN_WRITE_CONFIRMATION = 4 NUMBER_OF_PAYLOAD_BYTES_FOR_BYTECOUNTFIELD = 1 RTU_TO_ASCII...
440,583
Calculate the silent period length to comply with the 3.5 character silence between messages. Args: baudrate (numerical): The baudrate for the serial port Returns: The number of seconds (float) that should pass between each message on the bus. Raises: ValueError, TypeError.
def _calculate_minimum_silent_period(baudrate): _checkNumerical(baudrate, minvalue=1, description='baudrate') # Avoid division by zero BITTIMES_PER_CHARACTERTIME = 11 MINIMUM_SILENT_CHARACTERTIMES = 3.5 bittime = 1 / float(baudrate) return bittime * BITTIMES_PER_CHARACTERTIME * MINIMUM_SILEN...
440,584
Convert a long integer to a bytestring. Long integers (32 bits = 4 bytes) are stored in two consecutive 16-bit registers in the slave. Args: * value (int): The numerical value to be converted. * signed (bool): Whether large positive values should be interpreted as negative values. * nu...
def _longToBytestring(value, signed=False, numberOfRegisters=2): _checkInt(value, description='inputvalue') _checkBool(signed, description='signed parameter') _checkInt(numberOfRegisters, minvalue=2, maxvalue=2, description='number of registers') formatcode = '>' # Big-endian if signed: ...
440,587
Convert a bytestring to a long integer. Long integers (32 bits = 4 bytes) are stored in two consecutive 16-bit registers in the slave. Args: * bytestring (str): A string of length 4. * signed (bol): Whether large positive values should be interpreted as negative values. * numberOfRegis...
def _bytestringToLong(bytestring, signed=False, numberOfRegisters=2): _checkString(bytestring, 'byte string', minlength=4, maxlength=4) _checkBool(signed, description='signed parameter') _checkInt(numberOfRegisters, minvalue=2, maxvalue=2, description='number of registers') formatcode = '>' # Big...
440,588
Convert a four-byte string to a float. Floats are stored in two or more consecutive 16-bit registers in the slave. For discussion on precision, number of bits, number of registers, the range, byte order and on alternative names, see :func:`minimalmodbus._floatToBytestring`. Args: * bytestring...
def _bytestringToFloat(bytestring, numberOfRegisters=2): _checkString(bytestring, minlength=4, maxlength=8, description='bytestring') _checkInt(numberOfRegisters, minvalue=2, maxvalue=4, description='number of registers') numberOfBytes = _NUMBER_OF_BYTES_PER_REGISTER * numberOfRegisters formatcod...
440,590
Convert a list of numerical values to a bytestring. Each element is 'unsigned INT16'. Args: * valuelist (list of int): The input list. The elements should be in the range 0 to 65535. * numberOfRegisters (int): The number of registers. For error checking. Returns: A bytestring (str...
def _valuelistToBytestring(valuelist, numberOfRegisters): MINVALUE = 0 MAXVALUE = 65535 _checkInt(numberOfRegisters, minvalue=1, description='number of registers') if not isinstance(valuelist, list): raise TypeError('The valuelist parameter must be a list. Given {0!r}.'.format(valuelist))...
440,593
Convert a bytestring to a list of numerical values. The bytestring is interpreted as 'unsigned INT16'. Args: * bytestring (str): The string from the slave. Length = 2*numberOfRegisters * numberOfRegisters (int): The number of registers. For error checking. Returns: A list of integ...
def _bytestringToValuelist(bytestring, numberOfRegisters): _checkInt(numberOfRegisters, minvalue=1, description='number of registers') numberOfBytes = _NUMBER_OF_BYTES_PER_REGISTER * numberOfRegisters _checkString(bytestring, 'byte string', minlength=numberOfBytes, maxlength=numberOfBytes) values ...
440,594
Pack a value into a bytestring. Uses the built-in :mod:`struct` Python module. Args: * formatstring (str): String for the packing. See the :mod:`struct` module for details. * value (depends on formatstring): The value to be packed Returns: A bytestring (str). Raises: ...
def _pack(formatstring, value): _checkString(formatstring, description='formatstring', minlength=1) try: result = struct.pack(formatstring, value) except: errortext = 'The value to send is probably out of range, as the num-to-bytestring conversion failed.' errortext += ' Value:...
440,595
Unpack a bytestring into a value. Uses the built-in :mod:`struct` Python module. Args: * formatstring (str): String for the packing. See the :mod:`struct` module for details. * packed (str): The bytestring to be unpacked. Returns: A value. The type depends on the formatstring. ...
def _unpack(formatstring, packed): _checkString(formatstring, description='formatstring', minlength=1) _checkString(packed, description='packed string', minlength=1) if sys.version_info[0] > 2: packed = bytes(packed, encoding='latin1') # Convert types to make it Python3 compatible try: ...
440,596
Convert a hex encoded string to a byte string. For example '4A' will return 'J', and '04' will return ``'\\x04'`` (which has length 1). Args: hexstring (str): Can be for example 'A3' or 'A3B4'. Must be of even length. Allowed characters are '0' to '9', 'a' to 'f' and 'A' to 'F' (not space). ...
def _hexdecode(hexstring): # Note: For Python3 the appropriate would be: raise TypeError(new_error_message) from err # but the Python2 interpreter will indicate SyntaxError. # Thus we need to live with this warning in Python3: # 'During handling of the above exception, another exception occurred' ...
440,598
Convert a response string to a numerical value. Args: bytestring (str): A string of length 1. Can be for example ``\\x01``. Returns: The converted value (int). Raises: TypeError, ValueError
def _bitResponseToValue(bytestring): _checkString(bytestring, description='bytestring', minlength=1, maxlength=1) RESPONSE_ON = '\x01' RESPONSE_OFF = '\x00' if bytestring == RESPONSE_ON: return 1 elif bytestring == RESPONSE_OFF: return 0 else: raise ValueError('Co...
440,599
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
def _createBitpattern(functioncode, value): _checkFunctioncode(functioncode, [5, 15]) _checkInt(value, minvalue=0, maxvalue=1, description='inputvalue') if functioncode == 5: if value == 0: return '\x00\x00' else: return '\xff\x00' elif functioncode == 15: ...
440,600
Calculate the inverse(?) of a two's complement of an integer. Args: * x (int): input integer. * bits (int): number of bits, must be > 0. Returns: An int, that represents the inverse(?) of two's complement of the input. Example for bits=8: === ======= x returns === =...
def _fromTwosComplement(x, bits=16): _checkInt(bits, minvalue=0, description='number of bits') _checkInt(x, description='input') upperlimit = 2 ** (bits) - 1 lowerlimit = 0 if x > upperlimit or x < lowerlimit: raise ValueError('The input value is out of range. Given value is {0}, but a...
440,602
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 (...
def _setBitOn(x, bitNum): _checkInt(x, minvalue=0, description='input value') _checkInt(bitNum, minvalue=0, description='bitnumber') return x | (1 << bitNum)
440,603
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.
def _calculateCrcString(inputstring): _checkString(inputstring, description='input CRC string') # Preload a 16-bit register with ones register = 0xFFFF for char in inputstring: register = (register >> 8) ^ _CRC16TABLE[(register ^ ord(char)) & 0xFF] return _numToTwoByteString(regist...
440,604
Check that the Modbus mode is valie. Args: mode (string): The Modbus mode (MODE_RTU or MODE_ASCII) Raises: TypeError, ValueError
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 in [MODE_RTU, MODE_ASCII]: raise ValueError("Unreconized Modbus mode given. Must be 'rtu' or 'ascii' but {0!r} was given.".format(mode))
440,606
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...
def _checkFunctioncode(functioncode, listOfAllowedValues=[]): FUNCTIONCODE_MIN = 1 FUNCTIONCODE_MAX = 127 _checkInt(functioncode, FUNCTIONCODE_MIN, FUNCTIONCODE_MAX, description='functioncode') if listOfAllowedValues is None: return if not isinstance(listOfAllowedValues, list): ...
440,607
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
def _checkResponseByteCount(payload): POSITION_FOR_GIVEN_NUMBER = 0 NUMBER_OF_BYTES_TO_SKIP = 1 _checkString(payload, minlength=1, description='payload') givenNumberOfDatabytes = ord(payload[POSITION_FOR_GIVEN_NUMBER]) countedNumberOfDatabytes = len(payload) - NUMBER_OF_BYTES_TO_SKIP if ...
440,608
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
def _checkResponseRegisterAddress(payload, registeraddress): _checkString(payload, minlength=2, description='payload') _checkRegisteraddress(registeraddress) BYTERANGE_FOR_STARTADDRESS = slice(0, 2) bytesForStartAddress = payload[BYTERANGE_FOR_STARTADDRESS] receivedStartAddress = _twoByteStri...
440,609
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...
def _checkResponseNumberOfRegisters(payload, numberOfRegisters): _checkString(payload, minlength=4, description='payload') _checkInt(numberOfRegisters, minvalue=1, maxvalue=0xFFFF, description='numberOfRegisters') BYTERANGE_FOR_NUMBER_OF_REGISTERS = slice(2, 4) bytesForNumberOfRegisters = payload...
440,610
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
def _checkResponseWriteData(payload, writedata): _checkString(payload, minlength=4, description='payload') _checkString(writedata, minlength=2, maxlength=2, description='writedata') BYTERANGE_FOR_WRITEDATA = slice(2, 4) receivedWritedata = payload[BYTERANGE_FOR_WRITEDATA] if receivedWritedat...
440,611
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...
def _checkString(inputstring, description, minlength=0, maxlength=None): # Type checking if not isinstance(description, str): raise TypeError('The description should be a string. Given: {0!r}'.format(description)) if not isinstance(inputstring, str): raise TypeError('The {0} should be ...
440,612
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...
def _checkInt(inputvalue, minvalue=None, maxvalue=None, description='inputvalue'): if not isinstance(description, str): raise TypeError('The description should be a string. Given: {0!r}'.format(description)) if not isinstance(inputvalue, (int, long)): raise TypeError('The {0} must be an in...
440,613
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
def _checkBool(inputvalue, description='inputvalue'): _checkString(description, minlength=1, description='description string') if not isinstance(inputvalue, bool): raise TypeError('The {0} must be boolean. Given: {1!r}'.format(description, inputvalue))
440,615
r"""Generate a human readable description of a Modbus payload. Args: * functioncode (int): Function code * payload (str): The payload that should be interpreted. It should be a byte string. Returns: A descriptive string. For example, the payload ``'\x10\x01\x00\x01'`` for function...
def _interpretPayload(functioncode, payload): r raise NotImplementedError() output = '' output += 'Modbus payload decoder\n' output += 'Input payload (length {} characters): {!r} \n'.format(len(payload), payload) output += 'Function code: {} (dec).\n'.format(functioncode) if len(payload...
440,617
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,...
def read_bit(self, registeraddress, functioncode=2): _checkFunctioncode(functioncode, [1, 2]) return self._genericCommand(functioncode, registeraddress)
440,621
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,...
def write_bit(self, registeraddress, value, functioncode=5): _checkFunctioncode(functioncode, [5, 15]) _checkInt(value, minvalue=0, maxvalue=1, description='input value') self._genericCommand(functioncode, registeraddress, value)
440,622
Add an additional argument to be passed to the fitness function via additional arguments dictionary; this argument/value is not tuned Args: arg_name (string): name/dictionary key of argument arg_value (any): dictionary value of argument
def add_argument(self, arg_name, arg_value): if len(self._employers) > 0: self._logger.log( 'warn', 'Adding an argument after the employers have been created' ) if self._args is None: self._args = {} self._args[arg_nam...
440,719
Add a tunable value to the ABC (fitness function must be configured to handle it) Args: value_type (string): type of the value, 'int' or 'float' value_min (int or float): minimum bound for the value value_max (int or float): maximum bound for the value Retur...
def add_value(self, value_type, value_min, value_max): if len(self._employers) > 0: self._logger.log( 'warn', 'Adding a value after employers have been created' ) value = (value_type, (value_min, value_max)) self._value_ranges.ap...
440,720
Set additional arguments to be passed to the fitness function Args: args (dict): additional arguments
def args(self, args): self._args = args self._logger.log('debug', 'Args set to {}'.format(args))
440,721
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
def minimize(self, minimize): self._minimize = minimize self._logger.log('debug', 'Minimize set to {}'.format(minimize))
440,722
Sets the number of employer bees; at least two are required Args: num_employers (int): number of employer bees
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_employers = num_employers self._logger.log('debug', 'Numb...
440,723
Set the types, min/max values for tunable parameters Args: value_ranges (list): each element defines a tunable variable in the form "(type ('int' or 'float'), (min_val, max_val))"; initial, random values for each bee will between "min_val" and "max_va...
def value_ranges(self, value_ranges): self._value_ranges = value_ranges self._logger.log('debug', 'Value ranges set to {}'.format( value_ranges ))
440,724
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
def processes(self, processes): if self._processes > 1: self._pool.close() self._pool.join() self._pool = multiprocessing.Pool(processes) else: self._pool = None self._logger.log('debug', 'Number of processes set to {}'.format( ...
440,725
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)
def _merge_bee(self, bee): random_dimension = randint(0, len(self._value_ranges) - 1) second_bee = randint(0, self._num_employers - 1) while (bee.id == self._employers[second_bee].id): second_bee = randint(0, self._num_employers - 1) new_bee = deepcopy(bee) ...
440,733
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: bee.values = new_values[1] bee.score = score bee.error = new_values[2] bee.failed_trials = 0 ...
440,734
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: ...
def __update(self, score, values, error): if self._minimize: if self._best_score is None or score > self._best_score: self._best_score = score self._best_values = values.copy() self._best_error = error self._logger.log( ...
440,735
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' ) raise RuntimeWarning( 'Attribute value_ranges must have at le...
440,737
Import settings from a JSON file Args: filename (string): name of the file to import from
def import_settings(self, filename): if not os.path.isfile(filename): self._logger.log( 'error', 'File: {} not found, continuing with default settings'.format( filename ) ) else: with open(f...
440,738
EmployerBee object: stores individual employer bee information such as ID, position (current values), fitness function return value, fitness score, and probability of being chosen during the onlooker phase Args: values (list): position/current values for the bee
def __init__(self, values=[]): self.values = values self.score = None self.probability = 0 self.failed_trials = 0 self.id = uuid.uuid4() self.error = None
440,740
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
def get_score(self, error=None): if error is not None: self.error = error if self.error >= 0: return 1 / (self.error + 1) else: return 1 + abs(self.error)
440,741
Calculate the new value/position for two given bee values Args: first_bee_val (int or float): value from the first bee second_bee_val (int or float): value from the second bee value_ranges (tuple): "(value type, (min_val, max_val))" for the given value ...
def calculate_positions(self, first_bee_val, second_bee_val, value_range): value = first_bee_val + np.random.uniform(-1, 1) \ * (first_bee_val - second_bee_val) if value_range[0] == 'int': value = int(value) if value > value_range[1][1]: value = valu...
440,742
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.
def create_elb_dns(self, regionspecific=False): if regionspecific: dns_elb = self.generated.dns()['elb_region'] else: dns_elb = self.generated.dns()['elb'] dns_elb_aws = find_elb(name=self.app_name, env=self.env, region=self.region) zone_ids = get_dns_z...
440,744
Create dns entries in route53 for multiregion failover setups. Args: primary_region (str): primary AWS region for failover Returns: Auto-generated DNS name.
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, facing=self.elb_subnet) elb_dns_aws = find_elb(name=self.app_name, env=self.env, region=self.region) elb_dns_zone_id = find_elb_dns_z...
440,745
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...
def format_cert_name(env='', account='', region='', certificate=None): cert_name = None if certificate: if certificate.startswith('arn'): LOG.info("Full ARN provided...skipping lookup.") cert_name = certificate else: generated_cert_name = generate_custom...
440,747
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...
def generate_custom_cert_name(env='', region='', account='', certificate=None): cert_name = None template_kwargs = {'account': account, 'name': certificate} # TODO: Investigate moving this to a remote API, then fallback to local file if unable to connect try: rendered_template = get_templa...
440,748
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
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_format + '_{env}' else: template_name_format = template_name_format + '_stages' if pipeline_ty...
440,752
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.
def convert_ini(config_dict): config_lines = [] for env, configs in sorted(config_dict.items()): for resource, app_properties in sorted(configs.items()): try: for app_property, value in sorted(app_properties.items()): variable = '{env}_{resource}_{ap...
440,757
Destroy Cloudwatch log event. Args: app (str): Spinnaker Application name. env (str): Deployment environment. region (str): AWS region. Returns: bool: True upon successful completion.
def destroy_cloudwatch_log_event(app='', env='dev', region=''): session = boto3.Session(profile_name=env, region_name=region) cloudwatch_client = session.client('logs') # FIXME: see below # TODO: Log group name is required, where do we get it if it is not in application-master-env.json? cloud...
440,760
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.
def get_accounts(self, provider='aws'): url = '{gate}/credentials'.format(gate=API_URL) response = requests.get(url, verify=GATE_CA_BUNDLE, cert=GATE_CLIENT_CERT) assert response.ok, 'Failed to get accounts: {0}'.format(response.text) all_accounts = response.json() self...
440,762
S3 deployment object. Args: app (str): Application name env (str): Environment/Account region (str): AWS Region prop_path (str): Path of environment property file artifact_path (str): Path to tar.gz artifact primary_region (str): The prima...
def __init__(self, app, env, region, prop_path, artifact_path, artifact_version, primary_region='us-east-1'): self.app_name = app self.env = env self.region = region self.artifact_path = artifact_path self.version = artifact_version self.properties = get_properti...
440,767
Format the s3 path properly. Args: suffix (str): suffix to add on to an s3 path Returns: str: formatted path
def _path_formatter(self, suffix): if suffix.lower() == "mirror": path_items = [self.bucket, self.s3path] else: path_items = [self.bucket, self.s3path, suffix] path = '/'.join(path_items) s3_format = "s3://{}" formatted_path = path.replace('//', ...
440,769
Promote artifact version to dest. Args: promote_stage (string): Stage that is being promoted
def promote_artifacts(self, promote_stage='latest'): if promote_stage.lower() == 'alpha': self._sync_to_uri(self.s3_canary_uri) elif promote_stage.lower() == 'canary': self._sync_to_uri(self.s3_latest_uri) else: self._sync_to_uri(self.s3_latest_uri)
440,771
Generate the S3 CLI upload command Args: mirror (bool): If true, uses a flat directory structure instead of nesting under a version. Returns: str: The full CLI command to run.
def _get_upload_cmd(self, mirror=False): if mirror: dest_uri = self.s3_mirror_uri else: dest_uri = self.s3_version_uri cmd = 'aws s3 sync {} {} --delete --exact-timestamps --profile {}'.format(self.artifact_path, ...
440,772
Recursively upload directory contents to S3. Args: mirror (bool): If true, uses a flat directory structure instead of nesting under a version.
def _upload_artifacts_to_path(self, mirror=False): if not os.listdir(self.artifact_path) or not self.artifact_path: raise S3ArtifactNotFound uploaded = False if self.s3props.get("content_metadata"): LOG.info("Uploading in multiple parts to set metadata") ...
440,773
Finds all specified encoded directories and uploads in multiple parts, setting metadata for objects. Args: mirror (bool): If true, uses a flat directory structure instead of nesting under a version. Returns: bool: True if uploaded
def content_metadata_uploads(self, mirror=False): excludes_str = '' includes_cmds = [] cmd_base = self._get_upload_cmd(mirror=mirror) for content in self.s3props.get('content_metadata'): full_path = os.path.join(self.artifact_path, content['path']) if no...
440,774
Copy and sync versioned directory to uri in S3. Args: uri (str): S3 URI to sync version to.
def _sync_to_uri(self, uri): cmd_cp = 'aws s3 cp {} {} --recursive --profile {}'.format(self.s3_version_uri, uri, self.env) # AWS CLI sync does not work as expected bucket to bucket with exact timestamp sync. cmd_sync = 'aws s3 sync {} {} --delete --exact-timestamps --profile {}'.format...
440,775
Get VPC ID configured for ``account`` in ``region``. Args: account (str): AWS account name. region (str): Region name, e.g. us-east-1. Returns: str: VPC ID for the requested ``account`` in ``region``. Raises: :obj:`foremast.exceptions.SpinnakerVPCIDNotFound`: VPC ID not fo...
def get_vpc_id(account, region): url = '{0}/networks/aws'.format(API_URL) response = requests.get(url, verify=GATE_CA_BUNDLE, cert=GATE_CLIENT_CERT) if not response.ok: raise SpinnakerVPCNotFound(response.text) vpcs = response.json() for vpc in vpcs: LOG.debug('VPC: %(name)s,...
440,776
Get all availability zones for a given target. Args: target (str): Type of subnets to look up (ec2 or elb). env (str): Environment to look up. region (str): AWS Region to find Subnets for. Returns: az_dict: dictionary of availbility zones, structured like { $region: [ ...
def get_subnets( target='ec2', purpose='internal', env='', region='', ): account_az_dict = defaultdict(defaultdict) subnet_id_dict = defaultdict(defaultdict) subnet_url = '{0}/subnets/aws'.format(API_URL) subnet_response = requests.get(subnet_url, verify=GATE_CA_BUN...
440,777
Lambda event object. Args: app (str): Application name env (str): Environment/Account region (str): AWS Region prop_path (str): Path of environment property file
def __init__(self, app=None, env=None, region=None, prop_path=None): self.app_name = app self.env = env self.region = region self.prop_path = prop_path self.properties = get_properties(properties_file=prop_path, env=env, region=region)
440,779
Check a Pipeline name is a managed format **app_name [region]**. Args: name (str): Name of Pipeline to check. app_name (str): Name of Application to find in Pipeline name. Returns: str: Region name from managed Pipeline name. Raises: ValueError: Pipeline is not managed.
def check_managed_pipeline(name='', app_name=''): *pipeline_name_prefix, bracket_region = name.split() region = bracket_region.strip('[]') not_managed_message = '"{0}" is not managed.'.format(name) if 'onetime' in region: LOG.info('"%s" is a onetime, marked for cleaning.', name) r...
440,781
Get a list of all the Pipelines in _app_. Args: app (str): Name of Spinnaker Application. Returns: requests.models.Response: Response from Gate containing Pipelines.
def get_all_pipelines(app=''): url = '{host}/applications/{app}/pipelineConfigs'.format(host=API_URL, app=app) response = requests.get(url, verify=GATE_CA_BUNDLE, cert=GATE_CLIENT_CERT) assert response.ok, 'Could not retrieve Pipelines for {0}.'.format(app) pipelines = response.json() LOG.deb...
440,782
Get the ID for Pipeline _name_. Args: app (str): Name of Spinnaker Application to search. name (str): Name of Pipeline to get ID for. Returns: str: ID of specified Pipeline. None: Pipeline or Spinnaker Appliation not found.
def get_pipeline_id(app='', name=''): return_id = None pipelines = get_all_pipelines(app=app) for pipeline in pipelines: LOG.debug('ID of %(name)s: %(id)s', pipeline) if pipeline['name'] == name: return_id = pipeline['id'] LOG.info('Pipeline %s found, ID: %s',...
440,783
Extract details for Application. Args: app (str): Application Name env (str): Environment/account to get details from Returns: collections.namedtuple with _group_, _policy_, _profile_, _role_, _user_.
def get_details(app='groupproject', env='dev', region='us-east-1'): url = '{host}/applications/{app}'.format(host=API_URL, app=app) request = requests.get(url, verify=GATE_CA_BUNDLE, cert=GATE_CLIENT_CERT) if not request.ok: raise SpinnakerAppNotFound('"{0}" not found.'.format(app)) app_...
440,786
Generate the base Pipeline wrapper. This renders the non-repeatable stages in a pipeline, like jenkins, baking, tagging and notifications. Args: region (str): AWS Region. Returns: dict: Rendered Pipeline wrapper.
def render_wrapper(self, region='us-east-1'): base = self.settings['pipeline']['base'] if self.base: base = self.base email = self.settings['pipeline']['notifications']['email'] slack = self.settings['pipeline']['notifications']['slack'] deploy_type = self....
440,787
Lambda function object. Args: app (str): Application name env (str): Environment/Account region (str): AWS Region prop_path (str): Path of environment property file
def __init__(self, app, env, region, prop_path): self.app_name = app self.env = env self.region = region self.properties = get_properties(prop_path) generated = get_details(app=self.app_name) self.group = generated.data['project'] try: self.p...
440,789
Update existing Lambda function configuration. Args: vpc_config (dict): Dictionary of SubnetIds and SecurityGroupsIds for using a VPC in lambda
def update_function_configuration(self, vpc_config): LOG.info('Updating configuration for lambda function: %s', self.app_name) try: self.lambda_client.update_function_configuration( Environment=self.lambda_environment, FunctionName=self.app_name, ...
440,796
Create lambda function, configures lambda parameters. We need to upload non-zero zip when creating function. Uploading hello_world python lambda function since AWS doesn't care which executable is in ZIP. Args: vpc_config (dict): Dictionary of SubnetIds and SecurityGroupsId...
def create_function(self, vpc_config): zip_file = 'lambda-holder.zip' with zipfile.ZipFile(zip_file, mode='w') as zipped: zipped.writestr('index.py', 'print "Hello world"') contents = '' with open('lambda-holder.zip', 'rb') as openfile: contents = openfi...
440,797
Destroy Security Group. Args: app (str): Spinnaker Application name. env (str): Deployment environment. region (str): Region name, e.g. us-east-1. Returns: True upon successful completion.
def destroy_sg(app='', env='', region='', **_): vpc = get_vpc_id(account=env, region=region) url = '{api}/securityGroups/{env}/{region}/{app}'.format(api=API_URL, env=env, region=region, app=app) payload = {'vpcId': vpc} security_group = requests.get(url, params=payload, verify=GATE_CA_BUNDLE, cer...
440,799
Destroy S3 Resources for _app_ in _env_. Args: app (str): Application name env (str): Deployment environment/account name Returns: boolean: True if destroyed sucessfully
def destroy_s3(app='', env='dev', **_): session = boto3.Session(profile_name=env) client = session.resource('s3') generated = get_details(app=app, env=env) archaius = generated.archaius() bucket = client.Bucket(archaius['bucket']) for item in bucket.objects.filter(Prefix=archaius['path']...
440,800
Destroy S3 event. Args: app (str): Spinnaker Application name. env (str): Deployment environment. region (str): AWS region. Returns: bool: True upon successful completion.
def destroy_s3_event(app, env, region): # TODO: how do we know which bucket to process if triggers dict is empty? # Maybe list buckets and see which has notification to that lambda defined? # TODO: buckets should be named the same as apps, what if one app has multiple buckets? # bucket = rules.get...
440,802
Destroy IAM Resources. Args: app (str): Spinnaker Application name. env (str): Deployment environment, i.e. dev, stage, prod. Returns: True upon successful completion.
def destroy_iam(app='', env='dev', **_): session = boto3.Session(profile_name=env) client = session.client('iam') generated = get_details(env=env, app=app) generated_iam = generated.iam() app_details = collections.namedtuple('AppDetails', generated_iam.keys()) details = app_details(**gener...
440,803
Get role ARN given role name. Args: role_name (str): Role name to lookup env (str): Environment in which to lookup region (str): Region Returns: ARN if role found
def get_role_arn(role_name, env, region): session = boto3.Session(profile_name=env, region_name=region) iam_client = session.client('iam') LOG.debug('Searching for %s.', role_name) role = iam_client.get_role(RoleName=role_name) role_arn = role['Role']['Arn'] LOG.debug("Found role's %s AR...
440,804
Assemble IAM Policy for _app_. Args: app (str): Name of Spinnaker Application. env (str): Environment/Account in AWS group (str):A Application group/namespace region (str): AWS region pipeline_settings (dict): Settings from *pipeline.json*. Returns: json: Custom...
def construct_policy(app='coreforrest', env='dev', group='forrest', region='us-east-1', pipeline_settings=None): LOG.info('Create custom IAM Policy for %s.', app) services = pipeline_settings.get('services', {}) LOG.debug('Found requested services: %s', services) services = auto_service(pipeline_...
440,806
Create S3 lambda events from triggers Args: app_name (str): name of the lambda function env (str): Environment/Account for lambda function region (str): AWS region of the lambda function triggers (list): List of triggers from the settings
def create_s3_event(app_name, env, region, bucket, triggers): session = boto3.Session(profile_name=env, region_name=region) s3_client = session.client('s3') lambda_alias_arn = get_lambda_alias_arn(app_name, env, region) LOG.debug("Lambda ARN for lambda function %s is %s.", app_name, lambda_alias_...
440,809