text:
static const LRImageViewAnimationType kDefaultImageViewAnimationType = LRImageViewAnimationTypeCrossDissolve;
static NSTimeInterval const kDefaultImageViewAnimationTime = 0.25;

@implementation UIImageView (LRNetworking)

- (void)lr_setImageWithURL:(NSURL *)url
{
    [self lr_setImageWithURL:url placeholderImage:nil];
}

- (void)lr_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholderImage
{
    [self lr_setImageWithURL:url
            placeholderImage:placeholderImage
         cacheStorageOptions:[LRImageManager sharedManager].imageCache.cacheStorageOptions];
}

- (void)lr_setImageWithURL:(NSURL *)url size:(CGSize)size
{
    [self lr_setImageWithURL:url placeholderImage:nil size:size];
}

- (void)lr_setImageWithURL:(NSURL *)url cacheStorageOptions:(LRCacheStorageOptions)cacheStorageOptions
{
    [self lr_setImageWithURL:url placeholderImage:nil cacheStorageOptions:cacheStorageOptions];
}

- (void)lr_setImageWithURL:(NSURL *)url
          placeholderImage:(UIImage *)placeholderImage
       cacheStorageOptions:(LRCacheStorageOptions)cacheStorageOptions
{
    [self lr_setImageWithURL:url
            placeholderImage:placeholderImage
                        size:self.frame.size
         cacheStorageOptions:cacheStorageOptions];
}

- (void)lr_setImageWithURL:(NSURL *)url
          placeholderImage:(UIImage *)placeholderImage
                      size:(CGSize)size
{
    [self lr_setImageWithURL:url
            placeholderImage:placeholderImage
                        size:size
         cacheStorageOptions:[LRImageManager sharedManager].imageCache.cacheStorageOptions];
}

- (void)lr_setImageWithURL:(NSURL *)url
          placeholderImage:(UIImage *)placeholderImage
                      size:(CGSize)size
       cacheStorageOptions:(LRCacheStorageOptions)cacheStorageOptions
{
    [[LRImageManager sharedManager] downloadImageForImageView:self
                                             placeholderImage:placeholderImage
                                            activityIndicator:self.lr_activityIndicator
                                                     imageURL:url
                                                         size:size
                                          cacheStorageOptions:cacheStorageOptions
                               allowUntrustedHTTPSConnections:self.lr_allowUntrustedHTTPSConnections
                                          postProcessingBlock:self.lr_postProcessingBlock
                                            completionHandler:self.lr_completionHandler];
}

- (void)lr_cancelImageOperation;
{
    [[LRImageManager sharedManager] cancelDownloadImageForImageView:self];
}

static const void * kLRCompletionHandlerObjectKey = &kLRCompletionHandlerObjectKey;
static const void * kLRActivityIndicatorObjectKey = &kLRActivityIndicatorObjectKey;
static const void * kLRAnimationType = &kLRAnimationType;
static const void * kLRAnimationTime = &kLRAnimationTime;
static const void * kLRPostProcessingBlock = &kLRPostProcessingBlock;
static const void * kLRAllowUntrustedHTTPSConnections = &kLRAllowUntrustedHTTPSConnections;

#pragma mark - Completion Block

- (void)lr_setCompletionHandler:(LRImageCompletionHandler)completionHandler
{
    objc_setAssociatedObject(self, kLRCompletionHandlerObjectKey, completionHandler, OBJC_ASSOCIATION_COPY);
}

- (LRImageCompletionHandler)lr_completionHandler
{
    return objc_getAssociatedObject(self, kLRCompletionHandlerObjectKey);
}

#pragma mark - Activity Indicator

- (void)lr_setActivityIndicator:(UIView<LRActivityIndicator> *)activityIndicator
{
    [self.lr_activityIndicator removeFromSuperview];

    objc_setAssociatedObject(self, kLRActivityIndicatorObjectKey, activityIndicator, OBJC_ASSOCIATION_RETAIN);
}

- (UIView<LRActivityIndicator> *)lr_activityIndicator
{
    return objc_getAssociatedObject(self, kLRActivityIndicatorObjectKey);
}

#pragma mark - Animation Type

- (void)lr_setAnimationType:(LRImageViewAnimationType)animationType
{
    objc_setAssociatedObject(self, kLRAnimationType, @(animationType), OBJC_ASSOCIATION_RETAIN);
}

- (LRImageViewAnimationType)lr_animationType
{
    NSNumber *animationTypeNumber = objc_getAssociatedObject(self, kLRAnimationType);
    return animationTypeNumber ? [animationTypeNumber unsignedIntegerValue] : kDefaultImageViewAnimationType;
}

#pragma mark - Animation Time

- (void)lr_setAnimationTime:(NSTimeInterval)animationTme
{
    objc_setAssociatedObject(self, kLRAnimationTime, @(animationTme), OBJC_ASSOCIATION_RETAIN);
}

- (NSTimeInterval)lr_animationTime
{
    NSNumber *animationTimeNumber = objc_getAssociatedObject(self, kLRAnimationTime);
    return animationTimeNumber ? [animationTimeNumber doubleValue] : kDefaultImageViewAnimationTime;
}

#pragma mark - Post Processing block

- (void)lr_setPostProcessingBlock:(LRImagePostProcessingBlock)postProcessingBlock
{
    objc_setAssociatedObject(self, kLRPostProcessingBlock, postProcessingBlock, OBJC_ASSOCIATION_COPY);
}

- (LRImagePostProcessingBlock)lr_postProcessingBlock
{
    return objc_getAssociatedObject(self, kLRPostProcessingBlock);
}

#pragma mark - HTTPS

- (BOOL)lr_allowUntrustedHTTPSConnections
{
    NSNumber *allowUntrustedHTTPSConnections = objc_getAssociatedObject(self, kLRAllowUntrustedHTTPSConnections);
    return allowUntrustedHTTPSConnections ? [allowUntrustedHTTPSConnections boolValue] : NO;
}

- (void)lr_setAllowUntrustedHTTPSConnections:(BOOL)value
{
    objc_setAssociatedObject(self, kLRAllowUntrustedHTTPSConnections, @(value), OBJC_ASSOCIATION_RETAIN);
}

@end


text:
@interface FFXMasonryGridLayoutSectionInfo : AAPLGridLayoutSectionInfo

@end

redpajama_set_name: RedPajamaGithub


text:
import os
from setuptools import find_packages, setup

def extract_version():
    """Return ggplot.__version__ without importing ggplot.

    Extracts version from ggplot/__init__.py
    without importing ggplot, which requires dependencies to be installed.
    """
    with open('ggplot/__init__.py') as fd:
        ns = {}
        for line in fd:
            if line.startswith('__version__'):
                exec(line.strip(), ns)
                return ns['__version__']

setup(
    name="ggplot",
    # Increase the version in ggplot/__init__.py
    version=extract_version(),
    author="Greg Lamp",
    author_email="greg@yhathq.com",
    url="https://github.com/yhat/ggplot/",
    license="BSD",
    packages=find_packages(),
    package_dir={ "ggplot": "ggplot" },
    package_data={
        "ggplot": [
            "datasets/*.csv",
            "geoms/*.png"
        ]
    },
    description="ggplot for python",
    # run pandoc --from=markdown --to=rst --output=README.rst README.md
    long_description=open("README.rst").read(),
    install_requires=[
        "six",
        "statsmodels",
        "brewer2mpl",
        "matplotlib",
        "scipy",
        "patsy>=0.4",
        "pandas",
        "cycler",
        "numpy"
    ],
    classifiers=[
        'Intended Audience :: Science/Research',
        'Intended Audience :: Developers',
        'Programming Language :: Python',
        'Topic :: Software Development',
        'Topic :: Scientific/Engineering',
        'Operating System :: Microsoft :: Windows',
        'Operating System :: POSIX',
        'Operating System :: Unix',
        'Operating System :: MacOS',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3'
    ],
    zip_safe=False
)


text:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type='text/xsl' href='../../../../../../../../../../../test.xsl'?>
<!--
    Licensed to the Apache Software Foundation (ASF) under one or more
    contributor license agreements.  See the NOTICE file distributed with
    this work for additional information regarding copyright ownership.
    The ASF licenses this file to You under the Apache License, Version 2.0
    (the "License"); you may not use this file except in compliance with
    the License.  You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
-->
<!DOCTYPE Test SYSTEM '../../../../../../../../../../../test.dtd'>
<!--
-->

<Test
    ID="DefaultDocumentEventTest"
    date-of-creation="2005-06-03"
    timeout="1"
    >

    <MulticaseTestDescription>
        <TestedClass name="javax.swing.text.AbstractDocument$DefaultDocumentEvent"/>

        <Case ID="testConstructor">
            <TestedMethod name="public AbstractDocument.DefaultDocumentEvent(int offs, int len, DocumentEvent.EventType type)"/>
            <Precondition></Precondition>
            <Description></Description>
            <Expected></Expected>
        </Case>

        <Case ID="testAddEdit">
            <TestedMethod name="public boolean addEdit(UndoableEdit anEdit)"/>
            <Precondition></Precondition>
            <Description></Description>
            <Expected></Expected>
        </Case>

        <Case ID="testAddEdit">
            <TestedMethod name="public boolean addEdit(UndoableEdit anEdit)"/>
            <Precondition></Precondition>
            <Description></Description>
            <Expected></Expected>
        </Case>

        <Case ID="testGetChange">
            <TestedMethod name="public DocumentEvent.ElementChange getChange(Element elem)"/>
            <Precondition></Precondition>
            <Description></Description>
            <Expected></Expected>
        </Case>

        <Case ID="testGetDocument">
            <TestedClass name="javax.swing.text.AbstractDocument$AbstractElement"/>
            <TestedMethod name="public Document getDocument()"/>
            <Precondition></Precondition>
            <Description></Description>
            <Expected></Expected>
        </Case>

        <Case ID="testGetLength">
            <TestedMethod name="public int getLength()"/>
            <Precondition></Precondition>
            <Description></Description>
            <Expected></Expected>
        </Case>

        <Case ID="testGetOffset">
            <TestedMethod name="public int getOffset()"/>
            <Precondition></Precondition>
            <Description></Description>
            <Expected></Expected>
        </Case>

        <Case ID="testGetType">
            <TestedMethod name="public DocumentEvent.EventType getType()"/>
            <Precondition></Precondition>
            <Description></Description>
            <Expected></Expected>
        </Case>

        <Case ID="testIsSignificant">
            <TestedMethod name="public boolean isSignificant()"/>
            <Precondition></Precondition>
            <Description></Description>
            <Expected></Expected>
        </Case>

        <Case ID="testUndo">
            <TestedMethod name="public void redo()"/>
            <TestedMethod name="public void undo()"/>
            <Precondition></Precondition>
            <Description></Description>
            <Expected></Expected>
        </Case>

        <Case ID="testRedo">
            <TestedMethod name="public void redo()"/>
            <TestedMethod name="public void undo()"/>
            <Precondition></Precondition>
            <Description></Description>
            <Expected></Expected>
        </Case>
    </MulticaseTestDescription>

    <Keyword name="functional"/>
    <Keyword name="gui"/>
    <Source name="DefaultDocumentEventTest.java"/>

    <Runner ID="Runtime">
        <Param name="toRun" value="org.apache.harmony.test.func.api.javax.swing.text.AbstractDocument.DefaultDocumentEventTest">
        </Param>
    </Runner>
    <Restriction name="OtherVMOnly"/>
</Test>


text:
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<script src="script.js"></script>
	<title>Exercise_08</title>
</head>
<body>

</body>
</html>


text:
/**
 *
 */
package org.rcsb.mmtf.encoders;

import static org.junit.Assert.assertEquals;

import java.util.Arrays;
import java.util.List;

import org.junit.Test;
import org.rcsb.mmtf.intracoders.IntraDeltaEncoder;
import org.rcsb.mmtf.utils.Convertors;

/**
 * @author Yana Valasatava
 *
 */
public class TestIntraDeltaEncoder {

	@Test
	public void TestEncodeIntraDelta() {

		// create arrays with values known to be correct
		List<Integer> inArray = Arrays.asList(5,9,10,15,12,1);
		int[] in = Convertors.listIntegerToPrimitives(inArray);

		List<Integer> outArray = Arrays.asList(5,4,1,5,-3,-11);
		int[] out = Convertors.listIntegerToPrimitives(outArray);

		// create a test array with method to be tested
		IntraDeltaEncoder encoder = new IntraDeltaEncoder();
		int[] test = encoder.run(in);

		for (int i=0; i < out.length; i++) {
			assertEquals(out[i], test[i]);
		}
	}

}


text:
import logging

from . import Middleware

log = logging.getLogger("levitas.middleware.loggerMiddleware")

class LoggerMiddleware(Middleware):
    """
    Handles logging from python http-logging-handler.

    Example settings entry:
    urls = [(r"^/logging$", LoggerMiddleware, "myapp")]
    """
    LOG = False

    def __init__(self, loggerName=""):
        """
        @param loggerName: Name displayed in log.
        """
        Middleware.__init__(self)

        self.loggerName = loggerName

    def get(self):
        return self._do_logging(self.request_data)

    def post(self):
        return self._do_logging(self.request_data)

    def _do_logging(self, data):
        name = self.request_data["name"][0]
        name = self.loggerName + "." + name
        log = logging.getLogger(name)
        level = self.request_data["levelname"][0].upper()
        try:
            level = logging._levelNames[level]  # python 2
        except:
            level = logging._nameToLevel[level]  # python 3 @UndefinedVariable
        msg = self.request_data["msg"][0]
        msg += " - %s - %s" % (self.remote_address,
                               self.request_headers["HTTP_USER_AGENT"])
        log.log(level, msg)

        return


text:
<?xml version="1.0"?>
<!--

-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">
    <body>
        <attribute name="class" value="page-product-downloadable"/>
        <referenceBlock name="head.components">
            <block class="Magento\Framework\View\Element\Js\Components" name="wishlist_product_view_head_components" template="Magento_Wishlist::js/components.phtml"/>
            <block class="Magento\Framework\View\Element\Js\Components" name="downloadable_page_head_components" template="Magento_Downloadable::js/components.phtml"/>
        </referenceBlock>
        <referenceContainer name="product.info.main">
            <block class="Magento\Downloadable\Block\Catalog\Product\Samples" name="product.info.downloadable.samples" as="samples" template="catalog/product/samples.phtml" after="product.price.tier" />
        </referenceContainer>
        <referenceContainer name="product.info.type">
            <block class="Magento\Downloadable\Block\Catalog\Product\View\Type" name="product.info.downloadable" as="product_type_data" template="catalog/product/type.phtml">
                <block class="Magento\CatalogInventory\Block\Stockqty\DefaultStockqty" name="product.info.downloadable.extra" as="product_type_data_extra" template="stockqty/default.phtml"/>
            </block>
        </referenceContainer>
        <referenceBlock name="product.info.options.wrapper">
            <block class="Magento\Downloadable\Block\Catalog\Product\Links" name="product.info.downloadable.options" as="type_downloadable_options" before="-" template="catalog/product/links.phtml">
                <block class="Magento\Catalog\Pricing\Render" name="product.price.link" after="product.info.downloadable.options">
                    <arguments>
                        <argument name="price_render" xsi:type="string">product.price.render.default</argument>
                        <argument name="price_type_code" xsi:type="string">link_price</argument>
                    </arguments>
                </block>
            </block>
        </referenceBlock>
        <referenceContainer name="product.info.options.wrapper.bottom">
            <block class="Magento\Catalog\Pricing\Render" name="product.price.final.copy" before="-">
                <arguments>
                    <argument name="price_render" xsi:type="string">product.price.render.default</argument>
                    <argument name="price_type_code" xsi:type="string">final_price</argument>
                    <argument name="display_msrp_help_message" xsi:type="string">1</argument>
                    <argument name="zone" xsi:type="string">item_view</argument>
                    <argument name="id_suffix_some" xsi:type="string">copy-</argument>
                </arguments>
            </block>
        </referenceContainer>
        <move element="product.info" destination="content" after="product.info.media" />
        <move element="product.info.social" destination="product.info.options.wrapper.bottom" after="-" />
    </body>
</page>


text:
require_relative "../lib/mongoid-dsl"
require_relative "helper/connection"
require_relative "helper/models"

test_a= TestA.create! test: "hello"
test_a.test_b.create(test: "world")
test_b= test_a.test_b.last
test_b.test_c.create(test: "world")
test_c= test_b.test_c.last
test_c.test_d.create(test: "world")
test_d= test_c.test_d.last

# puts TestD._find(test_d['_id']).inspect
#<TestD _id: 536a10f6241548c811000004, created_at: 2014-05-07 10:54:46 UTC, updated_at: 2014-05-07 10:54:46 UTC, test: "world">

puts TestD._all.inspect
#> return every embedded TestD obj

puts TestD._where( TestA, test: "world" ).inspect
#> return by criteria the embedded TestD objects

Mongoid.purge!


text:
<?php

namespace Confidences\ZendIntercom\Factory;

use Interop\Container\ContainerInterface;
use Zend\ServiceManager\Factory\FactoryInterface;

class ModuleOptionsFactory implements FactoryInterface
{
    /**
     * {@inheritDoc}
     */
    public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
    {
        $config = $container->get('Config');
        return new $requestedName(isset($config['zend-intercom']) ? $config['zend-intercom'] : []);
    }
}


text:
function onChangeSelectHandler(event) {
    var target = event.target;
    var testDivEl = target.closest(".testDiv");
    onChangeSelectHandlerForTestDiv(testDivEl);
};

function onChangeSelectHandlerForTestDiv(testDiv) {
    var selectEl = getSelectElForTestDiv(testDiv);
    var options = selectEl.options;

    var generatedUlDivEl = testDiv.querySelector(".generatedUlDiv");
    var generatedUl = '
';
    for (i = 0; i < options.length; i++) {
        generatedUl += '
' + options[i].label + '
';

        if (options[i].selected) {
            setNameToResultFromTestDiv(testDiv, options[i].label);
        }
    }
    generatedUl += '
';
    generatedUlDivEl.innerHTML = generatedUl;

    var searchInputDivEl = testDiv.querySelector(".searchInputDiv");
    searchInputDivEl.innerHTML = '<input type="text" onkeyup="onKeyUpSearch(this)" id="searchInput" name="searchInput" value="" class="setting-input" placeholder="Search Tests..."/>';
};

// START
setTimeout(function() {
    var testDivs = getAllTestDivs();
    for (var i = 0; i < testDivs.length; i++) {
        var div = testDivs[i];
        setNameToResultFromTestDiv(div, getSelectElForTestDiv(div).getAttribute("value"));
        executeIntervalTaskForDiv(div);
    }

}, 2000);
// end of START

function executeIntervalTaskForDiv(testDiv) {
    // waiting when init state of original <select> will be changed
    var count = 0;
    var prevValue;
    var isFirst = true;
    var interval = setInterval(function() {
        var resultDivEl = testDiv.querySelector("#result");
        if (isFirst) {
            prevValue = resultDivEl.innerHTML;
            isFirst = false;
        }

        onChangeSelectHandlerForTestDiv(testDiv); // if <select> element filled it will change 'resultDivEl.innerHTML'
        var curValue = resultDivEl.innerHTML;

        if ((prevValue != curValue) || (count >= 20)) {
            clearInterval(interval);
        }
        count++;
    }, 500);
};

function setNameToResultFromTestDiv(testDiv, name) {
    var resultDivEl = testDiv.querySelector("#result");
    resultDivEl.innerHTML = name;
};

function getAllTestDivs() {
    return document.getElementsByClassName("testDiv");
};

function executeIntervalTask(selectEl) {
    var builderEl = selectEl.closest("div[descriptorid='hudson.plugins.blazemeter.PerformanceBuilder']");
    var testDivEl = builderEl.querySelector(".testDiv");
    executeIntervalTaskForDiv(testDivEl)
};

function getSelectElForTestDiv(testDivEl) {
    return testDivEl.getElementsByTagName("select")[0];
};

function onKeyUpSearch(searchInputEl) {
    var text = searchInputEl.value.toLowerCase();
    var testDivEl = searchInputEl.closest(".testDiv");
    var ulEl = testDivEl.querySelector("#generatedUl");
    var liList = ulEl.getElementsByTagName("li");
    var displayIndex = 0;
    for (i = 0; i < liList.length; i++) {
        if (!liList[i].innerHTML.toLowerCase().includes(text)) {
            liList[i].style.display = "none";
            liList[i].dataset.displayIndex = -1;
        } else {
            liList[i].style.display = "";
            liList[i].dataset.displayIndex = displayIndex;
            displayIndex++;
        }
    }
    ulEl.dataset.displayElements = displayIndex;
    if (curFocusedLi != null && curFocusedLi.dataset.displayIndex == -1) {
        clearFocusLi(curFocusedLi);
        curFocusedLi = null;
        ulEl.scrollTop = 0;
    }
};

function onClickResultHandler(resultDivEl) {
    var testDivEl = resultDivEl.closest(".testDiv");
    var toggleEl = testDivEl.querySelector(".hiddenSelect");
    if (toggleEl.style.display === "block") {
        hideHiddenSelect(toggleEl);
    } else {
        onChangeSelectHandlerForTestDiv(testDivEl);
        openHiddenSelect(testDivEl, toggleEl);
        disableScroll();
    }
};

function hideHiddenSelect(toggleEl) {
    if (toggleEl != null) {
        toggleEl.style.display = "none";
        curFocusedLi = null;
        enableScroll();
    }
};

function openHiddenSelect(testDivEl, toggleEl) {
    toggleEl.style.display = "block";
    var searchInputEl = toggleEl.querySelector("#searchInput");
    searchInputEl.focus();
    var generatedUlEl = toggleEl.querySelector("#generatedUl");
    var liList = generatedUlEl.getElementsByTagName("li");
    var resultDivEl = testDivEl.querySelector("#result");
    for (i = 0; i < liList.length; i++) {
        if (liList[i].innerHTML == resultDivEl.innerHTML) {
            focusLi(liList[i]);
            moveScroll(generatedUlEl, liList[i].dataset.displayIndex);
            return;
        }
    }
};

function onClickListElementHandler(li) {
    var testDivEl = li.closest(".testDiv");
    setNameToResultFromTestDiv(testDivEl, li.innerHTML);
    setValueToSelect(testDivEl, li);
    var toggleEl = testDivEl.querySelector(".hiddenSelect");
    hideHiddenSelect(toggleEl);
};

document.onmousedown = function(event) {
    if (!isGeneratedElement(event)) {
        var testDivs = getAllTestDivs();
        for (var i = 0; i < testDivs.length; i++) {
            var div = testDivs[i];
            var toggleEl = div.querySelector(".hiddenSelect");
            hideHiddenSelect(toggleEl);
        }
    }
};

function setValueToSelect(testDivEl, li) {
    var selectEl = getSelectElForTestDiv(testDivEl);
    selectEl.setAttribute("value", li.dataset.value);
    selectEl.options[li.dataset.index].selected = true;
};

function isGeneratedElement(event) {
    return (event.target.id == "result"
                   || event.target.id == "generatedUl"
                   || event.target.getAttribute("class") == "generatedLi"
                   || event.target.id == "searchInput");
};

document.onkeydown = function(event) {
    var charCode = event.keyCode;
    var focusedTag = document.activeElement.tagName;
    var targetInputEl = event.target;
    var toggleEl = targetInputEl.closest(".hiddenSelect");
    if (toggleEl != null && toggleEl.style.display === "block") {
        var generatedUlEl = toggleEl.querySelector("#generatedUl");
        if (isPressedDown(charCode)) {
            selectNextLi(generatedUlEl);
        } else if (isPressedUp(charCode)) {
            selectPrevLi(generatedUlEl);
        } else if (isPressedEnter(charCode)) {
            setCurrentLi(generatedUlEl);
        }
        preventDefaultForScrollKeys(event);
    }
};

function isPressedDown(charCode) {
    return (charCode === 40);
};

function isPressedUp(charCode) {
    return (charCode === 38);
};

function isPressedEnter(charCode) {
    return (charCode === 13);
};

var curFocusedLi = null;

// set style   background: #1E90FF;  color: #ffffff;
function focusLi(li) {
    li.style.background = "#1E90FF";
    li.style.color = "#ffffff";
    if (curFocusedLi != null) {
        clearFocusLi(curFocusedLi);
        curFocusedLi = null;
    }
    curFocusedLi = li;
};

// return default colors
function clearFocusLi(li) {
    li.style.background = "#ffffff";
    li.style.color = "#000000";
};

function selectNextLi(ulEl) {
    var currentIndex = (curFocusedLi == null) ? -1 : curFocusedLi.dataset.displayIndex;
    var nextIndex = ++currentIndex;
    var liList = ulEl.getElementsByTagName("li");
    for (i = 0; i < liList.length; i++) {
        if (liList[i].dataset.displayIndex == nextIndex) {
            focusLi(liList[i]);
            moveScroll(ulEl, nextIndex);
            return;
        }
    }
    selectFirst(ulEl, liList);
};

// need use liList[i].dataset.displayIndex
function moveScroll(ulEl, index) {
    var elementsCount = ulEl.dataset.displayElements;
    var liList = ulEl.getElementsByTagName("li");
    if (liList.length > 0 && elementsCount > 0) {
        var liHeight = parseFloat(getLiHeight(liList, index));
        var ulHeight = parseFloat(window.getComputedStyle(ulEl, null).getPropertyValue("height"));
        var median = (ulHeight / liHeight / 2);
        if (index > median) {
            ulEl.scrollTop = (liHeight * (index - median));
        } else {
            ulEl.scrollTop = 0;
        }
    }
};

function getLiHeight(liList, displayIndex) {
    for (i = 0; i < liList.length; i++) {
        if (liList[i].dataset.displayIndex == displayIndex) {
            return liList[i].clientHeight;
        }
    }

    var height = window.getComputedStyle(liList[0], null).getPropertyValue("height");
    if (height == 'auto') {
        return 19;
    } else {
        return height;
    }
};

function selectFirst(ulEl, liList) {
    for (i = 0; i < liList.length; i++) {
        if (liList[i].dataset.displayIndex != -1) {
            focusLi(liList[i]);
            moveScroll(ulEl, liList[i].dataset.displayIndex);
            return;
        }
    }
};

function selectPrevLi(ulEl) {
    var liList = ulEl.getElementsByTagName("li");
    if (curFocusedLi == null || curFocusedLi.dataset.displayIndex <= 0) {
        selectLast(ulEl, liList);
        return;
    }
    var currentIndex = curFocusedLi.dataset.displayIndex;
    var prevIndex = --currentIndex;
    for (i = 0; i < liList.length; i++) {
        if (liList[i].dataset.displayIndex == prevIndex) {
            focusLi(liList[i]);
            moveScroll(ulEl, prevIndex);
            return;
        }
    }
    selectLast(ulEl, liList);
};

function selectLast(ulEl, liList) {
    for (i = liList.length - 1; i >= 0; i--) {
        if (liList[i].dataset.displayIndex != -1) {
            focusLi(liList[i]);
            moveScroll(ulEl, liList[i].dataset.displayIndex);
            return;
        }
    }
};

function setCurrentLi(ulEl) {
    if (curFocusedLi != null) {
        onClickListElementHandler(curFocusedLi);
    }
};

// left: 37, up: 38, right: 39, down: 40,
// spacebar: 32, pageup: 33, pagedown: 34, end: 35, home: 36
var keys = {37: 1, 38: 1, 39: 1, 40: 1, 13: 1};

function preventDefault(e) {
    e = e || window.event;
    if (e.preventDefault) {
        e.preventDefault();
    }
    e.returnValue = false;
};

function preventDefaultForScrollKeys(e) {
    if (keys[e.keyCode]) {
        preventDefault(e);
        return false;
    }
};

function disableScroll() {
    if (window.addEventListener) { // older FF
        window.addEventListener('DOMMouseScroll', preventDefault, false);
    }
};

function enableScroll() {
    if (window.removeEventListener) {
        window.removeEventListener('DOMMouseScroll', preventDefault, false);
    }
};


text:
package openapi

import (
	"sync"

	"k8s.io/client-go/discovery"
	openapi "k8s.io/kube-openapi/pkg/util/proto"
)

// synchronizedOpenAPIGetter fetches the openapi schema once and then caches it in memory
type synchronizedOpenAPIGetter struct {
	// Cached results
	sync.Once
	openAPISchema openapi.Resources
	err           error

	openAPIClient discovery.OpenAPISchemaInterface
}

var _ Getter = &synchronizedOpenAPIGetter{}

// Getter is an interface for fetching openapi specs and parsing them into an Resources struct
type Getter interface {
	// OpenAPIData returns the parsed OpenAPIData
	Get() (openapi.Resources, error)
}

// NewOpenAPIGetter returns an object to return OpenAPIDatas which reads
// from a server, and then stores in memory for subsequent invocations
func NewOpenAPIGetter(openAPIClient discovery.OpenAPISchemaInterface) Getter {
	return &synchronizedOpenAPIGetter{
		openAPIClient: openAPIClient,
	}
}

// Resources implements Getter
func (g *synchronizedOpenAPIGetter) Get() (openapi.Resources, error) {
	g.Do(func() {
		s, err := g.openAPIClient.OpenAPISchema()
		if err != nil {
			g.err = err
			return
		}

		g.openAPISchema, g.err = openapi.NewOpenAPIData(s, ParseGroupVersionKind)
	})

	// Return the save result
	return g.openAPISchema, g.err
}


text:
<?php

defined('IN_IA') or exit('Access Denied');

function permission_build() {
	global $_W, $acl;
	$we7_file_permission = $acl;
	$permission_frames = require IA_ROOT . '/web/common/frames.inc.php';
	if (!in_array($_W['role'], array(ACCOUNT_MANAGE_NAME_OPERATOR, ACCOUNT_MANAGE_NAME_MANAGER)) || empty($_W['uniacid'])) {
		return $we7_file_permission;
	}

	$cachekey = cache_system_key("permission:{$_W['uniacid']}:{$_W['uid']}");
	$cache = cache_load($cachekey);
	if (!empty($cache)) {
		return $cache;
	}
	$permission_exist = permission_account_user_permission_exist($_W['uid'], $_W['uniacid']);
	if (empty($permission_exist)) {
		$we7_file_permission['platform'][$_W['role']] = array('platform*');
		$we7_file_permission['site'][$_W['role']] = array('site*');
		$we7_file_permission['mc'][$_W['role']] = array('mc*');
		$we7_file_permission['profile'][$_W['role']] = array('profile*');
		$we7_file_permission['module'][$_W['role']] = array('manage-account', 'display');
		$we7_file_permission['wxapp'][$_W['role']] = array('display', 'payment', 'post', 'version');
		$we7_file_permission['webapp'][$_W['role']] = array('home', 'manage');
		$we7_file_permission['phoneapp'][$_W['role']] = array('display', 'manage');
		cache_write($cachekey, $we7_file_permission);
		return $we7_file_permission;
	}
	$user_account_permission = permission_account_user_menu($_W['uid'], $_W['uniacid'], PERMISSION_ACCOUNT);
	$user_wxapp_permission = permission_account_user_menu($_W['uid'], $_W['uniacid'], PERMISSION_WXAPP);
	$user_permission = array_merge($user_account_permission, $user_wxapp_permission);

	$permission_contain = array('account', 'wxapp', 'system', 'phoneapp');
	$section = array();
	$permission_result = array();
	foreach ($permission_frames as $key => $frames) {
		if (!in_array($key, $permission_contain) || empty($frames['section'])) {
			continue;
		}
		foreach ($frames['section'] as $frame_key => $frame) {
			if (empty($frame['menu'])) {
				continue;
			}
			$section[$key][$frame_key] = $frame['menu'];
		}
	}
	$account = permission_get_nameandurl($section[$permission_contain[0]]);
	$wxapp = permission_get_nameandurl($section[$permission_contain[1]]);
	$system = permission_get_nameandurl($section[$permission_contain[2]]);
	$permission_result = array_merge($account, $wxapp, $system);

	foreach ($permission_result as $permission_val) {
		if (in_array($permission_val['permission_name'], $user_permission)) {
			$we7_file_permission[$permission_val['controller']][$_W['role']][] = $permission_val['action'];
		}
	}
	cache_write($cachekey, $we7_file_permission);
	return $we7_file_permission;
}

function permission_get_nameandurl($permission) {
	$result = array();
	if (empty($permission)) {
		return $result;
	}
	foreach ($permission as $menu) {
		if (empty($menu)) {
			continue;
		}
		foreach ($menu as $permission_name) {
			$url_query_array = url_params($permission_name['url']);
			$result[] = array(
				'url' => $permission_name['url'],
				'controller' => $url_query_array['c'],
				'action' => $url_query_array['a'],
				'permission_name' => $permission_name['permission_name']
			);
			if (!empty($permission_name['sub_permission'])) {
				foreach ($permission_name['sub_permission'] as $key => $sub_permission_name) {
					$sub_url_query_array = url_params($sub_permission_name['url']);
					$result[] = array(
						'url' => $sub_permission_name['url'],
						'controller' => $sub_url_query_array['c'],
						'action' => $sub_url_query_array['a'],
						'permission_name' => $sub_permission_name['permission_name'],
					);
				}
			}
		}
	}
	return $result;
}

function permission_create_account($uid, $type = ACCOUNT_TYPE_OFFCIAL_NORMAL) {
	$uid = intval($uid);
	if (empty($uid)) {
		return error(-1, '用户数据错误!');
	}
	$user_table = table('users');
	$userinfo = $user_table->usersInfo($uid);
	$groupdata = $user_table->usersGroupInfo($userinfo['groupid']);
	$list = table('account')->getOwnedAccountCount($uid);
	foreach ($list as $item) {
		if ($item['type'] == ACCOUNT_TYPE_APP_NORMAL) {
			$wxapp_num = $item['count'];
		} else {
			$account_num = $item['count'];
		}
	}
		if ($type == ACCOUNT_TYPE_OFFCIAL_NORMAL || $type == ACCOUNT_TYPE_OFFCIAL_AUTH) {
		if ($account_num >= $groupdata['maxaccount']) {
			return error('-1', '您所在的用户组最多只能创建' . $groupdata['maxaccount'] . '个主公众号');
		}
	} elseif ($type == ACCOUNT_TYPE_APP_NORMAL) {
		if ($wxapp_num >= $groupdata['maxwxapp']) {
			return error('-1', '您所在的用户组最多只能创建' . $groupdata['maxwxapp'] . '个小程序');
		}
	}
	return true;
}

function permission_account_user_role($uid = 0, $uniacid = 0) {
	global $_W;
	load()->model('user');
	$role = '';
	$uid = empty($uid) ? $_W['uid'] : intval($uid);

	if (user_is_founder($uid) && !user_is_vice_founder($uid)) {
		return ACCOUNT_MANAGE_NAME_FOUNDER;
	}

	if (user_is_vice_founder($uid)) {
		return ACCOUNT_MANAGE_NAME_VICE_FOUNDER;
	}
	if (!user_is_bind()) {
		return ACCOUNT_MANAGE_NAME_UNBIND_USER;
	}
	$user_table = table('users');
	if (!empty($uniacid)) {
		$role = $user_table->userOwnedAccountRole($uid, $uniacid);
		if ($role == ACCOUNT_MANAGE_NAME_OWNER) {
			$role = ACCOUNT_MANAGE_NAME_OWNER;
		} elseif ($role == ACCOUNT_MANAGE_NAME_VICE_FOUNDER) {
			$role = ACCOUNT_MANAGE_NAME_VICE_FOUNDER;
		} elseif ($role == ACCOUNT_MANAGE_NAME_MANAGER) {
			$role = ACCOUNT_MANAGE_NAME_MANAGER;
		} elseif ($role == ACCOUNT_MANAGE_NAME_OPERATOR) {
			$role = ACCOUNT_MANAGE_NAME_OPERATOR;
		} elseif ($role == ACCOUNT_MANAGE_NAME_CLERK) {
			$role = ACCOUNT_MANAGE_NAME_CLERK;
		}
		return $role;
	} else {
		$roles = $user_table->userOwnedAccountRole($uid);
		if (in_array(ACCOUNT_MANAGE_NAME_VICE_FOUNDER, $roles)) {
			$role = ACCOUNT_MANAGE_NAME_VICE_FOUNDER;
		} elseif (in_array(ACCOUNT_MANAGE_NAME_OWNER, $roles)) {
			$role = ACCOUNT_MANAGE_NAME_OWNER;
		} elseif (in_array(ACCOUNT_MANAGE_NAME_MANAGER, $roles)) {
			$role = ACCOUNT_MANAGE_NAME_MANAGER;
		} elseif (in_array(ACCOUNT_MANAGE_NAME_OPERATOR, $roles)) {
			$role = ACCOUNT_MANAGE_NAME_OPERATOR;
		} elseif (in_array(ACCOUNT_MANAGE_NAME_CLERK, $roles)) {
			$role = ACCOUNT_MANAGE_NAME_CLERK;
		}
	}
	$role = empty($role) ? ACCOUNT_MANAGE_NAME_OPERATOR : $role;
	return $role;
}

function permission_account_user_permission_exist($uid = 0, $uniacid = 0) {
	global $_W;
	load()->model('user');
	$uid = intval($uid) > 0 ? $uid : $_W['uid'];
	$uniacid = intval($uniacid) > 0 ? $uniacid : $_W['uniacid'];
	if (user_is_founder($uid)) {
		return false;
	}
	if (FRAME == 'system') {
		return true;
	}
	$is_exist = table('userspermission')->userPermissionInfo($uid, $uniacid);
	if(empty($is_exist)) {
		return false;
	} else {
		return true;
	}
}

function permission_account_user($type = 'system') {
	global $_W;
	$user_permission = table('userspermission')->userPermissionInfo($_W['uid'], $_W['uniacid'], $type);
	$user_permission = $user_permission['permission'];
	if (!empty($user_permission)) {
		$user_permission = explode('|', $user_permission);
	} else {
		$user_permission = array('account*', 'wxapp*', 'phoneapp*');
	}
	$permission_append = frames_menu_append();
		if (!empty($permission_append[$_W['role']])) {
		$user_permission = array_merge($user_permission, $permission_append[$_W['role']]);
	}
		if (empty($_W['role']) && empty($_W['uniacid'])) {
		$user_permission = array_merge($user_permission, $permission_append['operator']);
	}
	return (array)$user_permission;
}

function permission_account_user_menu($uid, $uniacid, $type) {
	$user_menu_permission = array();

	$uid = intval($uid);
	$uniacid = intval($uniacid);
	$type = trim($type);
	if (empty($uid) || empty($uniacid) || empty($type)) {
		return error(-1, '参数错误!');
	}
	$permission_exist = permission_account_user_permission_exist($uid, $uniacid);
	if (empty($permission_exist)) {
		return array('all');
	}
	$user_permission_table = table('userspermission');
	if ($type == 'modules') {
		$user_menu_permission = $user_permission_table->userModulesPermission($uid, $uniacid);
	} else {
		$module = uni_modules_by_uniacid($uniacid);
		$module = array_keys($module);
		if (in_array($type, $module) || in_array($type, array(PERMISSION_ACCOUNT, PERMISSION_WXAPP, PERMISSION_SYSTEM))) {
			$menu_permission = $user_permission_table->userPermissionInfo($uid, $uniacid, $type);
			if (!empty($menu_permission['permission'])) {
				$user_menu_permission = explode('|', $menu_permission['permission']);
			}
		}
	}

	return $user_menu_permission;
}

function permission_menu_name() {
	load()->model('system');
	$menu_permission = array();

	$menu_list = system_menu_permission_list();
	$middle_menu = array();
	$middle_sub_menu = array();
	if (!empty($menu_list)) {
		foreach ($menu_list as $nav_id => $section) {
			foreach ($section['section'] as $section_id => $section) {
				if (!empty($section['menu'])) {
					$middle_menu[] = $section['menu'];
				}
			}
		}
	}

	if (!empty($middle_menu)) {
		foreach ($middle_menu as $menu) {
			foreach ($menu as $menu_val) {
				$menu_permission[] = $menu_val['permission_name'];
				if (!empty($menu_val['sub_permission'])) {
					$middle_sub_menu[] = $menu_val['sub_permission'];
				}
			}
		}
	}

	if (!empty($middle_sub_menu)) {
		foreach ($middle_sub_menu as $sub_menu) {
			foreach ($sub_menu as $sub_menu_val) {
				$menu_permission[] = $sub_menu_val['permission_name'];
			}
		}
	}
	return $menu_permission;
}

function permission_update_account_user($uid, $uniacid, $data) {
	$uid = intval($uid);
	$uniacid = intval($uniacid);
	if (empty($uid) || empty($uniacid) || !in_array($data['type'], array(PERMISSION_ACCOUNT, PERMISSION_WXAPP, PERMISSION_SYSTEM))) {
		return error('-1', '参数错误!');
	}
	$user_menu_permission = permission_account_user_menu($uid, $uniacid, $data['type']);
	if (is_error($user_menu_permission)) {
		return error('-1', '参数错误!');
	}

	if (empty($user_menu_permission)) {
		$insert = array(
			'uniacid' => $uniacid,
			'uid' => $uid,
			'type' => $data['type'],
			'permission' => $data['permission'],
		);
		$result = table('userspermission')->fill($insert)->save();
	} else {
		$update = array(
			'permission' => $data['permission'],
		);
		$result = table('userspermission')->fill($update)->whereUniacid($uniacid)->whereUid($uid)->whereType($data['type'])->save();
	}
	return $result;
}

function permission_check_account_user($permission_name, $show_message = true, $action = '') {
	global $_W, $_GPC, $acl;
	$see_more_info = $acl['see_more_info'];
	if (strpos($permission_name, 'see_') === 0) {
		$can_see_more = false;
		if (defined('FRAME') && FRAME == 'system') {
			$can_see_more = in_array($permission_name, $see_more_info[$_W['highest_role']]) ? true : false;
		} else {
			if (is_array($see_more_info[$_W['role']]) && !empty($see_more_info[$_W['role']])) {
				$can_see_more = in_array($permission_name, $see_more_info[$_W['role']]) ? true : false;
			}
		}
		return $can_see_more;
	}
	$user_has_permission = permission_account_user_permission_exist();
	if (empty($user_has_permission)) {
		return true;
	}
	$modulename = trim($_GPC['m']);
	$do = trim($_GPC['do']);
	$entry_id = intval($_GPC['eid']);

	if ($action == 'reply') {
		$system_modules = system_modules();
		if (!empty($modulename) && !in_array($modulename, $system_modules)) {
			$permission_name = $modulename . '_rule';
			$users_permission = permission_account_user($modulename);
		}
	} elseif ($action == 'cover' && $entry_id > 0) {
		load()->model('module');
		$entry = module_entry($entry_id);
		if (!empty($entry)) {
			$permission_name = $entry['module'] . '_cover_' . trim($entry['do']);
			$users_permission = permission_account_user($entry['module']);
		}
	} elseif ($action == 'nav') {
				if(!empty($modulename)) {
			$permission_name = "{$modulename}_{$do}";
			$users_permission = permission_account_user($modulename);
		} else {
			return true;
		}
	} elseif ($action == 'wxapp' || !empty($_W['account']) && $_W['account']['type'] == ACCOUNT_TYPE_APP_NORMAL) {
		$users_permission = permission_account_user('wxapp');
	} else {
		$users_permission = permission_account_user('system');
	}
	if (!isset($users_permission)) {
		$users_permission = permission_account_user('system');
	}
	if ($users_permission[0] != 'all' && !in_array($permission_name, $users_permission)) {
		if ($show_message) {
			itoast('您没有进行该操作的权限', referer(), 'error');
		} else {
			return false;
		}
	}
	return true;
}

function permission_check_account_user_module($action = '', $module_name = '') {
	global $_W, $_GPC;
	$status = permission_account_user_permission_exist();
	if(empty($status)) {
		return true;
	}
	$a = trim($_GPC['a']);
	$do = trim($_GPC['do']);
	$m = trim($_GPC['m']);
		if ($a == 'manage-account' && $do == 'setting' && !empty($m)) {
		$permission_name = $m . '_setting';
		$users_permission = permission_account_user($m);
		if ($users_permission[0] != 'all' && !in_array($permission_name, $users_permission)) {
			return false;
		}
			} elseif ($a == 'default-entry' && !empty($m)) {
		if (!($_W['isfounder'] || $_W['role'] == ACCOUNT_MANAGE_NAME_OWNER)) {
			return false;
		}
			} elseif (!empty($do) && !empty($m)) {
		$is_exist = table('module')->moduleBindingsInfo($m, $do, 'menu');
		if(empty($is_exist)) {
			return true;
		}
	}
	if(empty($module_name)) {
		$module_name = IN_MODULE;
	}
	$permission = permission_account_user($module_name);
	if(empty($permission) || ($permission[0] != 'all' && !empty($action) && !in_array($action, $permission))) {
		return false;
	}
	return true;
}

function permission_user_account_num($uid = 0) {
	global $_W;
	$uid = intval($uid);
	if ($uid <= 0) {
		$user = $_W['user'];
	} else {
		load()->model('user');
		$user = user_single($uid);
	}

	$user_table = table('users');
	if (user_is_vice_founder($user['uid'])) {
		$role = ACCOUNT_MANAGE_NAME_VICE_FOUNDER;
		$group = $user_table->userFounderGroupInfo($user['groupid']);
		$group_num = uni_owner_account_nums($user['uid'], $role);
	} else {
		$role = ACCOUNT_MANAGE_NAME_OWNER;
		$group = $user_table->usersGroupInfo($user['groupid']);
		$group_num = uni_owner_account_nums($user['uid'], $role);

		if (empty($_W['isfounder'])) {
			if (!empty($user['owner_uid'])) {
				$owner_info = $user_table->usersInfo($user['owner_uid']);
				$group_vice = $user_table->userFounderGroupInfo($owner_info['groupid']);
				$founder_group_num = uni_owner_account_nums($owner_info['uid'], ACCOUNT_MANAGE_NAME_VICE_FOUNDER);
				$group['maxaccount'] = min(intval($group['maxaccount']), intval($group_vice['maxaccount']));
				$group['maxwxapp'] = min(intval($group['maxwxapp']), intval($group_vice['maxwxapp']));
				$group['maxwebapp'] = min(intval($group['maxwebapp']), intval($group_vice['maxwebapp']));
				$group['maxphoneapp'] = min(intval($group['maxphoneapp']), intval($group_vice['maxphoneapp']));
			}
		}
	}

	$store_table = table('store');
	$create_buy_account_num = $store_table->searchUserCreateAccountNum($_W['uid']);
	$create_buy_wxapp_num = $store_table->searchUserCreateWxappNum($_W['uid']);
	$store_buy_account = $store_table->searchUserBuyAccount($_W['uid']);
	$store_buy_wxapp = $store_table->searchUserBuyWxapp($_W['uid']);
	$uniacid_limit = max((intval($group['maxaccount']) + intval($store_buy_account) - $group_num['account_num']), 0);
	$wxapp_limit = max((intval($group['maxwxapp']) + intval($store_buy_wxapp) - $group_num['wxapp_num']), 0);
	$webapp_limit = max(intval($group['maxwebapp']) - $group_num['webapp_num'], 0);
	$phoneapp_limit = max(intval($group['maxphoneapp']) - $group_num['phoneapp_num'], 0);

	$founder_uniacid_limit = max((intval($group_vice['maxaccount']) + intval($store_buy_account) - $founder_group_num['account_num']), 0);
	$founder_wxapp_limit = max((intval($group_vice['maxwxapp']) + intval($store_buy_wxapp) - $founder_group_num['wxapp_num']), 0);
	$founder_webapp_limit = max(intval($group_vice['maxwebapp']) - $founder_group_num['webapp_num'], 0);
	$founder_phoneapp_limit = max(intval($group_vice['maxphoneapp']) - $founder_group_num['phoneapp_num'], 0);
	$data = array(
		'group_name' => $group['name'],
		'vice_group_name' => $group_vice['name'],
		'maxaccount' => $group['maxaccount'] + $store_buy_account,
		'usergroup_account_limit' => max($group['maxaccount'] - $group_num['account_num'] - $create_buy_account_num, 0),		'usergroup_wxapp_limit' => max($group['maxwxapp'] - $group_num['wxapp_num'] - $create_buy_wxapp_num, 0),		'usergroup_webapp_limit' => max($group['maxwebapp'] - $group_num['webapp_num'], 0),		'usergroup_phoneapp_limit' => max($group['maxphoneapp'] - $group_num['phoneapp_num'], 0),		'uniacid_num' => $group_num['account_num'],
		'uniacid_limit' => max($uniacid_limit, 0),
		'founder_uniacid_limit' => max($founder_uniacid_limit, 0),
		'maxwxapp' => $group['maxwxapp'] + $store_buy_wxapp,
		'wxapp_num' => $group_num['wxapp_num'],
		'wxapp_limit' => max($wxapp_limit, 0),
		'founder_wxapp_limit' => max($founder_wxapp_limit, 0),
		'maxwebapp'=>$group['maxwebapp'],		'webapp_limit' => $webapp_limit, 		'founder_webapp_limit' => max($founder_webapp_limit, 0),
		'webapp_num'=> $group_num['webapp_num'], 		'maxphoneapp' => $group['maxphoneapp'],
		'phoneapp_num' => $group_num['phoneapp_num'],
		'phoneapp_limit' => $phoneapp_limit,
		'founder_phoneapp_limit' => max($founder_phoneapp_limit, 0)
	);
	return $data;
}


text:
class Referral < ApplicationRecord
  belongs_to :referrer, class_name: User.name
  belongs_to :referree, class_name: User.name, foreign_key: 'referred_id'
end


text:
package hydra.blackboard;

import hydra.HydraRuntimeException;
import hydra.Log;
import hydra.RmiRegistryHelper;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.HashMap;
import java.util.Map;

import com.gemstone.gemfire.LogWriter;

/**
 * Maintains a remotely shared lock for a blackboard instance.
 * <p>
 * Requires a thread name to distinguish a non-hydra thread from a hydra thread
 * with the same logical VM id, in case the enumerative JDK 1.5 thread ids and
 * the logical hydra thread ids overlap (which is highly likely).
 */
public class RmiSharedLockImpl
extends UnicastRemoteObject implements RmiSharedLock {

  private String ownerName = null;
  private int ownerVmid = -1;
  private long ownerTid = -1;
  private int lockval = 0;

  private Map conditions = new HashMap(1);

  public RmiSharedLockImpl() throws RemoteException {
    super();
  }

  protected static void bind(String name, RmiSharedLock value) {
    RmiRegistryHelper.bindInMaster(name, value);
    if (log().finerEnabled()) {
      log().finer("Bound " + name + "=" + value + " into master registry");
    }
  }
  protected static RmiSharedLock lookup(String name) throws RemoteException {
    if (log().finerEnabled()) {
      log().finer("Looking up " + name + " in master registry");
    }
    return (RmiSharedLock)RmiRegistryHelper.lookupInMaster(name);
  }
  private static LogWriter log() {
    return Log.getLogWriter();
  }

//------------------------------------------------------------------------------
// SharedLock interface
//------------------------------------------------------------------------------

  /**
   * Implements {@link RmiSharedLock#lock(String,int,long)}.
   */
  public void lock(String name, int vmid, long tid) throws RemoteException {
    synchronized (this) {
      if (lockval == 0) {
        ownerName = name;
        ownerVmid = vmid;
        ownerTid = tid;
        lockval = 1;
        return;
      }
      else if (ownerVmid == vmid && ownerTid == tid && ownerName != null
                                 && ownerName.equals(name)) {
        String s = ownerName + " with vmid=" + ownerVmid + " tid=" + ownerTid
                 + " already unlocked lock";
        throw new HydraRuntimeException(s);
      }
      else {
        boolean wasInterrupted = Thread.interrupted();
        try {
          while (true) {
            try {
              wait();
            }
            catch (InterruptedException e) {
              wasInterrupted = true;
            }
            if (lockval == 0) {
              ownerName = name;
              ownerVmid = vmid;
              ownerTid = tid;
              lockval = 1;
              return;
            }
            else if (ownerVmid == vmid && ownerTid == tid && ownerName != null
                                       && ownerName.equals(name)) {
              String s = ownerName + " with vmid=" + ownerVmid + " tid="
                       + ownerTid + " already locked lock";
              throw new HydraRuntimeException(s);
            }
          }
        }
        finally {
          if (wasInterrupted) Thread.currentThread().interrupt();
        }
      }
    }
  }

  /**
   * Implements {@link RmiSharedLock#unlock(String,int,long)}.
   */
  public synchronized void unlock(String name, int vmid, long tid) throws RemoteException {
    if (ownerVmid == vmid && ownerTid == tid && ownerName != null && ownerName.equals(name)) {
      if (lockval == 1) {
        ownerName = null;
        ownerVmid = -1;
        ownerTid = -1;
        lockval = 0;
        notify();
      }
      else {
        String s = ownerName + " with vmid=" + ownerVmid + " tid=" + ownerTid
                 + " already unlocked lock";
        throw new HydraRuntimeException(s);
      }
    }
    else {
      String s = "Not lock owner, it is owned by " + ownerName
               + " with vmid=" + ownerVmid + " tid=" + ownerTid;
      throw new HydraRuntimeException(s);
    }
  }

  /**
   * Implements {@link RmiSharedLock#getCondition(String)}.
   */
public synchronized RmiSharedCondition getCondition(String name) throws RemoteException {
  RmiSharedCondition condition = (RmiSharedCondition) conditions.get(name);
  if(condition == null) {
    condition = new RmiSharedConditionImpl();
    conditions.put(name, condition);
  }

  return condition;
}

/**
 * A remotely shared condition for a lock object.
 * @author dsmith
 *
 */
private class RmiSharedConditionImpl extends UnicastRemoteObject implements RmiSharedCondition {

  protected RmiSharedConditionImpl() throws RemoteException {
    super();
  }

  private static final long serialVersionUID = 8493062817798851101L;

  /**
   * Implements {@link RmiSharedCondition#await(String,int,long)}.
   */
  public void await(String name, int vmid, long tid) throws RemoteException, InterruptedException {
    if (ownerVmid != vmid || ownerTid != tid ||
       (ownerName != null && !ownerName.equals(name)))
    {
      String s = "Not lock owner, it is owned by " + ownerName
               + " with vmid=" + ownerVmid + " tid=" + ownerTid;
      throw new HydraRuntimeException(s);
    }

    synchronized (this) {
      unlock(name, vmid, tid);
      wait();
    }

    lock(name, vmid, tid);
  }

  /**
   * Implements {@link RmiSharedCondition#signal(String,int,long)}.
   */
  public void signal(String name, int vmid, long tid) throws RemoteException {
    if (ownerVmid != vmid || ownerTid != tid ||
       (ownerName != null && !ownerName.equals(name)))
    {
      String s = "Not lock owner, it is owned by " + ownerName
               + " with vmid=" + ownerVmid + " tid=" + ownerTid;
      throw new HydraRuntimeException(s);
    }

    synchronized (this) {
     notify();
    }

  }

  /**
   * Implements {@link RmiSharedCondition#signalAll(String,int,long)}.
   */
  public void signalAll(String name, int vmid, long tid) throws RemoteException {
    if (ownerVmid != vmid || ownerTid != tid ||
       (ownerName != null && !ownerName.equals(name)))
    {
      String s = "Not lock owner, it is owned by " + ownerName
               + " with vmid=" + ownerVmid + " tid=" + ownerTid;
      throw new HydraRuntimeException(s);
    }

    synchronized(this) {
      notifyAll();
    }
  }

}

}


text:
@protocol AXPracticalHUDAnimator;

extern id<AXPracticalHUDAnimator> _Nullable AXPracticalHUDFadeAnimator(void) NS_SWIFT_NAME(PracticalHUDFadeAnimator());
extern id<AXPracticalHUDAnimator> _Nullable AXPracticalHUDFlipUpAnimator(void) NS_SWIFT_NAME(PracticalHUDFlipUpAnimator());
extern id<AXPracticalHUDAnimator> _Nullable AXPracticalHUDZoomAnimator(void) NS_SWIFT_NAME(PracticalHUDZoomAnimator());
extern id<AXPracticalHUDAnimator> _Nullable AXPracticalHUDDropDownAnimator(void) NS_SWIFT_NAME(PracticalHUDDropDownAnimator());

/// Mode of hud view
typedef NS_ENUM(NSInteger, AXPracticalHUDMode) {
    /// Progress is shown using an UIActivityIndicatorView. This is the default.
    AXPracticalHUDModeNormal,
    /// Progress is shown using a round, pie-chart like, progress view.
    AXPracticalHUDModeProgress,
    /// Progress is shown using a horizontal progress bar
    AXPracticalHUDModeProgressBar,
    /// Progress is shown using a horizontal colorful progress bar
    AXPracticalHUDModeColourfulProgressBar,
    /// Progress is shown using a ring-shaped progress view.
    AXPracticalHUDModeProgressRing,
    /// Shows a custom view
    AXPracticalHUDModeCustomView,
    /// Shows only labels
    AXPracticalHUDModeText,
    /// Progress is shown using an breach annular indicator.
    AXPracticalHUDModeBreachedRing
} NS_SWIFT_NAME(PracticalHUDMode);
/// Position of hud view.
typedef NS_ENUM(NSInteger, AXPracticalHUDPosition) {
    /// Top position.
    AXPracticalHUDPositionTop,
    /// Center position.
    AXPracticalHUDPositionCenter,
    /// Bottom position
    AXPracticalHUDPositionBottom
} NS_SWIFT_NAME(PracticalHUDPosition);
/// Completion block when task finished.
typedef void(^AXPracticalHUDCompletionBlock)(void);
/// HUD delegate
@protocol AXPracticalHUDDelegate;

NS_SWIFT_NAME(PracticalHUD) @interface AXPracticalHUD : UIView
/// Delegate of HUD view,
@property(assign, nonatomic, nullable) id<AXPracticalHUDDelegate>delegate;
#pragma mark - Boolean
/// Restore the hud view when hud hided if YES, setting the properties of hud view to the initial state. Default is NO.
@property(assign, nonatomic, getter=isRestoreEnabled) BOOL restoreEnabled;
/// Lock the background to avoid the touch events if YES. Default is NO.
@property(assign, nonatomic, getter=shouldLockBackground) BOOL lockBackground;
/// Using dim background if YES. Default is NO.
@property(assign, nonatomic, getter=shouldDimBackground) BOOL dimBackground;
/// Remove the hud from super view if hud is hidden. Default is YES.
@property(assign, nonatomic, getter=shouldRemoveFromSuperViewOnHide) BOOL removeFromSuperViewOnHide;
/// Using the square content view if YES. Default is NO.
@property(assign, nonatomic, getter=isSquare) BOOL square;
#pragma mark - Frame.
/// Total size of hud container view. Read only.
@property(readonly, nonatomic) CGSize size;
/// Margin of content views. Default is 15.0f.
@property(assign, nonatomic) CGFloat margin;
/// Offset of cotent view. Default is zero.
@property(assign, nonatomic) CGPoint offsets;
/// Minimum size of container view. Default is CGSizeZero.
@property(assign, nonatomic) CGSize minimumSize;
/// The insets of views in content view bounds. Default is {15.0f, 15.0f, 15.0f, 15.0f}
@property(assign, nonatomic) UIEdgeInsets contentInsets;
#pragma mark - Time interval.
/// Grace time showing hud view. Default is 0.0f.
@property(assign, nonatomic) NSTimeInterval grace;
/// Minimum showing time interval of hud view. Default is 0.5f.
@property(assign, nonatomic) NSTimeInterval threshold;
#pragma mark - Mode and ENUM.
/// Mode of the hud view..
@property(assign, nonatomic) AXPracticalHUDMode mode;
/// Animator to show or hide the hud view. Default using the fade animator.
@property(strong, nonatomic, nonnull) id<AXPracticalHUDAnimator> animator;
/// Position of the hud view.
@property(assign, nonatomic) AXPracticalHUDPosition position;
/// Completion block when hud view has hidden.
@property(copy, nonatomic, nullable) AXPracticalHUDCompletionBlock completion;
#pragma mark - Tasks.
/// Is tasks progressing.
@property(readonly, nonatomic, getter=isProgressing) BOOL progressing;
#pragma mark - Progress.
/// Progress of the progerss indicator.
@property(assign, nonatomic) CGFloat progress;
#pragma mark - Custom view.
/// Custom view. Readwrite.
@property(strong, nonatomic, nullable) UIView *customView;
#pragma mark - Content view
/// Content view.
@property(readonly, strong, nonatomic, nonnull) AXPracticalHUDContentView *contentView;
#pragma mark - Label
/// Title label.
@property(readonly, strong, nonatomic, nonnull) UILabel *label;
#pragma mark - Detail label.
/// Detail label.
@property(readonly, strong, nonatomic, nonnull) UILabel *detailLabel;
#pragma mark - Initializer
- (nullable instancetype)initWithView:(nullable UIView *)view;
- (nullable instancetype)initWithWindow:(nullable UIWindow *)window;
#pragma mark - Show & Hide.
- (void)show:(BOOL)animated;
- (void)hide:(BOOL)animated;

- (void)show:(BOOL)animated executingBlock:(nullable dispatch_block_t)executing onQueue:(nullable dispatch_queue_t)queue completion:(nullable AXPracticalHUDCompletionBlock)completion;
- (void)show:(BOOL)animated executingBlockOnGQ:(nullable dispatch_block_t)executing completion:(nullable AXPracticalHUDCompletionBlock)completion;
- (void)show:(BOOL)animated executingMethod:(nullable SEL)method toTarget:(nullable id)target withObject:(nullable id)object;

- (void)hide:(BOOL)animated afterDelay:(NSTimeInterval)delay completion:(nullable AXPracticalHUDCompletionBlock)completion;
@end

@interface AXPracticalHUD(Shared)
#if UIKIT_DEFINE_AS_PROPERTIES
@property(class, readonly, nonatomic, nullable) AXPracticalHUD *sharedHUD NS_SWIFT_NAME(shared);
#else
+ (nullable instancetype)sharedHUD NS_SWIFT_NAME(shared());
#endif

- (void)showProgressInView:(nullable UIView *)view NS_SWIFT_NAME(showProgress(in:));
- (void)showProgressBarInView:(nullable UIView *)view NS_SWIFT_NAME(showProgressBar(in:));
- (void)showColorfulProgressBarInView:(nullable UIView *)view NS_SWIFT_NAME(showColorfulProgressBar(in:));
- (void)showTextInView:(nullable UIView *)view NS_SWIFT_NAME(showText(in:));
- (void)showNormalInView:(nullable UIView *)view NS_SWIFT_NAME(showNormal(in:));
- (void)showErrorInView:(nullable UIView *)view NS_SWIFT_NAME(showError(in:));
- (void)showSuccessInView:(nullable UIView *)view NS_SWIFT_NAME(showSuccess(in:));

- (void)showProgressInView:(nullable UIView *)view
                      text:(nullable NSString *)text
                    detail:(nullable NSString *)detail
             configuration:(nullable void(^)(AXPracticalHUD * _Nullable HUD))configuration
NS_SWIFT_NAME(showProgress(in:text:detail:configuration:));
- (void)showProgressBarInView:(nullable UIView *)view
                         text:(nullable NSString *)text
                       detail:(nullable NSString *)detail
                configuration:(nullable void(^)(AXPracticalHUD * _Nullable HUD))configuration
NS_SWIFT_NAME(showProgressBar(in:text:detail:configuration:));
- (void)showColorfulProgressBarInView:(nullable UIView *)view
                                 text:(nullable NSString *)text
                               detail:(nullable NSString *)detail
                        configuration:(nullable void(^)(AXPracticalHUD * _Nullable HUD))configuration
NS_SWIFT_NAME(showColorfulProgressBar(in:text:detail:configuration:));
- (void)showTextInView:(nullable UIView *)view
                  text:(nullable NSString *)text
                detail:(nullable NSString *)detail
         configuration:(nullable void(^)(AXPracticalHUD * _Nullable HUD))configuration
NS_SWIFT_NAME(showText(in:text:detail:configuration:));
- (void)showNormalInView:(nullable UIView *)view
                    text:(nullable NSString *)text
                  detail:(nullable NSString *)detail
           configuration:(nullable void(^)(AXPracticalHUD * _Nullable HUD))configuration
NS_SWIFT_NAME(showNormal(in:text:detail:configuration:));
- (void)showErrorInView:(nullable UIView *)view
                   text:(nullable NSString *)text
                 detail:(nullable NSString *)detail
          configuration:(nullable void(^)(AXPracticalHUD * _Nullable HUD))configuration
NS_SWIFT_NAME(showError(in:text:detail:configuration:));
- (void)showSuccessInView:(nullable UIView *)view
                     text:(nullable NSString *)text
                   detail:(nullable NSString *)detail
            configuration:(nullable void(^)(AXPracticalHUD * _Nullable HUD))configuration
NS_SWIFT_NAME(showSuccess(in:text:detail:configuration:));
@end

@interface AXPracticalHUD(Convenence)
+ (nullable instancetype)showHUDInView:(nullable UIView *)view animated:(BOOL)animated NS_SWIFT_NAME(showHud(in:animated:));
+ (BOOL)hideHUDInView:(nullable UIView *)view animated:(BOOL)animated NS_SWIFT_NAME(hideHud(in:animated:));
+ (NSInteger)hideAllHUDsInView:(nullable UIView *)view animated:(BOOL)animated NS_SWIFT_NAME(hideAllHuds(in:animated:));
+ (nullable instancetype)HUDInView:(nullable UIView *)view NS_SWIFT_NAME(hud(in:));
+ (nonnull NSArray *)HUDsInView:(nullable UIView *)view NS_SWIFT_NAME(huds(in:));
@end

NS_SWIFT_NAME(PracticalHUDDelegate) @protocol AXPracticalHUDDelegate <NSObject>
@optional
- (void)HUDWillShow:(nonnull AXPracticalHUD *)HUD;
- (void)HUDDidHidden:(nonnull AXPracticalHUD *)HUD;
@end


text:
package org.takes.servlet;

import com.jcabi.aspects.Tv;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import javax.servlet.http.HttpServletRequest;
import org.takes.Request;

/**
 * Request from {@link HttpServletRequest}.
 *
 * @since 2.0
 */
final class RqFrom implements Request {
    /**
     * Servlet request.
     */
    private final HttpServletRequest sreq;

    /**
     * Ctor.
     * @param request Servlet request
     */
    RqFrom(final HttpServletRequest request) {
        this.sreq = request;
    }

    @Override
    public Iterable<String> head() {
        final Collection<String> head = new LinkedList<>();
        head.add(new HttpHead(this.sreq).toString());
        final Collection<String> names = Collections.list(
            this.sreq.getHeaderNames()
        );
        if (!names.stream().anyMatch("host"::equalsIgnoreCase)) {
            head.add(new HttpHost(this.sreq).toString());
        }
        names.forEach(
            header -> head.add(
                String.format(
                    "%s: %s",
                    header,
                    this.sreq.getHeader(header)
                )
            )
        );
        head.add(
            String.format(
                "X-Takes-LocalAddress: %s",
                this.sreq.getLocalAddr()
            )
        );
        head.add(
            String.format(
                "X-Takes-RemoteAddress: %s",
                this.sreq.getRemoteAddr()
            )
        );
        return head;
    }

    @Override
    public InputStream body() throws IOException {
        return this.sreq.getInputStream();
    }

    /**
     * Http request first line: method, uri, version.
     * @since 2.0
     */
    private static final class HttpHead {
        /**
         * Servlet request.
         */
        private final HttpServletRequest req;

        /**
         * Ctor.
         * @param request Servlet request
         */
        HttpHead(final HttpServletRequest request) {
            this.req = request;
        }

        @Override
        public String toString() {
            final StringBuilder bld = new StringBuilder(Tv.TWENTY)
                .append(this.req.getMethod())
                .append(' ');
            final String uri = this.req.getRequestURI();
            if (uri == null) {
                bld.append('/');
            } else {
                bld.append(uri);
            }
            final String query = this.req.getQueryString();
            if (query != null) {
                bld.append('?').append(query);
            }
            return bld.toString();
        }
    }

    /**
     * Host header line from request.
     * @since 2.0
     */
    private static final class HttpHost {
        /**
         * Default http port.
         */
        private static final int PORT_DEFAULT = 80;

        /**
         * Servlet request.
         */
        private final HttpServletRequest req;

        /**
         * Ctor.
         * @param request Servlet request.
         */
        private HttpHost(final HttpServletRequest request) {
            this.req = request;
        }

        @Override
        public String toString() {
            final StringBuilder bld = new StringBuilder(Tv.HUNDRED);
            bld.append("Host: ").append(this.req.getServerName());
            final int port = this.req.getServerPort();
            if (port != HttpHost.PORT_DEFAULT) {
                bld.append(':').append(port);
            }
            return bld.toString();
        }
    }
}


text:
package com.hyphenate.helpdesk.easeui.provider;

import android.widget.BaseAdapter;

import com.hyphenate.chat.Message;
import com.hyphenate.helpdesk.easeui.widget.chatrow.ChatRow;

/**
 * 自定义chat row提供者
 */
public interface CustomChatRowProvider {
    /**
     * 获取多少种类型的自定义chatrow
     * 注意,每一种chatrow至少有两种type:发送type和接收type
     * @return
     */
    int getCustomChatRowTypeCount();

    /**
     * 获取chatrow type,必须大于0, 从1开始有序排列
     * @return
     */
    int getCustomChatRowType(Message message);

    /**
     * 根据给定message返回chat row
     * @return
     */
    ChatRow getCustomChatRow(Message message, int position, BaseAdapter adapter);
}


text:
package io.lettuce.core.pubsub;

import static org.assertj.core.api.Assertions.assertThat;

import java.nio.ByteBuffer;
import java.util.concurrent.atomic.AtomicInteger;

import org.junit.jupiter.api.Test;

import io.lettuce.core.ByteBufferCodec;
import io.lettuce.core.ClientOptions;
import io.lettuce.core.codec.ByteArrayCodec;
import io.lettuce.core.codec.RedisCodec;
import io.lettuce.core.codec.StringCodec;
import io.lettuce.test.resource.TestClientResources;

/**
 * Unit tests for {@link PubSubEndpoint}.
 *
 * @author Mark Paluch
 */
class PubSubEndpointUnitTests {

    @Test
    void shouldRetainUniqueChannelNames() {

        PubSubEndpoint<String, String> sut = new PubSubEndpoint<>(ClientOptions.create(), TestClientResources.get());

        sut.notifyMessage(createMessage("subscribe", "channel1", StringCodec.UTF8));
        sut.notifyMessage(createMessage("subscribe", "channel1", StringCodec.UTF8));
        sut.notifyMessage(createMessage("subscribe", "channel1", StringCodec.UTF8));
        sut.notifyMessage(createMessage("subscribe", "channel2", StringCodec.UTF8));

        assertThat(sut.getChannels()).hasSize(2).containsOnly("channel1", "channel2");
    }

    @Test
    void shouldRetainUniqueBinaryChannelNames() {

        PubSubEndpoint<byte[], byte[]> sut = new PubSubEndpoint<>(ClientOptions.create(), TestClientResources.get());

        sut.notifyMessage(createMessage("subscribe", "channel1", ByteArrayCodec.INSTANCE));
        sut.notifyMessage(createMessage("subscribe", "channel1", ByteArrayCodec.INSTANCE));
        sut.notifyMessage(createMessage("subscribe", "channel1", ByteArrayCodec.INSTANCE));
        sut.notifyMessage(createMessage("subscribe", "channel2", ByteArrayCodec.INSTANCE));

        assertThat(sut.getChannels()).hasSize(2);
    }

    @Test
    void shouldRetainUniqueByteBufferChannelNames() {

        PubSubEndpoint<ByteBuffer, ByteBuffer> sut = new PubSubEndpoint<>(ClientOptions.create(), TestClientResources.get());

        sut.notifyMessage(createMessage("subscribe", "channel1", new ByteBufferCodec()));
        sut.notifyMessage(createMessage("subscribe", "channel1", new ByteBufferCodec()));
        sut.notifyMessage(createMessage("subscribe", "channel1", new ByteBufferCodec()));
        sut.notifyMessage(createMessage("subscribe", "channel2", new ByteBufferCodec()));

        assertThat(sut.getChannels()).hasSize(2).containsOnly(ByteBuffer.wrap("channel1".getBytes()),
                ByteBuffer.wrap("channel2".getBytes()));
    }

    @Test
    void addsAndRemovesChannels() {

        PubSubEndpoint<byte[], byte[]> sut = new PubSubEndpoint<>(ClientOptions.create(), TestClientResources.get());

        sut.notifyMessage(createMessage("subscribe", "channel1", ByteArrayCodec.INSTANCE));
        sut.notifyMessage(createMessage("unsubscribe", "channel1", ByteArrayCodec.INSTANCE));

        assertThat(sut.getChannels()).isEmpty();
    }

    @Test
    void listenerNotificationShouldFailGracefully() {

        PubSubEndpoint<byte[], byte[]> sut = new PubSubEndpoint<>(ClientOptions.create(), TestClientResources.get());

        AtomicInteger notified = new AtomicInteger();

        sut.addListener(new RedisPubSubAdapter<byte[], byte[]>() {
            @Override
            public void message(byte[] channel, byte[] message) {

                notified.incrementAndGet();
                throw new UnsupportedOperationException();
            }
        });

        sut.addListener(new RedisPubSubAdapter<byte[], byte[]>() {
            @Override
            public void message(byte[] channel, byte[] message) {
                notified.incrementAndGet();
            }
        });

        sut.notifyMessage(createMessage("message", "channel1", ByteArrayCodec.INSTANCE));

        assertThat(notified).hasValue(1);
    }

    private static <K, V> PubSubOutput<K, V> createMessage(String action, String channel, RedisCodec<K, V> codec) {

        PubSubOutput<K, V> output = new PubSubOutput<>(codec);

        output.set(ByteBuffer.wrap(action.getBytes()));
        output.set(ByteBuffer.wrap(channel.getBytes()));

        return output;
    }
}


text:
typedef boost::system::error_code           ErrorCode;

typedef boost::asio::streambuf              StreamBufType;
typedef boost::asio::ip::address            AddressType;
typedef boost::asio::ip::tcp                TcpProtocolType;
typedef boost::asio::ip::tcp::endpoint      EndpointType;
typedef boost::asio::ip::tcp::socket        SocketType;
typedef boost::asio::ip::tcp::acceptor      AcceptorType;
typedef boost::asio::io_service             IOServiceType;

typedef SmartPtr<SocketType>                SocketPtr;

#endif //__ASIO_TYPE_H__


text:
About
=====

This is a dead simple smtp proxy server for quickly getting mails and
sending it in asynchronous mode with external smtp server.

Requirements
============

Python 3.6+, compiled with SSL support, is required.

Installation
============

.. code-block:: bash

  $ git clone https://github.com/ak04nv/smtp-proxy.git /srv/aiosmtpd
  $ cd /srv/aiosmtpd
  $ virtualenv -p python3 .venv
  $ source .venv/bin/activate
  $ pip install -r requirements.txt
  $ chown -R www-data:www-data .

Create `config.ini` file and fill it like content below

.. code-block:: ini

  SERVER = smtp.gmail.com
  PORT = 587
  USERNAME = my_mail@gmail.com
  PASSWORD = my_strong_password

Activation
==========

.. code-block:: bash

  $ cp smtpd.service /etc/systemd/system
  $ cd /etc/systemd/system
  $ systemd enable smtpd.service
  $ systemd start smtpd.service

Service binds on localhost and 1025 port by default. You can change it in ``smtpd.service`` file in ``ExecStart`` param.

Finally
=======

Script was successfully tested on Ubuntu 16.04 with actual updates. Use
this command for seeing logs.

.. code-block:: bash

  $ journalctl -u smtpd.service

License
=======

MIT License


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const webpack = require("webpack");
const memoryFS = require("memory-fs");
const path = require("path");
const TypescriptConfigParser_1 = require("../TypescriptConfigParser");
const ava_1 = require("ava");
const LoaderPaths_1 = require("./LoaderPaths");
const root = process.cwd();
const fixtures = path.join(root, 'fixtures', 'CoreTypeScriptLoader');
const tsconfigJson = {
    compilerOptions: {
        "target": "ES5",
        "module": "ESNext",
        "strict": true,
        "noImplicitAny": false,
        "noImplicitReturns": true,
        "noFallthroughCasesInSwitch": true,
        "moduleResolution": "node",
        "allowSyntheticDefaultImports": true,
        "forceConsistentCasingInFileNames": true,
        "skipLibCheck": true,
    }
};
const tsconfig = TypescriptConfigParser_1.parseTypescriptConfig(fixtures, tsconfigJson);
async function compileAsync(entry) {
    const compiler = webpack({
        context: fixtures,
        entry: [entry],
        output: {
            filename: 'bundle.js',
            path: fixtures
        },
        module: {
            rules: [{
                    test: /\.tsx?$/,
                    use: [{
                            loader: LoaderPaths_1.LoaderPaths.typescript,
                            options: {
                                compilerOptions: tsconfig.options
                            }
                        }]
                }]
        },
        resolve: {
            extensions: ['.ts', '.tsx', '.js', '.jsx']
        },
        mode: 'development',
    });
    compiler.outputFileSystem = new memoryFS();
    return await new Promise((ok, reject) => {
        compiler.run((err, stats) => {
            if (err) {
                reject(err);
            }
            ok(stats);
        });
    });
}
ava_1.default('Core TypeScript Loader: ES5', async (t) => {
    const entry = path.join(fixtures, 'index.ts');
    const stats = await compileAsync(entry);
    if (!stats) {
        t.fail('webpack stats is undefined!');
        return;
    }
    const o = stats.toJson({
        source: true,
        modules: true
    });
    if (o.modules) {
        let result = o.modules.filter(Q => Q.name === './index.ts')[0].source;
        if (result && typeof result === 'string') {
            result = result.replace(/\r/g, '');
        }
        t.is(result, '"use strict";\nvar foo = function (bar) {\n    return bar.length;\n};\nvar x = foo(\'abcd\');\n');
    }
    else {
        t.fail('webpack stats.toJson().modules is undefined!');
    }
});


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
  <title>Bichromate Test History Report Directory</title>

  <link rel="stylesheet" href="reports.css">

</head>

<body>

</body>
</html>


text:
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.model;

import com.intellij.openapi.util.Key;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.util.ObjectUtils;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
 * Helper methods to work with {@link ModelBranch} API
 */
public class ModelBranchUtil {
  private ModelBranchUtil() {}

  /**
   * @param context context element that may belong to the branch
   * @param element element to get the copy in the same branch as context
   * @param <T> type of the element
   * @return a copy of element that belongs to the same branch as context.
   * May return input element if it already belongs to the same branch or if context doesn't belong to any branch
   * @throws IllegalArgumentException if element and context already belong to different branches
   */
  public static <T extends PsiElement> @NotNull T obtainCopyFromTheSameBranch(@NotNull PsiElement context, @NotNull T element) {
    ModelBranch branch = ModelBranch.getPsiBranch(context);
    if (branch == null) return element;
    ModelBranch elementBranch = ModelBranch.getPsiBranch(element);
    if (elementBranch == branch) return element;
    if (elementBranch != null) {
      throw new IllegalArgumentException("Branch of supplied element differs from context branch");
    }
    return branch.obtainPsiCopy(element);
  }

  /**
   * @param context context file that may belong to the branch
   * @param file file to get the copy in the same branch as context
   * @return a copy of the file that belongs to the same branch as context.
   * May return input file if it already belongs to the same branch or if context doesn't belong to any branch
   * @throws IllegalArgumentException if file and context already belong to different branches
   */
  public static @NotNull VirtualFile obtainCopyFromTheSameBranch(@NotNull VirtualFile context, @NotNull VirtualFile file) {
    ModelBranch branch = ModelBranch.getFileBranch(context);
    if (branch == null) return file;
    ModelBranch fileBranch = ModelBranch.getFileBranch(file);
    if (fileBranch == branch) return file;
    if (fileBranch != null) {
      throw new IllegalArgumentException("Branch of supplied file differs from context branch");
    }
    return branch.findFileCopy(file);
  }

  /**
   * @param file virtual file to find the original for
   * @return original file if the supplied file belongs to the branch; supplied file otherwise.
   * May return null for non-null input if the file exists in branch only.
   */
  @Contract("null -> null")
  public static @Nullable VirtualFile findOriginalFile(@Nullable VirtualFile file) {
    if (file == null) return null;
    ModelBranch branch = ModelBranch.getFileBranch(file);
    return branch == null ? file : branch.findOriginalFile(file);
  }

  /**
   * @param psi PSI-element to find the original for
   * @return original PSI element if the supplied element belongs to the branch.
   * May return null for non-null input if the PSI element exists in branch only.
   */
  @Contract("null -> null")
  public static <T extends PsiElement> @Nullable T findOriginalPsi(@Nullable T psi) {
    if (psi == null) return null;
    ModelBranch branch = ModelBranch.getPsiBranch(psi);
    return branch == null ? psi : branch.findOriginalPsi(psi);
  }

  /**
   * Retrieves and removes user-data from element. If the element belongs to the branch
   * then performs the action on original element writing after branch merge.
   * Requires write action for physical elements and read action for branch elements.
   *
   * @param element element to obtain copyable user data from
   * @param key data key
   * @param <T> type of the data
   * @return found data; null if nothing
   */
  @Nullable
  public static <T> T getAndResetCopyableUserData(PsiElement element, Key<T> key) {
    ModelBranch branch = ModelBranch.getPsiBranch(element);
    PsiElement original = branch == null ? null : branch.findOriginalPsi(element);
    T data = ObjectUtils.notNull(original, element).getCopyableUserData(key);
    if (data != null) {
      if (original != null) {
        branch.runAfterMerge(() -> original.putCopyableUserData(key, null));
      } else {
        element.putCopyableUserData(key, null);
      }
    }
    return data;
  }

  /**
   * Checks that both files belong to the same branch (or both do not belong to any branch)
   *
   * @param left left file
   * @param right right file
   * @throws IllegalArgumentException if files belong to different branches or one of the file
   * belongs to the branch while other doesn't.
   */
  public static void checkSameBranch(@NotNull VirtualFile left, @NotNull VirtualFile right) {
    ModelBranch leftBranch = ModelBranch.getFileBranch(left);
    ModelBranch rightBranch = ModelBranch.getFileBranch(right);
    if (leftBranch != rightBranch) {
      throw new IllegalArgumentException("Files from different branches: " + leftBranch + " vs " + rightBranch);
    }
  }
}


text:
package de.lessvoid.nifty.elements.render;

import static org.easymock.classextension.EasyMock.expect;
import static org.easymock.classextension.EasyMock.isA;
import static org.easymock.classextension.EasyMock.replay;
import static org.easymock.classextension.EasyMock.verify;
import static org.easymock.classextension.EasyMock.createMock;
import junit.framework.TestCase;
import de.lessvoid.nifty.Nifty;
import de.lessvoid.nifty.layout.align.HorizontalAlign;
import de.lessvoid.nifty.layout.align.VerticalAlign;
import de.lessvoid.nifty.spi.render.RenderFont;

public class TextRendererTest extends TestCase {

  private RenderFont renderFont;

  public void setUp() {
    renderFont = createMock(RenderFont.class);
    expect(renderFont.getHeight()).andReturn(10).anyTimes();
    expect(renderFont.getWidth(isA(String.class))).andReturn(0).anyTimes();
    replay(renderFont);
  }

  public void testInit() {
    Nifty niftyMock = createMock(Nifty.class);
    expect(niftyMock.specialValuesReplace("a\nc")).andReturn("a\nc");
    replay(niftyMock);

    TextRenderer render = new TextRenderer(niftyMock, renderFont, "a\nc");
    assertEquals( 20, render.getTextHeight());
    assertEquals( 0, render.getTextWidth());

    verify(renderFont);
    verify(niftyMock);
  }

  public void testGetStartYWithVerticalAlignTop() {
    assertEquals(0, TextRenderer.getStartYWithVerticalAlign(100, 200, VerticalAlign.top));
  }

  public void testGetStartYWithVerticalAlignBottom() {
    assertEquals(100, TextRenderer.getStartYWithVerticalAlign(100, 200, VerticalAlign.bottom));
  }

  public void testGetStartYWithVerticalAlignCenter() {
    assertEquals(50, TextRenderer.getStartYWithVerticalAlign(100, 200, VerticalAlign.center));
  }

  public void testGetStartYWithVerticalAlignDefault() {
    assertEquals(0, TextRenderer.getStartYWithVerticalAlign(100, 200, null));
  }

  public void testGetStartXWithHorizontalAlignLeft() {
    assertEquals(0, TextRenderer.getStartXWithHorizontalAlign(100, 200, HorizontalAlign.left));
  }

  public void testGetStartXWithHorizontalAlignRight() {
    assertEquals(100, TextRenderer.getStartXWithHorizontalAlign(100, 200, HorizontalAlign.right));
  }

  public void testGetStartXWithHorizontalAlignCenter() {
    assertEquals(50, TextRenderer.getStartXWithHorizontalAlign(100, 200, HorizontalAlign.center));
  }

  public void testGetStartXWithHorizontalAlignDefault() {
    assertEquals(0, TextRenderer.getStartXWithHorizontalAlign(100, 200, null));
  }
}


text:
@implementation HighScoresControllerTest

#if USE_APPLICATION_UNIT_TEST     // all code under test is in the iPhone Application

- (void)testAppDelegate {

    id yourApplicationDelegate = [[UIApplication sharedApplication] delegate];
    STAssertNotNil(yourApplicationDelegate, @"UIApplication failed to find the AppDelegate");

}

#else                           // all code under test must be linked into the Unit Test bundle

- (void) setUp {
    controller = [[HighScoresController alloc] init];
}

- (void)testFormatHourWithZeroMinutes {

    STAssertEqualObjects([controller formatTimeLeft:3600], @"1:00:00", @"Incorrect format");

}

- (void)testFormatHourWithZeroHours {

    STAssertEqualObjects([controller formatTimeLeft:66], @"1:06", @"Incorrect format");

}

- (void)testFormatHourWithLessThan10Seconds {

    STAssertEqualObjects([controller formatTimeLeft:6], @":06", @"Incorrect format");

}

- (void) tearDown {
    [controller release];
}

#endif

@end


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="Splash" parent="@android:style/Theme.NoTitleBar.Fullscreen">
        <item name="android:windowBackground">@android:color/black</item>
        <item name="android:background">@drawable/splash_bitmap</item>
    </style>
</resources>


text:
enum FileType {
	JS,
	TS,
}

export default FileType;


text:
local runner = require('user_modules/script_runner')
local common = require("test_scripts/Defects/6_1/common_3139_3140_3142")

--[[ Test Configuration ]]
runner.testSettings.isSelfIncluded = false

--[[ Apps Configuration ]]
common.app.getParams(1).appHMIType = { "NAVIGATION" }
common.app.getParams(2).appHMIType = { "NAVIGATION" }

--[[ Local Functions ]]
local function stopStreaming(pAppId)
  common.hmi.getConnection():ExpectRequest("Navigation.StopAudioStream", { appID = common.app.getHMIId(pAppId)})
  :Do(function(_, data)
      common.log("Navigation.StopAudioStream for App " .. pAppId)
      common.hmi.getConnection():SendResponse(data.id, data.method, "SUCCESS", { })
    end)
end

local function startStreaming(pAppId, pServiceId)
  common.mobile.getSession(pAppId):StartService(pServiceId)
  :Do(function()
      common.mobile.getSession(pAppId):StartStreaming(pServiceId, common.streamFiles[pAppId], 40*1024)
      common.log("App " .. pAppId .." starts streaming ...")
      common.streamingStatus[pAppId] = true
    end)
  common.hmi.getConnection():ExpectRequest("Navigation.StartAudioStream", { appID = common.app.getHMIId(pAppId) })
    :Do(function(_, data)
      common.log("Navigation.StartAudioStream for App " .. pAppId)
      common.hmi.getConnection():SendResponse(data.id, data.method, "SUCCESS", { })
    end)
end

local function activateApp2()
  local cid = common.hmi.getConnection():SendRequest("SDL.ActivateApp", { appID = common.app.getHMIId(2) })
  common.hmi.getConnection():ExpectResponse(cid)
  common.mobile.getSession(2):ExpectNotification("OnHMIStatus",
    { hmiLevel = "FULL", audioStreamingState = "AUDIBLE" })
  :Do(function()
      stopStreaming(1, 10)
      startStreaming(2, 10)
    end)
  common.hmi.getConnection():ExpectNotification("Navigation.OnAudioDataStreaming",
    { available = false }, { available = true })
  :Times(2)
end

local function stopStreamingWONotification()
  common.stopStreaming(1)
  common.hmi.getConnection():ExpectNotification("Navigation.OnAudioDataStreaming"):Times(0)
  common.wait(5000)
end

local function stopStreamingWithNotification()
  common.stopStreaming(2)
  common.hmi.getConnection():ExpectNotification("Navigation.OnAudioDataStreaming", { available = false })
  common.wait(5000)
end

--[[ Scenario ]]
runner.Title("Preconditions")
runner.Step("Clean environment", common.preconditions, {{ StopStreamingTimeout = 3000, AudioDataStoppedTimeout = 3000 }})
runner.Step("Start SDL, HMI, connect Mobile, start Session", common.start)
runner.Step("Register App 1", common.registerApp, { 1 })
runner.Step("Register App 2", common.registerApp, { 2 })
runner.Step("Activate App 1", common.activateApp, { 1 })

runner.Title("Test")
runner.Step("App 1 start audio streaming", common.startStreaming, { 1, 10 })
runner.Step("App 1 deactivated", common.deactivateApp, { 1 })
runner.Step("App 2 activated", activateApp2)
runner.Step("App 1 stop audio streaming", stopStreamingWONotification)
runner.Step("App 2 stop audio streaming with notification", stopStreamingWithNotification)

runner.Title("Postconditions")
runner.Step("Stop SDL", common.postconditions)


text:
from datetime import timedelta
from os.path import abspath, dirname
from os import getenv

from django.core.exceptions import ImproperlyConfigured

from luna_django_commons.settings import BaseSettings
from luna_django_commons.settings.mixins import CelerySettings

class SettingsBase(CelerySettings, BaseSettings):
    SETTINGS_DIR = abspath(dirname(__file__))

    PROJECT_BASENAME = 'pype'
    DEPLOYMENT_BASENAME = 'pype'

    # Required by cbs
    PROJECT_NAME = 'pype'

    def SECRET_KEY(self):
        return self.get_secret('SECRET_KEY')

    ALLOWED_HOSTS = [
        '127.0.0.1'
    ]

    TIME_ZONE = 'UTC'

    LANGUAGE_CODE = 'en'
    LANGUAGES = (('en', 'English'), )

    DEFAULT_FROM_EMAIL = 'noreply@pypeapp.com'

    SITE_ID = 1
    DOMAIN_NAME = 'dev.pypeapp.com'
    SITE_NAME = 'Pype (dev)'

    def STATICFILES_DIRS(self):
        return (
            self.root('static'),
            self.root('bower_components'),
        )

    #LOGIN_REDIRECT_URL = '/home/'
    LOGIN_REDIRECT_URL = '/virtualfolder/'
    LOGIN_URL = '/login/'

    MIDDLEWARE_CLASSES = (
        # Debreach content-length extension
        'debreach.middleware.RandomCommentMiddleware',

        # Django debug toolbar
        # 'debug_toolbar.middleware.DebugToolbarMiddleware',
        # 'silk.middleware.SilkyMiddleware',

        # Django-statsd
        'django_statsd.middleware.GraphiteRequestTimingMiddleware',
        'django_statsd.middleware.GraphiteMiddleware',

        # Debreach CSRF-token protection
        'debreach.middleware.CSRFCryptMiddleware',

        'django.middleware.common.CommonMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',

        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',

        'django.middleware.locale.LocaleMiddleware',
    )

    @property
    def INSTALLED_APPS(self):
        installed_apps = super(SettingsBase, self).INSTALLED_APPS

        installed_apps += (
            'rest_framework',
            'rest_framework.authtoken',
            'djoser',
            'djng',
            'ui',
            'api',
            'luna_websockets',
        )

        return installed_apps

    # ----------------------------------------------------------------------------------------------------------------------
    # Rest framework settings
    REST_FRAMEWORK = {
        'PAGINATE_BY': 10,
        'DEFAULT_AUTHENTICATION_CLASSES': (
            # 'rest_framework.authentication.BasicAuthentication',
            'rest_framework.authentication.TokenAuthentication',

            # Session authentication is used in production
            'rest_framework.authentication.SessionAuthentication',
        ),
        'NON_FIELD_ERRORS_KEY': '__all__',
    }

    # Celery
    REDIS_DB_ID = '8'
    BROKER_URL = 'redis://localhost:6379/' + REDIS_DB_ID

    CELERYBEAT_SCHEDULE = {
    }

    # Intercom settings
    INTERCOM_APP_ID = "ems6rg8l"

    # Google Drive App Credentials
    def GOOGLE_DRIVE_CLIENT_ID(self):
        return None

    def GOOGLE_DRIVE_CLIENT_SECRET(self):
        return None

    def GOOGLE_DRIVE_CLIENT_URI(self):
        return None

    # Dropbox credentials
    def DROPBOX_APP_KEY(self):
        return None

    def DROPBOX_APP_SECRET(self):
        return None

    def DROPBOX_CLIENT_REDIRECT_URI(self):
        return None

    def JS_CONFIG(self):
        return {
            'DEBUG': self.DEBUG,
            'INTERCOM_APP_ID': None,
            'ENABLE_REGISTER': True,
            'WS_SERVER': 'http://127.0.0.1:22000/ws',
        }

    # DJOSER
    DJOSER = {
        'SET_PASSWORD_RETYPE': True,
        'PASSWORD_RESET_CONFIRM_URL': 'home/#/password/reset/{token}/{uid}/',
        'PASSWORD_RESET_CONFIRM_RETYPE': True,
    }

    VF_HOST = getenv('VF_HOST', 'http://10.63.90.75:80')


text:
/**
 * eslint no-console: ["error", { allow: ["log"] }]
 * @jest-environment jsdom
 */

import './bids.spec.js'