text:
var gulp = require('gulp');
var less = require('gulp-less');
var minifyCss = require('gulp-minify-css');
var concat = require('gulp-concat');
var liveReload = require('gulp-livereload');
var inject = require('gulp-inject');
var jshint = require('gulp-jshint');
var uglify = require('gulp-uglify');
var series = require('stream-series');
var templateCache = require('gulp-angular-templatecache');
var ngAnnotate = require('gulp-ng-annotate');
var ngFilesort = require('gulp-angular-filesort');
var debug = require('gulp-debug');
var minimist = require('minimist');
var del = require('del');
var babel = require("gulp-babel");
var sourcemaps = require('gulp-sourcemaps');

// Arguments

var knownOptions = {
    string: 'version',
    default: {version: 'snapshot'}
};

var options = minimist(process.argv.slice(2), knownOptions);

// Paths

var web = 'src';
var webPath = './' + web;
var assetResources = webPath + '/assets/**';
var extensionAssetResources = [webPath + '/extension/**/*.png'];

var graphiqlJsResources = webPath + '/graphiql/*.js';
var graphiqlCssResources = webPath + '/graphiql/*.css';
var graphiqlIndexResource = webPath + '/graphiql.html';

var lessResources = webPath + '/less/*.less';

var jsResources = webPath + '/app/**/*.js';

var templateResources = webPath + '/app/**/*.html';

var indexResource = webPath + '/index.html';
var vendor = './vendor';

var build = 'build/web';

var buildPath = build + '/dev';
var buildTemplates = buildPath + '/templates';
var buildConvertedJs = buildPath + '/converted';
var buildAngular = buildPath + '/angular';
var buildCss = buildPath + '/css';

var outputPath = build + '/prod';
var output = './' + outputPath;
var outputCss = './' + outputPath + '/css';
var outputJs = './' + outputPath + '/js';
var outputFonts = './' + outputPath + '/fonts';
var outputAssets = './' + outputPath + '/assets';
var outputExtensionAssets = './' + outputPath + '/extension/';
var outputGraphiql = './' + outputPath + '/graphiql/';

// Vendor resources

var vendorJsResources = [
    'jquery/dist/jquery.js',
    'jquery-ui/jquery-ui.js',
    'angular/angular.js',
    'angular-ui-router/release/angular-ui-router.js',
    'angular-ui-sortable/sortable.js',
    'angular-multi-select/angular-multi-select.js',
    'angular-taglist/js/angular-taglist-directive.js',
    'angular-sanitize/angular-sanitize.js',
    'angular-bootstrap/ui-bootstrap-tpls.js',
    'moment/min/moment.min.js',
    'oclazyload/dist/ocLazyLoad.min.js',
    'unibabel/index.js'
].map(function (rel) {
    return vendor + '/' + rel;
});

var vendorCssResources = [
    'angular-multi-select/angular-multi-select.css',
    'angular-taglist/css/angular-taglist-directive.css'
].map(function (rel) {
    return vendor + '/' + rel;
});

var graphiqlVendorJsResources = [
    'fetch/fetch.js',
    'react/react.min.js',
    'react/react-dom.min.js'
].map(function (rel) {
    return vendor + '/' + rel;
});

// Cleaning

gulp.task('clean', function () {
    return del([build]);
});

// Javascript handling

gulp.task('lint', function () {
    return gulp.src(jsResources)
        .pipe(debug({title: 'lint:'}))
        .pipe(jshint({esversion: 6}))
        .pipe(jshint.reporter('default'))
        .pipe(jshint.reporter('fail'))
        .pipe(liveReload());
});

gulp.task('templates', function () {
    return gulp.src(templateResources)
        .pipe(debug({title: 'templates:'}))
        .pipe(templateCache({module: 'ontrack', root: 'app/'}))
        .pipe(gulp.dest(buildTemplates))
        .pipe(liveReload());
});

/**
 * Converted files
 */

gulp.task('js:conversion', ['lint'], function () {
    return gulp.src(jsResources)
        .pipe(debug({title: 'js:conversion:input'}))
        .pipe(babel())
        .pipe(gulp.dest(buildConvertedJs))
        .pipe(debug({title: 'js:conversion:output'}));
});

/**
 * Sorted and annotated Angular files
 */
gulp.task('js:angular', ['lint', 'js:conversion', 'templates'], function () {
    return gulp.src([buildTemplates + '/*.js', buildConvertedJs + '/**/*.js'])
        .pipe(debug({title: 'js:angular:input'}))
        .pipe(ngAnnotate())
        .pipe(ngFilesort())
        .pipe(sourcemaps.init())
        .pipe(concat('ci-angular.js'))
        .pipe(sourcemaps.write("."))
        .pipe(gulp.dest(buildAngular))
        .pipe(debug({title: 'js:angular:output'}));
});

gulp.task('js:concat', ['js:angular'], function () {
    var jsSource = vendorJsResources;
    jsSource.push(buildAngular + '/*.js');
    return gulp.src(jsSource)
        .pipe(debug({title: 'js:concat:input'}))
        .pipe(concat('ci-' + options.version + '.js'))
        .pipe(uglify())
        .pipe(gulp.dest(outputJs))
        .pipe(debug({title: 'js:concat:output'}))
        ;
});

// Translating Less into Minified CSS

gulp.task('less', function () {
    return gulp.src(lessResources)
        .pipe(debug({title: 'less:input:'}))
        .pipe(less())
        .pipe(debug({title: 'less:output:'}))
        .pipe(concat('ci-' + options.version + '.css'))
        .pipe(gulp.dest(buildCss))
        .pipe(liveReload());
});

// Concatenation of all CSS files, including the one generated from less

gulp.task('css:concat', function () {
    return series(
        gulp.src(lessResources)
            .pipe(debug({title: 'less:input:'}))
            .pipe(less())
            .pipe(debug({title: 'less:output:'})),
        gulp.src(vendorCssResources)
    )
        .pipe(debug({title: 'css:concat:input'}))
        .pipe(minifyCss())
        .pipe(concat('ci-' + options.version + '.css'))
        .pipe(debug({title: 'css:concat:output'}))
        .pipe(gulp.dest(outputCss));
});

// Fonts

gulp.task('fonts', function () {
    return gulp
        .src([
            vendor + '/font-awesome/fonts/*.*',
            vendor + '/bootstrap/fonts/*.*'
        ])
        .pipe(debug({title: 'fonts:input'}))
        .pipe(gulp.dest(outputFonts));
});

// Copy of assets

gulp.task('assets', function () {
    return gulp
        .src(assetResources)
        .pipe(debug({title: 'assets:input'}))
        .pipe(gulp.dest(outputAssets));
});

gulp.task('extensionAssets', function () {
    return gulp
        .src(extensionAssetResources)
        .pipe(debug({title: 'assets:input:extensions'}))
        .pipe(gulp.dest(outputExtensionAssets));
});

// Injection in index.html

gulp.task('index:dev', ['less', 'fonts', 'js:conversion', 'templates'], function () {
    var cssSources = gulp.src([buildCss + '/*.css'], {read: false});
    var vendorJsSources = gulp.src(vendorJsResources, {read: false});
    var vendorCssSources = gulp.src(vendorCssResources, {read: false});
    var appSources = gulp.src([buildTemplates + '/*.js', buildConvertedJs + '/**/*.js']).pipe(ngFilesort());

    return gulp.src(indexResource)
        .pipe(debug({title: 'index:dev:input'}))
        .pipe(inject(
            series(
                cssSources,
                vendorJsSources,
                vendorCssSources,
                appSources
            ),
            {relative: false, ignorePath: [outputPath, web, buildPath], addRootSlash: false}))
        .pipe(gulp.dest(buildPath))
        .pipe(debug({title: 'index:dev:output'}))
        .pipe(liveReload());
});

gulp.task('index:prod', ['css:concat', 'assets', 'fonts', 'templates', 'js:concat'], function () {
    var cssSources = gulp.src([outputCss + '/*.css'], {read: false});
    var jsSources = gulp.src(outputJs + '/*.js', {read: false});

    return gulp.src(indexResource)
        .pipe(debug({title: 'index:prod:input'}))
        .pipe(inject(
            series(
                cssSources,
                jsSources
            ),
            {relative: false, ignorePath: [outputPath, web, buildPath], addRootSlash: false}))
        .pipe(gulp.dest(output))
        .pipe(debug({title: 'index:prod:output'}));
});

// Injection in graphiql.html

gulp.task('graphiql:dev', [], function () {
    var cssSources = gulp.src([graphiqlCssResources], {read: false});

    var jsSources = graphiqlVendorJsResources;
    jsSources.push(graphiqlJsResources);

    return gulp.src(graphiqlIndexResource)
        .pipe(debug({title: 'graphiql:dev:input'}))
        .pipe(inject(
            series(
                cssSources,
                gulp.src(jsSources, {read: false})
            ),
            {relative: false, ignorePath: [outputPath, web, buildPath], addRootSlash: false}))
        .pipe(gulp.dest(buildPath))
        .pipe(debug({title: 'graphiql:dev:output'}))
        .pipe(liveReload());
});

gulp.task('graphiql:prod:css', [], function () {
    return gulp
        .src(graphiqlCssResources)
        .pipe(debug({title: 'graphiql:prod:css:input'}))
        .pipe(concat('ci-graphiql-' + options.version + '.css'))
        .pipe(gulp.dest(outputGraphiql));
});

gulp.task('graphiql:prod:js', [], function () {
    var jsSources = graphiqlVendorJsResources;
    jsSources.push(graphiqlJsResources);
    return gulp.src(jsSources)
        .pipe(debug({title: 'graphiql:prod:js:input'}))
        .pipe(concat('ci-graphiql-' + options.version + '.js'))
        .pipe(gulp.dest(outputGraphiql))
        .pipe(debug({title: 'graphiql:prod:js:output'}))
        ;
});

gulp.task('graphiql:prod:index', ['graphiql:prod:css', 'graphiql:prod:js'], function () {
    var cssSources = gulp.src([outputGraphiql + '/*.css'], {read: false});
    var jsSources = gulp.src([outputGraphiql + '/*.js'], {read: false});
    return gulp.src(graphiqlIndexResource)
        .pipe(debug({title: 'graphiql:prod:input'}))
        .pipe(inject(
            series(
                cssSources,
                jsSources
            ),
            {relative: false, ignorePath: [outputPath, web, buildPath], addRootSlash: false}))
        .pipe(gulp.dest(output))
        .pipe(debug({title: 'graphiql:prod:output'}));
});

// Default build

gulp.task('dev', ['index:dev', 'graphiql:dev', 'fonts']);

gulp.task('default', ['index:prod', 'graphiql:prod:index', 'assets', 'extensionAssets', 'fonts']);

// Watch setup

gulp.task('watch', function () {
    liveReload.listen();
    gulp.watch(lessResources, ['less']);
    gulp.watch(indexResource, ['index:dev']);
    gulp.watch(jsResources, ['index:dev']);
    gulp.watch(templateResources, ['templates']);
});


text:
static i: String = 10;
//~^ ERROR mismatched types
//~| expected `collections::string::String`
//~| found `_`
//~| expected struct `collections::string::String`
//~| found integral variable
fn main() { println!("{}", i); }

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
    PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">

  <title>QSqlDatabase Class Reference</title>
  <link href="classic.css" rel="stylesheet" type="text/css" />

QSqlDatabase Class Reference

[com.trolltech.qt.sql package]

Constructor

void QSqlDatabase()

void QSqlDatabase(QSqlDatabase other)

Constructor Properties

prototype: The QSqlDatabase prototype object

QSqlDatabase addDatabase(QSqlDriver driver, String connectionName)

QSqlDatabase cloneDatabase(QSqlDatabase other, String connectionName)

List connectionNames()

bool contains(String connectionName)

QSqlDatabase database(String connectionName, bool open)

List drivers()

bool isDriverAvailable(String name)

void registerSqlDriver(String name, QSqlDriverCreatorBase creator)

void removeDatabase(String connectionName)

Prototype Object Properties

void close()

bool commit()

String connectOptions()

String connectionName()

String databaseName()

QSqlDriver driver()

String driverName()

QSqlQuery exec(String query)

String hostName()

bool isOpen()

bool isOpenError()

bool isValid()

QSqlError lastError()

NumericalPrecisionPolicy numericalPrecisionPolicy()

bool open()

String password()

int port()

QSqlIndex primaryIndex(String tablename)

QSqlRecord record(String tablename)

bool rollback()

void setConnectOptions(String options)

void setDatabaseName(String name)

void setHostName(String host)

void setNumericalPrecisionPolicy(NumericalPrecisionPolicy precisionPolicy)

void setPassword(String password)

void setPort(int p)

void setUserName(String name)

List tables(TableType type)

bool transaction()

String userName()

Instance Properties

QSqlDatabase objects have no special properties beyond those inherited from the QSqlDatabase prototype object.


text:
using System;
using System.Collections.Generic;
using BlogML;
using BlogML.Xml;
using MbUnit.Framework;
using Moq;
using Subtext.Framework;
using Subtext.Framework.Components;
using Subtext.Framework.Providers;
using Subtext.Framework.Services;
using Subtext.Framework.Services.SearchEngine;
using Subtext.ImportExport;

namespace UnitTests.Subtext.BlogMl
{
    [TestFixture]
    public class BlogImportRepositoryTests
    {
        [Test]
        public void CreateCategories_WithBlogHavingCategories_CreatesCategories()
        {
            // arrange
            var context = new Mock<ISubtextContext>();
            context.Setup(c => c.Blog).Returns(new Blog { Id = 123 });
            bool categoryCreated = false;
            context.Setup(c => c.Repository.CreateLinkCategory(It.IsAny<LinkCategory>())).Callback(() => categoryCreated = true);
            var blog = new BlogMLBlog();
            blog.Categories.Add(new BlogMLCategory { Title = "Category Title", ID = "123" });
            var repository = new BlogImportRepository(context.Object, null, null, new BlogMLImportMapper());

            // act
            repository.CreateCategories(blog);

            // assert
            Assert.IsTrue(categoryCreated);
        }

        [Test]
        public void CreateCategories_WithBlogHavingNoCategories_DoesNotCreateCategories()
        {
            // arrange
            var context = new Mock<ISubtextContext>();
            context.Setup(c => c.Blog).Returns(new Blog { Id = 123 });
            context.Setup(c => c.Repository.CreateLinkCategory(It.IsAny<LinkCategory>())).Throws(new InvalidOperationException());
            var blog = new BlogMLBlog();
            var repository = new BlogImportRepository(context.Object, null, null, new BlogMLImportMapper());

            // act, assert
            repository.CreateCategories(blog);
        }

        [Test]
        public void CreateBlogPost_WithEntryPublisher_PublishesBlogPostAndReturnsId()
        {
            // arrange
            var context = new Mock<ISubtextContext>();
            context.Setup(c => c.Blog).Returns(new Blog());
            var entryPublisher = new Mock<IEntryPublisher>();
            entryPublisher.Setup(p => p.Publish(It.IsAny<Entry>())).Returns(310);
            var blog = new BlogMLBlog();
            var post = new BlogMLPost();
            var repository = new BlogImportRepository(context.Object, null, entryPublisher.Object, new BlogMLImportMapper());

            // act
            var id = repository.CreateBlogPost(blog, post);

            // assert
            Assert.AreEqual("310", id);
        }

        [Test]
        public void CreateBlogPost_WithEntryPublisher_RemovesKeywordExpander()
        {
            // arrange
            var context = new Mock<ISubtextContext>();
            context.Setup(c => c.Blog).Returns(new Blog());
            context.Setup(c => c.Repository.Create(It.IsAny<Entry>(), It.IsAny<IEnumerable<int>>()));
            var transformation = new CompositeTextTransformation();
            var searchengine = new Mock<IIndexingService>();
            var entryPublisher = new EntryPublisher(context.Object, transformation, null, searchengine.Object);
            var keywordExpander = new KeywordExpander((IEnumerable<KeyWord>)null);
            transformation.Add(keywordExpander);
            var blog = new BlogMLBlog() { Title = "MyBlog" };
            var post = new BlogMLPost();
            var repository = new BlogImportRepository(context.Object, null, entryPublisher, new BlogMLImportMapper());

            // act
            repository.CreateBlogPost(blog, post);

            // assert
            Assert.IsFalse(transformation.Contains(keywordExpander));
        }

        [Test]
        public void CreateComment_WithComment_CreatesCommentUsingCommentService()
        {
            // arrange
            var commentService = new Mock<ICommentService>();
            bool commentCreated = false;
            commentService.Setup(s => s.Create(It.IsAny<FeedbackItem>(), false/*runFilters*/)).Callback(() => commentCreated = true);

            var repository = new BlogImportRepository(null, commentService.Object, null, new BlogMLImportMapper());

            // act
            repository.CreateComment(new BlogMLComment(), "123");

            // assert
            Assert.IsTrue(commentCreated);
        }

        [Test]
        public void GetAttachmentDirectoryPath_WithAttachment_CreatesTrackbackUsingTrackbackService()
        {
            // arrange
            var commentService = new Mock<ICommentService>();
            bool trackbackCreated = false;
            commentService.Setup(s => s.Create(It.IsAny<FeedbackItem>(), It.IsAny<bool>())).Callback(() => trackbackCreated = true);

            var repository = new BlogImportRepository(null, commentService.Object, null, new BlogMLImportMapper());

            // act
            repository.CreateTrackback(new BlogMLTrackback(), "123");

            // assert
            Assert.IsTrue(trackbackCreated);
        }

        [Test]
        public void CreateTrackback_WithTrackback_CreatesTrackbackUsingTrackbackService()
        {
            // arrange
            var commentService = new Mock<ICommentService>();
            bool trackbackCreated = false;
            commentService.Setup(s => s.Create(It.IsAny<FeedbackItem>(), It.IsAny<bool>())).Callback(() => trackbackCreated = true);
            var repository = new BlogImportRepository(null, commentService.Object, null, new BlogMLImportMapper());

            // act
            repository.CreateTrackback(new BlogMLTrackback(), "123");

            // assert
            Assert.IsTrue(trackbackCreated);
        }

        [Test]
        public void GetAttachmentDirectoryPath_DelegatesToUrlHelperForPath()
        {
            // arrange
            var blog = new Blog();
            var context = new Mock<ISubtextContext>();
            context.Setup(c => c.Blog).Returns(blog);
            context.Setup(c => c.UrlHelper.ImageDirectoryPath(blog)).Returns(@"c:\web\images");
            var repository = new BlogImportRepository(context.Object, null, null, null);

            // act
            var path = repository.GetAttachmentDirectoryPath();

            // assert
            Assert.AreEqual(@"c:\web\images", path);
        }

        [Test]
        public void GetAttachmentDirectoryUrl_DelegatesToUrlHelperForUrl()
        {
            // arrange
            var blog = new Blog();
            var context = new Mock<ISubtextContext>();
            context.Setup(c => c.Blog).Returns(blog);
            context.Setup(c => c.UrlHelper.ImageDirectoryUrl(blog)).Returns("/test");
            var repository = new BlogImportRepository(context.Object, null, null, null);

            // act
            var path = repository.GetAttachmentDirectoryUrl();

            // assert
            Assert.AreEqual(@"/test", path);
        }

        [Test]
        public void SetupBlogForImport_ReturnsBlogMLScope()
        {
            // arrange
            var blog = new Blog();
            var repository = new Mock<ObjectRepository>();
            var context = new Mock<ISubtextContext>();
            context.Setup(c => c.Repository).Returns(repository.Object);
            context.Setup(c => c.Blog).Returns(blog);
            var importRepository = new BlogImportRepository(context.Object, null, null, null);

            // act
            var scope = importRepository.SetupBlogForImport() as BlogImportSetup;

            // assert
            Assert.IsNotNull(scope);
            Assert.AreEqual(blog, scope.Blog);
            Assert.AreEqual(repository.Object, scope.Repository);
        }

        [Test]
        public void SetExtendedProperties_WithKeyForCommentModeration_EnablesModeration()
        {
            // arrange
            var extendedProperties = new BlogMLBlog.ExtendedPropertiesCollection { new Pair<string, string>(BlogMLBlogExtendedProperties.CommentModeration, "true") };
            var context = new Mock<ISubtextContext>();
            var blog = new Blog { ModerationEnabled = false };
            context.Setup(c => c.Blog).Returns(blog);
            bool blogUpdated = false;
            context.Setup(c => c.Repository.UpdateBlog(blog)).Callback(() => blogUpdated = true);
            var repository = new BlogImportRepository(context.Object, null, null, null);

            // act
            repository.SetExtendedProperties(extendedProperties);

            // assert
            Assert.IsTrue(blogUpdated);
            Assert.IsTrue(blog.ModerationEnabled);
        }

        [Test]
        public void SetExtendedProperties_WithKeyForTrackbacksEnabled_EnablesTrackbacks()
        {
            // arrange
            var extendedProperties = new BlogMLBlog.ExtendedPropertiesCollection { new Pair<string, string>(BlogMLBlogExtendedProperties.EnableSendingTrackbacks, "true") };
            var context = new Mock<ISubtextContext>();
            var blog = new Blog { TrackbacksEnabled = false };
            context.Setup(c => c.Blog).Returns(blog);
            bool blogUpdated = false;
            context.Setup(c => c.Repository.UpdateBlog(blog)).Callback(() => blogUpdated = true);
            var repository = new BlogImportRepository(context.Object, null, null, null);

            // act
            repository.SetExtendedProperties(extendedProperties);

            // assert
            Assert.IsTrue(blogUpdated);
            Assert.IsTrue(blog.TrackbacksEnabled);
        }
    }
}


text:
import org.apache.commons.io.FileUtils
import sbt._
import Keys._

import scala.util.Properties

object Common {
  //  Parameters for publishing to artifact repositories
  val snapshot                  = Properties.envOrElse("IS_SNAPSHOT","true").toBoolean
  val repoPort                  = Properties.envOrElse("REPO_PORT","")
  val repoHost                  = Properties.envOrElse("REPO_HOST","")
  val repoUsername              = Properties.envOrElse("REPO_USERNAME","")
  val repoPassword              = Properties.envOrElse("REPO_PASSWORD","")
  val repoEndpoint              = Properties.envOrElse("REPO_ENDPOINT", if(snapshot) "/nexus/content/repositories/snapshots/" else "/nexus/content/repositories/releases/")
  val repoUrl                   = Properties.envOrElse("REPO_URL", s"http://${repoHost}:${repoPort}${repoEndpoint}")

  private val versionNumber     = "0.1.4.5-cassandra"
  private val buildOrganization = "com.ibm.spark"
  private val buildVersion      =
    if (snapshot) s"$versionNumber-SNAPSHOT"
    else versionNumber
  private val buildScalaVersion = "2.10.4"
  private val buildSbtVersion   = "0.13.7"

  // Global dependencies provided to all projects
  private val buildLibraryDependencies = Seq(
    // Needed to force consistent typesafe config with play json and spark
    "com.typesafe" % "config" % "1.2.1",
    "org.slf4j" % "slf4j-log4j12" % "1.7.5" % "test",
    "log4j" % "log4j" % "1.2.17" % "test",
    "org.scalatest" %% "scalatest" % "2.2.0" % "test", // Apache v2
    "org.scalactic" %% "scalactic" % "2.2.0" % "test", // Apache v2
    "org.mockito" % "mockito-all" % "1.9.5" % "test"   // MIT
  )

  lazy val sparkVersion = settingKey[String]("The Apache Spark version to use")

  // The prefix used for our custom artifact names
  private val artifactPrefix = "ibm-spark"

  val settings: Seq[Def.Setting[_]] = Seq(
    organization := buildOrganization,
    version := buildVersion,
    scalaVersion := buildScalaVersion,
    sbtVersion := buildSbtVersion,
    libraryDependencies ++= buildLibraryDependencies,
    isSnapshot := snapshot,
    sparkVersion := {
      val sparkEnvironmentVariable = "APACHE_SPARK_VERSION"
      val defaultSparkVersion = "1.4.1"

      val _sparkVersion = Properties.envOrNone(sparkEnvironmentVariable)

      if (_sparkVersion.isEmpty) {
        scala.Console.out.println(
          s"""
             |[INFO] Using default Apache Spark $defaultSparkVersion!
           """.stripMargin.trim.replace('\n', ' '))
        defaultSparkVersion
      } else {
        val version = _sparkVersion.get
        scala.Console.out.println(
          s"""
             |[INFO] Using Apache Spark $version provided from
             |$sparkEnvironmentVariable!
           """.stripMargin.trim.replace('\n', ' '))
        version
      }
    },

    scalacOptions in (Compile, doc) ++= Seq(
      // Ignore packages (for Scaladoc) not from our project
      "-skip-packages", Seq(
        "akka",
        "scala"
      ).mkString(":")
    ),

    // Scala-based options for compilation
    scalacOptions ++= Seq(
      "-deprecation", "-unchecked", "-feature",
      //"-Xlint", // Scala 2.11.x only
      "-Xfatal-warnings",
      "-Ywarn-all",
      "-language:reflectiveCalls"
    ),

    // Java-based options for compilation (all tasks)
    javacOptions in Compile ++= Seq(""),

    // Java-based options for just the compile task
    javacOptions in (Compile, compile) ++= Seq(
      "-Xlint:all",   // Enable all Java-based warnings
      "-Xlint:-path", // Suppress path warnings since we get tons of them
      "-Werror"       // Treat warnings as errors
    ),

    // Add additional test option to show time taken per test
    testOptions in Test += Tests.Argument("-oD"),

    // Add a global resource directory with compile/ and test/ for resources
    // in all projects
    unmanagedResourceDirectories in Compile +=
      (baseDirectory in Build.root).value / "resources/compile",
    unmanagedResourceDirectories in Test +=
      (baseDirectory in Build.root).value / "resources/test",

    publishTo := Some("Spark Kernel Nexus Repo" at repoUrl),

    credentials += Credentials("Sonatype Nexus Repository Manager", repoHost, repoUsername, repoPassword),

    // Change destination of local delivery (building ivy.xml) to have *-ivy.xml
    deliverLocalConfiguration := {
      val newDestinationPath = crossTarget.value / s"${name.value}-ivy.xml"
      val dlc = deliverLocalConfiguration.value
      new DeliverConfiguration(
        newDestinationPath.absolutePath, dlc.status,
        dlc.configurations, dlc.logging)
    },

    // Add rebuild ivy xml to the following tasks
    compile <<= (compile in Compile) dependsOn (rebuildIvyXml dependsOn deliverLocal)
  ) ++ rebuildIvyXmlSettings // Include our rebuild ivy xml settings

  // ==========================================================================
  // = REBUILD IVY XML SETTINGS BELOW
  // ==========================================================================

  lazy val rebuildIvyXml = TaskKey[Unit](
    "rebuild-ivy-xml",
    "Rebuilds the ivy xml using deliver-local and copies it to src " +
      "resource directories"
  )

  // TODO: Figure out how to retrieve the configuration being used to avoid
  //       this duplication
  lazy val rebuildIvyXmlSettings = Seq(
    rebuildIvyXml := {
      val s: TaskStreams = streams.value
      val inputFile = (crossTarget.value / s"${name.value}-ivy.xml").getAbsoluteFile
      val outputFile =
        ((resourceDirectory in Compile).value / s"${name.value}-ivy.xml").getAbsoluteFile
      s.log.info(s"Copying ${inputFile.getPath} to ${outputFile.getPath}")
      FileUtils.copyFile(inputFile, outputFile)
    }
  )
}


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/ads/googleads/v12/common/simulation.proto

package com.google.ads.googleads.v12.common;

public interface TargetRoasSimulationPointOrBuilder extends
    // @@protoc_insertion_point(interface_extends:google.ads.googleads.v12.common.TargetRoasSimulationPoint)
    com.google.protobuf.MessageOrBuilder {

  /**
   *

   * The simulated target ROAS upon which projected metrics are based.
   *

   *
   * optional double target_roas = 8;
   * @return Whether the targetRoas field is set.
   */
  boolean hasTargetRoas();
  /**
   *

   * The simulated target ROAS upon which projected metrics are based.
   *

   *
   * optional double target_roas = 8;
   * @return The targetRoas.
   */
  double getTargetRoas();

  /**
   *

   * Projected required daily budget that the advertiser must set in order to
   * receive the estimated traffic, in micros of advertiser currency.
   *

   *
   * int64 required_budget_amount_micros = 15;
   * @return The requiredBudgetAmountMicros.
   */
  long getRequiredBudgetAmountMicros();

  /**
   *

   * Projected number of biddable conversions.
   *

   *
   * optional double biddable_conversions = 9;
   * @return Whether the biddableConversions field is set.
   */
  boolean hasBiddableConversions();
  /**
   *

   * Projected number of biddable conversions.
   *

   *
   * optional double biddable_conversions = 9;
   * @return The biddableConversions.
   */
  double getBiddableConversions();

  /**
   *

   * Projected total value of biddable conversions.
   *

   *
   * optional double biddable_conversions_value = 10;
   * @return Whether the biddableConversionsValue field is set.
   */
  boolean hasBiddableConversionsValue();
  /**
   *

   * Projected total value of biddable conversions.
   *

   *
   * optional double biddable_conversions_value = 10;
   * @return The biddableConversionsValue.
   */
  double getBiddableConversionsValue();

  /**
   *

   * Projected number of clicks.
   *

   *
   * optional int64 clicks = 11;
   * @return Whether the clicks field is set.
   */
  boolean hasClicks();
  /**
   *

   * Projected number of clicks.
   *

   *
   * optional int64 clicks = 11;
   * @return The clicks.
   */
  long getClicks();

  /**
   *

   * Projected cost in micros.
   *

   *
   * optional int64 cost_micros = 12;
   * @return Whether the costMicros field is set.
   */
  boolean hasCostMicros();
  /**
   *

   * Projected cost in micros.
   *

   *
   * optional int64 cost_micros = 12;
   * @return The costMicros.
   */
  long getCostMicros();

  /**
   *

   * Projected number of impressions.
   *

   *
   * optional int64 impressions = 13;
   * @return Whether the impressions field is set.
   */
  boolean hasImpressions();
  /**
   *

   * Projected number of impressions.
   *

   *
   * optional int64 impressions = 13;
   * @return The impressions.
   */
  long getImpressions();

  /**
   *

   * Projected number of top slot impressions.
   * Only Search advertising channel type supports this field.
   *

   *
   * optional int64 top_slot_impressions = 14;
   * @return Whether the topSlotImpressions field is set.
   */
  boolean hasTopSlotImpressions();
  /**
   *

   * Projected number of top slot impressions.
   * Only Search advertising channel type supports this field.
   *

   *
   * optional int64 top_slot_impressions = 14;
   * @return The topSlotImpressions.
   */
  long getTopSlotImpressions();
}


text:
  <input type="text" ng-model="content.rssFeedUrl" ng-model-options="modelOptions" />

  <input type="text" ng-model="content.maxStories" />

  <input type="checkbox" ng-model="content.showTitle" />

  <input type="checkbox" ng-model="content.showDescription" />

  <input type="checkbox" ng-model="content.showStoryDescription" />

  <input type="checkbox" ng-model="content.showStoryDate" />


text:
'''
Created on Feb 2, 2011

@author: cgueret
'''
import re
import urllib2
from rdflib import ConjunctiveGraph, Literal, RDF, URIRef, BNode
from BeautifulSoup import BeautifulSoup
from datetime import date
from common import DCT, DBP, FOAF, EVENT, BIO, GOOGLE_ROOT, GART, DCMI, GARTW, get_dbpedia_resource

class Resource(object):
    def __init__(self):
        # Create the self.graph and the resource
        self.graph = ConjunctiveGraph()
        self.graph.bind('dct', DCT)
        self.graph.bind('dbprop', DBP)
        self.graph.bind('foaf', FOAF)
        self.graph.bind('event', EVENT)
        self.graph.bind('bio', BIO)
        self._load_data()

    def to_rdfxml(self):
        '''
        Returns an RDF/XML representation of the graph
        '''
        return self.graph.serialize()

    def _load_data(self):
        '''
        Load the data into the RDF document, to be defined by each resource
        '''
        pass

class Homepage(Resource):
    def _load_data(self):
        '''
        Returns an RDF representation of the list of museums
        '''
        document = BeautifulSoup(urllib2.urlopen(GOOGLE_ROOT).read())
        list_block = document.find(id='list')
        for entry in  list_block.findAll('li'):
            city = entry.find('a').find('span').getText()
            name = entry.get('data-bg-museum')
            url = entry.get('data-museum-url')
            this = GARTW['index.rdf']
            museum = GARTW[url[1:]]
            self.graph.add((this, DCT['relation'], museum))
            self.graph.add((museum, DCT['title'], Literal(name)))
            self.graph.add((museum, DCT['location'], get_dbpedia_resource(city)))

class Museum(Resource):
    def __init__(self, url):
        self.url = '/museums/'+url
        Resource.__init__(self)

    def _load_data(self):
        '''
        Returns an RDF representation of the list of museums
        '''
        document = BeautifulSoup(urllib2.urlopen(GOOGLE_ROOT + self.url).read())
        artwork_list = document.find(id='artworkList')
        for artwork in  artwork_list.findAll('a'):
            resource = GARTW[artwork.get('href')[1:]]
            this = GARTW[self.url]
            self.graph.add((this, DCT['relation'], resource))

class Painting(Resource):
    def __init__(self, url):
        self.url = '/museums/'+url
        Resource.__init__(self)

    def _load_data(self):
        '''
        Returns an RDF representation of a painting on google art
        '''
        # Load HTML page
        document = BeautifulSoup(urllib2.urlopen(GOOGLE_ROOT + self.url).read())
        info_block = document.find(id='info')

        # Create the resource
        this = GART[self.url]
        self.graph.add((this, RDF.type, DCMI['StillImage']))
        self.graph.add((this, RDF.type, DCMI['PhysicalResource']))

        # Get general information
        content = info_block.find(attrs={'class':'content'})
        self.graph.add((this, DCT['title'], Literal(content.find('h2').string)))
        self.graph.add((this, DCT['description'], Literal(content.find(attrs={'class':'altLang'}).string)))
        date_raw = content.find(attrs={'class':'year'}).string
        date_raw = re.search('([0-9]{4})', date_raw).group(0)
        self.graph.add((this, DCT['created'], Literal(date(int(date_raw), 1 , 1))))
        painter = get_dbpedia_resource(content.find('h3').string.split(',')[0])
        if painter == None:
            painter = BNode()
            self.graph.add((painter, RDF.type, DCT['Agent']))
            self.graph.add((painter, FOAF['name'], content.find('h3').string.split(',')[0]))
        self.graph.add((this, DCT['creator'], painter))
        about_raw = content.findAll('p')[2].getText()
        medium = get_dbpedia_resource(about_raw[:about_raw.index('Height')])
        if medium != None:
            self.graph.add((this, DCT['medium'], URIRef(medium)))
        self.graph.add((this, DBP['height'], Literal(about_raw[about_raw.index('Height') + len('Height : '):about_raw.index('Width')])))
        self.graph.add((this, DBP['width'], Literal(about_raw[about_raw.index('Width') + len('Width : '):])))

        # Get extra information
        content = info_block.find(attrs={'class':'exclusive'})
        for link in content.findAll(attrs={'class':'outside'}):
            self.graph.add((this, FOAF['page'], URIRef(link.get('href'))))
        for block in content.findAll('dt'):
            if block.string == 'Tags':
                for list in block.findNextSiblings('dd')[0].findAll('tr'):
                    for k in list.getText().split(','):
                        self.graph.add((this, DCT['subject'], Literal(k)))
            if block.attrMap.has_key('class') and block.get('class') == 'artworkListTrigger':
                for link in block.findNextSiblings('dd')[0].findAll('a'):
                    if link.attrMap['href'] != "#":
                        self.graph.add((this, DCT['relation'], GARTW[link.get('href')[1:]]))


text:
package org.auraframework.impl.css.style;

import com.google.common.collect.ImmutableList;
import com.salesforce.omakase.plugin.Plugin;
import org.auraframework.Aura;
import org.auraframework.adapter.StyleAdapter;
import org.auraframework.builder.BaseStyleDefBuilder;
import org.auraframework.css.ResolveStrategy;
import org.auraframework.css.StyleContext;
import org.auraframework.css.TokenValueProvider;
import org.auraframework.def.BaseStyleDef;
import org.auraframework.def.TokenDef;
import org.auraframework.expression.Expression;
import org.auraframework.expression.PropertyReference;
import org.auraframework.impl.DefinitionAccessImpl;
import org.auraframework.impl.css.parser.CssPreprocessor;
import org.auraframework.impl.expression.AuraExpressionBuilder;
import org.auraframework.impl.system.DefinitionImpl;
import org.auraframework.impl.util.AuraUtil;
import org.auraframework.service.DefinitionService;
import org.auraframework.system.AuraContext;
import org.auraframework.throwable.AuraRuntimeException;
import org.auraframework.throwable.quickfix.AuraValidationException;
import org.auraframework.throwable.quickfix.QuickFixException;
import org.auraframework.throwable.quickfix.StyleParserException;
import org.auraframework.validation.ReferenceValidationContext;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Base class for concrete {@link BaseStyleDef} implementations.
 */
public abstract class AbstractStyleDef<D extends BaseStyleDef> extends DefinitionImpl<D> implements BaseStyleDef {
    private static final long serialVersionUID = -7239904547091800250L;
    private static final String TOKEN_PROPERTY_VALIDATION_ERROR_MSG = "the '%s' token cannot be used with the %s property.\nAllowed properties: %s";

    private final String content;
    private final Set<String> expressions;
    private final Map<String, Set<String>> tokensInCssProperties;

    protected AbstractStyleDef(Builder<D> builder) {
        super(builder);
        this.content = builder.content;
        this.expressions = AuraUtil.immutableSet(builder.expressions);
        this.tokensInCssProperties = builder.tokensInCssProperties;
    }

    @Override
    public String getCode() {
        return getCode(ImmutableList.<Plugin>of());
    }

    @Override
    public String getCode(List<Plugin> plugins) {
        StyleContext styleContext = Aura.getContextService().getCurrentContext().getStyleContext();
        StyleAdapter styleAdapter = Aura.getStyleAdapter();
        TokenValueProvider tvp = styleAdapter.getTokenValueProvider(descriptor, ResolveStrategy.RESOLVE_NORMAL);

        try {
            return CssPreprocessor.runtime(styleContext, styleAdapter)
                    .source(content)
                    .resourceName(descriptor.getQualifiedName())
                    .tokens(descriptor, tvp)
                    .extras(plugins)
                    .parse()
                    .content();
        } catch (QuickFixException e) {
            throw new AuraRuntimeException(e);
        }
    }

    @Override
    public String getRawCode() {
        return content;
    }

    @Override
    public Set<String> getExpressions() {
        return expressions;
    }

    @Override
    public Set<String> getTokenNames() throws AuraValidationException {
        Set<String> set = new HashSet<>();

        if (!expressions.isEmpty()) {
            Set<PropertyReference> tmp = new HashSet<>();
            for (String rawExpression : expressions) {
                Expression expression = AuraExpressionBuilder.INSTANCE.buildExpression(rawExpression, null);
                expression.gatherPropertyReferences(tmp);
            }

            for (PropertyReference propRef : tmp) {
                set.add(propRef.getRoot());
            }
        }

        return set;
    }

    @Override
    public void validateReferences(ReferenceValidationContext validationContext) throws QuickFixException {
        super.validateReferences(validationContext);

        // validate tokens
        if (!expressions.isEmpty()) {
            StyleAdapter adapter = Aura.getStyleAdapter();
            TokenValueProvider vp = adapter.getTokenValueProvider(descriptor, ResolveStrategy.RESOLVE_DEFAULTS);
            DefinitionService definitionService = Aura.getDefinitionService();

            for (String reference : expressions) {
                // getValue will validate it's a valid expression/variable
                vp.getValue(reference, getLocation());

                // access checks FIXME this probably isn't the right location for this, and this check
                // can be bypassed via cross references, among other issues.
                for (List<TokenDef> tokenDefs : vp.extractTokenDefs(reference)) {
                    for (TokenDef tokenDef : tokenDefs) {
                        definitionService.assertAccess(descriptor, tokenDef);
                    }
                }
            }
        }

        if (tokensInCssProperties != null && !tokensInCssProperties.isEmpty()) {
            TokenValueProvider tvp = Aura.getStyleAdapter().getTokenValueProvider(descriptor, ResolveStrategy.PASSTHROUGH);
            for (String property : tokensInCssProperties.keySet()) {
                for (String tokens : tokensInCssProperties.get(property)) {
                    for (List<TokenDef> tokenDefs : tvp.extractTokenDefs(tokens)) {
                        for (TokenDef tokenDef : tokenDefs) {
                            Set<String> allowed = tokenDef.getAllowedProperties();
                            if (!allowed.isEmpty() && !allowed.contains(property)) {
                                throw new StyleParserException(String.format(TOKEN_PROPERTY_VALIDATION_ERROR_MSG, tokenDef.getName(), property, tokenDef.getAllowedPropertiesString()), tokenDef.getLocation());
                            }
                        }
                    }
                }
            }
        }
    }

    /** common builder for style defs */
    public static abstract class Builder<D extends BaseStyleDef> extends BuilderImpl<D> implements BaseStyleDefBuilder<D> {
        private String content;
        private Set<String> expressions;
        private Map<String, Set<String>> tokensInCssProperties;

        public Builder(Class<D> defClass) {
            super(defClass);
            setAccess(new DefinitionAccessImpl(AuraContext.Access.PUBLIC));
        }

        @Override
        public Builder<D> setContent(String content) {
            this.content = content;
            return this;
        }

        @Override
        public Builder<D> setTokenExpressions(Set<String> expressions) {
            this.expressions = expressions;
            return this;
        }

        @Override
        public Builder<D> setTokensInCssProperties(Map<String, Set<String>> tokensInCssProperties) {
            this.tokensInCssProperties = tokensInCssProperties;
            return this;
        }
    }
}


text:
package org.gradle.plugins.ide.internal.tooling.eclipse;

import com.google.common.collect.Lists;
import org.gradle.tooling.internal.gradle.DefaultGradleProject;
import org.gradle.tooling.internal.gradle.GradleProjectIdentity;

import java.io.File;
import java.io.Serializable;
import java.util.Collections;
import java.util.List;

/**
 * An implementation for {@link org.gradle.tooling.model.eclipse.EclipseProject}.
 */
public class DefaultEclipseProject implements Serializable, GradleProjectIdentity {
    private final String name;
    private final String path;
    private DefaultEclipseProject parent;
    private List<DefaultEclipseExternalDependency> classpath;
    private final List<DefaultEclipseProject> children;
    private List<DefaultEclipseSourceDirectory> sourceDirectories;
    private List<DefaultEclipseProjectDependency> projectDependencies;
    private final String description;
    private final File projectDirectory;
    private Iterable<? extends DefaultEclipseTask> tasks;
    private Iterable<? extends DefaultEclipseLinkedResource> linkedResources;
    private DefaultGradleProject gradleProject;
    private List<DefaultEclipseProjectNature> projectNatures;
    private List<DefaultEclipseBuildCommand> buildCommands;
    private DefaultEclipseJavaSourceSettings javaSourceSettings;

    public DefaultEclipseProject(String name, String path, String description, File projectDirectory, Iterable<? extends DefaultEclipseProject> children) {
        this.name = name;
        this.path = path;
        this.description = description;
        this.projectDirectory = projectDirectory;
        this.tasks = Collections.emptyList();
        this.children = Lists.newArrayList(children);
        this.classpath = Collections.emptyList();
        this.sourceDirectories = Collections.emptyList();
        this.projectDependencies = Collections.emptyList();
        this.projectNatures = Collections.emptyList();
        this.buildCommands = Collections.emptyList();
    }

    @Override
    public String toString() {
        return String.format("project '%s'", path);
    }

    public String getPath() {
        return path;
    }

    public String getName() {
        return name;
    }

    public String getDescription() {
        return description;
    }

    public DefaultEclipseProject getParent() {
        return parent;
    }

    public File getProjectDirectory() {
        return projectDirectory;
    }

    public void setParent(DefaultEclipseProject parent) {
        this.parent = parent;
    }

    public List<DefaultEclipseProject> getChildren() {
        return children;
    }

    public Iterable<? extends DefaultEclipseSourceDirectory> getSourceDirectories() {
        return sourceDirectories;
    }

    public void setSourceDirectories(List<DefaultEclipseSourceDirectory> sourceDirectories) {
        this.sourceDirectories = sourceDirectories;
    }

    public Iterable<? extends DefaultEclipseProjectDependency> getProjectDependencies() {
        return projectDependencies;
    }

    public void setProjectDependencies(List<DefaultEclipseProjectDependency> projectDependencies) {
        this.projectDependencies = projectDependencies;
    }

    public List<DefaultEclipseExternalDependency> getClasspath() {
        return classpath;
    }

    public void setClasspath(List<DefaultEclipseExternalDependency> classpath) {
        this.classpath = classpath;
    }

    public Iterable<? extends DefaultEclipseTask> getTasks() {
        return tasks;
    }

    public void setTasks(Iterable<? extends DefaultEclipseTask> tasks) {
        this.tasks = tasks;
    }

    public Iterable<? extends DefaultEclipseLinkedResource> getLinkedResources() {
        return linkedResources;
    }

    public void setLinkedResources(Iterable<? extends DefaultEclipseLinkedResource> linkedResources) {
        this.linkedResources = linkedResources;
    }

    public DefaultGradleProject<?> getGradleProject() {
        return gradleProject;
    }

    public DefaultEclipseProject setGradleProject(DefaultGradleProject gradleProject) {
        this.gradleProject = gradleProject;
        return this;
    }

    public List<DefaultEclipseProjectNature> getProjectNatures() {
        return projectNatures;
    }

    public void setProjectNatures(List<DefaultEclipseProjectNature> projectNatures) {
        this.projectNatures = projectNatures;
    }

    public List<DefaultEclipseBuildCommand> getBuildCommands() {
        return buildCommands;
    }

    public void setBuildCommands(List<DefaultEclipseBuildCommand> buildCommands) {
        this.buildCommands = buildCommands;
    }

    public DefaultEclipseJavaSourceSettings getJavaSourceSettings() {
        return javaSourceSettings;
    }

    public void setJavaSourceSettings(DefaultEclipseJavaSourceSettings javaSourceSettings) {
        this.javaSourceSettings = javaSourceSettings;
    }
}


text:
/**The panel for the Session clock. Appears as "Session Running Time: " under Session status.
 * Keeps track of the session time (sec_elapsed) and sends rewards during NCR
 */
import java.awt.*;
import javax.swing.*;
import java.util.*;

class SessionWatch extends JPanel implements Runnable {
    Integer sec_elapsed = new Integer(0);
    Calendar time1;
    Calendar time2;
    Calendar timer = Calendar.getInstance();
    boolean run = true;
    JLabel tLabel = new JLabel();
    static Font bigFont = new Font("arial", Font.BOLD, 26);

    SessionWatch() {
        this.setPreferredSize(new Dimension(440,40));
        this.add(tLabel);
        tLabel.setFont(bigFont);
        this.refreshTimeDisplay();
    }

    public void reset() {
        timer.set(Calendar.HOUR_OF_DAY,0);
        timer.set(Calendar.MINUTE,0);
        timer.set(Calendar.SECOND,0);
        time1 = Calendar.getInstance();
        sec_elapsed = 0;
        this.refreshTimeDisplay();
    }

    public void run() {
        run = true;
        time2 = Calendar.getInstance();
        time2.add(Calendar.SECOND,1);
        time2.add(Calendar.MILLISECOND,-1);
        timer_loop: for (;;) {
            time1 = Calendar.getInstance();
            try {
                Thread.sleep(100);
            } catch (Exception e) {}

            if ( time1.after(time2) && run ) {
                time2.add(Calendar.SECOND,1);
                timer.add(Calendar.SECOND,1);
                sec_elapsed = sec_elapsed + 1;
            }

            if (isRTime(sec_elapsed)) {
                TicTimer.send_reward();
            }

            this.refreshTimeDisplay();
            if ( ! run ) break timer_loop;
        }
    }

    /**
     * For NCR:
     * check if the given time is one of the times from the DRZ file
     */
    public boolean isRTime(Integer t) {
        if(TicTimer.session_type.equals("NCR")){
            for( Timestamp ts: TicTimer.ncrTimes) {
                if(ts.hrs*3600 + ts.mins*60 + ts.secs == t) {
                    TicTimer.ncrTimes.remove(ts);
                    return true;
                }
            }
        }
        return false;
    }

    public void pauseWatch() {
        run = false;
    }

    protected String getDigitsAsString(int i) {
        String str = Integer.toString(i);
        if (i<10) return "0"+str;
        return str;
    }

    public String getTimeAsString() {
        return getDigitsAsString(timer.get(Calendar.HOUR_OF_DAY)) + ":"
             + getDigitsAsString(timer.get(Calendar.MINUTE))  + ":"
             + getDigitsAsString(timer.get(Calendar.SECOND));
    }

    public void refreshTimeDisplay() {
        String display = "Session Running Time:  " + getTimeAsString();
        tLabel.setText( display );
        tLabel.repaint();
    }
}


text:
Install dependencies

```bash
$ npm install
```

Start the dev-server

```bash
$ npm start
```

To run all tests with mocha

```bash
$ npm test
```

Check your code with eslint

```bash
$ npm lint
```


text:
layout: post
dateCreated: 1/26/2010 8:49:00 AM
title: Optimize LINQ to SQL with PLINQO Futures
tags:
- PLINQO
---

PLINQO future queries are a way to defer query execution until it is needed. The difference between standard IQueryable deferred queries and future queries is that the future queries are batched up and executed in a single round trip to the database.

Read more at [PLINQO.com](http://PLINQO.com "PLINQO.com")


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VenoMpie.Common.Interfaces.GGn.SearchResults.SubResults;

namespace VenoMpie.Common.Interfaces.GGn.SearchResults
{
    public class UserRatioStats
    {
        public string uploaded { get; set; }
        public string downloaded { get; set; }
        public decimal ratio { get; set; }
        public long buffer { get; set; }
        public decimal disposable { get; set; }
        public string reqratio { get; set; }
    }
}


text:
@interface BOXFileShareRequest : BOXItemShareRequest

@property (nonatomic, readonly, copy) NSString *fileID;

- (instancetype)initWithFileID:(NSString *)fileID;
- (void)performRequestWithCompletion:(BOXFileBlock)completionBlock;

@end


text:
class ApplicationController < ActionController::Base
  protect_from_forgery

  private

  # Overwriting the sign_out redirect path method
  def after_sign_out_path_for(resource_or_scope)
    cookies.delete :session
    building_path
  end

  def check_admin!
    # admin if (1) User is signed in and (2) Does not have an omniauth provider or has a role as 'admin'
    unless user_signed_in? and (current_user.provider.nil? or current_user.role=='admin')
      redirect_to new_user_session_path
    end
  end

end


text:
local cFunc = {};		-- Local Functions
local cSetting = {};	-- Local Settings

CarStart = {};
CarStart.__index = CarStart;

--[[

]]

-- ///////////////////////////////
-- ///// New 				//////
-- ///// Returns: Object	//////
-- ///////////////////////////////

function CarStart:New(...)
	local obj = setmetatable({}, {__index = self});
	if obj.Constructor then
		obj:Constructor(...);
	end
	return obj;
end

-- ///////////////////////////////
-- ///// VehicleSound 		//////
-- ///// Returns: void		//////
-- ///////////////////////////////

function CarStart:VehicleSound(vehicle, was)
	local x, y, z = getElementPosition(vehicle);

	if(isElement(self.vehicleSound[vehicle])) then
		if(isTimer(self.vehicleTurnTimer[vehicle])) then
			killTimer(self.vehicleTurnTimer[vehicle])
		end
		local sound = self.vehicleSound[vehicle]
		setTimer(function()
			if(isElement(sound)) then
				destroyElement(sound);
			end
		end, 200, 1)
	end

	self.vehicleSound[vehicle] = playSound3D(self.pfade.sounds..was..".mp3", x, y, z);
	setSoundVolume(self.vehicleSound[vehicle], 1)
	attachElements(self.vehicleSound[vehicle], vehicle)
	setElementDimension(self.vehicleSound[vehicle], getElementDimension(vehicle))
	setElementInterior(self.vehicleSound[vehicle], getElementInterior(vehicle))
	setSoundMaxDistance(self.vehicleSound[vehicle], 50)

	if(was == "engine_start") then
		self.vehicleTurnTimer[vehicle] = setTimer(function()
			if(isElement(vehicle)) then
				if(self.vehicleTurnVar[vehicle] == 1) then
					setVehicleTurnVelocity(vehicle, 0.01, 0.01, 0)
					self.vehicleTurnVar[vehicle] = 0
				else
					setVehicleTurnVelocity(vehicle, -0.01, -0.01, 0)
					self.vehicleTurnVar[vehicle] = 1
				end
			else
				killTimer(self.vehicleTurnTimer[vehicle])
			end
		end, 100, -1)
	end
end

-- ///////////////////////////////
-- ///// Constructor 		//////
-- ///// Returns: void		//////
-- ///////////////////////////////

function CarStart:Constructor(...)
	addEvent("onVehicleStartSound", true)

	self.pfade = {}
	self.pfade.sounds = "res/sounds/car/"

	self.vehicleSound = {}
	self.vehicleTurnTimer = {}
	self.vehicleTurnVar = {}

	self.vehicleSoundFunc = function(...) self:VehicleSound(...) end;

	addEventHandler("onVehicleStartSound", getRootElement(), self.vehicleSoundFunc)
	--outputDebugString("[CALLING] CarStart: Constructor");
end

-- EVENT HANDLER --


text:
from pandas import Series
import simplejson as json

from bamboo.controllers.datasets import Datasets
from bamboo.models.dataset import Dataset
from bamboo.models.observation import Observation
from bamboo.tests.controllers.test_abstract_datasets import\
    TestAbstractDatasets

class TestDatasetsEdit(TestAbstractDatasets):

    def setUp(self):
        TestAbstractDatasets.setUp(self)

    def test_show_row(self):
        dataset_id = self._post_file()
        result = json.loads(self.controller.row_show(dataset_id, 0))

        self.assertTrue(isinstance(result, dict))
        self.assertEqual(9.0, result['amount'])

        result = json.loads(self.controller.row_show(dataset_id, "0"))

        self.assertTrue(isinstance(result, dict))
        self.assertEqual(9.0, result['amount'])

    def test_show_row_nonexistent_index(self):
        dataset_id = self._post_file()
        result = json.loads(self.controller.row_show(dataset_id, "90"))

        self.assertTrue(isinstance(result, dict))
        self.assertTrue(Datasets.ERROR in result)

    def test_show_row_bad_index(self):
        dataset_id = self._post_file()
        result = json.loads(self.controller.row_show(dataset_id, "A"))

        self.assertTrue(isinstance(result, dict))
        self.assertTrue(Datasets.ERROR in result)

    def test_delete_row(self):
        dataset_id = self._post_file()
        dataset = Dataset.find_one(dataset_id)
        index = 0
        expected_dframe = Dataset.find_one(
            dataset_id).dframe()[index + 1:].reset_index()
        del expected_dframe['index']

        results = json.loads(self.controller.row_delete(dataset_id, index))
        self.assertTrue(Datasets.SUCCESS in results.keys())

        dataset = Dataset.find_one(dataset_id)
        dframe = dataset.dframe()
        self.assertEqual(self.NUM_ROWS - 1, len(dframe))
        self._check_dframes_are_equal(expected_dframe, dframe)

        # check info updated
        info = dataset.info()
        self.assertEqual(self.NUM_ROWS - 1, info[Dataset.NUM_ROWS])

        # check that row is softly deleted
        all_observations = Observation.find(dataset, include_deleted=True)
        self.assertEqual(self.NUM_ROWS, len(all_observations))

    def test_delete_row_with_agg(self):
        amount_sum = 2007.5
        amount_sum_after = 1998.5
        index = 0

        self.dataset_id = self._post_file()
        self._post_calculations(formulae=['sum(amount)'])
        agg = self._test_aggregations()[0]
        self.assertEqual(agg['sum_amount_'], amount_sum)

        results = json.loads(
            self.controller.row_delete(self.dataset_id, index))
        self.assertTrue(Datasets.SUCCESS in results.keys())

        agg = self._test_aggregations()[0]
        self.assertEqual(agg['sum_amount_'], amount_sum_after)

    def test_delete_row_with_join(self):
        index = 0

        left_dataset_id = self._post_file()
        right_dataset_id = self._post_file('good_eats_aux.csv')
        on = 'food_type'
        results = json.loads(self.controller.join(
            left_dataset_id, right_dataset_id, on=on))
        joined_dataset_id = results[Dataset.ID]

        results = json.loads(self.controller.join(
            joined_dataset_id, right_dataset_id, on=on))
        joined_dataset_id2 = results[Dataset.ID]

        results = json.loads(
            self.controller.row_delete(left_dataset_id, index))
        self.assertTrue(Datasets.SUCCESS in results.keys())

        dframe = Dataset.find_one(joined_dataset_id).dframe(index=True)
        self.assertFalse(index in dframe['index'].tolist())

        dframe = Dataset.find_one(joined_dataset_id2).dframe(index=True)
        self.assertFalse(index in dframe['index'].tolist())

    def test_delete_row_with_merge(self):
        index = 0

        dataset_id1 = self._post_file()
        dataset_id2 = self._post_file()
        result = json.loads(self.controller.merge(
            dataset_ids=json.dumps([dataset_id1, dataset_id2])))
        merged_id = result[Dataset.ID]

        results = json.loads(
            self.controller.row_delete(dataset_id2, index))
        self.assertTrue(Datasets.SUCCESS in results.keys())

        results = json.loads(
            self.controller.row_delete(dataset_id1, index))
        self.assertTrue(Datasets.SUCCESS in results.keys())

        dframe = Dataset.find_one(merged_id).dframe(index=True)
        self.assertFalse(index in dframe['index'].tolist())
        self.assertFalse(index + self.NUM_ROWS in dframe['index'].tolist())

    def test_edit_row(self):
        dataset_id = self._post_file()
        index = 0
        update = {'amount': 10, 'food_type': 'breakfast'}
        expected_dframe = Dataset.find_one(dataset_id).dframe()
        expected_row = expected_dframe.ix[0].to_dict()
        expected_row.update(update)
        expected_dframe.ix[0] = Series(expected_row)

        results = json.loads(self.controller.row_update(dataset_id, index,
                                                        json.dumps(update)))
        self.assertTrue(Datasets.SUCCESS in results.keys())

        dataset = Dataset.find_one(dataset_id)
        dframe = dataset.dframe()
        self.assertEqual(self.NUM_ROWS, len(dframe))
        self._check_dframes_are_equal(expected_dframe, dframe)

        # check that previous row exists
        all_observations = Observation.find(dataset, include_deleted=True)
        self.assertEqual(self.NUM_ROWS + 1, len(all_observations))

    def test_edit_row_with_calculation(self):
        amount_before = 9
        amount_after = 10
        value = 5
        index = 0
        update = {'amount': amount_after, 'food_type': 'breakfast'}

        self.dataset_id = self._post_file()
        self._post_calculations(formulae=['amount + %s' % value])

        result = json.loads(self.controller.row_show(self.dataset_id, index))
        self.assertEqual(amount_before + value, result['amount___%s' % value])

        results = json.loads(self.controller.row_update(self.dataset_id, index,
                                                        json.dumps(update)))
        self.assertTrue(Datasets.SUCCESS in results.keys())

        result = json.loads(self.controller.row_show(self.dataset_id, index))
        self.assertEqual(amount_after + value, result['amount___%s' % value])

    def test_edit_row_with_agg(self):
        amount_sum = 2007.5
        amount_sum_after = 2008.5

        self.dataset_id = self._post_file()
        self._post_calculations(formulae=['sum(amount)'])
        agg = self._test_aggregations()[0]
        self.assertEqual(agg['sum_amount_'], amount_sum)

        index = 0
        update = {'amount': 10, 'food_type': 'breakfast'}
        results = json.loads(self.controller.row_update(self.dataset_id, index,
                                                        json.dumps(update)))
        self.assertTrue(Datasets.SUCCESS in results.keys())

        agg = self._test_aggregations()[0]
        self.assertEqual(agg['sum_amount_'], amount_sum_after)

    def test_edit_row_with_join(self):
        index = 0
        value = 10
        update = {'amount': value, 'food_type': 'breakfast'}

        left_dataset_id = self._post_file()
        right_dataset_id = self._post_file('good_eats_aux.csv')
        on = 'food_type'
        results = json.loads(self.controller.join(
            left_dataset_id, right_dataset_id, on=on))
        joined_dataset_id = results[Dataset.ID]

        results = json.loads(self.controller.join(
            joined_dataset_id, right_dataset_id, on=on))
        joined_dataset_id2 = results[Dataset.ID]

        results = json.loads(self.controller.row_update(left_dataset_id, index,
                                                        json.dumps(update)))
        self.assertTrue(Datasets.SUCCESS in results.keys())

        result = json.loads(self.controller.row_show(joined_dataset_id, 0))
        self.assertEqual(value, result['amount'])

        result = json.loads(self.controller.row_show(joined_dataset_id2, 0))
        self.assertEqual(value, result['amount'])

    def test_edit_row_with_join_invalid(self):
        index = 0
        update = {'food_type': 'deserts'}

        left_dataset_id = self._post_file()
        right_dataset_id = self._post_file('good_eats_aux.csv')
        num_rows_before = Dataset.find_one(right_dataset_id).num_rows
        on = 'food_type'
        json.loads(self.controller.join(
            left_dataset_id, right_dataset_id, on=on))

        results = json.loads(self.controller.row_update(
            right_dataset_id, index, json.dumps(update)))
        self.assertTrue(Datasets.SUCCESS in results.keys())

        dataset = Dataset.find_one(right_dataset_id)
        self.assertEqual(num_rows_before, dataset.num_rows)
        self.assertEqual(dataset.pending_updates, [])

    def test_edit_row_with_merge(self):
        index = 0
        value = 10
        update = {'amount': value, 'food_type': 'breakfast'}

        dataset_id1 = self._post_file()
        dataset_id2 = self._post_file()
        result = json.loads(self.controller.merge(
            dataset_ids=json.dumps([dataset_id1, dataset_id2])))
        merged_id = result[Dataset.ID]

        results = json.loads(self.controller.row_update(dataset_id1, index,
                                                        json.dumps(update)))
        self.assertTrue(Datasets.SUCCESS in results.keys())

        results = json.loads(self.controller.row_update(dataset_id2, index,
                                                        json.dumps(update)))
        self.assertTrue(Datasets.SUCCESS in results.keys())

        result = json.loads(self.controller.row_show(merged_id, index))
        self.assertEqual(value, result['amount'])

        result = json.loads(self.controller.row_show(merged_id, index +
                                                     self.NUM_ROWS))
        self.assertEqual(value, result['amount'])


text:
package com.cognizant.cognizantits.qcconnection.qcupdation;

import com4j.Com4jObject;
import com4j.DISPID;
import com4j.IID;
import com4j.NativeType;
import com4j.ReturnValue;
import com4j.VTID;

@IID("{45FF281C-B518-494A-A720-392B36BD7729}")
public abstract interface IComparisonSettings
  extends Com4jObject
{
  @DISPID(1)
  @VTID(7)
  public abstract String type();

  @DISPID(2)
  @VTID(8)
  public abstract IList fields();

  @VTID(8)
  @ReturnValue(type=NativeType.VARIANT, defaultPropertyThrough={IList.class})
  public abstract Object fields(int paramInt);

  @DISPID(3)
  @VTID(9)
  public abstract boolean attachments();

  @DISPID(4)
  @VTID(10)
  public abstract boolean richContent();
}

/* Location:           D:\Prabu\jars\QC.jar
 * Qualified Name:     qcupdation.IComparisonSettings
 * JD-Core Version:    0.7.0.1
 */


text:
package com.hazelcast.osgi.impl;

import com.hazelcast.internal.management.ScriptEngineManagerContext;
import com.hazelcast.test.HazelcastSerialClassRunner;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;

import javax.script.Bindings;
import javax.script.ScriptEngineManager;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.mockito.Mockito.mock;

@RunWith(HazelcastSerialClassRunner.class)
@Category(QuickTest.class)
public class HazelcastOSGiScriptEngineManagerTest extends HazelcastOSGiScriptingTest {

    @Test
    public void scriptEngineManagerSetSuccessfully() {
        assertNotNull(ScriptEngineManagerContext.getScriptEngineManager());
    }

    @Test
    public void scriptEnginesPrintedSuccessfully() {
        OSGiScriptEngineManager scriptEngineManager =
                (OSGiScriptEngineManager) ScriptEngineManagerContext.getScriptEngineManager();

        assertNotNull(scriptEngineManager.printScriptEngines());
    }

    @Test
    public void bindingsGetAndSetSuccessfully() {
        ScriptEngineManager scriptEngineManager = ScriptEngineManagerContext.getScriptEngineManager();

        assertNotNull(scriptEngineManager.getBindings());

        Bindings mockBindings = mock(Bindings.class);
        scriptEngineManager.setBindings(mockBindings);
        assertEquals(mockBindings, scriptEngineManager.getBindings());
    }

    @Test
    public void putAndGetOverBindingsSuccessfully() {
        ScriptEngineManager scriptEngineManager = ScriptEngineManagerContext.getScriptEngineManager();

        Bindings bindings = scriptEngineManager.getBindings();

        assertNull(bindings.get("my-key"));
        bindings.put("my-key", "my-value");
        assertEquals("my-value", bindings.get("my-key"));
    }
}


text:
/* Desc: Heightmap shape
 * Author: Nate Koenig, Andrew Howard
 * Date: 8 May 2003
 */

#include <string.h>
#include <math.h>

#include "common/Image.hh"
#include "common/Common.hh"
#include "common/Exception.hh"

#include "physics/HeightmapShape.hh"

using namespace gazebo;
using namespace physics;

//////////////////////////////////////////////////
HeightmapShape::HeightmapShape(CollisionPtr _parent)
    : Shape(_parent)
{
  this->AddType(Base::HEIGHTMAP_SHAPE);
}

//////////////////////////////////////////////////
HeightmapShape::~HeightmapShape()
{
}

//////////////////////////////////////////////////
void HeightmapShape::Load(sdf::ElementPtr _sdf)
{
  Base::Load(_sdf);

  std::string filename = common::find_file(this->sdf->GetValueString("uri"));
  if (filename.empty())
  {
    gzthrow("Unable to find heightmap[" +
            this->sdf->GetValueString("uri") + "]\n");
  }

  // Use the image to get the size of the heightmap
  this->img.Load(filename);

  if (this->img.GetWidth() != this->img.GetHeight() ||
      !math::isPowerOfTwo(this->img.GetWidth()-1))
  {
    gzthrow("Heightmap image size must be square, with a size of 2^n+1\n");
  }
}

//////////////////////////////////////////////////
int HeightmapShape::GetSubSampling() const
{
  return this->subSampling;
}

//////////////////////////////////////////////////
void HeightmapShape::Init()
{
  this->subSampling = 1;

  math::Vector3 terrainSize = this->GetSize();

  // sampling size along image width and height
  this->vertSize = this->img.GetWidth() * this->subSampling;
  this->scale.x = terrainSize.x / this->vertSize;
  this->scale.y = terrainSize.y / this->vertSize;

  if (math::equal(this->img.GetMaxColor().r, 0.0f))
    this->scale.z = fabs(terrainSize.z);
  else
    this->scale.z = fabs(terrainSize.z) / this->img.GetMaxColor().r;

  // Step 1: Construct the heightmap lookup table
  this->FillHeightMap();
}

//////////////////////////////////////////////////
void HeightmapShape::FillHeightMap()
{
  unsigned int x, y;
  float h = 0;
  float h1 = 0;
  float h2 = 0;

  // Resize the vector to match the size of the vertices
  this->heights.resize(this->vertSize * this->vertSize);

  common::Color pixel;

  double yf, xf, dy, dx;
  int y1, y2, x1, x2;
  double px1, px2, px3, px4;

  int imgHeight = this->img.GetHeight();
  int imgWidth = this->img.GetWidth();
  // Bytes per row
  unsigned int pitch = this->img.GetPitch();
  // Bytes per pixel
  unsigned int bpp = pitch / imgWidth;

  unsigned char *data = NULL;
  unsigned int count;
  this->img.GetData(&data, count);

  // Iterate over all the vertices
  for (y = 0; y < this->vertSize; y++)
  {
    // yf ranges between 0 and 4
    yf = y / static_cast<double>(this->subSampling);
    y1 = floor(yf);
    y2 = ceil(yf);
    if (y2 >= imgHeight)
      y2 = imgHeight-1;
    dy = yf - y1;

    for (x = 0; x < this->vertSize; x++)
    {
      xf = x / static_cast<double>(this->subSampling);
      x1 = floor(xf);
      x2 = ceil(xf);
      if (x2 >= imgWidth)
        x2 = imgWidth-1;
      dx = xf - x1;

      px1 = static_cast<int>(data[y1 * pitch + x1 * bpp]) / 255.0;
      px2 = static_cast<int>(data[y1 * pitch + x2 * bpp]) / 255.0;
      h1 = (px1 - ((px1 - px2) * dx));

      px3 = static_cast<int>(data[y2 * pitch + x1 * bpp]) / 255.0;
      px4 = static_cast<int>(data[y2 * pitch + x2 * bpp]) / 255.0;
      h2 = (px3 - ((px3 - px4) * dx));

      h = (h1 - ((h1 - h2) * dy)) * this->scale.z;

      // invert pixel definition so 1=ground, 0=full height,
      //   if the terrain size has a negative z component
      //   this is mainly for backward compatibility
      if (this->GetSize().z < 0)
        h = 1.0 - h;

      // Store the height for future use
      this->heights[y * this->vertSize + x] = h;
    }
  }

  delete [] data;
}

//////////////////////////////////////////////////
std::string HeightmapShape::GetURI() const
{
  return this->sdf->GetValueString("uri");
}

//////////////////////////////////////////////////
math::Vector3 HeightmapShape::GetSize() const
{
  return this->sdf->GetValueVector3("size");
}

//////////////////////////////////////////////////
math::Vector3 HeightmapShape::GetPos() const
{
  return this->sdf->GetValueVector3("pos");
}

//////////////////////////////////////////////////
void HeightmapShape::FillMsg(msgs::Geometry &_msg)
{
  _msg.set_type(msgs::Geometry::HEIGHTMAP);
  msgs::Set(_msg.mutable_heightmap()->mutable_image(),
            common::Image(this->GetURI()));
  msgs::Set(_msg.mutable_heightmap()->mutable_size(), this->GetSize());
  msgs::Set(_msg.mutable_heightmap()->mutable_origin(), this->GetPos());
}

//////////////////////////////////////////////////
void HeightmapShape::ProcessMsg(const msgs::Geometry & /*_msg*/)
{
  gzerr << "TODO: not implement yet.";
}

//////////////////////////////////////////////////
math::Vector2i HeightmapShape::GetVertexCount() const
{
  return math::Vector2i(this->vertSize, this->vertSize);
}

/////////////////////////////////////////////////
float HeightmapShape::GetHeight(int _x, int _y)
{
  return this->heights[(_y * this->subSampling) * this->vertSize +
                       (_x * this->subSampling)];
}

/////////////////////////////////////////////////
float HeightmapShape::GetMaxHeight() const
{
  float max = GZ_FLT_MIN;
  for (unsigned int i = 0; i < this->heights.size(); ++i)
  {
    if (this->heights[i] > max)
      max = this->heights[i];
  }

  return max;
}

/////////////////////////////////////////////////
float HeightmapShape::GetMinHeight() const
{
  float min = GZ_FLT_MAX;
  for (unsigned int i = 0; i < this->heights.size(); ++i)
  {
    if (this->heights[i] < min)
      min = this->heights[i];
  }

  return min;
}


text:
extern crate libc;

#[cfg(target_os = "macos")]
mod mac_clipboard;

#[cfg(target_os = "macos")]
use mac_clipboard as inner;

#[cfg(windows)]
mod windows_clipboard;

#[cfg(windows)]
use windows_clipboard as inner;

#[cfg(all(not(target_os = "macos"), unix))]
mod unix_clipboard;

#[cfg(all(not(target_os = "macos"), unix))]
use unix_clipboard as inner;

#[cfg(not(any(windows, unix, target_os = "macos")))]
mod dummy_clipboard;

#[cfg(not(any(windows, unix, target_os = "macos")))]
use dummy_clipboard as inner;

pub use inner::ClipboardExt;

use std::borrow::Cow;
use std::error::Error as StdError;
use std::fmt;

#[derive(Debug)]
pub struct Clipboard(inner::Clipboard);

impl Clipboard {
    #[inline]
    pub fn get() -> Result<Self> {
        inner::Clipboard::get().map(|cb| Clipboard(cb))
    }

    #[inline]
    pub fn copy(&mut self, item: &Item) -> Result<()> {
        self.0.copy(item)
    }

    #[inline]
    pub fn copy_items(&mut self, items: &[Item]) -> Result<()> {
        self.0.copy_items(items)
    }

    #[inline]
    pub fn get_paste_text(&self) -> Result<&str> {
        self.0.get_paste_text()
    }

    #[inline]
    pub fn get_items(&self) -> Cow<[Item]> {
        self.0.get_items()
    }
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum ImageFormat {
    Jpg,
    Png,
}

pub trait Image {
    fn bytes(&self) -> &[u8];
    fn format(&self) -> ImageFormat;
    fn from_bytes(bytes: &[u8]) -> Result<Self> where Self: Sized;
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum SoundFormat {
    Wav,
    Aiff,
    Alac,
    Flac,
    Mp3,
    OggVorbis,
}

pub trait Sound {
    fn bytes(&self) -> &[u8];
    fn format(&self) -> SoundFormat;
    fn from_bytes(bytes: &[u8]) -> Result<Self> where Self: Sized;
}

#[derive(Clone, Copy)]
pub enum Item<'a> {
    Text(&'a str),
    Image(&'a Image),
    Sound(&'a Sound),
    Other(*mut libc::c_void),
}

pub type Result<T> = ::std::result::Result<T, inner::Error>;

#[cfg(all(test, any(unix, windows)))]
mod tests {
    use {Clipboard, Item};
    #[test]
    fn test_native_clipboard() {
        const TEST_TEXT: &'static str = "BoomShakalaka";
        let mut clipboard = Clipboard::get().unwrap();

        // Save the current clipboard text
        let current_clipboard_text = clipboard.get_paste_text().unwrap().to_string();

        clipboard.copy(&Item::Text(TEST_TEXT)).unwrap();
        assert_eq!(clipboard.get_paste_text().unwrap(), TEST_TEXT);

        // And restore the clipboard to its previous state after the test
        clipboard
            .copy(&Item::Text(&current_clipboard_text))
            .unwrap();
    }
}


text:
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          ______     ______     ______   __  __     __     ______
          /\  == \   /\  __ \   /\__  _\ /\ \/ /    /\ \   /\__  _\
          \ \  __<   \ \ \/\ \  \/_/\ \/ \ \  _"-.  \ \ \  \/_/\ \/
          \ \_____\  \ \_____\    \ \_\  \ \_\ \_\  \ \_\    \ \_\
           \/_____/   \/_____/     \/_/   \/_/\/_/   \/_/     \/_/
This is a sample Slack bot built with Botkit.
This bot demonstrates many of the core features of Botkit:
* Connect to Slack using the real time API
* Receive messages based on "spoken" patterns
* Reply to messages
* Use the conversation system to ask questions
* Use the built in storage system to store and retrieve information
  for a user.
# RUN THE BOT:
  Get a Bot token from Slack:
    -> http://my.slack.com/services/new/bot
  Run your bot from the command line:
    set token=<MY TOKEN>
    node bot.js
# USE THE BOT:
  Find your bot inside Slack to send it a direct message.
  Say: "Hello"
  The bot will reply "Hello!"
  Say: "who are you?"
  The bot will tell you its name, where it running, and for how long.
  Say: "Call me <nickname>"
  Tell the bot your nickname. Now you are friends.
  Say: "who am I?"
  The bot will tell you your nickname, if it knows one for you.
  Say: "shutdown"
  The bot will ask if you are sure, and then shut itself down.
  Make sure to invite your bot into other channels using /invite @<my bot>!
# EXTEND THE BOT:
  Botkit is has many features for building cool and useful bots!
  Read all about it here:
    -> http://howdy.ai/botkit
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

if (!process.env.token) {
    console.log('Error: Specify token in environment');
    process.exit(1);
}

var MathHelper = require('./botmath.js');
var Botkit = require('./lib/Botkit.js');
var os = require('os');

var controller = Botkit.slackbot({
    debug: true,
});

var bot = controller.spawn({
    token: process.env.token
}).startRTM();

controller.hears(['hello','hi'],'direct_message,direct_mention,mention',function(bot, message) {

    bot.api.reactions.add({
        timestamp: message.ts,
        channel: message.channel,
        name: 'robot_face',
    },function(err, res) {
        if (err) {
            bot.botkit.log('Failed to add emoji reaction :(',err);
        }
    });

    controller.storage.users.get(message.user,function(err, user) {
        if (user && user.name) {
            bot.reply(message,'Hello ' + user.name + '!!');
        } else {
            bot.reply(message,'Hello.');
        }
    });
});

controller.hears(['call me (.*)'],'direct_message,direct_mention,mention',function(bot, message) {
    var matches = message.text.match(/call me (.*)/i);
    var name = matches[1];
    controller.storage.users.get(message.user,function(err, user) {
        if (!user) {
            user = {
                id: message.user,
            };
        }
        user.name = name;
        controller.storage.users.save(user,function(err, id) {
            bot.reply(message,'Got it. I will call you ' + user.name + ' from now on.');
        });
    });
});

controller.hears(['what is my name','who am i'],'direct_message,direct_mention,mention',function(bot, message) {

    controller.storage.users.get(message.user,function(err, user) {
        if (user && user.name) {
            bot.reply(message,'Your name is ' + user.name);
        } else {
            bot.reply(message,'I don\'t know yet!');
        }
    });
});

function isPrime(number) {
    var start = 2;
    while (start <= Math.sqrt(number)) {
        if (number % start++ < 1) return false;
    }
    return number > 1;
}

controller.hears(['who make you','who made you'],'direct_message,direct_mention,mention',function(bot, message) {

    controller.storage.users.get(message.user,function(err, user) {
        bot.reply(message,'Metro group made me. Hihi');
    });
});

controller.hears(['shutdown'],'direct_message,direct_mention,mention',function(bot, message) {

    bot.startConversation(message,function(err, convo) {
        convo.ask('Are you sure you want me to shutdown?',[
            {
                pattern: bot.utterances.yes,
                callback: function(response, convo) {
                    convo.say('Bye!');
                    convo.next();
                    setTimeout(function() {
                        process.exit();
                    },3000);
                }
            },
        {
            pattern: bot.utterances.no,
            default: true,
            callback: function(response, convo) {
                convo.say('*Phew!*');
                convo.next();
            }
        }
        ]);
    });
});

controller.hears(['uptime','identify yourself','who are you','what is your name'],'direct_message,direct_mention,mention',function(bot, message) {

    var hostname = os.hostname();
    var uptime = formatUptime(process.uptime());

    bot.reply(message,':robot_face: I am a bot named <@' + bot.identity.name + '>. I have been running for ' + uptime + ' on ' + hostname + '.');

});

controller.hears(['fibonacci'], 'direct_message,direct_mention,mention', function(bot, message) {
    if (message.text == 'fibonacci') {
        bot.reply(message, '1, 1, 2, 3, 5');
    }
});

controller.hears(['fibonacci ([0-9]+)'], 'direct_message,direct_mention,mention', function(bot, message) {
    var parameter = parseInt(message.match[1]);

    var fibonacci = calculateFibonacciUpto(parameter);
    if (fibonacci[fibonacci.length-1] !== parameter) {
        bot.reply(message, 'That is not a Fibonacci number!');
    }
    else {
      for (var i = 0; i < 5; i++){
        fibonacci.push(fibonacci[fibonacci.length-2] + fibonacci[fibonacci.length-1])
      }
        bot.reply(message, fibonacci.slice(fibonacci.length - 5,fibonacci.length).join(', '));
    }
});

function calculateFibonacciUpto(goal) {
    var fibonacci = [1, 1];
    while (fibonacci[fibonacci.length-1] < goal) {
        fibonacci.push(fibonacci[fibonacci.length-2] + fibonacci[fibonacci.length-1]);
    }

    return fibonacci;
}

function formatUptime(uptime) {
    var unit = 'second';
    if (uptime > 60) {
        uptime = uptime / 60;
        unit = 'minute';
    }
    if (uptime > 60) {
        uptime = uptime / 60;
        unit = 'hour';
    }
    if (uptime != 1) {
        unit = unit + 's';
    }

    uptime = uptime + ' ' + unit;
    return uptime;
}

controller.hears('prime',['direct_message', 'direct_mention', 'mention'],function(bot,message) {
    if (message.text === "prime") {
        return bot.reply(message, '2, 3, 5, 7, 11, 13, 17, 19, 23, 29');
    }
});

controller.hears('prime (.*)',['direct_message', 'direct_mention', 'mention'],function(bot,message) {

    var parameter = parseInt(message.match[1]);

    if (MathHelper.isPrime(parameter)) {
        bot.reply(message, "your parameter: " + parameter + " is a Prime number");
        var primes = new Array();
        var number = parameter - 1;

        while (primes.length < 10 && number >=0) {

            if (MathHelper.isPrime(number)) {
                primes.push(number);
            }

            number--;
        }

        var reply = "";
        for (var i = 0; i < primes.length; i++) {
            reply += primes[i] + " ";
        }

        return bot.reply(message, reply);
    }
    else {
        bot.reply(message, "your parameter: " + parameter + " is not Prime number");
        var primes = new Array();
        var number = parameter - 1;

        while (primes.length < 10 && number >=0) {

            if (MathHelper.isPrime(number)) {
                primes.push(number);
            }

            number--;
        }

        var reply = "";
        for (var i = 0; i < primes.length; i++) {
            reply += primes[i] + " ";
        }

        return bot.reply(message, reply);
    }
var weather = require('weather-js');

weather.find({search: 'San Francisco, CA', degreeType: 'F'}, function(err, result) {
  if(err) console.log(err);

  console.log(JSON.stringify(result, null, 2));
});

controller.hears('How is the temperature in (.*)',['direct_message','mention'],function(bot,message) {

    var city = message.match[1];
    console.log(city);

    weather.find({search: city, degreeType: 'C'}, function(err, result) {
      if(err) console.log(err);

      console.log(JSON.stringify(result, null, 2));

      return bot.reply(message,'The temperature is ' + result[0]['current']['temperature'] + ' degree Celcius');
    });

});

});


text:
// Copyright (C) 2015-2017 Luca Piccioni
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

using System;
using System.Text.RegularExpressions;

namespace Khronos
{
	/// <summary>
	/// Attribute asserting the features requiring the underlying member.
	/// </summary>
	[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
	public sealed class RequiredByFeatureAttribute : Attribute
	{
		#region Constructors

		/// <summary>
		/// Construct a RequiredByFeatureAttribute, specifying the feature name.
		/// </summary>
		/// <param name="featureName">
		/// A <see cref="string"/> that specifies the name of the feature that requires the element.
		/// </param>
		/// <exception cref="ArgumentException">
		/// Exception thrown if <paramref name="featureName"/> is null or empty.
		/// </exception>
		public RequiredByFeatureAttribute(string featureName)
		{
			if (string.IsNullOrEmpty(featureName))
				throw new ArgumentException("null or empty feature not allowed", nameof(featureName));
			FeatureName = featureName;
			FeatureVersion = KhronosVersion.ParseFeature(FeatureName);
		}

		#endregion

		#region Attributes

		/// <summary>
		/// The name of the feature.
		/// </summary>
		public readonly string FeatureName;

		/// <summary>
		/// A <see cref="KhronosVersion"/> representing <see cref="FeatureName"/>, in case it is an API version.
		/// </summary>
		public readonly KhronosVersion FeatureVersion;

		/// <summary>
		/// The name of the featuring API. Defaults to "gl".
		/// </summary>
		public string Api = "gl";

		/// <summary>
		/// The name of the API profile. Default to null, indicating all profiles for the API.
		/// </summary>
		public string Profile;

		/// <summary>
		/// If it is different from null, it specifies the complete name of the command to be loaded in case the
		/// feature is supported. It is meaninful only for commands. In it is null, the name of the command
		/// is implictly defined by the underlying field.
		/// </summary>
		public string EntryPoint;

		#endregion

		#region Support Detection

		internal bool IsSupportedApi(string api)
		{
			if (api == null)
				throw new ArgumentNullException(nameof(api));

			if (FeatureVersion != null)
				return (false);

			return (Regex.IsMatch(api, Api));
		}

		/// <summary>
		/// Determine whether an API implementation supports this feature.
		/// </summary>
		/// <param name="version">
		/// The <see cref="KhronosVersion"/> that specifies the API version.
		/// </param>
		/// <param name="extensions">
		/// The <see cref="KhronosApi.ExtensionsCollection"/> that specifies the API extensions registry. It can be null.
		/// </param>
		/// <returns>
		/// It returns a <see cref="Boolean"/> that specifies whether this feature is supported by the
		/// API having the version <paramref name="version"/> and the extensions registry <paramref name="extensions"/>.
		/// </returns>
		/// <exception cref="ArgumentNullException">
		/// Exception thrown if <paramref name="version"/> is null.
		/// </exception>
		public bool IsSupported(KhronosVersion version, KhronosApi.ExtensionsCollection extensions)
		{
			if (version == null)
				throw new ArgumentNullException(nameof(version));

			// Feature is an API version?
			if (FeatureVersion != null) {
				// API must match
				// Note: no need or regex, since Api cannot be a pattern
				if (version.Api != FeatureVersion.Api)
					return (false);
				// Profile must match, if defined
				if (Profile != null && version.Profile != null && Regex.IsMatch(version.Profile, Profile) == false)
					return (false);
				// API version must be greater than or equal to the required version
				return (version >= FeatureVersion);
			}

			// No API version: indeed it is an API extension
			if (extensions != null) {
				// Check compatible API
				// Note: regex is required since extensions can be implemented by multiple APIs
				if (Regex.IsMatch(version.Api, Api) == false)
					return (false);
				// Last chance: extension name
				return (extensions.HasExtensions(FeatureName));
			} else
				return (false);
		}

		#endregion
	}
}


text:
/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p10/common/include/p10_scom_pec_f.H $        */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2019,2020                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

#ifndef __PPE_HCODE__
    #include "proc_scomt.H"
#endif

#ifndef __p10_scom_pec_f_H_
#define __p10_scom_pec_f_H_

#ifndef __PPE_HCODE__
namespace scomt
{
namespace pec
{
#endif

//>> [BIST]
static const uint64_t BIST = 0x0803000bull;

static const uint32_t BIST_TC_BIST_START_TEST_DC = 0;
static const uint32_t BIST_TC_SRAM_ABIST_MODE_DC = 1;
static const uint32_t BIST_TC_IOBIST_MODE_DC = 3;
static const uint32_t BIST_REGION_PERV = 4;
static const uint32_t BIST_REGION_UNIT1 = 5;
static const uint32_t BIST_REGION_UNIT2 = 6;
static const uint32_t BIST_REGION_UNIT3 = 7;
static const uint32_t BIST_REGION_UNIT4 = 8;
static const uint32_t BIST_REGION_UNIT5 = 9;
static const uint32_t BIST_REGION_UNIT6 = 10;
static const uint32_t BIST_REGION_UNIT7 = 11;
static const uint32_t BIST_REGION_UNIT8 = 12;
static const uint32_t BIST_REGION_UNIT9 = 13;
static const uint32_t BIST_REGION_UNIT10 = 14;
static const uint32_t BIST_REGION_UNIT11 = 15;
static const uint32_t BIST_REGION_UNIT12 = 16;
static const uint32_t BIST_REGION_UNIT13 = 17;
static const uint32_t BIST_REGION_UNIT14 = 18;
static const uint32_t BIST_STROBE_WINDOW_EN = 48;
//<< [BIST]
// pec/reg00015.H

//>> [CPLT_CTRL5]
static const uint64_t CPLT_CTRL5_RW = 0x08000005ull;
static const uint64_t CPLT_CTRL5_WO_CLEAR = 0x08000025ull;
static const uint64_t CPLT_CTRL5_WO_OR = 0x08000015ull;

static const uint32_t CPLT_CTRL5_TC_CCFG_PMA0_MUX_SEL_DC = 0;
static const uint32_t CPLT_CTRL5_TC_CCFG_PMA1_MUX_SEL_DC = 1;
static const uint32_t CPLT_CTRL5_TC_CCFG_PMA2_MUX_SEL_DC = 2;
static const uint32_t CPLT_CTRL5_TC_CCFG_PMA3_MUX_SEL_DC = 3;
static const uint32_t CPLT_CTRL5_TC_CCFG_PCS01_MUX_SEL_DC = 4;
static const uint32_t CPLT_CTRL5_TC_CCFG_PCS23_MUX_SEL_DC = 5;
static const uint32_t CPLT_CTRL5_TC_CCFG_PIPE_LANEX_EXT_PLL_MODE_DC = 6;
static const uint32_t CPLT_CTRL5_TC_CCFG_PHYX_CR_PARA_SEL_DC = 7;
static const uint32_t CPLT_CTRL5_TC_CCFG_PHY_EXT_CTRL_SEL_DC = 8;
static const uint32_t CPLT_CTRL5_09 = 9;
static const uint32_t CPLT_CTRL5_010 = 10;
static const uint32_t CPLT_CTRL5_011 = 11;
static const uint32_t CPLT_CTRL5_012 = 12;
static const uint32_t CPLT_CTRL5_013 = 13;
static const uint32_t CPLT_CTRL5_014 = 14;
static const uint32_t CPLT_CTRL5_015 = 15;
static const uint32_t CPLT_CTRL5_016 = 16;
static const uint32_t CPLT_CTRL5_017 = 17;
static const uint32_t CPLT_CTRL5_018 = 18;
static const uint32_t CPLT_CTRL5_019 = 19;
//<< [CPLT_CTRL5]
// pec/reg00015.H

//>> [EPS_THERM_WSUB_DTS_RESULT0]
static const uint64_t EPS_THERM_WSUB_DTS_RESULT0 = 0x08050000ull;

static const uint32_t EPS_THERM_WSUB_DTS_RESULT0_0_RESULT = 0;
static const uint32_t EPS_THERM_WSUB_DTS_RESULT0_0_RESULT_LEN = 16;
static const uint32_t EPS_THERM_WSUB_DTS_RESULT0_1_RESULT = 16;
static const uint32_t EPS_THERM_WSUB_DTS_RESULT0_1_RESULT_LEN = 16;
static const uint32_t EPS_THERM_WSUB_DTS_RESULT0_2_RESULT = 32;
static const uint32_t EPS_THERM_WSUB_DTS_RESULT0_2_RESULT_LEN = 16;
//<< [EPS_THERM_WSUB_DTS_RESULT0]
// pec/reg00015.H

//>> [TIMEOUT_REG]
static const uint64_t TIMEOUT_REG = 0x080f0010ull;

static const uint32_t TIMEOUT_REG_INT_TIMEOUT = 0;
static const uint32_t TIMEOUT_REG_INT_TIMEOUT_LEN = 2;
//<< [TIMEOUT_REG]
// pec/reg00015.H

//>>THE END<<

#ifndef __PPE_HCODE__
}
}
#include "pec/reg00015.H"
#endif
#endif


text:
angular.module('gta.services', []).factory('LoginData', function () {
  return {
    status: false,
    user: {
      username: "anonymous"
    },
    dsUser: null,
    dsCoords: null,
    friendPositions: []
  };
}).factory('LoginPromise', function ($q) {
  return $q.defer();
}).factory('CurrentFriendSubs', function () {
  return [];
});