Load observing mode OB tagger
481090
def load_mode_tagger(obs_mode, node):
    """"""

    # handle tagger:
    ntagger = node.get('tagger')

    if ntagger is None:
        pass
    elif isinstance(ntagger, list):

        def full_tagger(obsres):
            return get_tags_from_full_ob(obsres, reqtags=ntagger)

        obs_mode.tagger = full_tagger
    elif isinstance(ntagger, six.string_types):
        # load function
        obs_mode.tagger = import_object(ntagger)
    else:
        raise TypeError('tagger must be None, a list or a string')

    return obs_mode
289666
def load_obo_file(self, obo_file, optional_attrs, load_obsolete, prt):
        """"""
        reader = OBOReader(obo_file, optional_attrs)

        # Save alt_ids and their corresponding main GO ID. Add to GODag after populating GO Terms
        alt2rec = {}
        for rec in reader:
            # Save record if:
            #   1) Argument load_obsolete is True OR
            #   2) Argument load_obsolete is False and the GO term is "live" (not obsolete)
            if load_obsolete or not rec.is_obsolete:
                self[rec.item_id] = rec
                for alt in rec.alt_ids:
                    alt2rec[alt] = rec

        # Save the typedefs and parsed optional_attrs
        # self.optobj = reader.optobj
        self.typedefs = reader.typedefs

        self._populate_terms(reader.optobj)
        self._set_level_depth(reader.optobj)

        # Add alt_ids to go2obj
        for goid_alt, rec in alt2rec.items():
            self[goid_alt] = rec
        desc = self._str_desc(reader)
        if prt is not None:
            prt.write("{DESC}\n".format(DESC=desc))
        return desc
356528
def retrieve_outputs(self):
        

        metrics = {}
        for obs in self._observers['cv_metrics']:
            metrics[obs.name] = obs.retrieve_metrics()
        self.metrics = metrics
1214429
def check_tags(my_expnum, ops_set, my_ccds, dry_run=True):
    
    tags = storage.get_tags(my_expnum)
    count = 0
    outcount = 0
    fails = []
    for ccd in my_ccds:
      success = True
      count += 1
      for ops in ops_set:
         for fake in ops[0]:
            for my_program in ops[1]:
               for version in ops[2]:
                    #print my_expnum, fake, my_program, version, ccd
                    key = storage.get_process_tag(fake + my_program, ccd, version)
                    uri = storage.tag_uri(key)
                    if "Failed to get image" in tags.get(uri, "Failed to get image"):
                        #print tags.get(uri, None)
                        fails.append(ccd)
                        success = False
      if success:
         outcount += 1
    sys.stderr.write("{} {} {:5.1f}%\n".format(outcount, count,100* float(outcount)/count))
    #print fails
    return set(fails)
1366701
def _set_listener(instance, obs):
    """"""
    if obs.names is everything:
        names = list(instance._props)
    else:
        names = obs.names
    for name in names:
        if name not in instance._listeners:
            instance._listeners[name] = {typ: [] for typ in LISTENER_TYPES}
        instance._listeners[name][obs.mode] += [obs]
1321417
protected void addObserver (Object obs)
    {
        if (_observers == null) {
            _observers = ObserverList.newFastUnsafe();
        }
        _observers.add(obs);
    }
693291
def loadMsbwt(self, dirName, logger):
        '''
        
        '''
        #open the file with our BWT in it
        self.dirName = dirName
        self.bwt = np.load(self.dirName+'/comp_msbwt.npy', 'r')
        
        #build auxiliary structures
        self.constructTotalCounts(logger)
        self.constructIndexing()
        self.constructFMIndex(logger)
445287
def register_click_watcher(self, watcher_name, selectors, *condition_list):
        
        watcher = self.device.watcher(watcher_name)
        for condition in condition_list:
            watcher.when(**self.__unicode_to_dict(condition))
        watcher.click(**self.__unicode_to_dict(selectors))
        self.device.watchers.run()
119423
private static TagList getMonitorTags(Object obj) {
    try {
      Set<Field> fields = getFieldsAnnotatedBy(obj.getClass(), MonitorTags.class);
      for (Field field : fields) {
        field.setAccessible(true);
        return (TagList) field.get(obj);
      }

      Set<Method> methods = getMethodsAnnotatedBy(obj.getClass(), MonitorTags.class);
      for (Method method : methods) {
        method.setAccessible(true);
        return (TagList) method.invoke(obj);
      }
    } catch (Exception e) {
      throw Throwables.propagate(e);
    }

    return null;
  }
332661
def main():
    
    try:
        # A bit of a hack: We want to load the plugins (specified via the mode
        # and health parameter) in order to add their arguments to the argument
        # parser. But this means we first need to look into the CLI arguments
        # to find them ... before looking at the arguments. So we first perform
        # a manual search through the argument list for this purpose only.
        args = sys.argv[1:]

        # Loading the watcher plugin
        mode_name = utils.param_extract(args, "-m", "--mode", default=None)
        if mode_name:
            watcher_plugin_class = \
                load_plugin(mode_name, watcher.WATCHER_DEFAULT_PLUGIN_MODULE)
        else:
            watcher_plugin_class = None

        # Loading the health monitor plugin
        health_check_name = \
            utils.param_extract(args, "-H", "--health",
                                default=monitor.MONITOR_DEFAULT_PLUGIN)
        if health_check_name:
            health_plugin_class = \
                load_plugin(health_check_name,
                            monitor.MONITOR_DEFAULT_PLUGIN_MODULE)
        else:
            health_plugin_class = None

        # Provide complete arg parsing for vpcrouter and all plugin classes.
        conf = _parse_args(sys.argv[1:],
                           watcher_plugin_class, health_plugin_class)

        if not health_plugin_class or not watcher_plugin_class:
            logging.error("Watcher plugin or health monitor plugin class "
                          "are missing.")
            sys.exit(1)

        _setup_logging(conf)

        # If we are on an EC2 instance then some data is already available to
        # us. The return data items in the meta data match some of the command
        # line arguments, so we can pass this through to the parser function to
        # provide defaults for those parameters. Specifically: VPC-ID and
        # region name.
        if not conf['vpc_id'] or not conf['region_name']:
            meta_data = get_ec2_meta_data()
            if 'vpc_id' not in meta_data or 'region_name' not in meta_data:
                logging.error("VPC and region were not explicitly specified "
                              "and can't be auto-discovered.")
                sys.exit(1)
            else:
                conf.update(meta_data)

        try:
            info_str = "vpc-router (%s): mode: %s (%s), " \
                       "health-check: %s (%s)" % \
                       (vpcrouter.__version__,
                        conf['mode'], watcher_plugin_class.get_version(),
                        health_check_name, health_plugin_class.get_version())
            logging.info("*** Starting %s ***" % info_str)
            CURRENT_STATE.versions = info_str

            http_srv = http_server.VpcRouterHttpServer(conf)
            CURRENT_STATE._vpc_router_http = http_srv

            watcher.start_watcher(conf,
                                  watcher_plugin_class, health_plugin_class)
            http_srv.stop()
            logging.info("*** Stopping vpc-router ***")
        except Exception as e:
            import traceback
            traceback.print_exc()
            logging.error(e.message)
            logging.error("*** Exiting")
    except Exception as e:
        print "\n*** Error: %s\n" % e.message

    sys.exit(1)
555638
@SuppressWarnings("unchecked")
  static <T> Monitor<T> wrap(TagList tags, Monitor<T> monitor) {
    Monitor<T> m;
    if (monitor instanceof CompositeMonitor<?>) {
      m = new CompositeMonitorWrapper<>(tags, (CompositeMonitor<T>) monitor);
    } else {
      m = MonitorWrapper.create(tags, monitor);
    }
    return m;
  }
638076
function (o, cb) {
    try {
      var reader = new FileReader();
      reader.onload = function (event) {
        cb && cb(reader.result);
      };
      reader.readAsText(o);
    } catch (error) {
      throw error
    }
  }
22977
def _batch_call_watchers(self_):
        
        while self_.self_or_cls.param._events:
            event_dict = OrderedDict([((event.name, event.what), event)
                                      for event in self_.self_or_cls.param._events])
            watchers = self_.self_or_cls.param._watchers[:]
            self_.self_or_cls.param._events = []
            self_.self_or_cls.param._watchers = []

            for watcher in watchers:
                events = [self_._update_event_type(watcher, event_dict[(name, watcher.what)],
                                                   self_.self_or_cls.param._TRIGGER)
                          for name in watcher.parameter_names
                          if (name, watcher.what) in event_dict]
                with batch_watch(self_.self_or_cls, run=False):
                    if watcher.mode == 'args':
                        watcher.fn(*events)
                    else:
                        watcher.fn(**{c.name:c.new for c in events})
234946
private function _loadObservers()
  {
    $class = $this->name();
    $name = self::_configName($class);
    $config = Config::getInstance($name);
    
    $this->_observers = $config->valueOf();
  }
131226
def read_tags(fh, byteorder, offsetsize, tagnames, customtags=None,
              maxifds=None):
    
    if offsetsize == 4:
        offsetformat = byteorder+'I'
        tagnosize = 2
        tagnoformat = byteorder+'H'
        tagsize = 12
        tagformat1 = byteorder+'HH'
        tagformat2 = byteorder+'I4s'
    elif offsetsize == 8:
        offsetformat = byteorder+'Q'
        tagnosize = 8
        tagnoformat = byteorder+'Q'
        tagsize = 20
        tagformat1 = byteorder+'HH'
        tagformat2 = byteorder+'Q8s'
    else:
        raise ValueError('invalid offset size')

    if customtags is None:
        customtags = {}
    if maxifds is None:
        maxifds = 2**32

    result = []
    unpack = struct.unpack
    offset = fh.tell()
    while len(result) < maxifds:
        # loop over IFDs
        try:
            tagno = unpack(tagnoformat, fh.read(tagnosize))[0]
            if tagno > 4096:
                raise TiffFileError('suspicious number of tags')
        except Exception:
            log.warning('read_tags: corrupted tag list at offset %i', offset)
            break

        tags = {}
        data = fh.read(tagsize * tagno)
        pos = fh.tell()
        index = 0
        for _ in range(tagno):
            code, type_ = unpack(tagformat1, data[index:index+4])
            count, value = unpack(tagformat2, data[index+4:index+tagsize])
            index += tagsize
            name = tagnames.get(code, str(code))
            try:
                dtype = TIFF.DATA_FORMATS[type_]
            except KeyError:
                raise TiffFileError('unknown tag data type %i' % type_)

            fmt = '%s%i%s' % (byteorder, count * int(dtype[0]), dtype[1])
            size = struct.calcsize(fmt)
            if size > offsetsize or code in customtags:
                offset = unpack(offsetformat, value)[0]
                if offset < 8 or offset > fh.size - size:
                    raise TiffFileError('invalid tag value offset %i' % offset)
                fh.seek(offset)
                if code in customtags:
                    readfunc = customtags[code][1]
                    value = readfunc(fh, byteorder, dtype, count, offsetsize)
                elif type_ == 7 or (count > 1 and dtype[-1] == 'B'):
                    value = read_bytes(fh, byteorder, dtype, count, offsetsize)
                elif code in tagnames or dtype[-1] == 's':
                    value = unpack(fmt, fh.read(size))
                else:
                    value = read_numpy(fh, byteorder, dtype, count, offsetsize)
            elif dtype[-1] == 'B' or type_ == 7:
                value = value[:size]
            else:
                value = unpack(fmt, value[:size])

            if code not in customtags and code not in TIFF.TAG_TUPLE:
                if len(value) == 1:
                    value = value[0]
            if type_ != 7 and dtype[-1] == 's' and isinstance(value, bytes):
                # TIFF ASCII fields can contain multiple strings,
                #   each terminated with a NUL
                try:
                    value = bytes2str(stripascii(value).strip())
                except UnicodeDecodeError:
                    log.warning(
                        'read_tags: coercing invalid ASCII to bytes (tag %i)',
                        code)

            tags[name] = value

        result.append(tags)
        # read offset to next page
        fh.seek(pos)
        offset = unpack(offsetformat, fh.read(offsetsize))[0]
        if offset == 0:
            break
        if offset >= fh.size:
            log.warning('read_tags: invalid page offset (%i)', offset)
            break
        fh.seek(offset)

    if result and maxifds == 1:
        result = result[0]
    return result
1167738
function Thumbnailer (opts) {
  // for the benefit of testing
  // perform dependency injection.
  _.extend(this, {
    tmp: require('tmp'),
    logger: require(config.get('logger'))
  }, opts)
}
732964
def oboTermParser(filepath):
    
    with io.open(filepath) as openfile:
        lineIter = iter([i.rstrip() for i in openfile.readlines()])

    #Iterate through lines until the first obo "[Term]" is encountered
    try:
        line = next(lineIter)
        while line != '[Term]':
            line = next(lineIter)
        header = line #Remove
        entryLines = list()
    except StopIteration:
        errorText = 'File does not contain obo "[Term]" entries.'
        raise maspy.errors.FileFormatError(errorText)

    for line in lineIter:
        #Skip empty lines between entries
        if not line:
            continue
        if line == '[Term]':
            yield entryLines
            header = line #Remove
            entryLines = list()
        else:
            entryLines.append(line)

    #Yield last entry
    if entryLines:
        yield entryLines