text:
<?php

class Odpcp {

    public static $genericControllerClass = "GenericCtr";
    public static $controllerFilepath = "../controller";
    public static $modelFilepath = "../model";

    public static function tabPanelEdit($array,$panelid) {

        $tabLabel = array();

        $html = "";
        $htmltabs = "";
        $masks = array();// like "array(array('fieldid'=>'','mask'=>''));"

        foreach($array as $keyT => $tab){

            $keyTab = isset($tab['id'])?$tab['id']:$keyT;
            $fieldLabel =array();
            $fieldsnullable = array();
            $aFldValidation = array();
            $htmlRows = '';
            $htmlDef = '';

            $rows = isset($tab['rows'])?$tab['rows']:array();
            $rows['default'] = array();

            //Set  tab label
            $tabLabel[$keyT] = array('label'=>$tab['label'],'id'=>$keyTab);

            //###########################################################
            //  COMEÇA CARREGAR DADOS
            //#############################################################
            for($i=0; $i<= sizeof($tab['data']); $i++){

                $fields=array();

                //for each field of tab
                for($keyField=0; $keyField< sizeof($tab['fields']); $keyField++){
                    $field = $tab['fields'][$keyField];
//                foreach($tab['fields'] as $keyField => $field){

                    $value= (!$i)?null:$tab['data'][$i-1][$field['name']];
                    $disabled = !$i?0:1;

                    $id    = isset($field['id'])?$tab['id'].'_'.$field['id']:$tab['id'].'_'.$keyField;
                    //$name  = 'a_'.$tab['id'].'_'.$field['name'];
                    $name  = $field['name'];
                    $label = isset($field['label'])?$field['label']:"";
                    $type  = isset($field['type'])?$field['type']:"text";
                    $width = isset($field['width'])?"style='width: ".$field['width'].";'":"";
                    $maxlength = isset($field['maxlength'])?"maxlength='".$field['maxlength']."'":"";
                    $onchange = isset($field['onchange'])?"onchange=".$field['onchange']."":"";
                    $hdisabled = $disabled?"disabled='disabled'":"";
                    //Required fields should has the odpRequired class
                    $class = (isset($field['mask'])?"odpInput ".$name:"odpInput").(isset($field['required'])&& in_array($field['required'],array('1',1,true,'true')) ? ' odpRequired':'');
                    $htmlfield = "";

                    //Set field masks into array
                    if(isset($field['mask'])){
                        array_push($masks, array('fieldid'=>$name, 'mask'=>$field['mask']));
                    }

                    //Verify field's type
                    if($type == "text"){
                        //Set the Header field
                        $htmlfield = "<input id='$id' name='$name' class='$class' $maxlength $onchange style='width: 100%;' type='text' value='$value' $hdisabled>";

                    }elseif($type == "hidden"){
                        $htmlfield = "<input id='$id' name='$name' class='$class' $maxlength $onchange style='width: 100%;' type='$type' value='$value' $hdisabled>";

                    }elseif($type == "checkbox"){
                        $htmlfield = "<input id='$id' name='$name' class='$class' $onchange style='width: 100%;' type='$type' ".($value?"checked='checked'":"")." $hdisabled>";

                    }elseif($type == "select"){
                        $loadType = isset($field['options']['load'])?'L':'F';

                        if($i>0){
                            if(isset($field['options']['dynamicparameter'])){
                                foreach($field['options']['dynamicparameter'] as $keyDefPar => $columnToLoad){
                                    $field['options']['by'][$keyDefPar] = $tab['data'][($i-1)][$columnToLoad];
                                }
                            }
                        }else{
                            unset($field['options']['by']);
                            unset($field['options']['dynamicparameter']);
                        }

                        $properties = array('name'=>$name, 'id'=>$id, 'class'=>$class, 'readonly'=>$disabled);
                        if(isset($field['onchange']))
                            $properties['onchange']= $field['onchange'];

                        $htmlfield = Odpcp::select($loadType,$field['options'],$value,null,$properties);
                    }//End of field type verification

                    if(!$i){
                        array_push($fieldLabel, "$label	");
                    }
                    //Set id into array, together with the first field
/*                    if(!$keyField){
                        $htmlfield = "<input type='hidden' name='id' value='".$tab['data'][$i-1]['id']."'>".$htmlfield;
                    }*/

                    //Set html field into array
                    array_push($fields,$htmlfield);

                }//End of field

                $htmlfield =  $i?"<input type='hidden' name='id' value='".$tab['data'][$i-1]['id']."'>	":"<input type='hidden' name='id' value=''>	";
                foreach($fields as $column){
                    $htmlfield = $htmlfield."".$column."	";
                }

                $htmlIco = "<input type='button' title='Salvar' class='odpButtonImg' style='background-image: url(\"".CT_FL_EXT_IMAGES."save.gif\");' onclick='".$panelid.$keyTab."SaveLine($(this).closest(\"tr\"));'>
                            <input type='button' title='Editar' class='odpButtonImg' style='background-image: url(\"".CT_FL_EXT_IMAGES."edit.gif\");' onclick='".$panelid.$keyTab."EditLine($(this).closest(\"tr\"));'>
                            <input type='button' title='Excluir' class='odpButtonImg' style='background-image: url(\"".CT_FL_EXT_IMAGES."delete.gif\");' onclick='".$panelid.$keyTab."RemoveLine($(this).closest(\"tr\"));'>	";

                if($i){ //Line with data
                    $htmlRows = $htmlRows."
".$htmlfield.$htmlIco."
";
                }else{ //Default empty line
                    $htmlDef = $htmlfield.$htmlIco;
                }
            }

            //#########################################################
            // TERMINA DE CARREGAR DADOS
            //########################################################

            //Convert arrays values to html
            $htmllabel = "	"; //Empty column to compensate id's hidden column
            foreach($fieldLabel as $column){
                $htmllabel = $htmllabel.$column;
            }

/*            $htmlvalidation = "";
            foreach($aFldValidation as $column){
                $htmlvalidation = $htmlvalidation.'if('.$column[0].'){alert("'.$column[1].'");return;}';
            }*/

            $htmlmask = "";
            foreach($masks as $column){
                $htmlmask = $htmlmask.'$(".'.$column['fieldid'].'").mask("'.$column['mask'].'");';
            }
            $htmlmask = sizeof($masks)?'jQuery(function($){'.$htmlmask.' });':"";

            //panel
            $htmltabs = $htmltabs.
            "

                <input type='hidden' name='odpMIPid' value='$keyTab'>

                    <input type='hidden' id='$panelid-$keyTab-nextLine' value='0'>

Novo

                                $htmlDef

                                $htmllabel
                                $htmlRows

";
        }//End of tab

        //odpItbPanHSel
        //odpItbPanHNSel
        $htmlHeader = "";
        foreach ($tabLabel as $key => $tlabel){
            $htmlHeader = $htmlHeader .
            "<a href='javascript:void(0);' id='".$panelid.$tlabel['id']."lbl' class='".(!$key?"odpTabSel":"odpTabNSel")."'
                onclick='jQuery(this).closest(\"div\").children(\"a\").each(".
                            "function(index) {".
                                "$(this).removeClass(\"odpTabSel\").addClass(\"odpTabNSel\");".
                            "});".
                          "jQuery(this).removeClass(\"odpTabNSel\").addClass(\"odpTabSel\");".
                          $panelid."Show(\"".$tlabel['id']."\");'".
             ">".$tlabel['label']."";
        }

        $htmlHeader = "
".$htmlHeader.
        "".
        "
";

        return $htmlHeader."
".$htmltabs."
"."";
    }

    public static function tabPanelInsert2($array,$panelid) {

        $tabLabel = array();

        $html = "";
        $htmltabs = "";
        $masks = array();// like "array(array('fieldid'=>'','mask'=>''));"

        foreach($array as $keyT => $tab){

            $keyTab = isset($tab['id'])?$tab['id']:$keyT;
            $fieldLabel =array();
            $fieldsnullable = array();
            $aFldValidation = array();
            $htmlRows = '';
            $htmlDef = '';
            $fields=array();

            $rows = isset($tab['rows'])?$tab['rows']:array();
            $rows['default'] = array();

            //Set  tab label
            $tabLabel[$keyT] = array('label'=>$tab['label'],'id'=>$keyTab);

            //for each field of tab
            foreach($tab['fields'] as $keyField => $field){

                $id    = isset($field['id'])?$tab['id'].'_'.$field['id']:$tab['id'].'_'.$keyField;
                $name  = 'a_'.$tab['id'].'_'.$field['name'];
                $label = isset($field['label'])?$field['label']:"";
                $type  = isset($field['type'])?$field['type']:"text";
                $width = isset($field['width'])?"style='width: ".$field['width'].";'":"";
                $maxlength = isset($field['maxlength'])?"maxlength='".$field['maxlength']."'":"";
                $onchange = isset($field['onchange'])?"onchange=".$field['onchange']."":"";
                //Required fields should has the odpRequired class
                $class = (isset($field['mask'])?"odpInput ".$name:"odpInput").(isset($field['required'])&& in_array($field['required'],array('1',1,true,'true')) ? ' odpRequired':'');

                $htmlfield = "";

                //Set field masks into array
                if(isset($field['mask'])){
                    array_push($masks, array('fieldid'=>$name, 'mask'=>$field['mask']));
                }

                //Verify field's type
                if($type == "text"){
                    //Set the Header field
                    $htmlfield = "<input id='$id' name='$name' class='$class' $maxlength $onchange style='width: 100%; 'type='text' >";

                }elseif($type == "hidden"){
                    $htmlfield = "<input id='$id' name='$name' class='$class' $maxlength $onchange style='width: 100%;' type='$type'>";

                }elseif($type == "checkbox"){
                    $htmlfield = "<input id='$id' name='$name' class='$class' $onchange style='width: 100%;' type='$type'>";

                }elseif($type == "select"){
                    $loadType = isset($field['options']['load'])?'L':'F';

 /*                   if(isset($field['options']['defineparameter'])){
                        foreach($field['options']['defineparameter'] as $keyDefPar => $columnToLoad){
                            $field['options']['by'][$keyDefPar] = $aFieldValues[$columnToLoad];
                        }
                    }*/

                    $properties = array('name'=>$name, 'id'=>$id, 'class'=>$class);
                    if(isset($field['onchange']))
                        $properties['onchange']= $field['onchange'];

                    $htmlfield = Odpcp::select($loadType,$field['options'],null,null,$properties);
                }//End of field type verification

                array_push($fieldLabel, "$label	");

                //Set html field into array
                array_push($fields,$htmlfield);

            }//End of field

            $htmlfield = "";
            foreach($fields as $column){
                $htmlfield = $htmlfield."".$column."	";
            }

            $htmlIco = "<input type='button' title='Excluir' class='odpButtonImg' style='background-image: url(\"".CT_FL_EXT_IMAGES."delete.gif\");' onclick='".$panelid.$keyTab."RemoveLine($(this).closest(\"tr\"));'>	";
            $htmlDef = $htmlfield.$htmlIco;

            //Convert arrays values to html
            $htmllabel = "";
            foreach($fieldLabel as $column){
                $htmllabel = $htmllabel.$column;
            }

/*            $htmlvalidation = "";
            foreach($aFldValidation as $column){
                $htmlvalidation = $htmlvalidation.'if('.$column[0].'){alert("'.$column[1].'");return;}';
            }*/

            $htmlmask = "";
            foreach($masks as $column){
                $htmlmask = $htmlmask.'$(".'.$column['fieldid'].'").mask("'.$column['mask'].'");';
            }
            $htmlmask = sizeof($masks)?'jQuery(function($){'.$htmlmask.' });':"";

            //panel
            $htmltabs = $htmltabs.
            "

                    <input type='hidden' id='$panelid-$keyTab-nextLine' value='0'>

Novo

                                $htmlDef

                                $htmllabel

";
        }//End of tab

        //odpItbPanHSel
        //odpItbPanHNSel
        $htmlHeader = "";
        foreach ($tabLabel as $key => $tlabel){
            $htmlHeader = $htmlHeader .
            "<a href='javascript:void(0);' id='".$panelid.$tlabel['id']."lbl' class='".(!$key?"odpTabSel":"odpTabNSel")."'
                onclick='jQuery(this).closest(\"div\").children(\"a\").each(".
                            "function(index) {".
                                "$(this).removeClass(\"odpTabSel\").addClass(\"odpTabNSel\");".
                            "});".
                          "jQuery(this).removeClass(\"odpTabNSel\").addClass(\"odpTabSel\");".
                          $panelid."Show(\"".$tlabel['id']."\");'".
             ">".$tlabel['label']."";
        }

        $htmlHeader = "
".$htmlHeader.
        "".
        "
";

        return $htmlHeader."
".$htmltabs."
"."";
    }

    /*

      array(  --Panel

            array(    --Tab
                   'label' =>'Telefones (exemplo)';
                   'fields'=>array(
                                     array(  --field text
                                           'id'      =>'name', //will be concatenated with panelid and tabid. Ex: wq-1-name
                                           'label'   =>'Nome',
                                           'type'    =>'text',  //text, checkbox, select
                                           'width'   =>'10%',
                                           'nullable'=> 'false',
                                           'maxlength' => 5,
                                           'onchange' => 'alert();', //javascript
                                           'mask' => '' //jquery.mask format
                                           ),
                                     array(  --field select
                                           'label'   =>'UF',
                                           'type'    =>'select',
                                           'width'   =>'10%',
                                           'nullable'=>'false',
                                           /## Options pode ser carregado de dois modos##/
                                           'options'=>array(
                                                             array('value'=>'10','label'=>'MG'),
                                                             array('value'=>'11','label'=>'SP')
                                                            )
                                           ou
                                           'options'=>array( 'load' => 'State', //obrigatório
                                                             'by'  => array('field1'=>'valor1','id_cidade'=>'23'),  //opcional
                                                             'value' => 'id',  //property of created object to get html option property 'value'
                                                             'label' => 'nameCity' //property of created object to get html option property 'label'
                                                            )
                                           /## Fim options ##/
                                           )
                                   )
                  )
            ),
            array()--Tab2

      */
    public static function tabPanel($array,$panelid) {

        $tabLabel = array();

        $html = "";
        $htmltabs = "";
        $masks = array();// like "array(array('fieldid'=>'','mask'=>''));"

        foreach($array as $keyTab => $tab){

            $fieldLabel =array();
            $fieldsnullable = array();
            $aFldValidation = array();
            $htmlRows = '';
            $htmlDef = '';

            $rows = isset($tab['rows'])?$tab['rows']:array();
            $rows['default'] = array();

            //Set  tab label
            array_push($tabLabel, $tab['label']);

            foreach($rows as $keyRow => $row){

                $fields = array();
                $aFieldValues = array();

                //for each field of tab
                foreach($tab['fields'] as $keyField => $field){

                    $value = (!strcmp($keyRow, 'default'))?null:$row[$keyField];
                    array_push($aFieldValues,$value);

                    $id    = isset($field['id'])?$panelid.'-'.$keyTab.'-'.$field['id']:$panelid."-".$keyTab."-".$keyField;
                    $name  = 'a_'.$tab['id'].'_'.$field['name'];
                    $label = isset($field['label'])?$field['label']:"";
                    $type  = isset($field['type'])?$field['type']:"text";
                    $width = isset($field['width'])?"style='width: ".$field['width'].";'":"";
                    $maxlength = isset($field['maxlength'])?"maxlength='".$field['maxlength']."'":"";
                    $onchange = isset($field['onchange'])?"onchange=".$field['onchange']."":"";
                    $readonly = (!is_null($value))?"disabled='disabled'":"";
                    $class = (!is_null($value))?"odpInputRO":"odpInputNotSaved odpNew";

                    $htmlfield = "";

                    //Set field masks into array
                    if(isset($field['mask'])){
                        array_push($masks, array('fieldid'=>$name, 'mask'=>$field['mask']));
                    }

                    //Verify field's type
                    if($type == "text"){
                        //Set the Header field
                        $hvalue = is_null($value)?"":"value='$value'";
                        $htmlfield = "<input id='".$id."' name='$name' class='$class' type='text' $maxlength $onchange $hvalue $readonly style='width: 100%;'>";

                    }elseif($type == "hidden"){
                        $hvalue = is_null($value)?"":"value='$value'";
                        $htmlfield = "<input name='$name' class='$class' type='$type' $maxlength $onchange $hvalue $readonly style='width: 100%;'>";

                    }elseif($type == "checkbox"){
                        $hvalue = is_null($value)?"":"value='$value'";
                        $htmlfield = "<input name='$name' class='$class' type='$type' $onchange $hvalue $readonly style='width: 100%;'>";

                    }elseif($type == "select"){
                        $loadType = isset($field['options']['load'])?'L':'F';

                        if(isset($field['options']['defineparameter'])){
                            foreach($field['options']['defineparameter'] as $keyDefPar => $columnToLoad){
                                $field['options']['by'][$keyDefPar] = $aFieldValues[$columnToLoad];
                            }
                        }

                        $htmlfield = Odpcp::select($loadType,$field['options'],$value,isset($field['onchange'])?$field['onchange']:null,$name,null,(!is_null($value)),$class);
                    }//End of field type verification

                    if(!strcmp($keyRow, 'default')){
                        //Set html label into array
                        array_push($fieldLabel, "$label	");
                    }

                    //Set html field into array
                    array_push($fields,$htmlfield);

                }//End of field

                $htmlfield = "";
                foreach($fields as $column){
                    $htmlfield = $htmlfield."".$column."	";
                }

                $htmlIco = "<input type='button' title='Salvar' class='odpButtonImg' style='background-image: url(\"".CT_FL_EXT_IMAGES."save.gif\");' onclick='".$panelid.$keyTab."SaveLine($(this).closest(\"tr\"));'>	".
                           "<input type='button' title='Editar' class='odpButtonImg' style='background-image: url(\"".CT_FL_EXT_IMAGES."edit.gif\");' onclick='".$panelid.$keyTab."EditLine($(this).closest(\"tr\"));'>	".
                           "<input type='button' title='Excluir' class='odpButtonImg' style='background-image: url(\"".CT_FL_EXT_IMAGES."delete.gif\");' onclick='".$panelid.$keyTab."RemoveLine($(this).closest(\"tr\"));'>	";
                //width='100%'
                if(!strcmp($keyRow, 'default')){
                    $htmlDef = $htmlfield.$htmlIco;
                }else{
                    $htmlRows = $htmlRows."
".$htmlfield.$htmlIco."
";
                }
            }//End of rows

            //Convert arrays values to html
            $htmllabel = "";
            foreach($fieldLabel as $column){
                $htmllabel = $htmllabel.$column;
            }

/*            $htmlvalidation = "";
            foreach($aFldValidation as $column){
                $htmlvalidation = $htmlvalidation.'if('.$column[0].'){alert("'.$column[1].'");return;}';
            }*/

            $htmlmask = "";
            foreach($masks as $column){
               // select[id|="mTabPn-0-city"]
                $htmlmask = $htmlmask.'$("input[name$=\''.$column['fieldid'].'\']").each(function(i){$("#"+$(this).attr("id")).mask("'.$column['mask'].'");});';
            }
            $htmlmask = sizeof($masks)?'jQuery(function($){'.$htmlmask.' });':"";

            //panel
            $htmltabs = $htmltabs.
            "

Novo

                                $htmlDef

                                $htmllabel

                            $htmlRows

";
        }//End of tab

        //odpItbPanHSel
        //odpItbPanHNSel
        $htmlHeader = "";
        foreach ($tabLabel as $key => $tlabel){
            $htmlHeader = $htmlHeader .
            "<a href='javascript:void(0);' id='".$panelid.$key."lbl' class='".(!$key?"odpTabSel":"odpTabNSel")."'
                onclick='jQuery(this).closest(\"div\").children(\"a\").each(".
                            "function(index) {".
                                "$(this).removeClass(\"odpTabSel\").addClass(\"odpTabNSel\");".
                            "});".
                          "jQuery(this).removeClass(\"odpTabNSel\").addClass(\"odpTabSel\");".
                          $panelid."Show($key);'".
             ">$tlabel";
        }

        $htmlHeader = "
".$htmlHeader.
        "".
        "
";

        return $htmlHeader.$htmltabs;
    }

    /*
     * $type = F(fixed) / L(load)
     *
     * Examples:
     * $type = F, $options = array(array('value'=>'1','label'=>'MG'),array('value'=>'2','label'=>'SP'))
     *
     * $type = L, $options = array('load'=>'State',                        //mandatory
     *                             'by'=>'array('id_city'=>'23')',         //optional
     *                             'value' => 'id',                        //mandatory = property of created object to get html option property 'value'
                                   'label' => 'nameCity'                   //mandatory = property of created object to get html option property 'label'
     *                            )
     *
     */
    public static function select($type='F',$options=array(), $selected=0,$nullable=false, $properties){

        $onchange= isset($properties['onchange'])?$properties['onchange']:null;
        $readonly = isset($properties['readonly'])?$properties['readonly']:false;
        $class = isset($properties['class'])?$properties['class']:'odpInput';
        $name = isset($properties['name'])?$properties['name']:null;
        $id = isset($properties['id'])?$properties['id']:null;
        $width = isset($properties['width'])?$properties['width']:'100%';
        $style = isset($properties['style'])?$properties['style']:'';

        $htmlSelOptions ="<option".($selected?" ":" selected='selected' ")."value='0'>Selecione uma opção</option>";

        if($type=='F'){
            foreach($options as $opt){
                $htmlSelOptions = $htmlSelOptions. "<option".($selected==$opt['value']?" selected='selected' ":" ")."value='".$opt['value']."'>".$opt['label']."</option>";
            }
        }elseif($type=='L' && isset($options['by'])){
            //Import Generic controller
            require_once Odpcp::$controllerFilepath.'/'.Odpcp::$genericControllerClass.'.php';
            //Import required class
            eval('require_once "'.Odpcp::$modelFilepath.'/'.$options['load'].'.php";');

            $generic=null;
            eval('$generic = new '.Odpcp::$genericControllerClass.'();');

            $listByObject = null;

            eval('$listByObject= new '.$options['load'].'();');

            foreach($options['by'] as $key => $data){
                if(is_null($data)){
                    $options['by'][$key] = 0;
                }
            }

            //Get list of objects
            $selOptionList = $generic->listByParameters($listByObject, $options['by']);

        }else{
            //Import Generic controller
            require_once Odpcp::$controllerFilepath.'/'.Odpcp::$genericControllerClass.'.php';
            //Import required class
            eval('require_once "'.Odpcp::$modelFilepath.'/'.$options['load'].'.php";');

            $generic=null;
            eval('$generic = new '.Odpcp::$genericControllerClass.'();');
            $listByObject = null;

            eval('$listByObject= new '.$options['load'].'();');

            $selOptionList = $generic->listAll($listByObject);
        }

        //Convert object list into html options
        if($type=='L'){
            foreach ($selOptionList as $optObj){
                $optObjValue = null;
                $optObjLabel = null;

                //Load Option Value
                eval('$optObjValue = $optObj->get'.ucfirst($options['value']).'();');
                if(is_object($optObjValue)){
                    $optObjValue = $optObjValue->getId();
                }
                //Load Option Label
                eval('$optObjLabel = $optObj->get'.ucfirst($options['label']).'();');
                if(is_object($optObjLabel)){
                    $optObjLabel = $optObjLabel->getId();
                }

                $htmlSelOptions = $htmlSelOptions. "<option".($selected==$optObjValue?" selected='selected' ":" ")."value='$optObjValue'>$optObjLabel</option>";
            }
        }

        if(!empty($onchange)){
            $onchange='onchange='.$onchange;
        }

        $xpto = "<select name='$name' id='$id' class='$class' ".($readonly?"disabled='disabled'":"")." $onchange "."style='".(!is_null($width)?"width: $width;":"").$style."'>$htmlSelOptions</select>";
//        echo $xpto;
        return $xpto;
    }

    /*

      array(  --Panel

            array(    --Tab
                   'label' =>'Telefones (exemplo)';
                   'fields'=>array(
                                     array(  --field text
                                           'id'      =>'name', //will be concatenated with panelid and tabid. Ex: wq-1-name
                                           'label'   =>'Nome',
                                           'type'    =>'text',  //text, checkbox, select
                                           'width'   =>'10%',
                                           'nullable'=> 'false',
                                           'maxlength' => 5,
                                           'onchange' => 'alert();', //javascript
                                           'mask' => '' //jquery.mask format
                                           ),
                                     array(  --field select
                                           'label'   =>'UF',
                                           'type'    =>'select',
                                           'width'   =>'10%',
                                           'nullable'=>'false',
                                           /## Options pode ser carregado de dois modos##/
                                           'options'=>array(
                                                             array('value'=>'10','label'=>'MG'),
                                                             array('value'=>'11','label'=>'SP')
                                                            )
                                           ou
                                           'options'=>array( 'load' => 'State', //obrigatório
                                                             'by'  => array(array('field1'=>'valor1'),  //opcional
                                                                            array('id_cidade'=>'23')),
                                                             'value' => 'id',  //property of created object to get html option property 'value'
                                                             'label' => 'nameCity' //property of created object to get html option property 'label'
                                                            )
                                           /## Fim options ##/
                                           )
                                   )
                  )
            ),
            array()--Tab2

      */
    public static function tabPanelInsert($array,$panelid) {

        $tabLabel = array();

        $html = "";
        $htmltabs = "";
        $masks = array();// like "array(array('fieldid'=>'','mask'=>''));"

        foreach($array as $keyTab => $tab){

            $fields = array();
            $fieldLabel =array();
            $fieldsnullable = array();
            $newLineFields = array();
            $aFldValidation = array();

            //Set  tab label
            array_push($tabLabel, $tab['label']);

            //for each field of tab
            foreach($tab['fields'] as $keyField => $field){

                $id    = isset($field['id'])?$panelid.'-'.$keyTab.'-'.$field['id']:$panelid."-".$keyTab."-".$keyField;
                $name  = 'a_'.$tab['id'].'_'.$field['name'];
                $label = isset($field['label'])?$field['label']:"";
                $type  = isset($field['type'])?$field['type']:"text";
                $width = isset($field['width'])?"style='width: ".$field['width'].";'":"";
                $maxlength = isset($field['maxlength'])?"maxlength='".$field['maxlength']."'":"";
                $onchange = isset($field['onchange'])?"onchange='".$field['onchange']."'":"";

                $htmlfield = "";

                //Set field masks into array
                if(isset($field['mask'])){
                    array_push($masks, array('fieldid'=>$id, 'mask'=>$field['mask']));
                }

                //Verify field's type
                if($type == "text"){
                    //Set the Header field
                    $htmlfield = "<input id='$id' name='$name' class='cadastroText' type='$type' $maxlength $onchange ".(!strpos($field['width'],'%')?$width:"style='width: 100%;'").">	";
                    //Set the field would be created when user click at add
                    array_push($newLineFields,'<input name=\'odpnewline\' class=\'odpTextboxRO\' readonly=\'readonly\' style=\'width: 100%;\' type=\'text\' value=\'"+$("#'.$id.'").val()+"\'>	');
                    //Set the validations
                    if(!isset($field['nullable'])){
                        array_push($aFldValidation, array('$("#'.$id.'").val().length == 0','Campo '.$field['label'].' deve ser informado'));
                    }

                }elseif($type == "hidden"){
                    $htmlfield = "<input id='$id' name='$name' class='cadastroText' type='$type' $maxlength $onchange ".(isset($field['width'])?$width:"style='width: 100%;'").">	";
                    array_push($newLineFields,'<input name=\'odpnewline\' class=\'odpTextboxRO\' readonly=\'readonly\' style=\'width: 100%;\' type=\'hidden\' value=\'"+$("#'.$id.'").val()+"\'>	');
                    //Set the validations
                    if(!isset($field['nullable'])){
                        array_push($aFldValidation, array('$("#'.$id.'").val().length == 0','Campo '.$field['label'].' deve ser informado'));
                    }

                }elseif($type == "checkbox"){
                    $htmlfield = "<input id='$id' name='$name' class='cadastroText' type='$type' $maxlength $onchange ".(!strpos($field['width'],'%')?$width:"style='width: 100%;'").">	";
                    array_push($newLineFields,'<input name=\'odpnewline\' class=\'odpTextboxRO\' readonly=\'readonly\' style=\'width: 100%;\' type=\'text\' value=\'"+$("#'.$id.'").is(":checked")?"Sim":"Não")+"\'>	');

                }elseif($type == "select"){
                    $loadType = isset($field['options']['load'])?'L':'F';
//($type='F',$options=array(), $selected=0, $onchange=null, $name=null,$nullable=false, $readonly=false, $class='odpInputRO')
                    $htmlfield = Odpcp::select($loadType,$field['options'],0,isset($field['onchange'])?$field['onchange']:null,$name,null,null,'odpInput',$id,(isset($field['width'])?(!strpos($field['width'],'%')?$field['width']:'100%'):null));
                    $htmlfield = "".$htmlfield."	";
                }//End of field type verification

                //Set html label into array
                array_push($fieldLabel, "$label	");

                //Set html field into array
                array_push($fields,$htmlfield);

            }//End of field

            //Convert arrays values to html
            $htmllabel = "";
            foreach($fieldLabel as $column){
                $htmllabel = $htmllabel.$column;
            }

            $htmlfield = "";
            foreach($fields as $column){
                $htmlfield = $htmlfield.$column;
            }

            $htmlnewline = "";
            foreach($newLineFields as $column){
                $htmlnewline = $htmlnewline.$column;
            }

            $htmlvalidation = "";
            foreach($aFldValidation as $column){
                $htmlvalidation = $htmlvalidation.'if('.$column[0].'){alert("'.$column[1].'");return;}';
            }

            $htmlmask = "";
            foreach($masks as $column){
                $htmlmask = $htmlmask.'$("#'.$column['fieldid'].'").mask("'.$column['mask'].'");';
            }
            $htmlmask = sizeof($masks)?'jQuery(function($){'.$htmlmask.' });':"";

            //panel
            $htmltabs = $htmltabs.
            "

                                $htmllabel

                                $htmlfield
                                <input type='button' class='odpButtonImg' style='background-image: url(\"".CT_FL_EXT_IMAGES."save.gif\");' onclick='".$panelid.$keyTab."SaveLine();'>

";

        }//End of tab

        //odpItbPanHSel
        //odpItbPanHNSel
        $htmlHeader = "";
        foreach ($tabLabel as $key => $tlabel){
            $htmlHeader = $htmlHeader .
            "<a href='javascript:void(0);' id='".$panelid.$key."lbl' class='".(!$key?"odpTabSel":"odpTabNSel")."'
                onclick='jQuery(this).closest(\"div\").children(\"a\").each(".
                            "function(index) {".
                                "$(this).removeClass(\"odpTabSel\").addClass(\"odpTabNSel\");".
                            "});".
                          "jQuery(this).removeClass(\"odpTabNSel\").addClass(\"odpTabSel\");".
                          $panelid."Show($key);'".
             ">$tlabel";
        }

        $htmlHeader = "
".$htmlHeader.
        "".
        "
";

        return $htmlHeader.$htmltabs;
    }

}

?>


text:
<?php

namespace Modules\Base\Libraries;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class BaseModel extends Model
{
    use SoftDeletes;
    protected $dates = ['deleted_at'];
}

redpajama_set_name: RedPajamaGithub


text:
const char PROTO_PATH_DELIMITER = '\\';

// Note: Windows already defines INT32 and UINT32 types
typedef signed char INT8;
typedef unsigned char UINT8;
typedef short INT16;
typedef unsigned short UINT16;

#else
#include <sys/types.h> // must include this first to make SGI's compiler happy
#include <sys/time.h>  // for UNIX gettimeofday(), etc
#ifdef FREEBSD4
#include <wchar.h>
#else
#include <stdint.h>    // for proper uint32_t, etc definitions
#endif // if/else freebsd4/other Unix
#include <limits.h>    // for PATH_MAX
const char PROTO_PATH_DELIMITER = '/';
#endif // if/else WIN32/UNIX

#ifdef SIMULATE
#ifdef NS2
#include "scheduler.h"
inline void ProtoSystemTime(struct timeval& theTime)
{
    double now = Scheduler::instance().clock();
    theTime.tv_sec = (unsigned long)(now);
    theTime.tv_usec = (unsigned long)((now - theTime.tv_sec) * 1.0e06);
}
#endif // NS2

#ifdef NS3
#include "ns3/simulator.h"
inline void ProtoSystemTime(struct timeval& theTime)
{
    double now = ns3::Simulator::Now().GetSeconds();
    theTime.tv_sec = (unsigned long)(now);
    theTime.tv_usec = (unsigned long)(now - theTime.tv_sec)*1.0e06;
}
#endif // NS3

#ifdef OPNET
#include "opnet.h"
inline void ProtoSystemTime(struct timeval& theTime)
{
    double current_time = op_sim_time();
    theTime.tv_sec = (unsigned long)(current_time);
    theTime.tv_usec = (unsigned long)((current_time - theTime.tv_sec) * 1.0e06);
}
#endif // OPNET

#else  // !SIMULATE

#ifdef WIN32

// NOTE: On _some_ WIN32 systems, it _may_ be beneficial to enable
//       the "USE_PERFORMANCE_COUNTER" macro.  It is done for WinCE
//       builds here because it is required to get sub-second
//       time of day granularity!  It is probably safer (for
//       the moment) to leave this undefined for most Win32 systems
//       because of various issues with the performance counter stuff,
//       but on certain systems may be useful to achieve high clock
//       granularity.  Uncomment the following line if desired:
#define USE_PERFORMANCE_COUNTER 1

#ifdef _WIN32_WCE
#define USE_PERFORMANCE_COUNTER 1
#endif // _WIN32_WCE

#ifdef USE_PERFORMANCE_COUNTER
// These funcs/variables are defined/inited in "protoTime.cpp"
inline LARGE_INTEGER ProtoGetPerformanceCounterFrequency()
{
    extern bool proto_performance_counter_init;
    extern LARGE_INTEGER proto_performance_counter_frequency;
    extern long proto_system_time_last_sec;
    extern unsigned long proto_system_count_roll_sec;
    extern LARGE_INTEGER proto_system_count_last;
    if (!proto_performance_counter_init)
    {
        QueryPerformanceFrequency(&proto_performance_counter_frequency);
        // Determine perf counter offset from system time
        extern long proto_performance_counter_offset;
        if (0 != proto_performance_counter_frequency.QuadPart)
        {
            LARGE_INTEGER count;
            FILETIME ft;
#ifdef _WIN32_WCE
			SYSTEMTIME st;
			QueryPerformanceCounter(&count);
			GetSystemTime(&st);
			SystemTimeToFileTime(&st, &ft);
#else
			QueryPerformanceCounter(&count);
			GetSystemTimeAsFileTime(&ft);
#endif // if/else _WIN32_WCE
            ULARGE_INTEGER systemTime = {ft.dwLowDateTime, ft.dwHighDateTime};
            // Convert system time to Jan 1, 1970 epoch
            const ULARGE_INTEGER epochTime = {0xD53E8000, 0x019DB1DE};
            systemTime.QuadPart -= epochTime.QuadPart;
            // Convert sytem time to seconds
            systemTime.QuadPart /= 10000000;
            // Save time and counter to detect possible counter rollover
            proto_system_time_last_sec = systemTime.LowPart;
            proto_system_count_last = count;
            proto_system_count_roll_sec = 0xffffffff / proto_performance_counter_frequency.LowPart;
            // Convert counter value to seconds
            count.QuadPart /= proto_performance_counter_frequency.QuadPart;
            proto_performance_counter_offset = systemTime.LowPart - count.LowPart;
        }
        proto_performance_counter_init = true;
    }
    return proto_performance_counter_frequency;
}  // end ProtoGetPerformanceCounterFrequency()
#endif // USE_PERFORMANCE_COUNTER

inline void ProtoSystemTime(struct timeval& theTime)
{
#ifdef USE_PERFORMANCE_COUNTER
    // We use the perf counter on WinCE so we can get better than
    // the one second granularity offered by WinCE GetSystemTime()
    // (TBD) This breaks if the user changes the system time _while_
    // a Protolib app is running, so this needs a better fix in
    // the long run.  For example, we could update the
    // "proto_performance_counter_offset" once in a while or if
    // we detect a significant delta in the counter-based time
    // and the actual system time ...
    LARGE_INTEGER counterFreq = ProtoGetPerformanceCounterFrequency();
    if (0 != counterFreq.QuadPart)
    {
        extern long proto_performance_counter_offset;
        extern long proto_system_time_last_sec;
        extern unsigned long proto_system_count_roll_sec;
        extern LARGE_INTEGER proto_system_count_last;
        // 1) Get current system time and performance counter count
		LARGE_INTEGER count;
        FILETIME ft;
#ifdef _WIN32_WCE
        SYSTEMTIME st;
		QueryPerformanceCounter(&count);
        GetSystemTime(&st);
        SystemTimeToFileTime(&st, &ft);
#else
		QueryPerformanceCounter(&count);
        GetSystemTimeAsFileTime(&ft);
#endif // if/else _WIN32_WCE
        ULARGE_INTEGER usec = {ft.dwLowDateTime, ft.dwHighDateTime};
        const ULARGE_INTEGER epochTime = {0xD53E8000, 0x019DB1DE};
        usec.QuadPart -= epochTime.QuadPart;
        ULARGE_INTEGER systemSecs;
        systemSecs.QuadPart =  (usec.QuadPart / 10000000);

        // Count rollover correction, if applicable
        if (count.HighPart < proto_system_count_last.HighPart)
            count.HighPart = proto_system_count_last.HighPart;
        // Rollover detection
        long timeDeltaSec = systemSecs.LowPart - proto_system_time_last_sec;
        bool rollover = false;
        if (count.QuadPart < proto_system_count_last.QuadPart)
        {
            rollover = true;
        }
        else
        {
            LARGE_INTEGER countDelta;
            countDelta.QuadPart = count.QuadPart - proto_system_count_last.QuadPart;
            countDelta.QuadPart /= counterFreq.QuadPart;  // delta in seconds
            long countDeltaSecs = countDelta.LowPart;
            if ((timeDeltaSec - countDeltaSecs) > (long)(proto_system_count_roll_sec >> 1))
                rollover = true;
        }
        if (rollover)
        {
            long rolloverCount = (timeDeltaSec / proto_system_count_roll_sec);
            if (0 != rolloverCount)
                count.HighPart += rolloverCount;
            else
                count.HighPart += 1;
        }
        proto_system_count_last = count;
        proto_system_time_last_sec = systemSecs.LowPart;

        // Compute whole seconds using (possibly corrected) counter value
        LARGE_INTEGER counterSec;
        counterSec.QuadPart = (count.QuadPart / counterFreq.QuadPart);
        theTime.tv_sec = counterSec.LowPart;
        // Adjust whole seconds by stored offset
        theTime.tv_sec += proto_performance_counter_offset;
        // Double-check our offset in case the user has changed system time
        // (Note counter drift may make this change, but only over _hopefully_
        //  a long interval time as "backwards" times might result
        long systemDelta = systemSecs.LowPart - theTime.tv_sec;
        if (labs(systemDelta) > 2)
        {
            theTime.tv_sec += systemDelta;
            proto_performance_counter_offset += systemDelta;
        }
        // Compute whole second count
        counterSec.QuadPart = counterSec.QuadPart * counterFreq.QuadPart;
        // Subtract to get fractional second count
        count.QuadPart = count.QuadPart - counterSec.QuadPart;
        // Scale to usec count
        count.QuadPart = 1000000 * count.QuadPart;
        // Compute usec
        LARGE_INTEGER counterUsec;
        counterUsec.QuadPart = count.QuadPart / counterFreq.QuadPart;
        theTime.tv_usec = counterUsec.LowPart;
    }
    else
#endif // USE_PERFORMANCE_COUNTER
    {
        FILETIME ft;
#ifdef _WIN32_WCE
        SYSTEMTIME st;
        GetSystemTime(&st);
        SystemTimeToFileTime(&st, &ft);
#else
        GetSystemTimeAsFileTime(&ft);
#endif // if/else _WIN32_WCE
        ULARGE_INTEGER usecTotal = {ft.dwLowDateTime, ft.dwHighDateTime};
        //epochTime = time for 00:00:0.00 1 Jan, 1970
        const ULARGE_INTEGER epochTime = {0xD53E8000, 0x019DB1DE};
        usecTotal.QuadPart -= epochTime.QuadPart;
        usecTotal.QuadPart /= 10;  // convert to microseconds
        theTime.tv_sec = (long)(usecTotal.QuadPart / 1000000);
        theTime.tv_usec = (long)(usecTotal.QuadPart - theTime.tv_sec * 1000000);
    }
}

#else

inline void ProtoSystemTime(struct timeval& theTime)
{
    struct timezone tz;
    gettimeofday(&theTime, &tz);
}

#endif  // if/else WIN32/UNIX

#endif // if/else SIMULATE

#ifndef PATH_MAX
#ifdef WIN32
#define PATH_MAX MAX_PATH
#else
#define PATH_MAX _POSIX_PATH_MAX
#endif // if/else WIN32/UNIX
#endif // !PATH_MAX

#ifndef NULL
#define NULL 0
#endif // !NULL

#ifndef WIN32
// Note: These are all already defined in WIN32 <basetsd.h>
typedef int8_t INT8;
typedef int16_t INT16;
#ifdef _USING_X11
typedef long int INT32;
#else
typedef int32_t INT32;
#endif // if/else _USING_X11
typedef uint8_t UINT8;
typedef uint16_t UINT16;
typedef uint32_t UINT32;
#endif  // !WIN32

#ifndef MAX
#define MAX(X,Y) ((X>Y)?(X):(Y))
#endif //!MAX
#ifndef MIN
#define MIN(X,Y) ((X<Y)?(X):(Y))
#endif //!MIN

#include "protoCheck.h"

#endif // _PROTO_DEFS


text:
from django import template
from django.utils.safestring import mark_safe
from bgundead.game.models import *

register = template.Library()

@register.filter
def pp_timedelta(td):
	"""
	Pretty-prints a timedelta representation a duration
	"""
	hours, remainder = divmod(td.seconds, 3600)
	minutes, seconds = divmod(remainder, 60)
	return "%s days, %s hours, %s minutes, %s seconds" % (td.days, hours, minutes, seconds)

@register.filter
def award_colorize(award):
	if award.redeem_type == 'H':
		return mark_safe("%s" % (award.name))
	elif award.redeem_type == 'Z':
		return mark_safe("%s" % (award.name))
	else:
		return award.name


text:
if (!window.InspectorExtensionRegistry) {
  /**
   * @unrestricted
   */
  Extensions.InspectorExtensionRegistryStub = class {
    getExtensionsAsync() {
    }
  };

  self.InspectorExtensionRegistry = new Extensions.InspectorExtensionRegistryStub();
}


text:
import os
import sys
import base64

from Crypto.Cipher import AES

flag = open("flag", "r").read().strip()
key = open("key", "r").read().strip()

welcome = """
{{welcome_message}}
"""

def encrypt():
    cipher = AES.new(base64.b16decode(key, casefold=True), AES.MODE_ECB)
    return base64.b16encode(cipher.encrypt(flag))

# flush output immediately
sys.stdout = os.fdopen(sys.stdout.fileno(), "w")
print(welcome)
print("KEY: " + key)
print("MESSAGE: " + encrypt().decode())


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The ASF licenses this file
  to you 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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<parent>
		<groupId>org.apache.isis.module</groupId>
		<artifactId>isis-module-devutils</artifactId>
        <version>2.0.0-SNAPSHOT</version>
	</parent>

	<artifactId>isis-module-devutils-impl</artifactId>

	<name>Isis Module: Developer Utilities implementation</name>
	<description>
		Implementation of the Developer Utilities module
	</description>

	<properties>
        <siteBaseDir>../..</siteBaseDir>
		<relativeUrl>module-devutils/impl/</relativeUrl>
	</properties>

    <url>http://isis.apache.org/${relativeUrl}</url>

	<dependencies>
        <dependency>
            <groupId>org.apache.isis.module</groupId>
            <artifactId>isis-module-devutils-applib</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.isis.core</groupId>
            <artifactId>isis-core-metamodel</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.isis.core</groupId>
            <artifactId>isis-core-unittestsupport</artifactId>
            <scope>test</scope>
        </dependency>
   </dependencies>

</project>


text:
#import "LKDBPersistenceObject.h"
#import <objc/runtime.h>
#import "LKDBSQLite.h"
#import "LKDBHelper.h"

@interface LKDBHelper(LKDBHelperQuery)

-(NSMutableArray *  _Nonnull )executeQuery:(NSString *  _Nonnull )sql toClass:(Class)modelClass;

-(NSMutableArray *  _Nonnull )executeQuery:(NSString *  _Nonnull )sql;

@end
@interface LKDBPersistenceObject()

+ (void)openFieldValidate;

@end
@implementation LKDBPersistenceObject

static BOOL openFieldValidate_Flag = false;
+ (void)openFieldValidate{
    openFieldValidate_Flag =  true;
}
+(void)initialize
{
#if DEBUG
    if(openFieldValidate_Flag){
        NSArray *  _Nonnull validateError = [[self class] validateFields:[self class]];
        if (validateError != nil) {
            NSException *  _Nonnull e = [[NSException alloc] initWithName:@"class define error!" reason:[validateError componentsJoinedByString:@"\n"] userInfo:nil];
            @throw e;
        }
    }
#endif
    //remove unwant property
    for (NSString *property in [[self class] transients]) {
        [self removePropertyWithColumnName:property];
    }

}

+ (NSDictionary *  _Nonnull )fields:(Class)class
{
    // Recurse up the classes, but stop at NSObject. Each class only reports its own properties, not those inherited from its superclass
    NSMutableDictionary *  _Nonnull theProps;

    if ([class superclass] != [NSObject class])
        theProps = (NSMutableDictionary *  _Nonnull )[[self class] fields:[class superclass]];
    else
        theProps = [NSMutableDictionary dictionary];

    unsigned int outCount;

    objc_property_t *propList = class_copyPropertyList(class, &outCount);

    // Loop through properties and add declarations for the create
    for (int i=0; i < outCount; i++)
    {
        objc_property_t oneProp = propList[i];

        NSString *propName = [NSString stringWithUTF8String:property_getName(oneProp)];
        NSString *attrs = [NSString stringWithUTF8String:property_getAttributes(oneProp)];

        // Read only attributes are assumed to be derived or calculated
        if ([attrs rangeOfString:@",R,"].location == NSNotFound)
        {
            NSArray *attrParts = [attrs componentsSeparatedByString:@","];
            if (attrParts != nil)
            {
                if ([attrParts count] > 0)
                {
                    NSString *propType = [[attrParts objectAtIndex:0] substringFromIndex:1];
                    [theProps setObject:propType forKey:propName];
                }
            }
        }
    }

    free(propList);

    return theProps;
}
+ (NSMutableArray *  _Nonnull )validateFields:(Class)class
{
    // Recurse up the classes, but stop at NSObject. Each class only reports its own properties, not those inherited from its superclass

    objc_property_t *propList;

    NSMutableArray *error=[[NSMutableArray alloc] init];
    [error addObject:[[NSMutableString alloc] initWithString:@"\n===============================对象定义错误========================================="]];
    [error addObject:[@"对象:" stringByAppendingString:[NSString stringWithUTF8String:class_getName(class)]]];

    @try {
        NSMutableDictionary *theProps;
        if ([class superclass] != [NSObject class])
            theProps = (NSMutableDictionary *)[[self class] fields:[class superclass]];
        else
            theProps = [NSMutableDictionary dictionary];

        unsigned int outCount;

        propList = class_copyPropertyList(class, &outCount);

        // Loop through properties and add declarations for the create
        for (int i=0; i < outCount; i++)
        {
            objc_property_t oneProp = propList[i];

            NSString *propName = [NSString stringWithUTF8String:property_getName(oneProp)];
            NSString *attrs = [NSString stringWithUTF8String:property_getAttributes(oneProp)];

            // Read only attributes are assumed to be derived or calculated
            if ([attrs rangeOfString:@",R,"].location == NSNotFound)
            {
//                attrs	__NSCFString *	@"T@\"NSString\",N,C,Vname"	0x00007fe32bb0ec80
//                attrs	__NSCFString *	@"T@\"NSNumber\",N,&,Vname"	0x00007f8682f1d3a0
//                attrs	__NSCFString *	@"Tq,V_rowid"	0x00007fb5a9e0dc90
//                attrs	__NSCFString *	@"Ti,N,V_name"	0x00007fb5a9f06fa0
//                attrs	__NSCFString *	@"T@\"TestObj\",&,N,V_name"	0x00007fd5ba509680

                if ([attrs rangeOfString:@"\\@"].location != NSNotFound){
                    if ([attrs rangeOfString:@"&"].location == NSNotFound){
                        NSMutableString *string=[[NSMutableString alloc] init];
                        [string appendString:@"参数 ["];
                        [string appendString:propName];
                        [string appendString:@"]: 类型错误 ,需要使用 strong 而不是 assgin"];
                        [error addObject:string];
                    }
                }else{
                    if ([attrs rangeOfString:@"&"].location != NSNotFound){
                        NSMutableString *string=[[NSMutableString alloc] init];
                        [string appendString:@"参数 ["];
                        [string appendString:propName];
                        [string appendString:@"]: 类型错误 ,需要使用 assgin 而不是 strong"];
                        [error addObject:string];
                    }

                }

            }
        }

    }
    @catch (NSException *exception) {
        [error addObject:[[exception callStackSymbols] componentsJoinedByString:@"\n"]];
    }@finally {
        if(propList)
            free(propList);
    }
    [error addObject:[[NSMutableString alloc] initWithString:@"\n========================================================================"]];
    if(error.count>3)
        return error;
    else {
        return nil;
    }
}

+ (NSMutableArray *  _Nonnull )validate:(LKDBPersistenceObject *  _Nonnull )object
{

    LKModelInfos*   _Nonnull infos = [[object class] getModelInfos];

    NSMutableArray *error=[[NSMutableArray alloc] init];
    [error addObject:[[NSMutableString alloc] initWithString:@"\n===============================数据与对象不匹配========================================="]];
    [error addObject:[[@"表名:" stringByAppendingString:[[object class] getTableName]] stringByAppendingString:@"\n\n"]];

    @try {
        for(int i=0;i<infos.count;i++){
            LKDBProperty *property =[infos objectWithIndex:i];

            NSString *propType = property.propertyType;
            NSString *propertyName = property.propertyName;

            id value = [object valueForKey:propertyName];

            if([value isKindOfClass:[NSNull class]]||value==nil)
                continue;

            if([propType isEqualToString:@"NSString"])
            {
                if([value isKindOfClass:[NSString class]])
                    continue;
            }else if([propType isEqualToString:@"NSData"])
            {
                if([value isKindOfClass:[NSData class]])
                    continue;
            }else if([propType isEqualToString:@"NSDate"])
            {
                if([value isKindOfClass:[NSDate class]])
                    continue;
            }else if([propType isEqualToString:@"NSNumber"])
            {
                if([value isKindOfClass:[NSNumber class]])
                    continue;
            }else
            {
                continue;
            }

            NSString *valueClassName=[NSString stringWithUTF8String:class_getName([value class])];

            NSMutableString *string=[[NSMutableString alloc] init];
            [string appendString:@"错误参数 ["];
            [string appendString:propertyName];
            [string appendString:@"]: 对象中错误的数据类型 "];
            [string appendString:@"["];
            [string appendString:valueClassName];
            [string appendString:@"], 实际需要的数据类型为实现或继承 "];
            [string appendString:@"["];
            [string appendString:propType];
            [string appendString:@"] Class的对象!"];
            [error addObject:string];

        }
    }
    @catch (NSException *exception) {
        [error addObject:[[exception callStackSymbols] componentsJoinedByString:@"\n"]];
    }
    [error addObject:[[NSMutableString alloc] initWithString:@"\n========================================================================"]];
    if(error.count>3)
        return error;
    else {
        return nil;
    }
}
+ (NSArray *  _Nonnull )transients{
    return nil;
}

+ (id _Nonnull)loadByRowid:(NSInteger)_rowid{
    return [[[[LKDBSQLite select:nil] from:[self class]] Where:LKDB_Equal_Int(@"rowid", _rowid)] querySingle];
}

- (id _Nonnull)reload{
    return [[[[LKDBSQLite select:nil] from:[self class]] Where:LKDB_Equal_Int(@"rowid", self.rowid)] querySingle];
}

+ (NSArray *   _Nonnull )listAll{
    return [[[LKDBSQLite select:nil] from:[self class]] queryList];
}

+ (int)count{
    return  [[[LKDBSQLite select:nil] from:[self class]] queryCount];
}

- (int)saveToDB{
    return  [LKDBSQLite insert:self];
}

- (int)updateToDB{
    return  [LKDBSQLite update:self];
}

- (void)deleteToDB{
    [LKDBSQLite delete:self];
}
+ (void)dropToDB{
    [LKDBSQLite dropTable:[self class]];
}
//+ (NSArray *  _Nonnull )execQuery:(NSString *  _Nonnull )sql{
//    return [[LKDBHelper getUsingLKDBHelper]  executeQuery:sql];
//}
//
//+ (NSArray *  _Nonnull )execQuery:(Class _Nonnull)clazz sql:(NSString *  _Nonnull )sql{
//
//    return [[LKDBHelper getUsingLKDBHelper]  executeQuery:sql toClass:clazz];
//}
//+ (BOOL)execSQL:(NSString *  _Nonnull )sql{
//    return [[LKDBHelper getUsingLKDBHelper]  executeSQL:sql arguments:nil];
//}
//- (NSArray *  _Nonnull )execQuery:(NSString * _Nonnull)sql{
//    return [[LKDBHelper getUsingLKDBHelper]  executeQuery:sql];
//}
//
//- (NSArray *  _Nonnull )execQuery:(Class _Nonnull)clazz sql:(NSString *  _Nonnull )sql{
//
//    return [[LKDBHelper getUsingLKDBHelper]  executeQuery:sql toClass:clazz];
//}
//- (BOOL)execSQL:(NSString *  _Nonnull )sql{
//    return [[LKDBHelper getUsingLKDBHelper]  executeSQL:sql arguments:nil];
//}
@end


text:
FROM anapsix/alpine-java:jdk8

MAINTAINER Mansheng Yang

RUN apk add --update wget jq coreutils

ENV KAFKA_VERSION="0.10.0.0" SCALA_VERSION="2.11"
ENV KAFKA_RELEASE_ARCHIVE kafka_${SCALA_VERSION}-${KAFKA_VERSION}.tgz

WORKDIR /tmp

RUN wget https://dist.apache.org/repos/dist/release/kafka/${KAFKA_VERSION}/${KAFKA_RELEASE_ARCHIVE} && \
  tar -xz -C /opt -f ${KAFKA_RELEASE_ARCHIVE} && \
  rm ${KAFKA_RELEASE_ARCHIVE}

ENV KAFKA_HOME /opt/kafka_${SCALA_VERSION}-${KAFKA_VERSION}
ADD start-kafka.sh /usr/bin/start-kafka.sh

VOLUME ["/data"]

# Use "exec" form so that it runs as PID 1 (useful for graceful shutdown)
CMD ["start-kafka.sh"]


text:
package org.sleuthkit.autopsy.actions;

import java.util.Collection;
import java.util.HashSet;
import java.util.logging.Level;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import org.openide.util.NbBundle;
import org.openide.util.Utilities;
import org.openide.windows.WindowManager;
import org.sleuthkit.autopsy.casemodule.Case;
import org.sleuthkit.autopsy.casemodule.NoCurrentCaseException;
import org.sleuthkit.autopsy.coreutils.Logger;
import org.sleuthkit.datamodel.AbstractFile;
import org.sleuthkit.datamodel.Content;
import org.sleuthkit.datamodel.TagName;
import org.sleuthkit.datamodel.TskCoreException;

/**
 * Instances of this Action allow users to apply tags to content.
 */
@NbBundle.Messages({
    "AddContentTagAction.singularTagFile=Add File Tag",
    "AddContentTagAction.pluralTagFile=Add File Tags",
    "# {0} - fileName",
    "AddContentTagAction.unableToTag.msg=Unable to tag {0}, not a regular file.",
    "AddContentTagAction.cannotApplyTagErr=Cannot Apply Tag",
    "# {0} - fileName",
    "AddContentTagAction.unableToTag.msg2=Unable to tag {0}.",
    "AddContentTagAction.taggingErr=Tagging Error",
    "# {0} - fileName", "# {1} - tagName",
    "AddContentTagAction.tagExists={0} has been tagged as {1}. Cannot reapply the same tag."
})
public class AddContentTagAction extends AddTagAction {

    // This class is a singleton to support multi-selection of nodes, since
    // org.openide.nodes.NodeOp.findActions(Node[] nodes) will only pick up an Action if every
    // node in the array returns a reference to the same action object from Node.getActions(boolean).
    private static AddContentTagAction instance;

    public static synchronized AddContentTagAction getInstance() {
        if (null == instance) {
            instance = new AddContentTagAction();
        }
        return instance;
    }

    private AddContentTagAction() {
        super("");
    }

    @Override
    protected String getActionDisplayName() {
        String singularTagFile = NbBundle.getMessage(this.getClass(), "AddContentTagAction.singularTagFile");
        String pluralTagFile = NbBundle.getMessage(this.getClass(), "AddContentTagAction.pluralTagFile");
        return Utilities.actionsGlobalContext().lookupAll(AbstractFile.class).size() > 1 ? pluralTagFile : singularTagFile;
    }

    @Override
    protected void addTag(TagName tagName, String comment) {
        /*
         * The documentation for Lookup.lookupAll() explicitly says that the
         * collection it returns may contain duplicates. Within this invocation
         * of addTag(), we don't want to tag the same AbstractFile more than
         * once, so we dedupe the AbstractFiles by stuffing them into a HashSet.
         *
         * We don't want VirtualFile and DerivedFile objects to be tagged.
         */
        final Collection<AbstractFile> selectedFiles = new HashSet<>(Utilities.actionsGlobalContext().lookupAll(AbstractFile.class));

        new Thread(() -> {
            for (AbstractFile file : selectedFiles) {
                try {
                    // Handle the special cases of current (".") and parent ("..") directory entries.
                    if (file.getName().equals(".")) {
                        Content parentFile = file.getParent();
                        if (parentFile instanceof AbstractFile) {
                            file = (AbstractFile) parentFile;
                        } else {
                            SwingUtilities.invokeLater(() -> {
                                JOptionPane.showMessageDialog(WindowManager.getDefault().getMainWindow(),
                                        NbBundle.getMessage(this.getClass(),
                                                "AddContentTagAction.unableToTag.msg",
                                                parentFile.getName()),
                                        NbBundle.getMessage(this.getClass(),
                                                "AddContentTagAction.cannotApplyTagErr"),
                                        JOptionPane.WARNING_MESSAGE);
                            });
                            continue;
                        }
                    } else if (file.getName().equals("..")) {
                        Content parentFile = file.getParent();
                        if (parentFile instanceof AbstractFile) {
                            parentFile = (AbstractFile) ((AbstractFile) parentFile).getParent();
                            if (parentFile instanceof AbstractFile) {
                                file = (AbstractFile) parentFile;
                            } else {
                                final Content parentFileCopy = parentFile;
                                SwingUtilities.invokeLater(() -> {
                                    JOptionPane.showMessageDialog(WindowManager.getDefault().getMainWindow(),
                                            NbBundle.getMessage(this.getClass(),
                                                    "AddContentTagAction.unableToTag.msg",
                                                    parentFileCopy.getName()),
                                            NbBundle.getMessage(this.getClass(),
                                                    "AddContentTagAction.cannotApplyTagErr"),
                                            JOptionPane.WARNING_MESSAGE);
                                });
                                continue;
                            }
                        } else {
                            final Content parentFileCopy = parentFile;
                            SwingUtilities.invokeLater(() -> {
                                JOptionPane.showMessageDialog(WindowManager.getDefault().getMainWindow(),
                                        NbBundle.getMessage(this.getClass(),
                                                "AddContentTagAction.unableToTag.msg",
                                                parentFileCopy.getName()),
                                        NbBundle.getMessage(this.getClass(),
                                                "AddContentTagAction.cannotApplyTagErr"),
                                        JOptionPane.WARNING_MESSAGE);
                            });
                            continue;
                        }
                    }

                    Case.getCurrentCaseThrows().getServices().getTagsManager().addContentTag(file, tagName, comment);
                } catch (TskCoreException | NoCurrentCaseException ex) {
                    Logger.getLogger(AddContentTagAction.class.getName()).log(Level.SEVERE, "Error tagging result", ex); //NON-NLS
                    AbstractFile fileCopy = file;
                    SwingUtilities.invokeLater(() -> {
                        JOptionPane.showMessageDialog(WindowManager.getDefault().getMainWindow(),
                                NbBundle.getMessage(this.getClass(),
                                        "AddContentTagAction.unableToTag.msg2",
                                        fileCopy.getName()),
                                NbBundle.getMessage(this.getClass(), "AddContentTagAction.taggingErr"),
                                JOptionPane.ERROR_MESSAGE);
                    });
                    break;
                }
            }
        }).start();
    }
}


text:
/*================================================================================
  code generated by: java2cpp
  author: Zoran Angelov, mailto://baldzar@gmail.com
  class: org.apache.http.impl.auth.BasicSchemeFactory
================================================================================*/

#ifndef J2CPP_INCLUDE_IMPLEMENTATION

#ifndef J2CPP_ORG_APACHE_HTTP_IMPL_AUTH_BASICSCHEMEFACTORY_HPP_DECL
#define J2CPP_ORG_APACHE_HTTP_IMPL_AUTH_BASICSCHEMEFACTORY_HPP_DECL

namespace j2cpp { namespace java { namespace lang { class Object; } } }
namespace j2cpp { namespace org { namespace apache { namespace http { namespace params { class HttpParams; } } } } }
namespace j2cpp { namespace org { namespace apache { namespace http { namespace auth { class AuthScheme; } } } } }
namespace j2cpp { namespace org { namespace apache { namespace http { namespace auth { class AuthSchemeFactory; } } } } }

#include <java/lang/Object.hpp>
#include <org/apache/http/auth/AuthScheme.hpp>
#include <org/apache/http/auth/AuthSchemeFactory.hpp>
#include <org/apache/http/params/HttpParams.hpp>

namespace j2cpp {

namespace org { namespace apache { namespace http { namespace impl { namespace auth {

	class BasicSchemeFactory;
	class BasicSchemeFactory
		: public object<BasicSchemeFactory>
	{
	public:

		J2CPP_DECLARE_CLASS

		J2CPP_DECLARE_METHOD(0)
		J2CPP_DECLARE_METHOD(1)

		explicit BasicSchemeFactory(jobject jobj)
		: object<BasicSchemeFactory>(jobj)
		{
		}

		operator local_ref<java::lang::Object>() const;
		operator local_ref<org::apache::http::auth::AuthSchemeFactory>() const;

		BasicSchemeFactory();
		local_ref< org::apache::http::auth::AuthScheme > newInstance(local_ref< org::apache::http::params::HttpParams >  const&);
	}; //class BasicSchemeFactory

} //namespace auth
} //namespace impl
} //namespace http
} //namespace apache
} //namespace org

} //namespace j2cpp

#endif //J2CPP_ORG_APACHE_HTTP_IMPL_AUTH_BASICSCHEMEFACTORY_HPP_DECL

#else //J2CPP_INCLUDE_IMPLEMENTATION

#ifndef J2CPP_ORG_APACHE_HTTP_IMPL_AUTH_BASICSCHEMEFACTORY_HPP_IMPL
#define J2CPP_ORG_APACHE_HTTP_IMPL_AUTH_BASICSCHEMEFACTORY_HPP_IMPL

namespace j2cpp {

org::apache::http::impl::auth::BasicSchemeFactory::operator local_ref<java::lang::Object>() const
{
	return local_ref<java::lang::Object>(get_jobject());
}

org::apache::http::impl::auth::BasicSchemeFactory::operator local_ref<org::apache::http::auth::AuthSchemeFactory>() const
{
	return local_ref<org::apache::http::auth::AuthSchemeFactory>(get_jobject());
}

org::apache::http::impl::auth::BasicSchemeFactory::BasicSchemeFactory()
: object<org::apache::http::impl::auth::BasicSchemeFactory>(
	call_new_object<
		org::apache::http::impl::auth::BasicSchemeFactory::J2CPP_CLASS_NAME,
		org::apache::http::impl::auth::BasicSchemeFactory::J2CPP_METHOD_NAME(0),
		org::apache::http::impl::auth::BasicSchemeFactory::J2CPP_METHOD_SIGNATURE(0)
	>()
)
{
}

local_ref< org::apache::http::auth::AuthScheme > org::apache::http::impl::auth::BasicSchemeFactory::newInstance(local_ref< org::apache::http::params::HttpParams > const &a0)
{
	return call_method<
		org::apache::http::impl::auth::BasicSchemeFactory::J2CPP_CLASS_NAME,
		org::apache::http::impl::auth::BasicSchemeFactory::J2CPP_METHOD_NAME(1),
		org::apache::http::impl::auth::BasicSchemeFactory::J2CPP_METHOD_SIGNATURE(1),
		local_ref< org::apache::http::auth::AuthScheme >
	>(get_jobject(), a0);
}

J2CPP_DEFINE_CLASS(org::apache::http::impl::auth::BasicSchemeFactory,"org/apache/http/impl/auth/BasicSchemeFactory")
J2CPP_DEFINE_METHOD(org::apache::http::impl::auth::BasicSchemeFactory,0,"<init>","()V")
J2CPP_DEFINE_METHOD(org::apache::http::impl::auth::BasicSchemeFactory,1,"newInstance","(Lorg/apache/http/params/HttpParams;)Lorg/apache/http/auth/AuthScheme;")

} //namespace j2cpp

#endif //J2CPP_ORG_APACHE_HTTP_IMPL_AUTH_BASICSCHEMEFACTORY_HPP_IMPL

#endif //J2CPP_INCLUDE_IMPLEMENTATION


text:
<?php

namespace SimpleMessage;

class PlainMessage {
	/**
	 * some explicit header setters aren't a bad idea
	 */
	use CommonHeadersTrait;
	/**
	 * the array of message headers
	 */
	protected $headers = array();
	/**
	 * the body of the message
	 */
	protected $message;
	/**
	 * the line ending delimiter
	 */
	protected $delim = "\r\n";
	/**
	 * method to set a message header
	 * @param array $header an array of header-name => value
	 * @return
	 */
	function setHeaders(array $header){
		foreach($header as $key => $value){
			$this->headers[strtolower($key)] = $value;
		}
	}
	/**
	 * allows internal access to headers
	 * @param string $header The name of the header to get
	 * @return mixed
	 */
	protected function getHeader($key){
		$key = strtolower($key);
		if(!array_key_exists($key, $this->headers)){ return null; }
		return $this->headers[$key];
	}
	/**
	 * method to set the message property
	 * @param string $message The message
	 * @return
	 */
	function setMessage($message){
		$this->message = $message;
	}
	/**
	 * method to format a message header
	 * @param string $key The message header value
	 * @param mixed $value The value of the header. Arrays are imploded via comma
	 * @return string
	 */
	protected function formatHeader($key, $value){
		if(is_array($value)){
			$value = implode(", ", $value);
		}
		$value = strtr($value, "\r\n\t", "   ");
		return sprintf("%s: %s%s", ucwords($key), trim($value), $this->delim);
	}
	/**
	 * method to take the $headers array and combine it into a header block for the message
	 * @return string
	 */
	protected function assembleHeaders(){

		$headers = "";

		//recommended order
		$ordered = array("return-path", "received", "date", "from", "subject", "sender", "to", "cc", "bcc");

		foreach($ordered as $key){
			if(array_key_exists($key, $this->headers)){
				$headers .= $this->formatHeader($key, $this->headers[$key]);
			}
		}

		//collapse the rest
		foreach($this->headers as $header => $value){
			if(!in_array($header, $ordered)){
				$headers .= $this->formatHeader($header, $value);
			}
		}

		return $headers;
	}
	/**
	 * method to order the pieces and out up the message as a string.
	 * @return string
	 */
	function marshal(){

		$this->setHeaders(["content-type" => "text/plain; charset=utf-8"]);

		$headers = $this->assembleHeaders();

		$message = "";
		$message .= $headers;
		$message .= $this->delim;
		$message .= strip_tags($this->message);
		$message .= $this->delim;
		return $message;
	}
}


text:
All notable changes to this module will be documented in this file.

## [1.0.1] - 2016-03-09
### Changed
- api.php (`GetList`): support search for multiple service names.

## [1.0.0] - 2016-02-29
The module was created by @alekseynemiro.


text:
import {LinkNode} from '../../node'
import {SpecificVisitor} from '../visitor'
import label from './label'
import entityPrefixLength from '../entity-prefix-length'

/*
 * Punctuation characters.
 */

const PUNCTUATION = /[-!"#$%&'()*+,.\/:;<=>?@\[\\\]^`{|}~_]/

/**
 * For shortcut and collapsed reference links, the contents
 * is also an identifier, so we need to restore the original
 * encoding and escaping that were present in the source
 * string.
 *
 * This function takes the unescaped & unencoded value from
 * shortcut's child nodes and the identifier and encodes
 * the former according to the latter.
 *
 * @example
 *   copyIdentifierEncoding('a*b', 'a\\*b*c')
 *   // 'a\\*b*c'
 *
 * @param {string} value - Unescaped and unencoded stringified
 *   link value.
 * @param {string} identifier - Link identifier.
 * @return {string} - Encoded link value.
 */
function copyIdentifierEncoding (value: string, identifier: string): string {
  let index = 0
  let position = 0
  const result: string[] = []

  while (index < value.length) {
    /*
     * Take next non-punctuation characters from `value`.
     */

    let start = index

    while (
        index < value.length &&
        !PUNCTUATION.test(value.charAt(index))
    ) {
      index += 1
    }

    result.push(value.slice(start, index))

    /*
     * Advance `position` to the next punctuation character.
     */
    while (
      position < identifier.length &&
      !PUNCTUATION.test(identifier.charAt(position))
    ) {
      position += 1
    }

    /*
     * Take next punctuation characters from `identifier`.
     */
    start = position

    while (
      position < identifier.length &&
      PUNCTUATION.test(identifier.charAt(position))
    ) {
      if (identifier.charAt(position) === '&') {
        position += entityPrefixLength(identifier.slice(position))
      }
      position += 1
    }

    result.push(identifier.slice(start, position))

    /*
     * Advance `index` to the next non-punctuation character.
     */
    while (index < value.length && PUNCTUATION.test(value.charAt(index))) {
      index += 1
    }
  }

  return result.join('')
}

const visitor: SpecificVisitor<LinkNode> = (compiler, node) => {
  compiler.context.inLink = true
  compiler.context.inShortcutReference = node.referenceType === 'shortcut'
  compiler.context.inCollapsedReference = node.referenceType === 'collapsed'
  let value = compiler.all(node).join('')

  compiler.context.inLink = false
  compiler.context.inShortcutReference = false
  compiler.context.inCollapsedReference = false

  if (
    node.referenceType === 'shortcut' ||
    node.referenceType === 'collapsed'
  ) {
    value = copyIdentifierEncoding(value, node.identifier)
  }

  return `[${value}]` + label(node)
}

export default visitor


text:
package org.wickedsource.coderadar.metricquery.rest.commit.metric.series;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.convert.Jsr310Converters;
import org.springframework.stereotype.Component;
import org.wickedsource.coderadar.commit.domain.Commit;
import org.wickedsource.coderadar.commit.domain.CommitRepository;
import org.wickedsource.coderadar.commit.domain.DateCoordinates;
import org.wickedsource.coderadar.core.configuration.CoderadarConfiguration;
import org.wickedsource.coderadar.core.rest.dates.Week;
import org.wickedsource.coderadar.core.rest.dates.series.Point;
import org.wickedsource.coderadar.core.rest.dates.series.WeekPoint;
import org.wickedsource.coderadar.metric.domain.metricvalue.MetricValueRepository;
import org.wickedsource.coderadar.metricquery.rest.commit.DateSeries;

import java.time.LocalDate;
import java.util.List;

import static java.time.temporal.ChronoUnit.WEEKS;

@Component
public class WeekSeriesFactory extends MetricValueSeriesFactory<Week> {

    private CommitRepository commitRepository;

    private CoderadarConfiguration config;

    @Autowired
    public WeekSeriesFactory(MetricValueRepository metricValueRepository, CommitRepository commitRepository, CoderadarConfiguration config) {
        super(metricValueRepository);
        this.commitRepository = commitRepository;
        this.config = config;
    }

    @Override
    protected DateSeries<Week> createEmptySeries(LocalDate startDate, LocalDate endDate) {
        DateSeries<Week> series = new DateSeries<>();
        for (int i = 0; i < WEEKS.between(startDate, endDate) + 1; i++) {
            LocalDate nextDate = startDate.plus(i, WEEKS);
            DateCoordinates dateCoordinates = new DateCoordinates(Jsr310Converters.LocalDateToDateConverter.INSTANCE.convert(nextDate), config.getDateLocale());
            Week week = new Week(dateCoordinates.getYearOfWeek(), dateCoordinates.getWeekOfYear());
            series.addPoint(new WeekPoint(week, null));
        }
        return series;
    }

    @Override
    protected List<Commit> getLastCommitPerInterval(Long projectId, LocalDate startDate, LocalDate endDate) {
        return commitRepository.findLastForEachWeek(projectId,
                Jsr310Converters.LocalDateToDateConverter.INSTANCE.convert(startDate),
                Jsr310Converters.LocalDateToDateConverter.INSTANCE.convert(endDate));
    }

    @Override
    protected Point<Week, Long> createPointForCommit(Commit commit, Long value) {
        Week week = new Week(commit.getDateCoordinates().getYearOfWeek(), commit.getDateCoordinates().getWeekOfYear());
        return new WeekPoint(week, value);
    }

}


text:
#ifndef ASLAM_BACKEND_OPTIMIZATION_PROBLEM_SIMPLE2
#define ASLAM_BACKEND_OPTIMIZATION_PROBLEM_SIMPLE2

#include "OptimizationProblemBase.hpp"
#include <boost/shared_ptr.hpp>
#include <vector>

#include <unordered_map>

namespace aslam {
  namespace backend {

    /**
     * \class SimpleOptimizationProblem
     *
     * \brief a simple implementation of the optimzation problem that
     *        only stores containers of design variables and error terms.
     *        This container owns the design variables and error terms and
     *        it will call delete on them when it goes out of scope.
     */
    class SimpleOptimizationProblem : public OptimizationProblemBase {
    public:
      SimpleOptimizationProblem();
      virtual ~SimpleOptimizationProblem();

      /// \brief Add a design variable to the problem. If the second
      /// argument is true, the design variable will be deleted
      /// when the problem is cleared or goes out of scope.
      void addDesignVariable(DesignVariable* dv, bool problemOwnsVariable);

      /// \brief Add a design variable to the problem.
      void addDesignVariable(boost::shared_ptr<DesignVariable> dv);

      /// \brief Add an error term to the problem. If the second
      /// argument is true, the error term will be deleted when the
      /// problem is cleared or goes out of scope.
      void addErrorTerm(ErrorTerm* dv, bool problemOwnsVariable);

      /// \brief Add an error term to the problem
      virtual void addErrorTerm(const boost::shared_ptr<ErrorTerm> & et);

      /// \brief clear the design variables and error terms.
      void clear();

      /// \brief used for debugging...is the design variable in the problem.
      bool isDesignVariableInProblem(const DesignVariable* dv);
    protected:
      virtual size_t numDesignVariablesImplementation() const;
      virtual DesignVariable* designVariableImplementation(size_t i);
      virtual const DesignVariable* designVariableImplementation(size_t i) const;

      virtual size_t numErrorTermsImplementation() const;
      virtual ErrorTerm* errorTermImplementation(size_t i);
      virtual const ErrorTerm* errorTermImplementation(size_t i) const;

      virtual void getErrorsImplementation(const DesignVariable* dv, std::set<ErrorTerm*>& outErrorSet);

      // \todo Replace these std::vectors by something better. The underlying algorithms that this object
      //       supports suck with these containers. Blerg. See "removeDesignVariable()" for an example of
      //       just how bad this is.
      std::vector< boost::shared_ptr<DesignVariable> > _designVariables;
      std::vector< boost::shared_ptr<ErrorTerm> > _errorTerms;
    };

  } // namespace backend
} // namespace aslam

#endif /* ASLAM_BACKEND_OPTIMIZATION_PROBLEM_SIMPLE2 */


text:
/* -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 8 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "mozilla/ipc/IOThreadChild.h"

#include "IPDLUnitTestProcessChild.h"
#include "IPDLUnitTests.h"

#include "nsRegion.h"

using mozilla::ipc::IOThreadChild;

namespace mozilla {
namespace _ipdltest {

bool
IPDLUnitTestProcessChild::Init()
{
    IPDLUnitTestChildInit(IOThreadChild::channel(),
                          ParentHandle(),
                          IOThreadChild::message_loop());

    if (NS_FAILED(nsRegion::InitStatic()))
      return false;

    return true;
}

} // namespace _ipdltest
} // namespace mozilla


text:
source ~/.config/danielbaird-osx/bin/homebrew-tools.sh # adds the cask-ensure-installed function
source ~/.config/danielbaird-osx/bin/macos-tools.sh # this adds the add-to-dock function

cask-ensure-installed keepingyouawake
open /Applications/KeepingYouAwake.app

cask-ensure-installed itsycal
open /Applications/Itsycal.app

# cask-ensure-installed 1password

cask-ensure-installed spotify
add-to-dock /Applications/Spotify.app

cask-ensure-installed vlc

cask-ensure-installed slack
add-to-dock /Applications/Slack.app

cask-ensure-installed skype
add-to-dock /Applications/Skype.app

cask-ensure-installed spectacle
open /Applications/Spectacle.app


text:
static E: bool = 1is == 2; //~ ERROR static assertion failed

fn main() {}


text:
namespace VCSJones.FiddlerCertGen.Interop
{
    internal static class SECURITY_STATUS
    {
        public const uint ERROR_SUCCESS = 0;
        public const uint NTE_BAD_KEYSET = 0x80090016;
    }
}


text:
from status.util import SafeHandler
from datetime import datetime

thresholds = {
    'HiSeq X': 320,
    'RapidHighOutput': 188,
    'HighOutput': 143,
    'RapidRun': 114,
    'MiSeq Version3': 18,
    'MiSeq Version2': 10,
    'MiSeq Version2Nano': 0.75,
    'NovaSeq SP': 325,
    'NovaSeq S1': 650,
    'NovaSeq S2': 1650,
    'NovaSeq S4': 2000,
    'NextSeq Mid' : 25,
    'NextSeq High' : 75,
    'NextSeq 2000 P1' : 100,
    'NextSeq 2000 P2' : 400,
    'NextSeq 2000 P3' : 1100
}

class FlowcellHandler(SafeHandler):
    """ Serves a page which shows information for a given flowcell.
    """
    def __init__(self, application, request, **kwargs):
        # to cache a list of project_names ->
        # then we don't query statusdb each time when accessing the flowcell page
        self._project_names = {}
        super(SafeHandler, self).__init__(application, request, **kwargs)

    def _get_project_id_by_name(self, project_name):
        if project_name not in self._project_names:
            view = self.application.projects_db.view('project/project_name')[project_name]
            # should be only one row, if not - will overwrite
            for row in view.rows:
                doc_id = row.value
                project_doc = self.application.projects_db.get(doc_id)
                project_id = project_doc.get('project_id')
                self._project_names[project_name] = project_id
        return self._project_names.get(project_name, '')

    def _get_project_list(self, flowcell):
        # replace '__' in project name
        replaced_plist = []
        if 'plist' in flowcell:
            for project in flowcell['plist']:
                if '__' in project:
                    project = project.replace('__', '.')
                else: # replace only the first one
                    project = project.replace('_', '.', 1)
                if project != 'default':
                    replaced_plist.append(project)
        return replaced_plist

    def find_DB_entry(self, flowcell_id):
        #Returns Runid (key), contents (complex)
        view = self.application.x_flowcells_db.view('info/summary2_full_id', key=flowcell_id)

        if view.rows:
            return view.rows[0]

        # No hit for a full name, check if the short name is found:
        complete_flowcell_rows = self.application.x_flowcells_db.view(
                                    'info/short_name_to_full_name',
                                    key=flowcell_id
                                ).rows

        if complete_flowcell_rows:
            complete_flowcell_id = complete_flowcell_rows[0].value
            view = self.application.x_flowcells_db.view(
                        'info/summary2_full_id',
                        key=complete_flowcell_id,
                        )

            if view.rows:
                return view.rows[0]

        return False

    def get(self, flowcell_id):

        entry = self.find_DB_entry(flowcell_id)

        if not entry:
            extra_message=""
            flowcell_date = datetime.strptime(flowcell_id[0:6], "%y%m%d")
            first_xflowcell_record = datetime(2015,3,13)
            if first_xflowcell_record>flowcell_date:
                extra_message = "Your flowcell is in an older database. It can still be accessed, contact your administrator."

            self.set_status(200)
            t = self.application.loader.load("flowcell_error.html")
            self.write(t.generate(gs_globals=self.application.gs_globals,
                                  flowcell_id=flowcell_id,
                                  user=self.get_current_user(),
                                  extra_message=extra_message
                                  ))
            return
        else:
            # replace '__' in project name
            entry.value['plist'] = self._get_project_list(entry.value)
            # list of project_names -> to create links to project page and bioinfo tab
            project_names = {project_name: self._get_project_id_by_name(project_name) for project_name in entry.value['plist']}
            t = self.application.loader.load("flowcell.html")
            self.write(t.generate(gs_globals=self.application.gs_globals,
                                  flowcell=entry.value,
                                  flowcell_id=flowcell_id,
                                  thresholds=thresholds,
                                  project_names=project_names,
                                  user=self.get_current_user()))


text:
const fs = require('fs');
const watch = require('node-watch');
const crypto = require('crypto');
const promisify = require('util').promisify;
const join = require('path').join;
const Storage = require('./storage.sut');
const sut = require('../../sut');

const HISTORY_DIR = '.sut';
const DATABASE_FILE = 'sut-db.json';

const SALT = 'generate-sut-hash';

const $build = {
  count: (fs.existsSync(join(HISTORY_DIR, DATABASE_FILE))) ? read_sut_db().build : Storage.BUILD,
  prev: ''
};

function create_sut_db(build, cb) {
  const database = {
    "build": build,
    "date": Date.now()
  };
  fs.writeFile(join(HISTORY_DIR, DATABASE_FILE), JSON.stringify(database, null, 2), (err) => {
    if (err) cb(false);

    if (!fs.existsSync(`${HISTORY_DIR}/${DATABASE_FILE}`))
      console.log(`> Building Database ...`);
    else
      console.log(`> Update Database: ${HISTORY_DIR}/${DATABASE_FILE}`);

    cb(true);
  });
}

function read_sut_db() {
  let data = fs.readFileSync(join(HISTORY_DIR, DATABASE_FILE), 'utf8');
  return {
    build: JSON.parse(data).build
  }
}

function create_build_history(e, name) {

  $build.count++;

  if (fs.existsSync(HISTORY_DIR)) {
    create_sut_db($build.count, (status) => (status &&
                  write(e, name, read_sut_db().build)))
  } else {

    const folder = fs.mkdirSync(HISTORY_DIR);

    if (folder)
      create_sut_db($build.count, (status) => (status &&
                    write(e, name, read_sut_db().build)))
  }

}

function write(e, name, build) {

  const hash = crypto.createHmac('sha256', SALT)
                      .update(`${name}-${e}-${$build.count}`)
                      .digest('hex');

  sut.store.all.BUILD = build;

  /*
  * Skip Genesis Package
  */
  if ( build === null ) return;

  if (build == 2) {
    sut.store.all.PREV_BUILD = `${HISTORY_DIR}/${name}-${e}-${build}.json`
  }

  if (build > 2) {
    /*
    * if build history was cleard, inital build count from current build
    */
    if (fs.existsSync(`${HISTORY_DIR}/${name}-${e}-${build-2}.json`))
      sut.store.all.PREV_BUILD = `${HISTORY_DIR}/${name}-${e}-${build-2}.json`;
    else
      sut.store.all.PREV_BUILD = `${HISTORY_DIR}/${name}-${e}-${build}.json`
  }

  /*
  * Skip odd build's to update test
  */
  if ( build % 2 === 0 ) {
    fs.writeFile(`${HISTORY_DIR}/${name}-${e}-${build}.json`, JSON.stringify(sut.store.all, null, 2),
        (err) => {
          if (err) SUTHandler(`Failed to save build ${build} for ${name}-${e}-${build}.json`, 0);
          console.log(`> Build History (${e}-${build}) -> ${hash}`);
        }
    );
  }

}

exports.createHistory = options => {
  if (options.build) {
    watch('./', { filter: /\.js$/ },
      (e, name) => create_build_history(e, name));
  }
}