text:
This file contains functions for extending the LSTM class to multiple
time steps, and also to compress the parameters of LSTM to single 1D-tensor

This code was originally based on Oxford University
Machine Learning class [practical 6](https://github.com/oxford-cs-ml-2015/practical6).

The 1D -Tensor makes it easier for nngraph to compute forward and
backward gradients
--]]

require 'torch'

local lstm_utils = {}

function lstm_utils.combine_all_parameters(...)
    --[[ like module:getParameters, but operates on many modules ]]--

    -- get parameters
    local networks = {...}
    local parameters = {}
    local gradParameters = {}
    for i = 1, #networks do
        local net_params, net_grads = networks[i]:parameters()

        if net_params then
            for _, p in pairs(net_params) do
                parameters[#parameters + 1] = p
            end
            for _, g in pairs(net_grads) do
                gradParameters[#gradParameters + 1] = g
            end
        end
    end

    local function storageInSet(set, storage)
        local storageAndOffset = set[torch.pointer(storage)]
        if storageAndOffset == nil then
            return nil
        end
        local _, offset = unpack(storageAndOffset)
        return offset
    end

    -- this function flattens arbitrary lists of parameters,
    -- even complex shared ones
    local function flatten(parameters)
        if not parameters or #parameters == 0 then
            return torch.Tensor()
        end
        local Tensor = parameters[1].new

        local storages = {}
        local nParameters = 0
        for k = 1,#parameters do
            local storage = parameters[k]:storage()
            if not storageInSet(storages, storage) then
                storages[torch.pointer(storage)] = {storage, nParameters}
                nParameters = nParameters + storage:size()
            end
        end

        local flatParameters = Tensor(nParameters):fill(1)
        local flatStorage = flatParameters:storage()

        for k = 1,#parameters do
            local storageOffset = storageInSet(storages, parameters[k]:storage())
            parameters[k]:set(flatStorage,
                storageOffset + parameters[k]:storageOffset(),
                parameters[k]:size(),
                parameters[k]:stride())
            parameters[k]:zero()
        end

        local maskParameters=  flatParameters:float():clone()
        local cumSumOfHoles = flatParameters:float():cumsum(1)
        local nUsedParameters = nParameters - cumSumOfHoles[#cumSumOfHoles]
        local flatUsedParameters = Tensor(nUsedParameters)
        local flatUsedStorage = flatUsedParameters:storage()

        for k = 1,#parameters do
            local offset = cumSumOfHoles[parameters[k]:storageOffset()]
            parameters[k]:set(flatUsedStorage,
                parameters[k]:storageOffset() - offset,
                parameters[k]:size(),
                parameters[k]:stride())
        end

        for _, storageAndOffset in pairs(storages) do
            local k, v = unpack(storageAndOffset)
            flatParameters[{{v+1,v+k:size()}}]:copy(Tensor():set(k))
        end

        if cumSumOfHoles:sum() == 0 then
            flatUsedParameters:copy(flatParameters)
        else
            local counter = 0
            for k = 1,flatParameters:nElement() do
                if maskParameters[k] == 0 then
                    counter = counter + 1
                    flatUsedParameters[counter] = flatParameters[counter+cumSumOfHoles[k]]
                end
            end
            assert (counter == nUsedParameters)
        end
        return flatUsedParameters
    end

    -- flatten parameters and gradients
    local flatParameters = flatten(parameters)
    local flatGradParameters = flatten(gradParameters)

    -- return new flat vector that contains all discrete parameters
    return flatParameters, flatGradParameters
end

function clone_list(tensor_list, zero_too)
    -- takes a list of tensors and returns a list of cloned tensors
    local out = {}
    for k,v in pairs(tensor_list) do
        out[k] = v:clone()
        if zero_too then out[k]:zero() end
    end
    return out
end

function lstm_utils.clone_model(model, T)
    -- model is the model class to be copied
    -- T is the number of copies
    -- returns a combination of models comb_model

    local comb_model = {}

    -- copy model params, and gradParams to local variables
    -- if not present, set them to {}
    local params, gradParams
    if model.parameters then
        params, gradParams = model:parameters()
        if params == nil then
            params = {}
        end
    end

    local paramsNoGrad
    if model.parametersNoGrad then
        paramsNoGrad = model:parametersNoGrad()
    end

    --create a local memory object for model for efficient multiple reading
    local mem = torch.MemoryFile("w"):binary()
    mem:writeObject(model)

    -- iterate over the T time steps and copy parameters
    for t=1,T do

        local reader = torch.MemoryFile(mem:storage(), "r"):binary()
        local model_clone = reader:readObject()
        reader:close()

        if model.parameters then
            local cloneParams, cloneGradParams = model_clone:parameters()
            local cloneParamsNoGrad
            for i = 1, #params do
                cloneParams[i]:set(params[i])
                cloneGradParams[i]:set(gradParams[i])
            end
            if paramsNoGrad then
                cloneParamsNoGrad = model_clone:parametersNoGrad()
                for i=1,#paramsNoGrad do
                    cloneParamsNoGrad[i]:set(paramsNoGrad[i])
                end
            end
        end

        comb_model[t] = model_clone
        collectgarbage()
    end

    -- close the write object
    mem:close()
    return comb_model
end

return lstm_utils


text:
<!DOCTYPE html>

    <title>Omdirigering/Redirect</title>
    <meta http-equiv="refresh" content="0; url=https://www.facebook.com/valforbundetavancez/" />

    Sidan är inte än skapad, för tillfället hänvisar vi till våran Facebook-sida

    ---

    This page does not yet exist, in the meantime we refer you to our Facebook page

redpajama_set_name: RedPajamaGithub


text:
<?php

declare(strict_types = 1);

namespace BrowserDetector\Version;

use Psr\Log\LoggerInterface;

final class RaspbianFactory implements RaspbianFactoryInterface
{
    public function __invoke(LoggerInterface $logger): Raspbian
    {
        return new Raspbian(
            $logger,
            new VersionFactory()
        );
    }
}


text:
package com.navercorp.pinpoint.web.dao.hbase;

import static org.mockito.Mockito.*;

import com.navercorp.pinpoint.common.hbase.TableNameProvider;
import com.navercorp.pinpoint.common.server.bo.AgentLifeCycleBo;
import com.navercorp.pinpoint.common.hbase.HbaseOperations2;
import com.navercorp.pinpoint.common.hbase.ResultsExtractor;
import com.navercorp.pinpoint.common.hbase.RowMapper;
import com.navercorp.pinpoint.common.server.util.AgentLifeCycleState;
import com.navercorp.pinpoint.web.dao.AgentLifeCycleDao;
import com.navercorp.pinpoint.web.vo.AgentInfo;
import com.navercorp.pinpoint.web.vo.AgentStatus;

import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Scan;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.Spy;

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

/**
 * @author HyunGil Jeong
 */
public class HbaseAgentLifeCycleDaoTest {

    @Mock
    private HbaseOperations2 hbaseOperations2;

    @Spy
    private TableNameProvider tableNameProvider = new TableNameProvider() {
        @Override
        public TableName getTableName(String tableName) {
            return TableName.valueOf(tableName);
        }
    };

    @Mock
    private RowMapper<AgentLifeCycleBo> agentLifeCycleMapper;

    @InjectMocks
    private AgentLifeCycleDao agentLifeCycleDao = new HbaseAgentLifeCycleDao();

    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void status_should_be_set_appropriately_if_status_is_known() {
        // Given
        final String expectedAgentId = "test-agent";
        final long expectedTimestamp = 1000L;
        final AgentLifeCycleState expectedAgentLifeCycleState = AgentLifeCycleState.RUNNING;

        final AgentLifeCycleBo scannedLifeCycleBo = createAgentLifeCycleBo(expectedAgentId, expectedTimestamp, expectedAgentLifeCycleState);
        when(this.hbaseOperations2.find(any(TableName.class), any(Scan.class), any(ResultsExtractor.class))).thenReturn(scannedLifeCycleBo);
        // When
        AgentStatus agentStatus = this.agentLifeCycleDao.getAgentStatus(expectedAgentId, expectedTimestamp);
        // Then
        Assert.assertEquals(expectedAgentId, agentStatus.getAgentId());
        Assert.assertEquals(expectedTimestamp, agentStatus.getEventTimestamp());
        Assert.assertEquals(expectedAgentLifeCycleState, agentStatus.getState());
    }

    @Test
    public void status_should_be_unknown_if_status_cannot_be_found() {
        // Given
        final String expectedAgentId = "test-agent";
        final long expectedTimestamp = 0L;
        final AgentLifeCycleState expectedAgentLifeCycleState = AgentLifeCycleState.UNKNOWN;

        final AgentLifeCycleBo scannedLifeCycleBo = null;
        when(this.hbaseOperations2.find(any(TableName.class), any(Scan.class), any(ResultsExtractor.class))).thenReturn(scannedLifeCycleBo);
        // When
        AgentStatus agentStatus = this.agentLifeCycleDao.getAgentStatus(expectedAgentId, expectedTimestamp);
        // Then
        Assert.assertEquals(expectedAgentId, agentStatus.getAgentId());
        Assert.assertEquals(expectedTimestamp, agentStatus.getEventTimestamp());
        Assert.assertEquals(expectedAgentLifeCycleState, agentStatus.getState());
    }

    @Test
    public void agentInfo_should_be_populated_appropriately_if_status_is_known() {
        // Given
        final String expectedAgentId = "test-agent";
        final long expectedTimestamp = 1000L;
        final AgentLifeCycleState expectedAgentLifeCycleState = AgentLifeCycleState.RUNNING;

        final AgentLifeCycleBo scannedLifeCycleBo = createAgentLifeCycleBo(expectedAgentId, expectedTimestamp, expectedAgentLifeCycleState);
        when(this.hbaseOperations2.find(any(TableName.class), any(Scan.class), any(ResultsExtractor.class))).thenReturn(scannedLifeCycleBo);
        // When
        AgentInfo givenAgentInfo = new AgentInfo();
        givenAgentInfo.setAgentId(expectedAgentId);
        givenAgentInfo.setStartTimestamp(expectedTimestamp);
        this.agentLifeCycleDao.populateAgentStatus(givenAgentInfo, expectedTimestamp);
        // Then
        AgentStatus actualAgentStatus = givenAgentInfo.getStatus();
        Assert.assertEquals(expectedAgentId, actualAgentStatus.getAgentId());
        Assert.assertEquals(expectedTimestamp, actualAgentStatus.getEventTimestamp());
        Assert.assertEquals(expectedAgentLifeCycleState, actualAgentStatus.getState());
    }

    @Test
    public void agentInfo_should_be_populated_as_unknown_if_status_cannot_be_found() {
        // Given
        final String expectedAgentId = "test-agent";
        final long expectedTimestamp = 0L;
        final AgentLifeCycleState expectedAgentLifeCycleState = AgentLifeCycleState.UNKNOWN;

        final AgentLifeCycleBo scannedLifeCycleBo = null;
        when(this.hbaseOperations2.find(any(TableName.class), any(Scan.class), any(ResultsExtractor.class))).thenReturn(scannedLifeCycleBo);

        AgentInfo givenAgentInfo = new AgentInfo();
        givenAgentInfo.setAgentId(expectedAgentId);
        givenAgentInfo.setStartTimestamp(expectedTimestamp);
        // When
        this.agentLifeCycleDao.populateAgentStatus(givenAgentInfo, expectedTimestamp);
        // Then
        AgentStatus actualAgentStatus = givenAgentInfo.getStatus();
        Assert.assertEquals(expectedAgentId, actualAgentStatus.getAgentId());
        Assert.assertEquals(expectedTimestamp, actualAgentStatus.getEventTimestamp());
        Assert.assertEquals(expectedAgentLifeCycleState, actualAgentStatus.getState());
    }

    @Test
    public void agentInfos_should_be_populated_accordingly_even_with_nulls() {
        // Given
        final String expectedAgentId = "test-agent";
        final long expectedTimestamp = 1000L;
        final AgentLifeCycleState expectedAgentLifeCycleState = AgentLifeCycleState.RUNNING;

        final AgentLifeCycleBo scannedLifeCycleBo = createAgentLifeCycleBo(expectedAgentId, expectedTimestamp, expectedAgentLifeCycleState);
        when(this.hbaseOperations2.findParallel(any(TableName.class), anyListOf(Scan.class), any(ResultsExtractor.class))).thenReturn(Arrays.asList(scannedLifeCycleBo, scannedLifeCycleBo));

        AgentInfo nonNullAgentInfo = new AgentInfo();
        nonNullAgentInfo.setAgentId(expectedAgentId);
        nonNullAgentInfo.setStartTimestamp(expectedTimestamp);
        AgentInfo nullAgentInfo = null;
        List<AgentInfo> givenAgentInfos = Arrays.asList(nonNullAgentInfo, nullAgentInfo, nonNullAgentInfo, nullAgentInfo);
        // When
        this.agentLifeCycleDao.populateAgentStatuses(givenAgentInfos, expectedTimestamp);
        // Then
        Assert.assertEquals(nonNullAgentInfo, givenAgentInfos.get(0));
        Assert.assertEquals(nullAgentInfo, givenAgentInfos.get(1));
        Assert.assertEquals(nonNullAgentInfo, givenAgentInfos.get(2));
        Assert.assertEquals(nullAgentInfo, givenAgentInfos.get(3));
        AgentStatus nonNullAgentInfoStatus = nonNullAgentInfo.getStatus();
        Assert.assertEquals(expectedAgentId, nonNullAgentInfoStatus.getAgentId());
        Assert.assertEquals(expectedTimestamp, nonNullAgentInfoStatus.getEventTimestamp());
        Assert.assertEquals(expectedAgentLifeCycleState, nonNullAgentInfoStatus.getState());
    }

    private AgentLifeCycleBo createAgentLifeCycleBo(String agentId, long eventTimestamp, AgentLifeCycleState state) {
        return new AgentLifeCycleBo(agentId, 0L, eventTimestamp, 0L, state);
    }
}


text:
//
//  LiveViewController.m
//  FFmpegTest
//
//  Created by zhaoyuan on 16/6/9.
//  Copyright © 2016年 times. All rights reserved.
//

#import "LiveViewController.h"
#import "ZYLivePreview.h"
#import "CommentView.h"

#import <POP.h>

@interface LiveViewController ()

@end

@implementation LiveViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    ZYLivePreview *liveview =[[ZYLivePreview alloc] initWithFrame:self.view.bounds];
    liveview.close = ^(){

        [self.navigationController popViewControllerAnimated:YES];

    };

    [self.view addSubview:liveview];

    CommentView *commentview =[CommentView initView];
    commentview.frame = self.view.bounds;
    [self.view addSubview:commentview];

//    UIImageView  *room_start_1=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 150, 150)];
//    [room_start_1 setImage:[ UIImage imageNamed:@"room_start_1"]];
//    room_start_1.tag = 10001;
//    [self.view addSubview:room_start_1];
//
//    UIImageView  *room_start_2=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 150, 150)];
//    [room_start_2 setImage:[ UIImage imageNamed:@"room_start_2"]];
//    room_start_2.tag = 10002;
//
//    [self.view addSubview:room_start_2];
//
//
//    UIImageView  *room_start_3=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 150, 150)];
//    [room_start_3 setImage:[ UIImage imageNamed:@"room_start_3"]];
//    room_start_3.tag = 10003;
//
//    [self.view addSubview:room_start_3];
//
//
//    room_start_1.center = room_start_2.center = room_start_3.center =self.view.center;
//    [self performSelector:@selector(start) withObject:nil afterDelay:2];

}

-(void)start{
    POPSpringAnimation *springAnimation = [POPSpringAnimation animationWithPropertyNamed:kPOPLayerBounds];
    springAnimation.springSpeed         = 0;                    // 设置动画速度(常用)
    springAnimation.springBounciness    = 20;                   // 设置弹性大小(常用)
    springAnimation.dynamicsFriction    = 10;                // 设置阻止弹性的阻力(选用)
    springAnimation.dynamicsTension     = 100;               // 设置弹性的张力(可以理解为每次变大的程度, 选用)
    springAnimation.toValue = [NSValue valueWithCGRect:CGRectMake(0, 0, 0, 0)];
    // 添加动画
    [[self.view viewWithTag:10003].layer pop_addAnimation:springAnimation forKey:nil];
    [[self.view viewWithTag:10003].layer pop_addAnimation:springAnimation forKey:nil];
    [[self.view viewWithTag:10003].layer pop_addAnimation:springAnimation forKey:nil];

}

- (UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation

 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end


text:
package org.gridkit.sjk.ssa.ui;

import java.awt.Dimension;

import javax.swing.JComponent;
import javax.swing.JScrollPane;

public class Stacker {

    public static JComponent scroll(JComponent comp, int width, int height) {
        JScrollPane pane = new JScrollPane(comp);
        pane.setPreferredSize(new Dimension(width, height));
        return pane;
    }
}


text:
<!DOCTYPE html>
<meta charset="utf-8">
<title>Declarative Shadow DOM</title>
<link rel="author" href="mailto:masonf@chromium.org">
<link rel="help" href="https://github.com/whatwg/dom/issues/831">

  <template shadowroot="open">
    <slot id="s1" name="slot1"></slot>
  </template>

  <template shadowroot="open">
    root 1
  </template>
  <template shadowroot="closed">
    root 2
  </template>

<template id="template-containing-shadow">

    <template shadowroot=open>Content</template>

</template>

<template id="template-containing-deep-shadow">

      <template shadowroot=open>Content</template>

</template>

<template id="template-containing-template">

    <template id="inner-template">

        <template shadowroot=open>Content</template>

    </template>

</template>

<template id="template-containing-ua-shadow">

    <template shadowroot=open>
      <video></video>
    </template>

</template>

<template id="template-containing-ua-shadow-closed">

    <template shadowroot=closed>
      <video></video>
    </template>

</template>

<template id="root-element-shadow">
    <template shadowroot=open>Content</template>
</template>


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model common\modules\sys_timezone\models\CountrySearch */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin([
        'action' => ['index'],
        'method' => 'get',
    ]); ?>

    <?= $form->field($model, 'id') ?>

    <?= $form->field($model, 'code') ?>

    <?= $form->field($model, 'name') ?>

    <?= $form->field($model, 'continent') ?>

    <?= $form->field($model, 'region') ?>

    <?php // echo $form->field($model, 'surface_area') ?>

    <?php // echo $form->field($model, 'indep_year') ?>

    <?php // echo $form->field($model, 'population') ?>

    <?php // echo $form->field($model, 'life_expectancy') ?>

    <?php // echo $form->field($model, 'gnp') ?>

    <?php // echo $form->field($model, 'gnpold') ?>

    <?php // echo $form->field($model, 'local_name') ?>

    <?php // echo $form->field($model, 'goverment_form') ?>

    <?php // echo $form->field($model, 'head_state') ?>

    <?php // echo $form->field($model, 'capital') ?>

    <?php // echo $form->field($model, 'iso_code') ?>

    <?php // echo $form->field($model, 'currency_data') ?>

    <?php // echo $form->field($model, 'numeric_code') ?>

    <?php // echo $form->field($model, 'phone_code') ?>

        <?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
        <?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>

    <?php ActiveForm::end(); ?>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Leafl. of Philipp. Bot. 6(105): 2274 (1914)

#### Original name
Phyllachora circinata var. sanguinea Rehm

### Remarks
null


text:
There is a different behavior of various plugins whether their name is absolute or relative, including:

1. mounting the same file somewhere else does not work
2. importing somewhere else (other than from where it was exported) does not work
   (See [here](https://github.com/ElektraInitiative/libelektra/issues/51))

## Constraints

- at least the dump plugin must be able to handle its old files

## Assumptions

- it still will be easy to support a workflow that exports/imports everything
- mounting across namespaces (user/system) does not make sense

## Considered Alternatives

- allow relative/absolute plugins and mark them what they are, tools (e.g. import/export) use this knowledge and react accordingly.
  This would still not solve problem 1.)

## Decision

Key names shall be relative to parent key name.

## Rationale

Provides a better import/export/remount and also a more uniform experience between different plugins.

## Implications

All plugins that had absolute paths were adapted, see [#51](https://issues.libelektra.org/51).

## Related Decisions

None

## Notes


text:
'use strict';

import { module } from 'angular';

import { SECURITY_GROUP_FILTER } from './filter/securityGroup.filter.component';
import { SECURITY_GROUP_DATA_SOURCE } from './securityGroup.dataSource';
import { SECURITY_GROUP_STATES } from './securityGroup.states';
import './securityGroupSearchResultType';

export const CORE_SECURITYGROUP_SECURITYGROUP_MODULE = 'spinnaker.core.securityGroup';
export const name = CORE_SECURITYGROUP_SECURITYGROUP_MODULE; // for backwards compatibility
module(CORE_SECURITYGROUP_SECURITYGROUP_MODULE, [
  SECURITY_GROUP_FILTER,
  SECURITY_GROUP_DATA_SOURCE,
  SECURITY_GROUP_STATES,
]);


text:
<?php

namespace Google\Service\Cloudchannel;

class GoogleCloudChannelV1alpha1DateRange extends \Google\Model
{
  protected $invoiceEndDateType = GoogleTypeDate::class;
  protected $invoiceEndDateDataType = '';
  protected $invoiceStartDateType = GoogleTypeDate::class;
  protected $invoiceStartDateDataType = '';
  protected $usageEndDateTimeType = GoogleTypeDateTime::class;
  protected $usageEndDateTimeDataType = '';
  protected $usageStartDateTimeType = GoogleTypeDateTime::class;
  protected $usageStartDateTimeDataType = '';

  /**
   * @param GoogleTypeDate
   */
  public function setInvoiceEndDate(GoogleTypeDate $invoiceEndDate)
  {
    $this->invoiceEndDate = $invoiceEndDate;
  }
  /**
   * @return GoogleTypeDate
   */
  public function getInvoiceEndDate()
  {
    return $this->invoiceEndDate;
  }
  /**
   * @param GoogleTypeDate
   */
  public function setInvoiceStartDate(GoogleTypeDate $invoiceStartDate)
  {
    $this->invoiceStartDate = $invoiceStartDate;
  }
  /**
   * @return GoogleTypeDate
   */
  public function getInvoiceStartDate()
  {
    return $this->invoiceStartDate;
  }
  /**
   * @param GoogleTypeDateTime
   */
  public function setUsageEndDateTime(GoogleTypeDateTime $usageEndDateTime)
  {
    $this->usageEndDateTime = $usageEndDateTime;
  }
  /**
   * @return GoogleTypeDateTime
   */
  public function getUsageEndDateTime()
  {
    return $this->usageEndDateTime;
  }
  /**
   * @param GoogleTypeDateTime
   */
  public function setUsageStartDateTime(GoogleTypeDateTime $usageStartDateTime)
  {
    $this->usageStartDateTime = $usageStartDateTime;
  }
  /**
   * @return GoogleTypeDateTime
   */
  public function getUsageStartDateTime()
  {
    return $this->usageStartDateTime;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(GoogleCloudChannelV1alpha1DateRange::class, 'Google_Service_Cloudchannel_GoogleCloudChannelV1alpha1DateRange');


text:
import hashlib
import os
from typing import Sequence, Union, overload

from . import crypto

class Shuffled(Sequence):
    """
    Randomized integer ranges

    :param range_size: Size of the range
    :type range_size: int
    :param seed: Seed to make randomization repeatable
    :type seed: bytes

    >>> shuffled_range = Shuffled(10)
    >>> list(shuffled_range)
    [4, 1, 2, 9, 8, 5, 3, 0, 6, 7]
    >>> same_shuffled_range = Shuffled(10, seed=shuffled_range.seed)
    >>> list(same_shuffled_range)
    [4, 1, 2, 9, 8, 5, 3, 0, 6, 7]
    """

    def __init__(self, range_size: int, seed: bytes = None) -> None:
        self._size = range_size

        if seed is None:
            self._seed = os.urandom(16 * 3)
        else:
            self._seed = seed
        material = hashlib.sha512(self.seed).digest()
        keys = [material[i : i + 16] for i in range(0, 3 * 16, 16)]
        randomizers = [crypto.AesRandomizer(key) for key in keys]
        self._encryptor = crypto.IndexEncryptor(randomizers, range_size)

    def __len__(self) -> int:
        return self._size

    @overload
    def __getitem__(self, index: int) -> int:
        ...

    @overload
    def __getitem__(self, index: slice) -> Sequence[int]:
        ...

    def __getitem__(self, index: Union[int, slice]) -> Union[int, Sequence[int]]:
        if isinstance(index, slice):
            raise NotImplementedError
        if index < 0 or index >= self._size:
            raise IndexError
        return self._encryptor.encrypt(index)

    @property
    def seed(self) -> bytes:
        """
        Seed of the randomization.

        It can be used to create a new identical :py:class:`Shuffled` object.
        """
        return self._seed


text:
import { moduleForModel, test } from 'ember-qunit';

moduleForModel('rental', 'Unit | Model | rental', {
  // Specify the other units that are required for this test.
  needs: []
});

test('it exists', function(assert) {
  let model = this.subject();
  // let store = this.store();
  assert.ok(!!model);
});


text:
FROM gcr.io/oss-fuzz-base/base-builder
MAINTAINER boxerab@gmail.com
RUN apt-get update && apt-get install -y wget

RUN git clone --depth 1 https://github.com/GrokImageCompression/grok.git grok
RUN git clone --depth 1 https://github.com/GrokImageCompression/grok-test-data.git grok/data
WORKDIR grok
COPY build.sh $SRC/


text:
package mixpanel

// http://play.golang.org/p/vd8qr3TGRz

import (
	"crypto/md5"
	"encoding/hex"
	"io/ioutil"
	"log"
	"sort"
	"strconv"
	"strings"
	"time"
)

const (
	// Endpoint const
	Endpoint string = "http://mixpanel.com/api"
	// RawEndpoint const
	RawEndpoint string = "http://data.mixpanel.com/api"
	// Version const
	Version string = "2.0"
	// Format const
	Format string = "json"
)

// Request object
type Request struct {
	Endpoint   string
	Method     string
	Parameters map[string]string
	Expire     string
	Signature  string
	Config
}

// Config ...
type Config struct {
	APIKey    string
	APISecret string
}

// ConfigureAuth takes a path for the mixpanel key and the secret key.
func (req *Request) ConfigureAuth(keypath string, secretpath string) {
	req.Config = Config{
		APIKey:    FileContents(keypath),
		APISecret: FileContents(secretpath),
	}
}

// NewRequest ...
func NewRequest() *Request {
	r := new(Request)
	r.Parameters = make(map[string]string)
	return r
}

// GenerateSignature ...
func (req *Request) GenerateSignature() {
	var hash []string
	param := make(map[string]string)
	param["api_key"] = req.APIKey
	param["format"] = Format
	param["expire"] = req.Expire

	// Add the all the endpoint specific parameters
	for key, value := range req.Parameters {
		param[key] = value
	}

	// Sort all the keys alphabetically and then append them to the 'to-be' hash string
	var keys []string
	for k := range param {
		keys = append(keys, k)
	}
	sort.Strings(keys)

	for _, k := range keys {
		kv := joinKeyValue(k, param[k])
		hash = append(hash, kv)
	}

	// Append api_secret and hash
	hash = append(hash, req.APISecret)
	joinedhash := strings.Join(hash, "")

	req.Signature = MD5Hash(joinedhash)
}

// CompileURL ...
func (req *Request) CompileURL(rawflag bool) string {
	var parts, params []string
	if rawflag {
		if len(req.Method) > 0 {
			parts = append(parts, RawEndpoint, Version, req.Endpoint, req.Method)
		} else {
			parts = append(parts, RawEndpoint, Version, req.Endpoint)
		}
	} else {
		if len(req.Method) > 0 {
			parts = append(parts, Endpoint, Version, req.Endpoint, req.Method)
		} else {
			parts = append(parts, Endpoint, Version, req.Endpoint)
		}
	}
	uri := strings.Join(parts, "/")
	uri += "/?"

	for key, value := range req.Parameters {
		kv := joinKeyValue(key, value)
		params = append(params, kv)
	}

	apikey := joinKeyValue("api_key", req.APIKey)
	expire := joinKeyValue("expire", req.Expire)
	format := joinKeyValue("format", Format)
	sig := joinKeyValue("sig", req.Signature)
	params = append(params, apikey, expire, format, sig)

	url := strings.Join(params, "&")

	uri += url
	return uri
}

func joinKeyValue(key string, value string) string {
	var slice []string
	slice = append(slice, key, value)
	kv := strings.Join(slice, "=")
	return kv
}

// CalculateExpiry expire is in seconds
func (req *Request) CalculateExpiry(expire int) string {
	return strconv.FormatInt(time.Now().Add(time.Duration(expire)*time.Second).UTC().Unix(), 10)
}

// MD5Hash returns a md5 hash of text.
func MD5Hash(text string) string {
	hasher := md5.New()
	hasher.Write([]byte(text))
	return hex.EncodeToString(hasher.Sum(nil))
}

//////////////
// REQUESTS //
//////////////

// CreateRequest is the base request function that is wrapped to make more convenient request functions.
func (req *Request) CreateRequest(raw bool, endpoint string, method string, expire int, params map[string]string) string {
	NewRequest()
	req.Endpoint = endpoint
	req.Method = method
	req.Expire = req.CalculateExpiry(expire)
	for key, value := range params {
		req.Parameters[key] = value
	}
	req.GenerateSignature()
	url := req.CompileURL(raw)
	return url
}

// GetEvents ...
func (req *Request) GetEvents(params map[string]string) string {
	return req.CreateRequest(false, "events", "", 600, params)
}

// GetEventsTop ...
func (req *Request) GetEventsTop(params map[string]string) string {
	return req.CreateRequest(false, "events", "top", 600, params)
}

// GetEventsNames ...
func (req *Request) GetEventsNames(params map[string]string) string {
	return req.CreateRequest(false, "events", "names", 600, params)
}

// GetRawData gets a raw data dump from mixpanel. Required parameters are `from_date`
// and `to_date`, they are both string and in the date format yyyy-mm-dd. Optional
// parameters are `event`, `where`, and `bucket`.
func (req *Request) GetRawData(params map[string]string) string {
	return req.CreateRequest(true, "export", "", 600, params)
}

////////////
//  Utils //
////////////

// FileContents reads out the contents of a file.
func FileContents(filename string) string {
	slurp, err := ioutil.ReadFile(filename)
	if err != nil {
		log.Fatalf("Error reading %q: %v", filename, err)
	}
	return strings.TrimSpace(string(slurp))
}


text:
@interface ChatGroupSetViewController : BaseSetViewController

- (instancetype)initWithTalkInfo:(GJGCChatFriendTalkModel *)talkInfo;

@end


text:
package jp.gr.java_conf.neko_daisuki.fsyscall.slave;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import jp.gr.java_conf.neko_daisuki.fsyscall.util.InvalidPathException;
import jp.gr.java_conf.neko_daisuki.fsyscall.util.PhysicalPath;
import jp.gr.java_conf.neko_daisuki.fsyscall.util.StringUtil;
import jp.gr.java_conf.neko_daisuki.fsyscall.util.VirtualPath;

public class FileMap {

    private static class Node {

        private PhysicalPath mDestination;
        private Map<String, Node> mNodes = new HashMap<String, Node>();

        public PhysicalPath walk(List<String> elems) throws InvalidPathException {
            return walk0(new PhysicalPath("/"), new LinkedList<String>(),
                         elems);
        }

        public void put(PhysicalPath dest, List<String> elems) {
            int size = elems.size();
            if (size == 0) {
                mDestination = dest;
                return;
            }

            String name = elems.get(0);
            List<String> rest = elems.subList(1, size);
            Node node = mNodes.get(name);
            if (node != null) {
                node.put(dest, rest);
                return;
            }

            Node newNode = new Node();
            newNode.put(dest, rest);
            mNodes.put(name, newNode);
        }

        public Collection<String> getNamesUnder(List<String> elems) {
            int size = elems.size();
            if (size == 0) {
                Collection<String> c = new HashSet<String>();
                for (String name: mNodes.keySet()) {
                    if (mNodes.get(name).mDestination != null) {
                        c.add(name);
                    }
                }
                return c;
            }

            Node node = mNodes.get(elems.get(0));
            return node != null ? node.getNamesUnder(elems.subList(1, size))
                                : new HashSet<String>();
        }

        private PhysicalPath walk0(PhysicalPath path, List<String> accum,
                                   List<String> elems) throws InvalidPathException {
            if (mDestination != null) {
                int size = elems.size();
                if (size == 0) {
                    return mDestination;
                }
                String name = elems.get(0);
                Node node = mNodes.get(name);
                if (node == null) {
                    return new PhysicalPath(mDestination, chain(elems));
                }
                List<String> newAccum = new LinkedList<String>();
                newAccum.add(name);
                List<String> rest = elems.subList(1, size);
                return node.walk0(mDestination, newAccum, rest);
            }

            int size = elems.size();
            if (size == 0) {
                return new PhysicalPath(path, chain(accum));
            }
            String name = elems.get(0);
            accum.add(name);
            List<String> rest = elems.subList(1, size);
            Node node = mNodes.get(name);
            if (node == null) {
                List<String> l = new LinkedList<String>();
                l.addAll(accum);
                l.addAll(rest);
                return new PhysicalPath(path, chain(l));
            }
            return node.walk0(path, accum, rest);
        }

        private String chain(List<String> elems) {
            StringBuilder buffer = new StringBuilder();
            String sep = "";
            for (String s: elems) {
                buffer.append(sep);
                buffer.append(s);
                sep = SEPARATOR;
            }
            return buffer.toString();
        }
    }

    private static final String SEPARATOR = "/";

    private Node mRootNode = new Node();

    public void put(PhysicalPath dest, VirtualPath src) {
        mRootNode.put(dest, listPathElements(src));
    }

    public PhysicalPath get(VirtualPath path) {
        try {
            return mRootNode.walk(listPathElements(path));
        }
        catch (InvalidPathException e) {
            String message = String.format("unexpected exception for %s", path);
            throw new Error(message, e);
        }
    }

    public Collection<String> getNamesUnder(VirtualPath path) {
        return mRootNode.getNamesUnder(listPathElements(path));
    }

    private List<String> listPathElements(VirtualPath path) {
        List<String> l = new LinkedList<String>();
        String[] sa = path.toString().split(SEPARATOR);
        int len = sa.length;
        for (int i = 1; i < len; i++) {
            l.add(sa[i]);
        }
        return l;
    }

    private static String makeResultMessage(boolean result, Object actual) {
        return result ? "OK" : String.format("NG (%s)", actual);
    }

    private static void test(String tag, FileMap fileMap, VirtualPath path,
                             PhysicalPath expected) {
        PhysicalPath actual = fileMap.get(path);
        String result = makeResultMessage(expected.equals(actual), actual);
        String fmt = "%s: path=%s, expected=%s: %s";
        String msg = String.format(fmt, tag, StringUtil.quote(path.toString()),
                                   StringUtil.quote(expected.toString()),
                                   result);
        System.out.println(msg);
    }

    private static void test(String tag, FileMap fileMap, String path,
                             String expected) {
        try {
            test(tag, fileMap, new VirtualPath(path),
                 new PhysicalPath(expected));
        }
        catch (InvalidPathException e) {
            e.printStackTrace();
        }
    }

    private static void test(PhysicalPath dest, VirtualPath src,
                             VirtualPath path, PhysicalPath expected) {
        String tag = String.format("test(dest=%s, src=%s)",
                                   StringUtil.quote(dest.toString()),
                                   StringUtil.quote(src.toString()));
        FileMap fileMap = new FileMap();
        fileMap.put(dest, src);
        test(tag, fileMap, path, expected);
    }

    private static void test(String dest, String src, String path,
                             String expected) {
        try {
            test(new PhysicalPath(dest), new VirtualPath(src),
                 new VirtualPath(path), new PhysicalPath(expected));
        }
        catch (InvalidPathException e) {
            e.printStackTrace();
        }
    }

    private static void test2(VirtualPath path, PhysicalPath expected)
                              throws InvalidPathException {
        FileMap fileMap = new FileMap();
        fileMap.put(new PhysicalPath("/foobar"), new VirtualPath("/"));
        fileMap.put(new PhysicalPath("/foobar/buzquux"),
                    new VirtualPath("/home"));
        test("test2", fileMap, path, expected);
    }

    private static void test2(String path, String expected) {
        try {
            test2(new VirtualPath(path), new PhysicalPath(expected));
        }
        catch (InvalidPathException e) {
            e.printStackTrace();
        }
    }

    private static void test3() {
        FileMap fileMap = new FileMap();
        try {
            fileMap.put(new PhysicalPath("/foobar"), new VirtualPath("/"));
            fileMap.put(new PhysicalPath("/foobar/usr/home"),
                        new VirtualPath("/home"));
            fileMap.put(new PhysicalPath("/foobar/usr/home/fsyscall/sdcard"),
                        new VirtualPath("/home/fsyscall/sdcard"));
            test("test3", fileMap, "/home/fsyscall/.local/share/fonts",
                 "/foobar/usr/home/fsyscall/.local/share/fonts");
        }
        catch (InvalidPathException e) {
            e.printStackTrace();
        }
    }

    private static void testGetNamesUnder(String tag, String path,
                                          String[] expected) {
        boolean result = false;
        Collection<String> actual = null;

        FileMap fileMap = new FileMap();
        try {
            String sdcardDir = "/hogehoge";
            fileMap.put(new PhysicalPath("/foobar/rootdir"),
                        new VirtualPath("/"));
            fileMap.put(new PhysicalPath(sdcardDir),
                        new VirtualPath("/usr/home/fugafuga/sdcard"));
            fileMap.put(new PhysicalPath("/foobar/rootdir/usr/home"),
                        new VirtualPath("/home"));
            fileMap.put(new PhysicalPath(sdcardDir),
                        new VirtualPath("/home/sdcard"));
            actual = fileMap.getNamesUnder(new VirtualPath(path));
            int n = expected.length;
            if (n == actual.size()) {
                Arrays.sort(expected);
                String[] a = actual.toArray(new String[0]);
                Arrays.sort(a);
                int i;
                for (i = 0; i < n; i++) {
                    if (!expected[i].equals(a[i])) {
                        break;
                    }
                }
                if (i == n) {
                    result = true;
                }
            }
        }
        catch (InvalidPathException e) {
            e.printStackTrace();
        }

        String msg = String.format("%s: %s",
                                   tag, makeResultMessage(result, actual));
        System.out.println(msg);
    }

    private static void test4() {
        testGetNamesUnder("test4", "/", new String[] { "home" });
    }

    private static void test5() {
        testGetNamesUnder("test5", "/hogehoge", new String[] {});
    }

    public static void main(String[] args) {
        test("/sdcard", "/home/fsyscall", "/home/fsyscall/dbus",
             "/sdcard/dbus");
        test("/sdcard", "/home/fsyscall", "/tmp", "/tmp");
        test("/foobar", "/", "/", "/foobar");
        test("/foobar", "/", "/hogehoge", "/foobar/hogehoge");
        test2("/", "/foobar");
        test2("/home", "/foobar/buzquux");
        test2("/home/hogehoge", "/foobar/buzquux/hogehoge");
        test2("/etc", "/foobar/etc");
        test3();
        test4();
        test5();
    }
}

/**
 * vim: tabstop=4 shiftwidth=4 expandtab softtabstop=4
 */


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using LightBDD.Core.Dependencies;
using LightBDD.Core.ExecutionContext;
using LightBDD.Core.ExecutionContext.Implementation;
using LightBDD.Core.Extensibility;
using LightBDD.Core.Extensibility.Execution;
using LightBDD.Core.Extensibility.Results;
using LightBDD.Core.Internals;
using LightBDD.Core.Metadata;
using LightBDD.Core.Metadata.Implementation;
using LightBDD.Core.Results;
using LightBDD.Core.Results.Implementation;
using LightBDD.Core.Results.Parameters;

namespace LightBDD.Core.Execution.Implementation
{
    internal class RunnableStep : IStep
    {
        private readonly RunnableStepContext _stepContext;
        private readonly MethodArgument[] _arguments;
        private readonly Func<Task> _decoratedStepMethod;
        private readonly StepResult _result;
        private readonly StepFunc _invocation;
        private readonly ExceptionCollector _exceptionCollector = new ExceptionCollector();
        private Func<Exception, bool> _shouldAbortSubStepExecutionFn = _ => true;
        private IDependencyContainer _subStepScope;
        public IStepResult Result => _result;
        public IStepInfo Info => Result.Info;
        public IDependencyResolver DependencyResolver => _stepContext.Container;
        public object Context => _stepContext.Context;

        public RunnableStep(RunnableStepContext stepContext, StepInfo info, StepDescriptor descriptor, MethodArgument[] arguments, IEnumerable<IStepDecorator> stepDecorators)
        {
            _stepContext = stepContext;
            _invocation = descriptor.StepInvocation;
            _arguments = arguments;
            _decoratedStepMethod = DecoratingExecutor.DecorateStep(this, RunStepAsync, stepDecorators);
            _result = new StepResult(info);
            UpdateNameDetails();
            ValidateDescriptor(descriptor);
        }

        public async Task ExecuteAsync()
        {
            var stepStartNotified = false;
            var watch = ExecutionTimeWatch.StartNew();
            try
            {
                StartStep();
                stepStartNotified = true;
                await _decoratedStepMethod.Invoke();
                UpdateStepStatus();
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
            finally
            {
                StopStep(watch, stepStartNotified);
            }
            ProcessExceptions();
        }

        private void ValidateDescriptor(StepDescriptor descriptor)
        {
            if (descriptor.IsValid)
                return;
            HandleException(descriptor.CreationException);
            ProcessExceptions(false);
        }

        private async Task InvokeSubStepsAsync(IStepResultDescriptor result)
        {
            var subSteps = InitializeComposite(result);

            if (!subSteps.Any())
                return;

            try
            {
                if (subSteps.Any(s => s.Result.ExecutionException != null))
                    throw new InvalidOperationException("Sub-steps initialization failed.");

                foreach (var subStep in subSteps)
                    await subStep.ExecuteAsync();
            }
            finally
            {
                _result.SetSubSteps(subSteps.Select(s => s.Result).ToArray());
            }
        }

        private RunnableStep[] InitializeComposite(IStepResultDescriptor result)
        {
            if (!(result is CompositeStepResultDescriptor compositeDescriptor))
                return Array.Empty<RunnableStep>();

            _subStepScope = _stepContext.Container.BeginScope(LifetimeScope.Local, compositeDescriptor.SubStepsContext.ScopeConfigurator);
            var subStepsContext = InstantiateSubStepsContext(compositeDescriptor.SubStepsContext, _subStepScope);
            try
            {
                return _stepContext.ProvideSteps(_result.Info, compositeDescriptor.SubSteps, subStepsContext, _subStepScope, $"{Info.GroupPrefix}{Info.Number}.", ShouldAbortSubStepExecution);
            }
            catch (Exception e)
            {
                throw new InvalidOperationException($"Sub-steps initialization failed: {e.Message}", e);
            }
        }

        private bool ShouldAbortSubStepExecution(Exception ex) => _shouldAbortSubStepExecutionFn(ex);

        private static object InstantiateSubStepsContext(ExecutionContextDescriptor contextDescriptor, IDependencyContainer container)
        {
            try
            {
                return contextDescriptor.ContextResolver(container);
            }
            catch (Exception e)
            {
                throw new InvalidOperationException($"Sub-steps context initialization failed: {e.Message}", e);
            }
        }

        private async Task RunStepAsync()
        {
            IStepResultDescriptor result;
            var ctx = AsyncStepSynchronizationContext.InstallNew();
            try
            {
                var args = PrepareArguments();
                try
                {
                    result = await _invocation.Invoke(Context, args);
                }
                finally
                {
                    CaptureParameterResults();
                }

                VerifyParameterResults();
            }
            catch (Exception e)
            {
                if (ScenarioExecutionException.TryWrap(e, out var wrapped))
                    throw wrapped;
                throw;
            }
            finally
            {
                UpdateNameDetails();
                ctx.RestoreOriginal();
                await ctx.WaitForTasksAsync();
            }

            await InvokeSubStepsAsync(result);
        }

        private void VerifyParameterResults()
        {
            var errors = _result.Parameters
                .Where(x => x.Details.VerificationStatus > ParameterVerificationStatus.Success)
                .Select(FormatErrorMessage)
                .ToArray();

            if (!errors.Any())
                return;

            throw new InvalidOperationException(string.Join(Environment.NewLine, errors));
        }

        private void CaptureParameterResults()
        {
            var results = new List<IParameterResult>();
            foreach (var argument in _arguments)
            {
                if (argument.Value is IComplexParameter complex)
                    results.Add(new ParameterResult(argument.RawName, complex.Details));
            }

            _result.SetParameters(results);
        }

        private static string FormatErrorMessage(IParameterResult result)
        {
            return $"Parameter '{result.Name}' verification failed: {result.Details.VerificationMessage?.Replace(Environment.NewLine, Environment.NewLine + "\t") ?? string.Empty}";
        }

        private object[] PrepareArguments()
        {
            return _arguments.Select(p => p.Value).ToArray();
        }

        private void UpdateStepStatus()
        {
            _result.SetStatus(_result.GetSubSteps().GetMostSevereOrNull()?.Status ?? ExecutionStatus.Passed);
        }

        private void ProcessExceptions(bool rethrowIfNeeded = true)
        {
            var exception = _exceptionCollector.CollectFor(_result.Status, _result.GetSubSteps());
            if (exception == null)
                return;

            _result.UpdateException(exception);
            if (rethrowIfNeeded && _stepContext.ShouldAbortSubStepExecution(exception))
                throw new StepExecutionException(exception, _result.Status);
        }

        private void StartStep()
        {
            ScenarioExecutionContext.Current.Get<CurrentStepProperty>().Stash(this);
            EvaluateParameters();
            _stepContext.ProgressNotifier.NotifyStepStart(_result.Info);
        }

        private void StopStep(ExecutionTimeWatch watch, bool stepStartNotified)
        {
            ScenarioExecutionContext.Current.Get<CurrentStepProperty>().RemoveCurrent(this);
            DisposeComposite();
            watch.Stop();
            _result.SetExecutionTime(watch.GetTime());
            _result.IncludeSubStepDetails();
            if (stepStartNotified)
                _stepContext.ProgressNotifier.NotifyStepFinished(_result);
        }

        private void DisposeComposite()
        {
            try
            {
                _subStepScope?.Dispose();
            }
            catch (Exception exception)
            {
                _stepContext.ExceptionProcessor.UpdateResultsWithException(_result.SetStatus, exception);
                _exceptionCollector.Capture(exception);
            }
        }

        private void HandleException(Exception exception)
        {
            switch (exception)
            {
                case StepExecutionException e:
                    _result.SetStatus(e.StepStatus);
                    break;
                case ScenarioExecutionException e when e.InnerException is StepBypassException:
                    _result.SetStatus(ExecutionStatus.Bypassed, exception.InnerException.Message);
                    break;
                case ScenarioExecutionException e:
                    _stepContext.ExceptionProcessor.UpdateResultsWithException(_result.SetStatus, e.InnerException);
                    _exceptionCollector.Capture(e);
                    break;
                default:
                    _stepContext.ExceptionProcessor.UpdateResultsWithException(_result.SetStatus, exception);
                    _exceptionCollector.Capture(exception);
                    break;
            }
        }

        private void EvaluateParameters()
        {
            foreach (var parameter in _arguments)
                parameter.Evaluate(Context);
            UpdateNameDetails();
        }

        private void UpdateNameDetails()
        {
            if (!_arguments.Any())
                return;

            _result.UpdateName(_arguments.Select(FormatStepParameter).ToArray());
        }

        private INameParameterInfo FormatStepParameter(MethodArgument p)
        {
            try
            {
                return p.FormatNameParameter();
            }
            catch (Exception e)
            {
                throw new InvalidOperationException($"Unable to format '{p.RawName}' parameter of step '{_result.Info}': {e.Message}");
            }
        }

        public void ConfigureExecutionAbortOnSubStepException(Func<Exception, bool> shouldAbortExecutionFn)
        {
            _shouldAbortSubStepExecutionFn = shouldAbortExecutionFn ?? throw new ArgumentNullException(nameof(shouldAbortExecutionFn));
        }

        public void Comment(string comment)
        {
            _result.AddComment(comment);
            _stepContext.ProgressNotifier.NotifyStepComment(_result.Info, comment);
        }

        public override string ToString()
        {
            return _result.ToString();
        }
    }
}


text:
using Maybe.BloomFilter;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using Xunit;

namespace Maybe.Test.BloomFilter
{
    public class ScalableBloomFilterTests
    {
        [Fact]
        [Trait("Category", "Unit")]
        public void Contains_WhenItemHasBeenAdded_ShouldReturnTrue()
        {
            var filter = new ScalableBloomFilter<int>(0.02);
            filter.Add(42);
            Assert.True(filter.Contains(42));
        }

        [Fact]
        [Trait("Category", "Unit")]
        public void Contains_WithFreshFilter_ShouldReturnFalse()
        {
            var filter = new ScalableBloomFilter<int>(0.02);
            Assert.False(filter.Contains(42));
        }

        [Fact]
        [Trait("Category", "Unit")]
        public void NumberFilters_WithThreeTimesFirstCapacity_ShouldBeTwo()
        {
            var filter = new ScalableBloomFilter<int>(0.02);
            for (var i = 0; i < 3*ScalableBloomFilter<int>.MinimumCapacity; i++)
            {
                filter.Add(i);
            }
            Assert.Equal(2, filter.NumberFilters);
        }

        [Fact]
        [Trait("Category", "Unit")]
        public void Contains_WhenItemHasBeenAdded_AndFilterHasBeenSerializedAndUnserialized_ShouldReturnTrue()
        {
            using (var stream = new MemoryStream())
            {
                var filterOld = new ScalableBloomFilter<int>(0.02);
                filterOld.Add(42);
                IFormatter formatter = new BinaryFormatter();
                formatter.Serialize(stream, filterOld);
                stream.Flush();
                stream.Position = 0;
                ScalableBloomFilter<int> filterNew = (ScalableBloomFilter<int>)formatter.Deserialize(stream);
                Assert.True(filterNew.Contains(42));
            }
        }
    }
}


text:
'use strict';

(function () {
	'use strict';

	var CANVAS = document.getElementById('myCanvas'),
	    CTX = CANVAS.getContext('2d');

	// Global settings
	var color = '#0095DD';

	// Ball settings
	var x = CANVAS.width / 2,
	    y = CANVAS.height - 30,
	    dx = 3,
	    dy = -3,
	    ballRadius = 10;

	// Paddle settings
	var paddleHeight = 10,
	    paddleWidth = 75,
	    paddleX = (CANVAS.width - paddleWidth) / 2,
	    paddleY = CANVAS.height - paddleHeight;

	// Control settings
	var rightPressed = false,
	    leftPressed = false;

	// Brick settings
	var brickRowCount = 3,
	    brickColumnCount = 5,
	    brickWidth = 75,
	    brickHeight = 20,
	    brickPadding = 10,
	    brickOffsetTop = 30,
	    brickOffsetLeft = 30,
	    bricks = [];

	// Score settings
	var score = 0;

	// Player Options
	var hardMode = true;

	// Draw bricks and animate
	generateBricks();
	draw();

	function draw() {
		CTX.clearRect(0, 0, CANVAS.width, CANVAS.height); // Redraw ball on each frame
		drawBall();
		drawPaddle();
		drawBricks();
		collisionDetection();
		drawScore();

		// Reverse direction when ball hits a boundary
		if (x + dx > CANVAS.width - ballRadius || x + dx < ballRadius) {
			dx = -dx;
		}
		if (y + dy < ballRadius) {
			dy = -dy;
		} else if (y + dy > CANVAS.height - ballRadius) {
			if (x > paddleX && x < paddleX + paddleWidth) {
				dy = -dy;
				if (hardMode) {
					dx = dx * 1.05; // speed up ball when it hits the paddle
					dy = dy * 1.05; // speed up ball when it hits the paddle
				}
			} else {
					alert('GAME OVER');
					document.location.reload();
				}
		}

		// Move paddle on keypress
		if (rightPressed && paddleX < CANVAS.width - paddleWidth) {
			paddleX += 7;
		} else if (leftPressed && paddleX > 0) {
			paddleX -= 7;
		}

		// Ball motion
		y += dy;
		x += dx;

		// Animation loop
		requestAnimationFrame(draw);
	}

	// Canvas rendering of ball
	function drawBall() {
		CTX.beginPath();
		CTX.arc(x, y, ballRadius, 0, Math.PI * 2);
		CTX.fillStyle = color;
		CTX.fill();
		CTX.closePath();
	}

	// Canvas rendering of paddle
	function drawPaddle() {
		CTX.beginPath();
		CTX.rect(paddleX, paddleY, paddleWidth, paddleHeight);
		CTX.fillStyle = color;
		CTX.fill();
		CTX.closePath();
	}

	// Draw bricks
	function drawBricks() {
		for (var i = 0; i < brickColumnCount; i++) {
			for (var j = 0; j < brickRowCount; j++) {
				// Only draw bricks if they have not been touched as indicated by "status"
				if (bricks[i][j].status === 1) {
					var brickX = i * (brickWidth + brickPadding) + brickOffsetLeft;
					var brickY = j * (brickHeight + brickPadding) + brickOffsetTop;
					bricks[i][j].x = brickX;
					bricks[i][j].y = brickY;
					CTX.beginPath();
					CTX.rect(brickX, brickY, brickWidth, brickHeight);
					CTX.fillStyle = color;
					CTX.fill();
					CTX.closePath();
				}
			}
		}
	}

	// Watch for keypress events to move paddle
	document.addEventListener('keydown', keyDownHandler, false);
	document.addEventListener('keyup', keyUpHandler, false);
	document.addEventListener("mousemove", mouseMoveHandler, false);

	function keyDownHandler(e) {
		if (e.keyCode == 39) {
			rightPressed = true;
		} else if (e.keyCode == 37) {
			leftPressed = true;
		}
	}
	function keyUpHandler(e) {
		if (e.keyCode == 39) {
			rightPressed = false;
		} else if (e.keyCode == 37) {
			leftPressed = false;
		}
	}
	function mouseMoveHandler(e) {
		var relativeX = e.clientX - CANVAS.offsetLeft;
		if (relativeX > 0 && relativeX < CANVAS.width) {
			paddleX = relativeX - paddleWidth / 2;
		}
	}

	// Fill bricks array according to rows and columns in the brick settings variables
	function generateBricks() {
		for (var i = 0; i < brickColumnCount; i++) {
			bricks[i] = [];
			for (var j = 0; j < brickRowCount; j++) {
				bricks[i][j] = {
					x: 0,
					y: 0,
					status: 1
				};
			}
		}
	}

	// Collision detection
	function collisionDetection() {
		for (var i = 0; i < brickColumnCount; i++) {
			for (var j = 0; j < brickRowCount; j++) {
				var brick = bricks[i][j];
				if (brick.status === 1) {
					if (x > brick.x && x < brick.x + brickWidth && y > brick.y && y < brick.y + brickHeight) {
						dy = -dy; // Reverse direction
						brick.status = 0; // Remove brick
						score++;
						if (score == brickRowCount * brickColumnCount) {
							alert('YOU WIN, CONGRATULATIONS!');
							document.location.reload();
						}
					}
				}
			}
		}
	}

	// Displaying the score
	function drawScore() {
		CTX.font = '16px Arial';
		CTX.fillStyle = color;
		CTX.fillText('Score: ' + score, 8, 20);
	}
})();


text:
using Drunkler.Web.MessageHandlers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace Drunkler.Web
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            config.MessageHandlers.Add(new HomeCinemaAuthHandler());

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}


text:
module Nyauth
  module ClientConcern
    extend ActiveSupport::Concern
    included do |base|
      helper_method :client_class
      helper_method :client_name
    end

    def initialize
      @client_classes = {}
      super
    end

    private

    def mounted_path
      request.script_name.presence || "/#{request.path.split('/').try(:second)}"
    end

    # specify client class from mounted_path
    def client_class
      @client_classes[mounted_path] ||= mounted_path[1..-1].classify.constantize
    rescue
      @client_classes[mounted_path] = User
    end

    def client_name
      client_class.name.underscore.to_sym
    end
  end
end


text:
import DataObjectsAmount from './DataObjectsAmount';

export default DataObjectsAmount;


text:
require 'helper'

describe "LinkedIn::Client" do

  let(:client) do
    key    = ENV['LINKED_IN_CONSUMER_KEY'] || '1234'
    secret = ENV['LINKED_IN_CONSUMER_SECRET'] || '1234'
    LinkedIn::Client.new(key, secret)
  end

  describe "#consumer" do
    describe "default oauth options" do
      let(:consumer) { client.consumer }

      it "should return a configured OAuth consumer" do
        consumer.site.should == 'https://api.linkedin.com'
        consumer.request_token_url.should == 'https://api.linkedin.com/uas/oauth/requestToken'
        consumer.access_token_url.should == 'https://api.linkedin.com/uas/oauth/accessToken'
        consumer.authorize_url.should == 'https://www.linkedin.com/uas/oauth/authorize'
      end
    end

    describe "proxy oauth options" do
      let(:proxy) { "http://dummy.proxy" }
      let(:consumer) do
        LinkedIn::Client.new('1234', '1234', {
          :proxy => proxy,
        }).consumer
      end

      it "should send requests though proxy" do
        consumer.proxy.should eq proxy
      end
    end

    describe "different api and auth hosts options" do
      let(:consumer) do
        LinkedIn::Client.new('1234', '1234', {
          :api_host => 'https://api.josh.com',
          :auth_host => 'https://www.josh.com'
        }).consumer
      end

      it "should return a configured OAuth consumer" do
        consumer.site.should == 'https://api.josh.com'
        consumer.request_token_url.should == 'https://api.josh.com/uas/oauth/requestToken'
        consumer.access_token_url.should == 'https://api.josh.com/uas/oauth/accessToken'
        consumer.authorize_url.should == 'https://www.josh.com/uas/oauth/authorize'
      end
    end

    describe "different oauth paths" do
      let(:consumer) do
        LinkedIn::Client.new('1234', '1234', {
          :request_token_path => "/secure/oauth/requestToken",
          :access_token_path  => "/secure/oauth/accessToken",
          :authorize_path     => "/secure/oauth/authorize",
        }).consumer
      end

      it "should return a configured OAuth consumer" do
        consumer.site.should == 'https://api.linkedin.com'
        consumer.request_token_url.should == 'https://api.linkedin.com/secure/oauth/requestToken'
        consumer.access_token_url.should == 'https://api.linkedin.com/secure/oauth/accessToken'
        consumer.authorize_url.should == 'https://www.linkedin.com/secure/oauth/authorize'
      end
    end

    describe "specify oauth urls" do
      let(:consumer) do
        LinkedIn::Client.new('1234', '1234', {
          :request_token_url => "https://api.josh.com/secure/oauth/requestToken",
          :access_token_url  => "https://api.josh.com/secure/oauth/accessToken",
          :authorize_url     => "https://www.josh.com/secure/oauth/authorize",
        }).consumer
      end

      it "should return a configured OAuth consumer" do
        consumer.site.should == 'https://api.linkedin.com'
        consumer.request_token_url.should == 'https://api.josh.com/secure/oauth/requestToken'
        consumer.access_token_url.should == 'https://api.josh.com/secure/oauth/accessToken'
        consumer.authorize_url.should == 'https://www.josh.com/secure/oauth/authorize'
      end
    end

    describe "use the :site option to specify the host of all oauth urls" do
      let(:consumer) do
        LinkedIn::Client.new('1234', '1234', {
          :site => "https://api.josh.com"
        }).consumer
      end

      it "should return a configured OAuth consumer" do
        consumer.site.should == 'https://api.josh.com'
        consumer.request_token_url.should == 'https://api.josh.com/uas/oauth/requestToken'
        consumer.access_token_url.should == 'https://api.josh.com/uas/oauth/accessToken'
        consumer.authorize_url.should == 'https://api.josh.com/uas/oauth/authorize'
      end
    end
  end

  describe "#request_token" do
    describe "with default options" do
      use_vcr_cassette :record => :new_episodes

      it "should return a valid request token" do
        request_token = client.request_token

        request_token.should be_a_kind_of OAuth::RequestToken
        request_token.authorize_url.should include("https://www.linkedin.com/uas/oauth/authorize?oauth_token=")

        a_request(:post, "https://api.linkedin.com/uas/oauth/requestToken").should have_been_made.once
      end
    end

    describe "with a callback url" do
      use_vcr_cassette :record => :new_episodes

      it "should return a valid access token" do
        request_token = client.request_token(:oauth_callback => 'http://www.josh.com')

        request_token.should be_a_kind_of OAuth::RequestToken
        request_token.authorize_url.should include("https://www.linkedin.com/uas/oauth/authorize?oauth_token=")
        request_token.callback_confirmed?.should == true

        a_request(:post, "https://api.linkedin.com/uas/oauth/requestToken").should have_been_made.once
      end
    end
  end

  describe "#authorize_from_request" do
    let(:access_token) do
      # if you remove the related casssette you will need to do the following
      # authorize_from_request request manually
      #
      # request_token = client.request_token
      # puts "token    : #{request_token.token} - secret #{request_token.secret}"
      # puts "auth url : #{request_token.authorize_url}"
      # raise 'keep note of the token and secret'
      #
      client.authorize_from_request('dummy-token', 'dummy-secret', 'dummy-pin')
    end

    use_vcr_cassette :record => :new_episodes, :match_requests_on => [:uri, :method]

    it "should return a valid access token" do
      access_token.should be_a_kind_of Array
      access_token[0].should be_a_kind_of String
      access_token[1].should be_a_kind_of String

      a_request(:post, "https://api.linkedin.com/uas/oauth/accessToken").should have_been_made.once
    end
  end

  describe "#access_token" do
    let(:access_token) do
      client.authorize_from_access('dummy-token', 'dummy-secret')
      client.access_token
    end

    it "should return a valid auth token" do
      access_token.should be_a_kind_of OAuth::AccessToken
      access_token.token.should be_a_kind_of String
    end
  end

  describe "#authorize_from_access" do
    let(:auth_token) do
      client.authorize_from_access('dummy-token', 'dummy-secret')
    end

    it "should return a valid auth token" do
      auth_token.should be_a_kind_of Array
      auth_token[0].should be_a_kind_of String
      auth_token[1].should be_a_kind_of String
    end
  end

end


text:
/* ###
 * IP: GHIDRA
 *
 * Licensed 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.
 */
package docking.widgets.textfield;

import java.text.Format;
import java.text.ParseException;
import java.util.HashSet;
import java.util.Set;

import javax.swing.text.DocumentFilter;

import ghidra.util.NumericUtilities;

public class HexIntegerFormatter extends IntegerFormatter {

	public HexIntegerFormatter() {
		setValueClass(Long.class);
	}

	@Override
	protected DocumentFilter createDocumentFilter() {
		return new HexAllowedPositiveValueIntgerDocumentFilterWrapper(getFormat(),
			getOriginalDocumentFilter());
	}

	@Override
	public Object stringToValue(String text) throws ParseException {
		Long asLong = null;
		try {
			asLong = NumericUtilities.parseHexLong(text);
		}
		catch (NumberFormatException nfe) {
			ParseException parseException =
				new ParseException("Cannot parse string to a long: \"" + text + "\"", 0);
			parseException.initCause(nfe);
			throw parseException;
		}

		return super.stringToValue(asLong.toString());
	}

	/**
	 * Overridden to translate the internal value to a hex representation.
	 */
	@Override
	public String valueToString(Object value) throws ParseException {
		String valueString = super.valueToString(value);
		if ("".equals(valueString)) {
			return valueString;
		}
		return Long.toHexString(Long.valueOf(valueString));
	}

	protected static class HexAllowedPositiveValueIntgerDocumentFilterWrapper extends
			PosiviteValueIntegerDocumentFilterWrapper {

		private Set<Character> hexCharacterSet = new HashSet<Character>();

		HexAllowedPositiveValueIntgerDocumentFilterWrapper(Format format,
				DocumentFilter wrappedFilter) {
			super(format, wrappedFilter);

			hexCharacterSet.add('a');
			hexCharacterSet.add('A');
			hexCharacterSet.add('b');
			hexCharacterSet.add('B');
			hexCharacterSet.add('c');
			hexCharacterSet.add('C');
			hexCharacterSet.add('d');
			hexCharacterSet.add('D');
			hexCharacterSet.add('e');
			hexCharacterSet.add('E');
			hexCharacterSet.add('f');
			hexCharacterSet.add('F');
		}

		@Override
		protected boolean isDigit(char character) {
			if (super.isDigit(character)) {
				return true;
			}
			return hexCharacterSet.contains(character);
		}

		@Override
		protected Number parseText(String text) {
			// our formatter used in super.parseText() doesn't properly parse long values that
			// are too big, so we must do it ourselves

			try {
				return Long.parseLong(text, 16);
			}
			catch (NumberFormatException nfe) {
				return null;
			}
		}
	}
}


text:
package de.plushnikov.builder.simple;

public class BuilderAtConstructorSimple {
    private int myInt;
    private String myString;

    @lombok.Builder
    public BuilderAtConstructorSimple(int myInt, String myString) {
        this.myInt = myInt + 1;
        this.myString = myString;
    }

    public static void main(String[] args) {
        BuilderAtConstructorSimple builderSimple = BuilderAtConstructorSimple.builder().myInt(123).myString("string").build();
        System.out.println(builderSimple);
    }
}


text:
package com.github.albertopeam.infrastructure.exceptions;

import android.arch.lifecycle.Lifecycle;
import android.arch.lifecycle.LifecycleOwner;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import com.github.albertopeam.infrastructure.concurrency.UseCase;

/**
 * Created by Alberto Penas Amor on 28/05/2017.
 *
 * This interface provides a way of handle Exceptions raised during the execution of
 * {@link UseCase}, it returns an
 * {@link HandledException} that can recover from the handled Exception.
 */

public interface ExceptionController {
    /**
     * Handles an Exception.
     * @param exception to be handled
     * @return an HandledException representing how we can recover from the handled Exception
     */
    HandledException handle(@NonNull Exception exception);
}


text:
package com.battlelancer.seriesguide.backend;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.preference.PreferenceManager;
import com.battlelancer.seriesguide.backend.settings.HexagonSettings;
import com.battlelancer.seriesguide.items.SearchResult;
import com.battlelancer.seriesguide.provider.SeriesGuideContract;
import com.battlelancer.seriesguide.sync.SgSyncAdapter;
import com.battlelancer.seriesguide.util.EpisodeTools;
import com.battlelancer.seriesguide.util.MovieTools;
import com.battlelancer.seriesguide.util.ShowTools;
import com.battlelancer.seriesguide.util.TaskManager;
import com.battlelancer.seriesguide.util.Utils;
import com.google.android.gms.auth.GoogleAuthException;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.extensions.android.json.AndroidJsonFactory;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.uwetrottmann.androidutils.AndroidUtils;
import com.uwetrottmann.seriesguide.backend.account.Account;
import com.uwetrottmann.seriesguide.backend.episodes.Episodes;
import com.uwetrottmann.seriesguide.backend.movies.Movies;
import com.uwetrottmann.seriesguide.backend.shows.Shows;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import timber.log.Timber;

/**
 * Handles credentials and services for interacting with Hexagon.
 */
public class HexagonTools {

    private static GoogleAccountCredential sAccountCredential;

    private static final JsonFactory JSON_FACTORY = new AndroidJsonFactory();
    private static final HttpTransport HTTP_TRANSPORT = AndroidHttp.newCompatibleTransport();

    private static Shows sShowsService;
    private static Episodes sEpisodesService;
    private static Movies sMoviesService;

    /**
     * Creates and returns a new instance for this hexagon service.
     */
    public static synchronized Account buildAccountService(Context context) {
        Account.Builder builder = new Account.Builder(
                HTTP_TRANSPORT, JSON_FACTORY, getAccountCredential(context)
        );
        return CloudEndpointUtils.updateBuilder(builder).build();
    }

    /**
     * Returns the instance for this hexagon service.
     */
    public static synchronized Shows getShowsService(Context context) {
        if (sShowsService == null) {
            Shows.Builder builder = new Shows.Builder(
                    HTTP_TRANSPORT, JSON_FACTORY, getAccountCredential(context)
            );
            sShowsService = CloudEndpointUtils.updateBuilder(builder).build();
        }
        return sShowsService;
    }

    /**
     * Returns the instance for this hexagon service.
     */
    public static synchronized Episodes getEpisodesService(Context context) {
        if (sEpisodesService == null) {
            Episodes.Builder builder = new Episodes.Builder(
                    HTTP_TRANSPORT, JSON_FACTORY, getAccountCredential(context)
            );
            sEpisodesService = CloudEndpointUtils.updateBuilder(builder).build();
        }
        return sEpisodesService;
    }

    /**
     * Returns the instance for this hexagon service.
     */
    public static synchronized Movies getMoviesService(Context context) {
        if (sMoviesService == null) {
            Movies.Builder builder = new Movies.Builder(
                    HTTP_TRANSPORT, JSON_FACTORY, getAccountCredential(context)
            );
            sMoviesService = CloudEndpointUtils.updateBuilder(builder).build();
        }
        return sMoviesService;
    }

    /**
     * Checks if it is possible to retrieve a valid OAuth2 token for the given account, hence, it
     * can be used for connecting to Hexagon.
     */
    public static boolean validateAccount(Context context, String accountName) {
        GoogleAccountCredential credential = GoogleAccountCredential.usingAudience(
                context.getApplicationContext(), HexagonSettings.AUDIENCE);
        credential.setSelectedAccountName(accountName);

        try {
            credential.getToken();
        } catch (IOException | GoogleAuthException e) {
            Timber.e(e, "validateAccount: failed to get valid OAuth2 token.");
            return false;
        }

        return true;
    }

    /**
     * Gets the account credentials used for talking with Hexagon.
     */
    public synchronized static GoogleAccountCredential getAccountCredential(Context context) {
        if (sAccountCredential == null) {
            GoogleAccountCredential credential = GoogleAccountCredential.usingAudience(
                    context.getApplicationContext(), HexagonSettings.AUDIENCE);
            credential.setSelectedAccountName(HexagonSettings.getAccountName(context));
            sAccountCredential = credential;
        }
        return sAccountCredential;
    }

    /**
     * Sets the account name used for calls to Hexagon.
     */
    public static void storeAccountName(Context context, String accountName) {
        // store account name in settings
        PreferenceManager.getDefaultSharedPreferences(context)
                .edit()
                .putString(HexagonSettings.KEY_ACCOUNT_NAME, accountName)
                .commit();

        // ensure account
        GoogleAccountCredential credential = getAccountCredential(context);
        credential.setSelectedAccountName(accountName);
    }

    /**
     * Returns true if an account for Hexagon is set and the user is allowed to use Hexagon (has
     * access to X).
     */
    public static boolean isSignedIn(Context context) {
        return Utils.hasAccessToX(context)
                && getAccountCredential(context).getSelectedAccountName() != null;
    }

    /**
     * Syncs episodes, shows and movies with Hexagon.
     *
     * <p> Merges shows, episodes and movies after a sign-in. Consecutive syncs will only download
     * changes to shows, episodes and movies.
     */
    public static boolean syncWithHexagon(Context context, HashSet<Integer> existingShows,
            HashMap<Integer, SearchResult> newShows) {
        Timber.d("syncWithHexagon: syncing...");

        //// EPISODES
        boolean syncEpisodesSuccessful = syncEpisodes(context);
        Timber.d("syncWithHexagon: episode sync "
                + (syncEpisodesSuccessful ? "SUCCESSFUL" : "FAILED"));

        //// SHOWS
        boolean syncShowsSuccessful = syncShows(context, existingShows, newShows);
        Timber.d("syncWithHexagon: show sync " + (syncShowsSuccessful ? "SUCCESSFUL" : "FAILED"));

        //// MOVIES
        boolean syncMoviesSuccessful = syncMovies(context);
        Timber.d("syncWithHexagon: movie sync " + (syncMoviesSuccessful ? "SUCCESSFUL" : "FAILED"));

        Timber.d("syncWithHexagon: syncing...DONE");
        return syncEpisodesSuccessful && syncShowsSuccessful && syncMoviesSuccessful;
    }

    private static boolean syncEpisodes(Context context) {
        // get shows that need episode merging
        Cursor query = context.getContentResolver().query(SeriesGuideContract.Shows.CONTENT_URI,
                new String[] { SeriesGuideContract.Shows._ID },
                SeriesGuideContract.Shows.HEXAGON_MERGE_COMPLETE + "=0",
                null, null);
        if (query == null) {
            return false;
        }

        // try merging episodes for them
        boolean mergeSuccessful = true;
        while (query.moveToNext()) {
            // abort if connection is lost
            if (!AndroidUtils.isNetworkConnected(context)) {
                return false;
            }

            int showTvdbId = query.getInt(0);

            boolean success = EpisodeTools.Download.flagsFromHexagon(context, showTvdbId);
            if (!success) {
                // try again next time
                mergeSuccessful = false;
                continue;
            }

            success = EpisodeTools.Upload.flagsToHexagon(context, showTvdbId);
            if (success) {
                // set merge as completed
                ContentValues values = new ContentValues();
                values.put(SeriesGuideContract.Shows.HEXAGON_MERGE_COMPLETE, true);
                context.getContentResolver()
                        .update(SeriesGuideContract.Shows.buildShowUri(showTvdbId), values,
                                null, null);
            } else {
                mergeSuccessful = false;
            }
        }
        query.close();

        // download changed episodes and update properties on existing episodes
        boolean changedDownloadSuccessful = EpisodeTools.Download.flagsFromHexagon(context);

        return mergeSuccessful && changedDownloadSuccessful;
    }

    private static boolean syncShows(Context context, HashSet<Integer> existingShows,
            HashMap<Integer, SearchResult> newShows) {
        boolean hasMergedShows = HexagonSettings.hasMergedShows(context);

        // download shows and apply property changes (if merging only overwrite some properties)
        boolean downloadSuccessful = ShowTools.Download.fromHexagon(context, existingShows,
                newShows, hasMergedShows);
        if (!downloadSuccessful) {
            return false;
        }

        // if merge required, upload all shows to Hexagon
        if (!hasMergedShows) {
            boolean uploadSuccessful = ShowTools.Upload.toHexagon(context);
            if (!uploadSuccessful) {
                return false;
            }
        }

        // add new shows
        if (newShows.size() > 0) {
            List<SearchResult> newShowsList = new LinkedList<>(newShows.values());
            TaskManager.getInstance(context).performAddTask(newShowsList, true, !hasMergedShows);
        } else if (!hasMergedShows) {
            // set shows as merged
            HexagonSettings.setHasMergedShows(context, true);
        }

        return true;
    }

    private static boolean syncMovies(Context context) {
        boolean hasMergedMovies = HexagonSettings.hasMergedMovies(context);

        // download movies and apply property changes, build list of new movies
        Set<Integer> newCollectionMovies = new HashSet<>();
        Set<Integer> newWatchlistMovies = new HashSet<>();
        boolean downloadSuccessful = MovieTools.Download.fromHexagon(context, newCollectionMovies,
                newWatchlistMovies, hasMergedMovies);
        if (!downloadSuccessful) {
            return false;
        }

        if (!hasMergedMovies) {
            boolean uploadSuccessful = MovieTools.Upload.toHexagon(context);
            if (!uploadSuccessful) {
                return false;
            }
        }

        // add new movies with the just downloaded properties
        SgSyncAdapter.UpdateResult result = MovieTools.Download.addMovies(context,
                newCollectionMovies, newWatchlistMovies);
        boolean addingSuccessful = result == SgSyncAdapter.UpdateResult.SUCCESS;
        if (!hasMergedMovies) {
            // ensure all missing movies from Hexagon are added before merge is complete
            if (!addingSuccessful) {
                return false;
            }
            // set movies as merged
            PreferenceManager.getDefaultSharedPreferences(context)
                    .edit()
                    .putBoolean(HexagonSettings.KEY_MERGED_MOVIES, true)
                    .commit();
        }

        return addingSuccessful;
    }
}


text:
<?php

namespace Magento\Reports\Test\TestCase;

use Magento\Catalog\Test\Fixture\CatalogProductSimple;
use Magento\Catalog\Test\Page\Category\CatalogCategoryView;
use Magento\Catalog\Test\Page\Product\CatalogProductView;
use Magento\Cms\Test\Page\CmsIndex;
use Magento\Customer\Test\Fixture\Customer;
use Magento\Customer\Test\Page\CustomerAccountLogout;
use Magento\Reports\Test\Page\Adminhtml\ProductReportReview;
use Magento\Review\Test\Fixture\Review;
use Magento\Mtf\Client\BrowserInterface;
use Magento\Mtf\Fixture\FixtureFactory;
use Magento\Mtf\TestCase\Injectable;

/**
 * Preconditions:
 * 1. Create customer
 * 2. Create simple product
 * 3. Open Product created in preconditions
 * 4. Click "Be the first to review this product "
 * 5. Fill data according to DataSet
 * 6. Click Submit review
 *
 * Steps:
 * 1. Open Reports -> Review : By Customers
 * 2. Assert Reviews qty
 * 3. Click Show Reviews
 * 4. Perform appropriate assertions.
 *
 * @group Reports_(MX)
 * @ZephyrId MAGETWO-27555
 *
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
 */
class CustomerReviewReportEntityTest extends Injectable
{
    /* tags */
    const MVP = 'no';
    const DOMAIN = 'MX';
    /* end tags */

    /**
     * Customer frontend logout page
     *
     * @var CustomerAccountLogout
     */
    protected $customerAccountLogout;

    /**
     * Product reviews report page
     *
     * @var ProductReportReview
     */
    protected $productReportReview;

    /**
     * Frontend product view page
     *
     * @var CatalogProductView
     */
    protected $pageCatalogProductView;

    /**
     * Cms Index page
     *
     * @var CmsIndex
     */
    protected $cmsIndex;

    /**
     * Catalog Category page
     *
     * @var CatalogCategoryView
     */
    protected $catalogCategoryView;

    /**
     * Prepare data
     *
     * @param FixtureFactory $fixtureFactory
     * @return array
     */
    public function __prepare(FixtureFactory $fixtureFactory)
    {
        $customer = $fixtureFactory->createByCode('customer', ['dataset' => 'johndoe_unique']);
        $customer->persist();

        return ['customer' => $customer];
    }

    /**
     * Preparing pages for test
     *
     * @param ProductReportReview $productReportReview
     * @param CatalogProductView $pageCatalogProductView
     * @param CmsIndex $cmsIndex
     * @param CatalogCategoryView $catalogCategoryView
     * @param CustomerAccountLogout $customerAccountLogout
     * @return void
     */
    public function __inject(
        ProductReportReview $productReportReview,
        CatalogProductView $pageCatalogProductView,
        CmsIndex $cmsIndex,
        CatalogCategoryView $catalogCategoryView,
        CustomerAccountLogout $customerAccountLogout
    ) {
        $this->productReportReview = $productReportReview;
        $this->pageCatalogProductView = $pageCatalogProductView;
        $this->cmsIndex = $cmsIndex;
        $this->catalogCategoryView = $catalogCategoryView;
        $this->customerAccountLogout = $customerAccountLogout;
    }

    /**
     * Test Creation for CustomerReviewReportEntity
     *
     * @param Review $review
     * @param Customer $customer
     * @param $customerLogin
     * @param CatalogProductSimple $product
     * @param BrowserInterface $browser
     * @return array
     *
     * @SuppressWarnings(PHPMD.ConstructorWithNameAsEnclosingClass)
     */
    public function test(
        Review $review,
        Customer $customer,
        CatalogProductSimple $product,
        BrowserInterface $browser,
        $customerLogin
    ) {
        // Preconditions
        $product->persist();
        $this->cmsIndex->open();
        if ($customerLogin == 'Yes') {
            $this->objectManager->create(
                'Magento\Customer\Test\TestStep\LoginCustomerOnFrontendStep',
                ['customer' => $customer]
            )->run();
        }
        // Steps
        $browser->open($_ENV['app_frontend_url'] . $product->getUrlKey() . '.html');
        $this->pageCatalogProductView->getReviewSummary()->getAddReviewLink()->click();
        $this->pageCatalogProductView->getReviewFormBlock()->fill($review);
        $this->pageCatalogProductView->getReviewFormBlock()->submit();

        return ['product' => $product];
    }

    /**
     * Logout customer from frontend account
     *
     * return void
     */
    public function tearDown()
    {
        $this->customerAccountLogout->open();
    }
}


text:
.class Lcom/xiaomi/auth/b;
.super Ljava/lang/Object;

# interfaces
.implements Landroid/content/ServiceConnection;

# instance fields
.field private final synthetic a:Landroid/accounts/Account;

.field private final synthetic b:Landroid/os/Bundle;

.field private final synthetic c:Lcom/xiaomi/auth/f;

# direct methods
.method constructor <init>(Landroid/accounts/Account;Landroid/os/Bundle;Lcom/xiaomi/auth/f;)V
    .locals 0

    iput-object p1, p0, Lcom/xiaomi/auth/b;->a:Landroid/accounts/Account;

    iput-object p2, p0, Lcom/xiaomi/auth/b;->b:Landroid/os/Bundle;

    iput-object p3, p0, Lcom/xiaomi/auth/b;->c:Lcom/xiaomi/auth/f;

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public onServiceConnected(Landroid/content/ComponentName;Landroid/os/IBinder;)V
    .locals 4

    const/4 v0, 0x0

    :try_start_0
    invoke-static {p2}, Lcom/xiaomi/account/IXiaomiAuthService$Stub;->asInterface(Landroid/os/IBinder;)Lcom/xiaomi/account/IXiaomiAuthService;

    move-result-object v1

    iget-object v2, p0, Lcom/xiaomi/auth/b;->a:Landroid/accounts/Account;

    iget-object v3, p0, Lcom/xiaomi/auth/b;->b:Landroid/os/Bundle;

    invoke-interface {v1, v2, v3}, Lcom/xiaomi/account/IXiaomiAuthService;->getMiCloudUserInfo(Landroid/accounts/Account;Landroid/os/Bundle;)Landroid/os/Bundle;
    :try_end_0
    .catch Ljava/lang/SecurityException; {:try_start_0 .. :try_end_0} :catch_0
    .catch Ljava/lang/Exception; {:try_start_0 .. :try_end_0} :catch_2

    move-result-object v0

    :goto_0
    iget-object v1, p0, Lcom/xiaomi/auth/b;->c:Lcom/xiaomi/auth/f;

    invoke-virtual {v1, v0}, Lcom/xiaomi/auth/f;->a(Ljava/lang/Object;)V

    return-void

    :catch_0
    move-exception v1

    invoke-static {p2}, Lmiui/net/IXiaomiAuthService$Stub;->asInterface(Landroid/os/IBinder;)Lmiui/net/IXiaomiAuthService;

    move-result-object v1

    :try_start_1
    iget-object v2, p0, Lcom/xiaomi/auth/b;->a:Landroid/accounts/Account;

    iget-object v3, p0, Lcom/xiaomi/auth/b;->b:Landroid/os/Bundle;

    invoke-interface {v1, v2, v3}, Lmiui/net/IXiaomiAuthService;->getMiCloudUserInfo(Landroid/accounts/Account;Landroid/os/Bundle;)Landroid/os/Bundle;
    :try_end_1
    .catch Ljava/lang/Exception; {:try_start_1 .. :try_end_1} :catch_1

    move-result-object v0

    goto :goto_0

    :catch_1
    move-exception v1

    const-string v2, "XiaomiAuthUtil"

    const-string v3, "miui.net.IXiaomiAuthService get MiCloud user info "

    invoke-static {v2, v3, v1}, Landroid/util/Log;->e(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)I

    goto :goto_0

    :catch_2
    move-exception v1

    const-string v2, "XiaomiAuthUtil"

    const-string v3, "com.xiaomi.account.IXiaomiAuthService get MiCloud user info "

    invoke-static {v2, v3, v1}, Landroid/util/Log;->e(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)I

    goto :goto_0
.end method

.method public onServiceDisconnected(Landroid/content/ComponentName;)V
    .locals 0

    return-void
.end method


text:
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Win32.SafeHandles;

namespace System.Net.Security
{
    internal sealed class SafeFreeNegoCredentials : SafeFreeCredentials
    {
        private SafeGssCredHandle _credential;
        private readonly bool _isNtlmOnly;
        private readonly string _userName;
        private readonly bool _isDefault;

        public SafeGssCredHandle GssCredential
        {
            get { return _credential; }
        }

        // Property represents if Ntlm Protocol is specfied or not.
        public bool IsNtlmOnly
        {
            get { return _isNtlmOnly; }
        }

        public string UserName
        {
            get { return _userName; }
        }

        public bool IsDefault
        {
            get { return _isDefault; }
        }

        public SafeFreeNegoCredentials(bool isNtlmOnly, string username, string password, string domain)
            : base(IntPtr.Zero, true)
        {
            Debug.Assert(username != null && password != null, "Username and Password can not be null");
            const char At = '@';
            const char Backwhack = '\\';

            // any invalid user format will not be mnipulated and passed as it is.
            int index = username.IndexOf(Backwhack);
            if (index > 0 && username.IndexOf(Backwhack, index + 1) < 0 && string.IsNullOrEmpty(domain))
            {
                domain = username.Substring(0, index);
                username = username.Substring(index + 1);
            }

            // remove any leading and trailing whitespace
            if (domain != null)
            {
                domain = domain.Trim();
            }

            if (username != null)
            {
                username = username.Trim();
            }

            if ((username.IndexOf(At) < 0) && !string.IsNullOrEmpty(domain))
            {
                username += At + domain;
            }

            bool ignore = false;
            _isNtlmOnly = isNtlmOnly;
            _userName = username;
            _isDefault = string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password);
            _credential = SafeGssCredHandle.Create(username, password, isNtlmOnly);
            _credential.DangerousAddRef(ref ignore);
        }

        public override bool IsInvalid
        {
            get { return (null == _credential); }
        }

        protected override bool ReleaseHandle()
        {
            _credential.DangerousRelease();
            _credential = null;
            return true;
        }
    }
}