text:
module ActiveRecord
  module ConnectionAdapters
    module OracleEnhanced
      class SchemaCreation < AbstractAdapter::SchemaCreation
        private

        def visit_ColumnDefinition(o)
          case
            when o.type.to_sym == :virtual
              sql_type = type_to_sql(o.default[:type], o.limit, o.precision, o.scale) if o.default[:type]
              return "#{quote_column_name(o.name)} #{sql_type} AS (#{o.default[:as]})"
            when [:blob, :clob].include?(sql_type = type_to_sql(o.type.to_sym,  o.limit, o.precision, o.scale).downcase.to_sym)
              if (tablespace = default_tablespace_for(sql_type))
                @lob_tablespaces ||= {}
                @lob_tablespaces[o.name] = tablespace
              end
          end
          super
        end

        def visit_TableDefinition(o)
          create_sql = "CREATE#{' GLOBAL TEMPORARY' if o.temporary} TABLE "
          create_sql << "#{quote_table_name(o.name)} ("
          create_sql << o.columns.map { |c| accept c }.join(', ')
          create_sql << ")"

          unless o.temporary
            @lob_tablespaces.each do |lob_column, tablespace|
              create_sql << " LOB (#{quote_column_name(lob_column)}) STORE AS (TABLESPACE #{tablespace}) \n"
            end if defined?(@lob_tablespaces)
            create_sql << " ORGANIZATION #{o.options[:organization]}" if o.options[:organization]
            if (tablespace = o.options[:tablespace] || default_tablespace_for(:table))
              create_sql << " TABLESPACE #{tablespace}"
            end
          end
          create_sql << " #{o.options[:options]}"
          create_sql
        end

        def default_tablespace_for(type)
          (ActiveRecord::ConnectionAdapters::OracleEnhancedAdapter.default_tablespaces[type] ||
           ActiveRecord::ConnectionAdapters::OracleEnhancedAdapter.default_tablespaces[native_database_types[type][:name]]) rescue nil
        end

        def add_column_options!(sql, options)
          type = options[:type] || ((column = options[:column]) && column.type)
          type = type && type.to_sym
          # handle case of defaults for CLOB columns, which would otherwise get "quoted" incorrectly
          if options_include_default?(options)
            if type == :text
              sql << " DEFAULT #{@conn.quote(options[:default])}"
            else
              sql << " DEFAULT #{quote_value(options[:default], options[:column])}"
            end
          end
          # must explicitly add NULL or NOT NULL to allow change_column to work on migrations
          if options[:null] == false
            sql << " NOT NULL"
          elsif options[:null] == true
            sql << " NULL" unless type == :primary_key
          end
          # add AS expression for virtual columns
          if options[:as].present?
            sql << " AS (#{options[:as]})"
          end
        end

        def action_sql(action, dependency)
          if action == 'UPDATE'
            raise ArgumentError, <<-MSG.strip_heredoc
              '#{action}' is not supported by Oracle
            MSG
          end
          case dependency
          when :nullify then "ON #{action} SET NULL"
          when :cascade  then "ON #{action} CASCADE"
          else
            raise ArgumentError, <<-MSG.strip_heredoc
              '#{dependency}' is not supported for #{action}
              Supported values are: :nullify, :cascade
            MSG
          end
        end

      end
    end
  end
end


text:
package com.google.devtools.kythe.extractors.shared;

import com.google.common.collect.Sets;
import com.google.devtools.kythe.proto.Analysis.CompilationUnit;
import com.google.devtools.kythe.proto.Analysis.FileData;

import java.util.Objects;

/**
 * Contains all data to completely describe a compilation.  Includes compilation
 * metadata and all required input files.
 */
public class CompilationDescription {
  private final CompilationUnit compilationUnit;
  private final Iterable<FileData> fileContents;

  public CompilationDescription(CompilationUnit compilationUnit, Iterable<FileData> fileContents) {
    this.compilationUnit = compilationUnit;
    this.fileContents = fileContents;
  }

  public CompilationUnit getCompilationUnit() {
    return compilationUnit;
  }

  public Iterable<FileData> getFileContents() {
    return this.fileContents;
  }

  @Override
  public int hashCode() {
    return Objects.hash(compilationUnit);
  }

  @Override
  public boolean equals(Object o) {
    if (o == this) {
      return true;
    } else if (o instanceof CompilationDescription) {
      CompilationDescription oDesc = (CompilationDescription) o;
      return Objects.equals(this.compilationUnit, oDesc.compilationUnit) &&
          Sets.newHashSet(this.fileContents).equals(Sets.newHashSet(oDesc.fileContents));
    }
    return false;
  }
}

redpajama_set_name: RedPajamaGithub


text:
const assert = require('assert')
const supertest = require('supertest')
const createApp = require('../app')
const { createSetup, getAuthPassword } = require('./lib')

describe('/api/logout', () => {
  let setup
  let request

  beforeAll(async () => {
    setup = await createSetup()
    const app = await createApp({ ...setup, disableUI: true })

    request = supertest(app.callback())
  }, 20000)

  afterAll(async () => {
    await setup.teardown()
  }, 20000)

  test('should not error if not logged in', async () => {
    const { statusCode } = await request
      .post('/api/logout')
      .set('Accept', 'application/json')

    assert.strictEqual(statusCode, 204)
  })

  test('should logout', async () => {
    const cookie = await getAuthPassword(request, 'admin@banmanagement.com')
    const { statusCode } = await request
      .post('/api/logout')
      .set('Cookie', cookie)
      .expect('Set-Cookie', /bm-webui-sess/)
      .set('Accept', 'application/json')

    assert.strictEqual(statusCode, 204)
  })
})


text:
package org.apache.stratos.cloud.controller.domain;

import org.apache.stratos.common.Properties;

public class ApplicationClusterContext {

    // cluster id
    private String clusterId;
    // cartridge type
    private String cartridgeUuid;
    // payload as a String
    private String textPayload;
    // host name
    private String hostName;
    // flag to indicate LB cluster
    private boolean isLbCluster;
    // autoscaling policy
    private String autoscalePolicyName;
    // deployment policy
    private String deploymentPolicyName;
    // tenant rance
    private String tenantRange;
    // properties
    private Properties properties;
    //dependencyclusterid
    private String[] dependencyClusterIds;

    private boolean isVolumeRequired;

    private Volume[] volumes;

    public ApplicationClusterContext() {
    }

    public String getClusterId() {
        return clusterId;
    }

    public void setClusterId(String clusterId) {
        this.clusterId = clusterId;
    }

    public String getCartridgeUuid() {
        return cartridgeUuid;
    }

    public void setCartridgeUuid(String cartridgeUuid) {
        this.cartridgeUuid = cartridgeUuid;
    }

    public String getTextPayload() {
        return textPayload;
    }

    public void setTextPayload(String textPayload) {
        this.textPayload = textPayload;
    }

    public String getHostName() {
        return hostName;
    }

    public void setHostName(String hostName) {
        this.hostName = hostName;
    }

    public boolean isLbCluster() {
        return isLbCluster;
    }

    public void setLbCluster(boolean lbCluster) {
        isLbCluster = lbCluster;
    }

    public String getAutoscalePolicyName() {
        return autoscalePolicyName;
    }

    public void setAutoscalePolicyName(String autoscalePolicyName) {
        this.autoscalePolicyName = autoscalePolicyName;
    }

    public String getDeploymentPolicyName() {
        return deploymentPolicyName;
    }

    public void setDeploymentPolicyName(String deploymentPolicyName) {
        this.deploymentPolicyName = deploymentPolicyName;
    }

    public String getTenantRange() {
        return tenantRange;
    }

    public void setTenantRange(String tenantRange) {
        this.tenantRange = tenantRange;
    }

    public boolean equals(Object other) {

        if (other == null || !(other instanceof ApplicationClusterContext)) {
            return false;
        }

        if (this == other) {
            return true;
        }

        ApplicationClusterContext that = (ApplicationClusterContext) other;

        return this.cartridgeUuid.equals(that.cartridgeUuid) &&
                this.clusterId.equals(that.clusterId);
    }

    public int hashCode() {
        return this.cartridgeUuid.hashCode() + this.clusterId.hashCode();
    }

    public Properties getProperties() {
        return properties;
    }

    public void setProperties(Properties properties) {
        this.properties = properties;
    }

    public String[] getDependencyClusterIds() {
        return dependencyClusterIds;
    }

    public void setDependencyClusterIds(String[] dependencyClusterIds) {
        this.dependencyClusterIds = dependencyClusterIds;
    }

    public boolean isVolumeRequired() {
        return isVolumeRequired;
    }

    public void setVolumeRequired(boolean isVolumeRequired) {
        this.isVolumeRequired = isVolumeRequired;
    }

    public Volume[] getVolumes() {
        return volumes;
    }

    public void setVolumes(Volume[] volumes) {
        this.volumes = volumes;
    }

}


text:
<?
defined('C5_EXECUTE') or die("Access Denied.");
use \Concrete\Core\Permission\Access\Entity\FileUploaderEntity as FileUploaderPermissionAccessEntity;
if (Loader::helper('validation/token')->validate('process')) {

	$js = Loader::helper('json');
	$obj = new stdClass;
	$pae = FileUploaderPermissionAccessEntity::getOrCreate();
	$obj->peID = $pae->getAccessEntityID();
	$obj->label = $pae->getAccessEntityLabel();
	print $js->encode($obj);

}


text:
require 'net/http'
require 'uri'
require 'json'

# Query Splunk with arbitrary search criteria

module NagiosHerald
  module Helpers
    class SplunkQuery
      #include NagiosHerald::Logging

      # Public: Initialize a new SplunkQuery object.
      #
      # query - A string representing the query to send to Splunk.
      # index - Optional index to specify (else Splunk defaults to all indexes
      #   available to the authenticated user).
      # output - The output format we'd like (i.e. csv, json, xml); defaults
      #   to json.
      #
      # Example:
      #
      # splunk_query = NagiosHerald::Helpers::SplunkQuery.new('sourcetype=perf_log page=index.html')
      # splunk_query = NagiosHerald::Helpers::SplunkQuery.new('transaction_state=paid', {:index => 'get_paid'})
      # splunk_query = NagiosHerald::Helpers::SplunkQuery.new('source=nagios-herald.log alert_type=host', {:output => 'csv'})
      #
      # Returns a new SplunkQuery object.
      def initialize(query, options={})
        @splunk_query = query
        @splunk_index = options[:index] ? options[:index] : nil
        @splunk_output = options[:output] ? options[:output] : 'json'

        # Pull the Splunk URI, username, and password from the config.
        splunk_url = Config.config['splunk']['url']
        @splunk_username = Config.config['splunk']['username']
        @splunk_password = Config.config['splunk']['password']

        # Parse the URI.
        uri = URI.parse(splunk_url)
        @splunk_host = uri.host
        @splunk_port = uri.port
        @splunk_uri  = uri.request_uri
      end

      # Public: Generate the parameters for the Splunk query.
      #
      # Example:
      #
      # parameters = splunk_query.parameters
      #
      # Returns the Splunk query parameters.
      def parameters
        # Earliest time we should look for events; defaults to 7 days ago.
        earliest_time = Config.config['splunk']['earliest_time'] ?
          Config.config['splunk']['earliest_time'] :
          '7d'

        # Latest time we should look for events; defaults to now.
        latest_time = Config.config['splunk']['latest_time'] ?
          Config.config['splunk']['latest_time'] :
          'now'

        # Maximum results returned; defaults to 100.
        max_results = Config.config['splunk']['max_results'] ?
          Config.config['splunk']['max_results'] :
          100

        params = {
            'exec_mode'     => 'oneshot',
            'earliest_time' => "-#{earliest_time}",
            'latest_time'   => latest_time,
            'output_mode'   => @splunk_output,
            'count'         => max_results
        }
        if @splunk_index.nil?
          params['search'] = "search #{@splunk_query}"
        else
          params['search'] = "search index=#{@splunk_index} " + @splunk_query
        end

        params
      end

      # Public: Queries Splunk.
      #
      # Example:
      #
      # results = splunk_query.query
      #
      # Returns the results of the query in the requested format, nil otherwise.
      def query
        http = Net::HTTP.new( @splunk_host, @splunk_port )
        http.use_ssl = true
        http.open_timeout = 1
        http.read_timeout = 2
        http.ssl_timeout = 1
        http.verify_mode = OpenSSL::SSL::VERIFY_NONE    # don't validate the cert
        request = Net::HTTP::Post.new( @splunk_uri )
        request.basic_auth( @splunk_username, @splunk_password )
        request.set_form_data( parameters )
        begin
          response = http.request( request )
        rescue Exception => e
          logger.warn "Failed to send request: #{e.message}"
          return nil
        end

        if response.code.eql?( "200" )
          response.body
        else
          logger.warn "Splunk query failed with HTTP #{response.code}: #{response.message}"
          logger.warn response.body
          return nil
        end
      end

    end
  end
end


text:
Author(s):
Uri Laserson, Tom White

Eggo is several things:

* a repository of commonly-used public genomics data sets that are pre-
  converted into Parquet data using the BDG (and possibly GA4GH) schemas.
* a user-oriented Python API to make it easy to work with public genomics data
  sets in a Hadoop environment
* an administrator-oriented API for generating/managing the Parquet cloud data
  repository

Eggo is primarily a Python package leveraging Fabric to work with provisioned
clusters and Luigi to define ETL tasks.

Eggo wants to help enable functionality like that provided in PLINK/SEQ,
SolveBio, etc. by alleviating the need for each project to re-process the same
data sets in possibly incompatible ways.

Most users will interact with Eggo simply by reading the datasets that are
hosted in its repository. However, we'd also like to foster dataset curation by
the community. Admins would issue a pull request to the Eggo GitHub repository
with relevant changes to add a new dataset, then an Eggo maintainer would
review and commit the change before running an update to add the new dataset to
the central Eggo repository. Advanced admins would also be able to maintain
their own Eggo repositories of datasets, although in general we'd prefer to add
everything to the central Eggo repository.

## Target data sets for ingestion

* BAM files
  * NA12878 pedigree
* VCF files
  * 1000 Genomes
  * ExAC
  * TCGA MAF
* Features/Annotations
  * ENCODE
* Other
  * dbSNP
  * COSMIC

## Data set ingestion

### Eggo S3 directory structure

    s3://bdg-eggo/<dataset-name>/<format>/<edition>

`<dataset-name>` must be globally unique in the registry.  Different
versions/releases of the data sets should be considered to be different data
sets in eggo (i.e., eggo doesn't explicitly support releases/versions of the
biological data sets; this may change in the future).

`<format>` will in principle support multiple formats/schemas.  At the moment,
we are only supporting the BDG schema, but we would like to support GA4GH as
well, and will track adding GA4GH support in ADAM.

`<edition>` refers to the specific instance of the ETL'd data, according to the
particular options that are set.  The registry JSON object will include a list
of "editions" that should be generated, specifying whether the data is
partitioned or flattened.  The possible values are:

* `basic`: no additional processing

* `flat`: the data is run through the ADAM flattener

* `locuspart`: the data is locus-partitioned (in the style of Hive partitions)

* `flat_locuspart`: both flattened and locus-partitioned

Some example S3 keys are:

    1kg-genotypes/bdg/basic
    1kg-genotypes/bdg/flat
    1kg-genotypes/bdg/flat_locuspart
    1kg-genotypes/ga4gh/basic

Temporary data during processing may be placed in the following location:

    s3://bdg-eggo/tmp

An S3 bucket for testing purposes/experimentation is

    s3://bdg-eggo-test

### Data partitioning

Currently, the data partitioning scheme that is planned to be supported is by
genome locus.  The specific details of how that will be done are TBD, however
it will likely be by chromosome and position (modulo 1e6 or 1e7, TBD). For
example, records for positions in the range `[4e6, 5e6)` would live in
the `/chr=1/pos=4` partition.

For datasets with many samples, the data may be further partitioned by sample
(hash of ID, or by date). However, this is not expected for any of the public
datasets at this point.

### Data flattening

Not all execution engines (e.g., Impala) can read/process nested data.
Therefore, eggo also offers versions of all data sets that are flattened with
the CLI `flatten` command.  Eggo also makes use of the Cloudera Kite project to
easily register the data sets with the Hive Metastore, for access through
Impala, Hive, SparkSQL, and other similar tools (TODO: @tomwhite).

## Eggo "user" API

### Configuration

Todo.

### Cluster Management

See admin API.

### Data set exploration

Todo.

Include Impala Python integration and Impala DDL.  Consider using Kite for Hive
Metastore registration

* `eggo list`

    Describe all available data sets

* `eggo info DATASET`

    Return metadata on DATASET

* `eggo get DATASET`

    Copy DATASET from S3 to "local" Hadoop cluster

* `eggo register DATASET`

    Register DATASET with the Hive metastore

## Eggo "admin/developer" API

Unfinished.

There should be a bucket (`s3://bdg-eggo-test`) that supports regular
integration tests from a test registry that includees small data sets.  There
should also be a hook to specify experimental runs that work off a specific
github fork/branch.

We should implement dry run support so the user can see all the things that
will happen.  May be difficult because it's not clear whether Fabric or Luigi
support dry run options.

### `registry/`

The `registry/` directory contains the metadata for the data sets we ingest and
convert to ADAM/Parquet.  Each data set is stored as a JSON file loosely based
on the Data Protocols spec.

### Environment variables

If using AWS, eggo will assume the following variables are set **locally**:

```bash
export SPARK_HOME= # local path to Spark
export EC2_KEY_PAIR= # EC2 name of the registered key pair
export EC2_PRIVATE_KEY_FILE= # local path to associated private key (.pem file)
export AWS_ACCESS_KEY_ID= # AWS credentials
export AWS_SECRET_ACCESS_KEY= # AWS credentials
```

Eggo will assume the following variables are set **remotely**

```bash
export AWS_ACCESS_KEY_ID= # AWS credentials
export AWS_SECRET_ACCESS_KEY= # AWS credentials
export SPARK_HOME= # remote path to Spark
export ADAM_HOME= # remote path to ADAM
export SPARK_MASTER= # Spark master host name
```

which can be done by executing

```bash
source path/to/eggo/eggo-ec2-variables.sh
```

on the remote machines.

### Desired API

**Cluster utilities**

* `eggo provision -s 3`

    Provision a cluster with 3 worker nodes on EC2.

* `eggo setup_master`/`eggo setup_slaves`

    Configure the master (driver) or slave (worker) nodes on EC2 with necessary
    prerequisites, including ADAM.

* `eggo login`

    Login to provisioned EC2 cluster.

* `eggo teardown`

    Destroy the provisioned EC2 cluster.

**Data conversion**

* `eggo toast DATASET`

    Run full pipeline on the specified dataset. There must exist a file called
    `registry/DATASET.json`.

## Examples of supported queries

Todo.

1000 genomes tutorials. It would be instructive to convert a 1000 genomes
tutorial to a BDG equivalent (such as this one [questions][questions], [answers][answers]). This
exercise would help flush out issues in the BDG datasets and tools, as well as
demonstrating a performance boost.

[questions]: ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/working/20120229_tutorial_docs/G1K_commandline_based_tutorial_exercises_20120217.pdf
[answers]: ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/working/20120229_tutorial_docs/G1K_commandline_based_tutorial_answers_20120217.txt


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _AST2 = require('./AST');

var _AST3 = _interopRequireDefault(_AST2);

var _CellIdentifier = require('./CellIdentifier');

var _CellIdentifier2 = _interopRequireDefault(_CellIdentifier);

var _Range = require('./../Range');

var _Range2 = _interopRequireDefault(_Range);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

/**
 * Range reference.
 *
 * @extends AST
 */
var RangeReference = function (_AST) {
    _inherits(RangeReference, _AST);

    /**
     * Create a Cell identifier object.
     * @param {Token} [token] - Range token.
     * @param {string} [sheet] - Sheet name.
     */
    function RangeReference(token) {
        var sheet = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;

        _classCallCheck(this, RangeReference);

        var _this = _possibleConstructorReturn(this, (RangeReference.__proto__ || Object.getPrototypeOf(RangeReference)).call(this));

        _this.token = token;
        _this.rangeValue = token.value;
        _this.sheet = sheet;
        return _this;
    }

    /**
     * Get Range pair
     * @return {array} Two CellIdentifier
     */

    _createClass(RangeReference, [{
        key: 'pair',
        value: function pair() {
            var pairs = this.rangeValue.split(':');

            return [new _CellIdentifier2.default(pairs[0]), new _CellIdentifier2.default(pairs[1])];
        }

        /**
         * Get range information
         * @return {Range} Range object
         */

    }, {
        key: 'range',
        value: function range() {
            var pairs = this.pair();

            return new _Range2.default(pairs[0].position(), pairs[1].position());
        }
    }]);

    return RangeReference;
}(_AST3.default);

RangeReference.displayName = 'RangeReference';
exports.default = RangeReference;


text:
package goryachev.common.util;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

public final class CRandom
{
	public static final String RAND_ALGORITHM = "SHA1PRNG";
	private static SecureRandom random = init();

	private static SecureRandom init()
	{
		try
		{
			return SecureRandom.getInstance(RAND_ALGORITHM);
		}
		catch(NoSuchAlgorithmException e)
		{
			// should not happen
			Log.ex(e);
			throw new Error(e);
		}
	}

	public static byte[] generateBits(int bits)
	{
		byte[] b = new byte[bits >>> 3];
		synchronized(random)
		{
			random.nextBytes(b);
		}
		return b;
	}

	public static String generateHexBits(int bits)
	{
		byte[] b = generateBits(bits);
		return Hex.toHexString(b);
	}

	public static long nextLong()
	{
		synchronized(random)
		{
			return random.nextLong();
		}
	}
}


text:
'use strict';

const Command = require('cmnd').Command;
const colors = require('colors/safe');

class VersionCommand extends Command {

  constructor() {

    super('version');

  }

  help() {

    return {
      description: 'Shows your currently globally installed Nodal version'
    };

  }

  run(params, callback) {

    let version = require('../../package.json').version;
    console.log(colors.green.bold('Nodal Version: ') + version);

    callback(null);

  }

}

module.exports = VersionCommand;


text:
#include <aws/chime/model/CreateSipMediaApplicationRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Chime::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

CreateSipMediaApplicationRequest::CreateSipMediaApplicationRequest() :
    m_awsRegionHasBeenSet(false),
    m_nameHasBeenSet(false),
    m_endpointsHasBeenSet(false)
{
}

Aws::String CreateSipMediaApplicationRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_awsRegionHasBeenSet)
  {
   payload.WithString("AwsRegion", m_awsRegion);

  }

  if(m_nameHasBeenSet)
  {
   payload.WithString("Name", m_name);

  }

  if(m_endpointsHasBeenSet)
  {
   Array<JsonValue> endpointsJsonList(m_endpoints.size());
   for(unsigned endpointsIndex = 0; endpointsIndex < endpointsJsonList.GetLength(); ++endpointsIndex)
   {
     endpointsJsonList[endpointsIndex].AsObject(m_endpoints[endpointsIndex].Jsonize());
   }
   payload.WithArray("Endpoints", std::move(endpointsJsonList));

  }

  return payload.View().WriteReadable();
}


text:
import { DateUtils } from '../../../libs/utils';

const newArray = function (start, end) {
  let result = [];
  for (let i = start; i <= end; i++) {
    result.push(i);
  }
  return result;
};

export const toDate = function (date) {
  date = new Date(date);
  if (isNaN(date.getTime())) return null;
  return date;
};

export const formatDate = function (date, format) {
  date = toDate(date);
  if (!date) return '';
  return DateUtils.format(date, format || 'yyyy-MM-dd');
};

export const parseDate = function (string, format) {
  return DateUtils.parse(string, format || 'yyyy-MM-dd');
};

export const getDayCountOfMonth = function (year, month) {
  if (month === 3 || month === 5 || month === 8 || month === 10) {
    return 30;
  }

  if (month === 1) {
    if (year % 4 === 0 && year % 100 !== 0 || year % 400 === 0) {
      return 29;
    } else {
      return 28;
    }
  }

  return 31;
};

export const getFirstDayOfMonth = function (date) {
  const temp = new Date(date.getTime());
  temp.setDate(1);
  return temp.getDay();
};

export const DAY_DURATION = 86400000;

export const getStartDateOfMonth = function (year, month) {
  const result = new Date(year, month, 1);
  const day = result.getDay();

  if (day === 0) {
    result.setTime(result.getTime() - DAY_DURATION * 7);
  } else {
    result.setTime(result.getTime() - DAY_DURATION * day);
  }

  return result;
};

export const getWeekNumber = function (src) {
  const date = new Date(src.getTime());
  date.setHours(0, 0, 0, 0);
  // Thursday in current week decides the year.
  date.setDate(date.getDate() + 3 - (date.getDay() + 6) % 7);
  // January 4 is always in week 1.
  const week1 = new Date(date.getFullYear(), 0, 4);
  // Adjust to Thursday in week 1 and count number of weeks from date to week 1.
  return 1 + Math.round(((date.getTime() - week1.getTime()) / 86400000 - 3 + (week1.getDay() + 6) % 7) / 7);
};

// http://stackoverflow.com/questions/16590500/javascript-calculate-date-from-week-number
export function getDateOfISOWeek(w, y) {
    var simple = new Date(y, 0, 1 + (w - 1) * 7);
    var dow = simple.getDay();
    var ISOweekStart = simple;
    if (dow <= 4)
        ISOweekStart.setDate(simple.getDate() - simple.getDay() + 1);
    else
        ISOweekStart.setDate(simple.getDate() + 8 - simple.getDay());
    return ISOweekStart;
}

export const prevMonth = function (src) {
  const year = src.getFullYear();
  const month = src.getMonth();
  const date = src.getDate();

  const newYear = month === 0 ? year - 1 : year;
  const newMonth = month === 0 ? 11 : month - 1;

  const newMonthDayCount = getDayCountOfMonth(newYear, newMonth);
  if (newMonthDayCount < date) {
    src.setDate(newMonthDayCount);
  }

  src.setMonth(newMonth);
  src.setFullYear(newYear);

  return new Date(src.getTime());
};

export const nextMonth = function (src) {
  const year = src.getFullYear();
  const month = src.getMonth();
  const date = src.getDate();

  const newYear = month === 11 ? year + 1 : year;
  const newMonth = month === 11 ? 0 : month + 1;

  const newMonthDayCount = getDayCountOfMonth(newYear, newMonth);
  if (newMonthDayCount < date) {
    src.setDate(newMonthDayCount);
  }

  src.setMonth(newMonth);
  src.setFullYear(newYear);

  return new Date(src.getTime());
};

export const getRangeHours = function (ranges) {
  const hours = [];
  let disabledHours = [];

  (ranges || []).forEach(range => {
    const value = range.map(date => date.getHours());

    disabledHours = disabledHours.concat(newArray(value[0], value[1]));
  });

  if (disabledHours.length) {
    for (let i = 0; i < 24; i++) {
      hours[i] = disabledHours.indexOf(i) === -1;
    }
  } else {
    for (let i = 0; i < 24; i++) {
      hours[i] = false;
    }
  }

  return hours;
};

export const limitRange = function (date, ranges) {
  if (!ranges || !ranges.length) return date;

  const len = ranges.length;
  const format = 'HH:mm:ss';

  date = DateUtils.parse(DateUtils.format(date, format), format);
  for (let i = 0; i < len; i++) {
    const range = ranges[i];
    if (date >= range[0] && date <= range[1]) {
      return date;
    }
  }

  let maxDate = ranges[0][0];
  let minDate = ranges[0][0];

  ranges.forEach(range => {
    minDate = new Date(Math.min(range[0], minDate));
    maxDate = new Date(Math.max(range[1], maxDate));
  });

  return date < minDate ? minDate : maxDate;
};

export function hasClass(target, classname) {
  return target.classList.contains(classname)
}

export const SELECTION_MODES = {
  YEAR: 'year',
  MONTH: 'month',
  WEEK: 'week',
  DAY: 'day',
  RANGE: 'range'
}

export function deconstructDate(date) {
  return {
    year: date.getFullYear(),
    month: date.getMonth(),
    week: getWeekNumber(date)
  }
}


text:
package org.elasticsearch.index.mapper;

import com.google.common.collect.ImmutableMap;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.index.analysis.AnalysisService;

import java.io.IOException;
import java.util.Map;

/**
 *
 */
public interface Mapper extends ToXContent {

    public static final Mapper[] EMPTY_ARRAY = new Mapper[0];

    public static class BuilderContext {
        private final Settings indexSettings;
        private final ContentPath contentPath;

        public BuilderContext(@Nullable Settings indexSettings, ContentPath contentPath) {
            this.contentPath = contentPath;
            this.indexSettings = indexSettings;
        }

        public ContentPath path() {
            return this.contentPath;
        }

        @Nullable
        public Settings indexSettings() {
            return this.indexSettings;
        }
    }

    public static abstract class Builder<T extends Builder, Y extends Mapper> {

        public String name;

        protected T builder;

        protected Builder(String name) {
            this.name = name;
        }

        public String name() {
            return this.name;
        }

        public abstract Y build(BuilderContext context);
    }

    public interface TypeParser {

        public static class ParserContext {

            private final AnalysisService analysisService;

            private final ImmutableMap<String, TypeParser> typeParsers;

            public ParserContext(AnalysisService analysisService, ImmutableMap<String, TypeParser> typeParsers) {
                this.analysisService = analysisService;
                this.typeParsers = typeParsers;
            }

            public AnalysisService analysisService() {
                return analysisService;
            }

            public TypeParser typeParser(String type) {
                return typeParsers.get(Strings.toUnderscoreCase(type));
            }
        }

        Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException;
    }

    String name();

    void parse(ParseContext context) throws IOException;

    void merge(Mapper mergeWith, MergeContext mergeContext) throws MergeMappingException;

    void traverse(FieldMapperListener fieldMapperListener);

    void traverse(ObjectMapperListener objectMapperListener);

    void close();
}


text:
<!DOCTYPE frameset SYSTEM "frameset.dtd">
<frameset>
    <predicate lemma="encounter">
        <note>
            Frames file for 'encounter' based on survey of sentences in the WSJ
            corpus.
        </note>

        <roleset id="encounter.01" name="to meet unexpectedly" vncls="-">
            <roles>
                <role descr="entity encountering something" n="0"/>
                <role descr="entity encountered " n="1"/>
            </roles>

            <example name="transitive with adverbials">
                <inflection aspect="ns" form="full" person="ns" tense="present" voice="active"/>
                <text>
                    In a meeting with Premier Li Peng on Monday , Mr. Nixon said that he hoped [0] he would n't encounter guards with machine guns during his visit to the U.S. Embassy .
                </text>
                <arg n="0">he</arg>
                <arg f="MOD" n="M">would</arg>
                <arg f="NEG" n="M">n't</arg>
                <rel>encounter</rel>
                <arg n="1">guards with machine guns</arg>
                <arg f="TMP" n="M">during his visit to the U.S. Embassy</arg>
            </example>

        </roleset>
    </predicate>

    <note>
        frames created by Olga
    </note>

</frameset>


text:
set -e

# Zip-file name
tag=`git describe --abbrev=0`
filename_tag=`echo $tag | tr . -`

# Where to place the installation bundle
DIR_NAME="IncludeOS_install"

[ -z $INSTALL_DIR ] && INSTALL_DIR=$HOME/$DIR_NAME
[ -z $BUILD_DIR ] && BUILD_DIR=$HOME/IncludeOS_build
[ -z $TEMP_INSTALL_DIR ] && TEMP_INSTALL_DIR=$BUILD_DIR/IncludeOS_TEMP_install

echo ">>> Creating Installation Bundle as $INSTALL_DIR"

OUTFILE="$DIR_NAME_$filename_tag.tar.gz"

newlib=$TEMP_INSTALL_DIR/i686-elf/lib
llvm=$BUILD_DIR/build_llvm

# Libraries
libc=$newlib/libc.a
libm=$newlib/libm.a
libg=$newlib/libg.a
libcpp=$llvm/lib/libc++.a

GPP=$TEMP_INSTALL_DIR/bin/i686-elf-g++
GCC_VER=`$GPP -dumpversion`
libgcc=$TEMP_INSTALL_DIR/lib/gcc/i686-elf/$GCC_VER/libgcc.a

# Includes
include_newlib=$TEMP_INSTALL_DIR/i686-elf/include
include_libcxx=$llvm/include/c++/v1

# Make directory-tree
mkdir -p $INSTALL_DIR
mkdir -p $INSTALL_DIR/newlib
mkdir -p $INSTALL_DIR/libcxx
mkdir -p $INSTALL_DIR/crt
mkdir -p $INSTALL_DIR/libgcc

# Copy binaries
cp $libcpp $INSTALL_DIR/libcxx/
cp $libm $INSTALL_DIR/newlib/
cp $libc $INSTALL_DIR/newlib/
cp $libg $INSTALL_DIR/newlib/
cp $libgcc $INSTALL_DIR/libgcc/
cp $TEMP_INSTALL_DIR/lib/gcc/i686-elf/$GCC_VER/crt*.o $INSTALL_DIR/crt/

# Copy includes
cp -r $include_newlib $INSTALL_DIR/newlib/
cp -r $include_libcxx $INSTALL_DIR/libcxx/include

# Zip it
tar -czvf $OUTFILE --directory=$INSTALL_DIR/../ $DIR_NAME

echo ">>> IncludeOS Installation Bundle created as $INSTALL_DIR and gzipped into $OUTFILE"


text:
<?php namespace Lecturize\Taxonomies\Models;

use Exception;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection as EloquentCollection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphToMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Collection;

/**
 * Class Taxonomy
 * @package Lecturize\Taxonomies\Models
 * @property int                 $id
 * @property string|null         $parent_id
 * @property Taxonomy|null       $parent
 * @property EloquentCollection  $children
 * @property EloquentCollection  $siblings
 * @property EloquentCollection  $taxables
 * @property string|null         $alias_id
 * @property Taxonomy|null       $alias
 * @property string              $term_id
 * @property Term                $term
 * @property string              $taxonomy
 * @property string|null         $description
 * @property string|null         $content
 * @property string|null         $lead
 * @property int|null            $sort
 * @property array|null          $properties
 */
class Taxonomy extends Model
{
    use SoftDeletes;

    /** @inheritdoc */
    protected $fillable = [
        'parent_id',
        'alias_id',
        'term_id',
        'taxonomy',

        'description',
        'content',
        'lead',

        'sort',

        'properties',
    ];

    /** @inheritdoc */
    protected $casts = [
        'properties' => 'array',
    ];

    /** @inheritdoc */
    protected $dates = [
        'deleted_at',
    ];

    /** @inheritdoc */
    protected $with = [
        'term',
    ];

    /** @inheritdoc */
    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);

        $this->table = config('lecturize.taxonomies.taxonomies.table', 'taxonomies');
    }

    /** @inheritdoc */
    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            if ($model->getConnection()
                      ->getSchemaBuilder()
                      ->hasColumn($model->getTable(), 'uuid'))
                $model->uuid = \Webpatser\Uuid\Uuid::generate()->string;
        });

        static::saving(function ($model) {
            if (isset($model->term) && $model->term->title && ! $model->description)
                $model->description = $model->term->title;

            if (! $model->sort) {
                $sort = ($siblings = $model->siblings()->get()) ? $siblings->max('sort') : 0;
                $model->sort = ($sort + 1);
            }
        });
    }

    /**
     * Get the term, that will be displayed as this taxonomies (categories) title.
     *
     * @return BelongsTo
     */
    public function term() {
        return $this->belongsTo(config('lecturize.taxonomies.terms.model', Term::class));
    }

    /**
     * Get the parent taxonomy (categories).
     *
     * @return BelongsTo
     */
    public function parent(): BelongsTo
    {
        return $this->belongsTo(config('lecturize.taxonomies.taxonomies.model', Taxonomy::class), 'parent_id');
    }

    /**
     * Get the children taxonomies (categories).
     *
     * @return HasMany
     */
    public function children(): HasMany
    {
        return $this->hasMany(config('lecturize.taxonomies.taxonomies.model', Taxonomy::class), 'parent_id');
    }

    /**
     * Get the children taxonomies (categories).
     *
     * @return Builder
     */
    public function siblings(): Builder
    {
        $class = config('lecturize.taxonomies.taxonomies.model', Taxonomy::class);
        return (new $class)->taxonomy($this->taxonomy)
                           ->where('parent_id', $this->parent_id)
                           ->orderBy('sort');
    }

    /**
     * Get the parent taxonomy (categories).
     *
     * @return BelongsTo
     */
    public function alias(): BelongsTo
    {
        return $this->belongsTo(config('lecturize.taxonomies.taxonomies.model', Taxonomy::class), 'alias_id');
    }

    /**
     * Return the related items.
     *
     * @return HasMany
     */
    public function taxables(): HasMany
    {
        return $this->hasMany(Taxable::class, 'taxonomy_id');
    }

    /**
     * An example for related posts.
     *
     * @return MorphToMany
     */
    public function posts(): MorphToMany
    {
        return $this->morphedByMany(config('lecturize.community.posts.model', 'App\Models\Posts\Post'), 'taxable', 'taxables');
    }

    /**
     * An example for related products.
     *
     * @return MorphToMany
     */
    public function products(): MorphToMany
    {
        return $this->morphedByMany(config('lecturize.shop.products.model', 'Lecturize\Shop\Products\Product'), 'taxable', 'taxables');
    }

    /**
     * Get the breadcrumbs for this Taxonomy.
     *
     * @param  bool  $exclude_self
     * @return Collection
     * @throws Exception
     */
    public function getBreadcrumbs(bool $exclude_self = true): Collection
    {
        $key = "taxonomies.{$this->id}.breadcrumbs";
        $key.= $exclude_self ? '.self-excluded' : '';

        return cache()->remember($key, now()->addMonth(), function() use($exclude_self) {
            $parameters = $this->getParentBreadcrumbs();

            if (! $exclude_self)
                $parameters->push($this->taxonomy);

            return $parameters->reverse()->values();
        });
    }

    /**
     * Add parent breadcrumb.
     *
     * @param  Collection|null  $parameters
     * @return Collection
     * @throws Exception
     */
    function getParentBreadcrumbs(?Collection $parameters = null): Collection
    {
        if ($parameters === null)
            $parameters = collect();

        $parameters->push([
            'title'  => $this->term->title,
            'slug'   => $this->term->slug,
            'params' => $this->getRouteParameters(),
        ]);

        if ($parent = $this->parent)
            return $parent->getParentBreadcrumbs($parameters);

        return $parameters;
    }

    /**
     * Get route parameters.
     *
     * @param  bool  $exclude_taxonomy
     * @return array
     * @throws Exception
     */
    public function getRouteParameters(bool $exclude_taxonomy = true): array
    {
        $key = "taxonomies.{$this->id}.breadcrumbs";
        $key.= $exclude_taxonomy ? '.without-taxonomy' : '';

        return cache()->remember($key, now()->addMonth(), function() use($exclude_taxonomy) {
            $parameters = $this->getParentSlugs();

            if (! $exclude_taxonomy)
                array_push($parameters, $this->taxonomy);

            return array_reverse($parameters);
        });
    }

    /**
     * Get slugs of parent terms.
     *
     * @param  array  $parameters
     * @return array
     */
    function getParentSlugs(array $parameters = []): array
    {
        array_push($parameters, $this->term->slug);

        if ($parent = $this->parent)
            return $parent->getParentSlugs($parameters);

        return $parameters;
    }

    /**
     * Scope by a given taxonomy (e.g. "blog_cat" for blog posts or "shop_cat" for shop products).
     *
     * @param  Builder  $query
     * @param  string   $taxonomy
     * @return Builder
     */
    public function scopeTaxonomy(Builder $query, string $taxonomy): Builder
    {
        return $query->where('taxonomy', $taxonomy);
    }

    /**
     * Scope by a given taxonomy prefix (e.g. to retrieve both "shop_cat_a" and "shop_cat_b" you would scope "shop_cat%").
     *
     * @param  Builder  $query
     * @param  string   $taxonomy_prefix
     * @return Builder
     */
    public function scopeTaxonomyStartsWith(Builder $query, string $taxonomy_prefix): Builder
    {
        return $query->where('taxonomy', 'like', "$taxonomy_prefix%");
    }

    /**
     * Scope by given taxonomies array, e.g. ['shop_cat_a', 'shop_cat_b'].
     *
     * @param  Builder  $query
     * @param  array    $taxonomies
     * @return Builder
     */
    public function scopeTaxonomies(Builder $query, array $taxonomies): Builder
    {
        return $query->whereIn('taxonomy', $taxonomies);
    }

    /**
     * Scope terms (category title) by given taxonomy.
     *
     * @param  Builder     $query
     * @param  string|int  $term
     * @param  string      $term_field
     * @return Builder
     */
    public function scopeTerm(Builder $query, $term, string $term_field = 'title'): Builder
    {
        $term_field = ! in_array($term_field, ['id', 'title', 'slug']) ? 'title' : $term_field;

        return $query->whereHas('term', function(Builder $q) use($term, $term_field) {
            $q->where($term_field, $term);
        });
    }

    /**
     * A simple search scope.
     *
     * @param  Builder  $query
     * @param  string   $term
     * @param  string   $taxonomy
     * @return Builder
     */
    public function scopeSearch(Builder $query, string $term, string $taxonomy): Builder
    {
        return $query->whereHas('term', function(Builder $q) use($term, $taxonomy) {
            $q->where('title', 'like', '%'. $term .'%');
        });
    }
}


text:
from __future__ import division
from pylab import *
import utils
utils.backup(__file__)

from chartmann.plot_single import plot_results as plot_results_single
from chartmann.plot_cluster import (plot_results
                                    as plot_results_cluster)
from common.sources import NoSource
from common.experiments import AbstractExperiment
from common.sorn_stats import *

class Experiment_noinput(AbstractExperiment):
    def start(self):
        super(Experiment_noinput,self).start()
        c = self.params.c

        self.source = NoSource()

        stats_all = [
                     ActivityStat(),
                     ConnectionFractionStat(),
                     WeightHistoryStat('W_ee',record_every_nth=
                                                        c.N_steps/1000),
                     ParamTrackerStat()
                    ]
        stats_single =  [
                         PopulationVariance(),
                         ISIsStat(),
                         EndWeightStat(),
                         WeightChangeStat(),
                         WeightLifetimeStat(),
                    ]
        return (self.source,stats_all+stats_single,stats_all)

    def reset(self,sorn):
        super(Experiment_noinput,self).reset(sorn)
        c = self.params.c
        stats = sorn.stats # init sets sorn.stats to None
        sorn.__init__(c,self.source)
        sorn.stats = stats

    def run(self,sorn):
        super(Experiment_noinput,self).run(sorn)
        c = self.params.c

        sorn.simulation(c.N_steps)

        return {'source_plastic':self.source}

    def plot_single(self,path,filename):
        plot_results_single(path,filename)
    def plot_cluster(self,path,filename):
        plot_results_cluster(path,filename)


text:
#ifndef LocalTypes_H_
#define LocalTypes_H_

#include <string.h>
#include <errno.h>

#define PLUGIN_VERSION "1.0.1"

#define DEVICE_INFO_BUFF_SIZE (256)
#define DEVICE_INFO_ADDR_SIZE (18)

#define JSON_KEY_STATUS "status"
#define JSON_KEY_DESCRIPTION "desc"
#define JSON_KEY_ERROR_CODE "error_code"
#define JSON_KEY_SOURCE "source"
#define JSON_KEY_EVENT "event"
#define JSON_KEY_ADDRESS "address"
#define JSON_KEY_NAME "name"
#define JSON_KEY_DEVICES "devices"
#define JSON_KEY_DATA "data"
#define JSON_VALUE_ERROR "ERROR"
#define JSON_VALUE_OK "OK"
#define JSON_VALUE_THREAD "thread"
#define JSON_VALUE_FUNCTION "function"
#define JSON_VALUE_HR_DATA "HRDATA"
#define JSON_VALUE_CONNECTION "CONNECTION"
#define JSON_VALUE_DISCONNECTION "DISCONNECTION"

#define JSON_KEY_HR_DATA_FLAGS "flags"
#define JSON_KEY_HR_DATA_FORMAT_8 "hr_data_format_8"
#define JSON_KEY_HR_DATA_SENSOR_CONTACT_FEATURE_SUPPORTED "sensor_contact_feature_supported"
#define JSON_KEY_HR_DATA_SENSOR_ENERGY_EXPENDED_FEATURE_SUPPORTED "energy_expended_feature_supported"
#define JSON_KEY_HR_DATA_SENSOR_RR_INTERVAL_DATA_PRESENT "rr_interval_data_present"
#define JSON_KEY_HR_DATA_SENSOR_HEART_RATE "heart_rate"
#define JSON_KEY_HR_DATA_SENSOR_CONTACT_DETECTED "sensor_contact_detected"
#define JSON_KEY_HR_DATA_SENSOR_ENERGY_EXPENDED "energy_expended"
#define JSON_KEY_HR_DATA_SENSOR_RR_INTERVALS "rr_intervals"

#define HEART_RATE_SERVICE_UUID "0x180D"
#define HEART_RATE_MEASUREMENT "0x2A37"

#define HEART_RATE_VALUE_FORMAT (1)
#define SENSOR_CONTACT_DETECTED (2)
#define SENSOR_CONTACT_FEATURE (4)
#define ENERGY_EXPENDED_FEATURE (8)
#define RR_INTERVAL_DATA (16)

typedef struct _bt_device_information_t {
    char address[DEVICE_INFO_ADDR_SIZE+1]; // '\0' terminated string
    char name[DEVICE_INFO_BUFF_SIZE+1];    // '\0' terminated string
} bt_device_information_t;

typedef struct _event_names_t {
    int id;
    const char *name;
} event_names_t;

#endif /* LocalTypes_H_ */


text:
<?xml version="1.0" encoding="UTF-8"?>
<metadata>
  <groupId>org.springframework</groupId>
  <artifactId>spring-instrument</artifactId>
  <versioning>
    <latest>4.1.6.RELEASE</latest>
    <release>4.1.6.RELEASE</release>
    <versions>
      <version>3.2.16.RELEASE</version>
      <version>4.1.6.RELEASE</version>
    </versions>
    <lastUpdated>20170320175519</lastUpdated>
  </versioning>
</metadata>


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;

namespace TaskBot.Helpers
{
    public class MapMaker
    {
        public static string Process(string incomingImageUrl, string sid)
        {
            var imageLocation = SaveImageLocally(incomingImageUrl, sid);
            return imageLocation;
        }

        private static string SaveImageLocally(string imageUrl, string sid)
        {
            var root = "/wwwroot";
            var dir = "/images/";
            var filename = $"{sid}.jpg";
            var path = Environment.CurrentDirectory + root + dir;
            var saveLocation = path + filename;
            var rootLocation = dir + filename;

            if (!Directory.Exists(path))
            {
                var di = Directory.CreateDirectory(path);
            }

            using (var httpClient = new HttpClient())
            {
                byte[] imageBytes = httpClient
                        .GetByteArrayAsync(imageUrl).Result;
                FileStream fs = new FileStream(saveLocation, FileMode.Create);
                BinaryWriter bw = new BinaryWriter(fs);
                bw.Write(imageBytes);
            }

            return rootLocation;
        }

        public static string GetAddressImage(string customerAddress)
        {
            using (WebClient wc = new WebClient())
            {
                try
                {
                    string addressUrl = $"http://dev.virtualearth.net/REST/v1/Imagery/Map/Road/{customerAddress}/16?key=At-9uaLoghwXOeWXbc1bmz4XLcczj0hzL7YeBweBRr0Zx8BFIO9cl6XCU_Jj4sCw";
                    var webClient = new WebClient();
                    byte[] imageBytes = webClient.DownloadData(addressUrl);
                    string url = "data:image/png;base64," + Convert.ToBase64String(imageBytes);
                    return url;
                }
                catch(Exception ex)
                {
                    throw ex;
                }
            }
        }
    }
}


text:
package lazyimmutabilitylinkedlist

type coordinatesLinkedList struct {
	operation CoordinateOperation
	previous  *coordinatesLinkedList
}

func (i *coordinatesLinkedList) execute(input *Coordinates) error {
	if i.previous != nil {
		err := i.previous.execute(input)

		if err != nil {
			return err
		}
	}

	return i.operation(input)
}

// LateralScalar represents a quantity in the east-west direction.
type LateralScalar int

// LongitudinalScalar represents a quantity in the north-south direction.
type LongitudinalScalar int

type CoordinateOperation func (input *Coordinates) error

// Coordinates represents the position of an object on a 2D cartesian surface with the origin in the top-left.
// The value for X positively increases towards the right and the value for Y positively increases towards the bottom.
type Coordinates struct {
	X LateralScalar
	Y LongitudinalScalar
}

func (c Coordinates) TranslateNorth(distance LongitudinalScalar) CoordinateTransform {
	transform := NewCoordinateTransform(&c)
	return transform.TranslateNorth(distance)
}

func (c Coordinates) TranslateEast(distance LateralScalar) CoordinateTransform {
	transform := NewCoordinateTransform(&c)
	return transform.TranslateEast(distance)
}

func (c Coordinates) TranslateSouth(distance LongitudinalScalar) CoordinateTransform {
	transform := NewCoordinateTransform(&c)
	return transform.TranslateSouth(distance)
}

func (c Coordinates) TranslateWest(distance LateralScalar) CoordinateTransform {
	transform := NewCoordinateTransform(&c)
	return transform.TranslateWest(distance)
}

func NewCoordinateTransform(input *Coordinates) CoordinateTransform {
	transform := CoordinateTransform{
		input: input,
	}

	return transform
}

type CoordinateTransform struct {
	input         *Coordinates
	lastOperation *coordinatesLinkedList
}

func (transform CoordinateTransform) Execute() *Coordinates {
	output := *transform.input

	if transform.lastOperation != nil {
		transform.lastOperation.execute(&output)
	}

	return &output
}

func (transform CoordinateTransform) TranslateNorth(distance LongitudinalScalar) CoordinateTransform {
	newOperation := &coordinatesLinkedList{}
	newOperation.previous = transform.lastOperation
	newOperation.operation = func (input *Coordinates) error {
		input.Y = input.Y - distance

		return nil
	}

	transform.lastOperation = newOperation

	return transform
}

func (transform CoordinateTransform) TranslateEast(distance LateralScalar) CoordinateTransform {
	newOperation := &coordinatesLinkedList{}
	newOperation.previous = transform.lastOperation
	newOperation.operation = func (input *Coordinates) error {
		input.X = input.X + distance

		return nil
	}

	transform.lastOperation = newOperation

	return transform
}

func (transform CoordinateTransform) TranslateSouth(distance LongitudinalScalar) CoordinateTransform {
	newOperation := &coordinatesLinkedList{}
	newOperation.previous = transform.lastOperation
	newOperation.operation = func (input *Coordinates) error {
		input.Y = input.Y + distance

		return nil
	}

	transform.lastOperation = newOperation

	return transform
}

func (transform CoordinateTransform) TranslateWest(distance LateralScalar) CoordinateTransform {
	newOperation := &coordinatesLinkedList{}
	newOperation.previous = transform.lastOperation
	newOperation.operation = func (input *Coordinates) error {
		input.X = input.X - distance

		return nil
	}

	transform.lastOperation = newOperation

	return transform
}


text:
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
-->
<project name="${project.name}" xmlns="http://maven.apache.org/DECORATION/1.8.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/DECORATION/1.8.0 http://maven.apache.org/xsd/decoration-1.8.0.xsd">

  <skin>
    <groupId>org.apache.maven.skins</groupId>
    <artifactId>maven-fluido-skin</artifactId>
    <version>1.7</version>
  </skin>

  <custom>
    <fluidoSkin>
      <googleSearch>
        <sitesearch>mojo.codehaus.org</sitesearch>
      </googleSearch>
      <ohloh>
        <projectId>5211</projectId>
        <widget>thin-badge</widget>
      </ohloh>
      <leftColumnClass>span2</leftColumnClass>
      <bodyColumnClass>span10</bodyColumnClass>
    </fluidoSkin>
  </custom>

  <body>
    <links>
      <item name="Clirr" href="http://clirr.sourceforge.net/"/>
    </links>

    <menu name="Overview">
      <item name="Introduction" href="index.html"/>
      <item name="Goals" href="plugin-info.html"/>
      <item name="Usage" href="usage.html"/>
      <item name="FAQ" href="faq.html"/>
    </menu>

    <menu name="Examples">
      <item name="Comparing against a specific version" href="examples/specific-version.html"/>
      <item name="Comparing against a specific artifact" href="examples/specific-artifacts.html"/>
      <item name="Specifying ignored differences" href="examples/ignored-differences.html"/>
    </menu>
  </body>
</project>


text:
using System.Security.Cryptography.X509Certificates;
using SyncTool.Common.Services;

namespace SyncTool.Synchronization.State
{
    public interface ISyncPointService : IItemService<int, ISyncPoint>
    {
        /// <summary>
        /// Gets the latest sync point (the point with the highest id) or null if no sync point exists
        /// </summary>
        ISyncPoint LatestSyncPoint { get; }

        //TODO: check that new item has a valid id (LatestSyncPoint.Id + 1)
        /// <summary>
        /// Adds a new synchronization state
        /// </summary>
        /// <param name="state">The state to add</param>
        /// <exception cref="DuplicateSyncPointException">Thrown if a state with the same id already exists</exception>
        void AddItem(ISyncPoint state);

    }
}


text:
package org.jetbrains.plugins.scala.lang
package transformation
package annotations

import com.intellij.psi.PsiElement
import org.jetbrains.plugins.scala.extensions.{&&, PsiElementExt}
import org.jetbrains.plugins.scala.lang.psi.api.expr.ScUnderscoreSection
import org.jetbrains.plugins.scala.lang.psi.impl.ScalaCode._
import org.jetbrains.plugins.scala.lang.psi.types.result.Typeable
import org.jetbrains.plugins.scala.project.ProjectContext

/**
  * @author Pavel Fatin
  */
class AddTypeToUnderscoreParameter extends AbstractTransformer {
  def transformation(implicit project: ProjectContext): PartialFunction[PsiElement, Unit] = {
    case (e: ScUnderscoreSection) && Typeable(t) if !e.nextSibling.exists(_.getText == ":") =>
      appendTypeAnnotation(t, e) { annotation =>
        val replacement = code"(_: $annotation)"
        val result = e.replace(replacement)
        result.getFirstChild.getNextSibling.getLastChild
      }
  }
}


text:
'use strict';

// Settings
const settings = require('../settings/default');

// Fabric Types
const App = require('../types/app');

// Fabric Services
const Lightning = require('../services/lightning');

// Functions
const _handleMessage = require('../functions/_handleMessage');
const _handleWarning = require('../functions/_handleWarning');
const _handleError = require('../functions/_handleError');

async function main () {
  // Instantiate Application
  const app = new App(settings);

  // Define Resources
  await app.define('Example', {
    components: {
      list: 'example-list',
      view: 'example-view'
    }
  });

  // Register Services
  await app._registerService('lightning', Lightning);

  // Attach Listeners
  app.on('message', _handleMessage);
  app.on('warning', _handleWarning);
  app.on('error', _handleError);

  // Start the Application
  await app.start();

  // Render the UI
  return app.render();
}

main().catch((exception) => {
  console.error('[SCRIPTS:MAIN]', 'Main Process Exception:', exception);
}).then((output) => {
  console.log('[SCRIPTS:MAIN]', 'Main Process Output:', output);
});


text:
/* eslint-disable jsx-a11y/click-events-have-key-events */
/* eslint-disable jsx-a11y/no-static-element-interactions */
import React, { useState } from 'react';
import { useQueensContext } from 'components/App/context';
import * as Styles from './styles';

function DropDown() {
    const [open, setOpen] = useState(false);
    const { changeGrid } = useQueensContext();

    return (

        </Styles.Wrapper>
    );
}

export default DropDown;


text:
"""
Measure the fluxes in a set of reactions
"""
import argparse
import os
import sys

import PyFBA
from PyFBA import log_and_message

def fluxes(reactions, modeldata, media, biomass_equation, verbose=False):
    """
    Run the FBA and return the fluxes through each reaction
    :param biomass_equation: the biomass equation
    :type biomass_equation: PyFBA.metabolism.Reaction
    :param reactions: a set of the reactions to run
    :type reactions: set[str]
    :param modeldata: the model data object
    :type modeldata: PyFBA.model_seed.ModelData
    :param media: the media object
    :type media: set[PyFBA.metabolism.Compound]
    :param verbose: more output
    :return: a dict of the reactions and their fluxes
    :rtype: dict[str, float]
    """

    todelete = set()
    for r in reactions:
        if r not in modeldata.reactions:
            log_and_message(f"WARNING: Reaction {r} not found in our reaction set", stderr=verbose)
            todelete.add(r)
    for r in todelete:
        reactions.remove(r)

    status, value, growth = PyFBA.fba.run_fba(modeldata, reactions, media, biomass_equation, verbose=verbose)
    if not growth:
        msg = f'ERROR: The set of {len(reactions)} reactions that you provided did not result in growth. '
        msg += 'We can not report fluxes if there was no growth!'
        log_and_message(msg, stderr=verbose)
        return {}
    return PyFBA.fba.reaction_fluxes()

def measure_fluxes():
    """
    Parse the arguments and start measuring the fluxes.
    """

    orgtypes = ['gramnegative', 'grampositive', 'microbial', 'mycobacteria', 'plant']
    parser = argparse.ArgumentParser(description='Run Flux Balance Analysis and calculate reaction fluxes')
    parser.add_argument('-r', '--reactions', help='A list of the reactions in this model, one per line', required=True)
    parser.add_argument('-o', '--output', help='file to save the fluxes list to', required=True)
    parser.add_argument('-m', '--media', help='media name', required=True)
    parser.add_argument('-t', '--type', default='gramnegative',
                        help=f'organism type for the model (currently allowed are {orgtypes}). Default=gramnegative')
    parser.add_argument('-b', '--biomass', help='biomass equation to use. Default is the same as --type option')
    parser.add_argument('-v', '--verbose', help='verbose output', action='store_true')
    args = parser.parse_args(sys.argv[2:])

    if not os.path.exists(args.reactions):
        sys.stderr.write(f"FATAL: {args.reactions} does not exist. Please check your files\n")
        sys.exit(1)

    log_and_message(f"Running PyFBA with the parameters: {sys.argv}\n", quiet=True)

    if args.verbose:
        log_and_message(f"Reading reactions from {args.reactions}", stderr=args.verbose)
    rxns = set()
    with open(args.reactions, 'r') as f:
        for li in f:
            if li.startswith('rxn'):
                rxns.add(li.strip())
            else:
                log_and_message(f'Skipped reaction {li} from {args.reactions} as it is not a standard reaction',
                                stderr=args.verbose)

    modeldata = PyFBA.parse.model_seed.parse_model_seed_data(args.type, verbose=args.verbose)
    if args.biomass:
        biomass_equation = PyFBA.metabolism.biomass_equation(args.biomass)
    else:
        biomass_equation = PyFBA.metabolism.biomass_equation(args.type)

    media = PyFBA.parse.pyfba_media(args.media, modeldata, args.verbose)
    fl = fluxes(reactions=rxns, modeldata=modeldata, media=media, biomass_equation=biomass_equation,
                verbose=args.verbose)

    if fl:
        with open(args.output, 'w') as out:
            for rx in fl:
                out.write(f"{rx}\t{fl[rx]}\n")


text:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Grove_i2c Io_3v3 Io_5v Plat_duino on A test config to generate mkdocs.yml frontmatter using Hugo's templating engine</title>
    <link>http://wiki.seeed.cc/tags/grove_i2c-io_3v3-io_5v-plat_duino/</link>
    <description>Recent content in Grove_i2c Io_3v3 Io_5v Plat_duino on A test config to generate mkdocs.yml frontmatter using Hugo's templating engine</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>en-us</language>

	<atom:link href="http://wiki.seeed.cc/tags/grove_i2c-io_3v3-io_5v-plat_duino/index.xml" rel="self" type="application/rss+xml" />

    <item>
      <title>Grove - NFC Tag</title>
      <link>http://wiki.seeed.cc/grove_nfc_tag/</link>
      <pubDate>Mon, 01 Jan 0001 00:00:00 +0000</pubDate>

      <guid>http://wiki.seeed.cc/grove_nfc_tag/</guid>
      <description>Grove - NFC Tag is a highly integrated Near Field Communication Tag module,this module is I2C interface,which base on M24LR64E-R,M24LR64E-R have a 64-bit unique identifier and 64 -Kbit EEPROM.Grove - NFC Tag attach an independent PCB antenna which can easily stretch out of any enclosure you use, leaving more room for you to design the exterior of your project.

Specifications  Working Voltage:5V or 3V3 Working Current&lt;1mA Effective range&lt;2cm Serve for contactless communication at 13.</description>
    </item>

    <item>
      <title>Grove - Q Touch Sensor</title>
      <link>http://wiki.seeed.cc/grove-q_touch_sensor/</link>
      <pubDate>Mon, 01 Jan 0001 00:00:00 +0000</pubDate>

      <guid>http://wiki.seeed.cc/grove-q_touch_sensor/</guid>
      <description>The Q Touch Sensor is a high sensitivity and high noise immunity touch input device. It is based on Atmel AT42QT1070. The AT42QT1070 modulates its bursts in a spread-spectrum fashion in order to heavily suppress the effects of external noise, and to suppress RF emissions. The QT1070 uses a dual-pulse method of acquisition. This provides greater noise immunity and eliminates the need for external sampling capacitors, allowing touch sensing using a single pin.</description>
    </item>

  </channel>
</rss>


text:
/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define, $, window */

/*
* Displays an auto suggest pop-up list of files to allow the user to quickly navigate to a file and lines
* within a file.
* Uses FileIndexManger to supply the file list.
*
* TODO (issue 333) - currently jquery smart auto complete is used for the pop-up list. While it mostly works
* it has several issues, so it should be replace with an alternative. Issues:
* - only accepts an array of strings. A list of objects is preferred to avoid some workarounds to display
*   both the path and filename.
* - the pop-up position logic has flaws that require CSS workarounds
* - the pop-up properties cannot be modified once the object is constructed
*/

define(function (require, exports, module) {
    "use strict";

    var FileIndexManager    = require("project/FileIndexManager"),
        DocumentManager     = require("document/DocumentManager"),
        EditorManager       = require("editor/EditorManager"),
        CommandManager      = require("command/CommandManager"),
        Strings             = require("strings"),
        StringUtils         = require("utils/StringUtils"),
        Commands            = require("command/Commands"),
        ProjectManager      = require("project/ProjectManager");

    /** @type Array.<QuickOpenPlugin> */
    var plugins = [];

    /** @type {QuickOpenPlugin} */
    var currentPlugin = null;

    /** @type Array.<FileInfo>*/
    var fileList;

    /**
     * Remembers the current document that was displayed when showDialog() was called
     * The current document is restored if the user presses escape
     * @type {string} full path
     */
    var origDocPath;

    /**
     * Remembers the selection in the document origDocPath that was present when showDialog() was called.
     * Focusing on an item can cause the current and and/or selection to change, so this variable restores it.
     * The cursor position is restored if the user presses escape.
     * @type ?{start:{line:number, ch:number}, end:{line:number, ch:number}}
     */
    var origSelection;

    var dialogOpen = false;

    /**
     * Defines API for new QuickOpen plug-ins
     */
    function QuickOpenPlugin(name, fileTypes, done, search, match, itemFocus, itemSelect, resultsFormatter) {

        this.name = name;
        this.fileTypes = fileTypes;
        this.done = done;
        this.search = search;
        this.match = match;
        this.itemFocus = itemFocus;
        this.itemSelect = itemSelect;
        this.resultsFormatter = resultsFormatter;
    }

    /**
     * Creates and registers a new QuickOpenPlugin
     *
     * @param { name: string,
     *          fileTypes:Array.<string>} plugin,
     *          done: function(),
     *          search: function(string):Array.<string>,
     *          match: function(string):boolean,
     *          itemFocus: functon(HTMLLIElement),
     *          itemSelect: functon(HTMLLIElement),
     *          resultsFormatter: ?Functon(string, string):string }
     *
     * @returns {QuickOpenPlugin} plugin
     *
     * Parameter Documentation:
     *
     * name - plug-in name
     * filetypes - file types array. Example: ["js", "css", "txt"]. An empty array
     *      indicates all file types.
     * done - called when quick open is complete. Plug-in should clear its internal state.
     * search - takes a query string and returns an array of strings that match the query.
     * match - takes a query string and returns true if this plug-in wants to provide
     *      results for this query.
     * itemFocus - performs an action when a result has focus.
     *      The focused HTMLLIElement is passed as an argument.
     * itemSelect - performs an action when a result is chosen.
     *      The selected HTMLLIElement is passed as an argument.
     * resultFormatter - takes a query string and an item string and returns
     *      a
 item to insert into the displayed search results. If null, default is provided.
     */
    function addQuickOpenPlugin(pluginDef) {
        plugins.push(new QuickOpenPlugin(
            pluginDef.name,
            pluginDef.fileTypes,
            pluginDef.done,
            pluginDef.search,
            pluginDef.match,
            pluginDef.itemFocus,
            pluginDef.itemSelect,
            pluginDef.resultsFormatter
        ));
    }

    /**
    * QuickNavigateDialog class
    * @constructor
    */
    function QuickNavigateDialog() {
        this.$searchField = undefined; // defined when showDialog() is called
    }

    /**
     * Creates a dialog div floating on top of the current code mirror editor
     */
    QuickNavigateDialog.prototype._createDialogDiv = function (template) {
        this.dialog = $("
")
                          .attr("class", "CodeMirror-dialog")
                          .html("
" + template + "
")
                          .prependTo($("#editor-holder"));
    };

    function _filenameFromPath(path, includeExtension) {
        var end;
        if (includeExtension) {
            end = path.length;
        } else {
            end = path.lastIndexOf(".");
        }
        return path.slice(path.lastIndexOf("/") + 1, end);
    }

    /**
     * Attempts to extract a line number from the query where the line number
     * is followed by a colon. Callers should explicitly test result with isNaN()
     *
     * @param {string} query string to extract line number from
     * @returns {number} line number. Returns NaN to indicate no line numbeer was found
     */
    function extractLineNumber(query) {
        // only match : at beginning of query for now
        // TODO: match any location of : when QuickOpen._handleItemFocus() is modified to
        // dynamic open files
        if (query.indexOf(":") !== 0) {
            return NaN;
        }

        var result = NaN;
        var regInfo = query.match(/(!?:)(\d+)/); // colon followed by a digit
        if (regInfo) {
            result = regInfo[2] - 1;
        }

        return result;
    }

    /**
     * Navigates to the appropriate file and file location given the selected item
     * and closes the dialog.
     *
     * Note, if selectedItem is null quick search should inspect $searchField for text
     * that may have not matched anything in in the list, but may have information
     * for carrying out an action.
     */
    QuickNavigateDialog.prototype._handleItemSelect = function (selectedItem) {

        // This is a work-around to select first item when a selection event occurs
        // (usually from pressing the enter key) and no item is selected in the list.
        // This is a work-around since  Smart auto complete doesn't select the first item
        if (!selectedItem) {
            selectedItem = $(".smart_autocomplete_container > li:first-child").get(0);
        }

        // Delegate to current plugin
        if (currentPlugin) {
            currentPlugin.itemSelect(selectedItem);
        } else {

            // extract line number
            var cursor,
                query = this.$searchField.val(),
                gotoLine = extractLineNumber(query);
            if (!isNaN(gotoLine)) {
                cursor = {line: gotoLine, ch: 0};
            }

            // Extract file path
            var fullPath;
            if (selectedItem) {
                fullPath = decodeURIComponent($(selectedItem).attr("data-fullpath"));
            }

            // Nagivate to file and line number
            if (fullPath) {
                CommandManager.execute(Commands.FILE_ADD_TO_WORKING_SET, {fullPath: fullPath})
                    .done(function () {
                        if (!isNaN(gotoLine)) {
                            EditorManager.getCurrentFullEditor().setCursorPos(cursor);
                        }
                    });
            } else if (!isNaN(gotoLine)) {
                EditorManager.getCurrentFullEditor().setCursorPos(cursor);
            }
        }

        this._close();
        EditorManager.focusEditor();
    };

    /**
     * Opens the file specified by selected item if there is no current plug-in, otherwise defers handling
     * to the currentPlugin
     */
    QuickNavigateDialog.prototype._handleItemFocus = function (selectedItem) {
        if (currentPlugin) {
            currentPlugin.itemFocus(selectedItem);
        }
        // TODO: Disable opening files on focus for now since this causes focus related bugs between
        // the editor and the search field.
        // Also, see related code in _handleItemFocus
        /*
        else {
            var fullPath = $(selectedItem).attr("data-fullpath");
            if (fullPath) {
                fullPath = decodeURIComponent(fullPath);
                CommandManager.execute(Commands.FILE_OPEN, {fullPath: fullPath, focusEditor: false});
            }
        }
        */

    };

    /**
     * KeyUp is for cases that handle AFTER a character has been committed to $searchField
     *
     */
    QuickNavigateDialog.prototype._handleKeyUp = function (e) {
        var query = this.$searchField.val();

        // extract line number
        var gotoLine = extractLineNumber(query);
        if (!isNaN(gotoLine)) {
            var from = {line: gotoLine, ch: 0};
            var to = {line: gotoLine, ch: 99999};

            EditorManager.getCurrentFullEditor().setSelection(from, to);
        }

        // Remove current plugin if the query stops matching
        if (currentPlugin && !currentPlugin.match(query)) {
            currentPlugin = null;
        }

        if ($(".smart_autocomplete_highlight").length === 0) {
            this._handleItemFocus($(".smart_autocomplete_container > li:first-child"));
        }
    };

    /**
     * Close the dialog when the ENTER (13) or ESC (27) key is pressed
     *
     * Note, when keydown is handled $searchField does not yet have the character added
     * for the current event e.
     */
    QuickNavigateDialog.prototype._handleKeyDown = function (e) {

        // TODO: pass event through KeyMap.translateKeyboardEvent() to get friendly names
        // instead of using these constants here. Note, translateKeyboardEvent() doesn't yet
        // make friendly names for the escape and enter key.
        var ESCKey = 27, EnterKey = 13;

        // clear the query on ESC key and restore document and cursor position
        if (e.keyCode === EnterKey || e.keyCode === ESCKey) {
            e.stopPropagation();
            e.preventDefault();

            if (e.keyCode === ESCKey) {

                // restore previously viewed doc if user navigated away from it
                if (origDocPath) {
                    CommandManager.execute(Commands.FILE_OPEN, {fullPath: origDocPath})
                        .done(function () {
                            if (origSelection) {
                                EditorManager.getCurrentFullEditor().setSelection(origSelection.start, origSelection.end);
                            }
                        });
                }

                this._close();
            }

            if (e.keyCode === EnterKey) {
                this._handleItemSelect($(".smart_autocomplete_highlight").get(0));
            }

        }
    };

    /**
    * Closes the search dialog and notifies all quick open plugins that
    * searching is done.
    */
    QuickNavigateDialog.prototype._close = function () {

        if (!dialogOpen) {
            return;
        }
        dialogOpen = false;

        var i;
        for (i = 0; i < plugins.length; i++) {
            var plugin = plugins[i];
            plugin.done();
        }

        // Ty TODO: disabled for now while file switching is disabled in _handleItemFocus
        //JSLintUtils.setEnabled(true);

        EditorManager.focusEditor();

        this.dialog.remove();
        $(".smart_autocomplete_container").remove();

        $(window.document).off("mousedown", this.handleDocumentClick);
    };

    function filterFileList(query) {
        var filteredList = $.map(fileList, function (fileInfo) {
            // match query against filename only (not the full path)
            var path = fileInfo.fullPath;
            var filename = _filenameFromPath(path, true);
            if (filename.toLowerCase().indexOf(query.toLowerCase()) !== -1) {
                return path;
            } else {
                return null;
            }
        }).sort(function (a, b) {
            a = a.toLowerCase();
            b = b.toLowerCase();
            //first,  sort by filename without extension
            var filenameA = _filenameFromPath(a, false);
            var filenameB = _filenameFromPath(b, false);
            if (filenameA < filenameB) {
                return -1;
            } else if (filenameA > filenameB) {
                return 1;
            } else {
                // filename is the same, compare including extension
                filenameA = _filenameFromPath(a, true);
                filenameB = _filenameFromPath(b, true);
                if (filenameA < filenameB) {
                    return -1;
                } else if (filenameA > filenameB) {
                    return 1;
                } else {
                    return 0;
                }
            }
        });

        return filteredList;
    }

    function _handleFilter(query) {
        var curDoc = DocumentManager.getCurrentDocument();
        if (curDoc) {
            var filename = _filenameFromPath(curDoc.file.fullPath, true);
            var extension = filename.slice(filename.lastIndexOf(".") + 1, filename.length);

            var i;
            for (i = 0; i < plugins.length; i++) {
                var plugin = plugins[i];
                var extensionMatch = plugin.fileTypes.indexOf(extension) !== -1 || plugin.fileTypes.length === 0;
                if (extensionMatch &&  plugin.match && plugin.match(query)) {
                    currentPlugin = plugin;
                    return plugin.search(query);
                }
            }
        }

        currentPlugin = null;
        return filterFileList(query);
    }

    function defaultResultsFormatter(item, query) {
        query = query.slice(query.indexOf("@") + 1, query.length);

        // Escape both query and item so the replace works properly below
        query = StringUtils.htmlEscape(query);
        item = StringUtils.htmlEscape(item);

        var displayName;
        if (query.length > 0) {
            // make the users query bold within the item's text
            displayName = item.replace(
                new RegExp(StringUtils.regexEscape(query), "gi"),
                "$&"
            );
        } else {
            displayName = item;
        }

        return "
" + displayName + "
";
    }

    function _handleResultsFormatter(item) {
        var query = $("input#quickOpenSearch").val();

        if (currentPlugin) {
            // Plugins use their own formatter or the default formatter
            var formatter = currentPlugin.resultsFormatter || defaultResultsFormatter;
            return formatter(item, query);
        } else {
            // Use the filename formatter
            query = StringUtils.htmlEscape(query);
            var filename = StringUtils.htmlEscape(_filenameFromPath(item, true));
            var rPath = StringUtils.htmlEscape(ProjectManager.makeProjectRelativeIfPossible(item));

            var displayName;
            if (query.length > 0) {
                // make the users query bold within the item's text
                displayName = filename.replace(
                    new RegExp(StringUtils.regexEscape(query), "gi"),
                    "$&"
                );
            } else {
                displayName = filename;
            }

            return "
" + displayName +
                "
" + rPath + "
";
        }
    }

    function setSearchFieldValue(prefix, initialString) {
        prefix = prefix || "";
        initialString = initialString || "";
        initialString = prefix + initialString;

        var $field = $("input#quickOpenSearch");
        if ($field) {
            $field.val(initialString);
            $field.get(0).setSelectionRange(prefix.length, initialString.length);
        }
    }

    /**
     * Close the dialog when the user clicks outside of it. Note, auto smart complete has a "lostFocus" event that is
     * supposed to capture this event, but it also gets triggered on keyUp which doesn't work for quick find.
     */
    QuickNavigateDialog.prototype.handleDocumentClick = function (e) {
        if ($(this.dialog).find(e.target).length === 0 && $(".smart_autocomplete_container").find(e.target).length === 0) {
            this._close();
        }
    };

    /**
    * Shows the search dialog and initializes the auto suggestion list with filenames from the current project
    */
    QuickNavigateDialog.prototype.showDialog = function (prefix, initialString) {
        var that = this;

        if (dialogOpen) {
            return;
        }
        dialogOpen = true;

        this.handleDocumentClick = this.handleDocumentClick.bind(this);
        $(window.document).on("mousedown", this.handleDocumentClick);

        // Ty TODO: disabled for now while file switching is disabled in _handleItemFocus
        // To improve performance during list selection disable JSLint until a document is chosen or dialog is closed
        //JSLintUtils.setEnabled(false);

        var curDoc = DocumentManager.getCurrentDocument();
        origDocPath = curDoc ? curDoc.file.fullPath : null;
        if (curDoc) {
            origSelection = EditorManager.getCurrentFullEditor().getSelection();
        } else {
            origSelection = null;
        }

        // Get the file list and initialize the smart auto completes
        FileIndexManager.getFileInfoList("all")
            .done(function (files) {
                fileList = files;
                var dialogHTML = "Quick Open: <input type='text' autocomplete='off' id='quickOpenSearch' style='width: 30em'>";
                that._createDialogDiv(dialogHTML);
                that.$searchField = $("input#quickOpenSearch");

                that.$searchField.smartAutoComplete({
                    source: files,
                    maxResults: 20,
                    minCharLimit: 0,
                    autocompleteFocused: true,
                    forceSelect: false,
                    typeAhead: false,   // won't work right now because smart auto complete
                                        // using internal raw results instead of filtered results for matching
                    filter: _handleFilter,
                    resultFormatter: _handleResultsFormatter
                });

                that.$searchField.bind({
                    itemSelect: function (e, selectedItem) { that._handleItemSelect(selectedItem); },
                    itemFocus: function (e, selectedItem) { that._handleItemFocus(selectedItem); },
                    keydown: function (e) { that._handleKeyDown(e); },
                    keyup: function (e, query) { that._handleKeyUp(e); }
                    // Note: lostFocus event DOESN'T work because auto smart complete catches the key up from shift-command-o and immediately
                    // triggers lostFocus
                });

                setSearchFieldValue(prefix, initialString);
            });
    };

    function getCurrentEditorSelectedText() {
        var currentEditor = EditorManager.getFocusedEditor();
        return (currentEditor && currentEditor.getSelectedText()) || "";
    }

    function doSearch(prefix, initialString) {
        if (dialogOpen) {
            setSearchFieldValue(prefix, initialString);
        } else {
            var dialog = new QuickNavigateDialog();
            dialog.showDialog(prefix, initialString);
        }
    }

    function doFileSearch() {
        doSearch("", getCurrentEditorSelectedText());
    }

    function doGotoLine() {
        // TODO: Brackets doesn't support disabled menu items right now, when it does goto line and
        // goto definition should be disabled when there is not a current document
        if (DocumentManager.getCurrentDocument()) {
            doSearch(":", "");
        }
    }

    // TODO: should provide a way for QuickOpenJSSymbol to create this function as a plug-in
    function doDefinitionSearch() {
        if (DocumentManager.getCurrentDocument()) {
            doSearch("@", getCurrentEditorSelectedText());
        }
    }

    // TODO: allow QuickOpenJS to register it's own commands and key bindings
    CommandManager.register(Strings.CMD_QUICK_OPEN,         Commands.NAVIGATE_QUICK_OPEN,       doFileSearch);
    CommandManager.register(Strings.CMD_GOTO_DEFINITION,    Commands.NAVIGATE_GOTO_DEFINITION,  doDefinitionSearch);
    CommandManager.register(Strings.CMD_GOTO_LINE,          Commands.NAVIGATE_GOTO_LINE,        doGotoLine);

    exports.addQuickOpenPlugin = addQuickOpenPlugin;
});


text:
package org.diirt.datasource.sim;

import java.time.Instant;
import java.util.Random;

import org.diirt.util.array.ArrayDouble;
import org.diirt.vtype.VDoubleArray;
import org.diirt.vtype.ValueFactory;

import static org.diirt.vtype.ValueFactory.*;

/**
 * Function to simulate a waveform containing a uniformly distributed
 * random data.
 *
 * @author carcassi
 */
public class NoiseWaveform extends SimFunction<VDoubleArray> {

    private Random rand = new Random();
    private double min;
    private double max;
    private int nSamples;
    private double range;
    private VDoubleArray lastValue;

    /**
     * Creates a waveform with samples from a uniform distribution from -5 to 5,
     * updating every second.
     */
    public NoiseWaveform() {
        this(-5.0, 5.0, 1.0);
    }

    /**
     * Creates a gaussian waveform signal with a gaussian distribution, updating at the rate
     * specified.
     *
     * @param min the minimum value
     * @param max the maximum value
     * @param interval time between samples in seconds
     */
    public NoiseWaveform(Double min, Double max, Double interval) {
        this(min, max, 100.0, interval);
    }

    /**
     * Creates a gaussian waveform signal with a gaussian distribution, updating at the rate
     * specified.
     *
     * @param min the minimum value
     * @param max the maximum value
     * @param nSamples number of elements in the waveform
     * @param interval time between samples in seconds
     */
    public NoiseWaveform(Double min, Double max, Double nSamples, Double interval) {
        super(interval, VDoubleArray.class);
        this.min = min;
        this.max = max;
        range = this.max - this.min;
        this.nSamples = nSamples.intValue();
        if (this.nSamples <= 0) {
            throw new IllegalArgumentException("Number of sample must be a positive integer.");
        }
    }

    private double[] generateNewValue() {
        double[] newArray = new double[nSamples];
        for (int i = 0; i < newArray.length; i++) {
            newArray[i] = min + rand.nextDouble() * (max - min);
        }
        return newArray;
    }

    @Override
    VDoubleArray nextValue() {
        if (lastTime == null)
            lastTime = Instant.now();
        return ValueFactory.newVDoubleArray(new ArrayDouble(generateNewValue()), alarmNone(),
                newTime(lastTime), newDisplay(min, min + range * 0.1, min + range * 0.2, "x", Constants.DOUBLE_FORMAT,
                min + range * 0.8, min + range * 0.9, max, min, max));
    }
}


text:
Add a stock to your portfolio

  {{ portfolio.error }}

<form class="col s12" ng-submit="portfolio.addStock()">

      search
      <input id="icon_prefix" type="text" class="validate" ng-model="portfolio.stock.symbol" required>
      Stock Ticker

      equalizer
      <input id="icon_prefix" type="number" class="validate" min="1" step="1" ng-model="portfolio.stock.shares" required>
      Number of shares

  <button class="btn waves-effect waves-light col s7 l4 offset-l4 offset-s2" type="submit" name="action">Submit
  </button>

  <button class="btn waves-effect waves-light col s7 l4 offset-l4 offset-s2 white cancel-add-stock-button" type="submit" name="action" ng-click="portfolio.displayForm = false">Cancel
  </button>
</form>


text:
<?xml version="1.0" encoding="UTF-8"?>
<ldswebml type="image" uri="/media-library/images/temples/apia-samoa#samoa-temple-765592" xml:lang="eng" locale="eng" status="publish">
  <search-meta>
      <uri-title its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">samoa-temple-765592</uri-title>
      <source>samoa-temple-765592</source>
      <publication-type its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">image</publication-type>
      <media-type its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">image</media-type>
      <publication value="ldsorg">LDS.org</publication>
      <publication-date value="2012-04-09">2012-04-09</publication-date>
      <title/>
      <description/>
      <collections>
          <collection its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">global-search</collection>
          <collection its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">media</collection>
          <collection its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">images</collection>
      </collections>
      <subjects>
          <subject>Apia</subject>
          <subject>Samoa</subject>
          <subject>Temples</subject>
          <subject>Flags</subject>
          <subject>Clouds</subject>
      </subjects>
  </search-meta>
  <no-search>
      <path>http://media.ldscdn.org/images/media-library/temples/apia-samoa/samoa-temple-765592-gallery.jpg</path>
      <images>
          <small its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">http://media.ldscdn.org/images/media-library/temples/apia-samoa/samoa-temple-765592-thumbnail.jpg</small>
      </images>
  </no-search>
<ldse-meta its:translate="no" xmlns="http://lds.org/code/lds-edit" xmlns:its="http://www.w3.org/2005/11/its"><document id="samoa-temple-765592" locale="eng" uri="/media-library/images/temples/apia-samoa#samoa-temple-765592" status="publish" site="ldsorg" source="chq" words="52" tgp="0.1818"/><created username="lds-edit" userid=""/><last-modified date="2012-05-10T12:26:23.573084-06:00" username="lds-edit" userid=""/></ldse-meta></ldswebml>


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<meta name="viewport" content="width=device-width" />

                            <td class="six sub-columns center" style="-moz-hyphens: auto; -webkit-font-smoothing: antialiased; -webkit-hyphens: auto; -webkit-text-size-adjust: none; border-collapse: collapse !important; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-size: 14px; font-weight: normal; hyphens: auto; line-height: 19px; margin: 0; min-width: 0px; padding: 0px 10px 10px 0px; text-align: center; vertical-align: top; width: 50%; word-break: break-word" align="center" valign="top">

								{{Subject .Subject "Reset your raintank password - {{.Name}}"}}

Hi {{.Name}}

							Please click the following link to reset your password within {{.EmailCodeValidHours}} hours.

							{{.AppUrl}}user/password/reset?code={{.Code}}

Not working? Try copying and pasting it to your browser. Otherwise, dont hesitate to email us at hello@raintank.io

																Sent by raintank v{{.BuildVersion}}


text:
/*
 * Hibernate Validator, declare and validate application constraints
 *
 * License: Apache License, Version 2.0
 * See the license.txt file in the root directory or <http://www.apache.org/licenses/LICENSE-2.0>.
 */
package org.hibernate.validator.cfg.defs;

import jakarta.validation.constraints.Positive;

import org.hibernate.validator.cfg.ConstraintDef;

/**
 * @author Gunnar Morling
 */
public class PositiveDef extends ConstraintDef<PositiveDef, Positive> {

	public PositiveDef() {
		super( Positive.class );
	}
}