text:
package com.gcw.sapienza.places.utils;

import android.content.Context;
import android.util.Log;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by snowblack on 3/31/15.
 */
public class PlacesStorage {
    public static final String INBOX_FILE = "inbox_data_file";
    private static final String TAG = "PlacesStorage";

    public static final int COMMENTER_POS = 0;
    public static final int FLAG_POS = 1;
    public static final int ALERT_TEXT_POS = 2;
    public static final int SEEN_TEXT_POS = 3;

    public static List<List<String>> fetchInbox(Context context)
            throws IOException, ClassNotFoundException{
        File storageFile = new File(context.getFilesDir(), PlacesStorage.INBOX_FILE);

        if(!storageFile.exists()){
            Log.w(TAG, "Storage file doesn't exist! Creating new one...");
            storageFile.createNewFile();
            FileOutputStream fos = context.openFileOutput(PlacesStorage.INBOX_FILE, Context.MODE_PRIVATE);
            ObjectOutputStream os = new ObjectOutputStream(fos);
            os.writeObject(new LinkedList<List<String>>());
            os.close();
            fos.close();
        }

        FileInputStream fis = context.openFileInput(PlacesStorage.INBOX_FILE);
        ObjectInputStream is = new ObjectInputStream(fis);

        List<List<String>> inbox = (List<List<String>>) is.readObject();

        is.close();
        fis.close();

        return inbox;
    }

    public static void updateInboxWith(Context context,String commenter, String flag_id, String alert_text)
            throws ClassNotFoundException, IOException {

        List<List<String>> inbox = fetchInbox(context);

        if(inbox == null){
            inbox = new LinkedList<>();
        }

        List<String> notificationEntry = new ArrayList<>();
        notificationEntry.add(commenter);
        notificationEntry.add(flag_id);
        notificationEntry.add(alert_text);
        notificationEntry.add("");
        ((LinkedList<List<String>>)inbox).addFirst(notificationEntry);

        updateInbox(context, inbox);
    }

    public static void updateInbox(Context context, List<List<String>> newInbox) throws IOException {
            FileOutputStream fos = context.openFileOutput(PlacesStorage.INBOX_FILE, Context.MODE_PRIVATE);
            ObjectOutputStream os = new ObjectOutputStream(fos);
            os.writeObject(newInbox);
            os.close();
            fos.close();
    }

    public static void updateSeenInboxAt(Context context, int position) throws IOException, ClassNotFoundException {
        List<List<String>> inbox = fetchInbox(context);
        inbox.get(position).set(SEEN_TEXT_POS, "0");
        updateInbox(context, inbox);
    }

    public static void clearInbox(Context context) throws IOException {
        updateInbox(context, new LinkedList<List<String>>());
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision: 322115 $ -->
<refentry xmlns="http://docbook.org/ns/docbook" xml:id="imagick.getimageredprimary">
 <refnamediv>
  <refname>Imagick::getImageRedPrimary</refname>
  <refpurpose>Returns the chromaticity red primary point</refpurpose>
 </refnamediv>

 <refsect1 role="description">
  &reftitle.description;
  <methodsynopsis>
   <type>array</type><methodname>Imagick::getImageRedPrimary</methodname>
   <void/>
  </methodsynopsis>
  <para>
   Returns the chromaticity red primary point as an array with the keys "x" and "y".
  </para>
 </refsect1>

 <refsect1 role="returnvalues">
  &reftitle.returnvalues;
  <para>
    Returns the chromaticity red primary point as an array with the keys "x"
    and "y".
    &imagick.imagickexception.throw;
  </para>
 </refsect1>

 <refsect1 role="errors">
  &reftitle.errors;
  <para>
   &imagick.imagick.throws;
  </para>
 </refsect1>

</refentry>

<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->

redpajama_set_name: RedPajamaGithub


text:
export interface MulticastPublicationSettings {
    multicastId: string;
    response?: any;
    error?: Record<string, any>;
}

export interface MulticastPublication extends MulticastPublicationSettings {
    _typeName: "joynr.MulticastPublication";
}

/**
 * @name MulticastPublication
 * @constructor
 *
 * @param settings.multicastId
 * @param settings.response
 * @param settings.error The exception object in case of publication failure
 */
export function create(settings: MulticastPublicationSettings): MulticastPublication {
    /**
     * The joynr type name
     *
     * @name MulticastPublication#_typeName
     * @type String
     */
    (settings as MulticastPublication)._typeName = "joynr.MulticastPublication";
    return settings as MulticastPublication;
}


text:
namespace geode {

template<class TV> inline const TV& mean(const TV& x) {
  return x;
}

template<class TV> inline TV mean(const TV& x, const TV& y) {
  return typename ScalarPolicy<TV>::type(.5)*(x+y);
}

template<class TV> inline TV mean(const TV& x, const TV& y, const TV& z) {
  return typename ScalarPolicy<TV>::type(1./3)*(x+y+z);
}

template<class TV> inline TV mean(const TV& x, const TV& y, const TV& z, const TV& w) {
  return typename ScalarPolicy<TV>::type(.25)*(x+y+z+w);
}

}


text:
'use strict';

const os = require('os');
const f = require('util').format;
const ReadPreference = require('./read_preference');
const Buffer = require('safe-buffer').Buffer;
const TopologyType = require('../sdam/topology_description').TopologyType;

/**
 * Emit event if it exists
 * @method
 */
function emitSDAMEvent(self, event, description) {
  if (self.listeners(event).length > 0) {
    self.emit(event, description);
  }
}

// Get package.json variable
var driverVersion = require('../../package.json').version;
var nodejsversion = f('Node.js %s, %s', process.version, os.endianness());
var type = os.type();
var name = process.platform;
var architecture = process.arch;
var release = os.release();

function createClientInfo(options) {
  // Build default client information
  var clientInfo = options.clientInfo
    ? clone(options.clientInfo)
    : {
        driver: {
          name: 'nodejs-core',
          version: driverVersion
        },
        os: {
          type: type,
          name: name,
          architecture: architecture,
          version: release
        }
      };

  // Is platform specified
  if (clientInfo.platform && clientInfo.platform.indexOf('mongodb-core') === -1) {
    clientInfo.platform = f('%s, mongodb-core: %s', clientInfo.platform, driverVersion);
  } else if (!clientInfo.platform) {
    clientInfo.platform = nodejsversion;
  }

  // Do we have an application specific string
  if (options.appname) {
    // Cut at 128 bytes
    var buffer = Buffer.from(options.appname);
    // Return the truncated appname
    var appname = buffer.length > 128 ? buffer.slice(0, 128).toString('utf8') : options.appname;
    // Add to the clientInfo
    clientInfo.application = { name: appname };
  }

  return clientInfo;
}

function createCompressionInfo(options) {
  if (!options.compression || !options.compression.compressors) {
    return [];
  }

  // Check that all supplied compressors are valid
  options.compression.compressors.forEach(function(compressor) {
    if (compressor !== 'snappy' && compressor !== 'zlib') {
      throw new Error('compressors must be at least one of snappy or zlib');
    }
  });

  return options.compression.compressors;
}

function clone(object) {
  return JSON.parse(JSON.stringify(object));
}

var getPreviousDescription = function(self) {
  if (!self.s.serverDescription) {
    self.s.serverDescription = {
      address: self.name,
      arbiters: [],
      hosts: [],
      passives: [],
      type: 'Unknown'
    };
  }

  return self.s.serverDescription;
};

var emitServerDescriptionChanged = function(self, description) {
  if (self.listeners('serverDescriptionChanged').length > 0) {
    // Emit the server description changed events
    self.emit('serverDescriptionChanged', {
      topologyId: self.s.topologyId !== -1 ? self.s.topologyId : self.id,
      address: self.name,
      previousDescription: getPreviousDescription(self),
      newDescription: description
    });

    self.s.serverDescription = description;
  }
};

var getPreviousTopologyDescription = function(self) {
  if (!self.s.topologyDescription) {
    self.s.topologyDescription = {
      topologyType: 'Unknown',
      servers: [
        {
          address: self.name,
          arbiters: [],
          hosts: [],
          passives: [],
          type: 'Unknown'
        }
      ]
    };
  }

  return self.s.topologyDescription;
};

var emitTopologyDescriptionChanged = function(self, description) {
  if (self.listeners('topologyDescriptionChanged').length > 0) {
    // Emit the server description changed events
    self.emit('topologyDescriptionChanged', {
      topologyId: self.s.topologyId !== -1 ? self.s.topologyId : self.id,
      address: self.name,
      previousDescription: getPreviousTopologyDescription(self),
      newDescription: description
    });

    self.s.serverDescription = description;
  }
};

var changedIsMaster = function(self, currentIsmaster, ismaster) {
  var currentType = getTopologyType(self, currentIsmaster);
  var newType = getTopologyType(self, ismaster);
  if (newType !== currentType) return true;
  return false;
};

var getTopologyType = function(self, ismaster) {
  if (!ismaster) {
    ismaster = self.ismaster;
  }

  if (!ismaster) return 'Unknown';
  if (ismaster.ismaster && ismaster.msg === 'isdbgrid') return 'Mongos';
  if (ismaster.ismaster && !ismaster.hosts) return 'Standalone';
  if (ismaster.ismaster) return 'RSPrimary';
  if (ismaster.secondary) return 'RSSecondary';
  if (ismaster.arbiterOnly) return 'RSArbiter';
  return 'Unknown';
};

var inquireServerState = function(self) {
  return function(callback) {
    if (self.s.state === 'destroyed') return;
    // Record response time
    var start = new Date().getTime();

    // emitSDAMEvent
    emitSDAMEvent(self, 'serverHeartbeatStarted', { connectionId: self.name });

    // Attempt to execute ismaster command
    self.command('admin.$cmd', { ismaster: true }, { monitoring: true }, function(err, r) {
      if (!err) {
        // Legacy event sender
        self.emit('ismaster', r, self);

        // Calculate latencyMS
        var latencyMS = new Date().getTime() - start;

        // Server heart beat event
        emitSDAMEvent(self, 'serverHeartbeatSucceeded', {
          durationMS: latencyMS,
          reply: r.result,
          connectionId: self.name
        });

        // Did the server change
        if (changedIsMaster(self, self.s.ismaster, r.result)) {
          // Emit server description changed if something listening
          emitServerDescriptionChanged(self, {
            address: self.name,
            arbiters: [],
            hosts: [],
            passives: [],
            type: !self.s.inTopology ? 'Standalone' : getTopologyType(self)
          });
        }

        // Updat ismaster view
        self.s.ismaster = r.result;

        // Set server response time
        self.s.isMasterLatencyMS = latencyMS;
      } else {
        emitSDAMEvent(self, 'serverHeartbeatFailed', {
          durationMS: latencyMS,
          failure: err,
          connectionId: self.name
        });
      }

      // Peforming an ismaster monitoring callback operation
      if (typeof callback === 'function') {
        return callback(err, r);
      }

      // Perform another sweep
      self.s.inquireServerStateTimeout = setTimeout(inquireServerState(self), self.s.haInterval);
    });
  };
};

//
// Clone the options
var cloneOptions = function(options) {
  var opts = {};
  for (var name in options) {
    opts[name] = options[name];
  }
  return opts;
};

function Interval(fn, time) {
  var timer = false;

  this.start = function() {
    if (!this.isRunning()) {
      timer = setInterval(fn, time);
    }

    return this;
  };

  this.stop = function() {
    clearInterval(timer);
    timer = false;
    return this;
  };

  this.isRunning = function() {
    return timer !== false;
  };
}

function Timeout(fn, time) {
  var timer = false;

  this.start = function() {
    if (!this.isRunning()) {
      timer = setTimeout(fn, time);
    }
    return this;
  };

  this.stop = function() {
    clearTimeout(timer);
    timer = false;
    return this;
  };

  this.isRunning = function() {
    if (timer && timer._called) return false;
    return timer !== false;
  };
}

function diff(previous, current) {
  // Difference document
  var diff = {
    servers: []
  };

  // Previous entry
  if (!previous) {
    previous = { servers: [] };
  }

  // Check if we have any previous servers missing in the current ones
  for (var i = 0; i < previous.servers.length; i++) {
    var found = false;

    for (var j = 0; j < current.servers.length; j++) {
      if (current.servers[j].address.toLowerCase() === previous.servers[i].address.toLowerCase()) {
        found = true;
        break;
      }
    }

    if (!found) {
      // Add to the diff
      diff.servers.push({
        address: previous.servers[i].address,
        from: previous.servers[i].type,
        to: 'Unknown'
      });
    }
  }

  // Check if there are any severs that don't exist
  for (j = 0; j < current.servers.length; j++) {
    found = false;

    // Go over all the previous servers
    for (i = 0; i < previous.servers.length; i++) {
      if (previous.servers[i].address.toLowerCase() === current.servers[j].address.toLowerCase()) {
        found = true;
        break;
      }
    }

    // Add the server to the diff
    if (!found) {
      diff.servers.push({
        address: current.servers[j].address,
        from: 'Unknown',
        to: current.servers[j].type
      });
    }
  }

  // Got through all the servers
  for (i = 0; i < previous.servers.length; i++) {
    var prevServer = previous.servers[i];

    // Go through all current servers
    for (j = 0; j < current.servers.length; j++) {
      var currServer = current.servers[j];

      // Matching server
      if (prevServer.address.toLowerCase() === currServer.address.toLowerCase()) {
        // We had a change in state
        if (prevServer.type !== currServer.type) {
          diff.servers.push({
            address: prevServer.address,
            from: prevServer.type,
            to: currServer.type
          });
        }
      }
    }
  }

  // Return difference
  return diff;
}

/**
 * Shared function to determine clusterTime for a given topology
 *
 * @param {*} topology
 * @param {*} clusterTime
 */
function resolveClusterTime(topology, $clusterTime) {
  if (topology.clusterTime == null) {
    topology.clusterTime = $clusterTime;
  } else {
    if ($clusterTime.clusterTime.greaterThan(topology.clusterTime.clusterTime)) {
      topology.clusterTime = $clusterTime;
    }
  }
}

// NOTE: this is a temporary move until the topologies can be more formally refactored
//       to share code.
const SessionMixins = {
  endSessions: function(sessions, callback) {
    if (!Array.isArray(sessions)) {
      sessions = [sessions];
    }

    // TODO:
    //   When connected to a sharded cluster the endSessions command
    //   can be sent to any mongos. When connected to a replica set the
    //   endSessions command MUST be sent to the primary if the primary
    //   is available, otherwise it MUST be sent to any available secondary.
    //   Is it enough to use: ReadPreference.primaryPreferred ?
    this.command(
      'admin.$cmd',
      { endSessions: sessions },
      { readPreference: ReadPreference.primaryPreferred },
      () => {
        // intentionally ignored, per spec
        if (typeof callback === 'function') callback();
      }
    );
  }
};

function topologyType(topology) {
  if (topology.description) {
    return topology.description.type;
  }

  if (topology.type === 'mongos') {
    return TopologyType.Sharded;
  } else if (topology.type === 'replset') {
    return TopologyType.ReplicaSetWithPrimary;
  }

  return TopologyType.Single;
}

const RETRYABLE_WIRE_VERSION = 6;

/**
 * Determines whether the provided topology supports retryable writes
 *
 * @param {Mongos|Replset} topology
 */
const isRetryableWritesSupported = function(topology) {
  const maxWireVersion = topology.lastIsMaster().maxWireVersion;
  if (maxWireVersion < RETRYABLE_WIRE_VERSION) {
    return false;
  }

  if (!topology.logicalSessionTimeoutMinutes) {
    return false;
  }

  if (topologyType(topology) === TopologyType.Single) {
    return false;
  }

  return true;
};

module.exports.SessionMixins = SessionMixins;
module.exports.resolveClusterTime = resolveClusterTime;
module.exports.inquireServerState = inquireServerState;
module.exports.getTopologyType = getTopologyType;
module.exports.emitServerDescriptionChanged = emitServerDescriptionChanged;
module.exports.emitTopologyDescriptionChanged = emitTopologyDescriptionChanged;
module.exports.cloneOptions = cloneOptions;
module.exports.createClientInfo = createClientInfo;
module.exports.createCompressionInfo = createCompressionInfo;
module.exports.clone = clone;
module.exports.diff = diff;
module.exports.Interval = Interval;
module.exports.Timeout = Timeout;
module.exports.isRetryableWritesSupported = isRetryableWritesSupported;


text:
// -*- C++ -*-

//=============================================================================
/**
 *  @file   SSL_Asynch_Stream.h
 *
 *  $Id: SSL_Asynch_Stream.h 72092 2006-04-14 16:15:58Z shuston $
 *
 *  @author Alexander Libman <alibman@baltimore.com>
 */
//=============================================================================

#ifndef ACE_SSL_ASYNCH_STREAM_H
#define ACE_SSL_ASYNCH_STREAM_H

#include /**/ "ace/pre.h"
#include "SSL_Context.h"

#if !defined (ACE_LACKS_PRAGMA_ONCE)
#pragma once
#endif /* ACE_LACKS_PRAGMA_ONCE */

#if OPENSSL_VERSION_NUMBER > 0x0090581fL && ((defined (ACE_WIN32) && !defined (ACE_HAS_WINCE)) || (defined (ACE_HAS_AIO_CALLS)))

#include "SSL_Asynch_BIO.h"

#include "ace/Asynch_IO_Impl.h"
#include "ace/Message_Block.h"
#include "ace/Synch_Traits.h"
#include "ace/Thread_Mutex.h"

/*
 * This facility doesn't follow the normal ACE asynch I/O support classes'
 * interface/implementation arrangement. It's not needed because rather than
 * branching off to platform-specific APIs, all platforms use the OpenSSL
 * API. Thus, you can think of this class as the implementation class (for
 * OpenSSL) and there's no separate interface class.
 * Also, since both read and write operations are defined in one I/O
 * factory, there's no single Result class defined as there is for
 * ACE_Asynch_Read_Stream, et al. There are separate result classes defined
 * for read and write operations.
 */

#if defined (ACE_WIN32)
#  include "ace/WIN32_Asynch_IO.h"
typedef ACE_WIN32_Asynch_Result              A_RESULT;
typedef ACE_WIN32_Asynch_Read_Stream_Result  ARS_RESULT;
typedef ACE_WIN32_Asynch_Write_Stream_Result AWS_RESULT;

# define ERR_CANCELED ERROR_OPERATION_ABORTED

#else
#  include "ace/POSIX_Asynch_IO.h"
typedef ACE_POSIX_Asynch_Result              A_RESULT;
typedef ACE_POSIX_Asynch_Read_Stream_Result  ARS_RESULT;
typedef ACE_POSIX_Asynch_Write_Stream_Result AWS_RESULT;

# define ERR_CANCELED ECANCELED

#endif  /* ACE_WIN32 */

ACE_BEGIN_VERSIONED_NAMESPACE_DECL

class ACE_SSL_Asynch_Stream;     // Forward decl for use in result class def.

/**
 * @class ACE_SSL_Asynch_Read_Stream_Result
 *
 * Result class that communicates result of read operations initiated on
 * an ACE_SSL_Asynch_Stream object.
 */
class ACE_SSL_Asynch_Read_Stream_Result : public ARS_RESULT
{
  /// Factory class will have special permissions.
  friend class ACE_SSL_Asynch_Stream;

protected:
  ACE_SSL_Asynch_Read_Stream_Result (ACE_Handler &handler,
                                     ACE_HANDLE handle,
                                     ACE_Message_Block &message_block,
                                     size_t bytes_to_read,
                                     const void* act,
                                     ACE_HANDLE event,
                                     int priority,
                                     int signal_number);
};

/**
 * @class ACE_SSL_Asynch_Write_Stream_Result
 *
 * Result class that communicates result of write operations initiated on
 * an ACE_SSL_Asynch_Stream object.
 */
class ACE_SSL_Asynch_Write_Stream_Result : public AWS_RESULT
{
  /// Factory class will have special permissions.
  friend class ACE_SSL_Asynch_Stream;

protected:
  ACE_SSL_Asynch_Write_Stream_Result (ACE_Handler &handler,
                                      ACE_HANDLE handle,
                                      ACE_Message_Block &message_block,
                                      size_t bytes_to_read,
                                      const void* act,
                                      ACE_HANDLE event,
                                      int priority,
                                      int signal_number);
};

/**
 * @class ACE_SSL_Asynch_Result
 *
 * Result class that is used internally for socket close notifications.
 */
class ACE_SSL_Asynch_Result : public A_RESULT
{
public:
    ACE_SSL_Asynch_Result (ACE_Handler &handler);

    void complete (size_t bytes_transferred,
                   int    success,
                   const  void * completion_key,
                   u_long error);
};

// Only provide forward declarations to prevent possible abuse of the
// friend declarations in ACE_SSL_Asynch_Stream.
struct ACE_SSL_Asynch_Stream_Accessor;

/**
 * @class ACE_SSL_Asynch_Stream
 *
 * @brief This class is a factory for initiating asynchronous reads
 * and writes on an SSL stream.
 *
 * Once open() is called, multiple asynchronous read and write operations
 * can be started using this class.  The handler object (derived from
 * ACE_Handler) specified in open() will receive completion events for the
 * operations initiated via this class.
 */
class ACE_SSL_Export ACE_SSL_Asynch_Stream
  : public ACE_Asynch_Operation,
    public ACE_Handler
{
public:

  // Use a class/struct to work around scoping
  // problems for extern "C" free functions with some compilers.  For
  // example, some can't handle
  //
  //   friend ::some_extern_c_free_function (...)
  //
  // Note that we could use a straight C++ (i.e. not extern "C") free
  // function, but using a class or struct allows us to hide the
  // interface from the user, which prevents abuse of this friend
  // relationship.
  friend struct ACE_SSL_Asynch_Stream_Accessor;

  enum Stream_Type
    {
      ST_CLIENT = 0x0001,
      ST_SERVER = 0x0002
    };

  /// Constructor.
  /**
   * @arg context  Pointer to an ACE_SSL_Context instance containing
   *               the OpenSSL information to be associated with this
   *               ACE_SSL_Asynch_Stream.  The needed SSL data will be
   *               copied before return. Therefore, this object can be
   *               reused, modified, or deleted upon return. If a 0 pointer
   *               is passed, the ACE_SSL_Context::instance() method will
   *               be called to get access to a singleton.
   */
  ACE_SSL_Asynch_Stream (Stream_Type s_type = ST_SERVER,
                         ACE_SSL_Context * context = 0);

  /// Destructor
  virtual ~ACE_SSL_Asynch_Stream (void);

  int cancel (void);

  int close (void);

  /**
   * Initializes the factory with information which will be used with
   * each asynchronous call.
   *
   * @arg handler The ACE_Handler that will be called to handle completions
   *              for operations initiated using this factory.
   * @arg handle  The handle that future read/write operations will use.
   *
   * @retval 0    for success.
   * @retval -1   for failure; consult @c errno for further information.
   */
  int open (ACE_Handler &handler,
            ACE_HANDLE handle = ACE_INVALID_HANDLE,
            const void *completion_key = 0,
            ACE_Proactor *proactor = 0);

  /**
   * Initiates an asynchronous read. If the operation is successfully
   * initiated, the handle_read_stream() method will be called on the
   * ACE_Handler object passed to open() when the operation completes.
   * Data is read into the specified ACE_Message_Block beginning at its
   * write pointer; the block's write pointer is updated to reflect any
   * added data when the operation completes.
   *
   * @arg message_block      The specified ACE_Message_Block will receive any
   *                         data that is read. Data will be read into the
   *                         block beginning at the block's write pointer.
   * @arg num_bytes_to_read  The maximum number of bytes to read. The actual
   *                         amount read may be less.
   * @arg act                ACT which is passed to the completion handler in
   *                         the result object.
   * @arg priority           Specifies the operation priority. This has an
   *                         affect on POSIX only. Works like @i nice in Unix.
   *                         Negative values are not allowed. 0 means priority
   *                         of the operation same as the process priority.
   *                         1 means priority of the operation is one less than
   *                         process, and so forth. This parameter has no
   *                         affect on Win32.
   * @arg signal_number      The POSIX4 real-time signal number to be used
   *                         for the operation. signal_number ranges from
   *                         ACE_SIGRTMIN to ACE_SIGRTMAX. This argument is
   *                         unused on non-POSIX4 systems.
   *
   * @retval 0    for success.
   * @retval -1   for failure; consult @c errno for further information.
   */
  int read (ACE_Message_Block &message_block,
            size_t num_bytes_to_read,
            const void *act = 0,
            int priority = 0,
            int signal_number = ACE_SIGRTMIN);

  /**
   * Initiates an asynchronous write. If the operation is successfully
   * initiated, the handle_write_stream() method will be called on the
   * ACE_Handler object passed to open() when the operation completes.
   * Data is taken from the specified ACE_Message_Block beginning at its
   * read pointer; the block's read pointer is updated to reflect any
   * data successfully sent when the operation completes.
   *
   * @arg message_block      The specified ACE_Message_Block is the source of
   *                         data that is written. Data will be taken from the
   *                         block beginning at the block's read pointer.
   * @arg bytes_to_write     The maximum number of bytes to write. The actual
   *                         amount written may be less.
   * @arg act                ACT which is passed to the completion handler in
   *                         the result object.
   * @arg priority           Specifies the operation priority. This has an
   *                         affect on POSIX only. Works like @i nice in Unix.
   *                         Negative values are not allowed. 0 means priority
   *                         of the operation same as the process priority.
   *                         1 means priority of the operation is one less than
   *                         process, and so forth. This parameter has no
   *                         affect on Win32.
   * @arg signal_number      The POSIX4 real-time signal number to be used
   *                         for the operation. signal_number ranges from
   *                         ACE_SIGRTMIN to ACE_SIGRTMAX. This argument is
   *                         unused on non-POSIX4 systems.
   *
   * @retval 0    for success.
   * @retval -1   for failure; consult @c errno for further information.
   */
  int write (ACE_Message_Block &message_block,
             size_t bytes_to_write,
             const void *act = 0,
             int priority = 0,
             int signal_number = ACE_SIGRTMIN);

protected:
  /// Virtual from ACE_Asynch_Operation. Since this class is essentially an
  /// implementation class, simply return 0.
  virtual ACE_Asynch_Operation_Impl *implementation (void) const { return 0; }

  /// virtual from ACE_Handler

  /// This method is called when BIO write request is completed. It
  /// processes the IO completion and calls do_SSL_state_machine().
  virtual void handle_write_stream
               (const ACE_Asynch_Write_Stream::Result &result);

  /// This method is called when BIO read request is completed. It
  /// processes the IO completion and calls do_SSL_state_machine().
  virtual void handle_read_stream
               (const ACE_Asynch_Read_Stream::Result &result);

  /// This method is called when all SSL sessions are closed and no
  /// more pending AIOs exist.  It also calls users handle_wakeup().
  virtual void handle_wakeup (void);

  /**
   * @name SSL State Machine
   */
  //@{
  int do_SSL_state_machine (void);
  int do_SSL_handshake (void);
  int do_SSL_read (void);
  int do_SSL_write(void);
  int do_SSL_shutdown(void);
  //@}

  void print_error (int err_ssl,
                    const ACE_TCHAR *pText);

  int pending_BIO_count (void);

  /// This method is called to notify user handler when user's read in
  /// done.
  int notify_read (int bytes_transferred, int error);

  /// This method is called to notify user handler when user's write
  /// in done.
  int notify_write (int bytes_transferred, int error);

  /// This method is called to notify ourself that SSL session is
  /// shutdown and that there is no more I/O activity now and in the
  /// future.
  int notify_close(void);

  /**
   * @name BIO Helpers
   */
  //@{
  int ssl_bio_read (char * buf, size_t len, int & errval);
  int ssl_bio_write (const char * buf, size_t len, int & errval);
  //@}

private:

  // Preventing copying through construction or assignment.
  ACE_SSL_Asynch_Stream (ACE_SSL_Asynch_Stream const &);
  ACE_SSL_Asynch_Stream & operator= (ACE_SSL_Asynch_Stream const &);

protected:

  /// Stream Type ST_CLIENT/ST_SERVER
  Stream_Type type_;

  /// The real file/socket handle
  ACE_HANDLE handle_;

  /// The proactor
  ACE_Proactor * proactor_;

  /// External,i.e user  handler
  ACE_Handler * ext_handler_;

  /// External, i.e. read result faked for user
  ACE_SSL_Asynch_Read_Stream_Result *  ext_read_result_ ;

  /// External, i.e. write result faked for user
  ACE_SSL_Asynch_Write_Stream_Result * ext_write_result_ ;

  /// Stream state/flags
  enum Stream_Flag
    {
      /// istream_ open OK
      SF_STREAM_OPEN    = 0x0001,
      /// request to SSL shutdown
      SF_REQ_SHUTDOWN   = 0x0002,
      /// SSL shutdown finished
      SF_SHUTDOWN_DONE  = 0x0004,
      /// Close notification sent
      SF_CLOSE_NTF_SENT = 0x0008,
      /// Stream can be safely destroyed
      SF_DELETE_ENABLE  = 0x0010
    };

  int flags_;

  /// The SSL session.
  SSL * ssl_;

  /// The BIO implementation
  BIO * bio_;

  /// The real streams which work under the ssl connection.
  /// BIO performs I/O via this streams
  enum BIO_Flag  // internal IO flags
    {
      /// End of stream
      BF_EOS   = 0x01,
      /// Real AIO in progress
      BF_AIO   = 0x02
    };

  /**
   * @name Internal stream, buffer and info for BIO read
   */
  //@{
  ACE_Asynch_Read_Stream  bio_istream_;
  ACE_Message_Block       bio_inp_msg_;
  int                     bio_inp_errno_;
  int                     bio_inp_flag_;
  //@}

  /**
   * @name Internal stream, buffer and info for BIO write
   */
  //@{
  ACE_Asynch_Write_Stream bio_ostream_;
  ACE_Message_Block       bio_out_msg_;
  int                     bio_out_errno_;
  int                     bio_out_flag_;
  //@}

  /// Mutex to protect work
  ACE_SYNCH_MUTEX mutex_;

};

ACE_END_VERSIONED_NAMESPACE_DECL

#endif  /* OPENSSL_VERSION_NUMBER > 0x0090581fL && (ACE_WIN32 ||
           ACE_HAS_AIO_CALLS) */

#include /**/ "ace/post.h"

#endif  /* ACE_SSL_ASYNCH_STREAM_H */


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

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
com.google.zxing.aztec.encoder (ZXing Core 2.3.0 API)
</TITLE>

<META NAME="date" CONTENT="2014-02-17">

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

      Overview
    Package
      Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV PACKAGE
 NEXT PACKAGE

  FRAMES
 NO FRAMES

  All Classes

Package com.google.zxing.aztec.encoder

Class Summary

AztecCode
Aztec 2D code representation

Encoder
Generates Aztec 2D barcodes.

HighLevelEncoder
This produces nearly optimal encodings of text into the first-level of
 encoding used by Aztec code.

      Overview
    Package
      Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV PACKAGE
 NEXT PACKAGE

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2007–2014. All rights reserved.


text:
<!DOCTYPE html>

		<meta charset="utf-8" />

		<link href="asset/css/bootstrap.css" rel="stylesheet" />
		<link rel="stylesheet" href="asset/css/dexter.min.css" />
		<link rel="stylesheet" href="asset/css/font-awesome.min.css" />

		<link rel="stylesheet" href="asset/css/prettify.css" />

 Checker Code

					IL_CONTAINER_ADDED_TO_ITSELF

 Description

					A collection is added to itself

 Severity

					Critical

 Detector / Bug Pattern

					InfiniteRecursiveLoop / IL

 More Information

A collection is added to itself. As a result, computing the hashCode of this
set will throw a StackOverflowException. Modifying a collection with itself is almost never what is intended

 Bad Code

Set<Integer> a = new Hashset<Integer>();
a.addAll(a); // Calling contain method or using sorting on this will throw a StackOverflowException.

 Good Code

 CWE ID

				CWE-586

 Code Review Asset

				N/A

 URLs

					FINDBUGS SITE  :

					STACKOVERFLOW SITE  :


text:
ACCEPTED

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

#### Published in
Trans. Br. mycol. Soc. 7: 34 (1921)

#### Original name
Hymenochaete ramealis Berk., 1875

### Remarks
null


text:
import os
import sys

from google.appengine.ext.webapp import util

# Some shortcuts
ROOT = os.path.dirname(os.path.realpath(__file__))
LIBS = os.path.join(ROOT, 'libs')

# Remove the standard version of Django
for k in [k for k in sys.modules if k.startswith('django')]:
    del sys.modules[k]

# Force sys.path to have our own directory first
sys.path.insert(0, LIBS)

# Must set this env var *before* importing any part of Django
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

from django.core.management import setup_environ
from django.core.handlers import wsgi

try:
    import settings_local as settings
except ImportError:
    import sys
    sys.stderr.write(
        "Error: tried importing 'settings_local.py' and 'settings.py' "
        "but neither could be found (or they are throwing an ImportError). "
        "Please, come back and try again later.")
    raise

setup_environ(settings)

def main():
    application = wsgi.WSGIHandler()
    util.run_wsgi_app(application)

if __name__ == '__main__':
    main()


text:
<?xml version="1.0" encoding="UTF-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
	<item android:id="@android:id/background">
		<shape>
			<corners android:radius="5.0dip" />
			<gradient
				android:startColor="#50000000"
				android:endColor="#50000000"
				android:angle="270.0"
				android:centerY="0.75"
				android:centerColor="#50000000" />
		</shape>
	</item>
	<item android:id="@android:id/secondaryProgress">
		<clip>
			<shape>
				<corners android:radius="8.0dip" />
				<gradient
					android:startColor="#e71a5e"
					android:endColor="#6c213a"
					android:angle="90.0"
					android:centerY="0.75"
					android:centerColor="#ac6079" />
			</shape>
		</clip>
	</item>
	<item android:id="@android:id/progress">
		<clip>
			<shape>
				<corners android:radius="8.0dip" />
				<gradient
					android:startColor="#05A412"
					android:endColor="#05A412"
					android:angle="270.0" />
			</shape>
		</clip>
	</item>
</layer-list>


text:
using namespace PinnedDownCore;
using namespace PinnedDownGameplay::Events;

namespace PinnedDownGameplay
{
	namespace Systems
	{
		class FightSystem : public GameSystem, public IEventListener
		{
		public:
			FightSystem();

			void InitSystem(PinnedDownCore::Game* game);

		private:
			void OnEvent(Event & event);

			EVENT_HANDLER_DECLARATION(FightStartedEvent);
		};
	}
}


text:
PlantCV has been tested on the following systems:

- Linux: CentOS 7 (RedHat Enterprise Linux)
- Linux: Ubuntu 12.04+
- Linux: Raspbian "Jessie"
- Mac OSX 10.11 and macOS 10.12+
- Windows 10
- Cloud9 IDE

#### Required dependencies

- Python (tested with versions 3.7, 3.8, and 3.9)
    - Package managers will automatically solve for the required dependencies, which can be found in the
    [requirements configuration files](https://github.com/danforthcenter/plantcv/blob/main/requirements.txt).

#### Optional but recommended

- conda (Anaconda or Miniconda)
- jupyter
- pytest (only if installing from source code and running tests)

### Install via a package manager

Stable releases of PlantCV are available through both the [Python Package Index (PyPI)](https://pypi.org/) and
`conda` through the [conda-forge channel](https://conda-forge.org/). We plan on releasing new versions of PlantCV
into both platforms on at a monthly basis.

#### PyPI

To install from PyPI run the following in any type of virtual environment, as an administrator, or add the `--user`
flag if needed.

```bash
pip install plantcv

```

#### Conda

To install using `conda` first install [Anaconda](https://www.anaconda.com/download/) or
[Miniconda](https://conda.io/miniconda.html) if you have not already. If needed, add the following channels to your
`conda` configuration.

```bash
conda config --add channels conda-forge

```

Then create an environment and install PlantCV.

```bash
conda create -n plantcv plantcv

```

Or install PlantCV in your current environment.

```bash
conda install plantcv

```

#### Using PlantCV containers

**Platforms**: Linux, macOS, Windows

PlantCV currently supports the Docker container system but support for Singularity and other container systems are on
our to-do list. [Docker](https://www.docker.com/) is a company/platform that provides operating-system-level
virtualization (containers). See [Wikipedia](https://en.wikipedia.org/wiki/Operating-system-level_virtualization) for
more background. Containers are a useful way to package and isolate applications (and their dependencies) into a
portable, lightweight virtualized environment. A PlantCV Docker container is available through
[Docker Hub](https://hub.docker.com/r/danforthcenter/plantcv/). To use the PlantCV container you will need docker
[installed on your local system](https://docs.docker.com/engine/installation/). If you have docker, you can use PlantCV
as in the following examples:

```bash
# Pull the latest image of PlantCV from Docker Hub
docker pull danforthcenter/plantcv

# A simple command to demonstrate it works (nothing returned if import is successful)
docker run danforthcenter/plantcv python -c 'from plantcv import plantcv as pcv; print(pcv.__version__)'

```

The PlantCV container is built on top of the
[Jupyter minimal-notebook container](https://hub.docker.com/r/jupyter/minimal-notebook). To analyze data with the
PlantCV Docker container you will need to map a local folder that contains your inputs into
the container filesystem. We use the same working directory as documented by
[Jupyter Docker Stacks](https://github.com/jupyter/docker-stacks). An easy way to run PlantCV in a container with
Jupyter notebook support is to map your current directory into the container:

```bash
docker run --rm -p 8888:8888 -v "$PWD":/home/jovyan/work danforthcenter/plantcv

```

Then point your browser to the URL that is printed to your terminal. Any data/notebooks saved to the `work` directory
will persist on your local filesystem after the container is shut down.

You can also run PlantCV on the command-line without Jupyter notebooks. For the sake of this example, assume that
your working directory contains a PlantCV script called `test-script.py` and an image called `test-image.png`.
The `test-script.py` in this case would be a script like the one described in the [VIS tutorial](tutorials/vis_tutorial.md).

```bash
# Analyzing data using the PlantCV docker image
docker run --rm -v "$PWD":/home/jovyan/work danforthcenter/plantcv python ./work/test-script.py \
-i ./work/test-image.png -o ./work -r ./work/plantcv-results.txt

```

### Installation from the source code

You can build PlantCV from the source on GitHub if you are a developer or want the absolute latest version available.

#### Conda-based installation procedure

**Platforms**: Linux, macOS, Windows

There are a variety of options for installing PlantCV depending on your use case. If you have experience with system
administration you can install PlantCV and the dependencies using system package management tools and administrator
privileges (feel free to [ask](https://github.com/danforthcenter/plantcv/issues) if you get stuck).

For most users we recommend installation using `conda`, a cross-platform package management system. Both the
[Anaconda](https://www.anaconda.com/download/) or [Miniconda](https://conda.io/miniconda.html) implementations of
`conda` can be used. Here is an overview of the process:

1. Download and install the version of `conda` that is appropriate for your system.
2. Clone or download PlantCV from GitHub. Feel free to use [GitHub Desktop](https://desktop.github.com/) or
command-line `git`. Git will allow you to pull updates from GitHub, but if you prefer not to use git you can download
a zip file of the package from [GitHub](https://github.com/danforthcenter/plantcv).
3. Create a Python environment for PlantCV that includes the Python dependencies.
4. Install PlantCV.

Once you have `conda` and `git` or GitHub Desktop installed, clone the PlantCV repository, open a command-line terminal
application (on Windows there are other options but for this tutorial we will use the Anaconda Prompt application). In
the example below we use an environment configuration file that is included with PlantCV.

```bash
# Clone PlantCV if you did not use the GitHub Desktop application
git clone https://github.com/danforthcenter/plantcv.git

# Enter the PlantCV directory (if you cloned with GitHub Desktop your path may be different than below)
cd plantcv

# Create a conda environment named "plantcv" (or whatever you like) and automatically install the dependencies
conda env create -n plantcv -f environment.yml

# Activate the plantcv environment (you will have to do this each time you start a new session)
conda activate plantcv

# Install PlantCV in editable mode so that it updates as you work on new features/updates
pip install -e .

```

If you have a broken environment, you can remove it and repeat the above steps.

```bash
# Remove the environment
conda env remove -n plantcv

```

#### Script-based installation

**Platforms**: Ubuntu, macOS

Clone the PlantCV repository:

```bash
git clone https://github.com/danforthcenter/plantcv.git
```

Run the setup script:

```bash
cd plantcv
bash scripts/setup.sh

```

The script guides you through the installation steps. Successful completion ends with a usage report.

The script has been tested on [Ubuntu](http://www.ubuntu.com/) x86_64-bit 16_04 server edition, OSX 10.11, and
macOS 10.12.

### Installation on other systems

#### Cloud9 IDE

[Cloud9](https://c9.io) is a development environment in the cloud that works with Chromebooks or other thin clients.
The IDE workspaces are powered by Docker Ubuntu containers within a web browser.

After signing up for an account create a new workspace and choose a Python template.

Install update

```bash
sudo apt-get update
```

Install software dependencies

```bash
sudo apt-get install git libopencv-dev python-opencv python-numpy python-matplotlib sqlite3
```

Clone the PlantCV repository into your home directory

```bash
git clone https://github.com/danforthcenter/plantcv.git
```

The default branch (main) is the latest release. If you want to check out a specific version:

```bash
# Switch to a stable release
cd plantcv

git checkout v1.1
```

Install PlantCV

```bash
sudo python setup.py install
```

After installation test with the following:

```bash
python -c 'import plantcv'
```

You will be given the following error:

`libdc1394 error: Failed to initialize libdc1394`

libdc1394 allows a program to interface with cameras that work on the ieee1394 standard(firewire).
Due to no option to enable USB access in the Cloud9 workspace this error will keep occuring when running a workflow.
This error will have no effect on the output of your workflows and can continue working despite the warning.

To temporarily remove the driver and error use:

```bash
sudo ln /dev/null /dev/raw1394
```

Test import again and you should see no more errors. Restarting workspace will require input to remove
libdc1394 error again.

```bash
python -c 'import plantcv'
```


text:
package com.vmware.vim25;

/**
* @author Steve Jin (http://www.doublecloud.org)
* @version 5.1
*/

@SuppressWarnings("all")
public class InvalidVmConfig extends VmConfigFault {
  public String property;

  public String getProperty() {
    return this.property;
  }

  public void setProperty(String property) {
    this.property=property;
  }
}


text:
"""
Helper methods for storage related operations(attach, detach, etc).
"""

import collections

from oslo_log import log as logging

from nova import block_device
from nova.virt import driver
from nova.virt.virtualbox import constants
from nova.virt.virtualbox import vhdutils

LOG = logging.getLogger(__name__)

def group_block_devices_by_type(block_device_mapping):
    """Return devices grouped by driver volume type."""
    block_devices = collections.defaultdict(list)
    for volume in block_device_mapping:
        connection_info = volume['connection_info']
        volume_type = connection_info.get('driver_volume_type')
        block_devices[volume_type].append(volume)
    return block_devices

def volume_in_mapping(mount_device, block_device_info):
    block_device_list = [
        block_device.strip_dev(volume['mount_device']) for volume in
        driver.block_device_info_get_mapping(block_device_info)
    ]

    swap = driver.block_device_info_get_swap(block_device_info)
    if driver.swap_is_usable(swap):
        block_device_list.append(block_device.strip_dev(
            swap['device_name']))
    block_device_list.extend([
        block_device.strip_dev(ephemeral['device_name']) for ephemeral in
        driver.block_device_info_get_ephemerals(block_device_info)])

def ebs_root_in_block_devices(block_device_info):
    if not block_device_info:
        return

    root_device = block_device_info.get('root_device_name')
    if not root_device:
        root_device = constants.DEFAULT_ROOT_DEVICE

    return volume_in_mapping(root_device, block_device_info)

def volume_uuid(connection_info):
    """Returm the volume uuid if is already registered."""
    data = connection_info['data']
    target_lun = str(data['target_lun'])
    target_iqn = data['target_iqn']
    target_portal = data['target_portal'].split(':')[0]

    registered_hdds = vhdutils.get_hard_disks()
    for uuid, disk in registered_hdds.items():
        if '|' not in disk[constants.VHD_PATH]:
            continue

        disk_info = disk[constants.VHD_PATH].split('|')
        for target_info in (target_lun, target_iqn, target_portal):
            if target_info not in disk_info:
                break
        else:
            return uuid

    return None


text:
package org.apache.skywalking.oap.server.receiver.event;

import org.apache.skywalking.oap.server.library.module.ModuleConfig;

public class EventModuleConfig extends ModuleConfig {
}


text:
package org.jabref.logic.bibtex.comparator;

import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.StandardField;

import org.junit.jupiter.api.Test;

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

class EntryComparatorTest {
    @Test
    void recognizeIdenticObjectsAsEqual() {
        BibEntry e1 = new BibEntry();
        BibEntry e2 = e1;
        assertEquals(0, new EntryComparator(false, false, StandardField.TITLE).compare(e1, e2));
    }
}


text:
import PlainPopupSource from "../src/plain/PlainPopupSource.js";
export default class ElixPopupSource extends PlainPopupSource {}
customElements.define("elix-popup-source", ElixPopupSource);


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Scrappy.Core.Imdb;

namespace Scrappy.Core.Rutor
{
    public class RutorCollection : DataCollection
    {
        private Dictionary<string, RutorItem> items;
        private Dictionary<string, RutorDetails> details;
        private Dictionary<string, ImdbDetails> imdbs;

        string DataCollection.Name
        {
            get { return "rutor"; }
        }

        void DataCollection.Get(DataStore store)
        {
            items = store.Get<Dictionary<string, RutorItem>>("items");
            details = store.Get<Dictionary<string, RutorDetails>>("details");
            imdbs = store.Get<Dictionary<string, ImdbDetails>>("imdbs");
        }

        void DataCollection.Update(DataStore store)
        {
            store.Add("items", items);
            store.Add("details", details);
            store.Add("imdbs", imdbs);
        }

        public IEnumerable<dynamic> Group(int page)
        {
            return GroupCore(page, x => true).Skip(page * 20).Take(21);
        }

        public IEnumerable<dynamic> Group(int page, string year)
        {
            return GroupCore(page, x => x.Year == year).Skip(page * 20).Take(21);
        }

        private IEnumerable<dynamic> GroupCore(int page, Func<RutorItem, bool> predicate)
        {
            HashSet<string> returnedImdb = new HashSet<string>();

            foreach (var group in items.Values.Where(predicate).GroupBy(x => new { x.Year, x.Title }).OrderByDescending(x => x.Max(i => i.Id)))
            {
                foreach (var rItem in group)
                {
                    if (details.ContainsKey(rItem.Id))
                    {
                        RutorDetails rDetails = details[rItem.Id];

                        if (rDetails.Imdb != null && imdbs.ContainsKey(rDetails.Imdb))
                        {
                            ImdbDetails iDetails = imdbs[rDetails.Imdb];

                            if (iDetails.Image != null && iDetails.Summary != null)
                            {
                                if (returnedImdb.Add(iDetails.Id))
                                {
                                    yield return new
                                    {
                                        Year = group.Key.Year,
                                        Title = group.Key.Title,
                                        Image = iDetails.Image,
                                        Summary = iDetails.Summary,
                                        Page = page
                                    };
                                }
                            }
                        }
                    }
                }
            }
        }

        public IEnumerable<RutorItem> MissingDetails()
        {
            DateTime threshold = DateTime.Now - TimeSpan.FromDays(7);

            foreach (RutorItem data in items.Values.OrderByDescending(x => x.Id))
            {
                if (details.ContainsKey(data.Id) == false)
                {
                    yield return data;
                }
            }

            foreach (RutorItem data in items.Values.OrderByDescending(x => x.Id))
            {
                if (details.ContainsKey(data.Id) && details[data.Id].Timestamp.GetValueOrDefault() < threshold)
                {
                    yield return data;
                }
            }
        }

        public IEnumerable<RutorDetails> MissingImdb()
        {
            List<RutorDetails> found = new List<RutorDetails>();

            foreach (RutorDetails data in details.Values)
            {
                if (data.Imdb != null && imdbs.ContainsKey(data.Imdb) == false)
                {
                    found.Add(data);
                }
            }

            return found;
        }

        public dynamic Details(string year, string title)
        {
            string id = null;
            string imdb = null;

            List<dynamic> entries = new List<dynamic>();

            foreach (RutorItem item in items.Values)
            {
                if (item.Title == title && item.Year == year)
                {
                    if (details.ContainsKey(item.Id))
                    {
                        id = item.Id;
                        imdb = imdb ?? details[id].Imdb;

                        entries.Add(new
                        {
                            Id = item.Id,
                            Date = item.Date,
                            Hash = item.Hash,
                            Size = item.Size,
                            Peers = item.Peers,
                            Seeds = item.Seeds
                        });
                    }
                }
            }

            return new
            {
                Group = new
                {
                    Year = year,
                    Title = title,
                    Image = imdbs[imdb].Image,
                    Summary = imdbs[imdb].Summary
                },
                Entries = entries.OrderByDescending(x => x.Size.Length).ThenByDescending(x => x.Size).ToArray()
            };
        }

        public dynamic Release(string id)
        {
            string imdb = null;

            foreach (RutorItem item in items.Values)
            {
                if (item.Title == items[id].Title && item.Year == items[id].Year)
                {
                    if (details.ContainsKey(item.Id))
                    {
                        imdb = imdb ?? details[item.Id].Imdb;
                    }
                }
            }

            return new
            {
                Group = new
                {
                    Year = items[id].Year,
                    Title = items[id].Title,
                    Image = imdbs[imdb].Image,
                    Summary = imdbs[imdb].Summary
                },
                Release = new
                {
                    Id = items[id].Id,
                    Imdb = imdb,
                    ImdbLink = $"http://www.imdb.com/title/tt{imdb}/",
                    Link = $"http://arutor.org/torrent/{id}/",
                    Date = items[id].Date,
                    Hash = items[id].Hash,
                    Size = items[id].Size,
                    Peers = items[id].Peers,
                    Seeds = items[id].Seeds,
                    Media = details[id].Media ?? new string[0],
                    Timestamp = details[id].Timestamp?.ToString("yyyy-MM-dd") ?? String.Empty
                }
            };
        }

        public void Apply(IEnumerable<RutorItem> data)
        {
            foreach (RutorItem item in data)
            {
                items[item.Id] = item;
            }
        }

        public void Apply(string id, RutorDetails data)
        {
            if (data == RutorDetails.Removed)
            {
                details.Remove(id);
                items.Remove(id);
            }
            else
            {
                details[data.Id] = data;
            }
        }

        public void Apply(ImdbDetails data)
        {
            imdbs[data.Id] = data;
        }
    }
}


text:
package android.sipgate.lunch.ormlite;

import com.j256.ormlite.android.apptools.OrmLiteConfigUtil;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;

/**
 * Helper class to generate the ormlite config file for database structure infos.
 *

 * Important:

 * Customize the static variable CONFIG_FILE (atm. only an absolute path seem to work correctly
 * with IntelliJ / AndroidStudio!)
 *
 * @author schafm
 */
public class DatabaseConfigUtil extends OrmLiteConfigUtil {
    public static final File CONFIG_FILE =
            new File("~/AndroidStudioProjects/SipgateLunch/app/src/main/res/raw/ormlite_config.txt");
	public static void main(String[] args) throws SQLException, IOException {
		writeConfigFile(CONFIG_FILE);
	}
}


text:
/* typescript-demo 0.0.1 (2013-06-04) | Outright Mental Inc. - https://github.com/outrightmental/typescript-demo.git */
var Todos=new TodoList;$(function(){new AppView});


text:
import React from 'react';

import css from '../styles/base.styl';
import AdminNav from './AdminNav.js';

export let themes = {
  DEFAULT: 'has--default-theme',
  DARK: 'has--dark-theme'
};

export class Shell extends React.Component {
  static get defaultProps() {
    return {
      theme: themes.DEFAULT
    };
  }

  render() {
    let overlayProps = {
      className: 'overlay'
    };

    switch(this.props.resultsStatus){
      case 'processing' :
        overlayProps.className = overlayProps.className +' is--processing';
        break;
    }

    return (
      <div className={'shell '+ this.props.theme}>
        <AdminNav {...this.props} />
        {React.cloneElement(this.props.children, this.props)}
        <div {...overlayProps} />
      </div>
    );
  }
}


text:
<?php

namespace Symfony\Component\Debug;

/**
 * Autoloader checking if the class is really defined in the file found.
 *
 * The ClassLoader will wrap all registered autoloaders
 * and will throw an exception if a file is found but does
 * not declare the class.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 * @author Christophe Coevoet <stof@notk.org>
 * @author Nicolas Grekas <p@tchwork.com>
 */
class DebugClassLoader
{
    private $classLoader;
    private $isFinder;
    private $loaded = array();
    private static $caseCheck;
    private static $checkedClasses = array();
    private static $final = array();
    private static $finalMethods = array();
    private static $deprecated = array();
    private static $internal = array();
    private static $internalMethods = array();
    private static $php7Reserved = array('int' => 1, 'float' => 1, 'bool' => 1, 'string' => 1, 'true' => 1, 'false' => 1, 'null' => 1);
    private static $darwinCache = array('/' => array('/', array()));

    public function __construct(callable $classLoader)
    {
        $this->classLoader = $classLoader;
        $this->isFinder = is_array($classLoader) && method_exists($classLoader[0], 'findFile');

        if (!isset(self::$caseCheck)) {
            $file = file_exists(__FILE__) ? __FILE__ : rtrim(realpath('.'), DIRECTORY_SEPARATOR);
            $i = strrpos($file, DIRECTORY_SEPARATOR);
            $dir = substr($file, 0, 1 + $i);
            $file = substr($file, 1 + $i);
            $test = strtoupper($file) === $file ? strtolower($file) : strtoupper($file);
            $test = realpath($dir.$test);

            if (false === $test || false === $i) {
                // filesystem is case sensitive
                self::$caseCheck = 0;
            } elseif (substr($test, -strlen($file)) === $file) {
                // filesystem is case insensitive and realpath() normalizes the case of characters
                self::$caseCheck = 1;
            } elseif (false !== stripos(PHP_OS, 'darwin')) {
                // on MacOSX, HFS+ is case insensitive but realpath() doesn't normalize the case of characters
                self::$caseCheck = 2;
            } else {
                // filesystem case checks failed, fallback to disabling them
                self::$caseCheck = 0;
            }
        }
    }

    /**
     * Gets the wrapped class loader.
     *
     * @return callable The wrapped class loader
     */
    public function getClassLoader()
    {
        return $this->classLoader;
    }

    /**
     * Wraps all autoloaders.
     */
    public static function enable()
    {
        // Ensures we don't hit https://bugs.php.net/42098
        class_exists('Symfony\Component\Debug\ErrorHandler');
        class_exists('Psr\Log\LogLevel');

        if (!is_array($functions = spl_autoload_functions())) {
            return;
        }

        foreach ($functions as $function) {
            spl_autoload_unregister($function);
        }

        foreach ($functions as $function) {
            if (!is_array($function) || !$function[0] instanceof self) {
                $function = array(new static($function), 'loadClass');
            }

            spl_autoload_register($function);
        }
    }

    /**
     * Disables the wrapping.
     */
    public static function disable()
    {
        if (!is_array($functions = spl_autoload_functions())) {
            return;
        }

        foreach ($functions as $function) {
            spl_autoload_unregister($function);
        }

        foreach ($functions as $function) {
            if (is_array($function) && $function[0] instanceof self) {
                $function = $function[0]->getClassLoader();
            }

            spl_autoload_register($function);
        }
    }

    /**
     * Loads the given class or interface.
     *
     * @param string $class The name of the class
     *
     * @return bool|null True, if loaded
     *
     * @throws \RuntimeException
     */
    public function loadClass($class)
    {
        $e = error_reporting(error_reporting() | E_PARSE | E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR);

        try {
            if ($this->isFinder && !isset($this->loaded[$class])) {
                $this->loaded[$class] = true;
                if ($file = $this->classLoader[0]->findFile($class) ?: false) {
                    $wasCached = \function_exists('opcache_is_script_cached') && opcache_is_script_cached($file);

                    require $file;

                    if ($wasCached) {
                        return;
                    }
                }
            } else {
                call_user_func($this->classLoader, $class);
                $file = false;
            }
        } finally {
            error_reporting($e);
        }

        $this->checkClass($class, $file);
    }

    private function checkClass($class, $file = null)
    {
        $exists = null === $file || \class_exists($class, false) || \interface_exists($class, false) || \trait_exists($class, false);

        if (null !== $file && $class && '\\' === $class[0]) {
            $class = substr($class, 1);
        }

        if ($exists) {
            if (isset(self::$checkedClasses[$class])) {
                return;
            }
            self::$checkedClasses[$class] = true;

            $refl = new \ReflectionClass($class);
            if (null === $file && $refl->isInternal()) {
                return;
            }
            $name = $refl->getName();

            if ($name !== $class && 0 === \strcasecmp($name, $class)) {
                throw new \RuntimeException(sprintf('Case mismatch between loaded and declared class names: "%s" vs "%s".', $class, $name));
            }

            // Don't trigger deprecations for classes in the same vendor
            if (2 > $len = 1 + (\strpos($name, '\\') ?: \strpos($name, '_'))) {
                $len = 0;
                $ns = '';
            } else {
                $ns = \substr($name, 0, $len);
            }

            // Detect annotations on the class
            if (false !== $doc = $refl->getDocComment()) {
                foreach (array('final', 'deprecated', 'internal') as $annotation) {
                    if (false !== \strpos($doc, $annotation) && preg_match('#\n \* @'.$annotation.'(?:( .+?)\.?)?\r?\n \*(?: @|/$)#s', $doc, $notice)) {
                        self::${$annotation}[$name] = isset($notice[1]) ? preg_replace('#\s*\r?\n \* +#', ' ', $notice[1]) : '';
                    }
                }
            }

            $parentAndTraits = \class_uses($name, false);
            if ($parent = \get_parent_class($class)) {
                $parentAndTraits[] = $parent;

                if (!isset(self::$checkedClasses[$parent])) {
                    $this->checkClass($parent);
                }

                if (isset(self::$final[$parent])) {
                    @trigger_error(sprintf('The "%s" class is considered final%s. It may change without further notice as of its next major version. You should not extend it from "%s".', $parent, self::$final[$parent], $name), E_USER_DEPRECATED);
                }
            }

            // Detect if the parent is annotated
            foreach ($parentAndTraits + $this->getOwnInterfaces($name, $parent) as $use) {
                if (!isset(self::$checkedClasses[$use])) {
                    $this->checkClass($use);
                }
                if (isset(self::$deprecated[$use]) && \strncmp($ns, $use, $len)) {
                    $type = class_exists($name, false) ? 'class' : (interface_exists($name, false) ? 'interface' : 'trait');
                    $verb = class_exists($use, false) || interface_exists($name, false) ? 'extends' : (interface_exists($use, false) ? 'implements' : 'uses');

                    @trigger_error(sprintf('The "%s" %s %s "%s" that is deprecated%s.', $name, $type, $verb, $use, self::$deprecated[$use]), E_USER_DEPRECATED);
                }
                if (isset(self::$internal[$use]) && \strncmp($ns, $use, $len)) {
                    @trigger_error(sprintf('The "%s" %s is considered internal%s. It may change without further notice. You should not use it from "%s".', $use, class_exists($use, false) ? 'class' : (interface_exists($use, false) ? 'interface' : 'trait'), self::$internal[$use], $name), E_USER_DEPRECATED);
                }
            }

            // Inherit @final and @internal annotations for methods
            self::$finalMethods[$name] = array();
            self::$internalMethods[$name] = array();
            foreach ($parentAndTraits as $use) {
                foreach (array('finalMethods', 'internalMethods') as $property) {
                    if (isset(self::${$property}[$use])) {
                        self::${$property}[$name] = self::${$property}[$name] ? self::${$property}[$use] + self::${$property}[$name] : self::${$property}[$use];
                    }
                }
            }

            $isClass = \class_exists($name, false);
            foreach ($refl->getMethods(\ReflectionMethod::IS_PUBLIC | \ReflectionMethod::IS_PROTECTED) as $method) {
                if ($method->class !== $name) {
                    continue;
                }

                // Method from a trait
                if ($method->getFilename() !== $refl->getFileName()) {
                    continue;
                }

                if ($isClass && $parent && isset(self::$finalMethods[$parent][$method->name])) {
                    list($declaringClass, $message) = self::$finalMethods[$parent][$method->name];
                    @trigger_error(sprintf('The "%s::%s()" method is considered final%s. It may change without further notice as of its next major version. You should not extend it from "%s".', $declaringClass, $method->name, $message, $name), E_USER_DEPRECATED);
                }

                foreach ($parentAndTraits as $use) {
                    if (isset(self::$internalMethods[$use][$method->name])) {
                        list($declaringClass, $message) = self::$internalMethods[$use][$method->name];
                        if (\strncmp($ns, $declaringClass, $len)) {
                            @trigger_error(sprintf('The "%s::%s()" method is considered internal%s. It may change without further notice. You should not extend it from "%s".', $declaringClass, $method->name, $message, $name), E_USER_DEPRECATED);
                        }
                    }
                }

                // Detect method annotations
                if (false === $doc = $method->getDocComment()) {
                    continue;
                }

                foreach (array('final', 'internal') as $annotation) {
                    if (false !== \strpos($doc, $annotation) && preg_match('#\n\s+\* @'.$annotation.'(?:( .+?)\.?)?\r?\n\s+\*(?: @|/$)#s', $doc, $notice)) {
                        $message = isset($notice[1]) ? preg_replace('#\s*\r?\n \* +#', ' ', $notice[1]) : '';
                        self::${$annotation.'Methods'}[$name][$method->name] = array($name, $message);
                    }
                }
            }

            if (isset(self::$php7Reserved[\strtolower($refl->getShortName())])) {
                @trigger_error(sprintf('The "%s" class uses the reserved name "%s", it will break on PHP 7 and higher', $name, $refl->getShortName()), E_USER_DEPRECATED);
            }
        }

        if ($file) {
            if (!$exists) {
                if (false !== strpos($class, '/')) {
                    throw new \RuntimeException(sprintf('Trying to autoload a class with an invalid name "%s". Be careful that the namespace separator is "\" in PHP, not "/".', $class));
                }

                throw new \RuntimeException(sprintf('The autoloader expected class "%s" to be defined in file "%s". The file was found but the class was not in it, the class name or namespace probably has a typo.', $class, $file));
            }
            if (self::$caseCheck) {
                $real = explode('\\', $class.strrchr($file, '.'));
                $tail = explode(DIRECTORY_SEPARATOR, str_replace('/', DIRECTORY_SEPARATOR, $file));

                $i = count($tail) - 1;
                $j = count($real) - 1;

                while (isset($tail[$i], $real[$j]) && $tail[$i] === $real[$j]) {
                    --$i;
                    --$j;
                }

                array_splice($tail, 0, $i + 1);
            }
            if (self::$caseCheck && $tail) {
                $tail = DIRECTORY_SEPARATOR.implode(DIRECTORY_SEPARATOR, $tail);
                $tailLen = strlen($tail);
                $real = $refl->getFileName();

                if (2 === self::$caseCheck) {
                    // realpath() on MacOSX doesn't normalize the case of characters

                    $i = 1 + strrpos($real, '/');
                    $file = substr($real, $i);
                    $real = substr($real, 0, $i);

                    if (isset(self::$darwinCache[$real])) {
                        $kDir = $real;
                    } else {
                        $kDir = strtolower($real);

                        if (isset(self::$darwinCache[$kDir])) {
                            $real = self::$darwinCache[$kDir][0];
                        } else {
                            $dir = getcwd();
                            chdir($real);
                            $real = getcwd().'/';
                            chdir($dir);

                            $dir = $real;
                            $k = $kDir;
                            $i = strlen($dir) - 1;
                            while (!isset(self::$darwinCache[$k])) {
                                self::$darwinCache[$k] = array($dir, array());
                                self::$darwinCache[$dir] = &self::$darwinCache[$k];

                                while ('/' !== $dir[--$i]) {
                                }
                                $k = substr($k, 0, ++$i);
                                $dir = substr($dir, 0, $i--);
                            }
                        }
                    }

                    $dirFiles = self::$darwinCache[$kDir][1];

                    if (isset($dirFiles[$file])) {
                        $kFile = $file;
                    } else {
                        $kFile = strtolower($file);

                        if (!isset($dirFiles[$kFile])) {
                            foreach (scandir($real, 2) as $f) {
                                if ('.' !== $f[0]) {
                                    $dirFiles[$f] = $f;
                                    if ($f === $file) {
                                        $kFile = $k = $file;
                                    } elseif ($f !== $k = strtolower($f)) {
                                        $dirFiles[$k] = $f;
                                    }
                                }
                            }
                            self::$darwinCache[$kDir][1] = $dirFiles;
                        }
                    }

                    $real .= $dirFiles[$kFile];
                }

                if (0 === substr_compare($real, $tail, -$tailLen, $tailLen, true)
                  && 0 !== substr_compare($real, $tail, -$tailLen, $tailLen, false)
                ) {
                    throw new \RuntimeException(sprintf('Case mismatch between class and real file names: "%s" vs "%s" in "%s".', substr($tail, -$tailLen + 1), substr($real, -$tailLen + 1), substr($real, 0, -$tailLen + 1)));
                }
            }
        }
    }

    /**
     * `class_implements` includes interfaces from the parents so we have to manually exclude them.
     *
     * @param string       $class
     * @param string|false $parent
     *
     * @return string[]
     */
    private function getOwnInterfaces($class, $parent)
    {
        $ownInterfaces = class_implements($class, false);

        if ($parent) {
            foreach (class_implements($parent, false) as $interface) {
                unset($ownInterfaces[$interface]);
            }
        }

        foreach ($ownInterfaces as $interface) {
            foreach (class_implements($interface) as $interface) {
                unset($ownInterfaces[$interface]);
            }
        }

        return $ownInterfaces;
    }
}


text:
namespace System.Activities.DurableInstancing
{
    using System.Data;
    using System.Data.SqlClient;
    using System.Globalization;
    using System.Linq;
    using System.Runtime;
    using System.Transactions;
    using System.Runtime.Diagnostics;

    sealed class SqlCommandAsyncResult : TransactedAsyncResult
    {

        static readonly TimeSpan MaximumOpenTimeout = TimeSpan.FromMinutes(2);

        static readonly RetryErrorCode[] retryErrorCodes =
            {
                new RetryErrorCode(-2, RetryErrorOptions.RetryBeginOrEnd | RetryErrorOptions.RetryWhenTransaction), // SqlError: Timeout
                new RetryErrorCode(20, RetryErrorOptions.RetryBeginOrEnd | RetryErrorOptions.RetryWhenTransaction), // SQL Azure error - a connection failed early in the login process. to SQL Server.
                new RetryErrorCode(53, RetryErrorOptions.RetryBeginOrEnd | RetryErrorOptions.RetryWhenTransaction), //A network-related or instance-specific error occurred while establishing a connection to SQL Server.
                new RetryErrorCode(64, RetryErrorOptions.RetryBeginOrEnd | RetryErrorOptions.RetryWhenTransaction), //A transport-level error has occurred when receiving results from the server (TCP Provider, error: 0 - The specified network name is no longer available).
                new RetryErrorCode(121, RetryErrorOptions.RetryBeginOrEnd), //  A transport-level error has occurred
                new RetryErrorCode(233, RetryErrorOptions.RetryBeginOrEnd | RetryErrorOptions.RetryWhenTransaction), // Severed shared memory/named pipe connection drawn from the pool
                new RetryErrorCode(1205, RetryErrorOptions.RetryBeginOrEnd), // Deadlock
                new RetryErrorCode(1222, RetryErrorOptions.RetryBeginOrEnd | RetryErrorOptions.RetryWhenTransaction), // Lock Request Timeout
                new RetryErrorCode(3910, RetryErrorOptions.RetryOnBegin | RetryErrorOptions.RetryWhenTransaction), // Transaction context in use by another session.
                new RetryErrorCode(4060, RetryErrorOptions.RetryBeginOrEnd | RetryErrorOptions.RetryWhenTransaction), // Database not online
                new RetryErrorCode(8645, RetryErrorOptions.RetryBeginOrEnd | RetryErrorOptions.RetryWhenTransaction), // A timeout occurred while waiting for memory resources
                new RetryErrorCode(8641, RetryErrorOptions.RetryBeginOrEnd | RetryErrorOptions.RetryWhenTransaction), // Could not perform the operation because the requested memory grant was not available
                new RetryErrorCode(10053, RetryErrorOptions.RetryBeginOrEnd | RetryErrorOptions.RetryWhenTransaction), // A transport-level error has occurred when receiving results from the server
                new RetryErrorCode(10054, RetryErrorOptions.RetryBeginOrEnd | RetryErrorOptions.RetryWhenTransaction), // Severed tcp connection drawn from the pool
                new RetryErrorCode(10060, RetryErrorOptions.RetryBeginOrEnd | RetryErrorOptions.RetryWhenTransaction), // The server was not found or was not accessible.
                new RetryErrorCode(10061, RetryErrorOptions.RetryBeginOrEnd | RetryErrorOptions.RetryWhenTransaction), // SQL Server not started
                new RetryErrorCode(40143, RetryErrorOptions.RetryBeginOrEnd | RetryErrorOptions.RetryWhenTransaction), // SQL Azure error - server encountered error processing the request.
                new RetryErrorCode(40197, RetryErrorOptions.RetryBeginOrEnd | RetryErrorOptions.RetryWhenTransaction), // SQL Azure error - server encountered error processing the request.
                new RetryErrorCode(40501, RetryErrorOptions.RetryBeginOrEnd | RetryErrorOptions.RetryWhenTransaction), // SQL Azure error - server is currently busy.
                new RetryErrorCode(40549, RetryErrorOptions.RetryBeginOrEnd | RetryErrorOptions.RetryWhenTransaction), // SQL Azure error - transaction blocking system calls
                new RetryErrorCode(40553, RetryErrorOptions.RetryBeginOrEnd | RetryErrorOptions.RetryWhenTransaction), // SQL Azure error - excessive memory usage
                new RetryErrorCode(40613, RetryErrorOptions.RetryBeginOrEnd | RetryErrorOptions.RetryWhenTransaction) // SQL Azure error - database on server is not available.
            };

        static AsyncCompletion onExecuteReaderCallback = new AsyncCompletion(OnExecuteReader);
        static AsyncCompletion onRetryCommandCallback = new AsyncCompletion(OnRetryCommand);
        string connectionString;
        DependentTransaction dependentTransaction;
        int maximumRetries;
        int retryCount;
        EventTraceActivity eventTraceActivity;

        SqlCommand sqlCommand;
        SqlDataReader sqlDataReader;
        TimeoutHelper timeoutHelper;

        public SqlCommandAsyncResult(SqlCommand sqlCommand, string connectionString, EventTraceActivity eventTraceActivity, DependentTransaction dependentTransaction,
            TimeSpan timeout, int retryCount, int maximumRetries, AsyncCallback callback, object state)
            : base(callback, state)
        {
            long openTimeout = Math.Min(timeout.Ticks, SqlCommandAsyncResult.MaximumOpenTimeout.Ticks);
            this.sqlCommand = sqlCommand;
            this.connectionString = connectionString;
            this.eventTraceActivity = eventTraceActivity;
            this.dependentTransaction = dependentTransaction;
            this.timeoutHelper = new TimeoutHelper(TimeSpan.FromTicks(openTimeout));
            this.retryCount = retryCount;
            this.maximumRetries = maximumRetries;
        }

        [Flags]
        enum RetryErrorOptions
        {
            RetryOnBegin = 1,
            RetryOnEnd = 2,
            RetryWhenTransaction = 4,
            RetryBeginOrEnd = RetryOnBegin | RetryOnEnd
        }

        public static SqlDataReader End(IAsyncResult result)
        {
            SqlCommandAsyncResult SqlCommandAsyncResult = AsyncResult.End<SqlCommandAsyncResult>(result);
            return SqlCommandAsyncResult.sqlDataReader;
        }

        public void StartCommand()
        {
            StartCommandInternal(true);
        }

        static bool OnExecuteReader(IAsyncResult result)
        {
            SqlCommandAsyncResult thisPtr = (SqlCommandAsyncResult)(result.AsyncState);
            return thisPtr.CompleteExecuteReader(result);
        }

        static bool OnRetryCommand(IAsyncResult childPtr)
        {
            SqlCommandAsyncResult parentPtr = (SqlCommandAsyncResult)(childPtr.AsyncState);
            parentPtr.sqlDataReader = SqlCommandAsyncResult.End(childPtr);
            return true;
        }

        static bool ShouldRetryForSqlError(int error, RetryErrorOptions retryErrorOptions)
        {
            if (Transaction.Current != null)
            {
                retryErrorOptions |= RetryErrorOptions.RetryWhenTransaction;
            }
            return SqlCommandAsyncResult.retryErrorCodes.Any(x => x.ErrorCode == error && (x.RetryErrorOptions & retryErrorOptions) == retryErrorOptions);
        }

        static void StartCommandCallback(object state)
        {
            SqlCommandAsyncResult thisPtr = (SqlCommandAsyncResult) state;
            try
            {
                // this can throw on the [....] path - we need to signal the callback
                thisPtr.StartCommandInternal(false);
            }
            catch (Exception e)
            {
                if (Fx.IsFatal(e))
                {
                    throw;
                }

                if (thisPtr.sqlCommand.Connection != null)
                {
                    thisPtr.sqlCommand.Connection.Close();
                }

                thisPtr.Complete(false, e);
            }
        }
        bool CheckRetryCount()
        {
            return (++this.retryCount < maximumRetries);
        }

        bool CheckRetryCountAndTimer()
        {
            return (this.CheckRetryCount() && !this.HasOperationTimedOut());
        }

        bool CompleteExecuteReader(IAsyncResult result)
        {
            bool completeSelf = true;

            try
            {
                this.sqlDataReader = this.sqlCommand.EndExecuteReader(result);
            }
            catch (SqlException exception)
            {
                if (TD.SqlExceptionCaughtIsEnabled())
                {
                    TD.SqlExceptionCaught(this.eventTraceActivity, exception.Number.ToString(CultureInfo.InvariantCulture), exception.Message);
                }

                if (this.sqlDataReader != null)
                {
                    this.sqlDataReader.Close();
                }

                if (this.sqlCommand.Connection != null)
                {
                    this.sqlCommand.Connection.Close();
                }

                // If we completed [....] then any retry is done by the original caller.
                if (!result.CompletedSynchronously)
                {
                    if (this.CheckRetryCountAndTimer() && ShouldRetryForSqlError(exception.Number, RetryErrorOptions.RetryOnEnd))
                    {
                        if (this.EnqueueRetry())
                        {
                            if (TD.RetryingSqlCommandDueToSqlErrorIsEnabled())
                            {
                                TD.RetryingSqlCommandDueToSqlError(this.eventTraceActivity, exception.Number.ToString(CultureInfo.InvariantCulture));
                            }
                            completeSelf = false;
                        }
                    }
                }

                if (completeSelf)
                {
                    if (this.retryCount == maximumRetries && TD.MaximumRetriesExceededForSqlCommandIsEnabled())
                    {
                        TD.MaximumRetriesExceededForSqlCommand(this.eventTraceActivity);
                    }

                    throw;
                }
            }

            return completeSelf;
        }

        bool EnqueueRetry()
        {
            bool result = false;

            int delay = this.GetRetryDelay();

            if (this.timeoutHelper.RemainingTime().TotalMilliseconds > delay)
            {
                this.sqlCommand.Dispose();
                IOThreadTimer iott = new IOThreadTimer(StartCommandCallback, new SqlCommandAsyncResult(CloneSqlCommand(this.sqlCommand), this.connectionString, this.eventTraceActivity, this.dependentTransaction,
                    this.timeoutHelper.RemainingTime(), this.retryCount, this.maximumRetries, this.PrepareAsyncCompletion(onRetryCommandCallback), this), false);
                iott.Set(delay);

                if (TD.QueuingSqlRetryIsEnabled())
                {
                    TD.QueuingSqlRetry(this.eventTraceActivity, delay.ToString(CultureInfo.InvariantCulture));
                }

                result = true;
            }

            return result;
        }

        static SqlCommand CloneSqlCommand(SqlCommand command)
        {
            //We do not want to use SqlCommand.Clone here because we do not want to replicate the parameters
            SqlCommand newCommand = new SqlCommand()
            {
                CommandType = command.CommandType,
                CommandText = command.CommandText,
            };

            SqlParameter[] tempParameterList = new SqlParameter[command.Parameters.Count];
            for (int i = 0; i < command.Parameters.Count; i++)
            {
                tempParameterList[i] = command.Parameters[i];
            }
            command.Parameters.Clear();
            newCommand.Parameters.AddRange(tempParameterList);

            return newCommand;
        }

        int GetRetryDelay()
        {
            return 1000;
        }

        bool HasOperationTimedOut()
        {
            return (this.timeoutHelper.RemainingTime() <= TimeSpan.Zero);
        }

        void StartCommandInternal(bool synchronous)
        {
            if (!this.HasOperationTimedOut())
            {
                try
                {
                    IAsyncResult result;

                    using (this.PrepareTransactionalCall(this.dependentTransaction))
                    {
                        AsyncCallback wrappedCallback = this.PrepareAsyncCompletion(onExecuteReaderCallback);
                        this.sqlCommand.Connection = StoreUtilities.CreateConnection(this.connectionString);
                        if (!this.HasOperationTimedOut())
                        {
                            result = this.sqlCommand.BeginExecuteReader(wrappedCallback, this, CommandBehavior.CloseConnection);
                        }
                        else
                        {
                            this.sqlCommand.Connection.Close();
                            this.Complete(synchronous, new TimeoutException(SR.TimeoutOnSqlOperation(this.timeoutHelper.OriginalTimeout.ToString())));
                            return;
                        }
                    }

                    if (this.CheckSyncContinue(result))
                    {
                        if (this.CompleteExecuteReader(result))
                        {
                            this.Complete(synchronous);
                        }
                    }
                    return;
                }
                catch (SqlException exception)
                {
                    if (TD.SqlExceptionCaughtIsEnabled())
                    {
                        TD.SqlExceptionCaught(this.eventTraceActivity, exception.Number.ToString(null, CultureInfo.InvariantCulture), exception.Message);
                    }

                    if (this.sqlCommand.Connection != null)
                    {
                        this.sqlCommand.Connection.Close();
                    }

                    if (!this.CheckRetryCount() || !ShouldRetryForSqlError(exception.Number, RetryErrorOptions.RetryOnBegin))
                    {
                        throw;
                    }

                    if (TD.RetryingSqlCommandDueToSqlErrorIsEnabled())
                    {
                        TD.RetryingSqlCommandDueToSqlError(this.eventTraceActivity, exception.Number.ToString(CultureInfo.InvariantCulture));
                    }
                }
                catch (InvalidOperationException)
                {
                    if (!this.CheckRetryCount())
                    {
                        throw;
                    }
                }

                if (this.EnqueueRetry())
                {
                    return;
                }
            }

            if (this.HasOperationTimedOut())
            {
                if (TD.TimeoutOpeningSqlConnectionIsEnabled())
                {
                    TD.TimeoutOpeningSqlConnection(this.eventTraceActivity, this.timeoutHelper.OriginalTimeout.ToString());
                }
            }
            else
            {
                if (TD.MaximumRetriesExceededForSqlCommandIsEnabled())
                {
                    TD.MaximumRetriesExceededForSqlCommand(this.eventTraceActivity);
                }
            }

            this.Complete(synchronous, new TimeoutException(SR.TimeoutOnSqlOperation(this.timeoutHelper.OriginalTimeout.ToString())));
        }

        class RetryErrorCode
        {
            public RetryErrorCode(int code, RetryErrorOptions retryErrorOptions)
            {
                this.ErrorCode = code;
                this.RetryErrorOptions = retryErrorOptions;
            }

            public int ErrorCode
            {
                get;
                private set;
            }

            public RetryErrorOptions RetryErrorOptions
            {
                get;
                private set;
            }
        }
    }
}


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

#import "MaterialColorScheme.h"
#import "MaterialNavigationDrawer.h"

#import <Foundation/Foundation.h>

/**
 The Material Design color system's themer for instances of MDCBottomDrawerViewController.
 */
@interface MDCBottomDrawerColorThemer : NSObject

/**
 Applies a color scheme's properties to an MDCBottomDrawerViewController

 @param colorScheme The color scheme to apply to the component instance.
 @param bottomDrawer A component instance to which the color scheme should be applied.
 */
+ (void)applySemanticColorScheme:(nonnull id<MDCColorScheming>)colorScheme
                  toBottomDrawer:(nonnull MDCBottomDrawerViewController *)bottomDrawer;

@end


text:
require 'github_api'
require 'rest'
require 'json'

module Metrics
  class Github
    ITEMS_PER_PAGE = 10

    attr_reader :user, :repo

    class ParseError < StandardError; end
    class RateLimitError < StandardError
      attr_reader :resets_at, :limit

      def initialize(limit, resets_at)
        super('Rate Limit exceeded')

        @limit = limit
        @resets_at = resets_at
      end
    end

    def initialize_client_with_repo_address(url)
      @user, @repo = parse url
      params = {
        :user => @user,
        :repo => @repo
      }
      github_client params
    end

    def github_client params
      if ENV['GITHUB_BOT_USER'] && ENV['GITHUB_BOT_PASS']
        params[:basic_auth] = "#{ENV['GITHUB_BOT_USER']}:#{ENV['GITHUB_BOT_PASS']}"
      end
      ::Github.new(params)
    end

    # Updates a GithubPodMetrics model with the latest Github data.
    #
    def update(pod)
      if url = pod.github_url
        client = initialize_client_with_repo_address(url)
        repo = client.repos.find
        client, repo = check_repo_redirection(client, repo)

        check_rate_limiting(repo)
        GithubPodMetrics.update_or_create({ :pod_id => pod.id }, update_hash(client, repo))

        reset_not_found(pod)
      else
        # Not having a Github URL counts as not found in the Github context.
        #
        not_found(pod)
      end
    rescue ParseError
      not_found(pod)
    rescue StandardError => e
      handle_update_error(e, pod)
    end

    def update_hash(client, repo)
      closed_issues = total_count_of(:closed_issues, client)
      closed_pull_requests = total_count_of(:closed_pull_requests, client)
      open_pull_requests = total_count_of(:open_pull_requests, client)
      {
        :subscribers => repo.subscribers_count,
        :stargazers => repo.stargazers_count,
        :forks => repo.forks_count,
        :contributors => total_count_of(:contributors, client),
        # Because every PR is an issue we subtract the closed/open PRs
        # from the closed/open issues
        :open_issues => repo.open_issues_count - open_pull_requests,
        :closed_issues => closed_issues - closed_pull_requests,
        :open_pull_requests => open_pull_requests,
        :closed_pull_requests => closed_pull_requests,
        :language => repo.language
      }
    end

    def handle_update_error(e, pod)
      case e.message
      when /404 Not Found/
        not_found(pod)
      when /403 API rate limit exceeded/
        headers = ::Github::Response::Header.new response_headers: e.http_headers
        raise build_rate_limit_error(headers)
      else
        # Only log out when there's an unexpected error, vs expected errors
        METRICS_APP_LOGGER.error e
        raise
      end
    end

    def check_rate_limiting(response)
      remaining = response.headers.ratelimit_remaining
      raise build_rate_limit_error(response.headers) if remaining.nil? || remaining.to_i <= 0
    end

    # Support GitHub's repo redirection feature
    #
    def check_repo_redirection(client, repo)
      if repo.respond_to?(:redirect?) && repo.redirect?
          redirect_details = REST.get(repo.url).body
          url = JSON.parse(redirect_details)["url"]

          new_repo_details = REST.get(url).body
          url = JSON.parse(new_repo_details)["url"]

          client = initialize_client_with_repo_address url
          repo = client.repos.find
      end
       [client, repo]
    end

    # Adds 1 to a GithubPodMetrics model's not found attribute.
    #
    def not_found(pod)
      metrics = pod.github_pod_metrics

      if metrics
        metrics.update(:not_found => (metrics.not_found + 1))
      else
        GithubPodMetrics.create(:pod_id => pod.id, :not_found => 1)
      end
    end

    def reset_not_found(pod)
      metrics = pod.github_pod_metrics
      if metrics
        metrics.update(:not_found => 0)
        metrics
      end
    end

    private

    def total_count_of(collection, client)
      case collection
      when :contributors
        result = client.repos.contributors(:per_page => ITEMS_PER_PAGE)
      when :open_pull_requests
        result = client.pull_requests.all(:state => 'open',
                                          :per_page => ITEMS_PER_PAGE)
      when :closed_pull_requests
        result = client.pull_requests.all(:state => 'closed',
                                          :per_page => ITEMS_PER_PAGE)
      when :closed_issues
        result = client.issues.list(:state => 'closed',
                                    :per_page => ITEMS_PER_PAGE,
                                    :user => client.user,
                                    :repo => client.repo)
      else
        raise 'Unsupported collection'
      end

      # Stop early if the first page contained all items
      return result.size if result.size < ITEMS_PER_PAGE
      page_count = result.count_pages

      last = result.last_page
      return result.size if last.nil?

      ITEMS_PER_PAGE * (page_count - 1) + last.size
    end

    def build_rate_limit_error(headers)
      resets_at = headers.ratelimit_reset.to_i
      limit = headers.ratelimit_limit.to_i

      resets_at = Time.now.to_i + 4000 if resets_at == 0
      raise RateLimitError.new(limit, resets_at)
    end

    # Takes a URL like
    #   https://github.com/lakesoft/LKAssetsLibrary.git
    # and finds its user/repo:
    #   lakesoft and LKAssetsLibrary
    #
    def parse(url)
      matches = url.match(%r{[:/](?<user>[^/]+)/(?<repo>[^/]+)\z})
      [matches[:user], matches[:repo].gsub(/\.git\z/, '')]
    rescue StandardError => e
      raise ParseError, 'Can not parse Github URL.'
    end
  end
end


text:
@protocol FPFactoryViewDataSource

@property (readonly) NSMutableArray *factories;
@property (readwrite, assign) id activeFactory;

@end

@interface FPFactoryView : NSOpenGLView
{
	IBOutlet id<FPFactoryViewDataSource> dataSource;
}

@end


text:
package com.arthurb.iterator.dinermergergery;

import java.util.Iterator;

/**
 * Created by Blackwood on 07.03.2016 23:00.
 */

// Простой интерфейс с единственным методом, который возвращает клиентам итератор для элементов меню
public interface Menu {
    public Iterator createIterator();
}