text:
extern crate cargo;
extern crate cargotest;
extern crate hamcrest;

use std::env;
use std::fs::{self, File};
use std::io::prelude::*;
use std::path::{Path, PathBuf};
use std::str;

use cargotest::cargo_process;
use cargotest::support::paths::{self, CargoPathExt};
use cargotest::support::{execs, project, Project, basic_bin_manifest};
use hamcrest::{assert_that, existing_file};

#[cfg_attr(windows,allow(dead_code))]
enum FakeKind<'a> {
    Executable,
    Symlink{target:&'a Path},
}

/// Add an empty file with executable flags (and platform-dependent suffix).
/// TODO: move this to `Project` if other cases using this emerge.
fn fake_file(proj: Project, dir: &Path, name: &str, kind: &FakeKind) -> Project {
    let path = proj.root().join(dir).join(&format!("{}{}", name,
                                                   env::consts::EXE_SUFFIX));
    path.parent().unwrap().mkdir_p();
    match *kind {
        FakeKind::Executable => {
            File::create(&path).unwrap();
            make_executable(&path);
        },
        FakeKind::Symlink{target} => {
            make_symlink(&path,target);
        }
    }
    return proj;

    #[cfg(unix)]
    fn make_executable(p: &Path) {
        use std::os::unix::prelude::*;

        let mut perms = fs::metadata(p).unwrap().permissions();
        let mode = perms.mode();
        perms.set_mode(mode | 0o111);
        fs::set_permissions(p, perms).unwrap();
    }
    #[cfg(windows)]
    fn make_executable(_: &Path) {}
    #[cfg(unix)]
    fn make_symlink(p: &Path, t: &Path) {
        ::std::os::unix::fs::symlink(t,p).expect("Failed to create symlink");
    }
    #[cfg(windows)]
    fn make_symlink(_: &Path, _: &Path) {
        panic!("Not supported")
    }
}

fn path() -> Vec<PathBuf> {
    env::split_paths(&env::var_os("PATH").unwrap_or_default()).collect()
}

#[test]
fn list_command_looks_at_path() {
    let proj = project("list-non-overlapping").build();
    let proj = fake_file(proj, Path::new("path-test"), "cargo-1", &FakeKind::Executable);
    let mut pr = cargo_process();

    let mut path = path();
    path.push(proj.root().join("path-test"));
    let path = env::join_paths(path.iter()).unwrap();
    let output = pr.arg("-v").arg("--list")
                   .env("PATH", &path);
    let output = output.exec_with_output().unwrap();
    let output = str::from_utf8(&output.stdout).unwrap();
    assert!(output.contains("\n    1\n"), "missing 1: {}", output);
}

// windows and symlinks don't currently agree that well
#[cfg(unix)]
#[test]
fn list_command_resolves_symlinks() {
    use cargotest::support::cargo_exe;

    let proj = project("list-non-overlapping").build();
    let proj = fake_file(proj, Path::new("path-test"), "cargo-2",
                         &FakeKind::Symlink{target:&cargo_exe()});
    let mut pr = cargo_process();

    let mut path = path();
    path.push(proj.root().join("path-test"));
    let path = env::join_paths(path.iter()).unwrap();
    let output = pr.arg("-v").arg("--list")
                   .env("PATH", &path);
    let output = output.exec_with_output().unwrap();
    let output = str::from_utf8(&output.stdout).unwrap();
    assert!(output.contains("\n    2\n"), "missing 2: {}", output);
}

#[test]
fn find_closest_biuld_to_build() {
    let mut pr = cargo_process();
    pr.arg("biuld");

    assert_that(pr,
                execs().with_status(101)
                       .with_stderr("[ERROR] no such subcommand: `biuld`

<tab>Did you mean `build`?

"));
}

// if a subcommand is more than 3 edit distance away, we don't make a suggestion
#[test]
fn find_closest_dont_correct_nonsense() {
    let mut pr = cargo_process();
    pr.arg("there-is-no-way-that-there-is-a-command-close-to-this")
      .cwd(&paths::root());

    assert_that(pr,
                execs().with_status(101)
                       .with_stderr("[ERROR] no such subcommand: \
                        `there-is-no-way-that-there-is-a-command-close-to-this`
"));
}

#[test]
fn displays_subcommand_on_error() {
    let mut pr = cargo_process();
    pr.arg("invalid-command");

    assert_that(pr,
                execs().with_status(101)
                       .with_stderr("[ERROR] no such subcommand: `invalid-command`
"));
}

#[test]
fn override_cargo_home() {
    let root = paths::root();
    let my_home = root.join("my_home");
    fs::create_dir(&my_home).unwrap();
    File::create(&my_home.join("config")).unwrap().write_all(br#"
        [cargo-new]
        name = "foo"
        email = "bar"
        git = false
    "#).unwrap();

    assert_that(cargo_process()
                    .arg("new").arg("foo")
                    .env("USER", "foo")
                    .env("CARGO_HOME", &my_home),
                execs().with_status(0));

    let toml = paths::root().join("foo/Cargo.toml");
    let mut contents = String::new();
    File::open(&toml).unwrap().read_to_string(&mut contents).unwrap();
    assert!(contents.contains(r#"authors = ["foo <bar>"]"#));
}

#[test]
fn cargo_subcommand_env() {
    use cargotest::support::cargo_exe;

    let src = format!(r#"
        use std::env;

        fn main() {{
            println!("{{}}", env::var("{}").unwrap());
        }}
        "#, cargo::CARGO_ENV);

    let p = project("cargo-envtest")
        .file("Cargo.toml", &basic_bin_manifest("cargo-envtest"))
        .file("src/main.rs", &src)
        .build();

    let target_dir = p.target_debug_dir();

    assert_that(p.cargo("build"), execs().with_status(0));
    assert_that(&p.bin("cargo-envtest"), existing_file());

    let mut pr = cargo_process();
    let cargo = cargo_exe().canonicalize().unwrap();
    let mut path = path();
    path.push(target_dir);
    let path = env::join_paths(path.iter()).unwrap();

    assert_that(pr.arg("envtest").env("PATH", &path),
                execs().with_status(0).with_stdout(cargo.to_str().unwrap()));
}

#[test]
fn cargo_help() {
    assert_that(cargo_process(),
                execs().with_status(0));
    assert_that(cargo_process().arg("help"),
                execs().with_status(0));
    assert_that(cargo_process().arg("-h"),
                execs().with_status(0));
    assert_that(cargo_process().arg("help").arg("build"),
                execs().with_status(0));
    assert_that(cargo_process().arg("build").arg("-h"),
                execs().with_status(0));
    assert_that(cargo_process().arg("help").arg("-h"),
                execs().with_status(0));
    assert_that(cargo_process().arg("help").arg("help"),
                execs().with_status(0));
}

#[test]
fn explain() {
    assert_that(cargo_process().arg("--explain").arg("E0001"),
                execs().with_status(0));
}


text:
alter table metric
   drop constraint metric_key_unique_idx;

redpajama_set_name: RedPajamaGithub


text:
/// <reference path="../node_modules/rx/ts/rx.all.d.ts" />

export class Notification<T> {
    hasValue: boolean;

    constructor(public kind: string, public value?: T, public error?: any) {
        this.hasValue = kind === 'N';
    }

    /**
     * Delivers to the given `observer` the value wrapped by this Notification.
     * @param {Observer} observer
     * @return
     */
    observe(observer: Rx.Observer<T>): any {
        switch (this.kind) {
            case 'N':
                return observer.onNext && observer.onNext(this.value);
            case 'E':
                return observer.onError && observer.onError(this.error);
            case 'C':
                return observer.onCompleted && observer.onCompleted();
        }
    }

    /**
     * Given some {@link Observer} callbacks, deliver the value represented by the
     * current Notification to the correctly corresponding callback.
     * @param {function(value: T): void} next An Observer `next` callback.
     * @param {function(err: any): void} [error] An Observer `error` callback.
     * @param {function(): void} [complete] An Observer `complete` callback.
     * @return {any}
     */
    do(next: (value: T) => void, error?: (err: any) => void, complete?: () => void): any {
        const kind = this.kind;
        switch (kind) {
            case 'N':
                return next && next(this.value);
            case 'E':
                return error && error(this.error);
            case 'C':
                return complete && complete();
        }
    }

    /**
     * Takes an Observer or its individual callback functions, and calls `observe`
     * or `do` methods accordingly.
     * @param {Observer|function(value: T): void} nextOrObserver An Observer or
     * the `next` callback.
     * @param {function(err: any): void} [error] An Observer `error` callback.
     * @param {function(): void} [complete] An Observer `complete` callback.
     * @return {any}
     */
    accept(nextOrObserver: Rx.Observer<T> | ((value: T) => void), error?: (err: any) => void, complete?: () => void) {
        if (nextOrObserver && typeof (<Rx.Observer<T>>nextOrObserver).onNext === 'function') {
            return this.observe(<Rx.Observer<T>>nextOrObserver);
        } else {
            return this.do(<(value: T) => void>nextOrObserver, error, complete);
        }
    }

    /**
     * Returns a simple Observable that just delivers the notification represented
     * by this Notification instance.
     * @return {any}
     */
    toObservable(rx: typeof Rx): Rx.Observable<T> {
        const kind = this.kind;
        switch (kind) {
            case 'N':
                return rx.Observable.of(this.value);
            case 'E':
                return rx.Observable.throw<T>(this.error);
            case 'C':
                return rx.Observable.empty<T>();
        }
        throw new Error('unexpected notification kind value');
    }

    private static completeNotification: Notification<any> = new Notification('C');
    private static undefinedValueNotification: Notification<any> = new Notification('N', undefined);

    /**
     * A shortcut to create a Notification instance of the type `next` from a
     * given value.
     * @param {T} value The `next` value.
     * @return {Notification<T>} The "next" Notification representing the
     * argument.
     */
    static createNext<T>(value: T): Notification<T> {
        if (typeof value !== 'undefined') {
            return new Notification('N', value);
        }
        return this.undefinedValueNotification;
    }

    /**
     * A shortcut to create a Notification instance of the type `error` from a
     * given error.
     * @param {any} [err] The `error` error.
     * @return {Notification<T>} The "error" Notification representing the
     * argument.
     */
    static createError<T>(err?: any): Notification<T> {
        return new Notification('E', undefined, err);
    }

    /**
     * A shortcut to create a Notification instance of the type `complete`.
     * @return {Notification<any>} The valueless "complete" Notification.
     */
    static createComplete(): Notification<any> {
        return this.completeNotification;
    }
}


text:
function checkGradMarginalRbfGP()
%CHECKGRADMARGINALRBFGP checkGradMarginalRbfGP()
%  Check gradients for nMarginalRbfGP().
%
% See also
%   nMarginalRbfGP

%rng(100, 'twister');
N = 100;
D = 10;
theta = rand(N*D+3, 1);
y = rand(N, 1);
[~, delta] = gradchek(theta', @f, @grad, y);
maxDiff = max(abs(delta));
assert(maxDiff < 1e-7,...
    ['test nMarginalRbfGP() failed with max diff ' num2str(maxDiff)]);
disp('test nMarginalRbfGP() passed');

bias = rand;
[~, delta] = gradchek(bias, @fbias, @gradbias, theta', y);
assert(maxDiff < 1e-7,...
    ['test nMarginalRbfGP() for bias failed with max diff ' num2str(maxDiff)]);
disp('test nMarginalRbfGP() for bias passed');

function obj = f(theta, y)
  obj = nMarginalRbfGP(theta, y);
end

function obj = fbias(bias, theta, y)
  obj = nMarginalRbfGP(theta, y, bias);
end

function g = grad(theta, y)
  [~, g] = nMarginalRbfGP(theta, y);
end

function g = gradbias(bias, theta, y)
  [~, ~, g] = nMarginalRbfGP(theta, y, bias);
end
end


text:
#import <DevToolsInterface/XCOrganizerNodeInfo.h>

@class NSViewController, XCRemoteComputer;

@interface XCOrganizerDeviceNodeInfo : XCOrganizerNodeInfo
{
    XCRemoteComputer *remoteComputer;
    NSViewController *viewController;
}

+ (id)keyPathsForValuesAffectingStatusImage;
+ (id)keyPathsForValuesAffectingIconImage;
+ (id)keyPathsForValuesAffectingName;
+ (id)keyPathsForValuesAffectingDeviceAvailable;
+ (id)nodeInfoWithRemoteComputer:(id)arg1;
@property(retain) NSViewController *viewController; // @synthesize viewController;
@property(retain) XCRemoteComputer *remoteComputer; // @synthesize remoteComputer;
- (id)statusImage;
- (id)iconImage;
- (id)name;
@property(readonly) BOOL deviceAvailable;
- (void)invalidate;
- (void)dealloc;

@end


text:
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateChocolateyUsersPreferencesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('chocolatey_users_preferences', function (Blueprint $table) {
            $table->integer('user_id');
            $table->enum('emailFriendRequestNotificationEnabled', ['1', '0'])->default('0');
            $table->enum('emailGiftNotificationEnabled', ['1', '0'])->default('0');
            $table->enum('emailGroupNotificationEnabled', ['1', '0'])->default('0');
            $table->enum('emailMiniMailNotificationEnabled', ['1', '0'])->default('0');
            $table->enum('emailNewsletterEnabled', ['1', '0'])->default('0');
            $table->enum('emailRoomMessageNotificationEnabled', ['1', '0'])->default('0');
            $table->enum('friendCanFollow', ['1', '0'])->default('0');
            $table->enum('friendRequestEnabled', ['1', '0'])->default('0');
            $table->enum('offlineMessagingEnabled', ['1', '0'])->default('0');
            $table->enum('onlineStatusVisible', ['1', '0'])->default('1');
            $table->enum('profileVisible', ['1', '0'])->default('1');
            $table->primary('user_id', 'chocolatey_users_preferences_primary');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('chocolatey_users_preferences');
    }
}


text:
MUSIC_DIR="/mpd/music"

if [ ! -d $MUSIC_DIR ]; then
    echo "Music dir not found."
    exit 1
fi

touch /mpd/cache/tag_cache
touch /mpd/cache/state
touch /mpd/cache/sticker.sql
chmod -R 0774 /mpd/cache
chown -R mpd: /mpd/cache

echo "Starting MPD..."
exec sudo -u mpd mpd --no-daemon --stdout --verbose /etc/mpd.conf $@


text:
package com.emc.storageos.model.block;

import org.codehaus.jackson.annotate.JsonProperty;

import javax.xml.bind.annotation.XmlElement;
import java.net.URI;

/**
 * A tuple specifying the data for a migration.
 */
public class VolumeMigrationInfo {

    private URI volume;
    private URI storageSystem;
    private URI virtualPool;

    public VolumeMigrationInfo() {
    }

    public VolumeMigrationInfo(URI volume, URI storageSystem, URI virtualPool) {
        this.volume = volume;
        this.storageSystem = storageSystem;
        this.virtualPool = virtualPool;
    }

    /**
     * This parameter specifies the id of the
     * volume to be migrated.
     *
     */
    @XmlElement(required = true, name = "volume")
    public URI getVolume() {
        return volume;
    }

    public void setVolume(URI volume) {
        this.volume = volume;
    }

    /**
     * This parameter specifies the id of the
     * storage system to which the volume is to
     * be migrated.
     *
     */
    @XmlElement(required = true, name = "storage_system")
    public URI getStorageSystem() {
        return storageSystem;
    }

    public void setStorageSystem(URI storageSystem) {
        this.storageSystem = storageSystem;
    }

    /**
     * This parameter specifies (optional) the id of the
     * virtual pool to which the volume is to be migrated.
     *
     */
    @XmlElement(name = "vpool")
    @JsonProperty("vpool")
    public URI getVirtualPool() {
        return virtualPool;
    }

    public void setVirtualPool(URI virtualPool) {
        this.virtualPool = virtualPool;
    }

}


text:
import asposetaskscloud
from asposetaskscloud.TasksApi import TasksApi
from asposetaskscloud.TasksApi import ApiException

import asposestoragecloud
from asposestoragecloud.StorageApi import StorageApi
from asposestoragecloud.StorageApi import ResponseMessage

apiKey = "XXXXX" #sepcify App Key
appSid = "XXXXX" #sepcify App SID
apiServer = "http://api.aspose.com/v1.1"
data_folder = "../../data/"

#Instantiate Aspose Storage API SDK
storage_apiClient = asposestoragecloud.ApiClient.ApiClient(apiKey, appSid, True)
storageApi = StorageApi(storage_apiClient)
#Instantiate Aspose Tasks API SDK
api_client = asposetaskscloud.ApiClient.ApiClient(apiKey, appSid, True)
tasksApi = TasksApi(api_client);

#set input file name
fileName = "sample-project"
name = fileName + ".mpp"
format = "pdf"

try:
    #upload file to aspose cloud storage
    response = storageApi.PutCreate(name, data_folder + name)

    #invoke Aspose.Tasks Cloud SDK API to convert project document to other formats
    response = tasksApi.GetTaskDocumentWithFormat(name, format)

    if response.Status == "OK":
        #download converted doc from api response
        outfilename = "c:/temp/" + fileName + "." + format
        with open(outfilename, 'wb') as f:
                    for chunk in response.InputStream:
                        f.write(chunk)

except ApiException as ex:
            print "ApiException:"
            print "Code:" + str(ex.code)
            print "Message:" + ex.message


text:
'use strict';

/**
 * Module dependencies.
 */
var passport = require('passport');

module.exports = function(app) {
	// User Routes
	var users = require('../../app/controllers/users');
	app.route('/users/me').get(users.me);
	app.route('/users').put(users.update);
	app.route('/users/edit/:userId').put(users.edit);
	app.route('/users/password').post(users.changePassword);
	app.route('/users/accounts').delete(users.removeOAuthProvider);

	// Setting up the users api
	app.route('/auth/signup').post(users.signup);
	app.route('/auth/signin').post(users.signin);
	app.route('/auth/signout').get(users.signout);

	//followers and following
	app.route('/users/followers/:userId')
		 .get(users.listFollowers)
		 .post( users.signin, users.followers );

	app.route('/users/following/:userId')
		 .get(users.listFollowing)
		 .post( users.signin, users.following );

	// Setting the facebook oauth routes
	app.route('/auth/facebook').get(passport.authenticate('facebook', {
		scope: ['email']
	}));
	app.route('/auth/facebook/callback').get(users.oauthCallback('facebook'));

	// Setting the twitter oauth routes
	app.route('/auth/twitter').get(passport.authenticate('twitter'));
	app.route('/auth/twitter/callback').get(users.oauthCallback('twitter'));

	// Setting the google oauth routes
	app.route('/auth/google').get(passport.authenticate('google', {
		scope: [
			'https://www.googleapis.com/auth/userinfo.profile',
			'https://www.googleapis.com/auth/userinfo.email'
		]
	}));
	app.route('/auth/google/callback').get(users.oauthCallback('google'));

	// Setting the linkedin oauth routes
	app.route('/auth/linkedin').get(passport.authenticate('linkedin'));
	app.route('/auth/linkedin/callback').get(users.oauthCallback('linkedin'));

	// Finish by binding the user middleware
	app.param('userId', users.userByID);
};


text:
package com.netflix.iep.lwc.fwd.admin

object Main {

  def main(args: Array[String]): Unit = {
    com.netflix.iep.spring.Main.main(args)
  }
}


text:
<?php

if(!defined('WPINC')) // MUST have WordPress.
	exit('Do not access this file directly.');

if(!class_exists('c_ws_plugin__s2member_pro_utils_ops'))
{
	/**
	 * s2Member Pro option utilities.
	 *
	 * @package s2Member\Utilities
	 * @since 110815
	 */
	class c_ws_plugin__s2member_pro_utils_ops
	{
		/**
		 * Handles s2Member option Replacement Codes.
		 *
		 * @package s2Member\Utilities
		 * @since 110815
		 *
		 * @param array $ops An array of s2Member options, or an option value array.
		 * @param bool  $fill Optional. If true, Replacement Codes are filled, else false.
		 *
		 * @return mixed The end result, after handling Replacement Codes.
		 */
		public static function op_replace($ops = array(), $fill = FALSE)
		{
			global $current_site, $current_blog; // Multisite.

			if(is_array($ops) && !empty($ops)) // Only if array.
			{
				foreach($ops as &$op) // Begin looping sequence.
				{
					if(is_array($op) && !empty($op)) // Array?
						$op = c_ws_plugin__s2member_pro_utils_ops::op_replace($op, $fill);

					else if(is_string($op) && !$fill) // Handle Replacement Codes.
					{
						$op = (is_multisite()) ? preg_replace('/'.preg_quote(rtrim($current_site->domain.$current_site->path, '/').'/', '/').'/', '%%_op__current_site_domain_path/%%', $op) : $op;
						$op = (is_multisite()) ? preg_replace('/'.preg_quote(rtrim($current_site->domain.$current_site->path, '/'), '/').'/', '%%_op__current_site_domain_path%%', $op) : $op;

						$op = (is_multisite()) ? preg_replace('/'.preg_quote(rtrim($current_blog->domain.$current_blog->path, '/').'/', '/').'/', '%%_op__current_blog_domain_path/%%', $op) : $op;
						$op = (is_multisite()) ? preg_replace('/'.preg_quote(rtrim($current_blog->domain.$current_blog->path, '/'), '/').'/', '%%_op__current_blog_domain_path%%', $op) : $op;

						$op = preg_replace('/'.preg_quote(rtrim(site_url(), '/'), '/').'/', '%%_op__site_url%%', preg_replace('/'.preg_quote(rtrim(site_url(), '/').'/', '/').'/', '%%_op__site_url/%%', $op));
						$op = preg_replace('/'.preg_quote(rtrim(home_url(), '/'), '/').'/', '%%_op__home_url%%', preg_replace('/'.preg_quote(rtrim(home_url(), '/').'/', '/').'/', '%%_op__home_url/%%', $op));

						$op = preg_replace('/'.preg_quote($_SERVER['HTTP_HOST'], '/').'/i', '%%_op__domain%%', ((get_bloginfo('name')) ? preg_replace('/'.preg_quote(get_bloginfo('name'), '/').'/', '%%_op__blog_name%%', $op) : $op));
					}
					else if(is_string($op) && $fill) // Handle Replacement Codes.
					{
						$op = (is_multisite()) ? preg_replace('/%%_op__current_site_domain_path\/%%/i', c_ws_plugin__s2member_utils_strings::esc_refs(rtrim($current_site->domain.$current_site->path, '/').'/'), $op) : preg_replace('/%%_op__current_site_domain_path\/%%/i', c_ws_plugin__s2member_utils_strings::esc_refs(rtrim(home_url(), '/').'/'), $op);
						$op = (is_multisite()) ? preg_replace('/%%_op__current_site_domain_path%%/i', c_ws_plugin__s2member_utils_strings::esc_refs(rtrim($current_site->domain.$current_site->path, '/')), $op) : preg_replace('/%%_op__current_site_domain_path%%/i', c_ws_plugin__s2member_utils_strings::esc_refs(rtrim(home_url(), '/')), $op);

						$op = (is_multisite()) ? preg_replace('/%%_op__current_blog_domain_path\/%%/i', c_ws_plugin__s2member_utils_strings::esc_refs(rtrim($current_blog->domain.$current_blog->path, '/').'/'), $op) : preg_replace('/%%_op__current_blog_domain_path\/%%/i', c_ws_plugin__s2member_utils_strings::esc_refs(rtrim(home_url(), '/').'/'), $op);
						$op = (is_multisite()) ? preg_replace('/%%_op__current_blog_domain_path%%/i', c_ws_plugin__s2member_utils_strings::esc_refs(rtrim($current_blog->domain.$current_blog->path, '/')), $op) : preg_replace('/%%_op__current_blog_domain_path%%/i', c_ws_plugin__s2member_utils_strings::esc_refs(rtrim(home_url(), '/')), $op);

						$op = preg_replace('/%%_op__site_url%%/i', c_ws_plugin__s2member_utils_strings::esc_refs(rtrim(site_url(), '/')), preg_replace('/%%_op__site_url\/%%/i', c_ws_plugin__s2member_utils_strings::esc_refs(rtrim(site_url(), '/').'/'), $op));
						$op = preg_replace('/%%_op__home_url%%/i', c_ws_plugin__s2member_utils_strings::esc_refs(rtrim(home_url(), '/')), preg_replace('/%%_op__home_url\/%%/i', c_ws_plugin__s2member_utils_strings::esc_refs(rtrim(home_url(), '/').'/'), $op));

						$op = preg_replace('/%%_op__domain%%/i', c_ws_plugin__s2member_utils_strings::esc_refs($_SERVER['HTTP_HOST']), preg_replace('/%%_op__blog_name%%/i', c_ws_plugin__s2member_utils_strings::esc_refs(get_bloginfo('name')), $op));
					}
				}
			}
			return $ops; // Now return the $ops.
		}
	}
}


text:
package dotty.tools.dotc.semanticdb
import dotty.tools.dotc.semanticdb.internal._
import scala.annotation.internal.sharable

@SerialVersionUID(0L)
final case class Documentation(
    message: _root_.scala.Predef.String = "",
    format: dotty.tools.dotc.semanticdb.Documentation.Format = dotty.tools.dotc.semanticdb.Documentation.Format.HTML
    )  extends SemanticdbGeneratedMessage  derives CanEqual {
    @transient @sharable
    private[this] var __serializedSizeMemoized: _root_.scala.Int = 0
    private[this] def __computeSerializedSize(): _root_.scala.Int = {
      var __size = 0

      {
        val __value = message
        if (!__value.isEmpty) {
          __size += SemanticdbOutputStream.computeStringSize(1, __value)
        }
      };

      {
        val __value = format.value
        if (__value != 0) {
          __size += SemanticdbOutputStream.computeEnumSize(2, __value)
        }
      };
      __size
    }
    override def serializedSize: _root_.scala.Int = {
      var __size = __serializedSizeMemoized
      if (__size == 0) {
        __size = __computeSerializedSize() + 1
        __serializedSizeMemoized = __size
      }
      __size - 1

    }
    def writeTo(`_output__`: SemanticdbOutputStream): _root_.scala.Unit = {
      {
        val __v = message
        if (!__v.isEmpty) {
          _output__.writeString(1, __v)
        }
      };
      {
        val __v = format.value
        if (__v != 0) {
          _output__.writeEnum(2, __v)
        }
      };
    }
    def withMessage(__v: _root_.scala.Predef.String): Documentation = copy(message = __v)
    def withFormat(__v: dotty.tools.dotc.semanticdb.Documentation.Format): Documentation = copy(format = __v)

    // @@protoc_insertion_point(GeneratedMessage[dotty.tools.dotc.semanticdb.Documentation])
}

object Documentation  extends SemanticdbGeneratedMessageCompanion[dotty.tools.dotc.semanticdb.Documentation] {
  implicit def messageCompanion: SemanticdbGeneratedMessageCompanion[dotty.tools.dotc.semanticdb.Documentation] = this
  def parseFrom(`_input__`: SemanticdbInputStream): dotty.tools.dotc.semanticdb.Documentation = {
    var __message: _root_.scala.Predef.String = ""
    var __format: dotty.tools.dotc.semanticdb.Documentation.Format = dotty.tools.dotc.semanticdb.Documentation.Format.HTML
    var _done__ = false
    while (!_done__) {
      val _tag__ = _input__.readTag()
      _tag__ match {
        case 0 => _done__ = true
        case 10 =>
          __message = _input__.readStringRequireUtf8()
        case 16 =>
          __format = dotty.tools.dotc.semanticdb.Documentation.Format.fromValue(_input__.readEnum())
        case tag => _input__.skipField(tag)
      }
    }
    dotty.tools.dotc.semanticdb.Documentation(
        message = __message,
        format = __format
    )
  }

  lazy val defaultInstance = dotty.tools.dotc.semanticdb.Documentation(
    message = "",
    format = dotty.tools.dotc.semanticdb.Documentation.Format.HTML
  )
  sealed abstract class Format(val value: _root_.scala.Int)  extends SemanticdbGeneratedEnum  derives CanEqual {
    type EnumType = Format
    def isHtml: _root_.scala.Boolean = false
    def isMarkdown: _root_.scala.Boolean = false
    def isJavadoc: _root_.scala.Boolean = false
    def isScaladoc: _root_.scala.Boolean = false
    def isKdoc: _root_.scala.Boolean = false

    final def asRecognized: _root_.scala.Option[dotty.tools.dotc.semanticdb.Documentation.Format.Recognized] = if (isUnrecognized) _root_.scala.None else _root_.scala.Some(this.asInstanceOf[dotty.tools.dotc.semanticdb.Documentation.Format.Recognized])
  }

  object Format  {
    sealed trait Recognized extends Format

    @SerialVersionUID(0L)
    case object HTML extends Format(0) with Format.Recognized {
      val index = 0
      val name = "HTML"
      override def isHtml: _root_.scala.Boolean = true
    }

    @SerialVersionUID(0L)
    case object MARKDOWN extends Format(1) with Format.Recognized {
      val index = 1
      val name = "MARKDOWN"
      override def isMarkdown: _root_.scala.Boolean = true
    }

    @SerialVersionUID(0L)
    case object JAVADOC extends Format(2) with Format.Recognized {
      val index = 2
      val name = "JAVADOC"
      override def isJavadoc: _root_.scala.Boolean = true
    }

    @SerialVersionUID(0L)
    case object SCALADOC extends Format(3) with Format.Recognized {
      val index = 3
      val name = "SCALADOC"
      override def isScaladoc: _root_.scala.Boolean = true
    }

    @SerialVersionUID(0L)
    case object KDOC extends Format(4) with Format.Recognized {
      val index = 4
      val name = "KDOC"
      override def isKdoc: _root_.scala.Boolean = true
    }

    @SerialVersionUID(0L)
    final case class Unrecognized(unrecognizedValue: _root_.scala.Int)  extends Format(unrecognizedValue) with SemanticdbUnrecognizedEnum
    lazy val values = scala.collection.immutable.Seq(HTML, MARKDOWN, JAVADOC, SCALADOC, KDOC)
    def fromValue(__value: _root_.scala.Int): Format = __value match {
      case 0 => HTML
      case 1 => MARKDOWN
      case 2 => JAVADOC
      case 3 => SCALADOC
      case 4 => KDOC
      case __other => Unrecognized(__other)
    }

  }
  final val MESSAGE_FIELD_NUMBER = 1
  final val FORMAT_FIELD_NUMBER = 2
  def of(
    message: _root_.scala.Predef.String,
    format: dotty.tools.dotc.semanticdb.Documentation.Format
  ): _root_.dotty.tools.dotc.semanticdb.Documentation = _root_.dotty.tools.dotc.semanticdb.Documentation(
    message,
    format
  )
  // @@protoc_insertion_point(GeneratedMessageCompanion[dotty.tools.dotc.semanticdb.Documentation])
}


text:
'use strict';

var semver = require('semver'),
    pkg = require('../../package.json');

var validate = function (version) {
  var node = {};

  try {
    node.expected = version ? semver.validRange(version) : semver.validRange(pkg.engines.node);
  } catch (err) {
    node.message = node.error = 'You must define a node verision in your project\'s `package.json` file.\nhttps://npmjs.org/doc/json.html#engines';
    return node;
  }

  node.actual = semver.valid(process.version),
  node.satisfies = semver.satisfies(node.actual, node.expected);

  if (node.satisfies === true) {
    node.message = 'Using node v' + node.actual + ' (Project requires ' + node.expected + ')';
  } else {
    node.message = 'Expected node ' + node.expected + ', but found v' + node.actual;
  }

  return node;
}

module.exports = validate;


text:
<?php
namespace backend\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\web\session;
use common\models\LoginForm;

/*
 * Site Controller
*/
class SiteController extends Controller
{
	/**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only'  => ['index', 'home'],
                'rules' => [
                    [
                        'actions' => ['index'],
                        'allow' => true,
                        'roles' => ['?'],
                    ],
                    [
                        'actions' => ['index','home'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    // 'logout' => ['post'],
                ],
            ],
        ];
    }

    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }

    public function actionIndex()
    {
        if(!Yii::$app->user->isGuest){
            return $this->redirect(['home']);
        }else{
            return $this->redirect(['login']);
        }
    }

    public function actionHome()
    {
    	Yii::$app->params['current_menu'] = '<i class="fa fa-desktop"></i> Dasboard';
        return $this->render('index');
    }

    public function actionLogin()
    {
        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            return $this->redirect(['home']);
        }

        $model->username ="";
        $model->password ="";
        return $this->renderPartial('login', [
            'model' => $model,
        ]);
    }

    public function actionLogout()
    {
        Yii::$app->user->logout();
        return $this->redirect(['login']);
    }
}


text: <db-product-list-item [product]="product"></db-product-list-item>


text:
<?php

require_once "../PagSeguroLibrary/PagSeguroLibrary.php";

class SearchTransactionsByDateInterval
{

    public static function main()
    {

        $initialDate = '2011-12-10T08:50';
        $finalDate = '2011-12-29T10:30';

        $pageNumber = 1;
        $maxPageResults = 20;

        try {

            /*
             * #### Credentials #####
             * Substitute the parameters below with your credentials (e-mail and token)
             * You can also get your credentials from a config file. See an example:
             * $credentials = PagSeguroConfig::getAccountCredentials();
             */
            $credentials = new PagSeguroAccountCredentials("your@email.com", "your_token_here");

            $result = PagSeguroTransactionSearchService::searchByDate(
                $credentials,
                $pageNumber,
                $maxPageResults,
                $initialDate,
                $finalDate
            );

            self::printResult($result, $initialDate, $finalDate);

        } catch (PagSeguroServiceException $e) {
            die($e->getMessage());
        }

    }

    public static function printResult(PagSeguroTransactionSearchResult $result, $initialDate, $finalDate)
    {
        $finalDate = $finalDate ? $finalDate : 'now';
        echo "
Search transactions by date
";
        echo "
$initialDate to $finalDate
";
        $transactions = $result->getTransactions();
        if (is_array($transactions) && count($transactions) > 0) {
            foreach ($transactions as $key => $transactionSummary) {
                echo "Code: " . $transactionSummary->getCode() . "
";
                echo "Reference: " . $transactionSummary->getReference() . "
";
                echo "amount: " . $transactionSummary->getGrossAmount() . "
";
                echo "
";
            }
        }
    }
}

SearchTransactionsByDateInterval::main();


text:
Each service has a method called buildRequest and receive a ApiRequestBuilder instance as a first argument. This object is used to create a request that will be send to a remote server.

#### withMethod

When creating a request, you are expected to provide the HTTP method you wish to perform. You can specify any method you'd like, including a custom method that might not be part of RFC 7231 (like "MOVE").

You can create and send a request using methods on a client that map to the HTTP method you wish to use.

Common HTTP methods

* GET
* POST
* HEAD
* PUT
* DELETE
* OPTIONS
* PATCH

````php
$requestBuilder->withMethod ('GET');
````

#### withUri

When creating a request, you can provide the URI as a string or an instance of Psr\Http\Message\UriInterface.

````php
$requestBuilder->withUri('http://jsonplaceholder.typicode.com/posts/');
````

#### withHeaders

Array of headers to send with the request

````php
$requestBuilder->withHeaders(['X-Foo' => 'bar']);
````

#### withBody

Body content to send with the request can be string or `Psr\Http\Message\StreamInterface`

````php
$requestBuilder->withBody({"id":1, "title": "updated"});
````

#### withProtocol

Protocol version to use. The version string MUST contain only the HTTP version number (e.g.,* "1.1", "1.0").

````php
$requestBuilder->withProtocol('1.1');
````

#### withMock

Class to emulate response, string with class name or instance of `Rafrsr\GenericApi\ApiMockInterface`

````php
$requestBuilder->withMock(GetPostsMock::class);
````
More info about [mocks](/rafrsr/generic-api/wiki/Mocking-a-service)

#### Options

Can customize requests created and transferred by a client using request options. Request options control various aspects of a request including, headers, query string parameters, timeout settings, the body of a request, and much more.

````php
$requestBuilder->options()->SSLVerification(false)
````

Can see al available options and specific documentation in the [guzzle documentation page](http://docs.guzzlephp.org/en/latest/request-options.html)

Unlike guzzle, to simplify the usage of set options, we have implemented a method for each option. Can set all options in your prefered way.

````php
$requestBuilder->options()->SSLVerification(false)
//or
$requestBuilder->options()->set('verify', false)
````


text:
package com.github.jdsjlzx.recyclerview;

import android.content.Context;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.LinearLayout;

import com.github.jdsjlzx.interfaces.ILoadMoreFooter;
import com.github.jdsjlzx.interfaces.IRefreshHeader;
import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.interfaces.OnNetWorkErrorListener;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.view.ArrowRefreshHeader;
import com.github.jdsjlzx.view.LoadingFooter;

/**
 *
 * @author lizhixian
 * @created 2016/8/29 11:21
 *
 */
public class LRecyclerView extends RecyclerView {
    private boolean mPullRefreshEnabled = true;
    private boolean mLoadMoreEnabled = true;
    private boolean mRefreshing = false;//是否正在下拉刷新
    private boolean mLoadingData = false;//是否正在加载数据
    private OnRefreshListener mRefreshListener;
    private OnLoadMoreListener mLoadMoreListener;
    private LScrollListener mLScrollListener;
    private IRefreshHeader mRefreshHeader;
    private ILoadMoreFooter mLoadMoreFooter;
    private View mEmptyView;
    private View mFootView;

    private final RecyclerView.AdapterDataObserver mDataObserver = new DataObserver();
    private int mActivePointerId;
    private float mLastY = -1;
    private float sumOffSet;
    private static final float DRAG_RATE = 2.0f;
    private int mPageSize = 10; //一次网络请求默认数量

    private LRecyclerViewAdapter mWrapAdapter;
    private boolean isNoMore = false;
    private boolean isCritical = false;
    private boolean mIsVpDragger;
    private int mTouchSlop;
    private float startY;
    private float startX;
    private boolean isRegisterDataObserver;
    //scroll variables begin
    /**
     * 当前RecyclerView类型
     */
    protected LayoutManagerType layoutManagerType;

    /**
     * 最后一个的位置
     */
    private int[] lastPositions;

    /**
     * 最后一个可见的item的位置
     */
    private int lastVisibleItemPosition;

    /**
     * 当前滑动的状态
     */
    private int currentScrollState = 0;

    /**
     * 触发在上下滑动监听器的容差距离
     */
    private static final int HIDE_THRESHOLD = 20;

    /**
     * 滑动的距离
     */
    private int mDistance = 0;

    /**
     * 是否需要监听控制
     */
    private boolean mIsScrollDown = true;

    /**
     * Y轴移动的实际距离(最顶部为0)
     */
    private int mScrolledYDistance = 0;

    /**
     * X轴移动的实际距离(最左侧为0)
     */
    private int mScrolledXDistance = 0;
    //scroll variables end

    private AppBarStateChangeListener.State appbarState = AppBarStateChangeListener.State.EXPANDED;

    public LRecyclerView(Context context) {
        this(context, null);
    }

    public LRecyclerView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public LRecyclerView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    private void init() {
        mTouchSlop = ViewConfiguration.get(getContext().getApplicationContext()).getScaledTouchSlop();
        if (mPullRefreshEnabled) {
            setRefreshHeader(new ArrowRefreshHeader(getContext().getApplicationContext()));
        }

        if (mLoadMoreEnabled) {
            setLoadMoreFooter(new LoadingFooter(getContext().getApplicationContext()),false);
        }

    }

    @Override
    public void setAdapter(Adapter adapter) {
        if (mWrapAdapter != null && mDataObserver != null && isRegisterDataObserver) {
            mWrapAdapter.getInnerAdapter().unregisterAdapterDataObserver(mDataObserver);
        }

        mWrapAdapter = (LRecyclerViewAdapter) adapter;
        super.setAdapter(mWrapAdapter);

        mWrapAdapter.getInnerAdapter().registerAdapterDataObserver(mDataObserver);
        mDataObserver.onChanged();
        isRegisterDataObserver = true;

        mWrapAdapter.setRefreshHeader(mRefreshHeader);

        //fix bug: https://github.com/jdsjlzx/LRecyclerView/issues/115
        if (mLoadMoreEnabled && mWrapAdapter.getFooterViewsCount()==0) {
            mWrapAdapter.addFooterView(mFootView);
        }

    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();

        if (mWrapAdapter != null && mDataObserver != null && isRegisterDataObserver) {
            mWrapAdapter.getInnerAdapter().unregisterAdapterDataObserver(mDataObserver);
            isRegisterDataObserver = false;
        }

    }

    private class DataObserver extends RecyclerView.AdapterDataObserver {
        @Override
        public void onChanged() {
            Adapter<?> adapter = getAdapter();
            if (adapter instanceof LRecyclerViewAdapter) {
                LRecyclerViewAdapter lRecyclerViewAdapter = (LRecyclerViewAdapter) adapter;
                if (lRecyclerViewAdapter.getInnerAdapter() != null && mEmptyView != null) {
                    int count = lRecyclerViewAdapter.getInnerAdapter().getItemCount();
                    if (count == 0) {
                        mEmptyView.setVisibility(View.VISIBLE);
                        LRecyclerView.this.setVisibility(View.GONE);
                    } else {
                        mEmptyView.setVisibility(View.GONE);
                        LRecyclerView.this.setVisibility(View.VISIBLE);
                    }
                }
            } else {
                if (adapter != null && mEmptyView != null) {
                    if (adapter.getItemCount() == 0) {
                        mEmptyView.setVisibility(View.VISIBLE);
                        LRecyclerView.this.setVisibility(View.GONE);
                    } else {
                        mEmptyView.setVisibility(View.GONE);
                        LRecyclerView.this.setVisibility(View.VISIBLE);
                    }
                }
            }

            if (mWrapAdapter != null) {
                mWrapAdapter.notifyDataSetChanged();
                if(mWrapAdapter.getInnerAdapter().getItemCount() < mPageSize ) {
                    mFootView.setVisibility(GONE);
                }
            }

        }

        @Override
        public void onItemRangeChanged(int positionStart, int itemCount) {
            mWrapAdapter.notifyItemRangeChanged(positionStart + mWrapAdapter.getHeaderViewsCount() + 1, itemCount);
        }

        @Override
        public void onItemRangeInserted(int positionStart, int itemCount) {
            mWrapAdapter.notifyItemRangeInserted(positionStart + mWrapAdapter.getHeaderViewsCount() + 1, itemCount);
        }

        @Override
        public void onItemRangeRemoved(int positionStart, int itemCount) {
            mWrapAdapter.notifyItemRangeRemoved(positionStart + mWrapAdapter.getHeaderViewsCount() + 1, itemCount);
            if(mWrapAdapter.getInnerAdapter().getItemCount() < mPageSize ) {
                mFootView.setVisibility(GONE);
            }

        }

        @Override
        public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) {
            int headerViewsCountCount = mWrapAdapter.getHeaderViewsCount();
            mWrapAdapter.notifyItemRangeChanged(fromPosition + headerViewsCountCount + 1, toPosition + headerViewsCountCount + 1 + itemCount);
        }

    }

    /**
     * 解决嵌套RecyclerView滑动冲突问题
     * @param ev
     * @return
     */
    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        int action = ev.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                // 记录手指按下的位置
                startY = ev.getY();
                startX = ev.getX();
                // 初始化标记
                mIsVpDragger = false;
                break;
            case MotionEvent.ACTION_MOVE:
                // 如果viewpager正在拖拽中,那么不拦截它的事件,直接return false;
                if (mIsVpDragger) {
                    return false;
                }

                // 获取当前手指位置
                float endY = ev.getY();
                float endX = ev.getX();
                float distanceX = Math.abs(endX - startX);
                float distanceY = Math.abs(endY - startY);
                // 如果X轴位移大于Y轴位移,那么将事件交给viewPager处理。
                if (distanceX > mTouchSlop && distanceX > distanceY) {
                    mIsVpDragger = true;
                    return false;
                }
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                // 初始化标记
                mIsVpDragger = false;
                break;
        }
        // 如果是Y轴位移大于X轴,事件交给swipeRefreshLayout处理。
        return super.onInterceptTouchEvent(ev);
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        if (mLastY == -1) {
            mLastY = ev.getY();
            mActivePointerId = ev.getPointerId(0);
            sumOffSet = 0;
        }
        switch (ev.getActionMasked()) {
            case MotionEvent.ACTION_DOWN:
                mLastY = ev.getY();
                mActivePointerId = ev.getPointerId(0);
                sumOffSet = 0;
                break;
            case MotionEvent.ACTION_POINTER_DOWN:
                final int index = ev.getActionIndex();
                mActivePointerId = ev.getPointerId(index);
                mLastY = (int) ev.getY(index);
                break;
            case MotionEvent.ACTION_MOVE:
                int pointerIndex = ev.findPointerIndex(mActivePointerId);
                if (pointerIndex == -1) {
                    pointerIndex = 0;
                    mActivePointerId = ev.getPointerId(pointerIndex);
                }
                final int moveY = (int) ev.getY(pointerIndex);
                final float deltaY = (moveY - mLastY) / DRAG_RATE;
                mLastY = moveY;
                sumOffSet += deltaY;
                if (isOnTop() && mPullRefreshEnabled && !mRefreshing && (appbarState == AppBarStateChangeListener.State.EXPANDED)) {
                    if(mRefreshHeader.getType() == IRefreshHeader.TYPE_HEADER_NORMAL) {
                        mRefreshHeader.onMove(deltaY, sumOffSet);
                    }else if (mRefreshHeader.getType() == IRefreshHeader.TYPE_HEADER_MATERIAL) {
                         if(deltaY > 0 && !canScrollVertically(-1) || deltaY < 0 && !canScrollVertically(1)) { //判断无法下拉和无法上拉(item过少的情况)
                          overScrollBy(0, (int) -deltaY, 0, 0, 0, 0, 0, (int) sumOffSet, true);
                        }
                    }
                }
                break;
            case MotionEvent.ACTION_UP:
                mLastY = -1; // reset
                mActivePointerId = -1;
                if (isOnTop() && mPullRefreshEnabled && !mRefreshing/*&& appbarState == AppBarStateChangeListener.State.EXPANDED*/) {
                    if (mRefreshHeader != null && mRefreshHeader.onRelease()) {
                        if (mRefreshListener != null) {
                            mRefreshing = true;
                            mFootView.setVisibility(GONE);
                            mRefreshListener.onRefresh();
                        }
                    }
                }
                break;
        }
        return super.onTouchEvent(ev);
    }

    @Override protected boolean overScrollBy(int deltaX, int deltaY, int scrollX, int scrollY, int scrollRangeX, int scrollRangeY, int maxOverScrollX,
        int maxOverScrollY, boolean isTouchEvent) {
        if (deltaY != 0 && isTouchEvent) {
            mRefreshHeader.onMove(deltaY, sumOffSet);
        }
        return super.overScrollBy(deltaX, deltaY, scrollX, scrollY, scrollRangeX, scrollRangeY, maxOverScrollX, maxOverScrollY, isTouchEvent);
    }

    private int findMax(int[] lastPositions) {
        int max = lastPositions[0];
        for (int value : lastPositions) {
            if (value > max) {
                max = value;
            }
        }
        return max;
    }

    public boolean isOnTop() {
        return  mPullRefreshEnabled && (mRefreshHeader.getHeaderView().getParent() != null);
    }

    /**
     * set view when no content item
     *
     * @param emptyView visiable view when items is empty
     */
    public void setEmptyView(View emptyView) {
        this.mEmptyView = emptyView;
        mDataObserver.onChanged();
    }

    /**
     *
     * @param pageSize 一页加载的数量
     */
    public void refreshComplete(int pageSize) {
        this.mPageSize = pageSize;
        if (mRefreshing) {
            isNoMore = false;
            mRefreshing = false;
            mRefreshHeader.refreshComplete();

            if(mWrapAdapter.getInnerAdapter().getItemCount() < pageSize) {
                mFootView.setVisibility(GONE);
                mWrapAdapter.removeFooterView();
            } else {
                if (mWrapAdapter.getFooterViewsCount() == 0) {
                    mWrapAdapter.addFooterView(mFootView);
                }
            }
        } else if (mLoadingData) {
            mLoadingData = false;
            mLoadMoreFooter.onComplete();
        }
        //visibleItemCount 10 lastVisibleItemPosition 9 totalItemCount 11 isNoMore false mRefreshing false
        //处理特殊情况 最后一行显示出来了加载更多的view的一部分
        if (mWrapAdapter.getInnerAdapter().getItemCount() == mPageSize) {
            isCritical = true;
        } else {
            isCritical = false;
        }
    }

    /**
     * @param pageSize 一页加载的数量
     * @param total 总数
     */
    public void refreshComplete(int pageSize, int total) {
        this.mPageSize = pageSize;
        if (mRefreshing) {
            mRefreshing = false;
            mRefreshHeader.refreshComplete();

            if(mWrapAdapter.getInnerAdapter().getItemCount() < pageSize) {
                mFootView.setVisibility(GONE);
                mWrapAdapter.removeFooterView();
            } else {
                if (mWrapAdapter.getFooterViewsCount() == 0) {
                    mWrapAdapter.addFooterView(mFootView);
                }
            }
        } else if (mLoadingData) {
            mLoadingData = false;
            mLoadMoreFooter.onComplete();
        }
        if (pageSize < total) {
            isNoMore = false;
        }
        //处理特殊情况 最后一行显示出来了加载更多的view的一部分
        if (mWrapAdapter.getInnerAdapter().getItemCount() == mPageSize) {
            isCritical = true;
        } else {
            isCritical = false;
        }
    }

    /**
     * 此方法主要是为了满足数据不满一屏幕或者数据小于pageSize的情况下,是否显示footview
     * 在分页情况下使用refreshComplete(int pageSize, int total, boolean false)就相当于refreshComplete(int pageSize, int total)
     * @param pageSize 一页加载的数量
     * @param total 总数
     * @param isShowFootView  是否需要显示footview(前提条件是:getItemCount() < pageSize)
     */
    public void refreshComplete(int pageSize, int total, boolean isShowFootView) {
        this.mPageSize = pageSize;
        if (mRefreshing) {
            mRefreshing = false;
            mRefreshHeader.refreshComplete();
            if (isShowFootView) {
                mFootView.setVisibility(VISIBLE);
            } else {
                if(mWrapAdapter.getInnerAdapter().getItemCount() < pageSize) {
                    mFootView.setVisibility(GONE);
                    mWrapAdapter.removeFooterView();
                } else {
                    if (mWrapAdapter.getFooterViewsCount() == 0) {
                        mWrapAdapter.addFooterView(mFootView);
                    }
                }
            }
        } else if (mLoadingData) {
            mLoadingData = false;
            mLoadMoreFooter.onComplete();
        }
        if (pageSize < total) {
            isNoMore = false;
        }
        //处理特殊情况 最后一行显示出来了加载更多的view的一部分
        if (mWrapAdapter.getInnerAdapter().getItemCount() == mPageSize) {
            isCritical = true;
        } else {
            isCritical = false;
        }
    }

    /**
     * 设置是否已加载全部
     * @param noMore
     */
    public void setNoMore(boolean noMore){
        mLoadingData = false;
        isNoMore = noMore;
        if(isNoMore) {
            mLoadMoreFooter.onNoMore();
            mFootView.setVisibility(VISIBLE);
        } else {
            mLoadMoreFooter.onComplete();
        }
    }

    /**
     * 设置自定义的RefreshHeader
     * 注意:setRefreshHeader方法必须在setAdapter方法之前调用才能生效
     */
    public void setRefreshHeader(IRefreshHeader refreshHeader) {
        if(isRegisterDataObserver){
            throw new RuntimeException("setRefreshHeader must been invoked before setting the adapter.");
        }
        this.mRefreshHeader = refreshHeader;
    }

    /**
     * 设置自定义的footerview
     * @param loadMoreFooter
     * @param isCustom 是否自定义footview
     */
    public void setLoadMoreFooter(ILoadMoreFooter loadMoreFooter, boolean isCustom) {
        this.mLoadMoreFooter = loadMoreFooter;
        if (isCustom) {
            if (null != mWrapAdapter && mWrapAdapter.getFooterViewsCount() >0) {
                mWrapAdapter.removeFooterView();
            }
        }
        mFootView = loadMoreFooter.getFootView();
        mFootView.setVisibility(VISIBLE);

        //wxm:mFootView inflate的时候没有以RecyclerView为parent,所以要设置LayoutParams
        ViewGroup.LayoutParams layoutParams = mFootView.getLayoutParams();
        if (layoutParams != null) {
            mFootView.setLayoutParams(new LayoutParams(layoutParams));
        } else {
            mFootView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
        }

        if (isCustom) {
            if (mLoadMoreEnabled && mWrapAdapter.getFooterViewsCount()==0) {
                mWrapAdapter.addFooterView(mFootView);
            }
        }

    }

    public void setPullRefreshEnabled(boolean enabled) {
        mPullRefreshEnabled = enabled;
    }

    /**
     * 到底加载是否可用
     */
    public void setLoadMoreEnabled(boolean enabled) {
        if(mWrapAdapter == null){
            throw new NullPointerException("LRecyclerViewAdapter cannot be null, please make sure the variable mWrapAdapter have been initialized.");
        }
        mLoadMoreEnabled = enabled;
        if (!enabled) {
            mWrapAdapter.removeFooterView();
        }
    }

    public void setRefreshProgressStyle(int style) {
        if (mRefreshHeader instanceof ArrowRefreshHeader) {
            ((ArrowRefreshHeader) mRefreshHeader).setProgressStyle(style);
        }
    }

    public void setArrowImageView(int resId) {
        if (mRefreshHeader instanceof ArrowRefreshHeader) {
            ((ArrowRefreshHeader) mRefreshHeader).setArrowImageView(resId);
        }
    }

    public void setLoadingMoreProgressStyle(int style) {
        if (mLoadMoreFooter instanceof LoadingFooter) {
            ((LoadingFooter) mLoadMoreFooter).setProgressStyle(style);
        }

    }

    public void setOnRefreshListener(OnRefreshListener listener) {
        mRefreshListener = listener;
    }

    public void setOnLoadMoreListener(OnLoadMoreListener listener) {
        mLoadMoreListener = listener;
    }

    public void setOnNetWorkErrorListener(final OnNetWorkErrorListener listener) {
        mLoadMoreFooter.setNetworkErrorViewClickListener(listener);
    }

    /**
     * 请使用自定义LoadingFooter的方式实现
     * @param loading
     * @param noMore
     * @param noNetWork
     */
    @Deprecated
    public void setFooterViewHint(String loading, String noMore, String noNetWork) {
        if (mLoadMoreFooter instanceof LoadingFooter) {
            LoadingFooter loadingFooter = ((LoadingFooter) mLoadMoreFooter);
            loadingFooter.setLoadingHint(loading);
            loadingFooter.setNoMoreHint(noMore);
            loadingFooter.setNoNetWorkHint(noNetWork);
        }
    }

    /**
     * 本方法不再推荐使用,请使用自定义LoadingFooter的方式实现
     * 设置Footer文字颜色
     * @param indicatorColor
     * @param hintColor
     * @param backgroundColor
     */
    @Deprecated
    public void setFooterViewColor(int indicatorColor, int hintColor, int backgroundColor) {
        if (mLoadMoreFooter instanceof LoadingFooter) {
            LoadingFooter loadingFooter = ((LoadingFooter) mLoadMoreFooter);
            loadingFooter.setIndicatorColor(ContextCompat.getColor(getContext(),indicatorColor));
            loadingFooter.setHintTextColor(hintColor);
            loadingFooter.setViewBackgroundColor(backgroundColor);
        }
    }

    /**
     * 设置颜色
     * @param indicatorColor Only call the method setRefreshProgressStyle(int style) to take effect
     * @param hintColor
     * @param backgroundColor
     */
    public void setHeaderViewColor(int indicatorColor, int hintColor, int backgroundColor) {
        if (mRefreshHeader instanceof ArrowRefreshHeader) {
            ArrowRefreshHeader arrowRefreshHeader = ((ArrowRefreshHeader) mRefreshHeader);
            arrowRefreshHeader.setIndicatorColor(ContextCompat.getColor(getContext(),indicatorColor));
            arrowRefreshHeader.setHintTextColor(hintColor);
            arrowRefreshHeader.setViewBackgroundColor(backgroundColor);
        }

    }

    public void setLScrollListener(LScrollListener listener) {
        mLScrollListener = listener;
    }

    public interface LScrollListener {

        void onScrollUp();//scroll down to up

        void onScrollDown();//scroll from up to down

        void onScrolled(int distanceX, int distanceY);// moving state,you can get the move distance

        void onScrollStateChanged(int state);
    }

    public void refresh() {
        if (mRefreshHeader.getVisibleHeight() > 0 || mRefreshing) {// if RefreshHeader is Refreshing, return
            return;
        }
        if (mPullRefreshEnabled && mRefreshListener != null) {
            mRefreshHeader.onRefreshing();
            int offSet = mRefreshHeader.getHeaderView().getMeasuredHeight();
            mRefreshHeader.onMove(offSet,offSet);
            mRefreshing = true;

            mFootView.setVisibility(GONE);
            mRefreshListener.onRefresh();
        }
    }

    public void forceToRefresh() {
        if (mLoadingData) {
            return;
        }
        refresh();
    }

    @Override
    public void onScrolled(int dx, int dy) {
        super.onScrolled(dx, dy);

        int firstVisibleItemPosition = 0;
        RecyclerView.LayoutManager layoutManager = getLayoutManager();

        if (layoutManagerType == null) {
            if (layoutManager instanceof LinearLayoutManager) {
                layoutManagerType = LayoutManagerType.LinearLayout;
            } else if (layoutManager instanceof GridLayoutManager) {
                layoutManagerType = LayoutManagerType.GridLayout;
            } else if (layoutManager instanceof StaggeredGridLayoutManager) {
                layoutManagerType = LayoutManagerType.StaggeredGridLayout;
            } else {
                throw new RuntimeException(
                        "Unsupported LayoutManager used. Valid ones are LinearLayoutManager, GridLayoutManager and StaggeredGridLayoutManager");
            }
        }

        switch (layoutManagerType) {
            case LinearLayout:
                firstVisibleItemPosition = ((LinearLayoutManager) layoutManager).findFirstVisibleItemPosition();
                lastVisibleItemPosition = ((LinearLayoutManager) layoutManager).findLastVisibleItemPosition();
                break;
            case GridLayout:
                firstVisibleItemPosition = ((GridLayoutManager) layoutManager).findFirstVisibleItemPosition();
                lastVisibleItemPosition = ((GridLayoutManager) layoutManager).findLastVisibleItemPosition();
                break;
            case StaggeredGridLayout:
                StaggeredGridLayoutManager staggeredGridLayoutManager = (StaggeredGridLayoutManager) layoutManager;
                if (lastPositions == null) {
                    lastPositions = new int[staggeredGridLayoutManager.getSpanCount()];
                }
                staggeredGridLayoutManager.findLastVisibleItemPositions(lastPositions);
                lastVisibleItemPosition = findMax(lastPositions);
                staggeredGridLayoutManager.findFirstCompletelyVisibleItemPositions(lastPositions);
                firstVisibleItemPosition = findMax(lastPositions);
                break;
            default:
                break;
        }

        // 根据类型来计算出第一个可见的item的位置,由此判断是否触发到底部的监听器
        // 计算并判断当前是向上滑动还是向下滑动
        calculateScrollUpOrDown(firstVisibleItemPosition, dy);
        // 移动距离超过一定的范围,我们监听就没有啥实际的意义了
        mScrolledXDistance += dx;
        mScrolledYDistance += dy;
        mScrolledXDistance = (mScrolledXDistance < 0) ? 0 : mScrolledXDistance;
        mScrolledYDistance = (mScrolledYDistance < 0) ? 0 : mScrolledYDistance;
        if (mIsScrollDown && (dy == 0)) {
            mScrolledYDistance = 0;
        }
        //Be careful in here
        if (null != mLScrollListener) {
            mLScrollListener.onScrolled(mScrolledXDistance, mScrolledYDistance);
        }

        if (mLoadMoreListener != null && mLoadMoreEnabled) {
            int visibleItemCount = layoutManager.getChildCount();
            int totalItemCount = layoutManager.getItemCount();
            if (visibleItemCount > 0
                    && lastVisibleItemPosition >= totalItemCount - 1
                    && (isCritical ? totalItemCount >= visibleItemCount : totalItemCount > visibleItemCount)
                    && !isNoMore
                    && !mRefreshing) {

                mFootView.setVisibility(View.VISIBLE);
                if (!mLoadingData) {
                    mLoadingData = true;
                    mLoadMoreFooter.onLoading();
                    mLoadMoreListener.onLoadMore();
                }

            }

        }
        if (isOnTop() && dy > 0 && mRefreshHeader.getType() == IRefreshHeader.TYPE_HEADER_MATERIAL && !mRefreshing && (appbarState
            == AppBarStateChangeListener.State.EXPANDED)) {
            mRefreshHeader.onMove(dy, mScrolledYDistance);
        }
    }

    @Override
    public void onScrollStateChanged(int state) {
        super.onScrollStateChanged(state);
        currentScrollState = state;

        if (mLScrollListener != null) {
            mLScrollListener.onScrollStateChanged(state);
        }

    }

    /**
     * 计算当前是向上滑动还是向下滑动
     */
    private void calculateScrollUpOrDown(int firstVisibleItemPosition, int dy) {
        if (null != mLScrollListener) {
            if (firstVisibleItemPosition == 0) {
                if (!mIsScrollDown) {
                    mIsScrollDown = true;
                    mLScrollListener.onScrollDown();
                }
            } else {
                if (mDistance > HIDE_THRESHOLD && mIsScrollDown) {
                    mIsScrollDown = false;
                    mLScrollListener.onScrollUp();
                    mDistance = 0;
                } else if (mDistance < -HIDE_THRESHOLD && !mIsScrollDown) {
                    mIsScrollDown = true;
                    mLScrollListener.onScrollDown();
                    mDistance = 0;
                }
            }
        }

        if ((mIsScrollDown && dy > 0) || (!mIsScrollDown && dy < 0)) {
            mDistance += dy;
        }
    }

    public enum LayoutManagerType {
        LinearLayout,
        StaggeredGridLayout,
        GridLayout
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        //解决LRecyclerView与CollapsingToolbarLayout滑动冲突的问题
        AppBarLayout appBarLayout = null;
        ViewParent p = getParent();
        while (p != null) {
            if (p instanceof CoordinatorLayout) {
                break;
            }
            p = p.getParent();
        }
        if(p instanceof CoordinatorLayout) {
            CoordinatorLayout coordinatorLayout = (CoordinatorLayout)p;
            final int childCount = coordinatorLayout.getChildCount();
            for (int i = childCount - 1; i >= 0; i--) {
                final View child = coordinatorLayout.getChildAt(i);
                if(child instanceof AppBarLayout) {
                    appBarLayout = (AppBarLayout)child;
                    break;
                }
            }
            if(appBarLayout != null) {
                appBarLayout.addOnOffsetChangedListener(new AppBarStateChangeListener() {
                    @Override
                    public void onStateChanged(AppBarLayout appBarLayout, State state) {
                        appbarState = state;
                    }
                });
            }
        }
    }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;

namespace TestControl
{
    /// <summary>
    /// Interaction logic for UserControlTreeViewLazyLoading.xaml
    /// </summary>
    public partial class UserControlTreeViewLazyLoading : UserControl
    {
        public UserControlTreeViewLazyLoading()
        {
            InitializeComponent();
            DriveInfo[] drives = DriveInfo.GetDrives();
            foreach (DriveInfo driveInfo in drives)
                trvStructure.Items.Add(CreateTreeItem(driveInfo));
        }

        public void TreeViewItem_Expanded(object sender, RoutedEventArgs e)
        {
            TreeViewItem item = e.Source as TreeViewItem;
            if ((item.Items.Count == 1) && (item.Items[0] is string))
            {
                item.Items.Clear();

                DirectoryInfo expandedDir = null;
                if (item.Tag is DriveInfo)
                    expandedDir = (item.Tag as DriveInfo).RootDirectory;
                if (item.Tag is DirectoryInfo)
                    expandedDir = (item.Tag as DirectoryInfo);
                try
                {
                    foreach (DirectoryInfo subDir in expandedDir.GetDirectories())
                        item.Items.Add(CreateTreeItem(subDir));
                }
                catch { }
            }
        }

        private TreeViewItem CreateTreeItem(object o)
        {
            TreeViewItem item = new TreeViewItem();
            item.Header = o.ToString();
            item.Tag = o;
            item.Items.Add("Loading...");
            return item;
        }
    }
}


text:
from flask_migrate import Migrate,MigrateCommand
from flask_script import Manager
from varappx.models.users import loaddata,db
import sys

migrate = Migrate(db.app,db)
manager = Manager(db.app)
manager.add_command('db',MigrateCommand)
from varappx import check_everything

if __name__ == "__main__":
    if 'loaddata' in sys.argv:
        loaddata()
    else:
        manager.run()
        check_everything()


text: Draw a square that moves down and right.


text:
package utilities;

import java.util.List;

import models.Knot;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import com.forkthecode.knotit.MainActivity;
import com.forkthecode.knotit.R;

public class CustomArrayAdapter extends ArrayAdapter<Knot> {

	Context context;

	public CustomArrayAdapter(Context context, int resource,
			 List<Knot> objects) {
		super(context, resource,  objects);
		this.context = context;
	}
    ImageView image;
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View output =  convertView;

		if(output == null){
			LayoutInflater inflater = (LayoutInflater)context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			 output = inflater.inflate(com.forkthecode.knotit.R.layout.knot, null);
		}

		Knot knot = getItem(position);
		TextView title = (TextView)output.findViewById(com.forkthecode.knotit.R.id.knot_title);
		TextView description = (TextView)output.findViewById(com.forkthecode.knotit
                .R.id.knot_description);
		TextView date = (TextView)output.findViewById(com.forkthecode.knotit
                .R.id.knot_reminder_time);
		image = (ImageView) output.findViewById(com.forkthecode.knotit.R.id.knot_image);
		title.setText(knot.title);
		description.setText(knot.description);
		String reminderDate  = tools.epochToTime(context, knot.reminderTimestamp);
		date.setText(reminderDate);
        CheckBox checkBox = (CheckBox) output.findViewById(R.id.checkBoxknot);
        if(knot.isRepeating==1){
            checkBox.setVisibility(View.VISIBLE);

            if(knot.repeatingTime == 3600000l) {
                checkBox.setText(context.getString(R.string.repeat_every_hour));
            }
            else if(knot.repeatingTime == 60000l){
                checkBox.setText(context.getString(R.string.repeat_every_min));
            }
            else if(knot.repeatingTime == 86400000l) {
                checkBox.setText(context.getString(R.string.repeat_every_day));
            }
            else if(knot.repeatingTime == 604800000l) {
                checkBox.setText(context.getString(R.string.repeat_every_week));
            }
        }else{
            checkBox.setVisibility(View.GONE);
        }
		if(knot.imageSource == null){
			image.setImageDrawable(null);
		}
		else{

               Drawable d = MainActivity.hashMap.get(knot.timestamp);

                    image.setImageDrawable(d);

		}
		return output;
	}

}


text:
"""Sample Vitess client in Python.

This is a sample for using the Python Vitess client with an unsharded keyspace.

Before running this, start up a local example cluster as described in the
README.md file.

Then run client.sh, which sets up PYTHONPATH before running client.py:
vitess/examples/local$ ./client.sh
"""

import argparse

from vtdb import keyrange
from vtdb import keyrange_constants
from vtdb import vtgate_client

# register the python gRPC client upon import
from vtdb import grpc_vtgate_client  # pylint: disable=unused-import

# Constants and params
UNSHARDED = [keyrange.KeyRange(keyrange_constants.NON_PARTIAL_KEYRANGE)]

# Parse args
parser = argparse.ArgumentParser()
parser.add_argument('--server', dest='server', default='localhost:15991')
parser.add_argument('--timeout', dest='timeout', type=float, default='10.0')
args = parser.parse_args()

# Connect
conn = vtgate_client.connect('grpc', args.server, args.timeout)

try:
  # Insert something.
  print 'Inserting into master...'
  cursor = conn.cursor(
      tablet_type='master', keyspace='test_keyspace',
      keyranges=UNSHARDED, writable=True)
  cursor.begin()
  cursor.execute(
      'INSERT INTO test_table (msg) VALUES (%(msg)s)',
      {'msg': 'V is for speed'})
  cursor.commit()

  # Read it back from the master.
  print 'Reading from master...'
  cursor.execute('SELECT * FROM test_table', {})
  for row in cursor.fetchall():
    print row

  cursor.close()

  # Read from a replica.
  # Note that this may be behind master due to replication lag.
  print 'Reading from replica...'
  cursor = conn.cursor(
      tablet_type='replica', keyspace='test_keyspace', keyranges=UNSHARDED)
  cursor.execute('SELECT * FROM test_table', {})
  for row in cursor.fetchall():
    print row
  cursor.close()

finally:
  # Clean up
  conn.close()


text:
// Copyright 2015 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.

package org.chromium.chrome.test;

import android.text.TextUtils;
import android.view.View;

import org.chromium.base.test.util.CommandLineFlags;
import org.chromium.chrome.browser.ChromeSwitches;
import org.chromium.chrome.browser.ChromeTabbedActivity;
import org.chromium.chrome.browser.EmptyTabObserver;
import org.chromium.chrome.browser.Tab;
import org.chromium.chrome.browser.tab.ChromeTab;
import org.chromium.chrome.browser.tabmodel.EmptyTabModelObserver;
import org.chromium.chrome.browser.tabmodel.TabModel;
import org.chromium.chrome.browser.tabmodel.TabModel.TabLaunchType;
import org.chromium.chrome.browser.tabmodel.TabModelUtils;
import org.chromium.content.browser.test.util.CallbackHelper;
import org.chromium.content.browser.test.util.TestTouchUtils;

import java.util.concurrent.TimeoutException;

/**
 * The base class of the ChromeTabbedActivity specific tests. It provides the common methods
 * to access the ChromeTabbedActivity UI.
 */
@CommandLineFlags.Add(ChromeSwitches.DISABLE_DOCUMENT_MODE)
public abstract class ChromeTabbedActivityTestBase extends
        ChromeActivityTestCaseBase<ChromeTabbedActivity> {
    private static final String TAG = "ChromeTabbedActivityTestBase";

    public ChromeTabbedActivityTestBase() {
        super(ChromeTabbedActivity.class);
    }

    /**
     * Load a url in multiple new tabs in parallel. Each {@link ChromeTab} will pretend to be
     * created from a link.
     *
     * @param url The url of the page to load.
     * @param numTabs The number of tabs to open.
     */
    public void loadUrlInManyNewTabs(final String url, final int numTabs)
            throws InterruptedException {
        final CallbackHelper[] pageLoadedCallbacks = new CallbackHelper[numTabs];
        final int[] tabIds = new int[numTabs];
        for (int i = 0; i < numTabs; ++i) {
            final int index = i;
            getInstrumentation().runOnMainSync(new Runnable() {
                @Override
                public void run() {
                    Tab currentTab = getActivity().getCurrentTabCreator().launchUrl(
                            url, TabLaunchType.FROM_LINK);
                    final CallbackHelper pageLoadCallback = new CallbackHelper();
                    pageLoadedCallbacks[index] = pageLoadCallback;
                    currentTab.addObserver(new EmptyTabObserver() {
                        @Override
                        public void onPageLoadFinished(Tab tab) {
                            pageLoadCallback.notifyCalled();
                            tab.removeObserver(this);
                        }
                    });
                    tabIds[index] = currentTab.getId();
                }
            });
        }
        //  When opening many tabs some may be frozen due to memory pressure and won't send
        //  PAGE_LOAD_FINISHED events. Iterate over the newly opened tabs and wait for each to load.
        for (int i = 0; i < numTabs; ++i) {
            final TabModel tabModel = getActivity().getCurrentTabModel();
            final Tab tab = TabModelUtils.getTabById(tabModel, tabIds[i]);
            getInstrumentation().runOnMainSync(new Runnable() {
                @Override
                public void run() {
                    TabModelUtils.setIndex(tabModel, tabModel.indexOf(tab));
                }
            });
            try {
                pageLoadedCallbacks[i].waitForCallback(0);
            } catch (TimeoutException e) {
                fail("PAGE_LOAD_FINISHED was not received for tabId=" + tabIds[i]);
            }
        }
    }

    /**
     * Long presses the view, selects an item from the context menu, and
     * asserts that a new tab is opened and is incognito iff expectIncognito is true.
     * @param view The View to long press.
     * @param contextMenuItemId The context menu item to select on the view.
     * @param expectIncognito Whether the opened tab is expected to be incognito.
     * @param expectedUrl The expected url for the new tab.
     */
    protected void invokeContextMenuAndOpenInANewTab(View view, int contextMenuItemId,
            boolean expectIncognito, final String expectedUrl) throws InterruptedException {
        final CallbackHelper createdCallback = new CallbackHelper();
        final TabModel tabModel = getActivity().getTabModelSelector().getModel(expectIncognito);
        tabModel.addObserver(new EmptyTabModelObserver() {
            @Override
            public void didAddTab(Tab tab, TabLaunchType type) {
                if (TextUtils.equals(expectedUrl, tab.getUrl())) {
                    createdCallback.notifyCalled();
                    tabModel.removeObserver(this);
                }
            }
        });

        TestTouchUtils.longClickView(getInstrumentation(), view);
        assertTrue(getInstrumentation().invokeContextMenuAction(getActivity(),
                contextMenuItemId, 0));

        try {
            createdCallback.waitForCallback(0);
        } catch (TimeoutException e) {
            fail("Never received tab creation event");
        }

        if (expectIncognito) {
            assertTrue(getActivity().getTabModelSelector().isIncognitoSelected());
        } else {
            assertFalse(getActivity().getTabModelSelector().isIncognitoSelected());
        }
    }
}


text:
package yelpInterview;

import java.util.Arrays;

public class _Array08RotateArray {
	public static void main(String a[]){
		int[] inputArray = new int[]{1, 2, 3, 4, 5, 6,7};
		System.out.println(Arrays.toString(inputArray));
		inputArray=rotateArray(inputArray,6);
		System.out.println(Arrays.toString(inputArray));
	}

	private static int[] rotateArray(int[] inputArray, int count) {
		for (int i = 0; i < count; i++) {
			inputArray=rotate(inputArray);
		}
		return inputArray;
	}

	private static int[] rotate(int[] inputArray) {
		int temp=inputArray[0];
		for (int i = 1; i < inputArray.length; i++) {
			inputArray[i]=temp^inputArray[i];
			temp=temp^inputArray[i];
			inputArray[i]=temp^inputArray[i];
		}
		inputArray[0]=temp;
		return inputArray;
	}
}


text:
@implementation ShowAlbumCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        self.posterImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 60, 60)];
        [self.contentView addSubview:self.posterImageView];

        self.albumNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(70, 15, 120, 30)];
        [self.contentView addSubview:self.albumNameLabel];

        self.albumCountLabel = [[UILabel alloc] initWithFrame:CGRectMake(190, 15, 80, 30)];
        [self.contentView addSubview:self.albumCountLabel];

    }
    return self;
}

- (void)configWithALAssetsGroup:(ALAssetsGroup *)group {
    CGImageRef posterImageRef = [group posterImage];
    UIImage *posterImage = [UIImage imageWithCGImage:posterImageRef];
    self.posterImageView.image = posterImage;
    self.albumNameLabel.text = [group valueForProperty:ALAssetsGroupPropertyName];
    self.albumCountLabel.text = [NSString stringWithFormat:@"(%d)",[@(group.numberOfAssets) intValue]];

}

@end


text:
package vaadin.scala.internal

trait Listener {
  def action: Any

  protected def wrapperFor[T](vaadinComponent: com.vaadin.ui.Component): Option[T] = WrapperUtil.wrapperFor[T](vaadinComponent)
}


text:
'use strict';

/**
 * Any regex added here should have a test written for it in ../test/RegexPill_test.js
 * This list should always be in alphabetical order for ease of use
 */
var RegexLibraryContents = {
    "uri/db/mongodb": /^(mongodb:\/\/)([a-z0-9]+:[a-z0-9]+@)?([a-zA-Z0-9-_.]+)(:[0-9]+)?(\/[a-z_-]+)?$/g,
};

var RegexLibrary = function(name) {
    if (!name) {
        throw new ReferenceError("A regex name should be passed to this constructor.");
    }

    this.setRegex(name);

    return this._regex;
};

RegexLibrary.prototype.setRegex = function(name) {
    if (RegexLibraryContents[name]) {
        this._regex = RegexLibraryContents[name];
    } else {
        this._regex = "";
    }
};

RegexLibrary.prototype.list = function() {
    return RegexLibraryContents;
};

module.exports = RegexLibrary;


text:
module PasswordAspect

    module ClassMethods
      # call-seq:
      #   trylogin(:email => String, :password => String) => User
      #
      # Versuche User mit den attributen email und password anzumelden
      # Bei Erfolg wird ein User zurückgegeben, bei Misserfolg nil
      def trylogin(attributes)
        p = attributes.delete :password
        u = self.find(:first, :limit => 1, :conditions => attributes)
        u.password = p
        u.authenticated? ? u : nil
      rescue ActiveRecord::RecordNotFound, NoMethodError
        nil
      end
    end

    def self.included(model) # :nodoc:
       model.extend  ClassMethods
       model.class_eval do
         attr_protected :hashed_password, :salt
         attr_accessor  :password, :old_password, :security_token
         before_save :generate_salt_and_hashed_password
         validates_presence_of     :password, :if => :new_user?
         validates_confirmation_of :password
         validates_length_of       :password, :minimum => 6, :allow_nil => true, :if => :changing_password?
         validate                  :password_change_allowed
         before_create             :generate_salt
       end
    end

    def authenticated?
      verify_password self.password
    end

    def generate_security_token(key='')
      encrypt "cdslgsdim;#{salt}#{email}#{hashed_password}#{key}"
    end

    def set_correct_token(k='')
      self.security_token = generate_security_token(k)
    end

    def security_token_valid?(k='')
      security_token == generate_security_token(k)
    end

    def email_unique?
      strip_email
      mail_owner = User.find_by_email(self.email)
      mail_owner.nil? || mail_owner.id == self.id
    end

  protected

    def encrypt(str)
      Digest::SHA256.hexdigest(str)
    end

    def generate_salt
      self.salt = encrypt("--#{Time.now.to_s}--#{email}--")
    end

    def generate_salt_and_hashed_password
      unless self.password.blank?
        generate_salt
        self.hashed_password = encrypt("#{self.password}#{self.salt}")
      end
    end

    def password_change_allowed
      if changing_password? && !security_token_valid? && !verify_password(self.old_password)
        errors.add :security_token, "Incorrect"
        errors.add :old_password, "Incorrect"
      end
    end

    # Eine Passwortänderung liegt vor, wenn passwort gesetzt ist und
    # es sich nicht um einen neuen User handelt
    def changing_password?
      #password not blank and existing user
      !self.password.blank? && !new_user?
    end

    def verify_password(pw)
      self.hashed_password == encrypt("#{pw}#{self.salt}")
    end

    # Sagt ob es sich um einen neuen User handelt
    #
    # Wenn kein hashed_password existiert muss es sich um einen neuen User
    # oder um einen Unshadow User handeln
    def new_user?
      hashed_password.blank?
    end

    def strip_email
      self.email = self.email.strip.downcase unless self.email.nil?
    end
end


text:
var five = require("../lib/johnny-five.js");
var board = new five.Board();

board.on("ready", function() {

  // Create a new generic sensor instance for
  // a sensor connected to an analog (ADC) pin
  var sensor = new five.Sensor("A0");

  // When the sensor value changes, log the value
  sensor.on("change", function() {
    console.log(this.value);
  });
});


text:
using Cosmos.Logging.Events;

namespace Cosmos.Logging.Core {
    /// <summary>
    /// Interface for message property value factory
    /// </summary>
    public interface IMessagePropertyValueFactory {
        /// <summary>
        /// Create property value
        /// </summary>
        /// <param name="value"></param>
        /// <param name="mode"></param>
        /// <param name="positionalValue"></param>
        /// <returns></returns>
        MessagePropertyValue CreatePropertyValue(object value, PropertyResolvingMode mode, int positionalValue = -1);
    }
}


text:
JuicyPixels-canvas
==================

Functions for drawing lines, squares and so on pixel by pixel.

Fore more details see: https://hackage.haskell.org/package/JuicyPixels-canvas


text:
package com.jayway.jsonpath.internal.function;

import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.Configurations;
import org.apache.commons.io.IOUtils;
import org.junit.Test;

import java.util.Arrays;
import java.util.HashSet;

/**
 * Author: Sergey Saiyan sergey.sova42@gmail.com
 * Created at 21/02/2018.
 */
public class KeySetFunctionTest extends BaseFunctionTest {

    private Configuration conf = Configurations.JACKSON_CONFIGURATION;

    @Test
    public void testKeySet() throws Exception {
        String json = IOUtils.toString(getClass().getResourceAsStream("/keyset.json"));
        verifyFunction(conf, "$.data.keys()", json, new HashSet<String>(Arrays.asList("a", "b")));
    }
}


text:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = process.env.PORT || 8080;
var NanoTimer = require('nanotimer');

// When a user visits the website
app.get('/', function(req, res){
  res.send('moppy megserver');
});

// This is called when a client connects
io.on('connection', function(socket){
  console.log('connected client');
  client = socket;
  startTimer();

  // Make the session timeout after 10s automatically
  const sessionTimeout = 60;
  setTimeout(function(){
    timer.clearInterval();
    endSession();
  }, sessionTimeout*1000);
});

// Log the session statistics when the user disconnects
io.on('disconnect', function(socket){
  console.log('user disconnected!')
  endSession();
});

http.listen(port, function(){
  console.log('begin listening for connections');
});

// Define variables
var client;                   // The iPhone app
var timer = new NanoTimer();  // Used to time sending new samples
var numberChannels = 10;      // The number of channels to simulate
var startTime = Date.now();   // Used to get time t for sine waves
var frequency = 30;           // The frequency to send samples at
var samplesSent = 0;          // The number of samples sent so far

// Generate Random Data at regular intervals
function startTimer() {

  // Mark the time when the signals begin
  startTime   = Date.now();
  samplesSent = 0;

  timer.setInterval(function(){

    // Time t for calculating this set of samples
    const t = (Date.now() - startTime)/1000;

    // An array of measurements
    // Sine waves for now
    var measurements = Array(numberChannels);
    for(var i = 0; i < numberChannels; i++) {
      measurements[i] = Math.sin(2*Math.PI*5*t - i*(Math.PI/numberChannels)) + 0.25*Math.sin(2*Math.PI*3*t)
      + Math.random()*0.1;
    }

    // Create a JavaScript object of data
    var data = {
      "data":measurements
    };

    // Convert to a UTF8 JSON string
    var stringy = JSON.stringify(data);

    // Send the measurenemts out to all of the clients
    io.emit('data', stringy);
    samplesSent += 1;

  // How often the timer fires is set to the sampling interval in ms
  }, '', 1000/frequency + 'm');
}

// Log the session statistics and disconnect the client
function endSession() {
  console.log('Session Statistics')

  const t = (Date.now() - startTime)/1000;
  console.log('time: ' + t + 's');
  console.log('samples: ' + samplesSent);
  console.log('freq: ' + samplesSent/t + '\n');

  client.disconnect();
}


text:
using System.IO;

namespace AntShares.IO
{
    public interface ISerializable
    {
        void Serialize(BinaryWriter writer);
        void Deserialize(BinaryReader reader);
    }
}


text:
====================
salt.renderers.wempy
====================

.. automodule:: salt.renderers.wempy
    :members: