text:
module('admin.SelectFilter2');

test('init', function(assert) {
    var $ = django.jQuery;
    $('<form><select id="id"></select></form>').appendTo('#qunit-fixture');
    $('<option value="0">A</option>').appendTo('#id');
    SelectFilter.init('id', 'things', 0);
    assert.equal($('.selector-available h2').text().trim(), "Available things");
    assert.equal($('.selector-chosen h2').text().trim(), "Chosen things");
    assert.equal($('.selector-chooseall').text(), "Choose all");
    assert.equal($('.selector-add').text(), "Choose");
    assert.equal($('.selector-remove').text(), "Remove");
    assert.equal($('.selector-clearall').text(), "Remove all");
});


text:
<?php
namespace DaveJamesMiller\Breadcrumbs;

use InvalidArgumentException;
use Illuminate\Routing\Router;

class Manager
{
    protected $factory;
    protected $router;

    protected $callbacks = array();
    protected $view;

    protected $currentRoute;

    public function __construct($factory, Router $router)
    {
        if (! $factory instanceof \Illuminate\View\Factory && ! $factory instanceof \Illuminate\View\Environment) {
            throw new InvalidArgumentException('$factory must be an instance of either \Illuminate\View\Factory or \Illuminate\View\Environment');
        }

        $this->factory = $factory;
        $this->router = $router;
    }

    public function getView()
    {
        return $this->view;
    }

    public function setView($view)
    {
        $this->view = $view;
    }

    public function register($name, $callback)
    {
        $this->callbacks[$name] = $callback;
    }

    public function exists($name = null)
    {
        if (is_null($name)) {
            try {
                list($name) = $this->currentRoute();
            } catch (Exception $e) {
                return false;
            }
        }

        return isset($this->callbacks[$name]);
    }

    public function generate($name = null)
    {
        if (is_null($name))
            return $this->generateCurrent();

        $params = array_slice(func_get_args(), 1);
        return $this->generateArray($name, $params);
    }

    public function generateArray($name, $params = array())
    {
        $generator = new Generator($this->callbacks);
        $generator->call($name, $params);
        return $generator->toArray();
    }

    public function generateIfExists($name)
    {
        if ($this->exists($name))
            return call_user_func_array(array($this, 'generate'), func_get_args());
        else
            return array();
    }

    public function generateArrayIfExists($name, $params = array())
    {
        if ($this->exists($name))
            return call_user_func_array(array($this, 'generateArray'), func_get_args());
        else
            return array();
    }

    public function render($name = null)
    {
        if (is_null($name))
            return $this->renderCurrent();

        $params = array_slice(func_get_args(), 1);
        return $this->renderArray($name, $params);
    }

    public function renderIfExists($name = null)
    {
        if ($this->exists($name))
            return call_user_func_array(array($this, 'render'), func_get_args());
        else
            return '';
    }

    public function renderArray($name, $params = array())
    {
        $breadcrumbs = $this->generateArray($name, $params);

        return $this->factory->make($this->view, compact('breadcrumbs'))->render();
    }

    public function renderArrayIfExists($name = null)
    {
        if ($this->exists($name))
            return call_user_func_array(array($this, 'renderArray'), func_get_args());
        else
            return '';
    }

    protected function generateCurrent()
    {
        list($name, $params) = $this->currentRoute();

        return $this->generateArray($name, $params);
    }

    protected function renderCurrent()
    {
        list($name, $params) = $this->currentRoute();

        return $this->renderArray($name, $params);
    }

    protected function currentRoute()
    {
        if ($this->currentRoute)
            return $this->currentRoute;

        $route = $this->router->current();

        if (is_null($route))
            return $this->currentRoute = array('', array());

        $name = $route->getName();

        if (is_null($name)) {
            $uri = head($route->methods()) . ' ' . $route->uri();
            throw new Exception("The current route ($uri) is not named - please check routes.php for an \"as\" parameter");
        }

        $params = $route->parameters();

        return $this->currentRoute = array($name, $params);
    }

    public function setCurrentRoute($name)
    {
        $params = array_slice(func_get_args(), 1);

        $this->setCurrentRouteArray($name, $params);
    }

    public function setCurrentRouteArray($name, $params = array())
    {
        $this->currentRoute = array($name, $params);
    }

    public function clearCurrentRoute()
    {
        $this->currentRoute = null;
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Web;
using AspxCommerce.Core.Mobile;
using SageFrame.Web.Utilities;
using AspxCommerce.Core;

namespace AspxCommerce.CashOnDelivery
{
    public class CashOnDelivery
    {
        public static string Parse(string transId, string invoice, string POrderno, int responseCode, int responsereasonCode, string responsetext, AspxCommonInfo aspxCommonObj)
        {
            try
            {
                var ot = new OrderDetailsCollection();
                var odinfo = new OrderDetailsInfo();
                var cms = new CartManageSQLProvider();
                var cf = new CommonInfo {StoreID = aspxCommonObj.StoreID, PortalID = aspxCommonObj.PortalID, AddedBy = aspxCommonObj.UserName};
                // UpdateOrderDetails

                odinfo.OrderID =int.Parse(HttpContext.Current.Session["OrderID"].ToString());
                odinfo.TransactionID = odinfo.ResponseCode.ToString(transId);
                odinfo.InvoiceNumber = Convert.ToString(invoice);
                odinfo.PurchaseOrderNumber = Convert.ToString(POrderno);
                odinfo.ResponseCode = Convert.ToInt32(responseCode);
                odinfo.ResponseReasonCode = Convert.ToInt32(responsereasonCode);
                odinfo.ResponseReasonText = Convert.ToString(responsetext);
                ot.ObjOrderDetails = odinfo;
                ot.ObjCommonInfo = cf;
                odinfo.OrderStatusID = 8;
                AspxOrderController.UpdateOrderDetails(ot);
                if (HttpContext.Current.Session["OrderCollection"] != null)
                {
                    var orderdata2 =  (OrderDetailsCollection)HttpContext.Current.Session["OrderCollection"];
                    AspxOrderController.UpdateItemQuantity(orderdata2);
                }
                HttpContext.Current.Session.Remove("OrderID");
                cms.ClearCartAfterPayment(aspxCommonObj);
                return "This transaction has been approved";
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }
        public static string ParseForMobile(string transId, OrderInfo orderInfo, string POrderno, int responseCode, int responsereasonCode, string responsetext)
        {
            try
            {
                var ot = new OrderDetailsCollection();
                var odinfo = new OrderDetailsInfo();
                var cms = new CartManageSQLProvider();
                var cf = new CommonInfo
                             {StoreID = orderInfo.StoreId, PortalID = orderInfo.PortalId, AddedBy = orderInfo.AddedBy};
                // UpdateOrderDetails

                odinfo.OrderID = orderInfo.OrderId;
                odinfo.TransactionID = odinfo.ResponseCode.ToString(transId);
                odinfo.InvoiceNumber = orderInfo.InvoiceNumber;
                odinfo.PurchaseOrderNumber = Convert.ToString(POrderno);
                odinfo.ResponseCode = Convert.ToInt32(responseCode);
                odinfo.ResponseReasonCode = Convert.ToInt32(responsereasonCode);
                odinfo.ResponseReasonText = Convert.ToString(responsetext);
                ot.ObjOrderDetails = odinfo;
                ot.ObjCommonInfo = cf;
                odinfo.OrderStatusID = 8;
                AspxOrderController.UpdateOrderDetails(ot);
                AspxCommonInfo aspxCommonObj = new AspxCommonInfo();
                aspxCommonObj.CustomerID = orderInfo.CustomerId;
                aspxCommonObj.SessionCode = orderInfo.SessionCode;
                aspxCommonObj.StoreID = orderInfo.StoreId;
                aspxCommonObj.PortalID = orderInfo.PortalId;
                cms.ClearCartAfterPayment(aspxCommonObj);
                return "This transaction has been approved";
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        /// <summary>
        /// update the quantity of items after order and also update the coupon code
        /// that used on that order
        ///
        /// </summary>
        /// /// <param name="orderInfo">info of order </param>
        /// <param name="itemsInfo">collection of items </param>
        /// <param name="coupon">and coupon code in coponCode#codeapplided  as single string</param>
        /// <param name="storeId">id of the store</param>
        /// <param name="portalId">id of the portal</param>
        /// <param name="userName">userName of customer</param>
        public static void UpdateItemQuantityAndCoupon(OrderInfo orderInfo, List<OrderItem> itemsInfo, List<CouponSession> coupons, int storeId, int portalId, string userName)
        {
            try
            {
                string error = "";
                try
                {

                    foreach (var coupon in coupons)
                    {
                        var paraMeter = new List<KeyValuePair<string, object>>
                                                {
                                                    new KeyValuePair<string, object>("@CouponCode",coupon.Key),
                                                    new KeyValuePair<string, object>("@StoreID", storeId),
                                                    new KeyValuePair<string, object>("@PortalID", portalId),
                                                    new KeyValuePair<string, object>("@UserName", userName),
                                                    new KeyValuePair<string, object>("@CouponUsedCount",coupon.AppliedCount),
                                                    new KeyValuePair<string, object>("@OrderID", orderInfo.OrderId)

                                                };
                        var sqlH = new SQLHandler();
                        sqlH.ExecuteNonQuery("usp_Aspx_UpdateCouponUserRecord", paraMeter);
                    }

                }
                catch (Exception ex)
                {
                    error = ex.InnerException.ToString();
                }

                foreach (var item in itemsInfo)
                {
                    if (item.IsDownloadable == false || item.IsGiftCard == false)
                    {
                        var paraMeter = new List<KeyValuePair<string, object>>
                                            {
                                                new KeyValuePair<string, object>("@StoreID", storeId),
                                                new KeyValuePair<string, object>("@PortalID", portalId),
                                                new KeyValuePair<string, object>("@AddedBy", userName),
                                                new KeyValuePair<string, object>("@ItemID", item.ItemId),
                                                new KeyValuePair<string, object>("@Quantity", item.Quantity),
                                                new KeyValuePair<string, object>("@OrderID", orderInfo.OrderId),
                                                new KeyValuePair<string, object>("@CostVariantsIDs", item.CostVariantIds)
                                            };
                        var sqlH = new SQLHandler();
                        sqlH.ExecuteNonQuery("[dbo].[usp_Aspx_UpdateItemQuantitybyOrder]", paraMeter);
                        if (!string.IsNullOrEmpty(error))
                        {
                            throw new Exception(error);
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }

        }
    }
}


text:
<!DOCTYPE html>

Enter Main Callout Here

Use this document as a way to quickly start any new project.
 All you get is this text and a
            mostly barebones HTML document.


text:
<form>
  <field>
    <id>prefixlist.enabled</id>
    Enabled
    <type>checkbox</type>
    <help>Enable / Disable</help>
  </field>
  <field>
    <id>prefixlist.name</id>
    Name
    <type>text</type>
    <help>The name of your Prefix-List, please choose one near to the result you want to achieve.</help>
  </field>
  <field>
    <id>prefixlist.seqnumber</id>
    Number
    <type>text</type>
    <help>The ACL sequence number (10-99)</help>
  </field>
  <field>
    <id>prefixlist.action</id>
    Action
    <type>select_multiple</type>
    <help>Set permit for match or deny to negate the rule.</help>
  </field>
  <field>
    <id>prefixlist.network</id>
    Network
    <type>text</type>
    <help>The network pattern you want to match. It's not validated so please be careful!</help>
  </field>
</form>


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
    <title>Sign In | Bootstrap Based Admin Template - Material Design</title>

    <link rel="icon" href="<?php echo base_url() ?>assets/favicon.ico" type="image/x-icon">

    <link href="https://fonts.googleapis.com/css?family=Roboto:400,700&subset=latin,cyrillic-ext" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet" type="text/css">

    <link href="<?php echo base_url() ?>assets/plugins/bootstrap/css/bootstrap.css" rel="stylesheet">

    <link href="<?php echo base_url() ?>assets/plugins/node-waves/waves.css" rel="stylesheet" />

    <link href="<?php echo base_url() ?>assets/plugins/animate-css/animate.css" rel="stylesheet" />

    <link href="<?php echo base_url() ?>assets/css/style.css" rel="stylesheet">

            AdminBSB
            Admin BootStrap Based - Material Design

                <form id="sign_in" method="POST" action="<?php echo current_url() ?>">

                    <?php $err = $this->session->flashdata('error'); if(isset($err)){ ?>

                        <?php echo $this->session->flashdata('error'); ?>

                    <?php } ?>

                    <?php $suc = $this->session->flashdata('success'); if(isset($suc)){ ?>

                        <?php echo $this->session->flashdata('success'); ?>

                    <?php } ?>

Sign in to start your session

                            person

                            <input type="text" class="form-control" name="username" placeholder="Username" required autofocus>

                            lock

                            <input type="password" class="form-control" name="password" placeholder="Password" required>

                            <input type="checkbox" name="rememberme" id="rememberme" class="filled-in chk-col-pink">
                            Remember Me

                            <input class="btn btn-block bg-pink waves-effect" type="submit" name="submit" value="SIGN IN">

                            <a href="<?php echo site_url('login/signUp') ?>">Register Now!

                            Forgot Password?

                </form>


text:
<?php

namespace Magestudy\PluginExample\Console\Command;

use Magento\Framework\App\ObjectManager;
use Magestudy\PluginExample\Model\Product;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class SaveProductCommand extends Command
{
    protected function configure()
    {
        $this->setName('magestudy:save_product')->setDescription('Save product');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        /** @var Product $product */
        $product = ObjectManager::getInstance()->get(Product::class);
        $output->writeln('Before save: ' . $product->toString());
        $product->save();
        $output->writeln('After save: ' . $product->toString());
    }
}


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

namespace Flunity.Common
{
	/// <summary>
	/// EventSender for actions without arguments.
	/// </summary>
	public class EventSender : EventSenderBase<Action>
	{
		/// <summary>
		/// Notifies all listeners.
		/// </summary>
		public void Dispatch()
		{
			isDispatchingPhase = true;
			isPropagationTerminated = false;
			iterator = new MutableListIterator<Action>(listeners);

			while (!isPropagationTerminated && iterator.MoveNext())
			{
				iterator.Current.Invoke();
			}

			isDispatchingPhase = false;
		}
	}

	/// <summary>
	/// EventSender for actions with one argument.
	/// </summary>
	public class EventSender<T> : EventSenderBase<Action<T>>
	{
		/// <summary>
		/// Notifies all listeners with specified parameter.
		/// </summary>
		public void Dispatch(T param)
		{
			isDispatchingPhase = true;
			isPropagationTerminated = false;
			iterator = new MutableListIterator<Action<T>>(listeners);

			while (!isPropagationTerminated && iterator.MoveNext())
			{
				iterator.Current.Invoke(param);
			}

			isDispatchingPhase = false;
		}
	}

	/// <summary>
	/// EventSender for actions with two arguments.
	/// </summary>
	public class EventSender<T1, T2> : EventSenderBase<Action<T1, T2>>
	{
		/// <summary>
		/// Notifies all listeners with specified parameters.
		/// </summary>
		public void Dispatch(T1 param1, T2 param2)
		{
			isDispatchingPhase = true;
			isPropagationTerminated = false;
			iterator = new MutableListIterator<Action<T1, T2>>(listeners);

			while (!isPropagationTerminated && iterator.MoveNext())
			{
				iterator.Current.Invoke(param1, param2);
			}

			isDispatchingPhase = false;
		}
	}

	/// <summary>
	/// Base class for events subscribing/dispatching.
	///
	/// It is safe to add/remove listeners during dispatching phase.
	/// </summary>
	public abstract class EventSenderBase<DelegateType> where DelegateType : class
	{
		protected List<DelegateType> listeners = new List<DelegateType>();
		protected MutableListIterator<DelegateType> iterator;
		protected bool isDispatchingPhase = false;
		protected bool isPropagationTerminated;

		/// <summary>
		/// Adds event listener.
		///
		/// It is safe to add listener if it is already added.
		/// Listener will not be added in this case.
		///
		/// It is safe to add listener during dispatching phase.
		/// (Newly added listeners will be nonified in the same phase)
		/// </summary>
		/// <param name="listener">Can be null</param>
		public void AddListener(DelegateType listener)
		{
			if (listener == null)
				return;

			if (listeners.Contains(listener))
				return;

			if (isDispatchingPhase)
				iterator.Add(listener);
			else
				listeners.Add(listener);
		}

		/// <summary>
		/// Removes event listener.
		///
		/// It is safe to remove listener if it hasn't been added before.
		///
		/// It is safe to remove listener during dispatching phase.
		/// (Removed listeners will not be notified)
		/// </summary>
		/// <param name="listener">Can be null. </param>
		public void RemoveListener(DelegateType listener)
		{
			if (listener == null)
				return;

			var index = listeners.IndexOf(listener);

			if (index < 0)
				return;

			if (isDispatchingPhase)
				iterator.RemoveAt(index);
			else
				listeners.RemoveAt(index);
		}

		/// <summary>
		/// Removes all listeners.
		/// It is safe to call this method during dispatching.
		/// </summary>
		public void ClearListeners()
		{
			while (listeners.Count > 0)
			{
				RemoveListener(listeners[0]);
			}
		}

		/// <summary>
		/// Can be called during dispatching phase to terminate farther propagation.
		/// </summary>
		public void StopPropagation()
		{
			isPropagationTerminated = true;
		}

		public bool hasListeners
		{
			get { return listeners.Count > 0; }
		}
	}

}


text:
<?php

class Jankkhvej_Weather_Block_Adminhtml_Weather extends Mage_Adminhtml_Block_Widget_Grid_Container
{

	protected function _construct()
	{
		parent::_construct();

		$helper = Mage::helper('weather');
		$this->_blockGroup = 'jankkhvej_weather';
		$this->_controller = 'adminhtml_weather';

		$this->_headerText = $helper->__('Jankkhvej Weather Records');
		$this->_addButtonLabel = $helper->__('Add Weather Record');
	}

}


text:
/**
 * DO NOT MODIFY, GENERATED BY TOOLS
 */
package com.titanium.zldt.controller.base;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.titanium.zldt.models.DailyTrouble;
import com.titanium.zldt.service.DailyTroubleService;
import com.titanium.zldt.mapper.DailyTroubleSearchTerms;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ResponseBody;

import com.titanium.component.date.CustomTimestampEditor;

 import com.titanium.component.query.Condition;
 import  com.titanium.component.pagenation.Page;

public class   DailyTroubleControllerBase {

	 @InitBinder
    protected void initBinder(WebDataBinder binder) throws ServletException {
                binder.registerCustomEditor(Date.class, new CustomTimestampEditor("yyyy-MM-dd HH:mm"));
    }

	@Autowired
	protected DailyTroubleService dailyTroubleService;

	protected Map<String, Object> successMap(){
		Map<String, Object> json = new  HashMap();
		json.put("result", "success");
		return json;
	}

	@RequestMapping(value="/admin/zldt/createDailyTrouble.do")
	public @ResponseBody Map<String, Object> createDailyTrouble(@ModelAttribute("dailyTrouble")  DailyTrouble dailyTrouble) {
		dailyTroubleService.createDailyTrouble(dailyTrouble);
		return successMap();
	}

	@RequestMapping(value="/admin/zldt/updateDailyTrouble.do")
	public @ResponseBody Map<String, Object> updateDailyTrouble(@ModelAttribute("dailyTrouble")  DailyTrouble dailyTrouble)  {
		dailyTroubleService.updateDailyTrouble(dailyTrouble);
		return successMap();
	}

	@RequestMapping(value="/admin/zldt/deleteDailyTrouble.do")
	public @ResponseBody Map<String, Object> deleteDailyTrouble(@RequestParam("id") int id) {
		dailyTroubleService.deleteDailyTrouble(id);
		return successMap();
	}

	@RequestMapping(value="/admin/zldt/getDailyTrouble.do")
	public String getDailyTrouble(@RequestParam("id") int id, ModelMap model){
		 setReferBean(model);
		 model.addAttribute("dailyTrouble", dailyTroubleService.getDailyTrouble(id));
		  return "admin/zldt/editDailyTrouble";
	}

	@RequestMapping(value="/admin/zldt/toCreateDailyTrouble.do")
	public String toCreateDailyTrouble( ModelMap model){
		 setReferBean(model);
		 model.addAttribute("dailyTrouble", new DailyTrouble());
		  return "admin/zldt/addDailyTrouble";
	}

	@RequestMapping(value="/admin/zldt/listDailyTrouble.do")
	public String listDailyTrouble(@ModelAttribute("dailyTroubleSearchTerms") DailyTroubleSearchTerms dailyTroubleSearchTerms, ModelMap model){
 			setListDailyTrouble(dailyTroubleSearchTerms,  model);
		     return "admin/zldt/listDailyTrouble";
	}

	public List<DailyTrouble> setListDailyTrouble(@ModelAttribute("dailyTroubleSearchTerms") DailyTroubleSearchTerms dailyTroubleSearchTerms, ModelMap model){
 			if(dailyTroubleSearchTerms.getPageNum()==-1){
 				dailyTroubleSearchTerms.setPageNum(1);
 			}
 			if(dailyTroubleSearchTerms.getNumPerPage()==-1){
 				dailyTroubleSearchTerms.setNumPerPage(10);
 			}
 			List<DailyTrouble> dailyTroubleList = dailyTroubleService.listDailyTrouble(dailyTroubleSearchTerms);
 			 model.addAttribute("dailyTroubleSearchTerms",dailyTroubleSearchTerms );
 			 long totalCount = dailyTroubleService.countDailyTrouble(dailyTroubleSearchTerms);
 			 dailyTroubleSearchTerms.getPage().setTotalCount(totalCount);
 			 model.addAttribute("dailyTroubleCount", totalCount);
 			  model.addAttribute("page", dailyTroubleSearchTerms.getPage());
		    model.addAttribute("dailyTroubleList", dailyTroubleList);
		    setReferBean(model);
		    setBigDataReferBean(model, dailyTroubleService.listDailyTrouble(dailyTroubleSearchTerms));
		   return  dailyTroubleList;
	}

	protected void setReferBean(ModelMap model){

	}

	protected void setBigDataReferBean(ModelMap model,List<DailyTrouble> list){
		if(list.size()>0){
		}

	}

	protected void setBigDataReferBeanByMap(ModelMap model,List<Map> list){
		if(list.size()>0){
		}

	}

public class KVMap{

	public KVMap(String key, String value){
		this.key = key;
		this.value = value;
	}
	String key;
	String value;
	public String getKey() {
		return key;
	}
	public void setKey(String key) {
		this.key = key;
	}
	public String getValue() {
		return value;
	}
	public void setValue(String value) {
		this.value = value;
	}

}

}


text:
package linodego

import (
	"context"
	"encoding/json"
	"fmt"
	"time"
)

// Stackscript represents a Linode StackScript
type Stackscript struct {
	CreatedStr string `json:"created"`
	UpdatedStr string `json:"updated"`

	ID                int               `json:"id"`
	Username          string            `json:"username"`
	Label             string            `json:"label"`
	Description       string            `json:"description"`
	Ordinal           int               `json:"ordinal"`
	LogoURL           string            `json:"logo_url"`
	Images            []string          `json:"images"`
	DeploymentsTotal  int               `json:"deployments_total"`
	DeploymentsActive int               `json:"deployments_active"`
	IsPublic          bool              `json:"is_public"`
	Created           *time.Time        `json:"-"`
	Updated           *time.Time        `json:"-"`
	RevNote           string            `json:"rev_note"`
	Script            string            `json:"script"`
	UserDefinedFields *[]StackscriptUDF `json:"user_defined_fields"`
	UserGravatarID    string            `json:"user_gravatar_id"`
}

// StackscriptUDF define a single variable that is accepted by a Stackscript
type StackscriptUDF struct {
	// A human-readable label for the field that will serve as the input prompt for entering the value during deployment.
	Label string `json:"label"`

	// The name of the field.
	Name string `json:"name"`

	// An example value for the field.
	Example string `json:"example"`

	// A list of acceptable single values for the field.
	OneOf string `json:"oneOf,omitempty"`

	// A list of acceptable values for the field in any quantity, combination or order.
	ManyOf string `json:"manyOf,omitempty"`

	// The default value. If not specified, this value will be used.
	Default string `json:"default,omitempty"`
}

// StackscriptCreateOptions fields are those accepted by CreateStackscript
type StackscriptCreateOptions struct {
	Label       string   `json:"label"`
	Description string   `json:"description"`
	Images      []string `json:"images"`
	IsPublic    bool     `json:"is_public"`
	RevNote     string   `json:"rev_note"`
	Script      string   `json:"script"`
}

// StackscriptUpdateOptions fields are those accepted by UpdateStackscript
type StackscriptUpdateOptions StackscriptCreateOptions

// GetCreateOptions converts a Stackscript to StackscriptCreateOptions for use in CreateStackscript
func (i Stackscript) GetCreateOptions() StackscriptCreateOptions {
	return StackscriptCreateOptions{
		Label:       i.Label,
		Description: i.Description,
		Images:      i.Images,
		IsPublic:    i.IsPublic,
		RevNote:     i.RevNote,
		Script:      i.Script,
	}
}

// GetUpdateOptions converts a Stackscript to StackscriptUpdateOptions for use in UpdateStackscript
func (i Stackscript) GetUpdateOptions() StackscriptUpdateOptions {
	return StackscriptUpdateOptions{
		Label:       i.Label,
		Description: i.Description,
		Images:      i.Images,
		IsPublic:    i.IsPublic,
		RevNote:     i.RevNote,
		Script:      i.Script,
	}
}

// StackscriptsPagedResponse represents a paginated Stackscript API response
type StackscriptsPagedResponse struct {
	*PageOptions
	Data []Stackscript `json:"data"`
}

// endpoint gets the endpoint URL for Stackscript
func (StackscriptsPagedResponse) endpoint(c *Client) string {
	endpoint, err := c.StackScripts.Endpoint()
	if err != nil {
		panic(err)
	}
	return endpoint
}

// appendData appends Stackscripts when processing paginated Stackscript responses
func (resp *StackscriptsPagedResponse) appendData(r *StackscriptsPagedResponse) {
	resp.Data = append(resp.Data, r.Data...)
}

// ListStackscripts lists Stackscripts
func (c *Client) ListStackscripts(ctx context.Context, opts *ListOptions) ([]Stackscript, error) {
	response := StackscriptsPagedResponse{}
	err := c.listHelper(ctx, &response, opts)

	for i := range response.Data {
		response.Data[i].fixDates()
	}

	if err != nil {
		return nil, err
	}
	return response.Data, nil
}

// fixDates converts JSON timestamps to Go time.Time values
func (i *Stackscript) fixDates() *Stackscript {
	i.Created, _ = parseDates(i.CreatedStr)
	i.Updated, _ = parseDates(i.UpdatedStr)
	return i
}

// GetStackscript gets the Stackscript with the provided ID
func (c *Client) GetStackscript(ctx context.Context, id int) (*Stackscript, error) {
	e, err := c.StackScripts.Endpoint()
	if err != nil {
		return nil, err
	}
	e = fmt.Sprintf("%s/%d", e, id)
	r, err := coupleAPIErrors(c.R(ctx).
		SetResult(&Stackscript{}).
		Get(e))
	if err != nil {
		return nil, err
	}
	return r.Result().(*Stackscript).fixDates(), nil
}

// CreateStackscript creates a StackScript
func (c *Client) CreateStackscript(ctx context.Context, createOpts StackscriptCreateOptions) (*Stackscript, error) {
	var body string
	e, err := c.StackScripts.Endpoint()
	if err != nil {
		return nil, err
	}

	req := c.R(ctx).SetResult(&Stackscript{})

	if bodyData, err := json.Marshal(createOpts); err == nil {
		body = string(bodyData)
	} else {
		return nil, NewError(err)
	}

	r, err := coupleAPIErrors(req.
		SetBody(body).
		Post(e))

	if err != nil {
		return nil, err
	}
	return r.Result().(*Stackscript).fixDates(), nil
}

// UpdateStackscript updates the StackScript with the specified id
func (c *Client) UpdateStackscript(ctx context.Context, id int, updateOpts StackscriptUpdateOptions) (*Stackscript, error) {
	var body string
	e, err := c.StackScripts.Endpoint()
	if err != nil {
		return nil, err
	}
	e = fmt.Sprintf("%s/%d", e, id)

	req := c.R(ctx).SetResult(&Stackscript{})

	if bodyData, err := json.Marshal(updateOpts); err == nil {
		body = string(bodyData)
	} else {
		return nil, NewError(err)
	}

	r, err := coupleAPIErrors(req.
		SetBody(body).
		Put(e))

	if err != nil {
		return nil, err
	}
	return r.Result().(*Stackscript).fixDates(), nil
}

// DeleteStackscript deletes the StackScript with the specified id
func (c *Client) DeleteStackscript(ctx context.Context, id int) error {
	e, err := c.StackScripts.Endpoint()
	if err != nil {
		return err
	}
	e = fmt.Sprintf("%s/%d", e, id)

	_, err = coupleAPIErrors(c.R(ctx).Delete(e))
	return err
}


text:
'use strict';

var videos = require('../controllers/videos');

// Video authorization helpers
var hasAuthorization = function(req, res, next) {
    if (!req.user.isAdmin && req.video.user.id !== req.user.id) {
        return res.send(401, 'User is not authorized');
    }
    next();
};

module.exports = function(Videos, app, auth) {
    app.get('/videos/search', auth.requiresLogin, videos.searchAll);
    app.get('/videos/tags', auth.requiresLogin, videos.taggedVideos);
    app.get('/videos/taglist', auth.requiresLogin, videos.tagList);
    app.get('/videos/categories', auth.requiresLogin, videos.categoryVideos);
    app.get('/videos/userlist', auth.requiresLogin, videos.userVideos);
    //app.get('/videos/categorylist', auth.requiresLogin, videos.categoryList);
    app.route('/videos')
        .get(videos.all)
        .post(auth.requiresLogin, videos.create);
    app.route('/videos/:videoId')
        .get(videos.show)
        .put(auth.requiresLogin, hasAuthorization, videos.update)
        .delete(auth.requiresLogin, hasAuthorization, videos.destroy);

    app.route('/videos/comment/:videoId')
        .post(auth.requiresLogin, videos.addComment);

    // Finish with setting up the videoId param
    app.param('videoId', videos.video);
};


text:
function LocalData() {
  this.storage = window.localStorage;
}

LocalData.prototype.get = function(key) {
  var item = parseInt(this.storage.getItem(key));
  if (!item) {
    item = 0;
    this.set(key, item);
  }
  return item;
};

LocalData.prototype.set = function(key, item) {
  this.storage.setItem(key, item);
};

LocalData.prototype.getHighScores = function() {
  var highScores = this.storage.getItem('fling_highScores');
  if (!highScores) {
    highScores = [];
    for (var i = 0; i < 7; i++) {
      highScores.push({name: 'someone', score: 0});
    }
    this.set('fling_highScores', JSON.stringify(highScores));
  } else {
    highScores = JSON.parse(highScores);
  }
  return highScores;
};


text:
package org.skife.jdbi.v2.sqlobject.customizers;

import org.skife.jdbi.v2.Query;
import org.skife.jdbi.v2.SQLStatement;
import org.skife.jdbi.v2.sqlobject.SqlStatementCustomizer;
import org.skife.jdbi.v2.sqlobject.SqlStatementCustomizerFactory;
import org.skife.jdbi.v2.sqlobject.SqlStatementCustomizingAnnotation;

import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import java.sql.SQLException;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.PARAMETER})
@SqlStatementCustomizingAnnotation(FetchSize.Factory.class)
public @interface FetchSize
{
    int value() default 0;

    static class Factory implements SqlStatementCustomizerFactory
    {
        @Override
        public SqlStatementCustomizer createForMethod(Annotation annotation, Class sqlObjectType, Method method)
        {
            final FetchSize fs = (FetchSize) annotation;
            return new SqlStatementCustomizer()
            {
                @Override
                public void apply(SQLStatement q) throws SQLException
                {
                    assert q instanceof Query;
                    ((Query) q).setFetchSize(fs.value());
                }
            };
        }

        @Override
        public SqlStatementCustomizer createForType(Annotation annotation, Class sqlObjectType)
        {
            final FetchSize fs = (FetchSize) annotation;
            return new SqlStatementCustomizer()
            {
                @Override
                public void apply(SQLStatement q) throws SQLException
                {
                    assert q instanceof Query;
                    ((Query) q).setFetchSize(fs.value());
                }
            };
        }

        @Override
        public SqlStatementCustomizer createForParameter(Annotation annotation, Class sqlObjectType, Method method, Object arg)
        {
            final Integer va = (Integer) arg;
            return new SqlStatementCustomizer()
            {
                @Override
                public void apply(SQLStatement q) throws SQLException
                {
                    assert q instanceof Query;
                    ((Query) q).setFetchSize(va);
                }
            };
        }
    }
}


text:
/*global hydrated, Backbone*/

hydrated.Collections = hydrated.Collections || {};

(function () {
    'use strict';

    hydrated.Collections.ApplicationCollection = Backbone.Collection.extend({

        model: hydrated.Models.ApplicationModel

    });

})();


text:
![Aplikasi Grosir Obat](public/imgs/readme-logo.png "Aplikasi Grosir Obat")

[![Build Status](https://travis-ci.org/nafiesl/grosir-obat.svg?branch=master)](https://travis-ci.org/nafiesl/grosir-obat)
[![StyleCI](https://styleci.io/repos/87638082/shield?branch=master)](https://styleci.io/repos/87638082)

Aplikasi Grosir Obat adalah sebuah sistem kasir (Point of Sales) dan manajemen produk obat yang dibuat menggunakan framework Laravel, dibangun dengan Test-Driven Development.

## Daftar Isi
1. [Fitur](#fitur)
2. [Demo Aplikasi](#demo-aplikasi)
3. [Instalasi](#instalasi)
    - [Spesifikasi yang Dibutuhkan](#spesifikasi)
    - [Cara Install](#cara-install)
    - [Login Admin](#cara-install)
    - [Testing](#automated-testing)
4. [Input Produk dan Satuan](#input-produk-dan-satuan)
5. [Proses Transaksi](#proses-transksi)
    - [Keranjang Belanja](#keranjang-belanja)
    - [Proses Entry Transaksi](#proses-entry-transaksi)
6. [Screenshots](#screenshots)
7. [Lisensi](#license)

## Fitur

Fitur pada Aplikasi ini meliputi:

1. Akun Login
    - Login dan Logout User
    - Ganti Password User
2. Entry Transaksi
    - Entry Transaksi Tunai
    - Entry Transaksi Kredit
    - Pencarian Produk
    - Konfirmasi Transaksi
    - Cetak Nota (PDF; Format A4)
3. Manajemen Produk
    - List Produk
    - Cetak Daftar Harga
    - Input Produk Baru
    - Edit Produk (Harga Tunai dan Kredit)
    - Hapus Produk
4. Manajemen Satuan Produk
    - List Satuan Produk
    - Input Produk Baru
    - Edit Satuan Produk
    - Hapus Satuan Produk
5. Manajemen Transaksi
    - List Transaksi Hari ini
    - List Transaksi
    - Detail Transaksi
    - Cetak Nota (PDF; Format A4)
6. Laporan Penjualan
    - Penjualan Per Tahun
    - Penjualan Per Bulan
    - Penjualan Per Tanggal
6. Manajemen User
    - List User
    - Input User Baru
    - Edit User
    - Hapus User (jika tidak ada transaksi)

Catatan:
- **Transaksi Kredit** saat ini hanya ditujukan untuk membedakan harga produk, bukan input pembayaran yang diangsur oleh customer. Dipersilakan jika ada yang berkenan mengembangkan fitur tersebut.

## Demo Aplikasi

| URL | http://grosir-obat.nafies.id/login |
| --- | --- |
| username | admin |
| password | secret |

## Instalasi

### Spesifikasi
- PHP ^7.2
- Laravel 6.x
- Database MySQL atau MariaDB
- SQlite (untuk `automated testing`)

### Cara Install

1. Clone atau download source code
    - Para terminal, clone repo `git clone git@github.com:nafiesl/grosir-obat.git`
    - atau `git clone https://github.com/nafiesl/grosir-obat.git`
    - Jika tidak menggunakan Git, silakan **Download Zip** dan *extract* pada direktori web server (misal: xampp/htdocs)
2. `cd grosir-obat`
3. `composer install`
4. `cp .env.example .env`
    - Jika tidak menggunakan Git, bisa rename file `.env.example` menjadi `.env`
5. Pada terminal `php artisan key:generate`
6. Buat **database pada mysql** untuk aplikasi ini
7. **Setting database** pada file `.env`
8. Masukkan **Nama Aplikasi**, **Nama Toko**, **Alamat Toko** dan **Telp Toko** pada pada file `.env`
    ```
    APP_NAME="Apotek Sejahtera"
    STORE_NAME="Apotek Sejahtera"
    STORE_ADDRESS="Jln. Pramuka, No. 60, Banjarmasin"
    STORE_PHONE="081234567890"
    ```
8. `php artisan migrate --seed`
9. `php artisan serve`
10. Selesai

### Login Admin
```
Username: admin
Password: secret
```

### Automated Testing
Aplikasi ini dilengkapi dengan **Testing Laravel**, ingin mencoba? Silakan:
```
vendor/bin/phpunit
```

## Input Produk dan Satuan
Untuk mulai menggunakan aplikasi, silakan inputkan **Satuan Produk** terlebih dahulu, misal:
`Box, Botol, Kaleng, Keping, Pak, Pcs`

Kemudian inputkan **Produk** agar dapat dimasukkan ke dalam transaksi belanja (Cart)

## Proses Transksi

### Keranjang Belanja

**Keranjang Belanja** didesain agar mengikuti hirarki berikut:
- Kelas **CartCollection** memiliki beberapa kelas **CashDraft** dan atau **CreditDraft**
- Kelas **CashDraft** memiliki beberapa **Item** dengan harga **Tunai**
- Kelas **CreditDraft** memiliki beberapa **Item** dengan harga **Kredit**
- Kelas **CashDraft** akan disimpan sebagai transaksi dengan model **Transaction** tipe **Tunai**
- Kelas **CreditDraft** akan disimpan sebagai transaksi dengan model **Transaction** tipe **Kredit**

### Proses Entry Transaksi

Proses Entry transaksi baru:

1. User login
2. Klik tombol **Transaksi Tunai** (atau **Transaksi Kredit**)
3. Cari produk (minimal 3 huruf)
4. Muncul list produk dengan harga sesuai jenis transaksi
5. Isi **Jumlah Item**, klik **Tambah**
6. Item produk yang bersangkutan akan muncul pada List Item
7. Isi data pembeli
8. Klik **Proses Transaksi**
9. Muncul halaman **Konfirmasi Transaksi** (cek list item, harga dan total)
10. Klik **Simpan Transaksi**
11. Muncul halaman **Detail Transaksi**
12. **Cetak Nota** format PDF ukuran A4.

## Screenshots

#### Shopping Cart
![Shopping Cart](public/imgs/01-shopping-cart.jpg "Shopping Cart")

#### Konfirmasi Entry Transaksi
![Konfirmasi Entry Transaksi](public/imgs/02-konfirmasi-entry-transaksi.jpg "Konfirmasi Entry Transaksi")

#### List Transaksi
![List Transaksi](public/imgs/03-list-transaksi.jpg "List Transaksi")

#### Daftar Produk
![Daftar Produk](public/imgs/04-daftar-produk.jpg "Daftar Produk")

#### Laporan Penjualan Pertahun
![Laporan Tahunan](public/imgs/06-yearly-sales.jpg "Laporan Tahunan")

#### Laporan Penjualan Perbulan
![Laporan Bulanan](public/imgs/07-monthly-sales.jpg "Laporan Bulanan")

#### Testing
![Testing](public/imgs/05-testing.jpg "Testing")

## Lisensi

Project Grosir Obat merupakan software Point of Sales yang free dan open source di bawah [lisensi MIT](LICENSE).


text:
[Free Advice](http://adrevice.github.io/) is a one place where you will get Knowledge and solutions to your small problems.

*Do Share the Website links*

## Getting Started

To get Started
* Go to the Above link and get started
* Must not fork it

## Bugs and Issues

Have a bug or an issue with this website? [Open a new issue](https://adrevice.github.io/issues) here on GitHub or elave feedback through contact page on the website

## Creator

Free Advice was created by and is maintained by **Manish Joshi**, Software Engineer at [Yamaha Motors Solution Pvt (I) Ltd.](http://www.ymsl.in/).

* https://twitter.com/
* https://github.com/AdreVice

## Copyright and License

Copyright 2017 AdreVice, under the *MIT* license...


text:
package com.hribol.bromium.core.utils;

import org.junit.Test;

import java.io.IOException;

import static org.junit.Assert.assertTrue;

/**
 * Created by hvrigazov on 22.04.17.
 */
public class JavascriptInjectionPreparatorTest {

    @Test
    public void jsInjectorProducesValidScriptTag() throws IOException {
        String pathToJSInjectionFile = getClass().getResource("/eventsRecorder.js").getFile();
        JavascriptInjectionPreparator javascriptInjectionPreparator = new JavascriptInjectionPreparator(pathToJSInjectionFile);

        String outputJS = javascriptInjectionPreparator.getInjectionCode();

        assertTrue(outputJS.startsWith("<script>"));
        assertTrue(outputJS.endsWith("</script>"));
    }
}


text:
package com.webcohesion.ofx4j.domain.data.signon;

import com.webcohesion.ofx4j.domain.data.MessageSetType;
import com.webcohesion.ofx4j.domain.data.ResponseMessageSet;
import com.webcohesion.ofx4j.domain.data.ResponseMessage;
import com.webcohesion.ofx4j.meta.ChildAggregate;
import com.webcohesion.ofx4j.meta.Aggregate;

import java.util.List;
import java.util.ArrayList;

/**
 * The sign-on response message set.
 *
 * @author Ryan Heaton
 * @see "Section 2.5, OFX Spec."
 */
@Aggregate ("SIGNONMSGSRSV1")
public class SignonResponseMessageSet extends ResponseMessageSet {

  private SignonResponse signonResponse;
  private PasswordChangeResponseTransaction passwordChangeResponse;

  public MessageSetType getType() {
    return MessageSetType.signon;
  }

  /**
   * The message for this message set.
   *
   * @return The message for this message set.
   */
  @ChildAggregate ( order = 0 )
  public SignonResponse getSignonResponse() {
    return signonResponse;
  }

  /**
   * The message for this message set.
   *
   * @param signonResponse The message for this message set.
   */
  public void setSignonResponse(SignonResponse signonResponse) {
    this.signonResponse = signonResponse;
  }

  /**
   * The password change response.
   *
   * @return The password change response.
   */
  @ChildAggregate ( order = 10 )
  public PasswordChangeResponseTransaction getPasswordChangeResponse() {
    return passwordChangeResponse;
  }

  /**
   * The password change response.
   *
   * @param passwordChangeResponse The password change response.
   */
  public void setPasswordChangeResponse(PasswordChangeResponseTransaction passwordChangeResponse) {
    this.passwordChangeResponse = passwordChangeResponse;
  }

  //todo: challenge request/response

  // Inherited.
  public List<ResponseMessage> getResponseMessages() {
    ArrayList<ResponseMessage> messages = new ArrayList<ResponseMessage>();

    if (getSignonResponse() != null) {
      messages.add(getSignonResponse());
    }

    return messages;
  }
}


text:
/*Adds a virtual column to the persons table*/
ALTER TABLE persons ADD (full_name varchar(50)
GENERATED ALWAYS AS (first_name || ' ' || last_name) VIRTUAL);

exit;


text:
import pytest

from polyaxon.connections.kinds import V1ConnectionKind
from polyaxon.connections.schemas import (
    V1BucketConnection,
    V1ClaimConnection,
    V1HostPathConnection,
)
from polyaxon.connections.schemas.connections import V1CustomConnection
from polyaxon.schemas.types import V1ConnectionType
from polyaxon.utils.test_utils import BaseTestCase

@pytest.mark.parser_mark
class TestConnectionType(BaseTestCase):
    def setUp(self):
        super().setUp()
        self.s3_store = V1ConnectionType(
            name="test",
            kind=V1ConnectionKind.S3,
            tags=["test", "foo"],
            schema=V1BucketConnection(bucket="s3//:foo"),
        )
        self.gcs_store = V1ConnectionType(
            name="test",
            kind=V1ConnectionKind.GCS,
            tags=["test"],
            schema=V1BucketConnection(bucket="gs//:foo"),
        )
        self.az_store = V1ConnectionType(
            name="test",
            kind=V1ConnectionKind.WASB,
            schema=V1BucketConnection(bucket="wasbs://x@y.blob.core.windows.net"),
        )
        self.claim_store = V1ConnectionType(
            name="test",
            kind=V1ConnectionKind.VOLUME_CLAIM,
            schema=V1ClaimConnection(
                volume_claim="test", mount_path="/tmp", read_only=True
            ),
        )
        self.host_path_store = V1ConnectionType(
            name="test",
            kind=V1ConnectionKind.HOST_PATH,
            schema=V1HostPathConnection(
                host_path="/tmp", mount_path="/tmp", read_only=True
            ),
        )

        self.custom_connection1 = V1ConnectionType(
            name="db",
            kind=V1ConnectionKind.POSTGRES,
        )

        self.custom_connection2 = V1ConnectionType(
            name="ssh",
            kind=V1ConnectionKind.SSH,
            schema=V1CustomConnection(key1="val1", key2="val2"),
        )

    def test_store_path(self):
        assert self.s3_store.store_path == self.s3_store.schema.bucket
        assert self.s3_store.tags == ["test", "foo"]
        assert self.gcs_store.store_path == self.gcs_store.schema.bucket
        assert self.gcs_store.tags == ["test"]
        assert self.az_store.store_path == "x"
        assert self.az_store.tags is None
        assert self.claim_store.store_path == self.claim_store.schema.mount_path
        assert self.claim_store.tags is None
        assert self.host_path_store.store_path == self.claim_store.schema.mount_path
        assert self.host_path_store.tags is None

    def test_is_bucket(self):
        assert self.s3_store.is_bucket is True
        assert self.s3_store.is_s3 is True
        assert self.s3_store.is_gcs is False

        assert self.gcs_store.is_bucket is True
        assert self.gcs_store.is_gcs is True
        assert self.gcs_store.is_s3 is False

        assert self.az_store.is_bucket is True
        assert self.az_store.is_wasb is True
        assert self.az_store.is_s3 is False
        assert self.az_store.is_gcs is False

        assert self.claim_store.is_bucket is False
        assert self.claim_store.is_s3 is False

        assert self.host_path_store.is_bucket is False
        assert self.host_path_store.is_s3 is False

    @staticmethod
    def assert_from_model(spec: V1ConnectionType):
        result = V1ConnectionType.from_model(model=spec)

        assert result.name == spec.name
        assert result.kind == spec.kind
        if spec.schema is None:
            assert result.schema == spec.schema
        else:
            value_dict = spec.schema.to_dict()
            result_dict = result.schema.to_dict()
            assert value_dict.keys() == result_dict.keys()
            for k in result_dict.keys():
                assert value_dict[k] == result_dict[k]
        assert result.secret == spec.secret

    def test_get_from_model_s(self):
        self.assert_from_model(self.s3_store)
        self.assert_from_model(self.gcs_store)
        self.assert_from_model(self.az_store)
        self.assert_from_model(self.claim_store)
        self.assert_from_model(self.host_path_store)
        assert self.custom_connection1.schema is None
        self.assert_from_model(self.custom_connection1)
        assert self.custom_connection2.schema.key1 == "val1"
        assert self.custom_connection2.schema.key2 == "val2"
        self.assert_from_model(self.custom_connection2)


text: I am the first post


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using GenericMvc.Test.Lib;
using GenericMvc.Test.Lib.Models;
using GenericMvc.Test.Lib.Repository;
using Xunit;
using GenericMvc.Test.Lib.Fixtures;
using GenericMvc.Test.Lib.Contexts;
using GenFu;

namespace GenericMvc.Tests.Repositories
{
	public class EntityFramework : EntityRepository<Blog, int, BlogRepo, BlogDbContext, DataBaseFixture<BlogDbContext>>
	{
		public EntityFramework() : base()
		{

		}

		protected override Blog Mutator(Blog entity) => entity;

		protected override Blog CreateObjectGraph(int n)
		{
			var blog = A.New<Blog>();

			blog.Owner = A.New<User>();

			blog.Posts = A.ListOf<BlogPost>(n);

			foreach (var post in blog.Posts)
			{
				//post.Blog = blog;

				post.Comments = A.ListOf<Comment>(n);

				foreach (var comment in post.Comments)
				{
					//comment.Post = post;

					comment.User = A.New<User>();

					comment.Replies = A.ListOf<Comment>(n);

					foreach (var reply in comment.Replies)
					{
						reply.User = A.New<User>();

						//reply.Post = post;
					}
				}
			}

			return blog;
		}

		protected override IEnumerable<Blog> CreateListofGraphs(int numberOfObjects, int numberOfSubObjects)
		{
			var list = new List<Blog>();

			for (int i = 0; i < numberOfObjects; i++)
			{
				var item = CreateObjectGraph(numberOfSubObjects);

				list.Add(item);
			}

			return SantitizeData(list);
		}

		protected override IEnumerable<Blog> SantitizeData(IEnumerable<Blog> collection)
		{
			foreach (var item in collection)
			{
				item.Id = 0;

				if (item.Owner != null)
				{
					item.Owner.Id = Guid.Empty;
				}

				if(item.Posts != null)
				{
					foreach (var post in item.Posts)
					{
						post.Id = 0;

						foreach (var comment in post.Comments)
						{
							comment.Id = 0;

							comment.User.Id = Guid.Empty;

							foreach (var reply in comment.Replies)
							{
								reply.Id = 0;

								reply.User.Id = Guid.Empty;
							}
						}
					}
				}
			}

			return collection;
		}

		public override Task GetManyWithData()
		{
			return Task.FromResult<object>(null);
		}

		public override Task GetWithData()
		{
			return Task.FromResult<object>(null);
		}

		protected override Expression<Func<Blog, bool>> GetManyQuery()
		{
			return null;
		}

		protected override Expression<Func<Blog, bool>> GetQuery()
		{
			return null;
		}

		public override Task GetMany()
		{
			throw new NotImplementedException();
		}
	}
}


text:
//=================================================================================================

//=================================================================================================

#ifndef _BLAZE_MATH_SHIMS_INVERT_H_
#define _BLAZE_MATH_SHIMS_INVERT_H_

//*************************************************************************************************
// Includes
//*************************************************************************************************

#include <blaze/math/shims/Pow2.h>
#include <blaze/system/Inline.h>
#include <blaze/util/Assert.h>
#include <blaze/util/Complex.h>
#include <blaze/util/EnableIf.h>
#include <blaze/util/typetraits/IsIntegral.h>

namespace blaze {

//=================================================================================================
//
//  INV SHIMS
//
//=================================================================================================

//*************************************************************************************************
/*!\brief Inverting the given integral value.
// \ingroup math_shims
//
// \param a The integral value to be inverted.
// \return The inverse of the given value.
//
// The \a inv shim represents an abstract interface for inverting a value/object of any given
// data type. For integral values this results in \f$ \frac{1}{a} \f$.
//
// \note A division by zero is only checked by an user assert.
*/
template< typename T, EnableIf_t< IsIntegral_v<T> >* = nullptr >
BLAZE_ALWAYS_INLINE constexpr double inv( T a ) noexcept
{
   BLAZE_USER_ASSERT( a != T(0), "Division by zero detected" );
   return ( 1.0 / a );
}
//*************************************************************************************************

//*************************************************************************************************
/*!\brief Inverting the given single precision value.
// \ingroup math_shims
//
// \param a The single precision value to be inverted.
// \return The inverse of the given value.
//
// The \a inv shim represents an abstract interface for inverting a value/object of any given
// data type. For single precision floating point values this results in \f$ \frac{1}{a} \f$.
//
// \note A division by zero is only checked by an user assert.
*/
BLAZE_ALWAYS_INLINE constexpr float inv( float a ) noexcept
{
   BLAZE_USER_ASSERT( a != 0.0F, "Division by zero detected" );
   return ( 1.0F / a );
}
//*************************************************************************************************

//*************************************************************************************************
/*!\brief Inverting the given double precision value.
// \ingroup math_shims
//
// \param a The double precision value to be inverted.
// \return The inverse of the given value.
//
// The \a inv shim represents an abstract interface for inverting a value/object of any given
// data type. For double precision floating point values this results in \f$ \frac{1}{a} \f$.
//
// \note A division by zero is only checked by an user assert.
*/
BLAZE_ALWAYS_INLINE constexpr double inv( double a ) noexcept
{
   BLAZE_USER_ASSERT( a != 0.0, "Division by zero detected" );
   return ( 1.0 / a );
}
//*************************************************************************************************

//*************************************************************************************************
/*!\brief Inverting the given extended precision value.
// \ingroup math_shims
//
// \param a The extended precision value to be inverted.
// \return The inverse of the given value.
//
// The \a inv shim represents an abstract interface for inverting a value/object of any given
// data type. For extended precision floating point values this results in \f$ \frac{1}{a} \f$.
//
// \note A division by zero is only checked by an user assert.
*/
BLAZE_ALWAYS_INLINE constexpr long double inv( long double a ) noexcept
{
   BLAZE_USER_ASSERT( a != 0.0L, "Division by zero detected" );
   return ( 1.0L / a );
}
//*************************************************************************************************

//*************************************************************************************************
/*!\brief Inverting the given single precision complex number.
// \ingroup math_shims
//
// \param a The single precision complex number to be inverted.
// \return The inverse of the given value.
//
// The \a inv shim represents an abstract interface for inverting a value/object of any given
// data type. For a single precision floating point complex number \f$ z = x + yi \f$ this
// results in \f$ \frac{\overline{z}}{x^2+y^2} \f$.
//
// \note A division by zero is only checked by an user assert.
*/
BLAZE_ALWAYS_INLINE constexpr complex<float> inv( const complex<float>& a ) noexcept
{
   const float abs( pow2( real(a) ) + pow2( imag(a) ) );
   BLAZE_USER_ASSERT( abs != 0.0F, "Division by zero detected" );

   const float iabs( 1.0F / abs );
   return complex<float>( iabs*real(a), -iabs*imag(a) );
}
//*************************************************************************************************

//*************************************************************************************************
/*!\brief Inverting the given double precision complex number.
// \ingroup math_shims
//
// \param a The double precision complex number to be inverted.
// \return The inverse of the given value.
//
// The \a inv shim represents an abstract interface for inverting a value/object of any given
// data type. For a double precision floating point complex number \f$ z = x + yi \f$ this
// results in \f$ \frac{\overline{z}}{x^2+y^2} \f$.
//
// \note A division by zero is only checked by an user assert.
*/
BLAZE_ALWAYS_INLINE constexpr complex<double> inv( const complex<double>& a ) noexcept
{
   const double abs( pow2( real(a) ) + pow2( imag(a) ) );
   BLAZE_USER_ASSERT( abs != 0.0, "Division by zero detected" );

   const double iabs( 1.0 / abs );
   return complex<double>( iabs*real(a), -iabs*imag(a) );
}
//*************************************************************************************************

//*************************************************************************************************
/*!\brief Inverting the given extended precision complex number.
// \ingroup math_shims
//
// \param a The extended precision complex number to be inverted.
// \return The inverse of the given value.
//
// The \a inv shim represents an abstract interface for inverting a value/object of any given
// data type. For an extended precision floating point complex number \f$ z = x + yi \f$ this
// results in \f$ \frac{\overline{z}}{x^2+y^2} \f$.
//
// \note A division by zero is only checked by an user assert.
*/
BLAZE_ALWAYS_INLINE constexpr complex<long double> inv( const complex<long double>& a ) noexcept
{
   const long double abs( pow2( real(a) ) + pow2( imag(a) ) );
   BLAZE_USER_ASSERT( abs != 0.0L, "Division by zero detected" );

   const long double iabs( 1.0L / abs );
   return complex<long double>( iabs*real(a), -iabs*imag(a) );
}
//*************************************************************************************************

//=================================================================================================
//
//  INVERT SHIMS
//
//=================================================================================================

//*************************************************************************************************
/*!\brief In-place inversion of the given single precision value.
// \ingroup math_shims
//
// \param a The single precision value to be inverted.
// \return The inverse of the given value.
//
// The \a invert shim represents an abstract interface for inverting a value/object of any
// given data type in-place. For single precision floating point values this results in
// \f$ \frac{1}{a} \f$.
//
// \note A division by zero is only checked by an user assert.
*/
BLAZE_ALWAYS_INLINE void invert( float& a ) noexcept
{
   a = inv( a );
}
//*************************************************************************************************

//*************************************************************************************************
/*!\brief In-place inversion of the given double precision value.
// \ingroup math_shims
//
// \param a The double precision value to be inverted.
// \return The inverse of the given value.
//
// The \a invert shim represents an abstract interface for inverting a value/object of any
// given data type in-place. For double precision floating point values this results in
// \f$ \frac{1}{a} \f$.
//
// \note A division by zero is only checked by an user assert.
*/
BLAZE_ALWAYS_INLINE void invert( double& a ) noexcept
{
   a = inv( a );
}
//*************************************************************************************************

//*************************************************************************************************
/*!\brief In-place inversion of the given extended precision value.
// \ingroup math_shims
//
// \param a The extended precision value to be inverted.
// \return The inverse of the given value.
//
// The \a invert shim represents an abstract interface for inverting a value/object of any
// given data type in-place. For extended precision floating point values this results in
// \f$ \frac{1}{a} \f$.
//
// \note A division by zero is only checked by an user assert.
*/
BLAZE_ALWAYS_INLINE void invert( long double& a ) noexcept
{
   a = inv( a );
}
//*************************************************************************************************

//*************************************************************************************************
/*!\brief In-place inversion of the given single precision complex number.
// \ingroup math_shims
//
// \param a The single precision complex number to be inverted.
// \return The inverse of the given value.
//
// The \a invert shim represents an abstract interface for inverting a value/object of any given
// data type in-place. For a single precision floating point complex number \f$ z = x + yi \f$
// this results in \f$ \frac{\overline{z}}{x^2+y^2} \f$.
//
// \note A division by zero is only checked by an user assert.
*/
BLAZE_ALWAYS_INLINE void invert( complex<float>& a ) noexcept
{
   a = inv( a );
}
//*************************************************************************************************

//*************************************************************************************************
/*!\brief In-place inversion of the given double precision complex number.
// \ingroup math_shims
//
// \param a The double precision complex number to be inverted.
// \return The inverse of the given value.
//
// The \a invert shim represents an abstract interface for inverting a value/object of any given
// data type in-place. For a double precision floating point complex number \f$ z = x + yi \f$
// this results in \f$ \frac{\overline{z}}{x^2+y^2} \f$.
//
// \note A division by zero is only checked by an user assert.
*/
BLAZE_ALWAYS_INLINE void invert( complex<double>& a ) noexcept
{
   a = inv( a );
}
//*************************************************************************************************

//*************************************************************************************************
/*!\brief In-place inversion of the given extended precision complex number.
// \ingroup math_shims
//
// \param a The extended precision complex number to be inverted.
// \return The inverse of the given value.
//
// The \a invert shim represents an abstract interface for inverting a value/object of any given
// data type in-place. For an extended precision floating point complex number \f$ z = x + yi \f$
// this results in \f$ \frac{\overline{z}}{x^2+y^2} \f$.
//
// \note A division by zero is only checked by an user assert.
*/
BLAZE_ALWAYS_INLINE void invert( complex<long double>& a ) noexcept
{
   a = inv( a );
}
//*************************************************************************************************

} // namespace blaze

#endif


text:
package com.complexible.clearbit;

import java.io.IOException;
import java.io.UncheckedIOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Optional;

import com.complexible.common.http.ApacheHttp;
import com.google.common.base.Charsets;
import com.google.common.base.Preconditions;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;

/**
 *

 *
 * @author  Michael Grove
 * @since   0.1
 * @version 0.2
 */
public class EnrichmentAPIV1 implements EnrichmentAPI {
	private final CloseableHttpClient mClient;

	private final String mKey;

	private final boolean mStreaming;

	public EnrichmentAPIV1(final String theKey) {
		this(theKey, false /* use streaming */);
	}

	public EnrichmentAPIV1(final String theKey, final boolean theUseStreamingAPI) {
		mKey = Preconditions.checkNotNull(theKey);
		mStreaming = theUseStreamingAPI;

		mClient = HttpClientBuilder.create()
		                             .setUserAgent("clearbit.api")
		                             .setConnectionManager(new PoolingHttpClientConnectionManager())
		                             .build();
	}

	/**
	 * @inheritDoc
	 */
	@Override
	public void close() throws IOException {
		mClient.close();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public PersonLookup person(final String theEmail) throws IOException {
		return new AbstractPersonLookup(theEmail) {
			@Override
			public Optional<Person> lookup() {
				final HttpGet aRequest;
				try {
					aRequest = new HttpGet(String.format("https://person%s.clearbit.com/v1/people/email/%s",
					                                                   mStreaming ? "-stream" : "",
					                                     URLEncoder.encode(mEmail, Charsets.UTF_8.name())));
				}
				catch (UnsupportedEncodingException e) {
					throw new AssertionError("Should not happen");
				}

				ApacheHttp.HttpRequests.header(aRequest, "Authorization", "Bearer " + mKey);
				ApacheHttp.HttpRequests.header(aRequest, "API-Version", "2015-04-30");

				try {
					return Clearbit.person(mClient.execute(aRequest));
				}
				catch (IOException e) {
					throw new UncheckedIOException(e);
				}
			}
		};
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public CompanyLookup company(final String theDomain) throws IOException {
		return new AbstractCompanyLookup(theDomain) {
			@Override
			public Optional<Company> lookup() {
				final HttpGet aRequest;
				try {
					aRequest = new HttpGet(String.format("https://company%s.clearbit.com/v1/companies/domain/%s",
					                                                   mStreaming ? "-stream" : "",
					                                     URLEncoder.encode(mDomain, Charsets.UTF_8.name())));
				}
				catch (UnsupportedEncodingException e) {
					throw new AssertionError("Should not occur");
				}

				ApacheHttp.HttpRequests.header(aRequest, "Authorization", "Bearer " + mKey);
				ApacheHttp.HttpRequests.header(aRequest, "API-Version", "2015-04-30");

				try {
					return Clearbit.company(mClient.execute(aRequest));
				}
				catch (IOException e) {
					throw new UncheckedIOException(e);
				}
			}
		};
	}
}


text:
import {Router} from 'aurelia-router';
import 'bootstrap';
import 'src/css/styles.css!';
import 'src/css/style.css!';

export class App {
  router:Router;

  configureRouter(config, router:Router) {

    config.title = 'Aurelia';
    config.map([
      {route: ['', 'main'], moduleId: './views/main', nav: false},
      { route: 'expenses',  moduleId: './views/expenses', nav: true, title:'First' },
      { route: 'receipts',  moduleId: './views/receipts', nav: true, title:'Second' },
      { route: 'nothing',  moduleId: './views/nothing', nav: true, title:'Third' }
    ]);

    this.router = router;
  }

}


text:
from xml.sax.saxutils import escape
import codecs
import json
import sys

class JsonOutput():
    def __init__(self, groups, board, inject_xml_file_name):
        all_json=dict()
        all_json['version']=1
        all_json['uid']=1  #COMPONENT_INFORMATION.comp_metadata_type
        all_json['scope']="Firmware"
        all_params=[]
        all_json['parameters']=all_params

        #xml_parameters = ET.Element("parameters")
        #xml_version = ET.SubElement(xml_parameters, "version")
        #xml_version.text = "3"
        #xml_version = ET.SubElement(xml_parameters, "parameter_version_major")
        #xml_version.text = "1"
        #xml_version = ET.SubElement(xml_parameters, "parameter_version_minor")
        #xml_version.text = "15"

        schema_map = {
                        "short_desc": "shortDesc",
			"long_desc": "longDesc",
			"unit": "units",
			"decimal": "decimalPlaces",
			"min": "min",
			"max": "max",
			"increment": "increment",
			"reboot_required": "rebootRequired"
			}
        allowed_types = { "Uint8", "Int8", "Uint16", "Int16", "Uint32", "Int32", "Float"}

        last_param_name = ""
        board_specific_param_set = False
        for group in groups:
            group_name=group.GetName()

            for param in group.GetParams():
                if (last_param_name == param.GetName() and not board_specific_param_set) or last_param_name != param.GetName():
                    curr_param=dict()
                    curr_param['name'] = param.GetName()
                    curr_param['default'] = param.GetDefault()
                    curr_param['type'] = param.GetType().capitalize()
                    if not curr_param['type'] in allowed_types:
                        print("Error: %s type not supported: curr_param['type']" % (curr_param['name'],curr_param['type']) )
                        sys.Exit(1)

                    curr_param['group'] = group_name
                    if (param.GetCategory()):
                        curr_param['category'] = param.GetCategory()

                    if (param.GetVolatile() == "true"):
                        curr_param['volatile'] = param.GetVolatile()

                    last_param_name = param.GetName()
                    for code in param.GetFieldCodes():
                        value = param.GetFieldValue(code)
                        if code == "board":
                            if value == board:
                                board_specific_param_set = True
                                # JSON schema has no field for board_specific schema. Ignore.
                            else:
                                #xml_group.remove(xml_param)
                                continue
                        else:
                            #map PX4 param field names to schema names
                           if code in schema_map:
                               curr_param[schema_map[code]] = value
                           else:
                               print('ERROR: Field not in json schema: %s' % code)
                               sys.exit(1)

                if last_param_name != param.GetName():
                    board_specific_param_set = False

                enum_codes=param.GetEnumCodes() or '' # Gets numerical values for parameter.
                if enum_codes:
                    enum_codes=sorted(enum_codes,key=float)
                    codes_list=list()
                    for item in enum_codes:
                        code_dict=dict()
                        code_dict['value']=item
                        code_dict['description']=param.GetEnumValue(item)
                        codes_list.append(code_dict)
                    curr_param['values'] = codes_list

                if len(param.GetBitmaskList()) > 0:
                    bitmasks_list=list()
                    for index in param.GetBitmaskList():
                        bitmask_dict=dict()
                        bitmask_dict['index']=index
                        bitmask_dict['description']=param.GetBitmaskBit(index)
                        bitmasks_list.append(bitmask_dict)
                    curr_param['bitmask'] = bitmasks_list

                all_params.append(curr_param)

        #Json string output.
        self.output = json.dumps(all_json,indent=2)

    def Save(self, filename):
        with codecs.open(filename, 'w', 'utf-8') as f:
            f.write(self.output)


text:
import re

from lampost.util.lputil import pronouns

defaults = {'e': 's', 't': 'e', 'st': 's', 'et': 'e', 'sf': 's', 'ef': 'e', 'sa': 'st', 'ea': 'et'}

broadcast_types = [{'id': bt[0], 'label': bt[1], 'reduce': bt[2], 'grid_x': bt[3], 'grid_y': bt[4]} for bt in [
    ('s', 'To self (no target)', 's', 0, 0),
    ('e', 'To others (no target)', 's', 0, 1),
    ('t', 'To target (target is other)', 'e', 0, 2),
    ('st', 'To self (target is other)', 's', 1, 0),
    ('et', 'To others (target is other)', 'e', 1, 1),
    ('sf', 'To self (target is self)', 's', 2, 0),
    ('ef', 'To others (target is self)', 'e', 2, 1),
    ('sa', 'To self (target is not living)', 'st', 3, 0),
    ('ea', 'To environment (target is not living)', 'et', 3, 1)]]

broadcast_tokens = [{'id': token_id, 'token': token} for token_id, token in [
    ('n', 'Subject name'),
    ('N', 'Target name'),
    ('e', 'Subject pronoun'),
    ('E', 'Target pronoun'),
    ('s', 'Subject possessive pronoun'),
    ('S', 'Target possessive pronoun'),
    ('m', 'Subject objective pronoun'),
    ('M', 'Target objective pronoun'),
    ('f', 'Subject self pronoun'),
    ('F', 'Target self pronoun'),
    ('a', 'Absolute possessive subj'),
    ('A', 'Absolute possessive targ'),
    ('v', 'Action/verb')]]

token_pattern = re.compile('\$([nNeEsSmMfFaA])')

def substitute(message, source=None, target=None, verb=None, **ext_fmt):
    if source:
        s_name = getattr(source, 'name', source)
        s_sub, s_obj, s_poss, s_self, s_abs = pronouns[getattr(source, 'sex', 'none')]
    else:
        s_name = s_sub = s_obj = s_poss = s_self = s_abs = None
    if target:
        t_name = getattr(target, 'name', target)
        t_sub, t_obj, t_poss, t_self, t_abs = pronouns[getattr(target, 'sex', 'none')]
    else:
        t_name = t_sub = t_obj = t_poss = t_self = t_abs = None

    result = message.format(n=s_name, N=t_name, e=s_sub, E=t_sub, s=s_poss, S=t_poss,
                            m=s_obj, M=t_obj, f=s_self, F=t_self, a=s_abs, A=t_abs,
                            v=verb, **ext_fmt)
    return result

class BroadcastMap:
    def __init__(self, **kwargs):
        for key, value in kwargs.items():
            value = token_pattern.sub(r'{\1}', value)
            setattr(self, key, value)

    def __getitem__(self, msg_key):
        while True:
            msg = getattr(self, msg_key, None)
            if msg:
                return msg
            msg_key = defaults.get(msg_key, None)
            if not msg_key:
                return "[EMPTY]"

class Broadcast:
    def __init__(self, broadcast_map=None, source=None, target=None, display='default',
                 silent=False, verb=None, ext_fmt=None, **kwargs):
        if broadcast_map:
            self.broadcast_map = broadcast_map
        else:
            self.broadcast_map = BroadcastMap(**kwargs)
        self.source = source
        self.target = target
        self.display = display
        self.silent = silent
        self.verb = verb
        self.ext_fmt = ext_fmt if ext_fmt else {}

    def translate(self, observer):
        if self.silent and observer == self.source:
            return None
        if hasattr(self.broadcast_map, 'raw'):
            return self.broadcast_map['raw']
        if not self.target:
            if not self.source or self.source == observer:
                return self.substitute('s')
        if self.target == self.source:
            if self.source == observer:
                return self.substitute('sf')
            return self.substitute('ef')
        if self.target == observer:
            return self.substitute('t')
        if not self.target:
            return self.substitute('e')
        if getattr(self.target, 'living', False):
            if self.source == observer:
                return self.substitute('st')
            return self.substitute('et')
        if self.source == observer:
            return self.substitute('sa')
        return self.substitute('ea')

    def substitute(self, version):
        return substitute(self.broadcast_map[version], self.source, self.target, self.verb, **self.ext_fmt)


text:
@interface SdkTableViewController : UITableViewController

@property (nonatomic, retain)NSMutableArray *sectionName;
@property (nonatomic, retain)NSMutableArray *sectionRow;

@end


text:
<?php

namespace Zend\Session;

/**
 * Session storage container for PHP 5.3.3 and less
 */
class Container extends AbstractContainer
{
}


text:
"""Utilities for debugging Darglint.

This file should not be imported into Darglint,
and should ideally be excluded from the sources.

"""
from ast import (
    AST,
)
from collections import (
    deque,
)
from typing import (
    Any,
    List,
    Optional,
    Set,
)
from .node import CykNode
from .config import (
    get_config,
    Configuration,
)

class AstNodeUtils(object):

    @staticmethod
    def iter_fields(node):
        for field in node._fields:
            try:
                yield field, getattr(node, field)
            except AttributeError:
                pass

    @staticmethod
    def _get_node_label(node):
        if hasattr(node, 'id'):
            return r'{}\nid: {}'.format(
                node.__class__.__name__,
                node.id,
            )
        elif hasattr(node, 'attr') and isinstance(node.attr, str):
            return r'{}\nattr: {}'.format(
                node.__class__.__name__,
                node.attr,
             )
        else:
            return node.__class__.__name__

    @staticmethod
    def to_dot(node):
        # type: (AST) -> str
        dot = ['digraph G {']  # type: List[str]
        id = 0
        queue = deque([(id, node)])
        while queue:
            parent_id, curr = queue.pop()
            dot.insert(1, '  {}_{} [label="{}"];'.format(
                curr.__class__.__name__,
                parent_id,
                AstNodeUtils._get_node_label(curr),
            ))
            for field, value in AstNodeUtils.iter_fields(curr):
                if isinstance(value, list):
                    for item in value:
                        if isinstance(item, AST):
                            id += 1
                            queue.appendleft((id, item))
                            dot.append('  {}_{} -> {}_{};'.format(
                                curr.__class__.__name__, parent_id,
                                item.__class__.__name__, id,
                            ))
                elif isinstance(value, AST):
                    id += 1
                    queue.appendleft((id, value))
                    dot.append('  {}_{} -> {}_{};'.format(
                        curr.__class__.__name__, parent_id,
                        value.__class__.__name__, id,
                    ))
        dot.append('}')
        return '\n'.join(dot)

class CykNodeUtils(object):

    @staticmethod
    def contains(self, symbol=None, value=None):
        # type: (CykNode, Optional[str], Optional[str]) -> bool
        """Return true if the tree contains the given symbol.

        This is intended only for testing.

        Args:
            self: The node where we should begin the search.
            symbol: The symbol to search for.
            value: If defined, the string value the node should
                have in order to match.

        Returns:
            True if the symbol/value is in the tree, false otherwise.

        """
        def _match(n):
            symbol_match = symbol is None or n.symbol == symbol
            value_match = value is None or n.value == value
            return symbol_match and value_match
        for node in self.walk():
            if _match(node):
                return True
        return False

    @staticmethod
    def get_annotated(self, annotation):
        # type: (CykNode, Any) -> Set[CykNode]
        nodes = set()
        for node in self.walk():
            if annotation in node.annotations:
                nodes.add(node)
        return nodes

    @staticmethod
    def to_dot(cyk_node, is_root=True, encountered=set()):
        # type: (CykNode, bool, Set[str]) -> str
        def _get_name(node):
            i = 0
            name = node.symbol
            if node.value:
                if node.value.value:
                    name += '_' + node.value.value
                else:
                    name += '_' + str(node.value)
            for x in '.*!@#$%^*,- ;:\'"\n\t{}[]()':
                name = name.replace(x, '_')
            while name.replace('__', '_') != name:
                name = name.replace('__', '_')
            name = name.lower()
            while name + str(i) in encountered:
                i += 1
            return name + str(i)

        def _get_value(node):
            if cyk_node.value and cyk_node.value.value:
                if cyk_node.value.value.isspace():
                    return repr(cyk_node.value.value).replace('\\', '\\\\')
                return cyk_node.value.value
            elif cyk_node.value:
                return str(cyk_node.value)
            else:
                return cyk_node.symbol

        if is_root:
            ret = 'digraph G {\n'
        else:
            ret = ''

        # Print this node's relationship with its children.
        name = _get_name(cyk_node)
        encountered.add(name)
        if cyk_node.lchild or cyk_node.rchild:
            ret += name + (
                '  [shape="oval", style="filled", '
                ' label="{}",'
                ' fillcolor="#fffde7"];\n'
            ).format(_get_value(cyk_node))
            if cyk_node.lchild:
                childname = _get_name(cyk_node.lchild)
                ret += '{} -> {}'.format(name, childname)
                if cyk_node.annotations:
                    ret += '[label="'
                    for annotation in cyk_node.annotations:
                        ret += annotation.__name__ + ',\\n'
                    ret += '"]'
                ret += ';\n'
            if cyk_node.rchild:
                childname = _get_name(cyk_node.rchild)
                if cyk_node.lchild and _get_name(cyk_node.lchild) == childname:
                    childname += '_'
                ret += '{} -> {};\n'.format(name, childname)
        else:
            ret += name + (
                ' [shape="rectangle", style="filled",'
                ' label="{}"'
                ' fillcolor="#80deea"];\n'
            ).format(_get_value(cyk_node))

        # Add all of the children's relationships.
        if cyk_node.lchild:
            ret += CykNodeUtils.to_dot(
                cyk_node.lchild, False, encountered
            ) + '\n'
        if cyk_node.rchild:
            ret += CykNodeUtils.to_dot(
                cyk_node.rchild, False, encountered
            ) + '\n'

        if is_root:
            ret += '}'
        return ret

class ConfigurationContext(object):
    """A context manager for the configuration.

    Resets the configuration to the value it had prior
    to entering the context.

    """

    def __init__(self, **kwargs):
        self.original = dict()
        self.config = get_config()
        self.kwargs = kwargs

    def __enter__(self):
        # Save the state of the original item.
        for keyword, value in vars(self.config).items():
            self.original[keyword] = getattr(self.config, keyword)

        # Override with the default configuration.
        default_config = Configuration.get_default_instance()
        for keyword in self.original:
            setattr(self.config, keyword, getattr(default_config, keyword))

        # Apply test-specific values.
        for keyword, value in self.kwargs.items():
            setattr(self.config, keyword, value)

        return self.config

    def __exit__(self, exc_type, exc_value, exc_traceack):
        for keyword, value in self.original.items():
            setattr(self.config, keyword, value)


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

<TITLE>Byte[] (Groovy JDK)</TITLE>

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

                        Overview
                        Package
                        Class
                        Tree
                        Deprecated
                        Index
                        Help

            Groovy JDK

java.lang

Class Byte[]

Method Summary

void

eachByte(Closure closure)

Traverse through each byte of this Byte array.

Writable

encodeBase64(boolean chunked)

Produce a Writable object which writes the Base64 encoding of the byte array.

Writable

encodeBase64()

Produce a Writable object which writes the Base64 encoding of the byte array.

Writable

encodeHex()

Produces a Writable that writes the hex encoding of the Byte[].

Method Detail

eachByte

public void eachByte(Closure closure)

Traverse through each byte of this Byte array. Alias for each.

Parameters:

closure -  a closure.

Since:

1.5.5

See:

Object#each.

encodeBase64

public Writable encodeBase64(boolean chunked)

Produce a Writable object which writes the Base64 encoding of the byte array.
Calling toString() on the result returns the encoding as a String. For more
information on Base64 encoding and chunking see RFC 4648.

Parameters:

chunked -  whether or not the Base64 encoded data should be MIME chunked.

Returns:

object which will write the Base64 encoding of the byte array

Since:

1.5.1

encodeBase64

public Writable encodeBase64()

Produce a Writable object which writes the Base64 encoding of the byte array.
Calling toString() on the result returns the encoding as a String. For more
information on Base64 encoding and chunking see RFC 4648.

Returns:

object which will write the Base64 encoding of the byte array

Since:

1.0

encodeHex

public Writable encodeHex()

Produces a Writable that writes the hex encoding of the Byte[]. Calling
toString() on this Writable returns the hex encoding as a String. The hex
encoding includes two characters for each byte and all letters are lower case.

Returns:

object which will write the hex encoding of the byte array

See:

Integer#toHexString(int).

                        Overview
                        Package
                        Class
                        Tree
                        Deprecated
                        Index
                        Help

            Groovy JDK


text:
package com.sponberg.fluid.layout;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import com.sponberg.fluid.GlobalState;
import com.sponberg.fluid.util.KeyValueList;

@ToString
@Getter
@Setter
public class ViewBehaviorWebView extends ViewBehavior {

	private ArrayList<FilePart> internalHtml;

	static final boolean useInline = false;

	static boolean useCache = true;

	private static ArrayList<FilePart> topSection;
	private static ArrayList<FilePart> bottomSection;
	private static HashMap<String, String> cachedResources = new HashMap<>();

	static {
		topSection = generateTopSection();
		bottomSection = generateBottomSection();
		preloadAssets();
	}

	static void preloadAssets() {
		if (useCache) {
			getFile("jquery-2.1.0.min.js");
			getFile("fastclick.js");
			getFile("fluid.js");
			getFile("html5-doctor-reset-stylesheet.css");
			getFile("lesswebby.css");
		}
	}

	public ViewBehaviorWebView(KeyValueList properties) {
		super(ViewBehavior.webview, properties);

		if (!properties.contains("html")) {
			throw new RuntimeException("WebView must contain 'html' that references the html file for the view");
		}

		this.internalHtml = generateInternalHtml(getStringProperty("html", null, properties));
	}

	public String getHtml() {
		StringBuilder buf = new StringBuilder();
		for (FilePart p : topSection) {
			buf.append(p.getHtml());
		}
		for (FilePart p : internalHtml) {
			buf.append(p.getHtml());
		}
		for (FilePart p : bottomSection) {
			buf.append(p.getHtml());
		}
		return buf.toString();
	}

	private static ArrayList<FilePart> generateTopSection() {

		ArrayList<FilePart> list = new ArrayList<>();

		StringBuilder buf = new StringBuilder();

		buf.append("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");

		buf.append("");

		buf.append("");

		buf.append("<title>Fluid View</title>");

		buf.append("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1, user-scalable=no\"></meta>");

		if (useInline) {

			buf.append("");
		} else {

			buf.append("");
			buf.append("");
			buf.append("");
		}

		if (useInline) {

			buf.append("");
		} else {

			buf.append("<link rel=\"stylesheet\" type=\"text/css\" href=\"fluid://load/html5-doctor-reset-stylesheet.css\">");
			buf.append("<link rel=\"stylesheet\" type=\"text/css\" href=\"fluid://load/lesswebby.css\">");
		}

		buf.append("");

		buf.append("");

		list.add(new StringFilePart(buf.toString()));

		return list;
	}

	private static ArrayList<FilePart> generateBottomSection() {

		ArrayList<FilePart> list = new ArrayList<>();

		StringBuilder buf = new StringBuilder();

		buf.append("");

		buf.append("");

		list.add(new StringFilePart(buf.toString()));

		return list;
	}

	private static ArrayList<FilePart> generateInternalHtml(String fileName) {
		String html = GlobalState.fluidApp.getResourceService().getResourceAsString("webview", fileName + ".html");

		if (useInline) {

			try {
				return generateHtmlInlineResources(html);
			} catch (IOException e) {
				e.printStackTrace();
				return new ArrayList<FilePart>();
			}
		} else {

			ArrayList<FilePart> list = new ArrayList<>();
			list.add(new StringFilePart(html));
			return list;
		}
	}

	private static ArrayList<FilePart> generateHtmlInlineResources(String html) throws IOException {

		ArrayList<FilePart> internalHtml = new ArrayList<>();

		StringBuilder buf = new StringBuilder();
		BufferedReader in = new BufferedReader(new StringReader(html));
		String line;
		while ( (line = in.readLine()) != null) {
			boolean finishedWithLine;
			do {
				finishedWithLine = true;
				int i = line.indexOf("");

						String resource = getFile(filename);
						if (resource == null) {
							throw new RuntimeException("Unable to find file " + filename);
						}
						internalHtml.add(new InlineResourceFilePart(filename));

						int i6 = line.indexOf("</script>", i5);
						if (i6 == -1) {
							throw new RuntimeException("Expected </script>");
						}
						line = line.substring(i6 + 9);
						finishedWithLine = false;
					}
				}
			} while (!finishedWithLine);
			buf.append(line + "\n");
		}
		if (buf.length() > 0) {
			internalHtml.add(new StringFilePart(buf.toString()));
		}

		return internalHtml;
	}

	public static String getFile(String name) {

		if (!(name.endsWith(".js") || name.endsWith(".css"))) {
			return null;
		}

		if (useCache) {
			String data = cachedResources.get(name);
			if (data != null) {
				return data;
			}
		}

		String resource = GlobalState.fluidApp.getResourceService().getResourceAsString("webview", name);
		if (useCache) {
			cachedResources.put(name, resource);
		}
		return resource;
	}

	static interface FilePart {
		String getHtml();
	}

	static class StringFilePart implements FilePart {
		final String html;
		public StringFilePart(String html) {
			this.html = html;
		}
		@Override
		public String getHtml() {
			return html;
		}
	}

	static class InlineResourceFilePart implements FilePart {
		final String key;
		public InlineResourceFilePart(String key) {
			this.key = key;
			if (useCache) {
				if (!cachedResources.containsKey(key)) {
					getFile(key);
				}
			}
		}
		@Override
		public String getHtml() {
			String html = cachedResources.get(key);
			return html;
		}
	}

}


text:
package org.apache.lucene.replicator;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.apache.lucene.index.IndexCommit;
import org.apache.lucene.index.IndexDeletionPolicy;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.SnapshotDeletionPolicy;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.IOContext;

/**
 * A {@link Revision} of a single index files which comprises the list of files
 * that are part of the current {@link IndexCommit}. To ensure the files are not
 * deleted by {@link IndexWriter} for as long as this revision stays alive (i.e.
 * until {@link #release()}), the current commit point is snapshotted, using
 * {@link SnapshotDeletionPolicy} (this means that the given writer's
 * {@link IndexWriterConfig#getIndexDeletionPolicy() config} should return
 * {@link SnapshotDeletionPolicy}).
 * <p>
 * When this revision is {@link #release() released}, it releases the obtained
 * snapshot as well as calls {@link IndexWriter#deleteUnusedFiles()} so that the
 * snapshotted files are deleted (if they are no longer needed).
 *
 * @lucene.experimental
 */
public class IndexRevision implements Revision {

  private static final int RADIX = 16;
  private static final String SOURCE = "index";

  private final IndexWriter writer;
  private final IndexCommit commit;
  private final SnapshotDeletionPolicy sdp;
  private final String version;
  private final Map<String,List<RevisionFile>> sourceFiles;

  // returns a RevisionFile with some metadata
  private static RevisionFile newRevisionFile(String file, Directory dir) throws IOException {
    RevisionFile revFile = new RevisionFile(file);
    revFile.size = dir.fileLength(file);
    return revFile;
  }

  /** Returns a singleton map of the revision files from the given {@link IndexCommit}. */
  public static Map<String,List<RevisionFile>> revisionFiles(IndexCommit commit) throws IOException {
    Collection<String> commitFiles = commit.getFileNames();
    List<RevisionFile> revisionFiles = new ArrayList<>(commitFiles.size());
    String segmentsFile = commit.getSegmentsFileName();
    Directory dir = commit.getDirectory();

    for (String file : commitFiles) {
      if (!file.equals(segmentsFile)) {
        revisionFiles.add(newRevisionFile(file, dir));
      }
    }
    revisionFiles.add(newRevisionFile(segmentsFile, dir)); // segments_N must be last
    return Collections.singletonMap(SOURCE, revisionFiles);
  }

  /**
   * Returns a String representation of a revision's version from the given
   * {@link IndexCommit}.
   */
  public static String revisionVersion(IndexCommit commit) {
    return Long.toString(commit.getGeneration(), RADIX);
  }

  /**
   * Constructor over the given {@link IndexWriter}. Uses the last
   * {@link IndexCommit} found in the {@link Directory} managed by the given
   * writer.
   */
  public IndexRevision(IndexWriter writer) throws IOException {
    IndexDeletionPolicy delPolicy = writer.getConfig().getIndexDeletionPolicy();
    if (!(delPolicy instanceof SnapshotDeletionPolicy)) {
      throw new IllegalArgumentException("IndexWriter must be created with SnapshotDeletionPolicy");
    }
    this.writer = writer;
    this.sdp = (SnapshotDeletionPolicy) delPolicy;
    this.commit = sdp.snapshot();
    this.version = revisionVersion(commit);
    this.sourceFiles = revisionFiles(commit);
  }

  @Override
  public int compareTo(String version) {
    long gen = Long.parseLong(version, RADIX);
    long commitGen = commit.getGeneration();
    return commitGen < gen ? -1 : (commitGen > gen ? 1 : 0);
  }

  @Override
  public int compareTo(Revision o) {
    IndexRevision other = (IndexRevision) o;
    return commit.compareTo(other.commit);
  }

  @Override
  public String getVersion() {
    return version;
  }

  @Override
  public Map<String,List<RevisionFile>> getSourceFiles() {
    return sourceFiles;
  }

  @Override
  public InputStream open(String source, String fileName) throws IOException {
    assert source.equals(SOURCE) : "invalid source; expected=" + SOURCE + " got=" + source;
    return new IndexInputInputStream(commit.getDirectory().openInput(fileName, IOContext.READONCE));
  }

  @Override
  public void release() throws IOException {
    sdp.release(commit);
    writer.deleteUnusedFiles();
  }

  @Override
  public String toString() {
    return "IndexRevision version=" + version + " files=" + sourceFiles;
  }

}


text:
.widget__active {
	border: 1px solid #EF9A9A !important;
}