text:
<?php

/**
 * Catalog product attribute api
 *
 * @category   Mage
 * @package    Mage_Catalog
 * @author     Magento Core Team <core@magentocommerce.com>
 */
class Mage_Catalog_Model_Product_Attribute_Api extends Mage_Catalog_Model_Api_Resource
{
    /**
     * Product entity type id
     *
     * @var int
     */
    protected $_entityTypeId;

    /**
     * Constructor. Initializes default values.
     */
    public function __construct()
    {
        $this->_storeIdSessionField = 'product_store_id';
        $this->_ignoredAttributeCodes[] = 'type_id';
        $this->_ignoredAttributeTypes[] = 'gallery';
        $this->_ignoredAttributeTypes[] = 'media_image';
        $this->_entityTypeId = Mage::getModel('eav/entity')->setType('catalog_product')->getTypeId();
    }

    /**
     * Retrieve attributes from specified attribute set
     *
     * @param int $setId
     * @return array
     */
    public function items($setId)
    {
        $attributes = Mage::getModel('catalog/product')->getResource()
                ->loadAllAttributes()
                ->getSortedAttributes($setId);
        $result = array();

        foreach ($attributes as $attribute) {
            /* @var $attribute Mage_Catalog_Model_Resource_Eav_Attribute */
            if ((!$attribute->getId() || $attribute->isInSet($setId))
                    && $this->_isAllowedAttribute($attribute)) {

                if (!$attribute->getId() || $attribute->isScopeGlobal()) {
                    $scope = 'global';
                } elseif ($attribute->isScopeWebsite()) {
                    $scope = 'website';
                } else {
                    $scope = 'store';
                }

                $result[] = array(
                    'attribute_id' => $attribute->getId(),
                    'code' => $attribute->getAttributeCode(),
                    'type' => $attribute->getFrontendInput(),
                    'required' => $attribute->getIsRequired(),
                    'scope' => $scope
                );
            }
        }

        return $result;
    }

    /**
     * Retrieve attribute options
     *
     * @param int $attributeId
     * @param string|int $store
     * @return array
     */
    public function options($attributeId, $store = null)
    {
        $storeId = $this->_getStoreId($store);
        $attribute = Mage::getModel('catalog/product')
                ->setStoreId($storeId)
                ->getResource()
                ->getAttribute($attributeId);

        /* @var $attribute Mage_Catalog_Model_Entity_Attribute */
        if (!$attribute) {
            $this->_fault('not_exists');
        }
        $options = array();
        if ($attribute->usesSource()) {
            foreach ($attribute->getSource()->getAllOptions() as $optionId => $optionValue) {
                if (is_array($optionValue)) {
                    $options[] = $optionValue;
                } else {
                    $options[] = array(
                        'value' => $optionId,
                        'label' => $optionValue
                    );
                }
            }
        }

        return $options;
    }

    /**
     * Retrieve list of possible attribute types
     *
     * @return array
     */
    public function types()
    {
        return Mage::getModel('catalog/product_attribute_source_inputtype')->toOptionArray();
    }

    /**
     * Create new product attribute
     *
     * @param array $data input data
     * @return integer
     */
    public function create($data)
    {
        /** @var $model Mage_Catalog_Model_Resource_Eav_Attribute */
        $model = Mage::getModel('catalog/resource_eav_attribute');
        /** @var $helper Mage_Catalog_Helper_Product */
        $helper = Mage::helper('catalog/product');

        if (empty($data['attribute_code']) || (isset($data['frontend_label']) && !is_array($data['frontend_label']))) {
            $this->_fault('invalid_parameters');
        }

        //validate attribute_code
        if (!preg_match('/^[a-z][a-z_0-9]{0,254}$/', $data['attribute_code'])) {
            $this->_fault('invalid_code');
        }

        //validate frontend_input
        $allowedTypes = array();
        foreach ($this->types() as $type) {
            $allowedTypes[] = $type['value'];
        }
        if (!in_array($data['frontend_input'], $allowedTypes)) {
            $this->_fault('invalid_frontend_input');
        }

        $data['source_model'] = $helper->getAttributeSourceModelByInputType($data['frontend_input']);
        $data['backend_model'] = $helper->getAttributeBackendModelByInputType($data['frontend_input']);
        if (is_null($model->getIsUserDefined()) || $model->getIsUserDefined() != 0) {
            $data['backend_type'] = $model->getBackendTypeByInput($data['frontend_input']);
        }

        $this->_prepareDataForSave($data);

        $model->addData($data);
        $model->setEntityTypeId($this->_entityTypeId);
        $model->setIsUserDefined(1);

        try {
            $model->save();
            // clear translation cache because attribute labels are stored in translation
            Mage::app()->cleanCache(array(Mage_Core_Model_Translate::CACHE_TAG));
        } catch (Exception $e) {
            $this->_fault('unable_to_save', $e->getMessage());
        }

        return (int) $model->getId();
    }

    /**
     * Update product attribute
     *
     * @param string|integer $attribute attribute code or ID
     * @param array $data
     * @return boolean
     */
    public function update($attribute, $data)
    {
        $model = $this->_getAttribute($attribute);

        if ($model->getEntityTypeId() != $this->_entityTypeId) {
            $this->_fault('can_not_edit');
        }

        $data['attribute_code'] = $model->getAttributeCode();
        $data['is_user_defined'] = $model->getIsUserDefined();
        $data['frontend_input'] = $model->getFrontendInput();

        $this->_prepareDataForSave($data);

        $model->addData($data);
        try {
            $model->save();
            // clear translation cache because attribute labels are stored in translation
            Mage::app()->cleanCache(array(Mage_Core_Model_Translate::CACHE_TAG));
            return true;
        } catch (Exception $e) {
            $this->_fault('unable_to_save', $e->getMessage());
        }
    }

    /**
     * Remove attribute
     *
     * @param integer|string $attribute attribute ID or code
     * @return boolean
     */
    public function remove($attribute)
    {
        $model = $this->_getAttribute($attribute);

        if ($model->getEntityTypeId() != $this->_entityTypeId) {
            $this->_fault('can_not_delete');
        }

        try {
            $model->delete();
            return true;
        } catch (Exception $e) {
            $this->_fault('can_not_delete', $e->getMessage());
        }
    }

    /**
     * Get full information about attribute with list of options
     *
     * @param integer|string $attribute attribute ID or code
     * @return array
     */
    public function info($attribute)
    {
        $model = $this->_getAttribute($attribute);

        if ($model->isScopeGlobal()) {
            $scope = 'global';
        } elseif ($model->isScopeWebsite()) {
            $scope = 'website';
        } else {
            $scope = 'store';
        }

        $frontendLabels = array(
            array(
                'store_id' => 0,
                'label' => $model->getFrontendLabel()
            )
        );
        foreach ($model->getStoreLabels() as $store_id => $label) {
            $frontendLabels[] = array(
                'store_id' => $store_id,
                'label' => $label
            );
        }

        $result = array(
            'attribute_id' => $model->getId(),
            'attribute_code' => $model->getAttributeCode(),
            'frontend_input' => $model->getFrontendInput(),
            'default_value' => $model->getDefaultValue(),
            'is_unique' => $model->getIsUnique(),
            'is_required' => $model->getIsRequired(),
            'apply_to' => $model->getApplyTo(),
            'is_configurable' => $model->getIsConfigurable(),
            'is_searchable' => $model->getIsSearchable(),
            'is_visible_in_advanced_search' => $model->getIsVisibleInAdvancedSearch(),
            'is_comparable' => $model->getIsComparable(),
            'is_used_for_promo_rules' => $model->getIsUsedForPromoRules(),
            'is_visible_on_front' => $model->getIsVisibleOnFront(),
            'used_in_product_listing' => $model->getUsedInProductListing(),
            'frontend_label' => $frontendLabels
        );
        if ($model->getFrontendInput() != 'price') {
            $result['scope'] = $scope;
        }

        // set additional fields to different types
        switch ($model->getFrontendInput()) {
            case 'text':
                    $result['additional_fields'] = array(
                        'frontend_class' => $model->getFrontendClass(),
                        'is_html_allowed_on_front' => $model->getIsHtmlAllowedOnFront(),
                        'used_for_sort_by' => $model->getUsedForSortBy()
                    );
                    break;
            case 'textarea':
                    $result['additional_fields'] = array(
                        'is_wysiwyg_enabled' => $model->getIsWysiwygEnabled(),
                        'is_html_allowed_on_front' => $model->getIsHtmlAllowedOnFront(),
                    );
                    break;
            case 'date':
            case 'boolean':
                    $result['additional_fields'] = array(
                        'used_for_sort_by' => $model->getUsedForSortBy()
                    );
                    break;
            case 'multiselect':
                    $result['additional_fields'] = array(
                        'is_filterable' => $model->getIsFilterable(),
                        'is_filterable_in_search' => $model->getIsFilterableInSearch(),
                        'position' => $model->getPosition()
                    );
                    break;
            case 'select':
            case 'price':
                    $result['additional_fields'] = array(
                        'is_filterable' => $model->getIsFilterable(),
                        'is_filterable_in_search' => $model->getIsFilterableInSearch(),
                        'position' => $model->getPosition(),
                        'used_for_sort_by' => $model->getUsedForSortBy()
                    );
                    break;
            default:
                    $result['additional_fields'] = array();
                    break;
        }

        // set options
        $options = $this->options($model->getId());
        // remove empty first element
        if ($model->getFrontendInput() != 'boolean') {
            array_shift($options);
        }

        if (count($options) > 0) {
            $result['options'] = $options;
        }

        return $result;
    }

    /**
     * Add option to select or multiselect attribute
     *
     * @param  integer|string $attribute attribute ID or code
     * @param  array $data
     * @return bool
     */
    public function addOption($attribute, $data)
    {
        $model = $this->_getAttribute($attribute);

        if (!$model->usesSource()) {
            $this->_fault('invalid_frontend_input');
        }

        /** @var $helperCatalog Mage_Catalog_Helper_Data */
        $helperCatalog = Mage::helper('catalog');

        $optionLabels = array();
        foreach ($data['label'] as $label) {
            $storeId = $label['store_id'];
            $labelText = $helperCatalog->stripTags($label['value']);
            if (is_array($storeId)) {
                foreach ($storeId as $multiStoreId) {
                    $optionLabels[$multiStoreId] = $labelText;
                }
            } else {
                $optionLabels[$storeId] = $labelText;
            }
        }
        // data in the following format is accepted by the model
        // it simulates parameters of the request made to
        // Mage_Adminhtml_Catalog_Product_AttributeController::saveAction()
        $modelData = array(
            'option' => array(
                'value' => array(
                    'option_1' => $optionLabels
                ),
                'order' => array(
                    'option_1' => (int) $data['order']
                )
            )
        );
        if ($data['is_default']) {
            $modelData['default'][] = 'option_1';
        }

        $model->addData($modelData);
        try {
            $model->save();
        } catch (Exception $e) {
            $this->_fault('unable_to_add_option', $e->getMessage());
        }

        return true;
    }

    /**
     * Remove option from select or multiselect attribute
     *
     * @param  integer|string $attribute attribute ID or code
     * @param  integer $optionId option to remove ID
     * @return bool
     */
    public function removeOption($attribute, $optionId)
    {
        $model = $this->_getAttribute($attribute);

        if (!$model->usesSource()) {
            $this->_fault('invalid_frontend_input');
        }

        // data in the following format is accepted by the model
        // it simulates parameters of the request made to
        // Mage_Adminhtml_Catalog_Product_AttributeController::saveAction()
        $modelData = array(
            'option' => array(
                'value' => array(
                    $optionId => array()
                ),
                'delete' => array(
                    $optionId => '1'
                )
            )
        );
        $model->addData($modelData);
        try {
            $model->save();
        } catch (Exception $e) {
            $this->_fault('unable_to_remove_option', $e->getMessage());
        }

        return true;
    }

    /**
     * Prepare request input data for saving
     *
     * @param array $data input data
     * @return void
     */
    protected function _prepareDataForSave(&$data)
    {
        /** @var $helperCatalog Mage_Catalog_Helper_Data */
        $helperCatalog = Mage::helper('catalog');

        if ($data['scope'] == 'global') {
            $data['is_global'] = Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL;
        } else if ($data['scope'] == 'website') {
            $data['is_global'] = Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_WEBSITE;
        } else {
            $data['is_global'] = Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_STORE;
        }
        if (!isset($data['is_configurable'])) {
            $data['is_configurable'] = 0;
        }
        if (!isset($data['is_filterable'])) {
            $data['is_filterable'] = 0;
        }
        if (!isset($data['is_filterable_in_search'])) {
            $data['is_filterable_in_search'] = 0;
        }
        if (!isset($data['apply_to'])) {
            $data['apply_to'] = array();
        }
        // set frontend labels array with store_id as keys
        if (isset($data['frontend_label']) && is_array($data['frontend_label'])) {
            $labels = array();
            foreach ($data['frontend_label'] as $label) {
                $storeId = $label['store_id'];
                $labelText = $helperCatalog->stripTags($label['label']);
                $labels[$storeId] = $labelText;
            }
            $data['frontend_label'] = $labels;
        }
        // set additional fields
        if (isset($data['additional_fields']) && is_array($data['additional_fields'])) {
            $data = array_merge($data, $data['additional_fields']);
            unset($data['additional_fields']);
        }
        //default value
        if (!empty($data['default_value'])) {
            $data['default_value'] = $helperCatalog->stripTags($data['default_value']);
        }
    }

    /**
     * Load model by attribute ID or code
     *
     * @param integer|string $attribute
     * @return Mage_Catalog_Model_Resource_Eav_Attribute
     */
    protected function _getAttribute($attribute)
    {
        $model = Mage::getResourceModel('catalog/eav_attribute')
            ->setEntityTypeId($this->_entityTypeId);

        if (is_numeric($attribute)) {
            $model->load(intval($attribute));
        } else {
            $model->load($attribute, 'attribute_code');
        }

        if (!$model->getId()) {
            $this->_fault('not_exists');
        }

        return $model;
    }

} // Class Mage_Catalog_Model_Product_Attribute_Api End


text:
#include <config.h>

#include "peripherals/joystick.h"
#include "../uijoystick.c"

redpajama_set_name: RedPajamaGithub


text:
'use strict';

/**
* FUNCTION: ready()
*	Event handler for when an element is ready.
*/
function ready() {
	/* jshint validthis:true */
	this._init();
} // end FUNCTION ready()

// EXPORTS //

module.exports = ready;


text:
var socketIOURL = '//' + location.host + '/socket.io/socket.io.js';

Slide.Control.add('socket', function(S, broadcast) {
    S.clientUID = 0;

    function time2str(time) {
        time = '00' + time;
        return time.substr(-2);
    }
    var showQrcode;
    var qrcodeLink = function() {
        //按 q显示控制区域二维码
        document.addEventListener('keydown', function(e) {
            if (e.keyCode === 81) {
                showQrcode(e);
            }
        }, true);
        var $layer = document.createElement('div');
        $layer.className = 'qrcode';
        $layer.id = 'qrcodeBox';
        $layer.innerHTML = '

打开控制端
';
        var $body = document.getElementsByTagName('body')[0];
        $body.appendChild($layer);
        var $container = document.getElementById('container');

        showQrcode = function(e) {
            if (showQrcode.isShow) {
                // $container.style.display = 'block';
                $layer.style.display = 'none';
                showQrcode.isShow = false;
            } else {
                // $container.style.display = 'none';
                $layer.style.display = 'block';
                showQrcode.isShow = true;
            }
        };
    };

    var webSocket;

    var Socket = {
        host: '',
        role: '', //角色
        clientConnect: function() {
            //角色是client,即被控制端,则连控制端服务器
            webSocket.on('data from another client', function(data) {
                var action = data.action;
                switch (action) {
                    case 'from control order':
                        var fnName = data.fn;
                        var args = data.args;
                        try {
                            args = JSON.parse(args);
                        } catch (e) {}
                        Slide.proxyFn(fnName, args);
                        break;
                    case 'from control updateItem':
                    case 'from control update':
                    case 'from control key event':
                        broadcast.fire(action, data);
                        break;
                    default:
                        broadcast.fire(action, data.data);
                }
            });

        },
        controlConnect: function() {
            webSocket.emit('add client', {
                targetUid: this.clientUID
            });

            //控制端不在直接运行函数,而是变成发送socket给client
            //注意参数,进行了json处理哦~
            Slide.proxyFn = function(fnName, args) {
                args = JSON.stringify(args);
                webSocket.emit('repost data', {
                    action: 'from control order',
                    fn: fnName,
                    args: args
                });
            };
            //角色是控制端,则连被控制端(client)服务器

            webSocket.on('data from another client', function(data) {
                var action = data.action;
                if (action.indexOf('client') !== -1) {
                    return;
                }
                action = action.replace('client', 'control');

                broadcast.fire(action, data);

                // switch (action) {
                //     case 'from client update':
                //         broadcast.fire('from control update', data);
                //         break;
                //     case 'from client updateItem':
                //         broadcast.fire('from control updateItem', data);
                //         break;
                // }
            });

        },
        connect: function() {
            webSocket = io.connect(this.host);
            webSocket.on('UUID', function(uid) {
                webSocket.uid = uid;
                if (Socket.role === 'client') {
                    MixJS.loadJS('/js/qrcode.js', function() {
                        qrcodeLink();
                        var url = location.href.split('#')[0];
                        url += (!~url.indexOf('?')) ? '?' : '&';
                        url += 'iscontroller=1&clientid=' + uid;
                        var qrcode = new QRCode('qrcode', {
                            text: url,
                            width: 256,
                            height: 256
                        });
                        document.getElementById('ctrlLink').href = url;
                    });
                }
            });
            webSocket.on('system', function(data) {
                // console.log(data);
                if (showQrcode && showQrcode.isShow) {
                    showQrcode();
                }
            });

            this[this.role + 'Connect']();
        },
        broadcast: function(evtName, data) {
            webSocket.emit('repost data', {
                action: 'from control ' + evtName,
                data: data
            });
        },
        update: function(id) {
            webSocket.emit('repost data', {
                action: 'from ' + Socket.role + ' update',
                id: id
            });
        },
        updateItem: function(id, item) {
            webSocket.emit('repost data', {
                action: 'from ' + Socket.role + ' updateItem',
                id: id,
                item: item
            });
        },
        keyEvent: function(keyCode) {
            webSocket.emit('repost data', {
                action: 'from ' + Socket.role + ' key event',
                keyCode: keyCode
            });
        },

        init: function(args) {
            this.host = args.host || location.href;
            this.clientUID = args.clientId;
            // console.log(this.clientUID);
            //角色,是否为控制端
            if (args.isControl) {
                console.log(this.clientUID);
                this.role = 'control';
                var $body = document.body;
                $body.classList.add('popup');
                $body.classList.add('with-notes');
                var $timer = document.createElement('time');
                $timer.id = '_timer_';
                $body.appendChild($timer);
                var hour = 0,
                    sec = 0,
                    min = 0;
                timer = setInterval(function() {
                    sec++;
                    if (sec === 60) {
                        sec = 0;
                        min++;
                    }
                    if (min === 60) {
                        hour++;
                    }
                    $timer.innerHTML = ['时间:' + time2str(hour), time2str(min), time2str(sec) + ' 幻灯片:' + Slide.current + '/' + Slide.count].join(':');
                }, 1000);
            } else {
                this.role = 'client';
            }
            if (args.shake) {
                //添加shake
                MixJS.loadJS(Slide.dir + 'shake.js', function() {
                    var lastTime = Date.now();
                    window.addEventListener('shake', function() {
                        var now = Date.now();
                        if (now - lastTime > 3000) {
                            lastTime = now;
                            Slide.next();
                        }
                    }, true);

                });
            }

            MixJS.loadJS(socketIOURL, function() {
                Socket.connect();
            });
        }
    };
    return Socket;
});


text:
<!DOCTYPE html>

<title>ALIXAN</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="w3.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Raleway">

  Ertak

TEZ KUNDA

ALIXAN

    Tashkil etuvchi Ahrorbek Alisherov


text:
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include <stdio.h>
#include <signal.h>
#include <time.h>
#include <unistd.h>
#include <sys/syscall.h>

#ifdef __NR_timer_create

int
main(void)
{
	int tid[4] = {};
	struct sigevent sev = {
		.sigev_notify = SIGEV_NONE,
		.sigev_signo = 0xfacefeed,
		.sigev_value.sival_ptr =
			(void *) (unsigned long) 0xdeadbeefbadc0ded
	};

	if (syscall(__NR_timer_create, CLOCK_REALTIME, &sev, &tid[0]))
		return 77;
	printf("timer_create(CLOCK_REALTIME, {sigev_value={int=%d, ptr=%p}"
	       ", sigev_signo=%u, sigev_notify=SIGEV_NONE}"
	       ", [%d]) = 0\n",
	       sev.sigev_value.sival_int,
	       sev.sigev_value.sival_ptr,
	       sev.sigev_signo, tid[0]);

	sev.sigev_notify = SIGEV_SIGNAL;
	sev.sigev_signo = SIGALRM;
	if (syscall(__NR_timer_create, CLOCK_MONOTONIC, &sev, &tid[1]))
		return 77;
	printf("timer_create(CLOCK_MONOTONIC, {sigev_value={int=%d, ptr=%p}"
	       ", sigev_signo=SIGALRM, sigev_notify=SIGEV_SIGNAL}"
	       ", [%d]) = 0\n",
	       sev.sigev_value.sival_int,
	       sev.sigev_value.sival_ptr, tid[1]);

	sev.sigev_notify = SIGEV_THREAD;
	sev.sigev_notify_function =
		(void *) (unsigned long) 0xdeadbeefbadc0ded;
	sev.sigev_notify_attributes =
		(void *) (unsigned long) 0xcafef00dfacefeed;
	if (syscall(__NR_timer_create, CLOCK_REALTIME, &sev, &tid[2]))
		return 77;
	printf("timer_create(CLOCK_REALTIME, {sigev_value={int=%d, ptr=%p}"
	       ", sigev_signo=SIGALRM, sigev_notify=SIGEV_THREAD"
	       ", sigev_notify_function=%p, sigev_notify_attributes=%p}"
	       ", [%d]) = 0\n",
	       sev.sigev_value.sival_int,
	       sev.sigev_value.sival_ptr,
	       sev.sigev_notify_function,
	       sev.sigev_notify_attributes,
	       tid[2]);

#ifndef sigev_notify_thread_id
# if defined HAVE_STRUCT_SIGEVENT__SIGEV_UN__PAD
#  define sigev_notify_thread_id _sigev_un._pad[0]
# elif defined HAVE_STRUCT_SIGEVENT___PAD
#  define sigev_notify_thread_id __pad[0]
# endif
#endif /* !sigev_notify_thread_id */

#ifdef sigev_notify_thread_id
# ifndef SIGEV_THREAD_ID
#  define SIGEV_THREAD_ID 4
# endif
	sev.sigev_notify = SIGEV_THREAD_ID;
	sev.sigev_notify_thread_id = getpid();
	if (syscall(__NR_timer_create, CLOCK_MONOTONIC, &sev, &tid[3]))
		return 77;
	printf("timer_create(CLOCK_MONOTONIC, {sigev_value={int=%d, ptr=%p}"
	       ", sigev_signo=SIGALRM, sigev_notify=SIGEV_THREAD_ID"
	       ", sigev_notify_thread_id=%d}"
	       ", [%d]) = 0\n",
	       sev.sigev_value.sival_int,
	       sev.sigev_value.sival_ptr,
	       sev.sigev_notify_thread_id,
	       tid[3]);
#endif /* sigev_notify_thread_id */

	puts("+++ exited with 0 +++");
	return 0;
}

#else

int
main(void)
{
	return 77;
}

#endif


text:
Any item in the config.json file starting with an underscore character are ignored.

Ignored

```json
"_title": "MyServer"
```

Valid setting

```json
"title": "MyServer"
```

json requires correct formatting, if in doubt copy/paste your json config into a web based format checker to make sure you have it right: <https://duckduckgo.com/?va=j&t=hc&q=json+lint&ia=answer>

## Help! I've been hacked there are weird agents appearing in my MeshCentral Console

No, you haven't.

1. Your agent installer was scanned by an antivirus.

2. It didn't recognize the exe.

3. You have the option enabled to submit unknown applications for analysis.

    ![AV Option1](images/faq_av_option1.png)

4. They ran it against their virtualization testing cluster.

5. You allow anyone to connect to your server (you should look into techniques to hide your server from the internet).

6. Here are some examples of what that looks like.

# Can't login on server after first setup

You're sure you're typing in everything right, giving it 2FA code and can't login

[TOTP](https://en.wikipedia.org/wiki/Time-based_one-time_password) is time sensitive, check your time/NTP and make sure it's right (on server and TOTP app device)! :)

![](images/2022-08-04-18-19-19.png)

# Branding and Customization

You can brand and customize MeshCentral almost as much as you like without delving into the code, a few changes in the config.json file and uploading images can change the way your system looks. Read more [here](https://ylianst.github.io/MeshCentral/meshcentral/#branding-terms-of-use)

!!!note
    You will need to reinstall the agent for agent customizations to take effect.


text:
//  Estimote Fleet Management SDK
//  Copyright © 2015 Estimote. All rights reserved.

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@class ESTSettingEddystoneTLMEnable, ESTSettingEddystoneTLMInterval, ESTSettingEddystoneTLMPower, ESTDeviceSettingsCollection;

/**
 *  ESTSettingsEddystoneTLM represents a group of settings related to Eddystone Telemetry packet.
 */
@interface ESTSettingsEddystoneTLM : NSObject

/**
 *  Eddystone Telemetry enable setting.
 */
@property (nonatomic, strong, readonly) ESTSettingEddystoneTLMEnable *enable;

/**
 *  Eddystone Telemetry advertising interval setting.
 */
@property (nonatomic, strong, readonly) ESTSettingEddystoneTLMInterval *interval;

/**
 *  Eddystone Telemetry power setting.
 */
@property (nonatomic, strong, readonly) ESTSettingEddystoneTLMPower *power;

/**
 *  Designated initializer.
 *
 *  @param settingsCollection Collection of settings containing Eddystone Telemetry related settings.
 *
 *  @return Initialized object.
 */
- (instancetype)initWithSettingsCollection:(ESTDeviceSettingsCollection *)settingsCollection;

@end

NS_ASSUME_NONNULL_END


text:
require 'spec_helper'

describe 'upcase', if: Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do
  describe 'signature validation' do
    it { is_expected.not_to eq(nil) }
    it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) }
    it { is_expected.to run.with_params('', '').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) }
    it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{Requires an array, hash or object that responds to upcase}) }
    it { is_expected.to run.with_params([1]).and_raise_error(Puppet::ParseError, %r{Requires an array, hash or object that responds to upcase}) }
  end

  describe 'normal string handling' do
    it { is_expected.to run.with_params('abc').and_return('ABC') }
    it { is_expected.to run.with_params('Abc').and_return('ABC') }
    it { is_expected.to run.with_params('ABC').and_return('ABC') }
  end

  describe 'handling classes derived from String' do
    it { is_expected.to run.with_params(AlsoString.new('ABC')).and_return('ABC') }
  end

  describe 'strings in arrays handling' do
    it { is_expected.to run.with_params([]).and_return([]) }
    it { is_expected.to run.with_params(['One', 'twO']).and_return(['ONE', 'TWO']) }
  end
end


text:
// Copyright (c) 2022, WNProject Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// clang-format off

#ifndef ROCKETDEBUGGER_H
#define ROCKETDEBUGGER_H

#include "Debugger/Debugger.h"

#endif


text:
CREATE TABLE intervaltmp (a interval);

\copy intervaltmp from 'data/interval.data'

SET enable_seqscan=on;

SELECT count(*) FROM intervaltmp WHERE a <  '199 days 21:21:23';

SELECT count(*) FROM intervaltmp WHERE a <= '199 days 21:21:23';

SELECT count(*) FROM intervaltmp WHERE a  = '199 days 21:21:23';

SELECT count(*) FROM intervaltmp WHERE a >= '199 days 21:21:23';

SELECT count(*) FROM intervaltmp WHERE a >  '199 days 21:21:23';

CREATE INDEX intervalidx ON intervaltmp USING gist ( a );

SET enable_seqscan=off;

SELECT count(*) FROM intervaltmp WHERE a <  '199 days 21:21:23'::interval;

SELECT count(*) FROM intervaltmp WHERE a <= '199 days 21:21:23'::interval;

SELECT count(*) FROM intervaltmp WHERE a  = '199 days 21:21:23'::interval;

SELECT count(*) FROM intervaltmp WHERE a >= '199 days 21:21:23'::interval;

SELECT count(*) FROM intervaltmp WHERE a >  '199 days 21:21:23'::interval;


text:
package com.equalize.xpi.af.modules.tester.junit;

import static org.junit.Assert.assertEquals;

import java.util.Hashtable;

import org.junit.Test;

import com.equalize.xpi.af.modules.tester.ModuleTester;
import com.equalize.xpi.tester.util.ParameterHelper;
import com.equalize.xpi.tester.util.ResultHelper;
import com.sap.aii.af.lib.mp.module.ModuleException;

public class JSON2XMLTest {

	@Test
	public void testScenario1() throws ModuleException {
		String inputFile = "TestData/Module/JSONTransformBean/JSON2XML_Scenario1_glossary.json";
		String paramFile = "TestData/Module/JSONTransformBean/JSON2XML_Scenario1_glossary_param.txt";
		String resultFile = "TestData/Module/JSONTransformBean/JSON2XML_Scenario1_glossary_output.txt";
		Hashtable<String, String> contextData = ParameterHelper.newInstance(paramFile).getParams();
		String results = ResultHelper.newInstance(resultFile).getResultContent();
		ModuleTester mt = ModuleTester.newInstance("com.equalize.xpi.af.modules.FormatConversionBean", inputFile, contextData);

		assertEquals("Error", results, mt.execute());
	}
	@Test
	public void testScenario3() throws ModuleException {
		String inputFile = "TestData/Module/JSONTransformBean/JSON2XML_Scenario3_array.json";
		String paramFile = "TestData/Module/JSONTransformBean/JSON2XML_Scenario3_array_param.txt";
		String resultFile = "TestData/Module/JSONTransformBean/JSON2XML_Scenario3_array_output.txt";
		Hashtable<String, String> contextData = ParameterHelper.newInstance(paramFile).getParams();
		String results = ResultHelper.newInstance(resultFile).getResultContent();
		ModuleTester mt = ModuleTester.newInstance("com.equalize.xpi.af.modules.FormatConversionBean", inputFile, contextData);

		assertEquals("Error", results, mt.execute());
	}
}


text:
import logging
from functools import partial

import rdflib.term as rt
from rdflib.plugins.parsers.pyMicrodata import pyMicrodata
from rdflib.plugins.parsers.pyRdfa import pyRdfa

from .errors import _error
from .validationresult import ValidationResult, ValidationWarning

log = logging.getLogger(__name__)

class SchemaValidator(object):
    """ASSUMPTIONS:
        This class knows about the file being validated, but it recieves that
        file as a graph and a doc_lines
        It does not perform any parsing logic on the file
        It recieves a "validatable" graph object and returns errors"""
    def __init__(self, graph, doc_lines, url=""):
        super(SchemaValidator, self).__init__()
        self.schema_def = None
        self.allowed_namespaces = []
        self.graph = graph
        self.checked_attributes = []
        self.stripped_attribute_names = {}

        log.info("init validator: %s" % self.__class__.__name__)
        self.doc_lines = doc_lines

        self.err = partial(_error, doc_lines=self.doc_lines)

    def validate(self):
        """Iterate over all triples in the graph and validate each one
            appropriately
        """
        log.info("{}\nValidating against {}"
                 .format("-" * 100, self.schema_def.__class__.__name__))

        if not self.schema_def:
            raise ValueError("No schema definition supplied.")

        self.checked_attributes = []

        # TODO - this should maybe choose the actually used namespace, not just
        # the first one in the list
        result = ValidationResult(self.allowed_namespaces[0],
                                  self.schema_def.__class__.__name__)
        for subject, predicate, object_ in self.graph:
            log.info("\nsubj: {subj}\npred: {pred}\n obj: {obj}"
                     .format(subj=subject, pred=predicate,
                             obj=object_.encode('utf-8')))
            result.add_error(self._check_triple((subject, predicate, object_)))
        return result

    def _should_ignore_predicate(self, predicate):
        ignored_predicates = ['type', 'item', 'first', 'rest']
        return self._field_name_from_uri(predicate) in ignored_predicates

    def _check_triple(self, triple):
        """compare triple to ontology, return error or None"""
        subj, pred, obj = triple

        if self._should_ignore_predicate(pred):
            log.info("Ignoring triple with predicate '{}'"
                     .format(self._field_name_from_uri(pred)))
            return

        classes = []
        log.warning("Possible member %s found" % pred)

        pred = self._expand_qname(pred)

        if self._namespace_from_uri(pred) not in self.allowed_namespaces:
            log.info("Member %s does not use an allowed namespace", pred)
            return

        instanceof = self._is_instance((subj, pred, obj))
        if type(instanceof) == rt.URIRef:
            instanceof = self._expand_qname(instanceof)

        if hasattr(self.schema_def, "attributes_by_class") and \
           not self.schema_def.attributes_by_class:
            log.info("Parsed ontology not found. Parsing...")
            self.schema_def.parse_ontology()

        class_invalid = self._validate_class(instanceof)
        if class_invalid:
            log.warning("Invalid class %s" % instanceof)
            return class_invalid
        # TODO - the above sometimes fails when a single object has more than
        # one rdfa type (eg <span property="schema:creator rnews:creator"
        # typeof="schema:Person rnews:Person">
        # Graph chooses the type in an arbitrary order, so it's unreliable
        # eg: http://semanticweb.com/the-impact-of-rdfa_b35003

        classes = self._superclasses_for_subject(self.graph, instanceof)
        classes.append(instanceof)

        member_invalid = self._validate_member(pred, classes, instanceof)
        if member_invalid:
            log.warning("Invalid member of class")
            return member_invalid

        dupe_invalid = self._validate_duplication((subj, pred), instanceof)
        if dupe_invalid:
            log.warning("Duplication found")
            return dupe_invalid

        # collect a list of checked attributes
        self.checked_attributes.append((subj, pred))
        log.warning("successfully validated triple, no errors")
        return

    def _validate_class(self, cl):
        """return error if class `cl` is not found in the ontology"""
        if cl not in self.schema_def.attributes_by_class:
            search_string = self._build_search_string(cl)
            err = self.err(
                "{0} - invalid class", self._field_name_from_uri(cl),
                search_string=search_string)
            return ValidationWarning(ValidationResult.ERROR, err['err'],
                                     err['line'], err['num'])

    def _get_stripped_attributes(self, member, classes):
        stripped = []
        if member not in self.stripped_attribute_names:
            for cl in classes:
                stripped.extend(
                    [self._field_name_from_uri(attr)
                     for attr in self.schema_def.attributes_by_class[cl]])
            self.stripped_attribute_names[member] = stripped
        else:
            stripped = self.stripped_attribute_names[member]
        return stripped

    def _validate_member(self, member, classes, instanceof):
        """return error if `member` is not a member of any class in
        `classes`
        """
        log.info("Validating member %s" % member)

        stripped = self._get_stripped_attributes(member, classes)
        if self._field_name_from_uri(member) in stripped:
            all_class_members = sum([self.schema_def.attributes_by_class[cl]
                                     for cl in classes], [])
            if member in all_class_members:
                return
            if self._namespace_from_uri(member) in self.allowed_namespaces:
                err = self.err("Unoficially allowed namespace {0}",
                               self._namespace_from_uri(member))
                return ValidationWarning(ValidationResult.WARNING, err['err'],
                                         err['line'], err['num'])
        else:
            err = self.err("{0} - invalid member of {1}",
                           self._field_name_from_uri(member),
                           self._field_name_from_uri(instanceof))
            return ValidationWarning(ValidationResult.ERROR, err['err'],
                                     err['line'], err['num'])

    def _validate_duplication(self, subj_and_pred, cl):
        """returns error if we've already seen the member `pred` on `subj`"""
        subj, pred = subj_and_pred

        log.info("Validating duplication of member %s" % pred)
        if (subj, pred) in self.checked_attributes:
            err = self.err("{0} - duplicated member of {1}",
                           self._field_name_from_uri(pred),
                           self._field_name_from_uri(cl))
            return ValidationWarning(ValidationResult.WARNING, err['err'],
                                     err['line'], err['num'])

    def _superclasses_for_subject(self, graph, typeof):
        """helper, returns a list of all superclasses of a given class"""
        # TODO - this might be replacing a fairly simple graph API query where
        # it doesn't need to
        classes = []
        superclass = typeof
        while True:
            found = False
            for p, o in self.schema_def.ontology[superclass]:
                if self.schema_def.lexicon['subclass'] == str(p):
                    found = True
                    classes.append(o)
                    superclass = o
            if not found:
                break
        return classes

    def _is_instance(self, triple):
        """helper, returns the class type of subj"""
        subj, pred, obj = triple
        input_pred_ns = self._namespace_from_uri(self._expand_qname(pred))
        triples = self.graph.triples(
            (subj, rt.URIRef(self.schema_def.lexicon['type']), None)
        )
        if triples:
            for tr in triples:
                triple_obj_ns = self._namespace_from_uri(
                    self._expand_qname(tr[2]))
                if input_pred_ns == triple_obj_ns:  # match namespaces
                    return tr[2]  # return the object

    def _field_name_from_uri(self, uri):
        """helper, returns the name of an attribute (without namespace prefix)
        """
        # TODO - should use graph API
        uri = str(uri)
        parts = uri.split('#')
        if len(parts) == 1:
            return uri.split('/')[-1] or uri
        return parts[-1]

    def _namespace_from_uri(self, uri):
        """returns the expanded namespace prefix of a uri"""
        # TODO - this could be helped a bunch with proper use of the graph API
        # it seems a bit fragile to treat these as simple string-splits
        uri = str(uri)
        parts = uri.split('#')
        if len(parts) == 1:
            return "%s/" % '/'.join(uri.split('/')[:-1])
        return "%s#" % '#'.join(parts[:-1])

    def _expand_qname(self, qname):
        """expand a qualified name's namespace prefix to include the resolved
        namespace root url"""
        if type(qname) is not rt.URIRef:
            raise TypeError("Cannot expand qname of type {}, must be URIRef"
                            .format(type(qname)))
        for ns in self.graph.namespaces():
            if ns[0] == qname.split(':')[0]:
                return rt.URIRef("%s%s" % (ns[1], qname.split(':')[-1]))
        return qname

    def _build_search_string(self, uri):
        return self._field_name_from_uri(uri)

class RdfValidator(SchemaValidator):
    def __init__(self, graph, doc_lines, url=""):
        super(RdfValidator, self).__init__(graph, doc_lines, url=url)
        self.parser = pyRdfa()
        # use the rdfa half of the compound graph
        self.graph = self.graph.rdfa_graph

class MicrodataValidator(SchemaValidator):
    def __init__(self, graph, doc_lines, url=""):
        super(MicrodataValidator, self).__init__(graph, doc_lines, url=url)
        self.parser = pyMicrodata()
        # use the microdata half of the compound
        self.graph = self.graph.microdata_graph

    def _build_search_string(self, uri):
        return str(uri)


text:
package org.apache.accumulo.core.volume;

import static java.util.Objects.requireNonNull;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import org.apache.accumulo.core.conf.AccumuloConfiguration;
import org.apache.accumulo.core.conf.Property;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

public class VolumeConfiguration {

  public static Volume getVolume(String path, Configuration conf, AccumuloConfiguration acuconf)
      throws IOException {
    requireNonNull(path);

    if (path.contains(":")) {
      // An absolute path
      return create(new Path(path), conf);
    } else {
      // A relative path
      return getDefaultVolume(conf, acuconf);
    }
  }

  public static Volume getDefaultVolume(Configuration conf, AccumuloConfiguration acuconf)
      throws IOException {
    @SuppressWarnings("deprecation")
    String uri = acuconf.get(Property.INSTANCE_DFS_URI);

    // By default pull from INSTANCE_DFS_URI, falling back to the Hadoop defined
    // default filesystem (fs.defaultFS or the deprecated fs.default.name)
    if ("".equals(uri))
      return create(FileSystem.get(conf), acuconf);
    else
      try {
        return create(FileSystem.get(new URI(uri), conf), acuconf);
      } catch (URISyntaxException e) {
        throw new IOException(e);
      }
  }

  /**
   * @see org.apache.accumulo.core.volume.VolumeConfiguration#getVolumeUris(AccumuloConfiguration,Configuration)
   */
  @Deprecated
  public static String getConfiguredBaseDir(AccumuloConfiguration conf,
      Configuration hadoopConfig) {
    String singleNamespace = conf.get(Property.INSTANCE_DFS_DIR);
    String dfsUri = conf.get(Property.INSTANCE_DFS_URI);
    String baseDir;

    if (dfsUri == null || dfsUri.isEmpty()) {
      try {
        baseDir = FileSystem.get(hadoopConfig).getUri() + singleNamespace;
      } catch (IOException e) {
        throw new RuntimeException(e);
      }
    } else {
      if (!dfsUri.contains(":"))
        throw new IllegalArgumentException("Expected fully qualified URI for "
            + Property.INSTANCE_DFS_URI.getKey() + " got " + dfsUri);
      baseDir = dfsUri + singleNamespace;
    }
    return baseDir;
  }

  public static String[] getVolumeUris(AccumuloConfiguration conf, Configuration hadoopConfig) {
    String ns = conf.get(Property.INSTANCE_VOLUMES);

    String[] configuredBaseDirs;

    if (ns == null || ns.isEmpty()) {
      // Fall back to using the old config values
      configuredBaseDirs = new String[] {getConfiguredBaseDir(conf, hadoopConfig)};
    } else {
      String[] namespaces = ns.split(",");
      configuredBaseDirs = new String[namespaces.length];
      int i = 0;
      for (String namespace : namespaces) {
        if (!namespace.contains(":")) {
          throw new IllegalArgumentException("Expected fully qualified URI for "
              + Property.INSTANCE_VOLUMES.getKey() + " got " + namespace);
        }

        try {
          // pass through URI to unescape hex encoded chars (e.g. convert %2C to "," char)
          configuredBaseDirs[i++] = new Path(new URI(namespace)).toString();
        } catch (URISyntaxException e) {
          throw new IllegalArgumentException(Property.INSTANCE_VOLUMES.getKey() + " contains "
              + namespace + " which has a syntax error", e);
        }
      }
    }

    return configuredBaseDirs;
  }

  public static String[] prefix(String[] bases, String suffix) {
    if (suffix.startsWith("/"))
      suffix = suffix.substring(1);
    String[] result = new String[bases.length];
    for (int i = 0; i < bases.length; i++) {
      if (bases[i].endsWith("/")) {
        result[i] = bases[i] + suffix;
      } else {
        result[i] = bases[i] + "/" + suffix;
      }
    }
    return result;
  }

  /**
   * Create a Volume with the given FileSystem that writes to the default path
   *
   * @param fs
   *          A FileSystem to write to
   * @return A Volume instance writing to the given FileSystem in the default path
   */
  @SuppressWarnings("deprecation")
  public static <T extends FileSystem> Volume create(T fs, AccumuloConfiguration acuconf) {
    String dfsDir = acuconf.get(Property.INSTANCE_DFS_DIR);
    return new VolumeImpl(fs,
        dfsDir == null ? Property.INSTANCE_DFS_DIR.getDefaultValue() : dfsDir);
  }

  public static <T extends FileSystem> Volume create(T fs, String basePath) {
    return new VolumeImpl(fs, basePath);
  }

  public static Volume create(Path path, Configuration conf) throws IOException {
    return new VolumeImpl(path, conf);
  }

}


text:
<?php
/**
 * Twenty Thirteen functions and definitions
 *
 * Sets up the theme and provides some helper functions, which are used in the
 * theme as custom template tags. Others are attached to action and filter
 * hooks in WordPress to change core functionality.
 *
 * When using a child theme (see http://codex.wordpress.org/Theme_Development
 * and http://codex.wordpress.org/Child_Themes), you can override certain
 * functions (those wrapped in a function_exists() call) by defining them first
 * in your child theme's functions.php file. The child theme's functions.php
 * file is included before the parent theme's file, so the child theme
 * functions would be used.
 *
 * Functions that are not pluggable (not wrapped in function_exists()) are
 * instead attached to a filter or action hook.
 *
 * For more information on hooks, actions, and filters, @link http://codex.wordpress.org/Plugin_API
 *
 * @package WordPress
 * @subpackage Twenty_Thirteen
 * @since Twenty Thirteen 1.0
 */

/**
 * Print HTML with meta information for current post: categories, tags, permalink, author, and date.
 *
 * Create your own twentythirteen_entry_meta() to override in a child theme.
 *
 * @since Twenty Thirteen 1.0
 *
 * @return void
 */
function twentythirteen_entry_meta() {
	if ( is_sticky() && is_home() && ! is_paged() )
		echo '' . __( 'Sticky', 'twentythirteen' ) . '';

	if ( ! has_post_format( 'link' ) && 'post' == get_post_type() ) {
		twentythirteen_entry_date();
	}

	$first = 1;
	foreach((get_the_category()) as $category) {
		if ( $first == 1 ) {
			$first = 0;
			echo " on " . $category->cat_name;
		}
		else {
 			echo ", " . $category->cat_name;
 		}
 	}

}

/**
 * Print HTML with date information for current post.
 *
 * Create your own twentythirteen_entry_date() to override in a child theme.
 *
 * @since Twenty Thirteen 1.0
 *
 * @param boolean $echo (optional) Whether to echo the date. Default true.
 * @return string The HTML-formatted post date.
 */
function twentythirteen_entry_date( $echo = true ) {
	if ( has_post_format( array( 'chat', 'status' ) ) )
		$format_prefix = _x( '%1$s on %2$s', '1: post format name. 2: date', 'twentythirteen' );
	else
		$format_prefix = '%2$s';

	$date = sprintf( '<time class="entry-date" datetime="%1$s">%2$s</time>',
		esc_attr( get_the_date( 'c' ) ),
		esc_html( sprintf( $format_prefix, get_post_format_string( get_post_format() ), get_the_date() ) )
	);

	if ( $echo )
		echo $date;

	return $date;
}

/**
 * Enqueue scripts and styles for the front end.
 *
 * @since Twenty Thirteen 1.0
 *
 * @return void
 */
function custom_twentythirteen_scripts_styles() {
    /*
     * Adds JavaScript to pages with the comment form to support
     * sites with threaded comments (when in use).
     */
    if ( is_singular() && comments_open() && get_option( 'thread_comments' ) )
            wp_enqueue_script( 'comment-reply' );

    // Loads JavaScript file with functionality specific to Twenty Thirteen.
    wp_enqueue_script( 'twentythirteen-script', get_template_directory_uri() . '/js/functions.js', array( 'jquery' ), '2013-07-18', true );

    // Add Source Sans Pro and Bitter fonts, used in the main stylesheet.
    wp_enqueue_style( 'twentythirteen-fonts', twentythirteen_fonts_url(), array(), null );

    // Add Genericons font, used in the main stylesheet.
    wp_enqueue_style( 'genericons', get_template_directory_uri() . '/fonts/genericons.css', array(), '2.09' );

    // Loads our main stylesheet.
    wp_enqueue_style( 'twentythirteen-style', get_stylesheet_uri(), array(), '2013-07-18' );

    // Loads the Internet Explorer specific stylesheet.
    wp_enqueue_style( 'twentythirteen-ie', get_template_directory_uri() . '/css/ie.css', array( 'twentythirteen-style' ), '2013-07-18' );
    wp_style_add_data( 'twentythirteen-ie', 'conditional', 'lt IE 9' );
}
add_action( 'wp_enqueue_scripts', 'custom_twentythirteen_scripts_styles' );

/**
 * Display the home tab in the navigation bar.
 */
function twentythirteenchild_page_menu_args( $args ) {
    $args['show_home'] = true;
    return $args;
}
add_filter( 'wp_page_menu_args', 'twentythirteenchild_page_menu_args', 40 );


text:
NSString * const ENLicenseEchoSource = @"echo-source";
NSString * const ENLicenseAllRightsReserved = @"all-rights-reserved";
NSString * const ENLicenseCreativeCommonsBy_SA = @"cc-by-sa";
NSString * const ENLicenseCreativeCommonsBy_NC = @"cc-by-nc";
NSString * const ENLicenseCreativeCommonsBy_NC_ND = @"cc-by-nc-nd";
NSString * const ENLicenseCreativeCommonsBy_NC_SA = @"cc-by-nc-sa";
NSString * const ENLicenseCreativeCommonsBy_ND = @"cc-by-nd";
NSString * const ENLicenseCreativeCommonsBy = @"cc-by";
NSString * const ENLicensePublicDomain = @"public-domain";
NSString * const ENLicenseUnknown = @"unknown";

NSString * const ENSortFamiliarityAscending = @"familiarity-asc";
NSString * const ENSortFamiliarityDescending = @"familiarity-desc";
NSString * const ENSortHotttnesssAscending = @"hotttnesss-asc";
NSString * const ENSortHotttnesssDescending = @"hotttnesss-desc";
NSString * const ENSortWeight = @"weight";
NSString * const ENSortFrequency = @"frequency";

static NSString *EN_API_KEY = nil;
static NSString *EN_CONSUMER_KEY = nil;
static NSString *EN_SHARED_SECRET = nil;
static NSMutableArray *EN_SECURED_ENDPOINTS = nil;

@implementation ENAPI

+ (void)initWithApiKey:(NSString *)apiKey {
    EN_API_KEY = apiKey;
}

+ (void)initWithApiKey:(NSString *)apiKey ConsumerKey:(NSString *)consumerKey
       AndSharedSecret:(NSString *)secret {
    [ENAPI initWithApiKey:apiKey];
    [ENAPI addSecuredEndpoint:@"sandbox/access"];
    [ENAPI setConsumerKey:consumerKey];
    [ENAPI setSharedSecret:secret];
}

+ (NSString *)apiKey {
    return EN_API_KEY;
}

+ (NSString *)consumerKey {
    return EN_CONSUMER_KEY;
}

+ (void)setConsumerKey:(NSString *)key {
    if (EN_CONSUMER_KEY != key) {
        EN_CONSUMER_KEY = key;
    }
}

+ (NSString *)sharedSecret {
    return EN_SHARED_SECRET;
}

+ (void)setSharedSecret:(NSString *)secret {
    if (EN_SHARED_SECRET != secret) {
        // API is not using OAuth tokens in the signing process,
        // but the & suffix is still required for the secret.
        if ([secret hasSuffix:@"&"]) {
            EN_SHARED_SECRET = secret;
        } else {
            EN_SHARED_SECRET = [[NSString alloc] initWithFormat:@"%@&", secret];
        }
    }
}

+ (BOOL)isSecuredEndpoint:(NSString *)endpoint {
    return [EN_SECURED_ENDPOINTS containsObject:endpoint];
}

+ (void)addSecuredEndpoint:(NSString *)endpoint {
    if (nil == EN_SECURED_ENDPOINTS) {
        EN_SECURED_ENDPOINTS = [[NSMutableArray alloc] init];
    }
    [EN_SECURED_ENDPOINTS addObject:endpoint];
}

+ (NSArray *)securedEndpoints {
    return [EN_SECURED_ENDPOINTS copy];
}

@end


text:
/MuseSp/bin/mkdic --add noun normal 1 /MuseSp/dict/char_left
/MuseSp/bin/mkdic --delete
/MuseSp/bin/mkdic --relist noun


text:
package com.google.ads.googleads.v11.resources;

import com.google.api.pathtemplate.PathTemplate;
import com.google.api.resourcenames.ResourceName;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import javax.annotation.Generated;

// AUTO-GENERATED DOCUMENTATION AND CLASS.
@Generated("by gapic-generator-java")
public class CampaignConversionGoalName implements ResourceName {
  private static final PathTemplate CUSTOMER_ID_CAMPAIGN_ID_CATEGORY_SOURCE =
      PathTemplate.createWithoutUrlEncoding(
          "customers/{customer_id}/campaignConversionGoals/{campaign_id}~{category}~{source}");
  private volatile Map<String, String> fieldValuesMap;
  private final String customerId;
  private final String campaignId;
  private final String category;
  private final String source;

  @Deprecated
  protected CampaignConversionGoalName() {
    customerId = null;
    campaignId = null;
    category = null;
    source = null;
  }

  private CampaignConversionGoalName(Builder builder) {
    customerId = Preconditions.checkNotNull(builder.getCustomerId());
    campaignId = Preconditions.checkNotNull(builder.getCampaignId());
    category = Preconditions.checkNotNull(builder.getCategory());
    source = Preconditions.checkNotNull(builder.getSource());
  }

  public String getCustomerId() {
    return customerId;
  }

  public String getCampaignId() {
    return campaignId;
  }

  public String getCategory() {
    return category;
  }

  public String getSource() {
    return source;
  }

  public static Builder newBuilder() {
    return new Builder();
  }

  public Builder toBuilder() {
    return new Builder(this);
  }

  public static CampaignConversionGoalName of(
      String customerId, String campaignId, String category, String source) {
    return newBuilder()
        .setCustomerId(customerId)
        .setCampaignId(campaignId)
        .setCategory(category)
        .setSource(source)
        .build();
  }

  public static String format(
      String customerId, String campaignId, String category, String source) {
    return newBuilder()
        .setCustomerId(customerId)
        .setCampaignId(campaignId)
        .setCategory(category)
        .setSource(source)
        .build()
        .toString();
  }

  public static CampaignConversionGoalName parse(String formattedString) {
    if (formattedString.isEmpty()) {
      return null;
    }
    Map<String, String> matchMap =
        CUSTOMER_ID_CAMPAIGN_ID_CATEGORY_SOURCE.validatedMatch(
            formattedString,
            "CampaignConversionGoalName.parse: formattedString not in valid format");
    return of(
        matchMap.get("customer_id"),
        matchMap.get("campaign_id"),
        matchMap.get("category"),
        matchMap.get("source"));
  }

  public static List<CampaignConversionGoalName> parseList(List<String> formattedStrings) {
    List<CampaignConversionGoalName> list = new ArrayList<>(formattedStrings.size());
    for (String formattedString : formattedStrings) {
      list.add(parse(formattedString));
    }
    return list;
  }

  public static List<String> toStringList(List<CampaignConversionGoalName> values) {
    List<String> list = new ArrayList<>(values.size());
    for (CampaignConversionGoalName value : values) {
      if (value == null) {
        list.add("");
      } else {
        list.add(value.toString());
      }
    }
    return list;
  }

  public static boolean isParsableFrom(String formattedString) {
    return CUSTOMER_ID_CAMPAIGN_ID_CATEGORY_SOURCE.matches(formattedString);
  }

  @Override
  public Map<String, String> getFieldValuesMap() {
    if (fieldValuesMap == null) {
      synchronized (this) {
        if (fieldValuesMap == null) {
          ImmutableMap.Builder<String, String> fieldMapBuilder = ImmutableMap.builder();
          if (customerId != null) {
            fieldMapBuilder.put("customer_id", customerId);
          }
          if (campaignId != null) {
            fieldMapBuilder.put("campaign_id", campaignId);
          }
          if (category != null) {
            fieldMapBuilder.put("category", category);
          }
          if (source != null) {
            fieldMapBuilder.put("source", source);
          }
          fieldValuesMap = fieldMapBuilder.build();
        }
      }
    }
    return fieldValuesMap;
  }

  public String getFieldValue(String fieldName) {
    return getFieldValuesMap().get(fieldName);
  }

  @Override
  public String toString() {
    return CUSTOMER_ID_CAMPAIGN_ID_CATEGORY_SOURCE.instantiate(
        "customer_id",
        customerId,
        "campaign_id",
        campaignId,
        "category",
        category,
        "source",
        source);
  }

  @Override
  public boolean equals(Object o) {
    if (o == this) {
      return true;
    }
    if (o != null || getClass() == o.getClass()) {
      CampaignConversionGoalName that = ((CampaignConversionGoalName) o);
      return Objects.equals(this.customerId, that.customerId)
          && Objects.equals(this.campaignId, that.campaignId)
          && Objects.equals(this.category, that.category)
          && Objects.equals(this.source, that.source);
    }
    return false;
  }

  @Override
  public int hashCode() {
    int h = 1;
    h *= 1000003;
    h ^= Objects.hashCode(customerId);
    h *= 1000003;
    h ^= Objects.hashCode(campaignId);
    h *= 1000003;
    h ^= Objects.hashCode(category);
    h *= 1000003;
    h ^= Objects.hashCode(source);
    return h;
  }

  /**
   * Builder for customers/{customer_id}/campaignConversionGoals/{campaign_id}~{category}~{source}.
   */
  public static class Builder {
    private String customerId;
    private String campaignId;
    private String category;
    private String source;

    protected Builder() {}

    public String getCustomerId() {
      return customerId;
    }

    public String getCampaignId() {
      return campaignId;
    }

    public String getCategory() {
      return category;
    }

    public String getSource() {
      return source;
    }

    public Builder setCustomerId(String customerId) {
      this.customerId = customerId;
      return this;
    }

    public Builder setCampaignId(String campaignId) {
      this.campaignId = campaignId;
      return this;
    }

    public Builder setCategory(String category) {
      this.category = category;
      return this;
    }

    public Builder setSource(String source) {
      this.source = source;
      return this;
    }

    private Builder(CampaignConversionGoalName campaignConversionGoalName) {
      this.customerId = campaignConversionGoalName.customerId;
      this.campaignId = campaignConversionGoalName.campaignId;
      this.category = campaignConversionGoalName.category;
      this.source = campaignConversionGoalName.source;
    }

    public CampaignConversionGoalName build() {
      return new CampaignConversionGoalName(this);
    }
  }
}


text:
define([
	"require", "intern!object", "intern/chai!assert", "../utils/testUtils", "gfx/gfx", "gfx/svg", "gfx/canvas"
], function (require, registerSuite, assert, tu, gfx) {

	function get(r) {
		try {
			return gfx[r] || require("gfx/" + r);
		} catch (err) {
		}
	}

	tu.registerSuite({
		name: "Compatibility with 1.X",
		"switchTo(object)": function () {
			var rname = tu.renderer === "svg" ? "canvas" : "svg";
			var r = get(rname);
			gfx.switchTo(r);
			assert.equal(gfx.Surface, r.Surface, "Unexpected Surface type");
			assert.equal(gfx.renderer, rname, "Unexpected renderer");

		},
		"switchTo(string)": function () {
			var r = tu.renderer === "svg" ? "canvas" : "svg";
			gfx.switchTo(r);
			assert.equal(gfx.Surface, get(r).Surface, "Unexpected Surface type");
			assert.equal(gfx.renderer, r, "Unexpected renderer");
		}
	});
});


text:
package com.sksamuel.elastic4s.search.queries

import com.sksamuel.elastic4s.testkit.DockerTests
import org.scalatest.{Matchers, WordSpec}

import scala.util.Try

class ExistsQueryTest extends WordSpec with DockerTests with Matchers {

  Try {
    client.execute {
      deleteIndex("person")
    }.await
  }

  client.execute(
    bulk(
      indexInto("person" / "interest") fields(
        "name" -> "reese",
        "weapon" -> "revolver"
      ),
      indexInto("person" / "interest") fields(
        "name" -> "finch",
        "weapon" -> "computer"
      )
    ).refreshImmediately
  ).await

  "exists query" should {
    "match non-null fields" in {
      client.execute {
        search("person" / "interest") postFilter {
          existsQuery("name")
        }
      }.await.result.totalHits shouldBe 2
    }
    "not match null fields" in {
      client.execute {
        search("person" / "interest") postFilter {
          existsQuery("place")
        }
      }.await.result.totalHits shouldBe 0
    }
  }
}


text:
using System;
using BTDB.IOC.CRegs;

namespace BTDB.IOC
{
    class SingleFactoryRegistration : RegistrationBaseImpl<IAsLiveScopeTrait>, IContanerRegistration
    {
        readonly Type _implementationType;
        readonly AsTraitImpl _asTrait = new AsTraitImpl();
        readonly LiveScopeTraitImpl _liveScopeTrait = new LiveScopeTraitImpl();
        readonly Func<IContainer, object> _factory;

        public SingleFactoryRegistration(Func<IContainer, object> factory, Type type)
        {
            _factory = factory;
            _implementationType = type;
        }

        public void Register(ContainerRegistrationContext context)
        {
            ICRegILGen reg = new FactoryWithContainerParamImpl(context.AddInstance(_factory), _implementationType);
            if (_liveScopeTrait.Lifetime == Lifetime.Singleton)
            {
                reg = new SingletonImpl(_implementationType, reg, context.SingletonCount);
                context.SingletonCount++;
            }
            context.AddCReg(_asTrait.GetAsTypesFor(_implementationType), _asTrait.PreserveExistingDefaults, _asTrait.UniqueRegistration, (ICReg)reg);
        }

        public override object InternalTraits(Type trait)
        {
            if (trait == typeof(IAsTrait)) return _asTrait;
            if (trait == typeof(ILiveScopeTrait)) return _liveScopeTrait;
            throw new ArgumentOutOfRangeException();
        }
    }
}


text:
/*******************************************************************************
*   $FILE:  QDebugTransport.c
*   Atmel Corporation:  http://www.atmel.com \n
*   Support: http://www.atmel.com/design-support/
******************************************************************************/

/**
 *
 * Copyright (c) 2010-2014 Atmel Corporation. All rights reserved.
 *
 * \asf_license_start
 *
 * \page License
 *
 * 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 Atmel may not be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 *
 * 4. This software may only be redistributed and used in connection with an
 *    Atmel microcontroller product.
 *
 * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
 * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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.
 *
 * \asf_license_stop
 *
 */

/*============================ INCLUDES ======================================*/
 /**
 * Support and FAQ: visit Atmel Support
 */
#include "touch_api.h"
#include "QDebug.h"
#include "QDebugTransport.h"
#include "QDebugSettings.h"

#if defined(QDEBUG_SPI)
#include "SPI_Master.h"
#elif defined(QDEBUG_TWI)
#include "TWI_Master.h"
#elif defined(QDEBUG_SPI_BB)
#include "BitBangSPI_Master.h"
#else
#warning "No Debug Interface is selected in QDebugSettings.h"
#endif

/*============================ GLOBAL VARIABLES ==============================*/

uint8_t TX_Buffer[TX_BUFFER_SIZE];
uint16_t TX_index;

uint8_t RX_Buffer[RX_BUFFER_SIZE];
uint16_t RX_index;

uint8_t SequenceL=0;
uint8_t SequenceH=0;

/*============================ IMPLEMENTATION ================================*/

/*============================================================================
Name    :   Init_Buffers
------------------------------------------------------------------------------
Purpose :   Initialize the send and receive buffers
Input   :   n/a
Output  :   n/a
Notes   :	Called from QDebug_Init
============================================================================*/
void Init_Buffers(void)
{
#ifdef __DEBUG__
   int i;

   for (i = 0; i < sizeof(TX_Buffer); i++)
   {
      RX_Buffer[i] = 0;
      RX_Buffer[i] = 0;
   }
#endif

   TX_Buffer[0] = MESSAGE_START;
   TX_index = 4; // Start to add data after MSG_START, MSG_SIZEH, MSG_SIZEL, and Sequence number
   RX_index=0;
}

/*============================================================================
Name    :   PutChar
------------------------------------------------------------------------------
Purpose :   Puts one byte in the Transmit Buffer
Input   :   n/a
Output  :   n/a
Notes   :	TX_index is post incremented
============================================================================*/
void PutChar(uint8_t data)
{
   TX_Buffer[TX_index++] = data;
}

/*============================================================================
Name    :   PutInt
------------------------------------------------------------------------------
Purpose :   Puts two bytes in the Transmit Buffer
Input   :   n/a
Output  :   n/a
Notes   :	Big Endian. TX_index is post incremented
============================================================================*/
void PutInt(uint16_t data)
{
   TX_Buffer[TX_index++] = data >> 8;
   TX_Buffer[TX_index++] = data;
}

/*============================================================================
Name    :   GetChar
------------------------------------------------------------------------------
Purpose :   Get one byte from the Receive Buffer
Input   :   n/a
Output  :   n/a
Notes   :	RX_index is post incremented
============================================================================*/
uint8_t GetChar(void)
{
   return RX_Buffer[RX_index++];
}

/*============================================================================
Name    :   Send_Message
------------------------------------------------------------------------------
Purpose :   Send the content of the TX_Buffer to the USB Bridge using the
interface selected in QDebugSettings.h
Input   :   n/a
Output  :   n/a
Notes   :	Called from the transmit functions in QDebug.c
============================================================================*/
void Send_Message(void)
{
   uint16_t i;
   uint8_t checksum = 0;

   SequenceL= (SequenceL+1)& 0x0F;	// inc and wrap

   // Store length field
   TX_Buffer[1] = (uint8_t)(TX_index >> 8);
   TX_Buffer[2] = (uint8_t)(TX_index & 0xFF);

   // Store Sequence Number
   TX_Buffer[3] = (SequenceH<<4)+SequenceL;

   // Calculate checksum
   for (i=1; i < TX_index; i++)
      checksum ^= TX_Buffer[i];
   TX_Buffer[TX_index] = checksum;

   // Send data using selected interface
#if defined(QDEBUG_SPI)
   SPI_Send_Message();
#elif defined(QDEBUG_TWI)
   TWI_Send_Message();
#elif defined(QDEBUG_SPI_BB)
   BitBangSPI_Send_Message();
#endif

   // Ready for next message
   TX_index = 4;
}

/*============================================================================
Name    :   Receive_Message
------------------------------------------------------------------------------
Purpose :   Executes a master read transmission if TWI is selected as interface
Checks if RX_Buffer has a valid frame
Input   :   n/a
Output  :   returns a true or false dependant on whether a valid frame is
available or not
Notes   :	Called from QDebug_ProcessCommands in QDebug.c
============================================================================*/
uint8_t Receive_Message(void)
{
#if defined(QDEBUG_TWI)
   static uint8_t count=0;

   count++;
   if (count == 10)
   {
      count=0;
      TWI_Retrieve_Message();
   }
   else
   {
      return 0;
   }
#endif

   // Check for token
   if (RX_Buffer[0] != 0x1B)
      return 0;

   // Yes, we have received a valid frame!
   RX_index = 4;	// Next GetChar() will get the command id
   return 1;
}

/*============================================================================
Name    :   RxHandler
------------------------------------------------------------------------------
Purpose :   Handles the incoming bytes from the interface selected in
QDebugSettings.h and puts the bytes in the RX_Buffer
Input   :   data read by the selected interface
Output  :   returns a true if more data must be read
returns a false if the frame is complete
Notes   :	Used by SPI and TWI receive handlers
============================================================================*/
uint8_t RxHandler(uint8_t c)
{
   static uint16_t length = 0;
   static uint16_t received = 0;
   static uint8_t state = STATE_IDLE;
   uint8_t nextstate;
   uint8_t checksum;
   uint16_t i;

   switch (state)
   {
   case STATE_IDLE:
      if (c == 0x1B)
      {
         nextstate = STATE_LENGTH1;
      }
      else
         nextstate = STATE_IDLE;
      break;

   case STATE_LENGTH1:
      RX_Buffer[1] = c;
      length = c << 8;
      nextstate = STATE_LENGTH2;
      break;

   case STATE_LENGTH2:
      RX_Buffer[2] = c;
      length |= c;
      if ((length < 4) || (length > 270))
      {
         // Illegal length, discard it
         nextstate = STATE_IDLE;
      }
      else
      {
         received = 3;
         nextstate = STATE_DATA;
      }
      break;

   case STATE_DATA:
      RX_Buffer[received] = c;
      if (received == length)
      {
         // This is the CRC byte
         checksum = 0;
         for (i = 1; i <= length; i++)
            checksum ^= RX_Buffer[i];

         if (checksum == 0)
         {
            // Valid frame
            RX_Buffer[0] = 0x1B;
         }
         nextstate = STATE_IDLE;
         break;
      }
      nextstate = STATE_DATA;
      received++;;
      break;

   default:
      nextstate = STATE_IDLE;
   }
   state = nextstate;
   return state;
}


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

	<title>Do you even mobile?</title>
	<meta name="description" content="Slide presentation getting a mobile application started">
	<meta name="author" content="Jason Mulligan, Mark Ellis">

	<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, maximum-scale=1.0">
	<meta name="apple-mobile-web-app-capable" content="yes"/>

Copyright © 2016 Jason Mulligan & Mark Ellis


text:
class Bootstrap {
    // needs:
    // - "true" counts
    // - ecmap
    // - target_names
    // - eff_lens
public:
  Bootstrap(const std::vector<int>& true_counts,
            const KmerIndex& index,
            const MinCollector& tc,
            const std::vector<double>& eff_lens,
            size_t seed,
            const std::vector<double>& mean_fls) :
    index_(index),
    tc_(tc),
    eff_lens_(eff_lens),
    seed_(seed),
    mult_(true_counts, seed_),
    mean_fls_(mean_fls)
    {}

  // EM Algorithm generates a sample from the Multinomial, then returns
  // an "EMAlgorithm" that has already run the EM as well as compute the
        // rho values
  EMAlgorithm run_em();

private:
  const KmerIndex& index_;
  const MinCollector& tc_;
  const std::vector<double>& eff_lens_;
  size_t seed_;
  Multinomial mult_;
  const std::vector<double>& mean_fls_;
};

class BootstrapThreadPool {
  friend class BootstrapWorker;

  public:
    BootstrapThreadPool(
        size_t n_threads,
        std::vector<size_t> seeds,
        const std::vector<int>& true_counts,
        const KmerIndex& index,
        const MinCollector& tc,
        const std::vector<double>& eff_lens,
        const ProgramOptions& p_opts,
        H5Writer& h5writer,
        const std::vector<double>& mean_fls
        );

    size_t num_threads() {return n_threads_;}

    ~BootstrapThreadPool();
  private:
    std::vector<size_t> seeds_;
    size_t n_threads_;

    std::vector<std::thread> threads_;
    std::mutex seeds_mutex_;
    std::mutex write_lock_;

    size_t n_complete_;

    // things to run bootstrap
    const std::vector<int> true_counts_;
    const KmerIndex& index_;
    const MinCollector& tc_;
    const std::vector<double>& eff_lens_;
    const ProgramOptions& opt_;
    H5Writer& writer_;
    const std::vector<double>& mean_fls_;
};

class BootstrapWorker {
  public:
    BootstrapWorker(BootstrapThreadPool& pool, size_t thread_id) :
      pool_(pool),
      thread_id_(thread_id)
    {}

  void operator()();

  private:
    BootstrapThreadPool& pool_;
    size_t thread_id_;
};

#endif


text:
Helpful tools for making environment for IDE and build.

#### switch code page
**`manual-code-page.bat`** helps to switch code page for console. Helpful when want to see what compiler or linker  write on output window (in QCreator with MSVC compiler)

#### Remove duplicates
**`uniqSet.bat`** helps to remove duplicates from the list (separated by `;` without `"`).

### Search for libs, headers, pc-files and etc.
**`querySearch.bat`** Make list of subdirectories for directories from the path list, with suffixes if set and check existing of file in the subdirectory by wildcard

`querySearch.bat ArrayVariable [ProjectsPathArray [ProjectPathSuffix [wildcard]]]`

  - ArrayVariable - Variable for resulting list store.
  - ProjectsPathArray - separated by ; list of directories for search. If ProjectsPathArray not set the %CD% will be used
  - ProjectPathSuffix - separated by ; list of each directory suffixes. If not set querySearch collect all first level subdirectories.
  - Wildcard used for check existence of file in a subdirectory. For pkg-config files use *.pc

### Macro for collecting path to libraries, includes, pc-files
**`projectConfig.bat`** used `querySearch` for collecting. Founded list sored in to the proper variable.

`projectConfig.bat "%ProjectPath%;%AnotherPathes%" [LIBPATH INCLUDE]`

First parameter is a directories list separated by `;`. Variables LIBPATH and INCLUDE are name for containers in which `*/lib` and `*/include` subdirectories from directories list will be added. The name used by default are `LIBRARY_PATH` and `CPLUS_INCLUDE_PATH` (mingw style).

#### Configuration for IDE:
Simple:
  * `mingw-env.bat "<extra project path list>"`
  * `msvc-env.bat "<extra project path list>"`

Both of these scripts call projectConfig.bat with `"<extra project path list>"` (for example, ` "%ProjectPath%;%ProjectPath%\opencv\install\x86\vc14"`) as the first parameter, so this list should contain a top directories for the search.

### CMake multi-configuration build helper `buildcmakeproject.bat`
**`buildcmakeproject.bat`** has three forms to make it easier to build an external project.
```batch
call buildcmakeproject <project name> <git address> <cmake additional>
call buildcmakeproject /a  <project name> <source path> <cmake additional>
call buildcmakeproject /b  <project name> <source path> <build path> <install path> <cmake additional>
```
Before you call `buildcmakeproject.bat` set:
1. `DEPENDENCY_ROOT_PATH` - where this script can save some project (source, build) data,
1. `DEPENDENCY_INSTALL_PATH` - where to install after build,
2. `CONFIGURE_CMAKE_GENERATOR` - some text for cmake generator,
3. optionaly `BUILD_CONFIGURATION` - ;-separated list of build types.

Example:
```batch
set DEPENDENCY_ROOT_PATH=c:/dependency
set DEPENDENCY_INSTALL_PATH=%DEPENDENCY_ROOT_PATH%/install

if "%VS150COMNTOOLS%"=="" (
  echo Configure for MinGW
  set CONFIGURE_CMAKE_GENERATOR=-G"CodeBlocks - MinGW Makefiles"
) else (
  echo Configure for MSVC
  call "%VS150COMNTOOLS%..\..\VC\Auxiliary\Build\vcvars64.bat"
  rem set CXXFLAGS=/wd4127
  set CONFIGURE_CMAKE_GENERATOR=-G"Visual Studio 15 Win64" -Thost=x64 -DCMAKE_SHARED_LINKER_FLAGS_DEBUG="/DEBUG:FULL" -DCMAKE_DEBUG_POSTFIX="d"
)
rem set BUILD_CONFIGURATION=Debug

call buildcmakeproject zlib "https://github.com/madler/zlib.git"
call buildcmakeproject /a jpeg "c:/Projects/jpeg"
if "%VS150COMNTOOLS%"=="" (
  call buildcmakeproject OpenCV "https://github.com/opencv/opencv.git -b 4.0.1" "-DWITH_MSMF=NO -DBUILD_TESTS=OFF -DBUILD_PERF_TESTS=OFF -DBUILD_EXAMPLES=OFF -DBUILD_opencv_apps=ON -DBUILD_SHARED_LIBS=ON -DBUILD_opencv_java=OFF -DBUILD_opencv_python=OFF"
  set "PATH=%PATH%;%DEPENDENCY_INSTALL_PATH%/x64/mingw/bin"
) else (
  call buildcmakeproject OpenCV "https://github.com/opencv/opencv.git -b 4.1.0" "-DBUILD_TESTS=OFF -DBUILD_PERF_TESTS=OFF -DBUILD_EXAMPLES=OFF"
  set "PATH=%PATH%;%DEPENDENCY_INSTALL_PATH%/x64/vc15/bin"
)

call buildcmakeproject /b MyProj "c:/Projects/MyProj/source" "c:/Projects/MyProj/source-build" "c:/dependency/install" "-DMyProj_OPTION=1"

```

### Example for launch IDE
**`using-querySearch.bat`** make launch IDE easier. Just set correct `QTDIR_base`, `configerPath` and `ProjectPath`. Also check CMakePath - path to CMake GUI and other settings for your project.


text:
@implementation ASStarRatingView
@synthesize notSelectedStar = _notSelectedStar;
@synthesize selectedStar = _selectedStar;
@synthesize halfSelectedStar = _halfSelectedStar;
@synthesize canEdit = _canEdit;
@synthesize maxRating = _maxRating;
@synthesize midMargin = _midrMargin;
@synthesize leftMargin = _leftMargin;
@synthesize rightMargin = _rightMargin;
@synthesize minStarSize = _minStarSize;
@synthesize rating = _rating;
@synthesize minAllowedRating = _minAllowedRating;
@synthesize maxAllowedRating = _maxAllowedRating;

- (void)refreshStars {
    for(int i = 0; i < _starViews.count; ++i) {
        UIImageView *imageView = [_starViews objectAtIndex:i];
        if (_rating >= i+1) {
            imageView.image = _selectedStar;
        } else if (_rating > i) {
            imageView.image = _halfSelectedStar;
        } else {
            imageView.image = _notSelectedStar;
        }
    }
}

- (void)setupView {
    for(int i = 0; i < _maxRating; ++i) {
        UIImageView *imageView = [[[UIImageView alloc] init] autorelease];
        imageView.contentMode = UIViewContentModeScaleAspectFit;
        [_starViews addObject:imageView];
        [self addSubview:imageView];
    }
    [self refreshStars];
}

- (void)baseInit {
    _notSelectedStar = [[UIImage imageNamed:@"not_selected_star"] retain];
    _selectedStar = [[UIImage imageNamed:@"selected_star"] retain];
    _halfSelectedStar = [[UIImage imageNamed:@"half_selected_star"] retain];
    _starViews = [[NSMutableArray array] retain];
    _maxRating = kDefaultMaxRating;
    _midMargin = kDefaultMidMargin;
    _leftMargin = kDefaultLeftMargin;
    _rightMargin = kDefaultRightMargin;
    _minStarSize = kDefaultMinStarSize;
    _minAllowedRating = kDefaultMinAllowedRating;
    _maxAllowedRating = kDefaultMaxAllowedRating;
    _rating = _minAllowedRating;
    _canEdit = YES;
    [self setupView];
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self baseInit];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder {
    if ((self = [super initWithCoder:aDecoder])) {
        [self baseInit];
    }
    return self;
}

- (void)dealloc {
    [_notSelectedStar release];
    _notSelectedStar = nil;
    [_selectedStar release];
    _selectedStar = nil;
    [_halfSelectedStar release];
    _halfSelectedStar = nil;
    [_starViews release];
    _starViews = nil;
    [super dealloc];
}

- (void)layoutSubviews {
    [super layoutSubviews];

    NSLog(@"%f, %f, %f, %d", self.frame.size.width, _leftMargin, _midMargin, _starViews.count);
    float desiredImageWidth = (self.frame.size.width - (_leftMargin*2) - (_midMargin*_starViews.count)) / _starViews.count;
    float imageWidth = MAX(_minStarSize.width, desiredImageWidth);
    float imageHeight = MAX(_minStarSize.height, self.frame.size.height);

    for (int i = 0; i < _starViews.count; ++i) {

        UIImageView *imageView = [_starViews objectAtIndex:i];
        CGRect imageFrame = CGRectMake(_leftMargin + i*(_midMargin+imageWidth), 0, imageWidth, imageHeight);
        imageView.frame = imageFrame;

    }

}

- (void)setMaxRating:(int)maxRating {
    if (_maxAllowedRating == _maxRating) {
        _maxAllowedRating = maxRating;
    }
    _maxRating = maxRating;

    // Remove old image views
    for(int i = 0; i < _starViews.count; ++i) {
        UIImageView *imageView = (UIImageView *) [_starViews objectAtIndex:i];
        [imageView removeFromSuperview];
    }
    [_starViews removeAllObjects];

    // Add new image views
    [self setupView];
    // Relayout and refresh
    [self setNeedsLayout];
    [self refreshStars];
}

- (void)setRating:(float)rating {
    _rating = rating;
    [self refreshStars];
}

#pragma mark - Touch Detection

- (void)handleTouchAtLocation:(CGPoint)touchLocation {
    if (!_canEdit) return;

    _rating = 0;
    for(int i = _starViews.count - 1; i >= 0; i--) {
        UIImageView *imageView = [_starViews objectAtIndex:i];
        if (touchLocation.x > imageView.frame.origin.x) {
            _rating = i+1;
            break;
        }
    }
    _rating = MAX(_minAllowedRating, _rating);
    _rating = MIN(_maxAllowedRating, _rating);
    [self refreshStars];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    CGPoint touchLocation = [touch locationInView:self];
    [self handleTouchAtLocation:touchLocation];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    CGPoint touchLocation = [touch locationInView:self];
    [self handleTouchAtLocation:touchLocation];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {

}

@end


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <title></title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="stylesheet" href="css/bootstrap.min.css">


text:
using EnergyTrading.Mdm.Messages.Services;
using MDM.ServiceHost.WebApi.Infrastructure.Exceptions;
using MDM.ServiceHost.WebApi.Infrastructure.Extensions;
using Microsoft.Practices.ServiceLocation;

namespace MDM.ServiceHost.WebApi.Controllers
{
    using System.Net;
    using System.Transactions;
    using System.Web.Http;

    using EnergyTrading.Mdm;
    using EnergyTrading.Mdm.Messages;
    using EnergyTrading.Mdm.Services;

    using MDM.ServiceHost.WebApi.Filters;
    using MDM.ServiceHost.WebApi.Infrastructure;
    using MDM.ServiceHost.WebApi.Infrastructure.Controllers;
    using MDM.ServiceHost.WebApi.Infrastructure.ETags;
    using MDM.ServiceHost.WebApi.Infrastructure.Results;

    using EnergyTrading.Mdm.Contracts;

    /// <summary>
    /// This controller handles requests for looking up MDM entities via the mapping functionality.
    /// </summary>
    public class EntityMapController<TContract, TEntity> : BaseEntityController
        where TContract : class, IMdmEntity
        where TEntity : IEntity
    {
        protected IMdmService<TContract, TEntity> service;

        public EntityMapController(IMdmService<TContract, TEntity> service, IServiceLocator serviceLocator)
            : base(serviceLocator)
        {
            this.service = service;
        }

        /// <summary>
        /// Will try and retrieve an entity with a matching mapping to what is supplied in the query parameters
        /// </summary>
        /// <param name="etag">The service verifies if its entity version matches what's held by the client cache</param>
        /// <returns>Response with appropriate status code and the serialised entity as content if found</returns>
        [ETagChecking]
        public IHttpActionResult Get([IfNoneMatch] ETag etag)
        {
            return WebHandler(() =>
            {
                var request = MessageFactory.MappingRequest(this.QueryParameters);
                request.Version = etag.ToVersion();

                ContractResponse<TContract> response;
                using (var scope = new TransactionScope(TransactionScopeOption.Required, ReadOptions()))
                {
                    response = this.service.Map(request);
                    scope.Complete();
                }

                if (response.IsValid)
                {
                    return new ResponseWithETag<TContract>(this.Request, response.Contract, HttpStatusCode.OK,
                        response.Version);
                }

                throw new MdmFaultException(new MappingRequestFaultHandler().Create(typeof(TContract).Name,
                    response.Error, request));
            });
        }
    }
}


text:
<?php

namespace app\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\SendAct;
use app\models\ServiceSend;

class ServiceSendSearch extends ServiceSend
{
    public $date_from;
    public $date_to;

    public static function tableName()
    {
        return 'service_send';
    }

    public function search($params)
    {
        $query = ServiceSend::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'pageSize' => 25,
            ],
            'sort' => [
                'defaultOrder' => [
                    'send_act_id' => SORT_DESC
                ]
            ]
        ]);

        // join with relation `author` that is a relation to the table `users`
        // and set the table alias to be `author`
        $query->joinWith('sendAct');

        // enable sorting for the related column
        //$dataProvider->sort->attributes['printersTypes.types'] = [
            //'asc' => ['printersTypes.types' => SORT_ASC],
           // 'desc' => ['printersTypes.types' => SORT_DESC],
       // ];
        // load the search form data and validate
        if (!($this->load($params) && $this->validate())) {
            return $dataProvider;
        }

        // adjust the query by adding the filters

        $query->andFilterWhere(['like', 'send_act_id', $this->getAttribute('send_act_id')])
            ->andFilterWhere(['>=', 'service_send.create_at', Yii::$app->formatter->asTimestamp($this->date_from) ]);

        if($this->date_to != ''){
            $query->andFilterWhere(['<=', 'service_send.create_at', Yii::$app->formatter->asTimestamp($this->date_to) + 86399 ]);
        }
        return $dataProvider;
    }

    //public function attributes()
    //{
        // add related fields to searchable attributes
       // return array_merge(parent::attributes(), ['printersTypes.types']);
   // }

    public function rules()
    {
        // only fields in rules() are searchable
        return [
            [['send_act_id', 'create_at'], 'safe'],
            [['date_from', 'date_to'], 'date', 'format' => 'php:d.m.Y'],

        ];
    }

}


text:
<FrameLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >

    <com.ogaclejapan.arclayout.ArcLayout
            android:id="@id/arc_layout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:arc_origin="center"
            app:arc_radius="@dimen/layout_radius_small"
            app:arc_axisRadius="@dimen/layout_child_offset_small"
            >

        <Button
                style="@style/Item.Large"
                android:text="A"
                android:background="@drawable/light_blue_oval_selector"
                />

        <Button
                style="@style/Item.Large"
                android:text="B"
                android:background="@drawable/cyan_oval_selector"
                />

        <Button
                style="@style/Item.Large"
                android:text="C"
                android:background="@drawable/teal_oval_selector"
                />

        <Button
                style="@style/Item.Large"
                android:text="D"
                android:background="@drawable/green_oval_selector"
                />

        <Button
                style="@style/Item.Large"
                android:text="E"
                android:background="@drawable/light_green_oval_selector"
                />

    </com.ogaclejapan.arclayout.ArcLayout>

    <TextView
            android:id="@id/note_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="16dp"
            android:textSize="16sp"
            />

</FrameLayout>


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <artifactId>edgegrid-signer-parent</artifactId>
        <groupId>com.akamai.edgegrid</groupId>
        <version>2.0.0-RC1</version>
    </parent>

    <artifactId>edgegrid-signer-rest-assured</artifactId>
    <packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>com.akamai.edgegrid</groupId>
            <artifactId>edgegrid-signer-core</artifactId>
            <version>2.0.0-RC1</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
        </dependency>
        <dependency>
            <groupId>com.github.tomakehurst</groupId>
            <artifactId>wiremock</artifactId>
        </dependency>
        <dependency>
            <groupId>io.rest-assured</groupId>
            <artifactId>rest-assured</artifactId>
        </dependency>
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-javadoc-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-source-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>