text:
//
//  XMLHTTPRequest.cpp
//  XMLHttpRequest
//
//  Created by Zynga 2013
//
//  Heavy based on: https://github.com/funkaster/FakeWebGL/blob/master/FakeWebGL/WebGL/XMLHTTPRequest.cpp
//  Copyright (c) 2012 Rolando Abarca. All rights reserved.
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.

#include "XMLHTTPRequest.h"
#include <string>

using namespace std;

//#pragma mark - MinXmlHttpRequest

/**
 *  @brief Implementation for header retrieving.
 *  @param header
 */
void MinXmlHttpRequest::_gotHeader(string header) {
	// Get Header and Set StatusText
    // Split String into Tokens
    char * cstr = new char [header.length()+1];

    // check for colon.
    unsigned found_header_field = header.find_first_of(":");

    if (found_header_field != std::string::npos) {

        // Found a header field.
        string http_field;
        string http_value;

        http_field = header.substr(0,found_header_field);
        http_value = header.substr(found_header_field+1, header.length());

        // Get rid of all \n
        if (!http_value.empty() && http_value[http_value.size() - 1] == '\n') {
        	http_value.erase(http_value.size() - 1);
        }

        http_header[http_field] = http_value;

    }
    else {

        // Seems like we have the response Code! Parse it and check for it.
        char * pch;
        std::strcpy(cstr, header.c_str());

        pch = strtok(cstr," ");
        while (pch != NULL)
        {

            stringstream ss;
            string val;

            ss << pch;
            val = ss.str();
            unsigned found_http = val.find("HTTP");

            // Check for HTTP Header to set statusText
            if (found_http != std::string::npos) {

                stringstream mystream;

                // Get Response Status
                pch = strtok (NULL, " ");
                mystream << pch;

                pch = strtok (NULL, " ");
                mystream << " " << pch;

                statusText = mystream.str();

            }

            pch = strtok (NULL, " ");
        }

    }

}

/**
 *  @brief Set Request header for next call.
 *  @param field  Name of the Header to be set.
 *  @param value  Value of the Headerfield
 */
void MinXmlHttpRequest::_setRequestHeader(const char* field, const char* value) {

    stringstream header_s;
    stringstream value_s;
    string header;

    map<string, string>::iterator iter = request_header.find(field);

    // Concatenate values when header exists.
    if (iter != request_header.end() ) {

        value_s << iter->second << "," << value;

    }
    else {
        value_s << value;
    }

    request_header[field] = value_s.str();
    return;

}

/**
 * @brief  If headers has been set, pass them to curl.
 *
 */
void MinXmlHttpRequest::_setHttpRequestHeader() {

    std::vector<string> header;

    for (std::map<string,string>::iterator it = request_header.begin(); it != request_header.end(); ++it) {

        const char* first = it->first.c_str();
        const char* second = it->second.c_str();
        size_t len = sizeof(char) * (strlen(first) + 3 + strlen(second));
        char* test = (char*) malloc(len);
        memset(test, 0,len);

        strcpy(test, first);
        strcpy(test + strlen(first) , ": ");
        strcpy(test + strlen(first) + 2, second);

        header.push_back(test);

        free(test);

    }

    if (!header.empty()) {
        cc_request->setHeaders(header);
    }

}

/**
 *  @brief Callback for HTTPRequest. Handles the response and invokes Callback.
 *  @param sender   Object which initialized callback
 *  @param respone  Response object
 */
void MinXmlHttpRequest::handle_requestResponse(cocos2d::extension::CCHttpClient *sender, cocos2d::extension::CCHttpResponse *response) {

    if (0 != strlen(response->getHttpRequest()->getTag()))
    {
        CCLOG("%s completed", response->getHttpRequest()->getTag());
    }

    int statusCode = response->getResponseCode();
    char statusString[64] = {};
    sprintf(statusString, "HTTP Status Code: %d, tag = %s", statusCode, response->getHttpRequest()->getTag());

    if (!response->isSucceed())
    {
        CCLOG("response failed");
        CCLOG("error buffer: %s", response->getErrorBuffer());
        return;
    }

    // set header
    std::vector<char> *headers = response->getResponseHeader();

    char* concatHeader = (char*) malloc(headers->size() + 1);
    std::string header(headers->begin(), headers->end());
    strcpy(concatHeader, header.c_str());

    std::istringstream stream(concatHeader);
    std::string line;
    while(std::getline(stream, line)) {
        _gotHeader(line);
    }

    /** get the response data **/
    std::vector<char> *buffer = response->getResponseData();
    char* concatenated = (char*) malloc(buffer->size() + 1);
    std::string s2(buffer->begin(), buffer->end());

    strcpy(concatenated, s2.c_str());

    if (statusCode == 200)
    {
        //Succeeded
        status = 200;
        readyState = DONE;
        data << concatenated;
        dataSize = buffer->size();
    }
    else
    {
        status = 0;
    }
    // Free Memory.
    free((void*) concatHeader);
    free((void*) concatenated);

    js_proxy_t * p;
    void* ptr = (void*)this;
    p = jsb_get_native_proxy(ptr);

    if(p){
        JSContext* cx = ScriptingCore::getInstance()->getGlobalContext();

        if (onreadystateCallback) {
            //JS_IsExceptionPending(cx) && JS_ReportPendingException(cx);
            jsval fval = OBJECT_TO_JSVAL(onreadystateCallback);
            jsval out;
            JS_CallFunctionValue(cx, NULL, fval, 0, NULL, &out);
        }

    }

}
/**
 * @brief   Send out request and fire callback when done.
 * @param cx    Javascript context
 */
void MinXmlHttpRequest::_sendRequest(JSContext *cx) {

    cc_request->setResponseCallback(this, httpresponse_selector(MinXmlHttpRequest::handle_requestResponse));
    cocos2d::extension::CCHttpClient::getInstance()->send(cc_request);
    cc_request->release();

}

/**
 * @brief  Constructor initializes cchttprequest and stuff
 *
 */
MinXmlHttpRequest::MinXmlHttpRequest() : onreadystateCallback(NULL), isNetwork(true) {

    http_header.clear();
    request_header.clear();
    withCredentialsValue = true;
    cx = ScriptingCore::getInstance()->getGlobalContext();
    cc_request = new cocos2d::extension::CCHttpRequest();
}

/**
 * @brief Destructor cleans up cc_request and stuff
 *
 */
MinXmlHttpRequest::~MinXmlHttpRequest() {

    http_header.clear();
    request_header.clear();

    if (onreadystateCallback != NULL)
    {
        JS_RemoveObjectRoot(cx, &onreadystateCallback);
    }

    if (cc_request) {
        // We don't need to release cc_request here since it will be released in the http callback.
//        cc_request->release();
    }

}

/**
 *  @brief Initialize Object and needed properties.
 *
 */
JS_BINDED_CLASS_GLUE_IMPL(MinXmlHttpRequest);

/**
 *  @brief Implementation for the Javascript Constructor
 *
 */
JS_BINDED_CONSTRUCTOR_IMPL(MinXmlHttpRequest)
{
    MinXmlHttpRequest* req = new MinXmlHttpRequest();
    req->autorelease();

    js_proxy_t *p;
    jsval out;

    JSObject *obj = JS_NewObject(cx, &MinXmlHttpRequest::js_class, MinXmlHttpRequest::js_proto, MinXmlHttpRequest::js_parent);

    if (obj) {
        JS_SetPrivate(obj, req);
        out = OBJECT_TO_JSVAL(obj);
    }

    JS_SET_RVAL(cx, vp, out);
    p =jsb_new_proxy(req, obj);

    JS_AddNamedObjectRoot(cx, &p->obj, "XMLHttpRequest");
    return JS_TRUE;
}

/**
 *  @brief  get Callback function for Javascript
 *
 */
JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, onreadystatechange)
{
    if (onreadystateCallback) {

        JSString *tmpstr = JS_NewStringCopyZ(cx, "1");
        jsval tmpval = STRING_TO_JSVAL(tmpstr);
        JS_SetProperty(cx, onreadystateCallback, "readyState", &tmpval);

        jsval out = OBJECT_TO_JSVAL(onreadystateCallback);
        vp.set(out);

    } else {
        vp.set(JSVAL_NULL);
    }
    return JS_TRUE;
}

/**
 *  @brief Set Callback function coming from Javascript
 *
 *
 */
JS_BINDED_PROP_SET_IMPL(MinXmlHttpRequest, onreadystatechange)
{
    jsval callback = vp.get();
    if (callback != JSVAL_NULL) {
        onreadystateCallback = JSVAL_TO_OBJECT(callback);
        JS_AddNamedObjectRoot(cx, &onreadystateCallback, "onreadystateCallback");
    }
    return JS_TRUE;
}

/**
 *  @brief upload getter - TODO
 *
 *  Placeholder for further implementations!!
 */
JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, upload)
{
    vp.set(JSVAL_NULL);
    return JS_TRUE;
}

/**
 *  @brief upload setter - TODO
 *
 *  Placeholder for further implementations
 */
JS_BINDED_PROP_SET_IMPL(MinXmlHttpRequest, upload)
{
    vp.set(JSVAL_NULL);
    return JS_TRUE;
}

/**
 *  @brief timeout getter - TODO
 *
 *  Placeholder for further implementations
 */
JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, timeout)
{
    vp.set(INT_TO_JSVAL(timeout));
    return JS_TRUE;
}

/**
 *  @brief timeout setter - TODO
 *
 *  Placeholder for further implementations
 */
JS_BINDED_PROP_SET_IMPL(MinXmlHttpRequest, timeout)
{
    jsval timeout_ms = vp.get();

    timeout = JSVAL_TO_INT(timeout_ms);
    //curl_easy_setopt(curlHandle, CURLOPT_CONNECTTIMEOUT_MS, timeout);
    return JS_TRUE;

}

/**
 *  @brief  get response type for actual XHR
 *
 *
 */
JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, responseType)
{
    JSString* str = JS_NewStringCopyN(cx, "", 0);
    vp.set(STRING_TO_JSVAL(str));
    return JS_TRUE;
}

/**
 *  @brief  responseXML getter - TODO
 *
 *  Placeholder for further implementation.
 */
JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, responseXML)
{
    vp.set(JSVAL_NULL);
    return JS_TRUE;
}

/**
 *  @brief  set response type for actual XHR
 *
 *
 */
JS_BINDED_PROP_SET_IMPL(MinXmlHttpRequest, responseType)
{
    jsval type = vp.get();
    if (type.isString()) {
        JSString* str = type.toString();
        JSBool equal;
        JS_StringEqualsAscii(cx, str, "text", &equal);
        if (equal) {
            responseType = kRequestResponseTypeString;
            return JS_TRUE;
        }
        JS_StringEqualsAscii(cx, str, "arraybuffer", &equal);
        if (equal) {
            responseType = kRequestResponseTypeArrayBuffer;
            return JS_TRUE;
        }
        JS_StringEqualsAscii(cx, str, "json", &equal);
        if (equal) {
            responseType = kRequestResponseTypeJSON;
            return JS_TRUE;
        }
        // ignore the rest of the response types for now
        return JS_TRUE;
    }
    JS_ReportError(cx, "Invalid response type");
    return JS_FALSE;
}

/**
 * @brief get readyState for actual XHR
 *
 *
 */
JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, readyState)
{
    vp.set(INT_TO_JSVAL(readyState));
    return JS_TRUE;
}

/**
 *  @brief get status for actual XHR
 *
 *
 */
JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, status)
{
    vp.set(INT_TO_JSVAL(status));
    return JS_TRUE;
}

/**
 *  @brief get statusText for actual XHR
 *
 *
 */
JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, statusText)
{
    JSString* str = JS_NewStringCopyZ(cx, statusText.c_str());//, dataSize);

    if (str) {
        vp.set(STRING_TO_JSVAL(str));
        return JS_TRUE;
    } else {
        JS_ReportError(cx, "Error trying to create JSString from data");
        return JS_FALSE;
    }
}

/**
 *  @brief  get value of withCredentials property.
 *
 */
JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, withCredentials)
{
    vp.set(BOOLEAN_TO_JSVAL(withCredentialsValue));
    return JS_TRUE;
}

/**
 *  withCredentials - set value of withCredentials property.
 *
 */
JS_BINDED_PROP_SET_IMPL(MinXmlHttpRequest, withCredentials)
{
    jsval credential = vp.get();
    if (credential != JSVAL_NULL) {
        withCredentialsValue = JSVAL_TO_BOOLEAN(credential);
    }

    return JS_TRUE;
}

/**
 *  @brief  get (raw) responseText
 *
 */
JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, responseText)
{
    JSString* str = JS_NewStringCopyZ(cx, data.str().c_str());//, dataSize);

    if (str) {
        vp.set(STRING_TO_JSVAL(str));
        //JS_ReportError(cx, "Result: %s", data.str().c_str());
        return JS_TRUE;
    } else {
        JS_ReportError(cx, "Error trying to create JSString from data");
        return JS_FALSE;
    }
}

/**
 *  @brief get response of latest XHR
 *
 */
JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, response)
{

    if (responseType == kRequestResponseTypeJSON) {
        jsval outVal;

        JSString* str = JS_NewStringCopyZ(cx, data.str().c_str());//, dataSize);
        if (JS_ParseJSON(cx, JS_GetStringCharsZ(cx, str), dataSize, &outVal)) {

            vp.set(outVal);
            return JS_TRUE;
        }
    } else if (responseType == kRequestResponseTypeArrayBuffer) {
        JSObject* tmp = JS_NewArrayBuffer(cx, dataSize);
        uint8_t* tmpData = JS_GetArrayBufferData(tmp);
        data.read((char*)tmpData, dataSize);
        jsval outVal = OBJECT_TO_JSVAL(tmp);

        vp.set(outVal);
        return JS_TRUE;
    }
    // by default, return text
    return _js_get_responseText(cx, id, vp);
}

/**
 *  @brief initialize new xhr.
 *
 */
JS_BINDED_FUNC_IMPL(MinXmlHttpRequest, open)
{

    if (argc >= 2) {
        jsval* argv = JS_ARGV(cx, vp);
        const char* method;
        const char* urlstr;
        JSBool async = true;
        JSString* jsMethod = JS_ValueToString(cx, argv[0]);
        JSString* jsURL = JS_ValueToString(cx, argv[1]);

        if (argc > 2) {
            JS_ValueToBoolean(cx, argv[2], &async);
        }

        JSStringWrapper w1(jsMethod);
        JSStringWrapper w2(jsURL);
        method = w1;
        urlstr = w2;

        url = urlstr;
        meth = method;
        readyState = 1;
        isAsync = async;

        if (url.length() > 5 && url.compare(url.length() - 5, 5, ".json") == 0) {
            responseType = kRequestResponseTypeJSON;
        }

        if (meth.compare("post") == 0 || meth.compare("POST") == 0) {
            cc_request->setRequestType(cocos2d::extension::CCHttpRequest::kHttpPost);
        }
        else {
            cc_request->setRequestType(cocos2d::extension::CCHttpRequest::kHttpGet);
        }

        cc_request->setUrl(url.c_str());

        isNetwork = true;
        readyState = OPENED;

        return JS_TRUE;
    }

    JS_ReportError(cx, "invalid call: %s", __FUNCTION__);
    return JS_FALSE;

}

/**
 *  @brief  send xhr
 *
 */
JS_BINDED_FUNC_IMPL(MinXmlHttpRequest, send)
{

    JSString *str = NULL;
    std::string data;

    // Clean up header map. New request, new headers!
    http_header.clear();
    if (argc == 1) {
        if (!JS_ConvertArguments(cx, argc, JS_ARGV(cx, vp), "S", &str)) {
            return JS_FALSE;
        };
        JSStringWrapper strWrap(str);
        data = strWrap.get();
    }

    if (data.length() > 0 && (meth.compare("post") == 0 || meth.compare("POST") == 0)) {
        cc_request->setRequestData(data.c_str(), data.length());
    }

    _setHttpRequestHeader();
    _sendRequest(cx);

    return JS_TRUE;
}

/**
 *  @brief abort function Placeholder!
 *
 */
JS_BINDED_FUNC_IMPL(MinXmlHttpRequest, abort)
{
    return JS_TRUE;
}

/**
 *  @brief Get all response headers as a string
 *
 */
JS_BINDED_FUNC_IMPL(MinXmlHttpRequest, getAllResponseHeaders)
{
    stringstream responseheaders;
    string responseheader;

    for (std::map<string,string>::iterator it=http_header.begin(); it!=http_header.end(); ++it) {
        responseheaders << it->first << ": " << it->second << "\n";
    }

    responseheader = responseheaders.str();

    JSString* str = JS_NewStringCopyZ(cx, responseheader.c_str());

    if (str) {
        JS_SET_RVAL(cx, vp, STRING_TO_JSVAL(str));
        return JS_TRUE;
    } else {
        JS_ReportError(cx, "Error trying to create JSString from data");
        return JS_FALSE;
    }

    return JS_TRUE;
}

/**
 *  @brief Get all response headers as a string
 *
 */
JS_BINDED_FUNC_IMPL(MinXmlHttpRequest, getResponseHeader)
{

    JSString *header_value;

    if (!JS_ConvertArguments(cx, argc, JS_ARGV(cx, vp), "S", &header_value)) {
        return JS_FALSE;
    };

    std::string data;
    JSStringWrapper strWrap(header_value);
    data = strWrap.get();

    stringstream streamdata;

    streamdata << data;

    string value = streamdata.str();

    map<string, string>::iterator iter = http_header.find(value);
    if (iter != http_header.end() ) {

        JSString *js_ret_val = JS_NewStringCopyZ(cx, iter->second.c_str());

        // iter->second
        JS_SET_RVAL(cx, vp, STRING_TO_JSVAL(js_ret_val));
        return JS_TRUE;
    }
    else {
        JS_SET_RVAL(cx, vp, JSVAL_NULL);
        return JS_TRUE;
    }

}

/**
 *  @brief Set the given Fields to request Header.
 *
 *
 */
JS_BINDED_FUNC_IMPL(MinXmlHttpRequest, setRequestHeader)
{

    if (argc >= 2) {
        jsval* argv = JS_ARGV(cx, vp);
        const char* field;
        const char* value;

        JSString* jsField = JS_ValueToString(cx, argv[0]);
        JSString* jsValue = JS_ValueToString(cx, argv[1]);

        JSStringWrapper w1(jsField);
        JSStringWrapper w2(jsValue);
        field = w1;
        value = w2;

        // Populate the request_header map.
        _setRequestHeader(field, value);

        return JS_TRUE;
    }

    return JS_FALSE;

}

/**
 * @brief overrideMimeType function - TODO!
 *
 * Just a placeholder for further implementations.
 */
JS_BINDED_FUNC_IMPL(MinXmlHttpRequest, overrideMimeType)
{
    return JS_TRUE;
}

/**
 *  @brief destructor for Javascript
 *
 */
static void basic_object_finalize(JSFreeOp *freeOp, JSObject *obj) {
    CCLOG("basic_object_finalize %p ...", obj);
}

/**
 *  @brief Register XMLHttpRequest to be usable in JS and add properties and Mehtods.
 *  @param cx   Global Spidermonkey JS Context.
 *  @param global   Global Spidermonkey Javascript object.
 */
void MinXmlHttpRequest::_js_register(JSContext *cx, JSObject *global) {

    JSClass js_class = {
        "XMLHttpRequest", JSCLASS_HAS_PRIVATE, JS_PropertyStub,
        JS_PropertyStub, JS_PropertyStub, JS_StrictPropertyStub,
        JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub,
        basic_object_finalize, JSCLASS_NO_OPTIONAL_MEMBERS
    };

    MinXmlHttpRequest::js_class = js_class;
    static JSPropertySpec props[] = {
        JS_BINDED_PROP_DEF_ACCESSOR(MinXmlHttpRequest, onreadystatechange),
        JS_BINDED_PROP_DEF_ACCESSOR(MinXmlHttpRequest, responseType),
        JS_BINDED_PROP_DEF_ACCESSOR(MinXmlHttpRequest, withCredentials),
        JS_BINDED_PROP_DEF_GETTER(MinXmlHttpRequest, readyState),
        JS_BINDED_PROP_DEF_GETTER(MinXmlHttpRequest, status),
        JS_BINDED_PROP_DEF_GETTER(MinXmlHttpRequest, statusText),
        JS_BINDED_PROP_DEF_GETTER(MinXmlHttpRequest, responseText),
        JS_BINDED_PROP_DEF_GETTER(MinXmlHttpRequest, responseXML),
        JS_BINDED_PROP_DEF_GETTER(MinXmlHttpRequest, response),
        {0, 0, 0, 0, 0}
    };

    static JSFunctionSpec funcs[] = {
        JS_BINDED_FUNC_FOR_DEF(MinXmlHttpRequest, open),
        JS_BINDED_FUNC_FOR_DEF(MinXmlHttpRequest, abort),
        JS_BINDED_FUNC_FOR_DEF(MinXmlHttpRequest, send),
        JS_BINDED_FUNC_FOR_DEF(MinXmlHttpRequest, setRequestHeader),
        JS_BINDED_FUNC_FOR_DEF(MinXmlHttpRequest, getAllResponseHeaders),
        JS_BINDED_FUNC_FOR_DEF(MinXmlHttpRequest, getResponseHeader),
        JS_BINDED_FUNC_FOR_DEF(MinXmlHttpRequest, overrideMimeType),
        JS_FS_END
    };

    MinXmlHttpRequest::js_parent = NULL;
    MinXmlHttpRequest::js_proto = JS_InitClass(cx, global, NULL, &MinXmlHttpRequest::js_class , MinXmlHttpRequest::_js_constructor, 0, props, funcs, NULL, NULL);

}


text:
var fs = require('fs');
var path = require('path');
var RSVP = require('rsvp');
var rimraf = RSVP.denodeify(require('rimraf'));
var mapSeries = require('promise-map-series');
var quickTemp = require('quick-temp')
var helpers = require('broccoli-kitchen-sink-helpers');
var symlinkOrCopy = require('symlink-or-copy');
var generateRandomString = require('./lib/generate-random-string');
var CoreObject = require("core-object");

function CachingWriter (inputTrees, options) {
  if (!(this instanceof CachingWriter)) return new CachingWriter(inputTrees, options);

  this._inputTreeCacheHash = [];
  this._shouldBeIgnoredCache = Object.create(null);
  this._destDir = path.resolve(path.join('tmp', 'caching-writer-dest-dir_' + generateRandomString(6) + '.tmp'));

  options = options || {};

  for (var key in options) {
    if (options.hasOwnProperty(key)) {
      this[key] = options[key];
    }
  }

  if (Array.isArray(inputTrees)) {
    if (this.enforceSingleInputTree) {
      throw new Error('You passed an array of input trees, but only a single tree is allowed.');
    }

    this.inputTrees = inputTrees;
  } else {
    this.inputTrees = [inputTrees];
  }

  if (this.filterFromCache === undefined) {
    this.filterFromCache = {};
  }

  if (this.filterFromCache.include === undefined) {
    this.filterFromCache.include = [];
  }

  if (this.filterFromCache.exclude === undefined) {
    this.filterFromCache.exclude = [];
  }

  if (!Array.isArray(this.filterFromCache.include)) {
    throw new Error("Invalid filterFromCache.include option, it must be an array or undefined.")
  }

  if (!Array.isArray(this.filterFromCache.exclude)) {
    throw new Error("Invalid filterFromCache.exclude option, it must be an array or undefined.")
  }
};
CachingWriter.__proto__ = CoreObject;
CachingWriter.prototype.constructor = CachingWriter;

CachingWriter.prototype.enforceSingleInputTree = false;

CachingWriter.prototype.getCacheDir = function () {
  return quickTemp.makeOrReuse(this, 'tmpCacheDir');
};

CachingWriter.prototype.getCleanCacheDir = function () {
  return quickTemp.makeOrRemake(this, 'tmpCacheDir');
};

CachingWriter.prototype.read = function (readTree) {
  var self = this;

  return mapSeries(this.inputTrees, readTree)
    .then(function(inputPaths) {
      var inputTreeHashes = [];
      var invalidateCache = false;
      var keys, dir, updateCacheResult;

      for (var i = 0, l = inputPaths.length; i < l; i++) {
        dir = inputPaths[i];
        keys = self.keysForTree(dir);
        inputTreeHashes[i] = helpers.hashStrings(keys);

        if (self._inputTreeCacheHash[i] !== inputTreeHashes[i]) {
          invalidateCache = true;
        }
      }

      if (invalidateCache) {
        var updateCacheSrcArg = self.enforceSingleInputTree ? inputPaths[0] : inputPaths;
        updateCacheResult = self.updateCache(updateCacheSrcArg, self.getCleanCacheDir());

        self._inputTreeCacheHash = inputTreeHashes;
      }

      return updateCacheResult;
    })
    .then(function() {
      return rimraf(self._destDir);
    })
    .then(function() {
      symlinkOrCopy.sync(self.getCacheDir(), self._destDir);
    })
    .then(function() {
      return self._destDir;
    });
};

CachingWriter.prototype.cleanup = function () {
  quickTemp.remove(this, 'tmpCacheDir');

  // sadly we must use sync removal for now
  rimraf.sync(this._destDir);
};

CachingWriter.prototype.updateCache = function (srcDir, destDir) {
  throw new Error('You must implement updateCache.');
};

// Takes in a path and { include, exclude }. Tests the path using regular expressions and
// returns true if the path does not match any exclude patterns AND matches atleast
// one include pattern.
CachingWriter.prototype.shouldBeIgnored = function (fullPath) {
  if (this._shouldBeIgnoredCache[fullPath] !== undefined) {
    return this._shouldBeIgnoredCache[fullPath];
  }

  var excludePatterns = this.filterFromCache.exclude;
  var includePatterns = this.filterFromCache.include;
  var i = null;

  // Check exclude patterns
  for (i = 0; i < excludePatterns.length; i++) {
    // An exclude pattern that returns true should be ignored
    if (excludePatterns[i].test(fullPath) === true) {
      return this._shouldBeIgnoredCache[fullPath] = true;
    }
  }

  // Check include patterns
  if (includePatterns !== undefined && includePatterns.length > 0) {
    for (i = 0; i < includePatterns.length; i++) {
      // An include pattern that returns true (and wasn't excluded at all)
      // should _not_ be ignored
      if (includePatterns[i].test(fullPath) === true) {
        return this._shouldBeIgnoredCache[fullPath] = false;
      }
    }

    // If no include patterns were matched, ignore this file.
    return this._shouldBeIgnoredCache[fullPath] = true;
  }

  // Otherwise, don't ignore this file
  return this._shouldBeIgnoredCache[fullPath] = false;
}

CachingWriter.prototype.keysForTree = function (fullPath, initialRelativePath) {
  var relativePath   = initialRelativePath || '.'
  var stats;
  var statKeys;

  try {
    stats = fs.statSync(fullPath);
  } catch (err) {
    console.warn('Warning: failed to stat ' + fullPath);
    // fullPath has probably ceased to exist. Leave `stats` undefined and
    // proceed hashing.
  }
  var childKeys = [];
  if (stats) {
    statKeys = ['stats', stats.mode];
  } else {
    statKeys = ['stat failed'];
  }
  if (stats && stats.isDirectory()) {
    var fileIdentity = stats.dev + '\x00' + stats.ino;
    var entries;
    try {
      entries = fs.readdirSync(fullPath).sort();
    } catch (err) {
      console.warn('Warning: Failed to read directory ' + fullPath);
      console.warn(err.stack);
      childKeys = ['readdir failed'];
      // That's all there is to say about this directory.
    }
    if (entries != null) {
      for (var i = 0; i < entries.length; i++) {

        var keys = this.keysForTree(
          path.join(fullPath, entries[i]),
          path.join(relativePath, entries[i])
        );
        childKeys = childKeys.concat(keys);
      }
    }
  } else if (stats && stats.isFile()) {
    if (this.shouldBeIgnored(fullPath)) {
      return [];
    }
    statKeys.push(stats.mtime.getTime(), stats.size);
  }

  // Perhaps we should not use basename to infer the file name
  return ['path', relativePath]
    .concat(statKeys)
    .concat(childKeys);
}

module.exports = CachingWriter;

redpajama_set_name: RedPajamaGithub


text:
package camelinaction;

import java.util.concurrent.TimeUnit;

import org.apache.camel.Exchange;
import org.apache.camel.builder.NotifyBuilder;
import org.apache.camel.test.spring.CamelSpringTestSupport;
import org.junit.Test;
import org.springframework.context.support.AbstractXmlApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Testing how to stop a route when its done using on completion.
 * <p/>
 * The route is defined in Spring XML file, see the <tt>SpringManualRouteWithOnCompletionTest.xml</tt> file.
 */
public class SpringManualRouteWithOnCompletionTest extends CamelSpringTestSupport {

    @Override
    protected AbstractXmlApplicationContext createApplicationContext() {
        return new ClassPathXmlApplicationContext("META-INF/spring/SpringManualRouteWithOnCompletionTest.xml");
    }

    @Override
    public void setUp() throws Exception {
        deleteDirectory("target/inventory");
        super.setUp();
    }

    @Test
    public void testManualRouteWithOnCompletion() throws Exception {
        // notify us when the exchange is done
        NotifyBuilder notify = new NotifyBuilder(context).whenDone(1).create();

        // we actually do not need to use a mock but since we wanted to show the trick
        // in the createRouteBuilders we do both. We could just have relied on using
        // the NotifyBuilder to signal when the exchange is done
        getMockEndpoint("mock:update").expectedMessageCount(2);

        // route should be stopped at startup
        assertTrue("Route should be stopped at startup", context.getRouteStatus("manual").isStopped());

        // then start the route
        context.startRoute("manual");

        // send a file which is picked up and processed
        String input = "4444,57123,Bumper,50\n4444,57124,Fender,87";
        template.sendBodyAndHeader("file:target/inventory/manual", input, Exchange.FILE_NAME, "manual.csv");

        // assert we got the message
        assertMockEndpointsSatisfied();

        // wait for the route to be done
        notify.matches(5, TimeUnit.SECONDS);

        // we gotta wait just a little extra to stop
        Thread.sleep(5000);

        // it should have stopped itself
        assertTrue("Route should be stopped", context.getRouteStatus("manual").isStopped());
    }

}


text:
       html_favicon_url = "http://www.rust-lang.org/favicon.ico",
       html_root_url = "http://doc.rust-lang.org/nightly/")]

#![no_std]
#![allow(unknown_features)]
#![allow(unstable)]
#![feature(lang_items, unsafe_destructor)]
#![feature(box_syntax)]
#![feature(optin_builtin_traits)]
#![allow(unknown_features)] #![feature(int_uint)]

#[macro_use]
extern crate core;

#[cfg(all(not(feature = "external_funcs"), not(feature = "external_crate")))]
extern crate libc;

// Allow testing this library

#[cfg(test)] #[macro_use] extern crate std;
#[cfg(test)] #[macro_use] extern crate log;

// Heaps provided for low-level allocation strategies

pub mod heap;

// Primitive types using the heaps above

#[cfg(not(test))]
pub mod boxed;
pub mod arc;
pub mod rc;

/// Common out-of-memory routine
#[cold]
#[inline(never)]
pub fn oom() -> ! {
    // FIXME(#14674): This really needs to do something other than just abort
    //                here, but any printing done must be *guaranteed* to not
    //                allocate.
    unsafe { core::intrinsics::abort() }
}

// FIXME(#14344): When linking liballoc with libstd, this library will be linked
//                as an rlib (it only exists as an rlib). It turns out that an
//                optimized standard library doesn't actually use *any* symbols
//                from this library. Everything is inlined and optimized away.
//                This means that linkers will actually omit the object for this
//                file, even though it may be needed in the future.
//
//                To get around this for now, we define a dummy symbol which
//                will never get inlined so the stdlib can call it. The stdlib's
//                reference to this symbol will cause this library's object file
//                to get linked in to libstd successfully (the linker won't
//                optimize it out).
#[doc(hidden)]
pub fn fixme_14344_be_sure_to_link_to_collections() {}

#[cfg(not(test))]
#[doc(hidden)]
mod std {
    pub use core::fmt;
    pub use core::option;
}


text:
<?php

	if ( ! class_exists( 'AvadaRedux_Validation_str_replace' ) ) {
		class AvadaRedux_Validation_str_replace {

			/**
			 * Field Constructor.
			 * Required - must call the parent constructor, then assign field and value to vars, and obviously call the render field function
			 *
			 * @since AvadaReduxFramework 1.0.0
			 */
			function __construct( $parent, $field, $value, $current ) {

				$this->parent  = $parent;
				$this->field   = $field;
				$this->value   = $value;
				$this->current = $current;

				$this->validate();
			} //function

			/**
			 * Field Render Function.
			 * Takes the vars and validates them
			 *
			 * @since AvadaReduxFramework 1.0.0
			 */
			function validate() {

				$this->value = str_replace( $this->field['str']['search'], $this->field['str']['replacement'], $this->value );
			} //function
		} //class
	}


text:
package bt.data;

/**
 * Traverses a data range on a per-unit basis.
 *
 * @since 1.2
 */
public interface DataRangeVisitor {

    /**
     * Visit (a part of) a file in a range of files
     * @param unit A storage unit
     * @param off Offset that designates the beginning of this chunk's part in the file, inclusive;
     *            visitor must not access the file before this index
     * @param lim Limit that designates the end of this chunk's part in the file, exclusive;
     *            visitor must not access the file at or past this index
     *            (i.e. the limit does not belong to this chunk)
     * @return true if next file should be visited; false to stop
     *
     * @since 1.2
     */
    boolean visitUnit(StorageUnit unit, long off, long lim);
}


text:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { observer, PropTypes as MobxPropTypes } from 'mobx-react';

import TabBarSortableList from './TabBarSortableList';

export default @observer class TabBar extends Component {
  static propTypes = {
    services: MobxPropTypes.arrayOrObservableArray.isRequired,
    setActive: PropTypes.func.isRequired,
    openSettings: PropTypes.func.isRequired,
    enableToolTip: PropTypes.func.isRequired,
    disableToolTip: PropTypes.func.isRequired,
    reorder: PropTypes.func.isRequired,
    reload: PropTypes.func.isRequired,
    toggleNotifications: PropTypes.func.isRequired,
    toggleAudio: PropTypes.func.isRequired,
    deleteService: PropTypes.func.isRequired,
    updateService: PropTypes.func.isRequired,
    showMessageBadgeWhenMutedSetting: PropTypes.bool.isRequired,
    showMessageBadgesEvenWhenMuted: PropTypes.bool.isRequired,
  };

  onSortEnd = ({ oldIndex, newIndex }) => {
    const {
      enableToolTip,
      reorder,
    } = this.props;

    enableToolTip();
    reorder({ oldIndex, newIndex });
  };

  shouldPreventSorting = event => event.target.tagName !== 'LI';

  toggleService = ({ serviceId, isEnabled }) => {
    const { updateService } = this.props;

    if (serviceId) {
      updateService({
        serviceId,
        serviceData: {
          isEnabled,
        },
        redirect: false,
      });
    }
  };

  disableService({ serviceId }) {
    this.toggleService({ serviceId, isEnabled: false });
  }

  enableService({ serviceId }) {
    this.toggleService({ serviceId, isEnabled: true });
  }

  render() {
    const {
      services,
      setActive,
      openSettings,
      disableToolTip,
      reload,
      toggleNotifications,
      toggleAudio,
      deleteService,
      showMessageBadgeWhenMutedSetting,
      showMessageBadgesEvenWhenMuted,
    } = this.props;

    return (
      <div>
        <TabBarSortableList
          services={services}
          setActive={setActive}
          onSortEnd={this.onSortEnd}
          onSortStart={disableToolTip}
          shouldCancelStart={this.shouldPreventSorting}
          reload={reload}
          toggleNotifications={toggleNotifications}
          toggleAudio={toggleAudio}
          deleteService={deleteService}
          disableService={args => this.disableService(args)}
          enableService={args => this.enableService(args)}
          openSettings={openSettings}
          distance={20}
          axis="y"
          lockAxis="y"
          helperClass="is-reordering"
          showMessageBadgeWhenMutedSetting={showMessageBadgeWhenMutedSetting}
          showMessageBadgesEvenWhenMuted={showMessageBadgesEvenWhenMuted}
        />
      </div>
    );
  }
}


text:
var gulp = require('gulp');

// Include Our Plugins
var jshint = require('gulp-jshint');
var sass = require('gulp-sass');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');

// Lint Task
gulp.task('lint', function() {
    return gulp.src('js/*.js')
        .pipe(jshint())
        .pipe(jshint.reporter('default'));
});

// Compile Our Sass
gulp.task('sass', function() {
    return gulp.src('scss/*.scss')
        .pipe(sass())
        .pipe(gulp.dest('css'));
});

// Concatenate & Minify JS
gulp.task('scripts', function() {
    return gulp.src('javascript/*.js')
        .pipe(concat('all.js'))
        .pipe(gulp.dest('dist'))
        .pipe(rename('all.min.js'))
        .pipe(uglify())
        .pipe(gulp.dest('dist'));
});

// Watch Files For Changes
gulp.task('watch', function() {
    gulp.watch('js/*.js', ['lint', 'scripts']);
    gulp.watch('scss/*.scss', ['sass']);
});

// Default Task
gulp.task('default', ['lint', 'sass', 'scripts', 'watch']);


text:
<?php

use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
use yiichina\icheck\ICheck;
use yiichina\icons\Icon;
use yiichina\select2\Select2;

/* @var $this yii\web\View */
/* @var $model common\models\Node */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'type')->widget(ICheck::className(), ['type' => ICheck::TYPE_RADIO_LIST, 'items' => $model->typeList]) ?>

    <?= $form->field($model, 'node_id')->widget(Select2::className(), ['items' => $model->nodeList, 'clientOptions' => ['width' => '100%']]) ?>

    <?= $form->field($model, 'template_id')->widget(Select2::className(), ['items' => $model->templateList, 'clientOptions' => ['width' => '100%']]) ?>

    <?= $form->field($model, 'key')->textInput() ?>

    <?= $form->field($model, 'description')->textInput() ?>

    <?= $form->field($model, 'status')->widget(ICheck::className(), ['type' => ICheck::TYPE_RADIO_LIST, 'items' => $model->statusList]) ?>

        <?= Html::submitButton($model->isNewRecord ? Icon::show('plus') . Yii::t('app', 'Create') : Icon::show('edit') . Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success btn-flat' : 'btn btn-primary btn-flat']) ?>
        <?= Html::a(Icon::show('cog') . Yii::t('app', '配置模板'), ['template/update', 'id' => $model->template_id], ['class' => 'btn btn-primary btn-flat']) ?>

    <?php ActiveForm::end(); ?>


text:
import React, {Component} from 'react';
import {finalizeAuction, getRegistrarAddress} from '../../lib/ensService';
import {getEstimateGas, getTransactionFee} from '../../lib/dAppService';
import Dialog, {DialogActions, DialogContent} from 'material-ui/Dialog';
import List from 'material-ui/List';
import Divider from 'material-ui/Divider';
import Button from 'material-ui/Button';
import './FinalizeAuctionConfirmDialog.css';

const ConfirmListItem = (props) => {
  const specialName = ['From', 'To'];
  const classes = specialName.includes(props.name) ? 'address': '';

  return (

{props.name}:

{props.info}

      <Divider/>

  );
}

export class FinalizeAuctionConfirmDialog extends Component {

  payload() {
    const {searchResult: {searchName}, privateKey} = this.props;
    const {gas} = this.props.inputResult

    return finalizeAuction(searchName, privateKey, gas);
  }

  getFeeString() {
    const {gas} = this.props.inputResult
    const estimateGas = getEstimateGas(this.payload());
    const transactionFee = getTransactionFee(gas, estimateGas);

    return `${gas} Gwei * ${estimateGas} = ${transactionFee} ETH`;
  }

  formInfo = () => ({
    From: `${this.props.address}`,
    To: getRegistrarAddress(),
    Fee:  this.getFeeString()
  });

  inputResultList() {
    const formInfo = this.formInfo();

    return(
      <List>
        {Object
          .keys(formInfo)
          .map((key, index) =>
            <ConfirmListItem key={`input-${index}`} name={key} info={formInfo[key]}/>)}
      </List>
    );
  }

  render() {
    const {open, handleClose} = this.props;
    const inputResultList = this.inputResultList();

    return(
      <Dialog open={open} onRequestClose={handleClose}>

Confirm Finalize Auction Information

          <DialogContent>
            {inputResultList}
          </DialogContent>

            <DialogActions>
              <Button raised onClick={handleClose}>Cancel</Button>
              <Button raised
                className='KeystoreUploader-button'
                onClick={() => this.props.handleFormSubmit(this.props.inputResult)}>
                Submit
              </Button>
            </DialogActions>

      </Dialog>
    )
  }
}


text:
package tests;

import org.junit.Test;
import util.TickingTimer;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static org.junit.Assert.fail;

public class TickingTimerTests {

    private static void delay(double seconds) {
        int time = (int) (seconds * 1000);
        try {
            Thread.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private static TickingTimer createTickingTimer() {
        return new TickingTimer("test", 10, (i) -> {}, () -> {}, TimeUnit.SECONDS);
    }

    @Test(expected = AssertionError.class)
    public void doublePauseTest() {
        final TickingTimer tickingTimer = createTickingTimer();
        tickingTimer.start();
        tickingTimer.pause();
        tickingTimer.pause();
    }

    @Test
    public void threadingTest() {
        final int attempts = 2;

        final TickingTimer tickingTimer = createTickingTimer();
        tickingTimer.start();
        ExecutorService es = Executors.newFixedThreadPool(2);
        Runnable positive = () -> {
            for (int i = 0; i < attempts; i++) {
                tickingTimer.pause();
                delay(2);
            }
        };
        Runnable negative = () -> {
            for (int i = 0; i < attempts; i++) {
                tickingTimer.resume();
                delay(2);
            }
        };
        es.execute(positive);
        delay(1);
        es.execute(negative);
        delay(4.5); // Need 6 seconds to wait for the positive and negative runnables to complete the run.
    }

    @Test
    public void triggerTest() {
        final ArrayList<Integer> ticks = new ArrayList<>();
        final ArrayList<Integer> ideal = new ArrayList<>(Arrays.asList(
                4, 3, // After 1.5
                5, 10, // Trigger
                4, 3)); // After 3.5

        // Timeouts every five seconds, tick every second
        final TickingTimer tickingTimer = new TickingTimer("test2",
                5,
                ticks::add,
                () -> {
                    ticks.add(10); // Append 10 every timeout
                },
                TimeUnit.SECONDS
        );

        tickingTimer.start();
        delay(1.5);
        tickingTimer.trigger();
        delay(3.5);
        tickingTimer.stop();

        for (int i = 0; i < ideal.size(); i++) {
            if (ticks.get(i) != ideal.get(i)) fail();
        }
    }
}


text:
<?php
/**
 * The contents of this file was generated using the WSDLs as provided by eBay.
 *
 * DO NOT EDIT THIS FILE!
 */

namespace DTS\eBaySDK\MerchantData\Types;

/**
 *
 * @property boolean $DigitalDelivery
 */
class DigitalGoodInfoType extends \DTS\eBaySDK\Types\BaseType
{
    /**
     * @var array Properties belonging to objects of this class.
     */
    private static $propertyTypes = [
        'DigitalDelivery' => [
            'type' => 'boolean',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'DigitalDelivery'
        ]
    ];

    /**
     * @param array $values Optional properties and values to assign to the object.
     */
    public function __construct(array $values = [])
    {
        list($parentValues, $childValues) = self::getParentValues(self::$propertyTypes, $values);

        parent::__construct($parentValues);

        if (!array_key_exists(__CLASS__, self::$properties)) {
            self::$properties[__CLASS__] = array_merge(self::$properties[get_parent_class()], self::$propertyTypes);
        }

        if (!array_key_exists(__CLASS__, self::$xmlNamespaces)) {
            self::$xmlNamespaces[__CLASS__] = 'xmlns="urn:ebay:apis:eBLBaseComponents"';
        }

        $this->setValues(__CLASS__, $childValues);
    }
}


text:
'use strict';

var should = require('should'),
    request = require('supertest');

var checkHeaders = function(err, res, done) {
    should.not.exist(err);
    if (err) {
        throw err;
    }
    res.should.have.status(200);
    res.should.have.header(
            'Content-Type',
            'application/json; charset=utf-8'
            );

    res.should.have.header(
            'Access-Control-Allow-Methods',
            'GET,PUT,POST,DELETE,OPTIONS'
            );

    res.should.have.header(
            'Access-Control-Allow-Headers',
            'X-Requested-With, Content-Type'
            );

    res.should.have.header(
            'Access-Control-Allow-Origin',
            '*'
            );

    done();
};

describe('Routing', function () {
    var url = 'http://localhost:3000';

    before(function(done) {
        done();
    });

    describe('Retrospectives GET all', function() {
        it('Should return correct headers', function(done) {
            request(url)
                .get('/retrospectives')
                .end(function(err, res) {
                    checkHeaders(err, res, done);
                });
        });
    });

    describe('Retrospectives GET', function() {
        it('Should return correct headers', function(done) {
            request(url)
                .get('/retrospectives/sdf23423sdf')
                .end(function(err, res) {
                    checkHeaders(err, res, done);
                });
        });
    });

    describe('Retrospectives POST', function() {
        it('Should return correct headers', function(done) {
            request(url)
                .post('/retrospectives')
                .end(function(err, res) {
                    checkHeaders(err, res, done);
                });
        });
    });

    describe('Tickets GET all', function() {
        it('Should return correct headers', function(done) {
            request(url)
                .get('/retrospectives/sfsdf234/tickets')
                .end(function(err, res) {
                    checkHeaders(err, res, done);
                });
        });
    });

    describe('Tickets GET', function() {
        it('Should return correct headers', function(done) {
            request(url)
                .get('/retrospectives/sdfsdr2334/tickets/dgdfgg')
                .end(function(err, res) {
                    checkHeaders(err, res, done);
                });
        });
    });
});


text:
using System.Collections.Generic;

namespace ConsoleApplication1
{
    public interface ILogging
    {
        Dictionary<string, string> LogTable { get; set; }

        void Log(string name, string eventDetail);

        string GetLoggedDataByName(string name);
    }
}


text:
export default {
  description:
    'Input allows to insert short text values. This component is used in submit forms or to build other form components like `<Autocomplete/>` or `<NumberInput/>`.
',
  do: [
    'To insert names, titles and other short textual information.',
    'To build custom inputs like Credit Card input.',
  ],
  dont: [
    'To insert long paragraphs, instead use the <InputArea/> component.',
    'As a search input, instead use the <Search/> component.',
  ],
  featureExamples: [
    {
      title: 'Size',
      description: `Adjust the component size using \`size\` prop. It supports 3 sizes:

         - \`large\` - use it in onboarding flows, where input needs emphasis.

         - \`medium\` (default) - use in all common cases.

         - \`small\` - use in more dense and narrow layouts.
`,
      example: '_size',
    },
    {
      title: 'Border',
      description: `Style the component using \`border\` prop. It supports 3 styles:

         - \`default\` - use in all common cases.

         - \`round\` (default) - use to build filter inputs, like search.

         - \`bottomLine\` - use as a title which can be edited on the click.
`,
      example: '_border',
    },
    {
      title: 'Status',
      description: `Control component status using \`status\` prop. It supports 3 states:

         - \`error\` - use to highlight invalid input value.

         - \`warning\` - use to highlight inputs that values impact user business or can't be validated.

         - \`loading\` - use to show that the value is being uploaded to the server.
`,
      example: '_status',
    },
    {
      title: 'Status Message',
      description: `Explain the status with \`statusMessage\` prop. The message is revealed when a user mouse hovers the status icon.
        The placement of a tooltip is controlled with \`tooltipPlacement\` prop.`,
      example: '_statusMessage',
    },
    {
      title: 'Read-Only and Disabled',
      description: `Control input interaction with:

         - \`readOnly\` - disables writing new values, but allows to copy the current value. Use to display urls, codes and similar text.

         - \`disabled\` - disables all input interactions. Use to highlight unavailable functions.
`,
      example: '_readOnlyAndDisabled',
    },
    {
      title: 'Affix',
      description: `Support input value with additional information added to \`prefix\` and \`suffix\` props.
        Props can contain text, icons and even buttons.`,
      example: '_affix',
    },
    {
      title: 'Clear Button',
      description: `Enable a button that clears input value by using \`clearButton\` prop.
        Show it when input's value is optional or often has to be clear, for example date and search inputs.`,
      example: '_clearButton',
    },
    {
      title: 'Text Overflow',
      description: `Control long text value truncation with \`textOverflow\` prop. It has 2 options:

         - \`clip\`(default) - ends the text  with a sharp cut.

         - \`ellipsis\` - shows ellipsis where  text is truncated. Use to emphasize that text doesn't fit, especially when \`bottomLine\` style is enabled.
`,
      example: '_textOverflow',
    },
  ],
  commonUseCaseExamples: [
    {
      title: 'Compound Input',
      description: `When multiple inputs represent the same data, like phone number or address input, fields can be stacked together using \`Layout\` component.`,
      example: '_compoundInput',
    },
    {
      title: 'Input as a title',
      description: `Input can be used as a card title when its border is set to bottomLine.
        This pattern is great when it's needed to give a control to quickly organize groups and files.`,
      example: '_inputAsTitle',
    },
  ],
};


text:
from sqlalchemy import MetaData
from sqlalchemy import orm
from sqlalchemy.orm import exc as orm_exc
from sqlalchemy import Table

def map(engine, models):
    meta = MetaData()
    meta.bind = engine
    if mapping_exists(models['applications']):
        return
    orm.mapper(models['applications'], Table('applications', meta, autoload=True))

def mapping_exists(model):
    try:
        orm.class_mapper(model)
        return True
    except orm_exc.UnmappedClassError:
        return False


text:
package org.apache.mahout.classifier.df.builder;

import java.lang.reflect.Method;
import java.util.Random;
import java.util.Arrays;

import org.apache.commons.lang.ArrayUtils;
import org.apache.mahout.common.MahoutTestCase;
import org.apache.mahout.common.RandomUtils;
import org.junit.Test;

public final class DecisionTreeBuilderTest extends MahoutTestCase {

  /**
   * make sure that DecisionTreeBuilder.randomAttributes() returns the correct number of attributes, that have not been
   * selected yet
   */
  @Test
  public void testRandomAttributes() throws Exception {
    Random rng = RandomUtils.getRandom();
    int nbAttributes = rng.nextInt(100) + 1;
    boolean[] selected = new boolean[nbAttributes];

    for (int nloop = 0; nloop < 100; nloop++) {
      Arrays.fill(selected, false);

      // randomly select some attributes
      int nbSelected = rng.nextInt(nbAttributes - 1);
      for (int index = 0; index < nbSelected; index++) {
        int attr;
        do {
          attr = rng.nextInt(nbAttributes);
        } while (selected[attr]);

        selected[attr] = true;
      }

      int m = rng.nextInt(nbAttributes);

      Method randomAttributes = DecisionTreeBuilder.class.getDeclaredMethod("randomAttributes",
        Random.class, boolean[].class, int.class);
      randomAttributes.setAccessible(true);
      int[] attrs = (int[]) randomAttributes.invoke(null, rng, selected, m);

      assertNotNull(attrs);
      assertEquals(Math.min(m, nbAttributes - nbSelected), attrs.length);

      for (int attr : attrs) {
        // the attribute should not be already selected
        assertFalse("an attribute has already been selected", selected[attr]);

        // each attribute should be in the range [0, nbAttributes[
        assertTrue(attr >= 0);
        assertTrue(attr < nbAttributes);

        // each attribute should appear only once
        assertEquals(ArrayUtils.indexOf(attrs, attr), ArrayUtils.lastIndexOf(attrs, attr));
      }
    }
  }
}


text:
using System;
using System.ComponentModel;

namespace Azure.ResourceManager.SecurityCenter.Models
{
    /// <summary> The rule severity. </summary>
    public readonly partial struct RuleSeverity : IEquatable<RuleSeverity>
    {
        private readonly string _value;

        /// <summary> Initializes a new instance of <see cref="RuleSeverity"/>. </summary>
        /// <exception cref="ArgumentNullException"> <paramref name="value"/> is null. </exception>
        public RuleSeverity(string value)
        {
            _value = value ?? throw new ArgumentNullException(nameof(value));
        }

        private const string HighValue = "High";
        private const string MediumValue = "Medium";
        private const string LowValue = "Low";
        private const string InformationalValue = "Informational";
        private const string ObsoleteValue = "Obsolete";

        /// <summary> High. </summary>
        public static RuleSeverity High { get; } = new RuleSeverity(HighValue);
        /// <summary> Medium. </summary>
        public static RuleSeverity Medium { get; } = new RuleSeverity(MediumValue);
        /// <summary> Low. </summary>
        public static RuleSeverity Low { get; } = new RuleSeverity(LowValue);
        /// <summary> Informational. </summary>
        public static RuleSeverity Informational { get; } = new RuleSeverity(InformationalValue);
        /// <summary> Obsolete. </summary>
        public static RuleSeverity Obsolete { get; } = new RuleSeverity(ObsoleteValue);
        /// <summary> Determines if two <see cref="RuleSeverity"/> values are the same. </summary>
        public static bool operator ==(RuleSeverity left, RuleSeverity right) => left.Equals(right);
        /// <summary> Determines if two <see cref="RuleSeverity"/> values are not the same. </summary>
        public static bool operator !=(RuleSeverity left, RuleSeverity right) => !left.Equals(right);
        /// <summary> Converts a string to a <see cref="RuleSeverity"/>. </summary>
        public static implicit operator RuleSeverity(string value) => new RuleSeverity(value);

        /// <inheritdoc />
        [EditorBrowsable(EditorBrowsableState.Never)]
        public override bool Equals(object obj) => obj is RuleSeverity other && Equals(other);
        /// <inheritdoc />
        public bool Equals(RuleSeverity other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase);

        /// <inheritdoc />
        [EditorBrowsable(EditorBrowsableState.Never)]
        public override int GetHashCode() => _value?.GetHashCode() ?? 0;
        /// <inheritdoc />
        public override string ToString() => _value;
    }
}


text:
// Copyright (C) 2009 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.

package com.google.caja.ancillary.opt;

import com.google.caja.lexer.ParseException;

/**
 * Symbolic names for snippets of code that give information about the quirks
 * of the interpreter the code is running in, and the API available to programs
 * run in that environment.
 *
 * @author mikesamuel@gmail.com
 */
public enum EnvironmentDatum {
  NAV_USER_AGENT("navigator.userAgent"),
  IS_WINDOW_GLOBAL("!!this.window && this === window"),
  ES5_STRICT_AVAILABLE("!(function () { return this; }.call(null))"),
  NEG_INDICES_SAFE("void 0 === ((function () {})[-2])"),
  FN_CTORS_PURE(
      "void 0 === ((function () { var b, a = function b(){}; return b; })())"),
  CATCH_BLOCK_SCOPED(
      "(function () { var e=true; try{throw false; }catch(e){} return e; })()"),
  FN_INIT_HOISTED(
      "function () { var a; if (0) function a(){} return void 0 === a; }()"),
  ;

  private final String js;

  EnvironmentDatum(String js) {
    try {
      this.js = EnvironmentData.normJs(js, EnvironmentData.LOUD_MQ);
    } catch (ParseException ex) {
      throw new RuntimeException(ex);
    }
  }

  public String getCode() { return js; }
}


text:
[reconstruct{T}(pp::T)](Parameters.md#method__reconstruct.1)  Make a new instance of a type with the same values as

[type2dict(dt)](Parameters.md#method__type2dict.1)  Transforms a type-instance into a dictionary.

---

## Macros [Exported]

[@pack(args)](Parameters.md#macro___pack.1)  Packs variables into a composite type or a `Dict{Symbol}`

[@unpack(args)](Parameters.md#macro___unpack.1)  Unpacks fields/keys from a composite type or a `Dict{Symbol}` into variables

[@with_kw(typedef)](Parameters.md#macro___with_kw.1)  Macro which allows default values for field types and a few other features.

---

## Functions [Internal]

[Parameters.pack!](Parameters.md#function__pack.1)  This function is invoked to pack one entity into some DataType and has

[Parameters.unpack](Parameters.md#function__unpack.1)  This function is invoked to unpack one entity of some DataType and has

---

## Methods [Internal]

[with_kw(typedef)](Parameters.md#method__with_kw.1)  This function is called by the `@with_kw` macro and does the syntax


text:
Original script by desgua, edited by northway

## Simple use

```shell
./path/to/ppp-check.sh
```
## Cron syntax

```cron
* * * * * /path/to/ppp-check.sh
```

With this the cron will execute the script in every minute.


text:
import java.util.List;
import java.util.Scanner;
import java.util.ArrayList;

public class LinkedBSTRunner {
    private static Scanner input = new Scanner(System.in);
	public static void main(String[] args) {
		List display = new ArrayList();
		LinkedBST tree = new LinkedBST();
		/*
		tree.addNode(7);
		tree.addNode(4);
		tree.addNode(12);
		tree.addNode(9);
		tree.addNode(19);
		tree.addNode(2);
		tree.addNode(6);
		tree.addNode(3);
		tree.addNode(5);
		tree.addNode(8);
		tree.addNode(11);
		tree.addNode(20);
		tree.addNode(15);
		*/
    	int menu = 0;
		do {
			//display menu
			System.out.println("");
			System.out.println("#=================== Binary Search Tree ====================#");
			System.out.println("|1. Add a node                                              |");
			System.out.println("|2. Preorder Traversal                                      |");
			System.out.println("|3. Inorder Traversal                                       |");
			System.out.println("|4. Postorder Traversal                                     |");
			System.out.println("|5. Remove a node                                           |");
			System.out.println("|6. Search the tree for a node                              |");
			System.out.println("|7. Count the number of leafs in the tree                   |");
			System.out.println("|8. Find Path                                               |");
			System.out.println("|9. Hard-Coded Test Case                                    |");
			System.out.println("|10. Quit                                                   |");
			System.out.println("#===========================================================#");
			System.out.println("");
			System.out.print("Please choose a selection: ");
			menu = input.nextInt();
			if (menu == 1) {
				System.out.print("Please enter the value of the node: ");
				String s1 = input.next();
				boolean value = tree.addNode(s1);
				if (value == true)
					System.out.println("Added the node successfully! (true)");
				else
					System.out.println("Failed to add the node! (false)");
			}
			if (menu == 2)
				System.out.println("Preorder: " + tree.preOrder());
			if (menu == 3)
				System.out.println("Inorder: " + tree.inOrder());
			if (menu == 4)
				System.out.println("Postorder: " + tree.postOrder());
			if (menu == 5) {
				System.out.println("Please enter the value to remove");
				String s1 = input.next();
				boolean value = tree.removeNode(s1);
				if (value == true)
					System.out.println("Removed the node successfully! (true)");
				else
					System.out.println("Failed to remove the node! (false)");
			}
			if (menu == 6) {
				System.out.println("What is the value you want to find?");
				String s2 = input.next();
				boolean result = tree.search(s2);
				if (result == true)
					System.out.println("The value \"" + s2 + "\" was found in the tree!");
				else
					System.out.println("The value \"" + s2 + "\" was not found in the tree!");
			}
			if (menu == 7) {
				int result = tree.countLeaf();
				System.out.println("The tree has " + result + " leaf(s).");
			}
			if (menu == 8) {
				System.out.println("Please enter the node to go twoards");
				String s3 = input.next();
				int result = tree.findPath(s3);
				System.out.println("Number of branches crossed: " + result);
			}
			if (menu == 9) {
				tree.addNode("17");
				tree.addNode("14");
				tree.addNode("22");
				tree.addNode("19");
				tree.addNode("29");
				tree.addNode("12");
				tree.addNode("16");
				tree.addNode("13");
				tree.addNode("15");
				tree.addNode("18");
				tree.addNode("21");
				tree.addNode("30");
				tree.addNode("25");
				System.out.println("Added nodes");
			}
		} while (menu != 10);
	}

}


text:
module ToggleableEntity
  extend ActiveSupport::Concern

  # Toggle entity flag when allowed
  def toggle
    if entity_is_locked?
      render json: { errors: { locked: true } }, status: :forbidden
    elsif entity_is_editable?
      render json: { data: @entity.toggle_parameter(params[:parameter].to_s) }
    else
      head :unauthorized
    end
  end

  private

  def entity_is_editable?
    if @entity.respond_to?(:editable_by?)
      @entity.editable_by?(current_user)
    else
      true
    end
  end

  def entity_is_locked?
    @entity.respond_to?(:locked?) ? @entity.locked? : false
  end
end


text:
package org.jeecqrs.common.event.routing;

import org.jeecqrs.common.event.AbstractEvent;

/**
 *
 */
public class TestEvent2 extends AbstractEvent<TestEvent2> {

}


text:
package com.intellij.openapi.vcs.impl.projectlevelman;

import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.WriteExternalException;
import com.intellij.openapi.vcs.VcsShowConfirmationOption;
import com.intellij.openapi.vcs.VcsShowConfirmationOptionImpl;
import com.intellij.openapi.vcs.VcsShowOptionsSettingImpl;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;

import java.util.Map;

public class ProjectLevelVcsManagerSerialization {
  @NonNls private static final String OPTIONS_SETTING = "OptionsSetting";
  @NonNls private static final String CONFIRMATIONS_SETTING = "ConfirmationsSetting";
  @NonNls private static final String VALUE_ATTTIBUTE = "value";
  @NonNls private static final String ID_ATTRIBUTE = "id";

  public void readExternalUtil(final Element element, final OptionsAndConfirmations optionsAndConfirmations) throws InvalidDataException {
    for (Element subElement : element.getChildren(OPTIONS_SETTING)) {
      final String id = subElement.getAttributeValue(ID_ATTRIBUTE);
      final String value = subElement.getAttributeValue(VALUE_ATTTIBUTE);
      if (id != null && value != null) {
        VcsShowOptionsSettingImpl option = optionsAndConfirmations.getOrCreateOption(id);
        option.setValue(Boolean.parseBoolean(value));
      }
    }

    for (Element subElement : element.getChildren(CONFIRMATIONS_SETTING)) {
      final String id = subElement.getAttributeValue(ID_ATTRIBUTE);
      final String value = subElement.getAttributeValue(VALUE_ATTTIBUTE);
      if (id != null && value != null) {
        VcsShowConfirmationOptionImpl confirmation = optionsAndConfirmations.getConfirmation(id);
        if (confirmation != null) {
          confirmation.setValue(VcsShowConfirmationOption.Value.fromString(value));
        }
      }
    }
  }

  public void writeExternalUtil(@NotNull Element element, @NotNull OptionsAndConfirmations optionsAndConfirmations) throws WriteExternalException {
    final Map<String, VcsShowOptionsSettingImpl> options = optionsAndConfirmations.getOptions();
    final Map<String, VcsShowConfirmationOptionImpl> confirmations = optionsAndConfirmations.getConfirmations();

    for (VcsShowOptionsSettingImpl setting : options.values()) {
      if (!setting.getValue()) {
        Element settingElement = new Element(OPTIONS_SETTING);
        element.addContent(settingElement);
        settingElement.setAttribute(VALUE_ATTTIBUTE, Boolean.toString(setting.getValue()));
        settingElement.setAttribute(ID_ATTRIBUTE, setting.getDisplayName());
      }
    }

    for (VcsShowConfirmationOptionImpl setting : confirmations.values()) {
      if (setting.getValue() != VcsShowConfirmationOption.Value.SHOW_CONFIRMATION) {
        final Element settingElement = new Element(CONFIRMATIONS_SETTING);
        element.addContent(settingElement);
        settingElement.setAttribute(VALUE_ATTTIBUTE, setting.getValue().toString());
        settingElement.setAttribute(ID_ATTRIBUTE, setting.getDisplayName());
      }
    }
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<objects serializationModel="Studio.01.08.00">
    <object class="AudioFile" id="{b629e5f8-18fa-4183-8dee-d489387fcdaf}">
        <property name="assetPath">
            <value>Environment/CampFire/LoopFireFlames_00b.wav</value>
        </property>
        <property name="isStreaming">
            <value>true</value>
        </property>
        <property name="frequencyInKHz">
            <value>44.0999985</value>
        </property>
        <property name="channelCount">
            <value>2</value>
        </property>
        <property name="length">
            <value>9</value>
        </property>
        <relationship name="masterAssetFolder">
            <destination>{cbdaacbf-f328-457b-bedb-8c33cacc0690}</destination>
        </relationship>
    </object>
</objects>


text:
using System;
using System.Collections.Generic;
using System.IO;
using BannerChecker.Wpf.Views;

namespace BannerChecker.Wpf.Models
{
	public class ImageDialogService
	{
		private readonly Dictionary<string, Action<string>> imageDialogOpeners = new Dictionary<string, Action<string>>()
		{
			{ ".jpg", ShowBitmapImage },
			{ ".jpeg", ShowBitmapImage },
			{ ".png", ShowBitmapImage },
			{ ".gif", ShowBitmapImage },
		};

		public void ShowImage(string filePath)
		{
			if (imageDialogOpeners.ContainsKey(Path.GetExtension(filePath)))
				imageDialogOpeners[Path.GetExtension(filePath)](filePath);
		}

		private static void ShowBitmapImage(string filePath)
		{
			var window = new ImagePreviewWindow(filePath);
			window.ShowDialog();
		}
	}
}


text:
include_recipe "mariadb-enterprise::default"

case node[:platform_family]
when "debian"
  package "mariadb-common" do
    action :remove
  end
when "rhel", "fedora", "suse"
  package "MariaDB-common" do
    action :remove
  end
end

include_recipe "mariadb-enterprise::repos_off"


text:
package br.unicamp.ic.lsd.mercurius.persistence.entities;

import java.util.List;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import br.unicamp.ic.lsd.mercurius.datatype.ProductAttribute;
import br.unicamp.ic.lsd.mercurius.datatype.ProductOption;

import com.google.common.base.Objects;

@Entity(name = "ProductOption")
@Table(name = "product_option")
public class ProductOptionImpl implements ProductOption {

	private static final long serialVersionUID = 6222272988011062337L;

	protected ProductOptionImpl() {
		super();
	}

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	@Column(name = "product_option_id")
	private Integer id;

	@Column(name = "product_option_name", nullable = false)
	private String name;

	@OneToMany(mappedBy = "option", targetEntity = ProductAttributeImpl.class)
	private List<ProductAttribute> attributes;

	@Override
	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	@Override
	public String getName() {
		return name;
	}

	@Override
	public void setName(String name) {
		this.name = name;
	}

	@Override
	public List<ProductAttribute> getAttributes() {
		return attributes;
	}

	public void setAttributes(List<ProductAttribute> attributes) {
		this.attributes = attributes;
	}

	@Override
	public int hashCode() {
		return Objects.hashCode(id);
	}

	@Override
	public boolean equals(Object obj) {
		if (obj instanceof ProductOptionImpl) {
			ProductOptionImpl option = (ProductOptionImpl) obj;
			return Objects.equal(option.getId(), id);
		}
		return false;
	}

	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append("ProductOptionImpl [id=");
		builder.append(id);
		builder.append(", name=");
		builder.append(name);
		builder.append("]");
		return builder.toString();
	}

}


text:
"""A Python calculator"""
import sys

command = sys.argv[1]
numbers = [float(a) for a in sys.argv[2:]]
a = float(sys.argv[2])
b = float(sys.argv[3])

if command == 'add':
    print sum(numbers)

elif command == 'multiply':
    product = 1
    for num in numbers:
        product *= num
    print product
elif command == 'divide':
    div = 1
    if b != 0:
        div = a/b
        print div
adding some errors here.
print ':)'

print "all good."


text:
"""Tests for single_file_library_package."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from io import BytesIO

import gflags as flags
from google.apputils import basetest
from googleapis.codegen.filesys import single_file_library_package

FLAGS = flags.FLAGS

class SingleFileLibraryPackageTest(basetest.TestCase):

  def setUp(self):
    self._output_stream = BytesIO()
    self._package = single_file_library_package.SingleFileLibraryPackage(
        self._output_stream)

  def tearDown(self):
    pass

  def testBasicWriteFile(self):
    name1 = 'def'
    content1 = 'contents of def'
    name2 = 'abc'
    content2 = 'contents of abc'
    expected_tmpl = '=== begin: %s\n%s=== end: %s\n'

    stream = self._package.StartFile(name1)
    stream.write(content1)
    stream = self._package.StartFile(name2)
    stream.write(content2)
    self._package.DoneWritingArchive()

    # read it back and verify
    expected = expected_tmpl % (name2, content2, name2)
    expected += expected_tmpl % (name1, content1, name1)
    got = self._output_stream.getvalue()
    self.assertEqual(expected, got)

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


text:
.block_course_overview .coursechildren {
    font-weight: normal;
    font-style: italic;
}

.block_course_overview .categorypath{
    text-align: right;
}

.dir-rtl .block_course_overview .categorypath{
    text-align: left;
}

.block_course_overview .content {
    margin: 0 20px;
}
.block_course_overview .content .notice {
    margin: 5px 0;
}

.block_course_overview .coursebox {
    padding: 15px;
    width: auto;
}

.block_course_overview .profilepicture {
    float: left;
}
.dir-rtl.block_course_overview .profilepicture {
    float:right;
}
.block_course_overview .welcome_area {
    width: 100%;
    padding-bottom: 5px;
}

.block_course_overview .welcome_message {
    float: left;
    padding: 10px;
    vertical-align: middle;
    border-collapse: separate;
    clear: none;
}
.dir-rtl .block_course_overview .welcome_message {
    float:right;
}

.block_course_overview .content h2.title {
    float: left;
    margin: 0 0 .5em 0;
    position: relative;
}
.dir-rtl .block_course_overview .content h2.title {
    float:right;
}

.block_course_overview .course_title {
    position: relative;
}

.editing .block_course_overview .coursebox .cursor {
    cursor: move;
    margin-bottom: 2px;
}

.editing .block_course_overview .move {
    float: left;
    padding: 2px 10px 0 0;
}
.dir-rtl.editing .block_course_overview .move {
    float:right;
    padding: 2px 10px;
}

.block_course_overview .course_list {
    width: 100%;
}

.block_course_overview div.flush {
    clear: both;
}

.block_course_overview .activity_info {
    clear: both;
}
.dir-rtl .block_course_overview .activity_info {
    margin-right: 25px;
}

.block_course_overview .activity_overview {
    padding: 2px;
}
.block_course_overview .activity_overview img.iconlarge { vertical-align: text-bottom; margin-right: 6px; }
.dir-rtl .block_course_overview .activity_overview img.iconlarge { margin-left: 6px; margin-right: 0;}

.block_course_overview .singleselect {
    text-align: left;
    margin: 0;
}
.dir-rtl .block_course_overview .singleselect {
    text-align: right;
}

.block_course_overview .content .course_list .movehere{
    margin-bottom: 15px;
}


text:
PKG_NAME = go
PKG_VERS = 1.4.2
PKG_EXT = tar.gz
PKG_DIST_NAME = $(PKG_NAME)$(PKG_VERS).src.$(PKG_EXT)
PKG_DIST_SITE = https://storage.googleapis.com/golang
PKG_DIR = $(PKG_NAME)

DEPENDS =

HOMEPAGE   = http://golang.org/
COMMENT    = Go is an open source programming language that makes it easy to build simple, reliable, and efficient software.
LICENSE    =

CONFIGURE_TARGET = nop
COMPILE_TARGET = myComp
INSTALL_TARGET = nop

include ../../mk/spksrc.native-cc.mk

myComp:
	@$(MSG) "Building Go"
	cd $(WORK_DIR)/$(PKG_NAME)/src && ./make.bash
	@$(MSG) "Building Go for arm"
	cd $(WORK_DIR)/$(PKG_NAME)/src && export GOARCH=arm && ./make.bash --no-clean
	@$(MSG) "Building Go amd64"
	cd $(WORK_DIR)/$(PKG_NAME)/src && export GOARCH=amd64 && ./make.bash --no-clean


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

import org.camunda.bpm.BpmPlatform;
import org.jboss.shrinkwrap.api.spec.WebArchive;

/**
 * @author roman.smirnov
 */
public class TestContainer {

  public final static String APP_NAME = "";

  public final static String PROCESS_ENGINE_SERVICE_JNDI_NAME = BpmPlatform.PROCESS_ENGINE_SERVICE_JNDI_NAME;
  public final static String PROCESS_APPLICATION_SERVICE_JNDI_NAME = BpmPlatform.PROCESS_APPLICATION_SERVICE_JNDI_NAME;

  public static String getAppName() {
    return APP_NAME;
  }

  public static void addContainerSpecificResources(WebArchive webArchive) {
    addContainerSpecificResourcesWithoutWeld(webArchive);
  }

  public static void addContainerSpecificResourcesWithoutWeld(WebArchive webArchive) {
    webArchive.addClass(TestProcessApplication.class);
  }

  public static void addContainerSpecificResourcesForNonPa(WebArchive webArchive) {
    addContainerSpecificResourcesForNonPaWithoutWeld(webArchive);
  }

  public static void addContainerSpecificResourcesForNonPaWithoutWeld(WebArchive webArchive) {
    // nothing to do
  }

  public static void addContainerSpecificProcessEngineConfigurationClass(WebArchive deployment) {
    // nothing to do
  }

}


text:
require 'tempfile'

module DeKrookParser
  module Parsers
    class CSV
      LOGGER = Logger.new(STDOUT)
      LOGGER.level = Logger::WARN

      attr_reader :encoding, :mapping, :baseIRI, :keyColumn, :columnCount

      def initialize(encoding: 'iso-8859-1', mapping: {}, baseIRI:, keyColumn: nil )
        logger.info "parser initialized"
        logger.info "encoding: #{encoding.inspect}, mapping:#{mapping.inspect}, baseIRI:#{baseIRI.inspect}, keyColumn: #{keyColumn.inspect}"
        @encoding = encoding
        @mapping = mapping
        @baseIRI = baseIRI
        @keyColumn = keyColumn
      end

      def parse(filepath, index = 0)
        output = Tempfile.new("parse-of-#{File.basename(filepath)}")
        output.write "# parsing #{filepath}"
        begin
        headers_parsed = false
        ::CSV.foreach(filepath, csv_parse_options) do |row|
          unless headers_parsed
            @columnCount = row.size
            index += 1
            headers_parsed = true
            next
          end
          ensure_valid_row(row, index) do |row|
            repo = RDF::Repository.new do |graph|
              parse_row(index, row).each do |statement|
                logger.debug statement.inspect
                graph << statement
              end
            end
            output.write(repo.dump(:ttl))
          end
          index += 1
        end
        rescue ::CSV::MalformedCSVError => e
          logger.error e.message
          logger.error "parsing stopped after this error"
        end
        output.close
        output
      end

      def logger
        LOGGER
      end

      def parse_row(index, row)
       row.map do | key, val |
          [ row_iri(index,row) , column_to_predicate(key), val ]
        end
      end

      def is_valid_key?(key)
        not is_empty?(key)
      end

      def ensure_valid_row(row, index, &block)
        errors = 0
        if row.size > columnCount
          logger.warn "ignored row #{row.count}: has more columns than expected #{row.size} > #{columnCount} "
          errors += 1
        end

        if row.size < columnCount
          logger.warn "ignored row #{row.count}: has more columns than expected #{row.size} < #{columnCount} "
          errors += 1
        end

        unless keyColumn.nil? or is_valid_key?(row[keyColumn])
          logger.warn "ignored row #{index}: has invalid key #{row[keyColumn]} for column #{keyColumn}"
          errors += 1
        end

        if errors == 0
          block.call(row)
        end
      end

      protected
      def csv_parse_options
        { headers: :first_row, return_headers: true, encoding: @encoding, skip_lines: /[^\x00-\x7F]/ }
      end

      def column_to_predicate(key)
        mapping[key.to_sym] or RDF::URI.new("#{baseIRI}predicates/#{key}")
      end

      def row_iri(index, row)
        if keyColumn.nil?
          RDF::URI.new("#{baseIRI}rows/#{index}")
        else
          RDF::URI.new("#{baseIRI}rows/#{row[keyColumn]}")
        end
      end

      def is_empty?(val)
        val.nil? or val.to_s.empty?
      end
    end
  end
end


text:
package im.actor.model.entity.compat.content;

import java.io.IOException;

import im.actor.model.api.Message;
import im.actor.model.api.ServiceExUserKicked;
import im.actor.model.api.ServiceMessage;
import im.actor.model.droidkit.bser.BserObject;
import im.actor.model.droidkit.bser.BserValues;
import im.actor.model.droidkit.bser.BserWriter;

public class ObsoleteServiceKicked extends BserObject {

    private int kickedUid;

    public ObsoleteServiceKicked(BserValues values) throws IOException {
        parse(values);
    }

    public Message toApiMessage() {
        return new ServiceMessage("Member kicked",
                new ServiceExUserKicked(kickedUid));
    }

    @Override
    public void parse(BserValues values) throws IOException {
        kickedUid = values.getInt(10);
    }

    @Override
    public void serialize(BserWriter writer) throws IOException {
        throw new UnsupportedOperationException();
    }
}


text:
package com.wikigraph.graph;

public enum Direction {
  INCOMING, OUTGOING
}


text:
'use strict';
const got = require('got');

let config;
try {
  config = require('./config.json');
} catch (err) {
  config = {};
}

const request = (url) => {
  url = config.apiKey ? `${url}?api_key=${config.apiKey}` : url;
  return got(url)
    .then(response => {
      return response.body;
    });
};

module.exports = { request };


text:
<?xml version="1.0" encoding="UTF-8"?>
<nifty-styles xmlns="http://nifty-gui.lessvoid.com/nifty-gui">
    <useStyles filename="fonts.xml"/>
    <useStyles filename="tabs/nifty-tabs.xml"/>
    <!-- nifty-panel.xml is already imported by nifty-tabs.xml -->
    <!-- <useStyles filename="panel/nifty-panel.xml"/> -->
    <useStyles filename="button/nifty-button.xml"/>
    <useStyles filename="label/nifty-label.xml"/>
    <useStyles filename="textfield/nifty-textfield.xml"/>
    <useStyles filename="dropdown/nifty-drop-down.xml"/>
    <useStyles filename="imageselect/nifty-image-select.xml"/>
    <useStyles filename="checkbox/nifty-checkbox.xml"/>
    <useStyles filename="radiobutton/nifty-radiobutton.xml"/>
    <useStyles filename="scrollbar/nifty-scrollbar-style.xml"/>
    <useStyles filename="slider/nifty-slider-style.xml"/>
    <useStyles filename="scrollpanel/nifty-scrollpanel-style.xml"/>
    <useStyles filename="console/nifty-console-style.xml"/>
    <useStyles filename="chat-control/nifty-chat-control.xml"/>
    <useStyles filename="menu/nifty-menu-style.xml"/>
    <useStyles filename="listbox/nifty-listbox-style.xml"/>
    <useStyles filename="window/nifty-window.xml"/>
    <useStyles filename="hint/nifty-hint.xml"/>
    <useStyles filename="treebox/nifty-treebox.xml"/>
    <useStyles filename="messagebox/nifty-messagebox.xml"/>
</nifty-styles>


text:
{-# LANGUAGE CPP #-}
{-# LANGUAGE AllowAmbiguousTypes #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}

module Nix.Render.Frame where

import           Control.Monad.Reader
import           Data.Fix
import           Data.Typeable
import           Data.Text.Prettyprint.Doc
import           Nix.Eval
import           Nix.Exec
import           Nix.Expr
import           Nix.Frames
import           Nix.Normal
import           Nix.Options
import           Nix.Pretty
import           Nix.Render
import           Nix.Thunk
import           Nix.Utils
import           Nix.Value
import           Text.Megaparsec.Pos
#ifdef MIN_VERSION_pretty_show
import qualified Text.Show.Pretty as PS
#endif

renderFrames
  :: forall v t f e m ann
   . ( MonadReader e m
     , Has e Options
     , MonadFile m
     , MonadCitedThunks t f m
     , Typeable v
     )
  => Frames
  -> m (Doc ann)
renderFrames []       = pure mempty
renderFrames (x : xs) = do
  opts :: Options <- asks (view hasLens)
  frames          <- if
    | verbose opts <= ErrorsOnly -> renderFrame @v @t @f x
    | verbose opts <= Informational -> do
      f <- renderFrame @v @t @f x
      pure $ concatMap go (reverse xs) ++ f
    | otherwise -> concat <$> mapM (renderFrame @v @t @f) (reverse (x : xs))
  pure $ case frames of
    [] -> mempty
    _  -> vsep frames
 where
  go :: NixFrame -> [Doc ann]
  go f = case framePos @v @m f of
    Just pos ->
      ["While evaluating at " <> pretty (sourcePosPretty pos) <> colon]
    Nothing -> []

framePos
  :: forall v (m :: * -> *)
   . (Typeable m, Typeable v)
  => NixFrame
  -> Maybe SourcePos
framePos (NixFrame _ f)
  | Just (e :: EvalFrame m v) <- fromException f = case e of
    EvaluatingExpr _ (Fix (Compose (Ann (SrcSpan beg _) _))) -> Just beg
    _ -> Nothing
  | otherwise = Nothing

renderFrame
  :: forall v t f e m ann
   . ( MonadReader e m
     , Has e Options
     , MonadFile m
     , MonadCitedThunks t f m
     , Typeable v
     )
  => NixFrame
  -> m [Doc ann]
renderFrame (NixFrame level f)
  | Just (e :: EvalFrame m v) <- fromException f = renderEvalFrame level e
  | Just (e :: ThunkLoop) <- fromException f = renderThunkLoop level e
  | Just (e :: ValueFrame t f m) <- fromException f = renderValueFrame level e
  | Just (e :: NormalLoop t f m) <- fromException f = renderNormalLoop level e
  | Just (e :: ExecFrame t f m) <- fromException f = renderExecFrame level e
  | Just (e :: ErrorCall) <- fromException f = pure [pretty (show e)]
  | Just (e :: SynHoleInfo m v) <- fromException f = pure [pretty (show e)]
  | otherwise = error $ "Unrecognized frame: " ++ show f

wrapExpr :: NExprF r -> NExpr
wrapExpr x = Fix (Fix (NSym "<?>") <$ x)

renderEvalFrame
  :: (MonadReader e m, Has e Options, MonadFile m)
  => NixLevel
  -> EvalFrame m v
  -> m [Doc ann]
renderEvalFrame level f = do
  opts :: Options <- asks (view hasLens)
  case f of
    EvaluatingExpr scope e@(Fix (Compose (Ann ann _))) -> do
      let scopeInfo | scopes opts = [pretty $ show scope]
                    | otherwise   = []
      fmap (\x -> scopeInfo ++ [x])
        $   renderLocation ann
        =<< renderExpr level "While evaluating" "Expression" e

    ForcingExpr _scope e@(Fix (Compose (Ann ann _))) | thunks opts ->
      fmap (: [])
        $   renderLocation ann
        =<< renderExpr level "While forcing thunk from" "Forcing thunk" e

    Calling name ann ->
      fmap (: [])
        $  renderLocation ann
        $  "While calling builtins."
        <> pretty name

    SynHole synfo ->
      sequence
        $ let e@(Fix (Compose (Ann ann _))) = _synHoleInfo_expr synfo
          in  [ renderLocation ann
                =<< renderExpr level "While evaluating" "Syntactic Hole" e
              , pure $ pretty $ show (_synHoleInfo_scope synfo)
              ]

    ForcingExpr _ _ -> pure []

renderExpr
  :: (MonadReader e m, Has e Options, MonadFile m)
  => NixLevel
  -> String
  -> String
  -> NExprLoc
  -> m (Doc ann)
renderExpr _level longLabel shortLabel e@(Fix (Compose (Ann _ x))) = do
  opts :: Options <- asks (view hasLens)
  let rendered
          | verbose opts >= DebugInfo =
#ifdef MIN_VERSION_pretty_show
              pretty (PS.ppShow (stripAnnotation e))
#else
              pretty (show (stripAnnotation e))
#endif
          | verbose opts >= Chatty = prettyNix (stripAnnotation e)
          | otherwise = prettyNix (Fix (Fix (NSym "<?>") <$ x))
  pure $ if verbose opts >= Chatty
    then
      vsep
        $ [pretty (longLabel ++ ":\n>>>>>>>>"), indent 2 rendered, "<<<<<<<<"]
    else pretty shortLabel <> fillSep [": ", rendered]

renderValueFrame
  :: forall e t f m ann
   . (MonadReader e m, Has e Options, MonadFile m, MonadCitedThunks t f m)
  => NixLevel
  -> ValueFrame t f m
  -> m [Doc ann]
renderValueFrame level = fmap (: []) . \case
  ForcingThunk    _t -> pure "ForcingThunk" -- jww (2019-03-18): NYI
  ConcerningValue _v -> pure "ConcerningValue"
  Comparison     _ _ -> pure "Comparing"
  Addition       _ _ -> pure "Adding"
  Division       _ _ -> pure "Dividing"
  Multiplication _ _ -> pure "Multiplying"

  Coercion       x y -> pure
    $ mconcat [desc, pretty (describeValue x), " to ", pretty (describeValue y)]
   where
    desc | level <= Error = "Cannot coerce "
         | otherwise      = "While coercing "

  CoercionToJson v -> do
    v' <- renderValue level "" "" v
    pure $ "CoercionToJson " <> v'
  CoercionFromJson _j -> pure "CoercionFromJson"
  Expectation t v     -> do
    v' <- renderValue @_ @t @f @m level "" "" v
    pure $ "Saw " <> v' <> " but expected " <> pretty (describeValue t)

renderValue
  :: forall e t f m ann
   . (MonadReader e m, Has e Options, MonadFile m, MonadCitedThunks t f m)
  => NixLevel
  -> String
  -> String
  -> NValue t f m
  -> m (Doc ann)
renderValue _level _longLabel _shortLabel v = do
  opts :: Options <- asks (view hasLens)
  (if values opts
     then prettyNValueProv
     else prettyNValue) <$> removeEffects v

renderExecFrame
  :: (MonadReader e m, Has e Options, MonadFile m, MonadCitedThunks t f m)
  => NixLevel
  -> ExecFrame t f m
  -> m [Doc ann]
renderExecFrame level = \case
  Assertion ann v ->
    fmap (: [])
      $   renderLocation ann
      =<< (   (\d -> fillSep ["Assertion failed:", d])
          <$> renderValue level "" "" v
          )

renderThunkLoop
  :: (MonadReader e m, Has e Options, MonadFile m, Show (ThunkId m))
  => NixLevel
  -> ThunkLoop
  -> m [Doc ann]
renderThunkLoop _level = pure . (: []) . \case
  ThunkLoop n -> pretty $ "Infinite recursion in thunk " ++ n

renderNormalLoop
  :: (MonadReader e m, Has e Options, MonadFile m, MonadCitedThunks t f m)
  => NixLevel
  -> NormalLoop t f m
  -> m [Doc ann]
renderNormalLoop level = fmap (: []) . \case
  NormalLoop v -> do
    v' <- renderValue level "" "" v
    pure $ "Infinite recursion during normalization forcing " <> v'


text:
SDL_Window * g_gfx_window;
SDL_GLContext * g_gfx_gl_context;

int g_gfx_window_width;
int g_gfx_window_height;

int gfx_getScreenWidth() {
    return g_gfx_window_width;
}

int gfx_getScreenHeight() {
    return g_gfx_window_height;
}

int gfx_createWindow(int width, int height) {

    SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER);

    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
    SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);

    SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
    SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 6);
    SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);

//    SDL_GL_SetAttribute(SDL_GL_CONTEXT_DEBUG_FLAG, 1);
//    SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG);
    g_gfx_window = SDL_CreateWindow("fridge-magnet", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN);

//    SDL_GL_GetDrawableSize(g_gfx_window, &g_gfx_window_width, &g_gfx_window_height);
    g_gfx_window_width = width;
    g_gfx_window_height = height;

    g_gfx_gl_context = SDL_GL_CreateContext(g_gfx_window);

    SDL_GL_SetSwapInterval(1);

    gl_setup(width, height);

    return 0;
}

void gfx_dispose() {
    SDL_GL_DeleteContext(g_gfx_gl_context);
    g_gfx_gl_context = NULL;

    SDL_DestroyWindow(g_gfx_window);
    g_gfx_window = NULL;

    SDL_Quit();
}

void gfx_swapBuffers() {
    SDL_GL_SwapWindow(g_gfx_window);
}

void gfx_handleWindowEvents(int * b_end) {
    SDL_Event e;
    while (SDL_PollEvent(&e)) {
        if (e.type == SDL_QUIT || (e.type == SDL_KEYDOWN && e.key.keysym.sym == SDLK_ESCAPE)) {
            *b_end = 1;
        }
    }
}