text:
var cadence = require('cadence')
var delta = require('delta')
var path = require('path')

var Interrupt = require('interrupt').createInterrupter('vizsla')
var logger = require('prolific.logger').createLogger('vizsla')

var PARSERS = {
    json: null,
    text: null,
    buffer: null,
    jsons: null,
    stream: null,
    dump: null
}

var SELECTORS = {
    json: {
        statusCode: 2,
        headers: {
            'content-type': 'application/json'
        },
        parser: 'json'
    },
    text: {
        statusCode: 2,
        parser: 'text'
    },
    buffer: {
        statusCode: 2,
        parser: 'buffer'
    },
    jsons: {
        statusCode: 2,
        headers: {
            'content-type': 'application/json-stream'
        },
        parser: 'jsons'
    },
    stream: {
        statusCode: 2,
        parser: 'stream'
    },
    dump: {
        statusCode: 2,
        parser: 'dump'
    }
}

function Parse (parsers) {
    this._parsers = parsers || []
}

Parse.prototype.descend = cadence(function (async, descent) {
    async(function () {
        descent.descend(async())
    }, function (body, response) {
        var parsers = [].concat(this._parsers, {}), parser = null
        for (var i = 0, I = parsers.length; parser == null && i < I; i++) {
            var selector = parsers[i]
            var selected = true
            if (typeof selector == 'string') {
                Interrupt.assert(SELECTORS[selector], 'unknown:parser', {
                    selector: selector,
                    parse: this._parsers
                })
                selector = SELECTORS[selector]
            }
            if (selector.statusCode) {
                if (selector.statusCode < 10) {
                    selected = selector.statusCode == Math.floor(response.statusCode / 100)
                } else {
                    selected = selector.statusCode == response.statusCode
                }
            }
            if (selected && selector.headers) {
                for (var header in selector.headers) {
                    var test = selector.headers[header]
                    var value = response.headers[header]
                    if (value == null) {
                        selected = false
                    } else {
                        if (header == 'content-type') {
                            value = response.type.type
                        }
                        if (typeof test == 'string') {
                            selected = value == test
                        } else {
                            selected = test.test(value)
                        }
                    }
                    if (!selected) {
                        break
                    }
                }
            }
            if (selected) {
                selected = selector.parser || 'stream'
                if (typeof selected == 'string') {
                    parser = PARSERS[selected]
                    if (parser == null) {
                        parser = PARSERS[selected] = require(path.join(__dirname, selected))()
                    }
                } else {
                    parser = selected
                }
            }
        }
        async(function () {
            parser.parse(body, response, async())
        }, function (body) {
            return [ body, response ]
        })
    })
})

module.exports = function (parsers) {
    return new Parse(parsers)
}


text:
<?php

namespace Catalog\FileGalleryBundle\Entity\Repository;

use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\EntityManager;
use Symfony\Component\HttpFoundation\Session\Session;

class FileCategoryRepository extends EntityRepository
{
    private $session;

    public function __construct(EntityManager $em, ClassMetadata $class) {
        parent::__construct($em, $class);
        global $kernel;
        if($kernel instanceOf \AppCache)
            $kernel = $kernel->getKernel();
        $this->session = $kernel->getContainer()->get('session');
    }

    public function getListCategory() {
        $q = $this->_em->createQueryBuilder();
        $query = $q->select("c")
                ->from("CatalogFileGalleryBundle:FileCategory", "c")
                ->where('c.project = :project')
                ->setParameter('project', self::getProject())
                ->addOrderBy('c.title');

        return $query;
    }

    private function getProject(){
        return $this->_em->getRepository('CatalogProjectBundle:Project')->find($this->session->get('project_id'));
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.camel.component.rest.openapi;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;

import com.github.tomakehurst.wiremock.WireMockServer;
import org.apache.camel.CamelContext;
import org.apache.camel.RoutesBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.rest.RestEndpoint;
import org.apache.camel.converter.jaxb.JaxbDataFormat;
import org.apache.camel.test.junit5.CamelTestSupport;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;

import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;

public class RestOpenApiComponentV3Test extends CamelTestSupport {

    public static WireMockServer petstore = new WireMockServer(wireMockConfig().dynamicPort());

    static final Object NO_BODY = null;

    public String componentName;

    @BeforeAll
    public static void startWireMockServer() {
        petstore.start();
    }

    @AfterAll
    public static void stopWireMockServer() {
        petstore.stop();
    }

    @Override
    public void setUp() {
    }

    @BeforeEach
    public void resetWireMock() {
        petstore.resetRequests();
    }

    public void doSetUp(String componentName) throws Exception {
        this.componentName = componentName;
        super.setUp();
    }

    @ParameterizedTest
    @MethodSource("knownProducers")
    public void shouldBeAddingPets(String componentName) throws Exception {
        doSetUp(componentName);

        final Pet pet = new Pet();
        pet.name = "Jean-Luc Picard";

        final Pet created = template.requestBody("direct:addPet", pet, Pet.class);

        assertNotNull(created);

        assertEquals(Integer.valueOf(14), created.id);

        petstore.verify(
                postRequestedFor(urlEqualTo("/api/v3/pet")).withHeader("Accept", equalTo("application/xml, application/json"))
                        .withHeader("Content-Type", equalTo("application/xml")));
    }

    @ParameterizedTest
    @MethodSource("knownProducers")
    public void shouldBeGettingPetsById(String componentName) throws Exception {
        doSetUp(componentName);

        final Pet pet = template.requestBodyAndHeader("direct:getPetById", NO_BODY, "petId", 14, Pet.class);

        assertNotNull(pet);

        assertEquals(Integer.valueOf(14), pet.id);
        assertEquals("Olafur Eliason Arnalds", pet.name);

        petstore.verify(getRequestedFor(urlEqualTo("/api/v3/pet/14")).withHeader("Accept",
                equalTo("application/xml, application/json")));
    }

    @ParameterizedTest
    @MethodSource("knownProducers")
    public void shouldBeGettingPetsByIdSpecifiedInEndpointParameters(String componentName) throws Exception {
        doSetUp(componentName);

        final Pet pet = template.requestBody("direct:getPetByIdWithEndpointParams", NO_BODY, Pet.class);

        assertNotNull(pet);

        assertEquals(Integer.valueOf(14), pet.id);
        assertEquals("Olafur Eliason Arnalds", pet.name);

        petstore.verify(getRequestedFor(urlEqualTo("/api/v3/pet/14")).withHeader("Accept",
                equalTo("application/xml, application/json")));
    }

    @ParameterizedTest
    @MethodSource("knownProducers")
    public void shouldBeGettingPetsByIdWithApiKeysInHeader(String componentName) throws Exception {
        doSetUp(componentName);

        final Map<String, Object> headers = new HashMap<>();
        headers.put("petId", 14);
        headers.put("api_key", "dolphins");
        final Pet pet = template.requestBodyAndHeaders("direct:getPetById", NO_BODY, headers, Pet.class);

        assertNotNull(pet);

        assertEquals(Integer.valueOf(14), pet.id);
        assertEquals("Olafur Eliason Arnalds", pet.name);

        petstore.verify(
                getRequestedFor(urlEqualTo("/api/v3/pet/14")).withHeader("Accept", equalTo("application/xml, application/json"))
                        .withHeader("api_key", equalTo("dolphins")));
    }

    @ParameterizedTest
    @MethodSource("knownProducers")
    public void shouldBeGettingPetsByIdWithApiKeysInQueryParameter(String componentName) throws Exception {
        doSetUp(componentName);

        final Map<String, Object> headers = new HashMap<>();
        headers.put("petId", 14);
        headers.put("api_key", "dolphins");
        final Pet pet = template.requestBodyAndHeaders("altPetStore:getPetById", NO_BODY, headers, Pet.class);

        assertNotNull(pet);

        assertEquals(Integer.valueOf(14), pet.id);
        assertEquals("Olafur Eliason Arnalds", pet.name);

        petstore.verify(getRequestedFor(urlEqualTo("/api/v3/pet/14?api_key=dolphins")).withHeader("Accept",
                equalTo("application/xml, application/json")));
    }

    @ParameterizedTest
    @MethodSource("knownProducers")
    public void shouldBeGettingPetsByStatus(String componentName) throws Exception {
        doSetUp(componentName);

        final Pets pets = template.requestBodyAndHeader("direct:findPetsByStatus", NO_BODY, "status", "available",
                Pets.class);

        assertNotNull(pets);
        assertNotNull(pets.pets);
        assertEquals(2, pets.pets.size());

        petstore.verify(
                getRequestedFor(urlPathEqualTo("/api/v3/pet/findByStatus")).withQueryParam("status", equalTo("available"))
                        .withHeader("Accept", equalTo("application/xml, application/json")));
    }

    @Override
    protected CamelContext createCamelContext() throws Exception {
        final CamelContext camelContext = super.createCamelContext();

        final RestOpenApiComponent component = new RestOpenApiComponent();
        component.setComponentName(componentName);
        component.setHost("http://localhost:" + petstore.port());
        component.setSpecificationUri(RestOpenApiComponentV3Test.class.getResource("/openapi-v3.json").toURI());

        camelContext.addComponent("petStore", component);

        final RestOpenApiComponent altPetStore = new RestOpenApiComponent();
        altPetStore.setComponentName(componentName);
        altPetStore.setHost("http://localhost:" + petstore.port());
        altPetStore.setSpecificationUri(RestOpenApiComponentV3Test.class.getResource("/alt-openapi.json").toURI());

        camelContext.addComponent("altPetStore", altPetStore);

        return camelContext;
    }

    @Override
    protected RoutesBuilder createRouteBuilder() {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                final JAXBContext jaxbContext = JAXBContext.newInstance(Pet.class, Pets.class);

                final JaxbDataFormat jaxb = new JaxbDataFormat(jaxbContext);

                jaxb.setJaxbProviderProperties(Collections.singletonMap(Marshaller.JAXB_FORMATTED_OUTPUT, false));

                from("direct:getPetById").to("petStore:getPetById").unmarshal(jaxb);

                from("direct:getPetByIdWithEndpointParams").to("petStore:getPetById?petId=14").unmarshal(jaxb);

                from("direct:addPet").marshal(jaxb).to("petStore:addPet").unmarshal(jaxb);

                from("direct:findPetsByStatus").to("petStore:findPetsByStatus").unmarshal(jaxb);
            }
        };
    }

    public static Iterable<String> knownProducers() {
        return Arrays.asList(RestEndpoint.DEFAULT_REST_PRODUCER_COMPONENTS);
    }

    @BeforeAll
    public static void setupStubs() throws IOException, URISyntaxException {
        petstore.stubFor(get(urlEqualTo("/openapi-v3.json")).willReturn(aResponse().withBody(
                Files.readAllBytes(Paths.get(RestOpenApiComponentV3Test.class.getResource("/openapi-v3.json").toURI())))));

        petstore.stubFor(post(urlEqualTo("/api/v3/pet"))
                .withRequestBody(equalTo(
                        "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><Pet><name>Jean-Luc Picard</name></Pet>"))
                .willReturn(aResponse().withStatus(HttpURLConnection.HTTP_CREATED)
                        .withBody("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><Pet><id>14</id></Pet>")));

        petstore.stubFor(
                get(urlEqualTo("/api/v3/pet/14")).willReturn(aResponse().withStatus(HttpURLConnection.HTTP_OK).withBody(
                        "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><Pet><id>14</id><name>Olafur Eliason Arnalds</name></Pet>")));

        petstore.stubFor(get(urlPathEqualTo("/api/v3/pet/findByStatus")).withQueryParam("status", equalTo("available"))
                .willReturn(aResponse().withStatus(HttpURLConnection.HTTP_OK).withBody(
                        "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><pets><Pet><id>1</id><name>Olafur Eliason Arnalds</name></Pet><Pet><name>Jean-Luc Picard</name></Pet></pets>")));

        petstore.stubFor(get(urlEqualTo("/api/v3/pet/14?api_key=dolphins"))
                .willReturn(aResponse().withStatus(HttpURLConnection.HTTP_OK).withBody(
                        "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><Pet><id>14</id><name>Olafur Eliason Arnalds</name></Pet>")));
    }

}


text:
using System;
using System.IO;

namespace XenCenterLib
{
    public class StreamUtilities
    {
        /// <summary>
        /// Perform a copy of the contents of one stream class to another in a buffered fashion
        ///
        /// Buffer size is a hard-coded 2Mb
        /// </summary>
        /// <param name="inputData">Source data</param>
        /// <param name="outputData">Target stream</param>
        public static void BufferedStreamCopy(Stream inputData, Stream outputData)
        {
            if( inputData == null)
                throw new ArgumentNullException("inputData", "BufferedStreamCopy argument cannot be null");

            if (outputData == null)
                throw new ArgumentNullException("outputData", "BufferedStreamCopy argument cannot be null");

            const long bufferSize = 2*1024*1024;

            byte[] buffer = new byte[bufferSize];
            int n;
            while ((n = inputData.Read(buffer, 0, buffer.Length)) > 0)
            {
                outputData.Write(buffer, 0, n);
            }

            outputData.Flush();
        }
    }
}


text:
import sys
# import re
# import os
# import string
import random as rnd
import numpy as np
import pandas as pd
import subprocess as sub
import matplotlib.pyplot as plt
from Bio import SeqIO
from Bio import SeqRecord
# import Bio
import copy
import re

import scipy.sparse as sparse

import matplotlib as mpl
mpl.rcParams['lines.linewidth'] = 4
# from matplotlib.patches import Polygon
import matplotlib.transforms as transforms

#Font sizes and stuff ...
mpl.rcParams['font.family']=['FreeSans']
# fig,ax = plt.subplots(nrows=1,ncols=1,figsize=(9,6))
# # ax = fig.add_subplot(111)
# plt.subplots_adjust(left=0.1,right=0.80,bottom=0.1,top=0.9)
fontsize_xy_label = 21
fontsize_xy_ticks_labels = 20
fontsize_useles_title = 15
linewidth_plot = 6

# before fixing the UTR problem seg lengthes were :
# seg_lengths = {'seg1_H1N1':2314, 'seg2_H1N1':2302, 'seg3_H1N1':2203, 'seg4_H1N1':1776, 'seg5_H1N1':1497, 'seg6_H1N1':1427, 'seg7_H1N1':1006, 'seg8_H1N1':870}

#####################################
#####################################
#####################################
class influenza(object):
    """influenza is a class describing all possible feature of a given influenza genome,
    including genome itself, lengths of segments, ORFs, RNA profiles etc."""
    #
    #
    #
    def __init__(self, genome_fname, ORF_fname, mutations=None):
        # read influenza genome ...
        self.genome = dict([(seq.id,seq.seq)for seq in SeqIO.parse(genome_fname,"fasta")])
        # length of the segments ...
        self.seglen = dict([(segid,len(self.genome[segid])) for segid in self.genome])
        # genome length ...
        self.genlen = sum(self.seglen.values())
        # number of segments ...
        self.segnum = len(self.genome)
        # name of the file with the genome ...
        self.genome_fname = genome_fname
        # just segment's names/ids - whatever ...
        self.segments = sorted(self.seglen.keys())
        # proteins ...
        # self.segcode = dict([(i,name) for i,name in enumerate(['PB2','PB1','PA','HA','NP','NA','M1/M2','NS1/NEP'])])
        # initialize ORF data using segment id-s from genome_fname file ...
        ORF_per_segment = {}
        for seg in self.segments:
            ORF_per_segment[seg] = {}
        # read ORF data ...
        with open(ORF_fname,'r') as fp:
            for line in fp.readlines():
                line = line.strip().split()
                #####################################################
                #    PERFORM SOME SIMPE ORF CHECKS ALONG ...
                #####################################################
                seg = line[0] # make sure you have the same segment ids in genome_fname and ORF_fname ...
                # the keys must coincide with the ones from genome_fname file ...
                if seg not in self.segments:
                    raise ValueError("segment ids in %s must coincide with the ids in %s!"%(ORF_fname,genome_fname))
                # bound must be specified with int numbers ...
                # shift them left by 1, to make them 0-numbered ...
                orf_bounds = [int(_)-1 for _ in line[2:]]
                # >0, even # of numbers ...
                if (len(orf_bounds)%2>0)or(len(orf_bounds)==0):
                    raise ValueError("ORF boundaries must be specified with even number of coordinates!")
                # form pairs: [1,2,3,4] -> [(1,2),(3,4)]
                orf_bounds = zip(orf_bounds[0::2],orf_bounds[1::2])
                # check 3-multiplicity for the ORF length ...
                if sum((oe-ob+1) for ob,oe in orf_bounds)%3 != 0:
                    raise ValueError("ORF length must be multiple of 3! Corrupted ORF prevents codons indentification!")
                # store ORF's translation(protein) name with the boundaries ...
                protein_id = line[1]
                ORF_per_segment[seg][protein_id] = orf_bounds
        self.orf = ORF_per_segment
    #
    #
    #
    #
    def __parser_unpaired(self,filename,unpaired):
        with open(filename,'r') as fp:
            lines = fp.readlines()
        #
        # where to store the data ...
        data = {}
        for i in xrange(unpaired):
            data[i+1] = []
        #
        # process unpaired-1 of lines with NA values ...
        skip = 2
        convert = (lambda x: float(x) if x!='NA' else None)
        for line in lines[skip:skip+unpaired-1]:
            line = line.strip().split()
            for i,probab in enumerate(line[1:]):
                data[i+1].append(convert(probab))
        # process those without NA values ...
        for line in lines[skip+unpaired-1:]:
            line = line.strip().split()
            for i,probab in enumerate(line[1:]):
                data[i+1].append(float(probab))
        # data is stored and populated now !
        return data
    #
    #
    #
    def __parser_pairhood(self,filename):
        with open(filename,'r') as fp:
            lines = fp.readlines()
        #
        # where to store the data ...
        data = {'idx':[],'jdx':[],'p':[]}
        # parse indexes and probabilities ...
        for line in lines:
            i,j,p = line.strip().split()
            data['idx'].append(int(i))
            data['jdx'].append(int(j))
            data['p'].append(float(p))
        # data is stored and populated now !
        return data
    #
    #
    #
    def calculate_rna_profiles(self,genome_fname,window=70,length=50,unpaired=3,pairing=False,unpairing=True):
        # to get the unpaired probabilities ...
        # cat H1N1FULL.fa |RNAplfold -W70 -L50 -u3
        # generates dp.ps files along with the _lunp(what we need) files
        #
        #
        # to get the probabilities of pairing for nucs i,j based on the entire ensemble ...
        # cat H1N1FULL.fa |RNAplfold -W70 -L50 -o
        # generates _basepairs COO sparse matrix style - really easy to parse! (i j probab), i<j
        #
        #
        # file prefixes are segment ids !, so that's really handy as well.
        #
        # entire fasta file with multiple sequences can be submitted to the program >
        # number of output files will match the number of fasta entries in the file!
        #
        cmd_unpaired = "cat %s | RNAplfold -W%d -L%d -u%d  >/dev/null 2>/dev/null"%(genome_fname,window,length,unpaired)
        cmd_pairhood = "cat %s | RNAplfold -W%d -L%d -o    >/dev/null 2>/dev/null"%(genome_fname,window,length)
        # get unpaired stats ...
        if pairing:
            retcode = sub.call(cmd_pairhood,shell=True)
            if retcode:
                print >> sys.stderr, "RNAplfold failed! RNA profile is not generated"
                return
            # now we have all these files available for us to parse ...
            pairhood_fnames = dict([ (name,"%s_basepairs"%name) for name in self.genome])
            #
            # now let's deal with the pairhood probabilities ...
            pairhood_data = {}
            for seg in pairhood_fnames:
                pairhood_data[seg] = self.__parser_pairhood(pairhood_fnames[seg])
            self.rna_pairhood = pairhood_data
        #
        #
        # extract unpaired probabilities ...
        if unpairing:
            retcode = sub.call(cmd_unpaired,shell=True)
            if retcode:
                print >> sys.stderr, "RNAplfold failed! RNA profile is not generated"
                return
            # now we have all these files available for us to parse ...
            unpaired_fnames = dict([ (name,"%s_lunp"%name) for name in self.genome])
            #
            # generate 'unpaired'-number of empty dictionaries here ...
            unpaired_data = dict([ (l,{}) for l in range(1,unpaired+1) ])
            for seg in unpaired_fnames:
                parsed_data = self.__parser_unpaired(unpaired_fnames[seg],unpaired)
                for l in range(1,unpaired+1):
                    unpaired_data[l][seg] = parsed_data[l]
            # unpaired data structured by the l number first, and then by the segment ...
            self.rna_unpaired = unpaired_data
    #
    #
    #
    def calculate_rna_lMFE(self,length=50):
        #
        genome_fname=self.genome_fname
        #
        cmd_lMFE = "cat %s | RNALfold -L%d"%(genome_fname,length)
        #
        try:
            out = sub.check_output(cmd_lMFE,shell=True)
        except sub.CalledProcessError:
            print "could not run '%s'"%cmd_lMFE
            return
        #
        #
        out_by_seg = {}
        # strip and split output segment by segment ...
        for lmfe_lines in out.strip().strip('>').split('>'):
            # for each segment - split data by newline ...
            lmfe_lines = lmfe_lines.strip().split('\n')
            # first line is the segment name ...
            seg = lmfe_lines[0]
            # the all but the last two lines are the local MFEs in dot-bracket format with dG and a starting point ...
            lmfes = lmfe_lines[1:-2]
            # lmfe_lines[-2:] - is just RNA sequence and some kind of total energy or something ...
            data = []
            for lmfe in lmfes:
                # replace('( ','(') will fight the situation ( -0.45) vs (-10.20) ...
                # yet (  0.11) will fail then - LOOK FOR IT ...
                item = lmfe.replace('( ','(').split()
                if len(item) != 3:
                    print "could not parse local MFE: %s"%lmfe
                    return
                # parse that stuff and store in an array ...
                structure = item[0]
                str_len = len(structure)
                delta_g = float(item[1].strip('()'))
                start = int(item[2])
                data.append((structure,start,str_len,delta_g))
            out_by_seg[seg] = data
        ############################################
        #
        # strore it in the self stuff ...
        self.local_MFE = out_by_seg
    #
    #
    # Local MFE example output ...
    #
    #
    # >seg8_H1N1FULL
    # .(((((((((...)))))..)))). ( -7.90)  123
    # .((((.....(((((...))))).....)))). (-10.30)  118
    # .((....)). ( -1.60)    1
    # AGCGAAAGCAGGGUGGCAAAGACAUAAUGGAUUCCCACACUGUGUAC...
    #  (-199.00)
    #
    # segments are overlapping or not ?!
    def __get_overlap(self,interval1,interval2):
        idx1,start1,str_len1 = interval1
        idx2,start2,str_len2 = interval2
        # L = max(A.left,B.left)
        # R = min(A.right,B.right)
        # L <= R - <=> intersection!!! overlap
        L = max(start1, start2)
        R = min(start1+(str_len1-1), start2+(str_len2-1))
        return (L <= R)
    #
    # calculate local RNA profile of a flu genome taking NP attraction into account(dg_NP threshold) ...
    def calculate_rna_lMFE_optimized(self, dg_NP, windows=[24,36,]):
        #
        genome_fname=self.genome_fname
        #
        mfe = {}
        for seg in self.segments:
            mfe[seg] = {}
        #
        # calculate local MFE structures for several window sizes,
        # to get a good grip on possible stable structures and their substructures ...
        for length in windows:
            self.calculate_rna_lMFE(length=length)
            for seg in self.segments:
                mfe[seg][length] = self.local_MFE[seg]
        # structures are stored in 'mfe':
        # organized first by segment, next by the window size
        #
        # next, we are calculating an overlap matrix, and store it in COO format:
        overlap_mat = {}
        overlat_sparse_mat = {}
        for seg in self.segments:
            #
            # mixing different folding lengths to find optimal folding solution ...
            mfe[seg] = pd.DataFrame(
                [(v1,v2,v3,v4,key) for key,values in mfe[seg].iteritems() for v1,v2,v3,v4 in values],
                columns = ['struct','start','str_len','dG','lfold'])
            #
            # sort by the starting point ... (1-indexed)
            mfe[seg] = mfe[seg].sort(columns=['start',]).reset_index(drop=True)
            # IMPORTANT adjustments to the segment dataframe ...
            # each structured rna segment includes 2 unpaired nucleotides (left & right)
            # we adjust corresponding segment lengths ...
            mfe[seg].str_len -= 2
            #
            # let's add energy per nt here
            mfe[seg]['dg_nuc'] = np.true_divide(mfe[seg]['dG'],mfe[seg]['str_len'])
            #
            # and objective coefficients along the way:
            # this is simply the dG of the structural element, corrected for the NP attraction ...
            mfe[seg]['objective_coeff'] = ( mfe[seg]['dg_nuc'] - dg_NP ) * mfe[seg]['str_len']
            #
            ##########################################################
            # clean redundant data:
            # drop duplicates first, ('lfold' is not taken inot account here ...)
            mfe[seg] = mfe[seg].drop_duplicates(subset=['struct', 'start', 'str_len', 'dG', 'dg_nuc', 'objective_coeff'])
            # drop those that are melted by NP,
            mfe[seg] = mfe[seg][mfe[seg]['objective_coeff']<0.0]
            # reset index - just in case ...
            mfe[seg] = mfe[seg].reset_index(drop=True)
            # looks like it's the best we can do so far...
            ##########################################################
            #
            # start indexes are actually OK, if you reconsider RNA sequences as 0-based indexed.
            #
            rna_seg_num = mfe[seg].shape[0]
            rna_str_seg = list(mfe[seg][['start','str_len']].itertuples())
            # integer matrix of overlap information.
            overlap_mat[seg] = []
            # overlap_mat[seg] = np.zeros((rna_seg_num,rna_seg_num),dtype=np.int)
            #
            for i in range(rna_seg_num):
                for j in range(i+1,rna_seg_num):
                    if self.__get_overlap(rna_str_seg[i],rna_str_seg[j]):
                        tmp_vec = np.zeros(rna_seg_num,dtype=np.int)
                        tmp_vec[i] = 1
                        tmp_vec[j] = 1
                        # overlap_mat[seg][i,i] = 1 # little bit redundant, but OK ...
                        # overlap_mat[seg][i,j] = 1
                        overlap_mat[seg].append(tmp_vec)
            overlap_mat[seg] = np.asarray(overlap_mat[seg],dtype=np.int)
            #
            overlat_sparse_mat[seg] = sparse.coo_matrix(overlap_mat[seg])
        ################################################################################
        ################################################################################
        ################################################################################
        # cycle through all of the segments ...
        for seg in self.segments:
            print "working on segment %s"%seg
            #
            fname_obj = "objective.dat"
            fname_cst = "sparse.dat"
            #
            # writing the sparse matrix of the constraints ...
            with open(fname_cst,'w') as fp:
                # glpk uses 1-based indexing ...
                # let's write the total number of lines at first:
                fp.write("%d\n" % len(overlat_sparse_mat[seg].data))
                #
                index = 1
                for i,j,v in zip(overlat_sparse_mat[seg].row+1,overlat_sparse_mat[seg].col+1,overlat_sparse_mat[seg].data):
                    fp.write("%d a%d%d %d %d %d\n" % (index,i,j,i,j,v))
                    index += 1
            ##############################
            with open(fname_obj,'w') as fp:
                # total number of items first ...
                fp.write("%d\n" % mfe[seg]['objective_coeff'].shape[0])
                # all items second ...
                for index,dg in mfe[seg]['objective_coeff'].iteritems():
                    fp.write("%d a%d %.2f\n" % (index+1,index+1,dg))
            # run the optimizer ...
            cmd_per_seg = "./rnaglpk/svbin/run_bip %s %s"%(fname_obj,fname_cst)
            result = sub.check_output(cmd_per_seg,shell=True)
            # ...
            expected_lines_useful = mfe[seg]['objective_coeff'].shape[0]
            result_out = np.asarray( [ int(i) for i in result.strip().split('\n')[-expected_lines_useful:] ] )
            # ...
            mfe[seg]['inc_rna'] = result_out
        #
        # now store that MFE object dictionary as an influenza class attribute ...
        self.optimal_MFE = mfe
        #
        #
        # we'd also calculate the dg profile over each segment: 0 if NP-bound, dg(per nucleotide) if belongs to some stable structure ...
        #
        dg_profile = {}
        pairing_profile = {}
        loops_profile = {}
        mfe_loops = {}
        #
        pairing_dict = {'.':1,'(':2,')':2}
        # big hairpin loops of 4 nt and more ...
        big_loop = re.compile('\.{4,}')
        #
        # now let's try to plot that stuff ...
        for seg in self.segments:
            seglen = self.seglen[seg]
            # take only those RNA that've been selected by optimizer ...
            seg_struct = mfe[seg][mfe[seg]['inc_rna']==1]
            # let's generate RNA profiles based on the optimized results ...
            # print seglen
            dg_profile[seg] = np.zeros(seglen)
            pairing_profile[seg] = np.zeros(seglen,dtype = np.int)
            loops_profile[seg] = np.zeros(seglen,dtype = np.int)
            mfe_loops[seg] = []
            #
            for dat in seg_struct.iterrows():
                struct = dat[1]['struct']
                start = dat[1]['start']
                str_len = dat[1]['str_len']
                dg_nuc = dat[1]['dg_nuc']
                # search big loops ...
                for res in big_loop.finditer(struct):
                    # the profile of big loops, those potentially available for intersegmental pairing ...
                    loops_profile[seg][start+res.start():start+res.end()] = 1
                    #  sequences of those big loops, just to look at who they really are ...
                    mfe_loops[seg].append(( start+res.start(), self.genome[seg][start+res.start():start+res.end()] ))
                    #
                dg_profile[seg][start:start+str_len] = dg_nuc
                pairing_profile[seg][start:start+str_len] = [ pairing_dict[char] for char in struct[1:-1] ]
                # maybe struct[1:-1] if 0 and -1 are '.'
        #
        # now store that as an influenza class attribute ...
        self.dg_profile = dg_profile
        self.pair_profile = pairing_profile
        self.loops_profile = loops_profile
        self.loops = mfe_loops
    #
    #
    #
    #
    #
    #
    #
    #
    #
    #
    # BROWSER WILL BREAK MOST LIKELY, BECAUSE ORF's DETERMINATION HAS BEEN UPDATED ...
    def genome_browser(self):
        """A function returning figure and axis for the influenza genome browser.
        It generates 8 empty panels of lengths proportional to the segment and
        allows """
        fig = plt.figure(figsize=(12,12))
        #
        # axs = [None for _ in range(self.segnum)]
        #
        # horizontal ...
        width_longestseq = 0.9
        left = (1. - width_longestseq)/2.
        # vertical ...
        bottom_lowest = 0.05
        v_delta = bottom_lowest
        span_to_height_coeff = 0.8
        num_of_spans = self.segnum - 1
        height = (1.-2.*v_delta)/(self.segnum + span_to_height_coeff*num_of_spans)
        v_span = span_to_height_coeff*height
        #
        #
        bottom = bottom_lowest
        max_seglen = float(max(self.seglen.values()))
        axs = {}
        # starting from the longest segment down to the shortest one ...
        for seg,seglen in sorted(self.seglen.items(),key=lambda x: (-x[1],x[0]),reverse=True):
            coeff = seglen/max_seglen
            axs[seg] = fig.add_axes([left, bottom, width_longestseq*coeff, height])
            bottom += height + v_span
        #
        #
        #go through axes to setup all the limits and  stuff ...
        # for i,ax in enumerate(axs):
        for seg,ax in axs.items():
            # DRAW ORF AT EVERY AXIS ...
            a,b = self.orf[seg]
            ax.axvspan(xmin=a,xmax=b,alpha=0.9, facecolor='0.9', edgecolor='none',zorder=1)
            #
            # draw middle lines ...
            ax.plot([0,1],[0.5,0.5],linestyle='-',color='k',linewidth=1.,transform=ax.transAxes)
            # #
            # # fontsize = 8
            x_step = 500 if self.seglen[seg]>=1500 else 200
            ax.set_xlim((0, self.seglen[seg] ))
            # no axis labels ...
            # ax.set_xlabel('nucleotide',fontsize=fontsize_xy_label-3)
            # ax.set_ylabel('SNP group',fontsize=fontsize_xy_label-3)\
            trans = transforms.blended_transform_factory(ax.transData, ax.transAxes)
            ax.xaxis.set_label_coords(500,-0.35*0.5,transform=trans)
            ax.set_xticks(np.arange(0, self.seglen[seg] , x_step))
            ax.set_xticklabels([1]+range(x_step,self.seglen[seg],x_step),fontsize=fontsize_xy_ticks_labels)
            # #
            # #
            # # we dont know much about y-range and limits - it'll be controlled outside!
            # # it'll depend on the type of data that we'll plot there ...
            # ylim = 1
            # ax.set_ylim((-1.*ylim,ylim))
            # yticks_range = range(ylim+1)
            # # clean y-axis just for clarity ...
            ax.set_yticks([])
            ax.set_yticklabels([])
            # # the segment length bar ...
            # # ax.bar(flu.seg_lengths[current_seg_name]+0.01*flu.seg_lengths['seg%d_H1N1FULL' % 1],ylim,width=5,color='black')
            ax.tick_params(axis='both', which='major', labelsize=fontsize_xy_ticks_labels-3)
            ax.set_title( seg ,fontsize=fontsize_xy_label-3)
        return (fig,axs)

# influenza mutant class ...
class influenza_mutant(influenza):
    """docstring for influenza_mutant:
    constructor takes an existing instance of the influenza object
    and modifies it in accordabce with the SNP requirements
    which can be muttion rate, genome positions, etc. (mutation rate - only now!)"""
    def __init__(self, wt, snp, fname='tmp.mutant.fasta'):
        # super(influenza_mutant, self).__init__()
        # self.arg = arg
        # make wt sequences mutable:
        local_genome_copy = dict([(seg,wt.genome[seg].tomutable())for seg in wt.genome])
        #
        # if snp is float, i.e. mutation rate ...
        #
        # let's store SNPs, so that we can access them afterwards ...
        self.snp = {}
        #
        for seg in wt.seglen:
            # number of SNPs to make
            snp_num = int(wt.seglen[seg]*float(snp))
            # unique indexes for SNP placement
            snp_idx = rnd.sample(xrange(wt.seglen[seg]),snp_num)
            #
            self.snp[seg] = np.asarray(snp_idx)
            # SNP placement ...
            for idx in snp_idx:
                local_genome_scopy[seg][idx] = rnd.choice(list( set('ATGC')-set(local_genome_copy[seg][idx]) ))
        ######################################################################################
        self.genome = dict([(seg,local_genome_copy[seg].toseq())for seg in local_genome_copy])
        #
        # # read influenza genome ...
        # self.genome = dict([(seq.id,seq.seq)for seq in SeqIO.parse(genome_fname,"fasta")])
        # # length of the segments ...
        self.seglen = copy.deepcopy(wt.seglen)
        # genome length ...
        self.genlen = sum(self.seglen.values())
        # number of segments ...
        self.segnum = len(self.genome)
        # # proteins ...
        # self.segcode = copy.deepcopy(wt.segcode)
        # read ORF data ...
        self.orf = copy.deepcopy(wt.orf)
        #
        #
        # ONE MORE THING!!!
        # mutated genome must be written to the disk! otherwise, we have no way of refolding it ...
        self.genome_fname = fname
        ####
        SeqIO.write([SeqRecord.SeqRecord(seq=self.genome[seg],id=seg,name='',description='') for seg in self.genome],self.genome_fname,'fasta')
        # now construction is complete, mutant genome is stored and can be accessed by RNA-folders; fname is a calss variable ...


text:
package org.apache.olingo.odata2.janos.processor.core.data.access;

import org.apache.olingo.odata2.api.edm.EdmMapping;
import org.apache.olingo.odata2.api.edm.EdmProperty;
import org.apache.olingo.odata2.api.exception.ODataException;
import org.apache.olingo.odata2.api.exception.ODataNotImplementedException;
import org.apache.olingo.odata2.janos.processor.api.data.access.ValueAccess;
import org.apache.olingo.odata2.janos.processor.core.util.AnnotationHelper;

/**
 *
 */
public class AnnotationValueAccess implements ValueAccess {
  private final AnnotationHelper annotationHelper = new AnnotationHelper();

  /**
   * Retrieves the value of an EDM property for the given data object.
   * @param data the Java data object
   * @param property the requested {@link EdmProperty}
   * @return the requested property value
   */
  @Override
  public <T> Object getPropertyValue(final T data, final EdmProperty property) throws ODataException {
    if (data == null) {
      return null;
    } else if (annotationHelper.isEdmAnnotated(data)) {
      return annotationHelper.getValueForProperty(data, property.getName());
    }
    throw new ODataNotImplementedException(ODataNotImplementedException.COMMON);
  }

  /**
   * Sets the value of an EDM property for the given data object.
   * @param data the Java data object
   * @param property the {@link EdmProperty}
   * @param value the new value of the property
   */
  @Override
  public <T, V> void setPropertyValue(final T data, final EdmProperty property, final V value) throws ODataException {
    if (data != null) {
      if (annotationHelper.isEdmAnnotated(data)) {
        annotationHelper.setValueForProperty(data, property.getName(), value);
      } else {
        throw new ODataNotImplementedException(ODataNotImplementedException.COMMON);
      }
    }
  }

  /**
   * Retrieves the Java type of an EDM property for the given data object.
   * @param data the Java data object
   * @param property the requested {@link EdmProperty}
   * @return the requested Java type
   */
  @Override
  public <T> Class<?> getPropertyType(final T data, final EdmProperty property) throws ODataException {
    if (data == null) {
      return null;
    } else if (annotationHelper.isEdmAnnotated(data)) {
      Class<?> fieldType = annotationHelper.getFieldTypeForProperty(data, property.getName());
      if (fieldType == null) {
        throw new ODataException("No field type found for property " + property);
      }
      return fieldType;
    }
    throw new ODataNotImplementedException(ODataNotImplementedException.COMMON);
  }

  /**
   * Retrieves the value defined by a mapping object for the given data object.
   * @param data the Java data object
   * @param mapping the requested {@link EdmMapping}
   * @return the requested value
   */
  @Override
  public <T> Object getMappingValue(final T data, final EdmMapping mapping) throws ODataException {
    if (mapping != null && mapping.getMediaResourceMimeTypeKey() != null) {
      return annotationHelper.getValueForProperty(data, mapping.getMediaResourceMimeTypeKey());
    }
    return null;
  }

  /**
   * Sets the value defined by a mapping object for the given data object.
   * @param data the Java data object
   * @param mapping the {@link EdmMapping}
   * @param value the new value
   */
  @Override
  public <T, V> void setMappingValue(final T data, final EdmMapping mapping, final V value) throws ODataException {
    if (mapping != null && mapping.getMediaResourceMimeTypeKey() != null) {
      annotationHelper.setValueForProperty(data, mapping.getMediaResourceMimeTypeKey(), value);
    }
  }
}


text:
<SageTVPlugin>

  <Name>Save EPG channel selection on Exit</Name>

  <Identifier>SaveEPGChannelSelection</Identifier>

  <Description>Saves the user selected EPG channel on Exit and then restores it when the EPG is displayed.</Description>

  <Author>49studebaker</Author>

  <CreationDate>2010.06.21</CreationDate>

  <ModificationDate>2010.06.22</ModificationDate>

  <Version>1.0.1</Version>

<Dependency>

  <STV>SageTV7</STV>

  <MinVersion>7.0</MinVersion>

</Dependency>

<PluginType>STVI</PluginType>

<STVImport>SaveEPGChannelSelection.stvi</STVImport>

<Package>

  <PackageType>STVI</PackageType>

  <Location>https://github.com/OpenSageTV/sagetv-plugin-repo/releases/download/1/SaveEPGChannelSelection.zip</Location>

  <MD5>00AF3419DD8A7929E2ACB9B8182D83EB</MD5>

</Package>

<ReleaseNotes>

Version 1.0 - Initial release.

</ReleaseNotes>

</SageTVPlugin>


text:
import * as YUKA from "yuka";

const targetMesh = {matrix: new YUKA.Matrix4()};
const entityMesh = {matrix: new YUKA.Matrix4()};

// game entity setup
const entityManager = new YUKA.EntityManager();
const time = new YUKA.Time();

const target = new YUKA.GameEntity();
target.setRenderComponent(targetMesh, sync);

const entity = new YUKA.GameEntity();
entity.maxTurnRate = Math.PI * 0.5;
entity.setRenderComponent(entityMesh, sync);

entityManager.add(entity);
entityManager.add(target);
//
generateTarget();

const delta = time.update().getDelta();
entity.rotateTo(target.position, delta);
entityManager.update(delta);

function sync(entity: YUKA.GameEntity, renderComponent: {matrix: YUKA.Matrix4}) {
    renderComponent.matrix.copy(entity.worldMatrix);
}

function generateTarget() {
// generate a random point on a sphere
    const radius = 2;
    const phi = Math.acos((2 * Math.random()) - 1);
    const theta = Math.random() * Math.PI * 2;
    target.position.fromSpherical(radius, phi, theta);
    setTimeout(generateTarget, 2000);
}


text:
package com.intellij.util.io;

import com.intellij.util.containers.SLRUMap;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public abstract class FileAccessorCache<K, T> implements com.intellij.util.containers.hash.EqualityPolicy<K> {
  /*@GuardedBy("myCacheLock")*/ private final SLRUMap<K, Handle<T>> myCache;
  /*@GuardedBy("myCacheLock")*/ private final List<T> myElementsToBeDisposed = new ArrayList<T>();
  private final Object myCacheLock = new Object();
  private final Object myUpdateLock = new Object();

  public FileAccessorCache(int protectedQueueSize, int probationalQueueSize) {
    myCache = new SLRUMap<K, Handle<T>>(protectedQueueSize, probationalQueueSize, this) {
      @Override
      protected final void onDropFromCache(K key, @NotNull Handle<T> value) {
        value.release();
      }
    };
  }

  @NotNull
  protected abstract T createAccessor(K key) throws IOException;

  protected abstract void disposeAccessor(@NotNull T fileAccessor) throws IOException;

  @NotNull
  public final Handle<T> get(K key) {
    Handle<T> cached = getIfCached(key);
    if (cached != null) return cached;

    synchronized (myUpdateLock) {
      cached = getIfCached(key);
      if (cached != null) return cached;
      return createHandle(key);
    }
  }

  @NotNull
  private Handle<T> createHandle(K key) {
    try {
      Handle<T> cached = new Handle<T>(createAccessor(key), this);
      cached.allocate();

      synchronized (myCacheLock) {
        myCache.put(key, cached);
      }

      disposeInvalidAccessors();
      return cached;
    }
    catch (IOException ex) {
      throw new RuntimeException(ex);
    }
  }

  private void disposeInvalidAccessors() {
    List<T> fileAccessorsToBeDisposed;
    synchronized (myCacheLock) {
      if (myElementsToBeDisposed.isEmpty()) return;
      fileAccessorsToBeDisposed = new ArrayList<T>(myElementsToBeDisposed);
      myElementsToBeDisposed.clear();
    }

    for (T t : fileAccessorsToBeDisposed) {
      try {
        disposeAccessor(t);
      }
      catch (IOException ex) {
        throw new RuntimeException(ex);
      }
    }
  }

  public Handle<T> getIfCached(K key) {
    synchronized (myCacheLock) {
      final Handle<T> value = myCache.get(key);
      if (value != null) {
        value.allocate();
      }
      return value;
    }
  }

  public boolean remove(K key) {
    try {
      synchronized (myCacheLock) {
        return myCache.remove(key);
      }
    }
    finally {
      synchronized (myUpdateLock) {
        disposeInvalidAccessors();
      }
    }
  }

  public void clear() {
    try {
      synchronized (myCacheLock) {
        myCache.clear();
      }
    }
    finally {
      synchronized (myUpdateLock) {
        disposeInvalidAccessors();
      }
    }
  }

  @Override
  public int getHashCode(K value) {
    return value.hashCode();
  }

  @Override
  public boolean isEqual(K val1, K val2) {
    return val1.equals(val2);
  }

  public static final class Handle<T> extends ResourceHandle<T> {
    private final FileAccessorCache<?, ? super T> myOwner;
    @NotNull
    private final T myResource;
    private final AtomicInteger myRefCount = new AtomicInteger(1);

    public Handle(@NotNull T fileAccessor, @NotNull FileAccessorCache<?, ? super T> owner) {
      myResource = fileAccessor;
      myOwner = owner;
    }

    public void allocate() {
      myRefCount.incrementAndGet();
    }

    public final void release() {
      if (myRefCount.decrementAndGet() == 0) {
        synchronized (myOwner.myCacheLock) {
          myOwner.myElementsToBeDisposed.add(myResource);
        }
      }
    }

    public int getRefCount() {
      return myRefCount.get();
    }

    @Override
    public void close() {
      release();
    }

    @Override
    @NotNull
    public T get() {
      return myResource;
    }
  }
}


text:
package io.quarkus.qute.deployment.typesafe;

import static org.junit.jupiter.api.Assertions.assertEquals;

import javax.inject.Inject;

import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;

import io.quarkus.qute.Template;
import io.quarkus.test.QuarkusUnitTest;

public class WhenValidationTest {

    @RegisterExtension
    static final QuarkusUnitTest config = new QuarkusUnitTest()
            .withApplicationRoot((jar) -> jar
                    .addClasses(Machine.class, MachineStatus.class)
                    .addAsResource(new StringAsset("{@io.quarkus.qute.deployment.typesafe.Machine machine}"
                            + "{#when machine.status}"
                            + "{#is ON}1"
                            + "{#is OFF}0"
                            + "{/when} "
                            + "{#when machine.status}"
                            + "{#is in ON OFF}"
                            + "OK"
                            + "{/when} "
                            + "{#when machine.ping}"
                            + "{#is machine.status}"
                            + "NOK"
                            + "{#is in 1 2}"
                            + "OK"
                            + "{/when}"), "templates/machine.html"));

    @Inject
    Template machine;

    @Test
    public void testValidation() {
        assertEquals("1 OK OK",
                machine.data("machine", new Machine().setStatus(MachineStatus.ON)).render());
        assertEquals("0 OK OK",
                machine.data("machine", new Machine().setStatus(MachineStatus.OFF)).render());
    }

}


text:
package org.apache.sysml.test.integration.functions.binary.matrix;

import java.util.HashMap;

import org.junit.Test;

import org.apache.sysml.api.DMLScript;
import org.apache.sysml.api.DMLScript.RUNTIME_PLATFORM;
import org.apache.sysml.lops.LopProperties.ExecType;
import org.apache.sysml.runtime.matrix.data.MatrixValue.CellIndex;
import org.apache.sysml.test.integration.AutomatedTestBase;
import org.apache.sysml.test.integration.TestConfiguration;
import org.apache.sysml.test.utils.TestUtils;

/**
 *
 */
public class CovarianceTest extends AutomatedTestBase
{

	private final static String TEST_NAME = "Covariance";
	private final static String TEST_DIR = "functions/binary/matrix/";
	private final static String TEST_CLASS_DIR = TEST_DIR + CovarianceTest.class.getSimpleName() + "/";
	private final static double eps = 1e-10;

	private final static int rows = 1871;
	private final static int maxVal = 7;
	private final static double sparsity1 = 0.65;
	private final static double sparsity2 = 0.05;

	@Override
	public void setUp()
	{
		TestUtils.clearAssertionInformation();
		addTestConfiguration(TEST_NAME, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME, new String[] { "R" })   );
	}

	@Test
	public void testCovarianceDenseCP()
	{
		runCovarianceTest(false, ExecType.CP);
	}

	@Test
	public void testCovarianceSparseCP()
	{
		runCovarianceTest(true, ExecType.CP);
	}

	@Test
	public void testCovarianceDenseMR()
	{
		runCovarianceTest(false, ExecType.MR);
	}

	@Test
	public void testCovarianceSparseMR()
	{
		runCovarianceTest(true, ExecType.MR);
	}

	@Test
	public void testCovarianceDenseSP()
	{
		runCovarianceTest(false, ExecType.SPARK);
	}

	@Test
	public void testCovarianceSparseSP()
	{
		runCovarianceTest(true, ExecType.SPARK);
	}

	/**
	 *
	 * @param sparseM1
	 * @param sparseM2
	 * @param instType
	 */
	private void runCovarianceTest( boolean sparse, ExecType et)
	{
		//rtplatform for MR
		RUNTIME_PLATFORM platformOld = rtplatform;
		switch( et ){
			case MR: rtplatform = RUNTIME_PLATFORM.HADOOP; break;
			case SPARK: rtplatform = RUNTIME_PLATFORM.SPARK; break;
			default: rtplatform = RUNTIME_PLATFORM.HYBRID; break;
		}

		boolean sparkConfigOld = DMLScript.USE_LOCAL_SPARK_CONFIG;
		if( rtplatform == RUNTIME_PLATFORM.SPARK )
			DMLScript.USE_LOCAL_SPARK_CONFIG = true;

		try
		{
			getAndLoadTestConfiguration(TEST_NAME);

			String HOME = SCRIPT_DIR + TEST_DIR;
			fullDMLScriptName = HOME + TEST_NAME + ".dml";
			programArgs = new String[]{"-args", input("A"), input("B"), output("R")};

			fullRScriptName = HOME + TEST_NAME + ".R";
			rCmd = "Rscript" + " " + fullRScriptName + " " + inputDir() + " " + expectedDir();

			//generate actual dataset (always dense because values <=0 invalid)
			double sparsitya = sparse ? sparsity2 : sparsity1;
			double[][] A = getRandomMatrix(rows, 1, 1, maxVal, sparsitya, 7);
			writeInputMatrixWithMTD("A", A, true);
			double[][] B = getRandomMatrix(rows, 1, 1, maxVal, sparsitya, 823);
			writeInputMatrixWithMTD("B", B, true);

			runTest(true, false, null, -1);
			runRScript(true);

			//compare matrices
			HashMap<CellIndex, Double> dmlfile = readDMLMatrixFromHDFS("R");
			HashMap<CellIndex, Double> rfile  = readRMatrixFromFS("R");
			TestUtils.compareMatrices(dmlfile, rfile, eps, "Stat-DML", "Stat-R");
		}
		finally
		{
			rtplatform = platformOld;
			DMLScript.USE_LOCAL_SPARK_CONFIG = sparkConfigOld;
		}
	}

}


text:
package aggregation

import (
	"bytes"
	"fmt"

	"github.com/juju/errors"
	"github.com/pingcap/tidb/sessionctx/stmtctx"
	"github.com/pingcap/tidb/types"
)

type concatFunction struct {
	aggFunction
	separator string
	sepInited bool
}

func (cf *concatFunction) writeValue(evalCtx *AggEvaluateContext, val types.Datum) {
	if val.Kind() == types.KindBytes {
		evalCtx.Buffer.Write(val.GetBytes())
	} else {
		evalCtx.Buffer.WriteString(fmt.Sprintf("%v", val.GetValue()))
	}
}

func (cf *concatFunction) initSeparator(sc *stmtctx.StatementContext, row types.Row) error {
	sepArg := cf.Args[len(cf.Args)-1]
	sepDatum, err := sepArg.Eval(row)
	if err != nil {
		return errors.Trace(err)
	}
	if sepDatum.IsNull() {
		return errors.Errorf("Invalid separator argument.")
	}
	cf.separator, err = sepDatum.ToString()
	return errors.Trace(err)
}

// Update implements Aggregation interface.
func (cf *concatFunction) Update(evalCtx *AggEvaluateContext, sc *stmtctx.StatementContext, row types.Row) error {
	datumBuf := make([]types.Datum, 0, len(cf.Args))
	if !cf.sepInited {
		err := cf.initSeparator(sc, row)
		if err != nil {
			return errors.Trace(err)
		}
		cf.sepInited = true
	}

	// The last parameter is the concat separator, we only concat the first "len(cf.Args)-1" parameters.
	for i, length := 0, len(cf.Args)-1; i < length; i++ {
		value, err := cf.Args[i].Eval(row)
		if err != nil {
			return errors.Trace(err)
		}
		if value.GetValue() == nil {
			return nil
		}
		datumBuf = append(datumBuf, value)
	}
	if cf.HasDistinct {
		d, err := evalCtx.DistinctChecker.Check(datumBuf)
		if err != nil {
			return errors.Trace(err)
		}
		if !d {
			return nil
		}
	}
	if evalCtx.Buffer == nil {
		evalCtx.Buffer = &bytes.Buffer{}
	} else {
		evalCtx.Buffer.WriteString(cf.separator)
	}
	for _, val := range datumBuf {
		cf.writeValue(evalCtx, val)
	}
	// TODO: if total length is greater than global var group_concat_max_len, truncate it.
	return nil
}

// GetResult implements Aggregation interface.
func (cf *concatFunction) GetResult(evalCtx *AggEvaluateContext) (d types.Datum) {
	if evalCtx.Buffer != nil {
		d.SetString(evalCtx.Buffer.String())
	} else {
		d.SetNull()
	}
	return d
}

// GetPartialResult implements Aggregation interface.
func (cf *concatFunction) GetPartialResult(evalCtx *AggEvaluateContext) []types.Datum {
	return []types.Datum{cf.GetResult(evalCtx)}
}


text:
(function () {

    var moscow = new L.LatLng(55.7504, 37.62302); // geographical point (longitude and latitude)
    var map = L.map('map').setView(moscow, 13);
    L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: '© OpenStreetMap contributors', minZoom: 3, maxZoom: 20 }).addTo(map);
    map.attributionControl.setPrefix(''); // Don't show the 'Powered by Leaflet' text. Attribution overload

})();


text:
package sarveshchavan777.quizgame;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class QuestionActivity extends Activity {
    List<Question> quesList;
    int score = 0;
    int qid = 0;

    Question currentQ;
    TextView txtQuestion, times, scored;
    Button button1, button2, button3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        QuizHelper db = new QuizHelper(this);
        quesList = db.getAllQuestions();
        currentQ = quesList.get(qid);

        txtQuestion = (TextView) findViewById(R.id.txtQuestion);
        button1 = (Button) findViewById(R.id.button1);
        button2 = (Button) findViewById(R.id.button2);
        button3 = (Button) findViewById(R.id.button3);

        scored = (TextView) findViewById(R.id.score);

        times = (TextView) findViewById(R.id.timers);

        setQuestionView();
        times.setText("00:02:00");

        CounterClass timer = new CounterClass(60000, 1000);
        timer.start();

        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                getAnswer(button1.getText().toString());
            }
        });

        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getAnswer(button2.getText().toString());
            }
        });

        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getAnswer(button3.getText().toString());
            }
        });
    }

    public void getAnswer(String AnswerString) {
        if (currentQ.getANSWER().equals(AnswerString)) {

            score++;
            scored.setText("Score : " + score);
        } else {

            Intent intent = new Intent(QuestionActivity.this,
                    ResultActivity.class);

            Bundle b = new Bundle();
            b.putInt("score", score);
            intent.putExtras(b);
            startActivity(intent);
            finish();
        }
        if (qid < 21) {

            currentQ = quesList.get(qid);
            setQuestionView();
        } else {

            Intent intent = new Intent(QuestionActivity.this,won.class);
            Bundle b = new Bundle();
            b.putInt("score",score);
            intent.putExtras(b);
            startActivity(intent);
            finish();
        }

    }

    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    @SuppressLint("NewApi")
    public class CounterClass extends CountDownTimer {

        public CounterClass(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
            // TODO Auto-generated constructor stub
        }

        @Override
        public void onFinish() {
            times.setText("Time is up");

        }

      @Override
        public void onTick(long millisUntilFinished) {
            // TODO Auto-generated method stub

            long millis = millisUntilFinished;
            String hms = String.format(
                    "%02d:%02d:%02d",
                    TimeUnit.MILLISECONDS.toHours(millis),
                    TimeUnit.MILLISECONDS.toMinutes(millis)
                            - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS
                            .toHours(millis)),
                    TimeUnit.MILLISECONDS.toSeconds(millis)
                            - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS
                            .toMinutes(millis)));
            System.out.println(hms);
            times.setText(hms);
        }

    }

    private void setQuestionView() {

        // the method which will put all things together
        txtQuestion.setText(currentQ.getQUESTION());
        button1.setText(currentQ.getOPTA());
        button2.setText(currentQ.getOPTB());
        button3.setText(currentQ.getOPTC());

        qid++;
    }

}


text:
package org.apache.struts2.util;

import java.math.BigInteger;
import java.util.Map;
import java.util.Random;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.util.LocalizedTextUtil;
import com.opensymphony.xwork2.util.logging.Logger;
import com.opensymphony.xwork2.util.logging.LoggerFactory;

/**
 * TokenHelper
 *
 */
public class TokenHelper {

    /**
     * The default name to map the token value
     */
    public static final String DEFAULT_TOKEN_NAME = "struts.token";

    /**
     * The name of the field which will hold the token name
     */
    public static final String TOKEN_NAME_FIELD = "struts.token.name";
    private static final Logger LOG = LoggerFactory.getLogger(TokenHelper.class);
    private static final Random RANDOM = new Random();

    /**
     * Sets a transaction token into the session using the default token name.
     *
     * @return the token string
     */
    public static String setToken() {
        return setToken(DEFAULT_TOKEN_NAME);
    }

    /**
     * Sets a transaction token into the session using the provided token name.
     *
     * @param tokenName the name to store into the session with the token as the value
     * @return the token string
     */
    public static String setToken(String tokenName) {
        Map session = ActionContext.getContext().getSession();
        String token = generateGUID();
        try {
            session.put(tokenName, token);
        }
        catch(IllegalStateException e) {
            // WW-1182 explain to user what the problem is
            String msg = "Error creating HttpSession due response is commited to client. You can use the CreateSessionInterceptor or create the HttpSession from your action before the result is rendered to the client: " + e.getMessage();
            LOG.error(msg, e);
            throw new IllegalArgumentException(msg);
        }

        return token;
    }

    /**
     * Gets a transaction token into the session using the default token name.
     *
     * @return token
     */
    public static String getToken() {
        return getToken(DEFAULT_TOKEN_NAME);
    }

    /**
     * Gets the Token value from the params in the ServletActionContext using the given name
     *
     * @param tokenName the name of the parameter which holds the token value
     * @return the token String or null, if the token could not be found
     */
    public static String getToken(String tokenName) {
        if (tokenName == null ) {
            return null;
        }
        Map params = ActionContext.getContext().getParameters();
        String[] tokens = (String[]) params.get(tokenName);
        String token;

        if ((tokens == null) || (tokens.length < 1)) {
            if (LOG.isWarnEnabled()) {
        	LOG.warn("Could not find token mapped to token name " + tokenName);
            }

            return null;
        }

        token = tokens[0];

        return token;
    }

    /**
     * Gets the token name from the Parameters in the ServletActionContext
     *
     * @return the token name found in the params, or null if it could not be found
     */
    public static String getTokenName() {
        Map params = ActionContext.getContext().getParameters();

        if (!params.containsKey(TOKEN_NAME_FIELD)) {
            if (LOG.isWarnEnabled()) {
        	LOG.warn("Could not find token name in params.");
            }

            return null;
        }

        String[] tokenNames = (String[]) params.get(TOKEN_NAME_FIELD);
        String tokenName;

        if ((tokenNames == null) || (tokenNames.length < 1)) {
            if (LOG.isWarnEnabled()) {
        	LOG.warn("Got a null or empty token name.");
            }

            return null;
        }

        tokenName = tokenNames[0];

        return tokenName;
    }

    /**
     * Checks for a valid transaction token in the current request params. If a valid token is found, it is
     * removed so the it is not valid again.
     *
     * @return false if there was no token set into the params (check by looking for {@link #TOKEN_NAME_FIELD}), true if a valid token is found
     */
    public static boolean validToken() {
        String tokenName = getTokenName();

        if (tokenName == null) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("no token name found -> Invalid token ");
            }
            return false;
        }

        String token = getToken(tokenName);

        if (token == null) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("no token found for token name "+tokenName+" -> Invalid token ");
            }
            return false;
        }

        Map session = ActionContext.getContext().getSession();
        String sessionToken = (String) session.get(tokenName);

        if (!token.equals(sessionToken)) {
            if (LOG.isWarnEnabled()) {
                LOG.warn(LocalizedTextUtil.findText(TokenHelper.class, "struts.internal.invalid.token", ActionContext.getContext().getLocale(), "Form token {0} does not match the session token {1}.", new Object[]{
                        token, sessionToken
                }));
            }

            return false;
        }

        // remove the token so it won't be used again
        session.remove(tokenName);

        return true;
    }

    public static String generateGUID() {
        return new BigInteger(165, RANDOM).toString(36).toUpperCase();
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="@string/hello"/>
</LinearLayout>


text:
package org.openehealth.ipf.commons.ihe.xds.core.requests;

import javax.xml.bind.annotation.*;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

/**
 * Request object for the Retrieve Document Set transaction.
 *

 * Lists are pre-created and can therefore never be null.
 * @author Jens Riemschneider
 */

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "RetrieveDocumentSet")
@XmlRootElement(name = "retrieveDocumentSet")
public class RetrieveDocumentSet implements Serializable {
    private static final long serialVersionUID = -3410625944194160618L;

    @XmlElementRef
    private final List<RetrieveDocument> documents = new ArrayList<RetrieveDocument>();

    /**
     * @return the list of documents to retrieve.
     */
    public List<RetrieveDocument> getDocuments() {
        return documents;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((documents == null) ? 0 : documents.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        RetrieveDocumentSet other = (RetrieveDocumentSet) obj;
        if (documents == null) {
            if (other.documents != null)
                return false;
        } else if (!documents.equals(other.documents))
            return false;
        return true;
    }

    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
    }
}


text:
// Copyright 2011 Avi Levi

// Licensed 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.

using ByContext.StringToValueTranslator.SerializeStringToValueTranslator;

namespace ByContext.StringToValueTranslator
{
    /// <summary>
    /// Provides an abstraction for resolving configuration values from given strings.
    /// Provides an extension point for resolving string configuration values in different ways.
    /// <remarks>
    /// Implementation that is provided with the library is <see cref="SerializeStringToValueTranslatorProvider"/>
    /// which deserializes the given string.
    /// </remarks>
    /// </summary>
    public interface IStringToValueTranslator
    {
        /// <summary>
        /// Deserializes the given string.
        /// </summary>
        /// <param name="value">Input string to be translated.</param>
        /// <returns>A configuration value.</returns>
        object Translate(string value);
    }
}


text: Other projects


text:
"""
Written by Lucas Sinclair.
MIT Licensed.
Contact at www.sinclair.bio
"""

# Special variables #
__version__ = '2.1.6'


text:
"""URLs for the social_media_links app."""
# from django.conf.urls import patterns, url

# from . import views

# urlpatterns = patterns(
#     '',
#     url(r'^$',
#         views.YourView.as_view(),
#         name='social_media_links_default'),
# )


text:
clearInterval();

var i = 0, file = E.openFile('test.txt', 'w');

function write() {

    // turn on the LED to indicate that we're writing
    LED1.write(true);

    // increment the line number, write a new message
    i++;
    file.write("hello world " + i + "\n");

    // turn off the LED to say we're done
    LED1.write(false);

}

// register to the button press
setWatch(write, BTN, { edge: "falling", repeat: true });


text:
{% extends "base.html" %}
{% block title %}Flasky{% endblock %}
{% block page_content %}

{{ account.username }}

            {% if account.name or account.location %}

                    {% if account.name %}{{ account.name }}{% endif %}
                    {% if account.location %}
                        From
                            {{ account.location }}

                    {% endif %}

            {% endif %}
            {% if current_user.is_administrator() %}

{{ account.email }}

            {% endif %}
            {% if account.about_me %}
{{ account.about_me }}
{% endif %}

                Member since {{ moment(account.member_since).format('L') }}.
                Last seen {{ moment(account.last_seen).fromNow() }}.

            {% if account == current_user %}

                    Edit Profile

            {% endif %}
            {% if current_user.is_administrator() %}

                    Edit Profile [Admin]

            {% endif %}

Posts by {{ account.username }}

    {% include '_posts.html' %}

clients {{ account.username }} have logged in:

            {% for user_id, user_device in users.items() %}

{% if self_info==user_device %}(self)    {% endif %}{{ user_device }}

            {% endfor %}

register status

            {% for reg_item, reg_status in register_status.items() %}
                {% if reg_status==False and reg_item=='Email' %}{{ reg_item }}{% endif %}
                {% if reg_status==True and reg_item=='Email' %}{{ reg_item }}{% endif %}
                {% if reg_status==False and reg_item=='Weibo' %}{{ reg_item }}{% endif %}
                {% if reg_status==True and reg_item=='Weibo' %}{{ reg_item }}{% endif %}
            {% endfor %}

{% endblock %}


text: A demo crud application for managing pages in a CMS


text:
//* Bobo Browse Engine - High performance faceted/parametric search implementation
//* that handles various types of semi-structured data.  Originally written in Java.
//*
//* Ported and adapted for C# by Shad Storhaug, Alexey Shcherbachev, and zhengchun.
//*
//* Copyright (C) 2005-2015  John Wang
//*
//* Licensed 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.

// Version compatibility level: 4.0.2
namespace BoboBrowse.Net.DocIdSet
{
    using Lucene.Net.Search;

    public abstract class RandomAccessDocIdSet : DocIdSet
    {
        public abstract bool Get(int docId);
    }
}


text:
if(-not $ENV:BHProjectPath)
{
    Set-BuildEnvironment -Path $PSScriptRoot\.. -Force
}
Remove-Module $ENV:BHProjectName -ErrorAction SilentlyContinue
Import-Module (Join-Path $ENV:BHProjectPath $ENV:BHProjectName) -Force

InModuleScope 'PSDeploy' {
    $PSVersion = $PSVersionTable.PSVersion.Major
    $ProjectRoot = $ENV:BHProjectPath
    $ModuleName = $ENV:BHProjectName

    $Verbose = @{}
    if($ENV:BHBranchName -notlike "master" -or $env:BHCommitMessage -match "!verbose")
    {
        $Verbose.add("Verbose",$True)
    }

    $FakeYml = @"
PlatyPS:
  Script: FakePlatyPS.ps1
  Description: Builds External Help files using PlatyPS markdown and Deploys them to Module Help directory.
"@

    Describe "Get-PSDeploymentScript PS$PSVersion" {
        $DeploymentScripts = Get-PSDeploymentScript @Verbose

        Context 'Deployment Scripts Should return valid paths' {

            foreach ($DeploymentScript in $DeploymentScripts.GetEnumerator())
            {
                It "[$($DeploymentScript.Name)] Should Exist" {
                    $Results = Test-Path $DeploymentScript.value
                    $Results | Should be $True
                }
            }
        }

        Context 'Deployment Script does not Exist' {
            $TestPath = Join-Path -Path 'TestDrive:\' -ChildPath 'PSDeploy.yml'
            $FakeYml | Out-File -FilePath $TestPath -Force

            It "[$($TestPath)] Should Throw" {
                $Results = { Get-PSDeploymentScript -Path $TestPath @Verbose -ErrorAction Stop }
                $Results | Should Throw
            }
        }

        Context 'Should have equal Counts' {

            It "Should have same number of Deployment Scripts as valid paths [Count $($DeploymentScripts.count)]" {
                $ScriptTypes = Get-ChildItem -Path $ProjectRoot\$ModuleName\PSDeployScripts
                $DeploymentScripts.count | Should be $ScriptTypes.count
            }
        }
    }
}


text:
A 2D game written in Python using PyGame that revolves around wars between boats. The original title of the game was "Battleport - The Rotterdam Edition".

As of February 1st which was two days before the deadline, we've counted the following data about the project source:

* 25 Packages
* 38 Python files
* 2183 lines of python code
* 201 function/method definitions
* 29 class definitions
* 90 PNG/JPG images


text:
package com.strv.rxjavademo.activity;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.strv.rxjavademo.cache.RequestCache;
import com.strv.rxjavademo.fragment.CoreFragment;

public class CoreActivity extends AppCompatActivity
{

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);

		if (savedInstanceState == null)
		{
			getSupportFragmentManager().beginTransaction()
					.replace(android.R.id.content, CoreFragment.newInstance(), this.toString())
					.commit();
		}
	}

	@Override
	public void onBackPressed()
	{
		super.onBackPressed();
		RequestCache.getInstance().deleteCache();
	}
}


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

  create_table "bookmarks", force: :cascade do |t|
    t.string   "title"
    t.string   "link"
    t.string   "summary"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

end


text:
package com.thoughtworks.go.agent.common;

import com.beust.jcommander.Parameter;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import java.util.Properties;

public class AgentBootstrapperArgs {

    public enum SslMode {
        FULL, NONE, NO_VERIFY_HOST
    }

    public static String SERVER_URL = "serverUrl";
    public static String SSL_VERIFICATION_MODE = "sslVerificationMode";
    public static String ROOT_CERT_FILE = "rootCertFile";

    @Parameter(names = "-serverUrl", description = "The GoCD server URL. Example: http://gocd.example.com:8153/go", required = true, validateWith = ServerUrlValidator.class)
    private URL serverUrl;

    @Parameter(names = "-rootCertFile", description = "The root certificate from the certificate chain of the GoCD server (in PEM format)", validateWith = CertificateFileValidator.class)
    private File rootCertFile;

    @Parameter(names = "-sslVerificationMode", description = "The SSL verification mode.")
    private SslMode sslVerificationMode = SslMode.NONE;

    @Parameter(names = "-help", help = true, description = "Print this help")
    boolean help;

    public AgentBootstrapperArgs() {
    }

    public AgentBootstrapperArgs(URL serverUrl, File rootCertFile, SslMode sslVerificationMode) {
        this.serverUrl = serverUrl;
        this.rootCertFile = rootCertFile;
        this.sslVerificationMode = sslVerificationMode;
    }

    public Properties toProperties() {
        Properties properties = new Properties();
        properties.put(SERVER_URL, serverUrl.toString());
        properties.put(SSL_VERIFICATION_MODE, sslVerificationMode.name());

        if (rootCertFile != null) {
            properties.put(ROOT_CERT_FILE, rootCertFile.getAbsoluteFile().toString());
        }

        return properties;
    }

    public static AgentBootstrapperArgs fromProperties(Map<?, ?> properties) {
        Properties props = new Properties();
        props.putAll(properties);

        return fromProperties(props);
    }

    public static AgentBootstrapperArgs fromProperties(Properties properties) {
        try {
            URL serverUrl = new URL(properties.getProperty(SERVER_URL));
            File rootCertFile = null;

            SslMode sslVerificationMode = SslMode.valueOf(properties.getProperty(SSL_VERIFICATION_MODE));

            if (properties.containsKey(ROOT_CERT_FILE)) {
                rootCertFile = new File(properties.getProperty(ROOT_CERT_FILE));
            }

            return new AgentBootstrapperArgs(serverUrl, rootCertFile, sslVerificationMode);
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String toString() {
        return "AgentBootstrapperArgs{" +
                "serverUrl=" + serverUrl +
                ", rootCertFile=" + rootCertFile +
                ", sslVerificationMode=" + sslVerificationMode +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        AgentBootstrapperArgs that = (AgentBootstrapperArgs) o;

        if (serverUrl != null ? !serverUrl.equals(that.serverUrl) : that.serverUrl != null) return false;
        if (rootCertFile != null ? !rootCertFile.getAbsoluteFile().equals(that.rootCertFile.getAbsoluteFile()) : that.rootCertFile != null)
            return false;
        return sslVerificationMode == that.sslVerificationMode;
    }

    public URL getServerUrl() {
        return serverUrl;
    }

    public File getRootCertFile() {
        return rootCertFile;
    }

    public SslMode getSslMode() {
        return sslVerificationMode;
    }
}


text:
package org.apache.fineract.data.services;

import org.apache.fineract.data.models.customer.Country;

import java.util.List;

import io.reactivex.Observable;
import retrofit2.http.GET;

/**
 * @author Rajan Maurya
 *         On 26/07/17.
 */
public interface AnonymousService {

    @GET("http://restcountries.eu/rest/v2/all?fields=name;alpha2Code;translations")
    Observable<List<Country>> getCountries();
}


text:
@interface PodsDummy_Pods_OptimizelySDKDatafileManagerTVOSTests : NSObject
@end
@implementation PodsDummy_Pods_OptimizelySDKDatafileManagerTVOSTests
@end


text:
PAL: The Parallel Architectures Library
========================================

[![Build Status](https://travis-ci.org/parallella/pal.svg?branch=master)](https://travis-ci.org/parallella/pal)

The Parallel Architectures Library (PAL) is a compact C library with optimized routines for math, synchronization, and inter-processor communication.

## Content
1.  [Why?](#why)

2.  [Design goals](#design-goals)

3.  [License](#license)

4.  [Contribution Wanted!](#contribution)

5.  [A Simple Example](#a-simple-example)

6.  [Build Instructions](#build-instructions)

7.  [Library API reference](#library-api-reference)
7.0 [Syntax](#syntax)
7.1 [Program Flow](#program-flow)
7.2 [Data Movement](#data-movement)
7.3 [Synchronization](#synchronization)
7.3 [Basic Math](#math)
7.5 [Basic DSP](#dsp)
7.4 [Image Processing](#image-processing)
7.6 [FFT (FFTW)](#fft)
7.7 [Linar Algebra (BLAS)](#blas)
7.8 [System Calls](#system-calls)

8   [Status Report](#status-report)

9   [Benchmarking](#benchmarking)

----------------------------------------------------------------------
##Why?
Any sane and informed person knows that the future of computing is massively parallel. Unfortunately the energy needed to escape the current "von Neumann potential well" seems to be approaching infinity. The legacy programming stack is so effective and so easy to use that developers and companies simply cannot afford to choose the better (parallel) solution. To make parallel computing ubiquitous our only choice is to rewrite the whole software stack from scratch, including: algorithms, run-times, libraries, and applications. The goal of the Parallel Architectures Library project is to establish the lowest layer of this brave new programming stack.

##Design Goals

* **Fast** (Super fast but no "belt AND suspenders")
* **Compact** (Small enough to work for memory limited processors with <32KB RAM)
* **Scalable** (Thread and data scalable)
* **Portable** (Portable across different ISAs and systems)
* **Permissive** (Apache 2.0 license to maximize industry adoption)

##License
The PAL source code is licensed under the Apache License, Version 2.0.
See LICENSE for full license text unless otherwise specified.

##Contribution
Our goal is to make PAL a broad community project from day one. If just 100 people contribute one function each, we'll be done in a couple of days! If you know C, you are ready to contribute!!

Instructions for contributing can be found [HERE](CONTRIBUTING.md).

##Build Instructions

###Install Prerequisites
``` bash
$ sudo apt-get install libtool build-essential pkg-config autoconf doxygen
```

###Build Sequence

``` bash
$ ./bootstrap
$ ./configure
$ make
```

###Testing

To run the automated unit tests you need to run
``` bash
$ make check
```

##A Simple Example
The following sample shows how to use PAL launch a simple task on a remote processor within the system. The program flow should be familiar to anyone who has used accelerator programming frameworks.

**Manager Code**

``` c
#include <pal.h>
#include <stdio.h>
#define N 16
int main(int argc, char *argv[])
{

    // Stack variables
    char *file = "./hello_task.elf";
    char *func = "main";
    int status, i, all, nargs = 1;
    char *args[nargs];
    char argbuf[20];

    // References as opaque structures
    p_dev_t dev0;
    p_prog_t prog0;
    p_team_t team0;
    p_mem_t mem[4];

    // Execution setup
    dev0 = p_init(P_DEV_DEMO, 0);        // initialize device and team
    prog0 = p_load(dev0, file, func, 0); // load a program from file system
    all = p_query(dev0, P_PROP_NODES);   // find number of nodes in system
    team0 = p_open(dev0, 0, all);        // create a team

    // Running program
    for (i = 0; i < all; i++) {
        sprintf(argbuf, "%d", i); // string args needed to run main asis
        args[0] = argbuf;
        status = p_run(prog0, team0, i, 1, nargs, args, 0);
    }
    p_wait(team0);    // not needed
    p_close(team0);   // close team
    p_finalize(dev0); // finalize memory

    return 0;
}
```

**Worker Code (hello_task.elf)**
``` c
#include <stdio.h>
int main(int argc, char* argv[]){
    int pid=0;
    int i;
    pid=atoi(argv[2]);
    printf("--Processor %d says hello!--\n", pid);
    return i;
}
```

PAL LIBRARY API REFERENCE
========================================
##SYNTAX

##PROGRAM FLOW
These program flow functions are used to manage the system and to execute programs. All PAL objects are referenced via handles (opaque objects).

FUNCTION     | NOTES
------------ | -------------
[p_init()](src/base/p_init.c)            | initialize the run time
[p_query()](src/base/p_query.c)          | query a device object
[p_load()](src/base/p_load.c)            | load binary elf file into memory
[p_run()](src/base/p_run.c)              | run a program on a team of processor
[p_open()](src/base/p_open.c)            | open a team of processors
[p_append()](src/base/p_append.c)        | add members to team
[p_remove()](src/base/p_remove.c)        | remove members from team
[p_close()](src/base/p_close.c)          | close a team of processors
[p_barrier()](src/base/p_barrier.c)      | team barrier
[p_wait()](src/base/p_wait.c)            | wait for team to finish
[p_fence()](src/base/p_fence.c)          | memory fence
[p_finalize()](src/base/p_finalize.c)    | cleans up run time
[p_get_err()](src/base/p_get_err.c)      | get error code (if any).

##MEMORY ALLOCATION
These functions are used for creating memory objects.
The functions return a unique PAL handle for each new memory object. This handle can then be used by functions like p_read() and p_write() to access data within the memory object.

FUNCTION     | NOTES        | STATUS
------------ | -------------|-----------
[p_malloc()](src/base/p_malloc.c)        | allocate memory on local processor
[p_rmalloc()](src/base/p_rmalloc.c)      | allocate memory on remote processor
[p_free()](src/base/p_free.c)            | free memory

##DATA MOVEMENT
The data movement functions move blocks of data between opaque memory objects and locations specified by pointers. The memory object is specified by a PAL handle returned by a previous API call. The exception is the p_memcpy function which copies blocks of bytes within a shared memory architecture only.

FUNCTION     | NOTES
------------ | -------------
[p_gather()](src/base/p_gather.c)       | gather operation
[p_memcpy()](src/base/p_memcpy.c)       | fast memcpy()
[p_read()](src/base/p_read.c)           | read from a memory object
[p_scatter()](src/base/p_scatter.c)     | scatter operation
[p_write()](src/base/p_write.c)         | write to a memory object

##SYNCHRONIZATION
The synchronization functions are useful for program sequencing and resource locking in shared memory systems.

FUNCTION     | NOTES
------------ | -------------
[p_mutex_lock()](src/base/p_mutex_lock.c)           | lock a mutex
[p_mutex_trylock()](src/base/p_mutex_trylock.c)     | try locking a mutex once
[p_mutex_unlock()](src/base/p_mutex_unlock.c)       | unlock (clear) a mutex
[p_mutex_init()](src/base/p_mutex_init.c)           | initialize a mutex
[p_atomic_add()](src/base/p_atomic_add.c)           | atomic fetch and add
[p_atomic_sub()](src/base/p_atomic_sub.c)           | atomic fetch and sub
[p_atomic_and()](src/base/p_atomic_and.c)           | atomic fetch and 'and'
[p_atomic_xor()](src/base/p_atomic_xor.c)           | atomic fetch and 'xor'
[p_atomic_or()](src/base/p_atomic_or.c)             | atomic fetch and 'or'
[p_atomic_swap()](src/base/p_atomic_swap.c)         | atomic exchange
[p_atomic_compswap()](src/base/p_atomic_compswap.c) | atomic compare and exchange

##MATH
The math functions replace the traditional math lib functions and extend them to include support for data as well as task parallelism.

FUNCTION     | NOTES
------------ | -------------
[p_abs()](src/math/p_abs.c)           | absolute value
[p_absdiff()](src/math/p_absdiff.c)   | absolute difference
[p_add()](src/math/p_add.c)           | add
[p_acos()](src/math/p_acos.c)         | arc cosine
[p_acosh()](src/math/p_acosh.c)       | arc hyperbolic cosine
[p_asin()](src/math/p_asin.c)         | arc sine
[p_asinh()](src/math/p_asinh.c)       | arc hyperbolic sine
[p_cbrt()](src/math/p_cbrt.c)         | cubic root
[p_cos()](src/math/p_cos.c)           | cosine
[p_cosh()](src/math/p_cosh.c)         | hyperbolic cosine
[p_div()](src/math/p_div.c)           | division
[p_dot()](src/math/p_dot.c)           | dot product
[p_erf()](src/math/p_erf.c)           | error function
[p_exp()](src/math/p_exp.c)           | exponential
[p_ftoi()](src/math/p_ftoi.c)         | float to
[p_itof()](src/math/p_itof.c)         | integer to float conversion
[p_inv()](src/math/p_inv.c)           | inverse
[p_invcbrt()](src/math/p_invcbrt.c)   | inverse cube root
[p_invsqrt()](src/math/p_invsqrt.c)   | inverse square root
[p_ln()](src/math/p_ln.c)             | natural log
[p_log10()](src/math/p_log10.c)       | denary log
[p_max()](src/math/p_max.c)           | finds max val
[p_min()](src/math/p_min.c)           | finds min val
[p_mean()](src/math/p_mean.c)         | mean operation
[p_median()](src/math/p_median.c)     | finds middle value
[p_mode()](src/math/p_mode.c)         | finds most common value
[p_mul()](src/math/p_mul.c)           | multiplication
[p_popcount()](src/math/p_popcount.c) | count the number of bits set
[p_pow()](src/math/p_pow.c)           | element raised to a power
[p_rand()](src/math/p_rand.c)         | random number generator
[p_randinit()](src/math/p_rand.c)     | init random number generator
[p_sort()](src/math/p_sort.c)         | heap sort
[p_sin()](src/math/p_sin.c)           | sine
[p_sinh()](src/math/p_sinh.c)         | hyperbolic sine
[p_sqrt()](src/math/p_sqrt.c)         | square root
[p_stddev()](src/math/p_stddev.c)     | calculates standard deviation
[p_sub()](src/math/p_sub.c)           | subtract
[p_sum()](src/math/p_sum.c)           | sum of all vector elements
[p_sumsq()](src/math/p_sumsq.c)       | sum of all squared elements
[p_tan()](src/math/p_tan.c)           | tangent
[p_tanh()](src/math/p_tanh.c)         | hyperbolic tangent

##DSP
The digital signal processing (DSP) functions follow the same convention as the math function set.

FUNCTION     | NOTES
------------ | -------------
[p_acorr()](src/dsp/p_acorr.c)   | autocorrelation (r[j] = sum ( x[j+k] * x[k] ), k=0..(n-j-1))
[p_conv()](src/dsp/p_conv.c)     | convolution: r[j] = sum ( h[k] * x[j-k), k=0..(nh-1)
[p_xcorr()](src/dsp/p_xcorr.c)   | correlation: r[j] = sum ( x[j+k] * y[k]), k=0..(nx+ny-1)
[p_fir()](src/dsp/p_fir.c)       | FIR filter direct form: r[j] = sum ( h[k] * x [j-k]), k=0..(nh-1)
[p_firdec()](src/dsp/p_firdec.c) | FIR filter with decimation: r[j] = sum ( h[k] * x [j*D-k]), k=0..(nh-1)
[p_firint()](src/dsp/p_firint.c) | FIR filter with inerpolation: r[j] = sum ( h[k] * x [j*D-k]), k=0..(nh-1)
[p_firsym()](src/dsp/p_firsym.c) | FIR symmetric form
[p_iir()](src/dsp/p_iir.c)       | IIR filter

##IMAGE PROCESSING
The image processing functions follow the same convention as the math function set.

FUNCTION     | NOTES
------------ | -------------
[p_box3x3()](src/image/p_box3x3.c)         | box filter (3x3)
[p_conv2d()](src/image/p_conv2d.c)         | 2d convolution
[p_gauss3x3()](src/image/p_gauss3x3.c)     | gaussian blur filter (3x3)
[p_median3x3()](src/image/p_median3x3.c)   | median filter (3x3)
[p_laplace3x3()](src/image/p_laplace3x3.c) | laplace filter (3x3)
[p_prewitt3x3()](src/image/p_prewitt3x3.c) | prewitt filter (3x3)
[p_sad8x8()](src/image/p_sad8x8.c)         | sum of absolute differences (8x8)
[p_sad16x16()](src/image/p_sad16x16.c)     | sum of absolute differences (16x16)
[p_sobel3x3()](src/image/p_sobel3x3.c)     | sobel filter (3x3)
[p_scharr3x3()](src/image/p_scharr3x3.c)   | scharr filter (3x3)

##FFT

* An FFTW like interface

##BLAS

* A port of the BLIS library?

##SYSTEM CALLS

* Bionic libc implementation as starting point..

STATUS REPORT
========================================
https://parallella.github.io/pal-stats/summary.html

BENCHMARKING
========================================
LINK
=======
* TBD

BENCHMARKING
========================================
E=Epiphany
X=x86
A=ARM
CC=Clock cycles

FUNCTION  | E-CC     | E-SIZE   | A-CC     | A-SIZE   | X-CC     |X-SIZE    |
----------|----------|----------|----------|----------|----------|----------|
p_add()   | TBD      | TBD      | TBD      | TBD      | TBD      | TBD      |
...       | ...      | ...      | ...      | ...      | ...      | ...      |


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using DevExpress.XtraEditors;

using Clifton.Tools.Data;

using Intertexti;
using Intertexti.Controls;

namespace Intertexti.DevExpressControls
{
	public partial class DxLabeledTextEdit : UserControl
	{
		public string LabelText
		{
			get { return lblTextBox.Text; }
			set { lblTextBox.Text = value; }
		}

		public string TextBoxText
		{
			get { return tbData.Text; }
			set { tbData.Text = value; }
		}

		public event TextChangedDlgt TextDataChanged;
		public event EventHandler TextBoxGotFocus;

		public DxLabeledTextEdit()
		{
			InitializeComponent();
			tbData.GotFocus += ((object sender, EventArgs args) => TextBoxGotFocus.IfNotNull(e => e(sender, args)));
			tbData.LostFocus += ((object sender, EventArgs args) => TextDataChanged.IfNotNull(e => e(tbData.Text)));
			tbData.KeyPress += ((object sender, KeyPressEventArgs args) =>
			{
				if (args.KeyChar == 13)
				{
					TextDataChanged.IfNotNull(e => e(tbData.Text));
				}
			});
		}
	}
}


text:
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
using Azure.Core;

namespace Azure.Security.Attestation
{
    [JsonConverter(typeof(PolicyCertificatesModificationResultConverter))]
    public partial class PolicyCertificatesModificationResult : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            if (Optional.IsDefined(CertificateThumbprint))
            {
                writer.WritePropertyName("x-ms-certificate-thumbprint");
                writer.WriteStringValue(CertificateThumbprint);
            }
            if (Optional.IsDefined(CertificateResolution))
            {
                writer.WritePropertyName("x-ms-policycertificates-result");
                writer.WriteStringValue(CertificateResolution.Value.ToString());
            }
            writer.WriteEndObject();
        }

        internal static PolicyCertificatesModificationResult DeserializePolicyCertificatesModificationResult(JsonElement element)
        {
            Optional<string> xMsCertificateThumbprint = default;
            Optional<PolicyCertificateResolution> xMsPolicycertificatesResult = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("x-ms-certificate-thumbprint"))
                {
                    xMsCertificateThumbprint = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("x-ms-policycertificates-result"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    xMsPolicycertificatesResult = new PolicyCertificateResolution(property.Value.GetString());
                    continue;
                }
            }
            return new PolicyCertificatesModificationResult(xMsCertificateThumbprint.Value, Optional.ToNullable(xMsPolicycertificatesResult));
        }

        internal partial class PolicyCertificatesModificationResultConverter : JsonConverter<PolicyCertificatesModificationResult>
        {
            public override void Write(Utf8JsonWriter writer, PolicyCertificatesModificationResult model, JsonSerializerOptions options)
            {
                writer.WriteObjectValue(model);
            }
            public override PolicyCertificatesModificationResult Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
            {
                using var document = JsonDocument.ParseValue(ref reader);
                return DeserializePolicyCertificatesModificationResult(document.RootElement);
            }
        }
    }
}