text:
#include "shelle.h"
#include "shellenvguid.h"

//
//  The shell running mode
//
CHAR16  *mShellMode[] = {
  EFI_SHELL_COMPATIBLE_MODE_VER,
  EFI_SHELL_ENHANCED_MODE_VER,
  NULL
};

typedef
EFI_STATUS
(*SPECIAL_VARIABLE_CHECK_FUNCTION) (
  IN CHAR16                                *Value,
  IN BOOLEAN                               Delete,
  IN BOOLEAN                               Volatile
  );

typedef
EFI_STATUS
(*SPECIAL_VARIABLE_GET_FUNCTION) (
  OUT CHAR16                           **Value
  );

typedef struct {
  CHAR16                          *CmdName;
  CHAR16                          *VarName;
  SPECIAL_VARIABLE_CHECK_FUNCTION SpecCheckFun;
  SPECIAL_VARIABLE_GET_FUNCTION   SpecGetFun;
} SPECIAL_VARIABLE_TABLE;

EFI_STATUS
SpecShellModeCheckFun (
  IN CHAR16                                *Value,
  IN BOOLEAN                               Delete,
  IN BOOLEAN                               Volatile
  );

EFI_STATUS
SpecShellModeGetFun (
  OUT CHAR16                               **Value
  );

SPECIAL_VARIABLE_TABLE  mSpecVarTable[] = {
  {
    L"set",
    L"efishellmode",
    SpecShellModeCheckFun,
    SpecShellModeGetFun
  },
  {
    NULL,
    NULL,
    NULL,
    NULL
  }
};

SHELL_VAR_CHECK_ITEM    VarCheckList[] = {
  {
    L"-d",
    0x01,
    0x02,
    FlagTypeSingle
  },
  {
    L"-v",
    0x02,
    0x01,
    FlagTypeSingle
  },
  {
    L"-b",
    0x04,
    0,
    FlagTypeSingle
  },
  {
    L"-?",
    0x08,
    0,
    FlagTypeSingle
  },
  {
    NULL,
    0,
    0,
    0
  }
};

//
// The different variable categories
//
EFI_LIST_ENTRY          SEnvEnv;
EFI_LIST_ENTRY          SEnvMap;
EFI_LIST_ENTRY          SEnvAlias;

VOID
SEnvInitVariables (
  VOID
  )
/*++

Routine Description:

Arguments:

Returns:

--*/
{
  CHAR16          *Name;
  CHAR16          *Data;
  UINTN           BufferSize;
  UINTN           NameSize;
  UINTN           DataSize;
  EFI_GUID        Id;
  EFI_LIST_ENTRY  *ListHead;
  VARIABLE_ID     *Var;
  EFI_STATUS      Status;
  BOOLEAN         IsString;
  UINT32          Attributes;

  //
  // Initialize the different variable lists
  //
  InitializeListHead (&SEnvEnv);
  InitializeListHead (&SEnvMap);
  InitializeListHead (&SEnvAlias);

  BufferSize  = 1024;
  Name        = AllocatePool (BufferSize);
  Data        = AllocatePool (BufferSize);
  ASSERT (Name && Data);

  Var = NULL;

  //
  // Read all the variables in the system and collect ours
  //
  Name[0] = 0;
  for (;;) {
    NameSize  = BufferSize;
    Status    = RT->GetNextVariableName (&NameSize, Name, &Id);
    if (EFI_ERROR (Status)) {
      break;
    }
    //
    // See if it's a shellenv variable
    //
    ListHead  = NULL;
    IsString  = FALSE;
    if (CompareGuid (&Id, &SEnvEnvId) == 0) {
      ListHead  = &SEnvEnv;
      IsString  = TRUE;
    }

    if (CompareGuid (&Id, &SEnvAliasId) == 0) {
      ListHead  = &SEnvAlias;
      IsString  = TRUE;
    }

    if (ListHead) {
      DataSize  = BufferSize;
      Status    = RT->GetVariable (Name, &Id, &Attributes, &DataSize, Data);

      if (!EFI_ERROR (Status)) {
        //
        // Add this value
        //
        SEnvAddVarToList (
          ListHead,
          Name,
          (UINT8 *) Data,
          DataSize,
          (BOOLEAN) ((Attributes & EFI_VARIABLE_NON_VOLATILE) == 0)
          );
      }
    }
    //
    // If this is a protocol entry, add it
    //
    if (CompareGuid (&Id, &SEnvProtId) == 0) {

      DataSize  = BufferSize;
      Status    = RT->GetVariable (Name, &Id, &Attributes, &DataSize, Data);

      if (!EFI_ERROR (Status) && DataSize == sizeof (EFI_GUID)) {
        SEnvIAddProtocol (FALSE, (EFI_GUID *) Data, NULL, NULL, Name);
      } else {
        DEBUG (
          (EFI_D_INIT | EFI_D_WARN,
          "SEnvInitVariables: skipping bogus protocol id %s\n",
          Var->Name)
          );
        RT->SetVariable (Name, &SEnvProtId, 0, 0, NULL);
      }
    }
  }

  FreePool (Name);
  FreePool (Data);
}

CHAR16 *
SEnvIGetStr (
  IN CHAR16           *Name,
  IN EFI_LIST_ENTRY   *Head
  )
/*++

Routine Description:

Arguments:

  Name - The variable name
  Head - The variable list
Returns:

--*/
{
  VARIABLE_ID *Var;
  CHAR16      *Value;

  AcquireLock (&SEnvLock);

  //
  // Walk through linked list to find corresponding Var
  //
  Value = NULL;
  Var   = SEnvFindVar (Head, Name);
  if (Var != NULL) {
    Value = Var->u.Str;
  }

  ReleaseLock (&SEnvLock);

  return Value;
}

CHAR16 *
EFIAPI
SEnvGetMap (
  IN CHAR16           *Name
  )
/*++

Routine Description:

Arguments:

  Name - The variable name

Returns:

--*/
{
  return SEnvIGetStr (Name, &SEnvMap);
}

CHAR16 *
EFIAPI
SEnvGetEnv (
  IN CHAR16           *Name
  )
/*++

Routine Description:

Arguments:

  Name - The variable name

Returns:

--*/
{
  UINTN       Index;
  CHAR16      *Str;
  EFI_STATUS  Status;

  for (Index = 0; mSpecVarTable[Index].CmdName != NULL; Index++) {
    if (StriCmp (mSpecVarTable[Index].CmdName, L"set") == 0 &&
        StriCmp (mSpecVarTable[Index].VarName, Name) == 0 &&
        mSpecVarTable[Index].SpecGetFun != NULL
        ) {
      Status = mSpecVarTable[Index].SpecGetFun (&Str);
      if (EFI_ERROR (Status)) {
        return NULL;
      }

      return Str;
    }
  }

  return SEnvIGetStr (Name, &SEnvEnv);
}

CHAR16 *
SEnvGetAlias (
  IN CHAR16           *Name
  )
/*++

Routine Description:

Arguments:

  Name - The variable name

Returns:

--*/
{
  return SEnvIGetStr (Name, &SEnvAlias);
}

VOID
SEnvSortVarList (
  IN EFI_LIST_ENTRY           *Head
  )
/*++

Routine Description:

Arguments:

  Head - The variable list head

Returns:

--*/
{
  ASSERT_LOCKED (&SEnvLock);

  return ;
}

VARIABLE_ID *
SEnvAddVarToList (
  IN EFI_LIST_ENTRY           *Head,
  IN CHAR16                   *Name,
  IN UINT8                    *Value,
  IN UINTN                    ValueSize,
  IN BOOLEAN                  Volatile
  )
/*++

Routine Description:

  Add a variable to the variable list

Arguments:
  Head        - The head of the variable list
  Name        - The name of the variable
  Value       - The value of the variable
  ValueSize   - The value size of the variable
  Volatile    - Indicate whether the variable is volatile

Returns:

--*/
{
  UINTN       Size;
  VARIABLE_ID *Var;

  Size  = sizeof (VARIABLE_ID) + StrSize (Name) + ValueSize;
  Var   = AllocateZeroPool (Size);
  if (Var == NULL) {
    return NULL;
  }

  Var->Signature  = VARIABLE_SIGNATURE;
  Var->u.Value    = ((UINT8 *) Var) + sizeof (VARIABLE_ID);
  Var->Name       = (CHAR16 *) (Var->u.Value + ValueSize);
  Var->ValueSize  = ValueSize;
  CopyMem (Var->u.Value, Value, ValueSize);
  StrCpy (Var->Name, Name);
  Var->Flags = (UINT8) (Volatile ? 0 : VAR_ID_NON_VOL);

  InsertTailList (Head, &Var->Link);
  return Var;
}

EFI_STATUS
SEnvAddVar (
  IN EFI_LIST_ENTRY           *Head,
  IN EFI_GUID                 *Guid,
  IN CHAR16                   *Name,
  IN UINT8                    *Value,
  IN UINTN                    ValueSize,
  IN BOOLEAN                  Volatile
  )
/*++

Routine Description:

  Add a variable to both the variable store and the variable list

Arguments:
  Head        - The head of the variable list
  Guid        - The GUID of the variable
  Name        - The name of the variable
  Value       - The value of the variable
  ValueSize   - The value size of the variable
  Volatile    - Indicate whether the variable is volatile

Returns:

--*/
{
  EFI_STATUS  Status;

  Status = RT->SetVariable (
                Name,
                Guid,
                EFI_VARIABLE_BOOTSERVICE_ACCESS | (Volatile ? 0 : EFI_VARIABLE_NON_VOLATILE),
                ValueSize,
                Value
                );

  if (!EFI_ERROR (Status)) {
    SEnvAddVarToList (Head, Name, Value, ValueSize, Volatile);
  }

  return Status;
}

VARIABLE_ID *
SEnvFindVar (
  IN EFI_LIST_ENTRY           *Head,
  IN CHAR16                   *Name
  )
/*++

Routine Description:

  Find the specified variable in the specified variable list

Arguments:
  Head        - The head of the variable list to find in
  Name        - The name of the variable to find

Returns:
  If not found, return NULL. Otherwise, return the pointer to the variable.

--*/
{
  EFI_LIST_ENTRY  *Link;
  VARIABLE_ID     *Var;
  VARIABLE_ID     *Found;

  Found = NULL;
  for (Link = Head->Flink; Link != Head; Link = Link->Flink) {
    Var = CR (Link, VARIABLE_ID, Link, VARIABLE_SIGNATURE);
    if (StriCmp (Var->Name, Name) == 0) {
      Found = Var;
      break;
    }
  }

  return Found;
}

EFI_STATUS
SEnvCmdGetStringByToken (
  IN     UINT16         Token,
  IN OUT CHAR16         **Str
  )
{
  EFI_STATUS  Status;
  CHAR16      *String;

  ASSERT (Str);
  *Str = NULL;
  Status = LibGetStringByToken (
            HiiEnvHandle,
            Token,
            NULL,
            &String
            );
  if (!EFI_ERROR (Status)) {
    *Str = String;
  }

  return Status;
}

EFI_STATUS
EFIAPI
SEnvCmdAliasGetLineHelp (
  IN OUT CHAR16         **Str
  )
/*++

Routine Description:

  Get this command's line help

Arguments:

  Str - The line help

Returns:

  EFI_SUCCESS   - Success

--*/
{
  return SEnvCmdGetStringByToken (STRING_TOKEN (STR_SHELLENV_ALIAS_LINE_HELP), Str);
}

EFI_STATUS
EFIAPI
SEnvCmdSetGetLineHelp (
  IN OUT CHAR16         **Str
  )
/*++

Routine Description:

  Get this command's line help

Arguments:

  Str - The line help

Returns:

  EFI_SUCCESS   - Success

--*/
{
  return SEnvCmdGetStringByToken (STRING_TOKEN (STR_SHELLENV_SET_LINE_HELP), Str);
}

BOOLEAN
_IsReserved (
  IN CHAR16                   *Name,
  IN CHAR16                   *Cmd
  )
{
  UINTN Index;

  for (Index = 0; mSpecVarTable[Index].CmdName != NULL; Index++) {
    if (!StriCmp (Cmd, mSpecVarTable[Index].CmdName) && !StriCmp (Name, mSpecVarTable[Index].VarName)) {
      return TRUE;
    }
  }

  return FALSE;
}

EFI_STATUS
SEnvCmdSA (
  IN EFI_HANDLE               ImageHandle,
  IN EFI_SYSTEM_TABLE         *SystemTable,
  IN EFI_LIST_ENTRY           *Head,
  IN EFI_GUID                 *Guid,
  IN CHAR16                   *CmdName,
  IN UINT16                   VHlpToken
  )
/*++

Routine Description:

  Code for shell "set" & "alias" command

Arguments:

  ImageHandle - The image handle
  SystemTable - The system table
  Head        - The variable list head
  Guid        - The guid
  CmdName     - The command name
  VHlpToken   - The help token

Returns:

--*/
{
  EFI_LIST_ENTRY          *Link;
  VARIABLE_ID             *Var;
  VARIABLE_ID             *Found;
  CHAR16                  *Name;
  CHAR16                  *Value;
  UINTN                   SLen;
  UINTN                   Len;
  BOOLEAN                 Delete;
  EFI_STATUS              Status;
  BOOLEAN                 Volatile;
  UINTN                   Index;
  SHELL_VAR_CHECK_CODE    RetCode;
  CHAR16                  *Useful;
  SHELL_VAR_CHECK_PACKAGE ChkPck;
  SHELL_ARG_LIST          *ArgItem;

  EFI_SHELL_APP_INIT (ImageHandle, SystemTable);

  Status = LibFilterNullArgs ();
  if (EFI_ERROR (Status)) {
    goto Quit;
  }

  ZeroMem (&ChkPck, sizeof (SHELL_VAR_CHECK_PACKAGE));
  ArgItem = NULL;

  RetCode = LibCheckVariables (SI, VarCheckList, &ChkPck, &Useful);
  if (VarCheckOk != RetCode) {
    switch (RetCode) {
    case VarCheckConflict:
      PrintToken (STRING_TOKEN (STR_SHELLENV_GNC_FLAG_CONFLICT), HiiEnvHandle, CmdName, Useful);
      break;

    case VarCheckDuplicate:
      PrintToken (STRING_TOKEN (STR_SHELLENV_GNC_DUP_FLAG), HiiEnvHandle, CmdName, Useful);
      break;

    case VarCheckUnknown:
      PrintToken (STRING_TOKEN (STR_SHELLENV_GNC_UNKNOWN_FLAG), HiiEnvHandle, CmdName, Useful);
      break;

    default:
      break;
    }

    Status = EFI_INVALID_PARAMETER;
    goto Quit;
  }
  //
  // Initializing variable to aVOID level 4 warning
  //
  Name      = NULL;
  Value     = NULL;
  Delete    = FALSE;
  Status    = EFI_SUCCESS;
  Found     = NULL;
  Var       = NULL;
  Volatile  = FALSE;

  //
  // Crack arguments
  //
  if (ChkPck.ValueCount > 2) {
    PrintToken (STRING_TOKEN (STR_SHELLENV_GNC_TOO_MANY), HiiEnvHandle, CmdName);
    Status = EFI_INVALID_PARAMETER;
    goto Quit;
  }

  if (LibCheckVarGetFlag (&ChkPck, L"-b") != NULL) {
    EnablePageBreak (DEFAULT_INIT_ROW, DEFAULT_AUTO_LF);
  }

  if (LibCheckVarGetFlag (&ChkPck, L"-?") != NULL) {
    if (IS_OLD_SHELL) {
      PrintToken (STRING_TOKEN (STR_NO_HELP), HiiEnvHandle);
      goto Quit;
    }

    if (ChkPck.ValueCount > 0 ||
        ChkPck.FlagCount > 2 ||
        (2 == ChkPck.FlagCount && !LibCheckVarGetFlag (&ChkPck, L"-b"))
        ) {
      PrintToken (STRING_TOKEN (STR_SHELLENV_GNC_TOO_MANY), HiiEnvHandle, CmdName);
      Status = EFI_INVALID_PARAMETER;
      goto Quit;
    }

    PrintToken (VHlpToken, HiiEnvHandle);
    Status = EFI_SUCCESS;
    goto Quit;
  }

  if (LibCheckVarGetFlag (&ChkPck, L"-d") != NULL) {
    if (ChkPck.ValueCount > 1) {
      PrintToken (STRING_TOKEN (STR_SHELLENV_GNC_TOO_MANY), HiiEnvHandle, CmdName);
      Status = EFI_INVALID_PARAMETER;
      goto Quit;
    } else if (ChkPck.ValueCount < 1) {
      PrintToken (STRING_TOKEN (STR_SHELLENV_GNC_TOO_FEW), HiiEnvHandle, CmdName);
      Status = EFI_INVALID_PARAMETER;
      goto Quit;
    }

    Delete = TRUE;
  }

  if (LibCheckVarGetFlag (&ChkPck, L"-v") != NULL) {
    if (ChkPck.ValueCount < 2) {
      PrintToken (STRING_TOKEN (STR_SHELLENV_GNC_TOO_FEW), HiiEnvHandle, CmdName);
      Status = EFI_INVALID_PARAMETER;
      goto Quit;
    }

    Volatile = TRUE;
  }

  ArgItem = GetFirstArg (&ChkPck);
  if (NULL != ArgItem) {
    if (SEnvGetCmdDispath (ArgItem->VarStr) && (StriCmp (CmdName, L"alias") == 0)) {
      PrintToken (STRING_TOKEN (STR_SHELLENV_VAR_INTERNAL_COMAMND), HiiEnvHandle, CmdName, ArgItem->VarStr);
      Status = EFI_INVALID_PARAMETER;
      goto Quit;
    } else if (StrSubCmp (L"*", ArgItem->VarStr, 1) == TRUE ||
             StrSubCmp (L"?", ArgItem->VarStr, 1) == TRUE ||
             StrSubCmp (L"<", ArgItem->VarStr, 1) == TRUE ||
             StrSubCmp (L">", ArgItem->VarStr, 1) == TRUE ||
             StrSubCmp (L"#", ArgItem->VarStr, 1) == TRUE ||
             StrSubCmp (L":", ArgItem->VarStr, 1) == TRUE ||
             StrSubCmp (L"^", ArgItem->VarStr, 1) == TRUE ||
             StrSubCmp (L"%", ArgItem->VarStr, 1) == TRUE ||
             StrSubCmp (L"/", ArgItem->VarStr, 1) == TRUE ||
             StrSubCmp (L"|", ArgItem->VarStr, 1) == TRUE ||
             StrSubCmp (L"\"", ArgItem->VarStr, 1) == TRUE
            ) {
      //
      // we donot allow *,?,<,>,#,:,^,%,/,|," in alias or variable name
      //
      PrintToken (STRING_TOKEN (STR_SHELLENV_GNC_INVALID_ARG), HiiEnvHandle, CmdName, ArgItem->VarStr);
      Status = EFI_INVALID_PARAMETER;
      goto Quit;
    } else {
      Name = ArgItem->VarStr;
    }

    ArgItem = GetNextArg (ArgItem);
  }

  if (NULL != ArgItem) {
    Value = ArgItem->VarStr;
  }

  if (Delete && Value) {
    PrintToken (STRING_TOKEN (STR_SHELLENV_GNC_TOO_MANY), HiiEnvHandle, CmdName);
    Status = EFI_INVALID_PARAMETER;
    goto Quit;
  }

  if (Name != NULL) {
    for (Index = 0; mSpecVarTable[Index].CmdName != NULL; Index++) {
      if (StriCmp (mSpecVarTable[Index].CmdName, CmdName) == 0 &&
          StriCmp (mSpecVarTable[Index].VarName, Name) == 0 &&
          mSpecVarTable[Index].SpecCheckFun != NULL
          ) {
        Status = mSpecVarTable[Index].SpecCheckFun (Value, Delete, Volatile);
        if (EFI_ERROR (Status)) {
          goto Quit;
        }
      }
    }
  }
  //
  // Process
  //
  AcquireLock (&SEnvLock);

  if (!Name) {
    //
    // dump the list
    //
    SEnvSortVarList (Head);

    SLen = 0;
    for (Link = Head->Flink; Link != Head; Link = Link->Flink) {
      Var = CR (Link, VARIABLE_ID, Link, VARIABLE_SIGNATURE);
      if (_IsReserved (Var->Name, CmdName)) {
        continue;
      }

      Len = StrLen (Var->Name);
      if (Len > SLen) {
        SLen = Len;
      }
    }

    for (Link = Head->Flink; Link != Head; Link = Link->Flink) {
      //
      // Break the execution?
      //
      if (GetExecutionBreak ()) {
        goto Done;
      }

      Var = CR (Link, VARIABLE_ID, Link, VARIABLE_SIGNATURE);
      if (_IsReserved (Var->Name, CmdName)) {
        continue;
      }

      if (Var->Flags & VAR_ID_NON_VOL) {
        PrintToken (
          STRING_TOKEN (STR_SHELLENV_VAR_DUMP_VAR_LIST),
          HiiEnvHandle,
          L' ',
          SLen,
          Var->Name,
          Var->u.Str
          );
      } else {
        PrintToken (
          STRING_TOKEN (STR_SHELLENV_VAR_DUMP_VAR_LIST),
          HiiEnvHandle,
          L'*',
          SLen,
          Var->Name,
          Var->u.Str
          );
      }
    }
  } else {
    //
    // Find the specified value
    //
    Found = SEnvFindVar (Head, Name);

    if (Found && Delete) {
      //
      // Remove it from the store
      //
      Status = RT->SetVariable (Found->Name, Guid, 0, 0, NULL);
      if (Status == EFI_NOT_FOUND) {
        PrintToken (
          STRING_TOKEN (STR_SHELLENV_VAR_NOT_FOUND),
          HiiEnvHandle,
          CmdName,
          Found->Name
          );
      }
    } else if (Value) {
      //
      // Add it to the store
      //
      if (Found && ((Volatile && (Found->Flags & VAR_ID_NON_VOL)) || (!Volatile && !(Found->Flags & VAR_ID_NON_VOL)))) {
        if (Found->Flags & VAR_ID_NON_VOL) {
          PrintToken (
            STRING_TOKEN (STR_SHELLENV_VAR_ALREADY_EXISTS_NONVOLATILE),
            HiiEnvHandle,
            CmdName,
            Found->Name
            );
        } else {
          PrintToken (
            STRING_TOKEN (STR_SHELLENV_VAR_ALREADY_EXISTS_VOLATILE),
            HiiEnvHandle,
            CmdName,
            Found->Name
            );
        }

        Found   = NULL;
        Status  = EFI_ACCESS_DENIED;
      } else {
        Status = SEnvAddVar (
                  Head,
                  Guid,
                  Found ? Found->Name : Name,
                  (UINT8 *) Value,
                  StrSize (Value),
                  Volatile
                  );
      }
    } else {
      if (Found) {
        if (Found->Flags & VAR_ID_NON_VOL) {
          PrintToken (
            STRING_TOKEN (STR_SHELLENV_VAR_DISPLAY_VAR),
            HiiEnvHandle,
            L' ',
            Found->Name,
            Found->u.Str
            );
        } else {
          PrintToken (
            STRING_TOKEN (STR_SHELLENV_VAR_DISPLAY_VAR),
            HiiEnvHandle,
            L'*',
            Found->Name,
            Found->u.Str
            );
        }
      } else {
        PrintToken (
          STRING_TOKEN (STR_SHELLENV_VAR_NOT_FOUND),
          HiiEnvHandle,
          CmdName,
          Name
          );
      }

      Found = NULL;
    }
    //
    // Remove the old in memory copy if there was one
    //
    if (Found && !EFI_ERROR (Status)) {
      RemoveEntryList (&Found->Link);
      FreePool (Found);
    }
  }

Done:
  ReleaseLock (&SEnvLock);
Quit:
  LibCheckVarFreeVarList (&ChkPck);
  return Status;
}

EFI_STATUS
EFIAPI
SEnvCmdSet (
  IN EFI_HANDLE               ImageHandle,
  IN EFI_SYSTEM_TABLE         *SystemTable
  )
/*++

Routine Description:

  Code for internal shell "set" command

Arguments:

  ImageHandle - The image handle
  SystemTable - The system table

Returns:

--*/
{
  //
  // Process 'set' command
  //
  return SEnvCmdSA (
          ImageHandle,
          SystemTable,
          &SEnvEnv,
          &SEnvEnvId,
          L"set",
          STRING_TOKEN (STR_SHELLENV_SET_VERBOSE_HELP)
          );
}

EFI_STATUS
EFIAPI
SEnvCmdAlias (
  IN EFI_HANDLE               ImageHandle,
  IN EFI_SYSTEM_TABLE         *SystemTable
  )
/*++

Routine Description:

  Code for internal shell "alias" command

Arguments:

  ImageHandle - The image handle
  SystemTable - The system table

Returns:

--*/
{
  //
  // Process 'alias' command
  //
  return SEnvCmdSA (
          ImageHandle,
          SystemTable,
          &SEnvAlias,
          &SEnvAliasId,
          L"alias",
          STRING_TOKEN (STR_SHELLENV_ALIAS_VERBOSE_HELP)
          );
}

EFI_STATUS
SEnvGetShellMode (
  OUT CHAR16       **Mode
  )
{
  if (Mode == NULL) {
    return EFI_INVALID_PARAMETER;
  }

  *Mode = SEnvGetEnv (L"efishellmode");
  return EFI_SUCCESS;
}

EFI_STATUS
SpecShellModeCheckFun (
  IN CHAR16                                *Value,
  IN BOOLEAN                               Delete,
  IN BOOLEAN                               Volatile
  )
{
  UINTN Index;
  if (Delete || !Volatile) {
    PrintToken (STRING_TOKEN (STR_SHELLENV_VAR_RESERVED), HiiEnvHandle, L"set", L"efishellmode");
    return EFI_INVALID_PARAMETER;
  }

  for (Index = 0; mShellMode[Index] != NULL; Index++) {
    if (StrCmp (mShellMode[Index], Value) == 0) {
      return EFI_SUCCESS;
    }
  }

  PrintToken (STRING_TOKEN (STR_SHELLENV_VAR_MODE_OPTIONS), HiiEnvHandle);
  for (Index = 0; mShellMode[Index] != NULL; Index++) {
    Print (mShellMode[Index]);
    Print (L"\n");
  }

  return EFI_INVALID_PARAMETER;
}

EFI_STATUS
SpecShellModeGetFun (
  OUT CHAR16                               **Value
  )
{
  UINTN Index;
  *Value = SEnvIGetStr (L"efishellmode", &SEnvEnv);
  if (*Value != NULL) {
    for (Index = 0; mShellMode[Index] != NULL; Index++) {
      if (StrCmp (mShellMode[Index], *Value) == 0) {
        return EFI_SUCCESS;
      }
    }
  }

  *Value = mShellMode[0];
  return EFI_SUCCESS;
}


text:
API improvements, particularly centred around simplifying common tasks
Added support for asynchronous IO within the IO type
Added support for forking and awaiting TPL tasks
Many performance optimisations
Documentation massively improved

#### 0.3.0-alpha - 12/07/2016
Added support for recursive PUs
Renamed Handles to Channels - part of wider API improvements
Added modules containing operations on each Channel type
Made a seperate operators module so that it can be opened independently
Misc performance improvements

#### 0.2.0-alpha - 12/06/2016
Added char PUs for fixed length string encodings
Redesigned the naming structure of big endian / little endian PUs to make them easier to work with
Made various improvements to the implementations of monadic functions in IO

#### 0.1.1-alpha - 22/05/2016
Removed test applications which should not be included

#### 0.1.0-alpha - 22/05/2016
Initial IO functionality created
Incorporated binary pickler with incremental and immediate execution
Strongly versioned dependencies
Updated documentation

#### 0.0.1-alpha - 28/02/2016
built initial documentation

redpajama_set_name: RedPajamaGithub


text:
using AutoMapper;
using Castle.Windsor;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using Statuos.Data;
using Statuos.Domain;
using Statuos.Service;
using Statuos.Web;
using Statuos.Web.Areas.Admin.Controllers;
using Statuos.Web.Infrastructure.AutoMapper.Profiles;
using Statuos.Web.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;

namespace Statuos.Test.Controllers.Admin
{
    [TestClass]
    public class ProjectControllerTests
    {
        private ProjectController controller;
        private Mock<IRepository<Project>> projectRepository;
        private Mock<IProjectService> projectService;
        private Mock<IRepository<Customer>> customerRepository;
        private int invalidProjectId = 11;
        private int validProjectId = 1;
        private BasicProject validProject;
        private BasicProjectViewModel projectViewModel;

        private Mock<IRepository<User>> userRepository;
        public ProjectControllerTests()
        {
            Mapper.AddProfile(new ProjectProfile());

            validProject = new BasicProject()
            {
                Id = 1,
                CustomerId = 1,
                EstimatedHours = 3.0M,
                Title = "New Project",
                ProjectManagerId = 1
            };

            projectViewModel = new BasicProjectViewModel() { UserName = "jdhall",
                Id=1,
                Title="Project View Model",
                CustomerId =1,
                EstimatedHours = 3.00M

            };

            projectService = new Mock<IProjectService>();
            projectRepository = new Mock<IRepository<Project>>();
            projectRepository.Setup(p => p.Find(invalidProjectId)).Returns((Project)null);
            projectRepository.Setup(p => p.Find(validProjectId)).Returns(validProject);
            customerRepository = new Mock<IRepository<Customer>>();
            userRepository = new Mock<IRepository<User>>();
            var users = new List<User> { new User() { Id = 1, UserName = "jdhall" } }.AsQueryable();
            userRepository.Setup(u => u.All).Returns(users);
            controller = new ProjectController(projectRepository.Object, projectService.Object, customerRepository.Object, userRepository.Object);

        }
        [TestMethod]
        public void RequestCreateNewBasicProjectReturnsCreateViewWithBasicViewModel()
        {
            var result = (ViewResult)controller.CreateProjectType(new BasicProjectViewModel());
            Assert.IsInstanceOfType(result.Model, typeof(BasicProjectViewModel));
        }

        [TestMethod]
        public void IndexGetsAllProjects()
        {
            var result = (ViewResult)controller.Index();
            projectRepository.Verify(r => r.All, Times.Once(), "All projects was not accessed");
        }

        [TestMethod]
        public void InvalidProjectIdDetailReturnsNotFound()
        {
            var result = controller.Details(invalidProjectId);
            Assert.IsInstanceOfType(result, typeof(HttpNotFoundResult));
        }

        [TestMethod]
        public void VaildProjectIdDetailReturnVaildProjectViewModel()
        {
            var result = (ViewResult)controller.Details(validProjectId);
            Assert.IsInstanceOfType(result.Model, typeof(BasicProjectViewModel));
        }

        [TestMethod]
        public void CreateProjectCallsProjectServiceAdd()
        {
            controller.Create(projectViewModel);
            projectService.Verify(p => p.Add(It.Is<Project>(pr => pr.Id ==projectViewModel.Id)));
        }

        [TestMethod]
        public void EditInvalidProjectIdReturnsNotFound()
        {
            var result = controller.Edit(invalidProjectId);
            Assert.IsInstanceOfType(result, typeof(HttpNotFoundResult));
        }

        [TestMethod]
        public void EditValidProjectIdReturnsViewResult()
        {
            var result = controller.Edit(validProjectId);
            Assert.IsInstanceOfType(result, typeof(ViewResult));
        }
        [TestMethod]
        public void EditCallsServiceEditFunctionOnProject()
        {
            var result = controller.Edit(projectViewModel);
            projectService.Verify(p => p.Edit(It.Is<Project>(pr => pr.Id == projectViewModel.Id)));
        }

        [TestMethod]
        public void DeleteInvalidProjectIdReturnsNotFound()
        {
            var result = controller.Delete(invalidProjectId);
            Assert.IsInstanceOfType(result, typeof(HttpNotFoundResult));
        }

        [TestMethod]
        public void DeleteValidProjectIdReturnsViewResult()
        {
            var result = controller.Delete(validProjectId);
            Assert.IsInstanceOfType(result, typeof(ViewResult));
        }

        [TestMethod]
        public void DeleteConfirmedInvalidProjectIdReturnsNotFound()
        {
            var result = controller.DeleteConfirmed(invalidProjectId);
            Assert.IsInstanceOfType(result, typeof(HttpNotFoundResult));
        }

        [TestMethod]
        public void DeleteConfirmedValidProjectIdCallsProjectServiceDeleteOnce()
        {
            var result = controller.DeleteConfirmed(validProjectId);
            projectService.Verify(p => p.Delete(validProject), Times.Once(), "Delete was not called once on project");
        }

        [TestMethod]
        public void CustomerViewBagSetupInCreateAction()
        {
            var result = (ViewResult)controller.CreateProjectType(projectViewModel);
            var selectList = (SelectList)result.ViewBag.Customers;
            var customers = selectList.Items;
            Assert.IsInstanceOfType(customers, typeof(List<Customer>));

        }
    }
}


text:
// Copyright 2009 the Sputnik authors.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/**
 * @name: S11.6.2_A3_T2.6;
 * @section: 11.6.2;
 * @assertion: Operator x - y returns ToNumber(x) - ToNumber(y);
 * @description: Type(x) is different from Type(y) and both types vary between String (primitive or object) and Undefined;
 */

//CHECK#1
if (isNaN("1" - undefined) !== true) {
  $ERROR('#1: "1" - undefined === Not-a-Number. Actual: ' + ("1" - undefined));
}

//CHECK#2
if (isNaN(undefined - "1") !== true) {
  $ERROR('#2: undefined - "1" === Not-a-Number. Actual: ' + (undefined - "1"));
}

//CHECK#3
if (isNaN(new String("1") - undefined) !== true) {
  $ERROR('#3: new String("1") - undefined === Not-a-Number. Actual: ' + (new String("1") - undefined));
}

//CHECK#4
if (isNaN(undefined - new String("1")) !== true) {
  $ERROR('#4: undefined - new String("1") === Not-a-Number. Actual: ' + (undefined - new String("1")));
}


text:
/*
 * @file Peer.h
 *
 * Contains the declaration of the class
 * Peer.
 */

#ifndef SPW_PEER_HPP_
#define SPW_PEER_HPP_

#include <cstdint>
#include <string>

#include "common.hpp"

namespace spw
{

/**
 * @class Peer
 * @brief Holds all information about a connected peers.
 *
 * Objects of the class TcpNode
 * can have multiple connections at the same time.
 * They use a vector of Peer objects to store
 * the information of all the currently connected peers.
 *
 * Each Peer object contains:
 * - A connection id
 * - The ip address of the peer.
 * - The port number the peer is using.
 * - The host name of the peer
 * - A valid flag, which indicates whether that
 *   particular Peer object was created properly.
 *   (Proper Peer objects can only be created by
 *    the TcpNode class)
 *
 * A Peer object can convert to bool. So
 * it can be used in a conditional:
 * Peer pr;
 * if(pr)
 * { ... }
 *
 * Peer objects evaluate to false when
 * they're not valid.
*/

class TcpNode;
class PeerPrivate;

#ifdef _WIN32
class DLL_IMPORT_EXPORT Peer
#else
class Peer
#endif
{

friend class TcpNode;
friend class TcpNodePrivate;

public:

    Peer();
    Peer(const Peer &other);
    Peer(Peer&& other);
    virtual ~Peer();

    virtual uint64_t id() const;
    virtual std::string ipAddress() const;
    virtual uint16_t port() const;
    virtual std::string hostName() const;
    virtual bool isValid() const;

    Peer& operator=(const Peer &other);
    bool operator==(const Peer &other) const;
    explicit operator bool() const;

private:

    mutable PeerPrivate *m_private = nullptr;
};

using PeerList = std::unordered_map<uint64_t, Peer>;

}

#endif /* SPW_PEER_HPP_ */


text:
package org.openkilda.persistence.context;

import org.openkilda.persistence.PersistenceImplementationType;

/**
 * Must be implemented by each {@link org.openkilda.persistence.PersistenceImplementation}. Aimed to store
 * implementation specific data (database connection etc).
 */
public interface PersistentContextExtension {
    PersistenceImplementationType getImplementationType();
}


text:
<?php
    ////////////////////////////////////////////////////////////
    /// \class Page
    ///
    /// \brief
    /// A Page is a class that inherits from the ApplicationComponent.
    /// The Page contains variables sent from the Controller to the View,
    /// and specific information about what is sent to the user.
    ////////////////////////////////////////////////////////////
    class Page extends ApplicationComponent
    {
        protected $m_filesToInclude = array();
        protected $m_contentFile;
        protected $m_vars = array();
		private $m_isAjaxPage = FALSE;

        ////////////////////////////////////////////////////////////
        /// \function addVar
        ///
        /// \brief
        /// Creates a new var passed to the View from the Controller
        ///
        /// \param var Name of the variable
        /// \param value Value of the variable
        ////////////////////////////////////////////////////////////
        public function addVar($var, $value)
        {
            if (!is_string($var) || is_numeric($var) || empty($var))
                throw new InvalidArgumentException('The name of the variable must be different than null');

            $this->m_vars[$var] = $value;
        }

        ////////////////////////////////////////////////////////////
        /// \function addFileToInclude
        ///
        /// \brief
        /// Registers which file must be included in the page
        ///
        /// \param filename Name of the file
        ////////////////////////////////////////////////////////////
        public function addFileToInclude($filename)
        {
            $this->m_filesToInclude[] = $filename;
        }

        ////////////////////////////////////////////////////////////
        /// \function getGeneratedPage
        ///
        /// \brief
        /// Returns the page once it is generated (ie: file included etc)
        /// \return Return of the output buffer
        ////////////////////////////////////////////////////////////
        public function getGeneratedPage()
        {
			if ($this->m_isAjaxPage)
				return '';

			if (!file_exists($this->m_contentFile))
                throw new RuntimeException('The needed view does not exist');

            $user = $this->app()->user();

            foreach($this->m_filesToInclude as $fileToInclude)
            {
				if(!empty($fileToInclude))
                    require $fileToInclude;
            }

            extract($this->m_vars);
            ob_start();
				require $this->m_contentFile;
            $content = ob_get_clean();

            ob_start();
				require dirname(__FILE__).'/../apps/'.$this->app()->name().'/templates/layout.php';
            return ob_get_clean();
        }

        public function setContentFile($contentFile)
        {
            if (!is_string($contentFile) || empty($contentFile))
                throw new InvalidArgumentException('The needed view is invalid');

            $this->m_contentFile = $contentFile;
        }

		public function setIsAjaxPage($value)
		{
			$this->m_isAjaxPage = $value;
		}
    }
?>


text:
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
import { PolygonMaskType } from "../Enums/PolygonMaskType";
import { Particle } from "./Particle";
import { PolygonMaskInlineArrangement } from "../Enums/PolygonMaskInlineArrangement";
import { Utils } from "./Utils/Utils";
export class PolygonMask {
    constructor(container) {
        this.container = container;
        this.width = 0;
        this.height = 0;
        this.polygonPathLength = 0;
        this.path2DSupported = window.hasOwnProperty("Path2D");
    }
    checkInsidePolygon(position) {
        const container = this.container;
        const options = container.options;
        if (!options.polygon.enable ||
            options.polygon.type === PolygonMaskType.none ||
            options.polygon.type === PolygonMaskType.inline) {
            return true;
        }
        if (!this.raw) {
            console.error('No polygon found, you need to specify SVG url in config.');
            return true;
        }
        const x = position ? position.x : Math.random() * container.canvas.dimension.width;
        const y = position ? position.y : Math.random() * container.canvas.dimension.height;
        let inside = false;
        if (this.path2DSupported && this.polygonPath && position) {
            inside = container.canvas.isPointInPath(this.polygonPath, position);
        }
        else {
            for (let i = 0, j = this.raw.length - 1; i < this.raw.length; j = i++) {
                const xi = this.raw[i].x;
                const yi = this.raw[i].y;
                const xj = this.raw[j].x;
                const yj = this.raw[j].y;
                const intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi);
                if (intersect) {
                    inside = !inside;
                }
            }
        }
        if (options.polygon.type === PolygonMaskType.inside) {
            return inside;
        }
        else if (options.polygon.type === PolygonMaskType.outside) {
            return !inside;
        }
        return false;
    }
    randomPointInPolygon() {
        const container = this.container;
        const options = container.options;
        let position;
        if (options.polygon.type === PolygonMaskType.inline) {
            switch (options.polygon.inline.arrangement) {
                case PolygonMaskInlineArrangement.randomPoint:
                    position = this.getRandomPointOnPolygonPath();
                    break;
                case PolygonMaskInlineArrangement.randomLength:
                    position = this.getRandomPointOnPolygonPathByLength();
                    break;
                case PolygonMaskInlineArrangement.equidistant:
                    position = this.getEquidistantPointOnPolygonPathByIndex(container.particles.count);
                    break;
                case PolygonMaskInlineArrangement.onePerPoint:
                default:
                    position = this.getPoingOnPolygonPathByIndex(container.particles.count);
            }
        }
        else {
            position = {
                x: Math.random() * container.canvas.dimension.width,
                y: Math.random() * container.canvas.dimension.height,
            };
        }
        if (this.checkInsidePolygon(position)) {
            return position;
        }
        else {
            return this.randomPointInPolygon();
        }
    }
    parseSvgPathToPolygon(svgUrl) {
        return __awaiter(this, void 0, void 0, function* () {
            const container = this.container;
            const options = container.options;
            const url = svgUrl || options.polygon.url;
            if (!this.path || !this.svg) {
                const req = yield fetch(url);
                if (req.ok) {
                    const xml = yield req.text();
                    const parser = new DOMParser();
                    const doc = parser.parseFromString(xml, "image/svg+xml");
                    this.svg = doc.getElementsByTagName("svg")[0];
                    this.path = doc.getElementsByTagName("path")[0];
                    if (this.path) {
                        this.polygonPathLength = this.path.getTotalLength();
                    }
                    this.createPath2D();
                }
                else {
                    console.error("tsParticles Error - during polygon mask download");
                    return;
                }
            }
            const scale = options.polygon.scale;
            this.width = parseFloat(this.svg.getAttribute("width") || "0") * scale;
            this.height = parseFloat(this.svg.getAttribute("height") || "0") * scale;
            this.offset = {
                x: container.canvas.dimension.width / 2 - this.width / 2,
                y: container.canvas.dimension.height / 2 - this.height / 2,
            };
            const len = this.path.pathSegList.numberOfItems;
            const polygonRaw = [];
            const p = {
                x: 0,
                y: 0,
            };
            for (let i = 0; i < len; i++) {
                const segment = this.path.pathSegList.getItem(i);
                switch (segment.pathSegType) {
                    case window.SVGPathSeg.PATHSEG_MOVETO_ABS:
                    case window.SVGPathSeg.PATHSEG_LINETO_ABS:
                    case window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_ABS:
                    case window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_ABS:
                    case window.SVGPathSeg.PATHSEG_ARC_ABS:
                    case window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_ABS:
                    case window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS:
                        const absSeg = segment;
                        p.x = absSeg.x;
                        p.y = absSeg.y;
                        break;
                    case window.SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_ABS:
                        p.x = segment.x;
                        break;
                    case window.SVGPathSeg.PATHSEG_LINETO_VERTICAL_ABS:
                        p.y = segment.y;
                        break;
                    case window.SVGPathSeg.PATHSEG_LINETO_REL:
                    case window.SVGPathSeg.PATHSEG_MOVETO_REL:
                    case window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_REL:
                    case window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_REL:
                    case window.SVGPathSeg.PATHSEG_ARC_REL:
                    case window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_REL:
                    case window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL:
                        const relSeg = segment;
                        p.x += relSeg.x;
                        p.y += relSeg.y;
                        break;
                    case window.SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_REL:
                        p.x += segment.x;
                        break;
                    case window.SVGPathSeg.PATHSEG_LINETO_VERTICAL_REL:
                        p.y += segment.y;
                        break;
                    case window.SVGPathSeg.PATHSEG_UNKNOWN:
                    case window.SVGPathSeg.PATHSEG_CLOSEPATH:
                        continue;
                }
                polygonRaw.push({
                    x: p.x * scale + this.offset.x,
                    y: p.y * scale + this.offset.y,
                });
            }
            return polygonRaw;
        });
    }
    drawPolygon() {
        const container = this.container;
        if (this.raw) {
            container.canvas.drawPolygonMask(this.raw);
        }
    }
    drawPointsOnPolygonPath() {
        const container = this.container;
        if (this.raw) {
            for (const item of this.raw) {
                const position = {
                    x: item.x,
                    y: item.y,
                };
                const particle = new Particle(container, position);
                container.particles.addParticle(particle);
            }
        }
    }
    getRandomPointOnPolygonPath() {
        if (!this.raw || !this.raw.length)
            throw new Error(`No polygon data loaded.`);
        const coords = Utils.itemFromArray(this.raw);
        return {
            x: coords.x,
            y: coords.y,
        };
    }
    getRandomPointOnPolygonPathByLength() {
        var _a, _b;
        const container = this.container;
        const options = container.options;
        if (!this.raw || !this.raw.length || !this.path)
            throw new Error(`No polygon data loaded.`);
        const distance = Math.floor(Math.random() * this.polygonPathLength) + 1;
        const point = this.path.getPointAtLength(distance);
        return {
            x: point.x * options.polygon.scale + (((_a = this.offset) === null || _a === void 0 ? void 0 : _a.x) || 0),
            y: point.y * options.polygon.scale + (((_b = this.offset) === null || _b === void 0 ? void 0 : _b.y) || 0),
        };
    }
    getEquidistantPointOnPolygonPathByIndex(index) {
        var _a, _b;
        const container = this.container;
        const options = container.options;
        if (!this.raw || !this.raw.length || !this.path)
            throw new Error(`No polygon data loaded.`);
        const distance = (this.polygonPathLength / options.particles.number.value) * index;
        const point = this.path.getPointAtLength(distance);
        return {
            x: point.x * options.polygon.scale + (((_a = this.offset) === null || _a === void 0 ? void 0 : _a.x) || 0),
            y: point.y * options.polygon.scale + (((_b = this.offset) === null || _b === void 0 ? void 0 : _b.y) || 0),
        };
    }
    getPoingOnPolygonPathByIndex(index) {
        if (!this.raw || !this.raw.length)
            throw new Error(`No polygon data loaded.`);
        const coords = this.raw[index % this.raw.length];
        return {
            x: coords.x,
            y: coords.y,
        };
    }
    createPath2D() {
        if (!this.path2DSupported || !this.raw) {
            return;
        }
        this.polygonPath = new Path2D();
        this.polygonPath.moveTo(this.raw[0].x, this.raw[0].y);
        this.raw.forEach((pos, i) => {
            var _a;
            if (i > 0) {
                (_a = this.polygonPath) === null || _a === void 0 ? void 0 : _a.lineTo(pos.x, pos.y);
            }
        });
        this.polygonPath.closePath();
    }
}
//# sourceMappingURL=PolygonMask.js.map


text:
<?php

namespace Codeages\Biz\Framework\Service;

use Codeages\Biz\Framework\Context\Biz;
use Codeages\Biz\Framework\Event\Event;
use Codeages\Biz\Framework\Service\Exception\AccessDeniedException;
use Codeages\Biz\Framework\Service\Exception\InvalidArgumentException;
use Codeages\Biz\Framework\Service\Exception\NotFoundException;
use Codeages\Biz\Framework\Service\Exception\ServiceException;
use Codeages\Biz\Framework\Validation\Validator;

abstract class BaseService
{
    protected $biz;

    public function __construct(Biz $biz)
    {
        $this->biz = $biz;
    }

    protected function dispatcher()
    {
        return $this->biz['dispatcher'];
    }

    protected function beginTransaction()
    {
        $this->biz['db']->beginTransaction();
    }

    protected function commit()
    {
        $this->biz['db']->commit();
    }

    protected function rollback()
    {
        $this->biz['db']->rollback();
    }

    protected function dispatch($eventName, $subject, $arguments = array())
    {
        if ($subject instanceof Event) {
            $event = $subject;
        } else {
            $event = new Event($subject, $arguments);
        }

        return $this->dispatcher()->dispatch($eventName, $event);
    }

    /**
     * @param string $message
     *
     * @return AccessDeniedException
     */
    protected function createAccessDeniedException($message = '')
    {
        return new AccessDeniedException($message);
    }

    /**
     * @param string $message
     *
     * @return InvalidArgumentException
     */
    protected function createInvalidArgumentException($message = '')
    {
        return new InvalidArgumentException($message);
    }

    /**
     * @param string $message
     *
     * @return NotFoundException
     */
    protected function createNotFoundException($message = '')
    {
        return new NotFoundException($message);
    }

    /**
     * @param string $message
     *
     * @return ServiceException
     */
    protected function createServiceException($message = '', $code = 0)
    {
        return new ServiceException($message, $code);
    }

    /**
     * @return Validator
     */
    protected function getValidator()
    {
        return $this->biz['validator'];
    }
}


text:
require "helper"

require "gapic/grpc/service_stub"

require "google/cloud/recommendation_engine/v1beta1/prediction_api_key_registry"

class ::Google::Cloud::RecommendationEngine::V1beta1::PredictionApiKeyRegistry::ClientPathsTest < Minitest::Test
  def test_event_store_path
    grpc_channel = ::GRPC::Core::Channel.new "localhost:8888", nil, :this_channel_is_insecure
    ::Gapic::ServiceStub.stub :new, nil do
      client = ::Google::Cloud::RecommendationEngine::V1beta1::PredictionApiKeyRegistry::Client.new do |config|
        config.credentials = grpc_channel
      end

      path = client.event_store_path project: "value0", location: "value1", catalog: "value2", event_store: "value3"
      assert_equal "projects/value0/locations/value1/catalogs/value2/eventStores/value3", path
    end
  end

  def test_prediction_api_key_registration_path
    grpc_channel = ::GRPC::Core::Channel.new "localhost:8888", nil, :this_channel_is_insecure
    ::Gapic::ServiceStub.stub :new, nil do
      client = ::Google::Cloud::RecommendationEngine::V1beta1::PredictionApiKeyRegistry::Client.new do |config|
        config.credentials = grpc_channel
      end

      path = client.prediction_api_key_registration_path project: "value0", location: "value1", catalog: "value2", event_store: "value3", prediction_api_key_registration: "value4"
      assert_equal "projects/value0/locations/value1/catalogs/value2/eventStores/value3/predictionApiKeyRegistrations/value4", path
    end
  end
end


text:
title: Ember Data v1.13 Released
author: Igor Terzic and the Ember Data Team
tags: Ember Data, 2015, Version 2.x
responsive: true
---

We are proud to announce the release of Ember Data 1.13. This
represents the first stable release of Ember Data since its creation
over 3 years ago.

As we explained in the [The Ember 2.x Project](http://emberjs.com/blog/2015/06/16/ember-project-at-2-0.html)
blog post, going forward Ember Data will be syncing up its releases and version numbers with Ember.js releases.

**Ember Data 1.13 is the first release of Ember Data that syncs its
  version with a version of Ember.js.** It will be followed by Ember Data 2.0, which will be released alongside Ember.js 2.0. **Ember Data 1.13 is fully backwards compatible with Ember Data beta.19, allowing for a smooth upgrade path.**

### Ember Data 1.13 Overview

Ember Data 1.13 is a massive release we are very proud of.
The highlight of the Ember Data 1.13 release is a total overhaul of Ember Data's internal format and Serializer API to follow JSON API.

Two years ago Tom Dale and Yehuda Katz [published](http://emberjs.com/blog/2013/05/03/ember-data-progress-update.html) a vision for how Ember Data should look in the future and articulated the need for a single, ubiquitous JSON API standard.

We are very happy to see the vision for that JSON API standard come to life in the form of the [JSON API 1.0 release](http://jsonapi.org).

JSON API and Ember Data have been intertwined since JSON API's inception.
[@dgeb](https://github.com/dgeb) gives the origins of JSON API in his [1.0 announcement](http://www.cerebris.com/blog/2015/06/04/jsonapi-1-0/):
> Yehuda Katz wrote the first draft of the JSON API specification in May 2013 after hammering out the details in a long discussion with Steve Klabnik at RailsConf. JSON API began as a codification of the shared expectations of a single server library for Rails, ActiveModel::Serializers, and a single JavaScript client library, Ember Data.

Ember Data has long supported JSON API through a community [adapter](https://github.com/kurko/ember-json-api) started by [@0x8890](https://twitter.com/0x8890) and maintained by [@kurko](https://github.com/kurko). However, now that JSON API has reached 1.0, it's time for Ember Data to uphold its part of the bargain and make using JSON API a first-class experience.

We have done exactly that, and Ember Data 1.13 adds support throughout the Ember Data stack for JSON API:

- **Ember Data 1.13 ships with a fully supported JSON API Adapter and Serializer.** In 2.0, these will become the default Adapter and Serializer.
- **`JSONSerializer` and `RESTSerializer` have been refactored and streamlined to return JSON API payloads.**
- **`store.push` now accepts JSON API compliant payload.**
- Ember Data `InvalidError` objects now accept JSON API error objects

Switching to the JSON API format unlocks many new features which will be added in the 2.0 cycle, including first-class pagination, filtering and metadata support.

While **using JSONSerializer, RESTSerializer and ActiveModelSerializer is not deprecated**, we consider JSON API to be the happiest of the happy paths for using Ember Data, and if you are creating a new app today and have control over the API you should be using JSON API, because it is a well designed and comprehensive solution for JSON serialization. **If your app is using the vanilla JSONSerializer or RESTSerializer, you will not have to make any changes, and your app will continue to work.** The existing serializers have been updated in a backwards compatible way to return JSON API data to the store.

Other major changes in Ember Data 1.13 include:

- [Refactored and simplified find methods](http://emberjs.com/blog/2015/06/18/ember-data-1-13-released.html#toc_simplified-find-methods)
- [Adapter level control for identity map caching](http://emberjs.com/blog/2015/06/18/ember-data-1-13-released.html#toc_new-adapter-hooks-for-better-caching)
- [Refactored and simplified Serializer APIs](http://emberjs.com/blog/2015/06/18/ember-data-1-13-released.html#toc_new-serializer-api-for-custom-serializer-authors)
- [Switch to using JSON API as the internal data storage format](http://emberjs.com/blog/2015/06/18/ember-data-1-13-released.html#toc_internal-format-change-to-json-api)
- [Native JSON API Serializer](http://emberjs.com/blog/2015/06/18/ember-data-1-13-released.html#toc_json-api-support)
- [Better error handling](http://emberjs.com/blog/2015/06/18/ember-data-1-13-released.html#toc_new-errors-api)

## Upgrade Guide

Ember Data 1.13 is backwards-compatible with previous beta versions, and there are no
breaking changes between Ember Data 1.13 and Ember Data beta.19. Ember Data follows Ember.js's lead in not removing any features in this release. The upgrade path should be familiar to Ember.js users: upgrade, remove deprecations, upgrade again.

**You should update your codebase to Ember Data 1.13, remove all the deprecations
and then move to Ember Data 2.0. It is critically important to do this process step by step**, as it will give you easy to follow deprecation warnings.
Otherwise, your app might fail in hard-to-debug ways.

If you have customized your serializer, you should upgrade to Ember Data 1.13,
check the upgrade guide to see if you need to make any changes, and then set a
temporary flag on your Serializer: `isNewSerializerAPI`. This will opt you into
the new serializer API. Once you are on the Ember Data 2.0 train, new Serializer API
is the default one, and there is no need for a flag.

We will be publishing a detailed step by step upgrade guide along with Ember.js
deprecations guides and [ember-watson](https://github.com/abuiles/ember-watson) helpers that will automatically upgrade some
of the deprecations for you.

## Release Logistics

**Ember Data 1.13 is the last release of Ember Data that supports IE8
  and the 1.x series of Ember.js. Ember Data 2.0-beta.1 will be released shortly, and it will follow the Ember.js release train.** Ember Data 2.0 will not work with the Ember.js 1.x series.

We would like to extend a special thanks to the many contributors who
have helped out with this release. We would also like to recognize the
following contributors who helped with multiple issues leading up to
this release. If you would like to help, please join #dev-ember-data in the
[Ember Community](https://ember-community-slackin.herokuapp.com/) on Slack.

- [@turbo87](https://github.com/turbo87)
- [@HeroicEric](https://github.com/HeroicEric)
- [@pangratz](https://github.com/pangratz)
- [@sly7-7](https://github.com/sly7-7)
- [@yratanov](https://github.com/yratanov)
- [@tchak](https://github.com/tchak)
- [@thaume](https://github.com/thaume)
- [@mikehollis](https://github.com/mikehollis)
- [@tricknotes](https://github.com/tricknotes)

We would also like to thank the companies which generously sponsored some of the work
that has gone into Ember Data:

- [DockYard](https://dockyard.com/)
- [Precision Nutrition](http://www.precisionnutrition.com/)
- [BookingSync](http://bookingsync.com)

As always this release can be obtained from npm (for
use with ember-cli), rubygems, or bower. The builds are also available
as static files at [http://emberjs.com/builds]().

## New Features

## Simplified Find Methods

Ember Data methods on the store have grown organically over the life
of the project. Originally, Ember Data started with `store.find(type)`
to request all records for a type and `store.find(type, id)` to
request a specific record. Later Ember Data added ways to issue a
query to the server via `store.find(type, {query})` or always reload a
record from the backend using `store.fetchById(type, id)` and
`store.fetchAll(type)`.

We realized the overloaded `store.find` method and inconsistent naming
of other methods is confusing for both new and existing developers. As a result, we have renamed many of the existing
store methods to make them more consistent and approachable for all
developers.

In particular, `store.find`, `store.all`, `store.getById` have been
deprecated and are replaced with consistently named methods. New methods follow a simple convention: If they are async and potentially go to the server, they start with `find`, and if they only get store local data without side-effects they start with `peek`.
If they return a single record they end in `Record` and if they return all the records they end in `All` .

#### Reorganized Find Methods

      Async from server/store
      Sync from store
      Query server

      Single Record
      findRecord(type,id)
      peekRecord(type, id)
      queryRecord(type, {query})

      All Records
      findAll(type)
      peekAll(type)
      query(type, {query})*

\* A query usually does not return all the records of a type, so doesn't end in `All`.

#### query and queryRecord

The final use case for the old `store.find` method was issuing queries
to the server. This usage of `store.find(type, { query })` has been
deprecated and replaced by a new `query` method
on the store.

```js
store.query(type, { query });
```

In addition to `store.query` we have also added a `queryRecord` for
issuing arbitrary queries to the backend where the expected response
is a single record.

```js
store.queryRecord(type, { query });
```

Thanks to [@thaume](http://github.com/thaume) for his work implementing this feature.

## Better Caching Defaults for `findAll` and `findRecord`

In Ember Data beta.19 calling `store.find(type, id)` would fetch the
fresh data from the server the first time find was called, and then every time after that
return cached data. If the user always needed fresh data, they had to
know to call `store.fetchRecord`, and if they needed to background update
they would have to make multiple calls and be careful about what they return from
a route's `model:` hook.

Calling `store.find(type)` had the exact opposite behavior, where it would
always go to the server, and the user had to know to use `store.all(type)`
to only use local data. Mimicking the caching behavior of `find(type, id)`
when using `find(type)` was not at all straightforward for new developers to write.

Having observed many Ember apps in the wild, we have realized that neither
of these two behaviors are the most common use case and deserving of being the default. The most commonly desired behavior we have seen in Ember apps is:

- First time `store.find` is called, fetch new data
- Next time return cached data
- Fetch new data in the background and update

This is the behavior of the new `findRecord` and `findAll` methods.

The first time you call `findRecord` and `findAll` they behave the same as
the old `find` method:

```js
//visiting /users/1 for the first time
model: function() {
  //We do not already have the user, so
  //store.findRecord returns a promise that resolves
  //after it has fetched the user from the server
  return this.store.findRecord('user', 1);
}
```

However if you already have the data cached locally, they resolve immediately
while fetching new data in the background:

```js
//visiting /users/1 for the second time
model: function() {
  //We already have the user, so store.findRecord
  //will resolve immediately with cached data, but will
  //send off a request in the background to update the user record
  //and once the user is updated your template will show the new changes
  return this.store.findRecord('user', 1);
}
```

While this is a great default data retrieval strategy, there are certain cases
where you want to ensure you have the freshest data (the old `store.fetch` behavior).

Because of that, `findRecord` and `findAll` accept `reload: true` an option in order to modify their default behavior.

If, for example you want to charge user for a purchase, and want to make sure you
get their latest account balance, you can pass a `reload: true` option that will
ensure we get the freshest data before continuing:

```js
//visiting /users/1/confirm-payment
model: function() {
  return this.store.findRecord('user', 1, { reload: true });
}
```

All of these behaviors are also shared by `findAll`:

```js
store.findAll('user');  //goes to the server the first time
store.findAll('user');  //after that returns from cache, but updates in background
store.findAll('user', { reload: true });  //enforces getting fresh data
```

#### `fetchById` and `fetchAll` Replaced by `findRecord` and `findAll`

Having these two methods, with customizable flags allows us to get rid of:
`store.fetchById` and `store.fetchAll`.

```js
store.fetchById(type, id) -> store.findRecord(type, id, { reload: true });
store.fetchAll(type, id) -> store.findAll(type, { reload: true });
```

### New Adapter Hooks for Better Caching

While `store.findRecord` and `store.findAll` now have sensible caching defaults
and are easy to override in specific places in the app, oftentimes your app and
adapter layer have specific knowledge related to caching. For example, your backend
might have given you an `expires` header, or you may not want to try fetching background updates if the network is down. To support these use cases, we have added new adapter
hooks to customize caching app wide beyond just passing options to `findRecord` and `findAll`.

Now, whenever you call `findRecord` or `findAll`, and the record is already cached in the store, the store will ask the adapter whether it needs to immediately reload it, or if it needs to update it in the background.

For example, if you are building an events ticketing system, in which users can only reserve tickets for 20 minutes at a time, and want to ensure that in each route you have data that is no more than 20 minutes old you could write:

```js
shouldReloadRecord: function(store, ticketSnapshot) {
  let timeDiff = moment().diff(ticketSnapshot.attr('lastAccessedAt')).minutes();
  if (timeDiff > 20) {
    return true;
  } else {
    return false;
  }
},
```

This method would ensure that whenever you do `findRecord('ticket')` you will
always get a ticket that is no more than 20 minutes old. In case the cached
version is more than 20 minutes old, `findRecord` will not resolve until you fetched
the latest version. By default this hook returns false, as most UIs should not block
user interactions while waiting on data update.

You can also customize whether you should try and do a background update. For example, if you do not want to fetch complex data over a mobile connection, or
if the network is down, you can implement `shouldBackgroundReloadRecord`

```js
shouldBackgroundReloadRecord: function(store, snapshot) {
  if (window.navigator.connection === 'cellular' ||
  	window.navigator.connection === 'none') {
  	return false;
  } else {
    return true;
  }
}
```

`Adapter#shouldBackgroundReloadRecord` is called by the store when the
store is resolving the `findRecord` promise with a cached record. If
this method returns `true` the store will attempt to reload the record
from the adapter in the background. The default implementation for
this method in Ember Data 1.13 is to always return `false`, in order
to ease the upgrade path. However in
Ember Data 2.0 this will be changed to always return `true`.

Symmetric methods have also been added for `store.findAll`.

```js
shouldReloadAll: function(store, snapshotRecordArray)
shouldBackgroundReloadAll: function(store, snapshotRecordArray)
```

[@eccegordo](https://github.com/eccegordo) put together this table
listing all the new store apis and the methods they replace.

      Ember beta.19
      Ember 1.13

      store.getById(type, id)
      store.peekRecord(type, id)

      store.all(type)
      store.peekAll(type)

      store.find(type, id)
      store.findRecord(type, id, options)

      store.find(type)
      store.findAll(type, options)

      N/A
      store.queryRecord(type, query)

      store.find(type, { query })
      store.query(type, query)

      store.fetch(type, id)
      store.findRecord(type, id, {reload: true})

## JSON API Support

### JSON API Adapter and Serializer

Ember Data 1.13 comes with support for [JSON API](http://jsonapi.org/)
1.0. There is a new `DS.JSONAPIAdapter` and `DS.JSONAPISerializer`
that support working with JSON API backends. In Ember Data 2.0 the
JSON API Adapter will be the default loaded by Ember Data.

### Internal Format Change to JSON API

In Ember Data beta.19, you communicated updates to the store by calling
`store.push(type, id)`. We have now changed `store.push` so it receives a
JSON API object, `store.push({JSON API compound document})`

For example

```js
store.push('user', { id: 1, name: 'Pangratz' });
```

becomes

```js
store.push({
  data: {
    id: '1',
    type: 'user',
    attributes: {
      name: 'Pangratz'
    }
  }
});
```

This allows for much better and fine grained meta handling, and ensures we do
not have to support, maintain and document a completely custom JSON format
as we had to until now, but can just reference the [JSON API specification](http://jsonapi.org/).

We will be publishing an [ember-watson](https://github.com/abuiles/ember-watson) helper that will be rewriting all the uses
of `store.push` inside your tests to the new format, as well as addon with helpers
that convert the old `store.push` format into the new format.

### New Serializer API for custom Serializer authors

If you made a `store.findRecord('user', 1)` request in Ember Data beta.19
and your server payload looked like:

```js
{
  user: { id: 1, name: 'wecc', accounts: [1, 2] },
  accounts: [
    { id: 1, email: 'wecc@sweden.se' },
    { id: 2, email: 'wecc@greece.gr' }
  ]
}
```

Your serializer would get the payload passed in an `extract` hook and its job was to:

- normalize and `store.push` everything that is not the `primary record`, in this
	case the array of sideloaded accounts
- normalize and return the primary data, in this case the `user` data

Having these two ways of pushing data to the store, with both returning primary record data
from `extract` hooks but also doing `store.push` with other data was both confusing,
hard to debug and optimize and also prevented us from implementing proper metadata support, especially for sideloaded arrays and records.

In Ember Data 1.13 this process has been greatly simplified. **In 1.13 Serializers
should just make the whole payload conform to the JSON API spec, and return the whole payload**. They should no longer `store.push` themselves.

In order to be backwards compatible, we created a new hook `normalizeResponse` which
Serializers should now implement, and just return JSON API from that hook.

For example a Serializer responsible for normalizing the above sample payload would just transform it to:

```js
{
  data: {
    id: '1',
    type: 'user',
    attributes: {
      name: 'wecc'
    },
    relationships: {
      accounts: {
        data: [
          { id: '1', type: 'account' },
          { id: '2', type: 'account' }
        ]
      }
    }
  },
  included: [{
    id: '1',
    type: 'account',
    attributes: {
      email: 'wecc@sweden.se'
    }
  }, {
    id: '2',
    type: 'account',
    attributes: {
      email: 'wecc@greece.gr'
    }
  }]
}
```

We will be posting a detailed Serializer transition guide shortly.

### New JSONSerializer and RESTSerializer API

As we rewrote JSONSerializer and RESTSerializer to implement the new
Serializer API we also simplified and greatly improved their own APIs.
Previously the possible places to modify a response for `store.find('user', 1)` were

- `extract`
- `extractFind`
- `extractSingle`
- `normalizePayload`
- `normalizeHash`
- `normalize`
- `extractMeta`
- `normalizeRelationships`
- `normalizeAttributes`

The new Serializer API allowed us to simplify these. If you receive a response
to `store.findRecord('user', 1)` in Ember Data 1.13 you can customize your response
in

- `normalizeResponse` - entry method to the Serializer and responsible for normalizing any response, gets the full payload, returns a JSON API compound document
- `normalizeFindRecordResponse` - a normalizeResponse for a specific operation
- `normalize` - normalizes data for a single record, returns a JSON API compound document
    - `extractId` | `extractAttributes` | `extractRelationships` - normalize delegates to these methods to extract the id, attributes and relationships from the payload. They receive the full payload for a single record and return the subsets of data for id, attributes and relationships, conforming to the JSON API specification.
- extractMeta - extracts the metadata for a payload

#### Transition to the new JSONSerializer and RESTSerializer APIs

If you have a custom serializer you will need to make some new changes
to your serializer to get it ready for Ember Data 2.0.

##### Custom `extract` Methods

If you have custom `extract` hooks you need to do two things:

First, rename:

- `extract()              => normalizeResponse()`
- `extractFindAll()       => normalizeFindAllResponse()`
- `extractFind()          => normalizeFindRecordResponse()`
- `extractFindMany()      => normalizeFindManyResponse()`
- `extractFindBelongsTo() => normalizeFindBelongsToResponse()`
- `extractFindHasMany()   => normalizeFindHasManyResponse()`
- `extractFindQuery()     => normalizeQueryResponse()`
- `extractQueryRecord()   => normalizeQueryRecordResponse()`
- `extractCreateRecord()  => normalizeCreateRecordResponse()`
- `extractDeleteRecord()  => normalizeDeleteRecordResponse()`
- `extractUpdateRecord()  => normalizeUpdateRecordResponse()`
- `extractSave()          => normalizeSaveResponse()`
- `extractSingle()        => normalizeSingleResponse()`
- `extractArray()         => normalizeArrayResponse()`

Second, make sure that your `extract` hooks return a full JSON API compound document
([http://jsonapi.org/format/#document-top-level](http://jsonapi.org/format/#document-top-level)) with the primary
resource(s) in a `data` array or object and eventual sideloaded
resources in a `included` array. Every resource object
([http://jsonapi.org/format/#document-resource-objects](http://jsonapi.org/format/#document-resource-objects)) has to
follow the JSON API format with `id`, `type`, attributes in
`attributes` and relationships in `relationships`. For the full
specification of the JSON API format see
[http://jsonapi.org/format/](http://jsonapi.org/format/).

##### Custom `extractMeta` Method

If you have a custom `extractMeta` method you have to make sure it
returns the meta data instead of calling `store.setMetadataFor()` (or
relying on `_super` to do so).

##### Custom `normalize` Method

If you have a custom `normalize()` method you need to update this to
return a full JSON API Document
([http://jsonapi.org/format/#document-top-level](http://jsonapi.org/format/#document-top-level)) with the primary
resource object
([http://jsonapi.org/format/#document-resource-objects](http://jsonapi.org/format/#document-resource-objects)) located in
`data`.

##### Opt Into the New Serializer API

To tell Ember Data that you are ready to use the new Serializer API,
add `isNewSerializerAPI: true` when extending `JSONSerializer` or
`RESTSerializer`. The new `JSONAPISerializer` uses the new Serializer
API by default. The `isNewSerializerAPI` flag is **only** required for
Ember Data 1.13 and will be removed in Ember Data 2.0. The new
`JSONAPISerializer` only supports the new Serializer API.

Thanks to [@wecc](https://github.com/wecc) for his hard work on
implementing this feature in a backwards compatible way.

We would also like thank [@kurko](https://github.com/kurko)
for his efforts maintaining the
[community JSON API adapter](https://github.com/kurko/ember-json-api).

## New Errors API

Similarly to the find APIs, our error handling APIs have grown over time,
and the switch to JSON API has given us a great opportunity for cleanup
and standardisation. [@tchak](https://twitter.com/tchak13) has done a great job rewriting our
Errors API to be JSON API compatible, while keeping backwards support for
REST/JSON/ActiveModel adapters. There are two main changes in Ember Data 1.13
error handling:

- Cleaner adapter hooks for errors
- Using JSON API Error object format

###Cleaner adapter hooks for errors

Previously, if you were subclassing the `RestAdapter` you could overwrite
`ajaxSuccess` and `ajaxError` hooks to implement custom error handling.
However, potential errors come in many flavors. For example, you could be receiving responses with a status code of `200` with the body of `{ error: error }`. In this case it was not intuitive to write error handling code in a method called `ajaxSuccess`. Because of this and many other examples, we realized that `ajaxSuccess` and `ajaxError` were not the
correct level at which to implement error handling.

 In Ember Data 1.13 we are introducing a new, simpler adapter hook:
`handleResponse` while deprecating `ajaxSuccess` and
`ajaxError`.

The responsibility of `handleResponse` is to take the returned status,
response headers and payload, and decide whether to pass the payload through as
a success, or to return an instance of `AdapterError` or `InvalidError`.

For example, if your API engineers for some unknown reason decided to return
`200 OK` with an error message, you could subclass your adapter to handle this:

```js
handleResponse: function(status, headers, payload) {
  if (status === 200 && payload.errors) {
    return new InvalidError(payload.errors);
  }
  return this._super(...arguments);
}
```

You could also subclass two helper methods, `isInvalid` and `isSuccess`
to customize when you adapter considers a request succesful or invalid.

Default implementation of `isInvalid` returns
true if http status code is `422`, however, you may desire other
semantics, for example checking the `code` property on a JSON API
error object.

This refactor also allows us to abstract away the jQuery `jqXHR` object, which
was tying Ember Data's Rest Adapter too closely with jQuery's implementation of ajax. New hooks take three arguments instead of `jqXHR`: status code, a hash of
response headers and parsed payload. It makes them agnostic about the
underlying implementation and will allow us to easily use methods like
[fetch](https://developers.google.com/web/updates/2015/03/introduction-to-fetch?hl=en)
in the future.

###Using JSON API Error object format
Similarly to the rest of Ember Data 1.13, we have refactored the error handling to use JSON API. JSON API has specified an
[error objects](http://jsonapi.org/format/#error-objects)
format. Starting with Ember Data 1.13 we are using JSON API format to
communicate errors from the adapter to the store.
We are deprecating the current Ruby on Rails inspired
format for creating `InvalidError` objects and replacing it with
proper JSON API objects. The old format is supported with a
deprecation warning in 1.13.

Deprecated format:

```js
new DS.InvalidError({
  first_name: ['is invalid']
});
```

New format:

```js
new DS.InvalidError([
  {
    source: { pointer: 'data/attributes/first_name' },
    detail: 'is invalid'
  }
]);
```

Thanks to [@tchak](https://github.com/tchak) and
[@twokul](https://github.com/twokul) for working on the design and
implementation of the new API.

## Significant Deprecations

In addition to new features, Ember Data 1.13 introduces deprecations for
features and behavior that will be removed in Ember Data 2.0.

### Async Relationships

In Ember Data 2.0 relationships will be asynchronous by default. Sync
relationships will still be supported but you will need to manually
opt into them by setting `{ async: false }` on your
relationships. Ember Data 1.13 will log a deprecation warning you if
you have any relationships where the `async` property is not
explicitly set. Additionally you can use
[ember-watson](https://github.com/abuiles/ember-watson) to help
identify cases in your codebase where you have relationships without
an explicit `async` property.

### DS.Store#filter Moved to an Addon

With Ember Data 2.0 and the commitment to semver we found we were not
happy with the state of the current `store.filter()` method. It
currently only supports a limited number of uses cases and often is a
source of memory leaks in long running applications. In order to give
Ember Data time to iterate on a better filter API the current
`store.filter` method has been deprecated and its functionality is
being moved into an addon
[https://github.com/ember-data/ember-data-filter/](https://github.com/ember-data/ember-data-filter).

In Ember 2.0, if you would like to use the current `store.filter`
method you will need to include the ember-data-filter addon with your
application.

### DS.ActiveModelAdapter Moved to an Addon

`DS.ActiveModelAdapter` and `DS.ActiveModelSerializer` has also been
[moved to an addon](https://github.com/ember-data/active-model-adapter). It
will continue to be supported by the Ember Data team, however, it will
no longer ship with Ember Data by default in Ember Data 2.0.

### Custom Stores

Over the years, Ember Data has supported a number of namespaces where
custom stores can be defined. In order to make things conceptually
simpler Ember Data 2.0 will require custom stores to be define as a
service.

If you have a custom store in your Ember CLI app defined in
`app/store.js` you will need to move it to `app/services/store.js`. If
you have a custom store in your globals app you will need to move it
to `App.StoreService`.

### JSON API Adapter Default

In Ember Data 2.0 the default adapter will be the `JSONAPIAdapter`. In
Ember Data 1.13 when loading the default `RESTAdapter` there will be a
deprecation warning.

To silence the warning and continue using the `RESTAdapter` you will
need to set the `RESTAdapter` as your application adapter.

```app/adapters/application.js
import DS from 'ember-data';

export default DS.RESTAdapter;
```

### `store.push` Changes

Previously, Ember Data allowed users to add a record to the store
using `store.push('model-name', {})`. This format has been deprecated
and now `store.push` will take a JSON API document as its first and
only argument. This new change will allow Ember Data to get better
performance in Ember Data 2.0 by deferring the creation of DS.Model
instances until they are needed by user code. `store.pushMany` has
also been deprecated because you can push multiple records using in a
JSON API document.

### `rollback` Renamed to `rollbackAttributes`

`record.rollback()` has been deprecated to
`record.rollbackAttributes()`. This new name more closely matches its
behavior and will allow for a new `record.rollback()` to be introduced
in the future that rolls back relationships in addition to attributes.

### `isDirty` Renamed to `hasDirtyAttributes`

`record.isDirty()` has been deprecated to
`record.hasDirtyAttributes()`. This new name more closely matches its
behavior and will allow for a new `record.hasDirtyRelationships()` to be introduced
in the future that allows you to check dirtiness of relationships.

### Preloading Record Data on Find

If you previously used the preload argument to `store.find` it has
been moved into the preload key on `findRecord`'s options argument

```js
// Deprecated
store.find('comment', 1, { post: 1 });

// Ember Data 1.13 style
store.findRecord('comment', 1, { preload: { post: 1 }});
```

## Changelog

[Ember Data 1.13](https://github.com/emberjs/data/blob/3bce36295a6e9f1bbe4824505046d22dc04d056d/CHANGELOG.md#release-113-june-16-2015)


text:
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
    if (kind === "m") throw new TypeError("Private method is not writable");
    if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
    if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
    return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
};
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
    if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
    if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
    return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var _Native_customPlayer;
class Native {
    constructor(element, media) {
        _Native_customPlayer.set(this, void 0);
        this.element = element;
        this.media = media;
        this.promise = new Promise((resolve) => {
            resolve();
        });
    }
    set instance(customPlayer) {
        __classPrivateFieldSet(this, _Native_customPlayer, customPlayer, "f");
    }
    get instance() {
        return __classPrivateFieldGet(this, _Native_customPlayer, "f");
    }
    play() {
        return this.element.play();
    }
    pause() {
        this.element.pause();
    }
    set volume(value) {
        this.element.volume = value;
    }
    get volume() {
        return this.element.volume;
    }
    set muted(value) {
        this.element.muted = value;
    }
    get muted() {
        return this.element.muted;
    }
    set playbackRate(value) {
        this.element.playbackRate = value;
    }
    get playbackRate() {
        return this.element.playbackRate;
    }
    set defaultPlaybackRate(value) {
        this.element.defaultPlaybackRate = value;
    }
    get defaultPlaybackRate() {
        return this.element.defaultPlaybackRate;
    }
    set currentTime(value) {
        this.element.currentTime = value;
    }
    get currentTime() {
        return this.element.currentTime;
    }
    get duration() {
        return this.element.duration;
    }
    get paused() {
        return this.element.paused;
    }
    get ended() {
        return this.element.ended;
    }
}
_Native_customPlayer = new WeakMap();
export default Native;


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using log4net;
using MindTouch.Deki.Data;
using MindTouch.Dream;
using MindTouch.Xml;

namespace MindTouch.Deki {
    public class ServiceRepository : IEnumerable<ServiceRepository.IServiceInfo> {

        //--- Types ---

        // Note (arnec): This is an interface so that ServiceInfo can be private and allow private access to its members by the repository
        public interface IServiceInfo {

            //--- Properties ---
            uint ServiceId { get; }
            XUri ServiceUri { get; }
            bool IsLocal { get; }
            bool IsExtensionService { get; }
            ExtensionInfo Extension { get; }
            string Namespace { get; }
        }

        private class ServiceInfo : IServiceInfo {

            //--- Fields ---
            private ExtensionInfo _extension;

            //--- Constructors ---
            public ServiceInfo(ServiceRepository owner, uint serviceId, XUri serviceUri, bool isLocal) {
                Owner = owner;
                ServiceId = serviceId;
                ServiceUri = serviceUri;
                IsLocal = isLocal;
            }

            //--- Properties ---
            public ServiceRepository Owner { get; private set; }
            public bool IsExtensionService { get { return Extension != null; } }
            public string Namespace { get; set; }
            public uint ServiceId { get; set; }
            public XUri ServiceUri { get; set; }
            public bool IsLocal { get; set; }

            public ExtensionInfo Extension {
                get {
                    if(_extension == null) {
                        _extension = new ExtensionInfo();
                        lock(Owner._servicesById) {
                            Owner._extensionServices.Add(this);
                        }
                    }
                    return _extension;
                }
            }
        }

        public class ExtensionInfo {

            //--- Fields ---
            private readonly Dictionary<string, string> _preferences = new Dictionary<string, string>();
            public IEnumerable<ExtensionFunctionInfo> Functions;
            public XDoc Manifest;
            public bool IsProtected;

            //--- Methods ---
            public void SetPreference(string key, string value) {
                if(string.IsNullOrEmpty(value)) {
                    return;
                }
                lock(_preferences) {
                    _preferences[key] = value;
                }
            }

            public string GetPreference(string key) {
                string value;
                _preferences.TryGetValue(key, out value);
                return value;
            }
        }

        public class ExtensionFunctionInfo {

            //--- Fields ---
            public readonly string Name;
            public readonly XUri Uri;

            //--- Constructors ---
            public ExtensionFunctionInfo(string name, XUri uri) {
                Name = name;
                Uri = uri;
            }
        }

        //--- Static Fields ---
        private static readonly ILog _log = LogUtils.CreateLog();

        //--- Fields ---

        // Note (arnec): Always lock on _servicesById before acccessing any of the lookups
        private readonly Dictionary<uint, ServiceInfo> _servicesById = new Dictionary<uint, ServiceInfo>();
        private readonly Dictionary<XUri, ServiceInfo> _servicesByUri = new Dictionary<XUri, ServiceInfo>();

        // Note (arnec): We store all services with the same namespace in the lookup, so that removal of one
        // automatically promotes the next as the one that can be looked up by name
        private readonly Dictionary<string, List<ServiceInfo>> _servicesByNamespace = new Dictionary<string, List<ServiceInfo>>();
        private readonly HashSet<ServiceInfo> _extensionServices = new HashSet<ServiceInfo>();

        // --- Properties ---
        public IServiceInfo this[string serviceNamespace] {
            get {
                lock(_servicesById) {
                    var info = GetNamespaceServices(serviceNamespace);
                    return info != null ? info.FirstOrDefault() : null;
                }
            }
        }

        public IServiceInfo this[uint serviceId] {
            get {
                lock(_servicesById) {
                    ServiceInfo info;
                    _servicesById.TryGetValue(serviceId, out info);
                    return info;
                }
            }
        }

        public IServiceInfo this[XUri serviceUri] {
            get {
                lock(_servicesById) {
                    ServiceInfo info;
                    _servicesByUri.TryGetValue(serviceUri, out info);
                    return info;
                }
            }
        }

        public IEnumerable<IServiceInfo> ExtensionServices {
            get {
                lock(_servicesById) {
                    return _extensionServices.ToArray();
                }
            }
        }

        //--- Methods ---
        public IServiceInfo RegisterService(ServiceBE service, XUri serviceUri, bool isLocal) {
            var serviceInfo = new ServiceInfo(this, service.Id, serviceUri, isLocal);
            lock(_servicesById) {
                _servicesById[service.Id] = serviceInfo;
                _servicesByUri[serviceUri] = serviceInfo;
                RegisterNamespace(serviceInfo, service.Preferences["namespace"]);
            }
            return serviceInfo;
        }

        public void RegisterNamespace(IServiceInfo serviceInfo, string serviceNamespace) {
            if(string.IsNullOrEmpty(serviceNamespace)) {
                return;
            }
            serviceNamespace = serviceNamespace.Trim();
            if(string.IsNullOrEmpty(serviceNamespace)) {
                return;
            }
            if(serviceNamespace.EqualsInvariant(serviceInfo.Namespace)) {
                return;
            }
            var info = serviceInfo as ServiceInfo;
            if(info == null || info.Owner != this) {
                _log.WarnFormat("The service {0} does not belong to this repository", serviceInfo);
                return;
            }
            lock(_servicesById) {
                if(!string.IsNullOrEmpty(info.Namespace)) {
                    var oldRegistration = GetNamespaceServices(info.Namespace);
                    if(oldRegistration != null) {
                        oldRegistration.Remove(info);
                        if(!oldRegistration.Any()) {
                            _servicesByNamespace.Remove(info.Namespace);
                        }
                    }
                }
                var newRegistration = GetNamespaceServices(serviceNamespace);
                if(newRegistration == null) {
                    newRegistration = new List<ServiceInfo>();
                    _servicesByNamespace[serviceNamespace] = newRegistration;
                }
                newRegistration.Add(info);
                newRegistration.Sort((x, y) => (int)((long)x.ServiceId - (long)y.ServiceId));
                info.Namespace = serviceNamespace;
            }
        }

        private List<ServiceInfo> GetNamespaceServices(string serviceNamespace) {

            // Note (arnec): assumes that method is always called in locked context
            List<ServiceInfo> info;
            _servicesByNamespace.TryGetValue(serviceNamespace, out info);
            return info;
        }

        public void DeregisterService(IServiceInfo serviceInfo) {
            lock(_servicesById) {
                _servicesById.Remove(serviceInfo.ServiceId);
                _servicesByUri.Remove(serviceInfo.ServiceUri);
                if(!string.IsNullOrEmpty(serviceInfo.Namespace)) {
                    var registration = GetNamespaceServices(serviceInfo.Namespace);
                    registration.Remove(serviceInfo as ServiceInfo);
                    if(!registration.Any()) {
                        _servicesByNamespace.Remove(serviceInfo.Namespace);
                    }
                }
                var info = serviceInfo as ServiceInfo;
                if(info != null) {
                    _extensionServices.Remove(info);
                }
            }
        }

        public void Clear() {
            lock(_servicesById) {
                _servicesById.Clear();
                _servicesByNamespace.Clear();
                _servicesByUri.Clear();
                _extensionServices.Clear();
            }
        }

        public IEnumerator<IServiceInfo> GetEnumerator() {
            lock(_servicesById) {
                return _servicesById.Values.Select(x => (IServiceInfo)x).ToList().GetEnumerator();
            }
        }

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


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Pilzkompendium (Eching) 1([2]): 432 (2001)

#### Original name
Omphalina albominutella E. Ludw.

### Remarks
null


text:
require 'adexchangeseller_common'

# The maximum number of results to be returned in a page.
MAX_PAGE_SIZE = 50

def get_all_ad_clients(adexchangeseller)
  request = adexchangeseller.adclients.list(:maxResults => MAX_PAGE_SIZE)

  loop do
    result = request.execute

    result.data.items.each do |ad_client|
      puts 'Ad client for product "%s" with ID "%s" was found.' %
        [ad_client.productCode, ad_client.id]

      puts '  Supports reporting: %s' %
        (ad_client.supportsReporting ? 'Yes' : 'No')
    end

    break unless result.next_page_token
    request = result.next_page
  end
end

if __FILE__ == $0
  adexchangeseller = service_setup()
  get_all_ad_clients(adexchangeseller)
end


text:
class ServiceTicket < ActiveRecord::Base
  set_table_name "casfuji_st"

  # Mixin module behaviors
  include Consumable
  include Ticket

  def consumed?
    not self.consumed.nil?
  end

  def service_valid?(service)
    self.service == CGI.escape(service)
  end

  def self.generate(service, permanent_id, client_hostname)
    ServiceTicket.create(:name            => self.unique_ticket_name('ST'),
                         :permanent_id    => permanent_id,
                         :service         => service,
                         :client_hostname => client_hostname)
  end
end


text:
layout: default
---

{% include site-header.html %}

{{ page.title }}

			{{ content }}

		{% include post-categories.html %}

	{% include site-aside.html %}

{% include returntotop_button.html %}

{% include site-footer.html %}


text:
dotfilespath="$HOME/dotfiles"

if [ "$(uname)" != "Darwin" ]; then
    curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > microsoft.gpg
    mv microsoft.gpg /etc/apt/trusted.gpg.d/microsoft.gpg
    sh -c 'echo "deb [arch=amd64] https://packages.microsoft.com/repos/vscode stable main" > /etc/apt/sources.list.d/vscode.list'
    apt-get update
    apt-get install code
fi

if [ "$(uname)" != "Linux" ]; then
    rm -rf ~/Library/Application\ Support/Code/User/snippets
    ln -sf "$dotfilespath/vscode/settings.json" ~/Library/Application\ Support/Code/User/settings.json
    ln -sf "$dotfilespath/vscode/keybindings.json" ~/Library/Application\ Support/Code/User/keybindings.json
    ln -sf "$dotfilespath/vscode/snippets/" ~/Library/Application\ Support/Code/User/snippets
fi