text:
"""
    Emblem API

    REST API for any Emblem server  # noqa: E501

    The version of the OpenAPI document: 2021-07-28
    Generated by: https://openapi-generator.tech
"""

import sys
import unittest

import generated
from generated.model.donor import Donor

class TestDonor(unittest.TestCase):
    """Donor unit test stubs"""

    def setUp(self):
        pass

    def tearDown(self):
        pass

    def testDonor(self):
        """Test Donor"""
        # FIXME: construct object with mandatory attributes with example values
        # model = Donor()  # noqa: E501
        pass

if __name__ == '__main__':
    unittest.main()


text:
get '/home' do #RESTfully /videos
  @videos = Video.all
  erb :index
end

get '/videos/new' do
  erb :"videos/new"
end

get '/videos/:id' do
  @video = Video.find(params[:id])

  erb :"videos/show"
end

get '/videos/:id/like' do
  video = Video.find(params[:id])
  video.likes.create(value: 1)

  content_type :json
  {like_count: video.likes.count}.to_json
end

post '/videos' do
  embed_url = convert_url(params[:video_url])
  @video = Video.new(video_name: params[:video_name],
                     video_url: embed_url,
                     description: params[:description],
                     rating: 0,
                     user_id: 1)

  if @video.save

    params[:tags].split(",").map(&:strip).each do |tag|
      the_tag = Tag.find_by(name: tag)
      the_tag = Tag.create(name: tag) unless the_tag

      @video.tags << the_tag
    end

    redirect '/home'
  else
    erb :"/videos/new"
  end
end

delete '/videos/delete/:id' do
  video = Video.find(params[:id])
  video.destroy

  redirect '/home'
end

redpajama_set_name: RedPajamaGithub


text:
package org.apache.axis2.jaxws.handler.lifecycle.impl;

import org.apache.axis2.jaxws.ExceptionFactory;
import org.apache.axis2.jaxws.core.MessageContext;
import org.apache.axis2.jaxws.description.ServiceDescription;
import org.apache.axis2.jaxws.handler.lifecycle.factory.HandlerLifecycleManager;
import org.apache.axis2.jaxws.i18n.Messages;
import org.apache.axis2.jaxws.injection.ResourceInjectionException;
import org.apache.axis2.jaxws.lifecycle.BaseLifecycleManager;
import org.apache.axis2.jaxws.lifecycle.LifecycleException;
import org.apache.axis2.jaxws.runtime.description.injection.ResourceInjectionServiceRuntimeDescription;
import org.apache.axis2.jaxws.runtime.description.injection.ResourceInjectionServiceRuntimeDescriptionFactory;

import javax.xml.ws.handler.Handler;

public class HandlerLifecycleManagerImpl extends BaseLifecycleManager implements HandlerLifecycleManager {

    public Handler createHandlerInstance(MessageContext mc, Class handlerClass) throws LifecycleException, ResourceInjectionException {
        if (handlerClass == null) {
            throw ExceptionFactory.
              makeWebServiceException(Messages.getMessage("createHandlerInstanceErr"));
        }

        ServiceDescription serviceDesc = mc.getEndpointDescription().getServiceDescription();
        ResourceInjectionServiceRuntimeDescription injectionDesc = null;
        if (serviceDesc != null) {
            injectionDesc = ResourceInjectionServiceRuntimeDescriptionFactory.get(serviceDesc, handlerClass);
        }

        try {
            this.instance = handlerClass.newInstance();
        } catch (InstantiationException e) {
            throw ExceptionFactory.makeWebServiceException(e);
        } catch (IllegalAccessException e) {
            throw ExceptionFactory.makeWebServiceException(e);
        }

        //Invoke PostConstruct
        if (injectionDesc != null && injectionDesc.getPostConstructMethod() != null) {
            invokePostConstruct(injectionDesc.getPostConstructMethod());
        }

        return (Handler)this.instance;
    }

    /**
     * destroyHandlerInstance calls the handler's annotated PreDestroy method,
     * if it exists.  A handler instance that has been passed through this method SHOULD NOT be used again
     *
     * @param handler
     */
    public void destroyHandlerInstance(MessageContext mc, Handler handler) throws LifecycleException, ResourceInjectionException {
        if (handler == null) {
            throw ExceptionFactory.
              makeWebServiceException(Messages.getMessage("destroyHandlerInstanceErr"));
        }

        this.instance = handler;

        ServiceDescription serviceDesc = mc.getEndpointDescription().getServiceDescription();
        ResourceInjectionServiceRuntimeDescription injectionDesc = null;
        if (serviceDesc != null) {
            injectionDesc = ResourceInjectionServiceRuntimeDescriptionFactory.get(serviceDesc, handler.getClass());
        }

        //Invoke PreDestroy
        if (injectionDesc != null && injectionDesc.getPreDestroyMethod() != null) {
            invokePreDestroy(injectionDesc.getPreDestroyMethod());
        }
    }

}


text:
<?php
class ControllerCheckoutGuestStep3 extends Controller {
	private $error = array();

	public function index() {
		if (!$this->cart->hasProducts() || (!$this->cart->hasStock() && !$this->config->get('config_stock_checkout'))) {
	  		$this->redirect(HTTPS_SERVER . 'index.php?route=checkout/cart');
    	}

		if ($this->customer->isLogged()) {
	  		$this->redirect(HTTPS_SERVER . 'index.php?route=checkout/shipping');
    	}

		if (!isset($this->session->data['guest'])) {
	  		$this->redirect(HTTPS_SERVER . 'index.php?route=checkout/guest_step_1');
    	}

    	if ($this->cart->hasShipping()) {
			if (!isset($this->session->data['shipping_method'])) {
	  			$this->redirect(HTTPS_SERVER . 'index.php?route=checkout/guest_step_2');
    		}
		} else {
			unset($this->session->data['shipping_method']);
			unset($this->session->data['shipping_methods']);

			$this->tax->setZone($this->config->get('config_country_id'), $this->config->get('config_zone_id'));
		}

		if (!isset($this->session->data['payment_method'])) {
	  		$this->redirect(HTTPS_SERVER . 'index.php?route=checkout/guest_step_2');
    	}

		$total_data = array();
		$total = 0;
		$taxes = $this->cart->getTaxes();

		$this->load->model('checkout/extension');

		$sort_order = array();

		$results = $this->model_checkout_extension->getExtensions('total');

		foreach ($results as $key => $value) {
			$sort_order[$key] = $this->config->get($value['key'] . '_sort_order');
		}

		array_multisort($sort_order, SORT_ASC, $results);

		foreach ($results as $result) {
			$this->load->model('total/' . $result['key']);

			$this->{'model_total_' . $result['key']}->getTotal($total_data, $total, $taxes);
		}

		$sort_order = array();

		foreach ($total_data as $key => $value) {
      		$sort_order[$key] = $value['sort_order'];
    	}

    	array_multisort($sort_order, SORT_ASC, $total_data);

		$this->language->load('checkout/confirm');

    	$this->document->title = $this->language->get('heading_title');

		$data = array();

		$data['store_id'] = $this->config->get('config_store_id');
		$data['store_name'] = $this->config->get('config_name');
		$data['store_url'] = $this->config->get('config_url');
		$data['customer_id'] = 0;
		$data['customer_group_id'] = $this->config->get('config_customer_group_id');
		$data['firstname'] = $this->session->data['guest']['firstname'];
		$data['lastname'] = $this->session->data['guest']['lastname'];
		$data['email'] = $this->session->data['guest']['email'];
		$data['telephone'] = $this->session->data['guest']['telephone'];
		$data['fax'] = $this->session->data['guest']['fax'];

		if ($this->cart->hasShipping()) {
			if (isset($this->session->data['guest']['shipping'])) {
				$data['shipping_firstname'] = $this->session->data['guest']['shipping']['firstname'];
				$data['shipping_lastname'] = $this->session->data['guest']['shipping']['lastname'];
				$data['shipping_company'] = $this->session->data['guest']['shipping']['company'];
				$data['shipping_address_1'] = $this->session->data['guest']['shipping']['address_1'];
				$data['shipping_address_2'] = $this->session->data['guest']['shipping']['address_2'];
				$data['shipping_city'] = $this->session->data['guest']['shipping']['city'];
				$data['shipping_postcode'] = $this->session->data['guest']['shipping']['postcode'];
				$data['shipping_zone'] = $this->session->data['guest']['shipping']['zone'];
				$data['shipping_zone_id'] = $this->session->data['guest']['shipping']['zone_id'];
				$data['shipping_country'] = $this->session->data['guest']['shipping']['country'];
				$data['shipping_country_id'] = $this->session->data['guest']['shipping']['country_id'];
				$data['shipping_address_format'] = $this->session->data['guest']['shipping']['address_format'];
			} else {
				$data['shipping_firstname'] = $this->session->data['guest']['firstname'];
				$data['shipping_lastname'] = $this->session->data['guest']['lastname'];
				$data['shipping_company'] = $this->session->data['guest']['company'];
				$data['shipping_address_1'] = $this->session->data['guest']['address_1'];
				$data['shipping_address_2'] = $this->session->data['guest']['address_2'];
				$data['shipping_city'] = $this->session->data['guest']['city'];
				$data['shipping_postcode'] = $this->session->data['guest']['postcode'];
				$data['shipping_zone'] = $this->session->data['guest']['zone'];
				$data['shipping_zone_id'] = $this->session->data['guest']['zone_id'];
				$data['shipping_country'] = $this->session->data['guest']['country'];
				$data['shipping_country_id'] = $this->session->data['guest']['country_id'];
				$data['shipping_address_format'] = $this->session->data['guest']['address_format'];
			}
			if (isset($this->session->data['shipping_method']['title'])) {
				$data['shipping_method'] = $this->session->data['shipping_method']['title'];
			} else {
				$data['shipping_method'] = '';
			}
		} else {
			$data['shipping_firstname'] = '';
			$data['shipping_lastname'] = '';
			$data['shipping_company'] = '';
			$data['shipping_address_1'] = '';
			$data['shipping_address_2'] = '';
			$data['shipping_city'] = '';
			$data['shipping_postcode'] = '';
			$data['shipping_zone'] = '';
			$data['shipping_zone_id'] = '';
			$data['shipping_country'] = '';
			$data['shipping_country_id'] = '';
			$data['shipping_address_format'] = '';
			$data['shipping_method'] = '';
		}

		$data['payment_firstname'] = $this->session->data['guest']['firstname'];
		$data['payment_lastname'] = $this->session->data['guest']['lastname'];
		$data['payment_company'] = $this->session->data['guest']['company'];
		$data['payment_address_1'] = $this->session->data['guest']['address_1'];
		$data['payment_address_2'] = $this->session->data['guest']['address_2'];
		$data['payment_city'] = $this->session->data['guest']['city'];
		$data['payment_postcode'] = $this->session->data['guest']['postcode'];
		$data['payment_zone'] = $this->session->data['guest']['zone'];
		$data['payment_zone_id'] = $this->session->data['guest']['zone_id'];
		$data['payment_country'] = $this->session->data['guest']['country'];
		$data['payment_country_id'] = $this->session->data['guest']['country_id'];
		$data['payment_address_format'] = $this->session->data['guest']['address_format'];

		if (isset($this->session->data['payment_method']['title'])) {
			$data['payment_method'] = $this->session->data['payment_method']['title'];
		} else {
			$data['payment_method'] = '';
		}

		$product_data = array();

		foreach ($this->cart->getProducts() as $product) {
      		$option_data = array();

      		foreach ($product['option'] as $option) {
        		$option_data[] = array(
					'product_option_value_id' => $option['product_option_value_id'],
          			'name'                    => $option['name'],
          			'value'                   => $option['value'],
		  			'prefix'                  => $option['prefix']
        		);
      		}

      		$product_data[] = array(
        		'product_id' => $product['product_id'],
				'name'       => $product['name'],
        		'model'      => $product['model'],
        		'option'     => $option_data,
				'download'   => $product['download'],
				'quantity'   => $product['quantity'],
				'price'      => $product['price'],
        		'total'      => $product['total'],
				'tax'        => $this->tax->getRate($product['tax_class_id'])
      		);
    	}

		$data['products'] = $product_data;
		$data['totals'] = $total_data;
		$data['comment'] = $this->session->data['comment'];
		$data['total'] = $total;
		$data['language_id'] = $this->config->get('config_language_id');
		$data['currency_id'] = $this->currency->getId();
		$data['currency'] = $this->currency->getCode();
		$data['value'] = $this->currency->getValue($this->currency->getCode());

		if (isset($this->session->data['coupon'])) {
			$this->load->model('checkout/coupon');

			$coupon = $this->model_checkout_coupon->getCoupon($this->session->data['coupon']);

			if ($coupon) {
				$data['coupon_id'] = $coupon['coupon_id'];
			} else {
				$data['coupon_id'] = 0;
			}
		} else {
			$data['coupon_id'] = 0;
		}

		$data['ip'] = $this->request->server['REMOTE_ADDR'];

		$this->load->model('checkout/order');

		$this->session->data['order_id'] = $this->model_checkout_order->create($data);

		$this->document->breadcrumbs = array();

      	$this->document->breadcrumbs[] = array(
        	'href'      => HTTP_SERVER . 'index.php?route=common/home',
        	'text'      => $this->language->get('text_home'),
        	'separator' => FALSE
      	);

      	$this->document->breadcrumbs[] = array(
        	'href'      => HTTP_SERVER . 'index.php?route=checkout/cart',
        	'text'      => $this->language->get('text_basket'),
        	'separator' => $this->language->get('text_separator')
      	);

      	$this->document->breadcrumbs[] = array(
        	'href'      => HTTPS_SERVER . 'index.php?route=checkout/guest_step_1',
        	'text'      => $this->language->get('text_guest_step_1'),
        	'separator' => $this->language->get('text_separator')
      	);

      	$this->document->breadcrumbs[] = array(
        	'href'      => HTTPS_SERVER . 'index.php?route=checkout/guest_step_2',
        	'text'      => $this->language->get('text_guest_step_2'),
        	'separator' => $this->language->get('text_separator')
      	);

      	$this->document->breadcrumbs[] = array(
        	'href'      => HTTPS_SERVER . 'index.php?route=checkout/guest_step_3',
        	'text'      => $this->language->get('text_confirm'),
        	'separator' => $this->language->get('text_separator')
      	);

    	$this->data['heading_title'] = $this->language->get('heading_title');

    	$this->data['text_shipping_address'] = $this->language->get('text_shipping_address');
    	$this->data['text_shipping_method'] = $this->language->get('text_shipping_method');
    	$this->data['text_payment_address'] = $this->language->get('text_payment_address');
    	$this->data['text_payment_method'] = $this->language->get('text_payment_method');
    	$this->data['text_comment'] = $this->language->get('text_comment');
    	$this->data['text_change'] = $this->language->get('text_change');

		$this->data['column_product'] = $this->language->get('column_product');
    	$this->data['column_model'] = $this->language->get('column_model');
    	$this->data['column_quantity'] = $this->language->get('column_quantity');
    	$this->data['column_price'] = $this->language->get('column_price');
    	$this->data['column_total'] = $this->language->get('column_total');

		if (isset($this->error['warning'])) {
    		$this->data['error_warning'] = $this->error['warning'];
		} else {
			$this->data['error_warning'] = '';
		}

		if (isset($this->session->data['success'])) {
			$this->data['success'] = $this->session->data['success'];

    		unset($this->session->data['success']);
		} else {
			$this->data['success'] = '';
		}

		if ($this->cart->hasShipping()) {
			if (isset($this->session->data['guest']['shipping'])) {
				$shipping_address = $this->session->data['guest']['shipping'];
			} else {
				$shipping_address = $this->session->data['guest'];
			}

			if ($shipping_address['address_format']) {
      			$format = $shipping_address['address_format'];
    		} else {
				$format = '{firstname} {lastname}' . "\n" . '{company}' . "\n" . '{address_1}' . "\n" . '{address_2}' . "\n" . '{city} {postcode}' . "\n" . '{zone}' . "\n" . '{country}';
			}

    		$find = array(
	  			'{firstname}',
	  			'{lastname}',
	  			'{company}',
      			'{address_1}',
      			'{address_2}',
     			'{city}',
      			'{postcode}',
      			'{zone}',
				'{zone_code}',
      			'{country}'
			);

			$replace = array(
	  			'firstname' => $shipping_address['firstname'],
	  			'lastname'  => $shipping_address['lastname'],
	  			'company'   => $shipping_address['company'],
      			'address_1' => $shipping_address['address_1'],
      			'address_2' => $shipping_address['address_2'],
      			'city'      => $shipping_address['city'],
      			'postcode'  => $shipping_address['postcode'],
      			'zone'      => $shipping_address['zone'],
				'zone_code' => $shipping_address['zone_code'],
      			'country'   => $shipping_address['country']
			);

			$this->data['shipping_address'] = str_replace(array("\r\n", "\r", "\n"), '
', preg_replace(array("/\s\s+/", "/\r\r+/", "/\n\n+/"), '
', trim(str_replace($find, $replace, $format))));
		} else {
			$this->data['shipping_address'] = '';
		}

		if (isset($this->session->data['shipping_method']['title'])) {
			$this->data['shipping_method'] = $this->session->data['shipping_method']['title'];
		} else {
			$this->data['shipping_method'] = '';
		}

    	$this->data['checkout_shipping'] = HTTPS_SERVER . 'index.php?route=checkout/guest_step_2';

    	$this->data['checkout_shipping_address'] = HTTPS_SERVER . 'index.php?route=checkout/guest_step_1';

		$payment_address = $this->session->data['guest'];

		if ($payment_address) {
			if ($payment_address['address_format']) {
      			$format = $payment_address['address_format'];
    		} else {
				$format = '{firstname} {lastname}' . "\n" . '{company}' . "\n" . '{address_1}' . "\n" . '{address_2}' . "\n" . '{city} {postcode}' . "\n" . '{zone}' . "\n" . '{country}';
			}

    		$find = array(
	  			'{firstname}',
	  			'{lastname}',
	  			'{company}',
      			'{address_1}',
      			'{address_2}',
     			'{city}',
      			'{postcode}',
      			'{zone}',
				'{zone_code}',
      			'{country}'
			);

			$replace = array(
	  			'firstname' => $payment_address['firstname'],
	  			'lastname'  => $payment_address['lastname'],
	  			'company'   => $payment_address['company'],
      			'address_1' => $payment_address['address_1'],
      			'address_2' => $payment_address['address_2'],
      			'city'      => $payment_address['city'],
      			'postcode'  => $payment_address['postcode'],
      			'zone'      => $payment_address['zone'],
				'zone_code' => $payment_address['zone_code'],
      			'country'   => $payment_address['country']
			);

			$this->data['payment_address'] = str_replace(array("\r\n", "\r", "\n"), '
', preg_replace(array("/\s\s+/", "/\r\r+/", "/\n\n+/"), '
', trim(str_replace($find, $replace, $format))));
		} else {
			$this->data['payment_address'] = '';
		}

		if (isset($this->session->data['payment_method']['title'])) {
			$this->data['payment_method'] = $this->session->data['payment_method']['title'];
		} else {
			$this->data['payment_method'] = '';
		}

    	$this->data['checkout_payment'] = HTTPS_SERVER . 'index.php?route=checkout/guest_step_2';

    	$this->data['checkout_payment_address'] = HTTPS_SERVER . 'index.php?route=checkout/guest_step_1';

    	$this->data['products'] = array();

    	foreach ($this->cart->getProducts() as $product) {
      		$option_data = array();

      		foreach ($product['option'] as $option) {
        		$option_data[] = array(
          			'name'  => $option['name'],
          			'value' => $option['value']
        		);
      		}

      		$this->data['products'][] = array(
				'product_id' => $product['product_id'],
        		'name'       => $product['name'],
        		'model'      => $product['model'],
        		'option'     => $option_data,
        		'quantity'   => $product['quantity'],
				'tax'        => $this->tax->getRate($product['tax_class_id']),
        		'price'      => $this->currency->format($product['price']),
        		'total'      => $this->currency->format($product['total']),
				'href'       => HTTP_SERVER . 'index.php?route=product/product&product_id=' . $product['product_id']
      		);
    	}

		$this->data['totals'] = $total_data;

		$this->data['comment'] = nl2br($this->session->data['comment']);

		if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/checkout/confirm.tpl')) {
			$this->template = $this->config->get('config_template') . '/template/checkout/confirm.tpl';
		} else {
			$this->template = 'default/template/checkout/confirm.tpl';
		}

		$this->children = array(
			'common/column_right',
			'common/footer',
			'common/column_left',
			'common/header',
			'payment/' . $this->session->data['payment_method']['id']
		);

		$this->response->setOutput($this->render(TRUE), $this->config->get('config_compression'));
	}
}
?>


text:
#if !defined(BOOST_SPIRIT_CONFIG_HPP)
#define BOOST_SPIRIT_CONFIG_HPP

#include <boost/config.hpp>

///////////////////////////////////////////////////////////////////////////////
//
//  Compiler check:
//
//  Historically, Spirit supported a lot of compilers, including (to some
//  extent) poorly conforming compilers such as VC6. Spirit v1.6.x will be
//  the last release that will support older poorly conforming compilers.
//  Starting from Spirit v1.8.0, ill conforming compilers will not be
//  supported. If you are still using one of these older compilers, you can
//  still use Spirit v1.6.x.
//
//  The reason why Spirit v1.6.x worked on old non-conforming compilers is
//  that the authors laboriously took the trouble of searching for
//  workarounds to make these compilers happy. The process takes a lot of
//  time and energy, especially when one encounters the dreaded ICE or
//  "Internal Compiler Error". Sometimes searching for a single workaround
//  takes days or even weeks. Sometimes, there are no known workarounds. This
//  stifles progress a lot. And, as the library gets more progressive and
//  takes on more advanced C++ techniques, the difficulty is escalated to
//  even new heights.
//
//  Spirit v1.6.x will still be supported. Maintenance and bug fixes will
//  still be applied. There will still be active development for the back-
//  porting of new features introduced in Spirit v1.8.0 (and Spirit 1.9.0)
//  to lesser able compilers; hopefully, fueled by contributions from the
//  community. For instance, there is already a working AST tree back-port
//  for VC6 and VC7 by Peder Holt.
//
//  If you got here somehow, your compiler is known to be poorly conforming
//  WRT ANSI/ISO C++ standard. Library implementers get a bad reputation when
//  someone attempts to compile the code on a non-conforming compiler. She'll
//  be confronted with tons of compiler errors when she tries to compile the
//  library. Such errors will somehow make less informed users conclude that
//  the code is poorly written. It's better for the user to see a message
//  "sorry, this code has not been ported to your compiler yet", than to see
//  pages and pages of compiler error messages.
//
/////////////////////////////////////////////////////////////////////////////////
#if     (defined(BOOST_MSVC) && (BOOST_MSVC < 1310))                            \
    ||  (defined(BOOST_BORLANDC) && (BOOST_BORLANDC <= 0x570))                      \
    ||  (defined(__GNUC__) && (__GNUC__ < 3))                                   \
    ||  (defined(__GNUC__) && (__GNUC__ == 3) && (__GNUC_MINOR__ < 1))
# error "Compiler not supported. See note in <boost/spirit/core/config.hpp>"
#else
// Pass... Compiler supported.
#endif

#endif


text:
<?php
/**
 * @author Guillaume Luchet <guillaume@geelweb.org>
 * @license http://opensource.org/licenses/bsd-license.php BSD License
 * @package StackIt
 */

namespace StackIt;

/**
 * StackIt is a library to push data in stack then to pop them latter for mass
 * procesing
 *
 * <code>
 * StackIt\Stack::setConfig('config.ini');
 * StackIt\Stack::push('my-stack', array('foo'));
 * </code>
 *
 * @example examples/config.ini A basic ini config file
 * @example examples/stack_push.php Push to the stack
 * @example examples/daemon.php Process the stack
 *
 * @authorGuillaume Luchet <guillaume@geelweb.org>
 * @license http://opensource.org/licenses/bsd-license.php BSD License
 * @package StackIt
 */
class Stack
{
    /**
     *
     */
    private static $_config = array();

    /**
     *
     */
    private static $_instance = array();

    /**
     * Load the KVS objectaccording to the given stack ID
     *
     * @param string $id The stack ID
     * @static
     * @access public
     * @return void
     */
    public static function factory($id)
    {
        if (!isset(self::$_instance[$id])) {
            if (!isset(self::$_config[$id])) {
                throw new Exception('Stack configuration not found');
            }

            if (!isset(self::$_config[$id]['kvs'])) {
                throw new Exception('kvs entry not found in stack config');
            }

            $class = self::$_config[$id]['kvs'];
            if (!class_exists($class)) {
                $class = "StackIt\Kvs\\$class";
                if (!class_exists($class)) {
                    throw new Exception('KVS ' . $class . ' not found');
                }
            }

            self::$_instance[$id] = $class::singleton(self::$_config[$id]);
        }

        return self::$_instance[$id];
    }

    /**
     * setConfig
     *
     * @param mixed $config
     * @static
     * @access public
     * @return void
     */
    public static function setConfig($config)
    {
        if (is_array($config)) {
            self::$_config = $config;
        } elseif(is_string($config) && file_exists($config)) {
            self::$_config = parse_ini_file($config, true);
        }
    }

    /**
     * getConfig
     *
     * @param mixed $id
     * @static
     * @access public
     * @return void
     */
    public static function getConfig($id=null)
    {
        return $id !== null && isset(self::$_config[$id]) ? self::$_config[$id] : self::$_config;
    }

    /**
     * getStacksIds
     *
     * @static
     * @access public
     * @return void
     */
    public static function getStacksIds()
    {
        return array_keys(self::$_config);
    }

    /**
     * push
     *
     * @param mixed $id
     * @param mixed $value
     * @static
     * @access public
     * @return void
     */
    public static function push($id, $value)
    {
        self::factory($id)->push($id, $value);
    }

    /**
     * process
     *
     * @param mixed $id
     * @static
     * @access public
     * @return void
     */
    public static function process($id)
    {
        $items = self::factory($id)->pop($id);

        if (!isset(self::$_config[$id]['processor'])) {
            throw new Exception('processor entry not found in stack config');
        }

        $class = self::$_config[$id]['processor'];
        if (!class_exists($class)) {
            $class = "StackIt\Processor\\$class";
            if (!class_exists($class)) {
                throw new Exception('Processor ' . $class . ' not found');
            }
        }
        $proc = $class::singleton(self::$_config[$id]);
        return $proc->process($items);
    }
}


text:
from neutronclient._i18n import _
from neutronclient.neutron import v2_0 as neutronV20

class ListVip(neutronV20.ListCommand):
    """List vips that belong to a given tenant."""

    resource = 'vip'
    list_columns = ['id', 'name', 'algorithm', 'address', 'protocol',
                    'admin_state_up', 'status']
    pagination_support = True
    sorting_support = True

class ShowVip(neutronV20.ShowCommand):
    """Show information of a given vip."""

    resource = 'vip'

class CreateVip(neutronV20.CreateCommand):
    """Create a vip."""

    resource = 'vip'

    def add_known_arguments(self, parser):
        parser.add_argument(
            'pool_id', metavar='POOL',
            help=_('Pool ID or name this vip belongs to.'))
        parser.add_argument(
            '--address',
            help=_('IP address of the vip.'))
        parser.add_argument(
            '--admin-state-down',
            dest='admin_state', action='store_false',
            help=_('Set admin state up to false.'))
        parser.add_argument(
            '--connection-limit',
            help=_('The maximum number of connections per second allowed for '
                   'the vip. Positive integer or -1 for unlimited (default).'))
        parser.add_argument(
            '--description',
            help=_('Description of the vip.'))
        parser.add_argument(
            '--name',
            required=True,
            help=_('Name of the vip.'))
        parser.add_argument(
            '--protocol-port',
            required=True,
            help=_('TCP port on which to listen for client traffic that is '
                   'associated with the vip address.'))
        parser.add_argument(
            '--protocol',
            required=True, choices=['TCP', 'HTTP', 'HTTPS'],
            help=_('Protocol for balancing.'))
        parser.add_argument(
            '--subnet-id', metavar='SUBNET',
            required=True,
            help=_('The subnet on which to allocate the vip address.'))

    def args2body(self, parsed_args):
        _pool_id = neutronV20.find_resourceid_by_name_or_id(
            self.get_client(), 'pool', parsed_args.pool_id)
        _subnet_id = neutronV20.find_resourceid_by_name_or_id(
            self.get_client(), 'subnet', parsed_args.subnet_id)

        body = {'pool_id': _pool_id,
                'admin_state_up': parsed_args.admin_state,
                'subnet_id': _subnet_id}
        neutronV20.update_dict(parsed_args, body,
                               ['address', 'connection_limit', 'description',
                                'name', 'protocol_port', 'protocol',
                                'tenant_id'])
        return {self.resource: body}

class UpdateVip(neutronV20.UpdateCommand):
    """Update a given vip."""

    resource = 'vip'

class DeleteVip(neutronV20.DeleteCommand):
    """Delete a given vip."""

    resource = 'vip'


text:
#include <kernel.h>
#include <device.h>
#include <init.h>
#include <fsl_common.h>
#include <fsl_clock.h>

#define PERIPH_CLK_PLLFLLSEL	(1)
#define PERIPH_CLK_OSCERCLK	(2)
#define PERIPH_CLK_MCGIRCLK	(3)

#define RUNM_RUN		(0)
#define RUNM_VLPR		(2)
#define RUNM_HSRUN		(3)

#define CLOCK_NODEID(clk) \
	DT_CHILD(DT_INST(0, nxp_kinetis_sim), clk)

#define CLOCK_DIVIDER(clk) \
	DT_PROP_OR(CLOCK_NODEID(clk), clock_div, 1) - 1

static const osc_config_t osc_config = {
	.freq = CONFIG_OSC_XTAL0_FREQ,
	.capLoad = 0,

#if defined(CONFIG_OSC_EXTERNAL)
	.workMode = kOSC_ModeExt,
#elif defined(CONFIG_OSC_LOW_POWER)
	.workMode = kOSC_ModeOscLowPower,
#elif defined(CONFIG_OSC_HIGH_GAIN)
	.workMode = kOSC_ModeOscHighGain,
#else
#error "An oscillator mode must be defined"
#endif

	.oscerConfig = {
		.enableMode = kOSC_ErClkEnable,
#if (defined(FSL_FEATURE_OSC_HAS_EXT_REF_CLOCK_DIVIDER) && \
	FSL_FEATURE_OSC_HAS_EXT_REF_CLOCK_DIVIDER)
		.erclkDiv = 0U,
#endif
	},
};

static const mcg_pll_config_t pll0_config = {
	.enableMode = 0U,
	.prdiv = CONFIG_MCG_PRDIV0,
	.vdiv = CONFIG_MCG_VDIV0,
};

static const sim_clock_config_t sim_config = {
	.pllFllSel = DT_PROP(DT_INST(0, nxp_kinetis_sim), pllfll_select),
	.er32kSrc = DT_PROP(DT_INST(0, nxp_kinetis_sim), er32k_select),
	.clkdiv1 = SIM_CLKDIV1_OUTDIV1(CLOCK_DIVIDER(core_clk)) |
		   SIM_CLKDIV1_OUTDIV2(CLOCK_DIVIDER(bus_clk)) |
		   SIM_CLKDIV1_OUTDIV3(CLOCK_DIVIDER(flexbus_clk)) |
		   SIM_CLKDIV1_OUTDIV4(CLOCK_DIVIDER(flash_clk)),
	/* Divide PLL output frequency by 2 for peripherals */
	.pllFllDiv = (1),
	.pllFllFrac = (0),
};

static ALWAYS_INLINE void clk_init(void)
{
	CLOCK_SetSimSafeDivs();

	CLOCK_InitOsc0(&osc_config);
	CLOCK_SetXtal0Freq(CONFIG_OSC_XTAL0_FREQ);

	CLOCK_BootToPeeMode(kMCG_OscselOsc, kMCG_PllClkSelPll0, &pll0_config);

	CLOCK_SetInternalRefClkConfig(kMCG_IrclkEnable, kMCG_IrcSlow,
				      CONFIG_MCG_FCRDIV);

	CLOCK_SetSimConfig(&sim_config);

#if CONFIG_UART_MCUX_LPUART
	CLOCK_SetLpuartClock(PERIPH_CLK_PLLFLLSEL);
#endif

#if CONFIG_USB_KINETIS
	CLOCK_EnableUsbfs0Clock(kCLOCK_UsbSrcPll0, 120000000UL);
#endif
}

static int k8x_init(const struct device *arg)
{
	ARG_UNUSED(arg);

	unsigned int old_level; /* old interrupt lock level */
#if !defined(CONFIG_ARM_MPU)
	uint32_t temp_reg;
#endif /* !CONFIG_ARM_MPU */

	/* Disable interrupts */
	old_level = irq_lock();

	/* release I/O power hold to allow normal run state */
	PMC->REGSC |= PMC_REGSC_ACKISO_MASK;

#if !defined(CONFIG_ARM_MPU)
	/*
	 * Disable memory protection and clear slave port errors.
	 * Note that the K8x does not implement the optional ARMv7-M memory
	 * protection unit (MPU), specified by the architecture (PMSAv7), in the
	 * Cortex-M4 core.  Instead, the processor includes its own MPU module.
	 */
	temp_reg = SYSMPU->CESR;
	temp_reg &= ~SYSMPU_CESR_VLD_MASK;
	temp_reg |= SYSMPU_CESR_SPERR_MASK;
	SYSMPU->CESR = temp_reg;
#endif /* !CONFIG_ARM_MPU */

	/* Initialize system clocks and PLL */
	clk_init();

	/*
	 * Install default handler that simply resets the CPU if
	 * configured in the kernel, NOP otherwise
	 */
	NMI_INIT();

	/* Restore interrupt state */
	irq_unlock(old_level);

	return 0;
}

SYS_INIT(k8x_init, PRE_KERNEL_1, 0);


text:
namespace System.Net {
    using System.Net.Sockets;
    using System.Collections;
    using System.Runtime.InteropServices;
    using System.Security.Permissions;
    using System.Globalization;

    // More sophisticated password cache that stores multiple
    // name-password pairs and associates these with host/realm
    /// <devdoc>
    ///    <para>Provides storage for multiple credentials.</para>
    /// </devdoc>
    public class CredentialCache : ICredentials, ICredentialsByHost, IEnumerable {

    // fields

        private Hashtable cache = new Hashtable();
        private Hashtable cacheForHosts = new Hashtable();
        internal int m_version;

        private int m_NumbDefaultCredInCache = 0;

        // [thread token optimization] The resulting counter of default credential resided in the cache.
        internal bool IsDefaultInCache {
            get {
                return m_NumbDefaultCredInCache != 0;
            }
        }

    // constructors

        /// <devdoc>
        ///    <para>
        ///       Initializes a new instance of the <see cref='System.Net.CredentialCache'/> class.
        ///    </para>
        /// </devdoc>
        public CredentialCache() {
        }

    // properties

    // methods

        /// <devdoc>
        /// <para>Adds a <see cref='System.Net.NetworkCredential'/>
        /// instance to the credential cache.</para>
        /// </devdoc>
        // UEUE
        public void Add(Uri uriPrefix, string authType, NetworkCredential cred) {
            //
            // parameter validation
            //
            if (uriPrefix==null) {
                throw new ArgumentNullException("uriPrefix");
            }
            if (authType==null) {
                throw new ArgumentNullException("authType");
            }
            if ((cred is SystemNetworkCredential)
#if !FEATURE_PAL
                && !((string.Compare(authType, NtlmClient.AuthType, StringComparison.OrdinalIgnoreCase)==0)
                     || (DigestClient.WDigestAvailable && (string.Compare(authType, DigestClient.AuthType, StringComparison.OrdinalIgnoreCase)==0))
                     || (string.Compare(authType, KerberosClient.AuthType, StringComparison.OrdinalIgnoreCase)==0)
                     || (string.Compare(authType, NegotiateClient.AuthType, StringComparison.OrdinalIgnoreCase)==0))
#endif
                ) {
                throw new ArgumentException(SR.GetString(SR.net_nodefaultcreds, authType), "authType");
            }

            ++m_version;

            CredentialKey key = new CredentialKey(uriPrefix, authType);

            GlobalLog.Print("CredentialCache::Add() Adding key:[" + key.ToString() + "], cred:[" + cred.Domain + "],[" + cred.UserName + "]");

            cache.Add(key, cred);
            if (cred is SystemNetworkCredential) {
                ++m_NumbDefaultCredInCache;
            }
        }

        public void Add(string host, int port, string authenticationType, NetworkCredential credential) {
            //
            // parameter validation
            //
            if (host==null) {
                throw new ArgumentNullException("host");
            }

            if (authenticationType==null) {
                throw new ArgumentNullException("authenticationType");
            }

            if (host.Length == 0) {
                throw new ArgumentException(SR.GetString(SR.net_emptystringcall,"host"));
            }

            if (port < 0) {
                throw new ArgumentOutOfRangeException("port");
            }
            if ((credential is SystemNetworkCredential)
#if !FEATURE_PAL
                && !((string.Compare(authenticationType, NtlmClient.AuthType, StringComparison.OrdinalIgnoreCase)==0)
                     || (DigestClient.WDigestAvailable && (string.Compare(authenticationType, DigestClient.AuthType, StringComparison.OrdinalIgnoreCase)==0))
                     || (string.Compare(authenticationType, KerberosClient.AuthType, StringComparison.OrdinalIgnoreCase)==0)
                     || (string.Compare(authenticationType, NegotiateClient.AuthType, StringComparison.OrdinalIgnoreCase)==0))
#endif
                ) {
                throw new ArgumentException(SR.GetString(SR.net_nodefaultcreds, authenticationType), "authenticationType");
            }

            ++m_version;

            CredentialHostKey key = new CredentialHostKey(host,port, authenticationType);

            GlobalLog.Print("CredentialCache::Add() Adding key:[" + key.ToString() + "], cred:[" + credential.Domain + "],[" + credential.UserName + "]");

            cacheForHosts.Add(key, credential);
            if (credential is SystemNetworkCredential) {
                ++m_NumbDefaultCredInCache;
            }
        }

        /// <devdoc>
        /// <para>Removes a <see cref='System.Net.NetworkCredential'/>
        /// instance from the credential cache.</para>
        /// </devdoc>
        public void Remove(Uri uriPrefix, string authType) {
            if (uriPrefix==null || authType==null) {
                // these couldn't possibly have been inserted into
                // the cache because of the test in Add()
                return;
            }

            ++m_version;

            CredentialKey key = new CredentialKey(uriPrefix, authType);

            GlobalLog.Print("CredentialCache::Remove() Removing key:[" + key.ToString() + "]");

            if (cache[key] is SystemNetworkCredential) {
                --m_NumbDefaultCredInCache;
            }
            cache.Remove(key);
        }

        public void Remove(string host, int port, string authenticationType) {
            if (host==null || authenticationType==null) {
                // these couldn't possibly have been inserted into
                // the cache because of the test in Add()
                return;
            }

            if (port < 0) {
                return;
            }

            ++m_version;

            CredentialHostKey key = new CredentialHostKey(host, port, authenticationType);

            GlobalLog.Print("CredentialCache::Remove() Removing key:[" + key.ToString() + "]");

            if (cacheForHosts[key] is SystemNetworkCredential) {
                --m_NumbDefaultCredInCache;
            }
            cacheForHosts.Remove(key);
        }

        /// <devdoc>
        ///    <para>
        ///       Returns the <see cref='System.Net.NetworkCredential'/>
        ///       instance associated with the supplied Uri and
        ///       authentication type.
        ///    </para>
        /// </devdoc>
        public NetworkCredential GetCredential(Uri uriPrefix, string authType) {
            if (uriPrefix==null)
                throw new ArgumentNullException("uriPrefix");
            if (authType==null)
                throw new ArgumentNullException("authType");

            GlobalLog.Print("CredentialCache::GetCredential(uriPrefix=\"" + uriPrefix + "\", authType=\"" + authType + "\")");

            int longestMatchPrefix = -1;
            NetworkCredential mostSpecificMatch = null;
            IDictionaryEnumerator credEnum = cache.GetEnumerator();

            //
            // Enumerate through every credential in the cache
            //

            while (credEnum.MoveNext()) {

                CredentialKey key = (CredentialKey)credEnum.Key;

                //
                // Determine if this credential is applicable to the current Uri/AuthType
                //

                if (key.Match(uriPrefix, authType)) {

                    int prefixLen = key.UriPrefixLength;

                    //
                    // Check if the match is better than the current-most-specific match
                    //

                    if (prefixLen > longestMatchPrefix) {

                        //
                        // Yes-- update the information about currently preferred match
                        //

                        longestMatchPrefix = prefixLen;
                        mostSpecificMatch = (NetworkCredential)credEnum.Value;
                    }
                }
            }

            GlobalLog.Print("CredentialCache::GetCredential returning " + ((mostSpecificMatch==null)?"null":"(" + mostSpecificMatch.UserName + ":" + mostSpecificMatch.Domain + ")"));

            return mostSpecificMatch;
        }

        public NetworkCredential GetCredential(string host, int port, string authenticationType) {
            if (host==null) {
                throw new ArgumentNullException("host");
            }
            if (authenticationType==null){
                throw new ArgumentNullException("authenticationType");
            }
            if (host.Length == 0) {
                throw new ArgumentException(SR.GetString(SR.net_emptystringcall, "host"));
            }
            if (port < 0) {
                throw new ArgumentOutOfRangeException("port");
            }

            GlobalLog.Print("CredentialCache::GetCredential(host=\"" + host + ":" + port.ToString() +"\", authenticationType=\"" + authenticationType + "\")");

            NetworkCredential match = null;

            IDictionaryEnumerator credEnum = cacheForHosts.GetEnumerator();

            //
            // Enumerate through every credential in the cache
            //

            while (credEnum.MoveNext()) {

                CredentialHostKey key = (CredentialHostKey)credEnum.Key;

                //
                // Determine if this credential is applicable to the current Uri/AuthType
                //

                if (key.Match(host, port, authenticationType)) {

                        match = (NetworkCredential)credEnum.Value;
                }
            }

            GlobalLog.Print("CredentialCache::GetCredential returning " + ((match==null)?"null":"(" + match.UserName + ":" + match.Domain + ")"));
            return match;
        }

        /// <devdoc>
        ///    [To be supplied]
        /// </devdoc>

        //
        // IEnumerable interface
        //

        public IEnumerator GetEnumerator() {
            return new CredentialEnumerator(this, cache ,cacheForHosts, m_version);
        }

        /// <devdoc>
        ///    <para>
        ///       Gets
        ///       the default system credentials from the <see cref='System.Net.CredentialCache'/>.
        ///    </para>
        /// </devdoc>
        public static ICredentials DefaultCredentials {
            get {
                //This check will not allow to use local user credentials at will.
                //Hence the username will not be exposed to the network
                new EnvironmentPermission(EnvironmentPermissionAccess.Read, "USERNAME").Demand();
                return SystemNetworkCredential.defaultCredential;
            }
        }

        public static NetworkCredential DefaultNetworkCredentials {
            get {
                //This check will not allow to use local user credentials at will.
                //Hence the username will not be exposed to the network
                new EnvironmentPermission(EnvironmentPermissionAccess.Read, "USERNAME").Demand();
                return SystemNetworkCredential.defaultCredential;
            }
        }

        private class CredentialEnumerator : IEnumerator {

        // fields

            private CredentialCache m_cache;
            private ICredentials[] m_array;
            private int m_index = -1;
            private int m_version;

        // constructors

            internal CredentialEnumerator(CredentialCache cache, Hashtable table, Hashtable hostTable, int version) {
                m_cache = cache;
                m_array = new ICredentials[table.Count + hostTable.Count];
                table.Values.CopyTo(m_array, 0);
                hostTable.Values.CopyTo(m_array, table.Count);
                m_version = version;
            }

        // IEnumerator interface

        // properties

            object IEnumerator.Current {
                get {
                    if (m_index < 0 || m_index >= m_array.Length) {
                        throw new InvalidOperationException(SR.GetString(SR.InvalidOperation_EnumOpCantHappen));
                    }
                    if (m_version != m_cache.m_version) {
                        throw new InvalidOperationException(SR.GetString(SR.InvalidOperation_EnumFailedVersion));
                    }
                    return m_array[m_index];
                }
            }

        // methods

            bool IEnumerator.MoveNext() {
                if (m_version != m_cache.m_version) {
                    throw new InvalidOperationException(SR.GetString(SR.InvalidOperation_EnumFailedVersion));
                }
                if (++m_index < m_array.Length) {
                    return true;
                }
                m_index = m_array.Length;
                return false;
            }

            void IEnumerator.Reset() {
                m_index = -1;
            }

        } // class CredentialEnumerator

    } // class CredentialCache

    // Abstraction for credentials in password-based
    // authentication schemes (basic, digest, NTLM, Kerberos)
    // Note this is not applicable to public-key based
    // systems such as SSL client authentication
    // "Password" here may be the clear text password or it
    // could be a one-way hash that is sufficient to
    // authenticate, as in HTTP/1.1 digest.

    //
    // Object representing default credentials
    //
    internal class SystemNetworkCredential : NetworkCredential {
        internal static readonly SystemNetworkCredential defaultCredential = new SystemNetworkCredential();

        // We want reference equality to work.  Making this private is a good way to guarantee that.
        private SystemNetworkCredential() :
            base(string.Empty, string.Empty, string.Empty) {
        }
    }

    internal class CredentialHostKey {

        internal string Host;
        internal string AuthenticationType;
        internal int Port;

        internal CredentialHostKey(string host, int port, string authenticationType) {
            Host = host;
            Port = port;
            AuthenticationType = authenticationType;
        }

        internal bool Match(string host, int port, string authenticationType) {
            if (host==null || authenticationType==null) {
                return false;
            }
            //
            // If the protocols dont match this credential
            // is not applicable for the given Uri
            //
            if (string.Compare(authenticationType, AuthenticationType, StringComparison.OrdinalIgnoreCase) != 0) {
                return false;
            }
            if (string.Compare(Host, host, StringComparison.OrdinalIgnoreCase ) != 0) {
                return false;
            }
            if (port != Port) {
                return false;
            }

            GlobalLog.Print("CredentialKey::Match(" + Host.ToString() + ":" + Port.ToString() +" & " + host.ToString() + ":" + port.ToString() + ")");
            return true;
        }

        private int m_HashCode = 0;
        private bool m_ComputedHashCode = false;
        public override int GetHashCode() {
            if (!m_ComputedHashCode) {
                //
                // compute HashCode on demand
                //

                m_HashCode = AuthenticationType.ToUpperInvariant().GetHashCode() + Host.ToUpperInvariant().GetHashCode() + Port.GetHashCode();
                m_ComputedHashCode = true;
            }
            return m_HashCode;
        }

        public override bool Equals(object comparand) {
            CredentialHostKey comparedCredentialKey = comparand as CredentialHostKey;

            if (comparand==null) {
                //
                // this covers also the compared==null case
                //
                return false;
            }

            bool equals =
                (string.Compare(AuthenticationType, comparedCredentialKey.AuthenticationType, StringComparison.OrdinalIgnoreCase ) == 0) &&
                (string.Compare(Host, comparedCredentialKey.Host, StringComparison.OrdinalIgnoreCase ) == 0) &&
                Port == comparedCredentialKey.Port;

            GlobalLog.Print("CredentialKey::Equals(" + ToString() + ", " + comparedCredentialKey.ToString() + ") returns " + equals.ToString());

            return equals;
        }

        public override string ToString() {
            return "[" + Host.Length.ToString(NumberFormatInfo.InvariantInfo) + "]:" + Host + ":" + Port.ToString(NumberFormatInfo.InvariantInfo) + ":" + ValidationHelper.ToString(AuthenticationType);
        }

    } // class CredentialKey

    internal class CredentialKey {

        internal Uri UriPrefix;
        internal int UriPrefixLength = -1;
        internal string AuthenticationType;

        internal CredentialKey(Uri uriPrefix, string authenticationType) {
            UriPrefix = uriPrefix;
            UriPrefixLength = UriPrefix.ToString().Length;
            AuthenticationType = authenticationType;
        }

        internal bool Match(Uri uri, string authenticationType) {
            if (uri==null || authenticationType==null) {
                return false;
            }
            //
            // If the protocols dont match this credential
            // is not applicable for the given Uri
            //
            if (string.Compare(authenticationType, AuthenticationType, StringComparison.OrdinalIgnoreCase) != 0) {
                return false;
            }

            GlobalLog.Print("CredentialKey::Match(" + UriPrefix.ToString() + " & " + uri.ToString() + ")");

            return IsPrefix(uri, UriPrefix);
        }
        //
        // IsPrefix (Uri)
        //
        //  Determines whether <prefixUri> is a prefix of this URI. A prefix
        //  match is defined as:
        //
        //      scheme match
        //      + host match
        //      + port match, if any
        //      + <prefix> path is a prefix of <URI> path, if any
        //
        // Returns:
        //  True if <prefixUri> is a prefix of this URI
        //
        internal bool IsPrefix(Uri uri, Uri prefixUri) {

            if (prefixUri.Scheme != uri.Scheme || prefixUri.Host != uri.Host || prefixUri.Port != uri.Port)
                return false;

            int prefixLen = prefixUri.AbsolutePath.LastIndexOf('/');
            if (prefixLen > uri.AbsolutePath.LastIndexOf('/'))
                return false;

            return String.Compare(uri.AbsolutePath, 0, prefixUri.AbsolutePath, 0, prefixLen, StringComparison.OrdinalIgnoreCase ) == 0;
        }

        private int m_HashCode = 0;
        private bool m_ComputedHashCode = false;
        public override int GetHashCode() {
            if (!m_ComputedHashCode) {
                //
                // compute HashCode on demand
                //

                m_HashCode = AuthenticationType.ToUpperInvariant().GetHashCode() + UriPrefixLength + UriPrefix.GetHashCode();
                m_ComputedHashCode = true;
            }
            return m_HashCode;
        }

        public override bool Equals(object comparand) {
            CredentialKey comparedCredentialKey = comparand as CredentialKey;

            if (comparand==null) {
                //
                // this covers also the compared==null case
                //
                return false;
            }

            bool equals =
                (string.Compare(AuthenticationType, comparedCredentialKey.AuthenticationType, StringComparison.OrdinalIgnoreCase ) == 0) &&
                UriPrefix.Equals(comparedCredentialKey.UriPrefix);

            GlobalLog.Print("CredentialKey::Equals(" + ToString() + ", " + comparedCredentialKey.ToString() + ") returns " + equals.ToString());

            return equals;
        }

        public override string ToString() {
            return "[" + UriPrefixLength.ToString(NumberFormatInfo.InvariantInfo) + "]:" + ValidationHelper.ToString(UriPrefix) + ":" + ValidationHelper.ToString(AuthenticationType);
        }

    } // class CredentialKey

} // namespace System.Net


text:
package redis_test

import (
	"time"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	"gopkg.in/redis.v5"
)

var _ = Describe("pool", func() {
	var client *redis.Client

	BeforeEach(func() {
		client = redis.NewClient(redisOptions())
		Expect(client.FlushDb().Err()).NotTo(HaveOccurred())
	})

	AfterEach(func() {
		Expect(client.Close()).NotTo(HaveOccurred())
	})

	It("respects max size", func() {
		perform(1000, func(id int) {
			val, err := client.Ping().Result()
			Expect(err).NotTo(HaveOccurred())
			Expect(val).To(Equal("PONG"))
		})

		pool := client.Pool()
		Expect(pool.Len()).To(BeNumerically("<=", 10))
		Expect(pool.FreeLen()).To(BeNumerically("<=", 10))
		Expect(pool.Len()).To(Equal(pool.FreeLen()))
	})

	It("respects max size on multi", func() {
		perform(1000, func(id int) {
			var ping *redis.StatusCmd

			err := client.Watch(func(tx *redis.Tx) error {
				cmds, err := tx.Pipelined(func(pipe *redis.Pipeline) error {
					ping = pipe.Ping()
					return nil
				})
				Expect(err).NotTo(HaveOccurred())
				Expect(cmds).To(HaveLen(1))
				return err
			})
			Expect(err).NotTo(HaveOccurred())

			Expect(ping.Err()).NotTo(HaveOccurred())
			Expect(ping.Val()).To(Equal("PONG"))
		})

		pool := client.Pool()
		Expect(pool.Len()).To(BeNumerically("<=", 10))
		Expect(pool.FreeLen()).To(BeNumerically("<=", 10))
		Expect(pool.Len()).To(Equal(pool.FreeLen()))
	})

	It("respects max size on pipelines", func() {
		perform(1000, func(id int) {
			pipe := client.Pipeline()
			ping := pipe.Ping()
			cmds, err := pipe.Exec()
			Expect(err).NotTo(HaveOccurred())
			Expect(cmds).To(HaveLen(1))
			Expect(ping.Err()).NotTo(HaveOccurred())
			Expect(ping.Val()).To(Equal("PONG"))
			Expect(pipe.Close()).NotTo(HaveOccurred())
		})

		pool := client.Pool()
		Expect(pool.Len()).To(BeNumerically("<=", 10))
		Expect(pool.FreeLen()).To(BeNumerically("<=", 10))
		Expect(pool.Len()).To(Equal(pool.FreeLen()))
	})

	It("respects max size on pubsub", func() {
		connPool := client.Pool()

		perform(1000, func(id int) {
			pubsub, err := client.Subscribe()
			Expect(err).NotTo(HaveOccurred())
			Expect(pubsub.Close()).NotTo(HaveOccurred())
		})

		Expect(connPool.Len()).To(Equal(connPool.FreeLen()))
		Expect(connPool.Len()).To(BeNumerically("<=", 10))
	})

	It("removes broken connections", func() {
		cn, _, err := client.Pool().Get()
		Expect(err).NotTo(HaveOccurred())
		cn.SetNetConn(&badConn{})
		Expect(client.Pool().Put(cn)).NotTo(HaveOccurred())

		err = client.Ping().Err()
		Expect(err).To(MatchError("bad connection"))

		val, err := client.Ping().Result()
		Expect(err).NotTo(HaveOccurred())
		Expect(val).To(Equal("PONG"))

		pool := client.Pool()
		Expect(pool.Len()).To(Equal(1))
		Expect(pool.FreeLen()).To(Equal(1))

		stats := pool.Stats()
		Expect(stats.Requests).To(Equal(uint32(4)))
		Expect(stats.Hits).To(Equal(uint32(2)))
		Expect(stats.Timeouts).To(Equal(uint32(0)))
	})

	It("reuses connections", func() {
		for i := 0; i < 100; i++ {
			val, err := client.Ping().Result()
			Expect(err).NotTo(HaveOccurred())
			Expect(val).To(Equal("PONG"))
		}

		pool := client.Pool()
		Expect(pool.Len()).To(Equal(1))
		Expect(pool.FreeLen()).To(Equal(1))

		stats := pool.Stats()
		Expect(stats.Requests).To(Equal(uint32(101)))
		Expect(stats.Hits).To(Equal(uint32(100)))
		Expect(stats.Timeouts).To(Equal(uint32(0)))
	})

	It("removes idle connections", func() {
		stats := client.PoolStats()
		Expect(stats).To(Equal(&redis.PoolStats{
			Requests:   1,
			Hits:       0,
			Timeouts:   0,
			TotalConns: 1,
			FreeConns:  1,
		}))

		time.Sleep(2 * time.Second)

		stats = client.PoolStats()
		Expect(stats).To(Equal(&redis.PoolStats{
			Requests:   1,
			Hits:       0,
			Timeouts:   0,
			TotalConns: 0,
			FreeConns:  0,
		}))
	})
})


text:
<?php defined('SYSPATH') OR die('No direct script access.');

/**
*
*/

class Kohana_MetrixResponse
{
	/**
     * Singleton instsance itself
     *
     * @var array
     * @access protected
     */
	protected static $_instance = null;

	/**
     * Instance of GearmanJob
     *
     * @var object
     * @access protected
     */
	protected $_job = null;

	/**
     * Instance of GearmanJob
     *
     * @var object
     * @access protected
     */
	protected $_response = null;

	/**
     * Last mxml file has generate by job
     *
     * @var string
     * @access private
     */
	private $_lastmxml = '';

	protected $_lastRecordId = null;

	private $_loaded = false;

	private $_workname;
	/**
	 * @method getInstance
	 * @access public
	 *
	 * getInstance method to create sinle instance of the respionse
	 * this method will be manipulate with the gearman server at the jobs
	 *
	 *
	 * @param   array    $data Set initial data to send to Gearman server at job
	 * @return  (void)
	 */
	public static function getInstance( array $sendData )
	{
		if( is_null(self::$_instance) )
		{
			self::$_instance = new self($sendData);
		}

		return self::$_instance;
	}

	/**
	 * @method __construct
	 * @access private
	 *
	 * self instance constructor
	 *
	 *
	 * @param   (array)  $data Set initial data to send to Gearman server at job
	 * @return  (void)
	 */
	private function __construct( array $data )
	{

		$this->_loaded = false;
		$config = Kohana::$config->load('gearman')->get('client');

		$this->_lastmxml = $data['params']['filename'].".mxml";
		$this->_workname = $data['params']['workname'];

		$this->_lastRecordId = $this->createNewJobTask();
		if( $this->isLoaded() )
		{
			$data['params']['recordId'] = $this->_lastRecordId;

			$client = new GearmanClient();
			$client->addServer($config['servers'], (int)$config['port']);

			$client->doBackground("send_metrix_calc", json_encode($data));
		}

		/*
		$client->setCreatedCallback(array($this, 'createTask'));
		$client->setDataCallback(array($this, 'editDataTask'));
		$client->setCompleteCallback(array($this, 'completeTask'));
		$client->setStatusCallback(array($this, 'statusTask'));

		$job_handle = $client->addTask("send_metrix_calc", json_encode($data));

		$client->runTasks();
		*/
	}

	public function isLoaded()
	{
		return $this->_loaded;
	}

	public function createNewJobTask()
	{
		$model = MongoModel::factory("Workers");
		$model->selectDB();

		$model->timestart = new MongoDate();
		$model->lastmxml = $this->_lastmxml;
		$model->status = 1;
		$model->workname = $this->_workname;

		$model->save();
		$this->_loaded = true;

		return Arr::objectToArray($model->get('_id')->{'$id'});
	}

	public function createTask(GearmanTask $task)
	{

	}

	public function editDataTask(GearmanTask $task)
	{

	}

	public function completeTask(GearmanTask $task)
	{

	}

	public function statusTask(GearmanTask $task)
	{

	}

	public function getBody()
	{
		$this->response['lastId'] = $this->_lastRecordId;

		return $this->response;
	}

}


text:
import React from 'react';
// eslint-disable-next-line deprecate/import
import { mount } from 'enzyme';
import { act } from 'react-dom/test-utils';
import maplibregl from 'maplibre-gl';
import {
    BeaconEvent,
    getBeaconInfoIdentifier,
    RelationType,
    MatrixEvent,
    EventType,
} from 'matrix-js-sdk/src/matrix';
import { Relations } from 'matrix-js-sdk/src/models/relations';
import { M_BEACON } from 'matrix-js-sdk/src/@types/beacon';

import MBeaconBody from '../../../../src/components/views/messages/MBeaconBody';
import {
    getMockClientWithEventEmitter,
    makeBeaconEvent,
    makeBeaconInfoEvent,
    makeRoomWithBeacons,
    makeRoomWithStateEvents,
} from '../../../test-utils';
import { RoomPermalinkCreator } from '../../../../src/utils/permalinks/Permalinks';
import { MediaEventHelper } from '../../../../src/utils/MediaEventHelper';
import MatrixClientContext from '../../../../src/contexts/MatrixClientContext';
import Modal from '../../../../src/Modal';
import { TILE_SERVER_WK_KEY } from '../../../../src/utils/WellKnownUtils';
import { MapError } from '../../../../src/components/views/location/MapError';
import * as mapUtilHooks from '../../../../src/utils/location/useMap';
import { LocationShareError } from '../../../../src/utils/location';

describe('<MBeaconBody />', () => {
    // 14.03.2022 16:15
    const now = 1647270879403;
    // stable date for snapshots
    jest.spyOn(global.Date, 'now').mockReturnValue(now);
    const roomId = '!room:server';
    const aliceId = '@alice:server';

    const mockMap = new maplibregl.Map();
    const mockMarker = new maplibregl.Marker();

    const mockClient = getMockClientWithEventEmitter({
        getClientWellKnown: jest.fn().mockReturnValue({
            [TILE_SERVER_WK_KEY.name]: { map_style_url: 'maps.com' },
        }),
        getUserId: jest.fn().mockReturnValue(aliceId),
        getRoom: jest.fn(),
        redactEvent: jest.fn(),
    });

    const defaultEvent = makeBeaconInfoEvent(aliceId,
        roomId,
        { isLive: true },
        '$alice-room1-1',
    );

    const defaultProps = {
        mxEvent: defaultEvent,
        highlights: [],
        highlightLink: '',
        onHeightChanged: jest.fn(),
        onMessageAllowed: jest.fn(),
        // we dont use these and they pollute the snapshots
        permalinkCreator: {} as unknown as RoomPermalinkCreator,
        mediaEventHelper: {} as unknown as MediaEventHelper,
    };

    const getComponent = (props = {}) =>
        mount(<MBeaconBody {...defaultProps} {...props} />, {
            wrappingComponent: MatrixClientContext.Provider,
            wrappingComponentProps: { value: mockClient },
        });

    const modalSpy = jest.spyOn(Modal, 'createDialog').mockReturnValue(undefined);

    beforeAll(() => {
        maplibregl.AttributionControl = jest.fn();
    });

    beforeEach(() => {
        jest.clearAllMocks();
    });

    const testBeaconStatuses = () => {
        it('renders stopped beacon UI for an explicitly stopped beacon', () => {
            const beaconInfoEvent = makeBeaconInfoEvent(aliceId,
                roomId,
                { isLive: false },
                '$alice-room1-1',
            );
            makeRoomWithStateEvents([beaconInfoEvent], { roomId, mockClient });
            const component = getComponent({ mxEvent: beaconInfoEvent });
            expect(component.text()).toEqual("Live location ended");
        });

        it('renders stopped beacon UI for an expired beacon', () => {
            const beaconInfoEvent = makeBeaconInfoEvent(aliceId,
                roomId,
                // puts this beacons live period in the past
                { isLive: true, timestamp: now - 600000, timeout: 500 },
                '$alice-room1-1',
            );
            makeRoomWithStateEvents([beaconInfoEvent], { roomId, mockClient });
            const component = getComponent({ mxEvent: beaconInfoEvent });
            expect(component.text()).toEqual("Live location ended");
        });

        it('renders loading beacon UI for a beacon that has not started yet', () => {
            const beaconInfoEvent = makeBeaconInfoEvent(
                aliceId,
                roomId,
                // puts this beacons start timestamp in the future
                { isLive: true, timestamp: now + 60000, timeout: 500 },
                '$alice-room1-1',
            );
            makeRoomWithStateEvents([beaconInfoEvent], { roomId, mockClient });
            const component = getComponent({ mxEvent: beaconInfoEvent });
            expect(component.text()).toEqual("Loading live location...");
        });

        it('does not open maximised map when on click when beacon is stopped', () => {
            const beaconInfoEvent = makeBeaconInfoEvent(aliceId,
                roomId,
                // puts this beacons live period in the past
                { isLive: true, timestamp: now - 600000, timeout: 500 },
                '$alice-room1-1',
            );
            makeRoomWithStateEvents([beaconInfoEvent], { roomId, mockClient });
            const component = getComponent({ mxEvent: beaconInfoEvent });
            act(() => {
                component.find('.mx_MBeaconBody_map').at(0).simulate('click');
            });

            expect(modalSpy).not.toHaveBeenCalled();
        });

        it('renders stopped UI when a beacon event is not the latest beacon for a user', () => {
            const aliceBeaconInfo1 = makeBeaconInfoEvent(
                aliceId,
                roomId,
                // this one is a little older
                { isLive: true, timestamp: now - 500 },
                '$alice-room1-1',
            );
            aliceBeaconInfo1.event.origin_server_ts = now - 500;
            const aliceBeaconInfo2 = makeBeaconInfoEvent(
                aliceId,
                roomId,
                { isLive: true },
                '$alice-room1-2',
            );

            makeRoomWithStateEvents([aliceBeaconInfo1, aliceBeaconInfo2], { roomId, mockClient });

            const component = getComponent({ mxEvent: aliceBeaconInfo1 });
            // beacon1 has been superceded by beacon2
            expect(component.text()).toEqual("Live location ended");
        });

        it('renders stopped UI when a beacon event is replaced', () => {
            const aliceBeaconInfo1 = makeBeaconInfoEvent(
                aliceId,
                roomId,
                // this one is a little older
                { isLive: true, timestamp: now - 500 },
                '$alice-room1-1',
            );
            aliceBeaconInfo1.event.origin_server_ts = now - 500;
            const aliceBeaconInfo2 = makeBeaconInfoEvent(
                aliceId,
                roomId,
                { isLive: true },
                '$alice-room1-2',
            );

            const room = makeRoomWithStateEvents([aliceBeaconInfo1], { roomId, mockClient });
            const component = getComponent({ mxEvent: aliceBeaconInfo1 });

            const beaconInstance = room.currentState.beacons.get(getBeaconInfoIdentifier(aliceBeaconInfo1));
            // update alice's beacon with a new edition
            // beacon instance emits
            act(() => {
                beaconInstance.update(aliceBeaconInfo2);
            });

            component.setProps({});

            // beacon1 has been superceded by beacon2
            expect(component.text()).toEqual("Live location ended");
        });
    };

    testBeaconStatuses();

    describe('on liveness change', () => {
        it('renders stopped UI when a beacon stops being live', () => {
            const aliceBeaconInfo = makeBeaconInfoEvent(
                aliceId,
                roomId,
                { isLive: true },
                '$alice-room1-1',
            );

            const room = makeRoomWithStateEvents([aliceBeaconInfo], { roomId, mockClient });
            const beaconInstance = room.currentState.beacons.get(getBeaconInfoIdentifier(aliceBeaconInfo));
            const component = getComponent({ mxEvent: aliceBeaconInfo });

            act(() => {
                // @ts-ignore cheat to force beacon to not live
                beaconInstance._isLive = false;
                beaconInstance.emit(BeaconEvent.LivenessChange, false, beaconInstance);
            });

            component.setProps({});

            // stopped UI
            expect(component.text()).toEqual("Live location ended");
        });
    });

    describe('latestLocationState', () => {
        const aliceBeaconInfo = makeBeaconInfoEvent(
            aliceId,
            roomId,
            { isLive: true },
            '$alice-room1-1',
        );

        const location1 = makeBeaconEvent(
            aliceId, { beaconInfoId: aliceBeaconInfo.getId(), geoUri: 'geo:51,41', timestamp: now + 1 },
        );
        const location2 = makeBeaconEvent(
            aliceId, { beaconInfoId: aliceBeaconInfo.getId(), geoUri: 'geo:52,42', timestamp: now + 10000 },
        );

        it('renders a live beacon without a location correctly', () => {
            makeRoomWithStateEvents([aliceBeaconInfo], { roomId, mockClient });
            const component = getComponent({ mxEvent: aliceBeaconInfo });

            expect(component.text()).toEqual("Loading live location...");
        });

        it('does nothing on click when a beacon has no location', () => {
            makeRoomWithStateEvents([aliceBeaconInfo], { roomId, mockClient });
            const component = getComponent({ mxEvent: aliceBeaconInfo });

            act(() => {
                component.find('.mx_MBeaconBody_map').at(0).simulate('click');
            });

            expect(modalSpy).not.toHaveBeenCalled();
        });

        it('renders a live beacon with a location correctly', () => {
            const room = makeRoomWithStateEvents([aliceBeaconInfo], { roomId, mockClient });
            const beaconInstance = room.currentState.beacons.get(getBeaconInfoIdentifier(aliceBeaconInfo));
            beaconInstance.addLocations([location1]);
            const component = getComponent({ mxEvent: aliceBeaconInfo });

            expect(component.find('Map').length).toBeTruthy;
        });

        it('opens maximised map view on click when beacon has a live location', () => {
            const room = makeRoomWithStateEvents([aliceBeaconInfo], { roomId, mockClient });
            const beaconInstance = room.currentState.beacons.get(getBeaconInfoIdentifier(aliceBeaconInfo));
            beaconInstance.addLocations([location1]);
            const component = getComponent({ mxEvent: aliceBeaconInfo });

            act(() => {
                component.find('Map').simulate('click');
            });

            // opens modal
            expect(modalSpy).toHaveBeenCalled();
        });

        it('does nothing on click when a beacon has no location', () => {
            makeRoomWithStateEvents([aliceBeaconInfo], { roomId, mockClient });
            const component = getComponent({ mxEvent: aliceBeaconInfo });

            act(() => {
                component.find('.mx_MBeaconBody_map').at(0).simulate('click');
            });

            expect(modalSpy).not.toHaveBeenCalled();
        });

        it('renders a live beacon with a location correctly', () => {
            const room = makeRoomWithStateEvents([aliceBeaconInfo], { roomId, mockClient });
            const beaconInstance = room.currentState.beacons.get(getBeaconInfoIdentifier(aliceBeaconInfo));
            beaconInstance.addLocations([location1]);
            const component = getComponent({ mxEvent: aliceBeaconInfo });

            expect(component.find('Map').length).toBeTruthy;
        });

        it('opens maximised map view on click when beacon has a live location', () => {
            const room = makeRoomWithStateEvents([aliceBeaconInfo], { roomId, mockClient });
            const beaconInstance = room.currentState.beacons.get(getBeaconInfoIdentifier(aliceBeaconInfo));
            beaconInstance.addLocations([location1]);
            const component = getComponent({ mxEvent: aliceBeaconInfo });

            act(() => {
                component.find('Map').simulate('click');
            });

            // opens modal
            expect(modalSpy).toHaveBeenCalled();
        });

        it('updates latest location', () => {
            const room = makeRoomWithStateEvents([aliceBeaconInfo], { roomId, mockClient });
            const component = getComponent({ mxEvent: aliceBeaconInfo });

            const beaconInstance = room.currentState.beacons.get(getBeaconInfoIdentifier(aliceBeaconInfo));
            act(() => {
                beaconInstance.addLocations([location1]);
                component.setProps({});
            });

            expect(mockMap.setCenter).toHaveBeenCalledWith({ lat: 51, lon: 41 });
            expect(mockMarker.setLngLat).toHaveBeenCalledWith({ lat: 51, lon: 41 });

            act(() => {
                beaconInstance.addLocations([location2]);
                component.setProps({});
            });

            expect(mockMap.setCenter).toHaveBeenCalledWith({ lat: 52, lon: 42 });
            expect(mockMarker.setLngLat).toHaveBeenCalledWith({ lat: 52, lon: 42 });
        });
    });

    describe('redaction', () => {
        const makeEvents = (): {
            beaconInfoEvent: MatrixEvent;
            location1: MatrixEvent;
            location2: MatrixEvent;
        } => {
            const beaconInfoEvent = makeBeaconInfoEvent(
                aliceId,
                roomId,
                { isLive: true },
                '$alice-room1-1',
            );

            const location1 = makeBeaconEvent(
                aliceId, { beaconInfoId: beaconInfoEvent.getId(), geoUri: 'geo:51,41', timestamp: now + 1 },
                roomId,
            );
            location1.event.event_id = '1';
            const location2 = makeBeaconEvent(
                aliceId, { beaconInfoId: beaconInfoEvent.getId(), geoUri: 'geo:52,42', timestamp: now + 10000 },
                roomId,
            );
            location2.event.event_id = '2';
            return { beaconInfoEvent, location1, location2 };
        };

        const redactionEvent = new MatrixEvent({ type: EventType.RoomRedaction, content: { reason: 'test reason' } });

        const setupRoomWithBeacon = (beaconInfoEvent, locationEvents: MatrixEvent[] = []) => {
            const room = makeRoomWithStateEvents([beaconInfoEvent], { roomId, mockClient });
            const beaconInstance = room.currentState.beacons.get(getBeaconInfoIdentifier(beaconInfoEvent));
            beaconInstance.addLocations(locationEvents);
        };
        const mockGetRelationsForEvent = (locationEvents: MatrixEvent[] = []) => {
            const relations = new Relations(RelationType.Reference, M_BEACON.name, mockClient);
            jest.spyOn(relations, 'getRelations').mockReturnValue(locationEvents);

            const getRelationsForEvent = jest.fn().mockReturnValue(relations);

            return getRelationsForEvent;
        };

        it('does nothing when getRelationsForEvent is falsy', () => {
            const { beaconInfoEvent, location1, location2 } = makeEvents();
            setupRoomWithBeacon(beaconInfoEvent, [location1, location2]);

            getComponent({ mxEvent: beaconInfoEvent });

            act(() => {
                beaconInfoEvent.makeRedacted(redactionEvent);
            });

            // no error, no redactions
            expect(mockClient.redactEvent).not.toHaveBeenCalled();
        });

        it('cleans up redaction listener on unmount', () => {
            const { beaconInfoEvent, location1, location2 } = makeEvents();
            setupRoomWithBeacon(beaconInfoEvent, [location1, location2]);
            const removeListenerSpy = jest.spyOn(beaconInfoEvent, 'removeListener');

            const component = getComponent({ mxEvent: beaconInfoEvent });

            act(() => {
                component.unmount();
            });

            expect(removeListenerSpy).toHaveBeenCalled();
        });

        it('does nothing when beacon has no related locations', async () => {
            const { beaconInfoEvent } = makeEvents();
            // no locations
            setupRoomWithBeacon(beaconInfoEvent, []);
            const getRelationsForEvent = await mockGetRelationsForEvent();

            getComponent({ mxEvent: beaconInfoEvent, getRelationsForEvent });

            act(() => {
                beaconInfoEvent.makeRedacted(redactionEvent);
            });

            expect(getRelationsForEvent).toHaveBeenCalledWith(
                beaconInfoEvent.getId(), RelationType.Reference, M_BEACON.name,
            );
            expect(mockClient.redactEvent).not.toHaveBeenCalled();
        });

        it('redacts related locations on beacon redaction', async () => {
            const { beaconInfoEvent, location1, location2 } = makeEvents();
            setupRoomWithBeacon(beaconInfoEvent, [location1, location2]);

            const getRelationsForEvent = await mockGetRelationsForEvent([location1, location2]);

            getComponent({ mxEvent: beaconInfoEvent, getRelationsForEvent });

            act(() => {
                beaconInfoEvent.makeRedacted(redactionEvent);
            });

            expect(getRelationsForEvent).toHaveBeenCalledWith(
                beaconInfoEvent.getId(), RelationType.Reference, M_BEACON.name,
            );
            expect(mockClient.redactEvent).toHaveBeenCalledTimes(2);
            expect(mockClient.redactEvent).toHaveBeenCalledWith(
                roomId,
                location1.getId(),
                undefined,
                { reason: 'test reason' },
            );
            expect(mockClient.redactEvent).toHaveBeenCalledWith(
                roomId,
                location2.getId(),
                undefined,
                { reason: 'test reason' },
            );
        });
    });

    describe('when map display is not configured', () => {
        beforeEach(() => {
            // mock map utils to raise MapStyleUrlNotConfigured error
            jest.spyOn(mapUtilHooks, 'useMap').mockImplementation(
                ({ onError }) => {
                    onError(new Error(LocationShareError.MapStyleUrlNotConfigured));
                    return mockMap;
                });
        });

        it('renders maps unavailable error for a live beacon with location', () => {
            const beaconInfoEvent = makeBeaconInfoEvent(aliceId,
                roomId,
                { isLive: true },
                '$alice-room1-1',
            );
            const location1 = makeBeaconEvent(
                aliceId, { beaconInfoId: beaconInfoEvent.getId(), geoUri: 'geo:51,41', timestamp: now + 1 },
            );

            makeRoomWithBeacons(roomId, mockClient, [beaconInfoEvent], [location1]);

            const component = getComponent({ mxEvent: beaconInfoEvent });
            expect(component.find(MapError)).toMatchSnapshot();
        });

        // test that statuses display as expected with a map display error
        testBeaconStatuses();
    });
});


text:
import TypeStyle = require('../src/TypeStyle');
var ss = TypeStyle.StyleSheet;
var r = TypeStyle.Rule;

export = new ss()
.addRules
([
    new r('.bar-button')
        .extend('.foo-button')
        .fontSize('200px')
]);


text:
using System;

namespace NFeEletronica.Consulta
{
    public class CartaCorrecao
    {
        public CartaCorrecao(String numeroLote, String notaChaveAcesso, String correcao, String cnpj, String codigoUF)
        {
            NumeroLote = numeroLote;
            NotaChaveAcesso = notaChaveAcesso;
            Correcao = correcao;
            CNPJ = cnpj;
            CodigoUF = codigoUF;
        }

        public String NumeroLote { get; private set; }
        public String NotaChaveAcesso { get; private set; }
        public String Correcao { get; private set; }
        public String CNPJ { get; private set; }
        public String CodigoUF { get; private set; }
        public DateTime DataEvento { get; set; }
    }
}


text:
package com.planet_ink.coffee_mud.MOBS;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.*;

public class Sheep extends StdMOB
{
	@Override
	public String ID()
	{
		return "Sheep";
	}

	public Sheep()
	{
		super();
		username="a sheep";
		setDescription("It looks warm in that big fluffy coat of wool, but is nervous that you are so close.");
		setDisplayText("A sheep has wandered away from the herd.");
		CMLib.factions().setAlignment(this,Faction.Align.NEUTRAL);
		setMoney(0);
		setWimpHitPoint(0);

		basePhyStats().setDamage(1);
		basePhyStats().setSpeed(1.0);
		basePhyStats().setAbility(0);
		basePhyStats().setLevel(1);
		basePhyStats().setArmor(90);
		baseCharStats().setMyRace(CMClass.getRace("Sheep"));
		baseCharStats().getMyRace().startRacing(this,false);

		baseState.setHitPoints(CMLib.dice().roll(basePhyStats().level(),20,basePhyStats().level()));

		recoverMaxState();
		resetToMaxState();
		recoverPhyStats();
		recoverCharStats();
	}

	@Override
	public String description()
	{
		if(fetchEffect("TemporaryImmunity")!=null)
			return L("The poor scrawny creature looks cold");
		return super.description();
	}

	@Override
	public String displayText(MOB viewer)
	{
		final Room R=location();
		if(R!=null)
		{
			if(R.fetchInhabitants("$sheep$").size()>1)
				return L("A sheep is following the herd around.");
		}
		return super.displayText(viewer);
	}

}


text:
module Pagers
  module Extensions
    module ActionView
      module Base
        extend ActiveSupport::Concern

        def page_path(number, options={})
          if number == 1
            number = nil
          end
          url_for request.query_parameters.merge(page: number)
        end

        def paginate(collection, options={})
          links = (options[:links] || Pagers.configuration.links)
          if collection.total_pages >= links
            middle = (links / 2).ceil
            if collection.current_page > (collection.total_pages - middle)
              starts_at = (collection.total_pages - links + 1)
              ends_at = collection.total_pages
            elsif collection.current_page <= middle
              starts_at = 1
              ends_at = links
            else
              starts_at = (collection.current_page - middle)
              ends_at = (collection.current_page + middle)
            end
          else
            starts_at = 1
            ends_at = collection.total_pages
          end
          pages = Range.new(starts_at, ends_at)
          less_pages = (starts_at > 1)
          more_pages = (ends_at < collection.total_pages)
          render(
            'pagers/main',
            collection: collection,
            pages: pages,
            less_pages: less_pages,
            more_pages: more_pages,
            options: options
          )
        end

      end
    end
  end
end


text:
import { ActionType, ContextModule, OwnerType } from "@artsy/cohesion"
import { fireEvent } from "@testing-library/react-native"
import { defaultEnvironment } from "app/relay/createEnvironment"
import { GlobalStore } from "app/store/GlobalStore"
import { flushPromiseQueue } from "app/tests/flushPromiseQueue"
import { renderWithWrappers } from "app/tests/renderWithWrappers"
import { useTracking } from "react-tracking"
import { createMockEnvironment, MockPayloadGenerator } from "relay-test-utils/"
import { updateConsignSubmission } from "../../mutations"
import { STEPS, SubmitSWAArtworkFlow } from "../SubmitArtwork"
import { ContactInformationQueryRenderer } from "./ContactInformation"

jest.mock("../../mutations/updateConsignSubmissionMutation", () => ({
  updateConsignSubmission: jest.fn().mockResolvedValue("54321"),
}))

const updateConsignSubmissionMock = updateConsignSubmission as jest.Mock

jest.unmock("react-relay")

describe("ContactInformationForm", () => {
  afterEach(() => {
    GlobalStore.actions.artworkSubmission.submission.resetSessionState()
  })
  const mockEnvironment = defaultEnvironment as ReturnType<typeof createMockEnvironment>
  const handlePressTest = jest.fn()
  const TestRenderer = ({ isLastStep = true }: { isLastStep?: boolean }) => (
    <ContactInformationQueryRenderer handlePress={handlePressTest} isLastStep={isLastStep} />
  )

  it("renders without throwing an error", () => {
    renderWithWrappers(
      <ContactInformationQueryRenderer handlePress={() => console.log("do nothing")} isLastStep />
    )
  })

  it("renders Form instructions", () => {
    const { findByText } = renderWithWrappers(<TestRenderer />)

    expect(
      findByText("We will only use these details to contact you regarding your submission.")
    ).toBeTruthy()
  })

  it("Happy path: User can submit information", async () => {
    GlobalStore.actions.artworkSubmission.submission.setSubmissionId(mockFormDataForSubmission.id)

    const { queryByText, getByText, getByPlaceholderText } = renderWithWrappers(
      <SubmitSWAArtworkFlow
        navigation={jest.fn() as any}
        stepsInOrder={[STEPS.ContactInformation]}
      />
    )

    await flushPromiseQueue()

    mockEnvironment.mock.resolveMostRecentOperation((operation) =>
      MockPayloadGenerator.generate(operation, {
        Me: () => ({
          ...mockQueryData,
        }),
      })
    )

    await flushPromiseQueue()

    const inputs = {
      nameInput: getByPlaceholderText("Your full name"),
      emailInput: getByPlaceholderText("Your email address"),
      phoneInput: getByPlaceholderText("(000) 000-0000"),
    }

    expect(inputs.nameInput).toBeTruthy()
    expect(inputs.nameInput).toHaveProp("value", "Angela")

    expect(inputs.emailInput).toBeTruthy()
    expect(inputs.emailInput).toHaveProp("value", "a@a.aaa")

    expect(inputs.phoneInput).toBeTruthy()
    expect(inputs.phoneInput).toHaveProp("value", "(202) 555-0174")

    expect(queryByText("Submit Artwork")).toBeTruthy()

    fireEvent.press(getByText("Submit Artwork"))

    await flushPromiseQueue()

    expect(updateConsignSubmissionMock).toHaveBeenCalled()
    expect(updateConsignSubmissionMock).toHaveBeenCalledWith(
      expect.objectContaining(mockFormDataForSubmission)
    )
  })

  it("Keeps Submit button deactivated when something is missing/not properly filled out. Gets enabled if everything is filled out.", async () => {
    const { getByText, getByPlaceholderText } = renderWithWrappers(<TestRenderer />)
    updateConsignSubmissionMock.mockResolvedValue("adsfasd")
    mockEnvironment.mock.resolveMostRecentOperation((operation) =>
      MockPayloadGenerator.generate(operation, {
        Me: () => ({
          ...mockQueryDataInfoMissing,
        }),
      })
    )
    const inputs = {
      nameInput: getByPlaceholderText("Your full name"),
      emailInput: getByPlaceholderText("Your email address"),
      phoneInput: getByPlaceholderText("(000) 000-0000"),
    }

    const submitButton = getByText("Submit Artwork")

    await flushPromiseQueue()

    expect(submitButton).toBeDisabled()

    fireEvent.changeText(inputs.nameInput, "Angelika")
    fireEvent.changeText(inputs.emailInput, "aa@aa.aaa")
    fireEvent.changeText(inputs.phoneInput, "2025550155")

    await flushPromiseQueue()

    expect(submitButton).not.toBeDisabled()
  })

  describe("validation", () => {
    it("displays error message for name", async () => {
      const { getByText, getByPlaceholderText } = renderWithWrappers(<TestRenderer />)
      mockEnvironment.mock.resolveMostRecentOperation((operation) =>
        MockPayloadGenerator.generate(operation, {
          Me: () => ({
            ...mockQueryData,
          }),
        })
      )

      await flushPromiseQueue()

      const inputs = {
        nameInput: getByPlaceholderText("Your full name"),
        emailInput: getByPlaceholderText("Your email address"),
      }

      fireEvent.changeText(inputs.nameInput, "a")
      fireEvent.changeText(inputs.emailInput, "aa")

      await flushPromiseQueue()

      expect(getByText("Please enter your full name.")).toBeTruthy()
    })

    it("displays error message for email address", async () => {
      const { getByText, getByPlaceholderText } = renderWithWrappers(<TestRenderer />)
      mockEnvironment.mock.resolveMostRecentOperation((operation) =>
        MockPayloadGenerator.generate(operation, {
          Me: () => ({
            ...mockQueryData,
          }),
        })
      )

      await flushPromiseQueue()

      const inputs = {
        emailInput: getByPlaceholderText("Your email address"),
        phoneInput: getByPlaceholderText("(000) 000-0000"),
      }

      fireEvent.changeText(inputs.emailInput, "aa")
      fireEvent.changeText(inputs.phoneInput, "12")

      await flushPromiseQueue()

      expect(getByText("Please enter a valid email address.")).toBeTruthy()
    })

    it("displays error message for phone number", async () => {
      const { getByText, getByPlaceholderText } = renderWithWrappers(<TestRenderer />)
      mockEnvironment.mock.resolveMostRecentOperation((operation) =>
        MockPayloadGenerator.generate(operation, {
          Me: () => ({
            ...mockQueryData,
          }),
        })
      )

      await flushPromiseQueue()

      const inputs = {
        emailInput: getByPlaceholderText("Your email address"),
        phoneInput: getByPlaceholderText("(000) 000-0000"),
      }

      fireEvent.changeText(inputs.phoneInput, "12")
      fireEvent.changeText(inputs.emailInput, "aa")

      await flushPromiseQueue()

      expect(getByText("Please enter a valid phone number.")).toBeTruthy()
    })
  })

  describe("analytics", () => {
    let trackEvent: (data: Partial<{}>) => void
    beforeEach(() => {
      trackEvent = useTracking().trackEvent
      GlobalStore.actions.auth.setState({
        userID: "my-id",
      })
    })

    afterEach(() => {
      GlobalStore.actions.auth.setState({
        userID: null,
      })
    })

    it("tracks uploadPhotosCompleted event on save", async () => {
      const { getByTestId } = renderWithWrappers(
        <SubmitSWAArtworkFlow
          navigation={jest.fn() as any}
          stepsInOrder={[
            STEPS.ContactInformation,
            // Add a random step so that STEPS.ContactInformation is not the last step
            STEPS.ArtworkDetails,
          ]}
        />
      )

      await flushPromiseQueue()

      mockEnvironment.mock.resolveMostRecentOperation((operation) =>
        MockPayloadGenerator.generate(operation, {
          Me: () => ({
            ...mockQueryData,
          }),
        })
      )

      await flushPromiseQueue()

      const contactInfoCTA = getByTestId("Submission_ContactInformation_Button")
      fireEvent.press(contactInfoCTA)

      await flushPromiseQueue()

      mockEnvironment.mock.resolveMostRecentOperation((operation) => {
        return MockPayloadGenerator.generate(operation, {
          consignmentSubmission: () => ({
            internalID: "54321",
          }),
        })
      })

      await flushPromiseQueue()

      expect(trackEvent).toHaveBeenCalled()
      expect(trackEvent).toHaveBeenCalledWith({
        action: ActionType.contactInformationCompleted,
        context_owner_type: OwnerType.consignmentFlow,
        context_module: ContextModule.contactInformation,
        submission_id: '<mock-value-for-field-"internalID">',
        user_email: mockQueryData.email,
        user_id: "my-id",
      })
    })
  })
})

export const mockQueryData: any = {
  name: "Angela",
  email: "a@a.aaa",
  phoneNumber: { isValid: true, originalNumber: "+1 (202) 555-0174" },
}

export const mockQueryDataInfoMissing: any = {
  name: "",
  email: "",
  phoneNumber: { isValid: false, originalNumber: "" },
}

export const mockFormDataForSubmission: any = {
  id: "54321",
  userEmail: "a@a.aaa",
  userName: "Angela",
  userPhone: "+1 (202) 555-0174",
}


text:
import serial
import time
import requests
import json
import sys

job_limit = 16
max_job = job_limit - 1

token = sys.argv[1]
url = 'https://circleci.com/api/v1.1/recent-builds?circle-token=' + token + '&limit=' + str(job_limit) + '&offset=0'
request_frequency = 15

s = None

color_map = {
              "running": "ltblue|breathe",
              "success": "green",
             "finished": "green",
                "fixed": "seafoam",
               "failed": "red",
             "no_tests": "gray",
              "retried": "yellow",
             "timedout": "yellow|blink",
             "canceled": "gray",
              "not_run": "gray",
               "queued": "purple|breathe",
            "scheduled": "purple",
          "not_running": "pink",
              "missing": "gray",
               "spacer": "black",
         "masterfailed": "red|blink",
          "masterfixed": "green|blink",
  "infrastructure_fail": "pink"
}

inter_command_delay = 0.02

def command(cmd_text):
  s.write((cmd_text + '|').encode())
  time.sleep(inter_command_delay)

def get_color_cmd(color_cmd_text):
  if color_cmd_text is None:
    return "missing"
  else:
    return color_map.get(color_cmd_text, "black")

def color_command(color_cmd_text):
  color_cmd = get_color_cmd(color_cmd_text)
  command(color_cmd)

def color_command3(color_cmd_text):
  color_cmd = get_color_cmd(color_cmd_text)
  for i in range(0, 3):
    command(color_cmd)

def spacer():
  color_command("spacer")

def fix_missing(value):
  if value is None:
    return "missing"
  else:
    return value

def setup():
  global s
  s = serial.Serial("/dev/ttyS0", 57600)
  command("erase")

def loop():
  r = requests.get(url)
  r = r.text.encode('utf-8')
  j = json.loads(r)

  command("pause");

  for x in range(0, job_limit):
    st = fix_missing(j[x]['status'])
    lc = fix_missing(j[x]['lifecycle'])
    oc = fix_missing(j[x]['outcome'])
    br = j[x]['branch']
    rp = j[x]['reponame']
    master = br == 'master'
    orders = rp == 'orders'
    orders_master = master and orders
#    print "st:\t" + st + "\tlc:\t" + lc + "\toc:\t" + oc + "\tbr:\t" + br + "\trp:\t" + rp

    if st == 'failed':
      if orders_master:
        color_command3('masterfailed')
      else:
        color_command3('failed')
    elif st == 'success':
      color_command3('success')
    elif st == 'running':
      color_command3('running')
    elif st == 'fixed':
      if orders_master:
        color_command3('masterfixed')
      else:
        color_command3('fixed')
    elif oc == 'infrastructure_fail':
      color_command3('infrastructure_fail')
    else:
        color_command(st)
        color_command(oc)
        color_command(lc)
    spacer()

  command("continue");
  command("flush");
  time.sleep(request_frequency)

if __name__ == '__main__':
  setup()
  while True:
    loop()