#ifndef PYTHONIC_BUILTIN_LEN_HPP
#define PYTHONIC_BUILTIN_LEN_HPP

#include "pythonic/include/builtins/len.hpp"

#include "pythonic/types/traits.hpp"
#include "pythonic/utils/functor.hpp"

#include <tuple>
#include <iterator>

PYTHONIC_NS_BEGIN

namespace builtins
{
  template <class... Types>
  long len(std::tuple<Types...> const &)
  {
    return sizeof...(Types);
  }

  template <class T>
  typename std::enable_if<types::has_size<T>::value, long>::type len(T const &t)
  {
    return t.size();
  }
}
PYTHONIC_NS_END
#endif

{'repo_name': 'serge-sans-paille/pythran', 'stars': '1428', 'repo_language': 'Python', 'file_name': 'typeof_impl.hpp', 'mime_type': 'text/x-c++', 'hash': -3588897707707891226, 'source_dataset': 'data'}


/**@file

Copyright (c) 2006 - 2015, Intel Corporation. All rights reserved.

(C) Copyright 2016 Hewlett Packard Enterprise Development LP

This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution.  The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php

THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.

Module Name:

  SecMain.c

Abstract:
  WinNt emulator of SEC phase. It's really a Win32 application, but this is
  Ok since all the other modules for NT32 are NOT Win32 applications.

  This program gets NT32 PCD setting and figures out what the memory layout
  will be, how may FD's will be loaded and also what the boot mode is.

  The SEC registers a set of services with the SEC core. gPrivateDispatchTable
  is a list of PPI's produced by the SEC that are available for usage in PEI.

  This code produces 128 K of temporary memory for the PEI stack by directly
  allocate memory space with ReadWrite and Execute attribute.

**/

#include "SecMain.h"

#ifndef SE_TIME_ZONE_NAME
#define SE_TIME_ZONE_NAME                 TEXT("SeTimeZonePrivilege")
#endif

NT_PEI_LOAD_FILE_PPI                      mSecNtLoadFilePpi     = { SecWinNtPeiLoadFile };

PEI_NT_AUTOSCAN_PPI                       mSecNtAutoScanPpi     = { SecWinNtPeiAutoScan };

PEI_NT_THUNK_PPI                          mSecWinNtThunkPpi     = { SecWinNtWinNtThunkAddress };

EFI_PEI_PROGRESS_CODE_PPI                 mSecStatusCodePpi     = { SecPeiReportStatusCode };

NT_FWH_PPI                                mSecFwhInformationPpi = { SecWinNtFdAddress };

EFI_PEI_TEMPORARY_RAM_SUPPORT_PPI         mSecTemporaryRamSupportPpi = {SecTemporaryRamSupport};

EFI_PEI_PPI_DESCRIPTOR  gPrivateDispatchTable[] = {
  {
    EFI_PEI_PPI_DESCRIPTOR_PPI,
    &gNtPeiLoadFilePpiGuid,
    &mSecNtLoadFilePpi
  },
  {
    EFI_PEI_PPI_DESCRIPTOR_PPI,
    &gPeiNtAutoScanPpiGuid,
    &mSecNtAutoScanPpi
  },
  {
    EFI_PEI_PPI_DESCRIPTOR_PPI,
    &gPeiNtThunkPpiGuid,
    &mSecWinNtThunkPpi
  },
  {
    EFI_PEI_PPI_DESCRIPTOR_PPI,
    &gEfiPeiStatusCodePpiGuid,
    &mSecStatusCodePpi
  },
  {
    EFI_PEI_PPI_DESCRIPTOR_PPI,
    &gEfiTemporaryRamSupportPpiGuid,
    &mSecTemporaryRamSupportPpi
  },
  {
    EFI_PEI_PPI_DESCRIPTOR_PPI | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST,
    &gNtFwhPpiGuid,
    &mSecFwhInformationPpi
  }
};

//
// Default information about where the FD is located.
//  This array gets filled in with information from PcdWinNtFirmwareVolume
//  The number of array elements is allocated base on parsing
//  PcdWinNtFirmwareVolume and the memory is never freed.
//
UINTN                                     gFdInfoCount = 0;
NT_FD_INFO                                *gFdInfo;

//
// Array that supports seperate memory rantes.
//  The memory ranges are set by PcdWinNtMemorySizeForSecMain.
//  The number of array elements is allocated base on parsing
//  PcdWinNtMemorySizeForSecMain value and the memory is never freed.
//
UINTN                                     gSystemMemoryCount = 0;
NT_SYSTEM_MEMORY                          *gSystemMemory;

VOID
EFIAPI
SecSwitchStack (
  UINT32   TemporaryMemoryBase,
  UINT32   PermenentMemoryBase
  );
EFI_STATUS
SecNt32PeCoffRelocateImage (
  IN OUT PE_COFF_LOADER_IMAGE_CONTEXT         *ImageContext
  );

VOID
EFIAPI
PeiSwitchStacks (
  IN      SWITCH_STACK_ENTRY_POINT  EntryPoint,
  IN      VOID                      *Context1,  OPTIONAL
  IN      VOID                      *Context2,  OPTIONAL
  IN      VOID                      *Context3,  OPTIONAL
  IN      VOID                      *NewStack
  );

VOID
SecPrint (
  CHAR8  *Format,
  ...
  )
{
  va_list  Marker;
  UINTN    CharCount;
  CHAR8    Buffer[EFI_STATUS_CODE_DATA_MAX_SIZE];

  va_start (Marker, Format);

  _vsnprintf (Buffer, sizeof (Buffer), Format, Marker);

  va_end (Marker);

  CharCount = strlen (Buffer);
  WriteFile (
    GetStdHandle (STD_OUTPUT_HANDLE),
    Buffer,
    (DWORD)CharCount,
    (LPDWORD)&CharCount,
    NULL
    );
}

INTN
EFIAPI
main (
  IN  INTN  Argc,
  IN  CHAR8 **Argv,
  IN  CHAR8 **Envp
  )
/*++

Routine Description:
  Main entry point to SEC for WinNt. This is a Windows program

Arguments:
  Argc - Number of command line arguments
  Argv - Array of command line argument strings
  Envp - Array of environment variable strings

Returns:
  0 - Normal exit
  1 - Abnormal exit

--*/
{
  EFI_STATUS            Status;
  HANDLE                Token;
  TOKEN_PRIVILEGES      TokenPrivileges;
  EFI_PHYSICAL_ADDRESS  InitialStackMemory;
  UINT64                InitialStackMemorySize;
  UINTN                 Index;
  UINTN                 Index1;
  UINTN                 Index2;
  CHAR16                *FileName;
  CHAR16                *FileNamePtr;
  BOOLEAN               Done;
  VOID                  *PeiCoreFile;
  CHAR16                *MemorySizeStr;
  CHAR16                *FirmwareVolumesStr;
  UINTN                 *StackPointer;
  UINT32                ProcessAffinityMask;
  UINT32                SystemAffinityMask;
  INT32                 LowBit;

  //
  // Enable the privilege so that RTC driver can successfully run SetTime()
  //
  OpenProcessToken (GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY, &Token);
  if (LookupPrivilegeValue(NULL, SE_TIME_ZONE_NAME, &TokenPrivileges.Privileges[0].Luid)) {
    TokenPrivileges.PrivilegeCount = 1;
    TokenPrivileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
    AdjustTokenPrivileges(Token, FALSE, &TokenPrivileges, 0, (PTOKEN_PRIVILEGES) NULL, 0);
  }

  MemorySizeStr      = (CHAR16 *) PcdGetPtr (PcdWinNtMemorySizeForSecMain);
  FirmwareVolumesStr = (CHAR16 *) PcdGetPtr (PcdWinNtFirmwareVolume);

  SecPrint ("\nEDK II SEC Main NT Emulation Environment from www.TianoCore.org\n");

  //
  // Determine the first thread available to this process.
  //
  if (GetProcessAffinityMask (GetCurrentProcess (), &ProcessAffinityMask, &SystemAffinityMask)) {
    LowBit = (INT32)LowBitSet32 (ProcessAffinityMask);
    if (LowBit != -1) {
      //
      // Force the system to bind the process to a single thread to work
      // around odd semaphore type crashes.
      //
      SetProcessAffinityMask (GetCurrentProcess (), (INTN)(BIT0 << LowBit));
    }
  }

  //
  // Make some Windows calls to Set the process to the highest priority in the
  //  idle class. We need this to have good performance.
  //
  SetPriorityClass (GetCurrentProcess (), IDLE_PRIORITY_CLASS);
  SetThreadPriority (GetCurrentThread (), THREAD_PRIORITY_HIGHEST);

  //
  // Allocate space for gSystemMemory Array
  //
  gSystemMemoryCount  = CountSeparatorsInString (MemorySizeStr, '!') + 1;
  gSystemMemory       = calloc (gSystemMemoryCount, sizeof (NT_SYSTEM_MEMORY));
  if (gSystemMemory == NULL) {
    SecPrint ("ERROR : Can not allocate memory for %S.  Exiting.\n", MemorySizeStr);
    exit (1);
  }
  //
  // Allocate space for gSystemMemory Array
  //
  gFdInfoCount  = CountSeparatorsInString (FirmwareVolumesStr, '!') + 1;
  gFdInfo       = calloc (gFdInfoCount, sizeof (NT_FD_INFO));
  if (gFdInfo == NULL) {
    SecPrint ("ERROR : Can not allocate memory for %S.  Exiting.\n", FirmwareVolumesStr);
    exit (1);
  }
  //
  // Setup Boot Mode. If BootModeStr == "" then BootMode = 0 (BOOT_WITH_FULL_CONFIGURATION)
  //
  SecPrint ("  BootMode 0x%02x\n", PcdGet32 (PcdWinNtBootMode));

  //
  //  Allocate 128K memory to emulate temp memory for PEI.
  //  on a real platform this would be SRAM, or using the cache as RAM.
  //  Set InitialStackMemory to zero so WinNtOpenFile will allocate a new mapping
  //
  InitialStackMemorySize  = STACK_SIZE;
  InitialStackMemory = (EFI_PHYSICAL_ADDRESS) (UINTN) VirtualAlloc (NULL, (SIZE_T) (InitialStackMemorySize), MEM_COMMIT, PAGE_EXECUTE_READWRITE);
  if (InitialStackMemory == 0) {
    SecPrint ("ERROR : Can not allocate enough space for SecStack\n");
    exit (1);
  }

  for (StackPointer = (UINTN*) (UINTN) InitialStackMemory;
       StackPointer < (UINTN*) ((UINTN)InitialStackMemory + (SIZE_T) InitialStackMemorySize);
       StackPointer ++) {
    *StackPointer = PcdGet32 (PcdInitValueInTempStack);
  }

  SecPrint ("  SEC passing in %d bytes of temp RAM to PEI\n", InitialStackMemorySize);

  //
  // Open All the firmware volumes and remember the info in the gFdInfo global
  //
  FileNamePtr = (CHAR16 *)malloc (StrLen ((CHAR16 *)FirmwareVolumesStr) * sizeof(CHAR16));
  if (FileNamePtr == NULL) {
    SecPrint ("ERROR : Can not allocate memory for firmware volume string\n");
    exit (1);
  }

  StrCpy (FileNamePtr, (CHAR16*)FirmwareVolumesStr);

  for (Done = FALSE, Index = 0, PeiCoreFile = NULL; !Done; Index++) {
    FileName = FileNamePtr;
    for (Index1 = 0; (FileNamePtr[Index1] != '!') && (FileNamePtr[Index1] != 0); Index1++)
      ;
    if (FileNamePtr[Index1] == 0) {
      Done = TRUE;
    } else {
      FileNamePtr[Index1]  = '\0';
      FileNamePtr = FileNamePtr + Index1 + 1;
    }

    //
    // Open the FD and remember where it got mapped into our processes address space
    //
    Status = WinNtOpenFile (
              FileName,
              0,
              OPEN_EXISTING,
              &gFdInfo[Index].Address,
              &gFdInfo[Index].Size
              );
    if (EFI_ERROR (Status)) {
      SecPrint ("ERROR : Can not open Firmware Device File %S (0x%X).  Exiting.\n", FileName, Status);
      exit (1);
    }

    SecPrint ("  FD loaded from");
    //
    // printf can't print filenames directly as the \ gets interpreted as an
    //  escape character.
    //
    for (Index2 = 0; FileName[Index2] != '\0'; Index2++) {
      SecPrint ("%c", FileName[Index2]);
    }

    if (PeiCoreFile == NULL) {
      //
      // Assume the beginning of the FD is an FV and look for the PEI Core.
      // Load the first one we find.
      //
      Status = SecFfsFindPeiCore ((EFI_FIRMWARE_VOLUME_HEADER *) (UINTN) gFdInfo[Index].Address, &PeiCoreFile);
      if (!EFI_ERROR (Status)) {
        SecPrint (" contains SEC Core");
      }
    }

    SecPrint ("\n");
  }
  //
  // Calculate memory regions and store the information in the gSystemMemory
  //  global for later use. The autosizing code will use this data to
  //  map this memory into the SEC process memory space.
  //
  for (Index = 0, Done = FALSE; !Done; Index++) {
    //
    // Save the size of the memory and make a Unicode filename SystemMemory00, ...
    //
    gSystemMemory[Index].Size = _wtoi (MemorySizeStr) * 0x100000;

    //
    // Find the next region
    //
    for (Index1 = 0; MemorySizeStr[Index1] != '!' && MemorySizeStr[Index1] != 0; Index1++)
      ;
    if (MemorySizeStr[Index1] == 0) {
      Done = TRUE;
    }

    MemorySizeStr = MemorySizeStr + Index1 + 1;
  }

  SecPrint ("\n");

  //
  // Hand off to PEI Core
  //
  SecLoadFromCore ((UINTN) InitialStackMemory, (UINTN) InitialStackMemorySize, (UINTN) gFdInfo[0].Address, PeiCoreFile);

  //
  // If we get here, then the PEI Core returned. This is an error as PEI should
  //  always hand off to DXE.
  //
  SecPrint ("ERROR : PEI Core returned\n");
  exit (1);
}

EFI_STATUS
WinNtOpenFile (
  IN  CHAR16                    *FileName,
  IN  UINT32                    MapSize,
  IN  DWORD                     CreationDisposition,
  IN OUT  EFI_PHYSICAL_ADDRESS  *BaseAddress,
  OUT UINT64                    *Length
  )
/*++

Routine Description:
  Opens and memory maps a file using WinNt services. If BaseAddress is non zero
  the process will try and allocate the memory starting at BaseAddress.

Arguments:
  FileName            - The name of the file to open and map
  MapSize             - The amount of the file to map in bytes
  CreationDisposition - The flags to pass to CreateFile().  Use to create new files for
                        memory emulation, and exiting files for firmware volume emulation
  BaseAddress         - The base address of the mapped file in the user address space.
                         If passed in as NULL the new memory region is used.
                         If passed in as non NULL the request memory region is used for
                          the mapping of the file into the process space.
  Length              - The size of the mapped region in bytes

Returns:
  EFI_SUCCESS      - The file was opened and mapped.
  EFI_NOT_FOUND    - FileName was not found in the current directory
  EFI_DEVICE_ERROR - An error occured attempting to map the opened file

--*/
{
  HANDLE  NtFileHandle;
  HANDLE  NtMapHandle;
  VOID    *VirtualAddress;
  UINTN   FileSize;

  //
  // Use Win API to open/create a file
  //
  NtFileHandle = CreateFile (
                  FileName,
                  GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE,
                  FILE_SHARE_READ,
                  NULL,
                  CreationDisposition,
                  FILE_ATTRIBUTE_NORMAL,
                  NULL
                  );
  if (NtFileHandle == INVALID_HANDLE_VALUE) {
    return EFI_NOT_FOUND;
  }
  //
  // Map the open file into a memory range
  //
  NtMapHandle = CreateFileMapping (
                  NtFileHandle,
                  NULL,
                  PAGE_EXECUTE_READWRITE,
                  0,
                  MapSize,
                  NULL
                  );
  if (NtMapHandle == NULL) {
    return EFI_DEVICE_ERROR;
  }
  //
  // Get the virtual address (address in the emulator) of the mapped file
  //
  VirtualAddress = MapViewOfFileEx (
                    NtMapHandle,
                    FILE_MAP_EXECUTE | FILE_MAP_ALL_ACCESS,
                    0,
                    0,
                    MapSize,
                    (LPVOID) (UINTN) *BaseAddress
                    );
  if (VirtualAddress == NULL) {
    return EFI_DEVICE_ERROR;
  }

  if (MapSize == 0) {
    //
    // Seek to the end of the file to figure out the true file size.
    //
    FileSize = SetFilePointer (
                NtFileHandle,
                0,
                NULL,
                FILE_END
                );
    if (FileSize == -1) {
      return EFI_DEVICE_ERROR;
    }

    *Length = (UINT64) FileSize;
  } else {
    *Length = (UINT64) MapSize;
  }

  *BaseAddress = (EFI_PHYSICAL_ADDRESS) (UINTN) VirtualAddress;

  return EFI_SUCCESS;
}

#define BYTES_PER_RECORD  512

EFI_STATUS
EFIAPI
SecPeiReportStatusCode (
  IN CONST EFI_PEI_SERVICES           **PeiServices,
  IN EFI_STATUS_CODE_TYPE       CodeType,
  IN EFI_STATUS_CODE_VALUE      Value,
  IN UINT32                     Instance,
  IN CONST EFI_GUID                   *CallerId,
  IN CONST EFI_STATUS_CODE_DATA       *Data OPTIONAL
  )
/*++

Routine Description:

  This routine produces the ReportStatusCode PEI service. It's passed
  up to the PEI Core via a PPI. T

  This code currently uses the NT clib printf. This does not work the same way
  as the EFI Print (), as %t, %g, %s as Unicode are not supported.

Arguments:
  (see EFI_PEI_REPORT_STATUS_CODE)

Returns:
  EFI_SUCCESS - Always return success

--*/
// TODO:    PeiServices - add argument and description to function comment
// TODO:    CodeType - add argument and description to function comment
// TODO:    Value - add argument and description to function comment
// TODO:    Instance - add argument and description to function comment
// TODO:    CallerId - add argument and description to function comment
// TODO:    Data - add argument and description to function comment
{
  CHAR8           *Format;
  BASE_LIST       Marker;
  CHAR8           PrintBuffer[BYTES_PER_RECORD * 2];
  CHAR8           *Filename;
  CHAR8           *Description;
  UINT32          LineNumber;
  UINT32          ErrorLevel;

  if (Data == NULL) {
  } else if (ReportStatusCodeExtractAssertInfo (CodeType, Value, Data, &Filename, &Description, &LineNumber)) {
    //
    // Processes ASSERT ()
    //
    SecPrint ("ASSERT %s(%d): %s\n", Filename, (int)LineNumber, Description);

  } else if (ReportStatusCodeExtractDebugInfo (Data, &ErrorLevel, &Marker, &Format)) {
    //
    // Process DEBUG () macro
    //
    AsciiBSPrint (PrintBuffer, BYTES_PER_RECORD, Format, Marker);
    SecPrint (PrintBuffer);
  }

  return EFI_SUCCESS;
}

#if defined (MDE_CPU_IA32)
/**
  Transfers control to a function starting with a new stack.

  Transfers control to the function specified by EntryPoint using the new stack
  specified by NewStack and passing in the parameters specified by Context1 and
  Context2. Context1 and Context2 are optional and may be NULL. The function
  EntryPoint must never return.

  If EntryPoint is NULL, then ASSERT().
  If NewStack is NULL, then ASSERT().

  @param  EntryPoint  A pointer to function to call with the new stack.
  @param  Context1    A pointer to the context to pass into the EntryPoint
                      function.
  @param  Context2    A pointer to the context to pass into the EntryPoint
                      function.
  @param  NewStack    A pointer to the new stack to use for the EntryPoint
                      function.
  @param  NewBsp      A pointer to the new BSP for the EntryPoint on IPF. It's
                      Reserved on other architectures.

**/
VOID
EFIAPI
PeiSwitchStacks (
  IN      SWITCH_STACK_ENTRY_POINT  EntryPoint,
  IN      VOID                      *Context1,  OPTIONAL
  IN      VOID                      *Context2,  OPTIONAL
  IN      VOID                      *Context3,  OPTIONAL
  IN      VOID                      *NewStack
  )
{
  BASE_LIBRARY_JUMP_BUFFER  JumpBuffer;

  ASSERT (EntryPoint != NULL);
  ASSERT (NewStack != NULL);

  //
  // Stack should be aligned with CPU_STACK_ALIGNMENT
  //
  ASSERT (((UINTN)NewStack & (CPU_STACK_ALIGNMENT - 1)) == 0);

  JumpBuffer.Eip = (UINTN)EntryPoint;
  JumpBuffer.Esp = (UINTN)NewStack - sizeof (VOID*);
  JumpBuffer.Esp -= sizeof (Context1) + sizeof (Context2) + sizeof(Context3);
  ((VOID**)JumpBuffer.Esp)[1] = Context1;
  ((VOID**)JumpBuffer.Esp)[2] = Context2;
  ((VOID**)JumpBuffer.Esp)[3] = Context3;

  LongJump (&JumpBuffer, (UINTN)-1);

  //
  // InternalSwitchStack () will never return
  //
  ASSERT (FALSE);
}
#endif

VOID
SecLoadFromCore (
  IN  UINTN   LargestRegion,
  IN  UINTN   LargestRegionSize,
  IN  UINTN   BootFirmwareVolumeBase,
  IN  VOID    *PeiCorePe32File
  )
/*++

Routine Description:
  This is the service to load the PEI Core from the Firmware Volume

Arguments:
  LargestRegion           - Memory to use for PEI.
  LargestRegionSize       - Size of Memory to use for PEI
  BootFirmwareVolumeBase  - Start of the Boot FV
  PeiCorePe32File         - PEI Core PE32

Returns:
  Success means control is transfered and thus we should never return

--*/
{
  EFI_STATUS                  Status;
  VOID                        *TopOfStack;
  UINT64                      PeiCoreSize;
  EFI_PHYSICAL_ADDRESS        PeiCoreEntryPoint;
  EFI_PHYSICAL_ADDRESS        PeiImageAddress;
  EFI_SEC_PEI_HAND_OFF        *SecCoreData;
  UINTN                       PeiStackSize;

  //
  // Compute Top Of Memory for Stack and PEI Core Allocations
  //
  PeiStackSize = (UINTN)RShiftU64((UINT64)STACK_SIZE,1);

  //
  // |-----------| <---- TemporaryRamBase + TemporaryRamSize
  // |   Heap    |
  // |           |
  // |-----------| <---- StackBase / PeiTemporaryMemoryBase
  // |           |
  // |  Stack    |
  // |-----------| <---- TemporaryRamBase
  //
  TopOfStack  = (VOID *)(LargestRegion + PeiStackSize);

  //
  // Reservet space for storing PeiCore's parament in stack.
  //
  TopOfStack  = (VOID *)((UINTN)TopOfStack - sizeof (EFI_SEC_PEI_HAND_OFF) - CPU_STACK_ALIGNMENT);
  TopOfStack  = ALIGN_POINTER (TopOfStack, CPU_STACK_ALIGNMENT);

  //
  // Bind this information into the SEC hand-off state
  //
  SecCoreData                        = (EFI_SEC_PEI_HAND_OFF*)(UINTN) TopOfStack;
  SecCoreData->DataSize               = sizeof(EFI_SEC_PEI_HAND_OFF);
  SecCoreData->BootFirmwareVolumeBase = (VOID*)BootFirmwareVolumeBase;
  SecCoreData->BootFirmwareVolumeSize = PcdGet32(PcdWinNtFirmwareFdSize);
  SecCoreData->TemporaryRamBase       = (VOID*)(UINTN)LargestRegion;
  SecCoreData->TemporaryRamSize       = STACK_SIZE;
  SecCoreData->StackBase              = SecCoreData->TemporaryRamBase;
  SecCoreData->StackSize              = PeiStackSize;
  SecCoreData->PeiTemporaryRamBase    = (VOID*) ((UINTN) SecCoreData->TemporaryRamBase + PeiStackSize);
  SecCoreData->PeiTemporaryRamSize    = STACK_SIZE - PeiStackSize;

  //
  // Load the PEI Core from a Firmware Volume
  //
  Status = SecWinNtPeiLoadFile (
            PeiCorePe32File,
            &PeiImageAddress,
            &PeiCoreSize,
            &PeiCoreEntryPoint
            );
  if (EFI_ERROR (Status)) {
    return ;
  }

  //
  // Transfer control to the PEI Core
  //
  PeiSwitchStacks (
    (SWITCH_STACK_ENTRY_POINT) (UINTN) PeiCoreEntryPoint,
    SecCoreData,
    (VOID *) (UINTN) ((EFI_PEI_PPI_DESCRIPTOR *) &gPrivateDispatchTable),
    NULL,
    TopOfStack
    );
  //
  // If we get here, then the PEI Core returned.  This is an error
  //
  return ;
}

EFI_STATUS
EFIAPI
SecWinNtPeiAutoScan (
  IN  UINTN                 Index,
  OUT EFI_PHYSICAL_ADDRESS  *MemoryBase,
  OUT UINT64                *MemorySize
  )
/*++

Routine Description:
  This service is called from Index == 0 until it returns EFI_UNSUPPORTED.
  It allows discontinuous memory regions to be supported by the emulator.
  It uses gSystemMemory[] and gSystemMemoryCount that were created by
  parsing PcdWinNtMemorySizeForSecMain value.
  The size comes from the Pcd value and the address comes from the memory space
  with ReadWrite and Execute attributes allocated by VirtualAlloc() API.

Arguments:
  Index      - Which memory region to use
  MemoryBase - Return Base address of memory region
  MemorySize - Return size in bytes of the memory region

Returns:
  EFI_SUCCESS - If memory region was mapped
  EFI_UNSUPPORTED - If Index is not supported

--*/
{
  if (Index >= gSystemMemoryCount) {
    return EFI_UNSUPPORTED;
  }

  //
  // Allocate enough memory space for emulator
  //
  gSystemMemory[Index].Memory = (EFI_PHYSICAL_ADDRESS) (UINTN) VirtualAlloc (NULL, (SIZE_T) (gSystemMemory[Index].Size), MEM_COMMIT, PAGE_EXECUTE_READWRITE);
  if (gSystemMemory[Index].Memory == 0) {
    return EFI_OUT_OF_RESOURCES;
  }

  *MemoryBase = gSystemMemory[Index].Memory;
  *MemorySize = gSystemMemory[Index].Size;

  return EFI_SUCCESS;
}

VOID *
EFIAPI
SecWinNtWinNtThunkAddress (
  VOID
  )
/*++

Routine Description:
  Since the SEC is the only Windows program in stack it must export
  an interface to do Win API calls. That's what the WinNtThunk address
  is for. gWinNt is initialized in WinNtThunk.c.

Arguments:
  InterfaceSize - sizeof (EFI_WIN_NT_THUNK_PROTOCOL);
  InterfaceBase - Address of the gWinNt global

Returns:
  EFI_SUCCESS - Data returned

--*/
{
  return gWinNt;
}

EFI_STATUS
EFIAPI
SecWinNtPeiLoadFile (
  IN  VOID                    *Pe32Data,
  IN  EFI_PHYSICAL_ADDRESS    *ImageAddress,
  IN  UINT64                  *ImageSize,
  IN  EFI_PHYSICAL_ADDRESS    *EntryPoint
  )
/*++

Routine Description:
  Loads and relocates a PE/COFF image into memory.

Arguments:
  Pe32Data         - The base address of the PE/COFF file that is to be loaded and relocated
  ImageAddress     - The base address of the relocated PE/COFF image
  ImageSize        - The size of the relocated PE/COFF image
  EntryPoint       - The entry point of the relocated PE/COFF image

Returns:
  EFI_SUCCESS   - The file was loaded and relocated
  EFI_OUT_OF_RESOURCES - There was not enough memory to load and relocate the PE/COFF file

--*/
{
  EFI_STATUS                            Status;
  PE_COFF_LOADER_IMAGE_CONTEXT          ImageContext;

  ZeroMem (&ImageContext, sizeof (ImageContext));
  ImageContext.Handle     = Pe32Data;

  ImageContext.ImageRead  = (PE_COFF_LOADER_READ_FILE) SecImageRead;

  Status                  = PeCoffLoaderGetImageInfo (&ImageContext);
  if (EFI_ERROR (Status)) {
    return Status;
  }
  //
  // Allocate space in NT (not emulator) memory with ReadWrite and Execute attribute.
  // Extra space is for alignment
  //
  ImageContext.ImageAddress = (EFI_PHYSICAL_ADDRESS) (UINTN) VirtualAlloc (NULL, (SIZE_T) (ImageContext.ImageSize + (ImageContext.SectionAlignment * 2)), MEM_COMMIT, PAGE_EXECUTE_READWRITE);
  if (ImageContext.ImageAddress == 0) {
    return EFI_OUT_OF_RESOURCES;
  }
  //
  // Align buffer on section boundary
  //
  ImageContext.ImageAddress += ImageContext.SectionAlignment - 1;
  ImageContext.ImageAddress &= ~((EFI_PHYSICAL_ADDRESS)ImageContext.SectionAlignment - 1);

  Status = PeCoffLoaderLoadImage (&ImageContext);
  if (EFI_ERROR (Status)) {
    return Status;
  }

  Status = SecNt32PeCoffRelocateImage (&ImageContext);
  if (EFI_ERROR (Status)) {
    return Status;
  }

  //
  // BugBug: Flush Instruction Cache Here when CPU Lib is ready
  //

  *ImageAddress = ImageContext.ImageAddress;
  *ImageSize    = ImageContext.ImageSize;
  *EntryPoint   = ImageContext.EntryPoint;

  return EFI_SUCCESS;
}

EFI_STATUS
EFIAPI
SecWinNtFdAddress (
  IN     UINTN                 Index,
  IN OUT EFI_PHYSICAL_ADDRESS  *FdBase,
  IN OUT UINT64                *FdSize
  )
/*++

Routine Description:
  Return the FD Size and base address. Since the FD is loaded from a
  file into Windows memory only the SEC will know it's address.

Arguments:
  Index  - Which FD, starts at zero.
  FdSize - Size of the FD in bytes
  FdBase - Start address of the FD. Assume it points to an FV Header

Returns:
  EFI_SUCCESS     - Return the Base address and size of the FV
  EFI_UNSUPPORTED - Index does not map to an FD in the system

--*/
{
  if (Index >= gFdInfoCount) {
    return EFI_UNSUPPORTED;
  }

  *FdBase = gFdInfo[Index].Address;
  *FdSize = gFdInfo[Index].Size;

  if (*FdBase == 0 && *FdSize == 0) {
    return EFI_UNSUPPORTED;
  }

  return EFI_SUCCESS;
}

EFI_STATUS
EFIAPI
SecImageRead (
  IN     VOID    *FileHandle,
  IN     UINTN   FileOffset,
  IN OUT UINTN   *ReadSize,
  OUT    VOID    *Buffer
  )
/*++

Routine Description:
  Support routine for the PE/COFF Loader that reads a buffer from a PE/COFF file

Arguments:
  FileHandle - The handle to the PE/COFF file
  FileOffset - The offset, in bytes, into the file to read
  ReadSize   - The number of bytes to read from the file starting at FileOffset
  Buffer     - A pointer to the buffer to read the data into.

Returns:
  EFI_SUCCESS - ReadSize bytes of data were read into Buffer from the PE/COFF file starting at FileOffset

--*/
{
  CHAR8 *Destination8;
  CHAR8 *Source8;
  UINTN Length;

  Destination8  = Buffer;
  Source8       = (CHAR8 *) ((UINTN) FileHandle + FileOffset);
  Length        = *ReadSize;
  while (Length--) {
    *(Destination8++) = *(Source8++);
  }

  return EFI_SUCCESS;
}

CHAR16 *
AsciiToUnicode (
  IN  CHAR8   *Ascii,
  IN  UINTN   *StrLen OPTIONAL
  )
/*++

Routine Description:
  Convert the passed in Ascii string to Unicode.
  Optionally return the length of the strings.

Arguments:
  Ascii   - Ascii string to convert
  StrLen  - Length of string

Returns:
  Pointer to malloc'ed Unicode version of Ascii

--*/
{
  UINTN   Index;
  CHAR16  *Unicode;

  //
  // Allocate a buffer for unicode string
  //
  for (Index = 0; Ascii[Index] != '\0'; Index++)
    ;
  Unicode = malloc ((Index + 1) * sizeof (CHAR16));
  if (Unicode == NULL) {
    return NULL;
  }

  for (Index = 0; Ascii[Index] != '\0'; Index++) {
    Unicode[Index] = (CHAR16) Ascii[Index];
  }

  Unicode[Index] = '\0';

  if (StrLen != NULL) {
    *StrLen = Index;
  }

  return Unicode;
}

UINTN
CountSeparatorsInString (
  IN  CONST CHAR16   *String,
  IN  CHAR16         Separator
  )
/*++

Routine Description:
  Count the number of separators in String

Arguments:
  String    - String to process
  Separator - Item to count

Returns:
  Number of Separator in String

--*/
{
  UINTN Count;

  for (Count = 0; *String != '\0'; String++) {
    if (*String == Separator) {
      Count++;
    }
  }

  return Count;
}

EFI_STATUS
SecNt32PeCoffRelocateImage (
  IN OUT PE_COFF_LOADER_IMAGE_CONTEXT         *ImageContext
  )
{
  EFI_STATUS        Status;
  VOID              *DllEntryPoint;
  CHAR16            *DllFileName;
  HMODULE           Library;
  UINTN             Index;

  Status = PeCoffLoaderRelocateImage (ImageContext);
  if (EFI_ERROR (Status)) {
    //
    // We could not relocated the image in memory properly
    //
    return Status;
  }

  //
  // If we load our own PE COFF images the Windows debugger can not source
  //  level debug our code. If a valid PDB pointer exists usw it to load
  //  the *.dll file as a library using Windows* APIs. This allows
  //  source level debug. The image is still loaded and relocated
  //  in the Framework memory space like on a real system (by the code above),
  //  but the entry point points into the DLL loaded by the code bellow.
  //

  DllEntryPoint = NULL;

  //
  // Load the DLL if it's not an EBC image.
  //
  if ((ImageContext->PdbPointer != NULL) &&
      (ImageContext->Machine != EFI_IMAGE_MACHINE_EBC)) {
    //
    // Convert filename from ASCII to Unicode
    //
    DllFileName = AsciiToUnicode (ImageContext->PdbPointer, &Index);

    //
    // Check that we have a valid filename
    //
    if (Index < 5 || DllFileName[Index - 4] != '.') {
      free (DllFileName);

      //
      // Never return an error if PeCoffLoaderRelocateImage() succeeded.
      // The image will run, but we just can't source level debug. If we
      // return an error the image will not run.
      //
      return EFI_SUCCESS;
    }
    //
    // Replace .PDB with .DLL on the filename
    //
    DllFileName[Index - 3]  = 'D';
    DllFileName[Index - 2]  = 'L';
    DllFileName[Index - 1]  = 'L';

    //
    // Load the .DLL file into the user process's address space for source
    // level debug
    //
    Library = LoadLibraryEx (DllFileName, NULL, DONT_RESOLVE_DLL_REFERENCES);
    if (Library != NULL) {
      //
      // InitializeDriver is the entry point we put in all our EFI DLL's. The
      // DONT_RESOLVE_DLL_REFERENCES argument to LoadLIbraryEx() suppresses the
      // normal DLL entry point of DllMain, and prevents other modules that are
      // referenced in side the DllFileName from being loaded. There is no error
      // checking as the we can point to the PE32 image loaded by Tiano. This
      // step is only needed for source level debugging
      //
      DllEntryPoint = (VOID *) (UINTN) GetProcAddress (Library, "InitializeDriver");

    }

    if ((Library != NULL) && (DllEntryPoint != NULL)) {
      ImageContext->EntryPoint  = (EFI_PHYSICAL_ADDRESS) (UINTN) DllEntryPoint;
      SecPrint ("LoadLibraryEx (%S,\n               NULL, DONT_RESOLVE_DLL_REFERENCES)\n", DllFileName);
    } else {
      SecPrint ("WARNING: No source level debug %S. \n", DllFileName);
    }

    free (DllFileName);
  }

  //
  // Never return an error if PeCoffLoaderRelocateImage() succeeded.
  // The image will run, but we just can't source level debug. If we
  // return an error the image will not run.
  //
  return EFI_SUCCESS;
}

VOID
_ModuleEntryPoint (
  VOID
  )
{
}

EFI_STATUS
EFIAPI
SecTemporaryRamSupport (
  IN CONST EFI_PEI_SERVICES   **PeiServices,
  IN EFI_PHYSICAL_ADDRESS     TemporaryMemoryBase,
  IN EFI_PHYSICAL_ADDRESS     PermanentMemoryBase,
  IN UINTN                    CopySize
  )
{
  //
  // Migrate the whole temporary memory to permanent memory.
  //
  CopyMem (
    (VOID*)(UINTN)PermanentMemoryBase,
    (VOID*)(UINTN)TemporaryMemoryBase,
    CopySize
    );

  //
  // SecSwitchStack function must be invoked after the memory migration
  // immediately, also we need fixup the stack change caused by new call into
  // permanent memory.
  //
  SecSwitchStack (
    (UINT32) TemporaryMemoryBase,
    (UINT32) PermanentMemoryBase
    );

  //
  // We need *not* fix the return address because currently,
  // The PeiCore is executed in flash.
  //

  //
  // Simulate to invalid temporary memory, terminate temporary memory
  //
  //ZeroMem ((VOID*)(UINTN)TemporaryMemoryBase, CopySize);

  return EFI_SUCCESS;
}

{'repo_name': 'google/google-ctf', 'stars': '1602', 'repo_language': 'Go', 'file_name': '0Harmony.xml', 'mime_type': 'text/xml', 'hash': -1840563248808600816, 'source_dataset': 'data'}


/*
 * Copyright (C) 2006 Joe Walnes.
 * Copyright (C) 2007, 2008, 2014, 2015, 2020 XStream Committers.
 * All rights reserved.
 *
 * The software in this package is published under the terms of the BSD
 * style license a copy of which has been included with this distribution in
 * the LICENSE.txt file.
 *
 * Created on 06. July 2006 by Guilherme Silveira
 */
package com.thoughtworks.xstream.persistence;

import java.util.AbstractList;

/**
 * A persistent list implementation backed on a XmlMap.
 *
 * @author Guilherme Silveira
 */
public class XmlArrayList<V> extends AbstractList<V> {

    private final XmlMap<Integer, V> map;

    public XmlArrayList(final PersistenceStrategy<Integer, V> persistenceStrategy) {
        this.map = new XmlMap<>(persistenceStrategy);
    }

    @Override
    public int size() {
        return map.size();
    }

    @Override
    public V set(final int index, final V element) {
        rangeCheck(index);
        final V value = get(index);
        map.put(Integer.valueOf(index), element);
        return value;
    }

    @Override
    public void add(final int index, final V element) {
        final int size = size();
        if (index >= size + 1 || index < 0) {
            throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
        }
        final int to = index != size ? index - 1 : index;
        for (int i = size; i > to; i--) {
            map.put(Integer.valueOf(i + 1), map.get(Integer.valueOf(i)));
        }
        map.put(Integer.valueOf(index), element);
    }

    private void rangeCheck(final int index) {
        final int size = size();
        if (index >= size || index < 0) {
            throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
        }
    }

    @Override
    public V get(final int index) {
        rangeCheck(index);
        return map.get(Integer.valueOf(index));
    }

    @Override
    public V remove(final int index) {
        final int size = size();
        rangeCheck(index);
        final V value = map.get(Integer.valueOf(index));
        for (int i = index; i < size - 1; i++) {
            map.put(Integer.valueOf(i), map.get(Integer.valueOf(i + 1)));
        }
        map.remove(Integer.valueOf(size - 1));
        return value;
    }

}

{'repo_name': 'x-stream/xstream', 'stars': '514', 'repo_language': 'Java', 'file_name': 'AnnotatedTypeProcessor.java', 'mime_type': 'text/x-java', 'hash': 6447771622926686872, 'source_dataset': 'data'}


#!/usr/bin/env python
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
# License: GPLv3 Copyright: 2008, Kovid Goyal <kovid at kovidgoyal.net>

import os
import re
from functools import partial

from sphinx.util.console import bold
from sphinx.util.logging import getLogger

from calibre.linux import cli_index_strings, entry_points
from epub import EPUBHelpBuilder
from latex import LaTeXHelpBuilder

def substitute(app, doctree):
    pass

def info(*a):
    getLogger(__name__).info(*a)

include_pat = re.compile(r'^.. include:: (\S+.rst)', re.M)

def source_read_handler(app, docname, source):
    src = source[0]
    if app.builder.name != 'gettext' and app.config.language != 'en':
        src = re.sub(r'(\s+generated/)en/', r'\1' + app.config.language + '/', src)
    # Sphinx does not call source_read_handle for the .. include directive
    for m in reversed(tuple(include_pat.finditer(src))):
        included_doc_name = m.group(1).lstrip('/')
        ss = [open(included_doc_name, 'rb').read().decode('utf-8')]
        source_read_handler(app, included_doc_name.partition('.')[0], ss)
        src = src[:m.start()] + ss[0] + src[m.end():]
    source[0] = src

CLI_INDEX='''
.. _cli:

%s
=========================================================

.. image:: ../../images/cli.png

.. note::
    %s

%s
--------------------------------------

.. toctree::
    :maxdepth: 1

{documented}

%s
----------------------------------------

{undocumented}

%s
'''

CLI_PREAMBLE='''\
.. _{cmdref}:

.. raw:: html

    <style>code {{font-size: 1em; background-color: transparent; font-family: sans-serif }}</style>

``{cmd}``
===================================================================

.. code-block:: none

    {cmdline}

{usage}
'''

def titlecase(app, x):
    if x and app.config.language == 'en':
        from calibre.utils.titlecase import titlecase as tc
        x = tc(x)
    return x

def generate_calibredb_help(preamble, app):
    from calibre.db.cli.main import COMMANDS, option_parser_for, get_parser
    preamble = preamble[:preamble.find('\n\n\n', preamble.find('code-block'))]
    preamble += '\n\n'
    preamble += _('''\
:command:`calibredb` is the command line interface to the calibre database. It has
several sub-commands, documented below.

:command:`calibredb` can be used to manipulate either a calibre database
specified by path or a calibre :guilabel:`Content server` running either on
the local machine or over the internet. You can start a calibre
:guilabel:`Content server` using either the :command:`calibre-server`
program or in the main calibre program click :guilabel:`Connect/share ->
Start Content server`. Since :command:`calibredb` can make changes to your
calibre libraries, you must setup authentication on the server first. There
are two ways to do that:

    * If you plan to connect only to a server running on the same computer,
      you can simply use the ``--enable-local-write`` option of the
      content server, to allow any program, including calibredb, running on
      the local computer to make changes to your calibre data. When running
      the server from the main calibre program, this option is in
      :guilabel:`Preferences->Sharing over the net->Advanced`.

    * If you want to enable access over the internet, then you should setup
      user accounts on the server and use the :option:`--username` and :option:`--password`
      options to :command:`calibredb` to give it access. You can setup
      user authentication for :command:`calibre-server` by using the ``--enable-auth``
      option and using ``--manage-users`` to create the user accounts.
      If you are running the server from the main calibre program, use
      :guilabel:`Preferences->Sharing over the net->Require username/password`.

To connect to a running Content server, pass the URL of the server to the
:option:`--with-library` option, see the documentation of that option for
details and examples.
    ''')

    global_parser = get_parser('')
    groups = []
    for grp in global_parser.option_groups:
        groups.append((titlecase(app, grp.title), grp.description, grp.option_list))

    global_options = '\n'.join(render_options('calibredb', groups, False, False))

    lines = []
    for cmd in COMMANDS:
        parser = option_parser_for(cmd)()
        lines += ['.. _calibredb-%s-%s:' % (app.config.language, cmd), '']
        lines += [cmd, '~'*20, '']
        usage = parser.usage.strip()
        usage = [i for i in usage.replace('%prog', 'calibredb').splitlines()]
        cmdline = '    '+usage[0]
        usage = usage[1:]
        usage = [re.sub(r'(%s)([^a-zA-Z0-9])'%cmd, r':command:`\1`\2', i) for i in usage]
        lines += ['.. code-block:: none', '', cmdline, '']
        lines += usage
        groups = [(None, None, parser.option_list)]
        lines += ['']
        lines += render_options('calibredb '+cmd, groups, False)
        lines += ['']
        for group in parser.option_groups:
            if not getattr(group, 'is_global_options', False):
                lines.extend(render_options(
                    'calibredb_' + cmd, [[titlecase(app, group.title), group.description, group.option_list]], False, False, header_level='^'))
        lines += ['']

    raw = preamble + '\n\n'+'.. contents::\n  :local:'+ '\n\n' + global_options+'\n\n'+'\n'.join(lines)
    update_cli_doc('calibredb', raw, app)

def generate_ebook_convert_help(preamble, app):
    from calibre.ebooks.conversion.cli import create_option_parser, manual_index_strings
    from calibre.customize.ui import input_format_plugins, output_format_plugins
    from calibre.utils.logging import default_log
    preamble = re.sub(r'http.*\.html', ':ref:`conversion`', preamble)

    raw = preamble + '\n\n' + manual_index_strings() % 'ebook-convert myfile.input_format myfile.output_format -h'
    parser, plumber = create_option_parser(['ebook-convert',
        'dummyi.mobi', 'dummyo.epub', '-h'], default_log)
    groups = [(None, None, parser.option_list)]
    for grp in parser.option_groups:
        if grp.title not in {'INPUT OPTIONS', 'OUTPUT OPTIONS'}:
            groups.append((titlecase(app, grp.title), grp.description, grp.option_list))
    options = '\n'.join(render_options('ebook-convert', groups, False))

    raw += '\n\n.. contents::\n  :local:'

    raw += '\n\n' + options
    for pl in sorted(input_format_plugins(), key=lambda x: x.name):
        parser, plumber = create_option_parser(['ebook-convert',
            'dummyi.'+sorted(pl.file_types)[0], 'dummyo.epub', '-h'], default_log)
        groups = [(pl.name+ ' Options', '', g.option_list) for g in
                parser.option_groups if g.title == "INPUT OPTIONS"]
        prog = 'ebook-convert-'+(pl.name.lower().replace(' ', '-'))
        raw += '\n\n' + '\n'.join(render_options(prog, groups, False, True))
    for pl in sorted(output_format_plugins(), key=lambda x: x.name):
        parser, plumber = create_option_parser(['ebook-convert', 'd.epub',
            'dummyi.'+pl.file_type, '-h'], default_log)
        groups = [(pl.name+ ' Options', '', g.option_list) for g in
                parser.option_groups if g.title == "OUTPUT OPTIONS"]
        prog = 'ebook-convert-'+(pl.name.lower().replace(' ', '-'))
        raw += '\n\n' + '\n'.join(render_options(prog, groups, False, True))

    update_cli_doc('ebook-convert', raw, app)

def update_cli_doc(name, raw, app):
    if isinstance(raw, bytes):
        raw = raw.decode('utf-8')
    path = 'generated/%s/%s.rst' % (app.config.language, name)
    old_raw = open(path, encoding='utf-8').read() if os.path.exists(path) else ''
    if not os.path.exists(path) or old_raw != raw:
        import difflib
        print(path, 'has changed')
        if old_raw:
            lines = difflib.unified_diff(old_raw.splitlines(), raw.splitlines(),
                    path, path)
            for line in lines:
                print(line)
        info('creating '+os.path.splitext(os.path.basename(path))[0])
        p = os.path.dirname(path)
        if p and not os.path.exists(p):
            os.makedirs(p)
        open(path, 'wb').write(raw.encode('utf-8'))

def render_options(cmd, groups, options_header=True, add_program=True, header_level='~'):
    lines = ['']
    if options_header:
        lines = [_('[options]'), '-'*40, '']
    if add_program:
        lines += ['.. program:: '+cmd, '']
    for title, desc, options in groups:
        if title:
            lines.extend([title, header_level * (len(title) + 4)])
            lines.append('')
        if desc:
            lines.extend([desc, ''])
        for opt in sorted(options, key=lambda x: x.get_opt_string()):
            help = opt.help or ''
            help = help.replace('\n', ' ').replace('*', '\\*').replace('%default', str(opt.default))
            help = help.replace('"', r'\ ``"``\ ')
            help = help.replace("'", r"\ ``'``\ ")
            help = mark_options(help)
            opt_strings = (x.strip() for x in tuple(opt._long_opts or ()) + tuple(opt._short_opts or ()))
            opt = '.. option:: ' + ', '.join(opt_strings)
            lines.extend([opt, '', '    '+help, ''])
    return lines

def mark_options(raw):
    raw = re.sub(r'(\s+)--(\s+)', u'\\1``--``\\2', raw)

    def sub(m):
        opt = m.group()
        a, b = opt.partition('=')[::2]
        if a in ('--option1', '--option2'):
            return '``' + m.group() + '``'
        a = ':option:`' + a + '`'
        b = (' = ``' + b + '``') if b else ''
        return a + b
    raw = re.sub(r'(--[|()a-zA-Z0-9_=,-]+)', sub, raw)
    return raw

def get_cli_docs():
    documented_cmds = []
    undocumented_cmds = []
    for script in entry_points['console_scripts'] + entry_points['gui_scripts']:
        module = script[script.index('=')+1:script.index(':')].strip()
        cmd = script[:script.index('=')].strip()
        if cmd in ('calibre-complete', 'calibre-parallel'):
            continue
        module = __import__(module, fromlist=[module.split('.')[-1]])
        if hasattr(module, 'option_parser'):
            try:
                documented_cmds.append((cmd, getattr(module, 'option_parser')()))
            except TypeError:
                documented_cmds.append((cmd, getattr(module, 'option_parser')(cmd)))
        else:
            undocumented_cmds.append(cmd)
    return documented_cmds, undocumented_cmds

def cli_docs(app):
    info(bold('creating CLI documentation...'))
    documented_cmds, undocumented_cmds = get_cli_docs()

    documented_cmds.sort(key=lambda x: x[0])
    undocumented_cmds.sort()

    documented = [' '*4 + c[0] for c in documented_cmds]
    undocumented = ['  * ' + c for c in undocumented_cmds]

    raw = (CLI_INDEX % cli_index_strings()[:5]).format(documented='\n'.join(documented),
            undocumented='\n'.join(undocumented))
    if not os.path.exists('cli'):
        os.makedirs('cli')
    update_cli_doc('cli-index', raw, app)

    for cmd, parser in documented_cmds:
        usage = [mark_options(i) for i in parser.usage.replace('%prog', cmd).splitlines()]
        cmdline = usage[0]
        usage = usage[1:]
        usage = [i.replace(cmd, ':command:`%s`'%cmd) for i in usage]
        usage = '\n'.join(usage)
        preamble = CLI_PREAMBLE.format(cmd=cmd, cmdref=cmd + '-' + app.config.language, cmdline=cmdline, usage=usage)
        if cmd == 'ebook-convert':
            generate_ebook_convert_help(preamble, app)
        elif cmd == 'calibredb':
            generate_calibredb_help(preamble, app)
        else:
            groups = [(None, None, parser.option_list)]
            for grp in parser.option_groups:
                groups.append((grp.title, grp.description, grp.option_list))
            raw = preamble
            lines = render_options(cmd, groups)
            raw += '\n'+'\n'.join(lines)
            update_cli_doc(cmd, raw, app)

def generate_docs(app):
    cli_docs(app)
    template_docs(app)

def template_docs(app):
    from template_ref_generate import generate_template_language_help
    raw = generate_template_language_help(app.config.language)
    update_cli_doc('template_ref', raw, app)

def localized_path(app, langcode, pagename):
    href = app.builder.get_target_uri(pagename)
    href = re.sub(r'generated/[a-z]+/', 'generated/%s/' % langcode, href)
    prefix = '/'
    if langcode != 'en':
        prefix += langcode + '/'
    return prefix + href

def add_html_context(app, pagename, templatename, context, *args):
    context['localized_path'] = partial(localized_path, app)
    context['change_language_text'] = cli_index_strings()[5]
    context['search_box_text'] = cli_index_strings()[6]

def guilabel_role(typ, rawtext, text, *args, **kwargs):
    from sphinx.roles import GUILabel
    text = text.replace(u'->', u'\N{THIN SPACE}\N{RIGHTWARDS ARROW}\N{THIN SPACE}')
    return GUILabel()(typ, rawtext, text, *args, **kwargs)

def setup_man_pages(app):
    documented_cmds = get_cli_docs()[0]
    man_pages = []
    for cmd, option_parser in documented_cmds:
        path = 'generated/%s/%s' % (app.config.language, cmd)
        man_pages.append((
            path, cmd, cmd, 'Kovid Goyal', 1
        ))
    app.config['man_pages'] = man_pages

def monkey_patch_docutils():
    # fixes a bug in sphinx https://github.com/sphinx-doc/sphinx/issues/5150
    from docutils import nodes

    orig_method = nodes.document.set_duplicate_name_id

    def set_duplicate_name_id(*a):
        try:
            return orig_method(*a)
        except KeyError:
            pass

    nodes.document.set_duplicate_name_id = set_duplicate_name_id

def setup(app):
    from docutils.parsers.rst import roles
    monkey_patch_docutils()
    setup_man_pages(app)
    app.add_builder(EPUBHelpBuilder)
    app.add_builder(LaTeXHelpBuilder)
    app.connect('source-read', source_read_handler)
    app.connect('doctree-read', substitute)
    app.connect('builder-inited', generate_docs)
    app.connect('html-page-context', add_html_context)
    app.connect('build-finished', finished)
    roles.register_local_role('guilabel', guilabel_role)

def finished(app, exception):
    pass

{'repo_name': 'kovidgoyal/calibre', 'stars': '8012', 'repo_language': 'Python', 'file_name': 'sfin.recipe', 'mime_type': 'text/x-python', 'hash': -692051313224934813, 'source_dataset': 'data'}


<?xml version="1.0" encoding="UTF-8"?><project-modules id="moduleCoreId" project-version="1.5.0">
    <wb-module deploy-name="RSAService">
        <wb-resource deploy-path="/" source-path="/WebContent" tag="defaultRootSource"/>
        <wb-resource deploy-path="/WEB-INF/classes" source-path="/src"/>
        <property name="context-root" value="RSAService"/>
        <property name="java-output-path" value="/RSAService/build/classes"/>
    </wb-module>
</project-modules>

{'repo_name': 'mengxiangyue/MShare_Salon', 'stars': '157', 'repo_language': 'C', 'file_name': 'ReadMe.md', 'mime_type': 'text/plain', 'hash': -6182725160471138962, 'source_dataset': 'data'}


<RelativeLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:id="@+id/offline_grid_item_layout"
	android:layout_width="wrap_content"
	android:layout_height="wrap_content"
	android:layout_margin="2dp"
	android:background="@drawable/background_item_grid"
	android:descendantFocusability="blocksDescendants"
	android:padding="1dp">
	<RelativeLayout
		android:id="@+id/item_file_grid_folder"
		android:layout_width="match_parent"
		android:layout_height="match_parent"
		android:background="@drawable/background_item_grid_new"
		android:visibility="visible">
		<RelativeLayout
			android:id="@+id/file_grid_thumbnail_layout"
			android:layout_width="match_parent"
			android:layout_height="56dp">
			<ImageView
				android:id="@+id/offline_grid_icon"
				android:layout_width="24dp"
				android:layout_height="24dp"
				android:layout_alignParentLeft="true"
				android:layout_centerVertical="true"
				android:layout_marginLeft="8dp"
				android:layout_marginRight="8dp"
				android:background="@null"
				android:scaleType="fitCenter"/>
			<TextView
				android:id="@+id/offline_grid_filename"
				android:layout_width="110dp"
				android:layout_height="wrap_content"
				android:layout_centerVertical="true"
				android:layout_marginRight="8dp"
				android:layout_toRightOf="@+id/offline_grid_icon"
				android:ellipsize="middle"
				android:singleLine="true"
				android:textColor="#DE000000"
				android:textSize="14sp"/>
			<ImageButton
				android:id="@+id/offline_grid_three_dots"
				android:layout_width="wrap_content"
				android:layout_height="wrap_content"
				android:layout_alignParentRight="true"
				android:layout_centerVertical="true"
				android:background="@null"
				android:src="@drawable/ic_dots_vertical_grey"/>
		</RelativeLayout>
	</RelativeLayout>
	<RelativeLayout
		android:id="@+id/item_file_grid_file"
		android:layout_width="match_parent"
		android:layout_height="match_parent"
		android:background="@drawable/background_item_grid_new"
		android:visibility="gone">
		<RelativeLayout
			android:id="@+id/file_grid_thumbnail_layout_for_file"
			android:layout_width="match_parent"
			android:layout_height="172dp">
			<ImageView
				android:id="@+id/file_grid_thumbnail"
				android:layout_width="match_parent"
				android:layout_height="match_parent"
				android:layout_centerInParent="true"
				android:scaleType="fitXY"
				android:paddingTop="1dp"
				android:paddingRight="1dp"
				android:paddingLeft="1dp"/>
			<ImageView
				android:id="@+id/file_grid_selected"
				android:layout_width="23dp"
				android:layout_height="23dp"
				android:layout_alignParentLeft="true"
				android:layout_alignParentTop="true"
				android:layout_marginLeft="7dp"
				android:layout_marginTop="7dp"/>
			<ImageView
				android:id="@+id/file_grid_icon_for_file"
				android:layout_width="88dp"
				android:layout_height="88dp"
				android:layout_centerHorizontal="true"
				android:layout_centerVertical="true"
				android:background="@null"
				android:scaleType="fitCenter"/>
		</RelativeLayout>
		<View
			android:layout_width="match_parent"
			android:layout_height="1dp"
			android:background="@color/divider_upgrade_account"
			android:layout_below="@+id/file_grid_thumbnail_layout_for_file"/>
		<RelativeLayout
			android:id="@+id/offline_grid_bottom_container"
			android:layout_width="match_parent"
			android:layout_height="47dp"
			android:layout_below="@+id/file_grid_thumbnail_layout_for_file">
			<TextView
				android:id="@+id/file_grid_filename_for_file"
				android:layout_width="wrap_content"
				android:layout_height="wrap_content"
				android:layout_alignParentLeft="true"
				android:layout_toLeftOf="@+id/file_grid_three_dots_for_file"
				android:layout_centerVertical="true"
				android:layout_marginLeft="8dp"
				android:ellipsize="middle"
				android:singleLine="true"
				android:textColor="#DE000000"
				android:textSize="14sp"/>
			<ImageButton
				android:id="@+id/file_grid_three_dots_for_file"
				android:layout_width="wrap_content"
				android:layout_height="wrap_content"
				android:layout_alignParentRight="true"
				android:layout_centerVertical="true"
				android:background="@null"
				android:src="@drawable/ic_dots_vertical_grey"/>
		</RelativeLayout>
	</RelativeLayout>
	<!--no use in grid-->
	<FrameLayout
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:visibility="gone">
		<!--<ImageView-->
			<!--android:id="@+id/offline_grid_thumbnail"-->
			<!--android:layout_width="match_parent"-->
			<!--android:layout_height="match_parent"-->
			<!--android:layout_centerHorizontal="true"-->
			<!--android:layout_centerVertical="true"-->
			<!--android:scaleType="fitXY"-->
			<!--android:visibility="gone"/>-->
		<View
			android:id="@+id/offline_grid_separator"
			android:layout_width="match_parent"
			android:layout_height="1dp"
			android:background="@color/new_background_fragment"
			android:visibility="gone"/>
		<TextView
			android:id="@+id/offline_grid_filesize"
			android:layout_width="wrap_content"
			android:layout_height="30dp"
			android:layout_alignParentLeft="true"
			android:layout_marginBottom="7dp"
			android:layout_marginLeft="12dp"
			android:ellipsize="end"
			android:maxLines="1"
			android:textColor="@color/file_list_second_row"
			android:textSize="12sp"
			android:visibility="gone"/>
	</FrameLayout>
</RelativeLayout>

{'repo_name': 'meganz/android', 'stars': '536', 'repo_language': 'Java', 'file_name': 'CameraUploadsService.java', 'mime_type': 'text/x-java', 'hash': 7345928901195253174, 'source_dataset': 'data'}


{'repo_name': 'microsoft/CDM', 'stars': '662', 'repo_language': 'Java', 'file_name': 'InventTransOriginRAssetScrap_RU.1.0.cdm.json', 'mime_type': 'text/plain', 'hash': -5659253805996274741, 'source_dataset': 'data'}


/*
 * SonarAnalyzer for .NET
 * Copyright (C) 2015-2020 SonarSource SA
 * mailto: contact AT sonarsource DOT com
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using SonarAnalyzer.Common;
using SonarAnalyzer.Helpers;

namespace SonarAnalyzer.Rules.CSharp
{
    [DiagnosticAnalyzer(LanguageNames.CSharp)]
    [Rule(DiagnosticId)]
    public sealed class CallerInformationParametersShouldBeLast : SonarDiagnosticAnalyzer
    {
        internal const string DiagnosticId = "S3343";
        private const string MessageFormat = "Move '{0}' to the end of the parameter list.";

        private static readonly DiagnosticDescriptor rule =
            DiagnosticDescriptorBuilder.GetDescriptor(DiagnosticId, MessageFormat, RspecStrings.ResourceManager);

        public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(rule);

        protected override void Initialize(SonarAnalysisContext context)
        {
            context.RegisterSyntaxNodeActionInNonGenerated(
                ReportOnViolation,
                SyntaxKind.MethodDeclaration,
                SyntaxKind.ConstructorDeclaration);
        }

        private static void ReportOnViolation(SyntaxNodeAnalysisContext context)
        {
            var methodDeclaration = (BaseMethodDeclarationSyntax)context.Node;
            if (methodDeclaration.ParameterList == null)
            {
                return;
            }

            var methodSymbol = context.SemanticModel.GetDeclaredSymbol(methodDeclaration);
            if (methodSymbol == null ||
                methodSymbol.IsOverride ||
                methodSymbol.GetInterfaceMember() != null)
            {
                return;
            }

            ParameterSyntax noCallerInfoParameter = null;
            foreach (var parameter in methodDeclaration.ParameterList.Parameters.Reverse())
            {
                if (parameter.AttributeLists.GetAttributes(KnownType.CallerInfoAttributes, context.SemanticModel).Any())
                {
                    if (noCallerInfoParameter != null &&
                        HasIdentifier(parameter))
                    {
                        context.ReportDiagnosticWhenActive(Diagnostic.Create(rule, parameter.GetLocation(),
                            parameter.Identifier.Text));
                    }
                }
                else
                {
                    noCallerInfoParameter = parameter;
                }
            }
        }

        private static bool HasIdentifier(ParameterSyntax parameter) =>
            !string.IsNullOrEmpty(parameter.Identifier.Text);
    }
}

{'repo_name': 'SonarSource/sonar-dotnet', 'stars': '411', 'repo_language': 'C#', 'file_name': 'Akka.TestKit.Xunit.csproj', 'mime_type': 'text/xml', 'hash': 6104292178738226748, 'source_dataset': 'data'}


---
description: How to compute vibrational free energy, entropy, specific heat, thermal expansion, as well as atomic temperature factors
authors: XG
---
<!--- This is the source file for this topics. Can be edited. -->

This page gives hints on how to compute vibrational free energy, entropy, specific heat, thermal expansion, as
well as atomic temperature factors with the ABINIT package.

## Introduction

When the phonon band structure and corresponding eigenvectors are known over
the whole Brillouin Zone, thanks fo Fourier interpolation (see
[[topic:PhononBands]]), integrals can be performed, allowing to obtain a
wealth of properties, like free energy, entropy, specific heat, as well as
atomic temperature factors. For applications of this technique, see
[[cite:Lee1995]].

Moreover, knowing such information for different volumes allows one to compute
the thermal expansion, see [[anaddb:gruns_ddbs]].

The input variables needed to perform the interpolation over the Brillouin
Zone are described in [[topic:PhononBands]] and are not listed again in the
present topic.

## Related Input Variables

{{ related_variables }}

## Selected Input Files

{{ selected_input_files }}

## Tutorials

* [[tutorial:rf2|The tutorial Response-Function 2 (RF2)]] presents the analysis of the DDBs that have been introduced in the preceeding tutorial RF1. The computation of the interatomic forces and the computation of thermodynamical properties is an outcome of this tutorial.

{'repo_name': 'abinit/abinit', 'stars': '110', 'repo_language': 'Fortran', 'file_name': 'INSTALL.in', 'mime_type': 'text/plain', 'hash': -9079235108967009726, 'source_dataset': 'data'}


/*
 * Pipeline API
 *
 * Pipeline v0.3.0 swagger
 *
 * API version: master
 * Contact: info@banzaicloud.com
 */

// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT.

package pipeline

type PodItem struct {
	Name string `json:"name,omitempty"`
	Namespace string `json:"namespace,omitempty"`
	CreatedAt string `json:"createdAt,omitempty"`
	Labels PodItemLabels `json:"labels,omitempty"`
	RestartPolicy string `json:"restartPolicy,omitempty"`
	Conditions []PodCondition `json:"conditions,omitempty"`
	ResourceSummary ResourceSummary `json:"resourceSummary,omitempty"`
}

{'repo_name': 'banzaicloud/pke', 'stars': '168', 'repo_language': 'Go', 'file_name': 'machine-image.go', 'mime_type': 'text/plain', 'hash': -2801646107012767609, 'source_dataset': 'data'}


package hns

import "fmt"

//go:generate go run ../../mksyscall_windows.go -output zsyscall_windows.go hns.go

//sys _hnsCall(method string, path string, object string, response **uint16) (hr error) = vmcompute.HNSCall?

type EndpointNotFoundError struct {
	EndpointName string
}

func (e EndpointNotFoundError) Error() string {
	return fmt.Sprintf("Endpoint %s not found", e.EndpointName)
}

type NetworkNotFoundError struct {
	NetworkName string
}

func (e NetworkNotFoundError) Error() string {
	return fmt.Sprintf("Network %s not found", e.NetworkName)
}

{'repo_name': 'rancher/rio', 'stars': '2018', 'repo_language': 'Go', 'file_name': 'riofile-export.yaml', 'mime_type': 'text/plain', 'hash': -4057166753469379807, 'source_dataset': 'data'}


// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/scheduler/renderer/throttling_helper.h"

#include <stddef.h>

#include <memory>

#include "base/callback.h"
#include "base/macros.h"
#include "base/memory/ptr_util.h"
#include "base/test/simple_test_tick_clock.h"
#include "cc/test/ordered_simple_task_runner.h"
#include "components/scheduler/base/test_time_source.h"
#include "components/scheduler/child/scheduler_tqm_delegate_for_test.h"
#include "components/scheduler/renderer/renderer_scheduler_impl.h"
#include "components/scheduler/renderer/web_frame_scheduler_impl.h"
#include "components/scheduler/renderer/web_view_scheduler_impl.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

using testing::ElementsAre;

namespace scheduler {

namespace {
void CountingTask(size_t* count, scoped_refptr<TaskQueue> timer_queue) {
  if (++(*count) < 10) {
    timer_queue->PostTask(FROM_HERE,
                          base::Bind(&CountingTask, count, timer_queue));
  }
}
}

class ThrottlingHelperTest : public testing::Test {
 public:
  ThrottlingHelperTest() {}
  ~ThrottlingHelperTest() override {}

  void SetUp() override {
    clock_.reset(new base::SimpleTestTickClock());
    clock_->Advance(base::TimeDelta::FromMicroseconds(5000));
    mock_task_runner_ =
        make_scoped_refptr(new cc::OrderedSimpleTaskRunner(clock_.get(), true));
    delegate_ = SchedulerTqmDelegateForTest::Create(
        mock_task_runner_, base::WrapUnique(new TestTimeSource(clock_.get())));
    scheduler_.reset(new RendererSchedulerImpl(delegate_));
    throttling_helper_ = scheduler_->throttling_helper();
    timer_queue_ = scheduler_->NewTimerTaskRunner("test_queue");
  }

  void TearDown() override {
    scheduler_->Shutdown();
    scheduler_.reset();
  }

  void ExpectThrottled(scoped_refptr<TaskQueue> timer_queue) {
    size_t count = 0;
    timer_queue->PostTask(FROM_HERE,
                          base::Bind(&CountingTask, &count, timer_queue));

    mock_task_runner_->RunForPeriod(base::TimeDelta::FromSeconds(1));
    EXPECT_LT(count, 10u);
    mock_task_runner_->RunUntilIdle();
  }

  void ExpectUnthrottled(scoped_refptr<TaskQueue> timer_queue) {
    size_t count = 0;
    timer_queue->PostTask(FROM_HERE,
                          base::Bind(&CountingTask, &count, timer_queue));

    mock_task_runner_->RunForPeriod(base::TimeDelta::FromSeconds(1));
    EXPECT_EQ(count, 10u);
    mock_task_runner_->RunUntilIdle();
  }

 protected:
  std::unique_ptr<base::SimpleTestTickClock> clock_;
  scoped_refptr<cc::OrderedSimpleTaskRunner> mock_task_runner_;
  scoped_refptr<SchedulerTqmDelegate> delegate_;
  std::unique_ptr<RendererSchedulerImpl> scheduler_;
  scoped_refptr<TaskQueue> timer_queue_;
  ThrottlingHelper* throttling_helper_;  // NOT OWNED

  DISALLOW_COPY_AND_ASSIGN(ThrottlingHelperTest);
};

TEST_F(ThrottlingHelperTest, ThrottledRunTime) {
  EXPECT_EQ(base::TimeTicks() + base::TimeDelta::FromSecondsD(1.0),
            ThrottlingHelper::ThrottledRunTime(
                base::TimeTicks() + base::TimeDelta::FromSecondsD(0.0)));

  EXPECT_EQ(base::TimeTicks() + base::TimeDelta::FromSecondsD(1.0),
            ThrottlingHelper::ThrottledRunTime(
                base::TimeTicks() + base::TimeDelta::FromSecondsD(0.1)));

  EXPECT_EQ(base::TimeTicks() + base::TimeDelta::FromSecondsD(1.0),
            ThrottlingHelper::ThrottledRunTime(
                base::TimeTicks() + base::TimeDelta::FromSecondsD(0.2)));

  EXPECT_EQ(base::TimeTicks() + base::TimeDelta::FromSecondsD(1.0),
            ThrottlingHelper::ThrottledRunTime(
                base::TimeTicks() + base::TimeDelta::FromSecondsD(0.5)));

  EXPECT_EQ(base::TimeTicks() + base::TimeDelta::FromSecondsD(1.0),
            ThrottlingHelper::ThrottledRunTime(
                base::TimeTicks() + base::TimeDelta::FromSecondsD(0.8)));

  EXPECT_EQ(base::TimeTicks() + base::TimeDelta::FromSecondsD(1.0),
            ThrottlingHelper::ThrottledRunTime(
                base::TimeTicks() + base::TimeDelta::FromSecondsD(0.9)));

  EXPECT_EQ(base::TimeTicks() + base::TimeDelta::FromSecondsD(2.0),
            ThrottlingHelper::ThrottledRunTime(
                base::TimeTicks() + base::TimeDelta::FromSecondsD(1.0)));

  EXPECT_EQ(base::TimeTicks() + base::TimeDelta::FromSecondsD(2.0),
            ThrottlingHelper::ThrottledRunTime(
                base::TimeTicks() + base::TimeDelta::FromSecondsD(1.1)));

  EXPECT_EQ(base::TimeTicks() + base::TimeDelta::FromSecondsD(9.0),
            ThrottlingHelper::ThrottledRunTime(
                base::TimeTicks() + base::TimeDelta::FromSecondsD(8.0)));

  EXPECT_EQ(base::TimeTicks() + base::TimeDelta::FromSecondsD(9.0),
            ThrottlingHelper::ThrottledRunTime(
                base::TimeTicks() + base::TimeDelta::FromSecondsD(8.1)));
}

namespace {
void TestTask(std::vector<base::TimeTicks>* run_times,
              base::SimpleTestTickClock* clock) {
  run_times->push_back(clock->NowTicks());
}
}  // namespace

TEST_F(ThrottlingHelperTest, TimerAlignment) {
  std::vector<base::TimeTicks> run_times;
  timer_queue_->PostDelayedTask(FROM_HERE,
                                base::Bind(&TestTask, &run_times, clock_.get()),
                                base::TimeDelta::FromMilliseconds(200.0));

  timer_queue_->PostDelayedTask(FROM_HERE,
                                base::Bind(&TestTask, &run_times, clock_.get()),
                                base::TimeDelta::FromMilliseconds(800.0));

  timer_queue_->PostDelayedTask(FROM_HERE,
                                base::Bind(&TestTask, &run_times, clock_.get()),
                                base::TimeDelta::FromMilliseconds(1200.0));

  timer_queue_->PostDelayedTask(FROM_HERE,
                                base::Bind(&TestTask, &run_times, clock_.get()),
                                base::TimeDelta::FromMilliseconds(8300.0));

  throttling_helper_->IncreaseThrottleRefCount(timer_queue_.get());

  mock_task_runner_->RunUntilIdle();

  // Times are aligned to a multipple of 1000 milliseconds.
  EXPECT_THAT(
      run_times,
      ElementsAre(
          base::TimeTicks() + base::TimeDelta::FromMilliseconds(1000.0),
          base::TimeTicks() + base::TimeDelta::FromMilliseconds(1000.0),
          base::TimeTicks() + base::TimeDelta::FromMilliseconds(2000.0),
          base::TimeTicks() + base::TimeDelta::FromMilliseconds(9000.0)));
}

TEST_F(ThrottlingHelperTest, TimerAlignment_Unthrottled) {
  std::vector<base::TimeTicks> run_times;
  base::TimeTicks start_time = clock_->NowTicks();
  timer_queue_->PostDelayedTask(FROM_HERE,
                                base::Bind(&TestTask, &run_times, clock_.get()),
                                base::TimeDelta::FromMilliseconds(200.0));

  timer_queue_->PostDelayedTask(FROM_HERE,
                                base::Bind(&TestTask, &run_times, clock_.get()),
                                base::TimeDelta::FromMilliseconds(800.0));

  timer_queue_->PostDelayedTask(FROM_HERE,
                                base::Bind(&TestTask, &run_times, clock_.get()),
                                base::TimeDelta::FromMilliseconds(1200.0));

  timer_queue_->PostDelayedTask(FROM_HERE,
                                base::Bind(&TestTask, &run_times, clock_.get()),
                                base::TimeDelta::FromMilliseconds(8300.0));

  throttling_helper_->IncreaseThrottleRefCount(timer_queue_.get());
  throttling_helper_->DecreaseThrottleRefCount(timer_queue_.get());

  mock_task_runner_->RunUntilIdle();

  // Times are not aligned.
  EXPECT_THAT(
      run_times,
      ElementsAre(start_time + base::TimeDelta::FromMilliseconds(200.0),
                  start_time + base::TimeDelta::FromMilliseconds(800.0),
                  start_time + base::TimeDelta::FromMilliseconds(1200.0),
                  start_time + base::TimeDelta::FromMilliseconds(8300.0)));
}

TEST_F(ThrottlingHelperTest, Refcount) {
  ExpectUnthrottled(timer_queue_.get());

  throttling_helper_->IncreaseThrottleRefCount(timer_queue_.get());
  ExpectThrottled(timer_queue_);

  throttling_helper_->IncreaseThrottleRefCount(timer_queue_.get());
  ExpectThrottled(timer_queue_);

  throttling_helper_->DecreaseThrottleRefCount(timer_queue_.get());
  ExpectThrottled(timer_queue_);

  throttling_helper_->DecreaseThrottleRefCount(timer_queue_.get());
  ExpectUnthrottled(timer_queue_);

  // Should be a NOP.
  throttling_helper_->DecreaseThrottleRefCount(timer_queue_.get());
  ExpectUnthrottled(timer_queue_);

  throttling_helper_->IncreaseThrottleRefCount(timer_queue_.get());
  ExpectThrottled(timer_queue_);
}

TEST_F(ThrottlingHelperTest,
       ThrotlingAnEmptyQueueDoesNotPostPumpThrottledTasksLocked) {
  throttling_helper_->IncreaseThrottleRefCount(timer_queue_.get());

  EXPECT_TRUE(throttling_helper_->task_runner()->IsEmpty());
}

TEST_F(ThrottlingHelperTest, WakeUpForNonDelayedTask) {
  std::vector<base::TimeTicks> run_times;

  // Nothing is posted on timer_queue_ so PumpThrottledTasks will not tick.
  throttling_helper_->IncreaseThrottleRefCount(timer_queue_.get());

  // Posting a task should trigger the pump.
  timer_queue_->PostTask(FROM_HERE,
                         base::Bind(&TestTask, &run_times, clock_.get()));

  mock_task_runner_->RunUntilIdle();
  EXPECT_THAT(run_times,
              ElementsAre(base::TimeTicks() +
                          base::TimeDelta::FromMilliseconds(1000.0)));
}

TEST_F(ThrottlingHelperTest, WakeUpForDelayedTask) {
  std::vector<base::TimeTicks> run_times;

  // Nothing is posted on timer_queue_ so PumpThrottledTasks will not tick.
  throttling_helper_->IncreaseThrottleRefCount(timer_queue_.get());

  // Posting a task should trigger the pump.
  timer_queue_->PostDelayedTask(FROM_HERE,
                                base::Bind(&TestTask, &run_times, clock_.get()),
                                base::TimeDelta::FromMilliseconds(1200.0));

  mock_task_runner_->RunUntilIdle();
  EXPECT_THAT(run_times,
              ElementsAre(base::TimeTicks() +
                          base::TimeDelta::FromMilliseconds(2000.0)));
}

namespace {
bool MessageLoopTaskCounter(size_t* count) {
  *count = *count + 1;
  return true;
}

void NopTask() {}

}  // namespace

TEST_F(ThrottlingHelperTest,
       SingleThrottledTaskPumpedAndRunWithNoExtraneousMessageLoopTasks) {
  throttling_helper_->IncreaseThrottleRefCount(timer_queue_.get());

  base::TimeDelta delay(base::TimeDelta::FromMilliseconds(10));
  timer_queue_->PostDelayedTask(FROM_HERE, base::Bind(&NopTask), delay);

  size_t task_count = 0;
  mock_task_runner_->RunTasksWhile(
      base::Bind(&MessageLoopTaskCounter, &task_count));

  EXPECT_EQ(1u, task_count);
}

TEST_F(ThrottlingHelperTest,
       SingleFutureThrottledTaskPumpedAndRunWithNoExtraneousMessageLoopTasks) {
  throttling_helper_->IncreaseThrottleRefCount(timer_queue_.get());

  base::TimeDelta delay(base::TimeDelta::FromSecondsD(15.5));
  timer_queue_->PostDelayedTask(FROM_HERE, base::Bind(&NopTask), delay);

  size_t task_count = 0;
  mock_task_runner_->RunTasksWhile(
      base::Bind(&MessageLoopTaskCounter, &task_count));

  EXPECT_EQ(1u, task_count);
}

TEST_F(ThrottlingHelperTest,
       TwoFutureThrottledTaskPumpedAndRunWithNoExtraneousMessageLoopTasks) {
  throttling_helper_->IncreaseThrottleRefCount(timer_queue_.get());
  std::vector<base::TimeTicks> run_times;

  base::TimeDelta delay(base::TimeDelta::FromSecondsD(15.5));
  timer_queue_->PostDelayedTask(FROM_HERE,
                                base::Bind(&TestTask, &run_times, clock_.get()),
                                delay);

  base::TimeDelta delay2(base::TimeDelta::FromSecondsD(5.5));
  timer_queue_->PostDelayedTask(FROM_HERE,
                                base::Bind(&TestTask, &run_times, clock_.get()),
                                delay2);

  size_t task_count = 0;
  mock_task_runner_->RunTasksWhile(
      base::Bind(&MessageLoopTaskCounter, &task_count));

  EXPECT_EQ(2u, task_count);  // There are two since the cancelled task runs in
  // the same DoWork batch.

  EXPECT_THAT(
      run_times,
      ElementsAre(base::TimeTicks() + base::TimeDelta::FromSeconds(6),
                  base::TimeTicks() + base::TimeDelta::FromSeconds(16)));
}

TEST_F(ThrottlingHelperTest, TaskDelayIsBasedOnRealTime) {
  std::vector<base::TimeTicks> run_times;

  throttling_helper_->IncreaseThrottleRefCount(timer_queue_.get());

  // Post an initial task that should run at the first aligned time period.
  timer_queue_->PostDelayedTask(FROM_HERE,
                                base::Bind(&TestTask, &run_times, clock_.get()),
                                base::TimeDelta::FromMilliseconds(900.0));

  mock_task_runner_->RunUntilIdle();

  // Advance realtime.
  clock_->Advance(base::TimeDelta::FromMilliseconds(250));

  // Post a task that due to real time + delay must run in the third aligned
  // time period.
  timer_queue_->PostDelayedTask(FROM_HERE,
                                base::Bind(&TestTask, &run_times, clock_.get()),
                                base::TimeDelta::FromMilliseconds(900.0));

  mock_task_runner_->RunUntilIdle();

  EXPECT_THAT(
      run_times,
      ElementsAre(
          base::TimeTicks() + base::TimeDelta::FromMilliseconds(1000.0),
          base::TimeTicks() + base::TimeDelta::FromMilliseconds(3000.0)));
}

TEST_F(ThrottlingHelperTest, ThrottledTasksReportRealTime) {
  EXPECT_EQ(timer_queue_->GetTimeDomain()->Now(), clock_->NowTicks());

  throttling_helper_->IncreaseThrottleRefCount(timer_queue_.get());
  EXPECT_EQ(timer_queue_->GetTimeDomain()->Now(), clock_->NowTicks());

  clock_->Advance(base::TimeDelta::FromMilliseconds(250));
  // Make sure the throttled time domain's Now() reports the same as the
  // underlying clock.
  EXPECT_EQ(timer_queue_->GetTimeDomain()->Now(), clock_->NowTicks());
}

TEST_F(ThrottlingHelperTest, TaskQueueDisabledTillPump) {
  timer_queue_->PostTask(FROM_HERE, base::Bind(&NopTask));

  EXPECT_TRUE(timer_queue_->IsQueueEnabled());
  throttling_helper_->IncreaseThrottleRefCount(timer_queue_.get());
  EXPECT_FALSE(timer_queue_->IsQueueEnabled());

  mock_task_runner_->RunUntilIdle();  // Wait until the pump.
  EXPECT_TRUE(timer_queue_->IsQueueEnabled());
}

TEST_F(ThrottlingHelperTest, TaskQueueUnthrottle_InitiallyEnabled) {
  timer_queue_->PostTask(FROM_HERE, base::Bind(&NopTask));

  timer_queue_->SetQueueEnabled(true);  // NOP
  throttling_helper_->IncreaseThrottleRefCount(timer_queue_.get());
  EXPECT_FALSE(timer_queue_->IsQueueEnabled());

  throttling_helper_->DecreaseThrottleRefCount(timer_queue_.get());
  EXPECT_TRUE(timer_queue_->IsQueueEnabled());
}

TEST_F(ThrottlingHelperTest, TaskQueueUnthrottle_InitiallyDisabled) {
  timer_queue_->PostTask(FROM_HERE, base::Bind(&NopTask));

  timer_queue_->SetQueueEnabled(false);
  throttling_helper_->IncreaseThrottleRefCount(timer_queue_.get());
  EXPECT_FALSE(timer_queue_->IsQueueEnabled());

  throttling_helper_->DecreaseThrottleRefCount(timer_queue_.get());
  EXPECT_FALSE(timer_queue_->IsQueueEnabled());
}

TEST_F(ThrottlingHelperTest, SetQueueEnabled_Unthrottled) {
  timer_queue_->PostTask(FROM_HERE, base::Bind(&NopTask));

  throttling_helper_->SetQueueEnabled(timer_queue_.get(), false);
  EXPECT_FALSE(timer_queue_->IsQueueEnabled());

  throttling_helper_->SetQueueEnabled(timer_queue_.get(), true);
  EXPECT_TRUE(timer_queue_->IsQueueEnabled());
}

TEST_F(ThrottlingHelperTest, SetQueueEnabled_DisabledWhileThrottled) {
  timer_queue_->PostTask(FROM_HERE, base::Bind(&NopTask));

  throttling_helper_->IncreaseThrottleRefCount(timer_queue_.get());
  EXPECT_FALSE(timer_queue_->IsQueueEnabled());

  throttling_helper_->SetQueueEnabled(timer_queue_.get(), false);
  throttling_helper_->DecreaseThrottleRefCount(timer_queue_.get());
  EXPECT_FALSE(timer_queue_->IsQueueEnabled());
}

TEST_F(ThrottlingHelperTest, TaskQueueDisabledTillPump_ThenManuallyDisabled) {
  timer_queue_->PostTask(FROM_HERE, base::Bind(&NopTask));

  EXPECT_TRUE(timer_queue_->IsQueueEnabled());
  throttling_helper_->IncreaseThrottleRefCount(timer_queue_.get());
  EXPECT_FALSE(timer_queue_->IsQueueEnabled());

  mock_task_runner_->RunUntilIdle();  // Wait until the pump.
  EXPECT_TRUE(timer_queue_->IsQueueEnabled());

  throttling_helper_->SetQueueEnabled(timer_queue_.get(), false);
  EXPECT_FALSE(timer_queue_->IsQueueEnabled());
}

TEST_F(ThrottlingHelperTest, DoubleIncrementDoubleDecrement) {
  timer_queue_->PostTask(FROM_HERE, base::Bind(&NopTask));

  EXPECT_TRUE(timer_queue_->IsQueueEnabled());
  throttling_helper_->IncreaseThrottleRefCount(timer_queue_.get());
  throttling_helper_->IncreaseThrottleRefCount(timer_queue_.get());
  EXPECT_FALSE(timer_queue_->IsQueueEnabled());
  throttling_helper_->DecreaseThrottleRefCount(timer_queue_.get());
  throttling_helper_->DecreaseThrottleRefCount(timer_queue_.get());
  EXPECT_TRUE(timer_queue_->IsQueueEnabled());
}

}  // namespace scheduler

{'repo_name': 'crosswalk-project/chromium-crosswalk', 'stars': '146', 'repo_language': 'None', 'file_name': 'keyboard_utils.js', 'mime_type': 'text/plain', 'hash': -2094741441448043887, 'source_dataset': 'data'}


#include <iostream>
#include <fstream>
#include <string>

#include "Source/source/smolv.h"

static std::vector<char> ReadBinaryFile(const char* fileName)
{
	std::ifstream ifs(fileName, std::ios::binary | std::ios::ate);
	std::ifstream::pos_type pos = ifs.tellg();

	std::vector<char> result(pos);

	ifs.seekg(0, std::ios::beg);
	ifs.read(&result[0], pos);

	return result;
}

enum InputLanguage
{
	Spirv,
	Smolv
};

int main(int argc, const char* argv[])
{
	auto shaderBytes = ReadBinaryFile(argv[1]);

	auto inputLanguage = (InputLanguage)std::stoi(argv[2]);
	auto encodeFlags = (smolv::EncodeFlags)std::stoi(argv[3]);

	bool result;
	smolv::ByteArray outputBytes;

	auto stats = smolv::StatsCreate();

	switch (inputLanguage)
	{
	case Spirv:
		result = smolv::Encode(shaderBytes.data(), shaderBytes.size(), outputBytes, encodeFlags);
		if (result)
		{
			smolv::StatsCalculate(stats, shaderBytes.data(), shaderBytes.size());
		}
		break;

	case Smolv:
		outputBytes.resize(smolv::GetDecodedBufferSize(shaderBytes.data(), shaderBytes.size()));
		result = smolv::Decode(shaderBytes.data(), shaderBytes.size(), outputBytes.data(), outputBytes.size());
		if (result)
		{
			smolv::StatsCalculateSmol(stats, shaderBytes.data(), shaderBytes.size());
		}
		break;

	default:
		return 1;
	}

	smolv::StatsPrint(stats);

	smolv::StatsDelete(stats);

	std::ofstream out(argv[4], std::ios::binary | std::ios::out);
	out.write((char*) outputBytes.data(), outputBytes.size());
	out.close();

	return 0;
}

{'repo_name': 'tgjones/shader-playground', 'stars': '213', 'repo_language': 'C', 'file_name': 'ShaderPlayground.Shims.Hlsl2Glsl.cpp', 'mime_type': 'text/x-c', 'hash': 7139019651318256980, 'source_dataset': 'data'}


//---------------------------------------------------------------------------
//	Greenplum Database
//	Copyright (C) 2011 EMC Corp.
//
//	@filename:
//		CLogicalLeftAntiSemiJoin.h
//
//	@doc:
//		Left anti semi join operator
//---------------------------------------------------------------------------
#ifndef GPOS_CLogicalLeftAntiSemiJoin_H
#define GPOS_CLogicalLeftAntiSemiJoin_H

#include "gpos/base.h"

#include "gpopt/operators/CLogicalJoin.h"

namespace gpopt
{
	//---------------------------------------------------------------------------
	//	@class:
	//		CLogicalLeftAntiSemiJoin
	//
	//	@doc:
	//		Left anti semi join operator
	//
	//---------------------------------------------------------------------------
	class CLogicalLeftAntiSemiJoin : public CLogicalJoin
	{
		private:

			// private copy ctor
			CLogicalLeftAntiSemiJoin(const CLogicalLeftAntiSemiJoin &);

		public:

			// ctor
			explicit
			CLogicalLeftAntiSemiJoin(CMemoryPool *mp);

			// dtor
			virtual
			~CLogicalLeftAntiSemiJoin()
			{}

			// ident accessors
			virtual
			EOperatorId Eopid() const
			{
				return EopLogicalLeftAntiSemiJoin;
			}

			// return a string for operator name
			virtual
			const CHAR *SzId() const
			{
				return "CLogicalLeftAntiSemiJoin";
			}

			// return true if we can pull projections up past this operator from its given child
			virtual
			BOOL FCanPullProjectionsUp
				(
				ULONG child_index
				) const
			{
				return (0 == child_index);
			}

			//-------------------------------------------------------------------------------------
			// Derived Relational Properties
			//-------------------------------------------------------------------------------------

			// derive output columns
			virtual
			CColRefSet *DeriveOutputColumns(CMemoryPool *mp, CExpressionHandle &exprhdl);

			// derive not nullable output columns
			virtual
			CColRefSet *DeriveNotNullColumns
				(
				CMemoryPool *,// mp
				CExpressionHandle &exprhdl
				)
				const
			{
				return PcrsDeriveNotNullPassThruOuter(exprhdl);
			}

			// dervive keys
			virtual
			CKeyCollection *DeriveKeyCollection(CMemoryPool *mp, CExpressionHandle &exprhdl) const;

			// derive max card
			virtual
			CMaxCard MaxCard(CMemoryPool *mp, CExpressionHandle &exprhdl) const;

			// derive constraint property
			virtual
			CPropConstraint *DerivePropertyConstraint
				(
				CMemoryPool *, //mp,
				CExpressionHandle &exprhdl
				)
				const
			{
				return PpcDeriveConstraintPassThru(exprhdl, 0 /*ulChild*/);
			}

			//-------------------------------------------------------------------------------------
			// Transformations
			//-------------------------------------------------------------------------------------

			// candidate set of xforms
			CXformSet *PxfsCandidates(CMemoryPool *mp) const;

			// derive statistics
			virtual
			IStatistics *PstatsDerive
						(
						CMemoryPool *mp,
						CExpressionHandle &exprhdl,
						IStatisticsArray *stats_ctxt
						)
						const;

			//-------------------------------------------------------------------------------------
			//-------------------------------------------------------------------------------------
			//-------------------------------------------------------------------------------------

			// conversion function
			static
			CLogicalLeftAntiSemiJoin *PopConvert
				(
				COperator *pop
				)
			{
				GPOS_ASSERT(NULL != pop);
				GPOS_ASSERT(EopLogicalLeftAntiSemiJoin == pop->Eopid());

				return dynamic_cast<CLogicalLeftAntiSemiJoin*>(pop);
			}

	}; // class CLogicalLeftAntiSemiJoin

}

#endif // !GPOS_CLogicalLeftAntiSemiJoin_H

// EOF

{'repo_name': 'greenplum-db/gporca', 'stars': '284', 'repo_language': 'C++', 'file_name': 'CKeyCollectionTest.h', 'mime_type': 'text/x-c++', 'hash': 2895673485311317254, 'source_dataset': 'data'}


/*
 * Copyright 2017-2020 original authors
 *
 * 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
 *
 * https://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 io.micronaut.annotation.processing.visitor;

import io.micronaut.core.annotation.AnnotationMetadata;
import io.micronaut.core.annotation.Internal;
import io.micronaut.core.util.CollectionUtils;
import io.micronaut.inject.annotation.DefaultAnnotationMetadata;
import io.micronaut.inject.ast.ClassElement;
import io.micronaut.inject.ast.MethodElement;
import io.micronaut.inject.ast.ParameterElement;

import edu.umd.cs.findbugs.annotations.NonNull;
import io.micronaut.inject.ast.PrimitiveElement;

import javax.lang.model.element.*;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.type.WildcardType;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * A method element returning data from a {@link ExecutableElement}.
 *
 * @author James Kleeh
 * @since 1.0
 */
@Internal
class JavaMethodElement extends AbstractJavaElement implements MethodElement {

    private final ExecutableElement executableElement;
    private final JavaVisitorContext visitorContext;
    private final JavaClassElement declaringClass;

    /**
     * @param declaringClass     The declaring class
     * @param executableElement  The {@link ExecutableElement}
     * @param annotationMetadata The annotation metadata
     * @param visitorContext The visitor context
     */
    JavaMethodElement(
            JavaClassElement declaringClass,
            ExecutableElement executableElement,
            AnnotationMetadata annotationMetadata,
            JavaVisitorContext visitorContext) {
        super(executableElement, annotationMetadata, visitorContext);
        this.executableElement = executableElement;
        this.visitorContext = visitorContext;
        this.declaringClass = declaringClass;
    }

    @NonNull
    @Override
    public ClassElement getGenericReturnType() {
        return returnType(declaringClass.getGenericTypeInfo());
    }

    @Override
    @NonNull
    public ClassElement getReturnType() {
        return returnType(Collections.emptyMap());
    }

    @Override
    public Optional<String> getDocumentation() {
        return Optional.ofNullable(visitorContext.getElements().getDocComment(executableElement));
    }

    @Override
    public ParameterElement[] getParameters() {
        List<? extends VariableElement> parameters = executableElement.getParameters();
        List<ParameterElement> elts = new ArrayList<>(parameters.size());
        for (Iterator<? extends VariableElement> i = parameters.iterator(); i.hasNext();) {
            VariableElement variableElement = i.next();
            if (! i.hasNext() && isSuspend(variableElement)) {
                continue;
            }
            AnnotationMetadata annotationMetadata = visitorContext.getAnnotationUtils().getAnnotationMetadata(variableElement);
            if (annotationMetadata.hasDeclaredAnnotation("org.jetbrains.annotations.Nullable")) {
                annotationMetadata = DefaultAnnotationMetadata.mutateMember(annotationMetadata, "javax.annotation.Nullable", Collections.emptyMap());
            }
            elts.add(new JavaParameterElement(declaringClass, variableElement, annotationMetadata, visitorContext));
        }
        return elts.toArray(new ParameterElement[elts.size()]);
    }

    @Override
    public ClassElement getDeclaringType() {
        Element enclosingElement = executableElement.getEnclosingElement();
        if (enclosingElement instanceof TypeElement) {
            TypeElement te = (TypeElement) enclosingElement;
            if (declaringClass.getName().equals(te.getQualifiedName().toString())) {
                return declaringClass;
            } else {
                return new JavaClassElement(
                        te,
                        visitorContext.getAnnotationUtils().getAnnotationMetadata(te),
                        visitorContext,
                        declaringClass.getGenericTypeInfo()
                );
            }
        } else {
            return declaringClass;
        }
    }

    @Override
    public ClassElement getOwningType() {
        return declaringClass;
    }

    private ClassElement returnType(Map<String, Map<String, TypeMirror>> info) {
        VariableElement varElement = CollectionUtils.last(executableElement.getParameters());
        if (isSuspend(varElement)) {
            DeclaredType dType = (DeclaredType) varElement.asType();
            WildcardType wType = (WildcardType) dType.getTypeArguments().iterator().next();
            TypeMirror tm = wType.getSuperBound();
            // check Void
            if ((tm instanceof DeclaredType) && sameType("kotlin.Unit", (DeclaredType) tm)) {
                return PrimitiveElement.VOID;
            } else {
                return mirrorToClassElement(tm, visitorContext, info);
            }
        }
        return mirrorToClassElement(executableElement.getReturnType(), visitorContext, info);
    }

    private static boolean sameType(String type, DeclaredType dt) {
        Element elt = dt.asElement();
        return (elt instanceof TypeElement) && type.equals(((TypeElement) elt).getQualifiedName().toString());
    }

    private boolean isSuspend(VariableElement ve) {
        if (ve != null && ve.asType() instanceof DeclaredType) {
            DeclaredType dt = (DeclaredType) ve.asType();
            return sameType("kotlin.coroutines.Continuation", dt);
        }
        return false;
    }

}

{'repo_name': 'micronaut-projects/micronaut-core', 'stars': '3896', 'repo_language': 'Java', 'file_name': 'BeansEndpointSpec.groovy', 'mime_type': 'text/plain', 'hash': -8848167382256102185, 'source_dataset': 'data'}


%% -------------------------------------------------------------------
%%
%% Copyright (c) 2014 Basho Technologies, Inc.  All Rights Reserved.
%%
%% This file is provided to you under the Apache License,
%% Version 2.0 (the "License"); you may not use this file
%% except in compliance with the License.  You may obtain
%% a copy of the License at
%%
%%   http://www.apache.org/licenses/LICENSE-2.0
%%
%% Unless required by applicable law or agreed to in writing,
%% software distributed under the License is distributed on an
%% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
%% KIND, either express or implied.  See the License for the
%% specific language governing permissions and limitations
%% under the License.
%%
%% -------------------------------------------------------------------
-module(clique_manager).

-behaviour(gen_server).

%% gen_server api and callbacks
-export([start_link/0,
         init/1,
         handle_call/3,
         handle_cast/2,
         handle_info/2,
         terminate/2,
         code_change/3
        ]).

-record(state, {}).

start_link() ->
    gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).

%% Note that this gen_server only exists to create ets tables and keep them
%% around indefinitely. If it dies once, the node will die, as riak-admin will
%% functionality will no longer be available. However, since it discards all
%% messages, it can only die if explicitly killed.
%%
init([]) ->
    ok = clique_writer:init(),
    ok = clique_command:init(),
    ok = clique_usage:init(),
    ok = clique_config:init(),
    ok = clique_nodes:init(),
    {ok, #state{}}.

handle_call(_Msg, _From, State) ->
    {reply, ok, State}.
handle_cast(_Msg, State) ->
    {noreply, State}.
handle_info(_Msg, State) ->
    {noreply, State}.
terminate(_Reason, _State) ->
    ok.
code_change(_OldVsn, State, _Extra) ->
    {ok, State}.

{'repo_name': 'basho/clique', 'stars': '133', 'repo_language': 'Erlang', 'file_name': 'clique_specs.hrl', 'mime_type': 'text/plain', 'hash': -8790615020696828654, 'source_dataset': 'data'}


//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------

#ifndef _TSFORESTITEMDATA_H_
#define _TSFORESTITEMDATA_H_

#ifndef _FORESTITEM_H_
#include "forest/forestItem.h"
#endif
#ifndef _TSSHAPE_H_
#include "ts/tsShape.h"
#endif
#ifndef _RESOURCEMANAGER_H_
#include "core/resourceManager.h"
#endif

class TSShapeInstance;
class TSLastDetail;

class TSForestItemData : public ForestItemData
{
protected:

   typedef ForestItemData Parent;

   bool mIsClientObject;

   // This is setup during forest creation.
   mutable TSShapeInstance *mShapeInstance;

   Resource<TSShape> mShape;

   Vector<S32> mCollisionDetails;
   Vector<S32> mLOSDetails;

   TSShapeInstance* _getShapeInstance() const;

   void _loadShape();

   void _onResourceChanged( const Torque::Path &path );

   void _checkLastDetail();

   void _updateCollisionDetails();

   // ForestItemData
   void _preload() { _loadShape(); }

public:

   DECLARE_CONOBJECT(TSForestItemData);
   TSForestItemData();
   virtual ~TSForestItemData();

   bool preload( bool server, String &errorBuffer );
   void onRemove();
   bool onAdd();

   virtual void inspectPostApply();

   TSLastDetail* getLastDetail() const;

   // JCF: need access to this to build convex(s) in ForestConvex
   TSShapeInstance* getShapeInstance() const { return _getShapeInstance(); }

   const Vector<S32>& getCollisionDetails() const { return mCollisionDetails; }
   const Vector<S32>& getLOSDetails() const { return mLOSDetails; }

   // ForestItemData
   const Box3F& getObjBox() const { return mShape ? mShape->mBounds : Box3F::Zero; }
   bool render( TSRenderState *rdata, const ForestItem& item ) const;
   ForestCellBatch* allocateBatch() const;
   bool canBillboard( const SceneRenderState *state, const ForestItem &item, F32 distToCamera ) const;
   bool buildPolyList( const ForestItem& item, AbstractPolyList *polyList, const Box3F *box ) const { return false; }
};

#endif // _TSFORESTITEMDATA_H_

{'repo_name': 'GarageGames/Torque3D', 'stars': '3168', 'repo_language': 'C++', 'file_name': 'config_types.h.in', 'mime_type': 'text/x-c', 'hash': -675133674635037495, 'source_dataset': 'data'}


/*
Strike by Appiphony

Version: 1.0.0
Website: http://www.lightningstrike.io
GitHub: https://github.com/appiphony/Strike-Components
License: BSD 3-Clause License
*/
({
    afterRender: function(component, helper) {
        helper.setContainerWidth(component, helper);
        this.superAfterRender();
    }
})
/*
Copyright 2017 Appiphony, LLC

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
disclaimer.
2. 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.
3. Neither the name of the copyright holder 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 HOLDER 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.
*/

{'repo_name': 'appiphony/Strike-Components', 'stars': '169', 'repo_language': 'JavaScript', 'file_name': 'strike_lookupController.cls', 'mime_type': 'text/plain', 'hash': -513969628990943300, 'source_dataset': 'data'}