text:
package ai.verta.modeldb;

import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.Assume.assumeTrue;

import ai.verta.artifactstore.DeleteArtifact;
import ai.verta.artifactstore.GetArtifact;
import ai.verta.artifactstore.StoreArtifact;
import ai.verta.artifactstore.StoreArtifactWithStream;
import ai.verta.modeldb.authservice.*;
import com.google.api.client.util.IOUtils;
import com.google.protobuf.ByteString;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.runners.MethodSorters;

@RunWith(JUnit4.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class ArtifactStoreTest extends TestsInit {

  private static final Logger LOGGER = Logger.getLogger(ArtifactStoreTest.class.getName());

  @Test
  public void storeArtifactOnCloudTest() {
    LOGGER.info("store artifact on cloud test start................................");

    try {
      StoreArtifact storeArtifact =
          StoreArtifact.newBuilder()
              .setKey("verta_logo.png")
              .setPath(
                  "https://www.verta.ai/static/logo-landing-424af27a5fc184c64225f604232db39e.png")
              .build();

      StoreArtifact.Response response = artifactStoreBlockingStub.storeArtifact(storeArtifact);

      String cloudFileKey = response.getArtifactStoreKey();
      String cloudFilePath = response.getArtifactStorePath();
      LOGGER.log(
          Level.INFO,
          "StoreArtifact.Response : \n cloudFileKey - "
              + cloudFileKey
              + " \n cloudFilePath - "
              + cloudFilePath);

      assumeTrue(cloudFileKey != null && !cloudFileKey.isEmpty());
      assumeTrue(cloudFilePath != null && !cloudFilePath.isEmpty());

      DeleteArtifact deleteArtifact = DeleteArtifact.newBuilder().setKey(cloudFileKey).build();
      DeleteArtifact.Response deleteArtifactResponse =
          artifactStoreBlockingStub.deleteArtifact(deleteArtifact);
      assertTrue(deleteArtifactResponse.getStatus());

    } catch (StatusRuntimeException e) {
      Status status = Status.fromThrowable(e);
      LOGGER.warning(
          "Error Code : " + status.getCode() + " Description : " + status.getDescription());
      fail();
    }

    LOGGER.info("store artifact on cloud test stop................................");
  }

  @Test
  public void storeStreamArtifactOnCloudTest() throws IOException {
    LOGGER.info("store stream artifact on cloud test start................................");

    try {
      URL url =
          new URL("https://www.verta.ai/static/logo-landing-424af27a5fc184c64225f604232db39e.png");
      HttpURLConnection connection = (HttpURLConnection) url.openConnection();
      InputStream inputStream = connection.getInputStream();

      StoreArtifactWithStream storeArtifactRequest =
          StoreArtifactWithStream.newBuilder()
              .setKey("verta_logo_using_stream.png")
              .setClientFile(ByteString.readFrom(inputStream))
              .build();
      inputStream.close();

      LOGGER.info("StoreStreamArtifact Request called");

      StoreArtifactWithStream.Response response =
          artifactStoreBlockingStub.storeArtifactWithStream(storeArtifactRequest);

      String cloudFileKey = response.getCloudFileKey();
      String cloudFilePath = response.getCloudFilePath();
      LOGGER.log(
          Level.INFO,
          "StoreStreamArtifact.Response : \n cloudFileKey - "
              + cloudFileKey
              + " \n cloudFilePath - "
              + cloudFilePath);

      assumeTrue(cloudFileKey != null && !cloudFileKey.isEmpty());
      assumeTrue(cloudFilePath != null && !cloudFilePath.isEmpty());

      DeleteArtifact deleteArtifact = DeleteArtifact.newBuilder().setKey(cloudFileKey).build();
      DeleteArtifact.Response deleteArtifactResponse =
          artifactStoreBlockingStub.deleteArtifact(deleteArtifact);
      assertTrue(deleteArtifactResponse.getStatus());

    } catch (StatusRuntimeException e) {
      Status status = Status.fromThrowable(e);
      LOGGER.warning(
          "Error Code : " + status.getCode() + " Description : " + status.getDescription());
      fail();
    }

    LOGGER.info("store stream artifact on cloud test stop................................");
  }

  @Test
  public void getArtifactFromCloudTest() {
    LOGGER.info("get artifact from cloud test start................................");

    try {
      StoreArtifact storeArtifact =
          StoreArtifact.newBuilder()
              .setKey("verta_logo.png")
              .setPath(
                  "https://www.verta.ai/static/logo-landing-424af27a5fc184c64225f604232db39e.png")
              .build();

      StoreArtifact.Response response = artifactStoreBlockingStub.storeArtifact(storeArtifact);

      String cloudFileKey = response.getArtifactStoreKey();
      String cloudFilePath = response.getArtifactStorePath();
      LOGGER.log(
          Level.INFO,
          "StoreArtifact.Response : \n cloudFileKey - "
              + cloudFileKey
              + " \n cloudFilePath - "
              + cloudFilePath);

      assumeTrue(cloudFileKey != null && !cloudFileKey.isEmpty());
      assumeTrue(cloudFilePath != null && !cloudFilePath.isEmpty());

      GetArtifact getArtifactRequest = GetArtifact.newBuilder().setKey(cloudFileKey).build();
      GetArtifact.Response getArtifactResponse =
          artifactStoreBlockingStub.getArtifact(getArtifactRequest);
      ByteString responseByteString = getArtifactResponse.getContents();
      InputStream inputStream = responseByteString.newInput();

      String rootPath = System.getProperty("user.dir");
      FileOutputStream fileOutputStream =
          new FileOutputStream(new File(rootPath + File.separator + cloudFileKey));
      IOUtils.copy(inputStream, fileOutputStream);
      fileOutputStream.close();
      inputStream.close();

      File downloadedFile = new File(rootPath + File.separator + cloudFileKey);
      if (!downloadedFile.exists()) {
        fail("File not fount at download destination");
      }
      downloadedFile.delete();

      DeleteArtifact deleteArtifact = DeleteArtifact.newBuilder().setKey(cloudFileKey).build();
      DeleteArtifact.Response deleteArtifactResponse =
          artifactStoreBlockingStub.deleteArtifact(deleteArtifact);
      assertTrue(deleteArtifactResponse.getStatus());

    } catch (Exception e) {
      e.printStackTrace();
      Status status = Status.fromThrowable(e);
      LOGGER.warning(
          "Error Code : " + status.getCode() + " Description : " + status.getDescription());
      fail();
    }

    LOGGER.info("get artifact from cloud test stop................................");
  }
}

redpajama_set_name: RedPajamaGithub


text:
<?php
/*
This script generates
the list of semantic relations for nouns, verbs, adjectives, adverbs
Only for Russian entries.
 * Restrictions:
 * - synset size >= 3
 * - skip multiword expressions

For example,
in the article "tree" there are
 * "sapling, seedling" in Synonyms section;
 * "plant" in Hyperonyms section;
 * "oak, birch, maple, fir, pine" in Hyponyms section

then the following line will be generated:

1) first file with only synonyms
tree sapling seedling

2) second file with all relations
tree sapling seedling plant oak birch maple fir pine

 */

require '../../../../vendor/autoload.php';

use piwidict\Piwidict;
use piwidict\sql\{TLang, TPage, TPOS, TRelationType};
use piwidict\widget\WForm;

require '../../config_examples.php';
require '../../config_password.php';

include(LIB_DIR."header.php");

// $pw = new Piwidict();
Piwidict::setDatabaseConnection($config['hostname'], $config['user_login'], $config['user_password'], $config['dbname']);
$link_db = Piwidict::getDatabaseConnection();

$wikt_lang = "ru"; // Russian language is the main language in ruwikt (Russian Wiktionary)
Piwidict::setWiktLang ($wikt_lang);

//$pos_name = "adjective";
$pos_name = "noun";
$lang_id = TLang::getIDByLangCode("ru");
$pos_id = TPOS::getIDByName($pos_name);
$syn_id = TRelationType::getIDByName("synonyms");

$fh1 = fopen('synset_synonyms_only_'.$pos_name.'.txt','w');
$fh2 = fopen('synset_all_relations_'.$pos_name.'.txt','w');

$query = "SELECT page_title as first_word, meaning.id as meaning_id
          FROM lang_pos, meaning, page
          WHERE lang_pos.id = meaning.lang_pos_id
            AND page.id = lang_pos.page_id
            AND page_title NOT LIKE '% %'
            AND lang_id = $lang_id
            AND pos_id=$pos_id
          ORDER BY page_title";

$result_meaning = $link_db -> query_e($query,"Query failed in file ".__FILE__.", string ".__LINE__."");

while ($row = $result_meaning -> fetch_object()) {

    $query = "SELECT wiki_text.text as relation_word, relation_type_id
              FROM wiki_text, relation
              WHERE relation.wiki_text_id=wiki_text.id
                AND wiki_text.text NOT LIKE '% %'
                AND relation.meaning_id = ".$row->meaning_id.
            " ORDER BY wiki_text.text";

    $result_relation = $link_db -> query_e($query,"Query failed in file ".__FILE__.", string ".__LINE__."");

    $num = $link_db -> query_count($result_relation);

    if ($num > 1) {
        $synonyms = array();
        fwrite($fh2, $row->first_word);

        while ($row_relation = $result_relation -> fetch_object()) {
            fwrite($fh2, ' '. $row_relation->relation_word);
            if ($row_relation->relation_type_id == $syn_id)
                $synonyms[] = $row_relation->relation_word;
        }
        fwrite($fh2, "\n");
        if (sizeof($synonyms)>1)
            fwrite($fh1, $row->first_word. ' '. join(' ', $synonyms)."\n");
    }
}

fclose($fh1);
fclose($fh2);
include(LIB_DIR."footer.php");
?>

done.


text:
/*global define:false*/
define(['pluginBaseView', 'underscore', 'api', 'contentTypeWorker', 'jquery',
    'masseuse', 'mixins/itemSelectModal', 'mixins/buildNodeRadioList'],
    function (PluginBaseView, _, Api, contentTypeWorker, $,
              masseuse, itemSelectModal, buildNodeRadioList) {

        'use strict';

        return PluginBaseView.extend({
            afterRender : afterRender,
            setAvailableContentTypes : setAvailableContentTypes,
            fireSelectContentModal : fireSelectContentModal,
            selectDefaultNode : selectDefaultNode
        })
            .extend(itemSelectModal)
            .extend(buildNodeRadioList);

        function afterRender() {
            if(this.model.get('inSetup')) {
                $.when(this.model.get('childNodesDeep').fetch(), _getAvailableContentTypes.call(this))
                    .done(
                        this.buildNodeRadioList.bind(this, this.$('#nodeRadioList'), this.model.get('childNodesDeep')),
                        _getSelectedNode.bind(this)
                    );
            } else {
                _toggleLoadingSpinner.call(this);
                _getSelectedContent.call(this)
                    .done(_toggleLoadingSpinner.bind(this));

                this.model.on('change:value', _getSelectedContent.bind(this));
            }

            this.parent && this.parent.resortMulti && this.parent.resortMulti();
        }

        function _getSelectedContent() {
            var contentId = this.model.get('value'),
                $deferred = new $.Deferred();

            if (contentId) {
                _getContentDetails.call(this, contentId)
                    .done(_setSelectedContent.bind(this), $deferred.resolve);
            } else {
                $deferred.resolve();
            }

            return $deferred.promise();
        }

        function _getContentDetails(contentId) {
            return Api.getContentDetail(contentId);
        }

        function _setSelectedContent(contentDetails) {
            this.model.set('contentDetails', contentDetails);
        }

        function _getSelectedNode() {
            var defaultNode = this.model.get('options.defaultNode'),
                $defaultNodeRadio = this.$('#selectDefaultNode').find('#'+ defaultNode);

            $defaultNodeRadio.prop('checked', true);

            this.selectDefaultNode();
        }

        function _getAvailableContentTypes() {
            var $deferred = new $.Deferred();

            contentTypeWorker.getAvailableContentTypes()
                .done(_setPreSelectedTypes.bind(this, $deferred));

            return $deferred.promise();
        }

        function _setPreSelectedTypes($deferred, availableTypes) {
            var allowedTypes = this.model.get('options.allowedTypes');

            _.each(availableTypes, function(type) {
                if(_.contains(allowedTypes, type._id)) {
                    type.checked = true;
                } else {
                    type.checked = false;
                }
            });

            this.model.set('availableTypes', availableTypes);
            $deferred.resolve();
        }

        function setAvailableContentTypes() {
            var availableTypes = this.model.get('availableTypes'),
                checkedTypes = _.pluck(_.where(availableTypes, { checked : true }), '_id');

            this.model.set('options.allowedTypes', checkedTypes);
        }

        function selectDefaultNode() {
            var $selectedNode = this.$('#selectDefaultNode').find('input:radio[name="nodeRadio"]:checked'),
                selectedNodeId = $selectedNode.val(),
                selectedNodeLabel = $selectedNode.attr('data-label');

            this.model.set('selectedNodeLabel', selectedNodeLabel);
            this.model.set('options.defaultNode', selectedNodeId);

        }

        function fireSelectContentModal() {
            _startModalView.call(this)
                .done(_contentReferenceSelected.bind(this));
        }

        function _contentReferenceSelected(selectedContentId) {
            this.model.set('value', selectedContentId);
        }

        function _startModalView() {
            var value = this.model.get('value'),
                nodeId = this.model.get('nodeId'),
                allowedTypes = this.model.get('options.allowedTypes');

            return this.fireContentSelectModal(value, nodeId, allowedTypes);
        }

        function _toggleLoadingSpinner() {
            this.model.toggle('loading');
        }

    });


text:
<?php

namespace Atlantis\Properties;

trait Content {
/*//
provide a content property to any object that requests to have one with get,
set, and an actionable method.
//*/

	protected
	$Content = '';

	////////
	////////

	public function
	GetContent():
	String {

		return $this->Content;
	}

	public function
	HasContent():
	Bool {

		return (is_string($this->Content) && strlen($this->Content));
	}

	public function
	SetContent(String $Content):
	self {

		$this->Content = $Content;
		return $this;
	}

	////////
	////////

	public function
	Content(?String $Content=NULL) {

		if($Content === NULL)
		return $this->GetContent();

		else
		return $this->SetContent($Content);
	}

}


text:
<?php
/* @var $this UsersController */
/* @var $model Users */

$this->breadcrumbs=array(
	'Users'=>array('index'),
	'Manage',
);

$this->menu=array(
	array('label'=>'Create Users', 'url'=>array('create')),
);
?>

Manage Users

You may optionally enter a comparison operator (<, <=, >, >=, <>
or =) at the beginning of each of your search values to specify how the comparison should be done.

<?php $this->widget('zii.widgets.grid.CGridView', array(
	'id'=>'users-grid',
	'itemsCssClass'=>'table table-striped',
	'pager'=>array('htmlOptions'=>array('class'=>'pagination')),
	'dataProvider'=>$model->search(),
	'filter'=>$model,
	'columns'=>array(
		'id',
		'username',
		'password',
		'email',
		'birthday',
		'name',
		/*
		'countries_id',
		'cities_id',
		'status',
		*/
		array(
			'class'=>'CButtonColumn',
		),
	),
)); ?>


text:
/*	$NetBSD: ydsvar.h,v 1.11 2011/11/23 23:07:36 jmcneill Exp $	*/

/*
 * Copyright (c) 2000, 2001 Kazuki Sakamoto and Minoura Makoto.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef _DEV_PCI_YDSVAR_H_
#define	_DEV_PCI_YDSVAR_H_

#define N_PLAY_SLOTS		2		/* We use only 2 (R and L) */
#define	N_PLAY_SLOT_CTRL	2
#define WORK_SIZE		0x0400

/*
 * softc
 */
struct yds_dma {
	bus_dmamap_t map;
	void *addr;			/* VA */
	bus_dma_segment_t segs[1];
	int nsegs;
	size_t size;
	struct yds_dma *next;
};

struct yds_codec_softc {
	struct yds_softc *sc;
	int id;
	int status_data;
	int status_addr;
	struct ac97_host_if host_if;
	struct ac97_codec_if *codec_if;
};

struct yds_softc {
	device_t		sc_dev;
	kmutex_t		sc_lock;
	kmutex_t		sc_intr_lock;
	pci_chipset_tag_t	sc_pc;
	pcitag_t		sc_pcitag;
	pcireg_t		sc_id;
	int			sc_revision;
	void			*sc_ih;		/* interrupt vectoring */
	bus_space_tag_t		memt;
	bus_space_handle_t	memh;
	bus_dma_tag_t		sc_dmatag;	/* DMA tag */
	u_int			sc_flags;

	struct yds_codec_softc	sc_codec[2];	/* Primary/Secondary AC97 */

	struct yds_dma		*sc_dmas;	/* List of DMA handles */

	/*
	 * Play/record status
	 */
	struct {
		void		(*intr)(void *); /* rint/pint */
		void		*intr_arg;	/* arg for intr */
		u_int		offset;		/* filled up to here */
		u_int		blksize;
		u_int		factor;		/* byte per sample */
		u_int		length;		/* ring buffer length */
		struct yds_dma	*dma;		/* DMA handle for ring buf */
	} sc_play, sc_rec;

	/*
	 * DSP control data
	 *
	 * Work space, play control data table, play slot control data,
	 * rec slot control data and effect slot control data are
	 * stored in a single memory segment in this order.
	 */
	struct yds_dma			sc_ctrldata;
	/* KVA and offset in buffer of play ctrl data tbl */
	uint32_t			*ptbl;
	off_t				ptbloff;
	/* KVA and offset in buffer of rec slot ctrl data */
	struct rec_slot_ctrl_bank	*rbank;
	off_t				rbankoff;
	/* Array of KVA pointers and offset of play slot control data */
	struct play_slot_ctrl_bank	*pbankp[N_PLAY_SLOT_CTRL_BANK
					       *N_PLAY_SLOTS];
	off_t				pbankoff;

	/*
	 * Legacy support
	 */
	bus_space_tag_t		sc_legacy_iot;
	bus_space_handle_t	sc_opl_ioh;
	device_t 		sc_mpu;
	bus_space_handle_t	sc_mpu_ioh;

	struct audio_encoding_set *sc_encodings;

	/*
	 * Power management
	 */
	struct pci_conf_state	sc_pciconf;
	pcireg_t		sc_dsctrl;
	pcireg_t		sc_legacy;
	pcireg_t		sc_ba[2];
};
#define sc_opl_iot	sc_legacy_iot
#define sc_mpu_iot	sc_legacy_iot

#endif /* _DEV_PCI_YDSVAR_H_ */


text:
import {config} from '../core/utils';
import * as Sequelize from "sequelize";
import Q = require('q');
import {IEntityService} from '../core/interfaces/entity-service';
import {MetaUtils} from "../core/metadata/utils";
import {pathRepoMap} from '../core/dynamic/model-entity';
import {QueryOptions} from '../core/interfaces/queryOptions';

import {Decorators as CoreDecorators} from '../core/constants';
//import {pathRepoMap} from './schema';
import * as schema  from "./schema";
import * as Enumerable from 'linq';

class SequelizeService implements IEntityService {
    private sequelize: any;
    private _schemaCollection = {};
    private _relationCollection = [];
    constructor() {

    }

    init(force?: boolean): Promise<any> {
        force = force || false;
        return this.sequelize.sync({ force: force, logging: true });
    }

    connect() {
        if (config().SqlConfig.isSqlEnabled == false)
            return;
        this.sequelize = new Sequelize(config().SqlConfig.database,
            config().SqlConfig.username,
            config().SqlConfig.password,
            config().SqlConfig.sequlizeSetting);
    }

    getSqlContext(): any {
        return this.sequelize;
    }

    getCustomResult(databaseName: string, query) {
        if (config().SqlConfig.isSqlEnabled == false)
            return;
        var dynamicSequelize = new Sequelize(databaseName,
            config().SqlConfig.username,
            config().SqlConfig.password,
            config().SqlConfig.sequlizeSetting);
        return dynamicSequelize.query(query);
    }

    addScheam(name: string, schema: any, detail: any) {
        var newSchema = this.sequelize.define(name, schema, detail);
        this._schemaCollection[name] = newSchema;
        return newSchema;
    }

    addRelationInSchema(fromSchema: any, toSchema: any, relationType: string, relationName: string, path: string) {
        if (relationType == CoreDecorators.ONETOMANY)
            fromSchema.hasMany(toSchema, { as: path });
        if (relationType == CoreDecorators.MANYTOONE)
            fromSchema.belongsTo(toSchema, { as: path });
        if (relationType == CoreDecorators.ONETOONE)
            fromSchema.has(toSchema, { as: path });

        let relationToDictionary: any = {};
        relationToDictionary["relation"] = relationName;
        relationToDictionary.fromSchema = fromSchema;
        relationToDictionary.toSchema = toSchema;
        relationToDictionary.path = path;

        this._relationCollection.push(relationToDictionary);
    }

    getModel(repoPath: string) {
        try {
            var schemaNamefromPathRepomap = pathRepoMap[repoPath].schemaName;
            return this._schemaCollection[schemaNamefromPathRepomap];
        } catch (e) {
            throw e;
        }
    }

    bulkPost(repoPath: string, objArr: Array<any>): Q.Promise<any> {
        return this.getModel(repoPath).bulkCreate(objArr);
    }

    bulkPutMany(repoPath: string, objIds: Array<any>, obj: any): Q.Promise<any> {
        return null;
    }

    bulkDel(repoPath: string, objArr: Array<any>): Q.Promise<any> {
        return this.getModel(repoPath).destroy({ where: { id: objArr } });
    }

    bulkPut(repoPath: string, objArr: Array<any>): Q.Promise<any> {
        return this.getModel(repoPath).bulkUpdate(objArr);
    }

    findAll(repoPath: string): Q.Promise<any> {
        return this.getModel(repoPath).findAll().then(result => {
            if (!result) return null;
            var finalOutput = Enumerable.from(result).select((x:any) => x.dataValues).toArray();// result.forEach(x => x.dataValues).toArray();
            return finalOutput;
        });
    }

    findWhere(repoPath: string, query, selectedFields?: Array<string>, queryOptions?: QueryOptions): Q.Promise<any> {
        return this.getModel(repoPath).findAll(query).then(result => {
            return result.dataValues;
        });
    }

    findOne(repoPath: string, id): Q.Promise<any> {

        let schemaModel = this.getModel(repoPath);
        let primaryKey = schemaModel.primaryKeyAttribute;
        var cond = {};
        cond[primaryKey] = id;
        var self = this;
        return schemaModel.find({ include: [{ all: true }], where: cond }).then(result => {
            let model = result.dataValues;
            self.getAssociationForSchema(result, schemaModel);
            return result.dataValues;
        }
        );
    }

    findByField(repoPath: string, fieldName, value): Q.Promise<any> {
        return this.getModel(repoPath).find({ where: { fieldName: value } });
    }

    findMany(repoPath: string, ids: Array<any>) {
        return this.getModel(repoPath).findAll({ where: { id: ids } });
    }

    findChild(repoPath: string, id, prop): Q.Promise<any> {
        return this.getModel(repoPath).find({
            where: { id: id },
            include: [
                { model: this.getModel(prop), as: prop }
            ]
        }).then(
            function (entity) {
                return entity[prop];
            });
    }

    /**
     * case 1: all new - create main item and child separately and embed if true
     * case 2: some new, some update - create main item and update/create child accordingly and embed if true
     * @param obj
     */
    post(repoPath: string, obj: any): Q.Promise<any> {
        return this.getModel(repoPath).create(obj);
    }

    put(repoPath: string, id: any, obj: any): Q.Promise<any> {
        return this.getModel(repoPath).update(obj, { where: { id: id } });
    }

    del(repoPath: string, id: any): Q.Promise<any> {
        return this.getModel(repoPath).destroy({ where: { id: id } });
    }

    patch(repoPath: string, id: any, obj): Q.Promise<any> {
        return this.getModel(repoPath).update(obj, { where: { id: id } });
    }

    private getAssociationForSchema(model: any, schema: any) {
        var asyncCalls = [];
        Enumerable.from(this._relationCollection)
            .where(relationSchema => relationSchema.fromSchema == schema).forEach(relation1 => {
                model.dataValues[relation1.path] = model[relation1.toSchema.name + "s"];
            });
        //return Q.allSettled(asyncCalls).then(res => {
        //    return model.dataValues;
        //});
    }

}
export var sequelizeService = new SequelizeService();
//export var connect = sequelizeService.connect;


text:
using System;
using System.Globalization;
using System.Text;
using System.Security.Cryptography;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using MobicomLibrary;

namespace Uniplat.Classes
{
    public class TrustAllCertificatePolicy : ICertificatePolicy
    {
        public bool CheckValidationResult(ServicePoint sp, X509Certificate cert, WebRequest req, int problem)
        {
            return true;
        }
    }

    public class ClPayment
    {

        private Guid _mts
        {
            get
            {
                return new Guid("46C0E592-917B-4663-83DB-8A9F13C19BCE");
            }
        }
        private Guid _beeline
        {
            get
            {
                return new Guid("1F2D6739-B5C1-4096-B7A9-CAF4AC454058");
            }
        }

        public int SendPaymentToMobicom(string phoneNumber, long moneyCount, Guid operatorBrand)
        {
            try
            {
                // Отключаем проверку сертификатов путем замены класса проверки сертификатов на пустой
#pragma warning disable 612,618
                ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy();
#pragma warning restore 612,618

                // Создаем клиентское подключение к сервису Мобиком
                var cc = new mobicomTypeClient("BasicHttpBinding_MobicomService");

                // Основные параметры подключения
                // ****************************************************************
                var a = new Agregator {id = 29};
                var m = new Merchant {id = 6889};
                const string sVersion = "1.0";
                const string sPassword = "Fdk5637Gr";

                // Переменные параметры подключения
                // ****************************************************************
                var p = new Phone {number = phoneNumber};
                //p.provider = 3; // 1 — «Вымпелком», 2 — «Мобильные Телесистемы», 3 — «Мегафон»

                var c = new Client {Phone = p};

                var pt = new Payment {currency = 643, amount = moneyCount};

                var ms = new Message
                    {
                        bill = DateTime.Now.Ticks.ToString(CultureInfo.InvariantCulture).Substring(1, 10),
                        comment = "Test"
                    };

                var o = new Owner { id = Guid.NewGuid().ToString().Replace("-", "") }; // Идентификатор транзакции, заданный Агрегатором. (Регулярное выражение для проверки: ^[A-Za-z0-9]+$ ). Этот идентификатор должен быть уникальным в течении всего периода взаимодействия с системой Mobicom, причём в пределах обоих типов сообщений: MCStartReq и MCStartExReq.

                // ****************************************************************

                //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
                // Создаем и инициализируем объект MobicomStartRequest для быстрой регистрации запроса на стороне Мобиком
                //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
                var r = new MobicomStartRequest
                    {
                        Agregator = a,
                        Merchant = m,
                        Client = c,
                        version = sVersion,
                        Owner = o,
                        Payment = pt,
                        Message = ms
                    };

                // Генерируем Хэш-Код для  MobicomStartExpressRequest (1)Owner.id, 2)Client.Phone.number, 3)Client.Phone.provider, 4)Payment.amount, 5)Payment.currency, 6)Message.bill, 7)Message.comment, 8)секретный пароль Агрегатора.)
                string ss = r.Owner.id + r.Client.Phone.number + r.Client.Phone.provider.ToString() + r.Payment.amount.ToString() + r.Payment.currency.ToString() + r.Message.bill + r.Message.comment + sPassword;
                r.hash = GetHash(ss);

                // Регистрируем запрос в Мобиком и получаем статус выполнения запроса.
                MobicomStartResponse resp = cc.MobicomStartRequestOperation(r);
                //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
                if (resp.Result.code != null) return resp.Result.code.Value;
            }

            catch
            {
                return -1;
            }

            return -1;
        }

        private string GetHash(string sStr)
        {
            //byte[] data = Encoding.ASCII.GetBytes(sStr);
            byte[] data = Encoding.GetEncoding(1251).GetBytes(sStr);

            // экземпляр MD5
            MD5 md5 = MD5.Create();

            // получаю хеш
            byte[] result = md5.ComputeHash(data);

            return Convert.ToBase64String(result);
        }
    }
}


text:
# Frequently Asked Questions

- [What are deployment modes?](#what-are-deployment-modes-)
- [Can exposed API be asynchronous?](#can-exposed-api-be-asynchronous-)
- [Are there limitations on exposed API signatures?](#are-there-limitations-on-exposed-api-signatures-)
- [Where to put asynchronous initialization?](#where-to-put-asynchronous-initialization-)
- [Can initialization code be configured?](#can-initialization-code-be-configured-)
- [How can service definition be more modular?](#how-can-service-definition-be-more-modular-)
- [How can initialisation be shared by different groups?](#how-can-initialisation-be-shared-by-different-groups-)
- [How could input parameters be validated?](#how-could-input-parameters-be-validated-)
- [How could results be validated](#how-could-results-be-validated-)
- [Is Swagger/OpenAPI supported?](#is-swagger-openapi-supported-)
- [Can endpoint method/headers/query be configured?](#can-endpoint-method-headers-query-be-configured-)

## What are deployment modes?

µServices based on mini-service could be deployed either:
- locally: runs on the same nodejs process as the caller code
  ```js
  const {getClient} = require('mini-service')

  // define a service
  const calc = getClient({
    name: 'calc',
    version: '1.0.0',
    init: () => ({
      add: (a, b) => a + b
    })
  })

  await calc.init()

  // invoke exposed api as async function
  const sum = await calc.add(10 + 5)
  ```

- remotely: runs as a dedicated HTTP server
  ```js
  // server.js
  const {startServer} = require('mini-service')

  // define a service, start Http server
  startServer({
    name: 'calc',
    version: '1.0.0',
    init: () => ({
      add: (a, b) => a + b
    })
  })
  ```

  ```js
  // client.js
  const {getClient} = require('mini-service')

  // will connect to server on demand
  const calc = getClient({
    remote: 'http://localhost:3000'
  })

  // invoke exposed api as async function
  const sum = await calc.add(10 + 5)
  ```

No need to add the service code as a dependency when using `getClient()` with remote url/

## Can exposed API be asynchronous?

Yes, by using Promises:

```js
const {startService} = require('mini-service')

startService({
  name: 'calc',
  version: '1.0.0',
  init: () => ({
    add: (a, b) => a + b,                    // synchronous API,
    subtract: async (a, b) => a - b          // asynchronous API, async/await syntax
    divide: (a, b) => Promise.resolve(a / b) // asynchronous API, promise-based
  })
})
```

## Are there limitations on exposed API signatures?

Despite all our efforts, yes. Hopefully main cases are covered.

Because parameters will be stringified when sent to server:
- they could be `null` or `undefined`
- they could be booleans, numbers, strings, arrays, and plain object (contains only properties of the previous types)
- they could be of other types (Date, Error, RegExp, custom classes...) but will boils down to the output of their `toString()` method
- they could be `Buffer` or `Stream` (see bellow). All paremeter but the first will be ignored

In particular, don't use functions as parameters.

Same limitations applies to API returned object.

You can use destructuring, rest parameters and even default values:
```js
async withExoticParameters ([a, b], {c: {d}} = {}, ...other) {
  return [a, b, d, ...other]
}
```

To use `Buffer` input parameter:
- decorate API with `hasBufferInput`
- use only one parameter (others will be set to `undefined`)
    ```js
    const api = {
      async bufferHandling (buffer) {
        assert(Buffer.isBuffer(buffer))
        return Buffer.concat([buffer, new Uint8Array([3, 4])])
      }
    }
    // decorate
    apis.bufferHandling.hasBufferInput = true
    ```

To use `Stream` input parameter:
- decorate API with `hasStreamInput`
- use only one parameter (others will be set to `undefined`)
    ```js
    const api = {
      async streamHandling (stream) {
        assert(stream instanceof Readable)
        const prefix = new BufferList()
        prefix.append('here is a prefix -- ', 'utf8')
        return multistream([prefix, stream])
      }
    }
    // decorate
    apis.streamHandling.hasStreamInput = true
    ```

You can return `Stream` and `Buffer` without any decoration, but don't nest them in objects (they will be stringified).

## Where to put asynchronous initialization?

To serve this purpose, the `init()` function can be either synchronous or return a Promise.

```js
const {promisify} = require('util')
const readFile = promisify(require('readFile').readFile)
const {startService} = require('mini-service')

startService({
  name: 'async-init',
  version: '1.0.0',
  init: async () => {
    // let's say we need to read a configuration file...
    const content = await readFile('whatever.html')
    return {
      // exposed API list
    }
  }
})
```

Rejecting the `init()` promise will prevent server to start.

## Can initialization code be configured?

`init()` functions are invoked with a single Object parameter, populated with values from the service descriptor.

```js
const {promisify} = require('util')
const readFile = promisify(require('readFile').readFile)
const {startService} = require('mini-service')

const config = {
  filePath: 'whatever.html'
}

startService({
  name: 'configurable-init'
  version: '1.0.0',
  // single parameter is the service definition itself
  init: async ({filePath}) => {
    const content = await readFile(filePath)
    return {
      // exposed API list
    }
  },
  // all keys in the service definition will be passed to init()
  ...config
})
```

If you use [API groups](#how-can-service-definition-be-more-modular), each group has its own configuration object stored in `groupOpts[group.name]`.

## How can service definition be more modular?

Service definition object tend to grow quickly.
API groups is how mini-service makes the code more modular.

This big service definition:

```js
const {startService} = require('mini-service')

startService({
  name: 'monolitic-service',
  version: '1.0.0',
  init: () => ({
    api1: () => {/* ... */},
    api2: () => {/* ... */},
    api3: () => {/* ... */},
    api4: () => {/* ... */},
    api5: () => {/* ... */}
  })
})
```

can be turned to different groups:

```js
// server.js
const {startService} = require('mini-service')

startService({
  name: 'modular-service',
  version: '1.0.0',
  groups: [
    require('./api/group1'),
    require('./api/group2')
  ],
  groupOpts: {
    group1: {/* for group 'group1' */},
    group2: {/* for group 'group2' */}
  }
})
```

```js
// api/group1.js
module.exports = {
  // must be a valid JS identifier
  name: 'group1',
  // opts comes from groupOpts[group1]
  init: opts => ({
    api1: () => {/* ... */},
    api2: () => {/* ... */}
  })
}
```

```js
// api/group2.js
module.exports = {
  name: 'group2',
  // opts comes from groupOpts[group2]
  init: opts => ({
    api3: () => {/* ... */},
    api4: () => {/* ... */},
    api5: () => {/* ... */}
  })
}
```

Please note that groups are initialized **sequentially**, following the declaration order.

## How can initialisation be shared by different groups?

Services are initialized sequentially.
One can use orderring to perform shared initialization.

```js
// server.js
const {startService} = require('mini-service')

let shared

startService({
  name: 'modular-configurable-service',
  version: '1.0.0',
  groups: [{
    name: 'global-init',
    init: obj => {
      // initialized shared items
      shared = { /* ... */ }
      // doesn't have to expose any API
    }
  }, {
    name: 'group1',
    // pass your shared object to your init method, as well as other options
    init: opts => require('./api/group1')(shared, opts)
  ],
  groupOpts: {
    shared: {/* for group 'shared' */}
    group1: {/* for group 'group1' */}
  }
})
```

```js
// api/group1.js
module.exports = (shared, opts) {
  // initialization code, can use shared items
  return {/* exposed APIs */}
}
```

## How could input parameters be validated?

As parameters validation is a common pattern (syntactic validation), mini-service supports it out of the box.
Parameters of exposed API could be validated with [Joi](https://github.com/hapijs/joi/blob/master/API.md).

Assign an array of *validation schemas* to the `validate` property of an exposed API.
Each schema will validated a given parameter (order matters).

```js
const Joi = require('joi')
const {startService} = require('mini-service')

startService({
  name: 'validate-inputs',
  version: '1.0.0',
  init: () => {
    // declare your API
    const add = (a, b) => a + b
    // attached a schema for each parameter in an array
    add.validate = [
      Joi.Number().required(), // a
      Joi.Number().required() // b, example used in Swagger documentation
    ]
    return {add}
  }
})
```

Prior to any invokation of the API, incoming parameters will be matched against the validation schema.
The invokation will fail with a 400 error (Bad Request) if they don't comply.

## How could results be validated?

Although less common, returned results can be validated against a [Joi](https://github.com/hapijs/joi/blob/master/API.md) schema by assigning to the expose API:
- a *validation schemas* to the `responseSchema`.
- `true` to `validateResponse` property.

Ommitting `validateResponse` property (or setting a falsy value) will disable result validation.

Results that don't match response schema will trigger a 512 `Bad Response` error.

```js
const Joi = require('joi')
const {startService} = require('mini-service')

startService({
  name: 'validate-results',
  version: '1.0.0',
  init: () => {
    // declare your API
    const add = (a, b) => a + b
    // adds output documentation & validation
    add.responseSchema = Joi.number().required()
    add.validateResponse = true
    return {add}
  }
})
```

## Is Swagger/OpenAPI supported?

Yes, but is disabled by default. It can only be used through `startService()`.

To enable and customize it, use `openApi` configuration key.
Documentation can be added:
- at upper level: `openApi.info.title`, `openApi.info.description`
- at group level: `openApi.tags[].description` (`tags[].name` has to match group's name)
- at api level, by attaching to the exposed API:
  - `description`: general description
  - `notes`: string or array of implementation notes
  - `validate`: array of Joi objects to validate incoming parameters (request body)
  - `responseSchema`: Joi object describing expected response

```js
const Joi = require('joi')
const {startService} = require('mini-service')

startService({
  name: 'documented-service',
  version: '1.0.0',
  openApi: {
    // see https://github.com/glennjones/hapi-swagger/blob/master/optionsreference.md
    info: {
      title: 'Simple calculator'
    }
    /* defaults are:
    info: {version},
    documentationPath: '/documentation',
    jsonPath: '/swagger.json',
    basePath: '/api',
    pathPrefixSize: 2
    */
  }
  init: () => {
    const add = (a, b) => a + b

    // document api
    add.description = 'Sum numbers'
    add.notes = 'Only works with two numbers'

    // document parameters
    add.validate = [
      Joi.Number().required().description('reference number').example(5),
      Joi.Number().required().description('added to reference').example(2)
    ]

    // document results
    add.responseSchema = Joi.Number().required().description('number summation').example(7)
    return {add}
  }
})
```

See a more [complete example](https://github.com/feugy/mini-service/tree/master/examples/documented-service).

## Can endpoint method/headers/query be configured?

No it cannot.

Mini-service purposely hides details regarding exposed Http endpoints.
Its goal is not to be another web framework, but acts more as an remote-procedure-call toolkit.

When exposing an API function, the following conventions apply:
- endpoint path is `/api/${function name}` (case sensitive)
- endpoint method is `GET` if function has no declared parameters, `POST` otherwise
- endpoint headers can not be configured
- endpoint query string can note be configured
- incoming request payload is always parsed as JSON
- when `validate` is set, and request payload doesn't comply, a 400 `Bad Request` error is returned with details
- when `responseSchema` and `validateResponse` are set, and response payload doesn't comply, a 512 `Bad Response` error is returned with details
- otherwise, endpoint always returns 200, and result (if it exists) is always serialized as JSON


text:
layout: page
title: Tracker Pearl Holdings Party
date: 2016-05-24
author: Stephen Mcdaniel
tags: weekly links, java
status: published
summary: Donec pulvinar sapien sit amet libero.
banner: images/banner/leisure-05.jpg
booking:
  startDate: 03/01/2016
  endDate: 03/04/2016
  ctyhocn: SKAWAHX
  groupCode: TPHP
published: true
---
Pellentesque et nibh porttitor, consequat turpis nec, laoreet quam. Suspendisse consectetur fermentum scelerisque. Phasellus imperdiet orci metus, et egestas magna tristique eget. Morbi lobortis, nisl ut faucibus suscipit, tellus erat eleifend risus, non interdum metus nulla sed massa. Pellentesque volutpat dolor ut velit posuere consectetur. Duis feugiat, odio in pellentesque convallis, sem justo gravida magna, non bibendum tellus turpis non velit. Quisque est leo, faucibus at accumsan lobortis, luctus quis diam. Vivamus eget tortor pharetra, vehicula nisi at, imperdiet lectus.
Donec varius non urna sit amet tempor. Donec at eros in leo mollis mollis. Suspendisse lobortis neque quis ipsum viverra porttitor. Phasellus magna magna, cursus eu bibendum ac, pharetra vel neque. In at neque pellentesque, vulputate neque id, condimentum mi. Curabitur condimentum egestas velit, nec venenatis sapien scelerisque iaculis. Morbi laoreet feugiat mauris. Aliquam eget diam justo. Ut dapibus dui sed ex lobortis, eget ultrices enim congue. Lorem ipsum dolor sit amet, consectetur adipiscing elit.

1 Praesent tincidunt elit ut consectetur posuere
1 Aliquam malesuada elit ut lacus tincidunt blandit
1 Quisque vitae elit ut elit commodo tempor ac et sapien
1 Quisque at quam nec tellus suscipit condimentum eu ac arcu
1 Maecenas porta magna sit amet consequat varius.

Donec pulvinar ultrices volutpat. Donec sed convallis augue. Cras in lectus vel eros bibendum commodo. Proin rutrum fringilla elementum. Phasellus diam nisi, consectetur id ante sed, lacinia posuere sem. Maecenas nisi urna, congue cursus tellus in, varius sagittis diam. Suspendisse et imperdiet orci. Sed ut nunc at diam fermentum rhoncus sit amet in ligula. Aliquam libero tortor, consequat quis risus vel, pellentesque euismod dui. Nunc commodo rhoncus suscipit. Nam finibus, leo mollis porttitor molestie, arcu turpis facilisis orci, at posuere nisi turpis sed dolor. Integer tincidunt leo vitae nisi consequat, placerat facilisis nisi fermentum. Vivamus non urna et mauris sollicitudin scelerisque. Aliquam eleifend id orci in pulvinar.


text:
package main

import (
	"context"

	certificatemanager "cloud.google.com/go/certificatemanager/apiv1"
	certificatemanagerpb "cloud.google.com/go/certificatemanager/apiv1/certificatemanagerpb"
	"google.golang.org/api/iterator"
)

func main() {
	ctx := context.Background()
	// This snippet has been automatically generated and should be regarded as a code template only.
	// It will require modifications to work:
	// - It may require correct/in-range values for request initialization.
	// - It may require specifying regional endpoints when creating the service client as shown in:
	//   https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options
	c, err := certificatemanager.NewClient(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	defer c.Close()

	req := &certificatemanagerpb.ListCertificateMapEntriesRequest{
		// TODO: Fill request struct fields.
		// See https://pkg.go.dev/cloud.google.com/go/certificatemanager/apiv1/certificatemanagerpb#ListCertificateMapEntriesRequest.
	}
	it := c.ListCertificateMapEntries(ctx, req)
	for {
		resp, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			// TODO: Handle error.
		}
		// TODO: Use resp.
		_ = resp
	}
}

// [END certificatemanager_v1_generated_CertificateManager_ListCertificateMapEntries_sync]


text:
#include <gbBase/Finally.hpp>
#include <gbBase/Log.hpp>
#include <gbBase/LogHandlers.hpp>
#include <gbBase/UnusedVariable.hpp>

#include <gbMath/Matrix4.hpp>
#include <gbMath/Transform3.hpp>
#include <gbMath/Vector2.hpp>
#include <gbMath/Vector3.hpp>

#include <gbVk/Buffer.hpp>
#include <gbVk/CommandBuffer.hpp>
#include <gbVk/CommandBuffers.hpp>
#include <gbVk/CommandPool.hpp>
#include <gbVk/DescriptorPool.hpp>
#include <gbVk/DescriptorPoolBuilder.hpp>
#include <gbVk/DescriptorSet.hpp>
#include <gbVk/DescriptorSetLayout.hpp>
#include <gbVk/DescriptorSetLayoutBuilder.hpp>
#include <gbVk/DescriptorSets.hpp>
#include <gbVk/Device.hpp>
#include <gbVk/DeviceBuilder.hpp>
#include <gbVk/DeviceMemory.hpp>
#include <gbVk/Fence.hpp>
#include <gbVk/Framebuffer.hpp>
#include <gbVk/Image.hpp>
#include <gbVk/ImageView.hpp>
#include <gbVk/Instance.hpp>
#include <gbVk/PhysicalDevice.hpp>
#include <gbVk/Pipeline.hpp>
#include <gbVk/PipelineBuilder.hpp>
#include <gbVk/PipelineLayout.hpp>
#include <gbVk/PipelineLayoutBuilder.hpp>
#include <gbVk/Queue.hpp>
#include <gbVk/RenderPass.hpp>
#include <gbVk/RenderPassBuilder.hpp>
#include <gbVk/Sampler.hpp>
#include <gbVk/Semaphore.hpp>
#include <gbVk/ShaderModule.hpp>
#include <gbVk/SpirvCode.hpp>
#include <gbVk/StringConverters.hpp>
#include <gbVk/Swapchain.hpp>

#include <gbBase/PerfLog.hpp>

#include <GLFW/glfw3.h>

#include <stb_image.h>

#include <algorithm>
#include <chrono>
#include <cstring>
#include <memory>
#include <vector>

struct DemoState {};

struct Vertex {
    GhulbusMath::Vector3f position;
    GhulbusMath::Vector3f color;
    GhulbusMath::Vector2f texCoords;
};

struct UBOMVP {
    GhulbusMath::Matrix4<float> model;
    GhulbusMath::Matrix4<float> view;
    GhulbusMath::Matrix4<float> projection;
};

inline std::vector<Vertex> generateVertexData()
{
    return {
        {{-0.5f, -0.5f, 0.0f}, {1.0f, 0.0f, 0.0f}, {0.0f, 0.0f}},
        {{ 0.5f, -0.5f, 0.0f}, {0.0f, 1.0f, 0.0f}, {1.0f, 0.0f}},
        {{ 0.5f,  0.5f, 0.0f}, {0.0f, 0.0f, 1.0f}, {1.0f, 1.0f}},
        {{-0.5f,  0.5f, 0.0f}, {1.0f, 1.0f, 1.0f}, {0.0f, 1.0f}},

        {{-0.5f, -0.5f, -0.5f}, {1.0f, 0.0f, 0.0f}, {0.0f, 0.0f}},
        {{ 0.5f, -0.5f, -0.5f}, {0.0f, 1.0f, 0.0f}, {1.0f, 0.0f}},
        {{ 0.5f,  0.5f, -0.5f}, {0.0f, 0.0f, 1.0f}, {1.0f, 1.0f}},
        {{-0.5f,  0.5f, -0.5f}, {1.0f, 1.0f, 1.0f}, {0.0f, 1.0f}}
    };
}

inline std::vector<uint16_t> generateIndexData() {
    return { 0, 1, 2, 2, 3, 0,
             4, 5, 6, 6, 7, 4 };
}

enum class DrawMode {
    Hardcoded,
    Direct,
    UniformTransform,
    Textured
};

int main()
{
    DrawMode const draw_mode = DrawMode::Textured;

    auto const gblog_init_guard = Ghulbus::Log::initializeLoggingWithGuard();
    Ghulbus::Log::Handlers::LogSynchronizeMutex logger(Ghulbus::Log::Handlers::logToCout);
    Ghulbus::Log::setLogHandler(logger);
    Ghulbus::Log::setLogLevel(Ghulbus::LogLevel::Trace);

    Ghulbus::PerfLog perflog;

    if (!glfwInit())
    {
        return 1;
    }
    auto const glfw_init_guard = Ghulbus::finally([]() { glfwTerminate(); });
    glfwSetErrorCallback([](int ec, char const* msg) { GHULBUS_LOG(Error, "GLFW Error " << ec << " - " << msg); });
    if (!glfwVulkanSupported()) {
        GHULBUS_LOG(Error, "No Vulkan support in GLFW.");
        return 1;
    }
    GHULBUS_LOG(Trace, "GLFW " << glfwGetVersionString() << " up and running.");

    GhulbusVulkan::Instance instance = GhulbusVulkan::Instance::createInstance();

    auto phys_devices = instance.enumeratePhysicalDevices();
    auto& physical_device = phys_devices.front();
    auto dev_props = physical_device.getProperties();
    GHULBUS_LOG(Info, "Using device " << dev_props.deviceName << " ("
                      << "Vulkan Version " << GhulbusVulkan::version_to_string(dev_props.apiVersion) << ", "
                      << "Driver Version " << GhulbusVulkan::version_to_string(dev_props.driverVersion)
                      << ").");

    glfwWindowHint(GLFW_RESIZABLE, 0);
    glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
    int const WINDOW_WIDTH = 1280;
    int const WINDOW_HEIGHT = 720;
    auto main_window =
        std::unique_ptr<GLFWwindow, void(*)(GLFWwindow*)>(glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, "Vulkan Demo",
            nullptr, nullptr),
            glfwDestroyWindow);
    if (!main_window) {
        return 1;
    }
    VkSurfaceKHR surface;
    VkResult res = glfwCreateWindowSurface(instance.getVkInstance(), main_window.get(), nullptr, &surface);
    if (res != VK_SUCCESS) {
        GHULBUS_LOG(Error, "Unable to create Vulkan surface.");
    }
    auto guard_surface = Ghulbus::finally([&instance, surface]() { vkDestroySurfaceKHR(instance.getVkInstance(), surface, nullptr); });
    perflog.tick(Ghulbus::LogLevel::Debug, "Window creation");

    // find queue family
    auto const queue_family_properties = physical_device.getQueueFamilyProperties();
    auto const opt_queue_family = [&physical_device, &surface, &queue_family_properties]() -> std::optional<uint32_t> {
        uint32_t i = 0;
        for (auto const& qfp : queue_family_properties) {
            if ((qfp.queueCount > 0) && (qfp.queueFlags & VK_QUEUE_GRAPHICS_BIT)) {
                // @todo: graphics and presentation might only be available on separate queues
                if (physical_device.getSurfaceSupport(i, surface)) {
                    return i;
                }
            }
            ++i;
        }
        GHULBUS_LOG(Error, "No suitable queue family found.");
        return std::nullopt;
    }();
    if (!opt_queue_family) {
        return 1;
    }

    uint32_t const queue_family = *opt_queue_family;

    uint32_t const transfer_queue_family = [&physical_device, queue_family, &queue_family_properties]() {
        uint32_t i = 0;
        for (auto const& qfp : queue_family_properties) {
            if ((qfp.queueCount > 0) &&
                (qfp.queueFlags & VK_QUEUE_TRANSFER_BIT) &&
                ((qfp.queueFlags & VK_QUEUE_GRAPHICS_BIT) == 0)) {
                return i;
            }
            ++i;
        }
        return queue_family;
    }();

    GhulbusVulkan::Device device = [&physical_device, queue_family, transfer_queue_family,
                                    &queue_family_properties]()
    {
        GhulbusVulkan::DeviceBuilder device_builder = physical_device.createDeviceBuilder();
        device_builder.requested_features.samplerAnisotropy = VK_TRUE;
        if (queue_family == transfer_queue_family) {
            device_builder.addQueues(queue_family, std::min(queue_family_properties[queue_family].queueCount, 2u));
        } else {
            device_builder.addQueues(queue_family, 1);
            device_builder.addQueues(transfer_queue_family, 1);
        }
        return device_builder.create();
    }();

    DemoState state;
    glfwSetWindowUserPointer(main_window.get(), &state);

    glfwSetKeyCallback(main_window.get(),
        [](GLFWwindow* window, int key, int scancode, int action, int mods)
        {
            GHULBUS_UNUSED_VARIABLE(scancode);
            GHULBUS_UNUSED_VARIABLE(action);
            GHULBUS_UNUSED_VARIABLE(mods);
            if (key == GLFW_KEY_ESCAPE) {
                glfwSetWindowShouldClose(window, true);
            }
        });

    GhulbusVulkan::DeviceMemory memory = device.allocateMemory(1024 * 1024 * 64, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
    GhulbusVulkan::DeviceMemory host_memory = device.allocateMemory(1024 * 1024 * 64, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT);

    {
        auto mapped = host_memory.map();
        for (int i = 0; i < 1024 * 1024 * 64; ++i) { mapped[i] = std::byte(i & 0xff); }
        mapped.flush();
    }
    {
        auto mapped_again = host_memory.map();
        mapped_again.invalidate();
        for (int i = 0; i < 1024; ++i) {
            /*
            GHULBUS_LOG(Info, i << " - " << std::to_integer<int>(
                static_cast<GhulbusVulkan::DeviceMemory::MappedMemory const&>(mapped_again)[i]));
             */
        }
    }

    auto swapchain = device.createSwapchain(surface, queue_family);
    uint32_t const swapchain_n_images = swapchain.getNumberOfImages();

    auto command_pool = device.createCommandPool(VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, queue_family);
    auto command_buffers = command_pool.allocateCommandBuffers(1);
    auto& command_buffer = command_buffers.getCommandBuffer(0);

    auto transfer_command_pool = device.createCommandPool(VK_COMMAND_POOL_CREATE_TRANSIENT_BIT, transfer_queue_family);

    command_buffer.begin();
    VkBufferCopy region;
    region.srcOffset = 0;
    region.dstOffset = 0;
    region.size = 1024 * 1024 * 64;
    //vkCmdCopyBuffer(command_buffer.getVkCommandBuffer(), host_memory, memory, 1, & region);
    command_buffer.end();

    auto queue = device.getQueue(queue_family, 0);
    queue.submit(command_buffer);
    queue.waitIdle();
    command_buffer.reset();

    auto transfer_queue = device.getQueue(transfer_queue_family, (transfer_queue_family == queue_family) ?
        ((queue_family_properties[queue_family].queueCount > 1) ? 1 : 0) : 0);

    auto fence = device.createFence();
    auto images = swapchain.getVkImages();
    auto swapchain_image = swapchain.acquireNextImage(fence);
    if (!swapchain_image) {
        GHULBUS_LOG(Error, "Unable to acquire image from swap chain.");
        return 1;
    }
    fence.wait();

    command_buffer.begin();

    auto source_image = device.createImage(VkExtent3D{ WINDOW_WIDTH, WINDOW_HEIGHT, 1 }, VK_FORMAT_R8G8B8A8_UNORM,
                                           1, 1, VK_SAMPLE_COUNT_1_BIT, VK_IMAGE_TILING_LINEAR,
                                           VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT);
    auto mem_reqs = source_image.getMemoryRequirements();
    auto source_image_memory = device.allocateMemory(mem_reqs, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT);
    source_image_memory.bindImage(source_image);

    // create image view
    /*
    VkImageView image_view;
    VkImageViewCreateInfo color_image_view = {};
    color_image_view.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
    color_image_view.pNext = nullptr;
    color_image_view.format = VK_FORMAT_B8G8R8A8_UNORM;
    color_image_view.components.r = VK_COMPONENT_SWIZZLE_R;
    color_image_view.components.g = VK_COMPONENT_SWIZZLE_G;
    color_image_view.components.b = VK_COMPONENT_SWIZZLE_B;
    color_image_view.components.a = VK_COMPONENT_SWIZZLE_A;
    color_image_view.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
    color_image_view.subresourceRange.baseMipLevel = 0;
    color_image_view.subresourceRange.levelCount = 1;
    color_image_view.subresourceRange.baseArrayLayer = 0;
    color_image_view.subresourceRange.layerCount = 1;
    color_image_view.viewType = VK_IMAGE_VIEW_TYPE_2D;
    color_image_view.flags = 0;
    color_image_view.image = swapchain_image->getVkImage();

    res = vkCreateImageView(device.getVkDevice(), &color_image_view, NULL, &image_view);
    if(res != VK_SUCCESS) {
        GHULBUS_LOG(Error, "Unable to create image view.");
    }
    auto guard_image_view = Ghulbus::finally([&device, &image_view]() { vkDestroyImageView(device.getVkDevice(), image_view, nullptr); });
    */

    // fill host image
    source_image.transition(command_buffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_HOST_BIT,
                            VK_ACCESS_HOST_WRITE_BIT, VK_IMAGE_LAYOUT_GENERAL);
    {
        struct ImageDim { int x, y, comp; } dim;
        auto img_data = stbi_load("textures/statue.jpg", &dim.x, &dim.y, &dim.comp, 0);
        auto mapped = source_image_memory.map();
        for (int i = 0; i < mem_reqs.size / 4; ++i) {
            int ix = i % WINDOW_WIDTH;
            int iy = i / WINDOW_WIDTH;
            if (!img_data || ix >= dim.x || iy >= dim.y || (dim.comp != 3 && dim.comp != 4)) {
                mapped[i * 4] = std::byte(255);           //R
                mapped[i * 4 + 1] = std::byte(0);         //G
                mapped[i * 4 + 2] = std::byte(0);         //B
                mapped[i * 4 + 3] = std::byte(255);       //A
            } else {
                auto const pixel_index = (iy * dim.x + ix) * dim.comp;
                mapped[i * 4] = std::byte(img_data[pixel_index]);           //R
                mapped[i * 4 + 1] = std::byte(img_data[pixel_index + 1]);         //G
                mapped[i * 4 + 2] = std::byte(img_data[pixel_index + 2]);         //B
                mapped[i * 4 + 3] = std::byte((dim.comp == 4) ? img_data[pixel_index + 3] : 255);       //A
            }
        }
        mapped.flush();
        stbi_image_free(img_data);
    }

    // copy
    source_image.transition(command_buffer, VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
        VK_ACCESS_TRANSFER_READ_BIT, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
    swapchain_image->transition(command_buffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
        VK_ACCESS_TRANSFER_WRITE_BIT, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
    GhulbusVulkan::Image::blit(command_buffer, source_image, *swapchain_image);

    perflog.tick(Ghulbus::LogLevel::Debug, "Swapchain setup");

    // presentation
    swapchain_image->transition(command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
        VK_ACCESS_MEMORY_READ_BIT, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR);

    command_buffer.end();
    queue.submit(command_buffer);
    queue.waitIdle();
    command_buffer.reset();

    swapchain.present(queue.getVkQueue(), std::move(swapchain_image));
    queue.waitIdle();
    //std::this_thread::sleep_for(std::chrono::seconds(5));

    perflog.tick(Ghulbus::LogLevel::Debug, "Initial present");

    std::vector<Vertex> vertex_data = generateVertexData();
    std::vector<uint16_t> index_data = generateIndexData();
    VkVertexInputBindingDescription vertex_binding;
    vertex_binding.binding = 0;
    vertex_binding.stride = sizeof(Vertex);
    vertex_binding.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;

    std::array<VkVertexInputAttributeDescription, 3> vertex_attributes;
    vertex_attributes[0].location = 0;
    vertex_attributes[0].binding = vertex_binding.binding;
    vertex_attributes[0].format = VK_FORMAT_R32G32B32_SFLOAT;
    vertex_attributes[0].offset = offsetof(Vertex, position);

    vertex_attributes[1].location = 1;
    vertex_attributes[1].binding = vertex_binding.binding;
    vertex_attributes[1].format = VK_FORMAT_R32G32B32_SFLOAT;
    vertex_attributes[1].offset = offsetof(Vertex, color);

    vertex_attributes[2].location = 2;
    vertex_attributes[2].binding = vertex_binding.binding;
    vertex_attributes[2].format = VK_FORMAT_R32G32_SFLOAT;
    vertex_attributes[2].offset = offsetof(Vertex, texCoords);

    GhulbusVulkan::Buffer staging_buffer = device.createBuffer(vertex_data.size() * sizeof(Vertex),
        VK_BUFFER_USAGE_TRANSFER_SRC_BIT);
    auto const staging_buffer_mem_reqs = staging_buffer.getMemoryRequirements();
    GhulbusVulkan::DeviceMemory staging_memory = device.allocateMemory(staging_buffer_mem_reqs,
        VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
    staging_memory.bindBuffer(staging_buffer);

    GhulbusVulkan::Buffer vertex_buffer = device.createBuffer(vertex_data.size() * sizeof(Vertex),
        VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT);
    auto const vertex_buffer_mem_reqs = vertex_buffer.getMemoryRequirements();
    GhulbusVulkan::DeviceMemory vertex_memory =
        device.allocateMemory(vertex_buffer_mem_reqs,
            VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
    vertex_memory.bindBuffer(vertex_buffer);

    auto transfer_command_buffers = transfer_command_pool.allocateCommandBuffers(2);

    // copy vertex buffer
    {
        auto mapped_memory = staging_memory.map();
        std::memcpy(mapped_memory, vertex_data.data(), vertex_data.size() * sizeof(Vertex));
    }
    {
        auto& transfer_command_buffer = transfer_command_buffers.getCommandBuffer(0);

        transfer_command_buffer.begin(VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT);
        VkBufferCopy buffer_copy;
        buffer_copy.srcOffset = 0;
        buffer_copy.dstOffset = 0;
        buffer_copy.size = vertex_data.size() * sizeof(Vertex);

        vkCmdCopyBuffer(transfer_command_buffer.getVkCommandBuffer(), staging_buffer.getVkBuffer(),
                        vertex_buffer.getVkBuffer(), 1, &buffer_copy);

        VkBufferMemoryBarrier barrier;
        barrier.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER;
        barrier.pNext = nullptr;
        barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
        barrier.dstAccessMask = VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT;
        barrier.srcQueueFamilyIndex = transfer_queue_family;
        barrier.dstQueueFamilyIndex = queue_family;
        barrier.buffer = vertex_buffer.getVkBuffer();
        barrier.offset = 0;
        barrier.size = VK_WHOLE_SIZE;
        vkCmdPipelineBarrier(transfer_command_buffer.getVkCommandBuffer(),
            VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_VERTEX_INPUT_BIT, VK_DEPENDENCY_BY_REGION_BIT,
            0, nullptr, 1, &barrier, 0, nullptr);

        transfer_command_buffer.end();
    }

    GhulbusVulkan::Buffer index_staging_buffer = device.createBuffer(index_data.size() * sizeof(uint16_t),
                                                                     VK_BUFFER_USAGE_TRANSFER_SRC_BIT);
    auto const index_staging_buffer_mem_reqs = index_staging_buffer.getMemoryRequirements();
    GhulbusVulkan::DeviceMemory index_staging_memory = device.allocateMemory(index_staging_buffer_mem_reqs,
        VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
    index_staging_memory.bindBuffer(index_staging_buffer);

    GhulbusVulkan::Buffer index_buffer = device.createBuffer(index_data.size() * sizeof(uint16_t),
        VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT);
    auto const index_buffer_mem_reqs = vertex_buffer.getMemoryRequirements();
    GhulbusVulkan::DeviceMemory index_memory =
        device.allocateMemory(index_buffer_mem_reqs,
            VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
    index_memory.bindBuffer(index_buffer);

    // copy index buffer
    {
        auto mapped_memory = index_staging_memory.map();
        std::memcpy(mapped_memory, index_data.data(), index_data.size() * sizeof(uint16_t));
    }
    {
        auto& transfer_command_buffer = transfer_command_buffers.getCommandBuffer(1);

        transfer_command_buffer.begin(VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT);
        VkBufferCopy buffer_copy;
        buffer_copy.srcOffset = 0;
        buffer_copy.dstOffset = 0;
        buffer_copy.size = index_data.size() * sizeof(uint16_t);

        vkCmdCopyBuffer(transfer_command_buffer.getVkCommandBuffer(), index_staging_buffer.getVkBuffer(),
                        index_buffer.getVkBuffer(), 1, &buffer_copy);

        VkBufferMemoryBarrier barrier;
        barrier.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER;
        barrier.pNext = nullptr;
        barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
        barrier.dstAccessMask = VK_ACCESS_INDEX_READ_BIT;
        barrier.srcQueueFamilyIndex = transfer_queue_family;
        barrier.dstQueueFamilyIndex = queue_family;
        barrier.buffer = index_buffer.getVkBuffer();
        barrier.offset = 0;
        barrier.size = VK_WHOLE_SIZE;
        vkCmdPipelineBarrier(transfer_command_buffer.getVkCommandBuffer(),
                             VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_VERTEX_INPUT_BIT,
                             VK_DEPENDENCY_BY_REGION_BIT,
                             0, nullptr, 1, &barrier, 0, nullptr);

        transfer_command_buffer.end();
    }
    fence.reset();
    transfer_queue.submit(transfer_command_buffers, fence);

    // ubo
    std::vector<GhulbusVulkan::Buffer> ubo_buffers;
    std::vector<GhulbusVulkan::DeviceMemory> ubo_memories;
    ubo_buffers.reserve(swapchain_n_images);
    ubo_memories.reserve(swapchain_n_images);
    for (uint32_t i = 0; i < swapchain_n_images; ++i)
    {
        ubo_buffers.push_back(device.createBuffer(sizeof(UBOMVP), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT));
        auto const ubo_buffer_mem_reqs = ubo_buffers.back().getMemoryRequirements();
        ubo_memories.push_back(device.allocateMemory(ubo_buffer_mem_reqs,
            VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT));
        ubo_memories.back().bindBuffer(ubo_buffers.back());
    }

    auto timestamp = std::chrono::steady_clock::now();
    UBOMVP ubo_data;
    auto update_uniform_buffer = [&timestamp, &ubo_data, &ubo_memories, WINDOW_WIDTH, WINDOW_HEIGHT](uint32_t index) {
        auto const t = std::chrono::steady_clock::now();
        float const time = std::chrono::duration<float>(t - timestamp).count();
        ubo_data.model = GhulbusMath::make_rotation((GhulbusMath::traits::Pi<float>::value / 2.f) * time,
            GhulbusMath::Vector3f(0.f, 0.f, 1.f)).m;
        ubo_data.view = GhulbusMath::make_view_look_at(GhulbusMath::Vector3f(2.0f, 2.0f, 2.0f),
            GhulbusMath::Vector3f(0.0f, 0.0f, 0.0f),
            GhulbusMath::Vector3f(0.0f, 0.0f, 1.0f)).m;
        ubo_data.projection = GhulbusMath::make_perspective_projection_fov(
            (GhulbusMath::traits::Pi<float>::value / 4.f),
            static_cast<float>(WINDOW_WIDTH) / static_cast<float>(WINDOW_HEIGHT), 0.1f, 10.f).m;

        // correct for vulkan screen coordinate origin being upper left, instead of lower left
        ubo_data.projection.m22 *= -1.f;

        // correct memory layout to column-major
        ubo_data.model = GhulbusMath::transpose(ubo_data.model);
        ubo_data.view = GhulbusMath::transpose(ubo_data.view);
        ubo_data.projection = GhulbusMath::transpose(ubo_data.projection);
        {
            auto mapped_mem = ubo_memories[index].map();
            std::memcpy(mapped_mem, &ubo_data, sizeof(UBOMVP));
        }
    };

    // texture
    int texture_dimensions_width, texture_dimensions_height, texture_dimensions_n_channels;
    stbi_uc* texture_data = stbi_load("textures/statue.jpg", &texture_dimensions_width, &texture_dimensions_height,
        &texture_dimensions_n_channels, STBI_rgb_alpha);
    if (!texture_data) { GHULBUS_LOG(Error, "Error loading texture file."); return 1; }
    auto texture_data_guard = Ghulbus::finally([texture_data]() { stbi_image_free(texture_data); });
    VkDeviceSize const texture_size = texture_dimensions_width * texture_dimensions_height * 4;

    auto texture_staging_buffer = device.createBuffer(texture_size, VK_BUFFER_USAGE_TRANSFER_SRC_BIT);
    auto texture_staging_buffer_mem_reqs = texture_staging_buffer.getMemoryRequirements();
    auto texture_staging_memory = device.allocateMemory(texture_staging_buffer_mem_reqs,
        VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
    texture_staging_memory.bindBuffer(texture_staging_buffer);
    {
        auto mapped_mem = texture_staging_memory.map();
        std::memcpy(mapped_mem, texture_data, texture_size);
    }
    GhulbusVulkan::Image texture_image = device.createImage2D(texture_dimensions_width, texture_dimensions_height);
    auto const texture_image_mem_reqs = texture_image.getMemoryRequirements();
    GhulbusVulkan::DeviceMemory texture_image_memory = device.allocateMemory(texture_image_mem_reqs,
        VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
    texture_image_memory.bindImage(texture_image);

    command_buffer.begin();
    texture_image.transition(command_buffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
        VK_ACCESS_TRANSFER_WRITE_BIT, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
    GhulbusVulkan::Image::copy(command_buffer, texture_staging_buffer, texture_image);
    texture_image.transition(command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
        VK_ACCESS_SHADER_READ_BIT, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
    command_buffer.end();
    queue.submit(command_buffer);
    queue.waitIdle();
    command_buffer.reset();

    GhulbusVulkan::ImageView texture_image_view = texture_image.createImageView();
    GhulbusVulkan::Sampler texture_sampler = device.createSampler();

    // depth buffer attachment
    auto const depth_buffer_opt_format = physical_device.findDepthBufferFormat();
    if (!depth_buffer_opt_format) { GHULBUS_LOG(Error, "No supported depth buffer format found."); return 1; }
    VkFormat const depth_buffer_format = *depth_buffer_opt_format;
    GhulbusVulkan::Image depth_buffer_image =
        device.createImageDepthBuffer(WINDOW_WIDTH, WINDOW_HEIGHT, depth_buffer_format);
    auto const depth_buffer_image_mem_reqs = depth_buffer_image.getMemoryRequirements();
    GhulbusVulkan::DeviceMemory depth_buffer_memory = device.allocateMemory(depth_buffer_image_mem_reqs,
        VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
    depth_buffer_memory.bindImage(depth_buffer_image);
    GhulbusVulkan::ImageView depth_buffer_image_view = depth_buffer_image.createImageViewDepthBuffer();

    auto spirv_code = GhulbusVulkan::SpirvCode::load("shaders/simple_compute.spv");
    auto version = spirv_code.getSpirvVersion();
    auto bound = spirv_code.getBound();
    GHULBUS_UNUSED_VARIABLE(version);
    GHULBUS_UNUSED_VARIABLE(bound);
    auto shader_module = device.createShaderModule(spirv_code);

    auto vert_spirv_code = GhulbusVulkan::SpirvCode::load("shaders/vert_hardcoded.spv");
    auto vert_hardcoded_shader_module = device.createShaderModule(vert_spirv_code);

    auto vert_direct_spirv_code = GhulbusVulkan::SpirvCode::load("shaders/vert_direct.spv");
    auto vert_direct_shader_module = device.createShaderModule(vert_direct_spirv_code);

    auto vert_mvp_spirv_code = GhulbusVulkan::SpirvCode::load("shaders/vert_mvp.spv");
    auto vert_mvp_shader_module = device.createShaderModule(vert_mvp_spirv_code);

    auto vert_textured_spirv_code = GhulbusVulkan::SpirvCode::load("shaders/vert_textured.spv");
    auto vert_textured_shader_module = device.createShaderModule(vert_textured_spirv_code);

    VkPipelineShaderStageCreateInfo vert_shader_stage_ci;
    vert_shader_stage_ci.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
    vert_shader_stage_ci.pNext = nullptr;
    vert_shader_stage_ci.flags = 0;
    vert_shader_stage_ci.stage = VK_SHADER_STAGE_VERTEX_BIT;
    if constexpr (draw_mode == DrawMode::Textured) {
        vert_shader_stage_ci.module = vert_textured_shader_module.getVkShaderModule();
    } else if constexpr (draw_mode == DrawMode::UniformTransform) {
        vert_shader_stage_ci.module = vert_mvp_shader_module.getVkShaderModule();
    } else if constexpr (draw_mode == DrawMode::Hardcoded) {
        vert_shader_stage_ci.module = vert_hardcoded_shader_module.getVkShaderModule();
    } else if constexpr (draw_mode == DrawMode::Direct) {
        vert_shader_stage_ci.module = vert_direct_shader_module.getVkShaderModule();
    }
    vert_shader_stage_ci.pName = "main";
    vert_shader_stage_ci.pSpecializationInfo = nullptr;

    auto frag_spirv_code = GhulbusVulkan::SpirvCode::load("shaders/frag_hardcoded.spv");
    auto frag_shader_module = device.createShaderModule(frag_spirv_code);

    auto frag_textured_spirv_code = GhulbusVulkan::SpirvCode::load("shaders/frag_textured.spv");
    auto frag_textured_shader_module = device.createShaderModule(frag_textured_spirv_code);

    VkPipelineShaderStageCreateInfo frag_shader_stage_ci;
    frag_shader_stage_ci.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
    frag_shader_stage_ci.pNext = nullptr;
    frag_shader_stage_ci.flags = 0;
    frag_shader_stage_ci.stage = VK_SHADER_STAGE_FRAGMENT_BIT;
    if constexpr (draw_mode == DrawMode::Textured) {
        frag_shader_stage_ci.module = frag_textured_shader_module.getVkShaderModule();
    } else {
        frag_shader_stage_ci.module = frag_shader_module.getVkShaderModule();
    }
    frag_shader_stage_ci.pName = "main";
    frag_shader_stage_ci.pSpecializationInfo = nullptr;

    std::vector<VkPipelineShaderStageCreateInfo> shader_stage_cis{ vert_shader_stage_ci, frag_shader_stage_ci };

    // render pass
    GhulbusVulkan::RenderPass render_pass = [&device, &swapchain_image, &depth_buffer_image]() {
            auto builder = device.createRenderPassBuilder();
            builder.addSubpassGraphics();
            builder.addColorAttachment(swapchain_image->getFormat());
            builder.addDepthStencilAttachment(depth_buffer_image.getFormat());
            return builder.create();
        }();

    // ubo
    GhulbusVulkan::DescriptorSetLayout ubo_layout = [&device]() {
        GhulbusVulkan::DescriptorSetLayoutBuilder layout_builder = device.createDescriptorSetLayoutBuilder();
        layout_builder.addUniformBuffer(0, VK_SHADER_STAGE_VERTEX_BIT);
        layout_builder.addSampler(1, VK_SHADER_STAGE_FRAGMENT_BIT);
        return layout_builder.create();
    }();
    GhulbusVulkan::DescriptorPool ubo_descriptor_pool = [&device, swapchain_n_images]() {
        GhulbusVulkan::DescriptorPoolBuilder descpool_builder = device.createDescriptorPoolBuilder();
        descpool_builder.addDescriptorPoolSize(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, swapchain_n_images);
        descpool_builder.addDescriptorPoolSize(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, swapchain_n_images);
        return descpool_builder.create(swapchain_n_images, 0,
                                       GhulbusVulkan::DescriptorPoolBuilder::NoImplicitFreeDescriptorFlag{});
    }();
    GhulbusVulkan::DescriptorSets ubo_descriptor_sets =
        ubo_descriptor_pool.allocateDescriptorSets(swapchain_n_images, ubo_layout);
    for (uint32_t i = 0; i < swapchain_n_images; ++i) {
        VkDescriptorBufferInfo buffer_info;
        buffer_info.buffer = ubo_buffers[i].getVkBuffer();
        buffer_info.offset = 0;
        buffer_info.range = sizeof(UBOMVP);

        std::array<VkWriteDescriptorSet, 2> write_desc_set;
        VkWriteDescriptorSet& ubo_write_desc_set = write_desc_set[0];
        ubo_write_desc_set.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
        ubo_write_desc_set.pNext = nullptr;
        ubo_write_desc_set.dstSet = ubo_descriptor_sets.getDescriptorSet(i).getVkDescriptorSet();
        ubo_write_desc_set.dstBinding = 0;
        ubo_write_desc_set.dstArrayElement = 0;
        ubo_write_desc_set.descriptorCount = 1;
        ubo_write_desc_set.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
        ubo_write_desc_set.pImageInfo = nullptr;
        ubo_write_desc_set.pBufferInfo = &buffer_info;
        ubo_write_desc_set.pTexelBufferView = nullptr;

        VkDescriptorImageInfo image_info;
        image_info.sampler = texture_sampler.getVkSampler();
        image_info.imageView = texture_image_view.getVkImageView();
        image_info.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;

        VkWriteDescriptorSet& texture_write_desc_set = write_desc_set[1];
        texture_write_desc_set.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
        texture_write_desc_set.pNext = nullptr;
        texture_write_desc_set.dstSet = ubo_descriptor_sets.getDescriptorSet(i).getVkDescriptorSet();
        texture_write_desc_set.dstBinding = 1;
        texture_write_desc_set.dstArrayElement = 0;
        texture_write_desc_set.descriptorCount = 1;
        texture_write_desc_set.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
        texture_write_desc_set.pImageInfo = &image_info;
        texture_write_desc_set.pBufferInfo = nullptr;
        texture_write_desc_set.pTexelBufferView = nullptr;

        vkUpdateDescriptorSets(device.getVkDevice(), static_cast<uint32_t>(write_desc_set.size()),
                               write_desc_set.data(), 0, nullptr);
    }

    // pipeline
    GhulbusVulkan::PipelineLayout pipeline_layout = [&device, &ubo_layout]() {
        GhulbusVulkan::PipelineLayoutBuilder builder = device.createPipelineLayoutBuilder();
        builder.addDescriptorSetLayout(ubo_layout);
        return builder.create();
    }();

    GhulbusVulkan::Pipeline pipeline = [&device, &swapchain_image, &pipeline_layout,
                                        &shader_stage_cis, &render_pass,
                                        &vertex_binding, &vertex_attributes, draw_mode]() {
        auto builder = device.createGraphicsPipelineBuilder(swapchain_image->getWidth(),
                                                            swapchain_image->getHeight());
        if (draw_mode != DrawMode::Hardcoded) {
            builder.addVertexBindings(&vertex_binding, 1, vertex_attributes.data(),
                                      static_cast<uint32_t>(vertex_attributes.size()));
        }
        return builder.create(pipeline_layout, shader_stage_cis.data(),
                              static_cast<std::uint32_t>(shader_stage_cis.size()),
                              render_pass.getVkRenderPass());
    }();

    std::vector<GhulbusVulkan::Framebuffer> framebuffers =
        device.createFramebuffers(swapchain, render_pass, depth_buffer_image_view);

    GhulbusVulkan::CommandBuffers triangle_draw_command_buffers =
        command_pool.allocateCommandBuffers(swapchain_n_images);

    for(uint32_t i = 0; i < triangle_draw_command_buffers.size(); ++i) {
        auto& local_command_buffer = triangle_draw_command_buffers.getCommandBuffer(i);
        local_command_buffer.begin(VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT);

        VkRenderPassBeginInfo render_pass_info;
        render_pass_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
        render_pass_info.pNext = nullptr;
        render_pass_info.renderPass = render_pass.getVkRenderPass();
        render_pass_info.framebuffer = framebuffers[i].getVkFramebuffer();
        render_pass_info.renderArea.offset.x = 0;
        render_pass_info.renderArea.offset.y = 0;
        render_pass_info.renderArea.extent.width = swapchain_image->getWidth();
        render_pass_info.renderArea.extent.height = swapchain_image->getHeight();
        std::array<VkClearValue, 2> clear_color;
        clear_color[0].color.float32[0] = 0.5f;
        clear_color[0].color.float32[1] = 0.f;
        clear_color[0].color.float32[2] = 0.5f;
        clear_color[0].color.float32[3] = 1.f;
        clear_color[1].depthStencil.depth = 1.0f;
        clear_color[1].depthStencil.stencil = 0;
        render_pass_info.clearValueCount = static_cast<uint32_t>(clear_color.size());
        render_pass_info.pClearValues = clear_color.data();

        vkCmdBeginRenderPass(local_command_buffer.getVkCommandBuffer(),
                             &render_pass_info, VK_SUBPASS_CONTENTS_INLINE);
        vkCmdBindPipeline(local_command_buffer.getVkCommandBuffer(),
                          VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline.getVkPipeline());

        if constexpr ((draw_mode == DrawMode::UniformTransform) || (draw_mode == DrawMode::Textured)) {
            VkDescriptorSet desc_set_i = ubo_descriptor_sets.getDescriptorSet(i).getVkDescriptorSet();
            vkCmdBindDescriptorSets(local_command_buffer.getVkCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS,
                                    pipeline_layout.getVkPipelineLayout(), 0, 1, &desc_set_i, 0, nullptr);
        }

        if constexpr (draw_mode == DrawMode::Hardcoded) {
            vkCmdDraw(local_command_buffer.getVkCommandBuffer(), 3, 1, 0, 0);
        } else {
            VkBuffer vertexBuffers[] = { vertex_buffer.getVkBuffer() };
            VkDeviceSize offsets[] = { 0 };
            vkCmdBindVertexBuffers(local_command_buffer.getVkCommandBuffer(), 0, 1, vertexBuffers, offsets);
            vkCmdBindIndexBuffer(local_command_buffer.getVkCommandBuffer(), index_buffer.getVkBuffer(),
                                 0, VK_INDEX_TYPE_UINT16);
            vkCmdDrawIndexed(local_command_buffer.getVkCommandBuffer(), static_cast<uint32_t>(index_data.size()),
                             1, 0, 0, 0);
        }

        vkCmdEndRenderPass(local_command_buffer.getVkCommandBuffer());
        local_command_buffer.end();
    }

    perflog.tick(Ghulbus::LogLevel::Debug, "Main setup");

    GhulbusVulkan::Semaphore semaphore_image_available = device.createSemaphore();
    GhulbusVulkan::Semaphore semaphore_render_finished = device.createSemaphore();

    fence.wait();
    GHULBUS_LOG(Trace, "Entering main loop...");
    while(!glfwWindowShouldClose(main_window.get())) {
        glfwPollEvents();

        auto frame_image = swapchain.acquireNextImage(semaphore_image_available);
        update_uniform_buffer(frame_image.getSwapchainIndex());
        VkSubmitInfo submit_info;
        submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
        submit_info.pNext = nullptr;
        VkSemaphore wait_semaphores[] = { semaphore_image_available.getVkSemaphore() };
        VkPipelineStageFlags wait_stages[] = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT };
        submit_info.waitSemaphoreCount = 1;
        submit_info.pWaitSemaphores = wait_semaphores;
        submit_info.pWaitDstStageMask = wait_stages;
        submit_info.commandBufferCount = 1;
        VkCommandBuffer cb = triangle_draw_command_buffers.getCommandBuffer(frame_image.getSwapchainIndex()).getVkCommandBuffer();
        submit_info.pCommandBuffers = &cb;
        VkSemaphore signal_semaphores[] = { semaphore_render_finished.getVkSemaphore() };
        submit_info.signalSemaphoreCount = 1;
        submit_info.pSignalSemaphores = signal_semaphores;
        res = vkQueueSubmit(queue.getVkQueue(), 1, &submit_info, VK_NULL_HANDLE);
        if(res != VK_SUCCESS) { GHULBUS_LOG(Error, "Error in vkQueueSubmit: " << res); return 1; }
        swapchain.present(queue.getVkQueue(), semaphore_render_finished, std::move(frame_image));
        queue.waitIdle();
    }
}


text:
"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;

Object.defineProperty(exports, "__esModule", {
  value: true
});
Object.defineProperty(exports, "ChipsSelect", {
  enumerable: true,
  get: function get() {
    return _ChipsSelect.default;
  }
});
Object.defineProperty(exports, "Dropdown", {
  enumerable: true,
  get: function get() {
    return _Dropdown.Dropdown;
  }
});
Object.defineProperty(exports, "TextTooltip", {
  enumerable: true,
  get: function get() {
    return _TextTooltip.TextTooltip;
  }
});
Object.defineProperty(exports, "RichTooltip", {
  enumerable: true,
  get: function get() {
    return _RichTooltip.RichTooltip;
  }
});
Object.defineProperty(exports, "Popper", {
  enumerable: true,
  get: function get() {
    return _Popper.Popper;
  }
});
Object.defineProperty(exports, "ViewInfinite", {
  enumerable: true,
  get: function get() {
    return _ViewInfinite.default;
  }
});
Object.defineProperty(exports, "SimpleCheckbox", {
  enumerable: true,
  get: function get() {
    return _SimpleCheckbox.default;
  }
});

var _ChipsSelect = _interopRequireDefault(require("./../components/ChipsSelect/ChipsSelect"));

var _Dropdown = require("../components/Dropdown/Dropdown");

var _TextTooltip = require("../components/TextTooltip/TextTooltip");

var _RichTooltip = require("../components/RichTooltip/RichTooltip");

var _Popper = require("../components/Popper/Popper");

var _ViewInfinite = _interopRequireDefault(require("./../components/View/ViewInfinite"));

var _SimpleCheckbox = _interopRequireDefault(require("./../components/SimpleCheckbox/SimpleCheckbox"));
//# sourceMappingURL=index.js.map


text:
static void Platform_CreateWindow(ImGuiViewport* viewport)
{
	ImGuiIO& io = ImGui::GetIO();
	//MitchHub& gui = *(MitchHub*)io.BackendPlatformUserData;

	ImGuiViewport* main_viewport = ImGui::GetMainViewport();
	PlatformWindow& app = *(PlatformWindow*)main_viewport->PlatformUserData;

	uint32_t sdl_flags = 0;
	//sdl_flags |= SDL_GetWindowFlags(app.m_window->GetWindowPtr()) & SDL_WINDOW_ALLOW_HIGHDPI;
	sdl_flags |= SDL_WINDOW_HIDDEN;
	sdl_flags |= (viewport->Flags & ImGuiViewportFlags_NoDecoration) ? SDL_WINDOW_BORDERLESS : 0;
	sdl_flags |= (viewport->Flags & ImGuiViewportFlags_NoDecoration) ? 0 : SDL_WINDOW_RESIZABLE;
#if !defined(_WIN32)
	// See SDL hack in Platform_ShowWindow().
	sdl_flags |= (viewport->Flags & ImGuiViewportFlags_NoTaskBarIcon) ? SDL_WINDOW_SKIP_TASKBAR : 0;
#endif
#if SDL_HAS_ALWAYS_ON_TOP
	sdl_flags |= (viewport->Flags & ImGuiViewportFlags_TopMost) ? SDL_WINDOW_ALWAYS_ON_TOP : 0;
#endif
	PlatformWindowParams params;
	params.Name = "No Title Yet";
	params.Flags = sdl_flags;
	params.Position = { viewport->Pos.x, viewport->Pos.y };
	params.Size = { viewport->Size.x, viewport->Size.y };

	PlatformWindow* vp = new PlatformWindow(params);
	vp->Create();
	vp->Viewport = viewport;
	vp->Renderer = app.Renderer;

	viewport->PlatformUserData = vp;
	viewport->PlatformHandle = (void*)vp->WindowPtr;
	viewport->PlatformHandleRaw = vp->GetHWND();

}

static void Platform_DestroyWindow(ImGuiViewport* viewport)
{
	if (viewport != ImGui::GetMainViewport())
	{
		PlatformWindow* app = (PlatformWindow*)viewport->PlatformUserData;
		app->Destroy();

		delete app;
	}
	viewport->PlatformUserData = nullptr;
	viewport->PlatformHandle = nullptr;
}

static void Platform_ShowWindow(ImGuiViewport* viewport)
{
	PlatformWindow& app = *(PlatformWindow*)viewport->PlatformUserData;
	app.Show();
}

static ImVec2 Platform_GetWindowPos(ImGuiViewport* viewport)
{
	PlatformWindow& app = *(PlatformWindow*)viewport->PlatformUserData;
	Vector2 pos = app.GetPosition();
	return { pos.x, pos.y };
}

static void Platform_SetWindowPos(ImGuiViewport* viewport, ImVec2 pos)
{
	PlatformWindow& app = *(PlatformWindow*)viewport->PlatformUserData;
	app.SetPosition({ pos.x, pos.y });
}

static ImVec2 Platform_GetWindowSize(ImGuiViewport* viewport)
{
	PlatformWindow& app = *(PlatformWindow*)viewport->PlatformUserData;
	Vector2 size = app.GetSize();
	return { size.x, size.y };
}

static void Platform_SetWindowSize(ImGuiViewport* viewport, ImVec2 size)
{
	PlatformWindow& app = *(PlatformWindow*)viewport->PlatformUserData;
	app.SetSize({ size.x, size.y });
	app.Reset();
}

static void Platform_SetWindowTitle(ImGuiViewport* viewport, const char* title)
{
	PlatformWindow& wnd = *(PlatformWindow*)viewport->PlatformUserData;
	SDL_SetWindowTitle(wnd.WindowPtr, title);
}

static bool Platform_GetWindowFocus(ImGuiViewport* viewport)
{
	PlatformWindow& wnd = *(PlatformWindow*)viewport->PlatformUserData;
	return (SDL_GetWindowFlags(wnd.WindowPtr) & SDL_WINDOW_INPUT_FOCUS) != 0;
}

static void Platform_SetWindowFocus(ImGuiViewport* viewport)
{
	PlatformWindow& wnd = *(PlatformWindow*)viewport->PlatformUserData;
	SDL_RaiseWindow(wnd.WindowPtr);
}

static bool Platform_GetWindowMinimized(ImGuiViewport* viewport)
{
	if (!viewport->DrawData)
	{
		return false;
	}
	PlatformWindow& wnd = *(PlatformWindow*)viewport->PlatformUserData;
	return (SDL_GetWindowFlags(wnd.WindowPtr) & SDL_WINDOW_MINIMIZED) != 0;
}

static void Platform_RenderWindow(ImGuiViewport* viewport, void* platformIndex)
{
	PlatformWindow& wnd = *(PlatformWindow*)viewport->PlatformUserData;
	uint16_t layer = *(uint16_t*)platformIndex;
	if (wnd.ViewId != layer)
	{
		wnd.ViewId = layer;
		wnd.Reset(true);
	}
	wnd.Render();
}

#if SDL_HAS_WINDOW_ALPHA
static void Platform_SetWindowAlpha(ImGuiViewport* viewport, float alpha)
{
}
#endif

namespace ImGui
{
	void InitHooks(SDLWindow* window, ImGuiRenderer* renderer)
	{
		ImGuiPlatformIO& io = ImGui::GetPlatformIO();
		io.Platform_CreateWindow = Platform_CreateWindow;
		io.Platform_DestroyWindow = Platform_DestroyWindow;
		io.Platform_ShowWindow = Platform_ShowWindow;
		io.Platform_SetWindowPos = Platform_SetWindowPos;
		io.Platform_GetWindowPos = Platform_GetWindowPos;
		io.Platform_SetWindowSize = Platform_SetWindowSize;
		io.Platform_GetWindowSize = Platform_GetWindowSize;
		io.Platform_SetWindowFocus = Platform_SetWindowFocus;
		io.Platform_GetWindowFocus = Platform_GetWindowFocus;
		io.Platform_GetWindowMinimized = Platform_GetWindowMinimized;
		io.Platform_SetWindowTitle = Platform_SetWindowTitle;
		io.Platform_RenderWindow = Platform_RenderWindow;
#if SDL_HAS_WINDOW_ALPHA
		io.Platform_SetWindowAlpha = Platform_SetWindowAlpha;
#endif

		// Asserts on start are because of the classes being built different,
		// move stuff to IWindow
		// viewport->PlatformUserData is MitchHub here, but is expected as a PlatformWindow in the callbacks
		PlatformWindowParams p;
		p.Name = "LMAO";
		p.Size = { 1920, 1080 };

		PlatformWindow* win = new PlatformWindow(p);
		win->WindowPtr = window->WindowHandle;
		win->Renderer = renderer;

		ImGuiViewport* viewport = ImGui::GetMainViewport();
		viewport->PlatformUserData = win;
		viewport->PlatformHandle = window->WindowHandle;
		viewport->PlatformHandleRaw = window->GetWindowPtr();
	}
}


text:
namespace AWDemo.Web.API.Models
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Data.Entity.Spatial;

    [Table("SalesLT.CustomerAddress")]
    public partial class CustomerAddress
    {
        [Key]
        [Column(Order = 0)]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int CustomerID { get; set; }

        [Key]
        [Column(Order = 1)]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int AddressID { get; set; }

        [Required]
        [StringLength(50)]
        public string AddressType { get; set; }

        public Guid rowguid { get; set; }

        public DateTime ModifiedDate { get; set; }

        public virtual Address Address { get; set; }

        public virtual Customer Customer { get; set; }
    }
}


text:
package com.dreampany.framework.ui.view;

import android.content.Context;
import android.text.Layout;
import android.text.Spannable;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.Log;
import android.util.Patterns;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.widget.TextView;

public class TextViewClickMovement extends LinkMovementMethod {

    private final String TAG = TextViewClickMovement.class.getSimpleName();

    private final OnTextViewClickMovementListener mListener;
    private final GestureDetector mGestureDetector;
    private TextView mWidget;
    private Spannable mBuffer;

    public enum LinkType {

        /** Indicates that phone link was clicked */
        PHONE,

        /** Identifies that URL was clicked */
        WEB_URL,

        /** Identifies that Email Address was clicked */
        EMAIL_ADDRESS,

        /** Indicates that none of above mentioned were clicked */
        NONE
    }

    /**
     * Interface used to handle Long clicks on the {@link TextView} and taps
     * on the phone, web, mail links inside of {@link TextView}.
     */
    public interface OnTextViewClickMovementListener {

        /**
         * This method will be invoked when user press and hold
         * finger on the {@link TextView}
         *
         * @param linkText Text which contains link on which user presses.
         * @param linkType Type of the link can be one of {@link LinkType} enumeration
         */
        void onLinkClicked(final String linkText, final LinkType linkType);

        /**
         *
         * @param text Whole text of {@link TextView}
         */
        void onLongClick(final String text);
    }

    public TextViewClickMovement(final OnTextViewClickMovementListener listener, final Context context) {
        mListener        = listener;
        mGestureDetector = new GestureDetector(context, new SimpleOnGestureListener());
    }

    @Override
    public boolean onTouchEvent(final TextView widget, final Spannable buffer, final MotionEvent event) {

        mWidget = widget;
        mBuffer = buffer;
        mGestureDetector.onTouchEvent(event);

        return false;
    }

    /**
     * Detects various gestures and events.
     * Notify users when a particular motion event has occurred.
     */
    class SimpleOnGestureListener extends GestureDetector.SimpleOnGestureListener {
        @Override
        public boolean onDown(MotionEvent event) {
            // Notified when a tap occurs.
            return true;
        }

        @Override
        public void onLongPress(MotionEvent e) {
            // Notified when a long press occurs.
            final String text = mBuffer.toString();

            if (mListener != null) {
                Log.d(TAG, "----> Long Click Occurs on TextView with ID: " + mWidget.getId() + "\n" +
                        "Text: " + text + "\n<----");

                mListener.onLongClick(text);
            }
        }

        @Override
        public boolean onSingleTapConfirmed(MotionEvent event) {
            // Notified when tap occurs.
            final String linkText = getLinkText(mWidget, mBuffer, event);

            LinkType linkType = LinkType.NONE;

            if (Patterns.PHONE.matcher(linkText).matches()) {
                linkType = LinkType.PHONE;
            }
            else if (Patterns.WEB_URL.matcher(linkText).matches()) {
                linkType = LinkType.WEB_URL;
            }
            else if (Patterns.EMAIL_ADDRESS.matcher(linkText).matches()) {
                linkType = LinkType.EMAIL_ADDRESS;
            }

            if (mListener != null) {
                Log.d(TAG, "----> Tap Occurs on TextView with ID: " + mWidget.getId() + "\n" +
                        "Link Text: " + linkText + "\n" +
                        "Link Type: " + linkType + "\n<----");

                mListener.onLinkClicked(linkText, linkType);
            }

            return false;
        }

        private String getLinkText(final TextView widget, final Spannable buffer, final MotionEvent event) {

            int x = (int) event.getX();
            int y = (int) event.getY();

            x -= widget.getTotalPaddingLeft();
            y -= widget.getTotalPaddingTop();

            x += widget.getScrollX();
            y += widget.getScrollY();

            Layout layout = widget.getLayout();
            int line = layout.getLineForVertical(y);
            int off = layout.getOffsetForHorizontal(line, x);

            ClickableSpan[] link = buffer.getSpans(off, off, ClickableSpan.class);

            if (link.length != 0) {
                return buffer.subSequence(buffer.getSpanStart(link[0]),
                        buffer.getSpanEnd(link[0])).toString();
            }

            return "";
        }
    }
}


text:
'use strict'

import request from 'superagent'

const API_URL = 'https://graph.facebook.com/v2.7/'
const PROFILE = [
  {
    'method': 'GET',
    'relative_url': 'me?fields=id,name,email,picture'
  },
  {
    'method': 'GET',
    'relative_url': 'me/accounts?fields=id,name,about,category,category_list,access_token,perms,picture,cover'
  }
]
const BATCH_REQUEST = 'batch=' + JSON.stringify(PROFILE)

export function validateUser (fb_uid, access_token) {
  return new Promise((resolve, reject) => {
    request
      .post(`${API_URL}?access_token=${access_token}`)
      .send(BATCH_REQUEST)
      .set('Accept', 'application/json')
      .end((err, res) => {
        if (err) {
          reject(err.response.text)
        } else {
          const ret = res.body.map(i => {
            return JSON.parse(i.body)
          })
          resolve({
            profile: ret[0],
            accounts: ret[1]
          })
        }
      })
  })
}


text:
package com.tc.scriptrunner.config;

public class ScriptRunnerCfg {
	public static final String RHINO_RUNNER="text/javascript";

}