text:
package gosteno

import (
	"bytes"
	"encoding/json"
	"os"
	"strconv"
	"time"
	"github.com/pborman/uuid"
	"github.com/Sirupsen/logrus"
)

const (
	globalDefaultEventName = "log"
)

var (
	newLine = []byte("\n")
	hostname = "<UNKNOWN>"
	processId = "<UNKNOWN>"
)

func init() {
	var value string
	var err error

	// Hostname
	value, err = os.Hostname()
	if (err == nil) {
		hostname = value
	}
	// Process id
	processId = strconv.Itoa(os.Getpid())
}

type Formatter struct {
	logEventName string
	injectContextHost bool
	injectContextProcess bool
	injectContextLogger bool
}

func NewFormatter() *Formatter {
	return &Formatter{
		logEventName: globalDefaultEventName,
		injectContextHost: true,
		injectContextProcess: true,
		injectContextLogger: false,
	}
}

func (sf *Formatter) Format(e *logrus.Entry) (result []byte, err error) {
	var initialStenoBuffer []byte = make([]byte, 0, 512)
	var initialUserBuffer []byte = make([]byte, 0, 256)
	var stenoBuffer *bytes.Buffer = bytes.NewBuffer(initialStenoBuffer)
	var userBuffer *bytes.Buffer = bytes.NewBuffer(initialUserBuffer)
	var value []byte

	// Begin steno wrapper
	if _, err = stenoBuffer.WriteString("{"); err != nil {
		return
	}
	if err = writeKeyStringValue(stenoBuffer, "time", sf.getTime(e)); err != nil {
		return
	}
	if err = writeKeyStringValue(stenoBuffer, "name", sf.getEventName(e, sf.logEventName)); err != nil {
		return
	}
	if err = writeKeyStringValue(stenoBuffer, "level", sf.getLevel(e)); err != nil {
		return
	}

	// Encode user data; handle errors more gracefully by encoding them into the buffer if possible
	if value, err = sf.getData(e); err != nil {
		if err = writeError(stenoBuffer, err); err != nil {
			return
		}
	} else if err = writeKeyJsonValue(userBuffer, "data", value); err != nil {
		if err = writeError(stenoBuffer, err); err != nil {
			return
		}
	} else {
		if value, err = sf.getContext(e); err != nil {
			if err = writeError(stenoBuffer, err); err != nil {
				return
			}
		} else if err = writeKeyJsonValue(userBuffer, "context", value); err != nil {
			if err = writeError(stenoBuffer, err); err != nil {
				return
			}
		} else {
			if value, err = sf.getError(e); err != nil {
				if err = writeError(userBuffer, err); err != nil {
					return
				}
			} else if value != nil {
				if err = writeKeyJsonValue(userBuffer, "exception", value); err != nil {
					if err = writeError(stenoBuffer, err); err != nil {
						return
					}
				} else if _, err = stenoBuffer.Write(userBuffer.Bytes()); err != nil {
					return
				}
			} else if _, err = stenoBuffer.Write(userBuffer.Bytes()); err != nil {
				return
			}
		}
	}

	// Complete steno wrapper
	if err = writeKeyStringValue(stenoBuffer, "id", uuid.New()); err != nil {
		return
	}
	if err = writeKeyStringValue(stenoBuffer, "version", "0"); err != nil {
		return
	}
	stenoBuffer.Write(newLine);
	result = stenoBuffer.Bytes()
	result[len(result) - len(newLine) - 1] = '}'
	return
}

func (sf *Formatter) LogEventName() string {
	return sf.logEventName
}

func (sf *Formatter) SetLogEventName(v string) {
	sf.logEventName = v
}

func (sf *Formatter) InjectContextHost() bool {
	return sf.injectContextHost
}

func (sf *Formatter) SetInjectContextHost(v bool) {
	sf.injectContextHost = v
}

func (sf *Formatter) InjectContextProcess() bool {
	return sf.injectContextProcess
}

func (sf *Formatter) SetInjectContextProcess(v bool) {
	sf.injectContextProcess = v
}

func (sf *Formatter) InjectContextLogger() bool {
	return sf.injectContextLogger
}

func (sf *Formatter) SetInjectContextLogger(v bool) {
	sf.injectContextLogger = v
}

func (sf *Formatter) getTime(e *logrus.Entry) string {
	return e.Time.UTC().Format(time.RFC3339Nano)
}

func (sf *Formatter) getEventName(e *logrus.Entry, defaultName string) string {
	var marker interface{} = e.Data[MarkerKey]
	switch marker := marker.(type) {
	default:
		return defaultName
	case *MapsMarker:
		var name string
		if name = marker.ParseEvent(e); name != "" {
			return name
		}
		return defaultName
	}
}

func (sf *Formatter) getLevel(e *logrus.Entry) string {
	switch e.Level {
	case logrus.DebugLevel:
		return "debug"
	case logrus.InfoLevel:
		return "info"
	case logrus.WarnLevel:
		return "warn"
	case logrus.ErrorLevel:
		return "crit"
	case logrus.FatalLevel:
		return "fatal"
	case logrus.PanicLevel:
		return "fatal"
	}
	return "unknown"
}

func (sf *Formatter) getData(e *logrus.Entry) (jsonBytes []byte, err error) {
	var data map[string]interface{}
	var marker interface{} = e.Data[MarkerKey]
	var hasValidMarker bool = true
	switch marker := marker.(type) {
	default:
		hasValidMarker = false
		data = e.Data
	case *MapsMarker:
		data = marker.ParseData(e)
	}
	var buffer bytes.Buffer
	if _, err = buffer.WriteString("{"); err != nil {
		return
	}
	if e.Message != "" {
		if err = writeKeyStringValue(&buffer, "message", e.Message); err != nil {
			return
		}
	}
	for key, value := range data {
		// Favor explicit message in event (if not empty) over any data with the same key
		if key == "message" && e.Message != "" {
			continue
		}
		// Suppress error in event if processing raw event data (e.g. without valid marker)
		if key == logrus.ErrorKey && !hasValidMarker {
			continue
		}
		var valueJsonBytes []byte
		if valueJsonBytes, err = json.Marshal(value); err != nil {
			return
		}
		if err = writeKeyJsonValue(&buffer, key, valueJsonBytes); err != nil {
			return
		}
	}
	if buffer.Len() == 1 {
		if _, err = buffer.WriteString("}"); err != nil {
			return
		}
		jsonBytes = buffer.Bytes()
	} else {
		jsonBytes = buffer.Bytes()
		jsonBytes[len(jsonBytes) - 1] = '}'
	}
	return
}

func (sf *Formatter) getContext(e *logrus.Entry) (jsonBytes []byte, err error) {
	var context map[string]interface{}
	var loggerName string
	var marker interface{} = e.Data[MarkerKey]
	switch marker := marker.(type) {
	default:
		context = nil
		loggerName = ""
	case *MapsMarker:
		context = marker.ParseContext(e)
		loggerName = marker.ParseLoggerName(e)
	}
	var buffer bytes.Buffer
	if _, err = buffer.WriteString("{"); err != nil {
		return
	}
	for key, value := range context {
		var valueJsonBytes []byte
		if valueJsonBytes, err = json.Marshal(value); err != nil {
			return
		}
		if err = writeKeyJsonValue(&buffer, key, valueJsonBytes); err != nil {
			return
		}
	}
	if sf.injectContextHost {
		if err = writeKeyStringValue(&buffer, "host", hostname); err != nil {
			return
		}
	}
	if sf.injectContextProcess {
		if err = writeKeyStringValue(&buffer, "processId", processId); err != nil {
			return
		}
	}
	if sf.injectContextLogger && loggerName != "" {
		if err = writeKeyStringValue(&buffer, "logger", loggerName); err != nil {
			return
		}
	}
	if buffer.Len() == 1 {
		if _, err = buffer.WriteString("}"); err != nil {
			return
		}
		jsonBytes = buffer.Bytes()
	} else {
		jsonBytes = buffer.Bytes()
		jsonBytes[len(jsonBytes) - 1] = '}'
	}
	return
}

func (sf *Formatter) getError(e *logrus.Entry) (jsonBytes []byte, err error) {
	var entryError error
	var marker interface{} = e.Data[MarkerKey]
	switch marker := marker.(type) {
	default:
		entryError = nil
		if logrusError, ok := e.Data[logrus.ErrorKey].(error); ok {
			entryError = logrusError
		}
	case *MapsMarker:
		entryError = marker.ParseError(e)
	}
	if entryError != nil {
		var buffer bytes.Buffer
		if _, err = buffer.WriteString("{"); err != nil {
			return
		}
		if err = writeKeyStringValue(&buffer, "type", "error"); err != nil {
			return
		}
		if err = writeKeyStringValue(&buffer, "message", entryError.Error()); err != nil {
			return
		}
		if err = writeKeyJsonValue(&buffer, "backtrace", []byte("[]")); err != nil {
			return
		}

		jsonBytes = buffer.Bytes()
		jsonBytes[len(jsonBytes) - 1] = '}'
	}
	return
}

func writeKeyStringValue(buffer *bytes.Buffer, key string, value string) (err error) {
	var bytes []byte
	if bytes, err = json.Marshal(key); err != nil {
		return
	} else if _, err = buffer.Write(bytes); err != nil {
		return
	}
	if _, err = buffer.WriteString(":"); err != nil {
		return
	}
	if bytes, err = json.Marshal(value); err != nil {
		return
	} else if _, err = buffer.Write(bytes); err != nil {
		return
	}
	if _, err = buffer.WriteString(","); err != nil {
		return
	}
	return nil
}

func writeKeyJsonValue(buffer *bytes.Buffer, key string, jsonBytes []byte) (err error) {
	var bytes []byte
	if bytes, err = json.Marshal(key); err != nil {
		return
	} else if _, err = buffer.Write(bytes); err != nil {
		return
	}
	if _, err = buffer.WriteString(":"); err != nil {
		return
	}
	if _, err = buffer.Write(jsonBytes); err != nil {
		return
	}
	if _, err = buffer.WriteString(","); err != nil {
		return
	}
	return nil
}

func writeError(buffer *bytes.Buffer, internalError error) (err error) {
	var internalErrorAsMap = map[string]interface{} {
		"message": internalError.Error(),
	}
	var bytes []byte
	if bytes, err = json.Marshal(internalErrorAsMap); err != nil {
		return
	}
	if _, err = buffer.Write(bytes); err != nil {
		return
	}
	if _, err = buffer.WriteString(","); err != nil {
		return
	}
	return nil
}


text:
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android">

    <de.hdodenhof.circleimageview.CircleImageView
        android:id="@+id/image"
        android:layout_width="52dp"
        android:layout_height="52dp"
        android:layout_alignParentLeft="true"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:alpha="0.5" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignBottom="@+id/image"
        android:layout_alignTop="@+id/image"
        android:layout_centerVertical="true"
        android:layout_toRightOf="@+id/image">

        <TextView

            android:id="@+id/name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:alpha="0.5"
            android:fontFamily="sans-serif-condensed-light"
            android:gravity="center_vertical"
            android:textColor="@color/font_name"
            android:textSize="16sp" />

        <TextView
            android:id="@+id/location"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_below="@+id/name"
            android:alpha="0.5"
            android:fontFamily="sans-serif-condensed-light"
            android:gravity="center_vertical"
            android:textColor="@color/font_location"
            android:textSize="14sp" />

        <TextView
            android:id="@+id/time"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/name"
            android:layout_marginLeft="8dp"
            android:layout_toRightOf="@id/location"
            android:alpha="0.5"
            android:fontFamily="sans-serif-condensed-light"
            android:gravity="center_vertical"
            android:textColor="@color/font_time"
            android:textSize="14sp" />

    </RelativeLayout>
</merge>

redpajama_set_name: RedPajamaGithub


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _q = require('q');

var _q2 = _interopRequireDefault(_q);

var _Api2 = require('../Api');

var _Api3 = _interopRequireDefault(_Api2);

var _helper = require('./helper');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var Addic7ed = function (_Api) {
  _inherits(Addic7ed, _Api);

  function Addic7ed() {
    var name = arguments.length <= 0 || arguments[0] === undefined ? 'addic7ed' : arguments[0];

    _classCallCheck(this, Addic7ed);

    // Set accepted type

    var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(Addic7ed).call(this, name));

    _this.acceptedType = ['serie'];

    _this.headers = {
      referer: 'http://www.addic7ed.com'
    };

    // Expected parameter for each type
    _this.parameters = {
      serie: ['title', 'episode', 'season', 'releaseGroup']
    };
    return _this;
  }

  /**
   * Be sure to scrappe addic7ed before get subtitles
   *
   *  @return {promise}
   */

  _createClass(Addic7ed, [{
    key: 'scrapping',
    value: function scrapping() {
      var _this2 = this;

      var deferred = _q2.default.defer();

      if (this._scrapping) {
        return deferred.resolve(this._scrapping);
      }

      (0, _helper.scrapper)(function (err, shows) {
        if (err) {
          return deferred.reject('fail to scrap addic7ed');
        }

        _this2._scrapping = shows;
        return deferred.resolve(_this2._scrapping);
      });

      return deferred.promise;
    }

    /**
     * Format a json from subtitles results
     *
     *  @param {Object} subtitles
     *
     *  @return {array} subtitles ordered
     */

  }, {
    key: 'formatJson',
    value: function formatJson(subtitles) {
      var _this3 = this;

      return subtitles.map(function (sub) {
        sub.api = _this3.name;
        sub.url = 'http://addic7ed.com' + sub.url;
        return sub;
      });
    }

    /**
     * Format correctly the languages to call Addic7ed
     *
     *  @param {array} languages
     *
     *  @return {string} formatted language
     */

  }, {
    key: 'formatLanguages',
    value: function formatLanguages() {
      var languages = arguments.length <= 0 || arguments[0] === undefined ? [] : arguments[0];

      if (languages.length == 0) return null;
      return '|' + languages.map(function (lang) {
        return (0, _helper.mapping)(lang);
      }).join('|') + '|';
    }

    /**
     * Construct the right url to the api
     *
     *  @param {string} formatted languages
     *  @param {string} season
     *  @param {string} serieId
     *
     *  @return {string} formatted url
     */

  }, {
    key: 'constructUrl',
    value: function constructUrl(languages, season, serieId) {
      return 'http://addic7ed.com/ajax_loadShow.php?show=' + serieId + '&season=' + season + (!languages ? '' : '&langs=' + languages);
    }

    /**
     * Handle api call
     *
     *  @param {string} type | movie / serie
     *  @param {Object} file
     *  @param {array} languages
     *
     *  @return {Promise} subtitles
     */

  }, {
    key: 'handle',
    value: function handle(type, _ref, languages) {
      var _this4 = this;

      var episode = _ref.episode;
      var releaseGroup = _ref.releaseGroup;
      var title = _ref.title;
      var season = _ref.season;

      var serieId = void 0;
      var languagesIds = this.formatLanguages(languages);

      return this.scrapping().then(function (results) {
        return (0, _helper.getSerieId)(results, title);
      }).then(function (id) {
        return (0, _helper.getSubs)(_this4.constructUrl(languagesIds, season, id), episode, releaseGroup);
      }).then(function (subs) {
        return _this4.formatJson(subs);
      });
    }
  }]);

  return Addic7ed;
}(_Api3.default);

exports.default = Addic7ed;


text:
import { take, call, cancel, takeLatest, put, takeEvery } from 'redux-saga/effects';
import { LOCATION_CHANGE, push } from 'react-router-redux';
import winston from 'winston';
import axios from 'axios';
import { HOST } from 'constants/host';
import {
  SEND_POST_REQUESTED,
  NEW_POST_REQUESTED,
  FETCH_CATEGORIES_SUCCESS,
  FETCH_CATEGORIES_FAILED,
  POST_CREATED,
  IMAGE_DELETE,
 } from './constants';

const TOKEN = localStorage.getItem('token');

export function* fetchCategories() {
  const URL = `${HOST}api/categories?access_token=${TOKEN}`;
  try {
    const response = yield call(axios.get, URL);
    yield put({ type: FETCH_CATEGORIES_SUCCESS, data: response.data });
  } catch (err) {
    yield put({ type: FETCH_CATEGORIES_FAILED, message: err.response.data.error.details.messages });
  }
}

/* eslint-disable no-param-reassign*/

export function* newPostRequest(action) {
  const { data, user, images } = action.content;
  const jsData = data.toJS();
  const jsImage = images.toJS();
  const postURL = `${HOST}api/posts?access_token=${TOKEN}`;
  const postImageURL = `${HOST}api/cloudinaries?access_token=${TOKEN}`;
  const toPost = {
    title: jsData.title,
    description: jsData.description,
    body: jsData.body,
    userId: user.id,
    date: jsData.date,
    categoryId: jsData.categoryId,
    mainimg: jsData.mainimg,
  };
  try {
    const response = yield call(axios.post, postURL, toPost);
    if (jsImage.length > 0) {
      jsImage.forEach((image) => {
        image.postId = response.data.id;
        image.userId = user.id;
        image.categoryId = jsData.categoryId;
      });
      yield jsImage.map((image) => call(axios.post, postImageURL, image));
    }
  } catch (err) {
    winston.log('warning', err);
  }
  yield put({ type: POST_CREATED });
  yield put(push('/admin/posts'));
}

export function* imageDeleteFromServer(action) {
  yield call(axios.post, `${HOST}api/cloudinaries/direct-remove?publicId=${action.id}&access_token=${TOKEN}`);
}

export function* postWatcher() {
  const watcher = yield takeLatest(SEND_POST_REQUESTED, newPostRequest);
  const watcherFetchCategories = yield takeLatest(NEW_POST_REQUESTED, fetchCategories);
  const imgDeleteWatcher = yield takeEvery(IMAGE_DELETE, imageDeleteFromServer);
  yield take(LOCATION_CHANGE);
  yield cancel(watcher);
  yield cancel(watcherFetchCategories);
  yield cancel(imgDeleteWatcher);
}

export default [
  postWatcher,
];


text:
#include <errno.h>
#include <error.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

static void *
dummy (void *x)
{
  return NULL;
}

static char buf[sizeof "something\n"];

static int
do_test (void)
{
  FILE *f;
  pthread_t p;
  int err;

  f = popen ("echo something", "r");
  if (f == NULL)
    error (EXIT_FAILURE, errno, "popen failed");
  if (fgets (buf, sizeof (buf), f) == NULL)
    error (EXIT_FAILURE, 0, "fgets failed");
  if (strcmp (buf, "something\n"))
    error (EXIT_FAILURE, 0, "read wrong data");
  if (pclose (f))
    error (EXIT_FAILURE, errno, "pclose returned non-zero");
  if ((err = pthread_create (&p, NULL, dummy, NULL)))
    error (EXIT_FAILURE, err, "pthread_create failed");
  if ((err = pthread_join (p, NULL)))
    error (EXIT_FAILURE, err, "pthread_join failed");
  exit (0);
}

#define TEST_FUNCTION do_test ()
#include "../test-skeleton.c"


text:
require 'forwardable'
require 'logger'
require 'net/http'
require 'ostruct'
require 'pp'
require 'set'
require 'singleton'
require 'socket'
require 'timeout'

require 'aws-sdk-v1'
require 'diffy'
require 'rspec'
require 'rspec/core/formatters/progress_formatter'
require 'term/ansicolor'
require 'uuid'
require 'hashie'

require 'kelbim/ext/string-ext'
require 'kelbim/ext/ec2-ext'
require 'kelbim/ext/elb-listener-ext'
require 'kelbim/ext/elb-load-balancer-ext'

require 'kelbim/logger'
require 'kelbim/utils'
require 'kelbim/policy-types'
require 'kelbim/dsl/checker'
require 'kelbim/template_helper'

require 'kelbim/client'
require 'kelbim/dsl'
require 'kelbim/dsl/attributes'
require 'kelbim/dsl/converter'
require 'kelbim/dsl/ec2'
require 'kelbim/dsl/health-check'
require 'kelbim/dsl/listener'
require 'kelbim/dsl/listeners'
require 'kelbim/dsl/load-balancer'
require 'kelbim/exporter'
require 'kelbim/tester'
require 'kelbim/version'
require 'kelbim/wrapper/elb-wrapper'
require 'kelbim/wrapper/listener'
require 'kelbim/wrapper/listener-collection'
require 'kelbim/wrapper/load-balancer'
require 'kelbim/wrapper/load-balancer-collection'
require 'kelbim/wrapper/policy'
require 'kelbim/wrapper/policy-collection'


text:
package s3

func String(v string) *string {
	return &v
}


text:
package dk.lessismore.nojpa.reflection.translate;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.fluent.Request;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

/**
 * Created with IntelliJ IDEA.
 * User: seb
 */
public class LessismoreTranslateServiceImpl implements TranslateService {

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

    private String googleAPIkey = null;
    private String lessismoreAPIkey = null;

    public LessismoreTranslateServiceImpl(String lessismoreAPIkey, String googleAPIkey){
        this.lessismoreAPIkey = lessismoreAPIkey;
        this.googleAPIkey = googleAPIkey;
    }

    @Override
    public String translate(String uniqueID, String attributeNameForDebug, String srcLang2Char, String destLang2Char, String originalText) throws Exception{

        if(originalText == null || srcLang2Char == null || destLang2Char == null){
            if(originalText != null) {
                log.warn("We will return null - because we was called with null, in translate[uniqueID("+ uniqueID +")srcLang2Char(" + srcLang2Char + "), destLang2Char(" + destLang2Char + "), originalText(" + originalText + ")]");
            }
            return null;
        }

        StringBuilder cache = new StringBuilder((int) (originalText.length() * 1.4));

        List<NameValuePair> qparams = new ArrayList<NameValuePair>();
        qparams.add(new BasicNameValuePair("key", googleAPIkey));
        qparams.add(new BasicNameValuePair("limkey", lessismoreAPIkey));
        qparams.add(new BasicNameValuePair("source", srcLang2Char));
        qparams.add(new BasicNameValuePair("target", destLang2Char));
        qparams.add(new BasicNameValuePair("q", originalText));
        qparams.add(new BasicNameValuePair("itemID", uniqueID));
        qparams.add(new BasicNameValuePair("attribute", attributeNameForDebug));

        InputStream getStream = Request.Post("https://www.googleapis.com/language/translate/v2")
                .setHeader(new BasicHeader("X-HTTP-Method-Override", "GET"))
                .body(new UrlEncodedFormEntity(qparams, "UTF-8"))
                .execute()
                .returnContent()
                .asStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(getStream));
        String line;
        while ((line = rd.readLine()) != null) {
            cache.append(line);
        }
        log.debug("uniqueID("+ uniqueID +") src("+ srcLang2Char +") dest("+ destLang2Char +") translated_text: " + cache);
        JsonNode jsonNode = new ObjectMapper().reader().readTree(cache.toString());

        String code = jsonNode.get("code").textValue();
        return jsonNode.get("translatedText").textValue();
    }
}


text:
"""
S3 Storage object.
"""
import os
import tempfile
from cStringIO import StringIO

import boto
from boto.s3.key import Key
from boto.s3.connection import S3Connection

from django.conf import settings

from .base import BaseStorage, StorageError

################################
#  S3 Storage Object
################################

class Storage(BaseStorage):
    """ S3 API Storage. """
    S3_BUCKET = getattr(settings, 'DBBACKUP_S3_BUCKET', None)
    S3_ACCESS_KEY = getattr(settings, 'DBBACKUP_S3_ACCESS_KEY', None)
    S3_SECRET_KEY = getattr(settings, 'DBBACKUP_S3_SECRET_KEY', None)
    S3_DOMAIN = getattr(settings, 'DBBACKUP_S3_DOMAIN', 's3.amazonaws.com')
    S3_IS_SECURE = getattr(settings, 'DBBACKUP_S3_USE_SSL', True)
    S3_DIRECTORY = getattr(settings, 'DBBACKUP_S3_DIRECTORY', "django-dbbackups/")
    S3_DIRECTORY = '%s/' % S3_DIRECTORY.strip('/')

    def __init__(self, server_name=None):
        self._check_filesystem_errors()
        self.name = 'AmazonS3'
        self.conn = S3Connection(aws_access_key_id=self.S3_ACCESS_KEY,
                                 aws_secret_access_key=self.S3_SECRET_KEY,
                                 host=self.S3_DOMAIN,
                                 is_secure=self.S3_IS_SECURE)
        self.bucket = self.conn.get_bucket(self.S3_BUCKET)
        BaseStorage.__init__(self)

    def _check_filesystem_errors(self):
        """ Check we have all the required settings defined. """
        if not self.S3_BUCKET:
            raise StorageError('Filesystem storage requires DBBACKUP_S3_BUCKET to be defined in settings.')
        if not self.S3_ACCESS_KEY:
            raise StorageError('Filesystem storage requires DBBACKUP_S3_ACCESS_KEY to be defined in settings.')
        if not self.S3_SECRET_KEY:
            raise StorageError('Filesystem storage requires DBBACKUP_S3_SECRET_KEY to be defined in settings.')

    ###################################
    #  DBBackup Storage Methods
    ###################################

    @property
    def bucket(self):
        return self.bucket

    def backup_dir(self):
        return self.S3_DIRECTORY

    def delete_file(self, filepath):
        """ Delete the specified filepath. """
        self.bucket.delete_key(filepath)

    def list_directory(self):
        """ List all stored backups for the specified. """
        return [k.name for k in
                self.bucket.list(prefix=self.S3_DIRECTORY)]

    def write_file(self, filehandle):
        """ Write the specified file.
            Use multipart upload because normal upload maximum is 5 GB.
        """
        filepath = os.path.join(self.S3_DIRECTORY, filehandle.name)

        filehandle.seek(0)

        mp = self.bucket.initiate_multipart_upload(filepath)

        try:
            part_index = 1
            while True:
                buffer = filehandle.read(5 * 1024 * 1024)

                if not buffer:
                    break
                else:
                    string_file = StringIO(buffer)
                    try:
                        string_file.seek(0)
                        mp.upload_part_from_file(string_file, part_index)
                    finally:
                        string_file.close()

                    part_index += 1

            mp.complete_upload()
        except:
            mp.cancel_upload()
            raise

    def read_file(self, filepath):
        """ Read the specified file and return it's handle. """
        key = Key(self.bucket)
        key.key = filepath
        filehandle = tempfile.SpooledTemporaryFile(max_size=10 * 1024 * 1024)
        key.get_contents_to_file(filehandle)
        return filehandle


text:
class WebStaticCodeGetter : public StaticCodeGetter {
public:
    WebStaticCodeGetter();
    std::string GetBeforePreHeader();
    std::string GetAfterPreHeader();
    std::string GetAfterHeader();
    std::string GetBeforeFooter();
    std::string GetAfterFooter();
    std::string GetAfterPostFooter();
    unsigned int GetStartingIndent();
};

#endif // WEBSTATICCODEGETTER_H


text:
require 'digest/sha2'
module WepayRails
  module Api
    module ChargeMethods
      # Many of the settings you pass in here are already factored in from
      # the wepay.yml file and only need to be overridden if you insist on doing
      # so when this method is called. The following list of key values are pulled
      # in for you from your wepay.yml file:
      #
      # Note: @wepay_config is your wepay.yml as a Hash
      # :callback_uri     => @wepay_config[:ipn_callback_uri],
      # :redirect_uri     => @wepay_config[:checkout_redirect_uri],
      # :fee_payer        => @wepay_config[:fee_payer],
      # :type             => @wepay_config[:checkout_type],
      # :charge_tax       => @wepay_config[:charge_tax] ? 1 : 0,
      # :app_fee          => @wepay_config[:app_fee],
      # :auto_capture     => @wepay_config[:auto_capture] ? 1 : 0,
      # :require_shipping => @wepay_config[:require_shipping] ? 1 : 0,
      # :shipping_fee     => @wepay_config[:shipping_fee],
      # :charge_tax       => @wepay_config[:charge_tax],
      # :account_id       => wepay_user['account_id'] # wepay-rails goes and gets this for you, but you can override it if you want to.
      #
      #
      # params hash key values possibilities are:
      # Parameter:	Required:	Description:
      # :account_id	Yes	The unique ID of the account you want to create a checkout for.
      # :short_description	Yes	A short description of what is being paid for.
      # :long_description	No	A long description of what is being paid for.
      # :type	Yes	The the checkout type (one of the following: GOODS, SERVICE, DONATION, or PERSONAL)
      # :reference_id	No	The unique reference id of the checkout (set by the application in /checkout/create
      # :amount	Yes	The amount that the payer will pay.
      # :app_fee	No	The amount that the application will receive in fees.
      # :fee_payer	  No	Who will pay the fees (WePay's fees and any app fees). Set to "Payer" to charge fees to the person paying (Payer will pay amount + fees, payee will receive amount). Set to "Payee" to charge fees to the person receiving money (Payer will pay amount, Payee will receive amount - fees). Defaults to "Payer".
      # :redirect_uri 	No	The uri the payer will be redirected to after paying.
      # :callback_uri	  No	The uri that will receive any Instant Payment Notifications sent. Needs to be a full uri (ex https://www.wepay.com )
      # :auto_capture	No	A boolean value (0 or 1). Default is 1. If set to 0 then the payment will not automatically be released to the account and will be held by WePay in payment state 'reserved'. To release funds to the account you must call /checkout/capture
      # :require_shipping	No	A boolean value (0 or 1). If set to 1 then the payer will be asked to enter a shipping address when they pay. After payment you can retrieve this shipping address by calling /checkout
      # :shipping_fee	No	The amount that you want to charge for shipping.
      # :charge_tax	No	A boolean value (0 or 1). If set to 1 and the account has a relevant tax entry (see /account/set_tax), then tax will be charged.
      def perform_charge(params)
        security_token = Digest::SHA2.hexdigest("#{Rails.env.production? ? rand(4) : 1}#{Time.now.to_i}") # Make less random during tests

        # add the security token to any urls that were passed in from the app
        if params[:callback_uri]
          params[:callback_uri] = apply_security_token( params[:callback_uri], security_token )
        end

        if params[:redirect_uri]
          params[:redirect_uri] = apply_security_token( params[:redirect_uri], security_token )
        end

        defaults = {
            :callback_uri     => ipn_callback_uri(security_token),
            :redirect_uri     => checkout_redirect_uri(security_token),
            :fee_payer        => @wepay_config[:fee_payer],
            :type             => @wepay_config[:checkout_type],
            :charge_tax       => @wepay_config[:charge_tax] ? 1 : 0,
            :app_fee          => @wepay_config[:app_fee],
            :auto_capture     => @wepay_config[:auto_capture] ? 1 : 0,
            :require_shipping => @wepay_config[:require_shipping] ? 1 : 0,
            :shipping_fee     => @wepay_config[:shipping_fee],
            :account_id       => @wepay_config[:account_id]
        }.merge(params)

        resp = self.call_api("/checkout/create", defaults)
        resp.merge({:security_token => security_token})
      end

      def lookup_checkout(checkout_id)
        co = self.call_api("/checkout", {:checkout_id => checkout_id})
        co.delete(:type)
        co
      end

      def lookup_preapproval(preapproval_id)
        co = self.call_api("/preapproval", {:preapproval_id => preapproval_id})
        co.delete("type")
        co
      end

      def ipn_callback_uri(security_token)
        uri = if @wepay_config[:ipn_callback_uri].present?
                @wepay_config[:ipn_callback_uri]
              else
                "#{@wepay_config[:root_callback_uri]}/wepay/ipn"
              end
        apply_security_token(uri, security_token)
      end

      def charge_redirect_uri(security_token)
        uri = if @wepay_config[:ipn_callback_uri].present?
                @wepay_config[:charge_redirect_uri]
              else
                "#{@wepay_config[:root_callback_uri]}/wepay/charge"
              end
        apply_security_token(uri, security_token)
      end

      def checkout_redirect_uri(security_token)
        uri = if @wepay_config[:ipn_callback_uri].present?
                @wepay_config[:checkout_redirect_uri]
              else
                "#{@wepay_config[:root_callback_uri]}/wepay/checkout"
              end
        apply_security_token(uri, security_token)
      end

      def apply_security_token(uri, security_token)
        uri += (uri =~ /\?/ ? '&' : '?') + "security_token=#{security_token}"
      end
    end
  end
end


text:
package au.com.williamhill.flywheel;

import static junit.framework.TestCase.*;
import static org.mockito.Mockito.*;

import java.io.*;
import java.util.*;
import java.util.function.*;

import org.junit.*;
import org.mockito.*;

import au.com.williamhill.flywheel.Launchpad.*;

public final class LaunchpadTest {
  @Before
  public void before() {
    clearProps();
  }

  @After
  public void after() {
    clearProps();
  }

  private static void clearProps() {
    System.clearProperty("TestLauncher.a");
    System.clearProperty("TestLauncher.b");
    System.clearProperty("flywheel.launchpad.profile");
  }

  @Test(expected=LaunchpadException.class)
  public void testPathDoesNotExit() throws LaunchpadException {
    new Launchpad(new File("foo/bar"));
  }

  @Test(expected=LaunchpadException.class)
  public void testPathNotADirectory() throws LaunchpadException {
    new Launchpad(new File("conf/test-good/profile.yaml"));
  }

  @Test(expected=LaunchpadException.class)
  public void testProfileMissing() throws LaunchpadException {
    new Launchpad(new File("conf"));
  }

  @Test(expected=LaunchpadException.class)
  public void testBadProfile() throws LaunchpadException {
    new Launchpad(new File("conf/test-bad"));
  }

  @Test(expected=LaunchpadException.class)
  public void testLauncherError() throws Exception {
    final Launchpad launchpad = new Launchpad(new File("conf/test-good"));
    final Launcher launcher = Mockito.mock(Launcher.class);
    Mockito.doThrow(new RuntimeException(new Exception("boom"))).when(launcher).launch(Mockito.any());
    launchpad.getProfile().launchers = new Launcher[] {launcher};
    launchpad.launch(new String[0]);
  }

  @Test
  public void testGetProfilePathProperty() {
    System.setProperty("flywheel.launchpad.profile", "conf/test-good");
    final File path = Launchpad.getProfilePath(new HashMap<>());
    assertNotNull(path);
    assertEquals("conf/test-good", path.getPath());
  }

  @Test
  public void testGetProfilePathEnvDefault() {
    final File path = Launchpad.getProfilePath(new HashMap<>());
    assertNotNull(path);
    assertEquals("conf/default", path.getPath());
  }

  @Test
  public void testGetProfilePathEnvSupplied() {
    final Map<String, String> env = new HashMap<>();
    env.put("FLYWHEEL_PROFILE", "conf/test-good");
    final File path = Launchpad.getProfilePath(env);
    assertNotNull(path);
    assertEquals("conf/test-good", path.getPath());
  }

  @Test
  public void testMain() {
    System.setProperty("flywheel.launchpad.profile", "conf/test-good");
    Launchpad.main();
  }

  @Test
  public void testBootstrap() {
    final IntConsumer exitHandler = mock(IntConsumer.class);
    System.setProperty("flywheel.launchpad.profile", "conf/test-bad");
    Launchpad.bootstrap(new String[0], exitHandler);
    verify(exitHandler).accept(eq(1));
  }

  @Test
  public void testDirect() throws LaunchpadException {
    final Launchpad launchpad = new Launchpad(new File("conf/test-good"));
    launchpad.launch(new String[0]);
    assertNotNull(launchpad.getProfile().launchers);
    assertEquals(TestLauncher.class, launchpad.getProfile().launchers[0].getClass());
    assertTrue(((TestLauncher) launchpad.getProfile().launchers[0]).launched);
    assertEquals("a", System.getProperty("TestLauncher.a"));
    assertEquals("b", System.getProperty("TestLauncher.b"));
  }
}


text:
<link href='cache.php?css=theme,default,grid,alerts,mysqlcolors' rel="stylesheet" />

{{MESSAGE}}

				<?php echo __('Table'); ?>
				<?php echo __('Number of matches'); ?>

			<?php foreach($data['results'] as $table => $info) { ?>

					<?php echo $table; ?>
					<?php
						if ($info['matches'] == 0)
							echo $info['matches'];
						else {
							$txt = str_replace('{{NUM}}', $info['matches'], __('{{NUM}} match(es)'));
							$txt .= ' [' . __('Copy query to editor') . ']';
							echo ''.$txt.'
'.htmlspecialchars($data['queries'][$table]).'
';
						}
					?>

			<?php } ?>


text:
#include <Array.hpp>
#include <sort.hpp>
#include <math.hpp>
#include <copy.hpp>
#include <algorithm>
#include <functional>
#include <platform.hpp>
#include <queue.hpp>
#include <range.hpp>
#include <iota.hpp>
#include <handle.hpp>
#include <sort_by_key.hpp>
#include <reorder.hpp>
#include <kernel/sort.hpp>

namespace cpu
{

template<typename T, int dim>
void sortBatched(Array<T>& val, bool isAscending)
{
    af::dim4 inDims = val.dims();

    // Sort dimension
    af::dim4 tileDims(1);
    af::dim4 seqDims = inDims;
    tileDims[dim] = inDims[dim];
    seqDims[dim] = 1;

    Array<uint> key = iota<uint>(seqDims, tileDims);

    Array<uint> resKey = createEmptyArray<uint>(dim4());
    Array<T   > resVal = createEmptyArray<T>(dim4());

    val.setDataDims(inDims.elements());
    key.setDataDims(inDims.elements());

    sort_by_key<T, uint>(resVal, resKey, val, key, 0, isAscending);

    // Needs to be ascending (true) in order to maintain the indices properly
    sort_by_key<uint, T>(key, val, resKey, resVal, 0, true);
    val.eval();

    val.setDataDims(inDims); // This is correct only for dim0
}

template<typename T>
void sort0(Array<T>& val, bool isAscending)
{
    int higherDims = val.elements() / val.dims()[0];
    // TODO Make a better heurisitic
    if(higherDims > 10)
        sortBatched<T, 0>(val, isAscending);
    else
        getQueue().enqueue(kernel::sort0Iterative<T>, val, isAscending);
}

template<typename T>
Array<T> sort(const Array<T> &in, const unsigned dim, bool isAscending)
{
    in.eval();

    Array<T> out = copyArray<T>(in);
    switch(dim) {
        case 0: sort0<T>(out, isAscending); break;
        case 1: sortBatched<T, 1>(out, isAscending); break;
        case 2: sortBatched<T, 2>(out, isAscending); break;
        case 3: sortBatched<T, 3>(out, isAscending); break;
        default: AF_ERROR("Not Supported", AF_ERR_NOT_SUPPORTED);
    }

    if(dim != 0) {
        af::dim4 preorderDims = out.dims();
        af::dim4 reorderDims(0, 1, 2, 3);
        reorderDims[dim] = 0;
        preorderDims[0] = out.dims()[dim];
        for(int i = 1; i <= (int)dim; i++) {
            reorderDims[i - 1] = i;
            preorderDims[i] = out.dims()[i - 1];
        }

        out.setDataDims(preorderDims);
        out = reorder<T>(out, reorderDims);
    }
    return out;
}

#define INSTANTIATE(T)                                                  \
    template Array<T> sort<T>(const Array<T> &in, const unsigned dim, bool isAscending);

INSTANTIATE(float)
INSTANTIATE(double)
//INSTANTIATE(cfloat)
//INSTANTIATE(cdouble)
INSTANTIATE(int)
INSTANTIATE(uint)
INSTANTIATE(char)
INSTANTIATE(uchar)
INSTANTIATE(short)
INSTANTIATE(ushort)
INSTANTIATE(intl)
INSTANTIATE(uintl)

}


text:
package com.google.appengine.api.search.dev;

import com.google.appengine.api.search.proto.SearchServicePb;
import com.google.apphosting.api.search.DocumentPb;
import com.google.common.collect.FluentIterable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.SortField;
import org.apache.lucene.search.TopDocs;

/**
 * Scorer for CUSTOM sorting algorithm, which uses expression evaluation for
 * multidimensional sorting.
 */
public class GenericScorer extends Scorer implements Comparator<GenericScorer.Result> {

  /** The regular expression that matches a field name. */
  private static final Pattern FIELD_NAME_PATTERN = Pattern.compile("^\\w+$");

  /** Lucene native Sort if convertable or default Sort. */
  private final Sort nativeSort;

  /** Expressions for scoring. */
  private final NumericExpression[] expressions;

  /** Sort strategy classes for multi-dimensional sorting. */
  private final Expression.Sorter[] sorters;

  /** Maximium number of documents to score. */
  private final int scorerLimit;

  public GenericScorer(
      int scorerLimit,
      Sort nativeSort,
      NumericExpression[] expressions,
      Expression.Sorter[] sorters) {
    this.scorerLimit = scorerLimit;
    this.nativeSort = nativeSort;
    this.expressions = expressions;
    this.sorters = sorters;
  }

  public static Scorer newInstance(
      SearchServicePb.SearchParams searchParams,
      Map<String, Set<DocumentPb.FieldValue.ContentType>> fieldTypes) {
    int count = searchParams.getSortSpecCount();
    if (count == 0) {
      throw new IllegalArgumentException("no sort exporessions found");
    }

    boolean isNative = true;
    SortField[] fields = new SortField[count];
    int index = 0;

    for (SearchServicePb.SortSpec spec : searchParams.getSortSpecList()) {
      String expression = spec.getSortExpression();
      if (!FIELD_NAME_PATTERN.matcher(expression).matches()) {
        // unable to use lucene native sort
        isNative = false;
        break;
      } else {
        fields[index++] = new SortField(expression, SortField.STRING, spec.getSortDescending());
      }
    }
    Sort nativeSort;

    if (isNative) {
      nativeSort = new Sort(fields);
    } else {
      nativeSort = SimpleScorer.naturalOrder();
    }

    ExpressionBuilder builder = new ExpressionBuilder(fieldTypes);
    NumericExpression[] expressions = new NumericExpression[count];
    List<Expression.Sorter> sorters = new ArrayList<Expression.Sorter>();

    for (int i = 0; i < count; i++) {
      SearchServicePb.SortSpec spec = searchParams.getSortSpec(i);
      Expression expression = null;
      try {
        expression = builder.parse(spec.getSortExpression());
      } catch (IllegalArgumentException e) {
        String errorMessage = String.format("Failed to parse sort expression \'%s\': %s",
            spec.getSortExpression(), e.getMessage());
        throw new SearchException(errorMessage);
      }
      double numericDefault = spec.getDefaultValueNumeric();
      sorters.addAll(expression.getSorters(
          spec.getSortDescending() ? 1 : -1,
          numericDefault, spec.getDefaultValueText()));
      if (expression instanceof NumericExpression) {
        expressions[i] = new NumericDefaultExpression(
            (NumericExpression) expression, numericDefault);
      } else {
        expressions[i] = new ExpressionBuilder.IntValueExpression(numericDefault);
      }
    }
    sorters.add(new Expression.Sorter() {
      /** Evaluate expression to intermediate value suitable for sorting. */
      @Override
      public Object eval(Document doc) {
        Field f = doc.getField(LuceneUtils.ORDER_ID_FIELD_NAME);
        return Integer.parseInt(f.stringValue());
      }

      /** Sort intermediate values. */
      @Override
      public int compare(Object left, Object right) {
        return Integer.compare((int) left, (int) right);
      }
    });
    Expression.Sorter[] sortersArray = sorters.toArray(new Expression.Sorter[sorters.size()]);
    return new GenericScorer(
        searchParams.getScorerSpec().getLimit(), nativeSort, expressions, sortersArray);
  }

  /**
   * Result class for GenericScorer. Keeps intermediate values produced by
   * sorters.
   */
  public class Result extends Scorer.Result {
    private final Object[] intermediate;

    public Result(Document doc) {
      super(doc);
      this.intermediate = new Object[sorters.length];
    }

    public Object getValue(int idx) {
      if (intermediate[idx] != null) {
        return intermediate[idx];
      }
      return intermediate[idx] = sorters[idx].eval(doc);
    }

    @Override
    public void addScores(
        SearchServicePb.SearchResult.Builder resultBuilder) {
      for (int i = 0; i < expressions.length; i++) {
        try {
          resultBuilder.addScore(expressions[i].evalDouble(doc));
        } catch (EvaluationException e) {
          throw new RuntimeException("internal error, the exception should be caught already", e);
        }
      }
    }
  }

  @Override
  public int compare(Result left, Result right) {
    for (int i = 0; i < sorters.length; i++) {
      int compare = sorters[i].compare(left.getValue(i), right.getValue(i));
      if (compare != 0) {
        return compare;
      }
    }
    return 0;
  }

  @Override
  public SearchResults search(
      IndexSearcher indexSearcher,
      Query q,
      int offset,
      int limit) throws IOException {
    int docsToFind = offset + limit;
    int numDocs = Math.max(scorerLimit, docsToFind);
    TopDocs topDocs = indexSearcher.search(q, null, numDocs, nativeSort);
    Result[] resultsArray = new Result[topDocs.scoreDocs.length];
    if (sorters.length != 0) {
      ArrayList<Result> results = new ArrayList<>();
      for (ScoreDoc scoreDoc : topDocs.scoreDocs) {
        results.add(new Result(indexSearcher.doc(scoreDoc.doc)));
      }
      // the call to reverseOrder is to make the highest-ranked items sort first (rather than the
      // lowest-ranked items)
      Collections.sort(results, Collections.reverseOrder(this));
      resultsArray = FluentIterable.from(results).skip(offset).limit(limit).toArray(Result.class);
    } else {
      // There are no valid sort specs so we default to the sort order of nativeSort.
      for (int i = 0; i < topDocs.scoreDocs.length; i++) {
        resultsArray[i] = new Result(indexSearcher.doc(topDocs.scoreDocs[i].doc));
      }
    }
    return new SearchResults(resultsArray, topDocs.totalHits);
  }
}


text:
package gov.nih.nci.cagrid.data.codegen;

import gov.nih.nci.cagrid.common.Utils;
import gov.nih.nci.cagrid.data.DataServiceConstants;
import gov.nih.nci.cagrid.data.ExtensionDataUtils;
import gov.nih.nci.cagrid.data.extension.AdditionalLibraries;
import gov.nih.nci.cagrid.data.extension.Data;
import gov.nih.nci.cagrid.data.extension.ModelClass;
import gov.nih.nci.cagrid.data.extension.ModelInformation;
import gov.nih.nci.cagrid.data.extension.ModelPackage;
import gov.nih.nci.cagrid.data.extension.ModelSourceType;
import gov.nih.nci.cagrid.data.mapping.ClassToQname;
import gov.nih.nci.cagrid.data.mapping.Mappings;
import gov.nih.nci.cagrid.introduce.IntroduceConstants;
import gov.nih.nci.cagrid.introduce.beans.extension.ExtensionTypeExtensionData;
import gov.nih.nci.cagrid.introduce.beans.extension.ServiceExtensionDescriptionType;
import gov.nih.nci.cagrid.introduce.beans.namespace.NamespaceType;
import gov.nih.nci.cagrid.introduce.beans.namespace.SchemaElementType;
import gov.nih.nci.cagrid.introduce.common.CommonTools;
import gov.nih.nci.cagrid.introduce.common.ServiceInformation;
import gov.nih.nci.cagrid.introduce.extension.CodegenExtensionException;
import gov.nih.nci.cagrid.introduce.extension.CodegenExtensionPostProcessor;
import gov.nih.nci.cagrid.introduce.extension.ExtensionTools;
import gov.nih.nci.cagrid.introduce.extension.utils.ExtensionUtilities;

import java.io.File;
import java.io.FileWriter;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

import javax.xml.namespace.QName;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 *  BaseCodegenPostProcessorExtension
 *  Base class for the DS codegen post processor extension
 *
 * @author David W. Ervin
 *
 * @created Jun 16, 2006
 * @version $Id: BaseCodegenPostProcessorExtension.java,v 1.5 2009-01-13 15:55:19 dervin Exp $
 */
public abstract class BaseCodegenPostProcessorExtension implements CodegenExtensionPostProcessor {
	private static final Log logger = LogFactory.getLog(DataServiceOperationProviderCodegenPostProcessor.class);

    public void postCodegen(ServiceExtensionDescriptionType desc, ServiceInformation info)
        throws CodegenExtensionException {
        modifyEclipseClasspath(desc, info);
        generateClassToQnameMapping(getExtensionData(desc, info), info);
        writeOutAuditorConfiguration(getExtensionData(desc, info), info);
        performCodegenProcess(desc, info);
    }

    protected abstract void performCodegenProcess(ServiceExtensionDescriptionType desc, ServiceInformation info) throws CodegenExtensionException;

	protected void modifyEclipseClasspath(ServiceExtensionDescriptionType desc, ServiceInformation info) throws CodegenExtensionException {
		// get the eclipse classpath document
		File classpathFile = new File(info.getBaseDirectory(), ".classpath");
		if (classpathFile.exists()) {
			logger.info("Modifying eclipse .classpath file");
			Set<File> libs = new HashSet<File>();
			ExtensionTypeExtensionData data = ExtensionTools.getExtensionData(desc, info);
			AdditionalLibraries additionalLibs = null;
			try {
				additionalLibs = ExtensionDataUtils.getExtensionData(data).getAdditionalLibraries();
			} catch (Exception ex) {
				throw new CodegenExtensionException("Error retrieving extension data");
			}
			if (additionalLibs != null && additionalLibs.getJarName() != null) {
				for (int i = 0; i < additionalLibs.getJarName().length; i++) {
					String jarFilename = additionalLibs.getJarName(i);
					libs.add(new File(info.getBaseDirectory(), "lib" + File.separator + jarFilename));
				}
			}
			File[] libFiles = new File[libs.size()];
			libs.toArray(libFiles);
			try {
				logger.info("Adding libraries to classpath file:");
				for (int i = 0; i < libFiles.length; i++) {
					logger.info("\t" + libFiles[i].getAbsolutePath());
				}
				ExtensionUtilities.syncEclipseClasspath(classpathFile, libFiles);
			} catch (Exception ex) {
				throw new CodegenExtensionException("Error modifying Eclipse .classpath file: " + ex.getMessage(), ex);
			}
		} else {
			logger.warn("Eclipse .classpath file " + classpathFile.getAbsolutePath() + " not found!");
		}
	}

	protected void generateClassToQnameMapping(Data extData, ServiceInformation info)
		throws CodegenExtensionException {
		try {
            Mappings mappings = new Mappings();
            List<ClassToQname> classMappings = new LinkedList<ClassToQname>();
            // the first place to look for mappings is in the model information, which
            // is derived from the data service Domain Model.  If no domain model is to be used,
            // the mappings are still required to do anything with caCORE SDK beans.
            ModelInformation modelInfo = extData.getModelInformation();
            if (modelInfo != null && !ModelSourceType.none.equals(modelInfo.getSource())
                && modelInfo.getModelPackage() != null) {
                logger.debug("Model information / domain model found in service model.");
                logger.debug("Generating class to qname mapping from the information");
                logger.debug("stored in the service model");
                // walk packages in the model
                for (ModelPackage pack : modelInfo.getModelPackage()) {
                    // locate a NamsepaceType in the service model mapped to this package
                    NamespaceType mappedNamespace = null;
                    for (NamespaceType nsType : info.getServiceDescriptor().getNamespaces().getNamespace()) {
                        if (pack.getPackageName().equals(nsType.getPackageName())) {
                            mappedNamespace = nsType;
                            break;
                        }
                    }
                    if (mappedNamespace != null && pack.getModelClass() != null) {
                        // walk classes in this package, if any exist
                        for (ModelClass clazz : pack.getModelClass()) {
                            if (clazz.isTargetable()) {
                                // find a schema element type mapped to this class
                                for (SchemaElementType element : mappedNamespace.getSchemaElement()) {
                                    if (clazz.getShortClassName().equals(element.getClassName())) {
                                        // found it!  Create a mapping
                                        QName qname = new QName(mappedNamespace.getNamespace(), element.getType());
                                        String fullClassname = pack.getPackageName() + "." + clazz.getShortClassName();
                                        ClassToQname map = new ClassToQname(fullClassname, qname.toString());
                                        classMappings.add(map);
                                        break;
                                    }
                                }
                            }
                        }
                    } else {
                        logger.warn("Model package " + pack.getPackageName() + " is not mapped to any namespace!");
                    }
                }
                ClassToQname[] mapArray = new ClassToQname[classMappings.size()];
                classMappings.toArray(mapArray);
                mappings.setMapping(mapArray);
            } else {
                logger.warn("No model information / domain model found in service model.");
                logger.warn("Falling back to schema information for class to qname mapping.");
                NamespaceType[] namespaces = info.getNamespaces().getNamespace();
                // a set of namespaces to ignore
                Set<String> nsIgnores = new HashSet<String>();
                nsIgnores.add(IntroduceConstants.W3CNAMESPACE);
                nsIgnores.add(info.getServices().getService(0).getNamespace());
                nsIgnores.add(DataServiceConstants.ENUMERATION_DATA_SERVICE_NAMESPACE);
                nsIgnores.add(DataServiceConstants.DATA_SERVICE_NAMESPACE);
                nsIgnores.add(DataServiceConstants.CQL_QUERY_URI);
                nsIgnores.add(DataServiceConstants.CQL_RESULT_SET_URI);

                for (int nsIndex = 0; nsIndex < namespaces.length; nsIndex++) {
                    NamespaceType currentNs = namespaces[nsIndex];
                    // ignore any unneeded namespaces
                    if (!nsIgnores.contains(currentNs.getNamespace())) {
                        SchemaElementType[] schemaElements = currentNs.getSchemaElement();
                        for (int elemIndex = 0; schemaElements != null && elemIndex < schemaElements.length; elemIndex++) {
                            SchemaElementType currentElement = schemaElements[elemIndex];
                            ClassToQname toQname = new ClassToQname();
                            QName qname = new QName(currentNs.getNamespace(), currentElement.getType());
                            String shortClassName = currentElement.getClassName();
                            if (shortClassName == null) {
                                shortClassName = currentElement.getType();
                            }
                            String fullClassName = currentNs.getPackageName() + "." + shortClassName;
                            toQname.setQname(qname.toString());
                            toQname.setClassName(fullClassName);
                            classMappings.add(toQname);
                        }
                    }
                }
            }

            ClassToQname[] mapArray = new ClassToQname[classMappings.size()];
            classMappings.toArray(mapArray);
            mappings.setMapping(mapArray);
            // create the filename where the mapping will be stored
            String mappingFilename = new File(info.getBaseDirectory(),
                "etc" + File.separator + DataServiceConstants.CLASS_TO_QNAME_XML).getAbsolutePath();
            // serialize the mapping to that file
            Utils.serializeDocument(mappingFilename, mappings, DataServiceConstants.MAPPING_QNAME);
		} catch (Exception ex) {
			ex.printStackTrace();
			throw new CodegenExtensionException(
                "Error generating class to QName mapping: " + ex.getMessage(), ex);
		}
	}

    protected void writeOutAuditorConfiguration(Data extData, ServiceInformation serviceInfo) throws CodegenExtensionException {
        if (CommonTools.servicePropertyExists(
            serviceInfo.getServiceDescriptor(),
            DataServiceConstants.DATA_SERVICE_AUDITORS_CONFIG_FILE_PROPERTY)) {
            try {
                // get the name of the auditor config file
                String filename = CommonTools.getServicePropertyValue(
                    serviceInfo.getServiceDescriptor(),
                    DataServiceConstants.DATA_SERVICE_AUDITORS_CONFIG_FILE_PROPERTY);
                if (extData.getDataServiceAuditors() != null) {
                    File outFile = new File(serviceInfo.getBaseDirectory().getAbsolutePath()
                        + File.separator + "etc" + File.separator + filename);
                    FileWriter writer = new FileWriter(outFile);
                    Utils.serializeObject(extData.getDataServiceAuditors(),
                        DataServiceConstants.DATA_SERVICE_AUDITORS_QNAME, writer);
                    writer.flush();
                    writer.close();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                throw new CodegenExtensionException(
                    "Error writing auditor configuration: " + ex.getMessage(), ex);
            }
        }
    }

    protected Data getExtensionData(ServiceExtensionDescriptionType desc, ServiceInformation info)
        throws CodegenExtensionException {
        ExtensionTypeExtensionData extData = ExtensionTools.getExtensionData(desc, info);
        Data data = null;
        try {
            data = ExtensionDataUtils.getExtensionData(extData);
        } catch (Exception ex) {
            throw new CodegenExtensionException("Error getting extension data: " + ex.getMessage(), ex);
        }
        return data;
    }
}


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

<recipeml version="0.5">
  <recipe>
    <head>
      <title>Almond Buttercrunch Candy</title>
      <categories>
        <cat>Candies</cat>
        <cat>Holiday</cat></categories>
      <yield>1</yield></head>
    <ingredients>
      <ing>
        <amt>
          <qty>1</qty>
          <unit>cup</unit></amt>
        <item>Almonds, slivered;blanched</item></ing>
      <ing>
        <amt>
          <qty>1/2</qty>
          <unit>cups</unit></amt>
        <item>Butter</item></ing>
      <ing>
        <amt>
          <qty>1/2</qty>
          <unit>cups</unit></amt>
        <item>Sugar</item></ing>
      <ing>
        <amt>
          <qty>1</qty>
          <unit>tablespoon</unit></amt>
        <item>Corn syrup, light</item></ing></ingredients>
    <directions>
      <step>  Line bottom and sides of 8 or 9 inch cake pan with foil. Butter heavily.
  Combine almonds, butter, sugar and corn syrup in 10 inch skillet. Bring to
  a boil over medium heat, stirring constantly until mixture turns golden
  brown, about 5 to 6 minutes. Quickly spread candy in prepared pan. Cool
  until firm. Remove candy from pan by lifting edges of foil. Break into
  pieces, if desired. makes; about 3/4 lb

  From Gemini's MASSIVE MealMaster collection at www.synapse.com/~gemini

</step></directions></recipe></recipeml>


text:
<?php
/**
 * EDP\Web\Controls\Label en_US localization
 *
 * @author Frederic BAYLE <contact (at) made-in-softland (dot) com>
 * @version 2017-12-28
 * @ignore
 */

namespace EDP;

use EDP\LocalizationResource as LRes;

// Resources
Localization::MergeEDPClassResources([
    'EDP\Web\Controls\Label::GetAssociatedControl_ErrNoControl' => new LRes('You must set an associated control for the Label {0}'),
    'EDP\Web\Controls\Label::GetAssociatedControl_ErrControlNotFound' => new LRes('Associated control not found for the Label {0}'),
    'EDP\Web\Controls\Label::GetAssociatedControl_ErrControlType' => new LRes('The associated control must be an instance on HtmlControl for the Label {0}'),
]);


text:
package org.apache.metron.common.field.validation;

import java.io.Serializable;
import java.util.Map;

public interface FieldValidation extends Serializable {
  boolean isValid( Map<String, Object> input
                 , Map<String, Object> validationConfig
                 , Map<String, Object> globalConfig
                 );
  void initialize(Map<String, Object> validationConfig, Map<String, Object> globalConfig);
}


text:
from django.conf.urls.defaults import *
from django.views.generic.list_detail import object_list, object_detail

from models import Project
from views import release_list, release_detail, document_list, document_detail

project_info = {
    'queryset': Project.objects.all(),
    'template_object_name': 'project',
}

urlpatterns = patterns('',
    url(r'^$',
        object_list,
        project_info,
        name='project-list'),
    url(r'^(?P<slug>[\w-]+)/$',
        object_detail,
        dict(project_info, slug_field='slug'),
        name='project-detail'),
    url(r'^(?P<project_slug>[\w-]+)/r/$',
        release_list,
        name='release-list'),
    url(r'^(?P<project_slug>[\w-]+)/r/(?P<release_slug>[\w-]+)/$',
        release_detail,
        name='release-detail'),
    url(r'^(?P<project_slug>[\w-]+)/d/$',
        document_list,
        name='document-list'),
    url(r'^(?P<project_slug>[\w-]+)/d/(?P<document_slug>[\w-]+)/(?P<revision>[\d]+)/$',
        document_detail,
        name='document-detail'),
)


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  Copyright 2015 Google Inc.

  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.
  -->

<io.plaidapp.ui.widget.ElasticDragDismissFrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/comments_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/background_light"
    android:transitionName="@string/transition_story_background"
    app:dragDismissDistance="@dimen/drag_dismiss_distance"
    app:dragDismissScale="0.95">

    <!-- toolbar & description added as header in the adapter
         see layout-land/designer_news_story_description -->

    <android.support.v7.widget.RecyclerView
        android:id="@+id/comments_list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/padding_normal"
        android:clipToPadding="false"
        android:scrollbars="vertical" />

    <include layout="@layout/designer_news_story_fab"/>

</io.plaidapp.ui.widget.ElasticDragDismissFrameLayout>


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

namespace Cake.Common.Tools.NuGet.Pack
{
    /// <summary>
    /// Represents a NuGet nuspec dependency
    /// </summary>
    public class NuSpecDependency
    {
        /// <summary>
        /// Gets or sets the dependency's package ID.
        /// </summary>
        /// <value>The dependency's package ID.</value>
        public string Id { get; set; }

        /// <summary>
        /// Gets or sets the dependency's version.
        /// </summary>
        /// <value>The dependency's version.</value>
        public string Version { get; set; }

        /// <summary>
        /// Gets or sets the target framework for the dependency.
        /// </summary>
        /// <value>The target framework for the dependency.</value>
        public string TargetFramework { get; set; }
    }
}


text:
'use strict';

/**
 * An arm role receiver.
 *
 */
class ArmRoleReceiver {
  /**
   * Create a ArmRoleReceiver.
   * @property {string} name The name of the arm role receiver. Names must be
   * unique across all receivers within an action group.
   * @property {string} roleId The arm role id.
   * @property {boolean} useCommonAlertSchema Indicates whether to use common
   * alert schema.
   */
  constructor() {
  }

  /**
   * Defines the metadata of ArmRoleReceiver
   *
   * @returns {object} metadata of ArmRoleReceiver
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'ArmRoleReceiver',
      type: {
        name: 'Composite',
        className: 'ArmRoleReceiver',
        modelProperties: {
          name: {
            required: true,
            serializedName: 'name',
            type: {
              name: 'String'
            }
          },
          roleId: {
            required: true,
            serializedName: 'roleId',
            type: {
              name: 'String'
            }
          },
          useCommonAlertSchema: {
            required: true,
            serializedName: 'useCommonAlertSchema',
            type: {
              name: 'Boolean'
            }
          }
        }
      }
    };
  }
}

module.exports = ArmRoleReceiver;


text:
/* eslint-disable */

'use strict';

/*::
import type { ReaderFragment } from 'relay-runtime';
import type { FragmentReference } from "relay-runtime";
declare export opaque type useFragmentNodeReactDoubleEffectsTestUserFragment$ref: FragmentReference;
declare export opaque type useFragmentNodeReactDoubleEffectsTestUserFragment$fragmentType: useFragmentNodeReactDoubleEffectsTestUserFragment$ref;
export type useFragmentNodeReactDoubleEffectsTestUserFragment = {|
  +id: string,
  +name: ?string,
  +$refType: useFragmentNodeReactDoubleEffectsTestUserFragment$ref,
|};
export type useFragmentNodeReactDoubleEffectsTestUserFragment$data = useFragmentNodeReactDoubleEffectsTestUserFragment;
export type useFragmentNodeReactDoubleEffectsTestUserFragment$key = {
  +$data?: useFragmentNodeReactDoubleEffectsTestUserFragment$data,
  +$fragmentRefs: useFragmentNodeReactDoubleEffectsTestUserFragment$ref,
  ...
};
*/

var node/*: ReaderFragment*/ = {
  "argumentDefinitions": [],
  "kind": "Fragment",
  "metadata": null,
  "name": "useFragmentNodeReactDoubleEffectsTestUserFragment",
  "selections": [
    {
      "alias": null,
      "args": null,
      "kind": "ScalarField",
      "name": "id",
      "storageKey": null
    },
    {
      "alias": null,
      "args": null,
      "kind": "ScalarField",
      "name": "name",
      "storageKey": null
    }
  ],
  "type": "User",
  "abstractKey": null
};

if (__DEV__) {
  (node/*: any*/).hash = "c5a3cbb897157399807b77d5584a1c51";
}

module.exports = node;


text:
require "extend/ENV"

shared_examples EnvActivation do
  subject { env.extend(described_class) }

  let(:env) { {}.extend(EnvActivation) }

  it "supports switching compilers" do
    subject.clang
    expect(subject["LD"]).to be nil
    expect(subject["CC"]).to eq(subject["OBJC"])
  end

  describe "#with_build_environment" do
    it "restores the environment" do
      before = subject.dup

      subject.with_build_environment do
        subject["foo"] = "bar"
      end

      expect(subject["foo"]).to be nil
      expect(subject).to eq(before)
    end

    it "ensures the environment is restored" do
      before = subject.dup

      expect {
        subject.with_build_environment do
          subject["foo"] = "bar"
          raise StandardError
        end
      }.to raise_error(StandardError)

      expect(subject["foo"]).to be nil
      expect(subject).to eq(before)
    end

    it "returns the value of the block" do
      expect(subject.with_build_environment { 1 }).to eq(1)
    end

    it "does not mutate the interface" do
      expected = subject.methods

      subject.with_build_environment do
        expect(subject.methods).to eq(expected)
      end

      expect(subject.methods).to eq(expected)
    end
  end

  describe "#append" do
    it "appends to an existing key" do
      subject["foo"] = "bar"
      subject.append "foo", "1"
      expect(subject["foo"]).to eq("bar 1")
    end

    it "appends to an existing empty key" do
      subject["foo"] = ""
      subject.append "foo", "1"
      expect(subject["foo"]).to eq("1")
    end

    it "appends to a non-existant key" do
      subject.append "foo", "1"
      expect(subject["foo"]).to eq("1")
    end

    # NOTE: this may be a wrong behavior; we should probably reject objects that
    # do not respond to #to_str. For now this documents existing behavior.
    it "coerces a value to a string" do
      subject.append "foo", 42
      expect(subject["foo"]).to eq("42")
    end
  end

  describe "#prepend" do
    it "prepends to an existing key" do
      subject["foo"] = "bar"
      subject.prepend "foo", "1"
      expect(subject["foo"]).to eq("1 bar")
    end

    it "prepends to an existing empty key" do
      subject["foo"] = ""
      subject.prepend "foo", "1"
      expect(subject["foo"]).to eq("1")
    end

    it "prepends to a non-existant key" do
      subject.prepend "foo", "1"
      expect(subject["foo"]).to eq("1")
    end

    # NOTE: this may be a wrong behavior; we should probably reject objects that
    # do not respond to #to_str. For now this documents existing behavior.
    it "coerces a value to a string" do
      subject.prepend "foo", 42
      expect(subject["foo"]).to eq("42")
    end
  end

  describe "#append_path" do
    it "appends to a path" do
      subject.append_path "FOO", "/usr/bin"
      expect(subject["FOO"]).to eq("/usr/bin")

      subject.append_path "FOO", "/bin"
      expect(subject["FOO"]).to eq("/usr/bin#{File::PATH_SEPARATOR}/bin")
    end
  end

  describe "#prepend_path" do
    it "prepends to a path" do
      subject.prepend_path "FOO", "/usr/libexec"
      expect(subject["FOO"]).to eq("/usr/libexec")

      subject.prepend_path "FOO", "/usr"
      expect(subject["FOO"]).to eq("/usr#{File::PATH_SEPARATOR}/usr/libexec")
    end
  end

  describe "#compiler" do
    it "allows switching compilers" do
      [:clang, :gcc_4_2, :gcc_4_0].each do |compiler|
        subject.public_send(compiler)
        expect(subject.compiler).to eq(compiler)
      end
    end
  end

  example "deparallelize_block_form_restores_makeflags" do
    subject["MAKEFLAGS"] = "-j4"

    subject.deparallelize do
      expect(subject["MAKEFLAGS"]).to be nil
    end

    expect(subject["MAKEFLAGS"]).to eq("-j4")
  end

  describe "#clear_sensitive_environment!" do
    it "removes sensitive environment variables" do
      subject["SECRET_TOKEN"] = "password"
      subject.clear_sensitive_environment!
      expect(subject).not_to include("SECRET_TOKEN")
    end

    it "leaves non-sensitive environment variables alone" do
      subject["FOO"] = "bar"
      subject.clear_sensitive_environment!
      expect(subject["FOO"]).to eq "bar"
    end
  end
end

describe Stdenv do
  include_examples EnvActivation
end

describe Superenv do
  include_examples EnvActivation

  it "initializes deps" do
    expect(subject.deps).to eq([])
    expect(subject.keg_only_deps).to eq([])
  end

  describe "#cxx11" do
    it "raises an error when the compiler isn't supported" do
      %w[gcc gcc-4.7].each do |compiler|
        subject["HOMEBREW_CC"] = compiler

        expect { subject.cxx11 }
          .to raise_error(/The selected compiler doesn't support C\+\+11:/)

        expect(subject["HOMEBREW_CCCFG"]).to be nil
      end
    end

    it "supports gcc-5" do
      subject["HOMEBREW_CC"] = "gcc-5"
      subject.cxx11
      expect(subject["HOMEBREW_CCCFG"]).to include("x")
    end

    example "supports gcc-6" do
      subject["HOMEBREW_CC"] = "gcc-6"
      subject.cxx11
      expect(subject["HOMEBREW_CCCFG"]).to include("x")
    end

    it "supports clang" do
      subject["HOMEBREW_CC"] = "clang"
      subject.cxx11
      expect(subject["HOMEBREW_CCCFG"]).to include("x")
      expect(subject["HOMEBREW_CCCFG"]).to include("g")
    end
  end
end


text:
<?php
/**
 * The template for displaying the header
 *
 * Displays all of the head element and everything up until the "container" div.
 *
 * @package FoundationPress
 * @since FoundationPress 1.0.0
 */

?>
<!doctype html>
<html class="no-js" <?php language_attributes(); ?> >

		<meta charset="<?php bloginfo( 'charset' ); ?>" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<?php wp_head(); ?>

	<body <?php body_class(); ?>>
	<?php do_action( 'foundationpress_after_body' ); ?>

	<?php if ( get_theme_mod( 'wpt_mobile_menu_layout' ) == 'offcanvas' ) : ?>

		<?php get_template_part( 'template-parts/mobile-off-canvas' ); ?>
	<?php endif; ?>

	<?php do_action( 'foundationpress_layout_start' ); ?>

			<button class="menu-icon" type="button" data-toggle="mobile-menu"></button>

				<a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home"><?php bloginfo( 'name' ); ?>

		<?php do_action( 'foundationpress_after_header' );


text:
"""
Creates and manages scheduled AWS Lambdas
"""
from setuptools import find_packages, setup

dependencies = [
  'click>=6.2',
  'boto3>=1.2.6',
  'botocore>=1.4.0',
  'cookiecutter>=1.3.0'
]

setup(
    name='lambder',
    version='1.2.2',
    url='https://github.com/LeafSoftware/python-lambder',
    license='MIT',
    author='Chris Chalfant',
    author_email='cchalfant@leafsoftwaresolutions.com',
    description='Creates and manages scheduled AWS Lambdas',
    long_description=__doc__,
    packages=find_packages(exclude=['tests']),
    include_package_data=True,
    zip_safe=False,
    platforms='any',
    install_requires=dependencies,
    entry_points={
        'console_scripts': [
            'lambder = lambder.cli:cli',
        ],
    },
    classifiers=[
        # As from http://pypi.python.org/pypi?%3Aaction=list_classifiers
        # 'Development Status :: 1 - Planning',
        # 'Development Status :: 2 - Pre-Alpha',
        # 'Development Status :: 3 - Alpha',
        'Development Status :: 4 - Beta',
        # 'Development Status :: 5 - Production/Stable',
        # 'Development Status :: 6 - Mature',
        # 'Development Status :: 7 - Inactive',
        'Environment :: Console',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Operating System :: POSIX',
        'Operating System :: MacOS',
        'Operating System :: Unix',
        'Operating System :: Microsoft :: Windows',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 3',
        'Topic :: Software Development :: Libraries :: Python Modules',
    ]
)


text:
@interface SMMPushPublicNumberPageAction : NSObject<SMMURIActionHandlerProtocol>

@end


text:
namespace
{
	ostream& operator << (ostream& stream, SYSTEMTIME& time)
	{
		stream<<setw(4)<<setfill('0')<<time.wYear<<'.';
		stream<<setw(2)<<setfill('0')<<time.wMonth<<'.';
		stream<<setw(2)<<setfill('0')<<time.wDay;

		stream<<" ";

		stream<<setw(2)<<setfill('0')<<time.wHour<<':';
		stream<<setw(2)<<setfill('0')<<time.wMinute<<':';
		stream<<setw(2)<<setfill('0')<<time.wSecond<<".";
		stream<<setw(3)<<setfill('0')<<time.wMilliseconds;
		return stream;
	}
}
CLrpLogEntry::CLrpLogEntry(const uint64 id, const LrpLogEntryType type, const uint16 componentId, const uint16 methodId, const MemoryBuffer& buffer)
{
	m_data = new CLrpLogEntryData(id, type, componentId, methodId, buffer);
}
CLrpLogEntry::CLrpLogEntry(const CLrpLogEntry& entry) : m_data(entry.m_data)
{
	m_data->Acquire();
}
CLrpLogEntry::CLrpLogEntry(const uint64 id, const string& message)
{
	m_data = new CLrpLogEntryData(id, message);
}
CLrpLogEntry& CLrpLogEntry::operator = (const CLrpLogEntry& entry)
{
	if (m_data != entry.m_data)
	{
		m_data->Release();
		m_data = entry.m_data;
		m_data->Acquire();
	}
	return *this;
}
CLrpLogEntry::~CLrpLogEntry()
{
	m_data->Release();
}
LrpLogEntryType CLrpLogEntry::GetType() const
{
	return m_data->Type;
}
void CLrpLogEntry::Format(ostream& stream) const
{
	SYSTEMTIME systemTime;
	ZeroMemory(&systemTime, sizeof(systemTime));
	FileTimeToSystemTime(&(m_data->TimeStamp), &systemTime);
	stream<<systemTime;

	const uint64 id = m_data->ID;

	if (id > 0)
	{
		stream<<", ID = "<<id;
	}
	stream<<", TID = "<<m_data->ThreadId<<", "<<m_data->Type<<">: ";

	const LrpLogEntryType type = m_data->Type;

	try
	{
		DoFormat(type, id, stream);
	}
	catch (const std::exception& ex)
	{
		stream<<ex.what();
	}
}

void CLrpLogEntry::DoFormat(const LrpLogEntryType type, const uint64 id, ostream& stream) const
{
	if (LrpLogEntryType_Outgoing == type)
	{
		if (id > 0)
		{
			CLrpClientLogger logger(stream);
			logger.Format(m_data->ComponentId, m_data->MethodId, m_data->Buffer);
		}
		else
		{
			CLrpServerLogger logger(stream);
			logger.Format(m_data->ComponentId, m_data->MethodId, m_data->Buffer);
		}
	}
	else if (LrpLogEntryType_Incomming == type)
	{
		if (id > 0)
		{
			CLrpServerLogger logger(stream);
			logger.Format(m_data->ComponentId, m_data->MethodId, m_data->Buffer);
		}
		else
		{
			CLrpClientLogger logger(stream);
			logger.Format(m_data->ComponentId, m_data->MethodId, m_data->Buffer);
		}
	}
	else
	{
		string st = ReadAString(m_data->Buffer);
		stream<<st;
	}
}
ostream& operator << (ostream& stream, const CLrpLogEntry& arg)
{
	arg.Format(stream);
	return stream;
}


text:
module Azure::ServiceFabric::V6_3_0_9
  module Models
    #
    # Defines values for ServiceOperationName
    #
    module ServiceOperationName
      Unknown = "Unknown"
      None = "None"
      Open = "Open"
      ChangeRole = "ChangeRole"
      Close = "Close"
      Abort = "Abort"
    end
  end
end


text:
<?php

  class CloudinaryApiError extends Exception {}
  class CloudinaryApiNotFound extends CloudinaryApiError {}
  class CloudinaryApiNotAllowed extends CloudinaryApiError {}
  class CloudinaryApiAlreadyExists extends CloudinaryApiError {}
  class CloudinaryApiRateLimited extends CloudinaryApiError {}
  class CloudinaryApiBadRequest extends CloudinaryApiError {}
  class CloudinaryApiGeneralError extends CloudinaryApiError {}
  class CloudinaryApiAuthorizationRequired extends CloudinaryApiError {}
  class CloudinaryApiResponse extends ArrayObject {
    function __construct($response) {
        parent::__construct(CloudinaryApi::parse_json_response($response));
        $this->rate_limit_reset_at = strtotime($response->headers["X-FeatureRateLimit-Reset"]);
        $this->rate_limit_allowed = intval($response->headers["X-FeatureRateLimit-Limit"]);
        $this->rate_limit_remaining = intval($response->headers["X-FeatureRateLimit-Remaining"]);
    }
  }

class CloudinaryApi {
  static $CLOUDINARY_API_ERROR_CLASSES = array(
    400 => "CloudinaryApiBadRequest",
    401 => "CloudinaryApiAuthorizationRequired",
    403 => "CloudinaryApiNotAllowed",
    404 => "CloudinaryApiNotFound",
    409 => "CloudinaryApiAlreadyExists",
    420 => "CloudinaryApiRateLimited",
    500 => "CloudinaryApiGeneralError"
   );

  function resource_types($options=array()) {
    return $this->call_api("get", array("resources"), array(), $options);
  }

  function resources($options=array()) {
    $resource_type = Cloudinary::option_get($options, "resource_type", "image");
    $type = Cloudinary::option_get($options, "type");
    $uri = array("resources", $resource_type);
    if ($type) array_push($uri, $type);
    return $this->call_api("get", $uri, $this->only($options, array("next_cursor", "max_results", "prefix")), $options);
  }

  function resources_by_tag($tag, $options=array()) {
    $resource_type = Cloudinary::option_get($options, "resource_type", "image");
    $uri = array("resources", $resource_type, "tags", $tag);
    return $this->call_api("get", $uri, $this->only($options, array("next_cursor", "max_results")), $options);
  }

  function resource($public_id, $options=array()) {
    $resource_type = Cloudinary::option_get($options, "resource_type", "image");
    $type = Cloudinary::option_get($options, "type", "upload");
    $uri = array("resources", $resource_type, $type, $public_id);
    return $this->call_api("get", $uri, $this->only($options, array("exif", "colors", "faces", "image_metadata", "derived", "max_results")), $options);
  }

  function delete_resources($public_ids, $options=array()) {
    $resource_type = Cloudinary::option_get($options, "resource_type", "image");
    $type = Cloudinary::option_get($options, "type", "upload");
    $uri = array("resources", $resource_type, $type);
    return $this->call_api("delete", $uri, array_merge(array("public_ids"=>$public_ids), $this->only($options, array("keep_original"))), $options);
  }

  function delete_resources_by_prefix($prefix, $options=array()) {
    $resource_type = Cloudinary::option_get($options, "resource_type", "image");
    $type = Cloudinary::option_get($options, "type", "upload");
    $uri = array("resources", $resource_type, $type);
    return $this->call_api("delete", $uri, array_merge(array("prefix"=>$prefix), $this->only($options, array("keep_original"))), $options);
  }

  function delete_resources_by_tag($tag, $options=array()) {
    $resource_type = Cloudinary::option_get($options, "resource_type", "image");
    $uri = array("resources", $resource_type, "tags", $tag);
    return $this->call_api("delete", $uri, $this->only($options, array("keep_original")), $options);
  }

    function delete_derived_resources($derived_resource_ids, $options=array()) {
    $uri = array("derived_resources");
    return $this->call_api("delete", $uri, array("derived_resource_ids"=>$derived_resource_ids), $options);
  }

  function tags($options=array()) {
    $resource_type = Cloudinary::option_get($options, "resource_type", "image");
    $uri = array("tags", $resource_type);
    return $this->call_api("get", $uri, $this->only($options, array("next_cursor", "max_results", "prefix")), $options);
  }

  function transformations($options=array()) {
    return $this->call_api("get", array("transformations"), $this->only($options, array("next_cursor", "max_results")), $options);
  }

  function transformation($transformation, $options=array()) {
    $uri = array("transformations", $this->transformation_string($transformation));
    return $this->call_api("get", $uri, $this->only($options, array("max_results")), $options);
  }

  function delete_transformation($transformation, $options=array()) {
    $uri = array("transformations", $this->transformation_string($transformation));
    return $this->call_api("delete", $uri, array(), $options);
  }

  # updates - currently only supported update is the "allowed_for_strict" boolean flag
  function update_transformation($transformation, $updates=array(), $options=array()) {
    $uri = array("transformations", $this->transformation_string($transformation));
    return $this->call_api("put", $uri, $updates, $options);
  }

  function create_transformation($name, $definition, $options=array()) {
    $uri = array("transformations", $name);
    return $this->call_api("post", $uri, array("transformation"=>$this->transformation_string($definition)), $options);
  }

  protected function call_api($method, $uri, $params, &$options) {
    $prefix = Cloudinary::option_get($options, "upload_prefix", Cloudinary::config_get("upload_prefix", "https://api.cloudinary.com"));
    $cloud_name = Cloudinary::option_get($options, "cloud_name", Cloudinary::config_get("cloud_name"));
    if (!$cloud_name) throw new InvalidArgumentException("Must supply cloud_name");
    $api_key = Cloudinary::option_get($options, "api_key", Cloudinary::config_get("api_key"));
    if (!$api_key) throw new InvalidArgumentException("Must supply api_key");
    $api_secret = Cloudinary::option_get($options, "api_secret", Cloudinary::config_get("api_secret"));
    if (!$api_secret) throw new InvalidArgumentException("Must supply api_secret");
    $api_url = implode("/", array_merge(array($prefix, "v1_1", $cloud_name), $uri));
    $api_url .= "?" . preg_replace("/%5B\d+%5D/", "%5B%5D", http_build_query($params));
    $ch = curl_init($api_url);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, strtoupper($method));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 60);
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($ch, CURLOPT_USERPWD, $api_key.":".$api_secret);
    curl_setopt($ch, CURLOPT_CAINFO,realpath(dirname(__FILE__))."/cacert.pem");
    $response = $this->execute($ch);
    curl_close($ch);
    if ($response->responseCode == 200) {
      return new CloudinaryApiResponse($response);
    } else {
      $exception_class = Cloudinary::option_get(self::$CLOUDINARY_API_ERROR_CLASSES, $response->responseCode);
      if (!$exception_class) throw new CloudinaryApiGeneralError("Server returned unexpected status code - {$response->responseCode} - {$response->body}");
      $json = $this->parse_json_response($response);
      throw new $exception_class($json["error"]["message"]);
    }
  }

  # Based on http://snipplr.com/view/17242/
  protected function execute($ch) {
    $string = curl_exec($ch);
    $headers = array();
    $content = '';
    $str = strtok($string, "\n");
    $h = null;
    while ($str !== false) {
        if ($h and trim($str) === '') {
            $h = false;
            continue;
        }
        if ($h !== false and false !== strpos($str, ':')) {
            $h = true;
            list($headername, $headervalue) = explode(':', trim($str), 2);
            $headervalue = ltrim($headervalue);
            if (isset($headers[$headername]))
                $headers[$headername] .= ',' . $headervalue;
            else
                $headers[$headername] = $headervalue;
        }
        if ($h === false) {
            $content .= $str."\n";
        }
        $str = strtok("\n");
    }
    $result = new stdClass;
    $result->headers = $headers;
    $result->body = trim($content);
    $result->responseCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    return $result;
  }

  static function parse_json_response($response) {
    $result = json_decode($response->body, TRUE);
    if ($result == NULL) {
      $error = json_last_error();
      throw new CloudinaryApiGeneralError("Error parsing server response ({$response->responseCode}) - {$response->body}. Got - {$error}");
    }
    return $result;
  }

  protected function only(&$hash, $keys) {
    $result = array();
    foreach ($keys as $key) {
      if (isset($hash[$key])) $result[$key] = $hash[$key];
    }

    return $result;
  }

  protected function transformation_string($transformation) {
    return is_string($transformation) ? $transformation : Cloudinary::generate_transformation_string($transformation);
  }
}
?>


text:
package org.apache.log4j.filter;

import junit.framework.TestCase;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.spi.Filter;
import org.apache.log4j.spi.LoggingEvent;

/**
 * Unit tests for LevelMatchFilter.
 */
public class LevelMatchFilterTest extends TestCase {

    /**
     * Create new test instance.
     *
     * @param name test name.
     */
    public LevelMatchFilterTest(final String name) {
        super(name);
    }

    /**
     * Check that LevelMatchFilter.decide() returns Filter.ACCEPT when level matches.
     */
    public void test1() {
        LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger",
                Logger.getLogger(LevelMatchFilterTest.class),
                System.currentTimeMillis(), Level.INFO, "Hello, World", null);
        LevelMatchFilter filter = new LevelMatchFilter();
        filter.setLevelToMatch("info");
        filter.activateOptions();
        assertEquals(Filter.ACCEPT, filter.decide(event));
    }

    /**
     * Check that LevelMatchFilter.decide() returns Filter.DENY
     *    when level matches and acceptOnMatch = false.
     */
    public void test2() {
        LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger",
                Logger.getLogger(LevelMatchFilterTest.class),
                System.currentTimeMillis(), Level.INFO, "Hello, World", null);
        LevelMatchFilter filter = new LevelMatchFilter();
        filter.setLevelToMatch("info");
        filter.setAcceptOnMatch(false);
        filter.activateOptions();
        assertEquals(Filter.DENY, filter.decide(event));
    }

    /**
     * Check that LevelMatchFilter.decide() returns Filter.NEUTRAL
     *    when levelToMatch is unspecified.
     */
    public void test3() {
        LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger",
                Logger.getLogger(LevelMatchFilterTest.class),
                System.currentTimeMillis(), Level.INFO, "Hello, World", null);
        LevelMatchFilter filter = new LevelMatchFilter();
        filter.activateOptions();
        assertEquals(Filter.NEUTRAL, filter.decide(event));
    }

    /**
     * Check that LevelMatchFilter.decide() returns Filter.NEUTRAL
     *    when event level is higher than level to match.
     */
    public void test4() {
        LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger",
                Logger.getLogger(LevelMatchFilterTest.class),
                System.currentTimeMillis(), Level.INFO, "Hello, World", null);
        LevelMatchFilter filter = new LevelMatchFilter();
        filter.setLevelToMatch("debug");
        filter.activateOptions();
        assertEquals(Filter.NEUTRAL, filter.decide(event));
    }

    /**
     * Check that LevelMatchFilter.decide() returns Filter.NEUTRAL
     *    when event level is lower than level to match.
     */
    public void test5() {
        LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger",
                Logger.getLogger(LevelMatchFilterTest.class),
                System.currentTimeMillis(), Level.INFO, "Hello, World", null);
        LevelMatchFilter filter = new LevelMatchFilter();
        filter.setLevelToMatch("warn");
        filter.activateOptions();
        assertEquals(Filter.NEUTRAL, filter.decide(event));
    }
}


text:
package com.elmakers.mine.bukkit.block;

public abstract class BlockExtraData implements Cloneable {
    public abstract BlockExtraData clone();
}


text:
import { flattenDepth } from "../index";
export = flattenDepth;


text:
<?php
function addRating($name){
	$str = '
        <input type="radio" class="rating-input"
            id="rating-input-1-5_'.$name.'" name="rating_'.$name.'" value="5">

        <input type="radio" class="rating-input"
            id="rating-input-1-4_'.$name.'" name="rating_'.$name.'" value="4">

        <input type="radio" class="rating-input"
            id="rating-input-1-3_'.$name.'" name="rating_'.$name.'" value="3">

        <input type="radio" class="rating-input"
            id="rating-input-1-2_'.$name.'" name="rating_'.$name.'" value="2">

        <input type="radio" class="rating-input"
            id="rating-input-1-1_'.$name.'" name="rating_'.$name.'" value="1">

    ';
	return($str);
}
?>