text:
namespace installer {

namespace {

// Returns true if product |type| cam be meaningfully installed without the
// --multi-install flag.
bool SupportsSingleInstall(BrowserDistribution::Type type) {
  return (type == BrowserDistribution::CHROME_BROWSER ||
          type == BrowserDistribution::CHROME_FRAME);
}

// Returns true if the "lastrun" value in |root|\|key_path| (a path to Chrome's
// ClientState key for a user) indicates that Chrome has been used within the
// last 28 days.
bool IsActivelyUsedIn(HKEY root, const wchar_t* key_path) {
  // This duplicates some logic in GoogleUpdateSettings::GetLastRunTime, which
  // is suitable for use from the context of Chrome but not from the installer
  // because it was implemented with the assumption that
  // BrowserDistribution::GetDistribution() will always be the right thing.
  // This is true in Chrome, but not in the installer in a multi-install world.
  // Once multi-install goes away, this assumption will once again become true
  // for the installer, and this new code here can then be deleted.
  VLOG(1) << "IsActivelyUsedIn probing " << root << "\\" << key_path;
  base::win::RegKey key;
  LONG result = key.Open(root, key_path, KEY_WOW64_32KEY | KEY_QUERY_VALUE);
  if (result != ERROR_SUCCESS) {
    ::SetLastError(result);
    PLOG_IF(ERROR, result != ERROR_FILE_NOT_FOUND) << "Failed opening " << root
                                                   << "\\" << key_path;
    return false;
  }
  base::string16 last_run_time_string;
  result =
      key.ReadValue(google_update::kRegLastRunTimeField, &last_run_time_string);
  if (result != ERROR_SUCCESS) {
    ::SetLastError(result);
    PLOG_IF(ERROR, result != ERROR_FILE_NOT_FOUND)
        << "Failed reading " << root << "\\" << key_path << "@"
        << google_update::kRegLastRunTimeField;
    return false;
  }
  int64_t last_run_time_value = 0;
  if (!base::StringToInt64(last_run_time_string, &last_run_time_value))
    return false;
  base::Time last_run_time = base::Time::FromInternalValue(last_run_time_value);
  int days_ago_last_run =
      (base::Time::NowFromSystemTime() - last_run_time).InDays();
  VLOG(1) << "Found a user that last ran Chrome " << days_ago_last_run
          << " days ago.";
  return days_ago_last_run <= 28;
}

// A visitor for user hives, run by VisitUserHives. |client_state_path| is the
// path to Chrome's ClientState key. |is_used| is set to true if Chrome has been
// used within the last 28 days based on the contents of |user_hive|, in which
// case |false| is returned to halt the hive visits. |user_sid| and |user_hive|
// are provided by VisitUserHives.
bool OnUserHive(const base::string16& client_state_path,
                bool* is_used,
                const wchar_t* user_sid,
                base::win::RegKey* user_hive) {
  // Continue the iteration if this hive isn't owned by an active Chrome user.
  if (!IsActivelyUsedIn(user_hive->Handle(), client_state_path.c_str()))
    return true;
  // Stop the iteration.
  *is_used = true;
  return false;
}

}  // namespace

int CourgettePatchFiles(const base::FilePath& src,
                        const base::FilePath& patch,
                        const base::FilePath& dest) {
  VLOG(1) << "Applying Courgette patch " << patch.value()
          << " to file " << src.value()
          << " and generating file " << dest.value();

  if (src.empty() || patch.empty() || dest.empty())
    return installer::PATCH_INVALID_ARGUMENTS;

  const courgette::Status patch_status =
      courgette::ApplyEnsemblePatch(src.value().c_str(),
                                    patch.value().c_str(),
                                    dest.value().c_str());
  const int exit_code = (patch_status != courgette::C_OK) ?
      static_cast<int>(patch_status) + kCourgetteErrorOffset : 0;

  LOG_IF(ERROR, exit_code)
      << "Failed to apply Courgette patch " << patch.value()
      << " to file " << src.value() << " and generating file " << dest.value()
      << ". err=" << exit_code;

  return exit_code;
}

int BsdiffPatchFiles(const base::FilePath& src,
                     const base::FilePath& patch,
                     const base::FilePath& dest) {
  VLOG(1) << "Applying bsdiff patch " << patch.value()
          << " to file " << src.value()
          << " and generating file " << dest.value();

  if (src.empty() || patch.empty() || dest.empty())
    return installer::PATCH_INVALID_ARGUMENTS;

  const int patch_status = bsdiff::ApplyBinaryPatch(src, patch, dest);
  const int exit_code = patch_status != bsdiff::OK ?
                        patch_status + kBsdiffErrorOffset : 0;

  LOG_IF(ERROR, exit_code)
      << "Failed to apply bsdiff patch " << patch.value()
      << " to file " << src.value() << " and generating file " << dest.value()
      << ". err=" << exit_code;

  return exit_code;
}

Version* GetMaxVersionFromArchiveDir(const base::FilePath& chrome_path) {
  VLOG(1) << "Looking for Chrome version folder under " << chrome_path.value();
  base::FileEnumerator version_enum(chrome_path, false,
      base::FileEnumerator::DIRECTORIES);
  // TODO(tommi): The version directory really should match the version of
  // setup.exe.  To begin with, we should at least DCHECK that that's true.

  std::unique_ptr<Version> max_version(new Version("0.0.0.0"));
  bool version_found = false;

  while (!version_enum.Next().empty()) {
    base::FileEnumerator::FileInfo find_data = version_enum.GetInfo();
    VLOG(1) << "directory found: " << find_data.GetName().value();

    std::unique_ptr<Version> found_version(
        new Version(base::UTF16ToASCII(find_data.GetName().value())));
    if (found_version->IsValid() &&
        found_version->CompareTo(*max_version.get()) > 0) {
      max_version.reset(found_version.release());
      version_found = true;
    }
  }

  return (version_found ? max_version.release() : NULL);
}

base::FilePath FindArchiveToPatch(const InstallationState& original_state,
                                  const InstallerState& installer_state,
                                  const base::Version& desired_version) {
  if (desired_version.IsValid()) {
    base::FilePath archive(installer_state.GetInstallerDirectory(
        desired_version).Append(kChromeArchive));
    return base::PathExists(archive) ? archive : base::FilePath();
  }

  // Check based on the version number advertised to Google Update, since that
  // is the value used to select a specific differential update. If an archive
  // can't be found using that, fallback to using the newest version present.
  base::FilePath patch_source;
  const ProductState* product =
      original_state.GetProductState(installer_state.system_install(),
                                     installer_state.state_type());
  if (product) {
    patch_source = installer_state.GetInstallerDirectory(product->version())
        .Append(installer::kChromeArchive);
    if (base::PathExists(patch_source))
      return patch_source;
  }
  std::unique_ptr<Version> version(
      installer::GetMaxVersionFromArchiveDir(installer_state.target_path()));
  if (version) {
    patch_source = installer_state.GetInstallerDirectory(*version)
        .Append(installer::kChromeArchive);
    if (base::PathExists(patch_source))
      return patch_source;
  }
  return base::FilePath();
}

bool DeleteFileFromTempProcess(const base::FilePath& path,
                               uint32_t delay_before_delete_ms) {
  static const wchar_t kRunDll32Path[] =
      L"%SystemRoot%\\System32\\rundll32.exe";
  wchar_t rundll32[MAX_PATH];
  DWORD size =
      ExpandEnvironmentStrings(kRunDll32Path, rundll32, arraysize(rundll32));
  if (!size || size >= MAX_PATH)
    return false;

  STARTUPINFO startup = { sizeof(STARTUPINFO) };
  PROCESS_INFORMATION pi = {0};
  BOOL ok = ::CreateProcess(NULL, rundll32, NULL, NULL, FALSE, CREATE_SUSPENDED,
                            NULL, NULL, &startup, &pi);
  if (ok) {
    // We use the main thread of the new process to run:
    //   Sleep(delay_before_delete_ms);
    //   DeleteFile(path);
    //   ExitProcess(0);
    // This runs before the main routine of the process runs, so it doesn't
    // matter much which executable we choose except that we don't want to
    // use e.g. a console app that causes a window to be created.
    size = static_cast<DWORD>(
        (path.value().length() + 1) * sizeof(path.value()[0]));
    void* mem = ::VirtualAllocEx(pi.hProcess, NULL, size, MEM_COMMIT,
                                 PAGE_READWRITE);
    if (mem) {
      SIZE_T written = 0;
      ::WriteProcessMemory(
          pi.hProcess, mem, path.value().c_str(),
          (path.value().size() + 1) * sizeof(path.value()[0]), &written);
      HMODULE kernel32 = ::GetModuleHandle(L"kernel32.dll");
      PAPCFUNC sleep = reinterpret_cast<PAPCFUNC>(
          ::GetProcAddress(kernel32, "Sleep"));
      PAPCFUNC delete_file = reinterpret_cast<PAPCFUNC>(
          ::GetProcAddress(kernel32, "DeleteFileW"));
      PAPCFUNC exit_process = reinterpret_cast<PAPCFUNC>(
          ::GetProcAddress(kernel32, "ExitProcess"));
      if (!sleep || !delete_file || !exit_process) {
        NOTREACHED();
        ok = FALSE;
      } else {
        ::QueueUserAPC(sleep, pi.hThread, delay_before_delete_ms);
        ::QueueUserAPC(delete_file, pi.hThread,
                       reinterpret_cast<ULONG_PTR>(mem));
        ::QueueUserAPC(exit_process, pi.hThread, 0);
        ::ResumeThread(pi.hThread);
      }
    } else {
      PLOG(ERROR) << "VirtualAllocEx";
      ::TerminateProcess(pi.hProcess, ~static_cast<UINT>(0));
    }
    ::CloseHandle(pi.hThread);
    ::CloseHandle(pi.hProcess);
  }

  return ok != FALSE;
}

// There are 4 disjoint cases => return values {false,true}:
// (1) Product is being uninstalled => false.
// (2) Product is being installed => true.
// (3) Current operation ignores product, product is absent => false.
// (4) Current operation ignores product, product is present => true.
bool WillProductBePresentAfterSetup(
    const installer::InstallerState& installer_state,
    const installer::InstallationState& machine_state,
    BrowserDistribution::Type type) {
  DCHECK(SupportsSingleInstall(type) || installer_state.is_multi_install());

  const ProductState* product_state =
      machine_state.GetProductState(installer_state.system_install(), type);

  // Determine if the product is present prior to the current operation.
  bool is_present = (product_state != NULL);
  bool is_uninstall = installer_state.operation() == InstallerState::UNINSTALL;

  // Determine if current operation affects the product.
  const Product* product = installer_state.FindProduct(type);
  bool is_affected = (product != NULL);

  // Decide among {(1),(2),(3),(4)}.
  return is_affected ? !is_uninstall : is_present;
}

bool AdjustProcessPriority() {
  if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
    DWORD priority_class = ::GetPriorityClass(::GetCurrentProcess());
    if (priority_class == 0) {
      PLOG(WARNING) << "Failed to get the process's priority class.";
    } else if (priority_class == BELOW_NORMAL_PRIORITY_CLASS ||
               priority_class == IDLE_PRIORITY_CLASS) {
      BOOL result = ::SetPriorityClass(::GetCurrentProcess(),
                                       PROCESS_MODE_BACKGROUND_BEGIN);
      PLOG_IF(WARNING, !result) << "Failed to enter background mode.";
      return !!result;
    }
  }
  return false;
}

void MigrateGoogleUpdateStateMultiToSingle(
    bool system_level,
    BrowserDistribution::Type to_migrate,
    const installer::InstallationState& machine_state) {
  const HKEY root = system_level ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER;
  const ProductState* product = NULL;
  BrowserDistribution* dist = NULL;
  LONG result = ERROR_SUCCESS;
  base::win::RegKey state_key;

  Product product_to_migrate(
      BrowserDistribution::GetSpecificDistribution(to_migrate));

  // Copy usagestats from the binaries to the product's ClientState key.
  product = machine_state.GetProductState(system_level,
                                          BrowserDistribution::CHROME_BINARIES);
  DWORD usagestats = 0;
  if (product && product->GetUsageStats(&usagestats)) {
    dist = product_to_migrate.distribution();
    result = state_key.Open(root, dist->GetStateKey().c_str(),
                            KEY_SET_VALUE);
    if (result != ERROR_SUCCESS) {
      LOG(ERROR) << "Failed opening ClientState key for "
                 << dist->GetDisplayName() << " to migrate usagestats.";
    } else {
      state_key.WriteValue(google_update::kRegUsageStatsField, usagestats);
    }
  }

  // Remove the migrating product from the "ap" value of other multi-install
  // products.
  for (int i = 0; i < BrowserDistribution::NUM_TYPES; ++i) {
    BrowserDistribution::Type type =
        static_cast<BrowserDistribution::Type>(i);
    if (type == to_migrate)
      continue;
    product = machine_state.GetProductState(system_level, type);
    if (product && product->is_multi_install()) {
      installer::ChannelInfo channel_info;
      dist = BrowserDistribution::GetSpecificDistribution(type);
      result = state_key.Open(root, dist->GetStateKey().c_str(),
                              KEY_QUERY_VALUE | KEY_SET_VALUE);
      if (result == ERROR_SUCCESS &&
          channel_info.Initialize(state_key) &&
          product_to_migrate.SetChannelFlags(false, &channel_info)) {
        VLOG(1) << "Moving " << dist->GetDisplayName()
                << " to channel: " << channel_info.value();
        channel_info.Write(&state_key);
      }
    }
  }

  // Remove -multi, all product modifiers, and everything else but the channel
  // name from the "ap" value of the product to migrate.
  dist = product_to_migrate.distribution();
  result = state_key.Open(root, dist->GetStateKey().c_str(),
                          KEY_QUERY_VALUE | KEY_SET_VALUE);
  if (result == ERROR_SUCCESS) {
    installer::ChannelInfo channel_info;
    if (!channel_info.Initialize(state_key)) {
      LOG(ERROR) << "Failed reading " << dist->GetDisplayName()
                 << " channel info.";
    } else if (channel_info.RemoveAllModifiersAndSuffixes()) {
      VLOG(1) << "Moving " << dist->GetDisplayName()
              << " to channel: " << channel_info.value();
      channel_info.Write(&state_key);
    }
  }
}

bool IsUninstallSuccess(InstallStatus install_status) {
  // The following status values represent failed uninstalls:
  // 15: CHROME_NOT_INSTALLED
  // 20: UNINSTALL_FAILED
  // 21: UNINSTALL_CANCELLED
  return (install_status == UNINSTALL_SUCCESSFUL ||
          install_status == UNINSTALL_REQUIRES_REBOOT);
}

bool ContainsUnsupportedSwitch(const base::CommandLine& cmd_line) {
  static const char* const kLegacySwitches[] = {
    // Chrome Frame ready-mode.
    "ready-mode",
    "ready-mode-opt-in",
    "ready-mode-temp-opt-out",
    "ready-mode-end-temp-opt-out",
    // Chrome Frame quick-enable.
    "quick-enable-cf",
    // Installation of Chrome Frame.
    "chrome-frame",
    "migrate-chrome-frame",
    // Stand-alone App Launcher.
    "app-host",
    "app-launcher",
  };
  for (size_t i = 0; i < arraysize(kLegacySwitches); ++i) {
    if (cmd_line.HasSwitch(kLegacySwitches[i]))
      return true;
  }
  return false;
}

bool IsProcessorSupported() {
  return base::CPU().has_sse2();
}

base::string16 GetRegistrationDataCommandKey(
    const AppRegistrationData& reg_data,
    const wchar_t* name) {
  base::string16 cmd_key(reg_data.GetVersionKey());
  cmd_key.append(1, base::FilePath::kSeparators[0])
      .append(google_update::kRegCommandsKey)
      .append(1, base::FilePath::kSeparators[0])
      .append(name);
  return cmd_key;
}

void DeleteRegistryKeyPartial(
    HKEY root,
    const base::string16& path,
    const std::vector<base::string16>& keys_to_preserve) {
  // Downcase the list of keys to preserve (all must be ASCII strings).
  std::set<base::string16> lowered_keys_to_preserve;
  std::transform(
      keys_to_preserve.begin(), keys_to_preserve.end(),
      std::inserter(lowered_keys_to_preserve, lowered_keys_to_preserve.begin()),
      [](const base::string16& str) {
        DCHECK(!str.empty());
        DCHECK(base::IsStringASCII(str));
        return base::ToLowerASCII(str);
      });
  base::win::RegKey key;
  LONG result = key.Open(root, path.c_str(), (KEY_ENUMERATE_SUB_KEYS |
                                              KEY_QUERY_VALUE | KEY_SET_VALUE));
  if (result != ERROR_SUCCESS) {
    LOG_IF(ERROR, result != ERROR_FILE_NOT_FOUND) << "Failed to open " << path
                                                  << "; result = " << result;
    return;
  }

  // Repeatedly iterate over all subkeys deleting those that should not be
  // preserved until only those remain. Multiple passes are needed since
  // deleting one key may change the enumeration order of all remaining keys.

  // Subkeys or values to be skipped on subsequent passes.
  std::set<base::string16> to_skip;
  DWORD index = 0;
  const size_t kMaxKeyNameLength = 256;  // MSDN says 255; +1 for terminator.
  base::string16 name(kMaxKeyNameLength, base::char16());
  bool did_delete = false;  // True if at least one item was deleted.
  while (true) {
    DWORD name_length = base::saturated_cast<DWORD>(name.capacity());
    name.resize(name_length);
    result = ::RegEnumKeyEx(key.Handle(), index, &name[0], &name_length,
                            nullptr, nullptr, nullptr, nullptr);
    if (result == ERROR_MORE_DATA) {
      // Unexpected, but perhaps the max key name length was raised. MSDN
      // doesn't clearly say that name_length will contain the necessary
      // length in this case, so double the buffer and try again.
      name.reserve(name.capacity() * 2);
      continue;
    }
    if (result == ERROR_NO_MORE_ITEMS) {
      if (!did_delete)
        break;  // All subkeys were deleted. The job is done.
      // Otherwise, loop again.
      did_delete = false;
      index = 0;
      continue;
    }
    if (result != ERROR_SUCCESS)
      break;
    // Shrink the string to the actual length of the name.
    name.resize(name_length);

    // Skip over this key if it couldn't be deleted on a previous iteration.
    if (to_skip.count(name)) {
      ++index;
      continue;
    }

    // Skip over this key if it is one of the keys to preserve.
    if (base::IsStringASCII(name) &&
        lowered_keys_to_preserve.count(base::ToLowerASCII(name))) {
      // Add the true name of the key to the list of keys to skip for subsequent
      // iterations.
      to_skip.insert(name);
      ++index;
      continue;
    }

    // Delete this key.
    result = key.DeleteKey(name.c_str());
    if (result != ERROR_SUCCESS) {
      LOG(ERROR) << "Failed to delete subkey " << name << " under path "
                 << path;
      // Skip over this key on subsequent iterations.
      to_skip.insert(name);
      ++index;
      continue;
    }
    did_delete = true;
  }

  // Delete the key if it no longer has any subkeys.
  if (to_skip.empty()) {
    result = key.DeleteEmptyKey(L"");
    LOG_IF(ERROR, result != ERROR_SUCCESS) << "Failed to delete empty key "
                                           << path << "; result: " << result;
    return;
  }

  // Delete all values since subkeys are being preserved.
  to_skip.clear();
  did_delete = false;
  index = 0;
  while (true) {
    DWORD name_length = base::saturated_cast<int16_t>(name.capacity());
    name.resize(name_length);
    result = ::RegEnumValue(key.Handle(), index, &name[0], &name_length,
                            nullptr, nullptr, nullptr, nullptr);
    if (result == ERROR_MORE_DATA) {
      if (name_length <
          static_cast<DWORD>(std::numeric_limits<int16_t>::max())) {
        // Double the space to hold the value name and try again.
        name.reserve(name.capacity() * 2);
        continue;
      }
      // Otherwise, the max has been exceeded. Nothing more to be done.
      break;
    }
    if (result == ERROR_NO_MORE_ITEMS) {
      if (!did_delete)
        break;  // All values were deleted. The job is done.
      // Otherwise, loop again.
      did_delete = false;
      index = 0;
      continue;
    }
    if (result != ERROR_SUCCESS)
      break;
    // Shrink the string to the actual length of the name.
    name.resize(name_length);

    // Skip over this value if it couldn't be deleted on a previous iteration.
    if (to_skip.count(name)) {
      ++index;
      continue;
    }

    // Delete this value.
    result = key.DeleteValue(name.c_str());
    if (result != ERROR_SUCCESS) {
      LOG(ERROR) << "Failed to delete value " << name << " in key " << path;
      // Skip over this value on subsequent iterations.
      to_skip.insert(name);
      ++index;
      continue;
    }
    did_delete = true;
  }
}

base::string16 GuidToSquid(const base::string16& guid) {
  base::string16 squid;
  squid.reserve(32);
  auto input = guid.begin();
  auto output = std::back_inserter(squid);

  // Reverse-copy relevant characters, skipping separators.
  std::reverse_copy(input + 0, input + 8, output);
  std::reverse_copy(input + 9, input + 13, output);
  std::reverse_copy(input + 14, input + 18, output);
  std::reverse_copy(input + 19, input + 21, output);
  std::reverse_copy(input + 21, input + 23, output);
  std::reverse_copy(input + 24, input + 26, output);
  std::reverse_copy(input + 26, input + 28, output);
  std::reverse_copy(input + 28, input + 30, output);
  std::reverse_copy(input + 30, input + 32, output);
  std::reverse_copy(input + 32, input + 34, output);
  std::reverse_copy(input + 34, input + 36, output);
  return squid;
}

bool IsDowngradeAllowed(const MasterPreferences& prefs) {
  bool allow_downgrade = false;
  return prefs.GetBool(master_preferences::kAllowDowngrade, &allow_downgrade) &&
         allow_downgrade;
}

bool IsChromeActivelyUsed(const InstallerState& installer_state) {
  BrowserDistribution* chrome_dist =
      BrowserDistribution::GetSpecificDistribution(
          BrowserDistribution::CHROME_BROWSER);
  if (!installer_state.system_install()) {
    return IsActivelyUsedIn(HKEY_CURRENT_USER,
                            chrome_dist->GetStateKey().c_str());
  }
  bool is_used = false;
  VisitUserHives(base::Bind(&OnUserHive, chrome_dist->GetStateKey(),
                            base::Unretained(&is_used)));
  return is_used;
}

ScopedTokenPrivilege::ScopedTokenPrivilege(const wchar_t* privilege_name)
    : is_enabled_(false) {
  HANDLE temp_handle;
  if (!::OpenProcessToken(::GetCurrentProcess(),
                          TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,
                          &temp_handle)) {
    return;
  }
  token_.Set(temp_handle);

  LUID privilege_luid;
  if (!::LookupPrivilegeValue(NULL, privilege_name, &privilege_luid)) {
    token_.Close();
    return;
  }

  // Adjust the token's privileges to enable |privilege_name|. If this privilege
  // was already enabled, |previous_privileges_|.PrivilegeCount will be set to 0
  // and we then know not to disable this privilege upon destruction.
  TOKEN_PRIVILEGES tp;
  tp.PrivilegeCount = 1;
  tp.Privileges[0].Luid = privilege_luid;
  tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  DWORD return_length;
  if (!::AdjustTokenPrivileges(token_.Get(), FALSE, &tp,
                               sizeof(TOKEN_PRIVILEGES),
                               &previous_privileges_, &return_length)) {
    token_.Close();
    return;
  }

  is_enabled_ = true;
}

ScopedTokenPrivilege::~ScopedTokenPrivilege() {
  if (is_enabled_ && previous_privileges_.PrivilegeCount != 0) {
    ::AdjustTokenPrivileges(token_.Get(), FALSE, &previous_privileges_,
                            sizeof(TOKEN_PRIVILEGES), NULL, NULL);
  }
}

}  // namespace installer


text:
<?php
// Allow OAuthSimple to be autoloaded instead of always including directly.
// The class_exists() call fires the autoloader.
if (! class_exists ( 'OAuthSimple' )) {
	require_once __DIR__ . DIRECTORY_SEPARATOR . 'OAuthSimple.php';
}

/**
 * Define a custom Exception for easy trap and detection
 */
class XeroOAuthException extends Exception {
}
class XeroOAuth {
	var $_xero_defaults;
	var $_xero_consumer_options;
	var $_action;
	var $_nonce_chars;

	/**
	 * Creates a new XeroOAuth object
	 *
	 * @param string $config,
	 *        	the configuration settings
	 */
	function __construct($config) {
		$this->params = array ();
		$this->headers = array ();
		$this->auto_fixed_time = false;
		$this->buffer = null;
		$this->request_params = array();

		if (! empty ( $config ['application_type'] )) {
			switch ($config ['application_type']) {
				case "Public" :
					$this->_xero_defaults = array (
							'xero_url' => 'https://api.xero.com/',
							'site' => 'https://api.xero.com',
							'authorize_url' => 'https://api.xero.com/oauth/Authorize',
							'signature_method' => 'HMAC-SHA1'
					);
					break;
				case "Private" :
					$this->_xero_defaults = array (
							'xero_url' => 'https://api.xero.com/',
							'site' => 'https://api.xero.com',
							'authorize_url' => 'https://api.xero.com/oauth/Authorize',
							'signature_method' => 'RSA-SHA1'
					);
					break;
				case "Partner" :
					$this->_xero_defaults = array (
							'xero_url' => 'https://api.xero.com/',
							'site' => 'https://api.xero.com',
							'authorize_url' => 'https://api.xero.com/oauth/Authorize',
							'signature_method' => 'RSA-SHA1'
					);
					break;
			}
		}

		$this->_xero_consumer_options = array (
				'request_token_path' => 'oauth/RequestToken',
				'access_token_path' => 'oauth/AccessToken',
				'authorize_path' => 'oauth/Authorize'
		);

		// Remove forced dependency on BASE_PATH constant.
		// Note that __DIR__ is PHP 5.3 and above only.
		$base_path = defined ( 'BASE_PATH' ) ? BASE_PATH : dirname ( __DIR__ );

		$this->_xero_curl_options = array ( // you probably don't want to change any of these curl values
				'curl_connecttimeout' => 30,
				'curl_timeout' => 20,
				// for security you may want to set this to TRUE. If you do you need
				// to install the servers certificate in your local certificate store.
				'curl_ssl_verifypeer' => 2,
				// include ca-bundle.crt from http://curl.haxx.se/ca/cacert.pem
				'curl_cainfo' => $base_path . '/certs/ca-bundle.crt',
				'curl_followlocation' => false, // whether to follow redirects or not
				                                // TRUE/1 is not a valid ssl verifyhost value with curl >= 7.28.1 and 2 is more secure as well.
				                                // More details here: http://php.net/manual/en/function.curl-setopt.php
				'curl_ssl_verifyhost' => 2,
				// support for proxy servers
				'curl_proxy' => false, // really you don't want to use this if you are using streaming
				'curl_proxyuserpwd' => false, // format username:password for proxy, if required
				'curl_encoding' => '', // leave blank for all supported formats, else use gzip, deflate, identity
				'curl_verbose' => true
		);

		$this->config = array_merge ( $this->_xero_defaults, $this->_xero_consumer_options, $this->_xero_curl_options, $config );
	}

	/**
	 * Utility function to parse the returned curl headers and store them in the
	 * class array variable.
	 *
	 * @param object $ch
	 *        	curl handle
	 * @param string $header
	 *        	the response headers
	 * @return the string length of the header
	 */
	private function curlHeader($ch, $header) {
		$i = strpos ( $header, ':' );
		if (! empty ( $i )) {
			$key = str_replace ( '-', '_', strtolower ( substr ( $header, 0, $i ) ) );
			$value = trim ( substr ( $header, $i + 2 ) );
			$this->response ['headers'] [$key] = $value;
		}
		return strlen ( $header );
	}

	/**
	 * Utility function to parse the returned curl buffer and store them until
	 * an EOL is found.
	 * The buffer for curl is an undefined size so we need
	 * to collect the content until an EOL is found.
	 *
	 * This function calls the previously defined streaming callback method.
	 *
	 * @param object $ch
	 *        	curl handle
	 * @param string $data
	 *        	the current curl buffer
	 */
	private function curlWrite($ch, $data) {
		$l = strlen ( $data );
		if (strpos ( $data, $this->config ['streaming_eol'] ) === false) {
			$this->buffer .= $data;
			return $l;
		}

		$buffered = explode ( $this->config ['streaming_eol'], $data );
		$content = $this->buffer . $buffered [0];

		$this->metrics ['tweets'] ++;
		$this->metrics ['bytes'] += strlen ( $content );

		if (! function_exists ( $this->config ['streaming_callback'] ))
			return 0;

		$metrics = $this->update_metrics ();
		$stop = call_user_func ( $this->config ['streaming_callback'], $content, strlen ( $content ), $metrics );
		$this->buffer = $buffered [1];
		if ($stop)
			return 0;

		return $l;
	}

	/**
	 * Extracts and decodes OAuth parameters from the passed string
	 *
	 * @param string $body
	 *        	the response body from an OAuth flow method
	 * @return array the response body safely decoded to an array of key => values
	 */
	function extract_params($body) {
		$kvs = explode ( '&', $body );
		$decoded = array ();
		foreach ( $kvs as $kv ) {
			$kv = explode ( '=', $kv, 2 );
			$kv [0] = $this->safe_decode ( $kv [0] );
			$kv [1] = $this->safe_decode ( $kv [1] );
			$decoded [$kv [0]] = $kv [1];
		}
		return $decoded;
	}

	/**
	 * Encodes the string or array passed in a way compatible with OAuth.
	 * If an array is passed each array value will will be encoded.
	 *
	 * @param mixed $data
	 *        	the scalar or array to encode
	 * @return $data encoded in a way compatible with OAuth
	 */
	private function safe_encode($data) {
		if (is_array ( $data )) {
			return array_map ( array (
					$this,
					'safe_encode'
			), $data );
		} else if (is_scalar ( $data )) {
			return str_ireplace ( array (
					'+',
					'%7E'
			), array (
					' ',
					'~'
			), rawurlencode ( $data ) );
		} else {
			return '';
		}
	}

	/**
	 * Decodes the string or array from it's URL encoded form
	 * If an array is passed each array value will will be decoded.
	 *
	 * @param mixed $data
	 *        	the scalar or array to decode
	 * @return $data decoded from the URL encoded form
	 */
	private function safe_decode($data) {
		if (is_array ( $data )) {
			return array_map ( array (
					$this,
					'safe_decode'
			), $data );
		} else if (is_scalar ( $data )) {
			return rawurldecode ( $data );
		} else {
			return '';
		}
	}

	/**
	 * Prepares the HTTP method for use in the base string by converting it to
	 * uppercase.
	 *
	 * @param string $method
	 *        	an HTTP method such as GET or POST
	 * @return void value is stored to a class variable
	 * @author themattharris
	 */
	private function prepare_method($method) {
		$this->method = strtoupper ( $method );
	}

	/**
	 * Makes a curl request.
	 * Takes no parameters as all should have been prepared
	 * by the request method
	 *
	 * @return void response data is stored in the class variable 'response'
	 */
	private function curlit() {
		$this->request_params = array();

		// configure curl
		$c = curl_init ();
		$useragent = (isset ( $this->config ['user_agent'] )) ? (empty ( $this->config ['user_agent'] ) ? 'XeroOAuth-PHP' : $this->config ['user_agent']) : 'XeroOAuth-PHP';
		curl_setopt_array ( $c, array (
				CURLOPT_USERAGENT => $useragent,
				CURLOPT_CONNECTTIMEOUT => $this->config ['curl_connecttimeout'],
				CURLOPT_TIMEOUT => $this->config ['curl_timeout'],
				CURLOPT_RETURNTRANSFER => TRUE,
				CURLOPT_SSL_VERIFYPEER => $this->config ['curl_ssl_verifypeer'],
				CURLOPT_CAINFO => $this->config ['curl_cainfo'],
				CURLOPT_SSL_VERIFYHOST => $this->config ['curl_ssl_verifyhost'],
				CURLOPT_FOLLOWLOCATION => $this->config ['curl_followlocation'],
				CURLOPT_PROXY => $this->config ['curl_proxy'],
				CURLOPT_ENCODING => $this->config ['curl_encoding'],
				CURLOPT_URL => $this->sign ['signed_url'],
				CURLOPT_VERBOSE => $this->config ['curl_verbose'],
				// process the headers
				CURLOPT_HEADERFUNCTION => array (
						$this,
						'curlHeader'
				),
				CURLOPT_HEADER => FALSE,
				CURLINFO_HEADER_OUT => TRUE
		) );

		/* ENTRUST CERTIFICATE DEPRECATED
		if ($this->config ['application_type'] == "Partner") {
			curl_setopt_array ( $c, array (
					// ssl client cert options for partner apps
					CURLOPT_SSLCERT => $this->config ['curl_ssl_cert'],
					CURLOPT_SSLKEYPASSWD => $this->config ['curl_ssl_password'],
					CURLOPT_SSLKEY => $this->config ['curl_ssl_key']
			) );
		}
		*/

		if ($this->config ['curl_proxyuserpwd'] !== false)
			curl_setopt ( $c, CURLOPT_PROXYUSERPWD, $this->config ['curl_proxyuserpwd'] );

		if (isset ( $this->config ['is_streaming'] )) {
			// process the body
			$this->response ['content-length'] = 0;
			curl_setopt ( $c, CURLOPT_TIMEOUT, 0 );
			curl_setopt ( $c, CURLOPT_WRITEFUNCTION, array (
					$this,
					'curlWrite'
			) );
		}

		switch ($this->method) {
			case 'GET' :
				$contentLength = 0;
				break;
			case 'POST' :
				curl_setopt ( $c, CURLOPT_POST, TRUE );
				$post_body = $this->safe_encode ( $this->xml );
				curl_setopt ( $c, CURLOPT_POSTFIELDS, $post_body );
				$this->request_params ['xml'] = $post_body;
				$contentLength = strlen ( $post_body );
				$this->headers ['Content-Type'] = 'application/x-www-form-urlencoded';

				break;
			case 'PUT' :
				$fh = tmpfile();
				if ($this->format == "file") {
					$put_body = $this->xml;
				} else {
					$put_body = $this->safe_encode ( $this->xml );
					$this->headers ['Content-Type'] = 'application/x-www-form-urlencoded';
				}
				fwrite ( $fh, $put_body );
				rewind ( $fh );
				curl_setopt ( $c, CURLOPT_PUT, true );
				curl_setopt ( $c, CURLOPT_INFILE, $fh );
				curl_setopt ( $c, CURLOPT_INFILESIZE, strlen ( $put_body ) );
				$contentLength = strlen ( $put_body );

				break;
			default :
				curl_setopt ( $c, CURLOPT_CUSTOMREQUEST, $this->method );
		}

		if (! empty ( $this->request_params )) {
			// if not doing multipart we need to implode the parameters
			if (! $this->config ['multipart']) {
				foreach ( $this->request_params as $k => $v ) {
					$ps [] = "{$k}={$v}";
				}
				$this->request_payload = implode ( '&', $ps );
			}
			curl_setopt ( $c, CURLOPT_POSTFIELDS, $this->request_payload);
		} else {
			// CURL will set length to -1 when there is no data
			$this->headers ['Content-Length'] = $contentLength;
		}

		$this->headers ['Expect'] = '';

		if (! empty ( $this->headers )) {
			foreach ( $this->headers as $k => $v ) {
				$headers [] = trim ( $k . ': ' . $v );
			}
			curl_setopt ( $c, CURLOPT_HTTPHEADER, $headers );
		}

		if (isset ( $this->config ['prevent_request'] ) && false == $this->config ['prevent_request'])
			return;

			// do it!
		$response = curl_exec ( $c );
		if ($response === false) {
			$response = 'Curl error: ' . curl_error ( $c );
			$code = 1;
		} else {
			$code = curl_getinfo ( $c, CURLINFO_HTTP_CODE );
		}

		$info = curl_getinfo ( $c );

		curl_close ( $c );
		if (isset ( $fh )) {
			fclose( $fh );
		}

		// store the response
		$this->response ['code'] = $code;
		$this->response ['response'] = $response;
		$this->response ['info'] = $info;
		$this->response ['format'] = $this->format;
		return $code;
	}

	/**
	 * Make an HTTP request using this library.
	 * This method doesn't return anything.
	 * Instead the response should be inspected directly.
	 *
	 * @param string $method
	 *        	the HTTP method being used. e.g. POST, GET, HEAD etc
	 * @param string $url
	 *        	the request URL without query string parameters
	 * @param array $params
	 *        	the request parameters as an array of key=value pairs
	 * @param string $format
	 *        	the format of the response. Default json. Set to an empty string to exclude the format
	 *
	 */
	function request($method, $url, $params = array(), $xml = "", $format = 'xml') {
		// removed these as function parameters for now
		$useauth = true;
		$multipart = false;
		$this->headers = array ();

		if (isset ( $format )) {
			switch ($format) {
				case "pdf" :
					$this->headers ['Accept'] = 'application/pdf';
					break;
				case "json" :
					$this->headers ['Accept'] = 'application/json';
					break;
				case "xml" :
				default :
					$this->headers ['Accept'] = 'application/xml';
					break;
			}
		}

		if (isset ( $params ['If-Modified-Since'] )) {
			$modDate = "If-Modified-Since: " . $params ['If-Modified-Since'];
			$this->headers ['If-Modified-Since'] = $params ['If-Modified-Since'];
		}

		if ($xml !== "") {
			$xml = trim($xml);
			$this->xml = $xml;
		}

		if ($method == "POST")
			$params ['xml'] = $xml;

		$this->prepare_method ( $method );
		$this->config ['multipart'] = $multipart;
		$this->url = $url;
		$oauthObject = new OAuthSimple ();
		try {
			$this->sign = $oauthObject->sign ( array (
					'path' => $url,
					'action' => $method,
					'parameters' => array_merge ( $params, array (
							'oauth_signature_method' => $this->config ['signature_method']
					) ),
					'signatures' => $this->config
			) );
		}

		catch ( Exception $e ) {
			$errorMessage = 'XeroOAuth::request() ' . $e->getMessage ();
			$this->response['response'] = $errorMessage;
			$this->response['helper'] = $url;
			return $this->response;
		}
		$this->format = $format;

		$curlRequest = $this->curlit ();

		if ($this->response ['code'] == 401 && isset ( $this->config ['session_handle'] )) {
			if ((strpos ( $this->response ['response'], "oauth_problem=token_expired" ) !== false)) {
				$this->response ['helper'] = "TokenExpired";
			} else {
				$this->response ['helper'] = "TokenFatal";
			}
		}
		if ($this->response ['code'] == 403) {
			$errorMessage = "It looks like your Xero Entrust cert issued by Xero is either invalid or has expired. See http://developer.xero.com/api-overview/http-response-codes/#403 for more";
			// default IIS page isn't informative, a little swap
			$this->response ['response'] = $errorMessage;
			$this->response ['helper'] = "SetupIssue";
		}
		if ($this->response ['code'] == 0) {
			$errorMessage = "It looks like your Xero Entrust cert issued by Xero is either invalid or has expired. See http://developer.xero.com/api-overview/http-response-codes/#403 for more";
			$this->response ['response'] = $errorMessage;
			$this->response ['helper'] = "SetupIssue";
		}

		return $this->response;
	}

	/**
	 * Convert the response into usable data
	 *
	 * @param string $response
	 *        	the raw response from the API
	 * @param string $format
	 *        	the format of the response
	 * @return string the concatenation of the host, API version and API method
	 */
	function parseResponse($response, $format) {
		if (isset ( $format )) {
			switch ($format) {
				case "pdf" :
					$theResponse = $response;
					break;
				case "json" :
					$theResponse = json_decode ( $response );
					break;
				default :
					$theResponse = simplexml_load_string ( $response );
					break;
			}
		}
		return $theResponse;
	}

	/**
	 * Utility function to create the request URL in the requested format
	 *
	 * @param string $request
	 *        	the API method without extension
	 * @return string the concatenation of the host, API version and API method
	 */
	function url($request, $api = "core") {
		if ($request == "RequestToken") {
			$this->config ['host'] = $this->config ['site'] . '/oauth/';
		} elseif ($request == "Authorize") {
			$this->config ['host'] = $this->config ['authorize_url'];
			$request = "";
		} elseif ($request == "AccessToken") {
			$this->config ['host'] = $this->config ['site'] . '/oauth/';
		} else {
			if (isset ( $api )) {
				if ($api == "core") {
					$api_stem = "api.xro";
					$api_version = $this->config ['core_version'];
				}
				if ($api == "payroll") {
					$api_stem = "payroll.xro";
					$api_version = $this->config ['payroll_version'];
				}
				if ($api == "file") {
					$api_stem = "files.xro";
					$api_version = $this->config ['file_version'];
				}
			}
			$this->config ['host'] = $this->config ['xero_url'] . $api_stem . '/' . $api_version . '/';
		}

		return implode ( array (
				$this->config ['host'],
				$request
		) );
	}

	/**
	 * Refreshes the access token for partner API type applications
	 *
	 * @param string $accessToken
	 *        	the current access token for the session
	 * @param string $sessionHandle
	 *        	the current session handle for the session
	 * @return array response array from request
	 */
	function refreshToken($accessToken, $sessionHandle) {
		$code = $this->request ( 'GET', $this->url ( 'AccessToken', '' ), array (
				'oauth_token' => $accessToken,
				'oauth_session_handle' => $sessionHandle
		) );
		if ($this->response ['code'] == 200) {

			$response = $this->extract_params ( $this->response ['response'] );

			return $response;
		} else {
			$this->response ['helper'] = "TokenFatal";
			return $this->response;
		}
	}

	/**
	 * Returns the current URL.
	 * This is instead of PHP_SELF which is unsafe
	 *
	 * @param bool $dropqs
	 *        	whether to drop the querystring or not. Default true
	 * @return string the current URL
	 */
	public static function php_self($dropqs = true)
	{
	$protocol = 'http';
	if (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on')
		{
		$protocol = 'https';
		}
	elseif (isset($_SERVER['SERVER_PORT']) && ($_SERVER['SERVER_PORT'] == '443'))
		{
		$protocol = 'https';
		}

	$url = sprintf('%s://%s%s', $protocol, $_SERVER['SERVER_NAME'], $_SERVER['REQUEST_URI']);
	$parts = parse_url($url);
	$port = $_SERVER['SERVER_PORT'];
	$scheme = $parts['scheme'];
	$host = $parts['host'];
	$path = @$parts['path'];
	$qs = @$parts['query'];
	$port or $port = ($scheme == 'https') ? '443' : '80';
	if (($scheme == 'https' && $port != '443') || ($scheme == 'http' && $port != '80'))
		{
		$host = "$host:$port";
		}

	$url = "$scheme://$host$path";
	if (!$dropqs) return "{$url}?{$qs}";
	  else return $url;
	}

	/*
	 * Run some basic checks on our config options etc to make sure all is ok
	 */
	function diagnostics() {
		$testOutput = array ();

		/* ENTRUST CERTIFICATE DEPRECATED
		if ($this->config ['application_type'] == 'Partner') {
			if (! file_get_contents ( $this->config ['curl_ssl_cert'] )) {
				$testOutput ['ssl_cert_error'] = "Can't read the Xero Entrust cert. You need one for partner API applications. http://developer.xero.com/documentation/getting-started/partner-applications/ \n";
			} else {
				$data = openssl_x509_parse ( file_get_contents ( $this->config ['curl_ssl_cert'] ) );
				$validFrom = date ( 'Y-m-d H:i:s', $data ['validFrom_time_t'] );
				if (time () < $data ['validFrom_time_t']) {
					$testOutput ['ssl_cert_error'] = "Xero Entrust cert not yet valid - cert valid from " . $validFrom . "\n";
				}
				$validTo = date ( 'Y-m-d H:i:s', $data ['validTo_time_t'] );
				if (time () > $data ['validTo_time_t']) {
					$testOutput ['ssl_cert_error'] = "Xero Entrust cert expired - cert valid to " . $validFrom . "\n";
				}
			}
		}
		*/

		if ($this->config ['application_type'] == 'Partner' || $this->config ['application_type'] == 'Private') {

			if (! file_exists ( $this->config ['rsa_public_key'] ))
				$testOutput ['rsa_cert_error'] = "Can't read the self-signed SSL cert. Private and Partner API applications require a self-signed X509 cert http://developer.xero.com/documentation/advanced-docs/public-private-keypair/ \n";
			if (file_exists ( $this->config ['rsa_public_key'] )) {
				$data = openssl_x509_parse ( file_get_contents ( $this->config ['rsa_public_key'] ) );
				$validFrom = date ( 'Y-m-d H:i:s', $data ['validFrom_time_t'] );
				if (time () < $data ['validFrom_time_t']) {
					$testOutput ['ssl_cert_error'] = "Application cert not yet valid - cert valid from " . $validFrom . "\n";
				}
				$validTo = date ( 'Y-m-d H:i:s', $data ['validTo_time_t'] );
				if (time () > $data ['validTo_time_t']) {
					$testOutput ['ssl_cert_error'] = "Application cert cert expired - cert valid to " . $validFrom . "\n";
				}
			}
			if (! file_exists ( $this->config ['rsa_private_key'] ))
				$testOutput ['rsa_cert_error'] = "Can't read the self-signed cert key. Check your rsa_private_key config variable. Private and Partner API applications require a self-signed X509 cert http://developer.xero.com/documentation/advanced-docs/public-private-keypair/ \n";
			if (file_exists ( $this->config ['rsa_private_key'] )) {
				$cert_content = file_get_contents ( $this->config ['rsa_public_key'] );
				$priv_key_content = file_get_contents ( $this->config ['rsa_private_key'] );
				if (! openssl_x509_check_private_key ( $cert_content, $priv_key_content ))
					$testOutput ['rsa_cert_error'] = "Application certificate and key do not match \n";
				;
			}
		}

		return $testOutput;
	}
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Application\Migrations;

use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;

/**
 * Auto-generated Migration: Please modify to your needs!
 */
class Version20160220133236 extends AbstractMigration
{
    /**
     * @param Schema $schema
     */
    public function up(Schema $schema)
    {
        // this up() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('CREATE TABLE configuration (field VARCHAR(255) NOT NULL, value LONGTEXT DEFAULT NULL, PRIMARY KEY(field)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB');
        $this->addSql('ALTER TABLE user_group DROP managed');
    }

    /**
     * @param Schema $schema
     */
    public function down(Schema $schema)
    {
        // this down() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('DROP TABLE configuration');
        $this->addSql('ALTER TABLE user_group ADD managed TINYINT(1) DEFAULT \'0\' NOT NULL');
    }
}


text:
package com.netflix.msl.io;

import java.io.InputStream;
import java.io.Reader;
import java.nio.charset.StandardCharsets;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import com.netflix.msl.MslConstants;
import com.netflix.msl.MslInternalException;

/**
 *
Create a new {@link MslTokenizer} that parses JSON-encoded MSL
 * messages.

 *
 *
This implementation is backed by {@code org.json}.

 *
 * @author Wesley Miaw <wmiaw@netflix.com>
 */
public class JsonMslTokenizer extends MslTokenizer {
    /**
     *
Create a new JSON MSL tokenzier that will read data off the provided
     * input stream.

     *
     * @param encoder MSL encoder factory.
     * @param source JSON input stream.
     */
    public JsonMslTokenizer(final MslEncoderFactory encoder, final InputStream source) {
        this.encoder = encoder;
        // We cannot use the standard {@code InputStreamReader} to support
        // UTF-8 decoding because it makes use of {@code StreamDecoder} which
        // will read {@code StreamDecoder.DEFAULT_BYTE_BUFFER_SIZE} bytes by
        // default, and enforces a minimum of
        // {@code StreamDecoder.MIN_BYTE_BUFFER_SIZE}. This will consume extra
        // bytes and prevent the input stream from being used for future MSL
        // messages.
        //
        // {@code JSONTokener} will consume one character at a time, but will
        // default to a {@code BufferedReader} with the default buffer size if
        // an {@code InputStream} or {@code Reader} is provided that does not
        // support mark, which will also consume extra bytes and prevent reuse
        // of the input stream.
        //
        // Ensure none of that occurs and that only the minimum number of bytes
        // are consumed by explicitly using the {@code ThriftyUtf8Reader} which
        // reads characters one at a time and also supports mark.
        //
        // Make sure we're trying to parse UTF-8 data.
        if (StandardCharsets.UTF_8 != MslConstants.DEFAULT_CHARSET)
            throw new MslInternalException("Charset " + MslConstants.DEFAULT_CHARSET + " unsupported.");
        final Reader reader = new ThriftyUtf8Reader(source);
        this.tokenizer = new JSONTokener(reader);
    }

    /* (non-Javadoc)
     * @see com.netflix.msl.io.MslTokenizer#next(int)
     */
    @Override
    protected MslObject next(final int timeout) throws MslEncoderException {
        try {
            if (!tokenizer.more())
                return null;
            final Object o = tokenizer.nextValue();
            if (o instanceof JSONObject)
                return new JsonMslObject(encoder, (JSONObject)o);
            throw new MslEncoderException("JSON value is not a JSON object.");
        } catch (final JSONException e) {
            throw new MslEncoderException("JSON syntax error.", e);
        }
    }

    /** MSL encoder factory. */
    private final MslEncoderFactory encoder;
    /** JSON tokenizer. */
    private final JSONTokener tokenizer;
}


text:
import logging
import time

import psutil

from icrawl_plugin import IVMCrawler
from utils.features import MetricFeature

try:
    import psvmi
except ImportError:
    psvmi = None

logger = logging.getLogger('crawlutils')

class MetricVmCrawler(IVMCrawler):

    """
    To calculate rates like packets sent per second, we need to
    store the last measurement. We store it in this dictionary.
    """

    def __init__(self):
        self._cached_values = {}

    def _cache_put_value(self, key, value):
        self._cached_values[key] = (value, time.time())

    def _cache_get_value(self, key):
        if key in self._cached_values:
            return self._cached_values[key]
        else:
            return None, None

    def _crawl_metrics_cpu_percent(self, process):
        p = process
        cpu_percent = 0

        feature_key = '{0}-{1}'.format('process', p.ident())
        cache_key = '{0}-{1}'.format('OUTVM', feature_key)

        curr_proc_cpu_time, curr_sys_cpu_time = p.get_cpu_times()

        (cputimeList, timestamp) = self._cache_get_value(cache_key)
        self._cache_put_value(
            cache_key, [curr_proc_cpu_time, curr_sys_cpu_time])

        if cputimeList is not None:
            prev_proc_cpu_time = cputimeList[0]
            prev_sys_cpu_time = cputimeList[1]

            if prev_proc_cpu_time and prev_sys_cpu_time:
                if curr_proc_cpu_time == -1 or prev_proc_cpu_time == -1:
                    cpu_percent = -1  # unsupported for this VM
                else:
                    if curr_sys_cpu_time == prev_sys_cpu_time:
                        cpu_percent = 0
                    else:
                        cpu_percent = (float(curr_proc_cpu_time -
                                             prev_proc_cpu_time) * 100 /
                                       float(curr_sys_cpu_time -
                                             prev_sys_cpu_time))

        return cpu_percent

    def crawl(self, vm_desc, **kwargs):

        created_since = -1
        logger.debug('Crawling Metrics')

        if psvmi is None:
            raise NotImplementedError()
        else:
            (domain_name, kernel_version, distro, arch) = vm_desc
            # XXX: this has to be read from some cache instead of
            # instead of once per plugin/feature
            vm_context = psvmi.context_init(
                domain_name, domain_name, kernel_version, distro, arch)
            list = psvmi.process_iter(vm_context)

        for p in list:
            create_time = (
                p.create_time() if hasattr(
                    p.create_time,
                    '__call__') else p.create_time)
            if create_time <= created_since:
                continue

            name = (p.name() if hasattr(p.name, '__call__'
                                        ) else p.name)
            pid = (p.pid() if hasattr(p.pid, '__call__') else p.pid)
            status = (p.status() if hasattr(p.status, '__call__'
                                            ) else p.status)
            if status == psutil.STATUS_ZOMBIE:
                continue
            username = (
                p.username() if hasattr(
                    p.username,
                    '__call__') else p.username)
            meminfo = (
                p.get_memory_info() if hasattr(
                    p.get_memory_info,
                    '__call__') else p.memory_info)
            ioinfo = (
                p.get_io_counters() if hasattr(
                    p.get_io_counters,
                    '__call__') else p.io_counters)

            cpu_percent = self._crawl_metrics_cpu_percent(p)

            memory_percent = (
                p.get_memory_percent() if hasattr(
                    p.get_memory_percent,
                    '__call__') else p.memory_percent)

            feature_key = '{0}/{1}'.format(name, pid)
            yield (feature_key, MetricFeature(
                round(cpu_percent, 2),
                round(memory_percent, 2),
                name,
                pid,
                ioinfo.read_bytes,
                meminfo.rss,
                str(status),
                username,
                meminfo.vms,
                ioinfo.write_bytes,
            ), 'metric')

    def get_feature(self):
        return 'metric'


text:
INPUT=$1
OUTPUT=$2
STANDARD_COMPRESSION=$3
SMALL_PIXEL_LIMIT=$4
SMALL_COMPRESSION=$5

# ---

XPATH_SCRIPT="number(//key[text()='pixelWidth']/following-sibling::integer[1]) * number(//key[text()='pixelHeight']/following-sibling::integer[1]) < $SMALL_PIXEL_LIMIT"

COMPRESSION=$STANDARD_COMPRESSION
if [ -n "`sips -g allxml "$INPUT" | xmllint --xpath "$XPATH_SCRIPT" - | grep true`" ]; then
    COMPRESSION=$SMALL_COMPRESSION
fi

SEMIOUTPUT=$OUTPUT.bmp

convert "$INPUT" "$SEMIOUTPUT"
opj_compress -i "$SEMIOUTPUT" -o "$OUTPUT" -r $COMPRESSION
rm "$SEMIOUTPUT"


text:
  <title>Container Networking</title>
  <para>
    When you create a container using
    <literal>nixos-container create</literal>, it gets it own private
    IPv4 address in the range <literal>10.233.0.0/16</literal>. You can
    get the container's IPv4 address as follows:
  </para>
  <programlisting>
# nixos-container show-ip foo
10.233.4.2

$ ping -c1 10.233.4.2
64 bytes from 10.233.4.2: icmp_seq=1 ttl=64 time=0.106 ms
</programlisting>
  <para>
    Networking is implemented using a pair of virtual Ethernet devices.
    The network interface in the container is called
    <literal>eth0</literal>, while the matching interface in the host is
    called <literal>ve-container-name</literal> (e.g.,
    <literal>ve-foo</literal>). The container has its own network
    namespace and the <literal>CAP_NET_ADMIN</literal> capability, so it
    can perform arbitrary network configuration such as setting up
    firewall rules, without affecting or having access to the host's
    network.
  </para>
  <para>
    By default, containers cannot talk to the outside network. If you
    want that, you should set up Network Address Translation (NAT) rules
    on the host to rewrite container traffic to use your external IP
    address. This can be accomplished using the following configuration
    on the host:
  </para>
  <programlisting language="bash">
networking.nat.enable = true;
networking.nat.internalInterfaces = ["ve-+"];
networking.nat.externalInterface = "eth0";
</programlisting>
  <para>
    where <literal>eth0</literal> should be replaced with the desired
    external interface. Note that <literal>ve-+</literal> is a wildcard
    that matches all container interfaces.
  </para>
  <para>
    If you are using Network Manager, you need to explicitly prevent it
    from managing container interfaces:
  </para>
  <programlisting language="bash">
networking.networkmanager.unmanaged = [ "interface-name:ve-*" ];
</programlisting>
  <para>
    You may need to restart your system for the changes to take effect.
  </para>


text:
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;

namespace QuickGraph.Algorithms.Observers
{
    /// <summary>
    ///
    /// </summary>
    /// <typeparam name="TVertex">type of a vertex</typeparam>
    /// <typeparam name="TEdge">type of an edge</typeparam>
    /// <reference-ref
    ///     idref="boost"
    ///     />
#if !SILVERLIGHT
    [Serializable]
#endif
    public sealed class EdgeRecorderObserver<TVertex, TEdge> :
        IObserver<ITreeBuilderAlgorithm<TVertex, TEdge>>
        where TEdge : IEdge<TVertex>
    {
        private readonly IList<TEdge> edges;

        public EdgeRecorderObserver()
            :this(new List<TEdge>())
        {}

        public EdgeRecorderObserver(IList<TEdge> edges)
        {
            Contract.Requires(edges != null);

            this.edges = edges;
        }

        public IList<TEdge> Edges
        {
            get
            {
                return this.edges;
            }
        }

        public IDisposable Attach(ITreeBuilderAlgorithm<TVertex, TEdge> algorithm)
        {
            algorithm.TreeEdge += RecordEdge;
            return new DisposableAction(() => algorithm.TreeEdge -= RecordEdge);
        }

        private void RecordEdge(TEdge args)
        {
            Contract.Requires(args != null);

            this.Edges.Add(args);
        }
    }
}


text:
(function () {

'use strict';

angular.module('OpenSlidesApp.assignments.projector', ['OpenSlidesApp.assignments'])

.config([
    'slidesProvider',
    function(slidesProvider) {
        slidesProvider.registerSlide('assignments/assignment', {
            template: 'static/templates/assignments/slide_assignment.html',
        });
    }
])

.controller('SlideAssignmentCtrl', [
    '$scope',
    'Assignment',
    'User',
    function($scope, Assignment, User) {
        // Attention! Each object that is used here has to be dealt on server side.
        // Add it to the coresponding get_requirements method of the ProjectorElement
        // class.
        var id = $scope.element.id;
        var poll = $scope.element.poll;

        // load assignemt object and related agenda item
        Assignment.find(id).then(function(assignment) {
            Assignment.loadRelations(assignment, 'agenda_item');
        });
        Assignment.bindOne(id, $scope, 'assignment');
        Assignment.getPhases().then(function(phases) {
            $scope.phases = phases;
        });
        // load all users
        User.findAll();
        User.bindAll({}, $scope, 'users');
    }
]);

}());


text:
init_cell
=========

Add a cell toolbar selector to mark cells as 'initialization' cells .
Such initialization cells are run:

 * on clicking the provided button in the main toolbar
   ![main toolabr button](icon.png)
 * by default, on kernel ready notification for trusted notebooks.
   This is configurable (see options section).
   In untrusted notebooks, a warning is displayed if the cells would otherwise
   have been run.

Options
-------

This nbextension provides option configurable using the
[jupyter_nbextensions_configurator](https://github.com/Jupyter-contrib/jupyter_nbextensions_configurator).

Once the extension is enabled, turn on the cell toolbar within your Notebook using
the "View > Cell Toolbar > Initialization Cell" menu
![Cell Toobar Menu](cell_toolbar_menu.png)

The running of initialization cells on kernel ready notification can be
frustrating if your kernel is attached to multiple frontends, or is persistent
between frontend reloads (e.g. reloading the notebook browser page without
killing the kernel).
As such, the option `init_cell.run_on_kernel_ready` in the notebook config
section controls whether this behaviour occurs.
The server's config value can also be overridden on a per-notebook basis by
setting `notebook.metadata.init_cell.run_on_kernel_ready`.

Internals
---------

Cells are marked as initialization cells in their metadata, as

  cell.metadata.init_cell = true

The running of initialization cells on kernel ready is bound to the Jupyter
event `kernel_ready.Kernel`.


text:
#ifndef __APP_LIB__
#define __APP_LIB__

#include <event2/event.h>

#include <openssl/ssl.h>

#include "ns_turn_ioaddr.h"
#include "ns_turn_msg_defs.h"
#include "ns_turn_ioalib.h"

#ifdef __cplusplus
extern "C" {
#endif

//////////// Common defines ///////////////////////////

#define PEER_DEFAULT_PORT (3480)

#define DTLS_MAX_RECV_TIMEOUT (5)

#define UR_CLIENT_SOCK_BUF_SIZE (65536)
#define UR_SERVER_SOCK_BUF_SIZE (UR_CLIENT_SOCK_BUF_SIZE * 32)

extern int IS_TURN_SERVER;

/* ALPN */

#define OPENSSL_FIRST_ALPN_VERSION (0x10002003L)

#if OPENSSL_VERSION_NUMBER >= OPENSSL_FIRST_ALPN_VERSION
#define ALPN_SUPPORTED 1
#else
#define ALPN_SUPPORTED 0
#endif

/* TLS */

#if defined(TURN_NO_TLS)

	#define TLS_SUPPORTED 0
	#define TLSv1_1_SUPPORTED 0
	#define TLSv1_2_SUPPORTED 0

#else

	#define TLS_SUPPORTED 1

	#if defined(SSL_OP_NO_TLSv1_1)
		#define TLSv1_1_SUPPORTED 1
	#else
		#define TLSv1_1_SUPPORTED 0
	#endif

	#if defined(SSL_OP_NO_TLSv1_2)
		#define TLSv1_2_SUPPORTED 1
	#else
		#define TLSv1_2_SUPPORTED 0
	#endif

#endif

#if defined(TURN_NO_DTLS) || !defined(DTLS_CTRL_LISTEN)

	#define DTLS_SUPPORTED 0
	#define DTLSv1_2_SUPPORTED 0

#else

	#define DTLS_SUPPORTED 1

#if defined(SSL_OP_NO_DTLSv1_2)
		#define DTLSv1_2_SUPPORTED 1
	#else
		#define DTLSv1_2_SUPPORTED 0
	#endif

#endif

#if OPENSSL_VERSION_NUMBER >= OPENSSL_FIRST_ALPN_VERSION
#define SSL_SESSION_ECDH_AUTO_SUPPORTED 1
#else
#define SSL_SESSION_ECDH_AUTO_SUPPORTED 0
#endif

/////////// SSL //////////////////////////

enum _TURN_TLS_TYPE {
	TURN_TLS_NO=0,
	TURN_TLS_SSL23,
	TURN_TLS_v1_0,
#if TLSv1_1_SUPPORTED
	TURN_TLS_v1_1,
#if TLSv1_2_SUPPORTED
	TURN_TLS_v1_2,
#endif
#endif
	TURN_TLS_TOTAL
};

typedef enum _TURN_TLS_TYPE TURN_TLS_TYPE;

////////////////////////////////////////////

struct _oauth_key_data_raw {
	char kid[OAUTH_KID_SIZE+1];
	char ikm_key[OAUTH_KEY_SIZE+1];
	u64bits timestamp;
	u32bits lifetime;
	char as_rs_alg[OAUTH_ALG_SIZE+1];
	char realm[STUN_MAX_REALM_SIZE+1];
};

typedef struct _oauth_key_data_raw oauth_key_data_raw;

//////////////////////////////////////////

#define EVENT_DEL(ev) if(ev) { event_del(ev); event_free(ev); ev=NULL; }

//////////////////////////////////////////

#define ioa_socket_raw int

///////////////////////// Sockets ///////////////////////////////

#if defined(WIN32)
/** Do the platform-specific call needed to close a socket returned from
    socket() or accept(). */
#define socket_closesocket(s) closesocket(s)
#else
/** Do the platform-specific call needed to close a socket returned from
    socket() or accept(). */
#define socket_closesocket(s) close(s)
#endif

void read_spare_buffer(evutil_socket_t fd);

int set_sock_buf_size(evutil_socket_t fd, int sz);

int socket_set_reusable(evutil_socket_t fd, int reusable, SOCKET_TYPE st);
int sock_bind_to_device(evutil_socket_t fd, const unsigned char* ifname);
int socket_set_nonblocking(evutil_socket_t fd);
int socket_tcp_set_keepalive(evutil_socket_t fd, SOCKET_TYPE st);

int addr_connect(evutil_socket_t fd, const ioa_addr* addr, int *out_errno);

int addr_bind(evutil_socket_t fd, const ioa_addr* addr, int reusable, int debug, SOCKET_TYPE st);

int addr_get_from_sock(evutil_socket_t fd, ioa_addr *addr);

int handle_socket_error(void);

#define CORRECT_RAW_TTL(ttl) do { if(ttl<0 || ttl>255) ttl=TTL_DEFAULT; } while(0)
#define CORRECT_RAW_TOS(tos) do { if(tos<0 || tos>255) tos=TOS_DEFAULT; } while(0)

int set_raw_socket_tos(evutil_socket_t fd, int family, int tos);
int set_raw_socket_ttl(evutil_socket_t fd, int family, int ttl);
int get_raw_socket_tos(evutil_socket_t fd, int family);
int get_raw_socket_ttl(evutil_socket_t fd, int family);

/////////////////////// SYS /////////////////////

void ignore_sigpipe(void);
unsigned long set_system_parameters(int max_resources);

///////////////////////// MTU //////////////////////////

#define MAX_MTU (1500 - 20 - 8)
#define MIN_MTU (576 - 20 - 8)
#define SOSO_MTU (1300)

#define MTU_STEP (68)

int set_socket_df(evutil_socket_t fd, int family, int value);
int set_mtu_df(SSL* ssl, evutil_socket_t fd, int family, int mtu, int df_value, int verbose);
int decrease_mtu(SSL* ssl, int mtu, int verbose);
int get_socket_mtu(evutil_socket_t fd, int family, int verbose);

////////////////// Misc utils /////////////////////////

char *skip_blanks(char* s);

////////////////// File search ////////////////////////

char* find_config_file(const char *config_file, int print_file_name);
void set_execdir(void);
void print_abs_file_name(const char *msg1, const char *msg2, const char *fn);

////////////////// Base64 /////////////////////////////

char *base64_encode(const unsigned char *data,
                    size_t input_length,
                    size_t *output_length);

void build_base64_decoding_table(void);

unsigned char *base64_decode(const char *data,
                             size_t input_length,
                             size_t *output_length);

///////////// SSL ////////////////

const char* turn_get_ssl_method(SSL *ssl, const char* mdefault);

////////////// OAUTH UTILS ////////////////

void convert_oauth_key_data_raw(const oauth_key_data_raw *raw, oauth_key_data *oakd);

//////////// Event Base /////////////////////

struct event_base *turn_event_base_new(void);

///////////////////////////////////////////////////////

#ifdef __cplusplus
}
#endif

#endif //__APP_LIB__


text:
package org.cubeengine.dirigent.formatter;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import org.cubeengine.dirigent.context.Contexts;
import org.cubeengine.dirigent.parser.component.Component;
import org.cubeengine.dirigent.context.Context;
import org.cubeengine.dirigent.context.Arguments;
import org.cubeengine.dirigent.parser.Text;
import org.junit.Assert;

import static org.cubeengine.dirigent.TestHelper.*;
import static org.cubeengine.dirigent.context.Contexts.createContext;

/**
 * Abstract methods for tests of the {@link DateTimeFormatter}.
 */
public abstract class AbstractDateTimeFormatterTest
{
    private final DateTimeFormatter formatter;

    protected AbstractDateTimeFormatterTest(DateTimeFormatter formatter)
    {
        this.formatter = formatter;
    }

    protected Date createDate()
    {
        TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
        final Calendar calendar = GregorianCalendar.getInstance(Locale.US);
        calendar.set(2017, Calendar.MAY, 25, 15, 13, 21);
        return calendar.getTime();
    }

    protected void checkFormat(final String expected, final Date date, final Locale locale, final String style)
    {
        checkFormat(expected, date, locale, TimeZone.getDefault(), style, null, null, null);
    }

    protected void checkFormat(final String expected, final Date date, final Locale locale, final TimeZone timeZone,
                               final String style)
    {
        checkFormat(expected, date, locale, timeZone, style, null, null, null);
    }

    protected void checkFormat(final String expected, final Date date, final String format)
    {
        checkFormat(expected, date, Locale.US, TimeZone.getDefault(), null, null, null, format);
    }

    protected void checkFormat(final String expected, final Date date, final Locale locale, final String defaultStyle,
                               final String dateStyle, final String timeStyle)
    {
        checkFormat(expected, date, locale, TimeZone.getDefault(), defaultStyle, dateStyle, timeStyle, null);
    }

    private void checkFormat(final String expected, final Date date, final Locale locale, final TimeZone timeZone,
                             final String defaultStyle, final String dateStyle, final String timeStyle,
                             final String format)
    {
        final Context context = createContext(Contexts.LOCALE.with(locale), Contexts.TIMEZONE.with(timeZone));
        final Arguments args = createArguments(defaultStyle, dateStyle, timeStyle, format);

        final Component component = formatter.format(date, context, args);

        Assert.assertTrue(component instanceof Text);
        Assert.assertEquals(expected, ((Text)component).getText());
    }

    private Arguments createArguments(final String defaultStyle, final String dateStyle, final String timeStyle,
                                      final String format)
    {
        final List<Object> arguments = new ArrayList<Object>();

        if (defaultStyle != null)
        {
            arguments.add(arg(defaultStyle));
        }
        if (dateStyle != null)
        {
            arguments.add(arg(DateTimeFormatter.DATE_PARAM_NAME, dateStyle));
        }
        if (timeStyle != null)
        {
            arguments.add(arg(DateTimeFormatter.TIME_PARAM_NAME, timeStyle));
        }
        if (format != null)
        {
            arguments.add(arg(DateTimeFormatter.FORMAT_PARAM_NAME, format));
        }

        return toArgs(arguments.toArray());
    }
}


text:
import abc
import uuid

from oslo_log import log as logging
from oslo_utils import netutils

from trove.common import cfg
from trove.common.i18n import _
from trove.common import utils
from trove.guestagent.backup.backupagent import BackupAgent
from trove.guestagent.datastore.mysql.service import MySqlAdmin
from trove.guestagent.db import models
from trove.guestagent.strategies import backup
from trove.guestagent.strategies.replication import base

AGENT = BackupAgent()
CONF = cfg.CONF

REPL_BACKUP_NAMESPACE = 'trove.guestagent.strategies.backup.mysql_impl'
REPL_BACKUP_STRATEGY = 'InnoBackupEx'
REPL_BACKUP_INCREMENTAL_STRATEGY = 'InnoBackupExIncremental'
REPL_BACKUP_RUNNER = backup.get_backup_strategy(
    REPL_BACKUP_STRATEGY, REPL_BACKUP_NAMESPACE)
REPL_BACKUP_INCREMENTAL_RUNNER = backup.get_backup_strategy(
    REPL_BACKUP_INCREMENTAL_STRATEGY, REPL_BACKUP_NAMESPACE)
REPL_EXTRA_OPTS = CONF.backup_runner_options.get(REPL_BACKUP_STRATEGY, '')

LOG = logging.getLogger(__name__)

class MysqlReplicationBase(base.Replication):
    """Base class for MySql Replication strategies."""

    def get_master_ref(self, service, snapshot_info):
        master_ref = {
            'host': netutils.get_my_ipv4(),
            'port': service.get_port()
        }
        return master_ref

    def _create_replication_user(self):
        replication_user = None
        replication_password = utils.generate_random_password(16)

        mysql_user = models.MySQLUser()
        mysql_user.password = replication_password

        retry_count = 0

        while replication_user is None:
            try:
                mysql_user.name = 'slave_' + str(uuid.uuid4())[:8]
                MySqlAdmin().create_user([mysql_user.serialize()])
                LOG.debug("Trying to create replication user " +
                          mysql_user.name)
                replication_user = {
                    'name': mysql_user.name,
                    'password': replication_password
                }
            except Exception:
                retry_count += 1
                if retry_count > 5:
                    LOG.error(_("Replication user retry count exceeded"))
                    raise

        return replication_user

    def snapshot_for_replication(self, context, service,
                                 location, snapshot_info):
        snapshot_id = snapshot_info['id']
        replica_number = snapshot_info.get('replica_number', 1)

        LOG.debug("Acquiring backup for replica number %d." % replica_number)
        # Only create a backup if it's the first replica
        if replica_number == 1:
            AGENT.execute_backup(
                context, snapshot_info, runner=REPL_BACKUP_RUNNER,
                extra_opts=REPL_EXTRA_OPTS,
                incremental_runner=REPL_BACKUP_INCREMENTAL_RUNNER)
        else:
            LOG.debug("Using existing backup created for previous replica.")
        LOG.debug("Replication snapshot %s used for replica number %d."
                  % (snapshot_id, replica_number))

        replication_user = self._create_replication_user()
        service.grant_replication_privilege(replication_user)

        # With streamed InnobackupEx, the log position is in
        # the stream and will be decoded by the slave
        log_position = {
            'replication_user': replication_user
        }
        return snapshot_id, log_position

    def enable_as_master(self, service, master_config):
        if not service.exists_replication_source_overrides():
            service.write_replication_source_overrides(master_config)
            service.restart()

    @abc.abstractmethod
    def connect_to_master(self, service, snapshot):
        """Connects a slave to a master"""

    def enable_as_slave(self, service, snapshot, slave_config):
        try:
            LOG.debug("enable_as_slave: about to call write_overrides")
            service.write_replication_replica_overrides(slave_config)
            LOG.debug("enable_as_slave: about to call restart")
            service.restart()
            LOG.debug("enable_as_slave: about to call connect_to_master")
            self.connect_to_master(service, snapshot)
            LOG.debug("enable_as_slave: after call connect_to_master")
        except Exception:
            LOG.exception(_("Exception enabling guest as replica"))
            raise

    def detach_slave(self, service, for_failover):
        replica_info = service.stop_slave(for_failover)
        service.remove_replication_replica_overrides()
        service.restart()
        return replica_info

    def get_replica_context(self, service):
        replication_user = self._create_replication_user()
        service.grant_replication_privilege(replication_user)
        return {
            'master': self.get_master_ref(service, None),
            'log_position': {
                'replication_user': replication_user
            }
        }

    def cleanup_source_on_replica_detach(self, admin_service, replica_info):
        admin_service.delete_user_by_name(replica_info['replication_user'])

    def demote_master(self, service):
        service.remove_replication_source_overrides()
        service.restart()


text:
#!/usr/bin/env node

var fs = require("fs")
  , path = require("path")
  , pull = require("pull-stream")
  , glob = require("pull-glob")
  , mkdirp = require("mkdirp")
  , async = require("async")
  , depGraph = require("../lib/dep-graph")
  , CombinedStream = require("combined-stream")

var argv = require("optimist")
  .usage("Stream run frontend tasks.\nUsage: $0")
  .alias("t", "task")
  .alias("c", "config")
  .describe("t", "Task name to run")
  .describe("c", "Config JSON file to load")
  .argv

var tasks = {}
  , config = JSON.parse(fs.readFileSync(argv.c))

function isMultiTask (taskConfig) {
  var keys = Object.keys(taskConfig)
  return keys.indexOf("src") == -1 && keys.indexOf("dest") == -1 && keys.indexOf("depends") == -1
}

// Require tasks and add task name to all instances
Object.keys(config).forEach(function (taskName) {
  console.log("Loading task", taskName + "...")
  tasks[taskName] = require(path.join(process.cwd(), "node_modules", taskName))

  if (isMultiTask(config[taskName])) {
    return Object.keys(config[taskName]).forEach(function (instanceName) {
      config[taskName][instanceName]._froTaskName = taskName
    })
  }

  config[taskName]._froTaskName = taskName
})

var graph = depGraph.create(config)

depGraph.print(graph)

function subtaskConfigs (taskConfig) {
  // TODO: Get subtasks for a task
  return []
}

function createTaskPipeline (fromStream, taskConfigs) {
  return taskConfigs.map(function (taskConfig) {
    var subtaskConfigs = subtaskConfigs(taskConfig)
      , task = tasks[taskConfig._froTaskName]

    if (!subtaskConfigs.length) {
      return fromStream.pipe(task(taskConfig))
    }

    return createTaskPipeline(fromStream.pipe(task(taskConfig)), subtaskConfigs)
  })
}

function flatten (array) {
  return array.reduce(function (flattened, o) {
    return flattened.concat(Array.isArray(o) ? flatten(o) : o)
  }, [])
}

// Get the top level tasks
var runners = graph.overallOrder(true).map(function (taskConfig) {
  return function (cb) {
    var globStream = glob(taskConfig.src)
      , sourceStream = CombinedStream.create()

    globStream.on("data", function (file) {
      sourceStream.append(fs.createReadStream(file))
    })

    globStream.on("end", function () {
      var pipeline = createTaskPipeline(sourceStream, [taskConfig])

      // pipeline is an array of streams/arrays of streams - make flatten
      // [stream, [stream, stream], stream, [stream, [stream, stream], stream]]
      pipeline = flatten(pipeline)

      var writeTasks = pipeline.map(function (stream, i) {
        return function (cb) {
          var taskConfig = depGraph.overallOrder()[i]

          var writeStream = fs.createWriteStream(/* but where does it go? */)
          writeStream.on("finish", cb)

          stream.pipe(writeStream)
        }
      })

      async.parallel(writeTasks, cb)
    })
  }
})

async.parallel(runners, function (er) {
  if (er) throw er
})


text:
CFastPin::CFastPin(
    const UINT8        pinMap[],
    const CONNECTION  *connection
)
{
    UINT8 pin = pinMap[connection->pin];

    m_decodedPinMap = pin;

    m_physicalPinMask         = digitalPinToBitMask(pin);
    m_physicalPinMaskInverted = ~m_physicalPinMask;
    m_physicalPortRegisterIn  = portInputRegister(digitalPinToPort(pin));
    m_physicalPortRegisterOut = portOutputRegister(digitalPinToPort(pin));
};

void
CFastPin::pinMode(
    int     mode
)
{
    ::pinMode(m_decodedPinMap, mode);
};


text:
using namespace IdealRandomWalk;
using namespace Parser;

namespace CalcNumWalks {

    void calc_num_ideal_walks(int max_d, int max_N, string filename);
}

#endif // CALC_NUM_WALKS_H


text:
.class public Landroid/net/CaptivePortal;
.super Ljava/lang/Object;
.source "CaptivePortal.java"

# interfaces
.implements Landroid/os/Parcelable;

# annotations
.annotation system Ldalvik/annotation/MemberClasses;
    value = {
        Landroid/net/CaptivePortal$1;
    }
.end annotation

# static fields
.field public static final APP_RETURN_DISMISSED:I = 0x0

.field public static final APP_RETURN_UNWANTED:I = 0x1

.field public static final APP_RETURN_WANTED_AS_IS:I = 0x2

.field public static final CREATOR:Landroid/os/Parcelable$Creator;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Landroid/os/Parcelable$Creator",
            "<",
            "Landroid/net/CaptivePortal;",
            ">;"
        }
    .end annotation
.end field

# instance fields
.field private final mBinder:Landroid/os/IBinder;

# direct methods
.method static constructor <clinit>()V
    .locals 1

    .prologue
    .line 55
    new-instance v0, Landroid/net/CaptivePortal$1;

    invoke-direct {v0}, Landroid/net/CaptivePortal$1;-><init>()V

    .line 54
    sput-object v0, Landroid/net/CaptivePortal;->CREATOR:Landroid/os/Parcelable$Creator;

    .line 29
    return-void
.end method

.method public constructor <init>(Landroid/os/IBinder;)V
    .locals 0
    .param p1, "binder"    # Landroid/os/IBinder;

    .prologue
    .line 40
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 41
    iput-object p1, p0, Landroid/net/CaptivePortal;->mBinder:Landroid/os/IBinder;

    .line 40
    return-void
.end method

# virtual methods
.method public describeContents()I
    .locals 1

    .prologue
    .line 46
    const/4 v0, 0x0

    return v0
.end method

.method public ignoreNetwork()V
    .locals 3

    .prologue
    .line 88
    :try_start_0
    iget-object v1, p0, Landroid/net/CaptivePortal;->mBinder:Landroid/os/IBinder;

    invoke-static {v1}, Landroid/net/ICaptivePortal$Stub;->asInterface(Landroid/os/IBinder;)Landroid/net/ICaptivePortal;

    move-result-object v1

    const/4 v2, 0x1

    invoke-interface {v1, v2}, Landroid/net/ICaptivePortal;->appResponse(I)V
    :try_end_0
    .catch Landroid/os/RemoteException; {:try_start_0 .. :try_end_0} :catch_0

    .line 86
    :goto_0
    return-void

    .line 89
    :catch_0
    move-exception v0

    .local v0, "e":Landroid/os/RemoteException;
    goto :goto_0
.end method

.method public reportCaptivePortalDismissed()V
    .locals 3

    .prologue
    .line 74
    :try_start_0
    iget-object v1, p0, Landroid/net/CaptivePortal;->mBinder:Landroid/os/IBinder;

    invoke-static {v1}, Landroid/net/ICaptivePortal$Stub;->asInterface(Landroid/os/IBinder;)Landroid/net/ICaptivePortal;

    move-result-object v1

    const/4 v2, 0x0

    invoke-interface {v1, v2}, Landroid/net/ICaptivePortal;->appResponse(I)V
    :try_end_0
    .catch Landroid/os/RemoteException; {:try_start_0 .. :try_end_0} :catch_0

    .line 72
    :goto_0
    return-void

    .line 75
    :catch_0
    move-exception v0

    .local v0, "e":Landroid/os/RemoteException;
    goto :goto_0
.end method

.method public useNetwork()V
    .locals 3

    .prologue
    .line 104
    :try_start_0
    iget-object v1, p0, Landroid/net/CaptivePortal;->mBinder:Landroid/os/IBinder;

    invoke-static {v1}, Landroid/net/ICaptivePortal$Stub;->asInterface(Landroid/os/IBinder;)Landroid/net/ICaptivePortal;

    move-result-object v1

    const/4 v2, 0x2

    invoke-interface {v1, v2}, Landroid/net/ICaptivePortal;->appResponse(I)V
    :try_end_0
    .catch Landroid/os/RemoteException; {:try_start_0 .. :try_end_0} :catch_0

    .line 102
    :goto_0
    return-void

    .line 105
    :catch_0
    move-exception v0

    .local v0, "e":Landroid/os/RemoteException;
    goto :goto_0
.end method

.method public writeToParcel(Landroid/os/Parcel;I)V
    .locals 1
    .param p1, "out"    # Landroid/os/Parcel;
    .param p2, "flags"    # I

    .prologue
    .line 51
    iget-object v0, p0, Landroid/net/CaptivePortal;->mBinder:Landroid/os/IBinder;

    invoke-virtual {p1, v0}, Landroid/os/Parcel;->writeStrongBinder(Landroid/os/IBinder;)V

    .line 50
    return-void
.end method


text:
<?php

declare(strict_types=1);

namespace Doctrine\ODM\MongoDB\Tests\Persisters;

use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
use Doctrine\ODM\MongoDB\Tests\BaseTest;

class GH1107Test extends BaseTest
{
    public function testOverrideIdStrategy()
    {
        $childObj       = new GH1107ChildClass();
        $childObj->name = 'ChildObject';
        $this->dm->persist($childObj);
        $this->dm->flush();
        $this->assertNotNull($childObj->id);
    }
}

/**
 * @ODM\Document
 * @ODM\InheritanceType("SINGLE_COLLECTION")
 */
class GH1107ParentClass
{
    /** @ODM\Id(strategy="NONE") */
    public $id;

    /** @ODM\Field(type="string") */
    public $name;
}

/** @ODM\Document */
class GH1107ChildClass extends GH1107ParentClass
{
    /** @ODM\Id(strategy="AUTO") */
    public $id;
}


text:
package iso20022

type CashAccountType5Code string


text:
namespace QCV {
  partial class FilterEvents {
    /// <summary>
    /// Required designer variable.
    /// </summary>
    private System.ComponentModel.IContainer components = null;

    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
    protected override void Dispose(bool disposing) {
      if (disposing && (components != null)) {
        components.Dispose();
      }
      base.Dispose(disposing);
    }

    #region Component Designer generated code

    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent() {
      this._layouter = new System.Windows.Forms.FlowLayoutPanel();
      this.SuspendLayout();
      //
      // _layouter
      //
      this._layouter.Dock = System.Windows.Forms.DockStyle.Fill;
      this._layouter.FlowDirection = System.Windows.Forms.FlowDirection.TopDown;
      this._layouter.Location = new System.Drawing.Point(0, 0);
      this._layouter.Name = "_layouter";
      this._layouter.Size = new System.Drawing.Size(398, 376);
      this._layouter.TabIndex = 0;
      //
      // FilterEvents
      //
      this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
      this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
      this.Controls.Add(this._layouter);
      this.Name = "FilterEvents";
      this.Size = new System.Drawing.Size(398, 376);
      this.ResumeLayout(false);

    }

    #endregion

    private System.Windows.Forms.FlowLayoutPanel _layouter;
  }
}


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

#include "components/password_manager/core/browser/password_generation_frame_helper.h"

#include <memory>

#include "base/strings/string_util.h"
#include "components/autofill/core/browser/field_types.h"
#include "components/autofill/core/browser/form_structure.h"
#include "components/autofill/core/browser/proto/password_requirements.pb.h"
#include "components/password_manager/core/browser/browser_save_password_progress_logger.h"
#include "components/password_manager/core/browser/generation/password_generator.h"
#include "components/password_manager/core/browser/password_feature_manager.h"
#include "components/password_manager/core/browser/password_manager.h"
#include "components/password_manager/core/browser/password_manager_client.h"
#include "components/password_manager/core/browser/password_manager_driver.h"
#include "components/password_manager/core/browser/password_manager_util.h"
#include "components/password_manager/core/browser/password_requirements_service.h"
#include "components/password_manager/core/common/password_manager_features.h"
#include "third_party/abseil-cpp/absl/types/optional.h"

using autofill::FieldSignature;
using autofill::FormSignature;
using autofill::FormStructure;

namespace password_manager {

namespace {
using Logger = autofill::SavePasswordProgressLogger;
}

PasswordGenerationFrameHelper::PasswordGenerationFrameHelper(
    PasswordManagerClient* client,
    PasswordManagerDriver* driver)
    : client_(client), driver_(driver) {}

PasswordGenerationFrameHelper::~PasswordGenerationFrameHelper() = default;

void PasswordGenerationFrameHelper::PrefetchSpec(const GURL& origin) {
  // IsGenerationEnabled is called multiple times and it is sufficient to
  // log debug data once.
  if (!IsGenerationEnabled(/*log_debug_data=*/false))
    return;

  // It is legit to have no PasswordRequirementsService on some platforms where
  // it has not been implemented.
  PasswordRequirementsService* password_requirements_service =
      client_->GetPasswordRequirementsService();
  if (!password_requirements_service)
    return;

  // Fetch password requirements for the domain.
  password_requirements_service->PrefetchSpec(origin);
}

void PasswordGenerationFrameHelper::ProcessPasswordRequirements(
    const std::vector<autofill::FormStructure*>& forms) {
  // IsGenerationEnabled is called multiple times and it is sufficient to
  // log debug data once.
  if (!IsGenerationEnabled(/*log_debug_data=*/false))
    return;

  // It is legit to have no PasswordRequirementsService on some platforms where
  // it has not been implemented.
  PasswordRequirementsService* password_requirements_service =
      client_->GetPasswordRequirementsService();
  if (!password_requirements_service)
    return;

  // Store password requirements from the autofill server.
  for (const autofill::FormStructure* form : forms) {
    for (const auto& field : *form) {
      if (field->password_requirements()) {
        password_requirements_service->AddSpec(
            form->source_url().DeprecatedGetOriginAsURL(),
            form->form_signature(), field->GetFieldSignature(),
            field->password_requirements().value());
      }
    }
  }
}

// In order for password generation to be enabled, we need to make sure:
// (1) Password sync is enabled, and
// (2) Password saving is enabled
// (3) The current page is not *.google.com.
bool PasswordGenerationFrameHelper::IsGenerationEnabled(
    bool log_debug_data) const {
  std::unique_ptr<Logger> logger;
  if (log_debug_data && password_manager_util::IsLoggingActive(client_)) {
    logger = std::make_unique<BrowserSavePasswordProgressLogger>(
        client_->GetLogManager());
  }

  GURL url = driver_->GetLastCommittedURL();
  if (url.DomainIs("google.com"))
    return false;

  if (!client_->IsSavingAndFillingEnabled(url)) {
    if (logger)
      logger->LogMessage(Logger::STRING_GENERATION_DISABLED_SAVING_DISABLED);
    return false;
  }

  if (client_->GetPasswordFeatureManager()->IsGenerationEnabled())
    return true;
  if (logger)
    logger->LogMessage(Logger::STRING_GENERATION_DISABLED_NO_SYNC);

  return false;
}

std::u16string PasswordGenerationFrameHelper::GeneratePassword(
    const GURL& last_committed_url,
    autofill::FormSignature form_signature,
    autofill::FieldSignature field_signature,
    uint32_t max_length) {
  autofill::PasswordRequirementsSpec spec;

  // Lookup password requirements.
  PasswordRequirementsService* password_requirements_service =
      client_->GetPasswordRequirementsService();
  if (password_requirements_service) {
    spec = password_requirements_service->GetSpec(
        last_committed_url.DeprecatedGetOriginAsURL(), form_signature,
        field_signature);
  }

  // Choose the password length as the minimum of default length, what website
  // allows, and what the autofill server suggests.
  uint32_t target_length = autofill::kDefaultPasswordLength;
  if (max_length && max_length < target_length)
    target_length = max_length;
  if (spec.has_max_length() && spec.max_length() < target_length)
    target_length = spec.max_length();
  spec.set_max_length(target_length);
  if (password_manager_util::IsLoggingActive(client_)) {
    BrowserSavePasswordProgressLogger logger(client_->GetLogManager());
    logger.LogPasswordRequirements(
        last_committed_url.DeprecatedGetOriginAsURL(), form_signature,
        field_signature, spec);
  }

  return autofill::GeneratePassword(spec);
}

}  // namespace password_manager


text:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Services.Testing.Web;

namespace Sighting.Services.Testing
{
    /// <summary>
    /// Tests the creation of sightings.
    /// </summary>
    [TestClass]
    public class SightingFixture
    {
        [TestMethod]
        public void TestCreateSighting()
        {
            var randomCoordinates = new Random();
            using (var sightingClient = new SightingServiceClient())
            {
                var latitude = randomCoordinates.Next(-90, 90) * randomCoordinates.NextDouble();
                var longitude = randomCoordinates.Next(-180, 180) * randomCoordinates.NextDouble();
                var sighting = sightingClient.CreateSighting(latitude, longitude, DateTime.Now);
                Assert.IsNotNull(sighting, @"Sighting must not be null!");
                Assert.IsFalse(string.IsNullOrEmpty(sighting.GeometryAsWellKnownText), @"The well known text representation must be set!");
            }
        }
    }
}