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

cr.define('cloudprint', function() {
  'use strict';

  /**
   * API to the Google Cloud Print service.
   * @param {string} baseUrl Base part of the Google Cloud Print service URL
   *     with no trailing slash. For example,
   *     'https://www.google.com/cloudprint'.
   * @param {!print_preview.NativeLayer} nativeLayer Native layer used to get
   *     Auth2 tokens.
   * @param {!print_preview.UserInfo} userInfo User information repository.
   * @param {boolean} isInAppKioskMode Whether the print preview is in App
   *     Kiosk mode.
   * @constructor
   * @extends {cr.EventTarget}
   */
  function CloudPrintInterface(
      baseUrl, nativeLayer, userInfo, isInAppKioskMode) {
    /**
     * The base URL of the Google Cloud Print API.
     * @type {string}
     * @private
     */
    this.baseUrl_ = baseUrl;

    /**
     * Used to get Auth2 tokens.
     * @type {!print_preview.NativeLayer}
     * @private
     */
    this.nativeLayer_ = nativeLayer;

    /**
     * User information repository.
     * @type {!print_preview.UserInfo}
     * @private
     */
    this.userInfo_ = userInfo;

    /**
     * Whether Print Preview is in App Kiosk mode, basically, use only printers
     * available for the device.
     * @type {boolean}
     * @private
     */
    this.isInAppKioskMode_ = isInAppKioskMode;

    /**
     * Currently logged in users (identified by email) mapped to the Google
     * session index.
     * @type {!Object.<string, number>}
     * @private
     */
    this.userSessionIndex_ = {};

    /**
     * Stores last received XSRF tokens for each user account. Sent as
     * a parameter with every request.
     * @type {!Object.<string, string>}
     * @private
     */
    this.xsrfTokens_ = {};

    /**
     * Pending requests delayed until we get access token.
     * @type {!Array.<!CloudPrintRequest>}
     * @private
     */
    this.requestQueue_ = [];

    /**
     * Outstanding cloud destination search requests.
     * @type {!Array.<!CloudPrintRequest>}
     * @private
     */
    this.outstandingCloudSearchRequests_ = [];

    /**
     * Event tracker used to keep track of native layer events.
     * @type {!EventTracker}
     * @private
     */
    this.tracker_ = new EventTracker();

    this.addEventListeners_();
  };

  /**
   * Event types dispatched by the interface.
   * @enum {string}
   */
  CloudPrintInterface.EventType = {
    PRINTER_DONE: 'cloudprint.CloudPrintInterface.PRINTER_DONE',
    PRINTER_FAILED: 'cloudprint.CloudPrintInterface.PRINTER_FAILED',
    SEARCH_DONE: 'cloudprint.CloudPrintInterface.SEARCH_DONE',
    SEARCH_FAILED: 'cloudprint.CloudPrintInterface.SEARCH_FAILED',
    SUBMIT_DONE: 'cloudprint.CloudPrintInterface.SUBMIT_DONE',
    SUBMIT_FAILED: 'cloudprint.CloudPrintInterface.SUBMIT_FAILED',
    UPDATE_PRINTER_TOS_ACCEPTANCE_FAILED:
        'cloudprint.CloudPrintInterface.UPDATE_PRINTER_TOS_ACCEPTANCE_FAILED'
  };

  /**
   * Content type header value for a URL encoded HTTP request.
   * @type {string}
   * @const
   * @private
   */
  CloudPrintInterface.URL_ENCODED_CONTENT_TYPE_ =
      'application/x-www-form-urlencoded';

  /**
   * Multi-part POST request boundary used in communication with Google
   * Cloud Print.
   * @type {string}
   * @const
   * @private
   */
  CloudPrintInterface.MULTIPART_BOUNDARY_ =
      '----CloudPrintFormBoundaryjc9wuprokl8i';

  /**
   * Content type header value for a multipart HTTP request.
   * @type {string}
   * @const
   * @private
   */
  CloudPrintInterface.MULTIPART_CONTENT_TYPE_ =
      'multipart/form-data; boundary=' +
      CloudPrintInterface.MULTIPART_BOUNDARY_;

  /**
   * Regex that extracts Chrome's version from the user-agent string.
   * @type {!RegExp}
   * @const
   * @private
   */
  CloudPrintInterface.VERSION_REGEXP_ = /.*Chrome\/([\d\.]+)/i;

  /**
   * Enumeration of JSON response fields from Google Cloud Print API.
   * @enum {string}
   * @private
   */
  CloudPrintInterface.JsonFields_ = {
    PRINTER: 'printer'
  };

  /**
   * Could Print origins used to search printers.
   * @type {!Array.<!print_preview.Destination.Origin>}
   * @const
   * @private
   */
  CloudPrintInterface.CLOUD_ORIGINS_ = [
      print_preview.Destination.Origin.COOKIES,
      print_preview.Destination.Origin.DEVICE
      // TODO(vitalybuka): Enable when implemented.
      // ready print_preview.Destination.Origin.PROFILE
  ];

  CloudPrintInterface.prototype = {
    __proto__: cr.EventTarget.prototype,

    /** @return {string} Base URL of the Google Cloud Print service. */
    get baseUrl() {
      return this.baseUrl_;
    },

    /**
     * @return {boolean} Whether a search for cloud destinations is in progress.
     */
    get isCloudDestinationSearchInProgress() {
      return this.outstandingCloudSearchRequests_.length > 0;
    },

    /**
     * Sends Google Cloud Print search API request.
     * @param {string=} opt_account Account the search is sent for. When
     *      omitted, the search is done on behalf of the primary user.
     * @param {print_preview.Destination.Origin=} opt_origin When specified,
     *     searches destinations for {@code opt_origin} only, otherwise starts
     *     searches for all origins.
     */
    search: function(opt_account, opt_origin) {
      var account = opt_account || '';
      var origins =
          opt_origin && [opt_origin] || CloudPrintInterface.CLOUD_ORIGINS_;
      if (this.isInAppKioskMode_) {
        origins = origins.filter(function(origin) {
          return origin != print_preview.Destination.Origin.COOKIES;
        });
      }
      this.abortSearchRequests_(origins);
      this.search_(true, account, origins);
      this.search_(false, account, origins);
    },

    /**
     * Sends Google Cloud Print search API requests.
     * @param {boolean} isRecent Whether to search for only recently used
     *     printers.
     * @param {string} account Account the search is sent for. It matters for
     *     COOKIES origin only, and can be empty (sent on behalf of the primary
     *     user in this case).
     * @param {!Array.<!print_preview.Destination.Origin>} origins Origins to
     *     search printers for.
     * @private
     */
    search_: function(isRecent, account, origins) {
      var params = [
        new HttpParam('connection_status', 'ALL'),
        new HttpParam('client', 'chrome'),
        new HttpParam('use_cdd', 'true')
      ];
      if (isRecent) {
        params.push(new HttpParam('q', '^recent'));
      }
      origins.forEach(function(origin) {
        var cpRequest = this.buildRequest_(
            'GET',
            'search',
            params,
            origin,
            account,
            this.onSearchDone_.bind(this, isRecent));
        this.outstandingCloudSearchRequests_.push(cpRequest);
        this.sendOrQueueRequest_(cpRequest);
      }, this);
    },

    /**
     * Sends a Google Cloud Print submit API request.
     * @param {!print_preview.Destination} destination Cloud destination to
     *     print to.
     * @param {!print_preview.PrintTicketStore} printTicketStore Contains the
     *     print ticket to print.
     * @param {!print_preview.DocumentInfo} documentInfo Document data model.
     * @param {string} data Base64 encoded data of the document.
     */
    submit: function(destination, printTicketStore, documentInfo, data) {
      var result =
          CloudPrintInterface.VERSION_REGEXP_.exec(navigator.userAgent);
      var chromeVersion = 'unknown';
      if (result && result.length == 2) {
        chromeVersion = result[1];
      }
      var params = [
        new HttpParam('printerid', destination.id),
        new HttpParam('contentType', 'dataUrl'),
        new HttpParam('title', documentInfo.title),
        new HttpParam('ticket',
                      printTicketStore.createPrintTicket(destination)),
        new HttpParam('content', 'data:application/pdf;base64,' + data),
        new HttpParam('tag',
                      '__google__chrome_version=' + chromeVersion),
        new HttpParam('tag', '__google__os=' + navigator.platform)
      ];
      var cpRequest = this.buildRequest_(
          'POST',
          'submit',
          params,
          destination.origin,
          destination.account,
          this.onSubmitDone_.bind(this));
      this.sendOrQueueRequest_(cpRequest);
    },

    /**
     * Sends a Google Cloud Print printer API request.
     * @param {string} printerId ID of the printer to lookup.
     * @param {!print_preview.Destination.Origin} origin Origin of the printer.
     * @param {string=} account Account this printer is registered for. When
     *     provided for COOKIES {@code origin}, and users sessions are still not
     *     known, will be checked against the response (both success and failure
     *     to get printer) and, if the active user account is not the one
     *     requested, {@code account} is activated and printer request reissued.
     */
    printer: function(printerId, origin, account) {
      var params = [
        new HttpParam('printerid', printerId),
        new HttpParam('use_cdd', 'true'),
        new HttpParam('printer_connection_status', 'true')
      ];
      this.sendOrQueueRequest_(this.buildRequest_(
          'GET',
          'printer',
          params,
          origin,
          account,
          this.onPrinterDone_.bind(this, printerId)));
    },

    /**
     * Sends a Google Cloud Print update API request to accept (or reject) the
     * terms-of-service of the given printer.
     * @param {!print_preview.Destination} destination Destination to accept ToS
     *     for.
     * @param {boolean} isAccepted Whether the user accepted ToS or not.
     */
    updatePrinterTosAcceptance: function(destination, isAccepted) {
      var params = [
        new HttpParam('printerid', destination.id),
        new HttpParam('is_tos_accepted', isAccepted)
      ];
      this.sendOrQueueRequest_(this.buildRequest_(
          'POST',
          'update',
          params,
          destination.origin,
          destination.account,
          this.onUpdatePrinterTosAcceptanceDone_.bind(this)));
    },

    /**
     * Adds event listeners to relevant events.
     * @private
     */
    addEventListeners_: function() {
      this.tracker_.add(
          this.nativeLayer_,
          print_preview.NativeLayer.EventType.ACCESS_TOKEN_READY,
          this.onAccessTokenReady_.bind(this));
    },

    /**
     * Builds request to the Google Cloud Print API.
     * @param {string} method HTTP method of the request.
     * @param {string} action Google Cloud Print action to perform.
     * @param {Array.<!HttpParam>} params HTTP parameters to include in the
     *     request.
     * @param {!print_preview.Destination.Origin} origin Origin for destination.
     * @param {?string} account Account the request is sent for. Can be
     *     {@code null} or empty string if the request is not cookie bound or
     *     is sent on behalf of the primary user.
     * @param {function(number, Object, !print_preview.Destination.Origin)}
     *     callback Callback to invoke when request completes.
     * @return {!CloudPrintRequest} Partially prepared request.
     * @private
     */
    buildRequest_: function(method, action, params, origin, account, callback) {
      var url = this.baseUrl_ + '/' + action + '?xsrf=';
      if (origin == print_preview.Destination.Origin.COOKIES) {
        var xsrfToken = this.xsrfTokens_[account];
        if (!xsrfToken) {
          // TODO(rltoscano): Should throw an error if not a read-only action or
          // issue an xsrf token request.
        } else {
          url = url + xsrfToken;
        }
        if (account) {
          var index = this.userSessionIndex_[account] || 0;
          if (index > 0) {
            url += '&user=' + index;
          }
        }
      }
      var body = null;
      if (params) {
        if (method == 'GET') {
          url = params.reduce(function(partialUrl, param) {
            return partialUrl + '&' + param.name + '=' +
                encodeURIComponent(param.value);
          }, url);
        } else if (method == 'POST') {
          body = params.reduce(function(partialBody, param) {
            return partialBody + 'Content-Disposition: form-data; name=\"' +
                param.name + '\"\r\n\r\n' + param.value + '\r\n--' +
                CloudPrintInterface.MULTIPART_BOUNDARY_ + '\r\n';
          }, '--' + CloudPrintInterface.MULTIPART_BOUNDARY_ + '\r\n');
        }
      }

      var headers = {};
      headers['X-CloudPrint-Proxy'] = 'ChromePrintPreview';
      if (method == 'GET') {
        headers['Content-Type'] = CloudPrintInterface.URL_ENCODED_CONTENT_TYPE_;
      } else if (method == 'POST') {
        headers['Content-Type'] = CloudPrintInterface.MULTIPART_CONTENT_TYPE_;
      }

      var xhr = new XMLHttpRequest();
      xhr.open(method, url, true);
      xhr.withCredentials =
          (origin == print_preview.Destination.Origin.COOKIES);
      for (var header in headers) {
        xhr.setRequestHeader(header, headers[header]);
      }

      return new CloudPrintRequest(xhr, body, origin, account, callback);
    },

    /**
     * Sends a request to the Google Cloud Print API or queues if it needs to
     *     wait OAuth2 access token.
     * @param {!CloudPrintRequest} request Request to send or queue.
     * @private
     */
    sendOrQueueRequest_: function(request) {
      if (request.origin == print_preview.Destination.Origin.COOKIES) {
        return this.sendRequest_(request);
      } else {
        this.requestQueue_.push(request);
        this.nativeLayer_.startGetAccessToken(request.origin);
      }
    },

    /**
     * Sends a request to the Google Cloud Print API.
     * @param {!CloudPrintRequest} request Request to send.
     * @private
     */
    sendRequest_: function(request) {
      request.xhr.onreadystatechange =
          this.onReadyStateChange_.bind(this, request);
      request.xhr.send(request.body);
    },

    /**
     * Creates a Google Cloud Print interface error that is ready to dispatch.
     * @param {!CloudPrintInterface.EventType} type Type of the error.
     * @param {!CloudPrintRequest} request Request that has been completed.
     * @return {!Event} Google Cloud Print interface error event.
     * @private
     */
    createErrorEvent_: function(type, request) {
      var errorEvent = new Event(type);
      errorEvent.status = request.xhr.status;
      if (request.xhr.status == 200) {
        errorEvent.errorCode = request.result['errorCode'];
        errorEvent.message = request.result['message'];
      } else {
        errorEvent.errorCode = 0;
        errorEvent.message = '';
      }
      errorEvent.origin = request.origin;
      return errorEvent;
    },

    /**
     * Updates user info and session index from the {@code request} response.
     * @param {!CloudPrintRequest} request Request to extract user info from.
     * @private
     */
    setUsers_: function(request) {
      if (request.origin == print_preview.Destination.Origin.COOKIES) {
        var users = request.result['request']['users'] || [];
        this.userSessionIndex_ = {};
        for (var i = 0; i < users.length; i++) {
          this.userSessionIndex_[users[i]] = i;
        }
        this.userInfo_.setUsers(request.result['request']['user'], users);
      }
    },

    /**
     * Terminates search requests for requested {@code origins}.
     * @param {!Array.<print_preview.Destination.Origin>} origins Origins
     *     to terminate search requests for.
     * @private
     */
    abortSearchRequests_: function(origins) {
      this.outstandingCloudSearchRequests_ =
          this.outstandingCloudSearchRequests_.filter(function(request) {
            if (origins.indexOf(request.origin) >= 0) {
              request.xhr.abort();
              return false;
            }
            return true;
          });
    },

    /**
     * Called when a native layer receives access token.
     * @param {Event} evt Contains the authentication type and access token.
     * @private
     */
    onAccessTokenReady_: function(event) {
      // TODO(vitalybuka): remove when other Origins implemented.
      assert(event.authType == print_preview.Destination.Origin.DEVICE);
      this.requestQueue_ = this.requestQueue_.filter(function(request) {
        assert(request.origin == print_preview.Destination.Origin.DEVICE);
        if (request.origin != event.authType) {
          return true;
        }
        if (event.accessToken) {
          request.xhr.setRequestHeader('Authorization',
                                       'Bearer ' + event.accessToken);
          this.sendRequest_(request);
        } else {  // No valid token.
          // Without abort status does not exist.
          request.xhr.abort();
          request.callback(request);
        }
        return false;
      }, this);
    },

    /**
     * Called when the ready-state of a XML http request changes.
     * Calls the successCallback with the result or dispatches an ERROR event.
     * @param {!CloudPrintRequest} request Request that was changed.
     * @private
     */
    onReadyStateChange_: function(request) {
      if (request.xhr.readyState == 4) {
        if (request.xhr.status == 200) {
          request.result = JSON.parse(request.xhr.responseText);
          if (request.origin == print_preview.Destination.Origin.COOKIES &&
              request.result['success']) {
            this.xsrfTokens_[request.result['request']['user']] =
                request.result['xsrf_token'];
          }
        }
        request.status = request.xhr.status;
        request.callback(request);
      }
    },

    /**
     * Called when the search request completes.
     * @param {boolean} isRecent Whether the search request was for recent
     *     destinations.
     * @param {!CloudPrintRequest} request Request that has been completed.
     * @private
     */
    onSearchDone_: function(isRecent, request) {
      var lastRequestForThisOrigin = true;
      this.outstandingCloudSearchRequests_ =
          this.outstandingCloudSearchRequests_.filter(function(item) {
            if (item != request && item.origin == request.origin) {
              lastRequestForThisOrigin = false;
            }
            return item != request;
          });
      var activeUser = '';
      if (request.origin == print_preview.Destination.Origin.COOKIES) {
        activeUser =
            request.result &&
            request.result['request'] &&
            request.result['request']['user'];
      }
      var event = null;
      if (request.xhr.status == 200 && request.result['success']) {
        // Extract printers.
        var printerListJson = request.result['printers'] || [];
        var printerList = [];
        printerListJson.forEach(function(printerJson) {
          try {
            printerList.push(cloudprint.CloudDestinationParser.parse(
                printerJson, request.origin, activeUser));
          } catch (err) {
            console.error('Unable to parse cloud print destination: ' + err);
          }
        });
        // Extract and store users.
        this.setUsers_(request);
        // Dispatch SEARCH_DONE event.
        event = new Event(CloudPrintInterface.EventType.SEARCH_DONE);
        event.origin = request.origin;
        event.printers = printerList;
        event.isRecent = isRecent;
      } else {
        event = this.createErrorEvent_(
            CloudPrintInterface.EventType.SEARCH_FAILED,
            request);
      }
      event.user = activeUser;
      event.searchDone = lastRequestForThisOrigin;
      this.dispatchEvent(event);
    },

    /**
     * Called when the submit request completes.
     * @param {!CloudPrintRequest} request Request that has been completed.
     * @private
     */
    onSubmitDone_: function(request) {
      if (request.xhr.status == 200 && request.result['success']) {
        var submitDoneEvent = new Event(
            CloudPrintInterface.EventType.SUBMIT_DONE);
        submitDoneEvent.jobId = request.result['job']['id'];
        this.dispatchEvent(submitDoneEvent);
      } else {
        var errorEvent = this.createErrorEvent_(
            CloudPrintInterface.EventType.SUBMIT_FAILED, request);
        this.dispatchEvent(errorEvent);
      }
    },

    /**
     * Called when the printer request completes.
     * @param {string} destinationId ID of the destination that was looked up.
     * @param {!CloudPrintRequest} request Request that has been completed.
     * @private
     */
    onPrinterDone_: function(destinationId, request) {
      // Special handling of the first printer request. It does not matter at
      // this point, whether printer was found or not.
      if (request.origin == print_preview.Destination.Origin.COOKIES &&
          request.result &&
          request.account &&
          request.result['request']['user'] &&
          request.result['request']['users'] &&
          request.account != request.result['request']['user']) {
        this.setUsers_(request);
        // In case the user account is known, but not the primary one,
        // activate it.
        if (this.userSessionIndex_[request.account] > 0) {
          this.userInfo_.activeUser = request.account;
          // Repeat the request for the newly activated account.
          this.printer(
              request.result['request']['params']['printerid'],
              request.origin,
              request.account);
          // Stop processing this request, wait for the new response.
          return;
        }
      }
      // Process response.
      if (request.xhr.status == 200 && request.result['success']) {
        var activeUser = '';
        if (request.origin == print_preview.Destination.Origin.COOKIES) {
          activeUser = request.result['request']['user'];
        }
        var printerJson = request.result['printers'][0];
        var printer;
        try {
          printer = cloudprint.CloudDestinationParser.parse(
              printerJson, request.origin, activeUser);
        } catch (err) {
          console.error('Failed to parse cloud print destination: ' +
              JSON.stringify(printerJson));
          return;
        }
        var printerDoneEvent =
            new Event(CloudPrintInterface.EventType.PRINTER_DONE);
        printerDoneEvent.printer = printer;
        this.dispatchEvent(printerDoneEvent);
      } else {
        var errorEvent = this.createErrorEvent_(
            CloudPrintInterface.EventType.PRINTER_FAILED, request);
        errorEvent.destinationId = destinationId;
        errorEvent.destinationOrigin = request.origin;
        this.dispatchEvent(errorEvent, request.origin);
      }
    },

    /**
     * Called when the update printer TOS acceptance request completes.
     * @param {!CloudPrintRequest} request Request that has been completed.
     * @private
     */
    onUpdatePrinterTosAcceptanceDone_: function(request) {
      if (request.xhr.status == 200 && request.result['success']) {
        // Do nothing.
      } else {
        var errorEvent = this.createErrorEvent_(
            CloudPrintInterface.EventType.SUBMIT_FAILED, request);
        this.dispatchEvent(errorEvent);
      }
    }
  };

  /**
   * Data structure that holds data for Cloud Print requests.
   * @param {!XMLHttpRequest} xhr Partially prepared http request.
   * @param {string} body Data to send with POST requests.
   * @param {!print_preview.Destination.Origin} origin Origin for destination.
   * @param {?string} account Account the request is sent for. Can be
   *     {@code null} or empty string if the request is not cookie bound or
   *     is sent on behalf of the primary user.
   * @param {function(!CloudPrintRequest)} callback Callback to invoke when
   *     request completes.
   * @constructor
   */
  function CloudPrintRequest(xhr, body, origin, account, callback) {
    /**
     * Partially prepared http request.
     * @type {!XMLHttpRequest}
     */
    this.xhr = xhr;

    /**
     * Data to send with POST requests.
     * @type {string}
     */
    this.body = body;

    /**
     * Origin for destination.
     * @type {!print_preview.Destination.Origin}
     */
    this.origin = origin;

    /**
     * User account this request is expected to be executed for.
     * @type {?string}
     */
    this.account = account;

    /**
     * Callback to invoke when request completes.
     * @type {function(!CloudPrintRequest)}
     */
    this.callback = callback;

    /**
     * Result for requests.
     * @type {Object} JSON response.
     */
    this.result = null;
  };

  /**
   * Data structure that represents an HTTP parameter.
   * @param {string} name Name of the parameter.
   * @param {string} value Value of the parameter.
   * @constructor
   */
  function HttpParam(name, value) {
    /**
     * Name of the parameter.
     * @type {string}
     */
    this.name = name;

    /**
     * Name of the value.
     * @type {string}
     */
    this.value = value;
  };

  // Export
  return {
    CloudPrintInterface: CloudPrintInterface
  };
});


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

using System;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.Core.TestFramework;
using Azure.Test.Perf;

namespace Azure.Identity.Perf
{
    public class BearerTokenAuthenticationPolicyPerfTest : PerfTest<CountOptions>
    {
        private HttpPipeline _pipeline;
        private HttpMessage _message;

        public BearerTokenAuthenticationPolicyPerfTest(CountOptions options) : base(options)
        {
            var _transport = new MockTransport((req) => new MockResponse(200));
            _pipeline = new HttpPipeline(_transport, new[] { new BearerTokenAuthenticationPolicy(new StaticCredential(), "scope") });
            _message = _pipeline.CreateMessage();
            _message.BufferResponse = true;
            _message.Request.Method = RequestMethod.Get;
            _message.Request.Uri.Reset(new Uri("https://example.com"));
        }

        public override void Run(CancellationToken cancellationToken)
        {
            _pipeline.Send(_message, cancellationToken);
        }

        public override async Task RunAsync(CancellationToken cancellationToken)
        {
            await _pipeline.SendAsync(_message, cancellationToken).ConfigureAwait(false);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Podaxon algericum Pat.

### Remarks
null


text:
namespace Endjin.Cancelable.Azure.Storage
{
    #region Using Directives

    using System.IO;
    using System.Threading.Tasks;

    using Endjin.Contracts;
    using Endjin.Core.Retry;

    using Microsoft.Azure;
    using Microsoft.WindowsAzure.Storage;
    using Microsoft.WindowsAzure.Storage.Blob;

    #endregion

    public class AzureBlobStorageCancellationTokenProvider : ICancellationTokenProvider
    {
        private readonly IConnectionStringProvider connectionStringProvider;

        private CloudBlobClient client;
        private CloudBlobContainer container;
        private bool initialised;
        private CloudStorageAccount storageAccount;

        public AzureBlobStorageCancellationTokenProvider(IConnectionStringProvider connectionStringProvider)
        {
            this.connectionStringProvider = connectionStringProvider;
        }

        public async Task CreateAsync(string cancellationToken)
        {
            await this.InitialiseAsync();

            var blob = this.container.GetBlockBlobReference(cancellationToken);

            await Retriable.RetryAsync(async () =>
            {
                using (var ms = new MemoryStream())
                {
                    await blob.UploadFromStreamAsync(ms);
                }
            });
        }

        public async Task DeleteAsync(string cancellationToken)
        {
            await this.InitialiseAsync();

            var blob = this.container.GetBlockBlobReference(cancellationToken);

            await Retriable.RetryAsync(() => blob.DeleteAsync());
        }

        public async Task<bool> ExistsAsync(string cancellationToken)
        {
            await this.InitialiseAsync();

            var blob = this.container.GetBlockBlobReference(cancellationToken);

            return await Retriable.RetryAsync(blob.ExistsAsync);
        }

        private async Task InitialiseAsync()
        {
            if (!this.initialised)
            {
                this.storageAccount = CloudStorageAccount.Parse(Configuration.GetSettingFor(this.connectionStringProvider.ConnectionStringKey));
                this.client = this.storageAccount.CreateCloudBlobClient();
                this.container = this.client.GetContainerReference("endjin-cancelable-tokens");

                if (await Retriable.RetryAsync(() => this.container.CreateIfNotExistsAsync()))
                {
                    var containerPermissions = new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Off };

                    await Retriable.RetryAsync(() => this.container.SetPermissionsAsync(containerPermissions));
                }

                this.initialised = true;
            }
        }
    }
}


text:
package com.baidu.openrasp.plugin.js.engine;

import com.baidu.openrasp.EngineBoot;
import com.baidu.openrasp.plugin.checker.CheckParameter;
import com.fuxi.javaagent.rhino.shim.Console;
import com.fuxi.javaagent.rhino.shim.Shim;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.mozilla.javascript.*;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by lanyuhang on 2017/9/25.
 */

/**
 * Rhino JSContext 构造工厂类
 */
public class JSContextFactory extends ContextFactory {
    private static final Logger LOGGER = Logger.getLogger(JSContextFactory.class.getPackage().getName() + ".log");

    private static JSContextFactory jsContextFactory = null;

    private ScriptableObject globalScope = null;
    private ScriptableObject RASP = null;
    private long pluginTime = 0;

    private JSContextFactory() throws Exception {
        ContextFactory.initGlobal(this);
        JSContext cx = (JSContext) JSContext.enter();
        cx.clearTimeout();
        try {
            globalScope = cx.initStandardObjects();

            globalScope.defineProperty("global", globalScope, ScriptableObject.READONLY);

            ScriptableObject.defineClass(globalScope, JSStdout.class);
            Object jsstdout = cx.newObject(globalScope, "Stdout");
            globalScope.defineProperty("stdout", jsstdout, ScriptableObject.READONLY);
            globalScope.defineProperty("stderr", jsstdout, ScriptableObject.READONLY);

            ScriptableObject.defineClass(globalScope, JSRequestContext.class);

            Script shim;
            shim = new Shim();
            shim.exec(cx, globalScope);
            shim = new Console();
            shim.exec(cx, globalScope);

            InputStream is;
            String name;
            String script;

            name = "error.js";
            is = EngineBoot.class.getResourceAsStream("/environment/" + name);
            script = IOUtils.toString(is, "UTF-8");
            cx.evaluateString(globalScope, script, name, 1, null);
            name = "checkpoint.js";
            is = EngineBoot.class.getResourceAsStream("/environment/" + name);
            script = IOUtils.toString(is, "UTF-8");
            cx.evaluateString(globalScope, script, name, 1, null);
            name = "rasp.js";
            is = EngineBoot.class.getResourceAsStream("/environment/" + name);
            script = IOUtils.toString(is, "UTF-8");
            cx.evaluateString(globalScope, script, name, 1, null);

            RASP = (ScriptableObject) ScriptableObject.getProperty(globalScope, "RASP");
            RASP.defineProperty("sql_tokenize", new JSTokenizeSql(), ScriptableObject.READONLY);
            RASP.defineProperty("config_set", new JSRASPConfig(), ScriptableObject.READONLY);
            RASP.defineProperty("get_jsengine", new BaseFunction() {
                @Override
                public Object call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args) {
                    return "rhino";
                }

                @Override
                public Object getDefaultValue(Class<?> hint) {
                    return "[Function: get_jsengine]";
                }
            }, ScriptableObject.READONLY);
        } finally {
            JSContext.exit();
        }

        System.out.println("[OpenRASP] JSContextFactory Initialized");
    }

    public static void init() throws Exception {
        jsContextFactory = new JSContextFactory();
    }

    public static void release() {
        setCheckScriptList(null);
        jsContextFactory = null;
    }

    public static void setCheckScriptList(List<CheckScript> checkScriptList) {
        if (jsContextFactory != null) {
            JSContext cx = (JSContext) JSContext.enter();
            cx.clearTimeout();
            try {
                ScriptableObject scope = (ScriptableObject) cx.newObject(jsContextFactory.globalScope);
                scope.setPrototype(jsContextFactory.globalScope);
                scope.setParentScope(null);
                Function clean = (Function) jsContextFactory.RASP.get("clean", jsContextFactory.RASP);
                clean.call(cx, scope, clean, null);
                if (checkScriptList != null) {
                    for (CheckScript checkScript : checkScriptList) {
                        cx.evaluateString(scope, "(function(){\n" + checkScript.getContent() + "\n})()", checkScript.getName(), 0, null);
                    }
                }
            } catch (Exception e) {
                LOGGER.info(e);
            } finally {
                jsContextFactory.pluginTime = System.currentTimeMillis();
                JSContext.exit();
            }
        }
    }

    /**
     * 获取当前线程绑定的 Context
     * 当该方法创建新 Context 时,初始化 global scope 并保存在 Context 的 ThreadLocal 中
     * 重复调用该方法不会增加 Context 中的引用计数,也不需要调用 Exit 解除绑定和释放
     * 该方法创建的 Context 与 Thread 同时释放
     *
     * @return 与当前线程绑定的 Context
     */
    public static JSContext enterAndInitContext() {
        JSContext cx = (JSContext) JSContext.getCurrentContext();
        if (cx == null) {
            cx = (JSContext) jsContextFactory.enterContext();
        }
        if (cx.getPluginTime() < jsContextFactory.pluginTime) {
            cx.setPluginTime(System.currentTimeMillis());
            Scriptable scope = cx.newObject(jsContextFactory.globalScope);
            scope.setPrototype(jsContextFactory.globalScope);
            scope.setParentScope(null);

            NativeObject checkPoints = (NativeObject) jsContextFactory.RASP.get("checkPoints", jsContextFactory.RASP);
            List<List<CheckProcess>> checkPointList = new ArrayList<List<CheckProcess>>(CheckParameter.Type.values().length);
            for (int i = 0; i < CheckParameter.Type.values().length; i++) {
                NativeArray functions = (NativeArray) checkPoints.get(CheckParameter.Type.values()[i].toString());
                if (functions == null) {
                    checkPointList.add(null);
                    continue;
                }
                List<CheckProcess> functionList = new ArrayList<CheckProcess>(functions.size());
                for (int j = 0; j < functions.size(); j++) {
                    NativeObject functionObj = (NativeObject) functions.get(j);
                    Function function = (Function) functionObj.get("func");
                    String pluginName = (String) ((NativeObject) functionObj.get("plugin")).get("name");
                    functionList.add(new CheckProcess(function, pluginName));
                }
                checkPointList.add(functionList);
            }

            cx.setScope(scope);
            cx.setCheckPointList(checkPointList);
        }

        return cx;
    }

    /**
     * 创建 JSContext 并设置默认值
     *
     * @return
     */
    @Override
    protected JSContext makeContext() {
        JSContext cx = new JSContext();
        // 每10 * 1000 * 1000个指令中断一次,用于检测超时
        cx.setInstructionObserverThreshold(10 * 1000 * 1000);
        cx.setLanguageVersion(Context.VERSION_ES6);
        // 使用解释执行
        cx.setOptimizationLevel(9);
        return cx;
    }

    @Override
    public boolean hasFeature(Context cx, int featureIndex) {
        switch (featureIndex) {
            case Context.FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME:
                return true;

            case Context.FEATURE_RESERVED_KEYWORD_AS_IDENTIFIER:
                return true;

            case Context.FEATURE_PARENT_PROTO_PROPERTIES:
                return false;

            case Context.FEATURE_LOCATION_INFORMATION_IN_ERROR:
                return true;

            case Context.FEATURE_STRICT_MODE:
                return true;
        }
        return super.hasFeature(cx, featureIndex);
    }

    /**
     * 每10 * 1000 * 1000个指令触发一次,用于检测超时
     * 判断超时后抛出异常终止引擎执行
     *
     * @param cx
     * @param instructionCount
     * @see JSContextFactory#makeContext()
     */
    @Override
    protected void observeInstructionCount(Context cx, int instructionCount) {
        JSContext jscx = (JSContext) cx;
        if (jscx.isTimeout()) {
            JSContext.reportError("Error: Plugin Execution Timeout");
        }
    }
}


text:
from google.cloud import enterpriseknowledgegraph_v1

def sample_create_entity_reconciliation_job():
    # Create a client
    client = enterpriseknowledgegraph_v1.EnterpriseKnowledgeGraphServiceClient()

    # Initialize request argument(s)
    request = enterpriseknowledgegraph_v1.CreateEntityReconciliationJobRequest(
        parent="parent_value",
    )

    # Make the request
    response = client.create_entity_reconciliation_job(request=request)

    # Handle the response
    print(response)

# [END enterpriseknowledgegraph_v1_generated_EnterpriseKnowledgeGraphService_CreateEntityReconciliationJob_sync]


text:
<?php

namespace App\Command\Tasks;

use App\Command\Task\ReportCompletionCommand as TaskReportCompletionCommand;
use App\Repository\TaskRepository;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class ReportCompletionCommand extends AbstractTaskCollectionCommand
{
    /**
     * @var TaskRepository
     */
    private $taskRepository;

    private $taskReportCompletionCommand;

    public function __construct(
        TaskRepository $taskRepository,
        TaskReportCompletionCommand $taskReportCompletionCommand
    ) {
        parent::__construct(null);

        $this->taskReportCompletionCommand = $taskReportCompletionCommand;
        $this->taskRepository = $taskRepository;
    }

    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this
            ->setName('simplytestable:tasks:reportcompletion')
            ->setDescription('Report completion for all jobs finished')
            ->setHelp('Report completion for all jobs finished');
    }

    /**
     * {@inheritdoc}
     */
    public function execute(InputInterface $input, OutputInterface $output)
    {
        $taskIds = $this->taskRepository->getIdsWithOutput();
        $output->writeln(count($taskIds).' tasks with output ready to report completion');

        $this->executeForCollection($taskIds, $this->taskReportCompletionCommand, $output);

        return 0;
    }
}


text:
/*
 * Beetle.h
 *
 *  Created on: Mar 23, 2016
 *      Author: James Hong
 */

#ifndef INCLUDE_BEETLE_H_
#define INCLUDE_BEETLE_H_

#include <boost/thread/lock_types.hpp>
#include <boost/thread/pthread/shared_mutex.hpp>
#include <sync/OrderedThreadPool.h>
#include <sync/SocketSelect.h>
#include <sync/ThreadPool.h>
#include <functional>
#include <map>
#include <memory>
#include <string>
#include <vector>

#include "BeetleTypes.h"
#include "HCI.h"

/* Forward declarations */
class AccessControl;
class BeetleInternal;
class NetworkDiscoveryClient;
class Router;

/* Defaults parallelism */
const int DEFAULT_NUM_WORKERS = 8;
const int DEFAULT_NUM_WRITERS = 4;
const int DEFAULT_NUM_READERS = 4;

class Beetle {
public:
	Beetle(std::string name, std::string dev, int numWorkers = DEFAULT_NUM_WORKERS, int numWriters = DEFAULT_NUM_WRITERS,
			int numReaders = DEFAULT_NUM_READERS);
	virtual ~Beetle();

	/*
	 * Add a device to Beetle's mappings. Threadsafe. Returns holding a shared lock on devices.
	 */
	void addDevice(std::shared_ptr<Device> device, boost::shared_lock<boost::shared_mutex> &returnLock);
	inline void addDevice(std::shared_ptr<Device> device) {
		boost::shared_lock<boost::shared_mutex> unused;
		addDevice(device, unused);
	};

	/*
	 * Inform Beetle that the device has been updated; for instance, if the handles have changed.
	 */
	void updateDevice(device_t device);

	/*
	 * Removes a device from Beetle's mappings and unsubscribes the device from all characteristics.
	 */
	bool removeDevice(device_t device, std::string &err);
	inline void removeDevice(device_t device) {
		std::string unused;
		removeDevice(device, unused);
	}

	/*
	 * Maps handles from device 1 to device 2.
	 */
	bool mapDevices(device_t from, device_t to, std::string &err);
	inline void mapDevices(device_t from, device_t to) {
		std::string unused;
		mapDevices(from, to, unused);
	};

	/*
	 * Unmaps handles from device 1 to device 2.
	 */
	bool unmapDevices(device_t from, device_t to, std::string &err);
	inline void unmapDevices(device_t from, device_t to) {
		std::string unused;
		unmapDevices(from, to, unused);
	}

	/*
	 * Register handler to be called after a device is added.
	 */
	void registerAddDeviceHandler(AddDeviceHandler h);
	std::vector<AddDeviceHandler> addHandlers;

	/*
	 * Register handler to be called after a device is removed.
	 */
	void registerRemoveDeviceHandler(RemoveDeviceHandler h);
	std::vector<RemoveDeviceHandler> removeHandlers;

	/*
	 * Register handler to be called after a device has been updated.
	 */
	void registerUpdateDeviceHandler(UpdateDeviceHandler h);
	std::vector<UpdateDeviceHandler> updateHandlers;

	/*
	 * Register handler to be called after mapping two devices.
	 */
	void registerMapDevicesHandler(MapDevicesHandler h);
	std::vector<MapDevicesHandler> mapHandlers;

	/*
	 * Register handler to be called after unmapping two devices.
	 */
	void registerUnmapDevicesHandler(UnmapDevicesHandler h);
	std::vector<UnmapDevicesHandler> unmapHandlers;

	/*
	 * Return a daemon to timeout devices.
	 */
	std::function<void()> getDaemon();

	/*
	 * Global map of all devices at this instance.
	 */
	std::map<device_t, std::shared_ptr<Device>> devices;
	boost::shared_mutex devicesMutex;

	/*
	 * Name this Beetle instance
	 */
	std::string name;

	/*
	 * Simulated device for Beetle's own services.
	 */
	std::shared_ptr<BeetleInternal> beetleDevice;

	/*
	 * Router object to route ATT packets
	 */
	std::unique_ptr<Router> router;

	/*
	 * HCI socket for all peripheral connections.
	 */
	HCI hci;

	/*
	 * Set the access control mechanism.
	 */
	void setAccessControl(std::shared_ptr<AccessControl> ac);
	std::shared_ptr<AccessControl> accessControl;

	/*
	 * Set the discovery client.
	 */
	void setDiscoveryClient(std::shared_ptr<NetworkDiscoveryClient> nd);
	std::shared_ptr<NetworkDiscoveryClient> discoveryClient;

	/*
	 * Workers for callbacks.
	 */
	ThreadPool workers;

	/*
	 * Threads used for writing.
	 */
	OrderedThreadPool writers;

	/*
	 * Threads used for reading.
	 */
	SocketSelect readers;
};

#endif /* INCLUDE_BEETLE_H_ */


text:
package info.macias.kaconf.sources;

import info.macias.kaconf.ConfiguratorException;
import info.macias.kaconf.PropertySource;

import java.net.URI;
import java.util.Collections;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static java.util.AbstractMap.SimpleEntry;

/**
 *
Class that implements some basic functionalities of the {@link PropertySource} interface,
 * such as converting string values to java basic types.

 *
Generally, new property sources should extend this class.

 */
public abstract class AbstractPropertySource implements PropertySource {

    @FunctionalInterface
    private interface Converter<C> {
        C convert(String value);
    }

    private static <C> SimpleEntry<Class<C>, Converter<C>> entry(Class<C> cClass, Converter<C> converter) {
        return new SimpleEntry<>(cClass, converter);
    }

    private static boolean convertBool(String str) {
        if (str != null) {
            str = str.trim().toLowerCase();
            return str.equals("true") || str.equals("yes") || str.equals("1");
        }
        return false;
    }

    private Map<Class, Converter> converters = Collections.unmodifiableMap(Stream.of(
            entry(Boolean.class, AbstractPropertySource::convertBool),
            entry(boolean.class, AbstractPropertySource::convertBool),
            entry(Byte.class, Byte::valueOf),
            entry(byte.class, Byte::valueOf),
            entry(Character.class, value -> value.charAt(0)),
            entry(char.class, value -> value.charAt(0)),
            entry(Short.class, Short::valueOf),
            entry(short.class, Short::valueOf),
            entry(Integer.class, Integer::valueOf),
            entry(int.class, Integer::valueOf),
            entry(Long.class, Long::valueOf),
            entry(long.class, Long::valueOf),
            entry(Float.class, Float::valueOf),
            entry(float.class, Float::valueOf),
            entry(Double.class, Double::valueOf),
            entry(double.class, Double::valueOf),
            entry(String.class, value -> value),
            entry(URI.class, URI::create)
    ).collect(Collectors.toMap(SimpleEntry::getKey, SimpleEntry::getValue)));

    /**
     *
Gets the string representation of a property whose name is defined by the name argument

     *
This method will be invoked by {@link #get(String, Class)} to transform the String value into
     * a numeric/char value

     *
     * @param name The name of the property to return
     * @return The property stored for the given name, as a String, null if a property
     * with such name does not exist or the property source is not available.
     */
    protected abstract String get(String name); //TODO: check whether it worths deprecating it and play better with optionals

    /**
     *
Gets the value of the property whose name is defined by the name argument, transforming
     * it to the type of the class passed as second argument.

     *
     *
If the requested type cannot be converted, it will throw a {@link ConfiguratorException}. Other
     * exceptions may raise, e.g. {@link NumberFormatException} when trying to convert an alphanumeric property
     * into an int.

     *
     * @param name The name of the property to return
     * @param type The class object of the property to return
     * @param <T>  The returned type
     * @return The property stored for the given name, as an instance of the given type, null if a property
     * with such name does not exist
     * @throws ConfiguratorException if an invalid type conversion has been intended (for example,
     *                               trying to return a non-basic, non-String type)
     * @throws NumberFormatException or trying to convert an alphanumeric property value to a Number
     */
    @Override
    public <T> T get(String name, Class<T> type) {
        String strVal = get(name);
        if (strVal == null) {
            return null;
        }
        @SuppressWarnings("unchecked")
        Converter<T> converter = converters.get(type);
        if (converter == null) {
            throw new ConfiguratorException("Cannot convert to type: " + type.getName());
        }
        return converter.convert(strVal);
    }
}


text:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#include "sst.h"
#include "test.h"

#define test(fn) \
  fputs("\n\x1b[34m# [stream-pipe] " # fn "\x1b[0m\n", stderr); \
  fn();

static char *strtoupper(char *s) {
  char *cp, *p;
  p = cp = strdup(s);
  while((*p = toupper(*p))) p++;
  return cp;
}

char* strreverse(char *s) {
  char* str = strdup(s);

  char temp;
  size_t len = strlen(str) - 1;
  size_t stop = len / 2;
  size_t i,k;

  for(i = 0, k = len; i <= stop; i++, k--) {
    temp = str[k];
    str[k] = str[i];
    str[i] = temp;
  }
  return str;
}

static void upper_onwrite(sst_t* self, sst_chunk_t* chunk) {
  char *s;
  sst_chunk_t *chunk_out;

  s = (char*)chunk->data;
  chunk_out = sst_chunk_new(strtoupper(s), free);

  self->emit(self, chunk_out);
  sst_chunk_free(chunk);
}

static void reverse_onwrite(sst_t* self, sst_chunk_t* chunk) {
  char *s;
  sst_chunk_t *chunk_out;
  s = (char*)chunk->data;

  chunk_out = sst_chunk_new(strreverse(s), free);
  self->emit(self, chunk_out);

  sst_chunk_free(chunk);
}

static char* emitted;
static int emit_count = 0;
static int end_src_called = 0;
static int end_uppertx_called = 0;
static int end_reversetx_called = 0;
static int end_dst_called = 0;
void setup() {
  emitted              = NULL;
  emit_count           = 0;
  end_src_called       = 0;
  end_uppertx_called   = 0;
  end_reversetx_called = 0;
  end_dst_called       = 0;
}

static void ondata(sst_t* self, sst_chunk_t* chunk) {
  emitted = strdup(chunk->data);
  emit_count++;
  sst_chunk_free(chunk);
}

static void onsrc_end(sst_t* self) {
  end_src_called++;
  sst_free(self);
}

static void onuppertx_end(sst_t* self) {
  end_uppertx_called++;
  sst_free(self);
}

static void onreversetx_end(sst_t* self) {
  end_reversetx_called++;
  sst_free(self);
}

static void ondst_end(sst_t* self) {
  end_dst_called++;
  sst_free(self);
}

/* ------ Tests ------- */

void pipe_transform_stream() {
  setup();

  sst_t *src = sst_new();
  sst_t *tx = sst_new();
  src->end_cb  = onsrc_end;

  tx->write = upper_onwrite;
  tx->emit_cb = ondata;
  tx->end = onuppertx_end;

  sst_pipe(src, tx);

  src->write(src, sst_chunk_new("d0", NULL));
  t_ok(emit_count == 1, "after one write, one chunk was emitted");
  t_equal_str(emitted, "D0", "first emitted chunk is the one first emitted uppercased");
  free(emitted);

  src->write(src, sst_chunk_new("d1", NULL));
  t_ok(emit_count == 2, "after two writes, two chunks were emitted");
  t_equal_str(emitted, "D1", "second emitted chunk is the one second emitted uppercased");
  free(emitted);

  src->end(src);
  t_ok(end_src_called == 1, "end src is called exactly once after src stream was ended");
  t_ok(end_uppertx_called == 1, "end upper tx is called exactly once after src stream was ended");
}

void pipe_multi_transform_stream() {
  setup();

  sst_t *src       = sst_new();
  sst_t *uppertx   = sst_new();
  sst_t *reversetx = sst_new();
  sst_t *dst       = sst_new();

  src->end_cb  = onsrc_end;

  uppertx->write = upper_onwrite;
  uppertx->end_cb = onuppertx_end;

  reversetx->write = reverse_onwrite;
  reversetx->end_cb = onreversetx_end;

  dst->emit_cb = ondata;
  dst->end_cb = ondst_end;

  sst_pipe(src, uppertx, reversetx, dst);

  src->write(src, sst_chunk_new("d0", NULL));
  t_ok(emit_count == 1, "after one write, one chunk was emitted by dst");
  t_equal_str(emitted, "0D", "first emitted chunk is the one first emitted reversed and uppercased");
  free(emitted);

  src->write(src, sst_chunk_new("d1", NULL));
  t_ok(emit_count == 2, "after two writes, two chunks were emitted by dst");
  t_equal_str(emitted, "1D", "second emitted chunk is the one second emitted reversed and uppercased");
  free(emitted);

  src->end(src);
  t_ok(end_src_called == 1, "end src is called exactly once after src stream was ended");
  t_ok(end_uppertx_called == 1, "end upper tx is called exactly once after src stream was ended");
  t_ok(end_reversetx_called == 1, "end reverse tx is called exactly once after src stream was ended");
  t_ok(end_dst_called == 1, "end dst is called exactly once after src stream was ended");
}

int main(void) {
  test(pipe_transform_stream);
  test(pipe_multi_transform_stream);

  return 0;
}


text:
👍🎉 First off, thanks for taking the time to contribute! 🎉👍

With a project like this there is always room for improvement. You can view the [current issues here](https://github.com/pietertolsma/NodeChat/issues), or you can add your own features!

## Coding conventions

  To keep our code style consistent, we ask you to follow the following conventions:

  - We indent using single tabs.
  - We ALWAYS put spaces after list items and method parameters `([1, 2, 3]`, not `[1,2,3])`, around operators `(x += 1`, `not x+=1)`, and around hash arrows.
  - We put spaces before and after method parameters like so: `if (true) { .. then this}`.

## Submitting changes

If you are ready to send a pull request, you should just go for it! Please make your commit messages as clear as possible. Also make sure you add one feature per commit. Your request will be reviewed as soon as possible!

Thanks!

Pieter Tolsma


text:
<?php

namespace Api\Status\Services;

use Exception;
use Illuminate\Auth\AuthManager;
use Illuminate\Database\DatabaseManager;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Events\Dispatcher;

use Api\Status\Repositories\StatusRepository;

use Api\Status\Exceptions\StatusNotFoundException;
use Illuminate\Support\Facades\Auth;

use Carbon\Carbon;

class StatusService
{
    // Must be public because is used in Ratchet to reinit Auth
    // See ./app/RatchetServer.php function initStatus
    private $auth;

    private $database;

    private $dispatcher;

    private $statusRepository;

    public function __construct(
        AuthManager $auth,
        DatabaseManager $database,
        Dispatcher $dispatcher,
        StatusRepository $statusRepository
    ) {
        $this->auth = $auth;
        $this->database = $database;
        $this->dispatcher = $dispatcher;
        $this->statusRepository = $statusRepository;
    }

    public function create($data)
    {
        $this->database->beginTransaction();

        try {
            $data['user_uuid'] = Auth::user()->user_uuid;

            $dataObject = $this->statusRepository->getWhereArray($data)->first();

            if (empty($dataObject))
            {
              $dataObject = $this->statusRepository->create($data);

              // ~ $this->dispatcher->dispatch(new StatusWasCreated($dataObject));
            }
            else
            {
              $dataObject['message'] = __('Already exists. Nothing to be done');
            }

        } catch (Exception $e) {
            $this->database->rollBack();

            throw $e;
        }

        $this->database->commit();

        return $dataObject;
    }

    public function update($uuid, array $data)
    {
        $object = $this->findUserStatus($uuid);

        if (is_null($object)) {
            throw new StatusNotFoundException();
        }

        $this->database->beginTransaction();

        try {
            $this->statusRepository->update($object, $data);
        } catch (Exception $e) {
            $this->database->rollBack();

            throw $e;
        }

        $this->database->commit();

        return $object;
    }

    public function setStatus($data)
    {
      $this->database->beginTransaction();

      try {

        $data['user_uuid'] = Auth::user()->user_uuid;
        $data['domain_uuid'] = Auth::user()->domain_uuid;

        if (isset($data['services']))
        {
          sort($data['services']);

          $data['services'] = json_encode($data['services']);
        }

        $dataObject = $this->statusRepository->getWhereArray(['user_uuid' => $data['user_uuid'], 'domain_uuid' => $data['domain_uuid']])->first();

        if (empty($dataObject))
        {
          $return = $this->statusRepository->create($data);
        }
        else
        {
          $dataObject->touch();
          $return = $this->statusRepository->update($dataObject, $data);
        }

        // Remove all outdated statuses
        $deadTime = Carbon::now()->subSeconds(config('api.status_lifetime'));
        $Status = $this->statusRepository->getModel();
        $Status->where('updated_at', '<', $deadTime)->delete();
        /*
        $Status = $this->statusRepository->getModel();
        $available_statuses = $Status
              ->where('domain_uuid', $data['domain_uuid'])
              ->where('updated_at', '>=', $deadTime)
                // ~ ->where('user_uuid', '<>', $data['user_uuid'])
                ->get();
        */

      } catch (Exception $e) {
        $this->database->rollBack();
        throw $e;
      }

      $this->database->commit();

      return $return;

      $return = [];

      foreach ($available_statuses as $k => $status)
      {
        $ret = [];
        /*
        if (!isset($return[$status->user_uuid]))
        {
          $return[$status->user_uuid] = [];
        }
        */

        $services = json_decode($status->services);

        if (!isset($return[$status->user_uuid]['services']))
        {
          $return[$status->user_uuid]['services'] = $services;
        }
        else
        {
          $return[$status->user_uuid]['services'] = array_unique(array_merge($return[$status->user_uuid]['services'], $services), SORT_REGULAR);
        }

        if (!isset($return[$status->user_uuid]['user_status']))
        {
          $return[$status->user_uuid]['user_status'] = $status->user_status;
        }
        else
        {
          $conf_statuses = config('api.statuses');
          if ($conf_statuses[$return[$status->user_uuid]['user_status']] <= $conf_statuses[$status->user_status])
          {
            // Leave old status
          }
          else
          {
            $return[$status->user_uuid]['user_status'] = $status->user_status;
          }

        }

      }

      return $return;
    }

    public function findUserStatus($user_uuid)
    {
      return $this->statusRepository->setOrdering('updated_at', 'DESC')->getWhere('user_uuid', $user_uuid)->first();
    }
}


text:
package org.keycloak.models.map.storage.hotRod.common;

import org.infinispan.query.dsl.Query;

/**
 * @author Martin Kanis
 */
public class HotRodUtils {

    public static final int DEFAULT_MAX_RESULTS = Integer.MAX_VALUE >> 1;

    public static <T> Query<T> paginateQuery(Query<T> query, Integer first, Integer max) {
        if (first != null && first > 0) {
            query = query.startOffset(first);

            // workaround because of ISPN-13702 bug, see https://github.com/keycloak/keycloak/issues/10090
            if (max == null || max < 0) {
                max = DEFAULT_MAX_RESULTS;
            }
        }

        if (max != null && max >= 0) {
            query = query.maxResults(max);
        }

        return query;
    }
}


text:
package jigg.nlp.ccg

import java.io.FileWriter

import scala.collection.mutable.ArrayBuffer
import scala.sys.process.Process
import scala.collection.mutable.HashMap

import lexicon._

import breeze.config.CommandLineParser

object OutputCategoryList {

  case class Params(
    bank: Opts.BankInfo,
    dict: Opts.DictParams
  )

  case class CategoryInfo(sentence: GoldSuperTaggedSentence, position: Int, num: Int = 1) {
    def increment(): CategoryInfo = this.copy(num = num + 1)
    def replace(_sentence: GoldSuperTaggedSentence, _p: Int) =
      CategoryInfo(_sentence, _p, num + 1)
  }

  def main(args:Array[String]) = {

    val params = CommandLineParser.readIn[Params](args)

    val dict = new JapaneseDictionary(params.dict.categoryDictinoary)
    val bank = CCGBank.select(params.bank, dict)

    val trainSentences: Array[GoldSuperTaggedSentence] = bank.trainSentences

    val stats = new HashMap[Category, CategoryInfo]

    trainSentences foreach { sentence =>
      (0 until sentence.size) foreach { i =>
        val cat = sentence.cat(i)
        stats.get(cat) match {
          case Some(info) =>
            if (sentence.size > info.sentence.size)
              stats += ((cat, info.replace(sentence, i)))
            else
              stats += ((cat, info.increment()))
          case None => stats += ((cat, CategoryInfo(sentence, i)))
          case _ =>
        }
      }
    }
    def highlight(sentence: Sentence, i: Int) = {
      val tokens = sentence.wordSeq
      // tokens.take(i).mkString("") + s"\\x1b[1;31m{${tokens(i)}}\\x1b[0m" + tokens.drop(i+1).mkString("")
      tokens.slice(i-5, i).mkString("") + s"${tokens(i)}" + tokens.slice(i+1, i+6).mkString("")
    }

    var fw = new FileWriter("./category.lst")
    stats.toSeq.sortBy(_._2.num).reverse.foreach {
      case (cat, CategoryInfo(sentence, i, num)) =>
        fw.write("%s\t%s\t%s\t%s\n"
          .format(num, cat, sentence.pos(i), highlight(sentence, i)))
    }
    fw.flush
    fw.close

    val noFeatureCategories = new HashMap[String, CategoryInfo]
    stats foreach { case (cat, CategoryInfo(sentence, i, numWithFeat)) =>
      val noFeature = cat.toStringNoFeature
      noFeatureCategories.get(noFeature) match {
        case Some(exist) =>
          val newNum = numWithFeat + exist.num
          val newInfo = exist.copy(num = newNum)
          noFeatureCategories += (noFeature -> newInfo)
        case None =>
          noFeatureCategories += (noFeature -> CategoryInfo(sentence, i, numWithFeat))
        case _ =>
      }
    }

    fw = new FileWriter("./category.nofeature.lst")
    noFeatureCategories.toSeq.sortBy(_._2.num).reverse.foreach {
      case (cat, CategoryInfo(sentence, i, num)) =>
        fw.write("%s\t%s\t%s\t%s\n"
          .format(num, cat, sentence.pos(i), highlight(sentence, i)))
    }
    fw.flush
    fw.close
  }
}


text:
#include "stdafx.h"
#include "EOSAIPlayerData.h"
//#include "EOSAISerial2.h"
#include "EOSAISerial.h"
#include "EOSAIMath.h"

using namespace EOSAI;

CPlayerData::CPlayerData( long iPlayer, long iAIBrainIntelligence )
{
	ASSERT( false );

	m_iPlayer = iPlayer;
	m_iAIBrainIntelligence = iAIBrainIntelligence;
	m_bFlag_ShutdownAIPlayer = false;

	/*
	m_fPersonality_HoldsGrudges01 = 0.0f;
	m_fPersonality_Aggressive01 = 0.0f;
	m_fPersonality_Fortifier01 = 0.0f;
	m_fPersonality_Builder01 = 0.0f;
	m_fPersonality_ProResearcherPos1_AntiResearcherNeg1 = 0.0f;
	m_fPersonality_ProSubmarine01 = 0.0f;
	//
	m_fPersonality_ProAirUnit11 = 0.0f;
	m_fPersonality_ProGroundUnit11 = 0.0f;
	m_fPersonality_ProSeaUnit11 = 0.0f;
	//
	m_fPersonality_ProStrategicBombing01 = 0.0f;
	m_fPersonality_ProMissile01 = 0.0f;
	m_fPersonality_ProArtillery01 = 0.0f;
	m_fPersonality_ProExpensiveShipsPos1_CheapShipsNeg1 = 0.0f; // 1.0 = Battleships, 0.0 = Destroyers
	m_fPersonality_ProUnitDiversity01 = 0.0f;
	*/
	m_fPersonality_HoldsGrudges01 = CEOSAIMath::GetRandomFloat( 0.4f,0.6f ); // 0.5f;
	m_fPersonality_Aggressive01 = CEOSAIMath::GetRandomFloat( 0.2f,0.3f )+CEOSAIMath::GetRandomFloat( 0.2f,0.4f ); // 0.4-0.7
	m_fPersonality_Fortifier01 = CEOSAIMath::GetRandomFloat( 0.3f,0.5f );//0.5f;
	m_fPersonality_Builder01 = CEOSAIMath::GetRandomFloat( 0.1f,0.4f )+CEOSAIMath::GetRandomFloat( 0.1f,0.4f ); // 0.5f;
	m_fPersonality_ProResearcherPos1_AntiResearcherNeg1 = CEOSAIMath::GetRandomFloat( 0.0f,0.5f );//0.25f; + CEOSAIMath::GetRandomFloat( 0.0f,0.5f );
	m_fPersonality_ProSubmarine01 = CEOSAIMath::GetRandomFloat( -0.1f,0.2f );
	if( m_fPersonality_ProSubmarine01 < 0.0f ){ m_fPersonality_ProSubmarine01 = 0.0f; }
	//m_fPersonality_ProAircraftPos1_ProGroundSeaNeg1 = -0.3f; // 0.0 = no influence
	m_fPersonality_ProAirUnit11 = -0.3f;
	m_fPersonality_ProGroundUnit11 = 0.2f;
	m_fPersonality_ProSeaUnit11 = CEOSAIMath::GetRandomFloat( 0.3f,0.5f ); // 0.2 - 0.5

	m_fPersonality_ProStrategicBombing01 = 0.0f;    // 0.0 = no influence
	m_fPersonality_ProMissile01 = 0.0f;             // 0.0 = no influence
	m_fPersonality_ProArtillery01 = 0.0f;           // 0.0 = no influence
	m_fPersonality_ProExpensiveShipsPos1_CheapShipsNeg1 = CEOSAIMath::GetRandomFloat( -0.2f,+0.1f ); // 0.0 = no influence
	m_fPersonality_ProUnitDiversity01 = CEOSAIMath::GetRandomFloat( 0.1f,0.3f );//0.2f;

	//m_iRand = 0; // changes each turn

	// AICheats
	//
		m_bAICheat_KnowsMapAndPoiInformation = false;

		// Setting up the default cheats.  These values can be changed after calling the constructor.
		m_fAICheat_FreeResearchPoints = 0.0f;
		if( iAIBrainIntelligence == 1 ) m_fAICheat_FreeResearchPoints = -2.0f; // this is a penalty
		if( iAIBrainIntelligence == 2 ) m_fAICheat_FreeResearchPoints = +0.0f;
		if( iAIBrainIntelligence == 3 ) m_fAICheat_FreeResearchPoints = +2.5f;

		m_fAICheat_CityProductionMultiplier = 1.0f;
		if( m_iAIBrainIntelligence == 1 ){ m_fAICheat_CityProductionMultiplier = 0.7f; } // this is a penalty
		if( m_iAIBrainIntelligence == 2 ){ m_fAICheat_CityProductionMultiplier = 1.0f; }
		if( m_iAIBrainIntelligence == 3 ){ m_fAICheat_CityProductionMultiplier = 1.3f; }

		m_fAICheat_LikesAIPlayers = 0.0f;
		if( m_iAIBrainIntelligence == 1 ){ m_fAICheat_LikesAIPlayers = -0.03f; } // Novice AI tends to prefer attacking other AIs
		if( m_iAIBrainIntelligence == 2 ){ m_fAICheat_LikesAIPlayers = 0.0f; }
		if( m_iAIBrainIntelligence == 3 ){ m_fAICheat_LikesAIPlayers = 0.0f; }

		m_fAICheat_LikesHumanPlayers = 0.0f;
		if( m_iAIBrainIntelligence == 1 ){ m_fAICheat_LikesHumanPlayers = 0.0f; }
		if( m_iAIBrainIntelligence == 2 ){ m_fAICheat_LikesHumanPlayers = -0.03f; }
		if( m_iAIBrainIntelligence == 3 ){ m_fAICheat_LikesHumanPlayers = -0.06f; } // Elite AI tends to prefer attacking humans

		m_fAICheat_AttackMultiplierAgainstMilitia = 1.0f;
		if( m_iAIBrainIntelligence == 1 ){ m_fAICheat_AttackMultiplierAgainstMilitia = 1.0f; }
		if( m_iAIBrainIntelligence == 2 ){ m_fAICheat_AttackMultiplierAgainstMilitia = 1.4f; }
		if( m_iAIBrainIntelligence == 3 ){ m_fAICheat_AttackMultiplierAgainstMilitia = 2.0f; } // Elite AI tends to prefer attacking humans

}

// Serialize/Deserialize
void  CPlayerData::Serialize( CEOSAISerial* pSerial )
{
	char iVersion = 4;
	pSerial->Serialize( iVersion ); // Version

	pSerial->Serialize( m_iNextAIMailId );
	pSerial->Serialize( m_iAIBrainIntelligence );

	pSerial->Serialize( m_fPersonality_HoldsGrudges01 );
	pSerial->Serialize( m_fPersonality_Aggressive01 );
	pSerial->Serialize( m_fPersonality_Fortifier01 );
	pSerial->Serialize( m_fPersonality_Builder01 );
	pSerial->Serialize( m_fPersonality_ProResearcherPos1_AntiResearcherNeg1 );
	pSerial->Serialize( m_fPersonality_ProSubmarine01 );
	/*
	if( iVersion <= 3 )
	{
		pSerial->Serialize( m_fPersonality_ProAircraftPos1_ProGroundSeaNeg1 );
	}
	*/
	if( iVersion >= 4 )
	{
		pSerial->Serialize( m_fPersonality_ProAirUnit11 );
		pSerial->Serialize( m_fPersonality_ProGroundUnit11 );
		pSerial->Serialize( m_fPersonality_ProSeaUnit11 );
	}
	pSerial->Serialize( m_fPersonality_ProStrategicBombing01 );
	pSerial->Serialize( m_fPersonality_ProMissile01 );
	pSerial->Serialize( m_fPersonality_ProArtillery01 );
	pSerial->Serialize( m_fPersonality_ProExpensiveShipsPos1_CheapShipsNeg1 );
	pSerial->Serialize( m_fPersonality_ProUnitDiversity01 );
}

void  CPlayerData::Deserialize( CEOSAISerial* pSerial )
{
	char iVersion = 0;
	pSerial->Deserialize( iVersion );

	//long iProcessingState = (long) m_eProcessingState;
	//pSerial->Deserialize( iProcessingState );
	//m_eProcessingState = (EnumState) iProcessingState;
	// If we are deserializing, then we are loading a game.
	//   If we are loading a game, then restart the processing
	//m_eProcessingState = enumWaitingForAutosaveAndLocalPlayerTurnReplayEnd;
	m_eProcessingState = enumBeginProcessingTurn;

	pSerial->Deserialize( m_iNextAIMailId );
	pSerial->Deserialize( m_iAIBrainIntelligence );

	if( iVersion == 3 )
	{
		pSerial->Deserialize( m_fPersonality_HoldsGrudges01 );
		pSerial->Deserialize( m_fPersonality_Aggressive01 );
		pSerial->Deserialize( m_fPersonality_Fortifier01 );
		pSerial->Deserialize( m_fPersonality_Builder01 );
		pSerial->Deserialize( m_fPersonality_ProResearcherPos1_AntiResearcherNeg1 );
		pSerial->Deserialize( m_fPersonality_ProSubmarine01 );

		float fPersonality_ProAircraftPos1_ProGroundSeaNeg1 = 0.0f;
		pSerial->Deserialize( fPersonality_ProAircraftPos1_ProGroundSeaNeg1 );
		m_fPersonality_ProAirUnit11 = fPersonality_ProAircraftPos1_ProGroundSeaNeg1;
		m_fPersonality_ProGroundUnit11 = 1.0f-fPersonality_ProAircraftPos1_ProGroundSeaNeg1;
		m_fPersonality_ProSeaUnit11 = 1.0f-fPersonality_ProAircraftPos1_ProGroundSeaNeg1;

		pSerial->Deserialize( m_fPersonality_ProStrategicBombing01 );
		pSerial->Deserialize( m_fPersonality_ProMissile01 );
		pSerial->Deserialize( m_fPersonality_ProArtillery01 );
		pSerial->Deserialize( m_fPersonality_ProExpensiveShipsPos1_CheapShipsNeg1 );
		pSerial->Deserialize( m_fPersonality_ProUnitDiversity01 );
	}
	if( iVersion >= 4 )
	{
		pSerial->Deserialize( m_fPersonality_HoldsGrudges01 );
		pSerial->Deserialize( m_fPersonality_Aggressive01 );
		pSerial->Deserialize( m_fPersonality_Fortifier01 );
		pSerial->Deserialize( m_fPersonality_Builder01 );
		pSerial->Deserialize( m_fPersonality_ProResearcherPos1_AntiResearcherNeg1 );
		pSerial->Deserialize( m_fPersonality_ProSubmarine01 );

		pSerial->Deserialize( m_fPersonality_ProAirUnit11 );
		pSerial->Deserialize( m_fPersonality_ProGroundUnit11 );
		pSerial->Deserialize( m_fPersonality_ProSeaUnit11 );

		pSerial->Deserialize( m_fPersonality_ProStrategicBombing01 );
		pSerial->Deserialize( m_fPersonality_ProMissile01 );
		pSerial->Deserialize( m_fPersonality_ProArtillery01 );
		pSerial->Deserialize( m_fPersonality_ProExpensiveShipsPos1_CheapShipsNeg1 );
		pSerial->Deserialize( m_fPersonality_ProUnitDiversity01 );
	}
}


text:
<?php defined("SYSPATH") or die("No direct script access.") ?>

      <?php echo $form ?>

    <?php if (identity::is_writable() && !module::get_var("gallery", "maintenance_mode")): ?>

      <?php echo t("Forgot your password?") ?>

    <?php endif ?>


text:
layout: post
title:  "Ma première toile"
date:   2014-06-09 15:41:34
categories: impressionisme
author: Lucie Bergeron
image: /images/intro.jpg
---
Description de la toile.


text:
/*
FUNCTION
<<fdopen>>---turn open file into a stream

INDEX
	fdopen
INDEX
	_fdopen_r

ANSI_SYNOPSIS
	#include <stdio.h>
	FILE *fdopen(int <[fd]>, const char *<[mode]>);
	FILE *_fdopen_r(struct _reent *<[reent]>,
                        int <[fd]>, const char *<[mode]>);

TRAD_SYNOPSIS
	#include <stdio.h>
	FILE *fdopen(<[fd]>, <[mode]>)
	int <[fd]>;
	char *<[mode]>;

	FILE *_fdopen_r(<[reent]>, <[fd]>, <[mode]>)
	struct _reent *<[reent]>;
        int <[fd]>;
	char *<[mode]>);

DESCRIPTION
<<fdopen>> produces a file descriptor of type <<FILE *>>, from a
descriptor for an already-open file (returned, for example, by the
system subroutine <<open>> rather than by <<fopen>>).
The <[mode]> argument has the same meanings as in <<fopen>>.

RETURNS
File pointer or <<NULL>>, as for <<fopen>>.

PORTABILITY
<<fdopen>> is ANSI.
*/

#include <_ansi.h>
#include <reent.h>
#include <sys/types.h>
#include <sys/fcntl.h>
#include <stdio.h>
#include <errno.h>
#include "local.h"
#include <_syslist.h>

FILE *
_DEFUN(_fdopen_r, (ptr, fd, mode),
       struct _reent *ptr _AND
       int fd             _AND
       _CONST char *mode)
{
  register FILE *fp;
  int flags, oflags;
#ifdef HAVE_FCNTL
  int fdflags, fdmode;
#endif

  if ((flags = __sflags (ptr, mode, &oflags)) == 0)
    return 0;

  /* make sure the mode the user wants is a subset of the actual mode */
#ifdef HAVE_FCNTL
  if ((fdflags = _fcntl_r (ptr, fd, F_GETFL, 0)) < 0)
    return 0;
  fdmode = fdflags & O_ACCMODE;
  if (fdmode != O_RDWR && (fdmode != (oflags & O_ACCMODE)))
    {
      ptr->_errno = EBADF;
      return 0;
    }
#endif

  if ((fp = __sfp (ptr)) == 0)
    return 0;

  _flockfile (fp);

  fp->_flags = flags;
  /* POSIX recommends setting the O_APPEND bit on fd to match append
     streams.  Someone may later clear O_APPEND on fileno(fp), but the
     stream must still remain in append mode.  Rely on __sflags
     setting __SAPP properly.  */
#ifdef HAVE_FCNTL
  if ((oflags & O_APPEND) && !(fdflags & O_APPEND))
    _fcntl_r (ptr, fd, F_SETFL, fdflags | O_APPEND);
#endif
  fp->_file = fd;
  fp->_cookie = (_PTR) fp;

#undef _read
#undef _write
#undef _seek
#undef _close

  fp->_read = __sread;
  fp->_write = __swrite;
  fp->_seek = __sseek;
  fp->_close = __sclose;

#ifdef __SCLE
  /* Explicit given mode results in explicit setting mode on fd */
  if (oflags & O_BINARY)
    setmode (fp->_file, O_BINARY);
  else if (oflags & O_TEXT)
    setmode (fp->_file, O_TEXT);
  if (__stextmode (fp->_file))
    fp->_flags |= __SCLE;
#endif

  _funlockfile (fp);
  return fp;
}

#ifndef _REENT_ONLY

FILE *
_DEFUN(fdopen, (fd, mode),
       int fd _AND
       _CONST char *mode)
{
  return _fdopen_r (_REENT, fd, mode);
}

#endif


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Chamaecyparis lawsoniana f. columnaris

### Remarks
null


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

namespace SudokuSolver.Core.Models
{
    /// <summary>
    /// Class used to represent a single solution of a sudoku.
    /// </summary>
    partial class Solution
    {
        #region Static Properties

        /// <summary>
        /// Specifies the dimension of the array representing the sudoku.
        /// </summary>
        //static private int _dimension;
        public static int Dimension { get; private set; }
        //{
        //    get { return _dimension; }
        //}
        #endregion

        #region Properties

        /// <summary>
        /// Specifies the state of the sudoku. Like UNSOLVED, SOLVED, etc
        /// </summary>
        private SudokuState _sudokuState;

        public SudokuState SudokuState
        {
            get { return _sudokuState; }
            set { _sudokuState = value; }
        }

        /// <summary>
        /// Specifies the type of sudoku.
        /// </summary>
        private SudokuType _sudokuType;

        /// <summary>
        /// The internal array of cells of the sudoku.
        /// </summary>
        private Cell[] _cellList;

        /// <summary>
        /// The internal list of groups defining the different groups of the sudoku. Can be rows, columns, etc.
        /// </summary>
        private List<Group> _groupList;

        #endregion

        #region Constructors

        /// <summary>
        /// Constructor with the type of the sudoku as parameters.
        /// </summary>
        /// <param name="sudokuType">The type of the sudoku</param>
        public Solution(SudokuType sudokuType)
        {
            _sudokuType = sudokuType;
            _groupList = new List<Group>();

            CreateSudoku();
        }
        #endregion

        /// <summary>
        /// Resets the sudoku.
        /// </summary>
        public void Reset()
        {
            CreateSudoku();
        }

        /// <summary>
        /// Checks the state of the sudoku and alters the _sudokuState variable.
        /// </summary>
        public void CheckState()
        {
            // Check in each group for doubles and empties
            bool emptyCell = false;
            bool doubleValue = false;
            int[] filledValue;

            for (int gId = 0; gId < this._groupList.Count; gId++) {
                filledValue = new int[Candidate.PossibleCandidateCount];
                foreach (int cId in this._groupList[gId].Cells)
                    if (this._cellList[cId].Value == Candidate.NotSet)
                        emptyCell = true;
                    else
                        filledValue[this._cellList[cId].Value]++;
                foreach (int v in filledValue)
                    if (v > 1) doubleValue = true;
            }

            if (!emptyCell && !doubleValue)
                _sudokuState = SudokuState.Solved;
            else if (doubleValue)
                _sudokuState = SudokuState.Broken;
            else if (emptyCell)
                _sudokuState = SudokuState.Unsolved;
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plugin PUBLIC "-//JPF//Java Plug-in Manifest 1.0" "http://jpf.sourceforge.net/plugin_1_0.dtd">
<plugin id="com.tle.web.wizard.page" version="1">
  <extension-point id="pageFactory">
    <parameter-def id="bean" multiplicity="one" />
  </extension-point>
</plugin>


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace BRSTMConverter {
	public partial class HTMLViewer : Form {
		public HTMLViewer(string url) {
			InitializeComponent();
			string curDir = Directory.GetCurrentDirectory();
			if (!url.StartsWith("http://")) {
				this.webBrowser1.Url = new Uri(String.Format("file:///{0}/" + url, curDir));
			} else {
				this.webBrowser1.Url = new Uri(url);
			}
		}
	}
}


text:
require_relative '../../../spec_helper'
require 'rexml/document'

describe "REXML::Attributes#namespaces" do
  it "needs to be reviewed for spec completeness"
end


text:
var Sammy = require("./errorsOnImportedSymbol_0");
var x = new Sammy.Sammy();
var y = Sammy.Sammy();


text:
#import <Mail/MFMessageSortingValue.h>

@class MFMailbox;

@interface _MFMessageSortingValueMailbox : MFMessageSortingValue
{
    MFMailbox *_mailbox;
}

- (id)description;
- (void)setMailbox:(id)arg1;
- (id)mailbox;
- (void)dealloc;

@end


text:
<!DOCTYPE html>

<title>File_deleteFile_onerror_TypeMismatch</title>


text:
Fetch dependencies:

```
npm install
```

Build example:
```
grunt auto-build
```

Run tests:

```
grunt auto-test
```


text:
package io.grpc.examples.manualflowcontrol;

import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.Status;
import io.grpc.stub.ServerCallStreamObserver;
import io.grpc.stub.StreamObserver;

import java.io.IOException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Logger;

public class ManualFlowControlServer {
  private static final Logger logger =
      Logger.getLogger(ManualFlowControlServer.class.getName());

  public static void main(String[] args) throws InterruptedException, IOException {
    // Service class implementation
    StreamingGreeterGrpc.StreamingGreeterImplBase svc = new StreamingGreeterGrpc.StreamingGreeterImplBase() {
      @Override
      public StreamObserver<HelloRequest> sayHelloStreaming(final StreamObserver<HelloReply> responseObserver) {
        // Set up manual flow control for the request stream. It feels backwards to configure the request
        // stream's flow control using the response stream's observer, but this is the way it is.
        final ServerCallStreamObserver<HelloReply> serverCallStreamObserver =
            (ServerCallStreamObserver<HelloReply>) responseObserver;
        serverCallStreamObserver.disableAutoInboundFlowControl();

        // Guard against spurious onReady() calls caused by a race between onNext() and onReady(). If the transport
        // toggles isReady() from false to true while onNext() is executing, but before onNext() checks isReady(),
        // request(1) would be called twice - once by onNext() and once by the onReady() scheduled during onNext()'s
        // execution.
        final AtomicBoolean wasReady = new AtomicBoolean(false);

        // Set up a back-pressure-aware consumer for the request stream. The onReadyHandler will be invoked
        // when the consuming side has enough buffer space to receive more messages.
        //
        // Note: the onReadyHandler's invocation is serialized on the same thread pool as the incoming StreamObserver's
        // onNext(), onError(), and onComplete() handlers. Blocking the onReadyHandler will prevent additional messages
        // from being processed by the incoming StreamObserver. The onReadyHandler must return in a timely manor or else
        // message processing throughput will suffer.
        serverCallStreamObserver.setOnReadyHandler(new Runnable() {
          public void run() {
            if (serverCallStreamObserver.isReady() && wasReady.compareAndSet(false, true)) {
              logger.info("READY");
              // Signal the request sender to send one message. This happens when isReady() turns true, signaling that
              // the receive buffer has enough free space to receive more messages. Calling request() serves to prime
              // the message pump.
              serverCallStreamObserver.request(1);
            }
          }
        });

        // Give gRPC a StreamObserver that can observe and process incoming requests.
        return new StreamObserver<HelloRequest>() {
          @Override
          public void onNext(HelloRequest request) {
            // Process the request and send a response or an error.
            try {
              // Accept and enqueue the request.
              String name = request.getName();
              logger.info("--> " + name);

              // Simulate server "work"
              Thread.sleep(100);

              // Send a response.
              String message = "Hello " + name;
              logger.info("<-- " + message);
              HelloReply reply = HelloReply.newBuilder().setMessage(message).build();
              responseObserver.onNext(reply);

              // Check the provided ServerCallStreamObserver to see if it is still ready to accept more messages.
              if (serverCallStreamObserver.isReady()) {
                // Signal the sender to send another request. As long as isReady() stays true, the server will keep
                // cycling through the loop of onNext() -> request()...onNext() -> request()... until either the client
                // runs out of messages and ends the loop or the server runs out of receive buffer space.
                //
                // If the server runs out of buffer space, isReady() will turn false. When the receive buffer has
                // sufficiently drained, isReady() will turn true, and the serverCallStreamObserver's onReadyHandler
                // will be called to restart the message pump.
                serverCallStreamObserver.request(1);
              } else {
                // If not, note that back-pressure has begun.
                wasReady.set(false);
              }
            } catch (Throwable throwable) {
              throwable.printStackTrace();
              responseObserver.onError(
                  Status.UNKNOWN.withDescription("Error handling request").withCause(throwable).asException());
            }
          }

          @Override
          public void onError(Throwable t) {
            // End the response stream if the client presents an error.
            t.printStackTrace();
            responseObserver.onCompleted();
          }

          @Override
          public void onCompleted() {
            // Signal the end of work when the client ends the request stream.
            logger.info("COMPLETED");
            responseObserver.onCompleted();
          }
        };
      }
    };

    final Server server = ServerBuilder
        .forPort(50051)
        .addService(svc)
        .build()
        .start();

    logger.info("Listening on " + server.getPort());

    Runtime.getRuntime().addShutdownHook(new Thread() {
      @Override
      public void run() {
        logger.info("Shutting down");
        server.shutdown();
      }
    });
    server.awaitTermination();
  }
}


text:
package quarks.connectors.jdbc;

import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * Function that sets parameters in a JDBC SQL {@link java.sql.PreparedStatement}.
 *
 * @param <T> stream tuple type
 */
@FunctionalInterface
public interface ParameterSetter<T> {
    /**
     * Set 0 or more parameters in a JDBC PreparedStatement.
     *

     * Sample use for a PreparedStatement of:
     *

     * {@code "SELECT id, firstname, lastname FROM persons WHERE id = ?"}
     *
{@code
     * ParameterSetter<PersonId> ps = (personId,stmt) -> stmt.setInt(1, personId.getId());
     * }

     *
     * @param t stream tuple of type T
     * @param stmt PreparedStatement
     * @throws SQLException
     */
    void setParameters(T t, PreparedStatement stmt) throws SQLException;
}


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

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/done"
        android:showAsAction="always"
        android:title="@string/done" />
</menu>


text:
namespace google_breakpad {

LogStream::LogStream(std::ostream &stream, Severity severity,
                     const char *file, int line)
    : stream_(stream) {
  time_t clock;
  time(&clock);
  struct tm tm_struct;
  localtime_r(&clock, &tm_struct);
  char time_string[20];
  strftime(time_string, sizeof(time_string), "%Y-%m-%d %H:%M:%S", &tm_struct);

  const char *severity_string = "UNKNOWN_SEVERITY";
  switch (severity) {
    case SEVERITY_INFO:
      severity_string = "INFO";
      break;
    case SEVERITY_ERROR:
      severity_string = "ERROR";
      break;
  }

  stream_ << time_string << ": " << PathnameStripper::File(file) << ":" <<
             line << ": " << severity_string << ": ";
}

LogStream::~LogStream() {
  stream_ << std::endl;
}

std::string HexString(u_int32_t number) {
  char buffer[11];
  snprintf(buffer, sizeof(buffer), "0x%x", number);
  return std::string(buffer);
}

std::string HexString(u_int64_t number) {
  char buffer[19];
  snprintf(buffer, sizeof(buffer), "0x%" PRIx64, number);
  return std::string(buffer);
}

std::string HexString(int number) {
  char buffer[19];
  snprintf(buffer, sizeof(buffer), "0x%x", number);
  return std::string(buffer);
}

int ErrnoString(std::string *error_string) {
  assert(error_string);

  // strerror isn't necessarily thread-safe.  strerror_r would be preferrable,
  // but GNU libc uses a nonstandard strerror_r by default, which returns a
  // char* (rather than an int success indicator) and doesn't necessarily
  // use the supplied buffer.
  error_string->assign(strerror(errno));
  return errno;
}

}  // namespace google_breakpad


text:
package containeranalysis

import (
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

// isAttestationExistsErr returns true if the passed Error is an "AlreadyExists" gRPC error.
func isAttestionExistsErr(err error) bool {
	if nil == err {
		return false
	}

	return (codes.AlreadyExists == status.Code(err))
}


text:
package org.jboss.seam.faces.test.server.projectstage;

import static junit.framework.Assert.assertEquals;

import javax.enterprise.inject.spi.BeanManager;
import javax.inject.Inject;

import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.seam.faces.projectstage.ProjectStageExtension;
import org.jboss.seam.faces.test.server.projectstage.beans.DevelopmentStageBean;
import org.jboss.seam.faces.test.server.projectstage.beans.NoStageRestrictionBean;
import org.jboss.seam.faces.test.server.projectstage.beans.ProductionStageBean;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;

/**
 *
 * This tests checks if the {@link ProjectStageExtension} works correctly if no project stage can be detected. In this case the
 * extension assumes the Production stage.
 *
 * @author Christian Kaltepoth <christian@kaltepoth.de>
 *
 */
@RunWith(Arquillian.class)
public class DefaultProjectStageExtensionTest {

    @Deployment
    public static WebArchive createTestArchive() {
        return ProjectStageBaseArchive.getBaseArchive()
                .addClasses(DevelopmentStageBean.class, ProductionStageBean.class, NoStageRestrictionBean.class);
    }

    @Inject
    private BeanManager beanManager;

    @Test
    public void testActivatedBeansInDevelopmentStageFromWebXml() {

        // The @Development annotated bean is vetoed, all others will be active
        assertEquals(0, beanManager.getBeans(DevelopmentStageBean.class).size());
        assertEquals(1, beanManager.getBeans(ProductionStageBean.class).size());
        assertEquals(1, beanManager.getBeans(NoStageRestrictionBean.class).size());

    }

}


text:
```php
use Artisanry\Database\Repositories\BaseRepository;

class UserRepository extends BaseRepository
{
    public function getModelClass()
    {
        return \App\User::class;
    }
}
```


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information

namespace DotNetNuke.Entities.Profile
{
    using System;
    using System.Collections.Generic;
    using System.Globalization;
    using System.Text;

    using DotNetNuke.Entities.Users;
    using DotNetNuke.Entities.Users.Social;
    using DotNetNuke.Security.Roles;

    [Serializable]
    public class ProfileVisibility
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="ProfileVisibility"/> class.
        /// </summary>
        public ProfileVisibility()
        {
            this.RoleVisibilities = new List<RoleInfo>();
            this.RelationshipVisibilities = new List<Relationship>();
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="ProfileVisibility"/> class.
        /// </summary>
        /// <param name="portalId"></param>
        /// <param name="extendedVisibility"></param>
        public ProfileVisibility(int portalId, string extendedVisibility)
            : this()
        {
            if (!string.IsNullOrEmpty(extendedVisibility))
            {
                var relationshipController = new RelationshipController();

                var lists = extendedVisibility.Split(';');

                if (!string.IsNullOrEmpty(lists[0].Substring(2).TrimEnd(',')))
                {
                    var roles = lists[0].Substring(2).TrimEnd(',').Split(',');
                    foreach (var role in roles)
                    {
                        int roleId = int.Parse(role);
                        RoleInfo userRole = RoleController.Instance.GetRole(portalId, r => r.RoleID == roleId);
                        this.RoleVisibilities.Add(userRole);
                    }
                }

                if (!string.IsNullOrEmpty(lists[1].Substring(2).TrimEnd(',')))
                {
                    var relationships = lists[1].Substring(2).TrimEnd(',').Split(',');
                    foreach (var relationship in relationships)
                    {
                        Relationship userRelationship = RelationshipController.Instance.GetRelationship(int.Parse(relationship));
                        this.RelationshipVisibilities.Add(userRelationship);
                    }
                }
            }
        }

        public UserVisibilityMode VisibilityMode { get; set; }

        public IList<RoleInfo> RoleVisibilities { get; set; }

        public IList<Relationship> RelationshipVisibilities { get; set; }

        public ProfileVisibility Clone()
        {
            var pv = new ProfileVisibility()
            {
                VisibilityMode = this.VisibilityMode,
                RoleVisibilities = new List<RoleInfo>(this.RoleVisibilities),
                RelationshipVisibilities = new List<Relationship>(this.RelationshipVisibilities),
            };
            return pv;
        }

        public string ExtendedVisibilityString()
        {
            if (this.VisibilityMode == UserVisibilityMode.FriendsAndGroups)
            {
                var sb = new StringBuilder();
                sb.Append("G:");
                foreach (var role in this.RoleVisibilities)
                {
                    sb.Append(role.RoleID.ToString(CultureInfo.InvariantCulture) + ",");
                }

                sb.Append(";R:");
                foreach (var relationship in this.RelationshipVisibilities)
                {
                    sb.Append(relationship.RelationshipId.ToString(CultureInfo.InvariantCulture) + ",");
                }

                return sb.ToString();
            }

            return string.Empty;
        }
    }
}


text:
package ru.valle.router;

import java.io.*;
import java.net.*;
import java.util.Base64;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Locale;

public class Main {

    public static void main(String[] args) {
        try {
            String routerAddress;
            String login;
            String password;
            if (args.length == 0 || args[0] == null) {
                System.out.println("No router's address was set, trying \"192.168.1.1\"");
                routerAddress = "192.168.1.1";
            } else {
                routerAddress = args[0];
            }
            if (!routerAddress.toLowerCase(Locale.US).startsWith("http")) {
                routerAddress = "http://" + routerAddress;
            }
            if (!routerAddress.endsWith("/")) {
                routerAddress += "/";
            }
            if (args.length <= 1 || args[1] == null) {
                System.out.println("No username set, trying \"admin\"");
                login = "admin";
            } else {
                login = args[1];
            }
            if (args.length <= 2 || args[2] == null) {
                System.out.println("No password set, trying \"admin\"");
                password = "admin";
            } else {
                password = args[2];
            }
            try {
                HttpURLConnection connectionLoc = (HttpURLConnection) new URL(routerAddress + "HNAP1/").openConnection();
                int httpCode = connectionLoc.getResponseCode();
                String apiResponse = new String(readAll(connectionLoc.getInputStream()), "UTF-8");
                if (httpCode != 200 || !apiResponse.contains("HNAP1")) {
                    System.err.println("No HNAP1 interface found for " + routerAddress + "HNAP1/");
                    return;
                }
            } catch (Exception e) {
                System.err.println("No HNAP1 interface found for " + routerAddress + "HNAP1/ because of " + e);
                return;
            }

            Enumeration<NetworkInterface> nInterfaces = NetworkInterface.getNetworkInterfaces();
            HashSet<String> macAddresses = new HashSet<String>();
            while (nInterfaces.hasMoreElements()) {
                Enumeration<InetAddress> inetAddresses = nInterfaces.nextElement().getInetAddresses();
                while (inetAddresses.hasMoreElements()) {
                    String address = inetAddresses.nextElement().getHostAddress();
                    NetworkInterface network = NetworkInterface.getByInetAddress(InetAddress.getByName(address));
                    if (network.isUp()) {
                        byte[] mac = network.getHardwareAddress();
                        if (mac != null) {
                            StringBuilder sb = new StringBuilder();
                            for (int i = 0; i < mac.length; i++) {
                                sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? ":" : ""));
                            }
                            String macAddress = sb.toString();
                            if (macAddresses.add(macAddress)) {
                                System.out.println(address + " -> " + macAddress + " " + network.getDisplayName());
                                try {
                                    allowAccessForThisMac(routerAddress, macAddress, login, password);
                                } catch (Exception e) {
                                    System.err.println("failed to allow access for  " + network);
                                }
                            }
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void allowAccessForThisMac(String routerAddress, String macAddress, String login, String password) throws IOException {
        URL url = new URL(routerAddress + "HNAP1/");
        HttpURLConnection connectionLoc = (HttpURLConnection) url.openConnection();
        connectionLoc.setRequestMethod("POST");
        connectionLoc.setRequestProperty("Content-Type", "text/xml; charset=\"utf-8\"");
        connectionLoc.setRequestProperty("Authorization", "Basic " + Base64.getEncoder().encodeToString((login + ":" + password).getBytes("UTF-8")));
        connectionLoc.setRequestProperty("SOAPAction", "http://cisco.com/HNAPExt/HotSpot/AddWebGUIAuthExemption");
        connectionLoc.setDoOutput(true);
        OutputStream os = connectionLoc.getOutputStream();
        os.write(("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
                "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n" +
                "<soap:Body>\n" +
                "<AddWebGUIAuthExemption xmlns=\"http://cisco.com/HNAPExt/HotSpot/\">\n" +
                "<MACAddress>" + macAddress + "</MACAddress>\n" +
                "<Duration>10</Duration>\n" +
                "</AddWebGUIAuthExemption>\n" +
                "</soap:Body>\n" +
                "</soap:Envelope>\n").getBytes("UTF-8"));
        os.close();
        int httpCode = connectionLoc.getResponseCode();
        System.out.println("HTTP " + httpCode);
        System.out.println(new String(readAll(connectionLoc.getInputStream()), "UTF-8"));
    }

    public static byte[] readAll(InputStream is) throws IOException {
        if (is != null) {
            byte[] buf = new byte[1024];
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            try {
                while (true) {
                    int bytesReadCurr = is.read(buf);
                    if (bytesReadCurr == -1) {
                        baos.close();
                        byte[] data = baos.toByteArray();
                        baos = null;
                        return data;
                    } else if (bytesReadCurr > 0) {
                        baos.write(buf, 0, bytesReadCurr);
                    }
                }
            } finally {
                if (baos != null) {
                    baos.close();
                }
            }
        } else {
            return null;
        }
    }

}