text:
package se.microcode.confluence.plugin.googleservices.base.youtube;

import com.atlassian.cache.Cache;
import com.atlassian.confluence.pages.Page;
import com.atlassian.confluence.renderer.PageContext;
import com.atlassian.confluence.renderer.radeox.macros.MacroUtils;
import com.atlassian.confluence.util.velocity.VelocityUtils;
import com.atlassian.renderer.v2.macro.MacroException;
import se.microcode.confluence.plugin.googleservices.PluginHelper;
import se.microcode.google.youtube.*;

import java.io.IOException;
import java.util.*;

public class PlaylistHelper
{
    public static List<Map> buildPlaylists(List<PlaylistEntry> playlists, int thumbSize)
    {
        ArrayList<Map> output = new ArrayList<Map>();

        for (PlaylistEntry playlist : playlists)
        {
            output.add(buildPlaylist(playlist, thumbSize));
        }

        return output;
    }

    public static Map buildPlaylist(PlaylistEntry playlist, int thumbSize)
    {
        HashMap<String,String> entry = new HashMap<String,String>();

        entry.put("id", playlist.id);
        entry.put("title", playlist.title);
        entry.put("count", Integer.toString(playlist.count));
        entry.put("image", playlist.thumbnail);
        entry.put("desc", playlist.description);

        return entry;
    }

    public static List buildVideoList(List<VideoEntry> videos, int thumbSize)
    {
        ArrayList<Map> output = new ArrayList<Map>();

        for (VideoEntry video : videos)
        {
            output.add(buildVideoEntry(video, thumbSize));
        }

        return output;
    }

    public static Map buildVideoEntry(VideoEntry video, int thumbSize)
    {
        HashMap<String,String> entry = new HashMap<String,String>();

        entry.put("id", video.id);
        entry.put("title", video.title);
        entry.put("desc", video.description);
        entry.put("credit", video.credit);

        if (video.thumbnail != null)
        {
            entry.put("image", video.thumbnail);
        }
        else
        {
            entry.put("image", "http://i.ytimg.com/vi/" + video.id + "/default.jpg");
        }
        return entry;
    }

    public static void retrievePlaylists(PlaylistMacroArguments args, PlaylistContext playlistContext) throws IOException
    {
        Cache cache = PluginHelper.getCache("se.microcode.confluence.plugin.googleservices.youtube");
        playlistContext.playlistFeed = YoutubeHelper.getPlaylistFeed(args.user, cache);

        if ((args.playlist != null) && (playlistContext.playlistFeed.playlists != null))
        {
            for (PlaylistEntry entry : playlistContext.playlistFeed.playlists)
            {
                if (entry.id.equals(args.playlist))
                {
                    playlistContext.playlistEntry = entry;
                    break;
                }
            }

            if (playlistContext.playlistEntry != null)
            {
                playlistContext.videoFeed = YoutubeHelper.getVideoFeed(playlistContext.playlistEntry.id, cache);
            }
        }

        if (args.video != null && (playlistContext.videoFeed != null) && (playlistContext.videoFeed.videos != null))
        {
            for (int i = 0, n = playlistContext.videoFeed.videos.size(); i != n; ++i)
            {
                VideoEntry video = playlistContext.videoFeed.videos.get(i);
                if (args.video.equals(video.id))
                {
                    int begin = (int)Math.max(0, i - Math.floor(args.thumbnails/2.0f));
                    int end = (int)Math.min(playlistContext.videoFeed.videos.size(), i + Math.ceil(args.thumbnails/2.0f));

                    playlistContext.videoEntry = video;
                    playlistContext.videoIndex = i;
                    playlistContext.thumbnails = playlistContext.videoFeed.videos.subList(begin, end);
                    break;
                }
            }
        }
    }

    public static void retrievePlaylistExcerpts(PlaylistExcerptsMacroArguments args, PlaylistContext playlistContext) throws IOException
    {
        Cache cache = PluginHelper.getCache("se.microcode.confluence.plugin.googleservices.youtube");

        playlistContext.playlistFeed = YoutubeHelper.getPlaylistFeed(args.user, cache);

        switch (args.display)
        {
            case VIDEOS:
            {
                if ((args.playlist != null) && (playlistContext.playlistFeed.playlists != null))
                {
                    for (PlaylistEntry entry : playlistContext.playlistFeed.playlists)
                    {
                        if (entry.id.equals(args.playlist))
                        {
                            playlistContext.playlistEntry = entry;
                            break;
                        }
                    }
                }
                else if ((playlistContext.playlistFeed.playlists != null) && (playlistContext.playlistFeed.playlists.size() > 0))
                {
                    playlistContext.playlistEntry = playlistContext.playlistFeed.playlists.get(playlistContext.playlistFeed.playlists.size()-1);
                }

                if (playlistContext.playlistEntry != null)
                {
                    playlistContext.videoFeed = YoutubeHelper.getVideoFeed(playlistContext.playlistEntry.id, cache);
                }
            }
            break;

            case PLAYLISTS:
            {

            }
            break;
        }
    }

    public static String renderPlaylists(PlaylistMacroArguments args, PageContext pageContext, PlaylistContext playlistContext)
    {
        Map context = MacroUtils.defaultVelocityContext();

        Page page = (pageContext.getEntity() != null && pageContext.getEntity() instanceof Page) ? (Page)pageContext.getEntity() : null;
        if (page != null)
        {
            context.put("title", page.getTitle());
        }

        if (args.pageId > 0)
        {
            context.put("baseUrl", "?pageId=" + args.pageId + "&");
        }
        else
        {
            context.put("baseUrl", "?");
        }

        if (playlistContext.videoEntry != null)
        {
            context.put("currPage", playlistContext.videoIndex + 1);
            context.put("pageCount", playlistContext.videoFeed.videos.size());

            if (playlistContext.videoIndex > 0)
            {
                context.put("prev", playlistContext.videoFeed.videos.get(playlistContext.videoIndex-1).id);
            }
            if (playlistContext.videoIndex < playlistContext.videoFeed.videos.size()-1)
            {
                context.put("next", playlistContext.videoFeed.videos.get(playlistContext.videoIndex+1).id);
            }

            context.put("video", PlaylistHelper.buildVideoEntry(playlistContext.videoEntry, args.thumbSize));
            context.put("playlist", PlaylistHelper.buildPlaylist(playlistContext.playlistEntry, args.thumbSize));
            context.put("thumbsize", args.thumbSize);

            if (playlistContext.thumbnails != null)
            {
                context.put("thumbnails", PlaylistHelper.buildVideoList(playlistContext.thumbnails, args.thumbSize));
            }

            return VelocityUtils.getRenderedTemplate("/se/microcode/confluence/plugin/googleservices/youtube/video.vm", context);
        }
        else if ((playlistContext.videoFeed != null) && (playlistContext.videoFeed.videos != null))
        {
            int begin = 0;
            int end = playlistContext.videoFeed.videos.size();
            if (args.pageSize > 0)
            {
                context.put("currPage", args.pageIndex +1);
                context.put("pageCount", (end+args.pageSize-1) / args.pageSize);

                begin = Math.min(end, args.pageIndex * args.pageSize);
                end = Math.min(end, begin + args.pageSize);
            }

            context.put("videos", PlaylistHelper.buildVideoList(playlistContext.videoFeed.videos.subList(begin, end), args.thumbSize));
            context.put("playlist", PlaylistHelper.buildPlaylist(playlistContext.playlistEntry, args.thumbSize));
            context.put("thumbsize", args.thumbSize);

            return VelocityUtils.getRenderedTemplate("/se/microcode/confluence/plugin/googleservices/youtube/playlist.vm", context);
        }
        else if (playlistContext.playlistFeed.playlists != null)
        {
            ArrayList<PlaylistEntry> playlists = new ArrayList<PlaylistEntry>(playlistContext.playlistFeed.playlists);

            int begin = 0;
            int end = playlists.size();

            Comparator<PlaylistEntry> comparator = PlaylistSorter.createSorter(args.sort);
            if (comparator != null)
            {
                Collections.sort(playlists, comparator);
            }

            if (args.reverse)
            {
                Collections.reverse(playlists);
            }

            if (args.pageSize > 0)
            {
                context.put("currPage", Integer.toString(args.pageIndex +1));
                context.put("pageCount", (end+args.pageSize-1) / args.pageSize);

                begin = Math.min(end, args.pageIndex * args.pageSize);
                end = Math.min(end, begin + args.pageSize);
            }

            context.put("thumbsize", args.thumbSize);

            context.put("playlists", PlaylistHelper.buildPlaylists(playlists.subList(begin, end), args.thumbSize));

            return VelocityUtils.getRenderedTemplate("/se/microcode/confluence/plugin/googleservices/youtube/playlists.vm", context);
        }

        return "";
    }

    public static String renderPlaylistExcerpts(PlaylistExcerptsMacroArguments args, String url, PageContext pageContext, PlaylistContext playlistContext)
    {
        switch (args.display)
        {
            case VIDEOS:
            {
                if ((playlistContext.videoFeed != null) && (playlistContext.videoFeed.videos != null))
                {
                    Map context = MacroUtils.defaultVelocityContext();
                    List<VideoEntry> videos = new ArrayList<VideoEntry>(playlistContext.videoFeed.videos);
                    int begin = 0;
                    int count = 0;
                    int end = (int)Math.min(videos.size(), 0 + (args.maxEntries - count));

                    if (args.reverse)
                    {
                        Collections.reverse(videos);
                    }

                    if (args.randomize)
                    {
                        Collections.shuffle(videos);
                    }

                    context.put("videos", PlaylistHelper.buildVideoList(videos.subList(begin, end), args.thumbSize));
                    context.put("playlist", PlaylistHelper.buildPlaylist(playlistContext.playlistEntry, args.thumbSize));
                    context.put("url", url);
                    context.put("thumbsize", args.thumbSize);

                    return VelocityUtils.getRenderedTemplate("/se/microcode/confluence/plugin/googleservices/youtube/playlist-excerpts.vm", context);
                }
            }
            break;

            case PLAYLISTS:
            {
                if ((playlistContext.playlistFeed != null) && (playlistContext.playlistFeed.playlists != null))
                {
                    Map context = MacroUtils.defaultVelocityContext();
                    List<PlaylistEntry> playlists = new ArrayList<PlaylistEntry>(playlistContext.playlistFeed.playlists);
                    int begin = 0;
                    int count = 0;
                    int end = (int)Math.min(playlists.size(), 0 + (args.maxEntries - count));

                    Comparator<PlaylistEntry> comparator = PlaylistSorter.createSorter(args.sort);
                    if (comparator != null)
                    {
                        Collections.sort(playlists, comparator);
                    }

                    if (args.reverse)
                    {
                        Collections.reverse(playlists);
                    }

                    if (args.randomize)
                    {
                        Collections.shuffle(playlists);
                    }

                    context.put("playlists", PlaylistHelper.buildPlaylists(playlists.subList(begin, end), args.thumbSize));
                    context.put("url", url);
                    context.put("thumbsize", args.thumbSize);

                    return VelocityUtils.getRenderedTemplate("/se/microcode/confluence/plugin/googleservices/youtube/playlists-excerpts.vm", context);
                }
            }
            break;
        }

        return "";
    }
}


text:
package com.microsoft.bingads.optimizer;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for ArrayOfBroadMatchOpportunity complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="ArrayOfBroadMatchOpportunity">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="BroadMatchOpportunity" type="{http://schemas.datacontract.org/2004/07/Microsoft.BingAds.Advertiser.Optimizer.Api.DataContracts.Entities}BroadMatchOpportunity" maxOccurs="unbounded" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ArrayOfBroadMatchOpportunity", propOrder = {
    "broadMatchOpportunities"
})
public class ArrayOfBroadMatchOpportunity {

    @XmlElement(name = "BroadMatchOpportunity", nillable = true)
    protected List<BroadMatchOpportunity> broadMatchOpportunities;

    /**
     * Gets the value of the broadMatchOpportunities property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the broadMatchOpportunities property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getBroadMatchOpportunities().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link BroadMatchOpportunity }
     *
     *
     */
    public List<BroadMatchOpportunity> getBroadMatchOpportunities() {
        if (broadMatchOpportunities == null) {
            broadMatchOpportunities = new ArrayList<BroadMatchOpportunity>();
        }
        return this.broadMatchOpportunities;
    }

}

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Grevillea 17(no. 84): 75 (1889)

#### Original name
Lenzites sinensis Cooke

### Remarks
null


text:
import { SECTIONS } from '~actions/sections'

const initialState = {}

const sectionsStore = (state = initialState, action) => {
  const {
    type,
    payload: { sections, error: errorMessage } = {},
    error
  } = action

  switch (type) {
    case `${SECTIONS}_REQUEST`:
      return state

    case `${SECTIONS}_SUCCESS`:
      return {
        sections
      }

    case `${SECTIONS}_FAILURE`:
      return {
        error,
        errorMessage
      }

    default:
      return state
  }
}

export default sectionsStore


text:
/*
 * IDK Game Server by Steve Winfield
 * https://github.com/WinfieldSteve
 */
package org.stevewinfield.suja.idk.communication.moderation.writers;

import org.magicwerk.brownies.collections.GapList;
import org.stevewinfield.suja.idk.communication.MessageWriter;
import org.stevewinfield.suja.idk.communication.OperationCodes;
import org.stevewinfield.suja.idk.game.moderation.ModerationPresetAction;
import org.stevewinfield.suja.idk.game.moderation.ModerationPresetMessage;
import org.stevewinfield.suja.idk.game.moderation.ModerationPresetMessageType;
import org.stevewinfield.suja.idk.game.players.PlayerInstance;

import java.util.Collection;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

public class ModerationToolWriter extends MessageWriter {

    public ModerationToolWriter(final PlayerInstance player, final Collection<ModerationPresetMessage> presetMessages, final ConcurrentHashMap<Integer, ModerationPresetAction> actions) {
        super(OperationCodes.getOutgoingOpCode("ModerationTool"));
        super.push(-1);

        final List<ModerationPresetMessage> playerPresetMessages = new GapList<>();
        final List<ModerationPresetMessage> roomPresetMessages = new GapList<>();

        for (final ModerationPresetMessage presetMessage : presetMessages) {
            if (presetMessage.getType() == ModerationPresetMessageType.ROOM_MESSAGE) {
                roomPresetMessages.add(presetMessage);
            } else {
                playerPresetMessages.add(presetMessage);
            }
        }

        super.push(playerPresetMessages.size());

        for (final ModerationPresetMessage presetMessage : playerPresetMessages) {
            super.push(presetMessage.getMessage());
        }

        super.push(actions.size());

        for (final ModerationPresetAction action : actions.values()) {
            super.push(action.getCaption());
            super.push(action.getItems().size());

            for (final ModerationPresetAction item : action.getItems().values()) {
                super.push(item.getCaption());
                super.push(item.getMessage());
            }
        }

        super.push(player.hasRight("moderation_tickets"));
        super.push(player.hasRight("moderation_chatlogs"));
        super.push(player.hasRight("moderation_actions"));
        super.push(player.hasRight("moderation_kick"));
        super.push(player.hasRight("moderation_ban"));
        super.push(player.hasRight("moderation_caution"));
        super.push(true);

        super.push(roomPresetMessages.size());

        for (final ModerationPresetMessage presetMessage : roomPresetMessages) {
            super.push(presetMessage.getMessage());
        }
    }

}


text:
/* Real Person jQuery plugin styles v1.0.1. */

/* http://keith-wood.name/realPerson.html
   Real Person Form Submission for jQuery v1.0.1.
   Written by Keith Wood (kwood{at}iinet.com.au) June 2009.
*/

/*
 * The Oxygen Webhelp plugin redistributes this file under the terms of the MIT license.
 * The full license terms of this license are available in the file MIT-License.txt
 * located in the same directory as the present file you are reading.
 */

.captcha{
    clear:both ;
}

.realperson-challenge {
	display: block;
	color: #000;
	clear:both;
	border:1px solid #fff;

}
.realperson-text {
	font-family: "Courier New",monospace;
	font-size: 6px;
	font-weight: bold;
	letter-spacing: -2px;
	line-height: 3px;
}
.realperson-regen {
	padding-top: 4px;
	font-size: 12px;
	text-align: center;
	cursor: pointer;
	float:left;
}


text:
import "./styles.scss";
import { View } from "backbone.marionette";
import { options } from "../../decorators";
import template from "./LoaderView.hbs";

@options({
  text: "Loading...",
})
class LoaderView extends View {
  template = template;

  initialize(opts) {
    this.options = opts;
  }

  serializeData() {
    return this.options;
  }
}

export default LoaderView;


text:
import random

GuessesTaken = 0

print ("Hello and welcome to my higher or lower number guessing game.")
print ("Whats your name?")
myName = input()

number = random.randint(1, 20)
number1 = random.randint(1, 20)
number2 = random.randint(1, 20)
number3 = random.randint(1, 20)
number4 = random.randint(1, 20)
number5 = random.randint(1, 20)
number6 = random.randint(1, 20)
number7 = random.randint(1, 20)
number8 = random.randint(1, 20)
number9 = random.randint(1, 20)
number10 = random.randint(1, 20)
number11 = random.randint(1, 20)
number12 = random.randint(1, 20)
number13 = random.randint(1, 20)
number14 = random.randint(1, 20)
number15 = random.randint(1, 20)
number16 = random.randint(1, 20)
number17 = random.randint(1, 20)
number18 = random.randint(1, 20)
number19 = random.randint(1, 20)
number20 = random.randint(1, 20)

print ("So, your names " + myName + " Hmmmmmmm")
print ("Ok " + myName + " here is your first number")
print ("")
print (number)
print ("")
print ("Also keep in mind that the numbers range from 1 to 20")
print ("")
print ("So will the next number be higher or lower?")
print ("")
print ("")
print ("Use h to guess Higher and use l to guess Lower.")

guess = input('Enter either h or l:    ')

if number > number1 and guess == "l":
    print ("Well done the number was " + number1 + " Now onto stage 2")
elif number > number1 and guess == "h":
    print ("Incorrect the number was " + number1 + "GAME OVER")
elif number < number1 and guess == "h":
    print ("Well done the number was " + number1 + " Now onto stage 2")
elif number < number1 and guess == "l":
    print ("Incorrect the number was " + number1 + " GAME OVER")


text:
namespace Envoy {
namespace Router {

DebugConfig::DebugConfig(bool append_cluster, absl::optional<Http::LowerCaseString> cluster_header,
                         bool append_upstream_host,
                         absl::optional<Http::LowerCaseString> hostname_header,
                         absl::optional<Http::LowerCaseString> host_address_header,
                         bool do_not_forward,
                         absl::optional<Http::LowerCaseString> not_forwarded_header)
    : append_cluster_(append_cluster), cluster_header_(std::move(cluster_header)),
      append_upstream_host_(append_upstream_host), hostname_header_(std::move(hostname_header)),
      host_address_header_(std::move(host_address_header)), do_not_forward_(do_not_forward),
      not_forwarded_header_(std::move(not_forwarded_header)) {}

const std::string& DebugConfig::key() {
  CONSTRUCT_ON_FIRST_USE(std::string, "envoy.router.debug_config");
}

} // namespace Router
} // namespace Envoy


text:
export {default as BamCacheService} from './bamCacheService';
export {default as BamCache} from './bamCache';


text:
module MojuraWebApp

	class LoginView < BaseView

		def initialize(options = {})
			WebApp.page.include_script_link('ext/crypto-js/md5.min.js')
			WebApp.page.include_script_link('ext/crypto-js/pbkdf2.min.js')
			WebApp.page.include_locale(:login)
			super(options, {})
		end

		def is_logged_in
			!WebApp.current_user.id.nil?
		end

	end

	WebApp.register_view('login', LoginView)

end


text:
<?php

namespace chervand\yii2\oauth2\server\rbac;

use yii\base\Configurable;
use yii\rbac\ManagerInterface;

/**
 * Class ScopePermission
 * @package chervand\yii2\oauth2\server\rbac
 */
class ScopePermission extends Permission implements Configurable
{
    /**
     * {@inheritdoc}
     */
    public function init()
    {
        /** @var ManagerInterface $authManager */
        $authManager = \Yii::$app->authManager;

        $grantedRule = new GrantedRule();
        $authManager->add($grantedRule);
        $this->ruleName = $grantedRule->name;

        parent::init();
    }
}


text:
/* See LICENSE for licensing information */

/**
 * \file crypto_pwbox.h
 *
 * \brief Header for crypto_pwbox.c
 **/

#ifndef CRYPTO_PWBOX_H_INCLUDED_
#define CRYPTO_PWBOX_H_INCLUDED_

#include "lib/cc/torint.h"

#define UNPWBOX_OKAY 0
#define UNPWBOX_BAD_SECRET -1
#define UNPWBOX_CORRUPTED -2

int crypto_pwbox(uint8_t **out, size_t *outlen_out,
                 const uint8_t *inp, size_t input_len,
                 const char *secret, size_t secret_len,
                 unsigned s2k_flags);

int crypto_unpwbox(uint8_t **out, size_t *outlen_out,
                   const uint8_t *inp, size_t input_len,
                   const char *secret, size_t secret_len);

#endif /* !defined(CRYPTO_PWBOX_H_INCLUDED_) */


text:
title: 'Zaisťovací tábor pre nepriateľov slovenského štátu'
slug: ilava
chapter: '2. kaptiola - Jeden národ, jedna strana, jeden vodca'
chapterHref: /chapters/2-jeden-narod-jedna-strana-jeden-vodca
routes:
    default: /chapters/2-jeden-narod-jedna-strana-jeden-vodca/ilava
    canonical: /chapters/2-jeden-narod-jedna-strana-jeden-vodca/ilava
    aliases:
        - /chapters/2/ilava
content:
    items: '@self.parent'
returnButtonText: 'Späť na 2. kapitolu'
---

Už krátko po vzniku samostatného štátu, 24. marca 1939, vydáva vláda nariadenie o "zaisťovacom uväznení nepriateľov slovenského štátu". Za nepriateľov sú označovaní všetci, ktorí by podľa režimu údajne mohli byť "prekážkou v budovaní nového štátu", teda najmä politickí oponenti – funkcionári rozpustených a zakázaných politických strán aj starí ľudáci nespokojní s novým smerovaním strany, bývalí československí legionári, ale tiež ktokoľvek, kto si na ulici či v krčme dovolil verejnú kritiku štátu, jeho predstaviteľov či spojencov.

O zaistení v Ilave, kde bol tento tábor zriadený v časti starej väznice, nerozhodoval súd, ale orgány ministerstva vnútra. Obídením súdneho systému väzňom nebolo treba dokazovať vinu, nevedeli, na ako dlho sú zavretí, a nemali sa ani voči čomu a kam odvolať. V rokoch 1939 – 1944 sa do Ilavy dostalo asi 2500-3000 osôb.

[![Zaisťovací tábor pre nepriateľov slovenského štátu v Ilave](Ilava_ZVJS.jpg "Zaisťovací tábor pre nepriateľov slovenského štátu v Ilave")](http://www.zvjs.sk/?ustav-vykonu-trestu-vykonu-vazby)


text:
<%#
 Copyright 2013-2017 the original author or authors from the StackStack project.

 This file is part of the StackStack project, see https://jhipster.github.io/
 for more information.

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

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

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-%>
package <%=packageName%>.config.oauth2;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * OAuth2 properties define properties for OAuth2-based microservices.
 */
@Component
@ConfigurationProperties(prefix = "oauth2", ignoreUnknownFields = false)
public class OAuth2Properties {
    private WebClientConfiguration webClientConfiguration = new WebClientConfiguration();

    private SignatureVerification signatureVerification = new SignatureVerification();

    public WebClientConfiguration getWebClientConfiguration() {
        return webClientConfiguration;
    }

    public SignatureVerification getSignatureVerification() {
        return signatureVerification;
    }

    public static class WebClientConfiguration {
        private String clientId = "web_app";
        private String secret = "changeit";
        /**
         * Holds the session timeout in seconds for non-remember-me sessions.
         * After so many seconds of inactivity, the session will be terminated.
         * Only checked during token refresh, so long access token validity may
         * delay the session timeout accordingly.
         */
        private int sessionTimeoutInSeconds = 1800;
        /**
         * Defines the cookie domain. If specified, cookies will be set on this domain.
         * If not configured, then cookies will be set on the top-level domain of the
         * request you sent, i.e. if you send a request to app1.your-domain.com,
         * then cookies will be set on .your-domain.com, such that they
         * are also valid for app2.your-domain.com.
         */
        private String cookieDomain;

        public String getClientId() {
            return clientId;
        }

        public void setClientId(String clientId) {
            this.clientId = clientId;
        }

        public String getSecret() {
            return secret;
        }

        public void setSecret(String secret) {
            this.secret = secret;
        }

        public int getSessionTimeoutInSeconds() {
            return sessionTimeoutInSeconds;
        }

        public void setSessionTimeoutInSeconds(int sessionTimeoutInSeconds) {
            this.sessionTimeoutInSeconds = sessionTimeoutInSeconds;
        }

        public String getCookieDomain() {
            return cookieDomain;
        }

        public void setCookieDomain(String cookieDomain) {
            this.cookieDomain = cookieDomain;
        }
    }

    public static class SignatureVerification {
        /**
         * Maximum refresh rate for public keys in ms.
         * We won't fetch new public keys any faster than that to avoid spamming UAA in case
         * we receive a lot of "illegal" tokens.
         */
        private long publicKeyRefreshRateLimit = 10 * 1000L;
        /**
         * Maximum TTL for the public key in ms.
         * The public key will be fetched again from UAA if it gets older than that.
         * That way, we make sure that we get the newest keys always in case they are updated there.
         */
        private long ttl = 24 * 60 * 60 * 1000L;
        /**
         * Endpoint where to retrieve the public key used to verify token signatures.
         */
        private String publicKeyEndpointUri = "http://uaa/oauth/token_key";

        public long getPublicKeyRefreshRateLimit() {
            return publicKeyRefreshRateLimit;
        }

        public void setPublicKeyRefreshRateLimit(long publicKeyRefreshRateLimit) {
            this.publicKeyRefreshRateLimit = publicKeyRefreshRateLimit;
        }

        public long getTtl() {
            return ttl;
        }

        public void setTtl(long ttl) {
            this.ttl = ttl;
        }

        public String getPublicKeyEndpointUri() {
            return publicKeyEndpointUri;
        }

        public void setPublicKeyEndpointUri(String publicKeyEndpointUri) {
            this.publicKeyEndpointUri = publicKeyEndpointUri;
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@color/card_background"
    android:paddingTop="@dimen/margin_top"

    android:paddingBottom="@dimen/margin_bottom">

    <LinearLayout
        android:layout_marginTop="10dp"
        android:background="@color/card_primary_cell_bg"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
    <EditText
        android:id="@+id/login_email"
        android:hint="@string/email_hint"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:drawablePadding="10dp"
        android:inputType="textEmailAddress"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <EditText
        android:id="@+id/login_password"
        android:hint="password"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:drawablePadding="10dp"
        android:inputType="textPassword"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    </LinearLayout>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        tools:text="validation"
        android:padding="5dp"
        android:id="@+id/validation"/>

    <Button
        android:layout_marginTop="30dp"
        android:layout_marginBottom="10dp"
        android:id="@+id/login_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/login_button"
        android:textColor="@drawable/textcolour_button_dark"

        android:background="@drawable/button_action_solid"/>
    <TextView
        android:background="@drawable/button_transparent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="@string/forgot_password"
        android:id="@+id/forgot_password"
        />
</LinearLayout>


text:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using Android.Support.V4.View;
using Android.Views;
using AView = Android.Views.View;

namespace Xamarin.Forms.Platform.Android
{
	public abstract class VisualElementRenderer<TElement> : FormsViewGroup, IVisualElementRenderer, AView.IOnTouchListener, AView.IOnClickListener, IEffectControlProvider where TElement : VisualElement
	{
		readonly List<EventHandler<VisualElementChangedEventArgs>> _elementChangedHandlers = new List<EventHandler<VisualElementChangedEventArgs>>();

		readonly Lazy<GestureDetector> _gestureDetector;
		readonly PanGestureHandler _panGestureHandler;
		readonly PinchGestureHandler _pinchGestureHandler;

		readonly TapGestureHandler _tapGestureHandler;

		NotifyCollectionChangedEventHandler _collectionChangeHandler;

		VisualElementRendererFlags _flags = VisualElementRendererFlags.AutoPackage | VisualElementRendererFlags.AutoTrack;

		InnerGestureListener _gestureListener;
		VisualElementPackager _packager;
		PropertyChangedEventHandler _propertyChangeHandler;
		Lazy<ScaleGestureDetector> _scaleDetector;

		protected VisualElementRenderer() : base(Forms.Context)
		{
			_tapGestureHandler = new TapGestureHandler(() => View);
			_panGestureHandler = new PanGestureHandler(() => View, Context.FromPixels);
			_pinchGestureHandler = new PinchGestureHandler(() => View);

			_gestureDetector =
				new Lazy<GestureDetector>(
					() =>
					new GestureDetector(
						_gestureListener =
						new InnerGestureListener(_tapGestureHandler.OnTap, _tapGestureHandler.TapGestureRecognizers, _panGestureHandler.OnPan, _panGestureHandler.OnPanStarted, _panGestureHandler.OnPanComplete)));

			_scaleDetector =
				new Lazy<ScaleGestureDetector>(
					() => new ScaleGestureDetector(Context, new InnerScaleListener(_pinchGestureHandler.OnPinch, _pinchGestureHandler.OnPinchStarted, _pinchGestureHandler.OnPinchEnded), Handler));
		}

		public TElement Element { get; private set; }

		protected bool AutoPackage
		{
			get { return (_flags & VisualElementRendererFlags.AutoPackage) != 0; }
			set
			{
				if (value)
					_flags |= VisualElementRendererFlags.AutoPackage;
				else
					_flags &= ~VisualElementRendererFlags.AutoPackage;
			}
		}

		protected bool AutoTrack
		{
			get { return (_flags & VisualElementRendererFlags.AutoTrack) != 0; }
			set
			{
				if (value)
					_flags |= VisualElementRendererFlags.AutoTrack;
				else
					_flags &= ~VisualElementRendererFlags.AutoTrack;
			}
		}

		View View
		{
			get { return Element as View; }
		}

		void IEffectControlProvider.RegisterEffect(Effect effect)
		{
			var platformEffect = effect as PlatformEffect;
			if (platformEffect != null)
				OnRegisterEffect(platformEffect);
		}

		void IOnClickListener.OnClick(AView v)
		{
			_tapGestureHandler.OnSingleClick();
		}

		bool IOnTouchListener.OnTouch(AView v, MotionEvent e)
		{
			var handled = false;
			if (_pinchGestureHandler.IsPinchSupported)
			{
				if (!_scaleDetector.IsValueCreated)
					ScaleGestureDetectorCompat.SetQuickScaleEnabled(_scaleDetector.Value, true);
				handled = _scaleDetector.Value.OnTouchEvent(e);
			}
			return _gestureDetector.Value.OnTouchEvent(e) || handled;
		}

		VisualElement IVisualElementRenderer.Element
		{
			get { return Element; }
		}

		event EventHandler<VisualElementChangedEventArgs> IVisualElementRenderer.ElementChanged
		{
			add { _elementChangedHandlers.Add(value); }
			remove { _elementChangedHandlers.Remove(value); }
		}

		public virtual SizeRequest GetDesiredSize(int widthConstraint, int heightConstraint)
		{
			Measure(widthConstraint, heightConstraint);
			return new SizeRequest(new Size(MeasuredWidth, MeasuredHeight), MinimumSize());
		}

		void IVisualElementRenderer.SetElement(VisualElement element)
		{
			if (!(element is TElement))
				throw new ArgumentException("element is not of type " + typeof(TElement), "element");

			SetElement((TElement)element);
		}

		public VisualElementTracker Tracker { get; private set; }

		public void UpdateLayout()
		{
			Performance.Start();
			if (Tracker != null)
				Tracker.UpdateLayout();

			Performance.Stop();
		}

		public ViewGroup ViewGroup
		{
			get { return this; }
		}

		public event EventHandler<ElementChangedEventArgs<TElement>> ElementChanged;

		public void SetElement(TElement element)
		{
			if (element == null)
				throw new ArgumentNullException("element");

			TElement oldElement = Element;
			Element = element;

			Performance.Start();

			if (oldElement != null)
			{
				oldElement.PropertyChanged -= _propertyChangeHandler;
				UnsubscribeGestureRecognizers(oldElement);
			}

			// element may be allowed to be passed as null in the future
			if (element != null)
			{
				Color currentColor = oldElement != null ? oldElement.BackgroundColor : Color.Default;
				if (element.BackgroundColor != currentColor)
					UpdateBackgroundColor();
			}

			if (_propertyChangeHandler == null)
				_propertyChangeHandler = OnElementPropertyChanged;

			element.PropertyChanged += _propertyChangeHandler;
			SubscribeGestureRecognizers(element);

			if (oldElement == null)
			{
				SetOnClickListener(this);
				SetOnTouchListener(this);
				SoundEffectsEnabled = false;
			}

			InputTransparent = Element.InputTransparent;

			// must be updated AFTER SetOnClickListener is called
			// SetOnClickListener implicitly calls Clickable = true
			UpdateGestureRecognizers(true);

			OnElementChanged(new ElementChangedEventArgs<TElement>(oldElement, element));

			if (AutoPackage && _packager == null)
				SetPackager(new VisualElementPackager(this));

			if (AutoTrack && Tracker == null)
				SetTracker(new VisualElementTracker(this));

			if (element != null)
				SendVisualElementInitialized(element, this);

			var controller = (IElementController)oldElement;
			if (controller != null && controller.EffectControlProvider == this)
				controller.EffectControlProvider = null;

			controller = element;
			if (controller != null)
				controller.EffectControlProvider = this;

			if (element != null && !string.IsNullOrEmpty(element.AutomationId))
				SetAutomationId(element.AutomationId);

			Performance.Stop();
		}

		/// <summary>
		/// Determines whether the native control is disposed of when this renderer is disposed
		/// Can be overridden in deriving classes
		/// </summary>
		protected virtual bool ManageNativeControlLifetime => true;

		protected override void Dispose(bool disposing)
		{
			if ((_flags & VisualElementRendererFlags.Disposed) != 0)
				return;
			_flags |= VisualElementRendererFlags.Disposed;

			if (disposing)
			{
				if (Tracker != null)
				{
					Tracker.Dispose();
					Tracker = null;
				}

				if (_packager != null)
				{
					_packager.Dispose();
					_packager = null;
				}

				if (_scaleDetector != null && _scaleDetector.IsValueCreated)
				{
					_scaleDetector.Value.Dispose();
					_scaleDetector = null;
				}

				if (_gestureListener != null)
				{
					_gestureListener.Dispose();
					_gestureListener = null;
				}

				if (ManageNativeControlLifetime)
				{
					int count = ChildCount;
					for (var i = 0; i < count; i++)
					{
						AView child = GetChildAt(i);
						child.Dispose();
					}
				}

				RemoveAllViews();

				if (Element != null)
				{
					Element.PropertyChanged -= _propertyChangeHandler;
					UnsubscribeGestureRecognizers(Element);

					if (Platform.GetRenderer(Element) == this)
						Platform.SetRenderer(Element, null);

					Element = null;
				}
			}

			base.Dispose(disposing);
		}

		protected virtual Size MinimumSize()
		{
			return new Size();
		}

		protected virtual void OnElementChanged(ElementChangedEventArgs<TElement> e)
		{
			var args = new VisualElementChangedEventArgs(e.OldElement, e.NewElement);
			for (var i = 0; i < _elementChangedHandlers.Count; i++)
				_elementChangedHandlers[i](this, args);

			EventHandler<ElementChangedEventArgs<TElement>> changed = ElementChanged;
			if (changed != null)
				changed(this, e);
		}

		protected virtual void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
		{
			if (e.PropertyName == VisualElement.BackgroundColorProperty.PropertyName)
				UpdateBackgroundColor();
			else if (e.PropertyName == VisualElement.InputTransparentProperty.PropertyName)
				InputTransparent = Element.InputTransparent;
		}

		protected override void OnLayout(bool changed, int l, int t, int r, int b)
		{
			if (Element == null)
				return;

			ReadOnlyCollection<Element> children = Element.LogicalChildren;
			for (var i = 0; i < children.Count; i++)
			{
				var visualElement = children[i] as VisualElement;
				if (visualElement == null)
					continue;

				IVisualElementRenderer renderer = Platform.GetRenderer(visualElement);
				renderer?.UpdateLayout();
			}
		}

		protected virtual void OnRegisterEffect(PlatformEffect effect)
		{
			effect.Container = this;
		}

		protected virtual void SetAutomationId(string id)
		{
			ContentDescription = id;
		}

		protected void SetPackager(VisualElementPackager packager)
		{
			_packager = packager;
			packager.Load();
		}

		protected void SetTracker(VisualElementTracker tracker)
		{
			Tracker = tracker;
		}

		protected virtual void UpdateBackgroundColor()
		{
			SetBackgroundColor(Element.BackgroundColor.ToAndroid());
		}

		internal virtual void SendVisualElementInitialized(VisualElement element, AView nativeView)
		{
			element.SendViewInitialized(nativeView);
		}

		void HandleGestureRecognizerCollectionChanged(object sender, NotifyCollectionChangedEventArgs notifyCollectionChangedEventArgs)
		{
			UpdateGestureRecognizers();
		}

		void SubscribeGestureRecognizers(VisualElement element)
		{
			var view = element as View;
			if (view == null)
				return;

			if (_collectionChangeHandler == null)
				_collectionChangeHandler = HandleGestureRecognizerCollectionChanged;

			var observableCollection = (ObservableCollection<IGestureRecognizer>)view.GestureRecognizers;
			observableCollection.CollectionChanged += _collectionChangeHandler;
		}

		void UnsubscribeGestureRecognizers(VisualElement element)
		{
			var view = element as View;
			if (view == null || _collectionChangeHandler == null)
				return;

			var observableCollection = (ObservableCollection<IGestureRecognizer>)view.GestureRecognizers;
			observableCollection.CollectionChanged -= _collectionChangeHandler;
		}

		void UpdateClickable(bool force = false)
		{
			var view = Element as View;
			if (view == null)
				return;

			bool newValue = view.ShouldBeMadeClickable();
			if (force || newValue)
				Clickable = newValue;
		}

		void UpdateGestureRecognizers(bool forceClick = false)
		{
			if (View == null)
				return;

			UpdateClickable(forceClick);
		}
	}
}


text:
const express  = require('express');
const mongoose = require('mongoose'),
      ObjectId = mongoose.Types.ObjectId;

const room     = require('./models/roomModel');

const isAuthed = require('./passport/isUserAuthed');

const roomRouter = express.Router();

roomRouter.get('/', isAuthed, (req, res) => {
    let query = {};

    room.find(query, (err, rooms) => {
      if(err) res.status(500).send(err);
      else res.json(rooms);
    });
});

roomRouter.get('/:id', isAuthed, (req, res) => {
    const roomId = ObjectId(req.params.id);
    room.findById(roomId, (err, room) => {
      if(err) res.status(500).send(err);
      if(!room) res.status(404).send('Room not found.');
      res.status(200).json(room);
    });
});

module.exports = roomRouter;


text:
'use strict';

var fs = require('fs');
var path = require('canonical-path');

/**
 * @dgProcessor generateKeywordsProcessor
 * @description
 * This processor extracts all the keywords from each document and creates
 * a new document that will be rendered as a JavaScript file containing all
 * this data.
 */
module.exports = function generateKeywordsProcessor(log, readFilesProcessor) {
  return {
    ignoreWordsFile: undefined,
    propertiesToIgnore: [],
    docTypesToIgnore: [],
    outputFolder: '',
    $validate: {
      ignoreWordsFile: {},
      docTypesToIgnore: {},
      propertiesToIgnore: {},
      outputFolder: {presence: true}
    },
    $runAfter: ['paths-computed'],
    $runBefore: ['rendering-docs'],
    $process: function(docs) {

      // Keywords to ignore
      var wordsToIgnore = [];
      var propertiesToIgnore;
      var docTypesToIgnore;

      // Keywords start with "ng:" or one of $, _ or a letter
      var KEYWORD_REGEX = /^((ng:|[$_a-z])[\w\-_]+)/;

      // Load up the keywords to ignore, if specified in the config
      if (this.ignoreWordsFile) {
        var ignoreWordsPath = path.resolve(readFilesProcessor.basePath, this.ignoreWordsFile);
        wordsToIgnore = fs.readFileSync(ignoreWordsPath, 'utf8').toString().split(/[,\s\n\r]+/gm);

        log.debug('Loaded ignore words from "' + ignoreWordsPath + '"');
        log.silly(wordsToIgnore);
      }

      propertiesToIgnore = convertToMap(this.propertiesToIgnore);
      log.debug('Properties to ignore', propertiesToIgnore);
      docTypesToIgnore = convertToMap(this.docTypesToIgnore);
      log.debug('Doc types to ignore', docTypesToIgnore);

      var ignoreWordsMap = convertToMap(wordsToIgnore);

      // If the title contains a name starting with ng, e.g. "ngController", then add the module
      // name
      // without the ng to the title text, e.g. "controller".
      function extractTitleWords(title) {
        var match = /ng([A-Z]\w*)/.exec(title);
        if (match) {
          title = title + ' ' + match[1].toLowerCase();
        }
        return title;
      }

      function extractWords(text, words, keywordMap) {
        var tokens = text.toLowerCase().split(/[.\s,`'"#]+/mg);
        tokens.forEach(function(token) {
          var match = token.match(KEYWORD_REGEX);
          if (match) {
            var key = match[1];
            if (!keywordMap[key]) {
              keywordMap[key] = true;
              words.push(key);
            }
          }
        });
      }

      const filteredDocs = docs
          // We are not interested in some docTypes
          .filter(function(doc) { return !docTypesToIgnore[doc.docType]; })
          // Ignore internals and private exports (indicated by the ɵ prefix)
          .filter(function(doc) { return !doc.internal && !doc.privateExport; });

      filteredDocs.forEach(function(doc) {

        var words = [];
        var keywordMap = Object.assign({}, ignoreWordsMap);
        var members = [];
        var membersMap = {};

        // Search each top level property of the document for search terms
        Object.keys(doc).forEach(function(key) {
          const value = doc[key];

          if (isString(value) && !propertiesToIgnore[key]) {
            extractWords(value, words, keywordMap);
          }

          if (key === 'methods' || key === 'properties' || key === 'events') {
            value.forEach(function(member) { extractWords(member.name, members, membersMap); });
          }
        });

        doc.searchTerms = {
          titleWords: extractTitleWords(doc.title || doc.name),
          keywords: words.sort().join(' '),
          members: members.sort().join(' ')
        };

      });

      var searchData =
          filteredDocs.filter(function(page) { return page.searchTerms; }).map(function(page) {
            return Object.assign(
                {path: page.path, title: page.name || page.title, type: page.docType}, page.searchTerms);
          });

      docs.push({
        docType: 'json-doc',
        id: 'search-data-json',
        template: 'json-doc.template.json',
        path: this.outputFolder + '/search-data.json',
        outputPath: this.outputFolder + '/search-data.json',
        data: searchData
      });
    }
  };
};

function isString(value) {
  return typeof value == 'string';
}

function convertToMap(collection) {
  const obj = {};
  collection.forEach(key => { obj[key] = true; });
  return obj;
}


text:
"""Main functions of library.

"""

from functools import partial
import selectors
import signal
import time

import linuxfd

from .log import logger
from .scheduler import Scheduler
from .tcpserver import init_socket, handle_request, close_socket

def run(host, port, Payload):
    """Select loop of scheduler.

    :param host: A string with the host to bind to.
    :param port: An integer with the port to bind to.
    :param Payload: A class that follows the interface of ``types.Payload``.

    """
    scheduler = Scheduler()

    sock = init_socket('127.0.0.1', 8000)
    selector = selectors.DefaultSelector()
    callback = partial(handle_request, klass=Payload)
    selector.register(sock, selectors.EVENT_READ, callback)

    sigint_fd = linuxfd.signalfd(
        signalset={signal.SIGINT, signal.SIGTERM}, nonBlocking=True
    )
    selector.register(sigint_fd, selectors.EVENT_READ, True)
    sighup_fd = linuxfd.signalfd(signalset={signal.SIGHUP}, nonBlocking=True)
    selector.register(sighup_fd, selectors.EVENT_READ, scheduler.report)
    signal.pthread_sigmask(
        signal.SIG_BLOCK, {signal.SIGINT, signal.SIGHUP, signal.SIGTERM}
    )

    timestamp = None
    should_exit = False
    while True:
        if should_exit:
            break
        if timestamp is None:
            timeout = timestamp
        else:
            timeout = timestamp - time.time()
            assert timeout >= 0
        logger.debug('Selecting on timeout {0}'.format(timeout))
        events = selector.select(timeout)
        if not events:
            item = scheduler.pop()
            item.execute()
            timestamp = getattr(scheduler.top(), 'timestamp', None)
        for key, mask in events:
            callback = key.data
            if not callable(callback):
                should_exit = True
            elif key.fileobj == sock:
                item = callback(key.fileobj)
                scheduler.push(item)
                timestamp = scheduler.top().timestamp
            else:
                key.fileobj.read()
                callback()
    close_socket(sock)


text:
module Swattr
  class SettingsController < ApplicationController
    before_action :set_settings

    def show
      respond_with @settings
    end

    def edit
      respond_with @settings
    end

    def update
      @settings.update(settings_params)

      respond_with @settings, location: -> { settings_path }
    end

    protected

    def permitted_attributes
      [
        :title, :per_page, :logo, :remove_logo
      ]
    end

    def set_settings
      @settings = Swattr::Setting.settings

      authorize @settings
    end

    def settings_params
      params.require(:settings).permit(permitted_attributes)
    end
  end
end


text:
from . import db
import math

class ZipCodes(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    zipcode = db.Column(db.Integer)
    latitude = db.Column(db.Float)
    longitude = db.Column(db.Float)

    def __init__(self, details):
        self.zipcode = details[0]
        self.latitude = float(details[1])
        self.longitude = float(details[2])

    def __repr__(self):
        return '<ZipCode %r>' % self.zipcode

class HotSpots(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    boro = db.Column(db.String(10))
    provider = db.Column(db.String(20))
    name = db.Column(db.String(20))
    location = db.Column(db.String(50))
    latitude = db.Column(db.Float)
    longitude = db.Column(db.Float)

    def __init__(self, details):
        self.boro = details[1]
        self.provider = details[3]
        self.name = details[4].decode('utf-8')
        self.location = details[5].decode('utf-8')
        self.latitude = float(details[6])
        self.longitude = float(details[7])

    def distance(self, destination):
        """
        This method implements the  Haversine Formula, it calculates the
        distances between two points on a map
        """
        lat1 = self.latitude
        lon1 = self.longitude
        lat2, lon2 = destination
        radius = 6371  # km

        dlat = math.radians(lat2-lat1)
        dlon = math.radians(lon2-lon1)
        a = math.sin(dlat/2) * math.sin(dlat/2) + math.cos(math.radians(lat1)) \
            * math.cos(math.radians(lat2)) * math.sin(dlon/2) * math.sin(dlon/2)
        c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
        d = radius * c

        return d

    def __repr__(self):
        return '<HotSpot %r>' % self.name


text:
create table [AsyncExecResults] (
	[token] uniqueidentifier primary key
	, [submit_time] datetime not null
	, [start_time] datetime null
	, [finish_time] datetime null
	, [error_number]	int null
	, [error_message] nvarchar(2048) null);
go

create queue [AsyncExecQueue];
go

create service [AsyncExecService] on queue [AsyncExecQueue] ([DEFAULT]);
go

create procedure usp_AsyncExecActivated
as
begin
    set nocount on;
    declare @h uniqueidentifier
        , @messageTypeName sysname
        , @messageBody varbinary(max)
        , @xmlBody xml
        , @procedureName sysname
        , @startTime datetime
        , @finishTime datetime
        , @execErrorNumber int
        , @execErrorMessage nvarchar(2048)
        , @xactState smallint
        , @token uniqueidentifier;

    begin transaction;
    begin try;
        receive top(1)
            @h = [conversation_handle]
            , @messageTypeName = [message_type_name]
            , @messageBody = [message_body]
            from [AsyncExecQueue];
        if (@h is not null)
        begin
            if (@messageTypeName = N'DEFAULT')
            begin
                -- The DEFAULT message type is a procedure invocation.
                -- Extract the name of the procedure from the message body.
                --
                select @xmlBody = CAST(@messageBody as xml);
                select @procedureName = @xmlBody.value(
                    '(//procedure/name)[1]'
                    , 'sysname');

                save transaction usp_AsyncExec_procedure;
                select @startTime = GETUTCDATE();
                begin try
                    exec @procedureName;
                end try
                begin catch
                -- This catch block tries to deal with failures of the procedure execution
                -- If possible it rolls back to the savepoint created earlier, allowing
                -- the activated procedure to continue. If the executed procedure
                -- raises an error with severity 16 or higher, it will doom the transaction
                -- and thus rollback the RECEIVE. Such case will be a poison message,
                -- resulting in the queue disabling.
                --
                select @execErrorNumber = ERROR_NUMBER(),
                    @execErrorMessage = ERROR_MESSAGE(),
                    @xactState = XACT_STATE();
                if (@xactState = -1)
                begin
                    rollback;
                    raiserror(N'Unrecoverable error in procedure %s: %i: %s', 16, 10,
                        @procedureName, @execErrorNumber, @execErrorMessage);
                end
                else if (@xactState = 1)
                begin
                    rollback transaction usp_AsyncExec_procedure;
                end
                end catch

                select @finishTime = GETUTCDATE();
                select @token = [conversation_id]
                    from sys.conversation_endpoints
                    where [conversation_handle] = @h;
                if (@token is null)
                begin
                    raiserror(N'Internal consistency error: conversation not found', 16, 20);
                end
                update [AsyncExecResults] set
                    [start_time] = @starttime
                    , [finish_time] = @finishTime
                    , [error_number] = @execErrorNumber
                    , [error_message] = @execErrorMessage
                    where [token] = @token;
                if (0 = @@ROWCOUNT)
                begin
                    raiserror(N'Internal consistency error: token not found', 16, 30);
                end
                end conversation @h;
            end
            else if (@messageTypeName = N'http://schemas.microsoft.com/SQL/ServiceBroker/EndDialog')
            begin
                end conversation @h;
            end
            else if (@messageTypeName = N'http://schemas.microsoft.com/SQL/ServiceBroker/Error')
            begin
                declare @errorNumber int
                    , @errorMessage nvarchar(4000);
                select @xmlBody = CAST(@messageBody as xml);
                with xmlnamespaces (DEFAULT N'http://schemas.microsoft.com/SQL/ServiceBroker/Error')
                select @errorNumber = @xmlBody.value ('(/Error/Code)[1]', 'INT'),
                    @errorMessage = @xmlBody.value ('(/Error/Description)[1]', 'NVARCHAR(4000)');
                -- Update the request with the received error
                select @token = [conversation_id]
                    from sys.conversation_endpoints
                    where [conversation_handle] = @h;
                update [AsyncExecResults] set
                    [error_number] = @errorNumber
                    , [error_message] = @errorMessage
                    where [token] = @token;
                end conversation @h;
             end
           else
           begin
                raiserror(N'Received unexpected message type: %s', 16, 50, @messageTypeName);
           end
        end
        commit;
    end try
    begin catch
        declare @error int
            , @message nvarchar(2048);
        select @error = ERROR_NUMBER()
            , @message = ERROR_MESSAGE()
            , @xactState = XACT_STATE();
        if (@xactState <> 0)
        begin
            rollback;
        end;
        raiserror(N'Error: %i, %s', 1, 60,  @error, @message) with log;
    end catch
end
go

alter queue [AsyncExecQueue]
    with activation (
    procedure_name = [usp_AsyncExecActivated]
    , max_queue_readers = 1
    , execute as owner
    , status = on);
go

create procedure [usp_AsyncExecInvoke]
    @procedureName sysname
    , @token uniqueidentifier output
as
begin
    declare @h uniqueidentifier
	    , @xmlBody xml
        , @trancount int;
    set nocount on;

	set @trancount = @@trancount;
    if @trancount = 0
        begin transaction
    else
        save transaction usp_AsyncExecInvoke;
    begin try
        begin dialog conversation @h
            from service [AsyncExecService]
            to service N'AsyncExecService', 'current database'
            with encryption = off;
        select @token = [conversation_id]
            from sys.conversation_endpoints
            where [conversation_handle] = @h;
        select @xmlBody = (
            select @procedureName as [name]
            for xml path('procedure'), type);
        send on conversation @h (@xmlBody);
        insert into [AsyncExecResults]
            ([token], [submit_time])
            values
            (@token, getutcdate());
    if @trancount = 0
        commit;
    end try
    begin catch
        declare @error int
            , @message nvarchar(2048)
            , @xactState smallint;
        select @error = ERROR_NUMBER()
            , @message = ERROR_MESSAGE()
            , @xactState = XACT_STATE();
        if @xactState = -1
            rollback;
        if @xactState = 1 and @trancount = 0
            rollback
        if @xactState = 1 and @trancount > 0
            rollback transaction usp_my_procedure_name;

        raiserror(N'Error: %i, %s', 16, 1, @error, @message);
    end catch
end
go


text:
package org.terasology.rendering.opengl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.terasology.config.Config;
import org.terasology.config.RenderingConfig;
import org.terasology.engine.paths.PathManager;
import org.terasology.engine.subsystem.common.ThreadManager;
import org.terasology.registry.CoreRegistry;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * The term "Post Processing" is in analogy to what occurs in the world of Photography:
 * first a number of shots are taken on location or in a studio. The resulting images
 * are then post-processed to achieve specific aesthetic or technical goals.
 *
 * In the context of Terasology, the WorldRenderer takes care of "taking the shots
 * on location" (a world of 3D data such as vertices, uv coordinates and so on)
 * while the PostProcessor starts from the resulting 2D buffers (which in most
 * cases can be thought as images) and through a series of steps it generates the
 * image seen on screen or saved in a screenshot.
 *
 * Most PostProcessor methods represent a single step of the process. I.e the
 * method generateLightShafts() only adds light shafts to the image.
 *
 * Also, most methods follow a typical pattern of operations:
 * 1) enable a material (a shader bundled with its control parameters)
 * 2) bind zero or more 2D buffers to sample from
 * 3) bind and configure an FBO to output to
 * 4) render a quad, usually covering the whole buffer area, but sometimes less
 *
 * Finally, post-processing can be thought as a part of the rendering pipeline,
 * the set of conceptually atomic steps (sometimes called "passes") that eventually
 * leads to the final image. In practice however these steps are not really arranged
 * in a "line" where a given step takes the output of the previous step and provides
 * an input to the next one. Some steps have no dependencies on previous steps and
 * only provide the basis for further processing. Other steps have instead one or
 * more inputs and in turn become the input to one or more further passes.
 *
 * The rendering pipeline the methods of the PostProcessor contribute to is therefore
 * better thought as a Directed Acyclic Graph (DAG) in which each step is a node
 * that might or might not have previous nodes in input but will always have at least
 * an output, with the final writing to the default framebuffer (the display) or
 * to a screenshot file.
 */
// TODO: Future work should not only "think" in terms of a DAG-like rendering pipeline
// TODO: but actually implement one, see https://github.com/MovingBlocks/Terasology/issues/1741
public class PostProcessor {
    private static final Logger logger = LoggerFactory.getLogger(PostProcessor.class);

    private FrameBuffersManager buffersManager;

    private boolean isTakingScreenshot;

    private RenderingConfig renderingConfig = CoreRegistry.get(Config.class).getRendering();

    private ThreadManager threadManager = CoreRegistry.get(ThreadManager.class);
    private float currentExposure;

    /**
     * Returns a PostProcessor instance. On instantiation the returned instance is not
     * yet usable. It lacks references to Material assets and Frame Buffer Objects (FBOs)
     * it needs to function.
     *
     * Method initializeMaterials() must be called to initialize the Materials references.
     * Method obtainStaticFBOs() must be called to initialize unchanging FBOs references.
     * Method refreshDynamicFBOs() must be called at least once to initialize all other FBOs references.
     *
     * @param buffersManager An FrameBuffersManager instance, required to obtain FBO references.
     */
    public PostProcessor(FrameBuffersManager buffersManager) {
        this.buffersManager = buffersManager;
    }

    /**
     * Disposes of the PostProcessor instance.
     */
    // Not strictly necessary given the simplicity of the objects being nulled,
    // it is probably a good habit to have a dispose() method. It both properly
    // dispose support objects and it clearly marks the end of a PostProcessor
    // instance's lifecycle.
    public void dispose() {
        buffersManager = null;
    }

    /**
     * Returns the current exposure value (set in downsampleSceneAndUpdateExposure()).
     *
     * @return a float representing the current exposure value.
     */
    public float getExposure() {
        return currentExposure;
    }

    // TODO: Remove this method, temporarily here for DownSampleSceneAndUpdateExposure
    public void setExposure(float exposure) {
        this.currentExposure = exposure;
    }

    /**
     * Triggers a screenshot.
     *
     * Notice that this method just starts the process: screenshot data is captured and written to file
     * as soon as possible but not necessarily immediately after the trigger.
     */
    public void takeScreenshot() {
        isTakingScreenshot = true;
    }

    /**
     * Schedules the saving of screenshot data to file.
     *
     * Screenshot data from the GPU is obtained as soon as this method executes. However, the data is only scheduled
     * to be written to file, by submitting a task to the ThreadManager. The task is then executed as soon as possible
     * but not necessarily immediately.
     *
     * The file is then saved in the designated screenshot folder with a filename in the form:
     *
     *     Terasology-[yyMMddHHmmss]-[width]x[height].[format]
     *
     * If no screenshot data is available an error is logged and the method returns doing nothing.
     */
    public void saveScreenshot() {
        final ByteBuffer buffer = buffersManager.getSceneFinalRawData();
        if (buffer == null) {
            logger.error("No screenshot data available. No screenshot will be saved.");
            return;
        }

        FBO sceneFinal = buffersManager.getFBO("sceneFinal");
        int width = sceneFinal.width();
        int height = sceneFinal.height();

        Runnable task = () -> {
            SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmss");

            final String format = renderingConfig.getScreenshotFormat();
            final String fileName = "Terasology-" + sdf.format(new Date()) + "-" + width + "x" + height + "." + format;
            Path path = PathManager.getInstance().getScreenshotPath().resolve(fileName);
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

            for (int x = 0; x < width; x++) {
                for (int y = 0; y < height; y++) {
                    int i = (x + width * y) * 4;
                    int r = buffer.get(i) & 0xFF;
                    int g = buffer.get(i + 1) & 0xFF;
                    int b = buffer.get(i + 2) & 0xFF;
                    image.setRGB(x, height - (y + 1), (0xFF << 24) | (r << 16) | (g << 8) | b);
                }
            }

            try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(path))) {
                ImageIO.write(image, format, out);
                logger.info("Screenshot '" + fileName + "' saved! ");
            } catch (IOException e) {
                logger.warn("Failed to save screenshot!", e);
            }
        };

        threadManager.submitTask("Write screenshot", task);
        isTakingScreenshot = false;
    }

    /**
     * Returns true if the rendering engine is not in the process of taking a screenshot.
     * Returns false if a screenshot is being taken.
     *
     * @return true if no screenshot is being taken, false otherwise
     */
    // for code readability it make sense to have this method rather than its opposite.
    public boolean isNotTakingScreenshot() {
        return !isTakingScreenshot;
    }
}


text:
'use strict';

describe('Service: vnApiProducts', function () {

    // load the service's module
    beforeEach(module('Volusion.toolboxCommon'));

    // instantiate service
    var vnApiProducts;
    beforeEach(inject(function (_vnApiProducts_) {
        vnApiProducts = _vnApiProducts_;
    }));

    it('should default to an empty object', function () {
        expect(vnApiProducts).toEqual({});
    });

    // When mocking or ajax testing is enabled test the integrity
    // of the responses structure.

});


text:
namespace fileapi {
namespace {

class FileSystemUtilTest : public testing::Test {};

TEST_F(FileSystemUtilTest, GetTempFileSystemRootURI) {
  GURL origin_url("http://chromium.org");
  fileapi::FileSystemType type = fileapi::kFileSystemTypeTemporary;
  GURL uri = GURL("filesystem:http://chromium.org/temporary/");
  EXPECT_EQ(uri, GetFileSystemRootURI(origin_url, type));
}

TEST_F(FileSystemUtilTest, GetPersistentFileSystemRootURI) {
  GURL origin_url("http://chromium.org");
  fileapi::FileSystemType type = fileapi::kFileSystemTypePersistent;
  GURL uri = GURL("filesystem:http://chromium.org/persistent/");
  EXPECT_EQ(uri, GetFileSystemRootURI(origin_url, type));
}

TEST_F(FileSystemUtilTest, VirtualPathBaseName) {
  struct test_data {
    const base::FilePath::StringType path;
    const base::FilePath::StringType base_name;
  } test_cases[] = {
    { FILE_PATH_LITERAL("foo/bar"), FILE_PATH_LITERAL("bar") },
    { FILE_PATH_LITERAL("foo/b:bar"), FILE_PATH_LITERAL("b:bar") },
    { FILE_PATH_LITERAL(""), FILE_PATH_LITERAL("") },
    { FILE_PATH_LITERAL("/"), FILE_PATH_LITERAL("/") },
    { FILE_PATH_LITERAL("foo//////bar"), FILE_PATH_LITERAL("bar") },
    { FILE_PATH_LITERAL("foo/bar/"), FILE_PATH_LITERAL("bar") },
    { FILE_PATH_LITERAL("foo/bar/////"), FILE_PATH_LITERAL("bar") },
    { FILE_PATH_LITERAL("/bar/////"), FILE_PATH_LITERAL("bar") },
    { FILE_PATH_LITERAL("bar/////"), FILE_PATH_LITERAL("bar") },
    { FILE_PATH_LITERAL("bar/"), FILE_PATH_LITERAL("bar") },
    { FILE_PATH_LITERAL("/bar"), FILE_PATH_LITERAL("bar") },
    { FILE_PATH_LITERAL("////bar"), FILE_PATH_LITERAL("bar") },
    { FILE_PATH_LITERAL("bar"), FILE_PATH_LITERAL("bar") }
  };
  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(test_cases); ++i) {
    base::FilePath input = base::FilePath(test_cases[i].path);
    base::FilePath base_name = VirtualPath::BaseName(input);
    EXPECT_EQ(test_cases[i].base_name, base_name.value());
  }
}

TEST_F(FileSystemUtilTest, VirtualPathGetComponents) {
  struct test_data {
    const base::FilePath::StringType path;
    size_t count;
    const base::FilePath::StringType components[3];
  } test_cases[] = {
    { FILE_PATH_LITERAL("foo/bar"),
      2,
      { FILE_PATH_LITERAL("foo"), FILE_PATH_LITERAL("bar") } },
    { FILE_PATH_LITERAL("foo"),
      1,
      { FILE_PATH_LITERAL("foo") } },
    { FILE_PATH_LITERAL("foo////bar"),
      2,
      { FILE_PATH_LITERAL("foo"), FILE_PATH_LITERAL("bar") } },
    { FILE_PATH_LITERAL("foo/c:bar"),
      2,
      { FILE_PATH_LITERAL("foo"), FILE_PATH_LITERAL("c:bar") } },
    { FILE_PATH_LITERAL("c:foo/bar"),
      2,
      { FILE_PATH_LITERAL("c:foo"), FILE_PATH_LITERAL("bar") } },
    { FILE_PATH_LITERAL("foo/bar"),
      2,
      { FILE_PATH_LITERAL("foo"), FILE_PATH_LITERAL("bar") } },
    { FILE_PATH_LITERAL("/foo/bar"),
      2,
      { FILE_PATH_LITERAL("foo"), FILE_PATH_LITERAL("bar") } },
  };
  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(test_cases); ++i) {
    base::FilePath input = base::FilePath(test_cases[i].path);
    std::vector<base::FilePath::StringType> components;
    VirtualPath::GetComponents(input, &components);
    EXPECT_EQ(test_cases[i].count, components.size());
    for (size_t j = 0; j < components.size(); ++j)
      EXPECT_EQ(test_cases[i].components[j], components[j]);
  }
}

TEST_F(FileSystemUtilTest, GetIsolatedFileSystemName) {
  GURL origin_url("http://foo");
  std::string fsname1 = GetIsolatedFileSystemName(origin_url, "bar");
  EXPECT_EQ("http_foo_0:Isolated_bar", fsname1);
}

TEST_F(FileSystemUtilTest, CrackIsolatedFileSystemName) {
  std::string fsid;
  EXPECT_TRUE(CrackIsolatedFileSystemName("foo:Isolated_bar", &fsid));
  EXPECT_EQ("bar", fsid);
  EXPECT_TRUE(CrackIsolatedFileSystemName("foo:isolated_bar", &fsid));
  EXPECT_EQ("bar", fsid);
  EXPECT_TRUE(CrackIsolatedFileSystemName("foo:Isolated__bar", &fsid));
  EXPECT_EQ("_bar", fsid);
  EXPECT_TRUE(CrackIsolatedFileSystemName("foo::Isolated_bar", &fsid));
  EXPECT_EQ("bar", fsid);
}

TEST_F(FileSystemUtilTest, RejectBadIsolatedFileSystemName) {
  std::string fsid;
  EXPECT_FALSE(CrackIsolatedFileSystemName("foobar", &fsid));
  EXPECT_FALSE(CrackIsolatedFileSystemName("foo:_bar", &fsid));
  EXPECT_FALSE(CrackIsolatedFileSystemName("foo:Isolatedbar", &fsid));
  EXPECT_FALSE(CrackIsolatedFileSystemName("fooIsolatedbar", &fsid));
  EXPECT_FALSE(CrackIsolatedFileSystemName("foo:Persistent", &fsid));
  EXPECT_FALSE(CrackIsolatedFileSystemName("foo:Temporary", &fsid));
  EXPECT_FALSE(CrackIsolatedFileSystemName("foo:External", &fsid));
  EXPECT_FALSE(CrackIsolatedFileSystemName(":Isolated_bar", &fsid));
  EXPECT_FALSE(CrackIsolatedFileSystemName("foo:Isolated_", &fsid));
}

}  // namespace (anonymous)
}  // namespace fileapi


text:
ACCEPTED

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

#### Published in
Thomsen, H. A. ; Bjørn, P. ; Højlund,L. ; Olesen J. ; Pedersen J. B. (1995). Ericiolus gen. nov. (Prymnesiophyceae), a new coccolithophorid genus from polar and temperate regions. European Journal of Phycology 30: 29-34

#### Original name
null

### Remarks
null


text:
package org.ada.pattern.proxy;

/**
 *
 *
VistaVehiculo

 *
 * Description
 *
 * @author TheOverLordKotan (ADA)
 * @version 1.0
 *
 */
public class VistaVehiculo
{
	public static void main(String[] args)
	{
		Animacion animacion = new AnimacionProxy();
		animacion.dibuja();
		animacion.clic();
		animacion.dibuja();
	}
}


text:
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
    </style>

    <style name="FullscreenTheme" parent="android:Theme.NoTitleBar">
        <item name="android:windowContentOverlay">@null</item>
        <item name="android:windowBackground">@null</item>
        <item name="metaButtonBarStyle">@style/ButtonBar</item>
        <item name="metaButtonBarButtonStyle">@style/ButtonBarButton</item>
    </style>

    <!-- Backward-compatible version of ?android:attr/buttonBarStyle -->
    <style name="ButtonBar">
        <item name="android:paddingLeft">2dp</item>
        <item name="android:paddingTop">5dp</item>
        <item name="android:paddingRight">2dp</item>
        <item name="android:paddingBottom">0dp</item>
        <item name="android:background">@android:drawable/bottom_bar</item>
    </style>

    <!-- Backward-compatible version of ?android:attr/buttonBarButtonStyle -->
    <style name="ButtonBarButton" />

    <style name="DarkBlueTheme" parent="DarkBlueTheme.Base">

    </style>

    <style name="DarkBlueTheme.Base" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="windowNoTitle">true</item>
        <item name="windowActionBar">false</item>
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

</resources>


text:
package ru.job4j.converter;

import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

/**
 * Test for Converter class.
 *
 * @author Dmitrii Eskov (eskovdmi@gmail.com)
 * @version 1.0
 * @since 06.06.2018
 */
public class ConverterTest {

    /**
     * Test for conversion of rubles into dollars.
     */
    @Test
    public void when60RublesToDollarThen1() {
        Converter converter = new Converter();
        double result = converter.rubleToDollar(65);
        assertThat(result, is(1.0));
    }

    /**
     * Test for conversion of rubles into euro.
     */
    @Test
    public void when70RublesToEuroThen() {
        Converter converter = new Converter();
        double result = converter.rubleToEuro(75);
        assertThat(result, is(1.0));
    }

    /**
     * Test for conversion of euro into rubles.
     */
    @Test
    public void when1000EuroToRublesThen70000() {
        Converter converter = new Converter();
        double result = converter.euroToRuble(1000);
        assertThat(result, is(70000.0));
    }

    /**
     * Test for conversion of dollars into rubles.
     */
    @Test
    public void when1000DollarsToRublesThen60000() {
        Converter converter = new Converter();
        double result = converter.dollarToRuble(1000);
        assertThat(result, is(60000.0));
    }
}


text:
package fr.insee.rmes.metadata.utils;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public interface XpathProcessor {

	/**
	 * Query a list of nodes using xpath
	 *
	 * @param fragment
	 *            - XML fragment as string
	 * @param xpathExpression
	 *            - Valid xpath expression
	 * @return - A list of DOM Node elements
	 * @throws Exception
	 */
	NodeList queryList(String fragment, String xpathExpression) throws Exception;

	/**
	 * Query a list of nodes using xpath
	 *
	 * @param node
	 *            - XML fragment as DOM Node
	 * @param xpathExpression
	 *            - Valid xpath expression
	 * @return - A list of DOM Node elements
	 * @throws Exception
	 */
	NodeList queryList(Node node, String xpathExpression) throws Exception;

	/**
	 * Query String representation of a XML fragment using xpath
	 *
	 * @param fragment
	 *            - XML fragment as string
	 * @param xpathExpression
	 *            - Valid xpath expression
	 * @return - An XML fragment represented as a String
	 * @throws Exception
	 */
	String queryString(String fragment, String xpathExpression) throws Exception;

	/**
	 * Query String representation of a XML fragment using xpath
	 *
	 * @param node
	 *            - XML fragment as DOM Node
	 * @param xpathExpression
	 *            - Valid xpath expression
	 * @return - An XML fragment represented as a String
	 * @throws Exception
	 */
	String queryString(Node node, String xpathExpression) throws Exception;

	/**
	 * Query a text element (ie value) from a XML fragment using xpath
	 *
	 * @param fragment
	 *            - XML fragment as string
	 * @param xpathExpression
	 *            - Valid xpath expression
	 * @return - A text element (ie value)
	 * @throws Exception
	 */
	String queryText(String fragment, String xpathExpression) throws Exception;

	/**
	 * Query a text element (ie value) from a XML fragment using xpath
	 *
	 * @param node
	 *            - XML fragment as DOM Node
	 * @param xpathExpression
	 *            - Valid xpath expression
	 * @return - A text element (ie value)
	 * @throws Exception
	 */
	String queryText(Node node, String xpathExpression) throws Exception;

	/**
	 * Converts an XML fragment represented as a String to a DOM Node
	 * representation
	 *
	 * @param xml
	 * @return
	 * @throws Exception
	 */
	Document toDocument(String xml) throws Exception;

	/**
	 * Converts an XML fragment represented as a DOM Node element to its String
	 * representation
	 *
	 * @param node
	 * @return
	 * @throws Exception
	 */
	String toString(Node node) throws Exception;
}


text:
package com.amihaiemil.charles.github;

import org.slf4j.Logger;
import java.io.IOException;

/**
 * The general preconditions for any command other than 'hello' are:
 *
 * 1) Repo is under the commander's name or commander is an active admin of the
 *    organization. This rule does not apply if the commander is specified in .charles.yml;
 * 2) Repo is not a fork;
 * 3) Repo is a website (is named commander.github.io) or has a gh-pages branch;
 *
 * @author Mihai Andronache (amihaiemil@gmail.com)
 * @version $Id$
 * @since 1.0.1
 * @todo #219:1h Write some integration tests for this step, check that
 *  the tree of steps executes correctly/in the right order. For this, you
 *  need to mock a Github server (use MkGithub) in appropriate ways, to check
 *  each flow.
 */
public final class GeneralPreconditionsCheck extends IntermediaryStep {

    /**
     * Ctor.
     * @param next Next step, after all precondition have passed.
     */
    public GeneralPreconditionsCheck(final Step next) {
        super(next);
    }

    @Override
    public void perform(Command command, Logger logger) throws IOException {
        final PreconditionCheckStep all;

        final PreconditionCheckStep repoForkCheck = new RepoForkCheck(
            this.next(),
            this.finalCommentStep(command, "denied.fork.comment", command.authorLogin())
        );

        if(!this.isCommanderAllowed(command)) {
            final PreconditionCheckStep authorOwnerCheck = new AuthorOwnerCheck(
                    repoForkCheck,
                    new OrganizationAdminCheck(
                        repoForkCheck,
                        this.finalCommentStep(command, "denied.commander.comment", command.authorLogin())
                    )
            );
            all = new RepoNameCheck(
                authorOwnerCheck,
                new GhPagesBranchCheck(
                    authorOwnerCheck,
                    this.finalCommentStep(command, "denied.name.comment", command.authorLogin())
                )
            );
        } else {
            all = new RepoNameCheck(
                repoForkCheck,
                new GhPagesBranchCheck(
                    repoForkCheck,
                    this.finalCommentStep(command, "denied.name.comment", command.authorLogin())
                )
            );
        }
        all.perform(command, logger);
    }

    /**
     * Builds the final comment to be sent to the issue.
     * <b>This should be the last in the steps' chain</b>.
     * @param com Command.
     * @param formatParts Parts to format the response %s elements with.
     * @return SendReply step.
     */
    private SendReply finalCommentStep(
        Command com, String messagekey, String ... formatParts
    ) {
        return new SendReply(
            new TextReply(
                com,
                String.format(
                    com.language().response(messagekey),
                    (Object[]) formatParts
                )
            ),
            new Step.FinalStep()
        );
    }

    /**
     * Is the command's author specified in .charles.yml as a commander?
     * @param com Initial command.
     * @throws IOException if the commanders' list cannot be read from Github.
     * @return True of False
     */
    private boolean isCommanderAllowed(Command com) throws IOException {
        for(String commander : com.repo().charlesYml().commanders()) {
            if(commander.equalsIgnoreCase(com.authorLogin())) {
                return true;
            }
        }
        return false;
    }
}