text:
<?php

namespace Sirius\Admin;

abstract class Actuator extends Controller
{
    public $definitions;
    public $table;
    public $columns = array();
    public $orders = array();
    public $groupsToPositions = array();
    public $groups = array(
        'default' => array(
            'title' => 'Genel',
            'position' => 'left'
        ),
        'publish' => array(
            'title' => 'Yayımla',
            'position' => 'right'
        ),
        'meta' => array(
            'title' => 'Meta Bilgileri',
            'position' => 'right'
        )
    );

    public $positions = array(
        'left' => 'col-sm-8',
        'right' => 'col-sm-4'
    );

    public $parent = false;

    private $defaults = array(
        'publish' => array(
            'status' => array(
                'label' => 'Durum',
                'type' => 'dropdown',
                'insert' => true,
                'update' => true,
                'show' => array(
                    'list' => true,
                    'insert' => true,
                    'update' => true
                ),
                'options' => ['published' => 'Yayında', 'unpublished' => 'Yayında Değil'],
                'default' => 'published',
                'styles' => [
                    'published' => 'Yayında',
                    'unpublished' => 'Yayında Değil'
                ],
                'width' => '150'
            ),
            'createdAt' => array(
                'label' => 'Oluşturulma Tarihi',
                'type' => 'datetime',
                'insert' => true,
                'show' => array(
                    'update' => true
                ),
                'group' => 'publish',
                'default' => 'now',
                'disabled' => true
            ),
            'updatedAt' => array(
                'label' => 'Güncellenme Tarihi',
                'type' => 'datetime',
                'update' => true,
                'show' => array(
                    'update' => true
                ),
                'group' => 'publish',
                'default' => 'now',
                'disabled' => true
            )
        ),
        'meta' => array(
            'metaTitle' => array(
                'label' => 'Title',
                'type' => 'text',
                'insert' => true,
                'update' => true,
                'show' => array(
                    'insert' => true,
                    'update' => true
                )

            ),
            'metaDescription' => array(
                'label' => 'Description',
                'type' => 'textarea',
                'insert' => true,
                'update' => true,
                'show' => array(
                    'insert' => true,
                    'update' => true
                )
            ),
            'metaKeywords' => array(
                'label' => 'Keywords',
                'type' => 'textarea',
                'insert' => true,
                'update' => true,
                'show' => array(
                    'insert' => true,
                    'update' => true
                )
            )
        )
    );

    public $images = false;
    public $imageOrders = array();
    public $imageColumns = array(
        'image' => array(
            'label' => 'Görsel',
            'type' => 'image',
            'insert' => true,
            'update' => true,
            'show' => array(
                'list' => true,
                'insert' => true,
                'update' => true
            ),
            'size' => array(480, 360),
            'process' => array(
                'news/images/thumb' => ['thumbnail' => [480, 360]],
                'news/images/normal' => ['best_fit' => [900, 900]]
            ),
            'required' => true
        ),
        'order' => array(
            'label' => 'Sıra',
            'type' => 'order',
            'insert' => true,
            'show' => array(
                'list' => true
            ),
            'sort' => 'asc'
        )
    );

    public function __construct()
    {
        if (empty($this->table)) {
            throw new \Exception('Actuator table tanimlanmamis.');
        }

        if (empty($this->definitions['columns'])) {
            throw new \Exception('Actuator columns tanimlanmamis.');
        }

        $this->model = 'Actuator';

        if (isset($this->definitions['groups'])) {
            $this->groups = array_merge($this->groups, $this->definitions['groups']);
        }

        if (isset($this->definitions['positions'])) {
            $this->positions = array_merge($this->positions, $this->definitions['positions']);
        }

        foreach ($this->groups as $group => $options) {
            if (! isset($this->groupsToPositions[$options['position']])) {
                $this->groupsToPositions[$options['position']] = array();
            }

            $this->groupsToPositions[$options['position']][] = $group;
        }

        if (isset($this->definitions['columns']['meta'])) {
            if ($this->definitions['columns']['meta'] === true) {
                $this->definitions['columns']['meta'] = $this->defaults['meta'];
            } else {
                $this->definitions['columns']['meta'] = array_merge($this->defaults['meta'], $this->definitions['columns']['meta']);
            }
        }

        if (isset($this->definitions['columns']['publish'])) {
            if ($this->definitions['columns']['publish'] === true) {
                $this->definitions['columns']['publish'] = $this->defaults['publish'];
            } else {
                $this->definitions['columns']['publish'] = array_merge($this->defaults['publish'], $this->definitions['columns']['publish']);
            }
        }

        foreach ($this->definitions['columns'] as $group) {
            $this->columns = array_merge($this->columns, $group);
        }

        foreach ($this->columns as $column => $options) {
            if ($options['type'] === 'order') {
                if (! isset($options['sort'])) {
                    throw new \Exception($column. 'alanı siralama yonu tanimlanmamis.');
                }

                $this->orders[$column] = $options['sort'];
            }
        }

        $this->orders['id'] = 'asc';

        if ($this->images === true) {
            foreach ($this->imageColumns as $column => $options) {
                if ($options['type'] === 'order') {
                    if (! isset($options['sort'])) {
                        throw new \Exception($column. 'alanı siralama yonu tanimlanmamis.');
                    }

                    $this->imageOrders[$column] = $options['sort'];
                }
            }
        }

        parent::__construct();
    }

    public function records()
    {
        if ($this->parent === true) {
            /**
             * Eğer parent verilmişse breadcrump hazırlanır.
             * Parent değeri view'a atanır.
             */
            if ($this->uri->segment(4) > 0) {
                if (! $parent = $this->appmodel->find($this->uri->segment(4))) {
                    show_404();
                }

                $this->setParentsBread($parent);
                $this->viewData['parent'] = $parent;
            }
        }

        parent::callRecords([
            'count' => [$this->appmodel, 'count', isset($parent) ? $parent : null],
            'all' => [$this->appmodel, 'all', isset($parent) ? $parent : null]
        ]);
        $this->render('records', true);
    }

    public function insert()
    {
        if ($this->parent === true) {
            /**
             * Eğer parent verilmişse breadcrump hazırlanır.
             * Parent değeri view'a atanır.
             */
            if ($this->uri->segment(4) > 0) {
                if (!$parent = $this->appmodel->find($this->uri->segment(4))) {
                    show_404();
                }

                $this->setParentsBread($parent);
                $this->viewData['parent'] = $parent;
            }
        }

        parent::callInsert([
            'insert' => [$this->appmodel, 'insert', isset($parent) ? $parent : null],
        ]);

        $this->assets->importEditor();
        $this->render('insert', true);
    }

    public function update()
    {
        if ($this->parent === true) {
            /**
             * Eğer parent verilmişse breadcrump hazırlanır.
             * Parent değeri view'a atanır.
             */
            if ($this->uri->segment(4) > 0) {
                if (!$parent = $this->appmodel->find($this->uri->segment(4))) {
                    show_404();
                }

                $this->setParentsBread($parent);
                $this->viewData['parent'] = $parent;
            }
        }

        parent::callUpdate();
        $this->assets->importEditor();
        $this->render('update', true);
    }

    public function delete()
    {
        parent::callDelete();
    }

    public function order()
    {
        parent::callOrder();
    }

    public function validation($action, $record = null)
    {
        $rules = [];

        foreach ($this->columns as $column => $options) {
            if (isset($options['validation'])) {
                if (isset($options['validation'][$action])) {
                    $rules[$column] = $options['validation'][$action];
                } else {
                    $rules[$column] = $options['validation'];
                }
            }

        }
        $this->validate($rules);
    }

    public function validationAfter($action, $record = null)
    {
        foreach ($this->columns as $column => $options) {
            if ($options['type'] === 'image') {
                if ($action === 'insert' && isset($options['required']) && $options['required'] === true) {
                    $this->image->required();
                } else {
                    $this->image->setDefaultImage($record->image);
                }

                if (isset($options['size'])) {
                    if (! is_array($options['size']) || (is_array($options['size']) && count($options['size']) === 1)) {
                        $options['size'] = array((int) $options['size']);
                    }

                    if (count($options['size']) === 1) {
                        $options['size'] = array($options['size'], 0);
                    }

                    $this->image->setMinSizes($options['size'][0], $options['size'][1]);

                }

                foreach ($options['process'] as $path => $opt) {
                    $this->image->addProcess($path, $opt);
                }

                $this->modelData['files'][$column] = $this->image->save();
            }
        }
    }

    private function setParentsBread($record)
    {
        $parents = $this->appmodel->parents($record->id);

        foreach ($parents as $bread){
            $this->utils->breadcrumb($bread['title'], $bread['url']);
        }
    }

    public function images()
    {
        if (! $parent = $this->appmodel->find($this->uri->segment(4))) {
            show_404();
        }

        $this->utils->breadcrumb("{$parent->title}: Resimler", moduleUri('images', $parent->id));

        parent::callRecords(array(
            'count' => [$this->appmodel, 'imageCount', $parent],
            'all' => [$this->appmodel, 'imageAll', $parent]
        ));

        $this->viewData['parent'] = $parent;
        $this->assets->importPlupload();
        $this->render('images/records', true);
    }

    public function imageInsert()
    {
        if (! $parent = $this->appmodel->find($this->uri->segment(4))) {
            $this->json(array(
                'jsonrpc'   => '2.0',
                'error'     => array('code' => '500', 'message' => 'Kayıt bulunamadı.'),
                'id'        => 'id'
            ));
        }

        foreach ($this->imageColumns as $column => $options) {
            if ($options['type'] === 'image') {
                $this->image->required()->usePlupload()->setUploadInput('file');

                if (isset($options['size'])) {
                    if (! is_array($options['size']) || (is_array($options['size']) && count($options['size']) === 1)) {
                        $options['size'] = array((int) $options['size']);
                    }

                    if (count($options['size']) === 1) {
                        $options['size'] = array($options['size'], 0);
                    }

                    $this->image->setMinSizes($options['size'][0], $options['size'][1]);

                }

                foreach ($options['process'] as $path => $opt) {
                    $this->image->addProcess($path, $opt);
                }

                if ($image = $this->image->save()) {
                    $this->modelData['files'][$column] = $image;
                } else {
                    return false;
                }

            }
        }

        $success = $this->appmodel->imageInsert($parent, $this->modelData);

        if ($success) {
            $this->json(array(
                'jsonrpc'   => '2.0',
                'error'     => array(),
                'id'        => 'id'
            ));
        }
    }

    public function imageUpdate()
    {
        if (! $record = $this->appmodel->image($this->uri->segment(4))) {
            show_404();
        }

        $parent = $this->appmodel->find($record->parentId);

        $this->utils->breadcrumb("{$parent->title}: Resimler", moduleUri('images', $parent->id));

        parent::callUpdate([
            'update' => [$this->appmodel, 'imageUpdate'],
            'find' => [$this->appmodel, 'image'],
            'redirect' => ['imageUpdate', '@id']
        ]);

        $this->viewData['parent'] = $parent;
        $this->render('images/update', true);
    }

    public function imageDelete()
    {
        parent::callDelete([
            'delete' => [$this->appmodel, 'imageDelete'],
            'find' => [$this->appmodel, 'image'],
        ]);
    }

    /**
     * Sıralama işlemi yapar
     */
    public function imageOrder()
    {
        parent::callOrder([
            'order' => [$this->appmodel, 'imageOrder']
        ]);
    }

    public function createForm($type, $columns, $record = null)
    {
        $response = '';

        foreach ($columns as $column => $options) {
            if (isset($options['show'][$type]) && $options['show'][$type] === true) {
                $required = isset($options['required']) ? $options['required'] : false;
                $disabled = isset($options['disabled']) ? $options['disabled'] : false;
                $value = null;
                if ($type === 'update' && ! is_null($record)) {
                    $value = $record->$column;
                }

                switch ($options['type']) {
                    case 'textarea': {
                        $response .= bsFormTextarea($column, $options['label'], [
                            'value' => $value,
                            'disabled' => $disabled,
                            'required' => $required
                        ]);
                        break;
                    }
                    case 'dropdown': {
                        $response .= bsFormDropdown($column, $options['label'], [
                            'options' => $options['options'],
                            'value' => $value,
                            'disabled' => $disabled,
                            'required' => $required
                        ]);
                        break;
                    }
                    case 'editor': {
                        $response .= bsFormEditor($column, $options['label'], [
                            'value' => $value,
                            'disabled' => $disabled,
                            'required' => $required
                        ]);
                        break;
                    }
                    case 'image': {
                        $response .= bsFormImage($column, $options['label'], [
                            'value' => $value,
                            'path' => 'public/upload/'.array_keys($options['process'])[0],
                            'disabled' => $disabled,
                            'required' => $required
                        ]);
                        break;
                    }
                    case 'datetime': {
                        $response .= bsFormDatetime($column, $options['label'], [
                            'value' => $value ? $this->date->set($value)->datetimeWithName() : $value,
                            'disabled' => $disabled,
                            'required' => $required
                        ]);
                        break;
                    }
                    default: {
                        $response .= bsFormText($column, $options['label'], [
                            'value' => $value,
                            'disabled' => $disabled,
                            'required' => $required
                        ]);
                    }
                }
            }
        }

        return $response;
    }

}


text:
/*
panelmix.cpp

Commonly used panel related functions
*/
/*
Copyright © 1996 Eugene Roshal
Copyright © 2000 Far Group
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.
3. The name of the authors may not be used to endorse or promote products
   derived from this software without specific prior written permission.

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.
*/

// BUGBUG
#include "platform.headers.hpp"

// Self:
#include "panelmix.hpp"

// Internal:
#include "strmix.hpp"
#include "filepanels.hpp"
#include "config.hpp"
#include "panel.hpp"
#include "ctrlobj.hpp"
#include "keys.hpp"
#include "filelist.hpp"
#include "pathmix.hpp"
#include "panelctype.hpp"
#include "datetime.hpp"
#include "flink.hpp"
#include "plugins.hpp"
#include "lang.hpp"
#include "fileattr.hpp"
#include "cvtname.hpp"
#include "global.hpp"
#include "exception.hpp"
#include "log.hpp"

// Platform:

// Common:
#include "common/enum_tokens.hpp"
#include "common/from_string.hpp"

// External:
#include "format.hpp"

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

static const struct column_info
{
	column_type Type;
	int DefaultWidth;
	const string_view String;
}
ColumnInfo[]
{
	{ column_type::name,                   0,     L"N"sv,     },
	{ column_type::size,                   6,     L"S"sv,     },
	{ column_type::size_compressed,        6,     L"P"sv,     },
	{ column_type::date,                   8,     L"D"sv,     },
	{ column_type::time,                   5,     L"T"sv,     },
	{ column_type::date_write,             14,    L"DM"sv,    },
	{ column_type::date_creation,          14,    L"DC"sv,    },
	{ column_type::date_access,            14,    L"DA"sv,    },
	{ column_type::date_change,            14,    L"DE"sv,    },
	{ column_type::attributes,             6,     L"A"sv,     },
	{ column_type::description,            0,     L"Z"sv,     },
	{ column_type::owner,                  0,     L"O"sv,     },
	{ column_type::links_number,           3,     L"LN"sv,    },
	{ column_type::streams_number,         3,     L"F"sv,     },
	{ column_type::streams_size,           6,     L"G"sv,     },
	{ column_type::extension,              0,     L"X"sv,     },
	{ column_type::custom_0,               0,     L"C0"sv,    },
};

static_assert(std::size(ColumnInfo) == static_cast<size_t>(column_type::count));

void ShellUpdatePanels(panel_ptr SrcPanel, bool NeedSetUpADir)
{
	if (!SrcPanel)
		SrcPanel = Global->CtrlObject->Cp()->ActivePanel();

	auto AnotherPanel = Global->CtrlObject->Cp()->GetAnotherPanel(SrcPanel);

	switch (SrcPanel->GetType())
	{
	case panel_type::FILE_PANEL:
	case panel_type::TREE_PANEL:
		break;

	case panel_type::QVIEW_PANEL:
	case panel_type::INFO_PANEL:
		SrcPanel.swap(AnotherPanel);
	}

	const auto AnotherType = AnotherPanel->GetType();

	if (AnotherType != panel_type::QVIEW_PANEL && AnotherType != panel_type::INFO_PANEL)
	{
		if (NeedSetUpADir)
		{
			AnotherPanel->SetCurDir(SrcPanel->GetCurDir(), true);
			AnotherPanel->Update(UPDATE_KEEP_SELECTION|UPDATE_SECONDARY);
		}
		else
		{
			// TODO: ???
			//if(AnotherPanel->NeedUpdatePanel(SrcPanel))
			//  AnotherPanel->Update(UPDATE_KEEP_SELECTION|UPDATE_SECONDARY);
			//else
			{
				AnotherPanel->UpdateIfChanged();
			}
		}
	}

	SrcPanel->Update(UPDATE_KEEP_SELECTION);

	if (AnotherType == panel_type::QVIEW_PANEL)
		AnotherPanel->Update(UPDATE_KEEP_SELECTION|UPDATE_SECONDARY);

	Global->CtrlObject->Cp()->Redraw();
}

bool CheckUpdateAnotherPanel(panel_ptr SrcPanel, string_view const SelName)
{
	if (!SrcPanel)
		SrcPanel = Global->CtrlObject->Cp()->ActivePanel();

	const auto AnotherPanel = Global->CtrlObject->Cp()->GetAnotherPanel(SrcPanel);
	AnotherPanel->CloseFile();

	if (AnotherPanel->GetMode() == panel_mode::NORMAL_PANEL)
	{
		string strAnotherCurDir(AnotherPanel->GetCurDir());
		AddEndSlash(strAnotherCurDir);
		auto strFullName = ConvertNameToFull(SelName);
		AddEndSlash(strFullName);

		if (contains(strAnotherCurDir, strFullName))
		{
			AnotherPanel->StopFSWatcher();
			return true;
		}
	}

	return false;
}

bool MakePath(const panel_ptr& SrcPanel, bool FilePath, bool RealName, bool ShortNameAsIs, string& strPathName)
{
	if (FilePath)
	{
		string strShortFileName;
		if (!SrcPanel->GetCurName(strPathName, strShortFileName))
			return false;

		if (ShortNameAsIs && SrcPanel->GetShowShortNamesMode()) // учтем короткость имен :-)
			strPathName = strShortFileName;
	}
	else
	{
		if (!(SrcPanel->GetType() == panel_type::FILE_PANEL || SrcPanel->GetType() == panel_type::TREE_PANEL))
			return false;

		strPathName = SrcPanel->GetCurDir();

		if (SrcPanel->GetMode() != panel_mode::PLUGIN_PANEL)
		{
			if (RealName)
				strPathName = SrcPanel->CreateFullPathName(strPathName, true, true, ShortNameAsIs);

			if (SrcPanel->GetShowShortNamesMode() && ShortNameAsIs)
				strPathName = ConvertNameToShort(strPathName);
		}
		else
		{
			if (const auto SrcFileList = std::dynamic_pointer_cast<FileList>(SrcPanel))
			{
				OpenPanelInfo Info;
				Global->CtrlObject->Plugins->GetOpenPanelInfo(SrcFileList->GetPluginHandle(), &Info);
				strPathName = SrcFileList->GetPluginPrefix();
				if (Info.HostFile && *Info.HostFile)
				{
					append(strPathName, Info.HostFile, L'/');
				}
				strPathName += NullToEmpty(Info.CurDir);
			}
		}

		AddEndSlash(strPathName);
	}

	return true;
}

bool MakePathForUI(DWORD Key, string &strPathName)
{
	auto RealName = false;

	switch (Key)
	{
	case KEY_CTRLALTBRACKET:       // Вставить сетевое (UNC) путь из левой панели
	case KEY_RCTRLRALTBRACKET:
	case KEY_CTRLRALTBRACKET:
	case KEY_RCTRLALTBRACKET:
	case KEY_CTRLALTBACKBRACKET:   // Вставить сетевое (UNC) путь из правой панели
	case KEY_RCTRLRALTBACKBRACKET:
	case KEY_CTRLRALTBACKBRACKET:
	case KEY_RCTRLALTBACKBRACKET:
	case KEY_ALTSHIFTBRACKET:      // Вставить сетевое (UNC) путь из активной панели
	case KEY_RALTSHIFTBRACKET:
	case KEY_ALTSHIFTBACKBRACKET:  // Вставить сетевое (UNC) путь из пассивной панели
	case KEY_RALTSHIFTBACKBRACKET:
		RealName = true;
		[[fallthrough]];
	case KEY_CTRLBRACKET:          // Вставить путь из левой панели
	case KEY_RCTRLBRACKET:
	case KEY_CTRLBACKBRACKET:      // Вставить путь из правой панели
	case KEY_RCTRLBACKBRACKET:
	case KEY_CTRLSHIFTBRACKET:     // Вставить путь из активной панели
	case KEY_RCTRLSHIFTBRACKET:
	case KEY_CTRLSHIFTBACKBRACKET: // Вставить путь из пассивной панели
	case KEY_RCTRLSHIFTBACKBRACKET:
	case KEY_CTRLSHIFTNUMENTER:    // Текущий файл с пасс.панели
	case KEY_RCTRLSHIFTNUMENTER:
	case KEY_SHIFTNUMENTER:        // Текущий файл с актив.панели
	case KEY_CTRLSHIFTENTER:       // Текущий файл с пасс.панели
	case KEY_RCTRLSHIFTENTER:
	case KEY_SHIFTENTER:           // Текущий файл с актив.панели
		{
			panel_ptr SrcPanel;
			const auto Cp = Global->CtrlObject->Cp();

			switch (Key)
			{
			case KEY_CTRLALTBRACKET:
			case KEY_RCTRLRALTBRACKET:
			case KEY_CTRLRALTBRACKET:
			case KEY_RCTRLALTBRACKET:
			case KEY_CTRLBRACKET:
			case KEY_RCTRLBRACKET:
				SrcPanel = Cp->LeftPanel();
				break;

			case KEY_CTRLALTBACKBRACKET:
			case KEY_RCTRLRALTBACKBRACKET:
			case KEY_CTRLRALTBACKBRACKET:
			case KEY_RCTRLALTBACKBRACKET:
			case KEY_CTRLBACKBRACKET:
			case KEY_RCTRLBACKBRACKET:
				SrcPanel = Cp->RightPanel();
				break;

			case KEY_SHIFTNUMENTER:
			case KEY_SHIFTENTER:
			case KEY_ALTSHIFTBRACKET:
			case KEY_RALTSHIFTBRACKET:
			case KEY_CTRLSHIFTBRACKET:
			case KEY_RCTRLSHIFTBRACKET:
				SrcPanel = Cp->ActivePanel();
				break;

			case KEY_CTRLSHIFTNUMENTER:
			case KEY_RCTRLSHIFTNUMENTER:
			case KEY_CTRLSHIFTENTER:
			case KEY_RCTRLSHIFTENTER:
			case KEY_ALTSHIFTBACKBRACKET:
			case KEY_RALTSHIFTBACKBRACKET:
			case KEY_CTRLSHIFTBACKBRACKET:
			case KEY_RCTRLSHIFTBACKBRACKET:
				SrcPanel = Cp->PassivePanel();
				break;
			}

			const auto FilePath = any_of(Key, KEY_SHIFTENTER, KEY_CTRLSHIFTENTER, KEY_RCTRLSHIFTENTER, KEY_SHIFTNUMENTER, KEY_CTRLSHIFTNUMENTER, KEY_RCTRLSHIFTNUMENTER);
			if (!SrcPanel || !MakePath(SrcPanel, FilePath, RealName, true, strPathName))
				return false;

			if (Global->Opt->QuotedName & QUOTEDNAME_INSERT)
				inplace::QuoteSpace(strPathName);

			return true;
		}

	default:
		return false;
	}
}

std::vector<column> DeserialiseViewSettings(string_view const ColumnTitles, string_view const ColumnWidths)
{
	// BUGBUG, add error checking

	std::vector<column> Columns;

	for (const auto& Type: enum_tokens(ColumnTitles, L","sv))
	{
		if (Type.empty())
			continue;

		column NewColumn{};

		if (Type.front() == L'N')
		{
			NewColumn.type = column_type::name;

			for (const auto& i: Type.substr(1))
			{
				switch (i)
				{
				case L'M': NewColumn.type_flags |= COLFLAGS_MARK;               break;
				case L'D': NewColumn.type_flags |= COLFLAGS_MARK_DYNAMIC;       break;
				case L'O': NewColumn.type_flags |= COLFLAGS_NAMEONLY;           break;
				case L'R': NewColumn.type_flags |= COLFLAGS_RIGHTALIGN;         break;
				case L'F': NewColumn.type_flags |= COLFLAGS_RIGHTALIGNFORCE;    break;
				case L'N': NewColumn.type_flags |= COLFLAGS_NOEXTENSION;        break;
				}
			}
		}
		else if (Type.front() == L'S' || Type.front() == L'P' || Type.front() == L'G')
		{
			NewColumn.type = Type.front() == L'S'?
				column_type::size :
				Type.front() == L'P'?
					column_type::size_compressed :
					column_type::streams_size;

			for (const auto& i: Type.substr(1))
			{
				switch (i)
				{
				case L'C': NewColumn.type_flags |= COLFLAGS_GROUPDIGITS;    break;
				case L'E': NewColumn.type_flags |= COLFLAGS_ECONOMIC;       break;
				case L'F': NewColumn.type_flags |= COLFLAGS_FLOATSIZE;      break;
				case L'T': NewColumn.type_flags |= COLFLAGS_THOUSAND;       break;
				}
			}
		}
		else if (
			starts_with(Type, L"DM"sv) ||
			starts_with(Type, L"DC"sv) ||
			starts_with(Type, L"DA"sv) ||
			starts_with(Type, L"DE"sv))
		{
			switch (Type[1])
			{
			case L'M': NewColumn.type = column_type::date_write;      break;
			case L'C': NewColumn.type = column_type::date_creation;   break;
			case L'A': NewColumn.type = column_type::date_access;     break;
			case L'E': NewColumn.type = column_type::date_change;     break;
			}

			for (const auto& i: Type.substr(2))
			{
				switch (i)
				{
				case L'B': NewColumn.type_flags |= COLFLAGS_BRIEF;    break;
				case L'M': NewColumn.type_flags |= COLFLAGS_MONTH;    break;
				}
			}
		}
		else if (Type.front() == L'O')
		{
			NewColumn.type = column_type::owner;

			if (Type.size() > 1 && Type[1] == L'L')
				NewColumn.type_flags |= COLFLAGS_FULLOWNER;
		}
		else if (Type.front() == L'X')
		{
			NewColumn.type = column_type::extension;

			if (Type.size() > 1 && Type[1] == L'R')
				NewColumn.type_flags |= COLFLAGS_RIGHTALIGN;
		}
		else if (Type.size() > 2 && Type.front() == L'<' && Type.back() == L'>')
		{
			NewColumn.title = Type.substr(1, Type.size() - 2);
			NewColumn.type = column_type::custom_0;
		}
		else
		{
			const auto ItemIterator = std::find_if(CONST_RANGE(ColumnInfo, i) { return Type == i.String; });
			if (ItemIterator != std::cend(ColumnInfo))
				NewColumn.type = ItemIterator->Type;
			else if (Type.size() >= 2 && Type.size() <= 3 && Type.front() == L'C')
			{
				size_t Index;
				if (from_string(Type.substr(1), Index))
					NewColumn.type = static_cast<column_type>(static_cast<size_t>(column_type::custom_0) + Index);
				else
				{
					LOGWARNING(L"Incorrect custom column {}"sv, Type);
					// TODO: error message?
				}
			}
			else
			{
				LOGWARNING(L"Unknown column type {}"sv, Type);
				// TODO: error message?
				continue;
			}
		}

		Columns.emplace_back(NewColumn);
	}

	enum_tokens const EnumWidths(ColumnWidths, L","sv);
	range EnumWidthsRange(EnumWidths);

	for (auto& i: Columns)
	{
		auto Width = L""sv;

		if (!EnumWidthsRange.empty())
		{
			Width = EnumWidthsRange.front();
			EnumWidthsRange.pop_front();
		}

		// "column types" is a determinant here (see the loop header) so we can't break or continue here -
		// if "column sizes" ends earlier or if user entered two commas we just use default size.
		if (!Width.empty() && !from_string(Width, i.width))
		{
			LOGWARNING(L"Incorrect column width {}"sv, Width);
		}

		i.width_type = col_width::fixed;

		if (Width.size()>1)
		{
			switch (Width.back())
			{
				case L'%':
					i.width_type = col_width::percent;
					break;
			}
		}
	}

	if (Columns.empty())
	{
		Columns.emplace_back();
	}

	return Columns;
}

std::pair<string, string> SerialiseViewSettings(const std::vector<column>& Columns)
{
	std::pair<string, string> Result;
	auto& [strColumnTitles, strColumnWidths] = Result;

	const auto GetModeSymbol = [](FILEPANEL_COLUMN_FLAGS Mode)
	{
		switch (Mode)
		{
		case COLFLAGS_MARK:            return L'M';
		case COLFLAGS_NAMEONLY:        return L'O';
		case COLFLAGS_RIGHTALIGN:      return L'R';
		case COLFLAGS_GROUPDIGITS:     return L'C';
		case COLFLAGS_THOUSAND:        return L'T';
		case COLFLAGS_BRIEF:           return L'B';
		case COLFLAGS_MONTH:           return L'M';
		case COLFLAGS_FLOATSIZE:       return L'F';
		case COLFLAGS_ECONOMIC:        return L'E';
		case COLFLAGS_FULLOWNER:       return L'L';
		case COLFLAGS_NOEXTENSION:     return L'N';
		case COLFLAGS_RIGHTALIGNFORCE: return L'F';
		case COLFLAGS_MARK_DYNAMIC:    return L'D';
		default:
			throw MAKE_FAR_FATAL_EXCEPTION(format(FSTR(L"Unexpected mode {}"sv), std::to_underlying(Mode)));
		}
	};

	for (const auto& i: Columns)
	{
		string strType;

		if (i.type <= column_type::custom_0)
		{
			strType = ColumnInfo[static_cast<size_t>(i.type)].String;
		}
		else
		{
			strType = L'C' + str(static_cast<size_t>(i.type) - static_cast<size_t>(column_type::custom_0));
		}

		const auto AddFlag = [&](auto Flag)
		{
			if (!(i.type_flags & Flag))
				return false;
			strType += GetModeSymbol(Flag);
			return true;
		};

		switch (i.type)
		{
		case column_type::name:
			AddFlag(COLFLAGS_MARK) && AddFlag(COLFLAGS_MARK_DYNAMIC);
			AddFlag(COLFLAGS_NAMEONLY);
			AddFlag(COLFLAGS_RIGHTALIGN) && AddFlag(COLFLAGS_RIGHTALIGNFORCE);
			AddFlag(COLFLAGS_NOEXTENSION);
			break;

		case column_type::size:
		case column_type::size_compressed:
		case column_type::streams_size:
			AddFlag(COLFLAGS_GROUPDIGITS);
			AddFlag(COLFLAGS_ECONOMIC);
			AddFlag(COLFLAGS_FLOATSIZE);
			AddFlag(COLFLAGS_THOUSAND);
			break;

		case column_type::date_write:
		case column_type::date_access:
		case column_type::date_creation:
		case column_type::date_change:
			AddFlag(COLFLAGS_BRIEF);
			AddFlag(COLFLAGS_MONTH);
			break;

		case column_type::owner:
			AddFlag(COLFLAGS_FULLOWNER);
			break;

		case column_type::extension:
			AddFlag(COLFLAGS_RIGHTALIGN);
			break;

		case column_type::custom_0:
			if(!i.title.empty())
				strType = concat(L'<', i.title, L'>');
			break;

		default:
			break;
		}

		strColumnTitles += strType;

		strColumnWidths += str(i.width);

		switch (i.width_type)
		{
			case col_width::percent:
				strColumnWidths += L'%';
				break;

			case col_width::fixed:
				break;
		}

		strColumnTitles += L',';
		strColumnWidths += L',';
	}

	if (!strColumnTitles.empty())
		strColumnTitles.pop_back();
	if (!strColumnWidths.empty())
		strColumnWidths.pop_back();

	return Result;
}

string FormatStr_Attribute(os::fs::attributes FileAttributes, size_t const Width)
{
	string OutStr;

	if (!FileAttributes)
		FileAttributes = FILE_ATTRIBUTE_NORMAL;

	enum_attributes([&](os::fs::attributes const Attribute, wchar_t const Character)
	{
		if (FileAttributes & Attribute)
		{
			OutStr.push_back(Character);
		}
		return OutStr.size() < Width;
	});

	inplace::fit_to_left(OutStr, Width);
	return OutStr;
}

string FormatStr_DateTime(os::chrono::time_point FileTime, column_type const ColumnType, unsigned long long Flags, int Width)
{
	if (Width < 0)
	{
		if (ColumnType == column_type::date)
			Width=0;
		else
			return {};
	}

	int ColumnWidth=Width;
	bool Brief = (Flags & COLFLAGS_BRIEF) != 0;
	bool TextMonth = (Flags & COLFLAGS_MONTH) != 0;
	bool FullYear = false;

	switch(ColumnType)
	{
		case column_type::date:
		case column_type::time:
		{
			Brief = false;
			TextMonth = false;
			if (ColumnType == column_type::date)
				FullYear=ColumnWidth>9;
			break;
		}
		case column_type::date_write:
		case column_type::date_creation:
		case column_type::date_access:
		case column_type::date_change:
		{
			if (!Brief)
			{
				const auto CmpWidth = ColumnWidth - (TextMonth? 1 : 0);

				if (CmpWidth==15 || CmpWidth==16 || CmpWidth==18 || CmpWidth==19 || CmpWidth>21)
					FullYear = true;
			}
			ColumnWidth-=9;
			break;
		}

		default:
			break;
	}

	const auto& [Date, Time] = ConvertDate(FileTime, ColumnWidth, FullYear, Brief, TextMonth);

	string OutStr;

	switch(ColumnType)
	{
		case column_type::date:
			OutStr = Date;
			break;

		case column_type::time:
			OutStr = Time;
			break;

		default:
			OutStr = concat(Date, L' ', Time);
			break;
	}

	return fit_to_right(OutStr, Width);
}

string FormatStr_Size(
	long long const Size,
	string_view const strName,
	os::fs::attributes const FileAttributes,
	DWORD const ShowFolderSize,
	DWORD const ReparseTag,
	column_type const ColumnType,
	unsigned long long const Flags,
	int Width,
	string_view const CurDir)
{
	string strResult;

	const auto Streams = ColumnType == column_type::streams_size;

	if (ShowFolderSize==2)
	{
		Width--;
		strResult += L'~';
	}

	const auto dir = (0 != (FileAttributes & FILE_ATTRIBUTE_DIRECTORY));
	const auto rpt = (0 != (FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT));
	const auto have_size = !dir && (!rpt || ReparseTag==IO_REPARSE_TAG_DEDUP || Size > 0);

	if (!Streams && !have_size && !ShowFolderSize)
	{
		static const lng FolderLabels[] =
		{
			lng::MListUp,
			lng::MListFolder,
		};

		const auto LabelSize = msg(*std::max_element(ALL_CONST_RANGE(FolderLabels), [](lng a, lng b) { return msg(a).size() < msg(b).size(); })).size();

		string TypeName;

		if (IsParentDirectory(strName))
		{
			TypeName = fit_to_center(msg(lng::MListUp), LabelSize);
		}
		else
		{
			if (rpt)
			{
				switch(ReparseTag)
				{
				// Directory Junction or Volume Mount Point
				case IO_REPARSE_TAG_MOUNT_POINT:
					{
						auto ID_Msg = lng::MListJunction;
						if (Global->Opt->PanelDetailedJunction && !CurDir.empty())
						{
							string strLinkName;
							if (GetReparsePointInfo(path::join(CurDir, PointToName(strName)), strLinkName))
							{
								NormalizeSymlinkName(strLinkName);
								bool Root;
								if(ParsePath(strLinkName, nullptr, &Root) == root_type::volume && Root)
								{
									ID_Msg = lng::MListVolMount;
								}
							}
						}
						TypeName=msg(ID_Msg);
					}
					break;

				default:
					if (!reparse_tag_to_string(ReparseTag, TypeName) && !Global->Opt->ShowUnknownReparsePoint)
						TypeName = msg(lng::MListUnknownReparsePoint);
					break;
				}
			}
			else if (dir)
			{
				TypeName = fit_to_center(msg(lng::MListFolder), LabelSize);
			}
		}

		if (static_cast<int>(TypeName.size()) <= Width-2 && msg(lng::MListBrackets).size() > 1)
		{
			TypeName = concat(msg(lng::MListBrackets)[0], TypeName, msg(lng::MListBrackets)[1]);
		}
		strResult += fit_to_right(TypeName, Width);
	}
	else
	{
		strResult += FileSizeToStr(Size, Width, Flags);
	}

	return strResult;
}

int GetDefaultWidth(const column& Column)
{
	int Width = (Column.type > column_type::custom_0)? 0 : ColumnInfo[static_cast<size_t>(Column.type)].DefaultWidth;

	if (
		Column.type == column_type::date_write ||
		Column.type == column_type::date_creation ||
		Column.type == column_type::date_access ||
		Column.type == column_type::date_change
	)
	{
		if (Column.type_flags & COLFLAGS_BRIEF)
			Width -= 3;

		if (Column.type_flags & COLFLAGS_MONTH)
			++Width;
	}
	return Width;
}

redpajama_set_name: RedPajamaGithub


text:
Use [Rabl](https://github.com/nesquena/rabl) templates in [Grape](https://github.com/intridea/grape)!

[![Build Status](https://secure.travis-ci.org/LTe/grape-rabl.png)](http://travis-ci.org/LTe/grape-rabl) [![Dependency Status](https://gemnasium.com/LTe/grape-rabl.png)](https://gemnasium.com/LTe/grape-rabl)

## Installation

Add the `grape` and `grape-rabl` gems to Gemfile.

```ruby
gem 'grape', "~> 0.2.3"
gem 'grape-rabl'
```

And then execute:

    $ bundle

## Usage

### Require grape-rabl

```ruby
# config.ru
require 'grape/rabl'
```

### Setup view root directory
```ruby
# config.ru
require 'grape/rabl'

use Rack::Config do |env|
  env['api.tilt.root'] = '/path/to/view/root/directory'
end
```

### Tell your API to use Grape::Formatter::Rabl

```ruby
class API < Grape::API
  format :json
  formatter :json, Grape::Formatter::Rabl
end
```

### Use rabl templates conditionally

Add the template name to the API options.

```ruby
get "/user/:id", :rabl => "user.rabl" do
  @user = User.find(params[:id])
end
```

You can use instance variables in the Rabl template.

```ruby
object @user => :user
attributes :name, :email

child @project => :project do
  attributes :name
end
```

## You can omit .rabl

The following are identical.

```ruby
get "/home", :rabl => "view"
get "/home", :rabl => "view.rabl"
```

### Example

```ruby
# config.ru
require 'grape/rabl'

use Rack::Config do |env|
  env['api.tilt.root'] = '/path/to/view/root/directory'
end

class UserAPI < Grape::API
  format :json
  formatter :json, Grape::Formatter::Rabl

  # use rabl with 'user.rabl' template
  get '/user/:id', :rabl => 'user' do
    @user = User.find(params[:id])
  end

  # do not use rabl, fallback to the defalt Grape JSON formatter
  get '/users' do
    User.all
  end
end
```

```ruby
# user.rabl
object @user => :user

attributes :name
```

## Usage with rails

Create grape application

```ruby
# app/api/user.rb
class MyAPI < Grape::API
  format :json
  formatter :json, Grape::Formatter::Rabl
  get '/user/:id', :rabl => "user" do
    @user = User.find(params[:id])
  end
end
```

```ruby
# app/views/api/user.rabl
object @user => :user
```

Edit your **config/application.rb** and add view path

```ruby
# application.rb
class Application < Rails::Application
  config.middleware.use(Rack::Config) do |env|
    env['api.tilt.root'] = Rails.root.join "app", "views", "api"
  end
end
```

Mount application to rails router

```ruby
# routes.rb
GrapeExampleRails::Application.routes.draw do
  mount MyAPI , :at => "/api"
end
```

## Rspec

See "Writing Tests" in https://github.com/intridea/grape.

Enjoy :)

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Added some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
namespace proximity_auth {

TEST(ProximityAuthWireMessage, Deserialize_EmptyMessage) {
  bool is_incomplete;
  scoped_ptr<WireMessage> message =
      WireMessage::Deserialize(std::string(), &is_incomplete);
  EXPECT_TRUE(is_incomplete);
  EXPECT_FALSE(message);
}

TEST(ProximityAuthWireMessage, Deserialize_IncompleteHeader) {
  bool is_incomplete;
  scoped_ptr<WireMessage> message =
      WireMessage::Deserialize("\3", &is_incomplete);
  EXPECT_TRUE(is_incomplete);
  EXPECT_FALSE(message);
}

TEST(ProximityAuthWireMessage, Deserialize_UnexpectedMessageFormatVersion) {
  bool is_incomplete;
  // Version 2 is below the minimum supported version.
  scoped_ptr<WireMessage> message =
      WireMessage::Deserialize("\2\1\1", &is_incomplete);
  EXPECT_FALSE(is_incomplete);
  EXPECT_FALSE(message);
}

TEST(ProximityAuthWireMessage, Deserialize_BodyOfSizeZero) {
  bool is_incomplete;
  scoped_ptr<WireMessage> message =
      WireMessage::Deserialize(std::string("\3\0\0", 3), &is_incomplete);
  EXPECT_FALSE(is_incomplete);
  EXPECT_FALSE(message);
}

TEST(ProximityAuthWireMessage, Deserialize_IncompleteBody) {
  bool is_incomplete;
  scoped_ptr<WireMessage> message =
      WireMessage::Deserialize(std::string("\3\0\5", 3), &is_incomplete);
  EXPECT_TRUE(is_incomplete);
  EXPECT_FALSE(message);
}

TEST(ProximityAuthWireMessage, Deserialize_BodyLongerThanSpecifiedInHeader) {
  bool is_incomplete;
  scoped_ptr<WireMessage> message = WireMessage::Deserialize(
      std::string("\3\0\5", 3) + "123456", &is_incomplete);
  EXPECT_FALSE(is_incomplete);
  EXPECT_FALSE(message);
}

TEST(ProximityAuthWireMessage, Deserialize_BodyIsNotValidJSON) {
  bool is_incomplete;
  scoped_ptr<WireMessage> message = WireMessage::Deserialize(
      std::string("\3\0\5", 3) + "12345", &is_incomplete);
  EXPECT_FALSE(is_incomplete);
  EXPECT_FALSE(message);
}

TEST(ProximityAuthWireMessage, Deserialize_BodyIsNotADictionary) {
  bool is_incomplete;
  std::string header("\3\0\x29", 3);
  std::string bytes =
      header + "[{\"permit_id\": \"Hi!\", \"payload\": \"YQ==\"}]";
  scoped_ptr<WireMessage> message =
      WireMessage::Deserialize(bytes, &is_incomplete);
  EXPECT_FALSE(is_incomplete);
  EXPECT_FALSE(message);
}

// The permit ID is optional.
TEST(ProximityAuthWireMessage, Deserialize_BodyLacksPermitId) {
  bool is_incomplete;
  std::string header("\3\0\x13", 3);
  std::string bytes = header + "{\"payload\": \"YQ==\"}";
  scoped_ptr<WireMessage> message =
      WireMessage::Deserialize(bytes, &is_incomplete);
  EXPECT_FALSE(is_incomplete);
  EXPECT_TRUE(message);
  EXPECT_EQ(std::string(), message->permit_id());
  EXPECT_EQ("a", message->payload());
}

TEST(ProximityAuthWireMessage, Deserialize_BodyLacksPayload) {
  bool is_incomplete;
  std::string header("\3\0\x14", 3);
  std::string bytes = header + "{\"permit_id\": \"Hi!\"}";
  scoped_ptr<WireMessage> message =
      WireMessage::Deserialize(bytes, &is_incomplete);
  EXPECT_FALSE(is_incomplete);
  EXPECT_FALSE(message);
}

// The permit ID is optional.
TEST(ProximityAuthWireMessage, Deserialize_BodyHasEmptyPermitId) {
  bool is_incomplete;
  std::string header("\3\0\x24", 3);
  std::string bytes = header + "{\"permit_id\": \"\", \"payload\": \"YQ==\"}";
  scoped_ptr<WireMessage> message =
      WireMessage::Deserialize(bytes, &is_incomplete);
  EXPECT_FALSE(is_incomplete);
  EXPECT_TRUE(message);
  EXPECT_EQ(std::string(), message->permit_id());
  EXPECT_EQ("a", message->payload());
}

TEST(ProximityAuthWireMessage, Deserialize_BodyHasEmptyPayload) {
  bool is_incomplete;
  std::string header("\3\0\x23", 3);
  std::string bytes = header + "{\"permit_id\": \"Hi!\", \"payload\": \"\"}";
  scoped_ptr<WireMessage> message =
      WireMessage::Deserialize(bytes, &is_incomplete);
  EXPECT_FALSE(is_incomplete);
  EXPECT_FALSE(message);
}

TEST(ProximityAuthWireMessage, Deserialize_PayloadIsNotBase64Encoded) {
  bool is_incomplete;
  std::string header("\3\0\x2A", 3);
  std::string bytes =
      header + "{\"permit_id\": \"Hi!\", \"payload\": \"garbage\"}";
  scoped_ptr<WireMessage> message =
      WireMessage::Deserialize(bytes, &is_incomplete);
  EXPECT_FALSE(is_incomplete);
  EXPECT_FALSE(message);
}

TEST(ProximityAuthWireMessage, Deserialize_ValidMessage) {
  bool is_incomplete;
  std::string header("\3\0\x27", 3);
  std::string bytes =
      header + "{\"permit_id\": \"Hi!\", \"payload\": \"YQ==\"}";
  scoped_ptr<WireMessage> message =
      WireMessage::Deserialize(bytes, &is_incomplete);
  EXPECT_FALSE(is_incomplete);
  ASSERT_TRUE(message);
  EXPECT_EQ("Hi!", message->permit_id());
  EXPECT_EQ("a", message->payload());
}

TEST(ProximityAuthWireMessage, Deserialize_ValidMessageWithBase64UrlEncoding) {
  bool is_incomplete;
  std::string header("\3\0\x27", 3);
  std::string bytes =
      header + "{\"permit_id\": \"Hi!\", \"payload\": \"_-Y=\"}";
  scoped_ptr<WireMessage> message =
      WireMessage::Deserialize(bytes, &is_incomplete);
  EXPECT_FALSE(is_incomplete);
  ASSERT_TRUE(message);
  EXPECT_EQ("Hi!", message->permit_id());
  EXPECT_EQ("\xFF\xE6", message->payload());
}

TEST(ProximityAuthWireMessage, Deserialize_ValidMessageWithExtraUnknownFields) {
  bool is_incomplete;
  std::string header("\3\0\x46", 3);
  std::string bytes = header +
                      "{"
                      "  \"permit_id\": \"Hi!\","
                      "  \"payload\": \"YQ==\","
                      "  \"unexpected\": \"surprise!\""
                      "}";
  scoped_ptr<WireMessage> message =
      WireMessage::Deserialize(bytes, &is_incomplete);
  EXPECT_FALSE(is_incomplete);
  ASSERT_TRUE(message);
  EXPECT_EQ("Hi!", message->permit_id());
  EXPECT_EQ("a", message->payload());
}

TEST(ProximityAuthWireMessage, Deserialize_SizeEquals0x01FF) {
  // Create a message with a body of 0x01FF bytes to test the size contained in
  // the header is parsed correctly.
  std::string header("\3\x01\xff", 3);
  char json_template[] = "{\"payload\":\"YQ==\", \"filler\":\"$1\"}";
  // Add 3 to the size to take into account the "$1" and NUL terminator ("\0")
  // characters in |json_template|.
  uint16_t filler_size = 0x01ff - sizeof(json_template) + 3;
  std::string filler(filler_size, 'F');

  std::string body = base::ReplaceStringPlaceholders(
      json_template, std::vector<std::string>(1u, filler), nullptr);
  std::string serialized_message = header + body;

  bool is_incomplete;
  scoped_ptr<WireMessage> message =
      WireMessage::Deserialize(serialized_message, &is_incomplete);
  EXPECT_FALSE(is_incomplete);
  ASSERT_TRUE(message);
  EXPECT_EQ("a", message->payload());
}

TEST(ProximityAuthWireMessage, Serialize_WithPermitId) {
  WireMessage message1("example payload", "example id");
  std::string bytes = message1.Serialize();
  ASSERT_FALSE(bytes.empty());

  bool is_incomplete;
  scoped_ptr<WireMessage> message2 =
      WireMessage::Deserialize(bytes, &is_incomplete);
  EXPECT_FALSE(is_incomplete);
  ASSERT_TRUE(message2);
  EXPECT_EQ("example id", message2->permit_id());
  EXPECT_EQ("example payload", message2->payload());
}

TEST(ProximityAuthWireMessage, Serialize_WithoutPermitId) {
  WireMessage message1("example payload");
  std::string bytes = message1.Serialize();
  ASSERT_FALSE(bytes.empty());

  bool is_incomplete;
  scoped_ptr<WireMessage> message2 =
      WireMessage::Deserialize(bytes, &is_incomplete);
  EXPECT_FALSE(is_incomplete);
  ASSERT_TRUE(message2);
  EXPECT_EQ(std::string(), message2->permit_id());
  EXPECT_EQ("example payload", message2->payload());
}

TEST(ProximityAuthWireMessage, Serialize_FailsWithoutPayload) {
  WireMessage message1(std::string(), "example id");
  std::string bytes = message1.Serialize();
  EXPECT_TRUE(bytes.empty());
}

}  // namespace proximity_auth


text:
'use strict';

module.exports = function(grunt) {
  grunt.task.registerMultiTask('ng_html_snapshot', function() {
    var phantom = require('phantomjs');

    var childProcess = require('child_process');

    var options = this.options();

    // Default parameters

    options.pageLoadingTimeout = options.pageLoadingTimeout || 100;

    options.pageDocType = options.pageDocType || '<!doctype html>';

    options.jobPath = options.jobPath || './node_modules/grunt-ng-html-snapshot/utils/phantom-job.js';

    options.removeMetaFragment =  options.removeMetaFragment === undefined ? true : !!options.removeMetaFragment;

    childProcess.execFileSync(
      phantom.path,

      [options.jobPath, JSON.stringify(options)],

      {
        timeout: 300000
      }
    );
  });
};


text:
$('#btnbuscar').on ('click',function(){
	//alert('presionando boton');

	 var buscar=$('#txtbuscarcliente').val();
//alert(buscar);

$.post(baseurl+"Cajax/buscarcliente",

	{id : buscar},
       function(data){
       	//alert();

		if(data==0){
			console.log(data);
			$('#formcliente').removeClass('hide');

			$('#identidad').val(buscar);
			$('.contenedor_json').addClass('hide');

		}else{
			//alert(data.nombres);

			 var obj=JSON.parse(data);

			 console.log(obj[0].nombres);

			$.each(obj,function(i,items){
				$(".contenedor_json").append(' El Cliente ' + items.nombres+ ' Ya se encuentra registrado..');
			});

			//$('#formcliente').addClass('hide');*/

		}

});
});

$('#insertcliente').submit(function(){

	var dato=$('#insertcliente').serialize();

$.ajax({

	url:baseurl+'Cajax/ingresarCliente',

	type:'POST',
	data:dato,
	success:function(data){
		alert(data);
		if(data){
			$('#msn').removeClass('hide');
		}

	}
	});

});


text:
package org.envbuild.generator.factory;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author kovlyashenko
 */
public class RandomizerFactory {

    private Map<Class, ValueRandomizer> randomizersMap = new HashMap<Class, ValueRandomizer>();
	private EnumRandomizerFactory enumRandomizerFactory = new EnumRandomizerFactory();

    public <T> ValueRandomizer<T> getRandomizer(Class<T> generateClass) {
		if (generateClass.isEnum()) {
			return (ValueRandomizer<T>) enumRandomizerFactory.getRandomizer(generateClass.asSubclass(Enum.class));
		} else {
			return randomizersMap.get(generateClass);
		}
    }

    public void initialize() {
        randomizersMap.put(Integer.class, new IntegerRandomizer());
        randomizersMap.put(Long.class, new LongRandomizer());
        randomizersMap.put(Double.class, new DoubleRandomizer());
        randomizersMap.put(Byte.class, new ByteRandomizer());
        randomizersMap.put(Short.class, new ShortRandomizer());
        randomizersMap.put(String.class, new StringRandomizer());
        randomizersMap.put(Boolean.class, new BooleanRandomizer());
        randomizersMap.put(Date.class, new DateRandomizer());
        randomizersMap.put(BigInteger.class, new BigIntegerRandomizer());
        randomizersMap.put(BigDecimal.class, new BigDecimalRandomizer());
        randomizersMap.put(Float.class, new FloatRandomizer());
        //fill primitive types
        randomizersMap.put(Integer.TYPE, randomizersMap.get(Integer.class));
        randomizersMap.put(Long.TYPE, randomizersMap.get(Long.class));
        randomizersMap.put(Double.TYPE, randomizersMap.get(Double.class));
        randomizersMap.put(Byte.TYPE, randomizersMap.get(Byte.class));
        randomizersMap.put(Short.TYPE, randomizersMap.get(Short.class));
        randomizersMap.put(Boolean.TYPE, randomizersMap.get(Boolean.class));
        randomizersMap.put(Float.TYPE, randomizersMap.get(Float.class));
    }

    public boolean hasRandomizer(Class generateClass) {
        return generateClass.isEnum() || randomizersMap.containsKey(generateClass);
    }

}


text:
'use strict';

var request = require('./../../util/request'),
    Promise = require('promise');

/**
 * Module containing Viswax functions
 * @module Viswax
 */
function Viswax() {

    /**
     * Pull from the rs forums...this can easily break if they stop using the version 4 of the thread
     * http://services.runescape.com/m=forum/forums.ws?75,76,387,65763383
     * @returns {Promise} current viswax
     * @example
     * rsapi.rs.distraction.viswax.getCurrent().then(function(vis) {
     *  console.log(vis);
     * }).catch(console.error);
     */
    this.getCurrent = function() {
        return new Promise(function (resolve, reject) {
            request.rsforum('http://services.runescape.com/m=forum/forums.ws?75,76,331,66006366').then(function(posts) {
                var sugar = posts.posts.filter(function(post) { post.username = post.username.replace('�', ' '); return post.username == 'Tiamat Rider';});
                var money = sugar[0].body;
                var update = sugar[0].postTime;
                var editIndex = update.indexOf('Last edited on');
                var slot1Index = money.indexOf('Slot 1');
                var slot2Index = money.indexOf('Slot 2');
                var slot3Index = money.indexOf('Slot 3');
                console.log(editIndex, slot1Index, slot2Index, slot3Index);
                if (slot3Index <= 1) {
                    // fail safe incase Sugar starts removing the # in Slot # 3
                    slot3Index = money.indexOf('Slot 3');
                }
                var lastUpdate = update.substring(editIndex, update.length);
                var slot1 = money.substring(slot1Index + 7, slot2Index).trim().replace(/-/g,'').trim();//.replace(/ *\([^)]*\)*/g, '').trim();
                var slot2 = money.substring(slot2Index + 7, slot3Index).trim().replace(/-/g,'').trim();//.replace(/ *\([^)]*\)*/g, '').trim();
                var obj = {
                    slot1: slot1,
                    slot2: slot2,
                    lastUpdate: lastUpdate.replace('�', ' ')
                };
                resolve(obj);
            }).catch(reject);
        });

    }
}

module.exports = Viswax;


text:
Imports SistFoncreagro.BussinesLogic
Imports SistFoncreagro.BussinessEntities
Public Class VentanaCentroCostoFactura
    Inherits System.Web.UI.Page
    Dim facturaCCostoBl As IFacturaCentroCostoBL
    Dim ordenCCostoBl As IOrdenCentroCostoBL
    Dim facturaCCosto As New FacturaCentroCosto
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        rcbTipoDocumento.Filter = 1
    End Sub

    Protected Sub gvFacturaCentroCosto_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gvFacturaCentroCosto.RowCommand
        facturaCCostoBl = New FacturaCentroCostoBL
        Dim index = e.CommandArgument
        If e.CommandName = "Eliminar" Then
            Dim idCentroCostoFactura As Int32 = CInt(gvFacturaCentroCosto.DataKeys(index).Item(0).ToString)
            facturaCCostoBl.DeleteFacturaCentroCosto(idCentroCostoFactura)
            gvFacturaCentroCosto.DataBind()
        End If
    End Sub

    Protected Sub lbAgregar_Click(ByVal sender As Object, ByVal e As EventArgs) Handles lbAgregar.Click
        facturaCCostoBl = New FacturaCentroCostoBL
        facturaCCosto.IdOrdenCentroCosto = rcbOrdenCentroCosto.SelectedValue
        facturaCCosto.IdTipoDocumento = rcbTipoDocumento.SelectedValue
        facturaCCosto.Serie = txtSerie.Text
        facturaCCosto.Numero = txtNumero.Text
        facturaCCosto.MontoFact = txtMonto.Text
        facturaCCostoBl.SaveFacturaCentroCosto(facturaCCosto)
        gvFacturaCentroCosto.DataBind()
        txtSerie.Text = ""
        txtNumero.Text = ""
        txtMonto.Text = ""
    End Sub

    Protected Sub lbFinalizar_Click(ByVal sender As Object, ByVal e As EventArgs) Handles lbFinalizar.Click
        ordenCCostoBl = New OrdenCentroCostoBL
        ordenCCostoBl.FinalizarRegOrdenCompraCentroCosto(rcbOrdenCentroCosto.SelectedValue)
        rcbOrdenCentroCosto.DataBind()
        gvFacturaCentroCosto.DataBind()
    End Sub

End Class


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

    <title>AJAX authentication test</title>

AJAX authentication test

JSON...

Datasets found...

Getting dataset list...


text:
from __future__ import print_function

import SimpleITK as sitk
import sys
import os

if len ( sys.argv ) < 4:
    print( "Usage: "+sys.argv[0]+ " <input> <variance> <output>" )
    sys.exit ( 1 )

##! [python director command]
class MyCommand(sitk.Command):
    def __init__(self, po):
        # required
        super(MyCommand,self).__init__()
        self.processObject = po

    def Execute(self):
        print("{0} Progress: {1:1.2f}".format(self.processObject.GetName(),self.processObject.GetProgress()))
##! [python director command]

reader = sitk.ImageFileReader()
reader.SetFileName ( sys.argv[1] )
image = reader.Execute()

pixelID = image.GetPixelIDValue()

gaussian = sitk.DiscreteGaussianImageFilter()
gaussian.SetVariance( float ( sys.argv[2] ) )

##! [python lambda command]
gaussian.AddCommand(sitk.sitkStartEvent, lambda: print("StartEvent"))
gaussian.AddCommand(sitk.sitkEndEvent, lambda: print("EndEvent"))
##! [python lambda command]

cmd = MyCommand(gaussian)
gaussian.AddCommand(sitk.sitkProgressEvent, cmd)

image = gaussian.Execute ( image )

caster = sitk.CastImageFilter()
caster.SetOutputPixelType( pixelID )
image = caster.Execute( image )

writer = sitk.ImageFileWriter()
writer.SetFileName ( sys.argv[3] )
writer.Execute ( image );

if ( not "SITK_NOSHOW" in os.environ ):
    sitk.Show( image, "Simple Gaussian" )


text:
package com.elegion.nbumakov.customviewexample.util;

import java.util.Random;

/**
 * @author Nikita Bumakov
 */
public class FakeCompassManager implements Runnable {

    private float mBearing = 0;
    private Random mRandom = new Random();
    private final Object mLock = new Object();

    private IBearingAware mListener;

    public void setListener(IBearingAware listener) {
        synchronized (mLock) {
            mListener = listener;
            if (mListener != null) {
                new Thread(this).start();
            }
        }
    }

    @Override
    public void run() {
        while (!Thread.interrupted()) {
            synchronized (mLock) {
                if (mListener != null) {
                    mBearing += mRandom.nextFloat() > 0.05f
                            ? rnd(5)
                            : rnd(150);

                    mListener.updateBearing(mBearing);
                }else {
                    Thread.currentThread().interrupt();
                }
            }
        }
    }

    private float rnd(int border) {
        return 2 * border * (mRandom.nextFloat() - 0.5f);
    }
}


text:
require "spec_helper"

$count = 0

describe Moe::Sequence::MetadataItem do
  let(:count)      { $count += 1 }
  let(:name)       { "metadata_item_test#{count}" }
  let!(:setup)     { Moe::Sequence.setup name, 2, 5, 10 }
  let(:collection) { Moe::Sequence::Collection.new name, "owner" }
  let(:collector)  { Moe::Sequence::Collector.new  name, "owner" }

  describe "#items" do
    it "returns the associated items" do
      1.upto(101) do
        collector.add
      end
      collector.save

      sequences = collection.metadata_items

      expect( sequences.first.items.size ).to eq(101)
    end
  end
end


text:
using System;
using System.Linq;
using System.Net;
using TweetLib.Browser.Interfaces;
using TweetLib.Browser.Request;
using TweetLib.Core.Features.Plugins.Enums;

namespace TweetLib.Core.Features.Plugins {
	public sealed class PluginSchemeHandler : ICustomSchemeHandler {
		private static readonly SchemeResource PathMustBeRelativeToRoot = new SchemeResource.Status(HttpStatusCode.Forbidden, "File path has to be relative to the plugin root folder.");

		public string Protocol => "tdp";

		private readonly ResourceCache resourceCache;
		private readonly PluginBridge bridge;

		public PluginSchemeHandler(ResourceCache resourceCache, PluginManager pluginManager) {
			this.resourceCache = resourceCache;
			this.bridge = pluginManager.bridge;
		}

		public SchemeResource? Resolve(Uri uri) {
			if (!uri.IsAbsoluteUri || uri.Scheme != Protocol || !int.TryParse(uri.Authority, out var identifier)) {
				return null;
			}

			var segments = uri.Segments.Select(static segment => segment.TrimEnd('/')).Where(static segment => !string.IsNullOrEmpty(segment)).ToArray();

			if (segments.Length > 0) {
				var handler = segments[0] switch {
					"root" => DoReadRootFile(identifier, segments),
					_      => null
				};

				if (handler != null) {
					return handler;
				}
			}

			return new SchemeResource.Status(HttpStatusCode.BadRequest, "Bad URL path: " + uri.AbsolutePath);
		}

		private SchemeResource DoReadRootFile(int identifier, string[] segments) {
			string path = string.Join("/", segments, 1, segments.Length - 1);

			Plugin? plugin = bridge.GetPluginFromToken(identifier);
			string fullPath = plugin == null ? string.Empty : plugin.GetFullPathIfSafe(PluginFolder.Root, path);
			return fullPath.Length == 0 ? PathMustBeRelativeToRoot : resourceCache.ReadFile(fullPath);
		}
	}
}


text:
name: Bug report
about: Create a report to help us improve Carbon
---

**Describe the bug**
A clear and concise description of what the bug is.

**To Reproduce**
Steps to reproduce the behavior:

1. Go to '...'
2. Click on '....'
3. See error

**Expected behavior**
A clear and concise description of what you expected to happen.

**Screenshots**
If applicable, add screenshots to help explain your problem.

**Info (please complete the following information):**

- OS [e.g. macOS, Linux, Windows, iOS]:
- Browser [e.g. chrome, safari]:
-

  Code Snippet (If Applicable)


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="alphasniper.com.github.returningintent.MainActivity">

    <Button
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:text="Pass Intent"
        android:id="@+id/intent_btn"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />
</RelativeLayout>


text:
package cgeo.geocaching.connector.gc;

import java.util.List;

/**
 *
 * @see Mapbox
 *
 */
final class UTFGrid {

    static final int GRID_MAXX = 63;
    static final int GRID_MAXY = 63;

    private UTFGrid() {
        // utility class
    }

    /** Calculate from a list of positions (x/y) the coords */
    static UTFGridPosition getPositionInGrid(final List<UTFGridPosition> positions) {
        int minX = GRID_MAXX;
        int maxX = 0;
        int minY = GRID_MAXY;
        int maxY = 0;
        for (final UTFGridPosition pos : positions) {
            minX = Math.min(minX, pos.x);
            maxX = Math.max(maxX, pos.x);
            minY = Math.min(minY, pos.y);
            maxY = Math.max(maxY, pos.y);
        }
        return new UTFGridPosition((minX + maxX) / 2, (minY + maxY) / 2);
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <appSettings>

        <!-- QA Server-->
        <!--service url="http://stagebitz.geveo.com/service/api/" /-->
        <!-- Live Server-->
        <!--service url="https://user.stagebitz.com/service/api/" /-->
        <!-- Main Server-->
        <!--service url="http://morpheus/StageBitz.Service/api/" /-->
        <!-- Local Server-->
        <service url="http://192.168.94.39/StageBitzEpicMobile.Service/api/" />

        <version versionnumber="1.0.0.0" />
         <itemurl value="http://stagebitz.geveo.com/Inventory/ItemDetails.aspx?ItemId={0}&CompanyId={1}"/>
        <contacturl value="http://stagebitz.uservoice.com/knowledgebase/topics/44096-stagebitz-mobile-app"/>

    </appSettings>
</configuration>


text:
require 'spec_helper'

describe Api::V1::OrganizationsController do

end


text:
#ifndef __INCLUDE_NUTTX_AUDIO_I2S_H
#define __INCLUDE_NUTTX_AUDIO_I2S_H

/****************************************************************************
 * Included Files
 ****************************************************************************/

#include <nuttx/config.h>

#include <sys/types.h>
#include <stdint.h>
#include <stdbool.h>

#include <nuttx/audio/audio.h>

#ifdef CONFIG_I2S

/****************************************************************************
 * Pre-processor Definitions
 ****************************************************************************/
/* Access macros ************************************************************/

/****************************************************************************
 * Name: I2S_RXSAMPLERATE
 *
 * Description:
 *   Set the I2S RX sample rate.  NOTE:  This will have no effect if (1) the
 *   driver does not support an I2S receiver or if (2) the sample rate is
 *   driven by the I2S frame clock.  This may also have unexpected side-
 *   effects of the RX sample is coupled with the TX sample rate.
 *
 * Input Parameters:
 *   dev  - Device-specific state data
 *   rate - The I2S sample rate in samples (not bits) per second
 *
 * Returned Value:
 *   Returns the resulting bitrate
 *
 ****************************************************************************/

#define I2S_RXSAMPLERATE(d,f) ((d)->ops->i2s_rxsamplerate(d,r))

/****************************************************************************
 * Name: I2S_RXDATAWIDTH
 *
 * Description:
 *   Set the I2S RX data width.  The RX bitrate is determined by
 *   sample_rate * data_width.
 *
 * Input Parameters:
 *   dev   - Device-specific state data
 *   width - The I2S data with in bits.
 *
 * Returned Value:
 *   Returns the resulting bitrate
 *
 ****************************************************************************/

#define I2S_RXDATAWIDTH(d,b) ((d)->ops->i2s_rxdatawidth(d,b))

/****************************************************************************
 * Name: I2S_RECEIVE
 *
 * Description:
 *   Receive a block of data from I2S.
 *
 * Input Parameters:
 *   dev      - Device-specific state data
 *   apb      - A pointer to the audio buffer in which to recieve data
 *   callback - A user provided callback function that will be called at
 *              the completion of the transfer.  The callback will be
 *              performed in the context of the worker thread.
 *   arg      - An opaque argument that will be provided to the callback
 *              when the transfer complete.
 *   timeout  - The timeout value to use.  The transfer will be canceled
 *              and an ETIMEDOUT error will be reported if this timeout
 *              elapsed without completion of the DMA transfer.  Units
 *              are system clock ticks.  Zero means no timeout.
 *
 * Returned Value:
 *   OK on success; a negated errno value on failure.  NOTE:  This function
 *   only enqueues the transfer and returns immediately.  Success here only
 *   means that the transfer was enqueued correctly.
 *
 *   When the transfer is complete, a 'result' value will be provided as
 *   an argument to the callback function that will indicate if the transfer
 *   failed.
 *
 ****************************************************************************/

#define I2S_RECEIVE(d,b,c,a,t) ((d)->ops->i2s_receive(d,b,c,a,t))

/****************************************************************************
 * Name: I2S_TXSAMPLERATE
 *
 * Description:
 *   Set the I2S TX sample rate.  NOTE:  This will have no effect if (1) the
 *   driver does not support an I2S transmitter or if (2) the sample rate is
 *   driven by the I2S frame clock.  This may also have unexpected side-
 *   effects of the TX sample is coupled with the RX sample rate.
 *
 * Input Parameters:
 *   dev  - Device-specific state data
 *   rate - The I2S sample rate in samples (not bits) per second
 *
 * Returned Value:
 *   Returns the resulting bitrate
 *
 ****************************************************************************/

#define I2S_TXSAMPLERATE(d,f) ((d)->ops->i2s_txsamplerate(d,r))

/****************************************************************************
 * Name: I2S_TXDATAWIDTH
 *
 * Description:
 *   Set the I2S TX data width.  The TX bitrate is determined by
 *   sample_rate * data_width.
 *
 * Input Parameters:
 *   dev   - Device-specific state data
 *   width - The I2S data with in bits.
 *
 * Returned Value:
 *   Returns the resulting bitrate
 *
 ****************************************************************************/

#define I2S_TXDATAWIDTH(d,b) ((d)->ops->i2s_txdatawidth(d,b))

/****************************************************************************
 * Name: I2S_SEND
 *
 * Description:
 *   Send a block of data on I2S.
 *
 * Input Parameters:
 *   dev      - Device-specific state data
 *   apb      - A pointer to the audio buffer from which to send data
 *   callback - A user provided callback function that will be called at
 *              the completion of the transfer.  The callback will be
 *              performed in the context of the worker thread.
 *   arg      - An opaque argument that will be provided to the callback
 *              when the transfer completes.
 *   timeout  - The timeout value to use.  The transfer will be cancelled
 *              and an ETIMEDOUT error will be reported if this timeout
 *              elapsed without completion of the DMA transfer.  Units
 *              are system clock ticks.  Zero means no timeout.
 *
 * Returned Value:
 *   OK on success; a negated errno value on failure.  NOTE:  This function
 *   only enqueues the transfer and returns immediately.  Success here only
 *   means that the transfer was enqueued correctly.
 *
 *   When the transfer is complete, a 'result' value will be provided as
 *   an argument to the callback function that will indicate if the transfer
 *   failed.
 *
 ****************************************************************************/

#define I2S_SEND(d,b,c,a,t) ((d)->ops->i2s_send(d,b,c,a,t))

/****************************************************************************
 * Public Types
 ****************************************************************************/
/* Transfer complete callbacks */

struct i2s_dev_s;
typedef CODE void (*i2s_callback_t)(FAR struct i2s_dev_s *dev,
                  FAR struct ap_buffer_s *apb, FAR void *arg, int result);

/* The I2S vtable */

struct i2s_ops_s
{
  /* Receiver methods */

  CODE uint32_t (*i2s_rxsamplerate)(FAR struct i2s_dev_s *dev, uint32_t rate);
  CODE uint32_t (*i2s_rxdatawidth)(FAR struct i2s_dev_s *dev, int bits);
  CODE int      (*i2s_receive)(FAR struct i2s_dev_s *dev,
                  FAR struct ap_buffer_s *apb, i2s_callback_t callback,
                  FAR void *arg, uint32_t timeout);

  /* Transmitter methods */

  CODE uint32_t (*i2s_txsamplerate)(FAR struct i2s_dev_s *dev, uint32_t rate);
  CODE uint32_t (*i2s_txdatawidth)(FAR struct i2s_dev_s *dev, int bits);
  CODE int      (*i2s_send)(FAR struct i2s_dev_s *dev,
                  FAR struct ap_buffer_s *apb, i2s_callback_t callback,
                  FAR void *arg, uint32_t timeout);
};

/* I2S private data.  This structure only defines the initial fields of the
 * structure visible to the I2S client.  The specific implementation may
 * add additional, device specific fields
 */

struct i2s_dev_s
{
  FAR const struct i2s_ops_s *ops;
};

/****************************************************************************
 * Public Data
 ****************************************************************************/

#undef EXTERN
#if defined(__cplusplus)
#define EXTERN extern "C"
extern "C"
{
#else
#define EXTERN extern
#endif

/****************************************************************************
 * Public Functions
 ****************************************************************************/

/****************************************************************************
 * Name: i2schar_register
 *
 * Description:
 *   Create and register the I2S character driver.
 *
 *   The I2S character driver is a simple character driver that supports I2S
 *   transfers via a read() and write().  The intent of this driver is to
 *   support I2S testing.  It is not an audio driver but does conform to some
 *   of the buffer management heuristics of an audio driver.  It is not
 *   suitable for use in any real driver application in its current form.
 *
 * Input Parameters:
 *   i2s - An instance of the lower half I2S driver
 *   minor - The device minor number.  The I2S character device will be
 *     registers as /dev/i2scharN where N is the minor number
 *
 * Returned Value:
 *   OK if the driver was successfully register; A negated errno value is
 *   returned on any failure.
 *
 ****************************************************************************/

int i2schar_register(FAR struct i2s_dev_s *i2s, int minor);

#undef EXTERN
#if defined(__cplusplus)
}
#endif

#endif /* CONFIG_I2S */
#endif /* __INCLUDE_NUTTX_AUDIO_I2S_H */


text:
using System;
using System.Collections.Generic;

namespace HL
{
    public partial class HypoLambda
    {
        IEnumerator<Terminal> enu;

        private string newLabel()
        {
            return string.Format(labelFmt, labelNumber++);
        }

        void nexttoken(IEnumerator<Terminal> enumerator)
        {
            enu = enumerator;
            if (enu.MoveNext())
                lookaheadtoken = enu.Current;
            else
                lookaheadtoken = new Terminal(TokenType.NIL, 0, 0);
            nexttoken();
        }

        void nexttoken()
        {
            currenttoken = lookaheadtoken;
            if (enu.MoveNext())
                lookaheadtoken = enu.Current;
            else
                lookaheadtoken = new Terminal(TokenType.NIL, currenttoken.LN, currenttoken.CP);
        }

        Terminal lookaheadtoken = null;
        Terminal lookaheadone()
        {
            return lookaheadtoken;
        }

        void error(string msg)
        {
            throw new ApplicationException(msg);
        }

        Terminal currenttoken;

        void expect(TokenType s)
        {
            if (currenttoken.TokenType != s) {
                string msg = string.Format(
                    Strings.Expression_Unexpected_symbol_Waits_for_comes,
                    s, currenttoken.TokenType, currenttoken.LN, currenttoken.CP);
                error(msg);
            }
        }

        Node factor()
        {
            Node f = null;
            switch (currenttoken.TokenType) {
                case TokenType.ident:
                    f = new Node(currenttoken);
                    break;
                case TokenType.number:
                    f = new Node(currenttoken);
                    break;
                case TokenType.str:
                    f = new Node(currenttoken);
                    break;
                case TokenType.lbrac:
                    nexttoken();
                    if (currenttoken.TokenType == TokenType.rbrac) {
                        var empty = new Terminal(TokenType.list, currenttoken.LN, currenttoken.CP);
                        f = new Node(empty);
                    } else
                        f = build_list();
                    expect(TokenType.rbrac);
                    break;
                case TokenType.lparen:
                    nexttoken();
                    f = expression();
                    expect(TokenType.rparen);
                    break;
                case TokenType.lcurly:
                    nexttoken();
                    expect(TokenType.ident);
                    f = new Node(currenttoken);
                    nexttoken();
                    expect(TokenType.rcurly);
                    break;
                default:
                    var msg = string.Format(Strings.Expression_Syntax_error,
                        currenttoken.LN, currenttoken.CP);
                    error(msg);
                    break;
            }
            nexttoken();
            return f;
        }

        Node build_list()
        {
            var f = expression_lambda();
            if (currenttoken.TokenType == TokenType.comma) {
                nexttoken();
                return new Node(new Terminal(TokenType.comma, currenttoken.LN, currenttoken.CP), f, build_list());
            } else {
                var empty = new Terminal(TokenType.list, currenttoken.LN, currenttoken.CP);
                var oplist = new Terminal(TokenType.comma, currenttoken.LN, currenttoken.CP);
                return new Node(oplist, f, new Node(empty));
            }
        }

        Node call(Node nleft)
        {
            if (currenttoken.TokenType == TokenType.lparen) {
                var tl = new Terminal(TokenType.list, currenttoken.LN, currenttoken.CP);
                var bindings = new Node(tl);
                nexttoken();
                if (currenttoken.TokenType != TokenType.rparen) {
                    bindings = build_list();
                }
                expect(TokenType.rparen);
                nexttoken();
                var op = new Terminal(TokenType.eval, currenttoken.LN, currenttoken.CP);
                var deep = new Node(op, bindings, nleft);
                // keep consuming evaluations.
                return call(deep);
            } else
                return nleft;
        }

        Node expression_evaluated()
        {
            Node nleft = factor();
            return call(nleft);
        }

        Node factor_negated()
        {
            Node nleft = null;
            if (currenttoken.TokenType == TokenType.not) {
                Terminal op = currenttoken;
                nexttoken();
                nleft = expression_evaluated();
                Node n = new Node(op, nleft, null);
                return n;
            } else
                return expression_evaluated();
        }

        Node term()
        {
            Node nleft = factor_negated();
            if (currenttoken.TokenType == TokenType.times || currenttoken.TokenType == TokenType.slash ||
                currenttoken.TokenType == TokenType.perc) {
                Terminal op = currenttoken;
                nexttoken();
                Node nright = term();
                Node n = new Node(op, nleft, nright);
                return n;
            } else
                return nleft;
        }

        Node expression_sum()
        {
            Node nleft = term();
            if (currenttoken.TokenType == TokenType.plus || currenttoken.TokenType == TokenType.minus) {
                Terminal op = currenttoken;
                nexttoken();
                Node nright = expression_sum();
                Node n = new Node(op, nleft, nright);
                return n;
            } else
                return nleft;
        }

        Node expression_logic()
        {
            Node nleft = expression_sum();
            if (currenttoken.TokenType == TokenType.eq || currenttoken.TokenType == TokenType.gt ||
                currenttoken.TokenType == TokenType.gteq || currenttoken.TokenType == TokenType.lt ||
                currenttoken.TokenType == TokenType.lteq || currenttoken.TokenType == TokenType.neq) {
                Terminal op = currenttoken;
                nexttoken();
                Node nright = expression_logic();
                Node n = new Node(op, nleft, nright);
                return n;
            } else
                return nleft;
        }

        Node expression_andor()
        {
            Node nleft = expression_logic();
            if (currenttoken.TokenType == TokenType.and || currenttoken.TokenType == TokenType.or) {
                Terminal op = currenttoken;
                nexttoken();
                Node nright = expression_andor();
                Node n = and_or_ast(op, nleft, nright);
                return n;
            } else
                return nleft;
        }

        Node expression_cond()
        {
            Node whentrue = expression_andor();
            if (currenttoken.TokenType == TokenType.iff) {
                nexttoken();
                Node condition = expression_andor();
                expect(TokenType.els);
                nexttoken();
                Node whenfalse = expression_cond();

                var n = new Node(new Terminal(TokenType.iff, currenttoken.LN, currenttoken.CP),
                    and_or_ast(new Terminal(TokenType.or, currenttoken.LN, currenttoken.CP),
                        and_or_ast(new Terminal(TokenType.and, currenttoken.LN, currenttoken.CP),
                            condition,
                            whentrue),
                        whenfalse),
                    null);
                return n;
            } else
                return whentrue;
        }

        List<string> name_list()
        {
            var names = new List<string>();
            if (currenttoken.TokenType == TokenType.ident) {
                names.Add(currenttoken.Value.ToString());
                nexttoken();
                if (currenttoken.TokenType == TokenType.comma) {
                    nexttoken();
                    names.AddRange(name_list());
                }
            }
            return names;
        }

        List<string> name_list_parens()
        {
            var rparen = false;
            if (currenttoken.TokenType == TokenType.lparen) {
                rparen = true;
                nexttoken();
            }
            var nl = name_list();
            if (rparen) {
                expect(TokenType.rparen);
                nexttoken();
            }
            return nl;
        }

        Node expression_lambda()
        {
            if (currenttoken.TokenType == TokenType.lambda) {
                var op = currenttoken;
                nexttoken();
                var nl = name_list_parens();
                expect(TokenType.colon);
                var ln = currenttoken.LN; var cp = currenttoken.CP;
                var head = new Terminal(TokenType.lambdahead, nl.ToArray(), ln, cp);
                nexttoken();
                ln = currenttoken.LN; cp = currenttoken.CP;
                var lbljmp = newLabel();
                var jmplabel = new Terminal(TokenType.label, lbljmp, ln, cp);
                var jmp = new Terminal(TokenType.jmp, lbljmp, ln, cp);
                var body = expression_lambda();
                ln = currenttoken.LN; cp = currenttoken.CP;
                var bodyop = new Terminal(TokenType.lambdabody, lbljmp, ln, cp);
                return new Node(op,
                    new Node(head),
                    new Node(bodyop,
                        new Node(jmp),
                        new Node(jmplabel,
                            body, null)));
            } else {
                return expression_cond();
            }
        }

        Node expression_list()
        {
            var f = expression_single();
            if (currenttoken.TokenType == TokenType.semicolon) {
                nexttoken();
                return new Node(new Terminal(TokenType.semicolon, currenttoken.LN, currenttoken.CP), f, expression_list());
            } else if (currenttoken.TokenType == TokenType.comma) {
                var msg = string.Format(Strings.Expression_Syntax_error,
                    currenttoken.LN, currenttoken.CP);
                error(msg);
                return null;
            } else
                return f;
        }

        Node assignment()
        {
            var s = currenttoken.Value.ToString();
            nexttoken();
            expect(TokenType.assig);
            var op = new Terminal(TokenType.assig, s, currenttoken.LN, currenttoken.CP);
            nexttoken();
            var r = new Node(new Terminal(TokenType.identlocal, s, currenttoken.LN, currenttoken.CP));
            var l = expression_single();
            return new Node(op, l, r);
        }

        Node expression_single()
        {
            if (currenttoken.TokenType == TokenType.ident && lookaheadone().TokenType == TokenType.assig) {
                return assignment();
            } else {
                return expression_lambda();
            }
        }

        Node expression()
        {
            return expression_list();
        }

        private Terminal nilterminal()
        {
            return new Terminal(TokenType.NIL, null, currenttoken.LN, currenttoken.CP);
        }

        private Node and_or_ast(Terminal op, Node nleft, Node nright)
        {
            Node n = null;
            switch (op.TokenType) {
                case TokenType.and:
                    var lbljmpzero = newLabel();
                    n = new Node(op,
                        nleft,
                        new Node(nilterminal(),
                            new Node(new Terminal(TokenType.jmpzero, lbljmpzero, currenttoken.LN, currenttoken.CP)),
                            new Node(nilterminal(),
                                nright,
                                new Node(new Terminal(TokenType.label, lbljmpzero, currenttoken.LN, currenttoken.CP)))));
                    break;
                case TokenType.or:
                    var lbljmpnotz = newLabel();
                    n = new Node(op,
                        nleft,
                        new Node(nilterminal(),
                            new Node(new Terminal(TokenType.jmpnotz, lbljmpnotz, currenttoken.LN, currenttoken.CP)),
                            new Node(nilterminal(),
                                nright,
                                new Node(new Terminal(TokenType.label, lbljmpnotz, currenttoken.LN, currenttoken.CP)))));
                    break;
            }
            return n;
        }
    }

    class Node
    {
        private Terminal o;
        private Node left;
        private Node right;

        public Node(Terminal o)
        {
            this.o = o;
        }

        public Node(Terminal o, Node izq, Node der)
        {
            this.o = o;
            this.left = izq;
            this.right = der;
        }

        public Terminal Tag
        {
            get { return this.o; }
        }

        public Node Left
        {
            get { return this.left; }
        }

        public Node Right
        {
            get { return this.right; }
        }
    }

}


text:
title: Will Spaetzel
layout: default
---

Will Spaetzel is a Software Developer in the Web Operations team at Maplesoft. He works on Maplesoft's web sites including the
[Application Center](http://www.maplesoft.com/applications) and the [Online Help System](http://www.maplesoft.com/support/help).

He started at Maplesoft in May of 2004 for a 16 month internship while completing his Bachelor of Computer Science from the
[University of Western Ontario](http://www.uwo.ca). During his final year at UWO, he continued on as moderator for [MaplePrimes](http://www.mapleprimes.com).
He joined Maplesoft full-time in May 2006 and moved to the web team in Jan 2007.

Will was born and grew up in Ontario, Canada. He maintains a [personal blog](http://spaetzel.com), dabbles in [photography](http://flickr.com/photos/redune)
builds [web applications](http://github.com/spaetzel) in his spare time.


text:
![](https://media.giphy.com/media/wlEPdDuMQzSkE/giphy.gif)

Everyone out there is making todo app's and here I am making evernote/Bearwriter clones. See [NIH](https://en.wikipedia.org/wiki/Not_invented_here) syndrome.

I made the decision to start this project for 3 reasons.

1. I needed some weekend code escapism. This project runs solely on the Minimum Viable, doesn't annoy me method of product management.  I'm using it to explore technology I find interesting.
2. I love bear writer, but I'm not ready to pay for the premium service. Instead, I'll implement the premium parts in Yanta.
3. I want a tool that works really well with existing repo's of markdown (think documentation/gitbooks)

# features
- index page (autorefresh)
- auto commit
- pdf download
- view page
- sync notes with git
- create new files

# Roadmap
See [/page/docs/todo.md](/page/docs/todo.md)

# usage
## Pdf export
This is a total hack right now and needs some TLC. Basically, you're gonna need to have https://github.com/ebuckley/pdf-now running. Then you're gonna need to hack the code in the pdf package so that it has the correct path as it's currently hard coded to where that project is running on my system :joy:

This will probably be fixed as soon as one other person wants to use this project :joy:

## development
Assuming you have a correctly configured `GOPATH` with the required dependencies.

```
cd src/code/github.com/ebuckley/yanta && go run main.go
```

The development instance will be running on port 1337, everything under the

## production
```
./yanta -dir <pathname>
```

Provide a directory for serving the site. The service will run on `0.0.0.0:1337`

The way pull/push works by default is by making the assumption that the target directory has a git repo and a "publish" remote. It will push master to "publish", and sync master from "publish".

# bugs/features/requests/planning
[TODO](/page/docs/todo.md)

Put content in the todo here

# Development dependencies
A common pattern in golang projects is dependency vendoring. I'm not doing that yet as the project is in it's initial stages and moving at a pace which warrents keeping dependenceis on the bleeding edge,

-	"github.com/gorilla/schema" is used for deserialization of form requests to structs
-	"github.com/gorilla/mux" is used for routing
-	"github.com/golang-commonmark/markdown" is used for markdown parsing