Read a DICOM file and perform some initial
        parsing of tags.

        NB!
        For thread safety, class member variables
        should not be assigned since other threads
        might override/change these variables in mid-
        flight!
320838
def DICOMfile_read(self, *args, **kwargs):
        
        b_status        = False
        l_tags          = []
        l_tagsToUse     = []
        d_tagsInString  = {}
        str_file        = ""

        d_DICOM           = {
            'dcm':              None,
            'd_dcm':            {},
            'strRaw':           '',
            'l_tagRaw':         [],
            'd_json':           {},
            'd_dicom':          {},
            'd_dicomSimple':    {}
        }

        for k, v in kwargs.items():
            if k == 'file':             str_file    = v
            if k == 'l_tagsToUse':      l_tags      = v

        if len(args):
            l_file          = args[0]
            str_file        = l_file[0]

        str_localFile   = os.path.basename(str_file)
        str_path        = os.path.dirname(str_file)
        # self.dp.qprint("%s: In input base directory:      %s" % (threading.currentThread().getName(), self.str_inputDir))
        # self.dp.qprint("%s: Reading DICOM file in path:   %s" % (threading.currentThread().getName(),str_path))
        # self.dp.qprint("%s: Analysing tags on DICOM file: %s" % (threading.currentThread().getName(),str_localFile))      
        # self.dp.qprint("%s: Loading:                      %s" % (threading.currentThread().getName(),str_file))

        try:
            # self.dcm    = dicom.read_file(str_file)
            d_DICOM['dcm']  = dicom.read_file(str_file)
            b_status    = True
        except:
            self.dp.qprint('In directory: %s' % os.getcwd(),    comms = 'error')
            self.dp.qprint('Failed to read %s' % str_file,      comms = 'error')
            b_status    = False
        d_DICOM['d_dcm']    = dict(d_DICOM['dcm'])
        d_DICOM['strRaw']   = str(d_DICOM['dcm'])
        d_DICOM['l_tagRaw'] = d_DICOM['dcm'].dir()

        if len(l_tags):
            l_tagsToUse     = l_tags
        else:
            l_tagsToUse     = d_DICOM['l_tagRaw']

        if 'PixelData' in l_tagsToUse:
            l_tagsToUse.remove('PixelData')

        for key in l_tagsToUse:
            d_DICOM['d_dicom'][key]       = d_DICOM['dcm'].data_element(key)
            try:
                d_DICOM['d_dicomSimple'][key] = getattr(d_DICOM['dcm'], key)
            except:
                d_DICOM['d_dicomSimple'][key] = "no attribute"
            d_DICOM['d_json'][key]        = str(d_DICOM['d_dicomSimple'][key])

        # pudb.set_trace()
        d_tagsInString  = self.tagsInString_process(d_DICOM, self.str_outputFileStem)
        str_outputFile  = d_tagsInString['str_result']

        return {
            'status':           b_status,
            'inputPath':        str_path,
            'inputFilename':    str_localFile,
            'outputFileStem':   str_outputFile,
            'd_DICOM':          d_DICOM,
            'l_tagsToUse':      l_tagsToUse
        }
214504
def tag(self, tag, child='', enclose=0, newline=True, **kwargs):
        
        kw = kwargs.copy()
        _class = ''
        if '_class' in kw:
            _class = kw.pop('_class')
        if 'class' in kw:
            _class += ' ' + kw.pop('class')
        tag_class = self.tag_class.get(tag, '')
        if tag_class:
            #if tag_class definition starts with '+', and combine it with original value
            if tag_class.startswith('+'):
                kw['class'] = tag_class[1:] + ' ' + _class.lstrip()
            else:
                kw['class'] = tag_class.lstrip()
        else:
            kw['class'] = _class.lstrip()
            
        #process inner and outter link
        if tag == 'a':
            print ('------', kw)
            href = kw.get('href', '#')
            if href and (href.startswith('http:') or href.startswith('https:') or href.startswith('ftp:')):
                _cls = 'outter'
            else:
                _cls = 'inner'
                kw['href'] = href
            if kw.get('class'):
                kw['class'] = kw['class'] + ' ' + _cls
            else:
                kw['class'] = _cls
            
        attrs = ' '.join(['%s="%s"' % (x, y) for x, y in sorted(kw.items()) if y])
        if attrs:
            attrs = ' ' + attrs
        nline = '\n' if newline else ''
        if child:
            enclose = 2
        if enclose == 1:
            return '<%s%s/>%s' % (tag, attrs, nline)
        elif enclose == 2:
            return '<%s%s>%s</%s>%s' % (tag, attrs, child, tag, nline)
        else:
            return '<%s%s>%s' % (tag, attrs, nline)
560437
def parse_input_file(text, variables=None):
    
    text = find_includes(text)
    lines = text.splitlines()
    tasks, linenumbers = find_tasks(lines)
    preamble = [line for line in lines[:linenumbers[0]]]
    logging.debug("Preamble:\n{}".format("\n".join(preamble)))
    if variables is not None:
        preamble += "\n" + "\n".join(variables)
    environment = create_environment(preamble)
    code_sections = []
    for n in range(len(linenumbers) - 1):
        code_sections.append((linenumbers[n], linenumbers[n+1]))
    for n, task in zip(code_sections, tasks):
        task["code"] = lines[n[0]: n[1]]
        task["environment"] = environment
    clean_tasks = []
    for task in tasks:
        clean_tasks.append(Task(**task))
    return clean_tasks
1365390
def read_uic4tag(fh, byteorder, dtype, planecount, offsetsize):
    """"""
    assert dtype == '1I' and byteorder == '<'
    result = {}
    while True:
        tagid = struct.unpack('<H', fh.read(2))[0]
        if tagid == 0:
            break
        name, value = read_uic_tag(fh, tagid, planecount, offset=False)
        result[name] = value
    return result
567732
def _read_tags(self):
        
        tags = self._config.get('tags', {})
        logging.info('Tags:')
        for tag_name in tags.keys():
            tag = {}
            tag['Key'] = tag_name
            tag['Value'] = tags[tag_name]
            self._tags.append(tag)
            logging.info('{} = {}'.format(tag_name, tags[tag_name]))

        logging.debug(json.dumps(
            self._tags,
            indent=2,
            sort_keys=True
        ))
        return True
798143
private void parseClass()
    throws IOException
  {
    int magic = readInt();

    if (magic != JavaClass.MAGIC)
      throw error(L.l("bad magic number in class file"));

    int minor = readShort();
    int major = readShort();

    _class.setMajor(major);
    _class.setMinor(minor);

    parseConstantPool();

    int accessFlags = readShort();
    _class.setAccessFlags(accessFlags);

    int thisClassIndex = readShort();
    _class.setThisClass(_cp.getClass(thisClassIndex).getName());
    
    int superClassIndex = readShort();
    if (superClassIndex > 0)
      _class.setSuperClass(_cp.getClass(superClassIndex).getName());

    int interfaceCount = readShort();
    for (int i = 0; i < interfaceCount; i++) {
      int classIndex = readShort();

      _class.addInterface(_cp.getClass(classIndex).getName());
    }

    int fieldCount = readShort();
    for (int i = 0; i < fieldCount; i++) {
      parseField();
    }

    int methodCount = readShort();
    for (int i = 0; i < methodCount; i++)
      parseMethod();

    int attrCount = readShort();
    for (int i = 0; i < attrCount; i++) {
      Attribute attr = parseAttribute();

      _class.addAttribute(attr);
    }
  }
237846
def _fromfile(self, parent):
        """"""
        fd = parent._fd
        byte_order = parent.byte_order

        self._offset = fd.tell()
        self.value_offset = self._offset + parent.offset_size + 4

        fmt, size = {4: ('HHI4s', 12), 8: ('HHQ8s', 20)}[parent.offset_size]
        data = fd.read(size)
        code, dtype = struct.unpack(byte_order + fmt[:2], data[:4])
        count, value = struct.unpack(byte_order + fmt[2:], data[4:])

        if code in TIFF_TAGS:
            name = TIFF_TAGS[code][0]
        elif code in CUSTOM_TAGS:
            name = CUSTOM_TAGS[code][0]
        else:
            name = str(code)

        try:
            dtype = TIFF_DATA_TYPES[dtype]
        except KeyError:
            raise ValueError("unknown TIFF tag data type %i" % dtype)

        fmt = '%s%i%s' % (byte_order, count*int(dtype[0]), dtype[1])
        size = struct.calcsize(fmt)
        if size > parent.offset_size or code in CUSTOM_TAGS:
            pos = fd.tell()
            tof = {4: 'I', 8: 'Q'}[parent.offset_size]
            self.value_offset = struct.unpack(byte_order+tof, value)[0]
            fd.seek(self.value_offset)
            if code in CUSTOM_TAGS:
                readfunc = CUSTOM_TAGS[code][1]
                value = readfunc(fd, byte_order, dtype, count)
                fd.seek(0, 2)  # bug in numpy/Python 3.x ?
                if isinstance(value, dict):  # numpy.core.records.record
                    value = Record(value)
            elif code in TIFF_TAGS or dtype[-1] == 's':
                value = struct.unpack(fmt, fd.read(size))
            else:
                value = read_numpy(fd, byte_order, dtype, count)
                fd.seek(0, 2)  # bug in numpy/Python 3.x ?
            fd.seek(pos)
        else:
            value = struct.unpack(fmt, value[:size])

        if not code in CUSTOM_TAGS:
            if len(value) == 1:
                value = value[0]

        if dtype.endswith('s'):
            value = stripnull(value)

        self.code = code
        self.name = name
        self.dtype = dtype
        self.count = count
        self.value = value
460527
void readClass(ClassSymbol c) {
        ClassType ct = (ClassType)c.type;

        // allocate scope for members
        c.members_field = new Scope(c);

        // prepare type variable table
        typevars = typevars.dup(currentOwner);
        if (ct.getEnclosingType().hasTag(CLASS))
            enterTypevars(ct.getEnclosingType());

        // read flags, or skip if this is an inner class
        long flags = adjustClassFlags(nextChar());
        if (c.owner.kind == PCK) c.flags_field = flags;

        // read own class name and check that it matches
        ClassSymbol self = readClassSymbol(nextChar());
        if (c != self)
            throw badClassFile("class.file.wrong.class",
                               self.flatname);

        // class attributes must be read before class
        // skip ahead to read class attributes
        int startbp = bp;
        nextChar();
        char interfaceCount = nextChar();
        bp += interfaceCount * 2;
        char fieldCount = nextChar();
        for (int i = 0; i < fieldCount; i++) skipMember();
        char methodCount = nextChar();
        for (int i = 0; i < methodCount; i++) skipMember();
        readClassAttrs(c);

        if (readAllOfClassFile) {
            for (int i = 1; i < poolObj.length; i++) readPool(i);
            c.pool = new Pool(poolObj.length, poolObj, types);
        }

        // reset and read rest of classinfo
        bp = startbp;
        int n = nextChar();
        if (ct.supertype_field == null)
            ct.supertype_field = (n == 0)
                ? Type.noType
                : readClassSymbol(n).erasure(types);
        n = nextChar();
        List<Type> is = List.nil();
        for (int i = 0; i < n; i++) {
            Type _inter = readClassSymbol(nextChar()).erasure(types);
            is = is.prepend(_inter);
        }
        if (ct.interfaces_field == null)
            ct.interfaces_field = is.reverse();

        Assert.check(fieldCount == nextChar());
        for (int i = 0; i < fieldCount; i++) enterMember(c, readField());
        Assert.check(methodCount == nextChar());
        for (int i = 0; i < methodCount; i++) enterMember(c, readMethod());

        typevars = typevars.leave();
    }
993244
private TagCIObject getTagCFObject(TagCIObject defaultValue) {
	if (_comp != null) return _comp;

	// first look for main
	Iterator<Statement> it = getStatements().iterator();
	Statement s;
	TagCIObject t, sub = null;

	while (it.hasNext()) {
	    s = it.next();
	    if (s instanceof TagCIObject) {
		t = (TagCIObject) s;
		if (t.isMain()) return _comp = t;
		else if (sub == null) sub = t;
	    }
	}
	if (sub != null) return _comp = sub;
	return defaultValue;
    }
989364
def as_tag(value)
      case true
      when value.tag?
        element(value) ? value : nil
      when value.dicom_name?
        get_tag(value)
      when value.dicom_method?
        get_tag(@names_from_methods[value.to_sym])
      else
        nil
      end
    end
4019
def _doc_parse(doc, module=None, qualname=None):
    

    # Build the rex
    known_tags = {
        'param': 'arg',
        'type': 'arg-type',
        'return': 'ret',
        'returns': 'ret',
        'rtype': 'ret-type',
        'exception': 'exc',
        'except': 'exc',
        'raise': 'exc',
        'raises': 'exc',
    }
    tag_rex = re.compile(r'^\s*:(' + '|'.join(map(re.escape, known_tags)) + r')\s*(\S+)?\s*:', re.MULTILINE)

    # Match tags
    collect_args = {}
    collect_ret = {}
    doc_args = []
    doc_exc = []
    for m in reversed(list(tag_rex.finditer(doc))):
        # Fetch data
        tag, arg = m.groups()
        tag = known_tags[tag]  # Normalized tag name

        # Fetch docstring part
        value = doc[m.end():].strip()  # Copy text after the tag
        doc = doc[:m.start()].strip()  # truncate the string

        # Handle tag: collect data
        if tag == 'exc':
            doc_exc.append(data.ExceptionDoc(arg, value))
        elif tag in ('ret', 'ret-type'):
            # Collect fields 1 by 1
            collect_ret[{'ret': 'doc', 'ret-type': 'type'}[tag]] = value
        elif tag in ('arg', 'arg-type'):
            # Init new collection
            if arg not in collect_args:
                doc_args.append(arg)  # add name for now, then map() replace with classes
                collect_args[arg] = {}
            # Collect fields 1 by 1
            collect_args[arg][{'arg': 'doc', 'arg-type': 'type'}[tag]] = value
        else:
            raise AssertionError('Unknown tag type: {}'.format(tag))

    # Merge collected data
    doc_ret = data.ValueDoc(**collect_ret) if collect_ret else None
    doc_args = map(lambda name: data.ArgumentDoc(name=name, **collect_args[name]), collect_args)

    # Finish
    return data.FDocstring(module=module, qualname=qualname, doc=doc, args=doc_args, exc=doc_exc, ret=doc_ret)
217747
public void readTags(InputStream tagsXML)
    {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        try
        {
            SAXParser saxParser = factory.newSAXParser();
            saxParser.parse(tagsXML, new TagsSaxHandler(this));
        }
        catch (ParserConfigurationException | SAXException | IOException ex)
        {
            throw new RuntimeException("Failed parsing the tags definition: " + ex.getMessage(), ex);
        }
    }
529772
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
        GetField fields = in.readFields();
        beginDefaultContext = fields.get(BEGIN_DEFAULT, true);

        // Note that further processing is required in JEEMetadataContextProviderImpl.deserializeThreadContext
        // in order to re-establish the thread context based on the metadata identity if not defaulted.
    }
1085847
@Trivial
    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
        final boolean trace = TraceComponent.isAnyTracingEnabled();
        if (trace && tc.isEntryEnabled())
            Tr.entry(this, tc, "readObject");

        GetField fields = in.readFields();
        initialDelay = fields.get(INITIAL_DELAY, -1l);
        interval = fields.get(INTERVAL, -1l);
        isFixedRate = fields.get(IS_FIXED_RATE, false);
        nonserTaskClassName = (String) fields.get(NONSER_TASK_CLASS_NAME, null);
        nonserTriggerClassName = (String) fields.get(NONSER_TRIGGER_CLASS_NAME, null);
        submittedAsCallable = fields.get(SUBMITTED_AS_CALLABLE, false);
        threadContextBytes = (byte[]) fields.get(THREAD_CONTEXT_DESCRIPTOR, null);

        if (trace && tc.isEntryEnabled())
            Tr.exit(this, tc, "readObject", new Object[] {
                                                          nonserTaskClassName,
                                                          nonserTriggerClassName,
                                                          "initial delay " + initialDelay,
                                                          "interval " + interval,
                                                          isFixedRate ? "fixed rate" : false,
                                                          submittedAsCallable ? "callable" : "runnable",
                                                          threadContextBytes == null ? null : threadContextBytes.length
            });
    }
304385
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
        in.defaultReadObject();
        // ICU 4.8 custom deserialization.
        String languageTag = (String)in.readObject();
        ulocale = ULocale.forLanguageTag(languageTag);
        MessagePattern.ApostropheMode aposMode = (MessagePattern.ApostropheMode)in.readObject();
        if (msgPattern == null || aposMode != msgPattern.getApostropheMode()) {
            msgPattern = new MessagePattern(aposMode);
        }
        String msg = (String)in.readObject();
        if (msg != null) {
            applyPattern(msg);
        }
        // custom formatters
        for (int numFormatters = in.readInt(); numFormatters > 0; --numFormatters) {
            int formatIndex = in.readInt();
            Format formatter = (Format)in.readObject();
            setFormat(formatIndex, formatter);
        }
        // skip future (int, Object) pairs
        for (int numPairs = in.readInt(); numPairs > 0; --numPairs) {
            in.readInt();
            in.readObject();
        }
    }
1277789
def parse_file(self, filename=None, buffer=None, fileobj=None):
        """"""
        if filename:
            self.file = GzipFile(filename, 'rb')
        elif buffer:
            if hasattr(buffer, 'name'):
                self.filename = buffer.name
            self.file = buffer
        elif fileobj:
            if hasattr(fileobj, 'name'):
                self.filename = fileobj.name
            self.file = GzipFile(fileobj=fileobj)
        if self.file:
            try:
                type = TAG_Byte(buffer=self.file)
                if type.value == self.id:
                    name = TAG_String(buffer=self.file).value
                    self._parse_buffer(self.file)
                    self.name = name
                    self.file.close()
                else:
                    raise MalformedFileError(
                        "First record is not a Compound Tag")
            except StructError as e:
                raise MalformedFileError(
                    "Partial File Parse: file possibly truncated.")
        else:
            raise ValueError(
                "NBTFile.parse_file(): Need to specify either a "
                "filename or a file object"
            )
1102859
def Read(self, file_object):
    
    config_parser = configparser.RawConfigParser()
    # pylint: disable=deprecated-method
    # TODO: replace readfp by read_file, check if Python 2 compatible
    config_parser.readfp(file_object)

    for section_name in config_parser.sections():
      dependency_definition = DependencyDefinition(section_name)
      for value_name in self._VALUE_NAMES:
        value = self._GetConfigValue(config_parser, section_name, value_name)
        setattr(dependency_definition, value_name, value)

      yield dependency_definition