text:
class Profile;

namespace base {
class CommandLine;
}

namespace extensions {
class ExtensionSystem;
}

class ProfileSyncComponentsFactoryImpl : public ProfileSyncComponentsFactory {
 public:
  // Constructs a ProfileSyncComponentsFactoryImpl.
  //
  // |sync_service_url| is the base URL of the sync server.
  //
  // |token_service| must outlive the ProfileSyncComponentsFactoryImpl.
  //
  // |url_request_context_getter| must outlive the
  // ProfileSyncComponentsFactoryImpl.
  ProfileSyncComponentsFactoryImpl(
      Profile* profile,
      base::CommandLine* command_line,
      const GURL& sync_service_url,
      OAuth2TokenService* token_service,
      net::URLRequestContextGetter* url_request_context_getter);
  virtual ~ProfileSyncComponentsFactoryImpl();

  virtual void RegisterDataTypes(ProfileSyncService* pss) OVERRIDE;

  virtual sync_driver::DataTypeManager* CreateDataTypeManager(
      const syncer::WeakHandle<syncer::DataTypeDebugInfoListener>&
          debug_info_listener,
      const sync_driver::DataTypeController::TypeMap* controllers,
      const sync_driver::DataTypeEncryptionHandler* encryption_handler,
      browser_sync::SyncBackendHost* backend,
      sync_driver::DataTypeManagerObserver* observer,
      sync_driver::FailedDataTypesHandler* failed_data_types_handler)
          OVERRIDE;

  virtual browser_sync::SyncBackendHost* CreateSyncBackendHost(
      const std::string& name,
      Profile* profile,
      invalidation::InvalidationService* invalidator,
      const base::WeakPtr<sync_driver::SyncPrefs>& sync_prefs,
      const base::FilePath& sync_folder) OVERRIDE;

  virtual scoped_ptr<browser_sync::LocalDeviceInfoProvider>
      CreateLocalDeviceInfoProvider() OVERRIDE;

  virtual base::WeakPtr<syncer::SyncableService> GetSyncableServiceForType(
      syncer::ModelType type) OVERRIDE;
  virtual scoped_ptr<syncer::AttachmentService> CreateAttachmentService(
      const syncer::UserShare& user_share,
      syncer::AttachmentService::Delegate* delegate) OVERRIDE;

  // Legacy datatypes that need to be converted to the SyncableService API.
  virtual SyncComponents CreateBookmarkSyncComponents(
      ProfileSyncService* profile_sync_service,
      sync_driver::DataTypeErrorHandler* error_handler) OVERRIDE;
  virtual SyncComponents CreateTypedUrlSyncComponents(
      ProfileSyncService* profile_sync_service,
      history::HistoryBackend* history_backend,
      sync_driver::DataTypeErrorHandler* error_handler) OVERRIDE;

 private:
  // Register data types which are enabled on desktop platforms only.
  // |disabled_types| and |enabled_types| correspond only to those types
  // being explicitly enabled/disabled by the command line.
  void RegisterDesktopDataTypes(syncer::ModelTypeSet disabled_types,
                                syncer::ModelTypeSet enabled_types,
                                ProfileSyncService* pss);
  // Register data types which are enabled on both desktop and mobile.
  // |disabled_types| and |enabled_types| correspond only to those types
  // being explicitly enabled/disabled by the command line.
  void RegisterCommonDataTypes(syncer::ModelTypeSet disabled_types,
                               syncer::ModelTypeSet enabled_types,
                               ProfileSyncService* pss);
  // Used to bind a callback to give to DataTypeControllers to disable
  // data types.
  sync_driver::DataTypeController::DisableTypeCallback
      MakeDisableCallbackFor(syncer::ModelType type);
  void DisableBrokenType(syncer::ModelType type,
                         const tracked_objects::Location& from_here,
                         const std::string& message);

  Profile* profile_;
  base::CommandLine* command_line_;
  scoped_refptr<autofill::AutofillWebDataService> web_data_service_;

  const GURL sync_service_url_;
  OAuth2TokenService* const token_service_;
  net::URLRequestContextGetter* const url_request_context_getter_;

  base::WeakPtrFactory<ProfileSyncComponentsFactoryImpl> weak_factory_;

  DISALLOW_COPY_AND_ASSIGN(ProfileSyncComponentsFactoryImpl);
};

#endif  // CHROME_BROWSER_SYNC_PROFILE_SYNC_COMPONENTS_FACTORY_IMPL_H__


text:
using System;
using System.Diagnostics;
using NUnit.Framework;
using NServiceKit.Common;
using NServiceKit.Text;

namespace NServiceKit.Redis.Tests
{
    [Explicit("Diagnostic only Integration Test")]
    [TestFixture]
    public class DiagnosticTests
    {
        const string RedisServer = "or-redis02";

        const int MessageSizeBytes = 1024 * 1024;
        private const int Count = 10;

        private byte[] RandomBytes(int Length)
        {
            var rnd = new Random();
            var bytes = new byte[Length];
            for (Int64 i = 0; i < Length; i++)
            {
                bytes[i] = (byte)rnd.Next(254);
            }
            return bytes;
        }

        [Test]
        public void Test_Throughput()
        {
            var bytes = RandomBytes(MessageSizeBytes);
            var swTotal = Stopwatch.StartNew();

            var key = "test:bandwidth:" + bytes.Length;

            int bytesSent = 0;
            int bytesRecv = 0;

            using (var redisClient = new RedisNativeClient(RedisServer))
            {
                Count.Times(x =>
                {
                    var sw = Stopwatch.StartNew();

                    redisClient.Set(key, bytes);
                    bytesSent += bytes.Length;
                    "SEND {0} bytes in {1}ms".Print(bytes.Length, sw.ElapsedMilliseconds);

                    sw.Reset();
                    sw.Start();
                    var receivedBytes = redisClient.Get(key);
                    bytesRecv += receivedBytes.Length;
                    "RECV {0} bytes in {1}ms".Print(receivedBytes.Length, sw.ElapsedMilliseconds);

                    "TOTAL {0} bytes SENT {0} RECV {1} in {2}ms\n".Print(
                        bytesSent, bytesRecv, swTotal.ElapsedMilliseconds);
                });
            }
        }

    }

}

redpajama_set_name: RedPajamaGithub


text:
#include "jss_core.hpp"
#include <utility>

namespace JSON
{
    namespace Internal
    {
        template <typename T,
                  typename = typename std::enable_if <Internal::can_stringify<T>::value>::type >
        void stringify_map_pair (std::ostream& stream, std::pair <const std::string, T> const& value, StringificationOptions const& options)
        {
            stringify(stream, value.first, value.second, options);
        }

        template <typename KeyT, typename ValueT,
                  typename = typename std::enable_if <Internal::can_stringify<ValueT>::value && Internal::can_stringify<KeyT>::value>::type >
        void stringify_map_pair_2 (std::ostream& stream, std::pair <const KeyT, ValueT> const& value, StringificationOptions const& options)
        {
            stringify(stream, {}, value.first, options);
            stream << options.delimiter;
            stringify(stream, {}, value.second, options);
        }
    }
}


text:
import sys

__all__ = 'Error','SpecificationError','WARN_ERROR','WARN_NORMAL','WARN_MINOR','emit_warning'

class Error(Exception):
    def __init__(self,msg,info=None):
        super(Error,self).__init__(msg,info or {})

    @property
    def msg(self):
        return self.args[0]

    @property
    def info(self):
        return self.args[1]

    def __str__(self):
        return self.msg + ''.join('\n  {0}: {1}'.format(*i) for i in self.info.iteritems())

class SpecificationError(Error):
    def __str__(self):
        return 'Specification Error: ' + super(SpecificationError,self).__str__()

WARN_ERROR = 3 # it's wrong but we can still generate the code
WARN_NORMAL = 2 # probably a mistake
WARN_MINOR = 1 # could be a mistake

error_level = WARN_ERROR
ignore_level = 0

def emit_warning(level,msg):
    if level >= error_level:
        raise SpecificationError(msg)

    if level > ignore_level:
        print >> sys.stderr, 'Warning: '+msg


text:
package com.deerweather.app.model;

/**
 * Created by Gdeer on 2016/3/30.
 */
public class ItemWeekly {

    private String mDayWeekly;
    private String mWeatherCodeWeekly;
    private String mWeatherWeekly;
    private String mAqiWeekly;
    private String mMaxTempWeekly;
    private String mMinTempWeekly;

    public String getMinTempWeekly() {
        return mMinTempWeekly;
    }

    public void setMinTempWeekly(String minTempWeekly) {
        mMinTempWeekly = minTempWeekly;
    }

    public String getMaxTempWeekly() {
        return mMaxTempWeekly;
    }

    public void setMaxTempWeekly(String maxTempWeekly) {
        mMaxTempWeekly = maxTempWeekly;
    }

    public String getWeatherCodeWeekly() {
        return mWeatherCodeWeekly;
    }

    public void setWeatherCodeWeekly(String weatherCodeWeekly) {
        mWeatherCodeWeekly = weatherCodeWeekly;
    }

    public String getWeatherWeekly() {
        return mWeatherWeekly;
    }

    public void setWeatherWeekly(String weatherWeekly) {
        mWeatherWeekly = weatherWeekly;
    }

    public String getDayWeekly() {
        return mDayWeekly;
    }

    public void setDayWeekly(String dayWeekly) {
        mDayWeekly = dayWeekly;
    }

    public String getAqiWeekly() {
        return mAqiWeekly;
    }

    public void setAqiWeekly(String aqiWeekly) {
        mAqiWeekly = aqiWeekly;
    }
}


text:
package com.sappenin.utils.rest.v2.model.examples;

import java.util.Map;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.ToString;

import org.joda.time.DateTime;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Optional;
import com.sappenin.utils.rest.v2.InternalId;
import com.sappenin.utils.rest.v2.model.RestModel;
import com.sappenin.utils.rest.v2.model.impl.AbstractRestModel;
import com.sappenin.utils.rest.v2.model.meta.Meta;

/**
 * An example implementation of {@link RestModel}.
 */
@Getter
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
public class SampleModelWithMutedAttributes extends AbstractRestModel<Meta>implements RestModel<Meta>
{
	private static final long serialVersionUID = 7940258555581761522L;

	@JsonIgnore
	private final Optional<Meta> optMeta = Optional.absent();

	// An example property that models a normative attribute called "name"
	private final String name;

	// An [RFC3339] date-time representing the date and time when this resource was created.
	@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss'Z'", timezone = "GMT")
	private final DateTime creationDateTime;

	/**
	 * Required-args Constructor
	 *
	 * @param internalId
	 * @param additionalAttributes
	 * @param name
	 * @param creationDateTime
	 */
	public SampleModelWithMutedAttributes(@JsonProperty("internalId") final InternalId internalId,
			@JsonProperty("additionalAttributes") final Map<String, String> additionalAttributes,
			@JsonProperty("name") final String name, @JsonProperty("creationDateTime") final DateTime creationDateTime)
	{
		super(Optional.<Meta> absent(), Optional.fromNullable(internalId), Optional.fromNullable(additionalAttributes));
		this.name = name;
		this.creationDateTime = creationDateTime;
	}

	public SampleModelWithMutedAttributes(final SampleModelWithMutedAttributes sampleModel)
	{
		super(sampleModel);
		this.name = sampleModel.getName();
		this.creationDateTime = sampleModel.getCreationDateTime();
	}
}


text:
@interface FRKAppDelegate : UIResponder <UIApplicationDelegate>

@property (strong,nonatomic) UIWindow *window;
@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;

//@property (strong,nonatomic) NSMutableDictionary *ozFeatures;
@property (strong,nonatomic) Userprofile *userprofile;

- (BOOL)initOZFeatureCoreDataFromFile;
- (BOOL)loadOZFeaturesFromJSON;

- (NSURL *)applicationDocumentsDirectory;

@end


text:
package org.dcm4chex.archive.ejb.entity;

import javax.ejb.CreateException;
import javax.ejb.EJBException;
import javax.ejb.EntityBean;
import javax.ejb.EntityContext;
import javax.ejb.FinderException;
import javax.ejb.RemoveException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.apache.log4j.Logger;
import org.dcm4che.data.Dataset;
import org.dcm4che.data.PersonName;
import org.dcm4che.dict.Tags;
import org.dcm4chex.archive.ejb.conf.AttributeFilter;
import org.dcm4chex.archive.ejb.interfaces.IssuerLocal;
import org.dcm4chex.archive.ejb.interfaces.IssuerLocalHome;
import org.dcm4chex.archive.ejb.interfaces.SeriesLocal;

/**
 * @author gunter.zeilinger@tiani.com
 * @version Revision $Date: 2010-12-25 00:10:14 +0800 (周六, 25 12月 2010) $
 * @since 01.04.2005
 *
 * @ejb.bean name="SeriesRequest" type="CMP" view-type="local"
 *           local-jndi-name="ejb/SeriesRequest" primkey-field="pk"
 * @jboss.container-configuration name="Instance Per Transaction CMP 2.x EntityBean"
 * @ejb.persistence table-name="series_req"
 * @ejb.transaction type="Required"
 * @jboss.entity-command name="hsqldb-fetch-key"
 *
 * @ejb.finder signature="Collection findAll()"
 *             query="SELECT OBJECT(r) FROM SeriesRequest AS r"
 *             transaction-type="Supports"
 * @ejb.ejb-ref ejb-name="Issuer" view-type="local" ref-name="ejb/Issuer"
 */

public abstract class SeriesRequestBean implements EntityBean {

    private static final Logger log = Logger.getLogger(SeriesRequestBean.class);

    private IssuerLocalHome issuerHome;

    public void setEntityContext(EntityContext ctx) {
        Context jndiCtx = null;
        try {
            jndiCtx = new InitialContext();
            issuerHome = (IssuerLocalHome) jndiCtx.lookup("java:comp/env/ejb/Issuer");
       } catch (NamingException e) {
            throw new EJBException(e);
        } finally {
            if (jndiCtx != null) {
                try {
                    jndiCtx.close();
                } catch (NamingException ignore) {
                }
            }
        }
    }

    public void unsetEntityContext() {
        issuerHome = null;
    }

    /**
     * @ejb.create-method
     */
    public Long ejbCreate(Dataset ds, SeriesLocal series)
            throws CreateException {
        AttributeFilter filter = AttributeFilter.getSeriesAttributeFilter();
        setAccessionNumber(ds.getString(Tags.AccessionNumber));
        setStudyIuid(ds.getString(Tags.StudyInstanceUID));
        setRequestedProcedureId(filter.getString(ds, Tags.RequestedProcedureID));
        setSpsId(filter.getString(ds, Tags.SPSID));
        setRequestingService(filter.getString(ds, Tags.RequestingService));
        PersonName pn = ds.getPersonName(Tags.RequestingPhysician);
        if (pn != null) {
            setRequestingPhysician(
                    filter.toUpperCase(pn.toComponentGroupString(false),
                            Tags.RequestingPhysician));
            PersonName ipn = pn.getIdeographic();
            if (ipn != null) {
                setRequestingPhysicianIdeographicName(
                        ipn.toComponentGroupString(false));
            }
            PersonName ppn = pn.getPhonetic();
            if (ppn != null) {
                setRequestingPhysicianPhoneticName(
                        ppn.toComponentGroupString(false));
            }
        }
        if (AttributeFilter.isSoundexEnabled()) {
            setRequestingPhysicianFamilyNameSoundex(
                    AttributeFilter.toSoundex(pn, PersonName.FAMILY, "*"));
            setRequestingPhysicianGivenNameSoundex(
                    AttributeFilter.toSoundex(pn, PersonName.GIVEN, "*"));
        }
        return null;
    }

    public void ejbPostCreate(Dataset ds, SeriesLocal series)
            throws CreateException {
        setSeries(series);
        try {
            setIssuerOfAccessionNumber(
                    IssuerBean.valueOf(issuerHome, ds.getItem(Tags.IssuerOfAccessionNumberSeq)));
        } catch (FinderException e) {
            throw new CreateException(e.getMessage());
        }
        log.info("Created " + prompt());
    }

    public void ejbRemove() throws RemoveException {
        log.info("Deleting " + prompt());
    }

    /**
     * Auto-generated Primary Key
     *
     * @ejb.interface-method
     * @ejb.pk-field
     * @ejb.persistence column-name="pk"
     * @jboss.persistence auto-increment="true"
     *
     */
    public abstract Long getPk();

    public abstract void setPk(Long pk);

    /**
     * Accession Number
     *
     * @ejb.interface-method
     * @ejb.persistence column-name="accession_no"
     */
    public abstract String getAccessionNumber();
    public abstract void setAccessionNumber(String no);

    /**
     * @ejb.persistence column-name="study_iuid"
     */
    public abstract String getStudyIuid();

    public abstract void setStudyIuid(String uid);

    /**
     * @ejb.persistence column-name="req_proc_id"
     */
    public abstract String getRequestedProcedureId();

    public abstract void setRequestedProcedureId(String id);

    /**
     * @ejb.persistence column-name="sps_id"
     */
    public abstract String getSpsId();

    public abstract void setSpsId(String no);

    /**
     * @ejb.persistence column-name="req_service"
     */
    public abstract String getRequestingService();

    public abstract void setRequestingService(String service);

    /**
     * @ejb.interface-method
     * @ejb.persistence column-name="req_physician"
     */
    public abstract String getRequestingPhysician();
    public abstract void setRequestingPhysician(String name);

    /**
     * @ejb.interface-method
     * @ejb.persistence column-name="req_phys_fn_sx"
     */
    public abstract String getRequestingPhysicianFamilyNameSoundex();

    /**
     * @ejb.interface-method
     */
    public abstract void setRequestingPhysicianFamilyNameSoundex(String name);

    /**
     * @ejb.interface-method
     * @ejb.persistence column-name="req_phys_gn_sx"
     */
    public abstract String getRequestingPhysicianGivenNameSoundex();

    /**
     * @ejb.interface-method
     */
    public abstract void setRequestingPhysicianGivenNameSoundex(String name);

    /**
     * @ejb.persistence column-name="req_phys_i_name"
     */
    public abstract String getRequestingPhysicianIdeographicName();
    public abstract void setRequestingPhysicianIdeographicName(String name);

    /**
     * @ejb.persistence column-name="req_phys_p_name"
     */
    public abstract String getRequestingPhysicianPhoneticName();
    public abstract void setRequestingPhysicianPhoneticName(String name);

    /**
     * @ejb.relation name="series-request-attributes"
     *               role-name="request-attributes-of-series"
     *               cascade-delete="yes"
     * @jboss.relation fk-column="series_fk" related-pk-field="pk"
     */
    public abstract void setSeries(SeriesLocal series);

    /**
     * @ejb.relation name="series-request-issuer-of-accno" role-name="series-request-with-issuer-of-accno"
     *               target-ejb="Issuer" target-role-name="issuer-of-series-request-accno"
     *               target-multiple="yes"
     * @jboss.relation fk-column="accno_issuer_fk" related-pk-field="pk"
     */
    public abstract IssuerLocal getIssuerOfAccessionNumber();
    public abstract void setIssuerOfAccessionNumber(IssuerLocal issuer);

    /**
     * @ejb.interface-method
     */
    public abstract SeriesLocal getSeries();

    private String prompt() {
        return "SeriesRequestAttribute[pk=" + getPk()
                + ", accno=" + getAccessionNumber()
                + ", rpid=" + getRequestedProcedureId()
                + ", spsid=" + getSpsId()
                + ", service=" + getRequestingService()
                + ", phys=" + getRequestingPhysician()
                + ", series->" + getSeries() + "]";
    }

}


text:
/*----------------------------------------------
Programmer: Alberto Bobadilla (labigm@gmail.com)
Date: 2015/11
----------------------------------------------*/
#ifndef __MYENTITYMANAGER_H_
#define __MYENTITYMANAGER_H_

#include "MyEntityClass.h"
#include "MyOctant.h"

//System Class
class MyEntityManager
{
	uint m_nEntityCount = 0; //number of elements in the list
	static MyEntityManager* m_pInstance; // Singleton pointer
	std::vector<MyEntityClass*> m_lEntity; //list of elements
	std::map<String, uint> m_map;//Map relating the mesh and the index

	int numTargets;

	bool d_DISPLAYOCTREE = false;
	MyOctant* m_pRoot = nullptr;

public:
	MyBOManager* m_pColliderManager = nullptr; //Collider manager
	/*
	USAGE: returns the singleton pointer
	ARGUMENTS: ---
	OUTPUT: MyEntityManager* -> singleton Accessor
	*/
	static MyEntityManager* GetInstance();
	/*
	USAGE: releases the singleton pointer
	ARGUMENTS: ---
	OUTPUT: ---
	*/
	static void ReleaseInstance(void);
	/*
	USAGE: Adds a new entry to the list of Entity
	ARGUMENTS:
	--- MyEntityClass* a_nEntity-> Entity to add
	OUTPUT: ---
	*/
	void AddEntity(MyEntityClass* a_nEntity);
	/*
	USAGE: Adds a new entry to the list of Entity
	ARGUMENTS:
	--- String a_nsEntity-> Creates an entity
	OUTPUT: ---
	*/
	void AddEntity(String a_sEntity, String a_sTag,float a_fMass);
	/*
	USAGE: Returns the entry in the specified index, nullptr if un-existent
	ARGUMENTS:
	--- int a_nIndex -> index to return
	OUTPUT: MyEntityClass* -> value on list
	*/
	MyEntityClass* GetEntity(int a_nIndex);
	/*
	USAGE: Returns the entry in the specified index, nullptr if un-existent
	ARGUMENTS:
	--- int a_nIndex -> index to return
	OUTPUT: MyEntityClass* -> value on list
	*/
	MyEntityClass* GetEntity(String a_sEntity);
	/*
	USAGE: Gets the number of entries on vector
	ARGUMENTS: ---
	OUTPUT: int -> number of entries
	*/
	int GetEntityCount(void);
	/*
	USAGE: Returns the index specified by name from the dictionary
	ARGUMENTS:
	--- String a_sIndex -> name of the index
	OUTPUT: index of the specified name, -1 if not found
	*/
	int GetIndex(String a_sEntity);
	/*
	USAGE: Accessor of mass
	ARGUMENTS:
	--- float a_fMass -> mass input
	--- String a_sEntity -> Entity ID
	OUTPUT: ---
	*/
	void SetMass(float a_fMass, String a_sEntity);
	/*
	USAGE: Accessor of friction
	ARGUMENTS:
	--- float a_fFriction -> friction input
	OUTPUT: ---
	*/
	void SetFriction(float a_fFriction, String a_sEntity);
	/*
	USAGE: Accessor of Maximum velocity
	ARGUMENTS:
	--- float a_fMaxVelocity -> Max Acceleration input
	--- String a_sEntity -> Entity ID
	OUTPUT: ---
	*/
	void SetMaxVelocity(float a_fMaxVelocity, String a_sEntity);
	/*
	USAGE: Accessor of Position
	ARGUMENTS:
	--- vector3 a_v3Position -> position input
	--- String a_sEntity -> Entity ID
	OUTPUT: ---
	*/
	void SetPosition(vector3 a_v3Position, String a_sEntity);
	/*
	USAGE: Accessor of velocity
	ARGUMENTS:
	--- vector3 a_v3Velocity -> velocity input
	--- String a_sEntity -> Entity ID
	OUTPUT: ---
	*/
	void SetModelMatrix(matrix4 m4, String a_sEntity);
	void SetVelocity(vector3 a_v3Velocity, String a_sEntity);
	/*
	USAGE: Accessor of gravity
	ARGUMENTS:
	--- bool a_bGravity -> Gravity flag
	--- String a_sEntity -> Entity ID
	OUTPUT: ---
	*/
	void SetGravityAffected(bool a_bGravity, String a_sEntity);
	/*
	USAGE: Applies a force into the entity
	ARGUMENTS:
	--- vector3 a_v3Force -> input force
	--- String a_sEntity -> entity id
	OUTPUT: ---
	*/
	void ApplyForce(vector3 a_v3Force, String a_sEntity);
	/*
	USAGE: Updates all the Entity
	ARGUMENTS: ---
	OUTPUT: ---
	*/

	void DeleteTargets(void);

	void Update(void);
	/*
	USAGE: Calculates the position of the entity based on the
	acceleration and mass, will also update its mesh and collider
	ARGUMENTS:
	--- int a_nRenderMode = ER_MESH -> specifies what to render
	ie ( ER_MESH | ER_RB ) will render the mesh and the Realligned Box
	OUTPUT: ---
	*/
	int GetNumTargets(void);
	void SetNumTargets(int numTargets);

	void Display(int a_nRenderMode = ER_MESH);

	bool gameOver = false;

private:
	/*
	USAGE: Constructor
	ARGUMENTS: ---
	OUTPUT: Class object
	*/
	MyEntityManager(void);
	/*
	USAGE: copy constructor
	ARGUMENTS: Class object to copy
	OUTPUT: Class object
	*/
	MyEntityManager(MyEntityManager const& other);
	/*
	USAGE: copy assignment operator
	ARGUMENTS: Class object to copy
	OUTPUT: Class object
	*/
	MyEntityManager& operator=(MyEntityManager const& other);
	/*
	USAGE: destructor
	ARGUMENTS: ---
	OUTPUT: ---
	*/
	~MyEntityManager(void);
	/*
	USAGE: Releases the memory of the singleton
	ARGUMENTS: ---
	OUTPUT: ---
	*/
	void Release(void);
	/*
	USAGE: Initializes the default values
	ARGUMENTS: ---
	OUTPUT: ---
	*/
	void Init(void);
};

#endif //__MYENTITYMANAGER_H_


text:
<?php

class La_Controller_Action_Helper_Download extends Zend_Controller_Action_Helper_Abstract
{
    public function direct($filepath, $filename = null)
    {
        if (file_exists($filepath)) {
            $controller = $this->getActionController();
            $controller->getHelper('layout')->disableLayout();
            $controller->getHelper('viewRenderer')->setNoRender();

            if (!$filename) {
                $filename = basename($filepath);
            }

            $etag = md5_file($filepath);
            $size = filesize($filepath);

            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename=' . $filename);
            header('Content-Transfer-Encoding: binary');
            header('Expires: 0');
            header('Etag: ' . $etag);
            header('Cache-Control: must-revalidate');
            header('Pragma: public');
            header('Content-Length: ' . $size);

            ob_clean();
            flush();

            readfile($filepath);
        }
    }
}


text:
package edu.uci.jforestsx.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Yasser Ganjisaffar <ganjisaffar at gmail dot com>
 */

public class Util {

	public static int putLongInByteArray(long l, byte[] array, int offset) {
		int i, shift;
		for (i = 0, shift = 56; i < 8; i++, shift -= 8) {
			array[offset] = (byte) (0xFF & (l >> shift));
			offset++;
		}
		return offset;
	}

	public static int putIntInByteArray(int value, byte[] array, int offset) {
		for (int i = 0; i < 4; i++) {
			int off = (3 - i) * 8;
			array[offset] = (byte) ((value >>> off) & 0xFF);
			offset++;
		}
		return offset;
	}

	public static int putBooleanInByteArray(boolean value, byte[] array, int offset) {
		array[offset] = (byte) (value ? 1 : 0);
		return offset + 1;
	}

	public static int putShortInByteArray(short value, byte[] array, int offset) {
		array[offset] = (byte) ((value >>> 8) & 0xFF);
		array[offset + 1] = (byte) (value & 0xFF);
		return offset + 2;
	}

	public static int putFloatInByteArray(float f, byte[] array, int offset) {
		int i = Float.floatToIntBits(f);
		return putIntInByteArray(i, array, offset);
	}

	public static int putDoubleInByteArray(double d, byte[] array, int offset) {
		long l = Double.doubleToRawLongBits(d);
		return putLongInByteArray(l, array, offset);
	}

	public static int putIntArrayInByteArray(int[] src, byte[] dest, int offset) {
		offset = Util.putIntInByteArray(src.length, dest, offset);

		for (int i = 0; i < src.length; i++) {
			offset = Util.putIntInByteArray(src[i], dest, offset);
		}
		return offset;
	}

	public static int putDoubleArrayInByteArray(double[] src, byte[] dest,
			int offset) {
		offset = Util.putIntInByteArray(src.length, dest, offset);

		for (int i = 0; i < src.length; i++) {
			offset = Util.putDoubleInByteArray(src[i], dest, offset);
		}
		return offset;
	}

	public static int putStringInByteArray(String src, byte[] dest, int offset) {
		if (src == null) {
			offset = Util.putShortInByteArray((short) 0, dest, offset);
		} else {
			char[] chars = src.toCharArray();
			offset = Util.putShortInByteArray((short) chars.length, dest,
					offset);

			for (int i = 0; i < chars.length; i++) {
				dest[offset] = (byte) chars[i];
				offset++;
			}
		}
		return offset;
	}

	public static byte[] toByteArray(int value) {
		byte[] array = new byte[4];
		putIntInByteArray(value, array, 0);
		return array;
	}

	public static long toLong(byte[] bytearray, int offset) {
		long result = 0;
		for (int i = offset; i < offset + 8 /* Bytes in long */; i++) {
			result = (result << 8 /* Bits in byte */)
					| (0xff & (byte) (bytearray[i] & 0xff));
		}
		return result;
	}

	public static int toInt(byte[] b, int offset) {
		int value = 0;
		for (int i = 0; i < 4; i++) {
			int shift = (4 - 1 - i) * 8;
			value += (b[i + offset] & 0x000000FF) << shift;
		}
		return value;
	}

	public static short toShort(byte[] b, int offset) {
		return (short) (((b[offset] & 0x000000FF) << 8) + ((b[offset + 1] & 0x000000FF)));
	}

	public static boolean toBoolean(byte[] data, int offset) {
		return (data[offset] == 1);
	}

	public static float toFloat(byte[] data, int offset) {
		int i = toInt(data, offset);
		return Float.intBitsToFloat(i);
	}

	public static double toDouble(byte[] data, int offset) {
		long l = toLong(data, offset);
		return Double.longBitsToDouble(l);
	}

	public static int[] toIntArray(byte[] data, int offset) {
		int length = toInt(data, offset);
		offset += 4;
		int[] arr = new int[length];
		for (int i = 0; i < length; i++) {
			arr[i] = toInt(data, offset);
			offset += 4;
		}
		return arr;
	}

	public static String toString(byte[] data, int offset) {
		int length = toShort(data, offset);
		offset += 2;
		char[] chars = new char[length];
		for (int i = 0; i < length; i++) {
			chars[i] = (char) data[offset];
			offset++;
		}
		return new String(chars);
	}

	public static String getFileNameWithoutExtension(String name) {
		int idx = name.lastIndexOf('.');
		if (idx < 0) {
			return name;
		}
		return name.substring(0, idx);
	}

	public static List<Integer> loadIntegersFromFile(String filename) throws Exception {
		List<Integer> result = new ArrayList<Integer>();
		BufferedReader reader = new BufferedReader(new FileReader(new File(filename)));
		String line;
		while ((line = reader.readLine()) != null) {
			result.add(Integer.parseInt(line.trim()));
		}
		return result;
	}
}


text:
<?php

namespace Simgroep\ConcurrentSpiderBundle\DocumentResolver\Type;

use Simgroep\ConcurrentSpiderBundle\DocumentResolver\Type\TypeAbstract;
use VDB\Spider\Resource;
use Simgroep\ConcurrentSpiderBundle\DocumentResolver\DocumentDataExtractor;
use PhpOffice\PhpWord\Reader\Word2007 as Word2007Reader;
use PhpOffice\PhpWord\Writer\HTML as HtmlWriter;
use PhpOffice\PhpWord\PhpWord as PhpWord;
use Simgroep\ConcurrentSpiderBundle\InvalidContentException;

/**
 * Word2007 Resolver Document Type
 */
class Word2007 extends TypeAbstract implements DocumentTypeInterface
{
    /**
     * Extracts content from a word2007 and returns document data.
     *
     * @param \VDB\Spider\Resource $resource
     *
     * @return array
     *
     * @throws \Simgroep\ConcurrentSpiderBundle\InvalidContentException
     */
    public function getData(Resource $resource)
    {
        $content = $this->extractContentFromResource($resource);

        if (strlen($content) < self::MINIMAL_CONTENT_LENGTH) {
            throw new InvalidContentException(
                sprintf("Word2007 didn't contain enough content (minimal chars is %s)", self::MINIMAL_CONTENT_LENGTH)
            );
        }

        $dataExtractor = new DocumentDataExtractor($resource);

        $url = $dataExtractor->getUrl();
        $title = $this->getTitleByUrl($url) ? : '';

        $data = [
            'id' => $dataExtractor->getId(),
            'url' => $url,
            'content' => $content,
            'title' => $title,
            'tstamp' => date('Y-m-d\TH:i:s\Z'),
            'contentLength' => strlen($content),
            'lastModified' => $dataExtractor->getLastModified(),
            'date' => date('Y-m-d\TH:i:s\Z'),
            'publishedDate' => date('Y-m-d\TH:i:s\Z'),
            'updatedDate' => date('Y-m-d\TH:i:s\Z'),
        ];

        return $data;
    }

    /**
     * Extract content from resource
     *
     * @param \VDB\Spider\Resource $resource
     *
     * @return string
     */
    public function extractContentFromResource(Resource $resource)
    {
        $tempFile = tempnam(sys_get_temp_dir(), 'docx');

        file_put_contents($tempFile, $resource->getResponse()->getBody());

        $reader = $this->getReader();

        //remove notice from library
        $errorReportingLevel = error_reporting();
        error_reporting($errorReportingLevel ^ E_NOTICE);

        $phpword = $reader->load($tempFile);

        //back error reporting to previous state
        error_reporting($errorReportingLevel);

        unlink($tempFile);

        $writer = $this->getWriter($phpword);

        return strip_tags($this->stripBinaryContent($writer->getContent()));
    }

    /**
     * Return Reader Object
     *
     * @return \PhpOffice\PhpWord\Reader\Word2007
     */
    protected function getReader()
    {
        return new Word2007Reader();
    }

    /**
     * Return Writer Object
     *
     * @param \PhpOffice\PhpWord\PhpWord $phpWord
     *
     * @return \PhpOffice\PhpWord\Writer\HTML
     */
    protected function getWriter(PhpWord $phpWord)
    {
        return new HtmlWriter($phpWord);
    }

}


text:
package org.wso2.carbon.logging.service.registry;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Appender;
import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Layout;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.net.SyslogAppender;
import org.wso2.carbon.core.RegistryResources;
import org.wso2.carbon.core.util.CryptoException;
import org.wso2.carbon.core.util.CryptoUtil;
import org.wso2.carbon.utils.logging.CircularBuffer;
import org.wso2.carbon.logging.service.appender.CarbonMemoryAppender;
import org.wso2.carbon.logging.service.config.SyslogConfigManager;
import org.wso2.carbon.logging.service.config.SyslogConfiguration;
import org.wso2.carbon.logging.service.data.SyslogData;
import org.wso2.carbon.logging.service.util.LoggingConstants;
import org.wso2.carbon.registry.core.Collection;
import org.wso2.carbon.registry.core.Registry;
import org.wso2.carbon.registry.core.Resource;
import org.wso2.carbon.registry.core.exceptions.RegistryException;
import org.wso2.carbon.utils.ServerConstants;

import java.io.File;
import java.io.IOException;

public class RegistryManager {
    private static Log log = LogFactory.getLog(RegistryManager.class);

    private static Registry registry;

    public static void setRegistry(Registry registryParam) {
        registry = registryParam;
    }

    public String getConfigurationProperty(String propertyName)
            throws RegistryException {
        String resourcePath = RegistryResources.LOGGING + propertyName;
        String value = null;
        if (registry.resourceExists(resourcePath)) {
            Resource resource = registry.get(resourcePath);
            value = resource.getProperty(propertyName);
        }
        return value;
    }

    public void updateConfigurationProperty(String propertyName, String value)
            throws RegistryException {
        if (propertyName == null || value == null) {
            return;
        }
        String resourcePath = RegistryResources.LOGGING + propertyName;
        Resource resource;
        if (!registry.resourceExists(resourcePath)) {
            resource = registry.newResource();
            resource.addProperty(propertyName, value);
            registry.put(resourcePath, resource);
        } else {
            resource = registry.get(resourcePath);
            String existingValue = resource.getProperty(propertyName);
            if (!(existingValue != null && existingValue.equals(value))) {
                resource.setProperty(propertyName, value);
                registry.put(resourcePath, resource);
            }
        }
    }

    /**
     * when getting loggers from getCurrentLoggers method it will return all the
     * loggers in the system. this includes loggers we have initialized using
     * getLogger methods. but these loggers does not have a log level set they
     * get the log level from the parent loggers. but to store in registry we
     * use only loggers with a log level
     * <p/>
     * Store the provided Log4J Logger in the Registry
     *
     * @param logger The Log4J Logger to be stored in the registry
     */
    public void addLogger(Logger logger) throws Exception {
        try {
            registry.beginTransaction();
            Resource loggerResource = registry.newResource();
            loggerResource.addProperty(LoggingConstants.LoggerProperties.NAME,
                    logger.getName());
            loggerResource.addProperty(
                    LoggingConstants.LoggerProperties.LOG_LEVEL, logger
                            .getEffectiveLevel().toString());
            loggerResource.addProperty(
                    LoggingConstants.LoggerProperties.ADDITIVITY,
                    Boolean.toString(logger.getAdditivity()));

            registry.put(LoggingConstants.LOGGERS + logger.getName(),
                    loggerResource);
            registry.commitTransaction();
        } catch (Exception e) {
            registry.rollbackTransaction();
            log.error("Unable to add the logger", e);
            throw e;
        }
    }

    public Resource getLogger(String loggerName) throws Exception {
        String loggerResourcePath = LoggingConstants.LOGGERS + loggerName;
        if (registry.resourceExists(loggerResourcePath)) {
            return registry.get(loggerResourcePath);
        }
        return null;
    }

    public Collection getLoggers() throws Exception {
        if (registry.resourceExists(LoggingConstants.LOGGERS)) {
            return (Collection) registry.get(LoggingConstants.LOGGERS);
        }
        return null;
    }

    public void updateLogger(String loggerName, String loggerLevel,
                             boolean aditivity) throws Exception {
        try {
            registry.beginTransaction();
            Resource loggerResource;
            String loggerResourcePath = LoggingConstants.LOGGERS + loggerName;
            if (registry.resourceExists(loggerResourcePath)) {
                loggerResource = registry.get(loggerResourcePath);
                loggerResource.setProperty(
                        LoggingConstants.LoggerProperties.LOG_LEVEL,
                        loggerLevel);
                loggerResource.setProperty(
                        LoggingConstants.LoggerProperties.ADDITIVITY,
                        Boolean.toString(aditivity));
                registry.put(loggerResourcePath, loggerResource);
            } else {
                loggerResource = registry.newResource();
                loggerResource.addProperty(
                        LoggingConstants.LoggerProperties.NAME, loggerName);
                loggerResource.addProperty(
                        LoggingConstants.LoggerProperties.LOG_LEVEL,
                        loggerLevel);
                loggerResource.addProperty(
                        LoggingConstants.LoggerProperties.ADDITIVITY,
                        Boolean.toString(aditivity));
                registry.put(loggerResourcePath, loggerResource);
            }
            registry.commitTransaction();
        } catch (Exception e) {
            registry.rollbackTransaction();
            log.error("Unable to update the logger", e);
            throw e;
        }
    }

    private String encriptSyslogPassword(String password)
            throws CryptoException {
        return CryptoUtil.getDefaultCryptoUtil().encryptAndBase64Encode(
                password.getBytes());
    }

    private String decriptPassword(String encriptedPassword)
            throws CryptoException, IOException {
        return new String(CryptoUtil.getDefaultCryptoUtil()
                .base64DecodeAndDecrypt(encriptedPassword));
    }

    public void addSyslogConfig(SyslogData syslogData) throws Exception {
        try {
            registry.beginTransaction();
            Resource syslogResource = registry.newResource();
            syslogResource.addProperty(
                    LoggingConstants.SyslogProperties.LOG_INDEX_URL,
                    syslogData.getUrl());
            syslogResource.addProperty(
                    LoggingConstants.SyslogProperties.SYSLOG_PORT,
                    syslogData.getPort());
            syslogResource.addProperty(LoggingConstants.SyslogProperties.REALM,
                    syslogData.getRealm());
            syslogResource.addProperty(
                    LoggingConstants.SyslogProperties.USER_NAME,
                    syslogData.getUserName());
            syslogResource.addProperty(
                    LoggingConstants.SyslogProperties.PASSWORD,
                    encriptSyslogPassword(syslogData.getPassword()));
            registry.put(LoggingConstants.SYSLOG, syslogResource);
            registry.commitTransaction();
        } catch (RegistryException e) {
            registry.rollbackTransaction();
            log.error("Cannot add syslog properties ", e);
            throw e;
        }
    }

    /**
     * Store the provided Log4J Appender in the Registry
     *
     * @param appender Log4J Appender to be stored in the registry
     */
    public void addAppender(Appender appender) throws Exception {
        try {
            registry.beginTransaction();
            Resource appenderResource = registry.newResource();
            if (appender.requiresLayout()) {
                Layout layout = appender.getLayout();
                if (layout instanceof PatternLayout) {
                    appenderResource.addProperty(
                            LoggingConstants.AppenderProperties.PATTERN,
                            ((PatternLayout) layout).getConversionPattern());
                }
            }

            if (appender instanceof FileAppender) {
                FileAppender fileAppender = (FileAppender) appender;
                String fileName = fileAppender.getFile();
                File logFile = new File(fileName);
                if (!logFile.isAbsolute()) {
                    if (fileName.startsWith(".")) {
                        fileName = fileName.substring(1);
                    }
                    fileName = (System.getProperty(ServerConstants.CARBON_HOME)
                            + "/" + fileName).replace('\\', '/');
                    fileAppender.setFile(fileName);
                    fileAppender.activateOptions();
                }
                appenderResource.addProperty(
                        LoggingConstants.AppenderProperties.LOG_FILE_NAME,
                        fileName);
                appenderResource.addProperty(
                        LoggingConstants.AppenderProperties.IS_FILE_APPENDER,
                        Boolean.toString(true));
            } else {
                appenderResource.addProperty(
                        LoggingConstants.AppenderProperties.IS_FILE_APPENDER,
                        Boolean.toString(false));
            }

            if (appender instanceof CarbonMemoryAppender) {
                CarbonMemoryAppender memoryAppender = (CarbonMemoryAppender) appender;
                memoryAppender.setCircularBuffer(new CircularBuffer(
                        LoggingConstants.MEMORY_APPENDER_BUFFER_SZ));
                memoryAppender.activateOptions();
            }

            // normally all the appenders inherit from AppenderSkelton
            if (appender instanceof AppenderSkeleton) {
                AppenderSkeleton appenderSkeleton = (AppenderSkeleton) appender;
                if (appenderSkeleton.getThreshold() != null) {
                    appenderResource.addProperty(
                            LoggingConstants.AppenderProperties.THRESHOLD,
                            appenderSkeleton.getThreshold().toString());
                } else {
                    appenderResource.addProperty(
                            LoggingConstants.AppenderProperties.THRESHOLD,
                            "DEBUG");
                }
            }

            if (appender instanceof SyslogAppender) {
                SyslogAppender syslogAppender = (SyslogAppender) appender;

                // if user has not set these properties system automatically
                // assign default values
                appenderResource.addProperty(
                        LoggingConstants.AppenderProperties.SYS_LOG_HOST,
                        syslogAppender.getSyslogHost());
                appenderResource.addProperty(
                        LoggingConstants.AppenderProperties.FACILITY,
                        syslogAppender.getFacility());
                appenderResource
                        .addProperty(
                                LoggingConstants.AppenderProperties.IS_SYS_LOG_APPENDER,
                                Boolean.toString(true));
            } else {
                appenderResource
                        .addProperty(
                                LoggingConstants.AppenderProperties.IS_SYS_LOG_APPENDER,
                                Boolean.toString(false));
            }
            registry.put(LoggingConstants.APPENDERS + appender.getName(),
                    appenderResource);
            registry.commitTransaction();
        } catch (Exception e) {
            registry.rollbackTransaction();
            log.error("Cannot add appender", e);
            throw e;
        }
    }

    public void updateCassandraConfig(String url, String keyspace,
                                      String columnFamily, String userName, String password)
            throws Exception {
        String cassandraResourcePath = LoggingConstants.CASSANDRA;
        try {
            if (registry.resourceExists(cassandraResourcePath)) {
                try {
                    registry.beginTransaction();
                    Resource appenderResource = registry
                            .get(cassandraResourcePath);
                    appenderResource.setProperty(
                            LoggingConstants.CassandraProperties.URL, url);
                    appenderResource.setProperty(
                            LoggingConstants.CassandraProperties.KEYSPACE,
                            keyspace);
                    appenderResource.setProperty(
                            LoggingConstants.CassandraProperties.COLUMN_FAMILY,
                            columnFamily);
                    appenderResource.setProperty(
                            LoggingConstants.CassandraProperties.USER_NAME,
                            userName);
                    appenderResource.setProperty(
                            LoggingConstants.CassandraProperties.PASSWORD,
                            encriptSyslogPassword(password));
                    registry.put(LoggingConstants.CASSANDRA, appenderResource);
                    registry.commitTransaction();
                } catch (RegistryException e) {
                    registry.rollbackTransaction();
                    log.error("Unable to update the appender", e);
                    throw e;
                }
            }
        } catch (RegistryException e) {
            log.error("Unable to update the appender", e);
            throw e;
        }
    }

    /**
     * this method is used to update syslog properties in the registry if syslog
     * property is not available a new resource is added to the registry along
     * with the syslog properties
     *
     * @param url      - syslog logs location
     * @param port     - port
     * @param realm    - realm
     * @param userName - syslog server authentic user name
     * @param password - syslog server authentic password
     * @throws Exception
     */
    public void updateSyslogConfig(String url, String port, String realm,
                                   String userName, String password) throws Exception {
        String syslogResourcePath = LoggingConstants.SYSLOG;
        try {
            if (registry.resourceExists(syslogResourcePath)) {
                try {
                    registry.beginTransaction();
                    Resource appenderResource = registry
                            .get(syslogResourcePath);
                    appenderResource.setProperty(
                            LoggingConstants.SyslogProperties.LOG_INDEX_URL,
                            url);
                    appenderResource
                            .setProperty(
                                    LoggingConstants.SyslogProperties.SYSLOG_PORT,
                                    port);
                    appenderResource.setProperty(
                            LoggingConstants.SyslogProperties.REALM, realm);
                    appenderResource.setProperty(
                            LoggingConstants.SyslogProperties.USER_NAME,
                            userName);
                    appenderResource.setProperty(
                            LoggingConstants.SyslogProperties.PASSWORD,
                            encriptSyslogPassword(password));
                    registry.put(LoggingConstants.SYSLOG, appenderResource);
                    registry.commitTransaction();
                } catch (RegistryException e) {
                    registry.rollbackTransaction();
                    log.error("Unable to update the appender", e);
                    throw e;
                }
            } else {
                SyslogData syslogData = new SyslogData(url, port, realm,
                        userName, password);
                addSyslogConfig(syslogData);
            }
        } catch (RegistryException e) {
            log.error("Unable to update the appender", e);
            throw e;
        }

    }

    public SyslogData getSyslogData() throws Exception {
        Resource syslogConfigResource;
        try {
            syslogConfigResource = getSyslogConfig();
            String url = "";
            String port = "";
            String realm = "";
            String userName = "";
            String password = "";
            if (syslogConfigResource != null) { // Check if the properties are
                // coming from the registry.
                url = syslogConfigResource
                        .getProperty(LoggingConstants.SyslogProperties.LOG_INDEX_URL);
                port = syslogConfigResource
                        .getProperty(LoggingConstants.SyslogProperties.SYSLOG_PORT);
                realm = syslogConfigResource
                        .getProperty(LoggingConstants.SyslogProperties.REALM);
                userName = syslogConfigResource
                        .getProperty(LoggingConstants.SyslogProperties.USER_NAME);
                password = decriptPassword(syslogConfigResource
                        .getProperty(LoggingConstants.SyslogProperties.PASSWORD));
            } else { // read syslog properties from the syslog-config.xml
                SyslogConfiguration config = SyslogConfigManager
                        .loadSyslogConfiguration();
                url = config.getSyslogHostURL();
                port = config.getPort();
                realm = config.getRealm();
                userName = config.getUserName();
                password = config.getPassword();
            }

            return new SyslogData(url, port, realm, userName, password);
        } catch (Exception e) {
            log.error("Unable get SyslogData ", e);
            throw e;
        }

    }

    /**
     * @return Registry resource of syslog property file.
     * @throws Exception
     */
    public Resource getSyslogConfig() throws Exception {
        String syslogResourcePath = LoggingConstants.SYSLOG;
        if (registry.resourceExists(syslogResourcePath)) {
            return registry.get(syslogResourcePath);
        }
        return null;
    }

    public Resource getCassandraConfig() throws Exception {
        String cassandraResourcePath = LoggingConstants.CASSANDRA;
        if (registry.resourceExists(cassandraResourcePath)) {
            return registry.get(cassandraResourcePath);
        }
        return null;
    }

    public void updateAppender(Appender appender, String appenderName,
                               String appenderPattern, String threshold, String logFileName,
                               String sysLogHost, String facility, boolean isFileAppender,
                               boolean isSysLogAppender) throws Exception {

        String appenderResourcePath = LoggingConstants.APPENDERS + appenderName;
        if (registry.resourceExists(appenderResourcePath)) {
            try {
                registry.beginTransaction();

                Resource appenderResource = registry.get(appenderResourcePath);
                appenderResource.setProperty(
                        LoggingConstants.AppenderProperties.PATTERN,
                        appenderPattern);

                if (isFileAppender) {
                    appenderResource.setProperty(
                            LoggingConstants.AppenderProperties.LOG_FILE_NAME,
                            logFileName);
                    appenderResource
                            .setProperty(
                                    LoggingConstants.AppenderProperties.IS_FILE_APPENDER,
                                    Boolean.toString(true));
                }

                if (isSysLogAppender) {
                    appenderResource.setProperty(
                            LoggingConstants.AppenderProperties.SYS_LOG_HOST,
                            sysLogHost);
                    appenderResource.setProperty(
                            LoggingConstants.AppenderProperties.FACILITY,
                            facility);
                    appenderResource
                            .setProperty(
                                    LoggingConstants.AppenderProperties.IS_SYS_LOG_APPENDER,
                                    Boolean.toString(true));
                }

                appenderResource.setProperty(
                        LoggingConstants.AppenderProperties.THRESHOLD,
                        threshold);
                registry.put(LoggingConstants.APPENDERS + appenderName,
                        appenderResource);

                registry.commitTransaction();
            } catch (Exception e) {
                registry.rollbackTransaction();
                log.error("Unable to update the appender", e);
                throw e;
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("appender " + appenderName
                        + " is not available, therefore adding to registry");
            }
            addAppender(appender);
            updateAppender(appender, appenderName, appenderPattern, threshold,
                    logFileName, sysLogHost, facility, isFileAppender,
                    isSysLogAppender);
        }
    }

    public Resource getAppender(String appenderName) throws Exception {
        String appenderResourcePath = LoggingConstants.APPENDERS + appenderName;
        if (registry.resourceExists(appenderResourcePath)) {
            return registry.get(appenderResourcePath);
        }
        return null;
    }

    public Collection getAppenders() throws Exception {
        if (registry.resourceExists(LoggingConstants.APPENDERS)) {
            return (Collection) registry.get(LoggingConstants.APPENDERS);
        }
        return null;
    }

    /**
     * method is used to check current appender is a syslog appender.
     *
     * @return isSyslogAppender
     * @throws RegistryException
     */
    public boolean isSysLogAppender() throws RegistryException {
        boolean isSyslogAppender = false;
        String appenderResourcePath = LoggingConstants.APPENDERS
                + LoggingConstants.WSO2CARBON_SYS_LOG_APPENDER;
        if (registry.resourceExists(appenderResourcePath)) {
            Resource appenderResource = registry.get(appenderResourcePath);
            isSyslogAppender = Boolean
                    .parseBoolean(appenderResource
                            .getProperty(LoggingConstants.AppenderProperties.IS_SYS_LOG_APPENDER));
        }
        return isSyslogAppender;
    }

    public void removeAllRegistryEntries() throws Exception {
        try {
            registry.beginTransaction();
            if (registry.resourceExists(LoggingConstants.LOGGERS)) {
                registry.delete(LoggingConstants.LOGGERS);
            }
            if (registry.resourceExists(LoggingConstants.APPENDERS)) {
                registry.delete(LoggingConstants.APPENDERS);
            }

            if (registry.resourceExists(RegistryResources.LOGGING
                    + LoggingConstants.SYSTEM_LOG_PATTERN)) {
                registry.delete(RegistryResources.LOGGING
                        + LoggingConstants.SYSTEM_LOG_PATTERN);
            }
            if (registry.resourceExists(RegistryResources.LOGGING
                    + LoggingConstants.SYSTEM_LOG_LEVEL)) {
                registry.delete(RegistryResources.LOGGING
                        + LoggingConstants.SYSTEM_LOG_LEVEL);
            }
            registry.commitTransaction();
        } catch (Exception e) {
            registry.rollbackTransaction();
            log.error("Unable to remove all the loggers and appenders", e);
            throw e;
        }
    }
}


text:
package net.trucas.david.peliculas;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class Pelis24 extends Activity implements AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener {

    private FilmeAdapter adapter;
    private List<Flist> Flist = new ArrayList<Flist>();

    String urlMainPageIndex = "http://pelis24.tv/";
    String urlMain = "http://pelis24.tv/page/";
    TextView txtPage;
    ProgressBar progressBar;
    private int page = 1;
    ImageLoader imageLoader;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_film);
        imageLoader = new ImageLoader(Volley.newRequestQueue(this), new LruBitmapCache());

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        txtPage = (TextView) findViewById(R.id.txtPage);

        adapter = new FilmeAdapter(this, R.layout.row_filme, Flist, imageLoader);
        ListView msgListView = (ListView) findViewById(R.id.lvFilmes);
        msgListView.setAdapter(adapter);
        msgListView.setOnItemClickListener(this);
        msgListView.setOnItemLongClickListener(this);

        getFilms(urlMain + page);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        TextView url = (TextView) view.findViewById(R.id.txturl);
        Intent intent = new Intent(this, MainGetUrl.class);
        intent.putExtra("url", url.getText().toString());
        startActivity(intent);
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        TextView txtsynopsis = (TextView) view.findViewById(R.id.txtsynopsis);
        String synopsis = txtsynopsis.getText().toString();
        Log.d(" SYNOPSIS FILME ", synopsis);
        Intent intent = new Intent(this, DialogSynopsis.class);
        intent.putExtra("synopsis", synopsis);
        startActivity(intent);
        return true;
    }

    public void gotoBack(View view) {
        if (progressBar.getVisibility() == View.GONE) {
            if (page > 1) {
                page = page - 1;
                getFilms(urlMain + page);
                txtPage.setText(String.valueOf(page));
            }
        }
    }

    public void gotoNext(View view) {
        if (progressBar.getVisibility() == View.GONE) {
            page = page + 1;
            getFilms(urlMain + page);
            txtPage.setText(String.valueOf(page));
        }
    }

    public void getFilms(final String urls) {

        progressBar.setVisibility(View.VISIBLE);
        adapter.clear();
        Flist.clear();
        adapter.notifyDataSetChanged();

        new Thread(new Runnable() {
            public void run() {

                URL url;
                HttpURLConnection urlConnection = null;
                boolean isContent = false;
                try {
                    url = new URL(urls);
                    urlConnection = (HttpURLConnection) url.openConnection();
                    urlConnection.setRequestProperty("User-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64)");
                    InputStream in = urlConnection.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder out = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        if (line.contains("dle-content")) {
                            isContent = true;
                        }
                        if (line.contains("
")) {
                            isContent = false;
                        }
                        if (isContent) {
                            out.append(line);
                            //Log.d(" PELIS ", line);
                        }
                    }

                    final String outfinal = out.toString();
                    reader.close();

                    processData(outfinal);

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    urlConnection.disconnect();
                }

            }
        }).start();
    }

    public void processData(String data) {

        String[] alldata = data.split("post2");
        for (String dat : alldata) {
            if (dat.contains("http://imgs24")) {
                String img = dat.substring(dat.indexOf("http://imgs24.com/"));
                img = img.substring(0, img.indexOf("\""));

                Log.d(" prueba ", dat);
                String title = dat.substring(dat.indexOf("
"), dat.indexOf("
"));
                title = title.substring(title.indexOf("\">") + 2, title.indexOf("</"));

                String link = dat.substring(dat.indexOf("
"), dat.indexOf("
"));
                link = link.substring(link.indexOf(urlMainPageIndex));
                link = link.substring(0, link.indexOf("\""));

                String synopsis = dat.substring(dat.indexOf("pop_desc"));
                synopsis = synopsis.substring(synopsis.indexOf(">") + 1, synopsis.indexOf(""));
                synopsis = synopsis.replace("\t", "").replace("  ", "");

                if (!title.contains("Temporada")) {
                    final Flist item = new Flist(img, title, link, synopsis);
                    runOnUiThread(new Runnable() {
                        public void run() {
                            adapter.add(item);
                        }
                    });
                }
            }
        }
        runOnUiThread(new Runnable() {
            public void run() {
                adapter.notifyDataSetChanged();
                progressBar.setVisibility(View.GONE);
            }
        });
    }

    public static Drawable LoadImageFromWeb(String url) {
        try {
            InputStream is = (InputStream) new URL(url).getContent();
            Drawable d = Drawable.createFromStream(is, "src name");
            return d;
        } catch (Exception e) {
            return null;
        }
    }

}


text:
using System;

namespace VacationMasters.UnitTests.Infrastructure
{
    public static class CreateRandom
    {
        private static readonly Random Generator = new Random();

        public static TEnum Enum<TEnum>()
        {
            int value = Int();
            return (TEnum)(object)value;
        }

        public static int Int()
        {
            return Generator.Next();
        }

        public static long Long()
        {
            return Int();
        }

        public static string String()
        {
            return Int().ToString();
        }
    }
}


text:
<?php

namespace Magento\CatalogSearch\Model\Resource\Advanced;

use Magento\Catalog\Model\Product;

/**
 * Collection Advanced
 *
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Collection extends \Magento\Catalog\Model\Resource\Product\Collection
{
    /**
     * List Of filters
     * @var array
     */
    private $filters = [];

    /**
     * @var \Magento\Framework\Search\Request\Builder
     */
    private $requestBuilder;

    /**
     * @var \Magento\Search\Model\SearchEngine
     */
    private $searchEngine;

    /**
     * @param \Magento\Core\Model\EntityFactory $entityFactory
     * @param \Magento\Framework\Logger $logger
     * @param \Magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchStrategy
     * @param \Magento\Framework\Event\ManagerInterface $eventManager
     * @param \Magento\Eav\Model\Config $eavConfig
     * @param \Magento\Framework\App\Resource $resource
     * @param \Magento\Eav\Model\EntityFactory $eavEntityFactory
     * @param \Magento\Catalog\Model\Resource\Helper $resourceHelper
     * @param \Magento\Framework\Validator\UniversalFactory $universalFactory
     * @param \Magento\Store\Model\StoreManagerInterface $storeManager
     * @param \Magento\Framework\Module\Manager $moduleManager ,
     * @param \Magento\Catalog\Model\Indexer\Product\Flat\State $catalogProductFlatState
     * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
     * @param \Magento\Catalog\Model\Product\OptionFactory $productOptionFactory
     * @param \Magento\Catalog\Model\Resource\Url $catalogUrl
     * @param \Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate
     * @param \Magento\Customer\Model\Session $customerSession
     * @param \Magento\Framework\Stdlib\DateTime $dateTime
     * @param \Magento\Customer\Api\GroupManagementInterface $groupManagement
     * @param \Magento\Framework\Search\Request\Builder $requestBuilder
     * @param \Magento\Search\Model\SearchEngine $searchEngine
     * @param \Zend_Db_Adapter_Abstract $connection
     * @SuppressWarnings(PHPMD.ExcessiveParameterList)
     */
    public function __construct(
        \Magento\Core\Model\EntityFactory $entityFactory,
        \Magento\Framework\Logger $logger,
        \Magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchStrategy,
        \Magento\Framework\Event\ManagerInterface $eventManager,
        \Magento\Eav\Model\Config $eavConfig,
        \Magento\Framework\App\Resource $resource,
        \Magento\Eav\Model\EntityFactory $eavEntityFactory,
        \Magento\Catalog\Model\Resource\Helper $resourceHelper,
        \Magento\Framework\Validator\UniversalFactory $universalFactory,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Framework\Module\Manager $moduleManager,
        \Magento\Catalog\Model\Indexer\Product\Flat\State $catalogProductFlatState,
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
        \Magento\Catalog\Model\Product\OptionFactory $productOptionFactory,
        \Magento\Catalog\Model\Resource\Url $catalogUrl,
        \Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate,
        \Magento\Customer\Model\Session $customerSession,
        \Magento\Framework\Stdlib\DateTime $dateTime,
        \Magento\Customer\Api\GroupManagementInterface $groupManagement,
        \Magento\Framework\Search\Request\Builder $requestBuilder,
        \Magento\Search\Model\SearchEngine $searchEngine,
        $connection = null
    ) {
        $this->requestBuilder = $requestBuilder;
        $this->searchEngine = $searchEngine;
        parent::__construct(
            $entityFactory,
            $logger,
            $fetchStrategy,
            $eventManager,
            $eavConfig,
            $resource,
            $eavEntityFactory,
            $resourceHelper,
            $universalFactory,
            $storeManager,
            $moduleManager,
            $catalogProductFlatState,
            $scopeConfig,
            $productOptionFactory,
            $catalogUrl,
            $localeDate,
            $customerSession,
            $dateTime,
            $groupManagement,
            $connection
        );
    }

    /**
     * Add not indexable fields to search
     *
     * @param array $fields
     * @return $this
     * @throws \Magento\Framework\Model\Exception
     */
    public function addFieldsToFilter($fields)
    {
        if ($fields) {
            $this->filters = array_merge($this->filters, $fields);
        }
        return $this;
    }

    /**
     * @inheritdoc
     */
    protected function _renderFiltersBefore()
    {
        if ($this->filters) {
            $this->requestBuilder->bindDimension('scope', $this->getStoreId());
            $this->requestBuilder->setRequestName('advanced_search_container');
            foreach ($this->filters as $attributes) {
                foreach ($attributes as $attributeCode => $attributeValue) {
                    if (is_numeric($attributeCode)) {
                        $attributeCode = $this->_eavConfig->getAttribute(Product::ENTITY, $attributeCode)
                            ->getAttributeCode();
                    }
                    if (isset($attributeValue['from']) || isset($attributeValue['to'])) {
                        if (isset($attributeValue['from']) && '' !== $attributeValue['from']) {
                            $this->requestBuilder->bind("{$attributeCode}.from", $attributeValue['from']);
                        }
                        if (isset($attributeValue['to']) && '' !== $attributeValue['to']) {
                            $this->requestBuilder->bind("{$attributeCode}.to", $attributeValue['to']);
                        }
                    } elseif (!is_array($attributeValue)) {
                        $this->requestBuilder->bind($attributeCode, $attributeValue);
                    } elseif (isset($attributeValue['like'])) {
                        $this->requestBuilder->bind($attributeCode, trim($attributeValue['like'], '%'));
                    } elseif (isset($attributeValue['in'])) {
                        $this->requestBuilder->bind($attributeCode, $attributeValue['in']);
                    } elseif (isset($attributeValue['in_set'])) {
                        $this->requestBuilder->bind($attributeCode, $attributeValue['in_set']);
                    }
                }
            }
            $queryRequest = $this->requestBuilder->create();
            $queryResponse = $this->searchEngine->search($queryRequest);

            $ids = [0];
            /** @var \Magento\Framework\Search\Document $document */
            foreach ($queryResponse as $document) {
                $ids[] = $document->getId();
            }

            $this->addIdFilter($ids);
        }
        return parent::_renderFiltersBefore();
    }
}


text:
/**
 * The global namespace for Telescope utils.
 * @namespace Telescope.utils
 */
Telescope.utils = {};

/**
 * Convert a camelCase string to dash-separated string
 * @param {String} str
 */
Telescope.utils.camelToDash = function (str) {
  return str.replace(/\W+/g, '-').replace(/([a-z\d])([A-Z])/g, '$1-$2').toLowerCase();
};

/**
 * Convert an underscore-separated string to dash-separated string
 * @param {String} str
 */
Telescope.utils.underscoreToDash = function (str) {
  return str.replace('_', '-');
};

/**
 * Convert a dash separated string to camelCase.
 * @param {String} str
 */
Telescope.utils.dashToCamel = function (str) {
  return str.replace(/(\-[a-z])/g, function($1){return $1.toUpperCase().replace('-','');});
};

/**
 * Convert a string to camelCase and remove spaces.
 * @param {String} str
 */
Telescope.utils.camelCaseify = function(str) {
  str = this.dashToCamel(str.replace(' ', '-'));
  str = str.slice(0,1).toLowerCase() + str.slice(1);
  return str;
};

/**
 * Trim a sentence to a specified amount of words and append an ellipsis.
 * @param {String} s - Sentence to trim.
 * @param {Number} numWords - Number of words to trim sentence to.
 */
Telescope.utils.trimWords = function(s, numWords) {

  if (!s)
    return s;

  var expString = s.split(/\s+/,numWords);
  if(expString.length >= numWords)
    return expString.join(" ")+"…";
  return s;
};

/**
 * Trim a block of HTML code to get a clean text excerpt
 * @param {String} html - HTML to trim.
 */
Telescope.utils.trimHTML = function (html, numWords) {
  var text = Telescope.utils.stripHTML(html);
  return Telescope.utils.trimWords(text, numWords);
};

/**
 * Capitalize a string.
 * @param {String} str
 */
Telescope.utils.capitalise = function(str) {
  return str.charAt(0).toUpperCase() + str.slice(1);
};

Telescope.utils.getCurrentTemplate = function() {
  var template = Router.current().lookupTemplate();
  // on postsDaily route, template is a function
  if (typeof template === "function") {
    return template();
  } else {
    return template;
  }
};

Telescope.utils.t = function(message) {
  var d = new Date();
  console.log("### "+message+" rendered at "+d.getHours()+":"+d.getMinutes()+":"+d.getSeconds());
};

Telescope.utils.nl2br = function(str) {
  var breakTag = '<br />';
  return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ breakTag +'$2');
};

Telescope.utils.scrollPageTo = function(selector) {
  $('body').scrollTop($(selector).offset().top);
};

Telescope.utils.getDateRange = function(pageNumber) {
  var now = moment(new Date());
  var dayToDisplay=now.subtract(pageNumber-1, 'days');
  var range={};
  range.start = dayToDisplay.startOf('day').valueOf();
  range.end = dayToDisplay.endOf('day').valueOf();
  // console.log("after: ", dayToDisplay.startOf('day').format("dddd, MMMM Do YYYY, h:mm:ss a"));
  // console.log("before: ", dayToDisplay.endOf('day').format("dddd, MMMM Do YYYY, h:mm:ss a"));
  return range;
};

//////////////////////////
// URL Helper Functions //
//////////////////////////

/**
 * Returns the user defined site URL or Meteor.absoluteUrl
 */
Telescope.utils.getSiteUrl = function () {
  return Settings.get('siteUrl', Meteor.absoluteUrl());
};

/**
 * The global namespace for Telescope utils.
 * @param {String} url - the URL to redirect
 */
Telescope.utils.getOutgoingUrl = function (url) {
  return Telescope.utils.getRouteUrl('out', {}, {query: {url: url}});
};

// This function should only ever really be necessary server side
// Client side using .path() is a better option since it's relative
// and shouldn't care about the siteUrl.
Telescope.utils.getRouteUrl = function (routeName, params, options) {
  options = options || {};
  var route = Router.url(
    routeName,
    params || {},
    options
  );
  return route;
};

Telescope.utils.getSignupUrl = function() {
  return this.getRouteUrl('atSignUp');
};
Telescope.utils.getSigninUrl = function() {
  return this.getRouteUrl('atSignIn');
};

//TODO: fix this
Telescope.utils.getPostCommentUrl = function(postId, commentId) {
  // get link to a comment on a post page
  return this.getRouteUrl('post_page_comment', {
    _id: postId,
    commentId: commentId
  });
};

Telescope.utils.slugify = function (s) {
  var slug = getSlug(s, {
    truncate: 60
  });

  // can't have posts with an "edit" slug
  if (slug === "edit") {
    slug = "edit-1";
  }

  return slug;
};

Telescope.utils.getUnusedSlug = function (collection, slug) {
  var suffix = "";
  var index = 0;

  // test if slug is already in use
  while (!!collection.findOne({slug: slug+suffix})) {
    index++;
    suffix = "-"+index;
  }

  return slug+suffix;
};

Telescope.utils.getShortUrl = function(post) {
  return post.shortUrl || post.url;
};

Telescope.utils.getDomain = function(url) {
  var urlObject = Npm.require('url');
  return urlObject.parse(url).hostname.replace('www.', '');
};

Telescope.utils.invitesEnabled = function() {
  return Settings.get("requireViewInvite") || Settings.get("requirePostInvite");
};

// add http: if missing
Telescope.utils.addHttp = function (url) {
  if (url.substring(0, 5) !== "http:" && url.substring(0, 6) !== "https:") {
    url = "http:"+url;
  }
  return url;
};

/////////////////////////////
// String Helper Functions //
/////////////////////////////

Telescope.utils.cleanUp = function(s) {
  return this.stripHTML(s);
};

Telescope.utils.sanitize = function(s) {
  // console.log('// before sanitization:')
  // console.log(s)
  if(Meteor.isServer){
    s = sanitizeHtml(s, {
      allowedTags: [
        'h3', 'h4', 'h5', 'h6', 'blockquote', 'p', 'a', 'ul',
        'ol', 'nl', 'li', 'b', 'i', 'strong', 'em', 'strike',
        'code', 'hr', 'br', 'div', 'table', 'thead', 'caption',
        'tbody', 'tr', 'th', 'td', 'pre', 'img'
      ]
    });
    // console.log('// after sanitization:')
    // console.log(s)
  }
  return s;
};

Telescope.utils.stripHTML = function(s) {
  return s.replace(/<(?:.|\n)*?>/gm, '');
};

Telescope.utils.stripMarkdown = function(s) {
  var htmlBody = marked(s);
  return Telescope.utils.stripHTML(htmlBody);
};

// http://stackoverflow.com/questions/2631001/javascript-test-for-existence-of-nested-object-key
Telescope.utils.checkNested = function(obj /*, level1, level2, ... levelN*/) {
  var args = Array.prototype.slice.call(arguments);
  obj = args.shift();

  for (var i = 0; i < args.length; i++) {
    if (!obj.hasOwnProperty(args[i])) {
      return false;
    }
    obj = obj[args[i]];
  }
  return true;
};

Telescope.log = function (s) {
  if(Settings.get('debug', false))
    console.log(s);
};

// see http://stackoverflow.com/questions/8051975/access-object-child-properties-using-a-dot-notation-string
Telescope.getNestedProperty = function (obj, desc) {
  var arr = desc.split(".");
  while(arr.length && (obj = obj[arr.shift()]));
  return obj;
};


text:
var util = require("util");
var choreography = require("temboo/core/choreography");

/*
    RegexMatch
    Returns the first substring that matches the specified regular expression pattern in the specified string.
*/

var RegexMatch = function(session) {
    /*
        Create a new instance of the RegexMatch Choreo. A TembooSession object, containing a valid
        set of Temboo credentials, must be supplied.
	*/
    var location = "/Library/Utilities/Finding/RegexMatch"
    RegexMatch.super_.call(this, session, location);

    /*
    Define a callback that will be used to appropriately format the results of this Choreo.
    */
    var newResultSet = function(resultStream) {
        return new RegexMatchResultSet(resultStream);
    }

	/*
	Obtain a new InputSet object, used to specify the input values for an execution of this Choreo.
	*/
    this.newInputSet = function() {
        return new RegexMatchInputSet();
    }

	/*
	Execute this Choreo with the specified inputs, calling the specified callback upon success,
	and the specified errorCallback upon error.
	*/
    this.execute = function(inputs, callback, errorCallback) {
        this._execute(inputs, newResultSet, callback, errorCallback);
    }
}

/*
An InputSet with methods appropriate for specifying the inputs to the RegexMatch
Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
*/

var RegexMatchInputSet = function() {
    RegexMatchInputSet.super_.call(this);
        /*
        Set the value of the Pattern input for this Choreo. ((conditional, string) A regular experession.)
        */
        this.set_Pattern = function(value) {
            this.setInput("Pattern", value);
        }

        /*
        Set the value of the Text input for this Choreo. ((conditional, string) The text on which to perform a regex match.)
        */
        this.set_Text = function(value) {
            this.setInput("Text", value);
        }

}

/*
A ResultSet with methods tailored to the values returned by the RegexMatch Choreo.
The ResultSet object is used to retrieve the results of a Choreo execution.
*/

var RegexMatchResultSet = function(resultStream) {
    RegexMatchResultSet.super_.call(this, resultStream);
        /*
        Retrieve the value for the "Result" output from this Choreo execution. ((string) The result of the match.)
        */
        this.get_Result = function() {
            return this.getResult("Result");
        }
}

util.inherits(RegexMatch, choreography.Choreography);
util.inherits(RegexMatchInputSet, choreography.InputSet);
util.inherits(RegexMatchResultSet, choreography.ResultSet);
exports.RegexMatch = RegexMatch;


text:
package habitrpg

type Reward struct {
	// todo
}


text:
REG_FIDDLE(Bitmap_colorSpace, 256, 256, true, 0) {
void draw(SkCanvas* canvas) {
    SkBitmap bitmap;
    bitmap.setInfo(SkImageInfo::MakeN32(16, 32, kPremul_SkAlphaType,
            SkColorSpace::MakeSRGBLinear()));
    SkColorSpace* colorSpace = bitmap.colorSpace();
    SkDebugf("gammaCloseToSRGB: %s  gammaIsLinear: %s  isSRGB: %s\n",
            colorSpace->gammaCloseToSRGB() ? "true" : "false",
            colorSpace->gammaIsLinear() ? "true" : "false",
            colorSpace->isSRGB() ? "true" : "false");
}
}  // END FIDDLE


text:
import state from '../../state'

function createChessboard(params) {
  // console.log(state)
  const body = document.getElementById('body')
  const canvas = document.createElement('canvas')
  const text = document.createTextNode("Your browser does not support Html5 canvas, please change a browser.")
  canvas.setAttribute("width", `${state.width * 2}px`)
  canvas.setAttribute("height", `${state.width * 2}px`)
  canvas.setAttribute("id", "chessboard")
  canvas.setAttribute("style", `width: ${state.width}px; height: ${state.width}px;`)
  canvas.id = 'chessboard'
  canvas.appendChild(text)
  body.appendChild(canvas)
}

function drawChessBoard() {
  const context = state.chessboard.getContext('2d')
  context.strokeStyle = state.lineColor;
  for (var i = 0; i < state.lineNum; i++) {
    context.moveTo(state.interval + i * state.interval * 2, state.interval);
    context.lineTo(state.interval + i * state.interval * 2, state.interval * 29);
    context.stroke();
    context.moveTo(state.interval, state.interval + i * state.interval * 2);
    context.lineTo(state.interval * 29, state.interval + i * state.interval * 2);
    context.stroke();
  }
}

function clearChessBoard() {
  const context = state.chessboard.getContext('2d')
  state.chessboard.height = state.chessboard.height
}

export { createChessboard, drawChessBoard, clearChessBoard }


text:
<?xml version="1.0"?>
<package>
  <name>ieee2017_tf_broadcaster</name>
  <version>0.0.0</version>
  <description>The ieee2017_tf_broadcaster package</description>

  <maintainer email="anthony@iris-systems.net">Anthony Olive</maintainer>

  <license>MIT</license>

  <buildtool_depend>catkin</buildtool_depend>
  <build_depend>rospy</build_depend>
  <build_depend>tf</build_depend>

  <run_depend>rospy</run_depend>
  <run_depend>tf</run_depend>
</package>


text:
using System;
using System.Security.AccessControl;
using System.Text.RegularExpressions;

namespace GitHub.Unity
{
    class BranchListOutputProcessor : BaseOutputListProcessor<GitBranch>
    {
        private static readonly Regex trackingBranchRegex = new Regex(@"\[[\w]+\/.*\]");

        public override void LineReceived(string line)
        {
            if (line == null)
                return;

            var proc = new LineParser(line);
            if (proc.IsAtEnd)
                return;

            try
            {
                string name;
                string trackingName = null;

                if (proc.Matches('*'))
                    proc.MoveNext();
                proc.SkipWhitespace();
                if (proc.Matches("(HEAD "))
                {
                    name = "detached";
                    proc.MoveToAfter(')');
                }
                else
                {
                    name = proc.ReadUntilWhitespace();
                }

                proc.ReadUntilWhitespaceTrim();
                if (proc.Matches(trackingBranchRegex))
                {
                    trackingName = proc.ReadChunk('[', ']');
                    var indexOf = trackingName.IndexOf(':');
                    if (indexOf != -1)
                    {
                        trackingName = trackingName.Substring(0, indexOf);
                    }
                }

                var branch = new GitBranch(name, trackingName);
                RaiseOnEntry(branch);
            }
            catch(Exception ex)
            {
                Logger.Warning(ex, "Unexpected input when listing branches");
            }
        }
    }
}


text:
package common.db.base.jpa.internal;

import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Query;

public class JpaUtil {

	private static String defaultAlias="o";

	public static String getDefaultAlias() {
		return defaultAlias;
	}

	public static void setDefaultAlias(String alias) {
		JpaUtil.defaultAlias = alias;
	}

    public static <T> String getEntityName(Class<T> entityClass) {

        String entityname = entityClass.getSimpleName();
        Entity entity = entityClass.getAnnotation(Entity.class);
        if (entity.name() != null && !"".equals(entity.name())) {
            entityname = entity.name();
        }
        return entityname;
    }

    public static String buildSelect(String[] fields, String alias) {
    	if(alias==null || alias.trim().isEmpty())
    		alias=getDefaultAlias();
        StringBuffer sf_select = new StringBuffer("SELECT");
        if (fields!=null && fields.length>0){
        	for (String field : fields) {
                sf_select.append(" ").append(alias).append(".").append(field)
                        .append(",");
            }
        }else{
        	sf_select.append(" ").append(alias).append(" ");
        }

        return (sf_select.substring(0, sf_select.length() - 1)).toString();
    }

    public static <T> String buildSelect(Class<T> clazz,String[] fields, String alias) {
    	if(alias==null || alias.trim().isEmpty())
    		alias=getDefaultAlias();
    	String ret=String.format(" %s from %s %s ", buildSelect(fields,alias),JpaUtil.getEntityName(clazz),alias);
        return ret;
    }

    public static String buildSelect(String className,String[] fields, String alias) {
    	if(alias==null || alias.trim().isEmpty())
    		alias=getDefaultAlias();
        StringBuffer sf_select = new StringBuffer("SELECT new ").append(className).append("(");
        for (String field : fields) {
            sf_select.append(" ").append(alias).append(".").append(field)
                    .append(",");
        }
        return (sf_select.substring(0, sf_select.length() - 1))+")";
    }

    public static String buildOrderby(LinkedHashMap<String, String> orderby,String alias) {
    	if(alias==null || alias.trim().isEmpty())
    		alias=getDefaultAlias();
        StringBuffer orderbyql = new StringBuffer("");
        if (orderby != null && orderby.size() > 0) {
            orderbyql.append(" order by ");
            for (String key : orderby.keySet()) {
                orderbyql.append(alias).append(".").append(key).append(" ").append(
                        orderby.get(key)).append(",");
            }
            orderbyql.deleteCharAt(orderbyql.length() - 1);
        }
        return orderbyql.toString();
    }

    public static String buildOrderby(LinkedHashMap<String, String> orderby){
    	return buildOrderby(orderby,null);
    }

    public static<T> String getPkFieldWithoutAlias(Class<T> clazz){
    	String out = "";
        try {
        	Field[] fields =  clazz.getDeclaredFields();
        	for(Field f : fields){

        	      Annotation annotation = f.getAnnotation(Id.class);

        	      if (annotation!=null) {
        	    	  out = f.getName();
        	    	  return out;

        	      }
        	}
            PropertyDescriptor[] propertyDescriptors = Introspector
                    .getBeanInfo(clazz).getPropertyDescriptors();
            for (PropertyDescriptor propertydesc : propertyDescriptors) {
            	propertydesc.getPropertyType();
                Method method = propertydesc.getReadMethod();
                if (method != null && method.isAnnotationPresent(Id.class)) {

                    out =  propertydesc.getName();

                    return out;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if("".equals(out))
        	throw new RuntimeException("entity上没有标注id,无法获取primarykey field");
        return out;
    }

    public static <T> String getPkField(Class<T> clazz, String alias) {
    	if(alias==null || alias.trim().isEmpty())
    		alias=getDefaultAlias();
        return alias+"."+getPkFieldWithoutAlias(clazz);
    }

    public static <T> String getPkField(Class<T> clazz){
    	return getPkField(clazz,null);
    }

    public static Query setQueryParams(Query query, Object queryParams) {
        if (queryParams != null) {
            if (queryParams instanceof Object[]) {
                Object[] params = (Object[]) queryParams;
                if (params.length > 0) {
                    for (int i = 0; i < params.length; i++) {
                        query.setParameter(i + 1, params[i]);
                    }
                }
            } else if (queryParams instanceof Map) {
                Map params = (Map) queryParams;
                Iterator<String> it = params.keySet().iterator();
                while(it.hasNext()){
                    String key = it.next();
                    query.setParameter(key, params.get(key));
                }
            }else{
            	throw new RuntimeException("无效的queryParams类型,只支持Object[]和map");
            }
        }
        return query;
    }

}


text:
extern void img_makePalette(int cmapsize, int tablesize, int lookupsize,
                            float lscale, float weight,
                            int prevclrs, int doMac,
                            unsigned char *reds,
                            unsigned char *greens,
                            unsigned char *blues,
                            unsigned char *lookup);


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

namespace Conventional
{
    public static class ReflectionExtensions
    {
        public static bool IsA<T>(this Type t)
        {
            Guard.IsNotNull(t, "t");

            return typeof (T).IsAssignableFrom(t);
        }

        public static bool IsConcreteClass(this Type t)
        {
            Guard.IsNotNull(t, "t");

            return t.IsClass && !t.IsAbstract;
        }

        public static IEnumerable<Type> GetClosedInterfacesOf(this Type type, Type openGeneric)
        {
            Guard.IsNotNull(type, "type");
            Guard.IsNotNull(openGeneric, "openGeneric");

            return from i in type.GetInterfaces()
                   where i.IsGenericType
                   let defn = i.GetGenericTypeDefinition()
                   where defn == openGeneric
                   select i;
        }

        public static bool ClosesInterface(this Type t, Type openGeneric)
        {
            Guard.IsNotNull(t, "t");
            Guard.IsNotNull(openGeneric, "openGeneric");

            return t.GetClosedInterfacesOf(openGeneric).Any();
        }

        public static IEnumerable<TAttribute> GetAttributes<TAttribute>(this Type t) where TAttribute : Attribute
        {
            Guard.IsNotNull(t, "type");

            return t.GetCustomAttributes(true).OfType<TAttribute>();
        }

        public static bool HasAttribute<TAttribute>(this Type t) where TAttribute : Attribute
        {
            Guard.IsNotNull(t, "t");

            return t.GetAttributes<TAttribute>().Any();
        }

        public static bool HasInterfaces(this Type t)
        {
            Guard.IsNotNull(t, "t");

            return t.GetInterfaces().Any();
        }
    }
}


text:
namespace boost
{
  namespace metaparse
  {
    using v1::token;
  }
}

#endif


text:
require 'minitest/autorun'
require './kata'

class FirstTest < Minitest::Unit::TestCase
  def test_returns_number
    expected = 1
    result = fizzbuzz(1)
    assert_equal expected, result
  end
end