code stringlengths 1 18.2k |
|---|
loop.close() |
def clear(self): ''' claar all the cache, and release memory ''' for node in self.dli(): node.empty = True node.key = None node.value = None self.head = _dlnode() self.head.next = self.head self.head.prev = self.head self.listSize = 1 self.table.clear() # status var self.hit_cnt = 0 self.miss_cnt = 0 self.remove_cnt = ... |
def pop(self, key, default = None): """Delete the item""" node = self.get(key, None) if node == None: value = default else: value = node try: del self[key] except: return value return value |
def main(): """ Main function. :return: None. """ try: # Get the `src` directory's absolute path src_path = os.path.dirname( # `aoiklivereload` directory's absolute path os.path.dirname( # `demo` directory's absolute path os.path.dirname( # This file's absolute path os.path.abspath(__file__) ) ) ) # If the `src` direct... |
save user setting PYTHONPATH when running this demo. # sys.path.append(src_path) # Import reloader class from aoiklivereload import LiveReloader # Create reloader reloader = LiveReloader() # Start watcher thread reloader.start_watcher_thread() # Server host server_host = '0.0.0.0' # Server port server_port = 8000 # Get... |
@bottle.get('/') def hello_handler(): # pylint: disable=unused-variable """ Request handler. :return: Response body. """ # Return response body return 'hello' # Run server bottle.run(host=server_host, port=server_port) # If have `KeyboardInterrupt` except KeyboardInterrupt: # Not treat as error pass |
async def get_or_create(cls, lang: str, *, client_token: str = None, mounts: Iterable[str] = None, envs: Mapping[str, str] = None, resources: Mapping[str, int] = None, cluster_size: int = 1, tag: str = None, owner_access_key: str = None) -> 'Kernel': ''' Get-or-creates a compute session. If *client_token* is ``None``, ... |
key has remaining quota. If *client_token* is a valid string and there is an existing compute session with the same token and the same *lang*, then it returns the :class:`Kernel` instance representing the existing session. :param lang: The image name and tag for the compute session. Example: ``python:3.6-ubuntu``. Chec... |
client_token: A client-side identifier to seamlessly reuse the compute session already created. :param mounts: The list of vfolder names that belongs to the currrent API access key. :param envs: The environment variables which always bypasses the jail policy. :param resources: The resource specification. (TODO: details... |
string to annotate extra information. :param owner: An optional access key that owns the created session. (Only available to administrators) :returns: The :class:`Kernel` instance. ''' if client_token: assert 4 <= len(client_token) <= 64, \ 'Client session token should be 4 to 64 characters long.' else: client_token = ... |
= Request(cls.session, 'POST', '/kernel/create') rqst.set_json({ 'lang': lang, 'tag': tag, 'clientSessionToken': client_token, 'config': { 'mounts': mounts, 'environ': envs, 'clusterSize': cluster_size, 'resources': resources, }, }) async with rqst.fetch() as resp: data = await resp.json() o = cls(data['kernelId'], own... |
async def destroy(self): ''' Destroys the compute session. Since the server literally kills the container(s), all ongoing executions are forcibly interrupted. ''' params = {} if self.owner_access_key: params['owner_access_key'] = self.owner_access_key rqst = Request(self.session, 'DELETE', '/kernel/{}'.format(self.kern... |
async def restart(self): ''' Restarts the compute session. The server force-destroys the current running container(s), but keeps their temporary scratch directories intact. ''' params = {} if self.owner_access_key: params['owner_access_key'] = self.owner_access_key rqst = Request(self.session, 'PATCH', '/kernel/{}'.for... |
async def complete(self, code: str, opts: dict = None) -> Iterable[str]: ''' Gets the auto-completion candidates from the given code string, as if a user has pressed the tab key just after the code in IDEs. Depending on the language of the compute session, this feature may not be supported. Unsupported sessions returns... |
Additional information about the current cursor position, such as row, col, line and the remainder text. :returns: An ordered list of strings. ''' opts = {} if opts is None else opts params = {} if self.owner_access_key: params['owner_access_key'] = self.owner_access_key rqst = Request(self.session, 'POST', '/kernel/{}... |
}) async with rqst.fetch() as resp: return await resp.json() |
async def get_info(self): ''' Retrieves a brief information about the compute session. ''' params = {} if self.owner_access_key: params['owner_access_key'] = self.owner_access_key rqst = Request(self.session, 'GET', '/kernel/{}'.format(self.kernel_id), params=params) async with rqst.fetch() as resp: return await resp.j... |
async def execute(self, run_id: str = None, code: str = None, mode: str = 'query', opts: dict = None): ''' Executes a code snippet directly in the compute session or sends a set of build/clean/execute commands to the compute session. For more details about using this API, please refer :doc:`the official API documentati... |
In the first call, it may be ``None`` so that the server auto-assigns one. Subsequent calls must use the returned ``runId`` value to request continuation or to send user inputs. :param code: A code snippet as string. In the continuation requests, it must be an empty string. When sending user inputs, this is where the u... |
string which is one of ``"query"``, ``"batch"``, ``"continue"``, and ``"user-input"``. :param opts: A dict for specifying additional options. Mainly used in the batch mode to specify build/clean/execution commands. See :ref:`the API object reference <batch-execution-query-object>` for details. :returns: :ref:`An execut... |
{'query', 'continue', 'input'}: assert code is not None, \ 'The code argument must be a valid string even when empty.' rqst = Request(self.session, 'POST', '/kernel/{}'.format(self.kernel_id), params=params) rqst.set_json({ 'mode': mode, 'code': code, 'runId': run_id, }) elif mode == 'batch': rqst = Request(self.sessio... |
None), }, }) elif mode == 'complete': rqst = Request(self.session, 'POST', '/kernel/{}/complete'.format(self.kernel_id), params=params) rqst.set_json({ 'code': code, 'options': { 'row': int(opts.get('row', 0)), 'col': int(opts.get('col', 0)), 'line': opts.get('line', ''), 'post': opts.get('post', ''), }, }) else: raise... |
async def upload(self, files: Sequence[Union[str, Path]], basedir: Union[str, Path] = None, show_progress: bool = False): ''' Uploads the given list of files to the compute session. You may refer them in the batch-mode execution or from the code executed in the server afterwards. :param files: The list of file paths in... |
compute session is calculated from the relative path to *basedir* and all intermediate parent directories are automatically created if not exists. For example, if a file path is ``/home/user/test/data.txt`` (or ``test/data.txt``) where *basedir* is ``/home/user`` (or the current working directory is ``/home/user``), th... |
default value is the current working directory. :param show_progress: Displays a progress bar during uploads. ''' params = {} if self.owner_access_key: params['owner_access_key'] = self.owner_access_key base_path = (Path.cwd() if basedir is None else Path(basedir).resolve()) files = [Path(file).resolve() for file in fi... |
for file_path in files: try: attachments.append(AttachedFile( str(file_path.relative_to(base_path)), ProgressReportingReader(str(file_path), tqdm_instance=tqdm_obj), 'application/octet-stream', )) except ValueError: msg = 'File "{0}" is outside of the base directory "{1}".' \ .format(file_path, base_path) raise ValueEr... |
async def download(self, files: Sequence[Union[str, Path]], dest: Union[str, Path] = '.', show_progress: bool = False): ''' Downloads the given list of files from the compute session. :param files: The list of file paths in the compute session. If they are relative paths, the path is calculated from ``/home/work`` in t... |
a progress bar during downloads. ''' params = {} if self.owner_access_key: params['owner_access_key'] = self.owner_access_key rqst = Request(self.session, 'GET', '/kernel/{}/download'.format(self.kernel_id), params=params) rqst.set_json({ 'files': [*map(str, files)], }) async with rqst.fetch() as resp: chunk_size = 1 *... |
pbar.update(len(chunk)) # TODO: more elegant parsing of multipart response? for part in chunk.split(b'\r\n'): if part.startswith(b'--'): if fp: fp.close() with tarfile.open(fp.name) as tarf: tarf.extractall(path=dest) file_names = tarf.getnames() os.unlink(fp.name) fp = tempfile.NamedTemporaryFile(suffix='.tar', delete... |
async def list_files(self, path: Union[str, Path] = '.'): ''' Gets the list of files in the given path inside the compute session container. :param path: The directory path in the compute session. ''' params = {} if self.owner_access_key: params['owner_access_key'] = self.owner_access_key rqst = Request(self.session, '... |
def stream_pty(self) -> 'StreamPty': ''' Opens a pseudo-terminal of the kernel (if supported) streamed via websockets. :returns: a :class:`StreamPty` object. ''' params = {} if self.owner_access_key: params['owner_access_key'] = self.owner_access_key request = Request(self.session, 'GET', '/stream/kernel/{}/pty'.format... |
def stream_execute(self, code: str = '', *, mode: str = 'query', opts: dict = None) -> WebSocketResponse: ''' Executes a code snippet in the streaming mode. Since the returned websocket represents a run loop, there is no need to specify *run_id* explicitly. ''' params = {} if self.owner_access_key: params['owner_access... |
opts = {} elif mode == 'batch': opts = { 'clean': opts.get('clean', None), 'build': opts.get('build', None), 'buildLog': bool(opts.get('buildLog', False)), 'exec': opts.get('exec', None), } else: msg = 'Invalid stream-execution mode: {0}'.format(mode) raise BackendClientError(msg) request = Request(self.session, 'GET',... |
def init_interface(): sys.stdout = LoggerWriter(LOGGER.debug) sys.stderr = LoggerWriter(LOGGER.error) """ Grab the ~/.polyglot/.env file for variables If you are running Polyglot v2 on this same machine then it should already exist. If not create it. """ warnings.simplefilter('error', UserWarning) try: load_dotenv(join... |
it will receive a STDIN config on startup that looks like: {"token":"2cb40e507253fc8f4cbbe247089b28db79d859cbed700ec151", "mqttHost":"localhost","mqttPort":"1883","profileNum":"10"} """ init = select.select([sys.stdin], [], [], 1)[0] if init: line = sys.stdin.readline() try: line = json.loads(line) os.environ['PROFILE_... |
def _connect(self, mqttc, userdata, flags, rc): """ The callback for when the client receives a CONNACK response from the server. Subscribing in on_connect() means that if we lose the connection and reconnect then subscriptions will be renewed. :param mqttc: The client instance for this callback :param userdata: The pr... |
the connection. :param rc: Result code of connection, 0 = Success, anything else is a failure """ if rc == 0: self.connected = True results = [] LOGGER.info("MQTT Connected with result code " + str(rc) + " (Success)") # result, mid = self._mqttc.subscribe(self.topicInput) results.append((self.topicInput, tuple(self._mq... |
+ " - " + " MID: " + str(mid) + " Result: " + str(result)) else: LOGGER.info("MQTT Subscription to " + topic + " failed. This is unusual. MID: " + str(mid) + " Result: " + str(result)) # If subscription fails, try to reconnect. self._mqttc.reconnect() self._mqttc.publish(self.topicSelfConnection, json.dumps( { 'connect... |
to connect. Result code: " + str(rc)) |
def _message(self, mqttc, userdata, msg): """ The callback for when a PUBLISH message is received from the server. :param mqttc: The client instance for this callback :param userdata: The private userdata for the mqtt client. Not used in Polyglot :param flags: The flags set on the connection. :param msg: Dictionary of ... |
'result', 'status', 'shortPoll', 'longPoll', 'delete'] parsed_msg = json.loads(msg.payload.decode('utf-8')) if 'node' in parsed_msg: if parsed_msg['node'] != 'polyglot': return del parsed_msg['node'] for key in parsed_msg: # LOGGER.debug('MQTT Received Message: {}: {}'.format(msg.topic, parsed_msg)) if key == 'config':... |
from Polyglot: {}'.format(key)) except (ValueError) as err: LOGGER.error('MQTT Received Payload Error: {}'.format(err), exc_info=True) |
def _disconnect(self, mqttc, userdata, rc): """ The callback for when a DISCONNECT occurs. :param mqttc: The client instance for this callback :param userdata: The private userdata for the mqtt client. Not used in Polyglot :param rc: Result code of connection, 0 = Graceful, anything else is unclean """ self.connected =... |
as ex: template = "An exception of type {0} occured. Arguments:\n{1!r}" message = template.format(type(ex).__name__, ex.args) LOGGER.error("MQTT Connection error: " + message) else: LOGGER.info("MQTT Graceful disconnection.") |
def _startMqtt(self): """ The client start method. Starts the thread for the MQTT Client and publishes the connected message. """ LOGGER.info('Connecting to MQTT... {}:{}'.format(self._server, self._port)) try: # self._mqttc.connect_async(str(self._server), int(self._port), 10) self._mqttc.connect_async('{}'.format(sel... |
def stop(self): """ The client stop method. If the client is currently connected stop the thread and disconnect. Publish the disconnected message if clean shutdown. """ # self.loop.call_soon_threadsafe(self.loop.stop) # self.loop.stop() # self._longPoll.cancel() # self._shortPoll.cancel() if self.connected: LOGGER.info... |
def send(self, message): """ Formatted Message to send to Polyglot. Connection messages are sent automatically from this module so this method is used to send commands to/from Polyglot and formats it for consumption """ if not isinstance(message, dict) and self.connected: warnings.warn('payload not a dictionary') retur... |
def addNode(self, node): """ Add a node to the NodeServer :param node: Dictionary of node settings. Keys: address, name, node_def_id, primary, and drivers are required. """ LOGGER.info('Adding node {}({})'.format(node.name, node.address)) message = { 'addnode': { 'nodes': [{ 'address': node.address, 'name': node.name, ... |
def saveCustomData(self, data): """ Send custom dictionary to Polyglot to save and be retrieved on startup. :param data: Dictionary of key value pairs to store in Polyglot database. """ LOGGER.info('Sending customData to Polyglot.') message = { 'customdata': data } self.send(message) |
def saveCustomParams(self, data): """ Send custom dictionary to Polyglot to save and be retrieved on startup. :param data: Dictionary of key value pairs to store in Polyglot database. """ LOGGER.info('Sending customParams to Polyglot.') message = { 'customparams': data } self.send(message) |
def addNotice(self, data): """ Add custom notice to front-end for this NodeServers :param data: String of characters to add as a notification in the front-end. """ LOGGER.info('Sending addnotice to Polyglot: {}'.format(data)) message = { 'addnotice': data } self.send(message) |
def removeNotice(self, data): """ Add custom notice to front-end for this NodeServers :param data: Index of notices list to remove. """ LOGGER.info('Sending removenotice to Polyglot for index {}'.format(data)) message = { 'removenotice': data } self.send(message) |
def delNode(self, address): """ Delete a node from the NodeServer :param node: Dictionary of node settings. Keys: address, name, node_def_id, primary, and drivers are required. """ LOGGER.info('Removing node {}'.format(address)) message = { 'removenode': { 'address': address } } self.send(message) |
def getNode(self, address): """ Get Node by Address of existing nodes. """ try: for node in self.config['nodes']: if node['address'] == address: return node return False except KeyError: LOGGER.error('Usually means we have not received the config yet.', exc_info=True) return False |
def inConfig(self, config): """ Save incoming config received from Polyglot to Interface.config and then do any functions that are waiting on the config to be received. """ self.config = config self.isyVersion = config['isyVersion'] try: for watcher in self.__configObservers: watcher(config) self.send_custom_config_doc... |
def save_typed_params(self, data): """ Send custom parameters descriptions to Polyglot to be used in front end UI configuration screen Accepts list of objects with the followin properties name - used as a key when data is sent from UI title - displayed in UI defaultValue - optionanl type - optional, can be 'NUMBER', 'S... |
tooltip in UI isRequired - optional, True/False, when set, will not validate UI input if it's empty isList - optional, True/False, if set this will be treated as list of values or objects by UI params - optional, can contain a list of objects. If present, then this (parent) is treated as object / list of objects by UI,... |
single / list of single values """ LOGGER.info('Sending typed parameters to Polyglot.') if type(data) is not list: data = [ data ] message = { 'typedparams': data } self.send(message) |
def delNode(self, address): """ Just send it along if requested, should be able to delete the node even if it isn't in our config anywhere. Usually used for normalization. """ if address in self.nodes: del self.nodes[address] self.poly.delNode(address) |
async def query(cls, query: str, variables: Optional[Mapping[str, Any]] = None, ) -> Any: ''' Sends the GraphQL query and returns the response. :param query: The GraphQL query string. :param variables: An optional key-value dictionary to fill the interpolated template variables in the query. :returns: The object parsed... |
} rqst = Request(cls.session, 'POST', '/admin/graphql') rqst.set_json(gql_query) async with rqst.fetch() as resp: return await resp.json() |
def get_readable_time_string(seconds): """Returns human readable string from number of seconds""" seconds = int(seconds) minutes = seconds // 60 seconds = seconds % 60 hours = minutes // 60 minutes = minutes % 60 days = hours // 24 hours = hours % 24 result = "" if days > 0: result += "%d %s " % (days, "Day" if (days =... |
if hours > 0: result += "%d %s " % (hours, "Hour" if (hours == 1) else "Hours") if minutes > 0: result += "%d %s " % (minutes, "Minute" if (minutes == 1) else "Minutes") if seconds > 0: result += "%d %s " % (seconds, "Second" if (seconds == 1) else "Seconds") return result.strip() |
def get_rate_limits(response): """Returns a list of rate limit information from a given response's headers.""" periods = response.headers['X-RateLimit-Period'] if not periods: return [] rate_limits = [] periods = periods.split(',') limits = response.headers['X-RateLimit-Limit'].split(',') remaining = response.headers['... |
= reset_datetime right_now = datetime.now() if (reset_datetime is not None) and (right_now < reset_datetime): # add 1 second because of rounding seconds_remaining = (reset_datetime - right_now).seconds + 1 else: seconds_remaining = 0 rate_limit["reset_in_seconds"] = seconds_remaining rate_limit["time_to_reset"] = get_r... |
def isubset(self, *keys): # type: (*Hashable) -> ww.g """Return key, self[key] as generator for key in keys. Raise KeyError if a key does not exist Args: keys: Iterable containing keys Example: >>> from ww import d >>> list(d({1: 1, 2: 2, 3: 3}).isubset(1, 3)) [(1, 1), (3, 3)] """ return ww.g((key, self[key]) for key i... |
def swap(self): # type: () -> DictWrapper """Swap key and value /!\ Be carreful, if there are duplicate values, only one will survive /!\ Example: >>> from ww import d >>> d({1: 2, 2: 2, 3: 3}).swap() {2: 2, 3: 3} """ return self.__class__((v, k) for k, v in self.items()) |
def fromkeys(cls, iterable, value=None): # TODO : type: (Iterable, Union[Any, Callable]) -> DictWrapper # https://github.com/python/mypy/issues/2254 """Create a new d from Args: iterable: Iterable containing keys value: value to associate with each key. If callable, will be value[key] Returns: new DictWrapper Example: ... |
4)] """ if not callable(value): return cls(dict.fromkeys(iterable, value)) return cls((key, value(key)) for key in iterable) |
def main(): """ Main function. :return: None. """ try: # Get the `src` directory's absolute path src_path = os.path.dirname( # `aoiklivereload` directory's absolute path os.path.dirname( # `demo` directory's absolute path os.path.dirname( # This file's absolute path os.path.abspath(__file__) ) ) ) # If the `src` direct... |
save user setting PYTHONPATH when running this demo. # sys.path.append(src_path) # Import reloader class from aoiklivereload import LiveReloader # Create reloader reloader = LiveReloader() # Start watcher thread reloader.start_watcher_thread() # Server host server_host = '0.0.0.0' # Server port server_port = 8000 # Get... |
flask_app = flask.Flask(__name__) # Create request handler @flask_app.route('/') def hello_handler(): # pylint: disable=unused-variable """ Request handler. :return: Response body. """ # Return response body return 'hello' # Run server flask_app.run( host=server_host, port=server_port, # Disable Flask's reloader debug=... |
def get_excel_workbook(api_data, result_info_key, identifier_keys): """Generates an Excel workbook object given api_data returned by the Analytics API Args: api_data: Analytics API data as a list of dicts (one per identifier) result_info_key: the key in api_data dicts that contains the data results identifier_keys: the... |
in api_data: result_info = item_data.pop(result_info_key, {}) cleaned_item_data = {} if 'meta' in item_data: meta = item_data.pop('meta') cleaned_item_data['meta'] = meta for key in item_data: cleaned_item_data[key] = item_data[key]['result'] cleaned_item_data[result_info_key] = result_info cleaned_data.append(cleaned_... |
def write_worksheets(workbook, data_list, result_info_key, identifier_keys): """Writes rest of the worksheets to workbook. Args: workbook: workbook to write into data_list: Analytics API data as a list of dicts result_info_key: the key in api_data dicts that contains the data results identifier_keys: the list of keys u... |
keys worksheet_keys = get_worksheet_keys(data_list[0], result_info_key) for key in worksheet_keys: title = key.split('/')[1] title = utilities.convert_snake_to_title_case(title) title = KEY_TO_WORKSHEET_MAP.get(title, title) if key == 'property/nod': # the property/nod endpoint needs to be split into two worksheets cre... |
result_info_key, identifier_keys) write_data(worksheet, processed_data) # remove the first, unused empty sheet workbook.remove_sheet(workbook.active) |
def create_property_nod_worksheets(workbook, data_list, result_info_key, identifier_keys): """Creates two worksheets out of the property/nod data because the data doesn't come flat enough to make sense on one sheet. Args: workbook: the main workbook to add the sheets to data_list: the main list of data result_info_key:... |
used as requested identifiers (address, zipcode, city, state, etc) """ nod_details_list = [] nod_default_history_list = [] for prop_data in data_list: nod_data = prop_data['property/nod'] if nod_data is None: nod_data = {} default_history_data = nod_data.pop('default_history', []) _set_identifier_fields(nod_data, prop_... |
def get_worksheet_keys(data_dict, result_info_key): """Gets sorted keys from the dict, ignoring result_info_key and 'meta' key Args: data_dict: dict to pull keys from Returns: list of keys in the dict other than the result_info_key """ keys = set(data_dict.keys()) keys.remove(result_info_key) if 'meta' in keys: keys.re... |
def get_keys(data_list, leading_columns=LEADING_COLUMNS): """Gets all possible keys from a list of dicts, sorting by leading_columns first Args: data_list: list of dicts to pull keys from leading_columns: list of keys to put first in the result Returns: list of keys to be included as columns in excel worksheet """ all_... |
not in all_keys: continue leading_keys.append(key) all_keys.remove(key) return leading_keys + sorted(all_keys) |
def write_data(worksheet, data): """Writes data into worksheet. Args: worksheet: worksheet to write into data: data to be written """ if not data: return if isinstance(data, list): rows = data else: rows = [data] if isinstance(rows[0], dict): keys = get_keys(rows) worksheet.append([utilities.convert_snake_to_title_case... |
values = [utilities.normalize_cell_value(value) for value in row] worksheet.append(values) else: for row in rows: worksheet.append([utilities.normalize_cell_value(row)]) |
def process_data(key, data_list, result_info_key, identifier_keys): """ Given a key as the endpoint name, pulls the data for that endpoint out of the data_list for each address, processes the data into a more excel-friendly format and returns that data. Args: key: the endpoint name of the data to process data_list: the... |
that contains the data results identifier_keys: the list of keys used as requested identifiers (address, zipcode, block_id, etc) Returns: A list of dicts (rows) to be written to a worksheet """ master_data = [] for item_data in data_list: data = item_data[key] if data is None: current_item_data = {} else: if key == 'pr... |
current_item_data = flatten_top_level_keys(data, top_level_keys) elif key == 'property/school': current_item_data = data['school'] school_list = [] for school_type_key in current_item_data: schools = current_item_data[school_type_key] for school in schools: school['school_type'] = school_type_key school['school_address... |
'client_value_sqft_percentile_range' ]) elif key in ['property/zip_details', 'zip/details']: top_level_keys = ['multi_family', 'single_family'] current_item_data = flatten_top_level_keys(data, top_level_keys) else: current_item_data = data if isinstance(current_item_data, dict): _set_identifier_fields(current_item_data... |
def flatten_top_level_keys(data, top_level_keys): """ Helper method to flatten a nested dict of dicts (one level) Example: {'a': {'b': 'bbb'}} becomes {'a_-_b': 'bbb'} The separator '_-_' gets formatted later for the column headers Args: data: the dict to flatten top_level_keys: a list of the top level keys to flatten ... |
None: flattened_data[top_level_key] = None else: for key in data[top_level_key]: flattened_data['{}_-_{}'.format(top_level_key, key)] = data[top_level_key][key] return flattened_data |
def check_database_connected(app_configs, **kwargs): """ A Django check to see if connecting to the configured default database backend succeeds. """ errors = [] try: connection.ensure_connection() except OperationalError as e: msg = 'Could not connect to database: {!s}'.format(e) errors.append(checks.Error(msg, id=hea... |
def check_migrations_applied(app_configs, **kwargs): """ A Django check to see if all migrations have been applied correctly. """ from django.db.migrations.loader import MigrationLoader errors = [] # Load migrations from disk/DB try: loader = MigrationLoader(connection, ignore_no_migrations=True) except (ImproperlyConf... |
node, migration in loader.graph.nodes.items(): if migration.app_label not in app_labels: continue if node not in loader.applied_migrations: msg = 'Unapplied migration {}'.format(migration) # NB: This *must* be a Warning, not an Error, because Errors # prevent migrations from being run. errors.append(checks.Warning(msg,... |
def check_redis_connected(app_configs, **kwargs): """ A Django check to connect to the default redis connection using ``django_redis.get_redis_connection`` and see if Redis responds to a ``PING`` command. """ import redis from django_redis import get_redis_connection errors = [] try: connection = get_redis_connection('... |
errors.append(checks.Error(msg, id=health.ERROR_MISSING_REDIS_CLIENT)) except ImproperlyConfigured as e: msg = 'Redis misconfigured: "{!s}"'.format(e) errors.append(checks.Error(msg, id=health.ERROR_MISCONFIGURED_REDIS)) else: result = connection.ping() if not result: msg = 'Redis ping failed' errors.append(checks.Erro... |
def get_realtime_alarm(username, auth, url): """Takes in no param as input to fetch RealTime Alarms from HP IMC RESTFUL API :param username OpeatorName, String type. Required. Default Value "admin". Checks the operator has the privileges to view the Real-Time Alarms. :param devId: int or str value of the target device ... |
IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return:list of dictionaries where each element of the list represents a single alarm as pulled from the the current list of realtime alarms in the HPE IMC Platform :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.alarms import * >>> aut... |
'list'> >>> assert 'faultDesc' in real_time_alarm[0] """ get_realtime_alarm_url = "/imcrs/fault/faultRealTime?operatorName=" + username f_url = url + get_realtime_alarm_url r = requests.get(f_url, auth=auth, headers=headers) try: realtime_alarm_list = (json.loads(r.text)) return realtime_alarm_list['faultRealTime']['fa... |
def get_alarms(username, auth, url): """Takes in no param as input to fetch RealTime Alarms from HP IMC RESTFUL API :param username OpeatorName, String type. Required. Default Value "admin". Checks the operator has the privileges to view the Real-Time Alarms. :param devId: int or str value of the target device :param a... |
IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return:list of dictionaries where each element of the list represents a single alarm as pulled from the the current list of browse alarms in the HPE IMC Platform :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.alarms import * >>> auth ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.