text:
module.exports = StatisticsPacket;
function StatisticsPacket() {
  this.message      = undefined;
}

StatisticsPacket.prototype.parse = function(parser) {
  this.message      = parser.parsePacketTerminatedString();

  var items = this.message.split(/\s\s/);
  for (var i = 0; i < items.length; i++) {
    var m = items[i].match(/^(.+)\:\s+(.+)$/);
    if (m !== null) {
      this[m[1].toLowerCase().replace(/\s/g, '_')] = Number(m[2]);
    }
  }
};

StatisticsPacket.prototype.write = function(writer) {
  writer.writeString(this.message);
};

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<project name="no-testcoverage">
<!--
    Fallback testcoverage implementation.
    Just fails with appropriate message.
-->
    <target name="coverage-report">
        <fail>
No test coverage implementation found in ${harness.dir}.
        </fail>
    </target>
</project>


text:
/* Base
----------------------------------*/
BODY { margin: 0px; padding: 0px; background-color: #FFF; font-family: helvetica; font-size: 12px; }
/* Firefox alignment hack */
BODY { text-align: -moz-center; }
TABLE { width: 100%; background: #FFF url("../images/menu_links_bg.png"); }
THEAD, .strong { font-weight: bold; }

.data, .label { overflow: hidden; }

BR { display: none; }
A { text-decoration: none; cursor: hand; cursor: pointer; }
.dialog, .hidden { display: none; }

.clear { clear: both; }
.invisible { margin: 0px; padding: 0px; }
.show-line-breaks BR { display: block; }

/* Columns
----------------------------------*/
.even-columns-2 { width: 50%; }
.even-columns-3 { width: 33%; }
.even-columns-4 { width: 25%; }
.even-columns-5 { width: 20%; }

/* Icons
----------------------------------*/
.icon { display: block; text-indent: -99999px; overflow: hidden; background-repeat: no-repeat; background-image: url('../images/icons.png'); }

.icon-rss { width: 30px; height: 30px; background-position: 0px 0px; }
.icon-refresh { width: 30px; height: 30px; background-position: -30px 0px; }
.icon-reload { width: 30px; height: 30px; background-position: -30px 0px; }
.icon-large-logout { width: 30px; height: 30px; background-position: -60px 0px; }

.icon-show-sections { width: 24px; height: 24px; background-position: 0px -30px; }
.icon-hide-sections { width: 24px; height: 24px; background-position: -24px -30px; }
.icon-show-errors { width: 24px; height: 24px; background-position: -48px -30px; }

.icon-change-password { width: 19px; height: 19px; background-position: 0px -54px; }
.icon-logout { width: 19px; height: 19px; background-position: -19px -54px; }
.icon-login { width: 19px; height: 19px; background-position: -38px -54px; }

.icon-large-up-arrow { width: 13px; height: 30px; background-position: 0px -73px; }
.icon-large-down-arrow { width: 13px; height: 30px; background-position: -13px -73px; }

.icon-small-up-arrow { width: 7px; height: 10px; background-position: 0px -103px; }
.icon-small-down-arrow { width: 7px; height: 10px; background-position: -10px -103px; }

/* Forms
----------------------------------*/
FORM { display: inline; margin: 0px; padding: 0px; border: none; vertical-align: baseline; }
INPUT { padding: 3px; border: none; background-color: #3b3a3a; color: #ededed; }
INPUT[type="submit"], INPUT[type="button"] { font-weight: bold; cursor: hand; cursor: pointer; }
INPUT[type="hidden"] { display: none; }
INPUT.invalid { background-color: #ce2a1b; }

/* Messaging
----------------------------------*/
.message { position: absolute; top: 0px; left: 0px; width: 100%; height: 40px; margin: 0px; color: #ededed; font-weight: bold; font-size: 20px; text-align: center; cursor: hand; cursor: pointer; }
.message SPAN { display: inline-block; margin-top: 5px; }
.message A { color: #FFFFFF; text-decoration: underline; }
.message INPUT[type="submit"], .message INPUT[type="button"] { margin: 6px; float: right; border: 1px solid #ededed; background-color: transparent; color: #ededed; font-weight: bold; cursor: hand; cursor: pointer; }

/* Dialogs
----------------------------------*/
.dialog OL { text-align: left; }

/* Selectbox
----------------------------------*/
.selection { float: left; width: 100%; padding: 0px; background-color: #3b3a3a; border-top: 1px dashed #FFF; }
.selection-data { width: 100%; list-style-type: none; }
.selection-data LI { display: inline-block; width: 33%; float: left; }
.selection-data A, .selection-data SPAN { color: #FFF; font-size: 14px; font-weight: bold; text-decoration: none; }
.selection-link-hide { clear: both; float: right; margin: 3px; }

/* Alignment
----------------------------------*/
.left { padding-left: 0.5em; text-align: left; }
.right { padding-right: 0.5em; text-align: right; }
.center { text-align: center; }

/* Background
----------------------------------*/
.exception { background-color: #ce2a1b !important; }
.success, #content UL LI.build-passed-link { background-color: #4e800c !important; }
.failed, #content UL LI.build-failed-link { background-color: #ce2a1b !important; }
.warning { background-color: #f0b440 !important; }
.success-light { background-color: #639f27 !important; }
.failed-light { background-color: #c94b3e !important; }
.warning-light { background-color: #f1c775 !important; }

/* Text
----------------------------------*/
.success-text { color: #4e800c !important; }
.failed-text { color: #ce2a1b !important; }
.warning-text { color: #f0b440 !important; }
.failed-underline { border-bottom: dotted 2px #ce2a1b; }

/* Layout
----------------------------------*/
#header, #main, #footer { width: 1000px; margin: 0 auto; padding: 0px; text-align: left; }
#header { margin-top: 10px !important; height: 65px; border-bottom: solid 2px #3b3a3a; vertical-align: top; }
#menu { float: left; width: 200px; margin: 20px 10px 20px 0px; padding: 0px; }
#content { float: right; clear: right; width: 790px; margin-top: 20px; }
#footer { margin-bottom: 20px !important; border-top: solid 2px #3b3a3a; }

/* Header
----------------------------------*/
.header-logo { float: left; color: #3b3a3a; }
.heading { float: left; font: 30px times new roman; letter-spacing: 2px; }
.subheading { float: left; clear: both; margin-top: -7px; margin-left: 30px; color: #3b3a3a; font: 12px trebuchet ms; }

.header-login, .header-navigation {	display: block; float: right; }

.header-login { padding: 5px; margin-top: -10px; clear: right; background-color: #f0b440; }
.header-login A { float: left; margin: 2px; }

.header-navigation { clear: both; }
.header-navigation UL { display: block; margin: 0px; list-style-type: none; }
.route { float: left; padding-left: 13px; background: url("../images/separator.png") no-repeat 0px 3px; color: #919EA9; font-weight: bold; }
.route A { color: #3b3a3a; text-decoration: none; }
.route-dashboard { padding-left: 0px !important; background-image: none !important; }

/* Menu
----------------------------------*/
#menu H2 { display: block; width: 100%; height: 35px; margin: 0px 0px 2px 0px; padding: 0px; background-color: #3b3a3a; color: #ededed; font: normal 15px trebuchet ms; vertical-align: middle; cursor: pointer; cursor: hand; }
#menu H2 SPAN { display: inline-block; margin: 6px 10px 6px 10px; }

#menu UL { display: block; margin: 0px; padding: 0px; list-style-type: none; }

#menu .section UL { width: 100%; }
#menu .section LI { display: block; width: 100%; height: 30px; margin: 0px 0px 1px 0px; padding: 0px; border-top: solid 1px #c9c5c5; border-bottom: solid 1px #c9c5c5; background-image: url("../images/menu_links_bg.png"); font-size: 12px; vertical-align: middle; }
#menu .section LI SPAN { display: block; margin: 7px; }
#menu A { color: #615e5c; font-weight: bold; }

#menu .build-passed-link { background: url("../images/build_passed_link_bg.png") !important; }
#menu .build-failed-link { background: url("../images/build_failed_link_bg.png") !important; }

.build-views { display: block; height: 25px; margin: 0px 0px 3px 0px; }
.build-views UL { float: right; height: 100%; margin-bottom: 3px !important; }
.build-views LI { float: left; width: 24px; height: 24px; margin: 1px; cursor: pointer; cursor: hand; }
.build-views LI SPAN { display: none; }

.colors { float: left !important; margin-left: -1px !important; }

#searchbox { width: 130px; margin: -4px 0px 0px 2px; background-color: #3b3a3a; color: #ededed; font: normal 15px trebuchet ms; vertical-align: middle; border-bottom: 1px solid #c9c5c5; }

/* Content
----------------------------------*/
#content .section { margin: 0px; margin-bottom: 5px !important; }
#content .section-content { width: 770px; margin: 0px; padding: 10px; background: #EEE; color: #3b3a3a !important; font-size: 12px; overflow: hidden; }

H1.title, #content .build { display: block; width: 100%; height: 60px; margin: 0px; padding: 0px; background-color: #3b3a3a; font-size: 24px; vertical-align: middle; }
H1.title, H1.title A, #content .build A { color: #ededed; font-family: trebuchet ms; cursor: pointer; cursor: hand; }

H1.title SPAN, #content .build SPAN { float: left; margin-left: 10px !important; margin-top: 15px; }
H1.title SPAN, H1.title A, #content .build SPAN, #content .build A { display: inline-block; }

.title-data { float: right !important; margin-right: 10px !important; }
.title-data .icon { margin: 0.1em; background-color: #FFF; }
.title-data .icon SPAN, .title-data .icon INPUT { display: none; }
.title-data SPAN { margin: 0px !important; }
.button-rss, .title-data .icon-large-down-arrow { background-color: Transparent !important; }

#content .build { margin-bottom: 4px !important; }

.log, PRE { overflow: auto; white-space: pre-wrap; }

.section-content A { color: #000000; text-decoration: underline; }
.report-link { color: #FFFFFF !important; text-decoration: none !important; }

/* Footer
----------------------------------*/
.version { float: left; color: #3b3a3a; font-size: 10px; }
.authors { float: right; margin-top: 2px; }
.authors A { display: block; float: right; margin-left: 5px; }
.authors A.thought-works { width: 129px; height: 30px; background-image: url('../images/thoughtworks.png'); }
.authors A.saiku { width: 34px; height: 25px; background-image: url('../images/saiku.png'); }
.authors SPAN { display: none; }

/* ------------------------------------- */
/* Extensions
/* ------------------------------------- */

/* jQuery XPH Tooltip
----------------------------------*/
.tooltip, .tooltip-fixed { color: #3b3a3a; border: 1px solid #3b3a3a; background: #ffffee; text-align: left; }
.tooltip-fixed { width: 400px; }
.tooltip .title { display: none; }
.tooltip .text, .tooltip .url { padding: 5px; font-size: x-small; }
.tooltip .url { font-weight: bold; }
.tooltip .shortcut { font-style: italic; font-weight: bold; }
.tooltip P, .tooltip-fixed P { margin: 2px; padding: 0px; }
.tooltip-fixed .text { font-size: small; }


text:
"""
labels.py

Created by Thomas Mangin on 2012-07-08.
Copyright (c) 2014-2015 Orange. All rights reserved.
Copyright (c) 2014-2015 Exa Networks. All rights reserved.
"""

# TODO: take into account E-VPN specs that specify the role of the first bit of ESI
# (since draft-ietf-l2vpn-evpn-05)

# Ethernet Segment Identifier
class ESI (object):
	DEFAULT = ''.join(chr(0) for _ in range(0,10))
	MAX = ''.join(chr(0xFF) for _ in range(0,10))

	__slots__ = ['esi']

	def __init__ (self, esi=None):
		self.esi = self.DEFAULT if esi is None else esi

	def __str__ (self):
		if self.esi == self.DEFAULT:
			return "-"
		return ":".join('%02x' % ord(_) for _ in self.esi)

	def __repr__ (self):
		return self.__str__()

	def pack (self):
		return self.esi

	def __len__ (self):
		return 10

	def __cmp__ (self, other):
		if not isinstance(other,self.__class__):
			return -1
		if self.esi != other.esi:
			return -1
		return 0

	def __hash__ (self):
		return hash(self.esi)

	@classmethod
	def unpack (cls, data):
		return cls(data[:10])


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

class Penjualan extends CI_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see https://codeigniter.com/user_guide/general/urls.html
	 */
	function __construct()
	{
		parent::__construct();
                date_default_timezone_set('Asia/Jakarta');
                $this->load->model('m_log', '', TRUE);
                $this->load->model('m_penjualan', '', TRUE);
                $this->load->model('m_client', '', TRUE);
                $this->load->model('m_product', '', TRUE);
                $this->load->model('m_employee', '', TRUE);
                $this->load->model('m_bank', '', TRUE);
	}

        public function sessVerif()
        {
            if($this->session->userdata('id_admin') == '') redirect (site_url());
            if($this->session->userdata('id_admin') != '1') redirect (site_url());
        }

	function index()
	{
            if($this->session->userdata('id_admin') == '') redirect (site_url());

//            $penjualan=$this->m_penjualan->penjualanGetAll();
//            $data=array(
//                'penjualan'=>$penjualan
//            );

            $header = array('js'=>array('jquery-ui-1.8.22.custom.min','js','flexigrid.pack','cookie'),'css'=>array('jquery-ui-1.8.22.custom','style','flexigrid.pack'));

            $this->load->view('template/header.php',$header);
            $this->load->view('penjualan/v_penjualan.php');
            $this->load->view('template/footer.php');
	}

        function cekHarga(){
            if($_POST){
                $data=new stdClass();

                $idProduct=  $this->input->post('idProduct');
                $idClient=  $this->input->post('idClient');
                $cetak='';
                $c=0;

                $client=$this->m_client->clientGetById($idClient);
                $clientPrice=$this->m_client->clientPriceGetByIdClient($client->id);
                $product=$this->m_product->productGetById($idProduct);

                if ($clientPrice != '') {
                    foreach ($clientPrice as $hasil) {
                        if(($hasil->idProduct != '' && $hasil->hargaJualDiskon != '') && ($hasil->idProduct == $idProduct)){
                            $data->cetakHargaJual='Rp. '.number_format($hasil->hargaJualDiskon,0,',','.');
                            $data->hargaJual=$hasil->hargaJual;
                            $data->hargaJualDiskon=$hasil->hargaJualDiskon;
                            $data->perhitungan=$hasil->perhitungan;
                            $data->cetakHargaEmployee=$hasil->hargaEmployee == '' ? '' : 'Rp. '.number_format($hasil->hargaEmployee,0,',','.');
                            $data->hargaEmployee=$hasil->hargaEmployee;
                            $c++;
                        }
                    }
                }
                if($c == 0){
                    $data->cetakHargaJual='Rp. '.number_format($product->hargaJualDiskon,0,',','.');
                    $data->hargaJual=$product->hargaJual;
                    $data->hargaJualDiskon=$product->hargaJualDiskon;
                    $data->perhitungan='default';
                    $data->cetakHargaEmployee=$product->hargaEmployee == '' ? '' : 'Rp. '.number_format($product->hargaEmployee,0,',','.');
                    $data->hargaEmployee=$product->hargaEmployee;
                }
                $data->scheme=$product->scheme;
                $data->hargaBeli=$product->hargaBeli;

                echo json_encode($data);
            }
        }

        function numberFormat(){
            $data=new stdClass();
            $data->val='Rp. ' . number_format($this->input->post('val'), 0, ',', '.');
            echo json_encode($data);
        }

//-------------------------------------------------------------------------------------------------------------------------------------------------------

        function penjualanForm(){
            if($this->session->userdata('id_admin') == '') redirect (site_url());

            $typeForm=$this->uri->segment(3);
            $id=$this->uri->segment(4);
            $client=$this->m_client->clientGetAll();
            $product=$this->m_product->productGetAll();
            $penjualanById=$this->m_penjualan->penjualanGetById($id);
            $penjualanDetail=$this->m_penjualan->penjualanGetDetail($id);
            $employee=$this->m_employee->empGetAll();
            $data=array(
                'client'=>$client,
                'typeForm'=>$typeForm,
                'product'=>$product,
                'penjualanById'=>$penjualanById,
                'penjualanDetail'=>$penjualanDetail,
                'employee'=>$employee
            );

            $header = array('js'=>array('jquery-ui-1.8.22.custom.min','js'),'css'=>array('jquery-ui-1.8.22.custom','style'));

            $this->load->view('template/header.php',$header);
            $this->load->view('penjualan/v_penjualanForm.php',$data);
            $this->load->view('template/footer.php');
        }

        function penjualanFormSave(){
            $this->load->view('v_loading.php');

//            print_r($this->input->post());
            if($this->input->post()){
//                echo str_replace(',','<br/>',json_encode((json_encode((array_merge(["statusAction" => 'sukses'],$this->input->post()))));
                if($this->input->post('id') == ''){
                    if($this->m_penjualan->penjualanAddSave(array_map('strtolower', $this->input->post())) != false){
                        $this->m_log->insert_log('simpan penjualan',json_encode((array_merge(["statusAction" => 'sukses'],$this->input->post()))));
                        $this->input->set_cookie('successNotif','Sukses Tambah Data',time()+6000);
                    }else{
                        $this->m_log->insert_log('simpan penjualan',json_encode((array_merge(["statusAction" => 'gagal'],$this->input->post()))));
                        $this->input->set_cookie('failedNotif','Tambah Data Gagal !!!',time()+6000);
                    }
                }else{
                    if($this->m_penjualan->penjualanEditSave(array_map('strtolower', $this->input->post())) != false){
                        $this->m_log->insert_log('edit penjualan',json_encode((array_merge(["statusAction" => 'sukses'],$this->input->post()))));
                        $this->input->set_cookie('successNotif','Sukses Edit Data',time()+6000);
                    }else{
                        $this->m_log->insert_log('edit penjualan',json_encode((array_merge(["statusAction" => 'gagal'],$this->input->post()))));
                        $this->input->set_cookie('failedNotif','Edit Data Gagal !!!',time()+6000);
                    }
                }
                redirect('penjualan');
            }else{
                redirect('login');
            }
        }

        function penjualanDelete(){
            $this->load->view('v_loading.php');

            $this->sessVerif();

            $data=$this->uri->segment(3);

            if($this->m_penjualan->penjualanDelete($data) != false){
                $this->m_log->insert_log('delete penjualan',json_encode((array_merge(["statusAction" => 'sukses'],$this->input->post()))));
                $this->input->set_cookie('successNotif','Sukses Hapus Data',time()+6000);
            }else{
                $this->m_log->insert_log('delete penjualan',json_encode((array_merge(["statusAction" => 'gagal'],$this->input->post()))));
                $this->input->set_cookie('failedNotif','Hapus Data Gagal !!!',time()+6000);
            }
            redirect(site_url('penjualan'));
        }

        function TFAUForm(){
            if($this->session->userdata('id_admin') == '') redirect (site_url());

            $typeForm=$this->uri->segment(3);
            $id=$this->uri->segment(4);
            $client=$this->m_client->clientGetAll();
            $product=$this->m_product->productGetAll();
            $penjualanById=$this->m_penjualan->penjualanGetById($id);
            $penjualanDetail=$this->m_penjualan->penjualanGetDetail($id);
            $employee=$this->m_employee->empGetAll();
            $bank=$this->m_bank->bankGetAll();
            $TF=$this->m_penjualan->tukarFakturGetByIdPenjualan($penjualanById->id);
            if($typeForm == 0){
                $addEdit=$this->m_penjualan->tukarFakturGetByIdPenjualan($penjualanById->id);
            }else{
                $addEdit=$this->m_penjualan->ambilUangGetByIdPenjualan($penjualanById->id);
            }
//            if($addEdit == 'add'){
//                $dataForm=new stdClass();
//                $dataForm->idEmployeePic='';
//                $dataForm->keterangan='';
//                $dataForm->id='';
//            }else{
//                $dataForm=new stdClass();
//                $dataForm->idEmployeePic=$addEdit->idEmployeePic;
//                $dataForm->keterangan=$addEdit->keterangan;
//                $dataForm->id=$addEdit->id;
//            }
            $data=array(
                'client'=>$client,
                'typeForm'=>$typeForm,
                'product'=>$product,
                'penjualanById'=>$penjualanById,
                'penjualanDetail'=>$penjualanDetail,
                'addEdit'=>$addEdit,
//                'dataForm'=>$dataForm,
                'employee'=>$employee,
                'bank'=>$bank,
                'TF'=>$TF

            );

            $header = array('js'=>array('jquery-ui-1.8.22.custom.min','js'),'css'=>array('jquery-ui-1.8.22.custom','style'));

            $this->load->view('template/header.php',$header);
            $this->load->view('penjualan/v_TFAUForm.php',$data);
            $this->load->view('template/footer.php');
        }

        function TFAUFormSave(){
            $this->load->view('v_loading.php');

            if($this->input->post()){
                if($this->input->post('typeForm') == 'tukarFaktur'){
                    if($this->input->post('addEdit') == 'add'){
                        if($this->m_penjualan->TFAUAddSave(array_map('strtolower', $this->input->post())) != false){
                            $this->m_log->insert_log('simpan TF',json_encode((array_merge(["statusAction" => 'sukses'],$this->input->post()))));
                            $this->input->set_cookie('successNotif','Sukses Tambah Data',time()+6000);
                        }else{
                            $this->m_log->insert_log('simpan TF',json_encode((array_merge(["statusAction" => 'gagal'],$this->input->post()))));
                            $this->input->set_cookie('failedNotif','Tambah Data Gagal !!!',time()+6000);
                        }
                    }else{
                        if($this->m_penjualan->TFAUEditSave(array_map('strtolower', $this->input->post())) != false){
                            $this->m_log->insert_log('edit TF',json_encode((array_merge(["statusAction" => 'sukses'],$this->input->post()))));
                            $this->input->set_cookie('successNotif','Sukses Edit Data',time()+6000);
                        }else{
                            $this->m_log->insert_log('edit TF',json_encode((array_merge(["statusAction" => 'gagal'],$this->input->post()))));
                            $this->input->set_cookie('failedNotif','Edit Data Gagal !!!',time()+6000);
                        }
                    }
                }else{
                    if($this->input->post('addEdit') == 'add'){
                        if($this->m_penjualan->TFAUAddSave(array_map('strtolower', $this->input->post())) != false){
                            $this->m_log->insert_log('simpan AU',json_encode((array_merge(["statusAction" => 'sukses'],$this->input->post()))));
                            $this->input->set_cookie('successNotif','Sukses Tambah Data',time()+6000);
                        }else{
                            $this->m_log->insert_log('simpan AU',json_encode((array_merge(["statusAction" => 'gagal'],$this->input->post()))));
                            $this->input->set_cookie('failedNotif','Tambah Data Gagal !!!',time()+6000);
                        }
                    }else{
                        if($this->m_penjualan->TFAUEditSave(array_map('strtolower', $this->input->post())) != false){
                            $this->m_log->insert_log('edit AU',json_encode((array_merge(["statusAction" => 'sukses'],$this->input->post()))));
                            $this->input->set_cookie('successNotif','Sukses Edit Data',time()+6000);
                        }else{
                            $this->m_log->insert_log('edit AU',json_encode((array_merge(["statusAction" => 'gagal'],$this->input->post()))));
                            $this->input->set_cookie('failedNotif','Edit Data Gagal !!!',time()+6000);
                        }
                    }
                }
                redirect('penjualan');
            }else{
                redirect('login');
            }
        }

//-------------------------------------------------------------------------------------------------------------------------------------------------------

        function penjualanDetail(){
            if($this->session->userdata('id_admin') == '') redirect (site_url());

            $id=$this->uri->segment(3);
            $client=$this->m_client->clientGetAllAll();
            $product=$this->m_product->productGetAllAll();
            $penjualanById=$this->m_penjualan->penjualanGetById($id);
            $penjualanDetail=$this->m_penjualan->penjualanGetDetail($id);
            $employee=$this->m_employee->empGetAllAll();
            $TF=$this->m_penjualan->TFGetByIdPenjualan($penjualanById->id);
            $AU=$this->m_penjualan->AUGetByIdPenjualan($penjualanById->id);
            $bank=$this->m_bank->bankGetAllAll();

            $data=array(
                'client'=>$client,
                'product'=>$product,
                'penjualanById'=>$penjualanById,
                'penjualanDetail'=>$penjualanDetail,
                'employee'=>$employee,
                'TF'=>$TF,
                'AU'=>$AU,
                'bank'=>$bank,
                'cashback'=>$this->cashback($id)
            );

            $header = array('js'=>array('jquery-ui-1.8.22.custom.min','js'),'css'=>array('jquery-ui-1.8.22.custom','style'));

            $this->load->view('template/header.php',$header);
            $this->load->view('penjualan/v_penjualanDetail.php',$data);
            $this->load->view('template/footer.php');
        }

	function penjualanPrint()
	{
            $this->sessVerif();

//            $penjualan=$this->m_penjualan->penjualanGetAll();
//            $data=array(
//                'penjualan'=>$penjualan
//            );
            $id=$this->uri->segment(3);
            $penjualanById=$this->m_penjualan->penjualanGetById($id);

            $data=array(
                'id'=>$id,
                'idClient'=>$penjualanById->idClient
            );

            $header = array('js'=>array('jquery-ui-1.8.22.custom.min','js','flexigrid.pack','cookie'),'css'=>array('jquery-ui-1.8.22.custom','style','flexigrid.pack'));

            $this->load->view('template/header.php',$header);
            $this->load->view('penjualan/v_penjualanPrint.php',$data);
            $this->load->view('template/footer.php');
	}

        function cashback($id){
            $client=$this->m_client->clientGetAll();
            $product=$this->m_product->productGetAll();
            $penjualanById=$this->m_penjualan->penjualanGetById($id);
            $penjualanDetail=$this->m_penjualan->penjualanGetDetail($id);
            $employee=$this->m_employee->empGetAll();
            $TF=$this->m_penjualan->TFGetByIdPenjualan($penjualanById->id);
            $AU=$this->m_penjualan->AUGetByIdPenjualan($penjualanById->id);
            $bank=$this->m_bank->bankGetAll();
            $cashback=0;

            if($penjualanDetail != false){
                foreach ($penjualanDetail as $penj) {
                    $temp=0;
                    $temp1=0;
                    if($penj->scheme == 'cashback'){
                        $temp=((($penj->hargaJual-$penj->hargaEmployee)/2)*$penj->jumlah);
                        $temp1=$penj->perhitungan == 'default' ? $temp : 0;
                        $cashback=$cashback+$temp1;
                    }
                }
            }
            return $cashback;
        }

//-------------------------------------------------------------------------------------------------------------------------------------------------------

        function penjualanTable()
	{
            if($this->session->userdata('id_admin') == '') redirect (site_url());

            $page = 1; // The current page
            $sortname = 'noFaktur'; // Sort column
            $sortorder = 'desc'; // Sort order
            $qtype = ''; // Search column
            $query = ''; // Search string
            $rp = 15;
            // Get posted data
            if (isset($_POST['page'])) {
                    $page = $this->input->post('page',true);
            }
            if (isset($_POST['sortname'])) {
                    $sortname = $this->input->post('sortname',true);
            }
            if (isset($_POST['sortorder'])) {
                    $sortorder = $this->input->post('sortorder',true);
            }
            if (isset($_POST['qtype'])) {
                    $qtype = $this->input->post('qtype',true);
            }
            if (isset($_POST['query'])) {
                    $query = $this->input->post('query',true);
            }
            if (isset($_POST['rp'])) {
                    $rp = $this->input->post('rp',true);
            }
            // Setup sort and search SQL using posted data
            $sortSql = "order by $sortname $sortorder";
            if($qtype == 'penjualan.idEmployeePic'){
                if(strtolower($query) == 'bawa sendiri' || strtolower($query) == 'sendiri'){
                    $query='0';
                }
            }
//            $employeeInput = $this->session->userdata('id_admin') == '1' ? '' : 'AND penjualan.time like "'.date("d-m-Y").'%" AND penjualan.id_admin="'.$this->session->userdata('id_admin').'"' ;
            $employeeInput = $this->session->userdata('id_admin') == '1' ? '' : 'AND penjualan.id_admin="'.$this->session->userdata('id_admin').'"' ;
            if($qtype == 'time' && $query != ''){
                $ttime=explode('-', $query);
                $whereSql = ($qtype != '' && $query != '') ? "where d=$ttime[0] AND m=$ttime[1] AND y=$ttime[2] AND client.id=penjualan.idClient $employeeInput AND penjualan.deleted='0'" : "WHERE  client.id=penjualan.idClient $employeeInput AND penjualan.deleted='0'";
            }else{
                $whereSql = ($qtype != '' && $query != '') ? "where $qtype LIKE '%$query%' AND client.id=penjualan.idClient $employeeInput AND penjualan.deleted='0'" : "WHERE  client.id=penjualan.idClient $employeeInput AND penjualan.deleted='0'";
            }

            // Setup paging SQL
            $pageStart = ($page-1)*$rp;
            $limitSql = "limit $pageStart, $rp";

            // Create JSON data
            $data = array();
            $data['page'] = $page;
            $data['rows'] = array();
            $select = "client.nama,penjualan.noFaktur,penjualan.diskon,penjualan.jumlahDiskon,penjualan.noPo,penjualan.d,penjualan.m,penjualan.y,penjualan.status,penjualan.id,penjualan.totalBayar,penjualan.idEmployeePic,penjualan.nominalFaktur";
            $sql = "SELECT $select FROM penjualan,client $whereSql $sortSql $limitSql";
            $sqlcount = "SELECT $select FROM penjualan,client $whereSql $sortSql";
//            echo $sql;
            // Get total count of records
            $total = $this->m_penjualan->get_count_query($sqlcount);
            $data['total'] = $total;

            $results = $this->m_penjualan->get_query($sql);

            $no=$pageStart+1;
            if($results != false){
                foreach($results as $row){
                    if($row->idEmployeePic == '0'){
                        $employeePic='Bawa Sendiri';
                    }else{
                        $a=$this->m_employee->empGetById($row->idEmployeePic);
                        $employeePic=$a->nama;
                    }
                    if($row->totalBayar != '') $totByr='Rp. ' . number_format($row->totalBayar, 0, ',', '.'); else $totByr='';
                    if($row->diskon == 'nominal'){
                        $nominalFaktur='Rp. ' . number_format($row->nominalFaktur-$row->jumlahDiskon, 0, ',', '.');
                    }else if($row->diskon == 'persen'){
                        $nominalFaktur='Rp. ' . number_format($row->nominalFaktur-($row->jumlahDiskon*$row->nominalFaktur/100), 0, ',', '.');
                    }else if ($row->diskon == 'tidak'){
                        $nominalFaktur='Rp. ' . number_format($row->nominalFaktur, 0, ',', '.');
                    }
                    $data['rows'][] = array(
                    'id' => $row->id,
                    'cell' => array($no,$row->noFaktur,  strtoupper($row->noPo),  ucwords($row->nama), ucwords($employeePic),date("d-M-Y",strtotime($row->d.'-'.$row->m.'-'.$row->y)),$nominalFaktur,$totByr,ucwords($row->status))
                    );
                    $no++;
                }
            }

            echo json_encode($data);
        }

        function penjualanPrintTable()
	{
            $this->sessVerif();

            $idClient=$this->uri->segment(3);
            $page = 1; // The current page
            $sortname = 'noFaktur'; // Sort column
            $sortorder = 'desc'; // Sort order
            $qtype = ''; // Search column
            $query = ''; // Search string
            $rp = 15;
            // Get posted data
            if (isset($_POST['page'])) {
                    $page = $this->input->post('page',true);
            }
            if (isset($_POST['sortname'])) {
                    $sortname = $this->input->post('sortname',true);
            }
            if (isset($_POST['sortorder'])) {
                    $sortorder = $this->input->post('sortorder',true);
            }
            if (isset($_POST['qtype'])) {
                    $qtype = $this->input->post('qtype',true);
            }
            if (isset($_POST['query'])) {
                    $query = $this->input->post('query',true);
            }
            if (isset($_POST['rp'])) {
                    $rp = $this->input->post('rp',true);
            }
            // Setup sort and search SQL using posted data
            $sortSql = "order by $sortname $sortorder";
            if($qtype == 'time' && $query != ''){
                $ttime=explode('-', $query);
                $whereSql = ($qtype != '' && $query != '') ? "where d=$ttime[0] AND m=$ttime[1] AND y=$ttime[2] AND client.id=penjualan.idClient AND penjualan.idClient='$idClient' AND penjualan.deleted='0'" : "WHERE  client.id=penjualan.idClient AND penjualan.idClient='$idClient' AND penjualan.deleted='0'";
            }else{
                $whereSql = ($qtype != '' && $query != '') ? "where $qtype LIKE '%$query%' AND client.id=penjualan.idClient AND penjualan.idClient='$idClient' AND penjualan.deleted='0'" : "WHERE  client.id=penjualan.idClient AND penjualan.idClient='$idClient' AND penjualan.deleted='0'";
            }

            // Setup paging SQL
            $pageStart = ($page-1)*$rp;
            $limitSql = "limit $pageStart, $rp";

            // Create JSON data
            $data = array();
            $data['page'] = $page;
            $data['rows'] = array();
            $select = "client.nama,penjualan.noFaktur,penjualan.diskon,penjualan.jumlahDiskon,penjualan.noPo,penjualan.d,penjualan.m,penjualan.y,penjualan.status,penjualan.id,penjualan.nominalFaktur,penjualan.idEmployeePic";
            $sql = "SELECT $select FROM penjualan,client $whereSql $sortSql $limitSql";
            $sqlcount = "SELECT $select FROM penjualan,client $whereSql $sortSql";
//            echo $sql;
            // Get total count of records
            $total = $this->m_penjualan->get_count_query($sqlcount);
            $data['total'] = $total;

            $results = $this->m_penjualan->get_query($sql);

            $no=$pageStart+1;
            if($results != false){
                foreach($results as $row){
                    if($row->status != 'ambil uang' && $row->status != 'manual close' ){
                        if($row->idEmployeePic == '0'){
                            $employeePic='Bawa Sendiri';
                        }else{
                            $a=$this->m_employee->empGetById($row->idEmployeePic);
                            $employeePic=$a->nama;
                        }
                        if($row->diskon == 'nominal'){
                            $nominalFaktur='Rp. ' . number_format($row->nominalFaktur-$row->jumlahDiskon, 0, ',', '.');
                        }else if($row->diskon == 'persen'){
                            $nominalFaktur='Rp. ' . number_format($row->nominalFaktur-($row->jumlahDiskon*$row->nominalFaktur/100), 0, ',', '.');
                        }else if ($row->diskon == 'tidak'){
                            $nominalFaktur='Rp. ' . number_format($row->nominalFaktur, 0, ',', '.');
                        }
                        $data['rows'][] = array(
                        'id' => $row->id,
                        'cell' => array($no,$row->noFaktur,$row->noPo,  ucwords($row->nama), ucwords($employeePic),date("d-M-Y",strtotime($row->d.'-'.$row->m.'-'.$row->y)),$nominalFaktur,ucwords($row->status))
                        );
                        $no++;
                    }
                }
            }

            echo json_encode($data);
        }
}


text:
[![Build Status](https://secure.travis-ci.org/razueroh/noflo-numbers.png?branch=master)](http://travis-ci.org/razueroh/noflo-numbers) [![npm version](https://badge.fury.io/js/noflo-numbers.svg)](http://badge.fury.io/js/noflo-numbers)

This package provides utility components for number representation in [NoFlo](http://noflojs.org/). Based on  [Javascript Number Methods](http://www.w3schools.com/js/js_number_methods.asp).

## Package Installation

    npm install noflo-numbers --save

## Component Usage

### ToExponential

Converts a number into an exponential notation

Port | Name | Datatype | Description
-----|------|----------|-------------
InPort | in | ```number``` | Input number
InPort | digits | ```number``` | Digits after decimal point. Integer between 0 and 20. If omitted, it is set to as many digits as necessary to represent the value
OutPort | out | ```string``` | A String, representing the number as an exponential notation

### ToFixed

Converts a number into a string,
keeping a specified number of decimals

Port | Name | Datatype | Description
-----|------|----------|-------------
InPort | in | ```number``` | Input number
InPort | digits | ```number``` | Digits after decimal point. Int from 0 to 20. Default 0
OutPort | out | ```string``` | A String, representing a number, with the exact number of decimals

### ToPrecision

Formats a number to a specified length

Port | Name | Datatype | Description
-----|------|----------|-------------
InPort | in | ```number``` | Input number
InPort | digits | ```number``` | Number of digits. Integer between 1 and 21. If omitted, it returns the entire number
OutPort | out | ```string``` | A String, representing a number formatted to the specified precision

### ToString

Converts a number into a string

Port | Name | Datatype | Description
-----|------|----------|-------------
InPort | in | ```number``` | Input number
InPort | radix | ```number``` | Base to use. Integer between 2 and 36. Default 10.
 - 2: Binary value
 - 8: Octal value
 - 16: Hexadecimal value
OutPort | out | ```string``` | A String, representing a number


text:
#include "config.h"
#include "PrototypeMap.h"

#include "JSGlobalObject.h"
#include "Operations.h"

namespace JSC {

void PrototypeMap::addPrototype(JSObject* object)
{
    m_prototypes.add(object, object);

    // Note that this method makes the somewhat odd decision to not check if this
    // object currently has indexed accessors. We could do that check here, and if
    // indexed accessors were found, we could tell the global object to have a bad
    // time. But we avoid this, to allow the following to be always fast:
    //
    // 1) Create an object.
    // 2) Give it a setter or read-only property that happens to have a numeric name.
    // 3) Allocate objects that use this object as a prototype.
    //
    // This avoids anyone having a bad time. Even if the instance objects end up
    // having indexed storage, the creation of indexed storage leads to a prototype
    // chain walk that detects the presence of indexed setters and then does the
    // right thing. As a result, having a bad time only happens if you add an
    // indexed setter (or getter, or read-only field) to an object that is already
    // used as a prototype.
}

Structure* PrototypeMap::emptyObjectStructureForPrototype(JSObject* prototype, unsigned inlineCapacity)
{
    StructureMap::AddResult addResult = m_structures.add(std::make_pair(prototype, inlineCapacity), nullptr);
    if (!addResult.isNewEntry) {
        ASSERT(isPrototype(prototype));
        return addResult.iterator->value.get();
    }

    addPrototype(prototype);
    Structure* structure = JSFinalObject::createStructure(
        prototype->globalObject()->vm(), prototype->globalObject(), prototype, inlineCapacity);
    addResult.iterator->value = structure;
    return structure;
}

void PrototypeMap::clearEmptyObjectStructureForPrototype(JSObject* object, unsigned inlineCapacity)
{
    m_structures.remove(std::make_pair(object, inlineCapacity));
}

} // namespace JSC


text:
import {assumeSet} from '../../detect/assume-set.js';
import {assumeMap} from '../../detect/assume-map.js';
import {assumeSymbol} from '../../detect/assume-symbol.js';
import {toHaveSize} from '../../../src/core/matchers/objects/to-have-size.js';
import {createFakeContext} from '../../testing/create-fake-context.js';

describe('toHaveSize', () => {
  it('should check length of array', () => {
    const actual = [1, 2, 3];
    const ctx = createFakeContext(actual);

    const result = toHaveSize(ctx, 3);

    expect(result).toEqual({
      pass: true,
      message: jasmine.any(Function),
    });

    expect(result.message()).toBe(
        `Expect size of [ 1, 2, 3 ] {{not}} to be 3 but was 3`
    );
  });

  it('should check size of object', () => {
    const actual = {foo: 'bar'};
    const ctx = createFakeContext(actual);

    const result = toHaveSize(ctx, 1);

    expect(result).toEqual({
      pass: true,
      message: jasmine.any(Function),
    });

    expect(result.message()).toBe(
        `Expect size of Object({ foo: 'bar' }) {{not}} to be 1 but was 1`
    );
  });

  it('should check size of set', () => {
    assumeSet();

    const actual = new Set();
    actual.add(1);

    const ctx = createFakeContext(actual);

    const result = toHaveSize(ctx, 1);

    expect(result).toEqual({
      pass: true,
      message: jasmine.any(Function),
    });

    expect(result.message()).toBe(
        `Expect size of ${ctx.pp(actual)} {{not}} to be 1 but was 1`
    );
  });

  it('should check size of map', () => {
    assumeMap();

    const actual = new Map();
    actual.set('one', 1);

    const ctx = createFakeContext(actual);

    const result = toHaveSize(ctx, 1);

    expect(result).toEqual({
      pass: true,
      message: jasmine.any(Function),
    });

    expect(result.message()).toBe(
        `Expect size of ${ctx.pp(actual)} {{not}} to be 1 but was 1`
    );
  });

  it('should check size of iterable object', () => {
    assumeSymbol();

    const actual = {
      [Symbol.iterator]() {
        let x = 0;
        return {
          next() {
            return x === 2 ? {done: true} : {value: x++, done: false};
          },
        };
      },
    };

    const ctx = createFakeContext(actual);

    const result = toHaveSize(ctx, 2);

    expect(result).toEqual({
      pass: true,
      message: jasmine.any(Function),
    });

    expect(result.message()).toBe(
        `Expect size of ${ctx.pp(actual)} {{not}} to be 2 but was 2`
    );
  });

  it('should fail with non expected length', () => {
    const actual = {foo: 'bar'};
    const ctx = createFakeContext(actual);

    const result = toHaveSize(ctx, 2);

    expect(result).toEqual({
      pass: false,
      message: jasmine.any(Function),
    });

    expect(result.message()).toBe(
        `Expect size of Object({ foo: 'bar' }) {{not}} to be 2 but was 1`
    );
  });
});


text:
Around '@head' do |scenario, block|
  previous_head = ActiveAdmin.application.head

  begin
    block.call
  ensure
    ActiveAdmin.application.head = previous_head
  end
end


text:
#region License

#endregion

using System;
using System.Collections;
using Common.Logging;
using Spring.Expressions;

namespace Spring.Aspects.Exceptions
{
    /// <summary>
    /// Log the exceptions.  Default log nameis "LogExceptionHandler" and log level is Debug
    /// </summary>
    /// <author>Mark Pollack</author>
    public class LogExceptionHandler : AbstractExceptionHandler
    {
        #region Fields
        private string logName = "LogExceptionHandler";

        private LogLevel logLevel = LogLevel.Trace;

        private bool logMessageOnly = false;

        private bool first = true;

        private string actionExpressionText;

        #endregion

        /// <summary>
        /// Initializes a new instance of the <see cref="LogExceptionHandler"/> class.
        /// </summary>
        public LogExceptionHandler()
        {
            ContinueProcessing = true;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="LogExceptionHandler"/> class.
        /// </summary>
        /// <param name="exceptionNames">The exception names.</param>
        public LogExceptionHandler(string[] exceptionNames) : base(exceptionNames)
        {
            ContinueProcessing = true;
        }

        /// <summary>
        /// Gets or sets the name of the log.
        /// </summary>
        /// <value>The name of the log.</value>
        public string LogName
        {
            get { return logName; }
            set { logName = value; }
        }

        /// <summary>
        /// Gets or sets the log level.
        /// </summary>
        /// <value>The log level.</value>
        public LogLevel LogLevel
        {
            get { return logLevel; }
            set { logLevel = value; }
        }

        /// <summary>
        /// Gets or sets a value indicating whether to log message only, and not pass in the
        /// exception to the logging API
        /// </summary>
        /// <value><c>true</c> if log message only; otherwise, <c>false</c>.</value>
        public bool LogMessageOnly
        {
            get { return logMessageOnly; }
            set { logMessageOnly = value; }
        }

        /// <summary>
        /// Gets the action translation expression text.  Overridden to add approprate settings to
        /// the SpEL expression that does the logging so that it depends on the values of LogLevel and
        /// LogMessageOnly.  Those properties must be set to the desired values before calling this method.
        ///
        /// </summary>
        /// <value>The action translation expression.</value>
        public override string ActionExpressionText
        {
            get { return actionExpressionText; }
            set
            {
                if (first)
                {
                    first = false;
                    string textPart1 = "#log." + LogLevel.ToString() + "(" + value;
                    if (logMessageOnly)
                    {
                        actionExpressionText = textPart1 + ")";
                    }
                    else
                    {
                        actionExpressionText = textPart1 + ", #e)";
                    }
                }
            }
        }

        /// <summary>
        /// Handles the exception.
        /// </summary>
        /// <param name="callContextDictionary">the calling context dictionary</param>
        /// <returns>
        /// The return value from handling the exception, if not rethrown or a new exception is thrown.
        /// </returns>
        public override object HandleException(IDictionary callContextDictionary)
        {
            //TODO log name is targettype.
            ILog adviceLogger = LogManager.GetLogger(logName);
            callContextDictionary.Add("log", adviceLogger);
            try
            {
                IExpression expression = Expression.Parse(ActionExpressionText);
                expression.GetValue(null, callContextDictionary);
            }
            catch (Exception e)
            {
                log.Warn("Was not able to evaluate action expression [" + ActionExpressionText + "]", e);
            }
            return "logged";
        }

    }
}


text:
namespace analyze_ISO
{
	class item_FileTypeBox : public item_Box
	{
	public:
		item_FileTypeBox(const agaliaContainer* image, uint64_t offset, uint64_t size, uint64_t endpos, uint32_t parent);
		virtual ~item_FileTypeBox();

		virtual HRESULT getItemPropCount(uint32_t* count) const override;
		virtual HRESULT getItemPropName(uint32_t index, agaliaString** str) const override;
		virtual HRESULT getItemPropValue(uint32_t index, agaliaString** str) const override;

		enum {
			prop_major_brand = item_Box::prop_last,
			prop_minor_version,
			prop_compatible_brands,
			prop_last
		};
	};

#pragma pack(push, 1)
	struct FileTypeBox
	{
		uint32_t major_brand;
		uint32_t minor_version;
		//uint32_t compatible_brands[];

		uint32_t getMajorBrand(void) const { return agalia_byteswap(major_brand); }
		uint32_t getMinorVersion(void) const { return agalia_byteswap(minor_version); }
	};
#pragma pack(pop)

}


text:
var mongoose = require('mongoose');
var autoIncrement = require('mongoose-auto-increment');
autoIncrement.initialize(mongoose.connection);
var Schema = mongoose.Schema;

var posicionesSchema = new Schema({

  posiciones:{
      type:String
  },
  costo:{
      type:Number
  }

});

posicionesSchema.plugin(autoIncrement.plugin, 'Posiciones');
module.exports = mongoose.model('Posiciones', posicionesSchema);


text:
require 'spec_helper'

require 'generators/formtastic/input/input_generator'

describe Formtastic::InputGenerator do
  include FormtasticSpecHelper

  destination File.expand_path("../../../../../tmp", __FILE__)

  before do
    prepare_destination
  end

  after do
    FileUtils.rm_rf(File.expand_path("../../../../../tmp", __FILE__))
  end

  describe 'without file name' do
    it 'should raise Thor::RequiredArgumentMissingError' do
      lambda { run_generator }.should raise_error(Thor::RequiredArgumentMissingError)
    end
  end

  describe "input generator with underscore definition" do
    before { run_generator %w(hat_size)}

    describe 'generate an input in its respective folder' do
      subject{ file('app/inputs/hat_size_input.rb')}
      it { should exist}
      it { should contain "class HatSizeInput"}
      it { should contain "def to_html"}
      it { should contain "include Formtastic::Inputs::Base"}
      it { should_not contain "super"}
    end
  end

  describe "input generator with camelcase definition" do
    before { run_generator %w(HatSize)}

    describe 'generate an input in its respective folder' do
      subject{ file('app/inputs/hat_size_input.rb')}
      it { should exist}
      it { should contain "class HatSizeInput"}
    end
  end

  describe "input generator with camelcase Input name sufixed" do
    before { run_generator %w(HatSizeInput)}

    describe 'generate an input in its respective folder' do
      subject{ file('app/inputs/hat_size_input.rb')}
      it { should exist}
      it { should contain "class HatSizeInput"}
    end
  end

  describe "input generator with underscore _input name sufixed" do
    before { run_generator %w(hat_size_input)}

    describe 'generate an input in its respective folder' do
      subject{ file('app/inputs/hat_size_input.rb')}
      it { should exist}
      it { should contain "class HatSizeInput"}
    end
  end

  describe "input generator with underscore input name sufixed" do
    before { run_generator %w(hat_sizeinput)}

    describe 'generate an input in its respective folder' do
      subject{ file('app/inputs/hat_size_input.rb')}
      it { should exist}
      it { should contain "class HatSizeInput"}
    end
  end

  describe "override an existing input using extend" do
    before { run_generator %w(string --extend)}

    describe 'app/inputs/string_input.rb' do
      subject{ file('app/inputs/string_input.rb')}
      it { should exist }
      it { should contain "class StringInput < Formtastic::Inputs::StringInput" }
      it { should contain "def to_html" }
      it { should_not contain "include Formtastic::Inputs::Base" }
      it { should contain "super" }
      it { should_not contain "def input_html_options" }
    end
  end

  describe "extend an existing input" do
    before { run_generator %w(FlexibleText --extend string)}

    describe 'app/inputs/flexible_text_input.rb' do
      subject{ file('app/inputs/flexible_text_input.rb')}
      it { should contain "class FlexibleTextInput < Formtastic::Inputs::StringInput" }
      it { should contain "def input_html_options" }
      it { should_not contain "include Formtastic::Inputs::Base" }
      it { should_not contain "def to_html" }
    end
  end

  describe "provide a slashed namespace" do
    before { run_generator %w(stuff/foo)}

    describe 'app/inputs/stuff/foo_input.rb' do
      subject{ file('app/inputs/stuff/foo_input.rb')}
      it {should exist}
      it { should contain "class Stuff::FooInput" }
      it { should contain "include Formtastic::Inputs::Base" }
    end
  end

  describe "provide a camelized namespace" do
    before { run_generator %w(Stuff::Foo)}

    describe 'app/inputs/stuff/foo_input.rb' do
      subject{ file('app/inputs/stuff/foo_input.rb')}
      it {should exist}
      it { should contain "class Stuff::FooInput" }
      it { should contain "include Formtastic::Inputs::Base" }
    end
  end
end


text:
ActsAsBookable::Engine.routes.draw do
end


text:
using Google.Api.Gax;
using Google.Api.Gax.Grpc;
using Google.Api.Gax.ResourceNames;
using Google.Cloud.ClientTesting;
using Google.Protobuf;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Xunit;

namespace Google.Cloud.PubSub.V1.Snippets
{
    [SnippetOutputCollector]
    [Collection(nameof(PubsubSnippetFixture))]
    public class SubscriberServiceApiClientSnippets
    {
        private readonly PubsubSnippetFixture _fixture;

        public SubscriberServiceApiClientSnippets(PubsubSnippetFixture fixture)
        {
            _fixture = fixture;
        }

        [Fact]
        public void Overview()
        {
            string projectId = _fixture.ProjectId;
            string topicId = _fixture.CreateTopicId();
            string subscriptionId = _fixture.CreateSubscriptionId();

            // Sample: Overview
            // First create a topic.
            PublisherServiceApiClient publisher = PublisherServiceApiClient.Create();
            TopicName topicName = new TopicName(projectId, topicId);
            publisher.CreateTopic(topicName);

            // Subscribe to the topic.
            SubscriberServiceApiClient subscriber = SubscriberServiceApiClient.Create();
            SubscriptionName subscriptionName = new SubscriptionName(projectId, subscriptionId);
            subscriber.CreateSubscription(subscriptionName, topicName, pushConfig: null, ackDeadlineSeconds: 60);

            // Publish a message to the topic.
            PubsubMessage message = new PubsubMessage
            {
                // The data is any arbitrary ByteString. Here, we're using text.
                Data = ByteString.CopyFromUtf8("Hello, Pubsub"),
                // The attributes provide metadata in a string-to-string dictionary.
                Attributes =
                {
                    { "description", "Simple text message" }
                }
            };
            publisher.Publish(topicName, new[] { message });

            // Pull messages from the subscription. This will wait for some time if no new messages have been
            // published yet.
            PullResponse response = subscriber.Pull(subscriptionName, maxMessages: 10);
            foreach (ReceivedMessage received in response.ReceivedMessages)
            {
                PubsubMessage msg = received.Message;
                Console.WriteLine($"Received message {msg.MessageId} published at {msg.PublishTime.ToDateTime()}");
                Console.WriteLine($"Text: '{msg.Data.ToStringUtf8()}'");
            }

            // Acknowledge that we've received the messages. If we don't do this within 60 seconds (as specified
            // when we created the subscription) we'll receive the messages again when we next pull.
            subscriber.Acknowledge(subscriptionName, response.ReceivedMessages.Select(m => m.AckId));

            // Tidy up by deleting the subscription and the topic.
            subscriber.DeleteSubscription(subscriptionName);
            publisher.DeleteTopic(topicName);
            // End sample

            Assert.Equal(1, response.ReceivedMessages.Count);
            Assert.Equal("Hello, Pubsub", response.ReceivedMessages[0].Message.Data.ToStringUtf8());
            Assert.Equal("Simple text message", response.ReceivedMessages[0].Message.Attributes["description"]);
        }

        [Fact]
        public async Task SimpleOverview()
        {
            string projectId = _fixture.ProjectId;
            string topicId = _fixture.CreateTopicId();
            string subscriptionId = _fixture.CreateSubscriptionId();

            // Sample: SimpleOverview
            // First create a topic.
            PublisherServiceApiClient publisherService = await PublisherServiceApiClient.CreateAsync();
            TopicName topicName = new TopicName(projectId, topicId);
            publisherService.CreateTopic(topicName);

            // Subscribe to the topic.
            SubscriberServiceApiClient subscriberService = await SubscriberServiceApiClient.CreateAsync();
            SubscriptionName subscriptionName = new SubscriptionName(projectId, subscriptionId);
            subscriberService.CreateSubscription(subscriptionName, topicName, pushConfig: null, ackDeadlineSeconds: 60);

            // Publish a message to the topic using PublisherClient.
            PublisherClient publisher = await PublisherClient.CreateAsync(topicName);
            // PublishAsync() has various overloads. Here we're using the string overload.
            string messageId = await publisher.PublishAsync("Hello, Pubsub");
            // PublisherClient instance should be shutdown after use.
            // The TimeSpan specifies for how long to attempt to publish locally queued messages.
            await publisher.ShutdownAsync(TimeSpan.FromSeconds(15));

            // Pull messages from the subscription using SubscriberClient.
            SubscriberClient subscriber = await SubscriberClient.CreateAsync(subscriptionName);
            List<PubsubMessage> receivedMessages = new List<PubsubMessage>();
            // Start the subscriber listening for messages.
            await subscriber.StartAsync((msg, cancellationToken) =>
            {
                receivedMessages.Add(msg);
                Console.WriteLine($"Received message {msg.MessageId} published at {msg.PublishTime.ToDateTime()}");
                Console.WriteLine($"Text: '{msg.Data.ToStringUtf8()}'");
                // Stop this subscriber after one message is received.
                // This is non-blocking, and the returned Task may be awaited.
                subscriber.StopAsync(TimeSpan.FromSeconds(15));
                // Return Reply.Ack to indicate this message has been handled.
                return Task.FromResult(SubscriberClient.Reply.Ack);
            });

            // Tidy up by deleting the subscription and the topic.
            subscriberService.DeleteSubscription(subscriptionName);
            publisherService.DeleteTopic(topicName);
            // End sample

            Assert.Equal(1, receivedMessages.Count);
            Assert.Equal("Hello, Pubsub", receivedMessages[0].Data.ToStringUtf8());
        }

        [Fact]
        public void ListSubscriptions()
        {
            string projectId = _fixture.ProjectId;

            // Snippet: ListSubscriptions(ProjectName,*,*,*)
            SubscriberServiceApiClient client = SubscriberServiceApiClient.Create();

            ProjectName projectName = new ProjectName(projectId);
            foreach (Subscription subscription in client.ListSubscriptions(projectName))
            {
                Console.WriteLine($"{subscription.Name} subscribed to {subscription.Topic}");
            }
            // End snippet
        }

        [Fact]
        public async Task ListSubscriptionsAsync()
        {
            string projectId = _fixture.ProjectId;

            // Snippet: ListSubscriptionsAsync(ProjectName,*,*,*)
            SubscriberServiceApiClient client = SubscriberServiceApiClient.Create();

            ProjectName projectName = new ProjectName(projectId);
            IAsyncEnumerable<Subscription> subscriptions = client.ListSubscriptionsAsync(projectName);
            await subscriptions.ForEachAsync(subscription =>
            {
                Console.WriteLine($"{subscription.Name} subscribed to {subscription.Topic}");
            });
            // End snippet
        }

        [Fact]
        public void CreateSubscription()
        {
            string projectId = _fixture.ProjectId;
            string topicId = _fixture.CreateTopicId();
            string subscriptionId = _fixture.CreateSubscriptionId();

            PublisherServiceApiClient.Create().CreateTopic(new TopicName(projectId, topicId));

            // Snippet: CreateSubscription(SubscriptionName,*,*,*,*)
            SubscriberServiceApiClient client = SubscriberServiceApiClient.Create();

            SubscriptionName subscriptionName = new SubscriptionName(projectId, subscriptionId);
            TopicName topicName = new TopicName(projectId, topicId);
            Subscription subscription = client.CreateSubscription(
                subscriptionName, topicName, pushConfig: null, ackDeadlineSeconds: 30);
            Console.WriteLine($"Created {subscription.Name} subscribed to {subscription.Topic}");
            // End snippet
        }

        [Fact]
        public async Task CreateSubscriptionAsync()
        {
            string projectId = _fixture.ProjectId;
            string topicId = _fixture.CreateTopicId();
            string subscriptionId = _fixture.CreateSubscriptionId();

            PublisherServiceApiClient.Create().CreateTopic(new TopicName(projectId, topicId));

            // Snippet: CreateSubscriptionAsync(SubscriptionName,TopicName,*,*,CallSettings)
            // Additional: CreateSubscriptionAsync(SubscriptionName,TopicName,*,*,CancellationToken)
            SubscriberServiceApiClient client = SubscriberServiceApiClient.Create();

            SubscriptionName subscriptionName = new SubscriptionName(projectId, subscriptionId);
            TopicName topicName = new TopicName(projectId, topicId);
            Subscription subscription = await client.CreateSubscriptionAsync(
                subscriptionName, topicName, pushConfig: null, ackDeadlineSeconds: 30);
            Console.WriteLine($"Created {subscription.Name} subscribed to {subscription.Topic}");
            // End snippet
        }

        [Fact]
        public void Pull()
        {
            string projectId = _fixture.ProjectId;
            string topicId = _fixture.CreateTopicId();
            string subscriptionId = _fixture.CreateSubscriptionId();

            PublisherServiceApiClient publisher = PublisherServiceApiClient.Create();
            TopicName topicName = new TopicName(projectId, topicId);
            publisher.CreateTopic(topicName);
            PubsubMessage newMessage = new PubsubMessage { Data = ByteString.CopyFromUtf8("Simple text") };
            SubscriberServiceApiClient.Create().CreateSubscription(new SubscriptionName(projectId, subscriptionId), topicName, null, 60);
            publisher.Publish(topicName, new[] { newMessage });

            // Snippet: Pull(SubscriptionName,*,*,*)
            SubscriberServiceApiClient client = SubscriberServiceApiClient.Create();

            SubscriptionName subscriptionName = new SubscriptionName(projectId, subscriptionId);

            PullResponse pullResponse = client.Pull(subscriptionName, maxMessages: 100);
            foreach (ReceivedMessage message in pullResponse.ReceivedMessages)
            {
                // Messages can contain any data. We'll assume that we know this
                // topic publishes UTF-8-encoded text.
                Console.WriteLine($"Message text: {message.Message.Data.ToStringUtf8()}");
            }

            // Acknowledge the messages after pulling them, so we don't pull them
            // a second time later. The ackDeadlineSeconds parameter specified when
            // the subscription is created determines how quickly you need to acknowledge
            // successfully-pulled messages before they will be redelivered.
            var ackIds = pullResponse.ReceivedMessages.Select(rm => rm.AckId);
            client.Acknowledge(subscriptionName, ackIds);
            // End snippet
        }

        [Fact]
        public async Task PullAsync()
        {
            string projectId = _fixture.ProjectId;
            string topicId = _fixture.CreateTopicId();
            string subscriptionId = _fixture.CreateSubscriptionId();

            PublisherServiceApiClient publisher = PublisherServiceApiClient.Create();
            TopicName topicName = new TopicName(projectId, topicId);
            publisher.CreateTopic(topicName);
            PubsubMessage newMessage = new PubsubMessage { Data = ByteString.CopyFromUtf8("Simple text") };
            SubscriberServiceApiClient.Create().CreateSubscription(new SubscriptionName(projectId, subscriptionId), topicName, null, 60);
            publisher.Publish(topicName, new[] { newMessage });

            // Snippet: PullAsync(SubscriptionName,*,*,CallSettings)
            // Additional: PullAsync(SubscriptionName,*,*,CancellationToken)
            SubscriberServiceApiClient client = SubscriberServiceApiClient.Create();

            SubscriptionName subscriptionName = new SubscriptionName(projectId, subscriptionId);

            PullResponse pullResponse = await client.PullAsync(subscriptionName, maxMessages: 100);
            foreach (ReceivedMessage message in pullResponse.ReceivedMessages)
            {
                // Messages can contain any data. We'll assume that we know this
                // topic publishes UTF-8-encoded text.
                Console.WriteLine($"Message text: {message.Message.Data.ToStringUtf8()}");
            }

            // Acknowledge the messages after pulling them, so we don't pull them
            // a second time later. The ackDeadlineSeconds parameter specified when
            // the subscription is created determines how quickly you need to acknowledge
            // successfully-pulled messages before they will be redelivered.
            var ackIds = pullResponse.ReceivedMessages.Select(rm => rm.AckId);
            await client.AcknowledgeAsync(subscriptionName, ackIds);
            // End snippet
        }

        [Fact]
        public async Task StreamingPull()
        {
            string projectId = _fixture.ProjectId;
            string topicId = _fixture.CreateTopicId();
            string subscriptionId = _fixture.CreateSubscriptionId();

            // Snippet: StreamingPull(*, *)
            PublisherServiceApiClient publisher = PublisherServiceApiClient.Create();
            TopicName topicName = new TopicName(projectId, topicId);
            publisher.CreateTopic(topicName);
            SubscriberServiceApiClient subscriber = SubscriberServiceApiClient.Create();
            SubscriptionName subscriptionName = new SubscriptionName(projectId, subscriptionId);
            subscriber.CreateSubscription(subscriptionName, topicName, null, 60);

            // If we don't see all the messages we expect in 10 seconds, we'll cancel the call.
            CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(10));
            CallSettings callSettings = CallSettings.FromCancellationToken(cancellationTokenSource.Token);
            SubscriberServiceApiClient.StreamingPullStream stream = subscriber.StreamingPull(callSettings);

            // The first request must include the subscription name and the stream ack deadline
            await stream.WriteAsync(new StreamingPullRequest { SubscriptionAsSubscriptionName = subscriptionName, StreamAckDeadlineSeconds = 20 });

            Task pullingTask = Task.Run(async () =>
            {
                int messagesSeen = 0;
                AsyncResponseStream<StreamingPullResponse> responseStream = stream.GetResponseStream();

                // Handle responses as we see them.
                while (await responseStream.MoveNextAsync())
                {
                    StreamingPullResponse response = responseStream.Current;
                    Console.WriteLine("Received streaming response");
                    foreach (ReceivedMessage message in response.ReceivedMessages)
                    {
                        // Messages can contain any data. We'll assume that we know this
                        // topic publishes UTF-8-encoded text.
                        Console.WriteLine($"Message text: {message.Message.Data.ToStringUtf8()}");
                    }
                    // Acknowledge the messages we've just seen
                    await stream.WriteAsync(new StreamingPullRequest { AckIds = { response.ReceivedMessages.Select(rm => rm.AckId) } });

                    // If we've seen all the messages we expect, we can complete the streaming call,
                    // and our next MoveNext call will return false.
                    messagesSeen += response.ReceivedMessages.Count;
                    if (messagesSeen == 3)
                    {
                        await stream.WriteCompleteAsync();
                    }
                }
            });

            publisher.Publish(topicName, new[] { new PubsubMessage { Data = ByteString.CopyFromUtf8("Message 1") } });
            publisher.Publish(topicName, new[] { new PubsubMessage { Data = ByteString.CopyFromUtf8("Message 2") } });
            publisher.Publish(topicName, new[] { new PubsubMessage { Data = ByteString.CopyFromUtf8("Message 3") } });

            await pullingTask;
            // End snippet
        }

        [Fact]
        public void Emulator()
        {
            // Sample: Emulator
            SubscriberServiceApiClient subscriber = new SubscriberServiceApiClientBuilder
            {
                EmulatorDetection = EmulatorDetection.EmulatorOrProduction
            }.Build();
            // End sample
        }
    }
}


text:
var esclient = require('pelias-esclient')(),
    responder = require('./responder'),
    SphericalMercator = require('sphericalmercator'),
    mercator = new SphericalMercator();

module.exports = function( req, res, next ){

  // Proxy request to ES backend & map response to a valid FeatureCollection
  esclient.search({
    index: 'pelias',
    type: req.params.type,
    body: buildSearchCommand( req )
  }, function( err, data ){

    if( err ){ return responder.error( req, res, next, err ); }
    if( data && data.hits ){

      // console.log( 'hits length', data.hits.hits.length );

      // response object
      var obj = {
        type: 'FeatureCollection',
        features: data.hits.hits.map( function( row ){

          var props = {};
          if( 'object' === typeof row._source.suggest ){
            props = row._source.suggest.payload;
          }
          props.name = row._source.name;

          return {
            type: 'Feature',
            id: row._id,
            properties: props,
            geometry: {
              type: 'Point',
              coordinates: [
                row._source.center_point.lon,
                row._source.center_point.lat
              ]
            }
          }

        })
      };

      return responder.cors( req, res, obj );
    }

    else {
      console.error( data );
      return next( 'an error occurred' );
    }
  });

}

// Generate bbox from tile coords
function generateBbox( req )
{
  return mercator.bbox(
    Number( req.params.x ),
    Number( req.params.y ),
    Number( req.params.z )
  );
}

// Build elasticsearch query object
function buildSearchCommand( req )
{
  var bbox = generateBbox( req );
  // [ w lon, s lat, e lon, n lat ]

  // console.log( 'bbox', bbox );

  return {
    'query': {
      'filtered': {
        'query': {
          'match_all': {}
        },
        'filter' : {
          'geo_bounding_box': {
            'center_point': {
              'top_left': {
                'lat': bbox[3],
                'lon': bbox[0]
              },
              'bottom_right': {
                'lat': bbox[1],
                'lon': bbox[2]
              }
            },
            '_cache' : true
          }
        }
      }
    },
    'size': 1000
  }
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.facebook.presto.geospatial.rtree;

import com.facebook.presto.geospatial.Rectangle;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OperationsPerInvocation;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.infra.Blackhole;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import org.openjdk.jmh.runner.options.VerboseMode;

import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import static com.facebook.presto.geospatial.rtree.RtreeTestUtils.makeRectangles;

@State(Scope.Thread)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@Fork(2)
@Warmup(iterations = 3, time = 2, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 10, time = 1, timeUnit = TimeUnit.SECONDS)
@BenchmarkMode(Mode.AverageTime)
public class BenchmarkFlatbushQuery
{
    private static final int SEED = 613;
    private static final int NUM_PROBE_RECTANGLES = 1000;

    @Benchmark
    @OperationsPerInvocation(NUM_PROBE_RECTANGLES)
    public void rtreeQuery(BenchmarkData data, Blackhole blackhole)
    {
        for (Rectangle query : data.getProbeRectangles()) {
            data.getRtree().findIntersections(query, blackhole::consume);
        }
    }

    @State(Scope.Thread)
    public static class BenchmarkData
    {
        @Param({"8", "16", "32"})
        private int rtreeDegree;
        @Param({"1000", "3000", "10000", "30000", "100000", "300000", "1000000"})
        private int numBuildRectangles;

        private List<Rectangle> probeRectangles;
        private Flatbush<Rectangle> rtree;

        @Setup
        public void setup()
        {
            Random random = new Random(SEED);
            probeRectangles = makeRectangles(random, NUM_PROBE_RECTANGLES);
            rtree = buildRtree(makeRectangles(random, numBuildRectangles));
        }

        public List<Rectangle> getProbeRectangles()
        {
            return probeRectangles;
        }

        public Flatbush<Rectangle> getRtree()
        {
            return rtree;
        }

        private Flatbush<Rectangle> buildRtree(List<Rectangle> rectangles)
        {
            return new Flatbush<>(rectangles.toArray(new Rectangle[] {}), rtreeDegree);
        }
    }

    public static void main(String[] args)
            throws Throwable
    {
        Options options = new OptionsBuilder()
                .verbosity(VerboseMode.NORMAL)
                .include(".*" + BenchmarkFlatbushQuery.class.getSimpleName() + ".*")
                .build();
        new Runner(options).run();
    }
}


text:
var caf = require('caf_core');

exports.init = function(spec, frameworkDesc, modules, cb) {
    modules = modules || [];
    if (modules && !Array.isArray(modules)) {
        modules = [modules];
    }
    modules.push(module);
    caf.init(modules, spec, frameworkDesc, cb);
};


text:
        Typography

        <nz-card>
            <ng-template #title>Headings</ng-template>
            <ng-template #body>

                    Heading 1
                    Sub-heading

                    Heading 2
                    Sub-heading

                    Heading 3
                    Sub-heading

                    Heading 4
                    Sub-heading

                    Heading 5
                    Sub-heading

                    Heading 6
                    Sub-heading

            </ng-template>
        </nz-card>

        <nz-card>
            <ng-template #title>Paragraphs</ng-template>
            <ng-template #body>

                    This is an example of small, fine print text.

                    This is an example of strong, bold text.

                    This is an example of emphasized, italic text.

Alignment & Sizing Helpers

Left aligned text.

Center aligned text.

Right aligned text.

            </ng-template>
        </nz-card>

        <nz-card>
            <ng-template #title>Text Colors</ng-template>
            <ng-template #body>

This is an example of {{color}} text.

            </ng-template>
        </nz-card>

        <nz-card>
            <ng-template #title>Formatting</ng-template>
            <ng-template #body>

text-nowrap

Ad eiusmod eu velit veniam laborum voluptate duis aliqua esse eiusmod ut labore deserunt. Minim cillum ullamco sit do dolor non adipisicing nulla dolore id minim sint. Commodo occaecat eu laboris ut do irure amet nulla dolor ex do anim quis dolor. Pariatur est deserunt esse anim commodo fugiat esse sit. Aliquip ipsum velit Lorem elit excepteur laboris in aute dolor.

text-truncate

Officia nulla velit minim mollit laborum et irure ullamco nisi dolore qui. Sint aute aliqua tempor commodo officia sunt non do id laborum mollit ex ea cupidatat. Amet ad non fugiat magna. Ut cupidatat labore pariatur esse reprehenderit esse sint in proident elit minim sunt enim sit. Enim sint deserunt exercitation duis. Aliquip cillum irure do incididunt do eu eiusmod excepteur culpa ex consectetur nulla duis sit. Ex officia excepteur officia ea ea cupidatat veniam officia officia est.

Transformation

text-lowercase

text-uppercase

text-capitalize

text-deleted

            </ng-template>
        </nz-card>

        <nz-card>
            <ng-template #title>Border</ng-template>
            <ng-template #body>

border-primary

border-success

border-error

border-warning

            </ng-template>
        </nz-card>

        <nz-card>
            <ng-template #title>Lists</ng-template>
            <ng-template #body>

list styled

List Item

List Item

List Item

Unstyled List

List Item

List Item

List Item

            </ng-template>
        </nz-card>

        <nz-card>
            <ng-template #title>Display</ng-template>
            <ng-template #body>

.display-1

.display-2

.display-3

            </ng-template>
        </nz-card>

        <nz-card>
            <ng-template #title>Code</ng-template>
            <ng-template #body>

This is an example of an inline code element within body copy. Wrap inline code within a...tag.

This is an example of preformatted text.

            </ng-template>
        </nz-card>


text:
"""
The dimensions for the geometry mentioned in this script are interpreted as feet
even though the project units in the document are millimeters. This could be because my revit
installation is imperial system, i.e. all the default templates have imperial units. That could
be the reason for feet.
"""
#import libraries and reference the RevitAPI and RevitAPIUI
import clr
import math
import random
import sys
import pickle

clr.AddReference('RevitAPI')
clr.AddReference('RevitAPIUI')
from Autodesk.Revit.DB import *

# returns an cube shaped outline object
def GetOutlineAt(center, size):
	hdiag = XYZ(size/2, size/2, size/2)
	pt1 = center.Subtract(hdiag)
	pt2 = center.Add(hdiag)

	return Outline(pt1, pt2)
# random coin toss - returns true or false
# can specify the probability of true if you want uneven odds
def coinToss(trueProb = 0.5):
	rand = random.WichmannHill().random()
	return rand < trueProb

# takes an Outline object and adds the corresponding box geometry to the document as a generic model
def AddBoxToDoc(box):
	size = box.MaximumPoint.Z -box.MinimumPoint.Z

	pt1 = box.MinimumPoint
	pt2 = pt1.Add(XYZ(0,size,0))
	pt3 = pt1.Add(XYZ(size,size,0))
	pt4 = pt1.Add(XYZ(size,0,0))

	l1 = Line.CreateBound(pt1, pt2)
	l2 = Line.CreateBound(pt2, pt3)
	l3 = Line.CreateBound(pt3, pt4)
	l4 = Line.CreateBound(pt4, pt1)

	loop = CurveLoop.Create([l1,l2,l3,l4])

	box = GeometryCreationUtilities.CreateExtrusionGeometry([loop], XYZ(0,0,1), size)

	t = Transaction(doc, "adding stuff")
	t.Start()
	ds = DirectShape.CreateElement(doc, ElementId(BuiltInCategory.OST_GenericModel))
	ds.ApplicationId = "app id"
	ds.ApplicationDataId = "obj id"
	ds.SetShape([box])
	t.Commit()

# instances of this class will contain the data collected in one window
class elementSet:
	# constructor
	def __init__(self, elementNames, materialDictionary):
		self.elements = elementNames
		# this is a dictionary where the keys are the element names and
		# values are sets containing the material names associated with that element
		self.matDict = materialDictionary
	# generate pairs of vocabulary from the set
	def GeneratePairs(self,num):
		labels = list()
		targets = list()
		# populate these lists now
		i = 0
		while i < num:
			pair = None
			if coinToss() and len(self.elements) > 1:
				pair = random.WichmannHill().sample(self.elements, 2)
				i += 1
			else:
				randElem = random.WichmannHill().sample(self.elements, 1)[0]
				if len(self.matDict[randElem]) < 1:
					i += 1
					continue
				else:
					matName = random.WichmannHill().sample(self.matDict[randElem], 1)[0]
					pair = [randElem, matName] if coinToss() else [matName, randElem]
					i += 1

			labels.append(pair[0])
			targets.append(pair[1])

		return [labels, targets]

#This applies all the needed filters and returns an element collector for the document
# the collector will only collec the elements that intersect with the box
def GetCollector(box, doc):
	filter = BoundingBoxIntersectsFilter(box)
	notCamFilter = ElementCategoryFilter(BuiltInCategory.OST_Cameras, True)
	notSketchFilter = ElementClassFilter(Sketch, True)
	notTopoFilter = ElementCategoryFilter(BuiltInCategory.OST_Topography,True)
	notLines = ElementClassFilter(CurveElement, True)

	collector = FilteredElementCollector(doc)

	collector = collector.WherePasses(filter).WherePasses(notCamFilter).WherePasses(notSketchFilter)
	collector = collector.WherePasses(notTopoFilter).WherePasses(notLines)
	collector = collector.WhereElementIsNotElementType().WhereElementIsViewIndependent()

	return collector

#this takes a revit element and returns the material category names associated with that element
def GetMaterials(element):
	matsToSkip = ["Miscellaneous","Unassigned", "Generic"]
	matList = element.GetMaterialIds(False)
	matNames = set()
	for mat in matList:
		materialCategory = doc.GetElement(mat).MaterialCategory
		if materialCategory in matsToSkip:continue
		matNames.add(materialCategory)

	return matNames

# returns a small box (random.WichmannHill()ly) of given size from inside the container box
def GetBox(container, size):
	minPt = container.Transform.OfPoint(container.Min)
	maxPt = container.Transform.OfPoint(container.Max)

	randX = 1-random.WichmannHill().random()
	randY = 1-random.WichmannHill().random()
	randZ = 1-random.WichmannHill().random()

	#if randX > 0.5 or randY > 0.5 or randZ > 0.5: print(randX, randY, randZ)

	center = XYZ(
		randX*(minPt.X) + (1-randX)*maxPt.X,
		randY*(minPt.Y) + (1-randY)*maxPt.Y,
		randZ*(minPt.Z) + (1-randZ)*maxPt.Z
	)

	# ratio = (center.X - minPt.X)/(maxPt.X - minPt.X)
	# print(ratio)

	# center = XYZ(
	# 	random.uniform(minPt.X + (size/2), maxPt.X - (size/2)),
	# 	random.uniform(minPt.Y + (size/2), maxPt.Y - (size/2)),
	# 	random.uniform(maxPt.Z - 7, maxPt.Z)
	# )

	box = GetOutlineAt(center, size)
	# AddBoxToDoc(box) # this is for debugging reasons
	return box
# writes the variable to the given path
def writeToFile(data, path):
	with open(path, 'wb') as writer:
		pickle.dump(data, writer, pickle.HIGHEST_PROTOCOL)

# global variables
app = __revit__.Application
doc = __revit__.ActiveUIDocument.Document

#make sure 3d view is active and the section box is turned on
#or else it won't know where to look
bigbox = doc.ActiveView.GetSectionBox()
print(bigbox.Max.Z - bigbox.Min.Z)

WINDOW_SIZE = 2 # this is in feet. trying to use a 2ft cube as a capture window
textPath = '../data/DataAsText.txt' # the text version of dataset will be saved to this file
dataPath = "../data/%02d.pkl" % 0
wordsFile = "../data/wordList.pkl"

def GenerateData(cycleNum):
	labels = []
	targets = []
	f_text = open(textPath, 'w')
	f_text.truncate()
	for _ in range(cycleNum):
		window = GetBox(bigbox, WINDOW_SIZE)
		#AddBoxToDoc(window)
		elemList = GetCollector(window, doc).ToElements()
		elemNameSet = set()
		materialDict = dict()
		if elemList.Count < 1:
			# print("slipping - %s" % elemList.Count)
			continue #too few elements collected
		for i in range(elemList.Count):
			matNames = GetMaterials(elemList[i])
			f_text.write(elemList[i].Category.Name+"; M: "+",".join(matNames)+"\n")

			elemNameSet.add(elemList[i].Category.Name)
			materialDict[elemList[i].Category.Name] = matNames
			#print("here")
			elemBatch = elementSet(elemNameSet, materialDict)
			batch = elemBatch.GeneratePairs(2)
			labels += batch[0]
			targets += batch[1]

		f_text.write('-------------\n')
	f_text.close()

	return [labels, targets]

# Generating the data
labels, targets = GenerateData(5000)
allWords = set()
allWords = allWords.union(set(labels))

allWords = allWords.union(set(targets))
# printing the generated pairs for debugging reasons
# for i in range(len(labels)):
# 	print("%03d - %s - %s"%(i, labels[i], targets[i]))

# now pickling the data on the disk to the predefined path
writeToFile([labels, targets], dataPath)
writeToFile(allWords, wordsFile)

print(len(allWords))