text:
<?php session_start(); ?>
<!DOCTYPE html>

        <title>Guess My Number</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="keyword" content="PHP, 'Guess My Number', 'Github Project', ConsonanceNg">
        <meta name="description" content="This PHP program enables the user to guess the number generated by the computer">
        <meta name="author" content="Moses Ajireloja">
        <link rel="stylesheet" href="style.css" type="text/css" media="all">

GUESS MY NUMBER

Welcome to this platform. The computer will generate a number between 1 and 100.
        Can you guess what the number is? Let the game begin!

            <form action="index.php" method="post" class="form">
                Enter Your Number:
                <input type="number" name="figure" min="1" max="100" required="required" title="Enter a number between 1 and 100">

                <input type="submit" name="submit" value="Submit and Check" class="button">
                <input type="reset" name="Reset"  value="Reset Number" class="button">
            </form>

        <?php
          // The computer generates a number and stores it in session.
                    if (!isset($_SESSION['compfigure']) || empty($_SESSION['compfigure'])) {
                        $compfigure = rand(1, 100);
                        $_SESSION['compfigure'] = $compfigure;
                    }
                    else {
                        $compfigure = "{$_SESSION['compfigure']}";
                    }

        // Validate the user's input and compare the user's input with the generated number.
            if (isset($_POST['submit'])) {
                // Ensure that a number has been entered.
                if (isset($_POST['figure']) && !empty($_POST['figure']) && is_numeric($_POST['figure'])) {

                    // Then obtain the user's number.
                    $figure = htmlentities(trim($_POST['figure']));

                    if ($figure > 0 && $figure < 101) {

                    // This is the computer's number
                       // echo $compfigure;

                    // Display this if the user's number is lower than the generated number.
                    if ($figure < $compfigure) {
                          echo "
Hmm... You're almost there! Try a higher number.
";
                          echo "
" . "Your Guess: {$figure}" . "
";
                          echo "
" . "Computer's number is greater than {$figure}." . "
";
                          echo "
" . "Please try again." . "
";
                    }
                    // Display this if the user's number is greater than the generated number.
                    if ($figure > $compfigure) {
                          echo "
Oh... That number is too high! Try a lower one.
";
                          echo "
" . "Your Guess: {$figure}" . "
";
                          echo "
" . "Computer's number is less than {$figure}." . "
";
                          echo "
" . "Please try again." . "
";
                    }

                    if ($figure == $compfigure) {
                          echo "
Awesome! You deserve a round of applause.
";
                          echo "
" . "Your Guess: {$figure}" . "
";
                          echo "
" . "Computer's Number: {$compfigure}" . "
";
                          echo "
" . "Remark: Accurate Guess!" . "
";
                          echo "START AGAIN";
                    }

                } else {
                    // The number must be between 1 and 100.
                    echo "
Sorry, something went wrong.
";
                    echo "
Please enter a number that is a minimum of 1 and maximum of 100.
";
                    echo "
Thank you.
";
                }

                }
                else {
                    // Notify user to enter a value and then submit.
                    echo "
Sorry, something went wrong.
";
                    echo "
Please enter a valid number.
";
                    echo "
Thank you.
";
                }
            }
        ?>


text:
using base::win::RegKey;

namespace {

// This class represents a single registry entry. The objective is to
// encapsulate all the registry entries required for registering Chrome at one
// place. This class can not be instantiated outside the class and the objects
// of this class type can be obtained only by calling a static method of this
// class.
class RegistryEntry {
 public:
  // This method returns a list of all the registry entries that
  // are needed to register Chromium ProgIds.
  static bool GetProgIdEntries(BrowserDistribution* dist,
                               const std::wstring& chrome_exe,
                               const std::wstring& suffix,
                               std::list<RegistryEntry*>* entries) {
    std::wstring icon_path = ShellUtil::GetChromeIcon(dist, chrome_exe);
    std::wstring open_cmd = ShellUtil::GetChromeShellOpenCmd(chrome_exe);

    // File association ProgId
    std::wstring chrome_html_prog_id(ShellUtil::kRegClasses);
    file_util::AppendToPath(&chrome_html_prog_id, ShellUtil::kChromeHTMLProgId);
    chrome_html_prog_id.append(suffix);
    entries->push_front(new RegistryEntry(
        chrome_html_prog_id, ShellUtil::kChromeHTMLProgIdDesc));
    entries->push_front(new RegistryEntry(
        chrome_html_prog_id, ShellUtil::kRegUrlProtocol, L""));
    entries->push_front(new RegistryEntry(
        chrome_html_prog_id + ShellUtil::kRegDefaultIcon, icon_path));
    entries->push_front(new RegistryEntry(
        chrome_html_prog_id + ShellUtil::kRegShellOpen, open_cmd));

    return true;
  }

  // This method returns a list of all the system level registry entries that
  // are needed to register Chromium on the machine.
  static bool GetSystemEntries(BrowserDistribution* dist,
                               const std::wstring& chrome_exe,
                               const std::wstring& suffix,
                               std::list<RegistryEntry*>* entries) {
    std::wstring icon_path = ShellUtil::GetChromeIcon(dist, chrome_exe);
    std::wstring quoted_exe_path = L"\"" + chrome_exe + L"\"";

    std::wstring app_name = dist->GetApplicationName() + suffix;
    std::wstring start_menu_entry(ShellUtil::kRegStartMenuInternet);
    start_menu_entry.append(L"\\" + app_name);
    entries->push_front(new RegistryEntry(start_menu_entry, app_name));
    entries->push_front(new RegistryEntry(
        start_menu_entry + ShellUtil::kRegShellOpen, quoted_exe_path));
    entries->push_front(new RegistryEntry(
        start_menu_entry + ShellUtil::kRegDefaultIcon, icon_path));

    std::wstring install_info(start_menu_entry + L"\\InstallInfo");
    // TODO: use CommandLine API instead of constructing command lines.
    entries->push_front(new RegistryEntry(install_info, L"ReinstallCommand",
        quoted_exe_path + L" --" + ASCIIToWide(switches::kMakeDefaultBrowser)));
    entries->push_front(new RegistryEntry(install_info, L"HideIconsCommand",
        quoted_exe_path + L" --" + ASCIIToWide(switches::kHideIcons)));
    entries->push_front(new RegistryEntry(install_info, L"ShowIconsCommand",
        quoted_exe_path + L" --" + ASCIIToWide(switches::kShowIcons)));
    entries->push_front(new RegistryEntry(install_info, L"IconsVisible", 1));

    std::wstring capabilities(start_menu_entry + L"\\Capabilities");
    entries->push_front(new RegistryEntry(ShellUtil::kRegRegisteredApplications,
        app_name, capabilities));
    entries->push_front(new RegistryEntry(
        capabilities, L"ApplicationDescription",
        dist->GetLongAppDescription()));
    entries->push_front(new RegistryEntry(
        capabilities, L"ApplicationIcon", icon_path));
    entries->push_front(new RegistryEntry(
        capabilities, L"ApplicationName", app_name));

    entries->push_front(new RegistryEntry(capabilities + L"\\StartMenu",
        L"StartMenuInternet", app_name));

    std::wstring html_prog_id(ShellUtil::kChromeHTMLProgId);
    html_prog_id.append(suffix);
    for (int i = 0; ShellUtil::kFileAssociations[i] != NULL; i++) {
      entries->push_front(new RegistryEntry(
          capabilities + L"\\FileAssociations",
          ShellUtil::kFileAssociations[i], html_prog_id));
    }
    for (int i = 0; ShellUtil::kProtocolAssociations[i] != NULL; i++) {
      entries->push_front(new RegistryEntry(
          capabilities + L"\\URLAssociations",
          ShellUtil::kProtocolAssociations[i], html_prog_id));
    }

    FilePath chrome_path(chrome_exe);
    std::wstring app_path_key(ShellUtil::kAppPathsRegistryKey);
    file_util::AppendToPath(&app_path_key, chrome_path.BaseName().value());
    entries->push_front(new RegistryEntry(app_path_key, chrome_exe));
    entries->push_front(new RegistryEntry(app_path_key,
        ShellUtil::kAppPathsRegistryPathName, chrome_path.DirName().value()));

    // TODO: add chrome to open with list (Bug 16726).
    return true;
  }

  // This method returns a list of all the user level registry entries that
  // are needed to make Chromium default browser.
  static bool GetUserEntries(BrowserDistribution* dist,
                             const std::wstring& chrome_exe,
                             const std::wstring& suffix,
                             std::list<RegistryEntry*>* entries) {
    // File extension associations.
    std::wstring html_prog_id(ShellUtil::kChromeHTMLProgId);
    html_prog_id.append(suffix);
    for (int i = 0; ShellUtil::kFileAssociations[i] != NULL; i++) {
      std::wstring ext_key(ShellUtil::kRegClasses);
      file_util::AppendToPath(&ext_key, ShellUtil::kFileAssociations[i]);
      entries->push_front(new RegistryEntry(ext_key, html_prog_id));
    }

    // Protocols associations.
    std::wstring chrome_open = ShellUtil::GetChromeShellOpenCmd(chrome_exe);
    std::wstring chrome_icon = ShellUtil::GetChromeIcon(dist, chrome_exe);
    for (int i = 0; ShellUtil::kProtocolAssociations[i] != NULL; i++) {
      std::wstring url_key(ShellUtil::kRegClasses);
      file_util::AppendToPath(&url_key, ShellUtil::kProtocolAssociations[i]);

      // <root hkey>\Software\Classes\<protocol>\DefaultIcon
      std::wstring icon_key = url_key + ShellUtil::kRegDefaultIcon;
      entries->push_front(new RegistryEntry(icon_key, chrome_icon));

      // <root hkey>\Software\Classes\<protocol>\shell\open\command
      std::wstring shell_key = url_key + ShellUtil::kRegShellOpen;
      entries->push_front(new RegistryEntry(shell_key, chrome_open));

      // <root hkey>\Software\Classes\<protocol>\shell\open\ddeexec
      std::wstring dde_key = url_key + L"\\shell\\open\\ddeexec";
      entries->push_front(new RegistryEntry(dde_key, L""));

      // <root hkey>\Software\Classes\<protocol>\shell\@
      std::wstring protocol_shell_key = url_key + ShellUtil::kRegShellPath;
      entries->push_front(new RegistryEntry(protocol_shell_key, L"open"));
    }

    // start->Internet shortcut.
    std::wstring start_menu(ShellUtil::kRegStartMenuInternet);
    std::wstring app_name = dist->GetApplicationName() + suffix;
    entries->push_front(new RegistryEntry(start_menu, app_name));
    return true;
  }

  // Generate work_item tasks required to create current registry entry and
  // add them to the given work item list.
  void AddToWorkItemList(HKEY root, WorkItemList *items) const {
    items->AddCreateRegKeyWorkItem(root, _key_path);
    if (_is_string) {
      items->AddSetRegValueWorkItem(root, _key_path, _name, _value, true);
    } else {
      items->AddSetRegValueWorkItem(root, _key_path, _name, _int_value, true);
    }
  }

  // Checks if the current registry entry exists in HKLM registry and the value
  // is same.
  bool ExistsInHKLM() const {
    RegKey key(HKEY_LOCAL_MACHINE, _key_path.c_str(), KEY_READ);
    bool found = false;
    if (_is_string) {
      std::wstring read_value;
      found = (key.ReadValue(_name.c_str(), &read_value) == ERROR_SUCCESS) &&
              (read_value.size() == _value.size()) &&
              (std::equal(_value.begin(), _value.end(), read_value.begin(),
                          base::CaseInsensitiveCompare<wchar_t>()));
    } else {
      DWORD read_value;
      found = (key.ReadValueDW(_name.c_str(), &read_value) == ERROR_SUCCESS) &&
              (read_value == _int_value);
    }
    key.Close();
    return found;
  }

  // Checks if the current registry entry exists in HKLM registry
  // (only the name).
  bool NameExistsInHKLM() const {
    RegKey key(HKEY_LOCAL_MACHINE, _key_path.c_str(), KEY_READ);
    bool found = false;
    if (_is_string) {
      std::wstring read_value;
      found = key.ReadValue(_name.c_str(), &read_value) == ERROR_SUCCESS;
    } else {
      DWORD read_value;
      found = key.ReadValueDW(_name.c_str(), &read_value) == ERROR_SUCCESS;
    }
    key.Close();
    return found;
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(RegistryEntry);

  // Create a object that represent default value of a key
  RegistryEntry(const std::wstring& key_path, const std::wstring& value)
      : _key_path(key_path), _name(),
        _is_string(true), _value(value), _int_value(0) {
  }

  // Create a object that represent a key of type REG_SZ
  RegistryEntry(const std::wstring& key_path, const std::wstring& name,
                const std::wstring& value)
      : _key_path(key_path), _name(name),
        _is_string(true), _value(value), _int_value(0) {
  }

  // Create a object that represent a key of integer type
  RegistryEntry(const std::wstring& key_path, const std::wstring& name,
                DWORD value)
      : _key_path(key_path), _name(name),
        _is_string(false), _value(), _int_value(value) {
  }

  std::wstring _key_path;  // key path for the registry entry
  std::wstring _name;      // name of the registry entry
  bool _is_string;         // true if current registry entry is of type REG_SZ
  std::wstring _value;     // string value (useful if _is_string = true)
  DWORD _int_value;        // integer value (useful if _is_string = false)
};  // class RegistryEntry

// This method converts all the RegistryEntries from the given list to
// Set/CreateRegWorkItems and runs them using WorkItemList.
bool AddRegistryEntries(HKEY root, const std::list<RegistryEntry*>& entries) {
  scoped_ptr<WorkItemList> items(WorkItem::CreateWorkItemList());

  for (std::list<RegistryEntry*>::const_iterator itr = entries.begin();
       itr != entries.end(); ++itr)
    (*itr)->AddToWorkItemList(root, items.get());

  // Apply all the registry changes and if there is a problem, rollback
  if (!items->Do()) {
    items->Rollback();
    return false;
  }
  return true;
}

// This method checks if Chrome is already registered on the local machine.
// It gets all the required registry entries for Chrome and then checks if
// they exist in HKLM. Returns true if all the entries exist, otherwise false.
bool IsChromeRegistered(BrowserDistribution* dist,
                        const std::wstring& chrome_exe,
                        const std::wstring& suffix) {
  bool registered = true;
  std::list<RegistryEntry*> entries;
  STLElementDeleter<std::list<RegistryEntry*>> entries_deleter(&entries);
  RegistryEntry::GetProgIdEntries(dist, chrome_exe, suffix, &entries);
  RegistryEntry::GetSystemEntries(dist, chrome_exe, suffix, &entries);
  for (std::list<RegistryEntry*>::const_iterator itr = entries.begin();
       itr != entries.end() && registered; ++itr) {
    // We do not need registered = registered && ... since the loop condition
    // is set to exit early.
    registered = (*itr)->ExistsInHKLM();
  }
  return registered;
}

// This method registers Chrome on Vista by launching an elevated setup.exe.
// That will show the user the standard Vista elevation prompt. If the user
// accepts it the new process will make the necessary changes and return SUCCESS
// that we capture and return.
bool ElevateAndRegisterChrome(BrowserDistribution* dist,
                              const std::wstring& chrome_exe,
                              const std::wstring& suffix) {
  FilePath exe_path =
      FilePath::FromWStringHack(chrome_exe).DirName()
          .Append(installer::kSetupExe);
  if (!file_util::PathExists(exe_path)) {
    HKEY reg_root = InstallUtil::IsPerUserInstall(chrome_exe.c_str()) ?
        HKEY_CURRENT_USER : HKEY_LOCAL_MACHINE;
    RegKey key(reg_root, dist->GetUninstallRegPath().c_str(), KEY_READ);
    std::wstring uninstall_string;
    key.ReadValue(installer::kUninstallStringField, &uninstall_string);
    CommandLine command_line = CommandLine::FromString(uninstall_string);
    exe_path = command_line.GetProgram();
  }

  if (file_util::PathExists(exe_path)) {
    CommandLine cmd(exe_path);
    cmd.AppendSwitchNative(installer::switches::kRegisterChromeBrowser,
                           chrome_exe);
    if (!suffix.empty()) {
      cmd.AppendSwitchNative(
          installer::switches::kRegisterChromeBrowserSuffix, suffix);
    }

    CommandLine& browser_command_line = *CommandLine::ForCurrentProcess();
    if (browser_command_line.HasSwitch(switches::kChromeFrame)) {
      cmd.AppendSwitch(installer::switches::kChromeFrame);
    }

    DWORD ret_val = 0;
    InstallUtil::ExecuteExeAsAdmin(cmd, &ret_val);
    if (ret_val == 0)
      return true;
  }
  return false;
}

// This method tries to figure out if another user has already registered her
// own copy of Chrome so that we can avoid overwriting it and append current
// user's login name to default browser registry entries. This function is
// not meant to detect all cases. It just tries to handle the most common case.
// All the conditions below have to be true for it to return true:
// - Software\Clients\StartMenuInternet\Chromium\"" key should have a valid
//   value.
// - The value should not be same as given value in |chrome_exe|
// - Finally to handle the default install path (C:\Document and Settings\
//   <user>\Local Settings\Application Data\Chromium\Application) the value
//   of the above key should differ from |chrome_exe| only in user name.
bool AnotherUserHasDefaultBrowser(BrowserDistribution* dist,
                                  const std::wstring& chrome_exe) {
  std::wstring reg_key(ShellUtil::kRegStartMenuInternet);
  reg_key.append(L"\\" + dist->GetApplicationName() + ShellUtil::kRegShellOpen);
  RegKey key(HKEY_LOCAL_MACHINE, reg_key.c_str(), KEY_READ);
  std::wstring registry_chrome_exe;
  if ((key.ReadValue(L"", &registry_chrome_exe) != ERROR_SUCCESS) ||
      registry_chrome_exe.length() < 2)
    return false;

  registry_chrome_exe = registry_chrome_exe.substr(1,
      registry_chrome_exe.length() - 2);
  if ((registry_chrome_exe.size() == chrome_exe.size()) &&
      (std::equal(chrome_exe.begin(), chrome_exe.end(),
                  registry_chrome_exe.begin(),
                  base::CaseInsensitiveCompare<wchar_t>()))) {
    return false;
  }

  std::vector<std::wstring> v1, v2;
  base::SplitString(registry_chrome_exe, L'\\', &v1);
  base::SplitString(chrome_exe, L'\\', &v2);
  if (v1.empty() || v2.empty() || v1.size() != v2.size())
    return false;

  // Now check that only one of the values within two '\' chars differ.
  std::vector<std::wstring>::iterator itr1 = v1.begin();
  std::vector<std::wstring>::iterator itr2 = v2.begin();
  bool one_mismatch = false;
  for ( ; itr1 < v1.end() && itr2 < v2.end(); ++itr1, ++itr2) {
    std::wstring s1 = *itr1;
    std::wstring s2 = *itr2;
    if ((s1.size() != s2.size()) ||
        (!std::equal(s1.begin(), s1.end(),
                     s2.begin(), base::CaseInsensitiveCompare<wchar_t>()))) {
      if (one_mismatch)
        return false;
      else
        one_mismatch = true;
    }
  }
  return true;
}

}  // namespace

const wchar_t* ShellUtil::kRegDefaultIcon = L"\\DefaultIcon";
const wchar_t* ShellUtil::kRegShellPath = L"\\shell";
const wchar_t* ShellUtil::kRegShellOpen = L"\\shell\\open\\command";
const wchar_t* ShellUtil::kRegStartMenuInternet =
    L"Software\\Clients\\StartMenuInternet";
const wchar_t* ShellUtil::kRegClasses = L"Software\\Classes";
const wchar_t* ShellUtil::kRegRegisteredApplications =
    L"Software\\RegisteredApplications";
const wchar_t* ShellUtil::kRegVistaUrlPrefs =
    L"Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\"
    L"http\\UserChoice";
const wchar_t* ShellUtil::kAppPathsRegistryKey =
    L"Software\\Microsoft\\Windows\\CurrentVersion\\App Paths";
const wchar_t* ShellUtil::kAppPathsRegistryPathName = L"Path";

#if defined(GOOGLE_CHROME_BUILD)
const wchar_t* ShellUtil::kChromeHTMLProgId = L"ChromeHTML";
const wchar_t* ShellUtil::kChromeHTMLProgIdDesc = L"Chrome HTML Document";
#else
const wchar_t* ShellUtil::kChromeHTMLProgId = L"ChromiumHTML";
const wchar_t* ShellUtil::kChromeHTMLProgIdDesc = L"Chromium HTML Document";
#endif

const wchar_t* ShellUtil::kFileAssociations[] = {L".htm", L".html", L".shtml",
    L".xht", L".xhtml", NULL};
const wchar_t* ShellUtil::kProtocolAssociations[] = {L"ftp", L"http", L"https",
    NULL};
const wchar_t* ShellUtil::kRegUrlProtocol = L"URL Protocol";

bool ShellUtil::AdminNeededForRegistryCleanup(BrowserDistribution* dist,
                                              const std::wstring& suffix) {
  bool cleanup_needed = false;
  std::list<RegistryEntry*> entries;
  STLElementDeleter<std::list<RegistryEntry*>> entries_deleter(&entries);
  RegistryEntry::GetProgIdEntries(dist, L"chrome.exe", suffix, &entries);
  RegistryEntry::GetSystemEntries(dist, L"chrome.exe", suffix, &entries);
  for (std::list<RegistryEntry*>::const_iterator itr = entries.begin();
       itr != entries.end() && !cleanup_needed; ++itr) {
    cleanup_needed = (*itr)->NameExistsInHKLM();
  }
  return cleanup_needed;
}

bool ShellUtil::CreateChromeDesktopShortcut(BrowserDistribution* dist,
                                            const std::wstring& chrome_exe,
                                            const std::wstring& description,
                                            ShellChange shell_change,
                                            bool alternate,
                                            bool create_new) {
  std::wstring shortcut_name;
  if (!ShellUtil::GetChromeShortcutName(dist, &shortcut_name, alternate))
    return false;

  bool ret = false;
  if (shell_change == ShellUtil::CURRENT_USER) {
    FilePath shortcut_path;
    // We do not want to create a desktop shortcut to Chrome in the current
    // user's desktop folder if there is already one in the "All Users"
    // desktop folder.
    bool got_system_desktop = ShellUtil::GetDesktopPath(true, &shortcut_path);
    FilePath shortcut = shortcut_path.Append(shortcut_name);
    if (!got_system_desktop || !file_util::PathExists(shortcut)) {
      // Either we couldn't query the "All Users" Desktop folder or there's
      // nothing in it, so let's continue.
      if (ShellUtil::GetDesktopPath(false, &shortcut_path)) {
        shortcut = shortcut_path.Append(shortcut_name);
        ret = ShellUtil::UpdateChromeShortcut(dist, chrome_exe,
                                              shortcut.value(),
                                              description, create_new);
      }
    }
  } else if (shell_change == ShellUtil::SYSTEM_LEVEL) {
    FilePath shortcut_path;
    if (ShellUtil::GetDesktopPath(true, &shortcut_path)) {
      FilePath shortcut = shortcut_path.Append(shortcut_name);
      ret = ShellUtil::UpdateChromeShortcut(dist, chrome_exe,
                                            shortcut.value(),
                                            description, create_new);
    }
  } else {
    NOTREACHED();
  }
  return ret;
}

bool ShellUtil::CreateChromeQuickLaunchShortcut(BrowserDistribution* dist,
                                                const std::wstring& chrome_exe,
                                                int shell_change,
                                                bool create_new) {
  std::wstring shortcut_name;
  if (!ShellUtil::GetChromeShortcutName(dist, &shortcut_name, false))
    return false;

  bool ret = true;
  // First create shortcut for the current user.
  if (shell_change & ShellUtil::CURRENT_USER) {
    std::wstring user_ql_path;
    if (ShellUtil::GetQuickLaunchPath(false, &user_ql_path)) {
      file_util::AppendToPath(&user_ql_path, shortcut_name);
      ret = ShellUtil::UpdateChromeShortcut(dist, chrome_exe, user_ql_path,
                                            L"", create_new);
    } else {
      ret = false;
    }
  }

  // Add a shortcut to Default User's profile so that all new user profiles
  // get it.
  if (shell_change & ShellUtil::SYSTEM_LEVEL) {
    std::wstring default_ql_path;
    if (ShellUtil::GetQuickLaunchPath(true, &default_ql_path)) {
      file_util::AppendToPath(&default_ql_path, shortcut_name);
      ret = ShellUtil::UpdateChromeShortcut(dist, chrome_exe, default_ql_path,
                                            L"", create_new) && ret;
    } else {
      ret = false;
    }
  }

  return ret;
}

std::wstring ShellUtil::GetChromeIcon(BrowserDistribution* dist,
                                      const std::wstring& chrome_exe) {
  std::wstring chrome_icon(chrome_exe);
  chrome_icon.append(L",");
  chrome_icon.append(base::IntToString16(dist->GetIconIndex()));
  return chrome_icon;
}

std::wstring ShellUtil::GetChromeShellOpenCmd(const std::wstring& chrome_exe) {
  return L"\"" + chrome_exe + L"\" -- \"%1\"";
}

bool ShellUtil::GetChromeShortcutName(BrowserDistribution* dist,
                                      std::wstring* shortcut, bool alternate) {
  shortcut->assign(alternate ? dist->GetAlternateApplicationName() :
                               dist->GetAppShortCutName());
  shortcut->append(L".lnk");
  return true;
}

bool ShellUtil::GetDesktopPath(bool system_level, FilePath* path) {
  wchar_t desktop[MAX_PATH];
  int dir = system_level ? CSIDL_COMMON_DESKTOPDIRECTORY :
                           CSIDL_DESKTOPDIRECTORY;
  if (FAILED(SHGetFolderPath(NULL, dir, NULL, SHGFP_TYPE_CURRENT, desktop)))
    return false;
  *path = FilePath(desktop);
  return true;
}

bool ShellUtil::GetQuickLaunchPath(bool system_level, std::wstring* path) {
  static const wchar_t* kQuickLaunchPath =
      L"Microsoft\\Internet Explorer\\Quick Launch";
  wchar_t qlaunch[MAX_PATH];
  if (system_level) {
    // We are accessing GetDefaultUserProfileDirectory this way so that we do
    // not have to declare dependency to Userenv.lib for chrome.exe
    typedef BOOL (WINAPI *PROFILE_FUNC)(LPWSTR, LPDWORD);
    HMODULE module = LoadLibrary(L"Userenv.dll");
    PROFILE_FUNC p = reinterpret_cast<PROFILE_FUNC>(GetProcAddress(module,
        "GetDefaultUserProfileDirectoryW"));
    DWORD size = _countof(qlaunch);
    if ((p == NULL) || ((p)(qlaunch, &size) != TRUE))
      return false;
    *path = qlaunch;
    if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
      file_util::AppendToPath(path, L"AppData\\Roaming");
    } else {
      file_util::AppendToPath(path, L"Application Data");
    }
  } else {
    if (FAILED(SHGetFolderPath(NULL, CSIDL_APPDATA, NULL,
                               SHGFP_TYPE_CURRENT, qlaunch)))
      return false;
    *path = qlaunch;
  }
  file_util::AppendToPath(path, kQuickLaunchPath);
  return true;
}

void ShellUtil::GetRegisteredBrowsers(BrowserDistribution* dist,
                                      std::map<std::wstring,
                                      std::wstring>* browsers) {
  std::wstring base_key(ShellUtil::kRegStartMenuInternet);
  HKEY root = HKEY_LOCAL_MACHINE;
  for (base::win::RegistryKeyIterator iter(root, base_key.c_str());
       iter.Valid(); ++iter) {
    std::wstring key = base_key + L"\\" + iter.Name();
    RegKey capabilities(root, (key + L"\\Capabilities").c_str(), KEY_READ);
    std::wstring name;
    if (!capabilities.Valid() ||
        capabilities.ReadValue(L"ApplicationName", &name) != ERROR_SUCCESS) {
      RegKey base_key(root, key.c_str(), KEY_READ);
      if (base_key.ReadValue(L"", &name) != ERROR_SUCCESS)
        continue;
    }
    RegKey install_info(root, (key + L"\\InstallInfo").c_str(), KEY_READ);
    std::wstring command;
    if (!install_info.Valid() ||
        (install_info.ReadValue(L"ReinstallCommand",
                                &command) != ERROR_SUCCESS))
      continue;
    if (!name.empty() && !command.empty() &&
        name.find(dist->GetApplicationName()) == std::wstring::npos)
      (*browsers)[name] = command;
  }
}

bool ShellUtil::GetUserSpecificDefaultBrowserSuffix(BrowserDistribution* dist,
                                                    std::wstring* entry) {
  wchar_t user_name[256];
  DWORD size = _countof(user_name);
  if (::GetUserName(user_name, &size) == 0)
    return false;
  entry->assign(L".");
  entry->append(user_name);

  std::wstring start_menu_entry(ShellUtil::kRegStartMenuInternet);
  start_menu_entry.append(L"\\" + dist->GetApplicationName() + *entry);
  RegKey key(HKEY_LOCAL_MACHINE, start_menu_entry.c_str(), KEY_READ);
  return key.Valid();
}

bool ShellUtil::MakeChromeDefault(BrowserDistribution* dist,
                                  int shell_change,
                                  const std::wstring& chrome_exe,
                                  bool elevate_if_not_admin) {
  if (!dist->CanSetAsDefault())
    return false;

  ShellUtil::RegisterChromeBrowser(dist, chrome_exe, L"", elevate_if_not_admin);

  bool ret = true;
  // First use the new "recommended" way on Vista to make Chrome default
  // browser.
  if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
    VLOG(1) << "Registering Chrome as default browser on Vista.";
    IApplicationAssociationRegistration* pAAR;
    HRESULT hr = CoCreateInstance(CLSID_ApplicationAssociationRegistration,
        NULL, CLSCTX_INPROC, __uuidof(IApplicationAssociationRegistration),
        (void**)&pAAR);
    if (SUCCEEDED(hr)) {
      std::wstring app_name = dist->GetApplicationName();
      std::wstring suffix;
      if (ShellUtil::GetUserSpecificDefaultBrowserSuffix(dist, &suffix))
        app_name += suffix;

      hr = pAAR->SetAppAsDefaultAll(app_name.c_str());
      pAAR->Release();
    }
    if (!SUCCEEDED(hr)) {
      ret = false;
      LOG(ERROR) << "Could not make Chrome default browser.";
    }
  }

  // Now use the old way to associate Chrome with supported protocols and file
  // associations. This should not be required on Vista but since some
  // applications still read Software\Classes\http key directly, we have to do
  // this on Vista also.

  std::list<RegistryEntry*> entries;
  STLElementDeleter<std::list<RegistryEntry*>> entries_deleter(&entries);
  std::wstring suffix;
  if (!GetUserSpecificDefaultBrowserSuffix(dist, &suffix))
    suffix = L"";
  RegistryEntry::GetUserEntries(dist, chrome_exe, suffix, &entries);
  // Change the default browser for current user.
  if ((shell_change & ShellUtil::CURRENT_USER) &&
      !AddRegistryEntries(HKEY_CURRENT_USER, entries))
      ret = false;

  // Chrome as default browser at system level.
  if ((shell_change & ShellUtil::SYSTEM_LEVEL) &&
      !AddRegistryEntries(HKEY_LOCAL_MACHINE, entries))
    ret = false;

  // Send Windows notification event so that it can update icons for
  // file associations.
  SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, NULL, NULL);
  return ret;
}

bool ShellUtil::RegisterChromeBrowser(BrowserDistribution* dist,
                                      const std::wstring& chrome_exe,
                                      const std::wstring& unique_suffix,
                                      bool elevate_if_not_admin) {
  if (!dist->CanSetAsDefault())
    return false;

  // First figure out we need to append a suffix to the registry entries to
  // make them unique.
  std::wstring suffix;
  if (!unique_suffix.empty()) {
    suffix = unique_suffix;
  } else if (InstallUtil::IsPerUserInstall(chrome_exe.c_str()) &&
             !GetUserSpecificDefaultBrowserSuffix(dist, &suffix) &&
             !AnotherUserHasDefaultBrowser(dist, chrome_exe)) {
    suffix = L"";
  }

  // Check if Chromium is already registered with this suffix.
  if (IsChromeRegistered(dist, chrome_exe, suffix))
    return true;

  // If user is an admin try to register and return the status.
  if (IsUserAnAdmin()) {
    std::list<RegistryEntry*> entries;
    STLElementDeleter<std::list<RegistryEntry*>> entries_deleter(&entries);
    RegistryEntry::GetProgIdEntries(dist, chrome_exe, suffix, &entries);
    RegistryEntry::GetSystemEntries(dist, chrome_exe, suffix, &entries);
    return AddRegistryEntries(HKEY_LOCAL_MACHINE, entries);
  }

  // If user is not an admin and OS is Vista, try to elevate and register.
  if (elevate_if_not_admin &&
      base::win::GetVersion() >= base::win::VERSION_VISTA &&
      ElevateAndRegisterChrome(dist, chrome_exe, suffix))
    return true;

  // If we got to this point then all we can do is create ProgIds under HKCU
  // on XP as well as Vista.
  std::list<RegistryEntry*> entries;
  STLElementDeleter<std::list<RegistryEntry*>> entries_deleter(&entries);
  RegistryEntry::GetProgIdEntries(dist, chrome_exe, L"", &entries);
  return AddRegistryEntries(HKEY_CURRENT_USER, entries);
}

bool ShellUtil::RemoveChromeDesktopShortcut(BrowserDistribution* dist,
                                            int shell_change, bool alternate) {
  std::wstring shortcut_name;
  if (!ShellUtil::GetChromeShortcutName(dist, &shortcut_name, alternate))
    return false;

  bool ret = true;
  if (shell_change & ShellUtil::CURRENT_USER) {
    FilePath shortcut_path;
    if (ShellUtil::GetDesktopPath(false, &shortcut_path)) {
      FilePath shortcut = shortcut_path.Append(shortcut_name);
      ret = file_util::Delete(shortcut, false);
    } else {
      ret = false;
    }
  }

  if (shell_change & ShellUtil::SYSTEM_LEVEL) {
    FilePath shortcut_path;
    if (ShellUtil::GetDesktopPath(true, &shortcut_path)) {
      FilePath shortcut = shortcut_path.Append(shortcut_name);
      ret = file_util::Delete(shortcut, false) && ret;
    } else {
      ret = false;
    }
  }
  return ret;
}

bool ShellUtil::RemoveChromeQuickLaunchShortcut(BrowserDistribution* dist,
                                                int shell_change) {
  std::wstring shortcut_name;
  if (!ShellUtil::GetChromeShortcutName(dist, &shortcut_name, false))
    return false;

  bool ret = true;
  // First remove shortcut for the current user.
  if (shell_change & ShellUtil::CURRENT_USER) {
    std::wstring user_ql_path;
    if (ShellUtil::GetQuickLaunchPath(false, &user_ql_path)) {
      file_util::AppendToPath(&user_ql_path, shortcut_name);
      ret = file_util::Delete(user_ql_path, false);
    } else {
      ret = false;
    }
  }

  // Delete shortcut in Default User's profile
  if (shell_change & ShellUtil::SYSTEM_LEVEL) {
    std::wstring default_ql_path;
    if (ShellUtil::GetQuickLaunchPath(true, &default_ql_path)) {
      file_util::AppendToPath(&default_ql_path, shortcut_name);
      ret = file_util::Delete(default_ql_path, false) && ret;
    } else {
      ret = false;
    }
  }

  return ret;
}

bool ShellUtil::UpdateChromeShortcut(BrowserDistribution* dist,
                                     const std::wstring& chrome_exe,
                                     const std::wstring& shortcut,
                                     const std::wstring& description,
                                     bool create_new) {
  std::wstring chrome_path = FilePath(chrome_exe).DirName().value();

  FilePath prefs_path(chrome_path);
  prefs_path = prefs_path.AppendASCII(installer::kDefaultMasterPrefs);
  installer::MasterPreferences prefs(prefs_path);
  int icon_index = dist->GetIconIndex();
  prefs.GetInt(installer::master_preferences::kChromeShortcutIconIndex,
               &icon_index);
  if (create_new) {
    return file_util::CreateShortcutLink(
        chrome_exe.c_str(),                // target
        shortcut.c_str(),                  // shortcut
        chrome_path.c_str(),               // working dir
        NULL,                              // arguments
        description.c_str(),               // description
        chrome_exe.c_str(),                // icon file
        icon_index,                        // icon index
        dist->GetBrowserAppId().c_str());  // app id
  } else {
    return file_util::UpdateShortcutLink(
        chrome_exe.c_str(),                // target
        shortcut.c_str(),                  // shortcut
        chrome_path.c_str(),               // working dir
        NULL,                              // arguments
        description.c_str(),               // description
        chrome_exe.c_str(),                // icon file
        icon_index,                        // icon index
        dist->GetBrowserAppId().c_str());  // app id
  }
}

redpajama_set_name: RedPajamaGithub


text:
package com.heliosapm.streams.tracing.writers;

/**
 *
Title: ConnectionStateListener

 *
Description: Defines a class that wants to be notified of connected state changes

 *
Company: Helios Development Group LLC

 * @author Whitehead (nwhitehead AT heliosdev DOT org)
 *
com.heliosapm.streams.tracing.writers.ConnectionStateListener

 */

public interface ConnectionStateListener {
	/**
	 * Fired when a writer is connected, i.e. has at least one connected channel
	 */
	public void onConnected();

	/**
	 * Fired when a writer is disconnected, i.e. has no connected channels
	 * @param shutdown true if source is disconnected on account of shutdown, false if a spurious disconnect
	 */
	public void onDisconnected(final boolean shutdown);
}


text:
{-+
Functions to support the implementation of functional dependencies, as described
by Mark P. Jones in "Type Classes with Functional Dependencies",
http://www.cse.ogi.edu/~mpj/pubs/fundeps.html
-}
module TiFunDeps where
import TiTypes
import HsTypeStruct
--import TiFreeNames(freeTyvars)
import TiInstanceDB(classInstances,InstEntry(..))
import TiMonad
import TiUtil(freshen)
import Unification(unify,match,subst)
import TiSolve(expandSynonyms)

import PrettyPrint
import MUtils(( # ),( #. ),(@@),collectByFst,done,usort,concatMapM,mapBoth)
import Monad(unless)
import Maybe(mapMaybe)
import List((\\),nub)

--import Debug.Trace(trace)
----mtrace s = trace s $ done
trace x y = y

{-+
Functions to ensure that declared instances are consisent with the functional
dependencies. See section 6.1 of the paper

We have relaxed the first condition in 6.1 to take the dependencies
implied by the predicates to the left of the arrow into account, to allow
instances like C a b => C [a] [b], where F_C = 1->2.
-}

checkInstances insts0 =
  do insts <- mapM flatInst insts0
     mapM_ checkInstanceConsistency insts
     mapM_ checkPairwiseConsistency (collectByFst insts)

-- Check that instances are pairwise consistent
checkPairwiseConsistency (cl@(HsCon c),heads) =
  do (fdeps,_) <- getDeps cl
     iheads <- instanceHeads c
     unless (null fdeps) $ mapM_ (checkDeps fdeps) (pairwise heads iheads)
  where
    checkDeps fdeps p = mapM_ (checkDep p) fdeps

    checkDep ((head1,_),(head2,_)) (dxs,rxs) = maybe done compare (unify domain)
      where
        ps = zip head1 head2
        domain = map (ps!!) dxs
        range = map (ps!!) rxs

        compare s = unless (all equal range) inconsistent
          where equal (t1,t2) = subst s t1==subst s t2

	inconsistent =
          fail $ pp $ "Instances are not pairwise consistent w.r.t. functional dependencies:" $$
                      nest 4 (vcat [appc cl head1,appc cl head2])

-- Check that an instance is consistent with the functional dependencies:
checkInstanceConsistency (cl,(ts,ps)) =
  do (fdeps,arity) <- getDeps cl
     unless (length ts==arity) $ badInstanceHead p
     pdeps <- predDeps ps
     unless (checkDeps ts pdeps fdeps) $
       fail $ pp $ sep [ppi "Instance is more general than dependencies allow:",ppi p]
  where
    p = appc cl ts
    checkDeps ts pdeps fdeps = all (checkDep ts pdeps) fdeps

    checkDep ts pdeps (dxs,rxs) = range `isSubsetOf` closure pdeps domain
      where
	 domain = vars dxs
	 range = vars rxs
	 vars ix = tv [ts!!i|i<-ix]

-- These errors shouldn't happen for instances that are free from kind errors
badInstanceHead hd = fail $ pp $ "Malformed instance head:"<+>hd

{-+ Iterated improvement: -}
improvements ps =
  do is <- improvement ps
     if apply is ps==ps
	then return is
	else (`compS` is) # improvements (nub (apply is ps))

{-+ Compute an improving subsitution using functional dependencies
    (section 6.2): -}

improvement ps =
    S . tr #. unify @@ expand @@
    concatMapM improve . collectByFst . mapMaybe flatPred $ ps
  where
    expand eqns =
       do kenv <- getKEnv
	  return $ mapBoth (expandSynonyms kenv) eqns

    tr [] = []
    tr s = trace ("Improving subst="++pp s) s

    improve (cl@(HsCon c),heads) =
      do (fdeps,_) <- getDeps cl
         iheads <- map fst # instanceHeads c
	 let imps = concatMap (improveAll cl heads iheads) fdeps
	 concatMapM freshimp imps

    freshimp ([],eqns) = return eqns -- optimization
    freshimp (gs,eqns) = freshen gs eqns

    improveAll cl heads iheads (dxs,rxs) =
        map improvePair (pairs1 heads) ++ map improveInst (pairs2 iheads heads)
      where
	improvePair (head1,head2) =
	  if ds1==ds2
	  then trace ("Improving pair "++show (dxs,rxs)++" "++ppp (head1,head2)) $
               ([],[(head1!!rx,head2!!rx)|rx<-rxs])
	  else ([],[])
          where (ds1,ds2) = ([head1!!dx|dx<-dxs],[head2!!dx|dx<-dxs])

        improveInst (ihead,head) =
            maybe ([],[]) improve1 $ match [(ihead!!dx,head!!dx)|dx<-dxs]
          where
	    improve1 s =
                trace ("Improving inst "++show (dxs,rxs)++ppp (ihead,head)) $
                (tv eqns \\ tv head,eqns)
              where eqns = [(subst s (ihead!!rx),head!!rx)|rx<-rxs]
        ppp (h1,h2) = pp (appc cl h1,appc cl h2)

{-+ Computing the closure w.r.t functional dependencies
    (section 5.2 of the paper).
-}
closure fdeps = fix step . usort
  where
     step xs = usort (xs++[r|(ds,rs)<-fdeps,ds `isSubsetOf` xs,r<-rs])
     fix f = stop . iterate f
     stop (x1:x2:xs) = if x1==x2 then x1 else stop (x2:xs)

{-+ Computing the functional dependencies applied by a set of predicates
    (section 6.3)
-}
predDeps ps = concatMapM pred1Deps (mapMaybe flatPred ps)
pred1Deps (cl,ts) =
  do (fdeps,_) <- getDeps cl
     let vars ix = tv [ts!!i|i<-ix]
     return [(dvs,rvs)|(dxs,rxs)<-fdeps,
	               let dvs = vars dxs
	                   rvs = vars rxs,
	               not (null rvs)]

{-+ Looking up the functional dependencies (and the arity) for a class: -}
getDeps cl =
  do (k,Class _ ps fdeps _) <- env kenv cl
     return (fdeps,length ps)

{-+ Looking up all the instances of a given class: -}
instanceHeads c = map snd # (mapM flatInst . flip classInstances c =<< getIEnv)

{-+
Auxiliary functions
-}

xs `isSubsetOf` ys = (`elem` ys) `all` xs

pairwise hs hs' = pairs1 hs++pairs2 hs hs'

pairs1 []     = []
pairs1 (x:xs) = [(x,x')|x'<-xs]++pairs1 xs

pairs2 xs ys = [(x,y)|x<-xs,y<-ys]

flatInst (hd,IE _ _ ps) =
  do (cl,hd') <- flatPred hd
     return (cl,(hd',ps))

flatPred ty = maybe (badInstanceHead ty) return (flatConAppT ty)

appc cl ts = appT (ty cl:ts)


text:
compass rally cookbook
===============

compass rally cookbook


text:
package com.fasterxml.jackson.core.base;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;

import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.core.JsonParser.Feature;
import com.fasterxml.jackson.core.io.JsonEOFException;
import com.fasterxml.jackson.core.io.NumberInput;
import com.fasterxml.jackson.core.sym.FieldNameMatcher;
import com.fasterxml.jackson.core.type.ResolvedType;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.core.util.ByteArrayBuilder;
import com.fasterxml.jackson.core.util.VersionUtil;

import static com.fasterxml.jackson.core.JsonTokenId.*;

/**
 * Intermediate base class used by all Jackson {@link JsonParser}
 * implementations, but does not add any additional fields that depend
 * on particular method of obtaining input.
 *

 * Note that 'minimal' here mostly refers to minimal number of fields
 * (size) and functionality that is specific to certain types
 * of parser implementations; but not necessarily to number of methods.
 */
public abstract class ParserMinimalBase extends JsonParser
{
    // Control chars:
    protected final static int INT_TAB = '\t';
    protected final static int INT_LF = '\n';
    protected final static int INT_CR = '\r';
    protected final static int INT_SPACE = 0x0020;

    // Markup
    protected final static int INT_LBRACKET = '[';
    protected final static int INT_RBRACKET = ']';
    protected final static int INT_LCURLY = '{';
    protected final static int INT_RCURLY = '}';
    protected final static int INT_QUOTE = '"';
    protected final static int INT_APOS = '\'';
    protected final static int INT_BACKSLASH = '\\';
    protected final static int INT_SLASH = '/';
    protected final static int INT_ASTERISK = '*';
    protected final static int INT_COLON = ':';
    protected final static int INT_COMMA = ',';
    protected final static int INT_HASH = '#';

    // Number chars
    protected final static int INT_0 = '0';
    protected final static int INT_9 = '9';
    protected final static int INT_MINUS = '-';
    protected final static int INT_PLUS = '+';

    protected final static int INT_PERIOD = '.';
    protected final static int INT_e = 'e';
    protected final static int INT_E = 'E';

    protected final static char CHAR_NULL = '\0';

    protected final static byte[] NO_BYTES = new byte[0];

    protected final static int[] NO_INTS = new int[0];

    /*
    /**********************************************************
    /* Constants and fields of former 'JsonNumericParserBase'
    /**********************************************************
     */

    protected final static int NR_UNKNOWN = 0;

    // First, integer types

    protected final static int NR_INT = 0x0001;
    protected final static int NR_LONG = 0x0002;
    protected final static int NR_BIGINT = 0x0004;

    // And then floating point types

    protected final static int NR_DOUBLE = 0x008;
    protected final static int NR_BIGDECIMAL = 0x0010;

    /**
     * NOTE! Not used by JSON implementation but used by many of binary codecs
     */
    protected final static int NR_FLOAT = 0x020;

    // Also, we need some numeric constants

    protected final static BigInteger BI_MIN_INT = BigInteger.valueOf(Integer.MIN_VALUE);
    protected final static BigInteger BI_MAX_INT = BigInteger.valueOf(Integer.MAX_VALUE);

    protected final static BigInteger BI_MIN_LONG = BigInteger.valueOf(Long.MIN_VALUE);
    protected final static BigInteger BI_MAX_LONG = BigInteger.valueOf(Long.MAX_VALUE);

    protected final static BigDecimal BD_MIN_LONG = new BigDecimal(BI_MIN_LONG);
    protected final static BigDecimal BD_MAX_LONG = new BigDecimal(BI_MAX_LONG);

    protected final static BigDecimal BD_MIN_INT = new BigDecimal(BI_MIN_INT);
    protected final static BigDecimal BD_MAX_INT = new BigDecimal(BI_MAX_INT);

    protected final static long MIN_INT_L = (long) Integer.MIN_VALUE;
    protected final static long MAX_INT_L = (long) Integer.MAX_VALUE;

    // These are not very accurate, but have to do... (for bounds checks)

    protected final static double MIN_LONG_D = (double) Long.MIN_VALUE;
    protected final static double MAX_LONG_D = (double) Long.MAX_VALUE;

    protected final static double MIN_INT_D = (double) Integer.MIN_VALUE;
    protected final static double MAX_INT_D = (double) Integer.MAX_VALUE;

    /*
    /**********************************************************
    /* Misc other constants
    /**********************************************************
     */

    /**
     * Maximum number of characters to include in token reported
     * as part of error messages.
     */
    protected final static int MAX_ERROR_TOKEN_LENGTH = 256;

    /*
    /**********************************************************
    /* Minimal generally useful state
    /**********************************************************
     */

    /**
     * Context object provided by higher level functionality like
     * databinding for two reasons: passing configuration information
     * during construction, and to allow calling of some databind
     * operations via parser instance.
     *
     * @since 3.0
     */
    protected final ObjectReadContext _objectReadContext;

    /**
     * Last token retrieved via {@link #nextToken}, if any.
     * Null before the first call to nextToken(),
     * as well as if token has been explicitly cleared
     */
    protected JsonToken _currToken;

    /**
     * Last cleared token, if any: that is, value that was in
     * effect when {@link #clearCurrentToken} was called.
     */
    protected JsonToken _lastClearedToken;

    /*
    /**********************************************************
    /* Life-cycle
    /**********************************************************
     */

    protected ParserMinimalBase(ObjectReadContext readCtxt) {
        _objectReadContext = readCtxt;
    }

    protected ParserMinimalBase(ObjectReadContext readCtxt,
            int features)
    {
        super(features);
        _objectReadContext = readCtxt;
    }

    /*
    /**********************************************************
    /* Configuration overrides if any
    /**********************************************************
     */

    @Override
    public ObjectReadContext getObjectReadContext() {
        return _objectReadContext;
    }

    // from base class:

    //public void enableFeature(Feature f)
    //public void disableFeature(Feature f)
    //public void setFeature(Feature f, boolean state)
    //public boolean isFeatureEnabled(Feature f)

    /*
    /**********************************************************
    /* JsonParser impl: open / close
    /**********************************************************
     */

    //public JsonToken getCurrentToken()
    //public boolean hasCurrentToken()

    @Override public abstract void close() throws IOException;
    @Override public abstract boolean isClosed();

    /*
    /**********************************************************
    /* JsonParser impl: basic state access
    /**********************************************************
     */

    @Override public abstract TokenStreamContext getParsingContext();

//  public abstract JsonLocation getTokenLocation();

//  public abstract JsonLocation getCurrentLocation();

    /**
     * Method sub-classes need to implement
     */
    protected abstract void _handleEOF() throws JsonParseException;

    @Override public abstract String currentName() throws IOException;

    /*
    /**********************************************************
    /* JsonParser impl: basic stream iteration
    /**********************************************************
     */

    @Override public abstract JsonToken nextToken() throws IOException;

    @Override public void finishToken() throws IOException { ; /* nothing */ }

    @Override public JsonToken currentToken() { return _currToken; }
    @Override public int currentTokenId() {
        final JsonToken t = _currToken;
        return (t == null) ? JsonTokenId.ID_NO_TOKEN : t.id();
    }

    @Override public boolean hasCurrentToken() { return _currToken != null; }
    @Override public boolean hasTokenId(int id) {
        final JsonToken t = _currToken;
        if (t == null) {
            return (JsonTokenId.ID_NO_TOKEN == id);
        }
        return t.id() == id;
    }

    @Override public boolean hasToken(JsonToken t) {
        return (_currToken == t);
    }

    @Override public boolean isExpectedStartArrayToken() { return _currToken == JsonToken.START_ARRAY; }
    @Override public boolean isExpectedStartObjectToken() { return _currToken == JsonToken.START_OBJECT; }

    @Override
    public JsonToken nextValue() throws IOException {
        // Implementation should be as trivial as follows; only needs to change if
        // we are to skip other tokens (for example, if comments were exposed as tokens)
        JsonToken t = nextToken();
        if (t == JsonToken.FIELD_NAME) {
            t = nextToken();
        }
        return t;
    }

    @Override
    public JsonParser skipChildren() throws IOException
    {
        if (_currToken != JsonToken.START_OBJECT
            && _currToken != JsonToken.START_ARRAY) {
            return this;
        }
        int open = 1;

        // Since proper matching of start/end markers is handled
        // by nextToken(), we'll just count nesting levels here
        while (true) {
            JsonToken t = nextToken();
            if (t == null) {
                _handleEOF();
                /* given constraints, above should never return;
                 * however, FindBugs doesn't know about it and
                 * complains... so let's add dummy break here
                 */
                return this;
            }
            if (t.isStructStart()) {
                ++open;
            } else if (t.isStructEnd()) {
                if (--open == 0) {
                    return this;
                }
            }
        }
    }

    /*
    /**********************************************************
    /* JsonParser impl: stream iteration, field names
    /**********************************************************
     */

    @Override
    public String nextFieldName() throws IOException {
        return (nextToken() == JsonToken.FIELD_NAME) ? currentName() : null;
    }

    @Override
    public boolean nextFieldName(SerializableString str) throws IOException {
        return (nextToken() == JsonToken.FIELD_NAME) && str.getValue().equals(currentName());
    }

    // Base implementation that should work well for most implementations but that
    // is typically overridden for performance optimization purposes
    @Override
    public int nextFieldName(FieldNameMatcher matcher) throws IOException {
        String str = nextFieldName();
        if (str != null) {
            return matcher.matchAnyName(str);
        }
        if (_currToken == JsonToken.END_OBJECT) {
            return FieldNameMatcher.MATCH_END_OBJECT;
        }
        return FieldNameMatcher.MATCH_ODD_TOKEN;
    }

    @Override
    public int currentFieldName(FieldNameMatcher matcher) throws IOException {
        if (_currToken == JsonToken.FIELD_NAME) {
            return matcher.matchAnyName(currentName());
        }
        if (_currToken == JsonToken.END_OBJECT) {
            return FieldNameMatcher.MATCH_END_OBJECT;
        }
        return FieldNameMatcher.MATCH_ODD_TOKEN;
    }

    /*
    /**********************************************************
    /* Public API, token state overrides
    /**********************************************************
     */

    @Override public void clearCurrentToken() {
        if (_currToken != null) {
            _lastClearedToken = _currToken;
            _currToken = null;
        }
    }

    @Override public JsonToken getLastClearedToken() { return _lastClearedToken; }

    @Override public abstract void overrideCurrentName(String name);

    /*
    /**********************************************************
    /* Public API, access to token information, text
    /**********************************************************
     */

    @Override public abstract String getText() throws IOException;
    @Override public abstract char[] getTextCharacters() throws IOException;
    @Override public abstract boolean hasTextCharacters();
    @Override public abstract int getTextLength() throws IOException;
    @Override public abstract int getTextOffset() throws IOException;

    /*
    /**********************************************************
    /* Public API, access to token information, binary
    /**********************************************************
     */

    @Override public abstract byte[] getBinaryValue(Base64Variant b64variant) throws IOException;

    /*
    /**********************************************************
    /* Public API, access with conversion/coercion
    /**********************************************************
     */

    @Override
    public boolean getValueAsBoolean(boolean defaultValue) throws IOException
    {
        JsonToken t = _currToken;
        if (t != null) {
            switch (t.id()) {
            case ID_STRING:
                String str = getText().trim();
                if ("true".equals(str)) {
                    return true;
                }
                if ("false".equals(str)) {
                    return false;
                }
                if (_hasTextualNull(str)) {
                    return false;
                }
                break;
            case ID_NUMBER_INT:
                return getIntValue() != 0;
            case ID_TRUE:
                return true;
            case ID_FALSE:
            case ID_NULL:
                return false;
            case ID_EMBEDDED_OBJECT:
                Object value = getEmbeddedObject();
                if (value instanceof Boolean) {
                    return (Boolean) value;
                }
                break;
            default:
            }
        }
        return defaultValue;
    }

    @Override
    public int getValueAsInt() throws IOException
    {
        JsonToken t = _currToken;
        if ((t == JsonToken.VALUE_NUMBER_INT) || (t == JsonToken.VALUE_NUMBER_FLOAT)) {
            return getIntValue();
        }
        return getValueAsInt(0);
    }

    @Override
    public int getValueAsInt(int defaultValue) throws IOException
    {
        JsonToken t = _currToken;
        if ((t == JsonToken.VALUE_NUMBER_INT) || (t == JsonToken.VALUE_NUMBER_FLOAT)) {
            return getIntValue();
        }
        if (t != null) {
            switch (t.id()) {
            case ID_STRING:
                String str = getText();
                if (_hasTextualNull(str)) {
                    return 0;
                }
                return NumberInput.parseAsInt(str, defaultValue);
            case ID_TRUE:
                return 1;
            case ID_FALSE:
                return 0;
            case ID_NULL:
                return 0;
            case ID_EMBEDDED_OBJECT:
                Object value = getEmbeddedObject();
                if (value instanceof Number) {
                    return ((Number) value).intValue();
                }
            }
        }
        return defaultValue;
    }

    @Override
    public long getValueAsLong() throws IOException
    {
        JsonToken t = _currToken;
        if ((t == JsonToken.VALUE_NUMBER_INT) || (t == JsonToken.VALUE_NUMBER_FLOAT)) {
            return getLongValue();
        }
        return getValueAsLong(0L);
    }

    @Override
    public long getValueAsLong(long defaultValue) throws IOException
    {
        JsonToken t = _currToken;
        if ((t == JsonToken.VALUE_NUMBER_INT) || (t == JsonToken.VALUE_NUMBER_FLOAT)) {
            return getLongValue();
        }
        if (t != null) {
            switch (t.id()) {
            case ID_STRING:
                String str = getText();
                if (_hasTextualNull(str)) {
                    return 0L;
                }
                return NumberInput.parseAsLong(str, defaultValue);
            case ID_TRUE:
                return 1L;
            case ID_FALSE:
            case ID_NULL:
                return 0L;
            case ID_EMBEDDED_OBJECT:
                Object value = getEmbeddedObject();
                if (value instanceof Number) {
                    return ((Number) value).longValue();
                }
            }
        }
        return defaultValue;
    }

    @Override
    public double getValueAsDouble(double defaultValue) throws IOException
    {
        JsonToken t = _currToken;
        if (t != null) {
            switch (t.id()) {
            case ID_STRING:
                String str = getText();
                if (_hasTextualNull(str)) {
                    return 0L;
                }
                return NumberInput.parseAsDouble(str, defaultValue);
            case ID_NUMBER_INT:
            case ID_NUMBER_FLOAT:
                return getDoubleValue();
            case ID_TRUE:
                return 1.0;
            case ID_FALSE:
            case ID_NULL:
                return 0.0;
            case ID_EMBEDDED_OBJECT:
                Object value = this.getEmbeddedObject();
                if (value instanceof Number) {
                    return ((Number) value).doubleValue();
                }
            }
        }
        return defaultValue;
    }

    @Override
    public String getValueAsString() throws IOException {
        if (_currToken == JsonToken.VALUE_STRING) {
            return getText();
        }
        if (_currToken == JsonToken.FIELD_NAME) {
            return currentName();
        }
        return getValueAsString(null);
    }

    @Override
    public String getValueAsString(String defaultValue) throws IOException {
        if (_currToken == JsonToken.VALUE_STRING) {
            return getText();
        }
        if (_currToken == JsonToken.FIELD_NAME) {
            return currentName();
        }
        if (_currToken == null || _currToken == JsonToken.VALUE_NULL || !_currToken.isScalarValue()) {
            return defaultValue;
        }
        return getText();
    }

    /*
    /**********************************************************
    /* Databind callbacks
    /**********************************************************
     */

    @Override
    public <T> T readValueAs(Class<T> valueType) throws IOException {
        return _objectReadContext.readValue(this, valueType);
    }

    @SuppressWarnings("unchecked")
    @Override
    public <T> T readValueAs(TypeReference<?> valueTypeRef) throws IOException {
        return (T) _objectReadContext.readValue(this, valueTypeRef);
    }

    @SuppressWarnings("unchecked")
    @Override
    public <T> T readValueAs(ResolvedType type) throws IOException {
        return (T) _objectReadContext.readValue(this, type);
    }

    @SuppressWarnings("unchecked")
    @Override
    public <T extends TreeNode> T readValueAsTree() throws IOException {
        return (T) _objectReadContext.readTree(this);
    }

    /*
    /**********************************************************
    /* Helper methods: Base64 decoding
    /**********************************************************
     */

    /**
     * Helper method that can be used for base64 decoding in cases where
     * encoded content has already been read as a String.
     */
    protected void _decodeBase64(String str, ByteArrayBuilder builder, Base64Variant b64variant) throws IOException
    {
        try {
            b64variant.decode(str, builder);
        } catch (IllegalArgumentException e) {
            _reportError(e.getMessage());
        }
    }

    /*
    /**********************************************************
    /* Coercion helper methods (overridable)
    /**********************************************************
     */

    /**
     * Helper method used to determine whether we are currently pointing to
     * a String value of "null" (NOT a null token); and, if so, that parser
     * is to recognize and return it similar to if it was real null token.
     */
    protected boolean _hasTextualNull(String value) { return "null".equals(value); }

    /*
    /**********************************************************
    /* Error reporting
    /**********************************************************
     */

    protected void reportUnexpectedNumberChar(int ch, String comment) throws JsonParseException {
        String msg = String.format("Unexpected character (%s) in numeric value", _getCharDesc(ch));
        if (comment != null) {
            msg += ": "+comment;
        }
        _reportError(msg);
    }

    protected void reportInvalidNumber(String msg) throws JsonParseException {
        _reportError("Invalid numeric value: "+msg);
    }

    protected void reportOverflowInt() throws IOException {
        _reportError(String.format("Numeric value (%s) out of range of int (%d - %s)",
                getText(), Integer.MIN_VALUE, Integer.MAX_VALUE));
    }

    protected void reportOverflowLong() throws IOException {
        _reportError(String.format("Numeric value (%s) out of range of long (%d - %s)",
                getText(), Long.MIN_VALUE, Long.MAX_VALUE));
    }

    protected void _reportUnexpectedChar(int ch, String comment) throws JsonParseException
    {
        if (ch < 0) { // sanity check
            _reportInvalidEOF();
        }
        String msg = String.format("Unexpected character (%s)", _getCharDesc(ch));
        if (comment != null) {
            msg += ": "+comment;
        }
        _reportError(msg);
    }

    protected void _reportInvalidEOF() throws JsonParseException {
        _reportInvalidEOF(" in "+_currToken, _currToken);
    }

    protected void _reportInvalidEOFInValue(JsonToken type) throws JsonParseException {
        String msg;
        if (type == JsonToken.VALUE_STRING) {
            msg = " in a String value";
        } else if ((type == JsonToken.VALUE_NUMBER_INT)
                || (type == JsonToken.VALUE_NUMBER_FLOAT)) {
            msg = " in a Number value";
        } else {
            msg = " in a value";
        }
        _reportInvalidEOF(msg, type);
    }

    protected void _reportInvalidEOF(String msg, JsonToken currToken) throws JsonParseException {
        throw new JsonEOFException(this, currToken, "Unexpected end-of-input"+msg);
    }

    protected void _reportMissingRootWS(int ch) throws JsonParseException {
        _reportUnexpectedChar(ch, "Expected space separating root-level values");
    }

    protected void _throwInvalidSpace(int i) throws JsonParseException {
        char c = (char) i;
        String msg = "Illegal character ("+_getCharDesc(c)+"): only regular white space (\\r, \\n, \\t) is allowed between tokens";
        _reportError(msg);
    }

    /**
     * Method called to report a problem with unquoted control character.
     * Note: starting with version 1.4, it is possible to suppress
     * exception by enabling {@link Feature#ALLOW_UNQUOTED_CONTROL_CHARS}.
     */
    protected void _throwUnquotedSpace(int i, String ctxtDesc) throws JsonParseException {
        // JACKSON-208; possible to allow unquoted control chars:
        if (!isEnabled(Feature.ALLOW_UNQUOTED_CONTROL_CHARS) || i > INT_SPACE) {
            char c = (char) i;
            String msg = "Illegal unquoted character ("+_getCharDesc(c)+"): has to be escaped using backslash to be included in "+ctxtDesc;
            _reportError(msg);
        }
    }

    protected char _handleUnrecognizedCharacterEscape(char ch) throws JsonProcessingException {
        // as per [JACKSON-300]
        if (isEnabled(Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER)) {
            return ch;
        }
        // and [JACKSON-548]
        if (ch == '\'' && isEnabled(Feature.ALLOW_SINGLE_QUOTES)) {
            return ch;
        }
        _reportError("Unrecognized character escape "+_getCharDesc(ch));
        return ch;
    }

    /*
    /**********************************************************
    /* Error reporting, generic
    /**********************************************************
     */

    protected final static String _getCharDesc(int ch)
    {
        char c = (char) ch;
        if (Character.isISOControl(c)) {
            return "(CTRL-CHAR, code "+ch+")";
        }
        if (ch > 255) {
            return "'"+c+"' (code "+ch+" / 0x"+Integer.toHexString(ch)+")";
        }
        return "'"+c+"' (code "+ch+")";
    }

    protected final void _reportError(String msg) throws JsonParseException {
        throw _constructError(msg);
    }

    protected final void _reportError(String msg, Object arg) throws JsonParseException {
        throw _constructError(String.format(msg, arg));
    }

    protected final void _reportError(String msg, Object arg1, Object arg2) throws JsonParseException {
        throw _constructError(String.format(msg, arg1, arg2));
    }

    protected final void _wrapError(String msg, Throwable t) throws JsonParseException {
        throw _constructError(msg, t);
    }

    protected final void _throwInternal() {
        VersionUtil.throwInternal();
    }

    protected final JsonParseException _constructError(String msg, Throwable t) {
        return new JsonParseException(this, msg, t);
    }

    protected static byte[] _asciiBytes(String str) {
        byte[] b = new byte[str.length()];
        for (int i = 0, len = str.length(); i < len; ++i) {
            b[i] = (byte) str.charAt(i);
        }
        return b;
    }

    protected static String _ascii(byte[] b) {
        try {
            return new String(b, "US-ASCII");
        } catch (IOException e) { // never occurs
            throw new RuntimeException(e);
        }
    }
}


text:
<?php

namespace Metrol\CSS;

/**
 * A utility for loading up style rules from a string or file into a CSS object
 *
 */
class Parse
{
  /**
   * The CSS object to populate
   *
   * @var \Metrol\CSS
   */
  private $css;

  /**
   * The string to parse and add to the CSS object
   *
   * @var string
   */
  private $styleText;

  /**
   * Instantiate the object
   *
   */
  public function __construct()
  {
    $this->css = new \Metrol\CSS;
    $this->styleText = '';
  }

  /**
   * Set the style text
   *
   * @param string $cssStr The set of CSS rules in a raw string
   *
   * @return this
   */
  public function setStyleText($cssStr)
  {
    $this->styleText = $cssStr;

    return $this;
  }

  /**
   * Specify a CSS file to parse
   *
   * @param string $file Full path and name to the CSS file
   *
   * @return this
   */
  public function setStyleFile($file)
  {
    $cssStr = file_get_contents($file);

    $this->setStyleText($cssStr);

    return $this;
  }

  /**
   * Parse what we've got to to work with and populate the CSS object
   *
   * @return this
   */
  public function parse()
  {
    if ( strlen($this->styleText) == 0 )
    {
      return $this->css;
    }

    $str = $this->removeComments();
    $str = str_replace("\n", ' ', $str);

    $sheetParts = explode("}", $str);

    foreach ( $sheetParts as $sheetPart )
    {
      if ( strpos($sheetPart, '{') === false ) { continue; }

      $rule = $this->css->getNewRule();

      $decBlkParts = explode('{', $sheetPart);

      $selector = $decBlkParts[0];

      $selObj = $rule->getSelector();

      if ( strpos($selector, ',') !== false )
      {
        $selObj->setSelector($selector);
      }
      else
      {
        $selectorBrk = explode(',', $selector);

        foreach ( $selectorBrk as $selPart )
        {
          $selObj->addSelector($selPart);
        }
      }

      $rawRules = $decBlkParts[1];
      $decList = explode(';', $rawRules);

      foreach ( $decList as $rawDec )
      {
        $rawDecTrm = trim($rawDec);
        if ( strpos($rawDecTrm, ':') === false ) { continue; }

        $decParts = explode(':', $rawDecTrm);

        $prop = $decParts[0];
        $val  = $decParts[1];

        $rule->getDeclarationBlock()
             ->addDeclaration($prop, $val);
      }
    }

    return $this;
  }

  /**
   * Fancy bit of regexp to remove the comments from a CSS input
   *
   * @return string
   */
  private function removeComments()
  {
    $buffer = $this->styleText;

    $regex = array(
    "`^([\t\s]+)`ism"=>'',
    "`^\/\*(.+?)\*\/`ism"=>"",
    "`([\n\A;]+)\/\*(.+?)\*\/`ism"=>"$1",
    "`([\n\A;\s]+)//(.+?)[\n\r]`ism"=>"$1\n",
    "`(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+`ism"=>"\n");

    $buffer = preg_replace(array_keys($regex), $regex, $buffer);

    return $buffer;
  }

  /**
   * Allow a caller to pass in a CSS object so that it can be added to by this
   * parser.  This needs to happen before parsing, as this will replace the CSS
   * object already here.
   *
   * @param \Metrol\CSS $css The CSS object to replace the one already here
   *
   * @return this
   */
  public function setCSS(\Metrol\CSS $css)
  {
    $this->css = $css;

    return $this;
  }

  /**
   * Provide the CSS object stored here
   *
   * @return \Metrol\CSS
   */
  public function getCSS()
  {
    return $this->css;
  }
}


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

package com.google.gke.auditor.configs.psp;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import com.google.gke.auditor.models.PodSecurityPolicy;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

/**
 * A test for {@link PrivilegedContainers}.
 */
public class PrivilegedContainersTest {

  private PrivilegedContainers privilegedContainers;

  @BeforeEach
  public void init() {
    privilegedContainers = new PrivilegedContainers();
  }

  @Test
  public void getRecommendationTextTest() {
    assertThat(privilegedContainers.getRecommendationText()).isNotEmpty();
  }

  @Test
  public void getDetectorNameTest() {
    assertThat(privilegedContainers.getDetectorName()).isNotEmpty();
    assertThat(privilegedContainers.getDetectorName())
        .isEqualTo("PRIVILEGED_CONTAINERS");
  }

  @Test
  public void getUsefulURLsTest() {
    List<String> usefulUrls = List
        .of("https://kubernetes.io/docs/concepts/policy/pod-security-policy/#enabling-pod-security-policies",
            "https://kubernetes.io/docs/concepts/policy/pod-security-policy/#privileged",
            "https://www.nccgroup.com/uk/our-research/abusing-privileged-and-unprivileged-linux-containers/");

    assertThat(privilegedContainers.getUsefulURLs()).isNotNull();
    assertThat(privilegedContainers.getUsefulURLs()).containsAll(usefulUrls);
  }

  @Test
  public void isVulnerablePrivilegedContainersFalseTest() {
    PodSecurityPolicy psp = mock(PodSecurityPolicy.class);
    when(psp.getPrivileged()).thenReturn(false);

    assertThat(privilegedContainers.isVulnerable(psp)).isFalse();
  }

  @Test
  public void isVulnerablePrivilegedContainersTrueTest() {
    PodSecurityPolicy psp = mock(PodSecurityPolicy.class);
    when(psp.getPrivileged()).thenReturn(true);

    assertThat(privilegedContainers.isVulnerable(psp)).isTrue();
  }

}


text:
describe("awesomplete.selected", function () {

	$.fixture("plain");

	subject(function () {
		return new Awesomplete("#plain", { list: ["item1", "item2", "item3"] });
	});

	describe("with newly created completer", function () {
		it("is false", function () {
			expect(this.subject.selected).toBe(false);
		});
	});

	describe("with opened completer", function () {
		beforeEach(function () {
			this.subject.open();
			$.type(this.subject.input, "ite");
		});

		describe("and no item selected", function () {
			it("is false", function () {
				expect(this.subject.selected).toBe(false);
			});
		});

		describe("and some item selected", function () {
			it("is true", function () {
				this.subject.next();
				expect(this.subject.selected).toBe(true);
			});
		});
	});

	describe("with closed completer", function () {
		it("is false", function () {
			this.subject.close();
			expect(this.subject.selected).toBe(false);
		});
	});
});


text:
#include "core.h"
#include <map>

#include "window/Window.h"
#include "graphics/opengl/Graphics.h"
#include "graphics/Color.h"
#include "math/MathModule.h"
#include "event/sdl/Event.h"
#include "timer/Timer.h"
#include "common/Module.h"

#if LUA_VERSION_NUM > 501
#error Not the right version of Lua!
#endif

using namespace love;
using namespace love::graphics;
using namespace love::math;
using namespace love::event::sdl;
using namespace love::timer;
using namespace love::keyboard;

namespace nersis {
	std::vector<NModule*> modules;
	std::map<std::string, NModule*> moduleMap;

	void registerModule(NModule *module) {
		modules.push_back(module);
	}

	NModule *getModule(std::string name) {
		return moduleMap[name];
	}

	std::vector<NModule*> moduleList() {
		return modules;
	}
}

//Use this as module sample
class FuckCPPModule : public nersis::NModule {
	public:
	FuckCPPModule() {
		name = "FUCKCPPMODULE";
		printf("Hello from core dummy module!\n");
	}
};

static int nersis_core_hello(lua_State *L) {
	printf("Hello from libnersiscore!\n");
	/*Window::singleton->setWindow(600,200);
	opengl::Graphics *graphics = Module::getInstance<opengl::Graphics>(Module::M_GRAPHICS);
	graphics->setBackgroundColor(Color(255,255,255,255));*/

	nersis::registerModule(new FuckCPPModule());
	return 0;
}

static int nersis_core_love_run(lua_State *L) {
	Math *math = Module::getInstance<Math>(Module::M_MATH);
	Timer *timer = Module::getInstance<Timer>(Module::M_TIMER);
	window::Window *window = Module::getInstance<window::Window>(Module::M_WINDOW);
	opengl::Graphics *graphics = Module::getInstance<opengl::Graphics>(Module::M_GRAPHICS);
	Keyboard *keyboard = Module::getInstance<Keyboard>(Module::M_KEYBOARD);

	//RandomGenerator::Seed seed; //will be random
	//math->setRandomSeed(seed);

	//we manually keep track of SDL Events for the sake of Event module conversions that we don't want
	//we can still use part of the event modules to push said conversions to lua

	for (auto module : nersis::moduleList()) {
		module->load();
	}

	timer->step();

	double dt = 0;

	//main loop
	while (true) {
		//process events
		SDL_Event e;
		while (SDL_PollEvent(&e))
		{
			for (auto module : nersis::moduleList()) {
				module->sdlEvent(e);
			}

			switch (e.type)
			{
			case SDL_QUIT:
			case SDL_APP_TERMINATING: {
				bool canQuit = true;
				for (auto module : nersis::moduleList()) {
					bool q = module->quit();
					if (q) {
						printf("module %s requested not to quit! %d\n", module->name.c_str(), q);
						canQuit = false;
						break;
					}
				}
				if (canQuit)
					return 0;
				break;
			}
			case SDL_KEYDOWN: {
				love::keyboard::Keyboard::Key key;
				std::map<SDL_Keycode, love::keyboard::Keyboard::Key>::const_iterator keyit;
				if (e.key.repeat)
				{
					if (!keyboard->hasKeyRepeat())
						break;
				}

				keyit = Event::keys.find(e.key.keysym.sym);
				if (keyit != Event::keys.end())
					key = keyit->second;

				for (auto module : nersis::moduleList()) {
					module->keyPressed(key, e.key.repeat);
				}
				break;
			}
			case SDL_KEYUP: {
				love::keyboard::Keyboard::Key key;
				std::map<SDL_Keycode, love::keyboard::Keyboard::Key>::const_iterator keyit;

				keyit = Event::keys.find(e.key.keysym.sym);
				if (keyit != Event::keys.end())
					key = keyit->second;

				for (auto module : nersis::moduleList()) {
					module->keyReleased(key);
				}
				break;
			}
			case SDL_TEXTINPUT:
				for (auto module : nersis::moduleList()) {
					module->textInput(e.text.text);
				}
				break;
			case SDL_MOUSEMOTION:
				for (auto module : nersis::moduleList()) {
					module->mouseMoved(e.motion.x,e.motion.y,e.motion.xrel,e.motion.yrel);
				}
				break;
			case SDL_MOUSEBUTTONDOWN:
				for (auto module : nersis::moduleList()) {
					module->mousePressed(e.button.x,e.button.y,e.button.button);
				}
				break;
			case SDL_MOUSEBUTTONUP:
				for (auto module : nersis::moduleList()) {
					module->mouseReleased(e.button.x,e.button.y,e.button.button);
				}
				break;
			}
		}

		timer->step();
		dt = timer->getDelta();

		for (auto module : nersis::moduleList()) {
			module->update(dt);
		}

		if (window->isCreated()) {
			graphics->clear();
			graphics->origin();
			for (auto module : nersis::moduleList()) {
				module->draw();
			}
			graphics->present();
		}

		timer->sleep(0.001);
	}

	return 0;
}

static const luaL_Reg nersis_corelib[] = {
	{"hello", nersis_core_hello},
	{"love_run", nersis_core_love_run},
	{NULL, NULL}
};

static int nersis_core_panic(lua_State *L) {
	printf("%s\n",lua_tostring(L,1));
	return 0;
}

LUALIB_API int luaopen_nersis_core(lua_State *L) {
	lua_atpanic(L, nersis_core_panic);
	luaL_register(L, "nersis.core", nersis_corelib);
	return 1;
}


text:
<?php namespace Pantono\Locale\Entity\Repository;

use Pantono\Database\Repository\AbstractRepository;

class CurrencyRepository extends AbstractRepository
{
    /**
     * @param $code
     * @return null|\Pantono\Locale\Entity\Currency
     */
    public function findCurrencyByCode($code)
    {
        return $this->_em->getRepository('Pantono\Locale\Entity\Currency')->findOneBy(['code' => $code]);
    }

    /**
     * @param $hideDisabled
     * @return \Pantono\Locale\Entity\Currency
     */
    public function getCurrencyList($hideDisabled)
    {
        if ($hideDisabled === true) {
            return $this->_em->getRepository('Pantono\Locale\Entity\Currency')->findBy(['enabled' => true]);
        }
        return $this->_em->getRepository('Pantono\Locale\Entity\Currency')->findAll();
    }
}