text:
'use strict';

angular.module('alienUiApp').factory('componentService', ['$http', '$resource', function($http, $resource) {
  var componentResource = $resource('rest/components/:componentId', {}, {
    'get': {
      method: 'GET'
    }
  });
  return {
    'get': componentResource.get,
    'getInArchives': function(elementName, componentType, dependencies) {
      return $http.post('rest/components/getInArchives', {
        'elementName': elementName,
        'componentType': componentType,
        'dependencies': dependencies
      });
    }
  };
}]);

angular.module('alienUiApp').factory('componentTagUpdate', ['$resource', function($resource) {
  // API REST Definition
  var resultUpdateComponentTag = $resource('rest/components/:componentId/tags', {}, {
    'upsert': {
      method: 'POST',
      isArray: false,
      headers: {
        'Content-Type': 'application/json; charset=UTF-8'
      }
    }
  });
  return resultUpdateComponentTag;
}]);

angular.module('alienUiApp').factory('componentTagDelete', ['$resource', function($resource) {
  // API REST Definition
  var resultDeleteComponentTag = $resource('rest/components/:componentId/tags/:tagKey', {}, {
    'remove': {
      method: 'DELETE',
      headers: {
        'Content-Type': 'application/json; charset=UTF-8'
      }
    }
  });
  return resultDeleteComponentTag;
}]);

/* CSAR handling */
angular.module('alienUiApp').factory('csarService', ['$resource', function($resource) {

  var nodeTypeCreateDAO = $resource('rest/csars/:csarId/nodetypes/', {}, {
    'upload': {
      method: 'POST',
      isArray: false,
      headers: {
        'Content-Type': 'application/json; charset=UTF-8'
      }
    }
  });

  var nodeTypeCRUDDAO = $resource('rest/csars/:csarId/nodetypes/:nodeTypeId', {}, {});

  var resultGetAndDelete = $resource('rest/csars/:csarId', {
    csarId: '@csarId'
  }, {
    'remove': {
      method: 'DELETE',
      headers: {
        'Content-Type': 'application/json; charset=UTF-8'
      }
    },
    'get': {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json; charset=UTF-8'
      }
    }
  });

  var searchCsar = $resource('rest/csars/search', {}, {
    'search': {
      method: 'POST',
      isArray: false,
      headers: {
        'Content-Type': 'application/json; charset=UTF-8'
      }
    }
  });

  var csarActiveDeploymentDAO = $resource('rest/csars/:csarId/active-deployment');

  return {
    'getAndDeleteCsar': resultGetAndDelete,
    'getActiveDeployment': csarActiveDeploymentDAO,
    'searchCsar': searchCsar,
    'createNodeType': nodeTypeCreateDAO,
    'nodeTypeCRUDDAO': nodeTypeCRUDDAO
  };
}]);

redpajama_set_name: RedPajamaGithub


text:
{% include header.html %}
<div class="large-12 columns">
{{ content }}
</div>
{% include footer.html %}


text:
using System;
using System.IO;
using System.Net;
using System.Runtime.Serialization;
using XenAPI;
using System.Web.Script.Serialization;

namespace XenAdmin.Actions
{
    public class HealthCheckAuthenticationAction : AsyncAction
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        private readonly string username;
        private readonly string password;

        private readonly long tokenExpiration;

        private string uploadToken;
        private string diagnosticToken;

        private const string identityTokenUrl = "/auth/api/create_identity/";
        private const string uploadGrantTokenUrl = "/feeds/api/create_grant/";
        private const string uploadTokenUrl = "/feeds/api/create_upload/";
        private const string diagnosticTokenUrl = "/diag_sdk/token_grant/";

        private readonly string identityTokenDomainName = "https://cis.citrix.com";
        private readonly string uploadGrantTokenDomainName = "https://rttf.citrix.com";
        private readonly string uploadTokenDomainName = "https://rttf.citrix.com";
        private readonly string diagnosticTokenDomainName = " https://cis.citrix.com";

        private readonly string productKey = "1a2d94a4263cd016dd7a7d510bde87f058a0b75d";

        public HealthCheckAuthenticationAction(string username, string password, long tokenExpiration, bool suppressHistory)
            : base(null, Messages.ACTION_HEALTHCHECK_AUTHENTICATION, Messages.ACTION_HEALTHCHECK_AUTHENTICATION_PROGRESS, suppressHistory)
        {
            this.username = username;
            this.password = password;
            this.tokenExpiration = tokenExpiration;

        }

        public HealthCheckAuthenticationAction(string username, string password,
            string identityTokenDomainName, string uploadGrantTokenDomainName, string uploadTokenDomainName, string diagnosticTokenDomainName,
            string productKey, long tokenExpiration, bool suppressHistory)
            : this(username, password, tokenExpiration, suppressHistory)
        {
            if (!string.IsNullOrEmpty(identityTokenDomainName))
                this.identityTokenDomainName = identityTokenDomainName;
            if (!string.IsNullOrEmpty(uploadGrantTokenDomainName))
                this.uploadGrantTokenDomainName = uploadGrantTokenDomainName;
            if (!string.IsNullOrEmpty(uploadTokenDomainName))
                this.uploadTokenDomainName = uploadTokenDomainName;
            if (!string.IsNullOrEmpty(diagnosticTokenDomainName))
                this.diagnosticTokenDomainName = diagnosticTokenDomainName;
            if (!string.IsNullOrEmpty(productKey))
                this.productKey = productKey;
        }

        protected override void Run()
        {
            try
            {
                string identityToken = GetIdentityToken();
                string uploadGrantToken = GetUploadGrantToken(identityToken);
                uploadToken = GetUploadToken(uploadGrantToken);
                diagnosticToken = GetDiagnosticToken(identityToken);
            }
            catch (HealthCheckAuthenticationException)
            {
                throw;
            }
            catch (Exception e)
            {
                throw new HealthCheckAuthenticationException(e);
            }
        }

        public string UploadToken
        {
            get { return uploadToken; }
        }

        public string DiagnosticToken
        {
            get { return diagnosticToken; }
        }

        private string GetIdentityToken()
        {
            var json = new JavaScriptSerializer().Serialize(new
            {
                username,
                password
            });
            var urlString = string.Format("{0}{1}", identityTokenDomainName, identityTokenUrl);
            try
            {
                return GetToken(urlString, json, null);
            }
            catch (WebException e)
            {
                log.InfoFormat("WebException while getting identity token from {0}. Exception Message: {1} ", identityTokenDomainName, e.Message);
                if (e.Status == WebExceptionStatus.ProtocolError && ((HttpWebResponse) e.Response).StatusCode == HttpStatusCode.Forbidden)
                    throw new HealthCheckAuthenticationException(Messages.HEALTH_CHECK_AUTHENTICATION_INVALID_CREDENTIALS, e);
                throw;
            }
            catch (Exception e)
            {
                log.InfoFormat("Exception while getting identity token from {0}. Exception Message: {1} ", identityTokenDomainName, e.Message);
                throw;
            }
        }

        private string GetUploadGrantToken(string identityToken)
        {
            var json = new JavaScriptSerializer().Serialize(new
            {
                identity_token = identityToken
            });
            if (tokenExpiration != 0)
            {
                json = new JavaScriptSerializer().Serialize(new
                {
                    identity_token = identityToken,
                    expiration = tokenExpiration
                });
            }
            var urlString = string.Format("{0}{1}", uploadGrantTokenDomainName, uploadGrantTokenUrl);

            try
            {
                return GetToken(urlString, json, null);
            }
            catch (Exception e)
            {
                log.InfoFormat("Exception while getting upload grant token from {0}. Exception Message: {1} ", uploadGrantTokenDomainName, e.Message);
                throw;
            }
        }

        private string GetUploadToken(string grantToken)
        {
            var json = new JavaScriptSerializer().Serialize(new
            {
                grant_token = grantToken,
                product_key = productKey,
                expiration = tokenExpiration
            });
            var urlString = string.Format("{0}{1}", uploadTokenDomainName, uploadTokenUrl);
            try
            {
                return GetToken(urlString, json, null);
            }
            catch (Exception e)
            {
                log.InfoFormat("Exception while getting upload token from {0}. Exception Message: {1} ", uploadTokenDomainName, e.Message);
                throw;
            }
        }

        private string GetDiagnosticToken(string identityToken)
        {
            var json = new JavaScriptSerializer().Serialize(new
            {
                agent = "XenServer",
                max_age = tokenExpiration
            });
            var urlString = string.Format("{0}{1}", diagnosticTokenDomainName, diagnosticTokenUrl);

            try
            {
                return GetToken(urlString, json, "BT " + identityToken);
            }
            catch (Exception e)
            {
                log.InfoFormat("Exception while getting diagnostic token from {0}. Exception Message: {1} ", diagnosticTokenDomainName, e.Message);
                throw;
            }
        }

        private string GetToken(string urlString, string jsonParameters, string authorizationHeader)
        {
            var httpWebRequest = (HttpWebRequest) WebRequest.Create(urlString);
            if (authorizationHeader != null)
            {
                httpWebRequest.Headers.Add("Authorization", authorizationHeader);
            }
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Method = "POST";

            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                streamWriter.Write(jsonParameters);
            }
            string result;
            var httpResponse = (HttpWebResponse) httpWebRequest.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                result = streamReader.ReadToEnd();
            }
            TemplateResponse response = new JavaScriptSerializer().Deserialize<TemplateResponse>(result);
            return response.Token;
        }

        class TemplateResponse
        {
            public string Token { get; set; }
        }

        [Serializable]
        public class HealthCheckAuthenticationException : Exception
        {
            public HealthCheckAuthenticationException() : base() { }

            public HealthCheckAuthenticationException(string message) : base(message) { }

            public HealthCheckAuthenticationException(string message, Exception exception) : base(message, exception) { }

            public HealthCheckAuthenticationException(Exception exception) : base(Messages.HEALTH_CHECK_AUTHENTICATION_FAILED, exception) { }

            public HealthCheckAuthenticationException(SerializationInfo serialinfo, StreamingContext context) : base(serialinfo, context) { }
        }
    }
}


text:
package jp.co.acroquest.endosnipe.report.converter.compressor;

import java.lang.reflect.InvocationTargetException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import jp.co.acroquest.endosnipe.report.converter.util.calc.Calculator;
import jp.co.acroquest.endosnipe.report.converter.util.calc.CalculatorFactory;
import jp.co.acroquest.endosnipe.report.util.ReporterConfigAccessor;
import jp.co.acroquest.endosnipe.report.converter.compressor.CompressOperation;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;

/**
 * 多数のサンプリングデータを圧縮し、Excelに表示可能なデータに変換するクラス。
 *
 * @author M.Yoshida
 */
@SuppressWarnings("unchecked")
public class SamplingCompressor
{
	private static final String MAX_VALUE_PROPERTY_SUFFIX_ = "Max";

	private static final String MIN_VALUE_PROPERTY_SUFFIX_ = "Min";

	private static final String SAMPLING_MAX_NUM_KEY_ = "reporter.report.maxSamples";

	/** サンプリンググループを生成する際の最小計測時間 */
	private long minLimitSamplingTerm_ = 5000;

	/** 生データのサンプリング周期[sec] */
	private long rawSamplingTerm_ = 5;

	/** 圧縮後のサンプリング数の最大数 */
	private long samplingMax_ = 0;

	private static long SEC_PER_MILLIS = 1000;

	/** デフォルトの圧縮後サンプリング数 */
	private static long DEFAULT_SAMPLING_MAX = 200;

	/**
	 * コンストラクタ(デフォルト)
	 */
	public SamplingCompressor()
	{
		this.samplingMax_ = Long.parseLong(ReporterConfigAccessor
			.getProperty(SAMPLING_MAX_NUM_KEY_));

		if (this.samplingMax_ <= 0)
		{
			this.samplingMax_ = DEFAULT_SAMPLING_MAX;
		}

	}

	/**
	 * コンストラクタ
	 *
	 * @param minTerm サンプリンググループ生成の際の最小計測時間
	 */
	public SamplingCompressor(long minTerm)
	{
		super();
		this.minLimitSamplingTerm_ = minTerm;
	}

	/**
	 * 指定のサンプリングデータを、一定数以下になるよう圧縮する。
	 * 指定したフィールドに関しては、圧縮したデータより、最大、最小、平均値を算出・補完設定する。
	 *
	 * @param samplingList     サンプリングデータ。measureTimeFieldで指定したフィールドによりソートされていることを前提とする。
	 * @param startTime        圧縮時の計測開始時刻
	 * @param endTime          圧縮時の計測終了時刻
	 * @param measureTimeField 計測時刻を格納しているフィールド
	 * @param operation        圧縮時の操作
	 * @param clazz            サンプリングデータのClass情報
	 * @return 圧縮したサンプリングデータのリスト
	 * @throws IllegalAccessException アクセスできないフィールドにアクセスした場合
	 * @throws InvocationTargetException 予期しないインスタンスを指定した場合
	 * @throws NoSuchMethodException 指定のフィールドが存在しない場合
	 * @throws NoSuchFieldException
	 * @throws InstantiationException
	 * @throws SecurityException
	 */
	public List compressSamplingList(List samplingList, Timestamp startTime, Timestamp endTime,
		String measureTimeField, List<CompressOperation> operation, Class clazz)
		throws NoSuchMethodException, IllegalAccessException, InvocationTargetException,
		SecurityException, InstantiationException, NoSuchFieldException
	{
		// サンプリンググループを作る際の1グループ当たりの「計測期間」を算出する。
		// 算出した結果が、計測時間が「最小計測時間」を下回った場合は、「最小計測時間」に合わせる。
		long samplingTerm = (endTime.getTime() - startTime.getTime()) / this.samplingMax_;

		if (samplingTerm < this.minLimitSamplingTerm_)
		{
			samplingTerm = this.minLimitSamplingTerm_;
		}

		long nowStartTime = startTime.getTime();
		int sampleIndex = 0;

		List compressedList = new ArrayList();

		while (nowStartTime < endTime.getTime())
		{
			// 現計測期間内に処理するサンプルデータを抽出する。
			List samplingGroup = new ArrayList();
			for (int cnt = sampleIndex; cnt < samplingList.size(); cnt++)
			{
				Object sampleData = samplingList.get(cnt);
				Date measureTime = (Date) PropertyUtils.getProperty(sampleData, measureTimeField);

				if (nowStartTime > measureTime.getTime())
				{
					sampleIndex++;
					continue;
				}

				if (nowStartTime + samplingTerm <= measureTime.getTime())
				{
					sampleIndex = cnt;
					break;
				}

				samplingGroup.add(sampleData);
			}

			// 圧縮データを生成する。
			Object compressedData = createCompressedSample(samplingGroup, nowStartTime,
				nowStartTime + samplingTerm, measureTimeField, operation, clazz);

			compressedList.add(compressedData);

			nowStartTime += samplingTerm;
		}

		return compressedList;
	}

	/**
	 * 指定のサンプリングデータを圧縮し、ひとつのサンプリングデータに変換する。
	 * 指定したフィールドに関しては、圧縮したデータより、最大、最小、平均値を算出・補完設定する。
	 *
	 * @param rawSamples   サンプリングデータ
	 * @param targetFields 補完を行うフィールド
	 * @return 圧縮を行ったサンプリングデータ
	 * @throws IllegalAccessException アクセスできないフィールドにアクセスした場合
	 * @throws InvocationTargetException 予期しないインスタンスを指定した場合
	 * @throws NoSuchMethodException 指定のフィールドが存在しない場合
	 * @throws InstantiationException
	 * @throws NoSuchFieldException
	 * @throws SecurityException
	 */
	private Object createCompressedSample(List rawSamples, long startTime, long endTime,
		String measureTimeField, List<CompressOperation> operation, Class clazz)
		throws IllegalAccessException, InvocationTargetException, NoSuchMethodException,
		InstantiationException, SecurityException, NoSuchFieldException
	{
		Object returnSample;

		if (rawSamples.size() < 1)
		{
			returnSample = clazz.newInstance();
		}
		else
		{
			returnSample = rawSamples.get(0);
		}

		BeanUtils.setProperty(returnSample, measureTimeField, new Timestamp(startTime));

		for (CompressOperation ope : operation)
		{
			Object maxObj = getMaxValueFromSampleList(rawSamples, ope.getCompressField(), clazz);
			Object minObj = getMinValueFromSampleList(rawSamples, ope.getCompressField(), clazz);
			Object compressedObj = getCompressedValue(rawSamples, ope, clazz, endTime - startTime);

			PropertyUtils.setProperty(returnSample, ope.getCompressField()
				+ MAX_VALUE_PROPERTY_SUFFIX_, maxObj);
			PropertyUtils.setProperty(returnSample, ope.getCompressField()
				+ MIN_VALUE_PROPERTY_SUFFIX_, minObj);
			PropertyUtils.setProperty(returnSample, ope.getCompressField(), compressedObj);
		}

		return returnSample;
	}

	/**
	 * サンプリングデータのリストから、指定したフィールドの「最大値」を算出する。
	 *
	 * @param rawSamples  サンプリングデータのリスト
	 * @param targetField 最大値を求めるフィールド
	 * @return 算出した最大値
	 * @throws IllegalAccessException アクセスできないフィールドにアクセスした場合
	 * @throws InvocationTargetException 予期しないインスタンスを指定した場合
	 * @throws NoSuchMethodException 指定のフィールドが存在しない場合
	 * @throws NoSuchFieldException
	 * @throws SecurityException
	 * @throws InstantiationException
	 */
	private Object getMaxValueFromSampleList(List rawSamples, String targetField, Class clazz)
		throws IllegalAccessException, InvocationTargetException, NoSuchMethodException,
		SecurityException, NoSuchFieldException, InstantiationException
	{
		if (rawSamples.size() < 1)
		{
			Calculator calculator = getFieldCalculator(clazz, targetField);
			return calculator.immediate("0");
		}

		List values = getValuesByFieldName(rawSamples, targetField);

		if (!(values.get(0) instanceof Comparable))
		{
			return values.get(0);
		}

		Comparable maxValue = (Comparable) values.get(0);
		for (Object value : values)
		{
			if (maxValue.compareTo(value) < 0)
			{
				maxValue = (Comparable) value;
			}
		}

		return maxValue;
	}

	/**
	 * サンプリングデータのリストから、指定したフィールドの「最小値」を算出する。
	 *
	 * @param rawSamples  サンプリングデータのリスト
	 * @param targetField 最小値を求めるフィールド
	 * @return 算出した最小値
	 * @throws IllegalAccessException アクセスできないフィールドにアクセスした場合
	 * @throws InvocationTargetException 予期しないインスタンスを指定した場合
	 * @throws NoSuchMethodException 指定のフィールドが存在しない場合
	 * @throws NoSuchFieldException
	 * @throws SecurityException
	 * @throws InstantiationException
	 */
	private Object getMinValueFromSampleList(List rawSamples, String targetField, Class clazz)
		throws IllegalAccessException, InvocationTargetException, NoSuchMethodException,
		SecurityException, NoSuchFieldException, InstantiationException
	{
		if (rawSamples.size() < 1)
		{
			Calculator calculator = getFieldCalculator(clazz, targetField);
			return calculator.immediate("0");
		}

		List values = getValuesByFieldName(rawSamples, targetField);

		if (!(values.get(0) instanceof Comparable))
		{
			return values.get(0);
		}

		Comparable minValue = (Comparable) values.get(0);
		for (Object value : values)
		{
			if (minValue.compareTo(value) > 0)
			{
				minValue = (Comparable) value;
			}
		}

		return minValue;
	}

	/**
	 * 指定したデータリストから「圧縮値」を求める
	 *
	 * @param rawSamples     サンプリングされた元データ
	 * @param operation      圧縮値を求める際の演算情報
	 * @param clazz          元データのクラス情報
	 * @param compressedTerm 圧縮するデータの計測期間
	 * @return 算出された圧縮値
	 * @throws SecurityException
	 * @throws NoSuchFieldException
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 * @throws NoSuchMethodException
	 * @throws InstantiationException
	 */
	private Object getCompressedValue(List rawSamples, CompressOperation operation, Class clazz,
		long compressedTerm) throws SecurityException, NoSuchFieldException,
		IllegalAccessException, InvocationTargetException, NoSuchMethodException,
		InstantiationException
	{
		Calculator calculator = getFieldCalculator(clazz, operation.getCompressField());

		if (rawSamples.size() < 1)
		{
			return calculator.immediate("0");
		}

		List values = getValuesByFieldName(rawSamples, operation.getCompressField());

		switch (operation.getOperation())
		{
		case SIMPLE_AVERAGE:
			Object totalValue = calcTotal(values, calculator);
			return calculator.div(totalValue, calculator.immediate(String.valueOf(values.size())));
		case TOTAL:
			return calcTotal(values, calculator);
		case TIME_AVERAGE:
			Object multipler = calculator.immediate(String.valueOf(this.rawSamplingTerm_));
			Object productSumValue = calcProductSum(values, multipler, calculator);
			Object samplingTerm = calculator.immediate(String.valueOf(compressedTerm));
			samplingTerm = calculator.div(samplingTerm,
				calculator.immediate(String.valueOf(SEC_PER_MILLIS)));
			return calculator.div(productSumValue, samplingTerm);
		}

		return null;
	}

	/**
	 * 指定したデータのリストから「合計値」を求める
	 *
	 * @param values データのリスト
	 * @param calculator 計算機クラス
	 * @return 合計値
	 */
	private Object calcTotal(List values, Calculator calculator)
	{
		if (values.size() < 1)
		{
			return calculator.immediate("0");
		}

		if (values.size() == 1)
		{
			return values.get(0);
		}

		Object result = values.get(0);

		for (int cnt = 1; cnt < values.size(); cnt++)
		{
			result = calculator.add(result, values.get(cnt));
		}

		return result;
	}

	/**
	 * 指定したデータのリストから、固定の倍数をかけた「積和」結果を求める
	 *
	 * @param values    データのリスト
	 * @param multipler 積を求めるときに用いる倍数
	 * @param calculator 計算機クラス
	 * @return 積和結果
	 */
	private Object calcProductSum(List values, Object multipler, Calculator calculator)
	{
		if (values.size() < 1)
		{
			return calculator.immediate("0");
		}

		if (values.size() == 1)
		{
			return calculator.mul(values.get(0), multipler);
		}

		Object result = calculator.mul(values.get(0), multipler);

		for (int cnt = 1; cnt < values.size(); cnt++)
		{
			Object adder = calculator.mul(values.get(cnt), multipler);
			result = calculator.add(result, adder);
		}

		return result;
	}

	/**
	 * 指定のJavaBeanを要素として持つリストから、指定のフィールドのデータのみを抜き出した
	 * リストを生成する。
	 *
	 * @param rawSamples  JavaBeanが入ったリスト
	 * @param targetField 抜き出すフィールドのフィールド名
	 * @return 抜き出したデータのリスト
	 * @throws IllegalAccessException アクセスできないフィールドにアクセスした場合
	 * @throws InvocationTargetException 予期しないインスタンスを指定した場合
	 * @throws NoSuchMethodException 指定のフィールドが存在しない場合
	 */
	private List getValuesByFieldName(List rawSamples, String targetField)
		throws IllegalAccessException, InvocationTargetException, NoSuchMethodException
	{
		List values = new ArrayList();

		for (Object sample : rawSamples)
		{
			values.add(PropertyUtils.getProperty(sample, targetField));
		}

		return values;
	}

	/**
	 * 指定クラスのフィールドの値を計算するための計算機クラスインスタンスを取得する。
	 *
	 * @param clazz     フィールドが属するクラス
	 * @param fieldName フィールドの名称
	 * @return フィールドの値を計算するための計算機クラス
	 * @throws NoSuchFieldException
	 * @throws SecurityException
	 * @throws IllegalAccessException
	 * @throws InstantiationException
	 * @throws NoSuchMethodException
	 * @throws InvocationTargetException
	 * @throws Exception 指定のフィールドがクラスに存在しないなどのエラー
	 */
	private Calculator getFieldCalculator(Class clazz, String fieldName) throws SecurityException,
		NoSuchFieldException, InstantiationException, IllegalAccessException,
		InvocationTargetException, NoSuchMethodException
	{
		Object dummy = clazz.newInstance();
		Object dummyObj = PropertyUtils.getProperty(dummy, fieldName);

		return CalculatorFactory.createCalculator(dummyObj.getClass());
	}

}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Title</title>
    <meta name="viewport" content="width=device-width" />
    <link type="text/css" rel="stylesheet" href="styles.css"/>
    <link href='https://fonts.googleapis.com/css?family=Raleway:400,300,700,900,800,500' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Roboto:200,400,700' rel='stylesheet' type='text/css'>


text:
'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
  paginate = require('mongoose-paginate'),
  Schema = mongoose.Schema;

/**
 * Report Schema
 */
var ReportSchema = new Schema({
  poll: { type : Schema.ObjectId, ref : 'Poll' },
  victim: { type: Schema.ObjectId, ref: 'User' },
  reason: { type: String, default: '' },
  created: { type: Date, default: Date.now },
  user: { type: Schema.ObjectId, ref: 'User' }
});
ReportSchema.plugin(paginate);

mongoose.model('Report', ReportSchema);


text:
import logging
import sys
import re
import subprocess
import time
import random
import signal
import requests
import json

def loggerMaster(name, logfile='slack.log', logLevel='NOTSET'):

    """master function to create loggers"""

    numeric_level = getattr(logging, logLevel.upper(), 10)

    logger = logging.getLogger(str(name))
    logger.setLevel(level=logLevel)
    fh = logging.FileHandler(logfile, mode="a")
    fh.setLevel(level=logLevel)
    ch = logging.StreamHandler(sys.stdout)
    ch.setLevel(level='CRITICAL')
    formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    fh.setFormatter(formatter)
    ch.setFormatter(formatter)
    logger.handlers
    logger.addHandler(fh)
    logger.addHandler(ch)
    logger.propagate=False

    return logger

logger = loggerMaster('slack.utils')

def signal_term_handler(signal, frame):

    logger.warning("Script terminated by kill command")
    sys.exit(0)

def set_signal():

    signal.signal(signal.SIGTERM, signal_term_handler)

class ConnectionDrop():

    """simple class to log connection errors"""

    def __init__(self, host, reason):

        self.timestamp = time.time()
        self.reason = str(reason)
        logger.error("Recorded: " + self.reason + " at " + str(self.timestamp))
        host.errors.append(self)

def get_temp():

    """returns the internal cpu temperature of a raspberry pi"""

    temp = subprocess.check_output(
        ["/opt/vc/bin/vcgencmd measure_temp"], shell=True)
    out = re.search(r'\d+\.\d+', temp)

    return str(out.group(0))

def post_message(token, username, text, emoji, channel='#general'):

    """sends a chat.postMessage to the specified channel.  data payload is a simple list, attachments must be json-encoded"""

    url="https://slack.com/api/chat.postMessage"
    #optional attachments:

    #attachments=json.dumps([{'pretext':'pretext', 'color':'warning', 'text':'text-test'}])

    payload = [
      ('channel', str(channel)),
      ('text', str(text)),
      ('token', str(token)),
      ('username', str(username)),
      ('icon_emoji', str(emoji)),
      #('attachments', attachments)
    ]

    req=requests.post(url, data=payload)
    logger.debug(str(req.text))

    return

def send_webhook(url, text, username, emoji=":robot:"):

    """sends a webhook into the specified channel.  payload is json format"""

    attachments=[{'color':'#00000', 'text':''}]

    payload = {'text':str(text), 'username':str(username), 'icon_emoji': str(emoji), 'attachments':attachments}

    req=requests.post(url, json=payload)
    logger.debug(str(req.text))

    return

def main():
    print "This is a module designed to be used with RaspiSlack"
    return 0

if __name__ == "__main__":

    main()


text:
using UnityEngine;
using System.Collections;

[CreateAssetMenu (menuName = "Spells/Spell Effect/Behavior Effect")]
public class BehaviorEffect : SpellEffect {

	public float duration;
	public BehaviorController.BEHAVIOR behavior;

	[HideInInspector] public BehaviorController behaviorController;

	public override void Initialize (GameObject caster, GameObject target)
	{
		behaviorController = target.GetComponent<BehaviorController> ();

	}

	public override IEnumerator Trigger ()
	{
		if (behaviorController != null) {
			behaviorController.Trigger(behavior);
			yield return new WaitForSeconds (duration);
			behaviorController.Trigger(BehaviorController.BEHAVIOR.NONE);
		}

	}
}


text:
package org.skife.jdbi.v2;

import org.skife.jdbi.v2.exceptions.UnableToCloseResourceException;
import org.skife.jdbi.v2.exceptions.UnableToManipulateTransactionIsolationLevelException;
import org.skife.jdbi.v2.sqlobject.SqlObjectBuilder;
import org.skife.jdbi.v2.tweak.ArgumentFactory;
import org.skife.jdbi.v2.tweak.ContainerFactory;
import org.skife.jdbi.v2.tweak.ResultSetMapper;
import org.skife.jdbi.v2.tweak.SQLLog;
import org.skife.jdbi.v2.tweak.StatementBuilder;
import org.skife.jdbi.v2.tweak.StatementCustomizer;
import org.skife.jdbi.v2.tweak.StatementLocator;
import org.skife.jdbi.v2.tweak.StatementRewriter;
import org.skife.jdbi.v2.tweak.TransactionHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

class BasicHandle implements Handle
{

    private StatementRewriter statementRewriter;
    private StatementLocator  statementLocator;
    private SQLLog            log;
    private TimingCollector   timingCollector;
    private StatementBuilder  statementBuilder;

    private boolean closed = false;

    private final Map<String, Object>      globalStatementAttributes;
    private final MappingRegistry          mappingRegistry;
    private final ContainerFactoryRegistry containerFactoryRegistry;
    private final Foreman                  foreman;
    private final TransactionHandler       transactions;
    private final Connection               connection;

    BasicHandle(TransactionHandler transactions,
                StatementLocator statementLocator,
                StatementBuilder preparedStatementCache,
                StatementRewriter statementRewriter,
                Connection connection,
                Map<String, Object> globalStatementAttributes,
                SQLLog log,
                TimingCollector timingCollector,
                MappingRegistry mappingRegistry,
                Foreman foreman,
                ContainerFactoryRegistry containerFactoryRegistry)
    {
        this.statementBuilder = preparedStatementCache;
        this.statementRewriter = statementRewriter;
        this.transactions = transactions;
        this.connection = connection;
        this.statementLocator = statementLocator;
        this.log = log;
        this.timingCollector = timingCollector;
        this.mappingRegistry = mappingRegistry;
        this.foreman = foreman;
        this.globalStatementAttributes = new HashMap<String, Object>();
        this.globalStatementAttributes.putAll(globalStatementAttributes);
        this.containerFactoryRegistry = containerFactoryRegistry.createChild();
    }

    @Override
    public Query<Map<String, Object>> createQuery(String sql)
    {
        return new Query<Map<String, Object>>(new Binding(),
                                              new DefaultMapper(),
                                              statementLocator,
                                              statementRewriter,
                                              this,
                                              statementBuilder,
                                              sql,
                                              new ConcreteStatementContext(globalStatementAttributes),
                                              log,
                                              timingCollector,
                                              Collections.<StatementCustomizer>emptyList(),
                                              new MappingRegistry(mappingRegistry),
                                              foreman.createChild(),
                                              containerFactoryRegistry.createChild());
    }

    /**
     * Get the JDBC Connection this Handle uses
     *
     * @return the JDBC Connection this Handle uses
     */
    @Override
    public Connection getConnection()
    {
        return this.connection;
    }

    @Override
    public void close()
    {
        if (!closed) {
            statementBuilder.close(getConnection());
            try {
                connection.close();
            }
            catch (SQLException e) {
                throw new UnableToCloseResourceException("Unable to close Connection", e);
            }
            finally {
                log.logReleaseHandle(this);
                closed = true;
            }
        }
    }

    boolean isClosed()
    {
        return closed;
    }

    @Override
    public void define(String key, Object value)
    {
        this.globalStatementAttributes.put(key, value);
    }

    /**
     * Start a transaction
     */
    @Override
    public Handle begin()
    {
        transactions.begin(this);
        log.logBeginTransaction(this);
        return this;
    }

    /**
     * Commit a transaction
     */
    @Override
    public Handle commit()
    {
        final long start = System.nanoTime();
        transactions.commit(this);
        log.logCommitTransaction((System.nanoTime() - start) / 1000000L, this);
        return this;
    }

    /**
     * Rollback a transaction
     */
    @Override
    public Handle rollback()
    {
        final long start = System.nanoTime();
        transactions.rollback(this);
        log.logRollbackTransaction((System.nanoTime() - start) / 1000000L, this);
        return this;
    }

    /**
     * Create a transaction checkpoint (savepoint in JDBC terminology) with the name provided.
     *
     * @param name The name of the checkpoint
     *
     * @return The same handle
     */
    @Override
    public Handle checkpoint(String name)
    {
        transactions.checkpoint(this, name);
        log.logCheckpointTransaction(this, name);
        return this;
    }

    /**
     * Release the named checkpoint, making rollback to it not possible.
     *
     * @return The same handle
     */
    @Override
    public Handle release(String checkpointName)
    {
        transactions.release(this, checkpointName);
        log.logReleaseCheckpointTransaction(this, checkpointName);
        return this;
    }

    @Override
    public void setStatementBuilder(StatementBuilder builder)
    {
        this.statementBuilder = builder;
    }

    @Override
    public void setSQLLog(SQLLog log)
    {
        this.log = log;
    }

    @Override
    public void setTimingCollector(final TimingCollector timingCollector)
    {
        if (timingCollector == null) {
            this.timingCollector = TimingCollector.NOP_TIMING_COLLECTOR;
        }
        else {
            this.timingCollector = timingCollector;
        }
    }

    /**
     * Rollback a transaction to a named checkpoint
     *
     * @param checkpointName the name of the checkpoint, previously declared with {@see Handle#checkpoint}
     */
    @Override
    public Handle rollback(String checkpointName)
    {
        final long start = System.nanoTime();
        transactions.rollback(this, checkpointName);
        log.logRollbackToCheckpoint((System.nanoTime() - start) / 1000000L, this, checkpointName);
        return this;
    }

    @Override
    public boolean isInTransaction()
    {
        return transactions.isInTransaction(this);
    }

    @Override
    public Update createStatement(String sql)
    {
        return new Update(this,
                          statementLocator,
                          statementRewriter,
                          statementBuilder,
                          sql,
                          new ConcreteStatementContext(globalStatementAttributes),
                          log,
                          timingCollector,
                          foreman,
                          containerFactoryRegistry);
    }

    @Override
    public Call createCall(String sql)
    {
        return new Call(this,
                        statementLocator,
                        statementRewriter,
                        statementBuilder,
                        sql,
                        new ConcreteStatementContext(globalStatementAttributes),
                        log,
                        timingCollector,
                        Collections.<StatementCustomizer>emptyList(),
                        foreman,
                        containerFactoryRegistry);
    }

    @Override
    public int insert(String sql, Object... args)
    {
        return update(sql, args);
    }

    @Override
    public int update(String sql, Object... args)
    {
        Update stmt = createStatement(sql);
        int position = 0;
        for (Object arg : args) {
            stmt.bind(position++, arg);
        }
        return stmt.execute();
    }

    @Override
    public PreparedBatch prepareBatch(String sql)
    {
        return new PreparedBatch(statementLocator,
                                 statementRewriter,
                                 this,
                                 statementBuilder,
                                 sql,
                                 new ConcreteStatementContext(this.globalStatementAttributes),
                                 log,
                                 timingCollector,
                                 Collections.<StatementCustomizer>emptyList(),
                                 foreman,
                                 containerFactoryRegistry);
    }

    @Override
    public Batch createBatch()
    {
        return new Batch(this.statementRewriter,
                         this.connection,
                         globalStatementAttributes,
                         log,
                         timingCollector,
                         foreman.createChild());
    }

    @Override
    public <ReturnType> ReturnType inTransaction(TransactionCallback<ReturnType> callback)
    {
        return transactions.inTransaction(this, callback);
    }

    @Override
    public void useTransaction(final TransactionConsumer callback)
    {
        transactions.inTransaction(this, new VoidTransactionCallback() {
            @Override
            protected void execute(Handle handle, TransactionStatus status) throws Exception {
                callback.useTransaction(handle, status);
            }
        });
    }

    @Override
    public <ReturnType> ReturnType inTransaction(TransactionIsolationLevel level,
                                                 TransactionCallback<ReturnType> callback)
    {
        final TransactionIsolationLevel initial = getTransactionIsolationLevel();
        boolean failed = true;
        try {
            setTransactionIsolation(level);

            ReturnType result = transactions.inTransaction(this, level, callback);
            failed = false;

            return result;
        }
        finally {
            try {
                setTransactionIsolation(initial);
            }
            catch (RuntimeException e) {
                if (! failed) {
                    throw e;
                }

                // Ignore, there was already an exceptional condition and we don't want to clobber it.
            }
        }
    }

    @Override
    public void useTransaction(TransactionIsolationLevel level, final TransactionConsumer callback)
    {
        inTransaction(level, new VoidTransactionCallback() {
            @Override
            protected void execute(Handle handle, TransactionStatus status) throws Exception {
                callback.useTransaction(handle, status);
            }
        });
    }

    @Override
    public List<Map<String, Object>> select(String sql, Object... args)
    {
        Query<Map<String, Object>> query = this.createQuery(sql);
        int position = 0;
        for (Object arg : args) {
            query.bind(position++, arg);
        }
        return query.list();
    }

    @Override
    public void setStatementLocator(StatementLocator locator)
    {
        this.statementLocator = locator;
    }

    @Override
    public void setStatementRewriter(StatementRewriter rewriter)
    {
        this.statementRewriter = rewriter;
    }

    @Override
    public Script createScript(String name)
    {
        return new Script(this, statementLocator, name, globalStatementAttributes);
    }

    @Override
    public void execute(String sql, Object... args)
    {
        this.update(sql, args);
    }

    @Override
    public void registerMapper(ResultSetMapper mapper)
    {
        mappingRegistry.add(mapper);
    }

    @Override
    public void registerMapper(ResultSetMapperFactory factory)
    {
        mappingRegistry.add(factory);
    }

    @Override
    public <SqlObjectType> SqlObjectType attach(Class<SqlObjectType> sqlObjectType)
    {
        return SqlObjectBuilder.attach(this, sqlObjectType);
    }

    @Override
    public void setTransactionIsolation(TransactionIsolationLevel level)
    {
        setTransactionIsolation(level.intValue());
    }

    @Override
    public void setTransactionIsolation(int level)
    {
        try {
            if (connection.getTransactionIsolation() == level) {
                // already set, noop
                return;
            }
            connection.setTransactionIsolation(level);
        }
        catch (SQLException e) {
            throw new UnableToManipulateTransactionIsolationLevelException(level, e);
        }
    }

    @Override
    public TransactionIsolationLevel getTransactionIsolationLevel()
    {
        try {
            return TransactionIsolationLevel.valueOf(connection.getTransactionIsolation());
        }
        catch (SQLException e) {
            throw new UnableToManipulateTransactionIsolationLevelException("unable to access current setting", e);
        }
    }

    @Override
    public void registerArgumentFactory(ArgumentFactory argumentFactory)
    {
        this.foreman.register(argumentFactory);
    }

    @Override
    public void registerContainerFactory(ContainerFactory<?> factory)
    {
        this.containerFactoryRegistry.register(factory);
    }
}


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

import com.facebook.presto.metadata.FunctionInfo;
import com.facebook.presto.metadata.FunctionRegistry;
import com.facebook.presto.metadata.ParametricFunction;
import com.facebook.presto.metadata.Signature;
import com.facebook.presto.spi.block.Block;
import com.facebook.presto.spi.type.Type;
import com.facebook.presto.spi.type.TypeManager;
import com.facebook.presto.spi.type.TypeSignature;
import com.google.common.collect.ImmutableList;
import io.airlift.slice.Slice;

import java.lang.invoke.MethodHandle;
import java.util.Map;

import static com.facebook.presto.metadata.FunctionType.SCALAR;
import static com.facebook.presto.metadata.Signature.typeParameter;
import static com.facebook.presto.type.TypeUtils.parameterizedTypeName;
import static com.facebook.presto.util.Reflection.methodHandle;

public class ElementToArrayConcatFunction
        implements ParametricFunction
{
    public static final ElementToArrayConcatFunction ELEMENT_TO_ARRAY_CONCAT_FUNCTION = new ElementToArrayConcatFunction();
    private static final String FUNCTION_NAME = "concat";
    private static final Signature SIGNATURE = new Signature(FUNCTION_NAME, SCALAR, ImmutableList.of(typeParameter("E")), "array<E>", ImmutableList.of("E", "array<E>"), false);

    private static final MethodHandle METHOD_HANDLE_BOOLEAN = methodHandle(ArrayConcatUtils.class, "prependElement", Type.class, boolean.class, Block.class);
    private static final MethodHandle METHOD_HANDLE_LONG = methodHandle(ArrayConcatUtils.class, "prependElement", Type.class, long.class, Block.class);
    private static final MethodHandle METHOD_HANDLE_DOUBLE = methodHandle(ArrayConcatUtils.class, "prependElement", Type.class, double.class, Block.class);
    private static final MethodHandle METHOD_HANDLE_SLICE = methodHandle(ArrayConcatUtils.class, "prependElement", Type.class, Slice.class, Block.class);
    private static final MethodHandle METHOD_HANDLE_OBJECT = methodHandle(ArrayConcatUtils.class, "prependElement", Type.class, Object.class, Block.class);

    @Override
    public Signature getSignature()
    {
        return SIGNATURE;
    }

    @Override
    public boolean isHidden()
    {
        return false;
    }

    @Override
    public boolean isDeterministic()
    {
        return true;
    }

    @Override
    public String getDescription()
    {
        return "Concatenates an element to an array";
    }

    @Override
    public FunctionInfo specialize(Map<String, Type> types, int arity, TypeManager typeManager, FunctionRegistry functionRegistry)
    {
        Type type = types.get("E");
        MethodHandle methodHandle;
        if (type.getJavaType() == boolean.class) {
            methodHandle = METHOD_HANDLE_BOOLEAN;
        }
        else if (type.getJavaType() == long.class) {
            methodHandle = METHOD_HANDLE_LONG;
        }
        else if (type.getJavaType() == double.class) {
            methodHandle = METHOD_HANDLE_DOUBLE;
        }
        else if (type.getJavaType() == Slice.class) {
            methodHandle = METHOD_HANDLE_SLICE;
        }
        else {
            methodHandle = METHOD_HANDLE_OBJECT;
        }
        methodHandle = methodHandle.bindTo(type);

        TypeSignature typeSignature = type.getTypeSignature();
        TypeSignature returnType = parameterizedTypeName("array", typeSignature);
        Signature signature = new Signature(FUNCTION_NAME, SCALAR, returnType, typeSignature, returnType);
        return new FunctionInfo(signature, getDescription(), isHidden(), methodHandle, isDeterministic(), false, ImmutableList.of(false, false));
    }
}


text:
package org.sakaibrary.xserver.session;

public class MetasearchSession implements java.io.Serializable {

	private static final long serialVersionUID = 1L;

	private String guid;

  private String username;
  private String password;
	private boolean isLoggedIn;
	private String sessionId;
  private String baseUrl;

	private org.osid.shared.Id repositoryId;
	private String repositoryDisplayName;

	private org.osid.shared.Properties searchProperties;
  private java.util.Properties searchStatusProperties;
  private boolean singleSearchSource;
  private boolean gotMergeError;

	private String foundGroupNumber;
	private String mergedGroupNumber;
	private String recordsSetNumber;

	private Integer numRecordsFound;
	private Integer numRecordsFetched;
	private Integer numRecordsMerged;

	public MetasearchSession( String guid ) {
		this.guid = guid;
	}

	public String getGuid() {
		return guid;
	}

	public String getFoundGroupNumber() {
		return foundGroupNumber;
	}

	public void setFoundGroupNumber(String foundGroupNumber) {
		this.foundGroupNumber = foundGroupNumber;
	}

	public boolean isLoggedIn() {
		return isLoggedIn;
	}

	public void setLoggedIn(boolean isLoggedIn) {
		this.isLoggedIn = isLoggedIn;
	}

	public String getRecordsSetNumber() {
		return recordsSetNumber;
	}

	public void setRecordsSetNumber(String recordsSetNumber) {
		this.recordsSetNumber = recordsSetNumber;
	}

	public String getSessionId() {
		return sessionId;
	}

	public void setSessionId(String sessionId) {
		this.sessionId = sessionId;
	}

	public Integer getNumRecordsFound() {
		return numRecordsFound;
	}

	public void setNumRecordsFound(Integer numRecordsFound) {
		this.numRecordsFound = numRecordsFound;
	}

	public Integer getNumRecordsFetched() {
		return numRecordsFetched;
	}

	public void setNumRecordsFetched(Integer numRecordsFetched) {
		this.numRecordsFetched = numRecordsFetched;
	}

	public String getMergedGroupNumber() {
		return mergedGroupNumber;
	}

	public void setMergedGroupNumber(String mergedGroupNumber) {
		this.mergedGroupNumber = mergedGroupNumber;
	}

	public org.osid.shared.Properties getSearchProperties() {
		return searchProperties;
	}

	public void setSearchProperties(org.osid.shared.Properties searchProperties) {
		this.searchProperties = searchProperties;
	}

	public org.osid.shared.Id getRepositoryId() {
		return repositoryId;
	}

	public void setRepositoryId(org.osid.shared.Id repositoryId) {
		this.repositoryId = repositoryId;
	}

	public String getRepositoryDisplayName() {
		return repositoryDisplayName;
	}

	public void setRepositoryDisplayName(String repositoryDisplayName) {
		this.repositoryDisplayName = repositoryDisplayName;
	}

	public Integer getNumRecordsMerged() {
		return numRecordsMerged;
	}

	public void setNumRecordsMerged(Integer numRecordsMerged) {
		this.numRecordsMerged = numRecordsMerged;
	}

  public boolean isSingleSearchSource() {
    return singleSearchSource;
  }

  public void setSingleSearchSource(boolean singleSearchSource) {
    this.singleSearchSource = singleSearchSource;
  }

  public boolean isGotMergeError() {
    return gotMergeError;
  }

  public void setGotMergeError(boolean gotMergeError) {
    this.gotMergeError = gotMergeError;
  }

  public java.util.Properties getSearchStatusProperties() {
    return searchStatusProperties;
  }

  public void setSearchStatusProperties(
      java.util.Properties searchStatusProperties) {
    this.searchStatusProperties = searchStatusProperties;
  }

  public String getBaseUrl() {
    return baseUrl;
  }

  public void setBaseUrl(String baseUrl) {
    this.baseUrl = baseUrl;
  }

  public String getPassword() {
    return password;
  }

  public void setPassword(String password) {
    this.password = password;
  }

  public String getUsername() {
    return username;
  }

  public void setUsername(String username) {
    this.username = username;
  }
}


text:
<?php
/**
 * SMOF Interface
 *
 * @package     WordPress
 * @subpackage  SMOF
 * @since       1.4.0
 * @author      Syamil MJ
 */

/**
 * Admin Init
 *
 * @uses wp_verify_nonce()
 * @uses header()
 * @uses update_option()
 *
 * @since 1.0.0
 */
function optionsframework_admin_init()
{
	// Rev up the Options Machine
	global $of_options, $options_machine;
	$options_machine = new Options_Machine($of_options);
}

/**
 * Create Options page
 *
 * @uses add_theme_page()
 * @uses add_action()
 *
 * @since 1.0.0
 */
function optionsframework_add_admin() {

    $of_page = add_theme_page( THEMENAME, 'Theme Options', 'edit_theme_options', 'optionsframework', 'optionsframework_options_page');

	// Add framework functionaily to the head individually
	add_action("admin_print_scripts-$of_page", 'of_load_only');
	add_action("admin_print_styles-$of_page",'of_style_only');
	add_action( "admin_print_styles-$of_page", 'optionsframework_mlu_css', 0 );
	add_action( "admin_print_scripts-$of_page", 'optionsframework_mlu_js', 0 );

}

/**
 * Build Options page
 *
 * @since 1.0.0
 */
function optionsframework_options_page(){

	global $options_machine;
	/*
	//for debugging
	$smof_data = get_option(OPTIONS);
	print_r($smof_data);
	*/

	include_once( ADMIN_PATH . 'front-end/options.php' );

}

/**
 * Create Options page
 *
 * @uses wp_enqueue_style()
 *
 * @since 1.0.0
 */
function of_style_only(){
	wp_enqueue_style('admin-style', ADMIN_DIR . 'assets/css/admin-style.css');
	wp_enqueue_style('color-picker', ADMIN_DIR . 'assets/css/colorpicker.css');
	wp_enqueue_style('jquery-ui-custom-admin', ADMIN_DIR .'assets/css/jquery-ui-custom.css');
}

/**
 * Create Options page
 *
 * @uses add_action()
 * @uses wp_enqueue_script()
 *
 * @since 1.0.0
 */
function of_load_only()
{
	add_action('admin_head', 'of_admin_head');

	wp_enqueue_script('jquery-ui-core');
	wp_enqueue_script('jquery-ui-sortable');
	wp_enqueue_script('jquery-ui-slider');
	wp_enqueue_script('jquery-input-mask', ADMIN_DIR .'assets/js/jquery.maskedinput-1.2.2.js', array( 'jquery' ));
	wp_enqueue_script('tipsy', ADMIN_DIR .'assets/js/jquery.tipsy.js', array( 'jquery' ));
	wp_enqueue_script('color-picker', ADMIN_DIR .'assets/js/colorpicker.js', array('jquery'));
	wp_enqueue_script('ajaxupload', ADMIN_DIR .'assets/js/ajaxupload.js', array('jquery'));
	wp_enqueue_script('cookie', ADMIN_DIR . 'assets/js/cookie.js', 'jquery');
	wp_enqueue_script('smof', ADMIN_DIR .'assets/js/smof.js', array( 'jquery' ));
}

/**
 * Front end inline jquery scripts
 *
 * @since 1.0.0
 */
function of_admin_head() { ?>

	<script type="text/javascript" language="javascript">

	jQuery.noConflict();
	jQuery(document).ready(function($){

		// COLOR Picker
		$('.colorSelector').each(function(){
			var Othis = this; //cache a copy of the this variable for use inside nested function

			$(this).ColorPicker({
					color: '<?php if(isset($color)) echo $color; ?>',
					onShow: function (colpkr) {
						$(colpkr).fadeIn(500);
						return false;
					},
					onHide: function (colpkr) {
						$(colpkr).fadeOut(500);
						return false;
					},
					onChange: function (hsb, hex, rgb) {
						$(Othis).children('div').css('backgroundColor', '#' + hex);
						$(Othis).next('input').attr('value','#' + hex);

					}
			});

		}); //end color picker

	}); //end doc ready

	</script>

<?php }

/**
 * Ajax Save Options
 *
 * @uses get_option()
 * @uses update_option()
 *
 * @since 1.0.0
 */
function of_ajax_callback()
{
	global $options_machine, $of_options;

	$nonce=$_POST['security'];

	if (! wp_verify_nonce($nonce, 'of_ajax_nonce') ) die('-1');

	//get options array from db
	$all = get_option(OPTIONS);

	$save_type = $_POST['type'];

	//echo $_POST['data'];

	//Uploads
	if($save_type == 'upload')
	{

		$clickedID = $_POST['data']; // Acts as the name
		$filename = $_FILES[$clickedID];
       	$filename['name'] = preg_replace('/[^a-zA-Z0-9._\-]/', '', $filename['name']);

		$override['test_form'] = false;
		$override['action'] = 'wp_handle_upload';
		$uploaded_file = wp_handle_upload($filename,$override);

			$upload_tracking[] = $clickedID;

			//update $options array w/ image URL
			$upload_image = $all; //preserve current data

			$upload_image[$clickedID] = $uploaded_file['url'];

			update_option(OPTIONS, $upload_image ) ;

		 if(!empty($uploaded_file['error'])) {echo 'Upload Error: ' . $uploaded_file['error']; }
		 else { echo $uploaded_file['url']; } // Is the Response

	}
	elseif($save_type == 'image_reset')
	{

			$id = $_POST['data']; // Acts as the name

			$delete_image = $all; //preserve rest of data
			$delete_image[$id] = ''; //update array key with empty value
			update_option(OPTIONS, $delete_image ) ;

	}
	elseif($save_type == 'backup_options')
	{

		$backup = $all;
		$backup['backup_log'] = date('r');

		update_option(BACKUPS, $backup ) ;

		die('1');
	}
	elseif($save_type == 'restore_options')
	{

		$smof_data = get_option(BACKUPS);

		update_option(OPTIONS, $smof_data);

		die('1');
	}
	elseif($save_type == 'import_options'){

		$smof_data = $_POST['data'];
		$smof_data = unserialize(base64_decode($smof_data)); //100% safe - ignore theme check nag
		update_option(OPTIONS, $smof_data);

		die('1');
	}
	elseif ($save_type == 'save')
	{
		wp_parse_str(stripslashes($_POST['data']), $smof_data);
		unset($smof_data['security']);
		unset($smof_data['of_save']);
		update_option(OPTIONS, $smof_data);

		die('1');
	}
	elseif ($save_type == 'reset')
	{
		update_option(OPTIONS,$options_machine->Defaults);

        die('1'); //options reset
	}

  	die();
}


text:
<?php

namespace EmployeurBundle\Controller;

use EmployeurBundle\Entity\Employeur;
use EmployeurBundle\Form\EmployeurType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use FOS\RestBundle\Controller\Annotations as Rest;
use FOS\RestBundle\View\View;
use Aws\S3\S3Client;

class ProfileController extends Controller {
    /**
     * @Rest\View(statusCode=Response::HTTP_CREATED, serializerGroups={"user"})
     * @Rest\Post("/profile")
     */
    public function postEmployeurAction(Request $request) {
        $employeur = new Employeur();
        $form = $this->createForm(EmployeurType::class, $employeur);
        $form->submit($request->request->get('profile'));
        if (!$form->isValid()) {
            return $form;
        }
        $token = $request->query->get('token');
        $em = $this->get('doctrine.orm.entity_manager');
        $authToken = $em->getRepository('AuthBundle:AuthToken')->findOneByValue($token);
        $user = $authToken->getUser();
        if ($user->getRole() != 'ROLE_EMPLOYEUR') {
            return View::create(['message' => 'Vous n\'êtes pas un employeur'], Response::HTTP_BAD_REQUEST);
        }
        $file = $request->files->get('file');
        if (!is_object($file) || !$file->isValid()) {
            return View::create(['message' => 'Votre photo ne passe pas'], Response::HTTP_BAD_REQUEST);
        }
        $root = $this->get('kernel')->getRootDir();
        $keyContent = file_get_contents($root . '/AWS_ACCESS_KEY_ID.txt');
        $secretContent = file_get_contents($root . '/AWS_SECRET_ACCESS_KEY.txt');
        $bucket = getenv('S3_BUCKET_NAME') ? getenv('S3_BUCKET_NAME') : 'dwarse';
        $key = getenv('AWS_ACCESS_KEY_ID') ? getenv('AWS_ACCESS_KEY_ID') : $keyContent;
        $secret = getenv('AWS_SECRET_ACCESS_KEY') ? getenv('AWS_SECRET_ACCESS_KEY') : $secretContent;
        $s3 = S3Client::factory(['key' => $key, 'secret' => $secret]);
        $extention = $file->getClientOriginalExtension();
        $libelle = 'employeur/photo/' . $user->getLogin() . '.' . $extention;
        $upload = $s3->upload($bucket, $libelle, fopen($_FILES['file']['tmp_name'], 'rb'), 'public-read');
        $photo = $upload->get('ObjectURL');
        $employeur->setPhoto($photo);
        $employeur->setUser($user);
        $user->setEmployeur($employeur);
        $em->persist($employeur);
        $em->persist($user);
        $em->flush();
        return $user;
    }
}


text:
import os
import shutil
import subprocess
import unittest
import muterl_lex
import muterl_logic
import muterl_clause
import muterl_constants

good_sources = [{'name': 'jsx',
                 'git': 'https://github.com/talentdeficit/jsx',
                 'revision': 'c61be973b95ba4cc5fd646d1f80b65b8eeba8376'},
                {'name': 'mochiweb',
                 'git': 'https://github.com/mochi/mochiweb',
                 'revision': 'aacb8f2e2fd98a729bd4f54e028c6b742bfb9dcb'},
                {'name': 'poolboy',
                 'git': 'https://github.com/devinus/poolboy',
                 'revision': 'd378f996182daa6251ad5438cee4d3f6eb7ea50f'},
#                {'name': 'lfe',
#                 'git': 'https://github.com/rvirding/lfe',
#                 'revision': 'c05fa59ecf51e345069787476b9e699e42be8cf6'}
                 ]

TEST_TEMP_DIR = 'test_tmp'
TEST_DATA_DIR = 'test_data'

def contents(filename):
    with open(filename) as file:
        return file.read()

def parse_source(source):
    path = os.getcwd()
    subprocess.check_call("git clone " + source["git"] + ' ' + TEST_TEMP_DIR + '/' + source["name"], shell=True)
    os.chdir(path + '/' + TEST_TEMP_DIR + '/' + source["name"])
    subprocess.check_call("git checkout "+ source["revision"], shell=True)
    try:
        subprocess.check_call("../../muterl --check-parsing", shell=True)
    finally:
        os.chdir(path)

class TestMutations(unittest.TestCase):
    def setUp(self) -> None:
        if os.path.isdir(TEST_TEMP_DIR):
            shutil.rmtree(TEST_TEMP_DIR)
        os.mkdir(TEST_TEMP_DIR)
        return super().setUp()

    def test_parsing(self):
        list(map(parse_source, good_sources))

    def test_removeclause(self):
        ast = muterl_lex.lex(('simple.erl', contents("test_data/simple.erl")))
        self.assertEqual(muterl_clause.clause_count(ast), 5)
        muterl_clause.clause_remove(0, ast, TEST_TEMP_DIR + "/simple_remove0.erl.res")
        muterl_clause.clause_remove(1, ast, TEST_TEMP_DIR + "/simple_remove1.erl.res")
        subprocess.check_call('diff ' + TEST_TEMP_DIR + '/simple_remove0.erl.res ' + TEST_DATA_DIR + '/simple_remove0.erl', shell=True)
        subprocess.check_call('diff ' + TEST_TEMP_DIR + '/simple_remove1.erl.res ' + TEST_DATA_DIR + '/simple_remove1.erl', shell=True)

    def test_inverse(self):
        ast = muterl_lex.lex(('simple2.erl', contents(TEST_DATA_DIR + '/simple2.erl')))
        muterl_logic.inverse(0, ast, TEST_TEMP_DIR + '/simple2_inverse.erl.res')
        subprocess.check_call('diff  ' + TEST_TEMP_DIR + '/simple2_inverse.erl.res ' + TEST_DATA_DIR + '/simple2_inverse.erl', shell=True)

    def test_constants(self):
        ast = muterl_lex.lex(('simple2.erl', contents(TEST_DATA_DIR + '/simple2.erl')))
        muterl_constants.change(0, ast, TEST_TEMP_DIR + '/simple2_constant.erl.res')
        subprocess.check_call('diff ' + TEST_TEMP_DIR + '/simple2_constant.erl.res ' + TEST_DATA_DIR + '/simple2_constant.erl', shell=True)

if __name__ == '__main__':
    unittest.main()


text:
echo $HOSTNAME
pm2 status
if [ $KUBERNETES_SERVICE_PORT ]
then
    mkdir - p /mnt/$HOSTNAME/
    npm run start-docker
else
    mkdir - p ./.pm2
    npm run start-docker
fi


text:
/*===========================================================================*/
/* Copyright (C) 2001 Authors                                                */
/*                                                                           */
/* This source file may be used and distributed without restriction provided */
/* that this copyright statement is not removed from the file and that any   */
/* derivative work contains the original copyright notice and the associated */
/* disclaimer.                                                               */
/*                                                                           */
/* This source file is free software; you can redistribute it and/or modify  */
/* it under the terms of the GNU Lesser General Public License as published  */
/* by the Free Software Foundation; either version 2.1 of the License, or    */
/* (at your option) any later version.                                       */
/*                                                                           */
/* This source is distributed in the hope that it will be useful, but WITHOUT*/
/* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or     */
/* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public       */
/* License for more details.                                                 */
/*                                                                           */
/* You should have received a copy of the GNU Lesser General Public License  */
/* along with this source; if not, write to the Free Software Foundation,    */
/* Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA        */
/*                                                                           */
/*===========================================================================*/
/*                             OMSP_FUNC C FILE                              */
/*---------------------------------------------------------------------------*/
/*                                                                           */
/* Author(s):                                                                */
/*             - Olivier Girard,    olgirard@gmail.com                       */
/*                                                                           */
/*---------------------------------------------------------------------------*/
/* $Rev: 19 $                                                                */
/* $LastChangedBy: olivier.girard $                                          */
/* $LastChangedDate: 2009-08-04 23:47:15 +0200 (Tue, 04 Aug 2009) $          */
/*===========================================================================*/

#include "omsp_func.h"

//--------------------------------------------------//
//                 putChar function                 //
//            (Send a byte to the Port-1)           //
//--------------------------------------------------//
//int putchar (int txdata) {
int tty_putc (int txdata) {

  // Write the output character to the Port-1
  P1OUT  = txdata;

  // Toggle Port-2[0] to signal new byte
  P2OUT ^= 0x01;

  return 0;
}

//--------------------------------------------------//
//                 Read time from the               //
//                 verilog stimulus                 //
//--------------------------------------------------//
unsigned long read_verilog_time () {

  unsigned long tick_time;

  tick_time = P6IN;
  tick_time = ((tick_time<<8) + P5IN);
  tick_time = ((tick_time<<8) + P4IN);
  tick_time = ((tick_time<<8) + P3IN);

  return tick_time;
}


text:
from datetime import datetime
from flask.ext.security import SQLAlchemyUserDatastore, UserMixin, RoleMixin
from app.model import db

# Define models required for Flask-Security
roles_users = db.Table('roles_users', db.Column('user_id', db.Integer(),
    db.ForeignKey('user.id')),
    db.Column('role_id', db.Integer(),
    db.ForeignKey('role.id')))

class Role(db.Model, RoleMixin):
    id = db.Column(db.Integer(), primary_key=True)
    name = db.Column(db.String(80), unique=True)
    description = db.Column(db.String(255))

class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key = True)
    email = db.Column(db.String(64), unique = True)
    password = db.Column(db.String(255))
    active = db.Column(db.Boolean())
    roles = db.relationship('Role', secondary=roles_users,
                            backref=db.backref('users', lazy='dynamic'))

    def is_authenticated(self):
        return True

    def is_active(self):
        return True

    def is_anonymous(self):
        return False

    def get_id(self):
        return unicode(self.id)

    def __repr__(self):
        return '<User %r>' % (self.name)

user_datastore = SQLAlchemyUserDatastore(db, User, Role)


text:
FactoryGirl.define do
  factory :button do
    assignment '1'
    association :phone
    association :story

    trait :button_star do
      assignment {'*'}
    end
    trait :button_hash do
      assignment {'#'}
    end
    trait :button_zero do
      assignment {'0'}
    end
    trait :button_one do
      assignment {'1'}
    end
    trait :button_two do
      assignment {'2'}
    end
    trait :button_three do
      assignment {'3'}
    end
    trait :button_four do
      assignment {'4'}
    end
    trait :button_five do
      assignment {'5'}
    end
    trait :button_six do
      assignment {'6'}
    end
    trait :button_seven do
      assignment {'7'}
    end
    trait :button_eight do
      assignment {'8'}
    end
    trait :button_nine do
      assignment {'9'}
    end
    trait :invalid_assignment_ß do
      assignment {'ß'}
    end
    trait :invalid_assignment_M do
      assignment {'M'}
    end
    trait :button_post_roll do
      assignment { 'PR' }
    end

    trait :fixed_story_button do
      association :story, :fixed_story
    end
    trait :venue_story_button do
      association :story, :venue_story
    end
    trait :ishmaels_story_button do
      association :story, :ishmaels_story
    end
    trait :postroll_story_button do
      association :story, :postroll_story
    end

    factory :star_button, traits: [:button_star, :fixed_story_button]
    factory :hash_button, traits: [:button_hash, :fixed_story_button]
    factory :zero_button, traits: [:button_zero, :fixed_story_button]
    factory :postroll, traits: [:button_post_roll, :postroll_story_button]

    factory :one_button_with_ishmael_story, traits: [:button_one, :ishmaels_story_button]
    factory :two_button_with_ishmael_story, traits: [:button_two, :ishmaels_story_button]
    factory :three_button_with_ishmael_story, traits: [:button_three, :ishmaels_story_button]
    factory :four_button_with_ishmael_story, traits: [:button_four, :ishmaels_story_button]
    factory :five_button_with_ishmael_story, traits: [:button_five, :ishmaels_story_button]
    factory :six_button_with_ishmael_story, traits: [:button_six, :ishmaels_story_button]
    factory :seven_button_with_ishmael_story, traits: [:button_seven, :ishmaels_story_button]
    factory :eight_button_with_ishmael_story, traits: [:button_eight, :ishmaels_story_button]
    factory :nine_button_with_ishmael_story, traits: [:button_nine, :ishmaels_story_button]

    factory :one_button_with_venue_story, traits: [:button_one, :venue_story_button]
    factory :two_button_with_venue_story, traits: [:button_two, :venue_story_button]
    factory :three_button_with_venue_story, traits: [:button_three, :venue_story_button]
    factory :four_button_with_venue_story, traits: [:button_four, :venue_story_button]
    factory :five_button_with_venue_story, traits: [:button_five, :venue_story_button]
    factory :six_button_with_venue_story, traits: [:button_six, :venue_story_button]
    factory :seven_button_with_venue_story, traits: [:button_seven, :venue_story_button]
    factory :eight_button_with_venue_story, traits: [:button_eight, :venue_story_button]
    factory :nine_button_with_venue_story, traits: [:button_nine, :venue_story_button]

    factory :invalid_button_ß, traits: [:invalid_assignment_ß]
    factory :invalid_button_M, traits: [:invalid_assignment_M]

    trait :associated_phone do
      after(:create) do |button, evaluator|
        if evaluator.phone
          button.phone = phone
        else
          button.phone = create(:phone)
        end
      end
    end

  end
end


text:
package com.github.cybortronik.registry.jwt;

import org.jose4j.jwk.PublicJsonWebKey;
import org.jose4j.lang.JoseException;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.List;

/**
 * Created by stanislav on 11/17/15.
 */
public class JsonKeyLoader {

    public PrivateKey loadPrivateKey(String jsonKey) throws JoseException {
        PublicJsonWebKey webKey = loadWebKey(jsonKey);
        return webKey.getPrivateKey();
    }

    public PublicJsonWebKey loadWebKey(String jsonKey) throws JoseException {
        return PublicJsonWebKey.Factory.newPublicJwk(jsonKey);
    }

    public PrivateKey loadPrivateKeyFromPath(Path path) throws JoseException, IOException {
        List<String> lines = Files.readAllLines(path);
        String jsonKey = String.join(" ", lines);
        return loadPrivateKey(jsonKey);
    }

    public PublicKey loadPublicKey(Path path) throws IOException, JoseException {
        List<String> lines = Files.readAllLines(path);
        String jsonKey = String.join(" ", lines);
        return loadPublicKey(jsonKey);
    }

    private PublicKey loadPublicKey(String jsonKey) throws JoseException {
        return loadWebKey(jsonKey).getPublicKey();
    }
}


text:
import {
  formatDate
} from '../../../helpers/format-date';
import { module, test } from 'qunit';

module('FormatDateHelper');

test('displays Month, Day Year', function(assert) {
  let date1 = new Date('2015-02-15T19:39:11Z');
  let date2 = new Date('2015-02-05T19:39:11Z');
  let result1 = formatDate(date1);
  let result2 = formatDate(date2);

  assert.equal(result1, 'February 15, 2015');
  assert.equal(result2, 'February 5, 2015');
});

test('handles empty values', function(assert) {
  try {
    formatDate(undefined);
    formatDate(null);
  } catch(e) {
    assert.ok(false, 'should not blow up on empty values');
  }
  assert.ok(true);
});