text:
class CloudsController < ApplicationController
  before_action :set_cloud, only: [:show, :edit, :update, :destroy]

  # GET /clouds
  # GET /clouds.json
  def index
    @clouds = Cloud.all
  end

  # GET /clouds/1
  # GET /clouds/1.json
  def show
  end

  # GET /clouds/new
  def new
    @cloud = Cloud.new
  end

  # GET /clouds/1/edit
  def edit
  end

  # POST /clouds
  # POST /clouds.json
  def create
    @cloud = Cloud.new(cloud_params)

    respond_to do |format|
      if @cloud.save
        format.html { redirect_to @cloud, notice: 'Cloud was successfully created.' }
        format.json { render :show, status: :created, location: @cloud }
      else
        format.html { render :new }
        format.json { render json: @cloud.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /clouds/1
  # PATCH/PUT /clouds/1.json
  def update
    respond_to do |format|
      if @cloud.update(cloud_params)
        format.html { redirect_to @cloud, notice: 'Cloud was successfully updated.' }
        format.json { render :show, status: :ok, location: @cloud }
      else
        format.html { render :edit }
        format.json { render json: @cloud.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /clouds/1
  # DELETE /clouds/1.json
  def destroy
    @cloud.destroy
    respond_to do |format|
      format.html { redirect_to clouds_url, notice: 'Cloud was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_cloud
      @cloud = Cloud.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def cloud_params
      params.require(:cloud).permit(:name, :cidr_block, :driver_id, :scenario_id)
    end
end


text:
module("baidu.fx.zoomOut");
// zoomOut引用scale,此处仅测试完成时的效果,
test('check property and hide after finish', function() {
	// 1、hide after finish
	// 2、check to and from as default
	stop();
	baidu.fx.zoomOut(te.dom[1], {
		onafterfinish : function() {
			ok(true, 'test id');
			equals(this.interval, 16, 'interval = ' + this.interval);
			equals(this.duration, 500, 'duration = ' + this.duration);
			equals(this.dynamic, true, 'dynamic = ' + this.dynamic);
			equals(this.percent, 1, 'percent = ' + this.percent);
			equals(this.to, 0.1, 'default: this.to = ' + this.to);
			equals(this.from, 1, 'default: this.from = ' + this.from);
			equals(this.restoreAfterFinish, true,
					'default: this.restoreAfterFinish = '
							+ this.restoreAfterFinish);
			equals(this.transition(2), 0, 'default: this.transition(2) = '
					+ this.transition(2));
			setTimeout(function() {
				equals($(te.dom[1]).css('display'), 'none', 'hide after finish');
				start();
			}, 20);
		}
	});
});

//
// 用例逻辑设置有问题(fx cancel后调用dispose),导致IE下抛异常
// // test id
// test('test id', function() {
// var c = baidu.fx.zoomOut('img_div', {
// onafterfinish : function() {
// ok(true, 'test id');
// equals(this.interval, 16, 'interval = ' + this.interval);
// equals(this.duration, 500, 'duration = ' + this.duration);
// equals(this.dynamic, true, 'dynamic = ' + this.dynamic);
// equals(this.percent, 1, 'percent = ' + this.percent);
// equals(this.to, 0.1, 'default: this.to = ' + this.to);
// equals(this.from, 1, 'default: this.from = ' + this.from);
// equals(this.restoreAfterFinish, true,
// 'default: this.restoreAfterFinish = '
// + this.restoreAfterFinish);
// equals(this.transition(2), 0, 'default: this.transition(2) = '
// + this.transition(2));
// start();
// }
// });
// stop();
// });
//
// // test dom
// test('test dom', function() {
// var c = baidu.fx.zoomOut('img_div', {
// onafterfinish : function() {
// ok(true, 'test id');
// equals(this.interval, 16, 'interval = ' + this.interval);
// equals(this.duration, 500, 'duration = ' + this.duration);
// equals(this.dynamic, true, 'dynamic = ' + this.dynamic);
// equals(this.percent, 1, 'percent = ' + this.percent);
// equals(this.to, 0.1, 'default: this.to = ' + this.to);
// equals(this.from, 1, 'default: this.from = ' + this.from);
// equals(this.restoreAfterFinish, true,
// 'default: this.restoreAfterFinish = '
// + this.restoreAfterFinish);
// equals(this.transition(2), 0, 'default: this.transition(2) = '
// + this.transition(2));
// start();
// }
// });
// stop();
// });
//
// // test from
// test('test from', function() {
// var c, f = 0.5;
// var img = document.getElementById('img_id');
// c = baidu.fx.zoomOut('img_div', {
// from : f,
// onafterfinish : function() {
// equals(img.height * f, 128 * f, 'from img height = ' + img.height
// * f); // img height=128px;
// start();
// }
// });
// stop();
// });
//
// // test to
// test('test to', function() {
// var c, t = 0.5;
// var img = document.getElementById('img_id');
// c = baidu.fx.zoomOut('img_div', {
// to : t,
// onafterfinish : function() {
// equals(img.width * t, 128 * t, 'to img width = ' + img.width * t); // img
// // width=128px;start();
// start();
// }
// });
// stop();
// });
//
// // test duraton
// test('test duration', function() {
// var c, stime, dtime;
// c = baidu.fx.zoomOut('img_div', {
// onafterfinish : function() {
// dtime = new Date().getTime() - stime;
// ok(dtime - 800 < 20, 'duration: ' + dtime + 'ms');
// start();
// }
// });
// stime = new Date().getTime();
// stop();
// });
//
// // test interval
// test('test interval', function() {
// var c, itime;
// c = baidu.fx.zoomOut('img_div', {
// onafterfinish : function() {
// setTimeout(QUnit.start, 50);
// }
// });
// equals(c.interval, 16, 'interval default 16ms');
// stop();
// });
//
// /* Events将在Timeline用例中被测试,此处忽略 */
// // //test transition
// // test('test transition 时间线', function(){
// // var c, img, timeline;
// // c = baidu.fx.zoomIn('img_div', {
// // onbeforestart: function(){
// // ok(this.transition>0, '');
// // start();
// // }
// // });
// // stop();
// // });
// // test onbeforestart
// test('test onbeforestart', function() {
// var c, bu = false, au = false; // bool 控制一次
// c = baidu.fx.zoomOut('img_div', {
// onbeforestart : function() {
// ok(true, 'before start');
// },
// onbeforeupdate : function() {
// if (!bu) {
// ok(true, 'before update');
// bu = true;
// }
// },
// onafterupdate : function() {
// if (!au) {
// ok(true, 'after update');
// au = true;
// }
// },
// onafterfinish : function() {
// ok(true, 'after finish');
// this.cancel();
// },
// oncancel : function() {
// ok(true, 'oncancel called');
// // setTimeout(QUnit.start, 200);
// },
// restore : function() {
// ok(true, 'restore called');
// }
// });
// stop();
// // te.checkfx.create(te.dom[1], {
// // method : baidu.fx.zoomOut,
// // beforestart : function() {/* 初始设置启动高度为100 */
// // $(te.dom[1]).css('height', 100).css('background-color', 'red');
// // }
// // }).checkevents({
// // onafterfinish : start
// // }, 4);
// });

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Utilities.IoC.Interfaces;

namespace Utilities.IoC.BaseClasses
{
    /// <summary>
    /// Bootstrapper base class
    /// </summary>
    /// <typeparam name="Container">The actual IoC object</typeparam>
    public abstract class BootstrapperBase<Container> : IBootstrapper
    {
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="assemblies">The assemblies.</param>
        /// <param name="types">The types.</param>
        protected BootstrapperBase(IEnumerable<Assembly> assemblies, IEnumerable<Type> types)
        {
            this.Assemblies = assemblies.ToList();
            this.Types = types.ToList();
        }

        /// <summary>
        /// Name of the bootstrapper
        /// </summary>
        public abstract string Name { get; }

        /// <summary>
        /// The IoC container
        /// </summary>
        protected abstract Container AppContainer { get; }

        /// <summary>
        /// Gets the types.
        /// </summary>
        /// <value>The types.</value>
        protected List<Type> Types { get; private set; }

        /// <summary>
        /// Gets the assemblies.
        /// </summary>
        /// <value>The assemblies.</value>
        private List<Assembly> Assemblies { get; set; }

        /// <summary>
        /// Adds the assembly.
        /// </summary>
        /// <param name="Assemblies">The assemblies.</param>
        public void AddAssembly(params Assembly[] Assemblies)
        {
            if (Assemblies == null || Assemblies.Length == 0)
                return;
            foreach (Assembly Assembly in Assemblies)
            {
                if (!this.Assemblies.Contains(Assembly))
                {
                    try
                    {
                        this.Types.AddRange(Assembly.GetTypes());
                        this.Assemblies.Add(Assembly);
                    }
                    catch (ReflectionTypeLoadException) { }
                }
            }
        }

        /// <summary>
        /// Disposes of the object
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// Registers an object with the bootstrapper
        /// </summary>
        /// <typeparam name="T">Object type</typeparam>
        /// <param name="Object">Object to register</param>
        /// <param name="Name">Name associated with the object</param>
        public abstract void Register<T>(T Object, string Name = "")
            where T : class;

        /// <summary>
        /// Registers a type with the default constructor
        /// </summary>
        /// <typeparam name="T">Object type to register</typeparam>
        /// <param name="Name">Name associated with the object</param>
        public abstract void Register<T>(string Name = "")
            where T : class,new();

        /// <summary>
        /// Registers a type with the default constructor of a child class
        /// </summary>
        /// <typeparam name="T1">Base class/interface type</typeparam>
        /// <typeparam name="T2">Child class type</typeparam>
        /// <param name="Name">Name associated with the object</param>
        public abstract void Register<T1, T2>(string Name = "")
            where T2 : class,T1
            where T1 : class;

        /// <summary>
        /// Registers a type with a function
        /// </summary>
        /// <typeparam name="T">Type that the function returns</typeparam>
        /// <param name="Name">Name associated with the object</param>
        /// <param name="Function">Function to register with the type</param>
        public abstract void Register<T>(Func<T> Function, string Name = "")
            where T : class;

        /// <summary>
        /// Registers all objects of a certain type with the bootstrapper
        /// </summary>
        /// <typeparam name="T">Object type</typeparam>
        public abstract void RegisterAll<T>()
            where T : class;

        /// <summary>
        /// Resolves the object based on the type specified
        /// </summary>
        /// <typeparam name="T">Type to resolve</typeparam>
        /// <param name="DefaultObject">Default object to return if the type can not be resolved</param>
        /// <returns>An object of the specified type</returns>
        public abstract T Resolve<T>(T DefaultObject = default(T))
            where T : class;

        /// <summary>
        /// Resolves the object based on the type specified
        /// </summary>
        /// <typeparam name="T">Type to resolve</typeparam>
        /// <param name="Name">Name associated with the object</param>
        /// <param name="DefaultObject">Default object to return if the type can not be resolved</param>
        /// <returns>An object of the specified type</returns>
        public abstract T Resolve<T>(string Name, T DefaultObject = default(T))
            where T : class;

        /// <summary>
        /// Resolves the object based on the type specified
        /// </summary>
        /// <param name="ObjectType">Object type</param>
        /// <param name="DefaultObject">Default object to return if the type can not be resolved</param>
        /// <returns>An object of the specified type</returns>
        public abstract object Resolve(Type ObjectType, object DefaultObject = null);

        /// <summary>
        /// Resolves the object based on the type specified
        /// </summary>
        /// <param name="ObjectType">Object type</param>
        /// <param name="Name">Name associated with the object</param>
        /// <param name="DefaultObject">Default object to return if the type can not be resolved</param>
        /// <returns>An object of the specified type</returns>
        public abstract object Resolve(Type ObjectType, string Name, object DefaultObject = null);

        /// <summary>
        /// Resolves the objects based on the type specified
        /// </summary>
        /// <typeparam name="T">Type to resolve</typeparam>
        /// <returns>A list of objects of the specified type</returns>
        public abstract IEnumerable<T> ResolveAll<T>()
            where T : class;

        /// <summary>
        /// Resolves all objects based on the type specified
        /// </summary>
        /// <param name="ObjectType">Object type</param>
        /// <returns>A list of objects of the specified type</returns>
        public abstract IEnumerable<object> ResolveAll(Type ObjectType);

        /// <summary>
        /// Disposes of the object
        /// </summary>
        /// <param name="Managed">
        /// Determines if all objects should be disposed or just managed objects
        /// </param>
        protected virtual void Dispose(bool Managed)
        {
        }

        /// <summary>
        /// Destructor
        /// </summary>
        ~BootstrapperBase()
        {
            Dispose(false);
        }
    }
}


text:
AFetchable::AFetchable() {
 	// Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
	PrimaryActorTick.bCanEverTick = false;

    // Create the hitbox component
    HitBox = CreateDefaultSubobject<UBoxComponent>(TEXT("HitBox"));
    RootComponent = HitBox;

    // Create the static mesh component
    Mesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Mesh"));
    Mesh->SetupAttachment(RootComponent);

	BindingActor = nullptr;
}

// Assume Component contains a socket named "fetchable_socket"
void AFetchable::BindToActor(AcceptsFetchable *Actor, USceneComponent *Component) {
	// Detach from current binding actor
	if (BindingActor != nullptr) {
		BindingActor->PreUnbindFetchable(this);

		const FDetachmentTransformRules DetachRules(EDetachmentRule::KeepWorld, true);
		DetachFromActor(DetachRules);

		BindingActor->PostUnbindFetchable(this);
	}

	// Set new binding actor
	BindingActor = Actor;

	// Bind to Actor
	BindingActor->PreBindFetchable(this);

	// Attach fetchable to mesh socket
	const FName FSocketName = TEXT("fetchable_socket");
	const FAttachmentTransformRules AttachmentRules(EAttachmentRule::SnapToTarget,
		                                            EAttachmentRule::SnapToTarget,
		                                            EAttachmentRule::KeepWorld,
		                                            true);
	AttachToComponent(Component, AttachmentRules, FSocketName);

	BindingActor->PostBindFetchable(this);
}

// Called when the game starts or when spawned
void AFetchable::BeginPlay() {
	Super::BeginPlay();
}


text:
Before submitting a Pull Request, please open an issue to discuss the proposed change.

Once you know that your change is aligned with `react-autowhatever` vision:

1. Add your goodness
2. Add tests
3. Update docs to reflect changes
4. Make sure that `npm run build` is happy
5. Submit a Pull Request (with a detailed description please)


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>com.turn</groupId>
        <artifactId>ttorrent</artifactId>
        <version>1.2</version>
        <relativePath>../pom.xml</relativePath>
    </parent>

    <name>ttorrent/client</name>
    <url>http://turn.github.com/ttorrent/</url>
    <artifactId>ttorrent-client</artifactId>
    <version>1.2</version>
    <packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>com.turn</groupId>
            <artifactId>ttorrent-bencoding</artifactId>
            <version>1.2</version>
        </dependency>

        <dependency>
            <groupId>com.turn</groupId>
            <artifactId>ttorrent-network</artifactId>
            <version>1.0</version>
        </dependency>

        <dependency>
            <groupId>com.turn</groupId>
            <artifactId>ttorrent-common</artifactId>
            <version>1.2</version>
        </dependency>

        <dependency>
            <groupId>com.turn</groupId>
            <artifactId>ttorrent-test-api</artifactId>
            <version>1.0</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

</project>


text:
define(['modules/console/module'], function (module) {

    'use strict';

    module.registerController('ConsoleServiceCtrl', function (consoleService,$scope,$modal,$log) {

        var showBtn = document.getElementById('importArea');
        var importServerList = document.getElementById('importServerList');
        showBtn.onclick = function(){
            importServerList.style.display == "block"?importServerList.style.display = "none":importServerList.style.display = "block";
        }

        //consoleService.getOutsideConsoleServers(function(data){
        //    $scope.outsideConsoleServers = data;
        //});
        $scope.consoleServers = consoleService.consoleServers;
        consoleService.listConsoleServers();
        function getOutsideConsoleServers(){
            consoleService.getOutsideConsoleServers(function(data){
                $scope.outsideConsoleServers = data;
                $scope.outsideConsoleServersInfo = data.length;
            });
        }
        getOutsideConsoleServers();
        //$scope.getOutsideConsoleServers = function(){
        //    consoleService.getOutsideConsoleServers(function(data){
        //        $scope.outsideConsoleServers = data;
        //    });
        //}

        $scope.ImportConsoleServer = function(console_server_ips,console_server_id) {
            var modalInstance = $modal.open({
                templateUrl: 'app/modules/console/views/importConsoleServer.tpl.html',
                controller: function($scope,$modalInstance){
                    $scope.console_server_id = console_server_id;
                    $scope.console_server_ips = console_server_ips;
                    $scope.closeModal = function(){
                        $modalInstance.close();
                    }
                    $scope.importConsoleServer=function(){
                        console.log("in import consoleserver");
                        consoleService.importConsoleServer($scope.console_server_id,$scope.console_server_name,$scope.console_server_ip,$scope.console_server_des,function(data){
                            $scope.return_data = data;
                            if ($scope.return_data.error != null){
                                $.smallBox({
                                    title: "Import Error",
                                    content: " Import Console Server Error.",
                                    color: "#C46A69",
                                    iconSmall: "fa fa-times fa-2x fadeInRight animated",
                                    timeout: 4000
                                });

                            }
                            else{
                                $.smallBox({
                                    title: "Import Console Server Succeed",
                                    content: " Console Server Imported",
                                    color: "#659265",
                                    iconSmall: "fa fa-check fa-2x fadeInRight animated",
                                    timeout: 4000
                                });
                                getOutsideConsoleServers();
                                $modalInstance.close();
                            }
                        });
                    }
                }
            });
            modalInstance.result.then(function () {
                //$scope.UpdateImageTree();
                $log.info('Modal closed at: ' + new Date());
            }, function () {
                //$scope.UpdateImageTree();
                $log.info('Modal dismissed at: ' + new Date());
            });
        };
    });
});


text:
package raven.sqdev.misc;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectNature;
import org.eclipse.core.runtime.CoreException;

public class SQDevProjectNature implements IProjectNature {

	// ID of the natures, which consists of Bundle-SymbolicName + ID
	public static final String SQDEV_NATURE_ID = "raven.sqdev.misc.SQDevProjectNature";

	private IProject project;

	@Override
	public void configure() throws CoreException {
		// only called once the nature has been set

		// configure the project...
	}

	@Override
	public void deconfigure() throws CoreException {
		// only called once the nature has been set

		// reset the project configuration...
	}

	@Override
	public IProject getProject() {
		return project;
	}

	@Override
	public void setProject(IProject project) {
		this.project = project;
	}

}


text:
//
//  ZBAddress.h
//  Books
//
//  Created by Balasankar J on 28/11/13.
//  Copyright (c) 2013 Balasankar J. All rights reserved.
//

/**
 \addtogroup Model
 *@{
 */

#import <Foundation/Foundation.h>

/**
 ZBAddress has the information of the company location.
 */
@interface ZBAddress : NSObject

/**
 @accessors \e \c getAddress, \e \c setAddress
 */
@property(nonatomic, retain, getter = getAddress) NSString *address;

/**
 @accessors \e \c getStreetAddress1, \e \c setStreetAddress1
 */
@property(nonatomic, retain, getter = getStreetAddress1) NSString *streetAddress1;

/**
 @accessors \e \c getStreetAddress2, \e \c setStreetAddress2
 */
@property(nonatomic, retain, getter = getStreetAddress2) NSString *streetAddress2;

/**
 @accessors \e \c getCity, \e \c setCity
 */
@property(nonatomic, retain, getter = getCity) NSString *city;

/**
 @accessors \e \c getState, \e \c setState
 */
@property(nonatomic, retain, getter = getState) NSString *state;

/**
 @accessors \e \c getCountry, \e \c setCountry
 */
@property(nonatomic, retain, getter = getCountry) NSString *country;

/**
 @accessors \e \c getPostalCode, \e \c setPostalCode
 */
@property(nonatomic, retain, getter = getPostalCode) NSString *postalCode;

/**
 @accessors \e \c getFaxNumber, \e \c setFaxNumber
 */
@property(nonatomic, retain, getter = getFaxNumber) NSString *faxNumber;

/**
 Create a new instance of ZBAddress object.
 @returns ZBAddress
 */
- init;

/**
 Return a JSON representation of this ZBAddress object.
 @returns NSMutableDictionary
 */
- (NSMutableDictionary *) toJSON;

@end

/** @}*/


text:
package net.kiberion.rlforj.util;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Some utilities.
 * @author sdatta
 *
 */
public class Utils
{

	/**
	 * Given a resource name, retrieve a resource and return
	 * the contents of the resource as a string.
	 * In case of any problems, returns empty string.
	 * @param resourceName
	 * @return
	 */
	public static String getStringFromResource(String resourceName) {
		InputStream iin=Utils.class.getResourceAsStream(resourceName);
		if(iin==null){
			System.err.println("Resource not found : "+resourceName);
			return "";
		}
		BufferedInputStream in=
			new BufferedInputStream(iin);

		byte[] buffer=new byte[1000];
		StringBuilder sb=new StringBuilder();

		while(true) {
			int len=0;
			try
			{
				len = in.read(buffer);
			} catch (IOException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
				return "";
			}
			if(len==-1)
				break;
			sb.append(new String(buffer, 0, len));
		}
		return sb.toString();
	}
}


text:
// My Account application customisation for user view.

'use strict';

var db = require('../db')
  , _  = require('../i18n').bind('User');

// Assure base customisations are loaded
require('./user-base');

var getSelectedBusinessProcesses = function (user, bpType) {
	return bpType.instances.filterByKey('user', user).filterByKey('isSubmitted', false);
};

module.exports = exports = require('eregistrations/view/user');

/**
 * Util for getting filtered businessProcesses of the user
 * var getSelectedBusinessProcesses =
 * require('eregistrations/business-processes/get-user-business-processes-by-type');
 */

exports._servicesBoxList = function () {
	/**
	 * Service box configuration example:
	 * {
	 * actionUrl: '/register-as-merchant/',
	 * buttonContent:  div({ class: 'user-account-service-button' },
	 * i({ class: 'fa fa-user' }), _("Register as individual trader")),
	 * content: span(_("Short description of merchant registration process")),
	 * disabledCondition: gtOrEq(getSelectedBusinessProcesses(this.user,
	 * db.BusinessProcessMerchant)._size, 5)
	 * }
	 *
	 */
	return [{
		actionUrl: '/register-as-demo/',
		buttonContent:  div({ class: 'user-account-service-button' },
			i({ class: 'fa fa-user' }), _("Register Demo")),
		content: span(_("Short description of demo registration process")),
		disabledCondition: gtOrEq(getSelectedBusinessProcesses(this.user,
			db.BusinessProcessDemo)._size, 5)
	}];
};


text:
package hudson.plugins.scm.koji;

import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;

abstract public class Constants {

    public static final String BUILD_XML = "build.xml";
    public static final String BUILD_ENV_NVR = "KOJI_NVR";
    public static final String BUILD_ENV_RPM_FILES = "KOJI_RPMS";
    public static final String BUILD_ENV_RPMS_DIR = "KOJI_RPMS_DIR";
    public static final String PROCESSED_BUILDS_HISTORY = "processed.txt";
    public static final String getPackageID = "getPackageID";
    public static final String listBuilds = "listBuilds";
    public static final String packageID = "packageID";
    public static final String listTags = "listTags";
    public static final String listRPMs = "listRPMs";
    public static final String listArchives = "listArchives";
    public static final String buildID = "buildID";
    public static final String arches = "arches";
    public static final String build = "build";
    public static final String name = "name";
    public static final String rpms = "rpms";
    public static final String nvr = "nvr";
    public static final String files = "files";
    public static final String file = "file";
    public static final String completion_time = "completion_time";
    public static final String build_id = "build_id";
    public static final String version = "version";
    public static final String release = "release";
    public static final String arch = "arch";
    public static final String filename = "filename";

    public static final String getBuildList = "getBuildList";
    public static final String getBuildDetail = "getBuildDetail";

    public static final DateTimeFormatter DTF = new DateTimeFormatterBuilder()
            .appendValue(ChronoField.YEAR, 4)
            .appendLiteral('-')
            .appendValue(ChronoField.MONTH_OF_YEAR, 2)
            .appendLiteral('-')
            .appendValue(ChronoField.DAY_OF_MONTH, 2)
            .appendLiteral(' ')
            .appendValue(ChronoField.HOUR_OF_DAY, 2)
            .appendLiteral(':')
            .appendValue(ChronoField.MINUTE_OF_HOUR, 2)
            .appendLiteral(':')
            .appendValue(ChronoField.SECOND_OF_MINUTE, 2)
            .optionalStart()
            .appendLiteral('.')
            .appendValue(ChronoField.MICRO_OF_SECOND)
            .optionalEnd()
            .toFormatter();

    /**
     * 2016-09-09T13:34:28
     */
 public static final DateTimeFormatter DTF2 = new DateTimeFormatterBuilder()
            .appendValue(ChronoField.YEAR, 4)
            .appendLiteral('-')
            .appendValue(ChronoField.MONTH_OF_YEAR, 2)
            .appendLiteral('-')
            .appendValue(ChronoField.DAY_OF_MONTH, 2)
            .appendLiteral('T')
            .appendValue(ChronoField.HOUR_OF_DAY, 2)
            .appendLiteral(':')
            .appendValue(ChronoField.MINUTE_OF_HOUR, 2)
            .appendLiteral(':')
            .appendValue(ChronoField.SECOND_OF_MINUTE, 2)
            .toFormatter();

}


text:
using namespace bsoncxx;
using namespace mongocxx;

using bsoncxx::builder::basic::kvp;
using bsoncxx::builder::basic::make_document;

TEST_CASE("result::gridfs::upload", "[result::gridfs::upload]") {
    instance::current();

    auto oid = types::b_oid{bsoncxx::oid{}};
    result::gridfs::upload upload_result{types::value{oid}};

    SECTION("returns correct response") {
        REQUIRE(upload_result.id() == oid);
    }
}

TEST_CASE("result::gridfs::upload owns id", "[result::gridfs::upload]") {
    // Constructing a result::gridfs::upload requires passing in an id, but we don't care what it
    // is.
    std::string baz = "baz";
    result::gridfs::upload res{types::value{types::b_utf8{baz}}};

    {
        std::string bar = "bar";
        auto doc = make_document(kvp("foo", types::value{types::b_utf8{bar}}));
        auto id = doc.view()["foo"].get_value();
        res = result::gridfs::upload{id};
    }

    std::string bar = "bar";

    // Because result::gridfs::upload owns its id, we should still be able to correctly read new
    // value for the id.
    REQUIRE(res.id().get_utf8().value == stdx::string_view{bar});
}


text:
bool dlclose( void* handle );

char* dlerror();

void* dlopen( const char *name, int mode );

void* dlsym( void *handle, const char *name );

#endif


text:
`Abstract Factory`__
====================

Purpose
-------

To create series of related or dependent objects without specifying
their concrete classes. Usually the created classes all implement the
same interface. The client of the abstract factory does not care about
how these objects are created, he just knows how they go together.

UML Diagram
-----------

.. image:: uml/uml.png
   :alt: Alt AbstractFactory UML Diagram
   :align: center

Code
----

You can also find these code on `GitHub`_

AbstractFactory.php

.. literalinclude:: AbstractFactory.php
   :language: php
   :linenos:

JsonFactory.php

.. literalinclude:: JsonFactory.php
   :language: php
   :linenos:

HtmlFactory.php

.. literalinclude:: HtmlFactory.php
   :language: php
   :linenos:

MediaInterface.php

.. literalinclude:: MediaInterface.php
   :language: php
   :linenos:

Picture.php

.. literalinclude:: Picture.php
   :language: php
   :linenos:

Text.php

.. literalinclude:: Text.php
   :language: php
   :linenos:

Json/Picture.php

.. literalinclude:: Json/Picture.php
   :language: php
   :linenos:

Json/Text.php

.. literalinclude:: Json/Text.php
   :language: php
   :linenos:

Html/Picture.php

.. literalinclude:: Html/Picture.php
   :language: php
   :linenos:

Html/Text.php

.. literalinclude:: Html/Text.php
   :language: php
   :linenos:

Test
----

Tests/AbstractFactoryTest.php

.. literalinclude:: Tests/AbstractFactoryTest.php
   :language: php
   :linenos:

.. _`GitHub`: https://github.com/domnikl/DesignPatternsPHP/tree/master/Creational/AbstractFactory
.. __: http://en.wikipedia.org/wiki/Abstract_factory_pattern


text:
describe Dymos::Query::GetItem do

  describe 'build query' do
    let(:builder) { Dymos::Query::GetItem.new }

    subject { @client.get_item(builder.build).item }
    it do
      builder.name('Reply').key(Id: "DynamoDB#DynamoDB Thread 1", ReplyDateTime: "2011-12-18T00:40:57.165Z").attributes(:ReplyDateTime, "Message")

      is_expected.to eq({"ReplyDateTime" => "2011-12-18T00:40:57.165Z", "Message" => "DynamoDB Thread 1 Reply 1 text"})
    end
  end

end


text:
package org.chocosolver.solver.constraints.unary;

import org.chocosolver.solver.constraints.Propagator;
import org.chocosolver.solver.constraints.PropagatorPriority;
import org.chocosolver.solver.exception.ContradictionException;
import org.chocosolver.solver.learn.ExplanationForSignedClause;
import org.chocosolver.solver.learn.Implications;
import org.chocosolver.solver.variables.IntVar;
import org.chocosolver.solver.variables.events.IntEventType;
import org.chocosolver.util.ESat;
import org.chocosolver.util.objects.ValueSortedMap;
import org.chocosolver.util.objects.setDataStructures.iterable.IntIterableRangeSet;

/**
 * X <= C
 *

 *
 * @author Charles Prud'homme
 * @since 16/06/11
 */
public class PropLessOrEqualXC extends Propagator<IntVar> {

    private final int constant;

    public PropLessOrEqualXC(IntVar var, int cste) {
        super(new IntVar[]{var}, PropagatorPriority.UNARY, false, true);
        this.constant = cste;
    }

    @Override
    public int getPropagationConditions(int vIdx) {
        return IntEventType.boundAndInst();
    }

    @Override
    public void propagate(int evtmask) throws ContradictionException {
        // with views such as abs(...), the prop can be not entailed after initial propagation
        if (vars[0].updateUpperBound(constant, this) || vars[0].getUB() <= constant) {
            this.setPassive();
        }
    }

    @Override
    public ESat isEntailed() {
        if (vars[0].getUB() <= constant) {
            return ESat.TRUE;
        }
        if (vars[0].getLB() > constant) {
            return ESat.FALSE;
        }
        return ESat.UNDEFINED;
    }

    /**
     * @implSpec
     *

     *     Consider that v1 has been modified by propagation of this.
     *     Before the propagation, the domains were like:
     *

     *         (v1 ∈ D1)
     *

     * Then this propagates v1 ≤ c, then:
     *

     *         (v1 ∈ D1) → v1 ≤ c
     *

     * Converting to DNF:
     *

     *         (v1 ∈ (U \ D1) ∪ (-∞, c])
     *

     *

     */
    @Override
    public void explain(ExplanationForSignedClause explanation,
                        ValueSortedMap<IntVar> front,
                        Implications ig, int p) {
        IntIterableRangeSet set = explanation.getRootSet(vars[0]);
        set.retainBetween(IntIterableRangeSet.MIN, constant);
        explanation.addLiteral(vars[0], set, true);
    }

    @Override
    public String toString() {
        return vars[0].getName() + " <= " + constant;
    }

}


text:
<?php

namespace Drupal\Tests\menu_ui\Functional;

use Drupal\Tests\BrowserTestBase;
use Drupal\system\Entity\Menu;

/**
 * Tests that uninstalling menu does not remove custom menus.
 *
 * @group menu_ui
 */
class MenuUninstallTest extends BrowserTestBase {

  /**
   * Modules to enable.
   *
   * @var array
   */
  public static $modules = ['menu_ui'];

  /**
   * Tests Menu uninstall.
   */
  public function testMenuUninstall() {
    \Drupal::service('module_installer')->uninstall(['menu_ui']);

    \Drupal::entityManager()->getStorage('menu')->resetCache(['admin']);

    $this->assertTrue(Menu::load('admin'), 'The \'admin\' menu still exists after uninstalling Menu UI module.');
  }

}


text:
package resourcemanager

import (
	"fmt"
	"io/ioutil"
	"path"
	"sync"
	"time"

	"github.com/golang/protobuf/proto"
	"github.com/jlmucb/cloudproxy/go/tao"
)

func EncodeTime(t time.Time) (string, error) {
	const longForm = "2006-01-02T15:04:05.999999999Z07:00"
	return t.Format(longForm), nil
}

func DecodeTime(s string) (*time.Time, error) {
	const longForm = "2006-01-02T15:04:05.999999999Z07:00"
	tt, err := time.Parse(longForm, s)
	if err != nil {
		return nil, err
	}
	return &tt, nil
}

// MakeCombinedPrincipalFromOne
func MakeCombinedPrincipalFromOne(appPrincipal *PrincipalInfo) *CombinedPrincipal {
	cp := new(CombinedPrincipal)
	cp.Principals = append(cp.Principals, appPrincipal)
	return cp
}

// MakeCombinedPrincipalFromTwo
func MakeCombinedPrincipalFromTwo(appPrincipal *PrincipalInfo, userPrincipal *PrincipalInfo) *CombinedPrincipal {
	cp := new(CombinedPrincipal)
	cp.Principals = append(cp.Principals, appPrincipal)
	cp.Principals = append(cp.Principals, userPrincipal)
	return cp
}

func SameCombinedPrincipal(p1 CombinedPrincipal, p2 CombinedPrincipal) bool {
	if len(p1.Principals) != len(p2.Principals) {
		return false
	}
	for i := 0; i < len(p1.Principals); i++ {
		if *p1.Principals[i].Name != *p2.Principals[i].Name {
			return false
		}
	}
	return true
}

// Add Owner
func (info *ResourceInfo) AddOwner(p CombinedPrincipal, mutex *sync.RWMutex) error {
	if mutex != nil {
		mutex.Lock()
		defer mutex.Unlock()
	}
	info.Owners = append(info.Owners, &p)
	return nil
}

// Add Reader
func (info *ResourceInfo) AddReader(p CombinedPrincipal, mutex *sync.RWMutex) error {
	if mutex != nil {
		mutex.Lock()
		defer mutex.Unlock()
	}
	info.Readers = append(info.Readers, &p)
	return nil
}

// Add Writer
func (info *ResourceInfo) AddWriter(p CombinedPrincipal, mutex *sync.RWMutex) error {
	if mutex != nil {
		mutex.Lock()
		defer mutex.Unlock()
	}
	info.Writers = append(info.Writers, &p)
	return nil
}

// FindCombinedPrincipalPosition looks up the resource by its name and returns position in stack.
func FindCombinedPrincipalPosition(toFind CombinedPrincipal, cpList []*CombinedPrincipal) int {
	// No mutex is needed since enclosing function should lock.
	for i := 0; i < len(cpList); i++ {
		if SameCombinedPrincipal(toFind, *cpList[i]) {
			return i
		}
	}
	return -1
}
// TODO(jlm): add test
// Delete Owner
func (info *ResourceInfo) DeleteOwner(p CombinedPrincipal, mutex *sync.RWMutex) error {
	if mutex != nil {
		mutex.Lock()
		defer mutex.Unlock()
	}
	n := FindCombinedPrincipalPosition(p, info.Owners)
	if n < 0 {
		return nil
	}
	info.Owners[n] = info.Owners[len(info.Owners)-1]
	info.Owners = info.Owners[:len(info.Owners)-1]
	return nil
}
// TODO(jlm): add test
// Delete Reader
func (info *ResourceInfo) DeleteReader(p CombinedPrincipal, mutex *sync.RWMutex) error {
	if mutex != nil {
		mutex.Lock()
		defer mutex.Unlock()
	}
	n := FindCombinedPrincipalPosition(p, info.Readers)
	if n < 0 {
		return nil
	}
	info.Readers[n] = info.Readers[len(info.Readers)-1]
	info.Readers = info.Readers[:len(info.Readers)-1]
	return nil
}

// TODO(jlm): add test
// Delete Writer.
func (info *ResourceInfo) DeleteWriter(p CombinedPrincipal, mutex *sync.RWMutex) error {
	if mutex != nil {
		mutex.Lock()
		defer mutex.Unlock()
	}
	n := FindCombinedPrincipalPosition(p, info.Writers)
	if n < 0 {
		return nil
	}
	// TODO(jlm): add test
	info.Writers[n] = info.Writers[len(info.Owners)-1]
	info.Writers = info.Writers[:len(info.Owners)-1]
	return nil
}

// FindResource looks up the resource by its name.
func (m *ResourceMasterInfo) FindResource(resourceName string, mutex *sync.RWMutex) *ResourceInfo {
	if mutex != nil {
		mutex.Lock()
		defer mutex.Unlock()
	}
	for i := 0; i < len(m.Resources); i++ {
		if *m.Resources[i].Name == resourceName {
			return m.Resources[i]
		}
	}
	return nil
}

// InsertResource adds a resource.
func (m *ResourceMasterInfo) InsertResource(info *ResourceInfo, mutex *sync.RWMutex) error {
	if mutex != nil {
		mutex.Lock()
		defer mutex.Unlock()
	}
	l := m.FindResource(*info.Name, nil)
	if l != nil {
		return nil
	}
	m.Resources = append(m.Resources, info)
	return nil
}

// DeleteResource deletes a resource.
func (m *ResourceMasterInfo) DeleteResource(resourceName string, mutex *sync.RWMutex) error {
	if mutex != nil {
		mutex.Lock()
		defer mutex.Unlock()
	}
	return nil
}

func (p *PrincipalInfo) PrintPrincipal() {
	if p.Name == nil || p.Cert == nil {
		return
	}
	fmt.Printf("Name: %s\nCertificate: %x\n", *p.Name, p.Cert)
}

func (cp *CombinedPrincipal) PrintCombinedPrincipal() {
	if cp == nil {
		return
	}
	// principals
	for i := 0; i < len(cp.Principals); i++ {
		cp.Principals[i].PrintPrincipal()
	}
}

func PrintPrincipalList(pl []*CombinedPrincipal) {
	if pl == nil {
		fmt.Printf("Empty\n")
		return
	}
	for i := 0; i < len(pl); i++ {
		pl[i].PrintCombinedPrincipal()
		fmt.Printf("\n")
	}
}

// PrintResource prints a resource to the log.
func (r *ResourceInfo) PrintResource(directory string, printContents bool) {
	if r == nil {
		return
	}
	fmt.Printf("\n")
	if r.Name != nil {
		fmt.Printf("Name: %s\n", *r.Name)
	} else {
		fmt.Printf("Name: empty\n");
	}
	if r.Type!= nil {
	fmt.Printf("Type: %d, ", *r.Type)
	} else {
		fmt.Printf("Type: empty, ");
	}
	if r.Size!= nil {
		fmt.Printf("size: %d\n", *r.Size)
	} else {
		fmt.Printf("Size: empty\n");
	}
	if r.DateCreated != nil && r.DateModified != nil {
		fmt.Printf("Created: %s, modified: %s\n", *r.DateCreated, *r.DateModified)
	} else {
		fmt.Printf("Created adn Modified names are empty\n")
	}
	fmt.Printf("Owners: \n")
	PrintPrincipalList(r.Owners)
	fmt.Printf("Readers: \n")
	PrintPrincipalList(r.Readers)
	fmt.Printf("Writers:\n")
	PrintPrincipalList(r.Writers)
	if printContents {
		fileName := path.Join(directory, *r.Name)
		contents, err := r.Read(fileName)
		if err != nil {
			fmt.Printf("File: %s\n", contents)
		}
	}
	fmt.Printf("\n")
}

// PrintMaster prints the ResourceMaster into the log.
func (m *ResourceMasterInfo) PrintMaster(printResources bool) {
	fmt.Printf("ServiceName: %s\n", *m.ServiceName)
	fmt.Printf("BaseDirectoryName: %s\n", *m.BaseDirectoryName)
	fmt.Printf("PolicyCert: %s\n", m.PolicyCert)
	fmt.Printf("Number of resources: %d\n", len(m.Resources))
	if printResources {
		for i := 0; i < len(m.Resources); i++ {
			m.Resources[i].PrintResource(*m.BaseDirectoryName, true)
			fmt.Printf("\n")
		}
	}
}

// Read causes the bytes of the file to be decrypted and read to the message
// stream. By the time this function is called, the remote principal has already
// been authenticated and the operation has already been authorized.
func (r *ResourceInfo) Read(directory string) ([]byte, error) {
	var err error
	var out []byte
	filename := path.Join(directory, *r.Name)
	bytes_read, err := ioutil.ReadFile(filename)
	if err != nil {
		return nil, err
	}
	if len(r.Keys) >= 32 {
		out, err = tao.Unprotect(r.Keys, bytes_read)
	} else {
		out = bytes_read
	}
	size := int32(len(out))
	if err == nil {
		r.Size = &size
	}
	return out, err
}

// Write causes the bytes of the file to be encrypted and integrity-protected
// and written to disk as they are read from the MessageStream.
func (r *ResourceInfo) Write(directory string, fileContents []byte) error {
	filename := path.Join(directory, *r.Name)
	if len(r.Keys) >= 32 {
		// Encrypt
		encrypted, err := tao.Protect(r.Keys, fileContents)
		if err != nil {
		}
		err = ioutil.WriteFile(filename, encrypted, 0644)
		if err == nil {
			size := int32(len(fileContents))
			r.Size = &size
		}
		return err
	} else {
		err := ioutil.WriteFile(filename, fileContents, 0644)
		if err == nil {
			size := int32(len(fileContents))
			r.Size = &size
		}
		return err
	}
}

func ReadTable(table *ResourceMasterInfo, tableFileName string, fileSecrets []byte, mutex *sync.RWMutex) bool {
	if mutex != nil {
		mutex.Lock()
		defer mutex.Unlock()
	}
	encryptedTable, err := ioutil.ReadFile(tableFileName)
	if err == nil {
		serializedTable, err := tao.Unprotect(fileSecrets, encryptedTable)
		if err != nil {
			return false
		}
		err = proto.Unmarshal(serializedTable, table)
		if err != nil {
			return false
		}
	}
	return true
}

func SaveTable(table *ResourceMasterInfo, tableFileName string, fileSecrets []byte, mutex *sync.RWMutex) bool {
	if mutex != nil {
		mutex.Lock()
		defer mutex.Unlock()
	}
	serializedTable, err := proto.Marshal(table)
	if err != nil {
		return false
	}
	encryptedTable, err := tao.Protect(fileSecrets, serializedTable)
	if err != nil {
		return false
	}
	err = ioutil.WriteFile(tableFileName, encryptedTable, 0666)
	if err != nil {
		return false
	}
	return true
}


text:
// memory.c - Basic source for memory dependent actions

#include "memory.h"
#include "common.h"
#include "monitor.h"

extern u32int placement_address;

//###############################################
//#########   MEMORY PATTERN SETTINGS   #########

//######### Pattern start #######################
u32int pattern_start = 0x7fa0104;   // >128 MiB
//u32int pattern_start = 0x2000000; // 32 MiB
//u32int pattern_start = 0x4000000; // 64 MiB
//u32int pattern_start = 0x8000000; // 128 MiB
//u32int pattern_start = 0xF000000; // 240 MiB
//u32int pattern_start = 0x20000000; // 512 MiB
//u32int pattern_start = 0x10000000; // 1024 MiB

//######### Pattern size ########################
//u32int pattern_size = 8;
u32int pattern_size = 1048576;     // 1 million 4 byte values -> 4MiB
//u32int pattern_size = 10485760;  // 10 million 4 byte values -> 40MiB
//u32int pattern_size = 104857600; // 100 million 4 byte values -> 400MiB

/*
 * Function: memory_write_area
 * ------------------------------
 * Write specified memory area to the screen.
 *
 */
void memory_write_area(char *startp, char *endp)
{
  int counter = 0;
  char  *p = startp;

  // We set the placement address to the pattern_start
  placement_address = startp;

  monitor_write("\n start : ");
  monitor_write_hex(startp);
  monitor_write("\n end : ");
  monitor_write_hex(endp);
  monitor_write("\n------------------------ \n ");

  // Write pattern to memory
  u32int i;
  u32int printcount =0;
  while ( p <= endp )
    {
      // Write pattern to memory
      u32int physsl;
      u32int *al = (u32int*)kmalloc_int(4,0,&physsl);
      memset(al,0,sizeof(u32int));
      *al = 305419896; // 0x12345678

      // Print out current memory address
      // and flush caches to memory
      // print out current memory write
      monitor_write("\nWRITE a: ");
      monitor_write_hex(al);
      monitor_write("|     phys: ");
      monitor_write_hex(physsl);
      monitor_write("|     val: ");
      monitor_write_hex(*al);
      // flush caches
      asm volatile("wbinvd");

      p++;
    }
}

/*
 * Function: memory_read_area
 * ------------------------------
 * Print out specified memory area to the screen.
 *
 */
void memory_read_area(char *startp, char *endp)
{
  int counter = 0;
  char *p = startp;
  char *asc;

  monitor_write("\n start : ");
  monitor_write_hex(startp);
  monitor_write("\n end : ");
  monitor_write_hex(endp);
  monitor_write("\n------------------------ \n ");

  while ( p != endp )
    {
      if (counter == 0){
        // print ascii view before line wrap
        monitor_write("    ");
        monitor_write(asc);
        // reset the counter
        counter = 15;
        // wrap line
        monitor_write("\n");
        monitor_write_hex(p);
        monitor_write("  : ");
      }
      else {
        counter = counter-1;
      }
      asc = build_ascii(p,counter);
      monitor_write_hex_byte(*p++);
    }

    // fill remaining space between hex and ascii
    for (counter; counter != 0; counter--){
      monitor_write("  ");
    }
    // print ascii view
    monitor_write("    ");
    monitor_write(asc);
    monitor_write("\n");
}

/*
 * Function: memory_error_pattern
 * ------------------------------
 * Function calculates byte error rate for
 * defined memory area.
 *
 */
void memory_error_pattern()
{
    // Byte error counter
    u32int error = 0;
    // u32int pattern_start = 0x7fa0104;   // >128 MiB
    // u32int pattern_size = 8;
    u8int *pattern_start_byte = (u8int*)pattern_start;

    // For our test routines
    u32int j;
    u32int bc = 0;

    monitor_write("\n\n Read pattern \n ------------------ \n");
    for (j = 0; j < pattern_size*4; j++,bc++)
    {
      if (*pattern_start_byte!=0x99){
        error++;
      }
      if(bc>4096){
        monitor_write_hex_byte(*pattern_start_byte++);
        monitor_write(" | error count: ");
        monitor_write_dec(error);
        monitor_write(" / ");
        monitor_write_dec(j+1);
        monitor_write(" | error rate: ");
        monitor_write_dec(((error*100)/(j+1)));
        monitor_write("% \n");
        bc = 0;
      }
    }
    monitor_write("\n########################## FINISHED\n");
    monitor_write_hex_byte(*pattern_start_byte++);
    monitor_write(" | error count: ");
    monitor_write_dec(error);
    monitor_write(" / ");
    monitor_write_dec(j+1);
    monitor_write(" | error rate: ");
    monitor_write_dec(((error*100)/(j)));
    monitor_write("% \n");
    bc = 0;

}

/*
 * Function: memory_read_pattern
 * ------------------------------
 * Function reads fixed pattern from the memory.
 *
 */
void memory_read_pattern()
{
    u32int pattern_end = pattern_start + pattern_size;
    memory_read_area(pattern_start, pattern_end);
}

/*
 * Function: memory_write_pattern
 * ------------------------------
 * Function writes fixed pattern to the memory.
 * The write pattern is 0x999999.
 *
 */
void memory_write_pattern()
{
    // We set the placement address to the pattern_start
    placement_address = pattern_start;

    // Write a single byte sequence for test and visualisation purpose
    monitor_write("- kmalloc memory for u32int *a\n");
    u32int physs;
    u32int *a = (u32int*)kmalloc_int(4,0,&physs);
    memset(a,0,sizeof(u32int)); // check if needed
    monitor_write("- set value to 0x999999\n");
    *a = 2576980377;

    // Check the written bytes directly after write
    monitor_write("\n              a hex: ");
    monitor_write_hex(a);
    monitor_write("\n             *a hex: ");
    monitor_write_hex(*a);
    monitor_write("\n             *a dec: ");
    monitor_write_dec(*a);
    monitor_write("\n               phys: ");
    monitor_write_hex(physs);
    // flush caches
    asm volatile("wbinvd");
    monitor_write("\n#########################\n");
    monitor_write("access with ptr\n");
    u32int *ptr = (u32int*)pattern_start;
    monitor_write("\n ptr hex: ");
    monitor_write_hex((u32int*)ptr);
    monitor_write("\n*ptr dec \n");
    monitor_write_dec(*ptr);

    // Write pattern to memory
    u32int i;
    u32int printcount =0;
    for (i = 0; i < pattern_size; i++)
      {
        // Write pattern to memory
        u32int physsl;
        u32int *al = (u32int*)kmalloc_int(4,0,&physsl);
        memset(al,0,sizeof(u32int));
        *al = 2576980377;

        // Print out current memory address
        // and flush caches to memory
        if (printcount>64000) {
          printcount = 0;
          // print out current memory write
          monitor_write("\nWRITE a: ");
          monitor_write_hex(al);
          monitor_write("|     phys: ");
          monitor_write_hex(physsl);
          monitor_write("|     val: ");
          monitor_write_hex(*al);
          // flush caches
          asm volatile("wbinvd");
        }
        printcount++;
      }
}


text:
classdef DirectInputSource < SceneConfig.SourceBase & Parameterized

    %% -----------------------------------------------------------------------------------
    properties
    end

    %% -----------------------------------------------------------------------------------
    methods

        function obj = DirectInputSource( varargin )
            obj = obj@SceneConfig.SourceBase( varargin{:} );
        end
        %% -------------------------------------------------------------------------------

        function srcInstance = instantiate( obj )
            srcInstance = instantiate@SceneConfig.SourceBase( obj );
        end
        %% -------------------------------------------------------------------------------

        function e = isequal( obj1, obj2 )
            e = isequal@SceneConfig.SourceBase( obj1, obj2 );
        end
        %% -------------------------------------------------------------------------------

    end

end


text:
<?php

namespace Tests\App\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class UserControllerTest extends WebTestCase
{
    /**
     * @dataProvider urlProvider
     */
    public function testRoutes($url, $text, $selector)
    {
        $client = self::createClient();
        $crawler = $client->request('GET', $url);
        $this->assertTrue($client->getResponse()->isSuccessful());
        $this->assertContains($text, $crawler->filter($selector)->text());
    }

    //---------------------Data providers-----------------------

    public function urlProvider()
    {
        return array(
            array('en/me/recipes', 'My Recipes', '#main-container h1'),
            array('en/me/reviews', 'My Reviews', '#main-container h1'),
            //TODO Add a fixture to show a profile
        );
    }
}


text:
"""This file contains code used in "Think Stats",
by Allen B. Downey, available from greenteapress.com

Copyright 2010 Allen B. Downey
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
"""

import survey

# copying Mean from thinkstats.py so we don't have to deal with
# importing anything in Chapter 1

def Mean(t):
    """Computes the mean of a sequence of numbers.

    Args:
        t: sequence of numbers

    Returns:
        float
    """
    return float(sum(t)) / len(t)

def PartitionRecords(table):
    """Divides records into two lists: first babies and others.

    Only live births are included

    Args:
        table: pregnancy Table
    """
    firsts = survey.Pregnancies()
    others = survey.Pregnancies()

    for p in table.records:
        # skip non-live births
        if p.outcome != 1:
            continue

        if p.birthord == 1:
            firsts.AddRecord(p)
        else:
            others.AddRecord(p)

    return firsts, others

def Process(table):
    """Runs analysis on the given table.

    Args:
        table: table object
    """
    table.lengths = [p.prglength for p in table.records]
    table.n = len(table.lengths)
    table.mu = Mean(table.lengths)

def MakeTables(data_dir='.'):
    """Reads survey data and returns tables for first babies and others."""
    table = survey.Pregnancies()
    table.ReadRecords(data_dir)

    firsts, others = PartitionRecords(table)

    return table, firsts, others

def ProcessTables(*tables):
    """Processes a list of tables

    Args:
        tables: gathered argument tuple of Tuples
    """
    for table in tables:
        Process(table)

def Summarize(data_dir):
    """Prints summary statistics for first babies and others.

    Returns:
        tuple of Tables
    """
    table, firsts, others = MakeTables(data_dir)
    ProcessTables(firsts, others)

    print('Number of first babies', firsts.n)
    print('Number of others', others.n)

    mu1, mu2 = firsts.mu, others.mu

    print('Mean gestation in weeks:')
    print('First babies', mu1)
    print('Others', mu2)

    print('Difference in days', (mu1 - mu2) * 7.0)

def main(name, data_dir='res'):
    Summarize(data_dir)

if __name__ == '__main__':
    import sys
    main(*sys.argv)


text:
using System;

namespace TestFirst.Net.Performance
{
    public static class RunStrategies
    {
        public static IRunStrategy Fixed(int numRepeats)
        {
            return new FixedNumRunsStrategy(numRepeats);
        }

        public static IRunStrategy Time(TimeSpan time)
        {
            return new TimeBasedRunStrategy(time);
        }

        private class FixedNumRunsStrategy : IRunStrategy
        {
            private readonly int m_numTimesToRun;

            public FixedNumRunsStrategy(int numTimesToRun)
            {
                m_numTimesToRun = numTimesToRun;
            }

            public bool ShouldRun(int runNum)
            {
                return runNum <= m_numTimesToRun;
            }
        }

        private class TimeBasedRunStrategy : IRunStrategy
        {
            private readonly TimeSpan m_time;
            private DateTime? m_firstRunAt;

            public TimeBasedRunStrategy(TimeSpan time)
            {
                m_time = time;
            }

            public bool ShouldRun(int runNum)
            {
                if (m_firstRunAt == null)
                {
                    m_firstRunAt = DateTime.Now;
                    return true;
                }

                return DateTime.Now - m_firstRunAt <= m_time;
            }
        }
    }
}


text:
/**
 *
 * @author greg (at) myrobotlab.org
 *
 * This file is part of MyRobotLab (http://myrobotlab.org).
 *
 * MyRobotLab is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version (subject to the "Classpath" exception
 * as provided in the LICENSE.txt file that accompanied this code).
 *
 * MyRobotLab is distributed in the hope that it will be useful or fun,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * All libraries in thirdParty bundle are subject to their own license
 * requirements - please refer to http://myrobotlab.org/libraries for
 * details.
 *
 * Enjoy !
 *
 * */

package org.myrobotlab.service;

import java.util.Vector;

import org.myrobotlab.framework.MRLError;
import org.myrobotlab.framework.Service;
import org.myrobotlab.framework.Status;
import org.myrobotlab.logging.Level;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.logging.Logging;
import org.myrobotlab.logging.LoggingFactory;
import org.myrobotlab.serial.VirtualSerialPort;
import org.myrobotlab.service.interfaces.ServoControl;
import org.myrobotlab.service.interfaces.ServoController;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
import org.slf4j.Logger;

/**
 * @author GroG
 *
 *         Servos have both input and output. Input is usually of the range of
 *         integers between 0 - 180, and output can relay those values directly
 *         to the servo's firmware (Arduino ServoLib, I2C controller, etc)
 *
 *         However there can be the occasion that the input comes from a system
 *         which does not have the same range. Such that input can vary from 0.0
 *         to 1.0. For example, OpenCV coordinates are often returned in this
 *         range. When a mapping is needed Servo.map can be used. For this
 *         mapping Servo.map(0.0, 1.0, 0, 180) might be desired. Reversing input
 *         would be done with Servo.map(180, 0, 0, 180)
 *
 *         outputY - is the values sent to the firmware, and should not
 *         necessarily be confused with the inputX which is the input values
 *         sent to the servo
 *
 */
@Root
public class Servo extends Service implements ServoControl {

	private static final long serialVersionUID = 1L;

	public final static Logger log = LoggerFactory.getLogger(Servo.class);

	ServoController controller;

	private Float inputX;

	// clipping
	@Element
	private float outputYMin = 0;
	@Element
	private float outputYMax = 180;

	// range mapping
	@Element
	private float minX = 0;
	@Element
	private float maxX = 180;
	@Element
	private float minY = 0;
	@Element
	private float maxY = 180;

	@Element
	private int rest = 90;

	private long lastActivityTime = 0;

	/**
	 * the pin is a necessary part of servo - even though this is really
	 * controller's information a pin is a integral part of a "servo" - so it is
	 * beneficial to store it allowing a re-attach during runtime
	 *
	 * FIXME - not true - attach on the controller puts in the data - it should
	 * leave it even on a detach - a attach with pin should only replace it -
	 * that way pin does not need to be stored on the Servo
	 */
	private Integer pin;
	Vector<String> controllers;
	// computer thread based sweeping
	boolean isSweeping = false;

	// sweep types
	// TODO - computer implemented speed control (non-sweep)
	boolean speedControlOnUC = true;

	transient Thread sweeper = null;

	private boolean isAttached = false;
	private boolean inverted = false;

	public Servo(String n) {
		super(n);
		load();
		lastActivityTime = System.currentTimeMillis();
	}

	public void releaseService() {
		detach();
		super.releaseService();
	}

	@Override
	public boolean setController(ServoController controller) {
		if (controller == null) {
			error("setting null as controller");
			return false;
		}

		log.info(String.format("%s setController %s", getName(), controller.getName()));

		if (isAttached()) {
			warn("can not set controller %s when servo %s is attached", controller, getName());
			return false;
		}

		this.controller = controller;
		broadcastState();
		return true;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see org.myrobotlab.service.interfaces.ServoControl#setPin(int)
	 */
	@Override
	public boolean setPin(int pin) {
		log.info(String.format("setting %s pin to %d", getName(), pin));
		if (isAttached()) {
			warn("%s can not set pin %d when servo is attached", getName(), pin);
			return false;
		}
		this.pin = pin;
		broadcastState();
		return true;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * org.myrobotlab.service.interfaces.ServoControl#attach(java.lang.String,
	 * int)
	 */
	public boolean attach(String controller, Integer pin) {
		return attach((Arduino) Runtime.getService(controller), pin);
	}

	public boolean attach(Arduino controller, Integer pin) {
		setPin(pin);

		if (setController(controller)) {
			return attach();
		}

		return false;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see org.myrobotlab.service.interfaces.ServoControl#attach()
	 */
	public boolean attach() {
		lastActivityTime = System.currentTimeMillis();
		if (isAttached) {
			log.info(String.format("%s.attach() - already attached - detach first", getName()));
			return false;
		}

		if (controller == null) {
			error("no valid controller can not attach %s", getName());
			return false;
		}

		isAttached = controller.servoAttach(getName(), pin);

		if (isAttached) {
			// changed state
			broadcastState();
		}

		return isAttached;
	}

	public void setInverted(boolean invert) {
		if (!inverted && invert) {
			map(maxX, minX, minY, maxY);
			inverted = true;
		} else {
			inverted = false;
		}

	}

	public boolean isInverted() {
		return inverted;
	}

	public float getMinInput(){
		return minX;
	}

	public float getMaxInput(){
		return maxX;
	}

	public void map(float minX, float maxX, float minY, float maxY) {
		this.minX = minX;
		this.maxX = maxX;
		this.minY = minY;
		this.maxY = maxY;
		broadcastState();
	}

	public void map(int minX, int maxX, int minY, int maxY) {
		this.minX = minX;
		this.maxX = maxX;
		this.minY = minY;
		this.maxY = maxY;
		broadcastState();
	}

	public int calc(float s) {
		return Math.round(minY + ((s - minX) * (maxY - minY)) / (maxX - minX));
	}

	/**
	 * basic move command of the servo - usually is 0 - 180 valid range but can
	 * be adjusted and / or re-mapped with min / max and map commands
	 *
	 * TODO - moveToBlocking - blocks until servo sends "ARRIVED_TO_POSITION"
	 * response
	 */
	@Override
	public void moveTo(Integer pos) {
		if (controller == null) {
			error(String.format("%s's controller is not set", getName()));
			return;
		}

		inputX = pos.floatValue();

		// the magic mapping
		int outputY = calc(inputX);

		if (outputY > outputYMax || outputY < outputYMin) {
			warn(String.format("%s.moveTo(%d) out of range", getName(), (int) outputY));
			return;
		}

		// FIXME - currently their is no timerPosition
		// this could be gotten with 100 * outputY for some valid range
		log.info("servoWrite({})", outputY);
		controller.servoWrite(getName(), outputY);
		lastActivityTime = System.currentTimeMillis();

	}

	public void writeMicroseconds(Integer pos) {
		if (controller == null) {
			error(String.format("%s's controller is not set", getName()));
			return;
		}

		inputX = pos.floatValue();

		// the magic mapping
		int outputY = calc(inputX);

		if (outputY > outputYMax || outputY < outputYMin) {
			warn(String.format("%s.moveTo(%d) out of range", getName(), (int) outputY));
			return;
		}

		// FIXME - currently their is no timerPosition
		// this could be gotten with 100 * outputY for some valid range
		log.info("servoWrite({})", outputY);
		controller.servoWriteMicroseconds(getName(), outputY);
		lastActivityTime = System.currentTimeMillis();

	}

	public boolean isAttached() {
		return isAttached;
	}

	public void setMinMax(int min, int max) {
		outputYMin = min;
		outputYMax = max;
		broadcastState();
	}

	public Integer getMin() {
		return (int) outputYMin;
	}

	public Integer getMax() {
		return (int) outputYMax;
	}

	public Float getPosFloat() {
		return inputX;
	}

	public int getPos() {
		return Math.round(inputX);
	}

	public long getLastActivityTime() {
		return lastActivityTime;
	}

	@Override
	public String getDescription() {
		return "basic servo service";
	}

	/**
	 * Sweeper - TODO - should be implemented in the arduino code for smoother
	 * function
	 *
	 */
	public class Sweeper extends Thread {

		int min;
		int max;
		int delay; // depending on type - this is 2 different things COMPUTER
					// its ms delay - CONTROLLER its modulus loop count
		int step;

		public Sweeper(String name, int min, int max, int delay, int step) {
			super(String.format("%s.sweeper", name));
			this.min = min;
			this.max = max;
			this.delay = delay;
			this.step = step;
		}

		@Override
		public void run() {

			if (inputX == null) {
				inputX = (float) min;
			}

			isSweeping = true;

			try {
				while (isSweeping) {

					inputX += step;

					// switch directions
					if ((inputX <= min && step < 0) || (inputX >= max && step > 0)) {
						step = step * -1;
					}

					moveTo(inputX.intValue());
					Thread.sleep(delay);

				}

			} catch (Exception e) {
				isSweeping = false;
				if (e instanceof InterruptedException) {
					info("shutting down sweeper");
				} else {
					logException(e);
				}
			}
		}

	}

	public void sweep(int min, int max) {
		sweep(min, max, 1, 1);
	}

	// FIXME - is it really speed control - you don't currently thread for
	// factional speed values
	public void sweep(int min, int max, int delay, int step) {
		// CONTROLLER TYPE SWITCH
		if (speedControlOnUC) {
			controller.servoSweep(getName(), min, max, step); // delay & step
																// implemented
		} else {
			if (isSweeping) {
				stop();
			}

			sweeper = new Sweeper(getName(), min, max, delay, step);
			sweeper.start();
		}
	}

	public void sweep() {
		sweep(Math.round(minX), Math.round(maxX), 1, 1);
	}

	@Override
	public String getControllerName() {
		if (controller == null) {
			return null;
		}

		return controller.getName();
	}

	// FIXME - really this could be normalized...
	// attach / detach - the detach would not remove the ServoData from
	// the controller only another attach with a different pin would
	// change it
	@Override
	public Integer getPin() {
		/*
		 * valiant attempt of normalizing - but Servo needs to know its own pin
		 * to support attach()
		 *
		 * if (controller == null) { return null; }
		 *
		 * return controller.getServoPin(getName());
		 */
		return pin;
	}

	public void setSpeed(Float speed) {
		if (speed == null) {
			return;
		}

		if (controller == null) {
			error("setSpeed - controller not set");
			return;
		}
		controller.setServoSpeed(getName(), speed);
	}

	public boolean detach() {
		if (!isAttached) {
			log.info(String.format("%s.detach() - already detach - attach first", getName()));
			return false;
		}

		if (controller != null) {
			if (controller.servoDetach(getName())) {
				isAttached = false;
				// changed state
				broadcastState();
				return true;
			}
		}

		return false;
	}

	public Vector<String> refreshControllers() {
		controllers = Runtime.getServicesFromInterface(ServoController.class.getCanonicalName());
		return controllers;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see org.myrobotlab.service.interfaces.ServoControl#stopServo()
	 */
	@Override
	public void stop() {
		// stop sweeper thread if running
		isSweeping = false;
		sweeper = null;
		// send a stop to the uC
		controller.servoStop(getName());
	}

	public int setRest(int i) {
		rest = i;
		return rest;
	}

	public int getRest() {
		return rest;
	}

	public void rest() {
		moveTo(rest);
	}

	@Override
	public boolean setController(String controller) {

		ServoController sc = (ServoController) Runtime.getService(controller);
		if (sc == null) {
			return false;
		}

		return setController(sc);
	}

	public boolean setEventsEnabled(boolean b) {
		controller.setServoEventsEnabled(getName(), b);
		return b;
	}

	public void setSpeedControlOnUC(boolean b) {
		speedControlOnUC = b;
	}

	// uber good
	public Integer publishServoEvent(Integer position) {
		return position;
	}

	// uber good
	public void addServoEventListener(Service service) {
		addListener("publishServoEvent", service.getName(), "onServoEvent", Integer.class);
	}

	public Status test(String port, int pin) {
		Status status = null;

		try {

		super.test();

		// FIXME GSON or PYTHON MESSAGES

		boolean useGUI = false;
		boolean useVirtualPorts = false;
		boolean testBasicMoves = false;
		boolean testSweep = true;
		boolean testDetachReAttach = false;
		boolean testBlocking = false;

		if (useVirtualPorts) {
			// virtual testing
			VirtualSerialPort.createNullModemCable("COM15", "UART");
			Serial uart = (Serial) Runtime.start("uart", "Serial");
			uart.connect("UART");
		}

		// dependencies - hardware - servocontroll & servo & port
		// challenges - no "real" feedback - even with hardware (visual?
		// contact?)
		// without hardware - possible serial binary MRLFile comparison !

		// TODO - check if !headless
		if (useGUI) {
			Runtime.start("gui", "GUIService");
		}

		// step 1 - test for success
		// step 2 - test for failures & recovery
		String arduinoName = "arduino";
		int min = 10;
		int max = 170;

		int pause = 2000;

		// weird notation - but its nice when copying out
		// into some script or other code
		// also good to guarantee being started

		Servo servo = (Servo) Runtime.start(getName(), "Arduino");

		// TODO test errros on servo move before attach

		Arduino arduino = (Arduino) Runtime.start(arduinoName, "Arduino");
		arduino.connect(port);
		info("attaching to pin %d", pin);

		if (!servo.attach(arduino, pin)) {
			throw new MRLError("could not attach to arduino");
		}

		if (servo.getPin() != pin) {
			throw new MRLError("bad pin value");
		}

		Vector<String> controllers = servo.refreshControllers();
		if (controllers.size() != 1) {
			throw new MRLError("should be on controller");
		}

		servo.setMinMax(min, max);

		info("should not move");
		sleep(pause);
		servo.moveTo(min - 1);
		servo.moveTo(max + 1);

		if (testBasicMoves) {

			info("testing 10 speeds on uC");
			sleep(pause);
			// TODO - moveToBlocking or callback when
			// servo reaches position would be nice here !
			for (int i = 0; i < 10; ++i) {
				float newSpeed = 1.0f - ((float) i * 0.1f);
				info("moveTo(pos=%d) %03f speed ", min, newSpeed);
				servo.setSpeed(newSpeed);
				servo.moveTo(min);
				sleep(pause);
				info("moveTo(pos=%d) %03f speed ", max, newSpeed);
				servo.moveTo(max);
				sleep(pause);
			}
		}

		info("back to rest");
		servo.setSpeed(1.0f);
		servo.rest();

		servo.setEventsEnabled(true);

		if (testSweep) {

			servo.setSpeed(0.9f);
			servo.sweep(min, max, 30, 1);

			servo.setEventsEnabled(false);

			/*
			 *
			 * info("computer controlled sweep speed"); int newDelay; for (int i
			 * = 0; i < 10; ++i) { newDelay = i * 100 + 1; // FIXME - make GSON
			 * or PYTHON message output
			 * info("sweep (min=%d max=%d delay=%d step=%d )", min, max,
			 * newDelay, 1); servo.setSpeed(0.3f); servo.sweep(min, max,
			 * newDelay, 1); sleep(3 * pause); servo.stop(); servo.rest(); }
			 */

			info("uc controlled sweep speed");
			servo.stop();

			// TODO - test blocking ..
			servo.setSpeed(1.0f);

			servo.setSpeedControlOnUC(false);
			servo.sweep(min, max, 10, 1);
		}

		// TODO - detach - re-attach - detach (move) - re-attach - check for no
		// move !

		if (testDetachReAttach) {
			info("testing detach re-attach");
			servo.detach();
			sleep(pause);
			servo.attach();

			info("make sure we can move after a re-attach");
			// put in testMode - collect controller data

			servo.moveTo(min);
			sleep(pause);
			servo.moveTo(max);
		}

		info("test completed");
		} catch(Exception e){
			status.addError(e);
		}
		return status;
	}

	public static void main(String[] args) throws InterruptedException {

		LoggingFactory.getInstance().configure();
		LoggingFactory.getInstance().setLevel(Level.INFO);
		try {

			Servo servo = (Servo) Runtime.start("servo", "Servo");
			/*
			 * Arduino arduino = (Arduino) Runtime.start("arduino", "Arduino");
			 * servo.setSpeedControlOnUC(true);
			 * Serial.createNullModemCable("COM15", "UART");
			 */
			servo.test();
		} catch (Exception e) {
			Logging.logException(e);
		}

	}

}


text:
package ariba.ui.widgets;

import ariba.ui.aribaweb.core.AWComponent;
import ariba.ui.aribaweb.core.AWRequestContext;
import ariba.ui.widgets.ActionHandler;
import ariba.ui.widgets.ActionInterceptor;

public final class DialogPageWrapper extends AWComponent implements ActionInterceptor
{
    public final static ActionHandler DisabledActionHandler =
        new ActionHandler(false, true, null);

    /**
        Action interceptor interface
    */
    public ActionHandler overrideAction (String action,
                                         ActionHandler defaultHandler,
                                         AWRequestContext requestContext)
    {
        return DisabledActionHandler;
    }
}


text:
module Tracksperanto::ConstName
  module C
    def const_name
      to_s.split('::').pop
    end
  end

  def const_name
    self.class.const_name
  end

  def self.included(into)
    into.extend(C)
    super
  end
end


text:
package space.gatt.GasaiBot.commands.Admin;

import com.google.common.collect.Lists;
import de.btobastian.javacord.DiscordAPI;
import de.btobastian.javacord.entities.User;
import de.btobastian.javacord.entities.message.Message;
import de.btobastian.javacord.entities.message.MessageBuilder;
import de.btobastian.javacord.entities.message.MessageDecoration;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import space.gatt.GasaiBot.Main;
import space.gatt.JavacordCommander.MessageManager;
import space.gatt.JavacordCommander.Settings;
import space.gatt.JavacordCommander.annotations.*;
import space.gatt.JavacordCommander.annotations.*;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * Created by Zach G on 06-Apr-16.
 */

@Command("clearchat")
@Syntax("clearchat [amt] [users]")
@Usage("clearchat 1000 @Gatt @Mitch @Jack @Whoever @Else @You @Want")
@Permissions({"Bot Commander"})
@Description("Clears the channel of the last {amt} messages from {users}.")
@Group("Moderation")
@CommandSettings(deleteInitatingMsg = false, sendResponseViaPM = false)
public class ClearChat {

	@IMethod
	public static String command(DiscordAPI api, Message message, User user, String[] args) {
		try{
			final Message msgEdit = message.reply("***Running deletion task. Edit your original message to say `stop` to stop finding messages!***").get();
			return (String)api.getThreadPool().getExecutorService().submit((Runnable) () -> handleDelete(api, message, user, args, msgEdit)).get();
		}catch (Exception e){
			return "K";
		}
	}

	private static String handleDelete(DiscordAPI api, Message message, User user, String[] args, Message originalMessage){
		try{
			final Message msgEdit = message.reply("***Scanning for messages...***").get();
			MessageBuilder builder;
			int amt = 1000;
			if (args.length > 0) {
				int testAmt = -1;
				testAmt = Integer.parseInt(args[0]);
				if (testAmt != -1) {
					amt = testAmt;
				}
			}
			boolean target = false;
			if (message.getMentions().size() > 0) {
				target = true;
			}
			int foundAmt = 0;
			amt = amt + 2;
			List<Message> messages = new ArrayList<Message>();
			try {
				for (Message m : Lists.reverse(message.getChannelReceiver().getMessageHistory(1000).get().getMessagesSorted())) {
					if (message.getContent().equalsIgnoreCase("stop")){
						message.reply("Ok, cancelled!").get();
						break;
					}
					if (foundAmt < amt) {
						if (target) {
							if (message.getMentions().contains(m.getAuthor())) {
								messages.add(m);
								foundAmt++;
								msgEdit.edit("***Scanning for messages... Found `" + foundAmt + "` messages so far...***").get();
							}
						} else {
							messages.add(m);
							foundAmt++;
							msgEdit.edit("***Scanning for messages... Found `" + foundAmt + "` messages so far...***").get();
						}
					} else {
						break;
					}
				}
			} catch (ExecutionException | InterruptedException e) {
				builder = new MessageBuilder();
				builder.append("(OH NO! SOMETHING HAPPENED. PRINTING STACK TRACE!)").append(e.getStackTrace().toString());
			}
			for (Message m : messages){
				MessageManager.deleteMessage(message.getChannelReceiver(), m);
			}
			builder = new MessageBuilder();
			builder.append(Settings.getMsgStarter()).appendUser(message.getAuthor()).append(" Attempting to clear " + amt + " messages in this channel!").appendNewLine().appendDecoration(MessageDecoration.BOLD, "If no messages are being removed, either I don't have the correct permissions, or my Timer Task is broken!");
			msgEdit.delete().get();
			originalMessage.delete().get();
			return builder.build();
		}catch (Exception e){

			return "Error in try/catch";
		}
	}
}


text:
<!DOCTYPE html>

	<meta charset="UTF-8">
	<title>Day 2 | Make a deal</title>
	<link rel="stylesheet" href="css/day2.css">
	<link href='https://fonts.googleapis.com/css?family=Roboto:400,700' rel='stylesheet' type='text/css'>

You win :D

Take you awesome video :D

Play again?


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Reactive.Threading.Tasks;
using Toggl.iOS.Shared.Exceptions;
using Toggl.iOS.Shared.Models;
using Toggl.Networking;
using Toggl.Shared;
using Toggl.Shared.Models;
using System.Threading.Tasks;
using Toggl.iOS.Shared;
using Toggl.iOS.Shared.Analytics;

namespace Toggl.iOS.TimerWidgetExtension
{
    internal class NetworkingHandler
    {
        private readonly ITogglApi togglApi;

        public NetworkingHandler(ITogglApi togglApi)
        {
           Ensure.Argument.IsNotNull(togglApi, nameof(togglApi));

           this.togglApi = togglApi;
        }

        public async Task<ITimeEntry> StartTimeEntry(TimeEntry timeEntry)
        {
            try
            {
                var createdTimeEntry = await togglApi.TimeEntries
                    .Create(timeEntry)
                    .ConfigureAwait(false);

                SharedStorage.Instance.SetNeedsSync(true);
                SharedStorage.Instance.AddWidgetTrackingEvent(WidgetTrackingEvent.StartTimer());

                return createdTimeEntry;
            }
            catch (Exception e)
            {
                SharedStorage.Instance.AddWidgetTrackingEvent(WidgetTrackingEvent.Error(e.Message));
                throw;
            }
        }

        public async Task StopRunningTimeEntry()
        {
            try
            {
                await togglApi.TimeEntries
                    .GetAll()
                    .ToObservable()
                    .Select(getRunningTimeEntry)
                    .Select(stopTimeEntry)
                    .FirstAsync();

                SharedStorage.Instance.SetNeedsSync(true);
                SharedStorage.Instance.AddWidgetTrackingEvent(WidgetTrackingEvent.StopTimer());
            }
            catch (Exception e)
            {
                SharedStorage.Instance.AddWidgetTrackingEvent(WidgetTrackingEvent.Error(e.Message));
                throw;
            }
        }

        private async Task stopTimeEntry(ITimeEntry timeEntry)
        {
            var duration = (long)(DateTime.Now - timeEntry.Start).TotalSeconds;
            await togglApi.TimeEntries.Update(
                TimeEntry.From(timeEntry).With(duration)
            );
        }

        private ITimeEntry getRunningTimeEntry(IList<ITimeEntry> timeEntries)
            => timeEntries.FirstOrDefault(te => te.Duration == null) ?? throw new NoRunningEntryException();
    }
}


text:
<?php

namespace Yurun\Util\YurunHttp\Test\HttpRequestTest;

use Yurun\Util\HttpRequest;
use Yurun\Util\YurunHttp\ConnectionPool;
use Yurun\Util\YurunHttp\Handler\Swoole\SwooleHttpConnectionManager;
use Yurun\Util\YurunHttp\Test\BaseTest;
use Yurun\Util\YurunHttp\Test\Traits\TSwooleHandlerTest;

class SwoolePoolTest extends BaseTest
{
    use TSwooleHandlerTest;

    public function test()
    {
        $this->call(function () {
            // 启用连接池
            ConnectionPool::enable();

            try
            {
                // 为这个地址设置限制连接池连接数量3个
                // 一定不要有 / 及后续参数等
                $url = rtrim($this->host, '/');
                ConnectionPool::setConfig($url, 3);

                $http = new HttpRequest();
                $response = $http->get($this->host . '?a=info');
                $data = $response->json(true);
                $remote = isset($data['remote']) ? $data['remote'] : null;
                $this->assertNotNull($remote);

                $pool = SwooleHttpConnectionManager::getInstance()->getConnectionPool($url);
                $this->assertEquals(1, $pool->getCount());
                $this->assertEquals(1, $pool->getFree());
                $this->assertEquals(0, $pool->getUsed());

                $http = new HttpRequest();
                $response = $http->get($this->host . '?a=info');
                $data = $response->json(true);

                $this->assertEquals($remote, isset($data['remote']) ? $data['remote'] : null);

                $pool = SwooleHttpConnectionManager::getInstance()->getConnectionPool($url);
                $this->assertEquals(1, $pool->getCount());
                $this->assertEquals(1, $pool->getFree());
                $this->assertEquals(0, $pool->getUsed());
            }
            finally
            {
                ConnectionPool::disable();
            }
        });
    }
}


text:
source $HOME/.bin/ratLibrary.sh
# pick action based on incoming argument
case "$1" in

   "scan")
      scanAllGroups
   ;;

   "inc")
      changeToGroupNumber $(getNextGroupNumber)
   ;;

   "dec")
      changeToGroupNumber $(getPreviousGroupNumber)
   ;;

   "sendn")
      sendWindowToNextGroup
   ;;

   "sendp")
      sendWindowToPreviousGroup
   ;;

   "follown")
      followWindowToNextGroup
   ;;

   "followp")
      followWindowToPreviousGroup
   ;;

   "swap")
      swapScreens
   ;;

   *)
      echo "invalid option $1"
      exit 1;
   ;;
esac

return 0


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Annls mycol. 26: 433 (1928)

#### Original name
Melanops phyllachoroidis Syd.

### Remarks
null


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="EntryViewPreference">
        <attr name="text" format="string" />
        <attr name="textFont" format="string" />
        <attr name="initial" format="string" />
        <attr name="fontSize" format="float" />
    </declare-styleable>

    <declare-styleable name="FontSizePickerPreference">
        <attr name="min" format="integer" />
        <attr name="max" format="integer" />
    </declare-styleable>

    <declare-styleable name="NotificationTimePreference">
        <!--
        <attr name="from" format="integer" />
        <attr name="fromMinute" format="integer" />
        <attr name="toHour" format="integer" />
        <attr name="toMinute" format="integer"/>
        <attr name="setHour" format="integer"/>
        <attr name="setMinute" format="integer"/>
        -->
        <attr name="setTime" format="boolean" />
    </declare-styleable>

    <declare-styleable name="MultiSpinner">
        <attr name="android:entries" />
    </declare-styleable>

</resources>


text:
package enl.sif.codepoint;

public class CodePointType extends AccessType {
	public String toString() {
		return "CodePointType";
	}
}


text: ({"iframeEditTitle":"área de edición","iframeFocusTitle":"marco del área de edición"})


text:
package edu.wpi.first.wpilibj.templates;

import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.KinectStick;
import edu.wpi.first.wpilibj.buttons.Button;
import edu.wpi.first.wpilibj.buttons.JoystickButton;
import edu.wpi.first.wpilibj.templates.commands.DriveWithJoystick;
import edu.wpi.first.wpilibj.templates.commands.SnapShot;
import edu.wpi.first.wpilibj.templates.commands.ToggleBallPickerDown;
import edu.wpi.first.wpilibj.templates.commands.ToggleBallPickerUp;
import edu.wpi.first.wpilibj.templates.commands.ToggleShooterOn;

public class OI {
    // This is the singleton instance of the OI class.
    private static OI instance = null;

    // This is the port the joystick is plugged into.
    private static final int JOYSTICK_PORT = 1;

    // These constants map the joystick buttons to constants.
    private static final int PORT_SHOOTER        = 1;
    private static final int PORT_ARM_UP         = 3;
    private static final int PORT_ARM_DOWN       = 4;
    private static final int PORT_PICKER_UP      = 5;
    private static final int PORT_PICKER_DOWN    = 6;
    private static final int PORT_SNAPSHOT       = 8;

    // These are the objects that represent controlling the robot with a
    // joystick.
    private Joystick joystick;
    private Button ballPickerUpButton;
    private Button ballPickerDownButton;
    private Button shootButton;
    private Button takeSnapshotButton;
    private Button moveArmDownButton;
    private Button moveArmUpButton;
    private DriveWithJoystick drive;

    // These are the objects that represent controlling the robot with a
    // Kinect.
    private KinectStick leftArm;
    private KinectStick rightArm;

    public OI() {
        // Initialize the joystick, the buttons, and the mapping betwen buttons
        // and commands.
        joystick = new Joystick(JOYSTICK_PORT);

        // Map a joystick button to the ball picker up command.
        ballPickerUpButton = new JoystickButton(joystick, PORT_PICKER_UP);
        ballPickerUpButton.whenPressed(new ToggleBallPickerUp());

        // Map a joystick button to the ball picker down command.
        ballPickerDownButton = new JoystickButton(joystick, PORT_PICKER_DOWN);
        ballPickerDownButton.whenPressed(new ToggleBallPickerDown());

        // Map a joystick button to the shoot command.
        shootButton = new JoystickButton(joystick, PORT_SHOOTER);
        shootButton.whenPressed(new ToggleShooterOn());

        // Map a joystick button to take a snapshot with the camera command.
        takeSnapshotButton = new JoystickButton(joystick, PORT_SNAPSHOT);
        takeSnapshotButton.whenPressed(new SnapShot());

        // Map a joystick button to move the bridge manipulator down.
        //moveArmDownButton = new JoystickButton(joystick, PORT_ARM_DOWN);
        //moveArmDownButton.whenPressed(new MoveArmDown());

        // Map a joystick button to move the bridge manipulator up.
        //moveArmUpButton = new JoystickButton(joystick, PORT_ARM_UP);
        //moveArmUpButton.whenPressed(new MoveArmUp());

        // Initialize the controls for the Kinect to control the robot.
        leftArm = new KinectStick(1);
        rightArm = new KinectStick(2);
    }

    /**
     * Return the singleton instance of the Operator Interface class.
     */
    public static OI getInstance() {
        if (instance == null) {
            instance = new OI();
        }
        return instance;
    }

    /**
     * Get the joystick for this Operator Interface instance.
     * @return the joystick for this OI instance
     */
    public Joystick getJoystick() {
        return joystick;
    }

    /**
     * Get the left arm Kinect object for this Operator Interface instance.
     * @return the Kinect object for the left arm.
     */
    public KinectStick getLeftArm() {
        return leftArm;
    }

    /**
     * Get the right arm Kinect object for this Operator Interface instance.
     * @return the Kinect object for the right arm.
     */
    public KinectStick getRightArm() {
        return rightArm;
    }
}


text:
jmdict is a JMdict parser for Go. It uses the `encoding/xml` package included in the Go standard library.

This repository also includes the `jmdict/index` package, which provides some utilities for indexing the JMdict for quick searching.

## What is JMdict?
JMdict is a large machine-readable multilingual Japanese dictionary. The files are available from http://www.edrdg.org/jmdict/j_jmdict.html.

## To-do List
- Write tests and examples
- Clean up code in `jmdict/index`