Run ChemDataExtractor on a document.
975311
def extract(ctx, input, output):
    """"""
    log.info('chemdataextractor.extract')
    log.info('Reading %s' % input.name)
    doc = Document.from_file(input, fname=input.name)
    records = [record.serialize(primitive=True) for record in doc.records]
    jsonstring = json.dumps(records, indent=2, ensure_ascii=False)
    output.write(jsonstring)
141196
def run(args):
    
    regex_extractor = RegexExtractor(pattern=args.pattern)

    with warnings.catch_warnings():
        warnings.simplefilter('ignore')

        for line in args.input_file:
            extractions = regex_extractor.extract(line)
            for e in extractions:
                print(e.value)
612321
def prepare_gold(ctx, annotations, gout):
    """"""
    click.echo('chemdataextractor.chemdner.prepare_gold')
    for line in annotations:
        pmid, ta, start, end, text, category = line.strip().split('\t')
        gout.write('%s\t%s:%s:%s\n' % (pmid, ta, start, end))
1293307
def mols_from_file(path, no_halt=True, assign_descriptors=True):
    """"""
    with open(path, 'rb') as f:
        fd = (tx.decode(line) for line in f)
        for c in mol_supplier(fd, no_halt, assign_descriptors):
            yield c
428847
public void run()
    {
        if ((m_url == null) && (m_strHtmlText == null))
        {   // restore the original cursor
            if (m_bChangeCursor)
            {
                if (m_applet != null)
                    m_applet.setStatus(0, m_editorPane, m_oldCursor);
                else
                {
                	Component component = m_editorPane;
                	while (component.getParent() != null)
                	{
                		component = component.getParent();
                	}
                    component.setCursor((Cursor)m_oldCursor);
                }
                Container parent = m_editorPane.getParent();
                parent.repaint();
            }
        }
        else
        {
            if (m_bChangeCursor)
            {
                if (m_applet != null)
                    m_oldCursor = m_applet.setStatus(Cursor.WAIT_CURSOR, m_editorPane, null);
                else
                {
                	Component component = m_editorPane;
                	boolean bIsVisible = true;
                	while (component.getParent() != null)
                	{
                		component = component.getParent();
                		if (!component.isVisible())
                			bIsVisible = false;
                	}
                	m_oldCursor = component.getCursor();
                    Cursor cursor = Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR);
                    if (bIsVisible)
                    	component.setCursor(cursor);
                }
            }
            
            synchronized (m_editorPane)
            {
                Document doc = m_editorPane.getDocument();
                try {
                    if (m_url != null) {
                        m_editorPane.setPage(m_url);
                    } else {
                    	this.setText(doc, m_strHtmlText);
                    }
                } catch (IOException ioe) {
                	String error = ioe.getLocalizedMessage();
                	if ((error != null)
                		&& (error.length() > 0))
                	{
                		String errorText = m_strHtmlErrorText;
                		if (errorText == null)
                			errorText = DEFAULT_ERROR_TEXT;
                		errorText = MessageFormat.format(errorText, m_url.toString(), error);
                    	this.setText(doc, errorText);
                	}
                	else
                		m_editorPane.setDocument(doc);
                    // getToolkit().beep();
                } finally {
                    // schedule the cursor to revert after
                    // the paint has happened.
                    m_url = null;
                    m_strHtmlText = null;
                    if (m_bChangeCursor)
                        SwingUtilities.invokeLater(this);
                }
            }
        }
    }
1360416
private void handleDocument(EntityDocument document) {
		if (document instanceof ItemDocument) {
			this.entityDocumentProcessor
					.processItemDocument((ItemDocument) document);
		} else if (document instanceof PropertyDocument) {
			this.entityDocumentProcessor
					.processPropertyDocument((PropertyDocument) document);
		} else if(document instanceof LexemeDocument) {
			this.entityDocumentProcessor
					.processLexemeDocument((LexemeDocument) document);
		}
	}
655001
def run(self):
        """"""

        # Create a set of excluded reactions
        exclude = set(self._args.exclude)
        count = 0
        unbalanced = 0
        unchecked = 0
        for reaction, result in formula_balance(self._model):
            count += 1

            if reaction.id in exclude or reaction.equation is None:
                continue

            if result is None:
                unchecked += 1
                continue

            left_form, right_form = result
            if right_form != left_form:
                unbalanced += 1
                right_missing, left_missing = Formula.balance(
                    right_form, left_form)

                print('{}\t{}\t{}\t{}\t{}'.format(
                    reaction.id, left_form, right_form,
                    left_missing, right_missing))

        logger.info('Unbalanced reactions: {}/{}'.format(unbalanced, count))
        logger.info('Unchecked reactions due to missing formula: {}/{}'.format(
            unchecked, count))
        logger.info('Reactions excluded from check: {}/{}'.format(
            len(exclude), count))
259146
def cueExtractAndRun(args, file):
    
    filename = file['file_path']
    if args['execute']:
        holla = run(filename)
    else:
        holla = run(filename, True)
    return holla
556300
def train(ctx, output, corpus, clusters):
    """"""
    click.echo('chemdataextractor.pos.train')
    click.echo('Output: %s' % output)
    click.echo('Corpus: %s' % corpus)
    click.echo('Clusters: %s' % clusters)

    wsj_sents = []
    genia_sents = []

    if corpus == 'wsj' or corpus == 'wsj+genia':
        wsj_sents = list(wsj_training.tagged_sents())
        # For WSJ, remove all tokens with -NONE- tag
        for i, wsj_sent in enumerate(wsj_sents):
            wsj_sents[i] = [t for t in wsj_sent if not t[1] == '-NONE-']

    if corpus == 'genia' or corpus == 'wsj+genia':
        genia_sents = list(genia_training.tagged_sents())
        # Translate GENIA
        for i, genia_sent in enumerate(genia_sents):
            for j, (token, tag) in enumerate(genia_sent):
                if tag == '(':
                    genia_sents[i][j] = (token, '-LRB-')  # ( to -RLB- (also do for evaluation)
                elif tag == ')':
                    genia_sents[i][j] = (token, '-RRB-')  # ) to -RRB- (also do for evaluation)
                elif tag == 'CT':
                    genia_sents[i][j] = (token, 'DT')  # Typo?
                elif tag == 'XT':
                    genia_sents[i][j] = (token, 'DT')  # Typo?
                elif tag == '-':
                    genia_sents[i][j] = (token, ':')  # Single hyphen character for dash
                elif tag == 'N':
                    genia_sents[i][j] = (token, 'NN')  # Typo?
                elif tag == 'PP':
                    genia_sents[i][j] = (token, 'PRP')  # Typo?
                elif tag == '' and token == ')':
                    genia_sents[i][j] = (token, '-RRB-')  # Typo?
                elif tag == '' and token == 'IFN-gamma':
                    genia_sents[i][j] = (token, 'NN')  # Typo?
                elif '|' in tag:
                    genia_sents[i][j] = (token, tag.split('|')[0])  # If contains |, choose first part
            # Filter any tags not in the allowed tagset (Shouldn't be any left anyway)
            genia_sents[i] = [t for t in genia_sent if t[1] in TAGS]

    if corpus == 'wsj':
        training_corpus = wsj_sents
    elif corpus == 'genia':
        training_corpus = genia_sents
    elif corpus == 'wsj+genia':
        training_corpus = wsj_sents + genia_sents
    else:
        raise click.ClickException('Invalid corpus')

    tagger = ChemCrfPosTagger(clusters=clusters)
    tagger.train(training_corpus, output)
407476
def run(self):
        """"""
        if not self.state.document.settings.file_insertion_enabled:
            raise self.warning('"%s" directive disabled.' % self.name)
        source = self.state_machine.input_lines.source(
            self.lineno - self.state_machine.input_offset - 1)
        source_dir = os.path.dirname(os.path.abspath(source))

        path = directives.path(self.arguments[0])
        path = os.path.normpath(os.path.join(source_dir, path))
        path = utils.relative_path(None, path)
        path = nodes.reprunicode(path)

        encoding = self.options.get(
            'encoding', self.state.document.settings.input_encoding)
        e_handler = self.state.document.settings.input_encoding_error_handler
        tab_width = self.options.get(
            'tab-width', self.state.document.settings.tab_width)

        try:
            self.state.document.settings.record_dependencies.add(path)
            include_file = io.FileInput(source_path=path,
                                        encoding=encoding,
                                        error_handler=e_handler)
        except UnicodeEncodeError as error:
            raise self.severe('Problems with "%s" directive path:\n'
                              'Cannot encode input file path "%s" '
                              '(wrong locale?).' %
                              (self.name, SafeString(path)))
        except IOError as error:
            raise self.severe('Problems with "%s" directive path:\n%s.' %
                              (self.name, ErrorString(error)))
        startline = self.options.get('start-line', None)
        endline = self.options.get('end-line', None)
        try:
            if startline or (endline is not None):
                lines = include_file.readlines()
                rawtext = ''.join(lines[startline:endline])
            else:
                rawtext = include_file.read()
        except UnicodeError as error:
            raise self.severe('Problem with "%s" directive:\n%s' %
                              (self.name, ErrorString(error)))

        include_lines = statemachine.string2lines(rawtext, tab_width,
                                                  convert_whitespace=True)

        # default lexer to 'text'
        lexer = self.options.get('lexer', 'text')

        self.options['source'] = path
        codeblock = Pygments(self.name,
                             [lexer],  # arguments
                             {},  # no options for this directive
                             include_lines,  # content
                             self.lineno,
                             self.content_offset,
                             self.block_text,
                             self.state,
                             self.state_machine)
        return codeblock.run()
354602
def run():
    """"""
    obj = CompareGOsCli()
    obj.write(obj.kws.get('xlsx'), obj.kws.get('ofile'), obj.kws.get('verbose', False))
897692
def run_script(pycode):
    """"""
    # Fix up the whitespace in pycode.
    if pycode[0] == "\n":
        pycode = pycode[1:]
    pycode.rstrip()
    pycode = textwrap.dedent(pycode)

    # execute it.
    globs = {}
    six.exec_(pycode, globs, globs)  # pylint: disable=W0122

    return globs
766311
def run(config, path=None, stop_on_error=True, just_tests=False):
    """"""
    if path is None:
        path = os.getcwd()
    prep(config, path=path)

    models = __import__('models')
    tests = __import__('tests')
    suites = __import__('suites')

    print('\n')
    for x in ['models', 'tests', 'suites']:
        module = __import__(x)
        assert hasattr(module, x), "'%s' module requires attribute '%s'" %\
                                   (x, x)

    if just_tests:
        for test in tests.tests:
            _run(test, models, stop_on_error)

    else:
        for suite in suites.suites:
            _run(suite, models, stop_on_error)
1229492
def list(ctx):
    """"""
    log.debug('chemdataextractor.data.list')
    click.echo('Downloaded\tPackage')
    for package in PACKAGES:
        click.echo('%s\t%s' % (package.local_exists(), package.path))
229339
def prepare_tokens(ctx, input, annotations, tout, lout):
    """"""
    click.echo('chemdataextractor.chemdner.prepare_tokens')
    # Collect the annotations into a dict
    anndict = defaultdict(list)
    for line in annotations:
        pmid, ta, start, end, text, category = line.strip().split('\t')
        anndict[(pmid, ta)].append((int(start), int(end), text))
    # Process the corpus
    for line in input:
        pmid, title, abstract = line.strip().split(u'\t')
        for t, section, anns in [(Title(title), 'T', anndict.get((pmid, u'T'), [])), (Paragraph(abstract), u'A', anndict.get((pmid, u'A'), []))]:
            # Write our tokens with POS and IOB tags
            tagged = _prep_tags(t, anns)
            for i, sentence in enumerate(tagged):
                tout.write(u' '.join([u'/'.join([token, tag, label]) for token, tag, label in sentence]))
                lout.write(u' '.join([u'/'.join([token, label]) for token, tag, label in sentence]))
                tout.write(u'\n')
                lout.write(u'\n')
            tout.write(u'\n')
            lout.write(u'\n')
1211231
def run(data):
    """"""
    name = dd.get_sample_name(data)
    in_bam = dd.get_transcriptome_bam(data)
    config = data['config']
    if not in_bam:
        logger.info("Transcriptome-mapped BAM file not found, skipping eXpress.")
        return data
    out_dir = os.path.join(dd.get_work_dir(data), "express", name)
    out_file = os.path.join(out_dir, name + ".xprs")
    express = config_utils.get_program("express", data['config'])
    strand = _set_stranded_flag(in_bam, data)
    if not file_exists(out_file):
        gtf_fasta = gtf.gtf_to_fasta(dd.get_gtf_file(data), dd.get_ref_file(data))
        with tx_tmpdir(data) as tmp_dir:
            with file_transaction(data, out_dir) as tx_out_dir:
                bam_file = _prepare_bam_file(in_bam, tmp_dir, config)
                cmd = ("{express} --no-update-check -o {tx_out_dir} {strand} {gtf_fasta} {bam_file}")
                do.run(cmd.format(**locals()), "Run express on %s." % in_bam, {})
            shutil.move(os.path.join(out_dir, "results.xprs"), out_file)
    eff_count_file = _get_column(out_file, out_file.replace(".xprs", "_eff.counts"), 7, data=data)
    tpm_file = _get_column(out_file, out_file.replace("xprs", "tpm"), 14, data=data)
    fpkm_file = _get_column(out_file, out_file.replace("xprs", "fpkm"), 10, data=data)
    data = dd.set_express_counts(data, eff_count_file)
    data = dd.set_express_tpm(data, tpm_file)
    data = dd.set_express_fpkm(data, fpkm_file)
    return data
881959
public function run() 
	{
		if ($this->documentor) {
			$this->documentor->setMethodData( $this->methods );
		}
		$request_xml = file_get_contents( 'php://input' );
		if ( !$request_xml ) 
		{
			if ( ( $query = $_SERVER['QUERY_STRING'] ) 
				&& isset($this->wsdl[$query]) && $this->wsdl[$query] )
			{
				header('Content-type: text/xml');
				header('Access-Control-Allow-Origin: *');
				echo $this->wsdl[$query];
			}
			else if ( $this->documentor )
			{
				header('Content-type: text/html; charset=' . $this->outputOptions['encoding']);
				$this->documentor->handle( $this, $this->methods );
			}
			else
			{
				// FIXME: add check for json-rpc protocol, if set and none of the xml protocols are set, use that
				header('Content-type: text/xml');
				header('Access-Control-Allow-Origin: *');
				echo xmlrpc_encode_request(
					null,  
					ripcord::fault( -1, 'No request xml found.' ),
					$this->outputOptions
				);
			}
		}
		else 
		{
			// FIXME: add check for the protocol of the request, could be json-rpc, then check if it is supported.
			header('Content-type: text/xml');
			header('Access-Control-Allow-Origin: *');
			echo $this->handle( $request_xml );
		}
	}