text:
package ru.job4j.crud.servlets;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.job4j.crud.model.Country;
import ru.job4j.crud.model.Role;
import ru.job4j.crud.model.User;
import ru.job4j.crud.model.UserStore;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * Servlet for update user.
 *
 * @since 09/02/2018
 * @version 3
 */
public class UpdateServlet extends HttpServlet {

    private static final Logger LOG = LoggerFactory.getLogger(UpdateServlet.class);
    private final UserStore store = UserStore.getInstance();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        addAllAttributesTo(req);
        req.getRequestDispatcher("/WEB-INF/views/UpdateUser.jsp").forward(req, resp);
    }

    private void addAllAttributesTo(HttpServletRequest req) {
        List<User> users = store.getAllUsers();
        List<Role> roles = store.getAllRoles();
        List<Country> countries = store.getAllCountries();
        req.setAttribute("users", users);
        req.setAttribute("roles", roles);
        req.setAttribute("countries", countries);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String oldLogin = req.getParameter("oldLogin");
        String name = req.getParameter("name");
        String login = req.getParameter("login");
        String password = req.getParameter("password");
        String role = req.getParameter("role");
        String email = req.getParameter("email");
        String city = req.getParameter("city");
        String country = req.getParameter("country");

        User user = new User(name, login, password, role, email, city, country);
        store.update(oldLogin, user);
        addAllAttributesTo(req);
        req.getRequestDispatcher("/WEB-INF/views/UpdateUser.jsp").forward(req, resp);
    }
}


text:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const postSchema = new Schema({
  title: {
    type: String,
    required: true
  },
  content: {
    type: String,
    required: true
  },
  creator: {
    type: Schema.Types.ObjectId,
    ref: 'User',
    required: true
  }
});

module.exports = mongoose.model('Post', postSchema);

redpajama_set_name: RedPajamaGithub


text:
package algo;

import model.MySqlDriver;

import com.fasterxml.jackson.databind.JsonNode;

public class EmotionsManager {

	public static boolean sendEmotions(JsonNode obj) {

		JsonNode emotions = obj.findPath("EMOTIONS");
		String userId = obj.findPath("USER_ID").asText();

		try {
			if (emotions.isArray()) {
				for (JsonNode jsonNode : emotions) {
					char like = jsonNode.findPath("ACTION").asText().charAt(0);
					String placeId = jsonNode.findPath("PLACE_ID").asText();
					int googleType = jsonNode.findPath("GOOG_TYPE").asInt();
					MySqlDriver.setEmotion(userId, like, placeId, googleType);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

		return true;
	}
}


text:
using System;

using Oxide.Core.Plugins;

namespace Oxide.Game.RustLegacy
{
    /// <summary>
    /// Responsible for loading Rust Legacy core plugins
    /// </summary>
    public class RustLegacyPluginLoader : PluginLoader
    {
        public override Type[] CorePlugins => new[] { typeof(RustLegacyCore) };
    }
}


text:
/*
(Small) portions of this file have been modified by anandthkaker
(http://github.com/anandthakker)
*/

/*
 * Copyright (C) 2011 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

var debug = require('debug')('atom-debugger:backend');
exports.Backend = InspectorBackendClass;

/**
 * @constructor
 */
function InspectorBackendClass(agents)
{
    this._websocket = null;
    this._agents = agents || {};

    this._lastCallbackId = 1;
    this._pendingResponsesCount = 0;
    this._callbacks = {};
    this._domainDispatchers = {};
    this._eventArgs = {};
    this._replyArgs = {};
    this._hasErrorData = {};

    this.dumpInspectorTimeStats = false;
    this.dumpInspectorProtocolMessages = false;
    this._initialized = false;
}

InspectorBackendClass.prototype = {

    setWebSocket: function setWebSocket(ws) { this._websocket = ws; },
    getWebSocket: function getWebSocket() { return this._websocket; },
    sendMessageToBackend: function(message) {
      this._websocket.send(message);
    },

    /**
     * @return {number}
     */
    nextCallbackId: function()
    {
        return this._lastCallbackId++;
    },

    _wrap: function(callback, method)
    {
        var callbackId = this.nextCallbackId();
        if (!callback)
            callback = function() {};

        this._callbacks[callbackId] = callback;
        callback.methodName = method;
        if (this.dumpInspectorTimeStats)
            callback.sendRequestTime = Date.now();

        return callbackId;
    },

    _getAgent: function(domain)
    {
        var agentName = domain + "Agent";
        if (!this._agents[agentName])
            this._agents[agentName] = {};
        return this._agents[agentName];
    },

    registerCommand: function(method, signature, replyArgs, hasErrorData)
    {
        var domainAndMethod = method.split(".");
        var agent = this._getAgent(domainAndMethod[0]);

        agent[domainAndMethod[1]] = this._sendMessageToBackend.bind(this, method, signature);
        agent[domainAndMethod[1]]["invoke"] = this._invoke.bind(this, method, signature);
        this._replyArgs[method] = replyArgs;
        if (hasErrorData)
            this._hasErrorData[method] = true;

        this._initialized = true;
    },

    registerEnum: function(type, values)
    {
        var domainAndMethod = type.split(".");
        var agent = this._getAgent(domainAndMethod[0]);

        agent[domainAndMethod[1]] = values;

        this._initialized = true;
    },

    registerEvent: function(eventName, params)
    {
        this._eventArgs[eventName] = params;

        this._initialized = true;
    },

    _invoke: function(method, signature, args, callback)
    {
        this._wrapCallbackAndSendMessageObject(method, args, callback);
    },

    _sendMessageToBackend: function(method, signature, vararg)
    {
        var args = Array.prototype.slice.call(arguments, 2);
        debug('send message', method, signature, args);
        var callback = (args.length && typeof args[args.length - 1] === "function") ? args.pop() : null;

        var params = {};
        var hasParams = false;
        for (var i = 0; i < signature.length; ++i) {
            var param = signature[i];
            var paramName = param["name"];
            var typeName = param["type"];
            var optionalFlag = param["optional"];

            if (!args.length && !optionalFlag) {
                console.error("Protocol Error: Invalid number of arguments for method '" + method + "' call. It must have the following arguments '" + JSON.stringify(signature) + "'.");
                return;
            }

            var value = args.shift();
            if (optionalFlag && typeof value === "undefined") {
                continue;
            }

            if (typeof value !== typeName) {
                console.error("Protocol Error: Invalid type of argument '" + paramName + "' for method '" + method + "' call. It must be '" + typeName + "' but it is '" + typeof value + "'.");
                return;
            }

            params[paramName] = value;
            hasParams = true;
        }

        if (args.length === 1 && !callback) {
            if (typeof args[0] !== "undefined") {
                console.error("Protocol Error: Optional callback argument for method '" + method + "' call must be a function but its type is '" + typeof args[0] + "'.");
                return;
            }
        }

        this._wrapCallbackAndSendMessageObject(method, hasParams ? params : null, callback);
    },

    _wrapCallbackAndSendMessageObject: function(method, params, callback)
    {
        var messageObject = {};
        messageObject.method = method;
        if (params)
            messageObject.params = params;
        messageObject.id = this._wrap(callback, method);

        if (this.dumpInspectorProtocolMessages)
            console.log("frontend: " + JSON.stringify(messageObject));

        ++this._pendingResponsesCount;
        this.sendMessageObjectToBackend(messageObject);
    },

    sendMessageObjectToBackend: function(messageObject)
    {
        var message = JSON.stringify(messageObject);
        debug('request', messageObject);
        this.getWebSocket().send(message);
    },

    registerDomainDispatcher: function(domain, dispatcher)
    {
        this._domainDispatchers[domain] = dispatcher;
    },

    dispatch: function(message)
    {

        debug("dispatch", {message: message});

        var messageObject;
        try {
          messageObject = (typeof message === "string") ? JSON.parse(message) : message;
        } catch(e) {
          console.error(e);
          return;
        }

        if ("id" in messageObject) { // just a response for some request
            if (messageObject.error) {
                if (messageObject.error.code !== -32000)
                    this.reportProtocolError(messageObject);
            }

            var callback = this._callbacks[messageObject.id];
            if (callback) {
                var argumentsArray = [ null ];
                if (messageObject.error) {
                    argumentsArray[0] = messageObject.error.message;
                }
                if (this._hasErrorData[callback.methodName]) {
                    argumentsArray.push(null);
                    if (messageObject.error)
                        argumentsArray[1] = messageObject.error.data;
                }
                if (messageObject.result) {
                    var paramNames = this._replyArgs[callback.methodName];
                    if (paramNames) {
                        for (var i = 0; i < paramNames.length; ++i)
                            argumentsArray.push(messageObject.result[paramNames[i]]);
                    }
                }

                var processingStartTime;
                if (this.dumpInspectorTimeStats && callback.methodName)
                    processingStartTime = Date.now();

                callback.apply(null, argumentsArray);
                --this._pendingResponsesCount;
                delete this._callbacks[messageObject.id];

                if (this.dumpInspectorTimeStats && callback.methodName)
                    console.log("time-stats: " + callback.methodName + " = " + (processingStartTime - callback.sendRequestTime) + " + " + (Date.now() - processingStartTime));
            }

            if (this._scripts && !this._pendingResponsesCount)
                this.runAfterPendingDispatches();

            return;
        } else {
            var method = messageObject.method.split(".");
            var domainName = method[0];
            var functionName = method[1];
            if (!(domainName in this._domainDispatchers)) {
                console.error("Protocol Error: the message is for non-existing domain '" + domainName + "'");
                return;
            }
            var dispatcher = this._domainDispatchers[domainName];
            if (!(functionName in dispatcher)) {
                console.error("Protocol Error: Attempted to dispatch an unimplemented method '" + messageObject.method + "'");
                return;
            }

            if (!this._eventArgs[messageObject.method]) {
                console.error("Protocol Error: Attempted to dispatch an unspecified method '" + messageObject.method + "'");
                return;
            }

            var params = [];
            if (messageObject.params) {
                var paramNames = this._eventArgs[messageObject.method];
                for (var i = 0; i < paramNames.length; ++i)
                    params.push(messageObject.params[paramNames[i]]);
            }

            var processingStartTime;
            if (this.dumpInspectorTimeStats)
                processingStartTime = Date.now();

            dispatcher[functionName].apply(dispatcher, params);

            if (this.dumpInspectorTimeStats)
                console.log("time-stats: " + messageObject.method + " = " + (Date.now() - processingStartTime));
        }
    },

    reportProtocolError: function(messageObject)
    {
        console.error("Request with id = " + messageObject.id + " failed. " + messageObject.error);
    },

    /**
     * @param {string=} script
     */
    runAfterPendingDispatches: function(script)
    {
        if (!this._scripts)
            this._scripts = [];

        if (script)
            this._scripts.push(script);

        if (!this._pendingResponsesCount) {
            var scripts = this._scripts;
            this._scripts = []
            for (var id = 0; id < scripts.length; ++id)
                 scripts[id].call(this);
        }
    },

    loadFromJSONIfNeeded: function(jsonUrl)
    {
        if (this._initialized)
            return;

        var xhr = new XMLHttpRequest();
        xhr.open("GET", jsonUrl, false);
        xhr.send(null);

        var schema = JSON.parse(xhr.responseText);
        var code = InspectorBackendClass._generateCommands(schema);
        eval(code);
    }
}

/**
 * @param {*} schema
 * @return {string}
 */
InspectorBackendClass._generateCommands = function(schema) {
    var jsTypes = { integer: "number", array: "object" };
    var rawTypes = {};
    var result = [];

    var domains = schema["domains"] || [];
    for (var i = 0; i < domains.length; ++i) {
        var domain = domains[i];
        for (var j = 0; domain.types && j < domain.types.length; ++j) {
            var type = domain.types[j];
            rawTypes[domain.domain + "." + type.id] = jsTypes[type.type] || type.type;
        }
    }

    function toUpperCase(groupIndex, group0, group1)
    {
        return [group0, group1][groupIndex].toUpperCase();
    }
    function generateEnum(enumName, items)
    {
        var members = []
        for (var m = 0; m < items.length; ++m) {
            var value = items[m];
            var name = value.replace(/-(\w)/g, toUpperCase.bind(null, 1)).toTitleCase();
            name = name.replace(/HTML|XML|WML|API/ig, toUpperCase.bind(null, 0));
            members.push(name + ": \"" + value +"\"");
        }
        return "InspectorBackend.registerEnum(\"" + enumName + "\", {" + members.join(", ") + "});";
    }

    for (var i = 0; i < domains.length; ++i) {
        var domain = domains[i];

        var types = domain["types"] || [];
        for (var j = 0; j < types.length; ++j) {
            var type = types[j];
            if ((type["type"] === "string") && type["enum"])
                result.push(generateEnum(domain.domain + "." + type.id, type["enum"]));
            else if (type["type"] === "object") {
                var properties = type["properties"] || [];
                for (var k = 0; k < properties.length; ++k) {
                    var property = properties[k];
                    if ((property["type"] === "string") && property["enum"])
                        result.push(generateEnum(domain.domain + "." + type.id + property["name"].toTitleCase(), property["enum"]));
                }
            }
        }

        var commands = domain["commands"] || [];
        for (var j = 0; j < commands.length; ++j) {
            var command = commands[j];
            var parameters = command["parameters"];
            var paramsText = [];
            for (var k = 0; parameters && k < parameters.length; ++k) {
                var parameter = parameters[k];

                var type;
                if (parameter.type)
                    type = jsTypes[parameter.type] || parameter.type;
                else {
                    var ref = parameter["$ref"];
                    if (ref.indexOf(".") !== -1)
                        type = rawTypes[ref];
                    else
                        type = rawTypes[domain.domain + "." + ref];
                }

                var text = "{\"name\": \"" + parameter.name + "\", \"type\": \"" + type + "\", \"optional\": " + (parameter.optional ? "true" : "false") + "}";
                paramsText.push(text);
            }

            var returnsText = [];
            var returns = command["returns"] || [];
            for (var k = 0; k < returns.length; ++k) {
                var parameter = returns[k];
                returnsText.push("\"" + parameter.name + "\"");
            }
            var hasErrorData = String(Boolean(command.error));
            result.push("InspectorBackend.registerCommand(\"" + domain.domain + "." + command.name + "\", [" + paramsText.join(", ") + "], [" + returnsText.join(", ") + "], " + hasErrorData + ");");
        }

        for (var j = 0; domain.events && j < domain.events.length; ++j) {
            var event = domain.events[j];
            var paramsText = [];
            for (var k = 0; event.parameters && k < event.parameters.length; ++k) {
                var parameter = event.parameters[k];
                paramsText.push("\"" + parameter.name + "\"");
            }
            result.push("InspectorBackend.registerEvent(\"" + domain.domain + "." + event.name + "\", [" + paramsText.join(", ") + "]);");
        }

        result.push("InspectorBackend.register" + domain.domain + "Dispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, \"" + domain.domain + "\");");
    }
    return result.join("\n");
}


text:
import { Component, OnInit } from '@angular/core';
import { GeolocationService } from '../geolocation.service';
import { Router } from '@angular/router';

@Component({
  selector: 'app-reservation',
  templateUrl: './reservation.component.html',
  styleUrls: ['./reservation.component.css'],
  providers: [
    GeolocationService
  ]
})
export class ReservationComponent implements OnInit {

  city: String = '';
  price: number = 0;
  numberOfPeople: number = 2;
  numberOfRooms: number = 1;

  constructor(private geolocationService: GeolocationService,
  private router: Router) {}

  onInputNumberOfPeopleChange(event: Event): void {
    this.numberOfPeople = +event;
    this.price = (this.numberOfPeople * this.numberOfRooms) * 30;
  }

  onInputNumberOfRoomsChange(event: Event): void {
    this.numberOfRooms = +event;
    this.price = (this.numberOfPeople * this.numberOfRooms) * 30;
  }

  redirectToRooms() {
    this.router.navigate(['./rooms', this.numberOfRooms,this.numberOfPeople,
      this.price, this.city
    ]);
  }

  ngOnInit() {
    this.geolocationService.getInfoByGeolocation().subscribe(
      data => this.city = data.city
    )

    this.price = (this.numberOfPeople * this.numberOfRooms) * 30;
  }

}


text:
/** @file  Importer.cpp
 *  @brief Implementation of the CPP-API class #Importer
 */

#include <assimp/version.h>
#include <assimp/config.h>
#include <assimp/importerdesc.h>

// ------------------------------------------------------------------------------------------------
/* Uncomment this line to prevent Assimp from catching unknown exceptions.
 *
 * Note that any Exception except DeadlyImportError may lead to
 * undefined behaviour -> loaders could remain in an unusable state and
 * further imports with the same Importer instance could fail/crash/burn ...
 */
// ------------------------------------------------------------------------------------------------
#ifndef ASSIMP_BUILD_DEBUG
#   define ASSIMP_CATCH_GLOBAL_EXCEPTIONS
#endif

// ------------------------------------------------------------------------------------------------
// Internal headers
// ------------------------------------------------------------------------------------------------
#include "Common/Importer.h"
#include "Common/BaseProcess.h"
#include "Common/DefaultProgressHandler.h"
#include "PostProcessing/ProcessHelper.h"
#include "Common/ScenePreprocessor.h"
#include "Common/ScenePrivate.h"

#include <assimp/BaseImporter.h>
#include <assimp/GenericProperty.h>
#include <assimp/MemoryIOWrapper.h>
#include <assimp/Profiler.h>
#include <assimp/TinyFormatter.h>
#include <assimp/Exceptional.h>
#include <assimp/Profiler.h>
#include <assimp/commonMetaData.h>

#include <set>
#include <memory>
#include <cctype>

#include <assimp/DefaultIOStream.h>
#include <assimp/DefaultIOSystem.h>

#ifndef ASSIMP_BUILD_NO_VALIDATEDS_PROCESS
#   include "PostProcessing/ValidateDataStructure.h"
#endif

using namespace Assimp::Profiling;
using namespace Assimp::Formatter;

namespace Assimp {
    // ImporterRegistry.cpp
    void GetImporterInstanceList(std::vector< BaseImporter* >& out);
	void DeleteImporterInstanceList(std::vector< BaseImporter* >& out);

    // PostStepRegistry.cpp
    void GetPostProcessingStepInstanceList(std::vector< BaseProcess* >& out);
}

using namespace Assimp;
using namespace Assimp::Intern;

// ------------------------------------------------------------------------------------------------
// Intern::AllocateFromAssimpHeap serves as abstract base class. It overrides
// new and delete (and their array counterparts) of public API classes (e.g. Logger) to
// utilize our DLL heap.
// See http://www.gotw.ca/publications/mill15.htm
// ------------------------------------------------------------------------------------------------
void* AllocateFromAssimpHeap::operator new ( size_t num_bytes)  {
    return ::operator new(num_bytes);
}

void* AllocateFromAssimpHeap::operator new ( size_t num_bytes, const std::nothrow_t& ) throw()  {
    try {
        return AllocateFromAssimpHeap::operator new( num_bytes );
    }
    catch( ... )    {
        return nullptr;
    }
}

void AllocateFromAssimpHeap::operator delete ( void* data)  {
    return ::operator delete(data);
}

void* AllocateFromAssimpHeap::operator new[] ( size_t num_bytes)    {
    return ::operator new[](num_bytes);
}

void* AllocateFromAssimpHeap::operator new[] ( size_t num_bytes, const std::nothrow_t& ) throw() {
    try {
        return AllocateFromAssimpHeap::operator new[]( num_bytes );
    } catch( ... )    {
        return nullptr;
    }
}

void AllocateFromAssimpHeap::operator delete[] ( void* data)    {
    return ::operator delete[](data);
}

// ------------------------------------------------------------------------------------------------
// Importer constructor.
Importer::Importer()
 : pimpl( new ImporterPimpl ) {
    pimpl->mScene = nullptr;
    pimpl->mErrorString = "";

    // Allocate a default IO handler
    pimpl->mIOHandler = new DefaultIOSystem;
    pimpl->mIsDefaultHandler = true;
    pimpl->bExtraVerbose     = false; // disable extra verbose mode by default

    pimpl->mProgressHandler = new DefaultProgressHandler();
    pimpl->mIsDefaultProgressHandler = true;

    GetImporterInstanceList(pimpl->mImporter);
    GetPostProcessingStepInstanceList(pimpl->mPostProcessingSteps);

    // Allocate a SharedPostProcessInfo object and store pointers to it in all post-process steps in the list.
    pimpl->mPPShared = new SharedPostProcessInfo();
    for (std::vector<BaseProcess*>::iterator it =  pimpl->mPostProcessingSteps.begin();
        it != pimpl->mPostProcessingSteps.end();
        ++it)   {

        (*it)->SetSharedData(pimpl->mPPShared);
    }
}

// ------------------------------------------------------------------------------------------------
// Destructor of Importer
Importer::~Importer() {
    // Delete all import plugins
	DeleteImporterInstanceList(pimpl->mImporter);

    // Delete all post-processing plug-ins
    for( unsigned int a = 0; a < pimpl->mPostProcessingSteps.size(); ++a ) {
        delete pimpl->mPostProcessingSteps[a];
    }

    // Delete the assigned IO and progress handler
    delete pimpl->mIOHandler;
    delete pimpl->mProgressHandler;

    // Kill imported scene. Destructor's should do that recursively
    delete pimpl->mScene;

    // Delete shared post-processing data
    delete pimpl->mPPShared;

    // and finally the pimpl itself
    delete pimpl;
}

// ------------------------------------------------------------------------------------------------
// Register a custom post-processing step
aiReturn Importer::RegisterPPStep(BaseProcess* pImp) {
    ai_assert( nullptr != pImp );

    ASSIMP_BEGIN_EXCEPTION_REGION();

        pimpl->mPostProcessingSteps.push_back(pImp);
        ASSIMP_LOG_INFO("Registering custom post-processing step");

    ASSIMP_END_EXCEPTION_REGION(aiReturn);
    return AI_SUCCESS;
}

// ------------------------------------------------------------------------------------------------
// Register a custom loader plugin
aiReturn Importer::RegisterLoader(BaseImporter* pImp) {
    ai_assert(nullptr != pImp);

    ASSIMP_BEGIN_EXCEPTION_REGION();

    // --------------------------------------------------------------------
    // Check whether we would have two loaders for the same file extension
    // This is absolutely OK, but we should warn the developer of the new
    // loader that his code will probably never be called if the first
    // loader is a bit too lazy in his file checking.
    // --------------------------------------------------------------------
    std::set<std::string> st;
    std::string baked;
    pImp->GetExtensionList(st);

    for(std::set<std::string>::const_iterator it = st.begin(); it != st.end(); ++it) {

#ifdef ASSIMP_BUILD_DEBUG
        if (IsExtensionSupported(*it)) {
            ASSIMP_LOG_WARN_F("The file extension ", *it, " is already in use");
        }
#endif
        baked += *it;
    }

    // add the loader
    pimpl->mImporter.push_back(pImp);
    ASSIMP_LOG_INFO_F("Registering custom importer for these file extensions: ", baked);
    ASSIMP_END_EXCEPTION_REGION(aiReturn);

    return AI_SUCCESS;
}

// ------------------------------------------------------------------------------------------------
// Unregister a custom loader plugin
aiReturn Importer::UnregisterLoader(BaseImporter* pImp) {
    if(!pImp) {
        // unregistering a NULL importer is no problem for us ... really!
        return AI_SUCCESS;
    }

    ASSIMP_BEGIN_EXCEPTION_REGION();
    std::vector<BaseImporter*>::iterator it = std::find(pimpl->mImporter.begin(),
        pimpl->mImporter.end(),pImp);

    if (it != pimpl->mImporter.end())   {
        pimpl->mImporter.erase(it);
        ASSIMP_LOG_INFO("Unregistering custom importer: ");
        return AI_SUCCESS;
    }
    ASSIMP_LOG_WARN("Unable to remove custom importer: I can't find you ...");
    ASSIMP_END_EXCEPTION_REGION(aiReturn);

    return AI_FAILURE;
}

// ------------------------------------------------------------------------------------------------
// Unregister a custom loader plugin
aiReturn Importer::UnregisterPPStep(BaseProcess* pImp) {
    if(!pImp) {
        // unregistering a NULL ppstep is no problem for us ... really!
        return AI_SUCCESS;
    }

    ASSIMP_BEGIN_EXCEPTION_REGION();
    std::vector<BaseProcess*>::iterator it = std::find(pimpl->mPostProcessingSteps.begin(),
        pimpl->mPostProcessingSteps.end(),pImp);

    if (it != pimpl->mPostProcessingSteps.end())    {
        pimpl->mPostProcessingSteps.erase(it);
        ASSIMP_LOG_INFO("Unregistering custom post-processing step");
        return AI_SUCCESS;
    }
    ASSIMP_LOG_WARN("Unable to remove custom post-processing step: I can't find you ..");
    ASSIMP_END_EXCEPTION_REGION(aiReturn);

    return AI_FAILURE;
}

// ------------------------------------------------------------------------------------------------
// Supplies a custom IO handler to the importer to open and access files.
void Importer::SetIOHandler( IOSystem* pIOHandler) {
    ai_assert(nullptr != pimpl);

    ASSIMP_BEGIN_EXCEPTION_REGION();
    // If the new handler is zero, allocate a default IO implementation.
    if (!pIOHandler) {
        // Release pointer in the possession of the caller
        pimpl->mIOHandler = new DefaultIOSystem();
        pimpl->mIsDefaultHandler = true;
    } else if (pimpl->mIOHandler != pIOHandler) { // Otherwise register the custom handler
        delete pimpl->mIOHandler;
        pimpl->mIOHandler = pIOHandler;
        pimpl->mIsDefaultHandler = false;
    }
    ASSIMP_END_EXCEPTION_REGION(void);
}

// ------------------------------------------------------------------------------------------------
// Get the currently set IO handler
IOSystem* Importer::GetIOHandler() const {
    ai_assert(nullptr != pimpl);

    return pimpl->mIOHandler;
}

// ------------------------------------------------------------------------------------------------
// Check whether a custom IO handler is currently set
bool Importer::IsDefaultIOHandler() const {
    ai_assert(nullptr != pimpl);

    return pimpl->mIsDefaultHandler;
}

// ------------------------------------------------------------------------------------------------
// Supplies a custom progress handler to get regular callbacks during importing
void Importer::SetProgressHandler ( ProgressHandler* pHandler ) {
    ai_assert(nullptr != pimpl);

    ASSIMP_BEGIN_EXCEPTION_REGION();

    // If the new handler is zero, allocate a default implementation.
    if (!pHandler) {
        // Release pointer in the possession of the caller
        pimpl->mProgressHandler = new DefaultProgressHandler();
        pimpl->mIsDefaultProgressHandler = true;
    } else if (pimpl->mProgressHandler != pHandler) { // Otherwise register the custom handler
        delete pimpl->mProgressHandler;
        pimpl->mProgressHandler = pHandler;
        pimpl->mIsDefaultProgressHandler = false;
    }
    ASSIMP_END_EXCEPTION_REGION(void);
}

// ------------------------------------------------------------------------------------------------
// Get the currently set progress handler
ProgressHandler* Importer::GetProgressHandler() const {
    ai_assert(nullptr != pimpl);

    return pimpl->mProgressHandler;
}

// ------------------------------------------------------------------------------------------------
// Check whether a custom progress handler is currently set
bool Importer::IsDefaultProgressHandler() const {
    ai_assert(nullptr != pimpl);

    return pimpl->mIsDefaultProgressHandler;
}

// ------------------------------------------------------------------------------------------------
// Validate post process step flags
bool _ValidateFlags(unsigned int pFlags) {
    if (pFlags & aiProcess_GenSmoothNormals && pFlags & aiProcess_GenNormals)   {
        ASSIMP_LOG_ERROR("#aiProcess_GenSmoothNormals and #aiProcess_GenNormals are incompatible");
        return false;
    }
    if (pFlags & aiProcess_OptimizeGraph && pFlags & aiProcess_PreTransformVertices)    {
        ASSIMP_LOG_ERROR("#aiProcess_OptimizeGraph and #aiProcess_PreTransformVertices are incompatible");
        return false;
    }
    return true;
}

// ------------------------------------------------------------------------------------------------
// Free the current scene
void Importer::FreeScene( ) {
    ai_assert(nullptr != pimpl);

    ASSIMP_BEGIN_EXCEPTION_REGION();

    delete pimpl->mScene;
    pimpl->mScene = nullptr;

    pimpl->mErrorString = "";
    ASSIMP_END_EXCEPTION_REGION(void);
}

// ------------------------------------------------------------------------------------------------
// Get the current error string, if any
const char* Importer::GetErrorString() const {
    ai_assert(nullptr != pimpl);

    // Must remain valid as long as ReadFile() or FreeFile() are not called
    return pimpl->mErrorString.c_str();
}

// ------------------------------------------------------------------------------------------------
// Enable extra-verbose mode
void Importer::SetExtraVerbose(bool bDo) {
    ai_assert(nullptr != pimpl);

    pimpl->bExtraVerbose = bDo;
}

// ------------------------------------------------------------------------------------------------
// Get the current scene
const aiScene* Importer::GetScene() const {
    ai_assert(nullptr != pimpl);

    return pimpl->mScene;
}

// ------------------------------------------------------------------------------------------------
// Orphan the current scene and return it.
aiScene* Importer::GetOrphanedScene() {
    ai_assert(nullptr != pimpl);

    aiScene* s = pimpl->mScene;

    ASSIMP_BEGIN_EXCEPTION_REGION();
    pimpl->mScene = nullptr;

    pimpl->mErrorString = ""; // reset error string
    ASSIMP_END_EXCEPTION_REGION(aiScene*);

    return s;
}

// ------------------------------------------------------------------------------------------------
// Validate post-processing flags
bool Importer::ValidateFlags(unsigned int pFlags) const {
    ASSIMP_BEGIN_EXCEPTION_REGION();
    // run basic checks for mutually exclusive flags
    if(!_ValidateFlags(pFlags)) {
        return false;
    }

    // ValidateDS does not anymore occur in the pp list, it plays an awesome extra role ...
#ifdef ASSIMP_BUILD_NO_VALIDATEDS_PROCESS
    if (pFlags & aiProcess_ValidateDataStructure) {
        return false;
    }
#endif
    pFlags &= ~aiProcess_ValidateDataStructure;

    // Now iterate through all bits which are set in the flags and check whether we find at least
    // one pp plugin which handles it.
    for (unsigned int mask = 1; mask < (1u << (sizeof(unsigned int)*8-1));mask <<= 1) {

        if (pFlags & mask) {

            bool have = false;
            for( unsigned int a = 0; a < pimpl->mPostProcessingSteps.size(); a++)   {
                if (pimpl->mPostProcessingSteps[a]-> IsActive(mask) ) {

                    have = true;
                    break;
                }
            }
            if (!have) {
                return false;
            }
        }
    }
    ASSIMP_END_EXCEPTION_REGION(bool);
    return true;
}

// ------------------------------------------------------------------------------------------------
const aiScene* Importer::ReadFileFromMemory( const void* pBuffer,
    size_t pLength,
    unsigned int pFlags,
    const char* pHint /*= ""*/) {
    ai_assert(nullptr != pimpl);

    ASSIMP_BEGIN_EXCEPTION_REGION();
    if (!pHint) {
        pHint = "";
    }

    if (!pBuffer || !pLength || strlen(pHint) > MaxLenHint ) {
        pimpl->mErrorString = "Invalid parameters passed to ReadFileFromMemory()";
        return nullptr;
    }

    // prevent deletion of the previous IOHandler
    IOSystem* io = pimpl->mIOHandler;
    pimpl->mIOHandler = nullptr;

    SetIOHandler(new MemoryIOSystem((const uint8_t*)pBuffer,pLength,io));

    // read the file and recover the previous IOSystem
    static const size_t BufSize(Importer::MaxLenHint + 28);
    char fbuff[BufSize];
    ai_snprintf(fbuff, BufSize, "%s.%s",AI_MEMORYIO_MAGIC_FILENAME,pHint);

    ReadFile(fbuff,pFlags);
    SetIOHandler(io);

    ASSIMP_END_EXCEPTION_REGION_WITH_ERROR_STRING(const aiScene*, pimpl->mErrorString);
    return pimpl->mScene;
}

// ------------------------------------------------------------------------------------------------
void WriteLogOpening(const std::string& file) {

    ASSIMP_LOG_INFO_F("Load ", file);

    // print a full version dump. This is nice because we don't
    // need to ask the authors of incoming bug reports for
    // the library version they're using - a log dump is
    // sufficient.
    const unsigned int flags( aiGetCompileFlags() );
    std::stringstream stream;
    stream << "Assimp " << aiGetVersionMajor() << "." << aiGetVersionMinor() << "." << aiGetVersionRevision() << " "
#if defined(ASSIMP_BUILD_ARCHITECTURE)
        << ASSIMP_BUILD_ARCHITECTURE
#elif defined(_M_IX86) || defined(__x86_32__) || defined(__i386__)
        << "x86"
#elif defined(_M_X64) || defined(__x86_64__)
        << "amd64"
#elif defined(_M_IA64) || defined(__ia64__)
        << "itanium"
#elif defined(__ppc__) || defined(__powerpc__)
        << "ppc32"
#elif defined(__powerpc64__)
        << "ppc64"
#elif defined(__arm__)
        << "arm"
#else
        << "<unknown architecture>"
#endif
        << " "
#if defined(ASSIMP_BUILD_COMPILER)
        << ( ASSIMP_BUILD_COMPILER )
#elif defined(_MSC_VER)
        << "msvc"
#elif defined(__GNUC__)
        << "gcc"
#else
        << "<unknown compiler>"
#endif

#ifdef ASSIMP_BUILD_DEBUG
        << " debug"
#endif

        << (flags & ASSIMP_CFLAGS_NOBOOST ? " noboost" : "")
        << (flags & ASSIMP_CFLAGS_SHARED  ? " shared" : "")
        << (flags & ASSIMP_CFLAGS_SINGLETHREADED  ? " singlethreaded" : "");

        ASSIMP_LOG_DEBUG(stream.str());
}

// ------------------------------------------------------------------------------------------------
// Reads the given file and returns its contents if successful.
const aiScene* Importer::ReadFile( const char* _pFile, unsigned int pFlags) {
    ai_assert(nullptr != pimpl);

    ASSIMP_BEGIN_EXCEPTION_REGION();
    const std::string pFile(_pFile);

    // ----------------------------------------------------------------------
    // Put a large try block around everything to catch all std::exception's
    // that might be thrown by STL containers or by new().
    // ImportErrorException's are throw by ourselves and caught elsewhere.
    //-----------------------------------------------------------------------

    WriteLogOpening(pFile);

#ifdef ASSIMP_CATCH_GLOBAL_EXCEPTIONS
    try
#endif // ! ASSIMP_CATCH_GLOBAL_EXCEPTIONS
    {
        // Check whether this Importer instance has already loaded
        // a scene. In this case we need to delete the old one
        if (pimpl->mScene)  {

            ASSIMP_LOG_DEBUG("(Deleting previous scene)");
            FreeScene();
        }

        // First check if the file is accessible at all
        if( !pimpl->mIOHandler->Exists( pFile)) {

            pimpl->mErrorString = "Unable to open file \"" + pFile + "\".";
            ASSIMP_LOG_ERROR(pimpl->mErrorString);
            return nullptr;
        }

        std::unique_ptr<Profiler> profiler(GetPropertyInteger(AI_CONFIG_GLOB_MEASURE_TIME,0)?new Profiler():NULL);
        if (profiler) {
            profiler->BeginRegion("total");
        }

        // Find an worker class which can handle the file
        BaseImporter* imp = nullptr;
        SetPropertyInteger("importerIndex", -1);
        for( unsigned int a = 0; a < pimpl->mImporter.size(); a++)  {

            if( pimpl->mImporter[a]->CanRead( pFile, pimpl->mIOHandler, false)) {
                imp = pimpl->mImporter[a];
                SetPropertyInteger("importerIndex", a);
                break;
            }
        }

        if (!imp)   {
            // not so bad yet ... try format auto detection.
            const std::string::size_type s = pFile.find_last_of('.');
            if (s != std::string::npos) {
                ASSIMP_LOG_INFO("File extension not known, trying signature-based detection");
                for( unsigned int a = 0; a < pimpl->mImporter.size(); a++)  {
                    if( pimpl->mImporter[a]->CanRead( pFile, pimpl->mIOHandler, true)) {
                        imp = pimpl->mImporter[a];
                        SetPropertyInteger("importerIndex", a);
                        break;
                    }
                }
            }
            // Put a proper error message if no suitable importer was found
            if( !imp)   {
                pimpl->mErrorString = "No suitable reader found for the file format of file \"" + pFile + "\".";
                ASSIMP_LOG_ERROR(pimpl->mErrorString);
                return nullptr;
            }
        }

        // Get file size for progress handler
        IOStream * fileIO = pimpl->mIOHandler->Open( pFile );
        uint32_t fileSize = 0;
        if (fileIO)
        {
            fileSize = static_cast<uint32_t>(fileIO->FileSize());
            pimpl->mIOHandler->Close( fileIO );
        }

        // Dispatch the reading to the worker class for this format
        const aiImporterDesc *desc( imp->GetInfo() );
        std::string ext( "unknown" );
        if ( nullptr != desc ) {
            ext = desc->mName;
        }
        ASSIMP_LOG_INFO("Found a matching importer for this file format: " + ext + "." );
        pimpl->mProgressHandler->UpdateFileRead( 0, fileSize );

        if (profiler) {
            profiler->BeginRegion("import");
        }

        pimpl->mScene = imp->ReadFile( this, pFile, pimpl->mIOHandler);
        pimpl->mProgressHandler->UpdateFileRead( fileSize, fileSize );

        if (profiler) {
            profiler->EndRegion("import");
        }

        SetPropertyString("sourceFilePath", pFile);

        // If successful, apply all active post processing steps to the imported data
        if( pimpl->mScene)  {
            if (!pimpl->mScene->mMetaData || !pimpl->mScene->mMetaData->HasKey(AI_METADATA_SOURCE_FORMAT)) {
                if (!pimpl->mScene->mMetaData) {
                    pimpl->mScene->mMetaData = new aiMetadata;
                }
                pimpl->mScene->mMetaData->Add(AI_METADATA_SOURCE_FORMAT, aiString(ext));
            }

#ifndef ASSIMP_BUILD_NO_VALIDATEDS_PROCESS
            // The ValidateDS process is an exception. It is executed first, even before ScenePreprocessor is called.
            if (pFlags & aiProcess_ValidateDataStructure) {
                ValidateDSProcess ds;
                ds.ExecuteOnScene (this);
                if (!pimpl->mScene) {
                    return nullptr;
                }
            }
#endif // no validation

            // Preprocess the scene and prepare it for post-processing
            if (profiler) {
                profiler->BeginRegion("preprocess");
            }

            ScenePreprocessor pre(pimpl->mScene);
            pre.ProcessScene();

            if (profiler) {
                profiler->EndRegion("preprocess");
            }

            // Ensure that the validation process won't be called twice
            ApplyPostProcessing(pFlags & (~aiProcess_ValidateDataStructure));
        }
        // if failed, extract the error string
        else if( !pimpl->mScene) {
            pimpl->mErrorString = imp->GetErrorText();
        }

        // clear any data allocated by post-process steps
        pimpl->mPPShared->Clean();

        if (profiler) {
            profiler->EndRegion("total");
        }
    }
#ifdef ASSIMP_CATCH_GLOBAL_EXCEPTIONS
    catch (std::exception &e) {
#if (defined _MSC_VER) &&   (defined _CPPRTTI)
        // if we have RTTI get the full name of the exception that occurred
        pimpl->mErrorString = std::string(typeid( e ).name()) + ": " + e.what();
#else
        pimpl->mErrorString = std::string("std::exception: ") + e.what();
#endif

        ASSIMP_LOG_ERROR(pimpl->mErrorString);
        delete pimpl->mScene; pimpl->mScene = nullptr;
    }
#endif // ! ASSIMP_CATCH_GLOBAL_EXCEPTIONS

    // either successful or failure - the pointer expresses it anyways
    ASSIMP_END_EXCEPTION_REGION_WITH_ERROR_STRING(const aiScene*, pimpl->mErrorString);

    return pimpl->mScene;
}

// ------------------------------------------------------------------------------------------------
// Apply post-processing to the currently bound scene
const aiScene* Importer::ApplyPostProcessing(unsigned int pFlags) {
    ai_assert(nullptr != pimpl);

    ASSIMP_BEGIN_EXCEPTION_REGION();
    // Return immediately if no scene is active
    if (!pimpl->mScene) {
        return nullptr;
    }

    // If no flags are given, return the current scene with no further action
    if (!pFlags) {
        return pimpl->mScene;
    }

    // In debug builds: run basic flag validation
    ai_assert(_ValidateFlags(pFlags));
    ASSIMP_LOG_INFO("Entering post processing pipeline");

#ifndef ASSIMP_BUILD_NO_VALIDATEDS_PROCESS
    // The ValidateDS process plays an exceptional role. It isn't contained in the global
    // list of post-processing steps, so we need to call it manually.
    if (pFlags & aiProcess_ValidateDataStructure) {
        ValidateDSProcess ds;
        ds.ExecuteOnScene (this);
        if (!pimpl->mScene) {
            return nullptr;
        }
    }
#endif // no validation
#ifdef ASSIMP_BUILD_DEBUG
    if (pimpl->bExtraVerbose)
    {
#ifdef ASSIMP_BUILD_NO_VALIDATEDS_PROCESS
        ASSIMP_LOG_ERROR("Verbose Import is not available due to build settings");
#endif  // no validation
        pFlags |= aiProcess_ValidateDataStructure;
    }
#else
    if (pimpl->bExtraVerbose) {
        ASSIMP_LOG_WARN("Not a debug build, ignoring extra verbose setting");
    }
#endif // ! DEBUG

    std::unique_ptr<Profiler> profiler(GetPropertyInteger(AI_CONFIG_GLOB_MEASURE_TIME,0)?new Profiler():NULL);
    for( unsigned int a = 0; a < pimpl->mPostProcessingSteps.size(); a++)   {
        BaseProcess* process = pimpl->mPostProcessingSteps[a];
        pimpl->mProgressHandler->UpdatePostProcess(static_cast<int>(a), static_cast<int>(pimpl->mPostProcessingSteps.size()) );
        if( process->IsActive( pFlags)) {
            if (profiler) {
                profiler->BeginRegion("postprocess");
            }

            process->ExecuteOnScene ( this );

            if (profiler) {
                profiler->EndRegion("postprocess");
            }
        }
        if( !pimpl->mScene) {
            break;
        }
#ifdef ASSIMP_BUILD_DEBUG

#ifdef ASSIMP_BUILD_NO_VALIDATEDS_PROCESS
        continue;
#endif  // no validation

        // If the extra verbose mode is active, execute the ValidateDataStructureStep again - after each step
        if (pimpl->bExtraVerbose)   {
            ASSIMP_LOG_DEBUG("Verbose Import: re-validating data structures");

            ValidateDSProcess ds;
            ds.ExecuteOnScene (this);
            if( !pimpl->mScene) {
                ASSIMP_LOG_ERROR("Verbose Import: failed to re-validate data structures");
                break;
            }
        }
#endif // ! DEBUG
    }
    pimpl->mProgressHandler->UpdatePostProcess( static_cast<int>(pimpl->mPostProcessingSteps.size()),
        static_cast<int>(pimpl->mPostProcessingSteps.size()) );

    // update private scene flags
    if( pimpl->mScene ) {
      ScenePriv(pimpl->mScene)->mPPStepsApplied |= pFlags;
    }

    // clear any data allocated by post-process steps
    pimpl->mPPShared->Clean();
    ASSIMP_LOG_INFO("Leaving post processing pipeline");

    ASSIMP_END_EXCEPTION_REGION(const aiScene*);

    return pimpl->mScene;
}

// ------------------------------------------------------------------------------------------------
const aiScene* Importer::ApplyCustomizedPostProcessing( BaseProcess *rootProcess, bool requestValidation ) {
    ai_assert(nullptr != pimpl);

    ASSIMP_BEGIN_EXCEPTION_REGION();

    // Return immediately if no scene is active
    if ( nullptr == pimpl->mScene ) {
        return nullptr;
    }

    // If no flags are given, return the current scene with no further action
    if ( NULL == rootProcess ) {
        return pimpl->mScene;
    }

    // In debug builds: run basic flag validation
    ASSIMP_LOG_INFO( "Entering customized post processing pipeline" );

#ifndef ASSIMP_BUILD_NO_VALIDATEDS_PROCESS
    // The ValidateDS process plays an exceptional role. It isn't contained in the global
    // list of post-processing steps, so we need to call it manually.
    if ( requestValidation )
    {
        ValidateDSProcess ds;
        ds.ExecuteOnScene( this );
        if ( !pimpl->mScene ) {
            return nullptr;
        }
    }
#endif // no validation
#ifdef ASSIMP_BUILD_DEBUG
    if ( pimpl->bExtraVerbose )
    {
#ifdef ASSIMP_BUILD_NO_VALIDATEDS_PROCESS
        ASSIMP_LOG_ERROR( "Verbose Import is not available due to build settings" );
#endif  // no validation
    }
#else
    if ( pimpl->bExtraVerbose ) {
        ASSIMP_LOG_WARN( "Not a debug build, ignoring extra verbose setting" );
    }
#endif // ! DEBUG

    std::unique_ptr<Profiler> profiler( GetPropertyInteger( AI_CONFIG_GLOB_MEASURE_TIME, 0 ) ? new Profiler() : NULL );

    if ( profiler ) {
        profiler->BeginRegion( "postprocess" );
    }

    rootProcess->ExecuteOnScene( this );

    if ( profiler ) {
        profiler->EndRegion( "postprocess" );
    }

    // If the extra verbose mode is active, execute the ValidateDataStructureStep again - after each step
    if ( pimpl->bExtraVerbose || requestValidation  ) {
        ASSIMP_LOG_DEBUG( "Verbose Import: revalidating data structures" );

        ValidateDSProcess ds;
        ds.ExecuteOnScene( this );
        if ( !pimpl->mScene ) {
            ASSIMP_LOG_ERROR( "Verbose Import: failed to revalidate data structures" );
        }
    }

    // clear any data allocated by post-process steps
    pimpl->mPPShared->Clean();
    ASSIMP_LOG_INFO( "Leaving customized post processing pipeline" );

    ASSIMP_END_EXCEPTION_REGION( const aiScene* );

    return pimpl->mScene;
}

// ------------------------------------------------------------------------------------------------
// Helper function to check whether an extension is supported by ASSIMP
bool Importer::IsExtensionSupported(const char* szExtension) const {
    return nullptr != GetImporter(szExtension);
}

// ------------------------------------------------------------------------------------------------
size_t Importer::GetImporterCount() const {
    ai_assert(nullptr != pimpl);

    return pimpl->mImporter.size();
}

// ------------------------------------------------------------------------------------------------
const aiImporterDesc* Importer::GetImporterInfo(size_t index) const {
    ai_assert(nullptr != pimpl);

    if (index >= pimpl->mImporter.size()) {
        return nullptr;
    }
    return pimpl->mImporter[index]->GetInfo();
}

// ------------------------------------------------------------------------------------------------
BaseImporter* Importer::GetImporter (size_t index) const {
    ai_assert(nullptr != pimpl);

    if (index >= pimpl->mImporter.size()) {
        return nullptr;
    }
    return pimpl->mImporter[index];
}

// ------------------------------------------------------------------------------------------------
// Find a loader plugin for a given file extension
BaseImporter* Importer::GetImporter (const char* szExtension) const {
    ai_assert(nullptr != pimpl);

    return GetImporter(GetImporterIndex(szExtension));
}

// ------------------------------------------------------------------------------------------------
// Find a loader plugin for a given file extension
size_t Importer::GetImporterIndex (const char* szExtension) const {
    ai_assert(nullptr != pimpl);
    ai_assert(nullptr != szExtension);

    ASSIMP_BEGIN_EXCEPTION_REGION();

    // skip over wildcard and dot characters at string head --
    for ( ; *szExtension == '*' || *szExtension == '.'; ++szExtension );

    std::string ext(szExtension);
    if (ext.empty()) {
        return static_cast<size_t>(-1);
    }
    std::transform( ext.begin(), ext.end(), ext.begin(), ToLower<char> );

    std::set<std::string> str;
    for (std::vector<BaseImporter*>::const_iterator i =  pimpl->mImporter.begin();i != pimpl->mImporter.end();++i)  {
        str.clear();

        (*i)->GetExtensionList(str);
        for (std::set<std::string>::const_iterator it = str.begin(); it != str.end(); ++it) {
            if (ext == *it) {
                return std::distance(static_cast< std::vector<BaseImporter*>::const_iterator >(pimpl->mImporter.begin()), i);
            }
        }
    }
    ASSIMP_END_EXCEPTION_REGION(size_t);
    return static_cast<size_t>(-1);
}

// ------------------------------------------------------------------------------------------------
// Helper function to build a list of all file extensions supported by ASSIMP
void Importer::GetExtensionList(aiString& szOut) const {
    ai_assert(nullptr != pimpl);

    ASSIMP_BEGIN_EXCEPTION_REGION();
    std::set<std::string> str;
    for (std::vector<BaseImporter*>::const_iterator i =  pimpl->mImporter.begin();i != pimpl->mImporter.end();++i)  {
        (*i)->GetExtensionList(str);
    }

	// List can be empty
	if( !str.empty() ) {
		for (std::set<std::string>::const_iterator it = str.begin();; ) {
			szOut.Append("*.");
			szOut.Append((*it).c_str());

			if (++it == str.end()) {
				break;
			}
			szOut.Append(";");
		}
	}
    ASSIMP_END_EXCEPTION_REGION(void);
}

// ------------------------------------------------------------------------------------------------
// Set a configuration property
bool Importer::SetPropertyInteger(const char* szName, int iValue) {
    ai_assert(nullptr != pimpl);

    bool existing;
    ASSIMP_BEGIN_EXCEPTION_REGION();
        existing = SetGenericProperty<int>(pimpl->mIntProperties, szName,iValue);
    ASSIMP_END_EXCEPTION_REGION(bool);
    return existing;
}

// ------------------------------------------------------------------------------------------------
// Set a configuration property
bool Importer::SetPropertyFloat(const char* szName, ai_real iValue) {
    ai_assert(nullptr != pimpl);

    bool existing;
    ASSIMP_BEGIN_EXCEPTION_REGION();
        existing = SetGenericProperty<ai_real>(pimpl->mFloatProperties, szName,iValue);
    ASSIMP_END_EXCEPTION_REGION(bool);
    return existing;
}

// ------------------------------------------------------------------------------------------------
// Set a configuration property
bool Importer::SetPropertyString(const char* szName, const std::string& value) {
    ai_assert(nullptr != pimpl);

    bool existing;
    ASSIMP_BEGIN_EXCEPTION_REGION();
        existing = SetGenericProperty<std::string>(pimpl->mStringProperties, szName,value);
    ASSIMP_END_EXCEPTION_REGION(bool);
    return existing;
}

// ------------------------------------------------------------------------------------------------
// Set a configuration property
bool Importer::SetPropertyMatrix(const char* szName, const aiMatrix4x4& value) {
    ai_assert(nullptr != pimpl);

    bool existing;
    ASSIMP_BEGIN_EXCEPTION_REGION();
        existing = SetGenericProperty<aiMatrix4x4>(pimpl->mMatrixProperties, szName,value);
    ASSIMP_END_EXCEPTION_REGION(bool);
    return existing;
}

// ------------------------------------------------------------------------------------------------
// Get a configuration property
int Importer::GetPropertyInteger(const char* szName, int iErrorReturn /*= 0xffffffff*/) const {
    ai_assert(nullptr != pimpl);

    return GetGenericProperty<int>(pimpl->mIntProperties,szName,iErrorReturn);
}

// ------------------------------------------------------------------------------------------------
// Get a configuration property
ai_real Importer::GetPropertyFloat(const char* szName, ai_real iErrorReturn /*= 10e10*/) const {
    ai_assert(nullptr != pimpl);

    return GetGenericProperty<ai_real>(pimpl->mFloatProperties,szName,iErrorReturn);
}

// ------------------------------------------------------------------------------------------------
// Get a configuration property
std::string Importer::GetPropertyString(const char* szName, const std::string& iErrorReturn /*= ""*/) const {
    ai_assert(nullptr != pimpl);

    return GetGenericProperty<std::string>(pimpl->mStringProperties,szName,iErrorReturn);
}

// ------------------------------------------------------------------------------------------------
// Get a configuration property
aiMatrix4x4 Importer::GetPropertyMatrix(const char* szName, const aiMatrix4x4& iErrorReturn /*= aiMatrix4x4()*/) const {
    ai_assert(nullptr != pimpl);

    return GetGenericProperty<aiMatrix4x4>(pimpl->mMatrixProperties,szName,iErrorReturn);
}

// ------------------------------------------------------------------------------------------------
// Get the memory requirements of a single node
inline
void AddNodeWeight(unsigned int& iScene,const aiNode* pcNode) {
    if ( nullptr == pcNode ) {
        return;
    }
    iScene += sizeof(aiNode);
    iScene += sizeof(unsigned int) * pcNode->mNumMeshes;
    iScene += sizeof(void*) * pcNode->mNumChildren;

    for (unsigned int i = 0; i < pcNode->mNumChildren;++i) {
        AddNodeWeight(iScene,pcNode->mChildren[i]);
    }
}

// ------------------------------------------------------------------------------------------------
// Get the memory requirements of the scene
void Importer::GetMemoryRequirements(aiMemoryInfo& in) const {
    ai_assert(nullptr != pimpl);

    in = aiMemoryInfo();
    aiScene* mScene = pimpl->mScene;

    // return if we have no scene loaded
    if (!mScene)
        return;

    in.total = sizeof(aiScene);

    // add all meshes
    for (unsigned int i = 0; i < mScene->mNumMeshes;++i) {
        in.meshes += sizeof(aiMesh);
        if (mScene->mMeshes[i]->HasPositions()) {
            in.meshes += sizeof(aiVector3D) * mScene->mMeshes[i]->mNumVertices;
        }

        if (mScene->mMeshes[i]->HasNormals()) {
            in.meshes += sizeof(aiVector3D) * mScene->mMeshes[i]->mNumVertices;
        }

        if (mScene->mMeshes[i]->HasTangentsAndBitangents()) {
            in.meshes += sizeof(aiVector3D) * mScene->mMeshes[i]->mNumVertices * 2;
        }

        for (unsigned int a = 0; a < AI_MAX_NUMBER_OF_COLOR_SETS;++a) {
            if (mScene->mMeshes[i]->HasVertexColors(a)) {
                in.meshes += sizeof(aiColor4D) * mScene->mMeshes[i]->mNumVertices;
            } else {
                break;
            }
        }
        for (unsigned int a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS;++a) {
            if (mScene->mMeshes[i]->HasTextureCoords(a)) {
                in.meshes += sizeof(aiVector3D) * mScene->mMeshes[i]->mNumVertices;
            } else {
                break;
            }
        }
        if (mScene->mMeshes[i]->HasBones()) {
            in.meshes += sizeof(void*) * mScene->mMeshes[i]->mNumBones;
            for (unsigned int p = 0; p < mScene->mMeshes[i]->mNumBones;++p) {
                in.meshes += sizeof(aiBone);
                in.meshes += mScene->mMeshes[i]->mBones[p]->mNumWeights * sizeof(aiVertexWeight);
            }
        }
        in.meshes += (sizeof(aiFace) + 3 * sizeof(unsigned int))*mScene->mMeshes[i]->mNumFaces;
    }
    in.total += in.meshes;

    // add all embedded textures
    for (unsigned int i = 0; i < mScene->mNumTextures;++i) {
        const aiTexture* pc = mScene->mTextures[i];
        in.textures += sizeof(aiTexture);
        if (pc->mHeight) {
            in.textures += 4 * pc->mHeight * pc->mWidth;
        } else {
            in.textures += pc->mWidth;
        }
    }
    in.total += in.textures;

    // add all animations
    for (unsigned int i = 0; i < mScene->mNumAnimations;++i) {
        const aiAnimation* pc = mScene->mAnimations[i];
        in.animations += sizeof(aiAnimation);

        // add all bone anims
        for (unsigned int a = 0; a < pc->mNumChannels; ++a) {
            const aiNodeAnim* pc2 = pc->mChannels[i];
            in.animations += sizeof(aiNodeAnim);
            in.animations += pc2->mNumPositionKeys * sizeof(aiVectorKey);
            in.animations += pc2->mNumScalingKeys * sizeof(aiVectorKey);
            in.animations += pc2->mNumRotationKeys * sizeof(aiQuatKey);
        }
    }
    in.total += in.animations;

    // add all cameras and all lights
    in.total += in.cameras = sizeof(aiCamera) *  mScene->mNumCameras;
    in.total += in.lights  = sizeof(aiLight)  *  mScene->mNumLights;

    // add all nodes
    AddNodeWeight(in.nodes,mScene->mRootNode);
    in.total += in.nodes;

    // add all materials
    for (unsigned int i = 0; i < mScene->mNumMaterials;++i) {
        const aiMaterial* pc = mScene->mMaterials[i];
        in.materials += sizeof(aiMaterial);
        in.materials += pc->mNumAllocated * sizeof(void*);

        for (unsigned int a = 0; a < pc->mNumProperties;++a) {
            in.materials += pc->mProperties[a]->mDataLength;
        }
    }

    in.total += in.materials;
}


text:
[![CI Status](http://img.shields.io/travis/vonkar/VKiOSViews.svg?style=flat)](https://travis-ci.org/vonkar/VKiOSViews)
[![Version](https://img.shields.io/cocoapods/v/VKiOSViews.svg?style=flat)](http://cocoapods.org/pods/VKiOSViews)
[![License](https://img.shields.io/cocoapods/l/VKiOSViews.svg?style=flat)](http://cocoapods.org/pods/VKiOSViews)
[![Platform](https://img.shields.io/cocoapods/p/VKiOSViews.svg?style=flat)](http://cocoapods.org/pods/VKiOSViews)

## Example

To run the example project, clone the repo, and run `pod install` from the Example directory first.

To use it, call methods directly on instances of UIImage class, UIButton class and UIView class and see
the effects like cicular crop for images, rounded corner effect for buttons etc.

## How To Use

See the below example,
```swift
Swift:

uiButton.getRoundedCornerButtonView(radius: 3.0)
```
It will create round corner button with radius 3.0 whichs is customizable.

```swift
Swift:

uiimageview.getFulCircularImageView()
```
Above code will create full circular UIImageView.

## Requirements

## Installation

VKiOSViews is available through [CocoaPods](http://cocoapods.org). To install
it, simply add the following line to your Podfile:

```ruby
pod "VKiOSViews"
```

## Author

vonkar, vinod.onkar@gmail.com

## License

VKiOSViews is available under the MIT license. See the LICENSE file for more info.


text:
package org.newdawn.slick;

/**
 * The main game interface that should be implemented by any game being developed using the container system. There will
 * be some utility type sub-classes as development continues.
 *

 *
 * @author kevin
 * @see org.newdawn.slick.BasicGame
 *

 */
public interface Game {

    /**
     * Initialise the game. This can be used to load static resources. It's called before the game loop starts
     *

     *
     * @param container The container holding the game
     *

     *
     * @throws SlickException Throw to indicate an internal error
     */
    public void init(GameContainer container) throws SlickException;

    /**
     * Update the game logic here. No rendering should take place in this method though it won't do any harm.
     *

     *
     * @param container The container holing this game
     * @param delta     The amount of time thats passed since last update in milliseconds
     *

     *
     * @throws SlickException Throw to indicate an internal error
     */
    public void update(GameContainer container, int delta) throws SlickException;

    /**
     * Render the game's screen here.
     *

     *
     * @param container The container holing this game
     * @param g         The graphics context that can be used to render. However, normal rendering routines can also be
     *                  used.
     *

     *
     * @throws SlickException Throw to indicate a internal error
     */
    public void render(GameContainer container, Graphics g) throws SlickException;

    /**
     * Notification that a game close has been requested
     *

     *
     * @return True if the game should close
     */
    public boolean closeRequested();

    /**
     * Get the title of this game
     *

     *
     * @return The title of the game
     */
    public String getTitle();

}


text:
The main goal of Kotlin IDE plugin performance tests is to collect statistics over
routines (open project, highlighting, inspection, autocompletion etc) for
further analysis like anomalies, degradations and reference for optimizations.

## Resources

You need an extra copy of kotlin project located at `${KOTLIN_PROJECT}/../perfTestProject`

## Run

Run all Kotlin IDE plugin performance tests with

`$ gradle idea-plugin-performance-tests`

## Run with profiler

`YOURKIT_PROFILER_HOME=/Applications/YourKit-Java-Profiler-2019.8.app ./gradlew -Pkotlin.test.instrumentation.disable=true  :idea:performanceTests:performanceTest --tests "<test-filter>"`

## Performance test

Output is provided to console in TeamCity format like

```
##teamcity[testSuiteStarted name='Field']
##teamcity[testStarted name='highlight: Field warm-up #0' captureStandardOutput='true']
##teamcity[buildStatisticValue key='highlight: Field warm-up #0' value='142']
##teamcity[testFinished name='highlight: Field warm-up #0' duration='142']
....
##teamcity[testStarted name='highlight: Field #0' captureStandardOutput='true']
##teamcity[buildStatisticValue key='highlight: Field #0 counter "Call resolve": time' value='8']
##teamcity[buildStatisticValue key='highlight: Field #0' value='67']
##teamcity[testFinished name='highlight: Field #0' duration='67']
....
##teamcity[testStarted name='highlight: Field #19' captureStandardOutput='true']
##teamcity[buildStatisticValue key='highlight: Field #19' value='56']
##teamcity[testFinished name='highlight: Field #19' duration='56']

##teamcity[testStarted name='highlight: Field : mean' captureStandardOutput='true']
##teamcity[buildStatisticValue key='highlight: Field' value='57']
##teamcity[testFinished name='highlight: Field : mean' duration='57']

##teamcity[testStarted name='highlight: Field : stdDev' captureStandardOutput='true']
##teamcity[buildStatisticValue key='highlight: Field stdDev' value='0']
##teamcity[testFinished name='highlight: Field : stdDev' duration='0']

##teamcity[testStarted name='highlight: Field : geomMean' captureStandardOutput='true']
##teamcity[buildStatisticValue key='highlight: Field geomMean' value='57']
##teamcity[testFinished name='highlight: Field : geomMean' duration='57']

##teamcity[testStarted name='highlight: Field stability' captureStandardOutput='true']
##teamcity[buildStatisticValue key='highlight: Field stability' value='2']
##teamcity[testFinished name='highlight: Field stability']

##teamcity[testSuiteFinished name='Field']
```

as well in CVS files at `build/stats*.csv`, e.g. `build/stats-highlight.csv`:

 Name          | ValueMS                              | StdDev
--- | --- | ---
  highlight: NonNullAssertion | 56.1 | 1.86
  highlight: PropertiesWithPropertyDeclarations | 308.1 | 11.05
  highlight: NamedArguments | 67.15 | 1.23
  highlight: Annotations | 84.85 | 1.18
  highlight: VariablesAsFunctions | 125.5 | 2.11
  highlight: Enums | 84.4 | 1.31
  highlight: Field | 67.8 | 1.74

## PerfTest DSL

TBD


text:
import { CallbackHook, CallbackChainHook } from '../vulcan-lib/callbacks';
import { userCanDo } from '../vulcan-users/permissions';
import { recalculateScore } from '../scoring';
import { voteTypes, calculateVotePower } from './voteTypes';

export interface VoteDocTuple {
  newDocument: DbVoteableType
  vote: DbVote
}
export const voteCallbacks = {
  cancelSync: new CallbackChainHook<VoteDocTuple,[CollectionBase<DbVoteableType>,DbUser]>("votes.cancel.sync"),
  cancelAsync: new CallbackHook<[VoteDocTuple,CollectionBase<DbVoteableType>,DbUser]>("votes.cancel.async"),
  castVoteSync: new CallbackChainHook<VoteDocTuple,[CollectionBase<DbVoteableType>,DbUser]>("votes.castVote.sync"),
  castVoteAsync: new CallbackHook<[VoteDocTuple,CollectionBase<DbVoteableType>,DbUser]>("votes.castVote.async"),
};

// Given a client-side view of a document, return a modified version in which
// the user has voted and the scores are updated appropriately.
const addVoteClient = ({ document, collection, voteType, user }: {
  document: VoteableTypeClient,
  collection: CollectionBase<DbObject>,
  voteType: string,
  user: UsersCurrent,
}) => {
  const power = getVotePower({user, voteType, document});
  const isAfVote = (document.af && userCanDo(user, "votes.alignment"))
  const afPower = isAfVote ? calculateVotePower(user.afKarma, voteType) : 0;

  const newDocument = {
    ...document,
    currentUserVote: voteType,
    baseScore: (document.baseScore||0) + power,
    voteCount: (document.voteCount||0) + 1,
    afBaseScore: (document.afBaseScore||0) + afPower,
    afVoteCount: (document.afVoteCount||0) + (isAfVote?1:0),
    __typename: collection.options.typeName,
  };

  newDocument.score = recalculateScore(newDocument);
  return newDocument;
}

// Given a client-side view of a document, return a modified version in which
// the current user's vote is removed and the score is adjusted accordingly.
const cancelVoteClient = ({document, collection, user}: {
  document: VoteableTypeClient,
  collection: CollectionBase<DbObject>,
  user: UsersCurrent,
}): VoteableTypeClient => {
  if (!document.currentUserVote)
    return document;

  // Compute power for the vote being removed. Note that this is not quite
  // right if the user's vote weight has changed; the eager update will remove
  // points based on the user's new vote weight, which will then be corrected
  // when the server responds.
  const voteType = document.currentUserVote;
  const power = getVotePower({user, voteType, document});
  const isAfVote = (document.af && userCanDo(user, "votes.alignment"))
  const afPower = isAfVote ? calculateVotePower(user.afKarma, voteType) : 0;

  const newDocument = {
    ...document,
    currentUserVote: null,
    baseScore: (document.baseScore||0) - power,
    afBaseScore: (document.afBaseScore||0) - afPower,
    voteCount: (document.voteCount||0)-1,
    afVoteCount: (document.afVoteCount||0) - (isAfVote?1:0),
  };
  newDocument.score = recalculateScore(newDocument);

  return newDocument;
}

// Determine a user's voting power for a given operation.
// If power is a function, call it on user
export const getVotePower = ({ user, voteType, document }: {
  user: DbUser|UsersCurrent,
  voteType: string,
  document: VoteableType,
}) => {
  const power = (voteTypes[voteType]?.power) || 1;
  return typeof power === 'function' ? power(user, document) : power;
};

// Create new vote object
export const createVote = ({ document, collectionName, voteType, user, voteId }: {
  document: VoteableType,
  collectionName: CollectionNameString,
  voteType: string,
  user: DbUser|UsersCurrent,
  voteId?: string,
}) => {
  if (!document.userId)
    throw new Error("Voted-on document does not have an author userId?");

  return {
    // when creating a vote from the server, voteId can sometimes be undefined
    ...(voteId ? {_id:voteId} : undefined),

    documentId: document._id,
    collectionName,
    userId: user._id,
    voteType: voteType,
    power: getVotePower({user, voteType, document}),
    votedAt: new Date(),
    authorId: document.userId,
    cancelled: false,
    documentIsAf: !!(document.af),
  }
};

// Optimistic response for votes
export const setVoteClient = async ({ document, collection, voteType, user }: {
  document: VoteableTypeClient,
  collection: CollectionBase<DbVoteableType>
  voteType: string|null,
  user: UsersCurrent,
}): Promise<VoteableTypeClient> => {
  if (voteType && !voteTypes[voteType]) throw new Error("Invalid vote type");
  const collectionName = collection.options.collectionName;

  // make sure item and user are defined
  if (!document || !user || (voteType && !userCanDo(user, `${collectionName.toLowerCase()}.${voteType}`))) {
    throw new Error(`Cannot vote on '${collectionName.toLowerCase()}`);
  }

  if (!voteType) {
    return cancelVoteClient({document, collection, user});
  } else {
    document = cancelVoteClient({document, collection, user})
    return addVoteClient({document, collection, voteType, user});
  }
}


text:
import React from 'react'
import { render } from 'enzyme'
import test from 'tape'

import Link from '../index.js'

test('Link', t => {
  t.ok(Link, 'export')
  t.equal(Link.displayName, 'FabricComponent(Link)')

  t.end()
})

test('Link#render - simple', t => {
  const container = render(
    <Link>Foo</Link>
  ).contents()

  t.assert(container.is('a.ms-Link', 'container'))
  t.assert(container.is('[data-fabric="Link"]'), 'data-fabric')
  t.equal(container.text(), 'Foo')

  t.end()
})


text:
package org.gradle.internal.installation.beacon;

/**
 * This marker is used to locate the "source" Gradle distribution at runtime.
 * See {@code GradleDistributionLocator}.
 */
@SuppressWarnings("unused")
public interface InstallationBeacon {
}


text:
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}

--
-- Copyright (c) 2009-2011, ERICSSON AB
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
--
--     * Redistributions of source code must retain the above copyright notice,
--       this list of conditions and the following disclaimer.
--     * Redistributions in binary form must reproduce the above copyright
--       notice, this list of conditions and the following disclaimer in the
--       documentation and/or other materials provided with the distribution.
--     * Neither the name of the ERICSSON AB nor the names of its contributors
--       may be used to endorse or promote products derived from this software
--       without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
-- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
-- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
-- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
-- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--

module Feldspar.Core.Frontend.Literal where

import Language.Syntactic
import Feldspar.Core.Types
import Feldspar.Core.Constructs.Literal
import Feldspar.Core.Constructs
import Feldspar.Core.Interpretation

value :: Syntax a => Internal a -> a
value = sugarSymF . Literal

false :: Data Bool
false = value False

true :: Data Bool
true = value True

instance Syntactic ()
  where
    type Domain ()   = FeldDomain
    type Internal () = ()
    desugar = appSymC . c' . Literal
    sugar _ = ()


text:
package com.acme.eval;

import groovy.util.Eval;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class E1_ExpressionEvaluation {
    public static void main(String[] args) throws IOException {
        Eval.me("println 'This is an expression evaluator'");
        Object result = null;
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        while (result == null || !result.equals(-1)) {
            System.out.println("What do you want to evaluate?");
            String code = reader.readLine();
            result = Eval.me(code);
            System.out.println("result = " + result);
        }
    }
}


text:
<use name="RecoJets/JetAlgorithms"/>
<use name="root"/>
<use name="fastjet"/>
<use name="fastjet-contrib"/>
<export>
  <lib name="1"/>
</export>


text:
export * from './auth-actions';
export * from './profile-actions';
export * from './anecdote-actions';


text: export { default } from './normalize-flags';


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Class org.myrobotlab.java.JavaClassInfo</title>
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
org.myrobotlab.java.JavaClassInfo

Packages that use JavaClassInfo

Package
Description

org.myrobotlab.java

Uses of JavaClassInfo in org.myrobotlab.java

Fields in org.myrobotlab.java declared as JavaClassInfo

Modifier and Type
Field and Description

static JavaClassInfo
JavaClassInfo.BOOLEAN

The boolean info

static JavaClassInfo
JavaClassInfo.CLASS

The Class info

static JavaClassInfo
JavaClassInfo.DOUBLE

The double info

static JavaClassInfo
JavaClassInfo.FLOAT

The float info

static JavaClassInfo
JavaClassInfo.INT

The int info

static JavaClassInfo
JavaClassInfo.LONG

The long info

static JavaClassInfo
JavaClassInfo.STRING

The string info

Constructors in org.myrobotlab.java with parameters of type JavaClassInfo

Constructor and Description

JavaClassInfo(JavaClassInfo c)

Creates a new class info representing an array

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
local schema_def = require "kong.plugins.zipkin.schema"
local v = require("spec.helpers").validate_plugin_config_schema

describe("Plugin: Zipkin (schema)", function()
  it("rejects repeated tags", function()
    local ok, err = v({
      http_endpoint = "http://example.dev",
      static_tags = {
        { name = "foo", value = "bar" },
        { name = "foo", value = "baz" },
      },
    }, schema_def)

    assert.is_falsy(ok)
    assert.same({
      config = {
        static_tags = "repeated tags are not allowed: foo"
      }
    }, err)
  end)
end)


text:
- Fixing basic description

# 1.0.3

## Bug Fixes

- Not importing angular-sanitize and adding it to `externals` anymore. Instead just relying on the end user to include it on the page.

# 1.0.2

## Bug Fixes

- Adding `peerDependencies` for angular and angular-sanitize.

# 1.0.1

## Bug Fixes

- The description didn't make sense... I don't think I've ever released properly the first time :-(

# 1.0.0

## New Features

- Initial Release


text:
namespace foundation    { class IAbortSwitch; }
namespace renderer      { class Project; }

using namespace foundation;

namespace renderer
{

namespace
{
    //
    // Per-hemisphere constant-emittance environment EDF.
    //

    const char* Model = "constant_hemisphere_environment_edf";

    class ConstantHemisphereEnvironmentEDF
      : public EnvironmentEDF
    {
      public:
        ConstantHemisphereEnvironmentEDF(
            const char*             name,
            const ParamArray&       params)
          : EnvironmentEDF(name, params)
        {
            m_inputs.declare("upper_hemi_radiance", InputFormat::SpectralIlluminance);
            m_inputs.declare("lower_hemi_radiance", InputFormat::SpectralIlluminance);
        }

        void release() override
        {
            delete this;
        }

        const char* get_model() const override
        {
            return Model;
        }

        bool on_frame_begin(
            const Project&          project,
            const BaseGroup*        parent,
            OnFrameBeginRecorder&   recorder,
            IAbortSwitch*           abort_switch) override
        {
            if (!EnvironmentEDF::on_frame_begin(project, parent, recorder, abort_switch))
                return false;

            if (!check_uniform("upper_hemi_radiance") || !check_uniform("lower_hemi_radiance"))
                return false;

            if (is_uniform_zero_spectrum("upper_hemi_radiance") && is_uniform_zero_spectrum("lower_hemi_radiance"))
                warn_zero_emission();

            m_inputs.evaluate_uniforms(&m_values);

            return true;
        }

        void sample(
            const ShadingContext&   shading_context,
            const Vector2f&         s,
            Vector3f&               outgoing,
            Spectrum&               value,
            float&                  probability) const override
        {
            const Vector3f local_outgoing = sample_sphere_uniform(s);
            probability = RcpFourPi<float>();

            Transformd scratch;
            const Transformd& transform = m_transform_sequence.evaluate(0.0f, scratch);
            outgoing = transform.vector_to_parent(local_outgoing);

            value =
                local_outgoing.y >= 0.0f
                    ? m_values.m_upper_hemi_radiance
                    : m_values.m_lower_hemi_radiance;
        }

        void evaluate(
            const ShadingContext&   shading_context,
            const Vector3f&         outgoing,
            Spectrum&               value) const override
        {
            assert(is_normalized(outgoing));

            Transformd scratch;
            const Transformd& transform = m_transform_sequence.evaluate(0.0f, scratch);
            const Transformd::MatrixType& parent_to_local = transform.get_parent_to_local();
            const float local_outgoing_y =
                static_cast<float>(parent_to_local[ 4]) * outgoing.x +
                static_cast<float>(parent_to_local[ 5]) * outgoing.y +
                static_cast<float>(parent_to_local[ 6]) * outgoing.z;

            value =
                local_outgoing_y >= 0.0f
                    ? m_values.m_upper_hemi_radiance
                    : m_values.m_lower_hemi_radiance;
        }

        void evaluate(
            const ShadingContext&   shading_context,
            const Vector3f&         outgoing,
            Spectrum&               value,
            float&                  probability) const override
        {
            assert(is_normalized(outgoing));

            Transformd scratch;
            const Transformd& transform = m_transform_sequence.evaluate(0.0f, scratch);
            const Transformd::MatrixType& parent_to_local = transform.get_parent_to_local();
            const float local_outgoing_y =
                static_cast<float>(parent_to_local[ 4]) * outgoing.x +
                static_cast<float>(parent_to_local[ 5]) * outgoing.y +
                static_cast<float>(parent_to_local[ 6]) * outgoing.z;

            value =
                local_outgoing_y >= 0.0f
                    ? m_values.m_upper_hemi_radiance
                    : m_values.m_lower_hemi_radiance;

            probability = RcpFourPi<float>();
        }

        float evaluate_pdf(
            const Vector3f&         outgoing) const override
        {
            assert(is_normalized(outgoing));
            return RcpFourPi<float>();
        }

      private:
        APPLESEED_DECLARE_INPUT_VALUES(InputValues)
        {
            Spectrum    m_upper_hemi_radiance;              // radiance emitted by the upper hemisphere, in W.m^-2.sr^-1
            Spectrum    m_lower_hemi_radiance;              // radiance emitted by the lower hemisphere, in W.m^-2.sr^-1
        };

        InputValues     m_values;
    };
}

//
// ConstantHemisphereEnvironmentEDFFactory class implementation.
//

void ConstantHemisphereEnvironmentEDFFactory::release()
{
    delete this;
}

const char* ConstantHemisphereEnvironmentEDFFactory::get_model() const
{
    return Model;
}

Dictionary ConstantHemisphereEnvironmentEDFFactory::get_model_metadata() const
{
    return
        Dictionary()
            .insert("name", Model)
            .insert("label", "Per-Hemisphere Constant Environment EDF")
            .insert("help", "An environment made of two hemispheres of constant radiance");
}

DictionaryArray ConstantHemisphereEnvironmentEDFFactory::get_input_metadata() const
{
    DictionaryArray metadata;

    metadata.push_back(
        Dictionary()
            .insert("name", "upper_hemi_radiance")
            .insert("label", "Upper Hemisphere Radiance")
            .insert("type", "colormap")
            .insert("entity_types",
                Dictionary().insert("color", "Colors"))
            .insert("use", "required")
            .insert("default", "0.7")
            .insert("help", "Upper hemisphere radiance"));

    metadata.push_back(
        Dictionary()
            .insert("name", "lower_hemi_radiance")
            .insert("label", "Lower Hemisphere Radiance")
            .insert("type", "colormap")
            .insert("entity_types",
                Dictionary().insert("color", "Colors"))
            .insert("use", "required")
            .insert("default", "0.3")
            .insert("help", "Lower hemisphere radiance"));

    add_common_input_metadata(metadata);

    return metadata;
}

auto_release_ptr<EnvironmentEDF> ConstantHemisphereEnvironmentEDFFactory::create(
    const char*         name,
    const ParamArray&   params) const
{
    return
        auto_release_ptr<EnvironmentEDF>(
            new ConstantHemisphereEnvironmentEDF(name, params));
}

}   // namespace renderer


text:
package org.mitre.taxii.client.xml11;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import javax.net.ssl.SSLContext;
import javax.xml.bind.JAXBException;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.fluent.Request;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import static org.junit.Assert.assertTrue;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Test;
import org.mitre.taxii.client.HttpClient;
import org.mitre.taxii.messages.TaxiiXml;
import org.mitre.taxii.messages.xml11.DiscoveryRequest;
import org.mitre.taxii.messages.xml11.DiscoveryResponse;
import org.mitre.taxii.messages.xml11.MessageHelper;
import org.mitre.taxii.messages.xml11.ObjectFactory;
import org.mitre.taxii.messages.xml11.TaxiiXmlFactory;

/**
 *
 * @author jasenj1
 */
public class DiscoveryTests {

    private final ObjectFactory factory = new ObjectFactory();
    private final TaxiiXmlFactory txf = new TaxiiXmlFactory();
    private final TaxiiXml taxiiXml;
    private final boolean debug = true; // Boolean.getBoolean("debug");

    private static final String serverURL = "http://127.0.0.1:8080/";

    public DiscoveryTests() {
        taxiiXml = txf.createTaxiiXml();
    }

    /*
        Confirm that the local TAXII server is running.
        If not, skip these tests. That is what the Assume is supposed to do.
        If the Assume is false, the tests will be ignored.
        In NetBeans, the Assume causes an ERROR rather than ignoring the tests.
    */
    @Before
    public void confirmConnection() {
        try {
            Request.Get(serverURL).execute();
        } catch (Exception ex) {
            Assume.assumeNoException(ex);
        }
    }

    @Test
    public void simpleDiscoveryTest() throws IOException, JAXBException, URISyntaxException {

        HttpClient taxiiClient = new HttpClient();

        final String serverUrl = serverURL + "services/discovery/";

        // Prepare the message to send.
        DiscoveryRequest dr = factory.createDiscoveryRequest()
                .withMessageId(MessageHelper.generateMessageId());

        // Call the services
        Object responseObj = taxiiClient.callTaxiiService(new URI(serverUrl), dr);

        if (debug) {
            System.out.println(taxiiXml.marshalToString(dr, true));
            System.out.println(taxiiXml.marshalToString(responseObj, true));
        }

        assertTrue("Received Discovery Response", (responseObj instanceof DiscoveryResponse));
    }

    @Test
    public void basicAuthDiscoveryTest() throws IOException, JAXBException, URISyntaxException {

        // Create a client that uses basic authentication (user & password).
        HttpClientBuilder cb = HttpClientBuilder.create();
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(
                AuthScope.ANY,
                new UsernamePasswordCredentials("taxii", "taxii"));
        cb.setDefaultCredentialsProvider(credsProvider);
        CloseableHttpClient httpClient = cb.build();

        // Create a Taxii Client with the HttpClient object.
        HttpClient taxiiClient = new HttpClient(httpClient);

        // Prepare the message to send.
        DiscoveryRequest dr = factory.createDiscoveryRequest()
                .withMessageId(MessageHelper.generateMessageId());

        // Call the service
        final String serverUrl = serverURL + "services/discovery/";
        Object responseObj = taxiiClient.callTaxiiService(new URI(serverUrl), dr);

        if (debug) {
            System.out.println(taxiiXml.marshalToString(dr, true));
            System.out.println(taxiiXml.marshalToString(responseObj, true));
        }

        assertTrue("Received Discovery Response", (responseObj instanceof DiscoveryResponse));
    }

    @Test
    public void sslDiscoveryTest() throws IOException, JAXBException, KeyStoreException, NoSuchAlgorithmException, CertificateException, KeyManagementException, URISyntaxException {
        final String serverUrl = "https://127.0.0.1:8443/services/discovery/";

        // Prepare the TLS objects necessary for SSL connection.
        KeyStore trustStore  = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null);

        // Trust own CA and all self-signed certs
        SSLContext sslcontext = SSLContexts.custom()
                .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy())
                .build();
        // Allow TLSv1 protocol only
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslcontext,
                new String[] { "TLSv1" },
                null,
                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        CloseableHttpClient httpClient = HttpClients.custom()
                .setSSLSocketFactory(sslsf)
                .build();

        // Create a Taxii Client with the HttpClient and TaxiiXml objects.
        HttpClient taxiiClient = new HttpClient(httpClient);

        // Prepare the message to send.
        DiscoveryRequest dr = factory.createDiscoveryRequest()
                .withMessageId(MessageHelper.generateMessageId());

        // Call the service
        Object responseObj = taxiiClient.callTaxiiService(new URI(serverUrl), dr);

        if (debug) {
            System.out.println(taxiiXml.marshalToString(dr, true));
            System.out.println(taxiiXml.marshalToString(responseObj, true));
        }

        assertTrue("Received Discovery Response", (responseObj instanceof DiscoveryResponse));
    }

    @Test
    public void proxyDiscoveryTest() throws IOException, JAXBException, URISyntaxException {

        // Create a client that connects via a proxy.
        HttpHost proxy = new HttpHost("gatekeeper-w.mitre.org", 80, "http");
        HttpClientBuilder cb = HttpClientBuilder.create();
        cb.setProxy(proxy);
        CloseableHttpClient httpClient = cb.build();

        // Create a Taxii Client with the HttpClient object.
        HttpClient taxiiClient = new HttpClient(httpClient);

        // Prepare the message to send.
        DiscoveryRequest dr = factory.createDiscoveryRequest()
                .withMessageId(MessageHelper.generateMessageId());

        // Call the service
        final String serverUrl = "http://taxiitest.mitre.org/services/discovery/";
        Object responseObj = taxiiClient.callTaxiiService(new URI(serverUrl), dr);

        if (debug) {
            System.out.println(taxiiXml.marshalToString(dr, true));
            System.out.println(taxiiXml.marshalToString(responseObj, true));
        }

        assertTrue("Received Discovery Response", (responseObj instanceof DiscoveryResponse));
    }
}


text:
<?php

namespace MediaBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;

class MediaCollectionType extends AbstractType
{

    /**
     *
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefault('translation_domain', 'MediaBundle');
    }

    /**
     *
     * @return string
     */
    public function getParent()
    {
        return CollectionType::class;
    }

}


text:
salt.modules.mac_keychain
=========================

.. automodule:: salt.modules.mac_keychain
    :members:


text:
package org.wikipedia.useroption.dataclient;

import android.support.annotation.NonNull;

import com.google.gson.annotations.SerializedName;

import org.wikipedia.useroption.UserOption;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;

public class UserInfo {
    @SerializedName("name")
    private String username;
    private int id;

    // Object type is any JSON type.
    @NonNull private Map<String, ?> options;

    public int id() {
        return id;
    }

    @NonNull
    public String username() {
        return username;
    }

    @NonNull
    public Collection<UserOption> userjsOptions() {
        Collection<UserOption> ret = new ArrayList<>();
        for (Map.Entry<String, ?> entry : options.entrySet()) {
            if (entry.getKey().startsWith("userjs-")) {
                ret.add(new UserOption(entry.getKey(), (String) entry.getValue()));
            }
        }
        return ret;
    }

    // Auto-generated
    @Override
    public String toString() {
        return "UserInfo{"
                + "username='" + username + '\''
                + ", id=" + id
                + ", options=" + options
                + '}';
    }
}