text:
package customresourcedefinition

import (
	"context"
	"fmt"

	"k8s.io/apiextensions-apiserver/pkg/apihelpers"
	"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions"
	"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1"
	"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation"
	apiextensionsfeatures "k8s.io/apiextensions-apiserver/pkg/features"
	apiequality "k8s.io/apimachinery/pkg/api/equality"
	"k8s.io/apimachinery/pkg/fields"
	"k8s.io/apimachinery/pkg/labels"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/util/validation/field"
	"k8s.io/apiserver/pkg/endpoints/request"
	"k8s.io/apiserver/pkg/registry/generic"
	"k8s.io/apiserver/pkg/storage"
	"k8s.io/apiserver/pkg/storage/names"
	utilfeature "k8s.io/apiserver/pkg/util/feature"
)

// strategy implements behavior for CustomResources.
type strategy struct {
	runtime.ObjectTyper
	names.NameGenerator
}

func NewStrategy(typer runtime.ObjectTyper) strategy {
	return strategy{typer, names.SimpleNameGenerator}
}

func (strategy) NamespaceScoped() bool {
	return false
}

// PrepareForCreate clears the status of a CustomResourceDefinition before creation.
func (strategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {
	crd := obj.(*apiextensions.CustomResourceDefinition)
	crd.Status = apiextensions.CustomResourceDefinitionStatus{}
	crd.Generation = 1

	dropDisabledFields(&crd.Spec, nil)

	for _, v := range crd.Spec.Versions {
		if v.Storage {
			if !apiextensions.IsStoredVersion(crd, v.Name) {
				crd.Status.StoredVersions = append(crd.Status.StoredVersions, v.Name)
			}
			break
		}
	}
}

// PrepareForUpdate clears fields that are not allowed to be set by end users on update.
func (strategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {
	newCRD := obj.(*apiextensions.CustomResourceDefinition)
	oldCRD := old.(*apiextensions.CustomResourceDefinition)
	newCRD.Status = oldCRD.Status

	// Any changes to the spec increment the generation number, any changes to the
	// status should reflect the generation number of the corresponding object. We push
	// the burden of managing the status onto the clients because we can't (in general)
	// know here what version of spec the writer of the status has seen. It may seem like
	// we can at first -- since obj contains spec -- but in the future we will probably make
	// status its own object, and even if we don't, writes may be the result of a
	// read-update-write loop, so the contents of spec may not actually be the spec that
	// the controller has *seen*.
	if !apiequality.Semantic.DeepEqual(oldCRD.Spec, newCRD.Spec) {
		newCRD.Generation = oldCRD.Generation + 1
	}

	dropDisabledFields(&newCRD.Spec, &oldCRD.Spec)

	for _, v := range newCRD.Spec.Versions {
		if v.Storage {
			if !apiextensions.IsStoredVersion(newCRD, v.Name) {
				newCRD.Status.StoredVersions = append(newCRD.Status.StoredVersions, v.Name)
			}
			break
		}
	}
}

// Validate validates a new CustomResourceDefinition.
func (strategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {
	fieldErrors := validation.ValidateCustomResourceDefinition(obj.(*apiextensions.CustomResourceDefinition))
	return append(fieldErrors, validateAPIApproval(ctx, obj.(*apiextensions.CustomResourceDefinition), nil)...)
}

// AllowCreateOnUpdate is false for CustomResourceDefinition; this means a POST is
// needed to create one.
func (strategy) AllowCreateOnUpdate() bool {
	return false
}

// AllowUnconditionalUpdate is the default update policy for CustomResourceDefinition objects.
func (strategy) AllowUnconditionalUpdate() bool {
	return false
}

// Canonicalize normalizes the object after validation.
func (strategy) Canonicalize(obj runtime.Object) {
}

// ValidateUpdate is the default update validation for an end user updating status.
func (strategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {
	fieldErrors := validation.ValidateCustomResourceDefinitionUpdate(obj.(*apiextensions.CustomResourceDefinition), old.(*apiextensions.CustomResourceDefinition))

	return append(fieldErrors, validateAPIApproval(ctx, obj.(*apiextensions.CustomResourceDefinition), old.(*apiextensions.CustomResourceDefinition))...)
}

// validateAPIApproval returns a list of errors if the API approval annotation isn't valid
func validateAPIApproval(ctx context.Context, newCRD, oldCRD *apiextensions.CustomResourceDefinition) field.ErrorList {
	// check to see if we need confirm API approval for kube group.  Do nothing for non-protected groups and do nothing in v1beta1.
	if requestInfo, ok := request.RequestInfoFrom(ctx); !ok || requestInfo.APIVersion == "v1beta1" {
		return field.ErrorList{}
	}
	if !apihelpers.IsProtectedCommunityGroup(newCRD.Spec.Group) {
		return field.ErrorList{}
	}

	// default to a state that allows missing values to continue to be missing
	var oldApprovalState *apihelpers.APIApprovalState
	if oldCRD != nil {
		t, _ := apihelpers.GetAPIApprovalState(oldCRD.Annotations)
		oldApprovalState = &t
	}
	newApprovalState, reason := apihelpers.GetAPIApprovalState(newCRD.Annotations)

	// if the approval state hasn't changed, never fail on approval validation
	// this is allowed so that a v1 client that is simply updating spec and not mutating this value doesn't get rejected.  Imagine a controller controlling a CRD spec.
	if oldApprovalState != nil && *oldApprovalState == newApprovalState {
		return field.ErrorList{}
	}

	// in v1, we require valid approval strings
	switch newApprovalState {
	case apihelpers.APIApprovalInvalid:
		return field.ErrorList{field.Invalid(field.NewPath("metadata", "annotations").Key(v1beta1.KubeAPIApprovedAnnotation), newCRD.Annotations[v1beta1.KubeAPIApprovedAnnotation], reason)}
	case apihelpers.APIApprovalMissing:
		return field.ErrorList{field.Required(field.NewPath("metadata", "annotations").Key(v1beta1.KubeAPIApprovedAnnotation), reason)}
	case apihelpers.APIApproved, apihelpers.APIApprovalBypassed:
		// success
		return field.ErrorList{}
	default:
		return field.ErrorList{field.Invalid(field.NewPath("metadata", "annotations").Key(v1beta1.KubeAPIApprovedAnnotation), newCRD.Annotations[v1beta1.KubeAPIApprovedAnnotation], reason)}
	}
}

type statusStrategy struct {
	runtime.ObjectTyper
	names.NameGenerator
}

func NewStatusStrategy(typer runtime.ObjectTyper) statusStrategy {
	return statusStrategy{typer, names.SimpleNameGenerator}
}

func (statusStrategy) NamespaceScoped() bool {
	return false
}

func (statusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {
	newObj := obj.(*apiextensions.CustomResourceDefinition)
	oldObj := old.(*apiextensions.CustomResourceDefinition)
	newObj.Spec = oldObj.Spec

	// Status updates are for only for updating status, not objectmeta.
	// TODO: Update after ResetObjectMetaForStatus is added to meta/v1.
	newObj.Labels = oldObj.Labels
	newObj.Annotations = oldObj.Annotations
	newObj.OwnerReferences = oldObj.OwnerReferences
	newObj.Generation = oldObj.Generation
	newObj.SelfLink = oldObj.SelfLink
}

func (statusStrategy) AllowCreateOnUpdate() bool {
	return false
}

func (statusStrategy) AllowUnconditionalUpdate() bool {
	return false
}

func (statusStrategy) Canonicalize(obj runtime.Object) {
}

func (statusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {
	return validation.ValidateUpdateCustomResourceDefinitionStatus(obj.(*apiextensions.CustomResourceDefinition), old.(*apiextensions.CustomResourceDefinition))
}

// GetAttrs returns labels and fields of a given object for filtering purposes.
func GetAttrs(obj runtime.Object) (labels.Set, fields.Set, error) {
	apiserver, ok := obj.(*apiextensions.CustomResourceDefinition)
	if !ok {
		return nil, nil, fmt.Errorf("given object is not a CustomResourceDefinition")
	}
	return labels.Set(apiserver.ObjectMeta.Labels), CustomResourceDefinitionToSelectableFields(apiserver), nil
}

// MatchCustomResourceDefinition is the filter used by the generic etcd backend to watch events
// from etcd to clients of the apiserver only interested in specific labels/fields.
func MatchCustomResourceDefinition(label labels.Selector, field fields.Selector) storage.SelectionPredicate {
	return storage.SelectionPredicate{
		Label:    label,
		Field:    field,
		GetAttrs: GetAttrs,
	}
}

// CustomResourceDefinitionToSelectableFields returns a field set that represents the object.
func CustomResourceDefinitionToSelectableFields(obj *apiextensions.CustomResourceDefinition) fields.Set {
	return generic.ObjectMetaFieldsSet(&obj.ObjectMeta, true)
}

func dropDisabledFields(crdSpec, oldCrdSpec *apiextensions.CustomResourceDefinitionSpec) {
	// if the feature gate is disabled, drop the feature.
	if !utilfeature.DefaultFeatureGate.Enabled(apiextensionsfeatures.CustomResourceValidation) &&
		!validationInUse(oldCrdSpec) {
		crdSpec.Validation = nil
		for i := range crdSpec.Versions {
			crdSpec.Versions[i].Schema = nil
		}
	}
	if !utilfeature.DefaultFeatureGate.Enabled(apiextensionsfeatures.CustomResourceSubresources) &&
		!subresourceInUse(oldCrdSpec) {
		crdSpec.Subresources = nil
		for i := range crdSpec.Versions {
			crdSpec.Versions[i].Subresources = nil
		}
	}

	// 1. On CREATE (in which case the old CRD spec is nil), if the CustomResourceWebhookConversion feature gate is off, we auto-clear
	// the per-version fields. This is to be consistent with the other built-in types, as the
	// apiserver drops unknown fields.
	// 2. On UPDATE, if the CustomResourceWebhookConversion feature gate is off, we auto-clear
	// the per-version fields if the old CRD doesn't use per-version fields already.
	// This is to be consistent with the other built-in types, as the apiserver drops unknown
	// fields. If the old CRD already uses per-version fields, the CRD is allowed to continue
	// use per-version fields.
	if !utilfeature.DefaultFeatureGate.Enabled(apiextensionsfeatures.CustomResourceWebhookConversion) &&
		!hasPerVersionField(oldCrdSpec) {
		for i := range crdSpec.Versions {
			crdSpec.Versions[i].Schema = nil
			crdSpec.Versions[i].Subresources = nil
			crdSpec.Versions[i].AdditionalPrinterColumns = nil
		}
	}

	if !utilfeature.DefaultFeatureGate.Enabled(apiextensionsfeatures.CustomResourceWebhookConversion) &&
		!conversionWebhookInUse(oldCrdSpec) {
		if crdSpec.Conversion != nil {
			crdSpec.Conversion.WebhookClientConfig = nil
		}
	}

}

func validationInUse(crdSpec *apiextensions.CustomResourceDefinitionSpec) bool {
	if crdSpec == nil {
		return false
	}
	if crdSpec.Validation != nil {
		return true
	}

	for i := range crdSpec.Versions {
		if crdSpec.Versions[i].Schema != nil {
			return true
		}
	}
	return false
}

func subresourceInUse(crdSpec *apiextensions.CustomResourceDefinitionSpec) bool {
	if crdSpec == nil {
		return false
	}
	if crdSpec.Subresources != nil {
		return true
	}

	for i := range crdSpec.Versions {
		if crdSpec.Versions[i].Subresources != nil {
			return true
		}
	}
	return false
}

// hasPerVersionField returns true if a CRD uses per-version schema/subresources/columns fields.
//func hasPerVersionField(versions []apiextensions.CustomResourceDefinitionVersion) bool {
func hasPerVersionField(crdSpec *apiextensions.CustomResourceDefinitionSpec) bool {
	if crdSpec == nil {
		return false
	}
	for _, v := range crdSpec.Versions {
		if v.Schema != nil || v.Subresources != nil || len(v.AdditionalPrinterColumns) > 0 {
			return true
		}
	}
	return false
}

func conversionWebhookInUse(crdSpec *apiextensions.CustomResourceDefinitionSpec) bool {
	if crdSpec == nil {
		return false
	}
	if crdSpec.Conversion == nil {
		return false
	}
	return crdSpec.Conversion.WebhookClientConfig != nil
}


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

import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import java.util.Arrays;
import java.util.List;

import static com.google.common.collect.Lists.cartesianProduct;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;

public class TestTopNPeerGroupLookup
{
    private static final RowIdHashStrategy HASH_STRATEGY = new RowIdHashStrategy()
    {
        @Override
        public boolean equals(long leftRowId, long rightRowId)
        {
            return leftRowId == rightRowId;
        }

        @Override
        public long hashCode(long rowId)
        {
            return rowId;
        }
    };
    private static final long UNMAPPED_GROUP_ID = Long.MIN_VALUE;
    private static final long DEFAULT_RETURN_VALUE = -1L;

    @DataProvider
    public static Object[][] parameters()
    {
        List<Integer> expectedSizes = Arrays.asList(0, 1, 2, 3, 1_000);
        List<Float> fillFactors = Arrays.asList(0.1f, 0.9f, 1f);
        List<Long> totalGroupIds = Arrays.asList(1L, 10L);
        List<Long> totalRowIds = Arrays.asList(1L, 1_000L);

        return to2DArray(cartesianProduct(expectedSizes, fillFactors, totalGroupIds, totalRowIds));
    }

    private static Object[][] to2DArray(List<List<Object>> nestedList)
    {
        Object[][] array = new Object[nestedList.size()][];
        for (int i = 0; i < nestedList.size(); i++) {
            array[i] = nestedList.get(i).toArray();
        }
        return array;
    }

    @Test(dataProvider = "parameters")
    public void testCombinations(int expectedSize, float fillFactor, long totalGroupIds, long totalRowIds)
    {
        TopNPeerGroupLookup lookup = new TopNPeerGroupLookup(expectedSize, fillFactor, HASH_STRATEGY, UNMAPPED_GROUP_ID, DEFAULT_RETURN_VALUE);

        assertEquals(lookup.size(), 0);
        assertTrue(lookup.isEmpty());

        // Put values
        int count = 0;
        for (int groupId = 0; groupId < totalGroupIds; groupId++) {
            for (int rowId = 0; rowId < totalRowIds; rowId++) {
                // Value should not exist yet
                assertEquals(lookup.get(groupId, rowId), DEFAULT_RETURN_VALUE);
                assertEquals(lookup.get(groupId, toRowReference(rowId)), DEFAULT_RETURN_VALUE);
                assertEquals(lookup.remove(groupId, rowId), DEFAULT_RETURN_VALUE);

                // Insert the value
                assertEquals(lookup.put(groupId, rowId, count), DEFAULT_RETURN_VALUE);

                count++;

                assertFalse(lookup.isEmpty());
                assertEquals(lookup.size(), count);
            }
        }

        // Get values
        count = 0;
        long totalEntries = totalGroupIds * totalRowIds;
        for (int groupId = 0; groupId < totalGroupIds; groupId++) {
            for (int rowId = 0; rowId < totalRowIds; rowId++) {
                assertEquals(lookup.get(groupId, rowId), count);
                assertEquals(lookup.get(groupId, toRowReference(rowId)), count);
                count++;

                assertFalse(lookup.isEmpty());
                assertEquals(lookup.size(), totalEntries);
            }
        }

        // Overwrite values
        count = 0;
        for (int groupId = 0; groupId < totalGroupIds; groupId++) {
            for (int rowId = 0; rowId < totalRowIds; rowId++) {
                assertEquals(lookup.put(groupId, rowId, count + 1), count);
                count++;

                assertFalse(lookup.isEmpty());
                assertEquals(lookup.size(), totalEntries);
            }
        }

        // Remove values
        count = 0;
        for (int groupId = 0; groupId < totalGroupIds; groupId++) {
            for (int rowId = 0; rowId < totalRowIds; rowId++) {
                assertFalse(lookup.isEmpty());
                assertEquals(lookup.size(), totalEntries - count);

                // Removed value should be the overwritten value
                assertEquals(lookup.remove(groupId, rowId), count + 1);
                count++;
            }
        }
        assertTrue(lookup.isEmpty());
        assertEquals(lookup.size(), 0);
    }

    private static RowReference toRowReference(long rowId)
    {
        return new RowReference()
        {
            @Override
            public int compareTo(RowIdComparisonStrategy strategy, long otherRowId)
            {
                return strategy.compare(rowId, otherRowId);
            }

            @Override
            public boolean equals(RowIdHashStrategy strategy, long otherRowId)
            {
                return strategy.equals(rowId, otherRowId);
            }

            @Override
            public long hash(RowIdHashStrategy strategy)
            {
                return strategy.hashCode(rowId);
            }

            @Override
            public long allocateRowId()
            {
                return rowId;
            }
        };
    }
}

redpajama_set_name: RedPajamaGithub


text:
/* tslint:disable:no-unused-variable */

import { TestBed, async } from '@angular/core/testing';
import { DashboardComponent } from './dashboard.component';

describe('Component: Dashboard', () => {
  it('should create an instance', () => {
    const component = new DashboardComponent();
    expect(component).toBeTruthy();
  });
});


text:
set(CMAKE_DEPENDS_LANGUAGES
  "C"
  )
# The set of files for implicit dependencies of each language:
set(CMAKE_DEPENDS_CHECK_C
  "/Users/Ye-Macbook/Documents/Development/raytracer/shared/glfw-3.1.1/tests/cursoranim.c" "/Users/Ye-Macbook/Documents/Development/raytracer/shared/glfw-3.1.1/build/tests/CMakeFiles/cursoranim.dir/cursoranim.c.o"
  )
set(CMAKE_C_COMPILER_ID "Clang")

# The include file search paths:
set(CMAKE_C_TARGET_INCLUDE_PATH
  "../include"
  "../deps"
  )

# Targets to which this target links.
set(CMAKE_TARGET_LINKED_INFO_FILES
  "/Users/Ye-Macbook/Documents/Development/raytracer/shared/glfw-3.1.1/build/src/CMakeFiles/glfw.dir/DependInfo.cmake"
  )

# Fortran module output directory.
set(CMAKE_Fortran_TARGET_MODULE_DIR "")


text:
@echo off
REM --------------------------
set BatchVersion=1.4
REM --------------------------
set Elevated=%1
echo This will Delete VSTOInstaller.exe.Config [batch Version %BatchVersion%]
echo .

set BadConfigFile="%ProgramFiles%\Common Files\Microsoft Shared\VSTO\10.0\VSTOInstaller.exe.config"
call :Delete

REM - we have also an second location - test it
if DEFINED ProgramFiles(x86) (
	set BadConfigFile="%ProgramFiles(x86)%\Common Files\Microsoft Shared\VSTO\10.0\VSTOInstaller.exe.config"
	call :Delete
	)

:end
pause
goto :eof

:Delete
if exist %BadConfigFile% (
	REM - The file exist - we have to delete it
	REM del /Q /F %BadConfigFile%
	del /Q %BadConfigFile%
	if exist %BadConfigFile% (
		echo .
		echo Deleting the file was not successful.
		echo Please verify you have admin rights and UAC is enabled.
		echo .
		echo Right click on the batch file and select 'Run as administrator'
		call :TryToElevate
	) else (
		echo File %BadConfigFile% was successful deleted.
		echo Please try to reinstall the plugin.
	)
) else (
    REM - The file doesn't exist
	echo The file %BadConfigFile% was not found.
)
echo .
echo Closing .bat
goto :eof

:TryToElevate
if NOT [%ELEVATED%]==[] (
	echo Match
	goto :eof
	)
echo -----------------------
echo Try to start as administrator
echo -----------------------
set Elevated=TRYED
echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
echo UAC.ShellExecute "%~s0", "ELEVATED", "", "runas", 1 >> "%temp%\getadmin.vbs"
"%temp%\getadmin.vbs"
goto :eof


text:
'use strict';
var url = require('url');
var Promise = require('bluebird');

var route = {
	handlers: {}
	, add: function(route) {
		var pathname = route.pathname;
		if (!this.handlers[route.pathname]) {
			this.handlers[route.pathname] = {};
		}
		if (route.pathname instanceof RegExp) {
			pathname = route.pathname.toString();
			this.handlers[pathname].regExp = route.pathname;
		}
		this.handlers[pathname][route.method] = route.handler;
	}
	, dispatch: function(req, res) {
		var requestedPathname = url.parse(req.url, true).pathname;
		var route = this.handlers[requestedPathname];

		// Static routes
		if(route && route[req.method]) {
			console.log('route handler found');
			return route[req.method](req, res);
		}

		// RegExp routes
		for (let r in this.handlers) {
			if (!this.handlers[r].regExp) {
				continue;
			}
			let routeRegExp = this.handlers[r].regExp;
			let matches = routeRegExp.exec(requestedPathname);
			if (matches
			&& this.handlers[r][req.method]
			) {
				console.log(matches);
				return this.handlers[r][req.method](req, res);
			}
		}

		console.log('Reqested route not found');
		return Promise.reject(new Error('Route not found'));
	}
};

require('./default')(route);
module.exports = route;


text:
require 'prawn-svg'

module Certificator
  # Converts an SVG to PDF using the Prawn library
  class PrawnConverter
    def initialize(font_paths = [])
      @font_paths = font_paths
    end

    def convert_to_pdf(svg_data)
      print_flow_warning if svg_data =~ /flowRoot/

      pdf_file = Tempfile.new('temporary.pdf')
      generate_pdf(svg_data, pdf_file)

      pdf = pdf_file.read
      pdf_file.unlink
      pdf
    end

    private

    def print_flow_warning
      puts <<-FLOW_WARNING
  Your SVG model contains flowRoot elements which are not SVG 1.1
  compatible.\nThose elements won't be rendered and they usually are used for
  text.\nIf you generated it with Inkscape, please edit your SVG and ensure all
  text elements are converted to text tags by using the 'Text->Convert to Text'
  menu.
      FLOW_WARNING
    end

    def generate_pdf(svg_data, pdf_file)
      options = {
        margin: [0, 0, 0, 0],
        page_size: [width(svg_data), height(svg_data)]
      }
      Prawn::Document.generate(pdf_file.path, options) do |prawn|
        prawn.font_families.update(fonts_for(svg_data))
        prawn.svg svg_data, at: [0, prawn.bounds.top]
      end
    end

    def fonts_for(svg)
      fonts_needed = svg.scan(/font-family:['"]?([^;'"]*)['"]?;/).flatten.uniq
      fonts_needed.each_with_object({}) do |family, result|
        result[family] = build_family_map(family)
        result
      end
    end

    def build_family_map(family)
      available_family_fonts = @font_paths.select { |p| p.match(/#{family}/) }
      available_family_fonts.inject({}) do |m, font|
        match = font.match(/#{family}-([^.-]+)/)
        if match
          m.merge(match[1].to_sym => File.expand_path(font))
        else
          m
        end
      end
    end

    def width(svg)
      svg_property(svg, 'width')
    end

    def height(svg)
      svg_property(svg, 'height')
    end

    def svg_property(svg, property)
      match = svg.match(/<svg[^>]*#{property}\s*=\s*['"](\d+)/)
      if match
        match[1].to_i
      else
        0
      end
    end
  end
end


text:
from chainer.dataset import convert
from chainer.dataset import dataset_mixin
from chainer.dataset import download
from chainer.dataset import iterator

DatasetMixin = dataset_mixin.DatasetMixin
Iterator = iterator.Iterator

concat_examples = convert.concat_examples

get_dataset_root = download.get_dataset_root
set_dataset_root = download.set_dataset_root
get_dataset_directory = download.get_dataset_directory
cached_download = download.cached_download
cache_or_load_file = download.cache_or_load_file


text:
import sys
import StringIO

import tokenize
import token as pytoken
import keyword as pykeyword
import ast

import piq

def is_token(l, i, toknum, tokval=None):
    if i >= len(l):
        return False

    token = l[i]
    if toknum == token[0]:
        if tokval == None:
            return True
        else:
            return (tokval == token[1])
    else:
        return False

def is_token_op(l, i, opname=None):
    return is_token(l, i, pytoken.OP, tokval=opname)

def is_token_op_in(l, i, opnames):
    for opname in opnames:
        if is_token_op(l, i, opname):
            return True
    return False

def is_token_name(l, i):
    return is_token(l, i, pytoken.NAME)

def peek_token(l, i):
    if i >= len(l):
        return None
    else:
        return l[i]

def pop_token(l, i):
    return (l[i], i + 1)

def is_token_keyword(l, i):
    token = peek_token(l, i)
    return (token is not None and token[0] == pytoken.NAME and pykeyword.iskeyword(token[1]))

def is_token_op_value_start(l, i):
    return is_token_op_in(l, i, ['`', '(', '[', '{', '-', '+', '~'])

def is_token_value_start(l, i):
    return (not is_token_op(l, i) or is_token_op_value_start(l, i)) and not is_token_keyword(l, i) and not is_token(l, i, pytoken.ENDMARKER)

def make_token(toknum, tokval, tokstart = None, tokend = None):
    if tokstart is None:
        return (toknum, tokval)
    else:
        if tokend is None:
            tokend = tokstart
        return (toknum, tokval, tokstart, tokend, None)

def is_piq_name_start(l, i):
    return is_token_op(l, i, '.') and is_token_name(l, i + 1)

def is_piq_name_continue(l, i):
    return is_token_op(l, i, '-') and is_token_name(l, i + 1)

# skip insignificant tokens
def skip_nl_and_comment_tokens(l, i, accu):
    if is_token(l, i, tokenize.NL) or is_token(l, i, tokenize.COMMENT):
        token, i = pop_token(l, i)
        accu.append(token)
        return skip_nl_and_comment_tokens(l, i, accu)  # see if we've got more of these
    else:
        return i

def transform_piq_name(filename, l, i, accu, name=None, name_loc=None):
    # '.' in case of name start, '-' in case of another name segment
    #
    # TODO: make sure '-' immediately follow preceeding name segment
    dot_or_dash_token, i = pop_token(l, i)
    dot_loc = dot_or_dash_token[3]
    dot_or_dash = dot_or_dash_token[1]

    name_token, i = pop_token(l, i)
    name_token_val = name_token[1]

    if name is None:
        name = ''
    else:
        name += dot_or_dash
    name += name_token_val

    if name_loc is None:
        name_loc = dot_loc

    def accu_append_keyword(keyword):
        def make_loc(loc):
            return [
                (pytoken.OP, ','),
                (pytoken.OP, '('),
                #(pytoken.STRING, "'" + filename + "'"),
                #(pytoken.OP, ','),
                (pytoken.NUMBER, str(loc[0])),  # line
                (pytoken.OP, ','),
                (pytoken.NUMBER, str(loc[1])),  # column
                (pytoken.OP, ')')
            ]

        accu.extend([
            (pytoken.NAME, keyword),
            (pytoken.OP, '('),
            (pytoken.STRING, "'" + name + "'")
        ])

        accu.extend(make_loc(name_loc))

        accu.extend([
            (pytoken.OP, ')')
        ])

    if is_piq_name_start(l, i):
        # next token is also a name => this name is chained with another Piq
        # name => recurse
        i = transform_piq_name(filename, l, i, accu, name, name_loc)
    elif is_piq_name_continue(l, i):
        # next token is a '-' followed by another name segment => recurse
        i = transform_piq_name(filename, l, i, accu, name, name_loc)
    else:
        # something else

        # skip whitespace
        nl_and_comment_accu = []
        i = skip_nl_and_comment_tokens(l, i, nl_and_comment_accu)

        if is_token_op_in(l, i, [')', ']', ',']):
            # end of name
            accu_append_keyword('_piq_make_name')
        elif is_token_value_start(l, i):
            # value juxtaposition
            accu_append_keyword('_piq_make_named')

            accu.append((pytoken.OP, '**'))
        elif is_token_op(l, i, '*') and is_token_value_start(l, i + 1):
            # splice
            accu_append_keyword('_piq_make_splice')

            # replace '*' with '**' which has a higher precedence and stronger
            # binding
            _, i = pop_token(l, i)
            accu.append((pytoken.OP, '**'))
        else:
            # something else, likely an error
            error_tok =  peek_token(l, i)
            error_tok_loc = error_tok[3]

            loc = piq.make_loc((error_tok_loc[0], error_tok_loc[1]))
            raise piq.ParseError(loc, "label must be followed by value, '*' value, or one of ')', ']', ','")

        # insert back newlines and comments
        accu.extend(nl_and_comment_accu)

    return i

def transform_token_list(filename, l):
    accu = []
    i = 0

    i = skip_nl_and_comment_tokens(l, i, accu)

    piq_name_allowed = False
    while True:
        if i >= len(l):
            return accu

        if piq_name_allowed and is_piq_name_start(l, i):
            i = transform_piq_name(filename, l, i, accu)

            # Piq name can not be immediately followed by another Piq name
            piq_name_allowed = False
        else:
            # Piq name is allowed only after these tokens
            #
            # TODO: allow only commas inside lists
            piq_name_allowed = is_token_op_in(l, i, ['(', '[', ','])

            token, i = pop_token(l, i)
            accu.append(token)

            i = skip_nl_and_comment_tokens(l, i, accu)

def tokenize_common(infile):
    tokens = tokenize.generate_tokens(infile)
    return list(tokens)

def tokenize_string(s):
    return tokenize_common(StringIO.StringIO(s).readline)

def tokenize_file(filename):
    with open(filename, 'rb') as infile:
        return tokenize_common(infile.readline)

def tokenize_and_transform_string(s, filename='-'):
    tokens = tokenize_string(s)
    return transform_token_list(filename, tokens)

def tokenize_and_transform_file(filename):
    tokens = tokenize_file(filename)
    return transform_token_list(filename, tokens)

class AstExprWrapper(ast.NodeTransformer):
    """Wraps all (load) expressions in a call to piq.ObjectProxy()"""
    def visit(self, node):
        node = self.generic_visit(node)
        ctx = getattr(node, 'ctx', None)
        if isinstance(node, ast.expr) and (not ctx or isinstance(ctx, ast.Load)):
            # TODO, XXX: don't wrap Call.func, because it can never result in a
            # piq data structure, also won't need __call__ method in
            # piq.ObjectProxy()

            # TODO: transform (_piq_make_named(name, loc) ** value) into
            # Named(name, loc, value); similarly, for _piq_make_splice()
            #
            # this way, we won't need AbstractNamed and AbstractSplice runtime

            #print "NODE:", node, list(ast.iter_fields(node))

            def make_node(new_node):
                return ast.copy_location(new_node, node)

            lineno = make_node(ast.Num(node.lineno))
            col_offset = make_node(ast.Num(node.col_offset))
            func = make_node(ast.Name(id='_piq_wrap_object', ctx=ast.Load()))

            return make_node(ast.Call(
                func=func,
                args=[node, lineno, col_offset],
                keywords=[]
            ))
        else:
            return node

class AstOverrideOperators(ast.NodeTransformer):
    """Wraps all (load) expressions in a call to piq.ObjectProxy()"""
    def visit(self, node):
        node = self.generic_visit(node)

        def make_node(new_node):
            return ast.copy_location(new_node, node)

        def make_operator_node(name, args):
            func = make_node(ast.Name(id='_piq_operator_' + name, ctx=ast.Load()))

            return make_node(ast.Call(
                func=func,
                args=args,
                keywords=[]
            ))

        def make_lazy_bool_operator_node(name, args):
            def make_lazy_arg_node(body):
                args = make_node(ast.arguments(
                    args=[],
                    vararg=None,
                    kwarg=None,
                    defaults=[]
                ))
                return make_node(ast.Lambda(
                    args=args,
                    body=body
                ))

            first_eager_arg_node, rest_args = args[0], args[1:]
            rest_lazy_arg_nodes = [make_lazy_arg_node(x) for x in rest_args]

            return make_operator_node(name, [first_eager_arg_node] + rest_lazy_arg_nodes)

        if isinstance(node, ast.BoolOp) and isinstance(node.op, ast.And):
            return make_lazy_bool_operator_node('and', node.values)

        if isinstance(node, ast.BoolOp) and isinstance(node.op, ast.Or):
            return make_lazy_bool_operator_node('or', node.values)

        elif isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not):
            return make_operator_node('not', [node.operand])

        elif isinstance(node, ast.Compare) and len(node.ops) == 1 and isinstance(node.ops[0], (ast.In, ast.NotIn)):
            # NOTE, XXX: not handling chained comparison operators, for example:
            #
            #    1 in 2 in 3
            #    1 in 2 > 3
            #    1 in 2 not in 3

            in_node = make_operator_node('in', [node.left, node.comparators[0]])

            if isinstance(node.ops[0], ast.In):
                return in_node
            else:
                return make_operator_node('not', [in_node])

        else:
            return node

class AbstractNamed(object):
    def __init__(self, name, loc):
        self.name = name
        self.loc = loc

    def __pow__(self, other):
        return piq.Named(self.name, self.loc, other)

class AbstractSplice(AbstractNamed):
    def __pow__(self, other):
        return piq.Splice(self.name, self.loc, other)

def wrap_object(*args):
    return piq.wrap_object(*args)
def make_name(name, loc):
    return piq.Name(name, loc)
def make_named(name, loc):
    return AbstractNamed(name, loc)
def make_splice(name, loc):
    return AbstractSplice(name, loc)

def is_domain_boolean_expression(x):
    return (
            hasattr(x, '__bool_and__') and hasattr(x, '__bool_or__') and hasattr(x, '__bool_not__')
    )

def check_is_domain_boolean_expression(x):
    # not allowed to mix domain boolean expressions and non-domain ones
    #
    # TODO, XXX: produce an actual error message, or leave such validation to
    # domain implementation
    assert is_domain_boolean_expression(x)

def check_is_not_domain_boolean_expression(x):
    assert not is_domain_boolean_expression(x)

def operator_and(accu, *args):
    def binary_and(accu, arg):
        if is_domain_boolean_expression(accu):
            arg = arg()
            check_is_domain_boolean_expression(arg)
            res = accu.__bool_and__(arg)
            check_is_domain_boolean_expression(res)
        else:
            # standard boolean and evaluation
            if not accu:
                res = False  # short-circuit
            else:
                arg = arg()
                check_is_not_domain_boolean_expression(arg)
                res = (accu and arg)  # NOTE, XXX: equivalent to just arg
        return res

    for arg in args:
        accu = binary_and(accu, arg)
        if accu == False:
            break  # short-circuit

    return accu

def operator_or(accu, *args):
    def binary_or(accu, arg):
        if is_domain_boolean_expression(accu):
            arg = arg()
            check_is_domain_boolean_expression(arg)
            res = accu.__bool_or__(arg)
            check_is_domain_boolean_expression(res)
        else:
            # standard boolean or evaluation
            if accu:
                res = accu
            else:
                arg = arg()
                check_is_not_domain_boolean_expression(arg)
                res = (accu or arg)  # NOTE, XXX: equivalent to just arg
        return res

    for arg in args:
        accu = binary_or(accu, arg)
        if accu and not is_domain_boolean_expression(accu):
            break  # short-circuit

    return accu

def operator_not(arg):
    if is_domain_boolean_expression(arg):
        res = arg.__bool_not__()
        check_is_domain_boolean_expression(res)
    else:
        res = (not arg)
    return res

def operator_in(left, right):
    if hasattr(left, '__in__'):
        res = left.__in__(right)
        check_is_domain_boolean_expression(res)
    else:
        res = (left in right)
    return res

# this is tweaked version of tokenize.Untokenizer.compact()
#
def untokenize(tokens):
    # stock Python's tokenize.untokenize() has a bug/omission when it doesn't
    # correctly carry indent state upon switching from Untokenizer.untokenize()
    # to Untokenizer.compat()
    #
    # to make it happy, we are forcing it to switch to Untokenizer.compat() on
    # the first token
    first_token = tokens[0]
    tokens[0] = (first_token[0], first_token[1])

    return tokenize.untokenize(tokens)

def parse_file(filename):
    tokens = tokenize_and_transform_file(filename)
    source = untokenize(tokens)
    return ast.parse(source, filename, 'exec')

# for AST transformations see
#
# https://docs.python.org/3/library/ast.html
# https://docs.python.org/2/library/ast.html
# http://greentreesnakes.readthedocs.io/

def parse_and_transform_file(filename, transform_expressions=True, transform_operators=True):
    ast = parse_file(filename)

    if transform_expressions:
        ast = AstExprWrapper().visit(ast)

    if transform_operators:
        ast = AstOverrideOperators().visit(ast)

    return ast

def exec_file(filename, user_globals=None, transform_operators=False):
    transformed_ast = parse_and_transform_file(filename, transform_operators=transform_operators)

    if user_globals is not None:
        assert isinstance(user_globals, dict)
        exec_globals = user_globals
    else:
        exec_globals = {}

    exec_globals.update(dict(
        _piq_wrap_object = wrap_object,
        _piq_make_name = make_name,
        _piq_make_named = make_named,
        _piq_make_splice = make_splice,

        _piq_operator_and = operator_and,
        _piq_operator_or = operator_or,
        _piq_operator_not = operator_not,
        _piq_operator_in = operator_in,
    ))

    exec(compile(transformed_ast, filename, 'exec'), exec_globals)

def main():
    arg_tokenize = False
    arg_tokenize_transform = False
    arg_parse = False

    arg_parse_transform = False
    arg_transform_operators = False
    arg_transform_expressions = False

    arg_abstract_output = False

    args = sys.argv[1:]

    i = 0
    while True:
        if i >= len(args):
            break

        a = args[i]

        if a in ['-t', '--tokenize']:
            arg_tokenize = True
            arg_abstract_output = True
        elif a in ['-tt', '--tokenize-transform']:
            arg_tokenize_transform = True
        elif a in ['-p', '--parse']:
            arg_parse = True
            arg_abstract_output = True
        elif a in ['-pt', '--parse-transform']:
            arg_parse_transform = True
            arg_transform_expressions = True
            arg_transform_operators = True
        elif a in ['-pte', '--parse-transform-expressions']:
            arg_parse_transform = True
            arg_transform_expressions = True
        elif a in ['-pto', '--parse-transform-operators']:
            arg_parse_transform = True
            arg_transform_operators = True
        elif a in ['-a', '--abstract-output']:
            arg_abstract_output = True
        elif a.startswith('-'):
            pass
        else:
            break  # positional argument
        i += 1

    positional_arg = args[i]
    filename = positional_arg

    def print_tokens(tokens):
        if arg_abstract_output:
            res = []
            for token in tokens:
                res.append((pytoken.tok_name[token[0]], token[1]))
            print res
        else:
            print untokenize(tokens)

    def print_ast(output_ast):
        if arg_abstract_output:
            try:
                import astunparse
                print astunparse.dump(output_ast)
            except ImportError:
                print ast.dump(output_ast)
        else:
            try:
                import astunparse
                print astunparse.unparse(output_ast)
            except ImportError:
                sys.exit("couldn't import 'astunparse'")

    if arg_tokenize:
        tokens = tokenize_file(filename)
        print_tokens(tokens)
    elif arg_tokenize_transform:
        tokens = tokenize_and_transform_file(filename)
        print_tokens(tokens)
    elif arg_parse:
        source_ast = parse_file(filename)
        print_ast(source_ast)
    elif arg_parse_transform:
        transformed_ast = parse_and_transform_file(
                filename,
                transform_operators=arg_transform_operators,
                transform_expressions=arg_transform_expressions)
        print_ast(transformed_ast)
    else:
        # XXX
        try:
            exec_file(filename, transform_operators=True)
        except piq.ParseError as e:
            sys.stderr.write(filename + ':' + str(loc.line) + ': ' + error)
            sys.exit(1)

if __name__ == '__main__':
    main()


text:
<?php

namespace ERP\AdminBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * CltCatProducto
 *
 * @ORM\Table(name="clt_cat_producto")
 * @ORM\Entity
 */
class CltCatProducto
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="nombre", type="string", length=100, nullable=true)
     */
    private $nombre;

    /**
     * @var string
     *
     * @ORM\Column(name="descripcion", type="string", length=255, nullable=true)
     */
    private $descripcion;

    /**
     * @var boolean
     *
     * @ORM\Column(name="estado", type="boolean", nullable=true)
     */
    private $estado;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set nombre
     *
     * @param string $nombre
     * @return CltCatProducto
     */
    public function setNombre($nombre)
    {
        $this->nombre = $nombre;

        return $this;
    }

    /**
     * Get nombre
     *
     * @return string
     */
    public function getNombre()
    {
        return $this->nombre;
    }

    /**
     * Set descripcion
     *
     * @param string $descripcion
     * @return CltCatProducto
     */
    public function setDescripcion($descripcion)
    {
        $this->descripcion = $descripcion;

        return $this;
    }

    /**
     * Get descripcion
     *
     * @return string
     */
    public function getDescripcion()
    {
        return $this->descripcion;
    }

    /**
     * Set estado
     *
     * @param boolean $estado
     * @return CltCatProducto
     */
    public function setEstado($estado)
    {
        $this->estado = $estado;

        return $this;
    }

    /**
     * Get estado
     *
     * @return boolean
     */
    public function getEstado()
    {
        return $this->estado;
    }

    public function __toString() {
    //return $this->cargo ? $this->cargo : '';
    return $this->getNombre();
    }
}


text:
struct MAP_EXP    // this is where we will put the info from file that we will read
{
    int MapsSingle[MAX_NUMBER_MAP]; // each map have each extra exp possibility so we make INTEGER array with max maps size
    int MapsParty[MAX_NUMBER_MAP]; // for party exp
};

// now we must put this struct in class so we can access it from anywhere
class CExtraEXP // most commonly use Candfilename for the name of class
{
    //and all functions that  want to use outside of the .cpp file where u make the class u must put in public:
public: // like this got it? yup
    void LoadFile(
            LPSTR file); // LPSTR is a string and file is name of argument. we must put the function here in class header so we can access it from anywhere nderstad? yup a
    // so now we put structure  in the class that we made above
    MAP_EXP m_ExtraExpData; // type of variable is MAP_EXP and name is u see
};

extern CExtraEXP g_ExtraEXP; // this is how we will call class later g_ExtraEXP.function()
// now we need a function that will load a file


text:
<?php

/* TwigBundle:Exception:trace.html.twig */
class __TwigTemplate_195ce9e50a275be1b2338345e7cd3d7b23c1afc8c4fec723b5500da320c436e8 extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = false;

        $this->blocks = array(
        );
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $__internal_dea68bbfa1ac442071a9db4b5d9f837e7a34f371ff58475db11607178d1abec4 = $this->env->getExtension("native_profiler");
        $__internal_dea68bbfa1ac442071a9db4b5d9f837e7a34f371ff58475db11607178d1abec4->enter($__internal_dea68bbfa1ac442071a9db4b5d9f837e7a34f371ff58475db11607178d1abec4_prof = new Twig_Profiler_Profile($this->getTemplateName(), "template", "TwigBundle:Exception:trace.html.twig"));

        // line 1
        if ($this->getAttribute((isset($context["trace"]) ? $context["trace"] : $this->getContext($context, "trace")), "function", array())) {
            // line 2
            echo "    at

        env, $this->getAttribute((isset($context["trace"]) ? $context["trace"] : $this->getContext($context, "trace")), "class", array()), "html", null, true);
            echo "\">";
            echo twig_escape_filter($this->env, $this->getAttribute((isset($context["trace"]) ? $context["trace"] : $this->getContext($context, "trace")), "short_class", array()), "html", null, true);
            echo "
        ";
            // line 5
            echo twig_escape_filter($this->env, ($this->getAttribute((isset($context["trace"]) ? $context["trace"] : $this->getContext($context, "trace")), "type", array()) . $this->getAttribute((isset($context["trace"]) ? $context["trace"] : $this->getContext($context, "trace")), "function", array())), "html", null, true);
            echo "

    (";
            // line 7
            echo $this->env->getExtension('code')->formatArgs($this->getAttribute((isset($context["trace"]) ? $context["trace"] : $this->getContext($context, "trace")), "args", array()));
            echo ")
";
        }
        // line 9
        echo "
";
        // line 10
        if (((($this->getAttribute((isset($context["trace"]) ? $context["trace"] : null), "file", array(), "any", true, true) && $this->getAttribute((isset($context["trace"]) ? $context["trace"] : $this->getContext($context, "trace")), "file", array())) && $this->getAttribute((isset($context["trace"]) ? $context["trace"] : null), "line", array(), "any", true, true)) && $this->getAttribute((isset($context["trace"]) ? $context["trace"] : $this->getContext($context, "trace")), "line", array()))) {
            // line 11
            echo "    ";
            echo (($this->getAttribute((isset($context["trace"]) ? $context["trace"] : $this->getContext($context, "trace")), "function", array())) ? ("
") : (""));
            echo "
    in ";
            // line 12
            echo $this->env->getExtension('code')->formatFile($this->getAttribute((isset($context["trace"]) ? $context["trace"] : $this->getContext($context, "trace")), "file", array()), $this->getAttribute((isset($context["trace"]) ? $context["trace"] : $this->getContext($context, "trace")), "line", array()));
            echo "
    ";
            // line 13
            ob_start();
            // line 14
            echo "    env, (((isset($context["prefix"]) ? $context["prefix"] : $this->getContext($context, "prefix")) . "-") . (isset($context["i"]) ? $context["i"] : $this->getContext($context, "i"))), "html", null, true);
            echo "'); switchIcons('icon-";
            echo twig_escape_filter($this->env, (((isset($context["prefix"]) ? $context["prefix"] : $this->getContext($context, "prefix")) . "-") . (isset($context["i"]) ? $context["i"] : $this->getContext($context, "i"))), "html", null, true);
            echo "-open', 'icon-";
            echo twig_escape_filter($this->env, (((isset($context["prefix"]) ? $context["prefix"] : $this->getContext($context, "prefix")) . "-") . (isset($context["i"]) ? $context["i"] : $this->getContext($context, "i"))), "html", null, true);
            echo "-close'); return false;\">
        env, (((isset($context["prefix"]) ? $context["prefix"] : $this->getContext($context, "prefix")) . "-") . (isset($context["i"]) ? $context["i"] : $this->getContext($context, "i"))), "html", null, true);
            echo "-close\" alt=\"-\" src=\"data:image/gif;base64,R0lGODlhEgASAMQSANft94TG57Hb8GS44ez1+mC24IvK6ePx+Wa44dXs92+942e54o3L6W2844/M6dnu+P/+/l614P///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAABIALAAAAAASABIAQAVCoCQBTBOd6Kk4gJhGBCTPxysJb44K0qD/ER/wlxjmisZkMqBEBW5NHrMZmVKvv9hMVsO+hE0EoNAstEYGxG9heIhCADs=\" style=\"display: ";
            echo (((0 == (isset($context["i"]) ? $context["i"] : $this->getContext($context, "i")))) ? ("inline") : ("none"));
            echo "\" />
        env, (((isset($context["prefix"]) ? $context["prefix"] : $this->getContext($context, "prefix")) . "-") . (isset($context["i"]) ? $context["i"] : $this->getContext($context, "i"))), "html", null, true);
            echo "-open\" alt=\"+\" src=\"data:image/gif;base64,R0lGODlhEgASAMQTANft99/v+Ga44bHb8ITG52S44dXs9+z1+uPx+YvK6WC24G+944/M6W28443L6dnu+Ge54v/+/l614P///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAABMALAAAAAASABIAQAVS4DQBTiOd6LkwgJgeUSzHSDoNaZ4PU6FLgYBA5/vFID/DbylRGiNIZu74I0h1hNsVxbNuUV4d9SsZM2EzWe1qThVzwWFOAFCQFa1RQq6DJB4iIQA7\" style=\"display: ";
            echo (((0 == (isset($context["i"]) ? $context["i"] : $this->getContext($context, "i")))) ? ("none") : ("inline"));
            echo "\" />

    ";
            echo trim(preg_replace('/>\s+</', '><', ob_get_clean()));
            // line 19
            echo "
env, (((isset($context["prefix"]) ? $context["prefix"] : $this->getContext($context, "prefix")) . "-") . (isset($context["i"]) ? $context["i"] : $this->getContext($context, "i"))), "html", null, true);
            echo "\" style=\"display: ";
            echo (((0 == (isset($context["i"]) ? $context["i"] : $this->getContext($context, "i")))) ? ("block") : ("none"));
            echo "\" class=\"trace\">
        ";
            // line 20
            echo $this->env->getExtension('code')->fileExcerpt($this->getAttribute((isset($context["trace"]) ? $context["trace"] : $this->getContext($context, "trace")), "file", array()), $this->getAttribute((isset($context["trace"]) ? $context["trace"] : $this->getContext($context, "trace")), "line", array()));
            echo "

";
        }

        $__internal_dea68bbfa1ac442071a9db4b5d9f837e7a34f371ff58475db11607178d1abec4->leave($__internal_dea68bbfa1ac442071a9db4b5d9f837e7a34f371ff58475db11607178d1abec4_prof);

    }

    public function getTemplateName()
    {
        return "TwigBundle:Exception:trace.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  90 => 20,  83 => 19,  75 => 16,  69 => 15,  60 => 14,  58 => 13,  54 => 12,  49 => 11,  47 => 10,  44 => 9,  39 => 7,  34 => 5,  28 => 4,  24 => 2,  22 => 1,);
    }
}


text:
package com.navercorp.pinpoint.web.cluster.connection;

import com.navercorp.pinpoint.common.util.NetUtils;
import com.navercorp.pinpoint.rpc.PinpointSocket;
import com.navercorp.pinpoint.rpc.cluster.ClusterOption;
import com.navercorp.pinpoint.web.cluster.ClusterId;
import com.navercorp.pinpoint.web.config.WebClusterConfig;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author Taejin Koo
 */
public class ClusterConnectionManager {
    private final Logger logger = LogManager.getLogger(this.getClass());

    private final WebClusterConfig config;

    private ClusterAcceptor clusterAcceptor;
    private ClusterConnector clusterConnector;

    public ClusterConnectionManager(WebClusterConfig config) {
        this.config = config;
    }

    public void start() {
        logger.info("start() started.");

        String hostAddress = config.getHostAddress();
        int bindPort = config.getClusterTcpPort();
        if (bindPort > 0) {
            if (StringUtils.isEmpty(hostAddress)) {
                hostAddress = getRepresentationLocalV4Ip();
            }

            clusterAcceptor = new ClusterAcceptor(hostAddress, bindPort);
            clusterAcceptor.start();
        }

        final String clusterConnectAddress = config.getClusterConnectAddress();
        if (StringUtils.isNotBlank(clusterConnectAddress)) {
            clusterConnector = new ClusterConnector(clusterConnectAddress);
            clusterConnector.start();
        } else {
            logger.info("cluster.connect.address is empty");
        }

        logger.info("start() completed.");
    }

    public void stop() {
        logger.info("stop() started.");

        if (clusterConnector != null) {
            clusterConnector.stop();
            clusterConnector = null;
        }

        if (clusterAcceptor!= null) {
            clusterAcceptor.stop();
            clusterAcceptor = null;
        }

        logger.info("stop() completed.");
    }

    private String getRepresentationLocalV4Ip() {
        String ip = NetUtils.getLocalV4Ip();

        if (!ip.equals(NetUtils.LOOPBACK_ADDRESS_V4)) {
            return ip;
        }

        // local ip addresses with all LOOPBACK addresses removed
        List<String> ipList = NetUtils.getLocalV4IpList();
        if (!ipList.isEmpty()) {
            return ipList.get(0);
        }

        return NetUtils.LOOPBACK_ADDRESS_V4;
    }

    public PinpointSocket getSocket(ClusterId clusterId) {
        Objects.requireNonNull(clusterId, "clusterId");

        if (clusterAcceptor != null) {
            List<PinpointSocket> clusterList = clusterAcceptor.getClusterSocketList();
            for (PinpointSocket cluster : clusterList) {
                ClusterOption remoteClusterOption = cluster.getRemoteClusterOption();
                logger.debug("clusterAcceptor clusterId:{} remoteClusterOption:{}", clusterId, remoteClusterOption);
                if (remoteClusterOption != null) {
                    if (clusterId.getCollectorId().equals(remoteClusterOption.getId())) {
                        return cluster;
                    }
                }
            }
        }

        if (clusterConnector != null) {
            List<PinpointSocket> clusterList = clusterConnector.getClusterSocketList();
            for (PinpointSocket cluster : clusterList) {
                ClusterOption remoteClusterOption = cluster.getRemoteClusterOption();
                logger.debug("clusterConnector clusterId:{} remoteClusterOption:{}", clusterId, remoteClusterOption);
                if (remoteClusterOption != null) {
                    if (clusterId.getCollectorId().equals(remoteClusterOption.getId())) {
                        return cluster;
                    }
                }
            }
        }

        return null;
    }

    public List<PinpointSocket> getClusterList() {
        List<PinpointSocket> clusterList = new ArrayList<>();

        if (clusterAcceptor != null) {
            clusterList.addAll(clusterAcceptor.getClusterSocketList());
        }

        if (clusterConnector != null) {
            clusterList.addAll(clusterConnector.getClusterSocketList());
        }

        return clusterList;
    }

    public ClusterAcceptor getClusterAcceptor() {
        return clusterAcceptor;
    }

    public ClusterConnector getClusterConnector() {
        return clusterConnector;
    }

}


text:
// -*- C++ -*-

//=============================================================================
/**
 *  @file    Auto_IncDec_T.h
 *
 *  @author Edan Ayal <EdanA@cti2.com>
 */
//=============================================================================

#ifndef ACE_AUTO_INCDEC_T_H
#define ACE_AUTO_INCDEC_T_H

#include /**/ "ace/pre.h"

#include /**/ "ace/config-all.h"

#if !defined (ACE_LACKS_PRAGMA_ONCE)
# pragma once
#endif /* ACE_LACKS_PRAGMA_ONCE */

#include "ace/Global_Macros.h"

ACE_BEGIN_VERSIONED_NAMESPACE_DECL

/**
 * @class ACE_Auto_IncDec
 *
 * @brief This class automatically increments and decrements a
 * parameterized counter.
 *
 * This data structure is meant to be used within a method,
 * function, or scope.  The actual parameter given for the
 * @c ACE_SAFELY_INCREMENTABLE_DECREMENTABLE template parameter
 * must provide at least operators ++ and --.
 */
template <class ACE_SAFELY_INCREMENTABLE_DECREMENTABLE>
class ACE_Auto_IncDec
{
public:
  /// Implicitly increment the counter.
  ACE_Auto_IncDec (ACE_SAFELY_INCREMENTABLE_DECREMENTABLE &counter);

  /// Implicitly decrement the counter.
  ~ACE_Auto_IncDec (void);

  /// Dump the state of an object.
  void dump (void) const;

  /// Declare the dynamic allocation hooks.
  ACE_ALLOC_HOOK_DECLARE;

protected:
  /// Reference to the @c ACE_SAFELY_INCREMENTABLE_DECREMENTABLE counter
  /// we're incrementing/decrementing.
  ACE_SAFELY_INCREMENTABLE_DECREMENTABLE &counter_;
private:
  ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Auto_IncDec<ACE_SAFELY_INCREMENTABLE_DECREMENTABLE> &))
  ACE_UNIMPLEMENTED_FUNC (ACE_Auto_IncDec (const ACE_Auto_IncDec<ACE_SAFELY_INCREMENTABLE_DECREMENTABLE> &))
};

ACE_END_VERSIONED_NAMESPACE_DECL

#if defined (__ACE_INLINE__)
#include "ace/Auto_IncDec_T.inl"
#endif /* __ACE_INLINE__ */

#if defined (ACE_TEMPLATES_REQUIRE_SOURCE)
#include "ace/Auto_IncDec_T.cpp"
#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */

#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA)
#pragma implementation ("Auto_IncDec_T.cpp")
#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */

#include /**/ "ace/post.h"

#endif /* ACE_AUTO_INCDEC_T_H */


text:
package gsh

import (
	"flag"
	"os"
	"time"

	"gopkg.in/pipe.v2"
)

type GitLastModifiedCmd struct {
}

func (cmd *GitLastModifiedCmd) Name() string {
	return "gitLastModified"
}

func (cmd *GitLastModifiedCmd) Flags() *flag.FlagSet {
	f := flag.NewFlagSet(cmd.Name(), flag.ExitOnError)
	return f
}

func (cmd *GitLastModifiedCmd) Run(s *pipe.State, args []string) error {
	return nil
}

// GitLastModified returns the the last-modified timestamp of a given file or files
func GitLastModified(argv ...string) pipe.Pipe {
	//cmd := GitLastModifiedCmd{}
	gitargs := []string{"log", "-n", "1", "--date=rfc", "--pretty=format:%cd"}
	gitargs = append(gitargs, argv...)

	return pipe.Line(
		pipe.Exec("git", gitargs...),
		ParseTime("-in", "RFC1123Z"),
	)
}

type FileLastModifiedCmd struct {
}

func (cmd *FileLastModifiedCmd) Name() string {
	return "fileLastModified"
}

func (cmd *FileLastModifiedCmd) Flags() *flag.FlagSet {
	f := flag.NewFlagSet(cmd.Name(), flag.ExitOnError)
	return f
}

func (cmd *FileLastModifiedCmd) exec(line []byte) ([]byte, error) {
	fi, err := os.Stat(string(line))
	if err != nil {
		return nil, err
	}
	return []byte(fi.ModTime().Format(time.RFC3339)), nil
}

func (cmd *FileLastModifiedCmd) Run(s *pipe.State, argv []string) error {
	fs := cmd.Flags()
	err := fs.Parse(argv)
	if err != nil {
		return err
	}
	args := fs.Args()
	return ForEachLine(s, args, cmd.exec)
}
func FileLastModified(argv ...string) pipe.Pipe {
	cmd := FileLastModifiedCmd{}
	return pipe.TaskFunc(func(s *pipe.State) error {
		return cmd.Run(s, argv)
	})
}

/*
func DirLastModified(argv ...string) pipe.Pipe {

}

*/


text:
class Searchbot::Sources::AcquisitionsDirect::Searcher < Searchbot::Generic::Searcher

  def base_url
    'http://www.acquisitionsdirect.com/buy/'
  end

  def url_for_page(page = 1)
    raise "AcquisitionsDirect has a single page of search results" unless page == 1
    base_url
  end

end


text:
package de.uniulm.omi.cloudiator.visor.config;

public class ContextConstants {

  public final static String COMPONENT_ID = "component.id";
  public static final String LOCAL_IP = "local.ip";
  public static final String OS_NAME = "os.name";
  public static final String OS_ARCH = "os.arch";
  public static final String OS_VERS = "os.version";
  public static final String JAVA_VERSION = "java.version";
  public static final String CLOUD_ID = "cloud.id";
  public static final String VM_ID = "vm.id";

}


text:
var gulp   = require('gulp'),
	rename = require('gulp-rename'),
	uglify = require('gulp-uglify'),
	header = require('gulp-header'),
	concat = require('gulp-concat'),
	highland = require('highland'),
	fs = require('fs'),
	path = require('path'),
	File = require('vinyl'),
	del = require('del'),
	yargs = require('yargs'),
	npm = require('npm'),

  runningPackagingTask = yargs.argv._.indexOf('createPackages') > -1,
  version = yargs.argv.version,

	paths  = {
		components: ['components/**/*.js', '!components/**/*.min.js'],
		main: [
			'components/prism-core.js',
			'components/prism-markup.js',
			'components/prism-css.js',
			'components/prism-clike.js',
			'components/prism-javascript.js',
			'plugins/file-highlight/prism-file-highlight.js'
		],
		plugins: ['plugins/**/*.js', '!plugins/**/*.min.js']
	};

gulp.task('components', function() {
	return gulp.src(paths.components)
		.pipe(uglify())
		.pipe(rename({ suffix: '.min' }))
		.pipe(gulp.dest('components'));
});

gulp.task('build', function() {
	return gulp.src(paths.main)
		.pipe(header('\n/* **********************************************\n' +
			'     Begin <%= file.relative %>\n' +
			'********************************************** */\n\n'))
		.pipe(concat('prism.js'))
		.pipe(gulp.dest('./'));
});

gulp.task('plugins', function() {
	return gulp.src(paths.plugins)
		.pipe(uglify())
		.pipe(rename({ suffix: '.min' }))
		.pipe(gulp.dest('plugins'));
});

gulp.task('watch', function() {
	gulp.watch(paths.components, ['components', 'build']);
	gulp.watch(paths.plugins, ['plugins', 'build']);
});

gulp.task('default', ['components', 'plugins', 'build']);

/* tasks for creating and publishing npm packages */

function readme(themeName) {
	return [
		'# Prism ' + themeName.charAt(0).toUpperCase() + themeName.substring(1) + ' Theme',
		'Prism is a lightweight, robust, elegant syntax highlighting library.',
		'Learn more at [http://prismjs.com/](http://prismjs.com/).'
	].join('\n\n');
}

function packagejson(themeName) {
	return JSON.stringify({
		name: 'prism-' + themeName + '-theme',
		version: version,
	  description: 'A CSS theme for PrismJS',
		repository: {
			type: 'git',
			url: 'https://github.com/PrismJS/prism.git'
		},
		keywords: [
			'prism',
			'highlight',
			'theme'
		],
		author: 'Lea Verou',
		license: 'MIT',
		style: 'prism-' + themeName + '.css'
	}, null, 2);
}

function license(themeName) {
	return fs.readFileSync('LICENSE');
}

var contentStrategy = {
	'package.json': packagejson,
	'README.md': readme,
	'LICENSE': license
};

gulp.task('clean-dist', function(done) {
	del('dist', done);
});

gulp.task('copy-css', ['build', 'clean-dist'], function() {
	return highland(gulp.src('themes/*.css'))
		.map(function(file) {
			var name = path.basename(file.path) === 'prism.css' ? 'prism-default' : path.basename(file.path, '.css');
			file.path = path.join(path.dirname(file.path), name, name + '.css');
			return file;
		})
		.pipe(gulp.dest('dist'));
});

gulp.task('copy-files', ['copy-css'], function() {
	return highland(gulp.src('dist/*'))
		.flatMap(function(dir) {
			var themeName = /prism-(\w+)/.exec(path.basename(dir.path))[1];
			return ['package.json', 'README.md', 'LICENSE']
				.map(function(fileName) {
					return new File({
						base: path.dirname(dir.path),
						path: path.join(dir.path, fileName),
						contents: new Buffer(contentStrategy[fileName](themeName))
					});
				});
		})
		.pipe(gulp.dest('dist'));
});

gulp.task('update-version', function() {
	return highland(gulp.src('package.json'))
		.map(function(file) {
			var packageInfo = JSON.parse(file.contents);
			packageInfo.version = version;
			file.contents = new Buffer(JSON.stringify(packageInfo, null, 2));
			return file;
		})
		.pipe(gulp.dest('.'));
});

if (runningPackagingTask && !version) {
	console.error('Please specify a version number for the release, for example: gulp createPackages --version 1.0.42');
	process.exit(1);
}

gulp.task('createPackages', ['copy-css', 'copy-files', 'update-version']);

gulp.task('publishPackages', function(done) {
	var packages = fs.readdirSync('dist')
		.map(function(packageName) {
			return path.join('dist', packageName);
		})
		.concat('.');

	npm.load({}, function() {
		function next() {
			if (packages.length > 0) {
				npm.commands.publish([packages.pop()], next);
			} else {
				done();
			}
		}
		next();
	});
});


text:
class AddFailureToCsvArchive < ActiveRecord::Migration
  def self.up
    add_column :csvarchives, :failure, :boolean
  end

  def self.down
    remove_column :csvarchives, :failure
  end
end


text:
$set 6 #Screen

$ #AnotherWMRunning
# BScreen::BScreen: feil ved forspørsel til X tjener.\n  \
en annen vindushåndterer kjører allerede på display %s.\n
$ #ManagingScreen
# BScreen::BScreen: håndterer skjerm %d, 0x%lx, fargedybde %d\n
$ #FontLoadFail
# BScreen::LoadStyle(): kunne ikke laste skrifttypen '%s'\n
$ #DefaultFontLoadFail
# BScreen::LoadStyle(): kunne ikke laste standard-skrifttypen.\n
$ #EmptyMenuFile
# %s: tom meny-fil\n
$ #xterm
# xterm
$ #Restart
# Omstart
$ #Exit
# Avslutt
$ #EXECError
# BScreen::parseMenuFile: [exec] feil, ingen meny-etikett og/eller kommando definert\n
$ #EXITError
# BScreen::parseMenuFile: [exit] feil, ingen meny-etikett definert\n
$ #STYLEError
# BScreen::parseMenuFile: [style] feil, ingen meny-etikett og/eller filnavn \
definert\n
$ #CONFIGError
# BScreen::parseMenuFile: [config] feil, ingen meny-etikett definert\n
$ #INCLUDEError
# BScreen::parseMenuFile: [include] feil, filnavn ikke definert\n
$ #INCLUDEErrorReg
# BScreen::parseMenuFile: [include] feil, '%s' er ikke en normal fil\n
$ #SUBMENUError
# BScreen::parseMenuFile: [submenu] feil, ingen meny-etikett definert\n
$ #RESTARTError
# BScreen::parseMenuFile: [restart] feil, ingen meny-etikett definert\n
$ #RECONFIGError
# BScreen::parseMenuFile: [reconfig] feil, ingen meny-etikett definert\n
$ #STYLESDIRError
# BScreen::parseMenuFile: [stylesdir/stylesmenu] feil, ingen katalog definert\n
$ #STYLESDIRErrorNotDir
# BScreen::parseMenuFile: [stylesdir/stylesmenu] feil, '%s' er ikke en katalog\n
$ #STYLESDIRErrorNoExist
# BScreen::parseMenuFile: [stylesdir/stylesmenu] feil, '%s' eksisterer ikke\n
$ #WORKSPACESError
# BScreen::parseMenuFile: [workspaces] feil, ingen meny-etikett definert\n
$ #PositionLength
# 0: 0000 x 0: 0000
$ #PositionFormat
# X: %4d x Y: %4d
$ #GeometryFormat
# B: %4d x H: %4d


text:
import os
import pkgutil
import shutil

from collections import defaultdict

from twitter.common.collections import OrderedSet
from twitter.common.dirutil import safe_mkdir, safe_open

from twitter.pants import get_buildroot
from twitter.pants.base.generator import TemplateData, Generator
from twitter.pants.tasks.ide_gen import IdeGen

__author__ = 'John Sirois'

_TEMPLATE_BASEDIR = os.path.join('eclipse', 'templates')

_VERSIONS = {
  '3.5': '3.7', # 3.5-3.7 are .project/.classpath compatible
  '3.6': '3.7',
  '3.7': '3.7',
}

_SETTINGS = (
  'org.eclipse.core.resources.prefs',
  'org.eclipse.jdt.core.prefs',
  'org.eclipse.jdt.ui.prefs',
)

class EclipseGen(IdeGen):
  @classmethod
  def setup_parser(cls, option_group, args, mkflag):
    IdeGen.setup_parser(option_group, args, mkflag)

    supported_versions = sorted(list(_VERSIONS.keys()))
    option_group.add_option(mkflag("eclipse-version"), dest = "eclipse_gen_version",
                            default = '3.6', type = "choice", choices = supported_versions,
                            help = "[%%default] The Eclipse version the project "
                                   "configuration should be generated for; can be one of: "
                                   "%s" % supported_versions)

  def __init__(self, context):
    IdeGen.__init__(self, context)

    eclipse_version = _VERSIONS[context.options.eclipse_gen_version]
    self.project_template = os.path.join(_TEMPLATE_BASEDIR, 'project-%s.mk' % eclipse_version)
    self.classpath_template = os.path.join(_TEMPLATE_BASEDIR, 'classpath-%s.mk' % eclipse_version)
    self.apt_template = os.path.join(_TEMPLATE_BASEDIR, 'factorypath-%s.mk' % eclipse_version)
    self.pydev_template = os.path.join(_TEMPLATE_BASEDIR, 'pydevproject-%s.mk' % eclipse_version)
    self.debug_template = os.path.join(_TEMPLATE_BASEDIR, 'debug-launcher-%s.mk' % eclipse_version)

    self.project_filename = os.path.join(self.cwd, '.project')
    self.classpath_filename = os.path.join(self.cwd, '.classpath')
    self.apt_filename = os.path.join(self.cwd, '.factorypath')
    self.pydev_filename = os.path.join(self.cwd, '.pydevproject')

  def generate_project(self, project):
    def linked_folder_id(path):
      return path.replace(os.path.sep, '.')

    def base_path(source_set):
      return os.path.join(source_set.root_dir, source_set.source_base)

    source_bases = {}
    for source_set in project.sources:
      source_bases[base_path(source_set)] = linked_folder_id(source_set.source_base)
    if project.has_python:
      for source_set in project.py_sources:
        source_bases[base_path(source_set)] = linked_folder_id(source_set.source_base)
      for source_set in project.py_libs:
        source_bases[base_path(source_set)] = linked_folder_id(source_set.source_base)

    def create_source_template(base, includes=None, excludes=None):
      return TemplateData(
        base=source_bases[base],
        includes=includes or [],
        excludes=excludes or [],
      )

    def create_sourcepath(base, sources):
      def normalize_path_pattern(path):
        return '%s/' % path if not path.endswith('/') else path

      includes = [normalize_path_pattern(src_set.path) for src_set in sources if src_set.path]
      excludes = []
      for source_set in sources:
        excludes.extend(normalize_path_pattern(exclude) for exclude in source_set.excludes)

      return create_source_template(base, includes, excludes)

    pythonpaths = []
    if project.has_python:
      for source_set in project.py_sources:
        pythonpaths.append(create_source_template(base_path(source_set)))
      for source_set in project.py_libs:
        lib_path = source_set.path if source_set.path.endswith('.egg') else '%s/' % source_set.path
        pythonpaths.append(create_source_template(base_path(source_set), includes=[lib_path]))

    configured_project = TemplateData(
      name=self.project_name,
      has_python=project.has_python,
      has_scala=project.has_scala and not project.skip_scala,
      source_bases=source_bases.items(),
      pythonpaths=pythonpaths,
      debug_port=project.debug_port,
    )

    outdir = os.path.abspath(os.path.join(self.work_dir, 'bin'))
    safe_mkdir(outdir)

    source_sets = defaultdict(OrderedSet) # base -> source_set
    for source_set in project.sources:
      source_sets[base_path(source_set)].add(source_set)
    sourcepaths = [create_sourcepath(base, sources) for base, sources in source_sets.items()]

    libs = []
    def add_jarlibs(classpath_entries):
      for classpath_entry in classpath_entries:
        jar = classpath_entry.jar
        source_jar = classpath_entry.source_jar
        libs.append((
          os.path.relpath(jar, self.cwd),
          os.path.relpath(source_jar, self.cwd) if source_jar else None
        ))
    add_jarlibs(project.internal_jars)
    add_jarlibs(project.external_jars)

    configured_classpath = TemplateData(
      sourcepaths=sourcepaths,
      has_tests=project.has_tests,
      libs=libs,
      has_scala = project.has_scala,
      outdir=os.path.relpath(outdir, get_buildroot()),
    )

    with safe_open(self.project_filename, 'w') as output:
      Generator(pkgutil.get_data(__name__, self.project_template),
                project=configured_project).write(output)

    with safe_open(self.classpath_filename, 'w') as output:
      Generator(pkgutil.get_data(__name__, self.classpath_template),
                classpath=configured_classpath).write(output)

    debug_filename = os.path.join(self.work_dir, 'Debug on port %d.launch' % project.debug_port)
    with safe_open(debug_filename, 'w') as output:
      Generator(pkgutil.get_data(__name__, self.debug_template),
                project=configured_project).write(output)

    for resource in _SETTINGS:
      with safe_open(os.path.join(self.cwd, '.settings', resource), 'w') as prefs:
        prefs.write(pkgutil.get_data(__name__, os.path.join('eclipse', 'files', resource)))

    factorypath = TemplateData(
      project_name=self.project_name,

      # The easiest way to make sure eclipse sees all annotation processors is to put all libs on
      # the apt factorypath - this does not seem to hurt eclipse performance in any noticeable way.
      jarpaths=libs
    )
    with open(self.apt_filename, 'w') as output:
      Generator(pkgutil.get_data(__name__, self.apt_template),
                factorypath =factorypath).write(output)

    if project.has_python:
      with safe_open(self.pydev_filename, 'w') as output:
        Generator(pkgutil.get_data(__name__, self.pydev_template),
                  project=configured_project).write(output)
    else:
      if os.path.exists(self.pydev_filename):
        os.remove(self.pydev_filename)

    print('\nGenerated project at %s%s' % (self.work_dir, os.sep))


text:
<?php

class Google_Service_AccessContextManager_EgressPolicy extends Google_Model
{
  protected $egressFromType = 'Google_Service_AccessContextManager_EgressFrom';
  protected $egressFromDataType = '';
  protected $egressToType = 'Google_Service_AccessContextManager_EgressTo';
  protected $egressToDataType = '';

  /**
   * @param Google_Service_AccessContextManager_EgressFrom
   */
  public function setEgressFrom(Google_Service_AccessContextManager_EgressFrom $egressFrom)
  {
    $this->egressFrom = $egressFrom;
  }
  /**
   * @return Google_Service_AccessContextManager_EgressFrom
   */
  public function getEgressFrom()
  {
    return $this->egressFrom;
  }
  /**
   * @param Google_Service_AccessContextManager_EgressTo
   */
  public function setEgressTo(Google_Service_AccessContextManager_EgressTo $egressTo)
  {
    $this->egressTo = $egressTo;
  }
  /**
   * @return Google_Service_AccessContextManager_EgressTo
   */
  public function getEgressTo()
  {
    return $this->egressTo;
  }
}


text:
package io.getlime.security.powerauth.lib.nextstep.model.entity.enumeration;

/**
 * Enum representing an authentication type.
 *
 * @author Roman Strobl, roman.strobl@wultra.com
 */
public enum AuthenticationType {

    /**
     * A credential.
     */
    CREDENTIAL,

    /**
     * An OTP.
     */
    OTP,

    /**
     * Credential and OTP.
     */
    CREDENTIAL_OTP

}


text:
@REM Verify if out of tree patches can be applied.
@IF NOT defined disableootpatch set disableootpatch=0
@set cannotootpatch=0
@if %gitstate%==0 IF NOT EXIST "%msysloc%\usr\bin\patch.exe" IF %toolchain%==msvc set cannotootpatch=1
@IF %cannotootpatch%==1 set disableootpatch=1
@IF %cannotootpatch%==1 echo Error: Git and MSYS2 GNU patch are both missing. Auto-patching disabled. This could have many consequences going all the way up to build failure.
@IF %cannotootpatch%==1 echo.
@IF %disableootpatch%==1 IF %cannotootpatch%==0 echo WARNING: Patching is forcefully disabled for debugging purposes.
@IF %disableootpatch%==1 IF %cannotootpatch%==0 echo.


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>wCMF 4.0: AbstractControllerMessage Class Reference</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="description" content="A MDSD framework for building reliable, maintainable and extendable web applications with PHP">
  <meta name="keywords" content="PHP, web application framework, model driven development">
  <meta name="author" content="wemove digital solutions">
  <link rel="shortcut icon" href="theme/images/favicon.ico">

  <link href="theme/css/doxstyles.css" rel="stylesheet">

  <link href="theme/bootstrap3/css/bootstrap.min.css" rel="stylesheet">
  <link href="theme/bootstrap3/css/font-awesome.min.css" rel="stylesheet">

  <link href="theme/js/tocify/jquery.tocify.css" rel="stylesheet">

  <link href="theme/css/syntax.css" rel="stylesheet">
  <link href="theme/css/style.css" rel="stylesheet">

          <button class="navbar-toggle" type="button" data-toggle="collapse" data-target=".menu-navbar-collapse">
            Toggle navigation
          </button>
          wCMF 4.0

 Guides

Getting started

Architecture

Model

Persistence

Presentation

Configuration

Security

I18n & l10n

Tests

 API

 Code

 Support

                <input id="MSearchField" type="text" class="form-control" placeholder="Search API" name="query" onkeyup="searchBox.OnSearchFieldChange(event)">

wcmf

lib

presentation

impl

AbstractControllerMessage

Public Member Functions |
Protected Member Functions |
List of all members

AbstractControllerMessage Class Reference

Detailed Description

AbstractControllerMessage is the base class for request/response implementations.

Author

ingo herwig ingo@.nosp@m.wemo.nosp@m.ve.co.nosp@m.m

Definition at line 24 of file AbstractControllerMessage.php.

   Inheritance diagram for AbstractControllerMessage:

This browser is not able to show SVG: try Firefox, Chrome, Safari, or Opera instead.

Public Member Functions

 	__construct (Formatter $formatter)

 	setSender ($sender)

 	getSender ()

 	setContext ($context)

 	getContext ()

 	setAction ($action)

 	getAction ()

 	setFormat ($format)

 	getFormat ()

 	setHeader ($name, $value)

 	setHeaders (array $headers)

 	getHeader ($name, $default=null)

 	getHeaders ()

 	clearHeader ($name)

 	clearHeaders ()

 	hasHeader ($name)

 	setValue ($name, $value)

 	setValues (array $values)

 	getValue ($name, $default=null, $filter=null, $options=null)

 	getBooleanValue ($name, $default=false)

 	getValues ()

 	clearValue ($name)

 	clearValues ()

 	hasValue ($name)

 	setProperty ($name, $value)

 	getProperty ($name)

 	addError (ApplicationError $error)

 	setErrors (array $errors)

 	getErrors ()

 	clearErrors ()

 	hasErrors ()

 	__toString ()

Protected Member Functions

 	getFormatter ()

Constructor & Destructor Documentation

          __construct
          (
          Formatter
          $formatter	)

Constructor.

Parameters

$formatter

Definition at line 75 of file AbstractControllerMessage.php.

Member Function Documentation

          setSender
          (

          $sender	)

See also

ControllerMessage::setSender()

Implements ControllerMessage.

Definition at line 82 of file AbstractControllerMessage.php.

          getSender
          (
          	)

See also

ControllerMessage::getSender()

Implements ControllerMessage.

Definition at line 89 of file AbstractControllerMessage.php.

          setContext
          (

          $context	)

See also

ControllerMessage::setContext()

Implements ControllerMessage.

Definition at line 96 of file AbstractControllerMessage.php.

          getContext
          (
          	)

See also

ControllerMessage::getContext()

Implements ControllerMessage.

Definition at line 103 of file AbstractControllerMessage.php.

          setAction
          (

          $action	)

See also

ControllerMessage::setAction()

Implements ControllerMessage.

Definition at line 110 of file AbstractControllerMessage.php.

          getAction
          (
          	)

See also

ControllerMessage::getAction()

Implements ControllerMessage.

Definition at line 117 of file AbstractControllerMessage.php.

          setFormat
          (

          $format	)

See also

ControllerMessage::setFormat()

Implements ControllerMessage.

Definition at line 124 of file AbstractControllerMessage.php.

          getFormat
          (
          	)

See also

ControllerMessage::getFormat()

Implements ControllerMessage.

Definition at line 131 of file AbstractControllerMessage.php.

          setHeader
          (

          $name,

          $value

          )

See also

ControllerMessage::setHeader()

Implements ControllerMessage.

Definition at line 141 of file AbstractControllerMessage.php.

          setHeaders
          (
          array
          $headers	)

See also

ControllerMessage::setHeaders()

Implements ControllerMessage.

Definition at line 148 of file AbstractControllerMessage.php.

          getHeader
          (

          $name,

          $default = null

          )

See also

ControllerMessage::getHeader()

Implements ControllerMessage.

Definition at line 155 of file AbstractControllerMessage.php.

          getHeaders
          (
          	)

See also

ControllerMessage::getHeaders()

Implements ControllerMessage.

Definition at line 167 of file AbstractControllerMessage.php.

          clearHeader
          (

          $name	)

See also

ControllerMessage::clearHeader()

Implements ControllerMessage.

Definition at line 174 of file AbstractControllerMessage.php.

          clearHeaders
          (
          	)

See also

ControllerMessage::clearHeaders()

Implements ControllerMessage.

Definition at line 181 of file AbstractControllerMessage.php.

          hasHeader
          (

          $name	)

See also

ControllerMessage::hasHeader()

Implements ControllerMessage.

Definition at line 188 of file AbstractControllerMessage.php.

          setValue
          (

          $name,

          $value

          )

See also

ControllerMessage::setValue()

Implements ControllerMessage.

Definition at line 195 of file AbstractControllerMessage.php.

          setValues
          (
          array
          $values	)

See also

ControllerMessage::setValues()

Implements ControllerMessage.

Definition at line 202 of file AbstractControllerMessage.php.

          getValue
          (

          $name,

          $default = null,

          $filter = null,

          $options = null

          )

See also

ControllerMessage::getValue()

Implements ControllerMessage.

Definition at line 209 of file AbstractControllerMessage.php.

          getBooleanValue
          (

          $name,

          $default = false

          )

See also

ControllerMessage::getBooleanValue()

Implements ControllerMessage.

Definition at line 222 of file AbstractControllerMessage.php.

          getValues
          (
          	)

See also

ControllerMessage::getValues()

Implements ControllerMessage.

Definition at line 234 of file AbstractControllerMessage.php.

          clearValue
          (

          $name	)

See also

ControllerMessage::clearValue()

Implements ControllerMessage.

Definition at line 241 of file AbstractControllerMessage.php.

          clearValues
          (
          	)

See also

ControllerMessage::clearValues()

Implements ControllerMessage.

Definition at line 248 of file AbstractControllerMessage.php.

          hasValue
          (

          $name	)

See also

ControllerMessage::hasValue()

Implements ControllerMessage.

Definition at line 255 of file AbstractControllerMessage.php.

          setProperty
          (

          $name,

          $value

          )

See also

ControllerMessage::setProperty()

Implements ControllerMessage.

Definition at line 262 of file AbstractControllerMessage.php.

          getProperty
          (

          $name	)

See also

ControllerMessage::getProperty()

Implements ControllerMessage.

Definition at line 269 of file AbstractControllerMessage.php.

          addError
          (
          ApplicationError
          $error	)

See also

ControllerMessage::addError()

Implements ControllerMessage.

Definition at line 279 of file AbstractControllerMessage.php.

          setErrors
          (
          array
          $errors	)

See also

ControllerMessage::setErrors()

Implements ControllerMessage.

Definition at line 286 of file AbstractControllerMessage.php.

          getErrors
          (
          	)

See also

ControllerMessage::getErrors()

Implements ControllerMessage.

Definition at line 293 of file AbstractControllerMessage.php.

          clearErrors
          (
          	)

See also

ControllerMessage::clearErrors()

Implements ControllerMessage.

Definition at line 300 of file AbstractControllerMessage.php.

          hasErrors
          (
          	)

See also

ControllerMessage::hasErrors()

Implements ControllerMessage.

Definition at line 307 of file AbstractControllerMessage.php.

          getFormatter
          (
          	)

protected

Get the Formatter instance.

Returns

Formatter

Definition at line 315 of file AbstractControllerMessage.php.

          __toString
          (
          	)

Get a string representation of the message.

Returns

The string

Definition at line 323 of file AbstractControllerMessage.php.

        © 2016 wemove digital solutions

          Generated on Fri Jul 15 2016 22:20:49 for wCMF by  doxygen 1.8.10


text:
Returns a web part property
##Syntax
```powershell
Get-SPOWebPartProperty -ServerRelativePageUrl <String> -Identity <GuidPipeBind> [-Key <String>] [-Web <WebPipeBind>]
```

##Parameters
Parameter|Type|Required|Description
---------|----|--------|-----------
|Identity|GuidPipeBind|True||
|Key|String|False||
|ServerRelativePageUrl|String|True||
|Web|WebPipeBind|False|The web to apply the command to. Omit this parameter to use the current web.|
##Examples

###Example 1
```powershell
PS:> Get-SPOWebPartProperty -ServerRelativePageUrl /sites/demo/sitepages/home.aspx -Identity ccd2c98a-c9ae-483b-ae72-19992d583914
```
Returns all properties of the webpart.

###Example 2
```powershell
PS:> Get-SPOWebPartProperty -ServerRelativePageUrl /sites/demo/sitepages/home.aspx -Identity ccd2c98a-c9ae-483b-ae72-19992d583914 -Key "Title"
```
Returns the title property of the webpart.


text:
module BootstrapHelper

  def has_error(object, method)
    if object.errors.any? && object.errors.include?(method)
      "has-error"
    end
  end

  def bootstrap_errors(f)
    return "" if f.object.errors.empty?

    content_tag(:div, class: "form-group") do
      content_tag(:div, class: "col-sm-offset-2 col-sm-10") do
        content_tag(:div, class: "panel panel-default panel-danger") do
          content_tag(:div, class: "panel-heading") do
            content_tag(:h2, class: "panel-title") do
              I18n.t("errors.messages.not_saved", :count => f.object.errors.count, :resource => f.object.class.model_name.human.downcase)
            end
          end +
          content_tag(:div, class: "panel-body") do
            content_tag(:ul) do
              f.object.errors.full_messages.map do |msg|
                content_tag(:li, msg)
              end.join.html_safe
            end
          end
        end
      end
    end
  end

  def bootstrap_errors_no_offset(f)
    return "" if f.object.errors.empty?

    content_tag(:div, class: "form-group") do
      content_tag(:div, class: "col-sm-12") do
        content_tag(:div, class: "panel panel-default panel-danger") do
          content_tag(:div, class: "panel-heading") do
            content_tag(:h2, class: "panel-title") do
              I18n.t("errors.messages.not_saved", :count => f.object.errors.count, :resource => f.object.class.model_name.human.downcase)
            end
          end +
          content_tag(:div, class: "panel-body") do
            content_tag(:ul) do
              f.object.errors.full_messages.map do |msg|
                content_tag(:li, msg)
              end.join.html_safe
            end
          end
        end
      end
    end
  end

  def validation_state?(success, danger = false)
    return "error" if danger
    if success
      "success"
    else
      "warning"
    end
  end

  def panel_validation_state?(success, danger = false)
    return "danger" if danger
    if success == true
      "success"
    else
      "warning"
    end
  end

  def default_or_danger?(boolean_value)
    if boolean_value
      "default"
    else
      "danger"
    end
  end

  def success_or_warning?(boolean_value)
    if boolean_value
      "success"
    else
      "warning"
    end
  end

  def success_or_danger?(boolean_value)
    if boolean_value
      "success"
    else
      "danger"
    end
  end

  def success?(boolean_value)
    "success" if boolean_value
  end
end


text: This package supports .netframework 4.5+ and netstandard1.0+.


text:
// Provides control sap.m.StandardListItem.
sap.ui.define([
	"sap/ui/core/library",
	"sap/ui/core/IconPool",
	"./library",
	"./ListItemBase",
	"./Image",
	"./StandardListItemRenderer"
],
	function(coreLibrary, IconPool, library, ListItemBase, Image, StandardListItemRenderer) {
	"use strict";

	// shortcut for sap.ui.core.TextDirection
	var TextDirection = coreLibrary.TextDirection;

	// shortcut for sap.ui.core.ValueState
	var ValueState = coreLibrary.ValueState;

	/**
	 * Constructor for a new StandardListItem.
	 *
	 * @param {string} [sId] Id for the new control, generated automatically if no id is given
	 * @param {object} [mSettings] Initial settings for the new control
	 *
	 * @class
	 * sap.m.StandardListItem is a list item providing the most common use cases, e.g. image, title and description.
	 * @extends sap.m.ListItemBase
	 *
	 * @author SAP SE
	 * @version ${version}
	 *
	 * @constructor
	 * @public
	 * @alias sap.m.StandardListItem
	 * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
	 */
	var StandardListItem = ListItemBase.extend("sap.m.StandardListItem", /** @lends sap.m.StandardListItem.prototype */ { metadata : {

		library : "sap.m",
		properties : {

			/**
			 * Defines the title of the list item.
			 */
			title : {type : "string", group : "Misc", defaultValue : null},

			/**
			 * Defines the additional information for the title.
			 * Note: This is only visible when the title property is not empty.
			 */
			description : {type : "string", group : "Misc", defaultValue : null},

			/**
			 * Defines the list item icon.
			 */
			icon : {type : "sap.ui.core.URI", group : "Misc", defaultValue : null},

			/**
			 * Defines the indentation of the icon. If set to false, the icon will not be shown as embedded. Instead it will take the full height of the list item.
			 */
			iconInset : {type : "boolean", group : "Appearance", defaultValue : true},

			/**
			 * By default, one or more requests are sent to get the density perfect version of the icon if the given version of the icon doesn't exist on the server.
			 * Note: If bandwidth is a key factor for the application, set this value to false.
			 */
			iconDensityAware : {type : "boolean", group : "Misc", defaultValue : true},

			/**
			 * Defines the icon that is shown while the list item is pressed.
			 */
			activeIcon : {type : "sap.ui.core.URI", group : "Misc", defaultValue : null},

			/**
			 * Defines an additional information text.
			 */
			info : {type : "string", group : "Misc", defaultValue : null},

			/**
			 * Defines the state of the information text, e.g. Error, Warning, Success.
			 */
			infoState : {type : "sap.ui.core.ValueState", group : "Misc", defaultValue : ValueState.None},

			/**
			 * By default, the title size adapts to the available space and gets bigger if the description is empty. If you have list items with and without descriptions, this results in titles with different sizes. In this case, it can be better to switch the size adaption off by setting this property to false.
			 * @since 1.16.3
			 */
			adaptTitleSize : {type : "boolean", group : "Appearance", defaultValue : true},

			/**
			 * Defines the title text directionality with enumerated options. By default, the control inherits text direction from the DOM.
			 * @since 1.28.0
			 */
			titleTextDirection : {type : "sap.ui.core.TextDirection", group : "Appearance", defaultValue : TextDirection.Inherit},

			/**
			 * Defines the info directionality with enumerated options. By default, the control inherits text direction from the DOM.
			 * @since 1.28.0
			 */
			infoTextDirection : {type : "sap.ui.core.TextDirection", group : "Appearance", defaultValue : TextDirection.Inherit}
		},
		designtime: "sap/m/designtime/StandardListItem.designtime"
	}});

	StandardListItem.prototype.exit = function() {
		if (this._oImage) {
			this._oImage.destroy("KeepDom");
		}

		ListItemBase.prototype.exit.apply(this, arguments);
	};

	StandardListItem.prototype.setIcon = function(sIcon) {
		var sOldIcon = this.getIcon();
		this.setProperty("icon", sIcon);

		// destroy the internal control if it is changed from Icon to Image or Image to Icon
		if (this._oImage && (!sIcon || IconPool.isIconURI(sIcon) != IconPool.isIconURI(sOldIcon))) {
			this._oImage.destroy("KeepDom");
			this._oImage = undefined;
		}

		return this;
	};

	/**
	 * @private
	 */
	StandardListItem.prototype._getImage = function() {
		var oImage = this._oImage;

		if (oImage) {
			oImage.setSrc(this.getIcon());
			if (oImage.setDensityAware) {
				oImage.setDensityAware(this.getIconDensityAware());
			}
		} else {
			oImage = IconPool.createControlByURI({
				id: this.getId() + "-img",
				src: this.getIcon(),
				densityAware: this.getIconDensityAware(),
				useIconTooltip: false
			}, Image).setParent(this, null, true);
		}

		var sImgStyle = this.getIconInset() ? "sapMSLIImg" : "sapMSLIImgThumb";
		oImage.addStyleClass(oImage instanceof Image ? sImgStyle : sImgStyle + "Icon", true);

		this._oImage = oImage;
		return this._oImage;
	};

	// overwrite base method to hook into the active handling
	StandardListItem.prototype._activeHandlingInheritor = function() {
		if (this._oImage) {
			var sActiveIcon = this.getActiveIcon();
			sActiveIcon && this._oImage.setSrc(sActiveIcon);
		}
	};

	// overwrite base method to hook into the inactive handling
	StandardListItem.prototype._inactiveHandlingInheritor = function() {
		if (this._oImage) {
			this._oImage.setSrc(this.getIcon());
		}
	};

	StandardListItem.prototype.getContentAnnouncement = function(oBundle) {
		var sAnnouncement = "",
			sInfoState = this.getInfoState(),
			oIconInfo = IconPool.getIconInfo(this.getIcon()) || {};

		sAnnouncement += (oIconInfo.text || oIconInfo.name || "") + " ";
		sAnnouncement += this.getTitle() + " " + this.getDescription() + " " + this.getInfo() + " ";

		if (sInfoState != "None" && sInfoState != this.getHighlight()) {
			sAnnouncement += oBundle.getText("LIST_ITEM_STATE_" + sInfoState.toUpperCase());
		}

		return sAnnouncement;
	};

	return StandardListItem;

});


text:
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace AccidentalFish.ApplicationSupport.Core.Repository
{
    /// <summary>
    /// Repository pattern for use with an ORM that supports asynchronous access
    /// </summary>
    /// <typeparam name="T">The type of the objects represented by the repository</typeparam>
    public interface IRepositoryAsync<T> where T : class
    {
        /// <summary>
        /// Get an IQueryable interface for the repository
        /// </summary>
        IQueryable<T> All { get; }
        /// <summary>
        /// Get an IQueryable interface for the repository including child object / collection references
        /// </summary>
        /// <param name="includeProperties">The child object / collection references to also fetch</param>
        /// <returns>An IQueryable interface</returns>
        IQueryable<T> AllIncluding(params Expression<Func<T, object>>[] includeProperties);
        /// <summary>
        /// Find the entity with the specified integer ID
        /// </summary>
        /// <param name="id">The ID to use to locate the entity</param>
        /// <returns>An entity reference or null if not found</returns>
        Task<T> FindAsync(int id);
        /// <summary>
        /// Insert or update the entity using idFunc to return the ID of the entity
        /// </summary>
        /// <param name="entity">The entity to insert or update</param>
        /// <param name="idFunc">Function that provides the ID of the entity</param>
        void InsertOrUpdate(T entity, Func<T, int> idFunc);
        /// <summary>
        /// Insert the given entity
        /// </summary>
        /// <param name="entity">The entity to insert</param>
        void Insert(T entity);
        /// <summary>
        /// Update the entity
        /// </summary>
        /// <param name="entity">The entity to update</param>
        void Update(T entity);
        /// <summary>
        /// Delete the entity
        /// </summary>
        /// <param name="entity">The entity to delete</param>
        void Delete(T entity);
        /// <summary>
        /// Delete the entity with the given ID
        /// </summary>
        /// <param name="id">The primary key of the entity to delete</param>
        Task DeleteAsync(int id);

    }
}