text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

require APPPATH . '/libraries/REST_Controller.php';

class SampleCtr extends REST_Controller {

    function SampleCtr()
    {
	parent::__construct();
	$this->load->model('SampleMod');
    }

   // Sample Date

	public function sampleAPI_post()
    {
        $result=$this->SampleMod->Saminsert();
		if($result==true){
			$this->set_response(['status' =>TRUE,'message'=>"Record Inserted Successfully"], REST_Controller::HTTP_CREATED);
		}else{
			$this->set_response(['status' =>FALSE,'message'=>"Failure"], REST_Controller::HTTP_CREATED);
		}
    }

	public function sampleAPI_get()
    {
		$id = $this->get('id');
		if($id==NULL){
			$users=$this->SampleMod->SamselectAll();
			if (!empty($users)){
				$this->set_response(['status' =>TRUE,'message'=>$users], REST_Controller::HTTP_OK); // OK (200) being the HTTP response code
			}
			else
			{
				$this->set_response([
				'status' => FALSE,
				'message' => 'Sample data could not be found'
				], REST_Controller::HTTP_NOT_FOUND); // NOT_FOUND (404) being the HTTP response code
			}
		}else{
			$user=$this->SampleMod->Samselect($id);
			if (!empty($user)){
				$this->set_response(['status' =>TRUE,'message'=>$user], REST_Controller::HTTP_OK); // OK (200) being the HTTP response code
			}
			else
			{
				$this->set_response([
				'status' => FALSE,
				'message' => 'Sample data could not be found'
				], REST_Controller::HTTP_NOT_FOUND); // NOT_FOUND (404) being the HTTP response code
			}
		}

    }

	 public function sampleAPI_delete()
    {
        $id = $this->delete('id');
        // // Validate the id.
        if ($id == null)
        {
            // Set the response and exit
            $this->response(['status'=>FALSE,'message'=>'No data Here'], REST_Controller::HTTP_BAD_REQUEST);
        }else{
			$result=$this->SampleMod->SamDelete($id);
			if($result!=0){
				$message = [
				'id' => $id,
				'message' => 'Deleted the resource'
				];
				$this->set_response(['status'=>TRUE,'message'=>$message], REST_Controller::HTTP_OK);
			}else{
				$this->set_response(['status'=>FALSE,'message'=>'There is no Record found'], REST_Controller::HTTP_NOT_FOUND);
			}
		}
    }
    public function addsampleData_post(){
    	$result=$this->SampleMod->addSampledata();
    	if($result==true){
    		echo "success";
    	}else {
    		echo "failed";
    	}
    }

	// Employee Category :

    function employeeCategory_post()
    {
    	$result=$this->SampleMod->addEmployeeCategory();
    	if($result==true){
			$this->set_response(['status' =>TRUE,'message'=>"Record Inserted Successfully"], REST_Controller::HTTP_CREATED);
		}else{
			$this->set_response(['status' =>FALSE,'message'=>"Failure"], REST_Controller::HTTP_CREATED);
		}
    }
	function employeeCategory_get(){
		$id=$this->get('id');
		if ($id == null){
			$result=$this->SampleMod->fetchCategoryDetails();
			foreach ($result as $cat) { ?>

					 <?php echo $cat['EMP_C_NAME'];?>
					<?php echo $cat['EMP_C_ACTIVE_YN'];?>
					<button type="button"  name="edit" id="edit" value="edit" class="btn btn-xs btn-primary" onclick="editCategory('<?php echo $cat['EMP_C_ID'];?>')" category-id="<?php echo $cat['EMP_C_ID'];?>"></button>
					<button type="button" category-id="<?php echo $cat['EMP_C_ID'];?>" onclick="deleteCategory('<?php echo $cat['EMP_C_ID'];?>')" id="delete" class="btn btn-xs btn-danger"></button>

			<?php }
		}else {
			$result=$this->SampleMod->getCategory_details($id);
    		echo json_encode($result);
		}
	}
    function employeeCategory_delete(){
    	$id=$this->delete('id');
    	$result=$this->SampleMod->deleteCategory($id);
    }

    function employeeCategory_put(){
    	$id=$this->put('id');
		$name=$this->put('name');
		$prefix=$this->put('prefix');
		$status=$this->put('status');
		$result=$this->SampleMod->updateCategory($id,$name,$prefix,$status);
		if($result==true){
			echo "success";
		}

    	// $mode=$this->put('mode');
    	// if($mode=='edit'){
    	// 	$id=$this->put('id');
    	// 	$name=$this->put('name');
    	// 	$prefix=$this->put('prefix');
    	// 	$status=$this->put('status');
    	// 	$result=$this->SampleMod->updateCategory($id,$name,$prefix,$status);
    	// 	if($result==true){
    	// 		echo "success";
    	// 	}
    	// }
    	// if($mode=='delete'){
    	// 	$id=$this->put('id');
    	// 	$result=$this->SampleMod->deleteCategory($id);
    	// }
    }

}


text:
@implementation MXThirdPartyProtocolInstance

+ (id)modelFromJSON:(NSDictionary *)JSONDictionary
{
    MXThirdPartyProtocolInstance *thirdpartyProtocolInstance = [[MXThirdPartyProtocolInstance alloc] init];
    if (thirdpartyProtocolInstance)
    {
        MXJSONModelSetString(thirdpartyProtocolInstance.networkId, JSONDictionary[@"network_id"]);
        MXJSONModelSetDictionary(thirdpartyProtocolInstance.fields, JSONDictionary[@"fields"]);
        MXJSONModelSetString(thirdpartyProtocolInstance.instanceId, JSONDictionary[@"instance_id"]);
        MXJSONModelSetString(thirdpartyProtocolInstance.desc, JSONDictionary[@"desc"]);
        MXJSONModelSetString(thirdpartyProtocolInstance.botUserId, JSONDictionary[@"bot_user_id"]);
        MXJSONModelSetString(thirdpartyProtocolInstance.icon, JSONDictionary[@"icon"]);
    }

    return thirdpartyProtocolInstance;
}

@end

redpajama_set_name: RedPajamaGithub


text:
function scaleToWindow(canvas, backgroundColor) {

  backgroundColor = backgroundColor || "#2C3539";
  var scaleX, scaleY, scale, center;

  //1. Scale the canvas to the correct size
  //Figure out the scale amount on each axis
  scaleX = window.innerWidth / canvas.offsetWidth;
  scaleY = window.innerHeight / canvas.offsetHeight;

  //Scale the canvas based on whichever value is less: `scaleX` or `scaleY`
  scale = Math.min(scaleX, scaleY);
  canvas.style.transformOrigin = "0 0";
  canvas.style.transform = "scale(" + scale + ")";
  //console.log(scaleX)

  //2. Center the canvas.
  //Decide whether to center the canvas vertically or horizontally.
  //Wide canvases should be centered vertically, and
  //square or tall canvases should be centered horizontally
  if (canvas.offsetwidth > canvas.offsetHeight) {
    if (canvas.offsetWidth * scale < window.innerWidth) {
      center = "horizontally";
    } else {
      center = "vertically";
    }
  } else {
    if (canvas.offsetHeight * scale < window.innerHeight) {
      center = "vertically";
    } else {
      center = "horizontally";
    }
  }

  //Center horizontally (for square or tall canvases)
  var margin;
  if (center === "horizontally") {
    margin = (window.innerWidth - canvas.offsetWidth * scale) / 2;
    canvas.style.marginTop = 0;
    canvas.style.marginBottom = 0;
    canvas.style.marginLeft = margin + "px";
    canvas.style.marginRight = margin + "px";
  }

  //Center vertically (for wide canvases)
  if (center === "vertically") {
    margin = (window.innerHeight - canvas.offsetHeight * scale) / 2;
    canvas.style.marginTop = margin + "px";
    canvas.style.marginBottom = margin + "px";
    canvas.style.marginLeft = 0;
    canvas.style.marginRight = 0;
  }

  //3. Remove any padding from the canvas  and body and set the canvas
  //display style to "block"
  canvas.style.paddingLeft = 0;
  canvas.style.paddingRight = 0;
  canvas.style.paddingTop = 0;
  canvas.style.paddingBottom = 0;
  canvas.style.display = "block";

  //4. Set the color of the HTML body background
  document.body.style.backgroundColor = backgroundColor;

  //Fix some quirkiness in scaling for Safari
  var ua = navigator.userAgent.toLowerCase();
  if (ua.indexOf("safari") != -1) {
    if (ua.indexOf("chrome") > -1) {
      // Chrome
    } else {
      // Safari
      //canvas.style.maxHeight = "100%";
      //canvas.style.minHeight = "100%";
    }
  }

  //5. Return the `scale` value. This is important, because you'll nee this value
  //for correct hit testing between the pointer and sprites
  return scale;
}


text:
package model.scenario;

import agents.firm.Firm;
import agents.firm.sales.SalesDepartment;
import agents.firm.sales.SalesDepartmentAllAtOnce;
import agents.firm.sales.SalesDepartmentFactory;
import agents.firm.sales.SalesDepartmentOneAtATime;
import agents.firm.sales.exploration.SimpleBuyerSearch;
import agents.firm.sales.exploration.SimpleSellerSearch;
import agents.firm.sales.pricing.AskPricingStrategy;
import agents.firm.sales.pricing.pid.SimpleFlowSellerPID;
import au.com.bytecode.opencsv.CSVWriter;
import com.google.common.base.Preconditions;
import financial.market.OrderBookMarket;
import financial.utilities.ShopSetPricePolicy;
import goods.UndifferentiatedGoodType;
import model.MacroII;
import model.utilities.ActionOrder;
import model.utilities.dummies.Customer;
import model.utilities.dummies.CustomerWithDelay;
import model.utilities.stats.collectors.DailyStatCollector;
import sim.engine.SimState;
import sim.engine.Steppable;

import java.io.FileWriter;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;

import static model.experiments.tuningRuns.MarginalMaximizerPIDTuning.printProgressBar;

/**
 *
Description

 *
 This is actually a copy of scenario1 for the test class SimpleFlowSellerPIDTest.
 * Very simple matching of supply and demand
 *
 Basically we periodically
 * create new buyers (after removing the old ones) to give the impression of a constant demand and let the
 * flow seller get to the right price
 *

 *
Notes

 * Created with IntelliJ
 *

 *

 *
References

 *
 * @author Ernesto
 * @version 2012-09-10
 * @see
 */
public class SimpleSellerScenario extends Scenario {

    private boolean demandShifts = false;

    /**
     * when this is >0 the demand responds to prices quoted "buyerDelay" days ago rather than current prices.
     */
    private int buyerDelay = 0;

    /**
     * the strategy used by the sales department to tinker with prices
     */
    private Class<? extends AskPricingStrategy> sellerStrategy = SimpleFlowSellerPID.class;

    /**
     * The kind of sales department to use
     */
    protected Class<? extends SalesDepartment> salesDepartmentType = SalesDepartmentAllAtOnce.class;

    /**
     * number of sellers in the model
     */
    protected int numberOfSellers = 1;

    /**
     * How many goods the seller receives every day
     */
    private int inflowPerSeller = 4;

    /**
     * If there is a demand shift, when will it appear?
     */
    public int howManyDaysLaterShockWillOccur = 2000;

    private int demandIntercept = 100;

    private int demandSlope = -10;

    private List<SalesDepartment> departments = new LinkedList<>();

    private List<AskPricingStrategy> pricingStrategies = new LinkedList<>();

    /**
     * when this is set to true during the production phase all previously unsold inventory is destroyed
     */
    private boolean destroyUnsoldInventoryEachDay = false;

    /**
     * how much inflow each firm gets
     */
    private LinkedHashMap<Firm, Integer> sellerToInflowMap = new LinkedHashMap< >();

    /**
     * the strategy used by the seller, after it has been instantiated
     */
    protected AskPricingStrategy strategy;

    /**
     * Called by MacroII, it creates agents and then schedules them.
     */
    @Override
    public void start() {

        departments = new LinkedList<>();
        pricingStrategies = new LinkedList<>();

        //create and record a new market!
        final OrderBookMarket market= new OrderBookMarket(UndifferentiatedGoodType.GENERIC);
        market.setPricePolicy(new ShopSetPricePolicy()); //make the seller price matter

        getMarkets().put(UndifferentiatedGoodType.GENERIC,market);

        //create sellers
        for(int i=0; i < numberOfSellers; i++)
        {
            final Firm seller = buildSeller(market);
            //arrange for goods to drop periodically in the firm
            setupProduction(seller);
        }

        //create demand
        int i=1;
        while(demandIntercept + i*demandSlope>0){
            buildBuyer(market, demandIntercept + i*demandSlope);
            i++;
        }

        //if demands shifts, add 10 more buyers after adjust 2000
        if(demandShifts)
        {
            //create 10 buyers
            for(i=0;i<10;i++){
                createAdditionalBuyer(market, i);

            }
        }

        //hopefully that's that!

    }

    private void createAdditionalBuyer(final OrderBookMarket market, final int i) {
        /**
         * For this scenario we use a different kind of dummy buyer that, after "period" passed, puts a new order in the market
         */
        model.scheduleAnotherDay(ActionOrder.DAWN,new Steppable() {
            @Override
            public void step(SimState state) {
                if(buyerDelay == 0)
                {
                    final Customer customer = new Customer(getModel(),(i+10)*10,market);
                    model.addAgent(customer);
                }
                else
                {
                    assert buyerDelay > 0;
                    CustomerWithDelay delay = new CustomerWithDelay(model,(i+10)*10,buyerDelay,market);
                    model.addAgent(delay);
                }
            }},howManyDaysLaterShockWillOccur);

    }

    private void setupProduction(final Firm seller) {
        sellerToInflowMap.put(seller,inflowPerSeller);
        getModel().scheduleSoon(ActionOrder.PRODUCTION,new Steppable() {
            @Override
            public void step(SimState simState) {
                if(destroyUnsoldInventoryEachDay)
                    seller.consumeAll();

                //sell 4 goods!
                int inflow = sellerToInflowMap.get(seller);
                seller.receiveMany(UndifferentiatedGoodType.GENERIC,inflow);
                seller.reactToPlantProduction(UndifferentiatedGoodType.GENERIC,inflow);

                //every day
                getModel().scheduleTomorrow(ActionOrder.PRODUCTION,this);
            }
        });
    }

    protected Firm buildSeller(final OrderBookMarket market) {
        final Firm seller = new Firm(getModel());
        getAgents().add(seller);

        SalesDepartment dept = SalesDepartmentFactory.incompleteSalesDepartment(seller, market, new SimpleBuyerSearch(market, seller),
                new SimpleSellerSearch(market, seller), salesDepartmentType);
        seller.registerSaleDepartment(dept, UndifferentiatedGoodType.GENERIC);

        strategy = AskPricingStrategy.Factory.newAskPricingStrategy(sellerStrategy,dept);

        //strategy.setSpeed(sellerDelay);
        dept.setAskPricingStrategy(strategy); //set strategy to PID

        departments.add(dept);
        pricingStrategies.add(strategy);

        return seller;
    }

    protected void buildBuyer(final OrderBookMarket market, final int price) {
        if(buyerDelay == 0 )
        {
            final Customer buyer = new Customer(getModel(),Math.max((price),1),market);
            getAgents().add(buyer);
        }
        else
        {
            CustomerWithDelay delay = new CustomerWithDelay(model,Math.max((price),1),buyerDelay,market);
            getAgents().add(delay);
        }
    }

    /**
     * Creates the scenario object, so that it links to the model.
     * =
     */
    public SimpleSellerScenario(MacroII model) {
        super(model);
    }

    public boolean isDemandShifts() {
        return demandShifts;
    }

    public void setDemandShifts(boolean demandShifts) {
        this.demandShifts = demandShifts;
    }

    /**
     * Gets the strategy used by the sales department to tinker with prices.
     *
     * @return Value of the strategy used by the sales department to tinker with prices.
     */
    public Class<? extends AskPricingStrategy> getSellerStrategy() {
        return sellerStrategy;
    }

    /**
     * Sets new the strategy used by the sales department to tinker with prices.
     *
     * @param sellerStrategy New value of the strategy used by the sales department to tinker with prices.
     */
    public void setSellerStrategy(Class<? extends AskPricingStrategy> sellerStrategy) {
        this.sellerStrategy = sellerStrategy;
    }

    /**
     * Gets The kind of sales department to use.
     *
     * @return Value of The kind of sales department to use.
     */
    public Class<? extends SalesDepartment> getSalesDepartmentType() {
        return salesDepartmentType;
    }

    /**
     * Sets new The kind of sales department to use.
     *
     * @param salesDepartmentType New value of The kind of sales department to use.
     */
    public void setSalesDepartmentType(Class<? extends SalesDepartment> salesDepartmentType) {
        this.salesDepartmentType = salesDepartmentType;
    }

    public int getBuyerDelay() {
        return buyerDelay;
    }

    public void setBuyerDelay(int buyerDelay) {
        Preconditions.checkArgument(buyerDelay >=0);
        this.buyerDelay = buyerDelay;
    }

    /**
     * Gets How many goods the seller receives every day.
     *
     * @return Value of How many goods the seller receives every day.
     */
    public int getInflowPerSeller() {
        return inflowPerSeller;
    }

    /**
     * Sets new number of sellers in the model.
     *
     * @param numberOfSellers New value of number of sellers in the model.
     */
    public void setNumberOfSellers(int numberOfSellers) {
        this.numberOfSellers = numberOfSellers;
    }

    /**
     * Gets number of sellers in the model.
     *
     * @return Value of number of sellers in the model.
     */
    public int getNumberOfSellers() {
        return numberOfSellers;
    }

    /**
     * Sets new How many goods the seller receives every day.
     *
     * @param inflowPerSeller New value of How many goods the seller receives every day.
     */
    public void setInflowPerSeller(int inflowPerSeller) {
        this.inflowPerSeller = inflowPerSeller;
    }

    /**
     * Runs the simple seller scenario with no GUI and writes a big CSV file  (to draw graphs for the paper)
     * @param args
     */
    public static void main(String[] args)
    {

        //do it 10 times
        for(int i=0; i<10;i++)
        {

            //set up
            final MacroII macroII = new MacroII(i);
            macroII.getRandom().setSeed(i);
            SimpleSellerScenario scenario1 = new SimpleSellerScenario(macroII);
            scenario1.setSalesDepartmentType(SalesDepartmentOneAtATime.class);
            scenario1.setSellerStrategy(SimpleFlowSellerPID.class);
            scenario1.setDemandShifts(true);
            scenario1.setHowManyDaysLaterShockWillOccur(500);

            //assign scenario
            macroII.setScenario(scenario1);

            macroII.start();

            //CSV writer set up
            try {
                CSVWriter writer = new CSVWriter(new FileWriter("runs/simpleSeller/"+"simpleSellerShock"+i +".csv"));
                DailyStatCollector collector = new DailyStatCollector(macroII,writer);
                collector.start();

            } catch (IOException e) {
                System.err.println("failed to create the file!");
            }

            //run!
            while(macroII.schedule.getTime()<1000)
            {
                macroII.schedule.step(macroII);
                printProgressBar(1001,(int)macroII.schedule.getSteps(),100);
            }

        }

    }

    /**
     * If there is a demand shift, when will it appear?.
     *
     * @return Value of If there is a demand shift, when will it appear?.
     */
    public int getHowManyDaysLaterShockWillOccur() {
        return howManyDaysLaterShockWillOccur;
    }

    /**
     * Sets new If there is a demand shift, when will it appear?.
     *
     * @param howManyDaysLaterShockWillOccur New value of If there is a demand shift, when will it appear?.
     */
    public void setHowManyDaysLaterShockWillOccur(int howManyDaysLaterShockWillOccur) {
        this.howManyDaysLaterShockWillOccur = howManyDaysLaterShockWillOccur;
    }

    public int getDemandIntercept() {
        return demandIntercept;
    }

    public void setDemandIntercept(int demandIntercept) {
        this.demandIntercept = demandIntercept;
    }

    public int getDemandSlope() {
        return demandSlope;
    }

    public void setDemandSlope(int demandSlope) {
        Preconditions.checkArgument(demandSlope <= 0, "slope can't be positive.");
        this.demandSlope = demandSlope;
    }

    public List<SalesDepartment> getDepartments() {
        return departments;
    }

    public LinkedHashMap<Firm, Integer> getSellerToInflowMap() {
        return sellerToInflowMap;
    }

    public boolean isDestroyUnsoldInventoryEachDay() {
        return destroyUnsoldInventoryEachDay;
    }

    public void setDestroyUnsoldInventoryEachDay(boolean destroyUnsoldInventoryEachDay) {
        this.destroyUnsoldInventoryEachDay = destroyUnsoldInventoryEachDay;
    }

    public List<AskPricingStrategy> getPricingStrategies() {
        return pricingStrategies;
    }
}


text:
package com.borealkiss.voronoi.debug;
import java.util.ArrayList;

import processing.core.PApplet;

import com.borealkiss.dragon.geom.Point;
import com.borealkiss.dragon.model.DragonCurveGenerator;
import com.borealkiss.dragon.model.Generator;
import com.borealkiss.dragon.util.Recursion;
import com.borealkiss.voronoi.data.Event;

public class TestDrawer2 extends TestDrawer {
	Generator[] _gens = null;

	/**
	 * Constructor.
	 */
	public TestDrawer2(PApplet p){
		super(p);
	}

	@Override
	protected Event[] _createEvents() {
		_gens = this._createGens();
		_gens = Recursion.generateRecursively(_gens, 3);

		ArrayList<Event> list = new ArrayList<Event>();
		int index = 0;

		for (Generator gen: _gens){
			double x = 0.5 * (gen.getOrigin().getX() + gen.getDestination().getX());
			double y = 0.5 * (gen.getOrigin().getY() + gen.getDestination().getY());
			Event event = new Event(x, y);
			event.setIndex(index++);
			list.add(event);
		}

		Event[] events = new Event[list.size()];
		list.toArray(events);

		return events;
	}

	protected Generator[] _createGens() {
		double w = _applet.width;
		double h = _applet.height;
		double dw = 0.25 * w;
		double dh = 0.25 * h;

		Point p0 = new Point(dw, h - dh);
		Point p1 = new Point(w - dw, dh);
		Generator g0 = new DragonCurveGenerator(p0, p1);
		Generator[] gens = {g0};
		return gens;
	}
}


text:
<?php

namespace Dscorp\AdminBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Tema
 */
class Tema
{
    /**
     * @var integer
     */
    private $id;

    /**
     * @var string
     */
    private $nombreTema;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set nombreTema
     *
     * @param string $nombreTema
     * @return Tema
     */
    public function setNombreTema($nombreTema)
    {
        $this->nombreTema = $nombreTema;

        return $this;
    }

    /**
     * Get nombreTema
     *
     * @return string
     */
    public function getNombreTema()
    {
        return $this->nombreTema;
    }
    /**
     * @var \Doctrine\Common\Collections\Collection
     */
    private $subtema;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->subtema = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Add subtema
     *
     * @param \Dscorp\AdminBundle\Entity\subtema $subtema
     * @return Tema
     */
    public function addSubtema(\Dscorp\AdminBundle\Entity\Subtema $subtema)
    {
        $this->subtema[] = $subtema;

        return $this;
    }

    /**
     * Remove subtema
     *
     * @param \Dscorp\AdminBundle\Entity\subtema $subtema
     */
    public function removeSubtema(\Dscorp\AdminBundle\Entity\Subtema $subtema)
    {
        $this->subtema->removeElement($subtema);
    }

    /**
     * Get subtema
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getSubtema()
    {
        return $this->subtema;
    }

    public function __toString(){
        return $this->nombreTema;
    }
    /**
     * @var \Dscorp\AdminBundle\Entity\Idioma
     */
    private $idioma;

    /**
     * Set idioma
     *
     * @param \Dscorp\AdminBundle\Entity\Idioma $idioma
     * @return Tema
     */
    public function setIdioma(\Dscorp\AdminBundle\Entity\Idioma $idioma = null)
    {
        $this->idioma = $idioma;

        return $this;
    }

    /**
     * Get idioma
     *
     * @return \Dscorp\AdminBundle\Entity\Idioma
     */
    public function getIdioma()
    {
        return $this->idioma;
    }
}


text:
/**
 * Spanwer for spawning processes, threads, docker containers to execute functions.
 */
package org.apache.pulsar.functions.metrics;


text:
extensions = [
    'sphinx.ext.autodoc',
    'sphinx.ext.napoleon'
]
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'builtin_codec'
copyright = u'2015, builtin_codec authors'
author = u'builtin_codec authors'
version = '0.0.1'
release = '0.0.1'
language = None
exclude_patterns = ['_build']
pygments_style = 'sphinx'
todo_include_todos = False
html_theme = 'alabaster'
html_static_path = ['_static']
htmlhelp_basename = 'builtin_codecdoc'
latex_elements = {}
latex_documents = [
    (master_doc, 'builtin_codec.tex', u'builtin_codec Documentation',
     u'builtin_codec authors', 'manual'),
]
man_pages = [
    (master_doc, 'builtin_codec', u'builtin_codec Documentation',
     [author], 1)
]
texinfo_documents = [
    (master_doc, 'builtin_codec', u'builtin_codec Documentation',
     author, 'builtin_codec', 'One line description of builtin_codec.',
     'Miscellaneous'),
]


text:
class Server{
	constructor(){
		this.sock = require('dgram').createSocket('udp4');
		this.sock.on('message',(msg,rinfo)=>{this.onPacket(msg,rinfo);});
		this.sock.bind(1234,()=>{
			console.log("Server is listening...")
			this.loop();
		});
	}
	loop(){
		this.broadcastPresence();
		setTimeout(()=>{ this.loop(); }, 1000);
	}
	onPacket(packet,rinfo){
		console.log("packet from " + rinfo.address +":"+rinfo.port+" : "+ packet);
	}
	broadcastPresence(){
		const buff = new Buffer("Joe's mediocre server is over there.");
		this.sock.send(buff,0,buff.length,1234,"10.252.20.255");
	}
}

new Server();


text:
import pytest
import os
from lxml import etree
import datetime

from codalib.xsdatetime import xsDateTime_format

from . import factories

SCHEMA_DIR = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'schema')

class EventTestXML(object):

    def __init__(self):
        self.attributes = factories.EventFactory.attributes()
        self.identifier = self.attributes['event_identifier']
        self._link_object_attributes = factories.LinkObjectFactory.attributes()

    @property
    def entry_xml(self):
        xml = """<?xml version="1.0"?>
            <entry xmlns="http://www.w3.org/2005/Atom">
              <title>{event_identifier}</title>
              <id>{event_identifier}</id>
              <updated>2015-10-02T19:59:22Z</updated>
              <content type="application/xml">
                <premis:event xmlns:premis="info:lc/xmlns/premis-v2">
                  <premis:eventDetail>{event_detail}</premis:eventDetail>
                  <premis:eventOutcomeInformation>
                    <premis:eventOutcomeDetail>{event_outcome_detail}</premis:eventOutcomeDetail>
                    <premis:eventOutcome>{event_outcome}</premis:eventOutcome>
                  </premis:eventOutcomeInformation>
                  <premis:eventType>{event_type}</premis:eventType>
                  <premis:linkingAgentIdentifier>
                    <premis:linkingAgentIdentifierValue>{linking_agent_identifier_value}</premis:linkingAgentIdentifierValue>
                    <premis:linkingAgentIdentifierType>{linking_agent_identifier_type}</premis:linkingAgentIdentifierType>
                  </premis:linkingAgentIdentifier>
                  <premis:eventIdentifier>
                      <premis:eventIdentifierValue>{event_identifier}</premis:eventIdentifierValue>
                    <premis:eventIdentifierType>{event_identifier_type}</premis:eventIdentifierType>
                  </premis:eventIdentifier>
                  <premis:eventDateTime>{event_date_time}</premis:eventDateTime>
                  {linking_objects}
                </premis:event>
              </content>
            </entry>
        """
        if isinstance(self.attributes['event_date_time'], datetime.datetime):
            self.attributes['event_date_time'] = xsDateTime_format(
                self.attributes['event_date_time']
            )
        return xml.format(
                linking_objects=self._linking_objects_xml(),
                **self.attributes)

    @property
    def obj_xml(self):
        xml = """<?xml version="1.0"?>
            <premis:event xmlns:premis="info:lc/xmlns/premis-v2">
                <premis:eventIdentifier>
                    <premis:eventIdentifierType>{event_identifier_type}</premis:eventIdentifierType>
                    <premis:eventIdentifierValue>{event_identifier}</premis:eventIdentifierValue>
                </premis:eventIdentifier>
                <premis:eventType>{event_type}</premis:eventType>
                <premis:eventDateTime>{event_date_time}</premis:eventDateTime>
                <premis:eventDetail>{event_detail}</premis:eventDetail>
                <premis:eventOutcomeInformation>
                    <premis:eventOutcome>{event_outcome}</premis:eventOutcome>
                    <premis:eventOutcomeDetail>
                        <premis:eventOutcomeDetailNote>{event_outcome_detail}</premis:eventOutcomeDetailNote>
                    </premis:eventOutcomeDetail>
                </premis:eventOutcomeInformation>
                <premis:linkingAgentIdentifier>
                    <premis:linkingAgentIdentifierType>{linking_agent_identifier_type}</premis:linkingAgentIdentifierType>
                    <premis:linkingAgentIdentifierValue>{linking_agent_identifier_value}</premis:linkingAgentIdentifierValue>
                </premis:linkingAgentIdentifier>
                {linking_objects}
            </premis:event>
        """
        self.attributes["event_date_time"] = xsDateTime_format(
            self.attributes["event_date_time"]
        )
        return xml.format(
                linking_objects=self._linking_objects_xml(),
                **self.attributes)

    def _linking_objects_xml(self):
        template = """<premis:linkingObjectIdentifier>
            <premis:linkingObjectIdentifierType>{object_type}</premis:linkingObjectIdentifierType>
            <premis:linkingObjectIdentifierValue>{object_identifier}</premis:linkingObjectIdentifierValue>
            <premis:linkingObjectRole>{object_role}</premis:linkingObjectRole>
        </premis:linkingObjectIdentifier>
        """
        return template.format(**self._link_object_attributes)

class AgentTestXML(object):

    def __init__(self):
        self.attributes = factories.AgentFactory.attributes()
        self.identifier = self.attributes['agent_identifier']

    @property
    def obj_xml(self):
        xml = """<?xml version="1.0"?>
            <premis:agent xmlns:premis="info:lc/xmlns/premis-v2">
              <premis:agentIdentifier>
                <premis:agentIdentifierType>PES:Agent</premis:agentIdentifierType>
                <premis:agentIdentifierValue>{agent_identifier}</premis:agentIdentifierValue>
              </premis:agentIdentifier>
              <premis:agentName>{agent_name}</premis:agentName>
              <premis:agentType>{agent_type}</premis:agentType>
              <premis:agentNote>{agent_note}</premis:agentNote>
            </premis:agent>
        """
        return xml.format(**self.attributes)

@pytest.fixture
def event_xml():
    """Provides XML representing an Event object.

    The XML is created using factories.EventFactory. Every instantiation
    provides random data using the EventFactory.attributes() method.

    The object provides three public properties.

    identifer: The identifier of the Event object the XML represents.
    obj_xml: The object xml.
    entry_xml: The object xml wrapped in an AtomPub entry.
    """
    return EventTestXML()

@pytest.fixture
def agent_xml():
    """Provides XML representing an Agent object.

    The XML is created using factories.AgentFactory. Every instantiation
    provides random data using the AgentFactory.attributes() method.

    The object provides two public properties.

    identifer: The identifier of the Agent object the XML represents.
    obj_xml: The object xml.
    """
    return AgentTestXML()

@pytest.fixture
def premis_schema():
    """Provides an lxml schema object for the Premis v2 XSD suitable
    for validation.
    """
    with open(os.path.join(SCHEMA_DIR, "premis-v2-3.xsd")) as schema_file:
        schema_doc = etree.parse(schema_file)
        schema = etree.XMLSchema(schema_doc)
    return schema


text:
from django.contrib import admin
from django import forms
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _

class FilteredSelectMultiple(forms.SelectMultiple):
    """
    A SelectMultiple with a JavaScript filter interface.

    Note that the resulting JavaScript assumes that the SelectFilter2.js
    library and its dependencies have been loaded in the HTML page.
    """
    def _media(self):
        from django.conf import settings
        js = ['js/SelectBox.js' , 'js/SelectFilter2.js']
        return forms.Media(js=['%s%s' % (settings.ADMIN_MEDIA_PREFIX, url) for url in js])
    media = property(_media)

    def __init__(self, verbose_name, is_stacked, attrs=None, choices=()):
        self.verbose_name = verbose_name
        self.is_stacked = is_stacked
        super(FilteredSelectMultiple, self).__init__(attrs, choices)

    def render(self, name, value, attrs=None, choices=()):
        from django.conf import settings
        output = [super(FilteredSelectMultiple, self).render(name, value, attrs, choices)]
        output.append(u'<script type="text/javascript">addEvent(window, "load", function(e) {')
        # TODO: "id_" is hard-coded here. This should instead use the correct
        # API to determine the ID dynamically.
        output.append(u'SelectFilter.init("id_%s", "%s", %s, "%s"); });</script>\n' % \
            (name, self.verbose_name.replace('"', '\\"'), int(self.is_stacked), settings.ADMIN_MEDIA_PREFIX))
        return mark_safe(u''.join(output))

class TaggableModelForm(forms.ModelForm):
    tags = forms.MultipleChoiceField(label=_('tags').capitalize(), required=True, widget=FilteredSelectMultiple(_('tags'), False))

    def __init__(self, *args, **kwargs):
        if 'instance' in kwargs:
            if 'initial' not in kwargs:
                kwargs['initial'] = {}
            kwargs['initial']['tags'] = [tag.id for tag in self.tag_model.objects.get_for_object(kwargs['instance'])]
        super(TaggableModelForm, self).__init__(*args, **kwargs)
        self.fields['tags'].choices = [(tag.id, tag.name) for tag in self.tag_model.objects.all()]

    def save(self, commit):
        obj = super(TaggableModelForm, self).save()
        tag_ids = self.cleaned_data['tags']
        tags = self.tag_model.objects.filter(pk__in=tag_ids)
        self.tag_model.objects.update_tags(obj, tags)
        return obj

    def save_m2m(self):
        # TODO: Shouldn't be needed
        pass

class TaggableModelAdmin(admin.ModelAdmin):
    form = TaggableModelForm

    def get_form(self, request, obj=None):
        form = super(TaggableModelAdmin, self).get_form(request, obj)
        form.tag_model = self.tag_model
        return form


text:
Override the method for this form.

    String, default = null

Only used when not null, otherwise set based on w2utils.settings.dataType.


text:
This example configures a project-level log sink that feeds a storage bucket destination

<!-- BEGINNING OF PRE-COMMIT-TERRAFORM DOCS HOOK -->
## Inputs

| Name | Description | Type | Default | Required |
|------|-------------|------|---------|:--------:|
| parent\_resource\_id | The ID of the project in which storage bucket destination will be created. | `string` | n/a | yes |
| project\_id | The ID of the project in which the log export will be created. | `string` | n/a | yes |

## Outputs

| Name | Description |
|------|-------------|
| destination\_map | Outputs from the destination module |
| log\_export\_map | Outputs from the log export module |

<!-- END OF PRE-COMMIT-TERRAFORM DOCS HOOK -->


text:
<?php
/**
 * This is a WebbTemp pagecontroller.
 *
 */
// Include the essential config-file which also creates the $webbtemp variable with its defaults.
include(__DIR__.'/config.php');

$roll = null;
	if(isset($_POST["kast"])) {
		$roll = $_POST["kast"];
	}

	if($roll > 20) {
	$html = "
Du har gjort för många kast, var god försök med färre kast";
	$roll = 0;
	}
	else if($roll > 0){
	$dice = new CDice();
	$dice->Roll($roll);
	$html = "
Du gjorde {$roll} kast och fick följande resultat.
\n
";
		foreach($dice->GetResults() as $val) {
			$html .= "\n
{$val}
";
		}
	$html .= "\n
\n";
	$html .= "
Totalt fick du " . $dice->GetTotal() . " poäng på dina kast.
";
	}else{
	$html = null;
	}

// Do it and store it all in variables in the WebbTemp container.
$webbtemp['title'] = "Tärnings kastning";

$webbtemp['header'] = <<<EOD

Tärnings kastning
Hur mycket poäng kan du få?
EOD;

$webbtemp['main'] = <<<EOD

Kasta tärning

Detta är en exempelsida som visar hur WebbTemp fungerar tillsammans med återanvändbara moduler.

Hur många kast vill du göra,
<form method = 'POST' action = 'dice.php'>
        <input type = 'text' name = 'kast' size = '1' >
        <input type = 'submit' value = 'Kasta' name="submit">
</form> {$html}

EOD;

$webbtemp['footer'] = <<<EOD

 Copyright (c) Mattias Rosengren

Unicorn

EOD;

// Finally, leave it all to the rendering phase of WebbTemp.
include(WEBBTEMP_THEME_PATH);


text:
package com.navercorp.pinpoint.web.filter.responsetime;

import com.navercorp.pinpoint.web.filter.ExecutionType;
import com.navercorp.pinpoint.web.filter.visitor.SpanVisitor;

import java.util.Objects;

/**
 * @author Woonduk Kang(emeroad)
 */
public class DefaultExecutionTypeFilter implements ExecutionTypeFilter {

    private final ExecutionType executionType;

    public static ExecutionTypeFilter newExecutionTypeFilter(Boolean includeException) {
        final ExecutionType executionType = getExecutionType(includeException);
        return new DefaultExecutionTypeFilter(executionType);

    }

    private static ExecutionType getExecutionType(Boolean includeException) {
        if (includeException == null) {
            return ExecutionType.ALL;
        }
        if (includeException) {
            return ExecutionType.FAIL_ONLY;
        }
        return ExecutionType.SUCCESS_ONLY;
    }

    public DefaultExecutionTypeFilter(ExecutionType executionType) {
        this.executionType = Objects.requireNonNull(executionType, "executionType");
    }

    @Override
    public boolean accept(boolean hasError) {
        switch (executionType) {
            case ALL: {
                return SpanVisitor.ACCEPT;
            }
            case FAIL_ONLY: {
                // is error
                if (hasError) {
                    return SpanVisitor.ACCEPT;
                }
                return SpanVisitor.REJECT;
            }
            case SUCCESS_ONLY: {
                // is success
                if (hasError == false) {
                    return SpanVisitor.ACCEPT;
                }
                return SpanVisitor.REJECT;
            }
            default: {
                throw new UnsupportedOperationException("Unsupported ExecutionType:" + executionType);
            }
        }
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("DefaultExecutionErrorFilter{");
        sb.append("executionType=").append(executionType);
        sb.append('}');
        return sb.toString();
    }
}