text:
from __future__ import division

__author__ = "Jon Sanders"
__copyright__ = "Copyright 2014, Jon Sanders"
__credits__ = ["Jon Sanders"]
__license__ = "GPL"
__version__ = "1.9.1"
__maintainer__ = "Jon Sanders"
__email__ = "jonsan@gmail.com"
__status__ = "Development"

from qiime.util import load_qiime_config, parse_command_line_parameters,\
    get_options_lookup, make_option
from qiime.parse import parse_qiime_parameters, parse_taxonomy, parse_mapping_file_to_dict
from qiime.filter import sample_ids_from_metadata_description
from bfillings.uclust import get_clusters_from_fasta_filepath
from bfillings.usearch import usearch_qf

from decontaminate import *

from biom import load_table

import os
import numpy as np

options_lookup = get_options_lookup()
script_info = {}
script_info['brief_description'] = """
A script to filter sequences by potential contaminants"""
script_info['script_description'] = """
This script performs a series of filtering steps on a sequence file with the
intent of removing contaminant sequences. It requires input of an OTU table, a
sample map, an OTU map, a sequence FASTA file, and an output directory.

There are two primary approaches the script can take: (1) comparing sequence
abundances in blank control sequence libraries to those in sample libraries,
where sequences present in blanks are presumed to be contaminants, and (2)
comparing sequences in sample libraries to a database of known contaminants.

In approach (1), OTUs (or unique sequences, if OTU table and map are defined at
100% identity) are tested for their maximum and mean presence in blank and
sample libraries, and excluded if they satisfy the given criteria. For example,
if you want to exclude any sequences whose maximum abundance in a blank sample
is more than 10% the maximum abundance in a sample (maxB > 0.1 * maxS), you
would choose '--removal_stat_blank maxB --removal_stat_sample maxS
--removal_differential 0.1'. For this approach, you must also provide a column
in your mapping file that indicates which samples to use as blanks, and pass
this information to the script with the 'valid states' option (e.g.
'Blank:True')

In approach (2), you must provide a fasta library of putative contaminants.
These may be previously clustered OTUs from the blank samples, commonly
sequenced contaminants (if known), or another fasta file. Sequences will be
clustered against this fasta file using Uclust-Ref, and any that match within
a given percent similarity (using the '-c' or '--contaminant_similarity' option)
will be marked as putative contaminants.

When using approach (2), it is possible to remove 'real' sequences from samples
that just happen to be similar to contaminants. This may be detectable when
using unique sequence OTU tables/maps as input, if the 'real' sequences are
nonetheless slightly different from contaminants. In this case, it may be
desireable to reinstate those unique sequences that are present in samples but
not in blanks. You may do this using criteria of relative abundance (similar to
approach [1], where a sequence is reinstated if its max presence in a sample is
greater than its max presence in a blank, i.e. maxS > X * maxB) or of incidence
in non-blank samples (i.e. reinstated if present in two or more samples). If
both criteria are provided, you must choose to reinstate either the intersection
of the criteria (i.e. BOTH more abundant in samples AND present in 2 or more)
or the union (i.e. EITHER more abundant in samples OR present in 2 or more).
"""
script_info['script_usage'] = []
script_info['script_usage'].append(("""Example:""", """
The following steps are performed by the command below:

1. Calculate max relative abundance of each sequence in samples and blanks

2. Identify sequences whose maximum abunance in blanks is more than 10% their
maximum abundance in samples.

3. Output OTU maps of sequences for which above is true, and for which above is
false.
""", """
decontaminate.py -i unique_seqs_otu_table.biom -o filter_out_dir
-m metadata_mapping_file.txt -f unique_seqs_rep_set.fna
-M unique_seqs_otus.txt -s 'Blank:True' --removal_stat_blank maxB
--removal_stat_sample maxS --removal_differential 0.1
"""))
script_info['output_description'] = """
This script will output a tab-delimited summary table, indicating the relative
abundance stats for each sequence considered, along with its fate at each step
of the process.

It will also output an OTU map for each category of sequences identified (e.g.
those never identified as contaminants, those identified as reference-based
contaminants, those identified as abundance-based contaminants, and those
reinstated). These OTU maps can then be used to filter in the input FASTA file.

Output file naming:
contamination_summary.txt -- tab-delimited per-sequence summary file
assed_otu_map.txt -- OTU map of non-contaminant sequences
ref_contaminants_otu_map.txt -- OTU map of reference contaminant sequences
abund_contaminants_otu_map.txt -- OTU map of abundance contaminant sequences
reinstated_contaminants_otu_map.txt -- OTU map of reinstated sequences
"""
script_info['required_options'] = [
    options_lookup["output_dir"]
    ]
script_info['optional_options'] = [
    options_lookup["otu_table_as_primary_input"],
    make_option('--mothur_counts_fp',
                type='existing_filepath',
                help='path to mothur counts table as input'),
    options_lookup["mapping_fp"],
    make_option('-M', '--otu_map_fp', type="existing_filepath",
                 help='the input OTU map file'),
    make_option('-s',
                '--valid_states', type='string',
                help="Column header:value pair in mapping file identifying blank samples"),
    make_option('--blank_id_fp',
                type='existing_filepath',
                help='path to file listing blank sample ids'),
    options_lookup["input_fasta"],
    make_option('--contaminant_db_fp', type="existing_filepath",
              help='A FASTA file of potential contaminant sequences'),
    make_option('-c', '--contaminant_similarity', type='float', default=0.97,
                help=('Sequence similarity threshold for contaminant matches')),
    make_option('-r', '--max_correlation', type='float',
                help=('Maximum Spearman correlation for contaminant identification')),
    make_option('--correlate_header', type='string',
                help=('Column header in mapping file with correlation data')),
    make_option('--min_relabund_threshold', type="float",
                help='discard sequences below this relative abundance threshold'),
    make_option('--prescreen_threshold', type="float",
                help='prescreen libraries that lose more than this proportion of sequences'),
    make_option('--removal_stat_blank', type="choice", choices=["maxB", "avgB", "quantile"],
                 help='blank statistic to be used for removal (maxB, avgB, quantile)'),
    make_option('--removal_stat_sample', type="choice", choices=["maxS", "avgS", "quantile"],
                 help='sample statistic to be used for removal (maxS, avgS, quantile)'),
    make_option('--qB', type="float", default=80,
                 help='Blank quantile to be used for removal [0-100, default = %default]'),
    make_option('--qS', type="float", default=80,
                 help='Sample quantile to be used for removal [0-100, default = %default]'),
    make_option('--interpolation', type="choice", default='nearest',
                 choices=['linear', 'lower', 'higher', 'midpoint', 'nearest'],
                 help='Interpolation to be used for quantiles [default=%default]'),
    make_option('--removal_differential', type="float",
                 help='differential proportion for removal (maxB > X * maxS)'),
    make_option('--reinstatement_stat_blank', type="choice", choices=["maxB", "avgB"],
                 help='blank statistic to be used for reinstatement (maxB, avgB)'),
    make_option('--reinstatement_stat_sample', type="choice", choices=["maxS", "avgS"],
                 help='sample statistic to be used for reinstatement (maxS, avgS)'),
    make_option('--reinstatement_differential', type="float",
                 help='differential proportion for reinstatement (maxS > X * maxB)'),
    make_option('--reinstatement_sample_number', type="int",
                 help='minimum number of samples necessary for reinstatement'),
    make_option('--reinstatement_method', type="choice", choices=["union", "intersection"],
                 help='method to rectify reinstatement criteria'),
    make_option('--drop_lib_threshold', type="float",
                 help='read loss threshold to drop libraries from output table'),
    make_option('--write_filtered_output', action="store_true",
                 help='write an output table filtered of contaminants'),
    make_option('--write_per_library_stats', action="store_true",
                 help='write a per-library decontamination summary'),
    make_option('--write_per_seq_stats', action="store_true",
                 help='write a per-sequence decontamination summary'),
    make_option('--write_per_seq_disposition', action="store_true",
                 help='write a per-sequence disposition file'),
    make_option('--write_output_seq_lists', action="store_true",
                 help='write separate sequence name lists for each contaminant category')

    ]

script_info['version'] = __version__

def main():
    option_parser, opts, args = parse_command_line_parameters(**script_info)
    otu_table_fp = opts.otu_table_fp
    mothur_counts_fp = opts.mothur_counts_fp
    mapping_fp = opts.mapping_fp
    valid_states = opts.valid_states
    blank_id_fp = opts.blank_id_fp
    contaminant_db_fp = opts.contaminant_db_fp
    contaminant_similarity = opts.contaminant_similarity
    max_correlation = opts.max_correlation
    correlate_header = opts.correlate_header
    input_fasta_fp = opts.input_fasta_fp
    otu_map_fp = opts.otu_map_fp
    output_dir = opts.output_dir
    min_relabund_threshold = opts.min_relabund_threshold
    prescreen_threshold = opts.prescreen_threshold
    removal_stat_blank = opts.removal_stat_blank
    removal_stat_sample = opts.removal_stat_sample
    qB = opts.qB
    qS = opts.qS
    interpolation = opts.interpolation
    removal_differential = opts.removal_differential
    reinstatement_stat_sample = opts.reinstatement_stat_sample
    reinstatement_stat_blank = opts.reinstatement_stat_blank
    reinstatement_differential = opts.reinstatement_differential
    reinstatement_sample_number = opts.reinstatement_sample_number
    reinstatement_method = opts.reinstatement_method
    write_output_seq_lists = opts.write_output_seq_lists
    write_filtered_output = opts.write_filtered_output
    drop_lib_threshold = opts.drop_lib_threshold
    write_per_seq_stats = opts.write_per_seq_stats
    write_per_library_stats = opts.write_per_library_stats
    write_per_seq_disposition = opts.write_per_seq_disposition

    # Make unique seq OTU table (biom file)

    # Compute unique seq stats
    #   output biom file with unique seq stats

    # Optionally: make candidate contaminant DB
    #   remove sequences present at higher abundance in samples
    #   cluster blanks
    #   remove low-abundance contaminant OTUs

    # Filter by similarity against candidate contaminant DB
    #   annotate unique seq OTU table with top hit (OTU#, rep seq, ID%)
    #   make list of seqs @ threshold

    # Calculate reinstatement rule for filtered sequences

    # Generate lists of seqs failing:
    #   - unique seq rule
    #   - hit to contaminant
    #   - reinstatement after hit

    # Make sure passed at least one of an OTU biom or mothur counts table file
    input_file_counter = 0

    if mothur_counts_fp:
        input_file_counter += 1
        unique_seq_biom = mothur_counts_to_biom(open(mothur_counts_fp,'Ur'))
        mothur_output = True
        print "mothur input"

    if otu_table_fp:
        input_file_counter += 1
        unique_seq_biom = load_table(otu_table_fp)
        mothur_output = False
        print "BIOM input"

    if input_file_counter != 1:
        option_parser.error("must provide ONLY ONE of an OTU table biom file or"
                            "mothur counts table")

    # Get rid of OTUs with no observations, if present
    unique_seq_biom.filter(
            lambda val, id_, metadata: val.sum() <= 0,
            axis='observation', invert=True, inplace=True)

    # Check to make sure that if blank-based contamination filtering requested,
    # all necessary options are specified:

    removal_options_counter = 0
    if removal_stat_blank:
        removal_options_counter += 1
    if removal_stat_sample:
        removal_options_counter += 1
    if removal_differential:
        removal_options_counter += 1

    if removal_stat_blank == 'quantile':
        removal_stat_blank = 'q%sB' % qB
    if removal_stat_sample == 'quantile':
        removal_stat_sample = 'q%sS' % qS

    if ((removal_options_counter > 0) and (removal_options_counter < 3)):
        option_parser.error("Must provide all of "
                            "removal_stats_blank, "
                            "removal_stat_sample, and "
                            "removal_differential, or none.")
    elif removal_options_counter == 0:
        blank_stats_removal = False
    elif removal_options_counter == 3:
        blank_stats_removal = True

    # If reference-based filtering requested, make sure all necessary options
    # have been specified:

    if contaminant_db_fp and not input_fasta_fp:
        option_parser.error("If specifying ref-based contaminant ID, must "
                            "also specify path to input sequence fasta")
    elif contaminant_db_fp and input_fasta_fp:
        ref_removal = True
    else:
        ref_removal = False

    # If correlation-based filtering requested, make sure correlate data
    # are specified

    if max_correlation and not (correlate_header and mapping_fp):
        option_parser.error("If specifying maximum Spearman correlation, must "
                           "also provide map column header for correlate data")
    elif max_correlation and correlate_header and mapping_fp:
        corr_removal = True
    else:
        corr_removal = False

    # Make sure at least one contaminant filtering method is supplied:

    if not (blank_stats_removal or ref_removal or corr_removal):
        option_parser.error("Must supply at least one valid contamination "
                            "identification method")

    # If sequence reinstatement is requested, make sure all necessary options
    # are specified

    reinstatement_options_counter = 0
    if reinstatement_stat_blank:
        reinstatement_options_counter += 1
    if reinstatement_stat_sample:
        reinstatement_options_counter += 1
    if reinstatement_differential:
        reinstatement_options_counter += 1

    if ((reinstatement_options_counter > 0) and
        (reinstatement_options_counter < 3)):
        option_parser.error("Must provide all of "
                            "reinstatement_stats_blank, "
                            "reinstatement_stat_sample, and "
                            "reinstatement_differential, or none.")

    if ((reinstatement_options_counter == 3 and reinstatement_sample_number)
        and not reinstatement_method):
        option_parser.error("If providing sample number AND abundance criteria "
                            "for sequence reinstatement, must also provide "
                            "a method for combining results.")

    if reinstatement_options_counter == 3 or reinstatement_sample_number:
        reinstatement = True
    else:
        reinstatement = False

    # get blank sample IDs from mapping file or sample ID list

    if mapping_fp and valid_states:
        blank_sample_ids = sample_ids_from_metadata_description(
            open(mapping_fp, 'U'), valid_states)
        blanks = True
    elif blank_id_fp is not None:
        blank_id_f = open(blank_id_fp, 'Ur')
        blank_sample_ids = set([line.strip().split()[0]
                                for line in blank_id_f
                                if not line.startswith('#')])
        blank_id_f.close()
        blanks = True
    else:
        blanks = False

    # Initialize output objets

    output_dict = {}
    contaminant_types = []

    contamination_stats_dict = None
    contamination_stats_header = None
    corr_data_dict = None

    # Do blank-based stats calculations, if not there check to make sure no
    # blank-dependent methods are requested:

    if blanks:
        contamination_stats_header, contamination_stats_dict = \
                get_contamination_stats(unique_seq_biom,
                                        qS=qS,
                                        qB=qB,
                                        interpolation=interpolation,
                                        blank_sample_ids=blank_sample_ids)

        if prescreen_threshold:
            low_contam_libraries = prescreen_libraries(unique_seq_biom,
                                                       contamination_stats_header,
                                                       contamination_stats_dict,
                                                       removal_stat_sample,
                                                       removal_stat_blank,
                                                       removal_differential,
                                                       prescreen_threshold)

            contamination_stats_header, contamination_stats_dict = \
                get_contamination_stats(unique_seq_biom,
                                        qS=qS,
                                        qB=qB,
                                        interpolation=interpolation,
                                        blank_sample_ids=blank_sample_ids,
                                        exp_sample_ids=low_contam_libraries)

    elif (blank_stats_removal or reinstatement or prescreen_threshold):
        option_parser.error("Blank-based filtering requested but no blank"
                            "samples indicated in mapping file or ID file.")
    else:
        contamination_stats_header, contamination_stats_dict = \
            get_contamination_stats(unique_seq_biom,
                                    qS=qS,
                                    qB=qB,
                                    interpolation=interpolation)

    seq_ids = unique_seq_biom.ids(axis='observation')

    # Do blank-based contaminant identification

    if min_relabund_threshold:
        output_dict['below_relabund_threshold'] = pick_min_relabund_threshold(
                                                  contamination_stats_dict,
                                                  contamination_stats_header,
                                                  min_relabund_threshold)

    if blank_stats_removal:
        output_dict['abund_contaminants'] = compare_blank_abundances(contamination_stats_dict,
                                contamination_stats_header,
                                removal_stat_sample,
                                removal_stat_blank,
                                removal_differential,
                                negate=True)

        contaminant_types.append('abund_contaminants')

    # Do reference-based contaminant identification

    if contaminant_db_fp:
        output_dict['ref_contaminants'] = pick_ref_contaminants(seq_ids, contaminant_db_fp, input_fasta_fp, contaminant_similarity, output_dir)

        contaminant_types.append('ref_contaminants')

    # Do spearman correlation based contaminant identification

    if max_correlation:
        metadata_dict = parse_mapping_file_to_dict(open(mapping_fp, 'U'))[0]

        corr_data_dict = {x: float(metadata_dict[x][correlate_header]) for x in metadata_dict}

        output_dict['corr_contaminants'], corr_contaminant_dict = pick_corr_contaminants(unique_seq_biom,
                                                   corr_data_dict,
                                                   max_correlation)

        contaminant_types.append('corr_contaminants')
    else:
        corr_contaminant_dict = None

    # Putative contaminants are those that have been identified by any method

    output_dict['putative_contaminants'] = set.union(*map(set, [output_dict[x] for x in contaminant_types]))

    # If considering low abundance sequences, remove those from consideration as potential contaminants

    if 'below_relabund_threshold' in output_dict:
        output_dict['putative_contaminants'] = output_dict['putative_contaminants'] - set(output_dict['below_relabund_threshold'])

    # Pick abundance-criterion seqs to reinstate

    if (reinstatement_stat_blank and reinstatement_stat_sample and reinstatement_differential):
        output_dict['abund_reinstated_seqs'] = reinstate_abund_seqs(output_dict['putative_contaminants'],
                     contamination_stats_dict,
                     contamination_stats_header,
                     reinstatement_stat_sample,
                     reinstatement_stat_blank,
                     reinstatement_differential)

        output_dict['reinstated_seqs'] = output_dict['abund_reinstated_seqs']

    # Pick incidence-criterion seqs to reinstate
    if reinstatement_sample_number:
        output_dict['incidence_reinstated_seqs'] = reinstate_incidence_seqs(
                     output_dict['putative_contaminants'],
                     unique_seq_biom,
                     blank_sample_ids,
                     reinstatement_sample_number)

        output_dict['reinstated_seqs'] = output_dict['incidence_reinstated_seqs']

    # combine incidence and abundance reinstatements
    if reinstatement_sample_number and reinstatement_stat_blank:
        if reinstatement_method == "union":
            output_dict['reinstated_seqs'] = output_dict['abund_reinstated_seqs'] | output_dict['incidence_reinstated_seqs']
        elif reinstatement_method == "intersection":
            output_dict['reinstated_seqs'] = output_dict['abund_reinstated_seqs'] & output_dict['incidence_reinstated_seqs']

    # make sets for sequence _never_ identified as contaminants:

    output_dict['ever_good_seqs'] = set(seq_ids) - output_dict['putative_contaminants']

    # If considering low abundance sequences, remove those from consideration as potential contaminants

    if 'below_relabund_threshold' in output_dict:
        output_dict['ever_good_seqs'] = output_dict['ever_good_seqs'] - set(output_dict['below_relabund_threshold'])

    # Make set of good seqs for final filtering

    final_good_seqs = output_dict['ever_good_seqs']

    # ...and those either never ID'd as contaminants or reinstated:
    if reinstatement:
        output_dict['all_good_seqs'] = set(output_dict['ever_good_seqs'] | output_dict['reinstated_seqs'])
        final_good_seqs = output_dict['all_good_seqs']
        # ...and those who remain contaminants after reinstatement:
        output_dict['never_good_seqs'] = set(output_dict['putative_contaminants'] - output_dict['reinstated_seqs'])

    # print filtered OTU maps if given a QIIME OTU map input

    if otu_map_fp:
        print_filtered_output('otu_map', otu_map_fp, output_dir, output_dict)

    # print filtered Mothur counts tables if given a Mothur counts table input

    if mothur_output:
        print_filtered_output('mothur_counts', mothur_counts_fp, output_dir, output_dict)

    # print filtered seq header files if requested

    if write_output_seq_lists:
        print_filtered_output('seq_headers', seq_ids, output_dir, output_dict)

    # filter final biom file to just good seqs

    filtered_biom = unique_seq_biom.filter(lambda val, id_, metadata: id_ in final_good_seqs,
                     axis='observation', invert=False, inplace=False)

    # drop heavily contaminated libraries if requested

    if drop_lib_threshold:
        dropped_libs = unique_seq_biom.norm(inplace=False).filter(lambda val, id_, metadata: id_ in final_good_seqs,
                 axis='observation', invert=False, inplace=False).filter(lambda val, id_, metadata: sum(val) >= drop_lib_threshold,
                 axis='sample', invert=True, inplace=False).ids(axis='sample')
        filtered_biom.filter(lambda val, id_, metadata: id_ in dropped_libs,
                 axis='sample', invert=True, inplace=True)
    else:
        dropped_libs = []

    # print filtered biom/mothur_output if library filtering is requested

    if write_filtered_output:

        if mothur_output:
            output_counts_string = biom_to_mothur_counts(filtered_biom)
            with open(os.path.join(output_dir,'decontaminated_table.counts'), "w") as output_counts_file:
                output_counts_file.write(output_counts_string)
        else:
            output_biom_string = filtered_biom.to_json('Filtered by decontaminate.py')
            output_biom_string
            with open(os.path.join(output_dir,'decontaminated_otu_table.biom'), "w") as output_biom_file:
                output_biom_file.write(output_biom_string)

    # print per-library stats if requested

    if write_per_library_stats:
        per_library_stats, per_library_stats_header = calc_per_library_decontam_stats(unique_seq_biom, output_dict)
        library_stats_string = print_per_library_stats(per_library_stats, per_library_stats_header, unique_seq_biom.ids(axis='sample'), dropped_libs=dropped_libs)

        with open(os.path.join(output_dir,'decontamination_per_library_stats.txt'), "w") as output_stats_file:
            output_stats_file.write(library_stats_string)

    # print otu by disposition file if requested

    if write_per_seq_disposition:
        per_seq_disposition = print_otu_disposition(seq_ids, output_dict)

        with open(os.path.join(output_dir,'decontamination_per_otu_disposition.txt'), "w") as output_stats_file:
            output_stats_file.write(per_seq_disposition)

    # print log file / per-seq info
    if write_per_seq_stats:
        print_results_file(seq_ids,
                       output_dict,
                       os.path.join(output_dir,'contamination_summary.txt'),
                       contamination_stats_header,
                       contamination_stats_dict,
                       corr_contaminant_dict)

if __name__ == "__main__":
    main()


text:
Changelog
---------

### 1.0.8
- Fix an error where the destination streams were ended prematurely [#27](https://github.com/peerigon/phridge/issues/27)

### 1.0.7
- Fix memory leak when disposing pages [#21](https://github.com/peerigon/phridge/pull/21)
- Fix confusing security warning when PhantomJS exits

### 1.0.6
- Fix potential performance issues when PhantomJS' stdin was cluttered with messages

### 1.0.5
- `phantom.childProcess.cleanStdout` now implements the regular Readable interface

### 1.0.4
- Improve performance when running synchronous functions

### 1.0.3
- Fix an error where new line characters where removed from `console.log()`-messages inside PhantomJS

### 1.0.2
- Fix an error where a promise could have been rejected after it has already been resolved

### 1.0.1
- Improved stack traces from PhantomJS

### 1.0.0
- Replaced inter-process communication from HTTP to regular stdin/stdout
- `Phantom.prototype.port` has been removed
- `Phantom.prototype.secret` has been removed
- `config.minPort` has been removed
- `config.maxPort` has been removed
- Improved performance
- Reached stable state :)

redpajama_set_name: RedPajamaGithub


text:
package com.woniukeji.jianguo.eventbus;

/**
 * Created by invinjun on 2015/10/12.
 */
public class HeadImgEvent {
    public String ImgUrl;
}


text:
FROM       docker.ocular8.net/base
MAINTAINER jake@300brand.net

RUN        apt-get install -y mysql-server

ADD        mysqld.cnf /etc/mysql/conf.d/mysqld.cnf
RUN        chmod 0664 /etc/mysql/conf.d/mysqld.cnf
ADD        mysql_setup.sh /root/mysql_setup.sh
RUN        chmod +x /root/mysql_setup.sh
RUN        /root/mysql_setup.sh
ADD        mysql.conf /etc/supervisor/conf.d/mysql.conf
EXPOSE     3306


text:
/*globals define*/
/*jshint node:true, browser:true*/

/**
 * Author: Dana Zhang
 * Created on: October 31, 2015
 */

define(['common/util/ejs',
        'plugin/SysMLExporter/SysMLExporter/Templates/Templates',
        './SysMLExporterConstants'], function (ejs, TEMPLATES, CONSTANTS) {

    'use strict';

    var SequenceDiagramExporter = function () {
    };

    SequenceDiagramExporter.prototype.addComponent = function (nodeObj) {

        var self = this,
            core = self.core,
            gmeID = core.getPath(nodeObj),
            baseClass = self.getMetaType(nodeObj),
            type = core.getAttribute(baseClass, 'name'),
            name = core.getAttribute(nodeObj, 'name'),
            xPos = core.getRegistry(nodeObj, 'position').x,
            yPos = core.getRegistry(nodeObj, 'position').y,
            element,
            parentPath = core.getPath(core.getParent(nodeObj)),
            diagramKey = parentPath + "+" + core.getAttribute(nodeObj.parent, 'name');

        self.idLUT[gmeID] = {id: self.modelID};
        self.reverseIdLUT[self.modelID] = gmeID;

        element = {
            name: name,
            id: self.modelID,
            x: xPos,
            y: yPos,
            type: type
        };

        if (self.isMetaTypeOf(baseClass, self.META.LifeLine) || self.isMetaTypeOf(baseClass, self.META.LostMessage)) {
            if (!self.sequenceDiagrams.hasOwnProperty(diagramKey)) {
                self.sequenceDiagrams[diagramKey] = {};
            }
            if (!self.sequenceDiagrams[diagramKey].hasOwnProperty('elements')) {
                self.sequenceDiagrams[diagramKey].elements = [];
            }
            self.sequenceDiagrams[diagramKey].elements.push(element);
            self.modelID += 1;
        } else if (self.isMetaTypeOf(baseClass, self.META.ExecutionSpecification)) {

        }
    };

    SequenceDiagramExporter.prototype.addConnection = function (nodeObj, callback) {

        var self = this,
            core = self.core,
            parentPath = core.getPath(core.getParent(nodeObj)),
            diagramKey = parentPath + "+" + core.getAttribute(nodeObj.parent, 'name'),
            src = core.getPointerPath(nodeObj, "src"),
            dst = core.getPointerPath(nodeObj, "dst"),
            type = core.getAttribute(self.getMetaType(nodeObj), 'name'),
            counter = 2,
            error = '',
            pushUseCaseLink,
            afterSrcLoaded,
            afterDstLoaded,
            srcMetaType,
            dstMetaType,
            srcX,
            srcY,
            dstX,
            dstY,
            srcName,
            dstName,
            srcId,
            dstId;

        pushUseCaseLink = function (err, shouldPush) {
            var link;
            if (err) {
                error += err;
                shouldPush = false;
            }
            counter -= 1;
            if (counter === 0) {
                if (error) {
                    callback(error);
                    return;
                }
                if (shouldPush) {

                    link = {
                        id: self.modelID,
                        src: self.idLUT[src].id,
                        srcName: srcName,
                        dstName: dstName,
                        dst: self.idLUT[dst].id,
                        type: type,
                        points: {
                            src: {
                                x: 1, //srcX,
                                y: 0.5 //srcY
                            },
                            dst: {
                                x: 0, //dstX,
                                y: 0.5 //dstY
                            }
                        }
                    };

                    if (!self.sequenceDiagrams.hasOwnProperty(diagramKey)) {
                        self.sequenceDiagrams[diagramKey] = {};
                    }
                    if (!self.sequenceDiagrams[diagramKey].hasOwnProperty('links')) {
                        self.sequenceDiagrams[diagramKey].links = [];
                    }
                    self.sequenceDiagrams[diagramKey].links.push(link);
                    if (type === "Extend" || type === "Include") {

                        if (!self.idLUT[src].hasOwnProperty('dst')) {
                            self.idLUT[src].dst = [];
                        }
                        self.idLUT[src].dst.push({
                            type: type,
                            dstId: link.dst,
                            connId: link.id
                        });
                        if (!self.idLUT[dst].hasOwnProperty('src')) {
                            self.idLUT[dst].src = [];
                        }
                        self.idLUT[dst].src.push({
                            type: type,
                            srcId: link.src
                        });
                    }
                }
                self.modelID += 1;
                callback(null);
            }
        };

        afterSrcLoaded = function (err, nodeObj) {
            if (err) {
                pushUseCaseLink(err, false);
                return;
            }
            if (!self.idLUT.hasOwnProperty(src)) {
                srcMetaType = core.getAttribute(self.getMetaType(nodeObj), 'name');
                self.addComponent(nodeObj, srcMetaType);
                self.modelID += 1;
            }
            srcX = core.getRegistry(nodeObj, 'position').x;
            srcY = core.getRegistry(nodeObj, 'position').y;
            srcName = core.getAttribute(nodeObj, 'name');
            srcId = core.getPath(nodeObj);
            pushUseCaseLink(null, true);
        };
        core.loadByPath(self.rootNode, src, afterSrcLoaded);

        afterDstLoaded = function (err, nodeObj) {
            if (err) {
                pushUseCaseLink(err, false);
                return;
            }
            if (!self.idLUT.hasOwnProperty(dst)) {
                srcMetaType = core.getAttribute(self.getMetaType(nodeObj), 'name');
                self.addComponent(nodeObj, dstMetaType);
                self.modelID += 1;
            }
            dstX = core.getRegistry(nodeObj, 'position').x;
            dstY = core.getRegistry(nodeObj, 'position').y;
            dstName = core.getAttribute(nodeObj, 'name');
            dstId = core.getPath(nodeObj);
            pushUseCaseLink(null, true);
        };
        core.loadByPath(self.rootNode, dst, afterDstLoaded);

    };

    SequenceDiagramExporter.prototype.saveResults = function (callback) {
        var self = this,
            diagramPath,
            i,
            h = 0,
            obj,
            diagramId = 1,
            output,
            artifact = self.blobClient.createArtifact('SysMLExporterOutput');

        for (diagramPath in self.sequenceDiagrams) {
            if (self.sequenceDiagrams.hasOwnProperty(diagramPath)) {
                var template,
                    modelFile,
                    modelElms = [];

                for (i = 0; i < self.sequenceDiagrams[diagramPath].elements.length; ++i) {
                    var childElement = self.sequenceDiagrams[diagramPath].elements[i],
                        elm,
                        j;

                    if (childElement.type === 'LifeLine') {
                        elm = '<lifeline xmi:type="uml:Lifeline" xmi:id="' + childElement.id + '" name="' +
                            + childElement.name + '"/>';
                        modelElms.push(elm);
                    }

                    template = TEMPLATES['packagedElement.uml.ejs'];
                    obj = {
                        type: childElement.type,
                        name: childElement.name,
                        id: childElement.id,
                        relations: ''
                    };

                    if (childElement.type === 'UseCase') {
                        var connType,
                            connId,
                            srcId,
                            dstId;

                        if (self.idLUT[self.reverseIdLUT[childElement.id]].src) {

                            for (j = 0; j < self.idLUT[self.reverseIdLUT[childElement.id]].src.length; ++j) {
                                connType = self.idLUT[self.reverseIdLUT[childElement.id]].src[j].type;
                                srcId = self.idLUT[self.reverseIdLUT[childElement.id]].src[j].srcId;
                                if (connType == "Extend") {
                                    obj.relations += '\n<extensionPoint xmi:type="uml:ExtensionPoint" xmi:id="ext_' + srcId
                                        + '" name="ExtensionPoint' + j + '"/>'
                                }
                            }
                        }
                        if (self.idLUT[self.reverseIdLUT[childElement.id]].dst) {

                            for (j = 0; j < self.idLUT[self.reverseIdLUT[childElement.id]].dst.length; ++j) {
                                connType = self.idLUT[self.reverseIdLUT[childElement.id]].dst[j].type;
                                dstId = self.idLUT[self.reverseIdLUT[childElement.id]].dst[j].dstId;
                                connId = self.idLUT[self.reverseIdLUT[childElement.id]].dst[j].connId;
                                if (connType == "Include") {
                                    obj.relations += '\n<include xmi:type="uml:Include" xmi:id="' + connId
                                        + '" addition="' + dstId + '"/>';
                                } else if (connType == "Extend") {
                                    obj.relations += '\n<extend xmi:type="uml:Extend" xmi:id="' + connId
                                        + '" extendedCase="' + dstId + '" extensionLocation="ext_' + obj.id + '"/>'
                                }
                            }
                        }
                    }

                    elm = ejs.render(template, obj)
                        .replace(/</g, '<')
                        .replace(/>/g, '>')
                        .replace(/'/g, "'")
                        .replace(/"/g, '"');

                    modelElms.push(elm);
                }

                for (i = 0; i < self.sequenceDiagrams[diagramPath].links.length; ++i) {
                    var link = self.sequenceDiagrams[diagramPath].links[i],
                        edge;

                    obj = CONSTANTS[link.type];
                    obj.srcId = link.src;
                    obj.dstId = link.dst;
                    obj.id = link.id;
                    obj.srcX = link.points.src.x;
                    obj.srcY = link.points.src.y;
                    obj.dstX = link.points.dst.x;
                    obj.dstY = link.points.dst.y;

                    edge = ejs.render(TEMPLATES['edges.ejs'], obj);
                    modelNotationElms.push(edge);

                    if (link.type === "CommunicationPath") {

                        edge = ejs.render(TEMPLATES['edge_packagedElement.ejs'],
                            {
                                connId: link.id,
                                srcId: link.src,
                                dstId: link.dst,
                                srcName: link.srcName,
                                dstName: link.dstName
                            });
                        modelElms.push(edge);
                    }
                }

                // save data into the only one packageElement
                elm = ejs.render(TEMPLATES['packagedElement.uml.ejs'], {
                    type: 'Interaction',
                    id: 'D' + diagramId,
                    name: diagramPath.split('+')[1],
                    relations: modelElms.join('\n')
                })
                    .replace(/</g, '<')
                    .replace(/>/g, '>')
                    .replace(/'/g, "'")
                    .replace(/"/g, '"');

                modelFile = ejs.render(TEMPLATES['model.uml.ejs'],
                    {
                        diagramId: '_D' + diagramId++,
                        id: h,
                        childElements: elm,
                        xmiElements: ''
                    })
                    .replace(/</g, '<')
                    .replace(/>/g, '>')
                    .replace(/'/g, "'")
                    .replace(/"/g, '"');

                output = {
                    modelUml: modelFile
                };
                self.outputFiles['model.uml'] = output.modelUml;
            }
            ++h;

        }

        artifact.addFiles(self.outputFiles, function (err, hashes) {
            if (err) {
                callback(err, self.result);
                return;
            }
            self.logger.warn(hashes.toString());
            artifact.save(function (err, hash) {
                if (err) {
                    callback(err, self.result);
                    return;
                }
                self.result.addArtifact(hash);
                self.result.setSuccess(true);
                callback(null, self.result);
            });
        });
    };

    return SequenceDiagramExporter;
});


text:
package org.bondlib;

import org.junit.Assert;
import org.junit.Test;

import java.io.*;
import java.lang.reflect.Field;
import java.net.URISyntaxException;
import java.net.URL;

import static org.junit.Assert.fail;

public class CloningTest {
    //
    // reflection assumptions
    //
    private static class PrivateInt {
        private int i;
    }

    @Test
    public void fieldAccessibilityIsolation() {
        // We depend on the assumption that we can modify accessibility through
        // our java.lang.reflect.Field instances without interfering with or
        // interference from other components.

        final Field accessible;
        final Field inaccessible;
        try {
            accessible = PrivateInt.class.getDeclaredField("i");
            inaccessible = PrivateInt.class.getDeclaredField("i");
        } catch (final NoSuchFieldException e) {
            fail("Couldn't get field - did the test class definition change?");
            return;     // javac doesn't realize fail() doesn't return
        }

        // Make only one field accessible...
        accessible.setAccessible(true);
        // ... then try to access the private field with the other.
        boolean getThrew = false;
        try {
            inaccessible.getInt(new PrivateInt());
        } catch (final IllegalAccessException e) {
            getThrew = true;
        }

        Assert.assertTrue("accessing private field through unmodified Field should have thrown", getThrew);
    }

    //
    // common code for stream cloning
    //
    private interface Cloner<S extends InputStream> {
        InputStream clone(final S stream);
    }

    private interface ExpectedGetter {
        byte get(final int i);
    }

    private <S extends InputStream> void compareStreams(
            final S original, final Cloner<S> cloner,
            final ExpectedGetter expected,
            final int readFirst, final int length) throws IOException {
        // Skip zero or more bytes before cloning.
        int i = 0;
        for (; i < readFirst; i++) {
            try {
                StreamHelper.readByte(original);
            } catch (final IOException ignored) {
                fail("original stream hit end-of-stream while skipping initial bytes");
            }
        }

        final InputStream cloned = cloner.clone(original);
        // original and cloned should see the same sequence of bytes from here.
        for (; i < length; i++) {
            final int originalInt = original.read();
            if (originalInt == -1) {
                fail(String.format("original stream hit end-of-stream at index %d", i));
            }
            final byte originalByte = (byte) originalInt;

            final int clonedInt = cloned.read();
            if (clonedInt == -1) {
                fail(String.format("cloned stream hit end-of-stream at index %d", i));
            }
            final byte clonedByte = (byte) clonedInt;

            final byte expectedByte = expected.get(i);
            Assert.assertEquals(String.format("original stream read the wrong value at index %d", i),
                expectedByte, originalByte);
            Assert.assertEquals(String.format("cloned stream read the wrong value at index %d", i),
                expectedByte, clonedByte);
        }

        // original and cloned should both signal end-of-stream on their next reads.
        Assert.assertTrue("original stream read past the end of its segment", original.read() == -1);
        Assert.assertTrue("cloned stream read past the end of its segment", cloned.read() == -1);
    }

    //
    // ByteArrayInputStream cloning
    //
    private static final byte[] bytes = new byte[] {
        0x01, 0x02, 0x03,
        0x04, 0x05, 0x06,
        0x07, 0x08, 0x09,
        0x0a, 0x0b, 0x0c
    };

    private static class ByteArrayInputStreamCloner implements Cloner<ByteArrayInputStream> {
        @Override
        public InputStream clone(ByteArrayInputStream stream) {
            return Cloning.clone(stream);
        }
    }

    private static class ByteArrayInputStreamExpectedGetter implements ExpectedGetter {
        private final int offset;

        ByteArrayInputStreamExpectedGetter(final int offset) {
            this.offset = offset;
        }

        @Override
        public byte get(int i) {
            return bytes[this.offset + i];
        }
    }

    @Test
    public void byteArrayInputStream_fieldAccessibility() throws NoSuchFieldException, IllegalAccessException {
        // We need to be able to access these fields by reflection to clone a
        // ByteArrayInputStream. They have been part of ByteArrayInputStream
        // since JDK 1.0, so something interesting has happened if this test
        // throws.

        final Field bufField = ByteArrayInputStream.class.getDeclaredField("buf");
        final Field posField = ByteArrayInputStream.class.getDeclaredField("pos");
        final Field countField = ByteArrayInputStream.class.getDeclaredField("count");

        bufField.setAccessible(true);
        posField.setAccessible(true);
        countField.setAccessible(true);

        final ByteArrayInputStream bais = new ByteArrayInputStream(new byte[]{});
        bufField.get(bais);
        posField.getInt(bais);
        countField.getInt(bais);
    }

    @Test
    public void byteArrayInput() throws IOException {
        final ByteArrayInputStreamCloner cloner = new ByteArrayInputStreamCloner();
        final int segmentLength = bytes.length / 2;

        // stream consumes entire array
        final ByteArrayInputStreamExpectedGetter wholeArrayGetter = new ByteArrayInputStreamExpectedGetter(0);
        compareStreams(
            new ByteArrayInputStream(bytes, 0, bytes.length), cloner, wholeArrayGetter,
            0, bytes.length);
        compareStreams(
            new ByteArrayInputStream(bytes, 0, bytes.length), cloner, wholeArrayGetter,
            bytes.length / 2, bytes.length);
        compareStreams(
            new ByteArrayInputStream(bytes, 0, bytes.length), cloner, wholeArrayGetter,
            bytes.length, bytes.length);

        // stream consumes prefix of array
        final ByteArrayInputStreamExpectedGetter prefixGetter = wholeArrayGetter;
        compareStreams(
            new ByteArrayInputStream(bytes, 0, segmentLength), cloner, prefixGetter,
            0, segmentLength);
        compareStreams(
            new ByteArrayInputStream(bytes, 0, segmentLength), cloner, prefixGetter,
            segmentLength / 2, segmentLength);
        compareStreams(
            new ByteArrayInputStream(bytes, 0, segmentLength), cloner, prefixGetter,
            segmentLength, segmentLength);

        // stream consumes suffix of array
        final ByteArrayInputStreamExpectedGetter suffixGetter =
            new ByteArrayInputStreamExpectedGetter(bytes.length - segmentLength);
        compareStreams(
            new ByteArrayInputStream(bytes, bytes.length - segmentLength, segmentLength), cloner, suffixGetter,
            0, segmentLength);
        compareStreams(
            new ByteArrayInputStream(bytes, bytes.length - segmentLength, segmentLength), cloner, suffixGetter,
            segmentLength / 2, segmentLength);
        compareStreams(
            new ByteArrayInputStream(bytes, bytes.length - segmentLength, segmentLength), cloner, suffixGetter,
            segmentLength, segmentLength);

        // stream consumes middle of array
        final int middleSegmentOffset = segmentLength / 2;
        final ByteArrayInputStreamExpectedGetter middleGetter =
            new ByteArrayInputStreamExpectedGetter(middleSegmentOffset);
        compareStreams(
            new ByteArrayInputStream(bytes, middleSegmentOffset, segmentLength), cloner, middleGetter,
            0, segmentLength);
        compareStreams(
            new ByteArrayInputStream(bytes, middleSegmentOffset, segmentLength), cloner, middleGetter,
            segmentLength / 2, segmentLength);
        compareStreams(
            new ByteArrayInputStream(bytes, middleSegmentOffset, segmentLength), cloner, middleGetter,
            segmentLength, segmentLength);
    }

    //
    // FileInputStream cloning
    //
    private static final String testTxtPath = "/alphabet.txt";
    private static final byte[] testTxtContents = StringHelper.encodeString("ABCDEFGHIJKLMNOPQRSTUVWXYZ");

    private static class FileInputStreamCloner implements Cloner<FileInputStream> {
        public InputStream clone(final FileInputStream stream) {
            try {
                return Cloning.clone(stream);
            } catch (final IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    private static class ByteBufferInputStreamCloner implements Cloner<Cloning.ByteBufferInputStream> {

        @Override
        public InputStream clone(Cloning.ByteBufferInputStream stream) {
            return Cloning.clone(stream);
        }
    }

    private static class FileInputStreamExpectedGetter implements ExpectedGetter {
        @Override
        public byte get(int i) {
            return testTxtContents[i];
        }
    }

    private FileInputStream testFileStream() {
        try {
            final URL url = getClass().getResource(testTxtPath);
            final File file = new File(url.toURI());
            return new FileInputStream(file);
        } catch (final IOException e) {
            throw new RuntimeException(e);
        } catch (final URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }

    @Test
    public void testTxtPreconditions() throws IOException, URISyntaxException {
        // We need a file to test FileInputStream cloning. This test asserts
        // the properties of the test file that the others will assume.

        // Check resource availability.
        final FileInputStream stream = testFileStream();

        // Check file length.
        final byte[] contents = new byte[testTxtContents.length];
        Assert.assertEquals(contents.length, stream.read(contents));
        // This should be the end of the file.
        Assert.assertEquals(-1, stream.read());

        // Check file content.
        Assert.assertArrayEquals(testTxtContents, contents);
    }

    @Test
    public void fileInput() throws IOException {
        final FileInputStreamCloner cloner = new FileInputStreamCloner();
        final FileInputStreamExpectedGetter getter = new FileInputStreamExpectedGetter();

        compareStreams(testFileStream(), cloner, getter, 0, testTxtContents.length);
        compareStreams(testFileStream(), cloner, getter, testTxtContents.length / 2, testTxtContents.length);
        compareStreams(testFileStream(), cloner, getter, testTxtContents.length, testTxtContents.length);
    }

    @Test
    public void byteBufferInput() throws IOException {
        final ByteBufferInputStreamCloner cloner = new ByteBufferInputStreamCloner();
        final FileInputStreamExpectedGetter getter = new FileInputStreamExpectedGetter();

        compareStreams(Cloning.clone(testFileStream()), cloner, getter,
            0, testTxtContents.length);
        compareStreams(Cloning.clone(testFileStream()), cloner, getter,
            testTxtContents.length / 2, testTxtContents.length);
        compareStreams(Cloning.clone(testFileStream()), cloner, getter,
            testTxtContents.length, testTxtContents.length);
    }
}


text:
require('nis.sessions')
require('nis.utils')
require('nis.commands')
require('nis.project_lookup')
require('nis.project')
local sessions = {} -- a table "filepath" - session

local function current_session()
  if vis.win and vis.win.file and vis.win.file.project then
    return sessions[vis.win.file.project]
  end
end

local function on_brace(session)
  vis:insert("(")
  session:context()
  return true
end

local function suggest_dot(session)
  vis:insert(".")
  session:suggest()
  return true
end

function check_it()
  local session = current_session()
  if session == nil then return end
  session:check()
end

function goto_def()
  local session = current_session()
  if session == nil then return end
  session:goto_definition()
end

function get_help()
  local session = current_session()
  if session == nil then return end
  session:help()
end

function suggest_key()
  local session = current_session()
  if session == nil then return end
  session:suggest()
end

local keyactions = {
  ['('] = on_brace,
  ['.'] = suggest_dot,
}

function dispatch_input(key)
  local session = current_session()
  if session == nil then return end
  if keyactions[key] then return keyactions[key](session) end
end

function on_open(file)
  if file == nil or file.path == nil or #file.path < 5 then return end
  if file.path:sub(-3) == "nim" then
    file.project, file.nimblefile = find_projectfile(file.path)
    vis:info("'"..file.project.."' used as a projectfile.")
    if sessions[file.project] then
      local cur = sessions[file.project].refcounter
      sessions[file.project].refcounter = cur + 1
    else
      sessions[file.project] = Session.new(file.project)
      sessions[file.project].refcounter = 1
    end
    --debugme(sessions[file.project])
  end
end

function on_close(file)
  if not file.project or not sessions[file.project] then return end
  local cur = sessions[file.project].refcounter
  if cur - 1 == 0 then
    sessions[file.project]:close()
    sessions[file.project] = nil
    collectgarbage()
  else
    sessions[file.project].refcounter = cur - 1
  end
end

function cycle_all(window)
  if vis.ignore then return end -- The lock to prevent endless windows updates
  vis.ignore = true
  for _, session in pairs(sessions) do
    session:cycle()
  end
  if window.triggers then
    for tname, trigger in pairs(window.triggers) do
      trigger(window)
    end
  end
  vis.ignore = false
end

function stop_all()
  for _, session in pairs(sessions) do
    session:close()
  end
end


text:
<?php

namespace Krystal\Application\Controller;

use Krystal\InstanceManager\ServiceLocatorInterface;
use Krystal\Application\View\Resolver\ModuleResolver;
use Krystal\Db\Filter\FilterableServiceInterface;
use Krystal\Db\Filter\FilterInvoker;
use Krystal\Stdlib\ArrayUtils;
use RuntimeException;

abstract class AbstractController
{
    /**
     * Service Locator
     *
     * @var \Krystal\InstanceManager\ServiceLocatorInterface
     */
    protected $serviceLocator;

    /**
     * Current module name
     *
     * @var string
     */
    protected $moduleName;

    /**
     * Controller options
     *
     * @var array
     */
    protected $options = array();

    /**
     * Whether execution is halted
     *
     * @var boolean
     */
    protected $halted = false;

    /**
     * State initialization
     *
     * @param \Krystal\InstanceManager\ServiceLocatorInterface $serviceLocator
     * @param string $moduleName Target module we are in
     * @param array $options
     * @return void
     */
    final public function __construct(ServiceLocatorInterface $serviceLocator, $moduleName, array $options)
    {
        $this->serviceLocator = $serviceLocator;
        $this->moduleName = $moduleName;
        $this->options = $options;
    }

    /**
     * Prepares a response as JSON string setting corresponding headers
     *
     * @param array $data
     * @param integer Native encoding options
     * @return string
     */
    final protected function json(array $data, $options = 0)
    {
        // Set JSON header
        $this->response->respondAsJson();

        return json_encode($data, $options);
    }

    /**
     * Creates a mapper
     *
     * @param string $namespace
     * @return \Krystal\Db\Sql\AbstractMapper
     */
    final protected function createMapper($namespace)
    {
        return $this->mapperFactory->build($namespace);
    }

    /**
     * Creates validation instance
     *
     * @param array $config
     * @return \Krystal\Validate\ValidatorChain
     */
    final protected function createValidator(array $params)
    {
        return $this->validatorFactory->build($params);
    }

    /**
     * Creates URL
     *
     * @param string $controller
     * @param array $args
     * @param integer $index
     * @return string
     */
    final protected function createUrl($controller, array $args = array(), $index = 0)
    {
        if (ArrayUtils::isAssoc($args)) {
            return $this->urlBuilder->createQueryUrl($controller, $args, $index);
        } else {
            return $this->urlBuilder->createUrl($controller, $args, $index);
        }
    }

    /**
     * Redirects to given route
     *
     * @param string $route Target route
     * @throws \RuntimeException if unknown route supplied
     * @return void
     */
    final protected function redirectToRoute($route)
    {
        $url = $this->urlBuilder->build($route);

        if ($url !== null) {
            $this->response->redirect($url);
        } else {
            throw new RuntimeException(sprintf('Unknown route supplied for redirection "%s"', $route));
        }
    }

    /**
     * Forwards to another controller's action
     *
     * @param string $route Framework-compliant route
     * @param array $args Optional arguments
     * @return string
     */
    final protected function forward($route, array $args = array())
    {
        return $this->dispatcher->forward($route, $args);
    }

    /**
     * Applies filtering method from the service that implements corresponding interface
     * That's just a shortcut method
     *
     * @param \Krystal\Db\Filter\FilterableServiceInterface $service A service which implement this interface
     * @param integer $perPageCount Items per page to display
     * @param string $route Base route
     * @return array
     */
    final protected function getQueryFilter(FilterableServiceInterface $service, $perPageCount, $route)
    {
        $invoker = new FilterInvoker($this->request->getQuery(), $route);
        return $invoker->invoke($service, $perPageCount);
    }

    /**
     * Returns a service of current module
     *
     * @param string $service
     * @return object
     */
    final protected function getModuleService($service)
    {
        return $this->getService($this->moduleName, $service);
    }

    /**
     * A shortcut for grabbing services
     *
     * @param string $module
     * @param string $service
     * @return object
     */
    final protected function getService($module, $service)
    {
        return $this->moduleManager->getModule($module)->getService($service);
    }

    /**
     * Handle calls to undefined class properties
     *
     * The point of this magic method is simple - avoid calling $this->serviceLocator->whatever, but call $this->whatever instead
     * It simplifies access to a service locator, when dependencies were injected manually
     *
     * @param string $property
     * @return mixed
     */
    public function __get($property)
    {
        if ($this->serviceLocator->has($property)) {
            return $this->serviceLocator->get($property);
        } else {
            trigger_error(sprintf('Attempted to grab non-existing service or accessed to undefined property "%s"', $property));
            return null;
        }
    }

    /**
     * Halts the execution
     *
     * @return void
     */
    public function halt()
    {
        $this->halted = true;
    }

    /**
     * Checks whether execution is halted
     *
     * @return boolean
     */
    public function isHalted()
    {
        return $this->halted;
    }

    /**
     * Checks whether current controller has an option in its route definition
     *
     * @param string $option
     * @return boolean
     */
    final protected function hasOption($option)
    {
        $options = $this->getOptions();
        return isset($options[$option]);
    }

    /**
     * Returns current options for a matched controller
     *
     * @param string $key
     * @return array
     */
    public function getOptions($key = null)
    {
        if ($key == null) {
            return $this->options;
        } else {
            return $this->options[$key];
        }
    }

    /**
     * Returns current module where this controller belongs
     *
     * @return string
     */
    public function getModule()
    {
        return $this->moduleName;
    }

    /**
     * Halts controller's execution on demand
     *
     * @return void
     */
    final protected function haltOnDemand()
    {
        switch (true) {

            // If at least one of below conditions is true, then $this->halt() is called
            case $this->hasOption('secure') && $this->getOptions('secure') == true && !$this->request->isSecure():
            case $this->hasOption('ajax') && $this->getOptions('ajax') == true && !$this->request->isAjax():
            case $this->hasOption('method') && (strtoupper($this->getOptions('method')) != $this->request->getMethod()):

            $this->halt();
        }
    }

    /**
     * Load translation messages from all available modules
     *
     * @param string $language
     * @return void
     */
    private function loadTranslationMessages($language)
    {
        // Reset any previous translations if any
        $this->moduleManager->clearTranslations();
        $this->translator->reset();

        // Now load new ones
        $this->moduleManager->loadAllTranslations($language);
        $this->translator->extend($this->moduleManager->getTranslations());
    }

    /**
     * Loads default translations if default language is defined
     *
     * @return void
     */
    private function loadDefaultTranslations()
    {
        $language = $this->appConfig->getLanguage();

        if ($language !== null) {
            $this->loadTranslationMessages($language);
        }
    }

    /**
     * Load translation messages
     *
     * @param string $language
     * @return boolean
     */
    final protected function loadTranslations($language)
    {
        // Don't load the same language twice, if that's the case
        if ($this->appConfig->getLanguage() !== $language) {

            $this->appConfig->setLanguage($language);
            $this->loadTranslationMessages($language);
            return true;

        } else {
            return false;
        }
    }

    /**
     * Invoked right after class instantiation
     *
     * @param string $action Current action to be executed
     * @return void
     */
    final public function initialize($action)
    {
        $this->haltOnDemand();

        // Configure view with defaults
        $this->view->setModule($this->getModule())
                   ->setTheme($this->appConfig->getTheme());

        if (method_exists($this, 'bootstrap')) {
            $this->bootstrap($action);
        }

        if (method_exists($this, 'onAuth')) {
            $this->onAuth();
        }

        $this->loadDefaultTranslations();
    }
}


text:
package hrv.lib.hrv.calc.manipulator;

import hrv.lib.hrv.RRData;
import org.apache.commons.math3.stat.descriptive.moment.Mean;

public class HRVSubtractMeanManipulator implements HRVDataManipulator {

	@Override
	public RRData manipulate(RRData data) {

		double[] oldRRY = data.getValueAxis();
		double[] oldRRX = data.getTimeAxis();

		var newRRY = new double[data.getValueAxis().length];
		var newRRX = new double[data.getTimeAxis().length];

		var m = new Mean();
		double mean = m.evaluate(oldRRY);

		for (var i = 0; i < newRRY.length; i++) {
			newRRY[i] = oldRRY[i] - mean;
			newRRX[i] = oldRRX[i];
		}

		return new RRData(newRRX, data.getTimeAxisUnit(), newRRY, data.getValueAxisUnit());
	}

}


text:
<!--
 ! Licensed to the Apache Software Foundation (ASF) under one
 ! or more contributor license agreements.  See the NOTICE file
 ! distributed with this work for additional information
 ! regarding copyright ownership.  The ASF licenses this file
 ! to you under the Apache License, Version 2.0 (the
 ! "License"); you may not use this file except in compliance
 ! with the License.  You may obtain a copy of the License at
 !
 !   http://www.apache.org/licenses/LICENSE-2.0
 !
 ! Unless required by applicable law or agreed to in writing,
 ! software distributed under the License is distributed on an
 ! "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 ! KIND, either express or implied.  See the License for the
 ! specific language governing permissions and limitations
 ! under the License.
 !-->
<test-suite xmlns="urn:xml.testframework.asterix.apache.org" ResultOffsetPath="results" QueryOffsetPath="queries" QueryFileExtension=".aql">
<test-group name="library-parsers">
    <test-case FilePath="library-parsers">
      <compilation-unit name="record-parser">
        <output-dir compare="Text">record-parser</output-dir>
      </compilation-unit>
    </test-case>
    </test-group>
  <test-group name="library-functions">
    <test-case FilePath="library-functions">
      <compilation-unit name="mysum">
        <output-dir compare="Text">mysum</output-dir>
      </compilation-unit>
    </test-case>
    <test-case FilePath="library-functions">
      <compilation-unit name="toUpper">
        <output-dir compare="Text">toUpper</output-dir>
      </compilation-unit>
    </test-case>
    <test-case FilePath="library-functions">
      <compilation-unit name="insert-from-select">
        <output-dir compare="Text">insert-from-select</output-dir>
      </compilation-unit>
    </test-case>
    <test-case FilePath="library-functions">
      <compilation-unit name="getCapital">
        <output-dir compare="Text">getCapital</output-dir>
      </compilation-unit>
    </test-case>
  </test-group>
  <test-group name="library-metadata">
    <test-case FilePath="library-metadata">
      <compilation-unit name="functionDataset">
        <output-dir compare="Text">functionDataset</output-dir>
      </compilation-unit>
    </test-case>
    <test-case FilePath="library-metadata">
      <compilation-unit name="libraryDataset">
        <output-dir compare="Text">libraryDataset</output-dir>
      </compilation-unit>
    </test-case>
    <test-case FilePath="library-metadata">
      <compilation-unit name="dataverseDataset">
        <output-dir compare="Text">dataverseDataset</output-dir>
      </compilation-unit>
    </test-case>
  </test-group>
  <test-group name="library-feeds">
    <test-case FilePath="library-feeds">
      <compilation-unit name="feed_ingest">
        <output-dir compare="Text">feed_ingest</output-dir>
      </compilation-unit>
    </test-case>
  </test-group>
  <test-group name="library-adapters">
    <test-case FilePath="library-adapters">
      <compilation-unit name="typed_adapter">
        <output-dir compare="Text">typed_adapter</output-dir>
      </compilation-unit>
    </test-case>
  </test-group>
</test-suite>


text:
package co.cask.cdap.internal.app.store.remote;

import co.cask.cdap.data2.registry.UsageRegistry;
import co.cask.cdap.internal.app.services.http.AppFabricTestBase;
import co.cask.cdap.proto.id.ApplicationId;
import co.cask.cdap.proto.id.DatasetId;
import co.cask.cdap.proto.id.NamespaceId;
import co.cask.cdap.proto.id.ProgramId;
import co.cask.cdap.proto.id.StreamId;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import com.google.inject.Injector;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;

/**
 * Tests implementation of {@link RemoteRuntimeUsageRegistry}, by using it to perform writes/updates, and then using a
 * local {@link UsageRegistry} to verify the updates/writes.
 */
public class RemoteRuntimeUsageRegistryTest extends AppFabricTestBase {

  private static UsageRegistry usageRegistry;
  private static RemoteRuntimeUsageRegistry runtimeUsageRegistry;

  @BeforeClass
  public static void setup() throws Exception {
    Injector injector = getInjector();
    usageRegistry = injector.getInstance(UsageRegistry.class);
    runtimeUsageRegistry = injector.getInstance(RemoteRuntimeUsageRegistry.class);
  }

  @Test
  public void testSimpleCase() {
    ApplicationId appId = NamespaceId.DEFAULT.app("test_app");
    ProgramId flowId1 = appId.flow("test_flow1");
    ProgramId flowId2 = appId.flow("test_flow2");

    // should be no data initially
    Assert.assertEquals(0, usageRegistry.getDatasets(appId).size());
    Assert.assertEquals(0, usageRegistry.getStreams(appId).size());

    Assert.assertEquals(0, usageRegistry.getDatasets(flowId1).size());
    Assert.assertEquals(0, usageRegistry.getStreams(flowId1).size());

    Assert.assertEquals(0, usageRegistry.getDatasets(flowId2).size());
    Assert.assertEquals(0, usageRegistry.getStreams(flowId2).size());

    DatasetId datasetId1 = NamespaceId.DEFAULT.dataset("test_dataset1");
    runtimeUsageRegistry.register(flowId1, datasetId1);

    ImmutableSet<DatasetId> datasetsUsedByFlow1 = ImmutableSet.of(datasetId1);
    Assert.assertEquals(datasetsUsedByFlow1, usageRegistry.getDatasets(appId));
    Assert.assertEquals(0, usageRegistry.getStreams(appId).size());

    Assert.assertEquals(datasetsUsedByFlow1, usageRegistry.getDatasets(flowId1));
    Assert.assertEquals(0, usageRegistry.getStreams(flowId1).size());

    Assert.assertEquals(0, usageRegistry.getDatasets(flowId2).size());
    Assert.assertEquals(0, usageRegistry.getStreams(flowId2).size());

    DatasetId datasetId2 = NamespaceId.DEFAULT.dataset("test_dataset2");
    StreamId streamId = NamespaceId.DEFAULT.stream("test_stream");
    runtimeUsageRegistry.register(flowId2, datasetId1);
    runtimeUsageRegistry.register(flowId2, datasetId2);
    runtimeUsageRegistry.register(flowId2, streamId);

    ImmutableSet<DatasetId> datasetsUsedByFlow2 = ImmutableSet.of(datasetId1, datasetId2);
    ImmutableSet<StreamId> streamsUsedByFlow2 = ImmutableSet.of(streamId);
    Assert.assertEquals(Sets.union(datasetsUsedByFlow1, datasetsUsedByFlow2), usageRegistry.getDatasets(appId));
    Assert.assertEquals(streamsUsedByFlow2, usageRegistry.getStreams(appId));

    Assert.assertEquals(datasetsUsedByFlow1, usageRegistry.getDatasets(flowId1));
    Assert.assertEquals(0, usageRegistry.getStreams(flowId1).size());

    Assert.assertEquals(datasetsUsedByFlow2, usageRegistry.getDatasets(flowId2));
    Assert.assertEquals(streamsUsedByFlow2, usageRegistry.getStreams(flowId2));
  }
}


text:
namespace Ren.CMS.NET_InstallProxy
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Http;
    using System.Web.Mvc;
    using System.Web.Optimization;
    using System.Web.Routing;

    // Hinweis: Anweisungen zum Aktivieren des klassischen Modus von IIS6 oder IIS7
    // finden Sie unter "http://go.microsoft.com/?LinkId=9394801".
    public class WebApiApplication : System.Web.HttpApplication
    {
        #region Methods

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }

        #endregion Methods
    }
}


text:
namespace sky {
namespace shell {

namespace {

void ConfigureSettings(blink::WebSettings* settings) {
  settings->setDefaultFixedFontSize(13);
  settings->setDefaultFontSize(16);
  settings->setLoadsImagesAutomatically(true);
}

}

Engine::Engine(const Config& config)
    : config_(config),
      animator_(new Animator(config, this)),
      web_view_(nullptr),
      device_pixel_ratio_(1.0f),
      viewport_observer_binding_(this),
      weak_factory_(this) {
}

Engine::~Engine() {
  if (web_view_)
    web_view_->close();
}

base::WeakPtr<Engine> Engine::GetWeakPtr() {
  return weak_factory_.GetWeakPtr();
}

void Engine::Init() {
  TRACE_EVENT0("sky", "Engine::Init");

  service_provider_ = CreateServiceProvider(config_.service_provider_context);
  mojo::NetworkServicePtr network_service;
  mojo::ConnectToService(service_provider_.get(), &network_service);
  platform_impl_.reset(new PlatformImpl(network_service.Pass()));

  blink::initialize(platform_impl_.get());
}

void Engine::BeginFrame(base::TimeTicks frame_time) {
  TRACE_EVENT0("sky", "Engine::BeginFrame");

  double frame_time_sec = (frame_time - base::TimeTicks()).InSecondsF();
  double deadline_sec = frame_time_sec;
  double interval_sec = 1.0 / 60;
  blink::WebBeginFrameArgs args(frame_time_sec, deadline_sec, interval_sec);

  if (web_view_) {
    web_view_->beginFrame(args);
    web_view_->layout();
  }
}

skia::RefPtr<SkPicture> Engine::Paint() {
  TRACE_EVENT0("sky", "Engine::Paint");

  SkRTreeFactory factory;
  SkPictureRecorder recorder;
  auto canvas = skia::SharePtr(recorder.beginRecording(
      physical_size_.width(), physical_size_.height(), &factory,
      SkPictureRecorder::kComputeSaveLayerInfo_RecordFlag));

  if (sky_view_) {
    skia::RefPtr<SkPicture> picture = sky_view_->Paint();
    canvas->clear(SK_ColorBLACK);
    canvas->scale(device_pixel_ratio_, device_pixel_ratio_);
    if (picture)
      canvas->drawPicture(picture.get());
  }

  if (web_view_)
    web_view_->paint(canvas.get(), blink::WebRect(gfx::Rect(physical_size_)));

  return skia::AdoptRef(recorder.endRecordingAsPicture());
}

void Engine::ConnectToViewportObserver(
    mojo::InterfaceRequest<ViewportObserver> request) {
  viewport_observer_binding_.Bind(request.Pass());
}

void Engine::OnAcceleratedWidgetAvailable(gfx::AcceleratedWidget widget) {
  config_.gpu_task_runner->PostTask(
      FROM_HERE, base::Bind(&GPUDelegate::OnAcceleratedWidgetAvailable,
                            config_.gpu_delegate, widget));
  if (web_view_)
    scheduleVisualUpdate();
}

void Engine::OnOutputSurfaceDestroyed() {
  config_.gpu_task_runner->PostTask(
      FROM_HERE,
      base::Bind(&GPUDelegate::OnOutputSurfaceDestroyed, config_.gpu_delegate));
}

void Engine::OnViewportMetricsChanged(int width, int height,
                                      float device_pixel_ratio) {
  physical_size_.SetSize(width, height);
  device_pixel_ratio_ = device_pixel_ratio;

  if (sky_view_) {
    blink::SkyDisplayMetrics metrics;
    metrics.physical_size = physical_size_;
    metrics.device_pixel_ratio = device_pixel_ratio_;
    sky_view_->SetDisplayMetrics(metrics);
  }

  if (web_view_)
    UpdateWebViewSize();
}

void Engine::UpdateWebViewSize()
{
  CHECK(web_view_);
  web_view_->setDeviceScaleFactor(device_pixel_ratio_);
  gfx::SizeF size = gfx::ScaleSize(physical_size_, 1 / device_pixel_ratio_);
  // FIXME: We should be able to set the size of the WebView in floating point
  // because its in logical pixels.
  web_view_->resize(blink::WebSize(size.width(), size.height()));
}

// TODO(eseidel): This is likely not needed anymore.
blink::WebScreenInfo Engine::screenInfo() {
  blink::WebScreenInfo screen;
  screen.rect = blink::WebRect(gfx::Rect(physical_size_));
  screen.availableRect = screen.rect;
  screen.deviceScaleFactor = device_pixel_ratio_;
  return screen;
}

void Engine::OnInputEvent(InputEventPtr event) {
  TRACE_EVENT0("sky", "Engine::OnInputEvent");
  scoped_ptr<blink::WebInputEvent> web_event =
      ConvertEvent(event, device_pixel_ratio_);
  if (!web_event)
    return;
  if (sky_view_)
    sky_view_->HandleInputEvent(*web_event);
  if (web_view_)
    web_view_->handleInputEvent(*web_event);
}

void Engine::LoadURL(const mojo::String& url) {
  // Enable SkyView here.
  if (false) {
    sky_view_ = blink::SkyView::Create(this);
    sky_view_->Load(GURL(url));
    return;
  }

  // Something bad happens if you try to call WebView::close and replace
  // the webview.  So for now we just load into the existing one. :/
  if (!web_view_)
    web_view_ = blink::WebView::create(this);
  ConfigureSettings(web_view_->settings());
  web_view_->setMainFrame(blink::WebLocalFrame::create(this));
  UpdateWebViewSize();
  web_view_->mainFrame()->load(GURL(url));
}

void Engine::frameDetached(blink::WebFrame* frame) {
  // |frame| is invalid after here.
  frame->close();
}

void Engine::initializeLayerTreeView() {
}

void Engine::scheduleVisualUpdate() {
  animator_->RequestFrame();
}

void Engine::didCreateIsolate(blink::WebLocalFrame* frame,
                              Dart_Isolate isolate) {
  Internals::Create(isolate,
                    CreateServiceProvider(config_.service_provider_context));
}

void Engine::SchedulePaint() {
  animator_->RequestFrame();
}

blink::ServiceProvider* Engine::services() {
  return this;
}

mojo::NavigatorHost* Engine::NavigatorHost() {
  return this;
}

void Engine::RequestNavigate(mojo::Target target,
                             mojo::URLRequestPtr request) {
  // Ignoring target for now.
  base::MessageLoop::current()->PostTask(FROM_HERE,
      base::Bind(&Engine::LoadURL, GetWeakPtr(), request->url));
}

void Engine::DidNavigateLocally(const mojo::String& url) {
}

void Engine::RequestNavigateHistory(int32_t delta) {
  NOTIMPLEMENTED();
}

}  // namespace shell
}  // namespace sky


text:
Z3PO.presence(from: "R2Z2", status: :online) do |event|
      event.bot.channel(313009155969384448).send_message('There you are R2Z2, you shouldn\'t go running off like that.')
end

Z3PO.presence(from: "R2Z2", status: :offline) do |event|
      event.bot.channel(313009155969384448).send_message('R2Z2 where do you think you\'re going?! Well, I\'m not going that way.')
end


text:
**To delete a pipeline**

This example deletes a pipeline named MySecondPipeline from AWS CodePipeline. Use the list-pipelines command to view a list of pipelines associated with your AWS account.

Command::

  aws codepipeline delete-pipeline --name MySecondPipeline

Output::

  None.


text:
ActiveRecord::Schema.define(version: 20131224105500) do

  create_table "custom_emails_email_kinds", force: true do |t|
    t.string   "name"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  add_index "custom_emails_email_kinds", ["name"], name: "index_custom_emails_email_kinds_on_name", unique: true

  create_table "custom_emails_emails", force: true do |t|
    t.integer  "emailable_id"
    t.string   "emailable_type"
    t.string   "locale"
    t.text     "subject"
    t.text     "content_text"
    t.text     "content_html"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "kind_id"
  end

  add_index "custom_emails_emails", ["emailable_id"], name: "index_custom_emails_emails_on_emailable_id"
  add_index "custom_emails_emails", ["kind_id", "emailable_id"], name: "index_custom_emails_emails_on_kind_id_and_emailable_id"
  add_index "custom_emails_emails", ["kind_id", "locale", "emailable_id", "emailable_type"], name: "unique_w_kind_locale_and_emailable", unique: true
  add_index "custom_emails_emails", ["locale"], name: "index_custom_emails_emails_on_locale"

  create_table "custom_emails_short_message_kinds", force: true do |t|
    t.string   "name"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  add_index "custom_emails_short_message_kinds", ["name"], name: "index_custom_emails_short_message_kinds_on_name", unique: true

  create_table "custom_emails_short_messages", force: true do |t|
    t.integer  "messageable_id"
    t.string   "messageable_type"
    t.integer  "kind_id"
    t.string   "locale"
    t.text     "content"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  add_index "custom_emails_short_messages", ["kind_id", "locale", "messageable_id", "messageable_type"], name: "unique_w_kind_locale_and_messageable", unique: true
  add_index "custom_emails_short_messages", ["kind_id", "messageable_id"], name: "index_w_kind_and_messageable"
  add_index "custom_emails_short_messages", ["locale"], name: "index_custom_emails_short_messages_on_locale"
  add_index "custom_emails_short_messages", ["messageable_id"], name: "index_custom_emails_short_messages_on_messageable_id"

  create_table "examples", force: true do |t|
  end

end


text:
package jasy.lang.ast;

import jasy.lang.ASMCompiler;
import jasy.lang.ClassResolver;
import jasy.lang.SingleClassLoader;
import java.lang.reflect.Method;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.commons.GeneratorAdapter;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode;

public class MetaExpressionAST<T> extends AbstractAST implements ExpressionAST {
//    public ASMCompiler compiler;
    public ExpressionAST body;
//    public Method bodyAsMethod;
//    public TypeAST resultType;
//    public ASMCompiler.MetaProcessing mp;

    // Region and compiler could probably be merged into a single CompilationContext|CompilationUnit thingy
    public MetaExpressionAST(ASMCompiler.Region region, /*ASMCompiler compiler, */ExpressionAST body/*, ASMCompiler.MetaProcessing mp*/) {
        super(region);

//        this.compiler = compiler;
        this.body = body;
//        this.bodyAsMethod = bodyAsMethod;
//        this.mp = mp;
    }

    public static int getOpcodesVersion() {
        String javaVersion = System.getProperty("java.version");
        String[] javaVersionNumbers = javaVersion.split("\\.|_");
        int major = Integer.parseInt(javaVersionNumbers[0]);
        int minor = Integer.parseInt(javaVersionNumbers[1]);

        switch(major) {
            case 1:
                switch(minor) {
                    case 1:
                        return Opcodes.V1_1;
                    case 2:
                        return Opcodes.V1_2;
                    case 3:
                        return Opcodes.V1_3;
                    case 4:
                        return Opcodes.V1_4;
                    case 5:
                        return Opcodes.V1_5;
                    case 6:
                        return Opcodes.V1_6;
                    case 7:
                        return Opcodes.V1_7;
                    case 8:
                        return Opcodes.V1_8;
                }
            break;
        }

        return -1;
    }

    @Override
    public void resolve(Scope thisClass, TypeAST expectedResultType, ClassResolver resolver, ClassLoader classLoader, List<ASMCompiler.Message> errorMessages) {
        body.resolve(thisClass, expectedResultType, resolver, classLoader, errorMessages);

//        // expectedResultType should for body should a type pattern including String, int, ...rest primitive types..., ExpressionAST
//        body.forEach(s -> s.resolve(n, new NameTypeAST(getRegion(), ExpressionAST.class), resolver, errorMessages));
//        List<TypeAST> returnTypes = MethodAST.getReturnType(body);
//        // Dangerous
//        Class<?> returnTypeClass = ((NameTypeAST)returnTypes.get(0)).getType();
//
//        // 1) Generate code to generate code
//        ClassNode generatorClassNode = new ClassNode(Opcodes.ASM5);
//
//        mp.metaScope.addFields(generatorClassNode);
//
//        generatorClassNode.version = getOpcodesVersion();
//        generatorClassNode.access = Opcodes.ACC_PUBLIC;
//        generatorClassNode.name = "dejain/generator/ASMGenerator" + mp.generatorCount;
//        generatorClassNode.superName = "java/lang/Object";
//        MethodNode generatorMethod = new MethodNode(Opcodes.ACC_PUBLIC, "generator", Type.getMethodDescriptor(Type.getType(returnTypeClass)), null, new String[]{});
//        generatorClassNode.methods.add(generatorMethod);
//
//        MethodNode defaultConstructor = new MethodNode(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null);
//        defaultConstructor.visitCode();
//        defaultConstructor.visitVarInsn(Opcodes.ALOAD, 0);
//        defaultConstructor.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
//        defaultConstructor.visitInsn(Opcodes.RETURN);
//        defaultConstructor.visitMaxs(1,1);
//        defaultConstructor.visitEnd();
//        generatorClassNode.methods.add(defaultConstructor);
//
//        GeneratorAdapter generatorAdapter = new GeneratorAdapter(generatorMethod, generatorMethod.access, generatorMethod.name, generatorMethod.desc);
//        MethodAST.toCode(new Transformation<>(generatorClassNode), body, new MethodAST.MethodCodeGenerator(generatorAdapter, null));
//
//        SingleClassLoader classLoader = new SingleClassLoader(generatorClassNode);
//        Class<?> generatorClass2 = classLoader.loadClass();
//        try {
//            bodyAsMethod = generatorClass2.getMethod("generator", null);
//        } catch (NoSuchMethodException ex) {
//            Logger.getLogger(MetaExpressionAST.class.getName()).log(Level.SEVERE, null, ex);
//        } catch (SecurityException ex) {
//            Logger.getLogger(MetaExpressionAST.class.getName()).log(Level.SEVERE, null, ex);
//        }
//
//        mp.generatorCount++;
//
//        resultType = new NameTypeAST(getRegion(), resultType(bodyAsMethod.getReturnType()));
    }

    public ExpressionAST convertToExpression(Object value, Class<?> returnType) {
        switch(returnType.getName()) {
            case "java.lang.String":
                return new StringLiteralAST(getRegion(), (String)value);
            case "int":
                return new IntLiteralAST(getRegion(), (int)value);
        }

        if(value instanceof ExpressionAST)
            return (ExpressionAST)value;

        return null;
    }

    private Class<?> resultType(Class<?> returnType) {
        switch(returnType.getName()) {
            case "java.lang.String":
            case "int":
                return LiteralAST.class;
        }

        if(returnType == ExpressionAST.class)
            return ExpressionAST.class;

        return null;
    }

    @Override
    public TypeAST resultType() {
        return null;
    }

    @Override
    public <T> T accept(CodeVisitor<T> visitor) {
        return visitor.visitMetaExpression(this);
    }
}