text:
namespace SDKSample
{
    namespace BluetoothGattHeartRate
    {
        public ref class HeartRateMeasurement sealed
        {
        public:
            property uint16 HeartRateValue
            {
                uint16 get()
                {
                    return heartRateValue;
                }
                void set(uint16 value)
                {
                    heartRateValue = value;
                }
            }

            property boolean HasExpendedEnergy
            {
                boolean get()
                {
                    return hasExpendedEnergy;
                }
                void set(boolean value)
                {
                    hasExpendedEnergy = value;
                }
            }

            property uint16 ExpendedEnergy
            {
                uint16 get()
                {
                    return expendedEnergy;
                }
                void set(uint16 value)
                {
                    expendedEnergy = value;
                }
            }

            property Windows::Foundation::DateTime Timestamp
            {
                Windows::Foundation::DateTime get()
                {
                    return timestamp;
                }
                void set(Windows::Foundation::DateTime value)
                {
                    timestamp = value;
                }
            }

        public:
            Platform::String^ GetDescription()
            {
                std::wstringstream wss;
                auto timeFormatter = ref new Windows::Globalization::DateTimeFormatting::DateTimeFormatter("longtime");
                auto dateFormatter = ref new Windows::Globalization::DateTimeFormatting::DateTimeFormatter("longdate");

                wss << HeartRateValue << L" bpm @ " << timeFormatter->Format(Timestamp)->Data() <<
                    dateFormatter->Format(Timestamp)->Data();

                return ref new Platform::String(wss.str().c_str());
            }

        private:
            uint16 heartRateValue;
            boolean hasExpendedEnergy;
            uint16 expendedEnergy;
            Windows::Foundation::DateTime timestamp;
        };

        public delegate void ValueChangeCompletedHandler(HeartRateMeasurement^ heartRateMeasurement);
        public delegate void DeviceConnectionUpdatedHandler(boolean isConnected);

        public ref class HeartRateService sealed
        {
        public:
            event ValueChangeCompletedHandler^ ValueChangeCompleted;
            event DeviceConnectionUpdatedHandler^ DeviceConnectionUpdated;

            static property HeartRateService^ Instance
            {
                HeartRateService^ get()
                {
                    if (instance == nullptr)
                    {
                        instance = ref new HeartRateService();
                    }

                    return instance;
                }
            }

            property bool IsServiceInitialized
            {
                bool get()
                {
                    return isServiceInitialized;
                }
                void set(bool value)
                {
                    isServiceInitialized = value;
                }
            }

            property Windows::Devices::Bluetooth::GenericAttributeProfile::GattDeviceService^ Service
            {
                Windows::Devices::Bluetooth::GenericAttributeProfile::GattDeviceService^ get()
                {
                    return service;
                }
                void set(Windows::Devices::Bluetooth::GenericAttributeProfile::GattDeviceService^ value)
                {
                    service = value;
                }
            }

            property Windows::Foundation::Collections::IVectorView<HeartRateMeasurement^>^ DataPoints
            {
                Windows::Foundation::Collections::IVectorView<HeartRateMeasurement^>^ get()
                {
                    auto retval = ref new Platform::Collections::Vector<HeartRateMeasurement^>();

                    // Obtain a RAII lock from dataLock
                    concurrency::reader_writer_lock::scoped_lock_read lock(dataLock);

                    // Create a snapshot of the data values
                    for (auto it = begin(datapoints); it != end(datapoints); it++)
                    {
                        retval->Append(*it);
                    }

                    return retval->GetView();
                }
            }

        public:
            virtual ~HeartRateService();
            Windows::Foundation::IAsyncAction^ InitializeHeartRateServicesAsync(
                Windows::Devices::Enumeration::DeviceInformation^ device);

            Platform::String^ ProcessBodySensorLocationData(
                const Platform::Array<unsigned char>^ bodySensorLocationData);

        private:
            HeartRateService();

            void App_Resuming(Platform::Object^ sender, Platform::Object^ e);
            void App_Suspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ e);

            concurrency::task<void> ConfigureServiceForNotificationsAsync();

            HeartRateMeasurement^ ProcessHeartRateMeasurementData(
                Platform::Array<unsigned char>^ heartRateMeasurementData);

            void Characteristic_ValueChanged(
                Windows::Devices::Bluetooth::GenericAttributeProfile::GattCharacteristic^ sender,
                Windows::Devices::Bluetooth::GenericAttributeProfile::GattValueChangedEventArgs^ args);

            void StartDeviceConnectionWatcher();
            void HeartRateService::OnDeviceConnectionUpdated(
                Windows::Devices::Enumeration::Pnp::PnpObjectWatcher^ sender,
                Windows::Devices::Enumeration::Pnp::PnpObjectUpdate^ e);

            static HeartRateService^ instance;
            bool isServiceInitialized;

            Windows::Devices::Bluetooth::GenericAttributeProfile::GattDeviceService^ service;
            Windows::Devices::Bluetooth::GenericAttributeProfile::GattCharacteristic^ characteristic;
            Platform::String^ deviceContainerId;
            Platform::Collections::Vector<HeartRateMeasurement^>^ datapoints;
            Windows::Devices::Enumeration::Pnp::PnpObjectWatcher^ watcher;

            concurrency::reader_writer_lock dataLock;
        };
    };
};


text:
<?php

use Core\Services\Contracts\Database;
use Core\Services\Contracts\Migration as MigrationContract;

class UpdateBarTable implements MigrationContract
{
    public function up(Database $db)
    {
        /** @noinspection SqlDialectInspection */
        $db->exec('INSERT INTO foo ("name") VALUES (?)', ['bar']);
    }

    public function down(Database $db)
    {
        /** @noinspection SqlDialectInspection */
        $db->exec('DELETE FROM foo WHERE "name"=?', ['bar']);
    }
}

redpajama_set_name: RedPajamaGithub


text:
param (
	$message
	)

Sleep -s 10
Get-Item -Path . | Select-Object name | ConvertTo-Json -Compress


text:
from __future__ import unicode_literals

from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('bunq_bot', '0002_auto_20170620_1430'),
    ]

    operations = [
        migrations.RenameModel(
            old_name='BotInfo',
            new_name='ChatInfo',
        ),
        migrations.RenameField(
            model_name='chatinfo',
            old_name='chat_ids',
            new_name='chat_id',
        ),
    ]


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace Cloud.Web
{
    /// 路由设置
    public class RouteConfig
    {
        /// 注册路由
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}


text:
local AABB = require 'lib/AABB'

layoutgen = {}

local function table_pick( tbl, index )
	local result = tbl[index]

	tbl[index] = tbl[#tbl]
	tbl[#tbl] = nil

	return result
end

-- limits = {
--     minwidth = minimum width of a resulting bbox
--     minheight = minimum height of a resulting bbox
--     maxwidth = maximum width of a resulting bbox
--     maxheight = maximum height of a resulting bbox
--     margin = minimum space between resulting bboxes
--     maxboxes = maximum no. of resulting leaves.
-- }
--

local _axes = {
	'horz',
	'vert',
}

function layoutgen.bsp( bbox, limits )
	error('layoutgen.bsp() is very bad')

	local minbranchwidth = (2 * limits.minwidth) + (2 * limits.margin)
	local minbranchheight = (2 * limits.minheight) + (2 * limits.margin)

	local minleafwidth = limits.minwidth + limits.margin
	local minleafheight = limits.minheight + limits.margin

	-- A branch is an aabb that is big enough to be split.
	local branches = { bbox }
	-- A leaf is an aabb that can't be split without making it smaller than
	-- the limits allow.
	local leaves = {}

	while #branches > 0 and #branches + #leaves < limits.maxboxes do
		local branch = table_pick(branches, math.random(1, #branches))

		local horzsplit = branch:width() > minbranchwidth
		local vertsplit = branch:height() > minbranchheight

		if not horzsplit and not vertsplit then
			leaves[#leaves+1] = branch
		else
			local axis = _axes[math.random(horzsplit and 1 or 2, vertsplit and 2 or 1)]
			local coord = nil

			if axis == 'horz' then
				local min = branch.xmin + minleafwidth
				local max = branch.xmax - minleafwidth
				coord = math.random(min, max)
			else
				local min = branch.ymin + minleafheight
				local max = branch.ymax - minleafheight
				coord = math.random(min, max)
			end

			local sub1, sub2 = branch:split(axis, coord)

			if sub1:width() < minbranchwidth and sub1:height() < minbranchheight then
				leaves[#leaves+1] = sub1
			else
				branches[#branches+1] = sub1
			end

			if sub2:width() < minbranchwidth and sub2:height() < minbranchheight then
				leaves[#leaves+1] = sub2
			else
				branches[#branches+1] = sub2
			end
		end
	end

	local result = {}

	for _, bbox in ipairs(branches) do
		result[#result+1] = bbox:shrink(limits.margin * 0.5)
	end

	for _, bbox in ipairs(leaves) do
		result[#result+1] = bbox:shrink(limits.margin * 0.5)
	end

	return result
end

function layoutgen.splat( bbox, limits )
	local result = {}

	local minwidth = limits.minwidth + limits.margin * 1.5
	local minheight = limits.minheight + limits.margin * 1.5
	local maxwidth = limits.maxwidth or math.floor(bbox:width() * 0.5)
	local maxheight = limits.maxheight or math.floor(bbox:height() * 0.5)

	-- print('pre', minwidth, minheight, maxwidth, maxheight)

	local attempts = 0
	local maxattempts = 1000

	while #result < limits.maxboxes and attempts < maxattempts do
		local width = minwidth + math.random(0, maxwidth - minwidth)
		local height = minheight + math.random(0, maxheight - minheight)

		assert(width >= minwidth)
		assert(height >= minheight)

		local x = math.random(bbox.xmin, bbox.xmax - width)
		local y = math.random(bbox.ymin, bbox.ymax - height)

		local aabb = AABB.new {
			xmin = x,
			ymin = y,
			xmax = x + width,
			ymax = y + height,
		}

		assert(width == aabb:width())
		assert(height == aabb:height())

		local accepted = true

		for _, other in ipairs(result) do
			if aabb:intersects(other) then
				accepted = false

				break
			end
		end

		if accepted then
			result[#result+1] = aabb
		end

		attempts = attempts + 1
	end

	for index, bbox in ipairs(result) do
		-- print('shrink', bbox.xmin, bbox.ymin, bbox.xmax, bbox.ymax, bbox:width(), bbox:height())
		result[index] = bbox:shrink(limits.margin * 0.75)
	end

	return result
end


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using OpenWeen.Core.Model;
using OpenWeen.UWP.BackgroundTask;
using OpenWeen.UWP.Common;
using OpenWeen.UWP.Common.Helpers;
using OpenWeen.UWP.Shared.Common;
using OpenWeen.UWP.Shared.Common.Helpers;
using OpenWeen.UWP.ToastNotificationTask;
using Windows.ApplicationModel.Activation;
using Windows.ApplicationModel.Background;
using Windows.Foundation;
using Windows.Graphics.Display;
using Windows.Storage;
using Windows.UI.Core;
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Animation;
using Windows.UI.Xaml.Navigation;
using Windows.UI.Xaml.Hosting;
using Windows.UI.Composition;
using Windows.UI.Xaml.Media;
using Windows.UI;

// "空白页"项模板在 http://go.microsoft.com/fwlink/?LinkId=234238 上提供

namespace OpenWeen.UWP.View
{
    /// <summary>
    /// 可用于自身或导航至 Frame 内部的空白页。
    /// </summary>
    partial class ExtendedSplash
    {
        internal Rect splashImageRect;
        private static SplashScreen splash;
        internal bool dismissed = false;
        internal Frame rootFrame = new Frame();
        private double ScaleFactor;

        public string StateText
        {
            get { return StateTextblock.Text; }
            set { StateTextblock.Text = value; }
        }

        public ExtendedSplash(SplashScreen splashscreen)
        {
            InitializeComponent();
            Window.Current.SizeChanged += ExtendedSplash_OnResize;
            if (splash == null && splashscreen != null)
            {
                splash = splashscreen;
            }
            SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Collapsed;
            ScaleFactor = DisplayInformation.GetForCurrentView().RawPixelsPerViewPixel;
            if (splash != null)
            {
                splash.Dismissed += DismissedEventHandler;
                splashImageRect = splash.ImageLocation;
                PositionImage();
            }
            InitTransitions();
        }

        private void InitTransitions()
        {
            TransitionCollection collection = new TransitionCollection();
            NavigationThemeTransition theme = new NavigationThemeTransition();

            var info = new DrillInNavigationTransitionInfo();

            theme.DefaultNavigationTransitionInfo = info;
            collection.Add(theme);
            rootFrame.ContentTransitions = collection;
        }

        private void PositionImage()
        {

            extendedSplashImage.SetValue(Canvas.LeftProperty, splashImageRect.Left);
            extendedSplashImage.SetValue(Canvas.TopProperty, splashImageRect.Top);
            if (StaticResource.IsPhone)
            {
                extendedSplashImage.Height = splashImageRect.Height / ScaleFactor;
                extendedSplashImage.Width = splashImageRect.Width / ScaleFactor;
            }
            else
            {
                extendedSplashImage.Height = splashImageRect.Height;
                extendedSplashImage.Width = splashImageRect.Width;
            }
        }

        private void ExtendedSplash_OnResize(object sender, WindowSizeChangedEventArgs e)
        {
            if (splash != null)
            {
                splashImageRect = splash.ImageLocation;
                PositionImage();
            }
        }

        private async void DismissedEventHandler(SplashScreen sender, object e)
        {
            dismissed = true;

            await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
             {
                 DismissExtendedSplash();
             });
        }

        private async Task InitUid()
        {
            StaticResource.Uid = long.Parse(await Core.Api.User.Account.GetUid());
        }

        private async void DismissExtendedSplash()
        {
            Window.Current.SizeChanged -= ExtendedSplash_OnResize;
            StateText = "正在检查后台通知";
            await BackgroundHelper.Register<UpdateUnreadCountTask>(new TimeTrigger(15, false));
            await BackgroundHelper.Register<ToastNotificationBackgroundTask>(new ToastNotificationActionTrigger());
            StateText = "正在初始化表情";
            await StaticResource.InitEmotion();
            var cahcesize = rootFrame.CacheSize;
            rootFrame.CacheSize = 0;
            rootFrame.CacheSize = cahcesize;
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            StateText = "正在初始化用户数据";
            if (await StaticResource.CheckForLogin())
            {
                await InitUid();
                rootFrame.Navigate(typeof(MainPage));
            }
            else
            {
                rootFrame.Navigate(typeof(LoginPage));
            }
            //var rootGrid = new Grid();
            //var grid = new Grid();
            //rootGrid.Children.Add(grid);
            //rootGrid.Children.Add(rootFrame);
            //Window.Current.Content = rootGrid;
            Window.Current.Content = rootFrame;
            App.HandleBackButton(rootFrame);
            //App.InitBlurEffect(grid);
        }
    }
}


text:
import {ServiceManagerClient} from '@google-cloud/service-management';

// check that the client class type name can be used
function doStuffWithServiceManagerClient(client: ServiceManagerClient) {
  client.close();
}

function main() {
  // check that the client instance can be created
  const serviceManagerClient = new ServiceManagerClient();
  doStuffWithServiceManagerClient(serviceManagerClient);
}

main();


text:
var express = require('express');
var router = express.Router();
var request = require('request');
var cheerio = require('cheerio');
var fs = require('fs');
var movie = {};

/* GET home page. */
router.get('/', function(req, res, next) {
  // res.render('scrape', { title: 'scrape page' });

  url = 'http://projectfreetv.so/free/stargate-atlantis-season-2/';

    // The structure of our request call
    // The first parameter is our URL
    // The callback function takes 3 parameters, an error, response status code and the html

    request(url, function(error, response, html){

        // First we'll check to make sure no errors occurred when making the request

        if(!error){
            // Next, we'll utilize the cheerio library on the returned html which will essentially give us jQuery functionality

            var $ = cheerio.load(html);

            // Finally, we'll define the variables we're going to capture

            var title, release, rating, episodeLink, videoLink;

            $('#content_box > h1 > span').filter(function(){
              var data = $(this);
              title = data.text();
              movie.title=title;
            });//end of title scraper

            $('#content_box > table > tbody > tr:nth-child(15) > th > div > a:nth-child(1)').filter(function(){
              var data=$(this);
              episodeLink=data.attr('href');
              movie.episodeLink=episodeLink;
            });
            console.log(movie)
        } else {
          console.log('there has been an error');
        } //end of if-else statement

    });//end of request

    // request(movie.episodeLink, function(err,res,html){
    //   if(!err){
    //     $('#mybox > table > tbody > tr:nth-child(3) > td:nth-child(1) > a').filter(function(){
    //       var videoLink;
    //       var data = $(this);
    //       videoLink=data.attr('href');
    //       console.log('video link:',videoLink);
    //       movie.videoLink=videoLink;
    //     });

    //   } else {
    //     console.log('there has been an error');
    //   }
    // });//end of video request
    res.send(movie);
});//end of router.get()

module.exports = router;


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.dreamera_master.MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context="com.example.dreamera_master.MainActivity">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:background="@drawable/search_layout">

                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@mipmap/ic_search"
                    android:layout_gravity="center_vertical"
                    android:layout_marginLeft="4dp"
                    android:layout_marginBottom="3dp"
                    android:layout_marginTop="3dp"
                    android:layout_marginRight="2dp"/>
                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:id="@+id/main_search_tv"
                    android:layout_marginBottom="3dp"
                    android:layout_marginTop="3dp"
                    android:textColor="#dddddd"
                    android:text="搜索地点"
                    android:textSize="15sp" />
            </LinearLayout>
        </android.support.v7.widget.Toolbar>

        <fragment
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/post_fragment"
            android:name="com.example.dreamera_master.PostFragment" />

        <!--<android.support.design.widget.TabLayout
            android:id="@+id/tab_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/colorPrimary"
            app:tabTextColor="#FFF"
            app:tabMode="fixed"
            app:tabIndicatorColor="@android:color/holo_blue_bright"
            app:tabTextAppearance="@android:style/TextAppearance.Holo.Large"/>

        <android.support.v4.view.ViewPager
            android:id="@+id/view_pager"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:background="#FFF" />-->

    </LinearLayout>

    <!--
    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:menu="@menu/nav_menu" />-->
    <fragment
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/get_fragment"
        android:name="com.example.dreamera_master.GetFragment"
        android:layout_gravity="start" />
</android.support.v4.widget.DrawerLayout>


text:
layout: reform
permalink: /gems/reform/
title: "Reform"
gems:
  - ["reform", "trailblazer/reform", "2.2"]
---

Reform provides form objects to run validations for one or multiple models.

## Overview

Validations no longer sit in model classes, but in forms. Once the data is coerced and validated, it can be written to the model.

A _model_ can be any kind of Ruby object. Reform is completely framework-agnostic and doesn't care about your database.

A *form* doesn't have to be a UI component, necessarily! It can be an intermediate validation before writing data to the persistence layer. While form objects may be used to render graphical web forms, Reform is used in many pure-API applications for deserialization and validation.

* **API** In Reform, form classes define fields and validations for the input. This input can be validated using `validate` and written to the model using `sync` or `save`. [→ API](api.html)
* **DATA TYPES** Reform can map model attributes, compositions of objects, nested models, hash fields and more. [→ DATA TYPES](data-types.html)
* **COERCION** When validating, the form can coerce input to arbitrary values using the dry-types gem. [→ COERCION](options.html#coercion)
* **POPULATOR** Deserialization of the incoming data can be customized using populators. [→ POPULATOR](populator.html)
* **VALIDATION GROUPS** Validations can be chained or run when certain criteria match, only. [→ VALIDATION GROUPS](validation.html#validation-groups)

For a technical architecture overview, read the [Architecture](#architecture) section.

## API

Forms are defined in classes. Often, these classes partially map to a model.

{% tabs %}
~~dry-validation
    class AlbumForm < Reform::Form
      property :title

      validation do
       required(:title).filled
      end
    end

~~ActiveModel
    class AlbumForm < Reform::Form
      property :title

      validates :title, presence: true
    end
{% endtabs %}

Form fields are specified using `property` and `collection`, validations for the fields using the respective validation engine's API.

Forms can also be nested and map to more complex object graphs.

{% tabs %}
~~dry-validation
    class AlbumForm < Reform::Form
      property :title

      validation do
       required(:title).filled
      end

      property :artist do
        property :name

        validation do
         required(:name).filled
        end
      end
    end

~~ActiveModel
    class AlbumForm < Reform::Form
      property :title

      validates :title, presence: true

      property :artist do
        property :name

        validates :name, presence: true
      end
    end
{% endtabs %}

While Reform is perfectly suited to map nested models with associations, it also allows mapping via composition, to hash fields, and more. Check out the [supported data types](data-types.html).

## Setup

In your controller or operation you create a form instance and pass in the models you want to validate data against.

    class AlbumsController < ApplicationController
      def new
        @form = AlbumForm.new(Album.new)
      end

This will also work as an editing form with an existing album.

    def edit
      @form = AlbumForm.new(Album.find(1))
    end

In setup, Reform will read values from the model.

    model = Album.find(1)
    model.title #=> "The Aristocrats"

    @form = AlbumForm.new(model)
    @form.title #=> "The Aristocrats"

Once read, the original model's values will never be accessed.

## Rendering

Your `@form` is now ready to be rendered, either do it yourself or use something like Rails' `#form_for`, `simple_form` or `formtastic`.

    = form_for @form do |f|
      = f.input :title

Nested forms and collections can be easily rendered with `fields_for`, etc. Note that you no longer pass the model to the form builder, but the Reform instance.

Optionally, you might want to use the `#prepopulate!` method to pre-populate fields and prepare the form for rendering.

## Validation

A submitted form is processed via `validate`.

    result = @form.validate(title: "Greatest Hits")

By passing the incoming hash to `validate`, the input is written to the form and validated.

This usually happens in a processing controller action.

    def create
      @form = AlbumForm.new(Album.new)

      if @form.validate(params[:album])
        # persist data
        @form.save
      end
    end

After validation, the form's values reflect the validated data.

    @form.validate(title: "Greatest Hits")
    @form.title #=> "Greatest Hits"

Note that the model remains untouched - validation solely happens on the form object.

    model.title #=> "The Aristocrats"

Reform never writes anything to the models, until you tell it to do so.

## Persisting

The easiest way to persist validated data is to call `#save` on the form.

    if form.validate(params[:song])
      form.save
    end

This will write the data to the model(s) using [`sync`](api.html#sync) and then call `album.save`.

You may save data manually using [`save` with a block](api.html#save).

    form.save do |nested_hash|
      Album.create(title: nested_hash["title"])
    end

Or you can let Reform write the validated data to the model(s) without saving anything.

    form.sync # the album is unsaved!

This will updated the model's attributes using its setter methods, but not `save` anything.

## Installation

{% tabs %}
~~Dry-validation
Add this your Gemfile.

    gem "reform"
    gem "dry-validation"

Please use [dry-validation](http://dry-rb.org/gems/dry-validation), which is our recommended validation engine. Put the following snippet into an initializer.

    require "reform/form/dry"

    Reform::Form.class_eval do
      include Reform::Form::Dry
    end

~~ActiveModel
Add this to your Gemfile.

    gem "reform"
    gem "reform-rails"

To use `ActiveModel` for validations put this into an initializer.

    require "reform/form/active_model/validations"

    Reform::Form.class_eval do
      include Reform::Form::ActiveModel::Validations
    end

Things you should know when using ActiveModel with Reform.

* `ActiveModel` support is provided by the `reform-rails` gem. You have to add it to your `Gemfile`.
* The above last step of including `ActiveModel::Validations` is done automatically in a Rails environment.
* Reform works fine with Rails 3.1-4.2. However, inheritance of validations with `ActiveModel::Validations` is broken in Rails 3.2 and 4.0.

{% endtabs %}

## Design Concepts

* **FRAMEWORK-AGNOSTIC** Reform is completely framework-agnostic and is used in many projects with Rails, Sinatra, Hanami and more.

  For Rails, the [reform-rails gem](rails.html) provides convenient glue code to make Reform work with Rails' form builders and `ActiveModel::Validations`.

* **ORMs** Reform works with any ORM or PORO - it has zero knowledge about underlying databases per design. The only requirements are reader and writer methods on the model(s) for defined properties.

* **DATA MAPPING** Reform helps mapping one or many models to a form object. Nevertheless, Reform is *not* a full-blown data mapper. It still is a form object. Simple data mapping like composition, delegation or hash fields come from the [Disposable](/gems/disposable/index.html) gem.

  Should you require more complex mapping, use something such as ROM and pass it to the form object.

* **SECURITY** Reform simply ignores unsolicited input in `validate`. It does so by only accepting values for defined `property`s. This makes half-baked solutions like `strong_parameter` or `attr_accessible` obsolete.

## Architecture

When experiencing Reform for the first time, it might seem to do a lot, too much: It decorates a model, parses the incoming data into some object graph, validates the data somehow and supports writing this data back to the model.

Actually, Reform is very simple and consists of several smaller objects. Each object has a very specific scope one does exactly one thing, where the actual form object orchestrates between those.

**SETUP** When instantiating the form object with a model, it will read its properties' values from the model. Internally, this happens because a [form is simply a `Twin`](https://github.com/apotonick/reform/blob/777ea4730bec913582bae78fece78bbb76fb22c4/lib/reform/contract.rb#L6). [Twins are light-weight decorator objects](/gems/disposable) from the Disposable gem.

For nested properties or collections, nested form objects will be created and wrap the respective contained models.

**DESERIALIZATION** In the `validate` method, the incoming hash or document is parsed. Each known field is assigned to the form object, each nested fragment will be mapped to a nested form. This process is known as *deserialization*.

The internal deserializer used for this is actually a *representer* from the Representable gem. It is [inferred automatically by Reform](https://github.com/apotonick/reform/blob/777ea4730bec913582bae78fece78bbb76fb22c4/lib/reform/form/validate.rb#L43), but theoretically, you could provide your own deserializer that goes through the document and then calls setters on the form.

**POPULATOR** Nested fragments in the document often need to be mapped to existing or new models. This is where *populators* in Reform help to find the respective model(s), wrap them in a nested form object, and create a virtual object graph of the parsed data.

Populators are code snippets you define in the form class, but they are called from the deserializing representer and help parsing the document into a graph of objects.

**VIRTUAL OBJECT GRAPH** After deserialization, the form object graph represents the input. All data in `validate` has been written to the virtual graph, **not to the model**. Once this graph is setup, it can be validated.

The deserialization process is the pivotal part in Reform. Where simple validation engines only allow formal validations, Reform allows rich business validations such as *"When user signed in, and it's the first order, allow maximum 10 items in the shopping cart!"*.

**VALIDATION** For the actual validation, Reform uses existing solutions such as dry-validation or `ActiveModel::Validations`. It passes the data to the validation engine in the appropriate format - usually, this is a hash representing the virtual object graph and its data.

The validation is then completely up to the engine. Reform doesn't know what is happening, it is only interested in the result and error messages. Both are exposed via the form object after validation has been finished.

The decoupled validation is why Reform provides multiple validation engines.

**SYNC/SAVE**

After the `validate` call, nothing has been written to the model(s), yet. This has to be explicitly invoked via `sync` or `save`. Now, Reform will use its basic twin functionality again and write the virtual data to the models using public setter methods. Again, Reform knows nothing about ORMs or model specifics.


text:
<TITLE>Review for Virtuosity (1995)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Virtuosity (1995)

reviewed by
Brian Koller

Virtuosity (1995)

Grade: 68

"Virtuosity" is a campy, action-packed thriller with some
elements of science fiction.  Despite much violence and
a few scenes that are difficult to believe, it is an
enjoyable and interesting film that is underrated and
worth a look.

Denzel Washington stars as an ex-cop with a troubled past:
while seeking revenge on a taunting mass-murderer who
killed his wife and daughter, he made the mistake of
killing some others as well.  He is now a prisoner, and
a volunteer in a bizarre virtual reality experiment
which has him tracking a sadistic and unpredictable
computerized serial killer (Russell Crowe).

A plot device has Crowe placed free in the real world:
an android with some interesting character traits.  He has
a massive need for attention, and his murders are intended
as a lure for Washington, the only human that he has any
respect for.  Desperate federal officials release Washington
from prison to hunt Crowe down, a task that Washington
accepts with reluctance but performs with relish.  He is
joined by a criminal psychiatrist (Kelly Lynch) who matches
Washington's humorless and determined disposition.

"Virtuosity" was a very enjoyable film for me to watch,
a definite guilty pleasure.  There are flaws however.

There is much gratuitous violence, most obviously in a
prison fight scene that demonstrates nothing except that
Washington is a tough guy that won't back down from a
fight.

Since I am a software programmer myself, I had trouble with
the fact that only *one* programmer was responsible for
Crowe's software (he would need a dozen engineers at least)
and of course that programmer is stereotyped as an
effiminate "mad scientist".  This engineer not only
frees this killer, but enjoys his subsequent exploits with
parental pride.

Washington's character has amazing resilence and courage,
and is even willing to engage in hand to hand combat with
the much stronger Crowe.  Okay, but can Washington outrun
the bullets from a half-dozen machine guns?

"Virtuosity" also has borrowed much of its plot from
"The Terminator".  Still, it is fun watching Crowe camp
it up, and Washington's intensity is compelling.

kollers@shell.mpsi.net
http://members.tripod.com/~Brian_Koller/movies.html

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
<?php

/**
 * @see Zend_Service_Amazon_Ec2_Abstract
 */
require_once 'Zend/Service/Amazon/Ec2/Abstract.php';

/**
 * Allows you to interface with the reserved instances on Amazon Ec2
 *
 * @category   Zend
 * @package    Zend_Service_Amazon
 * @subpackage Ec2
 * @copyright  Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Amazon_Ec2_Instance_Reserved extends Zend_Service_Amazon_Ec2_Abstract
{
    /**
     * Describes Reserved Instances that you purchased.
     *
     * @param string|array $instanceId        IDs of the Reserved Instance to describe.
     * @return array
     */
    public function describeInstances($instanceId)
    {
        $params = array();
        $params['Action'] = 'DescribeReservedInstances';

        if(is_array($instanceId) && !empty($instanceId)) {
            foreach($instanceId as $k=>$name) {
                $params['ReservedInstancesId.' . ($k+1)] = $name;
            }
        } elseif($instanceId) {
            $params['ReservedInstancesId.1'] = $instanceId;
        }

        $response = $this->sendRequest($params);

        $xpath = $response->getXPath();
        $items = $xpath->query('//ec2:reservedInstancesSet/ec2:item');

        $return = array();
        foreach($items as $item) {
            $i = array();
            $i['reservedInstancesId'] = $xpath->evaluate('string(ec2:reservedInstancesId/text())', $item);
            $i['instanceType'] = $xpath->evaluate('string(ec2:instanceType/text())', $item);
            $i['availabilityZone'] = $xpath->evaluate('string(ec2:availabilityZone/text())', $item);
            $i['duration'] = $xpath->evaluate('string(ec2:duration/text())', $item);
            $i['fixedPrice'] = $xpath->evaluate('string(ec2:fixedPrice/text())', $item);
            $i['usagePrice'] = $xpath->evaluate('string(ec2:usagePrice/text())', $item);
            $i['productDescription'] = $xpath->evaluate('string(ec2:productDescription/text())', $item);
            $i['instanceCount'] = $xpath->evaluate('string(ec2:instanceCount/text())', $item);
            $i['state'] = $xpath->evaluate('string(ec2:state/text())', $item);

            $return[] = $i;
            unset($i);
        }

        return $return;
    }

    /**
     * Describes Reserved Instance offerings that are available for purchase.
     * With Amazon EC2 Reserved Instances, you purchase the right to launch Amazon
     * EC2 instances for a period of time (without getting insufficient capacity
     * errors) and pay a lower usage rate for the actual time used.
     *
     * @return array
     */
    public function describeOfferings()
    {
        $params = array();
        $params['Action'] = 'DescribeReservedInstancesOfferings';

        $response = $this->sendRequest($params);

        $xpath = $response->getXPath();
        $items = $xpath->query('//ec2:reservedInstancesOfferingsSet/ec2:item');

        $return = array();
        foreach($items as $item) {
            $i = array();
            $i['reservedInstancesOfferingId'] = $xpath->evaluate('string(ec2:reservedInstancesOfferingId/text())', $item);
            $i['instanceType'] = $xpath->evaluate('string(ec2:instanceType/text())', $item);
            $i['availabilityZone'] = $xpath->evaluate('string(ec2:availabilityZone/text())', $item);
            $i['duration'] = $xpath->evaluate('string(ec2:duration/text())', $item);
            $i['fixedPrice'] = $xpath->evaluate('string(ec2:fixedPrice/text())', $item);
            $i['usagePrice'] = $xpath->evaluate('string(ec2:usagePrice/text())', $item);
            $i['productDescription'] = $xpath->evaluate('string(ec2:productDescription/text())', $item);

            $return[] = $i;
            unset($i);
        }

        return $return;
    }

    /**
     * Purchases a Reserved Instance for use with your account. With Amazon EC2
     * Reserved Instances, you purchase the right to launch Amazon EC2 instances
     * for a period of time (without getting insufficient capacity errors) and
     * pay a lower usage rate for the actual time used.
     *
     * @param string $offeringId            The offering ID of the Reserved Instance to purchase
     * @param integer $intanceCount         The number of Reserved Instances to purchase.
     * @return string                       The ID of the purchased Reserved Instances.
     */
    public function purchaseOffering($offeringId, $intanceCount = 1)
    {
        $params = array();
        $params['Action'] = 'PurchaseReservedInstancesOffering';
        $params['OfferingId.1'] = $offeringId;
        $params['instanceCount.1'] = intval($intanceCount);

        $response = $this->sendRequest($params);

        $xpath = $response->getXPath();
        $reservedInstancesId = $xpath->evaluate('string(//ec2:reservedInstancesId/text())');

        return $reservedInstancesId;
    }
}


text:
module OpenFlashChart

  class Bar3d < BarBase
    def initialize args={}
      super
      @type = "bar_3d"
    end
  end

  class Bar3dValue < Base
    def initialize(top, args={})
      @top = top
      super args
    end
  end

end


text:
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE

using System;
using osu.Framework.Caching;
using OpenTK.Graphics;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Game.Graphics;

namespace osu.Game.Rulesets.Mania.Objects.Drawables.Pieces
{
    /// <summary>
    /// Represents length-wise portion of a hold note.
    /// </summary>
    internal class BodyPiece : Container, IHasAccentColour
    {
        private readonly Container subtractionLayer;

        private readonly Drawable background;
        private readonly BufferedContainer foreground;
        private readonly BufferedContainer subtractionContainer;

        public BodyPiece()
        {
            Blending = BlendingMode.Additive;

            Children = new[]
            {
                background = new Box { RelativeSizeAxes = Axes.Both },
                foreground = new BufferedContainer
                {
                    RelativeSizeAxes = Axes.Both,
                    CacheDrawnFrameBuffer = true,
                    Children = new Drawable[]
                    {
                        new Box { RelativeSizeAxes = Axes.Both },
                        subtractionContainer = new BufferedContainer
                        {
                            RelativeSizeAxes = Axes.Both,
                            // This is needed because we're blending with another object
                            BackgroundColour = Color4.White.Opacity(0),
                            CacheDrawnFrameBuffer = true,
                            // The 'hole' is achieved by subtracting the result of this container with the parent
                            Blending = new BlendingParameters { AlphaEquation = BlendingEquation.ReverseSubtract },
                            Child = subtractionLayer = new CircularContainer
                            {
                                Anchor = Anchor.Centre,
                                Origin = Anchor.Centre,
                                // Height computed in Update
                                Width = 1,
                                Masking = true,
                                Child = new Box
                                {
                                    RelativeSizeAxes = Axes.Both,
                                    Alpha = 0,
                                    AlwaysPresent = true
                                }
                            }
                        }
                    }
                }
            };
        }

        protected override void LoadComplete()
        {
            base.LoadComplete();

            updateAccentColour();
        }

        private Color4 accentColour;
        public Color4 AccentColour
        {
            get { return accentColour; }
            set
            {
                if (accentColour == value)
                    return;
                accentColour = value;

                updateAccentColour();
            }
        }

        private Cached subtractionCache = new Cached();

        public override bool Invalidate(Invalidation invalidation = Invalidation.All, Drawable source = null, bool shallPropagate = true)
        {
            if ((invalidation & Invalidation.DrawSize) > 0)
                subtractionCache.Invalidate();

            return base.Invalidate(invalidation, source, shallPropagate);
        }

        protected override void Update()
        {
            base.Update();

            if (!subtractionCache.IsValid)
            {
                subtractionLayer.Width = 5;
                subtractionLayer.Height = Math.Max(0, DrawHeight - DrawWidth);
                subtractionLayer.EdgeEffect = new EdgeEffectParameters
                {
                    Colour = Color4.White,
                    Type = EdgeEffectType.Glow,
                    Radius = DrawWidth
                };

                foreground.ForceRedraw();
                subtractionContainer.ForceRedraw();

                subtractionCache.Validate();
            }
        }

        private void updateAccentColour()
        {
            if (!IsLoaded)
                return;

            foreground.Colour = AccentColour.Opacity(0.4f);
            background.Colour = AccentColour.Opacity(0.2f);

            subtractionCache.Invalidate();
        }
    }
}


text:
NS_ASSUME_NONNULL_BEGIN

@protocol PINGroupOperationReference;

@interface PINOperationGroup : NSObject

- (instancetype)init NS_UNAVAILABLE;
+ (instancetype)asyncOperationGroupWithQueue:(PINOperationQueue *)operationQueue;

- (nullable id <PINGroupOperationReference>)addOperation:(dispatch_block_t)operation;
- (nullable id <PINGroupOperationReference>)addOperation:(dispatch_block_t)operation withPriority:(PINOperationQueuePriority)priority;
- (void)start;
- (void)cancel;
- (void)setCompletion:(dispatch_block_t)completion;
- (void)waitUntilComplete;

@end

@protocol PINGroupOperationReference <NSObject>

@end

NS_ASSUME_NONNULL_END


text:
try:
    import simplejson as json
except ImportError:
    import json

from libcloud.common.luadns import LuadnsResponse, LuadnsConnection
from libcloud.common.luadns import LuadnsException
from libcloud.dns.base import DNSDriver, Zone, Record
from libcloud.dns.types import Provider, RecordType
from libcloud.dns.types import ZoneDoesNotExistError, ZoneAlreadyExistsError
from libcloud.dns.types import RecordDoesNotExistError

__all__ = ["LuadnsDNSDriver"]

class LuadnsDNSResponse(LuadnsResponse):
    pass

class LuadnsDNSConnection(LuadnsConnection):
    responseCls = LuadnsDNSResponse

class LuadnsDNSDriver(DNSDriver):
    type = Provider.LUADNS
    name = "Luadns"
    website = "https://www.luadns.com"
    connectionCls = LuadnsDNSConnection

    RECORD_TYPE_MAP = {
        RecordType.A: "A",
        RecordType.AAAA: "AAAA",
        RecordType.CNAME: "CNAME",
        RecordType.MX: "MX",
        RecordType.NS: "NS",
        RecordType.PTR: "PTR",
        RecordType.SOA: "SOA",
        RecordType.SRV: "SRV",
        RecordType.TXT: "TXT",
    }

    def list_zones(self):
        """
        Return a list of zones.

        :return: ``list`` of :class:`Zone`
        """
        action = "/v1/zones"
        response = self.connection.request(action=action, method="GET")
        zones = self._to_zones(response.parse_body())

        return zones

    def get_zone(self, zone_id):
        """
        Return a Zone instance.

        :param zone_id: ID of the required zone
        :type  zone_id: ``str``

        :rtype: :class:`Zone`
        """
        action = "/v1/zones/%s" % zone_id
        try:
            response = self.connection.request(action=action)
        except LuadnsException as e:
            if e.message in ["Zone not found.", "Resource not found."]:
                raise ZoneDoesNotExistError(zone_id=zone_id, value="", driver=self)
            else:
                raise e

        zone = self._to_zone(response.parse_body())

        return zone

    def delete_zone(self, zone):
        """
        Delete a zone.

        Note: This will delete all the records belonging to this zone.

        :param zone: Zone to delete.
        :type  zone: :class:`Zone`

        :rtype: ``bool``
        """
        action = "/v1/zones/%s" % zone.id
        try:
            response = self.connection.request(action=action, method="DELETE")
        except LuadnsException as e:
            if e.message in ["Resource not found.", "Zone not found."]:
                raise ZoneDoesNotExistError(zone_id=zone.id, value="", driver=self)
            else:
                raise e

        return response.status == 200

    def create_zone(self, domain, type="master", ttl=None, extra=None):
        """
        Create a new zone.

        :param domain: Zone domain name (e.g. example.com)
        :type domain: ``str``

        :param type: Zone type (This is not really used. See API docs for extra
                     parameters).
        :type  type: ``str``

        :param ttl: TTL for new records. (This is not really used)
        :type  ttl: ``int``

        :param extra: Extra attributes (driver specific). ('region_support',
                      'zone_data')
        :type extra: ``dict``

        :rtype: :class:`Zone`
        """
        action = "/v1/zones"
        data = json.dumps({"name": domain})
        try:
            response = self.connection.request(action=action, method="POST", data=data)
        except LuadnsException as e:
            if e.message == "Zone '%s' is taken already." % domain:
                raise ZoneAlreadyExistsError(zone_id=domain, value="", driver=self)
            else:
                raise e
        zone = self._to_zone(response.parse_body())

        return zone

    def list_records(self, zone):
        """
        Return a list of records for the provided zone.

        :param zone: Zone to list records for.
        :type zone: :class:`Zone`

        :return: ``list`` of :class:`Record`
        """
        action = "/v1/zones/%s/records" % zone.id
        response = self.connection.request(action=action)
        records = self._to_records(response.parse_body(), zone=zone)

        return records

    def get_record(self, zone_id, record_id):
        """
        Return a Record instance.

        :param zone_id: ID of the required zone
        :type  zone_id: ``str``

        :param record_id: ID of the required record
        :type  record_id: ``str``

        :rtype: :class:`Record`
        """
        zone = self.get_zone(zone_id=zone_id)
        action = "/v1/zones/%s/records/%s" % (zone_id, record_id)
        try:
            response = self.connection.request(action=action)
        except LuadnsException as e:
            if e.message == "Record not found.":
                raise RecordDoesNotExistError(
                    record_id=record_id, driver=self, value=""
                )
            else:
                raise e

        record = self._to_record(response.parse_body(), zone=zone)

        return record

    def delete_record(self, record):
        """
        Delete a record.

        :param record: Record to delete.
        :type  record: :class:`Record`

        :rtype: ``bool``
        """
        action = "/v1/zones/%s/records/%s" % (record.zone.id, record.id)
        try:
            response = self.connection.request(action=action, method="DELETE")
        except LuadnsException as e:
            if e.message == "Record not found.":
                raise RecordDoesNotExistError(
                    record_id=record.id, driver=self, value=""
                )
            else:
                raise e

        return response.status == 200

    def create_record(self, name, zone, type, data, extra=None):
        """
        Create a record.

        :param name: Record name without the domain name (e.g. www).
                     Note: If you want to create a record for a base domain
                     name, you should specify empty string ('') for this
                     argument.
        :type  name: ``str``

        :param zone: Zone which the records will be created for.
        :type zone: :class:`Zone`

        :param type: DNS record type ( 'A', 'AAAA', 'CNAME', 'MX', 'NS',
                     'PTR', 'SOA', 'SRV', 'TXT').
        :type  type: :class:`RecordType`

        :param data: Data for the record (depends on the record type).
        :type  data: ``str``

        :param extra: (optional) Extra attributes ('prio', 'ttl').
        :type  extra: ``dict``

        :rtype: :class:`Record`
        """
        action = "/v1/zones/%s/records" % zone.id
        to_post = {"name": name, "content": data, "type": type, "zone_id": int(zone.id)}
        # ttl is required to create a record for luadns
        # pass it through extra like this: extra={'ttl':ttl}
        if extra is not None:
            to_post.update(extra)
        data = json.dumps(to_post)
        try:
            response = self.connection.request(action=action, method="POST", data=data)
        except LuadnsException as e:
            raise e

        record = self._to_record(response.parse_body(), zone=zone)

        return record

    def _to_zone(self, item):
        common_attr = ["id", "name"]
        extra = {}
        for key in item:
            if key not in common_attr:
                extra[key] = item.get(key)
        zone = Zone(
            domain=item["name"],
            id=item["id"],
            type=None,
            ttl=None,
            driver=self,
            extra=extra,
        )

        return zone

    def _to_zones(self, items):
        zones = []
        for item in items:
            zones.append(self._to_zone(item))

        return zones

    def _to_record(self, item, zone):
        common_attr = ["id", "content", "name", "type"]
        extra = {}
        for key in item:
            if key not in common_attr:
                extra[key] = item.get(key)
        record = Record(
            id=item["id"],
            name=item["name"],
            type=item["type"],
            data=item["content"],
            zone=zone,
            driver=self,
            extra=extra,
        )

        return record

    def _to_records(self, items, zone):
        records = []
        for item in items:
            records.append(self._to_record(item, zone))

        return records


text:
package com.ctrip.hermes.kafka.admin;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Properties;
import java.util.Random;

import joptsimple.ArgumentAcceptingOptionSpec;
import joptsimple.OptionParser;
import joptsimple.OptionSet;
import joptsimple.OptionSpec;
import joptsimple.OptionSpecBuilder;
import kafka.consumer.ConsumerConfig;
import kafka.tools.PerfConfig;

public class ConsumerPerfConfig extends PerfConfig {

	public ConsumerConfig consumerConfig;

	public int numThreads;

	public String topic;

	public long numMessages;

	public int reportingInterval;

	public boolean showDetailedStats;

	public SimpleDateFormat dateFormat;

	public boolean hideHeader;

	public ConsumerPerfConfig(String[] args) {
		super(args);
		parserArgs(args);
	}

	private void parserArgs(String[] args) {
		ArgumentAcceptingOptionSpec<String> zkConnectOpt = parser()
		      .accepts(
		            "zookeeper",
		            "REQUIRED: The connection string for the zookeeper connection in the form host:port. "
		                  + "Multiple URLS can be given to allow fail-over.").withRequiredArg().describedAs("urls")
		      .ofType(String.class);
		ArgumentAcceptingOptionSpec<String> topicOpt = parser().accepts("topic", "REQUIRED: The topic to consume from.")
		      .withRequiredArg().describedAs("topic").ofType(String.class);
		ArgumentAcceptingOptionSpec<String> groupIdOpt = parser().accepts("group", "The group id to consume on.")
		      .withRequiredArg().describedAs("gid").defaultsTo("perf-consumer-" + new Random().nextInt(100000))
		      .ofType(String.class);
		ArgumentAcceptingOptionSpec<Integer> fetchSizeOpt = parser()
		      .accepts("fetch-size", "The amount of data to fetch in a single request.").withRequiredArg()
		      .describedAs("size").ofType(Integer.class).defaultsTo(1024 * 1024);
		OptionSpecBuilder resetBeginningOffsetOpt = parser()
		      .accepts(
		            "from-latest",
		            "If the consumer does not already have an established "
		                  + "offset to consume from, start with the latest message present in the log rather than the earliest message.");
		ArgumentAcceptingOptionSpec<Integer> socketBufferSizeOpt = parser()
		      .accepts("socket-buffer-size", "The size of the tcp RECV size.").withRequiredArg().describedAs("size")
		      .ofType(Integer.class).defaultsTo(2 * 1024 * 1024);
		ArgumentAcceptingOptionSpec<Integer> numThreadsOpt = parser().accepts("threads", "Number of processing threads.")
		      .withRequiredArg().describedAs("count").ofType(Integer.class).defaultsTo(10);
		ArgumentAcceptingOptionSpec<Integer> numFetchersOpt = parser()
		      .accepts("num-fetch-threads", "Number of fetcher threads.").withRequiredArg().describedAs("count")
		      .ofType(Integer.class).defaultsTo(1);

		OptionSet options = parser().parse(args);

		try {
			checkRequiredArgs(parser(), options, zkConnectOpt, topicOpt);
		} catch (IOException e) {
			e.printStackTrace();
		}

		Properties props = new Properties();
		props.put("group.id", options.valueOf(groupIdOpt));
		props.put("socket.receive.buffer.bytes", options.valueOf(socketBufferSizeOpt).toString());
		props.put("fetch.message.max.bytes", options.valueOf(fetchSizeOpt).toString());
		props.put("auto.offset.reset", options.has(resetBeginningOffsetOpt) ? "largest" : "smallest");
		props.put("zookeeper.connect", options.valueOf(zkConnectOpt));
		props.put("consumer.timeout.ms", "5000");
		props.put("num.consumer.fetchers", options.valueOf(numFetchersOpt).toString());
		consumerConfig = new ConsumerConfig(props);
		numThreads = options.valueOf(numThreadsOpt).intValue();
		topic = options.valueOf(topicOpt);
		numMessages = options.valueOf(numMessagesOpt()).longValue();
		reportingInterval = options.valueOf(reportingIntervalOpt()).intValue();
		showDetailedStats = options.has(showDetailedStatsOpt());
		dateFormat = new SimpleDateFormat(options.valueOf(dateFormatOpt()));
		hideHeader = options.has(hideHeaderOpt());
	}

	private static void checkRequiredArgs(OptionParser parser, OptionSet options, OptionSpec<?>... required)
	      throws IOException {
		for (OptionSpec<?> arg : required) {
			if (!options.has(arg))
				printUsageAndDie(parser, "Missing required argument \"" + arg + "\"");
		}
	}

	private static void printUsageAndDie(OptionParser parser, String message) throws IOException {
		System.err.println(message);
		parser.printHelpOn(System.err);
		System.exit(1);
	}
}


text:
{-# LANGUAGE GeneralizedNewtypeDeriving #-}

-- | A type for unique identifiers.
module Guide.Uid
(
  Uid(..),
  randomShortUid,
  randomLongUid,
)
where

import Imports
import Data.Aeson
import Data.SafeCopy
import Web.HttpApiData
import System.Random (randomRIO)

----------------------------------------------------------------------------
-- Type
----------------------------------------------------------------------------

-- | Unique id, used for many things – categories, items, and anchor ids.
newtype Uid a = Uid {uidToText :: Text}
  deriving stock (Generic, Eq, Ord, Data)
  deriving newtype
    (Read, Show, IsString, Buildable, ToHttpApiData, FromHttpApiData,
     Hashable, ToJSON, FromJSON)

----------------------------------------------------------------------------
-- Instances
----------------------------------------------------------------------------

-- This instance is written manually because otherwise it produces a warning:
--     • Redundant constraint: SafeCopy a
--     • In the instance declaration for 'SafeCopy (Uid a)'
instance SafeCopy (Uid a) where
  putCopy = contain . safePut . uidToText
  getCopy = contain (Uid <$> safeGet)
  version = 2
  kind = base

----------------------------------------------------------------------------
-- Generating random uids
----------------------------------------------------------------------------

-- | Generate a random text of given length from characters @a-z@ and digits.
randomText :: MonadIO m => Int -> m Text
randomText n = liftIO $ do
  -- We don't want the 1st char to be a digit. Just in case (I don't really
  -- have a good reason). Maybe to prevent Javascript from doing automatic
  -- conversions or something (though it should never happen).
  x <- randomRIO ('a', 'z')
  let randomChar = do
        i <- randomRIO (0, 35)
        return $ if i < 10 then toEnum (fromEnum '0' + i)
                           else toEnum (fromEnum 'a' + i - 10)
  xs <- replicateM (n-1) randomChar
  return (toText (x:xs))

-- For probability tables, see
-- https://en.wikipedia.org/wiki/Birthday_problem#Probability_table

-- | Generate a random UID of length 12.
--
-- Probability of collision for
--
--   * a million UIDs: approximately 1e-6
--   * a billion UIDs: approximately 0.25
randomLongUid :: MonadIO m => m (Uid a)
randomLongUid = Uid <$> randomText 12

-- | Generate a random UID of length 8.
--
-- These UIDs are only used for items and categories (because their uids can
-- occur in links and so they should look a bit nicer).
--
-- Probability of collision for
--
--   * a hundred thousand UIDs: approximately 0.5%
--   * a million UIDs: approximately 40%
randomShortUid :: MonadIO m => m (Uid a)
randomShortUid = Uid <$> randomText 8


text:
<?php

class AW_All_Block_Jsinit extends Mage_Adminhtml_Block_Template
{

    protected $_platform = -1;
    protected $_extensions_cache = array();
    protected $_extensions;

    protected $_section = '';
    protected $_store_data = null;

    /**
     * Include JS in head if section is moneybookers
     */
    protected function _prepareLayout()
    {
        $this->_section = $this->getAction()->getRequest()->getParam('section', false);
        if ($this->_section == 'awall') {
            $this->getLayout()
                    ->getBlock('head')
                    ->addJs('aw_all/aw_all.js');
            $this->setData('extensions', $this->_initExtensions());
        } elseif ($this->_section == 'awstore') {
            // AW extensions store
            $this->getLayout()
                    ->getBlock('head')
                    ->addJs('aw_all/aw_all.js');
            $this->setData('store_data', $this->_getStoreData());
        }
        parent::_prepareLayout();
    }

    /**
     * Print init JS script into body
     * @return string
     */
    protected function _toHtml()
    {
        if ($this->_section == 'awall' || $this->_section == 'awstore') {
            return parent::_toHtml();
        } else {
            return '';
        }
    }

    protected function _initExtensions()
    {

        $extensions = array();

        $modules = array_keys((array)Mage::getConfig()->getNode('modules')->children());
        sort($modules);

        foreach ($modules as $moduleName) {
            if (strstr($moduleName, 'AW_') === false) {
                continue;
            }

            if ($moduleName == 'AW_Core' || $moduleName == 'AW_All') {
                continue;
            }
            // Detect extension platform
            try {
                if ($platform = Mage::getConfig()->getNode("modules/$moduleName/platform")) {
                    $platform = strtolower($platform);
                    $ignore_platform = false;
                } else {
                    throw new Exception();
                }
            } catch (Exception $e) {
                $platform = "ce";
                $ignore_platform = true;
            }
            $platform = AW_All_Helper_Versions::convertPlatform($platform);

            // Detect installed version
            $ver = (Mage::getConfig()->getModuleConfig($moduleName)->version);
            $isPlatformValid = $platform >= $this->getPlatform();
            $feedInfo = $this->getExtensionInfo($moduleName);

            $upgradeAvailable = ($this->_convertVersion($feedInfo->getLatestVersion()) - $this->_convertVersion($ver)) > 0;

            $extensions[] = new Varien_Object(array(
                                                   'version' => $ver,
                                                   'name' => $moduleName,
                                                   'is_platform_valid' => $isPlatformValid,
                                                   'platform' => $platform,
                                                   'feed_info' => $feedInfo,
                                                   'upgrade_available' => $upgradeAvailable
                                              ));
        }
        return $extensions;
    }

    /**
     * Convert version to comparable integer
     * @param $v
     * @return int
     */
    protected function _convertVersion($v)
    {
        $digits = @explode(".", $v);
        $version = 0;
        if (is_array($digits)) {
            foreach ($digits as $k => $v) {
                $version += ($v * pow(10, max(0, (3 - $k))));
            }
        }
        return $version;
    }

    /**
     * Get extension info from cached feed
     * @param $moduleName
     * @return bool|Varien_Object
     */
    public function getExtensionInfo($moduleName)
    {
        if (!sizeof($this->_extensions_cache)) {
            if ($displayNames = Mage::app()->loadCache('aw_all_extensions_feed')) {
                $this->_extensions_cache = @unserialize($displayNames);
            }
        }
        if (array_key_exists($moduleName, $this->_extensions_cache)) {
            $data = array(
                'url' => @$this->_extensions_cache[$moduleName]['url'],
                'display_name' => @$this->_extensions_cache[$moduleName]['display_name'],
                'latest_version' => @$this->_extensions_cache[$moduleName]['version']
            );
            return new Varien_Object($data);
        }
        return new Varien_Object();
    }

    /**
     * Return icon for installed extension
     * @param $Extension
     * @return Varien_Object
     */
    public function getIcon($Extension)
    {
        if ($Extension->getUpgradeAvailable()) {
            $icon = 'aw_all/images/update.gif';
            $title = "Update available";
        } elseif (!$Extension->getIsPlatformValid()) {
            $icon = 'aw_all/images/bad.gif';
            $title = "Wrong Extension Platform";
        } else {
            $icon = 'aw_all/images/ok.gif';
            $title = "Installed and up to date";
        }
        return new Varien_Object(array('title' => $title, 'source' => $this->getSkinUrl($icon)));
    }

    /**
     * Fetch store data and return as Varien Object
     * @return Varien_Object
     */
    protected function _getStoreData()
    {
        if (!is_null($this->_store_data))
            return $this->_store_data;
        $storeData = array();
        $connection = $this->_getStoreConnection();
        $storeResponse = $connection->read();

        if ($storeResponse !== false) {
            $storeResponse = preg_split('/^\r?$/m', $storeResponse, 2);
            $storeResponse = trim($storeResponse[1]);
            Mage::app()->saveCache($storeResponse, AW_All_Helper_Config::STORE_RESPONSE_CACHE_KEY);
        }
        else {
            $storeResponse =  Mage::app()->loadCache(AW_All_Helper_Config::STORE_RESPONSE_CACHE_KEY);
            if (!$storeResponse) {
                Mage::getSingleton('adminhtml/session')->addError($this->__('Sorry, but Extensions Store is not available now. Please try again in a few minutes.'));
            }
        }

        $connection->close();
        $this->_store_data = new Varien_Object(array('text_response' => $storeResponse));
        return $this->_store_data;
    }

    /**
     * Returns URL to store
     * @return Varien_Http_Adapter_Curl
     */
    protected function _getStoreConnection()
    {
        $params = array(

        );
        $url = array();
        foreach ($params as $k => $v) {
            $url[] = urlencode($k) . "=" . urlencode($v);
        }
        $url = rtrim(AW_All_Helper_Config::STORE_URL) . (sizeof($url) ? ("?" . implode("&", $url)) : "");

        $curl = new Varien_Http_Adapter_Curl();
        $curl->setConfig(array(
                              'timeout' => 5
                         ));
        $curl->write(Zend_Http_Client::GET, $url, '1.0');

        return $curl;
    }

}


text:
'use strict';

angular.module('recipe')

.config(['$routeProvider', function($routeProvider) {
	$routeProvider.when('/home', {
		templateUrl: 'recipe-lib/home/home.html',
		controller: 'HomeCtrl'
	});
}])

.controller('HomeCtrl', function($scope, $location, userService) {

	var userHasClickedLoginSensitiveButton = false;

	$scope.navigateToRecipeBook = function() {
		userHasClickedLoginSensitiveButton = true;
		if (!userService.isLoggedIn()) {
			return;
		}

		var currentUser = userService.getLoggedInUser();
		var recipeBookUrl = '/user/' + currentUser.userId + '/recipe-book';
		$location.url(recipeBookUrl);
	};

	$scope.hideErrorMessage = function() {
		userHasClickedLoginSensitiveButton = false;
	};

	$scope.shouldShowErrorMessage = function() {
		return userHasClickedLoginSensitiveButton && !userService.isLoggedIn();
	};

	$scope.navigateToBrowseRecipes = function() {
		$location.url('/search-recipes');
	};

	$scope.navigateToSaveNewRecipe = function() {
		userHasClickedLoginSensitiveButton = true;
		if (!userService.isLoggedIn()) {
			return;
		}

		$location.url('/new-recipe');
	};
});


text:
var express = require('express');
var path = require('path');
var app = express();

// Define the port to run on
app.set('port', 3000);

app.use(function requireHTTP(req, res, next) {
  if (req.secure) {
    console.log('test');
    return res.redirect('http://' + req.headers.host + req.url);
  }
  next();
});

app.use(express.static(path.join(__dirname, '')));

// Listen for requests
var server = app.listen(app.get('port'), function() {
  var port = server.address().port;
  console.log('Magic happens on port ' + port);
});


text:
package thrift

import (
	"crypto/tls"
	"net"
	"time"
)

type SSLServerSocket struct {
	listener      net.Listener
	addr          net.Addr
	clientTimeout time.Duration
	interrupted   bool
	cfg           *tls.Config
}

func NewSSLServerSocket(listenAddr string, cfg *tls.Config) (*SSLServerSocket, error) {
	return NewSSLServerSocketTimeout(listenAddr, cfg, 0)
}

func NewSSLServerSocketTimeout(listenAddr string, cfg *tls.Config, clientTimeout time.Duration) (*SSLServerSocket, error) {
	addr, err := net.ResolveTCPAddr("tcp", listenAddr)
	if err != nil {
		return nil, err
	}
	return &SSLServerSocket{addr: addr, clientTimeout: clientTimeout, cfg: cfg}, nil
}

func (p *SSLServerSocket) Listen() error {
	if p.IsListening() {
		return nil
	}
	l, err := tls.Listen(p.addr.Network(), p.addr.String(), p.cfg)
	if err != nil {
		return err
	}
	p.listener = l
	return nil
}

func (p *SSLServerSocket) Accept() (Transport, error) {
	if p.interrupted {
		return nil, errTransportInterrupted
	}
	if p.listener == nil {
		return nil, NewTransportException(NOT_OPEN, "No underlying server socket")
	}
	conn, err := p.listener.Accept()
	if err != nil {
		return nil, NewTransportExceptionFromError(err)
	}
	return NewSSLSocketFromConnTimeout(conn, p.cfg, p.clientTimeout), nil
}

// Checks whether the socket is listening.
func (p *SSLServerSocket) IsListening() bool {
	return p.listener != nil
}

// Connects the socket, creating a new socket object if necessary.
func (p *SSLServerSocket) Open() error {
	if p.IsListening() {
		return NewTransportException(ALREADY_OPEN, "Server socket already open")
	}
	if l, err := tls.Listen(p.addr.Network(), p.addr.String(), p.cfg); err != nil {
		return err
	} else {
		p.listener = l
	}
	return nil
}

func (p *SSLServerSocket) Addr() net.Addr {
	return p.addr
}

func (p *SSLServerSocket) Close() error {
	defer func() {
		p.listener = nil
	}()
	if p.IsListening() {
		return p.listener.Close()
	}
	return nil
}

func (p *SSLServerSocket) Interrupt() error {
	p.interrupted = true
	return nil
}


text:
/**
 * Contains a batch to periodically flushes to the database.
 */
package com.feedzai.commons.sql.abstraction.batch;


text:
package com.dbumama.market.model;

import com.dbumama.market.model.base.BaseProduct;

/**
 * Generated by JFinal.
 */
@SuppressWarnings("serial")
public class Product extends BaseProduct<Product> {
	public static final Product dao = new Product();
	public static final String table = "t_product";
	/**库存 *//*
	private List<ProductStock> stocks=new ArrayList<ProductStock>();
	*//** 商品图片 *//*
	private List<ProductImage> productImages = new ArrayList<ProductImage>();

	*//** page speci **//*
	private List<Specification> specifications4Page = new ArrayList<Specification>();

	*//** 规格值 *//*
	private List<SpecificationValue> specificationValues4Page = new ArrayList<SpecificationValue>();

	public List<ProductStock> getStocks() {
		return stocks;
	}

	public void setStocks(List<ProductStock> stocks) {
		this.stocks = stocks;
	}

	public List<ProductImage> getProductImages() {
		return productImages;
	}

	public void setProductImages(List<ProductImage> productImages) {
		this.productImages = productImages;
	}

	public List<Specification> getSpecifications4Page() {
		return specifications4Page;
	}

	public void setSpecifications4Page(List<Specification> specifications4Page) {
		this.specifications4Page = specifications4Page;
	}

	public List<SpecificationValue> getSpecificationValues4Page() {
		return specificationValues4Page;
	}

	public void setSpecificationValues4Page(List<SpecificationValue> specificationValues4Page) {
		this.specificationValues4Page = specificationValues4Page;
	}*/

}


text:
import React from 'react';
import { Router, Route, IndexRoute, IndexRedirect, Redirect } from 'react-router';

import RestaurantLayout from 'pages/restaurant-layout';
import Restaurant from 'pages/restaurant';
import Menu from 'pages/menu';
import Tables from 'pages/tables';
import Staff from 'pages/staff';
import Reports from 'pages/reports';

import SuperLayout from 'pages/super-layout';
import RegisterPage from 'pages/register';
import AdminRestaurantList from 'pages/admin-restaurant-list';
import AdminRestaurantNew from 'pages/admin-restaurant-new';
import AdminRestaurantShow from 'pages/admin-restaurant-show';

import KitchenLayout from 'pages/kitchen-layout';
import KitchenPage from 'pages/kitchen';

import WaiterLayout from 'pages/waiter/waiter-layout';
import WaiterOrders from 'pages/waiter/orders';
import WaiterNewOrder from 'pages/waiter/new-order';

import AuthLayout from 'pages/auth-layout';
import LoginPage from 'pages/login';
import LogoutPage from 'pages/logout';
import changePasswordPage from 'pages/change-password';
import ResetPasswordPage from 'pages/reset-password';

export default function getRoutes(history, checkIfAuthed){
  return (
    <Router history={history}>
      <Route component={AuthLayout}>
        <Redirect from="/login" to="/" />
        <Route component={LoginPage} path="/" onEnter={checkIfAuthed} />
        <Route component={LogoutPage} path="/logout" />
        <Route component={ResetPasswordPage} path="/reset_password" />
        <Route component={changePasswordPage} path="/change_password" />
      </Route>
      <Redirect from="restaurante/:id" to="/" />
      <Route path="restaurante/:id/admin" component={RestaurantLayout} onEnter={checkIfAuthed}>
        <IndexRoute component={Restaurant} />
        <Route path="menu" component={Menu} />
        <Route path="mesas" component={Tables} />
        <Route path="personal" component={Staff} />
        <Route path="reportes" component={Reports}></Route>
      </Route>
      <Route path="restaurante/:id/cocina" component={KitchenLayout} onEnter={checkIfAuthed}>
        <IndexRoute component={KitchenPage} />
      </Route>
      <Route path="restaurante/:id/ordenes" component={WaiterLayout} onEnter={checkIfAuthed}>
        <IndexRedirect to="lista" />
        <Route path="lista" component={WaiterOrders} />
        <Route path="nueva-orden" component={WaiterNewOrder} />
        <Route path="editar-orden" component={WaiterNewOrder} />
      </Route>
      <Route path="super" component={SuperLayout} onEnter={checkIfAuthed}>
        <IndexRoute component={AdminRestaurantList} />
        <Route path="restaurante/:id" component={AdminRestaurantShow} />
      </Route>
    </Router>
  );
}


text:
### Components, Dependencies

In this step we are going to implement the top-level React component `TodoApp`.

#### A minimal React component

First we need to create a new file called `todoApp.jsx` in the `src` folder.
This file will contain the component that describes the overall structure of the web app.

We need some boilerplate code:

    :::js
    /**
     * @jsx React.DOM
     */
    define([
      "react"
    ], function (React) {
        // TODO
    });

Next we will create a React component and return it as the requireJS export.
Inside the callback function:

    :::js
    return React.createClass({
      render: function() {
        return (

It works!

        );
      }
    });

#### Adding a dependency to main.jsx

Now that we have a React component we can "require" it in `main.jsx`.
We do so by adding a `"build/todoApp"` to the list of dependencies in `define`.
In addition we need a `TodoApp` parameter in the callback function.
It should look like this:

    define([
      "ankor/AnkorSystem",
      "ankor/transport/WebSocketTransport",
      "ankor/utils/BaseUtils",
      "react",
      "build/todoApp"
    ], function (AnkorSystem, WebSocketTransport, BaseUtils, React, TodoApp) {

#### Implementing the render function

The render function will create an instance of our `TodoApp` component and patch it into the DOM.
React's `renderComponent` method will handle this for us.
It takes a React component as first parameter and a target DOM node as a second parameter.
As previously mentioned, any successive call to `renderComponent` will only patch the difference into that DOM node.

    function render() {
      React.renderComponent(
        <TodoApp modelRef={rootRef.appendPath("model")} />,
        document.getElementById('todoapp')
      );
    };

You may have noticed the inline XML. Again, the JSX transformer will turn it into valid JavaScript for us.

The other interesting thing here is the `modelRef` attribute of the `TodoApp` tag.
Attributes you pass to a React component like this will be available inside the component via `this.props`.

#### Navigating Refs

To understand the `appendPath` method that gets called on `rootRef` we take a look at the overall structure of our view model:

    :::javascript
    "root": {
        "model": {
            "tasks": [],
            "filter": "all",
            "itemsLeft": 0,
            "itemsLeftText": "items left",
            "footerVisibility": false,
            "itemsComplete": 0,
            "itemsCompleteText": "Clear completed (0)",
            "clearButtonVisibility": false,
            "toggleAll": true,
            "filterAllSelected": true,
            "filterActiveSelected": false,
            "filterCompletedSelected": false
        }
    }

To navigate the tree we can "append" a path to a `Ref`, yielding a new `Ref` to the specified child node.
We want access to the `model` property and its various key-value pairs, which hold the actual state of the UI.
`rootRef.appendPath("model")` will do just that.

That's it for this step. In the next step we will implement the `TodoApp` component.