text:
<?xml version="1.0" encoding="UTF-8"?>
<LearningStandards>
  <LearningStandardItem xml:lang="en" RefID="C42DDA736D104884B66DADF1B20D6336">
    <RefURI>http://corestandards.org/ELA-Literacy/L/8/2/c/</RefURI>
    <StandardHierarchyLevel>
      <number>6</number>
      <description>Component</description>
    </StandardHierarchyLevel>
    <StatementCodes>
      <StatementCode>CCSS.ELA-Literacy.L.8.2c</StatementCode>
    </StatementCodes>
    <Statements>
      <Statement>Spell correctly.</Statement>
    </Statements>
    <GradeLevels>
      <GradeLevel>08</GradeLevel>
    </GradeLevels>
    <LearningStandardDocumentRefId>0FAC40650F514a459951A657F942B845</LearningStandardDocumentRefId>
    <RelatedLearningStandardItems>
      <LearningStandardItemRefId RelationshipType="childOf">B863A110909C4b0790CC69BDE4297AF6</LearningStandardItemRefId>
    </RelatedLearningStandardItems>
  </LearningStandardItem>
</LearningStandards>


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <TITLE>Generic Image Library: variant.hpp File Reference</TITLE>
    <META HTTP-EQUIV="content-type" CONTENT="text/html;charset=ISO-8859-1"/>
    <LINK TYPE="text/css" REL="stylesheet" HREF="adobe_source.css"/>

Modules
                  | Alphabetical List
                  | Class List
                  | Directories
                  | File List
                  | GIL Home Page

boost &raquo gil &raquo extension &raquo dynamic_image

variant.hpp File Reference

Detailed Description

Support for run-time instantiated types.

Author:

Lubomir Bourdev and Hailin Jin

 Adobe Systems Incorporated

Date:

2005-2007

 Last updated on September 18, 2007

#include "../../gil_config.hpp"

#include "../../utilities.hpp"

#include <cstddef>

#include <cassert>

#include <algorithm>

#include <typeinfo>

#include <boost/bind.hpp>

#include <boost/mpl/transform.hpp>

#include <boost/mpl/size.hpp>

#include <boost/mpl/sizeof.hpp>

#include <boost/mpl/max.hpp>

#include <boost/mpl/at.hpp>

#include <boost/mpl/fold.hpp>

Go to the source code of this file.

Namespaces

namespace  	boost

namespace  	boost::gil

namespace  	boost::gil::detail

Classes

class  	variant

 	Represents a concrete instance of a run-time specified type from a set of types

A concept is typically modeled by a collection of different types. They may be instantiations of a templated type with different template parameters or even completely unrelated types.  More...

Functions

template<typename T, typename Bits>

void 	copy_construct_in_place (const T &t, Bits &bits)

template<typename Types>

void 	swap (variant< Types > &x, variant< Types > &y)

template<typename Types>

bool 	operator== (const variant< Types > &x, const variant< Types > &y)

template<typename C>

bool 	operator!= (const variant< C > &x, const variant< C > &y)

<address style="text-align: right;">Generated on Sat May 2 13:50:16 2009 for Generic Image Library by

 1.5.6 </address>

redpajama_set_name: RedPajamaGithub


text:
<?php
namespace SlimBootstrap\Endpoint;

use \SlimBootstrap;

/**
 * Class Info
 *
 * @package SlimBootstrap\Endpoint
 */
class Info
{
    public function get()
    {
        $gitVersion   = $this->_getGitVersion();
        $composerData = $this->_readComposerPackageVersions(
            __DIR__ . '/../../../../../../composer.lock'
        );

        $repoUrl = $this->_getRepoUrl($gitVersion);

        return new SlimBootstrap\DataObject(
            array(),
            array(
                'repoUrl'  => $repoUrl,
                'version'  => $gitVersion,
                'packages' => $composerData,
            )
        );
    }

    /**
     * Reads composer.lock and returns an array with used packages and its version.
     * When a git packages version contains dev, first characters of
     * reference will be added to version.
     *
     * @param string $composerLockPath
     *
     * @return array
     */
    private function _readComposerPackageVersions($composerLockPath)
    {
        $result = array();
        $data   = $this->_loadComposerFile($composerLockPath);

        if (false === is_array($data)
            || false === array_key_exists('packages', $data)
        ) {
            return array();
        }

        foreach ($data['packages'] as $package) {
            $versionString = $package['version'];

            if (true === array_key_exists('source', $package)
                && $package['source']['type'] === 'git'
                && false !== strpos($package['version'], 'dev')
            ) {
                $versionString .= ' (' . substr($package['source']['reference'], 0, 6) .'...)';
            }

            $packageUrl = 'https://packagist.org/';

            if (false !== strpos($package['notification-url'], 'packagist.bigpoint.net')) {
                $packageUrl = 'https://packagist.bigpoint.net/';
            }

            $packageUrl .= 'packages/' . $package['name'] . '#' . $package['version'];

            $result[$package['name']] = array(
                'version'       => $package['version'],
                'versionString' => $versionString,
                'packageUrl'    => $packageUrl,
            );
        }

        return $result;
    }

    /**
     * @param string $composerLockPath
     *
     * @return array
     *
     * @codeCoverageIgnore
     */
    protected function _loadComposerFile($composerLockPath)
    {
        return json_decode(file_get_contents($composerLockPath), true);
    }

    /**
     * @return string
     *
     * @codeCoverageIgnore
     */
    protected function _getGitVersion()
    {
        return trim(
            shell_exec(
                'git describe --tags --exact-match || git symbolic-ref -q --short HEAD'
            )
        );
    }

    /**
     * @param string $gitVersion
     *
     * @return string
     *
     * @codeCoverageIgnore
     */
    protected function _getRepoUrl($gitVersion)
    {
        $gitUrl = trim(shell_exec('git config --get remote.origin.url'));

        if ('' !== $gitUrl) {
            $repoUrl = explode('@', $gitUrl);
            return 'https://' . str_replace(
                array(
                    ':',
                    '.git',
                ),
                array(
                    '/',
                    '/tree/' . $gitVersion,
                ),
                $repoUrl[1]
            );
        }

        return '';
    }
}


text:
package hudson.plugins.cobertura;

import hudson.model.Run;

public class BuildUtils {
	public static Run<?, ?> getPreviousNotFailedCompletedBuild(Run<?, ?> b) {
		while (true) {
			b = b.getPreviousNotFailedBuild();
			if (b == null) {
				return null;
			}
			if (!b.isBuilding()) {
				return b;
			}
		}
	}
}


text: Things made just for fun


text:
from software.providers import github

from software.app import app, db

from software.test.utils import setup_postgres_for_unittests, teardown_postgres_for_unittests
from software.test.utils import http
from software.test.utils import open_file_from_data_dir

import unittest
from nose.tools import assert_equals
from nose.tools import assert_not_equals
from nose.tools import assert_true
from nose.tools import assert_items_equal

import json

handle = open_file_from_data_dir("github_users_jasonpriem.json")
github_user_json = json.loads(handle.read())

class TestGithub(unittest.TestCase):

    def setUp(self):
        self.db = setup_postgres_for_unittests(db, app)

    def tearDown(self):
        teardown_postgres_for_unittests(self.db)

    @http
    def test_get_user_live_from_github(self):
        github_user_dict = github.get_repo_names("jasonpriem")
        repo_names = [u'5uni-Twitter-study', u'altmetrics-crawler', u'altmetrics-tools-iConference-poster', u'angular-seo-heroku', u'annotateit', u'annotator', u'bibserver', u'BlackBoard_awesome_patch', u'bootstrap', u'daphne-masters-paper', u'FeedVis', u'HumanNameParser.php', u'ICanHaz.js', u'negotiate', u'php-backtype', u'plain-jane', u'plos_altmetrics_study', u'rerankit', u'rImpactStory', u'schol-search-study', u'sils-annotate', u'zotero-report-cleaner']
        assert_equals(github_user_dict, repo_names)

    def test_got_username(self):
        assert_equals(github_user_json, "hi")


text:
package com.hazelcast.jet.examples.files;

import com.hazelcast.internal.nio.IOUtil;
import com.hazelcast.jet.Jet;
import com.hazelcast.jet.JetInstance;
import com.hazelcast.jet.aggregate.AggregateOperations;
import com.hazelcast.jet.pipeline.Pipeline;
import com.hazelcast.jet.pipeline.Sinks;
import com.hazelcast.jet.pipeline.Sources;
import com.hazelcast.jet.pipeline.WindowDefinition;

import java.io.BufferedWriter;
import java.io.Serializable;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
import java.util.Random;
import java.util.concurrent.locks.LockSupport;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;

/**
 * Analyzes access log files from a HTTP server. Demonstrates the usage of
 * {@link Sources#fileWatcher(String)} (String, Charset, String)} to read
 * files line by line in streaming fashion - by running indefinitely and
 * watching for changes as they appear.
 *

 * It uses sliding window aggregation to output frequency of visits to each
 * page continuously.
 *

 * This analyzer could be run on a Jet cluster deployed on the same
 * machines as those forming the web server cluster. This way each instance
 * will process local files locally and subsequently merge the results
 * globally.
 *

 * This sample does not work well on Windows. On Windows, even though new
 * lines are flushed, WatchService is not notified of changes, until the
 * file is closed.
 */
public class AccessLogStreamAnalyzer {

    private static Pipeline buildPipeline(Path tempDir) {
        Pipeline p = Pipeline.create();
        p.readFrom(Sources.fileWatcher(tempDir.toString()))
         .withoutTimestamps()
         .map(LogLine::parse)
         .filter(line -> line.getResponseCode() >= 200 && line.getResponseCode() < 400)
         .addTimestamps(LogLine::getTimestamp, 1000)
         .window(WindowDefinition.sliding(10_000, 1_000))
         .groupingKey(LogLine::getEndpoint)
         .aggregate(AggregateOperations.counting())
         .writeTo(Sinks.logger());
        return p;
    }

    public static void main(String[] args) throws Exception {
        Path tempDir = Files.createTempDirectory(AccessLogStreamAnalyzer.class.getSimpleName());
        Pipeline p = buildPipeline(tempDir);

        JetInstance instance = Jet.bootstrappedInstance();
        try {
            instance.newJob(p);
            // job is running in its own threads. Let's generate some random traffic in this thread.
            startGenerator(tempDir);
            // wait for all writes to be picked up
            LockSupport.parkNanos(SECONDS.toNanos(1));
        } finally {
            Jet.shutdownAll();
            IOUtil.delete(tempDir.toFile());
        }
    }

    private static void startGenerator(Path tempDir) throws Exception {
        Random random = new Random();
        try (BufferedWriter w = Files.newBufferedWriter(tempDir.resolve("access_log"), StandardOpenOption.CREATE)) {
            for (int i = 0; i < 60_000; i++) {
                int articleNum = Math.min(10, Math.max(0, (int) (random.nextGaussian() * 2 + 5)));
                w.append("129.21.37.3 - - [")
                 .append(LogLine.DATE_TIME_FORMATTER.format(ZonedDateTime.now()))
                 .append("] \"GET /article")
                 .append(String.valueOf(articleNum))
                 .append(" HTTP/1.0\" 200 12345");

                w.newLine();
                w.flush();
                LockSupport.parkNanos(MILLISECONDS.toNanos(1));
            }
        }
    }

    /**
     * Immutable data transfer object mapping the log line.
     */
    private static class LogLine implements Serializable {

        public static final DateTimeFormatter DATE_TIME_FORMATTER =
                DateTimeFormatter.ofPattern("dd/MMM/yyyy:HH:mm:ss Z", Locale.US);

        // Example Apache log line:
        //   127.0.0.1 - - [21/Jul/2014:9:55:27 -0800] "GET /home.html HTTP/1.1" 200 2048
        private static final String LOG_ENTRY_PATTERN =
                // 1:IP  2:client 3:user 4:date time                   5:method 6:req 7:proto   8:respcode 9:size
                "^(\\S+) (\\S+) (\\S+) \\[([\\w:/]+\\s[+\\-]\\d{4})] \"(\\S+) (\\S+) (\\S+)\" (\\d{3}) (\\d+)";
        private static final Pattern PATTERN = Pattern.compile(LOG_ENTRY_PATTERN);

        private final String ipAddress;
        private final String clientIdentd;
        private final String userID;
        private final long timestamp;
        private final String method;
        private final String endpoint;
        private final String protocol;
        private final int responseCode;
        private final long contentSize;

        LogLine(String ipAddress, String clientIdentd, String userID, long timestamp, String method, String endpoint,
                String protocol, int responseCode, long contentSize) {
            this.ipAddress = ipAddress;
            this.clientIdentd = clientIdentd;
            this.userID = userID;
            this.timestamp = timestamp;
            this.method = method;
            this.endpoint = endpoint;
            this.protocol = protocol;
            this.responseCode = responseCode;
            this.contentSize = contentSize;
        }

        public static LogLine parse(String line) {
            Matcher m = PATTERN.matcher(line);
            if (!m.find()) {
                throw new IllegalArgumentException("Cannot parse log line: " + line);
            }
            long time = ZonedDateTime.parse(m.group(4), DATE_TIME_FORMATTER).toInstant().toEpochMilli();
            return new LogLine(m.group(1), m.group(2), m.group(3), time, m.group(5), m.group(6), m.group(7),
                    Integer.parseInt(m.group(8)), Long.parseLong(m.group(9)));
        }

        public String getIpAddress() {
            return ipAddress;
        }

        public String getClientIdentd() {
            return clientIdentd;
        }

        public String getUserID() {
            return userID;
        }

        public long getTimestamp() {
            return timestamp;
        }

        public String getMethod() {
            return method;
        }

        public String getEndpoint() {
            return endpoint;
        }

        public String getProtocol() {
            return protocol;
        }

        public int getResponseCode() {
            return responseCode;
        }

        public long getContentSize() {
            return contentSize;
        }
    }
}


text:
import os

import pytest

from landlab.core.messages import (
    assert_or_print,
    error_message,
    format_message,
    split_paragraphs,
    warning_message,
)

LOREM_IPSUM = os.linesep.join(
    [
        "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
        "",
        "Pharetra pharetra massa massa ultricies mi quis hendrerit.",
        "",
        "Dictumst vestibulum rhoncus est pellentesque. Sed viverra tellus in hac habitasse platea dictumst vestibulum rhoncus.",
    ]
)

def test_split_paragraphs_cr():
    """Test splitting paragraphs with carriage returns."""
    text = """
Pharetra pharetra massa massa ultricies mi quis hendrerit.\r\rDictumst vestibulum rhoncus est pellentesque.
    """
    assert split_paragraphs(text, linesep="\r") == [
        "Pharetra pharetra massa massa ultricies mi quis hendrerit.",
        "Dictumst vestibulum rhoncus est pellentesque.",
    ]

def test_split_paragraphs_lf():
    """Test splitting paragraphs with line feeds."""
    text = """
Pharetra pharetra massa massa ultricies mi quis hendrerit.\n\nDictumst vestibulum rhoncus est pellentesque.
    """
    assert split_paragraphs(text, linesep="\n") == [
        "Pharetra pharetra massa massa ultricies mi quis hendrerit.",
        "Dictumst vestibulum rhoncus est pellentesque.",
    ]

def test_split_paragraphs_crlf():
    """Test splitting paragraphs with carriage returns and line feeds."""
    text = """
Pharetra pharetra massa massa ultricies mi quis hendrerit.\r\n\r\nDictumst vestibulum rhoncus est pellentesque.
    """
    assert split_paragraphs(text, linesep="\r\n") == [
        "Pharetra pharetra massa massa ultricies mi quis hendrerit.",
        "Dictumst vestibulum rhoncus est pellentesque.",
    ]

def test_empty_message():
    """Test formatting an empty string."""
    assert format_message("") == ""

def test_one_line():
    """Test a single line message."""
    assert format_message("lorem ipsum") == "lorem ipsum"

def test_leading_whitespace():
    """Test a single line message."""
    assert format_message("   lorem ipsum") == "lorem ipsum"

def test_one_long_line():
    """Test a line that needs to be wrapped."""
    msg = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."

    assert format_message(msg) == os.linesep.join(
        [
            "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do",
            "eiusmod tempor incididunt ut labore et dolore magna aliqua.",
        ]
    )

def test_multiline():
    msg = """lorem
ipsum
    """
    assert format_message(msg) == "lorem ipsum"

def test_multiple_paragraphs():
    assert format_message(LOREM_IPSUM) == os.linesep.join(
        [
            "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do",
            "eiusmod tempor incididunt ut labore et dolore magna aliqua.",
            "",
            "Pharetra pharetra massa massa ultricies mi quis hendrerit.",
            "",
            "Dictumst vestibulum rhoncus est pellentesque. Sed viverra tellus in",
            "hac habitasse platea dictumst vestibulum rhoncus.",
        ]
    )

def test_warning_message():
    msg = "Pharetra pharetra massa massa ultricies mi quis hendrerit."

    assert warning_message(msg) == os.linesep.join(
        [
            "WARNING",
            "=======",
            "",
            "Pharetra pharetra massa massa ultricies mi quis hendrerit.",
        ]
    )

def test_error_message():
    msg = "Pharetra pharetra massa massa ultricies mi quis hendrerit."

    assert error_message(msg) == os.linesep.join(
        [
            "ERROR",
            "=====",
            "",
            "Pharetra pharetra massa massa ultricies mi quis hendrerit.",
        ]
    )

def test_warning_message_is_none():
    assert warning_message() == os.linesep.join(["WARNING", "======="])

def test_error_message_is_none():
    assert error_message() == os.linesep.join(["ERROR", "====="])

def test_assert_or_pass():
    assert_or_print(True, onerror="pass")
    assert_or_print(False, onerror="pass")

def test_assert_or_warn():
    assert_or_print(True, onerror="warn")
    assert_or_print(False, onerror="warn")

def test_assert_or_raise():
    assert_or_print(True, onerror="raise")
    with pytest.raises(AssertionError):
        assert_or_print(False, onerror="raise")


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.sergiostorino.model.service.sync;

import br.com.sergiostorino.model.domain.SendSMS;
import java.io.Serializable;

/**
 *
 * @author Junior
 * @param <T>
 */
public class BridgeSendSIMSMS<T extends SendSMS> implements Bridge<T>, Serializable {

    private Boolean disponivel = false;
    private T obj;

    public BridgeSendSIMSMS() {
    }

    public BridgeSendSIMSMS(T obj) {
        this.obj = obj;
    }

    @Override
    public synchronized void set(T obj) throws InterruptedException {
        while (disponivel) {

            System.err.println("Esperando set ponte BridgeSendSIMSMS ");
            wait();
        }
        this.obj = obj;
        this.disponivel = true;
        notifyAll();

    }

    @Override
    public synchronized T get() throws InterruptedException {
        while (!disponivel) {
            System.err.println("Esperando get ponte BridgeSendSIMSMS ");
            wait();
        }
        disponivel = false;
        notifyAll();
        return obj;
    }

}


text:
/* ----------------------------------------------------------------------
   OINK - scripting wrapper on MapReduce-MPI library
   http://www.sandia.gov/~sjplimp/mapreduce.html, Sandia National Laboratories
   Steve Plimpton, sjplimp@sandia.gov

   See the README file in the top-level MR-MPI directory.
------------------------------------------------------------------------- */

#ifdef COMMAND_CLASS

CommandStyle(wordfreq,WordFreq)

#else

#ifndef OINK_WORD_FREQ_H
#define OINK_WORD_FREQ_H

#include "command.h"
#include "keyvalue.h"
using MAPREDUCE_NS::KeyValue;

namespace OINK_NS {

class WordFreq : public Command {
 public:
  WordFreq(class OINK *);
  void run();
  void params(int, char **);

 private:
  int ntop;

  static void output(uint64_t, char *, int, char *, int, KeyValue *, void *);
};

}

#endif
#endif


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

#include <memory>
#include <vector>

#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/run_loop.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/scoped_feature_list.h"
#include "base/threading/thread_restrictions.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/extensions/api/webstore_private/webstore_private_api.h"
#include "chrome/browser/extensions/extension_function_test_utils.h"
#include "chrome/browser/extensions/extension_install_prompt.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/mixin_based_extension_apitest.h"
#include "chrome/browser/extensions/webstore_installer.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/common/buildflags.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/extensions/extension_test_util.h"
#include "components/safe_browsing/core/common/safe_browsing_prefs.h"
#include "content/public/browser/gpu_data_manager.h"
#include "content/public/browser/notification_observer.h"
#include "content/public/browser/notification_registrar.h"
#include "content/public/test/browser_test.h"
#include "extensions/browser/allowlist_state.h"
#include "extensions/browser/api/management/management_api.h"
#include "extensions/browser/extension_dialog_auto_confirm.h"
#include "extensions/browser/extension_system.h"
#include "extensions/browser/install/extension_install_ui.h"
#include "extensions/common/extension_features.h"
#include "gpu/config/gpu_feature_type.h"
#include "net/dns/mock_host_resolver.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "ui/gl/gl_switches.h"

#if BUILDFLAG(ENABLE_SUPERVISED_USERS)

#if !BUILDFLAG(IS_CHROMEOS_LACROS)
// TODO(https://crbug.com/1218633): Fix the mixin and enable extensions tests on
// LaCrOS.
#include "base/test/metrics/histogram_tester.h"
#include "base/test/metrics/user_action_tester.h"
#include "chrome/browser/ash/login/test/logged_in_user_mixin.h"
#include "chrome/browser/supervised_user/supervised_user_constants.h"
#include "chrome/browser/supervised_user/supervised_user_service.h"
#include "chrome/browser/supervised_user/supervised_user_service_factory.h"
#include "chrome/browser/supervised_user/supervised_user_test_util.h"  // nogncheck
#include "chrome/browser/ui/supervised_user/parent_permission_dialog.h"
#include "chrome/browser/ui/views/supervised_user/parent_permission_dialog_view.h"
#include "components/account_id/account_id.h"
#include "components/signin/public/identity_manager/identity_test_environment.h"
#include "extensions/common/extension_builder.h"
#endif  // !BUILDFLAG(IS_CHROMEOS_LACROS)

#if BUILDFLAG(IS_CHROMEOS_ASH)
#include "ash/constants/ash_switches.h"
#endif

#endif  // BUILDFLAG(ENABLE_SUPERVISED_USERS)

namespace utils = extension_function_test_utils;

namespace extensions {

namespace {

constexpr char kExtensionId[] = "enfkhcelefdadlmkffamgdlgplcionje";

class WebstoreInstallListener : public WebstoreInstaller::Delegate {
 public:
  WebstoreInstallListener()
      : received_failure_(false), received_success_(false), waiting_(false) {}

  void OnExtensionInstallSuccess(const std::string& id) override {
    received_success_ = true;
    id_ = id;

    if (waiting_) {
      waiting_ = false;
      base::RunLoop::QuitCurrentWhenIdleDeprecated();
    }
  }

  void OnExtensionInstallFailure(
      const std::string& id,
      const std::string& error,
      WebstoreInstaller::FailureReason reason) override {
    received_failure_ = true;
    id_ = id;
    error_ = error;
    last_failure_reason_ = reason;

    if (waiting_) {
      waiting_ = false;
      base::RunLoop::QuitCurrentWhenIdleDeprecated();
    }
  }

  void Wait() {
    if (received_success_ || received_failure_)
      return;

    waiting_ = true;
    content::RunMessageLoop();
  }
  bool received_success() const { return received_success_; }
  bool received_failure() const { return received_failure_; }
  const std::string& id() const { return id_; }
  WebstoreInstaller::FailureReason last_failure_reason() {
    return last_failure_reason_;
  }

 private:
  bool received_failure_;
  bool received_success_;
  bool waiting_;
  WebstoreInstaller::FailureReason last_failure_reason_;
  std::string id_;
  std::string error_;
};

}  // namespace

// A base class for tests below.
class ExtensionWebstorePrivateApiTest : public MixinBasedExtensionApiTest {
 public:
  ExtensionWebstorePrivateApiTest() {}

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

  ~ExtensionWebstorePrivateApiTest() override {}

  void SetUpCommandLine(base::CommandLine* command_line) override {
    MixinBasedExtensionApiTest::SetUpCommandLine(command_line);
    command_line->AppendSwitchASCII(
        switches::kAppsGalleryURL,
        "http://www.example.com/extensions/api_test");
  }

  void SetUpOnMainThread() override {
    MixinBasedExtensionApiTest::SetUpOnMainThread();

    // Start up the test server and get us ready for calling the install
    // API functions.
    host_resolver()->AddRule("www.example.com", "127.0.0.1");
    ASSERT_TRUE(StartEmbeddedTestServer());
    extensions::ExtensionInstallUI::set_disable_ui_for_tests();

    auto_confirm_install_ = std::make_unique<ScopedTestDialogAutoConfirm>(
        ScopedTestDialogAutoConfirm::ACCEPT);

    ASSERT_TRUE(webstore_install_dir_.CreateUniqueTempDir());
    webstore_install_dir_copy_ = webstore_install_dir_.GetPath();
    WebstoreInstaller::SetDownloadDirectoryForTests(
        &webstore_install_dir_copy_);
  }

 protected:
  // Returns a test server URL, but with host 'www.example.com' so it matches
  // the web store app's extent that we set up via command line flags.
  GURL DoGetTestServerURL(const std::string& path) {
    GURL url = embedded_test_server()->GetURL(path);

    // Replace the host with 'www.example.com' so it matches the web store
    // app's extent.
    GURL::Replacements replace_host;
    replace_host.SetHostStr("www.example.com");

    return url.ReplaceComponents(replace_host);
  }

  virtual GURL GetTestServerURL(const std::string& path) {
    return DoGetTestServerURL(
        std::string("/extensions/api_test/webstore_private/") + path);
  }

  // Navigates to |page| and runs the Extension API test there. Any downloads
  // of extensions will return the contents of |crx_file|.
  bool RunInstallTest(const std::string& page, const std::string& crx_file) {
    const GURL crx_url = GetTestServerURL(crx_file);
    extension_test_util::SetGalleryUpdateURL(crx_url);

    GURL page_url = GetTestServerURL(page);
    return OpenTestURL(page_url);
  }

  ExtensionService* service() {
    return ExtensionSystem::Get(browser()->profile())->extension_service();
  }

 private:
  base::ScopedTempDir webstore_install_dir_;
  // WebstoreInstaller needs a reference to a FilePath when setting the download
  // directory for testing.
  base::FilePath webstore_install_dir_copy_;

  std::unique_ptr<ScopedTestDialogAutoConfirm> auto_confirm_install_;
};

// Test cases where the user accepts the install confirmation dialog.
IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, InstallAccepted) {
  ASSERT_TRUE(RunInstallTest("accepted.html", "extension.crx"));
}

// Test having the default download directory missing.
IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, MissingDownloadDir) {
  // Set a non-existent directory as the download path.
  base::ScopedAllowBlockingForTesting allow_blocking;
  base::ScopedTempDir temp_dir;
  EXPECT_TRUE(temp_dir.CreateUniqueTempDir());
  base::FilePath missing_directory = temp_dir.Take();
  EXPECT_TRUE(base::DeletePathRecursively(missing_directory));
  WebstoreInstaller::SetDownloadDirectoryForTests(&missing_directory);

  // Now run the install test, which should succeed.
  ASSERT_TRUE(RunInstallTest("accepted.html", "extension.crx"));

  // Cleanup.
  if (base::DirectoryExists(missing_directory))
    EXPECT_TRUE(base::DeletePathRecursively(missing_directory));
}

// Tests passing a localized name.
IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, InstallLocalized) {
  ASSERT_TRUE(RunInstallTest("localized.html", "localized_extension.crx"));
}

// Now test the case where the user cancels the confirmation dialog.
IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, InstallCancelled) {
  ScopedTestDialogAutoConfirm auto_cancel(ScopedTestDialogAutoConfirm::CANCEL);
  ASSERT_TRUE(RunInstallTest("cancelled.html", "extension.crx"));
}

IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, IncorrectManifest1) {
  ASSERT_TRUE(RunInstallTest("incorrect_manifest1.html", "extension.crx"));
}

IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, IncorrectManifest2) {
  ASSERT_TRUE(RunInstallTest("incorrect_manifest2.html", "extension.crx"));
}

// Tests that we can request an app installed bubble (instead of the default
// UI when an app is installed).
IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, AppInstallBubble) {
  WebstoreInstallListener listener;
  WebstorePrivateApi::SetWebstoreInstallerDelegateForTesting(&listener);
  ASSERT_TRUE(RunInstallTest("app_install_bubble.html", "app.crx"));
  listener.Wait();
  ASSERT_TRUE(listener.received_success());
  ASSERT_EQ("iladmdjkfniedhfhcfoefgojhgaiaccc", listener.id());
}

IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, IsInIncognitoMode) {
  GURL page_url = GetTestServerURL("incognito.html");
  ASSERT_TRUE(OpenTestURL(page_url, /*open_in_incognito=*/true));
}

IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, IsNotInIncognitoMode) {
  GURL page_url = GetTestServerURL("not_incognito.html");
  ASSERT_TRUE(OpenTestURL(page_url));
}

// Tests using the iconUrl parameter to the install function.
IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, IconUrl) {
  ASSERT_TRUE(RunInstallTest("icon_url.html", "extension.crx"));
}

// Tests that the Approvals are properly created in beginInstall.
IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, BeginInstall) {
  std::string appId = "iladmdjkfniedhfhcfoefgojhgaiaccc";
  ASSERT_TRUE(RunInstallTest("begin_install.html", "extension.crx"));

  std::unique_ptr<WebstoreInstaller::Approval> approval =
      WebstorePrivateApi::PopApprovalForTesting(browser()->profile(), appId);
  EXPECT_EQ(appId, approval->extension_id);
  EXPECT_TRUE(approval->use_app_installed_bubble);
  EXPECT_FALSE(approval->skip_post_install_ui);
  EXPECT_EQ("2", approval->authuser);
  EXPECT_EQ(browser()->profile(), approval->profile);

  approval = WebstorePrivateApi::PopApprovalForTesting(browser()->profile(),
                                                       kExtensionId);
  EXPECT_EQ(kExtensionId, approval->extension_id);
  EXPECT_FALSE(approval->use_app_installed_bubble);
  EXPECT_FALSE(approval->skip_post_install_ui);
  EXPECT_TRUE(approval->authuser.empty());
  EXPECT_EQ(browser()->profile(), approval->profile);
}

// Tests that themes are installed without an install prompt.
IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, InstallTheme) {
  WebstoreInstallListener listener;
  WebstorePrivateApi::SetWebstoreInstallerDelegateForTesting(&listener);
  ASSERT_TRUE(RunInstallTest("theme.html", "../../theme.crx"));
  listener.Wait();
  ASSERT_TRUE(listener.received_success());
  ASSERT_EQ("idlfhncioikpdnlhnmcjogambnefbbfp", listener.id());
}

// Tests that an error is properly reported when an empty crx is returned.
IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, EmptyCrx) {
  ASSERT_TRUE(RunInstallTest("empty.html", "empty.crx"));
}

#if BUILDFLAG(ENABLE_SUPERVISED_USERS) && !BUILDFLAG(IS_CHROMEOS_LACROS)
static constexpr char kTestChildEmail[] = "test_child_user@google.com";
static constexpr char kTestChildGaiaId[] = "8u8tuw09sufncmnaos";

static constexpr char kTestAppId[] = "iladmdjkfniedhfhcfoefgojhgaiaccc";
static constexpr char kTestAppVersion[] = "0.1";

// Test fixture for various cases of installation for child accounts.
class ExtensionWebstorePrivateApiTestChild
    : public ExtensionWebstorePrivateApiTest,
      public TestParentPermissionDialogViewObserver {
 public:
  // The next dialog action to take.
  enum class NextDialogAction {
    kCancel,
    kAccept,
  };

  ExtensionWebstorePrivateApiTestChild()
      : TestParentPermissionDialogViewObserver(this),
        embedded_test_server_(std::make_unique<net::EmbeddedTestServer>()),
        logged_in_user_mixin_(
            &mixin_host_,
            ash::LoggedInUserMixin::LogInType::kChild,
            embedded_test_server_.get(),
            this,
            true /* should_launch_browser */,
            AccountId::FromUserEmailGaiaId(kTestChildEmail, kTestChildGaiaId)) {
    // Suppress regular user login to enable child user login.
    set_chromeos_user_ = false;
  }

  void SetUpCommandLine(base::CommandLine* command_line) override {
    ExtensionWebstorePrivateApiTest::SetUpCommandLine(command_line);
    // Shortens the merge session timeout from 20 to 1 seconds to speed up the
    // test by about 19 seconds.
    // TODO (crbug.com/995575): figure out why this switch speeds up the test,
    // and fix the test setup so this is not required.
    command_line->AppendSwitch(switches::kShortMergeSessionTimeoutForTest);
  }

  void InitializeFamilyData() {
    // Set up the child user's custodians (i.e. parents).
    ASSERT_TRUE(browser());
    supervised_user_test_util::AddCustodians(browser()->profile());

    // Set up the identity test environment, which provides fake
    // OAuth refresh tokens.
    identity_test_env_ = std::make_unique<signin::IdentityTestEnvironment>();
    identity_test_env_->MakeAccountAvailable(kTestChildEmail);
    identity_test_env_->SetPrimaryAccount(kTestChildEmail,
                                          signin::ConsentLevel::kSync);
    identity_test_env_->SetRefreshTokenForPrimaryAccount();
    identity_test_env_->SetAutomaticIssueOfAccessTokens(true);
  }

  void SetUpOnMainThread() override {
    logged_in_user_mixin_.LogInUser(true /* issue_any_scope_token */);
    ExtensionWebstorePrivateApiTest::SetUpOnMainThread();

    InitializeFamilyData();
    SupervisedUserService* service =
        SupervisedUserServiceFactory::GetForProfile(profile());
    service->SetSupervisedUserExtensionsMayRequestPermissionsPrefForTesting(
        true);
  }

  ash::LoggedInUserMixin* GetLoggedInUserMixin() {
    return &logged_in_user_mixin_;
  }

  void SetNextReAuthStatus(
      const GaiaAuthConsumer::ReAuthProofTokenStatus next_status) {
    GetLoggedInUserMixin()
        ->GetFakeGaiaMixin()
        ->fake_gaia()
        ->SetNextReAuthStatus(next_status);
  }

  // TestParentPermissionDialogViewObserver override:
  void OnTestParentPermissionDialogViewCreated(
      ParentPermissionDialogView* view) override {
    view->SetRepromptAfterIncorrectCredential(false);
    view->SetIdentityManagerForTesting(identity_test_env_->identity_manager());
    // Everything is set up, so take the next action.
    if (next_dialog_action_) {
      switch (next_dialog_action_.value()) {
        case NextDialogAction::kCancel:
          view->CancelDialog();
          break;
        case NextDialogAction::kAccept:
          view->AcceptDialog();
          break;
      }
    }
  }

  void set_next_dialog_action(NextDialogAction action) {
    next_dialog_action_ = action;
  }

 protected:
  std::unique_ptr<signin::IdentityTestEnvironment> identity_test_env_;

 private:
  // Create another embedded test server to avoid starting the same one twice.
  std::unique_ptr<net::EmbeddedTestServer> embedded_test_server_;
  ash::LoggedInUserMixin logged_in_user_mixin_;
  absl::optional<NextDialogAction> next_dialog_action_;
};

// Tests install for a child when parent permission is granted.
IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTestChild,
                       ParentPermissionGranted) {
  WebstoreInstallListener listener;
  WebstorePrivateApi::SetWebstoreInstallerDelegateForTesting(&listener);
  set_next_dialog_action(NextDialogAction::kAccept);

  // Tell the Reauth API client to return a success for the next reauth
  // request.
  SetNextReAuthStatus(GaiaAuthConsumer::ReAuthProofTokenStatus::kSuccess);
  ASSERT_TRUE(RunInstallTest("install_child.html", "app.crx"));
  listener.Wait();
  ASSERT_TRUE(listener.received_success());
  ASSERT_EQ(kTestAppId, listener.id());

  scoped_refptr<const Extension> extension =
      extensions::ExtensionBuilder("test extension")
          .SetID(kTestAppId)
          .SetVersion(kTestAppVersion)
          .Build();
  SupervisedUserService* service =
      SupervisedUserServiceFactory::GetForProfile(profile());
  ASSERT_TRUE(service->IsExtensionAllowed(*extension));
}

// Tests no install occurs for a child when the parent permission
// dialog is canceled.
IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTestChild,
                       ParentPermissionCanceled) {
  WebstoreInstallListener listener;
  set_next_dialog_action(NextDialogAction::kCancel);
  WebstorePrivateApi::SetWebstoreInstallerDelegateForTesting(&listener);
  ASSERT_TRUE(RunInstallTest("install_cancel_child.html", "app.crx"));
  listener.Wait();
  ASSERT_TRUE(listener.received_failure());
  ASSERT_EQ(kTestAppId, listener.id());
  ASSERT_EQ(listener.last_failure_reason(),
            WebstoreInstaller::FailureReason::FAILURE_REASON_CANCELLED);
  scoped_refptr<const Extension> extension =
      extensions::ExtensionBuilder("test extension")
          .SetID(kTestAppId)
          .SetVersion(kTestAppVersion)
          .Build();
  SupervisedUserService* service =
      SupervisedUserServiceFactory::GetForProfile(profile());
  ASSERT_FALSE(service->IsExtensionAllowed(*extension));
}

// Tests that no parent permission is required for a child to install a theme.
IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTestChild,
                       NoParentPermissionRequiredForTheme) {
  WebstoreInstallListener listener;
  WebstorePrivateApi::SetWebstoreInstallerDelegateForTesting(&listener);
  ASSERT_TRUE(RunInstallTest("theme.html", "../../theme.crx"));
  listener.Wait();
  ASSERT_TRUE(listener.received_success());
  ASSERT_EQ("idlfhncioikpdnlhnmcjogambnefbbfp", listener.id());
}

// Tests that even if the kSupervisedUserInitiatedExtensionInstall feature flag
// is enabled, supervised user extension installs are blocked if the
// "Permissions for sites, apps and extensions" toggle is off.
IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTestChild,
                       InstallBlockedWhenPermissionsToggleOff) {
  base::HistogramTester histogram_tester;
  base::UserActionTester user_action_tester;

  SupervisedUserService* service =
      SupervisedUserServiceFactory::GetForProfile(profile());
  service->SetSupervisedUserExtensionsMayRequestPermissionsPrefForTesting(
      false);

  set_next_dialog_action(NextDialogAction::kAccept);
  // Tell the Reauth API client to return a success for the next reauth
  // request.
  SetNextReAuthStatus(GaiaAuthConsumer::ReAuthProofTokenStatus::kSuccess);
  ASSERT_TRUE(RunInstallTest("install_blocked_child.html", "app.crx"));
  histogram_tester.ExpectUniqueSample(
      SupervisedUserExtensionsMetricsRecorder::kEnablementHistogramName,
      SupervisedUserExtensionsMetricsRecorder::EnablementState::kFailedToEnable,
      1);
  histogram_tester.ExpectTotalCount(
      SupervisedUserExtensionsMetricsRecorder::kEnablementHistogramName, 1);
  EXPECT_EQ(
      1,
      user_action_tester.GetActionCount(
          SupervisedUserExtensionsMetricsRecorder::kFailedToEnableActionName));
}

#endif  // BUILDFLAG(ENABLE_SUPERVISED_USERS) && !BUILDFLAG(IS_CHROMEOS_LACROS)

class ExtensionWebstoreGetWebGLStatusTest : public InProcessBrowserTest {
 protected:
  void RunTest(bool webgl_allowed) {
    // If Gpu access is disallowed then WebGL will not be available.
    if (!content::GpuDataManager::GetInstance()->GpuAccessAllowed(nullptr))
      webgl_allowed = false;

    static const char kEmptyArgs[] = "[]";
    static const char kWebGLStatusAllowed[] = "webgl_allowed";
    static const char kWebGLStatusBlocked[] = "webgl_blocked";
    scoped_refptr<WebstorePrivateGetWebGLStatusFunction> function =
        new WebstorePrivateGetWebGLStatusFunction();
    std::unique_ptr<base::Value> result(utils::RunFunctionAndReturnSingleResult(
        function.get(), kEmptyArgs, browser()));
    ASSERT_TRUE(result);
    EXPECT_EQ(base::Value::Type::STRING, result->type());
    EXPECT_TRUE(result->is_string());
    std::string webgl_status = result->GetString();
    EXPECT_STREQ(webgl_allowed ? kWebGLStatusAllowed : kWebGLStatusBlocked,
                 webgl_status.c_str());
  }
};

// Tests getWebGLStatus function when WebGL is allowed.
// Flaky on Mac. https://crbug.com/1346413.
#if BUILDFLAG(IS_MAC)
#define MAYBE_Allowed DISABLED_Allowed
#else
#define MAYBE_Allowed Allowed
#endif
IN_PROC_BROWSER_TEST_F(ExtensionWebstoreGetWebGLStatusTest, MAYBE_Allowed) {
  bool webgl_allowed = true;
  RunTest(webgl_allowed);
}

// Tests getWebGLStatus function when WebGL is blocklisted.
IN_PROC_BROWSER_TEST_F(ExtensionWebstoreGetWebGLStatusTest, Blocked) {
  content::GpuDataManager::GetInstance()->BlocklistWebGLForTesting();

  bool webgl_allowed = false;
  RunTest(webgl_allowed);
}

class ExtensionWebstorePrivateGetReferrerChainApiTest
    : public ExtensionWebstorePrivateApiTest {
 public:
  void SetUpOnMainThread() override {
    host_resolver()->AddRule("redirect1.com", "127.0.0.1");
    host_resolver()->AddRule("redirect2.com", "127.0.0.1");

    ExtensionWebstorePrivateApiTest::SetUpOnMainThread();
  }

  GURL GetTestServerURLWithReferrers(const std::string& path) {
    // Hand craft a url that will cause the test server to issue redirects.
    const std::vector<std::string> redirects = {"redirect1.com",
                                                "redirect2.com"};
    net::HostPortPair host_port = embedded_test_server()->host_port_pair();
    std::string redirect_chain;
    for (const auto& redirect : redirects) {
      std::string redirect_url = base::StringPrintf(
          "http://%s:%d/server-redirect?", redirect.c_str(), host_port.port());
      redirect_chain += redirect_url;
    }

    return GURL(redirect_chain + GetTestServerURL(path).spec());
  }
};

// Tests that the GetReferrerChain API returns the redirect information.
IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateGetReferrerChainApiTest,
                       GetReferrerChain) {
  GURL page_url = GetTestServerURLWithReferrers("referrer_chain.html");
  ASSERT_TRUE(OpenTestURL(page_url));
}

// Tests that the GetReferrerChain API returns an empty string for profiles
// opted out of SafeBrowsing.
IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateGetReferrerChainApiTest,
                       GetReferrerChainForNonSafeBrowsingUser) {
  PrefService* pref_service = browser()->profile()->GetPrefs();
  EXPECT_TRUE(pref_service->GetBoolean(prefs::kSafeBrowsingEnabled));
  // Disable SafeBrowsing.
  pref_service->SetBoolean(prefs::kSafeBrowsingEnabled, false);

  GURL page_url = GetTestServerURLWithReferrers("empty_referrer_chain.html");
  ASSERT_TRUE(OpenTestURL(page_url));
}

class ExtensionWebstorePrivateApiAllowlistEnforcementTest
    : public ExtensionWebstorePrivateApiTest {
 public:
  ExtensionWebstorePrivateApiAllowlistEnforcementTest() {
    feature_list_.InitWithFeatures(
        {extensions_features::kSafeBrowsingCrxAllowlistShowWarnings,
         extensions_features::kSafeBrowsingCrxAllowlistAutoDisable},
        {});
  }

 private:
  base::test::ScopedFeatureList feature_list_;
};

IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiAllowlistEnforcementTest,
                       EnhancedSafeBrowsingNotAllowlisted) {
  safe_browsing::SetSafeBrowsingState(
      browser()->profile()->GetPrefs(),
      safe_browsing::SafeBrowsingState::ENHANCED_PROTECTION);
  ASSERT_TRUE(
      RunInstallTest("safebrowsing_not_allowlisted.html", "extension.crx"));

  EXPECT_EQ(ALLOWLIST_NOT_ALLOWLISTED,
            extension_service()->allowlist()->GetExtensionAllowlistState(
                kExtensionId));
  EXPECT_EQ(
      ALLOWLIST_ACKNOWLEDGE_ENABLED_BY_USER,
      extension_service()->allowlist()->GetExtensionAllowlistAcknowledgeState(
          kExtensionId));
}

IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiAllowlistEnforcementTest,
                       EnhancedSafeBrowsingAllowlisted) {
  safe_browsing::SetSafeBrowsingState(
      browser()->profile()->GetPrefs(),
      safe_browsing::SafeBrowsingState::ENHANCED_PROTECTION);
  ASSERT_TRUE(RunInstallTest("safebrowsing_allowlisted.html", "extension.crx"));

  EXPECT_EQ(ALLOWLIST_UNDEFINED,
            extension_service()->allowlist()->GetExtensionAllowlistState(
                kExtensionId));
}

IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiAllowlistEnforcementTest,
                       StandardSafeBrowsingNotAllowlisted) {
  safe_browsing::SetSafeBrowsingState(
      browser()->profile()->GetPrefs(),
      safe_browsing::SafeBrowsingState::STANDARD_PROTECTION);
  ASSERT_TRUE(
      RunInstallTest("safebrowsing_not_allowlisted.html", "extension.crx"));

  EXPECT_EQ(ALLOWLIST_UNDEFINED,
            extension_service()->allowlist()->GetExtensionAllowlistState(
                kExtensionId));
}

}  // namespace extensions


text:
@interface ARRecorderViewController ()

@property(strong, nonatomic) ARRecorder *recorder;
@property(strong, nonatomic) IBOutlet UIButton *recordButton;
@property (strong, nonatomic) IBOutlet UIBarButtonItem *submitButton;
@property(strong, nonatomic) IBOutlet UILabel *durationCounter;
@property(strong, nonatomic) IBOutlet AROvalTimer *ovalTimer;
@property(strong, nonatomic) NSTimer *timer;

@end

@implementation ARRecorderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initRecorder];
}

- (void)viewDidAppear:(BOOL)animated {
    if (!self.recorder) {
        [self initRecorder];
    }
}

- (void)initRecorder {
    self.recorder = [ARRecorder alloc];
    if(!self.shouldOnlyPlay) {
        self.recorder = [self.recorder initAsRecorderWithName:self.recordingName duration:(long) self.recordingDuration];
        [self switchToReadyToRecordState];
    } else {
        self.recorder = [self.recorder initAsPlayerForFile:self.recordingName];
        [self switchToReadyToListenAndSubmitState];
    }
    self.recorder.delegate = self;
}

- (IBAction)recordButtonTapped:(UIButton *)sender {
    if (!self.recorder.recordingDidFinish) {
        [self toggleRecorderState];
    } else {
        [self togglePlayerState];
    }
}

- (void)toggleRecorderState {
    if (![self.recorder recording]) {
        // Have to start recording
        [self switchToRecordingState];
    } else {
        // Have to cancel recording
        [self switchToReadyToRecordState];
    }
}

- (void)togglePlayerState {
    if (![self.recorder playing]) {
        // Can listen
        [self switchToListeningState];
    } else {
        // Can stop listening
        [self switchToReadyToListenAndSubmitState];
    }
}

- (void)switchToReadyToRecordState {
    [self.recorder stopRecording];
    [self stopDurationCounter];
    [self.ovalTimer initTimerWithDuration:(CGFloat) self.recordingDuration];
    [self setButtonLabel:@"Record" submitButtonVisibility:NO];
    self.durationCounter.text = [NSString stringWithFormat:@"%li", (long) self.recordingDuration];
}

- (void)switchToRecordingState {
    [self setButtonLabel:@"Cancel" submitButtonVisibility:NO];
    [self startDurationCounter];
    [self.ovalTimer startTimer];
    [self.recorder startRecording];
}

- (void)switchToReadyToListenAndSubmitState {
    [self.recorder stopPlaying];
    [self.ovalTimer initTimerWithDuration:(CGFloat) self.recordingDuration];
    [self setButtonLabel:@"Listen" submitButtonVisibility:YES];
    self.durationCounter.text = @"0";
}

- (void)switchToListeningState {
    [self setButtonLabel:@"Stop" submitButtonVisibility:YES];
    [self.recorder startPlaying];
}

- (void)setButtonLabel:(NSString *)label submitButtonVisibility:(BOOL)visible {
    [self.recordButton setTitle:label forState:UIControlStateNormal];
    [self.submitButton setEnabled:visible];
}

- (void)startDurationCounter {
    self.timer = [NSTimer timerWithTimeInterval:0.2f target:self selector:@selector(updateDurationCounter) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

- (void)updateDurationCounter {
    self.durationCounter.text = [NSString stringWithFormat:@"%li", (long) [self.recorder timeLeft]];
    if ([self.recorder timeLeft] <= 0) {
        self.recorder.recordingDidFinish = YES;
        [self stopDurationCounter];
        [self.ovalTimer stopTimer];
        [self switchToReadyToListenAndSubmitState];
    }
}

- (void)stopDurationCounter {
    if (self.timer) {
        [self.timer invalidate];
    }
}

- (IBAction)submitButtonTapped:(UIButton *)sender {
    [self.recorder stopPlaying];
    if (self.recorder.recordingDidFinish) {
        [self.delegate recordingDidFinish:self withFileURL:self.recorder.recordingFileURL];
    }
}

- (IBAction)cancelButtonTapped:(UIButton *)sender {
    [self.recorder stopPlayingAndRecording];
    [self.delegate recordingDidCancel:self];
}

@end


text:
using System;
using HOLMS.Types.Extensions.Support;

namespace HOLMS.Types.Booking {
    public partial class CancellationReason {
        public CancellationReason(Guid id, string reason) {
            EntityId = id.ToUUID();
            ReasonText = reason;
        }
    }
}


text:
Add this line to your application's Gemfile:

    gem 'hipchat_exception_notifier'

And then execute:

    $ bundle

Add to your environment file:

```ruby
require "hipchat_exception_notifier"
config.middleware.use "HipchatExceptionNotifier",
  token: "...token...",
  room_name: "...room name...",
  user: "Notifier",
  announce: false
```

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
package com.datasaver.www.apis.services;

import com.datasaver.www.apis.APIAdapter;
import com.datasaver.www.apis.services.interfaces.CheckServiceInterface;

public class CheckService {
    public static CheckServiceInterface build() {
        return (CheckServiceInterface) APIAdapter.build(CheckServiceInterface.class);
    }
}


text:
#ifndef __MDSPARTIALDOWNLOAD_H
#define __MDSPARTIALDOWNLOAD_H

#include "midasStandardIncludes.h"

namespace mds
{

class PartialDownload
{
public:
  PartialDownload();
  ~PartialDownload();

  // Create a partial download record for a file
  bool Commit();

  // Remove a partial download record for a file
  bool Remove();

  // Return a list of all incomplete downloads
  static bool FetchAll(std::vector<mds::PartialDownload *>& list);

  // Clear all incomplete downloads
  static bool RemoveAll();

  void SetId(int id);

  int GetId();

  void SetOffset(int64 offset);

  int64 GetOffset();

  void SetPath(const std::string& path);

  std::string GetPath();

  void SetParentItem(int parentItem);

  int GetParentItem();

  void SetUuid(const std::string& uuid);

  std::string GetUuid();

protected:
  int         Id;
  int         ParentItem;
  std::string Path;
  std::string Uuid;
  int64       Offset;
};

} // end namespace mds
#endif


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.streamanalytics.models;

import com.azure.core.util.ExpandableStringEnum;
import com.fasterxml.jackson.annotation.JsonCreator;
import java.util.Collection;

/** Defines values for OutputErrorPolicy. */
public final class OutputErrorPolicy extends ExpandableStringEnum<OutputErrorPolicy> {
    /** Static value Stop for OutputErrorPolicy. */
    public static final OutputErrorPolicy STOP = fromString("Stop");

    /** Static value Drop for OutputErrorPolicy. */
    public static final OutputErrorPolicy DROP = fromString("Drop");

    /**
     * Creates or finds a OutputErrorPolicy from its string representation.
     *
     * @param name a name to look for.
     * @return the corresponding OutputErrorPolicy.
     */
    @JsonCreator
    public static OutputErrorPolicy fromString(String name) {
        return fromString(name, OutputErrorPolicy.class);
    }

    /** @return known OutputErrorPolicy values. */
    public static Collection<OutputErrorPolicy> values() {
        return values(OutputErrorPolicy.class);
    }
}


text:
/*--------------------------------------------------*/

#import "GLBGeoLocationManager.h"

/*--------------------------------------------------*/
#pragma mark -
/*--------------------------------------------------*/

@interface GLBGeoLocationManager () < CLLocationManagerDelegate > {
    CLLocationManager* _locationManager;
    NSMutableArray* _requests;
    BOOL _updatingLocation;
#if defined(GLB_TARGET_IOS)
    BOOL _startedMonitoringSignificantLocationChanges;
#endif
    BOOL _startedUpdatingLocation;
    CLAuthorizationStatus _authorizationStatus;
    NSError* _lastError;
}

+ (void)_perform:(dispatch_block_t)block;

- (void)_startUpdatingIfNeeded;
- (void)_stopUpdatingIfPossible;
- (GLBGeoLocationRequest*)_addRequest:(GLBGeoLocationRequest*)request;
- (void)_removeRequest:(GLBGeoLocationRequest*)request;
- (void)_processRequests:(CLLocation*)location;

@end

/*--------------------------------------------------*/
#pragma mark -
/*--------------------------------------------------*/

@interface GLBGeoLocationRequest () {
    __weak GLBGeoLocationManager* _geoLocationManager;
    BOOL _subscription;
    BOOL _canceled;

    NSDate* _requestStartTime;
    NSTimer* _timer;
}

@property(nonatomic, readonly, strong) GLBAction* actionSuccess;
@property(nonatomic, readonly, strong) GLBAction* actionFailure;

- (instancetype)initWithGeoLocationManager:(GLBGeoLocationManager*)geoLocationManager
                           desiredAccuracy:(CLLocationAccuracy)desiredAccuracy
                           timeoutInterval:(NSTimeInterval)timeoutInterval
                                   success:(GLBAction*)success
                                   failure:(GLBAction*)failure;

- (instancetype)initWithGeoLocationManager:(GLBGeoLocationManager*)geoLocationManager
                           desiredAccuracy:(CLLocationAccuracy)desiredAccuracy
                            updateInterval:(NSTimeInterval)updateInterval
                                   success:(GLBAction*)success
                                   failure:(GLBAction*)failure;

- (void)_start;
- (void)_stop;
- (void)_cancel;

@end

/*--------------------------------------------------*/
#pragma mark -
/*--------------------------------------------------*/

@implementation GLBGeoLocationManager

#pragma mark - Synthesize

@synthesize requests = _requests;
@synthesize updatingLocation = _updatingLocation;

#pragma mark - Init / Free

- (instancetype)init {
    self = [super init];
    if(self != nil) {
        [self setup];
    }
    return self;
}

- (void)setup {
    _timeAccuracy = 60.0f;
#if defined(GLB_TARGET_IOS)
    _useMonitoringSignificantChanges = YES;
#endif
    _useUpdatingLocation = YES;
    _locationManager = [CLLocationManager new];
    _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    _requests = [NSMutableArray array];
    _authorizationStatus = CLLocationManager.authorizationStatus;
}

#pragma mark - Static

+ (GLBGeoLocationServicesState)servicesState {
    if(CLLocationManager.locationServicesEnabled == NO) {
        return GLBGeoLocationServicesStateDisabled;
    } else if(CLLocationManager.authorizationStatus == kCLAuthorizationStatusNotDetermined) {
        return GLBGeoLocationServicesStateNotDetermined;
    } else if (CLLocationManager.authorizationStatus == kCLAuthorizationStatusDenied) {
        return GLBGeoLocationServicesStateDenied;
    } else if (CLLocationManager.authorizationStatus == kCLAuthorizationStatusRestricted) {
        return GLBGeoLocationServicesStateRestricted;
    }
    return GLBGeoLocationServicesStateAvailable;
}

#if defined(GLB_TARGET_IOS)

+ (BOOL)availableSignificantMonitoringChanges {
    return CLLocationManager.significantLocationChangeMonitoringAvailable;
}

#endif

+ (instancetype)shared {
    static id instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [self new];
    });
    return instance;
}

#pragma mark - Property

#if defined(GLB_TARGET_IOS)

- (void)setAllowsBackgroundUpdates:(BOOL)allowsBackgroundUpdates {
    if([UIDevice glb_compareSystemVersion:@"9.0"] != NSOrderedAscending) {
        _locationManager.allowsBackgroundLocationUpdates = allowsBackgroundUpdates;
    }
}

- (BOOL)allowsBackgroundUpdates {
    if([UIDevice glb_compareSystemVersion:@"9.0"] != NSOrderedAscending) {
        return _locationManager.allowsBackgroundLocationUpdates;
    }
    return YES;
}

#endif

#if defined(GLB_TARGET_IOS)

- (void)setUseMonitoringSignificantChanges:(BOOL)useMonitoringSignificantChanges {
    if(_useMonitoringSignificantChanges != useMonitoringSignificantChanges) {
        if((_useMonitoringSignificantChanges == YES) && (_startedMonitoringSignificantLocationChanges == YES)) {
            _startedMonitoringSignificantLocationChanges = NO;
            [_locationManager stopMonitoringSignificantLocationChanges];
        }
        _useMonitoringSignificantChanges = useMonitoringSignificantChanges;
        if((_useMonitoringSignificantChanges == YES) && (_updatingLocation == YES)) {
            _startedMonitoringSignificantLocationChanges = YES;
            [_locationManager startMonitoringSignificantLocationChanges];
        }
    }
}

#endif

- (void)setUseUpdatingLocation:(BOOL)useUpdatingLocation {
    if(_useUpdatingLocation != useUpdatingLocation) {
        if((_useUpdatingLocation == YES) && (_startedUpdatingLocation == YES)) {
            _startedUpdatingLocation = NO;
            [_locationManager stopUpdatingLocation];
        }
        _useUpdatingLocation = useUpdatingLocation;
        if((_useUpdatingLocation == YES) && (_updatingLocation == YES)) {
            _startedUpdatingLocation = YES;
            [_locationManager startUpdatingLocation];
        }
    }
}

#pragma mark - Public

- (GLBGeoLocationRequest*)requestWithDesiredAccuracy:(CLLocationAccuracy)desiredAccuracy
                                             success:(GLBAction*)success
                                             failure:(GLBAction*)failure {
    return [self requestWithDesiredAccuracy:desiredAccuracy
                            timeoutInterval:0.0
                                    success:success
                                    failure:failure];
}

- (GLBGeoLocationRequest*)requestWithDesiredAccuracy:(CLLocationAccuracy)desiredAccuracy
                                     timeoutInterval:(NSTimeInterval)timeoutInterval
                                             success:(GLBAction*)success
                                             failure:(GLBAction*)failure {
    GLBGeoLocationRequest* request = [[GLBGeoLocationRequest alloc] initWithGeoLocationManager:self
                                                                               desiredAccuracy:desiredAccuracy
                                                                               timeoutInterval:timeoutInterval
                                                                                success:success
                                                                                failure:failure];
    return [self _addRequest:request];
}

- (GLBGeoLocationRequest*)subscribeWithDesiredAccuracy:(CLLocationAccuracy)desiredAccuracy
                                               success:(GLBAction*)success
                                               failure:(GLBAction*)failure {
    return [self subscribeWithDesiredAccuracy:desiredAccuracy
                               updateInterval:0.0
                                     success:success
                                      failure:failure];
}

- (GLBGeoLocationRequest*)subscribeWithDesiredAccuracy:(CLLocationAccuracy)desiredAccuracy
                                        updateInterval:(NSTimeInterval)updateInterval
                                               success:(GLBAction*)success
                                               failure:(GLBAction*)failure {
    GLBGeoLocationRequest* request = [[GLBGeoLocationRequest alloc] initWithGeoLocationManager:self
                                                                               desiredAccuracy:desiredAccuracy
                                                                                updateInterval:updateInterval
                                                                                success:success
                                                                                failure:failure];
    return [self _addRequest:request];
}

- (void)cancelRequest:(GLBGeoLocationRequest*)request {
    [self.class _perform:^{
        [request _cancel];
        [self _removeRequest:request];
        if(_lastError != nil) {
            [request.actionFailure performWithArguments:@[ request, _lastError ]];
        } else {
            [request.actionFailure performWithArguments:@[ request ]];
        }
    }];
}

- (void)cancelAllRequests {
    [self.class _perform:^{
        [_requests enumerateObjectsUsingBlock:^(GLBGeoLocationRequest* request, NSUInteger index, BOOL* stop) {
            [self cancelRequest:request];
        }];
    }];
}

- (void)geocodeAddressString:(NSString*)address block:(CLGeocodeCompletionHandler)block {
    if(block != nil) {
        CLGeocoder* geocoder = [CLGeocoder new];
        [geocoder geocodeAddressString:address completionHandler:^(NSArray* placemarks, NSError* error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                block(placemarks, error);
            });
        }];
    }
}

- (void)reverseGeocodeLocation:(CLLocation*)location block:(CLGeocodeCompletionHandler)block {
    if(block != nil) {
        CLGeocoder* geocoder = [CLGeocoder new];
        [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray* placemarks, NSError* error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                block(placemarks, error);
            });
        }];
    }
}

#pragma mark - Private

+ (void)_perform:(dispatch_block_t)block {
    if(NSThread.isMainThread == YES) {
        block();
    } else {
        dispatch_sync(dispatch_get_main_queue(), block);
    }
}

- (void)_startUpdatingIfNeeded {
#if defined(GLB_TARGET_IOS)
    BOOL needRequest = ([UIDevice glb_compareSystemVersion:@"8.0"] != NSOrderedAscending);
#elif defined(GLB_TARGET_WATCHOS)
    BOOL needRequest = YES;
#endif
    BOOL requestAccess = NO;
    if(needRequest == YES) {
        switch(CLLocationManager.authorizationStatus) {
            case kCLAuthorizationStatusNotDetermined: {
                BOOL hasAlwaysKey = ([NSBundle.mainBundle objectForInfoDictionaryKey:@"NSLocationAlwaysUsageDescription"] != nil);
                BOOL hasWhenInUseKey = ([NSBundle.mainBundle objectForInfoDictionaryKey:@"NSLocationWhenInUseUsageDescription"] != nil);
                if(hasAlwaysKey == YES) {
                    [_locationManager requestAlwaysAuthorization];
                } else if(hasWhenInUseKey == YES) {
                    [_locationManager requestWhenInUseAuthorization];
                } else {
                    NSAssert((hasAlwaysKey == YES) || (hasWhenInUseKey == YES), @"To use location services in iOS 8+, your Info.plist must provide a value for either NSLocationWhenInUseUsageDescription or NSLocationAlwaysUsageDescription.");
                }
                requestAccess = YES;
                break;
            }
            default: break;
        }
    }
    if((_requests.count > 0) && (_updatingLocation == NO)) {
        if(requestAccess == NO) {
            CLLocation* location = _locationManager.location;
            if(location != nil) {
                __weak typeof(self) weakSelf = self;
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf _processRequests:location];
                });
            }
        }
        if(_requests.count > 0) {
            if(requestAccess == NO) {
                _updatingLocation = YES;
            }
            _locationManager.delegate = self;
#if defined(GLB_TARGET_IOS)
            if(_useMonitoringSignificantChanges == YES) {
                _startedMonitoringSignificantLocationChanges = YES;
                [_locationManager startMonitoringSignificantLocationChanges];
            }
#endif
            if(_useUpdatingLocation == YES) {
                _startedUpdatingLocation = YES;
                [_locationManager startUpdatingLocation];
            }
        }
    }
}

- (void)_stopUpdatingIfPossible {
    if((_requests.count < 1) && (_updatingLocation == YES)) {
        _updatingLocation = NO;

#if defined(GLB_TARGET_IOS)
        if(_startedMonitoringSignificantLocationChanges == YES) {
            _startedMonitoringSignificantLocationChanges = NO;
            [_locationManager stopMonitoringSignificantLocationChanges];
        }
#endif
        if(_startedUpdatingLocation == YES) {
            _startedUpdatingLocation = NO;
            [_locationManager stopUpdatingLocation];
        }
        _locationManager.delegate = nil;
    }
}

- (GLBGeoLocationRequest*)_addRequest:(GLBGeoLocationRequest*)request {
    __block GLBGeoLocationRequest* result = request;
    [self.class _perform:^{
        switch(self.class.servicesState) {
            case GLBGeoLocationServicesStateDisabled:
            case GLBGeoLocationServicesStateDenied:
            case GLBGeoLocationServicesStateRestricted: {
                if(_lastError == nil) {
                    _lastError = [NSError errorWithDomain:kCLErrorDomain code:kCLErrorDenied userInfo:nil];
                }
                [result.actionFailure performWithArguments:@[ result, _lastError ]];
                result = nil;
                break;
            }
            default:
                break;
        }
        if(result != nil) {
            [_requests addObject:result];
            [self _startUpdatingIfNeeded];
            if(_updatingLocation == YES) {
                [result _start];
            }
        }
    }];
    return result;
}

- (void)_removeRequest:(GLBGeoLocationRequest*)request {
    [self.class _perform:^{
        [_requests removeObject:request];
        [self _stopUpdatingIfPossible];
    }];
}

- (void)_processRequests:(CLLocation*)location {
    if(location != nil) {
        NSTimeInterval delta = location.timestamp.timeIntervalSinceNow;
        if(ABS(delta) > _timeAccuracy) {
            location = nil;
        }
    }
    NSMutableArray* removedRequest = [NSMutableArray array];
    for(GLBGeoLocationRequest* request in _requests) {
        if(request.hasTimedOut == YES) {
            [removedRequest addObject:request];
            _lastError = [NSError errorWithDomain:kCLErrorDomain code:kCLErrorLocationUnknown userInfo:nil];
            [request.actionFailure performWithArguments:@[ request, _lastError ]];
        } else if(location != nil) {
            BOOL finish = NO;
            CLLocationAccuracy desiredAccuracy = MAX(location.horizontalAccuracy, location.verticalAccuracy);
            NSTimeInterval timeSinceUpdate = ABS(location.timestamp.timeIntervalSinceNow);
            if((request.desiredAccuracy > FLT_EPSILON) && (desiredAccuracy <= request.desiredAccuracy)) {
                finish = YES;
            }
            if((request.updateInterval > FLT_EPSILON) && (timeSinceUpdate >= request.updateInterval)) {
                finish = YES;
            }
            if(finish == YES) {
                if(request.isSubscription == NO) {
                    [removedRequest addObject:request];
                }
                [request.actionSuccess performWithArguments:@[ request, location ]];
            }
        }
    }
    for(GLBGeoLocationRequest* request in removedRequest) {
        [request _stop];
        [self _removeRequest:request];
    }
}

#pragma mark - CLLocationManagerDelegate

- (void)locationManager:(CLLocationManager*)manager didUpdateLocations:(NSArray*)locations {
    [self.class _perform:^{
        [self _processRequests:locations.lastObject];
    }];
}

- (void)locationManager:(CLLocationManager*)manager didFailWithError:(NSError*)error {
    [self.class _perform:^{
        _lastError = error;
        [self cancelAllRequests];
    }];
}

- (void)locationManager:(CLLocationManager*)locationManager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    [self.class _perform:^{
        switch(status) {
            case kCLAuthorizationStatusDenied:
            case kCLAuthorizationStatusRestricted: {
                _lastError = [NSError errorWithDomain:kCLErrorDomain code:kCLErrorDenied userInfo:nil];
                [self cancelAllRequests];
                if(_authorizationStatus == kCLAuthorizationStatusNotDetermined) {
                    [NSNotificationCenter.defaultCenter postNotificationName:GLBGeoLocationManagerUserDenied object:self];
                    _authorizationStatus = status;
                }
                break;
            }
            case kCLAuthorizationStatusAuthorizedAlways:
            case kCLAuthorizationStatusAuthorizedWhenInUse: {
                for(GLBGeoLocationRequest* request in _requests) {
                    [request _start];
                }
                CLLocation* location = _locationManager.location;
                if(location != nil) {
                    [self _processRequests:location];
                }
                break;
            }
            default:
                break;
        }
    }];
}

@end

/*--------------------------------------------------*/

NSString* GLBGeoLocationManagerUserDenied = @"GLBGeoLocationManagerUserDenied";

/*--------------------------------------------------*/
#pragma mark -
/*--------------------------------------------------*/

@implementation GLBGeoLocationRequest

#pragma mark - Synthesize

@synthesize desiredAccuracy = _desiredAccuracy;
@synthesize timeoutInterval = _timeoutInterval;
@synthesize updateInterval = _updateInterval;
@synthesize subscription = _subscription;
@synthesize canceled = _canceled;

#pragma mark - Init / Free

- (instancetype)initWithGeoLocationManager:(GLBGeoLocationManager*)geoLocationManager
                           desiredAccuracy:(CLLocationAccuracy)desiredAccuracy
                           timeoutInterval:(NSTimeInterval)timeoutInterval
                                   success:(GLBAction*)success
                                   failure:(GLBAction*)failure {
    self = [super init];
    if(self != nil) {
        _geoLocationManager = geoLocationManager;
        _desiredAccuracy = desiredAccuracy;
        _timeoutInterval = timeoutInterval;
        _subscription = NO;
        _actionSuccess = success;
        _actionFailure = failure;
    }
    return self;
}

- (instancetype)initWithGeoLocationManager:(GLBGeoLocationManager*)geoLocationManager
                           desiredAccuracy:(CLLocationAccuracy)desiredAccuracy
                            updateInterval:(NSTimeInterval)updateInterval
                                   success:(GLBAction*)success
                                   failure:(GLBAction*)failure {
    self = [super init];
    if(self != nil) {
        _geoLocationManager = geoLocationManager;
        _desiredAccuracy = desiredAccuracy;
        _updateInterval = updateInterval;
        _subscription = YES;
        _actionSuccess = success;
        _actionFailure = failure;
    }
    return self;
}

- (void)dealloc {
    [self _stop];
}

#pragma mark - Public

- (BOOL)hasTimedOut {
    if(_timeoutInterval > FLT_EPSILON) {
        NSTimeInterval aliveInterval = ABS(_requestStartTime.timeIntervalSinceNow);
        if(aliveInterval >= _timeoutInterval) {
            return YES;
        }
    }
    return NO;
}

#pragma mark - Public

- (void)cancel {
    [_geoLocationManager cancelRequest:self];
}

#pragma mark - Private

- (void)_start {
    if(_requestStartTime == nil) {
        _requestStartTime = [NSDate date];
    }
    if((_timeoutInterval > FLT_EPSILON) && (_timer == nil)) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:_timeoutInterval
                                                  target:self
                                                selector:@selector(_timeout)
                                                userInfo:nil
                                                 repeats:NO];
    }
}

- (void)_stop {
    if(_timer != nil) {
        [_timer invalidate];
        _timer = nil;
    }
}

- (void)_cancel {
    [self _stop];
    _canceled = YES;
}

#pragma mark - Timer

- (void)_timeout {
    [_geoLocationManager _processRequests:nil];
}

@end

/*--------------------------------------------------*/
#pragma mark -
/*--------------------------------------------------*/

@implementation CLLocation (GLBGeoLocation)

#pragma mark - GLBObjectDebugProtocol

- (void)glb_debugString:(NSMutableString*)string context:(NSPointerArray*)context indent:(NSUInteger)indent root:(BOOL)root {
    if(root == YES) {
        [string glb_appendString:@"\t" repeat:indent];
    }
    NSUInteger baseIndent = indent + 1;
    [string appendFormat:@"<%@\n", self.glb_className];

    [string glb_appendString:@"\t" repeat:baseIndent];
    [string appendFormat:@"Latitude : %f\n", self.coordinate.latitude];

    [string glb_appendString:@"\t" repeat:baseIndent];
    [string appendFormat:@"Longitude : %f\n", self.coordinate.longitude];

    [string glb_appendString:@"\t" repeat:baseIndent];
    [string appendFormat:@"Altitude : %f\n", self.altitude];

    [string glb_appendString:@"\t" repeat:indent];
    [string appendString:@">"];
}

@end

/*--------------------------------------------------*/
#pragma mark -
/*--------------------------------------------------*/

@implementation NSError (GLBGeoLocation)

- (BOOL)glb_isGeoLocation {
    return ([self.domain isEqualToString:kCLErrorDomain] == YES);
}

- (BOOL)glb_geoLocationUnknown {
    return (self.glb_isGeoLocation == YES) && (self.code == kCLErrorLocationUnknown);
}

- (BOOL)glb_geoLocationAccessDenied {
    return (self.glb_isGeoLocation == YES) && (self.code == kCLErrorDenied);
}

- (BOOL)glb_geoLocationNetwork {
    return (self.glb_isGeoLocation == YES) && (self.code == kCLErrorNetwork);
}

@end

/*--------------------------------------------------*/


text:
set -e

puppy module <<-usage
    usage: puppy vpc create

    description:
        Create an AWS VPC.
usage

dir=$(mktemp -d -t homeport_append.XXXXXXX)

trap cleanup EXIT SIGTERM SIGINT

function cleanup() {
    [ ! -z "$dir" ] && rm -rf "$dir"
}

aws elb delete-security-group \
    --region="$puppy_region" \
    --group-id="$(puppy_exec elb group)"

aws elb delete-load-balancer \
    --region="$puppy_region" \
    --load-balancer-name="$puppy_tag-balancer"


text:
#ifndef __HOST1X_GEM_H
#define __HOST1X_GEM_H

#include <linux/host1x.h>

#include <drm/drm.h>
#include <drm/drmP.h>

#define TEGRA_BO_TILED     (1 << 0)
#define TEGRA_BO_BOTTOM_UP (1 << 1)

struct tegra_bo {
	struct drm_gem_object gem;
	struct host1x_bo base;
	unsigned long flags;
	struct sg_table *sgt;
	dma_addr_t paddr;
	void *vaddr;
};

static inline struct tegra_bo *to_tegra_bo(struct drm_gem_object *gem)
{
	return container_of(gem, struct tegra_bo, gem);
}

struct tegra_bo *tegra_bo_create(struct drm_device *drm, unsigned int size,
				 unsigned long flags);
struct tegra_bo *tegra_bo_create_with_handle(struct drm_file *file,
					     struct drm_device *drm,
					     unsigned int size,
					     unsigned long flags,
					     unsigned int *handle);
void tegra_bo_free_object(struct drm_gem_object *gem);
int tegra_bo_dumb_create(struct drm_file *file, struct drm_device *drm,
			 struct drm_mode_create_dumb *args);
int tegra_bo_dumb_map_offset(struct drm_file *file, struct drm_device *drm,
			     uint32_t handle, uint64_t *offset);

int tegra_drm_mmap(struct file *file, struct vm_area_struct *vma);

extern const struct vm_operations_struct tegra_bo_vm_ops;

struct dma_buf *tegra_gem_prime_export(struct drm_device *drm,
				       struct drm_gem_object *gem,
				       int flags);
struct drm_gem_object *tegra_gem_prime_import(struct drm_device *drm,
					      struct dma_buf *buf);

#endif


text:
<?php

namespace Presque\Log;

use Symfony\Component\HttpKernel\Log\LoggerInterface as SymfonyLoggerInterface;

/**
 * Symfony HttpKernel LoggerInterface adapter
 */
class SymfonyLogAdapter extends AbstractLogAdapter
{
    /**
     * {@inheritdoc}
     */
    public function __construct(SymfonyLoggerInterface $logObject = null)
    {
        $this->log = $logObject;
    }
}


text:
import axios from 'axios';
import config from '../helpers/config';
import { FETCH_PEOPLE, FETCH_PERSON_DETAILS, FILTER } from './StarWars/types';
import { CONFIG_DISCOVERY_URL_KEY, CONFIG_DISCOVERY_PEOPLE_KEY } from '../constants';

const ROOT_URL = config(CONFIG_DISCOVERY_URL_KEY);
let _links = {};
const params = {
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  }
};

const dispatchToAction = (payload, action) => {
  return {
    type: action,
    payload
  };
};

const getDiscoveryURL = (key) => {
  if (!!Object.keys(_links).length) {
    return Promise.resolve(_links[key]);
  }
  return axios.get(`${ROOT_URL}/?format=json`).then(response => {
    _links = response.data;
    return _links[key];
  });
};

const mapPersonWithPlanet = (results, planets) => {
  return results.map((person, index) => {
    return {
      ...person,
      id: Number(person.url.replace(/\D/g, '')),
      planet: {
        name: planets[index]
      }
    };
  });
};

const getPlanetByPerson = (results) => {
  return axios.all(results.map(person => {
    return axios.get(person.homeworld, params).then(planetResponse => {
      return planetResponse.data.name;
    });
  }));
};

export function fetchPeople(url) {
  const callback = !!url ? Promise.resolve(url) : getDiscoveryURL(CONFIG_DISCOVERY_PEOPLE_KEY);
  return callback
    .then(currentURL => axios.get(currentURL, params))
    .then(response => {
      return getPlanetByPerson(response.data.results)
        .then(planets => {
          response.data.results = mapPersonWithPlanet(response.data.results, planets);
          return response;
        })
        .then(res => dispatchToAction(res, FETCH_PEOPLE));
    });
}

export function fetchPeopleByPaginationURL(url) {
  return fetchPeople(url);
}

export function fetchPersonDetails(id) {
  return getDiscoveryURL(CONFIG_DISCOVERY_PEOPLE_KEY)
    .then(currentURL => `${currentURL}${id}`)
    .then(url => axios.get(url, params))
    .then(res => {
      return axios.get(res.data.homeworld)
        .then(planetResponse => {
          res.data.planet = { name: planetResponse.data.name };
          return dispatchToAction(res, FETCH_PERSON_DETAILS);
        });
    });
}

export function filterTable(filterBy) {
  return dispatchToAction(filterBy, FILTER);
}


text:
package de.codecentric.boot.admin.server.notify;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Nullable;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import reactor.core.publisher.Mono;

import de.codecentric.boot.admin.server.domain.entities.Instance;
import de.codecentric.boot.admin.server.domain.entities.InstanceRepository;
import de.codecentric.boot.admin.server.domain.events.InstanceEvent;

import static java.util.Collections.singleton;

/**
 * Notifier sending emails using thymleaf templates.
 *
 * @author Johannes Edmeier
 */
public class MailNotifier extends AbstractStatusChangeNotifier {

	private final JavaMailSender mailSender;

	private final TemplateEngine templateEngine;

	/**
	 * recipients of the mail
	 */
	private String[] to = { "root@localhost" };

	/**
	 * cc-recipients of the mail
	 */
	private String[] cc = {};

	/**
	 * sender of the change
	 */
	private String from = "Spring Boot Admin <noreply@localhost>";

	/**
	 * Additional properties to be set for the template
	 */
	private Map<String, Object> additionalProperties = new HashMap<>();

	/**
	 * Base-URL used for hyperlinks in mail
	 */
	@Nullable
	private String baseUrl;

	/**
	 * Thymleaf template for mail
	 */
	private String template = "classpath:/META-INF/spring-boot-admin-server/mail/status-changed.html";

	public MailNotifier(JavaMailSender mailSender, InstanceRepository repository, TemplateEngine templateEngine) {
		super(repository);
		this.mailSender = mailSender;
		this.templateEngine = templateEngine;
	}

	@Override
	protected Mono<Void> doNotify(InstanceEvent event, Instance instance) {
		return Mono.fromRunnable(() -> {
			Context ctx = new Context();
			ctx.setVariables(additionalProperties);
			ctx.setVariable("baseUrl", this.baseUrl);
			ctx.setVariable("event", event);
			ctx.setVariable("instance", instance);
			ctx.setVariable("lastStatus", getLastStatus(event.getInstance()));

			try {
				MimeMessage mimeMessage = mailSender.createMimeMessage();
				MimeMessageHelper message = new MimeMessageHelper(mimeMessage, StandardCharsets.UTF_8.name());
				message.setText(getBody(ctx).replaceAll("\\s+\\n", "\n"), true);
				message.setSubject(getSubject(ctx));
				message.setTo(this.to);
				message.setCc(this.cc);
				message.setFrom(this.from);
				mailSender.send(mimeMessage);
			}
			catch (MessagingException ex) {
				throw new RuntimeException("Error sending mail notification", ex);
			}
		});
	}

	protected String getBody(Context ctx) {
		return templateEngine.process(this.template, ctx);
	}

	protected String getSubject(Context ctx) {
		return templateEngine.process(this.template, singleton("subject"), ctx).trim();
	}

	public void setTo(String[] to) {
		this.to = Arrays.copyOf(to, to.length);
	}

	public String[] getTo() {
		return Arrays.copyOf(to, to.length);
	}

	public void setCc(String[] cc) {
		this.cc = Arrays.copyOf(cc, cc.length);
	}

	public String[] getCc() {
		return Arrays.copyOf(cc, cc.length);
	}

	public void setFrom(String from) {
		this.from = from;
	}

	public String getFrom() {
		return from;
	}

	public String getTemplate() {
		return template;
	}

	public void setTemplate(String template) {
		this.template = template;
	}

	@Nullable
	public String getBaseUrl() {
		return baseUrl;
	}

	public void setBaseUrl(@Nullable String baseUrl) {
		this.baseUrl = baseUrl;
	}

	public Map<String, Object> getAdditionalProperties() {
		return additionalProperties;
	}

	public void setAdditionalProperties(Map<String, Object> additionalProperties) {
		this.additionalProperties = additionalProperties;
	}

}


text:
define({
  "viewer": {
    "common": {
      "close": "Fechar",
      "focusMainstage": "Enviar foco de teclado para media",
      "expandImage": "Expandir imagem"
    },
    "a11y": {
      "skipToContent": "Saltar para conteúdo",
      "headerAria": "Cabeçalho da história",
      "panelAria": "Conteúdo da história",
      "mainStageAria": "Formato atual de entrada de história",
      "logoLinkAria": "Ligação ao logótipo",
      "toTop": "Ir para a primeira entrada",
      "focusContent": "Regressar a conteúdo",
      "navAria": "Entradas de histórias",
      "toEntryAria": "Ir para a entrada %ENTRY_NUMBER%: %ENTRY_TITLE%",
      "entryAria": "Entrada %ENTRY_NUMBER%: %ENTRY_TITLE%",
      "loadingAria": "O conteúdo da história está a carregar",
      "skipBelowContent": "Saltar abaixo deste conteúdo",
      "skipBelowVideo": "Saltar abaixo deste vídeo",
      "skipAboveContent": "Saltar acima deste conteúdo",
      "skipAboveVideo": "Saltar acima deste vídeo",
      "moreEntries": "Mais entradas"
    },
    "loading": {
      "long": "A história está a inicializar",
      "long2": "Obrigado por aguardar",
      "failButton": "Recarregar a história"
    },
    "signin": {
      "title": "É necessária autenticação",
      "explainViewer": "Por favor inicie sessão com uma conta em %PORTAL_LINK% para aceder à história.",
      "explainBuilder": "Por favor inicie sessão com uma conta em %PORTAL_LINK% para configurar a história."
    },
    "errors": {
      "boxTitle": "Ocorreu um erro",
      "invalidConfig": "Configuração inválida",
      "invalidConfigNoApp": "Identificador de Aplicação de Cartografia Web não especificada em index.html.",
      "invalidConfigNoAppDev": "Não foi especificado nenhum identificador de Aplicação de Mapeamento Web nos parâmetros URL (?appid=). No modo de desenvolvimento, a configuração appid em index.html é ignorada.",
      "unspecifiedConfigOwner": "O proprietário autorizado não foi configurado.",
      "invalidConfigOwner": "O proprietário da história não está autorizado.",
      "createMap": "Não foi possível criar mapa",
      "invalidApp": "O %TPL_NAME% não existe ou encontra-se inacessível.",
      "appLoadingFail": "Algo correu mal, o %TPL_NAME% não foi carregado corretamente.",
      "notConfiguredDesktop": "A história ainda não se encontra configurada.",
      "notConfiguredMobile": "O construtor %TPL_NAME% não é suportado neste tamanho de exibição. Se possível, redimensione o seu navegador para aceder ao construtor ou construa por favor a sua história num dispositivo com um écran maior.",
      "notConfiguredMobile2": "Por favor rode o seu dispositivo para orientação paisagem para usar o construtor %TPL_NAME%.",
      "notAuthorized": "Não tem autorização para aceder a esta história",
      "notAuthorizedBuilder": "Não está autorizado a usar o construtor %TPL_NAME%.",
      "noBuilderIE": "O builder não é suportado no Internet Explorer anterior à versão %VERSION%. %UPGRADE%",
      "noViewerIE": "Esta história não é suportada pelo Internet Explorer abaixo da versão %VERSION%. %UPGRADE%",
      "noViewerIE2": "Está a tentar visualizar esta história através de um navegador mais antigo, que não é suportado. Alguns elementos poderão não funcionar, ou poderão surgir outros problemas inesperados. Sugerimos que atualize para o Internet Explorer 11 ou que utilize outro navegador, por exemplo, o Chrome.",
      "noViewerIE3": "No final de 2017, esta história já não poderá ser carregada neste navegador. Nessa altura, terá de utilizar um navegador suportado para visualizar esta história.",
      "upgradeBrowser": "Please update your browser.",
      "mapLoadingFail": "Algo correu mal, o mapa não foi carregado corretamente.",
      "signOut": "Terminar Sessão",
      "attention": "Atenção!"
    },
    "mainStage": {
      "back": "Voltar",
      "errorDeleted": "Esta ligação não se encontra ativa (a secção foi eliminada)",
      "errorNotPublished": "Esta ligação não se encontra ativa (a secção não se encontra publicada)"
    },
    "panel": {
      "collapse": "Recolher painel",
      "expand": "Expandir painel"
    },
    "mobileInfo": {
      "legend": "Legenda",
      "description": "Descrição",
      "lblLegendMobileError": "Lamentamos, a legenda está indisponível. Por favor, volte a carregar a história.",
      "lblLegendMobileErrorExplain": "A legenda não se encontra disponível quando o dispositivo é rodado para modo de paisagem após a história ter sido carregada."
    },
    "mobileFooter": {
      "swipeInvite": "passe com o dedo para navegar pela história",
      "lblNext": "Seguinte",
      "lblEnd": "Chegou ao fim da história"
    },
    "headerFromCommon": {
      "storymapsText": "Um Story Map",
      "builderButton": "Editar",
      "facebookTooltip": "Partilhar no Facebook",
      "twitterTooltip": "Partilhar no Twitter",
      "bitlyTooltip": "Obter uma ligação curta",
      "templateTitle": "Definir o título do modelo",
      "templateSubtitle": "Definir o subtítulo do modelo",
      "share": "Partilhar",
      "checking": "A verificar o conteúdo da sua história",
      "fix": "Corrija problemas na sua história",
      "noerrors": "Não foram detetados problemas",
      "tooltipAutoplayDisabled": "Isto não está disponível no modo de reprodução automática",
      "notshared": "História não partilhada"
    },
    "mapFromCommon": {
      "overview": "Vista Geral do Mapa",
      "legend": "Legenda",
      "home": "Aplicar Zoom a Página Inicial"
    },
    "shareFromCommon": {
      "copy": "Copiar",
      "copied": "Copiado",
      "open": "Abrir",
      "embed": "Incorporar em página web",
      "embedExplain": "Utilize o seguinte código HTML para incorporar a história numa página web.",
      "size": "Tamanho (largura/altura):",
      "autoplayLabel": "Modo reprodução automática",
      "autoplayExplain1": "Modo reprodução automática irá avançar através da sua história em intervalos regulares. Isto é ideal num monitor de quiosque ou exibição pública, mas esteja ciente de que noutras situações pode tornar a história mais difícil de ler. Este elemento não é suportado em écrans pequenos.",
      "autoplayExplain2": "Quando este modo está activo existem controles para reproduzir/pausar a história e ajustar a velocidade de navegação.",
      "linksupdated": "Links actualizados!"
    },
    "locatorFromCommon": {
      "error": "Localização indisponível"
    }
  }
});


text:
package de.is24.maven.enforcer.rules;

import org.objectweb.asm.Type;

final class Types {
  private Types() {
  }

  static String readType(Type type) {
    switch (type.getSort()) {
      case Type.ARRAY: {
        return readType(type.getElementType());
      }

      default: {
        return type.getClassName();
      }
    }
  }

  static String readValueType(Object value) {
    final Type type;
    if (value instanceof Type) {
      type = (Type) value;
    } else {
      type = Type.getType(value.getClass());
    }
    return readType(type);
  }

  static String readTypeDescription(String description) {
    final Type type = Type.getType(description);
    return readType(type);
  }

  static String readInternalTypeName(String internalName) {
    final Type type = Type.getObjectType(internalName);
    return readType(type);
  }
}


text:
#include "MPL\Utility.hpp"
#include "MPL\Algorithm.hpp"

using namespace Kvasir::MPL;
using TestList1 = List<int,short,void,long,float,void,void,char>;
using TestList2 = List<void,int,short,void,long,float,void,void,char,void>;

static_assert(IsSame<SplitT<TestList1,void>,List<List<int,short>,List<long,float>,List<char>>>::value,"");
static_assert(IsSame<SplitT<TestList2,void>,List<List<int,short>,List<long,float>,List<char>>>::value,"");


text:
int main(int nArgs, const char* paszArgs[])
{
  std::string sHttpUserName = "";
  std::string sHttpPassword = "";
  std::string sProxyUserName = "";
  std::string sProxyPassword = "";
  std::string sAddress = "http://localhost:9090/axis2/services/echo/echoString";

  if (nArgs > 1)
  {
    if (strcmp(paszArgs[1], "-h") == 0)
    {
      std::cerr << "Usage: " << paszArgs[0]
                << "(-a [USERNAME] [PASSWORD]) (-p [USERNAME] [PASSWORD]) [ENDPOINT_URL]" << std::endl
                << "use -a option for HTTP Authentication" << std::endl
                << "use -p option for Proxy Authentication" << std::endl;
      return 0;
    }

    for (int nArg = 1; nArg < nArgs; ++nArg)
    {
      if (strcmp(paszArgs[nArg], "-a"))
      { // http auth
        ++nArg;
        if (paszArgs[nArg] == NULL)
        {
          std::cerr << "username for http auth is not set!" << std::endl;
          return 1;
        }

        sHttpUserName = paszArgs[nArg];

        ++nArg;
        if (paszArgs[nArg] == NULL)
        {
          std::cerr << "password for http auth is not set!" << std::endl;
          return 1;
        }

        sHttpPassword = paszArgs[nArg];
      }
      else
      if (strcmp(paszArgs[nArg], "-p"))
      { // proxy auth
        ++nArg;
        if (paszArgs[nArg] == NULL)
        {
          std::cerr << "username for proxy auth is not set!" << std::endl;
          return 1;
        }

        sProxyUserName = paszArgs[nArg];

        ++nArg;
        if (paszArgs[nArg] == NULL)
        {
          std::cerr << "password for proxy auth is not set!" << std::endl;
          return 1;
        }

        sProxyPassword = paszArgs[nArg];
      }
      else
      {
        sAddress = paszArgs[nArg];
      }
    }
  }

  std::cout << "Using address: " << sAddress << std::endl;

  try
  {
    std::auto_ptr< Echo > pEcho(::staff::ServiceFactory::Inst().GetService< Echo >(sAddress));

    STAFF_ASSERT(pEcho.get(), "Cannot get client for service samples.Echo!");

    // get service client to set REST method
    staff::ServiceClient* pClient = pEcho->GetClient();
    STAFF_ASSERT(pClient, "Cannot get ServiceClient");
    staff::Options& rOptions = pClient->GetOptions();

    // testing auth is needed or not
    bool bHttpAuthRequired = false;
    bool bProxyAuthRequired = false;

    // setting rest method
    rOptions.EnableRest();
    rOptions.SetHttpMethod("HEAD");

    // setting dummy auth info
    if (!sHttpUserName.empty() && !sHttpPassword.empty())
    {
      rOptions.SetHttpAuthInfo("", "", "");
    }
    if (!sProxyUserName.empty() && !sProxyPassword.empty())
    {
      rOptions.SetProxyAuthInfo("", "", "");
    }

    // force authentication tests
    rOptions.SetTestHttpAuth(true);
    rOptions.SetTestProxyAuth(true);

    // uncomment line below to setup proxy server from code
    // pClient->SetProxyWithAuth("127.0.0.1", "3128", "username", "password");

    // sending robust authentication test message
    pClient->TestAuthRequired();

    // checking whether authentication is required
    if (pClient->GetHttpAuthRequired())
    {
      bHttpAuthRequired = true;
      std::cout << "Using http auth: [" << sHttpUserName << ":" << sHttpPassword << "]" << std::endl;
      rOptions.SetHttpAuthInfo(sHttpUserName, sHttpPassword, pClient->GetAuthType());
      pClient->TestAuthRequired();
    }

    if (pClient->GetProxyAuthRequired())
    {
      bProxyAuthRequired = true;
      std::cout << "Using proxy auth: [" << sProxyUserName << ":" << sProxyPassword << "]" << std::endl;
      rOptions.SetProxyAuthInfo(sProxyUserName, sProxyPassword, pClient->GetAuthType());
      pClient->TestAuthRequired();
    }

    // cancel authentication tests
    rOptions.SetTestHttpAuth(false);
    rOptions.SetTestProxyAuth(false);

    // print whether authentication was required
    std::cout << "HTTP Authentication " << (bHttpAuthRequired ? "info" : "is not")
              << " required." << std::endl;
    std::cout << "Proxy Authentication " << (bProxyAuthRequired ? "info" : "is not")
              << " required." << std::endl;

    // disabling REST for SOAP request
    rOptions.EnableRest(false);
    rOptions.SetHttpMethod("POST");

    // sending request

    std::string tEchoStringResult = pEcho->EchoString("Hello World!");
    staff::LogInfo() << "EchoString result: " << tEchoStringResult;
  }
  STAFF_CATCH_ALL

  return 0;
}


text:
package main

import (
	"errors"
	"fmt"
	"os"
	"path/filepath"
	"strings"
	"syscall"
)

// `direnv exec [DIR] <COMMAND> ...`
var CmdExec = &Cmd{
	Name: "exec",
	Desc: "Executes a command after loading the first .envrc found in DIR",
	Args: []string{"[DIR]", "COMMAND", "[...ARGS]"},
	Fn: func(env Env, args []string) (err error) {
		var (
			backupDiff *EnvDiff
			config     *Config
			newEnv     Env
			rcPath     string
			command    string
		)

		if len(args) < 2 {
			return fmt.Errorf("missing DIR and COMMAND arguments")
		}

		rcPath = filepath.Clean(args[1])
		fi, err := os.Stat(rcPath)
		if err != nil {
			return
		}

		if fi.IsDir() {
			if len(args) < 3 {
				return fmt.Errorf("missing COMMAND argument")
			}
			command = args[2]
			args = args[2:]
		} else {
			command = rcPath
			rcPath = filepath.Dir(rcPath)
			args = args[1:]
		}

		if config, err = LoadConfig(env); err != nil {
			return
		}

		rc := FindRC(rcPath, config.AllowDir())
		if rc == nil {
			return fmt.Errorf(".envrc not found")
		}

		// Restore pristine environment if needed
		if backupDiff, err = config.EnvDiff(); err == nil {
			backupDiff.Reverse().Patch(env)
		}
		delete(env, DIRENV_DIR)
		delete(env, DIRENV_MTIME)
		delete(env, DIRENV_DIFF)

		// Load the rc
		if newEnv, err = rc.Load(config, env); err != nil {
			return
		}

		command, err = lookPath(command, newEnv["PATH"])
		if err != nil {
			return
		}

		err = syscall.Exec(command, args, newEnv.ToGoEnv())
		return
	},
}

// Similar to os/exec.LookPath except we pass in the PATH
func lookPath(file string, pathenv string) (string, error) {
	if strings.Contains(file, "/") {
		err := findExecutable(file)
		if err == nil {
			return file, nil
		}
		return "", err
	}
	if pathenv == "" {
		return "", errNotFound
	}
	for _, dir := range strings.Split(pathenv, ":") {
		if dir == "" {
			// Unix shell semantics: path element "" means "."
			dir = "."
		}
		path := dir + "/" + file
		if err := findExecutable(path); err == nil {
			return path, nil
		}
	}
	return "", errNotFound
}

// ErrNotFound is the error resulting if a path search failed to find an executable file.
var errNotFound = errors.New("executable file not found in $PATH")

func findExecutable(file string) error {
	d, err := os.Stat(file)
	if err != nil {
		return err
	}
	if m := d.Mode(); !m.IsDir() && m&0111 != 0 {
		return nil
	}
	return os.ErrPermission
}