text:
package rice.pastry.peerreview;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;

import org.mpisws.p2p.transport.ErrorHandler;
import org.mpisws.p2p.transport.MessageCallback;
import org.mpisws.p2p.transport.MessageRequestHandle;
import org.mpisws.p2p.transport.P2PSocket;
import org.mpisws.p2p.transport.SocketCallback;
import org.mpisws.p2p.transport.SocketRequestHandle;
import org.mpisws.p2p.transport.TransportLayer;
import org.mpisws.p2p.transport.TransportLayerCallback;
import org.mpisws.p2p.transport.multiaddress.MultiInetSocketAddress;
import org.mpisws.p2p.transport.peerreview.PeerReview;
import org.mpisws.p2p.transport.peerreview.PeerReviewCallback;
import org.mpisws.p2p.transport.peerreview.WitnessListener;
import org.mpisws.p2p.transport.peerreview.replay.Verifier;

import rice.Continuation;
import rice.environment.Environment;
import rice.environment.logging.Logger;
import rice.p2p.commonapi.rawserialization.InputBuffer;
import rice.p2p.commonapi.rawserialization.OutputBuffer;
import rice.pastry.Id;
import rice.pastry.NodeHandle;
import rice.pastry.NodeHandleFactory;
import rice.pastry.PastryNode;
import rice.pastry.socket.SocketNodeHandle;
import rice.pastry.socket.SocketNodeHandleFactory;
import rice.pastry.socket.SocketPastryNodeFactory;
import rice.pastry.socket.TransportLayerNodeHandle;
import rice.pastry.transport.NodeHandleAdapter;
import rice.pastry.transport.TLDeserializer;

public class PeerReviewCallbackImpl implements PeerReviewCallback<TransportLayerNodeHandle<MultiInetSocketAddress>, Id>,
    TransportLayer<TransportLayerNodeHandle<MultiInetSocketAddress>, ByteBuffer> {

  CallbackFactory nodeFactory;

  PastryNode pn;
  TransportLayer<TransportLayerNodeHandle<MultiInetSocketAddress>, ByteBuffer> tl;
  TransportLayerCallback<TransportLayerNodeHandle<MultiInetSocketAddress>, ByteBuffer>callback;

  FetchLeafsetApp fetchLeafSetApp;

  Logger logger;

  public PeerReviewCallbackImpl(PastryNode pn, TransportLayer<TransportLayerNodeHandle<MultiInetSocketAddress>, ByteBuffer> tl, CallbackFactory nodeFactory) {
    this(tl);
    this.pn = pn;
    this.nodeFactory = nodeFactory;
    this.logger = pn.getEnvironment().getLogManager().getLogger(getClass(), null);

    this.fetchLeafSetApp = new FetchLeafsetApp(pn,4);
    fetchLeafSetApp.register();
  }

  // only used in getReplayInstance
  protected PeerReviewCallbackImpl(TransportLayer<TransportLayerNodeHandle<MultiInetSocketAddress>, ByteBuffer> tl) {
    this.tl = tl;
  }

  /**
   * Construct a PastryNode down to my layer (figure out how to borrow the code from the PastryNodeFactory)
   * Construct a PeerReviewCallbackImpl with the PastryNode/Verifier
   * Construct the layers above self, attach them appropriately.
   */
  public PeerReviewCallback<TransportLayerNodeHandle<MultiInetSocketAddress>, Id> getReplayInstance(
      Verifier<TransportLayerNodeHandle<MultiInetSocketAddress>> v) {
    // defer the pastry node construction until we can get a checkpoint!
    return new PeerReviewCallbackImpl(v);
  }

  /**
   * Store rt/leafset
   */
  public void storeCheckpoint(OutputBuffer buffer) throws IOException {
    pn.getId().serialize(buffer); // redundant, but necessary for the way a PastryNode is constructed
    pn.getLocalHandle().serialize(buffer);
  }

  /**
   * Load rt/leafset
   */
  public boolean loadCheckpoint(InputBuffer buffer) throws IOException {
    Environment environment = ((Verifier<TransportLayerNodeHandle<MultiInetSocketAddress>>)tl).getEnvironment();
    Id nodeId = Id.build(buffer);
    pn = new PastryNode(nodeId, environment);
    NodeHandleFactory nodeHandleFactory = nodeFactory.getNodeHandleFactory(pn);
    NodeHandle handle = nodeHandleFactory.readNodeHandle(buffer);
    // put this in the localHandleTable, where it will be read/removed in the hacked PastryNodeFactory
    nodeFactory.localHandleTable.put(pn,handle);
    nodeFactory.nodeHandleHelper(pn);

    // load rt/leafset, liveness state
    // register witness searching algorithm

    return true;
  }

  public Collection<TransportLayerNodeHandle<MultiInetSocketAddress>> getMyWitnessedNodes() {
    Collection<NodeHandle> foo = pn.getLeafSet().getUniqueSet(); // TODO: make this a smaller set
    ArrayList<TransportLayerNodeHandle<MultiInetSocketAddress>> ret =
      new ArrayList<TransportLayerNodeHandle<MultiInetSocketAddress>>(foo.size());
    for (NodeHandle h : foo) {
      ret.add((TransportLayerNodeHandle<MultiInetSocketAddress>)h);
    }
    logger.log("myWitnessedNodes: "+ret);
    return ret;
  }

  public void init() {
    // TODO Auto-generated method stub

  }

  public void destroy() {
    // TODO Auto-generated method stub

  }

  public void notifyCertificateAvailable(Id id) {
    // TODO Auto-generated method stub

  }

  public void incomingSocket(P2PSocket<TransportLayerNodeHandle<MultiInetSocketAddress>> s) throws IOException {
    callback.incomingSocket(s);
  }

  public void messageReceived(TransportLayerNodeHandle<MultiInetSocketAddress> i, ByteBuffer m,
      Map<String, Object> options) throws IOException {
    callback.messageReceived(i, m, options);
  }

  public void notifyStatusChange(Id id, int newStatus) {
    // TODO Auto-generated method stub

  }

  public void acceptMessages(boolean b) {
    // TODO Auto-generated method stub

  }

  public void acceptSockets(boolean b) {
    // TODO Auto-generated method stub

  }

  public void getWitnesses(
      final Id subject,
      final WitnessListener<TransportLayerNodeHandle<MultiInetSocketAddress>, Id> callback) {
    fetchLeafSetApp.getNeighbors(subject,new Continuation<Collection<NodeHandle>, Exception>() {

      public void receiveResult(Collection<NodeHandle> result) {
        ArrayList<TransportLayerNodeHandle<MultiInetSocketAddress>> ret = new ArrayList<TransportLayerNodeHandle<MultiInetSocketAddress>>(result.size());
        for (NodeHandle nh : result) {
          if (!nh.getId().equals(subject)) ret.add((TransportLayerNodeHandle<MultiInetSocketAddress>)nh);
        }
        logger.log("returning witnesses for "+subject+" "+ret);
        callback.notifyWitnessSet(subject, ret);
      }

      public void receiveException(Exception exception) {
        throw new RuntimeException(exception);
      }

    });
  }

  public TransportLayerNodeHandle<MultiInetSocketAddress> getLocalIdentifier() {
    return tl.getLocalIdentifier();
  }

  public SocketRequestHandle<TransportLayerNodeHandle<MultiInetSocketAddress>> openSocket(TransportLayerNodeHandle<MultiInetSocketAddress> i,
      SocketCallback<TransportLayerNodeHandle<MultiInetSocketAddress>> deliverSocketToMe, Map<String, Object> options) {
    return tl.openSocket(i, deliverSocketToMe, options);
  }

  public void setCallback(
      TransportLayerCallback<TransportLayerNodeHandle<MultiInetSocketAddress>, ByteBuffer> callback) {
    this.callback = callback;
  }

  public void setErrorHandler(ErrorHandler<TransportLayerNodeHandle<MultiInetSocketAddress>> handler) {
    // TODO Auto-generated method stub

  }

  public MessageRequestHandle<TransportLayerNodeHandle<MultiInetSocketAddress>, ByteBuffer> sendMessage(
      TransportLayerNodeHandle<MultiInetSocketAddress> i,
      ByteBuffer m,
      MessageCallback<TransportLayerNodeHandle<MultiInetSocketAddress>, ByteBuffer> deliverAckToMe,
      Map<String, Object> options) {
    return tl.sendMessage(i, m, deliverAckToMe, options);
  }

}

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

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

#### Published in
null

#### Original name
Tibouchina virescens Cogn.

### Remarks
null


text:
package org.apache.servicemix.expression;

import javax.jbi.messaging.MessageExchange;
import javax.jbi.messaging.MessagingException;
import javax.jbi.messaging.NormalizedMessage;

/**
 * Represents a constant expression
 *
 * @version $Revision: 426415 $
 */
public class ConstantExpression implements Expression {
    private Object value;

    public ConstantExpression(Object value) {
        this.value = value;
    }

    public Object evaluate(MessageExchange exchange, NormalizedMessage message) throws MessagingException {
        return value;
    }
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Welcome extends CI_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see https://codeigniter.com/user_guide/general/urls.html
	 */
	public function index()
	{
		$this->load->view('welcome_message');
	}

	public function hello()
    {
        $this->load->view('welcome');
    }

    public function  spas()
    {
        $this->load->view('spas');
    }

    public function  love()
    {
        $matches = array(
            array(
                'openent' => 'Anthony Joshua',
            ),
            array(
                'openent' => 'Anthony Joshua',
            ),
            array(
                'openent' => 'Anthony Joshua',
            )
        );

        $data['matches'] = $matches;
        $this->load->view('love', $data);
    }
}


text:
#region Apache Notice

#endregion

using System;
using System.Reflection;

namespace IBatisNet.Common.Utilities.Objects.Members
{
    /// <summary>
    /// The <see cref="ReflectionPropertyGetAccessor"/> class provides an reflection get access
    /// to a property of a specified target class.
    /// </summary>
    public sealed class ReflectionPropertyGetAccessor : IGetAccessor
    {
        private PropertyInfo _propertyInfo = null;
		private string _propertyName = string.Empty;
		private Type _targetType = null;

        /// <summary>
        /// Initializes a new instance of the <see cref="ReflectionPropertyGetAccessor"/> class.
        /// </summary>
        /// <param name="targetType">Type of the target.</param>
        /// <param name="propertyName">Name of the property.</param>
        public ReflectionPropertyGetAccessor(Type targetType, string propertyName)
		{
			ReflectionInfo reflectionCache = ReflectionInfo.GetInstance( targetType );
            _propertyInfo = (PropertyInfo)reflectionCache.GetGetter(propertyName);

            _targetType = targetType;
			_propertyName = propertyName;
		}

        #region IAccessor Members

        /// <summary>
        /// Gets the property name.
        /// </summary>
        public string Name
        {
            get { return _propertyInfo.Name; }
        }

        /// <summary>
        /// Gets the type of this property.
        /// </summary>
        public Type MemberType
        {
            get { return _propertyInfo.PropertyType; }
        }

        #endregion

        #region IGet Members

        /// <summary>
        /// Gets the value stored in the property for
        /// the specified target.
        /// </summary>
        /// <param name="target">Object to retrieve the property from.</param>
        /// <returns>Property value.</returns>
        public object Get(object target)
        {
            if (_propertyInfo.CanRead)
            {
                return _propertyInfo.GetValue(target, null);
            }
            else
            {
                throw new NotSupportedException(
                    string.Format("Property \"{0}\" on type "
                    + "{1} doesn't have a get method.", _propertyName, _targetType));
            }
        }

        #endregion
    }
}


text:
import sys, re, time, string
import numpy;
import scipy;
import scipy.special;
import nltk;

from inferencer import compute_dirichlet_expectation;
from inferencer import Inferencer;

class Hybrid(Inferencer):
    def __init__(self,
                 hash_oov_words=False,
                 number_of_samples=10,
                 burn_in_sweeps=5
                 ):
        Inferencer.__init__(self, hash_oov_words);

        self._number_of_samples = number_of_samples;
        self._burn_in_sweeps = burn_in_sweeps;

    def parse_doc_list(self, docs):
        if (type(docs).__name__ == 'str'):
            temp = list()
            temp.append(docs)
            docs = temp

        D = len(docs)

        wordids = list()
        for d in range(0, D):
            docs[d] = docs[d].lower()
            docs[d] = re.sub(r'-', ' ', docs[d])
            docs[d] = re.sub(r'[^a-z ]', '', docs[d])
            docs[d] = re.sub(r' +', ' ', docs[d])
            words = string.split(docs[d])
            ddict=[];
            for word in words:
                if (word in self._vocab):
                    ddict.append(self._vocab[word])
                else:
                    if self._hash_oov_words:
                        ddict.append(hash(word) % len(self._vocab));
            if len(ddict)==0:
                print >> sys.stderr, 'warning: document collapsed during parsing...'
            wordids.append(ddict);

        return wordids;

    def e_step(self, wordids):
        batchD = len(wordids)

        document_level_elbo = 0;

        sufficient_statistics = numpy.zeros((self._number_of_topics, self._vocab_size));

        # Initialize the variational distribution q(theta|gamma) for the mini-batch
        batch_document_topic_distribution = numpy.zeros((batchD, self._number_of_topics));

        # Now, for each document d update that document's gamma and phi
        for d in xrange(batchD):
            phi = numpy.random.random((self._number_of_topics, len(wordids[d])));
            phi = phi / numpy.sum(phi, axis=0)[numpy.newaxis, :];
            phi_sum = numpy.sum(phi, axis=1)[:, numpy.newaxis];
            assert(phi_sum.shape == (self._number_of_topics, 1));

            for it in xrange(self._number_of_samples):
                for n in xrange(len(wordids[d])):
                    id = wordids[d][n];

                    phi_sum -= phi[:, n][:, numpy.newaxis];

                    # this is to get rid of the underflow error from the above summation, ideally, phi will become all integers after few iterations
                    phi_sum *= phi_sum > 0;
                    #assert(numpy.all(phi_sum >= 0));

                    temp_phi = (phi_sum + self._alpha_theta).T * self._exp_E_log_beta[:, wordids[d][n]];
                    assert(temp_phi.shape == (1, self._number_of_topics));
                    temp_phi /= numpy.sum(temp_phi);

                    # sample a topic for this word
                    temp_phi = numpy.random.multinomial(1, temp_phi[0, :])[:, numpy.newaxis];
                    assert(temp_phi.shape == (self._number_of_topics, 1));

                    phi[:, n][:, numpy.newaxis] = temp_phi;
                    phi_sum += temp_phi;

                    # discard the first few burn-in sweeps
                    if it < self._burn_in_sweeps:
                        continue;

                    sufficient_statistics[:, id] += temp_phi[:, 0];

            batch_document_topic_distribution[d, :] = self._alpha_theta + phi_sum.T[0, :];

            if self._compute_elbo:
                document_level_elbo += len(wordids[d]);

                gammad = batch_document_topic_distribution[d];
                document_level_elbo += numpy.sum((self._alpha_theta - gammad) * numpy.exp(compute_dirichlet_expectation(gammad)));
                document_level_elbo += numpy.sum(scipy.special.gammaln(gammad) - scipy.special.gammaln(self._alpha_theta));
                document_level_elbo += numpy.sum(scipy.special.gammaln(self._alpha_theta * self._number_of_topics) - scipy.special.gammaln(numpy.sum(gammad)));

        sufficient_statistics /= (self._number_of_samples - self._burn_in_sweeps);

        if self._compute_elbo:
            document_level_elbo *= self._number_of_documents / batchD;

        return batch_document_topic_distribution, sufficient_statistics, document_level_elbo

    def learning(self, docs):
        if (type(docs).__name__ == 'string'):
            temp = list()
            temp.append(docs)
            docs = temp
        wordids = self.parse_doc_list(docs)
        (gamma, sstats, document_level_elbo) = self.e_step(wordids);
        corpus_level_elbo = self.m_step(len(docs), sstats);
        self._counter += 1;

        return gamma, document_level_elbo + corpus_level_elbo


text:
/* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */
#include <sstream>
#include <limits>

#include "ifcpp/model/AttributeObject.h"
#include "ifcpp/model/BuildingException.h"
#include "ifcpp/model/BuildingGuid.h"
#include "ifcpp/reader/ReaderUtil.h"
#include "ifcpp/writer/WriterUtil.h"
#include "ifcpp/IFC4X3/include/IfcLabel.h"
#include "ifcpp/IFC4X3/include/IfcPresentationLayerAssignment.h"
#include "ifcpp/IFC4X3/include/IfcProductRepresentation.h"
#include "ifcpp/IFC4X3/include/IfcRepresentation.h"
#include "ifcpp/IFC4X3/include/IfcRepresentationContext.h"
#include "ifcpp/IFC4X3/include/IfcRepresentationItem.h"
#include "ifcpp/IFC4X3/include/IfcRepresentationMap.h"

// ENTITY IfcRepresentation
IFC4X3::IfcRepresentation::IfcRepresentation( int tag ) { m_tag = tag; }
shared_ptr<BuildingObject> IFC4X3::IfcRepresentation::getDeepCopy( BuildingCopyOptions& options )
{
	shared_ptr<IfcRepresentation> copy_self( new IfcRepresentation() );
	if( m_ContextOfItems )
	{
		if( options.shallow_copy_IfcRepresentationContext ) { copy_self->m_ContextOfItems = m_ContextOfItems; }
		else { copy_self->m_ContextOfItems = dynamic_pointer_cast<IfcRepresentationContext>( m_ContextOfItems->getDeepCopy(options) ); }
	}
	if( m_RepresentationIdentifier ) { copy_self->m_RepresentationIdentifier = dynamic_pointer_cast<IfcLabel>( m_RepresentationIdentifier->getDeepCopy(options) ); }
	if( m_RepresentationType ) { copy_self->m_RepresentationType = dynamic_pointer_cast<IfcLabel>( m_RepresentationType->getDeepCopy(options) ); }
	for( size_t ii=0; ii<m_Items.size(); ++ii )
	{
		auto item_ii = m_Items[ii];
		if( item_ii )
		{
			copy_self->m_Items.emplace_back( dynamic_pointer_cast<IfcRepresentationItem>(item_ii->getDeepCopy(options) ) );
		}
	}
	return copy_self;
}
void IFC4X3::IfcRepresentation::getStepLine( std::stringstream& stream ) const
{
	stream << "#" << m_tag << "= IFCREPRESENTATION" << "(";
	if( m_ContextOfItems ) { stream << "#" << m_ContextOfItems->m_tag; } else { stream << "$"; }
	stream << ",";
	if( m_RepresentationIdentifier ) { m_RepresentationIdentifier->getStepParameter( stream ); } else { stream << "$"; }
	stream << ",";
	if( m_RepresentationType ) { m_RepresentationType->getStepParameter( stream ); } else { stream << "$"; }
	stream << ",";
	writeEntityList( stream, m_Items );
	stream << ");";
}
void IFC4X3::IfcRepresentation::getStepParameter( std::stringstream& stream, bool /*is_select_type*/ ) const { stream << "#" << m_tag; }
void IFC4X3::IfcRepresentation::readStepArguments( const std::vector<std::string>& args, const std::map<int,shared_ptr<BuildingEntity> >& map, std::stringstream& errorStream )
{
	const size_t num_args = args.size();
	if( num_args != 4 ){ std::stringstream err; err << "Wrong parameter count for entity IfcRepresentation, expecting 4, having " << num_args << ". Entity ID: " << m_tag << std::endl; throw BuildingException( err.str().c_str() ); }
	readEntityReference( args[0], m_ContextOfItems, map, errorStream );
	m_RepresentationIdentifier = IfcLabel::createObjectFromSTEP( args[1], map, errorStream );
	m_RepresentationType = IfcLabel::createObjectFromSTEP( args[2], map, errorStream );
	readEntityReferenceList( args[3], m_Items, map, errorStream );
}
void IFC4X3::IfcRepresentation::getAttributes( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes ) const
{
	vec_attributes.emplace_back( std::make_pair( "ContextOfItems", m_ContextOfItems ) );
	vec_attributes.emplace_back( std::make_pair( "RepresentationIdentifier", m_RepresentationIdentifier ) );
	vec_attributes.emplace_back( std::make_pair( "RepresentationType", m_RepresentationType ) );
	if( !m_Items.empty() )
	{
		shared_ptr<AttributeObjectVector> Items_vec_object( new AttributeObjectVector() );
		std::copy( m_Items.begin(), m_Items.end(), std::back_inserter( Items_vec_object->m_vec ) );
		vec_attributes.emplace_back( std::make_pair( "Items", Items_vec_object ) );
	}
}
void IFC4X3::IfcRepresentation::getAttributesInverse( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes_inverse ) const
{
	if( !m_RepresentationMap_inverse.empty() )
	{
		shared_ptr<AttributeObjectVector> RepresentationMap_inverse_vec_obj( new AttributeObjectVector() );
		for( size_t i=0; i<m_RepresentationMap_inverse.size(); ++i )
		{
			if( !m_RepresentationMap_inverse[i].expired() )
			{
				RepresentationMap_inverse_vec_obj->m_vec.emplace_back( shared_ptr<IfcRepresentationMap>( m_RepresentationMap_inverse[i] ) );
			}
		}
		vec_attributes_inverse.emplace_back( std::make_pair( "RepresentationMap_inverse", RepresentationMap_inverse_vec_obj ) );
	}
	if( !m_LayerAssignments_inverse.empty() )
	{
		shared_ptr<AttributeObjectVector> LayerAssignments_inverse_vec_obj( new AttributeObjectVector() );
		for( size_t i=0; i<m_LayerAssignments_inverse.size(); ++i )
		{
			if( !m_LayerAssignments_inverse[i].expired() )
			{
				LayerAssignments_inverse_vec_obj->m_vec.emplace_back( shared_ptr<IfcPresentationLayerAssignment>( m_LayerAssignments_inverse[i] ) );
			}
		}
		vec_attributes_inverse.emplace_back( std::make_pair( "LayerAssignments_inverse", LayerAssignments_inverse_vec_obj ) );
	}
	if( !m_OfProductRepresentation_inverse.empty() )
	{
		shared_ptr<AttributeObjectVector> OfProductRepresentation_inverse_vec_obj( new AttributeObjectVector() );
		for( size_t i=0; i<m_OfProductRepresentation_inverse.size(); ++i )
		{
			if( !m_OfProductRepresentation_inverse[i].expired() )
			{
				OfProductRepresentation_inverse_vec_obj->m_vec.emplace_back( shared_ptr<IfcProductRepresentation>( m_OfProductRepresentation_inverse[i] ) );
			}
		}
		vec_attributes_inverse.emplace_back( std::make_pair( "OfProductRepresentation_inverse", OfProductRepresentation_inverse_vec_obj ) );
	}
}
void IFC4X3::IfcRepresentation::setInverseCounterparts( shared_ptr<BuildingEntity> ptr_self_entity )
{
	shared_ptr<IfcRepresentation> ptr_self = dynamic_pointer_cast<IfcRepresentation>( ptr_self_entity );
	if( !ptr_self ) { throw BuildingException( "IfcRepresentation::setInverseCounterparts: type mismatch" ); }
	if( m_ContextOfItems )
	{
		m_ContextOfItems->m_RepresentationsInContext_inverse.emplace_back( ptr_self );
	}
}
void IFC4X3::IfcRepresentation::unlinkFromInverseCounterparts()
{
	if( m_ContextOfItems )
	{
		std::vector<weak_ptr<IfcRepresentation> >& RepresentationsInContext_inverse = m_ContextOfItems->m_RepresentationsInContext_inverse;
		for( auto it_RepresentationsInContext_inverse = RepresentationsInContext_inverse.begin(); it_RepresentationsInContext_inverse != RepresentationsInContext_inverse.end(); )
		{
			weak_ptr<IfcRepresentation> self_candidate_weak = *it_RepresentationsInContext_inverse;
			if( self_candidate_weak.expired() )
			{
				++it_RepresentationsInContext_inverse;
				continue;
			}
			shared_ptr<IfcRepresentation> self_candidate( *it_RepresentationsInContext_inverse );
			if( self_candidate.get() == this )
			{
				it_RepresentationsInContext_inverse= RepresentationsInContext_inverse.erase( it_RepresentationsInContext_inverse );
			}
			else
			{
				++it_RepresentationsInContext_inverse;
			}
		}
	}
}


text:
/* global angular: false */

(function (app) {
    'use strict';

    app.factory('TourHelpers', ['$templateCache', '$http', '$compile', 'TourConfig', '$q', function ($templateCache, $http, $compile, TourConfig, $q) {

        var helpers = {},
            safeApply;

        /**
         * Helper function that calls scope.$apply if a digest is not currently in progress
         * Borrowed from: https://coderwall.com/p/ngisma
         *
         * @param {$rootScope.Scope} scope
         * @param {Function} fn
         */
        safeApply = helpers.safeApply = function(scope, fn) {
            var phase = scope.$$phase;
            if (phase === '$apply' || phase === '$digest') {
                if (fn && (typeof(fn) === 'function')) {
                    fn();
                }
            } else {
                scope.$apply(fn);
            }
        };

        /**
         * Compiles and links a template to the provided scope
         *
         * @param {String} template
         * @param {$rootScope.Scope} scope
         * @returns {Function}
         */
        function compileTemplate(template, scope) {
            return function (/*index, step*/) {
                var $template = angular.element(template); //requires jQuery
                return $compile($template)(scope);
            };

        }

        /**
         * Looks up a template by URL and passes it to {@link helpers.compile}
         *
         * @param {String} templateUrl
         * @param {$rootScope.Scope} scope
         * @returns {Promise}
         */
        function lookupTemplate(templateUrl, scope) {

            return $http.get(templateUrl, {
                cache: $templateCache
            }).success(function (template) {
                if (template) {
                    return compileTemplate(template, scope);
                }
                return '';
            });

        }

        /**
         * Converts a stringified boolean to a JS boolean
         *
         * @param string
         * @returns {*}
         */
        function stringToBoolean(string) {
            if (string === 'true') {
                return true;
            } else if (string === 'false') {
                return false;
            }

            return string;
        }

        /**
         * Helper function that attaches proper compiled template to options
         *
         * @param {$rootScope.Scope} scope
         * @param {Attributes} attrs
         * @param {Object} options represents the tour or step object
         */
        helpers.attachTemplate = function (scope, attrs, options) {

            var deferred = $q.defer(),
                template;

            if (attrs[helpers.getAttrName('template')]) {
                template = compileTemplate(scope.$eval(attrs[helpers.getAttrName('template')]), scope);
                options.template = template;
                deferred.resolve(template);
            } else if (attrs[helpers.getAttrName('templateUrl')]) {
                lookupTemplate(attrs[helpers.getAttrName('templateUrl')], scope).then(function (template) {
                    if (template) {
                        options.template = template;
                        deferred.resolve(template);
                    }
                });
            } else {
                deferred.resolve();
            }

            return deferred.promise;

        };

        /**
         * Helper function that attaches event handlers to options
         *
         * @param {$rootScope.Scope} scope
         * @param {Attributes} attrs
         * @param {Object} options represents the tour or step object
         * @param {Array} events
         */
        helpers.attachEventHandlers = function (scope, attrs, options, events) {

            angular.forEach(events, function (eventName) {
                if (attrs[helpers.getAttrName(eventName)]) {
                    options[eventName] = function (tour) {
                        safeApply(scope, function () {
                            scope.$eval(attrs[helpers.getAttrName(eventName)]);
                        });
                    };
                }
            });

        };

        /**
         * Helper function that attaches observers to option attributes
         *
         * @param {Attributes} attrs
         * @param {Object} options represents the tour or step object
         * @param {Array} keys attribute names
         */
        helpers.attachInterpolatedValues = function (attrs, options, keys) {

            angular.forEach(keys, function (key) {
                if (attrs[helpers.getAttrName(key)]) {
                    options[key] = stringToBoolean(attrs[helpers.getAttrName(key)]);
                    attrs.$observe(helpers.getAttrName(key), function (newValue) {
                        options[key] = stringToBoolean(newValue);
                    });
                }
            });

        };

        /**
         * Returns the attribute name for an option depending on the prefix
         *
         * @param {string} option - name of option
         * @returns {string} potentially prefixed name of option, or just name of option
         */
        helpers.getAttrName = function (option) {
            if (TourConfig.get('prefixOptions')) {
                return TourConfig.get('prefix') + option.charAt(0).toUpperCase() + option.substr(1);
            } else {
                return option;
            }
        };

        return helpers;

    }]);

}(angular.module('bm.bsTour')));


text:
package com.me.FinalProject.DAO;

import java.util.logging.Level;
import java.util.logging.Logger;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class DAO {
	private static final Logger log = Logger.getAnonymousLogger();
	private static final ThreadLocal sessionThread = new ThreadLocal();
	private static final SessionFactory sessionFactory = new Configuration().configure().addResource("hibernate.cfg.xml").buildSessionFactory();
	protected DAO(){

	}
	public static Session getSession(){
		Session session = (Session) DAO.sessionThread.get();
		if(session == null){
			session = sessionFactory.openSession();
			DAO.sessionThread.set(session);
		}
		return session;
	}
	protected void begin(){
		getSession().beginTransaction();
	}
	protected void commit(){
		getSession().getTransaction().commit();
	}
	protected void rollback(){
		try{
		getSession().getTransaction().rollback();
		}catch(HibernateException e){
			log.log(Level.WARNING, "Cannot close connection", e);
		}
		DAO.sessionThread.set(null);
	}
}


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

using GitHubServices.BusinessLogic.TagPageCreator;
using GitHubServices.BusinessLogic.TagPageCreator.Domain;
using GitHubServices.Models;

using NUnit.Framework;

namespace GitHubServices.Test.BusinessLogic
{
    /// <summary>
    /// run these to update the TOC's of the code quality project
    /// </summary>
    [TestFixture]
    public class CodeQualityProjectHelper
    {
        const string readPath = @"C:\src\CodeQualityAndReadability\";
	    const string writePath = readPath + "docs";

        readonly string baseUrl = @"http://firstclassthoughts.co.uk/";

        readonly string editBaseUrl = "https://github.com/kbilsted/CodeQualityAndReadability/blob/master/";

        [Test]
        public void DeleteThisWhenTheServiceIsRunning_makeToc()
        {
            DirectoryInfo di = new DirectoryInfo(readPath);
            foreach (var path in di.EnumerateFiles("*.md", SearchOption.AllDirectories))
            {
                if (path.FullName.Contains(Path.DirectorySeparatorChar + "Tags" + Path.DirectorySeparatorChar))
                    continue;
                if(path.FullName.EndsWith("Readme.md"))
                    continue;
                Console.Write(path.FullName);
                MutateTocSection(path.FullName);
            }
        }

        [Test]
        public void DeleteThisWhenTheServiceIsRunning_generatePages()
        {
            var contentGenerator = new ContentGenerator();

            var filesystemRepository = new HtmlWriter(baseUrl);

            var documentParser = new DocumentParser();

            var siteGenerator = new SiteGenerator(
                contentGenerator,
                filesystemRepository,
                documentParser,
                new MarkDownMutator(filesystemRepository, contentGenerator));

            siteGenerator.GenerateSite(new ReadWritePaths(readPath, writePath), baseUrl, editBaseUrl);
        }

//        [Explicit]
//        [Test]
//        public void TagCollector_GetTags()
//        {
//            DocumentParser co = new DocumentParser(new FilesystemRepository());
//            var tags = co.GetTags(readPath);
//            string exp = @"new TagsCollection()
//{
//    Pages[""Design""] = new List<Page>()
//    Pages[0] = new Page(), ref: 0
//    {
//        Name = ""Malleable code through using decorators
//""
//        FilePath = ""Articles\Design\MalleableCodeUsingDecorators.md""
//    }
//    Pages[""SOLID""] = new List<Page>()
//    Pages[0] =  -> 0
//    Pages[1] = new Page(), ref: 1
//    {
//        Name = ""Book review: Adaptive Code via C#
//""
//        FilePath = ""BookReviews\Adaptive Code via CS.md""
//    }
//    Pages[""Single_Responsibility_Principle""] = new List<Page>()
//    Pages[0] =  -> 0
//    Pages[""Design_Pattern""] = new List<Page>()
//    Pages[0] =  -> 0
//    Pages[""Decorator""] = new List<Page>()
//    Pages[0] =  -> 0
//    Pages[""Wrapper""] = new List<Page>()
//    Pages[0] =  -> 0
//    Pages[""Cache""] = new List<Page>()
//    Pages[0] =  -> 0
//    Pages[""Book_Review""] = new List<Page>()
//    Pages[0] =  -> 1
//}";

//            var assert = Create.Assert();
//            assert.Configuration.Test.SetAutomaticTestRewrite(x => false);
//            assert.PrintEquals(exp, tags);
//        }

        void MutateTocSection(string path)
        {
            var content = File.ReadAllText(path);

            var toc = new TocParser().MakeToc(content);
            var newContent = new ContentReplacer().TryReplaceToc(content, toc);
            if (newContent != null && content != newContent)
            {
                Console.Write("    ... Updating");
                File.WriteAllText(path, newContent, Encoding.UTF8);
            }

            Console.WriteLine("");
        }
    }
}


text:
<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/

Route::get('/', 'LoginController@returnPage');
Route::get('login', 'LoginController@returnPage');
Route::post('pages/login', 'LoginController@doLogin');
Route::post('pages/createuser', 'CreateUserController@postCreateUser');
Route::get('createuser', 'CreateUserController@returnPage');
Route::post('pages/feedback', 'FeedbackController@giveFeedback');
Route::get('feedback', 'FeedbackController@returnPage');
Route::post('pages/bugreport', 'BugReportController@reportBug');
Route::get('bugreport', 'BugReportController@returnPage');
Route::get('currencyoverview', 'CurrencyOverviewController@returnPage');
Route::get('dashboard', 'DashboardController@returnPage');
Route::get('errordetails', 'ErrorDetailsController@returnPage');
Route::get('investigatingerrors', 'InvestigatingErrorsController@returnPage');
Route::get('listdocumenterrors', 'ListDocumentErrorsController@returnPage');
Route::get('overview', 'OverviewController@returnPage');
Route::get('adderror', 'AddErrorController@returnPage');

?>


text:
#ifndef _LINUX_EXT3_FS_SB
#define _LINUX_EXT3_FS_SB

#ifdef __KERNEL__
#include <linux/timer.h>
#include <linux/wait.h>
#include <linux/blockgroup_lock.h>
#include <linux/percpu_counter.h>
#endif
#include <linux/rbtree.h>

/*
 * third extended-fs super-block data in memory
 */
struct ext3_sb_info {
	unsigned long s_frag_size;	/* Size of a fragment in bytes */
	unsigned long s_frags_per_block;/* Number of fragments per block */
	unsigned long s_inodes_per_block;/* Number of inodes per block */
	unsigned long s_frags_per_group;/* Number of fragments in a group */
	unsigned long s_blocks_per_group;/* Number of blocks in a group */
	unsigned long s_inodes_per_group;/* Number of inodes in a group */
	unsigned long s_itb_per_group;	/* Number of inode table blocks per group */
	unsigned long s_gdb_count;	/* Number of group descriptor blocks */
	unsigned long s_desc_per_block;	/* Number of group descriptors per block */
	unsigned long s_groups_count;	/* Number of groups in the fs */
	unsigned long s_overhead_last;  /* Last calculated overhead */
	unsigned long s_blocks_last;    /* Last seen block count */
	struct buffer_head * s_sbh;	/* Buffer containing the super block */
	struct ext3_super_block * s_es;	/* Pointer to the super block in the buffer */
	struct buffer_head ** s_group_desc;
	unsigned long  s_mount_opt;
	ext3_fsblk_t s_sb_block;
	uid_t s_resuid;
	gid_t s_resgid;
	unsigned short s_mount_state;
	unsigned short s_pad;
	int s_addr_per_block_bits;
	int s_desc_per_block_bits;
	int s_inode_size;
	int s_first_ino;
	spinlock_t s_next_gen_lock;
	u32 s_next_generation;
	u32 s_hash_seed[4];
	int s_def_hash_version;
	int s_hash_unsigned;	/* 3 if hash should be signed, 0 if not */
	struct percpu_counter s_freeblocks_counter;
	struct percpu_counter s_freeinodes_counter;
	struct percpu_counter s_dirs_counter;
	struct blockgroup_lock *s_blockgroup_lock;

	/* root of the per fs reservation window tree */
	spinlock_t s_rsv_window_lock;
	struct rb_root s_rsv_window_root;
	struct ext3_reserve_window_node s_rsv_window_head;

	/* Journaling */
	struct inode * s_journal_inode;
	struct journal_s * s_journal;
	struct list_head s_orphan;
	struct mutex s_orphan_lock;
	struct mutex s_resize_lock;
	unsigned long s_commit_interval;
	struct block_device *journal_bdev;
#ifdef CONFIG_QUOTA
	char *s_qf_names[MAXQUOTAS];		/* Names of quota files with journalled quota */
	int s_jquota_fmt;			/* Format of quota to use */
#endif
};

static inline spinlock_t *
sb_bgl_lock(struct ext3_sb_info *sbi, unsigned int block_group)
{
	return bgl_lock_ptr(sbi->s_blockgroup_lock, block_group);
}

#endif	/* _LINUX_EXT3_FS_SB */


text:
package com.amazonaws.services.medialive.model.transform;

import java.util.Map;
import java.util.List;
import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.medialive.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * ChannelMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class ChannelMarshaller {

    private static final MarshallingInfo<String> ARN_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("arn").build();
    private static final MarshallingInfo<StructuredPojo> CDIINPUTSPECIFICATION_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("cdiInputSpecification").build();
    private static final MarshallingInfo<String> CHANNELCLASS_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("channelClass").build();
    private static final MarshallingInfo<List> DESTINATIONS_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("destinations").build();
    private static final MarshallingInfo<List> EGRESSENDPOINTS_BINDING = MarshallingInfo.builder(MarshallingType.LIST)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("egressEndpoints").build();
    private static final MarshallingInfo<StructuredPojo> ENCODERSETTINGS_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("encoderSettings").build();
    private static final MarshallingInfo<String> ID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("id").build();
    private static final MarshallingInfo<List> INPUTATTACHMENTS_BINDING = MarshallingInfo.builder(MarshallingType.LIST)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("inputAttachments").build();
    private static final MarshallingInfo<StructuredPojo> INPUTSPECIFICATION_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("inputSpecification").build();
    private static final MarshallingInfo<String> LOGLEVEL_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("logLevel").build();
    private static final MarshallingInfo<StructuredPojo> MAINTENANCE_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("maintenance").build();
    private static final MarshallingInfo<String> NAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("name").build();
    private static final MarshallingInfo<List> PIPELINEDETAILS_BINDING = MarshallingInfo.builder(MarshallingType.LIST)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("pipelineDetails").build();
    private static final MarshallingInfo<Integer> PIPELINESRUNNINGCOUNT_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("pipelinesRunningCount").build();
    private static final MarshallingInfo<String> ROLEARN_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("roleArn").build();
    private static final MarshallingInfo<String> STATE_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("state").build();
    private static final MarshallingInfo<Map> TAGS_BINDING = MarshallingInfo.builder(MarshallingType.MAP).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("tags").build();
    private static final MarshallingInfo<StructuredPojo> VPC_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("vpc").build();

    private static final ChannelMarshaller instance = new ChannelMarshaller();

    public static ChannelMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(Channel channel, ProtocolMarshaller protocolMarshaller) {

        if (channel == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(channel.getArn(), ARN_BINDING);
            protocolMarshaller.marshall(channel.getCdiInputSpecification(), CDIINPUTSPECIFICATION_BINDING);
            protocolMarshaller.marshall(channel.getChannelClass(), CHANNELCLASS_BINDING);
            protocolMarshaller.marshall(channel.getDestinations(), DESTINATIONS_BINDING);
            protocolMarshaller.marshall(channel.getEgressEndpoints(), EGRESSENDPOINTS_BINDING);
            protocolMarshaller.marshall(channel.getEncoderSettings(), ENCODERSETTINGS_BINDING);
            protocolMarshaller.marshall(channel.getId(), ID_BINDING);
            protocolMarshaller.marshall(channel.getInputAttachments(), INPUTATTACHMENTS_BINDING);
            protocolMarshaller.marshall(channel.getInputSpecification(), INPUTSPECIFICATION_BINDING);
            protocolMarshaller.marshall(channel.getLogLevel(), LOGLEVEL_BINDING);
            protocolMarshaller.marshall(channel.getMaintenance(), MAINTENANCE_BINDING);
            protocolMarshaller.marshall(channel.getName(), NAME_BINDING);
            protocolMarshaller.marshall(channel.getPipelineDetails(), PIPELINEDETAILS_BINDING);
            protocolMarshaller.marshall(channel.getPipelinesRunningCount(), PIPELINESRUNNINGCOUNT_BINDING);
            protocolMarshaller.marshall(channel.getRoleArn(), ROLEARN_BINDING);
            protocolMarshaller.marshall(channel.getState(), STATE_BINDING);
            protocolMarshaller.marshall(channel.getTags(), TAGS_BINDING);
            protocolMarshaller.marshall(channel.getVpc(), VPC_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
namespace cobalt {
namespace overlay_info {
namespace {

const auto kDelimiter = OverlayInfoRegistry::kDelimiter;

class OverlayInfoRegistryImpl {
 public:
  static OverlayInfoRegistryImpl* GetInstance();

  void Disable();

  void Register(const char* category, const char* str);
  void RetrieveAndClear(std::string* infos);

 private:
  // Reserve enough data for |infos_| to avoid extra allocations.
  static const size_t kReservedSize = 4096;

  OverlayInfoRegistryImpl() = default;

  // To make our private constructor available to
  // base::Singleton<OverlayInfoRegistryImpl,
  // DefaultSingletonTraits<OverlayInfoRegistryImpl>>.
  friend struct base::DefaultSingletonTraits<OverlayInfoRegistryImpl>;

  bool enabled_ = true;
  starboard::Mutex mutex_;
  std::string infos_;
};

// static
OverlayInfoRegistryImpl* OverlayInfoRegistryImpl::GetInstance() {
  return base::Singleton<
      OverlayInfoRegistryImpl,
      base::DefaultSingletonTraits<OverlayInfoRegistryImpl>>::get();
}

void OverlayInfoRegistryImpl::Disable() {
  starboard::ScopedLock scoped_lock(mutex_);
  enabled_ = false;
  infos_.clear();
}

void OverlayInfoRegistryImpl::Register(const char* category, const char* data) {
  DCHECK(strchr(category, static_cast<char>(OverlayInfoRegistry::kDelimiter)) ==
         NULL)
      << "Category " << category
      << " cannot contain the delimiter:" << OverlayInfoRegistry::kDelimiter;
  DCHECK(strchr(data, static_cast<char>(OverlayInfoRegistry::kDelimiter)) ==
         NULL)
      << "Data " << data
      << " cannot contain the delimiter:" << OverlayInfoRegistry::kDelimiter;
  if (!infos_.empty()) {
    infos_ += kDelimiter;
  }
  infos_ += category;
  infos_ += kDelimiter;
  infos_ += data;
}

void OverlayInfoRegistryImpl::RetrieveAndClear(std::string* infos) {
  DCHECK(infos);

  starboard::ScopedLock scoped_lock(mutex_);
  if (enabled_) {
    infos->swap(infos_);
    infos_.clear();
    infos_.reserve(kReservedSize);
  }
}

}  // namespace

void OverlayInfoRegistry::Disable() {
  OverlayInfoRegistryImpl::GetInstance()->Disable();
}

void OverlayInfoRegistry::Register(const char* category, const char* data) {
  OverlayInfoRegistryImpl::GetInstance()->Register(category, data);
}

void OverlayInfoRegistry::Register(const char* category, const void* data,
                                   size_t data_size) {
  const char kHex[] = "0123456789abcdef";

  const uint8_t* data_as_bytes = static_cast<const uint8_t*>(data);
  std::string data_in_hex;

  data_in_hex.reserve(data_size * 2);

  while (data_size > 0) {
    data_in_hex += kHex[*data_as_bytes / 16];
    data_in_hex += kHex[*data_as_bytes % 16];
    ++data_as_bytes;
    --data_size;
  }
  OverlayInfoRegistryImpl::GetInstance()->Register(category,
                                                   data_in_hex.c_str());
}

void OverlayInfoRegistry::RetrieveAndClear(std::string* infos) {
  OverlayInfoRegistryImpl::GetInstance()->RetrieveAndClear(infos);
}

}  // namespace overlay_info
}  // namespace cobalt


text:
using AramData;
using MySql.Data.MySqlClient;
using RiotSharp;
using RiotSharp.Endpoints.MatchEndpoint;
using RiotSharp.Misc;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace GameFinderV4
{
    class Program
    {
        static void Main(string[] args)
        {
            Stopwatch stopWatch1 = new Stopwatch();
            Stopwatch stopWatch2 = new Stopwatch();
            long countje = 0;

            int ClientNumber = -1;
            try
            {
                ClientNumber = Convert.ToInt32(args[0]);
                Console.Title = "GameFinderV4 Client #" + ClientNumber.ToString();
                Console.WriteLine("Client Number: " + ClientNumber.ToString());
            }
            catch (Exception)
            {
                Console.WriteLine("Enter client number argument");
                Console.ReadKey();
                return;
            }

            MySqlConnection link;
            link = new MySqlConnection(ConfigurationManager.AppSettings["MySqlConnectionString"]);
            int timeoutTimetime = 1;

            while (!link.Ping())
            {
                try
                {
                    link.Open();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }

                System.Threading.Thread.Sleep(1000);
            }

            Console.WriteLine("Conncection to Database: " + link.Ping());
            //var api = RiotApi.(ConfigurationManager.AppSettings["RiotApiKey"], 500, 30000);
            var api = RiotApi.GetInstance(ConfigurationManager.AppSettings["RiotApiKey"], 495, 29500);

            try
            {
                var test = api.Champion.GetChampionRotationAsync(Region.euw);
                var result = test.Result.FreeChampionIds;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Connection to Api: " + ex.InnerException.Message);
                goto End;
            }

            Console.WriteLine("Connection to Api: True");

            var gameBase = new GameBase();
            var summonerBase = new SummonerBase();

            //var sips = new Summoner("SipsClar", null, null, "0fhpK-H2m0-tS_xeHpBRyXL9Lzu_uGTNts9cwCF36BJ-FnU", 0, 0, 0, 0, 0, new DateTime(0));

            //summonerBase.AddSummoner(sips);

            //summonerBase.LoadFromDatabase(link, 100);

            stopWatch2.Start();

            while (true)
            {
                if (!summonerBase.SummonersAvailable())
                {
                tryagain:
                    gameBase.NewGamesToDatabase(link);
                    //load new or break
                    if (summonerBase.LoadFromDatabase(link, ClientNumber*5000, 500))
                    {
                        Console.WriteLine("Loaded new players from database");
                        timeoutTimetime = 1;
                    }
                    else
                    {
                        if (timeoutTimetime > 5)
                        {
                            Console.WriteLine("Could not load new players from database: Breaking");
                            break;
                        }
                        Console.WriteLine("Could not load new players from database: Timeout " + timeoutTimetime + " minute");
                        System.Threading.Thread.Sleep(timeoutTimetime * 60000);
                        timeoutTimetime++;
                        goto tryagain;
                    }
                }

                if(gameBase.gameList.Count > 10000)
                {
                    //stopWatch2.Stop();
                    Console.WriteLine("batchtime: " + stopWatch2.ElapsedMilliseconds / countje);
                    //stopWatch2.Reset();
                    //stopWatch2.Start();

                    gameBase.NewGamesToDatabase(link);
                    summonerBase.UpdateSummonersToDatabase(link);

                }

                int beginIndex = 0;
                MatchList gameListResult = new MatchList();
                DateTime checkedUntil = DateTime.FromBinary(0);
                stopWatch1.Start();
                do
                {
                    try
                    {
                        gameListResult = api.Match.GetMatchListAsync(Region.euw, summonerBase.CurrentSummoner().accountId, null, new List<int>(new int[] { 450 }), null, summonerBase.CurrentSummoner().checkedUntil, null, beginIndex, null).Result;
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Error with Summoner: " + summonerBase.CurrentSummoner().name);
                        //Console.WriteLine(e.ToString());

                        string em = e.InnerException.Message;

                        if (e.InnerException.Message.Contains("A task"))
                        {
                            Console.WriteLine(em);
                            api = RiotApi.GetInstance(ConfigurationManager.AppSettings["RiotApiKey"], 495, 29500);
                        }
                        else if (em.StartsWith("500") || em.StartsWith("503") || em.StartsWith("504") || em.StartsWith("429"))
                        {
                            Console.WriteLine(em);
                        }
                        else
                        {
                            Console.WriteLine("\nOther Error\n");
                            Console.WriteLine(e.ToString());
                        }

                        System.Threading.Thread.Sleep(5000);
                    }

                    if (gameListResult.Matches != null)
                    {
                        foreach (MatchReference match in gameListResult.Matches)
                        {
                            gameBase.AddNewGame(match.GameId, match.PlatformID.GetHashCode(), match.Season.GetHashCode(), match.Timestamp);
                        }

                        if (beginIndex == 0) //only run first loop
                        {
                            checkedUntil = gameListResult.Matches.Max(t => t.Timestamp).AddSeconds(1);
                        }

                        beginIndex += 100;
                        countje++;
                    }
                    else
                    {
                        continue;
                    }

                } while (gameListResult.TotalGames > beginIndex);
                if (gameListResult.Matches != null)
                {
                    stopWatch1.Stop();

                    summonerBase.CurrentSummoner().AddGamesFound(gameListResult.TotalGames, checkedUntil);

                    Console.WriteLine(DateTime.Now.ToString("HH:mm:ss") + "  dt: " + stopWatch1.ElapsedMilliseconds / ((gameListResult.TotalGames + 99) / 100) + "\t" + gameListResult.TotalGames.ToString() + " games added from summoner: " + summonerBase.CurrentSummoner().name);
                    stopWatch1.Reset();

                    summonerBase.NextSummoner();
                }
            }

        End:
            Console.WriteLine("Hello World!");
            Console.ReadKey();

        }
    }
}


text:
try:
    from mock import Mock
except ImportError:
    from unittest.mock import Mock
from contesto.basis.component import BaseComponent
import unittest

class TestComponent(BaseComponent):
    def __init__(self, test, element):
        super(TestComponent, self).__init__(test, element)
        self.test = self.driver

class PageTestCase(unittest.TestCase):

    def setUp(self):
        self.driver = Mock()
        self.element = Mock()

    def test_component_without_element(self):
        component = BaseComponent(self.driver)
        self.assertEqual(component.element, None)

    def test_component_with_element(self):
        component = BaseComponent(self.driver, self.element)
        self.assertEqual(component.element, self.element)

    def test_extend_component(self):
        component = TestComponent(self.driver, self.element)
        self.assertEqual(component.element, self.element)
        self.assertEqual(component.test, self.driver)


text:
require "chef/resource"

class Chef
  class Resource
    class WindowsTask < Chef::Resource

      provides :windows_task, os: "windows"

      allowed_actions :create, :delete, :run, :end, :change, :enable, :disable
      default_action :create

      def initialize(name, run_context = nil)
        super
        @resource_name = :windows_task
        @task_name = name
        @action = :create
      end

      property :task_name, String, regex: [/\A[^\/\:\*\?\<\>\|]+\z/]
      property :command, String
      property :cwd, String
      property :user, String, default: "SYSTEM"
      property :password, String
      property :run_level, equal_to: [:highest, :limited], default: :limited
      property :force, [TrueClass, FalseClass], default: false
      property :interactive_enabled, [TrueClass, FalseClass], default: false
      property :frequency_modifier, [Integer, String], default: 1
      property :frequency, equal_to: [:minute,
                                       :hourly,
                                       :daily,
                                       :weekly,
                                       :monthly,
                                       :once,
                                       :on_logon,
                                       :onstart,
                                       :on_idle], default: :hourly
      property :start_day, String
      property :start_time, String
      property :day, [String, Integer]
      property :months, String
      property :idle_time, Integer
      property :random_delay, String
      property :execution_time_limit, String

      attr_accessor :exists, :status, :enabled

      def after_created
        if random_delay
          validate_random_delay(random_delay, frequency)
          duration = sec_to_dur(random_delay)
          random_delay(duration)
        end

        if execution_time_limit
          raise ArgumentError, "Invalid value passed for `execution_time_limit`. Please pass seconds as a String e.g. '60'." if execution_time_limit.to_i == 0
          duration = sec_to_dur(execution_time_limit)
          execution_time_limit(duration)
        else
          # schtask sets execution_time_limit as PT72H by default
          # We are setting the default value here so that we can do idempotency check later
          # Note: We can't use `default` in the property
          # because it will raise error for Invalid values passed as "PT72H" is not in seconds
          execution_time_limit("PT72H")
        end

        validate_start_time(start_time) if frequency == :once
        validate_start_day(start_day, frequency) if start_day
        validate_user_and_password(user, password)
        validate_interactive_setting(interactive_enabled, password)
        validate_create_frequency_modifier(frequency, frequency_modifier)
        validate_create_day(day, frequency) if day
        validate_create_months(months, frequency) if months
        validate_idle_time(idle_time, frequency) if idle_time
      end

      private

      def validate_random_delay(random_delay, frequency)
        if [:once, :on_logon, :onstart, :on_idle].include? frequency
          raise ArgumentError, "`random_delay` property is supported only for frequency :minute, :hourly, :daily, :weekly and :monthly"
        end

        raise ArgumentError, "Invalid value passed for `random_delay`. Please pass seconds as a String e.g. '60'." if random_delay.to_i == 0
      end

      def validate_start_day(start_day, frequency)
        if [:once, :on_logon, :onstart, :on_idle].include? frequency
          raise ArgumentError, "`start_day` property is not supported with frequency: #{frequency}"
        end
      end

      def validate_start_time(start_time)
        raise ArgumentError, "`start_time` needs to be provided with `frequency :once`" unless start_time
      end

      SYSTEM_USERS = ['NT AUTHORITY\SYSTEM', "SYSTEM", 'NT AUTHORITY\LOCALSERVICE', 'NT AUTHORITY\NETWORKSERVICE', 'BUILTIN\USERS', "USERS"].freeze

      def validate_user_and_password(user, password)
        if user && use_password?(user)
          if password.nil?
            raise ArgumentError, "Can't specify a non-system user without a password!"
          end
        end
      end

      def use_password?(user)
        @use_password ||= !SYSTEM_USERS.include?(user.upcase)
      end

      def validate_interactive_setting(interactive_enabled, password)
        if interactive_enabled && password.nil?
          raise ArgumentError, "Please provide the password when attempting to set interactive/non-interactive."
        end
      end

      def validate_create_frequency_modifier(frequency, frequency_modifier)
        # Currently is handled in create action 'frequency_modifier_allowed' line. Does not allow for frequency_modifier for once,onstart,onlogon,onidle
        # Note that 'OnEvent' is not a supported frequency.
        unless frequency.nil? || frequency_modifier.nil?
          case frequency
          when :minute
            unless frequency_modifier.to_i > 0 && frequency_modifier.to_i <= 1439
              raise ArgumentError, "frequency_modifier value #{frequency_modifier} is invalid.  Valid values for :minute frequency are 1 - 1439."
            end
          when :hourly
            unless frequency_modifier.to_i > 0 && frequency_modifier.to_i <= 23
              raise ArgumentError, "frequency_modifier value #{frequency_modifier} is invalid.  Valid values for :hourly frequency are 1 - 23."
            end
          when :daily
            unless frequency_modifier.to_i > 0 && frequency_modifier.to_i <= 365
              raise ArgumentError, "frequency_modifier value #{frequency_modifier} is invalid.  Valid values for :daily frequency are 1 - 365."
            end
          when :weekly
            unless frequency_modifier.to_i > 0 && frequency_modifier.to_i <= 52
              raise ArgumentError, "frequency_modifier value #{frequency_modifier} is invalid.  Valid values for :weekly frequency are 1 - 52."
            end
          when :monthly
            unless ("1".."12").to_a.push("FIRST", "SECOND", "THIRD", "FOURTH", "LAST", "LASTDAY").include?(frequency_modifier.to_s.upcase)
              raise ArgumentError, "frequency_modifier value #{frequency_modifier} is invalid.  Valid values for :monthly frequency are 1 - 12, 'FIRST', 'SECOND', 'THIRD', 'FOURTH', 'LAST', 'LASTDAY'."
            end
          end
        end
      end

      def validate_create_day(day, frequency)
        unless [:weekly].include?(frequency)
          raise "day attribute is only valid for tasks that run weekly"
        end
        if day.is_a?(String) && day.to_i.to_s != day
          days = day.split(",")
          days.each do |d|
            unless ["mon", "tue", "wed", "thu", "fri", "sat", "sun", "*"].include?(d.strip.downcase)
              raise "day attribute invalid.  Only valid values are: MON, TUE, WED, THU, FRI, SAT, SUN and *.  Multiple values must be separated by a comma."
            end
          end
        end
      end

      def validate_create_months(months, frequency)
        unless [:monthly].include?(frequency)
          raise "months attribute is only valid for tasks that run monthly"
        end
        if months.is_a? String
          months.split(",").each do |month|
            unless ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC", "*"].include?(month.strip.upcase)
              raise "months attribute invalid. Only valid values are: JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC and *. Multiple values must be separated by a comma."
            end
          end
        end
      end

      def validate_idle_time(idle_time, frequency)
        unless [:on_idle].include?(frequency)
          raise "idle_time attribute is only valid for tasks that run on_idle"
        end

        unless idle_time.to_i > 0 && idle_time.to_i <= 999
          raise "idle_time value #{idle_time} is invalid.  Valid values for :on_idle frequency are 1 - 999."
        end
      end

      # Convert the number of seconds to an ISO8601 duration format
      # @see http://tools.ietf.org/html/rfc2445#section-4.3.6
      # @param [Integer] seconds The amount of seconds for this duration
      def sec_to_dur(seconds)
        seconds = seconds.to_i
        return if seconds == 0
        iso_str = "P"
        if seconds > 604_800 # more than a week
          weeks = seconds / 604_800
          seconds -= (604_800 * weeks)
          iso_str << "#{weeks}W"
        end
        if seconds > 86_400 # more than a day
          days = seconds / 86_400
          seconds -= (86_400 * days)
          iso_str << "#{days}D"
        end
        if seconds > 0
          iso_str << "T"
          if seconds > 3600 # more than an hour
            hours = seconds / 3600
            seconds -= (3600 * hours)
            iso_str << "#{hours}H"
          end
          if seconds > 60 # more than a minute
            minutes = seconds / 60
            seconds -= (60 * minutes)
            iso_str << "#{minutes}M"
          end
          iso_str << "#{seconds}S"
        end

        iso_str
      end

    end
  end
end


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context="uk.co.deanwild.materialshowcaseviewsample.CustomExample">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:background="#00c2eb"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:elevation="4dp"
        android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light">

        <Button
            android:id="@+id/btn_show"
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:layout_gravity="right"
            android:layout_margin="5dp"
            android:backgroundTint="@android:color/white"
            android:text="Show" />

    </android.support.v7.widget.Toolbar>

    <Button
        android:id="@+id/btn_reset"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Reset" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="end|bottom"
        android:layout_margin="16dp"
        android:src="@drawable/ic_edit" />

</RelativeLayout>