text:
function err() {
    local exitcode=$1
    shift
    echo "ERROR: $@" >&2
    exit $exitcode
}

function warn() {
    echo "WARN : $@" >&2
}

function info() {
    if [[ -n "$VERBOSE" ]]; then
	echo "INFO : $@" >&2
    fi
}

## -- Pktgen proc config commands -- ##
export PROC_DIR=/proc/net/pktgen
#
# Three different shell functions for configuring the different
# components of pktgen:
#   pg_ctrl(), pg_thread() and pg_set().
#
# These functions correspond to pktgens different components.
# * pg_ctrl()   control "pgctrl" (/proc/net/pktgen/pgctrl)
# * pg_thread() control the kernel threads and binding to devices
# * pg_set()    control setup of individual devices
function pg_ctrl() {
    local proc_file="pgctrl"
    proc_cmd ${proc_file} "$@"
}

function pg_thread() {
    local thread=$1
    local proc_file="kpktgend_${thread}"
    shift
    proc_cmd ${proc_file} "$@"
}

function pg_set() {
    local dev=$1
    local proc_file="$dev"
    shift
    proc_cmd ${proc_file} "$@"
}

# More generic replacement for pgset(), that does not depend on global
# variable for proc file.
function proc_cmd() {
    local result
    local proc_file=$1
    # after shift, the remaining args are contained in $@
    shift
    local proc_ctrl=${PROC_DIR}/$proc_file
    if [[ ! -e "$proc_ctrl" ]]; then
	err 3 "proc file:$proc_ctrl does not exists (dev added to thread?)"
    else
	if [[ ! -w "$proc_ctrl" ]]; then
	    err 4 "proc file:$proc_ctrl not writable, not root?!"
	fi
    fi

    if [[ "$DEBUG" == "yes" ]]; then
	echo "cmd: $@ > $proc_ctrl"
    fi
    # Quoting of "$@" is important for space expansion
    echo "$@" > "$proc_ctrl"
    local status=$?

    result=$(grep "Result: OK:" $proc_ctrl)
    # Due to pgctrl, cannot use exit code $? from grep
    if [[ "$result" == "" ]]; then
	grep "Result:" $proc_ctrl >&2
    fi
    if (( $status != 0 )); then
	err 5 "Write error($status) occurred cmd: \"$@ > $proc_ctrl\""
    fi
}

# Old obsolete "pgset" function, with slightly improved err handling
function pgset() {
    local result

    if [[ "$DEBUG" == "yes" ]]; then
	echo "cmd: $1 > $PGDEV"
    fi
    echo $1 > $PGDEV
    local status=$?

    result=`cat $PGDEV | fgrep "Result: OK:"`
    if [[ "$result" == "" ]]; then
         cat $PGDEV | fgrep Result:
    fi
    if (( $status != 0 )); then
	err 5 "Write error($status) occurred cmd: \"$1 > $PGDEV\""
    fi
}

## -- General shell tricks --

function root_check_run_with_sudo() {
    # Trick so, program can be run as normal user, will just use "sudo"
    #  call as root_check_run_as_sudo "$@"
    if [ "$EUID" -ne 0 ]; then
	if [ -x $0 ]; then # Directly executable use sudo
	    info "Not root, running with sudo"
            sudo "$0" "$@"
            exit $?
	fi
	err 4 "cannot perform sudo run of $0"
    fi
}


text:
using namespace std;
#define MAX 10000
// defined a class stack
class Stack {
	//top variable which represents the top of the stack
	int top;
public:
	//declared an array of MAX size to store the elements of the stack
	int arr[MAX];
	//top is intialised to -1 when stack is created
	Stack() {
		top = -1;
	}
	// function to push elements into the stack
	bool push(int num) {
		//maximum size of the stack
		if (top >= MAX) {
			cout << "Stack OverFlow" << endl;
			return false;
		}
		else {
			arr[++top] = num;
			cout << num << " is pushed into the stack" << endl;
			return true;
		}
	}
	bool pop() {
		//minimum size of the stack
		if (top <= -1) {
			cout << "Stack UnderFlow";
			return false;
		}
		else {
			int x = arr[top--];
			cout << x << " is popped out of the stack" << endl;
			return true;
		}
	}
	bool isEmpty() {
		//checking if stack is empty or not.
		if (top <= -1) {
			return true;
		}
		else return false;
	}
};
int main() {
	Stack s;
	if (s.isEmpty()) cout << "Stack is empty" << endl;
	s.push(10);
	s.push(20);
	if (!s.isEmpty()) cout << "Stack is not empty" << endl;
	s.pop();
	s.pop();
	return 0;
}

redpajama_set_name: RedPajamaGithub


text:
all: index.html

NPM = $(shell which npm)
RAML2HTML = $(shell which raml2html)

index.html:
ifeq ($(NPM),)
	@echo "You don't have node.js installed."
	@echo "It's up to you to decide the best way of doing that for your system"
else
	@if ! [ -f $(RAML2HTML) ] ; then \
		echo "You don't have raml2html, but we'll assume you want it" ; \
		$(NPM) install -g raml2html; \
    fi;
	$(RAML2HTML) base.yml > index.html
endif

clean:
	@rm *.html


text:
<?php

namespace Phlexible\Component\MediaCache\Exception;

/**
 * Invalid argument exception for media cache.
 *
 * @author Stephan Wentz <sw@brainbits.net>
 */
class InvalidArgumentException extends \InvalidArgumentException implements ExceptionInterface
{
}


text:
<?php

namespace Interim\RecruteBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Poste
 *
 * @ORM\Table(name="postes")
 * @ORM\Entity
 */
class Poste
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="titre", type="string", length=255)
     */
    private $titre;

    /**
     * @var string
     *
     * @ORM\Column(name="description", type="string", length=255)
     */
    private $description;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="date_limite", type="date")
     */
    private $dateLimite;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="date_fonction", type="date")
     */
    private $dateFonction;

    /**
     * @var integer
     *
     * @ORM\Column(name="salaire", type="integer")
     */
    private $salaire;

    /**
     * @var string
     *
     * @ORM\Column(name="avantage", type="string", length=255)
     */
    private $avantage;

    /**
     * @var string
     *
     * @ORM\Column(name="tache", type="string", length=255)
     */
    private $tache;

    /**
     * @var string
     *
     * @ORM\Column(name="mission", type="string", length=255)
     */
    private $mission;

    /**
     * @var string
     *
     * @ORM\Column(name="objectif", type="string", length=255)
     */
    private $objectif;

    # Les Relations entre les societes

    /**
     *
     *@ORM\ManyToOne(targetEntity="Interim\RecruteBundle\Entity\Societe", cascade={"persist"} )
     */

   private $societe;

   /**
    *@ORM\OneToMany(targetEntity="Interim\RecruteBundle\Entity\Critere", cascade={"persist"}, mappedBy="poste")
    */
   private $critere;

   /**
    *
    * * @ORM\OneToMany(targetEntity="Interim\RecruteBundle\Entity\Competence", cascade={"persist"},mappedBy="poste")
    */
   private $competence;

    /**
     * * @ORM\OneToMany(targetEntity="CentreInteret", cascade={"persist"},mappedBy="poste")
     */
    private $centreInteret;

    # Fin Relations

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

    /**
     * Set titre
     *
     * @param string $titre
     * @return Poste
     */
    public function setTitre($titre)
    {
        $this->titre = $titre;

        return $this;
    }

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

    /**
     * Set description
     *
     * @param string $description
     * @return Poste
     */
    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }

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

    /**
     * Set dateLimite
     *
     * @param \DateTime $dateLimite
     * @return Poste
     */
    public function setDateLimite($dateLimite)
    {
        $this->dateLimite = $dateLimite;

        return $this;
    }

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

    /**
     * Set dateFonction
     *
     * @param \DateTime $dateFonction
     * @return Poste
     */
    public function setDateFonction($dateFonction)
    {
        $this->dateFonction = $dateFonction;

        return $this;
    }

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

    /**
     * Set salaire
     *
     * @param integer $salaire
     * @return Poste
     */
    public function setSalaire($salaire)
    {
        $this->salaire = $salaire;

        return $this;
    }

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

    /**
     * Set avantage
     *
     * @param string $avantage
     * @return Poste
     */
    public function setAvantage($avantage)
    {
        $this->avantage = $avantage;

        return $this;
    }

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

    /**
     * Set tache
     *
     * @param string $tache
     * @return Poste
     */
    public function setTache($tache)
    {
        $this->tache = $tache;

        return $this;
    }

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

    /**
     * Set mission
     *
     * @param string $mission
     * @return Poste
     */
    public function setMission($mission)
    {
        $this->mission = $mission;

        return $this;
    }

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

    /**
     * Set objectif
     *
     * @param string $objectif
     * @return Poste
     */
    public function setObjectif($objectif)
    {
        $this->objectif = $objectif;

        return $this;
    }

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

    /**
     * Set societe
     *
     * @param string $societe
     * @return Poste
     */
    public function setSociete($societe)
    {
        $this->societe = $societe;

        return $this;
    }

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

    /**
     * Set critere
     *
     * @param string $critere
     * @return Poste
     */
    public function setCritere($critere)
    {
        $this->critere = $critere;

        return $this;
    }

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

    /**
     * Set competence
     *
     * @param string $competence
     * @return Poste
     */
    public function setCompetence($competence)
    {
        $this->competence = $competence;

        return $this;
    }

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

    /**
     * Set centreInteret
     *
     * @param string $centreInteret
     * @return Poste
     */
    public function setCentreInteret($centreInteret)
    {
        $this->centreInteret = $centreInteret;

        return $this;
    }

    /**
     * Get centreInteret
     *
     * @return string
     */
    public function getCentreInteret()
    {
        return $this->centreInteret;
    }
    /**
     * Constructor
     */
    public function __construct()
    {
        $this->critere = new \Doctrine\Common\Collections\ArrayCollection();
        $this->competence = new \Doctrine\Common\Collections\ArrayCollection();
        $this->centreInteret = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Add critere
     *
     * @param \Interim\RecruteBundle\Entity\Critere $critere
     * @return Poste
     */
    public function addCritere(\Interim\RecruteBundle\Entity\Critere $critere)
    {
        $this->critere[] = $critere;

        return $this;
    }

    /**
     * Remove critere
     *
     * @param \Interim\RecruteBundle\Entity\Critere $critere
     */
    public function removeCritere(\Interim\RecruteBundle\Entity\Critere $critere)
    {
        $this->critere->removeElement($critere);
    }

    /**
     * Add competence
     *
     * @param \Interim\RecruteBundle\Entity\Competence $competence
     * @return Poste
     */
    public function addCompetence(\Interim\RecruteBundle\Entity\Competence $competence)
    {
        $this->competence[] = $competence;

        return $this;
    }

    /**
     * Remove competence
     *
     * @param \Interim\RecruteBundle\Entity\Competence $competence
     */
    public function removeCompetence(\Interim\RecruteBundle\Entity\Competence $competence)
    {
        $this->competence->removeElement($competence);
    }

    /**
     * Add centreInteret
     *
     * @param \Interim\RecruteBundle\Entity\CentreInteret $centreInteret
     * @return Poste
     */
    public function addCentreInteret(\Interim\RecruteBundle\Entity\CentreInteret $centreInteret)
    {
        $this->centreInteret[] = $centreInteret;

        return $this;
    }

    /**
     * Remove centreInteret
     *
     * @param \Interim\RecruteBundle\Entity\CentreInteret $centreInteret
     */
    public function removeCentreInteret(\Interim\RecruteBundle\Entity\CentreInteret $centreInteret)
    {
        $this->centreInteret->removeElement($centreInteret);
    }
    public function __toString()
    {
    	return $this->titre;
    }
}


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

#include "chrome/browser/ash/policy/uploading/system_log_uploader.h"

#include <algorithm>
#include <map>
#include <utility>
#include <vector>

#include "base/bind.h"
#include "base/callback_helpers.h"
#include "base/command_line.h"
#include "base/files/file_util.h"
#include "base/files/scoped_file.h"
#include "base/files/scoped_temp_dir.h"
#include "base/metrics/histogram_macros.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "base/syslog_logging.h"
#include "base/task/post_task.h"
#include "base/task/sequenced_task_runner.h"
#include "base/task/thread_pool.h"
#include "base/values.h"
#include "chrome/browser/ash/policy/core/policy_pref_names.h"
#include "chrome/browser/ash/policy/uploading/upload_job_impl.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/device_identity/device_oauth2_token_service.h"
#include "chrome/browser/device_identity/device_oauth2_token_service_factory.h"
#include "chrome/browser/policy/chrome_browser_policy_connector.h"
#include "chrome/browser/policy/chrome_policy_conversions_client.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/common/chrome_features.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/extensions/extension_constants.h"
#include "components/feedback/redaction_tool.h"
#include "components/policy/core/browser/browser_policy_connector.h"
#include "components/policy/core/browser/policy_conversions.h"
#include "components/prefs/pref_service.h"
#include "components/user_manager/user_manager.h"
#include "net/http/http_request_headers.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "third_party/zlib/google/zip.h"

namespace policy {

namespace {

// The maximum number of successive retries.
const int kMaxNumRetries = 1;

// String constant defining the url tail we upload system logs to.
constexpr char kSystemLogUploadUrlTail[] = "/upload";

// The cutoff point (in bytes) after which log contents are ignored.
const size_t kLogCutoffSize = 50 * 1024 * 1024;  // 50 MiB.

// Pseudo-location of policy dump file. Policy is uploaded from memory,
// there is no actual file on disk.
constexpr char kPolicyDumpFileLocation[] = "/var/log/policy_dump.json";

// The file names of the system logs to upload.
// Note: do not add anything to this list without checking for PII in the file.
const char* const kSystemLogFileNames[] = {"/var/log/bios_info.txt",
                                           "/var/log/chrome/chrome",
                                           "/var/log/chrome/chrome.PREVIOUS",
                                           "/var/log/eventlog.txt",
                                           "/var/log/platform_info.txt",
                                           "/var/log/messages",
                                           "/var/log/messages.1",
                                           "/var/log/net.log",
                                           "/var/log/net.1.log",
                                           "/var/log/ui/ui.LATEST",
                                           "/var/log/update_engine.log"};

std::string ZipFiles(
    std::unique_ptr<SystemLogUploader::SystemLogs> system_logs) {
  base::ScopedTempDir temp_dir;
  base::FilePath zip_file;
  std::string compressed_logs;
  auto zipped_logs = std::make_unique<SystemLogUploader::SystemLogs>();

  if (!temp_dir.CreateUniqueTempDir())
    return compressed_logs;

  for (const auto& syslog_entry : *system_logs) {
    base::FilePath file_name = base::FilePath(syslog_entry.first).BaseName();
    base::FilePath file_path(temp_dir.GetPath().Append(file_name));
    if (!base::WriteFile(file_path, syslog_entry.second.c_str(),
                         syslog_entry.second.size())) {
      PLOG(ERROR) << "Can't write log file: " << file_path.value();
      continue;
    }
  }
  system_logs.reset();

  if (!base::CreateTemporaryFile(&zip_file)) {
    PLOG(ERROR) << "Failed to create file to store zipped logs";
    return compressed_logs;
  }
  if (!zip::Zip(/*src_dir=*/temp_dir.GetPath(), /*dest_file=*/zip_file,
                /*include_hidden_files=*/false)) {
    SYSLOG(ERROR) << "Failed to zip system logs";
    return compressed_logs;
  }
  if (!base::ReadFileToString(zip_file, &compressed_logs)) {
    PLOG(ERROR) << "Failed to read zipped system logs";
    return compressed_logs;
  }
  base::DeleteFile(zip_file);
  return compressed_logs;
}

std::string ReadAndRedactLogFile(feedback::RedactionTool* redactor,
                                 const base::FilePath& file_path) {
  std::string data;
  if (!base::ReadFileToStringWithMaxSize(file_path, &data, kLogCutoffSize) &&
      data.empty()) {
    SYSLOG(ERROR) << "Failed to read the system log file from the disk "
                  << file_path.value();
  }
  // We want to remove the last line completely because PII data might be cut in
  // half (redactor might not recognize it).
  if (!data.empty() && data.back() != '\n') {
    size_t pos = data.find_last_of('\n');
    data.erase(pos != std::string::npos ? pos + 1 : 0);
    data += "... [truncated]\n";
  }
  return SystemLogUploader::RemoveSensitiveData(redactor, data);
}

// Reads the system log files as binary files, redacts data, stores the files
// as pairs (file name, data) and returns. Called on blocking thread.
std::unique_ptr<SystemLogUploader::SystemLogs> ReadFiles() {
  auto system_logs = std::make_unique<SystemLogUploader::SystemLogs>();
  feedback::RedactionTool redactor(
      extension_misc::kBuiltInFirstPartyExtensionIds);
  for (const char* file_path : kSystemLogFileNames) {
    if (!base::PathExists(base::FilePath(file_path)))
      continue;
    system_logs->push_back(std::make_pair(
        file_path, ReadAndRedactLogFile(&redactor, base::FilePath(file_path))));
  }
  return system_logs;
}

// An implementation of the |SystemLogUploader::Delegate|, that is used to
// create an upload job and load system logs from the disk.
class SystemLogDelegate : public SystemLogUploader::Delegate {
 public:
  explicit SystemLogDelegate(
      scoped_refptr<base::SequencedTaskRunner> task_runner);

  SystemLogDelegate(const SystemLogDelegate&) = delete;
  SystemLogDelegate& operator=(const SystemLogDelegate&) = delete;

  ~SystemLogDelegate() override;

  // SystemLogUploader::Delegate:
  std::string GetPolicyAsJSON() override;
  void LoadSystemLogs(LogUploadCallback upload_callback) override;

  std::unique_ptr<UploadJob> CreateUploadJob(
      const GURL& upload_url,
      UploadJob::Delegate* delegate) override;

  void ZipSystemLogs(std::unique_ptr<SystemLogUploader::SystemLogs> system_logs,
                     ZippedLogUploadCallback upload_callback) override;

 private:
  // TaskRunner used for scheduling upload the upload task.
  const scoped_refptr<base::SequencedTaskRunner> task_runner_;
};

SystemLogDelegate::SystemLogDelegate(
    scoped_refptr<base::SequencedTaskRunner> task_runner)
    : task_runner_(task_runner) {}

SystemLogDelegate::~SystemLogDelegate() {}

std::string SystemLogDelegate::GetPolicyAsJSON() {
  bool include_user_policies = false;
  if (user_manager::UserManager::IsInitialized()) {
    if (user_manager::UserManager::Get()->GetPrimaryUser()) {
      include_user_policies =
          user_manager::UserManager::Get()->GetPrimaryUser()->IsAffiliated();
    }
  }
  auto client = std::make_unique<ChromePolicyConversionsClient>(
      ProfileManager::GetActiveUserProfile());
  return policy::DictionaryPolicyConversions(std::move(client))
      .EnableUserPolicies(include_user_policies)
      .EnableDeviceLocalAccountPolicies(true)
      .EnableDeviceInfo(true)
      .ToJSON();
}

void SystemLogDelegate::LoadSystemLogs(LogUploadCallback upload_callback) {
  // Run ReadFiles() in the thread that interacts with the file system and
  // return system logs to |upload_callback| on the current thread.
  base::ThreadPool::PostTaskAndReplyWithResult(
      FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT},
      base::BindOnce(&ReadFiles), std::move(upload_callback));
}

std::unique_ptr<UploadJob> SystemLogDelegate::CreateUploadJob(
    const GURL& upload_url,
    UploadJob::Delegate* delegate) {
  DeviceOAuth2TokenService* device_oauth2_token_service =
      DeviceOAuth2TokenServiceFactory::Get();

  CoreAccountId robot_account_id =
      device_oauth2_token_service->GetRobotAccountId();

  SYSLOG(INFO) << "Creating upload job for system log";
  net::NetworkTrafficAnnotationTag traffic_annotation =
      net::DefineNetworkTrafficAnnotation("policy_system_logs", R"(
        semantics {
          sender: "Chrome OS system log uploader"
          description:
              "Admins can ask that their devices regularly upload their system "
              "logs."
          trigger: "After reboot and every 12 hours."
          data: "Non-user specific, redacted system logs from /var/log/."
          destination: GOOGLE_OWNED_SERVICE
        }
        policy {
          cookies_allowed: NO
          setting: "This feature cannot be disabled in settings."
          chrome_policy {
            LogUploadEnabled {
                LogUploadEnabled: false
            }
          }
        }
      )");
  return std::make_unique<UploadJobImpl>(
      upload_url, robot_account_id,
      device_oauth2_token_service->GetAccessTokenManager(),
      g_browser_process->shared_url_loader_factory(), delegate,
      std::make_unique<UploadJobImpl::RandomMimeBoundaryGenerator>(),
      traffic_annotation, task_runner_);
}

void SystemLogDelegate::ZipSystemLogs(
    std::unique_ptr<SystemLogUploader::SystemLogs> system_logs,
    ZippedLogUploadCallback upload_callback) {
  base::ThreadPool::PostTaskAndReplyWithResult(
      FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT},
      base::BindOnce(&ZipFiles, std::move(system_logs)),
      std::move(upload_callback));
}

// Returns the system log upload frequency.
base::TimeDelta GetUploadFrequency() {
  base::TimeDelta upload_frequency(
      base::Milliseconds(SystemLogUploader::kDefaultUploadDelayMs));
  if (base::CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kSystemLogUploadFrequency)) {
    std::string string_value =
        base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
            switches::kSystemLogUploadFrequency);
    int frequency;
    if (base::StringToInt(string_value, &frequency)) {
      upload_frequency = base::Milliseconds(frequency);
    }
  }
  return upload_frequency;
}

std::string GetUploadUrl() {
  return g_browser_process->browser_policy_connector()
             ->GetDeviceManagementUrl() +
         kSystemLogUploadUrlTail;
}

}  // namespace

// Determines the time between log uploads.
const int64_t SystemLogUploader::kDefaultUploadDelayMs =
    12 * 60 * 60 * 1000;  // 12 hours

// Determines the time, measured from the time of last failed upload,
// after which the log upload is retried.
const int64_t SystemLogUploader::kErrorUploadDelayMs =
    120 * 1000;  // 120 seconds

// Determines max number of logs to be uploaded in kLogThrottleWindowDuration.
const int64_t SystemLogUploader::kLogThrottleCount = 100;

// Determines the time window for which the upload times should be stored.
const base::TimeDelta SystemLogUploader::kLogThrottleWindowDuration =
    base::Hours(24);

// String constant identifying the header field which stores the file type.
const char* const SystemLogUploader::kFileTypeHeaderName = "File-Type";

// String constant signalling that the data segment contains log files.
const char* const SystemLogUploader::kFileTypeLogFile = "log_file";

// String constant signalling that the segment contains a plain text.
const char* const SystemLogUploader::kContentTypePlainText = "text/plain";

// Template string constant for populating the name field.
const char* const SystemLogUploader::kNameFieldTemplate = "file%d";

// String constant signalling that the data segment contains zipped log files.
const char* const SystemLogUploader::kFileTypeZippedLogFile = "zipped_log_file";

// String constant for zipped logs name.
const char* const SystemLogUploader::kZippedLogsName = "logs";

// Name used for file containing zip archive of the logs.
const char* const SystemLogUploader::kZippedLogsFileName = "logs.zip";

// String constant signalling that the segment contains a binary file.
const char* const SystemLogUploader::kContentTypeOctetStream =
    "application/octet-stream";

const char* const SystemLogUploader::kSystemLogUploadResultHistogram =
    "Enterprise.SystemLogUploadResult";

SystemLogUploader::SystemLogUploader(
    std::unique_ptr<Delegate> syslog_delegate,
    const scoped_refptr<base::SequencedTaskRunner>& task_runner)
    : retry_count_(0),
      upload_frequency_(GetUploadFrequency()),
      task_runner_(task_runner),
      syslog_delegate_(std::move(syslog_delegate)),
      upload_enabled_(false) {
  if (!syslog_delegate_)
    syslog_delegate_ = std::make_unique<SystemLogDelegate>(task_runner);
  DCHECK(syslog_delegate_);
  SYSLOG(INFO) << "Creating system log uploader.";

  // Watch for policy changes.
  upload_enabled_subscription_ = ash::CrosSettings::Get()->AddSettingsObserver(
      ash::kSystemLogUploadEnabled,
      base::BindRepeating(&SystemLogUploader::RefreshUploadSettings,
                          base::Unretained(this)));

  // Fetch the current value of the policy.
  RefreshUploadSettings();

  // Immediately schedule the next system log upload (last_upload_attempt_ is
  // set to the start of the epoch, so this will trigger an update upload in the
  // immediate future).
  ScheduleNextSystemLogUpload(upload_frequency_);
}

SystemLogUploader::~SystemLogUploader() {}

void SystemLogUploader::OnSuccess() {
  SYSLOG(INFO) << "Upload successful.";
  upload_job_.reset();
  last_upload_attempt_ = base::Time::NowFromSystemTime();
  log_upload_in_progress_ = false;
  retry_count_ = 0;

  UMA_HISTOGRAM_ENUMERATION(
      kSystemLogUploadResultHistogram,
      base::FeatureList::IsEnabled(features::kUploadZippedSystemLogs)
          ? ZIPPED_LOGS_UPLOAD_SUCCESS
          : NON_ZIPPED_LOGS_UPLOAD_SUCCESS);

  // On successful log upload schedule the next log upload after
  // upload_frequency_ time from now.
  ScheduleNextSystemLogUpload(upload_frequency_);
}

void SystemLogUploader::OnFailure(UploadJob::ErrorCode error_code) {
  upload_job_.reset();
  last_upload_attempt_ = base::Time::NowFromSystemTime();
  log_upload_in_progress_ = false;

  UMA_HISTOGRAM_ENUMERATION(
      kSystemLogUploadResultHistogram,
      base::FeatureList::IsEnabled(features::kUploadZippedSystemLogs)
          ? ZIPPED_LOGS_UPLOAD_FAILURE
          : NON_ZIPPED_LOGS_UPLOAD_FAILURE);
  //  If we have hit the maximum number of retries, terminate this upload
  //  attempt and schedule the next one using the normal delay. Otherwise, retry
  //  uploading after kErrorUploadDelayMs milliseconds.
  if (retry_count_++ < kMaxNumRetries) {
    SYSLOG(ERROR) << "Upload failed with error code " << error_code
                  << ", retrying later.";
    ScheduleNextSystemLogUpload(base::Milliseconds(kErrorUploadDelayMs));
  } else {
    // No more retries.
    SYSLOG(ERROR) << "Upload failed with error code " << error_code
                  << ", no more retries.";
    retry_count_ = 0;
    ScheduleNextSystemLogUpload(upload_frequency_);
  }
}

// static
std::string SystemLogUploader::RemoveSensitiveData(
    feedback::RedactionTool* redactor,
    const std::string& data) {
  return redactor->Redact(data);
}

void SystemLogUploader::ScheduleNextSystemLogUploadImmediately() {
  ScheduleNextSystemLogUpload(base::TimeDelta());
}

void SystemLogUploader::RefreshUploadSettings() {
  // Attempt to fetch the current value of the reporting settings.
  // If trusted values are not available, register this function to be called
  // back when they are available.
  ash::CrosSettings* settings = ash::CrosSettings::Get();
  auto trust_status = settings->PrepareTrustedValues(base::BindOnce(
      &SystemLogUploader::RefreshUploadSettings, weak_factory_.GetWeakPtr()));
  if (trust_status != ash::CrosSettingsProvider::TRUSTED)
    return;

  // CrosSettings are trusted - we want to use the last trusted values, by
  // default do not upload system logs.
  if (!settings->GetBoolean(ash::kSystemLogUploadEnabled, &upload_enabled_)) {
    upload_enabled_ = false;
  }
}

void SystemLogUploader::UploadSystemLogs(
    std::unique_ptr<SystemLogs> system_logs) {
  // Must be called on the main thread.
  DCHECK(thread_checker_.CalledOnValidThread());
  DCHECK(!upload_job_);

  SYSLOG(INFO) << "Uploading system logs.";

  GURL upload_url(GetUploadUrl());
  DCHECK(upload_url.is_valid());
  upload_job_ = syslog_delegate_->CreateUploadJob(upload_url, this);

  // Start a system log upload.
  int file_number = 1;
  for (const auto& syslog_entry : *system_logs) {
    std::map<std::string, std::string> header_fields;
    std::unique_ptr<std::string> data =
        std::make_unique<std::string>(syslog_entry.second);
    header_fields.insert(std::make_pair(kFileTypeHeaderName, kFileTypeLogFile));
    header_fields.insert(std::make_pair(net::HttpRequestHeaders::kContentType,
                                        kContentTypePlainText));
    upload_job_->AddDataSegment(
        base::StringPrintf(kNameFieldTemplate, file_number), syslog_entry.first,
        header_fields, std::move(data));
    ++file_number;
  }
  upload_job_->Start();
}

void SystemLogUploader::UploadZippedSystemLogs(std::string zipped_system_logs) {
  // Must be called on the main thread.
  DCHECK(thread_checker_.CalledOnValidThread());
  DCHECK(!upload_job_);

  if (zipped_system_logs.empty()) {
    SYSLOG(ERROR) << "No zipped log to upload";
    return;
  }

  SYSLOG(INFO) << "Uploading zipped system logs.";

  GURL upload_url(GetUploadUrl());
  DCHECK(upload_url.is_valid());
  upload_job_ = syslog_delegate_->CreateUploadJob(upload_url, this);

  // Start a system log upload.
  std::map<std::string, std::string> header_fields;
  std::unique_ptr<std::string> data =
      std::make_unique<std::string>(zipped_system_logs);
  header_fields.insert(
      std::make_pair(kFileTypeHeaderName, kFileTypeZippedLogFile));
  header_fields.insert(std::make_pair(net::HttpRequestHeaders::kContentType,
                                      kContentTypeOctetStream));
  upload_job_->AddDataSegment(kZippedLogsName, kZippedLogsFileName,
                              header_fields, std::move(data));
  upload_job_->Start();
}

void SystemLogUploader::StartLogUpload() {
  // Must be called on the main thread.
  DCHECK(thread_checker_.CalledOnValidThread());

  if (upload_enabled_) {
    SYSLOG(INFO) << "Reading system logs for upload.";
    log_upload_in_progress_ = true;
    syslog_delegate_->LoadSystemLogs(base::BindOnce(
        &SystemLogUploader::OnSystemLogsLoaded, weak_factory_.GetWeakPtr()));
  } else {
    // If upload is disabled, schedule the next attempt after 12h.
    SYSLOG(INFO) << "System log upload is disabled, rescheduling.";
    retry_count_ = 0;
    last_upload_attempt_ = base::Time::NowFromSystemTime();
    ScheduleNextSystemLogUpload(upload_frequency_);
  }
}

void SystemLogUploader::OnSystemLogsLoaded(
    std::unique_ptr<SystemLogs> system_logs) {
  // Must be called on the main thread.
  DCHECK(thread_checker_.CalledOnValidThread());
  system_logs->push_back(std::make_pair(kPolicyDumpFileLocation,
                                        syslog_delegate_->GetPolicyAsJSON()));

  if (base::FeatureList::IsEnabled(features::kUploadZippedSystemLogs)) {
    SYSLOG(INFO) << "Starting zipped system log upload.";
    syslog_delegate_->ZipSystemLogs(
        std::move(system_logs),
        base::BindOnce(&SystemLogUploader::UploadZippedSystemLogs,
                       weak_factory_.GetWeakPtr()));
  } else {
    SYSLOG(INFO) << "Starting system log upload.";
    UploadSystemLogs(std::move(system_logs));
  }
}

// Update the list of logs within kLogThrottleWindowDuration window and add the
// latest log upload time if any.
base::Time SystemLogUploader::UpdateLocalStateForLogs() {
  const base::Time now = base::Time::NowFromSystemTime();
  PrefService* local_state = g_browser_process->local_state();

  const base::Value* prev_log_uploads =
      local_state->GetList(policy::prefs::kStoreLogStatesAcrossReboots);

  std::vector<base::Time> updated_log_uploads;

  for (const base::Value& item : prev_log_uploads->GetListDeprecated()) {
    // ListValue stores Value type and Value does not support base::Time,
    // so we store double and convert to base::Time here.
    const base::Time current_item_time =
        base::Time::FromDoubleT(item.GetDouble());

    // Logs are valid only if they occur in previous kLogThrottleWindowDuration
    // time window.
    if (now - current_item_time <= kLogThrottleWindowDuration)
      updated_log_uploads.push_back(current_item_time);
  }

  if (!last_upload_attempt_.is_null() &&
      (updated_log_uploads.empty() ||
       last_upload_attempt_ > updated_log_uploads.back())) {
    updated_log_uploads.push_back(last_upload_attempt_);
  }

  // This happens only in case of ScheduleNextSystemLogUploadImmediately. It is
  // sufficient to delete only one entry as at most 1 entry is appended on the
  // method call, hence the list size would exceed by at most 1.
  if (updated_log_uploads.size() > kLogThrottleCount)
    updated_log_uploads.erase(updated_log_uploads.begin());

  // Create a list to be updated for the pref.
  base::Value updated_prev_log_uploads(base::Value::Type::LIST);
  for (auto it : updated_log_uploads) {
    updated_prev_log_uploads.Append(it.ToDoubleT());
  }
  local_state->Set(policy::prefs::kStoreLogStatesAcrossReboots,
                   updated_prev_log_uploads);

  // Write the changes to the disk to prevent loss of changes.
  local_state->CommitPendingWrite();
  // If there are no log entries till now, return zero value.
  return updated_log_uploads.empty() ? base::Time() : updated_log_uploads[0];
}

void SystemLogUploader::ScheduleNextSystemLogUpload(base::TimeDelta frequency) {
  // Don't schedule a new system log upload if there's a log upload in progress
  // (it will be scheduled once the current one completes).
  if (log_upload_in_progress_) {
    SYSLOG(INFO) << "In the middle of a system log upload, not scheduling the "
                 << "next one until this one finishes.";
    return;
  }
  base::Time last_valid_log_upload = UpdateLocalStateForLogs();
  // Calculate when to fire off the next update.
  base::TimeDelta delay = std::max(
      (last_upload_attempt_ + frequency) - base::Time::NowFromSystemTime(),
      base::TimeDelta());

  // To ensure at most kLogThrottleCount logs are uploaded in
  // kLogThrottleWindowDuration time.
  if (g_browser_process->local_state()
              ->GetList(policy::prefs::kStoreLogStatesAcrossReboots)
              ->GetListDeprecated()
              .size() >= kLogThrottleCount &&
      !frequency.is_zero()) {
    delay = std::max(delay, last_valid_log_upload + kLogThrottleWindowDuration -
                                base::Time::NowFromSystemTime());
  }

  SYSLOG(INFO) << "Scheduling next system log upload " << delay << " from now.";
  // Ensure that we never have more than one pending delayed task
  // (InvalidateWeakPtrs() will cancel any pending calls to log uploads).
  weak_factory_.InvalidateWeakPtrs();
  task_runner_->PostDelayedTask(
      FROM_HERE,
      base::BindOnce(&SystemLogUploader::StartLogUpload,
                     weak_factory_.GetWeakPtr()),
      delay);
}

}  // namespace policy


text:
include (CMakeParseArguments)

# Annoyingly, compiler flags in CMake are a space-separated string,
# not a list. This function allows for more consistent behaviour.
function (CTAddCompilerFlags scope)
  cmake_parse_arguments(args "" "" "FLAGS" ${ARGN})

  set (space_separated_flags "")
  foreach (flag IN LISTS args_FLAGS)
    set (space_separated_flags "${space_separated_flags} ${flag}")
  endforeach ()

  if (scope STREQUAL "TARGETS")
    set_property(TARGET ${args_UNPARSED_ARGUMENTS} APPEND_STRING
      PROPERTY COMPILE_FLAGS "${space_separated_flags}")

  elseif (scope STREQUAL "SOURCES")
    set_property(SOURCE ${args_UNPARSED_ARGUMENTS} APPEND_STRING
      PROPERTY COMPILE_FLAGS "${space_separated_flags}")

  elseif (scope STREQUAL "DIRECTORY")
    # Using add_definitions() feels slightly seedy--these are *flags*, not
    # *definitions* dammit!--but the docs say you can do it. CMake has no
    # COMPILE_FLAGS directory property, and we can't really use
    # CMAKE_<LANG>_FLAGS because they're passed to the linker as well, which
    # is surprising.
    add_definitions(${args_FLAGS})
  else ()
    message(FATAL_ERROR "Invalid scope '${scope}' passed CTAddCompilerFlags")
  endif ()
endfunction ()


text:
"""

Python Interchangeable Virtual Instrument Library

Copyright (c) 2012-2017 Alex Forencich

Modified by Jeff Wurzbach 2014

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

"""

__all__ = [
        # Base IVI class
        "ivi",
        # IVI abstract classes
        "scope",
        "dmm",
        "fgen",
        "dcpwr",
        "swtch",
        "pwrmeter",
        "specan",
        "rfsiggen",
        "counter",
        # Extra IVI base classes
        "extra",
        # Generic IVI drivers
        "scpi",
        # IVI drivers
        "agilent",
        "anritsu",
        "dicon",
        "chroma",
        "colby",
        "ics",
        "jdsu",
        "lecroy",
        "rigol",
        "santec",
        "tektronix",
        "testequity"]

from .ivi import *
from . import *


text:
#ifndef _RDT_DISP_H_
#define _RDT_DISP_H_

#include "rdt_defs.h"

/*****************************************************************************/
/*  function prototypes                                                      */
/*****************************************************************************/
extern void rdt_display_envyro(cheese_envyro *envyro, CHEESE_PTR charpos);   /* display an environment        */
extern void rdt_display_error(cheese_envyro *envyro, short code);             /* report error; stop interpreter*/
extern void rdt_display_str(cheese_envyro *envyro, char *s);
extern void rdt_display_char(cheese_envyro *envyro, char c);
extern void rdt_display_int(cheese_envyro *envyro, CHEESE_WORD n);
extern char rdt_input_char(cheese_envyro *envyro);
extern CHEESE_WORD rdt_input_int(cheese_envyro *envyro);

#endif /* _RDT_DISP_H_ */


text:
package org.opensplice.cm.qos;

public class SharePolicy {
    public String name;
    public boolean enable;
    public static final SharePolicy DEFAULT = new SharePolicy(null, false);

    public SharePolicy(String _name, boolean _enable){
        name = _name;
        enable = _enable;
    }

    public SharePolicy copy(){
        String str;
        if(this.name != null){
            str = new String(this.name);
        } else {
            str = null;
        }
        return new SharePolicy(str, this.enable);
    }
}


text:
@interface RootViewController ()

@property(nonatomic, strong, readwrite) IBOutlet UIButton *scanButton;
@property(nonatomic, strong, readwrite) IBOutlet UIButton *scanPicoPikaButton;
@property(nonatomic, strong, readwrite) IBOutlet UISwitch *manualSwitch;
@property(nonatomic, strong, readwrite) IBOutlet UISwitch *expirySwitch;
@property(nonatomic, strong, readwrite) IBOutlet UISwitch *cvvSwitch;
@property(nonatomic, strong, readwrite) IBOutlet UISwitch *zipSwitch;
@property(nonatomic, strong, readwrite) IBOutlet UILabel *outcomeLabel;
@property(nonatomic, strong, readwrite) IBOutlet UIImageView *cardImageView;
@property(nonatomic, strong, readwrite) IBOutlet UISwitch *processSwitch;
@property(nonatomic, strong, readwrite) IBOutlet UISwitch *confirmSwitch;
@property(nonatomic, strong, readwrite) IBOutlet UISwitch *hideCardImageSwitch;
@property(nonatomic, strong, readwrite) IBOutlet UISwitch *redactSwitch;
@property(nonatomic, strong, readwrite) IBOutlet UISwitch *disableManualEntrySwitch;
@property(nonatomic, strong, readwrite) IBOutlet UISwitch *useCardIOLogoSwitch;
@property(nonatomic, strong, readwrite) IBOutlet UISwitch *doABTestingSwitch;
@property(nonatomic, strong, readwrite) IBOutlet UISegmentedControl *modalPresentationStyleSegment;
@property(nonatomic, strong, readwrite) IBOutlet UITextField *scannedImageDurationField;
@property(nonatomic, strong, readwrite) IBOutlet CardIOView *hideableCardIOView;

@property(nonatomic, strong, readwrite) IBOutlet UIButton *languageButton;
@property(nonatomic, strong, readwrite) NSString *language;

@property(nonatomic, strong, readwrite) CardIOView *adHocCardIOView;

@property(nonatomic, assign, readwrite) CGFloat originalOutcomeLabelWidth;

@property(nonatomic, assign, readwrite) BOOL        i18nAutopilot;
@property(nonatomic, strong, readwrite) NSArray    *i18nLanguages;
@property(nonatomic, assign, readwrite) NSInteger   i18nLanguageIndex;
@property(nonatomic, assign, readwrite) NSInteger   i18nPhase;
@property(nonatomic, strong, readwrite) CardIOPaymentViewController *i18nCardIOPaymentViewController;
@property(nonatomic, strong, readwrite) UIAlertView *i18nAlertView;
@property(nonatomic, strong, readwrite) UIView      *i18nAlertViewBackground;

@end

#pragma mark -

@implementation RootViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
  if((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(didReceiveWillResignActiveNotification:)
                                                 name:UIApplicationWillResignActiveNotification
                                               object:[UIApplication sharedApplication]];
#if !CARDIO_DEBUG
    self.doABTestingSwitch.enabled = NO;
#endif
  }
  return self;
}

- (IBAction)scan {
  CardIOPaymentViewController *paymentVC = [[CardIOPaymentViewController alloc] initWithPaymentDelegate:self scanningEnabled:!self.manualSwitch.on];
  paymentVC.collectExpiry = self.expirySwitch.on;
  paymentVC.collectCVV = self.cvvSwitch.on;
  paymentVC.collectPostalCode = self.zipSwitch.on;
  paymentVC.disableManualEntryButtons = self.disableManualEntrySwitch.on;
  paymentVC.useCardIOLogo = self.useCardIOLogoSwitch.on;
  paymentVC.allowFreelyRotatingCardGuide = NO;
  paymentVC.scannedImageDuration = [self.scannedImageDurationField.text floatValue];
#if CARDIO_DEBUG
  paymentVC.doABTesting = self.doABTestingSwitch.on;
#endif

  paymentVC.languageOrLocale = self.language;

  paymentVC.suppressScanConfirmation = self.confirmSwitch ? !self.confirmSwitch.on : NO;
  paymentVC.suppressScannedCardImage = self.hideCardImageSwitch ? self.hideCardImageSwitch.on : NO;
  paymentVC.maskManualEntryDigits = self.doABTestingSwitch.on;

  if (self.modalPresentationStyleSegment) {
    paymentVC.modalPresentationStyle = (UIModalPresentationStyle)self.modalPresentationStyleSegment.selectedSegmentIndex;
  }

  [self presentViewController:paymentVC animated:YES completion:nil];
}

- (IBAction)scanPicoPika {
#if TEST_HIDEABLE_CARDIOVIEW
  if (!self.hideableCardIOView.hidden) {
    self.hideableCardIOView.hidden = YES;
    return;
  }
#else
  if (self.adHocCardIOView) {
    [self.adHocCardIOView removeFromSuperview];
    self.adHocCardIOView = nil;
    return;
  }
#endif

  CardIOView *cardIOView;
#if TEST_HIDEABLE_CARDIOVIEW
  cardIOView = self.hideableCardIOView;
#else
  self.adHocCardIOView = [[CardIOView alloc] initWithFrame:self.hideableCardIOView.frame];
  self.adHocCardIOView.delegate = self;
  cardIOView = self.adHocCardIOView;
#endif

  cardIOView.scanExpiry = self.expirySwitch.on;
  cardIOView.useCardIOLogo = self.useCardIOLogoSwitch.on;
  //  cardIOView.allowFreelyRotatingCardGuide = NO;
  cardIOView.scannedImageDuration = [self.scannedImageDurationField.text floatValue];

  cardIOView.languageOrLocale = self.language;

#if TEST_HIDEABLE_CARDIOVIEW
  self.hideableCardIOView.hidden = NO;
#else
  [self.view addSubview:self.adHocCardIOView];
#endif
}

- (void)updateLanguageDisplay {
  NSString *buttonText = nil;
  if ([self.language length]) {
    buttonText = self.language;
  }
  else {
    buttonText = @"device";
  }
  [self.languageButton setTitle:[NSString stringWithFormat:@"Language [%@]", buttonText] forState:UIControlStateNormal];
}

- (IBAction)languageChangeAction:(id)sender {
  NSArray *choices = @[@"ar", @"da", @"de", @"en", @"en_AU", @"en_GB", @"es", @"es_MX", @"fr", @"he", @"is", @"it", @"ja", @"ko", @"ms", @"nb", @"nl", @"pl", @"pt", @"pt_BR", @"ru", @"sv", @"th", @"tr", @"zh-Hans", @"zh-Hant", @"zh-Hant_TW"];

  iccChoicesSelectViewController *vc = [[iccChoicesSelectViewController alloc] initWithTitle:@"Language" choices:choices currentSelection:self.language completion:^(NSString *selection) {
    if (selection) {
      self.language = selection;
      [self updateLanguageDisplay];
    }
    [self dismissViewControllerAnimated:YES completion:nil];
  }];

  UINavigationController* nc = [[UINavigationController alloc] initWithRootViewController:vc];
  [self presentViewController:nc animated:YES completion:nil];
}

#pragma mark - I18n testing

#if CARDIO_DEBUG

- (IBAction)doI18n {
  self.i18nAutopilot = self.doABTestingSwitch.on;
  self.i18nLanguages = [CardIOLocalizer allLanguages];
  self.i18nLanguageIndex = 0;
  self.i18nPhase = 0;
  [self displayI18nCardIOPaymentViewController];
}

- (void)displayI18nCardIOPaymentViewController {
  NSString *language = self.i18nLanguages[self.i18nLanguageIndex];

  self.i18nCardIOPaymentViewController = [[CardIOPaymentViewController alloc] initWithPaymentDelegate:self scanningEnabled:(self.i18nPhase == 0)];
  self.i18nCardIOPaymentViewController.collectExpiry = YES;
  self.i18nCardIOPaymentViewController.collectCVV = YES;
  self.i18nCardIOPaymentViewController.collectPostalCode = YES;
  self.i18nCardIOPaymentViewController.disableManualEntryButtons = NO;
  self.i18nCardIOPaymentViewController.useCardIOLogo = NO;
  self.i18nCardIOPaymentViewController.languageOrLocale = language;

  UIView *coverView = [[UIView alloc] initWithFrame:self.i18nCardIOPaymentViewController.view.bounds];
  coverView.backgroundColor = [UIColor clearColor];
  coverView.userInteractionEnabled = YES;

  UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, coverView.frame.size.height / 5, coverView.frame.size.width, 44)];
  label.text = language;
  label.textAlignment = NSTextAlignmentCenter;
  label.textColor = [UIColor greenColor];
  label.font = [UIFont fontWithName:@"Helvetica" size:32];
  label.backgroundColor = [UIColor clearColor];
  [coverView addSubview:label];

  UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(displayNextI18nScreen)];
  [coverView addGestureRecognizer:tapRecognizer];

  UISwipeGestureRecognizer *tapLeftRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(displayNextI18nScreen)];
  tapLeftRecognizer.direction = UISwipeGestureRecognizerDirectionLeft;
  [coverView addGestureRecognizer:tapLeftRecognizer];

  UISwipeGestureRecognizer *tapRightRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(displayPreviousI18nScreen)];
  tapRightRecognizer.direction = UISwipeGestureRecognizerDirectionRight;
  [coverView addGestureRecognizer:tapRightRecognizer];

  [self presentViewController:self.i18nCardIOPaymentViewController animated:NO completion:nil];
  [self.i18nCardIOPaymentViewController.view addSubview:coverView];

  if (self.i18nAutopilot) {
    [self captureI18nScreenAndAdvance];
  }
}

- (void)dismissCurrentI18nScreen {
  if (self.i18nCardIOPaymentViewController) {
    [self.i18nCardIOPaymentViewController dismissViewControllerAnimated:NO completion:nil];
    self.i18nCardIOPaymentViewController = nil;
  }
  else if (self.i18nAlertView) {
    [self.i18nAlertView dismissWithClickedButtonIndex:0 animated:NO];
    self.i18nAlertView = nil;
  }
}

- (void)displayNextI18nScreen {
  [self dismissCurrentI18nScreen];

  self.i18nLanguageIndex++;

  if (self.i18nLanguageIndex < [self.i18nLanguages count]) {
    if (self.i18nPhase < 2) {
      [self displayI18nCardIOPaymentViewController];
    }
  }
  else {
    self.i18nLanguageIndex = 0;
    self.i18nPhase++;

    if (self.i18nPhase < 2) {
      [self displayI18nCardIOPaymentViewController];
    }
    else {
      if (self.i18nAlertViewBackground != nil) {
        [self.i18nAlertViewBackground removeFromSuperview];
        self.i18nAlertViewBackground = nil;
      }
    }
  }
}

- (void)displayPreviousI18nScreen {
  [self dismissCurrentI18nScreen];

  self.i18nLanguageIndex--;

  if (self.i18nLanguageIndex >= 0) {
    if (self.i18nPhase == 0 || self.i18nPhase == 1) {
      [self displayI18nCardIOPaymentViewController];
    }
  }
  else {
    self.i18nLanguageIndex = [self.i18nLanguages count] - 1;
    self.i18nPhase--;

    if (self.i18nPhase < 0) {
      // do nothing
    }
    else if (self.i18nPhase < 2) {
      if (self.i18nAlertViewBackground != nil) {
        [self.i18nAlertViewBackground removeFromSuperview];
        self.i18nAlertViewBackground = nil;
      }
      [self displayI18nCardIOPaymentViewController];
    }
  }
}

- (void)captureI18nScreenAndAdvance {
  dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(NSEC_PER_SEC)), dispatch_get_main_queue(), ^(void){
    UIWindow    *keyWindow = [UIApplication sharedApplication].keyWindow;
    UIGraphicsBeginImageContext(keyWindow.bounds.size);
    [keyWindow.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSData * data = UIImagePNGRepresentation(image);

    NSString *suffix;
    switch (self.i18nPhase) {
      case 0:
        suffix = @"camera";
        break;
      case 1:
        suffix = @"data";
        break;
      case 2:
        suffix = @"unauthorized";
        break;
    }
    NSString *applicationDocumentsDir = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString *filename = [NSString stringWithFormat:@"%@.png", [NSString stringWithFormat:@"%@-%@",
                                                                self.i18nLanguages[self.i18nLanguageIndex], suffix]];
    NSString *storePath = [applicationDocumentsDir stringByAppendingPathComponent:filename];
    NSLog(@"*** Writing file: '%@' ***", storePath);
    [data writeToFile:storePath atomically:YES];

    if (self.i18nLanguageIndex + 1 < [self.i18nLanguages count] || self.i18nPhase < 2) {
      [self displayNextI18nScreen];
    }
    else {
      [self dismissCurrentI18nScreen];
      [self.i18nAlertViewBackground removeFromSuperview];
      self.i18nAlertViewBackground = nil;
    }
  });
}

#endif // CARDIO_DEBUG

#pragma mark - View lifecycle etc.

- (void)viewWillAppear:(BOOL)animated {
  [super viewWillAppear:animated];

  [self updateLanguageDisplay];

  NSUInteger systemMajorVersion = [[[[[UIDevice currentDevice] systemVersion] componentsSeparatedByString:@"."] objectAtIndex:0] intValue];
  if (systemMajorVersion >= 7) {
    // There are ways to do this in the .xib, but this is a non-disruptive hack for the short run
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
      CGFloat delta = [UIApplication sharedApplication].statusBarFrame.size.height;
      for (UIView *subview in self.view.subviews) {
        if (subview != self.cardImageView) {
          subview.frame = CGRectByAddingYOffset(subview.frame, delta);
        }
      }
    });
  }
}

- (void)viewDidLoad {
  [super viewDidLoad];

  self.hideableCardIOView.delegate = self;

  self.originalOutcomeLabelWidth = self.outcomeLabel.frame.size.width;

#if TEST_GENERATED_MODELS
  [TestGeneratedModels selfCheck];
#endif

  [CardIOUtilities preload];
}

- (UIStatusBarStyle) preferredStatusBarStyle {
  return UIStatusBarStyleDefault;
}

- (BOOL)prefersStatusBarHidden {
  return [[[NSBundle mainBundle] objectForInfoDictionaryKey:@"UIStatusBarHidden"] boolValue];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
  return YES;
}

- (BOOL)shouldAutorotate {
  return YES;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
  return UIInterfaceOrientationMaskAll;
}

- (void)didReceiveWillResignActiveNotification:(NSNotification *)notification {
  [self setOutcomeText:@"" image:nil];
}

- (void)setOutcomeText:(NSString *)text image:(UIImage *)image {
  self.outcomeLabel.text = text;

  CGRect frame = self.outcomeLabel.frame;
  frame.size.width = self.originalOutcomeLabelWidth;
  self.outcomeLabel.frame = frame;
  [self.outcomeLabel sizeToFit];

  self.cardImageView.image = image;
}

#pragma mark - CardIOPaymentViewControllerDelegate methods

- (void)userDidCancelPaymentViewController:(CardIOPaymentViewController *)paymentViewController {
  CardIOLog(@"Received userDidCancelPaymentViewController:");
  [self setOutcomeText:@"Cancelled" image:nil];
  [paymentViewController dismissViewControllerAnimated:YES completion:nil];
}

- (void)userDidProvideCreditCardInfo:(CardIOCreditCardInfo *)info inPaymentViewController:(CardIOPaymentViewController *)paymentViewController {
  CardIOLog(@"Received userDidProvideCreditCardInfo:inPaymentViewController:");
  NSMutableString *resultStr = [NSMutableString stringWithCapacity:100];

  [resultStr appendFormat:@"Number (%@): %@\n", info.scanned ? @"scanned" : @"manual", [info redactedCardNumber]];

  NSString *cardType = [CardIOCreditCardInfo displayStringForCardType:info.cardType usingLanguageOrLocale:nil];
  [resultStr appendFormat:@"%@\n", [cardType length] ? cardType : @"Unrecognized card type"];

  if(self.expirySwitch.on) {
    [resultStr appendFormat:@"Expiry: %02lu/%02lu\n", (unsigned long)info.expiryMonth, (unsigned long)info.expiryYear];
  }
  if(self.cvvSwitch.on) {
    [resultStr appendFormat:@"CVV: %@\n", info.cvv];
  }
  if(self.zipSwitch.on) {
    [resultStr appendFormat:@"Postal Code: %@\n", info.postalCode];
  }

#if CARDIO_DEBUG
  [self setOutcomeText:resultStr image:info.cardImage];
#else
  [self setOutcomeText:resultStr image:nil];
#endif

  [paymentViewController dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark CardIOViewDelegate method

- (void)cardIOView:(CardIOView *)cardIOView didScanCard:(CardIOCreditCardInfo *)cardInfo {
  CardIOLog(@"Received cardIOView:didScanCard:");
  if (cardInfo) {
    NSMutableString *resultStr = [NSMutableString stringWithCapacity:100];
    [resultStr appendFormat:@"Number (%@): %@\n", @"scanned", [cardInfo redactedCardNumber]];

    NSString *cardType = [CardIOCreditCardInfo displayStringForCardType:cardInfo.cardType usingLanguageOrLocale:nil];
    [resultStr appendFormat:@"%@\n", [cardType length] ? cardType : @"Unrecognized card type"];

    if(self.expirySwitch.on) {
      [resultStr appendFormat:@"Expiry: %02lu/%02lu\n", (unsigned long)cardInfo.expiryMonth, (unsigned long)cardInfo.expiryYear];
    }

#if CARDIO_DEBUG
    [self setOutcomeText:resultStr image:cardInfo.cardImage];
#else
    [self setOutcomeText:resultStr image:nil];
#endif
  }
  else {
    [self setOutcomeText:@"Cancelled" image:nil];
  }

#if TEST_HIDEABLE_CARDIOVIEW
  self.hideableCardIOView.hidden = YES;
#else
  [self.adHocCardIOView removeFromSuperview];
  self.adHocCardIOView = nil;
#endif
}

#pragma mark - Memory management

- (void)dealloc {
  [[NSNotificationCenter defaultCenter] removeObserver:self];
  self.hideableCardIOView.delegate = nil;
}

@end


text:
var Utils	= {
	getAudioContextClass : function() {
		var audioContext	= window.webkitAudioContext || window.AudioContext;

		if (audioContext == null)
			console.warn("This browser does not implement the AudioContext API");

		return audioContext;
	},

	getRafFunc : function() {
		return window.requestAnimationFrame ||
			window.webkitRequestAnimationFrame ||
			window.mozRequestAnimationFrame ||
			window.msRequestAnimationFrame ||
			window.oRequestAnimationFrame ||
			function(zCallback) {
				return setTimeout(zCallback, 1.0 / 60.0);
			};
	},

	bindFunc : function(cScope, zFunction) {
		var aBoundArgs	= Array.prototype.slice.call(arguments, 2);

		return function(args) {
			aBoundArgs	= aBoundArgs.concat(Array.prototype.slice.call(arguments));

			zFunction.apply(cScope, aBoundArgs);
		};
	},

	clamp : function(fValue, fMin, fMax) {
		return Math.min(Math.max(0.0, fValue), fMax);
	}
};


text:
using System;

namespace SuperGlue.EventStore.Timeouts
{
    public static class TimeOutManager
    {
        private static readonly object SyncRoot = new object();

        public static Func<IStoreTimeouts> GetCurrent = () => null;

        public static void Configure(Func<IStoreTimeouts> getTimeOutManager)
        {
            lock (SyncRoot)
            {
                GetCurrent = getTimeOutManager;
            }
        }
    }
}


text:
package org.dasein.cloud.openstack.nova.os.network;

import org.apache.http.HttpStatus;
import org.apache.log4j.Logger;
import org.dasein.cloud.*;
import org.dasein.cloud.identity.ServiceAction;
import org.dasein.cloud.network.AbstractIpAddressSupport;
import org.dasein.cloud.network.AddressType;
import org.dasein.cloud.network.IPVersion;
import org.dasein.cloud.network.IpAddress;
import org.dasein.cloud.network.IPAddressCapabilities;
import org.dasein.cloud.network.IpAddressSupport;
import org.dasein.cloud.network.IpForwardingRule;
import org.dasein.cloud.network.Protocol;
import org.dasein.cloud.openstack.nova.os.NovaException;
import org.dasein.cloud.openstack.nova.os.NovaMethod;
import org.dasein.cloud.openstack.nova.os.NovaOpenStack;
import org.dasein.cloud.util.APITrace;
import org.dasein.util.CalendarWrapper;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * IP addresses services for Dasein Cloud to access OpenStack Nova floating IPs.
 * @author George Reese (george.reese@imaginary.com)
 * @since 2011.10
 * @version 2011.10
 * @version 2012.04.1 Added some intelligence around features Rackspace does not support
 * @version 2013.02 updated to 2013.02 model
 */
public class NovaFloatingIP extends AbstractIpAddressSupport<NovaOpenStack> {
    static private final Logger logger = NovaOpenStack.getLogger(NovaFloatingIP.class, "std");

    static public final String QUANTIUM_TARGET = "/floating-ips";
    static public final String NOVA_TARGET     = "/os-floating-ips";

    static private final ExecutorService threadPool = Executors.newFixedThreadPool(10);

    NovaFloatingIP(NovaOpenStack cloud) {
        super(cloud);
    }

    private String getEndpoint() {
        return NOVA_TARGET;
    }

    @Override
    public void assign(@Nonnull String addressId, @Nonnull String serverId) throws InternalException, CloudException {
        APITrace.begin(getProvider(), "IpAddress.assign");
        try {
            HashMap<String,Object> json = new HashMap<String,Object>();
            HashMap<String,Object> action = new HashMap<String,Object>();
            IpAddress addr = getIpAddress(addressId);

            if( addr == null ) {
                throw new ResourceNotFoundException("IP", addressId);
            }
            //action.put("server", serverId);
            action.put("address",addr.getRawAddress().getIpAddress());
            json.put("addFloatingIp", action);

            NovaMethod method = new NovaMethod(getProvider());

            method.postServers("/servers", serverId, new JSONObject(json), true);
        }
        finally {
            APITrace.end();
        }
    }

    @Override
    public void assignToNetworkInterface(@Nonnull String addressId, @Nonnull String nicId) throws InternalException, CloudException {
        throw new OperationNotSupportedException("Network interfaces are not currently supported");
    }

    @Override
    public @Nonnull String forward(@Nonnull String addressId, int publicPort, @Nonnull Protocol protocol, int privatePort, @Nonnull String onServerId) throws InternalException, CloudException {
        throw new OperationNotSupportedException("IP forwarding is not currently supported");
    }

    private transient volatile FloatingIPCapabilities capabilities;

    @Nonnull
    @Override
    public IPAddressCapabilities getCapabilities() throws CloudException, InternalException {
        if( capabilities == null ) {
            capabilities = new FloatingIPCapabilities(getProvider());
        }
        return capabilities;
    }

    @Override
    public @Nullable IpAddress getIpAddress(@Nonnull String addressId) throws InternalException, CloudException {
        APITrace.begin(getProvider(), "IpAddress.getIpAddress");
        try {
            NovaMethod method = new NovaMethod(getProvider());
            JSONObject ob = method.getServers(getEndpoint(), addressId, false);

            if( ob == null ) {
                return null;
            }
            try {
                if( ob.has("floating_ip") ) {
                    JSONObject json = ob.getJSONObject("floating_ip");
                    IpAddress addr = toIP(json);

                    if( addr != null ) {
                        return addr;
                    }
                }
            }
            catch( JSONException e ) {
                logger.error("getIpAddress(): Unable to identify expected values in JSON: " + e.getMessage());
                throw new CommunicationException("Missing JSON element for IP address", e);
            }
            return null;
        }
        finally {
            APITrace.end();
        }
    }

    private boolean verifySupport() throws InternalException, CloudException {
        APITrace.begin(getProvider(), "IpAddress.verifySupport");
        try {
            NovaMethod method = new NovaMethod(getProvider());

            try {
                method.getServers(getEndpoint(), null, false);
                return true;
            }
            catch( CloudException e ) {
                if( e.getHttpCode() == 404 ) {
                    return false;
                }
                throw e;
            }
        }
        finally {
            APITrace.end();
        }
    }

    @SuppressWarnings("SimplifiableIfStatement")
    @Override
    public boolean isSubscribed() throws CloudException, InternalException {
        APITrace.begin(getProvider(), "IpAddress.isSubscribed");
        try {
            if( getProvider().getMajorVersion() > 1 && getProvider().getComputeServices().getVirtualMachineSupport().isSubscribed() ) {
                return verifySupport();
            }
            if( getProvider().getMajorVersion() == 1 && getProvider().getMinorVersion() >= 1  &&  getProvider().getComputeServices().getVirtualMachineSupport().isSubscribed() ) {
                return verifySupport();
            }
            return false;
        }
        finally {
            APITrace.end();
        }
    }

    @Override
    public @Nonnull Iterable<IpAddress> listIpPool(@Nonnull IPVersion version, boolean unassignedOnly) throws InternalException, CloudException {
        APITrace.begin(getProvider(), "IpAddress.listIpPool");
        try {
            Future<Iterable<IpAddress>> ipPoolFuture = listIpPoolConcurrently(version, unassignedOnly);
            return ipPoolFuture.get();
        } catch (CloudException ce) {
            throw ce;
        } catch (Exception e) {
            throw new InternalException(e);
        }
        finally {
            APITrace.end();
        }

        /*try {
            if( !getVersions().contains(version) ) {
                return Collections.emptyList();
            }
            ProviderContext ctx = getProvider().getContext();

            if( ctx == null ) {
                logger.error("No context exists for this request");
                throw new InternalException("No context exists for this request");
            }
            NovaMethod method = new NovaMethod(getProvider());
            JSONObject ob = method.getServers(getEndpoint(), null, false);
            ArrayList<IpAddress> addresses = new ArrayList<IpAddress>();

            try {
                if( ob != null && ob.has("floating_ips") ) {
                    JSONArray list = ob.getJSONArray("floating_ips");

                    for( int i=0; i<list.length(); i++ ) {
                        JSONObject json = list.getJSONObject(i);

                        try {
                            IpAddress addr = toIP(ctx, json);

                            if( addr != null ) {
                                if( !unassignedOnly || addr.getServerId() == null ) {
                                    addresses.add(addr);
                                }
                            }
                        }
                        catch( JSONException e ) {
                            logger.error("Invalid JSON from cloud: " + e.getMessage());
                            throw new CloudException("Invalid JSON from cloud: " + e.getMessage());
                        }
                    }
                }
            }
            catch( JSONException e ) {
                logger.error("list(): Unable to identify expected values in JSON: " + e.getMessage());
                e.printStackTrace();
                throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for floating IP in " + ob.toString());
            }
            return addresses;
        }
        finally {
            APITrace.end();
        } */
    }

    @Nonnull
    @Override
    public Future<Iterable<IpAddress>> listIpPoolConcurrently(@Nonnull IPVersion ipVersion, boolean unassignedOnly) throws InternalException, CloudException {
        return threadPool.submit(
            new ListIpPoolCallable(
                ipVersion,
                unassignedOnly
            )
        );
    }

    public class ListIpPoolCallable implements Callable {
        IPVersion version;
        boolean unassignedOnly;

        public ListIpPoolCallable( IPVersion version, boolean unassignedOnly ) {
            this.version = version;
            this.unassignedOnly = unassignedOnly;
        }

        public Iterable<IpAddress> call() throws CloudException, InternalException {
            if( !getVersions().contains(version) ) {
                return Collections.emptyList();
            }
            NovaMethod method = new NovaMethod(getProvider());
            JSONObject ob = method.getServers(getEndpoint(), null, false);
            ArrayList<IpAddress> addresses = new ArrayList<IpAddress>();

            try {
                if( ob != null && ob.has("floating_ips") ) {
                    JSONArray list = ob.getJSONArray("floating_ips");

                    for( int i=0; i<list.length(); i++ ) {
                        JSONObject json = list.getJSONObject(i);

                        try {
                            IpAddress addr = toIP(json);

                            if( addr != null ) {
                                if( !unassignedOnly || addr.getServerId() == null ) {
                                    addresses.add(addr);
                                }
                            }
                        }
                        catch( JSONException e ) {
                            logger.error("Invalid JSON from cloud: " + e.getMessage());
                            throw new CommunicationException("Invalid JSON from cloud: " + e.getMessage(), e);
                        }
                    }
                }
            }
            catch( JSONException e ) {
                logger.error("list(): Unable to identify expected values in JSON: " + e.getMessage());
                throw new CommunicationException("Missing JSON element for floating IP in " + ob.toString(), e);
            }
            return addresses;
        }
    }

    @Override
    public @Nonnull Iterable<ResourceStatus> listIpPoolStatus(@Nonnull IPVersion version) throws InternalException, CloudException {
        APITrace.begin(getProvider(), "IpAddress.listIpPoolStatus");
        try {
            if( !getVersions().contains(version) ) {
                return Collections.emptyList();
            }
            NovaMethod method = new NovaMethod(getProvider());
            JSONObject ob = method.getServers(getEndpoint(), null, false);
            List<ResourceStatus> addresses = new ArrayList<ResourceStatus>();

            try {
                if( ob != null && ob.has("floating_ips") ) {
                    JSONArray list = ob.getJSONArray("floating_ips");

                    for( int i=0; i<list.length(); i++ ) {
                        JSONObject json = list.getJSONObject(i);

                        try {
                            ResourceStatus addr = toStatus(json);

                            if( addr != null ) {
                                addresses.add(addr);
                            }
                        }
                        catch( JSONException e ) {
                            throw new CommunicationException("Invalid JSON from cloud: " + e.getMessage(), e);
                        }
                    }
                }
            }
            catch( JSONException e ) {
                throw new CommunicationException("Missing JSON element for floating IP in " + ob.toString(), e);
            }
            return addresses;
        }
        finally {
            APITrace.end();
        }
    }

    @Override
    public @Nonnull Iterable<IpForwardingRule> listRules(@Nonnull String addressId) throws InternalException, CloudException {
        return Collections.emptyList();
    }

    static private volatile List<IPVersion> versions;

    private Collection<IPVersion> getVersions() {
        if( versions == null ) {
            ArrayList<IPVersion> tmp = new ArrayList<IPVersion>();

            tmp.add(IPVersion.IPV4);
            //tmp.add(IPVersion.IPV6);     TODO: when there's API support for IPv6
            versions = Collections.unmodifiableList(tmp);
        }
        return versions;
    }

    @Override
    public @Nonnull Iterable<IPVersion> listSupportedIPVersions() throws CloudException, InternalException {
        return getVersions();
    }

    @Override
    public @Nonnull String[] mapServiceAction(@Nonnull ServiceAction action) {
        return new String[0];
    }

    @Override
    public void releaseFromPool(@Nonnull String addressId) throws InternalException, CloudException {
        APITrace.begin(getProvider(), "IpAddress.releaseFromPool");
        try {
            NovaMethod method = new NovaMethod(getProvider());
            long timeout = System.currentTimeMillis() + CalendarWrapper.HOUR;

            do {
                try {
                    method.deleteServers(getEndpoint(), addressId);
                    return;
                }
                catch( NovaException e ) {
                    if( e.getHttpCode() != HttpStatus.SC_CONFLICT ) {
                        throw e;
                    }
                }
                try { Thread.sleep(CalendarWrapper.MINUTE); }
                catch( InterruptedException e ) { /* ignore */ }
            } while( System.currentTimeMillis() < timeout );
        }
        finally {
            APITrace.end();
        }
    }

    @Override
    public void releaseFromServer(@Nonnull String addressId) throws InternalException, CloudException {
        APITrace.begin(getProvider(), "IpAddress.releaseFromServer");
        try {
            Map<String,Object> json = new HashMap<String,Object>();
            Map<String,Object> action = new HashMap<String,Object>();
            IpAddress addr = getIpAddress(addressId);

            if( addr == null ) {
                throw new ResourceNotFoundException("IP", addressId);
            }
            String serverId = addr.getServerId();

            if( serverId == null ) {
                throw new InvalidStateException("IP address " + addressId + " is not attached to a server");
            }
            //action.put("server", serverId);
            action.put("address", addr.getRawAddress().getIpAddress());
            json.put("removeFloatingIp", action);

            NovaMethod method = new NovaMethod(getProvider());

            method.postServers("/servers", serverId, new JSONObject(json), true);
        }
        finally {
            APITrace.end();
        }
    }

    private Iterable<String> listPools() throws CloudException, InternalException {
        NovaMethod method = new NovaMethod(getProvider());
        JSONObject ob = method.getServers("/os-floating-ip-pools", null, false);
        List<String> pools = new ArrayList<String>();
        List<String> tmp = new ArrayList<String>();

        try {
            if( ob != null && ob.has("floating_ip_pools") ) {
                JSONArray list = ob.getJSONArray("floating_ip_pools");

                for( int i=0; i<list.length(); i++ ) {
                    JSONObject p = list.getJSONObject(i);

                    if( p.has("name") ) {
                        String n = p.getString("name");

                        if( n.equals("default") ) {
                            pools.add(n);
                        }
                        else {
                            tmp.add(n);
                        }
                    }
                }
                pools.addAll(tmp);
            }
        }
        catch( JSONException e ) {
            throw new CommunicationException("Missing JSON element for IP address", e);
        }
        return pools;
    }

    @Override
    public @Nonnull String request(@Nonnull IPVersion version) throws InternalException, CloudException {
        try {
            return request(version, null);
        }
        catch( NovaException e ) {
            if( e.getHttpCode() == 404 ) {
                for( String pool : listPools() ) {
                    try {
                        return request(version, pool);
                    }
                    catch( CloudException ignore ) {
                        // ignore
                    }
                }
            }
            throw e;
        }
    }

    private @Nonnull String request(@Nonnull IPVersion version, @Nullable String pool) throws InternalException, CloudException {
        APITrace.begin(getProvider(), "IpAddress.request");
        try {
            if( !getVersions().contains(version) ) {
                throw new OperationNotSupportedException("Cannot request an IPv6 IP address at this time");
            }

            Map<String,Object> wrapper = new HashMap<String,Object>();

            if( pool != null ) {
                wrapper.put("pool", pool);
            }

            NovaMethod method = new NovaMethod(getProvider());
            JSONObject result = method.postServers(getEndpoint(), null, new JSONObject(wrapper), false);

            if( result != null && result.has("floating_ip") ) {
                try {
                    JSONObject ob = result.getJSONObject("floating_ip");
                    IpAddress addr = toIP(ob);

                    if( addr != null ) {
                        return addr.getProviderIpAddressId();
                    }
                }
                catch( JSONException e ) {
                    logger.error("create(): Unable to understand create response: " + e.getMessage());
                    throw new CommunicationException("Invalid response", e);
                }
            }
            logger.error("create(): No IP address was created by the create attempt, and no error was returned");
            throw new GeneralCloudException("No IP address was created", CloudErrorType.GENERAL);

        }
        finally {
            APITrace.end();
        }
    }

    @Override
    public @Nonnull String requestForVLAN(@Nonnull IPVersion version) throws InternalException, CloudException {
        throw new OperationNotSupportedException(getProvider().getCloudName() + " does not support static IP addresses for VLANs");
    }

    @Override
    public @Nonnull String requestForVLAN(@Nonnull IPVersion version, @Nonnull String vlanId) throws InternalException, CloudException {
        throw new OperationNotSupportedException(getProvider().getCloudName() + " does not support static IP addresses for VLANs");
    }

    @Override
    public void stopForward(@Nonnull String ruleId) throws InternalException, CloudException {
        throw new OperationNotSupportedException("Forwarding not supported");
    }

    private IpAddress toIP(JSONObject json) throws JSONException, InternalException {
        if(json == null ) {
            return null;
        }
        String regionId = getContext().getRegionId();

        IpAddress address = new IpAddress();

        if( regionId != null ) {
            address.setRegionId(regionId);
        }
        address.setServerId(null);
        address.setProviderLoadBalancerId(null);
        address.setAddressType(AddressType.PUBLIC);

        String id = ((json.has("id") && !json.isNull("id")) ? json.getString("id") : null);
        String ip = ((json.has("ip") && !json.isNull("ip")) ? json.getString("ip") : null);
        String server = ((json.has("instance_id") && !json.isNull("instance_id")) ? json.getString("instance_id") : null);
        if( id != null ) {
            address.setIpAddressId(id);
        }
        if( server != null ) {
            address.setServerId(server);
        }
        if( ip != null ) {
            address.setAddress(ip);
        }
        if( id == null || ip == null ) {
            return null;
        }
        address.setVersion(IPVersion.IPV4);
        return address;
    }

    private ResourceStatus toStatus(JSONObject json) throws JSONException {
        if( json == null ) {
            return null;
        }
        Boolean available = null;
        String id;

        id = (json.has("id") ? json.getString("id") : null);
        if( json.has("instance_id") ) {
            String instance = json.getString("instance_id");

            available = !(instance != null && instance.length() > 0);
        }
        if( id == null ) {
            return null;
        }
        return new ResourceStatus(id, available == null ? true : available);
    }
}


text:
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.ExceptionServices;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.ObjectPool;
using Microsoft.Extensions.PlatformAbstractions;
using Margeta.Extensions.Cli.Builder;
using Margeta.Extensions.Cli.Builder.Internal;
using Margeta.Extensions.Cli.Builder.Middleware;
using Margeta.Extensions.Cli.Hosting.Internal;
using Margeta.Extensions.Cli.Hosting.Startup;
using Margeta.Extensions.Cli.Utilities;

namespace Margeta.Extensions.Cli.Hosting
{
    /// <summary>
    /// Represents a console host builder.
    /// </summary>
    public class ConsoleHostBuilder : IConsoleHostBuilder
    {
        private readonly IHostingEnvironment _hostingEnvironment;
        private readonly List<Action<IServiceCollection>> _configureServicesDelegates;
        private readonly List<Action<ILoggerFactory>> _configureLoggerFactoryDelegates;

        private readonly IConfiguration _configuration;
        private ILoggerFactory _loggerFactory;

        private ConsoleHostOptions _options;
        private bool _isConsoleHostBuilt;

        /// <summary>
        /// Initializes a new instance of the ConsoleHostBuilder class.
        /// </summary>
        public ConsoleHostBuilder()
        {
            _hostingEnvironment = new HostingEnvironment();
            _configureServicesDelegates = new List<Action<IServiceCollection>>();
            _configureLoggerFactoryDelegates = new List<Action<ILoggerFactory>>();

            _configuration = new ConfigurationBuilder()
                .AddEnvironmentVariables(prefix: "CLINETCORE_")
                .Build();
        }

        /// <summary>
        /// Builds an IConsoleHost which hosts the console application.
        /// </summary>
        /// <returns></returns>
        public IConsoleHost Build()
        {
            if (_isConsoleHostBuilt)
            {
                throw new InvalidOperationException(Resources.ConsoleHostBuilder_SingleInstance);
            }

            _isConsoleHostBuilt = true;

            var hostServices = BuildCommonServices();
            var applicationServices = hostServices.Clone();
            var hostServicesProvider = hostServices.BuildServiceProvider();

            ForwardApplicationServices(applicationServices, hostServicesProvider);

            return new ConsoleHost(applicationServices, hostServicesProvider);
        }

        /// <summary>
        /// Adds a delegate for configuring the provided ILoggerFactory.
        /// </summary>
        /// <param name="configureLogging">The delegate that configures the ILoggerFactory.</param>
        /// <returns>The IConsoleHostBuilder.</returns>
        /// <remarks>This method may be called multiple times.</remarks>
        public IConsoleHostBuilder ConfigureLogging(Action<ILoggerFactory> configureLogging)
        {
            if (configureLogging == null)
            {
                throw new ArgumentNullException(nameof(configureLogging));
            }

            _configureLoggerFactoryDelegates.Add(configureLogging);

            return this;
        }

        /// <summary>
        /// Specify the delegate that is used to configure the services of the console application.
        /// </summary>
        /// <param name="configureServices">The delegate that configures the IServiceCollection.</param>
        /// <returns>The IConsoleHostBuilder.</returns>
        public IConsoleHostBuilder ConfigureServices(Action<IServiceCollection> configureServices)
        {
            if (configureServices == null)
            {
                throw new ArgumentNullException(nameof(configureServices));
            }

            _configureServicesDelegates.Add(configureServices);

            return this;
        }

        /// <summary>
        /// Gets the setting value from the configuration.
        /// </summary>
        /// <param name="key">The key of the setting to look up.</param>
        /// <returns>The value the setting currently contains.</returns>
        public string GetSetting(string key) => _configuration[key];

        /// <summary>
        /// Specofy the ILoggerFactory to be used by the web host.
        /// </summary>
        /// <param name="loggerFactory">The ILoggerFactory to be used by the console host.</param>
        /// <returns>The IConsoleHostBuilder.</returns>
        public IConsoleHostBuilder UseLoggerFactory(ILoggerFactory loggerFactory)
        {
            _loggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory));
            return this;
        }

        /// <summary>
        /// Add or replace setting in the configuration.
        /// </summary>
        /// <param name="key">The key of te setting to add or replace.</param>
        /// <param name="value">The value of the setting to add or replace.</param>
        /// <returns>The IconsoleHostBuilder.</returns>
        public IConsoleHostBuilder UseSetting(string key, string value)
        {
            _configuration[key] = value;
            return this;
        }

        /// <summary>
        /// Builds the common services collection.
        /// </summary>
        /// <returns>The common services collection.</returns>
        private IServiceCollection BuildCommonServices()
        {
            _options = new ConsoleHostOptions(_configuration);

            var applicationEnvironment = PlatformServices.Default.Application;
            var applicationName = _options.ApplicationName ?? applicationEnvironment.ApplicationName;

            _hostingEnvironment.Initialize(applicationName, _options);

            var services = new ServiceCollection();

            services.AddSingleton(_hostingEnvironment);

            // The configured ILoggerFactory is added as a singleton here. AddLogging below will not add an additional one
            if (_loggerFactory == null)
            {
                _loggerFactory = new LoggerFactory();
                services.AddSingleton(serviceProvider => _loggerFactory);
            }
            else
            {
                services.AddSingleton(_loggerFactory);
            }

            foreach (var configureLogging in _configureLoggerFactoryDelegates)
            {
                configureLogging(_loggerFactory);
            }

            //This is required to add ILogger of T
            services.AddLogging();

            services.AddSingleton<ICommandLineParser, CommandLineParser>();
            services.AddSingleton<IApplicationBuilderFactory, ApplicationBuilderFactory>();
            services.AddSingleton<ICliContextFactory, CliContextFactory>();
            services.AddSingleton<IMiddlewareFactory, MiddlewareFactory>();
            services.AddOptions();

            services.AddSingleton<IServiceProviderFactory<IServiceCollection>, DefaultServiceProviderFactory>();
            services.AddSingleton<ObjectPoolProvider, DefaultObjectPoolProvider>();

            if (!string.IsNullOrEmpty(_options.StartupAssembly))
            {
                try
                {
                    var consoleStartupType = ConsoleStartupLoader.FindConsoleStartupType(_options.StartupAssembly, _hostingEnvironment.EnvironmentName);

                    if (typeof(IConsoleStartup).GetTypeInfo().IsAssignableFrom(consoleStartupType.GetTypeInfo()))
                    {
                        services.AddSingleton(typeof(IConsoleStartup), consoleStartupType);
                    }
                    else
                    {
                        services.AddSingleton(
                            typeof(IConsoleStartup),
                            serviceProvider =>
                            {
                                var hostingEnvironment = serviceProvider.GetRequiredService<IHostingEnvironment>();
                                var methods = ConsoleStartupLoader.LoadMethods(serviceProvider, consoleStartupType, hostingEnvironment.EnvironmentName);

                                return new ConventionBasedConsoleStartup(methods);
                            }
                        );
                    }
                }
                catch (Exception e)
                {
                    var capture = ExceptionDispatchInfo.Capture(e);
                    services.AddSingleton<IConsoleStartup>(
                        _ =>
                        {
                            capture.Throw();
                            return null;
                        }
                    );
                }
            }

            foreach (var configureServices in _configureServicesDelegates)
            {
                configureServices(services);
            }

            return services;
        }

        /// <summary>
        /// Forwards common services from the host service provider to the application services collection.
        /// </summary>
        /// <param name="services">Application services.</param>
        /// <param name="hostServiceProvider">Host service provider.</param>
        private void ForwardApplicationServices(IServiceCollection services, IServiceProvider hostServiceProvider)
        {
            // We are forwarding services from hosting contrainer so hosting container
            // can still manage their lifetime (disposal) shared instances with application services.
            // NOTE: This code overrides original services lifetime. Instances would always be singleton in
            // application container.
            var loggerFactory = hostServiceProvider.GetService<ILoggerFactory>();
            services.Replace(ServiceDescriptor.Singleton(typeof(ILoggerFactory), loggerFactory));
        }
    }
}


text:
@interface XWTerminalLogger () <XWSocketClientDelegate>

{
    dispatch_semaphore_t _semaphore;
}

@property (nonatomic, strong) XWSocketClient *socketClient;
@property (nonatomic, strong) NSMutableArray *sendArr;
@property (nonatomic, copy) NSString *host;
@property (nonatomic, assign) uint16_t port;

@end

@implementation XWTerminalLogger

- (instancetype)init {
    self = [super init];
    if (self) {
        _sendArr = [[NSMutableArray alloc] init];
        _semaphore = dispatch_semaphore_create(1);
        _socketClient = [[XWSocketClient alloc] init];
        _socketClient.delegate = self;
    }
    return self;
}

- (void)configWithHost:(NSString *)host port:(uint16_t)port {
    _host = [host copy];
    _port = port;
}

- (void)log:(XWLogInfo *)info {
    //timestamp appName[proccessID:threadID] content
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS"];
    NSString *timestamp = [df stringFromDate:[NSDate date]];
    uint64_t tid;
    pthread_threadid_np(NULL, &tid);
    NSString *showStr = [NSString stringWithFormat:@"%@ %@[%@:%llu] %@", timestamp, info.appName, info.proccessID, tid, info.content];
    NSDictionary *dict = @{@"level":@(info.level),@"content":showStr, @"type":@"log"};
    NSError *err;
    NSMutableData *data = [[NSMutableData alloc] init];
    NSData *bodyData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&err];
    NSData *lenData = [XWBasicDataUtility encodeInt:(unsigned int)bodyData.length];
    [data appendData:lenData];
    [data appendData:bodyData];
    if (!err) {
        dispatch_semaphore_wait(_semaphore, DISPATCH_TIME_FOREVER);
        [_sendArr addObject:data];
        dispatch_semaphore_signal(_semaphore);
        if ([_socketClient isConnect]) {
            [self _dequeueSendArr];
        } else {
            NSInteger cnt;
            dispatch_semaphore_wait(_semaphore, DISPATCH_TIME_FOREVER);
            cnt = _sendArr.count;
            dispatch_semaphore_signal(_semaphore);
            if (cnt == 1) {
                [_socketClient connectToHost:_host port:_port];
            }
        }
    }
}

- (void)_dequeueSendArr {
    dispatch_semaphore_wait(_semaphore, DISPATCH_TIME_FOREVER);
    NSData *data = [_sendArr firstObject];
    if (data) {
        [_sendArr removeObjectAtIndex:0];
        [_socketClient writeData:data];
    }
    dispatch_semaphore_signal(_semaphore);
}

- (void)_clearSendArr {
    dispatch_semaphore_wait(_semaphore, DISPATCH_TIME_FOREVER);
    [_sendArr removeAllObjects];
    dispatch_semaphore_signal(_semaphore);
}

- (void)socketClient:(XWSocketClient *)client didConnectToHost:(NSString *)host port:(uint16_t)port {
    [self _dequeueSendArr];
}

- (void)socketClientDidDisconnect:(XWSocketClient *)client withError:(NSError *)error {
    [self _clearSendArr];
}

- (void)socketClient:(XWSocketClient *)client didReadData:(NSData *)data {
    //    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
    //    NSLog(@"%@", dict);
    [self _dequeueSendArr];
}

- (void)socketClient:(XWSocketClient *)client didWriteData:(NSData *)data {

}

@end


text:
package org.terracotta.dynamic_config.api.model;

import java.util.Properties;
import java.util.stream.Stream;

import static org.terracotta.dynamic_config.api.model.Version.CURRENT;

/**
 * @author Mathieu Carbou
 */
public interface PropertyHolder {

  UID getUID();

  String getName();

  Scope getScope();

  default Properties toProperties(boolean expanded, boolean includeDefaultValues, boolean includeHiddenSettings) {
    return toProperties(expanded, includeDefaultValues, includeHiddenSettings, CURRENT);
  }

  Properties toProperties(boolean expanded, boolean includeDefaultValues, boolean includeHiddenSettings, Version version);

  default Stream<? extends PropertyHolder> descendants() {
    return Stream.empty();
  }
}