text:
package com.codepath.oauth;

import android.net.Uri;

import com.github.scribejava.core.builder.ServiceBuilder;
import com.github.scribejava.core.builder.api.BaseApi;
import com.github.scribejava.core.exceptions.OAuthException;
import com.github.scribejava.core.model.OAuth1AccessToken;
import com.github.scribejava.core.model.OAuth1RequestToken;
import com.github.scribejava.core.model.OAuth2AccessToken;
import com.github.scribejava.core.model.OAuthAsyncRequestCallback;
import com.github.scribejava.core.model.OAuthConstants;
import com.github.scribejava.core.model.Token;
import com.github.scribejava.core.oauth.OAuth10aService;
import com.github.scribejava.core.oauth.OAuth20Service;
import com.github.scribejava.core.oauth.OAuthService;
import com.github.scribejava.httpclient.okhttp.OkHttpHttpClientConfig;

/*
 * OAuthTokenClient is responsible for managing the request and access token exchanges and then
 * signing all requests with the OAuth signature after access token has been retrieved and stored.
 * The client is based on AsyncHttpClient for async http requests and uses Scribe to manage the OAuth authentication.
 */
public class OAuthTokenClient {

    private BaseApi apiInstance;
    private OAuthTokenHandler handler;
    private Token accessToken;
    private OAuthService service;

    // Requires the apiClass, consumerKey, consumerSecret and callbackUrl along with the TokenHandler
    public OAuthTokenClient(BaseApi apiInstance, String consumerKey, String consumerSecret, String callbackUrl,
                            String scope, OAuthTokenHandler handler) {
        this.apiInstance = apiInstance;
        this.handler = handler;
        if (callbackUrl == null) { callbackUrl = OAuthConstants.OUT_OF_BAND; };
        if(scope == null) {
            this.service = new ServiceBuilder()
                .apiKey(consumerKey)
                .apiSecret(consumerSecret).callback(callbackUrl)
                .httpClientConfig(OkHttpHttpClientConfig.defaultConfig())
                .build(apiInstance);
        } else {
            this.service = new ServiceBuilder()
                .apiKey(consumerKey)
                .apiSecret(consumerSecret).callback(callbackUrl)
                .httpClientConfig(OkHttpHttpClientConfig.defaultConfig())
                .scope(scope) // OAuth2 requires scope
                .build(apiInstance);
        }
    }

    // Get a request token and the authorization url
    // Once fetched, fire the onReceivedRequestToken for the request token handler
    // Works for both OAuth1.0a and OAuth2
    public void fetchRequestToken() {
        if (service.getVersion() == "1.0") {
            final OAuth10aService oAuth10aService = (OAuth10aService) service;
            oAuth10aService.getRequestTokenAsync(new OAuthAsyncRequestCallback<OAuth1RequestToken>() {
                @Override
                public void onCompleted(OAuth1RequestToken requestToken) {
                    String authorizeUrl = oAuth10aService.getAuthorizationUrl((OAuth1RequestToken) requestToken);
                    handler.onReceivedRequestToken(requestToken, authorizeUrl, service.getVersion());

                }

                @Override
                public void onThrowable(Throwable t) {
                    handler.onFailure(new Exception(t.getMessage()));
                }
            });
        }
        if (service.getVersion() == "2.0") {
            OAuth20Service oAuth20Service = (OAuth20Service) service;
            String authorizeUrl = oAuth20Service.getAuthorizationUrl(null);
            handler.onReceivedRequestToken(null, authorizeUrl, service.getVersion());
        }
    }

    // Get the access token by exchanging the requestToken to the defined URL
    // Once receiving the access token, fires the onReceivedAccessToken method on the handler
    public void fetchAccessToken(final Token requestToken, final Uri uri) {

        Uri authorizedUri = uri;

        if (service.getVersion() == "1.0") {
            // Use verifier token to fetch access token

            if (authorizedUri.getQuery().contains(OAuthConstants.VERIFIER)) {
                String oauth_verifier = authorizedUri.getQueryParameter(OAuthConstants.VERIFIER);
                OAuth1RequestToken oAuth1RequestToken = (OAuth1RequestToken) requestToken;
                OAuth10aService oAuth10aService = (OAuth10aService) service;

                oAuth10aService.getAccessTokenAsync(oAuth1RequestToken, oauth_verifier,
                        new OAuthAsyncRequestCallback<OAuth1AccessToken>() {

                            @Override
                            public void onCompleted(OAuth1AccessToken oAuth1AccessToken) {
                                setAccessToken(oAuth1AccessToken);
                                handler.onReceivedAccessToken(oAuth1AccessToken, service.getVersion());
                            }

                            @Override
                            public void onThrowable(Throwable e) {
                                handler.onFailure(new OAuthException(e.getMessage()));
                            }
                        });

            }
            else { // verifier was null
                throw new OAuthException("No verifier code was returned with uri '" + uri + "' " +
                        "and access token cannot be retrieved");
            }
        } else if (service.getVersion() == "2.0") {
            if (authorizedUri.getQuery().contains(OAuthConstants.CODE)) {
                String code = authorizedUri.getQueryParameter(OAuthConstants.CODE);
                OAuth20Service oAuth20Service = (OAuth20Service) service;
                oAuth20Service.getAccessToken(code, new OAuthAsyncRequestCallback<OAuth2AccessToken>() {
                    @Override
                    public void onCompleted(OAuth2AccessToken accessToken) {
                        setAccessToken(accessToken);
                        handler.onReceivedAccessToken(accessToken, service.getVersion());

                    }

                    @Override
                    public void onThrowable(Throwable t) {

                    }
                });
            }
            else { // verifier was null
                handler.onFailure(new OAuthException("No code was returned with uri '" + uri + "' " +
                        "and access token cannot be retrieved"));
            }
        }
    }

    // Set the access token used for signing requests
    public void setAccessToken(Token accessToken) {
    	if (accessToken == null) {
    		this.accessToken = null;
    	} else {
    		this.accessToken = accessToken;
        }
    }

    public Token getAccessToken() {
    	return this.accessToken;
    }

    // Defines the interface handler for different token handlers
    public interface OAuthTokenHandler {
        public void onReceivedRequestToken(Token requestToken, String authorizeUrl, String oAuthVersion);
        public void onReceivedAccessToken(Token accessToken, String oAuthVersion);
        public void onFailure(Exception e);
    }
}


text:
"""
clide.py: interface to the CLIDE database
.. moduleauthor:: Nicolas Fauchereau <Nicolas.Fauchereau@gmail.com>
"""

import clide
import utils

redpajama_set_name: RedPajamaGithub


text:
package org.nibiru.ui.core.impl.builder;

import org.nibiru.ui.core.api.HasContent;
import org.nibiru.ui.core.api.Widget;

import static com.google.common.base.Preconditions.checkNotNull;

public interface HasContentBuilder<T extends HasContent, B extends HasContentBuilder<T, ?>>
        extends ObjectBuilder<T>, ChainBuilder<B> {

    default B content(Widget content) {
        checkNotNull(content);
        object().setContent(content);
        return getThis();
    }

    default T build(Widget content) {
        return content(content).build();
    }
}


text:
import ma = require('azure-pipelines-task-lib/mock-answer');
import tmrm = require('azure-pipelines-task-lib/mock-run');
import path = require('path');

let taskPath = path.join(__dirname, '..', 'azurermwebappdeployment.js');
let tr: tmrm.TaskMockRunner = new tmrm.TaskMockRunner(taskPath);

tr.setInput('ConnectedServiceName', 'AzureRMSpn');
tr.setInput('WebAppName', 'mytestapp');
tr.setInput('Package', 'webAppPkg.zip');
tr.setInput('UseWebDeploy', 'true');

process.env['TASK_TEST_TRACE'] = "1";
process.env["ENDPOINT_AUTH_AzureRMSpn"] = "{\"parameters\":{\"serviceprincipalid\":\"spId\",\"serviceprincipalkey\":\"spKey\",\"tenantid\":\"tenant\"},\"scheme\":\"ServicePrincipal\"}";
process.env["ENDPOINT_AUTH_PARAMETER_AzureRMSpn_SERVICEPRINCIPALID"] = "spId";
process.env["ENDPOINT_AUTH_PARAMETER_AzureRMSpn_SERVICEPRINCIPALKEY"] = "spKey";
process.env["ENDPOINT_AUTH_PARAMETER_AzureRMSpn_TENANTID"] = "tenant";
process.env["ENDPOINT_DATA_AzureRMSpn_SUBSCRIPTIONNAME"] = "sName";
process.env["ENDPOINT_DATA_AzureRMSpn_SUBSCRIPTIONID"] =  "sId";
process.env["AZURE_HTTP_USER_AGENT"] = "TFS_useragent";
process.env["SYSTEM_DEFAULTWORKINGDIRECTORY"] =  "DefaultWorkingDirectory";
process.env["BUILD_SOURCEVERSION"] = "46da24f35850f455185b9188b4742359b537076f";
process.env["BUILD_BUILDID"] = '1',
process.env["RELEASE_RELEASEID"] = '1';
process.env["BUILD_BUILDNUMBER"] = '1';
process.env["RELEASE_RELEASENAME"] = "Release-1";
process.env["BUILD_REPOSITORY_PROVIDER"] = "TfsGit";
process.env["BUILD_REPOSITORY_NAME"] = "MyFirstProject";
process.env["SYSTEM_TEAMFOUNDATIONCOLLECTIONURI"] = "https://abc.visualstudio.com/";
process.env["SYSTEM_TEAMPROJECT"] = "MyFirstProject";
process.env["SYSTEM_TEAMPROJECTID"] = "1";
process.env["BUILD_SOURCEVERISONAUTHOR"] = "author";
process.env["RELEASE_RELEASEURI"] = "vstfs:///ReleaseManagement/Release/1";
process.env["AGENT_NAME"] = "author";

// provide answers for task mock
let a: any = <any>{
    "which": {
        "msdeploy": "msdeploy"
    },
    "stats": {
    	"webAppPkg.zip": {
    		"isFile": true
    	}
    },
    "osType": {
        "osType": "Windows"
    },
    "checkPath": {
        "webAppPkg.zip": true,
        "webAppPkg": true,
        "msdeploy": true
    },
    "exec": {
          "msdeploy -verb:getParameters -source:package=\'webAppPkg.zip\'": {
              "code": 0,
              "stdout": "Executed Successfully"
           },
            "msdeploy -verb:sync -source:package=\'webAppPkg.zip\' -dest:auto,ComputerName=\'https://mytestappKuduUrl/msdeploy.axd?site=mytestapp\',UserName=\'$mytestapp\',Password=\'mytestappPwd\',AuthType=\'Basic\' -setParam:name=\'IIS Web Application Name\',value=\'mytestapp\' -enableRule:DoNotDeleteRule -userAgent:TFS_useragent": {
                "code": 1,
                "stdout": "Failed to Deploy WebSite"
        }
    },
    "exist": {
    	"webAppPkg.zip": true,
        "DefaultWorkingDirectory\\error.txt": true
    },
    "getVariable": {
    	"ENDPOINT_AUTH_AzureRMSpn": "{\"parameters\":{\"serviceprincipalid\":\"spId\",\"serviceprincipalkey\":\"spKey\",\"tenantid\":\"tenant\"},\"scheme\":\"ServicePrincipal\"}",
   		"ENDPOINT_DATA_AzureRMSpn_SUBSCRIPTIONNAME": "sName",
    	"ENDPOINT_DATA_AzureRMSpn_SUBSCRIPTIONID": "sId",
    	"SYSTEM_DEFAULTWORKINGDIRECTORY" : "defaultWorkingDirectory",
    	"AZURE_HTTP_USER_AGENT" : "TFS_useragent",
        "System.DefaultWorkingDirectory" : "DefaultWorkingDirectory",
		"release.releaseId": '1',
		"release.releaseName": "Release-1",
		"system.TeamFoundationCollectionUri": "https://abc.visualstudio.com/",
		"system.teamProject": "MyFirstProject",
		"release.releaseUri": "vstfs:///ReleaseManagement/Release/1",
		"agent.name": "agent"
    },
    "rmRF": {
        "DefaultWorkingDirectory\\error.txt": true
    }
};

import mockTask = require('azure-pipelines-task-lib/mock-task');
tr.registerMock('azure-pipelines-tasks-webdeployment-common/ziputility.js', {
    getArchivedEntries: function(webDeployPkg) {
        return {
            "entries":[
                "systemInfo.xml",
                "parameters.xml"
            ]
        };
    }
});
var kuduDeploymentLog = require('azurerest-common/kududeploymentstatusutility.js');
var msDeployUtility = require('azure-pipelines-tasks-webdeployment-common/msdeployutility.js');
tr.registerMock('./msdeployutility.js', {
    shouldRetryMSDeploy: msDeployUtility.shouldRetryMSDeploy,
    redirectMSDeployErrorToConsole : msDeployUtility.redirectMSDeployErrorToConsole,
    getMSDeployCmdArgs : msDeployUtility.getMSDeployCmdArgs,
    getMSDeployFullPath : function() {
        var msDeployFullPath =  "msdeploypath\\msdeploy.exe";
        return msDeployFullPath;
    }
});

tr.registerMock('azurerest-common/azurerestutility.js', {
    getAzureRMWebAppPublishProfile: function(SPN, webAppName, resourceGroupName, deployToSlotFlag, slotName) {
        var mockPublishProfile = {
            profileName: 'mytestapp - Web Deploy',
            publishMethod: 'MSDeploy',
            publishUrl: 'mytestappKuduUrl',
            msdeploySite: 'mytestapp',
            userName: '$mytestapp',
            userPWD: 'mytestappPwd',
            destinationAppUrl: 'mytestappUrl',
            SQLServerDBConnectionString: '',
            mySQLDBConnectionString: '',
            hostingProviderForumLink: '',
            controlPanelLink: '',
            webSystem: 'WebSites'
        };
        if(deployToSlotFlag) {
            mockPublishProfile.profileName =  'mytestapp-' + slotName + ' - Web Deploy';
            mockPublishProfile.publishUrl = 'mytestappKuduUrl-' + slotName;
            mockPublishProfile.msdeploySite = 'mytestapp__' + slotName;
            mockPublishProfile.userName = '$mytestapp__' + slotName;
            mockPublishProfile.userPWD = 'mytestappPwd';
            mockPublishProfile.destinationAppUrl = 'mytestappUrl-' + slotName;
        }
        return mockPublishProfile;
    },
    getAzureRMWebAppConfigDetails: function(SPN, webAppName, resourceGroupName, deployToSlotFlag, slotName) {
	var config = {
			id: 'appid',
			properties: {
				virtualApplications: [ ['Object'], ['Object'], ['Object'] ],
                scmType: "None"
			}
		}

		return config;
	},
    updateDeploymentStatus: function(publishingProfile, isDeploymentSuccess, customMessage ) {
        if(isDeploymentSuccess) {
            console.log('Updated history to kudu');
        }
        else {
            console.log('Failed to update history to kudu');
        }
        var webAppPublishKuduUrl = publishingProfile.publishUrl;
        var requestDetails = kuduDeploymentLog.getUpdateHistoryRequest(webAppPublishKuduUrl, isDeploymentSuccess, customMessage);
        requestDetails["requestBody"].author = 'author';
        console.log("kudu log requestBody is:" + JSON.stringify(requestDetails["requestBody"]));
    },
    getResourceGroupName: function (SPN, webAppName) {
        return "foobar";
    },
    getWebAppAppSettings : function (SPN, webAppName: string, resourceGroupName: string, deployToSlotFlag: boolean, slotName: string){
        var appSettings = {
            properties : {
                MSDEPLOY_RENAME_LOCKED_FILES : '1'
            }
        };
        return appSettings;
    },
    updateWebAppAppSettings : function (){
        return true;
    },
    updateAzureRMWebAppConfigDetails: function() {
        console.log("Successfully updated scmType to VSTSRM");
    }
});

var fs = require('fs');
tr.registerMock('fs', {
    createWriteStream: function (filePath, options) {
        var retryFunction;
        return {
            "isWriteStreamObj": true,
            "on": (name, functionOnFinish) => { retryFunction = functionOnFinish;},
            "end" : () => {
                if(retryFunction != null) {
                    retryFunction();
                }
                return true;
            }
        };
    },
    ReadStream: fs.ReadStream,
    WriteStream: fs.WriteStream,
    readFileSync: function(msDeployErrorFilePath) {
        console.log("reading the error file");
        return "ERROR DEPLOYING WEBSITE";
    },
    openSync: function (fd, options) {
        return true;
    },
    closeSync: function (fd) {
        return true;
    },
    fsyncSync: function(fd) {
        return true;
    }
});

tr.setAnswers(a);
tr.run();


text:
package org.zalando.intellij.swagger.completion.field.completion.openapi;

import com.intellij.codeInsight.completion.CompletionResultSet;
import org.zalando.intellij.swagger.completion.CompletionHelper;
import org.zalando.intellij.swagger.completion.field.FieldCompletion;
import org.zalando.intellij.swagger.completion.field.model.common.CommonFields;

class ExternalDocsCompletion extends FieldCompletion {

  ExternalDocsCompletion(
      final CompletionHelper completionHelper, final CompletionResultSet completionResultSet) {
    super(completionHelper, completionResultSet);
  }

  @Override
  public void fill() {
    CommonFields.externalDocs().forEach(this::addUnique);
  }
}


text:
using Collada141;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;

namespace Quad64
{
    class DumpModel
    {
        private static double _scale = 1.0;

        private static param MakeParam(string name, string type)
        {
            param p = new param();
            p.name = name;
            p.type = type;
            return p;
        }

        public static accessor MakePosAccessor(ulong count, string source)
        {
            accessor acc = new accessor();
            acc.stride = 3;
            acc.count = count;
            acc.source = "#" + source;
            acc.param = new param[] {
                MakeParam("X", "float"),
                MakeParam("Y", "float"),
                MakeParam("Z", "float")
            };
            return acc;
        }

        public static accessor MakeTexCoordAccessor(ulong count, string source)
        {
            accessor acc = new accessor();
            acc.stride = 2;
            acc.count = count;
            acc.source = "#" + source;
            acc.param = new param[] {
                MakeParam("S", "float"),
                MakeParam("T", "float")
            };
            return acc;
        }

        public static accessor MakeColorAccessor(ulong count, string source)
        {
            accessor acc = new accessor();
            acc.stride = 3;
            acc.count = count;
            acc.source = "#" + source;
            acc.param = new param[] {
                MakeParam("R", "float"),
                MakeParam("G", "float"),
                MakeParam("B", "float")
            };
            return acc;
        }

        public static source makePositionsSource(ref Model3D mdl)
        {
            source src = new source();
            src.id = "positions_source";
            float_array fa = new float_array();
            fa.id = "positions";

            List<double> values = new List<double>();
            for (int id_num = 0; id_num < mdl.meshes.Count; id_num++)
            {
                int len = mdl.meshes[id_num].vertices.Length;
                for (int i = 0; i < len; i++)
                {
                    values.Add(mdl.meshes[id_num].vertices[i].X * _scale);
                    values.Add(mdl.meshes[id_num].vertices[i].Y * _scale);
                    values.Add(mdl.meshes[id_num].vertices[i].Z * _scale);
                }
            }
            fa.Values = values.ToArray();
            fa.count = (ulong)fa.Values.LongLength;

            src.technique_common = new sourceTechnique_common();
            src.technique_common.accessor = MakePosAccessor(fa.count / 3, fa.id);
            src.Item = fa;
            return src;
        }

        public static source makeTexCoordSource(ref Model3D mdl)
        {

            source src = new source();
            src.id = "texCoord_source";
            float_array fa = new float_array();
            fa.id = "texCoord";

            List<double> values = new List<double>();
            for (int id_num = 0; id_num < mdl.meshes.Count; id_num++)
            {
                bool clampX = mdl.meshes[id_num].texture.TextureParamS == 33071;
                bool clampY = mdl.meshes[id_num].texture.TextureParamT == 33071;
                int len = mdl.meshes[id_num].colors.Length;
                for (int i = 0; i < len; i++)
                {
                    float X = mdl.meshes[id_num].texCoord[i].X;
                    float Y = mdl.meshes[id_num].texCoord[i].Y;
                    if (clampX)
                        X = (X > 1.0f ? 1.0f : (X < 0.0f ? 0.0f : X));
                    if (clampY)
                        Y = (Y > 1.0f ? 1.0f : (Y < 0.0f ? 0.0f : Y));

                    values.Add(X);
                    values.Add(-Y);
                }
            }
            fa.Values = values.ToArray();
            fa.count = (ulong)fa.Values.LongLength;

            src.technique_common = new sourceTechnique_common();
            src.technique_common.accessor = MakeTexCoordAccessor(fa.count / 2, fa.id);
            src.Item = fa;
            return src;
        }

        public static source makeColorSource(ref Model3D mdl)
        {
            source src = new source();
            src.id = "color_source";
            float_array fa = new float_array();
            fa.id = "color";

            List<double> values = new List<double>();
            for (int id_num = 0; id_num < mdl.meshes.Count; id_num++)
            {
                int len = mdl.meshes[id_num].colors.Length;
                for (int i = 0; i < len; i++)
                {
                    values.Add(mdl.meshes[id_num].colors[i].X);
                    values.Add(mdl.meshes[id_num].colors[i].Y);
                    values.Add(mdl.meshes[id_num].colors[i].Z);
                }
            }
            fa.Values = values.ToArray();
            fa.count = (ulong)fa.Values.LongLength;

            src.technique_common = new sourceTechnique_common();
            src.technique_common.accessor = MakeColorAccessor(fa.count / 3, fa.id);
            src.Item = fa;
            return src;
        }

        public static InputLocal makeInput(string source, string semantic)
        {
            InputLocal input = new InputLocal();
            input.source = "#" + source;
            input.semantic = semantic;
            return input;
        }

        public static InputLocalOffset makeInputOffset(string source, string semantic,
            ulong offset, bool setSpecified, ulong set)
        {
            InputLocalOffset input = new InputLocalOffset();
            input.source = "#" + source;
            input.semantic = semantic;
            input.offset = offset;
            input.set = set;
            input.setSpecified = setSpecified;
            return input;
        }

        public static vertices MakeVertices()
        {
            vertices verts = new vertices();
            verts.id = "vertices";
            verts.input = new InputLocal[] { makeInput("positions_source", "POSITION") };
            return verts;
        }

        public static polylist MakePolyList(ulong id_num, uint[] indices, ref uint largest_offset)
        {
            polylist plist = new polylist();
            plist.material = "MaterialInstance_" + id_num;
            plist.input = new InputLocalOffset[] {
                makeInputOffset("vertices", "VERTEX", 0, false, 0),
                makeInputOffset("texCoord_source", "TEXCOORD", 1, true, 0),
                makeInputOffset("color_source", "COLOR", 2, true, 0)
            };
            string p = "", vcount = "";
            long len = indices.LongLength;
            uint largest = largest_offset;
            for (long i = 0; i < len; i++)
            {
                if(i % 3 == 0)
                    vcount += "3 ";
                uint index = indices[i] + largest_offset;
                largest = Math.Max(largest, indices[i] + largest_offset);
                p += index.ToString() + " " + index.ToString() + " " + index.ToString();
                if (i < len - 1)
                    p += " ";
            }
            largest_offset = largest + 1;

            plist.vcount = vcount;
            plist.count = (ulong)(indices.LongLength / 3);
            plist.p = p;

            return plist;
        }

        public static library_geometries MakeGeometryLibrary(ref Model3D mdl)
        {
            library_geometries lib_geo = new library_geometries();
            //lib_geo.id = "lib_geo";
            ulong len = (ulong)mdl.builder.TextureImages.Count;

            geometry geo = new geometry();

            //for (ulong i = 0; i < len; i++)
            //{
            geo = new geometry();
            geo.id = "geometry";
            mesh m = new mesh();

            m.source = new source[] {
                makePositionsSource(ref mdl),
                makeTexCoordSource(ref mdl),
                makeColorSource(ref mdl)
            };

            m.vertices = MakeVertices();
            List<object> polyLists = new List<object>();
            uint indices_offset = 0;
            for (ulong i = 0; i < len; i++)
            {
                polyLists.Add(MakePolyList(i, mdl.meshes[(int)i].indices, ref indices_offset));
                //indices_offset += (uint)mdl.meshes[(int)i].indices.LongLength;
            }
            m.Items = polyLists.ToArray();
            geo.Item = m;

            lib_geo.geometry = new geometry[] { geo };
            return lib_geo;
        }

        private static image MakeImage(ulong id_num, string modelName)
        {
            image img = new image();
            img.id = "image_"+id_num;
            img.Item = modelName + "/" + id_num + ".png";
            return img;
        }

        private static library_images MakeImagesLibrary(ref Model3D mdl, string modelName)
        {
            library_images lib_img = new library_images();
            int len = mdl.builder.TextureImages.Count;

            image[] imgs = new image[len];
            for (ulong i = 0; i < (ulong)imgs.LongLength; i++)
                imgs[i] = MakeImage(i, modelName);
            lib_img.image = imgs;
            return lib_img;
        }

        private static common_newparam_type MakeNewParamForEffect(ulong id_num, bool isSampler2D)
        {
            common_newparam_type newparam = new common_newparam_type();
            if (isSampler2D)
            {
                fx_sampler2D_common sampler2D = new fx_sampler2D_common();
                sampler2D.source = "surface_" + id_num;
                newparam.Item = sampler2D;
                newparam.ItemElementName = ItemChoiceType.sampler2D;
                newparam.sid = "sampler2D_" + id_num;
            }
            else
            {
                fx_surface_init_from_common initFrom = new fx_surface_init_from_common();
                fx_surface_common surface = new fx_surface_common();
                initFrom.Value = "image_" + id_num;
                surface.type = fx_surface_type_enum.Item2D;
                surface.init_from = new fx_surface_init_from_common[] {
                    initFrom
                };
                newparam.Item = surface;
                newparam.ItemElementName = ItemChoiceType.surface;
                newparam.sid = "surface_" + id_num;
            }
            return newparam;
        }

        private static effectFx_profile_abstractProfile_COMMON MakeProfileCOMMON(ulong id_num)
        {
            effectFx_profile_abstractProfile_COMMON proCom = new effectFx_profile_abstractProfile_COMMON();
            proCom.technique = new effectFx_profile_abstractProfile_COMMONTechnique();
            effectFx_profile_abstractProfile_COMMONTechniqueLambert lambert = new effectFx_profile_abstractProfile_COMMONTechniqueLambert();
            common_color_or_texture_type diffuse = new common_color_or_texture_type();
            common_color_or_texture_typeTexture tex = new common_color_or_texture_typeTexture();
            tex.texture = "sampler2D_"+ id_num;
            diffuse.Item = tex;
            lambert.diffuse = diffuse;
            proCom.Items = new object[] {
                MakeNewParamForEffect(id_num, false),
                MakeNewParamForEffect(id_num, true)
            };
            proCom.technique.Item = lambert;
            return proCom;
        }

        private static effect MakeEffect(ulong id_num)
        {
            effect eff = new effect();
            eff.id = "effect_" + id_num;
            eff.Items = new effectFx_profile_abstractProfile_COMMON[]
            {
                MakeProfileCOMMON(id_num)
            };
            return eff;
        }

        private static library_effects MakeEffectsLibrary(ref Model3D mdl, string modelName)
        {
            library_effects lib_eff = new library_effects();

            int len = mdl.builder.TextureImages.Count;

            effect[] effects = new effect[len];
            for (ulong i = 0; i < (ulong)effects.LongLength; i++)
                effects[i] = MakeEffect(i);

            lib_eff.effect = effects;
            return lib_eff;
        }

        private static material MakeMaterial(ulong id_num)
        {
            material mat = new material();
            mat.name = "Material_" + id_num;
            mat.id = "material_" + id_num;
            instance_effect ieffect = new instance_effect();
            ieffect.url = "#effect_" + id_num;
            mat.instance_effect = ieffect;
            return mat;
        }

        private static library_materials MakeMaterialsLibrary(ref Model3D mdl)
        {
            library_materials lib_mats = new library_materials();

            int len = mdl.builder.TextureImages.Count;

            material[] materials = new material[len];
            for (ulong i = 0; i < (ulong)materials.LongLength; i++)
                materials[i] = MakeMaterial(i);

            lib_mats.material = materials;
            return lib_mats;
        }

        private static bind_material MakeBindedMaterial(ref Model3D mdl)
        {
            bind_material bm = new bind_material();
            instance_material[] materials = new instance_material[mdl.builder.TextureImages.Count];
            for (int id_num = 0; id_num < materials.Length; id_num++)
            {
                materials[id_num] = new instance_material();
                materials[id_num].symbol = "MaterialInstance_" + id_num;
                materials[id_num].target = "#material_" + id_num;
            }

            bm.technique_common = materials;
            return bm;
        }

        private static library_visual_scenes MakeVisualScenesLibrary(ref Model3D mdl)
        {
            library_visual_scenes lib_visuals = new library_visual_scenes();
            visual_scene vs = new visual_scene();
            vs.id = "scene";
            node geo_node = new node();
            geo_node.id = "node";
            geo_node.name = "node";
            geo_node.type = NodeType.NODE;
            matrix transform_matrix = new matrix();
            transform_matrix.Values = new double[] {
                1, 0, 0, 0,
                0, 0,-1, 0,
                0, 1, 0, 0,
                0, 0, 0, 1
            };
            geo_node.Items = new object[] {
                transform_matrix
            };
            geo_node.ItemsElementName = new ItemsChoiceType2[] {
                ItemsChoiceType2.matrix
            };
            transform_matrix.sid = "transform";
            int len = mdl.builder.TextureImages.Count;

            instance_geometry geo = new instance_geometry();
            geo.url = "#geometry";
            geo.bind_material = MakeBindedMaterial(ref mdl);

            geo_node.instance_geometry = new instance_geometry[] { geo };

            vs.node = new node[] { geo_node };
            lib_visuals.visual_scene = new visual_scene[] { vs };
            return lib_visuals;
        }

        private static void WriteAllTextures(List<Bitmap> textures, string modelName)
        {
            for(int img_index = 0; img_index < textures.Count; img_index++)
            {
                string filepath = Directory.GetCurrentDirectory() + "\\" + modelName + "\\" + img_index + ".png";
                (new FileInfo(filepath)).Directory.Create();
                textures[img_index].Save(filepath, System.Drawing.Imaging.ImageFormat.Png);
            }
        }

        public static void dumpModelToCOLLADA(Model3D mdl, float scale)
        {
            _scale = scale;
            COLLADA model = new COLLADA();
            model.scene = new COLLADAScene();
            model.scene.instance_visual_scene = new InstanceWithExtra();
            model.scene.instance_visual_scene.url = "#scene";
            model.asset = new asset();
            model.asset.unit = new assetUnit();
            model.asset.unit.meter = 1.0;
            model.asset.unit.name = "meter";
            model.asset.up_axis = UpAxisType.Z_UP;

            model.Items = new object[] {
                MakeImagesLibrary(ref mdl, "Test"),
                MakeEffectsLibrary(ref mdl, "Test"),
                MakeMaterialsLibrary(ref mdl),
                MakeGeometryLibrary(ref mdl),
                MakeVisualScenesLibrary(ref mdl)
            };
            WriteAllTextures(mdl.builder.TextureImages, "Test");
            model.Save("Test.dae");
        }
    }
}


text:
using System.Web.Mvc;

namespace AngularJS_SignalR.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Title = "Home Page";

            return View();
        }
    }
}


text:
/*global describe, it, expect, require, beforeEach*/
const layoutGeometry = require('../../../src/core/layout/layout-geometry');
describe('layoutGeometry', function () {
	'use strict';
	describe('unitVector', function () {
		[
			[[1, 0], [1, 0]],
			[[2, 0], [1, 0]],
			[[0, 1], [0, 1]],
			[[0, 2], [0, 1]],
			[[3, 4], [3 / 5, 4 / 5]],
			[[0, 0], [0, 0]]
		].forEach(function (args) {
			it('should return ' + JSON.stringify(args[1]) + ' as the unit vector for ' + JSON.stringify(args[0]), function () {
				expect(layoutGeometry.unitVector(args[0])).toEqual(args[1]);
			});
		});

	});
	describe('projectPointOnLineVector', function () {
		it('should project point on horizontal line', function () {
			expect(layoutGeometry.projectPointOnLineVector([2, 0], [0, 1], [1, 0])).toEqual([2, 1]);
		});
		it('should project point on vertical line', function () {
			expect(layoutGeometry.projectPointOnLineVector([0, 3], [1, 0], [0, 1])).toEqual([1, 3]);
		});
		it('should project point onto an upward sloped line', function () {
			expect(layoutGeometry.projectPointOnLineVector([2, 3], [0, 0], [1, 2])).toEqual([8 / 5, 16 / 5]);
		});
		it('should project point onto an downward sloped line', function () {
			expect(layoutGeometry.projectPointOnLineVector([0, -2], [0, 0], [1, 3])).toEqual([-3 / 5, -9 / 5]);
		});
		it('should project point on a line when it is the origin', function () {
			expect(layoutGeometry.projectPointOnLineVector([2, 0], [2, 0], [1, 0])).toEqual([2, 0]);
		});
		it('should project point on a line when it is not the origin', function () {
			expect(layoutGeometry.projectPointOnLineVector([3, 0], [2, 0], [1, 0])).toEqual([3, 0]);
		});
		describe('should throw invalid-args exception', function () {
			it('when vector is 0', function () {
				expect(function () {
					layoutGeometry.projectPointOnLineVector([3, 0], [2, 0], [0, 0]);
				}).toThrow('invalid-args');
			});
		});

	});
	describe('orderPointsOnVector', function () {
		let points;
		describe('when vector is horizontal', function () {
			beforeEach(function () {
				points = [[2, 1], [3, 1], [0, 1], [-2, 1]];
			});
			it('should order points left to right', function () {
				expect(layoutGeometry.orderPointsOnVector(points, [0, 1], [1, 0])).toEqual([[0, 1], [2, 1], [3, 1]]);
			});
			it('should order points left to right and include points before origin', function () {
				expect(layoutGeometry.orderPointsOnVector(points, [0, 1], [1, 0], true)).toEqual([[-2, 1]]);
			});
			it('should order points right to left', function () {
				expect(layoutGeometry.orderPointsOnVector(points, [0, 1], [-1, 0])).toEqual([[0, 1], [-2, 1]]);
			});
			it('should order points right to left and include points before origin', function () {
				expect(layoutGeometry.orderPointsOnVector(points, [0, 1], [-1, 0], true)).toEqual([[3, 1], [2, 1]]);
			});

		});
		describe('when vector is vertical', function () {
			beforeEach(function () {
				points = [[1, 2], [1, 3], [1, 0], [1, -2]];
			});
			it('should order points bottom to top', function () {
				expect(layoutGeometry.orderPointsOnVector(points, [1, 0], [0, 1])).toEqual([[1, 0], [1, 2], [1, 3]]);
			});
			it('should order points bottom to top and include points before origin', function () {
				expect(layoutGeometry.orderPointsOnVector(points, [1, 0], [0, 1], true)).toEqual([[1, -2]]);
			});
			it('should order points top to bottom', function () {
				expect(layoutGeometry.orderPointsOnVector(points, [1, 0], [0, -1])).toEqual([[1, 0], [1, -2]]);
			});
			it('should order points top to bottom and include points before origin', function () {
				expect(layoutGeometry.orderPointsOnVector(points, [1, 0], [0, -1], true)).toEqual([[1, 3], [1, 2]]);
			});
		});
		describe('when line is sloped', function () {
			beforeEach(function () {
				points = [[4, 2], [2, 4], [3, 3], [7, -1]];
			});
			it('should order points top to bottom', function () {
				expect(layoutGeometry.orderPointsOnVector(points, [3, 3], [1, -1])).toEqual([[3, 3], [4, 2], [7, -1]]);
			});
			it('should order points bottom to top', function () {
				expect(layoutGeometry.orderPointsOnVector(points, [3, 3], [-1, 1])).toEqual([[3, 3], [2, 4]]);
			});

		});
	});
	describe('translatePoly', function () {
		it('should move all points of all regions in the poly', function () {
			expect(layoutGeometry.translatePoly([
				[[1, 2], [2, 3]],
				[[2, 1], [3, 2]]
			], [2, 3])).toEqual([
				[[3, 5], [4, 6]],
				[[4, 4], [5, 5]]
			]);
		});
	});
	describe('addVectors', function () {
		it('should add vectors', function () {
			expect(layoutGeometry.addVectors([1, 2], [3, 4])).toEqual([4, 6]);
		});
		describe('should throw exception', function () {
			it('when vector1 is falsy', function () {
				expect(function () {
					layoutGeometry.addVectors(undefined, [3, 4]);
				}).toThrow();
			});
			it('when vector2 is falsy', function () {
				expect(function () {
					layoutGeometry.addVectors([1, 2]);
				}).toThrow();
			});
			it('when result is not a number', function () {
				expect(function () {
					layoutGeometry.addVectors([1, 'a'], [3, 4]);
				}).toThrow();
			});
		});
	});
	describe('subtractVectors', function () {
		it('should subtract vectors', function () {
			expect(layoutGeometry.subtractVectors([1, 2], [3, 4])).toEqual([-2, -2]);
		});
		describe('should throw exception', function () {
			it('when vector1 is falsy', function () {
				expect(function () {
					layoutGeometry.subtractVectors(undefined, [3, 4]);
				}).toThrow();
			});
			it('when vector2 is falsy', function () {
				expect(function () {
					layoutGeometry.subtractVectors([1, 2]);
				}).toThrow();
			});
			it('when result is not a number', function () {
				expect(function () {
					layoutGeometry.subtractVectors([1, 'a'], [3, 4]);
				}).toThrow();
			});
		});
	});
	describe('translatePoly', function () {
		it('should translate a single point in a single region', function () {
			expect(layoutGeometry.translatePoly([[[1, 2]]],  [2, 3])).toEqual([[[3, 5]]]);
		});
		it('should translate a multiple points in a multiple regions',  function () {
			const poly = [
				[
					[1, 2],  [3, 4]
				],
				[
					[2, 4],  [6, 8]
				]
			];
			expect(layoutGeometry.translatePoly(poly,  [2, 3])).toEqual([
				[
					[3, 5],  [5, 7]
				],
				[
					[4, 7],  [8, 11]
				]
			]);
		});
	});

	describe('firstProjectedPolyPointOnVector', function () {
		let poly, vector;
		beforeEach(function () {
			poly = [
				[
					[-20, 20], [20, 20], [20, -20], [-20, -20]
				]
			];
		});
		describe('should return first projected point', function () {
			describe('when the vector is horizontal', function () {
				describe('left to right', function () {
					beforeEach(function () {
						vector = [1, 0];
					});
					it('should return falsy when all points are after the origin', function () {
						expect(layoutGeometry.firstProjectedPolyPointOnVector(poly, [-20, 10], vector)).toBeFalsy();
					});
					it('when some points are before the origin', function () {
						expect(layoutGeometry.firstProjectedPolyPointOnVector(poly, [0, 0], vector)).toEqual([-20, 0]);
					});
					it('when all points are before the origin', function () {
						expect(layoutGeometry.firstProjectedPolyPointOnVector(poly, [30, 10], vector)).toEqual([-20, 10]);
					});
				});
				describe('right to left', function () {
					beforeEach(function () {
						vector = [-1, 0];
					});
					it('when all points are after the origin', function () {
						expect(layoutGeometry.firstProjectedPolyPointOnVector(poly, [-30, 10], vector)).toEqual([20, 10]);
					});
					it('when some points are after the origin', function () {
						expect(layoutGeometry.firstProjectedPolyPointOnVector(poly, [0, 0], vector)).toEqual([20, 0]);
					});
					it('should return falsy when all points are after the origin', function () {
						expect(layoutGeometry.firstProjectedPolyPointOnVector(poly, [20, 10], vector)).toBeFalsy();
					});

				});
			});
			describe('when the vector is vertical', function () {
				describe('top to bottom', function () {
					beforeEach(function () {
						vector = [0, -1];
					});
					it('when all points are before the origin', function () {
						expect(layoutGeometry.firstProjectedPolyPointOnVector(poly, [10, -30], vector)).toEqual([10, 20]);
					});
					it('when some points are before the origin', function () {
						expect(layoutGeometry.firstProjectedPolyPointOnVector(poly, [0, 0], vector)).toEqual([0, 20]);
					});
					it('should return falsy when all points are after the origin', function () {
						expect(layoutGeometry.firstProjectedPolyPointOnVector(poly, [10, 20], vector)).toBeFalsy();
					});
				});
				describe('bottom to top', function () {
					beforeEach(function () {
						vector = [0, 1];
					});
					it('when all points are before the origin', function () {
						expect(layoutGeometry.firstProjectedPolyPointOnVector(poly, [10, 30], vector)).toEqual([10, -20]);
					});
					it('when some points are before the origin', function () {
						expect(layoutGeometry.firstProjectedPolyPointOnVector(poly, [0, 0], vector)).toEqual([0, -20]);
					});
					it('should return falsy when all points are after the origin', function () {
						expect(layoutGeometry.firstProjectedPolyPointOnVector(poly, [10, -20], vector)).toBeFalsy();
					});
				});

			});

		});
	});
	describe('furthestIntersectionPoint', function () {
		let movePoly, placedPolys, vectorOrigin;
		beforeEach(function () {
			movePoly = [
				[
					[-20, 20], [20, 20], [20, -20], [-20, -20]
				]
			];
			placedPolys = [
				[
					[-15, 15], [-5, 15], [-5, -5], [-15, -5]
				],
				[
					[-30, -10], [-10, -10], [-10, -30], [-30, -30]
				],
				[
					[10, -10], [30, -10], [30, -30], [10, -30]
				]
			];
			vectorOrigin = [0, 0];
		});
		describe('should return the most distant intersection point', function () {
			describe('when vector is horizontal', function () {
				it('left to right', function () {
					expect(layoutGeometry.furthestIntersectionPoint(movePoly, placedPolys, vectorOrigin, [1, 0])).toEqual([20, 0]);
				});
				it('right to left', function () {
					expect(layoutGeometry.furthestIntersectionPoint(movePoly, placedPolys, vectorOrigin, [-1, 0])).toEqual([-20, 0]);
				});
			});
			describe('when vector is vertical', function () {
				it('bottom to top', function () {
					expect(layoutGeometry.furthestIntersectionPoint(movePoly, placedPolys, vectorOrigin, [0, 1])).toEqual([0, 15]);
				});
				it('top to bottom', function () {
					expect(layoutGeometry.furthestIntersectionPoint(movePoly, placedPolys, vectorOrigin, [0, -1])).toEqual([0, -20]);
				});
			});
			describe('when vector is sloped', function () {
				it('top to bottom left to right', function () {
					expect(layoutGeometry.furthestIntersectionPoint(movePoly, placedPolys, vectorOrigin, [1, -1])).toEqual([20, -20]);
				});
				it('top to bottom right to left', function () {
					expect(layoutGeometry.furthestIntersectionPoint(movePoly, placedPolys, vectorOrigin, [-1, -1])).toEqual([-20, -20]);
				});
				it('bottom to top left to right', function () {
					expect(layoutGeometry.furthestIntersectionPoint(movePoly, placedPolys, vectorOrigin, [1, 1])).toEqual([5, 5]);
				});
				it('bottom to top right to left', function () {
					expect(layoutGeometry.furthestIntersectionPoint(movePoly, placedPolys, vectorOrigin, [-1, 1])).toEqual([-15, 15]);
				});
			});
		});
	});
	describe('translatePolyToIntersecton', function () {
		let movePoly, vector;
		beforeEach(function () {
			movePoly = [
				[
					[-20, 20], [20, 20], [20, -20], [-20, -20]
				]
			];
		});
		describe('when vector is horizontal', function () {
			describe('left to right', function () {
				beforeEach(function () {
					vector = [1, 0];
				});
				it('should return translation', function () {
					const result = layoutGeometry.translatePolyToIntersecton(movePoly, [0, 0], vector);
					expect(result.translation).toEqual([20, 0]);
				});
				it('should return the translated poly', function () {
					const result = layoutGeometry.translatePolyToIntersecton(movePoly, [0, 0], vector);
					expect(result.translatedPoly).toEqual([
						[
							[0, 20], [40, 20], [40, -20], [0, -20]
						]
					]);
				});
				it('should return falsy when the intersection is before the poly', function () {
					expect(layoutGeometry.translatePolyToIntersecton(movePoly, [-20, 0], vector)).toBeFalsy();
				});
			});
			describe('right to left', function () {
				beforeEach(function () {
					vector = [-1, 0];
				});
				it('should return translation', function () {
					const result = layoutGeometry.translatePolyToIntersecton(movePoly, [0, 0], vector);
					expect(result.translation).toEqual([-20, 0]);
				});
				it('should return the translated poly', function () {
					const result = layoutGeometry.translatePolyToIntersecton(movePoly, [0, 0], vector);
					expect(result.translatedPoly).toEqual([
						[
							[-40, 20], [0, 20], [0, -20], [-40, -20]
						]
					]);
				});
				it('should return falsy when the intersection is before the poly', function () {
					expect(layoutGeometry.translatePolyToIntersecton(movePoly, [20, 0], vector)).toBeFalsy();
				});
			});
		});
		describe('when vector is vertical', function () {
			describe('top to bottom', function () {
				beforeEach(function () {
					vector = [0, -1];
				});
				it('should return translation', function () {
					const result = layoutGeometry.translatePolyToIntersecton(movePoly, [0, 0], vector);
					expect(result.translation).toEqual([0, -20]);
				});
				it('should return the translated poly', function () {
					const result = layoutGeometry.translatePolyToIntersecton(movePoly, [0, 0], vector);
					expect(result.translatedPoly).toEqual([
						[
							[-20, 0], [20, 0], [20, -40], [-20, -40]
						]
					]);
				});
				it('should return falsy when the intersection is before the poly', function () {
					expect(layoutGeometry.translatePolyToIntersecton(movePoly, [0, 20], vector)).toBeFalsy();
				});
			});
			describe('bottom to top', function () {
				beforeEach(function () {
					vector = [0, 1];
				});
				it('should return translation', function () {
					const result = layoutGeometry.translatePolyToIntersecton(movePoly, [0, 0], vector);
					expect(result.translation).toEqual([0, 20]);
				});
				it('should return the translated poly', function () {
					const result = layoutGeometry.translatePolyToIntersecton(movePoly, [0, 0], vector);
					expect(result.translatedPoly).toEqual([
						[
							[-20, 40], [20, 40], [20, 0], [-20, 0]
						]
					]);
				});
				it('should return falsy when the intersection is before the poly', function () {
					expect(layoutGeometry.translatePolyToIntersecton(movePoly, [0, -20], vector)).toBeFalsy();
				});
			});
		});
		describe('when vector is diagonal', function () {
			describe('top to bottom', function () {
				beforeEach(function () {
					vector = [1, -1];
				});
				it('should return translation', function () {
					const result = layoutGeometry.translatePolyToIntersecton(movePoly, [0, 0], vector);
					expect(result.translation).toEqual([20, -20]);
				});
				it('should return the translated poly', function () {
					const result = layoutGeometry.translatePolyToIntersecton(movePoly, [0, 0], vector);
					expect(result.translatedPoly).toEqual([
						[
							[0, 0], [40, 0], [40, -40], [0, -40]
						]
					]);
				});
				it('should return falsy when the intersection is before the poly', function () {
					expect(layoutGeometry.translatePolyToIntersecton(movePoly, [-20, 20], vector)).toBeFalsy();
				});
			});
			describe('bottom to top', function () {
				beforeEach(function () {
					vector = [1, 1];
				});
				it('should return translation', function () {
					const result = layoutGeometry.translatePolyToIntersecton(movePoly, [0, 0], vector);
					expect(result.translation).toEqual([20, 20]);
				});
				it('should return the translated poly', function () {
					const result = layoutGeometry.translatePolyToIntersecton(movePoly, [0, 0], vector);
					expect(result.translatedPoly).toEqual([
						[
							[0, 40], [40, 40], [40, 0], [0, 0]
						]
					]);
				});
				it('should return falsy when the intersection is before the poly', function () {
					expect(layoutGeometry.translatePolyToIntersecton(movePoly, [-20, -20], vector)).toBeFalsy();
				});
			});
		});
	});
	describe('translatePolyToNotOverlap', function () {
		let movePoly, placedPolys, vector, result;
		beforeEach(function () {
			movePoly = [
				[
					[-20, 20], [20, 20], [20, -20], [-20, -20]
				]
			];
			placedPolys = [
				[
					[-15, 15], [-5, 15], [-5, -5], [-15, -5]
				],
				[
					[-30, -10], [-10, -10], [-10, -30], [-30, -30]
				],
				[
					[10, -10], [30, -10], [30, -30], [10, -30]
				]
			];
		});
		it('should return the containg poly is one is completely inside the other', function () {
			vector = [1, 0];
			movePoly = [
				[
					[-25, -15], [-15, -15], [-15, -25], [-25, -25]
				]
			];
			result = layoutGeometry.translatePolyToNotOverlap(movePoly, placedPolys, [0, 0], vector);
			expect(result.translation).toEqual([15, 0]);
			expect(result.translatedPoly).toEqual([[[-10, -15],  [0, -15],  [0, -25],  [-10, -25]]]);
		});
		describe('when vector is horizontal', function () {
			describe('left to right', function () {
				beforeEach(function () {
					vector = [1, 0];
				});
				it('should return translation', function () {
					result = layoutGeometry.translatePolyToNotOverlap(movePoly, placedPolys, [0, 0], vector);
					expect(result.translation).toEqual([50, 0]);
				});
				it('should return the translated poly', function () {
					result = layoutGeometry.translatePolyToNotOverlap(movePoly, placedPolys, [0, 0], vector);
					expect(result.translatedPoly).toEqual([[[30, 20], [70, 20], [70, -20], [30, -20]]]);

				});
			});
			describe('right to left', function () {
				beforeEach(function () {
					vector = [-1, 0];
				});
				it('should return translation', function () {
					result = layoutGeometry.translatePolyToNotOverlap(movePoly, placedPolys, [0, 0], vector);
					expect(result.translation).toEqual([-50, 0]);
				});
				it('should return the translated poly', function () {
					result = layoutGeometry.translatePolyToNotOverlap(movePoly, placedPolys, [0, 0], vector);
					expect(result.translatedPoly).toEqual([[[-70, 20], [-30, 20], [-30, -20], [-70, -20]]]);

				});
			});
		});
		describe('when vector is vertical', function () {
			describe('top to bottom', function () {
				beforeEach(function () {
					vector = [0, -1];
				});
				it('should return translation', function () {
					const result = layoutGeometry.translatePolyToNotOverlap(movePoly, placedPolys, [0, 0], vector);
					expect(result.translation).toEqual([0, -50]);
				});
				it('should return the translated poly', function () {
					const result = layoutGeometry.translatePolyToNotOverlap(movePoly, placedPolys, [0, 0], vector);
					expect(result.translatedPoly).toEqual([[[-20, -30], [20, -30], [20, -70], [-20, -70]]]);

				});

			});
			describe('bottom to top', function () {
				beforeEach(function () {
					vector = [0, 1];
				});
				it('should return translation', function () {
					const result = layoutGeometry.translatePolyToNotOverlap(movePoly, placedPolys, [0, 0], vector);
					expect(result.translation).toEqual([0, 35]);
				});
				it('should return the translated poly', function () {
					const result = layoutGeometry.translatePolyToNotOverlap(movePoly, placedPolys, [0, 0], vector);
					expect(result.translatedPoly).toEqual([[[-20, 55], [20, 55], [20, 15], [-20, 15]]]);

				});

			});

		});
		describe('when vector is diagonal', function () {
			describe('bottom to top', function () {
				beforeEach(function () {
					vector = [1, 1];
				});
				it('should return translation', function () {
					const result = layoutGeometry.translatePolyToNotOverlap(movePoly, placedPolys, [0, 0], vector);
					expect(result.translation).toEqual([25, 25]);
				});
				it('should return the translated poly', function () {
					const result = layoutGeometry.translatePolyToNotOverlap(movePoly, placedPolys, [0, 0], vector);
					expect(result.translatedPoly).toEqual([[[5, 45], [45, 45], [45, 5], [5, 5]]]);

				});

			});
			describe('top to bottom', function () {
				beforeEach(function () {
					vector = [1, -1];
				});
				it('should return translation', function () {
					const result = layoutGeometry.translatePolyToNotOverlap(movePoly, placedPolys, [0, 0], vector);
					expect(result.translation).toEqual([50, -50]);
				});
				it('should return the translated poly', function () {
					const result = layoutGeometry.translatePolyToNotOverlap(movePoly, placedPolys, [0, 0], vector);
					expect(result.translatedPoly).toEqual([[[30, -30], [70, -30], [70, -70], [30, -70]]]);

				});

			});
		});
		describe('when the intersection is before the origin', function () {
			beforeEach(function () {
				placedPolys = [
					[
						[-15, 15], [-5, 15], [-5, -5], [-15, -5]
					],
					[
						[-30, -10], [-10, -10], [-10, -30], [-30, -30]
					]
				];
				vector = [1, 0];
			});
			it('should return translation', function () {
				const result = layoutGeometry.translatePolyToNotOverlap(movePoly, placedPolys, [0, 0], vector);
				expect(result.translation).toEqual([15, 0]);
			});
			it('should return the translated poly', function () {
				const result = layoutGeometry.translatePolyToNotOverlap(movePoly, placedPolys, [0, 0], vector);
				expect(result.translatedPoly).toEqual([[[-5, 20], [35, 20], [35, -20], [-5, -20]]]);

			});

		});
		describe('when the first translation causes a new intersection', function () {
			beforeEach(function () {
				placedPolys = [
					[
						[-15, 15], [-5, 15], [-5, -5], [-15, -5]
					],
					[
						[-30, -10], [-10, -10], [-10, -30], [-30, -30]
					],
					[
						[25, -5], [45, -5], [45, -25], [25, -25]
					]
				];
				vector = [1, 0];
			});
			it('should return translation', function () {
				const result = layoutGeometry.translatePolyToNotOverlap(movePoly, placedPolys, [0, 0], vector);
				expect(result.translation).toEqual([65, 0]);
			});
			it('should return the translated poly', function () {
				const result = layoutGeometry.translatePolyToNotOverlap(movePoly, placedPolys, [0, 0], vector);
				expect(result.translatedPoly).toEqual([[[45, 20], [85, 20], [85, -20], [45, -20]]]);

			});
		});
	});
	describe('polygonIntersectionPoints', function () {
		let p1, p2;
		beforeEach(function () {
			p1 = [
				[[-20, 20], [20, 20], [20, -20], [-20, -20]]
			];
			p2 = [
				[[0, 30], [30, 30], [30, 0], [0, 0]],
				[[-30, 0], [0, 0], [0, -30], [-30, -30]]
			];

		});
		it('should return intersection between overlapping shapes', function () {
			expect(layoutGeometry.polygonIntersectionPoints(p1, p2)).toEqual([[0, 0], [0, -20], [-20, -20], [-20, 0], [20, 20], [20, 0], [0, 0], [0, 20]]);
		});
		it('should return intersection between same shapes', function () {
			p2 = [
				[[-20, 20], [20, 20], [20, -20], [-20, -20]],
				[[-130, -100], [-100, -100], [-110, -130], [-130, -130]]
			];
			expect(layoutGeometry.polygonIntersectionPoints(p1, p2)).toEqual([[20, 20], [20, -20], [-20, -20], [-20, 20]]);
		});
		it('should return second shape as intersection when second shape is contained in first', function () {
			p2 = [
				[[10, 10], [10, -10], [-10, -10], [-10, 10]]
			];
			expect(layoutGeometry.polygonIntersectionPoints(p1, p2)).toEqual(p2[0]);
		});
		it('should return second shape as intersection when first shape is contained in second', function () {
			p1 = [
				[[5, 15], [15, 15], [15, 5], [5, 5]]
			];
			expect(layoutGeometry.polygonIntersectionPoints(p1, p2)).toEqual([[0, 30], [30, 30], [30, 0], [0, 0]]);
		});
	});
	describe('shapeContainingIntersection', function () {
		let intersection, poly;
		beforeEach(function () {
			intersection = [
				[[5, 15], [15, 15], [15, 5], [5, 5]]
			];
			poly = [
				[[0, 30], [30, 30], [30, 0], [0, 0]],
				[[-30, 0], [0, 0], [0, -30], [-30, -30]]
			];
		});
		it('should return the shape containing the intersection', function () {
			expect(layoutGeometry.shapeContainingIntersection(poly, intersection)).toEqual([[0, 30], [30, 30], [30, 0], [0, 0]]);
		});
		it('should return falsy when no shape contains the intersection', function () {
			intersection = [
				[[-15, 15], [15, 15], [15, -15], [-15, -15]]
			];
			expect(layoutGeometry.shapeContainingIntersection(poly, intersection)).toBeFalsy();
		});
	});
});


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="org.gameplay3d.sample_character"
        android:versionCode="1"
        android:versionName="1.0">

    <uses-sdk android:minSdkVersion="16" />
	<uses-feature android:glEsVersion="0x00020000"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application android:icon="@drawable/icon" android:label="@string/app_name" android:hasCode="true">
        <activity android:name="org.gameplay3d.GamePlayNativeActivity"
                  android:label="@string/app_name"
                  android:configChanges="orientation|screenSize|keyboardHidden"
				  android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
				  android:screenOrientation="landscape">
            <meta-data android:name="android.app.lib_name" android:value="sample-character" />
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


text:
package protoutil_test

import (
	"bytes"
	"testing"

	"github.com/golang/protobuf/proto"
	"github.com/hyperledger/fabric-protos-go/common"
	"github.com/hyperledger/fabric/protoutil"
)

// More duplicate utility which should go away, but the utils are a bit of a mess right now with import cycles
func marshalOrPanic(msg proto.Message) []byte {
	data, err := proto.Marshal(msg)
	if err != nil {
		panic("Error marshaling")
	}
	return data
}

func TestNilConfigEnvelopeAsSignedData(t *testing.T) {
	var ce *common.ConfigUpdateEnvelope
	_, err := protoutil.ConfigUpdateEnvelopeAsSignedData(ce)
	if err == nil {
		t.Fatalf("Should have errored trying to convert a nil signed config item to signed data")
	}
}

func TestConfigEnvelopeAsSignedData(t *testing.T) {
	configBytes := []byte("Foo")
	signatures := [][]byte{[]byte("Signature1"), []byte("Signature2")}
	identities := [][]byte{[]byte("Identity1"), []byte("Identity2")}

	configSignatures := make([]*common.ConfigSignature, len(signatures))
	for i := range configSignatures {
		configSignatures[i] = &common.ConfigSignature{
			SignatureHeader: marshalOrPanic(&common.SignatureHeader{
				Creator: identities[i],
			}),
			Signature: signatures[i],
		}
	}

	ce := &common.ConfigUpdateEnvelope{
		ConfigUpdate: configBytes,
		Signatures:   configSignatures,
	}

	signedData, err := protoutil.ConfigUpdateEnvelopeAsSignedData(ce)
	if err != nil {
		t.Fatalf("Unexpected error: %s", err)
	}

	for i, sigData := range signedData {
		if !bytes.Equal(sigData.Identity, identities[i]) {
			t.Errorf("Expected identity to match at index %d", i)
		}
		if !bytes.Equal(sigData.Data, append(configSignatures[i].SignatureHeader, configBytes...)) {
			t.Errorf("Expected signature over concatenation of config item bytes and signature header")
		}
		if !bytes.Equal(sigData.Signature, signatures[i]) {
			t.Errorf("Expected signature to match at index %d", i)
		}
	}
}

func TestNilEnvelopeAsSignedData(t *testing.T) {
	var env *common.Envelope
	_, err := protoutil.EnvelopeAsSignedData(env)
	if err == nil {
		t.Fatalf("Should have errored trying to convert a nil envelope")
	}
}

func TestEnvelopeAsSignedData(t *testing.T) {
	identity := []byte("Foo")
	sig := []byte("Bar")

	shdrbytes, err := proto.Marshal(&common.SignatureHeader{Creator: identity})
	if err != nil {
		t.Fatalf("%s", err)
	}

	env := &common.Envelope{
		Payload: marshalOrPanic(&common.Payload{
			Header: &common.Header{
				SignatureHeader: shdrbytes,
			},
		}),
		Signature: sig,
	}

	signedData, err := protoutil.EnvelopeAsSignedData(env)
	if err != nil {
		t.Fatalf("Unexpected error converting envelope to SignedData: %s", err)
	}

	if len(signedData) != 1 {
		t.Fatalf("Expected 1 entry of signed data, but got %d", len(signedData))
	}

	if !bytes.Equal(signedData[0].Identity, identity) {
		t.Errorf("Wrong identity bytes")
	}
	if !bytes.Equal(signedData[0].Data, env.Payload) {
		t.Errorf("Wrong data bytes")
	}
	if !bytes.Equal(signedData[0].Signature, sig) {
		t.Errorf("Wrong data bytes")
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <artifactId>apiman-manager-api</artifactId>
    <groupId>io.apiman</groupId>
    <version>2.0.1-SNAPSHOT</version>
  </parent>
  <artifactId>apiman-manager-api-rest-exceptions</artifactId>
  <packaging>bundle</packaging>
  <name>apiman-manager-api-rest-exceptions</name>

  <dependencies>
    <dependency>
      <groupId>io.apiman</groupId>
      <artifactId>apiman-manager-api-beans</artifactId>
    </dependency>
    <dependency>
      <groupId>io.apiman</groupId>
      <artifactId>apiman-common-plugin</artifactId>
    </dependency>

    <!-- Third Party Dependencies -->
    <dependency>
      <groupId>javax.enterprise</groupId>
      <artifactId>cdi-api</artifactId>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.jboss.spec.javax.ws.rs</groupId>
      <artifactId>jboss-jaxrs-api_2.0_spec</artifactId>
      <scope>provided</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.felix</groupId>
        <artifactId>maven-bundle-plugin</artifactId>
        <extensions>true</extensions>
        <configuration>
          <instructions>
            <Export-Package>io.apiman.manager.api.rest.exceptions.*</Export-Package>
            <Import-Package>!org.jboss.errai.common.client.api.annotations,!javax.enterprise.context,!javax.enterprise.inject,!javax.inject,*</Import-Package>
          </instructions>
        </configuration>
      </plugin>
    </plugins>
  </build>

</project>


text:
<?xml version="1.0" encoding="utf-8"?>
<Roots >
  <Roots.PropertyPathNames>
    <RootPropertyPathName Name="Foreground" />
    <RootPropertyPathName Name="Background" />
    <RootPropertyPathName Name="Text" />
    <RootPropertyPathName Name="PlaceholderText" />
    <RootPropertyPathName Name="InputScope" />
  </Roots.PropertyPathNames>
  <Roots.RootTypes>
    <RootType FullName="Windows.UI.Xaml.Controls.UserControl">
      <RootProperty Name="Foreground" />
      <RootProperty Name="Background" />
      <RootProperty Name="DataContext" />
      <RootProperty Name="Style" />
      <RootProperty Name="Content" />
    </RootType>
    <RootType FullName="Microsoft.Xaml.Tools.DirectUI.ProxyTypes.ThemeResourceExtension" />
    <RootType FullName="Windows.UI.Xaml.Data.Binding">
      <RootProperty Name="RelativeSource" />
      <RootProperty Name="Mode" />
      <RootProperty Name="UpdateSourceTrigger" />
    </RootType>
    <RootType FullName="Windows.UI.Xaml.Data.RelativeSource" />
    <RootType FullName="Xamarin.Forms.Platform.WinRT.FormsTextBox" />
    <RootType FullName="Windows.UI.Xaml.Controls.Control">
      <RootProperty Name="Background" />
      <RootProperty Name="Foreground" />
      <RootProperty Name="Template" />
    </RootType>
    <RootType FullName="Windows.UI.Xaml.Setter">
      <RootProperty Name="Property" />
      <RootProperty Name="Value" />
    </RootType>
    <RootType FullName="Windows.UI.Xaml.Controls.Grid">
      <RootProperty Name="Children" />
      <RootProperty Name="Resources" />
      <RootProperty Name="ColumnDefinitions" />
      <RootMethod Name="GetColumn" />
      <RootMethod Name="SetColumn" />
    </RootType>
    <RootType FullName="Windows.UI.Xaml.Controls.PasswordBox">
      <RootProperty Name="Name" />
      <RootProperty Name="Foreground" />
      <RootProperty Name="Background" />
      <RootProperty Name="Opacity" />
      <RootProperty Name="Password" />
      <RootProperty Name="PlaceholderText" />
    </RootType>
    <RootType FullName="Windows.UI.Xaml.Controls.TextBox">
      <RootProperty Name="Name" />
      <RootProperty Name="Foreground" />
      <RootProperty Name="Background" />
      <RootProperty Name="Text" />
      <RootProperty Name="PlaceholderText" />
      <RootProperty Name="InputScope" />
    </RootType>
    <RootType FullName="Windows.UI.Xaml.Controls.ContentControl">
      <RootProperty Name="HorizontalContentAlignment" />
      <RootProperty Name="VerticalContentAlignment" />
      <RootProperty Name="Content" />
    </RootType>
    <RootType FullName="Xamarin.Forms.Platform.WinRT.PageControl" />
    <RootType FullName="Windows.UI.Xaml.Controls.Button">
      <RootProperty Name="Name" />
      <RootProperty Name="Content" />
      <RootProperty Name="BorderThickness" />
      <RootEvent Name="Click" />
    </RootType>
    <RootType FullName="Windows.UI.Xaml.FrameworkElement">
      <RootProperty Name="Margin" />
    </RootType>
    <RootType FullName="Windows.UI.Xaml.Controls.ControlTemplate">
      <RootProperty Name="TargetType" />
      <RootProperty Name="Template" />
    </RootType>
    <RootType FullName="Windows.UI.Xaml.VisualStateManager">
      <RootMethod Name="GetVisualStateGroups" />
    </RootType>
    <RootType FullName="Windows.UI.Xaml.VisualStateGroup">
      <RootProperty Name="States" />
    </RootType>
    <RootType FullName="Windows.UI.Xaml.VisualState">
      <RootProperty Name="Storyboard" />
    </RootType>
    <RootType FullName="Windows.UI.Xaml.Media.Animation.Storyboard">
      <RootProperty Name="Children" />
      <RootMethod Name="GetTargetProperty" />
      <RootMethod Name="SetTargetProperty" />
      <RootMethod Name="GetTargetName" />
      <RootMethod Name="SetTargetName" />
    </RootType>
    <RootType FullName="Windows.UI.Xaml.Media.Animation.DoubleAnimation">
      <RootProperty Name="Duration" />
      <RootProperty Name="To" />
    </RootType>
    <RootType FullName="Windows.UI.Xaml.Media.Animation.ObjectAnimationUsingKeyFrames">
      <RootProperty Name="KeyFrames" />
    </RootType>
    <RootType FullName="Windows.UI.Xaml.Media.Animation.DiscreteObjectKeyFrame">
      <RootProperty Name="KeyTime" />
      <RootProperty Name="Value" />
    </RootType>
    <RootType FullName="Windows.UI.Xaml.Controls.Border">
      <RootProperty Name="BorderBrush" />
      <RootProperty Name="BorderThickness" />
      <RootProperty Name="Background" />
      <RootProperty Name="Margin" />
      <RootProperty Name="Child" />
    </RootType>
    <RootType FullName="Windows.UI.Xaml.Shapes.Rectangle">
      <RootProperty Name="IsHitTestVisible" />
      <RootProperty Name="Opacity" />
      <RootProperty Name="StrokeDashOffset" />
      <RootProperty Name="StrokeEndLineCap" />
      <RootProperty Name="Stroke" />
      <RootProperty Name="StrokeDashArray" />
    </RootType>
    <RootType FullName="Microsoft.Xaml.Tools.DirectUI.ProxyTypes.TemplateBindingExtension" />
    <RootType FullName="Windows.UI.Xaml.Controls.ContentPresenter">
      <RootProperty Name="ContentTemplate" />
      <RootProperty Name="ContentTransitions" />
      <RootProperty Name="Content" />
      <RootProperty Name="HorizontalAlignment" />
      <RootProperty Name="Margin" />
      <RootProperty Name="VerticalAlignment" />
    </RootType>
    <RootType FullName="Windows.UI.Xaml.Automation.AutomationProperties">
      <RootMethod Name="GetAccessibilityView" />
      <RootMethod Name="SetAccessibilityView" />
    </RootType>
    <RootType FullName="Windows.UI.Xaml.Controls.ColumnDefinition">
      <RootProperty Name="Width" />
    </RootType>
    <RootType FullName="Xamarin.Forms.Platform.WinRT.StepperControl" />
  </Roots.RootTypes>
</Roots>


text:
<?php

namespace Google\Service\Apigee;

class GoogleCloudApigeeV1Reference extends \Google\Model
{
  /**
   * @var string
   */
  public $description;
  /**
   * @var string
   */
  public $name;
  /**
   * @var string
   */
  public $refers;
  /**
   * @var string
   */
  public $resourceType;

  /**
   * @param string
   */
  public function setDescription($description)
  {
    $this->description = $description;
  }
  /**
   * @return string
   */
  public function getDescription()
  {
    return $this->description;
  }
  /**
   * @param string
   */
  public function setName($name)
  {
    $this->name = $name;
  }
  /**
   * @return string
   */
  public function getName()
  {
    return $this->name;
  }
  /**
   * @param string
   */
  public function setRefers($refers)
  {
    $this->refers = $refers;
  }
  /**
   * @return string
   */
  public function getRefers()
  {
    return $this->refers;
  }
  /**
   * @param string
   */
  public function setResourceType($resourceType)
  {
    $this->resourceType = $resourceType;
  }
  /**
   * @return string
   */
  public function getResourceType()
  {
    return $this->resourceType;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(GoogleCloudApigeeV1Reference::class, 'Google_Service_Apigee_GoogleCloudApigeeV1Reference');


text:
//
//  LFAssetManager+Authorization.h
//  LFImagePickerController
//
//  Created by LamTsanFeng on 2017/2/13.
//  Copyright © 2017年 LamTsanFeng. All rights reserved.
//

#import "LFAssetManager.h"

typedef NS_ENUM(NSInteger, LFPhotoAuthorizationStatus) {
    /** 未询问过的 */
    LFPhotoAuthorizationStatusNotDetermined = 0,
    /** 被限制的 */
    LFPhotoAuthorizationStatusRestricted,
    /** 拒绝的 */
    LFPhotoAuthorizationStatusDenied,
    /** 允许访问所有 */
    LFPhotoAuthorizationStatusAuthorized,
    /** 允许访问部分 */
    LFPhotoAuthorizationStatusLimited
};

@interface LFAssetManager (Authorization)

/// Return YES if Authorized 返回YES如果得到了授权
- (BOOL)authorizationStatusAuthorized API_DEPRECATED_WITH_REPLACEMENT("-lf_authorizationStatusAndRequestAuthorization:", ios(8, API_TO_BE_DEPRECATED));
- (NSInteger)authorizationStatus API_DEPRECATED_WITH_REPLACEMENT("-lf_authorizationStatus:", ios(8, API_TO_BE_DEPRECATED));

- (LFPhotoAuthorizationStatus)lf_authorizationStatusAndRequestAuthorization:(void(^)(LFPhotoAuthorizationStatus status))handler;
- (LFPhotoAuthorizationStatus)lf_authorizationStatus;

@end


text:
import * as ldModule from './light_dom';
export declare class Content {
    contentStartElement: any;
    select: string;
    private _strategy;
    constructor(contentStartElement: any, select: string);
    init(destinationLightDom: ldModule.LightDom): void;
    nodes(): List<any>;
    insert(nodes: List<any>): void;
}


text:
#include <stdio.h>
#include <ruby.h>

/** Factory to create a new StatementExecutor */
VALUE rdo_postgres_statement_executor_new(VALUE driver, VALUE cmd, VALUE name);

/** Initializer for the statements framework */
void Init_rdo_postgres_statements(void);


text:
ipaddress = node['squid']['ipaddress']
listen_interface = node['squid']['listen_interface']
version = node['squid']['version']
netmask = node['network']['interfaces'][listen_interface]['addresses'][ipaddress]['netmask']

# squid/libraries/default.rb
acls = squid_load_acls(node['squid']['acls_databag_name'])
host_acl = squid_load_host_acl(node['squid']['hosts_databag_name'])
url_acl = squid_load_url_acl(node['squid']['urls_databag_name'])

# Log variables to Chef::Log::debug()
Chef::Log.debug("Squid listen_interface: #{listen_interface}")
Chef::Log.debug("Squid ipaddress: #{ipaddress}")
Chef::Log.debug("Squid netmask: #{netmask}")
Chef::Log.debug("Squid version: #{version}")
Chef::Log.debug("Squid host_acls: #{host_acl}")
Chef::Log.debug("Squid url_acls: #{url_acl}")
Chef::Log.debug("Squid acls: #{acls}")

# packages
package node['squid']['package']

# rhel_family sysconfig
template '/etc/sysconfig/squid' do
  source 'redhat/sysconfig/squid.erb'
  notifies :restart, "service[#{node['squid']['service_name']}]", :delayed
  mode 00644
  only_if { platform_family? 'rhel', 'fedora' }
end

# squid config dir
directory node['squid']['config_dir'] do
  action :create
  recursive true
  owner 'root'
  mode 00755
end

# squid mime config
cookbook_file "#{node['squid']['config_dir']}/mime.conf" do
  source 'mime.conf'
  mode 00644
end

# TODO:  COOK-3041 (manage this file appropriately)
file "#{node['squid']['config_dir']}/msntauth.conf" do
  action :delete
end

# squid config
template node['squid']['config_file'] do
  source 'squid.conf.erb'
  notifies :reload, "service[#{node['squid']['service_name']}]"
  mode 00644
  variables(
    :host_acl => host_acl,
    :url_acl => url_acl,
    :acls => acls,
    :directives => node['squid']['directives']
    )
end

# services
service node['squid']['service_name'] do
  supports :restart => true, :status => true, :reload => true
  provider Chef::Provider::Service::Upstart if platform?('ubuntu')
  action [:enable, :start]
end


text:
const webpack = require('webpack');
const conf = require('./gulp.conf');
const path = require('path');
var bourbon = require('bourbon').includePaths;

const HtmlWebpackPlugin = require('html-webpack-plugin');
const FailPlugin = require('webpack-fail-plugin');
const autoprefixer = require('autoprefixer');

module.exports = {
  module: {
    loaders: [
      {
        test: /.json$/,
        loaders: [
          'json-loader'
        ]
      },
      {
        test: /.js$/,
        exclude: /node_modules/,
        loader: 'eslint-loader',
        enforce: 'pre'
      },
      {
        test: /\.(css)$/,
        loaders: [
          'style-loader',
          'css-loader',
          'postcss-loader'
        ]
      },
      {
        test: /\.(sass|scss)$/,
        loaders: [
          'style-loader',
          'css-loader',
          'sass-loader?includePaths[]=' + bourbon
        ]
      },
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loaders: [
          'ng-annotate-loader',
          'babel-loader'
        ]
      },
      {
        test: /.html$/,
        loaders: [
          'html-loader'
        ]
      }
    ]
  },
  plugins: [
    new webpack.optimize.OccurrenceOrderPlugin(),
      new webpack.NoEmitOnErrorsPlugin(),
    FailPlugin,
    new HtmlWebpackPlugin({
      template: conf.path.src('index.html')
    }),
    new webpack.LoaderOptionsPlugin({
      options: {
        postcss: () => [autoprefixer]
      },
      debug: true
    })
  ],
  devtool: 'source-map',
  output: {
    path: path.join(process.cwd(), conf.paths.tmp),
    filename: 'index.js'
  },
  entry: `./${conf.path.src('index')}`
};


text:
mv ~/Library/Developer/Xcode/UserData/CodeSnippets ~/Library/Developer/Xcode/UserData/CodeSnippets.backup

SRC_HOME=`pwd`
ln -s ${SRC_HOME} ~/Library/Developer/Xcode/UserData/CodeSnippets
echo "setup code snippets done!"


text:
package com.providers;

import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.ColumnViewer;
import org.eclipse.jface.viewers.EditingSupport;

public class EditingSupportCLS extends EditingSupport {

	public EditingSupportCLS(ColumnViewer viewer) {
		super(viewer);
		// TODO Auto-generated constructor stub
	}

	@Override
	protected CellEditor getCellEditor(Object element) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected boolean canEdit(Object element) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	protected Object getValue(Object element) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected void setValue(Object element, Object value) {
		// TODO Auto-generated method stub

	}

}


text:
package org.apache.ignite.ml.math;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;

/**
 * Test suite for local and distributed math tests.
 */
@RunWith(Suite.class)
@Suite.SuiteClasses({
    MathImplLocalTestSuite.class,
    TracerTest.class,
    BlasTest.class
})
public class MathImplMainTestSuite {
    // No-op.
}


text:
package nam.model.operation;

import java.io.Serializable;
import java.util.List;

import javax.enterprise.context.SessionScoped;
import javax.enterprise.event.Observes;
import javax.inject.Inject;
import javax.inject.Named;

import org.aries.runtime.BeanContext;
import org.aries.ui.Display;
import org.aries.ui.event.Add;
import org.aries.ui.event.Remove;
import org.aries.util.Validator;

import nam.model.Operation;
import nam.model.Project;
import nam.model.util.OperationUtil;
import nam.model.util.ProjectUtil;
import nam.ui.design.AbstractNamRecordManager;
import nam.ui.design.SelectionContext;
import nam.ui.design.WorkspaceEventManager;

@SessionScoped
@Named("operationInfoManager")
public class OperationInfoManager extends AbstractNamRecordManager<Operation> implements Serializable {

	@Inject
	private OperationWizard operationWizard;

	@Inject
	private OperationDataManager operationDataManager;

	@Inject
	private OperationPageManager operationPageManager;

	@Inject
	private OperationEventManager operationEventManager;

	@Inject
	private WorkspaceEventManager workspaceEventManager;

	@Inject
	private OperationHelper operationHelper;

	@Inject
	private SelectionContext selectionContext;

	public OperationInfoManager() {
		setInstanceName("operation");
	}

	public Operation getOperation() {
		return getRecord();
	}

	public Operation getSelectedOperation() {
		return selectionContext.getSelection("operation");
	}

	@Override
	public Class<Operation> getRecordClass() {
		return Operation.class;
	}

	@Override
	public boolean isEmpty(Operation operation) {
		return operationHelper.isEmpty(operation);
	}

	@Override
	public String toString(Operation operation) {
		return operationHelper.toString(operation);
	}

	@Override
	public void initialize() {
		Operation operation = selectionContext.getSelection("operation");
		if (operation != null)
			initialize(operation);
	}

	protected void initialize(Operation operation) {
		operationWizard.initialize(operation);
		setContext("operation", operation);
	}

	@Override
	public String newRecord() {
		return newOperation();
	}

	public String newOperation() {
		try {
			Operation operation = create();
			selectionContext.resetOrigin();
			selectionContext.setSelection("operation",  operation);
			String url = operationPageManager.initializeOperationCreationPage(operation);
			operationPageManager.pushContext(operationWizard);
			initialize(operation);
			return url;
		} catch (Exception e) {
			handleException(e);
			return null;
		}
	}

	@Override
	public Operation create() {
		Operation operation = OperationUtil.create();
		return operation;
	}

	@Override
	public Operation clone(Operation operation) {
		operation = OperationUtil.clone(operation);
		return operation;
	}

	@Override
	public String viewRecord() {
		return viewOperation();
	}

	public String viewOperation() {
		Operation operation = selectionContext.getSelection("operation");
		String url = viewOperation(operation);
		return url;
	}

	public String viewOperation(Operation operation) {
		try {
			String url = operationPageManager.initializeOperationSummaryView(operation);
			operationPageManager.pushContext(operationWizard);
			initialize(operation);
			return url;
		} catch (Exception e) {
			handleException(e);
			return null;
		}
	}

	@Override
	public String editRecord() {
		return editOperation();
	}

	public String editOperation() {
		Operation operation = selectionContext.getSelection("operation");
		String url = editOperation(operation);
		return url;
	}

	public String editOperation(Operation operation) {
		try {
			//operation = clone(operation);
			selectionContext.resetOrigin();
			selectionContext.setSelection("operation",  operation);
			String url = operationPageManager.initializeOperationUpdatePage(operation);
			operationPageManager.pushContext(operationWizard);
			initialize(operation);
			return url;
		} catch (Exception e) {
			handleException(e);
			return null;
		}
	}

	public void saveOperation() {
		Operation operation = getOperation();
		if (validateOperation(operation)) {
			saveOperation(operation);
		}
	}

	public void persistOperation(Operation operation) {
		saveOperation(operation);
	}

	public void saveOperation(Operation operation) {
		try {
			saveOperationToSystem(operation);
			operationEventManager.fireAddedEvent(operation);
		} catch (Exception e) {
			handleException(e);
		}
	}

	protected void saveOperationToSystem(Operation operation) {
		operationDataManager.saveOperation(operation);
	}

	public void handleSaveOperation(@Observes @Add Operation operation) {
		saveOperation(operation);
	}

	public void enrichOperation(Operation operation) {
		//nothing for now
	}

	@Override
	public boolean validate(Operation operation) {
		return validateOperation(operation);
	}

	public boolean validateOperation(Operation operation) {
		Validator validator = getValidator();
		boolean isValid = OperationUtil.validate(operation);
		Display display = getFromSession("display");
		display.setModule("operationInfo");
		display.addErrors(validator.getMessages());
		//FacesContext.getCurrentInstance().isValidationFailed()
		setValidated(isValid);
		return isValid;
	}

	public void promptRemoveOperation() {
		display = getFromSession("display");
		display.setModule("operationInfo");
		Operation operation = selectionContext.getSelection("operation");
		if (operation == null) {
			display.error("Operation record must be selected.");
		}
	}

	public String handleRemoveOperation(@Observes @Remove Operation operation) {
		display = getFromSession("display");
		display.setModule("operationInfo");
		try {
			display.info("Removing Operation "+OperationUtil.getLabel(operation)+" from the system.");
			removeOperationFromSystem(operation);
			selectionContext.clearSelection("operation");
			operationEventManager.fireClearSelectionEvent();
			operationEventManager.fireRemovedEvent(operation);
			workspaceEventManager.fireRefreshEvent();
			return null;
		} catch (Exception e) {
			handleException(e);
			return null;
		}
	}

	protected void removeOperationFromSystem(Operation operation) {
		if (operationDataManager.removeOperation(operation))
			setRecord(null);
	}

	public void cancelOperation() {
		BeanContext.removeFromSession("operation");
		operationPageManager.removeContext(operationWizard);
	}

}


text:
layout: single
title: 'PSQL: Renaming A Table'
excerpt: Using alter table
date: 2017-02-02
modified: 2022-11-11
categories: til
tags:
    - psql
    - sql
    - til
---

Using the `alter table` command in PostgreSQL, you can rename an existing
table. This command will also update any references to the table such as via
foreign key constraints. Just run a command like the following:

```sql
alter table ingredient_types rename to item_types;
```

Note that this may result in breaking a number of conventions. Foreign keys,
sequences, and constraints with names eponymous to the original table will
no longer follow convention despite the references being updated. These can
be renamed as well if desired.

See
[`renaming_table.sql`](https://github.com/jbranchaud/postgresing/blob/master/renaming/rename_table.sql)
for a full example.

See the [`alter table`
docs](http://www.postgresql.org/docs/current/static/sql-altertable.html) for
more details.

Via [jbranchaud/til](https://github.com/jbranchaud/til).


text:
namespace ngraph
{
    namespace runtime
    {
        namespace reference
        {
            template <typename T>
            void tile(const T* arg, T* out, const Shape& in_shape, const Shape& out_shape)
            {
                Shape in_shape_expanded(in_shape);
                in_shape_expanded.insert(
                    in_shape_expanded.begin(), out_shape.size() - in_shape.size(), 1);
                CoordinateTransform input_transform(in_shape_expanded);
                CoordinateTransform output_transform(out_shape);

                for (const Coordinate& output_coord : output_transform)
                {
                    std::vector<size_t> coord;
                    for (auto i = 0; i < output_coord.size(); i++)
                    {
                        auto val = output_coord[i] % in_shape_expanded[i];
                        coord.push_back(val);
                    }
                    Coordinate input_coord(coord);
                    out[output_transform.index(output_coord)] =
                        arg[input_transform.index(input_coord)];
                }
            }
        }
    }
}


text:
package es.deusto.weblab.client.ui.widgets;

import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

public abstract class WlWidgetWithPressable extends VerticalPanel implements IWlWidget, IWlPressable{

	private Image currentImage;
	private Image oldImage;
	private final VerticalPanel visiblePanel;
	private final WlActionListenerContainer actionListenerContainer;

	private final Label title = new Label("");

	public WlWidgetWithPressable(){
		this.visiblePanel = new VerticalPanel();
		this.visiblePanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		this.visiblePanel.setWidth("100%");
		this.actionListenerContainer = new WlActionListenerContainer();

		this.setWidth("100%");
		this.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		this.visiblePanel.add(this.title);
		this.setStyleName("wl-pressable");

		this.add(this.visiblePanel);
	}

	/**
	 * Retrieves the title of the switch. The title is empty by default
	 * and may be set through the setTitle method.
	 */
	@Override
	public String getTitle() {
		return this.title.getText();
	}

	/**
	 * If set, shows a label containing the specified text. The title
	 * may be used to identify the widget.
	 */
	@Override
	public void setTitle(String title) {
		this.title.setVisible(true);
		this.title.setText(title);
	}

	public void addActionListener(IWlActionListener listener){
		this.actionListenerContainer.addActionListener(listener);
	}

	public void removeActionListener(IWlActionListener listener){
		this.actionListenerContainer.removeActionListener(listener);
	}

	protected void fireActionListeners(){
		this.actionListenerContainer.fireActionListeners(this);
	}

	@Override
	public void press(){
		this.changeState(this.currentImage,this.oldImage);
		this.toggleCurrent();
	}

	protected void changeState(Image original, Image newOne){
		for(int i = 0; i < this.visiblePanel.getWidgetCount(); ++i)
			if(this.visiblePanel.getWidget(i) == original){
				this.visiblePanel.remove(i);
				this.visiblePanel.add(newOne);
				break;
			}
	}

	private void toggleCurrent() {
		final Image tmp = this.currentImage;
		this.currentImage = this.oldImage;
		this.oldImage = tmp;
	}

	@Override
	public Widget getWidget(){
		return this;
	}

	protected Image getCurrentImage() {
		return this.currentImage;
	}

	protected void setCurrentImage(Image currentImage) {
		this.currentImage = currentImage;
	}

	protected void setCurrentVisibleImage(Image currentImage){
		this.currentImage = currentImage;
		for(int i = 0; i < this.visiblePanel.getWidgetCount(); ++i)
			this.visiblePanel.remove(i);
		this.visiblePanel.add(this.title);
		this.visiblePanel.add(this.currentImage);
	}

	protected Image getOldImage() {
		return this.oldImage;
	}

	protected void setOldImage(Image oldImage) {
		this.oldImage = oldImage;
	}
}


text:
require 'ward/dsl/validation_block'
require 'ward/dsl/validation_builder'

module Ward
  # Classes which provide the Ward validator DSL.
  module DSL; end
end # Ward


text:
SETUPDIR=$(dirname $(readlink -f $0))

# setup dhcp sever on ethernet port in order to connect the hue bridge
sudo DEBIAN_FRONTEND=noninteractive apt-get -y install isc-dhcp-server
DHCPCONF=/etc/dhcp/dhcpd.conf
sudo mv $DHCPCONF $DHCPCONF.orig
sudo cp -f $SETUPDIR/dhcp/dhcpd.conf $DHCPCONF
sudo cp -f $SETUPDIR/dhcp/isc-dhcp-server /etc/default
sudo chown root $DHCPCONF
sudo chmod u=rw,g=r,o=r $DHCPCONF

# setup eth0 as static IP
ETH0=/etc/network/interfaces.d/eth0
sudo cp -f $SETUPDIR/network/interfaces.d/eth0 $ETH0
sudo chown root $ETH0
sudo chmod u=rw,g=r,o=r $ETH0

# start dhcp
sudo service isc-dhcp-server restart

# phue
sudo pip3 install phue


text:
#include <memory>

#include "llvm/ADT/SmallVector.h"
#include "mlir/Dialect/Func/IR/FuncOps.h"  // from @llvm-project
#include "mlir/IR/Builders.h"  // from @llvm-project
#include "mlir/IR/BuiltinOps.h"  // from @llvm-project
#include "mlir/IR/Value.h"  // from @llvm-project
#include "mlir/Pass/Pass.h"  // from @llvm-project
#include "mlir/Pass/PassRegistry.h"  // from @llvm-project
#include "tensorflow/compiler/mlir/tensorflow/ir/tf_device.h"
#include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h"
#include "tensorflow/compiler/mlir/tensorflow/transforms/passes.h"
#include "tensorflow/compiler/mlir/tensorflow/utils/tpu_rewrite_device_util.h"

namespace mlir {
namespace TFTPU {
namespace {

#define GEN_PASS_DEF_TPUCOLOCATECOMPOSITERESOURCEOPSPASS
#include "tensorflow/compiler/mlir/tensorflow/transforms/tf_passes.h.inc"

// Pass that co-locates resource ops that use composite device resources
// (packed tensors) with the underlying physical TPU device.
struct TPUColocateCompositeResourceOps
    : public impl::TPUColocateCompositeResourceOpsPassBase<
          TPUColocateCompositeResourceOps> {
  void runOnOperation() override;
};

// Wraps single op in `tf_device.launch` for explicit device assignment.
void WrapOpInLaunch(OpBuilder* builder, Location loc, Operation* op,
                    llvm::StringRef device) {
  builder->setInsertionPoint(op);
  auto launch = builder->create<tf_device::LaunchOp>(
      loc, builder->getStringAttr(device), op->getResultTypes());
  launch.getBody().push_back(new Block);
  op->replaceAllUsesWith(launch);

  builder->setInsertionPointToEnd(&launch.GetBody());
  builder->create<tf_device::ReturnOp>(loc, op->getResults());

  // Move op inside cluster.
  op->moveBefore(launch.GetBody().getTerminator());
}

llvm::SmallVector<Operation*, 4> GetResourceOpsUsingCompositeArgsInReplicate(
    tf_device::ReplicateOp replicate) {
  llvm::SmallVector<Operation*, 4> resource_users;
  const auto add_resource_op_to_list = [&resource_users](Operation* op) {
    if (!llvm::isa<TF::AssignVariableOp, TF::ReadVariableOp>(op)) return;

    resource_users.emplace_back(op);
  };

  llvm::SmallVector<Operation*, 4> resource_users_to_visit;
  for (auto composite_arguments : replicate.GetPackedBlockArguments()) {
    for (auto resource_user : composite_arguments.getUsers())
      resource_users_to_visit.emplace_back(resource_user);
  }

  while (!resource_users_to_visit.empty()) {
    llvm::SmallVector<Operation*, 4> new_resource_users;

    for (auto resource_user : resource_users_to_visit) {
      add_resource_op_to_list(resource_user);

      // Account for pass-through identity ops.
      if (auto pass_through_identity =
              llvm::dyn_cast<TF::IdentityOp>(resource_user)) {
        for (auto identity_user :
             pass_through_identity.getOutput().getUsers()) {
          new_resource_users.emplace_back(identity_user);
        }
      }
    }
    resource_users_to_visit.swap(new_resource_users);
  }

  return resource_users;
}

void ColocateCompositeResourceOpsInReplicate(
    tf_device::ReplicateOp replicate_op, OpBuilder* builder) {
  auto devices = replicate_op.getDevices();
  if (!devices) return;
  if (!devices.getValue().get(tensorflow::GetDeviceAliasForLogicalCore(0)))
    return;

  const auto composite_resource_users =
      GetResourceOpsUsingCompositeArgsInReplicate(replicate_op);
  for (auto resource_user : composite_resource_users) {
    WrapOpInLaunch(builder, resource_user->getLoc(), resource_user,
                   tensorflow::GetDeviceAliasForLogicalCore(0));
  }
}

void TPUColocateCompositeResourceOps::runOnOperation() {
  // Find all the executes first, since we will mutate the nodes around each
  // execute in the same tf_device.replicate op.
  llvm::SmallVector<tf_device::LaunchOp, 8> execute_launches;
  getOperation().walk([&](tf_device::LaunchOp op) {
    if (op.WrapsSingleOp() &&
        llvm::isa<TF::TPUExecuteOp, TF::TPUExecuteAndUpdateVariablesOp>(
            op.GetBody().front()))
      execute_launches.push_back(op);
  });

  OpBuilder builder(&getContext());
  for (auto execute_launch : execute_launches) {
    auto replicate = execute_launch->getParentOfType<tf_device::ReplicateOp>();
    if (!replicate) continue;

    ColocateCompositeResourceOpsInReplicate(replicate, &builder);
  }
}

}  // namespace

std::unique_ptr<OperationPass<func::FuncOp>>
CreateTPUColocateCompositeResourceOps() {
  return std::make_unique<TPUColocateCompositeResourceOps>();
}

}  // namespace TFTPU
}  // namespace mlir


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

package io.warp10.continuum;

import io.warp10.continuum.store.thrift.data.DirectoryFindRequest;
import io.warp10.continuum.store.thrift.data.DirectoryStatsRequest;
import io.warp10.crypto.SipHashInline;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

import org.apache.commons.io.output.ByteArrayOutputStream;

import com.google.common.base.Charsets;
import com.google.common.primitives.Longs;

public class DirectoryUtil {
  /**
   * Compute the hash of a DirectoryFindRequest for the provided SipHash key
   *
   * @param k0 first half of SipHash key
   * @param k1 second half of SipHash key
   * @param request DirectoryFindRequest to hash
   * @return
   */
  public static long computeHash(long k0, long k1, DirectoryFindRequest request) {
    return computeHash(k0, k1, request.getTimestamp(), request.getClassSelector(), request.getLabelsSelectors());
  }

  public static long computeHash(long k0, long k1, DirectoryStatsRequest request) {
    return computeHash(k0, k1, request.getTimestamp(), request.getClassSelector(), request.getLabelsSelectors());
  }

  private static long computeHash(long k0, long k1, long timestamp, List<String> classSelectors, List<Map<String,String>> labelsSelectors) {
    //
    // Create a ByteArrayOutputStream into which the content will be dumped
    //

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    // Add timestamp

    try {
      baos.write(Longs.toByteArray(timestamp));

      if (null != classSelectors) {
        for (String classSelector: classSelectors) {
          baos.write(classSelector.getBytes(Charsets.UTF_8));
        }
      }

      if (null != labelsSelectors) {
        for (Map<String, String> map: labelsSelectors) {
          TreeMap<String,String> tm = new TreeMap<String, String>();
          tm.putAll(map);
          for (Entry<String,String> entry: tm.entrySet()) {
            baos.write(entry.getKey().getBytes(Charsets.UTF_8));
            baos.write(entry.getValue().getBytes(Charsets.UTF_8));
          }
        }
      }
    } catch (IOException ioe) {
      return 0L;
    }

    // Compute hash

    byte[] data = baos.toByteArray();

    long hash = SipHashInline.hash24(k0, k1, data, 0, data.length);

    return hash;
  }
}


text:
const assert = require('assert')
const _ = require('lodash')

module.exports = class ManifestPlugin {
  constructor ({ sha, timestamp }) {
    assert(sha, 'ManifestPlugin: missing SHA')
    assert(timestamp, 'ManifestPlugin: missing timestamp')
    this.data = { sha, timestamp }
  }

  apply (compiler) {
    const { data } = this

    // Add manifest.json to output
    if (compiler.hooks) {
      compiler.hooks.emit.tapAsync('ManifestPlugin', pluginEmit)
    } else {
      compiler.plugin('emit', pluginEmit)
    }

    function pluginEmit (compilation, callback) {
      const stats = compilation.getStats().toJson({
        assets: true,
        children: false,
        chunks: false,
        errorDetails: false,
        errors: false,
        hash: true,
        modules: false,
        publicPath: true,
        source: false,
        timings: false,
        version: false,
        warnings: false
      })
      const manifest = _.pick(stats, [
        'assets',
        'assetsByChunkName',
        'hash',
        'publicPath'
      ])
      Object.assign(manifest, data)
      const manifestSource = JSON.stringify(manifest)
      compilation.assets['manifest.json'] = {
        size: () => manifestSource.length,
        source: () => manifestSource
      }

      callback()
    }
  }
}