text:
package org.lnu.is.converter.order;

import static org.junit.Assert.assertEquals;

import java.util.Date;

import org.junit.Test;
import org.lnu.is.domain.asset.Asset;
import org.lnu.is.domain.department.Department;
import org.lnu.is.domain.employee.Employee;
import org.lnu.is.domain.optype.OperationType;
import org.lnu.is.domain.order.Order;
import org.lnu.is.domain.order.type.OrderType;
import org.lnu.is.domain.partner.Partner;
import org.lnu.is.domain.reason.Reason;
import org.lnu.is.resource.order.OrderResource;

public class OrderResourceConverterTest {

	private OrderResourceConverter unit = new OrderResourceConverter();

	@Test
	public void testConvert() throws Exception {
		// Given
		Long orderTypeId = 1L;
		OrderType orderType = new OrderType();
		orderType.setId(orderTypeId);

		Long employeeId = 2L;
		Employee employee = new Employee();
		employee.setId(employeeId);

		Long assetId = 3L;
		Asset asset = new Asset();
		asset.setId(assetId);

		Long partnerId = 4L;
		Partner partner = new Partner();
		partner.setId(partnerId);

		Long operationTypeId = 5L;
		OperationType opType = new OperationType();
		opType.setId(operationTypeId);

		Long departmentId = 6L;
		Department department = new Department();
		department.setId(departmentId);

		Long reasonId = 7L;
		Reason reason = new Reason();
		reason.setId(reasonId);

		Long parentId = 8L;
		Order parent = new Order();
		parent.setId(parentId);

		String reasonText = "reasonText";
		String docSeries = "docSeries";
		String docNum = "docnum";
		Date docDate = new Date();
		String docIssued = "docIssued";
		Date evDate = new Date();

		Order expected = new Order();
		expected.setOrderType(orderType);
		expected.setEmployee(employee);
		expected.setAsset(asset);
		expected.setPartner(partner);
		expected.setOpType(opType);
		expected.setDepartment(department);
		expected.setReason(reason);
		expected.setParent(parent);
		expected.setReasonText(reasonText);
		expected.setDocSeries(docSeries);
		expected.setDocNum(docNum);
		expected.setDocDate(docDate);
		expected.setDocIssued(docIssued);
		expected.setEvDate(evDate);

		OrderResource source = new OrderResource();
		source.setOrderTypeId(orderTypeId);
		source.setEmployeeId(employeeId);
		source.setAssetId(assetId);
		source.setPartnerId(partnerId);
		source.setOperationTypeId(operationTypeId);
		source.setDepartmentId(departmentId);
		source.setReasonId(reasonId);
		source.setParentId(parentId);
		source.setReasonText(reasonText);
		source.setDocSeries(docSeries);
		source.setDocNum(docNum);
		source.setDocDate(docDate);
		source.setDocIssued(docIssued);
		source.setEvDate(evDate);

		// When
		Order actual = unit.convert(source);

		// Then
		assertEquals(expected, actual);
	}

	@Test
	public void testConvertWithNoRelations() throws Exception {
		// Given
		String reasonText = "reasonText";
		String docSeries = "docSeries";
		String docNum = "docnum";
		Date docDate = new Date();
		String docIssued = "docIssued";
		Date evDate = new Date();

		Order expected = new Order();
		expected.setReasonText(reasonText);
		expected.setDocSeries(docSeries);
		expected.setDocNum(docNum);
		expected.setDocDate(docDate);
		expected.setDocIssued(docIssued);
		expected.setEvDate(evDate);

		OrderResource source = new OrderResource();
		source.setReasonText(reasonText);
		source.setDocSeries(docSeries);
		source.setDocNum(docNum);
		source.setDocDate(docDate);
		source.setDocIssued(docIssued);
		source.setEvDate(evDate);

		// When
		Order actual = unit.convert(source);

		// Then
		assertEquals(expected, actual);
	}
}


text:
// Copyright 2017 DAIMTO ([Linda Lawton](https://twitter.com/LindaLawtonDK)) :  [www.daimto.com](http://www.daimto.com/)
//
// 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.
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by DAIMTO-Google-apis-Sample-generator 1.0.0
//     Template File Name:  methodTemplate.tt
//     Build date: 2017-10-08
//     C# generater version: 1.0.0
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
// About
//
// Unoffical sample for the Drive v2 API for C#.
// This sample is designed to be used with the Google .Net client library. (https://github.com/google/google-api-dotnet-client)
//
// API Description: Manages files in Drive including uploading, downloading, searching, detecting changes, and updating sharing permissions.
// API Documentation Link https://developers.google.com/drive/
//
// Discovery Doc  https://www.googleapis.com/discovery/v1/apis/Drive/v2/rest
//
//------------------------------------------------------------------------------
// Installation
//
// This sample code uses the Google .Net client library (https://github.com/google/google-api-dotnet-client)
//
// NuGet package:
//
// Location: https://www.nuget.org/packages/Google.Apis.Drive.v2/
// Install Command: PM>  Install-Package Google.Apis.Drive.v2
//
//------------------------------------------------------------------------------
using Google.Apis.Drive.v2;
using Google.Apis.Drive.v2.Data;
using System;

namespace GoogleSamplecSharpSample.Drivev2.Methods
{

    public static class ChangesSample
    {

        public class ChangesGetOptionalParms
        {
            /// Whether the requesting application supports Team Drives.
            public bool? SupportsTeamDrives { get; set; }
            /// The Team Drive from which the change will be returned.
            public string TeamDriveId { get; set; }

        }

        /// <summary>
        /// Gets a specific change.
        /// Documentation https://developers.google.com/drive/v2/reference/changes/get
        /// Generation Note: This does not always build corectly.  Google needs to standardise things I need to figuer out which ones are wrong.
        /// </summary>
        /// <param name="service">Authenticated Drive service.</param>
        /// <param name="changeId">The ID of the change.</param>
        /// <param name="optional">Optional paramaters.</param>
        /// <returns>ChangeResponse</returns>
        public static Change Get(DriveService service, string changeId, ChangesGetOptionalParms optional = null)
        {
            try
            {
                // Initial validation.
                if (service == null)
                    throw new ArgumentNullException("service");
                if (changeId == null)
                    throw new ArgumentNullException(changeId);

                // Building the initial request.
                var request = service.Changes.Get(changeId);

                // Applying optional parameters to the request.
                request = (ChangesResource.GetRequest)SampleHelpers.ApplyOptionalParms(request, optional);

                // Requesting data.
                return request.Execute();
            }
            catch (Exception ex)
            {
                throw new Exception("Request Changes.Get failed.", ex);
            }
        }
        public class ChangesGetStartPageTokenOptionalParms
        {
            /// Whether the requesting application supports Team Drives.
            public bool? SupportsTeamDrives { get; set; }
            /// The ID of the Team Drive for which the starting pageToken for listing future changes from that Team Drive will be returned.
            public string TeamDriveId { get; set; }

        }

        /// <summary>
        /// Gets the starting pageToken for listing future changes.
        /// Documentation https://developers.google.com/drive/v2/reference/changes/getStartPageToken
        /// Generation Note: This does not always build corectly.  Google needs to standardise things I need to figuer out which ones are wrong.
        /// </summary>
        /// <param name="service">Authenticated Drive service.</param>
        /// <param name="optional">Optional paramaters.</param>
        /// <returns>StartPageTokenResponse</returns>
        public static StartPageToken GetStartPageToken(DriveService service, ChangesGetStartPageTokenOptionalParms optional = null)
        {
            try
            {
                // Initial validation.
                if (service == null)
                    throw new ArgumentNullException("service");

                // Building the initial request.
                var request = service.Changes.GetStartPageToken();

                // Applying optional parameters to the request.
                request = (ChangesResource.GetStartPageTokenRequest)SampleHelpers.ApplyOptionalParms(request, optional);

                // Requesting data.
                return request.Execute();
            }
            catch (Exception ex)
            {
                throw new Exception("Request Changes.GetStartPageToken failed.", ex);
            }
        }
        public class ChangesListOptionalParms
        {
            /// Whether changes should include the file resource if the file is still accessible by the user at the time of the request, even when a file was removed from the list of changes and there will be no further change entries for this file.
            public bool? IncludeCorpusRemovals { get; set; }
            /// Whether to include changes indicating that items have been removed from the list of changes, for example by deletion or loss of access.
            public bool? IncludeDeleted { get; set; }
            /// Whether to include public files the user has opened and shared files. When set to false, the list only includes owned files plus any shared or public files the user has explicitly added to a folder they own.
            public bool? IncludeSubscribed { get; set; }
            /// Whether Team Drive files or changes should be included in results.
            public bool? IncludeTeamDriveItems { get; set; }
            /// Maximum number of changes to return.
            public int? MaxResults { get; set; }
            /// The token for continuing a previous list request on the next page. This should be set to the value of 'nextPageToken' from the previous response or to the response from the getStartPageToken method.
            public string PageToken { get; set; }
            /// A comma-separated list of spaces to query. Supported values are 'drive', 'appDataFolder' and 'photos'.
            public string Spaces { get; set; }
            /// Change ID to start listing changes from.
            public string StartChangeId { get; set; }
            /// Whether the requesting application supports Team Drives.
            public bool? SupportsTeamDrives { get; set; }
            /// The Team Drive from which changes will be returned. If specified the change IDs will be reflective of the Team Drive; use the combined Team Drive ID and change ID as an identifier.
            public string TeamDriveId { get; set; }

        }

        /// <summary>
        /// Lists the changes for a user or Team Drive.
        /// Documentation https://developers.google.com/drive/v2/reference/changes/list
        /// Generation Note: This does not always build corectly.  Google needs to standardise things I need to figuer out which ones are wrong.
        /// </summary>
        /// <param name="service">Authenticated Drive service.</param>
        /// <param name="optional">Optional paramaters.</param>
        /// <returns>ChangeListResponse</returns>
        public static ChangeList List(DriveService service, ChangesListOptionalParms optional = null)
        {
            try
            {
                // Initial validation.
                if (service == null)
                    throw new ArgumentNullException("service");

                // Building the initial request.
                var request = service.Changes.List();

                // Applying optional parameters to the request.
                request = (ChangesResource.ListRequest)SampleHelpers.ApplyOptionalParms(request, optional);

                // Requesting data.
                return request.Execute();
            }
            catch (Exception ex)
            {
                throw new Exception("Request Changes.List failed.", ex);
            }
        }
        public class ChangesWatchOptionalParms
        {
            /// Whether changes should include the file resource if the file is still accessible by the user at the time of the request, even when a file was removed from the list of changes and there will be no further change entries for this file.
            public bool? IncludeCorpusRemovals { get; set; }
            /// Whether to include changes indicating that items have been removed from the list of changes, for example by deletion or loss of access.
            public bool? IncludeDeleted { get; set; }
            /// Whether to include public files the user has opened and shared files. When set to false, the list only includes owned files plus any shared or public files the user has explicitly added to a folder they own.
            public bool? IncludeSubscribed { get; set; }
            /// Whether Team Drive files or changes should be included in results.
            public bool? IncludeTeamDriveItems { get; set; }
            /// Maximum number of changes to return.
            public int? MaxResults { get; set; }
            /// The token for continuing a previous list request on the next page. This should be set to the value of 'nextPageToken' from the previous response or to the response from the getStartPageToken method.
            public string PageToken { get; set; }
            /// A comma-separated list of spaces to query. Supported values are 'drive', 'appDataFolder' and 'photos'.
            public string Spaces { get; set; }
            /// Change ID to start listing changes from.
            public string StartChangeId { get; set; }
            /// Whether the requesting application supports Team Drives.
            public bool? SupportsTeamDrives { get; set; }
            /// The Team Drive from which changes will be returned. If specified the change IDs will be reflective of the Team Drive; use the combined Team Drive ID and change ID as an identifier.
            public string TeamDriveId { get; set; }

        }

        /// <summary>
        /// Subscribe to changes for a user.
        /// Documentation https://developers.google.com/drive/v2/reference/changes/watch
        /// Generation Note: This does not always build corectly.  Google needs to standardise things I need to figuer out which ones are wrong.
        /// </summary>
        /// <param name="service">Authenticated Drive service.</param>
        /// <param name="body">A valid Drive v2 body.</param>
        /// <param name="optional">Optional paramaters.</param>
        /// <returns>ChannelResponse</returns>
        public static Channel Watch(DriveService service, Channel body, ChangesWatchOptionalParms optional = null)
        {
            try
            {
                // Initial validation.
                if (service == null)
                    throw new ArgumentNullException("service");
                if (body == null)
                    throw new ArgumentNullException("body");

                // Building the initial request.
                var request = service.Changes.Watch(body);

                // Applying optional parameters to the request.
                request = (ChangesResource.WatchRequest)SampleHelpers.ApplyOptionalParms(request, optional);

                // Requesting data.
                return request.Execute();
            }
            catch (Exception ex)
            {
                throw new Exception("Request Changes.Watch failed.", ex);
            }
        }

        }

        public static class SampleHelpers
        {

        /// <summary>
        /// Using reflection to apply optional parameters to the request.
        ///
        /// If the optonal parameters are null then we will just return the request as is.
        /// </summary>
        /// <param name="request">The request. </param>
        /// <param name="optional">The optional parameters. </param>
        /// <returns></returns>
        public static object ApplyOptionalParms(object request, object optional)
        {
            if (optional == null)
                return request;

            System.Reflection.PropertyInfo[] optionalProperties = (optional.GetType()).GetProperties();

            foreach (System.Reflection.PropertyInfo property in optionalProperties)
            {
                // Copy value from optional parms to the request.  They should have the same names and datatypes.
                System.Reflection.PropertyInfo piShared = (request.GetType()).GetProperty(property.Name);
				if (property.GetValue(optional, null) != null) // TODO Test that we do not add values for items that are null
					piShared.SetValue(request, property.GetValue(optional, null), null);
            }

            return request;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
import React from 'react';
import { DropdownLayout } from 'wix-style-react';

const generateOption = id => {
  return { id, value: 'options ' + id };
};

export default class ExampleInfiniteScroll extends React.Component {
  constructor(props) {
    super(props);
    this.loadMore = this.loadMore.bind(this);
    this.itemsPerPage = 15;
    this.total = 300;
    this.state = { hasMore: true, data: [] };
  }

  style = {
    display: 'inline-block',
    padding: '0 5px',
    width: '240px',
    lineHeight: '22px',
  };

  generateData = () => {
    const newOptions = [];
    for (let i = 0; i < this.itemsPerPage; i++) {
      newOptions.push(generateOption(this.state.data.length + i));
    }
    this.setState({ data: this.state.data.concat(newOptions) });
  };

  loadMore() {
    const loadMoreData = () => {
      if (this.state.data.length >= this.total) {
        this.setState({ hasMore: false });
      } else {
        this.generateData();
      }
    };
    setTimeout(loadMoreData, 500);
  }

  render = () => {
    return (
      <div style={this.style}>
        <DropdownLayout
          infiniteScroll
          dataHook={'infinite-scroll-dropdownLayout'}
          visible
          onSelect={item => alert(item.value + ' was selected!')}
          hasMore={this.state.hasMore}
          loadMore={this.loadMore}
          options={this.state.data}
        />
      </div>
    );
  };
}


text:
'use strict';

const winston = require('winston');

const logger = new winston.Logger({
    transports: [
        new winston.transports.Console({
            timestamp: function() {
                return Date.now();
            },
            formatter(options) {
                // Return string will be passed to logger.
                let result = '';
                result += `${options.timestamp()} `;
                result += `${options.level.toUpperCase()} `;
                if (undefined !== options.message) {
                    result += options.message;
                }
                if (options.meta && Object.keys(options.meta).length) {
                    result += `\t${JSON.stringify(options.meta)}`;
                }
                return result;
            },
        }),
    ],
});

const fs = require('fs');

logger.wrscLog = function wrscLog(wrscStr) {
    fs.appendFile('/home/debian/logs/wrsc.log', `${wrscStr}\n`, err => {
        if (err) {
            logger.error('logger.wrscLog()', err);
        }
    });
};

if (process.env.DEBUG) {
    logger.level = 'debug';
}

module.exports = logger;


text:
<features>
  <repository>mvn:org.apache.camel.karaf/apache-camel/${camel-version}/xml/features</repository>
  <repository>mvn:org.apache.cxf.karaf/apache-cxf/${cxf-version}/xml/features</repository>
  <repository>mvn:io.hawt/hawtio-karaf/${hawtio-version}/xml/features</repository>

  <feature name='chapter10-camel-cxf-rest-karaf' version='${project.version}'>
    <feature>war</feature>
    <feature version="${hawtio-version}">hawtio-offline</feature>
    <feature version="${camel-version}">camel</feature>
    <feature version="${camel-version}">camel-cxf</feature>
    <feature version="${camel-version}">camel-jaxb</feature>
    <feature version="${camel-version}">camel-jackson</feature>
    <feature version="${cxf-version}">cxf-jaxrs</feature>
    <feature version="${cxf-version}">cxf-http-jetty</feature>
    <bundle>mvn:com.fasterxml.jackson.jaxrs/jackson-jaxrs-base/${jackson-version}</bundle>
    <bundle>mvn:com.fasterxml.jackson.jaxrs/jackson-jaxrs-json-provider/${jackson-version}</bundle>
    <!-- we should start last -->
    <bundle start-level="90">mvn:com.camelinaction/chapter10-camel-cxf-rest-karaf/${project.version}</bundle>
  </feature>

</features>


text:
namespace igl
{
  namespace opengl
  {
    // Compile and link very simple vertex/fragment shaders
    //
    // Inputs:
    //   v_str  string of vertex shader contents
    //   f_str  string of fragment shader contents
    // Returns id of program
    //
    // Known bugs: this seems to duplicate `create_shader_program` with less
    // functionality.
    IGL_INLINE GLuint compile_and_link_program(
      const char * v_str, const char * f_str);
  }
}
#ifndef IGL_STATIC_LIBRARY
#  include "compile_and_link_program.cpp"
#endif
#endif


text:
package org.apache.flink.test.checkpointing;

import org.apache.flink.api.common.restartstrategy.RestartStrategies;
import org.apache.flink.configuration.ConfigConstants;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.TaskManagerOptions;
import org.apache.flink.runtime.minicluster.LocalFlinkMiniCluster;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.util.TestStreamEnvironment;
import org.apache.flink.test.util.TestUtils;
import org.apache.flink.util.TestLogger;

import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;

import java.io.Serializable;

import static org.junit.Assert.fail;

/**
 * Test base for fault tolerant streaming programs.
 */
public abstract class StreamFaultToleranceTestBase extends TestLogger {

	protected static final int NUM_TASK_MANAGERS = 3;
	protected static final int NUM_TASK_SLOTS = 4;
	protected static final int PARALLELISM = NUM_TASK_MANAGERS * NUM_TASK_SLOTS;

	private static LocalFlinkMiniCluster cluster;

	@BeforeClass
	public static void startCluster() {
		try {
			Configuration config = new Configuration();
			config.setInteger(ConfigConstants.LOCAL_NUMBER_TASK_MANAGER, NUM_TASK_MANAGERS);
			config.setInteger(ConfigConstants.TASK_MANAGER_NUM_TASK_SLOTS, NUM_TASK_SLOTS);
			config.setLong(TaskManagerOptions.MANAGED_MEMORY_SIZE, 12L);

			cluster = new LocalFlinkMiniCluster(config, false);

			cluster.start();
		}
		catch (Exception e) {
			e.printStackTrace();
			fail("Failed to start test cluster: " + e.getMessage());
		}
	}

	@AfterClass
	public static void stopCluster() {
		try {
			cluster.stop();
			cluster = null;
		}
		catch (Exception e) {
			e.printStackTrace();
			fail("Failed to stop test cluster: " + e.getMessage());
		}
	}

	/**
	 * Implementations are expected to assemble the test topology in this function
	 * using the provided {@link StreamExecutionEnvironment}.
	 */
	public abstract void testProgram(StreamExecutionEnvironment env);

	/**
	 * Implementations are expected to provide test here to verify the correct behavior.
	 */
	public abstract void postSubmit() throws Exception;

	/**
	 * Runs the following program the test program defined in {@link #testProgram(StreamExecutionEnvironment)}
	 * followed by the checks in {@link #postSubmit}.
	 */
	@Test
	public void runCheckpointedProgram() throws Exception {
		try {
			TestStreamEnvironment env = new TestStreamEnvironment(cluster, PARALLELISM);
			env.setParallelism(PARALLELISM);
			env.enableCheckpointing(500);
			env.getConfig().disableSysoutLogging();
			env.setRestartStrategy(RestartStrategies.fixedDelayRestart(Integer.MAX_VALUE, 0L));

			testProgram(env);

			TestUtils.tryExecute(env, "Fault Tolerance Test");

			postSubmit();
		}
		catch (Exception e) {
			e.printStackTrace();
			Assert.fail(e.getMessage());
		}
	}

	// --------------------------------------------------------------------------------------------
	//  Frequently used utilities
	// --------------------------------------------------------------------------------------------

	/**
	 * POJO storing prefix, value, and count.
	 */
	@SuppressWarnings("serial")
	public static class PrefixCount implements Serializable {

		public String prefix;
		public String value;
		public long count;

		public PrefixCount() {}

		public PrefixCount(String prefix, String value, long count) {
			this.prefix = prefix;
			this.value = value;
			this.count = count;
		}

		@Override
		public String toString() {
			return prefix + " / " + value;
		}
	}
}


text:
<link rel="import" href="../bower_components/polymer/polymer-element.html">
<link rel="import" href="../bower_components/app-layout/app-drawer/app-drawer.html">
<link rel="import" href="../bower_components/app-layout/app-drawer-layout/app-drawer-layout.html">
<link rel="import" href="../bower_components/app-layout/app-header/app-header.html">
<link rel="import" href="../bower_components/app-layout/app-header-layout/app-header-layout.html">
<link rel="import" href="../bower_components/app-layout/app-scroll-effects/app-scroll-effects.html">
<link rel="import" href="../bower_components/app-layout/app-toolbar/app-toolbar.html">
<link rel="import" href="../bower_components/app-route/app-location.html">
<link rel="import" href="../bower_components/app-route/app-route.html">
<link rel="import" href="../bower_components/iron-pages/iron-pages.html">
<link rel="import" href="../bower_components/iron-list/iron-list.html">
<link rel="import" href="../bower_components/iron-icons/iron-icons.html">
<link rel="import" href="../bower_components/iron-selector/iron-selector.html">
<link rel="import" href="../bower_components/paper-icon-button/paper-icon-button.html">
<link rel="import" href="my-icons.html">

<link rel="lazy-import" href="my-search.html">

<dom-module id="my-app">
  <template>

    <app-location route="{{route}}" url-space-regex="^[[rootPath]]"></app-location>
    <app-route
        route="{{route}}"
        pattern="[[rootPath]]:page"
        data="{{routeData}}"
        tail="{{subroute}}"></app-route>

    <app-drawer-layout fullbleed narrow="{{narrow}}">

      <app-drawer id="drawer" slot="drawer" swipe-open="[[narrow]]">
        <app-toolbar>Search Facets</app-toolbar>
        <template is="dom-if" if="{{refinements}}">

Selected Facets

              <iron-list items="{{refinements}}">
                <template>

                      <iron-icon icon="icons:remove-circle"></iron-icon>
                      [[_getFriendlyFacetName(item.facet_name)]]: [[item.facet_value]]

                </template>
              </iron-list>

        </template>
        <template is="dom-repeat" id="facetrepeat" items="{{_filterAvailableFacets(facets)}}">

[[_getFriendlyFacetName(item.name)]]

            <iron-list items="[[item.value]]">
              <template>

                    <iron-icon icon="icons:add-circle"></iron-icon>
                    [[item.facet_value]] ([[item.facet_count]])

              </template>
            </iron-list>

        </template>
      </app-drawer>

      <app-header-layout has-scrolling-region>

        <app-header slot="header" condenses reveals effects="waterfall">
          <app-toolbar>
            <paper-icon-button icon="my-icons:menu" drawer-toggle></paper-icon-button>

Image Search Demo

          </app-toolbar>
        </app-header>

        <iron-pages
            selected="[[page]]"
            attr-for-selected="name"
            fallback-selection="view404"
            role="main">
          <my-search name="search" facets="{{facets}}" refinements="{{refinements}}"></my-search>
          <my-view404 name="view404"></my-view404>
        </iron-pages>
      </app-header-layout>
    </app-drawer-layout>
  </template>

</dom-module>


text:
#include "include/core/SkString.h"
#include "include/gpu/GrContextOptions.h"
#include "src/gpu/GrShaderUtils.h"
#include "src/sksl/SkSLString.h"

namespace GrShaderUtils {

class GLSLPrettyPrint {
public:
    GLSLPrettyPrint() {}

    SkSL::String prettify(const SkSL::String& string) {
        fTabs = 0;
        fFreshline = true;

        // If a string breaks while in the middle 'parse until' we need to continue parsing on the
        // next string
        fInParseUntilNewline = false;
        fInParseUntil = false;

        int parensDepth = 0;

        // setup pretty state
        fIndex = 0;
        fLength = string.length();
        fInput = string.c_str();

        while (fLength > fIndex) {
            /* the heart and soul of our prettification algorithm.  The rules should hopefully
             * be self explanatory.  For '#' and '//' tokens we parse until we reach a newline.
             *
             * For long style comments like this one, we search for the ending token.  We also
             * preserve whitespace in these comments WITH THE CAVEAT that we do the newlines
             * ourselves.  This allows us to remain in control of line numbers, and matching
             * tabs Existing tabs in the input string are copied over too, but this will look
             *  funny
             *
             * '{' and '}' are handled in basically the same way.  We add a newline if we aren't
             * on a fresh line, dirty the line, then add a second newline, ie braces are always
             * on their own lines indented properly.  The one funkiness here is structs print
             * with the semicolon on its own line.  Its not a problem for a glsl compiler though
             *
             * '(' and ')' are basically ignored, except as a sign we need to ignore ';' ala
             * in for loops.
             *
             * ';' means add a new line
             *
             * '\t' and '\n' are ignored in general parsing for backwards compatability with
             * existing shader code and we also have a special case for handling whitespace
             * at the beginning of fresh lines.
             *
             * Otherwise just add the new character to the pretty string, indenting if
             * necessary.
             */
            if (fInParseUntilNewline) {
                this->parseUntilNewline();
            } else if (fInParseUntil) {
                this->parseUntil(fInParseUntilToken);
            } else if (this->hasToken("#") || this->hasToken("//")) {
                this->parseUntilNewline();
            } else if (this->hasToken("/*")) {
                this->parseUntil("*/");
            } else if ('{' == fInput[fIndex]) {
                this->newline();
                this->appendChar('{');
                fTabs++;
                this->newline();
            } else if ('}' == fInput[fIndex]) {
                fTabs--;
                this->newline();
                this->appendChar('}');
                this->newline();
            } else if (this->hasToken(")")) {
                parensDepth--;
            } else if (this->hasToken("(")) {
                parensDepth++;
            } else if (!parensDepth && this->hasToken(";")) {
                this->newline();
            } else if ('\t' == fInput[fIndex] || '\n' == fInput[fIndex] ||
                        (fFreshline && ' ' == fInput[fIndex])) {
                fIndex++;
            } else {
                this->appendChar(fInput[fIndex]);
            }
        }

        return fPretty;
    }

private:
    void appendChar(char c) {
        this->tabString();
        fPretty.appendf("%c", fInput[fIndex++]);
        fFreshline = false;
    }

    // hasToken automatically consumes the next token, if it is a match, and then tabs
    // if necessary, before inserting the token into the pretty string
    bool hasToken(const char* token) {
        size_t i = fIndex;
        for (size_t j = 0; token[j] && fLength > i; i++, j++) {
            if (token[j] != fInput[i]) {
                return false;
            }
        }
        this->tabString();
        fIndex = i;
        fPretty.append(token);
        fFreshline = false;
        return true;
    }

    void parseUntilNewline() {
        while (fLength > fIndex) {
            if ('\n' == fInput[fIndex]) {
                fIndex++;
                this->newline();
                fInParseUntilNewline = false;
                break;
            }
            fPretty.appendf("%c", fInput[fIndex++]);
            fInParseUntilNewline = true;
        }
    }

    // this code assumes it is not actually searching for a newline.  If you need to search for a
    // newline, then use the function above.  If you do search for a newline with this function
    // it will consume the entire string and the output will certainly not be prettified
    void parseUntil(const char* token) {
        while (fLength > fIndex) {
            // For embedded newlines,  this code will make sure to embed the newline in the
            // pretty string, increase the linecount, and tab out the next line to the appropriate
            // place
            if ('\n' == fInput[fIndex]) {
                this->newline();
                this->tabString();
                fIndex++;
            }
            if (this->hasToken(token)) {
                fInParseUntil = false;
                break;
            }
            fFreshline = false;
            fPretty.appendf("%c", fInput[fIndex++]);
            fInParseUntil = true;
            fInParseUntilToken = token;
        }
    }

    // We only tab if on a newline, otherwise consider the line tabbed
    void tabString() {
        if (fFreshline) {
            for (int t = 0; t < fTabs; t++) {
                fPretty.append("\t");
            }
        }
    }

    // newline is really a request to add a newline, if we are on a fresh line there is no reason
    // to add another newline
    void newline() {
        if (!fFreshline) {
            fFreshline = true;
            fPretty.append("\n");
        }
    }

    bool fFreshline;
    int fTabs;
    size_t fIndex, fLength;
    const char* fInput;
    SkSL::String fPretty;

    // Some helpers for parseUntil when we go over a string length
    bool fInParseUntilNewline;
    bool fInParseUntil;
    const char* fInParseUntilToken;
};

SkSL::String PrettyPrint(const SkSL::String& string) {
    GLSLPrettyPrint pp;
    return pp.prettify(string);
}

// Prints shaders one line at the time. This ensures they don't get truncated by the adb log.
void PrintLineByLine(const char* header, const SkSL::String& text) {
    if (header) {
        SkDebugf("%s\n", header);
    }
    SkTArray<SkString> lines;
    SkStrSplit(text.c_str(), "\n", kStrict_SkStrSplitMode, &lines);
    for (int i = 0; i < lines.count(); ++i) {
        SkDebugf("%4i\t%s\n", i + 1, lines[i].c_str());
    }
}

GrContextOptions::ShaderErrorHandler* DefaultShaderErrorHandler() {
    class GrDefaultShaderErrorHandler : public GrContextOptions::ShaderErrorHandler {
    public:
        void compileError(const char* shader, const char* errors) override {
            SkDebugf("Shader compilation error\n"
                     "------------------------\n");
            PrintLineByLine(nullptr, shader);
            SkDebugf("Errors:\n%s\n", errors);
            SkDEBUGFAIL("Shader compilation failed!");
        }
    };

    static GrDefaultShaderErrorHandler gHandler;
    return &gHandler;
}

}  // namespace


text:
require 'omniauth-oauth2'

module OmniAuth
  module Strategies
    class Evesso < OmniAuth::Strategies::OAuth2
      # Give your strategy a name.
      option :name, "evesso"

      # This is where you pass the options you would pass when
      # initializing your consumer from the OAuth gem.
      option :client_options, {
        site: "https://login.eveonline.com",
        authorize_url: "https://login.eveonline.com/oauth/authorize"
      }

      # These are called after authentication has succeeded. If
      # possible, you should try to set the UID without making
      # additional calls (if the user id is returned with the token
      # or as a URI parameter). This may not be possible with all
      # providers.
      uid do
       raw_info['CharacterID']
      end

      info do
        {
          character_id: raw_info['CharacterID'],
          name: raw_info['CharacterName'],
          token_type: raw_info['TokenType'],
          character_owner_hash: raw_info['CharacterOwnerHash'],
          expires_on: raw_info['ExpiresOn'],
          scopes: raw_info['Scopes']
        }
      end

      extra do
        {
          'raw_info' => raw_info
        }
      end

      def raw_info
        @raw_info ||= access_token.get('/oauth/verify').parsed
      end
    end
  end
end


text:
{% extends "base.html" %}
{% block title %}{{post.title|escape}} - {{config.blog_name}}{% endblock %}
{% block body %}

{{post.title|escape}}

      <time pubdate class="date">{{post.published_tz|date:config.date_format}}</time>
      {% if post.tags %}
        {% for tag in post.tag_pairs %}
          {{tag.0|escape}}
        {% endfor %}
      {% endif %}

  {{post.rendered}}

  {% if prev %}
    Previous Post
  {% endif %}
  {% if next %}
    Next Post
  {% endif %}

  {% if config.disqus_forum %}

Comments

    {% if devel %}

    {% endif %}

    View the discussion thread.
    blog comments powered by Disqus
  {% endif %}

  {% if config.google_friends_id and config.google_friends_comments %}

  {% endif %}

{% endblock %}


text:
# LUXRAYS_CUSTOM_CONFIG
# E:/projects/luxrays-32bit/luxrays/cmake/SpecializedConfig/Config_Dade-win32.cmake
#
# Boost:
#  bjam --toolset=msvc --stagedir=stage stage -j 8
#
# To disable OpenMP support (VCOMP.lib error) in Visula Studio 2010 go
# properties => C/C++ => languages and disable OpenMP

MESSAGE(STATUS "Using Dade's Win32 Configuration settings")

set(CMAKE_BUILD_TYPE "Release")

set(ENV{QTDIR} "C:/Qt/4.7.1")

set(FREEIMAGE_SEARCH_PATH "E:/projects/luxrays-32bit/FreeImage")
set(FreeImage_INC_SEARCH_PATH "${FREEIMAGE_SEARCH_PATH}/Dist")
set(FreeImage_LIB_SEARCH_PATH "${FREEIMAGE_SEARCH_PATH}/Dist")
set(FREEIMAGE_ROOT_DIR "${FREEIMAGE_SEARCH_PATH}/Dist")

set(BOOST_SEARCH_PATH         "E:/projects/luxrays-32bit/boost_1_48_0")
set(BOOST_LIBRARYDIR          "${BOOST_SEARCH_PATH}/stage/boost/lib")

set(OPENCL_SEARCH_PATH        "C:/Program Files (x86)/AMD APP")
set(OPENCL_LIBRARYDIR         "${OPENCL_SEARCH_PATH}/lib/x86")

# For GLUT with sources
set(GLUT_SEARCH_PATH          "E:/projects/luxrays-32bit/freeglut-2.8.0")
set(GLUT_LIBRARYDIR           "${GLUT_SEARCH_PATH}/lib/x86")
ADD_DEFINITIONS(-DFREEGLUT_STATIC)
# For GLUT with binary-only
#set(GLUT_SEARCH_PATH          "E:/projects/luxrays-32bit/freeglut-bin")
#set(GLUT_LIBRARYDIR           "${GLUT_SEARCH_PATH}/lib")

set(GLEW_SEARCH_PATH          "E:/projects/luxrays-32bit/glew-1.7.0")
ADD_DEFINITIONS(-DGLEW_BUILD)


text:
/* Includes ------------------------------------------------------------------*/
#include "tsl_time_stm32f0xx.h"

/* Private typedefs ----------------------------------------------------------*/
/* Private defines -----------------------------------------------------------*/
/* Private macros ------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private functions prototype -----------------------------------------------*/

/**
  * @brief  Initialization of the timing module.
  * @param  None
  * @retval Status Return TSL_STATUS_ERROR if the Systick configuration has failed.
  */
TSL_Status_enum_T TSL_tim_Init(void)
{
  // Program one systick interrupt every (1 / TSLPRM_TICK_FREQ) ms
  if (SysTick_Config(SystemCoreClock / TSLPRM_TICK_FREQ))
  {
    return TSL_STATUS_ERROR;
  }
  else
  {
    return TSL_STATUS_OK;
  }
}

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/


text:
/*global describe, it*/
"use strict";

var fs = require("fs"),
	es = require("event-stream"),
	should = require("should");

require("mocha");

delete require.cache[require.resolve("../")];

var gutil = require("gulp-util"),
	cdnizer = require("../"),
	loadFile = function(name) {
		return new gutil.File({
			path: "test/expected/"+name,
			cwd: "test/",
			base: "test/expected",
			contents: fs.readFileSync("test/expected/"+name)
		})
	};

describe("gulp-cdnizer", function () {

	var processInput = function(opts, expectedFileName, done) {
			var stream = cdnizer(opts),
				srcFile = new gutil.File({
					path: "test/fixtures/index.html",
					cwd: "test/",
					base: "test/fixtures",
					contents: fs.readFileSync("test/fixtures/index.html")
				});

			stream.on("error", function(err) {
				should.not.exist(err);
				done(err);
			});

			stream.on("data", function (newFile) {

				should.exist(newFile);
				should.exist(newFile.contents);

				String(newFile.contents).should.equal(String(loadFile(expectedFileName).contents));
				done();
			});

			stream.write(srcFile);
			stream.end();
		};

	it("should not modify a file if no matches", function (done) {
		processInput(['/no/match'], 'index-none.html', done);
	});

	it("should modify on basic input", function (done) {
		processInput({
			files: ['css/main.css', 'js/**/*.js'],
			defaultCDNBase: '//examplecdn/'
		}, 'index-generic.html', done);
	});

	it("should handle varied input", function (done) {
		processInput({
			files: ['css/*.css', 'js/**/*.js'],
			defaultCDNBase: '//examplecdn'
		}, 'index-generic.html', done);
	});

	it("should handle min and fallbacks", function (done) {
		processInput({
			files: [{
				file: 'js/**/angular/angular.js',
				test: 'window.angular'
			}],
			defaultCDNBase: '//examplecdn'
		}, 'index-fallback.html', done);
	});

	it("should add min with filenameMin", function(done) {
		processInput({
			files: [{
				file: 'js/**/firebase/firebase.js',
				cdn: '//examplecdn/js/vendor/firebase/${ filenameMin }'
			}]
		}, 'index-filename-min.html', done);
	});

	it("should handle bower versions (.bowerrc)", function (done) {
		processInput({
			files: [{
				file: 'js/**/angular/angular.js',
				package: 'angular',
				cdn: '//ajax.googleapis.com/ajax/libs/angularjs/${ major }.${ minor }.${ patch }/angular.min.js'
			}]
		}, 'index-bowerrc.html', done);
	});

	it("should handle bower versions (passed in)", function (done) {
		processInput({
			bowerComponents: './test/bower_components',
			files: [{
				file: 'js/**/angular/angular.js',
				package: 'angular',
				cdn: '//ajax.googleapis.com/ajax/libs/angularjs/${ major }.${ minor }.${ patch }/angular.min.js'
			}]
		}, 'index-bower.html', done);
	});

	it("should error on stream", function (done) {

		var stream = cdnizer(['foo/bar']);

		var srcFileStream = new gutil.File({
			path: "test/fixtures/index.html",
			cwd: "test/",
			base: "test/fixtures",
			contents: fs.createReadStream("test/fixtures/index.html")
		});

		stream.on("error", function(err) {
			should.exist(err);
			done();
		});

		stream.on("data", function (newFile) {
			newFile.contents.pipe(es.wait(function(err, data) {
				done(err);
			}));
		});

		stream.write(srcFileStream);
		stream.end();
	});
});


text:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LogicAppTemplate.Models
{
    public class Api
    {
        public string id { get; set; }
    }

    public class Properties
    {
        public Properties(string name, string apiId)
        {
            displayName = name;
            api = new Api { id = apiId};
        }
        public Api api { get; set; }
        public string displayName { get; set; }

        //only fill connectionParameters when source not empty, otherwise saved credentials will be lost.
        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public dynamic parameterValues { get; set; }
    }

    public class ConnectionTemplate
    {
        private string connectionName = "";
        public ConnectionTemplate(string name, string apiId)
        {
            connectionName = name;
            properties = new Properties(name, apiId);
        }
        public string type { get {
                return "Microsoft.Web/connections";
            } }
        public string apiVersion { get {
                return "2016-06-01";
            } }
        public string location { get {
                return "[parameters('logicAppLocation')]";
            } }
        public string name { get {
                return $"[parameters('{connectionName}')]";
            } }
        public Properties properties { get; set; }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;

namespace EasySoftware.PMS.Core.Models
{
	public partial class Project
	{

		public Project()
		{
			this.Tasks = new HashSet<Task>();
			this.Applications = new HashSet<Application>();
			this.Categories = new HashSet<Category>();
			this.ProjectUsers = new HashSet<ProjectUser>();
		}

		public virtual ICollection<Task> Tasks { get; set; }
		public virtual ICollection<Application> Applications { get; set; }
		public virtual ICollection<Category> Categories { get; set; }
		public virtual ICollection<ProjectUser> ProjectUsers { get; set; }
	}
}


text:
My OS X / Ubuntu dotfiles.

## Installation

```sh
bash -c "$(curl -fsSL https://raw.github.com/iantruslove/.dotfiles/master/bin/dotfiles)" && source ~/.bashrc
```
or
```sh
bash -c "$(wget -qO - https://raw.github.com/iantruslove/.dotfiles/master/bin/dotfiles)" && source ~/.bashrc
```

## Rationale

Heavily inspired by (i.e. stolen from) Ben Alman's https://github.com/cowboy/dotfiles.

I finally decided that I wanted to be able to execute a single command
to "bootstrap" a new system to pull down all of my dotfiles and
configs, as well as install all the tools I commonly use. In addition,
I wanted to be able to re-execute that command at any time to
synchronize anything that might have changed. Finally, I wanted to
make it easy to re-integrate changes back in, so that other machines
could be updated.

That command is [dotfiles][dotfiles], and this is my "dotfiles" Git repo.

[dotfiles]: bin/dotfiles
[bin]: https://github.com/iantruslove/.dotfiles/tree/master/bin

## What, exactly, does the "dotfiles" command do?

It's really not very complicated. When [dotfiles][dotfiles] is run, it does a few things:

1. Git is installed if necessary, via APT or Homebrew (which is installed if necessary).
2. This repo is cloned into the `~/.dotfiles` directory (or updated if it already exists).
3. Files in `init` are executed (in alphanumeric order, hence the "50_" names).
4. Files in `copy` are copied into `~/`.
5. Files in `link` are linked into `~/`.

Note:

* The `backups` folder only gets created when necessary. Any files in
  `~/` that would have been overwritten by `copy` or `link` get backed
  up there.
* Files in `bin` are executable shell scripts
  (Eg. [~/.dotfiles/bin][bin] is added into the path).
* Files in `source` get sourced whenever a new shell is opened (in
  alphanumeric order, hence the "50_" names).
* Files in `conf` just sit there. If a config file doesn't _need_ to
  go in `~/`, put it in there.
* Files in `caches` are cached files, only used by some scripts. This
  folder will only be created if necessary.

## Prerequisites

### OS X Notes

* You need to be an administrator (for `sudo`).
* You need to have installed [XCode][] or, at the very minimum, the
  [XCode Command Line Tools][], which are available as a
  _much smaller_ download.

[XCode]: https://developer.apple.com/downloads/index.action?=xcode
[XCode Command Line Tools]: https://developer.apple.com/downloads/index.action?=command%20line%20tools

### Ubuntu Notes

* You need to be an administrator (for `sudo`).
* You might want to update/upgrade APT with `sudo apt-get update &&
  sudo apt-get upgrade` first.  Or not, live dangerously!

## Details

### The "init" step

A whole bunch of things will be installed, but _only_ if they aren't
already.  Check out the scripts in the [init](init/) directory.

### The ~/ "copy" step

Any file in the `copy` subdirectory will be copied into `~/`. Any file
that _needs_ to be modified with personal information (like
[.gitconfig](copy/.gitconfig) which contains an email address and
private key) should be _copied_ into `~/`. Because the file you'll be
editing is no longer in `~/.dotfiles`, it's less likely to be
accidentally committed into your public dotfiles repo.

### The ~/ "link" step

Any file in the `link` subdirectory gets symbolically linked with `ln
-s` into `~/`. Edit these, and you change the file in the repo. Don't
link files containing sensitive data, or you might accidentally commit
that data!

### Aliases and Functions

To keep things easy, the `~/.bashrc` and `~/.bash_profile` files are
extremely simple, and should never need to be modified. Instead, add
your aliases, functions, settings, etc into one of the files in the
`source` subdirectory, or add a new file. They're all automatically
sourced when a new shell is opened. Take a look, I have
[a lot of aliases and functions](https://github.com/iantruslove/.dotfiles/tree/master/source).
I even have a [fancy prompt](source/50_prompt.sh) that shows the
current directory, time and current git/svn repo status.

### Scripts

In addition to the aforementioned [dotfiles][dotfiles] script, there
are a few other [bash scripts][bin]. This includes
[ack](https://github.com/petdance/ack), which is a
[git submodule](https://github.com/iantruslove/.dotfiles/tree/master/libs).

* [dotfiles][dotfiles] - (re)initialize dotfiles. It might ask for your password (for `sudo`).
* [src](link/.bashrc#L6-15) - (re)source all files in `source` directory
* Look through the [bin][bin] subdirectory for a few more.

### Prompt

It shows git and svn repo status, a timestamp, error exit codes, and
even changes color depending on how you've logged in.

Git repos display as **[branch:flags]** where flags are:

**?** untracked files
**!** changed (but unstaged) files
**+** staged files

SVN repos display as **[rev1:rev2]** where rev1 and rev2 are:

**rev1** last changed revision
**rev2** revision

## License

Licensed under the MIT license.


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/sky_background"
    android:orientation="vertical" >

    <Button
        android:id="@+id/return_to_homepage"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="5dp"
        android:text="Return to Homepage"
        android:gravity="center"
        android:textColor="#404040"
        android:background="@drawable/chatfrom_bg_normal"
        />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="35dp"
        android:text="Book ISBN:"
        android:gravity="center_vertical"
        android:textColor="@android:color/white"
        android:background="@drawable/mmtitle_bg_alpha"
        android:layout_margin="1dp" />
    <TextView
        android:id="@+id/book_isbn"
        android:layout_width="fill_parent"
        android:layout_height="35dp"
        android:lines="1"
        android:gravity="center_horizontal"
        android:textColor="@android:color/black"
        android:textSize="16sp"
        android:background="@drawable/aloha_light_blue_background"
        android:layout_margin="1dp" />
     <TextView
        android:layout_width="wrap_content"
        android:layout_height="35dp"
        android:text="Result Info:"
        android:gravity="left"
        android:textSize="16sp"
        android:textColor="@android:color/white"
        android:background="@drawable/mmtitle_bg_alpha"
        android:layout_margin="1dp" />
    <TextView
        android:id="@+id/result_info"
        android:layout_width="fill_parent"
        android:layout_height="35dp"
        android:lines="1"
        android:gravity="center_horizontal"
        android:layout_gravity="center"
        android:textColor="@android:color/black"
        android:textSize="16sp"
        android:background="@drawable/aloha_light_blue_background"
        android:layout_margin="1dp" />
    <ImageView
        android:id="@+id/qrcode_bitmap_after_scan"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        />

    <TextView
        android:id="@+id/jump_to_book"
        android:layout_width="fill_parent"
        android:layout_height="35dp"
        android:lines="1"
        android:gravity="center_horizontal"
        android:layout_gravity="center"
        android:textColor="@android:color/black"
        android:textSize="16sp"
        android:background="@drawable/aloha_light_blue_background"
        android:layout_margin="1dp"
        android:text="Click to jump to the book in douban.com"/>
</LinearLayout>


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

using Internal.Text;
using Internal.TypeSystem;

namespace ILCompiler.DependencyAnalysis
{
    internal sealed class ClonedConstructedEETypeNode : ConstructedEETypeNode, ISymbolDefinitionNode
    {
        public ClonedConstructedEETypeNode(NodeFactory factory, TypeDesc type) : base(factory, type)
        {
        }

        protected override string GetName(NodeFactory factory) => this.GetMangledName(factory.NameMangler) + " cloned";

        public override ObjectNode NodeForLinkage(NodeFactory factory) => this;

        //
        // A cloned type must be named differently than the type it is a clone of so the linker
        // will have an unambiguous symbol to resolve
        //
        public override void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb)
        {
            sb.Append("__Cloned_EEType_").Append(nameMangler.GetMangledTypeName(_type));
        }
        public override bool IsShareable => true;

        protected override void OutputRelatedType(NodeFactory factory, ref ObjectDataBuilder objData)
        {
            //
            // Cloned types use the related type field to point via an IAT slot at their true implementation
            //
            objData.EmitPointerReloc(factory.NecessaryTypeSymbol(_type));
        }

        protected internal override int ClassCode => -288888778;
    }
}


text:
Sample configuration files for:

SystemD: polcoind.service
Upstart: polcoind.conf
OpenRC:  polcoind.openrc
         polcoind.openrcconf
CentOS:  polcoind.init

have been made available to assist packagers in creating node packages here.

See doc/init.md for more information.


text:
"""Invoke tasks. To run a task, run ``$ invoke <COMMAND>``. To see a list of
commands, run ``$ invoke --list``.
"""
import os
import sys
import json
import platform
import subprocess
import logging
from time import sleep

import invoke
from invoke import Collection

from website import settings
from .utils import pip_install, bin_prefix

logging.getLogger('invoke').setLevel(logging.CRITICAL)

# gets the root path for all the scripts that rely on it
HERE = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..'))
WHEELHOUSE_PATH = os.environ.get('WHEELHOUSE')
CONSTRAINTS_PATH = os.path.join(HERE, 'requirements', 'constraints.txt')

ns = Collection()

try:
    from admin import tasks as admin_tasks
    ns.add_collection(Collection.from_module(admin_tasks), name='admin')
except ImportError:
    pass

def task(*args, **kwargs):
    """Behaves the same way as invoke.task. Adds the task
    to the root namespace.
    """
    if len(args) == 1 and callable(args[0]):
        new_task = invoke.task(args[0])
        ns.add_task(new_task)
        return new_task
    def decorator(f):
        new_task = invoke.task(f, *args, **kwargs)
        ns.add_task(new_task)
        return new_task
    return decorator

@task
def server(ctx, host=None, port=5000, debug=True, gitlogs=False):
    """Run the app server."""
    if os.environ.get('WERKZEUG_RUN_MAIN') == 'true' or not debug:
        if os.environ.get('WEB_REMOTE_DEBUG', None):
            import pydevd
            # e.g. '127.0.0.1:5678'
            remote_parts = os.environ.get('WEB_REMOTE_DEBUG').split(':')
            pydevd.settrace(remote_parts[0], port=int(remote_parts[1]), suspend=False, stdoutToServer=True, stderrToServer=True)

        if gitlogs:
            git_logs(ctx)
        from website.app import init_app
        os.environ['DJANGO_SETTINGS_MODULE'] = 'api.base.settings'
        app = init_app(set_backends=True, routes=True)
        settings.API_SERVER_PORT = port
    else:
        from framework.flask import app

    context = None
    if settings.SECURE_MODE:
        context = (settings.OSF_SERVER_CERT, settings.OSF_SERVER_KEY)
    app.run(host=host, port=port, debug=debug, threaded=debug, extra_files=[settings.ASSET_HASH_PATH], ssl_context=context)

@task
def git_logs(ctx, branch=None):
    from scripts.meta import gatherer
    gatherer.main(branch=branch)

@task
def apiserver(ctx, port=8000, wait=True, autoreload=True, host='127.0.0.1', pty=True):
    """Run the API server."""
    env = os.environ.copy()
    cmd = 'DJANGO_SETTINGS_MODULE=api.base.settings {} manage.py runserver {}:{} --nothreading'\
        .format(sys.executable, host, port)
    if not autoreload:
        cmd += ' --noreload'
    if settings.SECURE_MODE:
        cmd = cmd.replace('runserver', 'runsslserver')
        cmd += ' --certificate {} --key {}'.format(settings.OSF_SERVER_CERT, settings.OSF_SERVER_KEY)

    if wait:
        return ctx.run(cmd, echo=True, pty=pty)
    from subprocess import Popen

    return Popen(cmd, shell=True, env=env)

@task
def adminserver(ctx, port=8001, host='127.0.0.1', pty=True):
    """Run the Admin server."""
    env = 'DJANGO_SETTINGS_MODULE="admin.base.settings"'
    cmd = '{} python manage.py runserver {}:{} --nothreading'.format(env, host, port)
    if settings.SECURE_MODE:
        cmd = cmd.replace('runserver', 'runsslserver')
        cmd += ' --certificate {} --key {}'.format(settings.OSF_SERVER_CERT, settings.OSF_SERVER_KEY)
    ctx.run(cmd, echo=True, pty=pty)

@task
def shell(ctx, transaction=True, print_sql=False, notebook=False):
    cmd = 'DJANGO_SETTINGS_MODULE="api.base.settings" python manage.py osf_shell'
    if print_sql:
        cmd += ' --print-sql'
    if notebook:
        cmd += ' --notebook'
    if not transaction:
        cmd += ' --no-transaction'
    return ctx.run(cmd, pty=True, echo=True)

@task(aliases=['mongo'])
def mongoserver(ctx, daemon=False, config=None):
    """Run the mongod process.
    """
    if not config:
        platform_configs = {
            'darwin': '/usr/local/etc/tokumx.conf',  # default for homebrew install
            'linux': '/etc/tokumx.conf',
        }
        platform = str(sys.platform).lower()
        config = platform_configs.get(platform)
    port = settings.DB_PORT
    cmd = 'mongod --port {0}'.format(port)
    if config:
        cmd += ' --config {0}'.format(config)
    if daemon:
        cmd += ' --fork'
    ctx.run(cmd, echo=True)

@task(aliases=['mongoshell'])
def mongoclient(ctx):
    """Run the mongo shell for the OSF database."""
    db = settings.DB_NAME
    port = settings.DB_PORT
    ctx.run('mongo {db} --port {port}'.format(db=db, port=port), pty=True)

@task
def mongodump(ctx, path):
    """Back up the contents of the running OSF database"""
    db = settings.DB_NAME
    port = settings.DB_PORT

    cmd = 'mongodump --db {db} --port {port} --out {path}'.format(
        db=db,
        port=port,
        path=path,
        pty=True)

    if settings.DB_USER:
        cmd += ' --username {0}'.format(settings.DB_USER)
    if settings.DB_PASS:
        cmd += ' --password {0}'.format(settings.DB_PASS)

    ctx.run(cmd, echo=True)

    print()
    print('To restore from the dumped database, run `invoke mongorestore {0}`'.format(
        os.path.join(path, settings.DB_NAME)))

@task
def mongorestore(ctx, path, drop=False):
    """Restores the running OSF database with the contents of the database at
    the location given its argument.

    By default, the contents of the specified database are added to
    the existing database. The `--drop` option will cause the existing database
    to be dropped.

    A caveat: if you `invoke mongodump {path}`, you must restore with
    `invoke mongorestore {path}/{settings.DB_NAME}, as that's where the
    database dump will be stored.
    """
    db = settings.DB_NAME
    port = settings.DB_PORT

    cmd = 'mongorestore --db {db} --port {port}'.format(
        db=db,
        port=port,
        pty=True)

    if settings.DB_USER:
        cmd += ' --username {0}'.format(settings.DB_USER)
    if settings.DB_PASS:
        cmd += ' --password {0}'.format(settings.DB_PASS)

    if drop:
        cmd += ' --drop'

    cmd += ' ' + path
    ctx.run(cmd, echo=True)

@task
def sharejs(ctx, host=None, port=None, db_url=None, cors_allow_origin=None):
    """Start a local ShareJS server."""
    if host:
        os.environ['SHAREJS_SERVER_HOST'] = host
    if port:
        os.environ['SHAREJS_SERVER_PORT'] = port
    if db_url:
        os.environ['SHAREJS_DB_URL'] = db_url
    if cors_allow_origin:
        os.environ['SHAREJS_CORS_ALLOW_ORIGIN'] = cors_allow_origin

    if settings.SENTRY_DSN:
        os.environ['SHAREJS_SENTRY_DSN'] = settings.SENTRY_DSN

    share_server = os.path.join(settings.ADDON_PATH, 'wiki', 'shareServer.js')
    ctx.run('node {0}'.format(share_server))

@task(aliases=['celery'])
def celery_worker(ctx, level='debug', hostname=None, beat=False, queues=None):
    """Run the Celery process."""
    os.environ['DJANGO_SETTINGS_MODULE'] = 'api.base.settings'
    cmd = 'celery worker -A framework.celery_tasks -Ofair -l {0}'.format(level)
    if hostname:
        cmd = cmd + ' --hostname={}'.format(hostname)
    # beat sets up a cron like scheduler, refer to website/settings
    if beat:
        cmd = cmd + ' --beat'
    if queues:
        cmd = cmd + ' --queues={}'.format(queues)
    ctx.run(bin_prefix(cmd), pty=True)

@task(aliases=['beat'])
def celery_beat(ctx, level='debug', schedule=None):
    """Run the Celery process."""
    os.environ['DJANGO_SETTINGS_MODULE'] = 'api.base.settings'
    # beat sets up a cron like scheduler, refer to website/settings
    cmd = 'celery beat -A framework.celery_tasks -l {0} --pidfile='.format(level)
    if schedule:
        cmd = cmd + ' --schedule={}'.format(schedule)
    ctx.run(bin_prefix(cmd), pty=True)

@task
def rabbitmq(ctx):
    """Start a local rabbitmq server.

    NOTE: this is for development only. The production environment should start
    the server as a daemon.
    """
    ctx.run('rabbitmq-server', pty=True)

@task(aliases=['elastic'])
def elasticsearch(ctx):
    """Start a local elasticsearch server

    NOTE: Requires that elasticsearch is installed. See README for instructions
    """
    import platform
    if platform.linux_distribution()[0] == 'Ubuntu':
        ctx.run('sudo service elasticsearch start')
    elif platform.system() == 'Darwin':  # Mac OSX
        ctx.run('elasticsearch')
    else:
        print('Your system is not recognized, you will have to start elasticsearch manually')

@task
def migrate_search(ctx, delete=False, index=settings.ELASTIC_INDEX):
    """Migrate the search-enabled models."""
    from website.app import init_app
    init_app(routes=False, set_backends=False)
    from website.search_migration.migrate import migrate

    # NOTE: Silence the warning:
    # "InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised."
    SILENT_LOGGERS = ['py.warnings']
    for logger in SILENT_LOGGERS:
        logging.getLogger(logger).setLevel(logging.ERROR)

    migrate(delete, index=index)

@task
def rebuild_search(ctx):
    """Delete and recreate the index for elasticsearch"""
    from website.app import init_app
    import requests
    from website import settings

    init_app(routes=False, set_backends=True)
    if not settings.ELASTIC_URI.startswith('http'):
        protocol = 'http://' if settings.DEBUG_MODE else 'https://'
    else:
        protocol = ''
    url = '{protocol}{uri}/{index}'.format(
        protocol=protocol,
        uri=settings.ELASTIC_URI.rstrip('/'),
        index=settings.ELASTIC_INDEX,
    )
    print('Deleting index {}'.format(settings.ELASTIC_INDEX))
    print('----- DELETE {}*'.format(url))
    requests.delete(url + '*')
    print('Creating index {}'.format(settings.ELASTIC_INDEX))
    print('----- PUT {}'.format(url))
    requests.put(url)
    migrate_search(ctx)

@task
def mailserver(ctx, port=1025):
    """Run a SMTP test server."""
    cmd = 'python -m smtpd -n -c DebuggingServer localhost:{port}'.format(port=port)
    ctx.run(bin_prefix(cmd), pty=True)

@task
def jshint(ctx):
    """Run JSHint syntax check"""
    js_folder = os.path.join(HERE, 'website', 'static', 'js')
    jshint_bin = os.path.join(HERE, 'node_modules', '.bin', 'jshint')
    cmd = '{} {}'.format(jshint_bin, js_folder)
    ctx.run(cmd, echo=True)

@task(aliases=['flake8'])
def flake(ctx):
    ctx.run('flake8 .', echo=True)

@task(aliases=['req'])
def requirements(ctx, base=False, addons=False, release=False, dev=False, quick=False):
    """Install python dependencies.

    Examples:
        inv requirements
        inv requirements --quick

    Quick requirements are, in order, addons, dev and the base requirements. You should be able to use --quick for
    day to day development.

    By default, base requirements will run. However, if any set of addons, release, or dev are chosen, base
    will have to be mentioned explicitly in order to run. This is to remain compatible with previous usages. Release
    requirements will prevent dev, and base from running.
    """
    if quick:
        base = True
        addons = True
        dev = True
    if not(addons or dev):
        base = True
    if release or addons:
        addon_requirements(ctx)
    # "release" takes precedence
    if release:
        req_file = os.path.join(HERE, 'requirements', 'release.txt')
        ctx.run(
            pip_install(req_file, constraints_file=CONSTRAINTS_PATH),
            echo=True
        )
    else:
        if dev:  # then dev requirements
            req_file = os.path.join(HERE, 'requirements', 'dev.txt')
            ctx.run(
                pip_install(req_file, constraints_file=CONSTRAINTS_PATH),
                echo=True
            )

        if base:  # then base requirements
            req_file = os.path.join(HERE, 'requirements.txt')
            ctx.run(
                pip_install(req_file, constraints_file=CONSTRAINTS_PATH),
                echo=True
            )
    # fix URITemplate name conflict h/t @github
    ctx.run('pip uninstall uritemplate.py --yes || true')
    ctx.run('pip install --no-cache-dir uritemplate.py==0.3.0')

@task
def test_module(ctx, module=None, numprocesses=None, params=None):
    """Helper for running tests.
    """
    os.environ['DJANGO_SETTINGS_MODULE'] = 'osf_tests.settings'
    import pytest
    if not numprocesses:
        from multiprocessing import cpu_count
        numprocesses = cpu_count()
    # NOTE: Subprocess to compensate for lack of thread safety in the httpretty module.
    # https://github.com/gabrielfalcao/HTTPretty/issues/209#issue-54090252
    args = ['-s']
    if numprocesses > 1:
        args += ['-n {}'.format(numprocesses), '--max-slave-restart=0']
    modules = [module] if isinstance(module, basestring) else module
    args.extend(modules)
    if params:
        params = [params] if isinstance(params, basestring) else params
        args.extend(params)
    retcode = pytest.main(args)
    sys.exit(retcode)

OSF_TESTS = [
    'osf_tests',
]

ELSE_TESTS = [
    'tests',
]

API_TESTS1 = [
    'api_tests/identifiers',
    'api_tests/institutions',
    'api_tests/licenses',
    'api_tests/logs',
    'api_tests/metaschemas',
    'api_tests/preprint_providers',
    'api_tests/preprints',
    'api_tests/registrations',
    'api_tests/users',
]
API_TESTS2 = [
    'api_tests/nodes',
]
API_TESTS3 = [
    'api_tests/addons_tests',
    'api_tests/applications',
    'api_tests/base',
    'api_tests/collections',
    'api_tests/comments',
    'api_tests/files',
    'api_tests/guids',
    'api_tests/search',
    'api_tests/taxonomies',
    'api_tests/test',
    'api_tests/tokens',
    'api_tests/view_only_links',
    'api_tests/wikis',
]
ADDON_TESTS = [
    'addons',
]
ADMIN_TESTS = [
    'admin_tests',
]

@task
def test_osf(ctx, numprocesses=None):
    """Run the OSF test suite."""
    print('Testing modules "{}"'.format(OSF_TESTS + ADDON_TESTS))
    test_module(ctx, module=OSF_TESTS + ADDON_TESTS, numprocesses=numprocesses)

@task
def test_else(ctx, numprocesses=None):
    """Run the old test suite."""
    print('Testing modules "{}"'.format(ELSE_TESTS))
    test_module(ctx, module=ELSE_TESTS, numprocesses=numprocesses)

@task
def test_api1(ctx, numprocesses=None):
    """Run the API test suite."""
    print('Testing modules "{}"'.format(API_TESTS1 + ADMIN_TESTS))
    test_module(ctx, module=API_TESTS1 + ADMIN_TESTS, numprocesses=numprocesses)

@task
def test_api2(ctx, numprocesses=None):
    """Run the API test suite."""
    print('Testing modules "{}"'.format(API_TESTS2))
    test_module(ctx, module=API_TESTS2, numprocesses=numprocesses)

@task
def test_api3(ctx, numprocesses=None):
    """Run the API test suite."""
    print('Testing modules "{}"'.format(API_TESTS3))
    test_module(ctx, module=API_TESTS3, numprocesses=numprocesses)

@task
def test_admin(ctx, numprocesses=None):
    """Run the Admin test suite."""
    print('Testing module "admin_tests"')
    test_module(ctx, module=ADMIN_TESTS, numprocesses=numprocesses)

@task
def test_addons(ctx, numprocesses=None):
    """Run all the tests in the addons directory.
    """
    print('Testing modules "{}"'.format(ADDON_TESTS))
    test_module(ctx, module=ADDON_TESTS, numprocesses=numprocesses)

@task
def test_varnish(ctx):
    """Run the Varnish test suite."""
    proc = apiserver(ctx, wait=False, autoreload=False)
    try:
        sleep(5)
        test_module(ctx, module='api/caching/tests/test_caching.py')
    finally:
        proc.kill()

@task
def test(ctx, all=False, syntax=False):
    """
    Run unit tests: OSF (always), plus addons and syntax checks (optional)
    """
    if syntax:
        flake(ctx)
        jshint(ctx)

    test_osf(ctx)
    test_api1(ctx)
    test_api2(ctx)
    test_api3(ctx)

    if all:
        test_addons(ctx)
        # TODO: Enable admin tests
        test_admin(ctx)
        karma(ctx, single=True, browsers='PhantomJS')

@task
def test_js(ctx):
    jshint(ctx)
    karma(ctx, single=True, browsers='PhantomJS')

@task
def test_travis_osf(ctx, numprocesses=None):
    """
    Run half of the tests to help travis go faster. Lints and Flakes happen everywhere to keep from wasting test time.
    """
    flake(ctx)
    jshint(ctx)
    test_osf(ctx, numprocesses=numprocesses)

@task
def test_travis_else(ctx, numprocesses=None):
    """
    Run other half of the tests to help travis go faster. Lints and Flakes happen everywhere to keep from
    wasting test time.
    """
    flake(ctx)
    jshint(ctx)
    test_else(ctx, numprocesses=numprocesses)

@task
def test_travis_api1(ctx, numprocesses=None):
    flake(ctx)
    jshint(ctx)
    test_api1(ctx, numprocesses=numprocesses)

@task
def test_travis_api2(ctx, numprocesses=None):
    flake(ctx)
    jshint(ctx)
    test_api2(ctx, numprocesses=numprocesses)

@task
def test_travis_api3(ctx, numprocesses=None):
    flake(ctx)
    jshint(ctx)
    test_api3(ctx, numprocesses=numprocesses)

@task
def test_travis_varnish(ctx):
    """
    Run the fast and quirky JS tests and varnish tests in isolation
    """
    flake(ctx)
    jshint(ctx)
    test_js(ctx)
    test_varnish(ctx)

@task
def karma(ctx, single=False, sauce=False, browsers=None):
    """Run JS tests with Karma. Requires PhantomJS to be installed."""
    karma_bin = os.path.join(
        HERE, 'node_modules', 'karma', 'bin', 'karma'
    )
    cmd = '{} start'.format(karma_bin)
    if single:
        cmd += ' --single-run'
    # Use browsers if specified on the command-line, otherwise default
    # what's specified in karma.conf.js
    if browsers:
        cmd += ' --browsers {}'.format(browsers)
    ctx.run(cmd, echo=True)

@task
def wheelhouse(ctx, addons=False, release=False, dev=False, pty=True):
    """Build wheels for python dependencies.

    Examples:

        inv wheelhouse --dev
        inv wheelhouse --addons
        inv wheelhouse --release
    """
    if release or addons:
        for directory in os.listdir(settings.ADDON_PATH):
            path = os.path.join(settings.ADDON_PATH, directory)
            if os.path.isdir(path):
                req_file = os.path.join(path, 'requirements.txt')
                if os.path.exists(req_file):
                    cmd = 'pip wheel --find-links={} -r {} --wheel-dir={} -c {}'.format(
                        WHEELHOUSE_PATH, req_file, WHEELHOUSE_PATH, CONSTRAINTS_PATH,
                    )
                    ctx.run(cmd, pty=pty)
    if release:
        req_file = os.path.join(HERE, 'requirements', 'release.txt')
    elif dev:
        req_file = os.path.join(HERE, 'requirements', 'dev.txt')
    else:
        req_file = os.path.join(HERE, 'requirements.txt')
    cmd = 'pip wheel --find-links={} -r {} --wheel-dir={} -c {}'.format(
        WHEELHOUSE_PATH, req_file, WHEELHOUSE_PATH, CONSTRAINTS_PATH,
    )
    ctx.run(cmd, pty=pty)

@task
def addon_requirements(ctx):
    """Install all addon requirements."""
    for directory in os.listdir(settings.ADDON_PATH):
        path = os.path.join(settings.ADDON_PATH, directory)

        requirements_file = os.path.join(path, 'requirements.txt')
        if os.path.isdir(path) and os.path.isfile(requirements_file):
            print('Installing requirements for {0}'.format(directory))
            ctx.run(
                pip_install(requirements_file, constraints_file=CONSTRAINTS_PATH),
                echo=True
            )

    print('Finished installing addon requirements')

@task
def travis_addon_settings(ctx):
    for directory in os.listdir(settings.ADDON_PATH):
        path = os.path.join(settings.ADDON_PATH, directory, 'settings')
        if os.path.isdir(path):
            try:
                open(os.path.join(path, 'local-travis.py'))
                ctx.run('cp {path}/local-travis.py {path}/local.py'.format(path=path))
            except IOError:
                pass

@task
def copy_addon_settings(ctx):
    for directory in os.listdir(settings.ADDON_PATH):
        path = os.path.join(settings.ADDON_PATH, directory, 'settings')
        if os.path.isdir(path) and not os.path.isfile(os.path.join(path, 'local.py')):
            try:
                open(os.path.join(path, 'local-dist.py'))
                ctx.run('cp {path}/local-dist.py {path}/local.py'.format(path=path))
            except IOError:
                pass

@task
def copy_settings(ctx, addons=False):
    # Website settings
    if not os.path.isfile('website/settings/local.py'):
        print('Creating local.py file')
        ctx.run('cp website/settings/local-dist.py website/settings/local.py')

    # Addon settings
    if addons:
        copy_addon_settings(ctx)

@task
def packages(ctx):
    brew_commands = [
        'update',
        'upgrade',
        'install libxml2',
        'install libxslt',
        'install elasticsearch@1.7',
        'install rabbitmq',
        'install node',
        'tap tokutek/tokumx',
        'install chrisseto/homebrew-tokumx/tokumx-bin',
    ]
    if platform.system() == 'Darwin':
        print('Running brew commands')
        for item in brew_commands:
            command = 'brew {cmd}'.format(cmd=item)
            ctx.run(command)
    elif platform.system() == 'Linux':
        # TODO: Write a script similar to brew bundle for Ubuntu
        # e.g., run('sudo apt-get install [list of packages]')
        pass

@task(aliases=['bower'])
def bower_install(ctx):
    print('Installing bower-managed packages')
    bower_bin = os.path.join(HERE, 'node_modules', 'bower', 'bin', 'bower')
    ctx.run('{} prune --allow-root'.format(bower_bin), echo=True)
    ctx.run('{} install --allow-root'.format(bower_bin), echo=True)

@task
def setup(ctx):
    """Creates local settings, and installs requirements"""
    copy_settings(ctx, addons=True)
    packages(ctx)
    requirements(ctx, addons=True, dev=True)
    # Build nodeCategories.json before building assets
    build_js_config_files(ctx)
    assets(ctx, dev=True, watch=False)

@task
def docker_init(ctx):
    """Initial docker setup"""
    import platform
    print('You will be asked for your sudo password to continue...')
    if platform.system() == 'Darwin':  # Mac OSX
        ctx.run('sudo ifconfig lo0 alias 192.168.168.167')
    else:
        print('Your system is not recognized, you will have to setup docker manually')

def ensure_docker_env_setup(ctx):
    if hasattr(os.environ, 'DOCKER_ENV_SETUP') and os.environ['DOCKER_ENV_SETUP'] == '1':
        pass
    else:
        os.environ['WEB_REMOTE_DEBUG'] = '192.168.168.167:11000'
        os.environ['API_REMOTE_DEBUG'] = '192.168.168.167:12000'
        os.environ['WORKER_REMOTE_DEBUG'] = '192.168.168.167:13000'
        os.environ['DOCKER_ENV_SETUP'] = '1'
        docker_init(ctx)

@task
def docker_requirements(ctx):
    ensure_docker_env_setup(ctx)
    ctx.run('docker-compose up requirements requirements_mfr requirements_wb')

@task
def docker_appservices(ctx):
    ensure_docker_env_setup(ctx)
    ctx.run('docker-compose up assets fakecas elasticsearch tokumx postgres')

@task
def docker_osf(ctx):
    ensure_docker_env_setup(ctx)
    ctx.run('docker-compose up mfr wb web api')

@task
def clear_sessions(ctx, months=1, dry_run=False):
    from website.app import init_app
    init_app(routes=False, set_backends=True)
    from scripts import clear_sessions
    clear_sessions.clear_sessions_relative(months=months, dry_run=dry_run)

# Release tasks

@task
def hotfix(ctx, name, finish=False, push=False):
    """Rename hotfix branch to hotfix/<next-patch-version> and optionally
    finish hotfix.
    """
    print('Checking out master to calculate curent version')
    ctx.run('git checkout master')
    latest_version = latest_tag_info()['current_version']
    print('Current version is: {}'.format(latest_version))
    major, minor, patch = latest_version.split('.')
    next_patch_version = '.'.join([major, minor, str(int(patch) + 1)])
    print('Bumping to next patch version: {}'.format(next_patch_version))
    print('Renaming branch...')

    new_branch_name = 'hotfix/{}'.format(next_patch_version)
    ctx.run('git checkout {}'.format(name), echo=True)
    ctx.run('git branch -m {}'.format(new_branch_name), echo=True)
    if finish:
        ctx.run('git flow hotfix finish {}'.format(next_patch_version), echo=True, pty=True)
    if push:
        ctx.run('git push origin master', echo=True)
        ctx.run('git push --tags', echo=True)
        ctx.run('git push origin develop', echo=True)

@task
def feature(ctx, name, finish=False, push=False):
    """Rename the current branch to a feature branch and optionally finish it."""
    print('Renaming branch...')
    ctx.run('git branch -m feature/{}'.format(name), echo=True)
    if finish:
        ctx.run('git flow feature finish {}'.format(name), echo=True)
    if push:
        ctx.run('git push origin develop', echo=True)

# Adapted from bumpversion
def latest_tag_info():
    try:
        # git-describe doesn't update the git-index, so we do that
        # subprocess.check_output(["git", "update-index", "--refresh"])

        # get info about the latest tag in git
        describe_out = subprocess.check_output([
            'git',
            'describe',
            '--dirty',
            '--tags',
            '--long',
            '--abbrev=40'
        ], stderr=subprocess.STDOUT
        ).decode().split('-')
    except subprocess.CalledProcessError as err:
        raise err
        # logger.warn("Error when running git describe")
        return {}

    info = {}

    if describe_out[-1].strip() == 'dirty':
        info['dirty'] = True
        describe_out.pop()

    info['commit_sha'] = describe_out.pop().lstrip('g')
    info['distance_to_latest_tag'] = int(describe_out.pop())
    info['current_version'] = describe_out.pop().lstrip('v')

    # assert type(info["current_version"]) == str
    assert 0 == len(describe_out)

    return info

# Tasks for generating and bundling SSL certificates
# See http://cosdev.readthedocs.org/en/latest/osf/ops.html for details

@task
def generate_key(ctx, domain, bits=2048):
    cmd = 'openssl genrsa -des3 -out {0}.key {1}'.format(domain, bits)
    ctx.run(cmd)

@task
def generate_key_nopass(ctx, domain):
    cmd = 'openssl rsa -in {domain}.key -out {domain}.key.nopass'.format(
        domain=domain
    )
    ctx.run(cmd)

@task
def generate_csr(ctx, domain):
    cmd = 'openssl req -new -key {domain}.key.nopass -out {domain}.csr'.format(
        domain=domain
    )
    ctx.run(cmd)

@task
def request_ssl_cert(ctx, domain):
    """Generate a key, a key with password removed, and a signing request for
    the specified domain.

    Usage:
    > invoke request_ssl_cert pizza.osf.io
    """
    generate_key(ctx, domain)
    generate_key_nopass(ctx, domain)
    generate_csr(ctx, domain)

@task
def bundle_certs(ctx, domain, cert_path):
    """Concatenate certificates from NameCheap in the correct order. Certificate
    files must be in the same directory.
    """
    cert_files = [
        '{0}.crt'.format(domain),
        'COMODORSADomainValidationSecureServerCA.crt',
        'COMODORSAAddTrustCA.crt',
        'AddTrustExternalCARoot.crt',
    ]
    certs = ' '.join(
        os.path.join(cert_path, cert_file)
        for cert_file in cert_files
    )
    cmd = 'cat {certs} > {domain}.bundle.crt'.format(
        certs=certs,
        domain=domain,
    )
    ctx.run(cmd)

@task
def clean_assets(ctx):
    """Remove built JS files."""
    public_path = os.path.join(HERE, 'website', 'static', 'public')
    js_path = os.path.join(public_path, 'js')
    ctx.run('rm -rf {0}'.format(js_path), echo=True)

@task(aliases=['pack'])
def webpack(ctx, clean=False, watch=False, dev=False, colors=False):
    """Build static assets with webpack."""
    if clean:
        clean_assets(ctx)
    webpack_bin = os.path.join(HERE, 'node_modules', 'webpack', 'bin', 'webpack.js')
    args = [webpack_bin]
    args += ['--progress']
    if watch:
        args += ['--watch']
    if colors:
        args += ['--colors']
    config_file = 'webpack.dev.config.js' if dev else 'webpack.prod.config.js'
    args += ['--config {0}'.format(config_file)]
    command = ' '.join(args)
    ctx.run(command, echo=True)

@task()
def build_js_config_files(ctx):
    from website import settings
    print('Building JS config files...')
    with open(os.path.join(settings.STATIC_FOLDER, 'built', 'nodeCategories.json'), 'wb') as fp:
        json.dump(settings.NODE_CATEGORY_MAP, fp)
    print('...Done.')

@task()
def assets(ctx, dev=False, watch=False, colors=False):
    """Install and build static assets."""
    npm = 'npm install'
    if not dev:
        npm += ' --production'
    ctx.run(npm, echo=True)
    bower_install(ctx)
    build_js_config_files(ctx)
    # Always set clean=False to prevent possible mistakes
    # on prod
    webpack(ctx, clean=False, watch=watch, dev=dev, colors=colors)

@task
def generate_self_signed(ctx, domain):
    """Generate self-signed SSL key and certificate.
    """
    cmd = (
        'openssl req -x509 -nodes -days 365 -newkey rsa:2048'
        ' -keyout {0}.key -out {0}.crt'
    ).format(domain)
    ctx.run(cmd)

@task
def update_citation_styles(ctx):
    from scripts import parse_citation_styles
    total = parse_citation_styles.main()
    print('Parsed {} styles'.format(total))

@task
def clean(ctx, verbose=False):
    ctx.run('find . -name "*.pyc" -delete', echo=True)

@task(default=True)
def usage(ctx):
    ctx.run('invoke --list')

### Maintenance Tasks ###

@task
def set_maintenance(ctx, message='', level=1, start=None, end=None):
    from website.app import setup_django
    setup_django()
    from website.maintenance import set_maintenance
    """Creates a maintenance notice.

    Message is required.
    Level defaults to 1. Valid levels are 1 (info), 2 (warning), and 3 (danger).

    Set the time period for the maintenance notice to be displayed.
    If no start or end values are displayed, default to starting now
    and ending 24 hours from now. If no timezone info is passed along,
    everything will be converted to UTC.

    If a given end time results in a start that is after the end, start
    will be changed to be 24 hours before the end time.

    Examples:
        invoke set_maintenance --message 'OSF down for scheduled maintenance.' --start 2016-03-16T15:41:00-04:00
        invoke set_maintenance --message 'Apocalypse' --level 3 --end 2016-03-16T15:41:00-04:00
    """
    state = set_maintenance(message, level, start, end)
    print('Maintenance notice up {} to {}.'.format(state['start'], state['end']))

@task
def unset_maintenance(ctx):
    from website.app import setup_django
    setup_django()
    from website.maintenance import unset_maintenance
    print('Taking down maintenance notice...')
    unset_maintenance()
    print('...Done.')


text:
'''
This module helps include encrypted passwords in pillars, grains and salt state files.

:depends: libnacl, https://github.com/saltstack/libnacl

This is often useful if you wish to store your pillars in source control or
share your pillar data with others that you trust. I don't advise making your pillars public
regardless if they are encrypted or not.

When generating keys and encrypting passwords use --local when using salt-call for extra
security. Also consider using just the salt runner nacl when encrypting pillar passwords.

The nacl lib uses 32byte keys, these keys are base64 encoded to make your life more simple.
To generate your `key` or `keyfile` you can use:

.. code-block:: bash

    salt-call --local nacl.keygen keyfile=/root/.nacl

Now with your key, you can encrypt some data:

.. code-block:: bash

    salt-call --local nacl.enc mypass keyfile=/root/.nacl
    DRB7Q6/X5gGSRCTpZyxS6hXO5LnlJIIJ4ivbmUlbWj0llUA+uaVyvou3vJ4=

To decrypt the data:

.. code-block:: bash

    salt-call --local nacl.dec data='DRB7Q6/X5gGSRCTpZyxS6hXO5LnlJIIJ4ivbmUlbWj0llUA+uaVyvou3vJ4=' keyfile=/root/.nacl
    mypass

The following optional configurations can be defined in the
minion or master config. Avoid storing the config in pillars!

.. code-block:: yaml

    cat /etc/salt/master.d/nacl.conf
    nacl.config:
        key: None
        keyfile: /root/.nacl

When the key is defined in the master config you can use it from the nacl runner:

.. code-block:: bash

    salt-run nacl.enc 'myotherpass'

Now you can create a pillar with protected data like:

.. code-block:: yaml

    pillarexample:
        user: root
        password: {{ salt.nacl.dec('DRB7Q6/X5gGSRCTpZyxS6hXO5LnlJIIJ4ivbmUlbWj0llUA+uaVyvou3vJ4=') }}

Or do something interesting with grains like:

.. code-block:: yaml

    salt-call nacl.enc minionname:dbrole
    AL24Z2C5OlkReer3DuQTFdrNLchLuz3NGIhGjZkLtKRYry/b/CksWM8O9yskLwH2AGVLoEXI5jAa

    salt minionname grains.setval role 'AL24Z2C5OlkReer3DuQTFdrNLchLuz3NGIhGjZkLtKRYry/b/CksWM8O9yskLwH2AGVLoEXI5jAa'

    {%- set r = grains.get('role') %}
    {%- set role = None %}
    {%- if r and 'nacl.dec' in salt %}
        {%- set r = salt['nacl.dec'](r,keyfile='/root/.nacl').split(':') %}
        {%- if opts['id'] == r[0] %}
            {%- set role = r[1] %}
        {%- endif %}
    {%- endif %}
    base:
        {%- if role %}
        '{{ opts['id'] }}':
            - {{ role }}
        {%- endif %}
'''

from __future__ import absolute_import
import base64
import os
import salt.utils
import salt.syspaths

REQ_ERROR = None
try:
    import libnacl.secret
except (ImportError, OSError) as e:
    REQ_ERROR = 'libnacl import error, perhaps missing python libnacl package'

__virtualname__ = 'nacl'

def __virtual__():
    return (REQ_ERROR is None, REQ_ERROR)

def _get_config(**kwargs):
    '''
    Return configuration
    '''
    config = {
        'key': None,
        'keyfile': None,
    }
    config_key = '{0}.config'.format(__virtualname__)
    config.update(__salt__['config.get'](config_key, {}))
    for k in set(config.keys()) & set(kwargs.keys()):
        config[k] = kwargs[k]
    return config

def _get_key(rstrip_newline=True, **kwargs):
    '''
    Return key
    '''
    config = _get_config(**kwargs)
    key = config['key']
    keyfile = config['keyfile']
    if not key and keyfile:
        if not os.path.isfile(keyfile):
            raise Exception('file not found: {0}'.format(keyfile))
        with salt.utils.fopen(keyfile, 'rb') as keyf:
            key = keyf.read()
    if key is None:
        raise Exception('no key found')
    key = str(key)
    if rstrip_newline:
        key = key.rstrip('\n')
    return key

def keygen(keyfile=None):
    '''
    Use libnacl to generate a private key

    CLI Examples:

    .. code-block:: bash

        salt-call --local nacl.keygen
        salt-call --local nacl.keygen keyfile=/root/.nacl
        salt-call --local --out=newline_values_only nacl.keygen > /root/.nacl
    '''
    b = libnacl.secret.SecretBox()
    key = b.sk
    key = base64.b64encode(key)
    if keyfile:
        if os.path.isfile(keyfile):
            raise Exception('file already found: {0}'.format(keyfile))
        with salt.utils.fopen(keyfile, 'w') as keyf:
            keyf.write(key)
            return 'saved: {0}'.format(keyfile)
    return key

def enc(data, **kwargs):
    '''
    Takes a key generated from `nacl.keygen` and encrypt some data.

    CLI Examples:

    .. code-block:: bash

        salt-call --local nacl.enc datatoenc
        salt-call --local nacl.enc datatoenc keyfile=/root/.nacl
        salt-call --local nacl.enc datatoenc key='cKEzd4kXsbeCE7/nLTIqXwnUiD1ulg4NoeeYcCFpd9k='
    '''
    key = _get_key(**kwargs)
    sk = base64.b64decode(key)
    b = libnacl.secret.SecretBox(sk)
    return base64.b64encode(b.encrypt(data))

def dec(data, **kwargs):
    '''
    Takes a key generated from `nacl.keygen` and decrypt some data.

    CLI Examples:

    .. code-block:: bash

        salt-call --local nacl.dec pEXHQM6cuaF7A=
        salt-call --local nacl.dec data='pEXHQM6cuaF7A=' keyfile=/root/.nacl
        salt-call --local nacl.dec data='pEXHQM6cuaF7A=' key='cKEzd4kXsbeCE7/nLTIqXwnUiD1ulg4NoeeYcCFpd9k='
    '''
    key = _get_key(**kwargs)
    sk = base64.b64decode(key)
    b = libnacl.secret.SecretBox(key=sk)
    return b.decrypt(base64.b64decode(data))


text:
Brandito JS
==========

Brandito JS is a simple layout for displaying colour guides. Nothing complex.

Simply download, modify the `brandito.json` file and view.

---

Looks kinda like this:

![alt text](https://raw.githubusercontent.com/jimhill/branditojs/master/example.png "Example")

---

Enjoy :)


text:
import { DicitState, fetchRandomQuote } from '@libs/fetchQuotes';

describe('@libs: fetchRandomQuote', (): void => {
  it('will return certain contents', (): void => {
    const { quote, stats }: DicitState = fetchRandomQuote();
    expect(quote).toHaveProperty('sentence');
    expect(quote).toHaveProperty('author');
    expect(stats).toMatchObject({ consumed: 1, whole: expect.any(Number) });
  });
});


text:
package org.apache.servicecomb.it.testcase;

import static org.assertj.core.api.Assertions.assertThat;

import java.util.List;

import org.apache.servicecomb.foundation.common.utils.BeanUtils;
import org.junit.Test;
import org.springframework.core.env.Environment;

public class TestSpringConfiguration {
  @Test
  public void should_resolve_placeholder_in_list_by_spring_environment() {
    Environment environment = BeanUtils.getContext().getEnvironment();

    String value = environment.getProperty("placeholder");
    assertThat(value).isEqualTo("actual-value1,actual-value2");

    @SuppressWarnings("unchecked")
    List<String> list = environment.getProperty("placeholder", List.class);
    assertThat(list).containsExactly("actual-value1", "actual-value2");
  }
}


text:
title: "From N-Rays to Cold Fusion to NASA's EMDrive: A Tour of Pathological Science"
speaker: "Prof. Brian Watson (St. Lawrence University)"
speaker_url: "https://www.stlawu.edu/people/brian-watson"
event-date: 2017-02-02 19:00
image:
    title: watson_nrays.jpg
    thumb: thumb_watson_nrays.jpg
type: lecture
tags:
  - ethics
  - pathological science
---
*Abstract:*

Irving Langmuir coined the term "pathological science" to describe the science of things that are not so.  Being distinct from scientific hoaxes (Piltdown Man), deliberate fraud (Benveniste's water memory experiments), or simple error (superluminal neutrinos), Langmuir described the case where reputable scientists, by lapses in judgment and experimenter bias, convince themselves that they have discovered a new phenomenon, which is, in fact, spurious.  Other scientists replicate the experiments and often they also find the new effect, or think they have.  In this talk I will describe some of the most famous cases of pathological science.  Starting with the well-known case of Blondlot's N-Rays, I'll discuss cold fusion, facilitated communication, and the latest candidate, NASA's EMDrive, which purports to deliver a thrust without an exchange of momentum.


text:
import {
  test,
  moduleForComponent
} from 'ember-qunit';
import Ember from 'ember';
import {initialize} from 'ember-form-master-2000/initializers/fm-initialize';

moduleForComponent('fm-radio-group', {
  needs: ['component:fm-radio',
          'component:fm-errortext',
          'template:components/ember-form-master-2000/fm-radio',
          'template:components/ember-form-master-2000/fm-errortext',
          'template:components/ember-form-master-2000/fm-radio-group'],
  setup: function() {
    this.container.inject = this.container.injection;
    initialize(null, this.container);
  }
});

test('renders properly', function(assert) {
  var component = this.subject();
  this.render();
  assert.ok(component.$().hasClass('form-group'), 'fm-radio-group has the form-group class');
});

test('renders radio buttons for each content item provided', function(assert) {
  var component = this.subject();
  component.set('optionLabelPath', 'content.label');
  component.set('optionValuePath', 'content.value');
  component.set('content', Ember.A([{label: 'label', value: 'value'}, {label: 'two', value: 'two'}]));
  this.render();
  assert.equal(component.$('.radio').length, 2, 'fm-radio-group rendered two radio buttons');
});


text:
copyright:
  years: 2014, 2017
lastupdated: "2017-02-10"

---
{:new_window: target="_blank"}
{:shortdesc: .shortdesc}

# {{site.data.keyword.objectstorageshort}} Pubblico Bluemix

{{site.data.keyword.objectstorageshort}} Pubblico, basato su Swift, fornisce una piattaforma di archiviazione accessibile con API con provisioning completo, per gestire i tuoi dati. Puoi utilizzarlo direttamente nelle tue applicazioni oppure per i backup, rendendolo ideale per un'archiviazione con un buon rapporto costo/efficacia e con scaling incrementale.
{: shortdesc}

Per iniziare ad utilizzare Object Storage, completa le seguenti attività:

1. Autentica la tua istanza del servizio con [Keystone](/docs/services/ObjectStorage/os_authenticate.html).
2. Genera le [credenziali](/docs/services/ObjectStorage/os_credentials.html) per il tuo servizio.
3. Configura il [client Swift](/docs/services/ObjectStorage/os_configuring.html) e il rimanente software prerequisito.
4. Crea un URL [temporaneo](/docs/services/ObjectStorage/os_tempurl.html) o [permanente](/docs/services/ObjectStorage/os_constructing.html).

Ora, sei pronto a gestire gli [oggetti](/docs/services/ObjectStorage/os_managing.html) e ad [accedere](/docs/services/ObjectStorage/os_security.html).

Per ulteriori informazioni su come funziona il servizio, consulta [Informazioni su Object Storage](/docs/services/ObjectStorage/objectstorage_overview.html).


text:
using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace DataBaseOperator
{
    static class Program
    {

    }
}


text:
from django.contrib import admin

from . models import Location, DeviceType, Device, Parameter, Value

@admin.register(Location)
class LocationAdmin(admin.ModelAdmin):
    list_display = ('name', )
    search_fields = ('name', )

@admin.register(DeviceType)
class DeviceType(admin.ModelAdmin):
    list_display = ('name', )
    search_fields = ('name', )

@admin.register(Device)
class DeviceAdmin(admin.ModelAdmin):
    list_display = ('name', 'location', 'device_type')
    search_fields = ('name', )
    list_filter = ('device_type', 'location',)

@admin.register(Parameter)
class ParameterAdmin(admin.ModelAdmin):
    list_display = ('name', 'device_type', 'format', 'default_value')
    search_fields = ('name', )
    list_filter = ('device_type', )

@admin.register(Value)
class ValueAdmin(admin.ModelAdmin):
    list_display = ('device', 'parameter', 'value', 'applied')
    search_fields = ('name', )
    list_filter = ('applied', )