text:
App.loadCss($('<link href="themes/admin/assets/excel-zone/excel-zone.css" rel="stylesheet"/>'));

App.loadJs($('<script src="themes/admin/assets/excel-zone/xlsx/jszip.min.js"></script>'));
App.loadJs($('<script src="themes/admin/assets/excel-zone/xlsx/xlsx.js"></script>'));
App.loadJs($('<script src="themes/admin/assets/excel-zone/xlsx/ods.js"></script>'));

(function($){

    var use_worker = typeof Worker !== 'undefined';

    function to_json(workbook) {
        var result = {};
        workbook.SheetNames.forEach(function (sheetName) {
            var roa = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
            if (roa.length > 0) {
                result[sheetName] = roa;
            }
        });
        return result;
    }

    function xlsxworker_noxfer(data, cb) {
            var worker = new Worker('/themes/admin/assets/excel-zone/xlsxworker.js');
            worker.onmessage = function(e) {
                    switch(e.data.t) {
                            case 'ready': break;
                            case 'e': console.error(e.data.d); break;
                            case 'xlsx': cb(JSON.parse(e.data.d)); break;
                    }
            };
            worker.postMessage({d:data});
    }

    function xlsxworker(data, cb) {
            xlsxworker_noxfer(data, cb);
    }

    App.Func.handleExcelZone = function(selector){
        var drop = selector.find('.drop')[0];
        function handleDrop(e) {
            e.stopPropagation();
            e.preventDefault();
            var files = e.dataTransfer.files;
            handleFile(files);
        }

        function handleDragover(e) {
            e.stopPropagation();
            e.preventDefault();
            e.dataTransfer.dropEffect = 'copy';
        }

        if (drop.addEventListener) {
            drop.addEventListener('dragenter', handleDragover, false);
            drop.addEventListener('dragover', handleDragover, false);
            drop.addEventListener('drop', handleDrop, false);
        }

        function handleFile(files) {
            var i, f;
            for (i = 0, f = files[i]; i != files.length; ++i) {
                var reader = new FileReader();
                reader.onload = function (e) {
                    var data = e.target.result;
                    if (use_worker) {
                        xlsxworker(data, process_wb);
                    } else {
                        var wb = XLSX.read(data, {type: 'binary'});

                        process_wb(wb);
                    }
                };

                reader.readAsBinaryString(f);
            }
        }

        function process_wb(wb) {
            var output = to_json(wb);
            selector.triggerHandler('onReadData', [output]);
        }
        var fileEl = selector.find('input:file');
        $(drop).bind('click', function(){
            fileEl.trigger('click');
            return false;
        });
        fileEl.change(function (e) {
            handleFile(e.target.files);
        });

    };

})(jQuery);


text:
package ws.ament.hammock.mp.cochise.test;

import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.arquillian.test.spi.enricher.resource.ResourceProvider;
import ws.ament.hammock.HammockRuntime;

import javax.enterprise.inject.spi.CDI;
import java.lang.annotation.Annotation;
import java.net.URI;

public class HammockURIProvider implements ResourceProvider {
    @Override
    public Object lookup(ArquillianResource arquillianResource, Annotation... annotations) {
        HammockRuntime hammockRuntime = CDI.current().select(HammockRuntime.class).get();
        return URI.create(hammockRuntime.getMachineURL());
    }

    @Override
    public boolean canProvide(Class<?> type) {
        return type.isAssignableFrom(URI.class);
    }

}

redpajama_set_name: RedPajamaGithub


text:
package org.elasticsearch.cluster.coordination;

import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.service.ClusterApplier;

import java.util.function.Supplier;

public class NoOpClusterApplier implements ClusterApplier {
    @Override
    public void setInitialState(ClusterState initialState) {

    }

    @Override
    public void onNewClusterState(String source, Supplier<ClusterState> clusterStateSupplier, ClusterApplyListener listener) {
        listener.onSuccess(source);
    }
}


text:
"""
A simple command-line weather app using Python 3 and following modules:

http://docs.python.org/3.3/library/optparse.html
http://docs.python.org/3.3/library/json.html
http://www.python-requests.org/en/latest/
https://pypi.python.org/pypi/PrettyTable

Major thanks to the creators of the following APIs:

https://developers.google.com/maps/documentation/geocoding/
https://developer.forecast.io/
http://freegeoip.net/
http://ip.42.pl

And also to the people over at gnuplot:
http://www.gnuplot.info/
"""

import datetime as dt
import os
import json
import requests
import subprocess
import sys
import time
from optparse import OptionParser
from prettytable import PrettyTable

NUM_HOURLY_RECORDS = 16

speed = ["mph", "m/s"]
degrees = ["°F", "°C"]
length = ["in", "cm"]

parser = OptionParser()

with open(os.path.join(os.path.dirname(__file__), "private.json")) as f:
	private = json.loads(f.read())
	api_key = private["api_key"]
	loc = private["latitude"] + "," + private["longitude"]

try:
	ip = requests.get("http://ip.42.pl/raw").text
	geo_url = "http://freegeoip.net/{0}/{1}".format("json", ip)
	location_info = requests.get(geo_url).json()
	longitude = str(location_info["longitude"])
	latitude = str(location_info["latitude"])
	loc = latitude + "," + longitude
except Exception as e:
	print("Failed to detect location. Using default value from private.json")

parser.set_defaults(debug=False, graphics=False, location="", metric=False, now=False, today=False, week=False)
parser.add_option("-d", "--debug", action="store_true", help="show debug messages")
parser.add_option("-g", "--graphics", action="store_true", help="display visuals for weekly forecasts")
parser.add_option("-l", "--location", help="specify a location other than the default")
parser.add_option("-m", "--metric", action="store_true", help="use metric rather than imperial units")
parser.add_option("-n", "--now", action="store_true", help="display the current weather summary")
parser.add_option("-t", "--today", action="store_true", help="display today's hourly forecast")
parser.add_option("-w", "--week", action="store_true", help="display the weekly forecast")

(options, args) = parser.parse_args()

if options.debug:
	print()
	print("Options: " + str(options))
	print("Args: " + str(args))

if options.location:
	loc_url = "http://maps.googleapis.com/maps/api/geocode/json?address=M{0}&sensor=false".format(options.location)
	loc_info = requests.get(loc_url).json()
	lat_long = loc_info["results"][0]["geometry"]["location"]
	latitude = lat_long["lat"]
	longitude = lat_long["lng"]
	loc = str(latitude) + "," + str(longitude)

url = "https://api.forecast.io/forecast/{0}/{1}".format(api_key, loc)

if options.metric:
	url += "?units=si"

try:
	response = requests.get(url).json()
except:
	print("There was an error retrieving the forecast.")
	print("Please check your internet connection and try again.")
	sys.exit()

def plot_weekly():
	highs = []
	lows = []
	rain = []
	days = []
	for day in response["daily"]["data"]:
		highs.append(str(day["temperatureMax"]))
		lows.append(str(day["temperatureMin"]))
		rain.append(str(day["precipProbability"]))
		try:  # this may be too hacky, buuuut it works for now...
			days.append(str(int(days[len(days) - 1]) + 1))
		except IndexError:
			days.append(str(dt.datetime.weekday(dt.datetime.fromtimestamp(day["time"])) + 1))

	start_day = time.ctime(response["daily"]["data"][0]["time"]).split(" ")
	start_day = list(filter(None, start_day))  # required since time.ctime() pads left with an extra space for 1-digit dates
	start_day_pretty = start_day[0] + ' ' + start_day[1] + ' ' + start_day[2]

	end_day = time.ctime(response["daily"]["data"][-1]["time"]).split(" ")
	end_day = list(filter(None, end_day))  # required since time.ctime() pads left with an extra space for 1-digit dates
	end_day_pretty = end_day[0] + ' ' + end_day[1] + ' ' + end_day[2]

	period = start_day_pretty + " - " + end_day_pretty

	plot_data = []
	for day, low, high in zip(days, lows, highs):
		plot_data.append(day + "\t" + low + "\t" + high + "\n")

	gnuplot = subprocess.Popen(['gnuplot', '-persist'], stdin=subprocess.PIPE).stdin

	# Find the next value mod 5 == 0 next to the plot data's minimum and maximum
	plot_min = int(round(min(float(x) for x in lows) / 5.0) * 5.0) - 5
	plot_max = int(round(max(float(x) for x in highs) / 5.0) * 5.0) + 5

	# adjust the plot height so that y-axis spacing is consistent
	plot_height = int((plot_max - plot_min) / 2.5) + 6

	gnuplot = subprocess.Popen(['gnuplot', '-persist'], stdin=subprocess.PIPE).stdin

	plot_title = "'High and Low Temperatures, {0}'\n".format(period)

	setup_gnuplot(gnuplot, plot_title, plot_height, days[0], days[-1], plot_min, plot_max)

	gnuplot.write("plot '-' u 1:2 w l, '-' u 1:3 w l\n".encode())
	for line in plot_data:  # iterate through once for the lows
		gnuplot.write(line.encode())
	gnuplot.write("e\n".encode())  # 'e' is the end-of-input marker for gnuplot
	for line in plot_data:  # then again for the highs (per gnuplot docs)
		gnuplot.write(line.encode())
	gnuplot.write("e\n".encode())
	gnuplot.flush()

def setup_gnuplot(gnuplot_proc, title, height, xmin, xmax, ymin, ymax):
	gnuplot_proc.write("set terminal dumb size 79, {0}\n".format(height).encode())  # allows space for title and temp increments of 5
	gnuplot_proc.write("set title {0}\n".format(title).encode())
	gnuplot_proc.write("set nokey\n".encode())
	gnuplot_proc.write("set xdtics\n".encode())
	gnuplot_proc.write("set xrange [{0}:{1}]\n".format(xmin, xmax).encode())
	gnuplot_proc.write("set yrange [{0}:{1}]\n".format(ymin, ymax).encode())
	gnuplot_proc.write("set ytics 0,5\n".encode())
	gnuplot_proc.write("set tic scale 0\n".encode())

def display_current_weather():
	summary = response["currently"]["summary"]
	current_temp = response["currently"]["temperature"]
	current_wind = response["currently"]["windSpeed"]
	chance_of_rain = response["currently"]["precipProbability"]

	print()
	print("Current conditions: {0}".format(summary))
	print("Current temperature: {0}".format(current_temp) + " " + degrees[options.metric])
	print("Winds: {0} ".format(current_wind) + speed[options.metric])
	print("Chance of precipitation: {0}%".format(chance_of_rain))
	print()

def display_hourly_forecast():
	day_summary = response["hourly"]["summary"]

	print()
	print("Hourly forecast: {0}".format(day_summary))

	table = PrettyTable([
		"Time",
		"Summary",
		"Precipitation",
		"Temperature",
		"Wind",
		"Humidity"
	])

	for hour in response["hourly"]["data"][0:NUM_HOURLY_RECORDS]:
		dt = time.ctime(hour["time"]).split()
		short_dt = dt[0] + " " + dt[3][0:5]
		table.add_row([
			short_dt,
			hour["summary"],
			str(int(hour["precipProbability"]*100)) + "%",
			str(hour["temperature"]) + " " + degrees[options.metric],
			str(hour["windSpeed"]) + " " + speed[options.metric],
			str(int(hour["humidity"]*100)) + "%"
		])

	print(table)

def display_weekly_forecast():
	week_summary = response["daily"]["summary"]

	print()
	print("Forecast for the coming week: {0}".format(week_summary))

	table = PrettyTable([
		"Day",
		"Summary",
		"Precipitation",
		"High",
		"Low",
		"Wind",
		"Humidity"
	])

	for day in response["daily"]["data"]:
		dt = time.ctime(day["time"]).split()
		short_dt = dt[0] + " " + dt[1] + " " + dt[2]
		table.add_row([
			short_dt,
			day["summary"],
			str(int(day["precipProbability"]*100)) + "%",
			str(day["temperatureMax"]) + " " + degrees[options.metric],
			str(day["temperatureMin"]) + " " + degrees[options.metric],
			str(day["windSpeed"]) + " " + speed[options.metric],
			str(int(day["humidity"]*100)) + "%"
		])
	print(table)

if __name__ == "__main__":
	if options.now:
		display_current_weather()
	if options.graphics:
		plot_weekly()
	if options.today:
		display_hourly_forecast()
	if options.week:
		display_weekly_forecast()


text:
/**
 * set the login status to be true
 *
 * @arg uid{string} is the user id
 */
var loginAsTrialUser = function() {
  return { type: "LOGIN_AS_TRIAL_USER", operand: undefined };
};

/**
 * unset the login status
 */
var doLogout = function() {
  return { type: "DO_LOGOUT", operand: undefined };
};

/**
 * perform the registration action
 */
var doRegistration = function() {
  return { type: "DO_REGISTRATION", operand: undefined };
};

/**
 * add an new event
 */
var doNewEvent = function() {
  return { type: "DO_NEW_EVENT", operand: undefined };
};

/**
 * reset the current session using the provided data
 */
var resetSession = function(data) {
  return { type: "RESET_LOGIN", operand: data };
};

/**
 * delete event
 */
var doDeleteEvent = function(index) {
  return { type: "DO_DELETE_EVENT", operand: index };
};

/* export the action creation functions */
module.exports.loginAsTrialUser = loginAsTrialUser;
module.exports.doLogout = doLogout;
module.exports.doRegistration = doRegistration;
module.exports.resetSession = resetSession;
module.exports.doNewEvent = doNewEvent;
module.exports.doDeleteEvent = doDeleteEvent;


text:
<moya xmlns="http://moyaproject.com"
      xmlns:let="http://moyaproject.com/let"
      xmlns:db="http://moyaproject.com/db"
      xmlns:forms="http://moyaproject.com/forms"
      xmlns:auth="http://moyaproject.com/auth"
      xmlns:email="http://moyaproject.com/email">

	<mountpoint name="main" libname="mountpoint.main">
        <url route="/login/" methods="GET, POST" view="#view.login.post" name="login"/>
		<url route="/logout/" methods="GET" view="#view.logout" name="logout"/>
        <url route="/edit/" methods="GET, POST" view="#view.user_edit" name="user_edit" />
        <url route="/forgot-password/" methods="GET,POST" view="#view.forgot_password" name="forgot_password" />
        <url route="/reset/{token}/" methods="GET, POST" view="#view.reset_password" name="reset_password" />
	</mountpoint>

    <mountpoint name="middleware">
        <middleware route="/{*}" methods="GET,POST" macro="middleware.add_user_to_context" />
        <url route="/{*}" handler="forbidden">
            <redirect name="login" query="fwd=.request.path" />
        </url>
    </mountpoint>

    <macro docname="middleware.response_middleware">
    </macro>

    <handle signal="db.pre-create" sender="#User">
        <fire signal="moya.auth.new-user" let:user="signal.data.object" />
    </handle>

    <macro docname="get_permissions">
        <return>
            <auth:get-permissions user=".user"/>
        </return>
    </macro>

    <macro docname="middleware.add_user_to_context">
        <auth:get-user dst=".user" lazy="yes" />
        <call macro="get_permissions" dst=".permissions" lazy="yes" />
    </macro>

	<view libname="view.login" content="#content.login">
        <forms:get form="#form.login" dst="form"/>
	</view>

    <view libname="view.login.post" content="#content.login">
        <forms:get form="#form.login" dst="form" />
        <if-post>
            <forms:validate src="form">
                <try>
                    <auth:login username="form.data.username" password="form.data.password"/>
                    <redirect-to url="${form.data.fwd or .app.settings.default_fwd or '/'}" />
                </try>
                <catch exception="moya.auth.no-user,moya.auth.password-fail">
                    <forms:error src="form">No user with those credentials.</forms:error>
                </catch>
                <catch exception="moya.auth.forbidden.not-validated">
                    <forms:error src="form">A validated email is required.</forms:error>
                    <let validate_email="yes"/>
                </catch>
                <catch exception="moya.auth.forbidden.*">
                    <forms:error src="form">Sorry, you can't log in at this time.</forms:error>
                </catch>
                <catch exception="moya.auth.multiple-emails">
                    <forms:error src="form">Multiple users with that email address, please enter a username.</forms:error>
                </catch>
                <catch exception="moya.auth.*">
                    <forms:error src="form">The server was unable to log you in at this time. Please try again later.</forms:error>
                </catch>
            </forms:validate>
        </if-post>
    </view>

    <view libname="view.logout">
        <auth:logout/>
        <redirect-to url="${.request.GET.fwd or '/'}" />
    </view>

    <view libname="view.user_edit" content="#content.user_edit" requires=".user">
        <forms:get form="#form.user_edit" dst="user_form" src=".user" bind="None"/>
        <forms:get form="#form.password_change" dst="password_form" src=".user" bind="None"/>
        <if-post>
            <switch on=".request.POST.action">
                <case>details</case>
                <let-str tab="details"/>
                <forms:bind src="user_form"/>
                <forms:validate src="user_form">
                    <forms:apply src="user_form" dst=".user" />
                    <let details_success="yes" />
                </forms:validate>

                <case>password</case>
                <let-str tab="password"/>
                <forms:bind src="password_form"/>
                <forms:validate src="password_form">
                    <auth:set-password user=".user" password="password_form.data.new_password"/>
                    <let password_success="yes"/>
                    <forms:reset src="password_form"/>
                </forms:validate>
            </switch>
        </if-post>
    </view>

    <view libname="view.forgot_password" content="#content.forgot_password">
        <forms:get form="#form.forgot_password" dst="form"/>
        <if-post>
            <forms:validate src="form">
                <db:get model="#User" let:email="form.data.email" dst="user" />
                <if test="not user">
                    <forms:error src="form">No user with that email address</forms:error>
                    <done/>
                </if>
                <attempt times="10">
                    <db:create model="#ResetPassword" let:user="user" dst="reset_password" />
                </attempt>
                <email:send email="#email.password_reset"
                    to="${reset_password.user.email}"
                    let:name="user.first_name or user.username"
                    let:token="reset_password.token"
                    let:project_title=".settings.project_title"
                    let:site_url=".request.host_url" />
            </forms:validate>
        </if-post>
    </view>

    <view libname="view.reset_password" content="#content.reset_password">
        <forms:get form="#form.reset_password" dst="form"
            let:token="url.token"/>

        <get-url name="login" dst="login_url" />
        <get-url name="forgot_password" dst="forgot_password_url" />

        <db:get model="#ResetPassword" let:token="url.token" dst="reset_password"/>
        <let badtoken="not bool:reset_password" />

        <if-post>
            <forms:validate src="form">
                <db:get model="#ResetPassword" let:token="form.data.token" dst="reset_password"/>
                <if test="not reset_password">
                    <forms:error src="form">Reset token not found. Have you already used this link?</forms:error>
                </if>
                <else>
                    <auth:set-password user="reset_password.user" password="form.data.password" />
                    <let success="yes" />
                    <db:delete src="reset_password" />
                </else>
            </forms:validate>
        </if-post>

    </view>

</moya>


text:
void RenderScene(void)
	{
	// Clear the window with current clearing color
	glClear(GL_COLOR_BUFFER_BIT);

   	// Set current drawing color to red
	//		   R	 G	   B
	glColor3f(1.0f, 0.0f, 0.0f);

	// Draw a filled rectangle with current color
	glRectf(-25.0f, 25.0f, 25.0f, -25.0f);

	// Flush drawing commands
    glFlush();
	}

///////////////////////////////////////////////////////////
// Setup the rendering state
void SetupRC(void)
    {
    // Set clear color to blue
    glClearColor(0.0f, 0.0f, 1.0f, 1.0f);
    }

///////////////////////////////////////////////////////////
// Called by GLUT library when the window has chanaged size
void ChangeSize(int w, int h)
	{
	GLfloat aspectRatio;

	// Prevent a divide by zero
	if(h == 0)
		h = 1;

	// Set Viewport to window dimensions
    glViewport(0, 0, w, h);

	// Reset coordinate system
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();

	// Establish clipping volume (left, right, bottom, top, near, far)
	aspectRatio = (GLfloat)w / (GLfloat)h;
    if (w <= h)
		glOrtho (-100.0, 100.0, -100 / aspectRatio, 100.0 / aspectRatio, 1.0, -1.0);
    else
		glOrtho (-100.0 * aspectRatio, 100.0 * aspectRatio, -100.0, 100.0, 1.0, -1.0);

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	}

///////////////////////////////////////////////////////////
// Main program entry point
int main(int argc, char* argv[])
    {
    glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
    //    glutInitWindowSize(800, 600);
	glutCreateWindow("GLRect");
	glutDisplayFunc(RenderScene);
    glutReshapeFunc(ChangeSize);
	SetupRC();
	glutMainLoop();

    return 0;
    }


text:
{% load branding %}
{% load themes %}


text:
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
 *     Copyright 2015 Couchbase, Inc
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

/*
 *                "ewouldblock_engine"
 *
 * The "ewouldblock_engine" allows one to test how memcached responds when the
 * engine returns EWOULDBLOCK instead of the correct response.
 */
#pragma once

#include "config.h"

#include <memcached/protocol_binary.h>

/** Binary protocol command used to control this engine. */
const uint8_t PROTOCOL_BINARY_CMD_EWOULDBLOCK_CTL = 0xeb;

extern "C" {
    /**
     * Definition of the packet used to control this engine:
     */
    typedef union {
        struct {
            protocol_binary_request_header header;
            struct {
                uint32_t mode; // See EWB_Engine_Mode
                uint32_t value;
                uint32_t inject_error; // ENGINE_ERROR_CODE to inject.
            } body;
        } message;
        uint8_t bytes[sizeof(protocol_binary_request_header) +
                      sizeof(uint32_t) +
                      sizeof(uint32_t) +
                      sizeof(uint32_t)];
    } request_ewouldblock_ctl;

    /**
     * Definition of the packet returned by ewouldblock_ctl requests.
     */
    typedef protocol_binary_response_no_extras response_ewouldblock_ctl;
}

// The mode the engine is currently operating in. Determines when it will
// inject EWOULDBLOCK instead of the real return code.
enum class EWBEngineMode : uint32_t {
    // Make the next_N calls into engine return {inject_error}. N specified
    // by the {value} field.
    Next_N = 0,

    // Randomly return {inject_error}. Chance to return {inject_error} is
    // specified as an integer percentage (1,100) in the {value} field.
    Random = 1,

    // The first call to a given function from each connection will return
    // {inject_error}, with the next (and subsequent) calls to he *same*
    // function operating normally. Calling a different function will reset
    // back to failing again.  In other words, return {inject_error} iif the
    // previous function was not this one.
    First = 2,

    // Make the next N calls return a sequence of either their normal value or
    // the injected error code. The sequence can be up to 32 elements long.
    Sequence = 3,

    // Simulate CAS mismatch - make the next N store operations return
    // KEY_EEXISTS. N specified by the {value} field.
    CasMismatch = 4,

    // Increment the cluster map sequence number. Value and inject_error is
    // ignored for this opcode
    IncrementClusterMapRevno = 5
};


text:
import bcrypt from 'bcrypt';

let num = 10;
let str = 'password';
let bool = false;

str = bcrypt.genSaltSync();
str = bcrypt.genSaltSync(num);

bcrypt.genSalt((err, salt) => {
  str = salt;
});
bcrypt.genSalt(num, (err, salt) => {
  str = salt;
});
(bcrypt.genSalt(): Promise<string>);
(bcrypt.genSalt(num): Promise<string>);

str = bcrypt.hashSync(str, str);
str = bcrypt.hashSync(str, num);

bcrypt.hash(str, str, (err, encrypted) => {
  str = encrypted;
});
bcrypt.hash(str, num, (err, encrypted) => {
  str = encrypted;
});
(bcrypt.hash(str, str): Promise<string>);
(bcrypt.hash(str, num): Promise<string>);

bool = bcrypt.compareSync(str, str);
bcrypt.compare(str, str, (err, same) => {
  bool = same;
});
(bcrypt.compare(str, str): Promise<bool>);
// $FlowExpectedError
bcrypt.compare(str, num);

num = bcrypt.getRounds(str);


text:
foam.CLASS({
  package :'foam.box',
  name: 'InvalidMessageException',
  swiftImplements: ['Error'],

  properties: [
    'messageType'
  ]
});


text:
<?php
    $enlaces = array(
        array(
            'titulo' => 'Dashboard',
            'url' => site_url('admin/dashboard')
            )
    );
?>

<?php $this->load->view('admin/header', array('li_dashboard' => 'class="active"', 'enlaces' => $enlaces));?>

                        language

Página inicial

<?php $this->load->view('admin/footer');?>


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Poseidon.Recovery.ClientDx
{
    using DevExpress.XtraCharts;
    using Poseidon.Core.Utility;
    using Poseidon.Recovery.Core.Utility;

    /// <summary>
    /// 账户相关饼图
    /// </summary>
    public partial class AccountPieChart : DevExpress.XtraEditors.XtraUserControl
    {
        #region Constructor
        public AccountPieChart()
        {
            InitializeComponent();
        }
        #endregion //Constructor

        #region Method
        /// <summary>
        /// 设置图表标题
        /// </summary>
        /// <param name="text"></param>
        public void SetChartTitle(string text)
        {
            this.chartMain.Titles[0].Text = text;
        }

        /// <summary>
        /// 设置系列标签单位
        /// </summary>
        /// <param name="unit">单位</param>
        public void SetSeriesLabel(string unit)
        {
            this.chartMain.Series[0].Label.TextPattern = "{A}-{V}" + unit;
        }
        #endregion //Method

        #region Event
        /// <summary>
        /// 打印
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void menuPrint_Click(object sender, EventArgs e)
        {
            this.chartMain.ShowRibbonPrintPreview();
        }
        #endregion //Event

        #region Property
        /// <summary>
        /// 数据源
        /// </summary>
        [Description("数据源")]
        public List<AccountDataModel> DataSource
        {
            get
            {
                return this.bsAccountData.DataSource as List<AccountDataModel>;
            }
            set
            {
                this.bsAccountData.DataSource = value;
            }
        }
        #endregion //Property
    }
}


text:
package com.example.android.sunshine.data;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

import com.example.android.sunshine.R;

public class SunshinePreferences {

    private Context context;
    private String defaultWeatherLocation;
    private String temperatureUnits;

    public SunshinePreferences(Context context) {
        this.context = context;
        setUpPreferences();
    }

    public void setUpPreferences()
    {
        setUpLocationPreference();
        setUpTemperatureUnitsPreferences();
    }

    public void setUpLocationPreference() {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
        String prefLocationKey = context.getString(R.string.pref_location_key);
        defaultWeatherLocation = sharedPreferences.getString(prefLocationKey, SunshinePreferences.DEFAULT_WEATHER_LOCATION);
    }

    public void setUpTemperatureUnitsPreferences() {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
        String prefTempUnitKey = context.getString(R.string.pref_temperature_units_key);
        temperatureUnits = sharedPreferences.getString(prefTempUnitKey, SunshinePreferences.DEFAULT_TEMPERATURE_UNIT_VALUE);
    }

    /*
     * Human readable location string, provided by the API.  Because for styling,
     * "Mountain View" is more recognizable than 94043.
     */
    public static final String PREF_CITY_NAME = "city_name";

    /*
     * In order to uniquely pinpoint the location on the map when we launch the
     * map intent, we store the latitude and longitude.
     */
    public static final String PREF_COORD_LAT = "coord_lat";
    public static final String PREF_COORD_LONG = "coord_long";

    public static final String DEFAULT_WEATHER_LOCATION = "Mountain View, CA, 94843";
    public static final String DEFAULT_TEMPERATURE_UNIT_VALUE = "metric";
    private static final double[] DEFAULT_WEATHER_COORDINATES = {37.4284, 122.0724};

    private static final String DEFAULT_MAP_LOCATION =
            "1600 Amphitheatre Parkway, Mountain View, CA 94043";

    /**
     * Helper method to handle setting location details in Preferences (city name, latitude,
     * longitude)
     * <p>
     * When the location details are updated, the database should to be cleared.
     *
     * @param context  Context used to get the SharedPreferences
     * @param lat      the latitude of the city
     * @param lon      the longitude of the city
     */
    public static void setLocationDetails(Context context, double lat, double lon) {
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
        SharedPreferences.Editor editor = sp.edit();

        editor.putLong(PREF_COORD_LAT, Double.doubleToRawLongBits(lat));
        editor.putLong(PREF_COORD_LONG, Double.doubleToRawLongBits(lon));
        editor.apply();
    }

    /**
     * Helper method to handle setting a new location in preferences.  When this happens
     * the database may need to be cleared.
     *
     * @param c               Context used to get the SharedPreferences
     * @param locationSetting The location string used to request updates from the server.
     * @param lat             The latitude of the city
     * @param lon             The longitude of the city
     */
    static public void setLocation(Context c, String locationSetting, double lat, double lon) {
        /** This will be implemented in a future lesson **/
    }

    /**
     * Resets the stored location coordinates.
     *
     * @param c Context used to get the SharedPreferences
     */
    static public void resetLocationCoordinates(Context c) {
        /** This will be implemented in a future lesson **/
    }

    /**
     * Returns the location currently set in Preferences. The default location this method
     * will return is "94043,USA", which is Mountain View, California. Mountain View is the
     * home of the headquarters of the Googleplex!
     *
     * @return Location The current user has set in SharedPreferences. Will default to
     * "94043,USA" if SharedPreferences have not been implemented yet.
     */
    public String getPreferredWeatherLocation() {
        return getDefaultWeatherLocation();
    }

    /**
     * Returns true if the user has selected metric temperature display.
     *
     * @param context Context used to get the SharedPreferences
     * @return true if metric display should be used, false if imperial display should be used
     */
    public static boolean isMetric(Context context) {
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);

        String keyForUnits = context.getString(R.string.pref_temperature_units_key);
        String defaultUnits = context.getString(R.string.pref_temperature_metric_value);
        String preferredUnits = sp.getString(keyForUnits, defaultUnits);
        String metric = context.getString(R.string.pref_temperature_metric_value);

        boolean userPrefersMetric = false;
        if (metric.equals(preferredUnits)) {
            userPrefersMetric = true;
        }

        return userPrefersMetric;
    }

    /**
     * Returns the location coordinates associated with the location.  Note that these coordinates
     * may not be set, which results in (0,0) being returned. (conveniently, 0,0 is in the middle
     * of the ocean off the west coast of Africa)
     *
     * @param context Used to get the SharedPreferences
     * @return An array containing the two coordinate values.
     */
    public static double[] getLocationCoordinates(Context context) {
        return getDefaultWeatherCoordinates();
    }

    /**
     * Returns true if the latitude and longitude values are available. The latitude and
     * longitude will not be available until the lesson where the PlacePicker API is taught.
     *
     * @param context used to get the SharedPreferences
     * @return true if lat/long are set
     */
    public static boolean isLocationLatLonAvailable(Context context) {
        /** This will be implemented in a future lesson **/
        return false;
    }

    public String getDefaultWeatherLocation() {
        return defaultWeatherLocation;
    }

    public void setDefaultWeatherLocation(String defaultWeatherLocation) {
        this.defaultWeatherLocation = defaultWeatherLocation;
    }

    public String getTemperatureUnits() {
        return temperatureUnits;
    }

    public void setTemperatureUnits(String temperatureUnits) {
        this.temperatureUnits = temperatureUnits;
    }

    public static double[] getDefaultWeatherCoordinates() {
        /** This will be implemented in a future lesson **/
        return DEFAULT_WEATHER_COORDINATES;
    }

    /**
     * Saves the time that a notification is shown. This will be used to get the ellapsed time
     * since a notification was shown.
     *
     * @param context Used to access SharedPreferences
     * @param timeOfNotification Time of last notification to save (in UNIX time)
     */
    public static void saveLastNotificationTime(Context context, long timeOfNotification) {
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
        SharedPreferences.Editor editor = sp.edit();
        String lastNotificationKey = context.getString(R.string.pref_last_notification);
        editor.putLong(lastNotificationKey, timeOfNotification);
        editor.apply();
    }
}


text:
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import classnames from 'classnames'
import { validate } from 'validate.js'
import * as validationRules from '../../helpers/validation'

import GroupSelector from '../Groups/GroupSelector'
import GroupButton from '../Groups/GroupButton'
import ContactFormButtons from './ContactFormButtons'

class ContactForm extends Component {
  constructor(props) {
    super(props)
    let contact = props.contact || {}
    this.state = {
      contact: contact,
      name: contact.name,
      phone: contact.phone,
      email: contact.email,
      imageUrl: contact.imageUrl,
      group: contact.group || 'all',
      visibile: props.visibile,
      detailView: props.detailView,
      error: ''
    }
  }
  componentWillReceiveProps(nextProps) {
    this.setState({visibile: nextProps.visibile})
  }
  handleError = (err) => {
    if (typeof err == 'object'){
      this.setState({ error: err[0] })
    } else {
      this.setState({ error: err })
    }
  }
  handleClear = () => {
    if(this.state.detailView){
      this.props.onClear()
    } else {
      let notEmpty = (this.name.value || this.phone.value || this.email.value) ? true : false
      if(notEmpty){
        let conformation = confirm('Are you sure you want to discard changes?')
        if (conformation){
          this.name.value = ''
          this.phone.value = ''
          this.email.value = ''
          this.imageUrl.value = ''
          this.setState({error: ''})
        } else {
          console.log("Cancelled")
        }
      }
      this.props.onClear()
    }
  }
  handleSubmitForm = (e) => {
    e.preventDefault()
    let name = this.name.value.trim()
    let phone = this.phone.value
    let email = this.email.value
    let imageUrl = this.imageUrl.value

    if (phone && phone.length > 0 && phone.match(/^\d+$/)){
      phone = Number(phone)
    }

    let errors = this.validateInput(name, phone, email, imageUrl)
    if (errors){
      this.handleError(errors)
    }
    else {
      this.props.onSubmit(name, phone, email, imageUrl, this.state.group, this.handleError)
    }
  }
  validateInput = (name, phone, email, imageUrl) => {
    let errorDetector = ''
    let valid = validate({name: name}, validationRules.nameCheck, {format: "flat"})
    errorDetector += valid ? valid : ''

    // checkPhone
    if (phone && phone.length > 0){
      valid = validate({phone: phone}, validationRules.phoneCheck, {format: "flat"})
      errorDetector += valid ? (' ' + valid) : ''
    }
    //check email
    if (email && email.length > 0){
      valid = validate({email: email}, validationRules.emailCheck, {format: "flat"})
      errorDetector += valid ? (' ' + valid) : ''
    }
    //check image
    if (imageUrl && imageUrl.length > 0){
      valid = validate({imageUrl: imageUrl}, validationRules.urlCheck, {format: "flat"})
      errorDetector += valid ? (' ' + valid) : ''
    }
    return errorDetector
  }
  handleSelect = (selected) => {
    this.setState({
      group: selected
    })
  }
  toggleView = () => {
    this.setState({
      detailView: !this.state.detailView
    })
  }
  liveChangeName = (e) => {
    this.setState({name: e.target.value})
  }

  render(){
    const {state: {contact, name, phone, email, group, detailView, isEdited, visibile, error}} = this
    let imageUrl = contact.imageUrl ||
    'https://trendytheme.net/wp-content/themes/trendytheme/img/client.png'

    return (

              { this.props.createView ?

 Create Contact

                :

{name}

                      <button
                        className='btn btn-default edit-comment'
                        onClick={this.toggleView}>

                      </button>
                      <button
                        className='btn btn-default remove-comment'
                        onClick={this.props.onRemove}>

                      </button>

                    { Object.getOwnPropertyNames(contact).length ?
                      <GroupButton group={contact.group} toggleModal={this.props.onClear}/> : ''}

                }

                { error.length > 0 ?
{error}
 :''}
                <form className="form col-md-12 center-block" onSubmit={this.handleSubmitForm}>

                    { detailView ?
{name}

                    :
                    <input
                      className='form-control'
                      id='contact-name'
                      type="text"
                      placeholder='name'
                      defaultValue={name}
                      onChange={this.liveChangeName}
                      ref={node => this.name = node}
                    />
                  }

                  { detailView ?
{phone}

                  :
                  <input
                    className='form-control'
                    id='contact-phone'
                    type="text"
                    placeholder='phone'
                    defaultValue={phone}
                    ref={node => this.phone = node}
                  />
                }

                { detailView ?
<a href={`mailto:${email}`}>{email}

                :
                <input
                  className='form-control'
                  type="text"
                  id='contact-email'
                  placeholder='email'
                  defaultValue={email}
                  ref={node => this.email = node}
                />
              }

              { detailView ?
{imageUrl}

              :
              <input
                className='form-control'
                id='contact-imageUrl'
                type="text"
                placeholder='image url'
                defaultValue={imageUrl}
                ref={node => this.imageUrl = node}
              />
            }

          { detailView ? ''
          :
          <GroupSelector
            onSelect={this.handleSelect}
            hideIcon={false}
            selectedOption={group}
            smallButtons={false}
          />
        }

          <ContactFormButtons
            onClear={this.handleClear}
            hideSubmit={detailView}
          />

      </form>

)
}
}

ContactForm.propTypes = {
  onSubmit: PropTypes.func.isRequired,
  onClear: PropTypes.func,
  showIcons: PropTypes.bool,
  contact: PropTypes.object,
  detailView: PropTypes.bool.isRequired,
}

export default ContactForm


text:
    <link rel="stylesheet" href="../theme/default/style.css" type="text/css" />
    <link rel="stylesheet" href="style.css" type="text/css" />

Popup Mayhem

      All kinds of ways to create and interact with Popups.

If you open an anchoredbubble and switch to google, it shouldn't crash. If it does, don't release OpenLayers.

 click to add Popup to map

 click to add a Marker with an AnchoredBubble popup

 click to modify popup's attributes

 click to remove the popup from map

 click to remove the markers layer

 marker.onscreen()?

 click to destroy the popup from map

      Detailed description of this example needs to be written.


text:
package org.itevents.dao.mybatis.util;

import org.itevents.model.Event;
import org.itevents.model.Technology;

import java.util.Iterator;
import java.util.List;

public class AddEventTechnologySqlBuilder {

    public String addEventTechnology(final Event event) {
        List<Technology> technologies = event.getTechnologies();
        StringBuilder sql = new StringBuilder();
        if (technologies != null && technologies.size() > 0) {
            sql.append("INSERT INTO event_technology (event_id, technology_id) VALUES ");
            Iterator<Technology> iterator = technologies.iterator();
            while (iterator.hasNext()) {
                sql.append("(").append(event.getId()).append(", ").append(iterator.next().getId()).append(")");
                if (iterator.hasNext()) {
                    sql.append(", ");
                }
            }
        }
        return sql.toString();
    }
}


text:
Kafka Offset Monitor
===========

[![Build Status](https://travis-ci.org/quantifind/KafkaOffsetMonitor.svg?branch=master)](https://travis-ci.org/quantifind/KafkaOffsetMonitor)

This is an app to monitor your kafka consumers and their position (offset) in the queue.

You can see the current consumer groups, for each group the topics that they are consuming and the position of the group in each topic queue. This is useful to understand how quick you are consuming from a queue and how fast the queue is growing. It allows for debuging kafka producers and consumers or just to have an idea of what is going on in  your system.

The app keeps an history of queue position and lag of the consumers so you can have an overview of what has happened in the last days.

Here are a few screenshots:

List of Consumer Groups
-----------------------

![Consumer Groups](http://quantifind.github.io/KafkaOffsetMonitor/img/groups.png)

List of Topics for a Group
--------------------------

![Topic List](http://quantifind.github.io/KafkaOffsetMonitor/img/topics.png)

History of Topic position
-------------------------

![Position Graph](http://quantifind.github.io/KafkaOffsetMonitor/img/graph.png)

Running It
===========

If you do not want to build it manually, just download the [current jar](https://github.com/quantifind/KafkaOffsetMonitor/releases/latest).

This is a small webapp, you can run it locally or on a server, as long as you have access to the ZooKeeper nodes controlling kafka.

```
java -cp KafkaOffsetMonitor-assembly-0.2.1.jar \
     com.quantifind.kafka.offsetapp.OffsetGetterWeb \
     --zk zk-server1,zk-server2 \
     --port 8080 \
     --refresh 10.seconds \
     --retain 2.days
```

The arguments are:

- **zk** the ZooKeeper hosts
- **port** on what port will the app be available
- **refresh** how often should the app refresh and store a point in the DB
- **retain** how long should points be kept in the DB
- **dbName** where to store the history (default 'offsetapp')

Contributing
============

The KafkaOffsetMonitor is released under the Apache License and we **welcome any contributions** within this license. Any pull request is welcome and will be reviewed and merged as quickly as possible.

Because this open source tool is released by [Quantifind](http://www.quantifind.com) as a company, if you want to submit a pull request, you will have to sign the following simple contributors agreement:
- If you are an individual, please sign [this contributors agreement](https://docs.google.com/a/quantifind.com/document/d/1RS7qEjq3cCmJ1665UhoCMK8541Ms7KyU3kVFoO4CR_I/) and send it back to contributors@quantifind.com
- If you are contributing changes that you did as part of your work, please sign [this contributors agreement](https://docs.google.com/a/quantifind.com/document/d/1kNwLT4qG3G0Ct2mEuNdBGmKDYuApN1CpQtZF8TSVTjE/) and send it back to contributors@quantifind.com


text:
package com.ibm.cloudoe.samples;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.ibm.db2.jcc.DB2SimpleDataSource;

import com.ibm.nosql.json.api.BasicDBList;
import com.ibm.nosql.json.api.BasicDBObject;
import com.ibm.nosql.json.util.JSON;

// @author PvR, IBM 2013
// @version 0.3

public class DbHelper {
    private static Logger logger = Logger.getLogger(DbHelper.class.getName());
    // set defaults
    private String databaseHost = "";
    private int port = 50000;
    private String databaseName = "";
    private String user = "";
    private String password = "";
    private String url = "";

    public DbHelper() {
    }

    private boolean processVCAP() {
        // VCAP_SERVICES is a system environment variable
        // Parse it to obtain the for DB2 connection info
        String VCAP_SERVICES = System.getenv("VCAP_SERVICES");
        logger.log(Level.INFO, "VCAP_SERVICES content: " + VCAP_SERVICES);

        if (VCAP_SERVICES != null) {
            // parse the VCAP JSON structure
            BasicDBObject obj = (BasicDBObject) JSON.parse(VCAP_SERVICES);
            String thekey = null;
            Set<String> keys = obj.keySet();
            logger.log(Level.INFO, "Searching through VCAP keys");
            // Look for the VCAP key that holds the SQLDB information
            for (String eachkey : keys) {
                logger.log(Level.INFO, "Key is: " + eachkey);
                // Just in case the service name gets changed to lower case in the future, use toUpperCase
                if (eachkey.toUpperCase().contains("SQLDB")) {
                    thekey = eachkey;
                }
            }
            if (thekey == null) {
                logger.log(Level.INFO, "Cannot find any SQLDB service in the VCAP; exiting");
                return false;
            }
            BasicDBList list = (BasicDBList) obj.get(thekey);
            obj = (BasicDBObject) list.get("0");
            logger.log(Level.INFO, "Service found: " + obj.get("name"));
            // parse all the credentials from the vcap env variable
            obj = (BasicDBObject) obj.get("credentials");
            databaseHost = (String) obj.get("host");
            databaseName = (String) obj.get("db");
            port = (Integer)obj.get("port");
            user = (String) obj.get("username");
            password = (String) obj.get("password");
            url = (String) obj.get("jdbcurl");
        } else {
            logger.log(Level.INFO, "VCAP_SERVICES is null");
            return false;
        }
        logger.log(Level.INFO, "database host: " + databaseHost);
        logger.log(Level.INFO, "database port: " + port);
        logger.log(Level.INFO, "database name: " + databaseName);
        logger.log(Level.INFO, "username: " + user);
        logger.log(Level.INFO, "password: " + password);
        logger.log(Level.INFO, "url: " + url);
        return true;
    }

    public String getValue() {
        logger.log(Level.INFO, "IBM SQL Database, Java Demo Application using DB2 drivers");
        logger.log(Level.INFO, "Servlet: " + this.getClass().getName());
//        logger.log(Level.INFO, "Host IP:" + InetAddress.getLocalHost().getHostAddress());

        String value = null;

        // process the VCAP env variable and set all the global connection parameters
        if (processVCAP()) {

            // Connect to the Database
            Connection con;
            try {
                logger.log(Level.INFO, "Connecting to the database");
                DB2SimpleDataSource dataSource = new DB2SimpleDataSource();
                dataSource.setServerName(databaseHost);
                dataSource.setPortNumber(port);
                dataSource.setDatabaseName(databaseName);
                dataSource.setUser(user);
                dataSource.setPassword (password);
                dataSource.setDriverType(4);
                con=dataSource.getConnection();
                con.setAutoCommit(false);
            } catch (SQLException e) {
                logger.log(Level.INFO, "Error connecting to database");
                logger.log(Level.INFO, "SQL Exception: " + e);
                return null;
            }

            // Try out some dynamic SQL Statements
            Statement stmt = null;
            String tableName = "PROPERTIES";
            String sqlStatement = "";

            // Execute some SQL statements on the table: Insert, Select and Delete
            try {
                stmt = con.createStatement();
                sqlStatement = "SELECT VALUE FROM " + tableName + " WHERE NAME = 'property1'";
                ResultSet rs = stmt.executeQuery(sqlStatement);
                logger.log(Level.INFO, "Executing: " + sqlStatement);

                // Process the result set
                while (rs.next()) {
                    value = rs.getString(1);
                    logger.log(Level.INFO, "  Found value: " + value);
                }
                // Close the ResultSet
                rs.close();
            } catch (SQLException e) {
                logger.log(Level.INFO, "Error executing:" + sqlStatement);
                logger.log(Level.INFO, "SQL Exception: " + e);
            }

            // Close everything off
            try {
                // Close the Statement
                if (stmt != null) {
                    stmt.close();
                }
                // Connection must be on a unit-of-work boundary to allow close
                if (con != null) {
                    con.commit();
                    // Close the connection
                    con.close();
                }
                logger.log(Level.INFO, "Finished");

            } catch (SQLException e) {
                logger.log(Level.INFO, "Error closing things off");
                logger.log(Level.INFO, "SQL Exception: " + e);
            }
        }
        System.out.close();
        return value;
    }
}


text:
describe('validators.email', function() {
  var email = validate.validators.email;
  email = email.bind(email);

  afterEach(function() {
    delete validate.validators.email.message;
    delete validate.validators.email.options;
  });

  it("allows undefined values", function() {
    expect(email(null, {})).not.toBeDefined();
    expect(email(undefined, {})).not.toBeDefined();
  });

  it("doesn't allow non strings", function() {
    expect(email(3.14, {})).toBeDefined();
    expect(email(true, {})).toBeDefined();
  });

  it("allows valid emails", function() {
    expect(email('nicklas@ansman.se', {})).not.toBeDefined();
    expect(email('NiCkLaS@AnSmAn.Se', {})).not.toBeDefined();
    // Source: https://en.wikipedia.org/wiki/Email_address#Valid_email_addresses
    expect(email('niceandsimple@example.com', {})).not.toBeDefined();
    expect(email('very.common@example.com', {})).not.toBeDefined();
    expect(email('a.little.lengthy.but.fine@dept.example.com', {})).not.toBeDefined();
    expect(email('disposable.style.email.with+symbol@example.com', {})).not.toBeDefined();
    expect(email('other.email-with-dash@example.com', {})).not.toBeDefined();
    expect(email("foo@some.customtld", {})).not.toBeDefined();
  });

  it("doesn't allow 'invalid' emails", function() {
    var expected = "is not a valid email";
    expect(email("", {})).toEqual(expected);
    expect(email(" ", {})).toEqual(expected);
    expect(email("foobar", {})).toEqual(expected);
    expect(email("foo@bar", {})).toEqual(expected);
    expect(email('üñîçøðé@example.com', {})).toEqual(expected);

    // Source: https://en.wikipedia.org/wiki/Email_address#Invalid_email_addresses
    expect(email('abc.example.com', {})).toEqual(expected);
    expect(email('a@b@c@example.com', {})).toEqual(expected);
    expect(email('a"b(c)d,e:f;g<h>i[j\\k]l@example.com', {})).toEqual(expected);
    expect(email('just"not"right@example.com', {})).toEqual(expected);
    expect(email('this is"not\\allowed@example.com', {})).toEqual(expected);
    expect(email('this\\ still\\"not\\\\allowed@example.com', {})).toEqual(expected);
  });

  it("allows you to customize the error message", function() {
    validate.validators.email.message = "is totally not an email";
    expect(email("foobar", {})).toEqual("is totally not an email");
    var options = {message: "some other message"};
    expect(email("foobar", options)).toEqual("some other message");
  });

  it("supports default options", function() {
    validate.validators.email.options = {message: "barfoo"};
    var options = {message: 'foobar'};
    expect(email("foo", options)).toEqual('foobar');
    expect(email("foo", {})).toEqual('barfoo');
    expect(validate.validators.email.options).toEqual({message: "barfoo"});
    expect(options).toEqual({message: "foobar"});
  });

  it("allows functions as messages", function() {
    var message = function() { return "foo"; };
    var options = {message: message}
      , value = "foo";
    expect(email(value, options)).toBe(message);
  });
});


text:
/*
 * Created by SharpDevelop.
 * User: dcbelmont
 * Date: 16/02/2016
 * Time: 16:43
 *
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Windows.Forms;

namespace ExpressionBuilder
{
	/// <summary>
	/// Class with program entry point.
	/// </summary>
	internal sealed class Program
	{
		/// <summary>
		/// Program entry point.
		/// </summary>
		[STAThread]
		private static void Main(string[] args)
		{
			Application.EnableVisualStyles();
			Application.SetCompatibleTextRenderingDefault(false);
			Application.Run(new MainForm());
		}
	}
}


text:
package me.lucko.conditionalperms.hooks.impl;

import me.lucko.conditionalperms.ConditionalPerms;
import me.lucko.conditionalperms.events.PlayerFactionsRegionChangeEvent;
import me.lucko.conditionalperms.hooks.AbstractHook;
import me.lucko.conditionalperms.utils.FactionsRegion;
import me.lucko.helper.Events;
import me.lucko.helper.terminable.TerminableConsumer;
import me.markeh.factionsframework.FactionsFramework;
import me.markeh.factionsframework.entities.FPlayer;
import me.markeh.factionsframework.entities.FPlayers;
import me.markeh.factionsframework.entities.Faction;
import me.markeh.factionsframework.entities.Factions;
import me.markeh.factionsframework.enums.Rel;
import me.markeh.factionsframework.layer.EventsLayer;

import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerQuitEvent;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class FactionsHook extends AbstractHook {
    private Map<UUID, FactionsRegion> regions = new HashMap<>();

    FactionsHook(ConditionalPerms plugin) {
        super(plugin);

        FactionsFramework.load(getPlugin());
        // We don't need events
        HandlerList.unregisterAll(EventsLayer.get());
        FactionsFramework.get();
    }

    @Override
    public void setup(TerminableConsumer consumer) {
        consumer.bindRunnable(() -> FactionsFramework.get().stop());

        Events.subscribe(PlayerLoginEvent.class)
                .handler(e -> regions.put(e.getPlayer().getUniqueId(), getRegion(e.getPlayer())))
                .bindWith(consumer);

        Events.subscribe(PlayerQuitEvent.class)
                .handler(e -> regions.remove(e.getPlayer().getUniqueId()))
                .bindWith(consumer);

        Events.subscribe(PlayerMoveEvent.class)
                .filter(Events.DEFAULT_FILTERS.ignoreSameChunk())
                .filter(e -> shouldCheck(FactionsHook.class, e.getPlayer().getUniqueId()))
                .handler(e -> {
                    FactionsRegion from = regions.get(e.getPlayer().getUniqueId());
                    FactionsRegion to = getRegion(e.getPlayer());

                    if (from.equals(to)) {
                        return;
                    }

                    getPlugin().getServer().getPluginManager().callEvent(new PlayerFactionsRegionChangeEvent(e.getPlayer(), from, to));
                    regions.put(e.getPlayer().getUniqueId(), to);
                })
                .bindWith(consumer);
    }

    public FactionsRegion getRegion(Player player) {
        final FPlayer p = FPlayers.getBySender(player);
        if (p == null) return FactionsRegion.NONE;

        Faction factionAt = p.getFactionAt();
        if (factionAt == null) return FactionsRegion.NONE;
        if (factionAt.isNone()) return FactionsRegion.NONE;
        if (factionAt.getId().equals(p.getFaction().getId())) return FactionsRegion.OWN;
        if (factionAt.getId().equals(Factions.getWarZone(player.getWorld()).getId())) return FactionsRegion.WARZONE;
        if (factionAt.getId().equals(Factions.getSafeZone(player.getWorld()).getId())) return FactionsRegion.SAFEZONE;

        Rel rel = factionAt.getRelationTo(p.getFaction());
        if (rel == Rel.ALLY) return FactionsRegion.ALLY;
        if (rel == Rel.ENEMY) return FactionsRegion.ENEMY;
        if (rel == Rel.TRUCE) return FactionsRegion.TRUCE;
        if (rel == Rel.NEUTRAL) return FactionsRegion.NEUTRAL;

        return FactionsRegion.NONE;
    }
}


text:
// Copyright (c) 2011-present, Facebook, Inc.  All rights reserved.
//  This source code is licensed under both the GPLv2 (found in the
//  COPYING file in the root directory) and Apache 2.0 License
//  (found in the LICENSE.Apache file in the root directory).
//
// This file implements the "bridge" between Java and C++ and enables
// calling C++ ROCKSDB_NAMESPACE::SstFileWriter methods
// from Java side.

#include <jni.h>
#include <string>

#include "include/org_rocksdb_SstFileWriter.h"
#include "rocksdb/comparator.h"
#include "rocksdb/env.h"
#include "rocksdb/options.h"
#include "rocksdb/sst_file_writer.h"
#include "rocksjni/portal.h"

/*
 * Class:     org_rocksdb_SstFileWriter
 * Method:    newSstFileWriter
 * Signature: (JJJB)J
 */
jlong Java_org_rocksdb_SstFileWriter_newSstFileWriter__JJJB(
    JNIEnv * /*env*/, jclass /*jcls*/, jlong jenvoptions, jlong joptions,
    jlong jcomparator_handle, jbyte jcomparator_type) {
  ROCKSDB_NAMESPACE::Comparator *comparator = nullptr;
  switch (jcomparator_type) {
    // JAVA_COMPARATOR
    case 0x0:
      comparator = reinterpret_cast<ROCKSDB_NAMESPACE::ComparatorJniCallback *>(
          jcomparator_handle);
      break;

    // JAVA_NATIVE_COMPARATOR_WRAPPER
    case 0x1:
      comparator =
          reinterpret_cast<ROCKSDB_NAMESPACE::Comparator *>(jcomparator_handle);
      break;
  }
  auto *env_options =
      reinterpret_cast<const ROCKSDB_NAMESPACE::EnvOptions *>(jenvoptions);
  auto *options =
      reinterpret_cast<const ROCKSDB_NAMESPACE::Options *>(joptions);
  ROCKSDB_NAMESPACE::SstFileWriter *sst_file_writer =
      new ROCKSDB_NAMESPACE::SstFileWriter(*env_options, *options, comparator);
  return reinterpret_cast<jlong>(sst_file_writer);
}

/*
 * Class:     org_rocksdb_SstFileWriter
 * Method:    newSstFileWriter
 * Signature: (JJ)J
 */
jlong Java_org_rocksdb_SstFileWriter_newSstFileWriter__JJ(JNIEnv * /*env*/,
                                                          jclass /*jcls*/,
                                                          jlong jenvoptions,
                                                          jlong joptions) {
  auto *env_options =
      reinterpret_cast<const ROCKSDB_NAMESPACE::EnvOptions *>(jenvoptions);
  auto *options =
      reinterpret_cast<const ROCKSDB_NAMESPACE::Options *>(joptions);
  ROCKSDB_NAMESPACE::SstFileWriter *sst_file_writer =
      new ROCKSDB_NAMESPACE::SstFileWriter(*env_options, *options);
  return reinterpret_cast<jlong>(sst_file_writer);
}

/*
 * Class:     org_rocksdb_SstFileWriter
 * Method:    open
 * Signature: (JLjava/lang/String;)V
 */
void Java_org_rocksdb_SstFileWriter_open(JNIEnv *env, jobject /*jobj*/,
                                         jlong jhandle, jstring jfile_path) {
  const char *file_path = env->GetStringUTFChars(jfile_path, nullptr);
  if (file_path == nullptr) {
    // exception thrown: OutOfMemoryError
    return;
  }
  ROCKSDB_NAMESPACE::Status s =
      reinterpret_cast<ROCKSDB_NAMESPACE::SstFileWriter *>(jhandle)->Open(
          file_path);
  env->ReleaseStringUTFChars(jfile_path, file_path);

  if (!s.ok()) {
    ROCKSDB_NAMESPACE::RocksDBExceptionJni::ThrowNew(env, s);
  }
}

/*
 * Class:     org_rocksdb_SstFileWriter
 * Method:    put
 * Signature: (JJJ)V
 */
void Java_org_rocksdb_SstFileWriter_put__JJJ(JNIEnv *env, jobject /*jobj*/,
                                             jlong jhandle, jlong jkey_handle,
                                             jlong jvalue_handle) {
  auto *key_slice = reinterpret_cast<ROCKSDB_NAMESPACE::Slice *>(jkey_handle);
  auto *value_slice =
      reinterpret_cast<ROCKSDB_NAMESPACE::Slice *>(jvalue_handle);
  ROCKSDB_NAMESPACE::Status s =
      reinterpret_cast<ROCKSDB_NAMESPACE::SstFileWriter *>(jhandle)->Put(
          *key_slice, *value_slice);
  if (!s.ok()) {
    ROCKSDB_NAMESPACE::RocksDBExceptionJni::ThrowNew(env, s);
  }
}

/*
 * Class:     org_rocksdb_SstFileWriter
 * Method:    put
 * Signature: (JJJ)V
 */
void Java_org_rocksdb_SstFileWriter_put__J_3B_3B(JNIEnv *env, jobject /*jobj*/,
                                                 jlong jhandle, jbyteArray jkey,
                                                 jbyteArray jval) {
  jbyte *key = env->GetByteArrayElements(jkey, nullptr);
  if (key == nullptr) {
    // exception thrown: OutOfMemoryError
    return;
  }
  ROCKSDB_NAMESPACE::Slice key_slice(reinterpret_cast<char *>(key),
                                     env->GetArrayLength(jkey));

  jbyte *value = env->GetByteArrayElements(jval, nullptr);
  if (value == nullptr) {
    // exception thrown: OutOfMemoryError
    env->ReleaseByteArrayElements(jkey, key, JNI_ABORT);
    return;
  }
  ROCKSDB_NAMESPACE::Slice value_slice(reinterpret_cast<char *>(value),
                                       env->GetArrayLength(jval));

  ROCKSDB_NAMESPACE::Status s =
      reinterpret_cast<ROCKSDB_NAMESPACE::SstFileWriter *>(jhandle)->Put(
          key_slice, value_slice);

  env->ReleaseByteArrayElements(jkey, key, JNI_ABORT);
  env->ReleaseByteArrayElements(jval, value, JNI_ABORT);

  if (!s.ok()) {
    ROCKSDB_NAMESPACE::RocksDBExceptionJni::ThrowNew(env, s);
  }
}

/*
 * Class:     org_rocksdb_SstFileWriter
 * Method:    putDirect
 * Signature: (JLjava/nio/ByteBuffer;IILjava/nio/ByteBuffer;II)V
 */
void Java_org_rocksdb_SstFileWriter_putDirect(JNIEnv *env, jobject /*jdb*/,
                                              jlong jdb_handle, jobject jkey,
                                              jint jkey_off, jint jkey_len,
                                              jobject jval, jint jval_off,
                                              jint jval_len) {
  auto *writer =
      reinterpret_cast<ROCKSDB_NAMESPACE::SstFileWriter *>(jdb_handle);
  auto put = [&env, &writer](ROCKSDB_NAMESPACE::Slice &key,
                             ROCKSDB_NAMESPACE::Slice &value) {
    ROCKSDB_NAMESPACE::Status s = writer->Put(key, value);
    if (s.ok()) {
      return;
    }
    ROCKSDB_NAMESPACE::RocksDBExceptionJni::ThrowNew(env, s);
  };
  ROCKSDB_NAMESPACE::JniUtil::kv_op_direct(put, env, jkey, jkey_off, jkey_len,
                                           jval, jval_off, jval_len);
}

/*
 * Class:     org_rocksdb_SstFileWriter
 * Method:    fileSize
 * Signature: (J)J
 */
jlong Java_org_rocksdb_SstFileWriter_fileSize(JNIEnv * /*env*/, jobject /*jdb*/,
                                              jlong jdb_handle) {
  auto *writer =
      reinterpret_cast<ROCKSDB_NAMESPACE::SstFileWriter *>(jdb_handle);
  return static_cast<jlong>(writer->FileSize());
}

/*
 * Class:     org_rocksdb_SstFileWriter
 * Method:    merge
 * Signature: (JJJ)V
 */
void Java_org_rocksdb_SstFileWriter_merge__JJJ(JNIEnv *env, jobject /*jobj*/,
                                               jlong jhandle, jlong jkey_handle,
                                               jlong jvalue_handle) {
  auto *key_slice = reinterpret_cast<ROCKSDB_NAMESPACE::Slice *>(jkey_handle);
  auto *value_slice =
      reinterpret_cast<ROCKSDB_NAMESPACE::Slice *>(jvalue_handle);
  ROCKSDB_NAMESPACE::Status s =
      reinterpret_cast<ROCKSDB_NAMESPACE::SstFileWriter *>(jhandle)->Merge(
          *key_slice, *value_slice);
  if (!s.ok()) {
    ROCKSDB_NAMESPACE::RocksDBExceptionJni::ThrowNew(env, s);
  }
}

/*
 * Class:     org_rocksdb_SstFileWriter
 * Method:    merge
 * Signature: (J[B[B)V
 */
void Java_org_rocksdb_SstFileWriter_merge__J_3B_3B(JNIEnv *env,
                                                   jobject /*jobj*/,
                                                   jlong jhandle,
                                                   jbyteArray jkey,
                                                   jbyteArray jval) {
  jbyte *key = env->GetByteArrayElements(jkey, nullptr);
  if (key == nullptr) {
    // exception thrown: OutOfMemoryError
    return;
  }
  ROCKSDB_NAMESPACE::Slice key_slice(reinterpret_cast<char *>(key),
                                     env->GetArrayLength(jkey));

  jbyte *value = env->GetByteArrayElements(jval, nullptr);
  if (value == nullptr) {
    // exception thrown: OutOfMemoryError
    env->ReleaseByteArrayElements(jkey, key, JNI_ABORT);
    return;
  }
  ROCKSDB_NAMESPACE::Slice value_slice(reinterpret_cast<char *>(value),
                                       env->GetArrayLength(jval));

  ROCKSDB_NAMESPACE::Status s =
      reinterpret_cast<ROCKSDB_NAMESPACE::SstFileWriter *>(jhandle)->Merge(
          key_slice, value_slice);

  env->ReleaseByteArrayElements(jkey, key, JNI_ABORT);
  env->ReleaseByteArrayElements(jval, value, JNI_ABORT);

  if (!s.ok()) {
    ROCKSDB_NAMESPACE::RocksDBExceptionJni::ThrowNew(env, s);
  }
}

/*
 * Class:     org_rocksdb_SstFileWriter
 * Method:    delete
 * Signature: (JJJ)V
 */
void Java_org_rocksdb_SstFileWriter_delete__J_3B(JNIEnv *env, jobject /*jobj*/,
                                                 jlong jhandle,
                                                 jbyteArray jkey) {
  jbyte *key = env->GetByteArrayElements(jkey, nullptr);
  if (key == nullptr) {
    // exception thrown: OutOfMemoryError
    return;
  }
  ROCKSDB_NAMESPACE::Slice key_slice(reinterpret_cast<char *>(key),
                                     env->GetArrayLength(jkey));

  ROCKSDB_NAMESPACE::Status s =
      reinterpret_cast<ROCKSDB_NAMESPACE::SstFileWriter *>(jhandle)->Delete(
          key_slice);

  env->ReleaseByteArrayElements(jkey, key, JNI_ABORT);

  if (!s.ok()) {
    ROCKSDB_NAMESPACE::RocksDBExceptionJni::ThrowNew(env, s);
  }
}

/*
 * Class:     org_rocksdb_SstFileWriter
 * Method:    delete
 * Signature: (JJJ)V
 */
void Java_org_rocksdb_SstFileWriter_delete__JJ(JNIEnv *env, jobject /*jobj*/,
                                               jlong jhandle,
                                               jlong jkey_handle) {
  auto *key_slice = reinterpret_cast<ROCKSDB_NAMESPACE::Slice *>(jkey_handle);
  ROCKSDB_NAMESPACE::Status s =
      reinterpret_cast<ROCKSDB_NAMESPACE::SstFileWriter *>(jhandle)->Delete(
          *key_slice);
  if (!s.ok()) {
    ROCKSDB_NAMESPACE::RocksDBExceptionJni::ThrowNew(env, s);
  }
}

/*
 * Class:     org_rocksdb_SstFileWriter
 * Method:    finish
 * Signature: (J)V
 */
void Java_org_rocksdb_SstFileWriter_finish(JNIEnv *env, jobject /*jobj*/,
                                           jlong jhandle) {
  ROCKSDB_NAMESPACE::Status s =
      reinterpret_cast<ROCKSDB_NAMESPACE::SstFileWriter *>(jhandle)->Finish();
  if (!s.ok()) {
    ROCKSDB_NAMESPACE::RocksDBExceptionJni::ThrowNew(env, s);
  }
}

/*
 * Class:     org_rocksdb_SstFileWriter
 * Method:    disposeInternal
 * Signature: (J)V
 */
void Java_org_rocksdb_SstFileWriter_disposeInternal(JNIEnv * /*env*/,
                                                    jobject /*jobj*/,
                                                    jlong jhandle) {
  delete reinterpret_cast<ROCKSDB_NAMESPACE::SstFileWriter *>(jhandle);
}


text:
require_relative 'spec_helper'

shared_examples_for 'chef version' do |version, _args = {}|
  describe package('chef') do
    it { should be_installed }
  end

  describe command('chef-client -v') do
    its(:stdout) { should match(/Chef: #{version}/) }
  end
end


text:
An object containing the user environment. See environ(7).

An example of this object looks like:

    { TERM: 'xterm-256color',
      SHELL: '/usr/local/bin/bash',
      USER: 'maciej',
      PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin',
      PWD: '/Users/maciej',
      EDITOR: 'vim',
      SHLVL: '1',
      HOME: '/Users/maciej',
      LOGNAME: 'maciej',
      _: '/usr/local/bin/node' }

You can write to this object, but changes won't be reflected outside of your
process. That means that the following won't work:

    node -e 'process.env.foo = "bar"' && echo $foo

But this will:

    process.env.foo = 'bar';
    console.log(process.env.foo);


text:
async function showView(viewTemplate, viewObj) {
    let source = await $.get('./templates/' + viewTemplate + '.hbs');
    let compiled = Handlebars.compile(source);
    let template = compiled(viewObj);
    $('#page').html(template);
}

async function showHideMenuLinks() {
    let authToken = sessionStorage.getItem('authToken');
    let headers = window.headers.unAuthHeaders;
    if (authToken) {
        headers = window.headers.authHeaders;
        $('#loggedInUser').text("Welcome, " + sessionStorage.getItem('username') + "!")
    } else {
        $('#loggedInUser').text('');
    }
    let source = await $.get('./templates/header-template.hbs');
    let compiled = Handlebars.compile(source);
    let template = compiled({
        headers
    });
    let menu = $('#menu');
    if (menu.length) {
        menu.html(template);
    } else {
        $('#header').append(template);
    }

    attachEventsToLinks();
}

function showInfo(message) {
    let msgObj = {
        type: 'infoBox',
        text: message,
    };
    compileBoxElement(msgObj).then(function () {
        setTimeout(function () {
            $('#infoBox').fadeOut()
        }, 3000)
    }).catch(handleAjaxError);
}

function showError(errorMsg) {
    let msgObj = {
        type: 'errorBox',
        text: errorMsg,
    };
    compileBoxElement(msgObj).catch(handleAjaxError);
}

async function compileBoxElement(msgObj) {
    let source = await  $.get('./templates/box.hbs');
    let compiled = Handlebars.compile(source);
    let box = compiled(msgObj);
    $('#header').append(box);
    if (msgObj.type === 'errorBox') {
        $('#errorBox').on('click', function () {
            $(this).fadeOut();
        });
    } else if (msgObj.type === 'infoBox') {
        $('#infoBox').on('click', function () {
            $(this).fadeOut();
        });

    }
}

function showHomeView() {
    showView('home-view').catch(handleAjaxError);
}

function showLoginView() {
    let obj = {
        viewType: 'viewLogin',
        formType: 'formLogin',
        formTitle: 'Please login',
        buttonType: 'buttonLoginUser',
        value: 'Login',
    };
    showView('login-register-view', obj).then(function () {
        $('#formLogin').trigger('reset');
        $("#buttonLoginUser").on('click', loginUser);
    }).catch(handleAjaxError);

}

function showRegisterView() {
    let obj = {
        viewType: 'viewRegister',
        formType: 'formRegister',
        formTitle: 'Please register here',
        buttonType: 'buttonRegisterUser',
        value: 'Register',
    };
    showView('login-register-view', obj).then(function () {
        $('#formRegister').trigger('reset');
        $("#buttonRegisterUser").on('click', registerUser);
    }).catch(handleAjaxError);

}

function showCreateAdView() {
    let obj = {
        viewType: 'viewCreateAd',
        formType: 'formCreateAd',
        formTitle: 'Create new Advertisement',
        buttonType: 'buttonCreateAd',
        value: 'Create',
    };
    showView('create-edit-view', obj).then(function () {
        $('#formCreateAd').trigger('reset');
        $("#buttonCreateAd").on('click', createAd);
    }).catch(handleAjaxError);

}

function showEditAdView(ad) {
    let obj = {
        id: ad._id,
        publisher: ad._acl.creator,
        title: ad.title,
        description: ad.description,
        datePublished: ad.datePublished,
        price: ad.price,
        imagePath: ad.imagePath,
        viewType: 'viewEditAd',
        formType: 'formEditAd',
        formTitle: 'Edit existing advertisement',
        buttonType: 'buttonEditAd',
        value: 'Edit',
    };
    if(ad.edit){
        obj.edit = true;
    }
    showView('create-edit-view', obj).then(function () {
        console.log(obj);
        $("#buttonEditAd").on('click', editAd);
        $('#formEditAd').trigger('reset');
    }).catch(handleAjaxError);

}

function showSingleView(ad) {
    showView('single-view', ad).then(function () {
        $('#formEditAd').trigger('reset');
    }).catch(handleAjaxError);

}

function showAllAds(ads) {
    showView('view-ads', {ads}).catch(handleAjaxError)
}


text:
package com.rgpt.imagefilters;

import java.awt.*;
import java.awt.geom.*;
import java.awt.image.*;

public class MirrorFilter extends AbstractBufferedImageOp {
    private float opacity = 1.0f;
	private float centreY = 0.5f;
    private float distance;
    private float angle;
    private float rotation;
    private float gap;

    public MirrorFilter() {
	}

	/**
     * Specifies the angle of the mirror.
     * @param angle the angle of the mirror.
     * @angle
     * @see #getAngle
     */
	public void setAngle( float angle ) {
		this.angle = angle;
	}

	/**
     * Returns the angle of the mirror.
     * @return the angle of the mirror.
     * @see #setAngle
     */
	public float getAngle() {
		return angle;
	}

	public void setDistance( float distance ) {
		this.distance = distance;
	}

	public float getDistance() {
		return distance;
	}

	public void setRotation( float rotation ) {
		this.rotation = rotation;
	}

	public float getRotation() {
		return rotation;
	}

	public void setGap( float gap ) {
		this.gap = gap;
	}

	public float getGap() {
		return gap;
	}

	/**
     * Set the opacity of the reflection.
     * @param opacity the opacity.
     * @see #getOpacity
     */
	public void setOpacity( float opacity ) {
		this.opacity = opacity;
	}

	/**
     * Get the opacity of the reflection.
     * @return the opacity.
     * @see #setOpacity
     */
	public float getOpacity() {
		return opacity;
	}

	public void setCentreY( float centreY ) {
		this.centreY = centreY;
	}

	public float getCentreY() {
		return centreY;
	}

    public BufferedImage filter( BufferedImage src, BufferedImage dst ) {
        if ( dst == null )
            dst = createCompatibleDestImage( src, null );
        BufferedImage tsrc = src;
		Shape clip;
		int width = src.getWidth();
		int height = src.getHeight();
		int h = (int)(centreY * height);
		int d = (int)(gap * height);

		Graphics2D g = dst.createGraphics();
		clip = g.getClip();
		g.clipRect( 0, 0, width, h );
		g.drawRenderedImage( src, null );
		g.setClip( clip );
		g.clipRect( 0, h+d, width, height-h-d );
		g.translate( 0, 2*h+d );
		g.scale( 1, -1 );
		g.drawRenderedImage( src, null );
		g.setPaint( new GradientPaint( 0, 0, new Color( 1.0f, 0.0f, 0.0f, 0.0f ), 0, h, new Color( 0.0f, 1.0f, 0.0f, opacity ) ) );
		g.setComposite( AlphaComposite.getInstance( AlphaComposite.DST_IN ) );
		g.fillRect( 0, 0, width, h );
		g.setClip( clip );
		g.dispose();

        return dst;
    }

	public String toString() {
		return "Effects/Mirror...";
	}
}


text:
using Xunit;

namespace System.ComponentModel.Tests
{
    public class NestedContainerTests
    {
        [Fact]
        public void Ctor_IComponent()
        {
            var owner = new Component();
            var container = new NestedContainer(owner);
            Assert.Same(owner, container.Owner);
            Assert.Empty(container.Components);
        }

        [Fact]
        public void Ctor_NullOwner_ThrowsArgumentNullException()
        {
            AssertExtensions.Throws<ArgumentNullException>("owner", () => new NestedContainer(null));
        }

        [Fact]
        public void OwnerName_NoSite_ReturnsNull()
        {
            var owner = new Component();
            var container = new SubNestedContainer(owner);
            Assert.Null(container.OwnerNameEntryPoint);
        }

        [Fact]
        public void OwnerName_HasISite_ReturnsNull()
        {
            var owner = new Component() { Site = new Site() };
            var container = new SubNestedContainer(owner);
            Assert.Equal("SiteName", container.OwnerNameEntryPoint);
        }

        [Fact]
        public void OwnerName_HasINestedSite_ReturnsNull()
        {
            var owner = new Component() { Site = new NestedSite() };
            var container = new SubNestedContainer(owner);
            Assert.Equal("NestedSiteName", container.OwnerNameEntryPoint);
        }

        [Theory]
        [InlineData(null)]
        [InlineData("")]
        [InlineData("name")]
        public void CreateSite_NullOwnerSite_Success(string name)
        {
            var component = new Component();

            var owner = new Component();
            var container = new SubNestedContainer(owner);
            INestedSite site = Assert.IsAssignableFrom<INestedSite>(container.CreateSiteEntryPoint(component, name));
            Assert.Same(component, site.Component);
            Assert.Same(container, site.Container);
            Assert.False(site.DesignMode);
            Assert.Equal(name, site.Name);
            Assert.Equal(name, site.FullName);
        }

        [Theory]
        [InlineData(null)]
        [InlineData("")]
        [InlineData("name")]
        public void Add_NonNullOwnerSite_Success(string name)
        {
            var component = new Component();

            var owner = new Component() { Site = new Site() { DesignMode = true } };
            var container = new SubNestedContainer(owner);
            container.Add(component, name);

            INestedSite site = Assert.IsAssignableFrom<INestedSite>(component.Site);
            Assert.Same(component, site.Component);
            Assert.Same(container, site.Container);
            Assert.True(site.DesignMode);
            Assert.Equal(name, site.Name);
            Assert.Equal(name == null ? null : "SiteName." + name, site.FullName);
        }

        [Theory]
        [InlineData(null)]
        [InlineData("")]
        [InlineData("name")]
        [InlineData("newName")]
        public void CreateSite_SetSiteName_Success(string value)
        {
            var component = new Component();

            var owner = new Component();
            var container = new SubNestedContainer(owner);
            container.Add(component, "name");

            INestedSite site = Assert.IsAssignableFrom<INestedSite>(component.Site);
            site.Name = value;
            Assert.Equal(value, site.Name);
        }

        [Fact]
        public void CreateSite_GetSiteServiceType_ReturnsExpected()
        {
            var component = new Component();

            var owner = new Component();
            var container = new SubNestedContainer(owner);
            container.Add(component);

            INestedSite site = Assert.IsAssignableFrom<INestedSite>(component.Site);
            Assert.Same(site, site.GetService(typeof(ISite)));
            Assert.Same(container, site.GetService(typeof(INestedContainer)));
            Assert.Same(container, site.GetService(typeof(IContainer)));
            Assert.Null(site.GetService(typeof(INestedSite)));
            Assert.Null(site.GetService(typeof(int)));
            Assert.Null(site.GetService(null));
        }

        [Fact]
        public void CreateSite_NullComponent_ThrowsArgumentNullException()
        {
            var owner = new Component();
            var container = new SubNestedContainer(owner);
            AssertExtensions.Throws<ArgumentNullException>("component", () => container.CreateSiteEntryPoint(null, "name"));
        }

        [Fact]
        public void GetService_Invoke_ReturnsExpected()
        {
            var owner = new Component();
            var container = new SubNestedContainer(owner);

            Assert.Same(container, container.GetServiceEntryPoint(typeof(INestedContainer)));
            Assert.Same(container, container.GetServiceEntryPoint(typeof(IContainer)));
            Assert.Null(container.GetServiceEntryPoint(typeof(int)));
            Assert.Null(container.GetServiceEntryPoint(null));
        }

        [Fact]
        public void Dispose_Invoke_Success()
        {
            var owner = new Component();
            var container = new NestedContainer(owner);
            container.Dispose();
            container.Dispose();
        }

        [Fact]
        public void DisposeOwner_Invoke_Success()
        {
            var owner = new Component();
            var container = new NestedContainer(owner);
            owner.Dispose();
            owner.Dispose();
        }

        public class SubNestedContainer : NestedContainer
        {
            public SubNestedContainer(IComponent owner) : base(owner) { }

            public string OwnerNameEntryPoint => OwnerName;

            public ISite CreateSiteEntryPoint(IComponent component, string name) => CreateSite(component, name);

            public object GetServiceEntryPoint(Type service) => GetService(service);
        }

        public class Site : ISite
        {
            public IComponent Component { get; set; }

            public IContainer Container { get; set; }

            public bool DesignMode { get; set; }

            public string Name { get; set; } = "SiteName";

            public object GetService(Type serviceType) => 10;
        }

        public class NestedSite : Site, INestedSite
        {
            public string FullName => "NestedSiteName";
        }
    }
}


text:
from twilio.rest import TwilioRestClient

from mailhook.config.config import TWILIO_NUMBER, TWILIO_TOKEN, TWILIO_SID

def get_twilio():
    return TwilioRestClient(TWILIO_SID, TWILIO_TOKEN)

def send_picture(recipient, media_url):
    twclient = get_twilio()
    message = twclient.messages.create(
        from_=TWILIO_NUMBER,
        to=recipient,
        media_url=media_url,
    )
    return message


text:
package com.tobe.actions;

import java.awt.Component;

import com.tobe.config.ProjectConfig;
import com.tobe.ui.tree.MTreeNode;

public class ActionContext {

	private MTreeNode node;

	private ProjectConfig config;

	private Component attachComponent;

	public MTreeNode getNode() {
		return node;
	}

	public void setNode(MTreeNode node) {
		this.node = node;
	}

	public ProjectConfig getConfig() {
		return config;
	}

	public void setConfig(ProjectConfig config) {
		this.config = config;
	}

	public Component getAttachComponent() {
		return attachComponent;
	}

	public void setAttachComponent(Component attachComponent) {
		this.attachComponent = attachComponent;
	}

}


text:
namespace Org.BouncyCastle.Asn1
{
	public interface IAsn1Convertible
	{
		Asn1Object ToAsn1Object();
	}
}

#endif


text:
package org.axonframework.metrics;

import com.codahale.metrics.MetricRegistry;
import org.axonframework.commandhandling.CommandMessage;
import org.axonframework.eventhandling.EventMessage;
import org.axonframework.monitoring.MessageMonitor;
import org.axonframework.monitoring.MultiMessageMonitor;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class MessageMonitorBuilder {

    public MessageMonitor<EventMessage<?>> buildEventProcessorMonitor(MetricRegistry globalRegistry) {
        MessageTimerMonitor messageTimerMonitor = new MessageTimerMonitor();
        EventProcessorLatencyMonitor eventProcessorLatencyMonitor = new EventProcessorLatencyMonitor();
        CapacityMonitor capacityMonitor = new CapacityMonitor(1, TimeUnit.MINUTES);
        MessageCountingMonitor messageCountingMonitor = new MessageCountingMonitor();

        MetricRegistry eventProcessingRegistry = new MetricRegistry();
        eventProcessingRegistry.register("messageTimer", messageTimerMonitor);
        eventProcessingRegistry.register("latency", eventProcessorLatencyMonitor);
        eventProcessingRegistry.register("messageCounter", messageCountingMonitor);
        globalRegistry.register("eventProcessing", eventProcessingRegistry);

        List<MessageMonitor<? super EventMessage<?>>> monitors = new ArrayList<>();
        monitors.add(messageTimerMonitor);
        monitors.add(eventProcessorLatencyMonitor);
        monitors.add(capacityMonitor);
        monitors.add(messageCountingMonitor);
        return new MultiMessageMonitor<>(monitors);
    }

    public MessageMonitor<EventMessage<?>> buildEventBusMonitor(MetricRegistry globalRegistry) {
        MessageTimerMonitor messageTimerMonitor = new MessageTimerMonitor();

        MetricRegistry eventProcessingRegistry = new MetricRegistry();
        eventProcessingRegistry.register("messageTimer", messageTimerMonitor);
        globalRegistry.register("eventBus", eventProcessingRegistry);

        List<MessageMonitor<? super EventMessage<?>>> monitors = new ArrayList<>();
        monitors.add(messageTimerMonitor);
        return new MultiMessageMonitor<>(monitors);
    }

    public MessageMonitor<CommandMessage<?>> buildCommandBusMonitor(MetricRegistry globalRegistry) {
        MessageTimerMonitor messageTimerMonitor = new MessageTimerMonitor();
        CapacityMonitor capacityMonitor = new CapacityMonitor(1, TimeUnit.MINUTES);
        MessageCountingMonitor messageCountingMonitor = new MessageCountingMonitor();

        MetricRegistry commandHandlingRegistry = new MetricRegistry();
        commandHandlingRegistry.register("messageTimer", messageTimerMonitor);
        commandHandlingRegistry.register("capacity", capacityMonitor);
        commandHandlingRegistry.register("messageCounter", messageCountingMonitor);
        globalRegistry.register("commandHandling", commandHandlingRegistry);

        return new MultiMessageMonitor<>(messageTimerMonitor, capacityMonitor, messageCountingMonitor);
    }
}


text:
title: Measuring
---

    Browse to the makerjs.measure module documentation to see all functions related to measuring.

To get the bounding rectangle of a path or a model, use:

makerjs.measure.pathExtents(path: object)

makerjs.model.modelExtents(model: object)

These functions return a measurement object with high and low points.

Measure path example:

{% highlight javascript %}
//render an arc, and a measurement reactangle around it

var makerjs = require('makerjs');

var arc = new makerjs.paths.Arc([0, 0], 100, 45, 135);
var m = makerjs.measure.pathExtents(arc);

console.log('measurement:');
console.log(m);

var totalWidth = m.high[0] - m.low[0];
var totalHeight = m.high[1] - m.low[1];

var measureRect = new makerjs.models.Rectangle(totalWidth, totalHeight);
measureRect.origin = m.low;

var model = {
    paths: {
        arc: arc
    },
    models: {
        measureRect: measureRect
    }
};

var svg = makerjs.exporter.toSVG(model, {useSvgPathOnly: false});

document.write(svg);
{% endhighlight %}

Measure model example:

{% highlight javascript %}
//render an oval, and a measurement reactangle around it

var makerjs = require('makerjs');

var oval = new makerjs.models.Oval(100, 20);
makerjs.model.rotate(oval, 30);
var m = makerjs.measure.modelExtents(oval);

console.log('measurement:');
console.log(m);

var totalWidth = m.high[0] - m.low[0];
var totalHeight = m.high[1] - m.low[1];

var measureRect = new makerjs.models.Rectangle(totalWidth, totalHeight);
measureRect.origin = m.low;

var model = {
    models: {
        measureRect: measureRect,
        oval: oval
    }
};

var svg = makerjs.exporter.toSVG(model, {useSvgPathOnly: false});

document.write(svg);
{% endhighlight %}