INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Get the name of the file containing configuration overrides from the provided environment variable.
def get_overrides_filename(variable): """ Get the name of the file containing configuration overrides from the provided environment variable. """ filename = os.environ.get(variable) if filename is None: msg = 'Please set the {} environment variable.'.format(variable) raise Envir...
Parameters ---------- output_category: str inputs: epw idf table: summary table other: other
def get_output_files_layout(output_category): """ Parameters ---------- output_category: str inputs: epw, idf table: summary table other: other """ # check category if output_category not in ("inputs", "table", "other"): raise RuntimeError(f"unknown {output_c...
Finds the value depending in current eplus version.
def get_value_by_version(d): """ Finds the value depending in current eplus version. Parameters ---------- d: dict {(0, 0): value, (x, x): value, ...} for current version (cv), current value is the value of version v such as v <= cv < v+1 """ from oplus import CONF # touch...
works inplace
def switch_to_datetime_instants(df, start_year, eplus_frequency): """ works inplace """ # timestep -> monthly if eplus_frequency in (TIMESTEP, DAILY, HOURLY, MONTHLY): # prepare year switch if eplus_frequency in (TIMESTEP, HOURLY, DAILY): # print((df[["month", "day"]] - d...
if _eplus_version is defined = > _eplus_version else most recent eplus available version
def eplus_version(self): """ if _eplus_version is defined => _eplus_version else most recent eplus available version """ # check energy plus is installed if len(self.eplus_available_versions) == 0: raise RuntimeError("Energy plus is not install, can't use oplu...
Parameters ---------- df
def _check_and_sanitize_datetime_instants(df): """ Parameters ---------- df Returns ------- sanitized df """ # leave if not relevant if df is None or len(df) == 0: return df # check datetime index if not isinstance(df.index, pd.DatetimeIndex): raise Valu...
Returns ------- ( start end )
def get_bounds(self): """ Returns ------- (start, end) Datetime instants of beginning and end of data. If no data, will be: (None, None). """ start, end = None, None if len(self._weather_series) == 0: return start, end for i in (0, -1...
Parameters ---------- buffer_or_path: buffer or path containing epw format.
def from_epw(cls, buffer_or_path): """ Parameters ---------- buffer_or_path: buffer or path containing epw format. Returns ------- WeatherData instance. """ from .epw_parse import parse_epw _, buffer = to_buffer(buffer_or_path) wit...
Parameters ---------- buffer_or_path: buffer or path default None Buffer or path to write into. If None will return a string containing epw info.
def to_epw(self, buffer_or_path=None): """ Parameters ---------- buffer_or_path: buffer or path, default None Buffer or path to write into. If None, will return a string containing epw info. Returns ------- None or a string if buffer_or_path is None. ...
Records are created from string. They are not attached to idf yet. in idf: header comment chapter comments records in record: head comment field comments tail comment
def parse_idf(file_like): """ Records are created from string. They are not attached to idf yet. in idf: header comment, chapter comments, records in record: head comment, field comments, tail comment """ tables_data = {} head_comment = "" record_data = None make_new_record = Tru...
Parameters ---------- epm_or_idf_path: weather_data_or_epw_path simulation_dir_path stdout: default sys. stdout stderr: default sys. stderr beat_freq: if not none stdout will be used at least every beat_freq ( in seconds )
def run_eplus(epm_or_idf_path, weather_data_or_epw_path, simulation_dir_path, stdout=None, stderr=None, beat_freq=None): """ Parameters ---------- epm_or_idf_path: weather_data_or_epw_path simulation_dir_path stdout: default sys.stdout stderr: default sys.stderr beat_freq: if not non...
Parameters ---------- epm_or_path weather_data_or_path base_dir_path: simulation dir path simulation_name: str default None if provided simulation will be done in { base_dir_path }/ { simulation_name } else simulation will be done in { base_dir_path } stdout: stream default logger. info stream where EnergyPlus standard...
def simulate( cls, epm_or_path, weather_data_or_path, base_dir_path, simulation_name=None, stdout=None, stderr=None, beat_freq=None ): """ Parameters ---------- epm_or_path weather...
Defined here so that we can use the class variables in order to subclass in oplusplus
def _file_refs(self): """ Defined here so that we can use the class variables, in order to subclass in oplusplus """ if self._prepared_file_refs is None: self._prepared_file_refs = { FILE_REFS.idf: FileInfo( constructor=lambda path: self._e...
Parameters ---------- file_ref: str reference of file. Available references: idf epw eio eso mtr mtd mdd err summary_table See EnergyPlus documentation for more information.
def exists(self, file_ref): """ Parameters ---------- file_ref: str reference of file. Available references: 'idf', 'epw', 'eio', 'eso', 'mtr', 'mtd', 'mdd', 'err', 'summary_table' See EnergyPlus documentation for more information. Returns ...
Parameters ---------- file_ref: str reference of file. Available references: idf epw eio eso mtr mtd mdd err summary_table See EnergyPlus documentation for more information.
def get_file_path(self, file_ref): """ Parameters ---------- file_ref: str reference of file. Available references: 'idf', 'epw', 'eio', 'eso', 'mtr', 'mtd', 'mdd', 'err', 'summary_table' See EnergyPlus documentation for more information. Ret...
Parameters ---------- model_name: with or without extension
def default_external_files_dir_name(model_name): """ Parameters ---------- model_name: with or without extension """ name, ext = os.path.splitext(model_name) return name + CONF.external_files_suffix
!! Must only be called once when empty !!
def _dev_populate_from_json_data(self, json_data): """ !! Must only be called once, when empty !! """ # workflow # -------- # (methods belonging to create/update/delete framework: # epm._dev_populate_from_json_data, table.batch_add, record.update, queryset.de...
An external file manages file paths.
def get_external_files(self): """ An external file manages file paths. """ external_files = [] for table in self._tables.values(): for r in table: external_files.extend([ef for ef in r.get_external_files()]) return external_files
All fields of Epm with a default value and that are null will be set to their default value.
def set_defaults(self): """ All fields of Epm with a default value and that are null will be set to their default value. """ for table in self._tables.values(): for r in table: r.set_defaults()
Parameters ---------- json_data: dict Dictionary of serialized data ( text floats ints... ). For more information on data structure create an Epm and use to_json_data or to_json. check_required: boolean default True If True will raise an exception if a required field is missing. If False not not perform any checks. idd...
def from_json_data(cls, json_data, check_required=True, idd_or_buffer_or_path=None): """ Parameters ---------- json_data: dict Dictionary of serialized data (text, floats, ints, ...). For more information on data structure, create an Epm and use to_json_data or to...
Parameters ---------- buffer_or_path: idf buffer or path check_required: boolean default True If True will raise an exception if a required field is missing. If False not not perform any checks. idd_or_buffer_or_path: ( expert ) to load using a custom idd
def from_idf(cls, buffer_or_path, check_required=True, idd_or_buffer_or_path=None): """ Parameters ---------- buffer_or_path: idf buffer or path check_required: boolean, default True If True, will raise an exception if a required field is missing. If False, not not pe...
Parameters ---------- buffer_or_path: json buffer or path check_required: boolean default True If True will raise an exception if a required field is missing. If False not not perform any checks. idd_or_buffer_or_path: ( expert ) to load using a custom idd
def from_json(cls, buffer_or_path, check_required=True, idd_or_buffer_or_path=None): """ Parameters ---------- buffer_or_path: json buffer or path check_required: boolean, default True If True, will raise an exception if a required field is missing. If False, not not ...
Returns ------- A dictionary of serialized data.
def to_json_data(self): """ Returns ------- A dictionary of serialized data. """ # create data d = collections.OrderedDict((t.get_ref(), t.to_json_data()) for t in self._tables.values()) d["_comment"] = self._comment d.move_to_end("_comment", last=...
Parameters ---------- buffer_or_path: buffer or path default None output to write into. If None will return a json string. indent: int default 2 Defines the indentation of the json
def to_json(self, buffer_or_path=None, indent=2): """ Parameters ---------- buffer_or_path: buffer or path, default None output to write into. If None, will return a json string. indent: int, default 2 Defines the indentation of the json Returns ...
Parameters ---------- buffer_or_path: buffer or path default None output to write into. If None will return a json string. dump_external_files: boolean default True if True external files will be dumped in external files directory
def to_idf(self, buffer_or_path=None, dump_external_files=True): """ Parameters ---------- buffer_or_path: buffer or path, default None output to write into. If None, will return a json string. dump_external_files: boolean, default True if True, external f...
Parameters ---------- filter_by: callable default None Callable must take one argument ( a record of queryset ) and return True to keep record or False to skip it. Example:. select ( lambda x: x. name == my_name ). If None records are not filtered.
def select(self, filter_by=None): """ Parameters ---------- filter_by: callable, default None Callable must take one argument (a record of queryset), and return True to keep record, or False to skip it. Example : .select(lambda x: x.name == "my_name"). ...
Parameters ---------- filter_by: callable default None Callable must take one argument ( a record of table ) and return True to keep record or False to skip it. Example:. one ( lambda x: x. name == my_name ). If None records are not filtered.
def one(self, filter_by=None): """ Parameters ---------- filter_by: callable, default None Callable must take one argument (a record of table), and return True to keep record, or False to skip it. Example : .one(lambda x: x.name == "my_name"). If None,...
Returns ------- None if epw can be anywhere
def get_simulated_epw_path(): """ Returns ------- None if epw can be anywhere """ from oplus import CONF # touchy imports if OS_NAME == "windows": return os.path.join(CONF.eplus_base_dir_path, "WeatherData", "%s.epw" % CONF.default_model_name)
This function finishes initialization must be called once all field descriptors and tag have been filled.
def prepare_extensible(self): """ This function finishes initialization, must be called once all field descriptors and tag have been filled. """ # see if extensible and store cycle len for k in self._tags: if "extensible" in k: cycle_len = int(k.split(...
reduced index: modulo of extensible has been applied
def get_field_reduced_index(self, index): """ reduced index: modulo of extensible has been applied """ # return index if not extensible if self.extensible_info is None: return index # manage extensible cycle_start, cycle_len, _ = self.extensib...
manages extensible names
def get_extended_name(self, index): """ manages extensible names """ field_descriptor = self.get_field_descriptor(index) if self.extensible_info is None: return field_descriptor.name cycle_start, cycle_len, _ = self.extensible_info cycle_num = (index -...
index is used for extensible fields error messages ( if given )
def deserialize(self, value, index): """ index is used for extensible fields error messages (if given) """ # -- serialize if not raw type # transform to string if external file if isinstance(value, ExternalFile): value = value.pointer # transform to s...
Uses EPlus double approach of type ( type tag and/ or key object - list external - list reference tags ) to determine detailed type. Returns ------- integer real alpha choice reference object - list external - list node
def detailed_type(self): """ Uses EPlus double approach of type ('type' tag, and/or 'key', 'object-list', 'external-list', 'reference' tags) to determine detailed type. Returns ------- "integer", "real", "alpha", "choice", "reference", "object-list", "external-li...
we calculate on the fly to avoid managing registrations and un - registrations
def short_refs(self): """ we calculate on the fly to avoid managing registrations and un-registrations Returns ------- {ref: short_ref, ... """ naive_short_refs_d = dict() # naive_short_ref: {refs, ...} for ef in self._external_files: if ef.n...
Returns first occurrence of value of filter column matching filter criterion.
def get_value(self, column_name_or_i, filter_column_name_or_i, filter_criterion): """ Returns first occurrence of value of filter column matching filter criterion. """ # find column indexes column_i = self._get_column_index(column_name_or_i) filter_column_i = self._get_co...
is only called by _update_inert
def _update_value_inert(self, index, value): """ is only called by _update_inert """ # get field descriptor field_descriptor = self._table._dev_descriptor.get_field_descriptor(index) # prepare value value = field_descriptor.deserialize(value, index) # un...
Parameters ---------- ref_or_index external_files_mode: str default path path pointer model_file_path: str default None if external files are asked in a relative fashion relative path will be calculated relatively to model_file_path if given else current directory
def get_serialized_value(self, ref_or_index, model_name=None): """ Parameters ---------- ref_or_index external_files_mode: str, default 'path' 'path', 'pointer' model_file_path: str, default None if external files are asked in a relative fashion, r...
Returns ------- List of ExternalFiles instances contained by record.
def get_external_files(self): """ Returns ------- List of ExternalFiles instances contained by record. """ return [v for v in self._data.values() if isinstance(v, ExternalFile)]
Updates simultaneously all given fields.
def update(self, data=None, **or_data): """ Updates simultaneously all given fields. Parameters ---------- data: dictionary containing field lowercase names or index as keys, and field values as values (dict syntax) or_data: keyword arguments containing field names as ke...
Parameters ---------- new_name: str default None record s new name ( if table has a name ). If None although record has a name a random uuid will be given.
def copy(self, new_name=None): """ Parameters ---------- new_name: str, default None record's new name (if table has a name). If None although record has a name, a random uuid will be given. Returns ------- Copied record. """ # todo: c...
sets all empty fields for which a default value is defined to default value
def set_defaults(self): """ sets all empty fields for which a default value is defined to default value """ defaults = {} for i in range(len(self)): if i in self._data: continue default = self.get_field_descriptor(i).tags.get("default", [No...
This method only works for extensible fields. It allows to add values without precising their fields names or indexes.
def add_fields(self, *args): """ This method only works for extensible fields. It allows to add values without precising their fields' names or indexes. Parameters ---------- args: field values """ if not self.is_extensible(): raise TypeError(...
This method only works for extensible fields. It allows to remove a value and shift all other values to fill the gap.
def pop(self, index=None): """ This method only works for extensible fields. It allows to remove a value and shift all other values to fill the gap. Parameters ---------- index: int, default None index of field to remove. Returns ------- ...
This method only works for extensible fields. It allows to insert a value and shifts all other following values.
def insert(self, index, value): """ This method only works for extensible fields. It allows to insert a value, and shifts all other following values. Parameters ---------- index: position of insertion value: value to insert """ # prepare index (wi...
Returns ------- list of cleared fields ( serialized )
def clear_extensible_fields(self): """ Returns ------- list of cleared fields (serialized) """ if not self.is_extensible(): raise TypeError("Can't use add_fields on a non extensible record.") cycle_start, cycle_len, patterns = self.get_extensible_info(...
Deletes record and removes it from database.
def delete(self): """ Deletes record, and removes it from database. """ # workflow # -------- # (methods belonging to create/update/delete framework: # epm._dev_populate_from_json_data, table.batch_add, record.update, queryset.delete, record.delete) # ...
Parameters ---------- ref_or_index: str or int field lowercase name or field position
def get_field_descriptor(self, ref_or_index): """ Parameters ---------- ref_or_index: str or int field lowercase name, or field position Returns ------- Field descriptor (info contained in Idd) """ if isinstance(ref_or_index, int): ...
Parameters ---------- model_name: str default None if given will be used as external file directory base name
def to_json_data(self, model_name=None): """ Parameters ---------- model_name: str, default None if given, will be used as external file directory base name Returns ------- A dictionary of serialized data. """ return collections.Ordere...
Parameters ---------- model_name: str default None if given will be used as external file directory base name
def to_idf(self, model_name=None): """ Parameters ---------- model_name: str, default None if given, will be used as external file directory base name Returns ------- idf string """ json_data = self.to_json_data(model_name=model_name...
Tested under EPlus 8. 1. 0 on Windows ( Geoffroy ).
def check(): """ Tested under EPlus 8.1.0 on Windows (Geoffroy). """ # !! CAN BE VERY LONG epw_path = os.path.join(CONF.eplus_base_dir_path, "WeatherData", "USA_VA_Sterling-Washington.Dulles.Intl.AP.724030_TMY3.epw") idf_dir_path = os.path.join(CONF.eplus_base_dir_pat...
Parameters ---------- environment_title_or_num frequency: str default None timestep hourly daily monthly annual run_period If None will look for the smallest frequency of environment.
def get_data(self, environment_title_or_num=-1, frequency=None): """ Parameters ---------- environment_title_or_num frequency: 'str', default None 'timestep', 'hourly', 'daily', 'monthly', 'annual', 'run_period' If None, will look for the smallest frequenc...
this hack is used to document add function a methods __doc__ attribute is read - only ( or must use metaclasses what I certainly don t want to do... ) we therefore create a function ( who s __doc__ attribute is read/ write ) and will bind it to Table in __init__
def get_documented_add(self, record_descriptors): """ this hack is used to document add function a methods __doc__ attribute is read-only (or must use metaclasses, what I certainly don't want to do...) we therefore create a function (who's __doc__ attribute is read/write), and will bind it to Table in _...
inert: hooks and links are not activated
def _dev_add_inert(self, records_data): """ inert: hooks and links are not activated """ added_records = [] for r_data in records_data: # create record record = Record( self, data=r_data ) # store ...
Parameters ---------- filter_by: callable default None Callable must take one argument ( a record of table ) and return True to keep record or False to skip it. Example:. select ( lambda x: x. name == my_name ). If None records are not filtered.
def select(self, filter_by=None): """ Parameters ---------- filter_by: callable, default None Callable must take one argument (a record of table), and return True to keep record, or False to skip it. Example : .select(lambda x: x.name == "my_name"). If...
Parameters ---------- filter_by: callable default None Callable must take one argument ( a record of table ) and return True to keep record or False to skip it. Example:. one ( lambda x: x. name == my_name ). If None records are not filtered.
def one(self, filter_by=None): """ Parameters ---------- filter_by: callable, default None Callable must take one argument (a record of table), and return True to keep record, or False to skip it. Example : .one(lambda x: x.name == "my_name"). If None,...
Parameters ---------- records_data: list of dictionaries containing records data. Keys of dictionary may be field names and/ or field indexes
def batch_add(self, records_data): """ Parameters ---------- records_data: list of dictionaries containing records data. Keys of dictionary may be field names and/or field indexes Returns ------- Queryset instance of added records """ ...
target record must have been set
def register_record_hook(self, hook): """ target record must have been set """ for key in hook.keys: if key in self._record_hooks: field_descriptor = hook.target_record.get_field_descriptor(hook.target_index) raise FieldValidationError( ...
source record and index must have been set
def register_link(self, link): """ source record and index must have been set """ keys = tuple((ref, link.initial_hook_value) for ref in link.hook_references) # look for a record hook for k in keys: if k in self._record_hooks: # set link targe...
Parameters ---------- command: command cwd: current working directory stdout: output info stream ( must have write method ) stderr: output error stream ( must have write method ) shell: see subprocess. Popen beat_freq: if not none stdout will be used at least every beat_freq ( in seconds )
def run_subprocess(command, cwd=None, stdout=None, stderr=None, shell=False, beat_freq=None): """ Parameters ---------- command: command cwd: current working directory stdout: output info stream (must have 'write' method) stderr: output error stream (must have 'write' method) shell: see ...
path_or_content: path or content_str or content_bts or string_io or bytes_io
def get_string_buffer(path_or_content, expected_extension): """ path_or_content: path or content_str or content_bts or string_io or bytes_io Returns ------- string_buffer, path path will be None if input was not a path """ buffer, path = None, None # path or content string if...
Parameters ---------- simulation_step: if not given returns a raw report error_category: if only one argument is specified swaps dataframe report
def get_data(self, simulation_step=None, error_category=None): """ Parameters ---------- simulation_step: if not given, returns a raw report error_category: if only one argument is specified, swaps dataframe report """ if simulation_step is None and error_category...
Create regex and return. If error occurs returns None.
def _create_regex(self, line, intent_name): """ Create regex and return. If error occurs returns None. """ try: return re.compile(self._create_intent_pattern(line, intent_name), re.IGNORECASE) except sre_constants.error as e: LOG.warning('Fai...
Convert status ( id ) to its string name.
def str(cls, value): '''Convert status (id) to its string name.''' for k, v in cls.__dict__.items(): if k[0] in string.ascii_uppercase and v == value: return k.lower().replace('_', ' ')
Returns the remaining duration for a recording.
def remaining_duration(self, time): '''Returns the remaining duration for a recording. ''' return max(0, self.end - max(self.start, time))
Serialize this object as dictionary usable for conversion to JSON.
def serialize(self): '''Serialize this object as dictionary usable for conversion to JSON. :return: Dictionary representing this object. ''' return { 'type': 'event', 'id': self.uid, 'attributes': { 'start': self.start, ...
Make an HTTP request to a given URL with optional parameters.
def http_request(url, post_data=None): '''Make an HTTP request to a given URL with optional parameters. ''' logger.debug('Requesting URL: %s' % url) buf = bio() curl = pycurl.Curl() curl.setopt(curl.URL, url.encode('ascii', 'ignore')) # Disable HTTPS verification methods if insecure is set ...
Get available service endpoints for a given service type from the Opencast ServiceRegistry.
def get_service(service_type): '''Get available service endpoints for a given service type from the Opencast ServiceRegistry. ''' endpoint = '/services/available.json?serviceType=' + str(service_type) url = '%s%s' % (config()['server']['url'], endpoint) response = http_request(url).decode('utf-8...
Convert datetime into a unix timestamp. This is the equivalent to Python 3 s int ( datetime. timestamp () ).
def unix_ts(dtval): '''Convert datetime into a unix timestamp. This is the equivalent to Python 3's int(datetime.timestamp()). :param dt: datetime to convert ''' epoch = datetime(1970, 1, 1, 0, 0, tzinfo=tzutc()) delta = (dtval - epoch) return delta.days * 24 * 3600 + delta.seconds
Try to create a directory. Pass without error if it already exists.
def try_mkdir(directory): '''Try to create a directory. Pass without error if it already exists. ''' try: os.mkdir(directory) except OSError as err: if err.errno != errno.EEXIST: raise err
Get the location of a given service from Opencast and add it to the current configuration.
def configure_service(service): '''Get the location of a given service from Opencast and add it to the current configuration. ''' while not config().get('service-' + service) and not terminate(): try: config()['service-' + service] = \ get_service('org.opencastproject...
Register this capture agent at the Matterhorn admin server so that it shows up in the admin interface.
def register_ca(status='idle'): '''Register this capture agent at the Matterhorn admin server so that it shows up in the admin interface. :param address: Address of the capture agent web ui :param status: Current status of the capture agent ''' # If this is a backup CA we don't tell the Matterh...
Send the state of the current recording to the Matterhorn core.
def recording_state(recording_id, status): '''Send the state of the current recording to the Matterhorn core. :param recording_id: ID of the current recording :param status: Status of the recording ''' # If this is a backup CA we do not update the recording state since the # actual CA does that...
Update the status of a particular event in the database.
def update_event_status(event, status): '''Update the status of a particular event in the database. ''' dbs = db.get_session() dbs.query(db.RecordedEvent).filter(db.RecordedEvent.start == event.start)\ .update({'status': status}) event.status = status dbs.commit()
Update the status of a particular service in the database.
def set_service_status(service, status): '''Update the status of a particular service in the database. ''' srv = db.ServiceStates() srv.type = service srv.status = status dbs = db.get_session() dbs.merge(srv) dbs.commit() dbs.close()
Update the status of a particular service in the database.
def get_service_status(service): '''Update the status of a particular service in the database. ''' dbs = db.get_session() srvs = dbs.query(db.ServiceStates).filter(db.ServiceStates.type == service) if srvs.count(): return srvs[0].status return db.ServiceStatus.STOPPED
Update the current agent state in opencast.
def update_agent_state(): '''Update the current agent state in opencast. ''' configure_service('capture.admin') status = 'idle' # Determine reported agent state with priority list if get_service_status(db.Service.SCHEDULE) == db.ServiceStatus.STOPPED: status = 'offline' elif get_ser...
Find the best match for the configuration file.
def configuration_file(cfgfile): '''Find the best match for the configuration file. ''' if cfgfile is not None: return cfgfile # If no file is explicitely specified, probe for the configuration file # location. cfg = './etc/pyca.conf' if not os.path.isfile(cfg): return '/etc/...
Update configuration from file.
def update_configuration(cfgfile=None): '''Update configuration from file. :param cfgfile: Configuration file to load. ''' configobj.DEFAULT_INTERPOLATION = 'template' cfgfile = configuration_file(cfgfile) cfg = configobj.ConfigObj(cfgfile, configspec=cfgspec, encoding='utf-8') validator = ...
Check configuration for sanity.
def check(): '''Check configuration for sanity. ''' if config('server')['insecure']: logger.warning('HTTPS CHECKS ARE TURNED OFF. A SECURE CONNECTION IS ' 'NOT GUARANTEED') if config('server')['certificate']: # Ensure certificate exists and is readable open...
Initialize logger based on configuration
def logger_init(): '''Initialize logger based on configuration ''' handlers = [] logconf = config('logging') if logconf['syslog']: handlers.append(logging.handlers.SysLogHandler(address='/dev/log')) if logconf['stderr']: handlers.append(logging.StreamHandler(sys.stderr)) if l...
Serve the status page of the capture agent.
def home(): '''Serve the status page of the capture agent. ''' # Get IDs of existing preview images preview = config()['capture']['preview'] previewdir = config()['capture']['preview_dir'] preview = [p.replace('{{previewdir}}', previewdir) for p in preview] preview = zip(preview, range(len(p...
Serve the preview image with the given id
def serve_image(image_id): '''Serve the preview image with the given id ''' try: preview_dir = config()['capture']['preview_dir'] filepath = config()['capture']['preview'][image_id] filepath = filepath.replace('{{previewdir}}', preview_dir) filepath = os.path.abspath(filepath...
Intercept sigterm and terminate all processes.
def sigterm_handler(signum, frame): '''Intercept sigterm and terminate all processes. ''' sigint_handler(signum, frame) for process in multiprocessing.active_children(): process.terminate() sys.exit(0)
Start all services.
def run_all(*modules): '''Start all services. ''' processes = [multiprocessing.Process(target=mod.run) for mod in modules] for p in processes: p.start() for p in processes: p.join()
Parse Opencast schedule iCalendar file and return events as dict
def parse_ical(vcal): '''Parse Opencast schedule iCalendar file and return events as dict ''' vcal = vcal.replace('\r\n ', '').replace('\r\n\r\n', '\r\n') vevents = vcal.split('\r\nBEGIN:VEVENT\r\n') del(vevents[0]) events = [] for vevent in vevents: event = {} for line in ve...
Try to load schedule from the Matterhorn core. Returns a valid schedule or None on failure.
def get_schedule(): '''Try to load schedule from the Matterhorn core. Returns a valid schedule or None on failure. ''' params = {'agentid': config()['agent']['name'].encode('utf8')} lookahead = config()['agent']['cal_lookahead'] * 24 * 60 * 60 if lookahead: params['cutoff'] = str((timest...
Main loop retrieving the schedule.
def control_loop(): '''Main loop, retrieving the schedule. ''' set_service_status(Service.SCHEDULE, ServiceStatus.BUSY) notify.notify('READY=1') while not terminate(): notify.notify('WATCHDOG=1') # Try getting an updated schedule get_schedule() session = get_session()...
Main loop updating the capture agent state.
def control_loop(): '''Main loop, updating the capture agent state. ''' set_service_status(Service.AGENTSTATE, ServiceStatus.BUSY) notify.notify('READY=1') notify.notify('STATUS=Running') while not terminate(): notify.notify('WATCHDOG=1') update_agent_state() next_update...
Return a response with a jsonapi error object
def make_error_response(error, status=500): ''' Return a response with a jsonapi error object ''' content = { 'errors': [{ 'status': status, 'title': error }] } return make_response(jsonify(content), status)
Return a response with a list of jsonapi data objects
def make_data_response(data, status=200): ''' Return a response with a list of jsonapi data objects ''' content = {'data': ensurelist(data)} return make_response(jsonify(content), status)
Serve a json representation of internal agentstate as meta data
def internal_state(): '''Serve a json representation of internal agentstate as meta data ''' data = {'services': { 'capture': ServiceStatus.str(get_service_status(Service.CAPTURE)), 'ingest': ServiceStatus.str(get_service_status(Service.INGEST)), 'schedule': ServiceStatus.str(get_ser...
Serve a JSON representation of events
def events(): '''Serve a JSON representation of events ''' db = get_session() upcoming_events = db.query(UpcomingEvent)\ .order_by(UpcomingEvent.start) recorded_events = db.query(RecordedEvent)\ .order_by(RecordedEvent.start.desc()) result = [even...
Return a specific events JSON
def event(uid): '''Return a specific events JSON ''' db = get_session() event = db.query(RecordedEvent).filter(RecordedEvent.uid == uid).first() \ or db.query(UpcomingEvent).filter(UpcomingEvent.uid == uid).first() if event: return make_data_response(event.serialize()) return ma...
Delete a specific event identified by its uid. Note that only recorded events can be deleted. Events in the buffer for upcoming events are regularly replaced anyway and a manual removal could have unpredictable effects.
def delete_event(uid): '''Delete a specific event identified by its uid. Note that only recorded events can be deleted. Events in the buffer for upcoming events are regularly replaced anyway and a manual removal could have unpredictable effects. Use ?hard=true parameter to delete the recorded files...
Modify an event specified by its uid. The modifications for the event are expected as JSON with the content type correctly set in the request.
def modify_event(uid): '''Modify an event specified by its uid. The modifications for the event are expected as JSON with the content type correctly set in the request. Note that this method works for recorded events only. Upcoming events part of the scheduler cache cannot be modified. ''' try:...
Extract the set of configuration parameters from the properties attached to the schedule
def get_config_params(properties): '''Extract the set of configuration parameters from the properties attached to the schedule ''' param = [] wdef = '' for prop in properties.split('\n'): if prop.startswith('org.opencastproject.workflow.config'): key, val = prop.split('=', 1)...
Ingest a finished recording to the Opencast server.
def ingest(event): '''Ingest a finished recording to the Opencast server. ''' # Update status set_service_status(Service.INGEST, ServiceStatus.BUSY) notify.notify('STATUS=Uploading') recording_state(event.uid, 'uploading') update_event_status(event, Status.UPLOADING) # Select ingest ser...
Start a capture process but make sure to catch any errors during this process log them but otherwise ignore them.
def safe_start_ingest(event): '''Start a capture process but make sure to catch any errors during this process, log them but otherwise ignore them. ''' try: ingest(event) except Exception: logger.error('Something went wrong during the upload') logger.error(traceback.format_ex...
Main loop of the capture agent retrieving and checking the schedule as well as starting the capture process if necessry.
def control_loop(): '''Main loop of the capture agent, retrieving and checking the schedule as well as starting the capture process if necessry. ''' set_service_status(Service.INGEST, ServiceStatus.IDLE) notify.notify('READY=1') notify.notify('STATUS=Running') while not terminate(): ...
Intercept sigterm and terminate all processes.
def sigterm_handler(signum, frame): '''Intercept sigterm and terminate all processes. ''' if captureproc and captureproc.poll() is None: captureproc.terminate() terminate(True) sys.exit(0)