text:
import * as zrUtil from 'zrender/src/core/util';
import * as graphic from '../../util/graphic';
import * as textContain from 'zrender/src/contain/text';
import * as formatUtil from '../../util/format';
import * as matrix from 'zrender/src/core/matrix';
import * as axisHelper from '../../coord/axisHelper';
import AxisBuilder from '../axis/AxisBuilder';
import Axis from '../../coord/Axis';
import {
    ScaleDataValue, CallbackDataParams, ZRTextAlign, ZRTextVerticalAlign, ZRColor, CommonAxisPointerOption, ColorString
} from '../../util/types';
import { VectorArray } from 'zrender/src/core/vector';
import GlobalModel from '../../model/Global';
import IntervalScale from '../../scale/Interval';
import Axis2D from '../../coord/cartesian/Axis2D';
import { AxisPointerElementOptions } from './BaseAxisPointer';
import { AxisBaseModel } from '../../coord/AxisBaseModel';
import ExtensionAPI from '../../core/ExtensionAPI';
import CartesianAxisModel from '../../coord/cartesian/AxisModel';
import Model from '../../model/Model';
import { PathStyleProps } from 'zrender/src/graphic/Path';
import { createTextStyle } from '../../label/labelStyle';

interface LayoutInfo {
    position: VectorArray
    rotation: number
    labelOffset?: number
    /**
     * 1 | -1
     */
    labelDirection?: number
    labelMargin?: number
}

// Not use top level axisPointer model
type AxisPointerModel = Model<CommonAxisPointerOption>;

export function buildElStyle(axisPointerModel: AxisPointerModel) {
    const axisPointerType = axisPointerModel.get('type');
    const styleModel = axisPointerModel.getModel(axisPointerType + 'Style' as 'lineStyle' | 'shadowStyle');
    let style: PathStyleProps;
    if (axisPointerType === 'line') {
        style = styleModel.getLineStyle();
        style.fill = null;
    }
    else if (axisPointerType === 'shadow') {
        style = styleModel.getAreaStyle();
        style.stroke = null;
    }
    return style;
}

/**
 * @param {Function} labelPos {align, verticalAlign, position}
 */
export function buildLabelElOption(
    elOption: AxisPointerElementOptions,
    axisModel: AxisBaseModel,
    axisPointerModel: AxisPointerModel,
    api: ExtensionAPI,
    labelPos: {
        align?: ZRTextAlign
        verticalAlign?: ZRTextVerticalAlign
        position: number[]
    }
) {
    const value = axisPointerModel.get('value');
    const text = getValueLabel(
        value, axisModel.axis, axisModel.ecModel,
        axisPointerModel.get('seriesDataIndices'),
        {
            precision: axisPointerModel.get(['label', 'precision']),
            formatter: axisPointerModel.get(['label', 'formatter'])
        }
    );
    const labelModel = axisPointerModel.getModel('label');
    const paddings = formatUtil.normalizeCssArray(labelModel.get('padding') || 0);

    const font = labelModel.getFont();
    const textRect = textContain.getBoundingRect(text, font);

    const position = labelPos.position;
    const width = textRect.width + paddings[1] + paddings[3];
    const height = textRect.height + paddings[0] + paddings[2];

    // Adjust by align.
    const align = labelPos.align;
    align === 'right' && (position[0] -= width);
    align === 'center' && (position[0] -= width / 2);
    const verticalAlign = labelPos.verticalAlign;
    verticalAlign === 'bottom' && (position[1] -= height);
    verticalAlign === 'middle' && (position[1] -= height / 2);

    // Not overflow ec container
    confineInContainer(position, width, height, api);

    let bgColor = labelModel.get('backgroundColor') as ZRColor;
    if (!bgColor || bgColor === 'auto') {
        bgColor = axisModel.get(['axisLine', 'lineStyle', 'color']);
    }

    elOption.label = {
        // shape: {x: 0, y: 0, width: width, height: height, r: labelModel.get('borderRadius')},
        x: position[0],
        y: position[1],
        style: createTextStyle(labelModel, {
            text: text,
            font: font,
            fill: labelModel.getTextColor(),
            padding: paddings,
            backgroundColor: bgColor as ColorString
        }),
        // Lable should be over axisPointer.
        z2: 10
    };
}

// Do not overflow ec container
function confineInContainer(position: number[], width: number, height: number, api: ExtensionAPI) {
    const viewWidth = api.getWidth();
    const viewHeight = api.getHeight();
    position[0] = Math.min(position[0] + width, viewWidth) - width;
    position[1] = Math.min(position[1] + height, viewHeight) - height;
    position[0] = Math.max(position[0], 0);
    position[1] = Math.max(position[1], 0);
}

export function getValueLabel(
    value: ScaleDataValue,
    axis: Axis,
    ecModel: GlobalModel,
    seriesDataIndices: CommonAxisPointerOption['seriesDataIndices'],
    opt?: {
        precision?: number | 'auto'
        formatter?: CommonAxisPointerOption['label']['formatter']
    }
): string {
    value = axis.scale.parse(value);
    let text = (axis.scale as IntervalScale).getLabel(
        {
            value
        }, {
            // If `precision` is set, width can be fixed (like '12.00500'), which
            // helps to debounce when when moving label.
            precision: opt.precision
        }
    );
    const formatter = opt.formatter;

    if (formatter) {
        const params = {
            value: axisHelper.getAxisRawValue(axis, {value}),
            axisDimension: axis.dim,
            axisIndex: (axis as Axis2D).index,  // Only Carteian Axis has index
            seriesData: [] as CallbackDataParams[]
        };
        zrUtil.each(seriesDataIndices, function (idxItem) {
            const series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
            const dataIndex = idxItem.dataIndexInside;
            const dataParams = series && series.getDataParams(dataIndex);
            dataParams && params.seriesData.push(dataParams);
        });

        if (zrUtil.isString(formatter)) {
            text = formatter.replace('{value}', text);
        }
        else if (zrUtil.isFunction(formatter)) {
            text = formatter(params);
        }
    }

    return text;
}

export function getTransformedPosition(
    axis: Axis,
    value: ScaleDataValue,
    layoutInfo: LayoutInfo
): number[] {
    const transform = matrix.create();
    matrix.rotate(transform, transform, layoutInfo.rotation);
    matrix.translate(transform, transform, layoutInfo.position);

    return graphic.applyTransform([
        axis.dataToCoord(value),
        (layoutInfo.labelOffset || 0)
            + (layoutInfo.labelDirection || 1) * (layoutInfo.labelMargin || 0)
    ], transform);
}

export function buildCartesianSingleLabelElOption(
    value: ScaleDataValue,
    elOption: AxisPointerElementOptions,
    layoutInfo: LayoutInfo,
    axisModel: CartesianAxisModel,
    axisPointerModel: AxisPointerModel,
    api: ExtensionAPI
) {
    // @ts-ignore
    const textLayout = AxisBuilder.innerTextLayout(
        layoutInfo.rotation, 0, layoutInfo.labelDirection
    );
    layoutInfo.labelMargin = axisPointerModel.get(['label', 'margin']);
    buildLabelElOption(elOption, axisModel, axisPointerModel, api, {
        position: getTransformedPosition(axisModel.axis, value, layoutInfo),
        align: textLayout.textAlign,
        verticalAlign: textLayout.textVerticalAlign
    });
}

export function makeLineShape(p1: number[], p2: number[], xDimIndex?: number) {
    xDimIndex = xDimIndex || 0;
    return {
        x1: p1[xDimIndex],
        y1: p1[1 - xDimIndex],
        x2: p2[xDimIndex],
        y2: p2[1 - xDimIndex]
    };
}

export function makeRectShape(xy: number[], wh: number[], xDimIndex?: number) {
    xDimIndex = xDimIndex || 0;
    return {
        x: xy[xDimIndex],
        y: xy[1 - xDimIndex],
        width: wh[xDimIndex],
        height: wh[1 - xDimIndex]
    };
}

export function makeSectorShape(
    cx: number,
    cy: number,
    r0: number,
    r: number,
    startAngle: number,
    endAngle: number
) {
    return {
        cx: cx,
        cy: cy,
        r0: r0,
        r: r,
        startAngle: startAngle,
        endAngle: endAngle,
        clockwise: true
    };
}


text:
void BuddyList::addBuddy(const std::string& name, const std::string& buddy) {
    if (!isBuddy(name, buddy)) {
        _buddies.insert({ name, buddy });
    }
}

void BuddyList::removeBuddy(const std::string& name, const std::string& buddy) {
    auto iterator = _buddies.lower_bound(name);
    auto end = _buddies.upper_bound(name);

    for (; iterator != end; ++iterator) {
        if (buddy == iterator->second) {
            _buddies.erase(iterator);
            break;
        }
    }
}

bool BuddyList::isBuddy(const std::string& name, const std::string& buddy) const {
    auto range = _buddies.equal_range(name);
    auto iterator = range.first;
    auto end = range.second;

    for (; iterator != end; ++iterator) {
        if (buddy == iterator->second) {
            return true;
        }
    }

    return false;
}

std::list<std::string> BuddyList::getBuddies(const std::string& name) const {
    auto range = _buddies.equal_range(name);
    auto iterator = range.first;
    auto end = range.second;

    std::list<std::string> buddies;
    for (; iterator != end; ++iterator) {
        buddies.push_back(iterator->second);
    }

    return buddies;
}

redpajama_set_name: RedPajamaGithub


text:
using System.Collections.Generic;

namespace MK6.AutomatedTesting.Runner
{
    public static class Extensions
    {
        public static void AddRange<T>(this IList<T> list, IEnumerable<T> newItems)
        {
            foreach (var newItem in newItems)
            {
                list.Add(newItem);
            }
        }

        public static IDictionary<TKey, TValue> AddRange<TKey, TValue>(
            this IDictionary<TKey, TValue> dictionary,
            IEnumerable<KeyValuePair<TKey, TValue>> keyValuePairs)
        {
            foreach (var keyValuePair in keyValuePairs)
            {
                dictionary.Add(keyValuePair.Key, keyValuePair.Value);
            }

            return dictionary;
        }

        public static IDictionary<TKey, TValue> Add<TKey, TValue>(
            this IDictionary<TKey, TValue> dictionary,
            KeyValuePair<TKey, TValue> keyValue)
        {
            dictionary.Add(keyValue);
            return dictionary;
        }
    }
}


text:
class EditionForumCategory < ActiveRecord::Migration
  def change
    add_column :editions, :projects_forum_category, :string
  end
end


text:
<?php

namespace PDepend\Source\AST;

/**
 * Test case for the {@link \PDepend\Source\AST\ASTBreakStatement} class.
 *
 * @copyright 2008-2013 Manuel Pichler. All rights reserved.
 * @license http://www.opensource.org/licenses/bsd-license.php BSD License
 *
 * @covers \PDepend\Source\Language\PHP\AbstractPHPParser
 * @covers \PDepend\Source\AST\ASTBreakStatement
 * @group unittest
 */
class ASTBreakStatementTest extends \PDepend\Source\AST\ASTNodeTest
{
    /**
     * Tests the start line value.
     *
     * @return void
     */
    public function testBreakStatementHasExpectedStartLine()
    {
        $stmt = $this->_getFirstBreakStatementInFunction(__METHOD__);
        $this->assertEquals(5, $stmt->getStartLine());
    }

    /**
     * Tests the start column value.
     *
     * @return void
     */
    public function testBreakStatementHasExpectedStartColumn()
    {
        $stmt = $this->_getFirstBreakStatementInFunction(__METHOD__);
        $this->assertEquals(9, $stmt->getStartColumn());
    }

    /**
     * Tests the end line value.
     *
     * @return void
     */
    public function testBreakStatementHasExpectedEndLine()
    {
        $stmt = $this->_getFirstBreakStatementInFunction(__METHOD__);
        $this->assertEquals(7, $stmt->getEndLine());
    }

    /**
     * Tests the end column value.
     *
     * @return void
     */
    public function testBreakStatementHasExpectedEndColumn()
    {
        $stmt = $this->_getFirstBreakStatementInFunction(__METHOD__);
        $this->assertEquals(17, $stmt->getEndColumn());
    }

    /**
     * Returns a node instance for the currently executed test case.
     *
     * @param string $testCase Name of the calling test case.
     *
     * @return \PDepend\Source\AST\ASTBreakStatement
     */
    private function _getFirstBreakStatementInFunction($testCase)
    {
        return $this->getFirstNodeOfTypeInFunction(
            $testCase,
            'PDepend\\Source\\AST\\ASTBreakStatement'
        );
    }
}


text:
#ifndef SkiaImageFilterBuilder_h
#define SkiaImageFilterBuilder_h

#include "platform/PlatformExport.h"
#include "platform/geometry/FloatSize.h"
#include "platform/graphics/ColorSpace.h"
#include "platform/graphics/CompositorFilterOperations.h"
#include "platform/heap/Handle.h"

class SkImageFilter;

namespace blink {
class AffineTransform;
class FilterEffect;
class FilterOperations;

class PLATFORM_EXPORT SkiaImageFilterBuilder {
    STACK_ALLOCATED();
public:
    ~SkiaImageFilterBuilder();

    PassRefPtr<SkImageFilter> build(FilterEffect*, ColorSpace, bool requiresPMColorValidation = true);
    void buildFilterOperations(const FilterOperations&, CompositorFilterOperations*);
    PassRefPtr<SkImageFilter> buildTransform(const AffineTransform&, SkImageFilter* input);

    PassRefPtr<SkImageFilter> transformColorSpace(
        SkImageFilter* input, ColorSpace srcColorSpace, ColorSpace dstColorSpace);
};

} // namespace blink

#endif


text:
package com.hazelcast.map;

import com.hazelcast.config.Config;
import com.hazelcast.core.EntryEvent;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IMap;
import com.hazelcast.map.listener.EntryEvictedListener;
import com.hazelcast.map.listener.EntryExpiredListener;
import com.hazelcast.test.HazelcastParallelClassRunner;
import com.hazelcast.test.HazelcastTestSupport;
import com.hazelcast.test.TestHazelcastInstanceFactory;
import com.hazelcast.test.annotation.ParallelTest;
import com.hazelcast.test.annotation.QuickTest;
import com.hazelcast.util.RandomPicker;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

@RunWith(HazelcastParallelClassRunner.class)
@Category({QuickTest.class, ParallelTest.class})
public class ExpirationListenerTest extends HazelcastTestSupport {

    private static final int instanceCount = 3;

    private HazelcastInstance[] instances;
    private IMap<Integer, Integer> map;

    @Before
    public void init() {
        TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(instanceCount);
        Config config = new Config();
        instances = factory.newInstances(config);
        HazelcastInstance randomNode = instances[RandomPicker.getInt(instanceCount)];
        map = randomNode.getMap(randomMapName());
    }

    @Test
    public void testExpirationListener_notified_afterExpirationOfEntries() throws Exception {
        int numberOfPutOperations = 1000;
        CountDownLatch expirationEventArrivalCount = new CountDownLatch(numberOfPutOperations);

        map.addEntryListener(new ExpirationListener(expirationEventArrivalCount), true);

        for (int i = 0; i < numberOfPutOperations; i++) {
            map.put(i, i, 100, TimeUnit.MILLISECONDS);
        }

        // wait expiration of entries
        sleepAtLeastMillis(200);

        // trigger immediate fire of expiration events by touching them
        for (int i = 0; i < numberOfPutOperations; i++) {
            map.get(i);
        }

        assertOpenEventually(expirationEventArrivalCount);
    }

    @Test
    public void test_whenTTLisModified_ExpirationListenernotified_afterExpirationOfEntries() throws Exception {
        int numberOfPutOperations = 1000;
        CountDownLatch expirationEventArrivalCount = new CountDownLatch(numberOfPutOperations);

        map.addEntryListener(new ExpirationListener(expirationEventArrivalCount), true);

        for (int i = 0; i < numberOfPutOperations; i++) {
            map.put(i, i);
        }

        for (int i = 0; i < numberOfPutOperations; i++) {
            map.setTTL(i, 100, TimeUnit.MILLISECONDS);
        }

        // wait expiration of entries
        sleepAtLeastMillis(200);

        // trigger immediate fire of expiration events by touching them
        for (int i = 0; i < numberOfPutOperations; i++) {
            map.get(i);
        }

        assertOpenEventually(expirationEventArrivalCount);
    }

    private static class ExpirationListener implements EntryExpiredListener {

        private final CountDownLatch expirationEventCount;

        ExpirationListener(CountDownLatch expirationEventCount) {
            this.expirationEventCount = expirationEventCount;
        }

        @Override
        public void entryExpired(EntryEvent event) {
            expirationEventCount.countDown();
        }
    }

    @Test
    public void testExpirationAndEvictionListener_bothNotified_afterExpirationOfEntries() throws Exception {
        int numberOfPutOperations = 1000;
        CountDownLatch expirationEventCount = new CountDownLatch(numberOfPutOperations);
        CountDownLatch evictionEventCount = new CountDownLatch(numberOfPutOperations);

        map.addEntryListener(new ExpirationAndEvictionListener(expirationEventCount, evictionEventCount), true);

        for (int i = 0; i < numberOfPutOperations; i++) {
            map.put(i, i, 100, TimeUnit.MILLISECONDS);
        }

        // wait expiration of entries
        sleepAtLeastMillis(200);

        // trigger immediate fire of expiration events by touching them
        for (int i = 0; i < numberOfPutOperations; i++) {
            map.get(i);
        }

        assertOpenEventually(expirationEventCount);
        assertOpenEventually(evictionEventCount);
    }

    private static class ExpirationAndEvictionListener implements EntryExpiredListener, EntryEvictedListener {

        private final CountDownLatch expirationEventArrivalCount;
        private final CountDownLatch evictionEventArrivalCount;

        ExpirationAndEvictionListener(CountDownLatch expirationEventArrivalCount, CountDownLatch evictionEventArrivalCount) {
            this.expirationEventArrivalCount = expirationEventArrivalCount;
            this.evictionEventArrivalCount = evictionEventArrivalCount;
        }

        @Override
        public void entryExpired(EntryEvent event) {
            expirationEventArrivalCount.countDown();
        }

        @Override
        public void entryEvicted(EntryEvent event) {
            evictionEventArrivalCount.countDown();
        }
    }
}


text:
using System.Collections.Generic;
using System.Text.Json;
using Azure.Core;

namespace Azure.ResourceManager.CosmosDB.Models
{
    public partial class MetricDefinitionsListResult
    {
        internal static MetricDefinitionsListResult DeserializeMetricDefinitionsListResult(JsonElement element)
        {
            Optional<IReadOnlyList<MetricDefinition>> value = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("value"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    List<MetricDefinition> array = new List<MetricDefinition>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(MetricDefinition.DeserializeMetricDefinition(item));
                    }
                    value = array;
                    continue;
                }
            }
            return new MetricDefinitionsListResult(Optional.ToList(value));
        }
    }
}


text:
from __future__ import unicode_literals

from helium import Device, Configuration, DeviceConfiguration

def display_map(cls, client, uuid=False, include=None):
    def _trim_id(res):
        return res.id if uuid or client.uuid else res.short_id

    def _config(self):
        return _trim_id(self.configuration(use_included=True))

    def _device(self):
        return _trim_id(self.device(use_included=True))

    def _device_type(self):
        return self.device(use_included=True)._resource_type()

    def _loaded(self):
        return 'yes' if self.is_loaded else 'no'

    dict = super(DeviceConfiguration, cls).display_map(client, include=include)
    if include and Configuration in include:
        dict['config'] = _config
    if include and Device in include:
        dict['device'] = _device
        dict['type'] = _device_type

    dict['loaded'] = _loaded

    return dict

DeviceConfiguration.display_map = classmethod(display_map)


text:
<?php

use Indatus\Dispatcher\Scheduling\ScheduledCommand;
use Indatus\Dispatcher\Scheduling\Schedulable;
use Indatus\Dispatcher\Drivers\Cron\Scheduler;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;

class UpdateStatistics extends ScheduledCommand {

	/**
	 * The console command name.
	 *
	 * @var string
	 */
	protected $name = 'server:update';

	/**
	 * The console command description.
	 *
	 * @var string
	 */
	protected $description = 'Updates statistics of all servers';

	/**
	 * Create a new command instance.
	 *
	 * @return void
	 */
	public function __construct()
	{
		parent::__construct();
	}

	/**
	 * When a command should run
	 *
	 * @param Scheduler $scheduler
	 * @return \Indatus\Dispatcher\Scheduling\Schedulable
	 */
	public function schedule(Schedulable $scheduler)
	{
		return $scheduler->everyMinutes(60);
	}

	/**
	 * Execute the console command.
	 *
	 * @return mixed
	 */
	public function fire()
	{
		$games = Game::where('active', '=', 1)->get();
		foreach ($games as $game) {
			$statistic = new Statistic;
			$statistic->current_players = $game->server->sum("current_players");
			$statistic->max_players = $game->server->sum("max_players");
			$statistic->total_servers = $game->server->count();
			$statistic->game_id = $game->id;
			$statistic->save();
		}

		$date = new DateTime;
		$date->modify('-1 month');
		$formatted_date = $date->format('Y-m-d H:i:s');

		Statistic::where('created_at', "<", $formatted_date)->delete();
	}

	/**
	 * Get the console command arguments.
	 *
	 * @return array
	 */
	protected function getArguments()
	{
		return array(

		);
	}

	/**
	 * Get the console command options.
	 *
	 * @return array
	 */
	protected function getOptions()
	{
		return array(

		);
	}

}


text:
package com.epam.ta.reportportal.ws.converter.converters;

import com.epam.ta.reportportal.entity.Metadata;
import com.epam.ta.reportportal.entity.enums.ProjectType;
import com.epam.ta.reportportal.entity.project.Project;
import com.epam.ta.reportportal.entity.project.ProjectRole;
import com.epam.ta.reportportal.entity.user.ProjectUser;
import com.epam.ta.reportportal.entity.user.User;
import com.epam.ta.reportportal.entity.user.UserRole;
import com.epam.ta.reportportal.entity.user.UserType;
import com.epam.ta.reportportal.ws.model.activity.UserActivityResource;
import com.epam.ta.reportportal.ws.model.user.UserResource;
import com.google.common.collect.Sets;
import org.junit.jupiter.api.Test;

import java.util.HashMap;

import static org.assertj.core.api.Java6Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;

/**
 * @author Ihar Kahadouski
 */
class UserConverterTest {

	@Test
	void toResource() {
		final User user = getUser();
		final UserResource resource = UserConverter.TO_RESOURCE.apply(user);

		assertEquals(resource.getEmail(), user.getEmail());
		assertEquals(resource.getFullName(), user.getFullName());
		assertEquals(resource.getUserId(), user.getLogin());
		assertEquals(resource.getUserRole(), user.getRole().name());
		assertEquals(resource.getAccountType(), user.getUserType().name());
		assertEquals(resource.getPhotoId(), user.getAttachment());
		assertThat((HashMap<String, Object>) resource.getMetadata()).containsAllEntriesOf(getMetadata());
		assertThat(resource.getAssignedProjects()).containsKeys("project1", "project2");
	}

	@Test
	void toActivityResource() {
		final User user = getUser();
		final Long projectId = 2L;
		final UserActivityResource resource = UserConverter.TO_ACTIVITY_RESOURCE.apply(user, projectId);

		assertEquals(resource.getId(), user.getId());
		assertEquals(resource.getFullName(), user.getFullName());
		assertEquals(resource.getDefaultProjectId(), projectId);
	}

	private static User getUser() {
		final User user = new User();
		user.setLogin("login");
		user.setUserType(UserType.INTERNAL);
		user.setRole(UserRole.USER);
		user.setAttachment("attachmentId");
		user.setEmail("example@domain.com");
		user.setFullName("full name");
		user.setId(1L);
		user.setAttachmentThumbnail("thumbnailId");
		user.setExpired(false);
		final HashMap<String, Object> metadata = getMetadata();
		user.setMetadata(new Metadata(metadata));
		final Project project1 = new Project();
		project1.setName("project1");
		project1.setProjectType(ProjectType.INTERNAL);
		final ProjectUser projectUser1 = new ProjectUser().withProject(project1).withProjectRole(ProjectRole.MEMBER).withUser(user);
		final Project project2 = new Project();
		project2.setName("project2");
		project2.setProjectType(ProjectType.INTERNAL);
		final ProjectUser projectUser2 = new ProjectUser().withProject(project2)
				.withProjectRole(ProjectRole.PROJECT_MANAGER)
				.withUser(user);
		user.setProjects(Sets.newHashSet(projectUser1, projectUser2));
		return user;
	}

	private static HashMap<String, Object> getMetadata() {
		final HashMap<String, Object> metadata = new HashMap<>();
		metadata.put("key1", "value1");
		metadata.put("key2", "value2");
		return metadata;
	}
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: pavka
 * Date: 4/27/15
 * Time: 7:14 PM
 */

namespace Energine\shop\components;

use Energine\share\components\PageList;

class Categories extends PageList {

    protected function defineParams() {
        $id = array_intersect(
            array_keys(E()->getMap()->getParents($this->document->getID())),
            E()->getMap()->getPagesByTag('catalogue')
        );
        if (empty($id)) {
            $id = 'current';
        } else {
            list($id) = array_values($id);
        }
        return array_merge(
            parent::defineParams(),
            [
                'id' => $id,
                'bind' => false
            ]
        );
    }

    protected function main() {
        parent::main();
        if (!($this->getData()->isEmpty()) && ($bind = $this->getParam('bind')) && ($c = $this->document->componentManager->getBlockByName($bind))) {
            $sortSegment = substr(array_reduce($c->getSortData(), function ($p, $c) {
                    return $p . $c . '-';
                }, 'sort-'), 0, -1) . '/';
            foreach ($f = $this->getData()->getFieldByName('Segment') as $i => $segment) {
                $f->setRowData($i, $segment . $sortSegment);
            }
        }
    }
}


text:
/*
 *  Written for the Pkcs11Interop project by:
 *  Jaroslav IMRICH <jimrich@jimrich.sk>
 */

using System;
using Net.Pkcs11Interop.Common;
using Net.Pkcs11Interop.LowLevelAPI40;
using NUnit.Framework;

namespace Net.Pkcs11Interop.Tests.LowLevelAPI40
{
    /// <summary>
    /// C_SeedRandom and C_GenerateRandom tests.
    /// </summary>
    [TestFixture()]
    public class _11_SeedAndGenerateRandomTest
    {
        /// <summary>
        /// C_SeedRandom test.
        /// </summary>
        [Test()]
        public void _01_SeedRandomTest()
        {
            if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 0)
                Assert.Inconclusive("Test cannot be executed on this platform");

            CKR rv = CKR.CKR_OK;

            using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath))
            {
                rv = pkcs11.C_Initialize(Settings.InitArgs40);
                if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED))
                    Assert.Fail(rv.ToString());

                // Find first slot with token present
                uint slotId = Helpers.GetUsableSlot(pkcs11);

                // Open RO (read-only) session
                uint session = CK.CK_INVALID_HANDLE;
                rv = pkcs11.C_OpenSession(slotId, CKF.CKF_SERIAL_SESSION, IntPtr.Zero, IntPtr.Zero, ref session);
                if (rv != CKR.CKR_OK)
                    Assert.Fail(rv.ToString());

                // Mix additional seed material into the token's random number generator
                byte[] seed = ConvertUtils.Utf8StringToBytes("Additional seed material");
                rv = pkcs11.C_SeedRandom(session, seed, Convert.ToUInt32(seed.Length));
                if (rv != CKR.CKR_OK)
                    Assert.Fail(rv.ToString());

                // Do something interesting with random number generator

                rv = pkcs11.C_CloseSession(session);
                if (rv != CKR.CKR_OK)
                    Assert.Fail(rv.ToString());

                rv = pkcs11.C_Finalize(IntPtr.Zero);
                if (rv != CKR.CKR_OK)
                    Assert.Fail(rv.ToString());
            }
        }

        /// <summary>
        /// C_GenerateRandom test.
        /// </summary>
        [Test()]
        public void _02_GenerateRandomTest()
        {
            if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 0)
                Assert.Inconclusive("Test cannot be executed on this platform");

            CKR rv = CKR.CKR_OK;

            using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath))
            {
                rv = pkcs11.C_Initialize(Settings.InitArgs40);
                if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED))
                    Assert.Fail(rv.ToString());

                // Find first slot with token present
                uint slotId = Helpers.GetUsableSlot(pkcs11);

                // Open RO (read-only) session
                uint session = CK.CK_INVALID_HANDLE;
                rv = pkcs11.C_OpenSession(slotId, CKF.CKF_SERIAL_SESSION, IntPtr.Zero, IntPtr.Zero, ref session);
                if (rv != CKR.CKR_OK)
                    Assert.Fail(rv.ToString());

                // Allocate array for random bytes
                byte[] randomData = new byte[256];

                // Get random or pseudo-random data
                rv = pkcs11.C_GenerateRandom(session, randomData, Convert.ToUInt32(randomData.Length));
                if (rv != CKR.CKR_OK)
                    Assert.Fail(rv.ToString());

                // Do something interesting with random data

                rv = pkcs11.C_CloseSession(session);
                if (rv != CKR.CKR_OK)
                    Assert.Fail(rv.ToString());

                rv = pkcs11.C_Finalize(IntPtr.Zero);
                if (rv != CKR.CKR_OK)
                    Assert.Fail(rv.ToString());
            }
        }
    }
}


text:
<?php

namespace Lexik\Bundle\JWTAuthenticationBundle\Tests\Security\Guard;

use Lexik\Bundle\JWTAuthenticationBundle\Event\JWTAuthenticatedEvent;
use Lexik\Bundle\JWTAuthenticationBundle\Event\JWTInvalidEvent;
use Lexik\Bundle\JWTAuthenticationBundle\Event\JWTNotFoundEvent;
use Lexik\Bundle\JWTAuthenticationBundle\Events;
use Lexik\Bundle\JWTAuthenticationBundle\Exception\ExpiredTokenException;
use Lexik\Bundle\JWTAuthenticationBundle\Exception\InvalidPayloadException;
use Lexik\Bundle\JWTAuthenticationBundle\Exception\InvalidTokenException;
use Lexik\Bundle\JWTAuthenticationBundle\Exception\JWTDecodeFailureException;
use Lexik\Bundle\JWTAuthenticationBundle\Exception\MissingTokenException;
use Lexik\Bundle\JWTAuthenticationBundle\Exception\UserNotFoundException;
use Lexik\Bundle\JWTAuthenticationBundle\Response\JWTAuthenticationFailureResponse;
use Lexik\Bundle\JWTAuthenticationBundle\Security\Authentication\Token\JWTUserToken;
use Lexik\Bundle\JWTAuthenticationBundle\Security\Authentication\Token\PreAuthenticationJWTUserToken;
use Lexik\Bundle\JWTAuthenticationBundle\Security\Guard\JWTTokenAuthenticator;
use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface;
use Lexik\Bundle\JWTAuthenticationBundle\Tests\Stubs\User as AdvancedUserStub;
use Lexik\Bundle\JWTAuthenticationBundle\TokenExtractor\TokenExtractorInterface;
use PHPUnit\Framework\TestCase;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\User\UserProviderInterface;

class JWTTokenAuthenticatorTest extends TestCase
{
    public function testGetCredentials()
    {
        $jwtManager = $this->getJWTManagerMock();
        $jwtManager
            ->expects($this->once())
            ->method('decode')
            ->willReturn(['username' => 'lexik']);

        $authenticator = new JWTTokenAuthenticator(
            $jwtManager,
            $this->getEventDispatcherMock(),
            $this->getTokenExtractorMock('token')
        );

        $this->assertInstanceOf(PreAuthenticationJWTUserToken::class, $authenticator->getCredentials($this->getRequestMock()));
    }

    public function testGetCredentialsWithInvalidTokenThrowsException()
    {
        try {
            (new JWTTokenAuthenticator(
                $this->getJWTManagerMock(),
                $this->getEventDispatcherMock(),
                $this->getTokenExtractorMock('token')
            ))->getCredentials($this->getRequestMock());

            $this->fail(sprintf('Expected exception of type "%s" to be thrown.', InvalidTokenException::class));
        } catch (InvalidTokenException $e) {
            $this->assertSame('Invalid JWT Token', $e->getMessageKey());
        }
    }

    public function testGetCredentialsWithExpiredTokenThrowsException()
    {
        $jwtManager = $this->getJWTManagerMock();
        $jwtManager
            ->expects($this->once())
            ->method('decode')
            ->with(new PreAuthenticationJWTUserToken('token'))
            ->will($this->throwException(new JWTDecodeFailureException(JWTDecodeFailureException::EXPIRED_TOKEN, 'Expired JWT Token')));

        try {
            (new JWTTokenAuthenticator(
                $jwtManager,
                $this->getEventDispatcherMock(),
                $this->getTokenExtractorMock('token')
            ))->getCredentials($this->getRequestMock());

            $this->fail(sprintf('Expected exception of type "%s" to be thrown.', ExpiredTokenException::class));
        } catch (ExpiredTokenException $e) {
            $this->assertSame('Expired JWT Token', $e->getMessageKey());
        }
    }

    public function testGetCredentialsReturnsNullWithoutToken()
    {
        $authenticator = new JWTTokenAuthenticator(
            $this->getJWTManagerMock(),
            $this->getEventDispatcherMock(),
            $this->getTokenExtractorMock(false)
        );

        $this->assertNull($authenticator->getCredentials($this->getRequestMock()));
    }

    public function testGetUser()
    {
        $userIdentityField = 'username';
        $payload           = [$userIdentityField => 'lexik'];
        $rawToken          = 'token';
        $userRoles         = ['ROLE_USER'];

        $userStub = new AdvancedUserStub('lexik', 'password', 'user@gmail.com', $userRoles);

        $decodedToken = new PreAuthenticationJWTUserToken($rawToken);
        $decodedToken->setPayload($payload);

        $userProvider = $this->getUserProviderMock();
        $userProvider
            ->expects($this->once())
            ->method('loadUserByUsername')
            ->with($payload[$userIdentityField])
            ->willReturn($userStub);

        $authenticator = new JWTTokenAuthenticator(
            $this->getJWTManagerMock('username'),
            $this->getEventDispatcherMock(),
            $this->getTokenExtractorMock()
        );

        $this->assertSame($userStub, $authenticator->getUser($decodedToken, $userProvider));
    }

    public function testGetUserWithInvalidPayloadThrowsException()
    {
        $decodedToken = new PreAuthenticationJWTUserToken('rawToken');
        $decodedToken->setPayload([]); // Empty payload

        try {
            (new JWTTokenAuthenticator(
                $this->getJWTManagerMock('username'),
                $this->getEventDispatcherMock(),
                $this->getTokenExtractorMock()
            ))->getUser($decodedToken, $this->getUserProviderMock());

            $this->fail(sprintf('Expected exception of type "%s" to be thrown.', InvalidPayloadException::class));
        } catch (InvalidPayloadException $e) {
            $this->assertSame('Unable to find key "username" in the token payload.', $e->getMessageKey());
        }
    }

    /**
     * @expectedException        \InvalidArgumentException
     * @expectedExceptionMessage must be an instance of "Lexik\Bundle\JWTAuthenticationBundle\Security\Authentication\Token\PreAuthenticationJWTUserToken".
     */
    public function testGetUserWithInvalidFirstArg()
    {
        (new JWTTokenAuthenticator(
            $this->getJWTManagerMock(),
            $this->getEventDispatcherMock(),
            $this->getTokenExtractorMock()
        ))->getUser(new \stdClass(), $this->getUserProviderMock());
    }

    public function testGetUserWithInvalidUserThrowsException()
    {
        $userIdentityField = 'username';
        $payload           = [$userIdentityField => 'lexik'];

        $decodedToken = new PreAuthenticationJWTUserToken('rawToken');
        $decodedToken->setPayload($payload);

        $userProvider = $this->getUserProviderMock();
        $userProvider
            ->expects($this->once())
            ->method('loadUserByUsername')
            ->with($payload[$userIdentityField])
            ->will($this->throwException(new UsernameNotFoundException()));

        try {
            (new JWTTokenAuthenticator(
                $this->getJWTManagerMock('username'),
                $this->getEventDispatcherMock(),
                $this->getTokenExtractorMock()
            ))->getUser($decodedToken, $userProvider);

            $this->fail(sprintf('Expected exception of type "%s" to be thrown.', UserNotFoundException::class));
        } catch (UserNotFoundException $e) {
            $this->assertSame('Unable to load an user with property "username" = "lexik". If the user identity has changed, you must renew the token. Otherwise, verify that the "lexik_jwt_authentication.user_identity_field" config option is correctly set.', $e->getMessageKey());
        }
    }

    public function testCreateAuthenticatedToken()
    {
        $rawToken  = 'token';
        $userRoles = ['ROLE_USER'];
        $payload   = ['username' => 'lexik'];
        $userStub  = new AdvancedUserStub('lexik', 'password', 'user@gmail.com', $userRoles);

        $decodedToken = new PreAuthenticationJWTUserToken($rawToken);
        $decodedToken->setPayload($payload);

        $jwtUserToken = new JWTUserToken($userRoles, $userStub, $rawToken, 'lexik');

        $dispatcher = $this->getEventDispatcherMock();
        $dispatcher
            ->expects($this->once())
            ->method('dispatch')
            ->with(Events::JWT_AUTHENTICATED, new JWTAuthenticatedEvent($payload, $jwtUserToken));

        $authenticator = new JWTTokenAuthenticator(
            $this->getJWTManagerMock('username'),
            $dispatcher,
            $this->getTokenExtractorMock()
        );

        $userProvider = $this->getUserProviderMock();
        $userProvider
            ->expects($this->once())
            ->method('loadUserByUsername')
            ->with($payload['username'])
            ->willReturn($userStub);

        $authenticator->getUser($decodedToken, $userProvider);

        $this->assertEquals($jwtUserToken, $authenticator->createAuthenticatedToken($userStub, 'lexik'));
    }

    /**
     * @expectedException        \RuntimeException
     * @expectedExceptionMessage Unable to return an authenticated token
     */
    public function testCreateAuthenticatedTokenThrowsExceptionIfNotPreAuthenticatedToken()
    {
        $userStub = new AdvancedUserStub('lexik', 'test');

        (new JWTTokenAuthenticator(
           $this->getJWTManagerMock(),
           $this->getEventDispatcherMock(),
           $this->getTokenExtractorMock()
       ))->createAuthenticatedToken($userStub, 'lexik');
    }

    public function testOnAuthenticationFailureWithInvalidToken()
    {
        $authException    = new InvalidTokenException();
        $expectedResponse = new JWTAuthenticationFailureResponse('Invalid JWT Token');

        $dispatcher = $this->getEventDispatcherMock();
        $dispatcher
            ->expects($this->once())
            ->method('dispatch')
            ->with(
                Events::JWT_INVALID,
                new JWTInvalidEvent($authException, $expectedResponse)
            );

        $authenticator = new JWTTokenAuthenticator(
            $this->getJWTManagerMock(),
            $dispatcher,
            $this->getTokenExtractorMock()
        );

        $response = $authenticator->onAuthenticationFailure($this->getRequestMock(), $authException);

        $this->assertEquals($expectedResponse, $response);
        $this->assertSame($expectedResponse->getMessage(), $response->getMessage());
    }

    public function testStart()
    {
        $authException   = new MissingTokenException('JWT Token not found');
        $failureResponse = new JWTAuthenticationFailureResponse($authException->getMessageKey());

        $dispatcher = $this->getEventDispatcherMock();
        $dispatcher
            ->expects($this->once())
            ->method('dispatch')
            ->with(
                Events::JWT_NOT_FOUND,
                new JWTNotFoundEvent($authException, $failureResponse)
            );

        $authenticator = new JWTTokenAuthenticator(
            $this->getJWTManagerMock(),
            $dispatcher,
            $this->getTokenExtractorMock()
        );

        $response = $authenticator->start($this->getRequestMock());

        $this->assertEquals($failureResponse, $response);
        $this->assertSame($failureResponse->getMessage(), $response->getMessage());
    }

    public function testCheckCredentials()
    {
        $user = new AdvancedUserStub('test', 'test');

        $this->assertTrue(
            (new JWTTokenAuthenticator(
                $this->getJWTManagerMock(),
                $this->getEventDispatcherMock(),
                $this->getTokenExtractorMock()
            ))->checkCredentials(null, $user)
        );
    }

    public function testSupportsRememberMe()
    {
        $this->assertFalse(
            (new JWTTokenAuthenticator(
                $this->getJWTManagerMock(),
                $this->getEventDispatcherMock(),
                $this->getTokenExtractorMock()
            ))->supportsRememberMe()
        );
    }

    private function getJWTManagerMock($userIdentityField = null)
    {
        $jwtManager = $this->getMockBuilder(JWTTokenManagerInterface::class)
            ->disableOriginalConstructor()
            ->getMock();

        if (null !== $userIdentityField) {
            $jwtManager
                ->expects($this->once())
                ->method('getUserIdentityField')
                ->willReturn($userIdentityField);
        }

        return $jwtManager;
    }

    private function getEventDispatcherMock()
    {
        return $this->getMockBuilder(EventDispatcherInterface::class)
            ->disableOriginalConstructor()
            ->getMock();
    }

    private function getTokenExtractorMock($returnValue = null)
    {
        $extractor = $this->getMockBuilder(TokenExtractorInterface::class)
            ->disableOriginalConstructor()
            ->getMock();

        if (null !== $returnValue) {
            $extractor
                ->expects($this->once())
                ->method('extract')
                ->willReturn($returnValue);
        }

        return $extractor;
    }

    private function getRequestMock()
    {
        return $this->getMockBuilder(Request::class)
            ->disableOriginalConstructor()
            ->getMock();
    }

    private function getUserProviderMock()
    {
        return $this->getMockBuilder(UserProviderInterface::class)
            ->disableOriginalConstructor()
            ->getMock();
    }
}


text:
from .. import utils
from .storages import image_storage

async def save_image(app, user, filename, content, content_type):
    name = await app.loop.run_in_executor(
        None, image_storage.save, filename, content)
    image_uuid = image_storage.uuid(name)
    image = app.models.image
    await image.create(
        uuid=image_uuid,
        image=name,
        mime_type=content_type,
        author_id=user.id,
        created_at=utils.now(),
    )
    return image_uuid


text:
layout: post
microblog: true
audio:
photo: http://microblog.curtclifton.net/uploads/2017/608e4b0259.jpg
date: 2017-08-08 09:19:58 -0700
guid: http://curt.micro.blog/2017/08/08/i-think-ill.html
---
I think I'll like measuring screen real estate in m^2.

<img src="http://microblog.curtclifton.net/uploads/2017/608e4b0259.jpg" width="600" height="600" style="height: auto" />


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle"  >
            <corners android:radius="20dip" />
            <solid android:color="@color/darkBlueGrey" />
        </shape>
    </item>
</selector>


text:
<?php

namespace Brickoo\Tests\Component\Common;

use Brickoo\Component\Common\ArrayList;
use PHPUnit_Framework_TestCase;

/**
 * ArrayListTest
 *
 * Test suite for the ArrayList class.
 * @see Brickoo\Component\Common\ArrayList
 * @author Celestino Diaz <celestino.diaz@gmx.de>
 */
class ArrayListTest extends PHPUnit_Framework_TestCase {

    /**
     * @covers Brickoo\Component\Common\ArrayList::__construct
     * @covers Brickoo\Component\Common\ArrayList::add
     * @covers Brickoo\Component\Common\ArrayList::get
     * @covers Brickoo\Component\Common\ArrayList::indexOf
     * @covers Brickoo\Component\Common\ArrayList::isEmpty
     * @covers Brickoo\Component\Common\ArrayList::contains
     * @covers Brickoo\Component\Common\ArrayList::has
     * @covers Brickoo\Component\Common\ArrayList::count
     * @covers Brickoo\Component\Common\ArrayList::toArray
     * @covers Brickoo\Component\Common\ArrayList::remove
     */
    public function testCommonItemRoutines() {
        $item = "some value";
        $list = new ArrayList();
        $this->assertTrue($list->isEmpty());
        $list->add($item);
        $this->assertFalse($list->isEmpty());
        $this->assertTrue($list->contains($item));
        $this->assertTrue($list->has(($index = $list->indexOf($item))));
        $this->assertEquals($item, $list->get($index));
        $this->assertEquals(1, $list->count());
        $this->assertEquals([$item], $list->toArray());
        $list->remove($index);
        $this->assertTrue($list->isEmpty());
    }

    /**
     * @covers Brickoo\Component\Common\ArrayList::get
     * @covers Brickoo\Component\Common\Exception\InvalidIndexException
     * @expectedException \Brickoo\Component\Common\Exception\InvalidIndexException
     */
    public function testTryingToRetrieveAnItemByInvalidIndexThrowsException() {
        $list = new ArrayList();
        $list->get(0);
    }

    /**
     * @covers Brickoo\Component\Common\ArrayList::remove
     * @covers Brickoo\Component\Common\Exception\InvalidIndexException
     * @expectedException \Brickoo\Component\Common\Exception\InvalidIndexException
     */
    public function testTryingToRemoveAnItemByInvalidIndexThrowsException() {
        $list = new ArrayList();
        $list->remove(0);
    }

    /**
     * @covers Brickoo\Component\Common\ArrayList::first
     * @covers Brickoo\Component\Common\ArrayList::last
     */
    public function testRetrieveFirstAndLastItemsFromList() {
        $list = new ArrayList();
        $this->assertNull($list->first());
        $this->assertNull($list->last());

        $list = new ArrayList([1, 2, 3]);
        $this->assertEquals(1, $list->first());
        $this->assertEquals(3, $list->last());
    }

    /**
     * @covers Brickoo\Component\Common\ArrayList::reverse
     * @covers Brickoo\Component\Common\ArrayList::toArray
     */
    public function testListItemsOrderCanBeReverted() {
        $expectedArray = [3, 2, 1];
        $list = new ArrayList([1, 2, 3]);
        $list->reverse();
        $this->assertEquals($expectedArray, $list->toArray());
    }

    /**
     * Test is only for the purpose of code coverage only
     * since the shuffle could also retain the items order.
     * @covers Brickoo\Component\Common\ArrayList::shuffle
     * @covers Brickoo\Component\Common\ArrayList::toArray
     */
    public function testListItemsOrderCanBeShuffled() {
        $list = new ArrayList([1, 2, 3]);
        $list->shuffle();
        $this->assertTrue(true);
    }

    /**
     * @covers Brickoo\Component\Common\ArrayList::uniquify
     * @covers Brickoo\Component\Common\ArrayList::toArray
     */
    public function testListDuplicateItemsAreRemoved() {
        $expectedArray = [1, 2];
        $list = new ArrayList([1, 2, 1, 2]);
        $list->uniquify();
        $this->assertEquals($expectedArray, $list->toArray());
    }

    /** @covers Brickoo\Component\Common\ArrayList::getIterator */
    public function testListCanBeConvertedToAnIterableInstance() {
        $expectedArray = [1, 2, 3];
        $list = new ArrayList($expectedArray);
        $this->assertInstanceOf("Iterator", ($iterator = $list->getIterator()));
        $this->assertEquals($expectedArray, $iterator->getArrayCopy());
    }

    /** @covers Brickoo\Component\Common\ArrayList::toString */
    public function testListStringRepresentation() {
        $expectedString = "1\n2\n3\ntrue\nO:8:\"stdClass\":0:{}\na:0:{}";
        $list= new ArrayList([1, 2, 3, true, new \stdClass(), []]);
        $this->assertEquals($expectedString, $list->toString());
    }

}


text:
package com.dm.wallpaper.board.tasks;

import android.app.Activity;
import android.app.WallpaperManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.RectF;
import android.os.AsyncTask;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.danimahardhika.android.helpers.core.ColorHelper;
import com.danimahardhika.android.helpers.core.WindowHelper;
import com.danimahardhika.cafebar.CafeBar;
import com.danimahardhika.cafebar.CafeBarTheme;
import com.dm.wallpaper.board.R;
import com.dm.wallpaper.board.helpers.TypefaceHelper;
import com.dm.wallpaper.board.helpers.WallpaperHelper;
import com.dm.wallpaper.board.items.Wallpaper;
import com.dm.wallpaper.board.preferences.Preferences;
import com.dm.wallpaper.board.utils.ImageConfig;
import com.danimahardhika.android.helpers.core.utils.LogUtil;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageSize;

import java.lang.ref.WeakReference;
import java.util.Locale;
import java.util.concurrent.Executor;

public class WallpaperApplyTask extends AsyncTask<Void, Void, Boolean> implements WallpaperPropertiesLoaderTask.Callback{

    private final WeakReference<Context> mContext;
    private Apply mApply;
    private RectF mRectF;
    private Executor mExecutor;
    private Wallpaper mWallpaper;
    private MaterialDialog mDialog;

    private WallpaperApplyTask(Context context) {
        mContext = new WeakReference<>(context);
    }

    public WallpaperApplyTask to(Apply apply) {
        mApply = apply;
        return this;
    }

    public WallpaperApplyTask wallpaper(@NonNull Wallpaper wallpaper) {
        mWallpaper = wallpaper;
        return this;
    }

    public WallpaperApplyTask crop(@Nullable RectF rectF) {
        mRectF = rectF;
        return this;
    }

    public AsyncTask start() {
        return start(SERIAL_EXECUTOR);
    }

    public AsyncTask start(@NonNull Executor executor) {
        if (mDialog == null) {
            int color = mWallpaper.getColor();
            if (color == 0) {
                color = ColorHelper.getAttributeColor(mContext.get(), R.attr.colorAccent);
            }

            final MaterialDialog.Builder builder = new MaterialDialog.Builder(mContext.get());
            builder.widgetColor(color)
                    .typeface(TypefaceHelper.getMedium(mContext.get()), TypefaceHelper.getRegular(mContext.get()))
                    .progress(true, 0)
                    .cancelable(false)
                    .progressIndeterminateStyle(true)
                    .content(R.string.wallpaper_loading)
                    .positiveColor(color)
                    .positiveText(android.R.string.cancel)
                    .onPositive((dialog, which) -> {
                        ImageLoader.getInstance().stop();
                        cancel(true);
                    });

            mDialog = builder.build();
        }

        if (!mDialog.isShowing()) mDialog.show();

        mExecutor = executor;
        if (mWallpaper == null) {
            LogUtil.e("WallpaperApply cancelled, wallpaper is null");
            return null;
        }

        if (mWallpaper.getDimensions() == null) {
            return WallpaperPropertiesLoaderTask.prepare(mContext.get())
                    .wallpaper(mWallpaper)
                    .callback(this)
                    .start(AsyncTask.THREAD_POOL_EXECUTOR);
        }
        return executeOnExecutor(executor);
    }

    public static WallpaperApplyTask prepare(@NonNull Context context) {
        return new WallpaperApplyTask(context);
    }

    @Override
    public void onPropertiesReceived(Wallpaper wallpaper) {
        mWallpaper = wallpaper;
        if (mExecutor == null) mExecutor = SERIAL_EXECUTOR;
        if (mWallpaper.getDimensions() == null) {
            LogUtil.e("WallpaperApply cancelled, unable to retrieve wallpaper dimensions");

            if (mContext.get() == null) return;
            if (mContext.get() instanceof Activity) {
                if (((Activity) mContext.get()).isFinishing())
                    return;
            }

            if (mDialog != null && mDialog.isShowing()) {
                mDialog.dismiss();
            }

            Toast.makeText(mContext.get(), R.string.wallpaper_apply_failed,
                    Toast.LENGTH_LONG).show();
            return;
        }

        try {
            executeOnExecutor(mExecutor);
        } catch (IllegalStateException e) {
            LogUtil.e(Log.getStackTraceString(e));
        }
    }

    @Override
    protected Boolean doInBackground(Void... voids) {
        while (!isCancelled()) {
            try {
                Thread.sleep(1);
                ImageSize imageSize = WallpaperHelper.getTargetSize(mContext.get());

                LogUtil.d("original rectF: " +mRectF);

                if (mRectF != null && Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
                    Point point = WindowHelper.getScreenSize(mContext.get());
                    int height = point.y - WindowHelper.getStatusBarHeight(mContext.get()) - WindowHelper.getNavigationBarHeight(mContext.get());
                    float heightFactor = (float) imageSize.getHeight() / (float) height;
                    mRectF = WallpaperHelper.getScaledRectF(mRectF, heightFactor, 1f);
                }

                if (mRectF == null && Preferences.get(mContext.get()).isCropWallpaper()) {
                    /*
                     * Create a center crop rectF if wallpaper applied from grid, not opening the preview first
                     */
                    float widthScaleFactor = (float) imageSize.getHeight() / (float) mWallpaper.getDimensions().getHeight();

                    float side = ((float) mWallpaper.getDimensions().getWidth() * widthScaleFactor - (float) imageSize.getWidth())/2f;
                    float leftRectF = 0f - side;
                    float rightRectF = (float) mWallpaper.getDimensions().getWidth() * widthScaleFactor - side;
                    float topRectF = 0f;
                    float bottomRectF = (float) imageSize.getHeight();
                    mRectF = new RectF(leftRectF, topRectF, rightRectF, bottomRectF);
                    LogUtil.d("created center crop rectF: " +mRectF);
                }

                ImageSize adjustedSize = imageSize;
                RectF adjustedRectF = mRectF;

                float scaleFactor = (float) mWallpaper.getDimensions().getHeight() / (float) imageSize.getHeight();
                if (scaleFactor > 1f) {
                    /*
                     * Applying original wallpaper size caused a problem (wallpaper zoomed in)
                     * if wallpaper dimension bigger than device screen resolution
                     *
                     * Solution: Resize wallpaper to match screen resolution
                     */

                    /*
                     * Use original wallpaper size:
                     * adjustedSize = new ImageSize(width, height);
                     */

                    /*
                     * Adjust wallpaper size to match screen resolution:
                     */
                    float widthScaleFactor = (float) imageSize.getHeight() / (float) mWallpaper.getDimensions().getHeight();
                    int adjustedWidth = Float.valueOf((float) mWallpaper.getDimensions().getWidth() * widthScaleFactor).intValue();
                    adjustedSize = new ImageSize(adjustedWidth, imageSize.getHeight());

                    if (adjustedRectF != null) {
                        /*
                         * If wallpaper crop enabled, original wallpaper size should be loaded first
                         */
                        adjustedSize = new ImageSize(mWallpaper.getDimensions().getWidth(), mWallpaper.getDimensions().getHeight());
                        adjustedRectF = WallpaperHelper.getScaledRectF(mRectF, scaleFactor, scaleFactor);
                        LogUtil.d("adjusted rectF: " + adjustedRectF);
                    }

                    LogUtil.d(String.format(Locale.getDefault(), "adjusted bitmap: %d x %d",
                            adjustedSize.getWidth(), adjustedSize.getHeight()));
                }

                int call = 1;
                do {
                    /*
                     * Load the bitmap first
                     */
                    Bitmap loadedBitmap = ImageLoader.getInstance().loadImageSync(
                            mWallpaper.getUrl(), adjustedSize, ImageConfig.getWallpaperOptions());
                    if (loadedBitmap != null) {
                        try {
                            /*
                             * Checking if loaded bitmap resolution supported by the device
                             * If texture size too big then resize it
                             */
                            Bitmap bitmapTemp = Bitmap.createBitmap(
                                    loadedBitmap.getWidth(),
                                    loadedBitmap.getHeight(),
                                    loadedBitmap.getConfig());
                            bitmapTemp.recycle();

                            /*
                             * Texture size is ok
                             */
                            LogUtil.d(String.format(Locale.getDefault(), "loaded bitmap: %d x %d",
                                    loadedBitmap.getWidth(), loadedBitmap.getHeight()));
                            publishProgress();

                            Bitmap bitmap = loadedBitmap;
                            if (Preferences.get(mContext.get()).isCropWallpaper() && adjustedRectF != null) {
                                LogUtil.d("rectF: " +adjustedRectF);
                                /*
                                 * Cropping bitmap
                                 */
                                ImageSize targetSize = WallpaperHelper.getTargetSize(mContext.get());

                                int targetWidth = Double.valueOf(
                                        ((double) loadedBitmap.getHeight() / (double) targetSize.getHeight())
                                                * (double) targetSize.getWidth()).intValue();

                                bitmap = Bitmap.createBitmap(
                                        targetWidth,
                                        loadedBitmap.getHeight(),
                                        loadedBitmap.getConfig());
                                Paint paint = new Paint();
                                paint.setFilterBitmap(true);
                                paint.setAntiAlias(true);
                                paint.setDither(true);

                                Canvas canvas = new Canvas(bitmap);
                                canvas.drawBitmap(loadedBitmap, null, adjustedRectF, paint);

                                float scale = (float) targetSize.getHeight() / (float) bitmap.getHeight();
                                if (scale < 1f) {
                                    LogUtil.d("bitmap size is bigger than screen resolution, resizing bitmap");
                                    int resizedWidth = Float.valueOf((float) bitmap.getWidth() * scale).intValue();
                                    bitmap = Bitmap.createScaledBitmap(bitmap, resizedWidth, targetSize.getHeight(), true);
                                }
                            }

                            /*
                             * Final bitmap generated
                             */
                            LogUtil.d(String.format(Locale.getDefault(), "generated bitmap: %d x %d ",
                                    bitmap.getWidth(), bitmap.getHeight()));

                            if (mApply == Apply.HOMESCREEN_LOCKSCREEN) {
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                    WallpaperManager.getInstance(mContext.get().getApplicationContext()).setBitmap(
                                            bitmap, null, true, WallpaperManager.FLAG_LOCK | WallpaperManager.FLAG_SYSTEM);
                                    return true;
                                }
                            }

                            if (mApply == Apply.HOMESCREEN) {
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                    WallpaperManager.getInstance(mContext.get().getApplicationContext()).setBitmap(
                                            bitmap, null, true, WallpaperManager.FLAG_SYSTEM);
                                    return true;
                                }

                                WallpaperManager.getInstance(mContext.get().getApplicationContext()).setBitmap(bitmap);
                                return true;
                            }

                            if (mApply == Apply.LOCKSCREEN) {
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                    WallpaperManager.getInstance(mContext.get().getApplicationContext()).setBitmap(
                                            bitmap, null, true, WallpaperManager.FLAG_LOCK);
                                    return true;
                                }
                            }
                        } catch (OutOfMemoryError e) {
                            LogUtil.e("loaded bitmap is too big, resizing it ...");
                            /*
                             * Texture size is too big
                             * Resizing bitmap
                             */

                            double scale = 1 - (0.1 * call);
                            int scaledWidth = Double.valueOf(adjustedSize.getWidth() * scale).intValue();
                            int scaledHeight = Double.valueOf(adjustedSize.getHeight() * scale).intValue();

                            adjustedRectF = WallpaperHelper.getScaledRectF(adjustedRectF,
                                    (float) scale, (float) scale);
                            adjustedSize = new ImageSize(scaledWidth, scaledHeight);
                        }
                    }

                    /*
                     * Continue to next iteration
                     */
                    call++;
                } while (call <= 5 && !isCancelled());
                return false;
            } catch (Exception e) {
                LogUtil.e(Log.getStackTraceString(e));
                return false;
            }
        }
        return false;
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
        if (mContext.get() == null) return;
        if (mContext.get() instanceof Activity) {
            if (((Activity) mContext.get()).isFinishing())
                return;
        }

        mDialog.setContent(R.string.wallpaper_applying);
    }

    @Override
    protected void onCancelled(Boolean aBoolean) {
        super.onCancelled(aBoolean);
        if (mContext.get() == null) return;
        if (mContext.get() instanceof Activity) {
            if (((Activity) mContext.get()).isFinishing())
                return;
        }

        Toast.makeText(mContext.get(), R.string.wallpaper_apply_cancelled,
                Toast.LENGTH_LONG).show();
    }

    @Override
    protected void onPostExecute(Boolean aBoolean) {
        super.onPostExecute(aBoolean);
        if (mContext.get() == null) return;
        if (mContext.get() instanceof Activity) {
            if (((Activity) mContext.get()).isFinishing())
                return;
        }

        if (mDialog != null && mDialog.isShowing()) {
            mDialog.dismiss();
        }

        if (aBoolean) {
            CafeBar.builder(mContext.get())
                    .theme(Preferences.get(mContext.get()).isDarkTheme() ? CafeBarTheme.LIGHT : CafeBarTheme.DARK)
                    .contentTypeface(TypefaceHelper.getRegular(mContext.get()))
                    .floating(true)
                    .fitSystemWindow()
                    .content(R.string.wallpaper_applied)
                    .show();
        } else {
            Toast.makeText(mContext.get(), R.string.wallpaper_apply_failed,
                    Toast.LENGTH_LONG).show();
        }
    }

    public enum Apply {
        LOCKSCREEN,
        HOMESCREEN,
        HOMESCREEN_LOCKSCREEN
    }
}


text:
namespace org { namespace alljoyn { namespace Humidifier { namespace Actions {

ref class ActionsSignals;

public interface class IActionsSignals
{
};

public ref class ActionsSignals sealed : [Windows::Foundation::Metadata::Default] IActionsSignals
{
public:
internal:
    void Initialize(_In_ alljoyn_busobject busObject, _In_ alljoyn_sessionid sessionId);

private:
    alljoyn_busobject m_busObject;
    alljoyn_sessionid m_sessionId;

};

} } } }


text:
<?php

declare(strict_types=1);

namespace LaravelZero\Framework\Bootstrap;

use function class_exists;
use Dotenv\Dotenv;
use Illuminate\Foundation\Bootstrap\LoadEnvironmentVariables as BaseLoadEnvironmentVariables;
use LaravelZero\Framework\Application;
use LaravelZero\Framework\Contracts\BoostrapperContract;

/**
 * @internal
 */
final class LoadEnvironmentVariables implements BoostrapperContract
{
    /**
     * {@inheritdoc}
     */
    public function bootstrap(Application $app): void
    {
        if (class_exists(Dotenv::class)) {
            $app->make(BaseLoadEnvironmentVariables::class)->bootstrap($app);
            $app->make(BuildLoadEnvironmentVariables::class)->bootstrap($app);
        }
    }
}


text:
package resources

import (
	"encoding/json"

	"code.cloudfoundry.org/cli/api/cloudcontroller"
	"code.cloudfoundry.org/cli/types"
)

// Buildpack represents a Cloud Controller V3 buildpack.
type Buildpack struct {
	// Enabled is true when the buildpack can be used for staging.
	Enabled types.NullBool
	// Filename is the uploaded filename of the buildpack.
	Filename string
	// GUID is the unique identifier for the buildpack.
	GUID string
	// Locked is true when the buildpack cannot be updated.
	Locked types.NullBool
	// Name is the name of the buildpack. To be used by app buildpack field.
	// (only alphanumeric characters)
	Name string
	// Position is the order in which the buildpacks are checked during buildpack
	// auto-detection.
	Position types.NullInt
	// Stack is the name of the stack that the buildpack will use.
	Stack string
	// State is the current state of the buildpack.
	State string
	// Links are links to related resources.
	Links APILinks
	// Metadata is used for custom tagging of API resources
	Metadata *Metadata
}

// MarshalJSON converts a Package into a Cloud Controller Package.
func (buildpack Buildpack) MarshalJSON() ([]byte, error) {
	ccBuildpack := struct {
		Name     string    `json:"name,omitempty"`
		Stack    string    `json:"stack,omitempty"`
		Position *int      `json:"position,omitempty"`
		Enabled  *bool     `json:"enabled,omitempty"`
		Locked   *bool     `json:"locked,omitempty"`
		Metadata *Metadata `json:"metadata,omitempty"`
	}{
		Name:  buildpack.Name,
		Stack: buildpack.Stack,
	}

	if buildpack.Position.IsSet {
		ccBuildpack.Position = &buildpack.Position.Value
	}
	if buildpack.Enabled.IsSet {
		ccBuildpack.Enabled = &buildpack.Enabled.Value
	}
	if buildpack.Locked.IsSet {
		ccBuildpack.Locked = &buildpack.Locked.Value
	}

	return json.Marshal(ccBuildpack)
}

func (buildpack *Buildpack) UnmarshalJSON(data []byte) error {
	var ccBuildpack struct {
		GUID     string         `json:"guid,omitempty"`
		Links    APILinks       `json:"links,omitempty"`
		Name     string         `json:"name,omitempty"`
		Filename string         `json:"filename,omitempty"`
		Stack    string         `json:"stack,omitempty"`
		State    string         `json:"state,omitempty"`
		Enabled  types.NullBool `json:"enabled"`
		Locked   types.NullBool `json:"locked"`
		Position types.NullInt  `json:"position"`
		Metadata *Metadata      `json:"metadata"`
	}

	err := cloudcontroller.DecodeJSON(data, &ccBuildpack)
	if err != nil {
		return err
	}

	buildpack.Enabled = ccBuildpack.Enabled
	buildpack.Filename = ccBuildpack.Filename
	buildpack.GUID = ccBuildpack.GUID
	buildpack.Locked = ccBuildpack.Locked
	buildpack.Name = ccBuildpack.Name
	buildpack.Position = ccBuildpack.Position
	buildpack.Stack = ccBuildpack.Stack
	buildpack.State = ccBuildpack.State
	buildpack.Links = ccBuildpack.Links
	buildpack.Metadata = ccBuildpack.Metadata

	return nil
}


text:
using System;
using System.Collections.Generic;
using System.Text;
using OpenMetaverse;
using OpenMetaverse.Packets;

namespace OpenMetaverse.TestClient
{
    public class FollowCommand: Command
    {
        const float DISTANCE_BUFFER = 3.0f;
        uint targetLocalID = 0;

		public FollowCommand(TestClient testClient)
		{
			Name = "follow";
			Description = "Follow another avatar. Usage: follow [FirstName LastName]/off.";
            Category = CommandCategory.Movement;

            testClient.Network.RegisterCallback(PacketType.AlertMessage, new NetworkManager.PacketCallback(AlertMessageHandler));
		}

        public override string Execute(string[] args, UUID fromAgentID)
		{
            // Construct the target name from the passed arguments
			string target = String.Empty;
			for (int ct = 0; ct < args.Length; ct++)
				target = target + args[ct] + " ";
			target = target.TrimEnd();

            if (target.Length == 0 || target == "off")
            {
                Active = false;
                targetLocalID = 0;
                Client.Self.AutoPilotCancel();
                return "Following is off";
            }
            else
            {
                if (Follow(target))
                    return "Following " + target;
                else
                    return "Unable to follow " + target + ".  Client may not be able to see that avatar.";
            }
		}

        bool Follow(string name)
        {
            lock (Client.Network.Simulators)
            {
                for (int i = 0; i < Client.Network.Simulators.Count; i++)
                {
                    Avatar target = Client.Network.Simulators[i].ObjectsAvatars.Find(
                        delegate(Avatar avatar)
                        {
                            return avatar.Name == name;
                        }
                    );

                    if (target != null)
                    {
                        targetLocalID = target.LocalID;
                        Active = true;
                        return true;
                    }
                }
            }

            if (Active)
            {
                Client.Self.AutoPilotCancel();
                Active = false;
            }

            return false;
        }

        bool Follow(UUID id)
        {
            lock (Client.Network.Simulators)
            {
                for (int i = 0; i < Client.Network.Simulators.Count; i++)
                {
                    Avatar target = Client.Network.Simulators[i].ObjectsAvatars.Find(
                        delegate(Avatar avatar)
                        {
                            return avatar.ID == id;
                        }
                    );

                    if (target != null)
                    {
                        targetLocalID = target.LocalID;
                        Active = true;
                        return true;
                    }
                }
            }

            Active = false;
            return false;
        }

		public override void Think()
		{
            if (Active)
            {
                // Find the target position
                lock (Client.Network.Simulators)
                {
                    for (int i = 0; i < Client.Network.Simulators.Count; i++)
                    {
                        Avatar targetAv;

                        if (Client.Network.Simulators[i].ObjectsAvatars.TryGetValue(targetLocalID, out targetAv))
                        {
                            float distance = 0.0f;

                            if (Client.Network.Simulators[i] == Client.Network.CurrentSim)
                            {
                                distance = Vector3.Distance(targetAv.Position, Client.Self.SimPosition);
                            }
                            else
                            {
                                // FIXME: Calculate global distances
                            }

                            if (distance > DISTANCE_BUFFER)
                            {
                                uint regionX, regionY;
                                Utils.LongToUInts(Client.Network.Simulators[i].Handle, out regionX, out regionY);

                                double xTarget = (double)targetAv.Position.X + (double)regionX;
                                double yTarget = (double)targetAv.Position.Y + (double)regionY;
                                double zTarget = targetAv.Position.Z - 2f;

                                Logger.DebugLog(String.Format("[Autopilot] {0} meters away from the target, starting autopilot to <{1},{2},{3}>",
                                    distance, xTarget, yTarget, zTarget), Client);

                                Client.Self.AutoPilot(xTarget, yTarget, zTarget);
                            }
                            else
                            {
                                // We are in range of the target and moving, stop moving
                                Client.Self.AutoPilotCancel();
                            }
                        }
                    }
                }
            }

			base.Think();
		}

        private void AlertMessageHandler(Packet packet, Simulator simulator)
        {
            AlertMessagePacket alert = (AlertMessagePacket)packet;
            string message = Utils.BytesToString(alert.AlertData.Message);

            if (message.Contains("Autopilot cancel"))
            {
                Logger.Log("FollowCommand: " + message, Helpers.LogLevel.Info, Client);
            }
        }
    }
}