text:
require 'rubyXL/objects/ooxml_object'
require 'rubyXL/objects/simple_types'
require 'rubyXL/objects/extensions'

module RubyXL

  # Eventually, the entire code for Workbook will be moved here.

  # http://www.schemacentral.com/sc/ooxml/e-ssml_fileVersion-1.html
  class FileVersion < OOXMLObject
    define_attribute(:appName,      :string)
    define_attribute(:lastEdited,   :string)
    define_attribute(:lowestEdited, :string)
    define_attribute(:rupBuild,     :string)
    define_attribute(:codeName,     :string)
    define_element_name 'fileVersion'
  end

  # http://www.schemacentral.com/sc/ooxml/e-ssml_fileSharing-1.html
  class FileSharing < OOXMLObject
    define_attribute(:readOnlyRecommended, :bool, :default => false)
    define_attribute(:userName,            :string)
    define_attribute(:reservationPassword, :string)
    define_element_name 'fileSharing'
  end

  # http://www.schemacentral.com/sc/ooxml/e-ssml_workbookPr-1.html
  class WorkbookProperties < OOXMLObject
    define_attribute(:date1904,                   :bool,   :default => false)
    define_attribute(:showObjects,                RubyXL::ST_Objects, :default => 'all')
    define_attribute(:showBorderUnselectedTables, :bool,   :default => true)
    define_attribute(:filterPrivacy,              :bool,   :default => false)
    define_attribute(:promptedSolutions,          :bool,   :default => false)
    define_attribute(:showInkAnnotation,          :bool,   :default => true)
    define_attribute(:backupFile,                 :bool,   :default => false)
    define_attribute(:saveExternalLinkValues,     :bool,   :default => true)
    define_attribute(:updateLinks,                RubyXL::ST_UpdateLinks, :default => 'userSet')
    define_attribute(:hidePivotFieldList,         :bool,   :default => false)
    define_attribute(:showPivotChartFilter,       :bool,   :default => false)
    define_attribute(:allowRefreshQuery,          :bool,   :default => false)
    define_attribute(:publishItems,               :bool,   :default => false)
    define_attribute(:checkCompatibility,         :bool,   :default => false)
    define_attribute(:autoCompressPictures,       :bool,   :default => true)
    define_attribute(:refreshAllConnections,      :bool,   :default => false)
    define_attribute(:defaultThemeVersion,        :int)
    define_attribute(:codeName,                   :string)
    define_element_name 'workbookPr'
  end

  # http://www.schemacentral.com/sc/ooxml/e-ssml_workbookProtection-1.html
  class WorkbookProtection < OOXMLObject
    define_attribute(:workbookPassword,  :string)
    define_attribute(:revisionsPassword, :string)
    define_attribute(:lockStructure,     :bool,   :default => false)
    define_attribute(:lockWindows,       :bool,   :default => false)
    define_attribute(:lockRevision,      :bool,   :default => false)
    define_element_name 'workbookProtection'
  end

  # http://www.schemacentral.com/sc/ooxml/e-ssml_workbookView-1.html
  class WorkbookView < OOXMLObject
    define_attribute(:visibility,             RubyXL::ST_Visibility, :default => 'visible')
    define_attribute(:minimized,              :bool,   :default => false)
    define_attribute(:showHorizontalScroll,   :bool,   :default => true)
    define_attribute(:showVerticalScroll,     :bool,   :default => true)
    define_attribute(:showSheetTabs,          :bool,   :default => true)
    define_attribute(:xWindow,                :int)
    define_attribute(:yWindow,                :int)
    define_attribute(:windowWidth,            :int)
    define_attribute(:windowHeight,           :int)
    define_attribute(:tabRatio,               :int,    :default => 600)
    define_attribute(:firstSheet,             :int,    :default => 0)
    define_attribute(:activeTab,              :int,    :default => 0)
    define_attribute(:autoFilterDateGrouping, :bool,   :default => true)
    define_child_node(RubyXL::ExtensionStorageArea)
    define_element_name 'workbookView'
  end

  # http://www.schemacentral.com/sc/ooxml/e-ssml_bookViews-1.html
  class WorkbookViews < OOXMLContainerObject
    define_child_node(RubyXL::WorkbookView, :collection => true)
    define_element_name 'bookViews'
  end

  # http://www.schemacentral.com/sc/ooxml/e-ssml_sheet-1.html
  class Sheet < OOXMLObject
    define_attribute(:name,            :string, :required => true)
    define_attribute(:sheetId,         :int,    :required => true)
    define_attribute(:state,           RubyXL::ST_Visibility, :default => 'visible')
    define_attribute(:'r:id',          :string, :required => true)
    define_element_name 'sheet'
  end

  # http://www.schemacentral.com/sc/ooxml/e-ssml_sheets-1.html
  class Sheets < OOXMLContainerObject
    define_child_node(RubyXL::Sheet, :collection => true)
    define_element_name 'sheets'
  end

  # http://www.schemacentral.com/sc/ooxml/e-ssml_externalReference-1.html
  class ExternalReference < OOXMLObject
    define_attribute(:'r:id', :string, :required => true)
    define_element_name 'externalReference'
  end

  # http://www.schemacentral.com/sc/ooxml/e-ssml_externalReferences-1.html
  class ExternalReferences < OOXMLContainerObject
    define_child_node(RubyXL::ExternalReference, :collection => true)
    define_element_name 'externalReferences'
  end

  # http://www.schemacentral.com/sc/ooxml/e-ssml_definedName-2.html
  class DefinedName < OOXMLObject
    define_attribute(:name,              :string, :required => true)
    define_attribute(:comment,           :string)
    define_attribute(:customMenu,        :string)
    define_attribute(:description,       :string)
    define_attribute(:help,              :string)
    define_attribute(:description,       :string)
    define_attribute(:localSheetId,      :string)

    define_attribute(:hidden,            :bool, :default => false)
    define_attribute(:function,          :bool, :default => false)
    define_attribute(:vbProcedure,       :bool, :default => false)
    define_attribute(:xlm,               :bool, :default => false)

    define_attribute(:functionGroupId,   :int)
    define_attribute(:shortcutKey,       :string)
    define_attribute(:publishToServer,   :bool, :default => false)
    define_attribute(:workbookParameter, :bool, :default => false)

    define_attribute(:_,                 :string, :accessor => :reference)
    define_element_name 'definedName'
  end

  # http://www.schemacentral.com/sc/ooxml/e-ssml_definedName-2.html
  class DefinedNames < OOXMLContainerObject
    define_child_node(RubyXL::DefinedName, :collection => true)
    define_element_name 'definedNames'
  end

  # http://www.schemacentral.com/sc/ooxml/e-ssml_pivotCache-1.html
  class PivotCache < OOXMLObject
    define_attribute(:cacheId, :int,    :required => true)
    define_attribute(:'r:id',  :string, :required => true)
    define_element_name 'pivotCache'
  end

  # http://www.schemacentral.com/sc/ooxml/e-ssml_pivotCaches-1.html
  class PivotCaches < OOXMLContainerObject
    define_child_node(RubyXL::PivotCache, :collection => true)
    define_element_name 'pivotCaches'
  end

  # http://www.schemacentral.com/sc/ooxml/e-ssml_oleSize-1.html
  class OLESize < OOXMLObject
    define_attribute(:ref, :ref, :required => true)
    define_element_name 'oleSize'
  end

  # http://www.schemacentral.com/sc/ooxml/e-ssml_fileRecoveryPr-1.html
  class FileRecoveryProperties < OOXMLObject
    define_attribute(:autoRecover,     :bool, :default => true)
    define_attribute(:crashSave,       :bool, :default => false)
    define_attribute(:dataExtractLoad, :bool, :default => false)
    define_attribute(:repairLoad,      :bool, :default => false)
    define_element_name 'fileRecoveryPr'
  end

  # http://www.schemacentral.com/sc/ooxml/e-ssml_webPublishing-1.html
  class WebPublishingProperties < OOXMLObject
    define_attribute(:css,              :bool,   :default => true)
    define_attribute(:thicket,          :bool,   :default => true)
    define_attribute(:longFileNames,    :bool,   :default => true)
    define_attribute(:vml,              :bool,   :default => false)
    define_attribute(:allowPng,         :bool,   :default => false)
    define_attribute(:targetScreenSize, RubyXL::ST_TargetScreenSize, :default => '800x600')
    define_attribute(:dpi,              :int,    :default => 96)
    define_attribute(:codePage,         :int)
    define_element_name 'webPublishing'
  end

  # http://www.schemacentral.com/sc/ooxml/e-ssml_calcPr-1.html
  class CalculationProperties < OOXMLObject
    define_attribute(:calcId,                :int)
    define_attribute(:calcMode,              RubyXL::ST_CalcMode, :default => 'auto')
    define_attribute(:fullCalcOnLoad,        :bool,   :default => false)
    define_attribute(:refMode,               RubyXL::ST_RefMode, :default => 'A1')
    define_attribute(:iterate,               :bool,   :default => false)
    define_attribute(:iterateCount,          :int,    :default => 100)
    define_attribute(:iterateDelta,          :double, :default => 0.001)
    define_attribute(:fullPrecision,         :bool,   :default => true)
    define_attribute(:calcCompleted,         :bool,   :default => true)
    define_attribute(:calcOnSave,            :bool,   :default => true)
    define_attribute(:concurrentCalc,        :bool,   :default => true)
    define_attribute(:concurrentManualCount, :int)
    define_attribute(:forceFullCalc,         :bool)
    define_element_name 'calcPr'
  end

  # http://www.schemacentral.com/sc/ooxml/e-ssml_webPublishObject-1.html
  class WebPublishObject < OOXMLObject
    define_attribute(:id,              :int,    :required => true)
    define_attribute(:divId,           :string, :required => true)
    define_attribute(:sourceObject,    :string)
    define_attribute(:destinationFile, :string, :required => true)
    define_attribute(:title,           :string)
    define_attribute(:autoRepublish,   :bool,   :default => false)
    define_element_name 'webPublishObject'
  end

  # http://www.schemacentral.com/sc/ooxml/e-ssml_webPublishObjects-1.html
  class WebPublishObjects < OOXMLContainerObject
    define_child_node(RubyXL::WebPublishObject, :collection => :with_count)
    define_element_name 'webPublishObjects'
  end

  # http://www.schemacentral.com/sc/ooxml/e-ssml_smartTagPr-1.html
  class SmartTagProperties < OOXMLObject
    define_attribute(:embed, :bool,   :default => false)
    define_attribute(:show,  RubyXL::ST_SmartTagShow, :default => 'all')
    define_element_name 'smartTagPr'
  end

  # http://www.schemacentral.com/sc/ooxml/e-ssml_smartTagType-1.html
  class SmartTagType < OOXMLObject
    define_attribute(:namespaceUri, :string)
    define_attribute(:name,         :string)
    define_attribute(:url,          :string)
    define_element_name 'smartTagType'
  end

  # http://www.schemacentral.com/sc/ooxml/e-ssml_smartTagTypes-1.html
  class SmartTagTypes < OOXMLContainerObject
    define_child_node(RubyXL::SmartTagType, :collection => :true)
    define_element_name 'smartTagTypes'
  end

  # http://www.schemacentral.com/sc/ooxml/e-ssml_functionGroup-1.html
  class FunctionGroup < OOXMLObject
    define_attribute(:name, :string)
    define_element_name 'functionGroup'
  end

  # http://www.schemacentral.com/sc/ooxml/e-ssml_functionGroups-1.html
  class FunctionGroups < OOXMLContainerObject
    define_attribute(:builtInGroupCountpi, :int, :default => 16)
    define_child_node(RubyXL::FunctionGroup, :collection => :true)
    define_element_name 'functionGroups'
  end

  # http://www.schemacentral.com/sc/ooxml/e-ssml_customWorkbookView-1.html
  class CustomWorkbookView < OOXMLObject
    define_attribute(:name,                 :string, :required => true)
    define_attribute(:guid,                 :string, :required => true)
    define_attribute(:autoUpdate,           :bool,   :default => false)
    define_attribute(:mergeInterval,        :int)
    define_attribute(:changesSavedWin,      :bool,   :default => false)
    define_attribute(:onlySync,             :bool,   :default => false)
    define_attribute(:personalView,         :bool,   :default => false)
    define_attribute(:includePrintSettings, :bool,   :default => true)
    define_attribute(:includeHiddenRowCol,  :bool,   :default => true)
    define_attribute(:maximized,            :bool,   :default => false)
    define_attribute(:minimized,            :bool,   :default => false)
    define_attribute(:showHorizontalScroll, :bool,   :default => true)
    define_attribute(:showVerticalScroll,   :bool,   :default => true)
    define_attribute(:showSheetTabs,        :bool,   :default => true)
    define_attribute(:xWindow,              :int,    :default => 0)
    define_attribute(:yWindow,              :int,    :default => 0)
    define_attribute(:windowWidth,          :int)
    define_attribute(:windowHeight,         :int)
    define_attribute(:tabRatio,             :int,    :default => 600)
    define_attribute(:activeSheetId,        :int)
    define_attribute(:showFormulaBar,       :bool,   :default => true)
    define_attribute(:showStatusbar,        :bool,   :default => true)
    define_attribute(:showComments,         RubyXL::ST_Comments, :default => 'commIndicator')
    define_attribute(:showObjects,          RubyXL::ST_Objects,  :default => 'all')
    define_child_node(RubyXL::ExtensionStorageArea)
    define_element_name 'customWorkbookView'
  end

  # http://www.schemacentral.com/sc/ooxml/e-ssml_customWorkbookViews-1.html
  class CustomWorkbookViews < OOXMLContainerObject
    define_child_node(RubyXL::CustomWorkbookView, :collection => true)
    define_element_name 'customWorkbookViews'
  end

  # http://www.schemacentral.com/sc/ooxml/e-ssml_workbook.html
  class Workbook < OOXMLTopLevelObject
    CONTENT_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml'
    REL_TYPE     = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument'
    REL_CLASS    = RubyXL::WorkbookRelationships

    include RubyXL::RelationshipSupport

    def related_objects
      [ calculation_chain, stylesheet, theme, shared_strings_container ] + @worksheets
    end

    define_relationship(RubyXL::SharedStringsTable, :shared_strings_container)
    define_relationship(RubyXL::Stylesheet,         :stylesheet)
    define_relationship(RubyXL::Theme,              :theme)
    define_relationship(RubyXL::CalculationChain,   :calculation_chain)
    define_relationship(RubyXL::Stylesheet,         :stylesheet)
    define_relationship(RubyXL::Worksheet,          false)
    define_relationship(RubyXL::Chartsheet,         false)
    define_relationship(RubyXL::ExternalLinksFile)
    define_relationship(RubyXL::PivotCacheDefinitionFile)
    define_relationship(RubyXL::CustomXMLFile)
    define_relationship(RubyXL::MacrosFile)
    define_relationship(RubyXL::SlicerCacheFile)

    define_child_node(RubyXL::FileVersion)
    define_child_node(RubyXL::FileSharing)
    define_child_node(RubyXL::WorkbookProperties, :accessor => :workbook_properties)
    define_child_node(RubyXL::AlternateContent) # Somehow, order matters here
    define_child_node(RubyXL::WorkbookProtection)
    define_child_node(RubyXL::WorkbookViews)
    define_child_node(RubyXL::Sheets)
    define_child_node(RubyXL::FunctionGroups)
    define_child_node(RubyXL::ExternalReferences)
    define_child_node(RubyXL::DefinedNames)
    define_child_node(RubyXL::CalculationProperties)
    define_child_node(RubyXL::OLESize)
    define_child_node(RubyXL::CustomWorkbookViews)
    define_child_node(RubyXL::PivotCaches)
    define_child_node(RubyXL::SmartTagProperties)
    define_child_node(RubyXL::SmartTagTypes)
    define_child_node(RubyXL::WebPublishingProperties)
    define_child_node(RubyXL::FileRecoveryProperties)
    define_child_node(RubyXL::WebPublishObjects)
    define_child_node(RubyXL::ExtensionStorageArea)

    define_element_name 'workbook'
    set_namespaces('http://schemas.openxmlformats.org/spreadsheetml/2006/main' => '',
                   'http://schemas.openxmlformats.org/officeDocument/2006/relationships' => 'r',
                   'http://schemas.openxmlformats.org/markup-compatibility/2006' => 'mc',
                   'http://schemas.microsoft.com/office/spreadsheetml/2010/11/main' => 'x15')

    attr_accessor :root
    attr_accessor :calculation_chain, :theme, :stylesheet, :shared_strings_container, :worksheets

    def before_write_xml
      self.sheets = RubyXL::Sheets.new

      worksheets.each_with_index { |sheet, i|
        rel = relationship_container.find_by_target(sheet.xlsx_path.gsub(/\Axl\//, ''))
        sheets << RubyXL::Sheet.new(:name => sheet.sheet_name[0..30], # Max sheet name length is 31 char
                                    :sheet_id => sheet.sheet_id || (i + 1),
                                    :state => sheet.state, :r_id => rel.id)
      }
      true
    end

    def date1904
      workbook_properties && workbook_properties.date1904
    end

    def date1904=(v)
      self.workbook_properties ||= RubyXL::WorkbookProperties.new
      workbook_properties.date1904 = v
    end

    def company
      self.document_properties.company && self.document_properties.company.value
    end

    def company=(v)
      root.document_properties.company ||= StringNode.new
      root.document_properties.company.value = v
    end

    def application
      root.document_properties.application && self.document_properties.application.value
    end

    def application=(v)
      root.document_properties.application ||= StringNode.new
      root.document_properties.application.value = v
    end

    def appversion
      root.document_properties.app_version && root.document_properties.app_version.value
    end

    def appversion=(v)
      root.document_properties.app_version ||= StringNode.new
      root.document_properties.app_version.value = v
    end

    def creator
      root.core_properties.creator
    end

    def creator=(v)
      root.core_properties.creator = v
    end

    def modifier
      root.core_properties.modifier
    end

    def modifier=(v)
      root.core_properties.modifier = v
    end

    def created_at
      root.core_properties.created_at
    end

    def created_at=(v)
      root.core_properties.created_at = v
    end

    def modified_at
      root.core_properties.modified_at
    end

    def modified_at=(v)
      root.core_properties.modified_at = v
    end

    def xlsx_path
      File.join('xl', 'workbook.xml')
    end

    include LegacyWorkbook

  end

end


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;

namespace etag
{
    class Program
    {
        private static readonly Uri _searchMetadataUri = new Uri("https://go.microsoft.com/fwlink/?linkid=2087906&clcid=0x409");
        private const string EtagFileName = "etag.txt";

        static void Main(string[] args)
        {
            using (HttpClient client = new HttpClient())
            {
                if(File.Exists(EtagFileName))
                {
                    client.DefaultRequestHeaders.Add("If-None-Match", $"\"{File.ReadAllText(EtagFileName)}\"");
                }

                using (HttpResponseMessage response = client.GetAsync(_searchMetadataUri).Result)
                {
                    if (response.IsSuccessStatusCode)
                    {
                        string resultText = response.Content.ReadAsStringAsync().Result;
                        GC.KeepAlive(resultText);
                        IEnumerable<string> etagValues;
                        if(response.Headers.TryGetValues("ETag", out etagValues))
                        {
                            if (etagValues.Count() == 1)
                            {
                                File.WriteAllText(EtagFileName, etagValues.First());
                            }
                        }
                    }
                }
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package v20

import (
	"fmt"

	"github.com/golang/protobuf/proto"
	"github.com/hyperledger/fabric-protos-go/common"
	"github.com/hyperledger/fabric-protos-go/peer"
	commonerrors "github.com/hyperledger/fabric/common/errors"
	"github.com/hyperledger/fabric/common/flogging"
	"github.com/hyperledger/fabric/core/common/validation/statebased"
	vc "github.com/hyperledger/fabric/core/handlers/validation/api/capabilities"
	vi "github.com/hyperledger/fabric/core/handlers/validation/api/identities"
	vp "github.com/hyperledger/fabric/core/handlers/validation/api/policies"
	vs "github.com/hyperledger/fabric/core/handlers/validation/api/state"
	"github.com/hyperledger/fabric/protoutil"
	"github.com/pkg/errors"
)

var logger = flogging.MustGetLogger("vscc")

//go:generate mockery -dir . -name IdentityDeserializer -case underscore -output mocks/

// IdentityDeserializer is the local interface that used to generate mocks for foreign interface.
type IdentityDeserializer interface {
	vi.IdentityDeserializer
}

//go:generate mockery -dir . -name CollectionResources -case underscore -output mocks/

// CollectionResources is the local interface that used to generate mocks for foreign interface.
type CollectionResources interface {
	statebased.CollectionResources
}

//go:generate mockery -dir . -name StateBasedValidator -case underscore -output mocks/

// toApplicationPolicyTranslator implements statebased.PolicyTranslator
// by translating SignaturePolicyEnvelope policies into ApplicationPolicy
// ones; this is required because the 2.0 validator is supplied with a
// policy evaluator that can only understand ApplicationPolicy policies.
type toApplicationPolicyTranslator struct{}

func (n *toApplicationPolicyTranslator) Translate(b []byte) ([]byte, error) {
	if len(b) == 0 {
		return b, nil
	}

	spe := &common.SignaturePolicyEnvelope{}
	err := proto.Unmarshal(b, spe)
	if err != nil {
		return nil, errors.Wrap(err, "could not unmarshal signature policy envelope")
	}

	return protoutil.MarshalOrPanic(&peer.ApplicationPolicy{
		Type: &peer.ApplicationPolicy_SignaturePolicy{
			SignaturePolicy: spe,
		},
	}), nil
}

// New creates a new instance of the default VSCC
// Typically this will only be invoked once per peer
func New(c vc.Capabilities, s vs.StateFetcher, d vi.IdentityDeserializer, pe vp.PolicyEvaluator, cor statebased.CollectionResources) *Validator {
	vpmgr := &statebased.KeyLevelValidationParameterManagerImpl{
		StateFetcher:     s,
		PolicyTranslator: &toApplicationPolicyTranslator{},
	}
	eval := statebased.NewV20Evaluator(vpmgr, pe, cor, s)
	sbv := statebased.NewKeyLevelValidator(eval, vpmgr)

	return &Validator{
		capabilities:        c,
		stateFetcher:        s,
		deserializer:        d,
		policyEvaluator:     pe,
		stateBasedValidator: sbv,
	}
}

// Validator implements the default transaction validation policy,
// which is to check the correctness of the read-write set and the endorsement
// signatures against an endorsement policy that is supplied as argument to
// every invoke
type Validator struct {
	deserializer        vi.IdentityDeserializer
	capabilities        vc.Capabilities
	stateFetcher        vs.StateFetcher
	policyEvaluator     vp.PolicyEvaluator
	stateBasedValidator StateBasedValidator
}

type validationArtifacts struct {
	rwset        []byte
	prp          []byte
	endorsements []*peer.Endorsement
	chdr         *common.ChannelHeader
	env          *common.Envelope
	payl         *common.Payload
	cap          *peer.ChaincodeActionPayload
}

func (vscc *Validator) extractValidationArtifacts(
	block *common.Block,
	txPosition int,
	actionPosition int,
) (*validationArtifacts, error) {
	// get the envelope...
	env, err := protoutil.GetEnvelopeFromBlock(block.Data.Data[txPosition])
	if err != nil {
		logger.Errorf("VSCC error: GetEnvelope failed, err %s", err)
		return nil, err
	}

	// ...and the payload...
	payl, err := protoutil.UnmarshalPayload(env.Payload)
	if err != nil {
		logger.Errorf("VSCC error: GetPayload failed, err %s", err)
		return nil, err
	}

	chdr, err := protoutil.UnmarshalChannelHeader(payl.Header.ChannelHeader)
	if err != nil {
		return nil, err
	}

	// validate the payload type
	if common.HeaderType(chdr.Type) != common.HeaderType_ENDORSER_TRANSACTION {
		logger.Errorf("Only Endorser Transactions are supported, provided type %d", chdr.Type)
		err = fmt.Errorf("Only Endorser Transactions are supported, provided type %d", chdr.Type)
		return nil, err
	}

	// ...and the transaction...
	tx, err := protoutil.UnmarshalTransaction(payl.Data)
	if err != nil {
		logger.Errorf("VSCC error: GetTransaction failed, err %s", err)
		return nil, err
	}

	cap, err := protoutil.UnmarshalChaincodeActionPayload(tx.Actions[actionPosition].Payload)
	if err != nil {
		logger.Errorf("VSCC error: GetChaincodeActionPayload failed, err %s", err)
		return nil, err
	}

	pRespPayload, err := protoutil.UnmarshalProposalResponsePayload(cap.Action.ProposalResponsePayload)
	if err != nil {
		err = fmt.Errorf("GetProposalResponsePayload error %s", err)
		return nil, err
	}
	if pRespPayload.Extension == nil {
		err = fmt.Errorf("nil pRespPayload.Extension")
		return nil, err
	}
	respPayload, err := protoutil.UnmarshalChaincodeAction(pRespPayload.Extension)
	if err != nil {
		err = fmt.Errorf("GetChaincodeAction error %s", err)
		return nil, err
	}

	return &validationArtifacts{
		rwset:        respPayload.Results,
		prp:          cap.Action.ProposalResponsePayload,
		endorsements: cap.Action.Endorsements,
		chdr:         chdr,
		env:          env,
		payl:         payl,
		cap:          cap,
	}, nil
}

// Validate validates the given envelope corresponding to a transaction with an endorsement
// policy as given in its serialized form.
// Note that in the case of dependencies in a block, such as tx_n modifying the endorsement policy
// for key a and tx_n+1 modifying the value of key a, Validate(tx_n+1) will block until Validate(tx_n)
// has been resolved. If working with a limited number of goroutines for parallel validation, ensure
// that they are allocated to transactions in ascending order.
func (vscc *Validator) Validate(
	block *common.Block,
	namespace string,
	txPosition int,
	actionPosition int,
	policyBytes []byte,
) commonerrors.TxValidationError {
	vscc.stateBasedValidator.PreValidate(uint64(txPosition), block)

	va, err := vscc.extractValidationArtifacts(block, txPosition, actionPosition)
	if err != nil {
		vscc.stateBasedValidator.PostValidate(namespace, block.Header.Number, uint64(txPosition), err)
		return policyErr(err)
	}

	txverr := vscc.stateBasedValidator.Validate(
		namespace,
		block.Header.Number,
		uint64(txPosition),
		va.rwset,
		va.prp,
		policyBytes,
		va.endorsements,
	)
	if txverr != nil {
		logger.Errorf("VSCC error: stateBasedValidator.Validate failed, err %s", txverr)
		vscc.stateBasedValidator.PostValidate(namespace, block.Header.Number, uint64(txPosition), txverr)
		return txverr
	}

	vscc.stateBasedValidator.PostValidate(namespace, block.Header.Number, uint64(txPosition), nil)
	return nil
}

func policyErr(err error) *commonerrors.VSCCEndorsementPolicyError {
	return &commonerrors.VSCCEndorsementPolicyError{
		Err: err,
	}
}


text:
/*! angular-facebook-insight - v0.6.1 - 2014-07-13
* Copyright (c) 2014 ; Licensed  */
'use strict';

angular.module("angular-s3-upload-tpls", ["templates/angular-s3-upload-button.html"]);
'use strict';

var ngS3Upload = angular.module('angular-s3-upload', ["angular-s3-upload-tpls"]);
ngS3Upload.directive('ngS3Upload', [ '$upload', '$q', function($upload, $q) {
  return {
    restrict: 'EA',
    replace: true,
    scope: {
      label: '@',
      uploadHelper: '=',
      buttonClass: '@',
      index: '=',
      key: '@',
      path: '@',
      successCallback: '=',
      failureCallback: '=',
      progressCallback: '=',
      awsApi:'=',
      bucket: '@',
      filename: '@',
      maxWidth: '@',
      maxHeight: '@'
    },
    templateUrl: 'templates/angular-s3-upload-button.html',
    link: function(scope, element, attr) {
      scope.awsApi.getAWSToken(scope.key).then(function(data){
        scope.aws = {};
        scope.aws.policy = data.policy;
        scope.aws.signature = data.signature;
        scope.aws.key = data.key;
      }, function(err){
        if (typeof scope.failureCallback !== "undefined"){
          scope.failureCallback(err);
        } // die silently
      });
    },
    controller: function($scope) {
      $scope.createUUID = function () {
          return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
              var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
              return v.toString(16);
          });
      };

      var dataURItoBlob = function(dataURI) {
          var byteString;
          if (dataURI.split(',')[0].indexOf('base64') >= 0)
              byteString = atob(dataURI.split(',')[1]);
          else
              byteString = unescape(dataURI.split(',')[1]);

          var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

          var ia = new Uint8Array(byteString.length);
          for (var i = 0; i < byteString.length; i++) {
              ia[i] = byteString.charCodeAt(i);
          }
          return {blob: new Blob([ia], {type:mimeString}), type: mimeString};
      };

      var resizeImage = function(file) {
        var deferred = $q.defer();
        var canvas = document.createElement('canvas');

        var img = new Image();
        img.src = URL.createObjectURL(file);
        img.onload = function() {
          var ctx = canvas.getContext("2d");
          ctx.drawImage(img, 0, 0);

          var width = img.width;
          var height = img.height;
          if (width > height) {
            if (width > $scope.maxWidth) {
              height *= $scope.maxWidth / width;
              width = $scope.maxWidth;
            }
          } else {
            if (height > $scope.maxHeight) {
              width *= $scope.maxHeight / height;
              height = $scope.maxHeight;
            }
          }
          canvas.width = width;
          canvas.height = height;

          ctx = canvas.getContext("2d");
          ctx.drawImage(img, 0,0, width, height);

          var dataURL = canvas.toDataURL('image/png', 1.0);
          deferred.resolve(dataURItoBlob(dataURL));
        };

        return deferred.promise;
      };

      $scope.onFileSelect = function($files) {
        for ( var i = 0; i < $files.length; i++) {
          var file = $files[i];
          if ( !angular.isDefined($scope.filename) ) {
              $scope.filename = $scope.createUUID();
          }
          var fullPath = $scope.key+"/"+$scope.filename;
          if ( angular.isDefined($scope.path) ) {
            fullPath = $scope.key+"/"+$scope.path+"/"+$scope.filename;
          }

          var config = {};
          if ( !angular.isDefined($scope.maxWidth) || !angular.isDefined($scope.maxHeight) ) {
            config = {
              transformRequest: angular.identity,
              url: 'https://'+$scope.bucket+'.s3.amazonaws.com/',
              method: 'POST',
              data: {
                  'key' : fullPath,
                  'acl' : 'public-read',
                  'Content-Type' : file.type,
                  'AWSAccessKeyId': $scope.aws.key,
                  'Policy' : $scope.aws.policy,
                  'Signature' : $scope.aws.signature
              },
              file: file
            };
            uploadFile(config);
          } else {
            resizeImage(file).then(function(resized) {
              config = {
                transformRequest: angular.identity,
                url: 'https://'+$scope.bucket+'.s3.amazonaws.com/',
                method: 'POST',
                data: {
                    'key' : fullPath,
                    'acl' : 'public-read',
                    'Content-Type' : resized.type,
                    'AWSAccessKeyId': $scope.aws.key,
                    'Policy' : $scope.aws.policy,
                    'Signature' : $scope.aws.signature,
                    'file': resized.blob
                }
              };
              uploadFile(config);
            });
          }
        }
      };

      var uploadFile = function(config) {
        $scope.upload = $upload.upload(config).progress(function(evt) {
            // parseInt(100.0 * evt.loaded / evt.total));
            if ( typeof $scope.progressCallback.progress !== "undefined" ) {
              $scope.progressCallback(evt);
            }
        }).success(function(data, status, headers, config) {
          if ( typeof $scope.successCallback !== "undefined" ) {
            $scope.successCallback($scope.filename+ '?cb=' + (new Date().getTime()).toString(), $scope.index, data, status, headers, config);
          }
        }).error(function(data, status, headers, config) {
          if ( typeof $scope.failureCallback !== "undefined" ) {
            $scope.failureCallback($scope.index, data, status, headers, config);
          } // die silently
        });
      };
    }
  };
}]);
angular.module('templates/angular-s3-upload-button.html', []).run(['$templateCache', function($templateCache) {
  'use strict';

  $templateCache.put('templates/angular-s3-upload-button.html',
    "
\n" +
    "\t\n" +
    "\t\t\n" +
    "\t\n" +
    "\t<input type=\"file\" id=\"file\" style=\"display:none\" \n" +
    "\t\tng-file-select=\"onFileSelect($files, index)\"></input>\n" +
    "
"
  );

}]);


text:
import { ErrorConst } from '@common/type/error'
import { UserRegisterForm } from '@common/type/user-form'
import { Express2, toCallback } from '@server/express/express2'
import { registerUser } from '@server/domain/user/_service/user-register'
import { getObject } from '@server/oman/oman'
import { UserDB } from '@server/db/user/user-db'
import { newString } from '@common/util/primitive'
import { renderJson } from '@server/express/response'

export async function useUserRegisterApi() {

  const web = await getObject('Express2') as Express2
  const udb = await getObject('UserDB') as UserDB

  web.router.post('/api/user-register', toCallback(async (req, res) => {
    const body = req.body
    const form: UserRegisterForm = {
      email: newString(body.email).trim(),
      password: newString(body.password).trim()
    }
    const err: ErrorConst[] = []
    const user = await registerUser(udb, form, err)
    if (!user || err.length) throw err
    renderJson(res, {
      user: {
        id: user.id,
      }
    })
  }))
}


text:
from msrest.serialization import Model

class RepairTargetDescriptionBase(Model):
    """Describes the entities targeted by a repair action.
    This type supports the Service Fabric platform; it is not meant to be used
    directly from your code.
    .

    You probably want to use the sub-classes and not this class directly. Known
    sub-classes are: NodeRepairTargetDescription

    :param kind: Constant filled by server.
    :type kind: str
    """

    _validation = {
        'kind': {'required': True},
    }

    _attribute_map = {
        'kind': {'key': 'Kind', 'type': 'str'},
    }

    _subtype_map = {
        'kind': {'Node': 'NodeRepairTargetDescription'}
    }

    def __init__(self):
        super(RepairTargetDescriptionBase, self).__init__()
        self.kind = None


text:
A REST API developed to help robots on local navigation tasks

![ScreenShot](https://raw.githubusercontent.com/jabrena/skymapper/master/docs/webcamIdea.png)

Skymapper is a software developed for EV3 Brick which it has a ARM5 board.

To run the software execute the following statements:

``` go
go env
export GOPATH=`pwd`
go get .
go get github.com/blackjack/webcam
go get github.com/lucasb-eyer/go-colorful

go test
go test -bench .
```


text:
namespace GameSpace
{
	//////////////////////////////////////////////////////////////////////////
	void State::eventProcessing()
	{
		sf::Event gameEvent;
		while (getRender()->pollEvent(gameEvent))
		{
			stateEventProcessing(gameEvent);
			if (gameEvent.type == sf::Event::Closed)
			{
				getRender()->close();
			}
		}
	}
	//////////////////////////////////////////////////////////////////////////
	void State::drawing()
	{
		getRender()->clear(sf::Color(255, 255, 255, 0));
		stateDrawing();
		getRender()->display();
	}
	//////////////////////////////////////////////////////////////////////////
	GameState State::update()
	{
		eventProcessing();
		drawing();
		return m_nextState;
	}
	//////////////////////////////////////////////////////////////////////////
	State::State(sf::RenderWindow* render, GameSound* soundPlayer)
		: m_render(render), m_soundPlayer(soundPlayer)
	{
		assert(m_render && m_soundPlayer);
	}
	//////////////////////////////////////////////////////////////////////////
	void State::setNextState(GameState state)
	{
		m_nextState = state;
	}
	//////////////////////////////////////////////////////////////////////////
	sf::RenderWindow* State::getRender()
	{
		return m_render;
	}
	//////////////////////////////////////////////////////////////////////////
	GameSound* State::getSoundPlayer()
	{
		return m_soundPlayer;
	}
	//////////////////////////////////////////////////////////////////////////
	// èãðà
	const float StateGame::m_lowFilter = 0.4f;

	StateGame::StateGame(sf::RenderWindow* render, GameSound* soundPlayer, Config* mainConfig, World* gameWorld)
		: State(render, soundPlayer), m_mainConfig(mainConfig), m_gameWorld(gameWorld), m_fdt(0.0f)
	{
		assert(m_mainConfig && m_gameWorld);
	}

	void StateGame::statePrepare()
	{
		setNextState(GameState::GS_GAME);
		getSoundPlayer()->play(GameState::GS_GAME);

		m_fdt = 0.0f;
		m_gameClock.restart();
	}

	GameState StateGame::update()
	{
		m_fdt = m_gameClock.restart().asSeconds() * m_lowFilter + m_fdt * (1 - m_lowFilter);
		m_gameWorld->runGameTiming(m_fdt);

		if (m_gameWorld->isFail())
		{
			setNextState(GameState::GS_GAMEFAIL);
		}
		else if (m_gameWorld->isWin())
		{
			m_mainConfig->markLevelAsCompleted(m_gameWorld->getLastLevel());
			setNextState(GameState::GS_GAMEWIN);
		}

		return State::update();
	}

	void StateGame::stateEventProcessing(sf::Event& event)
	{
		if (event.type == sf::Event::KeyPressed)
		{
			if (event.key.code == sf::Keyboard::Escape)
			{
				setNextState(GameState::GS_LEVEL);
			}
		}
	}

	void StateGame::stateDrawing()
	{
		m_gameWorld->runDrawing(*getRender());
	}
	//////////////////////////////////////////////////////////////////////////
	// ïðîèãðûø
	StateFail::StateFail(sf::RenderWindow* render, GameSound* soundPlayer, Config* mainConfig)
		: State(render, soundPlayer)
	{
		assert(mainConfig);

		getSoundPlayer()->setMusic(GameState::GS_GAMEFAIL, mainConfig->getFailConfig().m_sound);

		if (!m_bgTexture.loadFromFile(mainConfig->getFailConfig().m_backgroundImage))
		{
			throw std::runtime_error("GameSpace::StateFail::StateFail if (!m_bgTexture.loadFromFile(...))");
		}
		if (!m_infoTexture.loadFromFile(mainConfig->getFailConfig().m_image))
		{
			throw std::runtime_error("GameSpace::StateFail::StateFail if (!m_infoTexture.loadFromFile(...))");
		}

		m_background.setTexture(m_bgTexture, true);

		m_info.setTexture(m_infoTexture);
		m_info.setOrigin(m_infoTexture.getSize().x / 2.0f, m_infoTexture.getSize().y / 2.0f);
	}

	void StateFail::statePrepare()
	{
		setNextState(GameState::GS_GAMEFAIL);
		getSoundPlayer()->play(GameState::GS_GAMEFAIL);
	}

	void StateFail::stateEventProcessing(sf::Event& event)
	{
		if (event.type == sf::Event::KeyPressed)
		{
			if (event.key.code == sf::Keyboard::Escape)
			{
				setNextState(GameState::GS_LEVEL);
			}
		}
	}

	void StateFail::stateDrawing()
	{
		const auto viewDim = getRender()->getView().getSize();
		const auto bgDim = m_background.getLocalBounds();
		const auto topLeftPos = getRender()->mapPixelToCoords(sf::Vector2i(0, 0));
		m_background.setPosition(topLeftPos);
		m_background.setScale(viewDim.x / bgDim.width, viewDim.y / bgDim.height);
		getRender()->draw(m_background);

		m_info.setPosition(getRender()->getView().getCenter());
		getRender()->draw(m_info);
	}
	//////////////////////////////////////////////////////////////////////////
	// âûéãðûø

	StateWin::StateWin(sf::RenderWindow* render, GameSound* soundPlayer, Config* mainConfig)
		: State(render, soundPlayer)
	{
		assert(mainConfig);

		getSoundPlayer()->setMusic(GameState::GS_GAMEWIN, mainConfig->getWinConfig().m_sound);

		if (!m_bgTexture.loadFromFile(mainConfig->getWinConfig().m_backgroundImage))
		{
			throw std::runtime_error("GameSpace::StateWin::StateWin if (!m_bgTexture.loadFromFile(...))");
		}
		if (!m_infoTexture.loadFromFile(mainConfig->getWinConfig().m_image))
		{
			throw std::runtime_error("GameSpace::StateWin::StateWin if (!m_infoTexture.loadFromFile(...))");
		}

		m_background.setTexture(m_bgTexture);

		m_info.setTexture(m_infoTexture);
		m_info.setOrigin(m_infoTexture.getSize().x / 2.0f, m_infoTexture.getSize().y / 2.0f);
	}

	void StateWin::statePrepare()
	{
		setNextState(GameState::GS_GAMEWIN);
		getSoundPlayer()->play(GameState::GS_GAMEWIN);
	}

	void StateWin::stateEventProcessing(sf::Event& event)
	{
		if (event.type == sf::Event::KeyPressed)
		{
			if (event.key.code == sf::Keyboard::Escape)
			{
				setNextState(GameState::GS_LEVEL);
			}
		}
	}

	void StateWin::stateDrawing()
	{
		const auto viewDim = getRender()->getView().getSize();
		const auto bgDim = m_background.getLocalBounds();
		const auto topLeftPos = getRender()->mapPixelToCoords(sf::Vector2i(0, 0));
		m_background.setPosition(topLeftPos);
		m_background.setScale(viewDim.x / bgDim.width, viewDim.y / bgDim.height);
		getRender()->draw(m_background);

		m_info.setPosition(getRender()->getView().getCenter());
		getRender()->draw(m_info);
	}
	//////////////////////////////////////////////////////////////////////////
	// ìåíþ
	StateMenu::StateMenu(sf::RenderWindow* render, GameSound* soundPlayer, Config* mainConfig)
		: State(render, soundPlayer)
	{
		assert(mainConfig);

		getSoundPlayer()->setMusic(GameState::GS_MENU, mainConfig->getMenuConfig().m_sound);

		if (!m_bgTexture.loadFromFile(mainConfig->getMenuConfig().m_backgroundImage))
		{
			throw std::runtime_error("GameSpace::StateMenu::StateMenu if (!m_bgTexture.loadFromFile(...))");
		}
		if (!m_startTexture.loadFromFile(mainConfig->getMenuConfig().m_startImage))
		{
			throw std::runtime_error("GameSpace::StateMenu::StateMenu if (!m_startTexture.loadFromFile(...))");
		}
		if (!m_exitTexture.loadFromFile(mainConfig->getMenuConfig().m_exitImage))
		{
			throw std::runtime_error("GameSpace::StateMenu::StateMenu if (!m_exitTexture.loadFromFile(...))");
		}

		m_background.setTexture(m_bgTexture, true);

		m_start.setTexture(m_startTexture);
		m_start.setOrigin(m_startTexture.getSize().x / 2.0f, 0);

		m_exit.setTexture(m_exitTexture);
		m_exit.setOrigin(m_exitTexture.getSize().x / 2.0f, 0);
	}

	void StateMenu::statePrepare()
	{
		setNextState(GameState::GS_MENU);
		getSoundPlayer()->play(GameState::GS_MENU);
	}

	void StateMenu::stateEventProcessing(sf::Event& event)
	{
		if (event.type == sf::Event::MouseButtonPressed &&
			event.mouseButton.button == sf::Mouse::Button::Left)
		{
			const auto coord = getRender()->mapPixelToCoords(sf::Vector2i(event.mouseButton.x, event.mouseButton.y));
			if (m_start.getGlobalBounds().contains(coord))
			{
				setNextState(GameState::GS_LEVEL);
			}
			else if (m_exit.getGlobalBounds().contains(coord))
			{
				setNextState(GameState::GS_EXIT);
			}
		}
	}
	void StateMenu::stateDrawing()
	{
		const auto viewDim = getRender()->getView().getSize();
		const auto bgDim = m_background.getLocalBounds();
		const auto topLeftPos = getRender()->mapPixelToCoords(sf::Vector2i(0, 0));
		m_background.setPosition(topLeftPos);
		m_background.setScale(viewDim.x / bgDim.width, viewDim.y / bgDim.height);
		getRender()->draw(m_background);

		const float ypart = viewDim.y / 4.0f;	// 1 ïóñòîé ñïðàéò + 2 çíà÷èìûõ + 1 ïóñòîé
		sf::Vector2f centerPos(topLeftPos.x + (viewDim.x / 2.0f), topLeftPos.y + ypart);

		auto drawSprite = [&](sf::Sprite& m_sprite)
		{
			m_sprite.setPosition(centerPos);
			getRender()->draw(m_sprite);
			centerPos.y += ypart;
		};

		drawSprite(m_start);
		drawSprite(m_exit);
	}
	//////////////////////////////////////////////////////////////////////////
	// âûáîð óðîâíÿ
	StateLevel::LevelsImage::LevelsImage(const std::string& image)
	{
		if (!m_texture.loadFromFile(image))
		{
			throw std::runtime_error("GameSpace::StateLevel::LevelsImage::LevelsImage if (!m_texture.loadFromFile(image))");
		}
		m_sprite.setTexture(m_texture);
	}
	StateLevel::LevelsImage::LevelsImage(const LevelsImage& other)
		: m_texture(other.m_texture), m_sprite(other.m_sprite)
	{
		m_sprite.setTexture(m_texture);
	}
	StateLevel::LevelsImage& StateLevel::LevelsImage::operator =(const LevelsImage& other)
	{
		if (this != &other)
		{
			m_texture = other.m_texture;
			m_sprite = other.m_sprite;
			m_sprite.setTexture(m_texture);
		}
		return *this;
	}

	StateLevel::StateLevel(sf::RenderWindow* render, GameSound* soundPlayer, Config* mainConfig, World* gameWorld)
		: State(render, soundPlayer), m_mainConfig(mainConfig), m_gameWorld(gameWorld)
	{
		assert(m_mainConfig && m_gameWorld);

		getSoundPlayer()->setMusic(GameState::GS_LEVEL, mainConfig->getLevelsConfig().m_sound);

		if (!m_bgTexture.loadFromFile(m_mainConfig->getLevelsConfig().m_backgroundImage))
		{
			throw std::runtime_error("GameSpace::StateLevel::StateLevel if (!m_bgTexture.loadFromFile(...))");
		}

		m_background.setTexture(m_bgTexture, true);

		if (!m_loadingTexture.loadFromFile(m_mainConfig->getLevelsConfig().m_loadImage))
		{
			throw std::runtime_error("GameSpace::StateLevel::StateLevel if (!m_loadingTexture.loadFromFile(...))");
		}
		m_loading.setTexture(m_loadingTexture);
		m_loading.setOrigin(m_loadingTexture.getSize().x / 2.0f, m_loadingTexture.getSize().y / 2.0f);

		for (const auto& itLevel : m_mainConfig->getLevelsConfig().m_levels)
		{
			m_levels.emplace_back(itLevel.m_image);
		}
	}

	void StateLevel::statePrepare()
	{
		setNextState(GameState::GS_LEVEL);
		getSoundPlayer()->play(GameState::GS_LEVEL);
	}

	void StateLevel::stateEventProcessing(sf::Event& event)
	{
		if (event.type == sf::Event::MouseButtonPressed &&
			event.mouseButton.button == sf::Mouse::Button::Left)
		{
			const auto coord = getRender()->mapPixelToCoords(sf::Vector2i(event.mouseButton.x, event.mouseButton.y));
			for (size_t i = 0; i < m_levels.size(); ++i)
			{
				if (m_levels[i].m_sprite.getGlobalBounds().contains(coord) &&
					(i == 0 || m_mainConfig->getLevelsConfig().m_levels.at(i - 1).m_isCompleted))
				{
					m_loading.setPosition(getRender()->getView().getCenter());
					getRender()->draw(m_loading);
					getRender()->display();

					getSoundPlayer()->setMusic(GameState::GS_GAME, m_mainConfig->getLevelsConfig().m_levels.at(i).m_levelSound);
					m_gameWorld->loadFromFile(m_mainConfig->getLevelsConfig().m_levels.at(i).m_levelFile);
					setNextState(GameState::GS_GAME);

					break;
				}
			}
		}
		else if (event.type == sf::Event::KeyPressed)
		{
			if (event.key.code == sf::Keyboard::Escape)
			{
				setNextState(GameState::GS_MENU);
			}
		}
	}

	void StateLevel::stateDrawing()
	{
		const auto viewDim = getRender()->getView().getSize();
		const auto bgDim = m_background.getLocalBounds();
		const auto topleftPos = getRender()->mapPixelToCoords(sf::Vector2i(0, 0));
		m_background.setPosition(topleftPos);
		m_background.setScale(viewDim.x / bgDim.width, viewDim.y / bgDim.height);
		getRender()->draw(m_background);

		const int blockPerLine = m_mainConfig->getLevelsConfig().m_blockPerLine;
		const float xpart = viewDim.x / (m_mainConfig->getLevelsConfig().m_blockPerLine + 2.0f);	// 1 áîêîâîé + n çíà÷èìûõ + 1 áîêîâîé
		const float ypart = viewDim.y / (m_mainConfig->getLevelsConfig().m_linePerScreen + 2.0f);	// 1 âåðõíèé + k çíà÷èìûõ + 1 íèæíèé

		for (size_t i = 0; i < m_levels.size(); ++i)
		{
			m_levels[i].m_sprite.setColor(sf::Color::White);
			m_levels[i].m_sprite.setPosition(	topleftPos.x + xpart + (i % blockPerLine)*xpart,
												topleftPos.y + ypart + (i / blockPerLine)*ypart);
			if (i > 0 && !m_mainConfig->getLevelsConfig().m_levels.at(i - 1).m_isCompleted)
			{
				m_levels[i].m_sprite.setColor(sf::Color::Blue);
			}
			getRender()->draw(m_levels[i].m_sprite);
		}
	}
	//////////////////////////////////////////////////////////////////////////
}


text:
#ifndef TextRunConstructor_h
#define TextRunConstructor_h

#include "platform/text/TextDirection.h"
#include "platform/text/TextRun.h"
#include "wtf/text/WTFString.h"
#include "wtf/unicode/Unicode.h"

namespace blink {

class Font;
class RenderObject;
class RenderStyle;
class RenderText;

enum TextRunFlag {
    DefaultTextRunFlags = 0,
    RespectDirection = 1 << 0,
    RespectDirectionOverride = 1 << 1
};

typedef unsigned TextRunFlags;

// Direction resolved from string value.
TextRun constructTextRun(RenderObject* context, const Font&, const String&, RenderStyle*,
    TextRun::ExpansionBehavior = TextRun::AllowTrailingExpansion | TextRun::ForbidLeadingExpansion, TextRunFlags = DefaultTextRunFlags);
TextRun constructTextRun(RenderObject* context, const Font&, const RenderText*, unsigned offset, unsigned length, RenderStyle*,
    TextRun::ExpansionBehavior = TextRun::AllowTrailingExpansion | TextRun::ForbidLeadingExpansion);

// Explicit direction.
TextRun constructTextRun(RenderObject* context, const Font&, const String&, RenderStyle*, TextDirection,
    TextRun::ExpansionBehavior = TextRun::AllowTrailingExpansion | TextRun::ForbidLeadingExpansion, TextRunFlags = DefaultTextRunFlags);

TextRun constructTextRun(RenderObject* context, const Font&, const RenderText*, RenderStyle*, TextDirection,
    TextRun::ExpansionBehavior = TextRun::AllowTrailingExpansion | TextRun::ForbidLeadingExpansion);

TextRun constructTextRun(RenderObject* context, const Font&, const RenderText*, unsigned offset, unsigned length, RenderStyle*, TextDirection,
    TextRun::ExpansionBehavior = TextRun::AllowTrailingExpansion | TextRun::ForbidLeadingExpansion);

TextRun constructTextRun(RenderObject* context, const Font&, const RenderText*, unsigned offset, RenderStyle*,
    TextRun::ExpansionBehavior = TextRun::AllowTrailingExpansion | TextRun::ForbidLeadingExpansion);

TextRun constructTextRun(RenderObject* context, const Font&, const LChar* characters, int length, RenderStyle*, TextDirection,
    TextRun::ExpansionBehavior = TextRun::AllowTrailingExpansion | TextRun::ForbidLeadingExpansion);

TextRun constructTextRun(RenderObject* context, const Font&, const UChar* characters, int length, RenderStyle*, TextDirection,
    TextRun::ExpansionBehavior = TextRun::AllowTrailingExpansion | TextRun::ForbidLeadingExpansion);

} // namespace blink

#endif


text:
<!doctype html>

    <title>jChat</title>
    <link href="/css/style.min.css" rel="stylesheet" />

node-jChat

        change font color

please insert your username

        <form id="userForm" action="">
            Username
            <input type="text" id="name" autocomplete="off" /><button>Send</button>
        </form>

username is required

    <form id="chatForm" action="">
        <input id="m" autocomplete="off" /><button>Send</button>
    </form>


text:
#pragma once

#include "il2cpp-config.h"

#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif

#include <stdint.h>
#include <assert.h>
#include <exception>

// System.Collections.Generic.Comparer`1/DefaultComparer<System.Int32>
struct DefaultComparer_t3957051573;

#include "codegen/il2cpp-codegen.h"

// System.Void System.Collections.Generic.Comparer`1/DefaultComparer<System.Int32>::.ctor()
extern "C"  void DefaultComparer__ctor_m925764245_gshared (DefaultComparer_t3957051573 * __this, const MethodInfo* method);
#define DefaultComparer__ctor_m925764245(__this, method) ((  void (*) (DefaultComparer_t3957051573 *, const MethodInfo*))DefaultComparer__ctor_m925764245_gshared)(__this, method)
// System.Int32 System.Collections.Generic.Comparer`1/DefaultComparer<System.Int32>::Compare(T,T)
extern "C"  int32_t DefaultComparer_Compare_m470059266_gshared (DefaultComparer_t3957051573 * __this, int32_t ___x0, int32_t ___y1, const MethodInfo* method);
#define DefaultComparer_Compare_m470059266(__this, ___x0, ___y1, method) ((  int32_t (*) (DefaultComparer_t3957051573 *, int32_t, int32_t, const MethodInfo*))DefaultComparer_Compare_m470059266_gshared)(__this, ___x0, ___y1, method)


text:
'use strict';

var should = require('should');// jshint ignore:line

var jshint = require('../lib/index');

var gulpMock = {};
var task = null;

gulpMock.task = function(name, description, deps, func) {// jshint ignore:line
  task = func;
};

var configMock = {
  root: __dirname,
  src: ['**/*.js', '!./node_modules/**', '!./docs/**']
};

jshint(gulpMock, configMock);

describe('Gulp Module JSHint', function() {
  it('Should return a function', function() {
    jshint.should.be.type('function');
  });

  it('Should create a task', function() {
    task.should.be.type('function');
  });

  it('Should run and throw an error', function(cb) {
    try {
      task();
    } catch (e) {
      cb();
    }
  });
});


text:
import config from '~/config/webpack';

const defaultConfig = {
  hot: true
, colors: true
, noInfo: true
, publicPath: config.output.publicPath
, historyApiFallback: true
, https: config.port === 443
};

export default defaultConfig;


text:
<!doctype HTML>

    <meta charset="utf-8">
    <title>Trivia Quiz</title>
    <meta name="description" content="Quiz App to play and learn">
    <meta name="viewport" content="width=device-width">
    <meta name="theme-color" content="#bf1e2e">

    <base href="/">

    <link href="assets/images/favicon.png" rel="icon">
    <link rel="manifest" href="./manifest.json?ver=1.0.1">
    <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700" rel="stylesheet">


text:
<?php

namespace Doris\Listener;

use Doris\Event\ConsumerCycle;
use League\Event\ListenerProviderInterface;
use League\Event\ListenerAcceptorInterface;
use League\Event\EventInterface;

/**
 * Stops the consumer when it reaches the command limit
 *
 * @author Márk Sági-Kazár <mark.sagikazar@gmail.com>
 */
class CommandLimit implements ListenerProviderInterface
{
    /**
     * @var integer
     */
    protected $commandLimit;

    /**
     * @var integer
     */
    protected $commandCount = 0;

    /**
     * @var boolean
     */
    protected $countFailures = true;

    /**
     * @param integer $commandLimit
     * @param boolean $countFailures
     */
    public function __construct($commandLimit, $countFailures = true)
    {
        $this->commandLimit = $commandLimit;
        $this->countFailures = (bool) $countFailures;
    }

    /**
     * {@inheritdoc}
     */
    public function provideListeners(ListenerAcceptorInterface $listenerAcceptor)
    {
        $listenerAcceptor->addListener('consumerCycle', [$this, 'check']);
        $listenerAcceptor->addListener('commandExecuted', [$this, 'count']);

        // Count failed commands as well
        if ($this->countFailures) {
            $listenerAcceptor->addListener('commandFailed', [$this, 'count']);
        }
    }

    /**
     * Check if the consumer passed the limit
     *
     * @param ConsumerCycle $event
     */
    public function check(ConsumerCycle $event)
    {
        if ($this->commandLimit <= $this->commandCount) {
            $event->stopConsumer();
        }
    }

    /**
     * Counts a command
     *
     * @param EventInterface $event
     */
    public function count(EventInterface $event)
    {
        $this->commandCount++;
    }
}


text:
namespace cyclus {

class Trader;
template<class T> class BidPortfolio;

/// @class Bid
///
/// @brief A Bid encapsulates all the information required to communicate a bid
/// response to a request for a resource, including the resource bid and the
/// bidder.
template <class T>
class Bid {
 public:
  /// @brief a factory method for a bid
  /// @param request the request being responded to by this bid
  /// @param offer the resource being offered in response to the request
  /// @param bidder the bidder
  /// @param portfolio the porftolio of which this bid is a part
  inline static Bid<T>* Create(Request<T>* request,
                               boost::shared_ptr<T> offer,
                               Trader* bidder,
                               typename BidPortfolio<T>::Ptr portfolio,
                               bool exclusive = false) {
    return new Bid<T>(request, offer, bidder, portfolio, exclusive);
  }

  /// @brief a factory method for a bid for a bid without a portfolio
  /// @warning this factory should generally only be used for testing
  inline static Bid<T>* Create(Request<T>* request, boost::shared_ptr<T> offer,
                               Trader* bidder, bool exclusive = false) {
    return new Bid<T>(request, offer, bidder, exclusive);
  }

  /// @return the request being responded to
  inline Request<T>* request() const {
    return request_;
  }

  /// @return the bid object for the request
  inline boost::shared_ptr<T> offer() const {
    return offer_;
  }

  /// @return the agent responding the request
  inline Trader* bidder() const {
    return bidder_;
  }

  /// @return the portfolio of which this bid is a part
  inline typename BidPortfolio<T>::Ptr portfolio() {
    return portfolio_.lock();
  }

  /// @return whether or not this an exclusive bid
  inline bool exclusive() const {
    return exclusive_;
  }

 private:
  /// @brief constructors are private to require use of factory methods
  Bid(Request<T>* request, boost::shared_ptr<T> offer, Trader* bidder,
      bool exclusive = false)
      : request_(request),
        offer_(offer),
        bidder_(bidder),
        exclusive_(exclusive) {}

  Bid(Request<T>* request, boost::shared_ptr<T> offer, Trader* bidder,
      typename BidPortfolio<T>::Ptr portfolio, bool exclusive = false)
      : request_(request),
        offer_(offer),
        bidder_(bidder),
        portfolio_(portfolio),
        exclusive_(exclusive) {}

  Request<T>* request_;
  boost::shared_ptr<T> offer_;
  Trader* bidder_;
  boost::weak_ptr<BidPortfolio<T> > portfolio_;
  bool exclusive_;
};

}  // namespace cyclus

#endif  // CYCLUS_SRC_BID_H_


text:
package workspace

import "github.com/eidolon/console"

// RootCommand creates a new command that is the parent to all workspace-related sub-commands.
func RootCommand() *console.Command {
	return &console.Command{
		Name:        "workspace",
		Alias:       "w",
		Description: "Manage workspaces.",
	}
}


text:
<!---
title: Helpers
subtitle: Helper methods
author: Robin Radic
-->

#### Method list
- path_join()
- path_is_absolute()
- path_is_relative()
- path_get_directory()
- path_get_extension()
- path_get_filename()
- file_put()
- file_rglob()
- file_rsearch()
- file_exists()
- file_get()
- file_getRequire()
- file_requireOnce()
- file_prepend()
- file_append()
- file_delete()
- file_move()
- file_copy()
- file_name()
- file_extension()
- file_type()
- file_mimeType()
- file_size()
- file_lastModified()
- file_isDirectory()
- file_isWriteable()
- file_isFile()
- file_glob()
- file_files()
- file_allFiles()
- file_directories()
- file_makeDirectory()
- file_copyDirectory()
- file_deleteDirectory()
- file_cleanDirectory()
- file_touch()
- file_chmod()
- file_chown()
- file_chgrp()
- file_rename()
- file_symlink()
- file_mirror()
- file_dumpFile()


text:
/*
 * @test
 * @bug     6507317 6932571
 * @summary Problem when casting from parametrized type to concrete class
 * @compile T6507317.java
 */

import java.util.Comparator;

abstract class T6507317<T extends Comparable<T>> implements Comparator<T> {
    void test(T t) {
        String s = (String)t;
    }
}


text:
package com.prancingdonkey.model.json;

import org.codehaus.jackson.annotate.JsonAutoDetect;
import org.codehaus.jackson.annotate.JsonIgnore;

//<start id="lis_04_json-create-mixin"/>
@JsonAutoDetect
public abstract class ExternalItemMixin
{

    public abstract String getItemNumber();

    public abstract void setItemNumber(String itemNumber);

    @JsonIgnore
    public abstract String getUnwantedValue();

    @JsonIgnore
    public abstract void setUnwantedValue(String unwantedValue);
}
//<end id="lis_04_json-create-mixin"/>


text:
#ifndef _TYPECHECKING_TYPESUBSTITUTIONVISITOR_H_
#define _TYPECHECKING_TYPESUBSTITUTIONVISITOR_H_

#include "frontends/p4/typeMap.h"
#include "ir/ir.h"
#include "typeSubstitution.h"

namespace P4 {

/**
 * See if a variable occurs in a Type.
 * If true, return null, else return the original type.
 */
class TypeOccursVisitor : public Inspector {
 public:
    const IR::ITypeVar* toFind;
    bool occurs;

    explicit TypeOccursVisitor(const IR::ITypeVar* toFind) : toFind(toFind), occurs(false) {
        setName("TypeOccurs");
    }
    bool preorder(const IR::Type_Var* typeVariable) override;
    bool preorder(const IR::Type_InfInt* infint) override;
};

/* Replaces TypeVariables with other types */
class TypeVariableSubstitutionVisitor : public Transform {
 protected:
    const TypeVariableSubstitution* bindings;
    bool replace;  // If true variables that map to variables are just replaced
                   // in the TypeParameterList of the replaced object; else they
                   // are removed.
    const IR::Node* replacement(const IR::ITypeVar* original, const IR::Node* node);

 public:
    explicit TypeVariableSubstitutionVisitor(const TypeVariableSubstitution* bindings,
                                             bool replace = false)
        : bindings(bindings), replace(replace) {
        setName("TypeVariableSubstitution");
    }

    const IR::Node* preorder(IR::TypeParameters* tps) override;
    const IR::Node* preorder(IR::Type_Var* tv) override {
        return replacement(getOriginal<IR::Type_Var>(), tv);
    }
    const IR::Node* preorder(IR::Type_InfInt* ti) override {
        return replacement(getOriginal<IR::Type_InfInt>(), ti);
    }
};

class TypeSubstitutionVisitor : public TypeVariableSubstitutionVisitor {
    TypeMap* typeMap;

 public:
    TypeSubstitutionVisitor(TypeMap* typeMap, TypeVariableSubstitution* ts)
        : TypeVariableSubstitutionVisitor(ts), typeMap(typeMap) {
        CHECK_NULL(typeMap);
        setName("TypeSubstitutionVisitor");
    }
    const IR::Node* postorder(IR::PathExpression* path) override {
        // We want fresh nodes for variables, etc.
        return new IR::PathExpression(path->path->clone());
    }
    const IR::Node* postorder(IR::Type_Name* type) override {
        auto actual = typeMap->getTypeType(getOriginal<IR::Type_Name>(), true);
        if (auto tv = actual->to<IR::ITypeVar>()) {
            LOG3("Replacing " << tv);
            return replacement(tv, type);
        }
        return type;
    }
};

}  // namespace P4
#endif /* _TYPECHECKING_TYPESUBSTITUTIONVISITOR_H_ */


text:
#include "tensorflow/core/grappler/utils/frame.h"
#include <deque>
#include <stack>
#include "tensorflow/core/framework/node_def.pb.h"
#include "tensorflow/core/grappler/op_types.h"
#include "tensorflow/core/grappler/utils.h"

namespace tensorflow {
namespace grappler {

int IdentifyFrames(
    const GraphDef& graph,
    std::unordered_map<const NodeDef*, std::vector<int>>* frames) {
  NodeMap node_map(const_cast<GraphDef*>(&graph));
  std::deque<std::pair<const NodeDef*, std::vector<int>>> ready_nodes;
  for (const NodeDef& node : graph.node()) {
    if (node.input_size() == 0) {
      std::vector<int> empty;
      ready_nodes.emplace_back(&node, empty);
    }
  }
  int frame_id = 0;
  while (!ready_nodes.empty()) {
    auto ready_node = ready_nodes.front();
    for (const auto& fanout : node_map.GetOutputs(ready_node.first->name())) {
      if (frames->count(fanout) < 1) {
        std::vector<int> frame_ids = ready_node.second;
        if (IsExit(*ready_node.first)) {
          frame_ids.pop_back();
        }
        if (IsEnter(*fanout)) {
          frame_ids.push_back(frame_id);
          frame_id++;
        }
        ready_nodes.emplace_back(fanout, frame_ids);
      } else {
        CHECK(ready_node.second == (*frames)[fanout]);
      }
    }
    (*frames)[ready_node.first] = ready_node.second;
    ready_nodes.pop_front();
  }
  return frame_id;
}

}  // namespace grappler
}  // namespace tensorflow


text:
<?php

namespace Illuminate\Console\Events;

use Illuminate\Console\Scheduling\Event;
use Throwable;

class ScheduledTaskFailed
{
    /**
     * The scheduled event that failed.
     *
     * @var \Illuminate\Console\Scheduling\Event
     */
    public $task;

    /**
     * The exception that was thrown.
     *
     * @var \Throwable
     */
    public $exception;

    /**
     * Create a new event instance.
     *
     * @param \Illuminate\Console\Scheduling\Event $task
     * @param \Throwable $exception
     */
    public function __construct(Event $task, Throwable $exception)
    {
        $this->task = $task;
        $this->exception = $exception;
    }
}


text:
@interface NBClientContactsTests : NBTestCase

- (void)assertContactsArray:(NSArray *)array;
- (void)assertContactDictionary:(NSDictionary *)dictionary;

- (void)assertContactTypesArray:(NSArray *)array;
- (void)assertContactMethodsArray:(NSArray *)array;
- (void)assertContactStatusesArray:(NSArray *)array;

@end

@implementation NBClientContactsTests

- (void)setUp
{
    [super setUp];
    [self setUpSharedClient];
}

#pragma mark - Contacts

#pragma mark Helpers

- (void)assertContactsArray:(NSArray *)array
{
    XCTAssertNotNil(array, @"Client should have received list of contacts.");
    for (NSDictionary *dictionary in array) { [self assertContactDictionary:dictionary]; }
}

- (void)assertContactDictionary:(NSDictionary *)dictionary
{
    static NSArray *keys; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{
        keys = @[ @"type_id", @"method", @"sender_id", @"recipient_id", @"status", @"broadcaster_id", @"note", @"created_at" ];
    });
    return XCTAssertTrue([dictionary nb_hasKeys:keys], "Contact has correct attributes.");
}

#pragma mark Tests

- (void)testFetchPersonContacts
{
    [self setUpAsync];
    NSDictionary *paginationParameters = @{ NBClientPaginationLimitKey: @5, NBClientPaginationTokenOptInKey: @1 };
    if (self.shouldUseHTTPStubbing) {
        [self stubRequestUsingFileDataWithMethod:@"GET" pathFormat:@"people/:id/contacts" pathVariables:@{ @"id": @(self.supporterIdentifier) } queryParameters:paginationParameters];
    }
    [self.client
     fetchPersonContactsByIdentifier:self.supporterIdentifier
     withPaginationInfo:[[NBPaginationInfo alloc] initWithDictionary:paginationParameters legacy:NO]
     completionHandler:^(NSArray *items, NBPaginationInfo *paginationInfo, NSError *error) {
        [self assertServiceError:error];
        [self assertContactsArray:items];
        [self completeAsync];
    }];
    [self tearDownAsync];
}

- (void)testCreatePersonContact
{
    [self setUpAsync];
    NSDictionary *contactInfo = @{ NBClientContactBroadcasterIdentifierKey: @1,
                                   NBClientContactMethodKey: @"door_knock",
                                   NBClientContactNoteKey: @"He did not support the cause.",
                                   NBClientContactSenderIdentifierKey: @(self.userIdentifier),
                                   NBClientContactStatusKey: @"not_interested",
                                   NBClientContactTypeIdentifierKey: @4 };
    if (self.shouldUseHTTPStubbing) {
        [self stubRequestUsingFileDataWithMethod:@"POST" pathFormat:@"people/:id/contacts" pathVariables:@{ @"id": @(self.supporterIdentifier) } queryParameters:nil];
    }
    [self.client createPersonContactByIdentifier:self.supporterIdentifier withContactInfo:contactInfo completionHandler:^(NSDictionary *item, NSError *error) {
        [self assertServiceError:error];
        [self assertContactDictionary:item];
        [self completeAsync];
    }];
    [self tearDownAsync];
}

#pragma mark - Contact Types (Fetch Only)

#pragma mark Helpers

- (void)assertContactTypesArray:(NSArray *)array
{
    XCTAssertNotNil(array, @"Client should have received list of contact types.");
    NSArray *keys = @[ @"id", @"name" ];
    for (NSDictionary *dictionary in array) {
        XCTAssertTrue([dictionary nb_hasKeys:keys], "Contact has correct attributes.");
    }
}

- (void)assertContactMethodsArray:(NSArray *)array
{
    XCTAssertNotNil(array, @"Client should have received list of contact methods.");
    NSArray *keys = @[ @"api_name", @"name" ];
    for (NSDictionary *dictionary in array) {
        XCTAssertTrue([dictionary nb_hasKeys:keys], "Contact status has correct attributes.");
    }
}

- (void)assertContactStatusesArray:(NSArray *)array
{
    XCTAssertNotNil(array, @"Client should have received list of contact statuses.");
    NSArray *keys = @[ @"api_name", @"name" ];
    for (NSDictionary *dictionary in array) {
        XCTAssertTrue([dictionary nb_hasKeys:keys], "Contact status has correct attributes.");
    }
}

#pragma mark Tests

- (void)testFetchContactTypes
{
    [self setUpAsync];
    if (self.shouldUseHTTPStubbing) {
        [self stubRequestUsingFileDataWithMethod:@"GET" path:@"settings/contact_types" queryParameters:nil];
    }
    [self.client fetchContactTypesWithPaginationInfo:nil completionHandler:^(NSArray *items, NBPaginationInfo *paginationInfo, NSError *error) {
        [self assertServiceError:error];
        [self assertContactTypesArray:items];
        [self completeAsync];
    }];
    [self tearDownAsync];
}

- (void)testFetchContactMethods
{
    [self setUpAsync];
    if (self.shouldUseHTTPStubbing) {
        [self stubRequestUsingFileDataWithMethod:@"GET" path:@"settings/contact_methods" queryParameters:nil];
    }
    [self.client fetchContactMethodsWithCompletionHandler:^(NSArray *items, NBPaginationInfo *paginationInfo, NSError *error) {
        [self assertServiceError:error];
        [self assertContactMethodsArray:items];
        [self completeAsync];
    }];
    [self tearDownAsync];
}

- (void)testFetchContactStatuses
{
    [self setUpAsync];
    if (self.shouldUseHTTPStubbing) {
        [self stubRequestUsingFileDataWithMethod:@"GET" path:@"settings/contact_statuses" queryParameters:nil];
    }
    [self.client fetchContactStatusesWithCompletionHandler:^(NSArray *items, NBPaginationInfo *paginationInfo, NSError *error) {
        [self assertServiceError:error];
        [self assertContactStatusesArray:items];
        [self completeAsync];
    }];
    [self tearDownAsync];
}

@end


text:
package com.amazonaws.services.route53resolver.model;

import java.io.Serializable;
import javax.annotation.Generated;

/**
 *
 * @see AWS API Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ListResolverDnssecConfigsResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {

    /**
     *

     * If a response includes the last of the DNSSEC configurations that are associated with the current Amazon Web
     * Services account, NextToken doesn't appear in the response.
     *

     *

     * If a response doesn't include the last of the configurations, you can get more configurations by submitting
     * another
     * ListResolverDnssecConfigs request. Get the value of NextToken that Amazon Route 53 returned in
     * the previous response and include it in NextToken in the next request.
     *

     */
    private String nextToken;
    /**
     *

     * An array that contains one ResolverDnssecConfig element for each configuration for DNSSEC validation that is associated with the
     * current Amazon Web Services account.
     *

     */
    private java.util.List<ResolverDnssecConfig> resolverDnssecConfigs;

    /**
     *

     * If a response includes the last of the DNSSEC configurations that are associated with the current Amazon Web
     * Services account, NextToken doesn't appear in the response.
     *

     *

     * If a response doesn't include the last of the configurations, you can get more configurations by submitting
     * another
     * ListResolverDnssecConfigs request. Get the value of NextToken that Amazon Route 53 returned in
     * the previous response and include it in NextToken in the next request.
     *

     *
     * @param nextToken
     *        If a response includes the last of the DNSSEC configurations that are associated with the current Amazon
     *        Web Services account, NextToken doesn't appear in the response.

     *

     *        If a response doesn't include the last of the configurations, you can get more configurations by
     *        submitting another ListResolverDnssecConfigs request. Get the value of NextToken that Amazon Route 53
     *        returned in the previous response and include it in NextToken in the next request.
     */

    public void setNextToken(String nextToken) {
        this.nextToken = nextToken;
    }

    /**
     *

     * If a response includes the last of the DNSSEC configurations that are associated with the current Amazon Web
     * Services account, NextToken doesn't appear in the response.
     *

     *

     * If a response doesn't include the last of the configurations, you can get more configurations by submitting
     * another
     * ListResolverDnssecConfigs request. Get the value of NextToken that Amazon Route 53 returned in
     * the previous response and include it in NextToken in the next request.
     *

     *
     * @return If a response includes the last of the DNSSEC configurations that are associated with the current Amazon
     *         Web Services account, NextToken doesn't appear in the response.

     *

     *         If a response doesn't include the last of the configurations, you can get more configurations by
     *         submitting another ListResolverDnssecConfigs request. Get the value of NextToken that Amazon Route 53
     *         returned in the previous response and include it in NextToken in the next request.
     */

    public String getNextToken() {
        return this.nextToken;
    }

    /**
     *

     * If a response includes the last of the DNSSEC configurations that are associated with the current Amazon Web
     * Services account, NextToken doesn't appear in the response.
     *

     *

     * If a response doesn't include the last of the configurations, you can get more configurations by submitting
     * another
     * ListResolverDnssecConfigs request. Get the value of NextToken that Amazon Route 53 returned in
     * the previous response and include it in NextToken in the next request.
     *

     *
     * @param nextToken
     *        If a response includes the last of the DNSSEC configurations that are associated with the current Amazon
     *        Web Services account, NextToken doesn't appear in the response.

     *

     *        If a response doesn't include the last of the configurations, you can get more configurations by
     *        submitting another ListResolverDnssecConfigs request. Get the value of NextToken that Amazon Route 53
     *        returned in the previous response and include it in NextToken in the next request.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ListResolverDnssecConfigsResult withNextToken(String nextToken) {
        setNextToken(nextToken);
        return this;
    }

    /**
     *

     * An array that contains one ResolverDnssecConfig element for each configuration for DNSSEC validation that is associated with the
     * current Amazon Web Services account.
     *

     *
     * @return An array that contains one ResolverDnssecConfig element for each configuration for DNSSEC validation that is associated with
     *         the current Amazon Web Services account.
     */

    public java.util.List<ResolverDnssecConfig> getResolverDnssecConfigs() {
        return resolverDnssecConfigs;
    }

    /**
     *

     * An array that contains one ResolverDnssecConfig element for each configuration for DNSSEC validation that is associated with the
     * current Amazon Web Services account.
     *

     *
     * @param resolverDnssecConfigs
     *        An array that contains one ResolverDnssecConfig element for each configuration for DNSSEC validation that is associated with the
     *        current Amazon Web Services account.
     */

    public void setResolverDnssecConfigs(java.util.Collection<ResolverDnssecConfig> resolverDnssecConfigs) {
        if (resolverDnssecConfigs == null) {
            this.resolverDnssecConfigs = null;
            return;
        }

        this.resolverDnssecConfigs = new java.util.ArrayList<ResolverDnssecConfig>(resolverDnssecConfigs);
    }

    /**
     *

     * An array that contains one ResolverDnssecConfig element for each configuration for DNSSEC validation that is associated with the
     * current Amazon Web Services account.
     *

     *

     * NOTE: This method appends the values to the existing list (if any). Use
     * {@link #setResolverDnssecConfigs(java.util.Collection)} or
     * {@link #withResolverDnssecConfigs(java.util.Collection)} if you want to override the existing values.
     *

     *
     * @param resolverDnssecConfigs
     *        An array that contains one ResolverDnssecConfig element for each configuration for DNSSEC validation that is associated with the
     *        current Amazon Web Services account.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ListResolverDnssecConfigsResult withResolverDnssecConfigs(ResolverDnssecConfig... resolverDnssecConfigs) {
        if (this.resolverDnssecConfigs == null) {
            setResolverDnssecConfigs(new java.util.ArrayList<ResolverDnssecConfig>(resolverDnssecConfigs.length));
        }
        for (ResolverDnssecConfig ele : resolverDnssecConfigs) {
            this.resolverDnssecConfigs.add(ele);
        }
        return this;
    }

    /**
     *

     * An array that contains one ResolverDnssecConfig element for each configuration for DNSSEC validation that is associated with the
     * current Amazon Web Services account.
     *

     *
     * @param resolverDnssecConfigs
     *        An array that contains one ResolverDnssecConfig element for each configuration for DNSSEC validation that is associated with the
     *        current Amazon Web Services account.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ListResolverDnssecConfigsResult withResolverDnssecConfigs(java.util.Collection<ResolverDnssecConfig> resolverDnssecConfigs) {
        setResolverDnssecConfigs(resolverDnssecConfigs);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getNextToken() != null)
            sb.append("NextToken: ").append(getNextToken()).append(",");
        if (getResolverDnssecConfigs() != null)
            sb.append("ResolverDnssecConfigs: ").append(getResolverDnssecConfigs());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof ListResolverDnssecConfigsResult == false)
            return false;
        ListResolverDnssecConfigsResult other = (ListResolverDnssecConfigsResult) obj;
        if (other.getNextToken() == null ^ this.getNextToken() == null)
            return false;
        if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false)
            return false;
        if (other.getResolverDnssecConfigs() == null ^ this.getResolverDnssecConfigs() == null)
            return false;
        if (other.getResolverDnssecConfigs() != null && other.getResolverDnssecConfigs().equals(this.getResolverDnssecConfigs()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode());
        hashCode = prime * hashCode + ((getResolverDnssecConfigs() == null) ? 0 : getResolverDnssecConfigs().hashCode());
        return hashCode;
    }

    @Override
    public ListResolverDnssecConfigsResult clone() {
        try {
            return (ListResolverDnssecConfigsResult) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

}


text:
module.exports = function (obj, path) {
    /** Method extracts a value from a deeply nested object
     * @param {Object} obj
     * @param {String} path, accessor is using dot notation.
     * @return {Object} value of obj[path]
     */
    var steps = path.split('.');
    var i = 0;
    while (i < steps.length && obj[steps[i]] !== undefined) {
        obj = obj[steps[i]];
        i += 1
    }
    if (i === steps.length) {
        return obj;
    }
    return undefined;
};


text:
The logger plugin is activated automatically when you attach a `LoggerInterface` to the `ClientBuilder`.
 It will hook in to the Request, Response and Fault event and will log every step of the SOAP process.
 No more code pollution for logging!


text:
require 'mongo'
require 'date'
class CLI
  def initialize args
    confs = load_configuration(verify_args(args))
    files = get_file_list(confs[:content])
    mongo = get_mongo_connection(confs[:mongodb])

    files.each do |f|
      entry = mongo.find("_id" => f).to_a
      if entry.size == 0
        puts "[ import ] creating:: #{f}"
        mongo.insert( { "_id" => f, "body" => File.read(f), "mtime" => File.mtime(f) } )
      #else
        #unless entry.first["mtime"] > File.mtime(f)
          #puts "[ import ] updating:: #{f}"
          #mongo.update( { "_id" => f }, { "$set" => { "body" => File.read(f), "mtime" => File.mtime(f).utc } } )
        #end
      end
    end
  end

  private
  def verify_args args
    return "./config/config.yml" if args.nil? or args.empty?
    return args.first if File.exists?(args)
    usage
  rescue
    usage
  end

  def load_configuration file
    conf = YAML.load_file(file)
    {
      :content => (conf.has_key?("content") ? conf["content"] : "./content"),
      :mongodb => (conf.has_key?("mongodb") ? conf["mongodb"] : nil)
    }
  end

  def get_file_list content
    files = Dir[ File.join( content, "**", "*" ) ].select do |f|
      (f =~ /mdown$/ or f =~ /haml$/ or f =~ /textile$/ or f =~ /txt$/)
    end
  end

  def get_mongo_connection conf
    begin
      # configure mongodb connection
      mdb_params = []

      mdb_params.push conf["host"] if conf.has_key?("host")
      mdb_params.push conf["port"] if conf.has_key?("port")

      mdb_database_name   = (conf.has_key?("database") ? conf["database"] : "nestacms")
      mdb_collection_name = (conf.has_key?("collection") ? conf["collection"] : "nestacms")

      mdb = if mdb_params.empty?
              Mongo::Connection.new.db(mdb_database_name)
            else
              Mongo::Connection.new(*mdb_params).db(mdb_database_name)
            end

      if Nesta::Config.mongdb.has_key?("username") and conf.has_key?("password")
        mdb.authenticate(conf["username"], conf["password"])
      end

      mongodb = mdb.collection(mdb_collection_name)
    rescue
      begin
        mongodb = Mongo::Connection.new.db('nestacms').collection('nestacms')
      rescue
        puts "ERROR: could not open mongodb connection"
        exit 1
      end
    end
  end

  def usage
    puts "Usage: #{File.basename(__FILE__)} [CONFIG_FILE]"
    exit 0
  end
end


text:
package com.datastax.spark.connector.writer

import com.datastax.spark.connector.ColumnSelector
import com.datastax.spark.connector.cql.CassandraConnector
import org.apache.spark.SparkContext

abstract class WritableToCassandra[T] {

  def sparkContext: SparkContext

  private[connector] lazy val connector = CassandraConnector(sparkContext.getConf)

  /**
   * Saves the data from [[org.apache.spark.rdd.RDD RDD]] to a Cassandra table.
   * By default, it saves all properties that have corresponding Cassandra columns.
   *
   * Example:
   * {{{
   *   CREATE KEYSPACE test WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1 };
   *   CREATE TABLE test.words(word VARCHAR PRIMARY KEY, count INT, other VARCHAR);
   * }}}
   *
   * {{{
   *   case class WordCount(word: String, count: Int, other: String)
   *   val rdd = sc.parallelize(Seq(WordCount("foo", 5, "bar")))
   * }}}
   *
   * By default, the underlying RDD class must provide data for all columns:
   * {{{
   *   rdd.saveToCassandra("test", "words")
   * }}}
   *
   * By default, writes are performed at ConsistencyLevel.LOCAL_QUORUM.
   * This write consistency level is controlled by the following property:
   *   - spark.cassandra.output.consistency.level: consistency level for RDD writes, string matching the ConsistencyLevel enum name.
   *
   * @param keyspaceName the name of the Keyspace to use
   * @param tableName the name of the Table to use
   * @param columnNames The list of column names to save data to.
   *                Uses only the unique column names, and you must select at least all primary key
   *                columns. All other fields are discarded. Non-selected property/column names are left unchanged.
   * @param writeConf additional configuration object allowing to set consistency level, batch size, etc.
   */
  def saveToCassandra(keyspaceName: String,
                      tableName: String,
                      columnNames: ColumnSelector,
                      writeConf: WriteConf)
                     (implicit connector: CassandraConnector, rwf: RowWriterFactory[T])

}


text:
#ifndef __LAGOPUS_STRUTILS_H__
#define __LAGOPUS_STRUTILS_H__

/**
 *      @file   lagopus_strutils.h
 */

lagopus_result_t
lagopus_str_tokenize(char *buf, char **tokens,
                     size_t max, const char *delm);

lagopus_result_t
lagopus_str_tokenize_quote(char *buf, char **tokens,
                           size_t max, const char *delm, const char *quote);

lagopus_result_t
lagopus_str_unescape(const char *org, const char *escaped,
                     char **retptr);

lagopus_result_t
lagopus_str_trim_right(const char *org, const char *trim_chars,
                       char **retptr);

lagopus_result_t
lagopus_str_parse_int16_by_base(const char *buf, int16_t *val,
                                unsigned int base);
lagopus_result_t
lagopus_str_parse_int16(const char *buf, int16_t *val);
lagopus_result_t
lagopus_str_parse_uint16_by_base(const char *buf, uint16_t *val,
                                 unsigned int base);
lagopus_result_t
lagopus_str_parse_uint16(const char *buf, uint16_t *val);

lagopus_result_t
lagopus_str_parse_int32_by_base(const char *buf, int32_t *val,
                                unsigned int base);
lagopus_result_t
lagopus_str_parse_int32(const char *buf, int32_t *val);
lagopus_result_t
lagopus_str_parse_uint32_by_base(const char *buf, uint32_t *val,
                                 unsigned int base);
lagopus_result_t
lagopus_str_parse_uint32(const char *buf, uint32_t *val);

lagopus_result_t
lagopus_str_parse_int64_by_base(const char *buf, int64_t *val,
                                unsigned int base);
lagopus_result_t
lagopus_str_parse_int64(const char *buf, int64_t *val);
lagopus_result_t
lagopus_str_parse_uint64_by_base(const char *buf, uint64_t *val,
                                 unsigned int base);
lagopus_result_t
lagopus_str_parse_uint64(const char *buf, uint64_t *val);

lagopus_result_t
lagopus_str_parse_float(const char *buf, float *val);

lagopus_result_t
lagopus_str_parse_double(const char *buf, double *val);

lagopus_result_t
lagopus_str_parse_long_double(const char *buf, long double *val);

lagopus_result_t
lagopus_str_parse_bool(const char *buf, bool *val);

#endif /* ! __LAGOPUS_STRUTILS_H__ */


text:
package helpers

import (
	"fmt"
	"syscall"
	"time"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"github.com/tedsuo/ifrit"
)

func StopProcesses(processes ...ifrit.Process) {
	failures := InterceptGomegaFailures(func() {
		for _, process := range processes {
			if process == nil {
				// sometimes components aren't initialized in individual tests, but a full
				// suite may want AfterEach to clean up everything
				continue
			}

			process.Signal(syscall.SIGTERM)
		}

		for _, process := range processes {
			if process == nil {
				// sometimes components aren't initialized in individual tests, but a full
				// suite may want AfterEach to clean up everything
				continue
			}

			select {
			case <-process.Wait():
			case <-time.After(10 * time.Second):
				fmt.Fprintf(GinkgoWriter, "!!!!!!!!!!!!!!!! STOP TIMEOUT !!!!!!!!!!!!!!!!")

				process.Signal(syscall.SIGQUIT)
				Eventually(process.Wait(), 10*time.Second).Should(Receive())

				Expect(true).To(BeFalse(), "process did not shut down cleanly; SIGQUIT sent")
			}
		}
	})

	Expect(failures).To(BeEmpty(), "at least one process failed to shut down cleanly")
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace Core.ReadWrite.Base
{
    public interface IAmValueObject
    {
    }

    [Serializable]
    public abstract class ValueObject<T> : IAmValueObject, IEquatable<T> where T : class
    {
        public virtual bool Equals(T other)
        {
            if (other == null)
                return false;

            var t = GetType();

            var fields = t.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);

            foreach (var field in fields)
            {
                var value1 = field.GetValue(other);
                var value2 = field.GetValue(this);

                if (value1 == null)
                {
                    if (value2 != null)
                        return false;
                }
                else if (value2 == null)
                {
                    return false;
                }
                else if ((typeof (DateTime).IsAssignableFrom(field.FieldType)) ||
                         ((typeof (DateTime?).IsAssignableFrom(field.FieldType))))
                {
                    var dateString1 = ((DateTime) value1).ToLongDateString();
                    var dateString2 = ((DateTime) value2).ToLongDateString();
                    if (!dateString1.Equals(dateString2))
                    {
                        return false;
                    }
                }
                else if (!value1.Equals(value2))
                    return false;
            }

            return true;
        }

        public override bool Equals(object obj)
        {
            if (obj == null)
                return false;

            var other = obj as T;

            return Equals(other);
        }

        public override int GetHashCode()
        {
            var fields = GetFields();

            const int startValue = 17;
            const int multiplier = 59;

            return fields.Select(field => field.GetValue(this))
                .Where(value => value != null)
                .Aggregate(startValue, (current, value) => current*multiplier + value.GetHashCode());
        }

        private IEnumerable<FieldInfo> GetFields()
        {
            var t = GetType();

            var fields = new List<FieldInfo>();

            while (t != typeof (object))
            {
                fields.AddRange(t.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public));

                t = t.BaseType;
            }

            return fields;
        }

        public static bool operator ==(ValueObject<T> x, ValueObject<T> y)
        {
            return ReferenceEquals(x, null) ? ReferenceEquals(y, null) : x.Equals(y);
        }

        public static bool operator !=(ValueObject<T> x, ValueObject<T> y)
        {
            return !(x == y);
        }
    }
}


text:
var table = document.getElementById('coursesTable').getElementsByTagName('TBODY')[0];

console.log("Eli's Extension: ", table);


text:
<?php

?>

<?php include("headercontent.php"); ?>

Home

New

Revised

Tools

Forums

<?php include("footer.php"); ?>


text:
using System;
using GameEngine.Interfaces;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace GameEngine.Drawing.Text
{
    public abstract class TextDrawable : IGameDrawable
    {
        public Vector2 Origin { get; set; }

        public TextDrawable()
        {
            Origin = Vector2.Zero;
        }

        public virtual int GetWidth(double elapsedMS)
        {
            SpriteFont spriteFont = GetSpriteFont(elapsedMS);

            return (int) Math.Ceiling(spriteFont.MeasureString(GetText(elapsedMS)).X);
        }

        public virtual int GetHeight(double elapsedMS)
        {
            SpriteFont spriteFont = GetSpriteFont(elapsedMS);

            return (int) Math.Ceiling(spriteFont.MeasureString(GetText(elapsedMS)).Y);
        }

        public virtual SpriteFont GetSpriteFont(double elapsedMS)
        {
            throw new NotImplementedException();
        }

        public virtual string GetText(double elapsedMS)
        {
            throw new NotImplementedException();
        }

        public virtual bool IsFinished(double elapsedMS)
        {
            return true;
        }

        public void Draw(SpriteBatch spriteBatch, Rectangle destRectangle, Color color, float rotation, Vector2 origin, SpriteEffects spriteEffects, float layerDepth, double elapsedMS)
        {
            float scale = ((float) destRectangle.Height) / GetHeight(elapsedMS);

            spriteBatch.DrawString(
                GetSpriteFont(elapsedMS),
                GetText(elapsedMS),
                new Vector2(destRectangle.Left, destRectangle.Top),
                color,
                rotation,
                origin,
                scale,
                spriteEffects,
                layerDepth
            );
        }
    }
}


text:
package jenkins.slaves;

import hudson.Extension;
import hudson.FilePath;
import jenkins.util.SystemProperties;
import hudson.model.Computer;
import hudson.model.TaskListener;
import hudson.remoting.Channel;
import hudson.remoting.StandardOutputStream;
import hudson.slaves.ComputerListener;
import hudson.util.jna.GNUCLibrary;
import jenkins.security.MasterToSlaveCallable;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Constructor;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author Kohsuke Kawaguchi
 */
@Extension
public class StandardOutputSwapper extends ComputerListener {
    @Override
    public void preOnline(Computer c, Channel channel, FilePath root, TaskListener listener)  {
        if (disabled)   return;

        try {
            if (channel.call(new ChannelSwapper()))
                listener.getLogger().println("Evacuated stdout");
        } catch (Exception x) {
            LOGGER.log(Level.FINE, "Fatal problem swapping file descriptors " + c.getName(), x);
        }
    }

    private static final class ChannelSwapper extends MasterToSlaveCallable<Boolean,Exception> {
        public Boolean call() throws Exception {
            if (File.pathSeparatorChar==';')    return false;   // Windows
            Channel c = getOpenChannelOrFail();
            StandardOutputStream sos = (StandardOutputStream) c.getProperty(StandardOutputStream.class);
            if (sos!=null) {
                _swap(sos);
                return true;
            }

            OutputStream o = c.getUnderlyingOutput();
            if (o instanceof StandardOutputStream) {
                _swap((StandardOutputStream) o);
                return true;
            }

            return false;
        }

        private void _swap(StandardOutputStream stdout) throws Exception {
            try {
                swap(stdout);
            } catch (LinkageError x) {
                throw new Exception(x);
            }
        }

        private void swap(StandardOutputStream stdout) throws IOException, NoSuchMethodException, InstantiationException, IllegalAccessException, java.lang.reflect.InvocationTargetException, UnsatisfiedLinkError {
            // duplicate the OS file descriptor and create FileOutputStream around it
            int out = GNUCLibrary.LIBC.dup(1);
            if (out<0)      throw new IOException("Failed to dup(1)");
            Constructor<FileDescriptor> c = FileDescriptor.class.getDeclaredConstructor(int.class);
            c.setAccessible(true);
            FileOutputStream fos = new FileOutputStream(c.newInstance(out));

            // swap it into channel so that it'll use the new file descriptor
            stdout.swap(fos);

            // close fd=1 (stdout) and duplicate fd=2 (stderr) into fd=1 (stdout)
            GNUCLibrary.LIBC.close(1);
            GNUCLibrary.LIBC.dup2(2,1);
        }
    }

    private static final Logger LOGGER = Logger.getLogger(StandardOutputSwapper.class.getName());
    public static boolean disabled = SystemProperties.getBoolean(StandardOutputSwapper.class.getName()+".disabled");
}


text:
published: true
title: File Manager
tags: file-manager
---
## [CLI](https://www.tecmint.com/linux-terminal-file-managers/)
- [Midnight Commander](http://www.linuxcommand.org/lc3_adv_mc.php)
{% highlight bash %}
sudo apt install mc
{% endhighlight %}