text:
<?php
declare(strict_types=1);

namespace StackGuru\Core;

use \Discord\Discord;
use \Discord\WebSockets\Event as DiscordEvent;
use StackGuru\Core\Utils;
use \Discord\Parts\Channel\Message as Message;
use \Discord\Parts\User\Member as Member;
use StackGuru\Core\Command\CommandContext as CommandContext;

class Bot
{
    private $discord; // \Discord\Discord

    private $callbacks  = [
        // string "callback_name"   => [callable, callable, ... ],
    ];

    private $cmdRegistry;
    private $services;
    private $cmdAliases;
    private $database;

    /**
     * Bot constructor.
     *
     * @param array $options = []
     * @param bool $shutup
     */
    public function __construct(array $options = [], bool $shutup = null)
    {

        // Used for testing the bot methods
        if ($shutup !== null && $shutup === true) {
            return;
        }

        // Verify parameter to have required keys
        $options = Utils\ResolveOptions::verify($options, ["discord", "database", "commands", "services"]);

        // Setup database connection
        $this->database = new Database($options["database"]);

        // Setup command registry.
        $this->cmdRegistry = new \StackGuru\Core\Command\Registry();
        $this->cmdRegistry->loadCommandFolder($options["commands"]["namespace"], $options["commands"]["folder"]);

        // Store commands to database
        //
        echo "Storing command namespaces to database";
        foreach ($this->cmdRegistry->getCommands() as $commandEntry) {
            $namespace      = $commandEntry->getFullName();
            $description    = $commandEntry->getDescription();
            $activated      = true;

            $this->database->saveCommand($namespace, $description, $activated);

            // Since a alias would be requested at the same level as a main command
            // We need to make an alias for each main command, that equals the normal command
            // alias == command (type of main, main is a command that can have sub commands)
            //
            // Essentially this means u cant create an alias that equals "google" if a command named "google" exists.
            //
            $this->database->saveCommandAlias($namespace, $commandEntry->getName());

            foreach ($commandEntry->getChildren() as $childEntry) {
                $namespace      = $childEntry->getFullName();
                $description    = $childEntry->getDescription();
                $activated      = true;

                $this->database->saveCommand($namespace, $description, $activated);
                echo ".";
            }
        }
        echo PHP_EOL;

        // Get command details from database
        //
        echo "Syncing command details with  database";
        foreach ($this->cmdRegistry->getCommands() as $commandEntry) {
            $info = $this->database->getCommandDetails($commandEntry->getFullName());

            $commandEntry->updateInfo($info);

            // also store each alias to an array for faster access
            foreach($info["aliases"] as $alias) {
                $this->cmdRegistry->addCommandAlias($alias, $commandEntry);
            }

            foreach ($commandEntry->getChildren() as $childEntry) {
                $info = $this->database->getCommandDetails($childEntry->getFullName());

                $childEntry->updateInfo($info);

                // also store each alias to an array for faster access
                foreach($info["aliases"] as $alias) {
                    $this->cmdRegistry->addCommandAlias($alias, $childEntry);
                }

                echo ".";
            }
        }
        echo PHP_EOL;

        // Debug output
        if (true === DEVELOPMENT) {
            $commands = $this->cmdRegistry->getCommands();
            echo "Loaded ", sizeof($commands), " commands:", PHP_EOL;

            $mask = "%-20s %s \n";
            printf($mask, "Name", "Subcommands");
            foreach ($commands as $name => $command) {
                $subcommands = array_keys($command->getChildren());
                printf($mask, " * " . $name, "[" . implode(", " , $subcommands) . "]");
            }
            echo PHP_EOL;
        }

        // load services
        $serviceCtx = new CommandContext();
        $serviceCtx->bot            = $this;
        $serviceCtx->guild          = null;
        $serviceCtx->cmdRegistry    = null;
        $serviceCtx->services       = null;
        $serviceCtx->message        = null;
        $serviceCtx->discord        = null;
        $serviceCtx->database       = $this->database;
        $this->services = new \StackGuru\Core\Service\Services();
        $this->services->loadServicesFolder($options["services"]["namespace"], $options["services"]["folder"], $serviceCtx);

        // Debug output
        if (true === DEVELOPMENT) {
            $services = $this->services->getAll();
            echo "Loaded ", sizeof($services), " services:", PHP_EOL;

            $mask = "%-20s %s \n";
            printf($mask, "Name", "Status");
            foreach ($services as $name => $srv) {
                $status = "{\"enabled\":".($srv->isEnabled($serviceCtx)?"true":"false").", \"running\":".($srv->running($serviceCtx)?"true":"false")."}";
                printf($mask, " * " . $name, $status);
            }
            echo PHP_EOL;
        }

        // Set up a discord instance
        $this->discord = new Discord($options["discord"]);
    }

    /**
     * Setup event handlers and run the bot.
     */
    public function run()
    {
        // Events to trigger a message update.
        $messageEvents = [
            DiscordEvent::MESSAGE_CREATE,
            DiscordEvent::MESSAGE_UPDATE, // disabled due to errors in Discord
        ];

        // DiscordEvent::MESSAGE_DELETE, only returns a string $id for the message.

        // When the app is ready, listen for messages.
        $this->discord->on("ready", function (Discord $self) use ($messageEvents) {

            //show that the bot is starting up

            if (true === DEVELOPMENT) {
                echo "... OK!", PHP_EOL;
            }

            // set presence
            $this->updatePresence("!help");

            // Start services
            //

            // Handle message events
            //
            if (true === DEVELOPMENT) {
                echo "Adding bot listeners";
            }

            // New message
            $self->on(DiscordEvent::MESSAGE_CREATE, function (Message $msg, $discordObj = null) {
                // Discord has it's own exception handler, so we have to catch exceptions from
                // our message handler ourselves.
                try {
                    $this->incoming(DiscordEvent::MESSAGE_CREATE, $msg->id, $msg);
                } catch (\Throwable $e) {
                    echo $e, PHP_EOL;
                }
            });

            // Updated message
            $self->on(DiscordEvent::MESSAGE_UPDATE, function (Message $msg, $discordObj = null) {
                // Discord has it's own exception handler, so we have to catch exceptions from
                // our message handler ourselves.
                try {
                    $this->incoming(DiscordEvent::MESSAGE_UPDATE, $msg->id, $msg);
                } catch (\Throwable $e) {
                    echo $e, PHP_EOL;
                }
            });

            // Deleted message
            $self->on(DiscordEvent::MESSAGE_DELETE, function (String $msgId) {
                // Discord has it's own exception handler, so we have to catch exceptions from
                // our message handler ourselves.
                try {
                    $this->incoming(DiscordEvent::MESSAGE_DELETE, $msgId);
                } catch (\Throwable $e) {
                    echo $e, PHP_EOL;
                }
            });

            // when someone joins the guild give them the member role.. todo: fix hack
            $self->on(DiscordEvent::GUILD_MEMBER_ADD, function (Member $member) {
                // Discord has it's own exception handler, so we have to catch exceptions from
                // our message handler ourselves.
                try {

                    // create service context
                    $serviceCtx = new CommandContext();
                    $serviceCtx->bot            = $this;
                    $serviceCtx->guild          = null;
                    $serviceCtx->cmdRegistry    = $this->cmdRegistry;
                    $serviceCtx->services       = $this->services;
                    $serviceCtx->message        = null;
                    $serviceCtx->discord        = $this->discord;
                    $serviceCtx->database       = $this->database;
                    $serviceCtx->parentCommand  = null;

                    $this->runScripts(BotEvent::MEMBER_JOINED_GUILD, DiscordEvent::GUILD_MEMBER_ADD, "", $serviceCtx, $member);
                } catch (\Throwable $e) {
                    echo $e, PHP_EOL;
                }
            });

            if (true === DEVELOPMENT) {
                echo "... OK!", PHP_EOL;
            }

            //$this->discord->loop->addTimer(1, function ($timer) { $this->updatePresence("!help"); });

            if (true === DEVELOPMENT) {
                echo "Bot is now running!", PHP_EOL, "---", PHP_EOL, PHP_EOL;
            }
        });

        // Run!
        if (true === DEVELOPMENT) {
            echo "Starting DiscordPHP service";
        }
        $this->discord->run();

    }

    /**
     * Stop the bot.
     */
    public function stop()
    {
        /*
         * Stop discord connection
         */
        try {
            $this->discord->close();
        } catch (\Throwable $e) {
            echo $e, PHP_EOL;
        }
    }

    /**
     * Probably the worst function i've written in my life.
     * If you can even call this a function.
     *
     * TODO: a method that takes any message and return a object for dealing with the content if it's a command.
     *
     * @param \Discord\Parts\Channel\Message $message
     */
    private function incoming(string $event, string $msgId, ?Message $message = null)
    {
        // sanity check of author/member object in message
        if ($message->author == null) {
            return;
        }
        else if (isset($message->author->member) && $message->author->member == null) {
            return;
        }

        // if development display request
        //

        if (true === DEVELOPMENT && null !== $message) {
            echo PHP_EOL, "Request: {$message->content}", PHP_EOL;
        }

        // create service context
        $serviceCtx = new CommandContext();
        $serviceCtx->bot            = $this;
        $serviceCtx->guild          = null === $message ? null : $message->channel->guild;
        $serviceCtx->cmdRegistry    = $this->cmdRegistry;
        $serviceCtx->services       = $this->services;
        $serviceCtx->message        = $message;
        $serviceCtx->discord        = $this->discord;
        $serviceCtx->database       = $this->database;
        $serviceCtx->parentCommand  = null;

        // First BOTEVENT::ALL_MESSAGES
        $this->runScripts(BotEvent::MESSAGE_ALL_I_SELF, $event, $msgId, $serviceCtx, $message);

        // If the event is MESSAGE_DELETE, don't continue as we only get a msg id.
        if (DiscordEvent::MESSAGE_DELETE === $event) {
            $this->runScripts(BotEvent::MESSAGE_DELETED, $event, $msgId, $serviceCtx, $message);
            return;
        }

        // If the message is null, don't continue..
        if (null === $message) {
            return;
        }

        // This checks if the message written is by this bot itself: AKA self.
        // If its a message from self: run
        //
        // Don't continue if the message is by the bot.
        // Initiate the BOTEVENT::ALL_MESSAGES_E_SELF
        {
            if (null !== $message->author && $message->author->id == $this->discord->id) {
                $this->runScripts(BotEvent::MESSAGE_FROM_SELF, $event, $msgId, $serviceCtx, $message);
                return;
            }

            $this->runScripts(BotEvent::MESSAGE_ALL_E_SELF, $event, $msgId, $serviceCtx, $message);
        }

        // Check if anyone is contacting the bot / SELF
        {
            // Check if this message was written in a public.
            // Otherwise its private => PM
            if (!$message->channel->is_private) {
                // Keeps track of whether or not the bot has been referenced.
                $referenced = false;

                // Convert the object to an array.
                //
                // Needs a better to handle this. But I wasn't able to use $in->mentions->{$self->id}
                // to get the content I needed..
                $mentions = json_decode(json_encode($message->mentions), true);

                // Check if the bot was referenced by either "@stack-guru" or "@Bot"
                // Sadly I've hardcoded the mention ID for @Bot. This should be fixed somehow.
                //
                // TODO: this is ugly, fix it.
                //
                // Saves some of the if checks, otherwise these gets so long.
                $mentioned = isset($mentions[$this->discord->id]);
                $usedBotReference = null !== $message->content && strpos($message->content, "<@&240626683487453184>") !== false; //@Bot
                if (!$referenced && ($mentioned || $usedBotReference)) {
                    $message->content = str_replace("<@" . $this->discord->id . ">", "", $message->content); // removes the mention of bot
                    $referenced = true; // Bot was not mentioned nor was @Bot used: <@&240626683487453184>
                }

                // Check if the bot was referenced by "!"
                if (!$referenced && null !== $message->content && substr($message->content, 0, 1) === "!") {
                    $message->content = ltrim($message->content, "!");
                    $referenced = true;
                }

                // Check if the bot wasn't referenced.
                //
                // If so, exit this function.
                if (!$referenced) {
                    $this->runScripts(BotEvent::MESSAGE_ALL_E_COMMAND, $event, $msgId, $serviceCtx, $message);
                    return;
                }

                // Since the bot has been referenced at this point, and the reference ID been stripped.
                // Remove any useless whitespaces, left of the message or command input.
                $message->content = ltrim($message->content, " ");
            }

            // show that the bot is typing
            //$message->channel->broadcastTyping();
            // this is sometimes sent after the bot message -> which makes it look bad..

            // The incoming message is for the bot.
            $this->runScripts(BotEvent::MESSAGE_OTHERS_TO_SELF, $event, $msgId, $serviceCtx, $message);
        }

        // make sure message content is of lower case
        $message->content = strtolower($message->content);

        // Check if a help flag has been added: --help, -h. if so we just throw help in front of whatever..
        // This should be rewritten as a service...
        //
        $flag_help = null !== $message->content && strpos($message->content, "--help") !== false;
        $flag_h = null !== $message->content && strpos($message->content, "-h") !== false;
        if (null !== $message->content && "help" !== Utils\StringParser::getFirstWord($message->content) && ($flag_h || $flag_help)) {
            $message->content = "help " . $message->content;
        }

        // It's a command. handle it.
        // Parse query to find the command and get the remaining query.
        $result = $this->cmdRegistry->parseCommandQuery($message->content);

        $command = $result["command"];
        if ($command === null) {
            Utils\Response::sendMessage("Try running `!help` :)", $message);
            return;
        }
        $query = $result["query"];

        // Create command instance
        $instance = $command->createInstance();
        $parentCmd = null == $result["parent"] ? null : $result["parent"]->createInstance();

        // Build command context so the command has references back to the bot
        // and other commands.
        $context                = new CommandContext();
        $context->bot           = $this;
        $context->guild         = $message->channel->guild;
        $context->cmdRegistry   = $this->cmdRegistry;
        $context->services      = $this->services;
        $context->message       = $message;
        $context->discord       = $this->discord;
        $context->parentCommand = $parentCmd;
        $context->database      = $this->database;
        $context->commandEntry  = $command;

        // Make sure that the user/member have permissions to use the command!
        if (!$instance->permitted($context)) {
            Utils\Response::sendMessage("Run `!help` to see what commands you have access to.", $message);
            return;
        }

        // Run command and send a response if the return is not null.
        $instance->process($query, $context); // returns a promise
    }

    /* ********************************************
     * callbacks for dealing with scripts........
     * *******************************************/

    /**
     * Stores requested callbacks.
     * Since there can be more than one callback with the same type,
     *  store each in a auto incremented index as child of the request type.
     *
     * @param string $state
     * @param \Closure $callback
     *
     * @return  int index which will always be above 0.
     */
    public function state(string $state, Callable $callback): int
    {
        if (!isset($this->callbacks[$state])) {
            $this->callbacks[$state] = [];
        }

        $sizeBefore = sizeof($this->callbacks[$state]);
        $this->callbacks[$state][] = $callback;
        $sizeAfter = sizeof($this->callbacks[$state]);

        $index = $sizeBefore === $sizeAfter ? null : $sizeAfter - 1; // this is not async so no issue i think...

        return $index;
    }

    /**
     * Removes a callback from the 2d array.
     *
     * @param  string $state [description]
     * @param  int    $index [description]
     * @return [type]        [description]
     */
    public function removeStateCallable(string $state, int $index)
    {
        if (null === $index || 0 > $index) {
            return;
        }

        if (isset($this->callbacks[$state]) && isset($this->callbacks[$state][$index])) {
            $this->callbacks[$state][$index] = null;
        }
    }

    public function containsStateCallable(string $state, int $index): bool
    {
        if (null === $index || 0 > $index) {
            return false;
        }

        return isset($this->callbacks[$state]) && isset($this->callbacks[$state][$index]);
    }

    /**
     * Checks if a callback request exists, and executes it.
     *
     * TODO: add parsed message content. but first create a class for it?
     *
     * @param string $state
     */
    private function runScripts(string $state, string $event, string $msgId, CommandContext $ctx, $data = null)
    {
        if (!isset($this->callbacks[$state])) {
            return;
        }

        foreach ($this->callbacks[$state] as &$e) {// ($i = sizeof($arr) - 1; $i >= 0; $i -= 1) {
            if (null === $e) {
                continue;
            }

            call_user_func_array($e, [$event, $msgId, $ctx, $data]);
            //call_user_func_array($this->callbacks[$state][$i], [$message, $event]);
        }
    }

    public function updatePresence(string $title, ?bool $idle = false)
    {
        $this->discord->updatePresence($this->discord->factory(\Discord\Parts\User\Game::class, ["name" => $title]), $idle);
    }

}


text:
#import <UIKit/UIKit.h>

/**
 Passed as root view controller to objects before root view controller
 becomes known.
 */
@interface ANProxyViewController : NSProxy

- (instancetype)init;

@property (nonatomic, readwrite, weak) UIViewController *rootViewController;
@property (nonatomic, readwrite, weak) UIView *adView;

@end

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

	<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
	<title>Dynatree - Example</title>

	<link href="../src/skin/ui.dynatree.css" rel="stylesheet" type="text/css">

	<link href="prettify.css" rel="stylesheet">

	<link href='sample.css' rel='stylesheet' type='text/css'>

Example: Expand level

minExpandLevel=1

	This is the default option.

minExpandLevel=2

	Top-level nodes are always expanded, so the expander icon is hidden.

minExpandLevel=3.

		jquery.dynatree.js project home
		Link to this page
		Example Browser
		View source code


text:
atom-sync is an Atom package to sync files bidirectionally between remote host and local over ssh+rsync. Inspired by [Sublime SFTP](http://wbond.net/sublime_packages/sftp).

[![experimental](http://badges.github.io/stability-badges/dist/experimental.svg)](http://github.com/badges/stability-badges)[![Build Status](https://travis-ci.org/dingjie/atom-sync.svg?branch=master)](https://travis-ci.org/dingjie/atom-sync)

> This package is currently in early development and has only been tested on Mac. Please kindly [try it out](http://atom.io/packages/atom-sync) and [provide feedback](https://github.com/dingjie/atom-sync/issues/new).

![atom-sync](https://cloud.githubusercontent.com/assets/586262/8085519/2b63a7c4-0fc3-11e5-930a-685b09fe7af3.gif)

### Feature ###
* Sync over ssh+rsync — still [secure](http://www.sakana.fr/blog/2008/05/07/securing-automated-rsync-over-ssh/), but much [faster](http://stackoverflow.com/questions/20244585/what-is-the-difference-between-scp-and-rsync).
* [Multi-Folder Projects](http://blog.atom.io/2015/04/15/multi-folder-projects.html) with different sync config files supported
* Triggers conditionally run commands after successful uploading

### Prerequisite ###
* Ensure you have `ssh` and `rsync` installed.

### Quick Start ###
* Open a project folder to sync in [Atom](http://atom.io).
* Right click on the project folder and select `Sync` -> `Edit Remote Config`.
* Edit and save the config file.
* Right click on the project folder and select `Sync` -> `Sync Remote -> Local`.
* Watch water flows.

### Notice ###
* Password based login is not supported—at least yet, you have to [assign your key file](https://www.linode.com/docs/security/use-public-key-authentication-with-ssh) and better host name in .ssh/config in advanced. Try to [Simplify Your Life With an SSH Config File](http://nerderati.com/2011/03/17/simplify-your-life-with-an-ssh-config-file/).

### Config File (and Tutorial) ###
> .sync-config.cson

```
remote:
    host: "HOSTNAME",       # server name or ip or ssh host abbr in .ssh/config
    user: "USERNAME",       # ssh username
    path: "REMOTE_DIR"      # e.g. /home/someone/somewhere

behaviour:
    uploadOnSave: true      # Upload every time you save a file
    syncDownOnOpen: true    # Download every time you open a file
    forgetConsole: false    # Never show console panel even while syncing
    autoHideConsole: true   # Hide console automatically after 1.5s
    alwaysSyncAll: false    # Sync all files and folders under the project \
                            # instead of syncing single file or folder
option:
    deleteFiles: true       # Delete files during syncing
    autoHideDelay: 1500     # Time delay to hide console
    exclude: [              # Excluding patterns
        '.sync-config.cson'
        '.git'
        'node_modules'
        'tmp'
        'vendor'
    ]
    flags: 'avzpur'         # Advanced option: rsync flags
    shell: 'ssh'
trigger:                    # Triggers fire after uploading file successfully
                            # which STARTS with following patterns

    "*": "uptime"            # Wildcard trigger for any file uploaded

    "resources/scripts/coffee": [   # Any file under %PROJECT_ROOT%/resources/scripts/coffee \
                                    # being uploaded will fire this trigger

        "echo Compile coffeescript to js ..."
        "coffee -b --output js/ --compile coffee/"
        "ls public/js/|xargs -I@ echo \\t@"       # You can also pipe commands but don't \
                                                  # forget to escape special characters
    ]
    "resources/scripts/sass": [
        "echo Compile sass to css ..."
        "sass --update resources/scripts/sass:public/css"
    ]
```

### Introduction to Trigger ###
#### Config ####
```
trigger:
    "*": [
        "echo \'<span class=warning>Every time you\\'ll see me</span>\'"
    ]
    "coffee": [
        "echo Compile coffeescript to js ..."
        "mkdir -p js"
        "coffee -b --output js/ --compile coffee/"
        "ls js/|xargs -I@ echo \\t@"
    ]
    "sass/style.sass": [
        "echo Compile sass to css ..."
        "mkdir -p css"
        "sass --update sass:css"
    ]
```
#### Result ####
![trigger](https://cloud.githubusercontent.com/assets/586262/14584004/a2cf2872-0466-11e6-9908-5f035a8b4e46.gif)

#### Suggestion ####
Trigger is implemented via ssh, it would be great to use triggers with SSH ControlMaster by transferring data through single ssh tunnel instead of making one ssh connection for rsync and another for ssh command, which could be very slow under unideal network speed or connection limits.

###### Config sample of ~/.ssh/config ######

```
Host *
    ControlMaster auto
    ControlPath ~/.ssh/ssh-%r@%h:%p
    ControlPersist 10m
    ServerAliveInterval 30
```

### Keybindings ###
* `ctrl`+`alt`+`l` (Windows/Linux) `cmd`+`alt`+`l` (Mac) Toggle log window

### Known Problems ###
* You have to `Sync Local -> Remote` manually after renaming and deleting files.

### Roadmap ###
* Listen to events
  * Create folders
  * Rename files/folders
  * What about deleting?


text:
package com.thesimego.senacrs.sistemasdistribuidos.waserver.dao;

import com.thesimego.senacrs.sistemasdistribuidos.waserver.entity.AccountEN;
import com.thesimego.senacrs.sistemasdistribuidos.waserver.entity.FriendEN;
import java.io.Serializable;
import java.util.List;
import org.springframework.stereotype.Repository;

/**
 *
 * @author drafaelli
 */
@Repository
public class FriendDAO extends GenericDAO<FriendEN> implements Serializable {

    public List<FriendEN> findByAccount(AccountEN account) {
        return findByAccountId(account.getId());
    }

    public List<FriendEN> findByAccountId(Integer id) {
        return list(new DBField("account", id));
    }

    public void create(AccountEN account, String friend) {
        insert(
                new DBField("friend", friend),
                new DBField("account", account.getId())
        );
    }

    public FriendEN findByAccountAndFriend(AccountEN account, AccountEN friend) {
        return find(
                new DBField("account", account.getId()),
                new DBField("friend", friend.getLogin())
        );
    }

}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Fl. moeno-francof. 2:96. 1778

#### Original name
Carex acuta var. nigra

### Remarks
null


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SuperGLU
{
    public class StorageToken
    {
        public static String ID_KEY = "id";
        public static String CLASS_ID_KEY = "classId";

        private static HashSet<String> reservedKeys = new HashSet<String>();

        public Dictionary<String, Object> data
        { get; set; }

        static StorageToken()
        {
            reservedKeys.Add(ID_KEY);
            reservedKeys.Add(CLASS_ID_KEY);
        }

        public StorageToken()
        {
            this.data = new Dictionary<string, object>();
        }

        public StorageToken(Dictionary<String, Object> data, String id, String classId)
        {
            this.data = data;
            if (data == null)
                data = new Dictionary<string, object>();

            if (id != null)
            {
                this.setId(id);
            }
            else if (!this.data.Keys.Contains(ID_KEY))
            {
                this.data.Add(ID_KEY, System.Guid.NewGuid().ToString());
            }

            if (classId != null)
            {
                this.setClassId(classId);
            }

        }

        public String getId()
        {
            return (String)this.data[ID_KEY];
        }

        public void setId(String id)
        {
            this.data[ID_KEY] = id;
        }

        public String getClassId()
        {
            return (String)this.data[CLASS_ID_KEY];
        }

        public void setClassId(String classId)
        {
            this.data[CLASS_ID_KEY] = classId;
        }

        public int getSize()
        {
            return data.Count;
        }

        public bool contains(String key)
        {
            return this.data.ContainsKey(key);
        }

        public Object getItem(String key, bool hasDefault, Object defalt)
        {
            if (hasDefault)
                if (this.data.ContainsKey(key))
                    return this.data[key];
                else
                    return defalt;
            else
                return this.data[key];
        }

        public void setItem(String key, Object value)
        {
            this.data[key] = value;
        }

        public void removeItem(String key)
        {
            this.data.Remove(key);
        }

        public Object getItem(String key)
        {
            return this.getItem(key, false, null);
        }
    }
 }


text:
package me.devphp.CrystalBansql;

import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;

public class EventListener implements Listener {
	private Core plugin;

	public EventListener(Core plugin) {
		this.plugin = plugin;
	}

	@EventHandler(priority = EventPriority.LOW)
	public void onPlayerJoinEvent(PlayerJoinEvent event) {
		Player player = event.getPlayer();

		try {
			this.plugin.connection = DriverManager.getConnection(this.plugin.url, this.plugin.user, this.plugin.passwd);
			this.plugin.state = this.plugin.connection.createStatement();

			String query = "SELECT reason FROM `bansql` WHERE `uid` LIKE '"
					+ player.getUniqueId().toString()
					+ "' OR `ip` LIKE '"
					+ player.getAddress().getAddress().getHostAddress()
							.toString() + "'";
			ResultSet result = this.plugin.state.executeQuery(query);

			// Petit delay pour le kick
			Thread.sleep(50L);
				while(result.next()) {
					player.kickPlayer(result.getString("reason"));
				return;
				}

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}


text:
require 'spec_helper'

describe SimpleHtml do
  it 'has a version number' do
    expect(SimpleHtml::VERSION).not_to be nil
  end

  describe SimpleHtml::Tag do
    describe "#to_html" do
      it "generates HTML for header level 1" do
        tag = SimpleHtml::Tag.new("h1", "Hello world")
        expect(tag.to_html).to eq("
Hello world
")
      end

      it "generates HTML for anchor" do
        tag = SimpleHtml::Tag.new("a", "Le Wagon", href: "http://www.lewagon.org")
        expect(tag.to_html).to eq('Le Wagon')
      end

      it "does not depend on attributes order" do
        tag_class_after = SimpleHtml::Tag.new("a", "Le Wagon", href: "http://www.lewagon.org", class: 'btn').to_html
        tag_class_before = SimpleHtml::Tag.new("a", "Le Wagon", class: 'btn', href: "http://www.lewagon.org").to_html
        expect(tag_class_after).to eq(tag_class_before)
      end
    end
  end
end


text:
package net.sf.jailer.ui;

import java.awt.Color;
import java.awt.Component;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.swing.DefaultCellEditor;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.RowSorter.SortKey;
import javax.swing.SortOrder;
import javax.swing.SwingConstants;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

import net.sf.jailer.datamodel.Association;
import net.sf.jailer.datamodel.DataModel;
import net.sf.jailer.datamodel.Table;

/**
 * Pending Decisions Panel.
 *
 * @author Ralf Wisser
 */
@SuppressWarnings("serial")
public abstract class PendingDecisionsPanel extends javax.swing.JPanel {

	private final DataModel dataModel;
	private final ExtractionModelEditor extractionModelEditor;

	private List<Association> atBorder = new ArrayList<Association>();
	private Set<Association> checked = new HashSet<Association>();

	/**
	 * Creates new form PendingDecisionsPanel
	 */
	public PendingDecisionsPanel(DataModel dataModel, ExtractionModelEditor extractionModelEditor) {
		this.dataModel = dataModel;
		this.extractionModelEditor = extractionModelEditor;
		initComponents();

		DefaultTableCellRenderer associationsListItemRenderer = new DefaultTableCellRenderer() {
			final Color BG_SELCOLOR = new Color(0.45f, 0.85f, 1.0f);
			final Color BG1 = UIUtil.TABLE_BACKGROUND_COLOR_1;
			final Color BG2 = UIUtil.TABLE_BACKGROUND_COLOR_2;

			@Override
			public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
					boolean hasFocus, int row, int column) {
				if (value == null) {
					value = "";
				}
				if (column == 4) {
					isSelected = false;
				}
				Component render = super.getTableCellRendererComponent(table, value, isSelected, false, row, column);
				if (value instanceof Boolean) {
					JCheckBox checkBox = new JCheckBox(" ");
					checkBox.setHorizontalAlignment(SwingConstants.CENTER);
					checkBox.setSelected(Boolean.TRUE.equals(value));
					checkBox.setOpaque(true);
					render = checkBox;
				}
				render.setBackground(isSelected ? BG_SELCOLOR : (row % 2 == 0) ? BG1 : BG2);
				render.setForeground(Color.BLACK);
				if (render instanceof JLabel) {
					((JLabel) render).setToolTipText(UIUtil.toHTML(String.valueOf(value), 100));
				}
				return render;
			}

			private static final long serialVersionUID = -6057505075587930064L;
		};
		associationsTable.setModel(createAssociationsListModel());
		associationsTable.setDefaultRenderer(Object.class, associationsListItemRenderer);
		associationsTable.setDefaultRenderer(Boolean.class, associationsListItemRenderer);
		associationsTable.getColumnModel().getColumn(4).setCellRenderer(associationsListItemRenderer);

		associationsTable.setAutoCreateRowSorter(true);
		associationsTable.setShowVerticalLines(false);
		associationsTable.setShowHorizontalLines(false);

		associationsTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		associationsTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
			@Override
			public void valueChanged(ListSelectionEvent e) {
				if (associationsTable.getSelectedRow() >= 0) {
					if (!ignoreSelection) {
						select(atBorder.get(associationsTable.getRowSorter().convertRowIndexToModel(associationsTable.getSelectedRow())));
					}
				}
			}
		});

		initRowSorter(associationsTable);

		updateView();
	}

	private boolean activated = false;
	private boolean updatePending = false;
	private boolean ignoreSelection = false;

	void updateView() {
		if (updatePending) {
			return;
		}
		updatePending = true;
		UIUtil.invokeLater(new Runnable() {
			@Override
			public void run() {
				try {
					Association selected = null;
					if (associationsTable.getSelectedRow() >= 0) {
						selected = atBorder.get(associationsTable.getRowSorter().convertRowIndexToModel(associationsTable.getSelectedRow()));
					}
					for (Iterator<Association> i = atBorder.iterator(); i.hasNext(); ) {
						if (!checked.contains(i.next())) {
							i.remove();
						}
					}
					Set<Association> atBorderSet = new HashSet<Association>(atBorder);
					Set
 closure = extractionModelEditor.getCurrentSubjectClosure();
					for (String a : dataModel.decisionPending) {
						Association association = dataModel.namedAssociations.get(a);
						if (association != null) {
							if (closure.contains(association.source) || closure.contains(association.destination)) {
								if (!atBorderSet.contains(association.reversalAssociation)) {
									atBorder.add(association.reversalAssociation);
									atBorderSet.add(association.reversalAssociation);
								}
							}
						}
					}

					Collections.sort(atBorder, new Comparator<Association>() {

						@Override
						public int compare(Association o1, Association o2) {
							int c = dataModel.getDisplayName(o1.source).compareTo(dataModel.getDisplayName(o2.source));
							if (c != 0) {
								return c;
							}
							c = dataModel.getDisplayName(o1.destination).compareTo(dataModel.getDisplayName(o2.destination));
							if (c != 0) {
								return c;
							}
							return o1.getName().compareTo(o2.getName());
						}
					});

					List<? extends SortKey> sortKeys = new ArrayList<>(associationsTable.getRowSorter().getSortKeys());
					associationsTable.setModel(createAssociationsListModel());
					try {
						associationsTable.getRowSorter().setSortKeys(sortKeys);
					} catch (Throwable t) {
						// ignore
					}
					selectAssociation(selected);

					adjustTableColumnsWidth(associationsTable);

					boolean hasChecked = false;
					for (Association association: atBorder) {
						if (checked.contains(association)) {
							hasChecked = true;
							break;
						}
					}

					checkAllButton.setEnabled(!checked.containsAll(atBorder));
					uncheckAllButton.setEnabled(hasChecked);
					clearButton.setEnabled(hasChecked);

					if (checked.containsAll(atBorder)) {
						if (activated) {
							deactivate();
							activated = false;
						}
					} else {
						if (!activated) {
							activate();
							activated = true;
						}
					}
				} finally {
					updatePending = false;
				}
			}
		});
	}

	private void initRowSorter(JTable table) {
		TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(table.getModel()) {
			@Override
			protected boolean useToString(int column) {
				return false;
			}

			@Override
			public void toggleSortOrder(int column) {
				List<? extends SortKey> sortKeys = getSortKeys();
				if (sortKeys.size() > 0) {
					if (sortKeys.get(0).getSortOrder() == SortOrder.DESCENDING) {
						setSortKeys(null);
						return;
					}
				}
				super.toggleSortOrder(column);
			}
		};
		table.setRowSorter(sorter);
	}

	public void adjustTableColumnsWidth(JTable table) {
		DefaultTableModel dtm = (DefaultTableModel) table.getModel();
		DefaultTableCellRenderer defaultTableCellRenderer = new DefaultTableCellRenderer();
		for (int i = 0; i < table.getColumnCount(); i++) {
			TableColumn column = table.getColumnModel().getColumn(i);
			Component comp = defaultTableCellRenderer.getTableCellRendererComponent(table, column.getHeaderValue(),
					false, false, 0, i);
			int width = 1;
			width = Math.max(width, comp.getPreferredSize().width);

			int line = 0;
			for (; line
= 2) {
				width = Math.min(width, 200);
			}
			column.setPreferredWidth(width);
		}
		table.getColumnModel().getColumn(table.getColumnModel().getColumnCount() - 1).setPreferredWidth(120);
	}

	/**
	 * Creates model for associations-list component.
	 *
	 * @return model for associations-list component
	 */
	private TableModel createAssociationsListModel() {
		DefaultTableModel associationsTableModel = new DefaultTableModel(
				new Object[] { "From", "To", "Condition", "Name", "Checked" }, 0) {
			@Override
			public boolean isCellEditable(int row, int column) {
				return column == 4;
			}
			@Override
            public Class<?> getColumnClass(int columnIndex) {
                if(columnIndex == 4) {
                    return Boolean.class;
                }
                return super.getColumnClass(columnIndex);
            }
			@Override
			public void setValueAt(Object aValue, int row, int column) {
				super.setValueAt(aValue, row, column);
				final Association association = atBorder.get(row);
				if (Boolean.TRUE.equals(aValue)) {
					decisionMade(association);
				} else {
					decisionUndone(association);
				}
			}
		};

		final JCheckBox checkBox = new JCheckBox(" ");
		checkBox.setOpaque(true);
		checkBox.setHorizontalAlignment(SwingConstants.CENTER);
		DefaultCellEditor anEditor = new DefaultCellEditor(checkBox);
		anEditor.setClickCountToStart(1);
		associationsTable.setDefaultEditor(Boolean.class, anEditor);

		for (Association a: atBorder) {
			String name = a.reversalAssociation.getName();
			associationsTableModel.addRow(
					new Object[] {
							dataModel.getDisplayName(a.source),
							dataModel.getDisplayName(a.destination),
							a.getUnrestrictedJoinCondition(),
							name,
							checked.contains(a) });
		}
		return associationsTableModel;
	}

	private void select(Association association) {
		if (!extractionModelEditor.select(association)) {
			extractionModelEditor.setRootSelection(association.destination);
			extractionModelEditor.select(association);
		}
	}

	/**
	 * Removes an association from "pendingDecisions" list.
	 *
	 * @param association the association
	 */
	public void decisionMade(Association association) {
		checked.add(association);
		dataModel.decisionPending.remove(association.reversalAssociation.getName());
		decisionMade = true;
		markDirty();
		updateView();
	}

	/**
	 * Adds an association to "pendingDecisions" list.
	 *
	 * @param association the association
	 */
	public void decisionUndone(Association association) {
		dataModel.decisionPending.add(association.reversalAssociation.getName());
		checked.remove(association);

		markDirty();
		updateView();
	}

	protected boolean decisionMade = false;

	protected abstract void toggleDockingState();
	protected abstract void activate();
	protected abstract void deactivate();
	protected abstract void markDirty();

	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Form Editor.
	 */
	// <editor-fold defaultstate="collapsed" desc="Generated
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        jPanel1 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        associationsTable = new javax.swing.JTable();
        jPanel2 = new javax.swing.JPanel();
        dockButton = new javax.swing.JButton();
        checkAllButton = new javax.swing.JButton();
        uncheckAllButton = new javax.swing.JButton();
        clearButton = new javax.swing.JButton();
        infoPanel = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();

        setLayout(new java.awt.GridLayout(1, 0));

        jPanel1.setLayout(new java.awt.GridBagLayout());

        associationsTable.setAutoCreateRowSorter(true);
        associationsTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane2.setViewportView(associationsTable);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        jPanel1.add(jScrollPane2, gridBagConstraints);

        jPanel2.setLayout(new java.awt.GridBagLayout());

        dockButton.setText("Dock");
        dockButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                dockButtonActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
        gridBagConstraints.weightx = 1.0;
        jPanel2.add(dockButton, gridBagConstraints);

        checkAllButton.setText("Check all");
        checkAllButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                checkAllButtonActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 5;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(2, 0, 0, 0);
        jPanel2.add(checkAllButton, gridBagConstraints);

        uncheckAllButton.setText("Uncheck all");
        uncheckAllButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                uncheckAllButtonActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 8;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(2, 0, 0, 0);
        jPanel2.add(uncheckAllButton, gridBagConstraints);

        clearButton.setText("Clear");
        clearButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clearButtonActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 14;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(2, 0, 0, 0);
        jPanel2.add(clearButton, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.insets = new java.awt.Insets(0, 4, 0, 0);
        jPanel1.add(jPanel2, gridBagConstraints);

        infoPanel.setBackground(new java.awt.Color(250, 255, 255));
        infoPanel.setLayout(new java.awt.GridBagLayout());

        jLabel1.setForeground(new java.awt.Color(0, 0, 62));
        jLabel1.setText("\nThis tool allows you to find and edit the newly added associations if the data model has been extended after the last change to this extraction model.
\nSelect associations here in the table and define restrictions, or check off an association if you're comfortable with the given restriction.\n");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2);
        infoPanel.add(jLabel1, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2);
        jPanel1.add(infoPanel, gridBagConstraints);

        add(jPanel1);
    }// </editor-fold>//GEN-END:initComponents

    private void dockButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_dockButtonActionPerformed
        toggleDockingState();
    }//GEN-LAST:event_dockButtonActionPerformed

    private void checkAllButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkAllButtonActionPerformed
        List<Association> associations = new ArrayList<Association>();
    	for (Association association: atBorder) {
        	if (!checked.contains(association)) {
        		associations.add(association);
        	}
        }
    	for (Association association: associations) {
    		decisionMade(association);
    	}
    }//GEN-LAST:event_checkAllButtonActionPerformed

    private void uncheckAllButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_uncheckAllButtonActionPerformed
        List<Association> associations = new ArrayList<Association>();
        Set<Association> atBorderSet = new HashSet<Association>(atBorder);
        for (Association association: checked) {
        	if (atBorderSet.contains(association)) {
        		associations.add(association);
        	}
        }
    	for (Association association: associations) {
    		decisionUndone(association);
    	}
    }//GEN-LAST:event_uncheckAllButtonActionPerformed

    private void clearButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clearButtonActionPerformed
        checked.clear();
        updateView();
    }//GEN-LAST:event_clearButtonActionPerformed

    public void selectAssociation(Association selected) {
		if (selected != null) {
			int i = atBorder.indexOf(selected);
			if (i < 0) {
				i = atBorder.indexOf(selected.reversalAssociation);
			}
			if (i >= 0) {
				try {
					ignoreSelection = true;
					i = associationsTable.getRowSorter().convertRowIndexToView(i);
					associationsTable.getSelectionModel().setSelectionInterval(i, i);
				} finally {
					ignoreSelection = false;
				}
			}
		}
	}

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTable associationsTable;
    protected javax.swing.JButton checkAllButton;
    protected javax.swing.JButton clearButton;
    protected javax.swing.JButton dockButton;
    protected javax.swing.JPanel infoPanel;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane2;
    protected javax.swing.JButton uncheckAllButton;
    // End of variables declaration//GEN-END:variables

}


text:
package org.ofbiz.base.conversion;

import java.util.HashSet;
import java.util.Set;

public class GenericSingletonToSet<T> extends AbstractConverter<T, Set<T>> {
    public GenericSingletonToSet(Class<T> sourceClass) {
        super(sourceClass, Set.class);
    }

    public Set<T> convert(T obj) throws ConversionException {
        Set<T> tempSet = new HashSet<>();
        tempSet.add(obj);
        return tempSet;
    }
}


text:
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections;
using System;

public class TooltipHint : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler {
	[TextArea]
	public string tooltipText;
	public BaseTooltip tooltip;

	public void Start() {
		if (this.tooltipText.Length <= 0) {
			this.tooltipText = "Hello world.";
		}
		Canvas canvas = GameObject.FindObjectOfType<Canvas>();
		if (canvas != null) {
			TooltipLocator loc = canvas.GetComponent<TooltipLocator>();
			if (loc.tooltip != null) {
				this.tooltip = loc.tooltip;
			}
			else {
				Debug.LogError("Something is wrong.");
			}
		}
	}

	public void OnPointerEnter(PointerEventData eventData) {
		this.tooltip.SetTarget(this.GetComponent<RectTransform>());
		this.tooltip.SetText(this.tooltipText);
		this.tooltip.SetToolTipHidden(false);
	}

	public void OnPointerExit(PointerEventData eventData) {
		this.tooltip.SetToolTipHidden(true);
	}
}


text:
module BlacklistHelper
  def blacklist_load
    blacklist = Highscore::Blacklist.load_file "../assets/blacklist.txt"
  end
end


text:
package us.ihmc.aci.dspro2;

import us.ihmc.aci.util.dspro.NodePath;

/**
 * @author Maggie Breedy    (mbreedy@ihmc.us)
 * @author Giacomo Benincasa    (gbenincasa@ihmc.us)
 */
public interface DSProProxyListener
{
    public boolean pathRegistered (NodePath path, String nodeId, String teamId, String mission);

    public boolean positionUpdated (float latitude, float longitude, float altitude, String nodeId);

    public void newNeighbor (String peerID);
    public void deadNeighbor (String peerID);

     /**
     * Callback function that is invoked when new data arrives.
     *
     * @param dsproId - id of the arrived metadata message.
     * @param groupName - the name of the group the metadata message belongs to.
     * @param objectId
     * @param instanceId
     * @param annotatedObjMsgId
     * @param mimeType
     * @param data - the data that was received.
     * @param chunkNumber - the number of chunks.
     * @param totChunksNumber - the total number of chunks
     * @param callbackParameters
     * @return
     */
    public boolean dataArrived (String dsproId, String groupName, String objectId,
                                String instanceId, String annotatedObjMsgId,
                                String mimeType, byte[] data, short chunkNumber,
                                short totChunksNumber, String callbackParameters);

    /**
     * Callback function that is invoked when new metadata arrives.
     *
     * @param dsproId - id of the arrived metadata message.
     * @param groupName
     * @param referredDataObjectId
     * @param referredDataInstanceId
     * @param callbackParameters
     * @groupName - the name of the group the metadata message belongs to.
     * @param XMLMetadata - the XML metadata.
     * @param referredDataDsproId - referred data id of the message.
     * @return
     */
    public boolean metadataArrived (String dsproId, String groupName, String referredDataObjectId,
                                    String referredDataInstanceId, String XMLMetadata,
                                    String referredDataDsproId, String callbackParameters);
}


text:
#pragma once
#include <aws/imagebuilder/Imagebuilder_EXPORTS.h>
#include <aws/imagebuilder/ImagebuilderRequest.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/imagebuilder/model/Filter.h>
#include <utility>

namespace Aws
{
namespace imagebuilder
{
namespace Model
{

  /**
   */
  class AWS_IMAGEBUILDER_API ListInfrastructureConfigurationsRequest : public ImagebuilderRequest
  {
  public:
    ListInfrastructureConfigurationsRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "ListInfrastructureConfigurations"; }

    Aws::String SerializePayload() const override;

    /**
     *
You can filter on name to streamline results.

     */
    inline const Aws::Vector<Filter>& GetFilters() const{ return m_filters; }

    /**
     *
You can filter on name to streamline results.

     */
    inline bool FiltersHasBeenSet() const { return m_filtersHasBeenSet; }

    /**
     *
You can filter on name to streamline results.

     */
    inline void SetFilters(const Aws::Vector<Filter>& value) { m_filtersHasBeenSet = true; m_filters = value; }

    /**
     *
You can filter on name to streamline results.

     */
    inline void SetFilters(Aws::Vector<Filter>&& value) { m_filtersHasBeenSet = true; m_filters = std::move(value); }

    /**
     *
You can filter on name to streamline results.

     */
    inline ListInfrastructureConfigurationsRequest& WithFilters(const Aws::Vector<Filter>& value) { SetFilters(value); return *this;}

    /**
     *
You can filter on name to streamline results.

     */
    inline ListInfrastructureConfigurationsRequest& WithFilters(Aws::Vector<Filter>&& value) { SetFilters(std::move(value)); return *this;}

    /**
     *
You can filter on name to streamline results.

     */
    inline ListInfrastructureConfigurationsRequest& AddFilters(const Filter& value) { m_filtersHasBeenSet = true; m_filters.push_back(value); return *this; }

    /**
     *
You can filter on name to streamline results.

     */
    inline ListInfrastructureConfigurationsRequest& AddFilters(Filter&& value) { m_filtersHasBeenSet = true; m_filters.push_back(std::move(value)); return *this; }

    /**
     *
The maximum items to return in a request.

     */
    inline int GetMaxResults() const{ return m_maxResults; }

    /**
     *
The maximum items to return in a request.

     */
    inline bool MaxResultsHasBeenSet() const { return m_maxResultsHasBeenSet; }

    /**
     *
The maximum items to return in a request.

     */
    inline void SetMaxResults(int value) { m_maxResultsHasBeenSet = true; m_maxResults = value; }

    /**
     *
The maximum items to return in a request.

     */
    inline ListInfrastructureConfigurationsRequest& WithMaxResults(int value) { SetMaxResults(value); return *this;}

    /**
     *
A token to specify where to start paginating. This is the NextToken from a
     * previously truncated response.

     */
    inline const Aws::String& GetNextToken() const{ return m_nextToken; }

    /**
     *
A token to specify where to start paginating. This is the NextToken from a
     * previously truncated response.

     */
    inline bool NextTokenHasBeenSet() const { return m_nextTokenHasBeenSet; }

    /**
     *
A token to specify where to start paginating. This is the NextToken from a
     * previously truncated response.

     */
    inline void SetNextToken(const Aws::String& value) { m_nextTokenHasBeenSet = true; m_nextToken = value; }

    /**
     *
A token to specify where to start paginating. This is the NextToken from a
     * previously truncated response.

     */
    inline void SetNextToken(Aws::String&& value) { m_nextTokenHasBeenSet = true; m_nextToken = std::move(value); }

    /**
     *
A token to specify where to start paginating. This is the NextToken from a
     * previously truncated response.

     */
    inline void SetNextToken(const char* value) { m_nextTokenHasBeenSet = true; m_nextToken.assign(value); }

    /**
     *
A token to specify where to start paginating. This is the NextToken from a
     * previously truncated response.

     */
    inline ListInfrastructureConfigurationsRequest& WithNextToken(const Aws::String& value) { SetNextToken(value); return *this;}

    /**
     *
A token to specify where to start paginating. This is the NextToken from a
     * previously truncated response.

     */
    inline ListInfrastructureConfigurationsRequest& WithNextToken(Aws::String&& value) { SetNextToken(std::move(value)); return *this;}

    /**
     *
A token to specify where to start paginating. This is the NextToken from a
     * previously truncated response.

     */
    inline ListInfrastructureConfigurationsRequest& WithNextToken(const char* value) { SetNextToken(value); return *this;}

  private:

    Aws::Vector<Filter> m_filters;
    bool m_filtersHasBeenSet = false;

    int m_maxResults;
    bool m_maxResultsHasBeenSet = false;

    Aws::String m_nextToken;
    bool m_nextTokenHasBeenSet = false;
  };

} // namespace Model
} // namespace imagebuilder
} // namespace Aws


text:
DART_SDK="/home/dis/bin/dart/dart-sdk"
TEST_WEB_PORT=8889
# Checking content_shell
CS_PATH=$(ls -d drt-*)
if [ -z "$CS_PATH" ]; then
 echo "Not found content_shell dir"
else
 PATH=$CS_PATH:$PATH
 echo "content_shell detect"
fi

# Checking content_shell
which content_shell
if [[ $? -ne 0 ]]; then
  $DART_SDK/../chromium/download_contentshell.sh
  unzip content_shell-linux-x64-release.zip

  CS_PATH=$(ls -d drt-*)
  PATH=$CS_PATH:$PATH
fi

echo "content_shell -> '$CS_PATH'"
echo "Please run dart ./bin/test.dart"
exit 0

# Static type analysis....
results=$($DART_SDK/bin/dartanalyzer lib/*.dart 2>&1)
echo "$results"
if [[ "$results" != *"No issues found"* ]]
then
    exit 1
fi
echo "Looks good!"

$DART_SDK/bin/pub serve test --port $TEST_WEB_PORT &
pub_pid=$!

# Wait for server to build elements and spin up...
sleep 3

# Run a set of Dart Unit tests
results=$(content_shell --dump-render-tree --allow-file-access-from-files test/index.html http://localhost:$TEST_WEB_PORT)
echo -e "$results"

kill $pub_pid


text:
#pragma once

#include <map>
#include <string>
#include <vector>
#include "paddle/fluid/framework/op_info.h"
#include "paddle/fluid/framework/program_desc.h"
#include "paddle/fluid/framework/scope.h"
#include "paddle/fluid/framework/tensor.h"
#include "paddle/fluid/platform/device_context.h"

namespace paddle {
namespace framework {
extern void InitializeVariable(Variable* var, proto::VarType::Type var_type);

struct ExecutorPrepareContext {
  ExecutorPrepareContext(const framework::ProgramDesc& prog, size_t block_id);
  ~ExecutorPrepareContext();

  const framework::ProgramDesc& prog_;
  size_t block_id_;
  std::vector<std::unique_ptr<OperatorBase>> ops_;
};

class Executor {
 public:
  // TODO(dzhwinter) : Do not rely on this function, it will be removed
  explicit Executor(const platform::DeviceContext& device)
      : Executor(device.GetPlace()) {}

  explicit Executor(const platform::Place& place);

  /* @Brief
   * Runtime evaluation of the given ProgramDesc under certain Scope
   *
   * @param
   *  ProgramDesc
   *  Scope
   */
  void Run(const ProgramDesc& prog, Scope* scope, int block_id,
           bool create_local_scope = true, bool create_vars = true);

  void Run(const ProgramDesc& program, Scope* scope,
           std::map<std::string, const LoDTensor*>* feed_targets,
           std::map<std::string, LoDTensor*>* fetch_targets,
           bool create_local_scope = true, bool create_vars = true,
           const std::string& feed_holder_name = "feed",
           const std::string& fetch_holder_name = "fetch");

  static std::unique_ptr<ExecutorPrepareContext> Prepare(
      const ProgramDesc& program, int block_id);

  static std::vector<std::shared_ptr<ExecutorPrepareContext>> Prepare(
      const ProgramDesc& program, const std::vector<int>& block_ids);

  void CreateVariables(const ProgramDesc& pdesc, Scope* scope, int block_id);

  void RunPreparedContext(ExecutorPrepareContext* ctx, Scope* scope,
                          bool create_local_scope = true,
                          bool create_vars = true);

  void RunPreparedContext(ExecutorPrepareContext* ctx, Scope* scope,
                          std::map<std::string, const LoDTensor*>* feed_targets,
                          std::map<std::string, LoDTensor*>* fetch_targets,
                          bool create_local_scope = true,
                          bool create_vars = true,
                          const std::string& feed_holder_name = "feed",
                          const std::string& fetch_holder_name = "fetch");

 private:
  const platform::Place place_;
};

}  // namespace framework
}  // namespace paddle


text:
module Hyrax::HasRepresentative
  extend ActiveSupport::Concern

  included do
    belongs_to :representative,
               predicate: ::RDF::Vocab::EBUCore.hasRelatedMediaFragment,
               class_name: 'ActiveFedora::Base'

    belongs_to :thumbnail,
               predicate: ::RDF::Vocab::EBUCore.hasRelatedImage,
               class_name: 'ActiveFedora::Base'
  end
end


text:
class CScroller {
public:
    void Init(short id);
    void SendIcon(short graphic);
    void SendIdCode(short id);
    void RunPage(short id, short page);
    void PageStart(short id, short page);
    void PageAppend(const char* msg);
    void PageDone();
    void SetColor(short color);
    void SetFont(short color);
    void SetFontSize(short size);
    void Transition(short color);
    void PageWrite(short id, short page, short color, const char* msg);
    void Target(short id, short page, const char* name);
    void Target(short id, short page, short icon, const char* name);
    void Warning(short id, short page, const char* name);

private:
    bool WasSentBefore(short id, short page, short color, short font, short fontsize, const char* msg);

    short last_id;
    short last_page;
    short last_color;
    short last_font;
    short last_fontsize;
    char  last_msg[128];

};

extern CScroller scroller;

#endif


text:
{% extends login_template %}
{% load i18n %}

{% block title %}{% trans "Single Sign-On is misconfigured" %}{% endblock title %}

{% block login-content %}

              {% blocktrans %}
                Single Sign-On
              {% endblocktrans %}

            {% if is_saml and error.code == error.REDIRECT_INVALID_URL %}

                {% blocktrans %}
                  Your Redirect URL is invalid.
                {% endblocktrans %}

                {% blocktrans %}
                  The redirect URL you have specified is not valid. Please
                  remove the text after "next=" in the url to temporarily
                  resolve this issue. If the issue persists, please contact
                  support so we can find a permanent solution.
                {% endblocktrans %}

            {% elif is_oidc and error.code == error.OP_ERROR_MESSAGE %}

                {% blocktrans with request.idp.service_name as service %}
                  There was an issue logging in with {{ service }}:
                {% endblocktrans %}

                {{ error.message }}

            {% elif request.idp.is_active %}

                {% blocktrans with request.idp.name as idp_name %}
                  It looks like there is an issue with {{ idp_name }}'s configuration.
                {% endblocktrans %}

                {% blocktrans %}
                  Please reach out to support, so we can quickly resolve this
                  problem. Thank you!
                {% endblocktrans %}

            {% else %}
              {% if is_saml and error.code == error.SETTINGS_INVALID %}

                  {% blocktrans %}
                    It looks like your setup is not complete.
                  {% endblocktrans %}

                  {% blocktrans %}
                    Information seems to be missing from your SSO configuration.
                    Please review the documentation
                    for setting up SSO.
                  {% endblocktrans %}

              {% elif is_saml and error.code == error.CERT_NOT_FOUND %}

                  {% blocktrans %}
                    It looks like we are missing your certificate.
                  {% endblocktrans %}

                  {% blocktrans %}
                    It looks like your x509 certificate is missing from your
                    SSO setup.  Please review the
                    documentation
                    for setting up SSO.
                  {% endblocktrans %}

              {% elif is_oidc and error.code == error.USER_PERMISSION_ISSUE %}

                  {% blocktrans %}
                    Obtaining User Information Was Not Possible
                  {% endblocktrans %}

                  {% blocktrans %}
                    It looks like there was an issue obtaining the user's information from
                    your Identity Provider. Please review the documentation
                    for setting up SSO.
                  {% endblocktrans %}

              {% elif is_oidc and error.code == error.SESSION_UNKNOWN %}

                  {% blocktrans %}
                    OpenID Connect Session Unknown
                  {% endblocktrans %}

                  {% blocktrans %}
                    It looks like you tried to authenticate without a valid OpenID Connect Session.
                    Please review the documentation for setting up SSO.
                  {% endblocktrans %}

              {% elif is_oidc and error.code == error.METHOD_NOT_ALLOWED %}

                  {% blocktrans %}
                    OIDC Method Not Allowed
                  {% endblocktrans %}

                  {% blocktrans %}
                    You did not complete a full SSO handshake.
                    Please review the documentation for setting up SSO.
                  {% endblocktrans %}

              {% else %}

                  {% blocktrans %}
                    It looks like there is an issue with your SSO configuration.
                  {% endblocktrans %}

                  {% blocktrans with error.code as error_code %}
                    The error code is "{{ error_code }}". Please reach out to
                    your support contact with this information so we can
                    assist with this issue.
                  {% endblocktrans %}

              {% endif %}
            {% endif %}

{% endblock %}


text:
namespace blink {

class TreeScopeStyleSheetCollectionTest : public testing::Test {
protected:
    using SheetVector = WillBeHeapVector<RefPtrWillBeMember<CSSStyleSheet>>;
    using ContentsVector = WillBeHeapVector<RawPtrWillBeMember<StyleSheetContents>>;

    enum UpdateType {
        Reconstruct = TreeScopeStyleSheetCollection::Reconstruct,
        Reset = TreeScopeStyleSheetCollection::Reset,
        Additive = TreeScopeStyleSheetCollection::Additive
    };

    static PassRefPtrWillBeRawPtr<CSSStyleSheet> createSheet()
    {
        return CSSStyleSheet::create(StyleSheetContents::create(CSSParserContext(HTMLStandardMode, nullptr)));
    }

    static void compareStyleSheets(const SheetVector& oldStyleSheets, const SheetVector& newStyleSheets, const ContentsVector& expAddedSheets, UpdateType testUpdateType)
    {
        ContentsVector addedSheets;
        UpdateType updateType = static_cast<UpdateType>(TreeScopeStyleSheetCollection::compareStyleSheets(oldStyleSheets, newStyleSheets, addedSheets));
        EXPECT_EQ(testUpdateType, updateType);
        EXPECT_EQ(expAddedSheets.size(), addedSheets.size());
        if (expAddedSheets.size() == addedSheets.size()) {
            for (unsigned i = 0; i < addedSheets.size(); i++)
                EXPECT_EQ(expAddedSheets.at(i), addedSheets.at(i));
        }
    }
};

TEST_F(TreeScopeStyleSheetCollectionTest, CompareStyleSheetsAppend)
{
    RefPtrWillBeRawPtr<CSSStyleSheet> sheet1 = createSheet();
    RefPtrWillBeRawPtr<CSSStyleSheet> sheet2 = createSheet();

    ContentsVector added;
    SheetVector previous;
    SheetVector current;

    previous.append(sheet1);

    current.append(sheet1);
    current.append(sheet2);

    added.append(sheet2->contents());

    compareStyleSheets(previous, current, added, Additive);
}

TEST_F(TreeScopeStyleSheetCollectionTest, CompareStyleSheetsPrepend)
{
    RefPtrWillBeRawPtr<CSSStyleSheet> sheet1 = createSheet();
    RefPtrWillBeRawPtr<CSSStyleSheet> sheet2 = createSheet();

    ContentsVector added;
    SheetVector previous;
    SheetVector current;

    previous.append(sheet2);

    current.append(sheet1);
    current.append(sheet2);

    added.append(sheet1->contents());

    compareStyleSheets(previous, current, added, Reconstruct);
}

TEST_F(TreeScopeStyleSheetCollectionTest, CompareStyleSheetsInsert)
{
    RefPtrWillBeRawPtr<CSSStyleSheet> sheet1 = createSheet();
    RefPtrWillBeRawPtr<CSSStyleSheet> sheet2 = createSheet();
    RefPtrWillBeRawPtr<CSSStyleSheet> sheet3 = createSheet();

    ContentsVector added;
    SheetVector previous;
    SheetVector current;

    previous.append(sheet1);
    previous.append(sheet3);

    current.append(sheet1);
    current.append(sheet2);
    current.append(sheet3);

    added.append(sheet2->contents());

    compareStyleSheets(previous, current, added, Reconstruct);
}

TEST_F(TreeScopeStyleSheetCollectionTest, CompareStyleSheetsRemove)
{
    RefPtrWillBeRawPtr<CSSStyleSheet> sheet1 = createSheet();
    RefPtrWillBeRawPtr<CSSStyleSheet> sheet2 = createSheet();
    RefPtrWillBeRawPtr<CSSStyleSheet> sheet3 = createSheet();

    ContentsVector added;
    SheetVector previous;
    SheetVector current;

    previous.append(sheet1);
    previous.append(sheet2);
    previous.append(sheet3);

    current.append(sheet1);
    current.append(sheet3);

    added.append(sheet2->contents());

    // This is really the same as Insert. TreeScopeStyleSheetCollection::compareStyleSheets
    // will assert if you pass an array that is longer as the first parameter.
    compareStyleSheets(current, previous, added, Reconstruct);
}

TEST_F(TreeScopeStyleSheetCollectionTest, CompareStyleSheetsInsertRemove)
{
    RefPtrWillBeRawPtr<CSSStyleSheet> sheet1 = createSheet();
    RefPtrWillBeRawPtr<CSSStyleSheet> sheet2 = createSheet();
    RefPtrWillBeRawPtr<CSSStyleSheet> sheet3 = createSheet();

    ContentsVector added;
    SheetVector previous;
    SheetVector current;

    previous.append(sheet1);
    previous.append(sheet2);

    current.append(sheet2);
    current.append(sheet3);

    // TODO(rune@opera.com): This is clearly wrong. We add sheet3 and remove sheet1 and
    // compareStyleSheets returns sheet2 and sheet3 as added (crbug/475858).
    added.append(sheet2->contents());
    added.append(sheet3->contents());

    compareStyleSheets(previous, current, added, Reconstruct);
}

}


text:
#include <unistd.h>
#include <thread>
#include <chrono>
#include "ps/internal/postoffice.h"
#include "ps/internal/message.h"
#include "ps/base.h"

namespace ps {
Postoffice::Postoffice() {
  van_ = Van::Create("zmq");
  env_ref_ = Environment::_GetSharedRef();
}

void Postoffice::InitEnvironment() {
  const char* val = NULL;
  val = CHECK_NOTNULL(Environment::Get()->find("DMLC_NUM_WORKER"));
  num_workers_ = atoi(val);
  val =  CHECK_NOTNULL(Environment::Get()->find("DMLC_NUM_SERVER"));
  num_servers_ = atoi(val);
  val = CHECK_NOTNULL(Environment::Get()->find("DMLC_ROLE"));
  std::string role(val);
  is_worker_ = role == "worker";
  is_server_ = role == "server";
  is_scheduler_ = role == "scheduler";
  verbose_ = GetEnv("PS_VERBOSE", 0);
}

void Postoffice::Start(int customer_id, const char* argv0, const bool do_barrier) {
  start_mu_.lock();
  if (init_stage_ == 0) {
    InitEnvironment();
    // init glog
    if (argv0) {
      dmlc::InitLogging(argv0);
    } else {
      dmlc::InitLogging("ps-lite\0");
    }

    // init node info.
    for (int i = 0; i < num_workers_; ++i) {
      int id = WorkerRankToID(i);
      for (int g : {id, kWorkerGroup, kWorkerGroup + kServerGroup,
                    kWorkerGroup + kScheduler,
                    kWorkerGroup + kServerGroup + kScheduler}) {
        node_ids_[g].push_back(id);
      }
    }

    for (int i = 0; i < num_servers_; ++i) {
      int id = ServerRankToID(i);
      for (int g : {id, kServerGroup, kWorkerGroup + kServerGroup,
                    kServerGroup + kScheduler,
                    kWorkerGroup + kServerGroup + kScheduler}) {
        node_ids_[g].push_back(id);
      }
    }

    for (int g : {kScheduler, kScheduler + kServerGroup + kWorkerGroup,
                  kScheduler + kWorkerGroup, kScheduler + kServerGroup}) {
      node_ids_[g].push_back(kScheduler);
    }
    init_stage_++;
  }
  start_mu_.unlock();

  // start van
  van_->Start(customer_id);

  start_mu_.lock();
  if (init_stage_ == 1) {
    // record start time
    start_time_ = time(NULL);
    init_stage_++;
  }
  start_mu_.unlock();
  // do a barrier here
  if (do_barrier) Barrier(customer_id, kWorkerGroup + kServerGroup + kScheduler);
}

void Postoffice::Finalize(const int customer_id, const bool do_barrier) {
  if (do_barrier) Barrier(customer_id, kWorkerGroup + kServerGroup + kScheduler);
  if (customer_id == 0) {
    num_workers_ = 0;
    num_servers_ = 0;
    van_->Stop();
    init_stage_ = 0;
    customers_.clear();
    node_ids_.clear();
    barrier_done_.clear();
    server_key_ranges_.clear();
    heartbeats_.clear();
    if (exit_callback_) exit_callback_();
  }
}

void Postoffice::AddCustomer(Customer* customer) {
  std::lock_guard<std::mutex> lk(mu_);
  int app_id = CHECK_NOTNULL(customer)->app_id();
  // check if the customer id has existed
  int customer_id = CHECK_NOTNULL(customer)->customer_id();
  CHECK_EQ(customers_[app_id].count(customer_id), (size_t) 0) << "customer_id " \
    << customer_id << " already exists\n";
  customers_[app_id].insert(std::make_pair(customer_id, customer));
  std::unique_lock<std::mutex> ulk(barrier_mu_);
  barrier_done_[app_id].insert(std::make_pair(customer_id, false));
}

void Postoffice::RemoveCustomer(Customer* customer) {
  std::lock_guard<std::mutex> lk(mu_);
  int app_id = CHECK_NOTNULL(customer)->app_id();
  int customer_id = CHECK_NOTNULL(customer)->customer_id();
  customers_[app_id].erase(customer_id);
  if (customers_[app_id].empty()) {
    customers_.erase(app_id);
  }
}

Customer* Postoffice::GetCustomer(int app_id, int customer_id, int timeout) const {
  Customer* obj = nullptr;
  for (int i = 0; i < timeout * 1000 + 1; ++i) {
    {
      std::lock_guard<std::mutex> lk(mu_);
      const auto it = customers_.find(app_id);
      if (it != customers_.end()) {
        std::unordered_map<int, Customer*> customers_in_app = it->second;
        obj = customers_in_app[customer_id];
        break;
      }
    }
    std::this_thread::sleep_for(std::chrono::milliseconds(1));
  }
  return obj;
}

void Postoffice::Barrier(int customer_id, int node_group) {
  if (GetNodeIDs(node_group).size() <= 1) return;
  auto role = van_->my_node().role;
  if (role == Node::SCHEDULER) {
    CHECK(node_group & kScheduler);
  } else if (role == Node::WORKER) {
    CHECK(node_group & kWorkerGroup);
  } else if (role == Node::SERVER) {
    CHECK(node_group & kServerGroup);
  }

  std::unique_lock<std::mutex> ulk(barrier_mu_);
  barrier_done_[0][customer_id] = false;
  Message req;
  req.meta.recver = kScheduler;
  req.meta.request = true;
  req.meta.control.cmd = Control::BARRIER;
  req.meta.app_id = 0;
  req.meta.customer_id = customer_id;
  req.meta.control.barrier_group = node_group;
  req.meta.timestamp = van_->GetTimestamp();
  CHECK_GT(van_->Send(req), 0);
  barrier_cond_.wait(ulk, [this, customer_id] {
      return barrier_done_[0][customer_id];
    });
}

const std::vector<Range>& Postoffice::GetServerKeyRanges() {
  server_key_ranges_mu_.lock();
  if (server_key_ranges_.empty()) {
    for (int i = 0; i < num_servers_; ++i) {
      server_key_ranges_.push_back(Range(
          kMaxKey / num_servers_ * i,
          kMaxKey / num_servers_ * (i+1)));
    }
  }
  server_key_ranges_mu_.unlock();
  return server_key_ranges_;
}

void Postoffice::Manage(const Message& recv) {
  CHECK(!recv.meta.control.empty());
  const auto& ctrl = recv.meta.control;
  if (ctrl.cmd == Control::BARRIER && !recv.meta.request) {
    barrier_mu_.lock();
    for (int customer_id = 0; customer_id < barrier_done_[recv.meta.app_id].size();
         customer_id++) {
      barrier_done_[recv.meta.app_id][customer_id] = true;
    }
    barrier_mu_.unlock();
    barrier_cond_.notify_all();
  }
}

std::vector<int> Postoffice::GetDeadNodes(int t) {
  std::vector<int> dead_nodes;
  if (!van_->IsReady() || t == 0) return dead_nodes;

  time_t curr_time = time(NULL);
  const auto& nodes = is_scheduler_
    ? GetNodeIDs(kWorkerGroup + kServerGroup)
    : GetNodeIDs(kScheduler);
  {
    std::lock_guard<std::mutex> lk(heartbeat_mu_);
    for (int r : nodes) {
      auto it = heartbeats_.find(r);
      if ((it == heartbeats_.end() || it->second + t < curr_time)
            && start_time_ + t < curr_time) {
        dead_nodes.push_back(r);
      }
    }
  }
  return dead_nodes;
}
}  // namespace ps


text:
#import "HUPasswordChangeDialog.h"
#import "Utils.h"

@implementation HUPasswordChangeDialog{
    BOOL positionChanged;
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.userInteractionEnabled = YES;
        positionChanged = NO;
    }
    return self;
}

- (id) initWithText:(NSString *)text delegate:(id<HUDialogDelegate>)delegate cancelTitle:(NSString *)cancelTitle otherTitle:(NSArray *)otherTitle
{
    self = [super initWithText:@"" delegate:delegate cancelTitle:cancelTitle otherTitle:otherTitle];
    if (self) {
        self.userInteractionEnabled = YES;
        positionChanged = NO;
    }
    return self;
}

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    [super drawRect:rect];

    self.oldPasswordView = [[UITextField alloc] initWithFrame:CGRectMake(30, 30, 220, 30)];
    self.oldPasswordView.placeholder = NSLocalizedString(@"Enter current password",nil);
    self.oldPasswordView.secureTextEntry = YES;
    [self.oldPasswordView setBorderStyle:UITextBorderStyleBezel];
    [self addSubview:self.oldPasswordView];
    self.oldPasswordView.delegate = self;

    self.passwordView = [[UITextField alloc] initWithFrame:CGRectMake(30, 70, 220, 30)];
    self.passwordView.placeholder = NSLocalizedString(@"Enter new password",nil);
    self.passwordView.secureTextEntry = YES;
    [self.passwordView setBorderStyle:UITextBorderStyleBezel];
    [self addSubview:self.passwordView];
    self.passwordView.delegate = self;

    self.confirmPasswordView = [[UITextField alloc] initWithFrame:CGRectMake(30, 110, 220, 30)];
    self.confirmPasswordView.placeholder = NSLocalizedString(@"Re-enter new password",nil);
    self.confirmPasswordView.secureTextEntry = YES;
    [self.confirmPasswordView setBorderStyle:UITextBorderStyleBezel];
    [self addSubview:self.confirmPasswordView];
    self.confirmPasswordView.delegate = self;

}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self endEditing:YES];
}

- (CGRect) calculateFrameForText:(NSString *)text buttons:(NSArray *)buttons
{
    return CGRectMake(10, 10, 280, 220);
}

- (void)textFieldDidBeginEditing:(UITextField *)textField{

    if(positionChanged)
        return;

    positionChanged = YES;

    [UIView animateWithDuration:0.2
                     animations:^{
                         self.frame = CGRectMake(
                                                         self.x,
                                                         self.y,
                                                         self.width,
                                                         self.height- [Utils getKeyboardHeight]
                                                         );
                     }
                     completion:^(BOOL finished){

                     }
     ];

}

- (void)textFieldDidEndEditing:(UITextField *)textField{

}

@end


text:
const five = require('johnny-five');
const Chip = require('chip-io');
const OLED = require('oled-js');
const font = require('oled-font-5x7');
const EventEmitter = require('events').EventEmitter;

/**
 * @class
 */
class OC extends EventEmitter
{
  /**
   * Constructor for the OLED-CHIP (OC) class.
   * @param {Object} oledOpts - Object to hold the settings for the OLED.
   * @param {Integer} oledOpts.width - Width of the OLED in pixels, decimal number.
   * @param {Integer} oledOpts.height - Height of the OLED in pixels, decimal number.
   * @param {Integer} oledOpts.address - Address of the OLED, hex number.
   * @param {Object} opts - Object to hold the settings for the OLED-CHIP (OC) class.
   * @param {Integer} opts.bus - The bus number that your OLED screen is connected to.
   */
  constructor(oledOpts, opts)
  {
    super();
    this.font = require('oled-font-5x7');
    this.oledOpts = oledOpts;
    this.opts = opts;
    this.lines = {
      1: 0,
      2: 9,
      3: 18,
      4: 27,
      5: 36,
      6: 45,
      7: 54
    };
    this.dim = false;
    this.invert = false;
    this.init.bind(this);
    this.init();
  }
  init()
  {
    let io = new Chip();
    let that = this;
    let oledOpts = that.oledOpts;
    let opts = that.opts;

    io.i2cConfig({
      address: oledOpts.address,
      bus: opts.bus
    });
    this.board = new five.Board({
      io: io,
      repl: false,
      debug: false
    });
    that.board.on('ready', () =>
    {
      that.screen = new OLED(that.board, five, oledOpts);
      that.screen.update();
      that.emit('ready');
    });
  }
  write(line, str)
  {
    let screen = this.screen;
    let font = this.font;
    let lines = this.lines;

    screen.setCursor(1,lines[line]);
    screen.writeString(font, 1, str, 1, true, 2);
  }
  clear()
  {
    let screen = this.screen;
    screen.clearDisplay();
  }
  toggleDim()
  {
    let dim = this.dim;
    let screen = this.screen;
    if(dim)
    {
      this.dim = false;
      screen.dimDisplay(false);
    }
    else
    {
      this.dim = true;
      screen.dimDisplay(true);
    }
  }
  toggleInvert()
  {
    let invert = this.invert;
    let screen = this.screen;
    if(invert)
    {
      this.invert = false
      screen.invertDisplay(false);
    }
    else
    {
      this.invert = true;
      screen.invertDisplay(true);
    }
  }
  turnOff()
  {
    this.screen.turnOffDisplay();
  }
  turnOn()
  {
    this.screen.turnOnDisplay();
  }
  /**
   * @param {Array} p - Multi-dimensional array with one or more sets of pixels. [x,y,color]
   */
  drawPixel(p)
  {
    this.screen.drawPixel(p);
  }
  /**
   * @param {Object} points - Points to start and end the line.
   * @param {Integer} points.x1 - Starting x coord.
   * @param {Integer} points.y1 - Starting y coord.
   * @param {Integer} points.x2 - Finishing x coord.
   * @param {Integer} points.y2 - Finishing y coord.
   * @param {Integer} points.color - Color of the line, 1 for white, 0 for black.
   */
  line(points)
  {
    let screen = this.screen;
    screen.drawLine(points.x1, points.y1, points.x2, points.y2, points.color);
  }
  /**
   * @param {Object} rect - Object to hold top left point and bottom right point, color is optional.
   * @param {Integer} rect.x1 - X coord for top left corner point.
   * @param {Integer} rect.y1 - Y coord for top left corner point.
   * @param {Integer} rect.x2 - X coord for bottom right corner point.
   * @param {Integer} rect.y2 - Y coord for bottom right corner point.
   * @param {Integer} rect.color - Color of the fill, 1 for white, 0 for black.
   */
  fillRect(rect)
  {
    let screen = this.screen;
    screen.fillRect(rect.x1, rect.y1, rect.x2, rect.y2, rect.color);
  }
  /**
   * @param {Object} rect - Object to hold top left point and bottom right point, color is optional.
   * @param {Integer} rect.x1 - X coord for top left corner point.
   * @param {Integer} rect.y1 - Y coord for top left corner point.
   * @param {Integer} rect.x2 - X coord for bottom right corner point.
   * @param {Integer} rect.y2 - Y coord for bottom right corner point.
   * @param {Integer} rect.color - Color of the line, 1 for white, 0 for black.
   */
  drawRect(rect)
  {
    let screen = this.screen;
    screen.drawRect(rect.x1, rect.y1, rect.x2, rect.y2, rect.color);
  }
  update()
  {
    this.screen.update();
  }
}

const i2c = require('i2c');

/**
 * @class
 */
class Finder
{
  /**
   * Constructor for the Finder class.
   * @param {Object} opts - Object to hold the options for the Finder class.
   * @param {Object} opts.bus - Bus number to look for i2c devices on. (From what I've seen, should be 0-2)
   */
  constructor(opts)
  {
    this.wire = new i2c(0x3c, {device: `/dev/i2c-${opts.bus.toString()}`});
  }
  /**
   * Scans for i2c devices on the bus that was passed in opts of the constructor
   * @function
   */
  find()
  {
    let wire = this.wire;
    wire.scan((err, data) =>
    {
      if(err) throw err;
      console.log(data);
    });
  }

}

module.exports =
{
  OC: OC,
  Finder: Finder
};


text:
<body>
Adds GUI support for the NIFS instrument.
</body>


text:
using SocketIOClient.Messages;
using System;

namespace SocketIOClient
{
	public class MessageEventArgs : EventArgs
	{
		public IMessage Message { get; private set; }

		public MessageEventArgs(IMessage msg)
			: base()
		{
			this.Message = msg;
		}
	}
}


text:
package org.apache.activemq.artemis.tests.integration.mqtt5;

import java.util.Arrays;
import java.util.Collection;

import org.eclipse.paho.mqttv5.client.MqttClient;
import org.jboss.logging.Logger;
import org.junit.Test;
import org.junit.runners.Parameterized;

public class BasicSslTests extends MQTT5TestSupport {

   private static final Logger log = Logger.getLogger(BasicSslTests.class);

   public BasicSslTests(String protocol) {
      super(protocol);
   }

   @Parameterized.Parameters(name = "protocol={0}")
   public static Collection<Object[]> getParams() {
      return Arrays.asList(new Object[][] {
         {SSL},
         {WSS}
      });
   }

   @Override
   public boolean isUseSsl() {
      return true;
   }

   /*
    * Basic SSL test. Just connect.
    */
   @Test(timeout = DEFAULT_TIMEOUT)
   public void testSsl() throws Exception {
      MqttClient client = createPahoClient("client");
      client.connect(getSslMqttConnectOptions());
   }
}


text:
<?php

namespace PHPExiftool\Driver\Tag\NikonCustom;

use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;

/**
 * @ExclusionPolicy("all")
 */
class MoviePreviewButtonPlusDials extends AbstractTag
{

    protected $Id = '52.2';

    protected $Name = 'MoviePreviewButtonPlusDials';

    protected $FullName = 'NikonCustom::SettingsD4';

    protected $GroupName = 'NikonCustom';

    protected $g0 = 'MakerNotes';

    protected $g1 = 'NikonCustom';

    protected $g2 = 'Camera';

    protected $Type = 'int8u';

    protected $Writable = true;

    protected $Description = 'Movie Preview Button Plus Dials';

    protected $flag_Permanent = true;

    protected $Values = array(
        0 => array(
            'Id' => 0,
            'Label' => 'None',
        ),
        1 => array(
            'Id' => 1,
            'Label' => 'Choose Image Area',
        ),
    );
}


text:
package io.pivotal.cc.app;

import io.pivotal.cc.common.Constants;
import io.pivotal.cc.common.Order;
import io.pivotal.cc.common.OrderRepository;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;

import javax.annotation.PreDestroy;
import javax.servlet.ServletContext;

import org.apache.log4j.Logger;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.gemstone.gemfire.cache.client.ClientCache;
/**
 * Handles requests for the application home page.
 */
@Controller
public class OrderController {
	@Autowired
	ServletContext context;

    @Autowired SalesForAllStatesCaller salesForAllStatesCaller;

	private static Map<String, Queue<Order>> stateOrdersMap = new HashMap<String, Queue<Order>>();
	/*
	@Autowired
	@Qualifier("salesForAllStatesCaller")
	private SalesForAllStatesCaller sfasc;
	*/
	boolean generatingData = false;

	static Logger logger = Logger.getLogger(OrderController.class);

	OrderGenerator generator = new OrderGenerator();
	Thread threadSender = new Thread(generator);

	public OrderController() {
		System.out.println("********* In OrderController constructor...");
		for (int i = 0; i < Constants.states.length; i++) {
			stateOrdersMap.put(Constants.states[i],
					new ArrayBlockingQueue<Order>(10));
		}

		threadSender.start();

	}

	private int getOrderSum(String state) {

		int sum = 0;
		Queue<Order> q = stateOrdersMap.get(state);
		Iterator<Order> it = q.iterator();
		while (it.hasNext()) {
			sum += it.next().getAmount();
		}

		return sum;
	}

	public static synchronized void registerOrder(Order order) {
		Queue<Order> orderQueue = stateOrdersMap.get(order.getState());
		if (!orderQueue.offer(order)) {
			orderQueue.remove();
			orderQueue.add(order);
		}
	}

	@RequestMapping(value = "/")
	public String home(Model model) throws Exception {
		//model.addAttribute("rabbitURI", client.getRabbitURI());

		ObjectMapper mapper = new ObjectMapper();

		// add details about VCAP APPLICATION
		if (System.getenv("VCAP_APPLICATION") != null) {
			Map vcapMap = mapper.readValue(System.getenv("VCAP_APPLICATION"),
					Map.class);
			model.addAttribute("vcap_app", vcapMap);
		}

		return "WEB-INF/views/pcfdemo.jsp";
	}

	@RequestMapping(value = "/getData")
	public @ResponseBody double getData(@RequestParam("state") String state) {
		logger.info("Getting data...");
		if (!stateOrdersMap.containsKey(state))
			return 0;
		Queue<Order> q = stateOrdersMap.get(state);
		if (q.size() == 0)
			return 0;
		Order[] orders = q.toArray(new Order[] {});
		return orders[orders.length - 1].getAmount();

	}
	/*
	@RequestMapping(value = "/startStream")
	public @ResponseBody String startStream() {
		logger.warn("Rabbit URI " + client.getRabbitURI());
		if (client.getRabbitURI() == null)
			return "Please bind a RabbitMQ service";

		if (generatingData)
			return "Data already being generated";

		generatingData = true;

		generator.startGen();
		return "Started";

	}

	@RequestMapping(value = "/stopStream")
	public @ResponseBody String stopStream() {
		logger.warn("Rabbit URI " + client.getRabbitURI());
		if (client.getRabbitURI() == null)
			return "Please bind a RabbitMQ service";

		if (!generatingData)
			return "Not Streaming";
		generatingData = false;
		generator.stopGen();

		return "Stopped";

	}
	*/
	@RequestMapping(value = "/killApp")
	public @ResponseBody String kill() {
		logger.warn("Killing application instance");
		System.exit(-1);
		return "Killed";

	}

	@RequestMapping(value = "/getHeatMap")
	public @ResponseBody HeatMap getHistograms() {
		HeatMap heatMap = new HeatMap();
		for (int i = 0; i < Constants.states.length; i++) {
			heatMap.addOrderSum(Constants.states[i],
					getOrderSum(Constants.states[i]));
		}

		heatMap.assignColors();
		return heatMap;

	}

	@RequestMapping(value = "/startStream")
	public @ResponseBody String startStream() {
		logger.error("Starting stream of orders...");
		if (generatingData)
			return "Data already being generated";

		generatingData = true;
		generator.startGen();
		return "Started";
	}

	@RequestMapping(value = "/stopStream")
	public @ResponseBody String stopStream() {
		logger.info("Stopping stream of orders...");
		if (!generatingData)
			return "Not Streaming";
		generatingData = false;
		generator.stopGen();

		return "Stopped";
	}

	@RequestMapping(value="/order", method=RequestMethod.GET)
	public @ResponseBody Order getTransaction(@RequestParam("transactionId")String transactionId, Map<String, Object> model){
		logger.info("getTransaction for " + transactionId);
		ApplicationContext ctx = CcDemoAppApplication.getApplicationContext();
		OrderRepository or = ctx.getBean(OrderRepository.class);
		Order order = or.findByTransactionId(transactionId);
		if(order == null){
			logger.error("Order not found: " + transactionId);
			return new Order();
			// return "Order not found!";
		}
		else
		{
			logger.info("Found order: " + order);
			model.put("order", order);
			return order;
			// return order.toString();
		}
	}

	@RequestMapping(value="/ccType", method=RequestMethod.GET)
	public @ResponseBody Iterable<Order> getByCreditCardType(@RequestParam("creditCardType")String creditCardType, Map<String, Object> model){
		logger.info("getByCreditCardType for " + creditCardType);
		ApplicationContext ctx = CcDemoAppApplication.getApplicationContext();
		OrderRepository or = ctx.getBean(OrderRepository.class);
		Iterable<Order> orders = or.findByCreditCardType(creditCardType);
		if(orders == null){
			logger.error("Orders not found for: " + creditCardType);
			Iterable<Order> o = new ArrayList<Order>();
			return o;
		}
		else
		{
			logger.info("Found orders for : " + creditCardType);
			model.put("orders", orders);
			return orders;
		}
	}

	@RequestMapping(value="/cache", method=RequestMethod.GET)
	public @ResponseBody ClientCache getCache(){
		logger.info("getCache");
		ApplicationContext ctx = CcDemoAppApplication.getApplicationContext();
		ClientCache cc = ctx.getBean(ClientCache.class);
		if(cc == null){
			logger.error("client cache is null");
			return null;
		}
		else
		{
			logger.info("ClientCache : " + cc.toString());
			return cc;
		}
	}

	@RequestMapping(value="/salesByState", method=RequestMethod.GET)
	public @ResponseBody List getSalesByState(){
		logger.info("getSalesByState");
		ApplicationContext ctx = CcDemoAppApplication.getApplicationContext();
		SalesByStateCaller salesByStateCaller = ctx.getBean(SalesByStateCaller.class);
		return salesByStateCaller.computeSum();
	}

	@PreDestroy
	public void shutdownThread() {

		generator.shutdown();
	}

}