text:
package org.apache.commons.httpclient.util;

import java.io.UnsupportedEncodingException;

import org.apache.commons.codec.net.URLCodec;
import org.apache.commons.httpclient.HttpClientError;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * The home for utility methods that handle various encoding tasks.
 *
 * @author Michael Becke
 * @author Oleg Kalnichevski
 *
 * @since 2.0 final
 */
public class EncodingUtil {

    /** Default content encoding chatset */
    private static final String DEFAULT_CHARSET = "ISO-8859-1";

    /** Log object for this class. */
    private static final Log LOG = LogFactory.getLog(EncodingUtil.class);

    /**
     * Form-urlencoding routine.
     *
     * The default encoding for all forms is `application/x-www-form-urlencoded'.
     * A form data set is represented in this media type as follows:
     *
     * The form field names and values are escaped: space characters are replaced
     * by `+', and then reserved characters are escaped as per [URL]; that is,
     * non-alphanumeric characters are replaced by `%HH', a percent sign and two
     * hexadecimal digits representing the ASCII code of the character. Line breaks,
     * as in multi-line text field values, are represented as CR LF pairs, i.e. `%0D%0A'.
     *
     *

     * if the given charset is not supported, ISO-8859-1 is used instead.
     *

     *
     * @param pairs the values to be encoded
     * @param charset the character set of pairs to be encoded
     *
     * @return the urlencoded pairs
     *
     * @since 2.0 final
     */
     public static String formUrlEncode(NameValuePair[] pairs, String charset) {
        try {
            return doFormUrlEncode(pairs, charset);
        } catch (UnsupportedEncodingException e) {
            LOG.error("Encoding not supported: " + charset);
            try {
                return doFormUrlEncode(pairs, DEFAULT_CHARSET);
            } catch (UnsupportedEncodingException fatal) {
                // Should never happen. ISO-8859-1 must be supported on all JVMs
                throw new HttpClientError("Encoding not supported: " +
                    DEFAULT_CHARSET);
            }
        }
    }

    /**
     * Form-urlencoding routine.
     *
     * The default encoding for all forms is `application/x-www-form-urlencoded'.
     * A form data set is represented in this media type as follows:
     *
     * The form field names and values are escaped: space characters are replaced
     * by `+', and then reserved characters are escaped as per [URL]; that is,
     * non-alphanumeric characters are replaced by `%HH', a percent sign and two
     * hexadecimal digits representing the ASCII code of the character. Line breaks,
     * as in multi-line text field values, are represented as CR LF pairs, i.e. `%0D%0A'.
     *
     * @param pairs the values to be encoded
     * @param charset the character set of pairs to be encoded
     *
     * @return the urlencoded pairs
     * @throws UnsupportedEncodingException if charset is not supported
     *
     * @since 2.0 final
     */
     private static String doFormUrlEncode(NameValuePair[] pairs, String charset)
        throws UnsupportedEncodingException
     {
        StringBuffer buf = new StringBuffer();
        for (int i = 0; i < pairs.length; i++) {
            URLCodec codec = new URLCodec();
            NameValuePair pair = pairs[i];
            if (pair.getName() != null) {
                if (i > 0) {
                    buf.append("&");
                }
                buf.append(codec.encode(pair.getName(), charset));
                buf.append("=");
                if (pair.getValue() != null) {
                    buf.append(codec.encode(pair.getValue(), charset));
                }
            }
        }
        return buf.toString();
    }

    /**
     * Converts the byte array of HTTP content characters to a string. If
     * the specified charset is not supported, default system encoding
     * is used.
     *
     * @param data the byte array to be encoded
     * @param offset the index of the first byte to encode
     * @param length the number of bytes to encode
     * @param charset the desired character encoding
     * @return The result of the conversion.
     *
     * @since 3.0
     */
    public static String getString(
        final byte[] data,
        int offset,
        int length,
        String charset
    ) {

        if (data == null) {
            throw new IllegalArgumentException("Parameter may not be null");
        }

        if (charset == null || charset.length() == 0) {
            throw new IllegalArgumentException("charset may not be null or empty");
        }

        try {
            return new String(data, offset, length, charset);
        } catch (UnsupportedEncodingException e) {

            if (LOG.isWarnEnabled()) {
                LOG.warn("Unsupported encoding: " + charset + ". System encoding used");
            }
            return new String(data, offset, length);
        }
    }

    /**
     * Converts the byte array of HTTP content characters to a string. If
     * the specified charset is not supported, default system encoding
     * is used.
     *
     * @param data the byte array to be encoded
     * @param charset the desired character encoding
     * @return The result of the conversion.
     *
     * @since 3.0
     */
    public static String getString(final byte[] data, String charset) {
        return getString(data, 0, data.length, charset);
    }

    /**
     * Converts the specified string to a byte array.  If the charset is not supported the
     * default system charset is used.
     *
     * @param data the string to be encoded
     * @param charset the desired character encoding
     * @return The resulting byte array.
     *
     * @since 3.0
     */
    public static byte[] getBytes(final String data, String charset) {

        if (data == null) {
            throw new IllegalArgumentException("data may not be null");
        }

        if (charset == null || charset.length() == 0) {
            throw new IllegalArgumentException("charset may not be null or empty");
        }

        try {
            return data.getBytes(charset);
        } catch (UnsupportedEncodingException e) {

            if (LOG.isWarnEnabled()) {
                LOG.warn("Unsupported encoding: " + charset + ". System encoding used.");
            }

            return data.getBytes();
        }
    }

    /**
     * Converts the specified string to byte array of ASCII characters.
     *
     * @param data the string to be encoded
     * @return The string as a byte array.
     *
     * @since 3.0
     */
    public static byte[] getAsciiBytes(final String data) {

        if (data == null) {
            throw new IllegalArgumentException("Parameter may not be null");
        }

        try {
            return data.getBytes("US-ASCII");
        } catch (UnsupportedEncodingException e) {
            throw new HttpClientError("HttpClient requires ASCII support");
        }
    }

    /**
     * Converts the byte array of ASCII characters to a string. This method is
     * to be used when decoding content of HTTP elements (such as response
     * headers)
     *
     * @param data the byte array to be encoded
     * @param offset the index of the first byte to encode
     * @param length the number of bytes to encode
     * @return The string representation of the byte array
     *
     * @since 3.0
     */
    public static String getAsciiString(final byte[] data, int offset, int length) {

        if (data == null) {
            throw new IllegalArgumentException("Parameter may not be null");
        }

        try {
            return new String(data, offset, length, "US-ASCII");
        } catch (UnsupportedEncodingException e) {
            throw new HttpClientError("HttpClient requires ASCII support");
        }
    }

    /**
     * Converts the byte array of ASCII characters to a string. This method is
     * to be used when decoding content of HTTP elements (such as response
     * headers)
     *
     * @param data the byte array to be encoded
     * @return The string representation of the byte array
     *
     * @since 3.0
     */
    public static String getAsciiString(final byte[] data) {
        return getAsciiString(data, 0, data.length);
    }

    /**
     * This class should not be instantiated.
     */
    private EncodingUtil() {
    }

}

redpajama_set_name: RedPajamaGithub


text:
'use strict';

const _ = require('lodash');
const AbstractConnectionManager = require('../abstract/connection-manager');
const logger = require('../../utils/logger');
const debug = logger.getLogger().debugContext('connection:pg');
const Promise = require('../../promise');
const sequelizeErrors = require('../../errors');
const semver = require('semver');
const dataTypes = require('../../data-types');
const moment = require('moment-timezone');

class ConnectionManager extends AbstractConnectionManager {
  constructor(dialect, sequelize) {
    super(dialect, sequelize);
    this.sequelize.config.port = this.sequelize.config.port || 5432;

    const pgLib = this._loadDialectModule('pg');
    this.lib = this.sequelize.config.native ? pgLib.native : pgLib;

    this._clearTypeParser();
    this.refreshTypeParser(dataTypes.postgres);
  }

  // Expose this as a method so that the parsing may be updated when the user has added additional, custom types
  _refreshTypeParser(dataType) {
    if (dataType.types.postgres.oids) {
      for (const oid of dataType.types.postgres.oids) {
        this.oidMap[oid] = value => dataType.parse(value, oid, this.lib.types.getTypeParser);
      }
    }

    if (dataType.types.postgres.array_oids) {
      for (const oid of dataType.types.postgres.array_oids) {
        this.arrayOidMap[oid] = value => {
          return this.lib.types.arrayParser.create(value, v =>
            dataType.parse(v, oid, this.lib.types.getTypeParser)
          ).parse();
        };
      }
    }
  }

  _clearTypeParser() {
    this.oidMap = {};
    this.arrayOidMap = {};
  }

  getTypeParser(oid) {
    if (this.oidMap[oid]) {
      return this.oidMap[oid];
    } else if (this.arrayOidMap[oid]) {
      return this.arrayOidMap[oid];
    }

    return this.lib.types.getTypeParser.apply(undefined, arguments);
  }

  connect(config) {
    config.user = config.username;
    const connectionConfig = _.pick(config, [
      'user', 'password', 'host', 'database', 'port'
    ]);

    connectionConfig.types = {
      getTypeParser: ConnectionManager.prototype.getTypeParser.bind(this)
    };

    if (config.dialectOptions) {
      _.merge(connectionConfig,
        _.pick(config.dialectOptions, [
        // see [http://www.postgresql.org/docs/9.3/static/runtime-config-logging.html#GUC-APPLICATION-NAME]
          'application_name',
          // choose the SSL mode with the PGSSLMODE environment variable
          // object format: [https://github.com/brianc/node-postgres/blob/master/lib/connection.js#L79]
          // see also [http://www.postgresql.org/docs/9.3/static/libpq-ssl.html]
          'ssl',
          // In addition to the values accepted by the corresponding server,
          // you can use "auto" to determine the right encoding from the
          // current locale in the client (LC_CTYPE environment variable on Unix systems)
          'client_encoding',
          // !! DO NOT SET THIS TO TRUE !!
          // (unless you know what you're doing)
          // see [http://www.postgresql.org/message-id/flat/bc9549a50706040852u27633f41ib1e6b09f8339d845@mail.gmail.com#bc9549a50706040852u27633f41ib1e6b09f8339d845@mail.gmail.com]
          'binary',
          // This should help with backends incorrectly considering idle clients to be dead and prematurely disconnecting them.
          // this feature has been added in pg module v6.0.0, check pg/CHANGELOG.md
          'keepAlive',
          // Times out queries after a set time in milliseconds. Added in pg v7.3
          'statement_timeout'
        ]));
    }

    return new Promise((resolve, reject) => {
      let responded = false;

      const connection = new this.lib.Client(connectionConfig);
      const endHandler = () => {
        debug('connection timeout');
        if (!responded) {
          reject(new sequelizeErrors.ConnectionTimedOutError(new Error('Connection timed out')));
        }
      };

      // If we didn't ever hear from the client.connect() callback the connection timeout
      // node-postgres does not treat this as an error since no active query was ever emitted
      connection.once('end', endHandler);

      connection.connect(err => {
        responded = true;
        if (err) {
          if (err.code) {
            switch (err.code) {
              case 'ECONNREFUSED':
                reject(new sequelizeErrors.ConnectionRefusedError(err));
                break;
              case 'ENOTFOUND':
                reject(new sequelizeErrors.HostNotFoundError(err));
                break;
              case 'EHOSTUNREACH':
                reject(new sequelizeErrors.HostNotReachableError(err));
                break;
              case 'EINVAL':
                reject(new sequelizeErrors.InvalidConnectionError(err));
                break;
              default:
                reject(new sequelizeErrors.ConnectionError(err));
                break;
            }
          } else {
            reject(new sequelizeErrors.ConnectionError(err));
          }
        } else {
          debug('connection acquired');
          connection.removeListener('end', endHandler);
          resolve(connection);
        }
      });
    }).tap(connection => {
      let query = '';

      if (
        this.sequelize.options.databaseVersion !== 0
        && semver.gte(this.sequelize.options.databaseVersion, '8.2.0')
        && semver.lt(this.sequelize.options.databaseVersion, '9.1.0')
      ) {
        // Disable escape characters in strings
        // see https://github.com/sequelize/sequelize/issues/3545 (security issue)
        // see https://www.postgresql.org/docs/current/static/runtime-config-compatible.html#GUC-STANDARD-CONFORMING-STRINGS
        query += 'SET standard_conforming_strings=on;';
      }

      if (!this.sequelize.config.keepDefaultTimezone) {
        const isZone = !!moment.tz.zone(this.sequelize.options.timezone);
        if (isZone) {
          query += `SET client_min_messages TO warning; SET TIME ZONE '${this.sequelize.options.timezone}';`;
        } else {
          query += `SET client_min_messages TO warning; SET TIME ZONE INTERVAL '${this.sequelize.options.timezone}' HOUR TO MINUTE;`;
        }
      }

      if (query) {
        return connection.query(query);
      }
    }).tap(connection => {
      if (
        dataTypes.GEOGRAPHY.types.postgres.oids.length === 0 &&
        dataTypes.GEOMETRY.types.postgres.oids.length === 0 &&
        dataTypes.HSTORE.types.postgres.oids.length === 0 &&
        dataTypes.ENUM.types.postgres.oids.length === 0 &&
        dataTypes.CITEXT.types.postgres.oids.length === 0
      ) {
        return this._refreshDynamicOIDs(connection);
      }
    }).tap(connection => {
      // Don't let a Postgres restart (or error) to take down the whole app
      connection.on('error', error => {
        connection._invalid = true;
        debug(`connection error ${error.code || error.message}`);
        this.pool.destroy(connection);
      });
    });
  }

  disconnect(connection) {
    if (connection._ending) {
      debug('connection tried to disconnect but was already at ENDING state');
      return Promise.resolve();
    }

    return Promise.fromCallback(callback => connection.end(callback));
  }

  validate(connection) {
    return !connection._invalid && !connection._ending;
  }

  _refreshDynamicOIDs(connection) {
    const databaseVersion = this.sequelize.options.databaseVersion;
    const supportedVersion = '8.3.0';

    // Check for supported version
    if ( (databaseVersion && semver.gte(databaseVersion, supportedVersion)) === false) {
      return Promise.resolve();
    }

    // Refresh dynamic OIDs for some types
    // These include, Geometry / HStore / Enum / Citext
    return (connection || this.sequelize).query(
      "SELECT typname, typtype, oid, typarray FROM pg_type WHERE (typtype = 'b' AND typname IN ('hstore', 'geometry', 'geography', 'citext')) OR (typtype = 'e')"
    ).then(results => {
      let result = Array.isArray(results) ? results.pop() : results;

      // When searchPath is prepended then two statements are executed and the result is
      // an array of those two statements. First one is the SET search_path and second is
      // the SELECT query result.
      if (Array.isArray(result)) {
        if (result[0].command === 'SET') {
          result = result.pop();
        }
      }

      // Reset OID mapping for dynamic type
      [
        dataTypes.GEOMETRY,
        dataTypes.HSTORE,
        dataTypes.GEOGRAPHY,
        dataTypes.ENUM,
        dataTypes.CITEXT
      ].forEach(type => {
        type.types.postgres.oids = [];
        type.types.postgres.array_oids = [];
      });

      for (const row of result.rows) {
        let type;

        if (row.typname === 'geometry') {
          type = dataTypes.GEOMETRY;
        } else if (row.typname === 'hstore') {
          type = dataTypes.HSTORE;
        } else if (row.typname === 'geography') {
          type = dataTypes.GEOGRAPHY;
        } else if (row.typname === 'citext') {
          type = dataTypes.CITEXT;
        } else if (row.typtype === 'e') {
          type = dataTypes.ENUM;
        }

        type.types.postgres.oids.push(row.oid);
        type.types.postgres.array_oids.push(row.typarray);
      }

      this.refreshTypeParser(dataTypes.postgres);
    });
  }
}

module.exports = ConnectionManager;
module.exports.ConnectionManager = ConnectionManager;
module.exports.default = ConnectionManager;


text:
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

window.pacRequestCount = 0;
window.title2RequestCount = 0;

chrome.webRequest.onBeforeRequest.addListener(function(details) {
  ++window.pacRequestCount;
}, {urls: ['*://*/self.pac']});

chrome.webRequest.onBeforeRequest.addListener(function(details) {
  ++window.title2RequestCount;
}, {urls: ['*://*/title2.html']});

chrome.test.sendMessage('ready');


text:
<!DOCTYPE html>

<link rel="stylesheet" href="/resources/quantum-code-highlight.css"></link><meta name="viewport" content="width=device-width, initial-scale=1"></meta>

Progress

Marker

Tracker

HTML

<div id="example"></div>

<div class="hx-layout hx-group hx-vertical">
  <div class="hx-group hx-horizontal">
    <div class="hx-section text hx-no-margin">Progress</div>
    <div class="hx-section hx-no-margin" id="completed-slider"></div>
  </div>
  <div class="hx-group hx-horizontal">
    <div class="hx-section text hx-no-margin">Marker</div>
    <div class="hx-section hx-no-margin" id="marker-slider"></div>
  </div>
  <div class="hx-group hx-horizontal">
    <div class="hx-section text hx-no-margin">Tracker</div>
    <div class="hx-section hx-no-margin" id="tracker-slider"></div>
  </div>
</div>

JavaScript

var meter = new hx.Meter('#example')

var total = 5000

function update(){
  meter.value({
    unitText: 'Completed',
    total: total,
    completed: Math.round(completed.value()*total),
    tracker: Math.round(tracker.value()*total),
    marker: Math.round(marker.value()*total),
    markerText: 'Plan: ' + Math.round(marker.value()*total)
  })
}

var marker = new hx.Slider('#marker-slider')
  .on('change', update)
  .value(0.35)

var tracker = new hx.Slider('#tracker-slider')
  .on('change', update)
  .value(0.45)

var completed = new hx.Slider('#completed-slider')
  .on('change', update)
  .value(0.75)

update()

CSS

#example {
  width: 100%;
  height: 300px;
}

.text {
  max-width: 60px;
}


text:
package com.gis.scr.methods;

import com.gis.scr.MethodProvider;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiAnnotation;
import com.intellij.psi.PsiField;
import de.plushnikov.intellij.plugin.util.PsiAnnotationUtil;

import java.util.Collection;

/**
 *
 */
public class UnbindMethodNameProvider implements MethodProvider {

    @Override
    public boolean validate(PsiAnnotation psiAnnotation) {
        Collection<String> unbind = PsiAnnotationUtil.getAnnotationValues(psiAnnotation, "unbind", String.class);
        return unbind.isEmpty() || unbind.size() ==  1 && unbind.contains("");
    }

    @Override
    public String getMethodName(PsiField psiField) {
        String psiFieldName = psiField.getName();
        return psiFieldName == null ? null : "unbind"+ StringUtil.capitalize(psiFieldName);
    }
}


text:
<?php
// INSTALL_ROOT is defined in the index.php bootstrap file
define('FUEL_VERSION', '1.4.13');
if (!defined('MODULES_FOLDER'))
{
	define('MODULES_FOLDER', '../../fuel/modules');
}
define('FUEL_FOLDER', 'fuel');
define('MODULES_PATH', APPPATH.MODULES_FOLDER.'/');
define('MODULES_FROM_APPCONTROLLERS', '../'.MODULES_FOLDER.'/');
define('FUEL_PATH', MODULES_PATH.FUEL_FOLDER.'/');
define('WEB_ROOT', str_replace('\\', '/', realpath(dirname(SELF)).DIRECTORY_SEPARATOR)); // replace \ with / for windows

// Needed to take care of some server environments
$_SERVER['SCRIPT_NAME'] = preg_replace('#^/(.+)\.php/(.*)#', '/$1.php', $_SERVER['SCRIPT_NAME']);
if (!isset($_SERVER['HTTP_HOST']))
{
	$_SERVER['HTTP_HOST'] = $_SERVER['SERVER_NAME'];
	if (!empty($_SERVER['SERVER_PORT']))
	{
		$_SERVER['HTTP_HOST'] .= ':'.$_SERVER['SERVER_PORT'];
	}
}
define('WEB_PATH', str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']));

// Change slashes for some Windows platforms
$_FUEL_SEGS = explode('/', str_replace("\\", '/', $_SERVER['SCRIPT_FILENAME']));

define('WEB_FOLDER', (count($_FUEL_SEGS) > 1) ? $_FUEL_SEGS[count($_FUEL_SEGS)-2] : '/');
define('MODULES_WEB_PATH', FUEL_FOLDER.'/modules/');

// Must include language helper if you want to use lang function
include(APPPATH.'helpers/MY_language_helper.php');
include(FUEL_PATH.'config/fuel.php');

// Used for CLI... must create $_SERVER['REQUEST_URI]
if (defined('STDIN'))
{
	$args = array_slice($_SERVER['argv'], 1);
	$_SERVER['REQUEST_URI'] = $args ? implode('/', $args) : '';
}

define('FUEL_ROUTE', $config['fuel_path']);

// Detect URI path
if (isset($_SERVER['REQUEST_URI']))
{
	$_URI_PATH = $_SERVER['REQUEST_URI'];
}
else if (isset($_SERVER['PATH_INFO']))
{
	$_URI_PATH = $_SERVER['PATH_INFO'];
}
else if (isset($_SERVER['ORIG_PATH_INFO']))
{
	$_URI_PATH = $_SERVER['ORIG_PATH_INFO'];
}

define('USE_FUEL_ROUTES', (strpos($_URI_PATH, '/'.$config['fuel_path']) !== FALSE));

foreach ($config['modules_allowed'] as $module)
{
	$constants_path = MODULES_PATH . $module . '/config/' . $module . '_constants.php';

	if (file_exists($constants_path))
	{
		require_once($constants_path);
	}
}

if ( ! defined('BASE_URL'))
{
	$_base_path = $_SERVER['HTTP_HOST'].str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']);

	if ( ! empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off' OR $_SERVER['SERVER_PORT'] == 443)
	{
		define('BASE_URL', "https://".$_base_path);
	}
	else
	{
		define('BASE_URL', "http://".$_base_path);
	}
}

/* End of file fuel_constants.php */
/* Location: ./modules/fuel/config/fuel_constants.php */


text:
void instr_ldi_test_decode(void **state);
void instr_ldi_test_exec(void **state);


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <artifactId>python</artifactId>

    <name>python</name>
    <description>
        sparktk is a python library that brings abstractions and conveniences to Spark and Pyspark.
    </description>

    <parent>
        <artifactId>spark-tk</artifactId>
        <groupId>org.trustedanalytics</groupId>
        <version>1.0-SNAPSHOT</version>
        <!--<relativePath>../../pom.xml</relativePath>-->
        <!--<version>master-SNAPSHOT</version>-->
    </parent>

    <profiles>
        <profile>
            <id>python-unittests</id>
            <activation>
                <property>
                    <name>!skipTests</name>
                </property>
            </activation>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.codehaus.mojo</groupId>
                        <artifactId>exec-maven-plugin</artifactId>
                        <executions>
                            <execution>
                                <id>chmod-shellscripts</id>
                                <phase>test</phase>
                                <goals>
                                    <goal>exec</goal>
                                </goals>
                                <configuration>
                                    <executable>chmod</executable>
                                    <workingDirectory>${basedir}</workingDirectory>
                                    <arguments>
                                        <argument>+x</argument>
                                        <argument>sparktk/tests/runtests.sh</argument>
                                    </arguments>
                                </configuration>
                            </execution>
                            <execution>
                                <id>python-tests</id>
                                <phase>test</phase>
                                <goals>
                                    <goal>exec</goal>
                                </goals>
                                <configuration>
                                    <executable>bash</executable>
                                    <workingDirectory>${basedir}</workingDirectory>
                                    <arguments>
                                        <argument>sparktk/tests/runtests.sh</argument>
                                    </arguments>
                                </configuration>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
        <profile>
            <id>docs</id>
            <activation>

                <property>
                    <name>env.DOCS</name>
                </property>
            </activation>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.codehaus.mojo</groupId>
                        <artifactId>exec-maven-plugin</artifactId>
                        <executions>
                            <execution>
                                <id>python-sparktk-docs</id>
                                <phase>prepare-package</phase>
                                <goals>
                                    <goal>exec</goal>
                                </goals>
                                <configuration>
                                    <executable>./builddoc.sh</executable>
                                    <workingDirectory>${basedir}/sparktk/doc/</workingDirectory>

                                </configuration>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
        <profile>
            <id>python-package</id>
            <activation>

                <property>
                    <name>env.BUILD_NUMBER</name>
                </property>
            </activation>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.codehaus.mojo</groupId>
                        <artifactId>exec-maven-plugin</artifactId>
                        <executions>
                            <execution>
                                <id>python-package</id>
                                <phase>package</phase>
                                <goals>
                                    <goal>exec</goal>
                                </goals>
                                <configuration>
                                    <executable>python</executable>
                                    <!--<workingDirectory>${basedir}/sparktk/doc/</workingDirectory>-->
                                    <arguments>
                                        <argument>setup.py</argument>
                                        <argument>sdist</argument>
                                    </arguments>

                                </configuration>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>
    <build>
        <plugins>
            <plugin>
                <groupId>com.mycila</groupId>
                <artifactId>license-maven-plugin</artifactId>
                <configuration>
                    <excludes combine.children="append">

                        <exclude>cover/status.dat</exclude>

                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>


text:
echo Installing dependencies...
#apt-get update
apt-get install -y unzip curl

echo Fetching Consul...
cd /tmp/
if [ ! -f consul.zip ]
  then
    #wget http://dl.bintray.com/mitchellh/consul/0.5.0_linux_amd64.zip -O consul.zip
    cp /consul/consul.zip consul.zip
fi

echo Installing Consul...
unzip consul.zip
chmod +x consul
mv consul /usr/bin/consul


text:
package org.apache.ignite.internal.processors.cache.persistence.file;

import java.io.File;
import java.nio.file.Path;
import java.util.function.LongConsumer;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.internal.pagemem.store.PageStore;
import org.apache.ignite.lang.IgniteOutClosure;

/**
 *
 */
public interface FilePageStoreFactory {
    /**
     * Creates instance of PageStore based on given file.
     *
     * @param type Data type, can be {@link PageStore#TYPE_IDX} or {@link PageStore#TYPE_DATA}.
     * @param file File Page store file.
     * @param allocatedTracker metrics updater.
     * @return page store
     * @throws IgniteCheckedException if failed.
     */
    default PageStore createPageStore(byte type, File file, LongConsumer allocatedTracker)
        throws IgniteCheckedException {
        return createPageStore(type, file::toPath, allocatedTracker);
    }

    /**
     * Creates instance of PageStore based on file path provider.
     *
     * @param type Data type, can be {@link PageStore#TYPE_IDX} or {@link PageStore#TYPE_DATA}
     * @param pathProvider File Page store path provider.
     * @param allocatedTracker metrics updater
     * @return page store
     * @throws IgniteCheckedException if failed
     */
    PageStore createPageStore(byte type, IgniteOutClosure<Path> pathProvider, LongConsumer allocatedTracker)
        throws IgniteCheckedException;
}


text:
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Shapes;
using Pulse.UI;

namespace Pulse.Patcher.Controls
{
    public sealed class DonationControl : UiGrid
    {
        public DonationControl()
        {
            SetCols(2);
            SetRows(5);

            Width = 250;
            VerticalAlignment = VerticalAlignment.Top;
            HorizontalAlignment = HorizontalAlignment.Left;
            Margin = new Thickness(5);
            DataContext = this;
            ColumnDefinitions[0].Width = GridLength.Auto;

            LinearGradientBrush backgroundStroke = new LinearGradientBrush
            {
                EndPoint = new Point(0.5, 1),
                StartPoint = new Point(0.5, 0),
                RelativeTransform = new RotateTransform(115, 0.5, 0.5),
                GradientStops = new GradientStopCollection
                {
                    new GradientStop(Color.FromArgb(0xff, 0x61, 0x61, 0x61), 0),
                    new GradientStop(Color.FromArgb(0xff, 0xF2, 0xF2, 0xF2), 0.504),
                    new GradientStop(Color.FromArgb(0xff, 0xAE, 0xB1, 0xB1), 1)
                }
            };
            backgroundStroke.Freeze();

            LinearGradientBrush backgroundFill = new LinearGradientBrush
            {
                MappingMode = BrushMappingMode.RelativeToBoundingBox,
                StartPoint = new Point(0.5, 1.0),
                EndPoint = new Point(0.5, -0.4),
                GradientStops = new GradientStopCollection
                {
                    new GradientStop(Color.FromArgb(0xBB, 0x44, 0x71, 0xc1), 0),
                    new GradientStop(Color.FromArgb(0xBB, 0x28, 0x36, 0x65), 1)
                }
            };
            backgroundFill.Freeze();

            Rectangle backround = AddUiElement(new Rectangle {Stroke = backgroundStroke, Fill = backgroundFill, StrokeThickness = 5}, 0, 0, 9, 2);

            UiTextBlock title = AddUiElement(UiTextBlockFactory.Create("Пожертвования"), 0, 0, 0, 2);
            title.FontSize = 18;
            title.HorizontalAlignment = HorizontalAlignment.Center;
            title.Margin = new Thickness(0, 4, 0, 0);

            AddUiElement(UiTextBoxFactory.Create("Яндекс: "), 1, 0);
            AddUiElement(UiTextBoxFactory.Create("410013254932482"), 1, 1);
            AddUiElement(UiTextBoxFactory.Create("WMR: "), 2, 0);
            AddUiElement(UiTextBoxFactory.Create("R255847965836"), 2, 1);
            AddUiElement(UiTextBoxFactory.Create("WMZ: "), 3, 0);
            AddUiElement(UiTextBoxFactory.Create("Z321220468886 "), 3, 1);
            AddUiElement(UiTextBoxFactory.Create("WME: "), 4, 0);
            AddUiElement(UiTextBoxFactory.Create("E223137827385"), 4, 1).Margin = new Thickness(0,0,0,5);

            foreach (FrameworkElement child in Children)
            {
                if (!ReferenceEquals(child, backround))
                {
                    child.Margin = GetColumn(child) == 0
                        ? new Thickness(child.Margin.Left + 8, child.Margin.Top, child.Margin.Right, child.Margin.Bottom)
                        : new Thickness(child.Margin.Left, child.Margin.Top, child.Margin.Right + 8, child.Margin.Bottom);
                }

                TextBlock textBlock = child as TextBlock;
                if (textBlock != null)
                {
                    textBlock.Foreground = Brushes.WhiteSmoke;
                    textBlock.FontWeight = FontWeight.FromOpenTypeWeight(500);
                    continue;
                }

                TextBox textBox = child as TextBox;
                if (textBox != null)
                {
                    textBox.Foreground = Brushes.WhiteSmoke;
                    textBox.FontWeight = FontWeight.FromOpenTypeWeight(500);
                    textBox.Background = Brushes.Transparent;
                    textBox.BorderThickness = new Thickness(0);
                    textBox.IsReadOnly = true;
                }
            }
        }
    }
}


text:
<?php

// +----------------------------------------------------------------------+
// | PEAR :: File :: Gettext :: MO                                        |
// +----------------------------------------------------------------------+
// | This source file is subject to version 3.0 of the PHP license,       |
// | that is available at http://www.php.net/license/3_0.txt              |
// | If you did not receive a copy of the PHP license and are unable      |
// | to obtain it through the world-wide-web, please send a note to       |
// | license@php.net so we can mail you a copy immediately.               |
// +----------------------------------------------------------------------+
// | Copyright (c) 2004 Michael Wallner <mike@iworks.at>                  |
// +----------------------------------------------------------------------+
//
// $Id: MO.php 9856 2008-06-25 11:33:49Z fabien $

/**
 * File::Gettext::MO
 *
 * @author      Michael Wallner <mike@php.net>
 * @license     PHP License
 */

require_once dirname(__FILE__).'/TGettext.class.php';

/**
 * File_Gettext_MO
 *
 * GNU MO file reader and writer.
 *
 * @author      Michael Wallner <mike@php.net>
 * @version     $Revision: 9856 $
 * @access      public
 * @package System.I18N.core
 */
class TGettext_MO extends TGettext
{
    /**
     * file handle
     *
     * @access  private
     * @var     resource
     */
    protected $_handle = null;

    /**
     * big endianess
     *
     * Whether to write with big endian byte order.
     *
     * @access  public
     * @var     bool
     */
    protected $writeBigEndian = false;

    /**
     * Constructor
     *
     * @access  public
     * @return  object      File_Gettext_MO
     * @param   string      $file   path to GNU MO file
     */
    function TGettext_MO($file = '')
    {
        $this->file = $file;
    }

    /**
     * _read
     *
     * @access  private
     * @return  mixed
     * @param   int     $bytes
     */
    function _read($bytes = 1)
    {
        if (0 < $bytes = abs($bytes)) {
            return fread($this->_handle, $bytes);
        }
        return null;
    }

    /**
     * _readInt
     *
     * @access  private
     * @return  int
     * @param   bool    $bigendian
     */
    function _readInt($bigendian = false)
    {
		//unpack returns a reference????
		$unpacked = unpack($bigendian ? 'N' : 'V', $this->_read(4));
        return array_shift($unpacked);
    }

    /**
     * _writeInt
     *
     * @access  private
     * @return  int
     * @param   int     $int
     */
    function _writeInt($int)
    {
        return $this->_write(pack($this->writeBigEndian ? 'N' : 'V', (int) $int));
    }

    /**
     * _write
     *
     * @access  private
     * @return  int
     * @param   string  $data
     */
    function _write($data)
    {
        return fwrite($this->_handle, $data);
    }

    /**
     * _writeStr
     *
     * @access  private
     * @return  int
     * @param   string  $string
     */
    function _writeStr($string)
    {
        return $this->_write($string . "\0");
    }

    /**
     * _readStr
     *
     * @access  private
     * @return  string
     * @param   array   $params     associative array with offset and length
     *                              of the string
     */
    function _readStr($params)
    {
        fseek($this->_handle, $params['offset']);
        return $this->_read($params['length']);
    }

    /**
     * Load MO file
     *
     * @access   public
     * @return   mixed   Returns true on success or PEAR_Error on failure.
     * @param    string  $file
     */
    function load($file = null)
    {
        if (!isset($file)) {
            $file = $this->file;
        }

        // open MO file
        if (!is_resource($this->_handle = @fopen($file, 'rb'))) {
            return false;
        }
        // lock MO file shared
        if (!@flock($this->_handle, LOCK_SH)) {
            @fclose($this->_handle);
            return false;
        }

        // read (part of) magic number from MO file header and define endianess

		//unpack returns a reference????
		$unpacked = unpack('c', $this->_read(4));
        switch ($magic = array_shift($unpacked))
        {
            case -34:
                $be = false;
            break;

            case -107:
                $be = true;
            break;

            default:
                return false;
        }

        // check file format revision - we currently only support 0
        if (0 !== ($_rev = $this->_readInt($be))) {
            return false;
        }

        // count of strings in this file
        $count = $this->_readInt($be);

        // offset of hashing table of the msgids
        $offset_original = $this->_readInt($be);
        // offset of hashing table of the msgstrs
        $offset_translat = $this->_readInt($be);

        // move to msgid hash table
        fseek($this->_handle, $offset_original);
        // read lengths and offsets of msgids
        $original = array();
        for ($i = 0; $i < $count; $i++) {
            $original[$i] = array(
                'length' => $this->_readInt($be),
                'offset' => $this->_readInt($be)
            );
        }

        // move to msgstr hash table
        fseek($this->_handle, $offset_translat);
        // read lengths and offsets of msgstrs
        $translat = array();
        for ($i = 0; $i < $count; $i++) {
            $translat[$i] = array(
                'length' => $this->_readInt($be),
                'offset' => $this->_readInt($be)
            );
        }

        // read all
        for ($i = 0; $i < $count; $i++) {
            $this->strings[$this->_readStr($original[$i])] =
                $this->_readStr($translat[$i]);
        }

        // done
        @flock($this->_handle, LOCK_UN);
        @fclose($this->_handle);
        $this->_handle = null;

        // check for meta info
        if (isset($this->strings[''])) {
            $this->meta = parent::meta2array($this->strings['']);
            unset($this->strings['']);
        }

        return true;
    }

    /**
     * Save MO file
     *
     * @access  public
     * @return  mixed   Returns true on success or PEAR_Error on failure.
     * @param   string  $file
     */
    function save($file = null)
    {
        if (!isset($file)) {
            $file = $this->file;
        }

        // open MO file
        if (!is_resource($this->_handle = @fopen($file, 'wb'))) {
            return false;
        }
        // lock MO file exclusively
        if (!@flock($this->_handle, LOCK_EX)) {
            @fclose($this->_handle);
            return false;
        }

        // write magic number
        if ($this->writeBigEndian) {
            $this->_write(pack('c*', 0x95, 0x04, 0x12, 0xde));
        } else {
            $this->_write(pack('c*', 0xde, 0x12, 0x04, 0x95));
        }

        // write file format revision
        $this->_writeInt(0);

        $count = count($this->strings) + ($meta = (count($this->meta) ? 1 : 0));
        // write count of strings
        $this->_writeInt($count);

        $offset = 28;
        // write offset of orig. strings hash table
        $this->_writeInt($offset);

        $offset += ($count * 8);
        // write offset transl. strings hash table
        $this->_writeInt($offset);

        // write size of hash table (we currently ommit the hash table)
        $this->_writeInt(0);

        $offset += ($count * 8);
        // write offset of hash table
        $this->_writeInt($offset);

        // unshift meta info
        if ($meta) {
            $meta = '';
            foreach ($this->meta as $key => $val) {
                $meta .= $key . ': ' . $val . "\n";
            }
            $strings = array('' => $meta) + $this->strings;
        } else {
            $strings = $this->strings;
        }

        // write offsets for original strings
        foreach (array_keys($strings) as $o) {
            $len = strlen($o);
            $this->_writeInt($len);
            $this->_writeInt($offset);
            $offset += $len + 1;
        }

        // write offsets for translated strings
        foreach ($strings as $t) {
            $len = strlen($t);
            $this->_writeInt($len);
            $this->_writeInt($offset);
            $offset += $len + 1;
        }

        // write original strings
        foreach (array_keys($strings) as $o) {
            $this->_writeStr($o);
        }

        // write translated strings
        foreach ($strings as $t) {
            $this->_writeStr($t);
        }

        // done
        @flock($this->_handle, LOCK_UN);
        @fclose($this->_handle);
        return true;
    }
}


text:
package de.uxnr.tsoexpert.file;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.spec.SecretKeySpec;

import sun.misc.BASE64Decoder;

public class FileDecrypter {
  public static final String PRIVATE_KEY_FILE = "PRIVATE_KEY";

  private final byte[] keyarr;
  private final Key key;

  public FileDecrypter() throws IOException {
    this.keyarr = this.readPrivateKey();
    this.key = new SecretKeySpec(this.keyarr, "Blowfish");
  }

  public FileData decryptFile(FileData fd) throws IOException {
    ByteArrayInputStream input = fd.getInputStream();
    ByteArrayOutputStream output = new ByteArrayOutputStream();

    BASE64Decoder base64 = new BASE64Decoder();
    byte[] bytearr = base64.decodeBuffer(input);
    input = new ByteArrayInputStream(bytearr);

    Cipher cipher = null;
    try {
      cipher = Cipher.getInstance("Blowfish/ECB/PKCS5Padding");
    } catch (Exception e) {
      throw new IOException(e);
    }

    try {
      cipher.init(Cipher.DECRYPT_MODE, key);
    } catch (Exception e) {
      throw new IOException(e);
    }

    int length = -1;
    CipherInputStream stream = new CipherInputStream(input, cipher);
    while ((length = stream.read(bytearr)) != -1) {
      output.write(bytearr, 0, length);
    }
    output.close();
    stream.close();

    String path = fd.getPath().replaceAll("\\.(.*)_enc", "\\.$1");
    return new FileData(path, output.toByteArray());
  }

  private byte[] readPrivateKey() throws IOException {
    File keyFile = new File(PRIVATE_KEY_FILE);

    FileInputStream input = new FileInputStream(keyFile);
    ByteArrayOutputStream output = new ByteArrayOutputStream();

    int length = -1;
    byte[] bytearr = new byte[1024];
    while ((length = input.read(bytearr)) != -1) {
      output.write(bytearr, 0, length);
    }
    output.close();
    input.close();

    String key = new String(output.toByteArray());
    return key.trim().getBytes("UTF8");
  }

  public static void main(String[] args) throws IOException {
    File file = new File("res/GFX/game_settings.xml_enc");
    FileInputStream fileStream = new FileInputStream(file);
    FileDecrypter fileDecrypter = new FileDecrypter();
    FileData fileData = new FileData(file.getPath(), fileStream);
    fileDecrypter.decryptFile(fileData);
  }
}


text:
import re
from os.path import abspath, dirname, join
from setuptools import setup, find_packages

# Find the directory containing the source distribution.
source_directory = dirname(abspath(__file__))

# Find the current version.
module = join(source_directory, 'redock', '__init__.py')
for line in open(module, 'r'):
    match = re.match(r'^__version__\s*=\s*["\']([^"\']+)["\']$', line)
    if match:
        version_string = match.group(1)
        break
else:
    raise Exception, "Failed to extract version from redock/__init__.py!"

# Fill in the long description (for the benefit of PyPi)
# with the contents of README.rst (rendered by GitHub).
readme_text = open(join(source_directory, 'README.rst'), 'r').read()

# Fill in the "install_requires" field based on requirements.txt.
requirements = [l.strip() for l in open(join(source_directory, 'requirements.txt'), 'r')]

setup(name='redock',
      version=version_string,
      description="Human friendly wrapper around Docker",
      long_description=readme_text,
      url='https://github.com/xolox/python-redock',
      author='Peter Odding',
      author_email='peter@peterodding.com',
      packages=find_packages(),
      entry_points=dict(console_scripts=['redock = redock.cli:main']),
      install_requires=requirements,
      test_suite='redock.tests')


text:
@extends('layouts.frontend')

@section('main')

Reset Password

        <form method="POST" action="{!! route('auth.password_reminder.postReset') !!}">
            {!! csrf_field() !!}
            <input type="hidden" name="token" value="{{ $token }}">

            @include($base_view.'errors')

                Email
                <input class="form-control" type="email" name="email" value="{{ old('email') }}">

                Password
                <input class="form-control" type="password" name="password">

                Confirm Password
                <input class="form-control" type="password" name="password_confirmation">

                <button class="btn btn-info" type="submit">
                    Reset Password
                </button>

        </form>

@endsection


text:
package org.jetbrains.plugins.scala.codeInspection.collections

import org.jetbrains.plugins.scala.lang.psi.api.expr.ScExpression

/**
  * mattfowler
  * 4/28/16
  */
class FindAndMapToApplyInspection extends OperationOnCollectionInspection {
  override def possibleSimplificationTypes: Array[SimplificationType] = Array(FindAndMapToApply)
}

object FindAndMapToApply extends SimplificationType {
  def hint = "Replace find and map with apply"

  override def getSimplification(expr: ScExpression): Option[Simplification] = {
    expr match {
      case qual`.find`(underscore() `==` equalsRhsExpr)`.map`(`_._2`()) if isMap(qual) =>
        Some(replace(expr).withText(qual.getText + argListText(Seq(equalsRhsExpr))).highlightFrom(qual))
      case _ => None
    }
  }
}


text:
package com.easypost;

import com.easypost.exception.EasyPostException;
import com.easypost.model.Address;
import com.easypost.model.EndShipper;
import com.easypost.model.Fee;
import com.easypost.model.Form;
import com.easypost.model.Parcel;
import com.easypost.model.Rate;
import com.easypost.model.Shipment;
import com.easypost.model.ShipmentCollection;
import com.easypost.model.Smartrate;
import com.easypost.model.SmartrateAccuracy;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;

public final class ShipmentTest {
    private static TestUtils.VCR vcr;

    /**
     * Set up the testing environment for this file.
     *
     * @throws EasyPostException when the request fails.
     */
    @BeforeAll
    public static void setup() throws EasyPostException {
        vcr = new TestUtils.VCR("shipment", TestUtils.ApiKey.TEST);
    }

    /**
     * Test creating a shipment.
     *
     * @throws EasyPostException when the request fails.
     */
    @Test
    public void testCreate() throws EasyPostException {
        vcr.setUpTest("create");

        Shipment shipment = createFullShipment();

        assertInstanceOf(Shipment.class, shipment);
        assertTrue(shipment.getId().startsWith("shp_"));
        assertNotNull(shipment.getRates());
        assertEquals("PNG", shipment.getOptions().get("label_format"));
        assertEquals("123", shipment.getOptions().get("invoice_number"));
        assertEquals("123", shipment.getReference());
    }

    /**
     * Create a full shipment.
     *
     * @return Shipment object
     */
    private static Shipment createFullShipment() throws EasyPostException {
        return vcr.client.shipment.create(Fixtures.fullShipment());
    }

    /**
     * Test retrieving a shipment.
     *
     * @throws EasyPostException when the request fails.
     */
    @Test
    public void testRetrieve() throws EasyPostException {
        vcr.setUpTest("retrieve");

        Shipment shipment = createFullShipment();

        Shipment retrievedShipment = vcr.client.shipment.retrieve(shipment.getId());

        assertInstanceOf(Shipment.class, retrievedShipment);
        assertTrue(shipment.equals(retrievedShipment));
    }

    /**
     * Test retrieving all shipments.
     *
     * @throws EasyPostException when the request fails.
     */
    @Test
    public void testAll() throws EasyPostException {
        vcr.setUpTest("all");

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("page_size", Fixtures.pageSize());

        ShipmentCollection shipmentCollection = vcr.client.shipment.all(params);

        List<Shipment> shipments = shipmentCollection.getShipments();

        assertTrue(shipments.size() <= Fixtures.pageSize());
        assertNotNull(shipmentCollection.getHasMore());
        assertTrue(shipments.stream().allMatch(shipment -> shipment instanceof Shipment));
    }

    /**
     * Test buying a shipment.
     *
     * @throws EasyPostException when the request fails.
     */
    @Test
    public void testBuy() throws EasyPostException {
        vcr.setUpTest("buy");

        Shipment shipment = createBasicShipment();

        Shipment boughtShipment = vcr.client.shipment.buy(shipment.getId(), shipment.lowestRate());

        assertNotNull(boughtShipment.getPostageLabel());
    }

    /**
     * Create a basic shipment.
     *
     * @return Shipment object
     */
    private static Shipment createBasicShipment() throws EasyPostException {
        return vcr.client.shipment.create(Fixtures.basicShipment());
    }

    /**
     * Test generating a new rate for a shipment.
     *
     * @throws EasyPostException when the request fails.
     */
    @Test
    public void testRegenerateRates() throws EasyPostException {
        vcr.setUpTest("regenerate_rates");

        Shipment shipment = createFullShipment();

        Shipment shipmentWithNewRates = vcr.client.shipment.newRates(shipment.getId());

        List<Rate> rates = shipmentWithNewRates.getRates();

        assertNotNull(rates);
        assertInstanceOf(List.class, rates);
        for (Rate rate : rates) {
            assertInstanceOf(Rate.class, rate);
        }
    }

    /**
     * Test converting a label for a shipment.
     *
     * @throws EasyPostException when the request fails.
     */
    @Test
    public void testConvertLabel() throws EasyPostException {
        vcr.setUpTest("convert_label");

        Shipment shipment = createOneCallBuyShipment();

        Map<String, Object> params = new HashMap<>();
        params.put("file_format", "ZPL");

        Shipment shipmentWithLabel = vcr.client.shipment.label(params, shipment.getId());

        assertNotNull(shipmentWithLabel.getPostageLabel().getLabelZplUrl());
    }

    /**
     * Create a one-call-buy shipment.
     *
     * @return Shipment object
     */
    private static Shipment createOneCallBuyShipment() throws EasyPostException {
        return vcr.client.shipment.create(Fixtures.oneCallBuyShipment());
    }

    /**
     * Test insuring a Shipment.
     *

     * If the shipment was purchased with a USPS rate, it must have had its
     * insurance set to `0` when bought
     * so that USPS doesn't automatically insure it so we could manually insure it
     * here.
     *
     * @throws EasyPostException when the request fails.
     */
    @Test
    public void testInsure() throws EasyPostException {
        vcr.setUpTest("insure");

        Map<String, Object> shipmentData = Fixtures.oneCallBuyShipment();
        // Set to 0 so USPS doesn't insure this automatically and we can insure the
        // shipment manually.
        shipmentData.put("insurance", 0);

        Map<String, Object> insuranceData = new HashMap<>();
        insuranceData.put("amount", "100");

        Shipment shipment = vcr.client.shipment.create(shipmentData);

        Shipment shipmentWithInsurance = vcr.client.shipment.insure(insuranceData, shipment.getId());

        assertEquals("100.00", shipmentWithInsurance.getInsurance());
    }

    /**
     * Test refunding a Shipment.
     *

     * Refunding a test shipment must happen within seconds of the shipment being
     * created as test shipments naturally
     * follow a flow of created -> delivered to cycle through tracking events in
     * test mode - as such anything older
     * than a few seconds in test mode may not be refundable.
     *
     * @throws EasyPostException when the request fails.
     */
    @Test
    public void testRefund() throws EasyPostException {
        vcr.setUpTest("refund");

        Shipment shipment = createOneCallBuyShipment();

        Shipment refundedShipment = vcr.client.shipment.refund(shipment.getId());

        assertEquals("submitted", refundedShipment.getRefundStatus());
    }

    /**
     * Test getting Smartrates from a shipment.
     *
     * @throws EasyPostException when the request fails.
     */
    @Test
    public void testSmartRate() throws EasyPostException {
        vcr.setUpTest("smart_rate");

        Shipment shipment = createBasicShipment();

        assertNotNull(shipment.getRates());
        Rate rate = shipment.getRates().get(0);

        List<Smartrate> smartRates = vcr.client.shipment.smartrates(shipment.getId());
        assertInstanceOf(List.class, smartRates);
        Smartrate smartRate = smartRates.get(0);

        assertEquals(rate.getId(), smartRate.getId());
        assertNotNull(smartRate.getTimeInTransit().getPercentile50());
        assertNotNull(smartRate.getTimeInTransit().getPercentile75());
        assertNotNull(smartRate.getTimeInTransit().getPercentile85());
        assertNotNull(smartRate.getTimeInTransit().getPercentile90());
        assertNotNull(smartRate.getTimeInTransit().getPercentile95());
        assertNotNull(smartRate.getTimeInTransit().getPercentile97());
        assertNotNull(smartRate.getTimeInTransit().getPercentile99());
    }

    /**
     * Test creating a Shipment with empty or null objects and arrays.
     *
     * @throws EasyPostException when the request fails.
     */
    @Test
    public void testCreateEmptyObjects() throws EasyPostException {
        vcr.setUpTest("create_empty_objects");

        Map<String, Object> shipmentData = Fixtures.basicShipment();

        Map<String, Object> customsInfo = new HashMap<>();

        customsInfo.put("customs_items", new ArrayList<String>());
        shipmentData.put("customs_info", customsInfo);

        shipmentData.put("options", null);
        shipmentData.put("tax_identifiers", null);
        shipmentData.put("reference", "");

        Shipment shipment = vcr.client.shipment.create(shipmentData);

        assertInstanceOf(Shipment.class, shipment);
        assertTrue(shipment.getId().startsWith("shp_"));

        assertNotNull(shipment.getOptions()); // The EasyPost API populates some default values here
        assertEquals(0, shipment.getCustomsInfo().getCustomsItems().size());
        assertNull(shipment.getReference());
        assertNull(shipment.getTaxIdentifiers());
    }

    /**
     * Test creating a Shipment with `tax_identifiers`.
     *
     * @throws EasyPostException when the request fails.
     */
    @Test
    public void testCreateTaxIdentifiers() throws EasyPostException {
        vcr.setUpTest("create_tax_identifiers");

        Map<String, Object> shipmentData = Fixtures.basicShipment();

        List<Object> taxIdentifiers = new ArrayList<>();
        taxIdentifiers.add(Fixtures.taxIdentifier());
        shipmentData.put("tax_identifiers", taxIdentifiers);

        Shipment shipmentWithTaxIdentifiers = vcr.client.shipment.create(shipmentData);

        assertInstanceOf(Shipment.class, shipmentWithTaxIdentifiers);
        assertTrue(shipmentWithTaxIdentifiers.getId().startsWith("shp_"));
        assertEquals("IOSS", shipmentWithTaxIdentifiers.getTaxIdentifiers().get(0).getTaxIdType());
    }

    /**
     * Test creating a shipment when only IDs are used.
     *
     * @throws EasyPostException when the request fails.
     */
    @Test
    @Disabled
    // TODO: test is for some reason failing to pull a proper recording when playing
    // back. Only test doing this
    public void testCreateWithIds() throws EasyPostException {
        vcr.setUpTest("create_with_ids");

        Address fromAddress = vcr.client.address.create(Fixtures.caAddress1());
        Address toAddress = vcr.client.address.create(Fixtures.caAddress1());
        Parcel parcel = vcr.client.parcel.create(Fixtures.basicParcel());

        Map<String, Object> shipmentData = Fixtures.basicShipment();
        shipmentData.put("from_address", Collections.singletonMap("id",
                fromAddress.getId()));
        shipmentData.put("to_address", Collections.singletonMap("id",
                toAddress.getId()));
        shipmentData.put("parcel", Collections.singletonMap("id", parcel.getId()));

        Shipment shipment = vcr.client.shipment.create(shipmentData);

        assertInstanceOf(Shipment.class, shipment);
        assertTrue(shipment.getId().startsWith("shp_"));
        assertTrue(shipment.getToAddress().getId().startsWith("adr_"));
        assertTrue(shipment.getFromAddress().getId().startsWith("adr_"));
        assertTrue(shipment.getParcel().getId().startsWith("prcl_"));
        assertEquals("388 Townsend St", shipment.getFromAddress().getStreet1());
    }

    /**
     * Test getting the lowest rate of a shipment.
     *
     * @throws EasyPostException when the request fails.
     */
    @Test
    public void testLowestRate() throws EasyPostException {
        vcr.setUpTest("lowest_rate");

        Shipment shipment = createFullShipment();

        // Test lowest rate with no filters
        Rate lowestRate = shipment.lowestRate();
        assertEquals("First", lowestRate.getService());
        assertEquals(5.82, lowestRate.getRate(), 0.01);
        assertEquals("USPS", lowestRate.getCarrier());

        // Test lowest rate with service filter (this rate is higher than the lowest but
        // should filter)
        List<String> service = new ArrayList<>(Arrays.asList("Priority"));
        Rate lowestRateService = shipment.lowestRate(null, service);
        assertEquals("Priority", lowestRateService.getService());
        assertEquals(8.15, lowestRateService.getRate(), 0.01);
        assertEquals("USPS", lowestRateService.getCarrier());

        // Test lowest rate with carrier filter (should error due to bad carrier)
        List<String> carrier = new ArrayList<>(Arrays.asList("BAD CARRIER"));
        assertThrows(EasyPostException.class, () -> {
            shipment.lowestRate(carrier, null);
        });
    }

    /**
     * Test getting the lowest Smartrate of a shipment.
     *
     * @throws EasyPostException when the request fails.
     */
    @Test
    public void testInstanceLowestSmartRate() throws EasyPostException {
        vcr.setUpTest("lowest_smartrate");

        Shipment shipment = createBasicShipment();
        Smartrate lowestSmartRateFilters = vcr.client.shipment.lowestSmartRate(shipment.getId(), 2,
                SmartrateAccuracy.Percentile90);

        // Test lowest smartrate with valid filters
        assertEquals("Priority", lowestSmartRateFilters.getService());
        assertEquals(8.15, lowestSmartRateFilters.getRate(), 0.01);
        assertEquals("USPS", lowestSmartRateFilters.getCarrier());

        // Test lowest smartrate with invalid filters (should error due to strict
        // delivery days)
        assertThrows(EasyPostException.class, () -> {
            vcr.client.shipment.lowestSmartRate(shipment.getId(), 0, SmartrateAccuracy.Percentile90);
        });
    }

    /**
     * Test getting the lowest smartrate from a list of smartrates.
     *
     * @throws EasyPostException when the request fails.
     */
    @Test
    public void testStaticLowestSmartRates() throws EasyPostException {
        vcr.setUpTest("lowest_smartrate_list");

        Shipment shipment = createBasicShipment();
        List<Smartrate> smartrates = vcr.client.shipment.smartrates(shipment.getId());

        // Test lowest smartrate with valid filters
        Smartrate lowestSmartRate = vcr.client.shipment.findLowestSmartrate(smartrates, 2,
                SmartrateAccuracy.Percentile90);
        assertEquals("Priority", lowestSmartRate.getService());
        assertEquals(8.15, lowestSmartRate.getRate(), 0.01);
        assertEquals("USPS", lowestSmartRate.getCarrier());

        // Test lowest smartrate with invalid filters (should error due to strict
        // delivery days)
        assertThrows(EasyPostException.class, () -> {
            vcr.client.shipment.findLowestSmartrate(smartrates, 0, SmartrateAccuracy.Percentile90);
        });
    }

    /**
     * Test generating a form from a shipment.
     *
     * @throws EasyPostException when the request fails.
     */
    @Test
    public void testGenerateForm() throws EasyPostException {
        vcr.setUpTest("generate_form");

        Shipment shipment = createOneCallBuyShipment();
        String formType = "return_packing_slip";

        Shipment shipmentWithForm = vcr.client.shipment.generateForm(formType, Fixtures.rmaFormOptions(),
                shipment.getId());

        assertTrue(shipmentWithForm.getForms().size() > 0);

        Form form = shipmentWithForm.getForms().get(0);

        assertEquals(formType, form.getFormType());
        assertTrue(form.getFormUrl() != null);
    }

    /**
     * Test creating a shipment with a carbon offset.
     *
     * @throws EasyPostException when the request fails.
     */
    @Test
    public void testCreateShipmentWithCarbonOffset() throws EasyPostException {
        vcr.setUpTest("create_shipment_with_carbon_offset");

        Shipment shipment = vcr.client.shipment.create(Fixtures.basicShipment(), true);

        assertInstanceOf(Shipment.class, shipment);

        List<Rate> rates = shipment.getRates();
        assertNotNull(rates);

        Rate rate = rates.get(0);
        assertNotNull(rate.getCarbonOffset());
        assertNotNull(rate.getCarbonOffset().getPrice());
    }

    /**
     * Test buying a shipment with a carbon offset.
     *
     * @throws EasyPostException when the request fails.
     */
    @Test
    public void testBuyShipmentWithCarbonOffset() throws EasyPostException {
        vcr.setUpTest("buy_shipment_with_carbon_offset");

        Shipment shipment = vcr.client.shipment.create(Fixtures.fullShipment());

        Shipment boughtShipment = vcr.client.shipment.buy(shipment.getId(), shipment.lowestRate(), true);

        assertInstanceOf(Shipment.class, shipment);

        List<Fee> fees = boughtShipment.getFees();
        assertNotNull(fees);

        boolean foundCarbonOffset = false;
        for (Fee fee : fees) {
            if (fee.getType().equals("CarbonOffsetFee")) {
                foundCarbonOffset = true;
                break;
            }
        }
        assertTrue(foundCarbonOffset);
    }

    /**
     * Test one-call buying a shipment with a carbon offset.
     *
     * @throws EasyPostException when the request fails.
     */
    @Test
    public void testOneCallBuyShipmentWithCarbonOffset() throws EasyPostException {
        vcr.setUpTest("one_call_buy_shipment_with_carbon_offset");

        Shipment shipment = vcr.client.shipment.create(Fixtures.oneCallBuyShipment(), true);

        assertInstanceOf(Shipment.class, shipment);

        List<Fee> fees = shipment.getFees();
        assertNotNull(fees);

        boolean foundCarbonOffset = false;
        for (Fee fee : fees) {
            if (fee.getType().equals("CarbonOffsetFee")) {
                foundCarbonOffset = true;
                break;
            }
        }
        assertTrue(foundCarbonOffset);
    }

    /**
     * Test re-rating a shipment with a carbon offset.
     *
     * @throws EasyPostException when the request fails.
     */
    @Test
    public void testRegenerateRatesWithCarbonOffset() throws EasyPostException {
        vcr.setUpTest("regenerate_rates_with_carbon_offset");

        Shipment shipment = vcr.client.shipment.create(Fixtures.oneCallBuyShipment());
        List<Rate> baseRates = shipment.getRates();

        Shipment shipmentWithNewRatesWithCarbon = vcr.client.shipment.newRates(shipment.getId(), true);
        List<Rate> newCarbonRates = shipmentWithNewRatesWithCarbon.getRates();

        Rate baseRate = baseRates.get(0);
        Rate newCarbonRate = newCarbonRates.get(0);

        assertNull(baseRate.getCarbonOffset());
        assertNotNull(newCarbonRate.getCarbonOffset());
    }

    /**
     * Test buying a shipment with an EndShipper ID.
     *
     * @throws EasyPostException when the request fails.
     */
    @Test
    public void testBuyShipmentWithEndShipperId() throws EasyPostException {
        vcr.setUpTest("buy_shipment_with_end_shipper_id");

        EndShipper endShipper = vcr.client.endShipper.create(Fixtures.caAddress1());

        Shipment shipment = vcr.client.shipment.create(Fixtures.basicShipment());
        Shipment boughtShipment = vcr.client.shipment.buy(shipment.getId(), shipment.lowestRate(), endShipper.getId());

        assertNotNull(boughtShipment.getPostageLabel());
    }
}


text:
<?php
namespace fennec\db\record;

use Yii;
use yii\behaviors\SluggableBehavior;

abstract class SluggableRecord extends ActiveRecord
{

  abstract public function getSlugAttribute();

  public function behaviors()
  {

    $behaviors =  [
      [
        'class' => SluggableBehavior::className(),
        'attribute' => $this->getSlugAttribute(),
      ]
    ];

    return array_merge(parent::behaviors(),$behaviors);
  }
}


text:
%w( rubygems test/spec mocha redgreen English ).each { |f| require f }

$LOAD_PATH.unshift File.dirname(__FILE__) + '/../lib'
require 'ambition'


text:
package org.darkstorm.minecraft.gui.theme.simple;

import static org.lwjgl.opengl.GL11.*;

import java.awt.*;

import net.minecraft.client.gui.FontRenderer;

import org.darkstorm.minecraft.gui.component.*;
import org.darkstorm.minecraft.gui.component.Container;
import org.darkstorm.minecraft.gui.theme.AbstractComponentUI;
import org.darkstorm.minecraft.gui.util.RenderUtil;
import org.lwjgl.input.Mouse;

public class SimpleSliderUI extends AbstractComponentUI<Slider> {
	private SimpleTheme theme;

	public SimpleSliderUI(SimpleTheme theme) {
		super(Slider.class);
		this.theme = theme;

		foreground = Color.LIGHT_GRAY;
		background = new Color(128, 128, 128, 128 + 128 / 2);
	}

	@Override
	protected void renderComponent(Slider component) {
		translateComponent(component, false);
		glEnable(GL_BLEND);
		glDisable(GL_CULL_FACE);
		Rectangle area = component.getArea();
		int fontSize = theme.getFontRenderer().FONT_HEIGHT;
		FontRenderer fontRenderer = theme.getFontRenderer();
		fontRenderer.drawString(component.getText(), 0, 0, RenderUtil.toRGBA(component.getForegroundColor()));
		String content = null;
		switch(component.getValueDisplay()) {
		case DECIMAL:
			content = String.format("%,.3f", component.getValue());
			break;
		case INTEGER:
			content = String.format("%,d", Long.valueOf(Math.round(component.getValue())));
			break;
		case PERCENTAGE:
			int percent = (int) Math.round((component.getValue() - component.getMinimumValue()) / (component.getMaximumValue() - component.getMinimumValue()) * 100D);
			content = String.format("%d%%", percent);
		default:
		}
		if(content != null) {
			String suffix = component.getContentSuffix();
			if(suffix != null && !suffix.trim().isEmpty())
				content = content.concat(" ").concat(suffix);
			fontRenderer.drawString(content, component.getWidth() - fontRenderer.getStringWidth(content), 0, RenderUtil.toRGBA(component.getForegroundColor()));
		}
		glDisable(GL_TEXTURE_2D);

		RenderUtil.setColor(component.getBackgroundColor());
		glLineWidth(0.9f);
		glBegin(GL_LINE_LOOP);
		{
			glVertex2d(0, fontSize + 2D);
			glVertex2d(area.width, fontSize + 2D);
			glVertex2d(area.width, area.height);
			glVertex2d(0, area.height);
		}
		glEnd();

		double sliderPercentage = (component.getValue() - component.getMinimumValue()) / (component.getMaximumValue() - component.getMinimumValue());
		RenderUtil.setColor(component.getForegroundColor());
		glBegin(GL_QUADS);
		{
			glVertex2d(0, fontSize + 2D);
			glVertex2d(area.width * sliderPercentage, fontSize + 2D);
			glVertex2d(area.width * sliderPercentage, area.height);
			glVertex2d(0, area.height);
		}
		glEnd();

		glEnable(GL_TEXTURE_2D);
		translateComponent(component, true);
	}

	@Override
	protected Dimension getDefaultComponentSize(Slider component) {
		return new Dimension(100, 8 + theme.getFontRenderer().FONT_HEIGHT);
	}

	@Override
	protected Rectangle[] getInteractableComponentRegions(Slider component) {
		return new Rectangle[] { new Rectangle(0, theme.getFontRenderer().FONT_HEIGHT + 2, component.getWidth(), component.getHeight() - theme.getFontRenderer().FONT_HEIGHT) };
	}

	@Override
	protected void handleComponentInteraction(Slider component, Point location, int button) {
		if(getInteractableComponentRegions(component)[0].contains(location) && button == 0)
			if(Mouse.isButtonDown(button) && !component.isValueChanging())
				component.setValueChanging(true);
			else if(!Mouse.isButtonDown(button) && component.isValueChanging())
				component.setValueChanging(false);
	}

	@Override
	protected void handleComponentUpdate(Slider component) {
		if(component.isValueChanging()) {
			if(!Mouse.isButtonDown(0)) {
				component.setValueChanging(false);
				return;
			}
			Point mouse = RenderUtil.calculateMouseLocation();
			Container parent = component.getParent();
			if(parent != null)
				mouse.translate(-parent.getX(), -parent.getY());
			double percent = (double) mouse.x / (double) component.getWidth();
			double value = component.getMinimumValue() + (percent * (component.getMaximumValue() - component.getMinimumValue()));
			component.setValue(value);
		}
	}
}


text:
#include "RhoClassfactory.h"
#include "sync/SyncThread.h"
#include "sync/ClientRegister.h"

static rho::common::CRhoClassFactory g_oRhoClassFactory;
rho::common::IRhoClassFactory* rho_get_RhoClassFactory()
{
    return &g_oRhoClassFactory;
}

extern "C" {

void rho_clientregister_create(const char* szDevicePin)
{
	rho::sync::CClientRegister::Create(szDevicePin);
}

};


text:
package org.ovirt.engine.core.bll.validator.storage;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;
import org.ovirt.engine.core.bll.ValidationResult;
import org.ovirt.engine.core.bll.provider.storage.OpenStackVolumeProviderProxy;
import org.ovirt.engine.core.common.businessentities.storage.CinderDisk;
import org.ovirt.engine.core.common.businessentities.storage.CinderVolumeType;
import org.ovirt.engine.core.common.businessentities.storage.Disk;
import org.ovirt.engine.core.common.businessentities.storage.VolumeClassification;
import org.ovirt.engine.core.common.errors.EngineMessage;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.dal.dbbroker.DbFacade;
import org.ovirt.engine.core.dao.DiskDao;
import org.ovirt.engine.core.dao.StorageDomainDao;
import com.woorea.openstack.base.client.OpenStackResponseException;
import com.woorea.openstack.cinder.model.Limits;

public class CinderDisksValidator {

    private Iterable<CinderDisk> cinderDisks;

    private Map<Guid, OpenStackVolumeProviderProxy> diskProxyMap;
    private Map<Guid, CinderStorageRelatedDisksAndProxy> cinderStorageToRelatedDisks;

    public CinderDisksValidator(Iterable<CinderDisk> cinderDisks) {
        this.cinderDisks = cinderDisks;
        this.diskProxyMap = initializeVolumeProviderProxyMap();
    }

    public CinderDisksValidator(CinderDisk cinderDisk) {
        this(Collections.singleton(cinderDisk));
    }

    private ValidationResult validate(Callable<ValidationResult> callable) {
        try {
            return callable.call();
        } catch (OpenStackResponseException e) {
            return new ValidationResult(EngineMessage.ACTION_TYPE_FAILED_CINDER,
                    String.format("$cinderException %1$s", e.getMessage()));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public ValidationResult validateCinderDiskLimits() {
        return validate(new Callable<ValidationResult>() {
            @Override
            public ValidationResult call() {
                Map<Guid, CinderStorageRelatedDisksAndProxy> relatedCinderDisksByStorageMap =
                        getRelatedCinderDisksToStorageDomainMap();
                Collection<CinderStorageRelatedDisksAndProxy> relatedCinderDisksByStorageCollection =
                        relatedCinderDisksByStorageMap.values();
                for (CinderStorageRelatedDisksAndProxy relatedCinderDisksByStorage : relatedCinderDisksByStorageCollection) {
                    Limits limits = relatedCinderDisksByStorage.getProxy().getLimits();
                    int numOfDisks = relatedCinderDisksByStorage.getCinderDisks().size();
                    if (isLimitExceeded(limits, VolumeClassification.Volume, numOfDisks)) {
                        String storageName =
                                getStorageDomainDao().get(relatedCinderDisksByStorage.getStorageDomainId())
                                        .getStorageName();
                        return new ValidationResult(EngineMessage.CANNOT_ADD_CINDER_DISK_VOLUME_LIMIT_EXCEEDED,
                                String.format("$maxTotalVolumes %d", limits.getAbsolute().getMaxTotalVolumes()),
                                String.format("$storageName %s", storageName));
                    }
                }
                return ValidationResult.VALID;
            }
        });
    }

    public ValidationResult validateCinderDiskSnapshotsLimits() {
        return validate(new Callable<ValidationResult>() {
            @Override
            public ValidationResult call() {
                Map<Guid, CinderStorageRelatedDisksAndProxy> relatedCinderDisksByStorageMap =
                        getRelatedCinderDisksToStorageDomainMap();
                Collection<CinderStorageRelatedDisksAndProxy> relatedCinderDisksByStorageCollection =
                        relatedCinderDisksByStorageMap.values();
                for (CinderStorageRelatedDisksAndProxy relatedCinderDisksByStorage : relatedCinderDisksByStorageCollection) {
                    Limits limits = relatedCinderDisksByStorage.getProxy().getLimits();
                    int numOfDisks = relatedCinderDisksByStorage.getCinderDisks().size();
                    if (isLimitExceeded(limits, VolumeClassification.Snapshot, numOfDisks)) {
                        String storageName =
                                getStorageDomainDao().get(relatedCinderDisksByStorage.getStorageDomainId())
                                        .getStorageName();
                        return new ValidationResult(EngineMessage.CANNOT_ADD_CINDER_DISK_SNAPSHOT_LIMIT_EXCEEDED,
                                String.format("$maxTotalSnapshots %d", limits.getAbsolute().getMaxTotalVolumes()),
                                String.format("$storageName %s", storageName));
                    }
                }
                return ValidationResult.VALID;
            }
        });
    }

    private boolean isLimitExceeded(Limits limits, VolumeClassification cinderType, int diskCount) {
        if (cinderType == VolumeClassification.Snapshot) {
            return (limits.getAbsolute().getTotalSnapshotsUsed() + diskCount >
                    limits.getAbsolute().getMaxTotalSnapshots());
        }
        if (cinderType == VolumeClassification.Volume) {
            return (limits.getAbsolute().getTotalVolumesUsed() + diskCount >
                    limits.getAbsolute().getMaxTotalVolumes());
        }
        return false;
    }

    private Map<Guid, CinderStorageRelatedDisksAndProxy> getRelatedCinderDisksToStorageDomainMap() {
        if (cinderStorageToRelatedDisks == null) {
            cinderStorageToRelatedDisks = new HashMap<>();
            for (CinderDisk cinderDisk : cinderDisks) {
                Guid storageDomainId = cinderDisk.getStorageIds().get(0);
                CinderStorageRelatedDisksAndProxy cinderRelatedDisksAndProxy =
                        cinderStorageToRelatedDisks.get(storageDomainId);
                if (cinderRelatedDisksAndProxy == null) {
                    List<CinderDisk> cinderDisks = new ArrayList<>();
                    cinderDisks.add(cinderDisk);
                    OpenStackVolumeProviderProxy proxy = diskProxyMap.get(cinderDisk.getId());
                    CinderStorageRelatedDisksAndProxy newCinderRelatedDisksAndProxy =
                            new CinderStorageRelatedDisksAndProxy(storageDomainId, cinderDisks, proxy);
                    cinderStorageToRelatedDisks.put(storageDomainId, newCinderRelatedDisksAndProxy);
                } else {
                    cinderRelatedDisksAndProxy.getCinderDisks().add(cinderDisk);
                }
            }
        }
        return cinderStorageToRelatedDisks;
    }

    private static class CinderStorageRelatedDisksAndProxy {
        private Guid storageDomainId;
        private List<CinderDisk> cinderDisks = new ArrayList<>();
        private OpenStackVolumeProviderProxy proxy;

        public CinderStorageRelatedDisksAndProxy(Guid storageDomainId, List<CinderDisk> cinderDisks, OpenStackVolumeProviderProxy proxy) {
            setStorageDomainId(storageDomainId);
            setCinderDisks(cinderDisks);
            setProxy(proxy);
        }

        public Guid getStorageDomainId() {
            return storageDomainId;
        }

        public void setStorageDomainId(Guid storageDomainId) {
            this.storageDomainId = storageDomainId;
        }

        public List<CinderDisk> getCinderDisks() {
            return cinderDisks;
        }

        public void setCinderDisks(List<CinderDisk> cinderDisks) {
            this.cinderDisks = cinderDisks;
        }

        public OpenStackVolumeProviderProxy getProxy() {
            return proxy;
        }

        public void setProxy(OpenStackVolumeProviderProxy proxy) {
            this.proxy = proxy;
        }
    }

    public ValidationResult validateCinderDisksAlreadyRegistered() {
        return validate(new Callable<ValidationResult>() {
            @Override
            public ValidationResult call() {
                for (CinderDisk disk : cinderDisks) {
                    Disk diskFromDB = getDiskDao().get(disk.getId());
                    if (diskFromDB != null) {
                        return new ValidationResult(EngineMessage.CINDER_DISK_ALREADY_REGISTERED,
                                String.format("$diskAlias %s", diskFromDB.getDiskAlias()));
                    }
                }
                return ValidationResult.VALID;
            }
        });
    }

    /**
     * Validates that the disk's volume type exists in Cinder
     * (note that this method validates only against a single disk).
     */
    public ValidationResult validateCinderVolumeTypesExist() {
        return validate(new Callable<ValidationResult>() {
            @Override
            public ValidationResult call() {
                final CinderDisk disk = cinderDisks.iterator().next();
                OpenStackVolumeProviderProxy proxy = diskProxyMap.get(disk.getId());
                List<CinderVolumeType> volumeTypes = proxy.getVolumeTypes();
                boolean volumeTypeExists = CollectionUtils.exists(volumeTypes, new Predicate() {
                    @Override
                    public boolean evaluate(Object o) {
                        return ((CinderVolumeType) o).getName().equals(disk.getCinderVolumeType());
                    }
                });

                if (!volumeTypeExists) {
                    return new ValidationResult(EngineMessage.CINDER_VOLUME_TYPE_NOT_EXISTS,
                            String.format("$cinderVolumeType %s", disk.getCinderVolumeType()));
                }
                return ValidationResult.VALID;
            }
        });
    }

    private Map<Guid, OpenStackVolumeProviderProxy> initializeVolumeProviderProxyMap() {
        if (diskProxyMap == null) {
            diskProxyMap = new HashMap<>();
            for (CinderDisk cinderDisk : cinderDisks) {
                OpenStackVolumeProviderProxy volumeProviderProxy = getVolumeProviderProxy(cinderDisk);
                diskProxyMap.put(cinderDisk.getId(), volumeProviderProxy);
            }

        }
        return diskProxyMap;
    }

    private OpenStackVolumeProviderProxy getVolumeProviderProxy(CinderDisk cinderDisk) {
        if (cinderDisk == null || cinderDisk.getStorageIds().isEmpty()) {
            return null;
        }
        return OpenStackVolumeProviderProxy.getFromStorageDomainId(cinderDisk.getStorageIds().get(0));
    }

    protected DiskDao getDiskDao() {
        return DbFacade.getInstance().getDiskDao();
    }

    protected StorageDomainDao getStorageDomainDao() {
        return DbFacade.getInstance().getStorageDomainDao();
    }
}


text:
<?php
/**
 * Created by mcfedr on 01/04/2014 16:45
 */

namespace mcfedr\Queue\JobManagerBundle\Listener;

use mcfedr\Queue\JobManagerBundle\Worker\MailerAwareWorker;
use mcfedr\Queue\JobManagerBundle\Worker\Worker;
use Psr\Log\LoggerInterface;

class MailerListener implements PostListener
{
    /**
     * @var \Swift_Mailer
     */
    protected $mailer;

    /**
     * @var \Swift_Transport
     */
    protected $transport;

    /**
     * @var \Psr\Log\LoggerInterface
     */
    protected $logger;

    public function __construct(LoggerInterface $logger, \Swift_Mailer $mailer = null, \Swift_Transport $transport = null)
    {
        $this->logger = $logger;
        $this->mailer = $mailer;
        $this->transport = $transport;
    }

    public function postTask(Worker $worker, array $options = null)
    {
        if ($worker instanceof MailerAwareWorker) {
            if ($this->mailer && $this->transport) {
                //Flush the mailer queue, this isn't normally done until the command execution finishes
                $this->mailer->getTransport()->getSpool()->flushQueue($this->transport);
                $this->transport->stop();
                $this->logger->info('Flushed mail queue');
            }
        }
    }
}


text:
const createTsRule = require('@moped/rule-ts');
const HtmlWebpackPlugin = require('html-webpack-plugin');

const tsRule = createTsRule({
  babelPresets: ['react-app'],
  tsConfigFileName: __dirname + '/tsconfig.build.json',
});

tsRule.use.unshift({loader: '@moped/loader-perf-log', options: 'typescript'});

module.exports = {
  entry: __dirname + '/src/index.tsx',
  output: {
    path: __dirname + '/build',
    filename: 'static/js/[name].[chunkhash:8].js',
    publicPath: '/',
  },
  resolve: {
    extensions: ['.ts', '.tsx', '.js', '.json'],
  },
  module: {
    rules: [tsRule],
  },
  plugins: [new HtmlWebpackPlugin()],
};


text:
template<int>
class Program {
} ;

template<>
class Program<0> {
public:
   inline friend float EvalNextArg()
        { return 1.0 ; }
} ;


text: All kinds of web delpoyment config files, which can be used in development and deployment phases.


text:
package com.asakusafw.m3bp.mirror.jni;

import java.text.MessageFormat;

import com.asakusafw.lang.utils.common.Arguments;
import com.asakusafw.m3bp.descriptor.M3bpVertexDescriptor;
import com.asakusafw.m3bp.mirror.FlowGraphMirror;
import com.asakusafw.m3bp.mirror.Identifier;
import com.asakusafw.m3bp.mirror.PortMirror;
import com.asakusafw.m3bp.mirror.VertexMirror;
import com.asakusafw.m3bp.mirror.basic.AbstractFlowGraphMirror;

/**
 * JNI bridge of {@link FlowGraphMirror}.
 */
public class FlowGraphMirrorImpl extends AbstractFlowGraphMirror implements NativeMirror {

    private final Pointer reference;

    FlowGraphMirrorImpl(Pointer reference) {
        this.reference = reference;
    }

    @Override
    public Pointer getPointer() {
        return reference;
    }

    @Override
    protected VertexMirror createVertex(Identifier id, String name, M3bpVertexDescriptor descriptor) {
        Arguments.requireNonNull(id);
        Arguments.requireNonNull(name);
        Arguments.requireNonNull(descriptor);
        Pointer ref = new Pointer(addVertex0(getPointer().getAddress(), name));
        VertexMirror vertex = new VertexMirrorImpl(ref, name, descriptor);
        return vertex;
    }

    @Override
    protected void internalAddEdge(PortMirror upstream, PortMirror downstream) {
        Arguments.requireNonNull(upstream);
        Arguments.requireNonNull(downstream);
        Pointer up = NativeMirror.getPointer(upstream);
        Pointer down = NativeMirror.getPointer(downstream);
        addEdge0(getPointer().getAddress(), up.getAddress(), down.getAddress());
    }

    @Override
    public String toString() {
        return MessageFormat.format(
                "FlowGraphMirror[{0}](vertices={1})", //$NON-NLS-1$
                getPointer(),
                getVertices().size());
    }

    private static native long addVertex0(long self, String name);

    private static native void addEdge0(long self, long upstream, long downstream);
}


text:
@setlocal

@set node_name=jb_server

@rem Get the absolute path to the parent directory,
@rem which is assumed to be the node root.
@for /F "delims=" %%I in ("%~dp0..") do @set node_root=%%~fI

@set releases_dir=%node_root%\releases

@rem Parse ERTS version and release version from start_erl.data
@for /F "usebackq tokens=1,2" %%I in ("%releases_dir%\start_erl.data") do @(
    @call :set_trim erts_version %%I
    @call :set_trim release_version %%J
)

@set vm_args=%releases_dir%\%release_version%\vm.args
@set sys_config=%releases_dir%\%release_version%\sys.config
@set node_boot_script=%releases_dir%\%release_version%\%node_name%
@set clean_boot_script=%releases_dir%\%release_version%\start_clean

@rem extract erlang cookie from vm.args
@for /f "usebackq tokens=1-2" %%I in (`findstr /b \-setcookie "%vm_args%"`) do @set erlang_cookie=%%J

@set erts_bin=%node_root%\erts-%erts_version%\bin

@set service_name=%node_name%_%release_version%

@set erlsrv="%erts_bin%\erlsrv.exe"
@set epmd="%erts_bin%\epmd.exe"
@set escript="%erts_bin%\escript.exe"
@set werl="%erts_bin%\werl.exe"

@if "%1"=="usage" @goto usage
@if "%1"=="install" @goto install
@if "%1"=="uninstall" @goto uninstall
@if "%1"=="start" @goto start
@if "%1"=="stop" @goto stop
@if "%1"=="restart" @call :stop && @goto start
@if "%1"=="console" @goto console
@if "%1"=="query" @goto query
@if "%1"=="attach" @goto attach
@if "%1"=="upgrade" @goto upgrade
@echo Unknown command: "%1"

:usage
@echo Usage: %~n0 [install^|uninstall^|start^|stop^|restart^|console^|query^|attach^|upgrade]
@goto :EOF

:install
@set description=Erlang node %node_name% in %node_root%
@set start_erl=%node_root%\bin\start_erl.cmd
@set args= ++ %node_name% ++ %node_root%
@%erlsrv% add %service_name% -c "%description%" -sname %node_name% -w "%node_root%" -m "%start_erl%" -args "%args%" -stopaction "init:stop()."
@goto :EOF

:uninstall
@%erlsrv% remove %service_name%
@%epmd% -kill
@goto :EOF

:start
@%erlsrv% start %service_name%
@goto :EOF

:stop
@%erlsrv% stop %service_name%
@goto :EOF

:console
@start "%node_name% console" %werl% -boot "%node_boot_script%" -config "%sys_config%" -args_file "%vm_args%" -sname %node_name%
@goto :EOF

:query
@%erlsrv% list %service_name%
@exit %ERRORLEVEL%
@goto :EOF

:attach
@for /f "usebackq" %%I in (`hostname`) do @set hostname=%%I
start "%node_name% attach" %werl% -boot "%clean_boot_script%" -remsh %node_name%@%hostname% -sname console -setcookie %erlang_cookie%
@goto :EOF

:upgrade
@if "%2"=="" (
    @echo Missing upgrade package argument
    @echo Usage: %~n0 upgrade {package base name}
    @echo NOTE {package base name} MUST NOT include the .tar.gz suffix
    @goto :EOF
)
@%escript% %node_root%\bin\install_upgrade.escript %node_name% %erlang_cookie% %2
@goto :EOF

:set_trim
@set %1=%2
@goto :EOF


text:
#ifndef itkRectangularImageNeighborhoodShape_h
#define itkRectangularImageNeighborhoodShape_h

#include <algorithm> // For transform.
#include <cassert>

#include "itkOffset.h"
#include "itkSize.h"

namespace itk
{

/**
 * \class RectangularImageNeighborhoodShape
 * Rectangular (or hyperrectangular) image-neighborhood shape.
 * Eases creating a sequence of offsets for ShapedImageNeighborhoodRange.
 * Can also be used for ShapedNeighborhoodIterator.
 *
 * The following example creates a 3 x 5 rectangular neighborhood around
 * pixel location [10, 20], and generates the offsets for a neighborhood range:
 \code
  const Index<> location = { 10, 20 };
  const Size<> radius = { { 1, 2 } };
  const RectangularImageNeighborhoodShape<2> shape{ radius };
  const std::vector<Offset<>> offsets = GenerateImageNeighborhoodOffsets(shape);
  ShapedImageNeighborhoodRange<ImageType> neighborhoodRange{ *image, location, offsets };
 \endcode
 *
 * \see ShapedNeighborhoodIterator
 * \see ShapedImageNeighborhoodRange
 * \ingroup ImageIterators
 * \ingroup ITKCommon
 */
template <unsigned int VImageDimension>
class RectangularImageNeighborhoodShape
{
public:
  static constexpr unsigned int ImageDimension = VImageDimension;

  /** Constructs a hyperrectangular shape whose size is specified by the radius */
  constexpr explicit RectangularImageNeighborhoodShape(const Size<ImageDimension> & radius) noexcept
    : m_Radius(radius)
    , m_NumberOfOffsets(CalculateNumberOfOffsets(ImageDimension))
  {}

  /** Returns the number of offsets needed to represent this shape. */
  constexpr size_t
  GetNumberOfOffsets() const noexcept
  {
    return m_NumberOfOffsets;
  }

  /** Fills the specified buffer with the offsets for a neighborhood of this shape. */
  void
  FillOffsets(Offset<ImageDimension> * const offsets) const noexcept
  {
    if (m_NumberOfOffsets > 0)
    {
      assert(offsets != nullptr);
      Offset<ImageDimension> offset;

      std::transform(m_Radius.begin(), m_Radius.end(), offset.begin(), [](const SizeValueType radiusValue) {
        return -static_cast<OffsetValueType>(radiusValue);
      });

      for (size_t i = 0; i < m_NumberOfOffsets; ++i)
      {
        offsets[i] = offset;

        for (unsigned int dimensionIndex = 0; dimensionIndex < ImageDimension; ++dimensionIndex)
        {
          OffsetValueType & offsetValue = offset[dimensionIndex];

          ++offsetValue;

          if (offsetValue <= static_cast<OffsetValueType>(m_Radius[dimensionIndex]))
          {
            break;
          }
          offsetValue = -static_cast<OffsetValueType>(m_Radius[dimensionIndex]);
        }
      }
    }
  }

private:
  // The radius of the neighborhood along each direction.
  Size<ImageDimension> m_Radius;

  // The number of offsets needed to represent this shape.
  size_t m_NumberOfOffsets;

  // Private helper function to calculate the number of Offsets by a recursive
  // function call. Recursion is necessary for C++11 constexpr.
  constexpr size_t
  CalculateNumberOfOffsets(const unsigned int dimension) const noexcept
  {
    return (dimension == 0)
             ? 1
             : (2 * m_Radius.m_InternalArray[dimension - 1] + 1) * CalculateNumberOfOffsets(dimension - 1);
  }
};

} // namespace itk

#endif


text: var foo = require('foo');


text:
package com.djs.learn.simpleframework;

/**
 * Main interface thread.
 *

 * Update log: (date / author : comments)
 *

 *
2008-03-26 / Du Jiang : Creation
 *

 *
 * @version 1.0.0.0
 */
public class MainInterfaceThread implements Runnable
{
	private MainInterface mi = null;

	/**
	 * @param mi
	 *        Main interface.
	 */
	public MainInterfaceThread(MainInterface mi){
		this.mi = mi;
	}

	/**
	 * Run.
	 */
	public void run(){
		mi.fnSetupInterface();
	}
}


text:
<?php LandingRecentItems('online-learning', 3) ?>
<?php get_template_part( 'parts/ads/lb-landingpage-2' ); ?>
<?php LandingRecentItems('cloud-computing', 3) ?>
<?php get_template_part( 'parts/ads/lb-landingpage-3' ); ?>
<?php LandingRecentItems('policy', 3) ?>
<?php get_template_part( 'parts/ads/lb-landingpage-4' ); ?>
<?php LandingRecentItems('technologies', 3) ?>


text:
Append the specified string to the existing value for each object in
\code{space} that matches \code{checks}.

\input{\topdir/client/fragments/group_operation}


text:
import { bindActionCreators } from "redux";
import { connect } from "react-redux";
import {
  getTodos,
  setFilterCurrent,
  setFilterDone
} from "src/redux/modules/examples/todos";
import getVisibleTodos from "src/selectors/getVisibleTodos";
import type { Todo } from "src/redux/modules/examples/todos";
import type { RootReducerState } from "src/redux/modules";
import Todos from "./Todos";

type StateProps = {
  // Always put the asterisk or it assumes 'empty'
  todos: Array<Todo>,
  filter: string
};

const mapStateToProps = (state: RootReducerState): StateProps => ({
  todos: getVisibleTodos(state),
  filter: state.examples.todos.filter
});

type DispatchProps = {
  setFilterCurrent: Function,
  setFilterDone: Function,
  getTodos: Function
};

const mapDispatchToProps = (dispatch: any): DispatchProps =>
  bindActionCreators(
    {
      setFilterCurrent,
      setFilterDone,
      getTodos
    },
    dispatch
  );

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Todos);
export type ReduxProps = StateProps & DispatchProps;


text:
package com.defano.wyldcard.part.builder;

import com.defano.hypertalk.ast.model.Value;
import com.defano.wyldcard.part.card.CardModel;
import com.defano.wyldcard.part.stack.StackModel;

import java.awt.image.BufferedImage;

public class CardModelBuilder extends PartModelBuilder<CardModel, CardModelBuilder> {

    private final CardModel model;

    public CardModelBuilder(StackModel parentPartModel) {
        model = new CardModel(parentPartModel);
    }

    public CardModelBuilder withBackgroundId(int backgroundId) {
        model.setBackgroundId(backgroundId);
        return this;
    }

    public CardModelBuilder withIsMarked(Object isMarked) {
        model.set(context, CardModel.PROP_MARKED, new Value(isMarked));
        return this;
    }

    public CardModelBuilder withCantDelete(Object v) {
        model.set(context, CardModel.PROP_CANTDELETE, new Value(v));
        return this;
    }

    public CardModelBuilder withDontSearch(Object v) {
        model.set(context, CardModel.PROP_DONTSEARCH, new Value(v));
        return this;
    }

    public CardModelBuilder withShowPict(Object v) {
        model.set(context, CardModel.PROP_SHOWPICT, new Value(v));
        return this;
    }

    public CardModelBuilder withImage(BufferedImage v) {
        model.setCardImage(v);
        return this;
    }

    @Override
    public CardModel build() {
        return model;
    }

    @Override
    public CardModelBuilder getBuilder() {
        return this;
    }
}