text:
import json
import random
import re
from datetime import date
from textwrap import dedent

import requests
from discord import Embed

from musicbot.constants import VERSION as BOTVERSION
from musicbot.tungsten import Tungsten
from musicbot.utils import (Response, command_info, get_dev_version,
                            get_version_changelog, hex_to_dec, prettydate)

class InfoCommands:

    @command_info("1.9.5", 1477774380, {
        "3.4.5": (1497616203, "Improved default help message using embeds"),
        "3.6.0": (1497904733, "Fixed weird indent of some help texts"),
        "3.7.0": (1498233256, "Some better help texts"),
        "3.7.1": (1498237739, "Added interactive help"),
        "3.7.4": (1498318916, "Added \"lyrics\" function help text"),
        "4.2.2": (1500905513, "Updated help texts"),
        "4.6.0": (1502208273, "Added a missing comma so resume and volume don't show on the same line"),
        "4.7.2": (1503855125, "Updated command list")
    })
    async def cmd_help(self, channel, leftover_args):
        """
        ///|Usage
        `{command_prefix}help [command]`
        ///|Explanation
        Logs a help message.
        ///|Interactive
        `{command_prefix}help <query>`
        """
        command = None

        if len(leftover_args) > 0:
            command = " ".join(leftover_args)

        if command:
            cmd = getattr(self, "cmd_" + command, None)
            if cmd:
                documentation = cmd.__doc__.format(
                    command_prefix=self.config.command_prefix)
                em = Embed(title="**{}**".format(command.upper()))
                fields = documentation.split("///")
                if len(fields) < 2:  # backward compatibility
                    return Response(
                        "```\n{}```".format(dedent(cmd.__doc__).format(command_prefix=self.config.command_prefix)))

                for field in fields:
                    if field is None or field is "":
                        continue
                    inline = True
                    if field.startswith("(NL)"):
                        inline = False
                        field = field[4:]
                        # print(field)

                    match = re.match(r"\|(.+)\n((?:.|\n)+)", field)
                    if match is None:
                        continue
                    title, text = match.group(1, 2)

                    em.add_field(
                        name="**{}**".format(title), value=dedent(text), inline=inline)
                await self.send_message(channel, embed=em)
                return
            else:
                await self.send_typing(channel)
                params = {
                    "v": date.today().strftime("%d/%m/%y"),
                    "q": command}
                headers = {
                    "Authorization": "Bearer CU4UAUCKWN37QLXHMBOYZ425NOGBMIYK"}
                resp = requests.get("https://api.wit.ai/message",
                                    params=params, headers=headers)
                data = resp.json()
                entities = data["entities"]

                return Response("**This is still a work-in-progress**\n{}".format(json.dumps(entities, indent=4)))

        else:
            em = Embed(
                title="GIESELA HELP",
                url="http://gieseladev.github.io/Giesela/",
                colour=random.randint(0, 0xFFFFFF),
                description="Here are some of the most useful commands,\nYou can always use `{0}help <cmd>` to get more detailed information on a command".
                format(self.config.command_prefix)
            )

            music_commands = "\n".join([
                "`{0}play` play music",
                "`{0}search` search for music",
                "`{0}radio` listen to the best radio stations",
                "`{0}stream` enqueue a livestream",
                "`{0}spotify` spotify integration",
                "`{0}pause` pause playback",
                "`{0}resume` resume playback",
                "`{0}volume` change volume",
                "`{0}seek` seek to a timestamp",
                "`{0}fwd` forward time",
                "`{0}rwd` rewind time"
            ]).format(self.config.command_prefix)
            em.add_field(name="Music", value=music_commands, inline=False)

            queue_commands = "\n".join([
                "`{0}queue` show the queue",
                "`{0}history` show playback history",
                "`{0}np` more information on the current entry",
                "`{0}skip` skip to the next entry in queue",
                "`{0}replay` replay the current entry",
                "`{0}repeat` change repeat mode",
                "`{0}remove` remove entry from queue",
                "`{0}clear` remove all entries from queue",
                "`{0}shuffle` shuffle the queue",
                "`{0}promote` promote entry to front",
                "`{0}autoplay` when you're out of ideas just let Giesela choose"
            ]).format(self.config.command_prefix)
            em.add_field(name="Queue", value=queue_commands, inline=False)

            playlist_commands = "\n".join([
                "`{0}playlist` create/edit/list playlists",
                "`{0}addtoplaylist` add entry to playlist",
                "`{0}removefromplaylist` remove entry from playlist",
                "`{0}editentry` edit an entry from a playlist"
            ]).format(self.config.command_prefix)
            em.add_field(name="Playlist", value=playlist_commands, inline=False)

            misc_commands = "\n".join([
                "`{0}register` register your token in order to use [Webiesela](http://giesela.org)",
                "`{0}summon` summon her like the servant she is",
                "`{0}lyrics` retrieve lyrics for the current song",
                "`{0}random` choose between items",
                "`{0}game` play a game",
                "`{0}ask` ask a question",
                "`{0}c` chat with Giesela",
                "`{0}explode` explode a timestamp-entry into its sub-entries"
            ]).format(self.config.command_prefix)
            em.add_field(name="Misc", value=misc_commands, inline=False)

            return Response(embed=em)

    @command_info("1.9.5", 1477774380, {
        "3.6.1": (1497971656, "Fixed broken line wrap")
    })
    async def cmd_ask(self, author, channel, message, leftover_args):
        """
        ///|Usage
        `{command_prefix}ask <query>`
        ///|Explanation
        You can ask anything from science, maths, to culture
        """

        await self.send_typing(channel)
        msgContent = " ".join(leftover_args)

        col = random.randint(0, 0xFFFFFF)

        client = Tungsten("EH8PUT-67PJ967LG8")
        res = client.query(msgContent)
        if not res.success:
            await self.safe_send_message(
                channel,
                "Nothing found!"
            )

        for pod in res.pods:
            em = Embed(title=pod.title, colour=col)
            em.set_image(url=pod.format["img"][0]["url"])
            em.set_footer(text=pod.format["img"][0]["alt"])
            await self.send_message(channel, embed=em)

    @command_info("3.4.0", 1497533758, {
        "3.4.8": (1497650090, "When showing changelogs, two logs can't be on the same line anymore"),
        "4.1.4": (1500795125, "Displaying the timestamp in a better way.")
    })
    async def cmd_commandinfo(self, command):
        """
        ///|Usage
        `{command_prefix}commandinfo <command>`
        ///|Explanation
        More information on a command
        """

        c_info = getattr(self, "cmd_" + command, None)
        if not c_info:
            return Response(
                "Couldn't find a command called \"{}\"".format(command))

        try:
            em = Embed(title=command.upper(), colour=hex_to_dec("#ffd700"))
            em.add_field(
                name="Version `{}`".format(c_info.version),
                value="`{}`\nCommand has been added".format(
                    prettydate(c_info.timestamp)),
                inline=False)

            for cl in c_info.changelog:
                v, t, l = cl
                em.add_field(
                    name="Version `{}`".format(v),
                    value="`{}`\n{}".format(prettydate(t), l),
                    inline=False)

            return Response(embed=em)
        except:
            return Response(
                "Couldn't find any information on the `{}` command".format(
                    command))

    @command_info("3.5.6", 1497819288, {
        "3.6.2": (1497978696, "references are now clickable"),
        "3.7.6": (1498947694, "fixed a bug which would stop Giesela from executing the command because of underscores in the version name"),
        "4.0.8": (1500774499, "Handling special case of already being up to date"),
        "4.8.9": (1504368571, "Fixed documentation")
    })
    async def cmd_version(self, channel):
        """
        ///|Usage
        `{command_prefix}version`
        ///|Explanation
        Some more information about the current version and what's to come.
        """

        await self.send_typing(channel)
        v_code, v_name = BOTVERSION.split("_", 1)
        dev_code, dev_name = get_dev_version()
        if v_code == dev_code:
            changelog = "**Up to date!**"
        else:
            changelog = "**What's to come:**\n\n"
            changelog += "\n".join(
                "● " + l for l in get_version_changelog()
            )

        desc = "Current Version is `{}`\nDevelopment is at `{}`\n\n{}".format(
            BOTVERSION, dev_code + "_" + dev_name, changelog)[:2000]

        em = Embed(title="Version \"{}\"".format(v_name.replace("_", " ").title()), description=desc,
                   url="https://gieseladev.github.io/Giesela", colour=hex_to_dec("#67BE2E"))

        return Response(embed=em)


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

  <groupId>com.aperigeek.jlad</groupId>
  <artifactId>jlad</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>pom</packaging>

  <name>jlad</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <modules>
    <module>jlad-core</module>
    <module>jlad-trainers</module>
    <module>jlad-detector</module>
    <module>jlad-webapp</module>
  </modules>
</project>

redpajama_set_name: RedPajamaGithub


text:
PROFILE=$1
OKTA_HOME=~/src/okta-aws-cli-assume-role
CONFIG_HOME=~/.okta

if [ -z $PROFILE ]; then
	echo error - you mush specify a profile: awslogin.sh profilename
else
	FILENAME=$CONFIG_HOME/config.properties.$PROFILE
	if [ -f $FILENAME ]; then
		#echo $FILENAME
		rm -f $OKTA_HOME/out/config.properties
		ln -s $FILENAME $OKTA_HOME/out/config.properties
		cd $OKTA_HOME/out/
		java -classpath $OKTA_HOME/out/:$OKTA_HOME/out/oktaawscli.jar:$OKTA_HOME/lib/aws-java-sdk-1.11.135.jar com.okta.tools.awscli
	else
		echo "Error no file name $FILENAME exists.  Are you sure thats the right account name?"
	fi
fi


text:
package org.jetbrains.plugins.scala
package annotator
package template

import org.jetbrains.plugins.scala.annotator.element.ScTemplateDefinitionAnnotator
import org.jetbrains.plugins.scala.lang.psi.api.toplevel.typedef.ScTemplateDefinition

class UndefinedMemberTest extends AnnotatorTestBase[ScTemplateDefinition] {

  def testValidHolders(): Unit = {
    assertNothing(messages("class C { def f }"))
    assertNothing(messages("trait T { def f }"))
  }

  def testHolderNew(): Unit = {
    assertMatches(messages("new { def f }")) {
      case Error("def f", Message) :: Nil =>
    }

    assertMatches(messages("new Object { def f }")) {
      case Error("def f", Message) :: Nil =>
    }
  }

  def testHolderObject(): Unit = {
    assertMatches(messages("object O { def f }")) {
      case Error("def f", Message) :: Nil =>
    }

    assertMatches(messages("object O extends Object { def f }")) {
      case Error("def f", Message) :: Nil =>
    }
  }

  def testDeclarations(): Unit = {
    assertMatches(messages("new { def f }")) {
      case Error("def f", Message) :: Nil =>
    }
    assertMatches(messages("new { var v: Object }")) {
      case Error("var v: Object", Message) :: Nil =>
    }
    assertMatches(messages("new { type T }")) {
      case Nil =>
    }
    assertMatches(messages("object O { type T }")) {
      case Nil =>
    }
  }

  def testDefinitions(): Unit = {
    assertNothing(messages("new { def f = null }"))
    assertNothing(messages("new { var v: Object = null }"))
    assertNothing(messages("new { type T = Any }"))
  }

  override protected def annotate(element: ScTemplateDefinition)
                                 (implicit holder: ScalaAnnotationHolder): Unit =
    ScTemplateDefinitionAnnotator.annotateUndefinedMember(element)

  private val Message = ScalaBundle.message("illegal.undefined.member")
}


text:
'use strict';

// src\services\picture\hooks\write-to-disk.js
//
// Use this hook to manipulate incoming or outgoing data.
// For more information on hooks see: http://docs.feathersjs.com/hooks/readme.html

const fs = require('fs');
const path = require('path');
const mkdirp = require('mkdirp');

// const defaults = {};

module.exports = test => {
    // options = Object.assign({}, defaults, options);

    return hook => new Promise((resolve, reject) => {
        if (test && !test(hook)) {
            resolve(hook);
        }

        // Attempt to recursively make the images directory and all the path's subdirectories
        mkdirp(path.join(hook.app.get('nedb'), path.dirname(hook.data.path)), err => {
            if(err) {
                reject(err);
            }
            else {
                fs.writeFile(path.join(hook.app.get('nedb'), hook.data.path), hook.data.buffer, err => {
                    if (err) {
                        reject(err);
                    }
                    else {
                        resolve(hook);
                    }
                });
            }
        });
    });
};


text:
// MESSAGE ENCAPSULATED_DATA PACKING

#define MAVLINK_MSG_ID_ENCAPSULATED_DATA 171

typedef struct __mavlink_encapsulated_data_t
{
	uint16_t seqnr; ///< sequence number (starting with 0 on every transmission)
	uint8_t data[253]; ///< image data bytes

} mavlink_encapsulated_data_t;

#define MAVLINK_MSG_ENCAPSULATED_DATA_FIELD_DATA_LEN 253

/**
 * @brief Pack a encapsulated_data message
 * @param system_id ID of this system
 * @param component_id ID of this component (e.g. 200 for IMU)
 * @param msg The MAVLink message to compress the data into
 *
 * @param seqnr sequence number (starting with 0 on every transmission)
 * @param data image data bytes
 * @return length of the message in bytes (excluding serial stream start sign)
 */
static inline uint16_t mavlink_msg_encapsulated_data_pack(uint8_t system_id, uint8_t component_id, mavlink_message_t* msg, uint16_t seqnr, const uint8_t* data)
{
	uint16_t i = 0;
	msg->msgid = MAVLINK_MSG_ID_ENCAPSULATED_DATA;

	i += put_uint16_t_by_index(seqnr, i, msg->payload); // sequence number (starting with 0 on every transmission)
	i += put_array_by_index((const int8_t*)data, sizeof(uint8_t)*253, i, msg->payload); // image data bytes

	return mavlink_finalize_message(msg, system_id, component_id, i);
}

/**
 * @brief Pack a encapsulated_data message
 * @param system_id ID of this system
 * @param component_id ID of this component (e.g. 200 for IMU)
 * @param chan The MAVLink channel this message was sent over
 * @param msg The MAVLink message to compress the data into
 * @param seqnr sequence number (starting with 0 on every transmission)
 * @param data image data bytes
 * @return length of the message in bytes (excluding serial stream start sign)
 */
static inline uint16_t mavlink_msg_encapsulated_data_pack_chan(uint8_t system_id, uint8_t component_id, uint8_t chan, mavlink_message_t* msg, uint16_t seqnr, const uint8_t* data)
{
	uint16_t i = 0;
	msg->msgid = MAVLINK_MSG_ID_ENCAPSULATED_DATA;

	i += put_uint16_t_by_index(seqnr, i, msg->payload); // sequence number (starting with 0 on every transmission)
	i += put_array_by_index((const int8_t*)data, sizeof(uint8_t)*253, i, msg->payload); // image data bytes

	return mavlink_finalize_message_chan(msg, system_id, component_id, chan, i);
}

/**
 * @brief Encode a encapsulated_data struct into a message
 *
 * @param system_id ID of this system
 * @param component_id ID of this component (e.g. 200 for IMU)
 * @param msg The MAVLink message to compress the data into
 * @param encapsulated_data C-struct to read the message contents from
 */
static inline uint16_t mavlink_msg_encapsulated_data_encode(uint8_t system_id, uint8_t component_id, mavlink_message_t* msg, const mavlink_encapsulated_data_t* encapsulated_data)
{
	return mavlink_msg_encapsulated_data_pack(system_id, component_id, msg, encapsulated_data->seqnr, encapsulated_data->data);
}

/**
 * @brief Send a encapsulated_data message
 * @param chan MAVLink channel to send the message
 *
 * @param seqnr sequence number (starting with 0 on every transmission)
 * @param data image data bytes
 */
#ifdef MAVLINK_USE_CONVENIENCE_FUNCTIONS

static inline void mavlink_msg_encapsulated_data_send(mavlink_channel_t chan, uint16_t seqnr, const uint8_t* data)
{
	mavlink_message_t msg;
	mavlink_msg_encapsulated_data_pack_chan(mavlink_system.sysid, mavlink_system.compid, chan, &msg, seqnr, data);
	mavlink_send_uart(chan, &msg);
}

#endif
// MESSAGE ENCAPSULATED_DATA UNPACKING

/**
 * @brief Get field seqnr from encapsulated_data message
 *
 * @return sequence number (starting with 0 on every transmission)
 */
static inline uint16_t mavlink_msg_encapsulated_data_get_seqnr(const mavlink_message_t* msg)
{
	generic_16bit r;
	r.b[1] = (msg->payload)[0];
	r.b[0] = (msg->payload)[1];
	return (uint16_t)r.s;
}

/**
 * @brief Get field data from encapsulated_data message
 *
 * @return image data bytes
 */
static inline uint16_t mavlink_msg_encapsulated_data_get_data(const mavlink_message_t* msg, uint8_t* r_data)
{

	memcpy(r_data, msg->payload+sizeof(uint16_t), sizeof(uint8_t)*253);
	return sizeof(uint8_t)*253;
}

/**
 * @brief Decode a encapsulated_data message into a struct
 *
 * @param msg The message to decode
 * @param encapsulated_data C-struct to decode the message contents into
 */
static inline void mavlink_msg_encapsulated_data_decode(const mavlink_message_t* msg, mavlink_encapsulated_data_t* encapsulated_data)
{
	encapsulated_data->seqnr = mavlink_msg_encapsulated_data_get_seqnr(msg);
	mavlink_msg_encapsulated_data_get_data(msg, encapsulated_data->data);
}


text:
#pragma once

#include "CX/Platform.hpp"

#if defined(CX_OS_ANDROID)

#include "CX/Types.hpp"
#include "CX/Status.hpp"
#include "CX/APIDefs.hpp"

namespace CX
{

namespace Sys
{

class CX_API Process
{
public:

	typedef UInt64    ID;

	static ID GetCurrentProcessID();

	static Status GetCurrentProcessPath(String &sPath);

	static Status GetCurrentProcessDir(String &sDir);

private:

	Process();

	~Process();

};

}//namespace Sys

}//namespace CX

#endif


text:
'Copyright 2019 Esri

'Licensed under the Apache License, Version 2.0 (the "License");
'you may not use this file except in compliance with the License.
'You may obtain a copy of the License at

'    http://www.apache.org/licenses/LICENSE-2.0

'Unless required by applicable law or agreed to in writing, software
'distributed under the License is distributed on an "AS IS" BASIS,
'WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

'See the License for the specific language governing permissions and
'limitations under the License.
Imports Microsoft.VisualBasic
Imports System
Imports System.Collections.Generic
Imports System.Text
Imports System.IO
Imports System.Runtime.Serialization.Formatters.Binary
Imports System.Runtime.Serialization
Imports System.Collections
Imports System.Reflection
Namespace PersistExtensionAddIn
  Public Class LogExtension
	  Inherits ESRI.ArcGIS.Desktop.AddIns.Extension
	Private _log As Dictionary(Of String, String)

	Public Sub New()
	End Sub

	Protected Overrides Sub OnStartup()
	  WireDocumentEvents()
	End Sub

	Private Sub WireDocumentEvents()
	  ' Named event handler
	  AddHandler ArcMap.Events.OpenDocument, AddressOf Events_OpenDocument
	End Sub

	Private Sub Events_OpenDocument()
	  Dim logText As String = "Document was saved by " & _log("userName") & " at " & _log("time")
	  LogMessage(logText)
	End Sub

	'Get called when saving document.
	Protected Overrides Sub OnSave(ByVal outStrm As Stream)
            ' Override OnSave and uses a binary formatter to serialize the log.
	  Dim log As New Dictionary(Of String, String)()
	  log.Add("userName", Environment.UserName)
	  log.Add("time", DateTime.Now.ToLongTimeString())
	  Dim bf = New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter()
	  bf.Serialize(outStrm, log)
	End Sub

	'Get called when opening a document with persisted stream.
	Protected Overrides Sub OnLoad(ByVal inStrm As Stream)
            ' Override OnLoad and uses a binary formatter to deserialize the log.
	  Dim bf = New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter()
	  _log = CType(bf.Deserialize(inStrm), Dictionary(Of String, String))
	End Sub

	Private Sub LogMessage(ByVal message As String)
	  System.Windows.Forms.MessageBox.Show(message)
	End Sub
  End Class

End Namespace


text:
var TextFieldSearchOption = function(displayName, fieldName) {
	var self = this;

	self.displayName = displayName;

	function isSingleValueMatch(value, searchText) {
		switch(typeof(value)) {
			case 'number':
				if(value === parseInt(searchText, 10))
					return true;
				break;
			case 'string':
				if(value.toLowerCase().indexOf(searchText.toLowerCase()) >= 0)
					return true;
				break;
			case 'object':
				var isSubMatch = false;
				_.each(value, function(arrayItem) {
					if(isSingleValueMatch(arrayItem, searchText)) {
						isSubMatch = true;
						return false;
					}
					return true;
				});
				return isSubMatch;
		}
		return false;
	}

	self.isMatch = function(addable, searchCriteria) {
		var isTextMatch = isSingleValueMatch(addable[fieldName], searchCriteria.searchText());
		return searchCriteria.isIs() ? isTextMatch : !isTextMatch;
	};
};


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;

namespace NoSqlBenchLib.Tests.TestHelpers
{
    public class SelfHostServerTestController : ApiController
    {
        [HttpGet]
        public string EchoString()
        {
            return "echoString";
        }

        [HttpGet]
        public HttpResponseMessage EchoStream()
        {
            return new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StreamContent(new MemoryStream(Encoding.UTF8.GetBytes("echoStream")))
            };
        }

        /*
        [HttpGet]
        public HttpResponseMessage ThrowBeforeTask()
        {
            return new HttpResponseMessage(HttpStatusCode.OK)
            {
                RequestMessage = Request,
                Content = new HttpSelfHostServerTest.ThrowsBeforeTaskObjectContent()
            };
        }

        [HttpGet]
        public HttpResponseMessage ThrowBeforeWrite()
        {
            return new HttpResponseMessage(HttpStatusCode.OK)
            {
                RequestMessage = Request,
                Content = new HttpSelfHostServerTest.ThrowBeforeWriteObjectContent()
            };
        }

        [HttpGet]
        public HttpResponseMessage ThrowAfterWrite()
        {
            return new HttpResponseMessage(HttpStatusCode.OK)
            {
                RequestMessage = Request,
                Content = new HttpSelfHostServerTest.ThrowAfterWriteObjectContent()
            };
        }

        [HttpGet]
        public HttpResponseMessage ThrowBeforeWriteStream()
        {
            return new HttpResponseMessage(HttpStatusCode.OK)
            {
                RequestMessage = Request,
                Content = new HttpSelfHostServerTest.ThrowBeforeWriteStream()
            };
        }

        [HttpGet]
        public HttpResponseMessage ThrowAfterWriteStream()
        {
            return new HttpResponseMessage(HttpStatusCode.OK)
            {
                RequestMessage = Request,
                Content = new HttpSelfHostServerTest.ThrowAfterWriteStream()
            };
        }
         * */
    }
}


text:
<?php

namespace App\Base\Console;

use Illuminate\Console\Scheduling\Schedule;
use App\Base\Console\Commands\PluginInstallCommand;
use App\Base\Console\Commands\PluginDiscoverCommand;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        PluginDiscoverCommand::class,
        PluginInstallCommand::class,
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        // $schedule->command('inspire')
        //          ->hourly();
    }

    /**
     * Register the Closure based commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        require base_path('routes/console.php');
        $this->load(__DIR__ . '/Commands');
    }
}


text:
using MatterHackers.Agg;
using MatterHackers.Agg.UI;

namespace MatterHackers.MatterControl.ConfigurationPage
{
	public class ThemePreviewButton : GuiWidget
	{
		private GuiWidget accentColor;
		private GuiWidget secondaryBackground;
		private GuiWidget tertiaryBackground;
		private GuiWidget icon1;
		private GuiWidget icon2;
		private GuiWidget icon3;

		public ThemePreviewButton(ThemeSet themeSet, ThemeColorPanel themeColorPanel)
		{
			this.ThemeSet = themeSet;

			var theme = themeSet.Theme;

			var primaryAccentColor = theme.PrimaryAccentColor;

			this.Padding = 8;
			this.BackgroundColor = theme.BackgroundColor;
			this.Cursor = Cursors.Hand;

			secondaryBackground = new GuiWidget()
			{
				HAnchor = HAnchor.Absolute | HAnchor.Left,
				VAnchor = VAnchor.Stretch,
				Margin = new BorderDouble(0),
				Width = 20 * GuiWidget.DeviceScale,
				BackgroundColor = theme.MinimalShade,
			};
			this.AddChild(secondaryBackground);

			accentColor = new GuiWidget()
			{
				HAnchor = HAnchor.Stretch,
				VAnchor = VAnchor.Absolute | VAnchor.Top,
				Height = 6 * GuiWidget.DeviceScale,
				Margin = new BorderDouble(left: 25),
				BackgroundColor = primaryAccentColor,
			};
			this.AddChild(accentColor);

			icon1 = new GuiWidget()
			{
				HAnchor = HAnchor.Absolute | HAnchor.Left,
				VAnchor = VAnchor.Absolute | VAnchor.Top,
				Height = 8 * GuiWidget.DeviceScale,
				Width = 8 * GuiWidget.DeviceScale,
				Margin = new BorderDouble(left: 6, top: 6),
				BackgroundColor = primaryAccentColor,
			};
			this.AddChild(icon1);

			icon2 = new GuiWidget()
			{
				HAnchor = HAnchor.Absolute | HAnchor.Left,
				VAnchor = VAnchor.Absolute | VAnchor.Top,
				Height = 8 * GuiWidget.DeviceScale,
				Width = 8 * GuiWidget.DeviceScale,
				Margin = new BorderDouble(left: 6, top: 20),
				BackgroundColor = primaryAccentColor,
			};
			this.AddChild(icon2);

			icon3 = new GuiWidget()
			{
				HAnchor = HAnchor.Absolute | HAnchor.Left,
				VAnchor = VAnchor.Absolute | VAnchor.Top,
				Height = 8 * GuiWidget.DeviceScale,
				Width = 8 * GuiWidget.DeviceScale,
				Margin = new BorderDouble(left: 6, top: 34),
				BackgroundColor = primaryAccentColor,
			};
			this.AddChild(icon3);

			tertiaryBackground = new GuiWidget()
			{
				HAnchor = HAnchor.Stretch,
				VAnchor = VAnchor.Absolute | VAnchor.Top,
				Height = 37 * GuiWidget.DeviceScale,
				Margin = new BorderDouble(left: 25, top: 12),
				BackgroundColor = theme.SlightShade,
			};
			this.AddChild(tertiaryBackground);

			var overlay = new GuiWidget
			{
				VAnchor = VAnchor.Stretch,
				HAnchor = HAnchor.Stretch,
				Cursor = Cursors.Hand
			};
			overlay.Click += (s, e) =>
			{
				// Activate the theme
				themeColorPanel.SetThemeColor(this.ThemeSet, primaryAccentColor, this.Mode);

				// Disable further theme clicks until reload completes
				themeColorPanel.Enabled = false;
			};

			this.AddChild(overlay);
		}

		public ThemeSet ThemeSet { get; }

		public string Mode { get; internal set; }

		public void PreviewThemeColor(Color sourceColor)
		{
			var adjustedAccentColor = sourceColor;

			accentColor.BackgroundColor = adjustedAccentColor;
			icon1.BackgroundColor = adjustedAccentColor;
			icon2.BackgroundColor = adjustedAccentColor;
			icon3.BackgroundColor = adjustedAccentColor;
		}
	}
}


text:
#include <aws/s3control/model/S3ObjectMetadata.h>
#include <aws/core/utils/xml/XmlSerializer.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>

#include <utility>

using namespace Aws::Utils::Xml;
using namespace Aws::Utils;

namespace Aws
{
namespace S3Control
{
namespace Model
{

S3ObjectMetadata::S3ObjectMetadata() :
    m_cacheControlHasBeenSet(false),
    m_contentDispositionHasBeenSet(false),
    m_contentEncodingHasBeenSet(false),
    m_contentLanguageHasBeenSet(false),
    m_userMetadataHasBeenSet(false),
    m_contentLength(0),
    m_contentLengthHasBeenSet(false),
    m_contentMD5HasBeenSet(false),
    m_contentTypeHasBeenSet(false),
    m_httpExpiresDateHasBeenSet(false),
    m_requesterCharged(false),
    m_requesterChargedHasBeenSet(false),
    m_sSEAlgorithm(S3SSEAlgorithm::NOT_SET),
    m_sSEAlgorithmHasBeenSet(false)
{
}

S3ObjectMetadata::S3ObjectMetadata(const XmlNode& xmlNode) :
    m_cacheControlHasBeenSet(false),
    m_contentDispositionHasBeenSet(false),
    m_contentEncodingHasBeenSet(false),
    m_contentLanguageHasBeenSet(false),
    m_userMetadataHasBeenSet(false),
    m_contentLength(0),
    m_contentLengthHasBeenSet(false),
    m_contentMD5HasBeenSet(false),
    m_contentTypeHasBeenSet(false),
    m_httpExpiresDateHasBeenSet(false),
    m_requesterCharged(false),
    m_requesterChargedHasBeenSet(false),
    m_sSEAlgorithm(S3SSEAlgorithm::NOT_SET),
    m_sSEAlgorithmHasBeenSet(false)
{
  *this = xmlNode;
}

S3ObjectMetadata& S3ObjectMetadata::operator =(const XmlNode& xmlNode)
{
  XmlNode resultNode = xmlNode;

  if(!resultNode.IsNull())
  {
    XmlNode cacheControlNode = resultNode.FirstChild("CacheControl");
    if(!cacheControlNode.IsNull())
    {
      m_cacheControl = Aws::Utils::Xml::DecodeEscapedXmlText(cacheControlNode.GetText());
      m_cacheControlHasBeenSet = true;
    }
    XmlNode contentDispositionNode = resultNode.FirstChild("ContentDisposition");
    if(!contentDispositionNode.IsNull())
    {
      m_contentDisposition = Aws::Utils::Xml::DecodeEscapedXmlText(contentDispositionNode.GetText());
      m_contentDispositionHasBeenSet = true;
    }
    XmlNode contentEncodingNode = resultNode.FirstChild("ContentEncoding");
    if(!contentEncodingNode.IsNull())
    {
      m_contentEncoding = Aws::Utils::Xml::DecodeEscapedXmlText(contentEncodingNode.GetText());
      m_contentEncodingHasBeenSet = true;
    }
    XmlNode contentLanguageNode = resultNode.FirstChild("ContentLanguage");
    if(!contentLanguageNode.IsNull())
    {
      m_contentLanguage = Aws::Utils::Xml::DecodeEscapedXmlText(contentLanguageNode.GetText());
      m_contentLanguageHasBeenSet = true;
    }
    XmlNode userMetadataNode = resultNode.FirstChild("UserMetadata");

    if(!userMetadataNode.IsNull())
    {
      XmlNode userMetadataEntry = userMetadataNode.FirstChild("entry");
      while(!userMetadataEntry.IsNull())
      {
        XmlNode keyNode = userMetadataEntry.FirstChild("key");
        XmlNode valueNode = userMetadataEntry.FirstChild("value");
        m_userMetadata[keyNode.GetText()] =
            valueNode.GetText();
        userMetadataEntry = userMetadataEntry.NextNode("entry");
      }

      m_userMetadataHasBeenSet = true;
    }
    XmlNode contentLengthNode = resultNode.FirstChild("ContentLength");
    if(!contentLengthNode.IsNull())
    {
      m_contentLength = StringUtils::ConvertToInt64(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(contentLengthNode.GetText()).c_str()).c_str());
      m_contentLengthHasBeenSet = true;
    }
    XmlNode contentMD5Node = resultNode.FirstChild("ContentMD5");
    if(!contentMD5Node.IsNull())
    {
      m_contentMD5 = Aws::Utils::Xml::DecodeEscapedXmlText(contentMD5Node.GetText());
      m_contentMD5HasBeenSet = true;
    }
    XmlNode contentTypeNode = resultNode.FirstChild("ContentType");
    if(!contentTypeNode.IsNull())
    {
      m_contentType = Aws::Utils::Xml::DecodeEscapedXmlText(contentTypeNode.GetText());
      m_contentTypeHasBeenSet = true;
    }
    XmlNode httpExpiresDateNode = resultNode.FirstChild("HttpExpiresDate");
    if(!httpExpiresDateNode.IsNull())
    {
      m_httpExpiresDate = DateTime(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(httpExpiresDateNode.GetText()).c_str()).c_str(), Aws::Utils::DateFormat::ISO_8601);
      m_httpExpiresDateHasBeenSet = true;
    }
    XmlNode requesterChargedNode = resultNode.FirstChild("RequesterCharged");
    if(!requesterChargedNode.IsNull())
    {
      m_requesterCharged = StringUtils::ConvertToBool(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(requesterChargedNode.GetText()).c_str()).c_str());
      m_requesterChargedHasBeenSet = true;
    }
    XmlNode sSEAlgorithmNode = resultNode.FirstChild("SSEAlgorithm");
    if(!sSEAlgorithmNode.IsNull())
    {
      m_sSEAlgorithm = S3SSEAlgorithmMapper::GetS3SSEAlgorithmForName(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(sSEAlgorithmNode.GetText()).c_str()).c_str());
      m_sSEAlgorithmHasBeenSet = true;
    }
  }

  return *this;
}

void S3ObjectMetadata::AddToNode(XmlNode& parentNode) const
{
  Aws::StringStream ss;
  if(m_cacheControlHasBeenSet)
  {
   XmlNode cacheControlNode = parentNode.CreateChildElement("CacheControl");
   cacheControlNode.SetText(m_cacheControl);
  }

  if(m_contentDispositionHasBeenSet)
  {
   XmlNode contentDispositionNode = parentNode.CreateChildElement("ContentDisposition");
   contentDispositionNode.SetText(m_contentDisposition);
  }

  if(m_contentEncodingHasBeenSet)
  {
   XmlNode contentEncodingNode = parentNode.CreateChildElement("ContentEncoding");
   contentEncodingNode.SetText(m_contentEncoding);
  }

  if(m_contentLanguageHasBeenSet)
  {
   XmlNode contentLanguageNode = parentNode.CreateChildElement("ContentLanguage");
   contentLanguageNode.SetText(m_contentLanguage);
  }

  if(m_userMetadataHasBeenSet)
  {
  }

  if(m_contentLengthHasBeenSet)
  {
   XmlNode contentLengthNode = parentNode.CreateChildElement("ContentLength");
   ss << m_contentLength;
   contentLengthNode.SetText(ss.str());
   ss.str("");
  }

  if(m_contentMD5HasBeenSet)
  {
   XmlNode contentMD5Node = parentNode.CreateChildElement("ContentMD5");
   contentMD5Node.SetText(m_contentMD5);
  }

  if(m_contentTypeHasBeenSet)
  {
   XmlNode contentTypeNode = parentNode.CreateChildElement("ContentType");
   contentTypeNode.SetText(m_contentType);
  }

  if(m_httpExpiresDateHasBeenSet)
  {
   XmlNode httpExpiresDateNode = parentNode.CreateChildElement("HttpExpiresDate");
   httpExpiresDateNode.SetText(m_httpExpiresDate.ToGmtString(Aws::Utils::DateFormat::ISO_8601));
  }

  if(m_requesterChargedHasBeenSet)
  {
   XmlNode requesterChargedNode = parentNode.CreateChildElement("RequesterCharged");
   ss << std::boolalpha << m_requesterCharged;
   requesterChargedNode.SetText(ss.str());
   ss.str("");
  }

  if(m_sSEAlgorithmHasBeenSet)
  {
   XmlNode sSEAlgorithmNode = parentNode.CreateChildElement("SSEAlgorithm");
   sSEAlgorithmNode.SetText(S3SSEAlgorithmMapper::GetNameForS3SSEAlgorithm(m_sSEAlgorithm));
  }

}

} // namespace Model
} // namespace S3Control
} // namespace Aws


text:
package com.kissintelligentsystems.ocm.java;

import java.util.Dictionary;
import java.util.Hashtable;

public class OCMRow
{
	private byte[] rowID;

	private Dictionary<byte[], OCMCell> columns;

	public OCMRow(byte[] rowID)
	{
		//Store the row ID
		this.rowID = rowID;

		//Initialise the columns dictionary
		columns = new Hashtable<byte[], OCMCell>(20);
	}

	public OCMRow(byte[] rowID, Dictionary<byte[], OCMCell> columns)
	{
		//Store the params
		this.rowID = rowID;
		this.columns = columns;
	}

	public byte[] getRowID()
	{
		return rowID;
	}

	public void setRowID(byte[] rowID)
	{
		this.rowID = rowID;
	}

	public Dictionary<byte[], OCMCell> getColumns()
	{
		return columns;
	}

	public void setColumns(Dictionary<byte[], OCMCell> columns)
	{
		this.columns = columns;
	}

}


text:
package com.appthwack.sandwich;

import android.app.Activity;
import android.test.ActivityInstrumentationTestCase2;
import android.util.Log;

// TODO: Auto-generated Javadoc
/**
 * The Class SandwichBaseTest.
 *
 * @param <T> the generic type
 */
public class SandwichBaseTest<T extends Activity> extends ActivityInstrumentationTestCase2<T> {

    /**
     * Instantiates a new sandwich base test.
     *
     * @param activityClass the activity class
     */
    public SandwichBaseTest(Class<T> activityClass) {
        super(activityClass);
    }

	/* (non-Javadoc)
	 * @see android.test.ActivityInstrumentationTestCase2#setUp()
	 */
	protected void setUp() throws Exception {
		super.setUp();
		Log.d("sandwich","setup");
		SoloFactory.createSolo(getInstrumentation());
		this.getActivity();

	}

	/* (non-Javadoc)
	 * @see android.test.ActivityInstrumentationTestCase2#tearDown()
	 */
	protected void tearDown() throws Exception {
		super.tearDown();
		SoloFactory.getSolo().finishOpenedActivities();
	}

	/* (non-Javadoc)
	 * @see android.test.ActivityInstrumentationTestCase2#runTest()
	 */
	@Override
	public void runTest() throws Throwable {
	     try{
	          super.runTest();
	     }
	     catch (Throwable t) {
	          String testCaseName = String.format("%s.%s", getClass().getName(), getName());
	          SoloFactory.getSolo().takeScreenshot(testCaseName);
	     throw t;
	     }
	}

}


text:
require('moonstone');

/**
* Contains the declaration for the {@link module:moonstone/ProgressButton~ProgressButton} kind.
* @module moonstone/ProgressButton
*/

var
	kind = require('enyo/kind'),
	Animator = require('enyo/Animator'),
	Control = require('enyo/Control');

var
	Button = require('../Button');

/**
* Fires when progress button finishes animating to a position. No event-specific data is sent
* with this event.
*
* @event module:moonstone/ProgressButton~ProgressButton#onButtonProgressFinish
* @type {Object}
* @public
*/

/**
* {@link module:moonstone/ProgressButton~ProgressButton} is an animated button
* that shows progress from one state to another.
*
* ```
* 	var
* 		kind = require('enyo/kind'),
* 		ProgressButton = require('moonstone/ProgressButton');
*
* 	{kind: ProgressButton, progress: 10, content: 'Download', postContent: 'Launch'}
* ```
*
* To animate progress changes, call the {@link module:moonstone/ProgressButton~ProgressButton#animateProgressTo} method:
*
* ```
* 	this.$.progressButton.animateProgressTo(50);
* ```
*
* You may customize the color of the bar by applying a style via the
* {@link module:moonstone/ProgressButton~ProgressButton#barClasses} property, e.g.:
*
* ```
* 	{kind: ProgressButton, barClasses: 'class-name'}
* ```
*
* For more information, see the documentation on [Progress Button
* Indicators](building-apps/controls/progress-button-indicators.html) in the Enyo
* Developer Guide
*
* @class ProgressButton
* @extends module:moonstone/Button~Button
* @ui
* @public
*/
module.exports = kind(
	/** @lends module:moonstone/ProgressButton~ProgressButton.prototype */ {

	/**
	* @private
	*/
	name: 'moon.ProgressButton',

	/**
	* @private
	*/
	kind: Button,

	/**
	* @private
	*/
	classes: 'moon-progress-button',

	/**
	* @private
	*/
	spotlight: true,

	/**
	* @private
	* @lends module:moonstone/ProgressButton~ProgressButton.prototype
	*/
	published: {

		/**
		* Current position of progress button.
		*
		* @type {Number}
		* @default 0
		* @public
		*/
		progress: 0,

		/**
		* Minimum progress value (i.e., no progress made).
		*
		* @type {Number}
		* @default 0
		* @public
		*/
		min: 0,

		/**
		* Maximum progress value (i.e., process complete).
		*
		* @type {Number}
		* @default 100
		* @public
		*/
		max: 100,

		/**
		* Optional CSS classes to apply to progress button bar.
		*
		* @type {String}
		* @default ''
		* @public
		*/
		barClasses: '',

		/**
		* The text to display after the progress has been completed.
		*
		* @type {String}
		* @default 'Completed'
		* @public
		*/
		postContent: 'Completed',

		/**
		* Toggle whether there will be animation on the progress updates
		*
		* @type {Boolean}
		* @default true
		* @public
		*/
		animated: true,

		/**
		* The amount of fixed-steps the progress bar should increment to. 4 steps would step to
		* 25%, 50%, 75%, and 100%. 5 steps would step to 20%, 40%, 60%, 80%, and 100%. etc.
		*
		* @type {Number}
		* @default 4
		* @public
		*/
		steps: 4
	},

	/**
	* @private
	*/
	events: {

		/**
		* {@link module:moonstone/ProgressButton~ProgressButton#onButtonProgressFinish}
		*/
		onButtonProgressFinish: ''
	},

	/**
	* @private
	*/
	components: [
		{name: 'progressAnimator', kind: Animator, onStep: 'progressAnimatorStep', onEnd: 'progressAnimatorComplete'},
		{name: 'bar', kind: Control, classes: 'moon-progress-button-bar'},
		{name: 'progressPercent', kind: Control, classes: 'moon-progress-button-progresspercent'}
	],

	/**
	* @private
	*/
	create: function () {
		Button.prototype.create.apply(this, arguments);
		this.preContent = this.content;
		this.addRemoveClass('moon-progress-button-rtl', this.rtl);
		this.progressChanged();
		this.animatedChanged();
		this.barClassesChanged();
	},

	/**
	* @private
	*/
	barClassesChanged: function (old) {
		this.$.bar.removeClass(old);
		this.$.bar.addClass(this.barClasses);
	},

	/**
	* @private
	*/
	progressChanged: function () {
		this.progress = this.clampValue(this.min, this.max, this.progress);

		var progress,
			percent = this.calcPercent(this.progress),
			offset = -10,
			minimumVisibleProgress = 10,
			increment = parseInt(100 / this.get('steps'), 10);
		if (percent < 100) {
			this.removeClass('completed');
		}
		if (percent < 5) {
			if (percent === 0) {
				this._inProgress(false);
				this.set('content', this.preContent);
				this.$.progressPercent.set('content', '');
				this.removeClass('in-progress');
			} else {
				this._inProgress(true);
				this.updateProgressPercent(percent);
			}
			// The value is so small that it should not be visible.
			this.$.bar.applyStyle('transform', 'translateX(-100%)');
			this.$.bar.applyStyle('-webkit-transform', 'translateX(-100%)');
			progress = 0;
		} else if (percent >= 5 && percent < 100) {
			// Disable spotlight: you can't click a button once it's in progress
			this._inProgress(true);
			if (percent < increment) {
				// Statically set the size of the progress bar if it's less than 1 increment.
				progress = minimumVisibleProgress;
			} else {
				// Calculate how many increments we should use
				progress = parseInt(percent / increment, 10) * increment;
			}
			this.updateProgressPercent(percent);
			// Only change the progress bar if it's different from the last time this was run
			if (progress != this._visibleProgress) {
				this.$.bar.applyStyle('transform', 'translateX(-' + (100 + offset - progress) + '%)');
				this.$.bar.applyStyle('-webkit-transform', 'translateX(-' + (100 + offset - progress) + '%)');
			}
		} else if (percent >= 100) {
			// Make it spottable again, now that it's finished.
			this.$.bar.applyStyle('transform', null);
			this.$.bar.applyStyle('-webkit-transform', null);
			this.setPostContent();
			progress = 100;
		}
		// Remember the last progress state
		this._visibleProgress = progress;
	},

	/**
	* @private
	*/
	_inProgress: function (state) {
		this.addRemoveClass('in-progress', state);
		this.set('spotlight', !state);
	},

	/**
	* @private
	*/
	clampValue: function (min, max, value) {
		return Math.max(min, Math.min(value, max));
	},

	/**
	* @private
	*/
	animatedChanged: function () {
		this.addRemoveClass('animated', this.get('animated'));
	},

	/**
	* @private
	*/
	calcRatio: function (value) {
		return (value - this.min) / (this.max - this.min);
	},

	/**
	* @private
	*/
	calcPercent: function (value) {
		return this.calcRatio(value) * 100;
	},

	/**
	* @private
	*/
	updateBarPosition: function (percent) {
		this.$.bar.applyStyle('width', percent + '%');
	},

	/**
	* @private
	*/
	updateProgressPercent: function(percent) {
		this.set('content', '');
		this.$.progressPercent.set('content', Math.round(percent) + '%');
	},

	/**
	* @private
	*/
	setPostContent: function(){
		this.startJob('completeProgress', function () {
			this.$.progressPercent.set('content', '');
			this.addClass('completed');
			this.set('content', this.get('postContent'));

			// When the animation is done, we are finally no longer in-progress.
			this.startJob('completeProgressDone', function () {
				this._inProgress(false);
			}, 200); // Same as the CSS transition duration
		}, 1000);
	},

	/**
	* Animates progress to the passed-in value.
	*
	* @param {Number} value  The destination number
	* @public
	*/
	animateProgressTo: function (value) {
		this.$.progressAnimator.play({
			startValue: this.progress,
			endValue: value,
			node: this.hasNode()
		});
	},

	/**
	* @private
	*/
	progressAnimatorStep: function (sender) {
		this.setProgress(sender.value);
		return true;
	},

	/**
	* @fires module:moonstone/ProgressBar~ProgressBar#onButtonProgressFinish
	* @private
	*/
	progressAnimatorComplete: function (sender) {
		this.doButtonProgressFinish();
		return true;
	}
});


text:
package influent.server.clustering;

import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import com.oculusinfo.ml.DataSet;
import com.oculusinfo.ml.Instance;
import com.oculusinfo.ml.feature.numeric.NumericVectorFeature;
import com.oculusinfo.ml.feature.numeric.centroid.MeanNumericVectorCentroid;
import com.oculusinfo.ml.feature.numeric.distance.EuclideanDistance;
import com.oculusinfo.ml.unsupervised.cluster.BaseClusterer;
import com.oculusinfo.ml.unsupervised.cluster.Cluster;
import com.oculusinfo.ml.unsupervised.cluster.ClusterResult;
import com.oculusinfo.ml.unsupervised.cluster.kmeans.KMeans;
import com.oculusinfo.ml.unsupervised.cluster.dpmeans.DPMeans;

import influent.idl.FL_Cluster;
import influent.idl.FL_Entity;
import influent.idlhelper.ClusterHelper;
import influent.idlhelper.PropertyHelper;
import influent.server.clustering.utils.EntityClusterFactory;

public class NumericEntityClusterer extends BaseEntityClusterer {

	private int MAX_CLUSTER_SIZE = 5;
	private double THRESHOLD = 100.0;

	@Override
	public void init(Object[] args) {
		try {
			clusterFactory = (EntityClusterFactory)args[0];
			clusterField = (String)args[1];
			THRESHOLD = (Double)args[2];
			MAX_CLUSTER_SIZE = (Integer)args[3];
		 }
		 catch (Exception e) {
			 throw new IllegalArgumentException("Invalid initialization parameters.", e);
		 }
	}

	private Instance createInstance(String id, Double value) {
		Instance inst = new Instance(id);

		NumericVectorFeature feature = new NumericVectorFeature("num");
		feature.setValue(new double[]{value});
		inst.addFeature( feature );

		return inst;
	}

	private Double getDoubleValue(PropertyHelper property) {
		Double val = null;

		// try to read the double value of the entity
		if (property != null && property.getRange() != null) {
			Object v = property.getValue();
			if (v instanceof Double) {
				val = (Double)v;
			}
			else if (v instanceof Float) {
				val = (double)(Float)v;
			}
			else if (v instanceof Long) {
				val = (double)(Long)v;
			}
			else if (v instanceof Integer) {
				val = (double)(Integer)v;
			}
		}
		return val;
	}

	private DataSet createDataSet(Collection<FL_Entity> entities, Collection<FL_Cluster> immutableClusters, ClusterContext context) {
		DataSet ds = new DataSet();

		for (FL_Entity entity : entities) {
			PropertyHelper prop = getFirstProperty(entity, clusterField);
			if (prop != null) {
				Double val = getDoubleValue(prop);

				if (val != null) {
					Instance inst = createInstance(entity.getUid(), val);
					ds.add(inst);
				}
			}
			else {
				// No valid clusterField property found default to -1
				Instance inst = createInstance(entity.getUid(), -1.0);
				ds.add(inst);
			}
		}
		for (FL_Cluster immutableCluster : immutableClusters) {
			PropertyHelper prop = getFirstProperty(immutableCluster, toClusterPropertyName(clusterField));
			if (prop == null) {
				FL_Entity firstChild = getFirstChildEntity(immutableCluster, context);
				if (firstChild != null) {
					prop = getFirstProperty(firstChild, clusterField);
				}
			}
			if (prop != null) {
				Double val = getDoubleValue(prop);

				if (val != null) {
					Instance inst = createInstance(immutableCluster.getUid(), val);
					ds.add(inst);
				}
			}
			else {
				// No valid clusterField property found default to -1
				Instance inst = createInstance(immutableCluster.getUid(), -1.0);
				ds.add(inst);
			}
		}
		return ds;
	}

	private DataSet createDataSet(Collection<FL_Cluster> entities, ClusterContext context) {
		DataSet ds = new DataSet();

		for (FL_Cluster entity : entities) {
			PropertyHelper prop = getFirstProperty(entity, toClusterPropertyName(clusterField));
			if (prop == null) {
				FL_Entity firstChild = getFirstChildEntity(entity, context);
				if (firstChild != null) {
					prop = getFirstProperty(firstChild, clusterField);
				}
			}
			if (prop != null) {
				double val = getDoubleValue(prop);
				Instance inst = createInstance(entity.getUid(), val);
				ds.add(inst);
			}
			else {
				// No valid clusterField property found default to 0.0
				Instance inst = createInstance(entity.getUid(), 0.0);
				ds.add(inst);
			}
		}
		return ds;
	}

	private BaseClusterer createNumericClusterer(boolean kmeans) {
		BaseClusterer clusterer = null;

		if (kmeans) {
			clusterer = new KMeans(MAX_CLUSTER_SIZE, 5, true);
		} else {
			DPMeans dpMeans = new DPMeans(3, true);
			dpMeans.setThreshold(THRESHOLD);
			clusterer = dpMeans;
		}
		clusterer.registerFeatureType("num", MeanNumericVectorCentroid.class, new EuclideanDistance(1.0));

		return clusterer;
	}

	private ClusterContext secondStageClustering(Collection<FL_Entity> entities,
											Collection<FL_Cluster> immutableClusters,
											Collection<FL_Cluster> mergeClusters,
											Collection<FL_Cluster> clusters,
											ClusterContext context) {
		Map<String, FL_Entity> entityIndex = createEntityIndex(entities);
		Map<String, FL_Cluster> mergeClusterIndex = createClusterIndex(mergeClusters);
		Map<String, FL_Cluster> immutableClusterIndex = createClusterIndex(immutableClusters);
		Map<String, FL_Cluster> clusterIndex = createClusterIndex(clusters);

		DataSet ds = createDataSet(mergeClusters, context);

		BaseClusterer clusterer = createNumericClusterer(true);

		List<Cluster> existingClusters = new LinkedList<Cluster>();

		for (FL_Cluster cluster : clusters) {
			double val = 0;
			PropertyHelper prop = getFirstProperty(cluster, toClusterPropertyName(clusterField));
			if (prop != null) {
				val = getDoubleValue(prop);
			}
			Cluster c = clusterer.createCluster();
			c.setId(cluster.getUid());
			NumericVectorFeature feature = new NumericVectorFeature("num");
			feature.setValue(new double[]{val});
			c.addFeature(feature);
			existingClusters.add(c);
		}

		ClusterResult rs = null;
		if (existingClusters.isEmpty()) {
			rs = clusterer.doCluster(ds);
		}
		else {
			rs = clusterer.doIncrementalCluster(ds, existingClusters);
		}
		// clean up
		clusterer.terminate();

		Map<String, FL_Cluster> modifiedClusters = new HashMap<String, FL_Cluster>();

		for (Cluster c : rs) {
			List<FL_Cluster> subClusters = new LinkedList<FL_Cluster>();
			List<FL_Entity> members = new LinkedList<FL_Entity>();

			for (Instance inst : c.getMembers()) {
				FL_Cluster mergeCluster = mergeClusterIndex.get(inst.getId());

				for (String entityId : mergeCluster.getMembers()) {
					if ( entityIndex.containsKey(entityId) ) {
						members.add( entityIndex.get(entityId) );
					}
				}

				for (String subClusterId : mergeCluster.getSubclusters()) {
					if ( immutableClusterIndex.containsKey(subClusterId) ){
						subClusters.add( immutableClusterIndex.get(subClusterId) );
					}
				}
			}

			FL_Cluster cluster = clusterIndex.get(c.getId());
			if (cluster == null) {
				cluster = clusterFactory.toCluster(members, subClusters);
				// cache the cluster property
				NumericVectorFeature feature = (NumericVectorFeature)c.getFeature("num");
				double value = feature.getValue()[0];
				addClusterProperty(cluster, clusterField, value);
			}
			else {
				ClusterHelper.addMembers(cluster, members);
				EntityClusterFactory.setEntityCluster(members, cluster);

				for (FL_Cluster subCluster : subClusters) {
					ClusterHelper.addSubCluster(cluster, subCluster);
					subCluster.setParent(cluster.getUid());
				}

				// cache the cluster property
				NumericVectorFeature feature = (NumericVectorFeature)c.getFeature("num");
				double value = feature.getValue()[0];
				addClusterProperty(cluster, clusterField, value);
			}
			modifiedClusters.put(cluster.getUid(), cluster);
		}

		ClusterContext result = new ClusterContext();
		result.roots.putAll(modifiedClusters);
		result.clusters.putAll(modifiedClusters);

		return result;
	}

	public ClusterContext firstStageClustering(Collection<FL_Entity> entities,
										  Collection<FL_Cluster> immutableClusters,
										  Collection<FL_Cluster> clusters,
										  ClusterContext context) {

		Map<String, FL_Entity> entityIndex = createEntityIndex(entities);
		Map<String, FL_Cluster> immutableClusterIndex = createClusterIndex(immutableClusters);
		Map<String, FL_Cluster> clusterIndex = createClusterIndex(clusters);

		DataSet ds = createDataSet(entities, immutableClusters, context);

		// first cluster using dp-means to control max difference of members
		BaseClusterer clusterer = createNumericClusterer(false);

		List<Cluster> existingClusters = new LinkedList<Cluster>();

		for (FL_Cluster cluster : clusters) {
			double val = 0;
			PropertyHelper prop = getFirstProperty(cluster, toClusterPropertyName(clusterField));
			if (prop != null) {
				val = getDoubleValue(prop);
			}
			Cluster c = clusterer.createCluster();
			c.setId(cluster.getUid());
			NumericVectorFeature feature = new NumericVectorFeature("num");
			feature.setValue(new double[]{val});
			c.addFeature(feature);
			existingClusters.add(c);
		}

		ClusterResult rs = null;
		if (existingClusters.isEmpty()) {
			rs = clusterer.doCluster(ds);
		}
		else {
			rs = clusterer.doIncrementalCluster(ds, existingClusters);
		}
		// clean up
		clusterer.terminate();

		Map<String, FL_Cluster> modifiedClusters = new HashMap<String, FL_Cluster>();

		for (Cluster c : rs) {
			List<FL_Cluster> subClusters = new LinkedList<FL_Cluster>();
			List<FL_Entity> members = new LinkedList<FL_Entity>();

			for (Instance inst : c.getMembers()) {
				String id = inst.getId();
				if ( entityIndex.containsKey(id) ) {
					members.add( entityIndex.get(id) );
				}
				else if ( immutableClusterIndex.containsKey(id) ){
					subClusters.add( immutableClusterIndex.get(id) );
				}
			}

			FL_Cluster cluster = clusterIndex.get(c.getId());
			if (cluster == null) {
				cluster = clusterFactory.toCluster(members, subClusters);
				// cache the cluster property
				NumericVectorFeature feature = (NumericVectorFeature)c.getFeature("num");
				double value = feature.getValue()[0];
				addClusterProperty(cluster, clusterField, value);
			}
			else {
				ClusterHelper.addMembers(cluster, members);
				EntityClusterFactory.setEntityCluster(members, cluster);

				for (FL_Cluster subCluster : subClusters) {
					ClusterHelper.addSubCluster(cluster, subCluster);
					subCluster.setParent(cluster.getUid());
				}

				// cache the cluster property
				NumericVectorFeature feature = (NumericVectorFeature)c.getFeature("num");
				double value = feature.getValue()[0];
				addClusterProperty(cluster, clusterField, value);
			}
			modifiedClusters.put(cluster.getUid(), cluster);
		}

		ClusterContext result = new ClusterContext();
		result.roots.putAll(modifiedClusters);
		result.clusters.putAll(modifiedClusters);

		return result;
	}

	@Override
	public ClusterContext clusterEntities(Collection<FL_Entity> entities,
										  Collection<FL_Cluster> immutableClusters,
										  Collection<FL_Cluster> clusters,
										  ClusterContext context) {
		ClusterContext modifiedClusters = firstStageClustering(entities, immutableClusters, clusters, context);

		Collection<FL_Cluster> newClusters = findNewClusters(modifiedClusters.roots, clusters);

		int totalClusters = newClusters.size() + clusters.size();

		if (totalClusters > MAX_CLUSTER_SIZE) {
			modifiedClusters = secondStageClustering(entities, immutableClusters, newClusters, clusters, context);
		}
		return modifiedClusters;
	}

}


text:
#import "GDataHTTPFetcher.h"

// GData HTTP Logging
//
// All traffic using GDataHTTPFetcher can be easily logged.  Call
//
//   [GDataHTTPFetcher setIsLoggingEnabled:YES];
//
// to begin generating log files.
//
// Log files are put into a folder on the desktop called "GDataHTTPDebugLogs"
// unless another directory is specified with +setLoggingDirectory.
//
// Each run of an application gets a separate set of log files.  An html
// file is generated to simplify browsing the run's http transactions.
// The html file includes javascript links for inline viewing of uploaded
// and downloaded data.
//
// A symlink is created in the logs folder to simplify finding the html file
// for the latest run of the application; the symlink is called
//
//   AppName_http_log_newest.html
//
// For better viewing of XML logs, use Camino or Firefox rather than Safari.
//
// Projects may define STRIP_GDATA_FETCH_LOGGING to remove logging code.

@interface GDataHTTPFetcher (GDataHTTPFetcherLogging)

// Note: the default logs directory is ~/Desktop/GDataHTTPDebugLogs; it will be
// created as needed.  If a custom directory is set, the directory should
// already exist.
+ (void)setLoggingDirectory:(NSString *)path;
+ (NSString *)loggingDirectory;

// client apps can turn logging on and off
+ (void)setIsLoggingEnabled:(BOOL)flag;
+ (BOOL)isLoggingEnabled;

// client apps can optionally specify process name and date string used in
// log file names
+ (void)setLoggingProcessName:(NSString *)str;
+ (NSString *)loggingProcessName;

+ (void)setLoggingDateStamp:(NSString *)str;
+ (NSString *)loggingDateStamp;

// internal; called by fetcher
- (void)logFetchWithError:(NSError *)error;
- (void)logCapturePostStream;
@end


text:
package net.daverix.logcatviewer;

import java.util.List;

public interface LogHandler {
    /**
     * Get all log items that have been read until now.
     *
     * @return list of log items
     */
    public List<LogItem> getReadItems();

    /**
     * Adds a listener for when a new log item have been read
     * @param listener the listener that will be notified
     */
    public void addOnLogItemReadListener(OnLogItemReadListener listener);

    /**
     * Removes a listener for incoming log items. Should be done in onDestroy etc.
     * @param listener the listener to be removed
     */
    public void removeOnLogItemReadListener(OnLogItemReadListener listener);

    /**
     * Interface for listening on incoming log items
     */
    public interface OnLogItemReadListener {
        /**
         * Callback for new log items read from the log
         *
         * @param item the log item that was read
         */
        public void onLogItemRead(LogItem item);
    }
}


text:
<?php

/**
 * @file
 * Contains \Drupal\book\BookUninstallValidator.
 */

namespace Drupal\book;

use Drupal\Core\Entity\Query\QueryFactory;
use Drupal\Core\Extension\ModuleUninstallValidatorInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\StringTranslation\TranslationInterface;

/**
 * Prevents book module from being uninstalled whilst any book nodes exist or
 * there are any book outline stored.
 */
class BookUninstallValidator implements ModuleUninstallValidatorInterface {

  use StringTranslationTrait;

  /**
   * The book outline storage.
   *
   * @var \Drupal\book\BookOutlineStorageInterface
   */
  protected $bookOutlineStorage;

  /**
   * The entity query for node.
   *
   * @var \Drupal\Core\Entity\Query\QueryInterface
   */
  protected $entityQuery;

  /**
   * Constructs a new BookUninstallValidator.
   *
   * @param \Drupal\book\BookOutlineStorageInterface $book_outline_storage
   *   The book outline storage.
   * @param \Drupal\Core\Entity\Query\QueryFactory $query_factory
   *   The entity query factory.
   * @param \Drupal\Core\StringTranslation\TranslationInterface $string_translation
   *   The string translation service.
   */
  public function __construct(BookOutlineStorageInterface $book_outline_storage, QueryFactory $query_factory, TranslationInterface $string_translation) {
    $this->bookOutlineStorage = $book_outline_storage;
    $this->entityQuery = $query_factory->get('node');
    $this->stringTranslation = $string_translation;
  }

  /**
   * {@inheritdoc}
   */
  public function validate($module) {
    $reasons = [];
    if ($module == 'book') {
      if ($this->hasBookOutlines()) {
        $reasons[] = $this->t('To uninstall Book, delete all content that is part of a book');
      }
      else {
        // The book node type is provided by the Book module. Prevent uninstall
        // if there are any nodes of that type.
        if ($this->hasBookNodes()) {
          $reasons[] = $this->t('To uninstall Book, delete all content that has the Book content type');
        }
      }
    }
    return $reasons;
  }

  /**
   * Checks if there are any books in an outline.
   *
   * @return bool
   *   TRUE if there are books, FALSE if not.
   */
  protected function hasBookOutlines() {
    return $this->bookOutlineStorage->hasBooks();
  }

  /**
   * Determines if there is any book nodes or not.
   *
   * @return bool
   *   TRUE if there are book nodes, FALSE otherwise.
   */
  protected function hasBookNodes() {
    $nodes = $this->entityQuery
      ->condition('type', 'book')
      ->accessCheck(FALSE)
      ->range(0, 1)
      ->execute();
    return !empty($nodes);
  }

}