repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
elmotec/massedit
massedit.py
MassEdit.set_code_exprs
python
def set_code_exprs(self, codes): self.code_objs = dict() self._codes = [] for code in codes: self.append_code_expr(code)
Convenience: sets all the code expressions at once.
train
https://github.com/elmotec/massedit/blob/57e22787354896d63a8850312314b19aa0308906/massedit.py#L310-L315
[ "def append_code_expr(self, code):\n \"\"\"Compile argument and adds it to the list of code objects.\"\"\"\n # expects a string.\n if isinstance(code, str) and not isinstance(code, unicode):\n code = unicode(code)\n if not isinstance(code, unicode):\n raise TypeError(\"string expected\")\n...
class MassEdit(object): """Mass edit lines of files.""" def __init__(self, **kwds): """Initialize MassEdit object. Args: - code (byte code object): code to execute on input file. - function (str or callable): function to call on input file. - module (str): module...
elmotec/massedit
massedit.py
MassEdit.set_functions
python
def set_functions(self, functions): for func in functions: try: self.append_function(func) except (ValueError, AttributeError) as ex: log.error("'%s' is not a callable function: %s", func, ex) raise
Check functions passed as argument and set them to be used.
train
https://github.com/elmotec/massedit/blob/57e22787354896d63a8850312314b19aa0308906/massedit.py#L317-L324
[ "def append_function(self, function):\n \"\"\"Append the function to the list of functions to be called.\n\n If the function is already a callable, use it. If it's a type str\n try to interpret it as [module]:?<callable>, load the module\n if there is one and retrieve the callable.\n\n Argument:\n ...
class MassEdit(object): """Mass edit lines of files.""" def __init__(self, **kwds): """Initialize MassEdit object. Args: - code (byte code object): code to execute on input file. - function (str or callable): function to call on input file. - module (str): module...
ChristianKuehnel/btlewrap
btlewrap/pygatt.py
wrap_exception
python
def wrap_exception(func: Callable) -> Callable: try: # only do the wrapping if pygatt is installed. # otherwise it's pointless anyway from pygatt.backends.bgapi.exceptions import BGAPIError from pygatt.exceptions import NotConnectedError except ImportError: return func ...
Decorator to wrap pygatt exceptions into BluetoothBackendException.
train
https://github.com/ChristianKuehnel/btlewrap/blob/1b7aec934529dcf03f5ecdccd0b09c25c389974f/btlewrap/pygatt.py#L9-L27
null
"""Bluetooth backend for Blue Giga based bluetooth devices. This backend uses the pygatt API: https://github.com/peplin/pygatt """ from typing import Callable from btlewrap.base import AbstractBackend, BluetoothBackendException class PygattBackend(AbstractBackend): """Bluetooth backend for Blue Giga based bluet...
ChristianKuehnel/btlewrap
btlewrap/pygatt.py
PygattBackend.connect
python
def connect(self, mac: str): import pygatt address_type = pygatt.BLEAddressType.public if self._address_type == 'random': address_type = pygatt.BLEAddressType.random self._device = self._adapter.connect(mac, address_type=address_type)
Connect to a device.
train
https://github.com/ChristianKuehnel/btlewrap/blob/1b7aec934529dcf03f5ecdccd0b09c25c389974f/btlewrap/pygatt.py#L53-L60
null
class PygattBackend(AbstractBackend): """Bluetooth backend for Blue Giga based bluetooth devices.""" @wrap_exception def __init__(self, adapter: str = None, address_type='public'): """Create a new instance. Note: the parameter "adapter" is ignored, pygatt detects the right USB port automag...
ChristianKuehnel/btlewrap
btlewrap/pygatt.py
PygattBackend.read_handle
python
def read_handle(self, handle: int) -> bytes: if not self.is_connected(): raise BluetoothBackendException('Not connected to device!') return self._device.char_read_handle(handle)
Read a handle from the device.
train
https://github.com/ChristianKuehnel/btlewrap/blob/1b7aec934529dcf03f5ecdccd0b09c25c389974f/btlewrap/pygatt.py#L74-L78
[ "def is_connected(self) -> bool:\n \"\"\"Check if connected to a device.\"\"\"\n return self._device is not None\n" ]
class PygattBackend(AbstractBackend): """Bluetooth backend for Blue Giga based bluetooth devices.""" @wrap_exception def __init__(self, adapter: str = None, address_type='public'): """Create a new instance. Note: the parameter "adapter" is ignored, pygatt detects the right USB port automag...
ChristianKuehnel/btlewrap
btlewrap/pygatt.py
PygattBackend.write_handle
python
def write_handle(self, handle: int, value: bytes): if not self.is_connected(): raise BluetoothBackendException('Not connected to device!') self._device.char_write_handle(handle, value, True) return True
Write a handle to the device.
train
https://github.com/ChristianKuehnel/btlewrap/blob/1b7aec934529dcf03f5ecdccd0b09c25c389974f/btlewrap/pygatt.py#L81-L86
[ "def is_connected(self) -> bool:\n \"\"\"Check if connected to a device.\"\"\"\n return self._device is not None\n" ]
class PygattBackend(AbstractBackend): """Bluetooth backend for Blue Giga based bluetooth devices.""" @wrap_exception def __init__(self, adapter: str = None, address_type='public'): """Create a new instance. Note: the parameter "adapter" is ignored, pygatt detects the right USB port automag...
ChristianKuehnel/btlewrap
btlewrap/bluepy.py
wrap_exception
python
def wrap_exception(func: Callable) -> Callable: try: # only do the wrapping if bluepy is installed. # otherwise it's pointless anyway from bluepy.btle import BTLEException except ImportError: return func def _func_wrapper(*args, **kwargs): error_count = 0 las...
Decorator to wrap BTLEExceptions into BluetoothBackendException.
train
https://github.com/ChristianKuehnel/btlewrap/blob/1b7aec934529dcf03f5ecdccd0b09c25c389974f/btlewrap/bluepy.py#L13-L35
null
"""Backend for Miflora using the bluepy library.""" import re import logging import time from typing import List, Tuple, Callable from btlewrap.base import AbstractBackend, BluetoothBackendException _LOGGER = logging.getLogger(__name__) RETRY_LIMIT = 3 RETRY_DELAY = 0.1 class BluepyBackend(AbstractBackend): """...
ChristianKuehnel/btlewrap
btlewrap/bluepy.py
BluepyBackend.connect
python
def connect(self, mac: str): from bluepy.btle import Peripheral match_result = re.search(r'hci([\d]+)', self.adapter) if match_result is None: raise BluetoothBackendException( 'Invalid pattern "{}" for BLuetooth adpater. ' 'Expetected something like "h...
Connect to a device.
train
https://github.com/ChristianKuehnel/btlewrap/blob/1b7aec934529dcf03f5ecdccd0b09c25c389974f/btlewrap/bluepy.py#L48-L57
null
class BluepyBackend(AbstractBackend): """Backend for Miflora using the bluepy library.""" def __init__(self, adapter: str = 'hci0', address_type: str = 'public'): """Create new instance of the backend.""" super(BluepyBackend, self).__init__(adapter) self.address_type = address_type ...
ChristianKuehnel/btlewrap
btlewrap/bluepy.py
BluepyBackend.read_handle
python
def read_handle(self, handle: int) -> bytes: if self._peripheral is None: raise BluetoothBackendException('not connected to backend') return self._peripheral.readCharacteristic(handle)
Read a handle from the device. You must be connected to do this.
train
https://github.com/ChristianKuehnel/btlewrap/blob/1b7aec934529dcf03f5ecdccd0b09c25c389974f/btlewrap/bluepy.py#L69-L76
null
class BluepyBackend(AbstractBackend): """Backend for Miflora using the bluepy library.""" def __init__(self, adapter: str = 'hci0', address_type: str = 'public'): """Create new instance of the backend.""" super(BluepyBackend, self).__init__(adapter) self.address_type = address_type ...
ChristianKuehnel/btlewrap
btlewrap/bluepy.py
BluepyBackend.write_handle
python
def write_handle(self, handle: int, value: bytes): if self._peripheral is None: raise BluetoothBackendException('not connected to backend') return self._peripheral.writeCharacteristic(handle, value, True)
Write a handle from the device. You must be connected to do this.
train
https://github.com/ChristianKuehnel/btlewrap/blob/1b7aec934529dcf03f5ecdccd0b09c25c389974f/btlewrap/bluepy.py#L79-L86
null
class BluepyBackend(AbstractBackend): """Backend for Miflora using the bluepy library.""" def __init__(self, adapter: str = 'hci0', address_type: str = 'public'): """Create new instance of the backend.""" super(BluepyBackend, self).__init__(adapter) self.address_type = address_type ...
ChristianKuehnel/btlewrap
btlewrap/bluepy.py
BluepyBackend.check_backend
python
def check_backend() -> bool: try: import bluepy.btle # noqa: F401 #pylint: disable=unused-import return True except ImportError as importerror: _LOGGER.error('bluepy not found: %s', str(importerror)) return False
Check if the backend is available.
train
https://github.com/ChristianKuehnel/btlewrap/blob/1b7aec934529dcf03f5ecdccd0b09c25c389974f/btlewrap/bluepy.py#L97-L104
null
class BluepyBackend(AbstractBackend): """Backend for Miflora using the bluepy library.""" def __init__(self, adapter: str = 'hci0', address_type: str = 'public'): """Create new instance of the backend.""" super(BluepyBackend, self).__init__(adapter) self.address_type = address_type ...
ChristianKuehnel/btlewrap
btlewrap/bluepy.py
BluepyBackend.scan_for_devices
python
def scan_for_devices(timeout: float) -> List[Tuple[str, str]]: from bluepy.btle import Scanner scanner = Scanner() result = [] for device in scanner.scan(timeout): result.append((device.addr, device.getValueText(9))) return result
Scan for bluetooth low energy devices. Note this must be run as root!
train
https://github.com/ChristianKuehnel/btlewrap/blob/1b7aec934529dcf03f5ecdccd0b09c25c389974f/btlewrap/bluepy.py#L108-L118
null
class BluepyBackend(AbstractBackend): """Backend for Miflora using the bluepy library.""" def __init__(self, adapter: str = 'hci0', address_type: str = 'public'): """Create new instance of the backend.""" super(BluepyBackend, self).__init__(adapter) self.address_type = address_type ...
ChristianKuehnel/btlewrap
btlewrap/gatttool.py
wrap_exception
python
def wrap_exception(func: Callable) -> Callable: def _func_wrapper(*args, **kwargs): try: return func(*args, **kwargs) except IOError as exception: raise BluetoothBackendException() from exception return _func_wrapper
Wrap all IOErrors to BluetoothBackendException
train
https://github.com/ChristianKuehnel/btlewrap/blob/1b7aec934529dcf03f5ecdccd0b09c25c389974f/btlewrap/gatttool.py#L19-L27
null
""" Reading from the sensor is handled by the command line tool "gatttool" that is part of bluez on Linux. No other operating systems are supported at the moment """ from threading import current_thread import os import logging import re import time from typing import Callable from subprocess import Popen, PIPE, Timeo...
ChristianKuehnel/btlewrap
btlewrap/gatttool.py
GatttoolBackend.write_handle
python
def write_handle(self, handle: int, value: bytes): # noqa: C901 # pylint: disable=arguments-differ if not self.is_connected(): raise BluetoothBackendException('Not connected to any device.') attempt = 0 delay = 10 _LOGGER.debug("Enter write_ble (%s)", curren...
Read from a BLE address. @param: mac - MAC address in format XX:XX:XX:XX:XX:XX @param: handle - BLE characteristics handle in format 0xXX @param: value - value to write to the given handle
train
https://github.com/ChristianKuehnel/btlewrap/blob/1b7aec934529dcf03f5ecdccd0b09c25c389974f/btlewrap/gatttool.py#L62-L116
[ "def is_connected(self) -> bool:\n \"\"\"Check if we are connected to the backend.\"\"\"\n return self._mac is not None\n" ]
class GatttoolBackend(AbstractBackend): """ Backend using gatttool.""" # pylint: disable=subprocess-popen-preexec-fn def __init__(self, adapter: str = 'hci0', retries: int = 3, timeout: float = 20, address_type: str = 'public'): super(GatttoolBackend, self).__init__(adapter) self.adapter =...
ChristianKuehnel/btlewrap
btlewrap/gatttool.py
GatttoolBackend.wait_for_notification
python
def wait_for_notification(self, handle: int, delegate, notification_timeout: float): if not self.is_connected(): raise BluetoothBackendException('Not connected to any device.') attempt = 0 delay = 10 _LOGGER.debug("Enter write_ble (%s)", current_thread()) while att...
Listen for characteristics changes from a BLE address. @param: mac - MAC address in format XX:XX:XX:XX:XX:XX @param: handle - BLE characteristics handle in format 0xXX a value of 0x0100 is written to register for listening @param: delegate - gatttool receives the ...
train
https://github.com/ChristianKuehnel/btlewrap/blob/1b7aec934529dcf03f5ecdccd0b09c25c389974f/btlewrap/gatttool.py#L119-L176
[ "def is_connected(self) -> bool:\n \"\"\"Check if we are connected to the backend.\"\"\"\n return self._mac is not None\n" ]
class GatttoolBackend(AbstractBackend): """ Backend using gatttool.""" # pylint: disable=subprocess-popen-preexec-fn def __init__(self, adapter: str = 'hci0', retries: int = 3, timeout: float = 20, address_type: str = 'public'): super(GatttoolBackend, self).__init__(adapter) self.adapter =...
ChristianKuehnel/btlewrap
btlewrap/gatttool.py
GatttoolBackend.extract_notification_payload
python
def extract_notification_payload(process_output): data = [] for element in process_output.splitlines()[1:]: parts = element.split(": ") if len(parts) == 2: data.append(parts[1]) return data
Processes the raw output from Gatttool stripping the first line and the 'Notification handle = 0x000e value: ' from each line @param: process_output - the raw output from a listen commad of GattTool which may look like this: Characteristic value was written successfully ...
train
https://github.com/ChristianKuehnel/btlewrap/blob/1b7aec934529dcf03f5ecdccd0b09c25c389974f/btlewrap/gatttool.py#L179-L202
null
class GatttoolBackend(AbstractBackend): """ Backend using gatttool.""" # pylint: disable=subprocess-popen-preexec-fn def __init__(self, adapter: str = 'hci0', retries: int = 3, timeout: float = 20, address_type: str = 'public'): super(GatttoolBackend, self).__init__(adapter) self.adapter =...
ChristianKuehnel/btlewrap
btlewrap/gatttool.py
GatttoolBackend.check_backend
python
def check_backend() -> bool: try: call('gatttool', stdout=PIPE, stderr=PIPE) return True except OSError as os_err: msg = 'gatttool not found: {}'.format(str(os_err)) _LOGGER.error(msg) return False
Check if gatttool is available on the system.
train
https://github.com/ChristianKuehnel/btlewrap/blob/1b7aec934529dcf03f5ecdccd0b09c25c389974f/btlewrap/gatttool.py#L260-L268
null
class GatttoolBackend(AbstractBackend): """ Backend using gatttool.""" # pylint: disable=subprocess-popen-preexec-fn def __init__(self, adapter: str = 'hci0', retries: int = 3, timeout: float = 20, address_type: str = 'public'): super(GatttoolBackend, self).__init__(adapter) self.adapter =...
ChristianKuehnel/btlewrap
btlewrap/gatttool.py
GatttoolBackend.bytes_to_string
python
def bytes_to_string(raw_data: bytes, prefix: bool = False) -> str: prefix_string = '' if prefix: prefix_string = '0x' suffix = ''.join([format(c, "02x") for c in raw_data]) return prefix_string + suffix.upper()
Convert a byte array to a hex string.
train
https://github.com/ChristianKuehnel/btlewrap/blob/1b7aec934529dcf03f5ecdccd0b09c25c389974f/btlewrap/gatttool.py#L276-L282
null
class GatttoolBackend(AbstractBackend): """ Backend using gatttool.""" # pylint: disable=subprocess-popen-preexec-fn def __init__(self, adapter: str = 'hci0', retries: int = 3, timeout: float = 20, address_type: str = 'public'): super(GatttoolBackend, self).__init__(adapter) self.adapter =...
google/google-visualization-python
gviz_api.py
DataTable.CoerceValue
python
def CoerceValue(value, value_type): if isinstance(value, tuple): # In case of a tuple, we run the same function on the value itself and # add the formatted value. if (len(value) not in [2, 3] or (len(value) == 3 and not isinstance(value[2], dict))): raise DataTableException("Wron...
Coerces a single value into the type expected for its column. Internal helper method. Args: value: The value which should be converted value_type: One of "string", "number", "boolean", "date", "datetime" or "timeofday". Returns: An item of the Python type appropriate t...
train
https://github.com/google/google-visualization-python/blob/cbfb4d69ad2f4ca30dc55791629280aa3214c8e3/gviz_api.py#L176-L270
[ "def CoerceValue(value, value_type):\n \"\"\"Coerces a single value into the type expected for its column.\n\n Internal helper method.\n\n Args:\n value: The value which should be converted\n value_type: One of \"string\", \"number\", \"boolean\", \"date\", \"datetime\" or\n \"timeofday\".\n...
class DataTable(object): """Wraps the data to convert to a Google Visualization API DataTable. Create this object, populate it with data, then call one of the ToJS... methods to return a string representation of the data in the format described. You can clear all data from the object to reuse it, but you cann...
google/google-visualization-python
gviz_api.py
DataTable.ColumnTypeParser
python
def ColumnTypeParser(description): if not description: raise DataTableException("Description error: empty description given") if not isinstance(description, (six.string_types, tuple)): raise DataTableException("Description error: expected either string or " "tuple, go...
Parses a single column description. Internal helper method. Args: description: a column description in the possible formats: 'id' ('id',) ('id', 'type') ('id', 'type', 'label') ('id', 'type', 'label', {'custom_prop1': 'custom_val1'}) Returns: Dictionary with the f...
train
https://github.com/google/google-visualization-python/blob/cbfb4d69ad2f4ca30dc55791629280aa3214c8e3/gviz_api.py#L316-L375
null
class DataTable(object): """Wraps the data to convert to a Google Visualization API DataTable. Create this object, populate it with data, then call one of the ToJS... methods to return a string representation of the data in the format described. You can clear all data from the object to reuse it, but you cann...
google/google-visualization-python
gviz_api.py
DataTable.TableDescriptionParser
python
def TableDescriptionParser(table_description, depth=0): # For the recursion step, we check for a scalar object (string or tuple) if isinstance(table_description, (six.string_types, tuple)): parsed_col = DataTable.ColumnTypeParser(table_description) parsed_col["depth"] = depth parsed_col["conta...
Parses the table_description object for internal use. Parses the user-submitted table description into an internal format used by the Python DataTable class. Returns the flat list of parsed columns. Args: table_description: A description of the table which should comply with...
train
https://github.com/google/google-visualization-python/blob/cbfb4d69ad2f4ca30dc55791629280aa3214c8e3/gviz_api.py#L378-L525
[ "def ColumnTypeParser(description):\n \"\"\"Parses a single column description. Internal helper method.\n\n Args:\n description: a column description in the possible formats:\n 'id'\n ('id',)\n ('id', 'type')\n ('id', 'type', 'label')\n ('id', 'type', 'label', {'custom_prop1': 'custom_val1'...
class DataTable(object): """Wraps the data to convert to a Google Visualization API DataTable. Create this object, populate it with data, then call one of the ToJS... methods to return a string representation of the data in the format described. You can clear all data from the object to reuse it, but you cann...
google/google-visualization-python
gviz_api.py
DataTable.SetRowsCustomProperties
python
def SetRowsCustomProperties(self, rows, custom_properties): if not hasattr(rows, "__iter__"): rows = [rows] for row in rows: self.__data[row] = (self.__data[row][0], custom_properties)
Sets the custom properties for given row(s). Can accept a single row or an iterable of rows. Sets the given custom properties for all specified rows. Args: rows: The row, or rows, to set the custom properties for. custom_properties: A string to string dictionary of custom properties to s...
train
https://github.com/google/google-visualization-python/blob/cbfb4d69ad2f4ca30dc55791629280aa3214c8e3/gviz_api.py#L536-L550
null
class DataTable(object): """Wraps the data to convert to a Google Visualization API DataTable. Create this object, populate it with data, then call one of the ToJS... methods to return a string representation of the data in the format described. You can clear all data from the object to reuse it, but you cann...
google/google-visualization-python
gviz_api.py
DataTable.LoadData
python
def LoadData(self, data, custom_properties=None): self.__data = [] self.AppendData(data, custom_properties)
Loads new rows to the data table, clearing existing rows. May also set the custom_properties for the added rows. The given custom properties dictionary specifies the dictionary that will be used for *all* given rows. Args: data: The rows that the table will contain. custom_properties: A di...
train
https://github.com/google/google-visualization-python/blob/cbfb4d69ad2f4ca30dc55791629280aa3214c8e3/gviz_api.py#L552-L565
[ "def AppendData(self, data, custom_properties=None):\n \"\"\"Appends new data to the table.\n\n Data is appended in rows. Data must comply with\n the table schema passed in to __init__(). See CoerceValue() for a list\n of acceptable data types. See the class documentation for more information\n and examples of...
class DataTable(object): """Wraps the data to convert to a Google Visualization API DataTable. Create this object, populate it with data, then call one of the ToJS... methods to return a string representation of the data in the format described. You can clear all data from the object to reuse it, but you cann...
google/google-visualization-python
gviz_api.py
DataTable.AppendData
python
def AppendData(self, data, custom_properties=None): # If the maximal depth is 0, we simply iterate over the data table # lines and insert them using _InnerAppendData. Otherwise, we simply # let the _InnerAppendData handle all the levels. if not self.__columns[-1]["depth"]: for row in data: ...
Appends new data to the table. Data is appended in rows. Data must comply with the table schema passed in to __init__(). See CoerceValue() for a list of acceptable data types. See the class documentation for more information and examples of schema and data values. Args: data: The row to add ...
train
https://github.com/google/google-visualization-python/blob/cbfb4d69ad2f4ca30dc55791629280aa3214c8e3/gviz_api.py#L567-L591
[ "def _InnerAppendData(self, prev_col_values, data, col_index):\n \"\"\"Inner function to assist LoadData.\"\"\"\n # We first check that col_index has not exceeded the columns size\n if col_index >= len(self.__columns):\n raise DataTableException(\"The data does not match description, too deep\")\n\n # Dealin...
class DataTable(object): """Wraps the data to convert to a Google Visualization API DataTable. Create this object, populate it with data, then call one of the ToJS... methods to return a string representation of the data in the format described. You can clear all data from the object to reuse it, but you cann...
google/google-visualization-python
gviz_api.py
DataTable._InnerAppendData
python
def _InnerAppendData(self, prev_col_values, data, col_index): # We first check that col_index has not exceeded the columns size if col_index >= len(self.__columns): raise DataTableException("The data does not match description, too deep") # Dealing with the scalar case, the data is the last value. ...
Inner function to assist LoadData.
train
https://github.com/google/google-visualization-python/blob/cbfb4d69ad2f4ca30dc55791629280aa3214c8e3/gviz_api.py#L593-L642
[ "def _InnerAppendData(self, prev_col_values, data, col_index):\n \"\"\"Inner function to assist LoadData.\"\"\"\n # We first check that col_index has not exceeded the columns size\n if col_index >= len(self.__columns):\n raise DataTableException(\"The data does not match description, too deep\")\n\n # Dealin...
class DataTable(object): """Wraps the data to convert to a Google Visualization API DataTable. Create this object, populate it with data, then call one of the ToJS... methods to return a string representation of the data in the format described. You can clear all data from the object to reuse it, but you cann...
google/google-visualization-python
gviz_api.py
DataTable._PreparedData
python
def _PreparedData(self, order_by=()): if not order_by: return self.__data sorted_data = self.__data[:] if isinstance(order_by, six.string_types) or ( isinstance(order_by, tuple) and len(order_by) == 2 and order_by[1].lower() in ["asc", "desc"]): order_by = (order_by,) for ke...
Prepares the data for enumeration - sorting it by order_by. Args: order_by: Optional. Specifies the name of the column(s) to sort by, and (optionally) which direction to sort in. Default sort direction is asc. Following formats are accepted: "string_col_name" ...
train
https://github.com/google/google-visualization-python/blob/cbfb4d69ad2f4ca30dc55791629280aa3214c8e3/gviz_api.py#L644-L681
null
class DataTable(object): """Wraps the data to convert to a Google Visualization API DataTable. Create this object, populate it with data, then call one of the ToJS... methods to return a string representation of the data in the format described. You can clear all data from the object to reuse it, but you cann...
google/google-visualization-python
gviz_api.py
DataTable.ToJSCode
python
def ToJSCode(self, name, columns_order=None, order_by=()): encoder = DataTableJSONEncoder() if columns_order is None: columns_order = [col["id"] for col in self.__columns] col_dict = dict([(col["id"], col) for col in self.__columns]) # We first create the table with the given name jscode = ...
Writes the data table as a JS code string. This method writes a string of JS code that can be run to generate a DataTable with the specified data. Typically used for debugging only. Args: name: The name of the table. The name would be used as the DataTable's variable name in the crea...
train
https://github.com/google/google-visualization-python/blob/cbfb4d69ad2f4ca30dc55791629280aa3214c8e3/gviz_api.py#L683-L768
[ "def _PreparedData(self, order_by=()):\n \"\"\"Prepares the data for enumeration - sorting it by order_by.\n\n Args:\n order_by: Optional. Specifies the name of the column(s) to sort by, and\n (optionally) which direction to sort in. Default sort direction\n is asc. Following formats ...
class DataTable(object): """Wraps the data to convert to a Google Visualization API DataTable. Create this object, populate it with data, then call one of the ToJS... methods to return a string representation of the data in the format described. You can clear all data from the object to reuse it, but you cann...
google/google-visualization-python
gviz_api.py
DataTable.ToHtml
python
def ToHtml(self, columns_order=None, order_by=()): table_template = "<html><body><table border=\"1\">%s</table></body></html>" columns_template = "<thead><tr>%s</tr></thead>" rows_template = "<tbody>%s</tbody>" row_template = "<tr>%s</tr>" header_cell_template = "<th>%s</th>" cell_template = "<t...
Writes the data table as an HTML table code string. Args: columns_order: Optional. Specifies the order of columns in the output table. Specify a list of all column IDs in the order in which you want the table created. Note that you must list all ...
train
https://github.com/google/google-visualization-python/blob/cbfb4d69ad2f4ca30dc55791629280aa3214c8e3/gviz_api.py#L770-L831
[ "def CoerceValue(value, value_type):\n \"\"\"Coerces a single value into the type expected for its column.\n\n Internal helper method.\n\n Args:\n value: The value which should be converted\n value_type: One of \"string\", \"number\", \"boolean\", \"date\", \"datetime\" or\n \"timeofday\".\n...
class DataTable(object): """Wraps the data to convert to a Google Visualization API DataTable. Create this object, populate it with data, then call one of the ToJS... methods to return a string representation of the data in the format described. You can clear all data from the object to reuse it, but you cann...
google/google-visualization-python
gviz_api.py
DataTable.ToCsv
python
def ToCsv(self, columns_order=None, order_by=(), separator=","): csv_buffer = six.StringIO() writer = csv.writer(csv_buffer, delimiter=separator) if columns_order is None: columns_order = [col["id"] for col in self.__columns] col_dict = dict([(col["id"], col) for col in self.__columns]) def...
Writes the data table as a CSV string. Output is encoded in UTF-8 because the Python "csv" module can't handle Unicode properly according to its documentation. Args: columns_order: Optional. Specifies the order of columns in the output table. Specify a list of all column IDs in ...
train
https://github.com/google/google-visualization-python/blob/cbfb4d69ad2f4ca30dc55791629280aa3214c8e3/gviz_api.py#L833-L893
[ "def CoerceValue(value, value_type):\n \"\"\"Coerces a single value into the type expected for its column.\n\n Internal helper method.\n\n Args:\n value: The value which should be converted\n value_type: One of \"string\", \"number\", \"boolean\", \"date\", \"datetime\" or\n \"timeofday\".\n...
class DataTable(object): """Wraps the data to convert to a Google Visualization API DataTable. Create this object, populate it with data, then call one of the ToJS... methods to return a string representation of the data in the format described. You can clear all data from the object to reuse it, but you cann...
google/google-visualization-python
gviz_api.py
DataTable.ToTsvExcel
python
def ToTsvExcel(self, columns_order=None, order_by=()): csv_result = self.ToCsv(columns_order, order_by, separator="\t") if not isinstance(csv_result, six.text_type): csv_result = csv_result.decode("utf-8") return csv_result.encode("UTF-16LE")
Returns a file in tab-separated-format readable by MS Excel. Returns a file in UTF-16 little endian encoding, with tabs separating the values. Args: columns_order: Delegated to ToCsv. order_by: Delegated to ToCsv. Returns: A tab-separated little endian UTF16 file representing the ta...
train
https://github.com/google/google-visualization-python/blob/cbfb4d69ad2f4ca30dc55791629280aa3214c8e3/gviz_api.py#L895-L911
[ "def ToCsv(self, columns_order=None, order_by=(), separator=\",\"):\n \"\"\"Writes the data table as a CSV string.\n\n Output is encoded in UTF-8 because the Python \"csv\" module can't handle\n Unicode properly according to its documentation.\n\n Args:\n columns_order: Optional. Specifies the order of colum...
class DataTable(object): """Wraps the data to convert to a Google Visualization API DataTable. Create this object, populate it with data, then call one of the ToJS... methods to return a string representation of the data in the format described. You can clear all data from the object to reuse it, but you cann...
google/google-visualization-python
gviz_api.py
DataTable._ToJSonObj
python
def _ToJSonObj(self, columns_order=None, order_by=()): if columns_order is None: columns_order = [col["id"] for col in self.__columns] col_dict = dict([(col["id"], col) for col in self.__columns]) # Creating the column JSON objects col_objs = [] for col_id in columns_order: col_obj = {"...
Returns an object suitable to be converted to JSON. Args: columns_order: Optional. A list of all column IDs in the order in which you want them created in the output table. If specified, all column IDs must be present. order_by: Optional. Specifies the name of ...
train
https://github.com/google/google-visualization-python/blob/cbfb4d69ad2f4ca30dc55791629280aa3214c8e3/gviz_api.py#L913-L966
[ "def CoerceValue(value, value_type):\n \"\"\"Coerces a single value into the type expected for its column.\n\n Internal helper method.\n\n Args:\n value: The value which should be converted\n value_type: One of \"string\", \"number\", \"boolean\", \"date\", \"datetime\" or\n \"timeofday\".\n...
class DataTable(object): """Wraps the data to convert to a Google Visualization API DataTable. Create this object, populate it with data, then call one of the ToJS... methods to return a string representation of the data in the format described. You can clear all data from the object to reuse it, but you cann...
google/google-visualization-python
gviz_api.py
DataTable.ToJSon
python
def ToJSon(self, columns_order=None, order_by=()): encoded_response_str = DataTableJSONEncoder().encode(self._ToJSonObj(columns_order, order_by)) if not isinstance(encoded_response_str, str): return encoded_response_str.encode("utf-8") return encoded_response_str
Returns a string that can be used in a JS DataTable constructor. This method writes a JSON string that can be passed directly into a Google Visualization API DataTable constructor. Use this output if you are hosting the visualization HTML on your site, and want to code the data table in Python. Pass th...
train
https://github.com/google/google-visualization-python/blob/cbfb4d69ad2f4ca30dc55791629280aa3214c8e3/gviz_api.py#L968-L1009
[ "def _ToJSonObj(self, columns_order=None, order_by=()):\n \"\"\"Returns an object suitable to be converted to JSON.\n\n Args:\n columns_order: Optional. A list of all column IDs in the order in which\n you want them created in the output table. If specified,\n all column IDs...
class DataTable(object): """Wraps the data to convert to a Google Visualization API DataTable. Create this object, populate it with data, then call one of the ToJS... methods to return a string representation of the data in the format described. You can clear all data from the object to reuse it, but you cann...
google/google-visualization-python
gviz_api.py
DataTable.ToJSonResponse
python
def ToJSonResponse(self, columns_order=None, order_by=(), req_id=0, response_handler="google.visualization.Query.setResponse"): response_obj = { "version": "0.6", "reqId": str(req_id), "table": self._ToJSonObj(columns_order, order_by), "status": "ok" } e...
Writes a table as a JSON response that can be returned as-is to a client. This method writes a JSON response to return to a client in response to a Google Visualization API query. This string can be processed by the calling page, and is used to deliver a data table to a visualization hosted on a differ...
train
https://github.com/google/google-visualization-python/blob/cbfb4d69ad2f4ca30dc55791629280aa3214c8e3/gviz_api.py#L1011-L1049
[ "def _ToJSonObj(self, columns_order=None, order_by=()):\n \"\"\"Returns an object suitable to be converted to JSON.\n\n Args:\n columns_order: Optional. A list of all column IDs in the order in which\n you want them created in the output table. If specified,\n all column IDs...
class DataTable(object): """Wraps the data to convert to a Google Visualization API DataTable. Create this object, populate it with data, then call one of the ToJS... methods to return a string representation of the data in the format described. You can clear all data from the object to reuse it, but you cann...
google/google-visualization-python
gviz_api.py
DataTable.ToResponse
python
def ToResponse(self, columns_order=None, order_by=(), tqx=""): tqx_dict = {} if tqx: tqx_dict = dict(opt.split(":") for opt in tqx.split(";")) if tqx_dict.get("version", "0.6") != "0.6": raise DataTableException( "Version (%s) passed by request is not supported." % tqx_dict["...
Writes the right response according to the request string passed in tqx. This method parses the tqx request string (format of which is defined in the documentation for implementing a data source of Google Visualization), and returns the right response according to the request. It parses out the "out" p...
train
https://github.com/google/google-visualization-python/blob/cbfb4d69ad2f4ca30dc55791629280aa3214c8e3/gviz_api.py#L1051-L1098
null
class DataTable(object): """Wraps the data to convert to a Google Visualization API DataTable. Create this object, populate it with data, then call one of the ToJS... methods to return a string representation of the data in the format described. You can clear all data from the object to reuse it, but you cann...
inveniosoftware/invenio-records
invenio_records/alembic/07fb52561c5c_alter_column_from_json_to_jsonb.py
upgrade
python
def upgrade(): if op._proxy.migration_context.dialect.name == 'postgresql': op.alter_column( 'records_metadata', 'json', type_=sa.dialects.postgresql.JSONB, postgresql_using='json::text::jsonb' )
Upgrade database.
train
https://github.com/inveniosoftware/invenio-records/blob/b0b1481d04012e45cb71b5ae4019e91dde88d1e2/invenio_records/alembic/07fb52561c5c_alter_column_from_json_to_jsonb.py#L21-L29
null
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2017-2018 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Alter column from json to jsonb.""" import sqlalchemy as sa from alembic import o...
inveniosoftware/invenio-records
invenio_records/alembic/07fb52561c5c_alter_column_from_json_to_jsonb.py
downgrade
python
def downgrade(): if op._proxy.migration_context.dialect.name == 'postgresql': op.alter_column( 'records_metadata', 'json', type_=sa.dialects.postgresql.JSON, postgresql_using='json::text::json' )
Downgrade database.
train
https://github.com/inveniosoftware/invenio-records/blob/b0b1481d04012e45cb71b5ae4019e91dde88d1e2/invenio_records/alembic/07fb52561c5c_alter_column_from_json_to_jsonb.py#L32-L40
null
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2017-2018 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Alter column from json to jsonb.""" import sqlalchemy as sa from alembic import o...
inveniosoftware/invenio-records
invenio_records/api.py
RecordBase.validate
python
def validate(self, **kwargs): r"""Validate record according to schema defined in ``$schema`` key. :Keyword Arguments: * **format_checker** -- A ``format_checker`` is an instance of class :class:`jsonschema.FormatChecker` containing business logic to validat...
r"""Validate record according to schema defined in ``$schema`` key. :Keyword Arguments: * **format_checker** -- A ``format_checker`` is an instance of class :class:`jsonschema.FormatChecker` containing business logic to validate arbitrary formats. For example: ...
train
https://github.com/inveniosoftware/invenio-records/blob/b0b1481d04012e45cb71b5ae4019e91dde88d1e2/invenio_records/api.py#L62-L126
null
class RecordBase(dict): """Base class for Record and RecordBase.""" def __init__(self, data, model=None): """Initialize instance with dictionary data and SQLAlchemy model. :param data: Dict with record metadata. :param model: :class:`~invenio_records.models.RecordMetadata` instance. ...
inveniosoftware/invenio-records
invenio_records/api.py
Record.create
python
def create(cls, data, id_=None, **kwargs): r"""Create a new record instance and store it in the database. #. Send a signal :data:`invenio_records.signals.before_record_insert` with the new record as parameter. #. Validate the new record data. #. Add the new record in the da...
r"""Create a new record instance and store it in the database. #. Send a signal :data:`invenio_records.signals.before_record_insert` with the new record as parameter. #. Validate the new record data. #. Add the new record in the database. #. Send a signal :data:`invenio_re...
train
https://github.com/inveniosoftware/invenio-records/blob/b0b1481d04012e45cb71b5ae4019e91dde88d1e2/invenio_records/api.py#L141-L189
[ "def validate(self, **kwargs):\n r\"\"\"Validate record according to schema defined in ``$schema`` key.\n\n :Keyword Arguments:\n * **format_checker** --\n A ``format_checker`` is an instance of class\n :class:`jsonschema.FormatChecker` containing business logic to\n validate arbitra...
class Record(RecordBase): """Define API for metadata creation and manipulation.""" @classmethod @classmethod def get_record(cls, id_, with_deleted=False): """Retrieve the record by id. Raise a database exception if the record does not exist. :param id_: record ID. :p...
inveniosoftware/invenio-records
invenio_records/api.py
Record.get_record
python
def get_record(cls, id_, with_deleted=False): with db.session.no_autoflush: query = RecordMetadata.query.filter_by(id=id_) if not with_deleted: query = query.filter(RecordMetadata.json != None) # noqa obj = query.one() return cls(obj.json, model=o...
Retrieve the record by id. Raise a database exception if the record does not exist. :param id_: record ID. :param with_deleted: If `True` then it includes deleted records. :returns: The :class:`Record` instance.
train
https://github.com/inveniosoftware/invenio-records/blob/b0b1481d04012e45cb71b5ae4019e91dde88d1e2/invenio_records/api.py#L192-L206
null
class Record(RecordBase): """Define API for metadata creation and manipulation.""" @classmethod def create(cls, data, id_=None, **kwargs): r"""Create a new record instance and store it in the database. #. Send a signal :data:`invenio_records.signals.before_record_insert` with th...
inveniosoftware/invenio-records
invenio_records/api.py
Record.get_records
python
def get_records(cls, ids, with_deleted=False): with db.session.no_autoflush: query = RecordMetadata.query.filter(RecordMetadata.id.in_(ids)) if not with_deleted: query = query.filter(RecordMetadata.json != None) # noqa return [cls(obj.json, model=obj) for ob...
Retrieve multiple records by id. :param ids: List of record IDs. :param with_deleted: If `True` then it includes deleted records. :returns: A list of :class:`Record` instances.
train
https://github.com/inveniosoftware/invenio-records/blob/b0b1481d04012e45cb71b5ae4019e91dde88d1e2/invenio_records/api.py#L209-L221
null
class Record(RecordBase): """Define API for metadata creation and manipulation.""" @classmethod def create(cls, data, id_=None, **kwargs): r"""Create a new record instance and store it in the database. #. Send a signal :data:`invenio_records.signals.before_record_insert` with th...
inveniosoftware/invenio-records
invenio_records/api.py
Record.patch
python
def patch(self, patch): data = apply_patch(dict(self), patch) return self.__class__(data, model=self.model)
Patch record metadata. :params patch: Dictionary of record metadata. :returns: A new :class:`Record` instance.
train
https://github.com/inveniosoftware/invenio-records/blob/b0b1481d04012e45cb71b5ae4019e91dde88d1e2/invenio_records/api.py#L223-L230
null
class Record(RecordBase): """Define API for metadata creation and manipulation.""" @classmethod def create(cls, data, id_=None, **kwargs): r"""Create a new record instance and store it in the database. #. Send a signal :data:`invenio_records.signals.before_record_insert` with th...
inveniosoftware/invenio-records
invenio_records/api.py
Record.commit
python
def commit(self, **kwargs): r"""Store changes of the current record instance in the database. #. Send a signal :data:`invenio_records.signals.before_record_update` with the current record to be committed as parameter. #. Validate the current record data. #. Commit the curre...
r"""Store changes of the current record instance in the database. #. Send a signal :data:`invenio_records.signals.before_record_update` with the current record to be committed as parameter. #. Validate the current record data. #. Commit the current record in the database. ...
train
https://github.com/inveniosoftware/invenio-records/blob/b0b1481d04012e45cb71b5ae4019e91dde88d1e2/invenio_records/api.py#L232-L278
[ "def validate(self, **kwargs):\n r\"\"\"Validate record according to schema defined in ``$schema`` key.\n\n :Keyword Arguments:\n * **format_checker** --\n A ``format_checker`` is an instance of class\n :class:`jsonschema.FormatChecker` containing business logic to\n validate arbitra...
class Record(RecordBase): """Define API for metadata creation and manipulation.""" @classmethod def create(cls, data, id_=None, **kwargs): r"""Create a new record instance and store it in the database. #. Send a signal :data:`invenio_records.signals.before_record_insert` with th...
inveniosoftware/invenio-records
invenio_records/api.py
Record.delete
python
def delete(self, force=False): if self.model is None: raise MissingModelError() with db.session.begin_nested(): before_record_delete.send( current_app._get_current_object(), record=self ) if force: db.sessi...
Delete a record. If `force` is ``False``, the record is soft-deleted: record data will be deleted but the record identifier and the history of the record will be kept. This ensures that the same record identifier cannot be used twice, and that you can still retrieve its history. If `for...
train
https://github.com/inveniosoftware/invenio-records/blob/b0b1481d04012e45cb71b5ae4019e91dde88d1e2/invenio_records/api.py#L280-L320
null
class Record(RecordBase): """Define API for metadata creation and manipulation.""" @classmethod def create(cls, data, id_=None, **kwargs): r"""Create a new record instance and store it in the database. #. Send a signal :data:`invenio_records.signals.before_record_insert` with th...
inveniosoftware/invenio-records
invenio_records/api.py
Record.revert
python
def revert(self, revision_id): if self.model is None: raise MissingModelError() revision = self.revisions[revision_id] with db.session.begin_nested(): before_record_revert.send( current_app._get_current_object(), record=self )...
Revert the record to a specific revision. #. Send a signal :data:`invenio_records.signals.before_record_revert` with the current record as parameter. #. Revert the record to the revision id passed as parameter. #. Send a signal :data:`invenio_records.signals.after_record_revert` ...
train
https://github.com/inveniosoftware/invenio-records/blob/b0b1481d04012e45cb71b5ae4019e91dde88d1e2/invenio_records/api.py#L322-L355
null
class Record(RecordBase): """Define API for metadata creation and manipulation.""" @classmethod def create(cls, data, id_=None, **kwargs): r"""Create a new record instance and store it in the database. #. Send a signal :data:`invenio_records.signals.before_record_insert` with th...
inveniosoftware/invenio-records
invenio_records/cli.py
create
python
def create(source, ids, force, pid_minter=None): records_deprecation_warning() # Make sure that all imports are done with application context. from .api import Record from .models import RecordMetadata pid_minter = [process_minter(minter) for minter in pid_minter or []] data = json.load(sourc...
Create new bibliographic record(s).
train
https://github.com/inveniosoftware/invenio-records/blob/b0b1481d04012e45cb71b5ae4019e91dde88d1e2/invenio_records/cli.py#L82-L130
[ "def records_deprecation_warning():\n \"\"\"Add deprecation warning for records cli.\"\"\"\n warnings.warn('The Invenio-Records cli module is deprecated.',\n PendingDeprecationWarning)\n", "def create(cls, data, id_=None, **kwargs):\n r\"\"\"Create a new record instance and store it in t...
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2015-2018 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Click command-line interface for record management.""" from __future__ import abs...
inveniosoftware/invenio-records
invenio_records/cli.py
patch
python
def patch(patch, ids): records_deprecation_warning() from .api import Record patch_content = patch.read() if ids: for id_ in ids: rec = Record.get_record(id_).patch(patch_content).commit() current_app.logger.info("Created new revision {0}".format( rec.r...
Patch existing bibliographic record.
train
https://github.com/inveniosoftware/invenio-records/blob/b0b1481d04012e45cb71b5ae4019e91dde88d1e2/invenio_records/cli.py#L137-L151
[ "def records_deprecation_warning():\n \"\"\"Add deprecation warning for records cli.\"\"\"\n warnings.warn('The Invenio-Records cli module is deprecated.',\n PendingDeprecationWarning)\n", "def get_record(cls, id_, with_deleted=False):\n \"\"\"Retrieve the record by id.\n\n Raise a da...
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2015-2018 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Click command-line interface for record management.""" from __future__ import abs...
inveniosoftware/invenio-records
invenio_records/cli.py
delete
python
def delete(ids, force): records_deprecation_warning() from .api import Record for id_ in ids: record = Record.get_record(id_, with_deleted=force) record.delete(force=force) db.session.commit()
Delete bibliographic record(s).
train
https://github.com/inveniosoftware/invenio-records/blob/b0b1481d04012e45cb71b5ae4019e91dde88d1e2/invenio_records/cli.py#L158-L166
[ "def records_deprecation_warning():\n \"\"\"Add deprecation warning for records cli.\"\"\"\n warnings.warn('The Invenio-Records cli module is deprecated.',\n PendingDeprecationWarning)\n", "def get_record(cls, id_, with_deleted=False):\n \"\"\"Retrieve the record by id.\n\n Raise a da...
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2015-2018 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Click command-line interface for record management.""" from __future__ import abs...
inveniosoftware/invenio-records
invenio_records/alembic/862037093962_create_records_tables.py
upgrade
python
def upgrade(): op.create_table( 'records_metadata', sa.Column('created', sa.DateTime(), nullable=False), sa.Column('updated', sa.DateTime(), nullable=False), sa.Column( 'id', sqlalchemy_utils.types.uuid.UUIDType(), nullable=False), sa.Column('json', sqlalchemy_uti...
Upgrade database.
train
https://github.com/inveniosoftware/invenio-records/blob/b0b1481d04012e45cb71b5ae4019e91dde88d1e2/invenio_records/alembic/862037093962_create_records_tables.py#L22-L70
null
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2016-2018 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Create records tables.""" import sqlalchemy as sa import sqlalchemy_utils from al...
inveniosoftware/invenio-records
invenio_records/ext.py
_RecordsState.validate
python
def validate(self, data, schema, **kwargs): if not isinstance(schema, dict): schema = {'$ref': schema} return validate( data, schema, resolver=self.ref_resolver_cls.from_schema(schema), types=self.app.config.get('RECORDS_VALIDATION_TYPES', {}),...
Validate data using schema with ``JSONResolver``.
train
https://github.com/inveniosoftware/invenio-records/blob/b0b1481d04012e45cb71b5ae4019e91dde88d1e2/invenio_records/ext.py#L32-L42
null
class _RecordsState(object): """State for record JSON resolver.""" def __init__(self, app, entry_point_group=None): """Initialize state.""" self.app = app self.resolver = JSONResolver(entry_point_group=entry_point_group) self.ref_resolver_cls = ref_resolver_factory(self.resolver...
inveniosoftware/invenio-records
invenio_records/admin.py
RecordMetadataModelView.delete_model
python
def delete_model(self, model): try: if model.json is None: return True record = Record(model.json, model=model) record.delete() db.session.commit() except SQLAlchemyError as e: if not self.handle_view_exception(e): ...
Delete a record.
train
https://github.com/inveniosoftware/invenio-records/blob/b0b1481d04012e45cb71b5ae4019e91dde88d1e2/invenio_records/admin.py#L49-L63
[ "def delete(self, force=False):\n \"\"\"Delete a record.\n\n If `force` is ``False``, the record is soft-deleted: record data will\n be deleted but the record identifier and the history of the record will\n be kept. This ensures that the same record identifier cannot be used\n twice, and that you can...
class RecordMetadataModelView(ModelView): """Records admin model view.""" filter_converter = FilterConverter() can_create = False can_edit = False can_delete = True can_view_details = True column_list = ('id', 'version_id', 'updated', 'created',) column_details_list = ('id', 'version_id...
shinux/PyTime
pytime/filter.py
BaseParser._str_parser
python
def _str_parser(string): if not any(c.isalpha() for c in string): _string = string[:19] _length = len(_string) if _length > 10: return BaseParser.parse_datetime elif 6 <= _length <= 10: if ':' in _string: return ...
return method by the length of string :param string: string :return: method
train
https://github.com/shinux/PyTime/blob/f2b9f877507e2a1dddf5dd255fdff243a5dbed48/pytime/filter.py#L86-L107
null
class BaseParser(object): """Parse string to regular datetime/date type 1990-10-28 23:23:23 - 19 90-10-28 23:23:23 - 17 1990-10-28 - 10 28-10-1990 - 10 1990/10/28 - 10 28/10/1990 - 10 1990.10.28 - 10 28.10.1990 - 10 ...
shinux/PyTime
pytime/filter.py
BaseParser.parse_date
python
def parse_date(string, formation=None): if formation: _stamp = datetime.datetime.strptime(string, formation).date() return _stamp _string = string.replace('.', '-').replace('/', '-') if '-' in _string: if len(_string.split('-')[0]) > 3 or len(_string.split('-...
string to date stamp :param string: date string :param formation: format string :return: datetime.date
train
https://github.com/shinux/PyTime/blob/f2b9f877507e2a1dddf5dd255fdff243a5dbed48/pytime/filter.py#L178-L220
null
class BaseParser(object): """Parse string to regular datetime/date type 1990-10-28 23:23:23 - 19 90-10-28 23:23:23 - 17 1990-10-28 - 10 28-10-1990 - 10 1990/10/28 - 10 28/10/1990 - 10 1990.10.28 - 10 28.10.1990 - 10 ...
shinux/PyTime
pytime/filter.py
BaseParser.parse_diff
python
def parse_diff(base_str): temp_dict = {'years': 0, 'months': 0, 'weeks': 0, 'days': 0, 'hours': 0, 'minutes': 0, 'seconds': 0} _pure_str = re.findall("[a-zA-Z]+", base_str) ...
parse string to regular timedelta :param base_str: str :return: dict
train
https://github.com/shinux/PyTime/blob/f2b9f877507e2a1dddf5dd255fdff243a5dbed48/pytime/filter.py#L231-L256
null
class BaseParser(object): """Parse string to regular datetime/date type 1990-10-28 23:23:23 - 19 90-10-28 23:23:23 - 17 1990-10-28 - 10 28-10-1990 - 10 1990/10/28 - 10 28/10/1990 - 10 1990.10.28 - 10 28.10.1990 - 10 ...
shinux/PyTime
pytime/filter.py
BaseParser.from_str
python
def from_str(date): month = date[:3][0] + date[:3][-2:].lower() if month not in NAMED_MONTHS: raise CanNotFormatError('Month not recognized') date = date.replace(',', '').replace(' ', '').replace('.', '') try: day_unit = [x for x in ['st', 'rd', 'nd', 'th'] if x ...
Given a date in the format: Jan,21st.2015 will return a datetime of it.
train
https://github.com/shinux/PyTime/blob/f2b9f877507e2a1dddf5dd255fdff243a5dbed48/pytime/filter.py#L259-L276
null
class BaseParser(object): """Parse string to regular datetime/date type 1990-10-28 23:23:23 - 19 90-10-28 23:23:23 - 17 1990-10-28 - 10 28-10-1990 - 10 1990/10/28 - 10 28/10/1990 - 10 1990.10.28 - 10 28.10.1990 - 10 ...
shinux/PyTime
pytime/pytime.py
today
python
def today(year=None): return datetime.date(int(year), _date.month, _date.day) if year else _date
this day, last year
train
https://github.com/shinux/PyTime/blob/f2b9f877507e2a1dddf5dd255fdff243a5dbed48/pytime/pytime.py#L50-L52
null
#!/usr/bin/env python # encoding: utf-8 """ pytime ~~~~~~~~~~~~~ A easy-use module to solve the datetime needs by string. :copyright: (c) 2015 by Sinux <nsinux@gmail.com> :license: MIT, see LICENSE for more details. """ import datetime import calendar from .filter import BaseParser bp = BasePa...
shinux/PyTime
pytime/pytime.py
tomorrow
python
def tomorrow(date=None): if not date: return _date + datetime.timedelta(days=1) else: current_date = parse(date) return current_date + datetime.timedelta(days=1)
tomorrow is another day
train
https://github.com/shinux/PyTime/blob/f2b9f877507e2a1dddf5dd255fdff243a5dbed48/pytime/pytime.py#L55-L61
[ "def parse(value):\n return bp(value)\n" ]
#!/usr/bin/env python # encoding: utf-8 """ pytime ~~~~~~~~~~~~~ A easy-use module to solve the datetime needs by string. :copyright: (c) 2015 by Sinux <nsinux@gmail.com> :license: MIT, see LICENSE for more details. """ import datetime import calendar from .filter import BaseParser bp = BasePa...
shinux/PyTime
pytime/pytime.py
yesterday
python
def yesterday(date=None): if not date: return _date - datetime.timedelta(days=1) else: current_date = parse(date) return current_date - datetime.timedelta(days=1)
yesterday once more
train
https://github.com/shinux/PyTime/blob/f2b9f877507e2a1dddf5dd255fdff243a5dbed48/pytime/pytime.py#L64-L70
[ "def parse(value):\n return bp(value)\n" ]
#!/usr/bin/env python # encoding: utf-8 """ pytime ~~~~~~~~~~~~~ A easy-use module to solve the datetime needs by string. :copyright: (c) 2015 by Sinux <nsinux@gmail.com> :license: MIT, see LICENSE for more details. """ import datetime import calendar from .filter import BaseParser bp = BasePa...
shinux/PyTime
pytime/pytime.py
days_range
python
def days_range(first=None, second=None, wipe=False): _first, _second = parse(first), parse(second) (_start, _end) = (_second, _first) if _first > _second else (_first, _second) days_between = (_end - _start).days date_list = [_end - datetime.timedelta(days=x) for x in range(0, days_between + 1)] if ...
get all days between first and second :param first: datetime, date or string :param second: datetime, date or string :param wipe: boolean, excludes first and last date from range when True. Default is False. :return: list
train
https://github.com/shinux/PyTime/blob/f2b9f877507e2a1dddf5dd255fdff243a5dbed48/pytime/pytime.py#L78-L93
[ "def parse(value):\n return bp(value)\n" ]
#!/usr/bin/env python # encoding: utf-8 """ pytime ~~~~~~~~~~~~~ A easy-use module to solve the datetime needs by string. :copyright: (c) 2015 by Sinux <nsinux@gmail.com> :license: MIT, see LICENSE for more details. """ import datetime import calendar from .filter import BaseParser bp = BasePa...
shinux/PyTime
pytime/pytime.py
last_day
python
def last_day(year=_year, month=_month): last_day = calendar.monthrange(year, month)[1] return datetime.date(year=year, month=month, day=last_day)
get the current month's last day :param year: default to current year :param month: default to current month :return: month's last day
train
https://github.com/shinux/PyTime/blob/f2b9f877507e2a1dddf5dd255fdff243a5dbed48/pytime/pytime.py#L96-L104
null
#!/usr/bin/env python # encoding: utf-8 """ pytime ~~~~~~~~~~~~~ A easy-use module to solve the datetime needs by string. :copyright: (c) 2015 by Sinux <nsinux@gmail.com> :license: MIT, see LICENSE for more details. """ import datetime import calendar from .filter import BaseParser bp = BasePa...
shinux/PyTime
pytime/pytime.py
midnight
python
def midnight(arg=None): if arg: _arg = parse(arg) if isinstance(_arg, datetime.date): return datetime.datetime.combine(_arg, datetime.datetime.min.time()) elif isinstance(_arg, datetime.datetime): return datetime.datetime.combine(_arg.date(), datetime.datetime.min.tim...
convert date to datetime as midnight or get current day's midnight :param arg: string or date/datetime :return: datetime at 00:00:00
train
https://github.com/shinux/PyTime/blob/f2b9f877507e2a1dddf5dd255fdff243a5dbed48/pytime/pytime.py#L107-L120
[ "def parse(value):\n return bp(value)\n" ]
#!/usr/bin/env python # encoding: utf-8 """ pytime ~~~~~~~~~~~~~ A easy-use module to solve the datetime needs by string. :copyright: (c) 2015 by Sinux <nsinux@gmail.com> :license: MIT, see LICENSE for more details. """ import datetime import calendar from .filter import BaseParser bp = BasePa...
shinux/PyTime
pytime/pytime.py
before
python
def before(base=_datetime, diff=None): _base = parse(base) if isinstance(_base, datetime.date): _base = midnight(_base) if not diff: return _base result_dict = dp(diff) # weeks already convert to days in diff_parse function(dp) for unit in result_dict: _val = result_dict[...
count datetime before `base` time :param base: minuend -> str/datetime/date :param diff: str :return: datetime
train
https://github.com/shinux/PyTime/blob/f2b9f877507e2a1dddf5dd255fdff243a5dbed48/pytime/pytime.py#L123-L151
[ "def parse(value):\n return bp(value)\n", "def parse_diff(base_str):\n \"\"\"\n parse string to regular timedelta\n :param base_str: str\n :return: dict\n \"\"\"\n temp_dict = {'years': 0,\n 'months': 0,\n 'weeks': 0,\n 'days': 0,\n ...
#!/usr/bin/env python # encoding: utf-8 """ pytime ~~~~~~~~~~~~~ A easy-use module to solve the datetime needs by string. :copyright: (c) 2015 by Sinux <nsinux@gmail.com> :license: MIT, see LICENSE for more details. """ import datetime import calendar from .filter import BaseParser bp = BasePa...
shinux/PyTime
pytime/pytime.py
_datetime_to_date
python
def _datetime_to_date(arg): _arg = parse(arg) if isinstance(_arg, datetime.datetime): _arg = _arg.date() return _arg
convert datetime/str to date :param arg: :return:
train
https://github.com/shinux/PyTime/blob/f2b9f877507e2a1dddf5dd255fdff243a5dbed48/pytime/pytime.py#L182-L191
[ "def parse(value):\n return bp(value)\n" ]
#!/usr/bin/env python # encoding: utf-8 """ pytime ~~~~~~~~~~~~~ A easy-use module to solve the datetime needs by string. :copyright: (c) 2015 by Sinux <nsinux@gmail.com> :license: MIT, see LICENSE for more details. """ import datetime import calendar from .filter import BaseParser bp = BasePa...
shinux/PyTime
pytime/pytime.py
mother
python
def mother(year=None): may_first = datetime.date(_year, 5, 1) if not year else datetime.date(int(year), 5, 1) weekday_seq = may_first.weekday() return datetime.date(may_first.year, 5, (14 - weekday_seq))
the 2nd Sunday in May :param year: int :return: Mother's day
train
https://github.com/shinux/PyTime/blob/f2b9f877507e2a1dddf5dd255fdff243a5dbed48/pytime/pytime.py#L260-L268
null
#!/usr/bin/env python # encoding: utf-8 """ pytime ~~~~~~~~~~~~~ A easy-use module to solve the datetime needs by string. :copyright: (c) 2015 by Sinux <nsinux@gmail.com> :license: MIT, see LICENSE for more details. """ import datetime import calendar from .filter import BaseParser bp = BasePa...
shinux/PyTime
pytime/pytime.py
father
python
def father(year=None): june_first = datetime.date(_year, 6, 1) if not year else datetime.date(int(year), 6, 1) weekday_seq = june_first.weekday() return datetime.date(june_first.year, 6, (21 - weekday_seq))
the 3rd Sunday in June :param year: int :return: Father's day
train
https://github.com/shinux/PyTime/blob/f2b9f877507e2a1dddf5dd255fdff243a5dbed48/pytime/pytime.py#L271-L279
null
#!/usr/bin/env python # encoding: utf-8 """ pytime ~~~~~~~~~~~~~ A easy-use module to solve the datetime needs by string. :copyright: (c) 2015 by Sinux <nsinux@gmail.com> :license: MIT, see LICENSE for more details. """ import datetime import calendar from .filter import BaseParser bp = BasePa...
shinux/PyTime
pytime/pytime.py
easter
python
def easter(year=None): y = int(year) if year else _year n = y - 1900 a = n % 19 q = n // 4 b = (7 * a + 1) // 19 m = (11 * a + 4 - b) % 29 w = (n + q + 31 - m) % 7 d = 25 - m - w if d > 0: return datetime.date(y, 4, d) else: return datetime.date(y, 3, (31 + d))
1900 - 2099 limit :param year: int :return: Easter day
train
https://github.com/shinux/PyTime/blob/f2b9f877507e2a1dddf5dd255fdff243a5dbed48/pytime/pytime.py#L286-L303
null
#!/usr/bin/env python # encoding: utf-8 """ pytime ~~~~~~~~~~~~~ A easy-use module to solve the datetime needs by string. :copyright: (c) 2015 by Sinux <nsinux@gmail.com> :license: MIT, see LICENSE for more details. """ import datetime import calendar from .filter import BaseParser bp = BasePa...
shinux/PyTime
pytime/pytime.py
thanks
python
def thanks(year=None): nov_first = datetime.date(_year, 11, 1) if not year else datetime.date(int(year), 11, 1) weekday_seq = nov_first.weekday() if weekday_seq > 3: current_day = 32 - weekday_seq else: current_day = 25 - weekday_seq return datetime.date(nov_first.year, 11, current_d...
4rd Thursday in Nov :param year: int :return: Thanksgiving Day
train
https://github.com/shinux/PyTime/blob/f2b9f877507e2a1dddf5dd255fdff243a5dbed48/pytime/pytime.py#L306-L318
null
#!/usr/bin/env python # encoding: utf-8 """ pytime ~~~~~~~~~~~~~ A easy-use module to solve the datetime needs by string. :copyright: (c) 2015 by Sinux <nsinux@gmail.com> :license: MIT, see LICENSE for more details. """ import datetime import calendar from .filter import BaseParser bp = BasePa...
achiku/jungle
jungle/rds.py
format_output
python
def format_output(instances, flag): out = [] line_format = '{0}\t{1}\t{2}\t{3}' name_len = _get_max_name_len(instances) + 3 if flag: line_format = '{0:<' + str(name_len+5) + '}{1:<16}{2:<65}{3:<16}' for i in instances: endpoint = "{0}:{1}".format(i['Endpoint']['Address'], i['Endpoin...
return formatted string per instance
train
https://github.com/achiku/jungle/blob/fb63f845cfa9e9c0dfbabd8cfa3ebca8177a11ca/jungle/rds.py#L6-L18
[ "def _get_max_name_len(instances):\n \"\"\"get max length of Tag:Name\"\"\"\n for i in instances:\n return max([len(i['DBInstanceIdentifier']) for i in instances])\n return 0\n" ]
# -*- coding: utf-8 -*- import click from jungle.session import create_session def _get_max_name_len(instances): """get max length of Tag:Name""" for i in instances: return max([len(i['DBInstanceIdentifier']) for i in instances]) return 0 @click.group() @click.option('--profile-name', '-P', def...
achiku/jungle
jungle/rds.py
ls
python
def ls(ctx, list_formatted): session = create_session(ctx.obj['AWS_PROFILE_NAME']) rds = session.client('rds') instances = rds.describe_db_instances() out = format_output(instances['DBInstances'], list_formatted) click.echo('\n'.join(out))
List RDS instances
train
https://github.com/achiku/jungle/blob/fb63f845cfa9e9c0dfbabd8cfa3ebca8177a11ca/jungle/rds.py#L39-L46
[ "def create_session(profile_name):\n if profile_name is None:\n return boto3\n else:\n try:\n session = boto3.Session(profile_name=profile_name)\n return session\n except botocore.exceptions.ProfileNotFound as e:\n click.echo(\"Invalid profile name: {0}\"....
# -*- coding: utf-8 -*- import click from jungle.session import create_session def format_output(instances, flag): """return formatted string per instance""" out = [] line_format = '{0}\t{1}\t{2}\t{3}' name_len = _get_max_name_len(instances) + 3 if flag: line_format = '{0:<' + str(name_len...
achiku/jungle
jungle/emr.py
ls
python
def ls(ctx, name): session = create_session(ctx.obj['AWS_PROFILE_NAME']) client = session.client('emr') results = client.list_clusters( ClusterStates=['RUNNING', 'STARTING', 'BOOTSTRAPPING', 'WAITING'] ) for cluster in results['Clusters']: click.echo("{0}\t{1}\t{2}".format(cluster['...
List EMR instances
train
https://github.com/achiku/jungle/blob/fb63f845cfa9e9c0dfbabd8cfa3ebca8177a11ca/jungle/emr.py#L20-L29
[ "def create_session(profile_name):\n if profile_name is None:\n return boto3\n else:\n try:\n session = boto3.Session(profile_name=profile_name)\n return session\n except botocore.exceptions.ProfileNotFound as e:\n click.echo(\"Invalid profile name: {0}\"....
# -*- coding: utf-8 -*- import subprocess import click from botocore.exceptions import ClientError from jungle.session import create_session @click.group() @click.option('--profile-name', '-P', default=None, help='AWS profile name') @click.pass_context def cli(ctx, profile_name): """EMR CLI group""" ctx.obj ...
achiku/jungle
jungle/emr.py
ssh
python
def ssh(ctx, cluster_id, key_file): session = create_session(ctx.obj['AWS_PROFILE_NAME']) client = session.client('emr') result = client.describe_cluster(ClusterId=cluster_id) target_dns = result['Cluster']['MasterPublicDnsName'] ssh_options = '-o StrictHostKeyChecking=no -o ServerAliveInterval=10'...
SSH login to EMR master node
train
https://github.com/achiku/jungle/blob/fb63f845cfa9e9c0dfbabd8cfa3ebca8177a11ca/jungle/emr.py#L36-L46
[ "def create_session(profile_name):\n if profile_name is None:\n return boto3\n else:\n try:\n session = boto3.Session(profile_name=profile_name)\n return session\n except botocore.exceptions.ProfileNotFound as e:\n click.echo(\"Invalid profile name: {0}\"....
# -*- coding: utf-8 -*- import subprocess import click from botocore.exceptions import ClientError from jungle.session import create_session @click.group() @click.option('--profile-name', '-P', default=None, help='AWS profile name') @click.pass_context def cli(ctx, profile_name): """EMR CLI group""" ctx.obj ...
achiku/jungle
jungle/emr.py
rm
python
def rm(ctx, cluster_id): session = create_session(ctx.obj['AWS_PROFILE_NAME']) client = session.client('emr') try: result = client.describe_cluster(ClusterId=cluster_id) target_dns = result['Cluster']['MasterPublicDnsName'] flag = click.prompt( "Are you sure you want to ...
Terminate a EMR cluster
train
https://github.com/achiku/jungle/blob/fb63f845cfa9e9c0dfbabd8cfa3ebca8177a11ca/jungle/emr.py#L52-L66
[ "def create_session(profile_name):\n if profile_name is None:\n return boto3\n else:\n try:\n session = boto3.Session(profile_name=profile_name)\n return session\n except botocore.exceptions.ProfileNotFound as e:\n click.echo(\"Invalid profile name: {0}\"....
# -*- coding: utf-8 -*- import subprocess import click from botocore.exceptions import ClientError from jungle.session import create_session @click.group() @click.option('--profile-name', '-P', default=None, help='AWS profile name') @click.pass_context def cli(ctx, profile_name): """EMR CLI group""" ctx.obj ...
achiku/jungle
jungle/ec2.py
format_output
python
def format_output(instances, flag): out = [] line_format = '{0}\t{1}\t{2}\t{3}\t{4}' name_len = _get_max_name_len(instances) + 3 if flag: line_format = '{0:<' + str(name_len) + '}{1:<16}{2:<21}{3:<16}{4:<16}' for i in instances: tag_name = get_tag_value(i.tags, 'Name') out.a...
return formatted string for instance
train
https://github.com/achiku/jungle/blob/fb63f845cfa9e9c0dfbabd8cfa3ebca8177a11ca/jungle/ec2.py#L10-L22
[ "def _get_max_name_len(instances):\n \"\"\"get max length of Tag:Name\"\"\"\n # FIXME: ec2.instanceCollection doesn't have __len__\n for i in instances:\n return max([len(get_tag_value(i.tags, 'Name')) for i in instances])\n return 0\n", "def get_tag_value(x, key):\n \"\"\"Get a value from t...
# -*- coding: utf-8 -*- import subprocess import sys import botocore import click from jungle.session import create_session def _get_instance_ip_address(instance, use_private_ip=False): if use_private_ip: return instance.private_ip_address elif instance.public_ip_address is not None: return ...
achiku/jungle
jungle/ec2.py
_get_max_name_len
python
def _get_max_name_len(instances): # FIXME: ec2.instanceCollection doesn't have __len__ for i in instances: return max([len(get_tag_value(i.tags, 'Name')) for i in instances]) return 0
get max length of Tag:Name
train
https://github.com/achiku/jungle/blob/fb63f845cfa9e9c0dfbabd8cfa3ebca8177a11ca/jungle/ec2.py#L35-L40
null
# -*- coding: utf-8 -*- import subprocess import sys import botocore import click from jungle.session import create_session def format_output(instances, flag): """return formatted string for instance""" out = [] line_format = '{0}\t{1}\t{2}\t{3}\t{4}' name_len = _get_max_name_len(instances) + 3 i...
achiku/jungle
jungle/ec2.py
get_tag_value
python
def get_tag_value(x, key): if x is None: return '' result = [y['Value'] for y in x if y['Key'] == key] if result: return result[0] return ''
Get a value from tag
train
https://github.com/achiku/jungle/blob/fb63f845cfa9e9c0dfbabd8cfa3ebca8177a11ca/jungle/ec2.py#L43-L50
null
# -*- coding: utf-8 -*- import subprocess import sys import botocore import click from jungle.session import create_session def format_output(instances, flag): """return formatted string for instance""" out = [] line_format = '{0}\t{1}\t{2}\t{3}\t{4}' name_len = _get_max_name_len(instances) + 3 i...
achiku/jungle
jungle/ec2.py
ls
python
def ls(ctx, name, list_formatted): session = create_session(ctx.obj['AWS_PROFILE_NAME']) ec2 = session.resource('ec2') if name == '*': instances = ec2.instances.filter() else: condition = {'Name': 'tag:Name', 'Values': [name]} instances = ec2.instances.filter(Filters=[condition])...
List EC2 instances
train
https://github.com/achiku/jungle/blob/fb63f845cfa9e9c0dfbabd8cfa3ebca8177a11ca/jungle/ec2.py#L65-L75
[ "def create_session(profile_name):\n if profile_name is None:\n return boto3\n else:\n try:\n session = boto3.Session(profile_name=profile_name)\n return session\n except botocore.exceptions.ProfileNotFound as e:\n click.echo(\"Invalid profile name: {0}\"....
# -*- coding: utf-8 -*- import subprocess import sys import botocore import click from jungle.session import create_session def format_output(instances, flag): """return formatted string for instance""" out = [] line_format = '{0}\t{1}\t{2}\t{3}\t{4}' name_len = _get_max_name_len(instances) + 3 i...
achiku/jungle
jungle/ec2.py
up
python
def up(ctx, instance_id): session = create_session(ctx.obj['AWS_PROFILE_NAME']) ec2 = session.resource('ec2') try: instance = ec2.Instance(instance_id) instance.start() except botocore.exceptions.ClientError as e: click.echo("Invalid instance ID {0} ({1})".format(instance_id, e),...
Start EC2 instance
train
https://github.com/achiku/jungle/blob/fb63f845cfa9e9c0dfbabd8cfa3ebca8177a11ca/jungle/ec2.py#L81-L90
[ "def create_session(profile_name):\n if profile_name is None:\n return boto3\n else:\n try:\n session = boto3.Session(profile_name=profile_name)\n return session\n except botocore.exceptions.ProfileNotFound as e:\n click.echo(\"Invalid profile name: {0}\"....
# -*- coding: utf-8 -*- import subprocess import sys import botocore import click from jungle.session import create_session def format_output(instances, flag): """return formatted string for instance""" out = [] line_format = '{0}\t{1}\t{2}\t{3}\t{4}' name_len = _get_max_name_len(instances) + 3 i...
achiku/jungle
jungle/ec2.py
create_ssh_command
python
def create_ssh_command(session, instance_id, instance_name, username, key_file, port, ssh_options, use_private_ip, gateway_instance_id, gateway_username): ec2 = session.resource('ec2') if instance_id is not None: try: instance = ec2.Instance(instance_id) ho...
Create SSH Login command string
train
https://github.com/achiku/jungle/blob/fb63f845cfa9e9c0dfbabd8cfa3ebca8177a11ca/jungle/ec2.py#L108-L169
[ "def get_tag_value(x, key):\n \"\"\"Get a value from tag\"\"\"\n if x is None:\n return ''\n result = [y['Value'] for y in x if y['Key'] == key]\n if result:\n return result[0]\n return ''\n", "def _get_instance_ip_address(instance, use_private_ip=False):\n if use_private_ip:\n ...
# -*- coding: utf-8 -*- import subprocess import sys import botocore import click from jungle.session import create_session def format_output(instances, flag): """return formatted string for instance""" out = [] line_format = '{0}\t{1}\t{2}\t{3}\t{4}' name_len = _get_max_name_len(instances) + 3 i...
achiku/jungle
jungle/ec2.py
ssh
python
def ssh(ctx, instance_id, instance_name, username, key_file, port, ssh_options, private_ip, gateway_instance_id, gateway_username, dry_run): session = create_session(ctx.obj['AWS_PROFILE_NAME']) if instance_id is None and instance_name is None: click.echo( "One of --instance-id/-i o...
SSH to EC2 instance
train
https://github.com/achiku/jungle/blob/fb63f845cfa9e9c0dfbabd8cfa3ebca8177a11ca/jungle/ec2.py#L191-L212
[ "def create_session(profile_name):\n if profile_name is None:\n return boto3\n else:\n try:\n session = boto3.Session(profile_name=profile_name)\n return session\n except botocore.exceptions.ProfileNotFound as e:\n click.echo(\"Invalid profile name: {0}\"....
# -*- coding: utf-8 -*- import subprocess import sys import botocore import click from jungle.session import create_session def format_output(instances, flag): """return formatted string for instance""" out = [] line_format = '{0}\t{1}\t{2}\t{3}\t{4}' name_len = _get_max_name_len(instances) + 3 i...
achiku/jungle
jungle/cli.py
JungleCLI.get_command
python
def get_command(self, ctx, name): try: mod = __import__('jungle.' + name, None, None, ['cli']) return mod.cli except ImportError: pass
get command
train
https://github.com/achiku/jungle/blob/fb63f845cfa9e9c0dfbabd8cfa3ebca8177a11ca/jungle/cli.py#L15-L21
null
class JungleCLI(click.MultiCommand): """Jangle CLI main class""" def list_commands(self, ctx): """return available modules""" return ['ec2', 'elb', 'emr', 'asg', 'rds']
achiku/jungle
jungle/elb.py
ls
python
def ls(ctx, name, list_instances): session = create_session(ctx.obj['AWS_PROFILE_NAME']) client = session.client('elb') inst = {'LoadBalancerDescriptions': []} if name == '*': inst = client.describe_load_balancers() else: try: inst = client.describe_load_balancers(LoadBa...
List ELB instances
train
https://github.com/achiku/jungle/blob/fb63f845cfa9e9c0dfbabd8cfa3ebca8177a11ca/jungle/elb.py#L19-L41
[ "def create_session(profile_name):\n if profile_name is None:\n return boto3\n else:\n try:\n session = boto3.Session(profile_name=profile_name)\n return session\n except botocore.exceptions.ProfileNotFound as e:\n click.echo(\"Invalid profile name: {0}\"....
# -*- coding: utf-8 -*- import click from botocore.exceptions import ClientError from jungle.session import create_session @click.group() @click.option('--profile-name', '-P', default=None, help='AWS profile name') @click.pass_context def cli(ctx, profile_name): """ELB CLI group""" ctx.obj = {'AWS_PROFILE_NAM...
achiku/jungle
jungle/asg.py
format_output
python
def format_output(groups, flag): out = [] line_format = '{0}\t{1}\t{2}\t{3}\t{4}\t{5}' for g in groups['AutoScalingGroups']: out.append(line_format.format( g['AutoScalingGroupName'], g['LaunchConfigurationName'], 'desired:'+str(g['DesiredCapacity']), '...
return formatted string for instance
train
https://github.com/achiku/jungle/blob/fb63f845cfa9e9c0dfbabd8cfa3ebca8177a11ca/jungle/asg.py#L6-L19
null
# -*- coding: utf-8 -*- import click from jungle.session import create_session @click.group() @click.option('--profile-name', '-P', default=None, help='AWS profile name') @click.pass_context def cli(ctx, profile_name): """AutoScaling CLI group""" ctx.obj = {} ctx.obj['AWS_PROFILE_NAME'] = profile_name ...
achiku/jungle
jungle/asg.py
ls
python
def ls(ctx, name, list_formatted): session = create_session(ctx.obj['AWS_PROFILE_NAME']) client = session.client('autoscaling') if name == "*": groups = client.describe_auto_scaling_groups() else: groups = client.describe_auto_scaling_groups( AutoScalingGroupNames=[ ...
List AutoScaling groups
train
https://github.com/achiku/jungle/blob/fb63f845cfa9e9c0dfbabd8cfa3ebca8177a11ca/jungle/asg.py#L35-L49
[ "def create_session(profile_name):\n if profile_name is None:\n return boto3\n else:\n try:\n session = boto3.Session(profile_name=profile_name)\n return session\n except botocore.exceptions.ProfileNotFound as e:\n click.echo(\"Invalid profile name: {0}\"....
# -*- coding: utf-8 -*- import click from jungle.session import create_session def format_output(groups, flag): """return formatted string for instance""" out = [] line_format = '{0}\t{1}\t{2}\t{3}\t{4}\t{5}' for g in groups['AutoScalingGroups']: out.append(line_format.format( g['A...
Celeo/Preston
preston/preston.py
Preston._get_access_from_refresh
python
def _get_access_from_refresh(self) -> Tuple[str, float]: headers = self._get_authorization_headers() data = { 'grant_type': 'refresh_token', 'refresh_token': self.refresh_token } r = self.session.post(self.TOKEN_URL, headers=headers, data=data) response_da...
Uses the stored refresh token to get a new access token. This method assumes that the refresh token exists. Args: None Returns: new access token and expiration time (from now)
train
https://github.com/Celeo/Preston/blob/7c94bf0b7dabecad0bd8b66229b2906dabdb8e79/preston/preston.py#L91-L109
[ "def _get_authorization_headers(self) -> dict:\n \"\"\"Constructs and returns the Authorization header for the client app.\n\n Args:\n None\n\n Returns:\n header dict for communicating with the authorization endpoints\n \"\"\"\n auth = base64.encodestring((self.client_id + ':' + self.cl...
class Preston: """Preston class. This class is used to interface with the EVE Online "ESI" API. The __init__ method only **kwargs instead of a specific listing of arguments; here's the list of useful key-values: version version of the spec to load user_agent ...
Celeo/Preston
preston/preston.py
Preston._get_authorization_headers
python
def _get_authorization_headers(self) -> dict: auth = base64.encodestring((self.client_id + ':' + self.client_secret).encode('latin-1')).decode('latin-1') auth = auth.replace('\n', '').replace(' ', '') auth = 'Basic {}'.format(auth) headers = {'Authorization': auth} return headers
Constructs and returns the Authorization header for the client app. Args: None Returns: header dict for communicating with the authorization endpoints
train
https://github.com/Celeo/Preston/blob/7c94bf0b7dabecad0bd8b66229b2906dabdb8e79/preston/preston.py#L111-L124
null
class Preston: """Preston class. This class is used to interface with the EVE Online "ESI" API. The __init__ method only **kwargs instead of a specific listing of arguments; here's the list of useful key-values: version version of the spec to load user_agent ...
Celeo/Preston
preston/preston.py
Preston._try_refresh_access_token
python
def _try_refresh_access_token(self) -> None: if self.refresh_token: if not self.access_token or self._is_access_token_expired(): self.access_token, self.access_expiration = self._get_access_from_refresh() self.access_expiration = time.time() + self.access_expiration
Attempts to get a new access token using the refresh token, if needed. If the access token is expired and this instance has a stored refresh token, then the refresh token is in the API call to get a new access token. If successful, this instance is modified in-place with that new access token. ...
train
https://github.com/Celeo/Preston/blob/7c94bf0b7dabecad0bd8b66229b2906dabdb8e79/preston/preston.py#L126-L142
[ "def _get_access_from_refresh(self) -> Tuple[str, float]:\n \"\"\"Uses the stored refresh token to get a new access token.\n\n This method assumes that the refresh token exists.\n\n Args:\n None\n\n Returns:\n new access token and expiration time (from now)\n \"\"\"\n headers = self....
class Preston: """Preston class. This class is used to interface with the EVE Online "ESI" API. The __init__ method only **kwargs instead of a specific listing of arguments; here's the list of useful key-values: version version of the spec to load user_agent ...
Celeo/Preston
preston/preston.py
Preston.authenticate
python
def authenticate(self, code: str) -> 'Preston': headers = self._get_authorization_headers() data = { 'grant_type': 'authorization_code', 'code': code } r = self.session.post(self.TOKEN_URL, headers=headers, data=data) if not r.status_code == 200: ...
Authenticates using the code from the EVE SSO. A new Preston object is returned; this object is not modified. The intended usage is: auth = preston.authenticate('some_code_here') Args: code: SSO code Returns: new Preston, authenticated
train
https://github.com/Celeo/Preston/blob/7c94bf0b7dabecad0bd8b66229b2906dabdb8e79/preston/preston.py#L173-L201
[ "def _get_authorization_headers(self) -> dict:\n \"\"\"Constructs and returns the Authorization header for the client app.\n\n Args:\n None\n\n Returns:\n header dict for communicating with the authorization endpoints\n \"\"\"\n auth = base64.encodestring((self.client_id + ':' + self.cl...
class Preston: """Preston class. This class is used to interface with the EVE Online "ESI" API. The __init__ method only **kwargs instead of a specific listing of arguments; here's the list of useful key-values: version version of the spec to load user_agent ...
Celeo/Preston
preston/preston.py
Preston._get_spec
python
def _get_spec(self) -> dict: if self.spec: return self.spec self.spec = requests.get(self.SPEC_URL.format(self.version)).json() return self.spec
Fetches the OpenAPI spec from the server. If the spec has already been fetched, the cached version is returned instead. ArgS: None Returns: OpenAPI spec data
train
https://github.com/Celeo/Preston/blob/7c94bf0b7dabecad0bd8b66229b2906dabdb8e79/preston/preston.py#L220-L234
null
class Preston: """Preston class. This class is used to interface with the EVE Online "ESI" API. The __init__ method only **kwargs instead of a specific listing of arguments; here's the list of useful key-values: version version of the spec to load user_agent ...
Celeo/Preston
preston/preston.py
Preston._get_path_for_op_id
python
def _get_path_for_op_id(self, id: str) -> Optional[str]: for path_key, path_value in self._get_spec()['paths'].items(): for method in self.METHODS: if method in path_value: if self.OPERATION_ID_KEY in path_value[method]: if path_value[metho...
Searches the spec for a path matching the operation id. Args: id: operation id Returns: path to the endpoint, or None if not found
train
https://github.com/Celeo/Preston/blob/7c94bf0b7dabecad0bd8b66229b2906dabdb8e79/preston/preston.py#L236-L251
[ "def _get_spec(self) -> dict:\n \"\"\"Fetches the OpenAPI spec from the server.\n\n If the spec has already been fetched, the cached version is returned instead.\n\n ArgS:\n None\n\n Returns:\n OpenAPI spec data\n \"\"\"\n if self.spec:\n return self.spec\n self.spec = requ...
class Preston: """Preston class. This class is used to interface with the EVE Online "ESI" API. The __init__ method only **kwargs instead of a specific listing of arguments; here's the list of useful key-values: version version of the spec to load user_agent ...
Celeo/Preston
preston/preston.py
Preston._insert_vars
python
def _insert_vars(self, path: str, data: dict) -> str: data = data.copy() while True: match = re.search(self.VAR_REPLACE_REGEX, path) if not match: return path replace_from = match.group(0) replace_with = str(data.get(match.group(1))) ...
Inserts variables into the ESI URL path. Args: path: raw ESI URL path data: data to insert into the URL Returns: path with variables filled
train
https://github.com/Celeo/Preston/blob/7c94bf0b7dabecad0bd8b66229b2906dabdb8e79/preston/preston.py#L253-L270
null
class Preston: """Preston class. This class is used to interface with the EVE Online "ESI" API. The __init__ method only **kwargs instead of a specific listing of arguments; here's the list of useful key-values: version version of the spec to load user_agent ...
Celeo/Preston
preston/preston.py
Preston.whoami
python
def whoami(self) -> dict: if not self.access_token: return {} self._try_refresh_access_token() return self.session.get(self.WHOAMI_URL).json()
Returns the basic information about the authenticated character. Obviously doesn't do anything if this Preston instance is not authenticated, so it returns an empty dict. Args: None Returns: character info if authenticated, otherwise an empty dict
train
https://github.com/Celeo/Preston/blob/7c94bf0b7dabecad0bd8b66229b2906dabdb8e79/preston/preston.py#L272-L287
[ "def _try_refresh_access_token(self) -> None:\n \"\"\"Attempts to get a new access token using the refresh token, if needed.\n\n If the access token is expired and this instance has a stored refresh token,\n then the refresh token is in the API call to get a new access token. If\n successful, this insta...
class Preston: """Preston class. This class is used to interface with the EVE Online "ESI" API. The __init__ method only **kwargs instead of a specific listing of arguments; here's the list of useful key-values: version version of the spec to load user_agent ...
Celeo/Preston
preston/preston.py
Preston.get_path
python
def get_path(self, path: str, data: dict) -> Tuple[dict, dict]: path = self._insert_vars(path, data) path = self.BASE_URL + path data = self.cache.check(path) if data: return data self._try_refresh_access_token() r = self.session.get(path) self.cache.s...
Queries the ESI by an endpoint URL. This method is not marked "private" as it _can_ be used by consuming code, but it's probably easier to call the `get_op` method instead. Args: path: raw ESI URL path data: data to insert into the URL Returns: ...
train
https://github.com/Celeo/Preston/blob/7c94bf0b7dabecad0bd8b66229b2906dabdb8e79/preston/preston.py#L289-L311
[ "def _try_refresh_access_token(self) -> None:\n \"\"\"Attempts to get a new access token using the refresh token, if needed.\n\n If the access token is expired and this instance has a stored refresh token,\n then the refresh token is in the API call to get a new access token. If\n successful, this insta...
class Preston: """Preston class. This class is used to interface with the EVE Online "ESI" API. The __init__ method only **kwargs instead of a specific listing of arguments; here's the list of useful key-values: version version of the spec to load user_agent ...
Celeo/Preston
preston/preston.py
Preston.get_op
python
def get_op(self, id: str, **kwargs: str) -> dict: path = self._get_path_for_op_id(id) return self.get_path(path, kwargs)
Queries the ESI by looking up an operation id. Endpoints are cached, so calls to this method for the same op and args will return the data from the cache instead of making the API call. Args: id: operation id kwargs: data to populate the endpoint's URL variables...
train
https://github.com/Celeo/Preston/blob/7c94bf0b7dabecad0bd8b66229b2906dabdb8e79/preston/preston.py#L313-L328
[ "def _get_path_for_op_id(self, id: str) -> Optional[str]:\n \"\"\"Searches the spec for a path matching the operation id.\n\n Args:\n id: operation id\n\n Returns:\n path to the endpoint, or None if not found\n \"\"\"\n for path_key, path_value in self._get_spec()['paths'].items():\n ...
class Preston: """Preston class. This class is used to interface with the EVE Online "ESI" API. The __init__ method only **kwargs instead of a specific listing of arguments; here's the list of useful key-values: version version of the spec to load user_agent ...
Celeo/Preston
preston/preston.py
Preston.post_path
python
def post_path(self, path: str, path_data: Union[dict, None], post_data: Any) -> dict: path = self._insert_vars(path, path_data or {}) path = self.BASE_URL + path self._try_refresh_access_token() return self.session.post(path, json=post_data).json()
Modifies the ESI by an endpoint URL. This method is not marked "private" as it _can_ be used by consuming code, but it's probably easier to call the `get_op` method instead. Args: path: raw ESI URL path path_data: data to format the path with (can be None) ...
train
https://github.com/Celeo/Preston/blob/7c94bf0b7dabecad0bd8b66229b2906dabdb8e79/preston/preston.py#L330-L348
[ "def _try_refresh_access_token(self) -> None:\n \"\"\"Attempts to get a new access token using the refresh token, if needed.\n\n If the access token is expired and this instance has a stored refresh token,\n then the refresh token is in the API call to get a new access token. If\n successful, this insta...
class Preston: """Preston class. This class is used to interface with the EVE Online "ESI" API. The __init__ method only **kwargs instead of a specific listing of arguments; here's the list of useful key-values: version version of the spec to load user_agent ...
Celeo/Preston
preston/preston.py
Preston.post_op
python
def post_op(self, id: str, path_data: Union[dict, None], post_data: Any) -> dict: path = self._get_path_for_op_id(id) return self.post_path(path, path_data, post_data)
Modifies the ESI by looking up an operation id. Args: path: raw ESI URL path path_data: data to format the path with (can be None) post_data: data to send to ESI Returns: ESI data
train
https://github.com/Celeo/Preston/blob/7c94bf0b7dabecad0bd8b66229b2906dabdb8e79/preston/preston.py#L350-L362
[ "def _get_path_for_op_id(self, id: str) -> Optional[str]:\n \"\"\"Searches the spec for a path matching the operation id.\n\n Args:\n id: operation id\n\n Returns:\n path to the endpoint, or None if not found\n \"\"\"\n for path_key, path_value in self._get_spec()['paths'].items():\n ...
class Preston: """Preston class. This class is used to interface with the EVE Online "ESI" API. The __init__ method only **kwargs instead of a specific listing of arguments; here's the list of useful key-values: version version of the spec to load user_agent ...
Celeo/Preston
preston/cache.py
Cache._get_expiration
python
def _get_expiration(self, headers: dict) -> int: expiration_str = headers.get('expires') if not expiration_str: return 0 expiration = datetime.strptime(expiration_str, '%a, %d %b %Y %H:%M:%S %Z') delta = (expiration - datetime.utcnow()).total_seconds() return math.cei...
Gets the expiration time of the data from the response headers. Args: headers: dictionary of headers from ESI Returns: value of seconds from now the data expires
train
https://github.com/Celeo/Preston/blob/7c94bf0b7dabecad0bd8b66229b2906dabdb8e79/preston/cache.py#L23-L37
null
class Cache: def __init__(self): """Cache class. The cache is desgined to respect the caching rules of ESI as to not request a page more often than it is updated by the server. Args: None Returns: None """ self.data: dict = {} ...
Celeo/Preston
preston/cache.py
Cache.set
python
def set(self, response: 'requests.Response') -> None: self.data[response.url] = SavedEndpoint( response.json(), self._get_expiration(response.headers) )
Adds a response to the cache. Args: response: response from ESI Returns: None
train
https://github.com/Celeo/Preston/blob/7c94bf0b7dabecad0bd8b66229b2906dabdb8e79/preston/cache.py#L39-L51
[ "def _get_expiration(self, headers: dict) -> int:\n \"\"\"Gets the expiration time of the data from the response headers.\n\n Args:\n headers: dictionary of headers from ESI\n\n Returns:\n value of seconds from now the data expires\n \"\"\"\n expiration_str = headers.get('expires')\n ...
class Cache: def __init__(self): """Cache class. The cache is desgined to respect the caching rules of ESI as to not request a page more often than it is updated by the server. Args: None Returns: None """ self.data: dict = {} ...
Celeo/Preston
preston/cache.py
Cache._check_expiration
python
def _check_expiration(self, url: str, data: 'SavedEndpoint') -> 'SavedEndpoint': if data.expires_after < time.time(): del self.data[url] data = None return data
Checks the expiration time for data for a url. If the data has expired, it is deleted from the cache. Args: url: url to check data: page of data for that url Returns: value of either the passed data or None if it expired
train
https://github.com/Celeo/Preston/blob/7c94bf0b7dabecad0bd8b66229b2906dabdb8e79/preston/cache.py#L53-L68
null
class Cache: def __init__(self): """Cache class. The cache is desgined to respect the caching rules of ESI as to not request a page more often than it is updated by the server. Args: None Returns: None """ self.data: dict = {} ...
Celeo/Preston
preston/cache.py
Cache.check
python
def check(self, url: str) -> Optional[dict]: data = self.data.get(url) if data: data = self._check_expiration(url, data) return data.data if data else None
Check if data for a url has expired. Data is not fetched again if it has expired. Args: url: url to check expiration on Returns: value of the data, possibly None
train
https://github.com/Celeo/Preston/blob/7c94bf0b7dabecad0bd8b66229b2906dabdb8e79/preston/cache.py#L70-L84
[ "def _check_expiration(self, url: str, data: 'SavedEndpoint') -> 'SavedEndpoint':\n \"\"\"Checks the expiration time for data for a url.\n\n If the data has expired, it is deleted from the cache.\n\n Args:\n url: url to check\n data: page of data for that url\n\n Returns:\n value of...
class Cache: def __init__(self): """Cache class. The cache is desgined to respect the caching rules of ESI as to not request a page more often than it is updated by the server. Args: None Returns: None """ self.data: dict = {} ...
almarklein/pyelastix
pyelastix.py
_find_executables
python
def _find_executables(name): exe_name = name + '.exe' * sys.platform.startswith('win') env_path = os.environ.get(name.upper()+ '_PATH', '') possible_locations = [] def add(*dirs): for d in dirs: if d and d not in possible_locations and os.path.isdir(d): possible_...
Try to find an executable.
train
https://github.com/almarklein/pyelastix/blob/971a677ce9a3ef8eb0b95ae393db8e2506d2f8a4/pyelastix.py#L76-L140
[ "def add(*dirs):\n for d in dirs:\n if d and d not in possible_locations and os.path.isdir(d):\n possible_locations.append(d)\n", "def do_check_version(exe):\n try:\n return subprocess.check_output([exe, '--version']).decode().strip()\n except Exception:\n # print('not a g...
# Copyright (c) 2010-2016, Almar Klein # This code is subject to the MIT license """ PyElastix - Python wrapper for the Elastix nonrigid registration toolkit This Python module wraps the Elastix registration toolkit. For it to work, the Elastix command line application needs to be installed on your computer. You can ...
almarklein/pyelastix
pyelastix.py
get_elastix_exes
python
def get_elastix_exes(): if EXES: if EXES[0]: return EXES else: raise RuntimeError('No Elastix executable.') # Find exe elastix, ver = _find_executables('elastix') if elastix: base, ext = os.path.splitext(elastix) base = os.path.dirname(base) ...
Get the executables for elastix and transformix. Raises an error if they cannot be found.
train
https://github.com/almarklein/pyelastix/blob/971a677ce9a3ef8eb0b95ae393db8e2506d2f8a4/pyelastix.py#L145-L168
[ "def _find_executables(name):\n \"\"\" Try to find an executable.\n \"\"\"\n exe_name = name + '.exe' * sys.platform.startswith('win')\n env_path = os.environ.get(name.upper()+ '_PATH', '')\n\n possible_locations = []\n def add(*dirs):\n for d in dirs:\n if d and d not in possibl...
# Copyright (c) 2010-2016, Almar Klein # This code is subject to the MIT license """ PyElastix - Python wrapper for the Elastix nonrigid registration toolkit This Python module wraps the Elastix registration toolkit. For it to work, the Elastix command line application needs to be installed on your computer. You can ...