text:
<?php

namespace app\controllers;

use app\models\EmployeeIncome;
use app\models\EmployeeOutcome;
use app\models\EmployeeOutcomeSearch;
use app\models\EmployeeIncomeSearch;
use app\models\Employees;
use app\models\IncomeTime;
use app\models\OutcomeTime;
use yii;
use yii\data\ActiveDataProvider;
use yii\db\Query;
use yii\helpers\VarDumper;
use yii\web\Controller;
use Google\Spreadsheet\DefaultServiceRequest;
use Google\Spreadsheet\ServiceRequestFactory;
use Google\Spreadsheet\SpreadsheetService;
use Google\Spreadsheet\Batch\BatchRequest;

class SiteController extends Controller
{
    const SECONDS_PER_DAY = 86400;
    const SECONDS_PER_MONTH = 2678400;
    const DAY_OFF_TRUE = 1;

    public function actionIndex()
    {
        $dataProvider = new ActiveDataProvider([
            'query' => EmployeeIncomeSearch::find()
                ->innerJoin('income_time it', 'it.id = employee_income.income_id'),
            'pagination' => [
                'pageSize' => 20,
            ],
        ]);
        $dataProvider->query->addOrderBy(['time' => SORT_DESC]);

        //  VarDumper::dump($dataProvider, 10, true);
        return $this->render('index', [
            'dataProvider' => $dataProvider,
            'messageFirst' => 'income'
        ]);
    }

    public function actionOutcome()
    {
        $dataProvider = new ActiveDataProvider([
            'query' => EmployeeOutcomeSearch::find()
                ->innerJoin('outcome_time ot', 'ot.id = employee_outcome.outcome_id'),
            'pagination' => [
                'pageSize' => 20,
            ],
        ]);
        $dataProvider->query->addOrderBy(['time' => SORT_DESC]);

        return $this->render('index', [
            'dataProvider' => $dataProvider,
            'messageFirst' => 'outcome'
        ]);
    }

    public function actionIncome_ajax($date)
    {
        $currDate = new \DateTime();
        $currDate->setTimestamp($date);
        $endOfDay = $currDate->format('23:59:59 d-m-Y');
        $var = new \DateTime($endOfDay);
        $endOfDayTimestamp = (string)$var->getTimestamp();

        //VarDumper::dump($endOfDayTimestamp, 10, true);

        $dataProvider = new ActiveDataProvider([
            'query' => EmployeeIncomeSearch::find()
                ->innerJoin('income_time it', 'it.id = employee_income.income_id')
                ->where('it.time > :date AND it.time < :nextDay',
                    [':date' => $date, ':nextDay' => $endOfDayTimestamp]),
            'pagination' => [
                'pageSize' => false,
            ],
        ]);
        $dataProvider->query->addOrderBy(['time' => SORT_DESC]);

        return $this->renderAjax('_statistics_income', [
            'dataProvider' => $dataProvider,
        ]);
    }

    public function actionOutcome_ajax($date)
    {
        $currDate = new \DateTime();
        $currDate->setTimestamp($date);
        $endOfDay = $currDate->format('23:59:59 d-m-Y');
        $var = new \DateTime($endOfDay);
        $endOfDayTimestamp = (string)$var->getTimestamp();

        $dataProvider = new ActiveDataProvider([
            'query' => EmployeeOutcomeSearch::find()
                ->innerJoin('outcome_time ot', 'ot.id = employee_outcome.outcome_id')
                ->where('ot.time > :date AND ot.time < :nextDay',
                    [':date' => $date, ':nextDay' => $endOfDayTimestamp]),
            'pagination' => [
                'pageSize' => false,
            ],
        ]);
        $dataProvider->query->addOrderBy(['time' => SORT_DESC]);

        return $this->renderAjax('_statistics_outcome', [
            'dataProvider' => $dataProvider,
        ]);
    }

    public function actionDayOff($limit, $offset = null)
    {
        $allEmployees = (new Query())
            ->from('employees e')
            ->select('*')
            ->limit($limit)
            ->offset($offset)
            ->createCommand();

        $rows = $allEmployees->queryAll();

        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        return ['allEmployees' => $rows];
    }

    public function actionAddDayOff()
    {
        if (isset($_POST['dayOffArr'])) {
            $dayOff = $_POST['dayOffArr'];
            $array = array_filter($dayOff);

            $this->addIncomeDate($array, self::DAY_OFF_TRUE);

            \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return ['status' => 'ok'];
        }
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        return ['status' => 'error'];
    }

    public function actionCustSearch($text)
    {
        $allEmployees = (new Query())
            ->from('employees e')
            ->select('*')
            ->andFilterWhere([
                'or',
                ['like', 'first_name', $text],
                ['like', 'last_name', $text],
            ])
            ->createCommand();

        $rows = $allEmployees->queryAll();

        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        return ['allEmployees' => $rows];
    }

    public function actionSetDateManual()
    {
        try {
            if (isset($_POST['incomeTime'])) {
                $income = $_POST['incomeTime'];
                $income = array_filter($income);
                $this->addIncomeDate($income);
            }
            if (isset($_POST['outcomeTime'])) {
                $outcome = $_POST['outcomeTime'];
                $outcome = array_filter($outcome);
                $this->addOutcomeDate($outcome);
            }
        } catch (yii\base\Exception $e) {
            return [
                'status' => 'error',
                'err' => $e
            ];
        }
        return 0;
    }

    private function addIncomeDate($incomeArr, $dayoff = 0)
    {
        foreach ($incomeArr as $id => $time) {
            $incomeTime = new IncomeTime();
            $incomeTime->time = $time;
            $incomeTime->day_off = $dayoff;
            $incomeTime->save();
            $employeeIncome = new EmployeeIncome();
            $employeeIncome->employee_id = $id;
            $employeeIncome->income_id = $incomeTime->id;
            $employeeIncome->save();
        }
    }

    private function addOutcomeDate($outComeArr)
    {
        foreach ($outComeArr as $id => $time) {
            $outComeTime = new OutcomeTime();
            $outComeTime->time = $time;
            $outComeTime->save();
            $employeeOutcome = new EmployeeOutcome();
            $employeeOutcome->employee_id = $id;
            $employeeOutcome->outcome_id = $outComeTime->id;
            $employeeOutcome->save();
        }
    }

    public function actionGoogle()
    {
        $serviceRequest = new DefaultServiceRequest("");
        ServiceRequestFactory::setInstance($serviceRequest);

        $spreadsheetService = new SpreadsheetService();
        $worksheetFeed = $spreadsheetService->getPublicSpreadsheet("1vu5W5KDAPGq9p0bVbdsdwb6LQ5tMxyMzZw01b_krqyo");

        $worksheet = $worksheetFeed->getByTitle('first');

        $cellFeed = $worksheet->getCellFeed();
        $var = $cellFeed->createCell(1, 3, "111");
        $var->update('222');
        //$cell = $cellFeed->getCell(1, 2);
        //  $cellFeed->createCell(1, 3, "111");
        //$cell = $cellFeed->getCell(1, 3);

//        $batchRequest = new BatchRequest();
//        $batchRequest->addEntry($cellFeed->createCell(2, 1, "111"));
//        $batchRequest->addEntry($cellFeed->createCell(3, 1, "222"));
//        $batchRequest->addEntry($cellFeed->createCell(4, 1, "333"));
//        $batchRequest->addEntry($cellFeed->createCell(5, 1, "=SUM(A2:A4)"));
//
//        $batchResponse = $cellFeed->insertBatch($batchRequest);

        VarDumper::dump($var, 10, true);
    }

}


text:
package org.aieonf.sketch.service;

import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.Map;

import org.aieonf.concept.IDescriptor;
import org.aieonf.concept.domain.IDomainAieon;
import org.aieonf.concept.function.IDescribablePredicate;
import org.aieonf.osgi.domain.IDomainProvider;
import org.aieonf.sketch.factory.SketchFactory;
import org.aieonf.sketch.factory.SketchModelFactory;
import org.osgi.service.component.annotations.Component;

@Component( name="org.aieonf.sketch.domain.provider.service",
immediate=true)
public class DomainProvider implements IDomainProvider {

	SketchFactory factory = SketchFactory.getInstance();

	@Override
	public IDomainAieon[] getDomains() {
		Map<IDomainAieon, SketchModelFactory> factories = new HashMap<>();
		try {
			factories = factory.getFactories();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		return factories.keySet().toArray( new IDomainAieon[factories.keySet().size()]);
	}

	public static IDomainAieon getDomain() {
		IDomainAieon domain = null;
		try{
			SketchFactory factory = SketchFactory.getInstance();
			factory.createTemplate();
			domain = factory.getDomain();
		}
		catch( Exception e ){
			e.printStackTrace();
		}
		return domain;
	}

	/**
	 * Get the predicates that have been registered
	 * @return
	 */
	@Override
	public IDescribablePredicate<IDescriptor> getPredicates(){
		// TODO Auto-generated method stub
		return null;
	}
}

redpajama_set_name: RedPajamaGithub


text:
namespace Microsoft.Azure.Management.RecoveryServices.Backup.Models
{
    using System.Linq;

    /// <summary>
    /// Filters to list backup copies.
    /// </summary>
    public partial class BMSRPQueryObject
    {
        /// <summary>
        /// Initializes a new instance of the BMSRPQueryObject class.
        /// </summary>
        public BMSRPQueryObject() { }

        /// <summary>
        /// Initializes a new instance of the BMSRPQueryObject class.
        /// </summary>
        /// <param name="startDate">Backup copies created after this
        /// time.</param>
        /// <param name="endDate">Backup copies created before this
        /// time.</param>
        public BMSRPQueryObject(System.DateTime? startDate = default(System.DateTime?), System.DateTime? endDate = default(System.DateTime?))
        {
            StartDate = startDate;
            EndDate = endDate;
        }

        /// <summary>
        /// Gets or sets backup copies created after this time.
        /// </summary>
        [Newtonsoft.Json.JsonProperty(PropertyName = "startDate")]
        public System.DateTime? StartDate { get; set; }

        /// <summary>
        /// Gets or sets backup copies created before this time.
        /// </summary>
        [Newtonsoft.Json.JsonProperty(PropertyName = "endDate")]
        public System.DateTime? EndDate { get; set; }

    }
}


text: pub mod hzfactor;


text:
/*
Package import_ provides the import sub command initial imports.
*/
package import_

import (
	"os"
	"path/filepath"

	"github.com/omniscale/go-osm/state"
	"github.com/omniscale/imposm3/cache"
	"github.com/omniscale/imposm3/config"
	"github.com/omniscale/imposm3/database"
	_ "github.com/omniscale/imposm3/database/postgis"
	"github.com/omniscale/imposm3/geom/limit"
	"github.com/omniscale/imposm3/log"
	"github.com/omniscale/imposm3/mapping"
	"github.com/omniscale/imposm3/reader"
	"github.com/omniscale/imposm3/stats"
	"github.com/omniscale/imposm3/update"
	"github.com/omniscale/imposm3/writer"
)

func Import(importOpts config.Import) {
	baseOpts := importOpts.Base

	if (importOpts.Write || importOpts.Read != "") && (importOpts.RevertDeploy || importOpts.RemoveBackup) {
		log.Fatal("-revertdeploy and -removebackup not compatible with -read/-write")
	}

	if importOpts.RevertDeploy && (importOpts.RemoveBackup || importOpts.DeployProduction) {
		log.Fatal("-revertdeploy not compatible with -deployproduction/-removebackup")
	}

	var geometryLimiter *limit.Limiter
	if (importOpts.Write || importOpts.Read != "") && baseOpts.LimitTo != "" {
		var err error
		step := log.Step("Reading limitto geometries")
		geometryLimiter, err = limit.NewFromGeoJSON(
			baseOpts.LimitTo,
			baseOpts.LimitToCacheBuffer,
			baseOpts.Srid,
		)
		if err != nil {
			log.Fatal(err)
		}
		step()
	}

	tagmapping, err := mapping.FromFile(baseOpts.MappingFile)
	if err != nil {
		log.Fatal("[error] reading mapping file: ", err)
	}

	var db database.DB

	if importOpts.Write || importOpts.DeployProduction || importOpts.RevertDeploy || importOpts.RemoveBackup || importOpts.Optimize {
		if baseOpts.Connection == "" {
			log.Fatal("[error] missing connection option in configuration")
		}
		conf := database.Config{
			ConnectionParams: baseOpts.Connection,
			Srid:             baseOpts.Srid,
			ImportSchema:     baseOpts.Schemas.Import,
			ProductionSchema: baseOpts.Schemas.Production,
			BackupSchema:     baseOpts.Schemas.Backup,
		}
		db, err = database.Open(conf, &tagmapping.Conf)
		if err != nil {
			log.Fatal("[error] opening database: ", err)
		}
		defer db.Close()
	}

	osmCache := cache.NewOSMCache(baseOpts.CacheDir)

	if importOpts.Read != "" && osmCache.Exists() {
		if importOpts.Overwritecache {
			log.Printf("[info] removing existing cache %s", baseOpts.CacheDir)
			err := osmCache.Remove()
			if err != nil {
				log.Fatal("unable to remove cache:", err)
			}
		} else if !importOpts.Appendcache {
			log.Fatal("cache already exists use -appendcache or -overwritecache")
		}
	}

	step := log.Step("Imposm")

	var elementCounts *stats.ElementCounts

	if importOpts.Read != "" {
		step := log.Step("Reading OSM data")
		err = osmCache.Open()
		if err != nil {
			log.Fatal("[error] opening cache files: ", err)
		}
		progress := stats.NewStatsReporter()

		if !importOpts.Appendcache {
			// enable optimization if we don't append to existing cache
			osmCache.Coords.SetLinearImport(true)
		}

		readLimiter := geometryLimiter
		if baseOpts.LimitToCacheBuffer == 0.0 {
			readLimiter = nil
		}

		err := reader.ReadPbf(importOpts.Read,
			osmCache,
			progress,
			tagmapping,
			readLimiter,
		)
		if err != nil {
			log.Fatal(err)
		}

		osmCache.Coords.SetLinearImport(false)
		elementCounts = progress.Stop()
		osmCache.Close()
		step()
		if importOpts.Diff {
			diffstate, err := estimateFromPBF(importOpts.Read, baseOpts.DiffStateBefore, baseOpts.ReplicationURL, baseOpts.ReplicationInterval)
			if err != nil {
				log.Println("[error] parsing diff state form PBF", err)
			} else if diffstate != nil {
				os.MkdirAll(baseOpts.DiffDir, 0755)
				err := state.WriteFile(filepath.Join(baseOpts.DiffDir, update.LastStateFilename), diffstate)
				if err != nil {
					log.Println("[error] writing last.state.txt: ", err)
				}
			}
		}
	}

	if importOpts.Write {
		importFinished := log.Step("Importing OSM data")
		writeFinished := log.Step("Writing OSM data")
		progress := stats.NewStatsReporterWithEstimate(elementCounts)

		err = db.Init()
		if err != nil {
			log.Fatal(err)
		}

		bulkDb, ok := db.(database.BulkBeginner)
		if ok {
			err = bulkDb.BeginBulk()
		} else {
			err = db.Begin()
		}
		if err != nil {
			log.Fatal(err)
		}

		var diffCache *cache.DiffCache
		if importOpts.Diff {
			diffCache = cache.NewDiffCache(baseOpts.CacheDir)
			if err = diffCache.Remove(); err != nil {
				log.Fatal(err)
			}
			if err = diffCache.Open(); err != nil {
				log.Fatal(err)
			}
		}

		err = osmCache.Open()
		if err != nil {
			log.Fatal(err)
		}
		if diffCache != nil {
			diffCache.Coords.SetLinearImport(true)
			diffCache.Ways.SetLinearImport(true)
		}
		osmCache.Coords.SetReadOnly(true)

		relations := osmCache.Relations.Iter()
		relWriter := writer.NewRelationWriter(osmCache, diffCache,
			tagmapping.Conf.SingleIDSpace,
			relations,
			db, progress,
			tagmapping.PolygonMatcher,
			tagmapping.RelationMatcher,
			tagmapping.RelationMemberMatcher,
			baseOpts.Srid,
		)
		relWriter.SetLimiter(geometryLimiter)
		relWriter.EnableConcurrent()
		relWriter.Start()
		relWriter.Wait() // blocks till the Relations.Iter() finishes
		osmCache.Relations.Close()

		ways := osmCache.Ways.Iter()
		wayWriter := writer.NewWayWriter(osmCache, diffCache,
			tagmapping.Conf.SingleIDSpace,
			ways, db,
			progress,
			tagmapping.PolygonMatcher,
			tagmapping.LineStringMatcher,
			baseOpts.Srid,
		)
		wayWriter.SetLimiter(geometryLimiter)
		wayWriter.EnableConcurrent()
		wayWriter.Start()
		wayWriter.Wait() // blocks till the Ways.Iter() finishes
		osmCache.Ways.Close()

		nodes := osmCache.Nodes.Iter()
		nodeWriter := writer.NewNodeWriter(osmCache, nodes, db,
			progress,
			tagmapping.PointMatcher,
			baseOpts.Srid,
		)
		nodeWriter.SetLimiter(geometryLimiter)
		nodeWriter.EnableConcurrent()
		nodeWriter.Start()
		nodeWriter.Wait() // blocks till the Nodes.Iter() finishes
		osmCache.Close()

		err = db.End()
		if err != nil {
			log.Fatal(err)
		}

		progress.Stop()

		if importOpts.Diff {
			diffCache.Close()
		}

		writeFinished()

		if db, ok := db.(database.Generalizer); ok {
			if err := db.Generalize(); err != nil {
				log.Fatal(err)
			}
		} else {
			log.Fatal("database not generalizeable")
		}

		// Optimize before creating indices.
		if importOpts.Optimize {
			if db, ok := db.(database.Optimizer); ok {
				if err := db.Optimize(); err != nil {
					log.Fatal(err)
				}
			} else {
				log.Fatal("database not optimizable")
			}
		}

		// Create indices in finisher.
		if db, ok := db.(database.Finisher); ok {
			if err := db.Finish(); err != nil {
				log.Fatal(err)
			}
		} else {
			log.Fatal("database not finishable")
		}
		importFinished()
	}

	if importOpts.Optimize && !importOpts.Write { // Optimize already called in Write.
		if db, ok := db.(database.Optimizer); ok {
			if err := db.Optimize(); err != nil {
				log.Fatal(err)
			}
		} else {
			log.Fatal("database not optimizable")
		}
	}

	if importOpts.DeployProduction {
		if db, ok := db.(database.Deployer); ok {
			if err := db.Deploy(); err != nil {
				log.Fatal(err)
			}
		} else {
			log.Fatal("database not deployable")
		}
	}

	if importOpts.RevertDeploy {
		if db, ok := db.(database.Deployer); ok {
			if err := db.RevertDeploy(); err != nil {
				log.Fatal(err)
			}
		} else {
			log.Fatal("database not deployable")
		}
	}

	if importOpts.RemoveBackup {
		if db, ok := db.(database.Deployer); ok {
			if err := db.RemoveBackup(); err != nil {
				log.Fatal(err)
			}
		} else {
			log.Fatal("database not deployable")
		}
	}

	step()

}


text:
/*eslint strict:0*/

var urlWithEncodedSpace = 'tests/site/has%20space.html';
var urlWithoutSpace = 'tests/site/index.html';

var urls = [urlWithEncodedSpace, urlWithoutSpace];
if (casper.cli.options.reverse) urls.reverse();

var phantomVersion = 'phantomjs ' + phantom.version.major + '.' + phantom.version.minor + '.' + phantom.version.patch;

var numPageResourcesRequested = 0;
var numPageResourcesReceived = 0;

casper.on ('page.resource.requested', function ResourceRequested (resource) {
   ++numPageResourcesRequested;
});

casper.on ('page.resource.received', function ResourceReceived (resource) {
   ++numPageResourcesReceived;
});

casper.test.begin(phantomVersion + ' ' + urls[0] + ' then ' + urls[1], 8, function(test) {

   casper.start(urls[0], function CheckResponse1(response1) {
      test.assertEquals(numPageResourcesRequested, 1, 'page.resource.requested 1');
      test.assertEquals(numPageResourcesReceived, 1, 'page.resource.received 1');
      test.assertEquals(response1.status, 200, 'status 200 for ' + urls[0]);
      test.assertEquals(response1.url, casper.filter('open.location', urls[0]) || urls[0], 'opened ' + urls[0]);   // Mimic Casper.prototype.open

      casper.thenOpen (urls[1], function CheckResponse2(response2) {
         test.assertEquals(numPageResourcesRequested, 2, 'page.resource.requested 2');
         test.assertEquals(numPageResourcesReceived, 2, 'page.resource.received 2');
         test.assertEquals(response2.status, 200, 'status 200 for ' + urls[1]);
         test.assertEquals(response2.url, casper.filter('open.location', urls[1]) || urls[1], 'opened ' + urls[1]); // Mimic Casper.prototype.open
      });
   });

   casper.run(function() {
      test.done();
   });
});


text:
/**
 *
 * backbone cartodb adapter
 *
 * this is a small library that allows to use Backbone with models
 * to work with data stored in CartoDB (a geospatial database on
 * the cloud, see more info at http://cartodb.com).
 *
 * it does NOT overrride Backbone.sync
 *
 */

Backbone.CartoDB = function(options, query, cache) {

    options = _.defaults(options, {
        USE_PROXY: false,
        user: ''
    });

    function _SQL(sql) {
        this.sql = sql;
    }
    function SQL(sql) {
        return new _SQL(sql);
    }

    // SQL("{0} is {1}").format("CartoDB", "epic!");
    _SQL.prototype.format = function() {
      var str = this.sql,
          len = arguments.length+1;
      var safe, arg;
      for (i=0; i < len; arg = arguments[i++]) {
          safe = typeof arg === 'object' ? JSON.stringify(arg) : arg;
          str = str.replace(RegExp('\\{'+(i-1)+'\\}', 'g'), safe);
      }
      return str;
    };

    var resource_path= options.user + '.cartodb.com/api/v2/sql';
    var resource_url = 'https://' + resource_path;

    /**
     * fetch sql from the server
     *
     * this function should be changed if you're working on node
     *
     */
    query = query || function(sql, callback, proxy) {
        var url = resource_url;
        var crossDomain = true;
        if(proxy) {
            url = 'api/v0/proxy/' + resource_url;
            crossDomain = false;
        }
        if(sql.length > 1500) {
            $.ajax({
              url: url,
              crossDomain: crossDomain,
              type: 'POST',
              dataType: 'json',
              data: 'q=' + encodeURIComponent(sql),
              success: callback,
              error: function(){
                if(proxy) {
                    callback();
                } else {
                    //try fallback
                    if(USE_PROXY) {
                        query(sql, callback, true);
                    }
                }
              }
            });
        } else {
             // TODO: add timeout
             $.getJSON(resource_url + '?q=' + encodeURIComponent(sql) + '&callback=?')
             .success(callback)
             .fail(function(){
                    callback();
             }).complete(function() {
             });
        }
    };

    var dummy_cache = {
        setItem: function(key, value) { },
        getItem: function(key) { return null; },
        removeItem: function(key) { }
    };

    cache = cache && dummy_cache;

    var CartoDBModel = Backbone.Model.extend({

      _create_sql: function() {
        var where = SQL(" where {0} = '{1}'").format(
            this.columns[this.what],
            this.get(this.what).replace("'", "''")
        );
        var select = this._sql_select();
        var sql = 'select ' + select.join(',') + ' from ' + this.table + where;
        return sql;
      },

      _sql_select: function() {
        var select = [];
        for(var k in this.columns) {
          var w = this.columns[k];
          if(w.indexOf('ST_') !== -1 || w === "the_geom") {
            select.push(SQL('ST_AsGeoJSON({1}) as {0}').format(k,w));
          } else {
            select.push(SQL('{1} as {0}').format(k, w));
          }
        }
        return select;
      },

      _parse_columns: function(row) {
        var parsed = {};
        for(var k in row) {
          var v = row[k];
          var c = this.columns[k];
          if (c.indexOf('ST_') !== -1 || c === "the_geom") {
            parsed[k] = JSON.parse(v);
          } else {
            parsed[k] = row[k];
          }
        }
        return parsed;
      },

      fetch: function() {
        var self = this;
        query(this._create_sql(), function(data) {
          self.set(self._parse_columns(data.rows[0]));
        });
      }
    });

    /**
     * cartodb collection created from a sql composed using 'columns' and
     * 'table' attributes defined in a child class
     *
     * var C = CartoDBCollection.extend({
     *  table: 'table',
     *  columns: ['c1', 'c2']
     * });
     * var c = new C();
     * c.fetch();
     */
    var CartoDBCollection = Backbone.Collection.extend({

      _create_sql: function() {
        var tables = this.table;
        if(!_.isArray(this.table)) {
            tables = [this.table];
        }
        tables = tables.join(',');
        var select = CartoDBModel.prototype._sql_select.call(this);
        var sql = 'select ' + select.join(',') + ' from ' + this.table;
        if (this.where) {
            sql += " WHERE " + this.where;
        }
        return sql;
      },

      fetch: function() {
        var self = this;
        var sql = this.sql || this._create_sql();
        if(typeof(sql) === "function") {
          sql = sql.call(this);
        }
        var item = this.cache ? cache.getItem(sql): false;
        if(!item) {
            query(sql, function(data) {
              if(this.cache) {
                  try {
                    cache.setItem(sql, JSON.stringify(data.rows));
                  } catch(e) {}
              }
              var rows;
              if(!self.sql) {
                  rows = _.map(data.rows, function(r) {
                    return CartoDBModel.prototype._parse_columns.call(self, r);
                  });
              } else {
                  rows = data.rows;
              }
              self.reset(rows);
            });
        } else {
            self.reset(JSON.parse(item));
        }
      }

    });

    return {
      query: query,
      CartoDBCollection: CartoDBCollection,
      CartoDBModel: CartoDBModel,
      SQL: SQL
    };

};


text:
<archimate:ArchimateDiagramModel
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:archimate="http://www.archimatetool.com/archimate"
    name="Whole-Part definitions for ISO 15926 Part 2"
    id="8b2cb1aa-13f0-49c1-acbc-793a9d6b00aa">
  <children
      xsi:type="archimate:DiagramModelNote"
      id="854c7d46-f1fb-4fdd-b7ae-fe19e20b15b5"
      textAlignment="1"
      content="There is a definition in EXPRESS of the data model">
    <bounds
        x="54"
        y="12"
        width="187"
        height="61"/>
  </children>
  <children
      xsi:type="archimate:DiagramModelNote"
      id="83d62daf-f279-41b1-a238-c9660d396060"
      textAlignment="1"
      content="A translation is provided in OWL">
    <bounds
        x="55"
        y="96"
        width="186"
        height="37"/>
  </children>
  <children
      xsi:type="archimate:DiagramModelNote"
      id="ba4391dc-ef65-4de5-b737-d94b7ceba6dd"
      textAlignment="1"
      content="It defines whole and part with composition of individuals and arrangement of individual">
    <bounds
        x="55"
        y="168"
        width="186"
        height="73"/>
  </children>
</archimate:ArchimateDiagramModel>


text:
package com.ts.entity.pdss.pdss.RSBeans;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.annotation.XmlElement;

import com.ts.entity.pdss.pdss.Beans.TDrug;
import com.ts.entity.pdss.pdss.Beans.TDrugInteractionInfo;

/**
 * 互动信息
 * @author liujc
 *
 */
public class TDrugInteractionRslt extends TBaseResult
{
	private static final long serialVersionUID = 1L;
	/* 本地药品A */
	private TDrug DrugA;
	/* 本地药品B */
	private TDrug DrugB;
	private List<TDrugInteractionInfo> drugInfos = new ArrayList<TDrugInteractionInfo>();
    /* 医嘱序号*/
    private String recMainNo2;
    /* 医嘱子序号*/
    private String recSubNo2;

    public TDrugInteractionRslt deepClone() throws IOException, ClassNotFoundException
    {
    	//首先将对象写到流里
        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        ObjectOutputStream oo    = new ObjectOutputStream(bo);
        oo.writeObject(this);
        //然后将对象从流里读出来
        ByteArrayInputStream bi     = new ByteArrayInputStream(bo.toByteArray());
        ObjectInputStream oi        = new ObjectInputStream(bi);
        TDrugInteractionRslt Result = (TDrugInteractionRslt)oi.readObject();
        return Result;
    }

    @XmlElement(name="getListDruginfo")
    public List<TDrugInteractionInfo> getListDruginfo()
    {
    	return drugInfos;
    }

    public TDrugInteractionRslt()
    {
        setVersion(2);
    }

    public void addDrugInfo(TDrug a, TDrug b, List<TDrugInteractionInfo> drugInfo)
	{
		DrugA = a;
		DrugB = b;
		drugInfos = drugInfo;
		setAlertLevel("");
		setAlertHint("");
        setAlertCause("");
		for (int i = 0; i < drugInfo.size(); i++)
		{
	        if (("1").equals(drugInfo.get(i).getINTER_INDI()) || ("2").equals(drugInfo.get(i).getINTER_INDI()))
	        {
	            setAlertLevel("R");
	            setAlertHint(drugInfo.get(i).getMEC_INFO());
	            setAlertCause(drugInfo.get(i).getWAR_INFO());
	        }
	        else if(("3").equals(drugInfo.get(i).getINTER_INDI()) || ("4").equals(drugInfo.get(i).getINTER_INDI()))
	        {
	            if(!"R".equals(this.getAlertLevel()))
	            {
	            	setAlertLevel("Y");
	            	setAlertHint(drugInfo.get(i).getMEC_INFO());
		            setAlertCause(drugInfo.get(i).getWAR_INFO());
	            }
	        }
		}
		if("Y".equals(this.getAlertLevel()))
		{
		    this.YellowCount++;
		}
		else if("R".equals(this.getAlertLevel()))
		{
		    this.RedCount++;
		}
		setAlertLevel(this.RedCount > 0 ? "R" : this.YellowCount > 0 ? "Y" : "");
	}

    public void setDrugA(TDrug value)
    {
    	DrugA = value;
    }

    public void setDrugB(TDrug value)
    {
    	DrugB = value;
    }

	public TDrug getDrugA()
	{
		return DrugA;
	}

	public TDrug getDrugB()
	{
		return DrugB;
	}

	/**
	 * @return
	 */
	public TDrugInteractionInfo[] getDrugInteractionInfo()
	{
	    return drugInfos.toArray(new TDrugInteractionInfo[0]);
	}
    public String getRecMainNo2()
    {
        return recMainNo2;
    }
    public void setRecMainNo2(String recMainNo2)
    {
        this.recMainNo2 = recMainNo2;
    }
    public String getRecSubNo2()
    {
        return recSubNo2;
    }
    public void setRecSubNo2(String recSubNo2)
    {
        this.recSubNo2 = recSubNo2;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace Monkeyspeak
{
	/// <summary>
	///
	/// </summary>
	[AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = true)]
	public sealed class TriggerHandlerAttribute : Attribute
	{
		private TriggerCategory triggerCategory;
		private int triggerID;
		private string description;
		internal MethodInfo owner;

		/// <summary>
		///
		/// </summary>
		/// <param name="category">Trigger Category</param>
		/// <param name="id">Trigger ID</param>
		/// <param name="description">Trigger Description</param>
		public TriggerHandlerAttribute(TriggerCategory category, int id, string description)
		{
			this.triggerCategory = category;
			this.triggerID = id;
			this.description = description;
		}

		internal void Register(Page page)
		{
			TriggerHandler handler = (TriggerHandler)Delegate.CreateDelegate(typeof(TriggerHandler), owner, false);
			if (handler != null)
				page.SetTriggerHandler(triggerCategory, triggerID, (TriggerHandler)Delegate.CreateDelegate(typeof(TriggerHandler), owner, false), description);
		}
	}
}


text:
<link href="hoja_de_estilo.css" type="text/css" rel="stylesheet">

	QUITAR
      EQUIPO

<?php
$id_c=$_GET['id_equipo'];

echo '<form action="quitar_equipo3.php?id_equipo='.$id_c.'" method="post">';
echo'

';

$nc=$_GET['id_equipo'];
//echo "SELECT cod_equipo, codigo_cliente, tipo_de_equipo, propiedad_equipo, condicion_entrega, tipo_garantia, observaciones_equipo, fecha_registro_equipo, precio_equipo FROM equipo WHERE cod_equipo=".$nc;
require_once("manejomysql.php");
			conectar_bd();

			$resultado= consulta_bd("SELECT cod_equipo, codigo_cliente, tipo_de_equipo, propiedad_equipo, condicion_entrega, tipo_garantia, observaciones_equipo, fecha_registro_equipo, precio_equipo FROM equipo WHERE cod_equipo=".$nc );
			$registro=sacar_registro_bd($resultado);
			$codigo_cliente=$registro['codigo_cliente'];
			$tipo_equipo=$registro['tipo_de_equipo'];
			$propiedad_equipo=$registro['propiedad_equipo'];
			$condicion_entrega=$registro['condicion_entrega'];
			$precio_equipo=$registro['precio_equipo'];
			$tipo_garantia=$registro['tipo_garantia'];
			$observaciones=$registro['observaciones_equipo'];
			$fecha_registro=$registro['fecha_registro_equipo'];

			$usuario_consulta2 = mysql_query("SELECT nombre_cliente, apellido_paterno, apellido_materno FROM cliente where codigo_cliente=".$codigo_cliente ) or die(header ("Location:error.php"));
			$registro2= sacar_registro_bd($usuario_consulta2);
			$name=$registro2['nombre_cliente']." ".$registro2['apellido_paterno']." ".$registro2['apellido_materno'];
		//	$cod_cliente=$_GET['id'];

echo '

              INFORMACIÓN EQUIPO

              Codigo Equipo:
               ';

			 echo $nc;
             echo'
              Nombre Cliente:
               '.$name.'	';
			  echo
			  '

              Propiedad del Equipo:
               '.$propiedad_equipo.'

              Fecha de Registro:
               '.$fecha_registro.'

              Tipo de Equipo:
               '.$tipo_equipo.'

              Condicion de Entrega:
               '.$condicion_entrega.'

               Tipo de Garantia:
               '.$tipo_garantia.'

              Precio del Equipo:
               '.$precio_equipo.'

      OBSERVACIONES

       '.$observaciones.'

       <form action="quitar_equipo3.php.php" method="post"><input name="image"  type="image" onMouseOver= src="images/quitar_e1.gif" onMouseMove= src="images/quitar_e1.gif" onMouseOut=src="images/quitar_e2.gif" value="" SRC="images/quitar_e2.gif"> 	</form>
      <form action="quitar_equipo.php" method="post"><input name="cancelar"  type="image" onMouseOver= src="images/c2.gif" onMouseMove= src="images/c2.gif" onMouseOut=src="images/c1.gif" value="" SRC="images/c1.gif"> 	 </form>

';
  ?>


text:
import { getlayoutStateJS } from './../../layout/reducers/layout.selector';
import { LayoutState } from './../../layout/reducers/layout.state';
import { Observable } from 'rxjs/internal/Observable';
import { AppState } from './../../interfaces';
import { Store } from '@ngrx/store';
import { LineItem } from './../../core/models/line_item';
import { Order } from './../../core/models/order';
import { UserService } from './../../user/services/user.service';
import { ActivatedRoute, Router, Params } from '@angular/router';
import { Component, OnInit } from '@angular/core';
import { environment } from '../../../environments/environment';

@Component({
  selector: 'app-order-success',
  templateUrl: './order-success.component.html',
  styleUrls: ['./order-success.component.scss']
})
export class OrderSuccessComponent implements OnInit {
  queryParams: Params;
  orderDetails: Order;
  layoutState$: Observable<LayoutState>;
  noImageUrl = 'assets/default/image-placeholder.svg';
  currency = environment.config.currency_symbol;

  constructor(
    private userService: UserService,
    private activatedRouter: ActivatedRoute,
    private route: Router,
    private store: Store<AppState>
  ) {
    this.activatedRouter.queryParams.subscribe(params => {
      this.queryParams = params;
      if (!this.queryParams.orderReferance) {
        this.route.navigate(['/']);
      }
    });
  }

  ngOnInit() {
    this.layoutState$ = this.store.select(getlayoutStateJS);
    this.userService
      .getOrderDetail(this.queryParams.orderReferance)
      .subscribe(order => {
        this.orderDetails = order;
      });
  }

  getProductImageUrl(line_item: LineItem) {
    const image_url = line_item.product.images[0]
      ? line_item.product.images[0].small
      : this.noImageUrl;
    return image_url;
  }
}


text:
/**
 * Tasks that add support for Java language.
 */
@Incubating
package org.gradle.language.java.tasks;

import org.gradle.api.Incubating;


text:
#ifndef __GSL_WAVELET_H__
#define __GSL_WAVELET_H__

#if !defined( GSL_FUN )
#  if !defined( GSL_DLL )
#    define GSL_FUN extern
#  elif defined( BUILD_GSL_DLL )
#    define GSL_FUN extern __declspec(dllexport)
#  else
#    define GSL_FUN extern __declspec(dllimport)
#  endif
#endif
#include <stdlib.h>
#include <gsl/gsl_types.h>
#include <gsl/gsl_errno.h>

#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS          /* empty */
# define __END_DECLS            /* empty */
#endif

__BEGIN_DECLS

#ifndef GSL_DISABLE_DEPRECATED
typedef enum {
  forward = 1, backward = -1,
  gsl_wavelet_forward = 1, gsl_wavelet_backward = -1
}
gsl_wavelet_direction;
#else
typedef enum {
  gsl_wavelet_forward = 1, gsl_wavelet_backward = -1
}
gsl_wavelet_direction;
#endif

typedef struct
{
  const char *name;
  int (*init) (const double **h1, const double **g1,
               const double **h2, const double **g2, size_t * nc,
               size_t * offset, size_t member);
}
gsl_wavelet_type;

typedef struct
{
  const gsl_wavelet_type *type;
  const double *h1;
  const double *g1;
  const double *h2;
  const double *g2;
  size_t nc;
  size_t offset;
}
gsl_wavelet;

typedef struct
{
  double *scratch;
  size_t n;
}
gsl_wavelet_workspace;

GSL_VAR const gsl_wavelet_type *gsl_wavelet_daubechies;
GSL_VAR const gsl_wavelet_type *gsl_wavelet_daubechies_centered;
GSL_VAR const gsl_wavelet_type *gsl_wavelet_haar;
GSL_VAR const gsl_wavelet_type *gsl_wavelet_haar_centered;
GSL_VAR const gsl_wavelet_type *gsl_wavelet_bspline;
GSL_VAR const gsl_wavelet_type *gsl_wavelet_bspline_centered;

GSL_FUN gsl_wavelet *gsl_wavelet_alloc (const gsl_wavelet_type * T, size_t k);
GSL_FUN void gsl_wavelet_free (gsl_wavelet * w);
GSL_FUN const char *gsl_wavelet_name (const gsl_wavelet * w);

GSL_FUN gsl_wavelet_workspace *gsl_wavelet_workspace_alloc (size_t n);
GSL_FUN void gsl_wavelet_workspace_free (gsl_wavelet_workspace * work);

GSL_FUN int gsl_wavelet_transform (const gsl_wavelet * w,
                           double *data, size_t stride, size_t n,
                           gsl_wavelet_direction dir,
                           gsl_wavelet_workspace * work);

GSL_FUN int gsl_wavelet_transform_forward (const gsl_wavelet * w,
                                   double *data, size_t stride, size_t n,
                                   gsl_wavelet_workspace * work);

GSL_FUN int gsl_wavelet_transform_inverse (const gsl_wavelet * w,
                                    double *data, size_t stride, size_t n,
                                    gsl_wavelet_workspace * work);

__END_DECLS

#endif /* __GSL_WAVELET_H__ */


text:
<?php
/**
 * Created by PhpStorm.
 * @user: MackRias
 * @site: http://mackrais.com
 * @email: mackraiscms@gmail.com
 */

use yii\helpers\Html;
use yii\helpers\Json;
use mackrais\cropimage\MrSectionWidgetAsset;

/* @var $this yii\web\View */
/* @var $model \yii\base\Model */
/* @var $class_block string */
/* @var $template_image string */
/* @var $attribute string */
/* @var $options array */
/* @var $attribute_x string */
/* @var $options_x array */
/* @var $attribute_x string */
/* @var $options_x array */
/* @var $attribute_y string */
/* @var $options_y array */
/* @var $attribute_height string */
/* @var $options_height array */
/* @var $attribute_width string */
/* @var $options_width array */
/* @var $attribute_origin_height string */
/* @var $options_origin_height array */
/* @var $attribute_origin_width string */
/* @var $options_origin_width array */
/* @var $attribute_scale string */
/* @var $options_scale  array */
/* @var $attribute_angle string */
/* @var $options_angle array */
/* @var $attribute_remove string */
/* @var $options_remove array */
/* @var $plugin_options array */

MrSectionWidgetAsset::register($this);
$removeBtn = !empty($template_image) ? '' : 'hidden';
$emptyBlock = empty($template_image) ? '' : 'hidden';
?>
    <div class="mr-section-base <?= $class_block ?>" style="width: <?= $plugin_options['width'] + 4 ?>px; ">

            <i class="fa fa-photo fa-5x" style="margin-top:<?= $plugin_options['height'] / 3 ?>px;">

<?= Yii::t('app', 'Please click on the field to select the picture section'); ?>

        <div class="mr-section" id="<?= $plugin_options['section'] ?>" data-role="upload_image"
             style="width: <?= $plugin_options['width'] + 4 ?>px; height: <?= $plugin_options['height'] + 3 ?>px;  ">
            <?php if ($template_image): ?>
                <?= $template_image ?>
            <?php endif; ?>
            <div class="mr-upload-block <?= $emptyBlock ?>">
                <i class="fa fa-photo fa-5x" style="margin-top:<?= $plugin_options['height'] / 3 ?>px;">

<?= Yii::t('app', 'Please click on the field to select the picture section'); ?>

            <span class="glyphicon  glyphicon-remove mr-remove <?= $removeBtn ?>">

                <button class='btn btn-primary mr-zoom-out' type='button' title='<?= Yii::t('site', 'Zoom out'); ?>'>
                    </button>
                <button class='btn btn-primary mr-fit' type='button' title='<?= Yii::t('site', 'Fit image'); ?>'></button>
                <button class='btn btn-primary mr-zoom-in' type='button' title='<?= Yii::t('site', 'Zoom in'); ?>'></button>

            <button class='btn btn-success mr-upload-btn-section pull-right' title='<?= Yii::t('app', 'Upload image'); ?>' type='button'>

            </button>

        <?= Html::activeFileInput($model, $attribute, $options); ?>

            <?= Html::textInput($attribute_x, '', $options_x) ?>
            <?= Html::textInput($attribute_y, '', $options_y) ?>
            <?= Html::textInput($attribute_height, '', $options_height) ?>
            <?= Html::textInput($attribute_width, '', $options_width) ?>
            <?= Html::textInput($attribute_origin_width, '', $options_origin_width) ?>
            <?= Html::textInput($attribute_origin_height, '', $options_origin_height) ?>
            <?= Html::textInput($attribute_scale, '', $options_scale) ?>
            <?= Html::textInput($attribute_angle, '', $options_angle) ?>
            <?= Html::textInput($attribute_remove, isset($options_remove['value']) ? $options_remove['value'] : '', $options_remove) ?>

<?php
$plugin_options['section'] = '#' . $plugin_options['section'];
$plugin_options['id_input_file'] = '#' . $plugin_options['id_input_file'];
$options = Json::encode($plugin_options, true);
$section = $plugin_options['section'];

$this->registerJs("
mr_section_init($options);
");
?>


text:
package org.drools.verifier.report.components;

import java.util.ArrayList;
import java.util.Collection;

public class Severity implements Comparable<Severity> {
    public static final Severity NOTE = new Severity(0, "Note", "Notes");
    public static final Severity WARNING = new Severity(1, "Warning",
            "Warnings");
    public static final Severity ERROR = new Severity(2, "Error", "Errors");

    private final int index;
    public final String singular;
    private final String tuple;

    private Severity(int i, String singular, String tuple) {
        this.index = i;
        this.singular = singular;
        this.tuple = tuple;
    }

    private int getIndex() {
        return index;
    }

    public String getSingular() {
        return singular;
    }

    public String getTuple() {
        return tuple;
    }

    public static Collection<Severity> values() {
        Collection<Severity> all = new ArrayList<Severity>();

        all.add(NOTE);
        all.add(WARNING);
        all.add(ERROR);

        return all;
    }

    @Override
    public String toString() {
        return singular;
    }

    public int compareTo(Severity s) {

        if (s.getIndex() == this.index) {
            return 0;
        }

        return (s.getIndex() < this.index ? -1 : 1);
    }
}


text:
/*
 * $Date: 2015-05-13 14:12:05 +0200 (Wed, 13 May 2015) $
 * $Revision: 2290 $
 */

/**
 * @file VL6180x_def.h
 *
 * @brief Type definitions for vl6180x api.
 *
 */

#ifndef _VL6180x_DEF
#define _VL6180x_DEF

/** API major version */
#define VL6180x_API_REV_MAJOR   3
/** API minor version */
#define VL6180x_API_REV_MINOR   0
/** API sub version */
#define VL6180x_API_REV_SUB     1

#define VL6180X_STR_HELPER(x) #x
#define VL6180X_STR(x) VL6180X_STR_HELPER(x)

#include "vl6180x_cfg.h"

/*
 * check configuration macro raise error or warning and suggest a default value
 */

#ifndef VL6180x_UPSCALE_SUPPORT
#error "VL6180x_UPSCALE_SUPPORT not defined"
/* TODO you must define value for  upscale support in your vl6180x_cfg.h  */
#endif

#ifndef VL6180x_ALS_SUPPORT
#error "VL6180x_ALS_SUPPORT not defined"
/* TODO you must define VL6180x_ALS_SUPPORT  with a value in your vl6180x_cfg.h  set to 0 do disable*/
#endif

#ifndef VL6180x_HAVE_DMAX_RANGING
#error "VL6180x_HAVE_DMAX_RANGING not defined"
/* TODO you may remove or comment these #error and keep the default below  or update your vl6180x_cfg.h .h file */
/**
 * force VL6180x_HAVE_DMAX_RANGING to not supported when not part of cfg file
 */
#define VL6180x_HAVE_DMAX_RANGING   0
#endif

#ifndef VL6180x_EXTENDED_RANGE
#define VL6180x_EXTENDED_RANGE   0
#endif

#ifndef  VL6180x_WRAP_AROUND_FILTER_SUPPORT
#error "VL6180x_WRAP_AROUND_FILTER_SUPPORT not defined ?"
/* TODO you may remove or comment these #error and keep the default below  or update vl6180x_cfg.h file */
/**
 * force VL6180x_WRAP_AROUND_FILTER_SUPPORT to not supported when not part of cfg file
 */
#define VL6180x_WRAP_AROUND_FILTER_SUPPORT 0
#endif

/****************************************
 * PRIVATE define do not edit
 ****************************************/

/** Maximal buffer size ever use in i2c */
#define VL6180x_MAX_I2C_XFER_SIZE   8 /* At present time it 6 byte max but that can change */

#if VL6180x_UPSCALE_SUPPORT < 0
/**
 * @def VL6180x_HAVE_UPSCALE_DATA
 * @brief  is defined if device data structure has data so when user configurable up-scale is active
 */
#define VL6180x_HAVE_UPSCALE_DATA /* have data only for user configurable up-scale config */
#endif

#if VL6180x_WRAP_AROUND_FILTER_SUPPORT
/**
 * @def VL6180x_HAVE_WRAP_AROUND_DATA
 * @brief  is defined if device data structure has filter data so when active in cfg file
 */
#define  VL6180x_HAVE_WRAP_AROUND_DATA
#endif

#if VL6180x_ALS_SUPPORT != 0
/**
 * @def  VL6180x_HAVE_ALS_DATA
 * @brief is defined when als data are include in device data structure so when als suport if configured
 */
#define VL6180x_HAVE_ALS_DATA
#endif

#if VL6180x_WRAP_AROUND_FILTER_SUPPORT || VL6180x_HAVE_DMAX_RANGING
	#define	VL6180x_HAVE_RATE_DATA
#endif

/** Error and warning code returned by API
 *
 * negative value are true error mostly fatal\n
 * positive value  are warning most of time it's ok to continue\n
 */
enum VL6180x_ErrCode_t{
	API_NO_ERROR        = 0,
    CALIBRATION_WARNING = 1,  /*!< warning invalid calibration data may be in used \a  VL6180x_InitData() \a VL6180x_GetOffsetCalibrationData \a VL6180x_SetOffsetCalibrationData*/
    MIN_CLIPED          = 2,  /*!< warning parameter passed was clipped to min before to be applied */
    NOT_GUARANTEED      = 3,  /*!< Correct operation is not guaranteed typically using extended ranging on vl6180x */
    NOT_READY           = 4,  /*!< the data is not ready retry */

    API_ERROR      = -1,    /*!< Unqualified error */
    INVALID_PARAMS = -2,    /*!< parameter passed is invalid or out of range */
    NOT_SUPPORTED  = -3,    /*!< function is not supported in current mode or configuration */
    RANGE_ERROR    = -4,    /*!< device report a ranging error interrupt status */
    TIME_OUT       = -5,    /*!< aborted due to time out */
};

/**
 * Filtered result data structure  range data is to be used
 */
typedef struct RangeFilterResult_tag {
    uint16_t range_mm;      /*!< Filtered ranging value */
    uint16_t rawRange_mm;   /*!< raw range value (scaled) */
} RangeFilterResult_t;

/**
 * "small" unsigned data type used in filter
 *
 * if data space saving is not a concern it can be change to platform native unsigned int
 */
typedef uint8_t  FilterType1_t;

/**
 * @def FILTER_NBOF_SAMPLES
 * @brief sample history len used for wrap around filtering
 */
#define FILTER_NBOF_SAMPLES             10
/**
 * Wrap around filter internal data
 */
struct FilterData_t {
    uint32_t MeasurementIndex;                      /*!< current measurement index */
    uint16_t LastTrueRange[FILTER_NBOF_SAMPLES];    /*!< filtered/corrected  distance history */
    uint32_t LastReturnRates[FILTER_NBOF_SAMPLES];  /*!< Return rate history */
    uint16_t StdFilteredReads;                      /*!< internal use */
    FilterType1_t Default_ZeroVal;                  /*!< internal use */
    FilterType1_t Default_VAVGVal;                  /*!< internal use */
    FilterType1_t NoDelay_ZeroVal;                  /*!< internal use */
    FilterType1_t NoDelay_VAVGVal;                  /*!< internal use */
    FilterType1_t Previous_VAVGDiff;                /*!< internal use */
};

#if  VL6180x_HAVE_DMAX_RANGING
typedef int32_t DMaxFix_t;
struct DMaxData_t {
    uint32_t ambTuningWindowFactor_K; /*!<  internal algo tuning (*1000) */

    DMaxFix_t retSignalAt400mm;  /*!< intermediate dmax computation value caching @a #SYSRANGE_CROSSTALK_COMPENSATION_RATE and private reg 0x02A */
    //int32_t RegB8;              /*!< register 0xB8 cached to speed reduce i2c traffic for dmax computation */
    /* place all word data below to optimize struct packing */
    //int32_t minSignalNeeded;    /*!< optimized computation intermediate base on register cached value */
    int32_t snrLimit_K;         /*!< cached and optimized computation intermediate from  @a #SYSRANGE_MAX_AMBIENT_LEVEL_MULT */
    uint16_t ClipSnrLimit;      /*!< Max value for snr limit */
    /* place all byte data below to optimize packing */
    //uint8_t MaxConvTime;        /*!< cached max convergence time @a #SYSRANGE_MAX_CONVERGENCE_TIME*/
};
#endif

/**
 * @struct VL6180xDevData_t
 *
 * @brief Per VL6180x device St private data structure \n
 * End user should never access any of these field directly
 *
 * These must never access directly but only via VL6180xDev/SetData(dev, field) macro
 */
struct VL6180xDevData_t {

    uint32_t Part2PartAmbNVM;  /*!< backed up NVM value */
    uint32_t XTalkCompRate_KCps; /*! Cached XTlak Compensation Rate */

    uint16_t EceFactorM;        /*!< Ece Factor M numerator  */
    uint16_t EceFactorD;        /*!< Ece Factor D denominator*/

#ifdef VL6180x_HAVE_ALS_DATA
    uint16_t IntegrationPeriod; /*!< cached als Integration period avoid slow read from device at each measure */
    uint16_t AlsGainCode;       /*!< cached Als gain avoid slow read from device at each measure */
    uint16_t AlsScaler;         /*!< cached Als scaler avoid slow read from device at each measure */
#endif

#ifdef VL6180x_HAVE_UPSCALE_DATA
    uint8_t UpscaleFactor;      /*!<  up-scaling factor*/
#endif

#ifdef  VL6180x_HAVE_WRAP_AROUND_DATA
    uint8_t WrapAroundFilterActive; /*!< Filter on/off */
    struct FilterData_t FilterData; /*!< Filter internal data state history ... */
#endif

#if  VL6180x_HAVE_DMAX_RANGING
    struct DMaxData_t DMaxData;
    uint8_t DMaxEnable;
#endif
    int8_t  Part2PartOffsetNVM;     /*!< backed up NVM value */
};

#if VL6180x_SINGLE_DEVICE_DRIVER
extern  struct VL6180xDevData_t SingleVL6180xDevData;
#define VL6180xDevDataGet(dev, field) (SingleVL6180xDevData.field)
/* is also used as direct accessor like VL6180xDevDataGet(dev, x)++*/
#define VL6180xDevDataSet(dev, field, data) (SingleVL6180xDevData.field)=(data)
#endif

/**
 * @struct VL6180x_RangeData_t
 * @brief Range and any optional measurement data.
 */
typedef struct {
    int32_t range_mm;          /*!< range distance in mm. */
    int32_t signalRate_mcps;   /*!< signal rate (MCPS)\n these is a 9.7 fix point value, which is effectively a measure of target reflectance.*/
    uint32_t errorStatus;      /*!< Error status of the current measurement. \n
                                  see @a ::RangeError_u @a VL6180x_GetRangeStatusErrString() */

#ifdef VL6180x_HAVE_RATE_DATA
    uint32_t rtnAmbRate;    /*!< Return Ambient rate in KCount per sec related to \a RESULT_RANGE_RETURN_AMB_COUNT */
    uint32_t rtnRate;       /*!< Return rate in KCount per sec  related to \a RESULT_RANGE_RETURN_SIGNAL_COUNT  */
    uint32_t rtnConvTime;   /*!< Return Convergence time \a RESULT_RANGE_RETURN_CONV_TIME */
    uint32_t refConvTime;   /*!< Reference convergence time \a RESULT_RANGE_REFERENCE_CONV_TIME */
#endif

#if  VL6180x_HAVE_DMAX_RANGING
    uint32_t DMax;              /*!< DMax  when applicable */
#endif

#ifdef  VL6180x_HAVE_WRAP_AROUND_DATA
    RangeFilterResult_t FilteredData; /*!< Filter result main range_mm is updated */
#endif
}VL6180x_RangeData_t;

/** use where fix point 9.7 bit values are expected
 *
 * given a floating point value f it's .7 bit point is (int)(f*(1<<7))*/
typedef uint16_t FixPoint97_t;

/** lux data type */
typedef uint32_t lux_t;

/**
 * @brief This data type defines als  measurement data.
 */
typedef struct VL6180x_AlsData_st{
    lux_t lux;                 /**< Light measurement (Lux) */
    uint32_t errorStatus;      /**< Error status of the current measurement. \n
     * No Error := 0. \n
     * Refer to product sheets for other error codes. */
}VL6180x_AlsData_t;

/**
 * @brief Range status Error code
 *
 * @a VL6180x_GetRangeStatusErrString() if configured ( @a #VL6180x_RANGE_STATUS_ERRSTRING )
 * related to register @a #RESULT_RANGE_STATUS and additional post processing
 */
typedef enum {
    NoError_=0,                /*!< 0  0b0000 NoError  */
    VCSEL_Continuity_Test,     /*!< 1  0b0001 VCSEL_Continuity_Test */
    VCSEL_Watchdog_Test,       /*!< 2  0b0010 VCSEL_Watchdog_Test */
    VCSEL_Watchdog,            /*!< 3  0b0011 VCSEL_Watchdog */
    PLL1_Lock,                 /*!< 4  0b0100 PLL1_Lock */
    PLL2_Lock,                 /*!< 5  0b0101 PLL2_Lock */
    Early_Convergence_Estimate,/*!< 6  0b0110 Early_Convergence_Estimate */
    Max_Convergence,           /*!< 7  0b0111 Max_Convergence */
    No_Target_Ignore,          /*!< 8  0b1000 No_Target_Ignore */
    Not_used_9,                /*!< 9  0b1001 Not_used */
    Not_used_10,               /*!< 10 0b1010 Not_used_ */
    Max_Signal_To_Noise_Ratio, /*!< 11 0b1011 Max_Signal_To_Noise_Ratio*/
    Raw_Ranging_Algo_Underflow,/*!< 12 0b1100 Raw_Ranging_Algo_Underflow*/
    Raw_Ranging_Algo_Overflow, /*!< 13 0b1101 Raw_Ranging_Algo_Overflow */
    Ranging_Algo_Underflow,    /*!< 14 0b1110 Ranging_Algo_Underflow */
    Ranging_Algo_Overflow,     /*!< 15 0b1111 Ranging_Algo_Overflow */

    /* code below are addition for API/software side they are not hardware*/
    RangingFiltered =0x10,     /*!< 16 0b10000 filtered by post processing*/

} RangeError_u;

/** @defgroup device_regdef Device registers & masks definitions
 *  @brief    Device registers and masks definitions
 */

/** @ingroup device_regdef
 * @{*/

/**
 * The device model ID
 */
#define IDENTIFICATION_MODEL_ID                 0x000
/**
 * Revision identifier of the Device for major change.
 */
#define IDENTIFICATION_MODULE_REV_MAJOR         0x003
/**
 * Revision identifier of the Device for minor change.
 */
#define IDENTIFICATION_MODULE_REV_MINOR         0x004

/**
 * @def SYSTEM_MODE_GPIO0
 * @brief Configures polarity and select which function gpio 0 serves.
 *  Gpio0 is chip enable at power up ! Be aware of all h/w implication of turning it to output.
 *  Same definition as #SYSTEM_MODE_GPIO1
 * @ingroup device_regdef
 */
#define SYSTEM_MODE_GPIO0                       0x010
/**
 * @def SYSTEM_MODE_GPIO1
 * @brief Configures polarity and select what als or ranging functionality gpio pin serves.
 *
 * Function can be #GPIOx_SELECT_OFF  #GPIOx_SELECT_GPIO_INTERRUPT_OUTPUT.\n
 * Same definition apply to register GPIO0 that is used as chip enable at power up.
 * @ingroup device_regdef
 */
#define SYSTEM_MODE_GPIO1                       0x011
    /** gpio pad POLARITY mask in #SYSTEM_MODE_GPIO1 (and/or 0) write  1  to set active high polarity (positive edge) */
    #define GPIOx_POLARITY_SELECT_MASK              0x20
    /** gpio pad Function select shift in #SYSTEM_MODE_GPIO1 or 0 */
    #define GPIOx_FUNCTIONALITY_SELECT_SHIFT          1
    /** gpio pad Function select mask in #SYSTEM_MODE_GPIO1 or 0 */
    #define GPIOx_FUNCTIONALITY_SELECT_MASK          (0xF<<GPIOx_FUNCTIONALITY_SELECT_SHIFT)
    /** select no interrupt in #SYSTEM_MODE_GPIO1 pad is put in  Hi-Z*/
    #define GPIOx_SELECT_OFF                        0x00
    /** select gpiox as interrupt output in  #SYSTEM_MODE_GPIO1 */
    #define GPIOx_SELECT_GPIO_INTERRUPT_OUTPUT      0x08
    /** select range as source for interrupt on in #SYSTEM_MODE_GPIO1 */
    #define GPIOx_MODE_SELECT_RANGING               0x00
    /** select als as source for interrupt on in #SYSTEM_MODE_GPIO1 */
    #define GPIOx_MODE_SELECT_ALS                   0x01

/**
 * @def SYSTEM_INTERRUPT_CONFIG_GPIO
 *
 * @brief   Configure Als and Ranging interrupt reporting
 *
 * Possible values for Range and ALS are\n
 *
 * #CONFIG_GPIO_INTERRUPT_DISABLED\n
 * #CONFIG_GPIO_INTERRUPT_LEVEL_LOW\n
 * #CONFIG_GPIO_INTERRUPT_LEVEL_HIGH\n
 * #CONFIG_GPIO_INTERRUPT_OUT_OF_WINDOW\n
 * #CONFIG_GPIO_INTERRUPT_NEW_SAMPLE_READY\n
 * Apply respective rang/als shift and mask \n
 *  #CONFIG_GPIO_RANGE_SHIFT and full reg mask #CONFIG_GPIO_RANGE_MASK\n
 *  #CONFIG_GPIO_ALS_SHIFT and full reg mask #CONFIG_GPIO_ALS_MASK\n
 *
 * \sa GPIO use for interrupt #SYSTEM_MODE_GPIO0 or #SYSTEM_MODE_GPIO1\n
 * @ingroup device_regdef
 */
#define SYSTEM_INTERRUPT_CONFIG_GPIO           0x014
    /** RANGE bits shift in #SYSTEM_INTERRUPT_CONFIG_GPIO */
    #define CONFIG_GPIO_RANGE_SHIFT            0
    /** RANGE bits mask in #SYSTEM_INTERRUPT_CONFIG_GPIO  (unshifted)*/
    #define CONFIG_GPIO_RANGE_MASK             (0x7<<CONFIG_GPIO_RANGE_SHIFT)
    /** ALS bits shift in #SYSTEM_INTERRUPT_CONFIG_GPIO */
    #define CONFIG_GPIO_ALS_SHIFT              3
    /** ALS bits mask in #SYSTEM_INTERRUPT_CONFIG_GPIO  (unshifted)*/
    #define CONFIG_GPIO_ALS_MASK               (0x7<<CONFIG_GPIO_ALS_SHIFT)
    /** interrupt is disabled */
    #define CONFIG_GPIO_INTERRUPT_DISABLED         0x00
    /** trigger when value < low threshold */
    #define CONFIG_GPIO_INTERRUPT_LEVEL_LOW        0x01
    /** trigger when value < low threshold */
    #define CONFIG_GPIO_INTERRUPT_LEVEL_HIGH       0x02
    /** trigger when outside range defined by high low threshold */
    #define CONFIG_GPIO_INTERRUPT_OUT_OF_WINDOW    0x03
    /** trigger when new sample are ready */
    #define CONFIG_GPIO_INTERRUPT_NEW_SAMPLE_READY 0x04

/**
 *  @def SYSTEM_INTERRUPT_CLEAR
 *  @brief Writing to this register will clear interrupt source
 *
 *  Use or combination of any #INTERRUPT_CLEAR_RANGING , #INTERRUPT_CLEAR_ALS , #INTERRUPT_CLEAR_ERROR
 *  @ingroup device_regdef
 */
#define SYSTEM_INTERRUPT_CLEAR                0x015
    /** clear ranging interrupt in write to #SYSTEM_INTERRUPT_CLEAR */
    #define INTERRUPT_CLEAR_RANGING                0x01
    /** clear als interrupt  in write to #SYSTEM_INTERRUPT_CLEAR */
    #define INTERRUPT_CLEAR_ALS                    0x02
    /** clear error interrupt in write to #SYSTEM_INTERRUPT_CLEAR */
    #define INTERRUPT_CLEAR_ERROR                  0x04

/** After power up or reset this register will start reading 1 when device is ready */
#define SYSTEM_FRESH_OUT_OF_RESET             0x016

/**
 * @def SYSTEM_GROUPED_PARAMETER_HOLD
 * @brief Writing 1/0 activate/deactivate safe host update of multiple register in critical group \n
 *        rather use \a VL6180x_SetGroupParamHold()
 *
 * The critical register group is made of: \n
 * #SYSTEM_INTERRUPT_CONFIG_GPIO \n
 * #SYSRANGE_THRESH_HIGH \n
 * #SYSRANGE_THRESH_LOW \n
 * #SYSALS_INTEGRATION_PERIOD \n
 * #SYSALS_ANALOGUE_GAIN \n
 * #SYSALS_THRESH_HIGH \n
 * #SYSALS_THRESH_LOW
 * @ingroup device_regdef
 */
#define SYSTEM_GROUPED_PARAMETER_HOLD         0x017

/**
 * @def SYSRANGE_START
 * @brief Start/stop and set operating range mode
 *
 * Write Combination of #MODE_START_STOP  and #MODE_CONTINUOUS to select and start desired operation.
 *
 * @ingroup device_regdef
 */
#define SYSRANGE_START                        0x018
    /** mask existing bit in #SYSRANGE_START*/
    #define MODE_MASK          0x03
    /** bit 0 in #SYSRANGE_START write 1 toggle state in continuous mode and arm next shot in single shot mode */
    #define MODE_START_STOP    0x01
    /** bit 1 write 1 in #SYSRANGE_START set continuous operation mode */
    #define MODE_CONTINUOUS    0x02
    /** bit 1 write 0 in #SYSRANGE_START set single shot mode */
    #define MODE_SINGLESHOT    0x00

/**
 * @def SYSRANGE_THRESH_HIGH
 * High level range  threshold (must be scaled)
 * @ingroup device_regdef
 */
#define SYSRANGE_THRESH_HIGH                  0x019

/**
 * @def SYSRANGE_THRESH_LOW
 * Low level range  threshold (must be scaled)
 * @ingroup device_regdef
 */
#define SYSRANGE_THRESH_LOW                   0x01A

/**
 * @def SYSRANGE_INTERMEASUREMENT_PERIOD
 * @brief Continuous mode intermeasurement delay \a VL6180x_RangeSetInterMeasPeriod()
 *
 * Time delay between measurements in Ranging continuous mode.\n
 * Range 0-254 (0 = 10ms).\n Step size = 10ms.
 *
 * @ingroup device_regdef
 */
#define SYSRANGE_INTERMEASUREMENT_PERIOD      0x01B

/**
 * @brief Maximum time to run measurement in Ranging modes.
 * Range 1 - 63 ms (1 code = 1 ms);
 *
 * Measurement aborted when limit reached to aid power  reduction.\
 * For example, 0x01 = 1ms, 0x0a = 10ms.\
 * Note: Effective max_convergence_time depends on readout_averaging_sample_period setting.
 *
 * @ingroup device_regdef
 */
#define SYSRANGE_MAX_CONVERGENCE_TIME         0x01C
/**@brief Cross talk compensation rate
 * @warning  never write register directly use @a VL6180x_SetXTalkCompensationRate()
 * refer to manual for calibration procedure and computation
 * @ingroup device_regdef
 */
#define SYSRANGE_CROSSTALK_COMPENSATION_RATE  0x01E
/**
 * @brief Minimum range value in mm to qualify for crosstalk compensation
 */
#define SYSRANGE_CROSSTALK_VALID_HEIGHT       0x021
#define SYSRANGE_EARLY_CONVERGENCE_ESTIMATE   0x022
#define SYSRANGE_PART_TO_PART_RANGE_OFFSET    0x024
#define SYSRANGE_RANGE_IGNORE_VALID_HEIGHT    0x025
#define SYSRANGE_RANGE_IGNORE_THRESHOLD       0x026
#define SYSRANGE_EMITTER_BLOCK_THRESHOLD      0x028
#define SYSRANGE_MAX_AMBIENT_LEVEL_THRESH     0x02A
#define SYSRANGE_MAX_AMBIENT_LEVEL_MULT       0x02C
/** @brief  various Enable check enabel register
 *  @a VL6180x_RangeSetEceState()
 */
#define SYSRANGE_RANGE_CHECK_ENABLES          0x02D
    #define RANGE_CHECK_ECE_ENABLE_MASK      0x01
    #define RANGE_CHECK_RANGE_ENABLE_MASK    0x02
    #define RANGE_CHECK_SNR_ENABLKE          0x10

#define SYSRANGE_VHV_RECALIBRATE              0x02E
#define SYSRANGE_VHV_REPEAT_RATE              0x031

/**
 * @def SYSALS_START
 * @brief Start/stop and set operating als mode
 *
 * same bit definition as range \a #SYSRANGE_START \n
 */
#define SYSALS_START                          0x038

/** ALS low Threshold high */
#define SYSALS_THRESH_HIGH                    0x03A
/** ALS low Threshold low */
#define SYSALS_THRESH_LOW                     0x03C
/** ALS intermeasurement period */
#define SYSALS_INTERMEASUREMENT_PERIOD        0x03E
/**
 * @warning or value with 0x40 when writing to these register*/
#define SYSALS_ANALOGUE_GAIN                  0x03F
/** ALS integration period */
#define SYSALS_INTEGRATION_PERIOD             0x040

/**
 * @brief Result range status
 *
 *  Hold the various range interrupt flags and error Specific error codes
 */
#define RESULT_RANGE_STATUS                   0x04D
    /** Device ready for new command bit 0*/
    #define RANGE_DEVICE_READY_MASK       0x01
    /** mask for error status covers bits [7:4]  in #RESULT_RANGE_STATUS @a ::RangeError_u */
    #define RANGE_ERROR_CODE_MASK         0xF0 /* */
    /** range error bit position in #RESULT_RANGE_STATUS */
    #define RANGE_ERROR_CODE_SHIFT        4

/**
 * @def RESULT_ALS_STATUS
 * @brief Result  als status \n
 *  Hold the various als interrupt flags and Specific error codes
 */
#define RESULT_ALS_STATUS                     0x4E
    /** Device ready for new command bit 0*/
   #define ALS_DEVICE_READY_MASK       0x01

/**
 * @def RESULT_ALS_VAL
 * @brief 16 Bit ALS count output value.
 *
 * Lux value depends on Gain and integration settings and calibrated lux/count setting
 * \a VL6180x_AlsGetLux() \a VL6180x_AlsGetMeasurement()
 */
#define RESULT_ALS_VAL                        0x50

/**
 * @def FW_ALS_RESULT_SCALER
 * @brief Als scaler register  Bits [3:0] analogue gain 1 to 16x
 * these register content is cached by API in \a VL6180xDevData_t::AlsScaler
 * for lux computation acceleration
 */
#define FW_ALS_RESULT_SCALER                  0x120

/**
 * these union can be use as a generic bit field type for map #RESULT_INTERRUPT_STATUS_GPIO register
 * @ingroup device_regdef
 */
typedef union IntrStatus_u{
    uint8_t val;           /*!< raw 8 bit register value*/
    struct  {
        unsigned Range     :3; /*!< Range status one of :\n  \a #RES_INT_STAT_GPIO_LOW_LEVEL_THRESHOLD  \n \a #RES_INT_STAT_GPIO_HIGH_LEVEL_THRESHOLD  \n \a #RES_INT_STAT_GPIO_OUT_OF_WINDOW \n \a #RES_INT_STAT_GPIO_NEW_SAMPLE_READY */
        unsigned Als       :3; /*!< Als status one of: \n \a #RES_INT_STAT_GPIO_LOW_LEVEL_THRESHOLD  \n \a #RES_INT_STAT_GPIO_HIGH_LEVEL_THRESHOLD  \n \a #RES_INT_STAT_GPIO_OUT_OF_WINDOW \n \a #RES_INT_STAT_GPIO_NEW_SAMPLE_READY  */
        unsigned Error     :2; /*!<  Error status of: \n \a #RES_INT_ERROR_LASER_SAFETY  \n \a #RES_INT_ERROR_PLL */
     } status;                 /*!< interrupt status as bit field */
} IntrStatus_t;

/**
 * @def RESULT_INTERRUPT_STATUS_GPIO
 * @brief System interrupt status report selected interrupt for als and ranging
 *
 * These register can be polled even if no gpio pins is active\n
 * What reported is selected by \a  #SYSTEM_INTERRUPT_CONFIG_GPIO \n
 * Range mask with \a #RES_INT_RANGE_MASK and shit by \a #RES_INT_RANGE_SHIFT
 * Als   mask with \a #RES_INT_ALS_MASK and shit by \a #RES_INT_ALS_SHIFT
 * Result value express condition (or combination?)
 * \a #RES_INT_STAT_GPIO_LOW_LEVEL_THRESHOLD \n
 * \a #RES_INT_STAT_GPIO_HIGH_LEVEL_THRESHOLD \n
 * \a #RES_INT_STAT_GPIO_OUT_OF_WINDOW \n
 * \a #RES_INT_STAT_GPIO_NEW_SAMPLE_READY
 *
 * @ingroup device_regdef
 */
#define RESULT_INTERRUPT_STATUS_GPIO          0x4F
    /** ranging interrupt 1st bit position in #RESULT_INTERRUPT_STATUS_GPIO */
    #define RES_INT_RANGE_SHIFT  0
    /** ALS interrupt 1st bit position in #RESULT_INTERRUPT_STATUS_GPIO */
    #define RES_INT_ALS_SHIFT    3
    /** interrupt bit position in #RESULT_INTERRUPT_STATUS_GPIO */
    #define RES_INT_ERROR_SHIFT  6
    /** Ranging interrupt mask in #RESULT_INTERRUPT_STATUS_GPIO (prior to shift)  \sa IntrStatus_t */
    #define RES_INT_RANGE_MASK (0x7<<RES_INT_RANGE_SHIFT)
    /** als interrupt mask in #RESULT_INTERRUPT_STATUS_GPIO (prior to shift)  \sa IntrStatus_t */
    #define RES_INT_ALS_MASK   (0x7<<RES_INT_ALS_SHIFT)

    /** low threshold condition in #RESULT_INTERRUPT_STATUS_GPIO for */
    #define RES_INT_STAT_GPIO_LOW_LEVEL_THRESHOLD  0x01
    /** high threshold condition in #RESULT_INTERRUPT_STATUS_GPIO for ALs or Rage*/
    #define RES_INT_STAT_GPIO_HIGH_LEVEL_THRESHOLD 0x02
    /** out of window condition in #RESULT_INTERRUPT_STATUS_GPIO */
    #define RES_INT_STAT_GPIO_OUT_OF_WINDOW        0x03
    /** new sample ready in #RESULT_INTERRUPT_STATUS_GPIO */
    #define RES_INT_STAT_GPIO_NEW_SAMPLE_READY     0x04
    /** error  in #RESULT_INTERRUPT_STATUS_GPIO */
    #define RES_INT_ERROR_MASK (0x3<<RES_INT_ERROR_SHIFT)
        /** laser safety error on #RES_INT_ERROR_MASK of #RESULT_INTERRUPT_STATUS_GPIO */
        #define RES_INT_ERROR_LASER_SAFETY  1
        /** pll 1 or 2 error on #RES_INT_ERROR_MASK of #RESULT_INTERRUPT_STATUS_GPIO*/
        #define RES_INT_ERROR_PLL           2

/**
 * Final range result value presented to the user for use. Unit is in mm.
 */
#define RESULT_RANGE_VAL                        0x062

/**
 * Raw Range result value with offset applied (no cross talk compensation applied). Unit is in mm.
 */
#define RESULT_RANGE_RAW                        0x064

/**
 * @brief Sensor count rate of signal returns correlated to IR emitter.
 *
 * Computed from RETURN_SIGNAL_COUNT / RETURN_CONV_TIME. Mcps 9.7 format
 */
#define RESULT_RANGE_SIGNAL_RATE                0x066

/**
 * @brief Return signal count
 *
 *  Sensor count output value attributed to signal correlated to IR emitter on the Return array.
 */
#define RESULT_RANGE_RETURN_SIGNAL_COUNT        0x06C

/**
 * @brief Reference signal count
 *
 * sensor count output value attributed to signal correlated to IR emitter on the Reference array.
 */
#define RESULT_RANGE_REFERENCE_SIGNAL_COUNT     0x070

/**
 * @brief Return ambient count
 *
 * sensor count output value attributed to uncorrelated ambient signal on the Return array.
 * Must be multiplied by 6 if used to calculate the ambient to signal threshold
 */
#define RESULT_RANGE_RETURN_AMB_COUNT           0x074

/**
 * @brief   Reference ambient count
 *
 * Sensor count output value attributed to uncorrelated ambient signal on the Reference array.
 */
#define RESULT_RANGE_REFERENCE_AMB_COUNT        0x078

/**
 * sensor count output value attributed to signal on the Return array.
 */
#define RESULT_RANGE_RETURN_CONV_TIME           0x07C

/**
 * sensor count output value attributed to signal on the Reference array.
 */
#define RESULT_RANGE_REFERENCE_CONV_TIME        0x080

/**
 * @def RANGE_SCALER
 * @brief RANGE scaling register
 *
 * Never should  user write directly onto that register directly \a VL6180x_UpscaleSetScaling()
 */
#define RANGE_SCALER                            0x096

/**
 * @def READOUT_AVERAGING_SAMPLE_PERIOD
 * @brief Readout averaging sample period register
 *
 *
 * The internal readout averaging sample period can be adjusted from 0 to 255.
 * Increasing the sampling period decreases noise but also reduces the effective
 * max convergence time and increases power consumption
 * Each unit sample period corresponds to around 64.5 μs additional processing time.
 * The recommended setting is 48 which equates to around 4.3 ms.
 *
 * see datasheet for more detail
 */
#define READOUT_AVERAGING_SAMPLE_PERIOD     0x10A

/**
 * @def I2C_SLAVE_DEVICE_ADDRESS
 * User programmable I2C address (7-bit). Device address can be re-designated after power-up.
 * @warning What programmed in the register 7-0 are bit 8-1 of i2c address on bus (bit 0 is rd/wr)
 * so what prohamd is commonly whar ergfer as adrerss /2
 * @sa VL6180x_SetI2CAddress()
 */
#define I2C_SLAVE_DEVICE_ADDRESS               0x212

#endif /* _VL6180x_DEF */


text:
using namespace IECoreMaya;

ToMayaMeshConverter::Description ToMayaMeshConverter::g_meshDataDescription( IECore::MeshPrimitive::staticTypeId(), MFn::kMeshData );
ToMayaMeshConverter::Description ToMayaMeshConverter::g_meshDescription( IECore::MeshPrimitive::staticTypeId(), MFn::kMesh );

ToMayaMeshConverter::ToMayaMeshConverter( IECore::ConstObjectPtr object )
: ToMayaObjectConverter( "Converts IECore::MeshPrimitive objects to a Maya object.", object)
{
}

void ToMayaMeshConverter::assignDefaultShadingGroup( MObject &shape ) const
{
	MFnDagNode fnDN( shape );
	// it would perhaps be preferable to use MFnSet::addMember() instead but at the time of
	// writing (maya 2010) that seems to print out "Result : initialShadingGroup" totally unnecessarily.
	MGlobal::executeCommand( "sets -addElement initialShadingGroup " + fnDN.fullPathName() );
}

void ToMayaMeshConverter::addUVSet( MFnMesh &fnMesh, const MIntArray &polygonCounts, IECore::ConstMeshPrimitivePtr mesh, const std::string &sPrimVarName, const std::string &tPrimVarName, const std::string &stIdPrimVarName, MString *uvSetName ) const
{
	IECore::PrimitiveVariableMap::const_iterator sIt = mesh->variables.find( sPrimVarName );
	bool haveS = sIt != mesh->variables.end();
	IECore::PrimitiveVariableMap::const_iterator tIt = mesh->variables.find( tPrimVarName );
	bool haveT = tIt != mesh->variables.end();
	IECore::PrimitiveVariableMap::const_iterator stIdIt = mesh->variables.find( stIdPrimVarName );
	bool haveSTId = stIdIt != mesh->variables.end();

	if ( haveS && haveT )
	{
		if ( sIt->second.interpolation != IECore::PrimitiveVariable::FaceVarying )
		{
			IECore::msg( IECore::Msg::Warning,"ToMayaMeshConverter::doConversion",  boost::format(  "PrimitiveVariable \"%s\" has unsupported interpolation (expected FaceVarying).") % sPrimVarName );
			return;
		}

		if ( tIt->second.interpolation != IECore::PrimitiveVariable::FaceVarying )
		{
			IECore::msg( IECore::Msg::Warning, "ToMayaMeshConverter::doConversion", boost::format( "PrimitiveVariable \"%s\" has unsupported interpolation (expected FaceVarying).") % tPrimVarName);
			return;
		}

		if ( !sIt->second.data )
		{
			IECore::msg( IECore::Msg::Warning, "ToMayaMeshConverter::doConversion", boost::format( "PrimitiveVariable \"%s\" has no data." ) % sPrimVarName );
		}

		if ( !tIt->second.data )
		{
			IECore::msg( IECore::Msg::Warning, "ToMayaMeshConverter::doConversion", boost::format( "PrimitiveVariable \"%s\" has no data." ) % tPrimVarName );
		}

		/// \todo Employ some M*Array converters to simplify this
		int numUVs = mesh->variableSize( IECore::PrimitiveVariable::FaceVarying );

		IECore::ConstFloatVectorDataPtr u = IECore::runTimeCast<const IECore::FloatVectorData>(sIt->second.data);

		if ( !u )
		{
			IECore::msg( IECore::Msg::Warning, "ToMayaMeshConverter::doConversion", boost::format( "PrimitiveVariable \"%s\" has unsupported type \"%s\"." ) % sPrimVarName % sIt->second.data->typeName() );
			return;
		}

		assert( (int)u->readable().size() == numUVs );

		IECore::ConstFloatVectorDataPtr v = IECore::runTimeCast<const IECore::FloatVectorData>(tIt->second.data);
		if ( !v )
		{
			IECore::msg( IECore::Msg::Warning, "ToMayaMeshConverter::doConversion", boost::format( "PrimitiveVariable \"%s\" has unsupported type \"%s\"." ) % tPrimVarName % tIt->second.data->typeName() );
			return;
		}

		assert( (int)v->readable().size() == numUVs );

		const std::vector<float> &uAll = u->readable();
		const std::vector<float> &vAll = v->readable();

		if ( uvSetName )
		{
			bool setExists = false;
			MStringArray existingSets;
			fnMesh.getUVSetNames( existingSets );
			for ( unsigned i=0; i < existingSets.length(); ++i )
			{
				if ( *uvSetName == existingSets[i] )
				{
					fnMesh.clearUVs( uvSetName );
					setExists = true;
					break;
				}
			}

			if ( !setExists )
			{
				MDagPath dag;
				MStatus s = fnMesh.getPath( dag );
				if ( s )
				{
					fnMesh.createUVSetWithName( *uvSetName );
				}
				else
				{
					fnMesh.createUVSetDataMeshWithName( *uvSetName );
				}
			}
		}

		MIntArray uvIds;
		uvIds.setLength( numUVs );
		MFloatArray uArray;
		MFloatArray vArray;

		if( haveSTId )
		{
			// Get compressed uv values by matching them with their uvId.
			IECore::ConstIntVectorDataPtr uvId = IECore::runTimeCast<const IECore::IntVectorData>(stIdIt->second.data);
			if ( !uvId )
			{
				IECore::msg( IECore::Msg::Warning, "ToMayaMeshConverter::doConversion", boost::format( "PrimitiveVariable \"%s\" has unsupported type \"%s\"." ) % stIdPrimVarName % stIdIt->second.data->typeName() );
				return;
			}

			const std::vector<int> &uvIdData = uvId->readable();

			assert( (int)uvIdData.size() == numUVs );

			int highestId = 0;
			for ( int i = 0; i < numUVs; i++)
			{
				uvIds[i] = uvIdData[i];
				if( uvIdData[i] > highestId )
				{
					highestId = uvIdData[i];
				}
			}

			// u and v arrays need only be as long as the number of unique uvIds
			uArray.setLength( highestId + 1 );
			vArray.setLength( highestId + 1 );

			for ( int i = 0; i < numUVs; i++ )
			{
				uArray[ uvIds[i] ] = uAll[i];
				// FromMayaMeshConverter does the opposite of this
				vArray[ uvIds[i] ] = 1 - vAll[i];
			}
		}
		else
		{
			// If for some reason we cannot find the uv indices, set the UVs using the old way
			// the performances in maya won't be good (for weigth painting in particular)
			uArray.setLength( numUVs );
			vArray.setLength( numUVs );

			for ( int i = 0; i < numUVs; i++)
			{
				uArray[i] = u->readable()[i];
				// FromMayaMeshConverter does the opposite of this
				vArray[i] = 1 - v->readable()[i];
			}

			for ( int i = 0; i < numUVs; i++)
			{
				uvIds[i] = i;
			}
		}

		MStatus s = fnMesh.setUVs( uArray, vArray, uvSetName );
		if ( !s )
		{
			IECore::msg( IECore::Msg::Warning, "ToMayaMeshConverter::doConversion", "Failed to set UVs." );
			return;
		}

		s = fnMesh.assignUVs( polygonCounts, uvIds, uvSetName );
		if ( !s )
		{
			IECore::msg( IECore::Msg::Warning, "ToMayaMeshConverter::doConversion", "Failed to assign UVs." );
			return;
		}

	}
	else if ( haveS )
	{
		IECore::msg( IECore::Msg::Warning, "ToMayaMeshConverter::doConversion", boost::format( "Primitive variable \"%s\" found, but not \"%s\"." ) % sPrimVarName % tPrimVarName );
	}
	else if ( haveT )
	{
		IECore::msg( IECore::Msg::Warning, "ToMayaMeshConverter::doConversion", boost::format( "Primitive variable \"%s\" found, but not \"%s\"." ) % tPrimVarName % sPrimVarName );
	}
	else
	{
		assert( !uvSetName );
	}
}

bool ToMayaMeshConverter::doConversion( IECore::ConstObjectPtr from, MObject &to, IECore::ConstCompoundObjectPtr operands ) const
{
	MStatus s;

	IECore::ConstMeshPrimitivePtr mesh = IECore::runTimeCast<const IECore::MeshPrimitive>( from );
	assert( mesh );

	if ( !mesh->arePrimitiveVariablesValid() )
	{
		return false;
	}

	MFloatPointArray vertexArray;
	MIntArray polygonCounts;
	MIntArray polygonConnects;

	MFnMesh fnMesh;

	int numVertices = 0;
	IECore::PrimitiveVariableMap::const_iterator it = mesh->variables.find("P");
	if ( it != mesh->variables.end() )
	{
		/// \todo Employ some M*Array converters to simplify this
		IECore::ConstV3fVectorDataPtr p = IECore::runTimeCast<const IECore::V3fVectorData>(it->second.data);
		if (p)
		{
			numVertices = p->readable().size();

			vertexArray.setLength( numVertices );
			for (int i = 0; i < numVertices; i++)
			{
				vertexArray[i] = IECore::convert<MFloatPoint, Imath::V3f>( p->readable()[i] );
			}
		}
		else
		{
			IECore::ConstV3dVectorDataPtr p = IECore::runTimeCast<const IECore::V3dVectorData>(it->second.data);
			if (p)
			{
				numVertices = p->readable().size();

				vertexArray.setLength( numVertices );
				for (int i = 0; i < numVertices; i++)
				{
					vertexArray[i] = IECore::convert<MFloatPoint, Imath::V3d>( p->readable()[i] );
				}
			}
			else
			{
				// "P" is not convertible to an array of "points"
				return false;
			}
		}
	}

	IECore::ConstIntVectorDataPtr verticesPerFace = mesh->verticesPerFace();
	assert( verticesPerFace );
	int numPolygons = verticesPerFace->readable().size();

	polygonCounts.setLength( numPolygons );
	for (int i = 0; i < numPolygons; i++)
	{
		polygonCounts[i] = verticesPerFace->readable()[i];
	}

	IECore::ConstIntVectorDataPtr vertexIds = mesh->vertexIds();
	assert( vertexIds );
	int numPolygonConnects = vertexIds->readable().size();
	polygonConnects.setLength( numPolygonConnects );
	for (int i = 0; i < numPolygonConnects; i++)
	{
		polygonConnects[i] = vertexIds->readable()[i];
	}

	MObject mObj = fnMesh.create( numVertices, numPolygons, vertexArray, polygonCounts, polygonConnects, to, &s );

	if (!s)
	{
		return false;
	}

	it = mesh->variables.find("N");
	if ( it != mesh->variables.end() )
	{
		if (it->second.interpolation == IECore::PrimitiveVariable::FaceVarying )
		{
			/// \todo Employ some M*Array converters to simplify this
			MVectorArray vertexNormalsArray;
			IECore::ConstV3fVectorDataPtr n = IECore::runTimeCast<const IECore::V3fVectorData>(it->second.data);
			if (n)
			{
				int numVertexNormals = n->readable().size();

				vertexNormalsArray.setLength( numVertexNormals );
				for (int i = 0; i < numVertexNormals; i++)
				{
					vertexNormalsArray[i] = IECore::convert<MVector, Imath::V3f>( n->readable()[i] );
				}
			}
			else
			{
				IECore::ConstV3dVectorDataPtr n = IECore::runTimeCast<const IECore::V3dVectorData>(it->second.data);
				if (n)
				{
					int numVertexNormals = n->readable().size();

					vertexNormalsArray.setLength( numVertexNormals );
					for (int i = 0; i < numVertexNormals; i++)
					{
						vertexNormalsArray[i] = IECore::convert<MVector, Imath::V3d>( n->readable()[i] );
					}
				}
				else
				{
					IECore::msg( IECore::Msg::Warning, "ToMayaMeshConverter::doConversion", boost::format( "PrimitiveVariable \"N\" has unsupported type \"%s\"." ) % it->second.data->typeName() );
				}
			}

			if ( vertexNormalsArray.length() )
			{
				MStatus status;
				MItMeshPolygon itPolygon( mObj, &status );
				if( status != MS::kSuccess )
				{
					IECore::msg( IECore::Msg::Warning, "ToMayaMeshConverter::doConversion", "Failed to create mesh iterator" );
				}

				unsigned v = 0;
				MIntArray vertexIds;
				MIntArray faceIds;

				for ( ; !itPolygon.isDone(); itPolygon.next() )
				{
					for ( v=0; v < itPolygon.polygonVertexCount(); ++v )
					{
						faceIds.append( itPolygon.index() );
						vertexIds.append( itPolygon.vertexIndex( v ) );
					}
				}

				if( !fnMesh.setFaceVertexNormals( vertexNormalsArray, faceIds, vertexIds ) )
				{
					IECore::msg( IECore::Msg::Warning, "ToMayaMeshConverter::doConversion", "Setting normals failed" );
				}
			}
		}
		else
		{
			IECore::msg( IECore::Msg::Warning, "ToMayaMeshConverter::doConversion", "PrimitiveVariable \"N\" has unsupported interpolation (expected FaceVarying)." );
		}
	}

	bool haveDefaultUVs = false;
	IECore::PrimitiveVariableMap::const_iterator sIt = mesh->variables.find( "s" );
	IECore::RefCountedPtr sDataRef = ( sIt == mesh->variables.end() ) ? 0 : static_cast<IECore::RefCountedPtr>( sIt->second.data );

	/// Add named UV sets
	std::set< std::string > uvSets;
	for ( it = mesh->variables.begin(); it != mesh->variables.end(); ++it )
	{
		const std::string &sName = it->first;

		size_t suffixOffset = sName.rfind( "_s" );

		if ( ( suffixOffset != std::string::npos) && ( suffixOffset == sName.length() - 2 ) )
		{
			std::string uvSetNameStr = sName.substr( 0, suffixOffset );

			if ( uvSetNameStr.size() )
			{
				MString uvSetName = uvSetNameStr.c_str();
				std::string tName = uvSetNameStr + "_t";
				std::string stIdName = uvSetNameStr + "Indices";

				addUVSet( fnMesh, polygonCounts, mesh, sName, tName, stIdName, &uvSetName );

				uvSets.insert( uvSetNameStr );

				if ( sDataRef == static_cast<IECore::RefCountedPtr>( it->second.data ) )
				{
					haveDefaultUVs = true;
				}
			}
		}
	}

	/// Add default UV set if it isn't just a reference to a named set
	if ( !haveDefaultUVs )
	{
		addUVSet( fnMesh, polygonCounts, mesh, "s", "t", "stIndices" );
	}

	// We do the search again, but looking for primvars ending "_t", so we can catch cases where either "UVSETNAME_s" or "UVSETNAME_t" is present, but not both, taking care
	// not to attempt adding any duplicate sets
	for ( it = mesh->variables.begin(); it != mesh->variables.end(); ++it )
	{
		const std::string &tName = it->first;

		size_t suffixOffset = tName.rfind( "_t" );

		if ( ( suffixOffset != std::string::npos) && ( suffixOffset == tName.length() - 2 ) )
		{
			std::string uvSetNameStr = tName.substr( 0, suffixOffset );

			if ( uvSetNameStr.size() && uvSets.find( uvSetNameStr ) == uvSets.end() )
			{
				MString uvSetName = uvSetNameStr.c_str();
				std::string sName = uvSetNameStr + "_s";
				std::string stIdName = uvSetNameStr + "Indices";

				addUVSet( fnMesh, polygonCounts, mesh, sName, tName, stIdName, &uvSetName );
				uvSets.insert( uvSetNameStr );
			}
		}
	}

	/// If we're making a mesh node (rather than a mesh data) then make sure it belongs
	/// to the default shading group and add the ieMeshInterpolation attribute.
	MObject oMesh = fnMesh.object();
	if( oMesh.apiType()==MFn::kMesh )
	{
		assignDefaultShadingGroup( oMesh );
		setMeshInterpolationAttribute( oMesh, mesh->interpolation() );
	}

	/// \todo Other primvars, e.g. vertex color ("Cs")

	return true;
}

bool ToMayaMeshConverter::setMeshInterpolationAttribute( MObject &object, std::string interpolation )
{
	MStatus st;
	MFnMesh fnMesh(object, &st);
	if ( !st )
	{
		return false;
	}

	int interpolationValue = 0;

	FromMayaMeshConverter fromMaya(object);
	const IECore::Parameter::PresetsContainer &presets = fromMaya.interpolationParameter()->getPresets();
	IECore::Parameter::PresetsContainer::const_iterator it;

	if ( interpolation != "default" )
	{
		int index = 0;

		for ( it = presets.begin(); it != presets.end(); it++, index++ )
		{
			if ( interpolation == it->first || interpolation == IECore::staticPointerCast< IECore::StringData >(it->second)->readable() )
			{
				interpolationValue = index;
				break;
			}
		}
		if ( it == presets.end() )
		{
			return false;
		}
	}

	MPlug interpPlug = fnMesh.findPlug( "ieMeshInterpolation", &st );

	if ( !st )
	{
		MFnEnumAttribute fnAttrib;
		MObject newAttr = fnAttrib.create( "ieMeshInterpolation", "interp", 0, &st );
		if ( !st )
		{
			return false;
		}

		int index = 0;
		for ( it = presets.begin(); it != presets.end(); it++ )
		{
			if ( it->first == "default" )
			{
				continue;
			}
			fnAttrib.addField( it->first.c_str(), index );
			index++;
		}

		// looks like the attribute does not exist yet..
		st = fnMesh.addAttribute( newAttr );
		if ( !st )
		{
			return false;
		}
		interpPlug = fnMesh.findPlug( "ieMeshInterpolation", &st );
		if ( !st )
		{
			return false;
		}
	}

	st = interpPlug.setValue( interpolationValue );
	if ( !st )
	{
		return false;
	}

	return true;
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BookReviews.Common
{
    public interface ITransactionManager
    {
        void BeforeTransaction(Action beforeTransactionAction);
        void AfterTransaction(Action afterTransactionAction);
        void AfterTransactionError(Action afterTransactionErrorAction);
        TResult ExecuteTransaction<TResult>(Func<TResult> command);
        Task ExecuteTransactionAsync(Action command);
        Task<TResult> ExecuteTransactionAsync<TResult>(Func<TResult> command);
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>stis Package — SamPy v0.1 documentation</title>
    <link rel="stylesheet" href="_static/default.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />

    <link rel="top" title="SamPy v0.1 documentation" href="index.html" />
    <link rel="next" title="SamPy.stis.ObservationSchedule" href="SamPy.stis.ObservationSchedule.html" />
    <link rel="prev" title="SamPy.statistics.basics" href="SamPy.statistics.basics.html" />

Navigation

          index

          modules |

          next |

          previous |

home|

search|

Previous topic

SamPy.statistics.basics

Next topic

SamPy.stis.ObservationSchedule

This Page

Show Source

Quick search

    <form class="search" action="search.html" method="get">
      <input type="text" name="q" size="18" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

stis Package¶

<colgroup>
<col width="10%" />
<col width="90%" />
</colgroup>

<tt class="xref py py-obj docutils literal">ObservationSchedule</tt>
This script can be used to parse instrument specific observations from SMS messages. It can also be used to generate memory dump schedule from the SMS.

<tt class="xref py py-obj docutils literal">STISCCDImagingFlats</tt>
Plots ratios between STIS CCD imaging flats.

<tt class="xref py py-obj docutils literal">STISCCDSpectroscopyFlat</tt>
Creates STIS Spectroscopic pixel-to-pixel flat fields from RAW data.

Navigation

          index

          modules |

          next |

          previous |

home|

search|

        © Copyright 2011, Sami-Matias Niemi.


text:
<?php

namespace Bolt\Filesystem\Exception;

class LogicException extends \LogicException implements ExceptionInterface
{
}


text:
<?php

/*
 * Test the performance of Slim Framework (https://github.com/slimphp/Slim) with many groups and subgroups.
 */

use Slim\App;
use Slim\Http\Request;
use Slim\Http\Response;

require 'vendor/autoload.php';

$startTime = microtime(true);
$initTime = 0;
$totalRoutes = 0;

function initRoutes($base, $generateUnmatchableRoutes = true)
{
    global $startTime, $initTime;

    $app = new App();
    $groupCount = 50;
    $subgroupCount = 25;

    for ($g = 1; $g <= $groupCount; $g++) {
        $app->group("/$base/group{$g}", function () use ($app, $g, $generateUnmatchableRoutes, $groupCount, $subgroupCount, $startTime, &$initTime, &$totalRoutes) {
            if (!$generateUnmatchableRoutes) {
                if ($g === 1) {
                    $subgroupCount = 1; // generate routes only for the matching subgroup
                } else {
                    return;
                }
            }

            for ($s = 1; $s <= $subgroupCount; $s++) {
                $app->group("/sub{$s}", endpointFactory($app, $g, $s));
            }
        });
    }

    $initTime = microtime(true) - $startTime;
    $app->run();
}

function endpointFactory(App $app, $g, $s)
{
    global $totalRoutes;

    $totalRoutes += 6;
    // A real world app would often use an ORM to generate get/post/patch/update/delete methods for each endpoint.
    // The ORM would be passed a unique class name for each subgroup, which it would use inside route callbacks.
    $class = "class" . md5($g * $s);

    return function () use ($app, $class) {
        $app->get('', 'handler')->setArgument('entity', $class);
        $app->get('/{id}', 'handler')->setArgument('entity', $class);
        $app->post('', 'handler')->setArgument('entity', $class);
        $app->put('/{id}', 'handler')->setArgument('entity', $class);
        $app->patch('/{id}', 'handler')->setArgument('entity', $class);
        $app->delete('/{id}', 'handler')->setArgument('entity', $class);
    };
}

// in a real-world app there would be separate delete/patch/update/etc. handler functions
function handler(Request $request, Response $response, array $args)
{
    global $totalRoutes, $startTime, $initTime;

    return $response->withJson([
        'class' => $request->getAttribute('entity'),
        'args' => $args,
        'generatedRoutes' => $totalRoutes,
        'initTime' => $initTime,
        'responseTime' => microtime(true) - $startTime,
    ]);
}


text:
(function() {
	//var mytarget = "https://upload-flowjs-java.mybluemix.net/upload";
	//var mymethod = "octet";
	var r = new Flow({
        target: "",
    	method: "",
//    	target:'https://upload-flowjs-node.mybluemix.net/upload',
        chunkSize: 1024 * 1024,
        testChunks: false,
        permanentErrors : [ 500, 501 ],
        maxChunkRetries : 3,
        chunkRetryInterval : 5000,
        simultaneousUploads : 1,
        progressCallbacksInterval : 1,
        query: function(file) {
            return {
                user: window.user
            }
        }
    });

		$("input[name='uploadtarget']").click(function() {
    		var uploadmode = this.value;
			if (uploadmode==="java"){
			 	r.opts.target = "https://upload-flowjs-java.eu-gb.mybluemix.net/upload";
			 	r.opts.method = "octet";

			}
			if(uploadmode==="node"){
				r.opts.target = "https://upload-flowjs-node.eu-gb.mybluemix.net/upload";
			 	r.opts.method = "multipart";
			}
			console.log("target: " +r.opts.target+" - method: " +r.opts.method);

		});

    $('.flow-error').hide();
    // Flow.js isn't supported, fall back on a different method
    if (!r.support) {
        $('.flow-error').show();
        return;
    }

    var _id = "";

    r.assignDrop($('.flow-drop')[0]);
    r.assignBrowse($('.flow-browse')[0]);
    r.assignBrowse($('.flow-browse-folder')[0], true);
    r.assignBrowse($('.flow-browse-image')[0], false, false, {
        accept: 'image/*'
    });

    $('.flow-progress, .flow-list').hide();

    // Handle file add event
    r.on('fileAdded', function(file) {

        $(".list-group").loadTemplate($("#template"), {
            'file': "flow-file-" + file.uniqueIdentifier,
            'flow-file-name': file.name,
            'flow-file-size': readablizeBytes(file.size),
            'flow-file-download': 'https://upload-flowjs-node.eu-gb.mybluemix.net/download/' + file.uniqueIdentifier + "/user/" + user
        }, { append: true });

        var $self = $(".flow-file-" + file.uniqueIdentifier);

        $self.find('.flow-file-pause').on('click', function() {
            file.pause();
            $self.find('.flow-file-pause').hide();
            $self.find('.flow-file-resume').show();
        });
        $self.find('.flow-file-resume').on('click', function() {
            file.resume();
            $self.find('.flow-file-pause').show();
            $self.find('.flow-file-resume').hide();
        });
        $self.find('.flow-file-cancel').on('click', function() {
            file.cancel();
            $self.remove();
        });

        $self.find('.flow-file-pause').hide();
        $self.find('.flow-file-resume').hide();
        $self.find('.flow-file-download').hide();
    });

    r.on('filesSubmitted', function(files, event) {

        var promises = files.map(function(file) {

        	console.log("r.target: "+r.opts.target);
        	console.log("r.method: "+r.opts.method);
        	console.log("user: "+user);
        	console.log("filename: "+file.name);
        	console.log("uniqueid: "+file.uniqueIdentifier);
        	console.log("chunks: "+file.chunks.length);
            return $.ajax({
                type: "POST",
                url: "/prepare",
                //contentType: 'application/json; charset=utf-8',
                dataType: "json",
                data: {
                	"user": user,
                	"name": file.name,
                	"uniqueIdentifier": file.uniqueIdentifier,
                	"size": file.chunks.length
                }
            })
        })

        $.when.apply($, promises).done(function(response) {
        	console.log("scrittura db DONE");
        	_id = response.id;
                files.forEach(function(file){
                    var $self = $('.flow-file-' + file.uniqueIdentifier);
                    $self.find('.flow-file-pause').show();
                    $self.find('.flow-file-resume').show();
                })
            })
            .fail(function(reject) {
                var $self = $("#messages").loadTemplate($("#alert-template"));
                console.log("Qualcosa non e' andato a buon fine ...");
            });
    });

    r.on('complete', function() {
        // Hide pause/resume when the upload has completed
        $('.flow-progress .progress-resume-link, .flow-progress .progress-pause-link').hide();
    });

    r.on('fileSuccess', function(file, message) {
        $.ajax({
                type: "POST",
                url: "/confirm",
                //contentType: 'application/json; charset=utf-8',
                dataType: "json",
                data: {
                	 "user": user,
                	 "uniqueIdentifier": file.uniqueIdentifier,
                	 "_id": _id
                	}
            }).done(function() {
            	console.log("Update DONE");
                var $self = $('.flow-file-' + file.uniqueIdentifier);
                // Reflect that the file upload has completed
                $self.find('.flow-file-progress').text('(completed)');
                $self.find('.flow-file-pause, .flow-file-resume').remove();
                $self.find('.flow-file-download').attr('href', 'https://upload-flowjs-node.eu-gb.mybluemix.net/download/' + file.uniqueIdentifier + "/user/" + user).show();
                //$self.find('.flow-file-download').show();
            })
            .fail(function() {
                console.log("Qualcosa non e' andato a buon fine ...");
            });
    });

    r.on('fileError', function(file, message) {
        // Reflect that the file upload has resulted in error
        $('.flow-file-' + file.uniqueIdentifier + ' .flow-file-progress').html('(file could not be uploaded: ' + message + ')');
    });

    r.on('fileProgress', function(file) {
        // Handle progress for both the file and the overall upload
        var $self = $('.flow-file-' + file.uniqueIdentifier);

        $('.flow-file-' + file.uniqueIdentifier + ' .flow-file-progress')
            .html(Math.floor(file.progress() * 100) + '% ' +
                readablizeBytes(file.averageSpeed) + '/s ' +
                secondsToStr(file.timeRemaining()) + ' remaining');
        $self.find('.progress-bar').css({
             width: Math.floor(r.progress() * 100) + '%'
        });
    });

    r.on('uploadStart', function() {
        // Show pause, hide resume
        $('.flow-progress .progress-resume-link').hide();
        $('.flow-progress .progress-pause-link').show();
    });

    r.on('catchAll', function() {
        //console.log.apply(console, arguments);
    });

    window.r = {
        pause: function() {
            r.pause();
            // Show resume, hide pause
            $('.flow-file-resume').show();
            $('.flow-file-pause').hide();
            $('.flow-progress .progress-resume-link').show();
            $('.flow-progress .progress-pause-link').hide();
        },
        cancel: function() {
            r.cancel();
            $('.flow-file').remove();
        },
        upload: function() {
            $('.flow-file-pause').show();
            $('.flow-file-resume').hide();
            r.resume();
        },
        flow: r
    };

    $("#user").blur(function(event) {
        window.user = $("#user").val();
        if(window.user) {
          $("#uploadButton").attr("disabled", false);
        }else{
          $("#uploadButton").attr("disabled", true);
        }
    });

})();

function readablizeBytes(bytes) {
    var s = ['bytes', 'kB', 'MB', 'GB', 'TB', 'PB'];
    var e = Math.floor(Math.log(bytes) / Math.log(1024));
    return (bytes / Math.pow(1024, e)).toFixed(2) + " " + s[e];
}

function secondsToStr(temp) {
    function numberEnding(number) {
        return (number > 1) ? 's' : '';
    }
    var years = Math.floor(temp / 31536000);
    if (years) {
        return years + ' year' + numberEnding(years);
    }
    var days = Math.floor((temp %= 31536000) / 86400);
    if (days) {
        return days + ' day' + numberEnding(days);
    }
    var hours = Math.floor((temp %= 86400) / 3600);
    if (hours) {
        return hours + ' hour' + numberEnding(hours);
    }
    var minutes = Math.floor((temp %= 3600) / 60);
    if (minutes) {
        return minutes + ' minute' + numberEnding(minutes);
    }
    var seconds = temp % 60;
    return seconds + ' second' + numberEnding(seconds);
}


text:
/**
 * This package provides all necessary classes for the TUS - Upload Client.
 */
package io.tus.java.client;