text:
<#
.SYNOPSIS
    This script is used to check which automation accounts have run as account configured and renew the run as certificate

.DESCRIPTION
    This script will assess automation account which has configured RunAs accounts and renews the certificate if the user chooses to do so. On confirmation
    it will renew the key credentials of Azure-AD App and
    uploading new self-signed certificate to the Azure-AD App.

    Prerequisites:
    1. .NET framework 4.7.2 or later installed.
    2. Windows PowerShell version 5.1(64-bit) or later installed and run with Administrator permissions.
    3. Azure Az PowerShell module latest version installed, having minimum version Az.Accounts (2.5.4)`, `Az.Resources (4.4.0)` & `Az.Automation (1.7.1)` cmdlets
    4. You need the following permissions on the Azure user account:
        a. 'Contributor' access on the Azure subscription that has the Azure Automation account, and
        b. Owner permissions on the associated Run-As-Account Azure AD Application.

    Examples to run :
        1) To assess and renew automation runas accounts in all subscriptions - Ex: .\RunAsAccountAssessAndRenew.ps1
        2) To assess and renew automation runas accounts in set of subscriptions - Ex: .\RunAsAccountAssessAndRenew.ps1 - SubscriptionIds subId1,subId2

.PARAMETER SubscriptionIds
    [Optional] Assess and renew all the Automation run as accounts from the input subscriptions.

.PARAMETER Env
    [Optional] Cloud environment name. 'AzureCloud' by default.

.PARAMETER Verbose
    [Optional] Enable verbose logging

.EXAMPLE
    PS> .\AutomationAssessAndRenew.ps1 -SubscriptionIds subId1,subId2

.AUTHOR Microsoft

.VERSION 1.0
#>

#Requires -Modules @{ ModuleName="Az.Accounts"; ModuleVersion="2.5.4" },@{ ModuleName="Az.Resources"; ModuleVersion="4.4.0" },@{ ModuleName="Az.Automation"; ModuleVersion="1.7.1" }
#Requires -PSEdition Desktop
#Requires -RunAsAdministrator

[CmdletBinding()]
Param(
    [string[]]
    $SubscriptionIds,

    # Max number of retries for List Applications or List ServicePrincipals MS Graph request
    [int]
    $MaxRetryLimitForGraphApiCalls = 5,

    # Cut off days for expiry upto which runascertificate can be renewed
    [int]
    $ExpiryCutOffDays = 30,

    [ValidateSet("AzureCloud", "AzureUSGovernment", "AzureChinaCloud")]
    [Parameter(Mandatory = $false, HelpMessage = "Cloud environment name. 'AzureCloud' by default")]
    [string]
    $Env = "AzureCloud"
)

function Show-Description {
    Write-Warning ""
    Write-Warning "The script can be used to run at a time on set of subscriptions."
    Write-Warning "Please note that the script will work for Automation managed RunAs AAD Apps, and if you are using Third-party/CA-signed certificates, please follow manual renewal steps mentioned in Notes #check"
    Write-Warning ""

    Write-Warning "Prerequisites:"
    Write-Warning "1. .NET framework 4.7.2 or later installed."
    Write-Warning "2. Windows PowerShell version 5.1(64-bit) or later installed and run with Administrator permissions."
    Write-Warning "3. Azure Az PowerShell module latest version installed, having minimum version Az.Accounts (2.5.4)`, `Az.Resources (4.4.0)` & `Az.Automation (1.7.1)` cmdlets"
    Write-Warning "4. You need the following permissions on the Azure user account:"
    Write-Warning "    a. 'Contributor' access on the Azure subscription that has the Azure Automation account, and"
    Write-Warning "    b. Owner permissions on the associated Run-As-Account Azure AD Application."

    Write-Warning "Example to run :"
    Write-Warning "    To assess and renew run as accounts in set of subscriptions - Ex: .\AutomationAssessAndRenew.ps1 - SubscriptionIds subId1,subId2"
}

Function Get-MSGraphEndpoint
{
    param(
        [string]
        $Env
    )

    switch ($Env)
    {
        "AzureCloud" { return "https://graph.microsoft.com" }
        "AzureChinaCloud" { return "https://microsoftgraph.chinacloudapi.cn" }
        "AzureUSGovernment" { return "https://graph.microsoft.us" }
        default { throw "$($Env) is not a valid cloud environment." }
    }
}

class AutomationAccount {
    [string] $Name
    [string] $ResourceId
    [string] $Region
    [string] $ResourceGroup
    [string] $SubscriptionId
    [string] $RunAsAppId
    [DateTimeOffset] $RunAsConnectionCreationTime
    [bool] $UsesThirdParytCert
    [string] $Thumbprint
    [bool] $IsExpireCert
}

$RunAsAutomationAccounts = New-Object System.Collections.ArrayList

function Assess-Accounts {
    Write-Output ""
    Write-Output "================================================="
    Write-Output "Started Assessing Automation accounts..."
    Write-Output "================================================="

    # Get all automation accounts accessible to current user
    $queryPayload = @{
        query = 'resources | where type == "microsoft.automation/automationaccounts"'
        subscriptions = $SubscriptionIds
        options = @{
        '$top' = 10000
        '$skip' = 0
        '$skipToken' = ""
        'resultFormat' = "table"
        }
    }
    $payload = $queryPayload | ConvertTo-Json

    $resp = Invoke-AzRestMethod -Path "/providers/Microsoft.ResourceGraph/resources?api-version=2021-03-01" -Method POST -Payload $payload
    $resp = $resp.Content | ConvertFrom-Json

    $allAccounts = New-Object System.Collections.ArrayList
    $defaultDate = (Get-Date 01-01-1970)
    foreach ($row in $resp.data.rows)
    {
        $a = [AutomationAccount]@{
            ResourceId = $row[0]
            Name = $row[1]
            Region = $row[5]
            ResourceGroup = $row[6]
            SubscriptionId = $row[7]
            RunAsAppId = ""
            RunAsConnectionCreationTime = $defaultDate
            UsesThirdParytCert = $false
            Thumbprint= ""
            IsExpireCert = $false
        }
        Write-Debug "$($a.Name), $($a.Region), $($a.ResourceGroup), $($a.SubscriptionId)"

        $allAccounts.Add($a) > $null
    }

    Assess-AccountsBySubscriptionGroup $allAccounts
    Write-Output ""
    Write-Output "==================================================="
    Write-Output "Completed Assessing Automation accounts..."
    Write-Output "==================================================="
    Write-Output ""
}

function Assess-AccountsBySubscriptionGroup {
    param ($accounts)

    # Group by subscription ID
    $accountsGroup = $accounts | Group-Object { $_.SubscriptionId }

    foreach ($item in $accountsGroup) {
        Write-Output ""
        Write-Output "Procesing accounts in subscription $($item.Name): $($item.Group.Count)"
        Select-AzSubscription -SubscriptionId $item.Name > $null

        foreach ($a in $item.Group) {
            Assess-Account $a
        }
    }
}

function Assess-Account {
    param ([AutomationAccount] $account)

    Write-Verbose "Assessing account $($account.ResourceId)"
    # Get the RunAs connection
    $conn = Get-AzAutomationConnection -AutomationAccountName $account.Name -ResourceGroupName $account.ResourceGroup -Name "AzureRunAsConnection" -ErrorAction SilentlyContinue

    $runAsCert = Get-AzAutomationCertificate -ResourceGroupName $account.ResourceGroup -AutomationAccountName $account.Name -Name "AzureRunAsCertificate" -ErrorAction SilentlyContinue

    if ($null -ne $conn -and $conn.ConnectionTypeName -eq "AzureServicePrincipal" -and $null -ne $runAsCert) {
        $account.RunAsAppId = $conn.FieldDefinitionValues.ApplicationId
        $account.RunAsConnectionCreationTime = $conn.CreationTime
        $account.Thumbprint= $runAsCert.Thumbprint

        Assess-CertificatesOnApp $account
    }
    else {
        Write-Verbose "Account $($a.ResourceId) is not using RunAsAccount"
    }
}

function Assess-CertificatesOnApp {
    param ([AutomationAccount] $account)

    $url = "$($MsGraphEndpoint)/v1.0/applications?`$filter=appId eq '$($account.RunAsAppId)'&`$select=id,appId,keyCredentials"

    $resp = Make-MSGraphRequest -Url $url -MaxRetryLimit $MaxRetryLimitForGraphApiCalls

    # check for associated certicates in AAD for RunAsApp
    if ($null -ne $resp -and $null -ne $resp.value.keyCredentials) {
        foreach ($keyCred in $resp.value.keyCredentials) {
            if (($keyCred.Key.Length -gt 0) -and ($keyCred.type -eq 'AsymmetricX509Cert') -and (($keyCred.usage -eq 'Verify') -or ($keyCred.usage -eq 'Encrypt'))) {

                $reqdiff = New-TimeSpan -Days $ExpiryCutOffDays
                $timediff = ((Get-Date $keyCred.endDateTime) - (Get-Date)) -lt $reqdiff

                # check cert is not expired and expiration days is within ExpiryCutoffDays
                if ($keyCred.customKeyIdentifier -eq $account.Thumbprint -and (Get-Date $keyCred.endDateTime) -gt (Get-Date) -and $timediff) {
                    Assess-Certificate $account $keyCred
                }
            }
        }
    }
    # if no certificates are found in AAD App (expired cert), can assign new certificate for RunAsAcc
    elseif ($null -ne $resp -and $resp.value.keyCredentials.length -eq 0) {
        $account.IsExpireCert = $true
        $RunAsAutomationAccounts.Add($account) > $null
    }
    else {
        Write-Error "Unable to Assess Account $($account.ResourceId) - Reason: Failed to retrieve metadata from Azure Graph API"
    }
}

# Remove unnecessary new line characters and whitespace in url
Function Trim-Url
{
    param(
        [string]
        $Url
    )

    return $Url -replace '`n','' -replace '\s+', ''
}

# Make MS Graph request with retry and exponential backoff
Function Make-MSGraphRequest
{
    param(
        [string]
        $Url,

        [int]
        $MaxRetryLimit,

        [int]
        $flatMinSeconds = 10,

        [bool]
        $AddConsistencyLevel
    )

    $headers = @{
        "Authorization" = "Bearer $($MsGraphToken)"
    }

    if ($AddConsistencyLevel) {
        $headers["ConsistencyLevel"] = "eventual"
    }

    for ($i=1; $i -le $MaxRetryLimit; $i+=1)
    {
        try
        {
            Write-Verbose "GET $($Url)"
            $result = Invoke-RestMethod -Uri $Url -Headers $headers -Method "GET" -Verbose:$false
            break
        }
        catch
        {
            if ($_.Exception.Response.StatusCode.value__ -eq 429)
            {
                # Sleep then retry (Exponential backoff)
                $sleepDuration = [Math]::Pow(2,$i) + $flatMinSeconds
                Write-Verbose "Retry after sleeping for $($sleepDuration) seconds"
                Start-Sleep -s $sleepDuration
                continue
            }

            if ($_.Exception.Response.StatusCode.value__ -eq 404)
            {
                Write-Warning "AAD Object not found. Query - '$($Url)'"
                break
            }

            if ($_.Exception.Response.StatusCode.value__ -eq 401)
            {
                Write-Warning "UnAuthorized Access Error - '$($Url)'"
                break
            }

            if ($_.Exception.Response.StatusCode.value__ -eq 403)
            {
                Write-Warning "Forbidden Error- '$($Url)'"
                break
            }
        }
    }

    if ($i -gt $MaxRetryLimit)
    {
        $Url = Trim-Url -Url $Url
        Write-Warning "Unexpected error while connecting to the Azure Graph API. URL - '$($Url)'"
    }

    return $result
}

function Assess-Certificate {
    param (
        [AutomationAccount] $account,
        $keyCred
    )

    $automationCertIssuerName = "DC=$($account.Name)_$($account.ResourceGroup)_$($account.SubscriptionId)"

    try {
        $certBytes = [Convert]::FromBase64String($keyCred.key)
        $cert = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new($certBytes)
    }
    catch {
        Write-Error "Unable to assess $($account.ResourceId) - Reason: Issue processing certificate."
    }

    $RunAsAutomationAccounts.Add($account) > $null

    if ($null -ne $cert) {
        if ($cert.Issuer -eq $automationCertIssuerName) {
            Write-Verbose "Account $($account.ResourceId) uses a self-signed cert with thumbprint: $($cert.Thumbprint)."
        }
        else {
            $account.UsesThirdParytCert = $true
            Write-Verbose "Account $($account.ResourceId) uses a third-party certificate with issuer: $($cert.Issuer)."
        }
        Write-Debug "issuer: $($cert.Issuer), subject: $($cert.Subject), expiry: $($cert.NotAfter)"
    }
}

function Renew-RunAsAccounts {
    param (
        $accounts
    )

    if ($accounts.Count -eq 0) {
        Write-Output ""
        Write-Output "No RunAs accounts to renew."
        return
    }

    Write-Output ""
    Write-Output "======================"
    Write-Output "Starting renewal..."
    Write-Output "======================"
    $count = 0
    foreach ($a in $accounts)
    {
        if ($a.UsesThirdParytCert) {
            Write-Output "$($a.ResourceId) uses a third-party certificate."
            $thirdPartyRenew = Read-Host "Do you want to renew this account with a self-signed certificate? (Y/N): "

            if ($thirdPartyRenew -ne "Y" -and $thirdPartyRenew -ne 'y') {
                continue
            }
        }

        Write-Output ""
        if ($a.IsExpireCert) {
            $renew = Read-Host "RunAs certificate for account $($a.ResourceId) has expired. Want to Create New RunAs Certificate (Y/N): "
        }
        else {
            $renew = Read-Host "Renew RunAs certificate for account $($a.ResourceId) (Y/N): "
        }

        if ($renew -eq "Y" -or $renew -eq 'y') {
            Renew-Account $a
            ++$count
        }
    }

    Write-Output ""
    Write-Output "======================"
    Write-Output "Completed renewal. Total accounts renewed -$($count)"
    Write-Output "======================"
}

function Renew-Account {
    param ([AutomationAccount]$account)

    Write-Output ""
    Write-Output "Started Rotating certificate for $($account.ResourceId)"
    Select-AzSubscription -SubscriptionId $account.SubscriptionId > $null

    $appId = $account.RunAsAppId
    $subId = $account.SubscriptionId
    $resourceGroup = $account.ResourceGroup
    $accountName = $account.Name

    # To renew AAD App certificate, user should have Automation Contributor role access and Application Administrator permission on AAD App
    # Checking user write access on automation account.
    $writePermission = Check-WriteAccessOnAutomationAccount $account
    if(!$writePermission ) {
        Write-Error "Unable to renew $($account.ResourceId) - Reason: User does not have write permission on the Automation account. Please check prerequisites."
        return
    }

    Write-Verbose "User has write permission on Automation account $($account.ResourceId)"

    Write-Debug "Creating new certificate"
    $certName = "$($accountName)_$($resourceGroup)_$($subId)"
    $cert = New-SelfSignedCertificate -KeyUsageProperty All -Provider "Microsoft Enhanced RSA and AES Cryptographic Provider" -FriendlyName $certName -Subject "DC=$certName" -HashAlgorithm SHA256 -KeyLength 2048 -KeyExportPolicy ExportableEncrypted
    $certString = [convert]::tobase64string($cert.RawData)

    Add-Type -AssemblyName System.Web
    $securePassword = ConvertTo-SecureString $([System.Web.Security.Membership]::GeneratePassword(25, 10)) -AsPlainText -Force
    Export-PfxCertificate -FilePath "$pwd\$certName.pfx" -Cert $cert -Password $securePassword -NoProperties > $null

    try {
        Write-Verbose "Adding the new certificate on the AAD application"
        New-AzADAppCredential -ApplicationId $appId -CertValue $certString -StartDate $cert.NotBefore -EndDate $cert.NotAfter > $null
        if (!$?) {
            Write-Error "Unable to renew $($account.ResourceId) - Reason: Failed to add new certificate to the AAD application. Please check prerequisites."
            return
        }
    }
    catch {
        Write-Error -Message "Unable to renew, error while accessing the App. Error Message: $($Error[0].Exception.Message)"
        return
    }

    Write-Verbose "Creating the RunAs certificate asset"
    Remove-AzAutomationCertificate -AutomationAccountName $accountName -ResourceGroupName $resourceGroup -Name "AzureRunAsCertificate" -ErrorAction SilentlyContinue > $null
    New-AzAutomationCertificate -AutomationAccountName $accountName -ResourceGroupName $resourceGroup -Name "AzureRunAsCertificate" -Exportable -Path "$pwd\$certName.pfx" -Password $securePassword > $null
    if (!$?) {
        Write-Error "Unable to renew $($account.ResourceId) - Reason: Failed to update automation account with new runas certificate, may be due to Network or Permission issue."
        Write-Error "Please check prerequisites and rerun the script or renew manually."
        return
    }

    Write-Verbose "Update the RunAs connection"
    Set-AzAutomationConnectionFieldValue -AutomationAccountName $accountName -ResourceGroupName $resourceGroup -Name "AzureRunAsConnection" -ConnectionFieldName CertificateThumbprint -Value $cert.Thumbprint > $null
    if (!$?) {
        Write-Error "Unable to renew $($account.ResourceId) - Reason: Failed to update automation account with new runas certificate, may be due to Network or Permission issue."
        Write-Error "Please check prerequisites and rerun the script or renew manually."
        return
    }

    Write-Output "Successfully renewed account $($account.ResourceId) . "
    Write-Output ""
}

function Check-WriteAccessOnAutomationAccount {
    param ([AutomationAccount]$account)

    $resourceGroup = $account.ResourceGroup
    $accountName = $account.Name

    #To renew AAD App cert,user should have Automation Contributor role access and admin permission on AAD App
    # Checking user write access on automation account.
    $VariableName = "Renew_AAD"+ $(Get-Random)
    $var = Get-AzAutomationVariable -ResourceGroupName $resourceGroup -AutomationAccountName $accountName -Name $VariableName -ErrorAction SilentlyContinue > $null
    while( $null -ne $var)
    {
        $VariableName = "Renew_AAD"+ $(Get-Random)
        $var = Get-AzAutomationVariable -ResourceGroupName $resourceGroup -AutomationAccountName $accountName -Name $VariableName -ErrorAction SilentlyContinue > $null
    }

    if( $null -eq $var) {
        $var = New-AzAutomationVariable -ResourceGroupName $resourceGroup -AutomationAccountName $accountName -Name $VariableName -Value $VariableName -Encrypted $false
        if( $null -ne $var) {
            Remove-AzAutomationVariable -ResourceGroupName $resourceGroup -AutomationAccountName $accountName -Name $VariableName
            return $true;
        }
    }

    return $false
}

function ParseResourceId {
    param (
       [string]$resourceID
   )
   $array = $resourceID.Split('/')
   $indexSubscriptionId = 0..($array.Length -1) | where {$array[$_] -ieq 'subscriptions'}
   $indexResourceGroup = 0..($array.Length -1) | where {$array[$_] -ieq 'resourcegroups'}
   $result = $array.get($indexSubscriptionId+1), $array.get($indexResourceGroup+1), $array.get($array.Length -1)
   return $result
}

# Start point for the script
Show-Description

Connect-AzAccount -Environment $Env -ErrorAction Stop > $null
$MsGraphEndpoint = Get-MSGraphEndpoint $Env
$MsGraphToken = (Get-AzAccessToken -ResourceUrl $MsGraphEndpoint).Token

    Write-Output "Start Assessment for given Subscriptions."
    # Assess all the given subscriptions and renew all the App Id's certs belonging to Azure automation
    Assess-Accounts

    Renew-RunAsAccounts $RunAsAutomationAccounts


text:
{-# LANGUAGE CPP #-}
{-# LANGUAGE Rank2Types #-}
#ifdef TRUSTWORTHY
{-# LANGUAGE Trustworthy #-}
#endif
-----------------------------------------------------------------------------
-- |
-- Module      :  Data.Typeable.Lens
-- Copyright   :  (C) 2012-14 Edward Kmett
-- License     :  BSD-style (see the file LICENSE)
-- Maintainer  :  Edward Kmett <ekmett@gmail.com>
-- Stability   :  experimental
-- Portability :  Rank2Types
--
----------------------------------------------------------------------------
module Data.Typeable.Lens
  ( _cast
  , _gcast
  ) where

import Control.Applicative
import Control.Lens
import Data.Typeable
import Data.Maybe

-- | A 'Traversal'' for working with a 'cast' of a 'Typeable' value.
_cast :: (Typeable s, Typeable a) => Traversal' s a
_cast f s = case cast s of
  Just a  -> fromMaybe (error "_cast: recast failed") . cast <$> f a
  Nothing -> pure s
{-# INLINE _cast #-}

-- | A 'Traversal'' for working with a 'gcast' of a 'Typeable' value.
_gcast :: (Typeable s, Typeable a) => Traversal' (c s) (c a)
_gcast f s = case gcast s of
  Just a  -> fromMaybe (error "_gcast: recast failed") . gcast <$> f a
  Nothing -> pure s
{-# INLINE _gcast #-}

redpajama_set_name: RedPajamaGithub


text:
set(CPP_FILES
  Internal/mitkIpPicGet.c
  Internal/mitkPicFileReader.cpp
  Internal/mitkPicFileIOFactory.cpp
  Internal/mitkPicHelper.cpp
  Internal/mitkPicVolumeTimeSeriesIOFactory.cpp
  Internal/mitkPicVolumeTimeSeriesReader.cpp
)


text:
from django.utils.translation import string_concat  # noqa
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import ungettext_lazy

from horizon import tables

from openstack_dashboard import api
from openstack_dashboard.usage import quotas

class DeleteKeyPairs(tables.DeleteAction):
    policy_rules = (("compute", "compute_extension:keypairs:delete"),)

    @staticmethod
    def action_present(count):
        return ungettext_lazy(
            u"Delete Key Pair",
            u"Delete Key Pairs",
            count
        )

    @staticmethod
    def action_past(count):
        return ungettext_lazy(
            u"Deleted Key Pair",
            u"Deleted Key Pairs",
            count
        )

    def delete(self, request, obj_id):
        api.nova.keypair_delete(request, obj_id)

class ImportKeyPair(tables.LinkAction):
    name = "import"
    verbose_name = _("Import Key Pair")
    url = "horizon:project:access_and_security:keypairs:import"
    classes = ("ajax-modal",)
    icon = "upload"
    policy_rules = (("compute", "compute_extension:keypairs:create"),)

class CreateKeyPair(tables.LinkAction):
    name = "create"
    verbose_name = _("Create Key Pair")
    url = "horizon:project:access_and_security:keypairs:create"
    classes = ("ajax-modal",)
    icon = "plus"
    policy_rules = (("compute", "compute_extension:keypairs:create"),)

    def allowed(self, request, keypair=None):
        usages = quotas.tenant_quota_usages(request)
        count = len(self.table.data)
        if (usages.get('key_pairs')
                and usages['key_pairs']['quota'] <= count):
            if "disabled" not in self.classes:
                self.classes = [c for c in self.classes] + ['disabled']
                self.verbose_name = string_concat(self.verbose_name, ' ',
                                                  _("(Quota exceeded)"))
        else:
            self.verbose_name = _("Create Key Pair")
            classes = [c for c in self.classes if c != "disabled"]
            self.classes = classes
        return True

class KeypairsTable(tables.DataTable):
    name = tables.Column("name", verbose_name=_("Key Pair Name"))
    fingerprint = tables.Column("fingerprint", verbose_name=_("Fingerprint"))

    def get_object_id(self, keypair):
        return keypair.name

    class Meta:
        name = "keypairs"
        verbose_name = _("Key Pairs")
        table_actions = (CreateKeyPair, ImportKeyPair, DeleteKeyPairs,)
        row_actions = (DeleteKeyPairs,)


text:
<?php

namespace Func\Pagination;

use Func\Pagination\Exception\LimitPageException;

/**
 * @link https://github.com/KnpLabs/knp-components/tree/master/src/Knp/Component/Pager
 * @link https://github.com/whiteoctober/Pagerfanta
 * @link https://spiral.dev/docs/component-pagination
 */
class Pagination
{
    /**
     * @var int $currentPage
     * @var int $perPage
     * @var int $totalCount
     * @var int|null $pageOffset
     * @var int|null $pageCount
     */
    private
        $currentPage,
        $perPage,
        $totalCount,
        $pageOffset,
        $pageCount
    ;

    public function __construct(int $currentPage, int $perPage, int $totalCount, int $limitPage = 100)
    {
        if ($perPage > $limitPage) {
            throw new LimitPageException(
                sprintf('The elements count must not be more than %d', $limitPage)
            );
        }

        $this->currentPage = $currentPage;
        $this->perPage = $perPage;
        $this->totalCount = $totalCount;
    }

    public function getCurrentPage(): int
    {
        return $this->currentPage;
    }

    public function getPerPage(): int
    {
        return $this->perPage;
    }

    public function getTotalCount(): int
    {
        return $this->totalCount;
    }

    public function getPageOffset(): int
    {
        if ($this->pageOffset) {
            return $this->pageOffset;
        }

        return $this->pageOffset = ($this->currentPage - 1) * $this->perPage;
    }

    public function getPageCount(): int
    {
        if ($this->pageCount) {
            return $this->pageCount;
        }

        return $this->pageCount = ceil($this->totalCount / $this->perPage);
    }

    public function getHeaders(): array
    {
        return [
            'X-Pagination-Current-Page' => $this->getCurrentPage(),
            'X-Pagination-Per-Page' => $this->getPerPage(),
            'X-Pagination-Page-Count' => $this->getPageCount(),
            'X-Pagination-Total-Count' => $this->getTotalCount(),
        ];
    }
}


text:
/*global DS.FirebaseAdapter*/
import DS from 'ember-data';

export default DS.FirebaseAdapter.extend({
  firebase: new Firebase('https://decider.firebaseio.com/quiz')
});


text:
@interface NSString (NamingConvention)

- (NSString *)autoCapitalizeStringForName;

@end


text: Solutions for codewars.com katas


text:
package io.atomix.vertx;

import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import io.atomix.cluster.Node;
import io.atomix.cluster.discovery.BootstrapDiscoveryProvider;
import io.atomix.cluster.protocol.SwimMembershipProtocol;
import io.atomix.core.Atomix;
import io.atomix.protocols.raft.partition.RaftPartitionGroup;
import io.atomix.utils.net.Address;

/**
 * Vert.x test helper.
 *
 * @author Jordan Halterman
 */
final class AtomixVertxTestHelper {
  private static final int BASE_PORT = 5000;
  private List<Atomix> instances;
  private int id = 10;

  void setUp() throws Exception {
    deleteData();
    instances = new ArrayList<>();
    instances.add(createAtomix(1, 1, 2, 3));
    instances.add(createAtomix(2, 1, 2, 3));
    instances.add(createAtomix(3, 1, 2, 3));
    List<CompletableFuture<Void>> futures = instances.stream().map(Atomix::start).collect(Collectors.toList());
    CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).get(30, TimeUnit.SECONDS);
  }

  /**
   * Creates an Atomix instance.
   */
  private Atomix createAtomix(int id, int... ids) {
    Collection<Node> nodes = IntStream.of(ids)
        .mapToObj(memberId -> Node.builder()
            .withId(String.valueOf(memberId))
            .withAddress(Address.from("localhost", BASE_PORT + memberId))
            .build())
        .collect(Collectors.toList());

    return Atomix.builder()
        .withClusterId("test")
        .withMemberId(String.valueOf(id))
        .withHost("localhost")
        .withPort(BASE_PORT + id)
        .withMembershipProtocol(SwimMembershipProtocol.builder()
            .withBroadcastDisputes(true)
            .withBroadcastUpdates(true)
            .withProbeInterval(Duration.ofMillis(100))
            .withNotifySuspect(true)
            .withFailureTimeout(Duration.ofSeconds(3))
            .build())
        .withMembershipProvider(new BootstrapDiscoveryProvider(nodes))
        .withManagementGroup(RaftPartitionGroup.builder("system")
            .withNumPartitions(1)
            .withPartitionSize(ids.length)
            .withMembers(nodes.stream().map(node -> node.id().id()).collect(Collectors.toSet()))
            .withDataDirectory(new File("target/test-logs/" + id + "/system"))
            .build())
        .withPartitionGroups(RaftPartitionGroup.builder("test")
            .withNumPartitions(3)
            .withPartitionSize(ids.length)
            .withMembers(nodes.stream().map(node -> node.id().id()).collect(Collectors.toSet()))
            .withDataDirectory(new File("target/test-logs/" + id + "/test"))
            .build())
        .build();
  }

  /**
   * Returns the next Atomix cluster manager.
   *
   * @return The next Atomix cluster manager.
   */
  AtomixClusterManager createClusterManager() {
    Atomix instance = createAtomix(id++, 1, 2, 3);
    instance.start().join();
    instances.add(instance);
    return new AtomixClusterManager(instance);
  }

  void tearDown() throws Exception {
    List<CompletableFuture<Void>> futures = instances.stream().map(Atomix::stop).collect(Collectors.toList());
    try {
      CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()])).join();
    } catch (Exception e) {
      // Do nothing
    }
    deleteData();
  }

  /**
   * Deletes data from the test data directory.
   */
  private static void deleteData() throws Exception {
    Path directory = Paths.get("target/test-logs/");
    if (Files.exists(directory)) {
      Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
          Files.delete(file);
          return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
          Files.delete(dir);
          return FileVisitResult.CONTINUE;
        }
      });
    }
  }
}


text:
package org.apache.webbeans.component;

import java.lang.reflect.Type;

import javax.enterprise.event.Event;
import javax.enterprise.util.TypeLiteral;

import org.apache.webbeans.config.WebBeansContext;
import org.apache.webbeans.event.EventImpl;
import org.apache.webbeans.portable.EventProducer;
import org.apache.webbeans.util.CollectionUtil;

/**
 * Implicit observable bean definition.
 *
 * @version $Rev$ $Date$
 */
public class EventBean<T> extends BuiltInOwbBean<Event<T>>
{

    /**
     * Creates a new instance of event bean.
     * @param webBeansContext
     */
    @SuppressWarnings("serial")
    public EventBean(WebBeansContext webBeansContext)
    {
        super(webBeansContext,
              WebBeansType.OBSERVABLE,
              new BeanAttributesImpl<>(CollectionUtil.<Type>unmodifiableSet(new TypeLiteral<Event<T>>()
              {
              }.getRawType(), Object.class)),
              new TypeLiteral<Event<T>>(){}.getRawType(),
              new SimpleProducerFactory<>(new EventProducer<T>(webBeansContext)));
    }

    /* (non-Javadoc)
     * @see org.apache.webbeans.component.AbstractOwbBean#isPassivationCapable()
     */
    @Override
    public boolean isPassivationCapable()
    {
        return true;
    }

    @Override
    public Class<?> proxyableType()
    {
        return EventImpl.class;
    }
}


text:
import pandas as pd
import numpy as np
import re
import argparse

def fix_hgvs(hgvs_string):
    if hgvs_string is np.nan:
        # handle na values
        return np.nan
    if 'in_frame_ins' in hgvs_string.lower():
        hgvs_string = re.sub('in_frame_ins', 'ins', hgvs_string,
                             flags=re.IGNORECASE)
    elif 'in_frame_del' in hgvs_string.lower():
        hgvs_string = re.sub('in_frame_del', 'del', hgvs_string,
                             flags=re.IGNORECASE)
    return hgvs_string

def parse_tumor_sample(tsample):
    if tsample.startswith('TCGA'):
        tsample = re.sub('-[A-Za-z0-9]+$', '', tsample)
        return tsample
    else:
        return tsample

def parse_arguments():
    parser = argparse.ArgumentParser()
    help_str = 'Data set from Davoli et al found at Elledge lab website'
    parser.add_argument('-t', '--txt',
                        type=str, required=True,
                        help=help_str)
    help_str = 'Path to save MAF file'
    parser.add_argument('-m', '--maf',
                        type=str, required=True,
                        help=help_str)
    args = parser.parse_args()
    return vars(args)

def main(opts):
    # read in data set
    davoli_df = pd.read_csv(opts['txt'], sep='\t')

    # convert positions to have separate cols for chr, start, and end
    tmp_list = [re.split(':|-', x) for x in davoli_df['Genome.position.hg19'].tolist()]
    col_names = ['Chromosome', 'Start_Position', 'End_Position']
    tmp_df = pd.DataFrame(tmp_list, columns=col_names)
    davoli_df[col_names] = tmp_df

    # convert classification of mutation types to something
    # more compatable with the MAF file format
    type2varClass = {'Silent': 'Silent',
                     'Splice Site': 'Splice_Site',
                     'Missense': 'Missense_Mutation',
                     'Indel Frameshift': 'Frame_Shift_Indel',
                     'Nonsense': 'Nonsense_Mutation',
                     'Indel In Frame': 'In_Frame_Indel',
                     'Complex Missense': 'In_Frame_Indel',
                     'Translation_Start_Site': 'Translation_Start_Site',
                     'De_novo_Start_OutOfFrame': 'Translation_Start_Site',
                     'De_novo_Start_InFrame': 'Translation_Start_Site',
                     'Nonstop Extension': 'Nonstop_Mutation',
                     'Complex Nonsense': 'Nonsense_Mutation',
                     'Indel Nonsense': 'Nonsense_Mutation',
                     "5'UTR": "5'UTR",
                     "3'UTR": "3'UTR",
                     'Intron': 'Intron',
                     'Promoter': 'Promoter'
                     }
    davoli_df['Mutation_Type'] = davoli_df['Mutation_Type'].apply(lambda x: type2varClass[x])
    davoli_df['Tumor_Sample'] = davoli_df['Tumor_Sample'].apply(parse_tumor_sample)
    davoli_df['Protein_Change'] = davoli_df['Protein_Change'].apply(fix_hgvs)

    # fix column name of ref/new base
    davoli_df.rename(columns={'Gene': 'Gene_Symbol',
                              'Mutation_Type': 'Variant_Classification',
                              'Reference': 'Reference_Allele',
                              'Mutation': 'Tumor_Allele'},
                     inplace=True)

    cols_of_interest = ['Gene_Symbol', 'Tumor_Sample', 'Tumor_Type',
                        'Chromosome', 'Start_Position',
                        'End_Position', 'Variant_Classification',
                        'Reference_Allele', 'Tumor_Allele',
                        'Protein_Change']
    davoli_df[cols_of_interest].to_csv(opts['maf'], sep='\t', index=False)

if __name__ == "__main__":
    opts = parse_arguments()
    main(opts)


text:
// Copyright 2010-2022 Google LLC
// 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 com.google.ortools.sat;

import com.google.ortools.sat.CpModelProto;
import com.google.ortools.sat.TableConstraintProto;

/**
 * Specialized assignment constraint.
 *
 * <p>This constraint allows adding tuples to the allowed/forbidden assignment constraint
 * incrementally.
 */
public class TableConstraint extends Constraint {
  public TableConstraint(CpModelProto.Builder builder) {
    super(builder);
  }

  /**
   * Adds a tuple of possible/forbidden values to the constraint.
   *
   * @param tuple the tuple to add to the constraint.
   * @throws CpModel.WrongLength if the tuple does not have the same length as the array of
   *     variables of the constraint.
   */
  public TableConstraint addTuple(int[] tuple) {
    TableConstraintProto.Builder table = getBuilder().getTableBuilder();
    if (tuple.length != table.getVarsCount()) {
      throw new CpModel.WrongLength(
          "addTuple", "tuple does not have the same length as the variables");
    }
    for (int value : tuple) {
      table.addValues(value);
    }
    return this;
  }

  /**
   * Adds a tuple of possible/forbidden values to the constraint.
   *
   * @param tuple the tuple to add to the constraint.
   * @throws CpModel.WrongLength if the tuple does not have the same length as the array of
   *     variables of the constraint.
   */
  public TableConstraint addTuple(long[] tuple) {
    TableConstraintProto.Builder table = getBuilder().getTableBuilder();
    if (tuple.length != table.getVarsCount()) {
      throw new CpModel.WrongLength(
          "addTuple", "tuple does not have the same length as the variables");
    }
    for (long value : tuple) {
      table.addValues(value);
    }
    return this;
  }

  /**
   * Adds a list of tuples of possible/forbidden values to the constraint.
   *
   * @param tuples the list of tuples to add to the constraint.
   * @throws CpModel.WrongLength if one tuple does not have the same length as the array of
   *     variables of the constraint.
   */
  public TableConstraint addTuples(int[][] tuples) {
    TableConstraintProto.Builder table = getBuilder().getTableBuilder();
    for (int[] tuple : tuples) {
      if (tuple.length != table.getVarsCount()) {
        throw new CpModel.WrongLength(
            "addTuples", "a tuple does not have the same length as the variables");
      }
      for (int value : tuple) {
        table.addValues(value);
      }
    }
    return this;
  }

  /**
   * Adds a list of tuples of possible/forbidden values to the constraint.
   *
   * @param tuples the list of tuples to add to the constraint.
   * @throws CpModel.WrongLength if one tuple does not have the same length as the array of
   *     variables of the constraint.
   */
  public TableConstraint addTuples(long[][] tuples) {
    TableConstraintProto.Builder table = getBuilder().getTableBuilder();
    for (long[] tuple : tuples) {
      if (tuple.length != table.getVarsCount()) {
        throw new CpModel.WrongLength(
            "addTuples", "a tuple does not have the same length as the variables");
      }
      for (long value : tuple) {
        table.addValues(value);
      }
    }
    return this;
  }
}


text:
package org.f0w.k2i.core.exchange.finder;

import com.google.common.collect.ImmutableMap;
import com.typesafe.config.ConfigFactory;
import lombok.val;
import org.f0w.k2i.core.DocumentSourceType;
import org.junit.Test;

import static org.f0w.k2i.core.DocumentSourceType.*;
import static org.junit.Assert.assertTrue;

public class MovieFinderFactoryTest {
    private MovieFinderFactory factory = new MovieFinderFactory(ConfigFactory.load());

    @Test
    public void makeSingle() throws Exception {
        val classMap = new ImmutableMap.Builder<DocumentSourceType, Class<? extends MovieFinder>>()
                .put(IMDB_HTML, BasicMovieFinder.class)
                .build();

        classMap.forEach((type, clazz) -> {
            MovieFinder instance = factory.make(type);

            assertTrue(clazz.isInstance(instance));
            assertTrue(instance.getDocumentSourceType().equals(type));
        });
    }

    @Test
    public void makeMultiple() throws Exception {
        assertTrue(factory.make(IMDB_HTML) instanceof MixedMovieFinder);
    }
}


text:
package org.fidonet.binkp.mina2.codec;

import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFactory;
import org.apache.mina.filter.codec.ProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolEncoder;
import org.fidonet.binkp.common.io.BinkFrame;

/**
 * Created by IntelliJ IDEA.
 * Author: Vladimir Kravets
 * E-Mail: vova.kravets@gmail.com
 * Date: 9/19/12
 * Time: 1:40 PM
 */
public class BinkDataCodecFactory implements ProtocolCodecFactory {

    @Override
    public ProtocolEncoder getEncoder(IoSession session) throws Exception {
        return new BinkDataEncoder<BinkFrame>();
    }

    @Override
    public ProtocolDecoder getDecoder(IoSession session) throws Exception {
        return new BinkDataDecoder();
    }
}


text:
"""This code example gets all active activity groups.

To create activity groups, run create_activity_groups.py.

The LoadFromStorage method is pulling credentials and properties from a
"googleads.yaml" file. By default, it looks for this file in your home
directory. For more information, see the "Caching authentication information"
section of our README.

"""

# Import appropriate modules from the client library.
from googleads import dfp

def main(client):
  # Initialize appropriate service.
  activity_group_service = client.GetService('ActivityGroupService',
                                             version='v201411')

  # Create statement object to only select active activity groups.
  values = [{
      'key': 'status',
      'value': {
          'xsi_type': 'TextValue',
          'value': 'ACTIVE'
      }
  }]
  query = 'WHERE status = :status'

  # Create a filter statement.
  statement = dfp.FilterStatement(query, values)

  # Get activity groups by statement.
  while True:
    response = activity_group_service.getActivityGroupsByStatement(
        statement.ToStatement())
    if 'results' in response:
      # Display results.
      for activity_group in response['results']:
        print ('Activity group with ID \'%s\' and name \'%s\' was found.'
               % (activity_group['id'], activity_group['name']))
      statement.offset += dfp.SUGGESTED_PAGE_LIMIT
    else:
      break

  print '\nNumber of results found: %s' % response['totalResultSetSize']

if __name__ == '__main__':
  # Initialize client object.
  dfp_client = dfp.DfpClient.LoadFromStorage()
  main(dfp_client)


text:
package rapture.jmx.beans;

import java.io.Serializable;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;

public class RaptureLogging implements RaptureLoggingMXBean, Serializable {
    private static final long serialVersionUID = 1L;
    private static final Logger log = Logger.getLogger(RaptureLogging.class);

    public void setLevel(String logName, String level) {
        log.info("Set level for " + logName + " to " + level);
        Logger.getLogger(logName).setLevel(Level.toLevel(level));
    }

}


text:
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc.  All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

// Author: kenton@google.com (Kenton Varda)

#include <google/protobuf/compiler/java/doc_comment.h>

#include <gtest/gtest.h>

namespace google {
namespace protobuf {
namespace compiler {
namespace java {
namespace {

TEST(JavaDocCommentTest, Escaping) {
  EXPECT_EQ("foo /* bar */ baz", EscapeJavadoc("foo /* bar */ baz"));
  EXPECT_EQ("foo /*/ baz", EscapeJavadoc("foo /*/ baz"));
  EXPECT_EQ("{@foo}", EscapeJavadoc("{@foo}"));
  EXPECT_EQ("&", EscapeJavadoc("&"));
  EXPECT_EQ("foo\u1234bar", EscapeJavadoc("foo\\u1234bar"));
  EXPECT_EQ("@deprecated", EscapeJavadoc("@deprecated"));
}

}  // namespace
}  // namespace java
}  // namespace compiler
}  // namespace protobuf
}  // namespace google


text:
namespace Microsoft.Azure.Management.ServiceBus.Models
{
    using System;
    using System.Linq;
    using System.Collections.Generic;
    using Newtonsoft.Json;
    using Microsoft.Rest;
    using Microsoft.Rest.Serialization;
    using Microsoft.Rest.Azure;

    /// <summary>
    /// Sku of the Namespace.
    /// </summary>
    public partial class Sku
    {
        /// <summary>
        /// Initializes a new instance of the Sku class.
        /// </summary>
        public Sku() { }

        /// <summary>
        /// Initializes a new instance of the Sku class.
        /// </summary>
        public Sku(string tier, string name = default(string), int? capacity = default(int?))
        {
            Name = name;
            Tier = tier;
            Capacity = capacity;
        }

        /// <summary>
        /// Name of this Sku. Possible values include: 'Basic', 'Standard',
        /// 'Premium'
        /// </summary>
        [JsonProperty(PropertyName = "name")]
        public string Name { get; set; }

        /// <summary>
        /// The tier of this particular SKU. Possible values include: 'Basic',
        /// 'Standard', 'Premium'
        /// </summary>
        [JsonProperty(PropertyName = "tier")]
        public string Tier { get; set; }

        /// <summary>
        /// The messaging units for the tier specified
        /// </summary>
        [JsonProperty(PropertyName = "capacity")]
        public int? Capacity { get; set; }

        /// <summary>
        /// Validate the object. Throws ValidationException if validation fails.
        /// </summary>
        public virtual void Validate()
        {
            if (Tier == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "Tier");
            }
        }
    }
}


text:
package skinny.controller.feature

import java.lang.reflect.Modifier
import org.scalatra.ScalatraBase
import skinny.controller.{ KeyAndErrorMessages, Params }
import skinny.exception.RequestScopeConflictException
import java.util.Locale
import org.joda.time._
import skinny.I18n
import skinny.logging.Logging
import javax.servlet.http.HttpServletRequest

object RequestScopeFeature extends Logging {

  /**
   * Key for request scope.
   */
  val REQUEST_SCOPE_KEY = "__SKINNY_FRAMEWORK_REQUEST_SCOPE__"

  // skinny has this request scope as a member
  val ATTR_SKINNY = "s"

  val ATTR_CONTEXT_PATH = "contextPath"
  val ATTR_REQUEST_PATH = "requestPath"
  val ATTR_REQUEST_PATH_WITH_QUERY_STRING = "requestPathWithQueryString"
  val ATTR_PARAMS = "params"
  val ATTR_MULTI_PARAMS = "multiParams"
  val ATTR_FLASH = "flash"
  val ATTR_ERROR_MESSAGES = "errorMessages"
  val ATTR_KEY_AND_ERROR_MESSAGES = "keyAndErrorMessages"
  val ATTR_I18N = "i18n"

  val ATTR_CSRF_KEY = "csrfKey"
  val ATTR_CSRF_TOKEN = "csrfToken"

  // Used in the SkinnyResource & TemplateEngineFeature
  val ATTR_RESOURCE_NAME = "resourceName"
  val ATTR_RESOURCES_NAME = "resourcesName"

  /**
   * Returns request scope Map value.
   */
  def requestScope(request: HttpServletRequest): scala.collection.concurrent.Map[String, Any] = {
    request.getAttribute(REQUEST_SCOPE_KEY) match {
      case null =>
        val values = scala.collection.concurrent.TrieMap[String, Any]()
        request.setAttribute(REQUEST_SCOPE_KEY, values)
        values
      case values: scala.collection.concurrent.Map[_, _] =>
        values.asInstanceOf[scala.collection.concurrent.Map[String, Any]]
      case _ => throw new RequestScopeConflictException(
        s"Don't use '${REQUEST_SCOPE_KEY}' for request attribute key name.")
    }
  }

  /**
   * Fetches value from request scope.
   */
  def getAs[A](request: HttpServletRequest, key: String): Option[A] = {
    requestScope(request).get(key).map { v =>
      try v.asInstanceOf[A]
      catch {
        case e: ClassCastException =>
          throw new RequestScopeConflictException(
            s"""\"${key}\" value in request scope is unexpected. (actual: ${v}, error: ${e.getMessage}})""")
      }
    }
  }

}

/**
 * Request scope support.
 */
trait RequestScopeFeature extends ScalatraBase with SnakeCasedParamKeysFeature with LocaleFeature with Logging {

  import RequestScopeFeature._

  /**
   * Registers default attributes in the request scope.
   */
  before()(initializeRequestScopeAttributes)

  def initializeRequestScopeAttributes = {
    if (requestScope().get(ATTR_SKINNY).isEmpty) {
      set(ATTR_SKINNY, skinny.Skinny(requestScope()))
      // requestPath/contextPath
      val requestPathWithContext = contextPath + requestPath
      val queryStringPart = Option(request.getQueryString).map(qs => "?" + qs).getOrElse("")
      set(ATTR_CONTEXT_PATH -> contextPath)
      set(ATTR_REQUEST_PATH -> requestPathWithContext)
      set(ATTR_REQUEST_PATH_WITH_QUERY_STRING -> s"${requestPathWithContext}${queryStringPart}")
      // for forms/validator
      set(ATTR_PARAMS -> skinny.controller.Params(params))
      set(ATTR_MULTI_PARAMS -> skinny.controller.MultiParams(multiParams))
      set(ATTR_ERROR_MESSAGES -> Seq())
      set(ATTR_KEY_AND_ERROR_MESSAGES -> KeyAndErrorMessages())
      // i18n in view templates
      setI18n()
    }
  }

  /**
   * Returns whole request scope attributes.
   *
   * @return whole attributes
   */
  def requestScope(): scala.collection.concurrent.Map[String, Any] = RequestScopeFeature.requestScope(request)
  /**
   * Set attribute to request scope.
   *
   * @param keyAndValue key and value
   * @return self
   */
  def requestScope(keyAndValue: (String, Any)): RequestScopeFeature = requestScope(Seq(keyAndValue))

  /**
   * Set attributes to request scope.
   *
   * @param keyAndValues collection of key and value.
   * @return self
   */
  def requestScope(keyAndValues: Seq[(String, Any)]): RequestScopeFeature = {
    keyAndValues.foreach {
      case (key, _) =>
        if (key == "layout") {
          logger.warn("'layout' is a special attribute for Scalate. " +
            "If you're not going to replace layout template, use another key for this attribute. " +
            "Or if you'd like to change layout for this action, use layout(\"/other\") instead.")
        }
    }
    requestScope() ++= keyAndValues
    this
  }

  /**
   * Set attribute to request scope.
   */
  def set(keyAndValue: (String, Any)): RequestScopeFeature = requestScope(Seq(keyAndValue))

  /**
   * Set attributes to request scope.
   */
  def set(keyAndValues: Seq[(String, Any)]): RequestScopeFeature = requestScope(keyAndValues)

  /**
   * Fetches value from request scope.
   *
   * @param key key
   * @tparam A type
   * @return value if exists
   */
  def requestScope[A](key: String): Option[A] = {
    requestScope().get(key).map { v =>
      try v.asInstanceOf[A]
      catch {
        case e: ClassCastException =>
          throw new RequestScopeConflictException(
            s"""\"${key}\" value in request scope is unexpected. (actual: ${v}, error: ${e.getMessage}})""")
      }
    }
  }

  /**
   * Set params which is generated from a model object using Java reflection APIs.
   *
   * @param model model instance
   */
  def setAsParams(model: Any): Unit = {
    import skinny.util.StringUtil.toSnakeCase

    getterNamesFromEntity(model).foreach { getterName =>
      val value = model.getClass.getDeclaredMethod(getterName).invoke(model)
      if (useSnakeCasedParamKeys) {
        addParam(toSnakeCase(getterName), value)
      } else {
        addParam(getterName, value)
      }

      value match {
        case opt: Option[_] => opt foreach {
          case dt: DateTime =>
            if (useSnakeCasedParamKeys) {
              addParam(toSnakeCase(s"${getterName}Year"), dt.getYearOfEra)
              addParam(toSnakeCase(s"${getterName}Month"), dt.getMonthOfYear)
              addParam(toSnakeCase(s"${getterName}Day"), dt.getDayOfMonth)
              addParam(toSnakeCase(s"${getterName}Hour"), dt.getHourOfDay)
              addParam(toSnakeCase(s"${getterName}Minute"), dt.getMinuteOfHour)
              addParam(toSnakeCase(s"${getterName}Second"), dt.getSecondOfMinute)
            } else {
              addParam(s"${getterName}Year", dt.getYearOfEra)
              addParam(s"${getterName}Month", dt.getMonthOfYear)
              addParam(s"${getterName}Day", dt.getDayOfMonth)
              addParam(s"${getterName}Hour", dt.getHourOfDay)
              addParam(s"${getterName}Minute", dt.getMinuteOfHour)
              addParam(s"${getterName}Second", dt.getSecondOfMinute)
            }

          case ld: LocalDate =>
            if (useSnakeCasedParamKeys) {
              addParam(toSnakeCase(s"${getterName}Year"), ld.getYearOfEra)
              addParam(toSnakeCase(s"${getterName}Month"), ld.getMonthOfYear)
              addParam(toSnakeCase(s"${getterName}Day"), ld.getDayOfMonth)
            } else {
              addParam(s"${getterName}Year", ld.getYearOfEra)
              addParam(s"${getterName}Month", ld.getMonthOfYear)
              addParam(s"${getterName}Day", ld.getDayOfMonth)
            }

          case lt: LocalTime =>
            if (useSnakeCasedParamKeys) {
              addParam(toSnakeCase(s"${getterName}Hour"), lt.getHourOfDay)
              addParam(toSnakeCase(s"${getterName}Minute"), lt.getMinuteOfHour)
              addParam(toSnakeCase(s"${getterName}Second"), lt.getSecondOfMinute)
            } else {
              addParam(s"${getterName}Hour", lt.getHourOfDay)
              addParam(s"${getterName}Minute", lt.getMinuteOfHour)
              addParam(s"${getterName}Second", lt.getSecondOfMinute)
            }

          case value =>
        }
        case dt: DateTime =>
          if (useSnakeCasedParamKeys) {
            addParam(toSnakeCase(s"${getterName}Year"), dt.getYearOfEra)
            addParam(toSnakeCase(s"${getterName}Month"), dt.getMonthOfYear)
            addParam(toSnakeCase(s"${getterName}Day"), dt.getDayOfMonth)
            addParam(toSnakeCase(s"${getterName}Hour"), dt.getHourOfDay)
            addParam(toSnakeCase(s"${getterName}Minute"), dt.getMinuteOfHour)
            addParam(toSnakeCase(s"${getterName}Second"), dt.getSecondOfMinute)
          } else {
            addParam(s"${getterName}Year", dt.getYearOfEra)
            addParam(s"${getterName}Month", dt.getMonthOfYear)
            addParam(s"${getterName}Day", dt.getDayOfMonth)
            addParam(s"${getterName}Hour", dt.getHourOfDay)
            addParam(s"${getterName}Minute", dt.getMinuteOfHour)
            addParam(s"${getterName}Second", dt.getSecondOfMinute)
          }

        case ld: LocalDate =>
          if (useSnakeCasedParamKeys) {
            addParam(toSnakeCase(s"${getterName}Year"), ld.getYearOfEra)
            addParam(toSnakeCase(s"${getterName}Month"), ld.getMonthOfYear)
            addParam(toSnakeCase(s"${getterName}Day"), ld.getDayOfMonth)
          } else {
            addParam(s"${getterName}Year", ld.getYearOfEra)
            addParam(s"${getterName}Month", ld.getMonthOfYear)
            addParam(s"${getterName}Day", ld.getDayOfMonth)
          }

        case lt: LocalTime =>
          if (useSnakeCasedParamKeys) {
            addParam(toSnakeCase(s"${getterName}Hour"), lt.getHourOfDay)
            addParam(toSnakeCase(s"${getterName}Minute"), lt.getMinuteOfHour)
            addParam(toSnakeCase(s"${getterName}Second"), lt.getSecondOfMinute)
          } else {
            addParam(s"${getterName}Hour", lt.getHourOfDay)
            addParam(s"${getterName}Minute", lt.getMinuteOfHour)
            addParam(s"${getterName}Second", lt.getSecondOfMinute)
          }

        case value =>
      }
    }
  }

  /**
   * Returns getter names from the target object.
   *
   * @param obj object
   * @return getter names
   */
  private def getterNamesFromEntity(obj: Any): Seq[String] = {
    val fieldNames = obj.getClass.getDeclaredFields
      .filter(f => Modifier.isPrivate(f.getModifiers))
      .filterNot(f => Modifier.isStatic(f.getModifiers))
      .map(_.getName)

    val methodNames = obj.getClass.getDeclaredMethods
      .filter(m => Modifier.isPublic(m.getModifiers))
      .filterNot(m => Modifier.isStatic(m.getModifiers))
      .filterNot(m => m.getParameterTypes.size > 0)
      .map(_.getName)

    methodNames.filter(m => fieldNames.contains(m))
  }

  /**
   * Set params to request scope.
   */
  def setParams() = setParamsToRequestScope()

  /**
   * Set params to request scope.
   */
  def setParamsToRequestScope(): Unit = set(ATTR_PARAMS -> Params(params))

  /**
   * Set {{skinny.I18n}} object for the current request to request scope.
   *
   * @param locale current locale
   * @return self
   */
  def setI18n()(implicit locale: Locale = currentLocale.orNull[Locale]) = {
    set(RequestScopeFeature.ATTR_I18N, I18n(locale))
  }

  /**
   * Add param to params in the request scope.
   *
   * @param name name
   * @param value value
   */
  def addParam(name: String, value: Any): Unit = {

    // ensure "params" in the request scope is valid
    // don't delete requestScope[Any] 's `Any` (because cannot cast Nothing to Params)
    val isParamsInRequestScopeValid = requestScope[Any](ATTR_PARAMS).map(_.isInstanceOf[Params]).getOrElse(false)

    if (isParamsInRequestScopeValid) {
      val updatedParams: Params = {
        Params(requestScope[Params]("params")
          .map(_.underlying)
          .getOrElse(params)
          .updated(name, value))
      }
      set(RequestScopeFeature.ATTR_PARAMS -> updatedParams)

    } else {
      val actual = requestScope(ATTR_PARAMS)
      throw new RequestScopeConflictException(
        s"""Skinny Framework expects that $${params} is a SkinnyParams value. (actual: "${actual}", class: ${actual.getClass.getName})""")
    }
  }

  /**
   * Returns erorrMessages in the RequestScope.
   */
  def errorMessages: Seq[String] = {
    requestScope.get(RequestScopeFeature.ATTR_ERROR_MESSAGES)
      .map(_.asInstanceOf[Seq[String]]).getOrElse(Nil)
  }

  /**
   * Returns keyAndErrorMessages in the RequestScope.
   */
  def keyAndErrorMessages: Map[String, Seq[String]] = {
    requestScope.get(RequestScopeFeature.ATTR_KEY_AND_ERROR_MESSAGES)
      .map(_.asInstanceOf[KeyAndErrorMessages].underlying).getOrElse(Map())
  }

}


text:
layout: post
title: Go 15.1.0 Released
status: public
type: post
published: true
author: Go Team
---

We would like to announce a new release of gocd. Head over to our [downloads page](http://www.go.cd/download/) to get your hands on the latest and greatest. Read more about what's new in this release from our [release notes](http://www.go.cd/releases/#latest).

Sincere thanks to everyone who contributed to Go in form of features, ideas, issues / feature requests and much more! A special mention goes to [@ashwanthkumar](https://github.com/ashwanthkumar), [@alexschwartz](https://github.com/alexschwartz), [@sachinsudheendra](https://github.com/sachinsudheendra), [@pwen](https://github.com/pwen), [@pamo](https://github.com/pamo), [@bernardn](https://github.com/bernardn), [@danielsomerfield](https://github.com/danielsomerfield), [@iliasbartolini](https://github.com/iliasbartolini) for their active contributions and support.

Thanks once again!


text:
import os
import time
import datetime
import json
import operator

import redis
import requests
from pocket import Pocket
from functional import compose
from dateutil.relativedelta import relativedelta
from jinja2 import Environment, FileSystemLoader

from SortedCollection import SortedCollection

class PocketItem(object):
    def __init__(self, json):
        to_datetime = compose(datetime.datetime.utcfromtimestamp,
                              float)

        self.title = json.get('resolved_title').strip()
        self.url = json.get('resolved_url')
        self.item_id = json.get('item_id')
        self.time_added = to_datetime(json.get('time_added'))
        self.time_read = to_datetime(json.get('time_read'))
        self.time_updated = to_datetime(json.get('time_updated'))
        self._status = int(json.get('status'))

    @property
    def is_new(self):
        return self._status == 0

    is_unread = is_new

    @property
    def is_read(self):
        return self._status == 1

    @property
    def is_deleted(self):
        return self._status == 2

    @property
    def status(self):
        return ["undread", "read", "deleted"][self._status]

    def __repr__(self):
        return u"<PocketItem {}>".format(self.item_id)

    def __str__(self):
        return u"({}, {}, A:{}, R:{}, U:{})".format(self.item_id,
                                                    self.status,
                                                    self.time_added,
                                                    self.time_read,
                                                    self.time_updated)

def get_credentials():
    "Extract Pocket API credentials from environment"
    consumer_key = os.environ.get('POCKET_KEY')
    access_token = os.environ.get('POCKET_TOKEN')
    if not consumer_key or not access_token:
        raise ValueError("No key/token found in POCKET_TOKEN or POCKET_KEY")

    return consumer_key, access_token

class PocketStats(object):
    def __init__(self):
        self.redis = redis.StrictRedis(host='localhost', port=6379, db=0)
        self.key, self.token = get_credentials()
        self.pocket = Pocket(self.key, self.token)

        loader = FileSystemLoader(os.path.join(os.path.dirname(os.path.realpath(__file__)), "reports"))
        print os.path.join(os.path.dirname(os.path.realpath(__file__)), "reports")
        self.env = Environment(loader=loader)

    def get_last_sync(self):
        return self.redis.get('pocketstats.last_sync')

    def sync_data(self):
        "Fetch latest data from Pocket to our local redis cache"
        since = self.get_last_sync()
        if since is None:
            since = 'all'

        print("sync since: " + since)
        data, response = self.pocket.get(since=since)

        # pocket returns an empty list instead of an empty dict if
        # there are no changes, so we have to manually check before
        # iterating
        if data['list']:
            for id, item in data['list'].iteritems():
                print("syncing " + id)
                self.redis.set('pocketstats.item:' + id,
                               json.dumps(item))
        else:
            print("Up to date")

        self.redis.set('pocketstats.last_sync', time.time())
        self.redis.bgsave()

    def get_items(self, sync=False):
        "Return all know items as a list of PocketItems.  Sync against pocket if `sync' is true"

        if sync:
            self.sync_data()

        itemskeys = self.redis.keys('pocketstats.item:*')
        items = []
        for doc in self.redis.mget(itemskeys):
            parsed_json = json.loads(doc)
            if parsed_json.get('resolved_url') is not None:
                items.append(PocketItem(parsed_json))

        return items

    def render(self, template, **kwargs):
        template = self.env.get_template(template)
        return template.render(**kwargs)

    def _get_items_since(self, sorted_collection, since):
        first = sorted_collection.find_ge(since)
        index = sorted_collection.index(first)
        return sorted_collection[index:]

    def get_stats(self):
        items = self.get_items(False)
        read = filter(operator.attrgetter("is_read"), items)
        unread = filter(operator.attrgetter("is_unread"), items)

        read_sorted = SortedCollection(read, operator.attrgetter('time_read'))
        unread_sorted = SortedCollection(unread, operator.attrgetter('time_added'))

        # find items read less than a week ago
        now = datetime.datetime.now()
        _7_days_ago = now + relativedelta(days=-7)
        _30_days_ago = now + relativedelta(days=-30)

        print self.render("report.txt",
                          total=len(items),
                          total_read=len(read),
                          total_unread=len(unread),
                          now=now,

                          newly_added_7d=self._get_items_since(unread_sorted, _7_days_ago),
                          newly_read_7d=self._get_items_since(read_sorted, _7_days_ago),

                          newly_added_30d=self._get_items_since(unread_sorted, _30_days_ago),
                          newly_read_30d=self._get_items_since(read_sorted, _30_days_ago)
                      )

if __name__ == '__main__':
    stats = PocketStats()
    stats.get_stats()


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.15"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>reVision: Texture Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

reVision
    5.0.0

Video game engine project.

Public Member Functions |
Public Attributes |
Friends |
List of all members

Texture Class Referencefinal

An encapsulation of an OpenGL texture object.
 More...

#include <Texture.h>

Inheritance diagram for Texture:

  <map id="Texture_map" name="Texture_map">
<area href="class_asset.html" title="An abstract base-class for assets." alt="Asset" shape="rect" coords="0,0,54,24"/>
  </map>

Public Member Functions

 	~Texture ()

 	Destroy the Texture.  More...

 	Texture (Engine &engine, const std::string &filename)

 	Construct the Texture.  More...

 	Texture (Engine &engine, const std::string &filename, const GLuint &type, const bool &mipmap, const bool &anisotropy)

 	Construct the Texture with a specific texture type, and optionally enable mipmapping and anisotropic filtering.  More...

void 	bind (const unsigned int &texture_unit) noexcept

 	Makes this texture active at a specific texture unit.  More...

 Public Member Functions inherited from Asset

virtual 	~Asset ()=default

 	Destroy the asset only when all references are destroyed.  More...

std::string 	getFileName () const

 	Retrieves the file name of this asset.  More...

void 	setFileName (const std::string &filename)

 	Sets the file name of this asset.  More...

void 	addCallback (const std::shared_ptr< bool > &alive, const AssetFinalizedCallback &callback)

 	Attaches a callback method to be triggered when the asset finishes loading.  More...

bool 	ready () const noexcept

 	Retrieves whether or not this asset has completed finalizing.  More...

Public Attributes

GLuint 	m_glTexID = 0

GLuint 	m_type = GL_TEXTURE_2D

bool 	m_mipmap = false

bool 	m_anis = false

Shared_Image 	m_image

Friends

class 	Shared_Texture

Additional Inherited Members

 Static Public Member Functions inherited from Asset

template<typename FirstAsset , typename ... RemainingAssets>

static bool 	All_Ready (const FirstAsset &firstAsset, const RemainingAssets &...rest) noexcept

 	Check if an input variadic list of shared assets have all completed finalizing.  More...

 Protected Member Functions inherited from Asset

 	Asset (Engine &engine, const std::string &filename)

 	Create asset that uses the specified file-path.  More...

void 	finalize ()

 	Declares this asset ready-to-use.  More...

 Protected Attributes inherited from Asset

Engine & 	m_engine

std::atomic_bool 	m_finalized = false

GLsync 	m_fence = nullptr

std::string 	m_filename = ""

std::vector< std::pair< std::shared_ptr< bool >, std::function< void()> > > 	m_callbacks

Detailed Description

An encapsulation of an OpenGL texture object.

Represents an OpenGL texture object, and is responsible for loading the image from disk. Supports MIP-mapping and anisotropic filtering.

Note

owns 1 Shared_Image object.

Constructor & Destructor Documentation

◆ ~Texture()

          Texture::~Texture
          (
          	)

Destroy the Texture.

◆ Texture() [1/2]

          Texture::Texture
          (
          Engine &
          engine,

          const std::string &
          filename

          )

Construct the Texture.

Parameters

engine	reference to the engine to use.

filename	the asset file name (relative to engine directory).

◆ Texture() [2/2]

          Texture::Texture
          (
          Engine &
          engine,

          const std::string &
          filename,

          const GLuint &
          type,

          const bool &
          mipmap,

          const bool &
          anisotropy

          )

Construct the Texture with a specific texture type, and optionally enable mipmapping and anisotropic filtering.

Parameters

engine	reference to the engine to use.

filename	the asset file name (relative to engine directory).

type	the texture type (2D, 3D, CUBEMAP, etc).

mipmap	use mipmaps.

anisotropy	use 16x anisotropic filtering.

Member Function Documentation

◆ bind()

          void Texture::bind
          (
          const unsigned int &
          texture_unit	)

noexcept

Makes this texture active at a specific texture unit.

Parameters

texture_unit	the texture unit to make this texture active at.

The documentation for this class was generated from the following files:

src/Assets/Texture.h

src/Assets/Texture.cpp

<address class="footer">
Generated by

 1.8.15
</address>


text:
/**
 * generated by Xtext 2.12.0
 */
package de.evorepair.feature.expression.ui.labeling;

import org.eclipse.xtext.ui.label.DefaultDescriptionLabelProvider;

/**
 * Provides labels for IEObjectDescriptions and IResourceDescriptions.
 *
 * See https://www.eclipse.org/Xtext/documentation/304_ide_concepts.html#label-provider
 */
@SuppressWarnings("all")
public class EvoExpressionDslDescriptionLabelProvider extends DefaultDescriptionLabelProvider {
}


text:
package ru.job4j.array;

import java.util.Arrays;

public class ArrayDuplicate {
	public String[] remove(String[] array) {
		int original = array.length;
	for (int big = 0; big < original; big++) {
		for (int small = big + 1; small < original; small++) {
			if (array[big].equals(array[small])) {
				array[small] = array[original - 1];
				original--;
				small--;
			}
		}
	}
	return Arrays.copyOf(array, original);
	}

}


text:
package com.betfair.cougar.marshalling.impl.databinding.json;

import com.betfair.cougar.api.ResponseCode;
import com.betfair.cougar.core.api.exception.CougarMarshallingException;
import com.betfair.cougar.core.api.exception.CougarServiceException;
import com.betfair.cougar.core.api.exception.CougarValidationException;
import com.betfair.cougar.core.api.fault.CougarFault;
import com.betfair.cougar.core.api.transcription.ParameterType;
import com.betfair.cougar.marshalling.api.databinding.FaultUnMarshaller;
import com.betfair.cougar.marshalling.api.databinding.UnMarshaller;
import com.betfair.cougar.test.CougarTestCase;
import com.betfair.cougar.util.dates.DateTimeUtility;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.mockito.Mockito;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.util.*;

import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.when;

public class JSONUnMarshallerTest extends CougarTestCase {

    UnMarshaller unMarshaller = new JSONBindingFactory().getUnMarshaller();

    private static final ParameterType TEST_DATE_CLASS_PARAMETER_TYPE = new ParameterType(TestDateClass.class, null);
    private static final ParameterType TEST_CLASS_PARAMETER_TYPE = new ParameterType(TestClass.class, null);

    private static final String UTF8 = "UTF-8";

    public void testUnMarshal() {
        JSONUnMarshaller unMarshaller = new JSONUnMarshaller(new ObjectMapper());

        TestClass test = (TestClass)unMarshaller.unmarshall(new ByteArrayInputStream("{\"message\":\"foo\"}".getBytes()), TestClass.class, UTF8, false);
        assertEquals("foo", test.getMessage());
    }

    public void testUnMarshalExtraField() {
        JSONUnMarshaller unMarshaller = new JSONUnMarshaller(new ObjectMapper());

        TestClass test = (TestClass)unMarshaller.unmarshall(new ByteArrayInputStream("{\"message\":\"foo\", \"xtra\":\"bar\"}".getBytes()), TestClass.class, UTF8, false);
        assertEquals("foo", test.getMessage());
    }

    public void testUnMarshalParseException() {
        JSONUnMarshaller unMarshaller = new JSONUnMarshaller(new ObjectMapper());

        try {
            unMarshaller.unmarshall(new ByteArrayInputStream("{\"message\":\"foo\"".getBytes()), TestClass.class, UTF8, false);
            fail();
        } catch (CougarMarshallingException dve) {
            assertEquals(ResponseCode.BadRequest, dve.getResponseCode());
        }
    }

    public void testUnMarshallDateByParam() {

        testDateByJavaType("2011-03-07T11:02:01.095Z", "2011-03-07T11:02:01.095Z", TEST_DATE_CLASS_PARAMETER_TYPE);
        testDateByJavaType("2009-07-05T00:00:00.001Z", "2009-07-05T00:00:00.001Z", TEST_DATE_CLASS_PARAMETER_TYPE);
        testDateByJavaType("2009-07-05", "2009-07-05T00:00:00.000Z", TEST_DATE_CLASS_PARAMETER_TYPE);
        testDateByJavaType("2009-07-05T00:00:01", "2009-07-05T00:00:01.000Z", TEST_DATE_CLASS_PARAMETER_TYPE);
    }

    public void testUnMarshalDate() {

        TestDateClass test = (TestDateClass)unMarshaller.unmarshall(
                new ByteArrayInputStream("{\"date\":\"2011-03-07T11:02:01.095Z\"}".getBytes()),
                TestDateClass.class,
                UTF8, false);

        Date date = DateTimeUtility.parse("2011-03-07T11:02:01.095Z");
        assertEquals("Mon Mar 07 11:02:01 UTC 2011", test.getDate().toString());
        assertEquals(date, test.getDate());

        testDate("2011-03-07T11:02:01.095Z","2011-03-07T11:02:01.095Z");
        testDate("2009-07-05T00:00:00.001Z","2009-07-05T00:00:00.001Z");
        testDate("2009-07-05","2009-07-05T00:00:00.000Z");
        testDate("2009-07-05T00:00:01","2009-07-05T00:00:01.000Z");

    }

    private void testDate(String in,String out){
               TestDateClass test = (TestDateClass)unMarshaller.unmarshall(
                new ByteArrayInputStream(("{\"date\":\""+in+"\"}").getBytes()),
                TestDateClass.class,
                UTF8, false);

        Date date=DateTimeUtility.parse(out);

        assertEquals(date, test.getDate());
    }

    public void testListMarshallingByJavaType() {
        String[] strings = {
            "West Indies",
            "England",
            "Australia"
        };

        StringBuilder sb = new StringBuilder("[");
        for (int i=0; i<strings.length; i++) {
            if (i>0) {
                sb.append(",");
            }
            sb.append("\"");
            sb.append(strings[i]);
            sb.append("\"");
        }
        sb.append("]");

        ParameterType pt = ParameterType.create(List.class, new Class[] { String.class });

        JSONUnMarshaller unMarshaller = new JSONUnMarshaller(new ObjectMapper());
        List<String> actual = (List<String>)unMarshaller.unmarshall(new ByteArrayInputStream(sb.toString().getBytes()), pt, UTF8, false);

        assertEqualsArray(strings, actual.toArray());
    }

    public void testMapMarshallingByJavaType() {
        Map<String, String> map = new HashMap<>();

        //Cricket world cup was on - teams rated
        map.put("India", "Very good");
        map.put("Australia", "Fair");
        map.put("England", "Unlikely");
        map.put("South Africa", "Fair");

        StringBuilder sb = new StringBuilder("{");
        int i=0;
        for (String s : map.keySet()) {
            if (i++ > 0) {
                sb.append(",");
            }
            sb.append("\"");
            sb.append(s);
            sb.append("\":");
            sb.append("\"");
            sb.append(map.get(s));
            sb.append("\"");
        }
        sb.append("}");

        ParameterType pt = ParameterType.create(Map.class, new Class[] { String.class, String.class });

        JSONUnMarshaller unMarshaller = new JSONUnMarshaller(new ObjectMapper());
        Map<String,String> actual = (Map<String,String>)unMarshaller.unmarshall(new ByteArrayInputStream(sb.toString().getBytes()), pt, UTF8, false);

        assertEqualsArray(map.keySet().toArray(), actual.keySet().toArray());
        assertEqualsArray(map.values().toArray(), actual.values().toArray());
        assertEquals(map.keySet().size(), actual.keySet().size());
        assertEquals(map.get("India"), actual.get("India"));
    }

    private void testDateByJavaType(String in,String out, ParameterType pt){
        TestDateClass test = (TestDateClass)unMarshaller.unmarshall(
        new ByteArrayInputStream(("{\"date\":\""+in+"\"}").getBytes()),
        pt,
        UTF8, false);

        Date date=DateTimeUtility.parse(out);

        assertEquals(date, test.getDate());
    }

    public void testUnMarshalIOExceptionByType() {
        JSONUnMarshaller unMarshaller = new JSONUnMarshaller(new ObjectMapper());
        final IOException ex = new IOException("NOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO");
        try {
            unMarshaller.unmarshall(new InputStream() {

                @Override
                public int read() throws IOException {
                    throw ex;
                }
            }, TEST_CLASS_PARAMETER_TYPE, UTF8, false);
            fail();
        } catch (CougarMarshallingException dse) {
            assertEquals(ex, dse.getCause());
        }

    }

    public void testUnMarshalIOException() {
        JSONUnMarshaller unMarshaller = new JSONUnMarshaller(new ObjectMapper());
        final IOException ex = new IOException("NOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO");
        try {
            unMarshaller.unmarshall(new InputStream() {

                @Override
                public int read() throws IOException {
                    throw ex;
                }
            }, TestClass.class, UTF8, false);
            fail();
        } catch (CougarMarshallingException dse) {
            assertEquals(ex, dse.getCause());
        }
    }

    public void testUnMarshallFault() throws IOException {
        ObjectMapper mockedOM = Mockito.mock(ObjectMapper.class);
        FaultUnMarshaller faultUnMarshaller = new JSONUnMarshaller(mockedOM);

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("value1", "yellow");
        params.put("value2", (byte)100);

        Map<String, Object> detailMap = new HashMap<String, Object>();
        detailMap.put("trace", new Exception().getStackTrace());
        detailMap.put("message", "The rain in spain stays mainly on the plane");
        detailMap.put("exceptionname", "SimpleException");
        detailMap.put("SimpleException", params);

        Map<String, Object> aMap = new HashMap<String, Object>();
        aMap.put("faultcode", "Client");

        final String expectedFaultString = "DSC-0019";

        aMap.put("faultstring", expectedFaultString);
        aMap.put("detail", detailMap);

        when(mockedOM.readValue(any(Reader.class), eq(HashMap.class))).thenReturn((HashMap)aMap);

        CougarFault fault = faultUnMarshaller.unMarshallFault(new ByteArrayInputStream(new byte[]{}), "utf-8");
        assertNotNull(fault);
        assertEquals(expectedFaultString, fault.getErrorCode());
        assertEquals("Client", fault.getFaultCode().name());

        List<String[]> faultMessages = fault.getDetail().getFaultMessages();
        assertEquals(params.size(), faultMessages.size());
        for (String[] pair : faultMessages) {
            assertTrue(pair.length == 2);
            assertTrue(params.containsKey(pair[0]));
            assertEquals(params.get(pair[0]).toString(), pair[1]);
        }

    }

    @JsonIgnoreProperties(ignoreUnknown=true)
    public static class TestClass {
        private String message;
        private RuntimeException ex;

        public String getMessage() {
            return message;
        }

        public void setMessage(String msg) {
            if (ex != null) {
                throw ex;
            }
            message = msg;
        }
    }

    public static class TestDateClass {
        public Date getDate() {
            return date;
        }

        public void setDate(Date date) {
            this.date = date;
        }

        private Date date;

    }
}


text:
cask "hyper" do
  arch = Hardware::CPU.intel? ? "x64" : "arm64"

  version "3.2.3"

  if Hardware::CPU.intel?
    sha256 "08efdaf559d482441fb61557f4e2d0a406f9a96d5489692ebab5ab3fbf0f0915"
  else
    sha256 "90b9ce0bc19fa03d0cfec2ec00f2dd0d74eea3d0a91ab4285bcfd83cbeeefca4"
  end

  url "https://github.com/vercel/hyper/releases/download/v#{version}/Hyper-#{version}-mac-#{arch}.zip",
      verified: "github.com/vercel/hyper/"
  name "Hyper"
  desc "Terminal built on web technologies"
  homepage "https://hyper.is/"

  livecheck do
    url :url
    strategy :github_latest
  end

  auto_updates true
  conflicts_with cask: "homebrew/cask-versions/hyper-canary"

  app "Hyper.app"
  binary "#{appdir}/Hyper.app/Contents/Resources/bin/hyper"

  zap trash: [
    "~/.hyper_plugins",
    "~/.hyper.js",
    "~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/co.zeit.hyper.sfl*",
    "~/Library/Application Support/Hyper",
    "~/Library/Caches/co.zeit.hyper.ShipIt",
    "~/Library/Caches/co.zeit.hyper",
    "~/Library/Cookies/co.zeit.hyper.binarycookies",
    "~/Library/Logs/Hyper",
    "~/Library/Preferences/ByHost/co.zeit.hyper.ShipIt.*.plist",
    "~/Library/Preferences/co.zeit.hyper.helper.plist",
    "~/Library/Preferences/co.zeit.hyper.plist",
    "~/Library/Saved Application State/co.zeit.hyper.savedState",
  ]
end


text:
package com.gigigo.orchextra.android.builders;

import com.gigigo.orchextra.domain.model.ProximityPointType;
import com.gigigo.orchextra.domain.model.entities.proximity.OrchextraGeofence;
import com.gigigo.orchextra.domain.model.vo.OrchextraPoint;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class ControlGeofenceBuilder {

    public static final OrchextraPoint POINT = OrchextraPointBuilder.Builder().build();
    public static final int RADIUS = 30;
    public static final String ID = "1234";
    public static final String CODE = "999";
    public static final String NAME = "GEOFENCE";
    public static final ProximityPointType TYPE = ProximityPointType.GEOFENCE;
    public static final int STAY = 3000;
    public static final Date CREATED = DateBuilder.getCalendar(2013, Calendar.SEPTEMBER, 29, 18, 46, 19);
    public static final Date UPDATED = DateBuilder.getCalendar(2014, Calendar.SEPTEMBER, 29, 18, 46, 19);
    public static final String TAG_NAME = "tagName";

    public static final String CREATEDS = "2013-09-29T18:46:19Z";
    public static final String UPDATEDS = "2014-09-29T18:46:19Z";

    private OrchextraPoint point = POINT;
    private int radius = RADIUS;
    private String id = ID;
    private String code = CODE;
    private String name = NAME;
    private ProximityPointType type = TYPE;
    private int stay = STAY;
    private Date created = CREATED;
    private Date updated = UPDATED;
    private String tag = TAG_NAME;

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

    public OrchextraGeofence build() {
        OrchextraGeofence geofence = new OrchextraGeofence();
        geofence.setPoint(point);
        geofence.setRadius(radius);
        geofence.setId(id);
        geofence.setCode(code);
        geofence.setName(name);
        geofence.setType(type);
        geofence.setNotifyOnEntry(true);
        geofence.setNotifyOnExit(true);
        geofence.setCreatedAt(created);
        geofence.setUpdatedAt(updated);
        geofence.setStayTime(stay);

        List<String> list = new ArrayList<>();
        list.add(tag);

        geofence.setTags(list);

        return geofence;
    }
}


text:
title:  Misijní příběh
date:   30/09/2022
---

#### Osvobozen z řetězů

_Andrew McChesney_

Vzduch v zemědělské vesnici v Laosu pronikaly výkřiky.

Pastor adventistů sedmého dne, který vesnici navštívil s malým týmem církevních pracovníků, zamířil k hlasitému křiku, aby zjistil, co se děje. S překvapením spatřil šestnáctiletého chlapce připoutaného řetězem k dřevěné podlaze rodinného domu. "Co se stalo vašemu chlapci?" zeptal se rodičů. "Proč je připoutaný?"

Rodiče vypadali smutně. "Náš syn Aer je už mnoho let nemocný," řekl otec. "Na několik hodin se stane normálním, ale pak zase přijde o rozum. Děje se tak několikrát denně," dodala jeho matka.

Rodiče utratili všechny své peníze, aby našli lék. Situace se však neustále zhoršovala, až se neochotně rozhodli nechat Aera stále v řetězech, aby neublížil sobě ani ostatním. K dřevěné podlaze byl připoután posledních šest měsíců.

Pastor s Aerem promluvil a vyprávěl mu i jeho rodičům o Ježíšově zachraňující lásce. "Pokud to bude Ježíšova vůle, může Aera uzdravit," řekl.

Požádal o svolení modlit se za chlapce. Aerovi rodiče s radostí souhlasili. Ve tvářích jim zářila naděje, že jejich syn bude uzdraven.

O několik dní později pastor se svým týmem znovu navštívil Aera a modlil se za něj. Pastor pozval rodinu na bohoslužbu do nejbližšího adventistického sboru v sousední vesnici.

Následující sobotu přišli rodiče do sboru s Aerem, který měl ruce spoutané řetězy. Každý člen církve se za Aera modlil a poté pastor požádal také chlapcova otce, aby se za něj pomodlil. Všechny hlavy se sklonily, když se otec modlil k Ježíši za svého syna. Od toho dne byl chlapec uzdraven. Vrátil se do normálního života a už nemusel být připoután.

Sousedé byli ohromeni a zasypali Arovy rodiče otázkami.

"Je to ten chlapec, který byl dlouhá léta nemocný a byl připoutaný?" ptal se jeden z nich.

"Proč je teď v pořádku?" ptal se další. "Kdo ho uzdravil?"

Rodiče vysvětlili, že jejich chlapce uzdravil křesťanský Bůh.

Po uzdravení přijali Ježíše jako svého osobního Spasitele nejen Aerovi rodiče, ale i mnoho dalších rodin. Tyto rodiny patří mezi 122 lidí, kteří byli v dubnu 2021 ve sboru pokřtěni a zaplnili tak budovu sboru do posledního místa.

"Chválíme Boha za to, že v této oblasti vykonal tolik zázraků, které vedly k tomu, že k Němu přišlo mnoho lidí, aby byli zachráněni," řekl laoský pastor, který se o tento příběh podělil s organizací Adventist Mission.

_Děkujeme vám za vaše misijní dary při sobotní škole, které podporují šíření evangelia v Laosu a po celém světě._