text:
namespace skia {

PlatformCanvas::PlatformCanvas(int width, int height, bool is_opaque) {
  TRACE_EVENT2("skia", "PlatformCanvas::PlatformCanvas",
               "width", width, "height", height);
  if (!initialize(width, height, is_opaque))
    SK_CRASH();
}

#if defined(WIN32)
PlatformCanvas::PlatformCanvas(int width,
                               int height,
                               bool is_opaque,
                               HANDLE shared_section) {
  TRACE_EVENT2("skia", "PlatformCanvas::PlatformCanvas",
               "width", width, "height", height);
  if (!initialize(width, height, is_opaque, shared_section))
    SK_CRASH();
}
#elif defined(__APPLE__)
PlatformCanvas::PlatformCanvas(int width, int height, bool is_opaque,
                               uint8_t* data) {
  TRACE_EVENT2("skia", "PlatformCanvas::PlatformCanvas",
               "width", width, "height", height);
  if (!initialize(width, height, is_opaque, data))
    SK_CRASH();
}
PlatformCanvas::PlatformCanvas(int width,
                               int height,
                               bool is_opaque,
                               CGContextRef context) {
  TRACE_EVENT2("skia", "PlatformCanvas::PlatformCanvas",
               "width", width, "height", height);
  if (!initialize(context, width, height, is_opaque))
    SK_CRASH();
}
#elif defined(__linux__) || defined(__FreeBSD__) || defined(__OpenBSD__) || \
      defined(__sun) || defined(ANDROID)
PlatformCanvas::PlatformCanvas(int width, int height, bool is_opaque,
                               uint8_t* data) {
  TRACE_EVENT2("skia", "PlatformCanvas::PlatformCanvas",
               "width", width, "height", height);
  if (!initialize(width, height, is_opaque, data))
    SK_CRASH();
}
#endif

PlatformCanvas::~PlatformCanvas() {
}

#if defined(WIN32)
bool PlatformCanvas::initialize(int width,
                                int height,
                                bool is_opaque,
                                HANDLE shared_section) {
  // Use platform specific device for shared_section.
  if (shared_section)
    return initializeWithDevice(BitmapPlatformDevice::Create(
        width, height, is_opaque, shared_section));

  return initializeWithDevice(new SkDevice(
      SkBitmap::kARGB_8888_Config, width, height, is_opaque));
}
#elif defined(__APPLE__)
bool PlatformCanvas::initialize(int width,
                                int height,
                                bool is_opaque,
                                uint8_t* data) {
  // Use platform specific device for data.
  if (data)
    return initializeWithDevice(BitmapPlatformDevice::CreateWithData(
        data, width, height, is_opaque));

  return initializeWithDevice(new SkDevice(
      SkBitmap::kARGB_8888_Config, width, height, is_opaque));
}

bool PlatformCanvas::initialize(CGContextRef context,
                                int width,
                                int height,
                                bool is_opaque) {
  return initializeWithDevice(BitmapPlatformDevice::Create(
      context, width, height, is_opaque));
}
#elif defined(__linux__) || defined(__FreeBSD__) || defined(__OpenBSD__) || \
      defined(__sun) || defined(ANDROID)
bool PlatformCanvas::initialize(int width, int height, bool is_opaque,
                                uint8_t* data) {
  // Use platform specific device for data.
  if (data)
    return initializeWithDevice(BitmapPlatformDevice::Create(
        width, height, is_opaque, data));

  return initializeWithDevice(new SkDevice(
      SkBitmap::kARGB_8888_Config, width, height, is_opaque));
}
#endif

}  // namespace skia

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Magento\Checkout\Helper;

use Magento\Framework\Pricing\PriceCurrencyInterface;
use Magento\Quote\Model\Quote\Item\AbstractItem;
use Magento\Store\Model\Store;
use Magento\Store\Model\ScopeInterface;

/**
 * Checkout default helper
 *
 * @author      Magento Core Team <core@magentocommerce.com>
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
 */
class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
    const XML_PATH_GUEST_CHECKOUT = 'checkout/options/guest_checkout';

    const XML_PATH_CUSTOMER_MUST_BE_LOGGED = 'checkout/options/customer_must_be_logged';

    /**
     * @var \Magento\Store\Model\StoreManagerInterface
     */
    protected $_storeManager;

    /**
     * @var \Magento\Checkout\Model\Session
     */
    protected $_checkoutSession;

    /**
     * @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface
     */
    protected $_localeDate;

    /**
     * @var \Magento\Framework\Mail\Template\TransportBuilder
     */
    protected $_transportBuilder;

    /**
     * @var \Magento\Framework\Translate\Inline\StateInterface
     */
    protected $inlineTranslation;

    /**
     * @var PriceCurrencyInterface
     */
    protected $priceCurrency;

    /**
     * @param \Magento\Framework\App\Helper\Context $context
     * @param \Magento\Store\Model\StoreManagerInterface $storeManager
     * @param \Magento\Checkout\Model\Session $checkoutSession
     * @param \Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate
     * @param \Magento\Framework\Mail\Template\TransportBuilder $transportBuilder
     * @param \Magento\Framework\Translate\Inline\StateInterface $inlineTranslation
     * @param PriceCurrencyInterface $priceCurrency
     * @codeCoverageIgnore
     */
    public function __construct(
        \Magento\Framework\App\Helper\Context $context,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Checkout\Model\Session $checkoutSession,
        \Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate,
        \Magento\Framework\Mail\Template\TransportBuilder $transportBuilder,
        \Magento\Framework\Translate\Inline\StateInterface $inlineTranslation,
        PriceCurrencyInterface $priceCurrency
    ) {
        $this->_storeManager = $storeManager;
        $this->_checkoutSession = $checkoutSession;
        $this->_localeDate = $localeDate;
        $this->_transportBuilder = $transportBuilder;
        $this->inlineTranslation = $inlineTranslation;
        $this->priceCurrency = $priceCurrency;
        parent::__construct($context);
    }

    /**
     * Retrieve checkout session model
     *
     * @return \Magento\Checkout\Model\Session
     * @codeCoverageIgnore
     */
    public function getCheckout()
    {
        return $this->_checkoutSession;
    }

    /**
     * Retrieve checkout quote model object
     *
     * @return \Magento\Quote\Model\Quote
     * @codeCoverageIgnore
     */
    public function getQuote()
    {
        return $this->getCheckout()->getQuote();
    }

    /**
     * @param float $price
     * @return string
     */
    public function formatPrice($price)
    {
        return $this->priceCurrency->format(
            $price,
            true,
            PriceCurrencyInterface::DEFAULT_PRECISION,
            $this->getQuote()->getStore()
        );
    }

    /**
     * @param float $price
     * @param bool $format
     * @return float
     */
    public function convertPrice($price, $format = true)
    {
        return $format
            ? $this->priceCurrency->convertAndFormat($price)
            : $this->priceCurrency->convert($price);
    }

    /**
     * Get onepage checkout availability
     *
     * @return bool
     */
    public function canOnepageCheckout()
    {
        return (bool)$this->scopeConfig->getValue(
            'checkout/options/onepage_checkout_enabled',
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        );
    }

    /**
     * Get sales item (quote item, order item etc) price including tax based on row total and tax amount
     *
     * @param   \Magento\Framework\DataObject $item
     * @return  float
     */
    public function getPriceInclTax($item)
    {
        if ($item->getPriceInclTax()) {
            return $item->getPriceInclTax();
        }
        $qty = $item->getQty() ? $item->getQty() : ($item->getQtyOrdered() ? $item->getQtyOrdered() : 1);
        $taxAmount = $item->getTaxAmount() + $item->getDiscountTaxCompensation();
        $price = floatval($qty) ? ($item->getRowTotal() + $taxAmount) / $qty : 0;
        return $this->priceCurrency->round($price);
    }

    /**
     * Get sales item (quote item, order item etc) row total price including tax
     *
     * @param   \Magento\Framework\DataObject $item
     * @return  float
     */
    public function getSubtotalInclTax($item)
    {
        if ($item->getRowTotalInclTax()) {
            return $item->getRowTotalInclTax();
        }
        $tax = $item->getTaxAmount() + $item->getDiscountTaxCompensation();
        return $item->getRowTotal() + $tax;
    }

    /**
     * @param AbstractItem $item
     * @return float
     */
    public function getBasePriceInclTax($item)
    {
        $qty = $item->getQty() ? $item->getQty() : ($item->getQtyOrdered() ? $item->getQtyOrdered() : 1);
        $taxAmount = $item->getBaseTaxAmount() + $item->getBaseDiscountTaxCompensation();
        $price = floatval($qty) ? ($item->getBaseRowTotal() + $taxAmount) / $qty : 0;
        return $this->priceCurrency->round($price);
    }

    /**
     * @param AbstractItem $item
     * @return float
     */
    public function getBaseSubtotalInclTax($item)
    {
        $tax = $item->getBaseTaxAmount() + $item->getBaseDiscountTaxCompensation();
        return $item->getBaseRowTotal() + $tax;
    }

    /**
     * Send email id payment was failed
     *
     * @param \Magento\Quote\Model\Quote $checkout
     * @param string $message
     * @param string $checkoutType
     * @return $this
     * @SuppressWarnings(PHPMD.CyclomaticComplexity)
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
     */
    public function sendPaymentFailedEmail($checkout, $message, $checkoutType = 'onepage')
    {
        $this->inlineTranslation->suspend();

        $template = $this->scopeConfig->getValue(
            'checkout/payment_failed/template',
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE,
            $checkout->getStoreId()
        );

        $copyTo = $this->_getEmails('checkout/payment_failed/copy_to', $checkout->getStoreId());
        $copyMethod = $this->scopeConfig->getValue(
            'checkout/payment_failed/copy_method',
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE,
            $checkout->getStoreId()
        );
        $bcc = [];
        if ($copyTo && $copyMethod == 'bcc') {
            $bcc = $copyTo;
        }

        $_receiver = $this->scopeConfig->getValue(
            'checkout/payment_failed/receiver',
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE,
            $checkout->getStoreId()
        );
        $sendTo = [
            [
                'email' => $this->scopeConfig->getValue(
                    'trans_email/ident_' . $_receiver . '/email',
                    \Magento\Store\Model\ScopeInterface::SCOPE_STORE,
                    $checkout->getStoreId()
                ),
                'name' => $this->scopeConfig->getValue(
                    'trans_email/ident_' . $_receiver . '/name',
                    \Magento\Store\Model\ScopeInterface::SCOPE_STORE,
                    $checkout->getStoreId()
                ),
            ],
        ];

        if ($copyTo && $copyMethod == 'copy') {
            foreach ($copyTo as $email) {
                $sendTo[] = ['email' => $email, 'name' => null];
            }
        }
        $shippingMethod = '';
        if ($shippingInfo = $checkout->getShippingAddress()->getShippingMethod()) {
            $data = explode('_', $shippingInfo);
            $shippingMethod = $data[0];
        }

        $paymentMethod = '';
        if ($paymentInfo = $checkout->getPayment()) {
            $paymentMethod = $paymentInfo->getMethod();
        }

        $items = '';
        foreach ($checkout->getAllVisibleItems() as $_item) {
            /* @var $_item \Magento\Quote\Model\Quote\Item */
            $items .=
                $_item->getProduct()->getName() . '  x ' . $_item->getQty() . '  ' . $checkout->getStoreCurrencyCode()
                . ' ' . $_item->getProduct()->getFinalPrice(
                    $_item->getQty()
                ) . "\n";
        }
        $total = $checkout->getStoreCurrencyCode() . ' ' . $checkout->getGrandTotal();

        foreach ($sendTo as $recipient) {
            $transport = $this->_transportBuilder->setTemplateIdentifier(
                $template
            )->setTemplateOptions(
                [
                    'area' => \Magento\Backend\App\Area\FrontNameResolver::AREA_CODE,
                    'store' => Store::DEFAULT_STORE_ID
                ]
            )->setTemplateVars(
                [
                    'reason' => $message,
                    'checkoutType' => $checkoutType,
                    'dateAndTime' => $this->_localeDate->formatDateTime(
                        new \DateTime(),
                        \IntlDateFormatter::MEDIUM,
                        \IntlDateFormatter::MEDIUM
                    ),
                    'customer' => $checkout->getCustomerFirstname() . ' ' . $checkout->getCustomerLastname(),
                    'customerEmail' => $checkout->getCustomerEmail(),
                    'billingAddress' => $checkout->getBillingAddress(),
                    'shippingAddress' => $checkout->getShippingAddress(),
                    'shippingMethod' => $this->scopeConfig->getValue(
                        'carriers/' . $shippingMethod . '/title',
                        \Magento\Store\Model\ScopeInterface::SCOPE_STORE
                    ),
                    'paymentMethod' => $this->scopeConfig->getValue(
                        'payment/' . $paymentMethod . '/title',
                        \Magento\Store\Model\ScopeInterface::SCOPE_STORE
                    ),
                    'items' => nl2br($items),
                    'total' => $total,
                ]
            )->setFrom(
                $this->scopeConfig->getValue(
                    'checkout/payment_failed/identity',
                    \Magento\Store\Model\ScopeInterface::SCOPE_STORE,
                    $checkout->getStoreId()
                )
            )->addTo(
                $recipient['email'],
                $recipient['name']
            )->addBcc(
                $bcc
            )->getTransport();

            $transport->sendMessage();
        }

        $this->inlineTranslation->resume();

        return $this;
    }

    /**
     * @param string $configPath
     * @param null|string|bool|int|Store $storeId
     * @return array|false
     */
    protected function _getEmails($configPath, $storeId)
    {
        $data = $this->scopeConfig->getValue(
            $configPath,
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE,
            $storeId
        );
        if (!empty($data)) {
            return explode(',', $data);
        }
        return false;
    }

    /**
     * Check is allowed Guest Checkout
     * Use config settings and observer
     *
     * @param \Magento\Quote\Model\Quote $quote
     * @param int|Store $store
     * @return bool
     */
    public function isAllowedGuestCheckout(\Magento\Quote\Model\Quote $quote, $store = null)
    {
        if ($store === null) {
            $store = $quote->getStoreId();
        }
        $guestCheckout = $this->scopeConfig->isSetFlag(
            self::XML_PATH_GUEST_CHECKOUT,
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE,
            $store
        );

        if ($guestCheckout == true) {
            $result = new \Magento\Framework\DataObject();
            $result->setIsAllowed($guestCheckout);
            $this->_eventManager->dispatch(
                'checkout_allow_guest',
                ['quote' => $quote, 'store' => $store, 'result' => $result]
            );

            $guestCheckout = $result->getIsAllowed();
        }

        return $guestCheckout;
    }

    /**
     * Check if context is checkout
     *
     * @return bool
     * @codeCoverageIgnore
     */
    public function isContextCheckout()
    {
        return $this->_request->getParam('context') == 'checkout';
    }

    /**
     * Check if user must be logged during checkout process
     *
     * @return boolean
     * @codeCoverageIgnore
     */
    public function isCustomerMustBeLogged()
    {
        return $this->scopeConfig->isSetFlag(
            self::XML_PATH_CUSTOMER_MUST_BE_LOGGED,
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        );
    }

    /**
     * Checks if display billing address on payment method is available, otherwise
     * billing address should be display on payment page
     * @return bool
     */
    public function isDisplayBillingOnPaymentMethodAvailable()
    {
        return (bool) !$this->scopeConfig->getValue(
            'checkout/options/display_billing_address_on',
            ScopeInterface::SCOPE_STORE
        );
    }
}


text:
require "rubocops/extend/formula"

module RuboCop
  module Cop
    module FormulaAudit
      # This cop audits `deprecate!` and `disable!` dates.
      class DeprecateDisableDate < FormulaCop
        def audit_formula(_node, _class_node, _parent_class_node, body_node)
          [:deprecate!, :disable!].each do |method|
            node = find_node_method_by_name(body_node, method)

            next if node.nil?

            date(node) do |date_node|
              Date.iso8601(string_content(date_node))
            rescue ArgumentError
              fixed_date_string = Date.parse(string_content(date_node)).iso8601
              offending_node(date_node)
              problem "Use `#{fixed_date_string}` to comply with ISO 8601"
            end
          end
        end

        def autocorrect(node)
          lambda do |corrector|
            fixed_fixed_date_string = Date.parse(string_content(node)).iso8601
            corrector.replace(node.source_range, "\"#{fixed_fixed_date_string}\"")
          end
        end

        def_node_search :date, <<~EOS
          (pair (sym :date) $str)
        EOS
      end

      # This cop audits `deprecate!` and `disable!` reasons.
      class DeprecateDisableReason < FormulaCop
        PUNCTUATION_MARKS = %w[. ! ?].freeze

        def audit_formula(_node, _class_node, _parent_class_node, body_node)
          [:deprecate!, :disable!].each do |method|
            node = find_node_method_by_name(body_node, method)

            next if node.nil?

            reason_found = false
            reason(node) do |reason_node|
              reason_found = true
              next if reason_node.sym_type?

              offending_node(reason_node)
              reason_string = string_content(reason_node)

              problem "Do not start the reason with `it`" if reason_string.start_with?("it ")

              problem "Do not end the reason with a punctuation mark" if PUNCTUATION_MARKS.include?(reason_string[-1])
            end

            next if reason_found

            case method
            when :deprecate!
              problem 'Add a reason for deprecation: `deprecate! because: "..."`'
            when :disable!
              problem 'Add a reason for disabling: `disable! because: "..."`'
            end
          end
        end

        def autocorrect(node)
          return unless node.str_type?

          lambda do |corrector|
            reason = string_content(node)
            reason = reason[3..] if reason.start_with?("it ")
            reason.chop! if PUNCTUATION_MARKS.include?(reason[-1])
            corrector.replace(node.source_range, "\"#{reason}\"")
          end
        end

        def_node_search :reason, <<~EOS
          (pair (sym :because) ${str sym})
        EOS
      end
    end
  end
end


text:
'use strict';

var React = require('react');
var ReactDOM = require('react-dom');

var MayeumiPlace = require('./MayeumiPlace.js');
//var Game = require('./Game.js');

ReactDOM.render(React.createElement(MayeumiPlace, null), document.getElementById('app'));


text:
<script>

'use strict';

function _slicedToArray(arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i['return']) _i['return'](); } finally { if (_d) throw _e; } } return _arr; } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }

window.PolyAuth = {};

(function (scope) {

	'use strict';

	var POLYAUTH_ORIGIN = 'polyauth.herokuapp.com';
	var POLYAUTH_ORIGIN_URI = 'https://' + POLYAUTH_ORIGIN;
	var POLYAUTH_API_VERSION = 'v1';
	var KEYS = ['oauth2.google-plus', 'oauth2.facebook', 'oauth2.vk', 'oauth2.ok'];

	scope.api = function (token, v) {
		v = v || POLYAUTH_API_VERSION;
		return {
			user: function user(id) {
				return id ? {
					get: function get(options) {
						return makeUserGetRequest(token, v, id, options);
					},
					remove: function remove() {
						return makeUserRemoveRequest(token, v, id);
					},
					reset: function reset() {
						return makeUserResetRequest(token, v, id);
					},
					auth: function auth(authId) {
						return authId ? {
							remove: function remove() {
								return makeUserAuthRemoveRequest(token, v, id, authId);
							}
						} : {
							list: function list() {
								return makeUserAuthListRequest(token, v, id);
							}
						};
					}
				} : {
					list: function list(options) {
						return makeUserListRequest(token, v, options);
					}
				};
			},
			profile: function profile(id) {
				return {
					get: function get() {
						return makeProfileGetRequest(token, v, id);
					},
					update: function update(options) {
						return makeProfileUpdateRequest(token, v, id, options);
					}
				};
			},
			realm: function realm(id) {
				return id ? {
					get: function get(options) {
						return makeRealmGetRequest(token, v, id, options);
					},
					update: function update(options) {
						return makeRealmUpdateRequest(token, v, id, options);
					},
					remove: function remove() {
						return makeRealmRemoveRequest(token, v, id);
					},
					reset: function reset() {
						return makeRealmResetRequest(token, v, id);
					},
					auth: function auth(key) {
						return {
							accessToken: function accessToken(options) {
								return makeAuthTokenRequest(v, id, key, options);
							},
							standaloneToken: function standaloneToken(options) {
								return makeAuthStandaloneTokenRequest(v, id, key, options);
							},
							standaloneProfile: function standaloneProfile(options) {
								return makeAuthStandaloneProfileRequest(v, id, key, options);
							}
						};
					}
				} : {
					list: function list(options) {
						return makeRealmListRequest(token, v, options);
					},
					create: function create(options) {
						return makeRealmCreateRequest(token, v, options);
					}
				};
			}
		};
	};

	{
		(function () {
			var signAcc = {};

			scope.authCodeURI = function (realmId, options) {
				if (!realmId || !options || !options.key || !options.redirectURI) {
					throw new TypeError('badarg');
				}

				options = options || {};
				var v = options.apiv || POLYAUTH_API_VERSION;
				var op = options.op || 'm/token';
				var ns = op[0];
				var state = 'state' in options ? options.state : makeState();

				var opt = {};
				if (state) {
					storeState({ value: state, op: op });
					opt.state = state;
				}

				switch (ns) {

					case 'm':
						return makeAuthCodeURI(v, realmId, options.key, options.redirectURI, opt);

					case 's':
						opt.scope = options.scope;
						return makeAuthStandaloneCodeURI(v, realmId, options.key, options.redirectURI, opt);

					default:
						throw new TypeError('bad_ns');

				}
			};

			scope.signIn = function (realmId, options) {
				if (!realmId) {
					throw new TypeError('badarg');
				}

				options = options || {};
				var v = options.apiv || POLYAUTH_API_VERSION;
				var sign = signAcc[realmId];
				return sign ? sign : signAcc[realmId] = authenticate(v, realmId, options);
			};

			scope.signOut = function (realmId) {
				if (!realmId) {
					throw new TypeError('badarg');
				}

				delete signAcc[realmId];
				return removeSign(realmId);
			};
		})();
	}

	scope.fetch = fetchJSON;

	scope.Key = {
		all: function all() {
			return KEYS;
		},
		key: key,
		parse: parseKey
	};

	scope.State = {
		make: makeState,
		take: takeState
	};

	scope.QS = {
		parse: parseQS
	};

	scope.Hex = {
		make: makeHex
	};

	scope.Response = {
		success: respSuccess,
		json: respJSON,
		text: respText
	};

	function makeUserListRequest(token, v, options) {
		if (!v || !options.qRealmId || !token) {
			throw new TypeError('badarg');
		}
		options = options || {};

		var params = {};
		if (options.qRealmId) {
			params.q = 'realm_id:' + options.qRealmId;
		}
		if (options.fields) {
			params.fl = options.fields.join(',');
		}
		if (options.start) {
			params.start = options.start;
		}
		if (options.rows) {
			params.rows = options.rows;
		}

		var uri = makeURI('' + POLYAUTH_ORIGIN_URI + '/api/' + v + '/users', params);
		var opt = {
			method: 'GET',
			headers: addAuthrorizationHeader(token)
		};
		return new Request(uri, opt);
	}

	function makeUserGetRequest(token, v, id, options) {
		if (!v || !id) {
			throw new TypeError('badarg');
		}
		options = options || {};

		var params = {};
		if (options.fields) {
			params.fl = options.fields.join(',');
		}

		var uri = makeURI('' + POLYAUTH_ORIGIN_URI + '/api/' + v + '/users/' + id, params);
		var opt = {
			method: 'GET',
			headers: addAuthrorizationHeader(token)
		};
		return new Request(uri, opt);
	}

	function makeUserRemoveRequest(token, v, id) {
		if (!v || !id || !token) {
			throw new TypeError('badarg');
		}

		var uri = '' + POLYAUTH_ORIGIN_URI + '/api/' + v + '/users/' + id;
		var opt = {
			method: 'DELETE',
			headers: addAuthrorizationHeader(token)
		};
		return new Request(uri, opt);
	}

	function makeUserResetRequest(token, v, id) {
		if (!v || !id || !token) {
			throw new TypeError('badarg');
		}

		var uri = '' + POLYAUTH_ORIGIN_URI + '/api/' + v + '/users/' + id + '/reset';
		var opt = {
			method: 'POST',
			headers: addAuthrorizationHeader(token)
		};
		return new Request(uri, opt);
	}

	function makeUserAuthListRequest(token, v, id) {
		if (!v || !id || !token) {
			throw new TypeError('badarg');
		}

		var uri = '' + POLYAUTH_ORIGIN_URI + '/api/' + v + '/users/' + id + '/auth';
		var opt = {
			method: 'GET',
			headers: addAuthrorizationHeader(token)
		};
		return new Request(uri, opt);
	}

	function makeUserAuthRemoveRequest(token, v, id, authId) {
		if (!v || !id || !authId || !token) {
			throw new TypeError('badarg');
		}

		var uri = '' + POLYAUTH_ORIGIN_URI + '/api/' + v + '/users/' + id + '/auth/' + authId;
		var opt = {
			method: 'DELETE',
			headers: addAuthrorizationHeader(token)
		};
		return new Request(uri, opt);
	}

	function makeProfileGetRequest(token, v, id) {
		if (!v || !id) {
			throw new TypeError('badarg');
		}

		var uri = '' + POLYAUTH_ORIGIN_URI + '/api/' + v + '/profiles/' + id;
		var opt = {
			method: 'GET',
			headers: addAuthrorizationHeader(token)
		};
		return new Request(uri, opt);
	}

	function makeProfileUpdateRequest(token, v, id, options) {
		if (!v || !id || !options || !options.data || !token) {
			throw new TypeError('badarg');
		}

		var uri = '' + POLYAUTH_ORIGIN_URI + '/api/' + v + '/profiles/' + id;
		var opt = {
			method: 'PUT',
			headers: addAuthrorizationHeader(token, { 'Content-Type': 'application/json' }),
			body: JSON.stringify(options.data)
		};
		return new Request(uri, opt);
	}

	function makeRealmListRequest(token, v, options) {
		if (!v || !token) {
			throw new TypeError('badarg');
		}
		options = options || {};

		var params = {};
		if (options.start) {
			params.start = options.start;
		}
		if (options.rows) {
			params.rows = options.rows;
		}
		if (options.fields) {
			params.fl = options.fields.join(',');
		}

		var uri = makeURI('' + POLYAUTH_ORIGIN_URI + '/api/' + v + '/realms', params);
		var opt = {
			method: 'GET',
			headers: addAuthrorizationHeader(token)
		};
		return new Request(uri, opt);
	}

	function makeRealmCreateRequest(token, v, options) {
		if (!v || !options || !options.data || !token) {
			throw new TypeError('badarg');
		}

		var uri = '' + POLYAUTH_ORIGIN_URI + '/api/' + v + '/realms';
		var opt = {
			method: 'POST',
			headers: addAuthrorizationHeader(token, { 'Content-Type': 'application/json' }),
			body: JSON.stringify(options.data)
		};
		return new Request(uri, opt);
	}

	function makeRealmGetRequest(token, v, id, options) {
		if (!v || !id) {
			throw new TypeError('badarg');
		}

		var params = {};
		if (options.fields) {
			params.fl = options.fields.join(',');
		}

		var uri = makeURI('' + POLYAUTH_ORIGIN_URI + '/api/' + v + '/realms/' + id, params);
		var opt = {
			method: 'GET',
			headers: addAuthrorizationHeader(token)
		};
		return new Request(uri, opt);
	}

	function makeRealmUpdateRequest(token, v, id, options) {
		if (!v || !id || !options || !options.data || !token) {
			throw new TypeError('badarg');
		}

		var uri = '' + POLYAUTH_ORIGIN_URI + '/api/' + v + '/realms/' + id;
		var opt = {
			method: 'PUT',
			headers: addAuthrorizationHeader(token, { 'Content-Type': 'application/json' }),
			body: JSON.stringify(options.data)
		};
		return new Request(uri, opt);
	}

	function makeRealmRemoveRequest(token, v, id) {
		if (!v || !id || !token) {
			throw new TypeError('badarg');
		}

		var uri = '' + POLYAUTH_ORIGIN_URI + '/api/' + v + '/realms/' + id;
		var opt = {
			method: 'DELETE',
			headers: addAuthrorizationHeader(token)
		};
		return new Request(uri, opt);
	}

	function makeRealmResetRequest(token, v, id) {
		if (!v || !id || !token) {
			throw new TypeError('badarg');
		}

		var uri = '' + POLYAUTH_ORIGIN_URI + '/api/' + v + '/realms/' + id + '/reset';
		var opt = {
			method: 'POST',
			headers: addAuthrorizationHeader(token)
		};
		return new Request(uri, opt);
	}

	function makeAuthTokenRequest(v, realmId, key, _ref) {
		var code = _ref.code;

		if (!v || !realmId || !key || !code) {
			throw new TypeError('badarg');
		}

		var uri = '' + POLYAUTH_ORIGIN_URI + '/api/' + v + '/realms/' + realmId + '/auth/' + key + '/m/token';
		var opt = {
			method: 'POST',
			headers: { 'Content-Type': 'application/json' },
			body: JSON.stringify({ code: code })
		};
		return new Request(uri, opt);
	}

	function makeAuthLinkRequest(token, v, realmId, key, _ref2) {
		var code = _ref2.code;

		if (!v || !realmId || !key || !code || !token) {
			throw new TypeError('badarg');
		}

		var uri = '' + POLYAUTH_ORIGIN_URI + '/api/' + v + '/realms/' + realmId + '/auth/' + key + '/m/link';
		var opt = {
			method: 'POST',
			headers: addAuthrorizationHeader(token, { 'Content-Type': 'application/json' }),
			body: JSON.stringify({ code: code })
		};
		return new Request(uri, opt);
	}

	function makeAuthStandaloneProfileRequest(v, realmId, key, _ref3) {
		var code = _ref3.code;

		if (!v || !realmId || !key || !code) {
			throw new TypeError('badarg');
		}

		var uri = '' + POLYAUTH_ORIGIN_URI + '/api/' + v + '/realms/' + realmId + '/auth/' + key + '/s/profile';
		var opt = {
			method: 'POST',
			headers: { 'Content-Type': 'application/json' },
			body: JSON.stringify({ code: code })
		};
		return new Request(uri, opt);
	}

	function makeAuthStandaloneTokenRequest(v, realmId, key, _ref4) {
		var code = _ref4.code;
		var secret = _ref4.secret;

		if (!v || !realmId || !key || !code || !secret) {
			throw new TypeError('badarg');
		}

		var uri = '' + POLYAUTH_ORIGIN_URI + '/api/' + v + '/realms/' + realmId + '/auth/' + key + '/s/token';
		var opt = {
			method: 'POST',
			headers: { 'Content-Type': 'application/json' },
			body: JSON.stringify({ code: code, client_secret: secret })
		};
		return new Request(uri, opt);
	}

	function makeAuthCodeURI(v, realmId, key, redirectURI, options) {
		if (!v || !realmId || !key || !redirectURI) {
			throw new TypeError('badarg');
		}

		var params = {};
		params.redirect_uri = redirectURI;
		if (options.state) {
			params.state = options.state;
		}

		return makeURI('' + POLYAUTH_ORIGIN_URI + '/api/' + v + '/realms/' + realmId + '/auth/' + key + '/m/code', params);
	}

	function makeAuthStandaloneCodeURI(v, realmId, key, redirectURI, options) {
		if (!v || !realmId || !key || !redirectURI) {
			throw new TypeError('badarg');
		}

		var params = {};
		params.redirect_uri = redirectURI;
		if (options.state) {
			params.state = options.state;
		}
		if (options.scope) {
			params.scope = options.scope;
		}

		return makeURI('' + POLYAUTH_ORIGIN_URI + '/api/' + v + '/realms/' + realmId + '/auth/' + key + '/s/code', params);
	}

	function makeURI(base, params) {
		var q = qs(params);
		return q ? base + '?' + q : base;
	}

	function qs(params) {
		var fn = function fn(key) {
			return '' + encodeURIComponent(key) + '=' + encodeURIComponent(params[key]);
		};
		return Object.keys(params).map(fn).join('&');
	}

	function parseQS() {
		return window.location.search.substr(1).split('&').reduce(function (acc, el) {
			var _el$split$map = el.split('=').map(decodeURIComponent);

			var _el$split$map2 = _slicedToArray(_el$split$map, 2);

			var key = _el$split$map2[0];
			var val = _el$split$map2[1];

			acc[key] = val ? val : true;
			return acc;
		}, {});
	}

	function key(val) {
		switch (val.prot) {

			case 'oauth2':
				if (!val.prov) {
					throw new TypeError('badarg');
				}
				return val.prot + '.' + val.prov;

			default:
				throw new TypeError('bad_key');

		}
	}

	function parseKey(key) {
		var p = key.split('.');
		switch (p[0]) {

			case 'oauth2':
				return {
					prot: p[0],
					prov: p[1]
				};

			default:
				throw new TypeError('bad_key');

		}
	}

	function flushQS() {
		window.location.href = window.location.origin + window.location.pathname;
	}

	function fetchJSON(req) {
		return fetch(req).then(respSuccess).then(respJSON);
	}

	function respSuccess(resp) {
		return new Promise(function (resolve, reject) {
			if (resp.status && (resp.status < 200 || resp.status >= 300)) {
				reject({ status: resp.status });
			} else if (resp.ok === false) {
				reject({ network: 'bad' });
			} else {
				resolve(resp);
			}
		});
	}

	function respText(resp) {
		return resp.text();
	}

	function respJSON(resp) {
		return resp.json();
	}

	function addAuthrorizationHeader(token, headers) {
		headers = headers || {};
		if (token) {
			headers.authorization = 'Bearer ' + token;
			return headers;
		}

		return headers;
	}

	function authenticate(v, realmId, options) {
		return new Promise(function (resolve, reject) {

			options = options || {};
			var redirect = options.redirect === false ? false : true;
			var verifyState = options.verifyState === false ? false : true;
			var sign = loadSign(realmId);
			var data = options.data || parseQS();
			var op = options.op || 'm/token';
			var opInitialized = options.op ? true : false;

			var done = function done(s, err) {
				return s ? resolve(s) : reject(err);
			};
			var maybeRedirect = function maybeRedirect(res) {
				if (redirect) {
					flushQS();
				}
				return resolve(res);
			};

			var error = data.error;
			var key = data.key;
			var code = data.code;
			var state = data.state;

			if (!key && !code) {
				return done(sign, { accessToken: 'required' });
			}

			if (verifyState) {
				if (!state) {
					return done(sign, { state: 'required' });
				}

				var storedState = takeState(state);
				if (!storedState) {
					return done(sign, { state: 'bad' });
				}

				if (!opInitialized) {
					op = storedState.op;
				}
			}

			if (error) {
				return reject({ error: error });
			}

			var reqOptions = { code: code };
			switch (op) {

				case 'm/token':
					return fetchJSON(makeAuthTokenRequest(v, realmId, key, reqOptions)).then(function (_ref5) {
						var access_token = _ref5.access_token;

						var sign = { accessToken: access_token };
						return resolve(storeSign(realmId, sign));
					}).then(maybeRedirect);

				case 'm/link':
					return !sign || !sign.accessToken ? reject({ accessToken: 'required' }) : fetchJSON(makeAuthLinkRequest(sign.accessToken, v, realmId, key, reqOptions)).then(function () {
						return resolve(sign);
					}).then(maybeRedirect);

				default:
					return reject({ op: 'bad' });

			}
		});
	}

	function loadSign(realmId) {
		var key = 'polyauth-sign.' + realmId;
		var val = localStorage.getItem(key);
		return val ? JSON.parse(val) : null;
	}

	function storeSign(realmId, val) {
		var key = 'polyauth-sign.' + realmId;
		localStorage.setItem(key, JSON.stringify(val));
		return val;
	}

	function removeSign(realmId) {
		var key = 'polyauth-sign.' + realmId;
		localStorage.removeItem(key);
		return null;
	}

	function loadStateArray() {
		var key = 'polyauth-state';
		var arr = sessionStorage.getItem(key);
		return arr ? JSON.parse(arr) : [];
	}

	function storeStateArray(arr) {
		var key = 'polyauth-state';
		sessionStorage.setItem(key, JSON.stringify(arr));
		return arr;
	}

	function takeState(val) {
		var arr = loadStateArray();
		if (!arr.length) {
			return null;
		}

		var _arr$reduceRight = arr.reduceRight(function (acc, state) {
			switch (state.value) {
				case val:
					acc.res = state;
					break;
				default:
					acc.rest.push(state);
			}

			return acc;
		}, { res: null, rest: [] });

		var res = _arr$reduceRight.res;
		var rest = _arr$reduceRight.rest;

		storeStateArray(rest);
		return res;
	}

	function storeState(state) {
		var arr = loadStateArray();
		arr.push(state);
		storeStateArray(arr);
		return state;
	}

	function makeState() {
		return makeHex(64);
	}

	function arrToHex(arr) {
		var acc = '';
		for (var i = 0; i < arr.length; ++i) {
			acc = acc + numToHex(arr[i]);
		}

		return acc;
	}

	function numToHex(num) {
		var hex = num.toString(16);
		return hex.length === 2 ? hex : '0' + hex;
	}

	function makeHex(len) {
		return arrToHex(makeRandomArray(len));
	}

	function makeRandomArray(len) {
		var crypto = window.crypto || window.msCrypto;
		if (crypto) {
			var arr = new Uint8Array(len);
			crypto.getRandomValues(arr);
			return arr;
		}

		return Array.apply(null, new Array(len)).map(function () {
			return Math.floor(Math.random() * 256);
		});
	}
})(window.PolyAuth);

</script>


text:
using Testura.Android.Util;

namespace Testura.Android.Device
{
    /// <summary>
    /// Defines an inteface to provide an adb terminal
    /// </summary>
    public interface IAdbCommandExecutorProvider
    {
        /// <summary>
        /// Get an adb terminal configured for this device.
        /// </summary>
        /// <returns>Adb terminal configured for this device</returns>
        AdbCommandExecutor GetAdbCommandExecutor();
    }
}


text:
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 27 10:08:17 2018

@author: fboers

---> update 03.04.2019 FB
 --> user logger from logging avoid print
"""

import os,sys,glob,re,textwrap
import ast
import logging
from types import ModuleType

#from pathlib import Path

import numpy as np

from jumeg.base.jumeg_base import JuMEG_Base_Basic
jb = JuMEG_Base_Basic()

logger = logging.getLogger('jumeg')
__version__="2019.05.14.001"

class JuMEG_UtilsIO_ModuleBase(object):
    """

     Paremeters:
     -----------
      name     : <None>
      prefix   : <jumeg>
      fullfile : <None>
      extention: <.py>
      function : <get_args>
      import   : <None>

      verbose  : <False>

     Example:
     --------
      command/module: my-path/jumeg/jumeg_test01.py
      name          : jumeg_test01
      fullfile      : my-path/jumeg/jumeg_test01.py

      command       : dict of {"name":None,"prefix":"jumeg","fullfile":None,
                               "extention":".py","function":"get_args","package":None}
    """
    def __init__(self,**kwargs):
        super().__init__()
        self.__command  = {"name":None,"prefix":"jumeg","fullfile":None,"extention":".py","function":"get_args","package":None}
        self.__isLoaded = False
        self._update_kwargs(**kwargs)

    @property
    def command(self): return self.__command

    @property
    def name(self)  : return self.__command["name"]
    @name.setter
    def name(self,v): self.__command["name"]=v

    @property
    def module(self)  : return self.__command["name"]
    @module.setter
    def module(self,v): self.__command["name"]=v

    @property
    def prefix(self)  : return self.__command["prefix"]
    @prefix.setter
    def prefix(self,v): self.__command["prefix"]=v

    @property
    def package(self)    : return self.__command["package"]
    @package.setter
    def pachkage(self,v)  : self.__command["package"]=v

    @property
    def fullfile(self)  : return self.__command["fullfile"]
    @fullfile.setter
    def fullfile(self,v):
        self.__isLoaded = False
        self.__command["fullfile"]=v

    @property
    def function(self)  : return self.__command["function"]
    @function.setter
    def function(self,v):
        self.__isLoaded = False
        self.__command["function"]=v

    @property
    def extention(self)  : return self.__command["extention"]
    @extention.setter
    def extention(self,v): self.__command["extention"]=v

    @property
    def import_name(self): return self.prefix +"."+self.name

   #-----
    def update(self,**kwargs):
        self._update_kwargs(**kwargs)

    def _update_kwargs(self,**kwargs):
        for k in self.__command.keys():
            self.__command[k] = kwargs.get(k,self.__command[k])

    #def info(self):
    #    jb.pp(self.command,head="JuMEG Function Command")

class JuMEG_UtilsIO_FunctionFromText(JuMEG_UtilsIO_ModuleBase):
    """
    special issue
    extract a function from a text file e.g. <get_arg> in <jumeg_filter.py>
    and compile it in a new module e.g. for argparser gui
    avoiding/excluding <import>  and imports of dependencies

    Parameters
    -----------
     name     : <None>
     prefix   : <jumeg>
     fullfile : <None>
     extention: <.py>
     function : <get_args>
     import   : <None>

     start_pattern: <def >
     stop_pattern : <return >

     verbose  : <False>

    Example
    -------
     from jumeg.gui.utils.jumeg_gui_utils_io import JuMEG_UtilsIO_FunctionFromText
     JFT          = JuMEG_UtilsIO_FunctionFromText()
     JFT.fullfile = os.environ["JUMEG_PATH"]+"jumeg/filter/jumeg_filter.py"
     JFT.function = "get_args"
     opt,parser   = JFT.apply()

     parser.print_help()

    """
    def __init__(self,**kwargs):
        super(JuMEG_UtilsIO_FunctionFromText,self).__init__(**kwargs)
        self.__command = {"name":None,"fullfile":None,"extention":".py","function":"get_args","start_pattern":"def","stop_pattern":"return" }
        self.__text     = None
        self.__isLoaded = False
        self._update_kwargs(**kwargs)

    @property
    def function_text(self)  : return self.__text

    @property
    def isLoaded(self)  : return self.__isLoaded

    @property
    def start_pattern(self)  : return self.__command["start_pattern"]
    @start_pattern.setter
    def start_pattern(self,v): self.__command["start_pattern"]=v

    @property
    def stop_pattern(self)  : return self.__command["stop_pattern"]
    @stop_pattern.setter
    def stop_pattern(self,v): self.__command["stop_pattern"]=v

    def _open_txt(self):
        """ open module-file (.py) """
        lines = None
        #print("Function File: "+self.fullfile)

        with open (self.fullfile,"r+") as farg:
             lines=farg.readlines()
             farg.close()
        return lines

    def _get_function_code_from_text(self,**kwargs):
        """  extract the function text from module"""
        self._update_kwargs(**kwargs)
        idx = 0
        lines        = None
        l_idx_start  = None
        l_idx_end    = None
        l_intend_pos = None
        self.__text  = None

       #--- read in module as txt
        lines = self._open_txt()
        if not lines : return

       #--- mk mathch pattern
        find_start_pattern = re.compile(self.start_pattern +'\s+'+ self.function)
       #--- find module start index
        for l in lines:
            if find_start_pattern.match(l):
               l_idx_start = idx
               break
            idx += 1
       #--- find intend pos first char
        idx = l_idx_start
        for l in lines[l_idx_start+1:-1]:
            idx += 1
            if not len(l.lstrip() )     :  continue
            if l.lstrip().startswith("#"): continue
            l_intend_pos = len(l) - len(l.lstrip()) # line pos of return
            break

       #--- find module end
        idx = l_idx_start
        for l in lines[l_idx_start+1:-1]:
            idx += 1
            if ( l.find( self.stop_pattern) ) == l_intend_pos:
               l_idx_end=idx
               break
        self.__text = "import sys,os,argparse\n" +''.join( lines[l_idx_start:l_idx_end+1] )
        lines=[]
        return self.__text

    def _clear(self):
        """
        clear function module space
        """
        self.__isLoaded = False

    def load_function(self):
        """
         load function from source code (text file)
         create a new module and execute code

         Result
         -------
         return function results

        """
        if self.isLoaded: self._clear()
        self.__isLoaded = False

        if not self._get_function_code_from_text(): return

        self.__ModuleType = ModuleType(self.function)
        sys.modules[self.function] = self.__ModuleType
        exec( textwrap.dedent( self.function_text), self.__ModuleType.__dict__)
        self.__isLoaded = True

    def apply(self):
        """
         if not loaded load function from source code (text file)
         and create a new module and execupte code
         execute function

         Result
         -------
         return function results
        """
        if not self.isLoaded:
           self.load_function()
        if self.isLoaded:
           # print("OK loaded {}".format(sys.modules[self.function] ))
           return getattr(self.__ModuleType,self.function)() #opt,parser

        return None

class JuMEG_UtilsIO_JuMEGModule(object):
    """
    CLS find jumeg modules under jumeg sub folders in PYTHONOATH

    Parameters:
    -----------
    stage_prefix : jumeg stage start of jumeg directory : <jumeg>
    prefix       : file prefix     <None>
    postfix      : file postfix    <None>
    extention    : file extention  <".py>
    permission   : file permission <os.X_OK|os.R_OK>
    function     : function name in module <get_args>

    Results:
    --------
    list of executable modules with fuction < get_args> in jumeg PYTHONPATH

    """
    def __init__(self,stage_prefix="jumeg",prefix="jumeg",postfix=None,extention=".py",permission=os.X_OK|os.R_OK,function="get_args",**kwargs):
        super(JuMEG_UtilsIO_JuMEGModule, self).__init__(**kwargs)
        #super().__init__()

        self.stage_prefix  = stage_prefix
        self.prefix        = prefix
        self.postfix       = postfix
        self.extention     = extention
        self.permission    = permission
        self.function      = function
        self.skip_dir_list = ["old","gui","wx"]
        self._module_list  = []
        self._jumeg_path_list=[]

    @property
    def module_list(self): return self._module_list
    @property
    def jumeg_path_list(self): return self._jumeg_path_list

    def PathListItem(self,idx):
        return os.path.split( self.module_list[idx] )[0]

    def _is_function_in_module(self,fmodule,function=None):
        """
        https://stackoverflow.com/questions/45684307/get-source-script-details-similar-to-inspect-getmembers-without-importing-the

        """
        if function:
           self.function=function
        if not self.function: return

        try:
            mtxt = open(fmodule).read()
            tree = ast.parse(mtxt)
            for fct in tree.body:
                if isinstance( fct,(ast.FunctionDef)):
                   if fct.name == self.function:
                      return True
        except:
            pass

    def get_jumeg_path_list_from_pythonpath(self):
        """ jumeg """

        self._jumeg_path_list=[]
        l=[]
        for d in os.environ["PYTHONPATH"].split(":"):
            if os.environ.get(d):
               d = os.environ.get(d)
            if d == ".":
               d = os.getcwd()
            if os.path.isdir( d + "/" + self.stage_prefix):
               l.append( d + "/" + self.stage_prefix )

        self._jumeg_path_list = list( set(l) ) # exclude double
        self._jumeg_path_list.sort()
        return self._jumeg_path_list

    def ModuleListItem(self,idx):
        """  jumeg.my subdirs.<jumeg_function name>"""

        if not len(self.module_list): return
        p,f = os.path.split( self.module_list[idx])
        m = p.split("/"+self.stage_prefix + "/")[-1] + "/" + os.path.splitext(f)[0]
        return m.replace("/",".")

    def ModuleFileName(self,idx):
        """
        Parameters:
        -----------
        index
        """
        return self._module_list[idx]

    def ModuleNames(self,idx=None):
        """
        get module name from file list
        Parameters:
        -----------
        idx: if defined return only this filename from list <None>
             else return list of filenames
        """
        if jb.is_number(idx):
           return os.path.basename( self._module_list[idx] ).replace(self.extention,"")
        l=[]
        for f in self.module_list:
            l.append(os.path.basename(f).replace(self.extention,""))
        return l

        #--- get_path_and_file
        # p,f=os.path.split( self.file_list[idx] )
    def FindModules(self,**kwargs):
        """
        find modules /commands under jumeg with defined permissions

        Parameters:
        -----------
        stage_prefix: <jumeg">
        prefix      : <jumeg>
        postfix     : <None>
        extention   : <.py>
        permission  : <os.X_OK|os.R_OK>
        function    : <get_args>

        Results:
        ---------
        list of module names
        """
        self._walk(**kwargs)
        return self.ModuleNames()

    def update(self,**kwargs):
        """ """
        self.stage_prefix = kwargs.get("stage_prefix",self.stage_prefix)
        self.prefix       = kwargs.get("prefix",self.prefix)
        self.postfix      = kwargs.get("postfix",self.postfix)
        self.extention    = kwargs.get("extention",self.extention)
        self.permission   = kwargs.get("permission",self.permission)
        self.function     = kwargs.get("function",self.function)
        self._module_list = []
        self._jumeg_path_list = self.get_jumeg_path_list_from_pythonpath()

    def _walk(self,**kwargs):
        """
        search recursive for executable modules

        Parameters:
        -----------
        stage_prefix : stage prefix <jumeg>
        prefix    : file prefix     <jumeg>
        postfix   : file postfix    <None>
        extention : file extention  <".py>
        permission: file permission <os.X_OK|os.R_OK>

        Results:
        --------
        list of executable modules, full filename
        """
        self.update(**kwargs)

        skip_dir_set = set(self.skip_dir_list)
        for p in  ( self._jumeg_path_list ):
            for root, dirs, files in os.walk(p):
                if (set(root.split(os.sep)) & skip_dir_set): continue
                for f in files:
                    if self.prefix:
                       if not f.startswith(self.prefix): continue
                    if self.extention:
                       if not f.endswith(self.extention): continue
                    if os.access(root+"/"+f,self.permission):
                       fmodule = os.path.join(root,f)
                       if self._is_function_in_module(fmodule):
                          self._module_list.append(fmodule)

        self._module_list.sort()
        return self._module_list

#===========================================================================

class JuMEG_UtilsIO_PDFBase(object):
    """
    Base CLS to find Posted Data Files (PDFs) via pattern search on harddisk
    default for 4D/BTi format

    Parameters:
    -----------
    prefix     : <'*'>
    postfix    : <'*c,rfDC'>
    id         : <None>
    scan       : <None>
    session    : <None>
    run        : <None>
    data_type  : <'bti'>
    verbose    : <False>

    """
    __slots__ =["id","scan","session","run","prefix","pdf_name","seperator","pattern","data_type","verbose","debug","_number_of_pdfs","_stage","_total_filesize"]

    def __init__(self,**kwargs):
        self._init(**kwargs)

    def _init(self,**kwargs):
        """ init slots """
        for k in self.__slots__:
            self.__setattr__(k,None)

        self.pdf_name   = "c,rfDC"
        self.data_type  = "bti"
        self.seperator  = "/"  # for glob.glob
        self.verbose    = False

        self.__NO_MATCH      = -1
        self._pdfs           = dict()
        self._total_filesize = 0
        self._update_from_kwargs(**kwargs)

    @property
    def NO_MATCH(self): return self.__NO_MATCH
    @property
    def pdfs(self)    : return self._pdfs
    @property
    def ids(self)     : return [*self._pdfs] #.sorted()
    @property
    def number_of_ids(self): return len(self._pdfs.keys())
    @property
    def number_of_pdfs(self): return self._number_of_pdfs
    @property
    def matches(self) : return self._MATCHES
    @property
    def stage(self)   : return self._stage
    @stage.setter
    def stage(self,v):
        if v:
           self._stage = os.path.expandvars( os.path.expanduser(v) )

    def GetTotalFileSize(self):
        return self._total_filesize

    def GetTotalFileSizeGB(self):
        return self._total_filesize / 1024 ** 3

    def GetTotalFileSizeMB(self):
        return self._total_filesize / 1024 ** 2

    def GetIDs(self):
        return sorted([*self._pdfs])

    def GetPDFsFromIDs(self,ids=None):
        """
         https://stackoverflow.com/questions/3129322/how-do-%20i-get-monitor-resolution-in-python
        :param ids:
        :return:
        PDF dict for ids in idlist
        {"pdf":fullfile reletive to <stage>,"size":file size,"hs_file":True/Faslse,"config":Ture/False}
        """
        return {x: self.pdfs[x] for x in ids if x in self.pdfs}

    def _update_from_kwargs(self,**kwargs):
        for k in kwargs:
            if k in self.__slots__:
                self.__setattr__(k,kwargs.get(k,self.__getattribute__(k)))

        #for k in self.__slots__:
        #    self.__setattr__(k,kwargs.get(k,self.__getattribute__(k)))

        if kwargs.get("stage"):
           self.stage=kwargs.get("stage")

    def get_parameter(self,key=None):
        """
        get  parameter
        :param key:
        :return: parameter dict or value for parameter[key] or all keys
        """
        if key: return self.__getattribute__(key)
        return { slot:self.__getattribute__(slot) for slot in self.__slots__ }

    def update(self,**kwargs):
        self._update_from_kwargs(**kwargs)

    def update_pattern(self,*args,**kwargs):
        """
        pattern for glob.glob

        "/mnt/meg_store2/megdaw_data21/204471/*EG*/*/c,rfDC"

        https://docs.python.org/3.5/library/glob.html?highlight=glob#glob.glob

        :return
         pattern
        """
        self._update_from_kwargs(**kwargs)
        #for k in kwargs:
        #    if k in self.__slots__:
        #       self.__setattr__(k,kwargs.get(k,self.__getattribute__(k)))

        l = []
        if self.id:
            l.append(self.id)
        if self.scan:
            l.append(self.scan)
        if self.session:
            l.append(self.session)
        if self.run:
            l.append(self.run)
        if self.pdf_name:
           l.append(self.pdf_name)
        if len(l):
           self.pattern = self.seperator.join(l)
        else:
           self.pattern = self.pdf_name

       #--- glob.glob
        if self.pattern.find("/**/") < 0:
           d = self.pattern.split("/")
           d[-1]= "**/" + d[-1]
           self.pattern = "/".join(d)

        return self.pattern

    @property
    def path(self):
        if not self.stage.endswith("/"):
           self.stage +="/"
        return self.stage

class JuMEG_UtilsIO_PDFBTi(JuMEG_UtilsIO_PDFBase):
    """
     CLS find BTi IDs in <stage>
     for bti [meg] data along directory structure:
     <stage/id/scan/session/run/
     check for  <c,rfDC>,<config> and <hs_file>

     from jumeg.gui.utils.jumeg_gui_utils_io  import JuMEG_UtilsIO_BTiPDFs
     p="/mnt/meg_store2/megdaw_data21"
     IDs=JuMEG_UtilsIO_Id(stage=p,data_type="bti",postfix="c,rfDC")

     Example:
     -------
      from jumeg import jumeg_base as jb
      from jumeg.gui.utils.jumeg_gui_utils_io  import JuMEG_UtilsIO_BTiPDFs
      p = os.getenv("JUMEG_PATH_BTI_EXPORT",default="/data/megdaw_data21")

      PDFs = JuMEG_UtilsIO_BTiPDFs(stage=p,postfix="c,rfDC",verbose=True)
      PDFs.scan="INTEXT*"
      PDFs.update()

      for id in  PDFs.pdfs:
          print("id: ".format(id))
          for pdf in PDFs.pdfs[id]:
              # {"pdf":f,"size": fsize in byte,"hs_file":bol,"config":bol}
              print(pdf)

      PDFs.info()
    """
    def __init__(self,**kwargs):
        super().__init__(**kwargs)
        self.data_type       = "bti"
        self.hs_filename     = "hs_file"
        self.config_filename = "config"

    def info(self):
        """
        prints info stage,number of found ids and pdfs, total filesize
        :return:
        """
        logger.info(
                "BTi  PDF  Stage     : {}\n".format(self.stage)+
                "pdf name            : {}\n".format(self.pdf_name)+
                "scan                : {}\n".format(self.scan)+
                "hs filename         : {}\n".format(self.hs_filename)+
                "config filename     : {}\n".format(self.config_filename)+
                "Number of IDs       : {}\n".format(self.number_of_ids)+
                "Number of PDFS      : {}\n".format(self.number_of_pdfs)+
                "total file size[GB] : {0:.9f}\n".format( self.GetTotalFileSizeGB() )+
                "last used pattern   : {}\n".format(self.pattern)
                )

    def check_config_hs(self,fbti):
        """
        check filesize of hs_file and config file
        :param full filename

        :return:
        size of headshape file
        size of config file
        """
        try:
           size_hs=os.stat(os.path.dirname(fbti)+"/"+self.hs_filename).st_size
        except:
           size_hs=0
        try:
            size_cfg = os.stat(os.path.dirname(fbti) + "/" + self.config_filename).st_size
        except:
            size_cfg = 0

        return size_hs,size_cfg

    def update(self,**kwargs):
        """
        find under stage all IDs matching  <search pattern> e.g. 204471/INTEXT*/**/c,rfDC
        https://stackoverflow.com/questions/50948391/whats-the-fastest-way-to-recursively-search-for-files-in-python
        using glob.iglob

        :return
        pdfs list of dict {"pdf":fullfile reletive to <stage>,"size":file size,"hs_file":True/Faslse,"config":Ture/False}

        """
        self._pdfs = dict()
        self._update_from_kwargs(**kwargs)

        self._number_of_pdfs=0
        self._total_filesize=0.0

        # if not os.path.isdir(stage): return
        with jb.working_directory(self.stage):
             for id in os.listdir( "." ):
                 lpdfs = []
                 for f in glob.iglob(self.update_pattern(id=id),recursive=True):
                     lpdfs.append(f)
                     lpdfs.sort()

                 if not lpdfs: continue
                 if not self._pdfs.get(id):
                    self._pdfs[id] = []
                 for f in lpdfs:
                     size_hs,size_cfg = self.check_config_hs(f)
                     self._pdfs[id].append( {"pdf":f,"size":os.stat(f).st_size,"hs_file":size_hs,"config":size_cfg,"seleted":False} )
                     self._total_filesize += size_hs + size_cfg + self._pdfs[id][-1]["size"]

                 self._number_of_pdfs+=len(self._pdfs[id])

        if self.debug:
           msg=[]
           for id in self.pdfs.keys():
               msg.append("  -> ID: "+id)
               for pdf in self.pdfs[id]:
                   msg.append(pdf)

           logger.debug("\n".join(msg))

class JuMEG_UtilsIO_IDs(object):
    """
     CLS find IDs in <stage>
     for mne [meg] data or eeg along directory structure:
     <stage/mne>   <stage/eeg>
    """
    def __init__(self,stage=None,data_type='mne'):
        super().__init__()
        self._stage      = None
        self.stage       = stage
        self.data_type   = data_type
        self.found_list  = []
        self.pdfs        = dict()

    @property
    def stage(self): return self._stage
    @stage.setter
    def stage(self,v):
        if v:
           self._stage = os.path.expandvars( os.path.expanduser(v) )

    def __get_path(self):
        # logger.info(self.stage)
        try:
            if not self.stage.endswith(self.data_type):
               return self.stage+"/"+self.data_type
            return self.stage

        except:
            logger.error("JuMEG_UtilsIO_PDFMEEG: No such file or directory or not defined: <data_type>:{} <stage>: {}".format(self.data_type,self.stage))
            return None

    path = property(__get_path)

    def update(self,data_type=None,scan=None):
        """
        update data type and call update for eeg  or meg

        Parameters:
        -----------
        data_type: meg or eeg   <None>
        scan     : name of scan <None>

        Results:
        --------
        file list
        """
        if data_type:
           self.data_type = data_type
        if self.data_type == 'mne':
           return self.update_mne(scan=scan)
        if self.data_type == 'eeg':
            return self.update_eeg()

    def update_mne(self,path=None,scan=None):
        """
        update meg file list
        Parameters:
        -----------
        sacn: name of scan <None>

        Results:
        --------
        file list
        """
        self.found_list = []
        if path:
           self.path = path

        if not self.path: return
        p = self.path
        if not os.path.isdir(p):
           logger.error("No directory: {}".format(p))
           return None

        for f in os.listdir(p):
            if os.path.isdir(p+"/"+f ):
               if f.isdigit():
                  if scan:
                     if os.path.isdir(p+"/"+f+"/"+scan ):
                        self.found_list.append(f)
                  else:
                     self.found_list.append(f)
        self.found_list.sort()
        return self.found_list

    def update_eeg(self):
        """
        update eeg file list

        Results:
        --------
        file list
        """
        self.found_list = []
        if not self.path: return
        p = self.path
        if not os.path.isdir(p):
           logger.error("NO directory: {}".format(p))
           return None

        for f in os.listdir(p):
            if os.path.isdir(p+"/"+f ):
               if f.isdigit():
                  self.found_list.append(f)

        self.found_list.sort()

        return self.found_list

class JuMEG_UtilsIO_PDFMEEGBase(object):  # JuMEG_UtilsIO_PDFBase
    """
    Base CLS to find PosteddataFiles (MEG or EEG files) via pattern

    Parameters:
    -----------
    prefix     : <'*'>
    postfix_meg: <'*c,rfDC-raw.fif'>
    postfix_eeg: <'*.vhdr'>
    id         : <None>
    scan       : <None>
    session    : <None>
    run        : <None>
    data_type  : <'mne'>

    """
    def __init__(self,prefix='*',postfix_meg='*c,rfDC-raw.fif',postfix_eeg='*.vhdr',id=None,scan=None,session=None,run=None,data_type='mne'):
        super().__init__()

        self._number_of_pdfs = {'mne':0,'eeg':0}
        self.verbose         = False
        self._pdf={'id':id,'scan':scan,'session':session,'run':run,'postfix_meg':postfix_meg,'postfix_eeg':postfix_eeg,'prefix':prefix,'data_type':data_type,
                   'pattern':None,'seperator':'_','data_type_mne':'mne','data_type_eeg':'eeg'
                  }

    def _update_from_kwargs(self,**kwargs):
        """
        :param stage:
        :param id:
        :param scan:
        :param session:
        :param run:
        :param postfix:
        :param postfix_meg:
        :param postfix_eeg:
        :param prefix:
        :param data_type:
        :return:
        """
        self.stage       = kwargs.get("stage",self.stage)
        self.id          = kwargs.get("id",self.id)
        self.data_type   = kwargs.get("data_type",self.data_type)# mne / eeg
        self.scan        = kwargs.get("scan",self.scan)
        self.session     = kwargs.get("session",self.session)
        self.run         = kwargs.get("run",self.run)
        self.postfix     = kwargs.get("postfix",self.postfix)
        self.postfix_meg = kwargs.get("postfix_meg",self.postfix_meg)
        self.postfix_eeg = kwargs.get("postfx_eeg",self.postfix_eeg)
        self.prefix      = kwargs.get("prefix",self.prefix)

    def update_pattern(self,*args,**kwargs):
        """ """
        self._update_from_kwargs(**kwargs)

        l=[]
        if self.id:
           l.append(self.id)
        if self.scan:
           l.append(self.scan)
        if self.session:
           l.append(self.session)
        if self.run:
           l.append(self.run)
        if len(l):
           l.append(self.postfix)
           self.pattern = self.prefix+self.seperator.join(l)
        else:
           self.pattern = self.postfix
        return self.pattern
  #---
    @property
    def number_of_pdfs(self):     return self._number_of_pdfs[self.data_type]
  #---
    @property
    def number_of_pdfs_mne(self): return self._number_of_pdfs['mne']
  #---
    @property
    def number_of_pdfs_eeg(self): return self._number_of_pdfs['eeg']
  #---
    @property
    def data_type(self):  return self._pdf['data_type']
    @data_type.setter
    def data_type(self,v): self._pdf['data_type']=v
  #---
    @property
    def data_type_mne(self):  return self._pdf['data_type_mne']
    @data_type_mne.setter
    def data_type_mne(self,v): self._pdf['data_type_mne']=v
  #---
    @property
    def data_type_eeg(self):  return self._pdf['data_type_eeg']
    @data_type_eeg.setter
    def data_type_eeg(self,v): self._pdf['data_type_eeg']=v
  #---
    @property
    def pattern(self):  return self._pdf['pattern']
    @pattern.setter
    def pattern(self,v): self._pdf['pattern']=v
  #---
    @property
    def seperator(self): return self._pdf['seperator']
    @seperator.setter
    def seperator(self,v): self._pdf['seperator']=v
  #---
    @property
    def id(self): return self._pdf['id']
    @id.setter
    def id(self,v): self._pdf['id']=v
  #---
    @property
    def scan(self): return self._pdf['scan']
    @scan.setter
    def scan(self,v): self._pdf['scan']=v
  #---
    @property
    def session(self): return self._pdf['session']
    @session.setter
    def session(self,v): self._pdf['session']=v
  #---
    @property
    def run(self): return self._pdf['run']
    @run.setter
    def run(self,v): self._pdf['run']=v
  #---
    @property
    def data_type(self): return self._pdf['data_type']
    @data_type.setter
    def data_type(self,v): self._pdf['data_type']=v
  #---
    @property
    def prefix(self): return self._pdf['prefix']
    @prefix.setter
    def prefix(self,v):  self._pdf['prefix']=v
  #---
    @property
    def postfix_meg(self):   return self._pdf['postfix_meg']
    @postfix_meg.setter
    def postfix_meg(self,v): self._pdf['postfix_meg']=v
  #---
    @property
    def postfix_eeg(self):   return self._pdf['postfix_eeg']
    @postfix_eeg.setter
    def postfix_eeg(self,v): self._pdf['postfix_eeg']=v
  #---
    @property
    def postfix(self):
        if self.data_type =='mne':
           return self.postfix_meg
        return self.postfix_eeg
    @postfix.setter
    def postfix(self,v):
        if self.data_type =='mne':
           self.postfix_meg=v
        else:
           self.postfix_eeg=v
  #---
    @property
    def path(self):
        if not self.stage.endswith(self.data_type):
           return self.stage+"/"+self.data_type
        return self.stage

class JuMEG_UtilsIO_PDFMEEG(JuMEG_UtilsIO_PDFMEEGBase):
    """
     CLS find IDs in <stage>
     for mne [meg] data or eeg along directory structure:
     <stage/mne>   <stage/eeg>

    """
    def __init__(self,stage='.', data_type='mne',experiment=None,scan=None,**kwargs):
        super().__init__(data_type=data_type,scan=scan,**kwargs)
        self.stage       = stage
        self.experiment  = experiment
        #self.type        = data_type
        self.id_list     = []
        self.pdfs        = dict()

        self.__NO_MATCH  = -1
        #self.scan        = scan
        #self.data_type   = data_type
        #self.pattern     = JuMEG_UtilsIO_PDFPattern()

    def GetIDs(self):
        return sorted([*self.pdfs[self.data_type_mne]])

    def GetPDFsFromIDs(self,ids=None):
        """
         https://stackoverflow.com/questions/3129322/how-do-%20i-get-monitor-resolution-in-python
        :param ids:
        :return:
        PDF dict for ids in idlist
        {"pdf":fullfile reletive to <stage>,"size":file size,"hs_file":True/Faslse,"config":Ture/False}
        """
        # print(self.pdfs)
        return { x:self.pdfs[self.data_type_mne][x] for x in ids if x in self.pdfs[self.data_type_mne] }

    def updateIDs(self,**kwargs):
        self.update(**kwargs)
        # print(self.pdfs)
        return self.pdfs[self.data_type_mne]

    def update(self,**kwargs):
        """
        for each id in id-list find mne/meg and eeg data
        Parameter:
        ----------
         parameter to change is defined

         id_list: <None>
         stage  : <None>
         scan   : <None>
         session: <None>
         run    : <None>
         postfix_meg: <None>
         postfix_eeg: <None>

        Result:
        -------
        pdf dictionary

        """

        self.id_list = kwargs.get("id_list",[])
        if self.id_list:
           if not isinstance(self.id_list,(list)):
              self.id_list = list(self.id_list)
        else:
           self.id_list=[]

        self._update_from_kwargs(**kwargs)

        self._update_data_type(data_type=self.data_type_mne)

        self._update_data_type(data_type=self.data_type_eeg)

        #print(self.stage)
        #print(self.scan)
        #print("pdfs")
        #print(self.pdfs)

      #--- search for matching scan and run
        for id_item in self.pdfs[ self.data_type_mne ]:
            n_raw = len( self.pdfs[ self.data_type_mne ][id_item]['raw'] )
          #--- make lookup tab for matching later mne raw with eeg raw
            self.pdfs[ self.data_type_mne ][id_item]['eeg_idx'] = np.zeros( n_raw,dtype=np.int64 ) + self.__NO_MATCH

            if id_item in self.pdfs[ self.data_type_eeg ]:
               eeg_index = self._match_meg_eeg_list(meg_list=self.pdfs[ self.data_type_mne ][id_item]['raw'],
                                                    eeg_list=self.pdfs[ self.data_type_eeg ][id_item]['raw'])
            else:
               eeg_index = np.zeros( n_raw,dtype=np.int64 ) + self.__NO_MATCH

        #--- ck for double
            uitems,uidx,uinv = np.unique(eeg_index,return_inverse=True,return_index=True)
            self.pdfs[self.data_type_mne][id_item]['eeg_idx'][uidx] = uitems

        return self.pdfs

    def _match_meg_eeg_list(self,meg_list=None,eeg_list=None):
        """
         find common eeg & meg files from meg and eeg list

         Parameter:
         ----------
         meg_list: <None>
         eeg_list: <None>

         Result:
         --------
         numpy array: matching index for eeg list; -1 => no match

         Example:
         --------
         type of input data

          MNE/MEG
           path to data/205630/INTEXT01/181017_1006/1/205630_INTEXT01_181017_1006_1_c,rfDC-raw.fif
           path to data/205630/INTEXT01/181017_1006/2/205630_INTEXT01_181017_1006_2_c,rfDC-raw.fif
           ...
           path to data/205630/INTEXT01/181017_1112/1/205630_INTEXT01_181017_1112_1_c,rfDC-raw.fif
           path to data/205630/INTEXT01/181017_1112/2/205630_INTEXT01_181017_1112_2_c,rfDC-raw.fif
           path to data/205630/INTEXT01/181017_1135/1/205630_INTEXT01_181017_1135_1_c,rfDC-raw.fif
          EEG
           path to data/205630_INTEXT01_181017_1006.02.vhdr
           path to data/205630_INTEXT01_181017_1006.01.vhdr
           ...
           path to data/205630_INTEXT01_181017_1112.01.vhdr
           path to data/205630_INTEXT01_181017_1112.02.vhdr

          or older experiments
             meg: path to data/204260_MEG9_130619_1301_2_c,rfDC-raw.fif
             eeg: path to data/204260_MEG9_2.vhdr
         """

        found_list = np.zeros( len(meg_list),dtype=np.int64 ) + self.__NO_MATCH
        match_run  = True
        match_time = False
        match_date = False
        n    = len( os.path.basename(eeg_list[0]).replace('.', '_').split('_') )
        eeg_idx0 = 2

        if n == 6:
           match_date = True
           match_time = True
           eeg_idx1 = 5
        elif n == 5:
           match_date = True
           eeg_idx1 = 4
        else:
           eeg_idx1 = 3

        eeg_pattern = np.zeros( (len(eeg_list),eeg_idx1 - 2), dtype=np.int)

        idx = 0
        for feeg in eeg_list:
            s = os.path.basename(feeg).replace('.', '_').split('_')
            eeg_pattern[idx][:] = np.array(s[ eeg_idx0:eeg_idx1 ], dtype=np.int)
            idx+=1

        idx = 0
        for fmeg in meg_list:
            idxs = None
            f = os.path.basename(fmeg)
            try:
          #--- error if run=2a
               meg_pattern = np.array(f.replace('.', '_').split('_')[2:5],dtype=np.int)

          #--- match run
               if match_run:
                  idxs = np.where(eeg_pattern[:,-1]== meg_pattern[-1])[0]
                  if not idxs.size: continue
          #--- match time
               if match_time:
                  found_idxs = np.where(eeg_pattern[idxs, -2] == meg_pattern[-2])[0]
                  if not found_idxs.size: continue
                  idxs = idxs[found_idxs]
         # --- match date
               if match_date:
                  found_idxs = np.where(eeg_pattern[idxs, -3] == meg_pattern[-3])[0]
                  if not found_idxs.size: continue
                  idxs = idxs[found_idxs]

               if isinstance(idxs,(np.ndarray)):
                  if idxs.size:
                     found_list[idx]=idxs[0]
            except:
                pass

            idx+=1
        return found_list

    def _update_data_type(self,data_type=None):
        """ """
        data_path = self.stage+'/'+data_type

        pdfs   = dict()
        n_pdfs = 0

        for id_item in self.id_list:
            pattern = self.update_pattern(id=id_item,data_type=data_type)
            if self.verbose:
               jb.Log.info(
                   ["---> JuMEG_UtilsIO_PDFs._update_data_type:",
                    " --> Search     : {} -> {}".format(id_item,self.scan),
                    "  -> data type  : {}".format(data_type),
                    "  -> pattern    : {}".format(pattern),
                    "  -> data path  : {}\n".format(data_path)])
          #--- https://stackoverflow.com/questions/18394147/recursive-sub-folder-search-and-return-files-in-a-list-python
            r=[y for x in os.walk(data_path) for y in glob(os.path.join(x[0], pattern))]
            if r :
               pdfs[id_item] = dict()
               pdfs[id_item]['path']    = [ os.path.dirname(raw)  for raw in sorted(r) ]
               pdfs[id_item]['raw']     = [ os.path.basename(raw) for raw in sorted(r) ]

               n_pdfs += len (pdfs[id_item]['raw'])

        self.pdfs[data_type] = pdfs

        self._number_of_pdfs[data_type] = n_pdfs
        return self.pdfs,n_pdfs

'''

class JuMEG_UtilsIO_PDFPattern(object):
    """
    Base CLS to find PosteddataFiles (MEG or EEG files) via pattern

    Parameters:
    -----------
    prefix     : <'*'>
    postfix_meg: <'*c,rfDC-raw.fif'>
    postfix_eeg: <'*.vhdr'>
    id         : <None>
    scan       : <None>
    session    : <None>
    run        : <None>
    data_type  : <'mne'>

    """

    def __init__(self,prefix='*',postfix_meg='*c,rfDC-raw.fif',postfix_eeg='*.vhdr',id=None,scan=None,session=None,
                 run=None,data_type='mne'):
        super(JuMEG_UtilsIO_PDFPattern,self).__init__()

        self._number_of_pdfs = { 'mne':0,'eeg':0 }
        self.verbose = False
        self._pdf = { 'id'         :id,'scan':scan,'session':session,'run':run,'postfix_meg':postfix_meg,
                      'postfix_eeg':postfix_eeg,'prefix':prefix,'data_type':data_type,
                      'pattern'    :None,'seperator':'_','data_type_mne':'mne','data_type_eeg':'eeg'
                      }

    def _update(self,stage=None,id=None,scan=None,session=None,run=None,postfix=None,postfix_meg=None,postfix_eeg=None,
                prefix=None,data_type=None):
        """ """
        if stage:
            self.stage = stage
        if data_type:  # mne / eeg
            self.data_type = data_type
        if id:
            self.id = id
        if scan:
            self.scan = scan
        if session:
            self.session = session
        if run:
            self.run = run

        if postfix:
            self.postfix = postfix
        if postfix_meg:
            self.postfix_meg = postfix_meg
        if postfix_eeg:
            self.postfix_eeg = postfix_eeg

        if prefix:
            self.prefix = prefix

    def update_pattern(self,*args,**kwargs):
        """ """
        self._update(*args,**kwargs)

        l = []
        if self.id:
            l.append(self.id)
        if self.scan:
            l.append(self.scan)
        if self.session:
            l.append(self.session)
        if self.run:
            l.append(self.run)
        if len(l):
            l.append(self.postfix)
            self.pattern = self.prefix + self.seperator.join(l)
        else:
            self.pattern = self.postfix
        return self.pattern

    #---
    @property
    def number_of_pdfs(self):
        return self._number_of_pdfs[self.data_type]

    #---
    @property
    def number_of_pdfs_mne(self):
        return self._number_of_pdfs['mne']

    #---
    @property
    def number_of_pdfs_eeg(self):
        return self._number_of_pdfs['eeg']

    #---
    @property
    def data_type(self):
        return self._pdf['data_type']

    @data_type.setter
    def data_type(self,v):
        self._pdf['data_type'] = v

    #---
    @property
    def data_type_mne(self):
        return self._pdf['data_type_mne']

    @data_type_mne.setter
    def data_type_mne(self,v):
        self._pdf['data_type_mne'] = v

    #---
    @property
    def data_type_eeg(self):
        return self._pdf['data_type_eeg']

    @data_type_eeg.setter
    def data_type_eeg(self,v):
        self._pdf['data_type_eeg'] = v

    #---
    @property
    def pattern(self):
        return self._pdf['pattern']

    @pattern.setter
    def pattern(self,v):
        self._pdf['pattern'] = v

    #---
    @property
    def seperator(self):
        return self._pdf['seperator']

    @seperator.setter
    def seperator(self,v):
        self._pdf['seperator'] = v

    #---
    @property
    def id(self):
        return self._pdf['id']

    @id.setter
    def id(self,v):
        self._pdf['id'] = v

    #---
    @property
    def scan(self):
        return self._pdf['scan']

    @scan.setter
    def scan(self,v):
        self._pdf['scan'] = v

    #---
    @property
    def session(self):
        return self._pdf['session']

    @session.setter
    def session(self,v):
        self._pdf['session'] = v

    #---
    @property
    def run(self):
        return self._pdf['run']

    @run.setter
    def run(self,v):
        self._pdf['run'] = v

    #---
    @property
    def data_type(self):
        return self._pdf['data_type']

    @data_type.setter
    def data_type(self,v):
        self._pdf['data_type'] = v

    #---
    @property
    def prefix(self):
        return self._pdf['prefix']

    @prefix.setter
    def prefix(self,v):
        self._pdf['prefix'] = v

    #---
    @property
    def postfix_meg(self):
        return self._pdf['postfix_meg']

    @postfix_meg.setter
    def postfix_meg(self,v):
        self._pdf['postfix_meg'] = v

    #---
    @property
    def postfix_eeg(self):
        return self._pdf['postfix_eeg']

    @postfix_eeg.setter
    def postfix_eeg(self,v):
        self._pdf['postfix_eeg'] = v

    #---
    @property
    def postfix(self):
        if self.data_type == 'mne':
            return self.postfix_meg
        return self.postfix_eeg

    @postfix.setter
    def postfix(self,v):
        if self.data_type == 'mne':
            self.postfix_meg = v
        else:
            self.postfix_eeg = v
            #---

    @property
    def path(self):
        if not self.stage.endswith(self.data_type):
            return self.stage + "/" + self.data_type
        return self.stage

'''


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Jl S. Afr. Bot. 35: 288 (1969)

#### Original name
Camillea leprieurii Mont., 1849

### Remarks
null


text:
The SDK is a library containing many helper functions for service orchestrators to create and manage their services. A main function of the SDK in the current implementation is to deploy Heat templates on an underlying infrastructure, but it also offers many more methods.

### Local Installation

The CC SDK is provided with a setup script.

    python setup.py install

### Helper methods
Below is a short description of the main functions in each component of the CC SDK. Details on each method provided by these components are provided within the inline documentation.
#### sdk.services
This class provides service discovery methods to retrieve service endpoint for a given service type within the service registry.
#### sdk.mcn.security
This class provides authentication methods to be used by other classes of the SDK. The current implementation is restricted to Keystone authentication.
#### sdk.mcn.runtime
The runtime library offers functions to be used by service orchestrators to create and manage alarms and callback notifications for runtime management of their service. More information can be found in the runtime_usage.md document.
#### sdk.mcn.deployment
This file contains an interface for generic deployers with one implementation for deployment via Heat. It provides methods to CRUD Heat templates through a user provided Heat endpoint.
#### sdk.mcn.util
Util provides static methods to retrieve instances of a deployer object, of the auth object, as well as method to create or dispose automatically instances of some atomic services. Note that using these methods circumvent the normal usage of the service graph and the resolver which are normally tasked to deploy all services comprising a composed application.

### Usage Examples
Examples of using the SDK are provided within the sample_so repository.


text:
<?php

namespace SMB\Arrayto\Plugins\Tsv;

/**
 * Test of SMB\Arrayto\Plugins\Tsv\Outputter
 *
 * PHP version 5 >= 5.4
 *
 * @group  SMBArrayto
 * @author shimabox.net
 */
class OutputterTest extends \TestCaseBase
{
    /** @var SMB\Arrayto\Plugins\Tsv\Outputter */
    protected $target;

    /** @var string */
    protected $expectedFilePath = '';

    public function setUp()
    {
        parent::setUp();

        $this->target = new Outputter();

        $this->expectedFilePath = FIXTURE_FILE_PATH . '/plugins/tsv/expected/';
    }

    public function tearDown()
    {
        parent::tearDown();
    }

    /**
     * @test
     * @runInSeparateProcess
     */
    public function it_can_output_to_tsv()
    {
        $array = [
            ['apple', 'りんご', "Sweet\tRed"],
            ['pineapple', 'パインアップル', "Sour\tYellow"]
        ];

        ob_start();

        $this->target->setRows($array)->output();

        $actual = ob_get_contents();

        $this->assertStringEqualsFile($this->expectedFilePath . 'expected_1.tsv', $actual);

        ob_end_clean();
    }
}


text:
<?php

namespace Dime\TimetrackerBundle\Controller;

use Dime\OfferBundle\Entity\Offer;
use Dime\TimetrackerBundle\Entity\Activity;
use Dime\TimetrackerBundle\Entity\ActivityRepository;
use Dime\TimetrackerBundle\Entity\Project;
use Dime\TimetrackerBundle\Entity\Timeslice;
use Dime\TimetrackerBundle\Exception\InvalidFormException;
use FOS\RestBundle\Controller\Annotations;
use FOS\RestBundle\Request\ParamFetcherInterface;
use FOS\RestBundle\Util\Codes;
use FOS\RestBundle\View\View;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
use Symfony\Component\Form\FormTypeInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Intl\Exception\NotImplementedException;

class ProjectsController extends DimeController
{
    private $handlerSerivce = 'dime.project.handler';

    private $formType = 'dime_timetrackerbundle_projectformtype';

    /**
     * List all Entities.
     *
     * @ApiDoc(
     * resource = true,
     * description="Get a Collection of Projects",
     * output = "Dime\TimetrackerBundle\Entity\Project",
     * section="projects",
     * statusCodes = {
     * 200 = "Returned when successful"
     * }
     * )
     *
     * @Annotations\QueryParam(name="customer", requirements="\d+", nullable=true, description="Filter By Project")
     * @Annotations\QueryParam(name="user", requirements="\d+", nullable=true, description="Filter By User")
     * @Annotations\QueryParam(name="search", requirements="[\w-]+", nullable=true, description="Filter By Name or alias")
     * @Annotations\QueryParam(array=true, name="withtags", requirements="\d+", nullable=true, description="Show Entities with these Tags")
     * @Annotations\QueryParam(array=true, name="withouttags", requirements="\d+", nullable=true, description="Show Entities without this Tags")
     *
     * @Annotations\View(
     * serializerEnableMaxDepthChecks=true,
     * serializerGroups={"List"}
     * )
     *
     * @Annotations\Route(requirements={"_format"="json|xml"})
     *
     * @param ParamFetcherInterface $paramFetcher
     *            param fetcher project
     *
     * @return array
     */
    public function getProjectsAction(ParamFetcherInterface $paramFetcher)
    {
        return $this->container->get($this->handlerSerivce)->all($paramFetcher->all());
    }

    /**
     * Get single Entity
     *
     * @ApiDoc(
     * resource = true,
     * description = "Gets a Project for a given id",
     * output = "Dime\TimetrackerBundle\Entity\Project",
     * section="projects",
     * statusCodes = {
     * 200 = "Returned when successful",
     * 404 = "Returned when the page is not found"
     * }
     * )
     *
     * @Annotations\View(
     * serializerEnableMaxDepthChecks=true,
     * serializerGroups={"List", "Default"}
     * )
     *
     * @Annotations\Route(requirements={"_format"="json|xml"})
     *
     * @param int $id
     *            the page id
     *
     * @return array
     *
     * @throws NotFoundHttpException when page not exist
     */
    public function getProjectAction($id)
    {
        return $this->getOr404($id, $this->handlerSerivce);
    }

    /**
     * List all Entities with open invoices.
     *
     * @ApiDoc(
     * resource = true,
     * description="Get a Collection of Projects with open invoices",
     * output = "Dime\TimetrackerBundle\Entity\Project",
     * section="projects",
     * statusCodes = {
     * 200 = "Returned when successful"
     * }
     * )
     *
     * @Annotations\View(
     * serializerEnableMaxDepthChecks=true,
     * serializerGroups={"List"}
     * )
     *
     * @Annotations\Route(requirements={"_format"="json|xml"})
     *
     * @return array
     */
    public function getProjectsopeninvoicesAction()
    {
        return $this->container->get($this->handlerSerivce)->allProjectsWithOpenInvoices();
    }

    /**
     * Create a new Entity from the submitted data.
     *
     * @ApiDoc(
     * resource = true,
     * description = "Creates a new Project from the submitted data.",
     * input = "Dime\TimetrackerBundle\Form\Type\ProjectFormType",
     * output = "Dime\TimetrackerBundle\Entity\Project",
     * section="projects",
     * statusCodes = {
     * 201 = "Returned when successful",
     * 400 = "Returned when the form has errors"
     * }
     * )
     *
     * @Annotations\Route(requirements={"_format"="json|xml"})
     *
     * @Annotations\View(
     * serializerEnableMaxDepthChecks=true
     * )
     *
     * @param Request $request
     *            the request object
     *
     * @return FormTypeInterface|View
     */
    public function postProjectAction(Request $request)
    {
        try {
            $newProject = $this->container->get($this->handlerSerivce)->post($request->request->all());
            return $this->view($newProject, Codes::HTTP_CREATED);
        } catch (InvalidFormException $exception) {
            return $exception->getForm();
        }
    }

    /**
     * Update existing Entity.
     *
     * @ApiDoc(
     * resource = true,
     * input = "Dime\TimetrackerBundle\Form\Type\ProjectFormType",
     * output = "Dime\TimetrackerBundle\Entity\Project",
     * section="projects",
     * statusCodes = {
     * 200 = "Returned when the Entity was updated",
     * 400 = "Returned when the form has errors",
     * 404 = "Returned when the Project does not exist"
     * }
     * )
     *
     * @Annotations\Route(requirements={"_format"="json|xml"})
     *
     * @Annotations\View(
     * serializerEnableMaxDepthChecks=true
     * )
     *
     * @param Request $request
     *            the request object
     * @param int $id
     *            the page id
     *
     * @return FormTypeInterface|View
     *
     * @throws NotFoundHttpException when page not exist
     *
     */
    public function putProjectAction(Request $request, $id)
    {
        try {
            $entity = $this->getOr404($id, $this->handlerSerivce);
            $entity = $this->container->get($this->handlerSerivce)->put($entity, $request->request->all());
            return $this->view($entity, Codes::HTTP_OK);
        } catch (InvalidFormException $exception) {
            return $exception->getForm();
        }
    }

    /**
     * Delete existing Entity
     *
     * @ApiDoc(
     * resource = true,
     * section="projects",
     * statusCodes = {
     * 204 = "Returned when successful",
     * 404 = "Returned when Project does not exist."
     * }
     * )
     *
     * @Annotations\Route(requirements={"_format"="json|xml"})
     * @Annotations\View(
     * serializerEnableMaxDepthChecks=true
     * )
     *
     * @param int $id
     *            the page id
     *
     * @return FormTypeInterface|View
     *
     * @throws NotFoundHttpException when page not exist
     */
    public function deleteProjectAction($id)
    {
        // Find linked activities
        $activityRepository = $this->getDoctrine()->getRepository('Dime\TimetrackerBundle\Entity\Activity');
        $activities = $activityRepository->findByProject($id);

        foreach ($activities as $key => $activity) {
            // Find linked timeslices
            $timesliceRepository = $this->getDoctrine()->getRepository('Dime\TimetrackerBundle\Entity\Timeslice');
            $timeslices = $timesliceRepository->findByActivity($activity->getId());

            foreach ($timeslices as $key2 => $timeslice) {
                $this->container->get($this->handlerSerivce)->delete($timeslice);
            }

            $this->container->get($this->handlerSerivce)->delete($activity);
        }

        // Delete the project
        /** @var Project $project */
        $project = $this->getOr404($id, $this->handlerSerivce);
        $em = $this->getDoctrine()->getManager();

        // set project_id of all offers pointing to the project to null
        /** @var Offer $offer */
        foreach ($project->getOffers() as $offer) {
            $offer->setProject(null);
            $em->persist($offer);
        }
        $em->flush();
        $this->container->get($this->handlerSerivce)->delete($project);

        return $this->view(null, Codes::HTTP_NO_CONTENT);
    }

    /**
     * Move timeslices to this project.
     *
     * Each timeslice will be moved to an activity corresponding to the service it previously belonged to.
     * If the project does not have the corresponding activity, it will be created.
     *
     * @ApiDoc(
     * resource = true,
     * section="projects",
     * statusCodes = {
     * 204 = "Returned when successful",
     * 404 = "Returned when Project does not exist."
     * }
     * )
     *
     * @Annotations\Route(requirements={"_format"="json|xml"})
     * @Annotations\View(
     * serializerEnableMaxDepthChecks=true
     * )
     *
     * @Annotations\RequestParam(name="timeslices", array=true, description="The IDs of the timeslices to move")
     *
     * @param int $projectId
     *            the page id
     *
     * @return FormTypeInterface|View
     *
     * @throws NotFoundHttpException when page not exist
     */
    public function putProjectTimeslicesAction(int $projectId, ParamFetcherInterface $params)
    {
        $timesliceIds = $params->get("timeslices");

        /** @var Project $targetProject */
        $targetProject = $this->getOr404($projectId, $this->handlerSerivce);

        $timesliceRepository = $this->getDoctrine()->getRepository(Timeslice::class);
        $timeslices = $timesliceRepository->findById($timesliceIds);

        $em = $this->getDoctrine()->getManager();

        /** @var Timeslice $timeslice */
        foreach ($timeslices as $timeslice) {
            $service = $timeslice->getActivity()->getService();

            /** @var Activity $targetActivity */
            $targetActivity = null;
            /** @var Activity $Activity */
            foreach ($targetProject->getActivities() as $activity) {
                if ($activity->getService()->getId() == $service->getId()) {
                    $targetActivity = $activity;
                    break;
                }
            }

            if ($targetActivity == null) {
                //create new activity for target project
                $targetActivity = clone $timeslice->getActivity();
                $targetActivity->setProject($targetProject);
                $em->persist($targetActivity);
                $em->flush();
                $targetProject->getActivities()->add($targetActivity);
            }

            $timeslice->setActivity($targetActivity);
            $em->persist($timeslice);
        }
        $em->flush();
        return $this->view(null, Codes::HTTP_NO_CONTENT);
    }
}


text:
const DHTCrawler = require('../index')

const crawler = new DHTCrawler({ address: '0.0.0.0', port: 6881 })

crawler.on('infohash', (infohash, address, port) => {
  console.log(`${infohash} from ${address}:${port}`)
})

crawler.start()


text:
from ..bepasty_xstatic import serve_files

from flask import send_from_directory
from werkzeug.exceptions import NotFound

from . import blueprint

@blueprint.route('/xstatic/<name>', defaults=dict(filename=''))
@blueprint.route('/xstatic/<name>/<path:filename>')
def xstatic(name, filename):
    """Route to serve the xstatic files (from serve_files)"""
    try:
        base_path = serve_files[name]
    except KeyError:
        raise NotFound()

    if not filename:
        raise NotFound()

    return send_from_directory(base_path, filename)


text:
package io.reflectoring.modules;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan()
public class DemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);
	}

}


text:
namespace Geocoding.Microsoft
{
	public enum ConfidenceLevel
	{
		High,
		Medium,
		Low,
		Unknown
	}
}