text:
package com.sf.codingcomp.regex;

import static org.junit.Assert.*;

import org.junit.Test;
//
//Do not change anything in the following JAVA class!
//
public class RegexTest {
	@Test
	public void isFullPhoneNumber() {
		assertTrue(Regex.isFullPhoneNumber("191-428-2958"));
		assertTrue(Regex.isFullPhoneNumber("1938257165"));
		assertTrue(Regex.isFullPhoneNumber("3095728492"));
		assertTrue(Regex.isFullPhoneNumber("184 328 1922"));

		assertFalse(Regex.isFullPhoneNumber("12-01-2002"));
		assertFalse(Regex.isFullPhoneNumber("12345678"));
		assertFalse(Regex.isFullPhoneNumber("123456789101010123123123"));
		assertFalse(Regex.isFullPhoneNumber("XX Hwy 280, Birmingham, AL 35147"));
	}

	@Test
	public void isAmericanAddressTest() {
		assertTrue(Regex.isAmericanAddress("12 Hwy 280, Birmingham, AL 35147"));
		assertTrue(Regex.isAmericanAddress("3 State Farm Pl S, Bloomington, IL 61701"));
		assertTrue(Regex.isAmericanAddress("PO Box 1, Bloomington, IL 61701"));
		assertTrue(Regex.isAmericanAddress("3 State Farm Pl S Bloomington IL 61701-0000"));
		assertTrue(Regex.isAmericanAddress("3 State Farm Pl S Bloomington IL 617010000"));

		assertFalse(Regex.isAmericanAddress("Bloomington IL 61701"));
		assertFalse(Regex.isAmericanAddress("3 State Farm PL S 61701"));
		assertFalse(Regex.isAmericanAddress("61701"));
		assertFalse(Regex.isAmericanAddress("State Farm Pl S, Bloomington, IL 61701"));
	}

	@Test
	public void isIPv4AddressTest() {
		assertTrue(Regex.isIPv4Address("1.1.1.1"));
		assertTrue(Regex.isIPv4Address("192.168.1.1"));
		assertTrue(Regex.isIPv4Address("255.255.255.1"));

		assertFalse(Regex.isIPv4Address("255.255.255.256"));
		assertFalse(Regex.isIPv4Address("123"));
		assertFalse(Regex.isIPv4Address("1.2.3."));
		assertFalse(Regex.isIPv4Address("-1.2.4.5"));
		assertFalse(Regex.isIPv4Address("a.1.4.2"));
		assertFalse(Regex.isIPv4Address("1a.2.4.5"));
	}
}

redpajama_set_name: RedPajamaGithub


text:
class ClientsController < ApplicationController
  before_filter :require_authentication

  def new
    @client = current_account.clients.new
  end

  def create
    @client = current_account.clients.new params[:client]
    if @client.save
      redirect_to dashboard_url, flash: {
        notice: "Registered #{@client.name}"
      }
    else
      flash[:error] = @client.errors.full_messages.to_sentence
      render :new
    end
  end

  def edit
    @client = current_account.clients.find(params[:id])
  end

  def update
    @client = current_account.clients.find(params[:id])
    if @client.update_attributes(params[:client])
      redirect_to dashboard_url, flash: {
        notice: "Updated #{@client.name}"
      }
    else
      flash[:error] = @client.errors.full_messages.to_sentence
      render :edit
    end
  end

  def destroy
    current_account.clients.find(params[:id]).destroy
    redirect_to dashboard_url
  end
end


text:
![Bootstrap logo](/bootstrap-logo.png) ![Font Awesome logo](/font-awesome-logo.png)
## Bootstrap Learning
#### Date(s)
01/25/17 - 02/04/17
### Description
Initial attempt at learning [Bootstrap](http://getbootstrap.com/) with [Font Awesome](http://fontawesome.io/) added for fun.
### Technologies
- Bootstrap
- Font Awesome
- JavaScript
- HTML5
- CSS3


text:
package co.uk.fernandopinto.aco.algo;

/**
 * Created by Fernando on 20/09/2017.
 */
public interface Individual {

    void initAnts();
    float chooseNextLocation(byte iteration);
}


text:
import sys
from PySide.QtGui import QApplication
from biopredyn.ui.mainwindow import MainWindow

app = QApplication(sys.argv)
frame = MainWindow()
frame.show()
sys.exit(app.exec_())


text:
import os

from .. import bot
from .. import db

from .test_bot import EXAMPLE_TWEET

TESTDB = 'test_goldstar.db'

class TestDB():

    def setup(self):
        os.remove(TESTDB)
        self.db = db.GoldStarDB(TESTDB)

    def teardown(self):
        os.remove(TESTDB)

    def test_db_save(self):
        # Save a tweet to the test db and check if it got inserted
        handler = bot.TweetHandler(EXAMPLE_TWEET, dbfile=TESTDB, dry_run=True)
        handler.handle()
        for recipient in handler.get_recipients():
            assert self.db.count_stars(recipient['id']) == 1
        assert self.db.count_stars(123) == 0  # Random user_id


text:
require 'rails/generators'
require 'rails/generators/named_base'

module SeedMigration
  module Generators
    class SeedMigrationGenerator < Rails::Generators::NamedBase
      namespace 'seed_migration'
      desc 'Creates a seed migration'
      class_option :migration_name, :type => :string, :default => nil
      argument :timestamp, :type => :string, :required => false, :default => Time.now.utc.strftime("%Y%m%d%H%M%S")

      def create_seed_migration_file
        path = SeedMigration::Migrator.data_migration_directory
        create_file path.join("#{timestamp}_#{file_name.gsub(/([A-Z])/, '_\1').downcase}.rb"), contents
      end

      private

      def contents
        <<STRING
class #{file_name.camelize} < SeedMigration::Migration
  def up

  end

  def down

  end
end
STRING
      end
    end
  end
end


text:
#include <aws/proton/model/ListServicePipelineOutputsResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>

#include <utility>

using namespace Aws::Proton::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;

ListServicePipelineOutputsResult::ListServicePipelineOutputsResult()
{
}

ListServicePipelineOutputsResult::ListServicePipelineOutputsResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  *this = result;
}

ListServicePipelineOutputsResult& ListServicePipelineOutputsResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  JsonView jsonValue = result.GetPayload().View();
  if(jsonValue.ValueExists("nextToken"))
  {
    m_nextToken = jsonValue.GetString("nextToken");

  }

  if(jsonValue.ValueExists("outputs"))
  {
    Aws::Utils::Array<JsonView> outputsJsonList = jsonValue.GetArray("outputs");
    for(unsigned outputsIndex = 0; outputsIndex < outputsJsonList.GetLength(); ++outputsIndex)
    {
      m_outputs.push_back(outputsJsonList[outputsIndex].AsObject());
    }
  }

  return *this;
}


text:
require 'rails_helper'

describe TwitterStatus do
  let(:post) do
    FactoryBot.build(:post,
                      title: 'Hacking on Elixir',
                      url_slug: 'hacking-on-elixir')
  end

  let(:old_post) do
    FactoryBot.build(:post,
                      title: 'My First Ruby Post',
                      url_slug: 'my-first-ruby-post',
                      created_at: 5.years.ago)
  end

  describe '#status' do
    it 'returns a Twitter status' do
      twitter_status = described_class.new(post)

      expected = "New blog post: 'Hacking on Elixir' http://www.jakeworth.com/hacking-on-elixir"
      actual = twitter_status.send(:status)

      expect(actual).to eq expected
    end
  end

  describe '#archive_status' do
    it 'returns a Twitter status with appropriate hashtag' do
      twitter_status = described_class.new(old_post)

      expected = "'My First Ruby Post' http://www.jakeworth.com/my-first-ruby-post #5yrsago"
      actual = twitter_status.send(:archive_status)

      expect(actual).to eq expected
    end
  end
end


text:
/* ----------------------------------------------------------------------------
 * This file was automatically generated by SWIG (http://www.swig.org).
 * Version 3.0.12
 *
 * Do not make changes to this file unless you know what you are doing--modify
 * the SWIG interface file instead.
 * ----------------------------------------------------------------------------- */

package com.frostwire.jlibtorrent.swig;

public class alerts_dropped_alert extends alert {
  private transient long swigCPtr;

  protected alerts_dropped_alert(long cPtr, boolean cMemoryOwn) {
    super(libtorrent_jni.alerts_dropped_alert_SWIGUpcast(cPtr), cMemoryOwn);
    swigCPtr = cPtr;
  }

  protected static long getCPtr(alerts_dropped_alert obj) {
    return (obj == null) ? 0 : obj.swigCPtr;
  }

  protected void finalize() {
    delete();
  }

  public synchronized void delete() {
    if (swigCPtr != 0) {
      if (swigCMemOwn) {
        swigCMemOwn = false;
        libtorrent_jni.delete_alerts_dropped_alert(swigCPtr);
      }
      swigCPtr = 0;
    }
    super.delete();
  }

  public int type() {
    return libtorrent_jni.alerts_dropped_alert_type(swigCPtr, this);
  }

  public alert_category_t category() {
    return new alert_category_t(libtorrent_jni.alerts_dropped_alert_category(swigCPtr, this), true);
  }

  public String what() {
    return libtorrent_jni.alerts_dropped_alert_what(swigCPtr, this);
  }

  public String message() {
    return libtorrent_jni.alerts_dropped_alert_message(swigCPtr, this);
  }

  public void setDropped_alerts(SWIGTYPE_p_std__bitsetT_97_t value) {
    libtorrent_jni.alerts_dropped_alert_dropped_alerts_set(swigCPtr, this, SWIGTYPE_p_std__bitsetT_97_t.getCPtr(value));
  }

  public SWIGTYPE_p_std__bitsetT_97_t getDropped_alerts() {
    long cPtr = libtorrent_jni.alerts_dropped_alert_dropped_alerts_get(swigCPtr, this);
    return (cPtr == 0) ? null : new SWIGTYPE_p_std__bitsetT_97_t(cPtr, false);
  }

  public final static int priority = libtorrent_jni.alerts_dropped_alert_priority_get();
  public final static int alert_type = libtorrent_jni.alerts_dropped_alert_alert_type_get();
  public final static alert_category_t static_category = new alert_category_t(libtorrent_jni.alerts_dropped_alert_static_category_get(), false);
}


text:
<?php

namespace Application\Components\HTMLGenerator;

/**
 * Author: Wahab Qureshi.
 */
use Application\Components\TemplateHandler\TemplateHandler;

class HTMLGenerator extends TemplateHandler{

    private $formname; //used for saving and retrieving form from database
    private $form, $errors = array(), $errorColor, $elements = array(), $element = array();
    private $name, $method, $action;
    private $host, $database, $username, $password, $link;

    function __construct($params = null) {

        $this->router = $this->getComponent('Router');
    }

    public function Form($name, array $params = array())
    {
        $this->formname = $this->name = $name;
        $this->method = $params['method'];
        $this->action = $params['action'];
        $this->form = "<form method='$#method' " . (@$params['enctype'] == true ? "enctype='multipart/form-data'" : null) . " name='$#name' action='$#action' id = '" . @$params['id'] . "' class='" . @$params['class'] . "' style='" . (@$params['align'] == 'center' ? 'margin:0px auto;' : (@$params['align'] == 'right' ? 'float: right;' : (@$params[''] == 'left' ? 'float:left;' : null))) . " " . (isset($params['width']) ? 'width: ' . $params['width'] . ';' : null) . " " . @$params['style'] . "'>";
        $this->color = 'red';
    }

    public function __get($property) {
        if (property_exists($this, $property)) {
            return $this->$property;
        }
    }

    public function __set($property, $value) {
        if (property_exists($this, $property)) {
            $this->$property = $value;
        }
        return $this;
    }

    /**
     *
     * @param type $element
     * @return type
     */
    public function generateInput($element) {

        $element = $this->add($element);

        return $element;
    }

    /**
     *
     * @param type $elements
     */
    public function generateInputs($elements)
    {
        $html = null;

        foreach($elements as $element)
            $html .= $this->add($element);

        return $html;
    }

    public function generateForm($input) {

        $formHeader = function() use ($input) {

                    $form = '

' . @($input['title'] ? $input['title'] : 'Default title' ) . '

            <form method="' . @(($input['method']) ? $input['method'] : 'POST' ) . '" message="' . @$input['message'] . '" action="' . @$input['action'] . '" enctype="' . @$input['enctype'] . '" class="' . @(($input['class']) ? $input['class'] : 'form' ) . '" id="' . @$input['id'] . '">
            <fieldset>';

                    return $form;
                };

        $formBody = function($form = null) use ($input) {

                    if (isset($input['table']))
                        $form .= $this->DBForm($input['table']);

                    foreach ($input['inputs'] as $key => $element) {

                        if ($key != 'hidden')
                            $form .= '
';

                        $element['type'] = $key;

                        if ($key != 'hidden')
                            $form .= '' . @$element['label'] . '

';

                        $form .= $this->generateInput($element);

                        if ($key != 'hidden')
                            $form .= '

';
                    }

                    $form .= '</fieldset>';

                    return $form;
                };

        $formFooter = function() use ($input) {

                    $form = '

';

                    foreach ($input['submission'] as $key => $submit) {

                        $submit['type'] = $key;

                        $form .= $this->generateInput($submit);
                    }

                    $form .= '

</form>
';

                    return $form;
                };

        return $formHeader() . $formBody() . $formFooter();
    }

    function startSection($params = array()) {
        $this->form .= '
';
    }

    function endSection() {
        $this->form .= '
';
    }

    function flush() {
        $this->form = null;
    }

    function save() {//use to save form in its current state and continue building it on another page
        //save the added fields
    }

    function erase() {//delete the form history saved by the save method
        //delete * from database
    }

    function recall() {//recall the saved data from the database
        //get data from the database
    }

    function add($params) {//this function should store data in an array so that they can be re-arranged or modified individually.
        $i = 0;

        $element =
        $value =
        $class =
        $id =
        $name =
        $type =
        $disabled =
        $buttonValue =
        $buttonStyle =
        $buttonId =
        $buttonClass =
        $style =
        $rows =
        $cols =
        $multiple =
        $requiredText =
        $append =
        $prepend =
        $align =
        $src =
        $title =
        $alt =
        $href =
        $target =
        $size =
        $valid =
        $icon =
        $iconText =
        null;

        if(isset($params['value']))
            $value = "value='{$params['value']}'";

        if(isset($params['class']))
            $class = "class='{$params['class']} {$params['validation']}'";

        if(isset($params['id']))
            $id = "id='{$params['id']}'";

        if(isset($params['name']))
            $name = "name='{$params['name']}'";

        if(isset($params['type']))
            $type = "type='{$params['type']}'";

        if(isset($params['disabled']))
            $disabled = "disabled='{$params['disabled']}'";

        if(isset($params['buttonValue']))
            $buttonValue = "value='{$params['buttonValue']}'";

        if(isset($params['buttonStyle']))
            $buttonStyle = "style='{$params['buttonStyle']}'";

        if(isset($params['buttonId']))
            $buttonId = "id='='{$params['buttonId']}''";

        if(isset($params['buttonClass']))
            $buttonClass = "class='{$params['buttonClass']}'";

        if(isset($params['style']))
            $style = "style='{$params['style']}'";

        if(isset($params['rows']))
            $rows = "rows='{$params['rows']}'";

        if(isset($params['cols']))
            $cols = "cols='{$params['cols']}'";

        if(isset($params['requiredText']))
            $requiredText = "<option value=''>{$params['requiredtext']}</option>";

        if(isset($params['multiple']))
            $multiple = "multiple='{$params['multiple']}'";

        if(isset($params['append']))
            $append = $params['append'];

        if(isset($params['prepend']))
            $prepend = $params['prepend'];

        if(isset($params['align']))
            $align = "align='{$params['align']}";

        if(isset($params['src']))
            $src = "src='{$params['src']}'";

        if(isset($params['title']))
            $title = "title='{$params['title']}'";

        if(isset($params['alt']))
            $alt = "alt='{$params['alt']}'";

        if(isset($params['href']))
            $href = "href='{$params['href']}'";

        if(isset($params['target']))
            $target = "target='{$params['target']}'";

        if(isset($params['size']))
            $size = "size='{$params['size']}'";

        if(isset($params['valid']))
            $valid = $params['valid'];

        if(isset($params['icon']))
            $icon = $params['icon'];

        if(isset($params['icontext']))
            $iconText = "title='{$params['icontext']}";

        if(isset($params['for']))
            $for = "for='{$params['for']}";

        $option = function($label, $value = null, $selected = null, $params = null) use ($append, $prepend)
        {
            return "<option value='$value' ".($selected == $value ? "selected='selected'" : '')." $params >{$append}{$label}{$prepend}</option>";
        };

        switch (strtolower($params['type'])) {

            case 'text':
            case 'password':
            case 'submit':
            case 'reset':
            case 'file':
            case 'button':
                {
                    return "<input $type $class $disabled $value $name $id >";
                }

            case 'label':
            {
                return "{$params['label']}";
            }

            case 'textarea':
                {
                    $element .= "<textarea $cols $rows $class $id $name $disabled $style>{$params['value']}</textarea>";
                    break;
                }

            case 'imageUpload': {
                    $element .= "<input type='text' class='fittosize {$params['class']} {$params['validation']}' $disabled $value $name $id>
                                <input type='button' $buttonValue $buttonStyle $buttonId $buttonClass>";
                    break;
                }

            case 'select': {

                    $elements = explode(',', @$params['value']);
                    $element .= "<select $class $name $id $multiple $disabled>";

                    if (isset($params['requiredtext']))
                    {
                        $element .= $requiredText;
                    }
                    if (is_numeric($elements[0]))
                    {
                        if ($elements[0] < $elements[1])
                        {
                            for ($j = $elements[0]; $j <= $elements[1]; $j += $elements[2])
                            {
                                $element .= $option($j,$j, @$params['selected'], $disabled.$selected, $append, $prepend);
                            }
                        }
                        else
                        {
                            for ($j = $elements[1]; $j >= $elements[0]; $j -= $elements[2])
                            {
                                $element .= $option($j,$j, @$params['selected'], $disabled.$selected, $append, $prepend);
                            }
                        }
                    }
                    else
                    {
                        foreach ($elements as $elementname)
                        {
                            $element .= $option($elementname, str_replace(' ', '_', $elementname), @$params['selected'], $disabled.$selected, $append, $prepend);
                        }
                    }
                    $element .= '</select>';
                    break;
                }

            case 'image': {
                    $element .= "";
                    break;
                }

            case 'linkedImage': {
                    $element .= "";
                    break;
                }

            case 'href':
            case 'link': {
                    $element .= "$label";
                    break;
                }

            case 'radio': {
                    $elements = explode(',', @$params['value']);
                    if (is_numeric($elements[0]))
                    {
                        if ($elements[0] < $elements[1])
                        {
                            for ($j = $elements[0]; $j <= $elements[1]; $j += $elements[2])
                            {
                                $element .= "<input id='{$params['id']}_$i' $class";
                                if (isset($params['selected']) && @$params['selected'] == $j)
                                    $element .= ' checked="checked" ';
                                $element .= "$disabled $type  name='{$params['name']}[]' value='$j'>";
                                $i++;
                            }
                        }
                        else
                        {
                            for ($j = $elements[1]; $j >= $elements[0]; $j -= $elements[2])
                            {
                                $element .= "<input id='{$params['id']}_$i' $class";
                                if (isset($params['selected']) && @$params['selected'] == $j)
                                    $element .= ' checked="checked" ';
                                $element .= "$disabled $type  name='{$params['name']}[]' value='$j'>";
                                $i++;
                            }
                        }
                    }
                    else
                    {
                        foreach ($elements as $elementname)
                        {
                            $element .= "<input id='{$params['id']}_$i' $class";
                            if (isset($params['selected']) && @$params['selected'] == $elementname)
                                $element .= ' checked="checked" ';
                            $element .= "$disabled $type  name='{$params['name']}[]' value='".str_replace(' ', '_', $elementname)."'>";
                            $i++;
                        }
                    }

                    break;
                }

            case 'checkbox': {
                    $elements = explode(',', @$params['value']);
                    if (is_numeric($elements[0])) {
                        if ($elements[0] < $elements[1]) {
                            for ($j = $elements[0]; $j <= $elements[1]; $j += $elements[2]) {
                                $element .= "<input id='{$params['id']}_$i' $type $class";
                                if (isset($params['selected']) && @$params['selected'] == $j)
                                    $element .= ' checked="checked" ';
                                $element .= "$disabled name='{$params['name']}[]' value='$j'>";
                                $i++;
                            }
                        }
                        else {
                            for ($j = $elements[1]; $j >= $elements[0]; $j -= $elements[2]) {
                                $element .= "<input id='{$params['id']}_$i' $type $class";
                                if (isset($params['selected']) && @$params['selected'] == $j)
                                    $element .= ' checked="checked" ';
                                $element .= "$disabled name='{$params['name']}[]' value='$j'>";
                                $i++;
                            }
                        }
                    }
                    else {
                        foreach ($elements as $elementname) {
                            $element .= "<input id='{$params['id']}_$i' $type $class";
                            if (isset($params['selected']) && @$params['selected'] == $elementname)
                                $element .= ' checked="checked" ';
                            $element .= "$disabled name='{$params['name']}[]' value='$elementname'>";
                            $i++;
                        }
                    }
                    break;
                }

            case 'slider': {
                    $elements = explode(',', @$params['value']);
                    $element .= "

                        <input type='text' $size $disabled class='{$params['class']} digit bb_valuedinput' value='0' $name $id>

                        ";
                    break;
                }

            case 'datepicker': {
                    $element .= "

                            <input type='text' class='datepicker {$params['class']} date' value='' $disabled $name $id>
";
                    break;
                }

            case 'selectdate': {
                    $selected = explode(',', @$params['selected']);
                    $element .= '

                            ' . @$params['htmlprepend'] . '

                            <select name="selectday' . $params['name'] . '" id="selectday' . $params['name'] . '" class="dobday dateselect' . @$params['valid'] . ' ' . @$params['class'] . '">
                            <option value="">Day</option>
                            ';
                    for ($j = 1; $j < 32; $j++) {
                        $element .= '<option value="' . $j . '" ';
                        if (isset($params['selected']) && $selected[0] == $j)
                            $element .= ' selected="selected" ';
                        $element .= '>' . @$params['prepend'] . $j . @$params['append'] . '</option>';
                    }
                    $element .= '</select>
                            <select name="selectmonth' . $params['name'] . '" id="selectmonth' . $params['name'] . '" class="dobmonth dateselect' . @$params['valid'] . ' ' . @$params['class'] . '">
                            <option value="">Month</option>
                            ';
                    for ($j = 1; $j < 13; $j++) {
                        $element .= '<option value="' . $j . '" ';
                        if (isset($params['selected']) && $selected[1] == $j)
                            $element .= ' selected="selected" ';
                        $element .= '>' . @$params['prepend'] . $j . @$params['append'] . '</option>';
                    }
                    $element .= '</select>
                            <select name="selectyear' . $params['name'] . '" id="selectyear' . $params['name'] . '" class="dobyear dateselect' . @$params['valid'] . ' ' . @$params['class'] . '">
                            <option value="">Year</option>
                            ';
                    for ($j = 2012; $j > 1950; $j--) {
                        $element .= '<option value="' . $j . '" ';
                        if (isset($params['selected']) && $selected[2] == $j)
                            $element .= ' selected="selected" ';
                        $element .= '>' . @$params['prepend'] . $j . @$params['append'] . '</option>';
                    }
                    $element .= '</select>
                            ' . $params['title'] . '' . @$params['required'] . '

                            ' . @$params['htmlappend'] . '

                            ';
                    break;
                }

            case 'postcode': {
                    $element .= "
                        $prepend

                                    <input style='display: none;' type='text' class='postcodeinput {$params['class']}' $value
                                            $name id='postcode'> $label$requiredText

                        $append";
                    break;
                }

            case 'iframe': {
                    $element .= "";
                }

            default: {
                    $this->form .= @$params['content'];
                }
        }

        return $element;
    }

    function submit() {

    }

    function validate() {

    }

    public function dump($var = null) {
        $dump = $this->filterForRender($var);
        $dump = str_replace('<', '<', $dump);
        $dump = str_replace('>', '>', $dump);
        $dump = str_replace('<!--', '

<!--', $dump);
        echo $dump;
        echo '</form>

';
    }

    function setError($error) {
        $err = array();
        if (!is_array($error))
            $err[] = $error;
        else
            $err = $error;
        foreach ($err as $err => $errr)
            $this->errors[$err] = $errr;
    }

    function showError() {
        pre($this->errors);
    }

    private function filterForRender($var = null) {

        $var = ($var == null) ? $this->form : $var;

        return $this->Variable($var)->Replace(array(
                    '$#name' => $this->name,
                    '$#method' => $this->method,
                    '$#action' => $this->action
                ))->GetVariableResult();
    }

    function setErrorColor($color) {

        $this->errorColor = $color;
    }

    private function rand_string($length) {

        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = null;
        $size = strlen($chars);

        for ($i = 0; $i < $length; $i++) {
            $str .= $chars[rand(0, $size - 1)];
        }

        return $str;
    }

    function startFooter($align) {
        $this->form .= '
';
    }

    function endFooter() {
        $this->form .= '
';
    }

    function addVariable($name) {
        $this->form .= '<#' . $name . '>';
    }

    function useVariable($varName, $var) {
        $this->form = str_replace('<#' . $varName . '>', $var, $this->form);
    }

    /**
     *
     * @param type $items
     * @param type $contentDescriptiveOutput - will show the Div sections below the table with more information.
     * @return string - formated table of index
     * Renders a fully functional index table.
     */
    public function RenderIndexTable($items, $contentDescriptiveOutput = true) {

        $content = null;

        ob_start();

        echo '
';

        foreach ($items as $key => $value) {

            if (is_array($value)) {

                $content .= '
' . $key . '
';

                $content .= $this->outputIndexItems($key, $value);
            } else {

                if (is_numeric($key))
                    echo '
' . $value . '
';
                else {
                    echo '
' . $key . '
';

                    $content .= '

' . $key . '

' . $this->formatCode($value) . '

                    ';
                }
            }
        }

        echo '

';

        if ($contentDescriptiveOutput)
            echo $content;

        return ob_get_clean();
    }

    /**
     *
     * @param type $keys
     * @param type $items
     * @return string - creates headings within the menu for the RenderTableIndex method
     */
    private function outputIndexItems($keys, $items) {

        $content = null;

        echo '
' . $keys . '
';

        foreach ($items as $key => $item) {

            if (is_array($item)) {

                $content .= '
' . $key . '
';

                $this->outputIndexItems($key, $item);
            } else {
                if (is_numeric($key))
                    echo '
' . $item . '
';
                else {
                    echo '
' . $key . '
';

                    $content .= '

' . $key . '

' . $this->formatCode($item) . '

                    ';
                }
            }
        }

        echo '

';

        return $content . '
';
    }

    /**
     *
     * @param type $index
     * @return string - format code for displaying on html page.
     */
    public function formatCodeToHTML($index) {

        return $this->Variable($index)->Replace(array(
                    '<php' => '<php',
                    '<' => '<',
                    '<br />' => '
',
                    '<p>' => '
',
                    '</p>' => '
',
                    '</ol>' => '
',
                    '</li>' => '
',
                    '<li>' => '
',
                    '<ol>' => '
',
                    '<div' => '
 '
GetVariableResult();

//        $index = str_replace('<php', '<php', $index);
//        $index = str_replace('<', '<', $index);
//        $index = str_replace('<br />', '
', $index);
//        $index = str_replace('<p>', '
', $index);
//        $index = str_replace('</p>', '
', $index);
//        $index = str_replace('</ol>', '
', $index);
//        $index = str_replace('</li>', '
', $index);
//        $index = str_replace('<li', '<li', $index);
//        $index = str_replace('<ol', '<ol', $index);
//        $index = str_replace('<div', 'formatCodeColors($code);

        return $code;
    }

    /**
     *
     * @param type $code
     * @return string - format html code colors.
     */
    public function formatCodeColors($code) {

        $replace = array(
            '<php' => '<php',
            'if(' => ' if ( ',
            '->' => ' -> ',
            '(' => ' ( ',
            ')' => ' )',
            ' new ' => ' new ',
            ';' => ' ;',
            '$this' => ' $this',
            '$' => ' $',
            '::' => ' :: ',
            'Configs/' => 'Configs/'
        );

        $code = $this->replaceMultiple($code, $replace);

        return $code;
    }

    /**
     *
     * @param type $haystack
     * @param type $needlesArray
     * @return string - Run a multiple search and replace function.
     */
    public function replaceMultiple($haystack, $needlesArray) {

        foreach ($needlesArray as $key => $value) {

            $haystack = str_replace($key, $value, $haystack);
        }

        return $haystack;
    }

    public function ToUpperCase($string) {

        $string = strtoupper($string);

        return $string;
    }

    public function ToLowerCase($string) {

        $string = strtolower($string);

        return $string;
    }

    public function FirstCharacterToUpperCase($string) {

        $string = strtoupper(substr($string, 0, 1)) . substr($string, 1);

        return $string;
    }

    public function FirstCharacterToLowerCase($string) {

        $string = strtolower(substr($string, 0, 1)) . substr($string, 1);

        return $string;
    }

    public function SpaceToBreak($string) {

        $string = str_replace(' ', '
', $string);

        return $string;
    }

    public function RenderRows($array) {

        $index = 1;

        $rows = null;

        $objectCopy = null;

        if (count($array['tbody']) != 0)
        {
            $rows = '
';

            foreach ($array['tbody'] as $arr)
            {
                if(is_object($arr))
                {
                    $objectCopy = clone $arr;
                }
                else
                {
                    $objectCopy = $arr;
                }

                if ($index % 2 == 0)
                {
                    $rows .= '
';
                }
                else
                {
                    $rows .= '
';
                }

                if (is_array($arr) || is_object($arr))
                {

                    // Rendering functions

                    $body = function($rows = null) use ($arr, $array){

                        if (is_array($array['ignoreFields']) && count($array['ignoreFields']) != 0)
                        {
                            foreach ($array['ignoreFields'] as $ignore)
                            {
                                if(is_object($arr))
                                {
                                    unset($arr -> $ignore);
                                }
                                else
                                {
                                    unset($arr[$ignore]);
                                }
                            }
                        }

                        foreach ($arr as $item)
                        {
                            $rows .= '' . $item . '	';
                        }

                        return $rows;
                    };

                    $actions = function($rows = null) use ($objectCopy, $array, $index) {

                        if (isset($array['actions']))
                        {
                            $rows .= '

';

                            foreach ($array['actions'] as $key => $action)
                            {
                                if (isset($action['message']))
                                {
                                    $rows .= '<input type="hidden" value="' . @(isset($action['route']) ? $this->setRoute($action['route'], array($action['routeParam'] => (is_object($objectCopy) ? $objectCopy->$action['dataParam'] : $objectCopy[$action['dataParam']] ))) : $action['url'] ) . '">';

                                    $rows .= ' ' . $key . ' ';

                                    $rows .= '<input type="hidden" value="' . $action['message'] . '">';
                                }
                                else
                                {
                                    $rows .= ' setRoute($action['route'], array($action['routeParam'] => (is_object($objectCopy) ? $objectCopy->$action['dataParam'] : $objectCopy[$action['dataParam']] ))) : @$action['url'] ) . '">' . $key . ' ';
                                }

                                $rows .= '
';
                            }
                        }

                        $rows .= '
	';

                        return $rows;
                    };

                    // End of Rendering functions

                    // Execution of functions

                    $rows .= $body();
                    $rows .= $actions() ;

                    // End of Execution
                }
                else
                {
                    $rows .= '' . $arr . '	';
                }

                $rows .= '
';

                $index++;
            }

            return $rows . '
';
        }
        else
            return 'No Record(s) Found	';
    }

    public function RenderTable($array) {

        $rows = function() use ($array) {

                    $rows = null;

                    $rows .= $this->renderTableHead($array);

                    $rows .= $this->RenderRows($array);

                    $rows .= $this->renderTableFooter($array);

                    return $rows;
                };

        return $rows();
    }

    private function renderTableFooter($array) {

        $rows = function($row = null) use ($array) {

                    $row .= '

';

                    if (isset($array['tfoot']))
                    {
                        foreach ($array['tfoot'] as $arr)
                        {
                            $row .= '' . $arr . '	';
                        }
                    }

                    $row .= '

';

                    return $row;
                };

        return $rows();
    }

    public function renderTableHead($array) {

        $heading = function ($rows = null) use ($array) {

                    if (isset($array['title']))
                    {
                        $rows = '

' . $array['title'] . '

';
                    }

                    $rows .= '

';

                    return $rows;
                };

        $tableTitles = function ($rows = null, $objectCopy = null) use ($array) {

                    if (isset($array['thead']) && $this->isLoopable($array['thead']))
                    {

                        foreach ($array['thead'] as $arr) {

                            $rows .= '' . $arr . '	';
                        }

                        $rows .= '

';
                    }
                    else
                    {

                        if (is_array($array['tbody']))
                        {

                            foreach ($array['tbody'] as $arr)
                            {

                                if (is_array($array['ignoreFields']) && count($array['ignoreFields']) != 0)
                                {

                                    if(is_object($arr))
                                        $objectCopy = clone $arr;
                                    else
                                        $objectCopy = $arr;

                                    foreach ($array['ignoreFields'] as $ignore)
                                    {

                                        if(is_object($objectCopy))
                                        {
                                            unset($objectCopy -> $ignore);
                                        }
                                        else
                                        {
                                            unset($objectCopy[$ignore]);
                                        }
                                    }

                                    foreach ($objectCopy as $key => $val)
                                    {
                                        $rows .= '' . str_replace('_', ' ', $this->FirstCharacterToUpperCase($key)) . '	';
                                    }

                                    break;
                                }
                            }
                        }
                    }

                    return $rows;
                };

        $tableActions = function($rows = null) use ($array) {

                    if (isset($array['actions'])) {

                        $rows .= 'Actions	';
                    }

                    $rows .= '

';

                    return $rows;
                };

        return $heading() . $tableTitles() . $tableActions();
    }

    /**
     *
     * @param array $sectionData
     * @return string
     * Renders sections html, can be set to two types:
     * Pages
     * Accordians
     */
    public function RenderSections(array $sectionData) {

        $sectionHeader = function($title, $section, $index, $sections = null) use ($sectionData) {

                    if (strtolower($sectionData['type']) == 'accordian')
                        $sections .= '

' . $title . '

';

                    $sections .= '
';

                    $sections .= '
';
                    $sections .= $section['header'];
                    $sections .= '
';

                    return $sections;
                };

        $sectionBody = function($section, $sections = null) {

                    $sections .= '
';
                    $sections .= $section['body'];
                    $sections .= '
';

                    return $sections;
                };

        $sectionFooter = function ($section, $sections = null) {

                    $sections .= '
';
                    $sections .= $section['footer'];
                    $sections .= '
';

                    $sections .= '
';

                    return $sections;
                };

        if (is_array($sectionData)) {

            $sections = '
';

            $index = 1;

            if (!isset($sectionData['type']))
                $sectionData['type'] = 'pages';

            if (strtolower($sectionData['type']) == 'pages')
                $sections .= '

' . $sectionData['title'] . '

';

            foreach ($sectionData['sections'] as $title => $section) {

                $sections .= $sectionHeader($title, $section, $index) . $sectionBody($section) . $sectionFooter();

                $index += 1;
            }

            $sectionStats = function() {

                        return '

Page: 1

<input type="button" value="Previous" class="prev"><input type="button" value="Next" class="next">

';
                    };

            $sections .= $sectionStats() . '
';

            return $sections;
        }
        else
            echo 'INVALID DATA FOR RENDERING SECTIONS';
    }

    /**
     * @param Mixed $string Can be an array or string depending on the filter applied
     * @param string $filter Options given below
     *
     * You can use the output method to filter your output character cases.

     * Four filters can be applied:

     * upper - subject: string

     * lower - subject: string

     * firstUpper or charUpper - subject: string

     * firstLower or charLower - subject: string

     * spacetobreak - subject: string

     * list/orderedlist - subject: array

     * unorderelist - subject: array

     * tablebody/tablerows - subject: array

     * table - subject: array

     * tablehead - subject: array

     * form - subject: array

     * indextable - subject: array

     * sections - subject: array

     *
     */
    public function Output($subject, $filter = null) {

        $filter = strtolower(str_replace(' ', '', $filter));

        if (!empty($filter))
            switch ($filter) {

                case 'upper':
                    $subject = $this->ToUpperCase($subject);
                    break;
                case 'lower':
                    $subject = $this->ToLowerCase($subject);
                    break;
                case 'charupper':
                case 'firstupper':
                    $subject = $this->FirstCharacterToUpperCase($subject);
                    break;
                case 'charlower':
                case 'firstlower':
                    $subject = $this->FirstCharacterToLowerCase($subject);
                    break;
                case 'spacetobreak':
                    $subject = $this->SpaceToBreak($subject);
                    break;
                case 'list':
                case 'orderedlist':
                    $subject = '

' . str_replace(' ', '

', $subject) . '

';
                    break;
                case 'unorderedlist':
                    $subject = '

' . str_replace(' ', '

', $subject) . '

';
                    break;
                case 'tablebody':
                case 'tablerows':
                    $html = new HTMLGenerator();
                    $subject = $html->renderRows($subject);
                    break;
                case 'table':
                    $html = new HTMLGenerator();
                    $subject = $html->renderTable($subject);
                    break;
                case 'tablehead':
                    $html = new HTMLGenerator();
                    $subject = $html->renderTableHead($subject);
                    break;
                case 'form':
                    $html = new HTMLGenerator();
                    $subject = $html->generateForm($subject);
                    break;
                case 'indextable':
                    $html = new HTMLGenerator();
                    $subject = $html->RenderIndexTable($subject);
                    break;
                case 'sections':
                    $html = new HTMLGenerator();
                    $subject = $html->RenderSections($subject);
                    break;
                default:
                    echo 'invalid filter';
                    break;
            }

        return $subject;
    }

    public function element($element = array()) {

        $this->element = $element;

        return $this;
    }

    public function style($style = array()) {

        $this->style = $style;

        return $this;
    }

    public function addClass($class) {

        $this->class = $class;

        return $this;
    }

    public function id($id) {

        $this->id = $id;

        return $this;
    }

    public function renderElement() {

        $element = $this->element;
        $element['style'] = $this->style;
        $element['id'] = $this->id;
        $element['class'] = $this->class;

        $renderedElement = $this->add($element);

        return $renderedElement;
    }

}


text:
<?php

namespace Pingpp;

class Refund extends ApiResource
{
    /**
     * @return string The API URL for this Pingpp refund.
     */
    public function instanceUrl()
    {
        $id = $this['id'];
        $charge = $this['charge'];
        if (!$id) {
            throw new Error\InvalidRequest(
                "Could not determine which URL to request: " .
                "class instance has invalid ID: $id",
                null
            );
        }
        $id = Util\Util::utf8($id);
        $charge = Util\Util::utf8($charge);

        $base = Charge::classUrl();
        $chargeExtn = urlencode($charge);
        $extn = urlencode($id);
        return "$base/$chargeExtn/refunds/$extn";
    }

    /**
     * @param array|string|null $opts
     *
     * @return Refund The saved refund.
     */
    public function save($opts = null)
    {
        return $this->_save($opts);
    }
}


text: Packages and tutorials for YouBot developed in B.Sc thesis project


text:
from __future__ import print_function
from .MapAnalyzer import MapAnalyzer


text:
package com.supremainc.biostar2;

import android.support.test.espresso.action.ViewActions;
import android.support.test.espresso.assertion.ViewAssertions;
import android.support.test.espresso.matcher.ViewMatchers;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.util.Log;

import com.supremainc.biostar2.activity.LoginActivity;

import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.matcher.ViewMatchers.isRoot;
import static android.support.test.espresso.matcher.ViewMatchers.withId;

@RunWith(AndroidJUnit4.class)
public class LoginTest {
    public static final String TAG = "AutoTest";
    @Rule
    public ActivityTestRule<LoginActivity> mActivityRule =
            new ActivityTestRule<>(LoginActivity.class);

    public void w(int time) {
        onView(isRoot()).perform(ExtTest.waitTime(time));
    }

    @Test
    public void login() {
        w(3000);
        if (ExtTest.isExist(R.id.subdomain)) {

            onView(withId(R.id.subdomain)).perform(ViewActions.click());

            w(1100);
            ExtTest.delEditText(R.id.input);

            w(1100);
            onView(withId(R.id.input)).perform(ViewActions.typeText("subdomain")); // subdomain
            onView(withId(R.id.input)).perform(ViewActions.closeSoftKeyboard());

            w(1100);
            onView(withId(R.id.login_id)).perform(ViewActions.click());

            w(1100);
            ExtTest.delEditText(R.id.login_id);

            w(1100);
            onView(withId(R.id.login_id)).perform(ViewActions.typeText("id")); //id
            onView(withId(R.id.login_id)).perform(ViewActions.closeSoftKeyboard());

            w(1100);
            onView(withId(R.id.password)).perform(ViewActions.typeText("password")); //password
            onView(withId(R.id.login_id)).perform(ViewActions.closeSoftKeyboard());

            w(1100);
            onView(withId(R.id.login)).perform(ViewActions.click());
            //  onView(isRoot()).perform(ExtTest.waitId(R.id.main_menu, 10000));

            ExtTest.checkPopup(false);
            onView(withId(R.id.display_time)).check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
            Log.e(TAG, "Login Success");
            w(1100);
            ExtTest.checkPopup(false);
        }
    }
}


text:
<colgroup>
<col width="50%" />
<col width="50%" />
</colgroup>

 Overview
 Library
  Tag
 Help

 FRAMES   NO FRAMES
All Tags

------------------------------------------------------------------------

Struts-Faces
 Tag loadMessages
-----------------

------------------------------------------------------------------------

Create a Map wrapping the specified MessageResources instance, which will return localized messages based on the Locale stored in the view root component of the current view.

------------------------------------------------------------------------

**Tag Information**

Tag Class

org.apache.struts.faces.taglib.LoadMessagesTag

TagExtraInfo Class

*None*

Body Content

empty

Display Name

*None*

**Attributes**

**Name**

**Required**

**Request-time**

**Type**

**Description**

messages

false

false

`java.lang.String`

Application scope key containing the MessageResources instance to be exposed. If not specified, the default MessageResources instance for the current application module is exposed.

var

true

false

`java.lang.String`

Request scope key under which the Map will be stored.

|-------------------------|
| **Variables**           |
| *No Variables Defined.* |

<colgroup>
<col width="50%" />
<col width="50%" />
</colgroup>

 Overview
 Library
  Tag
 Help

 FRAMES   NO FRAMES
All Tags

------------------------------------------------------------------------

*Output Generated by [Tag Library Documentation Generator](http://taglibrarydoc.dev.java.net/). Java, JSP, and JavaServer Pages are trademarks or registered trademarks of Sun Microsystems, Inc. in the US and other countries. Copyright 2002-4 Sun Microsystems, Inc. 4150 Network Circle Santa Clara, CA 95054, U.S.A. All Rights Reserved.*


text:
package server

import (
	"context"
	"errors"
	"strconv"
	"strings"
	"time"

	v1 "k8s.io/api/core/v1"
)

const (
	// bootstrapTokenIDKey is the id of this token. This can be transmitted in the
	// clear and encoded in the name of the secret. It must be a random 6 character
	// string that matches the regexp `^([a-z0-9]{6})$`. Required.
	bootstrapTokenIDKey = "token-id"

	// bootstrapTokenSecretKey is the actual secret. It must be a random 16 character
	// string that matches the regexp `^([a-z0-9]{16})$`. Required.
	bootstrapTokenSecretKey = "token-secret"

	// bootstrapTokenExpirationKey is when this token should be expired and no
	// longer used. A controller will delete this resource after this time. This
	// is an absolute UTC time using RFC3339. If this cannot be parsed, the token
	// should be considered invalid. Optional.
	bootstrapTokenExpirationKey = "expiration"

	// bootstrapTokenUsagePrefix is the prefix for the other usage constants that specifies different
	// functions of a bootstrap token
	bootstrapTokenUsagePrefix = "usage-bootstrap-"

	// bootstrapTokenSecretPrefix is the prefix for bootstrap token names.
	// Bootstrap tokens secrets must be named in the form
	// `bootstrap-token-<token-id>`.  This is the prefix to be used before the
	// token ID.
	bootstrapTokenSecretPrefix = "bootstrap-token-"

	// secretTypeBootstrapToken is used during the automated bootstrap process (first
	// implemented by kubeadm). It stores tokens that are used to sign well known
	// ConfigMaps. They may also eventually be used for authentication.
	secretTypeBootstrapToken v1.SecretType = "bootstrap.kubernetes.io/token"
)

// Config is the configuration for the service
type Config struct {
	// AuthorizationTimeout is the max duration for a authorization
	AuthorizationTimeout time.Duration
	// ClusterTag is the cloud tag key used to identity the cluster
	ClusterTag string
	// Features is arbitrary feature set for a authorizer
	Features []string
	// EnableVerbose indicate verbose logging
	EnableVerbose bool
	// ClientCommonName is the common name on the client certificate if mutual tls is enabled
	ClientCommonName string
	// ClusterName is the name of the kubernetes cluster
	ClusterName string
	// Listen is the interacted to bind to
	Listen string
	// TokenDuration is the expiration of a bootstrap token
	TokenDuration time.Duration
	// TLSCertPath is the path to the server TLS certificate
	TLSCertPath string
	// TLSClientCAPath is the path to a certificate authority
	TLSClientCAPath string
	// TLSPrivateKeyPath is the path to the private key
	TLSPrivateKeyPath string
}

// UseFeature indicates a feature is in use
func (c *Config) UseFeature(name string) bool {
	if len(c.Features) <= 0 {
		return false
	}

	for _, x := range c.Features {
		items := strings.Split(x, "=")
		if items[0] != name {
			continue
		}
		if len(items) == 1 {
			return true
		}

		v, err := strconv.ParseBool(items[1])
		if err != nil {
			return false
		}
		return v
	}

	return false
}

// NodeRegistration is an incomming request
type NodeRegistration struct {
	// Spec is the request specification
	Spec NodeRegistrationSpec
	// Status is the result of a admission
	Status NodeRegistrationStatus
}

// Deny marks the request as denied and adds the reason why
func (n *NodeRegistration) Deny(reason string) {
	n.Status.Allowed = false
	n.Status.Reason = reason
}

// IsAllowed checks if the request if allowed
func (n *NodeRegistration) IsAllowed() bool {
	return n.Status.Allowed
}

// Token defines a bootstrap token
type Token struct {
	// ID is the id of the token
	ID string
	// Secret is the secret of the token
	Secret string
}

// NodeRegistrationSpec is the node request specification
type NodeRegistrationSpec struct {
	// NodeName is the name of the node
	NodeName string
	// RemoteAddr is the address of the requester
	RemoteAddr string
	// Request is the request body
	Request []byte
}

// NodeRegistrationStatus is result of a authorization
type NodeRegistrationStatus struct {
	// Allowed indicates the request is permitted
	Allowed bool
	// Token is the bootstrap token
	Token string
	// Reason is the reason for the error if any
	Reason string
}

// Authorizer is the generic means to authorize the incoming node request
type Authorizer interface {
	// Admit is responsible for checking if the request is permitted
	Authorize(context.Context, *NodeRegistration) error
	// Close provides a signal to close of resources
	Close() error
	// Name returns the name of the authorizer
	Name() string
}

// Verifier is the client side of authorizer
type Verifier interface {
	// VerifyIdentity is responsible for constructing the parameters for a request
	VerifyIdentity(context.Context) ([]byte, error)
}

// IsValid checks the configuration options
func (c *Config) IsValid() error {
	if c.ClusterName == "" {
		return errors.New("no cluster name")
	}
	if c.Listen == "" {
		return errors.New("no interface to bind specified")
	}
	if c.TLSCertPath == "" {
		return errors.New("no tls certificate")
	}
	if c.TLSPrivateKeyPath == "" {
		return errors.New("no private key")
	}

	return nil
}


text:
<?if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true)die();

use Bitrix\Main\Page\Asset,
    Bitrix\Main\Config\Option;

$APPLICATION->SetPageProperty('OG_URL', 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']);

?><!doctype html>
<!--[if lt IE 7]><html class="no-js lt-ie9 lt-ie8 lt-ie7" lang=""><![endif]-->
<!--[if IE 7]><html class="no-js lt-ie9 lt-ie8" lang=""><![endif]-->
<!--[if IE 8]><html class="no-js lt-ie9" lang=""><![endif]-->
<!--[if gt IE 8]><!-->
<html class="no-js" lang="ru">
<!--<![endif]-->
<head><?

    ?><meta charset="utf-8"><?
    ?><meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"><?
    ?><title><?$APPLICATION->ShowTitle()?></title><?
    ?><meta name="description" content=""><?
    ?><meta id="viewport" name="viewport" width="initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no"><?

    ?><meta property="og:title" content="<?$APPLICATION->ShowProperty('OG_TITLE')?>" />
    <meta property="og:description" content="<?$APPLICATION->ShowProperty('OG_DESCRIPTION')?>" />
    <meta property="og:url" content="<?$APPLICATION->ShowProperty('OG_URL')?>" />
    <meta property="og:image" content="<?$APPLICATION->ShowProperty('OG_IMAGE')?>" />
    <meta property="og:type" content="website" />
    <meta property="fb:app_id" content="<?=Option::get('socialservices', 'facebook_appid')?>" /><?

    $APPLICATION->ShowHead();

    Asset::getInstance()->addCss(SITE_TEMPLATE_PATH . '/css/styles.css');
    Asset::getInstance()->addJs(SITE_TEMPLATE_PATH . '/js/scripts.js');

?></head><?
?><body><?

    $APPLICATION->ShowPanel();
    ?>
    <header>
        <?$APPLICATION->IncludeComponent(
            "bitrix:menu",
            "top",
            array(
                "ALLOW_MULTI_SELECT" => "N",
                "CHILD_MENU_TYPE" => "top",
                "COMPONENT_TEMPLATE" => "top",
                "DELAY" => "N",
                "MAX_LEVEL" => "1",
                "MENU_CACHE_GET_VARS" => array(
                ),
                "MENU_CACHE_TIME" => "3600",
                "MENU_CACHE_TYPE" => "A",
                "MENU_CACHE_USE_GROUPS" => "Y",
                "ROOT_MENU_TYPE" => "top",
                "USE_EXT" => "N",
            ),
            false
        );?>
    </header>
    <?

    if (
        $APPLICATION->GetProperty('layout') &&
        file_exists($_SERVER['DOCUMENT_ROOT'] . SITE_TEMPLATE_PATH . '/layouts/' . $APPLICATION->GetProperty('layout') . '/header.php')
    )
    {
        require 'layouts/' . $APPLICATION->GetProperty('layout') . '/header.php';
    }
    else
    {
        require 'layouts/default/header.php';
    }
    ?>


text:
from typing import Callable, Dict, Sequence, Union
import json

import ray
import ray.cloudpickle as cloudpickle
from collections import deque
import copy
import logging
import platform
import shutil
import uuid
import time
import os
from numbers import Number
from ray.tune import TuneError
from ray.tune.checkpoint_manager import Checkpoint, CheckpointManager
# NOTE(rkn): We import ray.tune.registry here instead of importing the names we
# need because there are cyclic imports that may cause specific names to not
# have been defined yet. See https://github.com/ray-project/ray/issues/1716.
from ray.tune.registry import get_trainable_cls, validate_trainable
from ray.tune.result import DEFAULT_RESULTS_DIR, DONE, TRAINING_ITERATION
from ray.tune.resources import Resources, \
    json_to_resources, resources_to_json
from ray.tune.utils.placement_groups import PlacementGroupFactory, \
    resource_dict_to_pg_factory
from ray.tune.utils.serialization import TuneFunctionEncoder
from ray.tune.utils.trainable import TrainableUtil
from ray.tune.utils import date_str, flatten_dict
from ray.util import log_once
from ray._private.utils import binary_to_hex, hex_to_binary

DEBUG_PRINT_INTERVAL = 5
logger = logging.getLogger(__name__)

class Location:
    """Describes the location at which Trial is placed to run."""

    def __init__(self, hostname=None, pid=None):
        self.hostname = hostname
        self.pid = pid

    def __str__(self):
        if not self.pid:
            return ""
        elif self.hostname == platform.node():
            return "pid={}".format(self.pid)
        else:
            return "{}:{}".format(self.hostname, self.pid)

class ExportFormat:
    """Describes the format to import/export the trial Trainable.

    This may correspond to different file formats based on the
    Trainable implementation.
    """
    CHECKPOINT = "checkpoint"
    MODEL = "model"
    H5 = "h5"

    @staticmethod
    def validate(formats):
        """Validates formats.

        Raises:
            ValueError if the format is unknown.
        """
        for i in range(len(formats)):
            formats[i] = formats[i].strip().lower()
            if formats[i] not in [
                    ExportFormat.CHECKPOINT, ExportFormat.MODEL,
                    ExportFormat.H5
            ]:
                raise TuneError("Unsupported import/export format: " +
                                formats[i])

def checkpoint_deleter(trial_id, runner):
    """Returns a checkpoint deleter callback for a runner."""
    if not runner:
        return lambda checkpoint: None

    def delete(checkpoint):
        """Requests checkpoint deletion asynchronously.

        Args:
            checkpoint (Checkpoint): Checkpoint to delete.
        """
        if checkpoint.storage == Checkpoint.PERSISTENT and checkpoint.value:
            logger.debug("Trial %s: Deleting checkpoint %s", trial_id,
                         checkpoint.value)
            checkpoint_path = checkpoint.value
            # Delete local copy, if any exists.
            if os.path.exists(checkpoint_path):
                try:
                    checkpoint_dir = TrainableUtil.find_checkpoint_dir(
                        checkpoint_path)
                    shutil.rmtree(checkpoint_dir)
                except FileNotFoundError:
                    logger.warning("Checkpoint dir not found during deletion.")

            # TODO(ujvl): Batch remote deletes.
            runner.delete_checkpoint.remote(checkpoint.value)

    return delete

class TrialInfo:
    """Serializable struct for holding information for a Trial.

    Attributes:
        trial_name (str): String name of the current trial.
        trial_id (str): trial_id of the trial
    """

    def __init__(self, trial):
        self._trial_name = str(trial)
        self._trial_id = trial.trial_id

    @property
    def trial_name(self):
        return self._trial_name

    @property
    def trial_id(self):
        return self._trial_id

def create_logdir(dirname, local_dir):
    local_dir = os.path.expanduser(local_dir)
    logdir = os.path.join(local_dir, dirname)
    if os.path.exists(logdir):
        old_dirname = dirname
        dirname += "_" + uuid.uuid4().hex[:4]
        logger.info(f"Creating a new dirname {dirname} because "
                    f"trial dirname '{old_dirname}' already exists.")
        logdir = os.path.join(local_dir, dirname)
    os.makedirs(logdir, exist_ok=True)
    return logdir

class Trial:
    """A trial object holds the state for one model training run.

    Trials are themselves managed by the TrialRunner class, which implements
    the event loop for submitting trial runs to a Ray cluster.

    Trials start in the PENDING state, and transition to RUNNING once started.
    On error it transitions to ERROR, otherwise TERMINATED on success.

    Attributes:
        trainable_name (str): Name of the trainable object to be executed.
        config (dict): Provided configuration dictionary with evaluated params.
        trial_id (str): Unique identifier for the trial.
        local_dir (str): Local_dir as passed to tune.run.
        logdir (str): Directory where the trial logs are saved.
        evaluated_params (dict): Evaluated parameters by search algorithm,
        experiment_tag (str): Identifying trial name to show in the console.
        resources (Resources): Amount of resources that this trial will use.
        status (str): One of PENDING, RUNNING, PAUSED, TERMINATED, ERROR/
        error_file (str): Path to the errors that this trial has raised.

    """

    _nonjson_fields = [
        "results",
        "best_result",
        "param_config",
        "extra_arg",
    ]

    PENDING = "PENDING"
    RUNNING = "RUNNING"
    PAUSED = "PAUSED"
    TERMINATED = "TERMINATED"
    ERROR = "ERROR"

    def __init__(self,
                 trainable_name,
                 config=None,
                 trial_id=None,
                 local_dir=DEFAULT_RESULTS_DIR,
                 evaluated_params=None,
                 experiment_tag="",
                 resources=None,
                 placement_group_factory=None,
                 stopping_criterion=None,
                 remote_checkpoint_dir=None,
                 sync_to_cloud=None,
                 checkpoint_freq=0,
                 checkpoint_at_end=False,
                 sync_on_checkpoint=True,
                 keep_checkpoints_num=None,
                 checkpoint_score_attr=TRAINING_ITERATION,
                 export_formats=None,
                 restore_path=None,
                 trial_name_creator=None,
                 trial_dirname_creator=None,
                 log_to_file=None,
                 max_failures=0):
        """Initialize a new trial.

        The args here take the same meaning as the command line flags defined
        in ray.tune.config_parser.
        """
        validate_trainable(trainable_name)
        # Trial config
        self.trainable_name = trainable_name
        self.trial_id = Trial.generate_id() if trial_id is None else trial_id
        self.config = config or {}
        self.local_dir = local_dir  # This remains unexpanded for syncing.

        #: Parameters that Tune varies across searches.
        self.evaluated_params = evaluated_params or {}
        self.experiment_tag = experiment_tag
        trainable_cls = self.get_trainable_cls()
        if trainable_cls:
            default_resources = trainable_cls.default_resource_request(
                self.config)

            # If Trainable returns resources, do not allow manual override via
            # `resources_per_trial` by the user.
            if default_resources:
                if resources or placement_group_factory:
                    raise ValueError(
                        "Resources for {} have been automatically set to {} "
                        "by its `default_resource_request()` method. Please "
                        "clear the `resources_per_trial` option.".format(
                            trainable_cls, default_resources))

                # New way: Trainable returns a PlacementGroupFactory object.
                if isinstance(default_resources, PlacementGroupFactory):
                    placement_group_factory = default_resources
                    resources = None
                # Set placement group factory to None for backwards
                # compatibility.
                else:
                    placement_group_factory = None
                    resources = default_resources
        self.location = Location()

        self.resources = resources or Resources(cpu=1, gpu=0)
        self.placement_group_factory = placement_group_factory
        self._setup_resources()

        self.stopping_criterion = stopping_criterion or {}

        self.log_to_file = log_to_file
        # Make sure `stdout_file, stderr_file = Trial.log_to_file` works
        if not self.log_to_file or not isinstance(self.log_to_file, Sequence) \
           or not len(self.log_to_file) == 2:
            self.log_to_file = (None, None)

        self.max_failures = max_failures

        # Local trial state that is updated during the run
        self.last_result = {}
        self.last_update_time = -float("inf")

        # stores in memory max/min/avg/last-n-avg/last result for each
        # metric by trial
        self.metric_analysis = {}

        # keep a moving average over these last n steps
        self.n_steps = [5, 10]
        self.metric_n_steps = {}

        self.export_formats = export_formats
        self.status = Trial.PENDING
        self.start_time = None
        self.logdir = None
        self.runner = None
        self.last_debug = 0
        self.error_file = None
        self.error_msg = None
        self.trial_name_creator = trial_name_creator
        self.custom_trial_name = None
        self.custom_dirname = None

        # Checkpointing fields
        self.saving_to = None
        if remote_checkpoint_dir:
            self.remote_checkpoint_dir_prefix = remote_checkpoint_dir
        else:
            self.remote_checkpoint_dir_prefix = None
        self.sync_to_cloud = sync_to_cloud
        self.checkpoint_freq = checkpoint_freq
        self.checkpoint_at_end = checkpoint_at_end
        self.keep_checkpoints_num = keep_checkpoints_num
        self.checkpoint_score_attr = checkpoint_score_attr
        self.sync_on_checkpoint = sync_on_checkpoint
        self.checkpoint_manager = CheckpointManager(
            keep_checkpoints_num, checkpoint_score_attr,
            checkpoint_deleter(self._trainable_name(), self.runner))

        # Restoration fields
        self.restore_path = restore_path
        self.restoring_from = None
        self.num_failures = 0

        # AutoML fields
        self.results = None
        self.best_result = None
        self.param_config = None
        self.extra_arg = None

        if trial_name_creator:
            self.custom_trial_name = trial_name_creator(self)

        if trial_dirname_creator:
            self.custom_dirname = trial_dirname_creator(self)
            if os.path.sep in self.custom_dirname:
                raise ValueError("Trial dirname must not contain '/'. "
                                 "Got {self.custom_dirname}")

        self._state_json = None
        self._state_valid = False

    def _setup_resources(self, log_always: bool = False):
        """Set up resource and placement group requirements.

        This will try to convert the resource request in ``self.resources``
        to a placement group factory object. If this is unsuccessful,
        placement groups will not be used.

        Args:
            log_always (bool): If True, this will always log a warning if
                conversion from a resource dict to a placement group
                definition was unsuccessful (e.g. when passing ``extra_``
                requests).

        """
        if not self.placement_group_factory and \
           not int(os.getenv("TUNE_PLACEMENT_GROUP_AUTO_DISABLED", "0")):
            try:
                self.placement_group_factory = resource_dict_to_pg_factory(
                    self.resources)
            except ValueError as exc:
                if log_always or log_once("tune_pg_extra_resources"):
                    logger.warning(exc)
                self.placement_group_factory = None

        # Set placement group factory flag to True in Resources object.
        if self.placement_group_factory:
            resource_kwargs = self.resources._asdict()
            resource_kwargs["has_placement_group"] = True
            self.resources = Resources(**resource_kwargs)

    @property
    def node_ip(self):
        return self.location.hostname

    @property
    def checkpoint(self):
        """Returns the most recent checkpoint.

        If the trial is in ERROR state, the most recent PERSISTENT checkpoint
        is returned.
        """
        if self.status == Trial.ERROR:
            checkpoint = self.checkpoint_manager.newest_persistent_checkpoint
        else:
            checkpoint = self.checkpoint_manager.newest_checkpoint
        if checkpoint.value is None:
            checkpoint = Checkpoint(Checkpoint.PERSISTENT, self.restore_path)
        return checkpoint

    @classmethod
    def generate_id(cls):
        return str(uuid.uuid1().hex)[:8]

    @property
    def remote_checkpoint_dir(self):
        assert self.logdir, "Trial {}: logdir not initialized.".format(self)
        if not self.remote_checkpoint_dir_prefix:
            return None
        logdir_name = os.path.basename(self.logdir)
        return os.path.join(self.remote_checkpoint_dir_prefix, logdir_name)

    @property
    def uses_placement_groups(self):
        return bool(self.placement_group_factory)

    def reset(self):
        return Trial(
            self.trainable_name,
            config=self.config,
            trial_id=None,
            local_dir=self.local_dir,
            evaluated_params=self.evaluated_params,
            experiment_tag=self.experiment_tag,
            resources=self.resources,
            placement_group_factory=self.placement_group_factory,
            stopping_criterion=self.stopping_criterion,
            remote_checkpoint_dir=self.remote_checkpoint_dir,
            checkpoint_freq=self.checkpoint_freq,
            checkpoint_at_end=self.checkpoint_at_end,
            sync_on_checkpoint=self.sync_on_checkpoint,
            keep_checkpoints_num=self.keep_checkpoints_num,
            checkpoint_score_attr=self.checkpoint_score_attr,
            export_formats=self.export_formats,
            restore_path=self.restore_path,
            trial_name_creator=self.trial_name_creator,
            log_to_file=self.log_to_file,
            max_failures=self.max_failures,
        )

    def init_logdir(self):
        """Init logdir."""
        if not self.logdir:
            self.logdir = create_logdir(self._generate_dirname(),
                                        self.local_dir)
        else:
            os.makedirs(self.logdir, exist_ok=True)
        self.invalidate_json_state()

    def update_resources(
            self, resources: Union[Dict, Callable, PlacementGroupFactory]):
        """EXPERIMENTAL: Updates the resource requirements.

        Should only be called when the trial is not running.

        Raises:
            ValueError if trial status is running.
        """
        if self.status is Trial.RUNNING:
            raise ValueError("Cannot update resources while Trial is running.")

        if isinstance(resources, PlacementGroupFactory):
            self.placement_group_factory = resources
        else:
            self.resources = Resources(**resources)

        self._setup_resources()

        self.invalidate_json_state()

    def set_runner(self, runner):
        self.runner = runner
        self.checkpoint_manager.delete = checkpoint_deleter(
            self._trainable_name(), runner)
        # No need to invalidate state cache: runner is not stored in json
        # self.invalidate_json_state()

    def set_location(self, location):
        """Sets the location of the trial."""
        self.location = location
        # No need to invalidate state cache: location is not stored in json
        # self.invalidate_json_state()

    def set_status(self, status):
        """Sets the status of the trial."""
        self.status = status
        if status == Trial.RUNNING:
            if self.start_time is None:
                self.start_time = time.time()
        self.invalidate_json_state()

    def set_config(self, config):
        self.config = config
        self.invalidate_json_state()

    def set_experiment_tag(self, experiment_tag):
        self.experiment_tag = experiment_tag
        self.invalidate_json_state()

    def write_error_log(self, error_msg):
        if error_msg and self.logdir:
            self.num_failures += 1
            self.error_file = os.path.join(self.logdir, "error.txt")
            with open(self.error_file, "a+") as f:
                f.write("Failure # {} (occurred at {})\n".format(
                    self.num_failures, date_str()))
                f.write(error_msg + "\n")
            self.error_msg = error_msg
        self.invalidate_json_state()

    def should_stop(self, result):
        """Whether the given result meets this trial's stopping criteria."""
        if result.get(DONE):
            return True

        for criteria, stop_value in self.stopping_criterion.items():
            if criteria not in result:
                raise TuneError(
                    "Stopping criteria {} not provided in result {}.".format(
                        criteria, result))
            elif isinstance(criteria, dict):
                raise ValueError(
                    "Stopping criteria is now flattened by default. "
                    "Use forward slashes to nest values `key1/key2/key3`.")
            elif result[criteria] >= stop_value:
                return True
        return False

    def should_checkpoint(self):
        """Whether this trial is due for checkpointing."""
        result = self.last_result or {}
        if result.get(DONE) and self.checkpoint_at_end:
            return True
        return (self.checkpoint_freq and
                result.get(TRAINING_ITERATION, 0) % self.checkpoint_freq == 0)

    def has_checkpoint(self):
        return self.checkpoint.value is not None

    def clear_checkpoint(self):
        self.checkpoint.value = None
        self.restoring_from = None
        self.invalidate_json_state()

    def on_checkpoint(self, checkpoint):
        """Hook for handling checkpoints taken by the Trainable.

        Args:
            checkpoint (Checkpoint): Checkpoint taken.
        """
        self.checkpoint_manager.on_checkpoint(checkpoint)
        self.invalidate_json_state()

    def on_restore(self):
        """Handles restoration completion."""
        assert self.is_restoring
        self.last_result = self.restoring_from.result
        self.restoring_from = None
        self.invalidate_json_state()

    def should_recover(self):
        """Returns whether the trial qualifies for retrying.

        This is if the trial has not failed more than max_failures. Note this
        may return true even when there is no checkpoint, either because
        `self.checkpoint_freq` is `0` or because the trial failed before
        a checkpoint has been made.
        """
        return self.num_failures < self.max_failures or self.max_failures < 0

    def update_last_result(self, result, terminate=False):
        if self.experiment_tag:
            result.update(experiment_tag=self.experiment_tag)

        self.set_location(Location(result.get("node_ip"), result.get("pid")))
        self.last_result = result
        self.last_update_time = time.time()

        for metric, value in flatten_dict(result).items():
            if isinstance(value, Number):
                if metric not in self.metric_analysis:
                    self.metric_analysis[metric] = {
                        "max": value,
                        "min": value,
                        "avg": value,
                        "last": value
                    }
                    self.metric_n_steps[metric] = {}
                    for n in self.n_steps:
                        key = "last-{:d}-avg".format(n)
                        self.metric_analysis[metric][key] = value
                        # Store n as string for correct restore.
                        self.metric_n_steps[metric][str(n)] = deque(
                            [value], maxlen=n)
                else:
                    step = result["training_iteration"] or 1
                    self.metric_analysis[metric]["max"] = max(
                        value, self.metric_analysis[metric]["max"])
                    self.metric_analysis[metric]["min"] = min(
                        value, self.metric_analysis[metric]["min"])
                    self.metric_analysis[metric]["avg"] = 1 / step * (
                        value +
                        (step - 1) * self.metric_analysis[metric]["avg"])
                    self.metric_analysis[metric]["last"] = value

                    for n in self.n_steps:
                        key = "last-{:d}-avg".format(n)
                        self.metric_n_steps[metric][str(n)].append(value)
                        self.metric_analysis[metric][key] = sum(
                            self.metric_n_steps[metric][str(n)]) / len(
                                self.metric_n_steps[metric][str(n)])
        self.invalidate_json_state()

    def get_trainable_cls(self):
        return get_trainable_cls(self.trainable_name)

    def is_finished(self):
        return self.status in [Trial.ERROR, Trial.TERMINATED]

    @property
    def is_restoring(self):
        return self.restoring_from is not None

    @property
    def is_saving(self):
        return self.saving_to is not None

    def __repr__(self):
        return self._trainable_name(include_trial_id=True)

    def __str__(self):
        return self._trainable_name(include_trial_id=True)

    def _trainable_name(self, include_trial_id=False):
        """Combines ``env`` with ``trainable_name`` and ``trial_id``.

        Can be overridden with a custom string creator.
        """
        if self.custom_trial_name:
            return self.custom_trial_name

        if "env" in self.config:
            env = self.config["env"]
            if isinstance(env, type):
                env = env.__name__
            identifier = "{}_{}".format(self.trainable_name, env)
        else:
            identifier = self.trainable_name
        if include_trial_id:
            identifier += "_" + self.trial_id
        return identifier.replace("/", "_")

    def _generate_dirname(self):
        if self.custom_dirname:
            generated_dirname = self.custom_dirname
        else:
            if "MAX_LEN_IDENTIFIER" in os.environ:
                logger.error("The MAX_LEN_IDENTIFIER environment variable is "
                             "deprecated and will be removed in the future. "
                             "Use TUNE_MAX_LEN_IDENTIFIER instead.")
            MAX_LEN_IDENTIFIER = int(
                os.environ.get("TUNE_MAX_LEN_IDENTIFIER",
                               os.environ.get("MAX_LEN_IDENTIFIER", 130)))
            generated_dirname = f"{str(self)}_{self.experiment_tag}"
            generated_dirname = generated_dirname[:MAX_LEN_IDENTIFIER]
            generated_dirname += f"_{date_str()}"
        return generated_dirname.replace("/", "_")

    def invalidate_json_state(self):
        self._state_valid = False

    def get_json_state(self) -> str:
        if not self._state_json or not self._state_valid:
            json_state = json.dumps(
                self.__getstate__(), indent=2, cls=TuneFunctionEncoder)
            self._state_json = json_state
            self._state_valid = True
        return self._state_json

    def __getstate__(self):
        """Memento generator for Trial.

        Sets RUNNING trials to PENDING.
        Note this can only occur if the trial holds a PERSISTENT checkpoint.
        """
        state = self.__dict__.copy()
        state["resources"] = resources_to_json(self.resources)

        for key in self._nonjson_fields:
            state[key] = binary_to_hex(cloudpickle.dumps(state.get(key)))

        state["runner"] = None
        state["location"] = Location()
        # Avoid waiting for events that will never occur on resume.
        state["restoring_from"] = None
        state["saving_to"] = None

        state["_state_json"] = None
        state["_state_valid"] = False

        return copy.deepcopy(state)

    def __setstate__(self, state):
        state["resources"] = json_to_resources(state["resources"])

        if state["status"] == Trial.RUNNING:
            state["status"] = Trial.PENDING
        for key in self._nonjson_fields:
            state[key] = cloudpickle.loads(hex_to_binary(state[key]))

        self.__dict__.update(state)
        validate_trainable(self.trainable_name)

        # Avoid creating logdir in client mode for returned trial results,
        # since the dir might not be creatable locally. TODO(ekl) thsi is kind
        # of a hack.
        if not ray.util.client.ray.is_connected():
            self.init_logdir()  # Create logdir if it does not exist


text:
package io.fabric8.camel;

import io.fabric8.groups.GroupListener;
import io.fabric8.groups.GroupListener.GroupEvent;
import io.fabric8.zookeeper.utils.ZooKeeperUtils;
import org.apache.camel.Consumer;
import org.apache.camel.Processor;
import org.apache.camel.Producer;
import org.apache.camel.impl.DefaultEndpoint;
import org.apache.camel.util.IntrospectionSupport;
import org.apache.camel.util.URISupport;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import io.fabric8.groups.Group;
import org.apache.curator.framework.state.ConnectionState;
import io.fabric8.common.util.PublicPortMapper;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

/**
 * Creates an endpoint which uses FABRIC to map a logical name to physical endpoint names
 */
public class FabricPublisherEndpoint extends DefaultEndpoint {
    private static final transient Log LOG = LogFactory.getLog(FabricPublisherEndpoint.class);

    private final FabricComponent component;
    private final String singletonId;
    private final String child;
    private final String consumer;
    private Group<CamelNodeState> group;
    private String joined;

    private final AtomicReference<GroupEvent> prevConnectionState = new AtomicReference<GroupEvent>(GroupEvent.DISCONNECTED);

    public FabricPublisherEndpoint(String uri, FabricComponent component, String singletonId, String child) throws Exception {
        super(uri, component);
        this.component = component;
        this.singletonId = singletonId;

        String path = child;
        int idx = path.indexOf('?');
        if (idx > -1) {
            path = path.substring(0, idx);
        }
        Map<String, Object> params = URISupport.parseParameters(new URI(child));
        String consumer = params != null ? (String) params.remove("consumer") : null;
        if (consumer != null) {
            Map<String, Object> properties = IntrospectionSupport.extractProperties(params, "consumer.");
            if (properties != null && properties.size() > 0) {
                consumer = consumer + "?" + URISupport.createQueryString(properties);
                for (String k : properties.keySet()) {
                    params.remove(k);
                }
            }
            child = path;
            if (params.size() > 0) {
                child = child + "?" + URISupport.createQueryString(params);
            }
        } else {
            consumer = child;
        }
        LOG.info("Child: " + child);
        LOG.info("Consumer (internal address): " + consumer);
        // let's make the consumer URI public (important inside OpenShift)
        consumer = toPublicAddress(consumer);
        LOG.info("Consumer (public address): " + consumer);

        this.child = child;
        this.consumer = consumer;

        publishOnZK();

    }

    public Producer createProducer() throws Exception {
        return getCamelContext().getEndpoint(child).createProducer();
    }

    @Override
    public boolean isLenientProperties() {
        // to allow properties to be propagated to the child endpoint
        return true;
    }

    public Consumer createConsumer(Processor processor) throws Exception {
        return getCamelContext().getEndpoint(child).createConsumer(processor);
    }

    public boolean isSingleton() {
        return true;
    }

    @Override
    public void doStart() throws Exception {
        super.doStart();
        group.start();
    }

    @Override
    public void doStop() throws Exception {
        group.close();
        super.doStop();
    }

    /**
     * Uses a port mapper to correctly convert to public address:port (e.g. in OpenShift environment)
     *
     * @param address
     * @return
     */
    protected String toPublicAddress(String address) {
        try {
            String containerId = System.getProperty("karaf.name");
            if (containerId == null || containerId.trim().equals("")) {
                return address;
            }
            URI uri = new URI(address);
            StringBuilder schemes = new StringBuilder();
            String answer;
            while (uri.getSchemeSpecificPart().contains("://")) {
                schemes.append(uri.getScheme()).append(":");
                uri = new URI(uri.getSchemeSpecificPart());
            }
            int port = publicPort(uri);
            String path = uri.getPath();
            if (uri.getQuery() != null) {
                path += "?" + uri.getQuery();
            }
            while (path.startsWith("/")) {
                path = path.substring(1);
            }
            if (!path.trim().equals("")) {
                path = "/" + path;
            }
            if (getComponent().getCurator() != null) {
                String hostname = "${zk:" + containerId + "/ip}";
                answer =  schemes.toString() + uri.getScheme() + "://" + hostname + ":" + port + path;
                getComponent().getCurator().getZookeeperClient().blockUntilConnectedOrTimedOut();
                answer = ZooKeeperUtils.getSubstitutedData(getComponent().getCurator(), answer);
            } else {
                answer =  schemes.toString() + uri.getScheme() + "://" + uri.getHost() + ":" + port + path;
            }
            return answer;
        } catch (InterruptedException e) {
            LOG.warn("Could not connect to Zookeeper to get public container address");
            return address;
        } catch (URISyntaxException e) {
            LOG.warn("Could not map URL to a public address: " + address);
            return address;
        }
    }

    protected int publicPort(URI uri) {
        return PublicPortMapper.getPublicPort(uri.getPort());
    }

    // Properties
    //-------------------------------------------------------------------------
    public FabricComponent getComponent() {
        return component;
    }

    public String getChild() {
        return child;
    }

    public synchronized void publishOnZK(){
        String path = getComponent().getFabricPath(singletonId);
        this.group = getComponent().createGroup(path);
        CamelNodeState state = new CamelNodeState(singletonId);
        state.consumer = consumer;
        group.update(state);

        group.add(new GroupListener<CamelNodeState>() {
            @Override
            public void groupEvent(Group<CamelNodeState> group, GroupEvent newState) {
                LOG.info("Triggered event: " + newState);
                switch (prevConnectionState.getAndSet(newState)){
                    case DISCONNECTED:
                        switch (newState){
                            case CONNECTED:
                                CamelNodeState state = new CamelNodeState(singletonId);
                                state.consumer = consumer;
                                group.update(state);
                                break;
                            case CHANGED:
                            case DISCONNECTED:
                                break;
                            default:
                                LOG.error("Unhandled Curator connection state: " + newState, new IllegalArgumentException("Unhandled Curator connection state."));
                        }
                        break;
                    case CONNECTED:
                    case CHANGED:
                        break;
                    default:
                        LOG.error("Unhandled Curator connection state: " + newState, new IllegalArgumentException("Unhandled Curator connection state."));
                }

            }
        });

        group.start();

    }
}


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

    <TITLE>
        org.apache.jmeter.engine.event (Apache JMeter API)
    </TITLE>

    <META NAME="keywords" CONTENT="org.apache.jmeter.engine.event package">

    <LINK REL="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

    org.apache.jmeter.engine.event

            Interfaces

                LoopIterationListener

            Classes

                LoopIterationEvent