text:
package me.kutrumbos;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Observable;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import com.google.gson.Gson;

/**
 * A web-socket based Meteor DDP client
 * @author peterkutrumbos
 *
 */
public class DdpClient extends Observable {

	private int currentId;
	private final Map<Integer,String> identifiers;
	private final WebSocketClient wsClient;
	private final Gson gson = new Gson();

	private final static String DDP_PROTOCOL_VERSION = "pre1";

	/**
	 * Field names supported in the DDP protocol
	 *
	 */
	public enum DdpMessageField {
		MSG("msg"), ID("id"), METHOD("method"), PARAMS("params"), NAME("name"), SERVER_ID("server_id"),
		SESSION("session"), VERSION("version"), SUPPORT("support");

		private String fieldId;

		private DdpMessageField(String fieldId){
			this.fieldId = fieldId;
		}

		public String toString() {
			return this.fieldId;
		}
	}

	/**
	 * Instantiates a Meteor DDP client for the Meteor server located at the supplied IP and port
	 *   (note: running Meteor locally will typically have a port of 3000 but
	 *   	port 80 is the typical default for publicly deployed servers)
	 * @param meteorServerIp - IP of Meteor server
	 * @param meteorServerPort - Port of Meteor server, if left null it will default to 3000
	 * @throws URISyntaxException
	 */
	public DdpClient(String meteorServerIp, Integer meteorServerPort) throws URISyntaxException{
		if(meteorServerPort == null) meteorServerPort = 3000;
		String meteorServerAddress = "ws://"+meteorServerIp+":"+meteorServerPort.toString()+"/websocket";
		this.currentId = 0;
		this.identifiers = new HashMap<Integer,String>();
		this.wsClient = new WebSocketClient(new URI(meteorServerAddress)) {

			@Override
			public void onOpen(ServerHandshake handshakedata) {
				connectionOpened();
			}

			@Override
			public void onMessage(String message) {
				received(message);
			}

			@Override
			public void onError(Exception ex) {
				handleError(ex);
			}

			@Override
			public void onClose(int code, String reason, boolean remote) {
				connectionClosed(code, reason, remote);
			}
		};
	}

	/**
	 * Ran on initial web-socket connection, sends back a connection confirmation message to the Meteor server
	 */
	private void connectionOpened() {
		// reply to Meteor server with connection confirmation message ({"msg": "connect"})
		System.out.println("WebSocket connection opened");
		Map<DdpMessageField,Object> connectMsg = new HashMap<DdpMessageField,Object>();
		connectMsg.put(DdpMessageField.MSG, "connect");
		connectMsg.put(DdpMessageField.VERSION, DDP_PROTOCOL_VERSION);
		connectMsg.put(DdpMessageField.SUPPORT, new String[]{DDP_PROTOCOL_VERSION});
		send(connectMsg);
	}

	/**
	 * Ran when connection is closed
	 * @param code
	 * @param reason
	 * @param remote
	 */
	private void connectionClosed(int code, String reason, boolean remote) {
		// is this how onClose messages should be handled??
		String closeMsg = "WebSocketClient connection closed:"+code+", "+reason+", "+remote;
		System.out.println(closeMsg);
		received(closeMsg);
	}

	/**
	 * Error handling for any errors over the web-socket connection
	 * @param ex
	 */
	private void handleError(Exception ex) {
		String errorMsg = "WebSocketClient error: "+ex.getMessage();
		ex.printStackTrace();
		received(errorMsg);
	}

	/**
	 * Increments and returns the client's current ID
	 * @return
	 */
	private int nextId() {
		return ++currentId;
	}

	/**
	 * Registers a client DDP message by storing it in the identifiers map
	 * @param identifier
	 * @return
	 */
	private String registerIdentifier(String identifier) {
		Integer id = nextId();
		identifiers.put(id, identifier);
		return id.toString();
	}

	/**
	 * Initiate connection to meteor server
	 */
	public void connect() {
		this.wsClient.connect();
	}

	/**
	 * Call a meteor method with the supplied parameters
	 * @param method - name of corresponding Meteor method
	 * @param args - arguments to be passed to the Meteor method
	 */
	public void call(String method, Object[] params){
		Map<DdpMessageField,Object> callMsg = new HashMap<DdpMessageField,Object>();
		callMsg.put(DdpMessageField.MSG, "method");
		callMsg.put(DdpMessageField.METHOD, method);
		callMsg.put(DdpMessageField.PARAMS, params);

		String id = registerIdentifier("method,"+method+","+Arrays.toString(params));

		callMsg.put(DdpMessageField.ID, id);

		send(callMsg);
	}

	/**
	 * Subscribe to a Meteor record set with the supplied parameters
	 * @param name - name of the corresponding Meteor subscription
	 * @param params - arguments corresponding to the Meteor subscription
	 */
	public void subscribe(String name, Object[] params) {
		Map<DdpMessageField,Object> subMsg = new HashMap<DdpMessageField,Object>();
		subMsg.put(DdpMessageField.MSG, "sub");
		subMsg.put(DdpMessageField.NAME, name);
		subMsg.put(DdpMessageField.PARAMS, params);

		String id = registerIdentifier("sub,"+name+","+Arrays.toString(params));

		subMsg.put(DdpMessageField.ID, id);

		send(subMsg);
	}

	/**
	 * Un-subscribe to a record set
	 * @param name - name of the corresponding Meteor subscription
	 */
	public void unsubscribe(String name) {
		Map<DdpMessageField,Object> unsubMsg = new HashMap<DdpMessageField,Object>();
		unsubMsg.put(DdpMessageField.MSG, "unsub");
		unsubMsg.put(DdpMessageField.NAME, name);

		String id = registerIdentifier("unsub,"+name);

		unsubMsg.put(DdpMessageField.ID, id);

		send(unsubMsg);
	}

	/**
	 * Converts DDP-formatted message to JSON and sends over web-socket
	 * @param msg
	 */
	public void send(Map<DdpMessageField,Object> msg) {
		String json = gson.toJson(msg);
		this.wsClient.send(json);
	}

	/**
	 * Notifies observers of this DDP client of messages received from the Meteor server
	 * @param msg
	 */
	public void received(String msg) {
		this.setChanged();
		this.notifyObservers(msg);
	}

}


text:
require 'protobuf/rpc/server'
require 'protobuf/rpc/servers/zmq/util'
require 'thread'

module Protobuf
  module Rpc
    module Zmq
      class Worker
        include ::Protobuf::Rpc::Server
        include ::Protobuf::Rpc::Zmq::Util

        ##
        # Constructor
        #
        def initialize(server, broker)
          @server = server
          @broker = broker

          init_zmq_context
          init_backend_socket
        rescue
          teardown
          raise
        end

        ##
        # Instance Methods
        #
        def process_request
          client_address, _, data = read_from_backend
          return unless data

          gc_pause do
            encoded_response = handle_request(data)
            write_to_backend([client_address, ::Protobuf::Rpc::Zmq::EMPTY_STRING, encoded_response])
          end
        end

        def run
          poller = ::ZMQ::Poller.new
          poller.register_readable(@backend_socket)
          poller.register_readable(@shutdown_socket)

          # Send request to broker telling it we are ready
          write_to_backend([::Protobuf::Rpc::Zmq::WORKER_READY_MESSAGE])

          loop do
            rc = poller.poll(500)

            if rc == 0 && !running?
              break # The server was shutdown and no requests are pending
            elsif rc == -1
              break # Something went wrong
            elsif rc > 0
              ::Thread.current[:busy] = true
              process_request
              ::Thread.current[:busy] = false
            end
          end
        ensure
          teardown
        end

        def running?
          @broker.running? && @server.running?
        end

        private

        def init_zmq_context
          if inproc?
            @zmq_context = @server.zmq_context
          else
            @zmq_context = ZMQ::Context.new
          end
        end

        def init_backend_socket
          @backend_socket = @zmq_context.socket(ZMQ::REQ)
          zmq_error_check(@backend_socket.connect(@server.backend_uri))
        end

        def inproc?
          !!@server.try(:inproc?)
        end

        def read_from_backend
          frames = []
          zmq_error_check(@backend_socket.recv_strings(frames))
          frames
        end

        def teardown
          @backend_socket.try(:close)
          @zmq_context.try(:terminate) unless inproc?
        end

        def write_to_backend(frames)
          zmq_error_check(@backend_socket.send_strings(frames))
        end
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
from testinfra.backend import base

class DockerBackend(base.BaseBackend):
    NAME = "docker"

    def __init__(self, name, *args, **kwargs):
        self.name, self.user = self.parse_containerspec(name)
        super().__init__(self.name, *args, **kwargs)

    def run(self, command, *args, **kwargs):
        cmd = self.get_command(command, *args)
        if self.user is not None:
            out = self.run_local(
                "docker exec -u %s %s /bin/sh -c %s",
                self.user, self.name, cmd)
        else:
            out = self.run_local(
                "docker exec %s /bin/sh -c %s", self.name, cmd)
        out.command = self.encode(cmd)
        return out


text:
AudioReceiveStream::AudioReceiveStream(VoiceTransport *t):
    voiceTransport(t), voiceChannel(-1), voiceChannelTransport(NULL) {
}

void AudioReceiveStream::startSend() {
}

void AudioReceiveStream::startReceive() {
    WebRTC *rtc = WebRTC::sharedWebRTC();
    rtc->voe_base->StartReceive(this->voiceChannel);
}

void AudioReceiveStream::start() {
    WebRTC *rtc = WebRTC::sharedWebRTC();

    this->voiceChannel = rtc->voe_base->CreateChannel();

    this->voiceChannelTransport = new VoiceChannelTransport(rtc->voe_network, this->voiceChannel, this->voiceTransport, false);

    startReceive();
    startSend();
    rtc->voe_base->StartPlayout(this->voiceChannel);
}

void AudioReceiveStream::stop() {
    WebRTC *rtc = WebRTC::sharedWebRTC();

    rtc->voe_base->StopReceive(this->voiceChannel);
    rtc->voe_base->StopPlayout(this->voiceChannel);
    rtc->voe_base->DeleteChannel(this->voiceChannel);
    delete this->voiceChannelTransport;
    this->voiceChannelTransport = NULL;
}


text:
<?php

namespace hiqdev\yii2\cart;

use Closure;
use Yii;
use yii\helpers\Url;

/**
 * Cart Module.
 *
 * Example application configuration:
 *
 * ```php
 * 'modules' => [
 *     'cart' => [
 *         'class'  => 'hiqdev\yii2\cart\Module',
 *     ],
 * ],
 * ```
 */
class Module extends \yii\base\Module
{
    /**
     * @var array array of the options that will be passed to [[set]]
     */
    public $shoppingCartOptions = [];

    /**
     * Cart component ID.
     */
    const CART_COMPONENT_ID = 'cart';

    /**
     * {@inheritdoc}
     * @throws \yii\base\InvalidConfigException
     */
    public function init()
    {
        parent::init();
        if (!$this->has(static::CART_COMPONENT_ID)) {
            $this->set(static::CART_COMPONENT_ID, array_merge([
                'class' => 'hiqdev\yii2\cart\ShoppingCart',
            ], $this->shoppingCartOptions));
        }
        $this->get(static::CART_COMPONENT_ID)->module = $this;
        $this->registerTranslations();
    }

    /**
     * Registers translations.
     * @void
     */
    public function registerTranslations()
    {
        Yii::$app->i18n->translations['cart'] = [
            'class'          => 'yii\i18n\PhpMessageSource',
            'sourceLanguage' => 'en-US',
            'basePath'       => '@hiqdev/yii2/cart/messages',
            'fileMap'        => [
                'merchant' => 'cart.php',
            ],
        ];
    }

    /**
     * @var string the module name
     */
    public static $name = 'cart';

    /**
     * Finds cart module.
     * TODO think of how to find NOT by name.
     */
    public static function getInstance()
    {
        return Yii::$app->getModule(static::$name);
    }

    /**
     * @throws \yii\base\InvalidConfigException
     * @return null|\yz\shoppingcart\ShoppingCart|ShoppingCart
     */
    public function getCart()
    {
        return $this->get(static::CART_COMPONENT_ID);
    }

    public function createUrl($route = null)
    {
        $params = is_array($route) ? $route : [$route];
        $params[0] = '/' . $this->id . '/' . (strpos($params[0], '/') !== false ? $params[0] : 'cart/' . ($params[0] ?: 'index'));

        return Url::toRoute($params);
    }

    /**
     * @var string|array route to the terms of use page, suitable for Url::to().
     */
    public $termsPage;

    /**
     * @var string|array route to the order page, suitable for Url::to().
     */
    public $orderPage = ['order'];

    protected $_orderButton;

    public function setOrderButton($value)
    {
        $this->_orderButton = $value;
    }

    public function getOrderButton()
    {
        return $this->_orderButton instanceof Closure ? call_user_func($this->_orderButton, $this) : $this->_orderButton;
    }

    protected $_paymentMethods;

    public function setPaymentMethods($value)
    {
        $this->_paymentMethods = $value;
    }

    public function getPaymentMethods()
    {
        return $this->_paymentMethods instanceof Closure ? call_user_func($this->_paymentMethods, $this) : $this->_paymentMethods;
    }
}


text:
local class = require "andross.middleclass"
local Pose = require "andross.pose"

local AnimationManager = class("AnimationManager")

function AnimationManager:initialize(skeleton, animations, skin)
    self.skeleton = skeleton
    self.skin = skin
    self.animationStates = {}
    self.layers = {{alpha = 1.0, animations = {}}}
    for _, anim in pairs(animations) do
        self.animationStates[anim.name] = {
            animation = anim,
            time = 0.0,
            speed = 1.0,
            playing = false,
            loopPoint = 0, -- the frame to loop to
            callbacks = {},
            blendWeight = 0.0,
            layer = 1,
            weightSpeed = 0,
            range = anim.duration,
        }
        self.layers[1].animations[anim.name] = self.animationStates[anim.name]
    end
    -- self.layers might be sparse, so that iterating via ipairs or #self.layers
    -- might terminate early. So we have another list, which just stores a list of
    -- layer indices (sorted)
    self.layerList = {1}
end

function AnimationManager:getAnimation(name)
    return self.animationStates[name].animation
end

-- This functionality should be improved. I have never used something like this before, so I
-- don't really know it's use cases and caveats, but I know there should probably be a way to
-- disable/remove callbacks afterwards
function AnimationManager:setCallback(name, time, callback)
    table.insert(self.animationStates[name].callbacks, {time = time, callback = callback})
end

function AnimationManager:setSpeed(name, speed)
    self.animationStates[name].speed = speed
end

function AnimationManager:setDuration(name, duration, range, start)
    start = start or self.animationStates[name].time
    range = range or self.animationStates[name].range
    self.animationStates[name].speed = (range - start) / duration
end

function AnimationManager:setTime(name, time)
    self.animationStates[name].time = time
end

function AnimationManager:setLooping(name, loopPoint)
    if type(loopPoint) == "boolean" then
        if loopPoint then
            self.animationStates[name].loopPoint = 0
        else
            self.animationStates[name].loopPoint = nil
        end
    else
        self.animationStates[name].loopPoint = loopPoint
    end
end

function AnimationManager:setRange(name, range)
    self.animationStates[name].range = range
end

function AnimationManager:setBlendWeight(name, blendWeight)
    self.animationStates[name].blendWeight = math.min(math.max(blendWeight, 0.0), 1.0)
end

function AnimationManager:getBlendWeight(name)
    return self.animationStates[name].blendWeight
end

function AnimationManager:play(name, weight, startTime)
    self.animationStates[name].playing = true
    if weight then self.animationStates[name].blendWeight = weight end
    self.animationStates[name].time = startTime or 0
end

function AnimationManager:stop(name)
    self.animationStates[name].playing = false
end

function AnimationManager:isPlaying(name)
    return self.animationStates[name].playing
end

function AnimationManager:isFinished(name)
    return not self.animationStates[name].playing and self.animationStates[name].time >= self.animationStates[name].animation.duration
end

-- makes sure the weight of the animation <name> is increased to targetWeight in duration seconds
-- also decreases all other weights on the same layer to zero in the same amount of time
-- it's easy to show that the relative weight of all the decreasing weight animations
-- stays the same for the whole fade
-- obviously this is not the case for the animation faded in
function AnimationManager:fadeInEx(name, duration, targetWeight) -- Ex = "exclusive"
    local layer = self.layers[self.animationStates[name].layer]
    for otherName, anim in pairs(layer.animations) do
        self:fadeOut(otherName, duration)
    end
    self:fade(name, duration, targetWeight or 1.0)
    self:play(name)
end

function AnimationManager:fade(name, duration, targetWeight)
    local anim = self.animationStates[name]
    anim.weightSpeed = (targetWeight - anim.blendWeight) / duration
    anim.targetWeight = targetWeight
end

function AnimationManager:fadeIn(name, duration, targetWeight)
    self:fade(name, duration, targetWeight or 1.0)
end

function AnimationManager:fadeOut(name, duration)
    self:fade(name, duration, 0.0)
end

-- These things only exist if you want to manage animations as a group
-- then you can just fade your group in and multiply it with your sub-weights
-- also you can fade in something else and the group get's faded out.
-- This is essentially just a mock animation that has a weight than can be animated and
-- will be animated by fadeInEx (if called for other animations)
-- see examples/highlevelapi.lua to see how it can be used
function AnimationManager:addAnimationGroup(name)
    self.animationStates[name] = {
        animation = nil,
        blendWeight = 0.0,
        layer = 1,
        weightSpeed = 0,
    }
    self.layers[1].animations[name] = self.animationStates[name]
end

function AnimationManager:getState(name)
    return self.animationStates[name]
end

function AnimationManager:rebuildLayerList()
    local layers = {}
    for name, animState in pairs(self.animationStates) do
        layers[animState.layer] = true
    end

    self.layerList = {}
    for layerId, layer in pairs(layers) do
        table.insert(self.layerList, layerId)
    end
    table.sort(self.layerList)
end

function AnimationManager:setLayer(name, layer)
    if self.layers[layer] == nil then
        self.layers[layer] = {alpha = 1.0, animations = {}}
    end

    local animState = self.animationStates[name]
    self.layers[animState.layer].animations[name] = nil
    animState.layer = layer
    self.layers[layer].animations[name] = animState
    self:rebuildLayerList()
end

function AnimationManager:setLayerAlpha(layer, alpha)
    if self.layers[layer] == nil then
        self.layers[layer] = {alpha = alpha, animations = {}}
    else
        self.layers[layer].alpha = alpha
    end
end

function AnimationManager:update(dt)
    local pose = nil

    --local layerMixParams = {}
    for _, layerId in ipairs(self.layerList) do
        local layer = self.layers[layerId]

        -- consider reusing this table, so far no difference can be measured between
        -- this and a static (module-local) mixParams
        local mixParams = {}
        for name, animState in pairs(layer.animations) do
            local anim = animState.animation
            if animState.playing and anim then
                local oldTime = animState.time
                local time = oldTime + dt * animState.speed

                -- callbacks
                for _, cb in ipairs(animState.callbacks) do
                    if oldTime < cb.time and time >= cb.time then
                        cb.callback(self, anim.name)
                    end
                end

                -- looping
                if time > animState.range then
                    if animState.loopPoint then
                        time = time % animState.range + animState.loopPoint
                    else
                        time = animState.range
                        animState.playing = false
                    end
                end
                animState.time = time
            end

            -- animate weights
            -- NOTE: you can not set a nonzero weight speed for a weight > 1 or < 0
            if math.abs(animState.weightSpeed) > 0 then
                local preDiff = animState.blendWeight - animState.targetWeight
                animState.blendWeight = animState.blendWeight + animState.weightSpeed * dt
                animState.blendWeight = math.max(0, math.min(1, animState.blendWeight))

                local postDiff = animState.blendWeight - animState.targetWeight
                if preDiff * postDiff <= 0 then
                    animState.blendWeight = animState.targetWeight
                    animState.weightSpeed = 0
                end
            end

            if animState.blendWeight > 0 and anim then
                local pose = anim:getPose(animState.time)
                table.insert(mixParams, pose)
                table.insert(mixParams, animState.blendWeight)
                --print(anim.name, animState.blendWeight)
            end
        end

        layer._pose = Pose.static:mix(unpack(mixParams))
        if pose == nil then
            pose = layer._pose
        else
            assert("Multiple layers not yet implemented!")
            pose = Pose.static:overlay(pose, layer._pose, layer.alpha)
        end
    end

    self.currentPose = pose
end

function AnimationManager:updateSkeleton()
    self.skeleton:update()
end

function AnimationManager:poseSkeleton(updateSkeleton)
    if updateSkeleton == nil then updateSkeleton = true end

    self.skeleton:reset()
    if self.currentPose then
        self.currentPose:apply(self.skeleton)
    end

    if updateSkeleton then
        self.skeleton:update()
    end
end

function AnimationManager:render()
    self.skin:render(self.skeleton)
end

function AnimationManager:poseAndRender()
    self:poseSkeleton(true)
    self:render()
end

return AnimationManager


text:
<?php

/**
 * This function generates a recurive HTML list from an array
 * or an iterable object. By default, it returns an unordered
 * list (UL). But you can change the templates through the $options
 * argument.
 *
 * Options: (as a key-value array)
 * - outer_tpl' wrapper for all rows (default: '
%s
')
 * - inner_tpl' => '
%1$s
'
 *
 * @param Iterator $list
 * @param array $options
 * @return null
 */
function getHtmlList( $list, array $options = array() )
{
    if( empty( $list ) || (!is_array( $list ) && !($list instanceof Iterator) ) )
    {
        return null;
    }

    $options = array_merge( array(
        'outer_tpl' => '
%1$s
',
        'inner_tpl' => '
%1$s
',
            ), $options );

    $html = '';

    foreach( $list as $key => $value )
    {
        if( is_array( $value ) || ($value instanceof Iterator) )
        {
            $value = getHtmlList( $value );
        }
        $html .= sprintf( $options['inner_tpl'], $value, $key );
    }

    return sprintf( $options['outer_tpl'], $html );
}


text:
module 'mock_edit'

--------------------------------------------------------------------
--COMMAND: create global object
--------------------------------------------------------------------
CLASS: CmdCreateGlobalObject ( EditorCommand )
	:register( 'scene_editor/create_global_object' )

function CmdCreateGlobalObject:init( option )
	self.className = option.name
end

function CmdCreateGlobalObject:redo()
	local objClas = mock.getGlobalObjectClass( self.className )
	assert( objClas )
	local object = objClas()
	self.created = object
	local lib = mock.game:getGlobalObjectLibrary()
	local node = lib.root:addObject( 'object', object )
	gii.emitPythonSignal('global_object.added', node )
end

function CmdCreateGlobalObject:undo()
	--TODO
	gii.emitPythonSignal('global_object.removed', self.created )
end

--------------------------------------------------------------------
--COMMAND: remove global object
--------------------------------------------------------------------
CLASS: CmdRemoveGlobalObject ( EditorCommand )
	:register( 'scene_editor/remove_global_object' )

function CmdRemoveGlobalObject:init( option )
	self.target = option.target
end

function CmdRemoveGlobalObject:redo()
	--TODO!!!!
	local target = self.target
	local parent = target and target.parent
	if parent then
		parent:removeNode( target.name )
		gii.emitPythonSignal( 'global_object.removed', target )
		return true
	else
		return false
	end
end

function CmdRemoveGlobalObject:undo()
	--TODO
	local target, parent = self.target, self.parent
	parent:addNode( target.name, target )
	gii.emitPythonSignal('global_object.added', target, 'undo' )

end

--------------------------------------------------------------------
--COMMAND: clone global object
--------------------------------------------------------------------
CLASS: CmdCloneGlobalObject ( EditorCommand )
	:register( 'scene_editor/clone_global_object' )

function CmdCloneGlobalObject:init( option )
	self.className = option.name
end

function CmdCloneGlobalObject:redo()
	--TODO!!!!
end

function CmdCloneGlobalObject:undo()
	--TODO
	gii.emitPythonSignal('global_object.removed', self.created )
end


text:
package io.reactivex.internal.operators.maybe;

import static org.junit.Assert.*;

import java.util.*;

import org.junit.Test;

import io.reactivex.*;
import io.reactivex.exceptions.TestException;
import io.reactivex.functions.*;
import io.reactivex.internal.functions.Functions;
import io.reactivex.observers.TestObserver;
import io.reactivex.plugins.RxJavaPlugins;
import io.reactivex.subjects.PublishSubject;

public class MaybeDoAfterSuccessTest {

    final List<Integer> values = new ArrayList<Integer>();

    final Consumer<Integer> afterSuccess = new Consumer<Integer>() {
        @Override
        public void accept(Integer e) throws Exception {
            values.add(-e);
        }
    };

    final TestObserver<Integer> ts = new TestObserver<Integer>() {
        @Override
        public void onNext(Integer t) {
            super.onNext(t);
            MaybeDoAfterSuccessTest.this.values.add(t);
        }
    };

    @Test
    public void just() {
        Maybe.just(1)
        .doAfterSuccess(afterSuccess)
        .subscribeWith(ts)
        .assertResult(1);

        assertEquals(Arrays.asList(1, -1), values);
    }

    @Test
    public void error() {
        Maybe.<Integer>error(new TestException())
        .doAfterSuccess(afterSuccess)
        .subscribeWith(ts)
        .assertFailure(TestException.class);

        assertTrue(values.isEmpty());
    }

    @Test
    public void empty() {
        Maybe.<Integer>empty()
        .doAfterSuccess(afterSuccess)
        .subscribeWith(ts)
        .assertResult();

        assertTrue(values.isEmpty());
    }

    @Test(expected = NullPointerException.class)
    public void consumerNull() {
        Maybe.just(1).doAfterSuccess(null);
    }

    @Test
    public void justConditional() {
        Maybe.just(1)
        .doAfterSuccess(afterSuccess)
        .filter(Functions.alwaysTrue())
        .subscribeWith(ts)
        .assertResult(1);

        assertEquals(Arrays.asList(1, -1), values);
    }

    @Test
    public void errorConditional() {
        Maybe.<Integer>error(new TestException())
        .doAfterSuccess(afterSuccess)
        .filter(Functions.alwaysTrue())
        .subscribeWith(ts)
        .assertFailure(TestException.class);

        assertTrue(values.isEmpty());
    }

    @Test
    public void emptyConditional() {
        Maybe.<Integer>empty()
        .doAfterSuccess(afterSuccess)
        .filter(Functions.alwaysTrue())
        .subscribeWith(ts)
        .assertResult();

        assertTrue(values.isEmpty());
    }

    @Test
    public void consumerThrows() {
        List<Throwable> errors = TestHelper.trackPluginErrors();
        try {
            Maybe.just(1)
            .doAfterSuccess(new Consumer<Integer>() {
                @Override
                public void accept(Integer e) throws Exception {
                    throw new TestException();
                }
            })
            .test()
            .assertResult(1);

            TestHelper.assertError(errors, 0, TestException.class);
        } finally {
            RxJavaPlugins.reset();
        }
    }

    @Test
    public void dispose() {
        TestHelper.checkDisposed(PublishSubject.<Integer>create().singleElement().doAfterSuccess(afterSuccess));
    }

    @Test
    public void doubleOnSubscribe() {
        TestHelper.checkDoubleOnSubscribeMaybe(new Function<Maybe<Integer>, MaybeSource<Integer>>() {
            @Override
            public MaybeSource<Integer> apply(Maybe<Integer> m) throws Exception {
                return m.doAfterSuccess(afterSuccess);
            }
        });
    }
}


text:
package org.codehaus.mojo.buildhelper;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;

public abstract class AbstractDefinePropertyMojo
    extends AbstractMojo
{
    /**
     * The maven project
     */
    @Parameter( readonly = true, defaultValue = "${project}" )
    protected MavenProject project;

    protected void defineProperty( String name, String value )
    {
        if ( getLog().isDebugEnabled() )
        {
            getLog().debug( "define property " + name + " = \"" + value + "\"" );
        }

        project.getProperties().put( name, value );
    }

    /**
     * Get the current project instance.
     *
     * @return the project
     */
    public MavenProject getProject()
    {
        return this.project;
    }
}


text:
{% extends "main/base.html" %}
{% load url from future %}
{% load i18n %}
{% load notifications_tags %}
{% load bootstrap3 %}
{% block head_title %}Acerca de...{%endblock head_title%}
{% load static %}
{% block scripts %}
{% endblock %}
{% load static %}

{% block styles %}
{% endblock styles %}

{% block content %}

Error 404 Página no encontrada

			La url a la que intentas acceder no existe. Esto es todo lo que sabemos.
			Volver

{% endblock content %}


text:
<?php
namespace TraceguideBase\Client;

use \mersenne_twister\twister;

class Util {

    protected $_rng = null;

    public function __construct() {
        $seed = floor(microtime(TRUE) * 1000.0 * 1000.0);
        $this->_rng = new \mersenne_twister\twister($seed);
    }

    /**
     * Returns an integer in the following closed range (i.e. inclusive,
     * $lower <= $x <= $upper).
     */
    public function randIntRange($lower, $upper) {
        return $this->_rng->rangeint($lower, $upper);
    }

    /**
     * Returns a positive or *negative* 32-bit integer.
     * http://kingfisher.nfshost.com/sw/twister/
     */
    public function randInt32() {
        return $this->_rng->int32();
    }

    public function nowMicros() {
        // Note: microtime returns the current time *in seconds* but with
        // microsecond accuracy (not the current time in microseconds!).
        return floor(microtime(TRUE) * 1000.0 * 1000.0);
    }
}


text:
BSLS_IDENT_RCSID(btls5_negotiator_cpp,"$Id$ $CSID$")

#include <btls5_detailedstatus.h>
#include <btls5_testserver.h>  // for testing only

#include <bslmt_lockguard.h>
#include <bslmt_mutex.h>
#include <bdlf_bind.h>
#include <bdlf_placeholder.h>
#include <bdlt_currenttime.h>
#include <bslma_default.h>
#include <bsls_assert.h>
#include <bsls_atomic.h>
#include <btlso_eventmanager.h>
#include <btlso_eventtype.h>

#include <bsl_cstddef.h>
#include <bsl_memory.h>
#include <bsl_new.h>
#include <bsl_sstream.h>
#include <bsl_string.h>

namespace BloombergLP {

namespace btls5 {

namespace {

// SOCKS5 protocol messages as defined in RFCs 1928 and 1929.

enum Socks5 {
    VERSION                        = 0x05,
    VERSION_USERNAME_PASSWORD_AUTH = 0x01
};

enum Authentication {
    NONE         = 0x00
  , PASSWORD     = 0x02
  , UNACCEPTABLE = 0xFF
};

enum CommandCode {
    TCP_STREAM_CONNECTION = 0x01
  , TCP_PORT_BINDING      = 0x02
  , UDP_PORT              = 0x03
};

enum ATYP {
    IPv4ADDRESS = 0x01
  , DOMAINNAME  = 0x03
  , IPv6ADDRESS = 0x04
};

enum StatusCode {
    REQUEST_GRANTED            = 0x00
  , GENERAL_FAILURE            = 0x01
  , CONNECTION_NOT_ALLOWED     = 0x02
  , NETWORK_UNREACHABLE        = 0x03
  , HOST_UNREACHABLE           = 0x04
  , CONNECTION_REFUSED         = 0x05
  , TTL_EXPIRED                = 0x06
  , CMD_PROTO_NOT_SUPPORTED    = 0x07
  , ADDRESS_TYPE_NOT_SUPPORTED = 0x08
};

struct MethodRequestPkt {
    unsigned char d_ver;
    unsigned char d_nmethods;
    unsigned char d_methods[2];
};

struct MethodResponsePkt {
    unsigned char d_ver;
    unsigned char d_method;
};

struct AuthenticationResponsePkt {
    unsigned char d_ver;
    unsigned char d_status;
};

struct ConnectBase {
    unsigned char d_ver;
    unsigned char d_cmd;
    unsigned char d_rsv;
    unsigned char d_atype;
};

struct ConnectRspBase {
    unsigned char d_ver;
    unsigned char d_rep;
    unsigned char d_rsv;
    unsigned char d_atype;
};

}  // close unnamed namespace

                        // ============================
                        // class Negotiator_Negotiation
                        // ============================

class Negotiator_Negotiation {
    // This mechanism class describes the state of a SOCKS connection
    // negotiation.  The object lifetime is managed by using a
    // 'bsl::shared_ptr<Negotiator_Negotiation>' in callback registration.  A
    // 'Negotiator_Negotiation' object is in one of two states: it is created
    // in the normal state indicated by 'd_terminating == 0', and it enters a
    // terminating state when 'd_terminating != 0'.

  public:
    // DATA
    Credentials                              d_credentials;     // SOCKS5
                                                                // credentials

    btlso::Endpoint                          d_destination;     // destination

    btlso::StreamSocket<btlso::IPv4Address> *d_socket_p;        // proxy socket

    btlso::SocketHandle::Handle              d_handle;          // OS-level
                                                                // socket

    Negotiator::NegotiationStateCallback     d_callback;        // result
                                                                // callback

    btlmt::TcpTimerEventManager             *d_eventManager_p;  // asynch event
                                                                // registration
                                                                // manager, not
                                                                // owned

    bsls::TimeInterval                       d_timeout;         // timeout

    void                                    *d_timer;           // expiration
                                                                // timer

    bslmt::Mutex                             d_timerLock;       // 'd_timer'
                                                                // access

    bsls::AtomicInt                          d_terminating;     // negotiation
                                                                // being
                                                                // terminated

    // CREATORS
    Negotiator_Negotiation(
                      btlso::StreamSocket<btlso::IPv4Address> *socket,
                      const btlso::Endpoint&                   destination,
                      Negotiator::NegotiationStateCallback     callback,
                      const bsls::TimeInterval&                timeout,
                      btlmt::TcpTimerEventManager             *eventManager,
                      bslma::Allocator                        *basicAllocator);
        // Create a 'Negotiator_Negotiation' object to connect to the specified
        // 'destination' over the specified 'socket' and asynchronously invoke
        // the specified 'callback', using the specified 'eventManager' to
        // schedule callbacks.  If the specified 'timeout' is equal to
        // 'bsls::TimeInterval()' the negotiation will not time out.
        // Otherwise, the negotiation will conclude, either successfully or in
        // error, within the 'timeout' interval.  Use the specified
        // 'basicAllocator' to supply memory.

    ~Negotiator_Negotiation();
        // Destroy this object.
};

                       // -----------------------------
                       // struct Negotiator_Negotiation
                       // -----------------------------

// CREATORS
Negotiator_Negotiation::Negotiator_Negotiation(
                       btlso::StreamSocket<btlso::IPv4Address> *socket,
                       const btlso::Endpoint&                   destination,
                       Negotiator::NegotiationStateCallback     callback,
                       const bsls::TimeInterval&                timeout,
                       btlmt::TcpTimerEventManager             *eventManager,
                       bslma::Allocator                        *basicAllocator)
: d_credentials(basicAllocator)
, d_destination(destination, basicAllocator)
, d_socket_p(socket)
, d_handle(socket->handle())
, d_callback(
          bsl::allocator_arg_t(),
          bsl::allocator<Negotiator::NegotiationStateCallback>(basicAllocator),
          callback)
, d_eventManager_p(eventManager)
, d_timeout(timeout)
, d_timer(0)
{
    BSLS_ASSERT(socket);
    BSLS_ASSERT(eventManager);
}

Negotiator_Negotiation::~Negotiator_Negotiation()
{
    // clean up in case 'terminate' was called prior to registering timer

    if (d_timer) {
        d_eventManager_p->deregisterTimer(d_timer);
    }
}

// STATIC HELPER FUNCTIONS

static void terminate(
                     btls5::Negotiator::NegotiationHandle negotiation,
                     btls5::Negotiator::NegotiationStatus status,
                     const btls5::DetailedStatus&         error,
                     bool                                 canceledFlag = false)
    // Terminate the specified 'negotiation'.  If the optionally specified
    // 'canceledFlag' is 'false', invoke the user-supplied callback with the
    // specified 'status' and 'error'.  If 'canceledFlag' is 'true', do not
    // invoke the callback.
{
    if (negotiation->d_terminating.testAndSwap(0, 1)) {

        // this negotiation is already being terminated

        return;                                                       // RETURN
    }

    negotiation->d_eventManager_p->deregisterSocket(negotiation->d_handle);

    {
        bslmt::LockGuard<bslmt::Mutex> lock(&negotiation->d_timerLock);
        if (negotiation->d_timer) {
            negotiation->d_eventManager_p->deregisterTimer(
                                                         negotiation->d_timer);
        }
    }

    if (!canceledFlag) {
        negotiation->d_callback(status, error);
    }
}

typedef void (*ReadCallback)(btls5::Negotiator::NegotiationHandle negotiation);
    // A callback of this type is invoked when data is received for the
    // specified 'negotiation'.

static int registerReadCb(ReadCallback                         callback,
                          btls5::Negotiator::NegotiationHandle negotiation)
    // Register the specified 'callback' to be invoked with the argument of the
    // specified 'negotiation' on read events on 'negotiation->d_handle'.
    // Return 0 on success and a negative value otherwise.
{
    btlso::EventManager::Callback readCb =
                                   bdlf::BindUtil::bind(callback, negotiation);

    int rc = negotiation->d_eventManager_p->registerSocketEvent(
                                                      negotiation->d_handle,
                                                      btlso::EventType::e_READ,
                                                      readCb);

    if (rc < 0) {
        terminate(negotiation,
                  btls5::Negotiator::e_ERROR,
                  btls5::DetailedStatus("error registering read handler"));
        return btls5::Negotiator::e_ERROR;                            // RETURN
    }
    return 0;
}

static void connectCallback(btls5::Negotiator::NegotiationHandle negotiation)
    // Process a response from the SOCKS5 connect request for the specified
    // 'negotiation'.
{
    if (negotiation->d_terminating) {
        return;                                                       // RETURN
    }

    bsl::ostringstream e("connect response: ");
    e.seekp(0, bsl::ios_base::end);

    ConnectRspBase hdr;
    int rc = negotiation->d_socket_p->read(reinterpret_cast<char *>(&hdr),
                                           sizeof hdr);

    if (sizeof hdr != rc) {
        e << "error reading: " << rc;

        terminate(negotiation,
                  btls5::Negotiator::e_ERROR,
                  btls5::DetailedStatus(e.str()));
        return;                                                       // RETURN
    }

    if (hdr.d_ver != VERSION) {
        e << "invalid SOCK version, expected " << VERSION
          << ", got " << hdr.d_ver;

        terminate(negotiation,
                  btls5::Negotiator::e_ERROR,
                  btls5::DetailedStatus(e.str()));
        return;                                                       // RETURN
    }

    int addressLength;  // bytes to read for the bound address
    if (IPv4ADDRESS == hdr.d_atype) {
        addressLength = 4;
    } else if (IPv6ADDRESS == hdr.d_atype) {
        addressLength = 16;
    } else if (DOMAINNAME == hdr.d_atype) {
        unsigned char length = 0;
        rc = negotiation->d_socket_p->read(reinterpret_cast<char *>(&length),
                                           1);
        if (1 != rc) {
            e << "error reading domainname length: " << rc;

            terminate(negotiation,
                      btls5::Negotiator::e_ERROR,
                      btls5::DetailedStatus(e.str()));
            return;                                                   // RETURN
        }
        addressLength = length;
    } else {
        e << "received invalid address type: " << hdr.d_atype;

        terminate(negotiation,
                  btls5::Negotiator::e_ERROR,
                  btls5::DetailedStatus(e.str()));
        return;                                                       // RETURN
    }

    // consume address and port (not presently used)

    char buf[255 + 2];  // maximum length of address + 2-byte port
    BSLS_ASSERT(addressLength + 2 <= static_cast<int>(sizeof buf));
    rc = negotiation->d_socket_p->read(buf, addressLength + 2);

    if (addressLength + 2 != rc) {
        e << "error reading bound address, expected " << addressLength + 2
          << ", got " << rc;

        terminate(negotiation,
                  btls5::Negotiator::e_ERROR,
                  btls5::DetailedStatus(e.str()));
        return;                                                       // RETURN
    }

    switch (hdr.d_rep) {
      case REQUEST_GRANTED: {
        e << "status: request granted";
      } break;
      case GENERAL_FAILURE: {
        e << "status: general failure";
      } break;
      case CONNECTION_NOT_ALLOWED: {
        e << "status: connection not allowed";
      } break;
      case NETWORK_UNREACHABLE: {
        e << "status: network unreachable";
      } break;
      case HOST_UNREACHABLE: {
        e << "status: host unreachable";
      } break;
      case CONNECTION_REFUSED: {
        e << "status: connection refused";
      } break;
      case TTL_EXPIRED: {
        e << "status: time to live expired";
      } break;
      case CMD_PROTO_NOT_SUPPORTED: {
        e << "status: cmd protocol not supported";
      } break;
      case ADDRESS_TYPE_NOT_SUPPORTED: {
        e << "status: address type not supported";
      } break;
      default: {
        e << "status: unknown = " << hdr.d_rep;
      } break;
    }
    terminate(negotiation,
              REQUEST_GRANTED == hdr.d_rep
              ? btls5::Negotiator::e_SUCCESS
              : btls5::Negotiator::e_ERROR,
              btls5::DetailedStatus(e.str()));
}

static void connectToEndpoint(btls5::Negotiator::NegotiationHandle negotiation)
    // Send the request for the specified 'negotiation' to connect to
    // 'negotiation->d_destination' via the proxy host reachable by
    // 'negotiation->d_socket_p'.
{
    bsl::ostringstream req;

    req << static_cast<unsigned char>(VERSION)
        << static_cast<unsigned char>(TCP_STREAM_CONNECTION)
        << static_cast<unsigned char>(0x00);                  // reserved

    const bool dottedDecimal = btlso::IPv4Address::isValidAddress(
                               negotiation->d_destination.hostname().c_str());
    if (dottedDecimal) {
        req << static_cast<unsigned char>(IPv4ADDRESS);       // address type
        btlso::IPv4Address   ipv4Address(
                                 negotiation->d_destination.hostname().c_str(),
                                 negotiation->d_destination.port());
        const int            ipAddress = ipv4Address.ipAddress();
        const unsigned char *addrPtr =
                           reinterpret_cast<const unsigned char *>(&ipAddress);
        req << addrPtr[0] << addrPtr[1] << addrPtr[2] << addrPtr[3];
    } else {
        req << static_cast<unsigned char>(DOMAINNAME);        // address type

        bsl::size_t length = negotiation->d_destination.hostname().size();
        req << static_cast<unsigned char>(length)
            << negotiation->d_destination.hostname();
    }

    // encode 2-byte port in network (bigendian) order: MSB first

    req << static_cast<unsigned char>(
                               (negotiation->d_destination.port() >> 8) & 0xff)
        << static_cast<unsigned char>(
                                     negotiation->d_destination.port() & 0xff);

    if (registerReadCb(connectCallback, negotiation)) {
        return;                                                       // RETURN
    }
    const bsl::string& buf = req.str();
    int rc = negotiation->d_socket_p->write(buf.c_str(), buf.size());
    if (rc != static_cast<int>(buf.size())) {
        terminate(negotiation,
                  btls5::Negotiator::e_ERROR,
                  btls5::DetailedStatus("error writing connection request"));
        return;                                                       // RETURN
    }
}

static void sendAuthenticationRequest(
                             btls5::Negotiator::NegotiationHandle negotiation);
    // Send the username and password credentials to authenticate with the
    // SOCKS5 server for the specified 'negotiation'.

static void authenticationCallback(
                              btls5::Negotiator::NegotiationHandle negotiation)
    // Process the response to an authentication request for the specified
    // 'negotiation'.
{
    if (negotiation->d_terminating) {
        return;                                                       // RETURN
    }

    AuthenticationResponsePkt pkt;
    int rc = negotiation->d_socket_p->read(reinterpret_cast<char *>(&pkt),
                                           sizeof pkt);
    if (sizeof pkt != rc) {
        terminate(
               negotiation,
               btls5::Negotiator::e_ERROR,
               btls5::DetailedStatus("error reading authentication response"));
        return;                                                       // RETURN
    }

    if (pkt.d_status) {
        terminate(negotiation,
                  btls5::Negotiator::e_ERROR,
                  btls5::DetailedStatus("authentication rejected"));
        return;                                                       // RETURN
    }

    connectToEndpoint(negotiation);
}

static void sendAuthenticationRequest(
                              btls5::Negotiator::NegotiationHandle negotiation)
    // Send an authentication request for the specified 'negotiation'.
{
    // The Username/Password request (RFC 1929) format is:
    // +----+------+----------+------+----------+
    // |VER | ULEN |  UNAME   | PLEN |  PASSWD  |
    // +----+------+----------+------+----------+
    // | 1  |  1   | 1 to 255 |  1   | 1 to 255 |
    // +----+------+----------+------+----------+

    bsl::ostringstream request;
    request << static_cast<unsigned char>(VERSION_USERNAME_PASSWORD_AUTH)
            << static_cast<unsigned char>(
                                  negotiation->d_credentials.username().size())
            << negotiation->d_credentials.username()
            << static_cast<unsigned char>(
                                  negotiation->d_credentials.password().size())
            << negotiation->d_credentials.password();

    if (registerReadCb(authenticationCallback, negotiation)) {
        return;                                                       // RETURN
    }
    const bsl::string& buf = request.str();
    int rc = negotiation->d_socket_p->write(buf.c_str(), buf.size());

    if (rc != static_cast<int>(buf.size())) {
        terminate(negotiation,
                  btls5::Negotiator::e_ERROR,
                  btls5::DetailedStatus("error writing username/password"));
        return;                                                       // RETURN
    }
}

static void methodCallback(btls5::Negotiator::NegotiationHandle negotiation)
    // Process SOCKS5 Method Selection response for the specified
    // 'negotiation'.
{
    if (negotiation->d_terminating) {
        return;                                                       // RETURN
    }

    negotiation->d_eventManager_p->deregisterSocketEvent(
                                                     negotiation->d_handle,
                                                     btlso::EventType::e_READ);
    MethodResponsePkt pkt;
    int rc = negotiation->d_socket_p->read(reinterpret_cast<char *>(&pkt),
                                           sizeof pkt);
    if (sizeof pkt != rc) {
        bsl::ostringstream description;
        description << "error reading method response, rc " << rc;
        terminate(negotiation,
                  btls5::Negotiator::e_ERROR,
                  btls5::DetailedStatus(description.str()));
        return;                                                       // RETURN
    }

    switch (pkt.d_method) {
      case NONE: {
        connectToEndpoint(negotiation);
      } break;
      case PASSWORD: {
        if (!negotiation->d_credentials.username().length()) {
            terminate(negotiation,
                      btls5::Negotiator::e_ERROR,
                      btls5::DetailedStatus(
                               "Got authentication request when we did not"
                               " offer authentication as an option, closing"));
            return;                                                   // RETURN
        }
        sendAuthenticationRequest(negotiation);
      } break;
      case UNACCEPTABLE: {
        terminate(negotiation,
                  btls5::Negotiator::e_ERROR,
                  btls5::DetailedStatus(
                          "proxy server rejected all authentication methods"));
      } break;
      default: {
        bsl::ostringstream description;
        description << "unknown response "
                    << static_cast<int>(pkt.d_method)
                    << " from proxy server";
        terminate(negotiation,
                  btls5::Negotiator::e_ERROR,
                  btls5::DetailedStatus(description.str()));
      } break;
    }
}

static void timeoutCallback(btls5::Negotiator::NegotiationHandle negotiation)
    // Expire the specified 'negotiation'.
{
    if (negotiation->d_terminating) {
        return;                                                       // RETURN
    }

    negotiation->d_timer = 0;
    terminate(negotiation,
              btls5::Negotiator::e_ERROR,
              btls5::DetailedStatus("timeout"));
}

static int sendMethodRequest(btls5::Negotiator::NegotiationHandle negotiation)
    // Send SOCKS5 greeting including list of authentication methods supported
    // using the specified 'negotiation' for managing object lifetime.  Return
    // 0 on success and a non-zero value otherwise.
{
    MethodRequestPkt pkt;
    pkt.d_ver        = VERSION;
    pkt.d_nmethods   = 2;
    pkt.d_methods[0] = NONE;
    pkt.d_methods[1] = PASSWORD;

    int length = sizeof pkt;
    if (!negotiation->d_credentials.username().length()) {

        // Don't offer PASSWORD authentication unless we have credentials.

        --pkt.d_nmethods;
        length -= sizeof *pkt.d_methods;
    }

    if (registerReadCb(methodCallback, negotiation)) {
        return btls5::Negotiator::e_ERROR;                            // RETURN
    }

    if (bsls::TimeInterval() != negotiation->d_timeout) {
        bsls::TimeInterval expiration =
                             bdlt::CurrentTime::now() + negotiation->d_timeout;
        btlso::EventManager::Callback cb =
                            bdlf::BindUtil::bind(timeoutCallback, negotiation);
        {
            bslmt::LockGuard<bslmt::Mutex> lock(&negotiation->d_timerLock);
            negotiation->d_timer =
                  negotiation->d_eventManager_p->registerTimer(expiration, cb);
        }
    }

    int rc = negotiation->d_socket_p->write(
                                          reinterpret_cast<const char *>(&pkt),
                                          length);
    if (length != rc) {
        // Since we indicate an immediate error via return code, do not invoke
        // the callback.

        const bool noCallback = true;
        terminate(negotiation,
                  btls5::Negotiator::e_ERROR,
                  btls5::DetailedStatus("error writing method request"),
                  noCallback);
        return btls5::Negotiator::e_ERROR;                            // RETURN
    }

    return 0;
}

                              // ----------------
                              // class Negotiator
                              // ----------------

// CREATORS
Negotiator::Negotiator(btlmt::TcpTimerEventManager *eventManager,
                       bslma::Allocator            *basicAllocator)
: d_eventManager_p(eventManager)
, d_allocator_p(bslma::Default::allocator(basicAllocator))
{
    BSLS_ASSERT(eventManager);
}

// MANIPULATORS
Negotiator::NegotiationHandle Negotiator::makeNegotiationHandle(
                          btlso::StreamSocket<btlso::IPv4Address> *socket,
                          const btlso::Endpoint&                   destination,
                          NegotiationStateCallback                 callback)
{
    BSLS_ASSERT(socket);

    Negotiator::NegotiationHandle negotiation(
              new (*d_allocator_p) Negotiator_Negotiation(socket,
                                                          destination,
                                                          callback,
                                                          bsls::TimeInterval(),
                                                          d_eventManager_p,
                                                          d_allocator_p),
              d_allocator_p);

    return negotiation;
}

Negotiator::NegotiationHandle Negotiator::makeNegotiationHandle(
                          btlso::StreamSocket<btlso::IPv4Address> *socket,
                          const btlso::Endpoint&                   destination,
                          NegotiationStateCallback                 callback,
                          const bsls::TimeInterval&                timeout)
{
    BSLS_ASSERT(socket);

    Negotiator::NegotiationHandle negotiation(
                  new (*d_allocator_p) Negotiator_Negotiation(socket,
                                                              destination,
                                                              callback,
                                                              timeout,
                                                              d_eventManager_p,
                                                              d_allocator_p),
                  d_allocator_p);

    return negotiation;
}

Negotiator::NegotiationHandle Negotiator::makeNegotiationHandle(
                          btlso::StreamSocket<btlso::IPv4Address> *socket,
                          const btlso::Endpoint&                   destination,
                          NegotiationStateCallback                 callback,
                          const Credentials&                       credentials)
{
    BSLS_ASSERT(socket);

    Negotiator::NegotiationHandle negotiation(
              new (*d_allocator_p) Negotiator_Negotiation(socket,
                                                          destination,
                                                          callback,
                                                          bsls::TimeInterval(),
                                                          d_eventManager_p,
                                                          d_allocator_p),
              d_allocator_p);

    negotiation->d_credentials = credentials;
    return negotiation;
}

Negotiator::NegotiationHandle Negotiator::makeNegotiationHandle(
                          btlso::StreamSocket<btlso::IPv4Address> *socket,
                          const btlso::Endpoint&                   destination,
                          NegotiationStateCallback                 callback,
                          const bsls::TimeInterval&                timeout,
                          const Credentials&                       credentials)
{
    BSLS_ASSERT(socket);

    Negotiator::NegotiationHandle negotiation(
                  new (*d_allocator_p) Negotiator_Negotiation(socket,
                                                              destination,
                                                              callback,
                                                              timeout,
                                                              d_eventManager_p,
                                                              d_allocator_p),
                  d_allocator_p);

    negotiation->d_credentials = credentials;
    return negotiation;
}

int Negotiator::startNegotiation(const NegotiationHandle& handle)
{
    return sendMethodRequest(handle);
}

void Negotiator::cancelNegotiation(const NegotiationHandle& handle)
{
    terminate(handle,
              Negotiator::e_ERROR,
              DetailedStatus("SOCKS5 negotiation canceled"),
              true);
}

}  // close package namespace

}  // close enterprise namespace

// ----------------------------------------------------------------------------
// Copyright 2015 Bloomberg Finance L.P.
//
// 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.
// ----------------------------- END-OF-FILE ----------------------------------


text:
class Api::V1::TagsController < Api::V1::BaseController
  # GET /api/v1/tags
  def index
    render json: Tag.page(page).per(per)
  end

  # GET /api/v1/tags/count
  def count
    render json: { count: Tag.count }
  end
end


text:
<resources>
    <string name="app_name">自助盖章</string>
    <string name="drawer_open">Open drawer</string>
    <string name="drawer_close">Close drawer</string>

    <!-- TODO: Remove or change this placeholder text -->
    <string name="using_seal">普通用印</string>
    <string name="using_seal_offline">紧急用印</string>
    <string name="get_seal">普通取印</string>
    <string name="get_seal_offline">紧急取印</string>
    <string name="return_seal">归还印章</string>
    <string name="using_seal_hint">请输入用印编码</string>
    <string name="get_seal_hint">请输入取印编码</string>
    <string name="send">发送</string>
    <string name="confirm">确认</string>
    <string name="scan_tip">扫码输入</string>
    <string name="hello_blank_fragment">Hello blank fragment</string>
    <string name="title_activity_take_photo">TakePhotoActivity</string>
    <string name="camera_permission_confirmation">This app demonstrates the usage of CameraView. In order to do that, it needs permission to access camera.</string>
    <string name="camera_permission_not_granted">Camera app cannot do anything without camera permission.</string>
    <string name="flash_auto">Flash auto</string>
    <string name="flash_off">Flash off</string>
    <string name="flash_on">Flash on</string>
    <string name="title_activity_settings_preference">Settings</string>

    <string name="checking">验证中……</string>
    <string name="using_seal_code_invalid">用印编码不存在</string>
    <string name="using_seal_code_used">用印编码已使用</string>
    <string name="get_seal_code_invalid">取印编码不存在</string>
    <string name="get_seal_code_used">取印编码已使用</string>
    <string name="hardware_code_invalid">机器码不对应</string>
    <string name="using_seal_code_description">用印编码有效,确认盖章信息无误后,请点击确认拍照按钮,并拍下您的正面照以存档方可盖章</string>
    <string name="get_seal_code_description">取印编码有效,确认印章信息无误后,请点击确认拍照按钮,并拍下您的正面照以存档方可取印</string>
    <string name="confirm_take_photo">确认拍照</string>

    <string name="notifyTitle">提示</string>
    <string name="gpsNotifyMsg">当前手机扫描蓝牙需要打开定位功能。</string>
    <string name="setting">前往设置</string>
    <string name="cancel">取消</string>

    <!-- Strings related to Settings -->

    <!-- Example General settings -->
    <string name="pref_header_general">General</string>

    <string name="pref_title_social_recommendations">Enable social recommendations</string>
    <string name="pref_description_social_recommendations">Recommendations for people to contact
        based on your message history
    </string>

    <string name="pref_title_display_name">Display name</string>
    <string name="pref_default_display_name">John Smith</string>

    <string name="pref_title_add_friends_to_messages">Add friends to messages</string>
    <string-array name="pref_example_list_titles">
        <item>Always</item>
        <item>When possible</item>
        <item>Never</item>
    </string-array>
    <string-array name="pref_example_list_values">
        <item>1</item>
        <item>0</item>
        <item>-1</item>
    </string-array>

    <!-- Example settings for Data & Sync -->
    <string name="pref_header_data_sync">Data & sync</string>

    <string name="pref_title_sync_frequency">Sync frequency</string>
    <string-array name="pref_sync_frequency_titles">
        <item>15 minutes</item>
        <item>30 minutes</item>
        <item>1 hour</item>
        <item>3 hours</item>
        <item>6 hours</item>
        <item>Never</item>
    </string-array>
    <string-array name="pref_sync_frequency_values">
        <item>15</item>
        <item>30</item>
        <item>60</item>
        <item>180</item>
        <item>360</item>
        <item>-1</item>
    </string-array>

    <string-array name="list_preference_entries">
        <item>Entry 1</item>
        <item>Entry 2</item>
        <item>Entry 3</item>
    </string-array>

    <string-array name="list_preference_entry_values">
        <item>1</item>
        <item>2</item>
        <item>3</item>
    </string-array>

    <string-array name="multi_select_list_preference_default_value" />

    <string name="pref_title_system_sync_settings">System sync settings</string>

    <!-- Example settings for Notifications -->
    <string name="pref_header_notifications">Notifications</string>

    <string name="pref_title_new_message_notifications">New message notifications</string>

    <string name="pref_title_ringtone">Ringtone</string>
    <string name="pref_ringtone_silent">Silent</string>

    <string name="pref_title_vibrate">Vibrate</string>
</resources>


text:
//  /* DO NOT REMOVE THIS LINE */

//  /* DO NOT REMOVE THIS LINE */

// This is the main bootstrap file for setting all the correct paths and stuff

// Domain-config sets paths for image server, api server, etc.
define("domain-config", {
    imageServer : "http://images.poms.omroep.nl/image/",
    couchDbServer : "http://couchdb.vpro.nl",
    jsServer: "http://js.vpro.nl",
    apiServer: "http://rs.vpro.nl",
    embedServer: "http://embed.vpro.nl",
    woordEmbedServer: "http://embed.woord.nl",
    npoCookieCSS: "//cookiesv2.publiekeomroep.nl/static/css/npo_cc_styles.css",
    npoCookieJs: "//cookiesv2.publiekeomroep.nl/data/script/cconsent.min",
    googleApiKey: "AIzaSyA6kZmkM8yTDGAugfJ-tOzEQ5uhlMr8hTY",
    locationApiKey: "vprodigitaal",
    locationApiSecret: "tndzOIjEwhxSBO5x"
});
(function() {
    var conf = {};

    function debugArgs() {
        /*
         * Debug magic for easily turning on and off components
         *
         * A list of all possible options
         *   - logrequireloads : Put all loads in Require through console.log
         *   - nocachebust - Don't add a ?cachebust argument to Javascript urls
         */
        var m = window.location.href.match(/(?:\?|&)debug=([^&]*)/);
        return (!m) ? false : ((m[1].split(",")).indexOf(arguments[0]) !== -1);
    };

    function getAttribute(name) {
        return document.getElementById('meta-' + name).getAttribute('content');
    }

    function getRequireConf() {
        // Get all the javascript attributes
        conf.js = {
            "remotehost" : getAttribute('jsremotehost'),
            "version" : getAttribute('jsversion'),
            "develop" : (getAttribute('jsmgnldevelop')).toString() == 'true'
        };

        var requireConf = {
            "paths" : {
                "vpro" : conf.js.remotehost + "/" + conf.js.version + "/vpro",
                "ext" : conf.js.remotehost + "/ext"
            },
            "shim": {
                // Takes care of initializing the NPO cookie functionality, depending on jquery.
                // path and require should be defined in the impl.js files
                "npo_cookies": {
                    "deps": ["jquery"],
                    "exports": "npo_cookies",
                    "init": function(jQuery) {
                        this.npo_cookies.init();
                    }
                }
            }
        };

        if (conf.js.develop) {
            if (!vpro.debugArgs('nocachebust')) {
                requireConf.urlArgs = 'cachebust=' + Math.random();
            }

            requireConf.waitSeconds = 3;
        }

        return requireConf;
    }

    // Expose to global scope
    window.vpro = window.vpro || {};
    window.vpro.conf = conf;
    window.vpro.debugArgs = debugArgs;
    window.vpro.getRequireConf = getRequireConf;
})();
(function(){
    // Trace RequireJS loads?
    if (vpro.debugArgs('logrequireloads')) {
        require.onResourceLoad = function(ctx, map, dep) {
            console.log(map, dep);
        };
    }

    var requireConf = window.vpro.getRequireConf();
    requireConf.paths.jquery = "//ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min";
    requireConf.paths.npo_cookies = "//cookiesv2.publiekeomroep.nl/data/script/cconsent.min";
    requireConf.useHandlebarsForXmltemplate = true;

    var queryParameters = (function(){
            var vars = {};
            var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
                vars[key] = value;
            });
            return vars;

        })();

    var viewVariant = 'full',               // selected/default view variant
        viewVariants = ['full', 'small'];   // available view variants

    var iOSVersion = (parseFloat(('' + (/CPU.*OS ([0-9_]{1,5})|(CPU like).*AppleWebKit.*Mobile/i.exec(navigator.userAgent) || [0,''])[1]).replace('undefined', '3_2').replace('_', '.').replace('_', '')) || 0) || 0;

    // viewVariant can be forced by defining so in the url
    // this will overwrite all behaviour
    if ( queryParameters.viewVariant && viewVariants.indexOf( queryParameters.viewVariant ) != -1 ){
        viewVariant = queryParameters.viewVariant;
        startLoading();
    } else if (
        // detects Posible iPad 1
        navigator.platform.indexOf("iPad") != -1
        // iPad 1 has a low pixelRatio
        &&  (window.devicePixelRatio || 1) == 1
        // iOS 6 cant be installed on iPad 1
        // this check detects the iOS version
        && 6 > iOSVersion
    ) {
        // the iPad 1 needs to be using the small variant to boost the performance
        // iPad 1 only difference is that is has no acceleration
        // so we have to wait on the ondevicemotion event to occur to detect this
        var time = (+new Date()) - window._perfStartTime;

        var detectIpadVersion = function(event) {
            if (!event.acceleration){
                viewVariant = 'small';
            }
            window.ondevicemotion = null;

            startLoading();
        };

        window.ondevicemotion = detectIpadVersion;

        // fallback if no event occurs
        // chooses the small variant after 1.5s
        setTimeout(function(){
            if ( window.ondevicemotion === detectIpadVersion ){
                window.ondevicemotion = null;
                viewVariant = 'small';
                startLoading();
            }

            detectIpadVersion = null;
        }, 1500);
    } else {
        // small touch devices should use the smaller view variation
        if ( Modernizr.touch ){
            var documentElement = document.documentElement,
                screenWidth = documentElement.clientWidth || documentElement.offsetWidth,
                screenHeight = documentElement.clientHeight || documentElement.offsetHeight;

            if ( !( screenWidth > 768 || screenHeight > 768 ) ){
                viewVariant = 'small';
            }
        }

        startLoading();
    }

    function startLoading() {
        var htmlEl = document.getElementsByTagName('html')[0];

        htmlEl.classList.add( 'viewvariant-' + viewVariant );

        // iOS should be hardware accelerated if possible
        // otherwise low-end iOS devices will only partially
        // render the page
        if ( iOSVersion && iOSVersion >= 1 ){
            htmlEl.classList.add( 'hardware-accelerate' );
        }

        require(
            requireConf,

            // Dependencies
            ["domain-config", "vpro/woord/js/woord", "npo_cookies"],

            // Init callback
            function (domainConfig, woord, npo_cookies) {

                var siteRootRelative = $("meta[name=siteroot]").attr('content'),
                    siteRoot = ''.concat(
                        window.location.protocol,
                        '//',
                        window.location.host,
                        siteRootRelative
                    );

                // MGNL-9856
    // MGNL-9856 - blueconic should honor the cookie permissions
    // TODO remove the try catch after NPO released it's update, currently it throws an error see: MGNL-11259
    try {
        if( typeof npo_cookies !== 'undefined' && npo_cookies.has_permission('recommendations') ) {
            require(['vpro/util/blueconic'], function ( blueconic ) {
                blueconic();
            });
        }
    } catch(e) {
    }

                if(npo_cookies.has_permission("social")) {

                    // UserVoice JavaScript SDK and config
                    (function(){
                        var uv=document.createElement('script');
                        uv.type='text/javascript';
                        uv.async=true;
                        uv.src='//widget.uservoice.com/zzHEauPow8ZvSF45VMQFA.js';
                        var s=document.getElementsByTagName('script')[0];
                        s.parentNode.insertBefore(uv,s)
                    })();
                    window.UserVoice = window.UserVoice || [];
                    UserVoice.push(['showTab', 'classic_widget', {
                        mode: 'feedback',
                        primary_color: '#cc6d00',
                        link_color: '#007dbf',
                        forum_id: 212521,
                        support_tab_name: 'Support',
                        feedback_tab_name: 'Feedback',
                        tab_label: 'Feedback',
                        tab_color: '#00c8ff',
                        tab_position: 'middle-right',
                        tab_inverted: false
                    }]);
                }

                var oldShow_banner = npo_cookies.show_banner;

                if( $('#npo_cc_notification').length > 0){
                    $('html').addClass('npo_cookieBar');
                }

                npo_cookies.show_banner = function(){

                    oldShow_banner();

                    if( $('#npo_cc_notification').length > 0){
                        $('html').addClass('npo_cookieBar');
                    }

                };

                var jsRootUrl = ''.concat(
                    window.vpro.conf.js.remotehost,
                    '/',
                    window.vpro.conf.js.version
                );

                woord.on('error', function(msg, level) {
                    if (level === 0) {
                        $("#wrapper").html( msg );
                    }
                });

                woord.init({
                    // 'autoscrolltop' repositions the document to the top after
                    // every routechange. This is needed on touch devices that
                    // don't support overflowscrolling (Android 2.3),
                    // because otherwise the current scroll position is used.
                    // On devices that do support overflowScrolling this is not
                    // needed because the height of the total app is always
                    // the height of the window
                    autoScrollTop : Modernizr.touch && !Modernizr.overflowscrolling,
                    containers: {
                        app : "#wrapper",
                        home : "#home",
                        search : "#search .content",
                        play :"#play .content",
                        overlay : "#overlay"
                    },
                    debug : window.vpro.conf.js.develop,
                    embedUrl : domainConfig.woordEmbedServer + '/woord/',
                    historySupport : Modernizr.history,
                    homepageUrl : siteRoot + "start.html",
                    homepageTeaserGroup: $('body').data('homepage-teasergroup'),
                    isTouchDevice : $("html").hasClass('touch'),
                    jsRoot : jsRootUrl,
                    shareUrl : siteRoot + "deel.{{type}}.{{id}}.html",
                    favoriteUrl : siteRoot + "favoriet.html",
                    playerPage : siteRoot + "luister.{{type}}.{{id}}.html",
                    playerPageCheck : /\/luister\.(.*)\.(.*)\.html/,
                    apiRoot : domainConfig.apiServer,
                    searchApiRoot : domainConfig.apiServer + '/media/search/es',
                    searchUrl : siteRoot + 'zoek.html',
                    siteRoot : siteRoot,
                    // Needed for hashbang fallback
                    siteRootRelative : siteRootRelative,
                    viewVariant : viewVariant,
                    disqusEnabled : $('meta[name=disqus-shortname]').length > 0 && npo_cookies.has_permission("social"),
                    disqusShortname : $('meta[name=disqus-shortname]').attr('content') || '',
                    disqusUrlPrefix : $('meta[name=disqus-urlprefix]').attr('content') || '',
                    disqusApiKey : $('meta[name=disqus-apikey]').attr('content') || '',
                    slogan : $('meta[name=slogan]').attr('content') || ''
                });

                // In development mode, expose 'woord' to the global scope
                if (window.vpro.conf.js.develop) {
                    window.woord = woord;
                }

            }
        ); // require
    }
})();


text:
import ast
import os
from os.path import expanduser
import re
import shutil
import time

from kubernetes import client, config

from googleapiclient import discovery
from oauth2client.client import GoogleCredentials

from server.common import constants
from server.common import common_functions
from server.common import docker_lib
from server.common import exceptions
from server.common import fm_logger
from server.dbmodule.objects import app as app_db
from server.dbmodule.objects import environment as env_db
from server.dbmodule.objects import resource as res_db
import server.server_plugins.coe_base as coe_base
from server.server_plugins.gcloud import gcloud_helper
from __builtin__ import True

home_dir = expanduser("~")

APP_AND_ENV_STORE_PATH = ("{home_dir}/.cld/data/deployments/").format(home_dir=home_dir)

fmlogger = fm_logger.Logging()

GCR = "us.gcr.io"

GCLOUD_ACTION_TIMEOUT = 60

DEFAULT_MACHINE_TYPE = 'g1-small'

class GKEHandler(coe_base.COEBase):
    """GKE Handler."""

    gcloudhelper = gcloud_helper.GCloudHelper()

    allowed_commands = ["kubectl get*",
                        "kubectl describe*",
                        "kubectl logs*",
                        "kubectl delete*"]

    help_commands = ["kubectl get ",
                     "kubectl describe ",
                     "kubectl logs ",
                     "kubectl delete "]

    def __init__(self):
        credentials = GoogleCredentials.get_application_default()
        self.gke_service = discovery.build('container', 'v1',
                                           credentials=credentials)
        self.compute_service = discovery.build('compute', 'v1',
                                               credentials=credentials,
                                               cache_discovery=False)
        self.docker_handler = docker_lib.DockerLib()

        self.app_yaml_def = ''

    def _verify(self, command):
        matched = None
        for pattern in GKEHandler.allowed_commands:
            p = re.compile(pattern, re.IGNORECASE)
            matched = p.match(command)
            if matched:
                return True
        return False

    def _delete_firewall_rule(self, project, cluster_name):
        try:
            self.compute_service.firewalls().delete(
                project=project,
                firewall=cluster_name
            ).execute()
        except Exception as e:
            fmlogger.error(e)

    def _delete_network(self, project, cluster_name):
        try:
            resp = self.compute_service.networks().delete(
                project=project,
                network=cluster_name
            ).execute()
        except Exception as e:
            fmlogger.error(e)

        network_deleted = False
        count = 0
        while not network_deleted and count < GCLOUD_ACTION_TIMEOUT:
            try:
                network_obj = self.compute_service.networks().get(
                    project=project,
                    network=cluster_name
                ).execute()
            except Exception as e:
                fmlogger.error(e)
                network_deleted = True
            else:
                time.sleep(1)
                count = count + 1

        if count >= GCLOUD_ACTION_TIMEOUT:
            message = ("Failed to delete network {network_name}").format(network_name=cluster_name)
            raise exceptions.EnvironmentDeleteFailure("Failed to delete network ")

    def _create_firewall_rule(self, env_id, project, cluster_name):
        count = 0
        while count < GCLOUD_ACTION_TIMEOUT:
            try:
                resp = self.compute_service.firewalls().insert(
                    project=project,
                    body={"direction": "INGRESS",
                          "allowed": [{"IPProtocol": "tcp",
                                       "ports": ["80","443"]}],
                          "network": "global/networks/" + cluster_name,
                          "name": cluster_name
                          }
                ).execute()
                break
            except Exception as e:
                fmlogger.error(e)
                time.sleep(2)
                count = count + 1

        if count >= GCLOUD_ACTION_TIMEOUT:
            raise exceptions.AppDeploymentFailure()

    def _create_network(self, env_id, project, cluster_name):
        network_name = cluster_name
        try:
            resp = self.compute_service.networks().insert(
                project=project,
                body={"autoCreateSubnetworks": True,
                      "routingConfig":{
                          "routingMode": "GLOBAL"
                      },
                      "name": network_name
                     }
            ).execute()
        except Exception as e:
            fmlogger.error(e)
            env_update = {}
            env_update['output_config'] = str({'error': str(e)})
            env_db.Environment().update(env_id, env_update)
            raise e

        network_obj = ''
        count = 0
        while not network_obj:
            try:
                network_obj = self.compute_service.networks().get(
                    project=project,
                    network=network_name
                ).execute()
            except Exception as e:
                fmlogger.error(e)
                #env_update = {}
                #env_update['output_config'] = str({'error': str(e)})
                #env_db.Environment().update(env_id, env_update)

            if network_obj:
                break
            else:
                time.sleep(2)
                count = count + 1

        if count >= GCLOUD_ACTION_TIMEOUT:
            raise exceptions.AppDeploymentFailure()

        return network_obj

    def _get_cluster_node_ip(self, env_name, project, zone):
        pageToken = None
        list_of_node_objs = []
        list_of_ips = []

        try:
            resp = self.compute_service.instances().list(
                project=project, zone=zone, orderBy="creationTimestamp desc",
                pageToken=pageToken).execute()

            for res in resp['items']:
                if res['name'].lower().find(env_name) >= 0:
                    list_of_node_objs.append(res)

            for res in list_of_node_objs:
                external_ip = res['networkInterfaces'][0]['accessConfigs'][0]['natIP']
                print(res)
                list_of_ips.append(external_ip.strip())
        except Exception as e:
            fmlogger.error(e)
            raise e

        return list_of_ips

    def create_cluster(self, env_id, env_info):
        fmlogger.debug("Creating GKE cluster.")

        cluster_status = 'unavailable'

        env_obj = env_db.Environment().get(env_id)
        env_name = env_obj.name
        env_details = ast.literal_eval(env_obj.env_definition)

        env_output_config = ast.literal_eval(env_obj.output_config)
        env_version_stamp = env_output_config['env_version_stamp']

        cluster_name = env_name + "-" + env_version_stamp

        filtered_description = {}

        res_data = {}
        res_data['env_id'] = env_id
        res_data['cloud_resource_id'] = cluster_name
        res_data['type'] = 'gke-cluster'
        res_data['status'] = 'provisioning'
        res_id = res_db.Resource().insert(res_data)

        cluster_size = 1
        if 'cluster_size' in env_details['environment']['app_deployment']:
            cluster_size = env_details['environment']['app_deployment']['cluster_size']

        project = ""
        if 'project' in env_details['environment']['app_deployment']:
            project = env_details['environment']['app_deployment']['project']
        else:
            fmlogger("Project ID required. Not continuing with the request.")
            status = 'not-continuing-with-provisioning:missing parameter project id'
            res_data['status'] = status
            res_db.Resource().update(res_id, res_data)
            return status

        zone = ""
        if 'zone' in env_details['environment']['app_deployment']:
            zone = env_details['environment']['app_deployment']['zone']
        else:
            fmlogger("Zone required. Not continuing with the request.")
            status = 'not-continuing-with-provisioning:missing parameter zone'
            res_data['status'] = status
            res_db.Resource().update(res_id, res_data)
            return status

        filtered_description['cluster_name'] = cluster_name
        filtered_description['project'] = project
        filtered_description['zone'] = zone
        filtered_description['env_name'] = env_name
        res_data['filtered_description'] = str(filtered_description)
        res_db.Resource().update(res_id, res_data)

        instance_type = DEFAULT_MACHINE_TYPE
        if 'instance_type' in env_details['environment']['app_deployment']:
            instance_type = env_details['environment']['app_deployment']['instance_type']

        try:
            self._create_network(env_id, project, cluster_name)
        except Exception as e:
            fmlogger.error(e)
            return

        try:
            self._create_firewall_rule(env_id, project, cluster_name)
        except Exception as e:
            fmlogger.error(e)
            return

        resp = ''
        try:
            resp = self.gke_service.projects().zones().clusters().create(
                projectId=project,
                zone=zone,
                body={"cluster": {"name": cluster_name,
                                  "initialNodeCount": cluster_size,
                                  "nodeConfig": {
                                      "oauthScopes": "https://www.googleapis.com/auth/devstorage.read_only",
                                      "machineType": instance_type},
                                  "network": cluster_name}}
            ).execute()
            fmlogger.debug(resp)
        except Exception as e:
            fmlogger.error(e)

            env_update = {}
            env_update['output_config'] = str({'error': str(e)})
            env_db.Environment().update(env_id, env_update)
            # Cleanup
            self._delete_firewall_rule(project, cluster_name)
            return

        count = 1
        available = False
        while not available:
            resp = self.gke_service.projects().zones().clusters().get(
                projectId=project,
                zone=zone,
                clusterId=cluster_name).execute()
            status = resp['status']
            res_data['status'] = status
            res_db.Resource().update(res_id, res_data)
            if status.lower() == 'running' or status.lower() == 'available':
                available = True
                break
            else:
                count = count + 1
                time.sleep(3)

        instance_ip_list = ''
        try:
            instance_ip_list = self._get_cluster_node_ip(env_name,
                                                         project,
                                                         zone)
        except Exception as e:
            cluster_status = 'unavailable ' + str(e)
        else:
            cluster_status = 'available'

        if instance_ip_list:
            env_output_config['cluster_ips'] = instance_ip_list
            env_data = {}
            env_data['output_config'] = str(env_output_config)
            env_db.Environment().update(env_id, env_data)
            res_data['status'] = cluster_status
            filtered_description['cluster_ips'] = instance_ip_list
            res_data['filtered_description'] = str(filtered_description)
            res_db.Resource().update(res_id, res_data)
            fmlogger.debug("Done creating GKE cluster.")
        else:
            resource_obj = res_db.Resource().get(res_id)
            cluster_status = 'Could not get IP address of the cluster.. Not continuing.. Deleting cluster.'
            res_data['status'] = cluster_status
            res_db.Resource().update(res_id, res_data)
            self.delete_cluster(env_id, env_info, resource_obj)
            fmlogger.debug("Done deleting GKE cluster.")
        return cluster_status

    def delete_cluster(self, env_id, env_info, resource_obj):
        fmlogger.debug("Deleting GKE cluster")

        res_db.Resource().update(resource_obj.id, {'status': 'deleting'})
        try:
            filtered_description = ast.literal_eval(resource_obj.filtered_description)
            cluster_name = filtered_description['cluster_name']
            project = filtered_description['project']
            zone = filtered_description['zone']

            # Network delete is not working for some reason. So temporarily
            # commenting it out.
            #try:
            #    self._delete_network(project, cluster_name)
            #except Exception as e:
            #    fmlogger.error("Exception deleting network %s " % str(e))
            #    env_update = {}
            #    env_update['output_config'] = str({'error': str(e)})
            #    env_db.Environment().update(env_id, env_update)

            self._delete_firewall_rule(project, cluster_name)

            try:
                resp = self.gke_service.projects().zones().clusters().delete(
                    projectId=project,
                    zone=zone,
                    clusterId=cluster_name
                ).execute()
                fmlogger.debug(resp)
            except Exception as e:
                fmlogger.error("Encountered exception when deleting cluster %s" % e)

            available = True
            while available:
                try:
                    resp = self.gke_service.projects().zones().clusters().get(
                        projectId=project,
                        zone=zone,
                        clusterId=cluster_name).execute()
                except Exception as e:
                    fmlogger.error("Exception encountered in retrieving cluster. Cluster does not exist. %s " % e)
                    available = False
                    break
                time.sleep(3)
        except Exception as e:
            fmlogger.error(e)

        res_db.Resource().delete(resource_obj.id)
        fmlogger.debug("Done deleting GKE cluster.")

    def run_command(self, env_id, env_name, resource_obj, command):
        fmlogger.debug("Running command against GKE cluster")

        if command.lower() == 'help':
            return GKEHandler.help_commands

        command_output = ''

        is_supported_command = self._verify(command)
        if not is_supported_command:
            command_output = ["Command not supported"]
            return command_output

        base_command = ''
        cluster_name = resource_obj.cloud_resource_id

        user_account, project_name, zone_name = GKEHandler.gcloudhelper.get_deployment_details(env_id)

        base_command = ("RUN /google-cloud-sdk/bin/gcloud container clusters get-credentials {cluster_name} --zone {zone} \n").format(
                        cluster_name=cluster_name, zone=zone_name)

        base_image = "gke"
        command_output = GKEHandler.gcloudhelper.run_command(env_id,
                                                             env_name,
                                                             resource_obj,
                                                             base_command,
                                                             command,
                                                             base_image)

        output_lines = command_output.split("\n")

        return output_lines

    # Leaving these methods here as this coe_base.COEBase still contains these methods.
    # Once we remove them from coe_base.COEBase, we should remove these methods
    def deploy_application(self, app_id, app_info):
        pass

    def redeploy_application(self, app_id, app_info):
        pass

    def delete_application(self, app_id, app_info):
        pass

    def get_logs(self, app_id, app_info):
        pass


text:
from waldur_core.core import WaldurExtension

class KeycloakExtension(WaldurExtension):
    @staticmethod
    def django_app():
        return 'waldur_keycloak'

    @staticmethod
    def celery_tasks():
        from datetime import timedelta

        return {
            'waldur-keycloak-sync-groups': {
                'task': 'waldur_keycloak.sync_groups',
                'schedule': timedelta(hours=1),
                'args': (),
            },
        }


text:
//
//  JXWebFileDownloadOperation.h
//  JXWebFile
//
//  Created by 朱佳翔 on 2017/7/10.
//  Copyright © 2017年 zjx. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface JXWebFileDownloadOperation : NSOperation

/**
 * The request used by the operation's task.
 */
@property(strong, nonatomic, readonly, nullable) NSURLRequest *request;

/**
 * The operation's task
 */
@property(strong, nonatomic, readonly, nullable) NSURLSessionDownloadTask *downloadTask;

@property (assign, nonatomic) NSInteger bytesWritten;

@property (assign, nonatomic) NSInteger totalBytes;
/**
 *  Initializes a `SJWebFileDownloaderOperation` object
 *
 *  @see SJWebFileDownloaderOperation
 *
 *  @param request        the URL request
 *  @param session        the URL session in which this operation will run
 *
 *  @return the initialized instance
 */

- (nonnull instancetype)initWithRequest:(nullable NSURLRequest *)request
                                session:(nullable NSURLSession *)session;

- (nonnull instancetype)initWithResumeData:(nullable NSData *)resumeData session:(nullable NSURLSession *)session;

@end


text:
using System;
using System.Collections.Generic;

namespace Spine {
	/// Stores attachments by slot index and attachment name.
	public class Skin {
		internal String name;
		private Dictionary<KeyValuePair<int, String>, Attachment> attachments =
			new Dictionary<KeyValuePair<int, String>, Attachment>(AttachmentComparer.Instance);

		public String Name { get { return name; } }

		public Skin (String name) {
			if (name == null) throw new ArgumentNullException("name cannot be null.");
			this.name = name;
		}

		public void AddAttachment (int slotIndex, String name, Attachment attachment) {
			if (attachment == null) throw new ArgumentNullException("attachment cannot be null.");
			attachments[new KeyValuePair<int, String>(slotIndex, name)] = attachment;
		}

		/// <returns>May be null.</returns>
		public Attachment GetAttachment (int slotIndex, String name) {
			Attachment attachment;
			attachments.TryGetValue(new KeyValuePair<int, String>(slotIndex, name), out attachment);
			return attachment;
		}

		public void FindNamesForSlot (int slotIndex, List<String> names) {
			if (names == null) throw new ArgumentNullException("names cannot be null.");
			foreach (KeyValuePair<int, String> key in attachments.Keys)
				if (key.Key == slotIndex) names.Add(key.Value);
		}

		public void FindAttachmentsForSlot (int slotIndex, List<Attachment> attachments) {
			if (attachments == null) throw new ArgumentNullException("attachments cannot be null.");
			foreach (KeyValuePair<KeyValuePair<int, String>, Attachment> entry in this.attachments)
				if (entry.Key.Key == slotIndex) attachments.Add(entry.Value);
		}

		override public String ToString () {
			return name;
		}

		/// Attach all attachments from this skin if the corresponding attachment from the old skin is currently attached.
		internal void AttachAll (Skeleton skeleton, Skin oldSkin) {
			foreach (KeyValuePair<KeyValuePair<int, String>, Attachment> entry in oldSkin.attachments) {
				int slotIndex = entry.Key.Key;
				Slot slot = skeleton.slots[slotIndex];
				if (slot.attachment == entry.Value) {
					Attachment attachment = GetAttachment(slotIndex, entry.Key.Value);
					if (attachment != null) slot.Attachment = attachment;
				}
			}
		}

		// Avoids boxing in the dictionary.
		private class AttachmentComparer : IEqualityComparer<KeyValuePair<int, String>> {
			internal static readonly AttachmentComparer Instance = new AttachmentComparer();

			bool IEqualityComparer<KeyValuePair<int, string>>.Equals (KeyValuePair<int, string> o1, KeyValuePair<int, string> o2) {
				return o1.Key == o2.Key && o1.Value == o2.Value;
			}

			int IEqualityComparer<KeyValuePair<int, string>>.GetHashCode (KeyValuePair<int, string> o) {
				return o.Key;
			}
		}
	}
}


text:
FROM pytorch/pytorch:1.2-cuda10.0-cudnn7-runtime
WORKDIR /root

# Installs pandas, and google-cloud-storage.
RUN pip install pandas google-cloud-storage

# The data for this sample has been publicly hosted on a GCS bucket.
# Download the data from the public Google Cloud Storage bucket for this sample
RUN curl https://storage.googleapis.com/cloud-samples-data/ml-engine/sonar/sonar.all-data --output ./sonar.all-data

# Copies the trainer code to the docker image.
COPY model.py ./model.py
COPY data_utils.py ./data_utils.py
COPY task.py ./task.py

# Set up the entry point to invoke the trainer.
ENTRYPOINT ["python", "task.py"]


text:
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace Abp.AspNetCore.Mvc.Results.Wrapping
{
    public class NullAbpActionResultWrapper : IAbpActionResultWrapper
    {
        public void Wrap(ResultExecutingContext actionResult)
        {

        }
    }
}


text:
package com.fasteque.leanback.sample;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;

import com.fasteque.leanback.widget.app.LoadingFragment;

/*
 * LoadingActivity shows how to use LoadingFragment.
 */
public class LoadingActivity extends Activity {

	/**
	 * Called when the activity is first created.
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		LoadingFragment loadingFragment = LoadingFragment.newInstance(Color.BLUE, Color.WHITE, 256, 256);
		getFragmentManager().beginTransaction().add(R.id.main_browse_fragment, loadingFragment).commit();
	}
}


text:
package com.jakubsprega.untestable.code.h;

/**
 * Silencer
 *
 * @author jakubsprega
 */
public class Silencer {

}