Search is not available for this dataset
text
stringlengths
75
104k
def get_page(self, form): '''Get the requested page''' page_size = form.cleaned_data['iDisplayLength'] start_index = form.cleaned_data['iDisplayStart'] paginator = Paginator(self.object_list, page_size) num_page = (start_index / page_size) + 1 return paginator.page(num_pa...
def get_row(self, row): '''Format a single row (if necessary)''' if isinstance(self.fields, dict): return dict([ (key, text_type(value).format(**row) if RE_FORMATTED.match(value) else row[value]) for key, value in self.fields.items() ]) el...
def render_to_response(self, form, **kwargs): '''Render Datatables expected JSON format''' page = self.get_page(form) data = { 'iTotalRecords': page.paginator.count, 'iTotalDisplayRecords': page.paginator.count, 'sEcho': form.cleaned_data['sEcho'], ...
def set_grant_type(self, grant_type = 'client_credentials', api_key=None, api_secret=None, scope=None, info=None): """ Grant types: - token: An authorization is requested to the end-user by redirecting it to an authorization page hosted on Dailymotion. Once authorized, ...
def authenticated(func): """ Decorator to check if Smappee's access token has expired. If it has, use the refresh token to request a new access token """ @wraps(func) def wrapper(*args, **kwargs): self = args[0] if self.refresh_token is not None and \ self.token_expira...
def urljoin(*parts): """ Join terms together with forward slashes Parameters ---------- parts Returns ------- str """ # first strip extra forward slashes (except http:// and the likes) and # create list part_list = [] for part in parts: p = str(part) ...
def authenticate(self, username, password): """ Uses a Smappee username and password to request an access token, refresh token and expiry date. Parameters ---------- username : str password : str Returns ------- requests.Response ...
def _set_token_expiration_time(self, expires_in): """ Saves the token expiration time by adding the 'expires in' parameter to the current datetime (in utc). Parameters ---------- expires_in : int number of seconds from the time of the request until expiration...
def get_service_locations(self): """ Request service locations Returns ------- dict """ url = URLS['servicelocation'] headers = {"Authorization": "Bearer {}".format(self.access_token)} r = requests.get(url, headers=headers) r.raise_for_sta...
def get_service_location_info(self, service_location_id): """ Request service location info Parameters ---------- service_location_id : int Returns ------- dict """ url = urljoin(URLS['servicelocation'], service_location_id, "info") ...
def get_consumption(self, service_location_id, start, end, aggregation, raw=False): """ Request Elektricity consumption and Solar production for a given service location. Parameters ---------- service_location_id : int start : int | dt.datetime | pd.Timestamp ...
def get_sensor_consumption(self, service_location_id, sensor_id, start, end, aggregation): """ Request consumption for a given sensor in a given service location Parameters ---------- service_location_id : int sensor_id : int start ...
def _get_consumption(self, url, start, end, aggregation): """ Request for both the get_consumption and get_sensor_consumption methods. Parameters ---------- url : str start : dt.datetime end : dt.datetime aggregation : int Returns ...
def get_events(self, service_location_id, appliance_id, start, end, max_number=None): """ Request events for a given appliance Parameters ---------- service_location_id : int appliance_id : int start : int | dt.datetime | pd.Timestamp e...
def actuator_on(self, service_location_id, actuator_id, duration=None): """ Turn actuator on Parameters ---------- service_location_id : int actuator_id : int duration : int, optional 300,900,1800 or 3600 , specifying the time in seconds the actuator ...
def actuator_off(self, service_location_id, actuator_id, duration=None): """ Turn actuator off Parameters ---------- service_location_id : int actuator_id : int duration : int, optional 300,900,1800 or 3600 , specifying the time in seconds the actuato...
def _actuator_on_off(self, on_off, service_location_id, actuator_id, duration=None): """ Turn actuator on or off Parameters ---------- on_off : str 'on' or 'off' service_location_id : int actuator_id : int duration : i...
def get_consumption_dataframe(self, service_location_id, start, end, aggregation, sensor_id=None, localize=False, raw=False): """ Extends get_consumption() AND get_sensor_consumption(), parses the results in a Pandas DataFrame ...
def _to_milliseconds(self, time): """ Converts a datetime-like object to epoch, in milliseconds Timezone-naive datetime objects are assumed to be in UTC Parameters ---------- time : dt.datetime | pd.Timestamp | int Returns ------- int ...
def _basic_post(self, url, data=None): """ Because basically every post request is the same Parameters ---------- url : str data : str, optional Returns ------- requests.Response """ _url = urljoin(self.base_url, url) r = ...
def logon(self, password='admin'): """ Parameters ---------- password : str default 'admin' Returns ------- dict """ r = self._basic_post(url='logon', data=password) return r.json()
def active_power(self): """ Takes the sum of all instantaneous active power values Returns them in kWh Returns ------- float """ inst = self.load_instantaneous() values = [float(i['value']) for i in inst if i['key'].endswith('ActivePower')] ...
def active_cosfi(self): """ Takes the average of all instantaneous cosfi values Returns ------- float """ inst = self.load_instantaneous() values = [float(i['value']) for i in inst if i['key'].endswith('Cosfi')] return sum(values) / len(values)
def on_command_control(self, val_id): """ Parameters ---------- val_id : str Returns ------- requests.Response """ data = "control,controlId=1|" + val_id return self._basic_post(url='commandControlPublic', data=data)
def off_command_control(self, val_id): """ Parameters ---------- val_id : str Returns ------- requests.Response """ data = "control,controlId=0|" + val_id return self._basic_post(url='commandControlPublic', data=data)
def delete_command_control(self, val_id): """ Parameters ---------- val_id : str Returns ------- requests.Response """ data = "delete,controlId=" + val_id return self._basic_post(url='commandControlPublic', data=data)
def delete_command_control_timers(self, val_id): """ Parameters ---------- val_id : str Returns ------- requests.Response """ data = "deleteTimers,controlId=" + val_id return self._basic_post(url='commandControlPublic', data=data)
def select_logfile(self, logfile): """ Parameters ---------- logfile : str Returns ------- dict """ data = 'logFileSelect,' + logfile r = self._basic_post(url='logBrowser', data=data) return r.json()
def getInterfaceInAllSpeeds(interface, endpoint_list, class_descriptor_list=()): """ Produce similar fs, hs and ss interface and endpoints descriptors. Should be useful for devices desiring to work in all 3 speeds with maximum endpoint wMaxPacketSize. Reduces data duplication from descriptor declara...
def getDescriptor(klass, **kw): """ Automatically fills bLength and bDescriptorType. """ # XXX: ctypes Structure.__init__ ignores arguments which do not exist # as structure fields. So check it. # This is annoying, but not doing it is a huge waste of time for the # developer. empty = kla...
def getOSDesc(interface, ext_list): """ Return an OS description header. interface (int) Related interface number. ext_list (list of OSExtCompatDesc or OSExtPropDesc) List of instances of extended descriptors. """ try: ext_type, = {type(x) for x in ext_list} except Va...
def getOSExtPropDesc(data_type, name, value): """ Returns an OS extension property descriptor. data_type (int) See wPropertyDataType documentation. name (string) See PropertyName documentation. value (string) See PropertyData documentation. NULL chars must be explicit...
def getDescsV2(flags, fs_list=(), hs_list=(), ss_list=(), os_list=()): """ Return a FunctionFS descriptor suitable for serialisation. flags (int) Any combination of VIRTUAL_ADDR, EVENTFD, ALL_CTRL_RECIP, CONFIG0_SETUP. {fs,hs,ss,os}_list (list of descriptors) Instances of the fo...
def getStrings(lang_dict): """ Return a FunctionFS descriptor suitable for serialisation. lang_dict (dict) Key: language ID (ex: 0x0409 for en-us) Value: list of unicode objects All values must have the same number of items. """ field_list = [] kw = {} try: s...
def serialise(structure): """ structure (ctypes.Structure) The structure to serialise. Returns a ctypes.c_char array. Does not copy memory. """ return ctypes.cast( ctypes.pointer(structure), ctypes.POINTER(ctypes.c_char * ctypes.sizeof(structure)), ).contents
def halt(self, request_type): """ Halt current endpoint. """ try: if request_type & ch9.USB_DIR_IN: self.read(0) else: self.write(b'') except IOError as exc: if exc.errno != errno.EL2HLT: raise ...
def getRealInterfaceNumber(self, interface): """ Returns the host-visible interface number, or None if there is no such interface. """ try: return self._ioctl(INTERFACE_REVMAP, interface) except IOError as exc: if exc.errno == errno.EDOM: ...
def getDescriptor(self): """ Returns the currently active endpoint descriptor (depending on current USB speed). """ result = USBEndpointDescriptor() self._ioctl(ENDPOINT_DESC, result, True) return result
def halt(self): """ Halt current endpoint. """ try: self._halt() except IOError as exc: if exc.errno != errno.EBADMSG: raise else: raise ValueError('halt did not return EBADMSG ?') self._halted = True
def close(self): """ Close all endpoint file descriptors. """ ep_list = self._ep_list while ep_list: ep_list.pop().close() self._closed = True
def onSetup(self, request_type, request, value, index, length): """ Called when a setup USB transaction was received. Default implementation: - handles USB_REQ_GET_STATUS on interface and endpoints - handles USB_REQ_CLEAR_FEATURE(USB_ENDPOINT_HALT) on endpoints - handles...
def main(): """ Slowly writes to stdout, without emitting a newline so any output buffering (or input for next pipeline command) can be detected. """ now = datetime.datetime.now try: while True: sys.stdout.write(str(now()) + ' ') time.sleep(1) except KeyboardI...
def onEnable(self): """ The configuration containing this function has been enabled by host. Endpoints become working files, so submit some read operations. """ trace('onEnable') self._disable() self._aio_context.submit(self._aio_recv_block_list) self._rea...
def _disable(self): """ The configuration containing this function has been disabled by host. Endpoint do not work anymore, so cancel AIO operation blocks. """ if self._enabled: self._real_onCannotSend() has_cancelled = 0 for block in self._aio...
def onAIOCompletion(self): """ Call when eventfd notified events are available. """ event_count = self.eventfd.read() trace('eventfd reports %i events' % event_count) # Even though eventfd signaled activity, even though it may give us # some number of pending even...
def write(self, value): """ Queue write in kernel. value (bytes) Value to send. """ aio_block = libaio.AIOBlock( mode=libaio.AIOBLOCK_MODE_WRITE, target_file=self.getEndpoint(1), buffer_list=[bytearray(value)], offset=0,...
def pretty_error(error, verbose=False): """Return an error message that is easier to read and more useful. May require updating if the schemas change significantly. """ error_loc = '' if error.path: while len(error.path) > 0: path_elem = error.path.popleft() if type(...
def _iter_errors_custom(instance, checks, options): """Perform additional validation not possible merely with JSON schemas. Args: instance: The STIX object to be validated. checks: A sequence of callables which do the checks. Each callable may be written to accept 1 arg, which is t...
def list_json_files(directory, recursive=False): """Return a list of file paths for JSON files within `directory`. Args: directory: A path to a directory. recursive: If ``True``, this function will descend into all subdirectories. Returns: A list of JSON file paths dire...
def get_json_files(files, recursive=False): """Return a list of files to validate from `files`. If a member of `files` is a directory, its children with a ``.json`` extension will be added to the return value. Args: files: A list of file paths and/or directory paths. recursive: If ``tru...
def run_validation(options): """Validate files based on command line options. Args: options: An instance of ``ValidationOptions`` containing options for this validation run. """ if options.files == sys.stdin: results = validate(options.files, options) return [FileVa...
def validate_parsed_json(obj_json, options=None): """ Validate objects from parsed JSON. This supports a single object, or a list of objects. If a single object is given, a single result is returned. Otherwise, a list of results is returned. If an error occurs, a ValidationErrorResults instance ...
def validate(in_, options=None): """ Validate objects from JSON data in a textual stream. :param in_: A textual stream of JSON data. :param options: Validation options :return: An ObjectValidationResults instance, or a list of such. """ obj_json = json.load(in_) results = validate_pars...
def validate_file(fn, options=None): """Validate the input document `fn` according to the options passed in. If any exceptions are raised during validation, no further validation will take place. Args: fn: The filename of the JSON file to be validated. options: An instance of ``Validat...
def validate_string(string, options=None): """Validate the input `string` according to the options passed in. If any exceptions are raised during validation, no further validation will take place. Args: string: The string containing the JSON to be validated. options: An instance of ``V...
def load_validator(schema_path, schema): """Create a JSON schema validator for the given schema. Args: schema_path: The filename of the JSON schema. schema: A Python object representation of the same schema. Returns: An instance of Draft4Validator. """ # Get correct prefix...
def find_schema(schema_dir, obj_type): """Search the `schema_dir` directory for a schema called `obj_type`.json. Return the file path of the first match it finds. """ schema_filename = obj_type + '.json' for root, dirnames, filenames in os.walk(schema_dir): if schema_filename in filenames: ...
def load_schema(schema_path): """Load the JSON schema at the given path as a Python object. Args: schema_path: A filename for a JSON schema. Returns: A Python object representation of the schema. """ try: with open(schema_path) as schema_file: schema = json.loa...
def _get_error_generator(type, obj, schema_dir=None, version=DEFAULT_VER, default='core'): """Get a generator for validating against the schema for the given object type. Args: type (str): The object type to find the schema for. obj: The object to be validated. schema_dir (str): The pat...
def _get_musts(options): """Return the list of 'MUST' validators for the correct version of STIX. Args: options: ValidationOptions instance with validation options for this validation run, including the STIX spec version. """ if options.version == '2.0': return musts20.list_...
def _get_shoulds(options): """Return the list of 'SHOULD' validators for the correct version of STIX. Args: options: ValidationOptions instance with validation options for this validation run, including the STIX spec version. """ if options.version == '2.0': return shoulds20...
def _schema_validate(sdo, options): """Set up validation of a single STIX object against its type's schema. This does no actual validation; it just returns generators which must be iterated to trigger the actual generation. This function first creates generators for the built-in schemas, then adds ...
def validate_instance(instance, options=None): """Perform STIX JSON Schema validation against STIX input. Find the correct schema by looking at the 'type' property of the `instance` JSON object. Args: instance: A Python dictionary representing a STIX object with a 'type' property. ...
def object_result(self): """ Get the object result object, assuming there is only one. Raises an error if there is more than one. :return: The result object :raises ValueError: If there is more than one result """ num_obj_results = len(self._object_results) ...
def object_results(self, object_results): """ Set the results to an iterable of values. The values will be collected into a list. A single value is allowed; it will be converted to a length 1 list. :param object_results: The results to set """ if _is_iterable_no...
def as_dict(self): """A dictionary representation of the :class:`.ObjectValidationResults` instance. Keys: * ``'result'``: The validation results (``True`` or ``False``) * ``'errors'``: A list of validation errors. Returns: A dictionary representatio...
def custom_prefix_strict(instance): """Ensure custom content follows strict naming style conventions. """ for error in chain(custom_object_prefix_strict(instance), custom_property_prefix_strict(instance), custom_observable_object_prefix_strict(instance), ...
def custom_prefix_lax(instance): """Ensure custom content follows lenient naming style conventions for forward-compatibility. """ for error in chain(custom_object_prefix_lax(instance), custom_property_prefix_lax(instance), custom_observable_object_prefix_lax...
def custom_object_prefix_strict(instance): """Ensure custom objects follow strict naming style conventions. """ if (instance['type'] not in enums.TYPES and instance['type'] not in enums.RESERVED_OBJECTS and not CUSTOM_TYPE_PREFIX_RE.match(instance['type'])): yield JSONError("...
def custom_object_prefix_lax(instance): """Ensure custom objects follow lenient naming style conventions for forward-compatibility. """ if (instance['type'] not in enums.TYPES and instance['type'] not in enums.RESERVED_OBJECTS and not CUSTOM_TYPE_LAX_PREFIX_RE.match(instance['typ...
def custom_property_prefix_strict(instance): """Ensure custom properties follow strict naming style conventions. Does not check property names in custom objects. """ for prop_name in instance.keys(): if (instance['type'] in enums.PROPERTIES and prop_name not in enums.PROPERTIES[...
def custom_property_prefix_lax(instance): """Ensure custom properties follow lenient naming style conventions for forward-compatibility. Does not check property names in custom objects. """ for prop_name in instance.keys(): if (instance['type'] in enums.PROPERTIES and prop_n...
def open_vocab_values(instance): """Ensure that the values of all properties which use open vocabularies are in lowercase and use hyphens instead of spaces or underscores as word separators. """ if instance['type'] not in enums.VOCAB_PROPERTIES: return properties = enums.VOCAB_PROPERTIE...
def kill_chain_phase_names(instance): """Ensure the `kill_chain_name` and `phase_name` properties of `kill_chain_phase` objects follow naming style conventions. """ if instance['type'] in enums.KILL_CHAIN_PHASE_USES and 'kill_chain_phases' in instance: for phase in instance['kill_chain_phases']:...
def check_vocab(instance, vocab, code): """Ensure that the open vocabulary specified by `vocab` is used properly. This checks properties of objects specified in the appropriate `_USES` dictionary to determine which properties SHOULD use the given vocabulary, then checks that the values in those propert...
def vocab_marking_definition(instance): """Ensure that the `definition_type` property of `marking-definition` objects is one of the values in the STIX 2.0 specification. """ if (instance['type'] == 'marking-definition' and 'definition_type' in instance and not instance['definitio...
def relationships_strict(instance): """Ensure that only the relationship types defined in the specification are used. """ # Don't check objects that aren't relationships or that are custom objects if (instance['type'] != 'relationship' or instance['type'] not in enums.TYPES): ret...
def valid_hash_value(hashname): """Return true if given value is a valid, recommended hash name according to the STIX 2 specification. """ custom_hash_prefix_re = re.compile(r"^x_") if hashname in enums.HASH_ALGO_OV or custom_hash_prefix_re.match(hashname): return True else: retu...
def vocab_hash_algo(instance): """Ensure objects with 'hashes' properties only use values from the hash-algo-ov vocabulary. """ for key, obj in instance['objects'].items(): if 'type' not in obj: continue if obj['type'] == 'file': try: hashes = obj...
def vocab_windows_pebinary_type(instance): """Ensure file objects with the windows-pebinary-ext extension have a 'pe-type' property that is from the windows-pebinary-type-ov vocabulary. """ for key, obj in instance['objects'].items(): if 'type' in obj and obj['type'] == 'file': try: ...
def vocab_account_type(instance): """Ensure a user-account objects' 'account-type' property is from the account-type-ov vocabulary. """ for key, obj in instance['objects'].items(): if 'type' in obj and obj['type'] == 'user-account': try: acct_type = obj['account_type'...
def observable_object_keys(instance): """Ensure observable-objects keys are non-negative integers. """ digits_re = re.compile(r"^\d+$") for key in instance['objects']: if not digits_re.match(key): yield JSONError("'%s' is not a good key value. Observable Objects " ...
def custom_observable_object_prefix_strict(instance): """Ensure custom observable objects follow strict naming style conventions. """ for key, obj in instance['objects'].items(): if ('type' in obj and obj['type'] not in enums.OBSERVABLE_TYPES and obj['type'] not in enums.OBSERVABLE_R...
def custom_observable_object_prefix_lax(instance): """Ensure custom observable objects follow naming style conventions. """ for key, obj in instance['objects'].items(): if ('type' in obj and obj['type'] not in enums.OBSERVABLE_TYPES and obj['type'] not in enums.OBSERVABLE_RESERVED_OB...
def custom_object_extension_prefix_strict(instance): """Ensure custom observable object extensions follow strict naming style conventions. """ for key, obj in instance['objects'].items(): if not ('extensions' in obj and 'type' in obj and obj['type'] in enums.OBSERVABLE_EXTENSIONS...
def custom_object_extension_prefix_lax(instance): """Ensure custom observable object extensions follow naming style conventions. """ for key, obj in instance['objects'].items(): if not ('extensions' in obj and 'type' in obj and obj['type'] in enums.OBSERVABLE_EXTENSIONS): ...
def custom_observable_properties_prefix_strict(instance): """Ensure observable object custom properties follow strict naming style conventions. """ for key, obj in instance['objects'].items(): if 'type' not in obj: continue type_ = obj['type'] for prop in obj: ...
def network_traffic_ports(instance): """Ensure network-traffic objects contain both src_port and dst_port. """ for key, obj in instance['objects'].items(): if ('type' in obj and obj['type'] == 'network-traffic' and ('src_port' not in obj or 'dst_port' not in obj)): yield ...
def mime_type(instance): """Ensure the 'mime_type' property of file objects comes from the Template column in the IANA media type registry. """ mime_pattern = re.compile(r'^(application|audio|font|image|message|model' '|multipart|text|video)/[a-zA-Z0-9.+_-]+') for key, ...
def protocols(instance): """Ensure the 'protocols' property of network-traffic objects contains only values from the IANA Service Name and Transport Protocol Port Number Registry. """ for key, obj in instance['objects'].items(): if ('type' in obj and obj['type'] == 'network-traffic' and ...
def ipfix(instance): """Ensure the 'ipfix' property of network-traffic objects contains only values from the IANA IP Flow Information Export (IPFIX) Entities Registry. """ ipf_pattern = re.compile(r'^[a-z][a-zA-Z0-9]+') for key, obj in instance['objects'].items(): if ('type' in obj and obj['...
def http_request_headers(instance): """Ensure the keys of the 'request_headers' property of the http-request- ext extension of network-traffic objects conform to the format for HTTP request headers. Use a regex because there isn't a definitive source. https://www.iana.org/assignments/message-headers/mes...
def socket_options(instance): """Ensure the keys of the 'options' property of the socket-ext extension of network-traffic objects are only valid socket options (SO_*). """ for key, obj in instance['objects'].items(): if ('type' in obj and obj['type'] == 'network-traffic'): try: ...
def pdf_doc_info(instance): """Ensure the keys of the 'document_info_dict' property of the pdf-ext extension of file objects are only valid PDF Document Information Dictionary Keys. """ for key, obj in instance['objects'].items(): if ('type' in obj and obj['type'] == 'file'): try...
def countries(instance): """Ensure that the `country` property of `location` objects is a valid ISO 3166-1 ALPHA-2 Code. """ if (instance['type'] == 'location' and 'country' in instance and not instance['country'].upper() in enums.COUNTRY_CODES): return JSONError("Location `country`...
def windows_process_priority_format(instance): """Ensure the 'priority' property of windows-process-ext ends in '_CLASS'. """ class_suffix_re = re.compile(r'.+_CLASS$') for key, obj in instance['objects'].items(): if 'type' in obj and obj['type'] == 'process': try: pr...
def hash_length(instance): """Ensure keys in 'hashes'-type properties are no more than 30 characters long. """ for key, obj in instance['objects'].items(): if 'type' not in obj: continue if obj['type'] == 'file': try: hashes = obj['hashes'] ...
def duplicate_ids(instance): """Ensure objects with duplicate IDs have different `modified` timestamps. """ if instance['type'] != 'bundle' or 'objects' not in instance: return unique_ids = {} for obj in instance['objects']: if 'id' not in obj or 'modified' not in obj: c...
def list_shoulds(options): """Construct the list of 'SHOULD' validators to be run by the validator. """ validator_list = [] # Default: enable all if not options.disabled and not options.enabled: validator_list.extend(CHECKS['all']) return validator_list # --disable # Add SH...
def timestamp(instance): """Ensure timestamps contain sane months, days, hours, minutes, seconds. """ ts_re = re.compile(r"^[0-9]{4}-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])T([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]|60)(\.[0-9]+)?Z$") timestamp_props = ['created', 'modified'] if instance['type'] i...