text:
//#include <windows.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

typedef int INT;
typedef void VOID;
typedef unsigned int   UINT;
typedef char           CHAR;
typedef unsigned char  BOOL;
typedef unsigned char  BYTE;

typedef short         WORD;
typedef int           DWORD;

typedef void          *HANDLE;
#define INVALID_HANDLE_VALUE    ((HANDLE)(-1))

#define _stricmp   strcasecmp
#define _strnicmp  strncasecmp
#define FALSE         0
#define TRUE          1

#define IN
#define OUT

#define MAX_PATH  1024

#define FILE_BEGIN           0
#define FILE_CURRENT         1
#define FILE_END             2

#define GENERIC_READ                     (0x80000000L)
#define GENERIC_WRITE                    (0x40000000L)
#define GENERIC_EXECUTE                  (0x20000000L)
#define GENERIC_ALL                      (0x10000000L)

#define DEVICE_TYPE DWORD

#define FILE_DEVICE_DISK                0x00000007
#define FILE_DEVICE_MASS_STORAGE        0x0000002d

#define IOCTL_STORAGE_BASE FILE_DEVICE_MASS_STORAGE

#define METHOD_BUFFERED                 0

#define FILE_ANY_ACCESS                 0

#define CTL_CODE( DeviceType, Function, Method, Access ) (                 \
    ((DeviceType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method) \
)

#define IOCTL_STORAGE_GET_DEVICE_NUMBER       CTL_CODE(IOCTL_STORAGE_BASE, 0x0420, METHOD_BUFFERED, FILE_ANY_ACCESS)

#define DRIVE_UNKNOWN     0
#define DRIVE_NO_ROOT_DIR 1
#define DRIVE_REMOVABLE   2
#define DRIVE_FIXED       3
#define DRIVE_REMOTE      4
#define DRIVE_CDROM       5
#define DRIVE_RAMDISK     6

#define FILE_SHARE_READ                 0x00000001
#define FILE_SHARE_WRITE                0x00000002
#define FILE_SHARE_DELETE               0x00000004

#define FILE_ATTRIBUTE_NORMAL               0x00000080

#define CREATE_NEW          1
#define CREATE_ALWAYS       2
#define OPEN_EXISTING       3
#define OPEN_ALWAYS         4
#define TRUNCATE_EXISTING   5

#define MAX_DRIVE                             26
#define PARTITION_TABLE_OFFSET                0x1BE

#define SIZE_OF_PARTITION_ENTRY               0x10

#define PARTITION_ENTRY_STARTLBA_OFFSET       8

#define PARTITION_ENTRY_NUM                   4

typedef struct _STORAGE_DEVICE_NUMBER {

    //
    // The FILE_DEVICE_XXX type for this device.
    //

    DEVICE_TYPE DeviceType;

    //
    // The number of this device
    //

    DWORD       DeviceNumber;

    //
    // If the device is partitionable, the partition number of the device.
    // Otherwise -1
    //

    DWORD       PartitionNumber;
} STORAGE_DEVICE_NUMBER, *PSTORAGE_DEVICE_NUMBER;

INT
GetDrvNumOffset (
  IN VOID *BootSector
  );

typedef enum {
  PatchTypeUnknown,
  PatchTypeFloppy,
  PatchTypeIde,
  PatchTypeUsb,
} PATCH_TYPE;

typedef enum {
  ErrorSuccess,
  ErrorFileCreate,
  ErrorFileReadWrite,
  ErrorNoMbr,
  ErrorFatType
} ERROR_STATUS;

CHAR *ErrorStatusDesc[] = {
  "Success",
  "Failed to create files",
  "Failed to read/write files",
  "No MBR exists",
  "Failed to detect Fat type"
};

typedef struct _DRIVE_TYPE_DESC {
  UINT  Type;
  CHAR  *Description;
} DRIVE_TYPE_DESC;

#define DRIVE_TYPE_ITEM(x) {x, #x}
DRIVE_TYPE_DESC DriveTypeDesc[] = {
  DRIVE_TYPE_ITEM (DRIVE_UNKNOWN),
  DRIVE_TYPE_ITEM (DRIVE_NO_ROOT_DIR),
  DRIVE_TYPE_ITEM (DRIVE_REMOVABLE),
  DRIVE_TYPE_ITEM (DRIVE_FIXED),
  DRIVE_TYPE_ITEM (DRIVE_REMOTE),
  DRIVE_TYPE_ITEM (DRIVE_CDROM),
  DRIVE_TYPE_ITEM (DRIVE_RAMDISK),
  (UINT) -1, NULL
};

typedef struct _DRIVE_INFO {
  CHAR              VolumeLetter;
  DRIVE_TYPE_DESC   *DriveType;
  UINT              DiskNumber;
} DRIVE_INFO;

#define BOOT_SECTOR_LBA_OFFSET 0x1FA

#define IsLetter(x) (((x) >= 'a' && (x) <= 'z') || ((x) >= 'A' && (x) <= 'Z'))

BOOL
GetDriveInfo (
  CHAR       VolumeLetter,
  DRIVE_INFO *DriveInfo
  )
/*++
Routine Description:
  Get drive information including disk number and drive type,
  where disknumber is useful for reading/writing disk raw data.
  NOTE: Floppy disk doesn't have disk number but it doesn't matter because
        we can reading/writing floppy disk without disk number.

Arguments:
  VolumeLetter : volume letter, e.g.: C for C:, A for A:
  DriveInfo    : pointer to DRIVE_INFO structure receiving drive information.

Return:
  TRUE  : successful
  FALSE : failed
--*/
{
  HANDLE                  VolumeHandle;
  STORAGE_DEVICE_NUMBER   StorageDeviceNumber;
  DWORD                   BytesReturned;
  BOOL                    Success;
  UINT                    DriveType;
  UINT                    Index;

  CHAR RootPath[]         = "X:\\";       // "X:\"  -> for GetDriveType
  CHAR VolumeAccessPath[] = "\\\\.\\X:";  // "\\.\X:"  -> to open the volume

  RootPath[0] = VolumeAccessPath[4] = VolumeLetter;
  DriveType = GetDriveType(RootPath);
  if (DriveType != DRIVE_REMOVABLE && DriveType != DRIVE_FIXED) {
    return FALSE;
  }

  DriveInfo->VolumeLetter = VolumeLetter;
  VolumeHandle = CreateFile (
                   VolumeAccessPath,
                   0,
                   FILE_SHARE_READ | FILE_SHARE_WRITE,
                   NULL,
                   OPEN_EXISTING,
                   0,
                   NULL
                   );
  if (VolumeHandle == INVALID_HANDLE_VALUE) {
    fprintf (
      stderr,
      "ERROR: CreateFile failed: Volume = %s, LastError = 0x%x\n",
      VolumeAccessPath,
      GetLastError ()
      );
    return FALSE;
  }

  //
  // Get Disk Number. It should fail when operating on floppy. That's ok
  //  because Disk Number is only needed when operating on Hard or USB disk.
  //
  // To direct write to disk:
  //   for USB and HD: use path = \\.\PHYSICALDRIVEx, where x is Disk Number
  //   for floppy:     use path = \\.\X:, where X can be A or B
  //
  Success = DeviceIoControl(
              VolumeHandle,
              IOCTL_STORAGE_GET_DEVICE_NUMBER,
              NULL,
              0,
              &StorageDeviceNumber,
              sizeof(StorageDeviceNumber),
              &BytesReturned,
              NULL
              );
  //
  // DeviceIoControl should fail if Volume is floppy or network drive.
  //
  if (!Success) {
    DriveInfo->DiskNumber = (UINT) -1;
  } else if (StorageDeviceNumber.DeviceType != FILE_DEVICE_DISK) {
    //
    // Only care about the disk.
    //
    return FALSE;
  } else{
    DriveInfo->DiskNumber = StorageDeviceNumber.DeviceNumber;
  }
  CloseHandle(VolumeHandle);

  //
  // Fill in the type string
  //
  DriveInfo->DriveType = NULL;
  for (Index = 0; DriveTypeDesc[Index].Description != NULL; Index ++) {
    if (DriveType == DriveTypeDesc[Index].Type) {
      DriveInfo->DriveType = &DriveTypeDesc[Index];
      break;
    }
  }

  if (DriveInfo->DriveType == NULL) {
    //
    // Should have a type.
    //
    fprintf (stderr, "ERROR: fetal error!!!\n");
    return FALSE;
  }
  return TRUE;
}

VOID
ListDrive (
  VOID
  )
/*++
Routine Description:
  List every drive in current system and their information.

--*/
{
  UINT       Index;
  DRIVE_INFO DriveInfo;

  UINT Mask =  GetLogicalDrives();

  for (Index = 0; Index < MAX_DRIVE; Index++) {
    if (((Mask >> Index) & 0x1) == 1) {
      if (GetDriveInfo ('A' + (CHAR) Index, &DriveInfo)) {
        if (Index < 2) {
          // Floppy will occupy 'A' and 'B'
          fprintf (
            stdout,
            "%c: - Type: %s\n",
            DriveInfo.VolumeLetter,
            DriveInfo.DriveType->Description
            );
        }
        else {
          fprintf (
            stdout,
            "%c: - DiskNum: %d, Type: %s\n",
            DriveInfo.VolumeLetter,
            DriveInfo.DiskNumber,
            DriveInfo.DriveType->Description
            );
        }
      }
    }
  }

}

INT
GetBootSectorOffset (
  HANDLE     DiskHandle,
  BOOL       WriteToDisk,
  PATCH_TYPE PatchType
  )
/*++
Description:
  Get the offset of boot sector.
  For non-MBR disk, offset is just 0
  for disk with MBR, offset needs to be caculated by parsing MBR

  NOTE: if no one is active, we will patch MBR to select first partition as active.

Arguments:
  DiskHandle  : HANDLE of disk
  WriteToDisk : TRUE indicates writing
  PatchType   : PatchTypeFloppy, PatchTypeIde, PatchTypeUsb

Return:
  -1   : failed
  o.w. : Offset to boot sector
--*/
{
  BYTE    DiskPartition[0x200];
  DWORD   BytesReturn;
  DWORD   DbrOffset;
  DWORD   Index;
  BOOL    HasMbr;

  DbrOffset = 0;
  HasMbr    = FALSE;

  SetFilePointer(DiskHandle, 0, NULL, FILE_BEGIN);
  if (!ReadFile (DiskHandle, DiskPartition, 0x200, &BytesReturn, NULL)) {
    return -1;
  }

  //
  // Check Signature, Jmp, and Boot Indicator.
  // if all pass, we assume MBR found.
  //

  // Check Signature: 55AA
  if ((DiskPartition[0x1FE] == 0x55) && (DiskPartition[0x1FF] == 0xAA)) {
    // Check Jmp: (EB ?? 90) or (E9 ?? ??)
    if (((DiskPartition[0] != 0xEB) || (DiskPartition[2] != 0x90)) &&
        (DiskPartition[0] != 0xE9)) {
      // Check Boot Indicator: 0x00 or 0x80
      // Boot Indicator is the first byte of Partition Entry
      HasMbr = TRUE;
      for (Index = 0; Index < PARTITION_ENTRY_NUM; ++Index) {
        if ((DiskPartition[PARTITION_TABLE_OFFSET + Index * SIZE_OF_PARTITION_ENTRY] & 0x7F) != 0) {
          HasMbr = FALSE;
          break;
        }
      }
    }
  }

  if (HasMbr) {
    //
    // Skip MBR
    //
    fprintf (stdout, "Skip MBR!\n");
    for (Index = 0; Index < PARTITION_ENTRY_NUM; Index++) {
      //
      // Found Boot Indicator.
      //
      if (DiskPartition[PARTITION_TABLE_OFFSET + (Index * SIZE_OF_PARTITION_ENTRY)] == 0x80) {
        DbrOffset = *(DWORD *)&DiskPartition[PARTITION_TABLE_OFFSET + (Index * SIZE_OF_PARTITION_ENTRY) + PARTITION_ENTRY_STARTLBA_OFFSET];
        break;
      }
    }
    //
    // If no boot indicator, we manually select 1st partition, and patch MBR.
    //
    if (Index == PARTITION_ENTRY_NUM) {
      DbrOffset = *(DWORD *)&DiskPartition[PARTITION_TABLE_OFFSET + PARTITION_ENTRY_STARTLBA_OFFSET];
      if (WriteToDisk && (PatchType == PatchTypeUsb)) {
        SetFilePointer(DiskHandle, 0, NULL, FILE_BEGIN);
        DiskPartition[PARTITION_TABLE_OFFSET] = 0x80;
        WriteFile (DiskHandle, DiskPartition, 0x200, &BytesReturn, NULL);
      }
    }
  }

  return DbrOffset;
}

ERROR_STATUS
ProcessBsOrMbr (
  CHAR        *DiskName,
  CHAR        *FileName,
  BOOL        WriteToDisk,
  PATCH_TYPE  PatchType,
  BOOL        ProcessMbr
  )
/*++
Routine Description:
  Writing or reading boot sector or MBR according to the argument.

Arguments:
  DiskName    : Win32 API recognized string name of disk
  FileName    : file name
  WriteToDisk : TRUE is to write content of file to disk, otherwise, reading content of disk to file
  PatchType   : PatchTypeFloppy, PatchTypeIde, PatchTypeUsb
  ProcessMbr  : TRUE is to process MBR, otherwise, processing boot sector

Return:
  ErrorSuccess
  ErrorFileCreate
  ErrorFileReadWrite
  ErrorNoMbr
  ErrorFatType
--*/
{
  BYTE    DiskPartition[0x200];
  BYTE    DiskPartitionBackup[0x200];
  HANDLE  DiskHandle;
  HANDLE  FileHandle;
  DWORD   BytesReturn;
  DWORD   DbrOffset;
  INT     DrvNumOffset;

  DiskHandle = CreateFile (
                 DiskName,
                 GENERIC_READ | GENERIC_WRITE,
                 FILE_SHARE_READ,
                 NULL,
                 OPEN_EXISTING,
                 FILE_ATTRIBUTE_NORMAL,
                 NULL
                 );
  if (DiskHandle == INVALID_HANDLE_VALUE) {
    return ErrorFileCreate;
  }

  FileHandle = CreateFile (
                 FileName,
                 GENERIC_READ | GENERIC_WRITE,
                 0,
                 NULL,
                 OPEN_ALWAYS,
                 FILE_ATTRIBUTE_NORMAL,
                 NULL
                 );
  if (FileHandle == INVALID_HANDLE_VALUE) {
    return ErrorFileCreate;
  }

  DbrOffset = 0;
  //
  // Skip potential MBR for Ide & USB disk
  //
  if ((PatchType == PatchTypeIde) || (PatchType == PatchTypeUsb)) {
    //
    // Even user just wants to process MBR, we get offset of boot sector here to validate the disk
    //  if disk have MBR, DbrOffset should be greater than 0
    //
    DbrOffset = GetBootSectorOffset (DiskHandle, WriteToDisk, PatchType);

    if (!ProcessMbr) {
      //
      // 1. Process boot sector, set file pointer to the beginning of boot sector
      //
      SetFilePointer (DiskHandle, DbrOffset * 0x200, NULL, FILE_BEGIN);
    } else if(DbrOffset == 0) {
      //
      // If user want to process Mbr, but no Mbr exists, simply return FALSE
      //
      return ErrorNoMbr;
    } else {
      //
      // 2. Process MBR, set file pointer to 0
      //
      SetFilePointer (DiskHandle, 0, NULL, FILE_BEGIN);
    }
  }

  //
  // [File Pointer is pointed to beginning of Mbr or Dbr]
  //
  if (WriteToDisk) {
    //
    // Write
    //
    if (!ReadFile (FileHandle, DiskPartition, 0x200, &BytesReturn, NULL)) {
      return ErrorFileReadWrite;
    }
    if (ProcessMbr) {
      //
      // Use original partition table
      //
      if (!ReadFile (DiskHandle, DiskPartitionBackup, 0x200, &BytesReturn, NULL)) {
        return ErrorFileReadWrite;
      }
      memcpy (DiskPartition + 0x1BE, DiskPartitionBackup + 0x1BE, 0x40);
      SetFilePointer (DiskHandle, 0, NULL, FILE_BEGIN);
    }

    if (!WriteFile (DiskHandle, DiskPartition, 0x200, &BytesReturn, NULL)) {
      return ErrorFileReadWrite;
    }

  } else {
    //
    // Read
    //
    if (!ReadFile (DiskHandle, DiskPartition, 0x200, &BytesReturn, NULL)) {
      return ErrorFileReadWrite;
    }

    if (PatchType == PatchTypeUsb) {
      // Manually set BS_DrvNum to 0x80 as window's format.exe has a bug which will clear this field discarding USB disk's MBR.
      // offset of BS_DrvNum is 0x24 for FAT12/16
      //                        0x40 for FAT32
      //
      DrvNumOffset = GetDrvNumOffset (DiskPartition);
      if (DrvNumOffset == -1) {
        return ErrorFatType;
      }
      //
      // Some legacy BIOS require 0x80 discarding MBR.
      // Question left here: is it needed to check Mbr before set 0x80?
      //
      DiskPartition[DrvNumOffset] = ((DbrOffset > 0) ? 0x80 : 0);
  }

    if (PatchType == PatchTypeIde) {
      //
      // Patch LBAOffsetForBootSector
      //
      *(DWORD *)&DiskPartition [BOOT_SECTOR_LBA_OFFSET] = DbrOffset;
    }
    if (!WriteFile (FileHandle, DiskPartition, 0x200, &BytesReturn, NULL)) {
      return ErrorFileReadWrite;
    }
  }
  CloseHandle (FileHandle);
  CloseHandle (DiskHandle);
  return ErrorSuccess;
}

VOID
PrintUsage (
  CHAR* AppName
  )
{
  fprintf (
    stdout,
    "Usage: %s [OPTIONS]...\n"
    "Copy file content from/to bootsector.\n"
    "\n"
    "  -l        list disks\n"
    "  -if=FILE  specified an input, can be files or disks\n"
    "  -of=FILE  specified an output, can be files or disks\n"
    "  -mbr      process MBR also\n"
    "  -h        print this message\n"
    "\n"
    "FILE providing a volume plus a colon (X:), indicates a disk\n"
    "FILE providing other format, indicates a file\n",
    AppName
    );
}

INT
main (
  INT  argc,
  CHAR *argv[]
  )
{
  CHAR          *AppName;
  INT           Index;
  BOOL          ProcessMbr;
  CHAR          VolumeLetter;
  CHAR          *FilePath;
  BOOL          WriteToDisk;
  DRIVE_INFO    DriveInfo;
  PATCH_TYPE    PatchType;
  ERROR_STATUS  Status;

  CHAR        FloppyPathTemplate[] = "\\\\.\\%c:";
  CHAR        DiskPathTemplate[]   = "\\\\.\\PHYSICALDRIVE%u";
  CHAR        DiskPath[MAX_PATH];

  AppName = *argv;
  argv ++;
  argc --;

  ProcessMbr    = FALSE;
  WriteToDisk   = TRUE;
  FilePath      = NULL;
  VolumeLetter  = 0;

  //
  // Parse command line
  //
  for (Index = 0; Index < argc; Index ++) {
    if (_stricmp (argv[Index], "-l") == 0) {
      ListDrive ();
      return 0;
    }
    else if (_stricmp (argv[Index], "-mbr") == 0) {
      ProcessMbr = TRUE;
    }
    else if ((_strnicmp (argv[Index], "-if=", 4) == 0) ||
             (_strnicmp (argv[Index], "-of=", 4) == 0)
             ) {
      if (argv[Index][6] == '\0' && argv[Index][5] == ':' && IsLetter (argv[Index][4])) {
        VolumeLetter = argv[Index][4];
        if (_strnicmp (argv[Index], "-if=", 4) == 0) {
          WriteToDisk = FALSE;
        }
      }
      else {
        FilePath = &argv[Index][4];
      }
    }
    else {
      PrintUsage (AppName);
      return 1;
    }
  }

  //
  // Check parameter
  //
  if (VolumeLetter == 0) {
    fprintf (stderr, "ERROR: Volume isn't provided!\n");
    PrintUsage (AppName);
    return 1;
  }

  if (FilePath == NULL) {
    fprintf (stderr, "ERROR: File isn't pvovided!\n");
    PrintUsage (AppName);
    return 1;
  }

  PatchType = PatchTypeUnknown;

  if ((VolumeLetter == 'A') || (VolumeLetter == 'a') ||
      (VolumeLetter == 'B') || (VolumeLetter == 'b')
      ) {
    //
    // Floppy
    //
    sprintf (DiskPath, FloppyPathTemplate, VolumeLetter);
    PatchType = PatchTypeFloppy;
  }
  else {
    //
    // Hard/USB disk
    //
    if (!GetDriveInfo (VolumeLetter, &DriveInfo)) {
      fprintf (stderr, "ERROR: GetDriveInfo - 0x%x\n", GetLastError ());
      return 1;
    }

    //
    // Shouldn't patch my own hard disk, but can read it.
    // very safe then:)
    //
    if (DriveInfo.DriveType->Type == DRIVE_FIXED && WriteToDisk) {
      fprintf (stderr, "ERROR: Write to local harddisk - permission denied!\n");
      return 1;
    }

    sprintf (DiskPath, DiskPathTemplate, DriveInfo.DiskNumber);
    if (DriveInfo.DriveType->Type == DRIVE_REMOVABLE) {
      PatchType = PatchTypeUsb;
    }
    else if (DriveInfo.DriveType->Type == DRIVE_FIXED) {
      PatchType = PatchTypeIde;
    }
  }

  if (PatchType == PatchTypeUnknown) {
    fprintf (stderr, "ERROR: PatchType unknown!\n");
    return 1;
  }

  //
  // Process DBR (Patch or Read)
  //
  Status = ProcessBsOrMbr (DiskPath, FilePath, WriteToDisk, PatchType, ProcessMbr);
  if (Status == ErrorSuccess) {
    fprintf (
      stdout,
      "%s %s successfully!\n",
      WriteToDisk ? "Write" : "Read",
      ProcessMbr ? "MBR" : "DBR"
      );
    return 0;
  } else {
    fprintf (
      stderr,
      "%s: %s %s failed - %s (LastError: 0x%x)!\n",
      (Status == ErrorNoMbr) ? "WARNING" : "ERROR",
      WriteToDisk ? "Write" : "Read",
      ProcessMbr ? "MBR" : "DBR",
      ErrorStatusDesc[Status],
      GetLastError ()
      );
    return 1;
  }
}


text:
namespace
{
using namespace routing;

char const kNo[] = "No";
char const kOnly[] = "Only";
char const kNoUTurn[] = "NoUTurn";
char const kOnlyUTurn[] = "OnlyUTurn";
char const kDelim[] = ", \t\r\n";

bool ParseLineOfWayIds(strings::SimpleTokenizer & iter, std::vector<base::GeoObjectId> & numbers)
{
  uint64_t number = 0;
  for (; iter; ++iter)
  {
    if (!strings::to_uint64(*iter, number))
      return false;
    numbers.push_back(base::MakeOsmWay(number));
  }
  return true;
}
}  // namespace

namespace routing
{
m2::PointD constexpr RestrictionCollector::kNoCoords;

RestrictionCollector::RestrictionCollector(std::string const & osmIdsToFeatureIdPath,
                                           std::unique_ptr<IndexGraph> && graph)
  : m_indexGraph(std::move(graph))
{
  CHECK(ParseRoadsOsmIdToFeatureIdMapping(osmIdsToFeatureIdPath, m_osmIdToFeatureId),
        ("An error happened while parsing feature id to "
         "osm ids mapping from file:", osmIdsToFeatureIdPath));
}

bool RestrictionCollector::Process(std::string const & restrictionPath)
{
  CHECK(m_indexGraph, ());

  SCOPE_GUARD(clean, [this]() {
    m_osmIdToFeatureId.clear();
    m_restrictions.clear();
  });

  if (!ParseRestrictions(restrictionPath))
  {
    LOG(LWARNING, ("An error happened while parsing restrictions from file:",  restrictionPath));
    return false;
  }

  clean.release();

  base::SortUnique(m_restrictions);

  LOG(LDEBUG, ("Number of loaded restrictions:", m_restrictions.size()));
  return true;
}

bool RestrictionCollector::ParseRestrictions(string const & path)
{
  std::ifstream stream(path);
  if (stream.fail())
    return false;

  std::string line;
  while (std::getline(stream, line))
  {
    strings::SimpleTokenizer iter(line, kDelim);
    if (!iter)  // the line is empty
      return false;

    Restriction::Type restrictionType;
    auto viaType = RestrictionWriter::ViaType::Count;
    FromString(*iter, restrictionType);
    ++iter;

    FromString(*iter, viaType);
    ++iter;

    m2::PointD coords = kNoCoords;
    if (viaType == RestrictionWriter::ViaType::Node)
    {
      FromString(*iter, coords.x);
      ++iter;
      FromString(*iter, coords.y);
      ++iter;
    }

    std::vector<base::GeoObjectId> osmIds;
    if (!ParseLineOfWayIds(iter, osmIds))
    {
      LOG(LWARNING, ("Cannot parse osm ids from", path));
      return false;
    }

    if (viaType == RestrictionWriter::ViaType::Node)
      CHECK_EQUAL(osmIds.size(), 2, ("Only |from| and |to| osmId."));

    CHECK_NOT_EQUAL(viaType, RestrictionWriter::ViaType::Count, ());
    AddRestriction(coords, restrictionType, osmIds);
  }
  return true;
}

Joint::Id RestrictionCollector::GetFirstCommonJoint(uint32_t firstFeatureId,
                                                    uint32_t secondFeatureId) const
{
  uint32_t const firstLen = m_indexGraph->GetGeometry().GetRoad(firstFeatureId).GetPointsCount();
  uint32_t const secondLen = m_indexGraph->GetGeometry().GetRoad(secondFeatureId).GetPointsCount();

  auto const firstRoad = m_indexGraph->GetRoad(firstFeatureId);
  auto const secondRoad = m_indexGraph->GetRoad(secondFeatureId);

  std::unordered_set<Joint::Id> used;
  for (uint32_t i = 0; i < firstLen; ++i)
  {
    if (firstRoad.GetJointId(i) != Joint::kInvalidId)
      used.emplace(firstRoad.GetJointId(i));
  }

  for (uint32_t i = 0; i < secondLen; ++i)
  {
    if (used.count(secondRoad.GetJointId(i)) != 0)
      return secondRoad.GetJointId(i);
  }

  return Joint::kInvalidId;
}

bool RestrictionCollector::FeatureHasPointWithCoords(uint32_t featureId,
                                                     m2::PointD const & coords) const
{
  CHECK(m_indexGraph, ());
  auto const & roadGeometry = m_indexGraph->GetGeometry().GetRoad(featureId);
  uint32_t const pointsCount = roadGeometry.GetPointsCount();
  for (uint32_t i = 0; i < pointsCount; ++i)
  {
    static double constexpr kEps = 1e-5;
    if (base::AlmostEqualAbs(roadGeometry.GetPoint(i), coords, kEps))
      return true;
  }

  return false;
}

bool RestrictionCollector::FeaturesAreCross(m2::PointD const & coords,
                                            uint32_t prev, uint32_t cur) const
{
  if (coords == kNoCoords)
    return GetFirstCommonJoint(prev, cur) != Joint::kInvalidId;

  return FeatureHasPointWithCoords(prev, coords) && FeatureHasPointWithCoords(cur, coords);
}

Restriction::Type ConvertUTurnToSimpleRestriction(Restriction::Type type)
{
  CHECK(IsUTurnType(type), ());

  // Some people create no_u_turn not in the way we expect.
  // For example: https://www.openstreetmap.org/relation/9511182
  //              https://www.openstreetmap.org/relation/2532732
  //              https://www.openstreetmap.org/relation/7606104
  // OsmId of |from| member is differ from |to| member.
  // So we "convert" such no_u_turn to any no_* restriction.
  // And we do the same thing with only_u_turn.
  return type == Restriction::Type::NoUTurn ? Restriction::Type::No
                                            : Restriction::Type::Only;
}

void ConvertToUTurnIfPossible(Restriction::Type & type, m2::PointD const & coords,
                              std::vector<uint32_t> const & featureIds)
{
  if (IsUTurnType(type))
    return;

  // Some people create u_turn not in the way we expect.
  // For example:
  // At 31.05.2019 there is no_left_turn by url:
  // https://www.openstreetmap.org/relation/1431150
  // with the same |from| and |to| member with node as |via|):
  //
  // So we "convert" such relations to no_u_turn or only_u_turn restrictions.
  if (featureIds.size() == 2 &&
      featureIds.front() == featureIds.back() &&
      coords != RestrictionCollector::kNoCoords)
  {
    type = type == Restriction::Type::No ? Restriction::Type::NoUTurn
                                         : Restriction::Type::OnlyUTurn;
  }
}

bool RestrictionCollector::CheckAndProcessUTurn(Restriction::Type & restrictionType,
                                                m2::PointD const & coords,
                                                std::vector<uint32_t> & featureIds) const
{
  CHECK(IsUTurnType(restrictionType), ());

  // UTurn with via as way.
  if (coords == kNoCoords)
  {
    // featureIds = {from, via_1, ..., via_N, to}, size must be greater or equal 3.
    CHECK_GREATER_OR_EQUAL(featureIds.size(), 3, ());
    restrictionType = ConvertUTurnToSimpleRestriction(restrictionType);
    return true;
  }

  // Only |from| and |to| member must be here, because via is node.
  if (featureIds.size() != 2)
    return false;

  // Typical no_u_turn with node as via, for example:
  // {
  //  from(featureId = 123),
  //  via (node at feature 123 = 2),
  //  to(featureId = 123)
  // }
  if (featureIds[0] == featureIds[1])
  {
    featureIds.pop_back();
    CHECK_EQUAL(featureIds.size(), 1, ());

    uint32_t & featureId = featureIds.back();

    auto const & road = m_indexGraph->GetGeometry().GetRoad(featureId);
    // Can not do UTurn from feature to the same feature if it is one way.
    if (road.IsOneWay())
      return false;

    uint32_t const n = road.GetPointsCount();

    // According to the wiki: via must be at the end or at the beginning of feature.
    // https://wiki.openstreetmap.org/wiki/Relation:restriction
    static auto constexpr kEps = 1e-5;
    bool const viaIsFirstNode = base::AlmostEqualAbs(coords, road.GetPoint(0), kEps);
    bool const viaIsLastNode = base::AlmostEqualAbs(coords, road.GetPoint(n - 1), kEps);

    if (viaIsFirstNode)
    {
      featureId |= RestrictionSerializer::kUTurnAtTheBeginMask;
    }
    else if (viaIsLastNode)
    {
      CHECK_EQUAL(featureId & RestrictionSerializer::kUTurnAtTheBeginMask, 0,
                  ("The first bit of featureId must be zero, too big value "
                   "of featureId, invariant violated."));
    }

    return viaIsFirstNode || viaIsLastNode;
  }

  restrictionType = ConvertUTurnToSimpleRestriction(restrictionType);
  return true;
}

bool RestrictionCollector::IsRestrictionValid(Restriction::Type & restrictionType,
                                              m2::PointD const & coords,
                                              std::vector<uint32_t> & featureIds) const
{
  if (featureIds.empty() || !m_indexGraph->IsRoad(featureIds[0]))
    return false;

  for (size_t i = 1; i < featureIds.size(); ++i)
  {
    auto prev = featureIds[i - 1];
    auto cur = featureIds[i];
    if (!m_indexGraph->IsRoad(cur))
      return false;

    if (!FeaturesAreCross(coords, prev, cur))
      return false;
  }

  ConvertToUTurnIfPossible(restrictionType, coords, featureIds);

  if (!IsUTurnType(restrictionType))
    return true;

  return CheckAndProcessUTurn(restrictionType, coords, featureIds);
}

bool RestrictionCollector::AddRestriction(m2::PointD const & coords,
                                          Restriction::Type restrictionType,
                                          std::vector<base::GeoObjectId> const & osmIds)
{
  std::vector<uint32_t> featureIds(osmIds.size());
  for (size_t i = 0; i < osmIds.size(); ++i)
  {
    auto const result = m_osmIdToFeatureId.find(osmIds[i]);
    if (result == m_osmIdToFeatureId.cend())
    {
      // It could happend near mwm border when one of a restriction lines is not included in mwm
      // but the restriction is included.
      return false;
    }

    // Only one feature id is found for |osmIds[i]|.
    featureIds[i] = result->second;
  }

  if (!IsRestrictionValid(restrictionType, coords, featureIds))
    return false;

  m_restrictions.emplace_back(restrictionType, featureIds);
  return true;
}

void RestrictionCollector::AddFeatureId(uint32_t featureId, base::GeoObjectId osmId)
{
  ::routing::AddFeatureId(osmId, featureId, m_osmIdToFeatureId);
}

void FromString(std::string const & str, Restriction::Type & type)
{
  if (str == kNo)
  {
    type = Restriction::Type::No;
    return;
  }

  if (str == kOnly)
  {
    type = Restriction::Type::Only;
    return;
  }

  if (str == kNoUTurn)
  {
    type = Restriction::Type::NoUTurn;
    return;
  }

  if (str == kOnlyUTurn)
  {
    type = Restriction::Type::OnlyUTurn;
    return;
  }

  CHECK(false,
        ("Invalid line:", str, "expected:", kNo, "or", kOnly, "or", kNoUTurn, "or", kOnlyUTurn));
  UNREACHABLE();
}

void FromString(std::string const & str, RestrictionWriter::ViaType & type)
{
  if (str == RestrictionWriter::kNodeString)
  {
    type = RestrictionWriter::ViaType::Node;
    return;
  }

  if (str == RestrictionWriter::kWayString)
  {
    type = RestrictionWriter::ViaType::Way;
    return;
  }

  CHECK(false, ("Invalid line:", str, "expected:", RestrictionWriter::kNodeString,
                "or", RestrictionWriter::kWayString));
}

void FromString(std::string const & str, double & number)
{
  CHECK(strings::to_double(str.c_str(), number), ());
}
}  // namespace routing

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace sagaco\DsagacoBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * ESagaco.tbMunicipio
 *
 * @ORM\Table(name="e_sagaco.tb_municipio", uniqueConstraints={@ORM\UniqueConstraint(name="uk_tb_municipio_co_estado_tx_inicia_municipio", columns={"co_estado", "tx_inicia_municipio"})}, indexes={@ORM\Index(name="IDX_AE18C511C82EC2C6", columns={"co_estado"})})
 * @ORM\Entity(repositoryClass="sagaco\DsagacoBundle\Entity\clMunicipioRepository")
 */
class clMunicipio
{
    /**
     * @var integer
     *
     * @ORM\Column(name="co_municipio", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="SEQUENCE")
     * @ORM\SequenceGenerator(sequenceName="e_sagaco.seq_tb_municipio_co_municipio", allocationSize=1, initialValue=1)
     */
    private $coMunicipio;

    /**
     * @var string
     *
     * @ORM\Column(name="tx_inicia_municipio", type="string", length=4, nullable=false)
     */
    private $txIniciaMunicipio;

    /**
     * @var string
     *
     * @ORM\Column(name="nb_municipio", type="string", length=50, nullable=false)
     */
    private $nbMunicipio;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="fh_creacion", type="datetime", nullable=false)
     */
    private $fhCreacion;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="fh_actualizacion", type="datetime", nullable=false)
     */
    private $fhActualizacion;

    /**
     * @var \ESagaco.tbEstado
     *
     * @ORM\ManyToOne(targetEntity="clEstado")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="co_estado", referencedColumnName="co_estado")
     * })
     */
    private $coEstado;

    /**
     * Get coMunicipio
     *
     * @return integer
     */
    public function getCoMunicipio()
    {
        return $this->coMunicipio;
    }

    /**
     * Set txIniciaMunicipio
     *
     * @param string $txIniciaMunicipio
     * @return clMunicipio
     */
    public function setTxIniciaMunicipio($txIniciaMunicipio)
    {
        $this->txIniciaMunicipio = $txIniciaMunicipio;

        return $this;
    }

    /**
     * Get txIniciaMunicipio
     *
     * @return string
     */
    public function getTxIniciaMunicipio()
    {
        return $this->txIniciaMunicipio;
    }

    /**
     * Set nbMunicipio
     *
     * @param string $nbMunicipio
     * @return clMunicipio
     */
    public function setNbMunicipio($nbMunicipio)
    {
        $this->nbMunicipio = $nbMunicipio;

        return $this;
    }

    /**
     * Get nbMunicipio
     *
     * @return string
     */
    public function getNbMunicipio()
    {
        return $this->nbMunicipio;
    }

    /**
     * Set fhCreacion
     *
     * @param \DateTime $fhCreacion
     * @return clMunicipio
     */
    public function setFhCreacion($fhCreacion)
    {
        $this->fhCreacion = $fhCreacion;

        return $this;
    }

    /**
     * Get fhCreacion
     *
     * @return \DateTime
     */
    public function getFhCreacion()
    {
        return $this->fhCreacion;
    }

    /**
     * Set fhActualizacion
     *
     * @param \DateTime $fhActualizacion
     * @return clMunicipio
     */
    public function setFhActualizacion($fhActualizacion)
    {
        $this->fhActualizacion = $fhActualizacion;

        return $this;
    }

    /**
     * Get fhActualizacion
     *
     * @return \DateTime
     */
    public function getFhActualizacion()
    {
        return $this->fhActualizacion;
    }

    /**
     * Set coEstado
     *
     * @param \sagaco\DsagacoBundle\Entity\clEstado $coEstado
     * @return clMunicipio
     */
    public function setCoEstado(\sagaco\DsagacoBundle\Entity\clEstado $coEstado = null)
    {
        $this->coEstado = $coEstado;

        return $this;
    }

    /**
     * Get coEstado
     *
     * @return \sagaco\DsagacoBundle\Entity\clEstado
     */
    public function getCoEstado()
    {
        return $this->coEstado;
    }

    public function __toString()
    {
        return $this->getNbMunicipio();
    }
}


text:
using System.IO;
using System.Xml.Serialization;

namespace CSharpTradeOffers.Configuration
{
    public class GenericConfigHandler
    {
        /// <summary>
        /// Reloads the configuration file (path). If file is not present, it will generate a new one.
        /// </summary>
        /// <returns>A generic object where TConfig:IConfig.</returns>
        public TConfig Reload<TConfig>(TConfig config) where TConfig : IConfig
        {
            string path = config.Path;
            if (!File.Exists(config.Path))
            {
                File.Create(config.Path).Close();
                File.WriteAllText(config.Path, config.SerializeToXml());
            }

            using (var sr = new StreamReader(config.Path))
            {
                config =
                    (TConfig)
                        new XmlSerializer(typeof(TConfig)).Deserialize(sr);
            }

            config.Path = path;

            return config;
        }

        /// <summary>
        /// Writes the changes made to the config.
        /// </summary>
        /// <param name="towrite"></param>
        public void WriteChanges<TConfig>(TConfig towrite) where TConfig : IConfig
        {
            File.WriteAllText(towrite.Path, towrite.SerializeToXml());
        }
    }
}


text:
export PATH='/go/bin':$PATH
export DOCKER_PATH='/go/src/github.com/awkisopen/docker'

# Signal coverage report name, parsed by docker-ci
set -x
COVERAGE_PATH=$(date +"docker-%Y%m%d%H%M%S")
set +x

REPORTS="/data/$COVERAGE_PATH"
INDEX="$REPORTS/index.html"

# Test docker
cd $DOCKER_PATH
./hack/make.sh test; exit_status=$?
PROFILE_PATH="$(ls -d $DOCKER_PATH/bundles/* | sed -n '$ p')/test/coverprofiles"

if [ "$exit_status" -eq "0" ]; then
    # Download coverage dependencies
    go get github.com/axw/gocov/gocov
    go get -u github.com/matm/gocov-html

    # Create coverage report
    mkdir -p $REPORTS
    cd $PROFILE_PATH
    cat > $INDEX << "EOF"
<!DOCTYPE html><meta charset="utf-8">

<title>Docker Coverage Report</title>

Docker Coverage Report

package	pct

EOF
    for profile in *; do
        gocov convert $profile | gocov-html >$REPORTS/$profile.html
        echo "
$profile	" >> $INDEX
        go tool cover -func=$profile | sed -En '$ s/.+\t(.+)/\1/p' >> $INDEX
        echo "
" >> $INDEX
    done
    echo "

" >> $INDEX
fi

# Signal test and coverage result, parsed by docker-ci
set -x
exit $exit_status


text:
require 'formula'

class Irrtoolset < Formula
  homepage 'http://irrtoolset.isc.org/'
  url 'http://ftp.isc.org/isc/IRRToolSet/IRRToolSet-5.0.1/irrtoolset-5.0.1.tar.gz'
  sha1 '19510275f5f64608e4a683c744c14f8e900ea19e'

  head do
    url 'svn://irrtoolset.isc.org/trunk'

    depends_on :autoconf
    depends_on :automake
    depends_on :libtool
  end

  depends_on 'pkg-config' => :build

  def install
    if build.head?
      system "glibtoolize"
      system "autoreconf -i"
    end

    system "./configure", "--prefix=#{prefix}"
    system "make install"
  end

  test do
    system "#{bin}/peval", "ANY"
  end
end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Validation</title>
<meta name="date" content="2017-01-14">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Field |

Required |

Optional

Detail:

Field |

Element

io.github.kkysen.quicktrip.app.input

Annotation Type Validation

@Documented
 @Retention(value=RUNTIME)
 @Target(value={METHOD,FIELD})
public @interface Validation

Optional Element Summary

Optional Elements

Modifier and Type
Optional Element and Description

boolean
value

Element Detail

value

public abstract boolean value

Default:

true

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Field |

Required |

Optional

Detail:

Field |

Element


text:
package com.tkmdpa.taf.pages.site.products_and_docs;

import com.tkmdpa.taf.pages.AncestorPage;
import net.serenitybdd.core.annotations.findby.FindBy;
import net.serenitybdd.core.pages.WebElementFacade;
import net.thucydides.core.annotations.DefaultUrl;

import java.util.HashMap;
import java.util.Map;

@DefaultUrl("/products-and-docs/apis/getting-started/")
public class PD_GettingStartedPage extends AncestorPage {

    public final String pageHeader = "GETTING STARTED";

    @FindBy(xpath = "//table[@class='article double-margin']/tbody")
    private WebElementFacade availableResourcesTable;

    @FindBy(xpath = "//div[contains(@class,'horizontal-events-tracker__section')]")
    private WebElementFacade summaryWidget;

    @FindBy(xpath = "//*[@id='main-block']/div/figure[2]/pre/code/span[@class='s2' and contains(., 'Rate limit quota violation. Quota limit  exceeded. Identifier :')]")
    private WebElementFacade apikeyPlaceHolder;

    public WebElementFacade getAvailableResourcesTable() {
       return  availableResourcesTable;
    }

    public WebElementFacade getSummaryWidget() {
        return  summaryWidget;
    }

    public Map<String,WebElementFacade> getAPIKeyPlaceHoldersList() {
        Map<String,WebElementFacade> elements = new HashMap<>();
        elements.put("apikeyPlaceHolder", apikeyPlaceHolder);
        return elements;
    }

}


text:
;(function($) {
  'use strict';

  /* global Notification:false */

  var Notifications = function(element, options) {
    this.$notifications = $(element);
    this.options = options || {};
  };

  Notifications.prototype.add = function(notification) {
    var template = this.options.template;

    if (notification.template) {
      template = notification.template;
    }

    var $notification = $(template).appendTo(this.$notifications).hide();

    // Get title and body
    $.when(
      this.getOption(notification.title, $notification),
      this.getOption(notification.body, $notification)
    )
      .done(function(title, body) {
        // Show event
        var showEvent = $.Event('show.lt.notification', {
          relatedTarget: $notification
        });
        this.$notifications.trigger(showEvent);

        // Allow event to be prevented
        if (showEvent.isDefaultPrevented()) { return; }

        // Update notification data
        $notification.find('.notification-title').text(title);
        $notification.find('.notification-body').text(body);

        // Set state
        if (notification.state) {
          $notification.addClass('notification-' + notification.state);
        }

        // Show notification
        var isGlobal = this.options.global;

        if (typeof notification.global !== 'undefined') {
          isGlobal = notification.global;
        }

        if (isGlobal && 'Notification' in window) {
          if (Notification.permission === 'granted') {
            new Notification(notification.title, {
              body: notification.body
            });
          }

          else if (Notification.permission !== 'denied') {
            Notification.requestPermission(function (permission) {
              if (!('permission' in Notification)) {
                Notification.permission = permission;
              }

              if (permission === 'granted') {
                new Notification(notification.title, {
                  body: notification.body
                });
              }
            });
          }
        } else {
          $notification.show();
        }

        // Shown event
        var shownEvent = $.Event('shown.lt.notification', {
          relatedTarget: $notification
        });
        this.$notifications.trigger(shownEvent);
      }.bind(this))
      .fail(function(err) {
        throw new Error(err);
      });

    // Add closing timer
    var duration = this.options.duration;

    if (typeof notification.duration !== 'undefined') {
      duration = notification.duration;
    }

    $.when(
      this.getOption(duration, $notification)
    )
      .done(function(timeout) {
        var timer = (typeof timeout === 'number') ? timeout : 0;
        setTimeout(function() {
          this.close($notification);
        }.bind(this), timer);
      }.bind(this));
  };

  Notifications.prototype.close = function($notification) {
    // Close event
    var closeEvent = $.Event('close.lt.notification', {
      relatedTarget: $notification
    });
    this.$notifications.trigger(closeEvent);

    // Allow event to be prevented
    if (closeEvent.isDefaultPrevented()) { return; }

    // Close notification
    $notification.remove();

    // Closed event
    var closedEvent = $.Event('closed.lt.notification', {
      relatedTarget: $notification
    });
    this.$notifications.trigger(closedEvent);
  };

  Notifications.prototype.getOption = function(option, $notification) {
    var deferred = $.Deferred();

    if (typeof option === 'string' || typeof option === 'number') {
      deferred.resolve(option);
    }
    else if (typeof option === 'function') {
      $.when(option.call(this, $notification)).then(function(result) {
        deferred.resolve(result);
      }, function(err) {
        deferred.reject(err);
      });
    }
    else if (typeof option === 'object') {
      $.when(option).then(function(result) {
        deferred.resolve(result);
      }, function(err) {
        deferred.reject(err);
      });
    }

    return deferred;
  };

  // Define jQuery plugin
  function Plugin(method, options) {
    return this.each(function() {
      var $notifications = $(this);
      var settings = $.extend({}, Plugin.defaults, $notifications.data(), typeof method === 'object' && method);

      var data = $notifications.data('lt.notifications');

      if (!data) {
        data = new Notifications(this, settings);
        $notifications.data('lt.notifications', data);
      }

      if (typeof method === 'string') {
        data[method](options);
      }
    });
  }

  Plugin.defaults = {
    duration: 5000,
    state: null,
    global: false,
    template: [
      '
',
        '

',
        '

',
        '<button type="button" class="notification-close" data-toggle="notification-close" aria-label="Close">×</button>',
      '
'
    ].join('')
  };

  $.fn.notifications = Plugin;

  $(document).on(
    'click.lt.notification.data-attr',
    '[data-toggle="notification-close"]',
    function (e) {
      var $trigger = $(this);

      if ($trigger.is('a')) {
        e.preventDefault();
      }

      var $notification = $trigger.closest('.notification');
      var notifications = $notification.closest('.notifications').data('lt.notifications');
      notifications.close($notification);
    }
  );

})(jQuery);


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace SharperArchitecture.Common.Collections
{
    public class CircularLinkedList<T> : IEnumerable<T> {
        private readonly LinkedList<T> _list = new LinkedList<T>();
        private readonly int _capacity;

        public CircularLinkedList(int capacity)
        {
            _capacity = capacity;
        }

        [MethodImpl(MethodImplOptions.Synchronized)]
        public void Add(T e) {
            _list.AddFirst(e);
            if (_list.Count > _capacity)
                _list.RemoveLast();
        }

        public IEnumerator<T> GetEnumerator() {
            return _list.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator() {
            return GetEnumerator();
        }
    }
}


text:
package org.spoofax.modelware.emf.resource;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;

import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.emf.common.CommonPlugin;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EAnnotation;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.impl.EPackageRegistryImpl;
import org.eclipse.emf.ecore.resource.impl.ResourceImpl;
import org.spoofax.interpreter.terms.IStrategoAppl;
import org.spoofax.interpreter.terms.IStrategoTerm;
import org.spoofax.interpreter.terms.ITermFactory;
import org.spoofax.modelware.emf.Language;
import org.spoofax.modelware.emf.LanguageRegistry;
import org.spoofax.modelware.emf.trans.Constants;
import org.spoofax.modelware.emf.trans.Tree2modelConverter;
import org.spoofax.modelware.emf.tree2model.Model2Term;
import org.spoofax.modelware.emf.utils.Utils;
import org.spoofax.terms.TermFactory;
import org.strategoxt.imp.runtime.Environment;
import org.strategoxt.imp.runtime.FileState;
import org.strategoxt.imp.runtime.dynamicloading.BadDescriptorException;

/**
 * An EMF resource implementation for Spoofax, which provides generic functionality for serializing and deserializing EObjects by means of a
 * user-defined syntax. One can use this resource implementation by extending `org.eclipse.emf.ecore.extension_parser` by means of an Eclipse
 * extension.
 *
 * @author oskarvanrest
 */
public class SpoofaxEMFResource extends ResourceImpl {

	protected IPath path;
	protected ITermFactory termFactory;

	public SpoofaxEMFResource(URI uri) {
		super(uri);

		URI resolvedFile = CommonPlugin.resolve(uri);
		this.path = new Path(resolvedFile.toFileString());
		this.termFactory = new TermFactory();
	}

	/**
	 * @override
	 */
	protected void doLoad(InputStream inputStream, Map<?, ?> options) {
		FileState editorOrFileState = Utils.getEditorOrFileState(path);
		IStrategoTerm ASTgraph = Utils.getASTgraph(editorOrFileState);

		EPackage pack = getEPackage();
		EObject eObject = null;

		if (ASTgraph instanceof IStrategoAppl) {
			eObject = new Tree2modelConverter(pack).convert(ASTgraph);
		}
		else {
			EAnnotation rootElementAnnotation = pack.getEAnnotation(Constants.ANNO_SPOOFAX_CONFIG);
			if (rootElementAnnotation != null) {
				String rootClass_String = rootElementAnnotation.getDetails().get(Constants.ANNO_SPOOFAX_CONFIG_ROOT);
				if (rootClass_String != null) {
					EClass rootClass_EClass = (EClass) pack.getEClassifier(rootClass_String);
					if (rootClass_EClass != null) {
						eObject = pack.getEFactoryInstance().create(rootClass_EClass);
					}
				}
			}
			if (eObject == null) {
				Environment.logException("Unknown root class.");
				return;
			}
		}

		getContents().add(0, eObject);
	}

	protected void doSave(OutputStream outputStream, Map<?, ?> options) {
		FileState editorOrFileState = Utils.getEditorOrFileState(path);

		if (editorOrFileState.getCurrentAst() == null) {
			Environment.logException("Can't parse file, see Spoofax.modelware/7");
			// TODO: pretty-print newTree
		}

		EObject object = getContents().get(0);
		Model2Term model2term = new Model2Term(new TermFactory());
		IStrategoTerm newTree = model2term.convert(object);
		newTree = Utils.getASTtext(newTree, editorOrFileState);

		try {
			String result = Utils.calculateTextReplacement(editorOrFileState.getCurrentAnalyzedAst(), newTree, editorOrFileState);
			outputStream.write(result.getBytes());
		}
		catch (IOException e) {
			e.printStackTrace();
		} catch (BadDescriptorException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Method to obtain the {@link EPackage} corresponding to the model to load, based on 'org.spoofax.modelware.gmf.synchronizer' extension.
	 *
	 * If no extension is provided (e.g. no GMF dependency is required), clients may override this method to provide the particular
	 * {@link EPackage} instance.
	 *
	 * @return the {@link EPackage} corresponding to the model to load
	 */
	protected EPackage getEPackage() {
		String textFileExtension = uri.fileExtension();
		Language language = LanguageRegistry.getInstance().get(textFileExtension);
		if (language == null) {
			Environment.logException("No language found for file extension '" + textFileExtension + "'. Most likely, you forgot to add an 'org.spoofax.modelware.gmf.synchronizer' extension. Note that this extension can be added to a random plugin.");
		}

		EPackage pack = EPackageRegistryImpl.INSTANCE.getEPackage(language.getNsURI());
		if (pack == null) {
			Environment.logException("Cannot find EPackage " + textFileExtension + ".");
		}
		return pack;
	}
}


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="DefaultEventHubTest.cs" company="Kephas Software SRL">
//   Copyright (c) Kephas Software SRL. All rights reserved.
//   Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
// <summary>
//   Implements the default event hub test class.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Kephas.Core.Tests.Interaction
{
    using System;

    using Kephas.Interaction;

    using NSubstitute;

    using NUnit.Framework;

    [TestFixture]
    public class EventHubExtensionsTest
    {
        [Test]
        public void Subscribe_wrong_args()
        {
            var calls = 0;
            Assert.Throws<ArgumentNullException>(() => EventHubExtensions.Subscribe<string>(null, async (e, c, t) => calls++));

            Assert.Throws<ArgumentNullException>(() => EventHubExtensions.Subscribe<string>(Substitute.For<IEventHub>(), null));
        }
    }
}


text:
<?php
namespace App\Controller\Admin;

use App\Controller\AppController;

/**
 * Users Controller
 *
 * @property \App\Model\Table\UsersTable $Users
 * @property \Alaxos\Controller\Component\FilterComponent $Filter
 */
class UsersController extends AppController
{
    /**
     * Helpers
     *
     * @var array
     */
    public $helpers = ['Alaxos.AlaxosHtml', 'Alaxos.AlaxosForm', 'Alaxos.Navbars'];

    /**
     * Components
     *
     * @var array
     */
    public $components = ['Alaxos.Filter'];

    /**
     * Index method
     *
     * @return void
     */
    public function index()
    {
        $this->paginate = [
            'contain' => ['Roles']
        ];
        $this->set('users', $this->paginate($this->Filter->getFilterQuery()));
        $this->set('_serialize', ['users']);

        $roles = $this->Users->Roles->find('list', ['limit' => 200]);
        $this->set(compact('roles'));
    }

    /**
     * View method
     *
     * @param string|null $id User id.
     * @return void
     * @throws \Cake\Http\Exception\NotFoundException When record not found.
     */
    public function view($id = null)
    {
        $user = $this->Users->get($id, [
            'contain' => ['Roles']
        ]);
        $this->set('user', $user);
        $this->set('_serialize', ['user']);
    }

    /**
     * Add method
     *
     * @return void|\Cake\Http\Response|null Redirects on successful add, renders view otherwise.
     */
    public function add()
    {
        $user = $this->Users->newEntity();
        if ($this->getRequest()->is('post')) {
            $user = $this->Users->patchEntity($user, $this->getRequest()->getData());
            if ($this->Users->save($user)) {
                $this->Flash->success(___('the user has been saved'), ['plugin' => 'Alaxos']);

                return $this->redirect(['action' => 'index']);
            } else {
                $this->Flash->error(___('the user could not be saved. Please, try again.'), ['plugin' => 'Alaxos']);
            }
        }
        $roles = $this->Users->Roles->find('list', ['limit' => 200]);
        $this->set(compact('user', 'roles'));
        $this->set('_serialize', ['user']);
    }

    /**
     * Edit method
     *
     * @param string|null $id User id.
     * @return void|\Cake\Http\Response|null Redirects on successful edit, renders view otherwise.
     * @throws \Cake\Http\Exception\NotFoundException When record not found.
     */
    public function edit($id = null)
    {
        $user = $this->Users->get($id, [
            'contain' => []
        ]);
        if ($this->getRequest()->is(['patch', 'post', 'put'])) {
            $user = $this->Users->patchEntity($user, $this->getRequest()->getData());
            if ($this->Users->save($user)) {
                $this->Flash->success(___('the user has been saved'), ['plugin' => 'Alaxos']);

                return $this->redirect(['action' => 'view', $id]);
            } else {
                $this->Flash->error(___('the user could not be saved. Please, try again.'), ['plugin' => 'Alaxos']);
            }
        }
        $roles = $this->Users->Roles->find('list', ['limit' => 200]);
        $this->set(compact('user', 'roles'));
        $this->set('_serialize', ['user']);
    }

    /**
     * Delete method
     *
     * @param string|null $id User id.
     * @return \Cake\Http\Response|null Redirects to index.
     * @throws \Cake\Http\Exception\NotFoundException When record not found.
     */
    public function delete($id = null)
    {
        $this->getRequest()->allowMethod(['post', 'delete']);
        $user = $this->Users->get($id);

        try {
            if ($this->Users->delete($user)) {
                $this->Flash->success(___('the user has been deleted'), ['plugin' => 'Alaxos']);
            } else {
                $this->Flash->error(___('the user could not be deleted. Please, try again.'), ['plugin' => 'Alaxos']);
            }
        } catch (\Exception $ex) {
            if ($ex->getCode() == 23000) {
                $this->Flash->error(___('the user could not be deleted as it is still used in the database'), ['plugin' => 'Alaxos']);
            } else {
                $this->Flash->error(sprintf(__('The user could not be deleted: %s', $ex->getMessage())), ['plugin' => 'Alaxos']);
            }
        }

        return $this->redirect(['action' => 'index']);
    }

    /**
     * Delete all method
     */
    public function deleteAll() {

        $this->getRequest()->allowMethod('post', 'delete');

        $checkedIds = $this->getRequest()->getData('checked_ids');
        if(!empty($checkedIds)) {

            $users = $this->Users->find()->where(['id IN' => $checkedIds]);

            $total         = $users->count();
            $total_deleted = 0;

            foreach($users as $user) {

                try {

                    if ($this->Users->delete($user)) {
                        $total_deleted++;
                    }

                } catch(\Exception $ex) {
                    $this->log($ex);
                }

            }

            if ($total_deleted == $total) {

                if ($total_deleted == 1) {
                    $this->Flash->success(___('the selected user has been deleted.'), ['plugin' => 'Alaxos']);
                } elseif ($total_deleted > 1) {
                    $this->Flash->success(sprintf(__('The %s selected users have been deleted.'), $total_deleted), ['plugin' => 'Alaxos']);
                }

            } else {

                if ($total_deleted == 0) {
                    $this->Flash->error(___('the selected users could not be deleted. Please, try again.'), ['plugin' => 'Alaxos']);
                } else {
                    $this->Flash->error(sprintf(___('only %s selected users on %s could be deleted'), $total_deleted, $total), ['element' => 'Alaxos']);
                }

            }

        } else {
            $this->Flash->error(___('there was no user to delete'), ['plugin' => 'Alaxos']);
        }

        return $this->redirect(['action' => 'index']);
    }

    /**
     * Copy method
     *
     * @param string|null $id User id.
     * @return void|\Cake\Http\Response|null Redirects on successful copy, renders view otherwise.
     * @throws \Cake\Http\Exception\NotFoundException When record not found.
     */
    public function copy($id = null)
    {
        $user = $this->Users->get($id, [
            'contain' => []
        ]);
        if ($this->getRequest()->is(['patch', 'post', 'put'])) {
            $user = $this->Users->newEntity();
            $user = $this->Users->patchEntity($user, $this->getRequest()->getData());
            if ($this->Users->save($user)) {
                $this->Flash->success(___('the user has been saved'), ['plugin' => 'Alaxos']);

                return $this->redirect(['action' => 'index']);
            } else {
                $this->Flash->error(___('the user could not be saved. Please, try again.'), ['plugin' => 'Alaxos']);
            }
        }
        $roles = $this->Users->Roles->find('list', ['limit' => 200]);

        $user->id = $id;
        $this->set(compact('user', 'roles'));
        $this->set('_serialize', ['user']);
    }
}


text:
package org.springframework.security.web.server.authentication;

import java.security.cert.X509Certificate;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

import org.springframework.http.server.reactive.SslInfo;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.mock.web.server.MockServerWebExchange;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.preauth.x509.X509PrincipalExtractor;
import org.springframework.security.web.authentication.preauth.x509.X509TestUtils;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;

@RunWith(MockitoJUnitRunner.class)
public class ServerX509AuthenticationConverterTests {

	@Mock
	private X509PrincipalExtractor principalExtractor;

	@InjectMocks
	private ServerX509AuthenticationConverter converter;

	private X509Certificate certificate;

	private MockServerHttpRequest.BaseBuilder<?> request;

	@Before
	public void setUp() throws Exception {
		this.request = MockServerHttpRequest.get("/");
		this.certificate = X509TestUtils.buildTestCertificate();
		given(this.principalExtractor.extractPrincipal(any())).willReturn("Luke Taylor");
	}

	@Test
	public void shouldReturnNullForInvalidCertificate() {
		Authentication authentication = this.converter.convert(MockServerWebExchange.from(this.request.build()))
				.block();
		assertThat(authentication).isNull();
	}

	@Test
	public void shouldReturnAuthenticationForValidCertificate() {
		this.request.sslInfo(new MockSslInfo(this.certificate));
		Authentication authentication = this.converter.convert(MockServerWebExchange.from(this.request.build()))
				.block();
		assertThat(authentication.getName()).isEqualTo("Luke Taylor");
		assertThat(authentication.getCredentials()).isEqualTo(this.certificate);
	}

	class MockSslInfo implements SslInfo {

		private final X509Certificate[] peerCertificates;

		MockSslInfo(X509Certificate... peerCertificates) {
			this.peerCertificates = peerCertificates;
		}

		@Override
		public String getSessionId() {
			return "mock-session-id";
		}

		@Override
		public X509Certificate[] getPeerCertificates() {
			return this.peerCertificates;
		}

	}

}


text:
<!DOCTYPE html>
<link rel="author" title="Morten Stenshorne" href="mailto:mstensho@chromium.org">
<link rel="help" href="https://www.w3.org/TR/css-break-3/#breaking-rules">
<link rel="help" href="https://bugs.chromium.org/p/chromium/issues/detail?id=1122901">
<link rel="match" href="../reference/ref-filled-green-100px-square.xht">

Test passes if there is a filled green square and no red.


text:
QMultiFileDialog::QMultiFileDialog() : QFileDialog() {
    m_btnOpen = NULL;
    m_listView = NULL;
    m_treeView = NULL;
    m_selectedFiles.clear();

    this->setOption(QFileDialog::DontUseNativeDialog, true);
    this->setOption(QFileDialog::DontResolveSymlinks, true);
    this->setFileMode(QFileDialog::Directory);
    QList<QPushButton*> btns = this->findChildren<QPushButton*>();
    for (int i = 0; i < btns.size(); ++i) {
        QString text = btns[i]->text();
        if (text.toLower().contains("open") || text.toLower().contains("choose"))
        {
            m_btnOpen = btns[i];
            break;
        }
    }

    if (!m_btnOpen) return;

    m_btnOpen->installEventFilter(this);
    m_btnOpen->disconnect(SIGNAL(clicked()));
    connect(m_btnOpen, SIGNAL(clicked()), this, SLOT(chooseClicked()));

    m_listView = findChild<QListView*>("listView");
    if (m_listView) {
        m_listView->setSelectionMode(QAbstractItemView::ExtendedSelection);
    }

    m_treeView = findChild<QTreeView*>();
    if (m_treeView) {
        m_treeView->setSelectionMode(QAbstractItemView::ExtendedSelection);
    }

}

bool QMultiFileDialog::eventFilter( QObject* watched, QEvent* event ) {
    QPushButton *btn = qobject_cast<QPushButton*>(watched);
    if (btn) {
        if(event->type()==QEvent::EnabledChange) {
            if (!btn->isEnabled()) {
                btn->setEnabled(true);
            }
        }
    }

    return QWidget::eventFilter(watched, event);
}

void QMultiFileDialog::chooseClicked() {
    QModelIndexList indexList = m_listView->selectionModel()->selectedIndexes();
    QString lastPath = "";
    foreach (QModelIndex index, indexList) {
        if (index.column() == 0) {
            if (!lastPath.isEmpty()) {
                m_selectedFiles.append(lastPath);
            }
            lastPath = this->directory().absolutePath() + '/' + index.data().toString();
        } else if (index.column() == 1) {
            // Check if a file size is specified. If not, it's a directory.
            if (!lastPath.isEmpty() && index.data().toString().isEmpty()) {
                lastPath.append('/');
            }
        }
    }
    if (!lastPath.isEmpty()) {
        m_selectedFiles.append(lastPath);
    }
    QDialog::accept();
}

QStringList QMultiFileDialog::selectedFiles() {
    return m_selectedFiles;
}


text:
title: SharePoint k1 trực tuyến
inshort: undefined
translator: Microsoft Cognitive Services
---


text:
<?xml version="1.0" encoding="utf-8"?>
<openerp>
    <data>

        <record id="view_base_module_configuration_form" model="ir.ui.view">
            <field name="name">Module Configuration</field>
            <field name="model">base.module.configuration</field>
            <field name="arch" type="xml">
                <form string="System Configuration Done">
                    <label string="All pending configuration wizards have been executed. You may restart individual wizards via the list of configuration wizards."/>
                    <footer>
                        <button string="Close" class="btn-primary" special="cancel" />
                    </footer>
                </form>
            </field>
        </record>

    </data>
</openerp>


text:
package org.jboss.resteasy.springmvc;

import org.jboss.resteasy.core.ServerResponseWriter;
import org.jboss.resteasy.core.SynchronousDispatcher;
import org.jboss.resteasy.specimpl.BuiltResponse;
import org.jboss.resteasy.spi.HttpRequest;
import org.jboss.resteasy.spi.HttpResponse;
import org.jboss.resteasy.spi.ResteasyDeployment;
import org.jboss.resteasy.util.HttpHeaderNames;
import org.jboss.resteasy.util.MediaTypeHelper;
import org.springframework.validation.BindingResult;
import org.springframework.web.servlet.View;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.MediaType;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * @author Solomon Duskis
 * @version $Revision: 1 $
 */

@SuppressWarnings("rawtypes")
public class ResteasyView implements View
{

   private MediaType contentType = null;
   private List<MediaType> potentialContentTypes = null;
   private ResteasyDeployment deployment;

   public ResteasyView(String contentType, ResteasyDeployment deployment)
   {
      setContentType(contentType);
      this.deployment = deployment;
   }

   public ResteasyView()
   {
   }

   public ResteasyDeployment getDeployment()
   {
      return deployment;
   }

   public void setDeployment(ResteasyDeployment deployment)
   {
      this.deployment = deployment;
   }

   public String getContentType()
   {
      return contentType.toString();
   }

   public List<String> getPotentialContentTypes()
   {
      List<String> contentTypes = new ArrayList<String>(potentialContentTypes.size());
      for (MediaType mediaType : potentialContentTypes)
      {
         contentTypes.add(mediaType.toString());
      }
      return contentTypes;
   }

   public void setPotentialContentTypes(List<String> potentialContentTypes)
   {
      this.potentialContentTypes = new ArrayList<MediaType>();
      for (String type : potentialContentTypes)
      {
         this.potentialContentTypes.add(MediaType.valueOf(type));
      }
   }

   public void render(final Map model, final HttpServletRequest servletRequest,
                      final HttpServletResponse servletResponse) throws Exception
   {
      final SynchronousDispatcher dispatcher = (SynchronousDispatcher)deployment.getDispatcher();
      ResteasyWebHandlerTemplate template = new ResteasyWebHandlerTemplate<Void>(dispatcher.getProviderFactory())
      {
         protected Void handle(ResteasyRequestWrapper requestWrapper,
                               HttpResponse response) throws Exception
         {
            HttpRequest httpRequest = requestWrapper.getHttpRequest();
            dispatcher.pushContextObjects(httpRequest, response);
            try
            {
               try
               {
                  MediaType resolvedContentType = resolveContentType(httpRequest,
                          httpRequest.getHttpHeaders().getMediaType());
                  BuiltResponse responseInvoker = getResponse(model, resolvedContentType);
                  if (responseInvoker != null)
                  {
                     ServerResponseWriter.writeNomapResponse(responseInvoker, httpRequest, response, dispatcher.getProviderFactory());
                  }
               }
               catch (Exception e)
               {
                  dispatcher.writeException(httpRequest, response, e);
               }
               return null;
            }
            finally
            {
               dispatcher.clearContextData();
            }
         }
      };
      ResteasyRequestWrapper requestWrapper = RequestUtil.getRequestWrapper(servletRequest);
      template.handle(requestWrapper, servletResponse);
   }

   private MediaType resolveContentType(HttpRequest jaxrsRequest, MediaType mt)
   {
      if (mt == null || MediaType.MEDIA_TYPE_WILDCARD.equals(mt.getType()))
      {
         List<MediaType> acceptableMediaTypes = jaxrsRequest.getHttpHeaders()
                 .getAcceptableMediaTypes();

         if (contentType != null && isAcceptable(acceptableMediaTypes, contentType))
         {
            return contentType;
         }

         return MediaTypeHelper.getBestMatch(potentialContentTypes, acceptableMediaTypes);
      }
      return mt;
   }

   private boolean isAcceptable(List<MediaType> acceptableMediaTypes,
                                MediaType potentialContentType)
   {
      boolean isAcceptable = false;
      for (MediaType acceptableMediaType : acceptableMediaTypes)
      {
         if (acceptableMediaType.isCompatible(potentialContentType))
         {
            isAcceptable = true;
            break;
         }
      }
      return isAcceptable;
   }

   protected BuiltResponse getResponse(Map model, MediaType mt)
   {
      Collection modelValues = model.values();
      for (Object value : modelValues)
      {
         if (value instanceof BuiltResponse)
         {
            return (BuiltResponse) value;
         }
      }

      if (model.size() == 1)
      {
         return createResponse(modelValues.iterator().next(), mt);
      }
      if (model.size() == 2)
      {
         for (Object value : modelValues)
         {
            if (!(value instanceof BindingResult))
            {
               return createResponse(value, mt);
            }
         }
      }
      return null;
   }

   private BuiltResponse createResponse(Object value, MediaType contentType)
   {
      BuiltResponse responseImpl = new BuiltResponse();
      responseImpl.setEntity(value);
      if (contentType != null)
         responseImpl.getMetadata().putSingle(HttpHeaderNames.CONTENT_TYPE, contentType);
      return responseImpl;
   }

   public void setContentType(String contentType)
   {
      this.contentType = MediaType.valueOf(contentType);
   }

}


text:
compil.erl
=========

This is a student project from the fu berlin compiler construction course_ in summer 2012.

about
-----

Compil.erl is an erlang written compiler, that compiles a static, inferred and
strong typed lisp ddialect into textual llvm ir.

quickstart
----------

Clone and build, build all erlang files:

::

    git clone git://github.com/slomo/compil.git
    cd compil
    ./build.sh

Given valid source code is in file code.lisp run:

::

    ./compil.sh code.lisp | tee | lli

or for llvm compilation instead of interpretation:

::

    ./compil.sh code.lisp | llc | gcc -x assembler -

REMEMBER: upon excution there will be no output (check return type)

Tested on erlang R14B02 and llvm 2.9.

reading order
-------------

* `doc/presentation.pdf` are slides to a 15 min talk about the language
* `doc/language_reference.rst` explains the language

thanks
------

* rvirding for lfe_ (took yecc and xrl file/ generated code from there )
* alxanders gave me good advice with fix point operator

Yves Müller, July 2012

.. _lfe: https://github.com/rvirding/lfe/
.. _course: https://page.mi.fu-berlin.de/konzackma12


text:
// Header for CAddressBookTitleTable class

#ifndef __CADRESSBOOKTITLETABLE__MULBERRY__
#define __CADRESSBOOKTITLETABLE__MULBERRY__

#include "CTitleTableView.h"

// Classes
class	CAddressBookTitleTable : public CTitleTableView
{
public:
					CAddressBookTitleTable();
	virtual 		~CAddressBookTitleTable();

protected:
	DECLARE_MESSAGE_MAP()
};

#endif


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="25dp"
    android:paddingLeft="15dp"
    android:paddingRight="15dp"
    android:paddingTop="25dp">

    <TextView
        android:id="@+id/tv_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:textColor="#000000"
        android:textSize="18sp" />

    <cn.iwgang.countuptime.CountupView
        android:id="@+id/cv_countdownView"
        android:layout_width="90dp"
        android:layout_height="30dp"
        android:layout_alignParentRight="true"
        android:background="@drawable/sel_btn"
        app:isShowMillisecond="true"
        app:isShowMinute="true"
        app:isShowSecond="true"
        app:suffixGravity="center"
        app:suffixTextColor="#000000"
        app:suffixTextSize="15sp"
        app:timeTextColor="#000000"
        app:timeTextSize="15sp" />

</RelativeLayout>


text:
package boofcv.alg.sfm.robust;

import boofcv.struct.geo.AssociatedPair;
import boofcv.struct.sfm.ScaleTranslate2D;
import org.ddogleg.fitting.modelset.DistanceFromModel;

import java.util.List;

/**
 * Computes distance squared between p1 after applying the {@link boofcv.struct.sfm.ScaleTranslate2D} motion model and p2.
 * </p>
 * ||p2 - (p1*scale+trans)||^2
 *
 * @author Peter Abeles
 */
public class DistanceScaleTranslate2DSq implements DistanceFromModel<ScaleTranslate2D,AssociatedPair> {

	ScaleTranslate2D model;

	@Override
	public void setModel(ScaleTranslate2D model) {
		this.model = model;
	}

	@Override
	public double computeDistance(AssociatedPair pt)
	{
		double dx = pt.p2.x - pt.p1.x*model.scale - model.transX;
		double dy = pt.p2.y - pt.p1.y*model.scale - model.transY;

		return dx*dx + dy*dy;
	}

	@Override
	public void computeDistance(List<AssociatedPair> obs, double[] distance) {
		final int N = obs.size();
		for( int i = 0; i < N; i++ ) {
			distance[i] = computeDistance(obs.get(i));
		}
	}
}


text:
package jetbrains.buildServer.runAs.agent;

import jetbrains.buildServer.dotNet.buildRunner.agent.CommandLineArgument;
import jetbrains.buildServer.dotNet.buildRunner.agent.ResourceGenerator;
import org.jetbrains.annotations.NotNull;

public class ShGenerator implements ResourceGenerator<RunAsParams> {
  public static final String BASH_HEADER = "#!/bin/bash";
  private static final String LINE_SEPARATOR = System.getProperty("line.separator");
  private final Converter<String, String> myArgumentConverter;

  public ShGenerator(
    @NotNull final Converter<String, String> argumentConverter) {
    myArgumentConverter = argumentConverter;
  }

  @NotNull
  @Override
  public String create(@NotNull final RunAsParams settings) {
    final StringBuilder sb = new StringBuilder();
    sb.append(BASH_HEADER);
    sb.append(LINE_SEPARATOR);

    boolean first = true;
    for (CommandLineArgument arg: settings.getCommandLineArguments()) {
      if(first) {
        first = false;
      }
      else {
        sb.append(' ');
      }

      sb.append(myArgumentConverter.convert(arg.getValue()));
    }

    return sb.toString();
  }
}


text:
#pragma once

#include "TCPClientServerBase.h"

namespace RS::Network::SocketPlus
{
    class TCPServer : public TCPClientServerBase
    {
    protected:
        i32                         mClientSocketFileDescriptor; //Keeps the socket file descriptor of the connected client.
        std::string                 mClientAddress; //Keeps the address of the connected client.

        /**
            @description: Binds the socket to the specified port number.
            @param portNumber : the port number that socket should bind to.
            @return void.
        **/
        virtual void                bind(ui32 portNumber);

        /**
            @description: Listen on the specified port number.
            @param backLogSize: maximum number of waiting connections in the queue before
            to be accepted by the server(default = 64).
            @return void.
        **/
        virtual void                listen(ui32 backlog = 64);

         /**
            @description: Accepts a proper connection request.
            @return file descriptor of the client.
        **/
        virtual i32                 accept(void);
    public:

        /**
            @description: TCPServer class constructor.
            @param domain : the communication domain which can be IPv4 or IPv6.
            @param protocol : the socket protocol. (will be removed in future updates.)
            @return
        **/
                                    TCPServer(SocketDomain domain = SocketDomain::IPv4, i32 protocol = 0);
        virtual                     ~TCPServer(void);

        /**
            @description: Sends entire string to the connected client.
            @param flags: specifies the behaviour of the function.(default = 0).
            @return: number of sent byte.
        **/
        virtual i32                 send(const std::string& message, i32 flags = 0);

        /**
            @description: Sends all data to the connected client.
            @param data: data that should be sent.
            @param length: length of the data.
            @param flags: specifies the behaviour of the function.(default = 0).
            @return: number of sent byte.
        **/
        virtual i32                 send(const char* data, i32 length, i32 flags = 0);

        /**
            @description: receives string from the connected client.
            @param outString: keeps received string.
            @param length: length of the received data.(default = 256)
            @param flags: specifies the behaviour of the function.(default = 0).
            @return: number of received byte.
        **/
        virtual i32                 receive(std::string& outString, i32 length = 256, i32 flags = 0);

        /**
            @description: starts the server. The server start listening on the specified port number.
            @param portNumber : the port number that socket should use.
            @param backLogSize: maximum number of waiting connection in the queue before accepted by server(default = 64)
            @return: void.
        **/
        virtual void                start(i32 portNumber, i32 backLogSize = 64);

        /**
            @description: Returns the connected client address.
            @param portNumber : the port number that socket should use.
            @param backLogSize: maximum number of waiting connection in the queue before accepted by server(default = 64)
            @return: void.
        **/
        virtual const std::string&  getClientAddress(void);
    };
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>R.attr</title>
<meta name="date" content="2014-08-18">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.echo.holographlibrary

Class R.attr

java.lang.Object

com.echo.holographlibrary.R.attr

Enclosing class:

R

public static final class R.attr
extends java.lang.Object

Field Summary

Fields

Modifier and Type
Field and Description

static int
barAxisColor

static int
barShowAxis

static int
barShowAxisLabel

static int
barShowPopup

static int
barShowText

static int
lineAxisColor

static int
lineStrokeColor

static int
lineStrokeSpacing

static int
lineStrokeWidth

static int
lineUseDip

static int
orientation

static int
pieInnerCircleRatio

static int
pieSlicePadding

Constructor Summary

Constructors

Constructor and Description

attr()

Method Summary

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

barAxisColor

public static final int barAxisColor

See Also:

Constant Field Values

barShowAxis

public static final int barShowAxis

See Also:

Constant Field Values

barShowAxisLabel

public static final int barShowAxisLabel

See Also:

Constant Field Values

barShowPopup

public static final int barShowPopup

See Also:

Constant Field Values

barShowText

public static final int barShowText

See Also:

Constant Field Values

lineAxisColor

public static final int lineAxisColor

See Also:

Constant Field Values

lineStrokeColor

public static final int lineStrokeColor

See Also:

Constant Field Values

lineStrokeSpacing

public static final int lineStrokeSpacing

See Also:

Constant Field Values

lineStrokeWidth

public static final int lineStrokeWidth

See Also:

Constant Field Values

lineUseDip

public static final int lineUseDip

See Also:

Constant Field Values

orientation

public static final int orientation

See Also:

Constant Field Values

pieInnerCircleRatio

public static final int pieInnerCircleRatio

See Also:

Constant Field Values

pieSlicePadding

public static final int pieSlicePadding

See Also:

Constant Field Values

Constructor Detail

attr

public attr()

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
package io.github.cjstehno.ersatz.encdec;

import lombok.val;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import static io.github.cjstehno.ersatz.TestAssertions.verifyEqualityAndHashCode;
import static io.github.cjstehno.ersatz.cfg.ContentType.IMAGE_PNG;
import static io.github.cjstehno.ersatz.cfg.ContentType.TEXT_PLAIN;
import static io.github.cjstehno.ersatz.encdec.MultipartRequestContent.multipartRequest;
import static org.junit.jupiter.api.Assertions.assertEquals;

class MultipartRequestContentTest {

    private static MultipartRequestContent multipartRequestContent() {
        return multipartRequest(mrc -> {
            mrc.part("alpha", "one");
            mrc.part("bravo", "text/markdown", "this _is_ *rich^ text");
            mrc.part("charlie", IMAGE_PNG, new byte[]{8, 6, 7, 5, 3, 0, 9});
            mrc.part("delta", "delta.txt", "text/markdown", "this _is_ more text");
            mrc.part("echo", "some.png", IMAGE_PNG, new byte[]{4, 2});
        });
    }

    @Test @DisplayName("consumer configuration") void consumer() {
        val content = multipartRequestContent();

        assertEquals(new MultipartPart("alpha", null, TEXT_PLAIN.getValue(), null, "one"), content.getAt("alpha"));
        assertEquals(new MultipartPart("bravo", null, "text/markdown", null, "this _is_ *rich^ text"), content.getAt("bravo"));
        assertEquals(new MultipartPart("charlie", null, IMAGE_PNG.getValue(), null, new byte[]{8, 6, 7, 5, 3, 0, 9}), content.getAt("charlie"));
        assertEquals(new MultipartPart("delta", "delta.txt", "text/markdown", null, "this _is_ more text"), content.getAt("delta"));
        assertEquals(new MultipartPart("echo", "some.png", IMAGE_PNG.getValue(), null, new byte[]{4, 2}), content.getAt("echo"));
    }

    @Test void equalsAndHash() {
        verifyEqualityAndHashCode(multipartRequestContent(), multipartRequestContent());
    }
}


text:
set -e
cd "`dirname "$0"`"

#if [ ! -f app/config/parameters.yml ]; then
#    cp app/config/parameters.yml.dist app/config/parameters.yml
#fi

if [ ! -f composer.phar ]; then
    curl -s http://getcomposer.org/installer | php
fi

php composer.phar install

rm -rf app/cache/* app/logs/*

if [ "$1" == "--symlink" ]; then
    ./app/console assets:install --symlink -v
else
    ./app/console assets:install -v
fi

./app/console doctrine:database:drop --force -v || true
./app/console doctrine:database:create -v
./app/console doctrine:schema:create -v
./app/console doctrine:fixtures:load --append -v
./app/console assetic:dump --env=prod --no-debug -v


text:
var mongoose = require("mongoose");

module.exports = mongoose.model('agent', {
	id: {
		type: String
	},
	name: {
		type: String
	}
});


text:
<?php
/**
 * PHP version 5
 *
 * This source file is subject to the license that is bundled with this package in the file LICENSE.
 */
namespace Mandragora\Controller\Action;

use Zend_Controller_Action_Exception;

/**
 * Base class for Mandragora controllers that handle authentication process
 */
class Auth extends AbstractAction
{
    /**
     * @var array
     */
    protected $sessionOptions;

    /**
     * @return mixed
     * @throws Zend_Controller_Action_Exception
     */
    public function getSessionOption($key)
    {
        if (is_null($this->sessionOptions)) {
            $this->sessionOptions = $this->getInvokeArg('bootstrap')
                                         ->getPluginResource('session')
                                         ->getOptions();
        }
        if (!array_key_exists($key, $this->sessionOptions)) {
            $message = "Session option '$key' does not exists";
            throw new Zend_Controller_Action_Exception($message, 500);
        }
        return $this->sessionOptions[$key];
    }
}


text:
package com.yngvark.gridwalls.microservices.netcom_forwarder.app.consume_input_file;

import com.yngvark.communicate_through_named_pipes.input.InputFileReader;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import static org.slf4j.LoggerFactory.getLogger;

public class InputFileConsumer {
    private final Logger logger = getLogger(getClass());
    private final Map<Command, FileMessageListener> listeners = new HashMap<>();
    private final InputFileReader inputFileReader;

    public InputFileConsumer(InputFileReader inputFileReader) {
        this.inputFileReader = inputFileReader;
    }

    public void addMessageListener(FileMessageListener fileMessageListener, String commandToListenFor) {
        logger.info("Adding message listener for command: " + commandToListenFor);
        listeners.put(new Command(commandToListenFor), fileMessageListener);
    }

    public void consume() throws IOException {
        inputFileReader.consume((msgRaw) -> {
            Message msg = parse(msgRaw);
            logger.info("<<< From input: " + msg);

            if (listeners.containsKey(msg.getCommand())) {
                listeners.get(msg.getCommand()).messageReceived(msg.getContents());
            } else {
                logger.warn("No listener for msg.");
            }
        });
    }

    private Message parse(String msg) {
        String[] parts = StringUtils.split(msg, " ", 2);
        if (parts.length != 2) {
            logger.error("Cannot parse raw message: {}", msg);
            return new Message(new Command("(unknown)"), msg);
        }

        return new Message(new Command(parts[0]), parts[1]);
    }
}


text:
#include "console/colors.h"
#include "scrollprf.h"
#include <stdio.h>
#include <stdarg.h>

ScrollPrintfElem::~ScrollPrintfElem ()
{
    if (text != 0)
	free (text);
}

ScrollPrintfElem::ScrollPrintfElem (const ScrollPrintfElem& elem) :
    line (0), color (ceFirstEntry), text (0)
{
    set (elem.line, elem.color, elem.text);
}

ScrollPrintfElem& ScrollPrintfElem::operator = (const ScrollPrintfElem& elem)
{
    set (elem.line, elem.color, elem.text);
    return *this;
}

int ScrollPrintfElem::compare (const ScrollPrintfElem& elem) const
{
    if (line < elem.line)
	return -1;
    else if (line > elem.line)
	return 1;
    else
	return 0;
}

void ScrollPrintfElem::set (int l, ColorEntry c, const char *t)
{
    line = l;
    color = c;
    if (text)
	free (text);
    text = _strdup (t);
    if (text == 0)
	throw AppException (WHERE, ERR_OUT_OF_MEMORY);
}

ScrollPrintf::~ScrollPrintf ()
{
}

int ScrollPrintf::isAtHome () const
{
    if (mCursor == 0)
	return 1;
    return 0;
}

int ScrollPrintf::isAtEnd () const
{
    if (mCursor == (int) mLines.size () - 1)
	return 1;
    return 0;
}

int ScrollPrintf::moveCursor (int count)
{
    // If a negative count is more than mCursor, we must limit it to neg mCursor
    if (-count > mCursor)
	count = -mCursor;

    // If a positive count is more than size - cursor - 1, we must limit it too.
    if (count > (int) mLines.size () - 1 - mCursor)
	count = (int) mLines.size () - 1 - mCursor;

    // Set the cursor and return actual amount
    mCursor += count;
    return count;
}

int ScrollPrintf::home ()
{
    int where = mCursor;
    mCursor = 0;
    return -where;
}

int ScrollPrintf::end ()
{
    int where = mCursor;
    mCursor = (int) mLines.size () - 1;
    return mCursor - where;
}

int ScrollPrintf::getText (int pos, char *line, int width) const
{
    if (line == 0)
	throw AppException (WHERE, ERR_INTERNAL);

    // Check for out of bounds
    line[0] = 0;
    if (mCursor + pos < 0  ||  mCursor + pos > (int) mLines.size () - 1)
	return 0;

    strncpy (line, mLines[mCursor + pos].getLine (), width);
    line[width] = 0;
    return (int) strlen (line);
}

void ScrollPrintf::getAttributes (int pos, WORD *attrs, int width) const
{
    if (attrs == 0)
	throw AppException (WHERE, ERR_INTERNAL);

    WORD cBack = (pos == 0 ? getColor (mcSel) : getColor (mcNorm));
    WORD color;

    // handle out of bounds case
    if (mCursor + pos < 0  ||  mCursor + pos > (int) mLines.size () - 1)
	color = cBack;
    else
	color = (cBack & (BACKGROUND_INTENSITY | BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE)) |
		(getColor (mLines[mCursor + pos].getColor ()) &
		 (FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE));

    for (int i = 0; i < width; i++)
        attrs[i] = color;
}

void ScrollPrintf::printLine (ColorEntry color, const char *fmt, ...)
{
    va_list list;

    va_start (list, fmt);
    vPrintLine (color, fmt, list);
    va_end (list);
}

void ScrollPrintf::vPrintLine (ColorEntry color, const char *fmt, va_list list)
{
    ScrollPrintfElem elem;
    char text [256];	    // 80 is real limit but let's play it safe
    vsprintf (text, fmt, list);
    elem.set (mNextLine, color, text);
    mLines.add (elem);
    mNextLine++;
}

// End


text:
package org.openfact.pe.services;

import org.jboss.logging.Logger;
import org.openfact.core.models.OrganizationModel;
import org.openfact.core.models.OrganizationProvider;
import org.openfact.core.models.PermissionType;
import org.openfact.core.security.ISecurityContext;
import org.openfact.pe.BajasResource;
import org.openfact.pe.managers.TypeManager;
import org.openfact.pe.models.BajaModel;
import org.openfact.pe.models.BajaProvider;
import org.openfact.pe.models.utils.ModelToRepresentation;
import org.openfact.pe.representations.idm.BajaRepresentation;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.transaction.Transactional;
import javax.ws.rs.ForbiddenException;
import javax.ws.rs.NotFoundException;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

@Transactional
@ApplicationScoped
public class DefaultBajasResource implements BajasResource {

    private static final Logger logger = Logger.getLogger(DefaultBajasResource.class);

    @Inject
    private ISecurityContext securityContext;

    @Inject
    private TypeManager typeManager;

    @Inject
    private BajaProvider bajaProvider;

    @Inject
    private ResourceManager resourceManager;

    @Inject
    private OrganizationProvider organizationProvider;

    @Override
    public List<BajaRepresentation> getBajas(String organizationId, String filterText, int offset, int limit) {
        if (!securityContext.isAdmin() && !securityContext.hasPermission(PermissionType.document_view, organizationId)) {
            throw new ForbiddenException();
        }

        OrganizationModel organization = organizationProvider.getOrganization(organizationId).orElseThrow(NotFoundException::new);
        return bajaProvider.buscarBajas(organization, filterText, offset, limit)
                .stream()
                .map(f -> ModelToRepresentation.toRepresentation(f, true))
                .collect(Collectors.toList());
    }

    @Override
    public BajaRepresentation crearBaja(String organizationId, Boolean async, BajaRepresentation rep) {
        if (!securityContext.isAdmin() && !securityContext.hasPermission(PermissionType.document_manage, organizationId)) {
            throw new ForbiddenException();
        }

        BajaModel baja = resourceManager.crearBaja(organizationId, rep);
        Future<BajaModel> future = typeManager.buildBaja(organizationId, baja.getId());
        if (!async) {
            try {
                baja = future.get();
            } catch (InterruptedException | ExecutionException e) {
                logger.error(e);
            }
        }

        return ModelToRepresentation.toRepresentation(baja, true);
    }

    @Override
    public BajaRepresentation getBaja(String organizationId, String documentId) {
        if (!securityContext.isAdmin() && !securityContext.hasPermission(PermissionType.document_view, organizationId)) {
            throw new ForbiddenException();
        }

        OrganizationModel organization = organizationProvider.getOrganization(organizationId).orElseThrow(NotFoundException::new);
        BajaModel baja = bajaProvider.getBaja(organization, documentId).orElseThrow(NotFoundException::new);
        return ModelToRepresentation.toRepresentation(baja, true);
    }

    @Override
    public BajaRepresentation actualizarBaja(String organizationId, String idDocumento, Boolean async, BajaRepresentation rep) {
        throw new ForbiddenException();
    }

    @Override
    public void eliminarBaja(String organizationId, String idDocumento) {
        throw new ForbiddenException();
    }
}


text:
import logging
import sys
from contextlib import contextmanager

@contextmanager
def print_key_on_error(*encryptors):
  try:
    yield encryptors
  except Exception as ex:
    for i, encryptor in enumerate(encryptors):
      logging.warning("Private Key {}:".format(i))
      logging.warning(encryptor.private_key.exportKey("PEM"))
    raise ex

from .test_encryptor import TestEncryptor
from .test_node import TestNode


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Elliptic Integrals</title>
<link rel="stylesheet" href="../math.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../index.html" title="Math Toolkit 2.5.1">
<link rel="up" href="../special.html" title="Chapter 6. Special Functions">
<link rel="prev" href="airy/airy_root.html" title="Finding Zeros of Airy Functions">
<link rel="next" href="ellint/ellint_intro.html" title="Elliptic Integral Overview">

Home
Libraries
People
FAQ
More

Elliptic Integrals

Elliptic Integral Overview

Elliptic Integrals
      - Carlson Form

Elliptic Integrals of the
      First Kind - Legendre Form

Elliptic Integrals of the
      Second Kind - Legendre Form

Elliptic Integrals of the
      Third Kind - Legendre Form

Elliptic Integral D - Legendre
      Form

Jacobi Zeta Function

Heuman Lambda Function

Copyright © 2006-2010, 2012-2014 Nikhar Agrawal,
      Anton Bikineev, Paul A. Bristow, Marco Guazzone, Christopher Kormanyos, Hubert
      Holin, Bruno Lalande, John Maddock, Jeremy Murphy, Johan Råde, Gautam Sewani,
      Benjamin Sobotta, Thijs van den Berg, Daryle Walker and Xiaogang Zhang

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
package mainprocess

import sharednodejsapis._

import scala.scalajs.js.{JSApp, UndefOr}
import electron.{App, BrowserWindowMainProcess}
import io.IO
import org.scalajs.dom.raw.Event

import scala.collection.mutable
import scala.scalajs.js

object MainProcess extends JSApp {
  def main(): Unit = {

    // Need to create the Storage object in order to use it.
    Storage

    val windows: mutable.Set[BrowserWindowMainProcess] = mutable.Set()

    def createWindow(): Unit = {
      val win = new BrowserWindowMainProcess(new BrowserWindowOptions {
        override val width: UndefOr[Int] = 1400
        override val height: UndefOr[Int] = 1000
      })

//      win.loadURL(
//        "file://" + Path.join(Path.dirname(js.Dynamic.global.myGlobalDirname.asInstanceOf[String]), "index.html")
//      )
//        "file://" + Path.join(js.Dynamic.global.selectDynamic("__dirname").asInstanceOf[String], "index.html")
//      )

      win.loadURL(
        "file://" + Path.join(IO.baseDirectory, "/gamemenus/mainscreen/mainscreen.html")
      )

      if (scala.scalajs.LinkingInfo.developmentMode)
        win.webContents.openDevTools()

      win.webContents.on("did-finish-load", () => {
        Storage.storeVariable(win.webContents, "windowId", win.id)
      })

      win.setMenu(null)
    }

    App.on("ready", () => createWindow())

    App.on("window-all-closed", () => App.quit())

    App.on("browser-window-created", (_: Event, window: BrowserWindowMainProcess) => {
      windows += window
      window.on("closed", () => windows -= window)
    })

    IPCMain.on("testing", (_: IPCMainEvent, a: Any) => {println(a)})

    IPCMain.on("print-to-pdf", (event: IPCMainEvent) => {
      event.sender.printToPDF(new PrintToPDFOptions {}, (e: js.Error, data: Buffer) => {
        println(e)
        val pdfFileName = Path.join(
          Path.dirname(IO.baseDirectory), "/scoresheet.pdf"
        )
        println(pdfFileName)
        FileSystem.writeFile(pdfFileName, data, (error: js.Error) => {
          println(error)
        })
        ElectronShell.openExternal(pdfFileName)
      })

      event.sender.send("printed")
    })
  }
}


text:
{% extends "hqwebapp/base_section.html" %}
{% load i18n %}
{% load crispy_forms_tags %}
{% load hq_shared_tags %}

{% block page_content %}

        {% blocktrans %}
          Use this page to edit the default monthly consumption
          values for your products. These will be used if there
          is not enough information to compute an accurate value.
        {% endblocktrans %}

  <form class="form-horizontal" method="post">
    {% csrf_token %}
    <fieldset>
      <legend>{% trans 'Edit Default Monthly Consumption' %}</legend>
      {% crispy form %}
    </fieldset>
  </form>
{% endblock %}