text:
package microsoft.exchange.webservices.data.property.complex;

import microsoft.exchange.webservices.data.core.EwsServiceXmlReader;
import microsoft.exchange.webservices.data.core.EwsServiceXmlWriter;
import microsoft.exchange.webservices.data.core.EwsUtilities;
import microsoft.exchange.webservices.data.core.XmlElementNames;
import microsoft.exchange.webservices.data.core.enumeration.property.MailboxType;
import microsoft.exchange.webservices.data.core.enumeration.misc.XmlNamespace;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Represents an e-mail address.
 */
public class EmailAddress extends ComplexProperty implements ISearchStringProvider {

  private static final Log LOG = LogFactory.getLog(EmailAddress.class);

  // SMTP routing type.
  /**
   * The Constant SmtpRoutingType.
   */
  protected final static String SmtpRoutingType = "SMTP";

  // / Display name.
  /**
   * The name.
   */
  private String name;

  // / Email address.
  /**
   * The address.
   */
  private String address;

  // / Routing type.
  /**
   * The routing type.
   */
  private String routingType;

  // / Mailbox type.
  /**
   * The mailbox type.
   */
  private MailboxType mailboxType;

  // / ItemId - Contact or PDL.
  /**
   * The id.
   */
  private ItemId id;

  /**
   * Initializes a new instance.
   */
  public EmailAddress() {
    super();
  }

  /**
   * Initializes a new instance.
   *
   * @param smtpAddress The SMTP address used to initialize the EmailAddress.
   */
  public EmailAddress(String smtpAddress) {
    this();
    this.address = smtpAddress;
  }

  /**
   * Initializes a new instance.
   *
   * @param name        The name used to initialize the EmailAddress.
   * @param smtpAddress The SMTP address used to initialize the EmailAddress.
   */
  public EmailAddress(String name, String smtpAddress) {
    this(smtpAddress);
    this.name = name;
  }

  /**
   * Initializes a new instance.
   *
   * @param name        The name used to initialize the EmailAddress.
   * @param address     The address used to initialize the EmailAddress.
   * @param routingType The routing type used to initialize the EmailAddress.
   */
  public EmailAddress(String name, String address, String routingType) {
    this(name, address);
    this.routingType = routingType;
  }

  /**
   * Initializes a new instance.
   *
   * @param name        The name used to initialize the EmailAddress.
   * @param address     The address used to initialize the EmailAddress.
   * @param routingType The routing type used to initialize the EmailAddress.
   * @param mailboxType Mailbox type of the participant.
   */
  protected EmailAddress(String name, String address, String routingType,
      MailboxType mailboxType) {
    this(name, address, routingType);
    this.mailboxType = mailboxType;
  }

  /**
   * Initializes a new instance.
   *
   * @param name        The name used to initialize the EmailAddress.
   * @param address     The address used to initialize the EmailAddress.
   * @param routingType The routing type used to initialize the EmailAddress.
   * @param mailboxType Mailbox type of the participant.
   * @param id          ItemId of a Contact or PDL.
   */
  protected EmailAddress(String name, String address, String routingType,
      MailboxType mailboxType, ItemId id) {
    this(name, address, routingType);
    this.mailboxType = mailboxType;
    this.id = id;
  }

  /**
   * Initializes a new instance from another EmailAddress instance.
   *
   * @param mailbox EMailAddress instance to copy.
   * @throws Exception the exception
   */
  protected EmailAddress(EmailAddress mailbox) throws Exception {
    this();
    EwsUtilities.validateParam(mailbox, "mailbox");
    this.name = mailbox.getName();
    this.address = mailbox.getAddress();
    this.routingType = mailbox.getRoutingType();
    this.mailboxType = mailbox.getMailboxType();
    this.setId(mailbox.getId());

  }

  /**
   * Gets the name associated with the e-mail address.
   *
   * @return the name
   */
  public String getName() {
    return name;
  }

  /**
   * Sets the name associated with the e-mail address.
   *
   * @param name the new name
   */
  public void setName(String name) {
    if (this.canSetFieldValue(this.name, name)) {
      this.name = name;
      this.changed();
    }
  }

  /**
   * Gets the actual address associated with the e-mail address.
   *
   * @return address associated with the e-mail address.
   */
  public String getAddress() {
    return address;
  }

  /**
   * Sets the actual address associated with the e-mail address. The type of
   * the Address property must match the specified routing type. If
   * RoutingType is not set, Address is assumed to be an SMTP address.
   *
   * @param address address associated with the e-mail address.
   */
  public void setAddress(String address) {

    if (this.canSetFieldValue(this.address, address)) {
      this.address = address;
      this.changed();
    }

  }

  /**
   * Gets the routing type associated with the e-mail address.
   *
   * @return the routing type
   */
  public String getRoutingType() {
    return routingType;
  }

  /**
   * Sets the routing type associated with the e-mail address. If RoutingType
   * is not set, Address is assumed to be an SMTP address.
   *
   * @param routingType routing type associated with the e-mail address.
   */
  public void setRoutingType(String routingType) {
    if (this.canSetFieldValue(this.routingType, routingType)) {
      this.routingType = routingType;
      this.changed();
    }
  }

  /**
   * Gets the type of the e-mail address.
   *
   * @return type of the e-mail address.
   */
  public MailboxType getMailboxType() {
    return mailboxType;
  }

  /**
   * Sets the type of the e-mail address.
   *
   * @param mailboxType the new mailbox type
   */
  public void setMailboxType(MailboxType mailboxType) {
    if (this.canSetFieldValue(this.mailboxType, mailboxType)) {
      this.mailboxType = mailboxType;
      this.changed();
    }
  }

  /**
   * Gets the Id of the contact the e-mail address represents.
   *
   * @return the id
   */
  public ItemId getId() {
    return id;
  }

  /**
   * Sets the Id of the contact the e-mail address represents. When Id is
   * specified, Address should be set to null.
   *
   * @param id the new id
   */
  public void setId(ItemId id) {

    if (this.canSetFieldValue(this.id, id)) {
      this.id = id;
      this.changed();
    }
  }

  /**
   * Defines an implicit conversion between a string representing an SMTP
   * address and EmailAddress.
   *
   * @param smtpAddress The SMTP address to convert to EmailAddress.
   * @return An EmailAddress initialized with the specified SMTP address.
   */
  public static EmailAddress getEmailAddressFromString(String smtpAddress) {
    return new EmailAddress(smtpAddress);
  }

  /**
   * Try read element from xml.
   *
   * @param reader accepts EwsServiceXmlReader
   * @return true
   * @throws Exception throws Exception
   */
  public boolean tryReadElementFromXml(EwsServiceXmlReader reader)
      throws Exception {
    try {
      if (reader.getLocalName().equals(XmlElementNames.Name)) {
        this.name = reader.readElementValue();
        return true;
      } else if (reader.getLocalName().equals(
          XmlElementNames.EmailAddress)) {
        this.address = reader.readElementValue();
        return true;
      } else if (reader.getLocalName()
          .equals(XmlElementNames.RoutingType)) {
        this.routingType = reader.readElementValue();
        return true;
      } else if (reader.getLocalName()
          .equals(XmlElementNames.MailboxType)) {
        this.mailboxType = reader.readElementValue(MailboxType.class);
        return true;
      } else if (reader.getLocalName().equals(XmlElementNames.ItemId)) {
        this.id = new ItemId();
        this.id.loadFromXml(reader, reader.getLocalName());
        return true;
      } else {
        return false;
      }
    } catch (Exception e) {
      LOG.error(e);
      return false;
    }
  }

  /**
   * Writes elements to XML.
   *
   * @param writer The writer.
   * @throws Exception the exception
   */
  @Override
  public void writeElementsToXml(EwsServiceXmlWriter writer)
      throws Exception {
    writer.writeElementValue(XmlNamespace.Types, XmlElementNames.Name, this
        .getName());
    writer.writeElementValue(XmlNamespace.Types,
        XmlElementNames.EmailAddress, this.getAddress());
    writer.writeElementValue(XmlNamespace.Types,
        XmlElementNames.RoutingType, this.getRoutingType());
    writer.writeElementValue(XmlNamespace.Types,
        XmlElementNames.MailboxType, this.getMailboxType());

    if (this.getId() != null) {
      this.getId().writeToXml(writer, XmlElementNames.ItemId);
    }

  }

  /**
   * Get a string representation for using this instance in a search filter.
   *
   * @return String representation of instance.
   */
  @Override
  public String getSearchString() {
    return this.getAddress();
  }

  /**
   * Returns string that represents the current instance.
   *
   * @return String representation of instance.
   */
  @Override
  public String toString() {
    String addressPart;

    if (null == this.getAddress() || this.getAddress().isEmpty()) {
      return "";
    }

    if (null != this.getRoutingType() && this.getRoutingType().isEmpty()) {
      addressPart = this.getRoutingType() + ":" + this.getAddress();
    } else {
      addressPart = this.getAddress();
    }

    if (null != this.getName() && !this.getName().isEmpty()) {
      return this.getName() + " <" + addressPart + ">";
    } else {
      return addressPart;
    }
  }

  /**
   * Gets the routing type.
   *
   * @return SMTP Routing type
   */
  protected String getSmtpRoutingType() {
    return SmtpRoutingType;
  }

}


text:
import subprocess
from dataclasses import dataclass
from os import environ
from pathlib import Path
from warnings import warn
from knowledgerepr.ekgstore.neo4j_store import Neo4jExporter
from fire import Fire
import IPython
from main import init_system

run_cmd = subprocess.call

get_env = environ.get

class BaseAurumException(Exception):
    pass

class DataSourceNotConfigured(BaseAurumException):
    pass

class ModelNotFoundError(BaseAurumException):
    pass

@dataclass()
class CSVDataSource:
    name: str = 'NO NAME PROVIDED'
    _path: Path = Path.cwd()
    separator: str = ','

    @property
    def path(self):
        return self._path

    @path.setter
    def path(self, p):
        assert isinstance(p, Path) or isinstance(p, str)
        self._path = Path(p)

    def __dict__(self):
        return {
            'name': self.name,
            'type': 'csv',
            'config': {
                'path': str(self.path),
                'separator': self.separator
            }
        }

    def to_yml(self):
        return f"""api_version: 0
sources:
- name: "{self.name}"
  type: csv
  config:
    path: "{str(self.path)}"
    separator: '{self.separator}'"""

@dataclass()
class DBDataSource:
    name: str = ''
    host: str = ''
    _port: int = ''
    db_name: str = ''
    db_user: str = ''
    db_password: str = ''
    _type: str = ''

    @property
    def port(self):
        return self._port

    @port.setter
    def port(self, p):
        self._port = int(p)

    @property
    def type(self):
        return self._type

    @type.setter
    def type(self, s):
        self._type = s

    def __dict__(self):
        return {
            'name': self.name,
            'type': self.type,
            'config': {
                'db_server_ip': self.host,
                'db_server_port': self.port,
                'database_name': self.db_name,
                'db_username': self.db_user,
                'db_password': self.db_password
            }
        }

    def to_yml(self):
        return f"""api_version: 0
sources:
- name: "{self.name}"
  type: {self.type}
  config:
    db_server_ip: {self.host}
    db_server_port: {self.port}
    database_name: {self.db_name}
    db_username: {self.db_user}
    db_password: {self.db_password}"""

class AurumWrapper(object):
    """
    Class that acts as a bridge between the current Aurum source code and an higher-level APIs (e.g. CLI and Web).
    Relies heavily on filesystem CRUD interaction (e.g. relative paths) and thus should be removed once imports can be handled at the code level.
    Eventually the FS will need to be replaced with something like SQLite to store data sources, track profilings etc.
    """

    def __init__(self):
        self.aurum_src_home = Path(get_env('AURUM_SRC_HOME', Path.cwd()))
        self.ddprofiler_home = self.aurum_src_home.joinpath('ddprofiler')
        self.ddprofiler_run_sh = self.ddprofiler_home.joinpath('run.sh')
        self.aurum_home = Path(get_env('AURUM_HOME', Path.home().joinpath('.aurum')))
        try:
            self.aurum_home.mkdir(parents=True)
        except FileExistsError:
            pass

        self.sources_dir = self.aurum_home.joinpath('sources')
        try:
            self.sources_dir.mkdir(parents=True)
        except FileExistsError:
            pass

        self.models_dir = self.aurum_home.joinpath('models')
        try:
            self.models_dir.mkdir(parents=True)
        except FileExistsError:
            pass

    def _make_ds_path(self, ds_name):
        return self.sources_dir.joinpath(ds_name + '.yml')

    def _make_model_path(self, model_name):
        return self.models_dir.joinpath(model_name)

    @property
    def sources(self):
        return [f.name.replace('.yml', '') for f in self.sources_dir.iterdir()]

    @property
    def models(self):
        return [f.name for f in self.models_dir.iterdir()]

    def _make_csv_ds(self, name, fp, separator=','):
        return {
            'name': name,
            'type': 'csv',
            'config': {
                'path': fp,
                'separator': separator
            }
        }

    def _store_ds(self, ds):
        with open(self._make_ds_path(ds.name), 'w') as f:
            f.write(ds.to_yml())

class AurumCLI(AurumWrapper):

    def __init__(self):
        super().__init__()

    @property
    def sources(self):
        return super().sources

    def add_csv_data_source(self, name, path, sep=','):
        ds = CSVDataSource()
        ds.name = name
        ds.path = path
        ds.separator = sep

        super()._store_ds(ds)

    def add_db_data_source(self, name, db_type, host, port, db_name, username, password):
        # TODO check if `db_type` is supported

        ds = DBDataSource()
        ds.name = name
        ds.type = db_type
        ds.host = host
        ds.port = port
        ds.db_name = db_name
        ds.db_user = username
        ds.db_password = password

        super()._store_ds(ds)

    def profile(self, data_source_name):
        ds_fp = super()._make_ds_path(data_source_name)
        if not ds_fp.exists():
            raise DataSourceNotConfigured(f"Data Source {data_source_name} not configured!")
        profile_cmd = ['bash', self.ddprofiler_run_sh, '--sources', ds_fp]
        run_cmd(profile_cmd, cwd=self.ddprofiler_home)

    def build_model(self, name):
        model_dir_path = self._make_model_path(name)
        try:
            model_dir_path.mkdir(parents=True)
        except FileExistsError:
            warn(f'Model with the same name ({name}) already exists!')

        run_cmd(['python', 'networkbuildercoordinator.py', '--opath', model_dir_path])

    def export_model(self, model_name, to='neo4j', neo4j_host='localhost', neo4j_port=7687, neo4j_user='neo4j',
                     neo4j_pass='n304j'):
        supported_destionations = ['neo4j']

        if to not in supported_destionations:
            raise NotImplementedError(f"Model destination not supported. Only {supported_destionations} are supported")

        model_dir_path = self._make_model_path(model_name)

        # Check if model exists
        # TODO refactor to separate method
        if not model_dir_path.exists():
            available_models = '\n'.join(self.models)
            raise ModelNotFoundError(
                f"Model {model_name} not found!\nHere are the available ones:\n{available_models}")

        # Hacky way. The underlying `fieldnetwork.py:deserialize_network` should be changed
        model_path_str = model_dir_path.__str__() + '/'
        if to == 'neo4j':
            exporter = Neo4jExporter(host=neo4j_host, port=neo4j_port, user=neo4j_user, pwd=neo4j_pass)
        exporter.export(model_path_str)

    def clear_store(self):
        """
        γφ
        """
        from elasticsearch import Elasticsearch
        # TODO extract AURUM_ES_HOST
        es = Elasticsearch()
        es.indices.delete('profile')
        es.indices.delete('text')

    def show_source(self, soure_name):
        with open(self._make_ds_path(soure_name)) as f:
            print(f.read())

    def explore_model(self, model_name):
        """
        Initiates an interactive IPython session to run discovery queries.

        :param model_name:
        :return:
        """
        api, reporting = init_system(self._make_model_path(model_name).__str__() + '/', create_reporting=True)
        IPython.embed()

if __name__ == '__main__':
    aurum_cli = AurumCLI()
    Fire({
        'list-sources': aurum_cli.sources,
        'add-csv': aurum_cli.add_csv_data_source,
        'add-db': aurum_cli.add_db_data_source,
        'show-source': aurum_cli.show_source,
        'profile': aurum_cli.profile,
        'build-model': aurum_cli.build_model,
        'list-models': aurum_cli.models,
        'export-model': aurum_cli.export_model,
        'clear-store': aurum_cli.clear_store,
        'explore-model': aurum_cli.explore_model
    })

redpajama_set_name: RedPajamaGithub


text:
sap.ui.define([
	"sap/ui/test/Opa5"
], function (Opa5) {
    "use strict";

    return {
        /**
         * Assertion to check that there is a mdc chart visible on the screen.
         */
		iShouldSeeAChart: function() {
		//return Opa5.assert.ok(true);

			return this.waitFor({
				controlType: "sap.ui.mdc.Chart",
				check: function(aChart) {
					return aChart.length === 1;
				},
				success: function(aChart) {
					Opa5.assert.ok(aChart.length, 'MDC Chart is on the screen');
				},
				errorMessage: "No MDC Chart found"
			});
		},

        /**
         * Assertion to check that there is a legend visible on the screen for given mdc chart.
         * @param {string} sId Id of the chart to be checked for a visible legend
         */
		iShouldSeeALegend: function(sId) {

		},

        /**
         * Assertion to check that there is no legend visible on the screen for given mdc chart.
         * @param {string} sId Id of the chart to be checked for a visible legend
         */
		iShouldSeeNoLegend: function(sId) {

		},

        /**
         * Assertion to check that there is a chart type popover visible on the screen.
         */
		iShouldSeeAChartTypePopover: function() {

			return this.waitFor({
				controlType: "sap.m.Popover",
				success: function(aPopovers) {
					Opa5.assert.ok(aPopovers.length, "Dialogs were found");

					var oDialog = aPopovers.filter(function(oDialog){return (oDialog.getId().toLowerCase().includes("btncharttypepopover"));})[0];
					Opa5.assert.ok(oDialog, "Chart Type dialog is opened");
				},
				errorMessage: "No Dialogs found"
			});

		},

        /**
         * Assertion to check that there is chart visible with given chart type.
         * @param {string} sChartId Id of the chart to be checked for a chart type
         * @param {string} sChartType Chart type which should be selected for the given chart
         */
		iShouldSeeTheChartWithChartType: function(sChartId,  sChartType){

		},

        /**
         * Assertion to check that there is a chart with given drillstack visible.
         * @param {array} aCheckDrillStack Drillstack to check for
         * @param {string} sChartId Id of the mdc chart
         */
		 iShouldSeeTheDrillStack: function(aCheckDrillStack, sChartId) {

		},

        /**
         * Assertion to check that there is a drilldown popover visible.
         */
		iShouldSeeADrillDownPopover: function() {

			return this.waitFor({
				controlType: "sap.m.Popover",
				success: function(aPopovers) {
					Opa5.assert.ok(aPopovers.length, "Dialogs were found");

					var oDialog = aPopovers.filter(function(oDialog){return (oDialog.getId().includes("drilldownPopover"));})[0];
					Opa5.assert.ok(oDialog, "Drilldown dialog is opened");
				},
				errorMessage: "No Dialogs found"
			});

		},

		/**
         * Assertion to check that there is a drilldown popover visible.
         */
		iShouldSeeADetailsPopover: function() {
			return this.waitFor({
				controlType: "sap.m.Popover",
				success: function(aPopovers) {
					Opa5.assert.ok(aPopovers.length, "Dialogs were found");

					var oDialog = aPopovers.filter(function(oDialog){return (oDialog.getId().includes("selectionDetails"));})[0];
					Opa5.assert.ok(oDialog, "Details dialog is opened");
				},
				errorMessage: "No Dialogs found"
			});
		},
		iShouldSeeVisibleDimensionsInOrder: function(aOrderedDimensionNames, sId) {

		},
		iShouldSeeVisibleMeasuresInOrder: function(aOrderedMeasureNames, sId) {

		}

    };
});


text:
namespace utymap {
namespace builders {

/// Provides the way to use pool of meshes instead of
/// building them each time which might be expensive.
class MeshPool final {
  const std::size_t ThresholdSize = 1024 * 10 * 2;
 public:

  MeshPool() {}

  /// Disable copying to prevent accidental copy
  MeshPool(const MeshPool &) = delete;
  MeshPool &operator=(const MeshPool &) = delete;

  /// Gets small size mesh.
  utymap::math::Mesh getSmall(const std::string& name) {
    return getMesh(name, true);
  }

  /// Gets large size mesh.
  utymap::math::Mesh getLarge(const std::string& name) {
    return getMesh(name, false);
  }

  /// Returns mesh to pool.
  void release(utymap::math::Mesh&& mesh) {
    mesh.clear();
    mesh.name.clear();
    std::lock_guard<std::mutex> lock(lock_);
    pool_.emplace(mesh.vertices.capacity(), std::move(mesh));
  }

 private:
  utymap::math::Mesh getMesh(const std::string &name, bool isLower) {
    std::lock_guard<std::mutex> lock(lock_);
    auto it = isLower
      ? pool_.lower_bound(0)
      : pool_.upper_bound(ThresholdSize);
    if (it == pool_.end())
      return utymap::math::Mesh(name);

    auto mesh = std::move(it->second);
    mesh.name = name;
    pool_.erase(it);
    return mesh;
  }

  std::map<std::size_t, utymap::math::Mesh> pool_;
  std::mutex lock_;
};

}
}

#endif // BUILDERS_MESHPOOL_HPP_DEFINED


text:
using System;
using System.Threading;
using System.Threading.Tasks;
using Contracts;
using Orleans;

namespace PingClient
{
    class PingClient : IPingClient
    {
        private readonly bool _wait;

        private IPingWorker _pinger;
        private Timer _timer;

        public PingClient(bool wait)
        {
            _wait = wait;
        }

        //private IPingWorker _pinger => GrainClient.GrainFactory.GetGrain<IPingWorker>("mario");

        private async Task Execute(Func<Task> action)
        {
            try
            {
                await action();
            }
            catch (Exception exx)
            {
                var color = Console.ForegroundColor;
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(exx.Message);
                Console.ForegroundColor = color;
            }
        }

        public async Task Init()
        {
            if (_wait)
            {
                Console.WriteLine("Waiting for Orleans Silo to start. Press Enter to proceed...");
                Console.ReadLine();
            }

            GrainClient.Initialize();

            _pinger = GrainClient.GrainFactory.GetGrain<IPingWorker>("mario");
            await _pinger.Join(await GrainClient.GrainFactory.CreateObjectReference<IPingClient>(this));

            _timer = new System.Threading.Timer(async (data) =>
            {
                Console.Write("Ping");
                await Execute(async () => await _pinger.Ping(DateTime.Now.Ticks.ToString()));
            }, null, 2000, 2000);
        }

        public void Response(string data)
        {
            Console.Write("Pong : " + data);
        }

        public Task Stop()
        {
            return Execute(
                async () =>
                {
                    await _pinger?.Leave(await GrainClient.GrainFactory.CreateObjectReference<IPingClient>(this));
                });
        }
    }
}


text:
if (typeof module !== 'undefined' && module.exports) {
    var assert = require( "assert" );
    var W = require( "../build/W.node.js" );
}

describe( "partial", function () {

    it( 'should be a function', function () {
       assert.equal( typeof W.partial, 'function' );
    });

    it( 'should return a function', function () {
       assert.equal( typeof W.partial( W.add, 0 ), 'function' );
    });

    it( 'should return the correct result with 1 argument', function () {
        assert.equal( W.partial( W.add, 2 )( 2 ), 4 );
    });

    it( 'should return the correct result with 4 argument', function () {
        assert.equal( W.partial ( W.add, 2, 10, 1, 1 )( 2, 1000 ), 1016 );
    });

    it( 'should maintain array when array passed as argument', function () {

        function returnArgs () { return W.toArray( arguments ); }
        var args = W.partial( returnArgs, 1, 2 )( 3, [ 4, 5 ] );
        assert.equal( typeof args[ 3 ], 'object' );
    });

});


text:
package com.phpsysinfo.psidesktop.business.utils;

import java.io.InputStream;
import java.net.ProxySelector;
import java.net.URI;
import java.util.HashMap;

import org.apache.http.HttpEntity;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.SystemDefaultRoutePlanner;

public class HTTPSimpleQuery {

  public class DataAccessException extends Exception{

    /**
     *
     */
    public DataAccessException() {
      super();
    }

    /**
     * @param message
     * @param cause
     */
    public DataAccessException(String message, Throwable cause) {
      super(message, cause);
    }

    /**
     * @param message
     */
    public DataAccessException(String message) {
      super(message);
    }

    /**
     * @param cause
     */
    public DataAccessException(Throwable cause) {
      super(cause);
    }

  }

  private final String url;

  private HashMap<String, String> params;

  private int timeout = 20000;

  private String username = null;
  private char[] password = null;

  public HTTPSimpleQuery(final String url)  {

    this.url = url;
  }

  /**
   * Add a parameter to the request.
   *
   * @param name the name of the parameter
   * @param value the value of the parameter
   * @return HTTPSimpleQuery
   */
  public HTTPSimpleQuery withParameter(final String name, final String value) {

    if (params == null) {

      params = new HashMap<String, String>();
    }

    params.put(name, value);

    return this;
  }

  public HTTPSimpleQuery withBasicCredentials(String anUsername, char[] aPassword) {
    this.username = anUsername;
    this.password = aPassword;
    return this;
  }

  /**
   * Sets the timeout of the request.
   *
   * @param aTimeout the timeout in ms
   * @return HTTPSimpleQuery
   */
  public HTTPSimpleQuery withTimeout(final int aTimeout) {

    timeout = aTimeout;

    return this;
  }

  /**
   * Launch the request.
   *
   * @return the result  of the request.
   * @throws DataAccessException if any exception occurs.
   */
  public String execute() throws Exception {

    /*
    final HttpParams httpParams = new BasicHttpParams();

    HttpConnectionParams.setConnectionTimeout(httpParams, timeout);
    HttpConnectionParams.setSoTimeout(httpParams, timeout);
    */

    URIBuilder uriBuilder = new URIBuilder(url);

    if ((params != null) && !(params.size() == 0)) {

      for (String key : params.keySet()) {
        uriBuilder.addParameter(key, params.get(key));
      }
    }

    URI uri = uriBuilder.build();

    System.out.println("Calling > " + uri);

    HttpGet request = new HttpGet(uri);

    RequestConfig config = RequestConfig.custom()
        .setSocketTimeout(timeout)
        .setConnectTimeout(timeout)
        .build();

    SystemDefaultRoutePlanner routePlanner = new SystemDefaultRoutePlanner(ProxySelector.getDefault());

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    if (username != null) {
      credsProvider.setCredentials(
          new AuthScope(uri.getHost(), AuthScope.ANY_PORT),
          new UsernamePasswordCredentials(username, new String(password)));
    }

    final CloseableHttpClient  client = HttpClients.custom()
        .setDefaultRequestConfig(config)
        .setRoutePlanner(routePlanner)
        .setDefaultCredentialsProvider(credsProvider)
        .build();

    System.out.println("Client configuration complete");

    if (username != null) {
      final StringBuilder sb = new StringBuilder();
      sb.append(username).append(":").append(password);
      request.setHeader("Authorization", "Basic " + CryptUtils.base64Encode(sb.toString().getBytes()));
    }

    System.out.println("Before execute");
    CloseableHttpResponse response = client.execute(request);
    System.out.println("After execute");

    System.out.println("Reading data");
    final StringBuilder res = new StringBuilder();

    try {
      final HttpEntity entity = response.getEntity();
      if (entity != null) {

        final InputStream instream = entity.getContent();
        int l;
        final byte[] tmp = new byte[2048];

        while ((l = instream.read(tmp)) != -1) {
          res.append(new String(tmp, 0, l));
        }
      }
    }
    finally {
      response.close();
      client.close();
    }

    System.out.println("Data read > " + res.length());

    return res.toString();
  }
}


text:
/** \file os/posix/code/os_semaphore.c
 *  \brief Semaphore - os_semaphore
 *
 * Implements os_semaphore for POSIX
 */

#include <semaphore.h>

os_result os_sem_init (sem_t * sem, os_uint32 value)
{
  return (sem_init (sem, 0, value) == 0) ? os_resultSuccess : os_resultFail;
}

os_result os_sem_destroy (sem_t *sem)
{
  return (sem_destroy (sem) == 0) ? os_resultSuccess : os_resultFail;
}

os_result os_sem_post (sem_t *sem)
{
  return (sem_post (sem) == 0) ? os_resultSuccess : os_resultFail;
}

os_result os_sem_wait (sem_t *sem)
{
  return (sem_wait (sem) == 0) ? os_resultSuccess : os_resultFail;
}


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

import java.util.Map;

import org.flowable.cmmn.api.CmmnRuntimeService;
import org.flowable.cmmn.api.runtime.CaseInstance;
import org.flowable.cmmn.api.runtime.CaseInstanceBuilder;
import org.flowable.cmmn.api.runtime.CaseInstanceQuery;
import org.flowable.cmmn.api.runtime.MilestoneInstanceQuery;
import org.flowable.cmmn.api.runtime.PlanItemInstanceQuery;
import org.flowable.cmmn.engine.impl.ServiceImpl;
import org.flowable.cmmn.engine.impl.cmd.EvaluateCriteriaCmd;
import org.flowable.cmmn.engine.impl.cmd.GetLocalVariableCmd;
import org.flowable.cmmn.engine.impl.cmd.GetLocalVariablesCmd;
import org.flowable.cmmn.engine.impl.cmd.GetVariableCmd;
import org.flowable.cmmn.engine.impl.cmd.GetVariablesCmd;
import org.flowable.cmmn.engine.impl.cmd.RemoveLocalVariableCmd;
import org.flowable.cmmn.engine.impl.cmd.RemoveVariableCmd;
import org.flowable.cmmn.engine.impl.cmd.SetLocalVariablesCmd;
import org.flowable.cmmn.engine.impl.cmd.SetVariablesCmd;
import org.flowable.cmmn.engine.impl.cmd.StartCaseInstanceCmd;
import org.flowable.cmmn.engine.impl.cmd.TerminateCaseInstanceCmd;
import org.flowable.cmmn.engine.impl.cmd.TriggerPlanItemInstanceCmd;

/**
 * @author Joram Barrez
 */
public class CmmnRuntimeServiceImpl extends ServiceImpl implements CmmnRuntimeService {

    @Override
    public CaseInstanceBuilder createCaseInstanceBuilder() {
        return new CaseInstanceBuilderImpl(this);
    }

    public CaseInstance startCaseInstance(CaseInstanceBuilder caseInstanceBuilder) {
        return commandExecutor.execute(new StartCaseInstanceCmd(caseInstanceBuilder));
    }

    @Override public void triggerPlanItemInstance(String planItemInstanceId) {
        commandExecutor.execute(new TriggerPlanItemInstanceCmd(planItemInstanceId));
    }

    @Override
    public void terminateCaseInstance(String caseInstanceId) {
        commandExecutor.execute(new TerminateCaseInstanceCmd(caseInstanceId));
    }

    @Override
    public void evaluateCriteria(String caseInstanceId) {
        commandExecutor.execute(new EvaluateCriteriaCmd(caseInstanceId));
    }

    @Override
    public Map<String, Object> getVariables(String caseInstanceId) {
        return commandExecutor.execute(new GetVariablesCmd(caseInstanceId));
    }

    @Override
    public Map<String, Object> getLocalVariables(String planItemInstanceId) {
        return commandExecutor.execute(new GetLocalVariablesCmd(planItemInstanceId));
    }

    @Override
    public Object getVariable(String caseInstanceId, String variableName) {
        return commandExecutor.execute(new GetVariableCmd(caseInstanceId, variableName));
    }

    @Override
    public Object getLocalVariable(String planItemInstanceId, String variableName) {
        return commandExecutor.execute(new GetLocalVariableCmd(planItemInstanceId, variableName));
    }

    @Override
    public void setVariables(String caseInstanceId, Map<String, Object> variables) {
        commandExecutor.execute(new SetVariablesCmd(caseInstanceId, variables));
    }

    @Override
    public void setLocalVariables(String planItemInstanceId, Map<String, Object> variables) {
        commandExecutor.execute(new SetLocalVariablesCmd(planItemInstanceId, variables));
    }

    @Override
    public void removeVariable(String caseInstanceId, String variableName) {
        commandExecutor.execute(new RemoveVariableCmd(caseInstanceId, variableName));
    }

    @Override
    public void removeLocalVariable(String planItemInstanceId, String variableName) {
        commandExecutor.execute(new RemoveLocalVariableCmd(planItemInstanceId, variableName));
    }

    @Override
    public CaseInstanceQuery createCaseInstanceQuery() {
        return cmmnEngineConfiguration.getCaseInstanceEntityManager().createCaseInstanceQuery();
    }

    @Override
    public PlanItemInstanceQuery createPlanItemInstanceQuery() {
        return cmmnEngineConfiguration.getPlanItemInstanceEntityManager().createPlanItemInstanceQuery();
    }

    @Override
    public MilestoneInstanceQuery createMilestoneInstanceQuery() {
        return cmmnEngineConfiguration.getMilestoneInstanceEntityManager().createMilestoneInstanceQuery();
    }

}


text:
class Post < ActiveRecord::Base
  belongs_to :user
  has_many :comments, :dependent => :destroy
  has_many :posts_tags
  has_many :tags, :through => :posts_tags

  before_validation :generate_permalink

  validate :check_permalink
  validates_uniqueness_of :permalink
  validates_presence_of :title_draft, :date

  scope :by_date_descending, -> { order(date: :desc) }
  scope :by_last_published, -> { order(last_published_at: :desc) }
  scope :published, -> { where('version IS NOT NULL') }
  scope :unpublished, -> { where('version IS NULL') }
  scope :outdated, -> { where('version IS NOT NULL AND version != version_draft') }
  scope :current, -> { where('version IS NOT NULL AND version = version_draft') }
  scope :for_author, ->(user) { where('user_id = ?', user.id) }
  scope :with_tag, ->(tag) { joins('JOIN posts_tags pt ON pt.post_id = posts.id').where('pt.tag_id = ?', tag.id) }
  scope :since, ->(date) { where('last_published_at > ?', date) }

  INVALID_PERMALINKS = ['admin', 'register', 'login', 'logout', 'posts', 'comments', 'tag']

  def content_draft_html
    markdown(content_draft.gsub('~', ' '))
  end

  def content_html
    markdown(content.gsub('~', ' '))
  end

  def content_short_html(more_label=nil)
    return nil if self.content.nil?
    return content_html unless content_shortened?
    markdown(self.content.split('~')[0] + "#{more_label}")
  end

  def content_shortened?
    !self.content.nil? and self.content.include?('~')
  end

  def status
    return :unpublished if self.version.blank?
    return :outdated if self.version_draft != self.version
    :current
  end

  def published?
    !version.blank?
  end

  def permalink_url
    self.published? ? "/#{self.permalink}" : nil
  end

  def full_permalink_url
    permalink_url ? "http://#{File.join(APP_CONFIG.domain, permalink_url)}" : nil
  end

  def preview_url
    "/#{self.permalink}/preview"
  end

  def avatar_url(default_host=nil, default_port=nil)
    Avatar.avatar_url(self.user.email, default_host, default_port)
  end

  def publish!(quiet=false)
    self.title = self.title_draft
    self.content = self.content_draft
    self.version = self.version_draft
    now = Time.now
    self.first_published_at = now if self.first_published_at.nil?
    self.last_published_at = now if self.last_published_at.nil? or !quiet
    true
  end

  def change_to_bump_version?
    self.changed? and (self.content_draft_changed? or self.title_draft_changed?)
  end

  private
    def generate_permalink
      return unless self.permalink.blank?
      return if self.date.blank? or self.title_draft.blank?
      self.permalink = "#{self.date.strftime('%Y-%m-%d')}-#{title_draft.downcase.gsub(/[^A-Za-z0-9 \-]/, '').gsub(/( |-)+/, '-')}"
    end

    def check_permalink
      unless self.permalink.match(/^([a-zA-Z0-9]|-)*$/)
        errors.add(:permalink, "can only contain alphanumerics and dashes")
      else
        errors.add(:permalink, "can not be the same as a system path") if INVALID_PERMALINKS.include?(self.permalink.downcase)
      end
    end

    def markdown(s)
      BlueCloth.new(keep_linebreaks(s)).to_html.html_safe
    end

    def keep_linebreaks(s)
      s.gsub("\r\n", "\n").gsub("\r", "\n").gsub("\n\n", "\r\r").gsub("\n", "  \n").gsub("\r\r", "\n\n")
    end
end


text:
package com.github.dstaflund.geomemorial.ui.fragment.searchexamples;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.github.dstaflund.geomemorial.R;

public class SearchExamplesFragmentPresenterImpl implements SearchExamplesFragmentPresenter {
    private SearchExamplesFragmentView mView;

    public SearchExamplesFragmentPresenterImpl(@NonNull SearchExamplesFragmentView view){
        super();
        mView = view;
    }

    @Override
    public void onCreate(@Nullable Bundle savedState) {
        if (mView != null) {
            mView.setRetainInstance(true);
            mView.setHasOptionsMenu(false);
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater i, @Nullable ViewGroup c, @Nullable Bundle b) {
        return i.inflate(R.layout.fragment_search_examples, c, false);
    }
}


text:
<?php

/**
 * Spiral Framework.
 *
 * @license   MIT
 * @author    Anton Titov (Wolfy-J)
 */

declare(strict_types=1);

namespace Spiral\Tests\Stempler;

use Spiral\Views\Context\ValueDependency;
use Spiral\Views\Exception\CompileException;
use Spiral\Views\Exception\RenderException;
use Spiral\Views\ViewContext;

class EngineTest extends BaseTest
{
    public function testList(): void
    {
        $views = $this->getStempler()->getLoader()->list();

        $this->assertContains('default:test', $views);
        $this->assertContains('other:test', $views);
    }

    public function testRender(): void
    {
        $s = $this->getStempler();
        $this->assertSame(
            'test',
            $s->get('test', new ViewContext())->render([])
        );

        $this->assertSame(
            'other test',
            $s->get('other:test', new ViewContext())->render([])
        );
    }

    public function testRenderInContext(): void
    {
        $ctx = new ViewContext();
        $ctx = $ctx->withDependency(new ValueDependency('name', 'Test'));

        $s = $this->getStempler();

        $this->assertSame(
            'hello Anton of Test',
            $s->get('other:ctx', $ctx)->render(['name' => 'Anton'])
        );
    }

    public function testRenderException(): void
    {
        $s = $this->getStempler();

        try {
            $s->get('echo', new ViewContext())->render();
        } catch (RenderException $e) {
            $t = $e->getUserTrace()[0];

            $this->assertSame(2, $t['line']);
            $this->assertStringContainsString('echo.dark.php', $t['file']);
        }
    }

    public function testRenderNestedException(): void
    {
        $s = $this->getStempler();

        try {
            $s->get('other:echo-in', new ViewContext())->render();
        } catch (RenderException $e) {
            $t = $e->getUserTrace();
            $this->assertCount(2, $t);

            $this->assertSame(2, $t[0]['line']);
            $this->assertStringContainsString('echo.dark.php', $t[0]['file']);

            $this->assertSame(3, $t[1]['line']);
            $this->assertStringContainsString('echo-in.dark.php', $t[1]['file']);
        }
    }

    public function testSyntaxException(): void
    {
        $twig = $this->getStempler();

        try {
            $twig->get('other:bad', new ViewContext());
        } catch (CompileException $e) {
            $this->assertStringContainsString('bad.dark.php', $e->getFile());
        }
    }
}


text:
package defyndian.exception;

public class ConfigInitialisationException extends Exception {

	public ConfigInitialisationException(Exception e){
		super(e);
	}

	public ConfigInitialisationException(String msg, Exception e){
		super(msg, e);
	}

	public ConfigInitialisationException(String message){
		super(message);
	}

	public ConfigInitialisationException(Throwable cause) {
		super(cause);
	}
}


text:
#include <math.h>
#include "local.h"

/* On platforms where long double is as wide as double.  */
#ifdef _LDBL_EQ_DBL
long
lroundl (long double x)
{
  return lround(x);
}
#endif


text:
#pragma once
#include <aws/states/SFN_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>

namespace Aws
{
namespace SFN
{
namespace Model
{
  enum class ExecutionStatus
  {
    NOT_SET,
    RUNNING,
    SUCCEEDED,
    FAILED,
    TIMED_OUT,
    ABORTED
  };

namespace ExecutionStatusMapper
{
AWS_SFN_API ExecutionStatus GetExecutionStatusForName(const Aws::String& name);

AWS_SFN_API Aws::String GetNameForExecutionStatus(ExecutionStatus value);
} // namespace ExecutionStatusMapper
} // namespace Model
} // namespace SFN
} // namespace Aws


text:
<?xml version="1.0" encoding="UTF-8"?>
<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0"
        xmlns:android="http://schemas.android.com/apk/res/android"
        id="io.cozy.jsbgservice-newpicture"
        version="1.0.0">
    <name>JSBgSerivce new picture</name>
    <description>
        Plugin on top of Javascript Backgournd Services, which start it on new picture taken with camera.
    </description>

    <license>AGPL v3</license>
    <keywords>cordova,android,background service,new picture</keywords>
    <repo>https://github.com/cozy/cordova-jsbgservice-newpicture.git</repo>
    <issue>https://github.com/cozy/cordova-jsbgservice-newpicture/issues/</issue>

    <engines>
        <engine name="cordova" version=">=3.0.0"/>
    </engines>
    <dependency id="io.cozy.jsbackgroundservice" url="https://github.com/jacquarg/cordova-jsbackgroundservice.git"/>

    <!-- android -->
    <platform name="android">
        <config-file target="AndroidManifest.xml" parent="/manifest/application">
            <receiver android:name="io.cozy.jsbackgroundservice.NewPictureReceiver">
                <intent-filter>
                    <action android:name="android.hardware.action.NEW_PICTURE"/>
                    <!-- Old undocumented intent, hearsay used on some Samsungs and HTCs. -->
                    <action android:name="com.android.camera.NEW_PICTURE"/>
                    <category android:name="android.intent.category.DEFAULT" />
                    <data android:mimeType="image/*" />
                </intent-filter>
                <intent-filter>
                    <action android:name="android.net.wifi.supplicant.CONNECTION_CHANGE"/>
                </intent-filter>
            </receiver>
        </config-file>
        <config-file target="AndroidManifest.xml" parent="/manifest">
            <!-- TODO : might be overkill -->
            <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
        </config-file>

        <source-file src="src/android/NewPictureReceiver.java" target-dir="src/io/cozy/jsbackgroundservice" />

    </platform>
</plugin>


text:
package io.digdag.core.config;

import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Properties;
import java.util.Map;
import java.util.HashMap;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.digdag.client.config.Config;
import io.digdag.client.config.ConfigFactory;
import io.digdag.client.config.ConfigElement;
import io.digdag.client.config.ConfigException;

public class PropertyUtils
{
    private PropertyUtils()
    { }

    public static Properties loadFile(Path file)
        throws IOException
    {
        Properties props = new Properties();
        try (InputStream in = Files.newInputStream(file)) {
            props.load(in);
        }
        return props;
    }

    public static ConfigElement toConfigElement(Properties props)
    {
        Config builder = new ConfigFactory(new ObjectMapper()).create();
        for (String key : props.stringPropertyNames()) {
            builder.set(key, props.getProperty(key));
        }
        return ConfigElement.copyOf(builder);
    }

    public static Map<String, String> toMap(Properties props, String prefix)
    {
        Map<String, String> map = new HashMap<>();
        for (String key : props.stringPropertyNames()) {
            if (key.startsWith(prefix)) {
                map.put(key.substring(prefix.length()), props.getProperty(key));
            }
        }
        return map;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>

<xs:schema
  xmlns="http://packagemanagement.org/installation"
  targetNamespace="http://packagemanagement.org/installation"

  xmlns:swid="http://standards.iso.org/iso/19770/-2/2015/schema.xsd"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  xmlns:ds="http://www.w3.org/2000/09/xmldsig#"
  xmlns:xml="http://www.w3.org/XML/1998/namespace"
  elementFormDefault="qualified">

  <xs:annotation>
    <xs:documentation>
      Schema for Software Installation via swidtag metadata.
    </xs:documentation>
    <xs:appinfo>
      <version>1.0</version>
    </xs:appinfo>
  </xs:annotation>

</xs:schema>


text:
import React from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
import { imageHost } from '../../isomorphicVars';

const StoryHover = (props) => {

  return (

        <Link to={props.href}>

{props.title}

Read the story

        </Link>

  );
};

StoryHover.propTypes = {
  children: PropTypes.oneOfType([
    PropTypes.array,
    PropTypes.element
  ]),
  title: PropTypes.string.isRequired,
  href: PropTypes.string.isRequired,
  src: PropTypes.string.isRequired
};

export default StoryHover;


text:
<!DOCTYPE html>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<link rel="stylesheet" type="text/css"
          href="https://fonts.googleapis.com/css?family=Open+Sans">

Data for Kentucky

2016 Kentucky poll results by county

              Demo     Repub

2000:  638,898  872,492

2004:  712,733  1,069,439

2008:  751,985  1,048,462

2012:  679,370  1,087,190

2016:  628,834  1,202,942

      </object>

<title>Kentucky (KY) </title>


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Mycotaxon 8(2): 489 (1979)

#### Original name
Calonectria aurantiella Penz. & Sacc., 1897

### Remarks
null


text:
package org.apereo.cas.oidc.claims;

import lombok.val;
import org.jose4j.jwt.JwtClaims;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;

import java.util.List;

import static org.junit.jupiter.api.Assertions.*;

/**
 * This is {@link OidcIdTokenClaimCollectorTests}.
 *
 * @author Misagh Moayyed
 * @since 6.6.0
 */
@Tag("OIDC")
public class OidcIdTokenClaimCollectorTests {
    @Test
    public void verifyDefaultOperation() throws Exception {
        val claims = new JwtClaims();
        val collector = OidcIdTokenClaimCollector.defaultCollector();
        collector.collect(claims, "claim1", List.of("value1"));
        collector.collect(claims, "claim2", List.of("value1", "value2"));
        assertEquals("value1", claims.getStringClaimValue("claim1"));
        assertEquals(List.of("value1", "value2"), claims.getStringListClaimValue("claim2"));
    }

    @Test
    public void verifyListing() throws Exception {
        val claims = new JwtClaims();
        val collector = OidcIdTokenClaimCollector.listableCollector();
        collector.collect(claims, "claim1", List.of("value1"));
        collector.collect(claims, "claim2", List.of("value1", "value2"));
        assertEquals(List.of("value1"), claims.getStringListClaimValue("claim1"));
        assertEquals(List.of("value1", "value2"), claims.getStringListClaimValue("claim2"));
    }
}


text:
package skeleton;

import static org.assertj.core.api.Assertions.*;

import cucumber.api.java.en.Given;
import cucumber.api.java.en.When;
import cucumber.api.java.en.Then;

public class Stepdefs {
    private Belly belly;
    private String sound;

    @Given("^I have (\\d+) cukes in my belly$")
    public void I_have_cukes_in_my_belly(int cukes) throws Exception {
	belly = new Belly();
        belly.eat(cukes);
    }

    @When("^I wait (\\d+) hours?$")
    public void When_I_wait_x_hour_s(int waitTime) throws Exception {
	sound = belly.getSound(waitTime);
    }

    @Then("^(?:[Mm]y) belly should (\\w+)$")
    public void Then_my_belly_should_make_a_sound(String sound) throws Exception {
	assertThat(this.sound).isEqualTo(sound);
    }
}


text:
python -m grpc_tools.protoc -I../simnetrpc \
	-I$GOPATH/src \
	-I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \
	--python_out=. \
	--grpc_python_out=. \
	../simnetrpc/simnetrpc.proto

python -m grpc_tools.protoc -I. \
	-I$GOPATH/src \
	-I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \
	--python_out=. \
	--grpc_python_out=. \
	./rpc.proto


text:
API Response Trait
##################

Much of modern PHP development requires building APIs, whether simply to provide data for a javascript-heavy
single page application, or as a standalone product. CodeIgniter provides an API Response trait that can be
used with any controller to make common response types simple, with no need to remember which HTTP status code
should be returned for which response types.

.. contents::
    :local:
    :depth: 2

*************
Example Usage
*************

The following example shows a common usage pattern within your controllers.

.. literalinclude:: api_responses/001.php

In this example, an HTTP status code of 201 is returned, with the generic status message, 'Created'. Methods
exist for the most common use cases:

.. literalinclude:: api_responses/002.php

***********************
Handling Response Types
***********************

When you pass your data in any of these methods, they will determine the data type to format the results as based on
the following criteria:

* If data is a string, it will be treated as HTML to send back to the client.
* If data is an array, it will be formatted according to the controller's ``$this->format`` value. If that is empty,
  it will try to negotiate the content type with what the client asked for, defaulting to JSON
  if nothing else has been specified within **Config/Format.php**, the ``$supportedResponseFormats`` property.

To define the formatter that is used, edit **Config/Format.php**. The ``$supportedResponseFormats`` contains a list of
mime types that your application can automatically format the response for. By default, the system knows how to
format both XML and JSON responses:

.. literalinclude:: api_responses/003.php

This is the array that is used during :doc:`Content Negotiation </incoming/content_negotiation>` to determine which
type of response to return. If no matches are found between what the client requested and what you support, the first
format in this array is what will be returned.

Next, you need to define the class that is used to format the array of data. This must be a fully qualified class
name, and the class must implement ``CodeIgniter\Format\FormatterInterface``. Formatters come out of the box that
support both JSON and XML:

.. literalinclude:: api_responses/004.php

So, if your request asks for JSON formatted data in an **Accept** header, the data array you pass any of the
``respond*`` or ``fail*`` methods will be formatted by the ``CodeIgniter\Format\JSONFormatter`` class. The resulting
JSON data will be sent back to the client.

***************
Class Reference
***************

.. php:method:: setResponseFormat($format)

    :param string $format: The type of response to return, either ``json`` or ``xml``

    This defines the format to be used when formatting arrays in responses. If you provide a ``null`` value for
    ``$format``, it will be automatically determined through content negotiation.

.. literalinclude:: api_responses/005.php

.. php:method:: respond($data[, $statusCode = 200[, $message = '']])

    :param mixed  $data: The data to return to the client. Either string or array.
    :param int    $statusCode: The HTTP status code to return. Defaults to 200
    :param string $message: A custom "reason" message to return.

    This is the method used by all other methods in this trait to return a response to the client.

    The ``$data`` element can be either a string or an array. By default, a string will be returned as HTML,
    while an array will be run through json_encode and returned as JSON, unless :doc:`Content Negotiation </incoming/content_negotiation>`
    determines it should be returned in a different format.

    If a ``$message`` string is passed, it will be used in place of the standard IANA reason codes for the
    response status. Not every client will respect the custom codes, though, and will use the IANA standards
    that match the status code.

    .. note:: Since it sets the status code and body on the active Response instance, this should always
        be the final method in the script execution.

.. php:method:: fail($messages[, int $status = 400[, string $code = null[, string $message = '']]])

    :param mixed $messages: A string or array of strings that contain error messages encountered.
    :param int   $status: The HTTP status code to return. Defaults to 400.
    :param string $code: A custom, API-specific, error code.
    :param string $message: A custom "reason" message to return.
    :returns: A multi-part response in the client's preferred format.

    The is the generic method used to represent a failed response, and is used by all of the other "fail" methods.

    The ``$messages`` element can be either a string or an array of strings.

    The ``$status`` parameter is the HTTP status code that should be returned.

    Since many APIs are better served using custom error codes, a custom error code can be passed in the third
    parameter. If no value is present, it will be the same as ``$status``.

    If a ``$message`` string is passed, it will be used in place of the standard IANA reason codes for the
    response status. Not every client will respect the custom codes, though, and will use the IANA standards
    that match the status code.

    The response is an array with two elements: ``error`` and ``messages``. The ``error`` element contains the status
    code of the error. The ``messages`` element contains an array of error messages. It would look something like:

    .. literalinclude:: api_responses/006.php

.. php:method:: respondCreated($data = null[, string $message = ''])

    :param mixed  $data: The data to return to the client. Either string or array.
    :param string $message: A custom "reason" message to return.
    :returns: The value of the Response object's send() method.

    Sets the appropriate status code to use when a new resource was created, typically 201:

    .. literalinclude:: api_responses/007.php

.. php:method:: respondDeleted($data = null[, string $message = ''])

    :param mixed  $data: The data to return to the client. Either string or array.
    :param string $message: A custom "reason" message to return.
    :returns: The value of the Response object's send() method.

    Sets the appropriate status code to use when a new resource was deleted as the result of this API call, typically 200.

    .. literalinclude:: api_responses/008.php

.. php:method:: respondNoContent(string $message = 'No Content')

    :param string $message: A custom "reason" message to return.
    :returns: The value of the Response object's send() method.

    Sets the appropriate status code to use when a command was successfully executed by the server but there is no
    meaningful reply to send back to the client, typically 204.

    .. literalinclude:: api_responses/009.php

.. php:method:: failUnauthorized(string $description = 'Unauthorized'[, string $code = null[, string $message = '']])

    :param string  $description: The error message to show the user.
    :param string $code: A custom, API-specific, error code.
    :param string $message: A custom "reason" message to return.
    :returns: The value of the Response object's send() method.

    Sets the appropriate status code to use when the user either has not been authorized,
    or has incorrect authorization. Status code is 401.

    .. literalinclude:: api_responses/010.php

.. php:method:: failForbidden(string $description = 'Forbidden'[, string $code=null[, string $message = '']])

    :param string  $description: The error message to show the user.
    :param string $code: A custom, API-specific, error code.
    :param string $message: A custom "reason" message to return.
    :returns: The value of the Response object's send() method.

    Unlike ``failUnauthorized()``, this method should be used when the requested API endpoint is never allowed.
    Unauthorized implies the client is encouraged to try again with different credentials. Forbidden means
    the client should not try again because it won't help. Status code is 403.

    .. literalinclude:: api_responses/011.php

.. php:method:: failNotFound(string $description = 'Not Found'[, string $code=null[, string $message = '']])

    :param string  $description: The error message to show the user.
    :param string $code: A custom, API-specific, error code.
    :param string $message: A custom "reason" message to return.
    :returns: The value of the Response object's send() method.

    Sets the appropriate status code to use when the requested resource cannot be found. Status code is 404.

    .. literalinclude:: api_responses/012.php

.. php:method:: failValidationErrors($errors[, string $code=null[, string $message = '']])

    :param mixed  $errors: The error message or array of messages to show the user.
    :param string $code: A custom, API-specific, error code.
    :param string $message: A custom "reason" message to return.
    :returns: The value of the Response object's send() method.

    Sets the appropriate status code to use when data the client sent did not pass validation rules. Status code is typically 400.

    .. literalinclude:: api_responses/013.php

.. php:method:: failResourceExists(string $description = 'Conflict'[, string $code=null[, string $message = '']])

    :param string  $description: The error message to show the user.
    :param string $code: A custom, API-specific, error code.
    :param string $message: A custom "reason" message to return.
    :returns: The value of the Response object's send() method.

    Sets the appropriate status code to use when the resource the client is trying to create already exists.
    Status code is typically 409.

    .. literalinclude:: api_responses/014.php

.. php:method:: failResourceGone(string $description = 'Gone'[, string $code=null[, string $message = '']])

    :param string  $description: The error message to show the user.
    :param string $code: A custom, API-specific, error code.
    :param string $message: A custom "reason" message to return.
    :returns: The value of the Response object's send() method.

    Sets the appropriate status code to use when the requested resource was previously deleted and
    is no longer available. Status code is typically 410.

    .. literalinclude:: api_responses/015.php

.. php:method:: failTooManyRequests(string $description = 'Too Many Requests'[, string $code=null[, string $message = '']])

    :param string  $description: The error message to show the user.
    :param string $code: A custom, API-specific, error code.
    :param string $message: A custom "reason" message to return.
    :returns: The value of the Response object's send() method.

    Sets the appropriate status code to use when the client has called an API endpoint too many times.
    This might be due to some form of throttling or rate limiting. Status code is typically 400.

    .. literalinclude:: api_responses/016.php

.. php:method:: failServerError(string $description = 'Internal Server Error'[, string $code = null[, string $message = '']])

    :param string $description: The error message to show the user.
    :param string $code: A custom, API-specific, error code.
    :param string $message: A custom "reason" message to return.
    :returns: The value of the Response object's send() method.

    Sets the appropriate status code to use when there is a server error.

    .. literalinclude:: api_responses/017.php


text:
package nl.han.ica.core.issue.solver;

import nl.han.ica.core.issue.Issue;
import nl.han.ica.core.issue.detector.HideMethodDetector;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.junit.Before;
import org.junit.Test;

import java.lang.reflect.Modifier;

import static junit.framework.Assert.*;

/**
 * @author: Wouter Konecny
 * @created: 09-11-12
 */
public class HideMethodSolverTest {
    HideMethodSolver hideMethodSolver = null;
    private MethodDeclaration methodDeclaration = null;
    private AST ast;

//    @Before
//    public void setUp() throws Exception {
//        hideMethodSolver = new HideMethodSolver();
//        ast = AST.newAST(AST.JLS3);
//        methodDeclaration = ast.newMethodDeclaration();
//        methodDeclaration.modifiers().addAll(ast.newModifiers(Modifier.PUBLIC | Modifier.STATIC | Modifier.FINAL));
//    }
//
//    @Test
//    public void testRewriteAST() throws Exception {
//        Issue issue = new Issue(new HideMethodDetector());
//        issue.getNodes().add(methodDeclaration);
//        assertFalse(Modifier.isPrivate(methodDeclaration.getModifiers()));
//        assertTrue(Modifier.isPublic(methodDeclaration.getModifiers()));
//        hideMethodSolver.internalSolve(issue, null);
//        assertFalse(Modifier.isPublic(methodDeclaration.getModifiers()));
//        assertTrue(Modifier.isPrivate(methodDeclaration.getModifiers()));
//    }

    @Test
    public void testGetDefaultParameters() throws Exception {

    }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.azure.cosmos.models;

import com.azure.cosmos.implementation.ImplementationBridgeHelpers;
import com.azure.cosmos.implementation.batch.BatchRequestResponseConstants;
import com.azure.cosmos.implementation.spark.OperationContextAndListenerTuple;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

import static com.azure.cosmos.implementation.guava25.base.Preconditions.checkArgument;

/**
 * Encapsulates options that can be specified for operations used in Bulk execution.
 * It can be passed while processing bulk operations.
 */
public final class CosmosBulkExecutionOptions {
    private int maxMicroBatchSize = BatchRequestResponseConstants.MAX_OPERATIONS_IN_DIRECT_MODE_BATCH_REQUEST;
    private int maxMicroBatchConcurrency = BatchRequestResponseConstants.DEFAULT_MAX_MICRO_BATCH_CONCURRENCY;
    private double maxMicroBatchRetryRate = BatchRequestResponseConstants.DEFAULT_MAX_MICRO_BATCH_RETRY_RATE;
    private double minMicroBatchRetryRate = BatchRequestResponseConstants.DEFAULT_MIN_MICRO_BATCH_RETRY_RATE;
    private Duration maxMicroBatchInterval = Duration.ofMillis(
        BatchRequestResponseConstants.DEFAULT_MAX_MICRO_BATCH_INTERVAL_IN_MILLISECONDS);
    private final Object legacyBatchScopedContext;
    private final CosmosBulkExecutionThresholdsState thresholds;
    private Integer maxConcurrentCosmosPartitions = null;
    private OperationContextAndListenerTuple operationContextAndListenerTuple;
    private Map<String, String> customOptions;
    private String throughputControlGroupName;

    /**
     * Constructor
     * @param thresholdsState thresholds
     */
    CosmosBulkExecutionOptions(Object legacyBatchScopedContext, CosmosBulkExecutionThresholdsState thresholdsState, Map<String, String> customOptions) {
        this.legacyBatchScopedContext = legacyBatchScopedContext;
        if (thresholdsState == null) {
            this.thresholds = new CosmosBulkExecutionThresholdsState();
        } else {
            this.thresholds = thresholdsState;
        }
        if (customOptions == null) {
            this.customOptions = new HashMap<>();
        } else {
            this.customOptions = customOptions;
        }
    }

    /**
     * Constructor
     * @param thresholdsState thresholds
     */
    public CosmosBulkExecutionOptions(CosmosBulkExecutionThresholdsState thresholdsState) {
        this(null, thresholdsState, null);
    }

    /**
     * Constructor
     */
    public CosmosBulkExecutionOptions() {
        this(null, null, null);
    }

    /**
     * The maximum batching size for bulk operations. This value determines number of operations executed in one
     * request. There is an upper limit on both number of operations and sum of size of operations. Any overflow is
     * internally retried.
     *
     * Another instance is: Currently we support a max limit of 200KB, and user select batch size to be 100 and individual
     * documents are of size 20KB, approximately 90 operations will always be retried. So it's better to choose a batch
     * size of 10 here if user is aware of there workload. If sizes are totally unknown and user cannot put a number on it
     * then retries are handled, so no issues as such.
     *
     * If the retry rate exceeds `getMaxMicroBatchInterval` the micro batch size gets dynamically reduced at runtime
     * @return micro batch size
     */
    int getMaxMicroBatchSize() {
        return maxMicroBatchSize;
    }

    /**
     * The maximum batching size for bulk operations. This value determines number of operations executed in one
     * request. There is an upper limit on both number of operations and sum of size of operations. Any overflow is
     * internally retried.
     *
     * Another instance is: Currently we support a max limit of 200KB, and user select batch size to be 100 and individual
     * documents are of size 20KB, approximately 90 operations will always be retried. So it's better to choose a batch
     * size of 10 here if user is aware of there workload. If sizes are totally unknown and user cannot put a number on it
     * then retries are handled, so no issues as such.
     *
     * If the retry rate exceeds `getMaxMicroBatchInterval` the micro batch size gets dynamically reduced at runtime
     *
     * @param maxMicroBatchSize batching size.
     *
     * @return the bulk processing options.
     */
    CosmosBulkExecutionOptions setMaxMicroBatchSize(int maxMicroBatchSize) {
        this.maxMicroBatchSize = maxMicroBatchSize;
        return this;
    }

    Integer getMaxConcurrentCosmosPartitions() {
        return this.maxConcurrentCosmosPartitions;
    }

    CosmosBulkExecutionOptions setMaxConcurrentCosmosPartitions(int maxConcurrentCosmosPartitions) {
        this.maxConcurrentCosmosPartitions = maxConcurrentCosmosPartitions;
        return this;
    }

    /**
     * The maximum concurrency for executing requests for a partition key range.
     * By default, the maxMicroBatchConcurrency is 1.
     *
     * @return max micro batch concurrency
     */
    public int getMaxMicroBatchConcurrency() {
        return maxMicroBatchConcurrency;
    }

    /**
     * Set the maximum concurrency for executing requests for a partition key range.
     * By default, the maxMicroBatchConcurrency is 1.
     * It only allows values ≥1 and ≤5.
     *
     * Attention! Please adjust this value with caution.
     * By increasing this value, more concurrent requests will be allowed to be sent to the server,
     * in which case may cause 429 or request timed out due to saturate local resources, which could degrade the performance.
     *
     * @param maxMicroBatchConcurrency the micro batch concurrency.
     *
     * @return the bulk processing options.
     */
    public CosmosBulkExecutionOptions setMaxMicroBatchConcurrency(int maxMicroBatchConcurrency) {
        checkArgument(
            maxMicroBatchConcurrency >= 1 && maxMicroBatchConcurrency <= 5,
            "maxMicroBatchConcurrency should be between [1, 5]");
        this.maxMicroBatchConcurrency = maxMicroBatchConcurrency;
        return this;
    }

    /**
     * The flush interval for bulk operations.
     *
     * @return max micro batch interval
     */
    Duration getMaxMicroBatchInterval() {
        return maxMicroBatchInterval;
    }

    /**
     * The maximum acceptable retry rate bandwidth. This value determines how aggressively the actual micro batch size
     * gets reduced or increased if the number of retries (for example due to 429 - Throttling or because the total
     * request size exceeds the payload limit) is higher or lower that the targeted range.
     *
     * @return max targeted micro batch retry rate
     */
    double getMaxTargetedMicroBatchRetryRate() {
        return this.maxMicroBatchRetryRate;
    }

    /**
     * The acceptable retry rate bandwidth. This value determines how aggressively the actual micro batch size
     * gets reduced or increased if the number of retries (for example due to 429 - Throttling or because the total
     * request size exceeds the payload limit) is higher or lower that the targeted range.
     *
     * @param minRetryRate minimum targeted retry rate of batch requests. If the retry rate is
     *                     lower than this threshold the micro batch size will be dynamically increased over time
     * @param maxRetryRate maximum retry rate of batch requests that is treated as acceptable. If the retry rate is
     *                     higher than this threshold the micro batch size will be dynamically reduced over time
     *
     * @return the bulk processing options.
     */
    CosmosBulkExecutionOptions setTargetedMicroBatchRetryRate(double minRetryRate, double maxRetryRate) {
        if (minRetryRate < 0) {
            throw new IllegalArgumentException("The maxRetryRate must not be a negative value");
        }

        if (minRetryRate > maxRetryRate) {
            throw new IllegalArgumentException("The minRetryRate must not exceed the maxRetryRate");
        }

        this.maxMicroBatchRetryRate = maxRetryRate;
        this.minMicroBatchRetryRate = minRetryRate;
        return this;
    }

    /**
     * The minimum acceptable retry rate bandwidth. This value determines how aggressively the actual micro batch size
     * gets reduced or increased if the number of retries (for example due to 429 - Throttling or because the total
     * request size exceeds the payload limit) is higher or lower that the targeted range.
     *
     * @return min targeted micro batch retry rate
     */
    double getMinTargetedMicroBatchRetryRate() {
        return this.minMicroBatchRetryRate;
    }

    /**
     * Returns batch context
     * @return batch context
     */
    Object getLegacyBatchScopedContext() {
        return this.legacyBatchScopedContext;
    }

    /**
     * Returns threshold state that can be passed to other CosmosBulkExecutionOptions in the future
     * @return thresholds
     */
    public CosmosBulkExecutionThresholdsState getThresholdsState() {
        return this.thresholds;
    }

    OperationContextAndListenerTuple getOperationContextAndListenerTuple() {
        return this.operationContextAndListenerTuple;
    }

    void setOperationContextAndListenerTuple(OperationContextAndListenerTuple operationContextAndListenerTuple) {
        this.operationContextAndListenerTuple = operationContextAndListenerTuple;
    }

    /**
     * Sets the custom bulk request option value by key
     *
     * @param name  a string representing the custom option's name
     * @param value a string representing the custom option's value
     * @return the CosmosBulkExecutionOptions.
     */
    CosmosBulkExecutionOptions setHeader(String name, String value) {
        if (this.customOptions == null) {
            this.customOptions = new HashMap<>();
        }
        this.customOptions.put(name, value);
        return this;
    }

    /**
     * Gets the custom batch request options
     *
     * @return Map of custom request options
     */
    Map<String, String> getHeaders() {
        return this.customOptions;
    }

    /**
     * Gets the throughput control group name.
     *
     * @return the throughput control group name.
     */
    public String getThroughputControlGroupName() {
        return this.throughputControlGroupName;
    }

    /**
     * Sets the throughput control group name.
     *
     * @param throughputControlGroupName the throughput control group name.
     * @return the CosmosBulkExecutionOptions.
     */
    public CosmosBulkExecutionOptions setThroughputControlGroupName(String throughputControlGroupName) {
        this.throughputControlGroupName = throughputControlGroupName;

        return this;
    }

    ///////////////////////////////////////////////////////////////////////////////////////////
    // the following helper/accessor only helps to access this class outside of this package.//
    ///////////////////////////////////////////////////////////////////////////////////////////
    static void initialize() {
        ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper.setCosmosBulkExecutionOptionsAccessor(
            new ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper.CosmosBulkExecutionOptionsAccessor() {

                @Override
                public void setOperationContext(CosmosBulkExecutionOptions options,
                                                OperationContextAndListenerTuple operationContextAndListenerTuple) {
                    options.setOperationContextAndListenerTuple(operationContextAndListenerTuple);
                }

                @Override
                public OperationContextAndListenerTuple getOperationContext(CosmosBulkExecutionOptions options) {
                    return options.getOperationContextAndListenerTuple();
                }

                @Override
                @SuppressWarnings({"unchecked"})
                public <T> T getLegacyBatchScopedContext(CosmosBulkExecutionOptions options) {
                    return (T)options.getLegacyBatchScopedContext();
                }

                @Override
                public double getMinTargetedMicroBatchRetryRate(CosmosBulkExecutionOptions options) {
                    return options.getMinTargetedMicroBatchRetryRate();
                }

                @Override
                public double getMaxTargetedMicroBatchRetryRate(CosmosBulkExecutionOptions options) {
                    return options.getMaxTargetedMicroBatchRetryRate();
                }

                @Override
                public int getMaxMicroBatchSize(CosmosBulkExecutionOptions options) {
                    return options.getMaxMicroBatchSize();
                }

                @Override
                public CosmosBulkExecutionOptions setMaxMicroBatchSize(
                    CosmosBulkExecutionOptions options,
                    int maxMicroBatchSize) {

                    return options.setMaxMicroBatchSize(maxMicroBatchSize);
                }

                @Override
                public int getMaxMicroBatchConcurrency(CosmosBulkExecutionOptions options) {
                    return options.getMaxMicroBatchConcurrency();
                }

                @Override
                public Integer getMaxConcurrentCosmosPartitions(CosmosBulkExecutionOptions options) {
                    return options.getMaxConcurrentCosmosPartitions();
                }

                @Override
                public CosmosBulkExecutionOptions setMaxConcurrentCosmosPartitions(
                    CosmosBulkExecutionOptions options, int maxConcurrentCosmosPartitions) {
                    return options.setMaxConcurrentCosmosPartitions(maxConcurrentCosmosPartitions);
                }

                @Override
                public Duration getMaxMicroBatchInterval(CosmosBulkExecutionOptions options) {
                    return options.getMaxMicroBatchInterval();
                }

                @Override
                public CosmosBulkExecutionOptions setTargetedMicroBatchRetryRate(
                    CosmosBulkExecutionOptions options,
                    double minRetryRate,
                    double maxRetryRate) {

                    return options.setTargetedMicroBatchRetryRate(minRetryRate, maxRetryRate);
                }

                @Override
                public CosmosBulkExecutionOptions setHeader(CosmosBulkExecutionOptions cosmosBulkExecutionOptions,
                                                            String name, String value) {
                    return cosmosBulkExecutionOptions.setHeader(name, value);
                }

                @Override
                public Map<String, String> getHeader(CosmosBulkExecutionOptions cosmosBulkExecutionOptions) {
                    return cosmosBulkExecutionOptions.getHeaders();
                }

                @Override
                public Map<String, String> getCustomOptions(CosmosBulkExecutionOptions cosmosBulkExecutionOptions) {
                    return cosmosBulkExecutionOptions.customOptions;
                }

            });
    }

    static { initialize(); }
}


text:
require 'rubygems'
require 'rubygems/dependency_list'
require 'rubygems/installer'
require 'rubygems/spec_fetcher'
require 'rubygems/user_interaction'

##
# Installs a gem along with all its dependencies from local and remote gems.

class Gem::DependencyInstaller

  include Gem::UserInteraction

  attr_reader :gems_to_install
  attr_reader :installed_gems

  DEFAULT_OPTIONS = {
    :env_shebang => false,
    :domain => :both, # HACK dup
    :force => false,
    :format_executable => false, # HACK dup
    :ignore_dependencies => false,
    :prerelease => false,
    :security_policy => nil, # HACK NoSecurity requires OpenSSL.  AlmostNo? Low?
    :wrappers => true,
  }

  ##
  # Creates a new installer instance.
  #
  # Options are:
  # :cache_dir:: Alternate repository path to store .gem files in.
  # :domain:: :local, :remote, or :both.  :local only searches gems in the
  #           current directory.  :remote searches only gems in Gem::sources.
  #           :both searches both.
  # :env_shebang:: See Gem::Installer::new.
  # :force:: See Gem::Installer#install.
  # :format_executable:: See Gem::Installer#initialize.
  # :ignore_dependencies:: Don't install any dependencies.
  # :install_dir:: See Gem::Installer#install.
  # :prerelease:: Allow prerelease versions.  See #install.
  # :security_policy:: See Gem::Installer::new and Gem::Security.
  # :user_install:: See Gem::Installer.new
  # :wrappers:: See Gem::Installer::new

  def initialize(options = {})
    if options[:install_dir] then
      spec_dir = options[:install_dir], 'specifications'
      @source_index = Gem::SourceIndex.from_gems_in spec_dir
    else
      @source_index = Gem.source_index
    end

    options = DEFAULT_OPTIONS.merge options

    @bin_dir = options[:bin_dir]
    @development = options[:development]
    @domain = options[:domain]
    @env_shebang = options[:env_shebang]
    @force = options[:force]
    @format_executable = options[:format_executable]
    @ignore_dependencies = options[:ignore_dependencies]
    @prerelease = options[:prerelease]
    @security_policy = options[:security_policy]
    @user_install = options[:user_install]
    @wrappers = options[:wrappers]

    @installed_gems = []

    @install_dir = options[:install_dir] || Gem.dir
    @cache_dir = options[:cache_dir] || @install_dir

    # Set with any errors that SpecFetcher finds while search through
    # gemspecs for a dep
    @errors = nil
  end

  ##
  # Returns a list of pairs of gemspecs and source_uris that match
  # Gem::Dependency +dep+ from both local (Dir.pwd) and remote (Gem.sources)
  # sources.  Gems are sorted with newer gems preferred over older gems, and
  # local gems preferred over remote gems.

  def find_gems_with_sources(dep)
    # Reset the errors
    @errors = nil
    gems_and_sources = []

    if @domain == :both or @domain == :local then
      Dir[File.join(Dir.pwd, "#{dep.name}-[0-9]*.gem")].each do |gem_file|
        spec = Gem::Format.from_file_by_path(gem_file).spec
        gems_and_sources << [spec, gem_file] if spec.name == dep.name
      end
    end

    if @domain == :both or @domain == :remote then
      begin
        requirements = dep.requirement.requirements.map do |req, ver|
          req
        end

        all = !dep.prerelease? &&
              # we only need latest if there's one requirement and it is
              # guaranteed to match the newest specs
              (requirements.length > 1 or
                (requirements.first != ">=" and requirements.first != ">"))

        found, @errors = Gem::SpecFetcher.fetcher.fetch_with_errors dep, all, true, dep.prerelease?

        gems_and_sources.push(*found)

      rescue Gem::RemoteFetcher::FetchError => e
        if Gem.configuration.really_verbose then
          say "Error fetching remote data:\t\t#{e.message}"
          say "Falling back to local-only install"
        end
        @domain = :local
      end
    end

    gems_and_sources.sort_by do |gem, source|
      [gem, source =~ /^http:\/\// ? 0 : 1] # local gems win
    end
  end

  ##
  # Gathers all dependencies necessary for the installation from local and
  # remote sources unless the ignore_dependencies was given.

  def gather_dependencies
    specs = @specs_and_sources.map { |spec,_| spec }

    dependency_list = Gem::DependencyList.new @development
    dependency_list.add(*specs)
    to_do = specs.dup

    add_found_dependencies to_do, dependency_list unless @ignore_dependencies

    @gems_to_install = dependency_list.dependency_order.reverse
  end

  def add_found_dependencies to_do, dependency_list
    seen = {}

    until to_do.empty? do
      spec = to_do.shift
      next if spec.nil? or seen[spec.name]
      seen[spec.name] = true

      deps = spec.runtime_dependencies
      deps |= spec.development_dependencies if @development

      deps.each do |dep|
        results = find_gems_with_sources(dep).reverse

        # FIX: throw in everything that satisfies, and let
        # FIX: dependencylist reduce to the chosen few
        results.reject! do |dep_spec,|
          to_do.push dep_spec

          # already locally installed
          @source_index.any? do |_, installed_spec|
            dep.name == installed_spec.name and
              dep.requirement.satisfied_by? installed_spec.version
          end
        end

        results.each do |dep_spec, source_uri|
          next if seen[dep_spec.name]
          @specs_and_sources << [dep_spec, source_uri]

          # FIX: this is the bug
          dependency_list.add dep_spec
        end
      end
    end
  end

  ##
  # Finds a spec and the source_uri it came from for gem +gem_name+ and
  # +version+.  Returns an Array of specs and sources required for
  # installation of the gem.

  def find_spec_by_name_and_version(gem_name,
                                    version = Gem::Requirement.default,
                                    prerelease = false)
    spec_and_source = nil

    glob = if File::ALT_SEPARATOR then
             gem_name.gsub File::ALT_SEPARATOR, File::SEPARATOR
           else
             gem_name
           end

    local_gems = Dir["#{glob}*"].sort.reverse

    unless local_gems.empty? then
      local_gems.each do |gem_file|
        next unless gem_file =~ /gem$/
        begin
          spec = Gem::Format.from_file_by_path(gem_file).spec
          spec_and_source = [spec, gem_file]
          break
        rescue SystemCallError, Gem::Package::FormatError
        end
      end
    end

    if spec_and_source.nil? then
      dep = Gem::Dependency.new gem_name, version
      dep.prerelease = true if prerelease
      spec_and_sources = find_gems_with_sources(dep).reverse

      spec_and_source = spec_and_sources.find { |spec, source|
        Gem::Platform.match spec.platform
      }
    end

    if spec_and_source.nil? then
      raise Gem::GemNotFoundException.new(
        "Could not find a valid gem '#{gem_name}' (#{version}) locally or in a repository",
        gem_name, version, @errors)
    end

    @specs_and_sources = [spec_and_source]
  end

  ##
  # Installs the gem +dep_or_name+ and all its dependencies.  Returns an Array
  # of installed gem specifications.
  #
  # If the +:prerelease+ option is set and there is a prerelease for
  # +dep_or_name+ the prerelease version will be installed.
  #
  # Unless explicitly specified as a prerelease dependency, prerelease gems
  # that +dep_or_name+ depend on will not be installed.
  #
  # If c-1.a depends on b-1 and a-1.a and there is a gem b-1.a available then
  # c-1.a, b-1 and a-1.a will be installed.  b-1.a will need to be installed
  # separately.

  def install dep_or_name, version = Gem::Requirement.default
    if String === dep_or_name then
      find_spec_by_name_and_version dep_or_name, version, @prerelease
    else
      dep_or_name.prerelease = @prerelease
      @specs_and_sources = [find_gems_with_sources(dep_or_name).last]
    end

    @installed_gems = []

    gather_dependencies

    @gems_to_install.each do |spec|
      last = spec == @gems_to_install.last
      # HACK is this test for full_name acceptable?
      next if @source_index.any? { |n,_| n == spec.full_name } and not last

      # TODO: make this sorta_verbose so other users can benefit from it
      say "Installing gem #{spec.full_name}" if Gem.configuration.really_verbose

      _, source_uri = @specs_and_sources.assoc spec
      begin
        local_gem_path = Gem::RemoteFetcher.fetcher.download spec, source_uri,
                                                             @cache_dir
      rescue Gem::RemoteFetcher::FetchError
        next if @force
        raise
      end

      inst = Gem::Installer.new local_gem_path,
                                :bin_dir             => @bin_dir,
                                :development         => @development,
                                :env_shebang         => @env_shebang,
                                :force               => @force,
                                :format_executable   => @format_executable,
                                :ignore_dependencies => @ignore_dependencies,
                                :install_dir         => @install_dir,
                                :security_policy     => @security_policy,
                                :source_index        => @source_index,
                                :user_install        => @user_install,
                                :wrappers            => @wrappers

      spec = inst.install

      @installed_gems << spec
    end

    @installed_gems
  end

end


text:
package okreplay;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import static java.util.Collections.unmodifiableList;
import static okreplay.Util.VIA;

/**
 * Represents a set of recorded HTTP interactions that can be played back or
 * appended to.
 */
abstract class MemoryTape implements Tape {
  private String name;
  private List<YamlRecordedInteraction> interactions = new ArrayList<>();
  private transient TapeMode mode = OkReplayConfig.DEFAULT_MODE;
  private transient MatchRule matchRule = OkReplayConfig.DEFAULT_MATCH_RULE;
  private final transient AtomicInteger orderedIndex = new AtomicInteger();

  @Override public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  @Override public TapeMode getMode() {
    return mode;
  }

  @Override public void setMode(TapeMode mode) {
    this.mode = mode;
  }

  @Override public MatchRule getMatchRule() {
    return this.matchRule;
  }

  @Override public void setMatchRule(MatchRule matchRule) {
    this.matchRule = matchRule;
  }

  @Override public boolean isReadable() {
    return mode.isReadable();
  }

  @Override public boolean isWritable() {
    return mode.isWritable();
  }

  @Override public boolean isSequential() {
    return mode.isSequential();
  }

  @Override public int size() {
    return interactions.size();
  }

  public List<YamlRecordedInteraction> getInteractions() {
    return unmodifiableList(interactions);
  }

  public void setInteractions(List<YamlRecordedInteraction> interactions) {
    this.interactions = new ArrayList<>(interactions);
  }

  @Override public boolean seek(Request request) {
    if (isSequential()) {
      try {
        // TODO: it's a complete waste of time using an AtomicInteger when this method is called
        // before play in a non-transactional way
        int index = orderedIndex.get();
        RecordedInteraction interaction = interactions.get(index).toImmutable();
        Request nextRequest = interaction == null ? null : interaction.request();
        return nextRequest != null && matchRule.isMatch(request, nextRequest);
      } catch (IndexOutOfBoundsException e) {
        throw new NonWritableTapeException();
      }
    } else {
      return findMatch(request) >= 0;
    }
  }

  @Override public Response play(final Request request) {
    if (!mode.isReadable()) {
      throw new IllegalStateException("the tape is not readable");
    }

    if (mode.isSequential()) {
      int nextIndex = orderedIndex.getAndIncrement();
      RecordedInteraction nextInteraction = interactions.get(nextIndex).toImmutable();
      if (nextInteraction == null) {
        throw new IllegalStateException(String.format("No recording found at position %s",
            nextIndex));
      }

      if (!matchRule.isMatch(request, nextInteraction.request())) {
        throw new IllegalStateException(String.format("Request %s does not match recorded " +
            "request" + " %s", stringify(request), stringify(nextInteraction.request())));
      }

      return nextInteraction.response();
    } else {
      int position = findMatch(request);
      if (position < 0) {
        throw new IllegalStateException("no matching recording found");
      } else {
        return interactions.get(position).toImmutable().response();
      }
    }
  }

  private String stringify(Request request) {
    byte[] body = request.body() != null ? request.body() : new byte[0];
    String bodyLog = " (binary " + body.length + "-byte body omitted)";
    return "method: " + request.method() + ", " + "uri: " + request.url() + ", " + "headers: " +
        request.headers() + ", " + bodyLog;
  }

  @Override public synchronized void record(Request request, Response response) {
    if (!mode.isWritable()) {
      throw new IllegalStateException("the tape is not writable");
    }

    RecordedInteraction interaction = new RecordedInteraction(new Date(), recordRequest(request),
        recordResponse(response));

    if (mode.isSequential()) {
      interactions.add(interaction.toYaml());
    } else {
      int position = findMatch(request);
      if (position >= 0) {
        interactions.set(position, interaction.toYaml());
      } else {
        interactions.add(interaction.toYaml());
      }
    }
  }

  @Override public String toString() {
    return String.format("Tape[%s]", name);
  }

  private synchronized int findMatch(final Request request) {
    return Util.indexOf(interactions.iterator(), new Predicate<YamlRecordedInteraction>() {
      @Override public boolean apply(YamlRecordedInteraction input) {
        return matchRule.isMatch(request, input.toImmutable().request());
      }
    });
  }

  private Request recordRequest(Request request) {
    return request.newBuilder()
        .removeHeader(VIA)
        .build();
  }

  private Response recordResponse(Response response) {
    return response.newBuilder()
        .removeHeader(VIA)
        .removeHeader(Headers.X_OKREPLAY)
        .build();
  }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
Uses of Class net.oauth.j2me.BadTokenStateException (FE OAuth)
</TITLE>

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
net.oauth.j2me.BadTokenStateException

Packages that use BadTokenStateException

net.oauth.j2me

net.yahoo.fireeagle.j2me

Uses of BadTokenStateException in net.oauth.j2me

Methods in net.oauth.j2me that throw BadTokenStateException

 AccessToken
Consumer.getAccessToken(java.lang.String endpoint,
               RequestToken requestToken)

Uses of BadTokenStateException in net.yahoo.fireeagle.j2me

Methods in net.yahoo.fireeagle.j2me that throw BadTokenStateException

 AccessToken
FireEagleConsumer.fetchNewAccessToken()

          Makes an HTTPS call to Fire Eagle to get an access token
 NOTE: this makes a synchronous HTTPS connection, which might make J2ME unhappy if you don't
 deal with threading elsewhere.

 java.lang.String
FireEagleConsumer.queryUserLocation()

          Makes an HTTPS call to Fire Eagle to update location
 NOTE: this makes a synchronous HTTPS connection, which might make J2ME unhappy if you don't
 deal with threading elsewhere.

 java.lang.String
FireEagleConsumer.updateLocation(java.util.Hashtable queryParams)

          Makes an HTTPS call to Fire Eagle to update location
 NOTE: this makes a synchronous HTTPS connection, which might make J2ME unhappy if you don't
 deal with threading elsewhere.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes


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

namespace Sdl.Community.GroupShareKit.Models.Response
{
    public class User
    {
        /// <summary>
        /// Gets or sets the  user id
        /// </summary>
        public Guid UniqueId { get; set; }
        /// <summary>
        /// Gets or sets the user name
        /// </summary>
        public string Name { get; set; }
        /// <summary>
        /// Gets or sets the password
        /// </summary>
        public object Password { get; set; }
        /// <summary>
        /// Gets or sets the display name
        /// </summary>
        public string DisplayName { get; set; }
        /// <summary>
        /// Gets or sets the discription
        /// </summary>
        public string Description { get; set; }
        /// <summary>
        /// Gets or sets the email adress
        /// </summary>
        public string EmailAddress { get; set; }
        /// <summary>
        /// Gets or sets the phone number
        /// </summary>
        public string PhoneNumber { get; set; }
        /// <summary>
        /// Gets or sets the locale
        /// </summary>
        public string Locale { get; set; }
        /// <summary>
        /// Gets or sets the  organization id
        /// </summary>
        public Guid OrganizationId { get; set; }
        /// <summary>
        /// Gets or sets the user type
        /// </summary>
        public string UserType { get; set; }
        /// <summary>
        /// Gets or sets if the user is protected
        /// </summary>
        public bool IsProtected { get; set; }
        /// <summary>
        /// Gets or sets a list of roles <see cref="Role"/>
        /// </summary>
        public List<Role> Roles { get; set; }
    }
}


text:
require 'rails_helper'

RSpec.describe "dependencies/edit", type: :view do
  before(:each) do
    @dependency = assign(:dependency, Dependency.create!(
      :dependent_id => nil,
      :depended_id => nil
    ))
  end

  it "renders the edit dependency form" do
    render

    assert_select "form[action=?][method=?]", dependency_path(@dependency), "post" do

      assert_select "input#dependency_dependent_id[name=?]", "dependency[dependent_id]"

      assert_select "input#dependency_depended_id[name=?]", "dependency[depended_id]"
    end
  end
end