Search is not available for this dataset
text
stringlengths
75
104k
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=...
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 ...
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...
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"). ...
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,...
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)
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(...
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...
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 -...
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...
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...
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...
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...
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...
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...
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)]
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...
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...
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...
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(...
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 ------- ...
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...
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(...
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) # ...
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): ...
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...
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...
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...
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...
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 _...
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 ...
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...
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,...
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 """ ...
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( ...
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...
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 ...
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...
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...
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...
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('_', ' ')
def remaining_duration(self, time): '''Returns the remaining duration for a recording. ''' return max(0, self.end - max(self.start, time))
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, ...
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 ...
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...
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
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
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...
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...
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...
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()
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()
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
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...
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/...
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 = ...
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...
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...
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...
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...
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)
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()
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...
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...
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()...
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...
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)
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)
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...
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...
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...
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...
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:...
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)...
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...
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...
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(): ...
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)
def start_capture(upcoming_event): '''Start the capture process, creating all necessary files and directories as well as ingesting the captured files if no backup mode is configured. ''' logger.info('Start recording') # First move event to recording_event table db = get_session() event = db...
def safe_start_capture(event): '''Start a capture process but make sure to catch any errors during this process, log them but otherwise ignore them. ''' try: start_capture(event) except Exception: logger.error('Recording failed') logger.error(traceback.format_exc()) #...
def recording_command(event): '''Run the actual command to record the a/v material. ''' conf = config('capture') # Prepare command line cmd = conf['command'] cmd = cmd.replace('{{time}}', str(event.remaining_duration(timestamp()))) cmd = cmd.replace('{{dir}}', event.directory()) cmd = cm...
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.CAPTURE, ServiceStatus.IDLE) notify.notify('READY=1') notify.notify('STATUS=Waiting') while not terminate(): ...
def render_to_fragment(self, request, **kwargs): """ Returns a simple fragment """ fragment = Fragment(TEST_HTML) fragment.add_javascript(TEST_JS) fragment.add_css(TEST_CSS) return fragment
def resources(self): """ Returns list of unique `FragmentResource`s by order of first appearance. """ seen = set() # seen.add always returns None, so 'not seen.add(x)' is always True, # but will only be called if the value is not already in seen (because # 'and' s...
def to_dict(self): """ Returns the fragment in a dictionary representation. """ return { 'content': self.content, 'resources': [r._asdict() for r in self.resources], # pylint: disable=W0212 'js_init_fn': self.js_init_fn, 'js_init_version':...
def from_dict(cls, pods): """ Returns a new Fragment from a dictionary representation. """ frag = cls() frag.content = pods['content'] frag._resources = [FragmentResource(**d) for d in pods['resources']] # pylint: disable=protected-access frag.js_init_fn = pods['...
def add_content(self, content): """ Add content to this fragment. `content` is a Unicode string, HTML to append to the body of the fragment. It must not contain a ``<body>`` tag, or otherwise assume that it is the only content on the page. """ assert isinstance(...
def add_resource(self, text, mimetype, placement=None): """ Add a resource needed by this Fragment. Other helpers, such as :func:`add_css` or :func:`add_javascript` are more convenient for those common types of resource. `text`: the actual text of this resource, as a unicode st...
def add_resource_url(self, url, mimetype, placement=None): """ Add a resource by URL needed by this Fragment. Other helpers, such as :func:`add_css_url` or :func:`add_javascript_url` are more convenent for those common types of resource. `url`: the URL to the resource. ...
def initialize_js(self, js_func, json_args=None): """ Register a Javascript function to initialize the Javascript resources. `js_func` is the name of a Javascript function defined by one of the Javascript resources. As part of setting up the browser's runtime environment, the f...
def resources_to_html(self, placement): """ Get some resource HTML for this Fragment. `placement` is "head" or "foot". Returns a unicode string, the HTML for the head or foot of the page. """ # - non url js could be wrapped in an anonymous function # - non url c...
def resource_to_html(resource): """ Returns `resource` wrapped in the appropriate html tag for it's mimetype. """ if resource.mimetype == "text/css": if resource.kind == "text": return u"<style type='text/css'>\n%s\n</style>" % resource.data elif r...
def get(self, request, *args, **kwargs): """ Render a fragment to HTML or return JSON describing it, based on the request. """ fragment = self.render_to_fragment(request, **kwargs) response_format = request.GET.get('format') or request.POST.get('format') or 'html' if resp...
def render_standalone_response(self, request, fragment, **kwargs): # pylint: disable=unused-argument """ Renders a standalone page as a response for the specified fragment. """ if fragment is None: return HttpResponse(status=204) html = self.render_to_standalone_htm...
def render_to_standalone_html(self, request, fragment, **kwargs): # pylint: disable=unused-argument """ Render the specified fragment to HTML for a standalone page. """ template = get_template(STANDALONE_TEMPLATE_NAME) context = { 'head_html': fragment.head_html(), ...
def calc(pvalues, lamb): """ meaning pvalues presorted i descending order""" m = len(pvalues) pi0 = (pvalues > lamb).sum() / ((1 - lamb)*m) pFDR = np.ones(m) print("pFDR y Pr fastPow") for i in range(m): y = pvalues[i] Pr = max(1, m - i) / float(m) pFDR[i]...
def unwrap_self_for_multiprocessing(arg): """ You can not call methods with multiprocessing, but free functions, If you want to call inst.method(arg0, arg1), unwrap_self_for_multiprocessing(inst, "method", (arg0, arg1)) does the trick. """ (inst, method_name, args) = arg r...
def to_one_dim_array(values, as_type=None): """ Converts list or flattens n-dim array to 1-dim array if possible """ if isinstance(values, (list, tuple)): values = np.array(values, dtype=np.float32) elif isinstance(values, pd.Series): values = values.values values = values.flatten() ...
def lookup_values_from_error_table(scores, err_df): """ Find matching q-value for each score in 'scores' """ ix = find_nearest_matches(np.float32(err_df.cutoff.values), np.float32(scores)) return err_df.pvalue.iloc[ix].values, err_df.svalue.iloc[ix].values, err_df.pep.iloc[ix].values, err_df.qvalue.iloc[ix]...
def posterior_chromatogram_hypotheses_fast(experiment, prior_chrom_null): """ Compute posterior probabilities for each chromatogram For each chromatogram (each group_id / peptide precursor), all hypothesis of all peaks being correct (and all others false) as well as the h0 (all peaks are false) are com...