text:
Build script with gulp to release and create apk with ionic and new Version, also tasks to update the version and commit the changes.

## HowTo Preparation
* 1. Create a new Ionic Project or add the gulpfile.js to your ionic project
* 2. Add dependencies to your package.json
```
  "devDependencies": {
      "bower": "^1.3.3",
      "del": "^2.2.0",
      "grunt": "^0.4.5",
      "gulp": "^3.9.0",
      "gulp-bump": "^1.0.0",
      "gulp-clean": "^0.3.1",
      "gulp-edit-xml": "^2.0.0",
      "gulp-filter": "^3.0.1",
      "gulp-git": "^1.6.1",
      "gulp-if": "^2.0.0",
      "gulp-jshint": "^2.0.0",
      "gulp-load-plugins": "^1.1.0",
      "gulp-merge": "^0.1.1",
      "gulp-open": "^1.0.0",
      "gulp-regex-replace": "^0.2.3",
      "gulp-replace": "^0.5.4",
      "gulp-tag-version": "^1.3.0",
      "gulp-task-listing": "^1.0.1",
      "gulp-uglify": "^1.5.1",
      "gulp-util": "^2.2.14",
      "gulp-xml-editor": "^2.2.1",
      "gulp-concat": "^2.2.0",
      "gulp-rename": "^1.2.0",
      "minimist": "^1.2.0",
      "moment": "^2.11.0",
      "q": "^1.4.1",
      "run-sequence": "^1.1.5",
      "semver": "^5.1.0",
      "shelljs": "^0.3.0",
      "yargs": "^3.31.0"
    },
```
* 3. Update your node modules with `npm install`
* 4. Add the following keys to your package.json (is necessary for config.xml and AndroidManifest.xml)
  "name": "nameofyourapp",
  "version": "VersionForYourAppForExample:0.0.1",
  "description": "DescriptionForYourApp",
  "author": "AuthorNAme",
  "authorEmail": "YourMailAddress",
  "authorUrl": "YourUrl",
* 5. Create a keystore for your ionic app
* 6. Create a new file under `platforms/android` with the name 'release-signing.properties' with content:
```
storeFile=pathtoyourkeystore/nameofyourkeystore.keystore
keyAlias=aliasname
storePassword=storepassword
keyPassword=keypassword
```
* 7. Call `gulp help` at your command line

## Create a new apk with new version

Please call

`gulp createNewRelease --envType patch` for an new apk with new patch version

`gulp createNewRelease --envType minor` for an new apk with new minor version

`gulp createNewRelease --envType major` for an new apk with new major version

`gulp createNewRelease --envType prerelease` for an new apk with new prerelease version

The default envType is patch if you only call `gulp createNewRelease`

After a success build you find in `release_builds` a new apk with `android-release-zipalign-MMDDYYYY-hhmmss-versionnumber.apk` and a new tag with versionnumber.

## Tasks

```
Main Tasks
------------------------------
    cleanBuild
    commitAndTag
    createNewRelease
    help
    updateInfos
    versionFeature
    versionPatch
    versionPrerelease
    versionRelease

Sub Tasks
------------------------------
    build-debug
    build-release
```

* help: Show all tasks
* cleanBuild: Clean the build dir in platforms/Android
* commitAndTag: Create an new commit for config.xml and package.json and create a tag by version from package.json
* createNewRelease: Change the version in package.json, create a new android apk release and commit and tag the result.
* updateInfos: Change the author.*, description and name values in config.xml by package.json
* build-release: Create a new apk with the version from package.json without changes on versionnumber or git

For the following tasks read also http://semver.org/ (the version changes are only in config.xml and package.json - AndroidManifest is update by ionic release build)
* versionFeature: Set a new feature version - for example from 0.0.1 to 0.1.0
* versionPatch: Set a new patch version - for example from 0.0.1 to 0.0.2
* versionPrerelease: Set a new prerelease version - for example from 0.1.0 to 1.0.0-1
* versionRelease: Set a new release version - for example from 1.0.5 to 2.0.0


text:
'use strict'

const natural = require('../lib/natural')
const LogisticRegressionClassifier = natural.LogisticRegressionClassifier

describe('logistic regression', function () {
  it('should classify with individually trained documents', function () {
    const classifier = new LogisticRegressionClassifier()

    classifier.addDocument(['have', 'computer'], 'IT')
    classifier.addDocument(['have', 'phone'], 'IT')
    classifier.addDocument(['computer', 'suck'], 'IT')
    classifier.addDocument(['field', 'goal'], 'sports')
    classifier.addDocument(['score', 'goal'], 'sports')
    classifier.addDocument(['great', 'speed'], 'sports')

    classifier.train()

    expect(classifier.classify(['hate', 'computer'])).toBe('IT')
    expect(classifier.classify(['score', 'please'])).toBe('sports')
  })

  it('should provide all classification scores', function () {
    const classifier = new natural.LogisticRegressionClassifier()
    classifier.addDocument(['fix', 'box'], 'computing')
    classifier.addDocument(['write', 'code'], 'computing')
    classifier.addDocument(['script', 'code'], 'computing')
    classifier.addDocument(['write', 'book'], 'literature')
    classifier.addDocument(['read', 'book'], 'literature')
    classifier.addDocument(['study', 'book'], 'literature')

    classifier.train()

    expect(classifier.getClassifications('i write code')[0].label).toBe('computing')
    expect(classifier.getClassifications('i write code')[1].label).toBe('literature')
  })

  function createClassifier () {
    const classifier = new natural.LogisticRegressionClassifier()
    classifier.addDocument('i fixed the box', 'computing')
    classifier.addDocument('i write code', 'computing')
    classifier.addDocument('nasty script code', 'computing')
    classifier.addDocument('write a book', 'literature')
    classifier.addDocument('read a book', 'literature')
    classifier.addDocument('study the books', 'literature')

    return classifier
  }

  it('should classify with arrays', function () {
    const classifier = createClassifier()
    classifier.train()
    expect(classifier.classify('a bug in the code')).toBe('computing')
    expect(classifier.classify('read all the books')).toBe('literature')
  })

  it('should serialize and deserialize a working classifier', function () {
    const classifier = createClassifier()

    const obj = JSON.stringify(classifier)
    const newClassifier = natural.LogisticRegressionClassifier.restore(JSON.parse(obj))

    newClassifier.addDocument('kick a ball', 'sports')
    newClassifier.addDocument('hit some balls', 'sports')
    newClassifier.addDocument('kick and punch', 'sports')

    newClassifier.train()

    expect(newClassifier.classify('a bug in the code')).toBe('computing')
    expect(newClassifier.classify('read all the books')).toBe('literature')
    expect(newClassifier.classify('kick butt')).toBe('sports')
  })

  /*
    it('should save and load a working classifier', function() {
        var classifier = new natural.LogisticRegressionClassifier();
        classifier.addDocument('i fixed the box', 'computing');
        classifier.addDocument('i write code', 'computing');
        classifier.addDocument('nasty script code', 'computing');
        classifier.addDocument('write a book', 'literature');
        classifier.addDocument('read a book', 'literature');
        classifier.addDocument('study the books', 'literature');
        classifier.train();

        classifier.save('lr_classifier.json', function(err) {
          natural.LogisticRegressionClassifier.load('lr_classifier.json', null, function(err, newClassifier) {
            newClassifier.addDocument('hit some balls', 'sports');
            newClassifier.addDocument('kick a ball', 'sports');
            newClassifier.addDocument('kick and punch things', 'sports');
            newClassifier.train();

            expect(newClassifier.classify('a bug in the code')).toBe('computing');
            expect(newClassifier.classify('read all the books')).toBe('literature');
            expect(newClassifier.classify('kick butt')).toBe('sports');

            done();
          });

        });

    });
    */

  /*
    it('should only execute the callback once when failing to load a classifier', function() {
        natural.LogisticRegressionClassifier.load('nonexistant_lr_classifier.json', null, function(err, newClassifier){
          expect(err.code).toBe('ENOENT');
          expect(newClassifier).toBe(undefined);
          //asyncSpecDone();
        });
    });
    */
})

redpajama_set_name: RedPajamaGithub


text:
using System.Collections;

namespace NeuroSystem.Workflow.UserData.UI.Html.Version1.DataSources
{
    public class ObjectDataSource : DataSourceBase
    {
        public ObjectDataSource()
        {
        }

        public ObjectDataSource(IList dataObject)
        {
            DataObject = dataObject;
        }

        public IList DataObject { get; set; }

        public override object GetAll(string filtr = null)
        {
            return DataObject;
        }

        public override object GetData(long start, long cout, string sort, string filtr, out long virtualItemsCout)
        {
            virtualItemsCout = DataObject.Count;
            return DataObject;
        }
    }
}


text:
import { Template } from 'meteor/templating';
import { _ } from 'meteor/erasaur:meteor-lodash';
import { FeedbackFunctions } from '../../../api/feedback/FeedbackFunctions';
import { Semesters } from '../../../api/semester/SemesterCollection.js';
import { CourseInstances } from '../../../api/course/CourseInstanceCollection';
import { defineMethod, removeItMethod } from '../../../api/base/BaseCollection.methods';
import { Slugs } from '../../../api/slug/SlugCollection.js';
import { getRouteUserName } from '../shared/route-user-name';
import { getUserIdFromRoute } from '../shared/get-user-id-from-route';
import { userInteractionDefineMethod } from '../../../api/analytic/UserInteractionCollection.methods';

Template.Student_Explorer_Courses_Widget_Button.helpers({
  equals(a, b) {
    return a === b;
  },
  existingSemesters() {
    const semesters = [];
    const { course } = this;
    const ci = CourseInstances.find({
      studentID: getUserIdFromRoute(),
      courseID: course._id,
    }).fetch();
    _.forEach(ci, function (c) {
      const semester = Semesters.findDoc(c.semesterID);
      if (semester.semesterNumber >= Semesters.getCurrentSemesterDoc().semesterNumber) {
        semesters.push(Semesters.toString(c.semesterID, false));
      }
    });
    return semesters;
  },
  nextYears(amount) {
    const nextYears = [];
    const currentSem = Semesters.getCurrentSemesterDoc();
    let currentYear = currentSem.year;
    for (let i = 0; i < amount; i += 1) {
      nextYears.push(currentYear);
      currentYear += 1;
    }
    return nextYears;
  },
  yearSemesters(year) {
    const semesters = [`Spring ${year}`, `Summer ${year}`, `Fall ${year}`];
    return semesters;
  },
});

Template.Student_Explorer_Courses_Widget_Button.events({
  'click .addToPlan': function clickItemAddToPlan(event) {
    event.preventDefault();
    const { course } = this;
    const semester = event.target.text;
    const courseSlug = Slugs.findDoc({ _id: course.slugID });
    const semSplit = semester.split(' ');
    const semSlug = `${semSplit[0]}-${semSplit[1]}`;
    const username = getRouteUserName();
    const collectionName = CourseInstances.getCollectionName();
    const definitionData = {
      semester: semSlug,
      course: courseSlug,
      verified: false,
      note: course.number,
      grade: 'B',
      student: username,
    };
    defineMethod.call({ collectionName, definitionData }, (error) => {
      if (!error) {
        FeedbackFunctions.checkPrerequisites(getUserIdFromRoute());
        // FeedbackFunctions.checkCompletePlan(getUserIdFromRoute());
        // FeedbackFunctions.generateRecommendedCourse(getUserIdFromRoute());
        FeedbackFunctions.checkOverloadedSemesters(getUserIdFromRoute());
        FeedbackFunctions.generateNextLevelRecommendation(getUserIdFromRoute());
      }
    });
    const interactionData = { username, type: 'addCourse', typeData: courseSlug.name };
    userInteractionDefineMethod.call(interactionData, (err) => {
      if (err) {
        console.log('Error creating UserInteraction', err);
      }
    });
  },
  'click .removeFromPlan': function clickItemRemoveFromPlan(event) {
    event.preventDefault();
    const { course } = this;
    const semester = event.target.text;
    const semSplit = semester.split(' ');
    const semSlug = `${semSplit[0]}-${semSplit[1]}`;
    const semID = Semesters.getID(semSlug);
    const collectionName = CourseInstances.getCollectionName();
    const ci = CourseInstances.find({
      studentID: getUserIdFromRoute(),
      courseID: course._id,
      semesterID: semID,
    }).fetch();
    if (ci > 1) {
      console.log('Too many course instances found for a single semester.');
    }
    removeItMethod.call({ collectionName, instance: ci[0]._id }, (error) => {
      if (!error) {
        FeedbackFunctions.checkPrerequisites(getUserIdFromRoute());
        // FeedbackFunctions.checkCompletePlan(getUserIdFromRoute());
        // FeedbackFunctions.generateRecommendedCourse(getUserIdFromRoute());
        FeedbackFunctions.checkOverloadedSemesters(getUserIdFromRoute());
        FeedbackFunctions.generateNextLevelRecommendation(getUserIdFromRoute());
      }
    });
    const interactionData = {
      username: getRouteUserName(), type: 'removeCourse',
      typeData: Slugs.getNameFromID(course.slugID),
    };
    userInteractionDefineMethod.call(interactionData, (err) => {
      if (err) {
        console.log('Error creating UserInteraction', err);
      }
    });
  },
});

Template.Student_Explorer_Courses_Widget_Button.onRendered(function studentExplorerCoursesWidgetButtonOnRendered() {
  const template = this;
  template.$('.chooseYear')
    .popup({
      on: 'click',
    });
  template.$('.chooseSemester')
    .popup({
      on: 'click',
    });
});


text:
<?php
/**
 * Jetpack Compatibility File
 * See: http://jetpack.me/
 *
 * @package storefront
 */

/**
 * Add theme support for Infinite Scroll.
 * See: http://jetpack.me/support/infinite-scroll/
 */
function storefront_jetpack_setup() {
	add_theme_support( 'infinite-scroll', array(
		'container' => 'main',
		'footer'    => 'page',
	) );
}

/**
 * Enqueue jetpack styles.
 * @since  1.6.1
 */
function storefront_jetpack_scripts() {
	global $storefront_version;

	if ( class_exists( 'Jetpack' ) ) {
		wp_enqueue_style( 'storefront-jetpack-style', get_template_directory_uri() . '/inc/jetpack/css/jetpack.css', '', $storefront_version );
		wp_style_add_data( 'storefront-jetpack-style', 'rtl', 'replace' );
	}
}


text:
pytest-2.8.6
============

pytest is a mature Python testing tool with more than a 1100 tests
against itself, passing on many different interpreters and platforms.
This release is supposed to be drop-in compatible to 2.8.5.

See below for the changes and see docs at:

    http://pytest.org

As usual, you can upgrade from pypi via::

    pip install -U pytest

Thanks to all who contributed to this release, among them:

    AMiT Kumar
    Bruno Oliveira
    Erik M. Bray
    Florian Bruhin
    Georgy Dyuldin
    Jeff Widman
    Kartik Singhal
    Loïc Estève
    Manu Phatak
    Peter Demin
    Rick van Hattem
    Ronny Pfannschmidt
    Ulrich Petri
    foxx

Happy testing,
The py.test Development Team

2.8.6 (compared to 2.8.5)
-------------------------

- fix #1259: allow for double nodeids in junitxml,
  this was a regression failing plugins combinations
  like pytest-pep8 + pytest-flakes

- Workaround for exception that occurs in pyreadline when using
  ``--pdb`` with standard I/O capture enabled.
  Thanks Erik M. Bray for the PR.

- fix #900: Better error message in case the target of a ``monkeypatch`` call
  raises an ``ImportError``.

- fix #1292: monkeypatch calls (setattr, setenv, etc.) are now O(1).
  Thanks David R. MacIver for the report and Bruno Oliveira for the PR.

- fix #1223: captured stdout and stderr are now properly displayed before
  entering pdb when ``--pdb`` is used instead of being thrown away.
  Thanks Cal Leeming for the PR.

- fix #1305: pytest warnings emitted during ``pytest_terminal_summary`` are now
  properly displayed.
  Thanks Ionel Maries Cristian for the report and Bruno Oliveira for the PR.

- fix #628: fixed internal UnicodeDecodeError when doctests contain unicode.
  Thanks Jason R. Coombs for the report and Bruno Oliveira for the PR.

- fix #1334: Add captured stdout to jUnit XML report on setup error.
  Thanks Georgy Dyuldin for the PR.


text:
#ifndef QSIMPLEXMLNODEMODEL_H
#define QSIMPLEXMLNODEMODEL_H

#include <QtXmlPatterns/QAbstractXmlNodeModel>
#include <QtXmlPatterns/QXmlQuery>

QT_BEGIN_HEADER

QT_BEGIN_NAMESPACE

QT_MODULE(XmlPatterns)

template<typename T> class QExplicitlySharedDataPointer;
class QSimpleXmlNodeModelPrivate;
class Q_XMLPATTERNS_EXPORT QSimpleXmlNodeModel : public QAbstractXmlNodeModel
{
public:
    QSimpleXmlNodeModel(const QXmlNamePool &namePool);
    virtual ~QSimpleXmlNodeModel();

    virtual QUrl baseUri(const QXmlNodeModelIndex &node) const;
    QXmlNamePool &namePool() const;
    virtual QVector<QXmlName> namespaceBindings(const QXmlNodeModelIndex&) const;
    virtual QString stringValue(const QXmlNodeModelIndex &node) const;
    virtual QXmlNodeModelIndex elementById(const QXmlName &id) const;
    virtual QVector<QXmlNodeModelIndex> nodesByIdref(const QXmlName &idref) const;

private:
    Q_DECLARE_PRIVATE(QSimpleXmlNodeModel)
};

QT_END_NAMESPACE

QT_END_HEADER

#endif


text:
package com.druk.bonjour.browser.dnssd;

import com.apple.dnssd.BrowseListener;
import com.apple.dnssd.DNSSD;
import com.apple.dnssd.DNSSDException;
import com.apple.dnssd.DNSSDService;
import com.apple.dnssd.DomainListener;
import com.apple.dnssd.QueryListener;
import com.apple.dnssd.ResolveListener;
import com.apple.dnssd.TXTRecord;

import android.content.Context;
import android.support.v4.util.ArrayMap;
import android.text.TextUtils;

import java.net.InetAddress;
import java.util.Map;

import rx.Observable;
import rx.Subscriber;

public final class RxDNSSD {

    private static final RxDNSSD INSTANCE = new RxDNSSD();
    private Context mContext;

    public static void init(Context ctx) {
        INSTANCE.mContext = ctx;
    }

    public static Observable<BonjourService> resolve(Observable<BonjourService> observable) {
        return observable.flatMap(bs -> {
            if ((bs.flags & BonjourService.DELETED_MASK) == BonjourService.DELETED_MASK) {
                return Observable.just(bs);
            }
            return new RxDNSSDService<BonjourService> (){

                @Override
                protected DNSSDService getService(Subscriber<? super BonjourService> subscriber) throws DNSSDException {

                    return DNSSD.resolve(bs.flags, bs.ifIndex, bs.serviceName, bs.regType, bs.domain, new ResolveListener() {
                        @Override
                        public void serviceResolved(DNSSDService resolver, int flags, int ifIndex, String fullName, String hostName, int port, TXTRecord txtRecord) {
                            bs.port = port;
                            bs.hostname = hostName;
                            bs.dnsRecords.clear();
                            bs.dnsRecords.put(BonjourService.DNS_RECORD_KEY_ADDRESS, "0.0.0.0:" + bs.port);
                            bs.dnsRecords.putAll(parseTXTRecords(txtRecord));
                            bs.timestamp = System.currentTimeMillis();
                            subscriber.onNext(bs);
                            subscriber.onCompleted();
                            resolver.stop();
                        }

                        @Override
                        public void operationFailed(DNSSDService service, int errorCode) {
                            subscriber.onError(new RuntimeException("DNSSD resolve error: " + errorCode));
                        }
                    });

                }
            }.getObservable(INSTANCE.mContext);
        });
    }

    public static Observable<BonjourService> queryRecords(Observable<BonjourService> observable) {
        return observable.flatMap(bs -> {
            if ((bs.flags & BonjourService.DELETED_MASK) == BonjourService.DELETED_MASK) {
                return Observable.just(bs);
            }
            return new RxDNSSDService<BonjourService> () {

                @Override
                protected DNSSDService getService(Subscriber<? super BonjourService> subscriber) throws DNSSDException {
                    return DNSSD.queryRecord(0, bs.ifIndex, bs.hostname, 1 /* ns_t_a */, 1 /* ns_c_in */, new QueryListener() {

                        @Override
                        public void queryAnswered(DNSSDService query, int flags, int ifIndex, String fullName, int rrtype, int rrclass, byte[] rdata, int ttl) {
                            try {
                                InetAddress address = InetAddress.getByAddress(rdata);
                                bs.dnsRecords.put(BonjourService.DNS_RECORD_KEY_ADDRESS, address.getHostAddress() + ":" + bs.port);
                                subscriber.onNext(bs);
                                subscriber.onCompleted();
                            } catch (Exception e) {
                                subscriber.onError(e);
                            } finally {
                                query.stop();
                            }
                        }

                        @Override
                        public void operationFailed(DNSSDService service, int errorCode) {
                            subscriber.onError(new RuntimeException("DNSSD queryRecord error: " + errorCode));
                        }
                    });
                }

            }.getObservable(INSTANCE.mContext);
        });
    }

    public static Observable<BonjourService> browse(final String regType, final String domain) {
        return new RxDNSSDService<BonjourService> (){

            @Override
            protected DNSSDService getService(Subscriber<? super BonjourService> subscriber) throws DNSSDException {
                return DNSSD.browse(0, DNSSD.ALL_INTERFACES, regType, domain, new BrowseListener() {
                    @Override
                    public void serviceFound(DNSSDService browser, int flags, int ifIndex, String serviceName, String regType, String domain) {
                        if (!subscriber.isUnsubscribed()) {
                            BonjourService service = new BonjourService(flags, ifIndex, serviceName, regType, domain);
                            subscriber.onNext(service);
                        }
                    }

                    @Override
                    public void serviceLost(DNSSDService browser, int flags, int ifIndex, String serviceName, String regType, String domain) {
                        if (!subscriber.isUnsubscribed()) {
                            BonjourService service = new BonjourService(flags | BonjourService.DELETED_MASK, ifIndex, serviceName, regType, domain);
                            subscriber.onNext(service);
                        }
                    }

                    @Override
                    public void operationFailed(DNSSDService service, int errorCode) {
                        if (!subscriber.isUnsubscribed()) {
                            subscriber.onError(new RuntimeException("DNSSD browse error: " + errorCode));
                        }
                    }
                });
            }
        }.getObservable(INSTANCE.mContext);
    }

    public static Observable<String> enumerateDomains() {
        return new RxDNSSDService<String>(){

            @Override
            protected DNSSDService getService(Subscriber<? super String> subscriber) throws DNSSDException {
                return DNSSD.enumerateDomains(DNSSD.BROWSE_DOMAINS, DNSSD.ALL_INTERFACES, new DomainListener() {
                    @Override
                    public void domainFound(DNSSDService domainEnum, int flags, int ifIndex, String domain) {
                        subscriber.onNext(domain);
                    }

                    @Override
                    public void domainLost(DNSSDService domainEnum, int flags, int ifIndex, String domain) {

                    }

                    @Override
                    public void operationFailed(DNSSDService service, int errorCode) {
                        subscriber.onError(new RuntimeException("DNSSD browse error: " + errorCode));
                    }
                });
            }
        }.getObservable(INSTANCE.mContext);
    }

    private static Map<String, String> parseTXTRecords(TXTRecord record) {
        Map<String, String> result = new ArrayMap<>();
        for (int i = 0; i < record.size(); i++) {
            if (!TextUtils.isEmpty(record.getKey(i)) && !TextUtils.isEmpty(record.getValueAsString(i)))
                result.put(record.getKey(i), record.getValueAsString(i));
        }
        return result;
    }

    private abstract static class RxDNSSDService<T> {

        private DNSSDService mService;

        private RxDNSSDService(){}

        private void startDaemonProcess(Context ctx) {
            ctx.getSystemService(Context.NSD_SERVICE);
        }

        protected abstract DNSSDService getService(Subscriber<? super T> subscriber) throws DNSSDException;

        protected Observable<T> getObservable(final Context context){
            return Observable.create(new Observable.OnSubscribe<T>() {
                @Override
                public void call(Subscriber<? super T> subscriber) {
                    if (!subscriber.isUnsubscribed()) {
                        startDaemonProcess(context);
                        try {
                            mService = getService(subscriber);
                        } catch (DNSSDException e) {
                            e.printStackTrace();
                            subscriber.onError(e);
                        }
                    }
                }
            }).doOnUnsubscribe(() -> {
                if (mService != null) {
                    mService.stop();
                    mService = null;
                }
            });
        }
    }

}


text:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.patches import Rectangle
from mpl_toolkits.mplot3d import Axes3D
import mpl_toolkits.mplot3d.art3d as art3d

class DroneLanding:
    def __init__(self, world_size=11):
        """ Create a new drone-landing environment.

        It is possible to pass the parameter of the simulation.
        @param world_size is the size of the world (in meters),
            it must be a positive integer.
        """
        self.position_list = list()
        self.world_size = world_size
        self.position_x = np.random.randint(low=0, high=world_size)
        self.position_y = np.random.randint(low=0, high=world_size)
        self.position_z = np.random.randint(low=0, high=world_size)
        self.center_x = int(world_size / 2)
        self.center_y = int(world_size / 2)
        self.center_z = 0

    def reset(self, exploring_starts=True, initial_position=[0,0,0]):
        """ It reset the car to an initial position [-1.2, 0.5]

        @param exploring_starts: if True a random position is taken
        @param initial_position: the initial position of the drone (requires exploring_starts=False)
        @return: it returns the initial position [x,y,z] of the drone
        """
        if exploring_starts:
            self.position_x = np.random.randint(low=0, high=self.world_size)
            self.position_y = np.random.randint(low=0, high=self.world_size)
            self.position_z = np.random.randint(low=0, high=self.world_size)
        else:
            self.position_x = initial_position[0]
            self.position_y = initial_position[1]
            self.position_z = initial_position[2]

        self.position_list = []  # clear the list
        self.position_list.append(initial_position)
        return [self.position_x, self.position_y, self.position_z]

    def step(self, action):
        """Perform one step in the environment following the action.

        @param action: an integer representing one of three actions [0, 1, 2, 3, 4, 5]
         where 0=forward, 1=left, 2=backward, 3=right, 4=up, 5=down
        @return: [x,y,z], reward, done
         where reward is always negative but when the goal is reached
         done is True when the goal is reached
        """
        if action == 0:
            self.position_x += 1  # FORWARD
        elif action == 1:
            self.position_y += 1  # LEFT
        elif action == 2:
            self.position_x -= 1  # BACKWARD
        elif action == 3:
            self.position_y -= 1  # RIGHT
        elif action == 4:
            self.position_z += 1  # UP
        elif action ==5:
            self.position_z -= 1  # DOWN
        else:
            raise ValueError("[DRONE LANDING][ERROR] The action value "
                             + str(action) + " is out of range.")

        # Check if the drone is outside the bounding box
        if self.position_x >= self.world_size:
            self.position_x = self.world_size - 1
        elif self.position_x < 0:
            self.position_x = 0
        if self.position_y >= self.world_size:
            self.position_y = self.world_size - 1
        elif self.position_y < 0:
            self.position_y = 0
        if self.position_z >= self.world_size:
            self.position_z = self.world_size - 1
        elif self.position_z < 0:
            self.position_z = 0

        # append the position in the list
        self.position_list.append([self.position_x, self.position_y, self.position_z])

        # The drone landed!!!
        if self.position_x == self.center_x and self.position_y == self.center_y and self.position_z == self.center_z:
            reward = 1.0
            done = True
            return [self.position_x, self.position_y, self.position_z], reward, done

        # Drone landed outside the pad.
        if self.position_z == self.center_z:
            reward = -1.0
            done = True
            return [self.position_x, self.position_y, self.position_z], reward, done

        # Nothing special happened
        reward = -0.01
        done = False
        return [self.position_x, self.position_y, self.position_z], reward, done

    def render(self, file_path='./drone.mp4', mode='mp4'):
        """ When the method is called it saves an animation
        of what happened until that point in the episode.
        Ideally it should be called at the end of the episode,
        and every k episodes.

        ATTENTION: It requires avconv and/or imagemagick installed.
        @param file_path: the name and path of the video file
        @param mode: the file can be saved as 'gif' or 'mp4'
        """
        # Internal function used to plot animation
        def _animate(i):
            x = self.position_list[i][0]
            y = self.position_list[i][1]
            z = self.position_list[i][2]
            #print x,y,z,num
            graph._offsets3d = ([x], [y], [z])
            title.set_text('Time={}s'.format(i))
        # Define the figure and the plot (with axis limits)
        fig = plt.figure()
        ax = fig.add_subplot(111, projection='3d', autoscale_on=False,
                             xlim=(-1, self.world_size+1), ylim=(-1, self.world_size+1), zlim=(0, self.world_size))
        # Set the tick label
        if self.world_size < 15:
            ax.set_xticklabels(np.arange(0, self.world_size+1))
            ax.set_yticklabels(np.arange(0, self.world_size+1))
        else:
            #ax.set_xticklabels([])
            step = int(self.world_size / 10.0)
            label_list = list()
            for i in range(self.world_size):
                if i % step == 0:
                    label_list.append(str(i))
                else:
                    label_list.append('')
            ax.set_yticklabels(label_list)
            ax.set_xticklabels(label_list)
            ax.set_zticklabels(label_list)

        # Set the ticks
        ax.set_xticks(np.arange(0,self.world_size+1))
        ax.set_yticks(np.arange(0,self.world_size+1))
        ax.set_zticks(np.arange(0,self.world_size))
        # Set title and title location
        title = ax.set_title('', loc='left')
        # Draw the red rectangle
        p = Rectangle((0, 0), self.world_size, self.world_size, color="red", alpha=0.5)
        ax.add_patch(p)
        art3d.pathpatch_2d_to_3d(p, z=0, zdir="z")
        # Draw the green rectangle
        p = Rectangle((self.center_x, self.center_y), 1, 1, color="green")
        ax.add_patch(p)
        art3d.pathpatch_2d_to_3d(p, z=0.1, zdir="z")
        # Get the starting position
        x = self.position_list[0][0]
        y = self.position_list[0][1]
        z = self.position_list[0][2]
        graph = ax.scatter([x], [y], [z], c='r', marker='o')
        # Define the animation
        ani = animation.FuncAnimation(fig, _animate, frames=np.arange(1, len(self.position_list)), blit=False, repeat=False)
        # Saving in gif or video
        if mode == 'gif':
            ani.save(file_path, writer='imagemagick', fps=5)
        elif mode == 'mp4':
            ani.save(file_path, fps=5, writer='avconv', codec='libx264')
        # Clear the figure
        fig.clear()
        plt.close(fig)


text:
local Container, parent = torch.class('nn.Container', 'nn.Module')

function Container:__init(...)
    parent.__init(self, ...)
    self.modules = {}
end

function Container:add(module)
    table.insert(self.modules, module)
    return self
end

function Container:get(index)
    return self.modules[index]
end

function Container:size()
    return #self.modules
end

-- Check if passing arguments through xpcall is supported in this Lua interpreter.
local _, XPCALL_ARGS = xpcall(function(x) return x ~= nil end, function() end, 1)
local TRACEBACK_WARNING = "WARNING: If you see a stack trace below, it doesn't point to the place where this error occurred. Please use only the one above."
-- module argument can be retrieved with moduleIndex, but code is cleaner when
-- it has to be specified anyway.
function Container:rethrowErrors(module, moduleIndex, funcName, ...)
   assert(module == self.modules[moduleIndex],
          "mismatch between moduleIndex and self.modules in rethrowErrors")
   local function handleError(err)
      -- This will be executed only in the first container that handles the error.
      if not err:find(TRACEBACK_WARNING) then
         local traceback = debug.traceback()
         -- Remove this handler from the stack
         local _, first_line_end = traceback:find('^.-\n')
         local _, second_line_end = traceback:find('^.-\n.-\n')
         traceback = traceback:sub(1, first_line_end) .. traceback:sub(second_line_end+1)
         err = err .. '\n' .. traceback .. '\n\n' .. TRACEBACK_WARNING
      else
         -- Remove file path
         err = err:sub(err:find('\n')+1)
      end
      local msg = string.format('In %d module of %s:',
                              moduleIndex, torch.type(self))
      -- Preceding newline has to be here, because Lua will prepend a file path.
      err = '\n' .. msg .. '\n' .. err
      return err
   end

   -- Lua 5.1 doesn't support passing arguments through xpcall, so they have to
   -- be passed via a closure. This incurs some overhead, so it's better not to
   -- make it the default.
   local ok, ret, noret
   if not XPCALL_ARGS then
      local args = {...}
      local unpack = unpack or table.unpack
      ok, ret, noret = xpcall(function()
                                 return module[funcName](module, unpack(args))
                              end,
                              handleError)
   else
      ok, ret, noret = xpcall(module[funcName], handleError, module, ...)
   end
   assert(noret == nil, "rethrowErrors supports only one return argument")

   if not ok then error(ret) end
   return ret
end

function Container:applyToModules(func)
    for _, module in ipairs(self.modules) do
        func(module)
    end
end

function Container:zeroGradParameters()
    self:applyToModules(function(module) module:zeroGradParameters() end)
end

function Container:updateParameters(learningRate)
    self:applyToModules(function(module) module:updateParameters(learningRate) end)
end

function Container:training()
    self:applyToModules(function(module) module:training() end)
    parent.training(self)
end

function Container:evaluate()
    self:applyToModules(function(module) module:evaluate() end)
    parent.evaluate(self)
end

function Container:share(mlp, ...)
    for i=1,#self.modules do
        self.modules[i]:share(mlp.modules[i], ...);
    end
    return self
end

function Container:reset(stdv)
    self:applyToModules(function(module) module:reset(stdv) end)
end

function Container:parameters()
    local function tinsert(to, from)
        if type(from) == 'table' then
            for i=1,#from do
                tinsert(to,from[i])
            end
        else
            table.insert(to,from)
        end
    end
    local w = {}
    local gw = {}
    for i=1,#self.modules do
        local mw,mgw = self.modules[i]:parameters()
        if mw then
            tinsert(w,mw)
            tinsert(gw,mgw)
        end
    end
    return w,gw
end

function Container:clearState()
   -- don't call set because it might reset referenced tensors
   local function clear(f)
      if self[f] then
         if torch.isTensor(self[f]) then
            self[f] = self[f].new()
         elseif type(self[f]) == 'table' then
            self[f] = {}
         else
            self[f] = nil
         end
      end
   end
   clear('output')
   clear('gradInput')
   if self.modules then
      for i,module in pairs(self.modules) do
         module:clearState()
      end
   end
   return self
end


text:
namespace Epic::EON::detail
{
	template<class T, class Converter>
	class ConversionVisitor;

	class InheritVisitor;
	class MergeVisitor;
	class FilterVisitor;
	class TypeNameVisitor;
}

//////////////////////////////////////////////////////////////////////////////

// ConversionVisitor
template<class T, class Converter>
class Epic::EON::detail::ConversionVisitor
{
private:
	T& m_To;
	Converter m_ConvertFn;
	const EONObject& m_GlobalScope;

public:
	ConversionVisitor() = delete;
	ConversionVisitor(T& to, Converter convertFn, const EONObject& scope)
		: m_To(to), m_ConvertFn(std::move(convertFn)), m_GlobalScope(scope) { }

private:
	using Traits = EONTraits<T>;

	using MakeArrayTag =
		std::conditional_t<Traits::IsVectorLike || Traits::IsSetLike, ArrayTag,
		std::conditional_t<Traits::IsIndexableScalar, ScalarTag,
		FailTag>>;

	using MakeObjectTag = std::conditional_t<Traits::IsMapLike, MapTag, FailTag>;

	using MakeScalarTag =
		std::conditional_t<!Traits::IsContainer, ScalarTag,
		std::conditional_t<Traits::IsVectorLike, ArrayTag,
		std::conditional_t<Traits::IsSetLike, SetTag,
		FailTag>>>;

	template<class... Params>
	using ResizeImpl = decltype(std::declval<T>().resize(std::declval<Params>()...));

private:
	template<class S>
	bool DoScalarConversion(const S&, FailTag) { return false; }

	template<class S>
	bool DoScalarConversion(const S& v, ScalarTag)
	{
		return ConvertIf(m_ConvertFn, m_To, v);
	}

	template<class S>
	bool DoScalarConversion(const S& v, ArrayTag)
	{
		using Item = typename T::value_type;

		static_assert(std::is_default_constructible_v<Item>, "Array value type must be default constructible");

		Item item;

		if (!ConvertIf(m_ConvertFn, item, v))
			return false;

		m_To.emplace_back(std::move(item));

		return true;
	}

	template<class S>
	bool DoScalarConversion(const S& v, SetTag)
	{
		using Item = typename T::key_type;

		static_assert(std::is_default_constructible_v<Item>, "Set key type must be default constructible");

		Item item;

		if (!ConvertIf(m_ConvertFn, item, v))
			return false;

		m_To.emplace(std::move(item));

		return true;
	}

	bool DoArrayConversion(const EONArray&, FailTag) { return false; }

	bool DoArrayConversion(const EONArray& v, ScalarTag)
	{
		using Item = std::decay_t<decltype(m_To[0])>;

		static_assert(std::is_default_constructible_v<Item>, "Array value type must be default constructible");

		if constexpr (Epic::TMP::IsDetected<ResizeImpl, size_t>::value)
			m_To.resize(v.Members.size());

		for(decltype(v.Members.size()) i = 0; i < v.Members.size(); ++i)
		{
			if (i >= std::size(m_To))
				break;

			Item item;

			if (!std::visit(ConversionVisitor<Item, Converter>(item, m_ConvertFn, m_GlobalScope), v.Members[i].Data))
				return false;

			m_To[i] = std::move(item);
		}

		return true;
	}

	bool DoArrayConversion(const EONArray& v, ArrayTag)
	{
		for (const auto& vm : v.Members)
		{
			if (!std::visit(ConversionVisitor<T, Converter>(m_To, m_ConvertFn, m_GlobalScope), vm.Data))
				return false;
		}

		return true;
	}

	bool DoObjectConversion(const EONObject&, FailTag) { return false; }

	bool DoObjectConversion(const EONObject& v, MapTag)
	{
		using Key = typename T::key_type;
		using Item = typename T::mapped_type;

		static_assert(std::is_default_constructible_v<Key>, "Map key type must be default constructible");
		static_assert(std::is_default_constructible_v<Item>, "Map mapped type must be default constructible");

		for (const auto& vm : v.Members)
		{
			Key key;
			if (!ConvertIf(m_ConvertFn, key, vm.Name))
				return false;

			Item value;
			if (!std::visit(ConversionVisitor<Item, Converter>(value, m_ConvertFn, m_GlobalScope), vm.Value.Data))
				return false;

			m_To.emplace(std::move(key), std::move(value));
		}

		return true;
	}

public:
	template<class Scalar>
	bool operator () (const Scalar& v)
	{
		return DoScalarConversion(v.Value, MakeScalarTag());
	}

	bool operator () (const EONArray& v)
	{
		return DoArrayConversion(v, MakeArrayTag());
	}

	bool operator () (const EONObject& v)
	{
		return DoObjectConversion(v, MakeObjectTag());
	}
};

//////////////////////////////////////////////////////////////////////////////

// InheritVisitor
class Epic::EON::detail::InheritVisitor
{
public:
	InheritVisitor() = default;

private:
	template<class From, class To>
	void Inherit(To&, const From&) const
	{
		throw InvalidValueException("Incompatible types.");
	}

	template<class Type>
	void Inherit(Type& to, const Type& from) const
	{
		to.Value = from.Value;
	}

	void Inherit(EONObject& to, const EONObject& from) const
	{
		std::copy(std::begin(from.Members),
				  std::end(from.Members),
				  std::inserter(to.Members, std::begin(to.Members)));
	}

	void Inherit(EONArray& to, const EONArray& from) const
	{
		std::copy(std::begin(from.Members),
				  std::end(from.Members),
				  std::inserter(to.Members, std::begin(to.Members)));
	};

	void Inherit(EONString& to, const EONString& from) const
	{
		to.Value.insert(0, from.Value);
	}

public:
	template<class From, class To>
	void operator() (To& to, const From& from) const
	{
		Inherit(to, from);
	}
};

//////////////////////////////////////////////////////////////////////////////

// MergeVisitor
class Epic::EON::detail::MergeVisitor
{
private:
	EONVariant& _To;
	const EONVariant& _From;

public:
	MergeVisitor(EONVariant& to, const EONVariant& from)
		: _From{ from }, _To{ to } { }

private:
	template<class From, class To>
	void Merge(To&, const From&)
	{
		_To = _From;
	}

	void Merge(EONObject& to, const EONObject& from)
	{
		// Move all of the members of "from" to "to"
		for (auto& vfrom : from.Members)
		{
			bool isDuplicate = false;

			for (auto& vto : to.Members)
			{
				if (vto.Name == vfrom.Name)
				{
					isDuplicate = true;

					MergeVisitor vsMerger(vto.Value, vfrom.Value);
					std::visit(vsMerger, vto.Value.Data, vfrom.Value.Data);

					break;
				}
			}

			if (!isDuplicate)
				to.Members.emplace_back(vfrom);
		}
	};

public:
	template<class From, class To>
	void operator() (To& to, const From& from)
	{
		Merge(to, from);
	}
};

//////////////////////////////////////////////////////////////////////////////

// FilterVisitor
class Epic::EON::detail::FilterVisitor
{
private:
	size_t _Filter;

public:
	explicit FilterVisitor(eEONVariantType filter) noexcept
		: _Filter(size_t(filter)) { }

public:
	bool operator() (const EONInteger& v) { return (_Filter & size_t(eEONVariantType::Integer)) != 0; }
	bool operator() (const EONFloat& v) { return (_Filter & size_t(eEONVariantType::Float)) != 0; }
	bool operator() (const EONBoolean& v) { return (_Filter & size_t(eEONVariantType::Boolean)) != 0; }
	bool operator() (const EONString& v) { return (_Filter & size_t(eEONVariantType::String)) != 0; }
	bool operator() (const EONArray& v) { return (_Filter & size_t(eEONVariantType::Array)) != 0; }
	bool operator() (const EONObject& v) { return (_Filter & size_t(eEONVariantType::Object)) != 0; }
};

//////////////////////////////////////////////////////////////////////////////

// TypeNameVisitor
class Epic::EON::detail::TypeNameVisitor
{
public:
	STLString<char> operator() (const EONInteger& v) { return "INTEGER"; }
	STLString<char> operator() (const EONFloat& v) { return "FLOAT"; }
	STLString<char> operator() (const EONBoolean& v) { return "BOOLEAN"; }
	STLString<char> operator() (const EONString& v) { return "STRING"; }
	STLString<char> operator() (const EONArray& v) { return "ARRAY"; }
	STLString<char> operator() (const EONObject& v) { return "OBJECT"; }
};


text:
"""
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2011 Cisco Systems, Inc.  All rights reserved.
#
#    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.
#
# @author: Ying Liu, Cisco Systems, Inc.
#
"""

def get_view_builder(req):
    """get view builder """
    base_url = req.application_url
    return ViewBuilder(base_url)

class ViewBuilder(object):
    """
    ViewBuilder for Credential,
    derived from quantum.views.networks
    """
    def __init__(self, base_url):
        """
        :param base_url: url of the root wsgi application
        """
        self.base_url = base_url

    def build(self, credential_data, is_detail=False):
        """Generic method used to generate a credential entity."""
        if is_detail:
            credential = self._build_detail(credential_data)
        else:
            credential = self._build_simple(credential_data)
        return credential

    def _build_simple(self, credential_data):
        """Return a simple description of credential."""
        return dict(credential=dict(id=credential_data['credential_id']))

    def _build_detail(self, credential_data):
        """Return a detailed description of credential."""
        return dict(credential=dict(id=credential_data['credential_id'],
                                name=credential_data['user_name'],
                                password=credential_data['password']))


text:
// Copyright (c) 2003-present, Jodd Team (jodd.org). All Rights Reserved.

package jodd.lagarto;

/**
 * Parsing state.
 */
public interface State {

	/**
	 * Parses content.
	 */
	public void parse();

}


text:
const express = require('express');
const helmet = require('helmet'); // secure
const logger = require('morgan');
const expressSession = require('express-session');
const RedisStore = require('connect-redis')(expressSession);
const redisClient = require('./config/redis-client');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');

// passport local
const passport = require('./config/passport');

// common router
const router = require('./routes');

const app = express();
app.use(helmet()); // secure my express apps by setting various HTTP headers.

// ---------- GZip Compress all response -------------//
app.use(require('compression')());
// ---------- GZip End -------------//

// 设置Express的session存储中间件
app.use(cookieParser());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(expressSession({
  name: 'sessionId',
  store: new RedisStore({
    client: redisClient
  }),
  secret: 'honeymorningjdkljfjsdiwuerzxcmlaoroq4asdasd4qwe',
  resave: false,
  saveUninitialized: false,
  cookie: {
    maxAge: 1 * 24 * 60 * 60 * 1000 // 1 day
  }
}));

// 缓存Wechat token
app.use(expressSession({
  name: 'access_token',
  store: new RedisStore({
    client: redisClient
  }),
  secret: 'honeymorningjdkljfjsdiwuerzxcmlaoroq4asdasd4qwe',
  resave: false,
  saveUninitialized: false,
  cookie: {
    maxAge: 7200 * 1000 // 2h
  }
}));

// 缓存 Wechat jsapi_ticket
app.use(expressSession({
  name: 'jsapi_ticket',
  store: new RedisStore({
    client: redisClient
  }),
  secret: 'honeymorningjdkljfjsdiwuerzxcmlaoroq4asdasd4qwe',
  resave: false,
  saveUninitialized: false,
  cookie: {
    maxAge: 7200 * 1000 // 2h
  }
}));

// use passport
app.use(passport.initialize());
app.use(passport.session());

// ============ 支持跨域请求 =============//
// app.all('*', (req, res, next) => {
//   res.header('Access-Control-Allow-Origin', 'http://localhost:9000');
//   res.header('Access-Control-Allow-Credentials', true);
//   res.header('X-Frame-Options', 'ALLOW-FROM');
//   res.header('Access-Control-Allow-Headers', 'Content-Type,Content-Length, Authorization, Accept,X-Requested-With');
//   res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS');
//   // res.header("X-Powered-By", ' 3.2.1')
//   if (req.method === 'OPTIONS') {
//     res.sendStatus(200); /* 让options请求快速返回*/
//   } else {
//     next();
//   }
// });
// ============ 跨域 End ===============//

// 所有请求都验证用户是否已经登录
// app.use((req, res, next) => {
//   if (!req.session.user) { // 未登录,如果不是登录注册找回密码页面,则跳转到登录页面
//     // res.redirect('/account/login');

//     next();
//   } else { // 已登录
//     next();
//   }
// });

// 添加 access_token
// app.use('*', (req, res, next) => {
//   // 如果没有,set cookie
//   if (!req.cookies['access_token']) {
//     res.cookie('access_token', `hm${new Date().valueOf()}`);
//   }
//   next();
// });

// ============ Route Start ==========//
app.use('/v1', router);
// ============= Route End ========//

// catch 404 and forward to error handler
app.use((req, res, next) => {
  if (!req.session) {
    return next(new Error('no session'));
  }

  const err = {
    code: 404,
    data: null,
    msg: 'Not Found!'
  };
  next(err);
});

// error handler
app.use((err, req, res, next) => {
  // set locals, only providing error in development
  res.locals.message = err.msg;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.json(err);
});

module.exports = app;


text:
require "spec_helper"

RSpec.describe Keisan::AST::Cache do
  describe "caching" do
    context "not frozen" do
      it "adds to the cache when calling #fetch_or_build" do
        cache = described_class.new

        expect(cache.instance_variable_get(:@cache)).to eq({})
        expect(cache.has_key?("x+1")).to eq false
        expect(cache.fetch_or_build("x+1")).to be_a(Keisan::AST::Plus)
        expect(cache.instance_variable_get(:@cache).has_key?("x+1")).to eq true
        expect(cache.has_key?("x+1")).to eq true
        expect(cache.instance_variable_get(:@cache)["x+1"]).to be_a(Keisan::AST::Plus)
        expect(cache.instance_variable_get(:@cache)["x+1"].to_s).to eq "x+1"
      end
    end

    context "frozen" do
      it "does not add to the cache when calling #fetch_or_build" do
        cache = described_class.new
        cache.freeze

        expect(cache.instance_variable_get(:@cache)).to eq({})
        expect(cache.has_key?("x+1")).to eq false
        expect(cache.fetch_or_build("x+1")).to be_a(Keisan::AST::Plus)
        expect(cache.instance_variable_get(:@cache)).to eq({})
        expect(cache.has_key?("x+1")).to eq false
      end
    end
  end

  describe "x = 15; 10*x**2 + exp(-x/5.0)" do
    it "should be at least 5 times faster than no caching" do
      # This benchmark test can sometimes be flaky (e.g. caching is only 4.8
      # times faster). To mitigate this, we will try 3 times until the benchmark
      # passes.
      attempts = 0
      success = false

      while attempts < 3
        uncached_calculator = Keisan::Calculator.new

        uncached_before = Time.now
        100.times do
          uncached_calculator.evaluate("x = 15; 10*x**2 + exp(-x/5.0)")
        end
        uncached_after = Time.now

        cache = described_class.new
        cached_calculator = Keisan::Calculator.new(cache: cache)

        cached_before = Time.now
        100.times do
          cached_calculator.evaluate("x = 15; 10*x**2 + exp(-x/5.0)")
        end
        cached_after = Time.now

        uncached_time = uncached_after - uncached_before
        cached_time = cached_after - cached_before
        success = (5 * cached_time < uncached_time)
        break if success
      end

      expect(success).to be true
    end
  end
end


text:
@import url(https://fonts.googleapis.com/css?family=Share:400,700,400italic|Neuton:400,400italic,700);

/* CSS Overrides for CSF Discussions - Version 3, as of 7 Sep 2016
   Keep copies at: /custom/css
------------------------------------------------------------------
   Be sure repo versions are updated if changes are made here.
*/

body {
color: #333;
font-family: 'neuton', georgia, serif;
font-size: 1em;
background: #f7f7ef;
line-height: 1;
}

/* Typography
------------------------------------------------------------*/

/*
********** TYPEFACE, WEIGHT & STYLE
*/

.Hero-title,
.DiscussionHero-title,
.DiscussionListItem-title,
.Post-body h2,
.Post-body h3,
.Post-body h4,
.Post-body h5,
.TagTile-name {
font-weight: normal;
font-family: 'Share', arial, sans-serif;
}

input,
button,
legend,
.Select,
.username,
.ComposerBody-mentionsWrapper,
.App-nav .AdminNav .Button-label,
.DiscussionListItem-info > .item-tags { font-family: arial, sans-serif; }

.Post-body code { font-family: 'Everson Mono', consolas, Monaco, 'Lucida Console', monospace; }

.Post-body h5,
.Post-body blockquote p { font-style: italic; }

blockquote > p .PostMention { font-style: normal; }

/*
********** FONT SIZE
*/

.Hero-subtitle { font-size: 120%; }

.Header-title,
.Header-primary { font-size: 115%; }

.Header-secondary { font-size: 140%; }

.Header-secondary .Button-label { font-size: 70%; }

.item-terminalPost,
.DiscussionListItem-info .item-excerpt { font-size: 115%; }

.username { font-size: 90%; }

.Hero-title,
.Hero h2 { font-size: 180%; }

.Dropdown-menu > li > a,
.ComposerBody-header h3 a { font-size: 115%; }

.Post-body,
.Post-body h5 { font-size: 120%; }

.Post-body h2 { font-size: 160%; }
.Post-body h3 { font-size: 145%; }
.Post-body h4 {font-size: 130%; }

.Post-body blockquote p { font-size: 105%; }

.Post-body code { font-size: 80%; }

input,
button { font-size: 84%; }

.App-nav .AdminNav .AdminLinkButton-description,
.AdminLinkButton-description,
.helpText,
.UserCard-info,
.UserBio { font-size: 105%; }

.UserBio textarea { font-size: 100%; }

.TagTile-description { font-size: 1em }
.TagTile-children,
.TagTile-lastDiscussion { font-size: .9em }

/*
********** FONT COLOR & TRANSFORMATIONS
*/

.Hero-title,
.Hero-subtitle,
button.Hero-close,
button.Hero-close i,
.Button--primary:hover { color: #fff; }

.DiscussionListItem-info,
.DiscussionListItem-info .item-excerpt { color: #777; }

.Post-body h3,
.read .DiscussionListItem-title { color: #444; }

.Post-body h4 { color: #a7a175; }
.Post-body h5 { color: #a0996d; }

.Post-body h3,
.Post-body h4,
.Post-body h5 { text-transform: none; }

.Post-body code { color: darkorange; } /* 7fa51f */
.Post-body pre code { color: brown; }

.FormControl:hover,
.Select-caret:hover { color: #333; }

blockquote > p .PostMention:after { content: ' said:'; }

/*
********** FONT LINE HEIGHT
*/

.Hero-title,
.Hero h2,
.DiscussionListItem-info .item-excerpt,
.AdminLinkButton-description,
.Header-controls > li,
.Search-input:before,
.Search-input input.FormControl { line-height: 1; }

.Hero-subtitle { line-height: 1.4; }

a#home-link,
a.LinksButton { line-height: 30px; }

/*
a#home-link,
a.LinksButton,
.Header-primary li {padding-top: 10px; }
*/

.Header-primary .Button {padding-top: 0; }

.Header-secondary .username { line-height: 24px; }

.Post-body { line-height: 1.5em; }

.Post-body pre { line-height: 1.2; }

.ComposerBody-mentionsWrapper { line-height: 1.3; }

/*
********** LINKS (STYLES ALL TOGETHER)
*/

a { color: #147a97; }
a:visited { color: #462b72; }
a:hover { color: #c11f46; }

.Post-body a { font-weight: 300; }

.Post-body a,
.Post-body a:visited {
color: #61b0c7;
border-bottom: 1px solid #61b0c7;
}

.Post-body a:visited { border-bottom-style: dashed; }

.Post-body a:hover {
color: #c11f46;
border-bottom: 1px solid #c11f46;
}

/* For links in Hero (Marquee), which just need to be white. */
.Pages .Hero a,
.Pages .Hero a:hover,
.Pages .Hero a:visited,
.UserCard-identity a:hover,
.UserCard-identity a:visited { color: #fff; }

a#home-link,
a.LinksButton {
color: #777;
display: block;
}

a#home-link:hover,
a.LinksButton:hover,
.Pages .Hero a { text-decoration: none; }

a#home-link:hover,
a.LinksButton:hover { color: #333; }

/*
********** TYPOGRAPHICAL BLOCK ELEMENTS (Positioning & Presentation)
*/

.Post-body blockquote {
border-top: 0;
border-bottom: 0;
border-left: 3px solid #a7a175;
padding-left: .7em;
margin: 1.2em 0 1.2em 1.5em;
width: auto;
background: transparent;
}

blockquote > p .PostMention {
display: block;
margin-bottom: .5em;
background: transparent;
}

/* .Post-body { padding-top: 1.5em; } */

.Pages .Post-body > h2:first-child { margin-top: 0;}

.Post-body h2 { margin-top: 1.5em; }

.Post-body h3,
.Post-body h4 { margin-bottom: .6em; }

.Post-body h5 { margin-bottom: .3em; }

.Post-body ol,
.Post-body ul {
margin-top: .6em;
margin-bottom: .6em;
}

.Post-body pre { background: #fcfcf4; }

.Post-body code {
border: 1px solid rgba(0, 0, 0, 0.1);
border-radius: 0.3em;
padding: 0.2em;
background: #fdfdfd;
}

.Post-body pre code {
background: transparent;
border: 0;
}

/* Images & Media
------------------------------------------------------------*/

.Post-body img {
margin-top: .75em;
margin-bottom: .75em;
}

.Avatar{ background: transparent; }

.UserCard-avatar .Avatar { background: #fff; }

.Hero { background: #117b99 url(https://csf.community/assets/img/marquee_bg.jpg) 50% 0 repeat-x; }

/* Masthead Layout
------------------------------------------------------------*/

/*
********** HEADER STUFF
*/

.App-header {
padding-top: 6px;
margin-bottom: 5px;
background: transparent url(https://csf.community/assets/img/stripe.jpg) 80% -15px repeat-x;
}

.App { padding-top: 95px; }

.App-nav { top: 95px; } /* For administration pages only */

.App-header {
height: 90px;
padding-left: 0;
padding-right: 0;
}

/* .App::before needs to be 5px taller than the elements above. */
.App::before { height: 95px; }

.App::before { background: #f7f7ef; }

/*
********** CONTAINERS PER SECTION
*/

.container,
.Pages .container { width: 77.5%; max-width: 77.5%; }

.container { background: transparent; }

.DiscussionPage .container { width: 90%; }

.Hero .container { padding: 3em 0; }

.container,
.DiscussionPage .container,
.content .Pages .container { padding-left: 0; padding-right: 0; }

/* Main page stuff
------------------------------------------------------------*/

.Hero { margin: 0; }

.sideNav .Dropdown--select .Dropdown-menu > li > a {
padding-top: .35em;
padding-bottom: .35em;
}

/* Discussions main
------------------------------------------------------------*/

.DiscussionHero .item-title { padding-top: 1em; }

.DiscussionListItem-info .item-excerpt { margin-right: 0; }

.DiscussionListItem-info > li { opacity: 1; }

.DiscussionListItem:hover,
.DiscussionListItem-content:hover { background: #fff; }

.sideNav > ul,
.sideNavOffset { margin-top: 20px; }

/* Left slide-out list */
.DiscussionPage-list { top: 60px; }

/* Right fixed buttons/dropdown */
.DiscussionPage-nav > ul { margin-top: 10px; }

.Placeholder p { text-align: left; }

/* Forms, controls, and button-like things
------------------------------------------------------------*/

.Button { padding: 5px 8px; }

.Button--primary,
.Button--primary.disabled {
background: #f7b917;
border: none;
}

.Search-input:before { padding: 8px 0; }

.FormControl {
border: 1px solid transparent;
border-color: #ccc;
background: #f9f9f9;
height: 30px;
}

select.FormControl { padding-top: 0; padding-bottom: 0; }

.FormControl:hover { background: #fff; }

.FormControl:hover,
.FormControl:focus { border-color: #333; }

/* The icons and user dropdown items at right of search box. */

.NotificationsDropdown .Dropdown-toggle { padding: 5px 3px; }

.SessionDropdown .Dropdown-toggle { padding: 3px; }

.Button--flat,
.NotificationsDropdown .Dropdown-toggle,
.SessionDropdown .Dropdown-toggle { border-radius: 4px; }

.SessionDropdown .Dropdown-toggle .Avatar { margin: 0; }

.TagLabel { padding: .3em .4em; }

/* Admin > Permissions
------------------------------------------------------------*/

.Dropdown-menu--top {
top:100%;
bottom: auto;
}

/* Admin > Extensions > Pages
------------------------------------------------------------*/

.Pages .Post-body {
padding-top: 2em;
}

/* Admin > Extensions > Modal popups
------------------------------------------------------------*/

.Modal-body .FormControl { padding: 3px 10px; }

.Modal-body textarea  { font-family: arial, sans-serif; }

.Form-group > label {
margin-top: 25px;
margin-bottom: 4px;
}


text:
Router
========

Waiting.


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FeatureExtractor
{
    class Program
    {
        static void Main(string[] args)
        {
            FeatureReader reader = new FeatureReader();
            Extractor extractor = new Extractor();
            FeatureTransformer transformer = new FeatureTransformer();
            FeatureWriter writer = new FeatureWriter();
            writer.write(transformer.transform(extractor.extract(reader.readRequirements(args[0]))));
        }
    }
}


text:
package fradiani.env;

/**
 * Model of an order
 */
public class AOrder {

  /**
   * Order Stop Loss
   */
  public double sl;
  /**
   * Order Take Profit
   */
  public double tp;

  public long open_time;  //order opening time
  public long close_time;  //order closing time
  public double open_price;  //opening price of the order
  public double close_price;  //closing price of the order
  public double size;  //lot size
  public String pair;  //pair of the order
  public String label;  //user-defined identification of the order
  public OType type;  //BUY or SELL

  public double commission;
  public OStatus status;
  public double profit;

  /**
   * Types of Orders
   */
  public static enum OType {
    BUY,
    SELL
  }

  /**
   * Status of an order
   */
  public static enum OStatus {
    OPENED,
    CLOSED
  }

  /**
   * Order Messages sent from the TestingEnvironment to the strategy
   */
  public static enum OMsg {
    OPENED,
    CLOSED
  }

  public AOrder() {
    close_time = 0;
    close_price = 0;
    label = "";

    sl = tp = 0;
  }
}


text:
#region

using System.Security.Cryptography.X509Certificates;

#endregion

namespace Kombit.Samples.STSTestSigningService.Code
{
    /// <summary>
    ///     An interface to specify all attributes, methods used in token signing service
    /// </summary>
    public interface ITokenSigningService
    {
        string UpdateToken(string encodedRstr, X509Certificate2 certificate);
    }
}


text:
package fi.vincit.babyschedule.utils;

import java.io.Serializable;
import java.util.Date;

import android.content.Context;
import android.content.res.Resources;
import fi.vincit.babyschedule.MainTabWidget.StaticContext;
import fi.vincit.babyschedule.R;

public class BabyEvent implements Comparable<BabyEvent>
								   ,Serializable {
	/**
	 *
	 */
	private static final long serialVersionUID = 7385675124548040589L;
	private String actionName;
	private Date actionDate;
	private int durationInSeconds = 0;
	private int freeValue = 0;

	public BabyEvent(String name, Date actionDate) {
		this.actionName = name;
		this.actionDate = actionDate;
	}

	public BabyEvent(String name, Date actionDate, int duration, int freeValue) {
		this.actionName = name;
		this.actionDate = actionDate;
		this.durationInSeconds = duration;
		this.freeValue = freeValue;
	}

	public void setActionName(String activityName) {
		this.actionName = activityName;
	}

	/**
	 *
	 * @return the date as dd.mm.yyyy
	 */
	public String getDateString() {
	    return getActionDate().getDate() + "." + (getActionDate().getMonth()+1) + "." + (getActionDate().getYear()+1900);
	}

	/**
	 *
	 * @return returns time as hh.mm
	 */
	public String getTimeString() {
	    int hours = getActionDate().getHours();
	    String hoursStr = hours + "";
	    if( hours < 10) {
	        hoursStr = "0" + hoursStr;
	    }
	    int minutes = getActionDate().getMinutes();
        String minutesStr = minutes + "";
        if( minutes < 10) {
            minutesStr = "0" + minutesStr;
        }
	    return hoursStr + "." + minutesStr;
	}

	public String getActionName() {
		return actionName;
	}

	public Date getActionDate() {
		return actionDate;
	}

	public int getDurationInSeconds() {
		return durationInSeconds;
	}

	public int getFreeValue() {
		return freeValue;
	}

	public void setFreeValue(int freeValue) {
		this.freeValue = freeValue;
	}

	@Override
	public int compareTo(BabyEvent another) {
		if( getActionDate().equals(another.getActionDate())) {
			return 0;
		} else if( getActionDate().after(another.getActionDate())) {
			return 1;
		} else {
			return -1;
		}
	}

	public static int getActivityIconId(String activityName) {
		Context context = StaticContext.ctx;
		Resources res = context.getResources();
		if( activityName.equalsIgnoreCase(res.getString(R.string.eat_activity)) ) {
			return R.drawable.eat_icon;
		}
		else if( activityName.equalsIgnoreCase(res.getString(R.string.bath_activity)) ) {
			return R.drawable.bath_icon;
		}
		else if( activityName.equalsIgnoreCase(res.getString(R.string.milk_activity)) ) {
			return R.drawable.milk_icon;
		}
		else if( activityName.equalsIgnoreCase(res.getString(R.string.nursing)) ||
				 activityName.equalsIgnoreCase(res.getString(R.string.nurse_left_activity)) ||
				 activityName.equalsIgnoreCase(res.getString(R.string.nurse_right_activity))) {
			return R.drawable.nurse_icon;
		}
		else if( activityName.equalsIgnoreCase(res.getString(R.string.changed_diaper_activity)) ) {
			return R.drawable.icon_diaper;
		}
		else if( activityName.equalsIgnoreCase(res.getString(R.string.made_poop_activity)) ) {
			return R.drawable.potty_icon;
		}
		else if( activityName.equalsIgnoreCase(res.getString(R.string.go_to_nap_activity)) ||
				 activityName.equalsIgnoreCase(res.getString(R.string.go_to_sleep_activity)) ||
				 activityName.equalsIgnoreCase(res.getString(R.string.woke_up_activity)) ||
				 activityName.equalsIgnoreCase(res.getString(R.string.woke_up_during_night_activity))) {
			return R.drawable.sleep_icon;
		}
		else {
			return R.drawable.icon_empty;
		}
	}
}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>Working with students</title>

        Using the REST API at 'localhost:3000/students' create a web application for managing students

        The REST API provides methods as follows:

        POST creates a new student

        GET returns all students

        DELETE deletes a student by Id

        You may extend the demo for jQuery.ajax()

    Name:
    <input id="tb-name" name="tb-name" type="text" />

    Grade:
    <input id="tb-grade" name="tb-grade" type="number" min='1' max='12' />

    Id to delete:
    <input id="tb-id" name="tb-id" type="number" min='1' />

    <button id='btn-add-student'>Add new</button>
    <button id="btn-delete-student">Delete student by id</button>

This web page should be run on a server (localhost or in WWW).


text:
=pod

=head1 NAME

Bio::EnsEMBL::Compara::Production::GenomicAlignBlock::ChunkAndGroupDna

=cut

=head1 SYNOPSIS

my $db       = Bio::EnsEMBL::Compara::DBAdaptor->new($locator);
my $runnable = Bio::EnsEMBL::Compara::Production::GenomicAlignBlock::ChunkAndGroupDna->new (
                                                    -db      => $db,
                                                    -input_id   => $input_id
                                                    -analysis   => $analysis );
$runnable->fetch_input(); #reads from DB
$runnable->run();
$runnable->write_output(); #writes to DB

=cut

=head1 DESCRIPTION

This object chunks the Dna from a genome_db and creates and stores the
chunks as DnaFragChunk objects into the compara database

=cut

=head1 CONTACT

Describe contact details here

=cut

=head1 APPENDIX

The rest of the documentation details each of the object methods.
Internal methods are usually preceded with a _

=cut

package Bio::EnsEMBL::Compara::Production::GenomicAlignBlock::ChunkAndGroupDna;

use strict;
use Time::HiRes qw(time gettimeofday tv_interval);
use Bio::EnsEMBL::Utils::Exception qw( throw warning verbose );

use Bio::EnsEMBL::DBLoader;

use Bio::EnsEMBL::Compara::Production::DBSQL::DBAdaptor;

use Bio::EnsEMBL::Compara::Production::DnaFragChunk;
use Bio::EnsEMBL::Compara::Production::DnaFragChunkSet;
use Bio::EnsEMBL::Compara::Production::DnaCollection;

use Bio::EnsEMBL::Hive::DBSQL::AnalysisJobAdaptor;

use Bio::EnsEMBL::Analysis::RunnableDB;
use Bio::EnsEMBL::Hive::Process;
use Bio::EnsEMBL::Hive::Utils 'stringify';  # import 'stringify()'

our @ISA = qw(Bio::EnsEMBL::Hive::Process Bio::EnsEMBL::Analysis::RunnableDB);

=head2 fetch_input

    Title   :   fetch_input
    Usage   :   $self->fetch_input
    Function:   prepares global variables and DB connections
    Returns :   none
    Args    :   none

=cut

sub fetch_input {
  my( $self) = @_;

  #
  # parameters which can be set either via
  # $self->parameters OR
  # $self->input_id
  #
  $self->{'genome_db_id'}             = 0;  # 'gdb'

  #set default store_seq to 0 so that the sequence table is NOT populated during
  #the chunking process. Have now added separate module StoreSequence to deal
  #with storing very fragmented genomes.
  $self->{'store_seq'}                = 0;
  $self->{'store_chunk'}              = 0;
  $self->{'overlap'}                  = 0;
  $self->{'chunk_size'}               = undef;
  $self->{'region'}                   = undef;
  $self->{'masking_analysis_data_id'} = 0;
  $self->{'masking_options'}          = undef;
  $self->{'group_set_size'}           = undef;
  $self->{'include_non_reference'}    = 0;     # eg haplotypes
  $self->{'include_duplicates'}       = 0;     # eg PAR region

  $self->{'analysis_job'}             = undef;
#  $self->{'create_analysis_prefix'}   = undef; # 'analysis', 'job'
  $self->{'collection_id'}            = undef;
  $self->{'collection_name'}          = undef;

  $self->get_params($self->parameters);
  $self->get_params($self->input_id);

  throw("No genome_db specified") unless defined($self->{'genome_db_id'});
  $self->print_params;

  #create a Compara::DBAdaptor which shares the same DBI handle
  #with the DBAdaptor that is based into this runnable
  $self->{'comparaDBA'} = Bio::EnsEMBL::Compara::Production::DBSQL::DBAdaptor->new(-DBCONN => $self->db->dbc);

  #get the Compara::GenomeDB object for the genome_db_id
  $self->{'genome_db'} = $self->{'comparaDBA'}->get_GenomeDBAdaptor->
                           fetch_by_dbID($self->{'genome_db_id'});
  throw("Can't fetch genome_db for id=".$self->{'genome_db_id'}) unless($self->{'genome_db'});

  #using genome_db_id, connect to external core database
  my $coreDBA = $self->{'genome_db'}->db_adaptor();
  throw("Can't connect to genome database for id=".$self->{'genome_db_id'}) unless($coreDBA);

  return 1;
}

sub run
{
  my $self = shift;

  # main routine which takes a genome_db_id (from input_id) and
  # access the ensembl_core database, useing the SliceAdaptor
  # it will load all slices, all genes, and all transscripts
  # and convert them into members to be stored into compara
  $self->create_chunks;

  return 1;
}

sub write_output
{
  my $self = shift;

  #Create a StoreSequence job for each DnaFragChunk or DnaFragChunkSet object
  #to parallelise the storing of sequences in the Sequence table. Only do this if
  #chunk_size is defined

  if (defined $self->{'chunk_size'}) {
      my $dna_objects = $self->{'dna_collection'}->get_all_dna_objects;
      foreach my $dna_object (@$dna_objects) {
            my $object_id_name = $dna_object->isa('Bio::EnsEMBL::Compara::Production::DnaFragChunkSet')
                ? 'chunkSetID'
                : 'chunkID';

                # Use branch1 to send data to StoreSequence:
            $self->dataflow_output_id( { $object_id_name => $dna_object->dbID }, 1 );
      }
  } else {
      #Do not produce any StoreSequence jobs
      $self->input_job->autoflow(0);
  }

  return 1;
}

######################################
#
# subroutines
#
#####################################

sub get_params {
  my $self         = shift;
  my $param_string = shift;

  return unless($param_string);
  print("parsing parameter string : ",$param_string,"\n");

  my $params = eval($param_string);
  return unless($params);

  foreach my $key (keys %$params) {
    print("  $key : ", $params->{$key}, "\n");
  }

  if($params->{'input_data_id'}) {
    my $input_id = $self->db->get_AnalysisDataAdaptor->fetch_by_dbID($params->{'input_data_id'});
    $self->get_params($input_id);
  }

  $self->{'store_seq'} = $params->{'store_seq'} if(defined($params->{'store_seq'}));
  $self->{'store_chunk'} = $params->{'store_chunk'} if(defined($params->{'store_chunk'}));
  $self->{'chunk_size'} = $params->{'chunk_size'} if(defined($params->{'chunk_size'}));
  $self->{'overlap'} = $params->{'overlap'} if(defined($params->{'overlap'}));

  $self->{'dump_loc'} = $params->{'dump_loc'} if(defined($params->{'dump_loc'}));

  $self->{'genome_db_id'} = $params->{'gdb'} if(defined($params->{'gdb'}));
  $self->{'genome_db_id'} = $params->{'genome_db_id'} if(defined($params->{'genome_db_id'}));

  $self->{'region'} = $params->{'region'} if(defined($params->{'region'}));

  $self->{'masking_options'} = $params->{'masking_options'}
    if(defined($params->{'masking_options'}));
  $self->{'masking_analysis_data_id'} = $params->{'masking_analysis_data_id'}
    if(defined($params->{'masking_analysis_data_id'}));

## there seems to have been a typo since the very beginning, and nobody noticed :)
#
#  $self->{'create_analysis_prefix'} = $params->{'analysis_template'}
#    if(defined($params->{'analysis_template'}));

  $self->{'analysis_job'} = $params->{'analysis_job'} if(defined($params->{'analysis_job'}));

  $self->{'group_set_size'} = $params->{'group_set_size'} if(defined($params->{'group_set_size'}));

  $self->{'collection_name'} = $params->{'collection_name'} if(defined($params->{'collection_name'}));
  $self->{'collection_id'} = $params->{'collection_id'} if(defined($params->{'collection_id'}));

  $self->{'include_non_reference'} = $params->{'include_non_reference'} if(defined($params->{'include_non_reference'}));
  $self->{'include_duplicates'} = $params->{'include_duplicates'} if(defined($params->{'include_duplicates'}));

  return;

}

sub print_params {
  my $self = shift;

  print(" params:\n");
  print("   genome_db_id             : ", $self->{'genome_db_id'},"\n");
  print("   region                   : ", $self->{'region'},"\n") if($self->{'region'});
  print("   store_seq                : ", $self->{'store_seq'},"\n");
  print("   store_chunk              : ", $self->{'store_chunk'},"\n");
  print("   chunk_size               : ", $self->{'chunk_size'},"\n");
  print("   overlap                  : ", $self->{'overlap'} ,"\n");
  print("   masking_analysis_data_id : ", $self->{'masking_analysis_data_id'} ,"\n");
  print("   masking_options          : ", $self->{'masking_options'} ,"\n") if($self->{'masking_options'});
  print("   include_non_reference    : ", $self->{'include_non_reference'} ,"\n");
  print("   include_duplicates       : ", $self->{'include_duplicates'} ,"\n");

}

sub create_chunks
{
  my $self      = shift;

  my $genome_db = $self->{'genome_db'};

  my $collectionDBA = $self->{'comparaDBA'}->get_DnaCollectionAdaptor;
  if ($self->{'collection_id'}) {
    $self->{'dna_collection'} = $collectionDBA->fetch_by_dbID($self->{'collection_id'});
  } else {
    $self->{'dna_collection'} = new Bio::EnsEMBL::Compara::Production::DnaCollection;
    $self->{'dna_collection'}->description($self->{'collection_name'});
    $self->{'dna_collection'}->dump_loc($self->{'dump_loc'}) if(defined($self->{'dump_loc'}));
    $collectionDBA->store($self->{'dna_collection'});
  }
  throw("couldn't get a DnaCollection for ChunkAndGroup analysis\n") unless($self->{'dna_collection'});

  $genome_db->db_adaptor->dbc->disconnect_when_inactive(0);
  my $SliceAdaptor = $genome_db->db_adaptor->get_SliceAdaptor;
  my $dnafragDBA = $self->{'comparaDBA'}->get_DnaFragAdaptor;

  my $chromosomes = [];
  if(defined $self->{'region'}) {
    #Support list of regions
    my @regions = split(/,/, $self->{'region'});

    foreach my $region (@regions) {
        my ($coord_system_name, $seq_region_name, $seq_region_start, $seq_region_end) = split(/:/,  $region);
        if (defined $seq_region_name && $seq_region_name ne "") {
            print("fetch by region coord:$coord_system_name seq_name:$seq_region_name\n");
            my $slice;
            if (defined $seq_region_start && defined $seq_region_end) {
                $slice = $SliceAdaptor->fetch_by_region($coord_system_name, $seq_region_name, $seq_region_start, $seq_region_end);
                push @{$chromosomes}, $slice;
            } else {
                if ($self->{'include_non_reference'}) {
                    $slice = $SliceAdaptor->fetch_by_region_unique($coord_system_name, $seq_region_name);
                    push @{$chromosomes}, @$slice;
                } else {
                    $slice = $SliceAdaptor->fetch_by_region($coord_system_name, $seq_region_name);
                    push @{$chromosomes}, $slice;
                }
            }
        } else {
            print("fetch by region coord:$coord_system_name\n");
            push @{$chromosomes}, $SliceAdaptor->fetch_all($coord_system_name);
        }
    }
  } else {
      #default for $include_non_reference = 0, $include_duplicates = 0
    $chromosomes = $SliceAdaptor->fetch_all('toplevel',undef, $self->{'include_non_reference'}, $self->{'include_duplicates'});
  }

  print("number of seq_regions ".scalar @{$chromosomes}."\n");

  $self->{'chunkset_counter'} = 1;
  $self->{'current_chunkset'} = new Bio::EnsEMBL::Compara::Production::DnaFragChunkSet;
  $self->{'current_chunkset'}->description(sprintf("collection_id:%d group:%d",
                                 $self->{'dna_collection'}->dbID,
                                 $self->{'chunkset_counter'}++));

  #Temporary fix to problem in core when masking haplotypes because the
  #assembly mapper is cached but shouldn't be
  #if including haplotypes
  my $asm;
  if ($self->{'include_non_reference'}) {
      my $asma = $genome_db->db_adaptor->get_AssemblyMapperAdaptor;
      my $csa = $genome_db->db_adaptor->get_CoordSystemAdaptor;
      my $cs1 = $csa->fetch_by_name("Chromosome",$genome_db->assembly);
      my $cs2 = $csa->fetch_by_name("Contig");
      $asm = $asma->fetch_by_CoordSystems($cs1,$cs2);
  }

  my $starttime = time();
  foreach my $chr (@{$chromosomes}) {
    #print "fetching dnafrag\n";
    if (defined $self->{'region'}) {
      unless(scalar @{$chr->get_all_Attributes('toplevel')}) {
        warn "No toplevel attributes, skipping this region";
      }
    }

    my ($dnafrag) = @{$dnafragDBA->fetch_all_by_GenomeDB_region(
                      $genome_db,
                      $chr->coord_system->name(), #$self->{'coordinate_system'},
                      $chr->seq_region_name)};

    #if($dnafrag) { print("  already stores as dbID ", $dnafrag->dbID, "\n"); }
    unless($dnafrag) {
      #
      # create dnafrag for this chromosome
      #
      #print "loading dnafrag for ".$chr->name."...\n";
      $dnafrag = new Bio::EnsEMBL::Compara::DnaFrag;
      $dnafrag->name($chr->seq_region_name); #ie just 22
      $dnafrag->genome_db($genome_db);
      $dnafrag->coord_system_name($chr->coord_system->name());

      #Need total length of dnafrag, not just end-start+1, otherwise the dnafrag_chunks are created
      #incorrectly because the chr->end becomes (end-start+1) but this could be less than chr->start
      #$dnafrag->length($chr->length);
      $dnafrag->length($chr->seq_region_length);
      $dnafragDBA->store_if_needed($dnafrag);
    }
    $self->create_dnafrag_chunks($dnafrag, $chr->start, $chr->end);
    #Temporary fix to problem in core when masking haplotypes because the
    #assembly mapper is cached but shouldn't be
    if (defined $asm) {
	$asm->flush;
    }
  }

  #save the current_chunkset if it isn't empty
  if($self->{'current_chunkset'}->count > 0) {
    $self->{'comparaDBA'}->get_DnaFragChunkSetAdaptor->store($self->{'current_chunkset'});
    #$self->submit_job($self->{'current_chunkset'});
    $self->{'dna_collection'}->add_dna_object($self->{'current_chunkset'});
  } else {
    warn "current_chunkset->count is zero => not adding it to the collection";
  }

  #
  # finish by storing all the dna_objects of the collection
  #
  $collectionDBA->store($self->{'dna_collection'});

  print "genome_db ",$genome_db->dbID, " : total time ", (time()-$starttime), " secs\n";

}

sub create_dnafrag_chunks {
  my $self = shift;
  my $dnafrag = shift;
  my $region_start = (shift or 1);
  my $region_end = (shift or $dnafrag->length);

 #return if($dnafrag->display_id =~ /random/);

  my $dnafragDBA = $self->{'comparaDBA'}->get_DnaFragAdaptor;

  #If chunk_size is not set then set it to be the fragment length
  #overlap must be 0 in this case.
  my $chunk_size = $self->{'chunk_size'};
  my $overlap = $self->{'overlap'};
  if (!defined $chunk_size) {
      $chunk_size = $region_end;
      $overlap = 0;
  }

  #print "dnafrag : ", $dnafrag->display_id, "n";
  #print "  sequence length : ",$length,"\n";
  #print "chunk_size $chunk_size\n";

  my $lasttime = time();

  #initialise chunk_start and chunk_end to be the dnafrag start and end
  my $chunk_start = $region_start;
  my $chunk_end = $region_start;

  while ($chunk_end < $region_end) {

    my $chunk = new Bio::EnsEMBL::Compara::Production::DnaFragChunk();
    $chunk->dnafrag($dnafrag);
    $chunk->seq_start($chunk_start);

    $chunk_end = $chunk_start + $chunk_size - 1;

    #if current $chunk_end is too long, trim to be $region_end
    if ($chunk_end > $region_end) {
	$chunk_end = $region_end;
    }
    $chunk->seq_end($chunk_end);

    $chunk->masking_analysis_data_id($self->{'masking_analysis_data_id'});
    if($self->{'masking_options'}) {
      $chunk->masking_options($self->{'masking_options'});
    }

    #Store the sequence at this point, rather than in the blastz analysis
    #only try to store the sequence if its length is less than that
    #allowed by myslwd max_allowed_packet=12M
    if($self->{'store_seq'} &&
       ($chunk->seq_end - $chunk->seq_start + 1) <= 11500000) {

	#Set the masking_options variable for the masking_analysis_data_id
	if (!$self->{'_masking_options'} && $chunk->masking_analysis_data_id) {
	    $chunk->masking_options($self->{'comparaDBA'}->get_DnaFragChunkAdaptor->_fetch_MaskingOptions_by_dbID($chunk->masking_analysis_data_id));
	}

	$chunk->bioseq; #fetches sequence and stores internally in ->sequence variable
    }

    #print "store chunk " . $chunk->dnafrag->name . " " . $chunk->seq_start . " " . $chunk->seq_end . " " . length($chunk->bioseq->seq) . "\n";

    $self->{'comparaDBA'}->get_DnaFragChunkAdaptor->store($chunk);

    # do grouping if requested but do not group MT chr
    if($self->{'group_set_size'} and ($chunk->length < $self->{'group_set_size'}) and $chunk->dnafrag->name ne "MT") {
      if(($self->{'current_chunkset'}->count > 0) and
         (($self->{'current_chunkset'}->total_basepairs + $chunk->length) > $self->{'group_set_size'}))
      {
        #set has hit max, so save it
        $self->{'comparaDBA'}->get_DnaFragChunkSetAdaptor->store($self->{'current_chunkset'});
        $self->{'dna_collection'}->add_dna_object($self->{'current_chunkset'});
        #$self->submit_job($self->{'current_chunkset'});
        if($self->debug) {
          printf("created chunkSet(%d) %d chunks, %1.3f mbase\n",
                 $self->{'current_chunkset'}->dbID, $self->{'current_chunkset'}->count,
                 $self->{'current_chunkset'}->total_basepairs/1000000.0);
        }
        $self->{'current_chunkset'} = new Bio::EnsEMBL::Compara::Production::DnaFragChunkSet;
        $self->{'current_chunkset'}->description(sprintf("collection_id:%d group:%d",
                                       $self->{'dna_collection'}->dbID,
                                       $self->{'chunkset_counter'}++));
      }

      $self->{'current_chunkset'}->add_DnaFragChunk($chunk);
      if($self->debug) {
        printf("chunkSet %d chunks, %1.3f mbase\n",
               $self->{'current_chunkset'}->count,
               $self->{'current_chunkset'}->total_basepairs/1000000.0);
      }
  }
    else {
      #not doing grouping so put the $chunk directly into the collection
      $self->{'dna_collection'}->add_dna_object($chunk);
      if($self->debug) {
        printf("dna_collection : chunk (%d) %s\n",$chunk->dbID, $chunk->display_id);
      }
    }

    $self->submit_job($chunk) if($self->{'analysis_job'});
#    $self->create_chunk_analysis($chunk) if($self->{'create_analysis_prefix'});

    #This is very important, otherwise it leaks
    undef($chunk->{'_sequence'});

    #These 2 don't seem to have any effect
    #undef($chunk->{'_slice'});
    #undef($chunk);
    $chunk_start = $chunk_end - $overlap + 1;
  }

  #print "Done\n";
  #print scalar(time()-$lasttime), " secs to chunk, and store\n";
}

sub submit_job {
  my $self  = shift;
  my $chunk = shift;

  unless($self->{'submit_analysis'}) {
    #print("\ncreate Submit Analysis\n");
    my $gdb = $chunk->dnafrag->genome_db;
    my $logic_name = $self->{'analysis_job'} ."_". $gdb->dbID ."_". $gdb->assembly;

    #print("  see if analysis '$logic_name' is in database\n");
    my $analysis =  $self->{'comparaDBA'}->get_AnalysisAdaptor->fetch_by_logic_name($logic_name);
    #if($analysis) { print("  YES in database with analysis_id=".$analysis->dbID()); }

    unless($analysis) {
      #print("  NOPE: go ahead and insert\n");
      $analysis = Bio::EnsEMBL::Analysis->new(
          -db              => '',
          -db_file         => '',
          -db_version      => '1',
          -parameters      => "",
          -logic_name      => $logic_name,
          -module          => 'Bio::EnsEMBL::Hive::RunnableDB::Dummy',
        );
      $self->db->get_AnalysisAdaptor()->store($analysis);

      my $stats = $analysis->stats;
      $stats->batch_size(3);
      $stats->hive_capacity(11);
      $stats->status('BLOCKED');
      $stats->update();
    }
    $self->{'submit_analysis'} = $analysis;
  }

  my $input_id = "{'qyChunk'=>" . $chunk->dbID . "}";
  Bio::EnsEMBL::Hive::DBSQL::AnalysisJobAdaptor->CreateNewJob (
        -input_id       => $input_id,
        -analysis       => $self->{'submit_analysis'},
        -input_job_id   => $self->input_job->dbID,
        );

  return;
}

# this subroutine is never called and can probably be deleted:

sub create_chunk_analysis {
  #routine to create one analysis per chunk
  my $self  = shift;
  my $chunk = shift;

  my $analysisDBA = $self->db->get_AnalysisAdaptor();
  my $gdb = $chunk->dnafrag->genome_db;
  my $logic_name = $self->{'create_analysis_prefix'}
                  ."_". $gdb->dbID
                  ."_". $gdb->assembly
                  ."_". $chunk->dbID;

  #print("look for analysis ", $self->{'create_analysis_prefix'}, "\n");
  my $analysis = $analysisDBA->fetch_by_logic_name($self->{'create_analysis_prefix'});
  unless($analysis) {
    $analysis = Bio::EnsEMBL::Analysis->new(
      -db              => '',
      -db_file         => '',
      -db_version      => '1',
      -logic_name      => $logic_name,
      -program         => 'blastz',
      -module          => 'Bio::EnsEMBL::Compara::Production::GenomicAlignBlock::BlastZ',
    );
  }
  return unless($analysis);

  my $template_analysis_stats = $analysis->stats;

  $analysis->adaptor(0);
  $analysis->dbID(0);
  $analysis->logic_name($logic_name);
  #print("new logic_name : ", $analysis->logic_name, "\n");

  my $param_hash = {};
  if($analysis->parameters and ($analysis->parameters =~ /^{/)) {
    #print("parsing parameters : ", $analysis->parameters, "\n");
    $param_hash = eval($analysis->parameters);
  }
  $param_hash->{'dbChunk'} = $chunk->dbID;
  $analysis->parameters(stringify($param_hash));
  #print("new parameters : ", $analysis->parameters, "\n");
  $analysisDBA->store($analysis);

  my $stats = $analysis->stats;
  $stats->batch_size($template_analysis_stats->batch_size);
  $stats->hive_capacity($template_analysis_stats->hive_capacity);
  $stats->update();

  return;
}

1;


text:
whereyoat
=========

Yo service for checking in with friends and family. Location-based.

——————————————————
PURPOSE
——————————————————

YoCheckIn enables the seamless sharing of your location with several people via SMS by sending a yo. Subscribe to
YoCheckIn by sending a yo to YOCHECKIN, add up to 5 valid cellphone numbers with whom you want to share your location,
and then share your location with these numbers at any given time by simply sending a yo. You can update the numbers
with whom you would like to share your location at any given time by going to www.yocheckin.appspot.com.

Applications include kids sharing their location with their parents or guardians, friends meeting up or trying to
invite each other to events that are quickly changing location, and infinitely more exist.
It extends the ability to yo people who do not have the app. The power and extensibility all reside
in its simplicity.

—————————————————
DEVELOPING
—————————————————

Developed using the Yo API, Twilio API, and the Google Geocoding API
Created using appengine by Hannah Zhang, Edward Dugan, Alexandra Paul, and Laura Shea @YHACKS 2014


text:
all:	ospac

ospac:	src/*cpp src/*h
	cd Release;make all;cd ..

ospac-ffmpeg:	src/*cpp src/*h
	cd Release-ffmpeg;make all;cd ..

gui:	ospac-gui

ospac-gui:	src/*cpp src/*h
	cd GUI-Release;make all;cd ..

ospac-gui-linux:	src/*cpp src/*h
	cd GUI-Release;make ospac-gui-linux;cd ..

GUI-Release/ospac-gui:	src/*cpp src/*h
	cd GUI-Release;make all;cd ..

GUI-Release/ospac-gui-linux:	src/*cpp src/*h
	cd GUI-Release;make ospac-gui-linux;cd ..

Release/ospac:	src/*cpp src/*h
	cd Release;make all;cd ..

tab-completion: create_tab_completion.py
	python3 create_tab_completion.py zsh zsh_completion.sh
	python3 create_tab_completion.py bash bash_completion.sh

test:	Release/ospac
	cd test;make all;cd ..

install-ospac:	Release/ospac
	cd Release;make install;cd ..

install-ospac-ffmpeg:	Release-ffmpeg/ospac
	cd Release-ffmpeg;make install;cd ..

install-gui:	GUI-Release/ospac-gui
	cd GUI-Release;make install-gui;cd ..

install: install-ospac

uninstall:
	cd Release;make uninstall; cd ..
	cd Release-ffmpeg;make uninstall; cd ..
	cd GUI-Release;make uninstall; cd ..

uninstall-gui:
	cd Release;make uninstall; cd ..
	cd Release-ffmpeg;make uninstall; cd ..
	cd GUI-Release;make uninstall; cd ..

clean:
	cd Release;make clean; cd ..
	cd Release-ffmpeg;make clean; cd ..
	cd GUI-Release;make clean; cd ..
	cd test;make clean;cd ..
	rm -f *~
	rm -f src/*~
	rm zsh_completion.sh bash_completion.sh