text:
package db

import (
	"context"
	"database/sql"
	"encoding/json"
	"errors"
	"fmt"
	"strconv"
	"time"

	sq "github.com/Masterminds/squirrel"
	"github.com/lib/pq"

	"github.com/concourse/concourse/atc"
	"github.com/concourse/concourse/atc/db/lock"
	"github.com/concourse/concourse/atc/util"
)

var (
	ErrTooManyBuilds           = errors.New("too many builds")
	ErrTooManyResourceVersions = errors.New("too many resoruce versions")
	ErrPinnedThroughConfig     = errors.New("resource is pinned through config")
)

type ResourceHasNoScopeErr struct {
	Name string
}

func (e ResourceHasNoScopeErr) Error() string {
	return fmt.Sprintf("resource/resource-type %s has no scope", e.Name)
}

const CheckBuildName = "check"

type CausalityDirection string

const (
	CausalityDownstream CausalityDirection = "downstream"
	CausalityUpstream   CausalityDirection = "upstream"

	downStreamCausalityQuery = `
WITH RECURSIVE build_ids AS (
		SELECT DISTINCT i.build_id
		FROM build_resource_config_version_inputs i
		WHERE i.resource_id=$1 AND i.version_md5=$2
	UNION
		SELECT i.build_id
		FROM build_ids bi
		INNER JOIN build_resource_config_version_outputs o ON o.build_id = bi.build_id
		INNER JOIN build_resource_config_version_inputs i ON i.resource_id = o.resource_id AND i.version_md5 = o.version_md5
		WHERE i.resource_id!=$1
)
`

	upStreamCausalityQuery = `
WITH RECURSIVE build_ids AS (
		SELECT DISTINCT o.build_id
		FROM build_resource_config_version_outputs o
		WHERE o.resource_id=$1 AND o.version_md5=$2
	UNION
		SELECT o.build_id
		FROM build_ids bi
		INNER JOIN build_resource_config_version_inputs i ON i.build_id = bi.build_id
		INNER JOIN build_resource_config_version_outputs o ON o.resource_id = i.resource_id AND o.version_md5 = i.version_md5
		WHERE i.resource_id!=$1
)
`
	// arbitrary numbers based around what we observed to be reasonable
	causalityMaxBuilds        = 5000
	causalityMaxInputsOutputs = 25000
)

//counterfeiter:generate . Resource
type Resource interface {
	PipelineRef

	ID() int
	Name() string
	Public() bool
	TeamID() int
	TeamName() string
	Type() string
	Source() atc.Source
	CheckEvery() *atc.CheckEvery
	CheckTimeout() string
	LastCheckStartTime() time.Time
	LastCheckEndTime() time.Time
	Tags() atc.Tags
	WebhookToken() string
	Config() atc.ResourceConfig
	ConfigPinnedVersion() atc.Version
	APIPinnedVersion() atc.Version
	PinComment() string
	SetPinComment(string) error
	ResourceConfigID() int
	ResourceConfigScopeID() int
	Icon() string

	HasWebhook() bool

	CurrentPinnedVersion() atc.Version

	BuildSummary() *atc.BuildSummary

	ClearVersions() (int64, error)
	Versions(page Page, versionFilter atc.Version) ([]atc.ResourceVersion, Pagination, bool, error)
	FindVersion(filter atc.Version) (ResourceConfigVersion, bool, error) // Only used in tests!!
	UpdateMetadata(atc.Version, ResourceConfigMetadataFields) (bool, error)

	EnableVersion(rcvID int) error
	DisableVersion(rcvID int) error

	PinVersion(rcvID int) (bool, error)
	UnpinVersion() error

	Causality(rcvID int, direction CausalityDirection) (atc.Causality, bool, error)

	SetResourceConfigScope(ResourceConfigScope) error

	CheckPlan(planFactory atc.PlanFactory, imagePlanner atc.ImagePlanner, from atc.Version, interval atc.CheckEvery, sourceDefaults atc.Source, skipInterval bool, skipIntervalRecursively bool) atc.Plan
	CreateBuild(context.Context, bool, atc.Plan) (Build, bool, error)
	CreateInMemoryBuild(context.Context, atc.Plan, util.SequenceGenerator) (Build, error)

	NotifyScan() error

	ClearResourceCache(atc.Version) (int64, error)

	SharedResourcesAndTypes() (atc.ResourcesAndTypes, error)

	Reload() (bool, error)
}

var (
	resourcesQuery = psql.Select(
		"r.id",
		"r.name",
		"r.type",
		"r.config",
		"rs.last_check_start_time",
		"rs.last_check_end_time",
		"rs.last_check_build_id",
		"rs.last_check_succeeded",
		"rs.last_check_build_plan",
		"r.pipeline_id",
		"r.nonce",
		"r.resource_config_id",
		"r.resource_config_scope_id",
		"p.name",
		"p.instance_vars",
		"t.id",
		"t.name",
		"rp.version",
		"rp.comment_text",
		"rp.config",
		"r.in_memory_build_id",
		"r.in_memory_build_start_time",
		"r.in_memory_build_plan",
		"r.in_memory_build_status",
	).
		From("resources r").
		Join("pipelines p ON p.id = r.pipeline_id").
		Join("teams t ON t.id = p.team_id").
		LeftJoin("resource_config_scopes rs ON r.resource_config_scope_id = rs.id").
		LeftJoin("resource_pins rp ON rp.resource_id = r.id").
		Where(sq.Eq{"r.active": true})
)

type resource struct {
	pipelineRef

	id                    int
	name                  string
	teamID                int
	teamName              string
	type_                 string
	lastCheckStartTime    time.Time
	lastCheckEndTime      time.Time
	config                atc.ResourceConfig
	configPinnedVersion   atc.Version
	apiPinnedVersion      atc.Version
	pinComment            string
	resourceConfigID      int
	resourceConfigScopeID int
	buildSummary          *atc.BuildSummary
}

func newEmptyResource(conn Conn, lockFactory lock.LockFactory) *resource {
	return &resource{pipelineRef: pipelineRef{conn: conn, lockFactory: lockFactory}}
}

type ResourceNotFoundError struct {
	ID int
}

func (e ResourceNotFoundError) Error() string {
	return fmt.Sprintf("resource '%d' not found", e.ID)
}

type Resources []Resource

func (resources Resources) Lookup(name string) (Resource, bool) {
	for _, resource := range resources {
		if resource.Name() == name {
			return resource, true
		}
	}

	return nil, false
}

func (resources Resources) Configs() atc.ResourceConfigs {
	var configs atc.ResourceConfigs
	for _, r := range resources {
		configs = append(configs, r.Config())
	}
	return configs
}

func (r *resource) ID() int                          { return r.id }
func (r *resource) Name() string                     { return r.name }
func (r *resource) Public() bool                     { return r.config.Public }
func (r *resource) TeamID() int                      { return r.teamID }
func (r *resource) TeamName() string                 { return r.teamName }
func (r *resource) Type() string                     { return r.type_ }
func (r *resource) Source() atc.Source               { return r.config.Source }
func (r *resource) CheckEvery() *atc.CheckEvery      { return r.config.CheckEvery }
func (r *resource) CheckTimeout() string             { return r.config.CheckTimeout }
func (r *resource) LastCheckStartTime() time.Time    { return r.lastCheckStartTime }
func (r *resource) LastCheckEndTime() time.Time      { return r.lastCheckEndTime }
func (r *resource) Tags() atc.Tags                   { return r.config.Tags }
func (r *resource) WebhookToken() string             { return r.config.WebhookToken }
func (r *resource) Config() atc.ResourceConfig       { return r.config }
func (r *resource) ConfigPinnedVersion() atc.Version { return r.configPinnedVersion }
func (r *resource) APIPinnedVersion() atc.Version    { return r.apiPinnedVersion }
func (r *resource) PinComment() string               { return r.pinComment }
func (r *resource) ResourceConfigID() int            { return r.resourceConfigID }
func (r *resource) ResourceConfigScopeID() int       { return r.resourceConfigScopeID }
func (r *resource) Icon() string                     { return r.config.Icon }

func (r *resource) HasWebhook() bool { return r.WebhookToken() != "" }

func (r *resource) Reload() (bool, error) {
	row := resourcesQuery.Where(sq.Eq{"r.id": r.id}).
		RunWith(r.conn).
		QueryRow()

	err := scanResource(r, row)
	if err != nil {
		if err == sql.ErrNoRows {
			return false, nil
		}
		return false, err
	}

	return true, nil
}

func (r *resource) SetResourceConfigScope(scope ResourceConfigScope) error {
	tx, err := r.conn.Begin()
	if err != nil {
		return err
	}

	defer Rollback(tx)

	err = setResourceConfigScopeForResource(tx, scope, sq.Eq{"id": r.id})
	if err != nil {
		return err
	}

	err = tx.Commit()
	if err != nil {
		return err
	}

	return nil
}

func setResourceConfigScopeForResource(tx Tx, scope ResourceConfigScope, pred interface{}, args ...interface{}) error {
	var resourceID int
	err := psql.Update("resources").
		Set("resource_config_id", scope.ResourceConfig().ID()).
		Set("resource_config_scope_id", scope.ID()).
		Where(pred, args...).
		Where(sq.Or{
			sq.Eq{"resource_config_id": nil},
			sq.Eq{"resource_config_scope_id": nil},
			sq.NotEq{"resource_config_id": scope.ResourceConfig().ID()},
			sq.NotEq{"resource_config_scope_id": scope.ID()},
		}).
		Suffix("RETURNING id").
		RunWith(tx).
		QueryRow().
		Scan(&resourceID)
	if err != nil {
		if err == sql.ErrNoRows {
			return nil
		}
		return err
	}

	err = requestScheduleForJobsUsingResource(tx, resourceID)
	if err != nil {
		return err
	}

	return nil
}

func (r *resource) CheckPlan(planFactory atc.PlanFactory, imagePlanner atc.ImagePlanner, from atc.Version, interval atc.CheckEvery, sourceDefaults atc.Source, skipInterval bool, skipIntervalRecursively bool) atc.Plan {
	plan := planFactory.NewPlan(atc.CheckPlan{
		Name:    r.name,
		Type:    r.type_,
		Source:  sourceDefaults.Merge(r.config.Source),
		Tags:    r.config.Tags,
		Timeout: r.config.CheckTimeout,

		FromVersion: from,
		Interval:    interval,

		SkipInterval: skipInterval,

		Resource: r.name,
	})

	plan.Check.TypeImage = imagePlanner.ImageForType(plan.ID, r.type_, r.config.Tags, skipInterval && skipIntervalRecursively)
	return plan
}

// CreateBuild tries to create a check build for this resource. A new build
// will only be created if there isn't an existing running check build for this
// resource, or if the build is manuallyTriggered (in which case a new build
// will always be created).
func (r *resource) CreateBuild(ctx context.Context, manuallyTriggered bool, plan atc.Plan) (Build, bool, error) {
	tx, err := r.conn.Begin()
	if err != nil {
		return nil, false, err
	}

	defer Rollback(tx)

	if !manuallyTriggered {
		var numRunningBuilds int
		err = psql.Select("COUNT(1)").
			From("builds").
			Where(sq.Eq{"resource_id": r.id, "completed": false}).
			RunWith(tx).
			QueryRow().
			Scan(&numRunningBuilds)
		if err != nil {
			return nil, false, err
		}

		if numRunningBuilds > 0 {
			// a build is already running; leave it be
			return nil, false, nil
		}
	}

	build := newEmptyBuild(r.conn, r.lockFactory)
	err = createStartedBuild(tx, build, startedBuildArgs{
		Name:              CheckBuildName,
		PipelineID:        r.pipelineID,
		TeamID:            r.teamID,
		Plan:              plan,
		ManuallyTriggered: manuallyTriggered,
		SpanContext:       NewSpanContext(ctx),
		ExtraValues: map[string]interface{}{
			"resource_id": r.id,
		},
	})
	if err != nil {
		return nil, false, err
	}

	err = tx.Commit()
	if err != nil {
		return nil, false, err
	}

	err = r.conn.Bus().Notify(atc.ComponentBuildTracker)
	if err != nil {
		return nil, false, err
	}

	_, err = build.Reload()
	if err != nil {
		return nil, false, err
	}

	return build, true, nil
}

func (r *resource) CreateInMemoryBuild(ctx context.Context, plan atc.Plan, seqGen util.SequenceGenerator) (Build, error) {
	return newRunningInMemoryCheckBuild(r.conn, r.lockFactory, r, plan, NewSpanContext(ctx), seqGen)
}

func (r *resource) UpdateMetadata(version atc.Version, metadata ResourceConfigMetadataFields) (bool, error) {
	versionJSON, err := json.Marshal(version)
	if err != nil {
		return false, err
	}

	metadataJSON, err := json.Marshal(metadata)
	if err != nil {
		return false, err
	}

	_, err = psql.Update("resource_config_versions").
		Set("metadata", string(metadataJSON)).
		Where(sq.Eq{
			"resource_config_scope_id": r.ResourceConfigScopeID(),
		}).
		Where(sq.Expr(
			"version_md5 = md5(?)", versionJSON,
		)).
		RunWith(r.conn).
		Exec()

	if err != nil {
		if err == sql.ErrNoRows {
			return false, nil
		}
		return false, err
	}
	return true, nil
}

// XXX: Deprecated, only used in tests
func (r *resource) FindVersion(v atc.Version) (ResourceConfigVersion, bool, error) {
	if r.resourceConfigScopeID == 0 {
		return nil, false, nil
	}

	ver := &resourceConfigVersion{
		conn: r.conn,
	}

	versionByte, err := json.Marshal(v)
	if err != nil {
		return nil, false, err
	}

	row := resourceConfigVersionQuery.
		Where(sq.Eq{
			"v.resource_config_scope_id": r.resourceConfigScopeID,
		}).
		Where(sq.Expr("v.version_md5 = md5(?)", versionByte)).
		RunWith(r.conn).
		QueryRow()

	err = scanResourceConfigVersion(ver, row)
	if err != nil {
		if err == sql.ErrNoRows {
			return nil, false, nil
		}
		return nil, false, err
	}

	return ver, true, nil
}

func (r *resource) SetPinComment(comment string) error {
	_, err := psql.Update("resource_pins").
		Set("comment_text", comment).
		Where(sq.Eq{"resource_id": r.ID()}).
		RunWith(r.conn).
		Exec()

	return err
}

func (r *resource) CurrentPinnedVersion() atc.Version {
	if r.configPinnedVersion != nil {
		return r.configPinnedVersion
	} else if r.apiPinnedVersion != nil {
		return r.apiPinnedVersion
	}
	return nil
}

func (r *resource) BuildSummary() *atc.BuildSummary {
	return r.buildSummary
}

func (r *resource) ClearVersions() (int64, error) {
	results, err := psql.Delete("resource_config_versions").
		Where(sq.Eq{
			"resource_config_scope_id": r.resourceConfigScopeID,
		}).
		RunWith(r.conn).
		Exec()

	rowsDeleted, err := results.RowsAffected()
	if err != nil {
		return 0, err
	}

	return rowsDeleted, err
}

func (r *resource) Versions(page Page, versionFilter atc.Version) ([]atc.ResourceVersion, Pagination, bool, error) {
	tx, err := r.conn.Begin()
	if err != nil {
		return nil, Pagination{}, false, err
	}

	defer Rollback(tx)

	query := `
		SELECT v.id, v.version, v.metadata, v.check_order,
			NOT EXISTS (
				SELECT 1
				FROM resource_disabled_versions d
				WHERE v.version_md5 = d.version_md5
				AND r.resource_config_scope_id = v.resource_config_scope_id
				AND r.id = d.resource_id
			)
		FROM resource_config_versions v, resources r
		WHERE r.id = $1 AND r.resource_config_scope_id = v.resource_config_scope_id
	`

	filterJSON := "{}"
	if len(versionFilter) != 0 {
		filterBytes, err := json.Marshal(versionFilter)
		if err != nil {
			return nil, Pagination{}, false, err
		}

		filterJSON = string(filterBytes)
	}

	var rows *sql.Rows
	if page.From != nil {
		rows, err = tx.Query(fmt.Sprintf(`
			SELECT sub.*
				FROM (
						%s
					AND version @> $4
					AND v.check_order >= (SELECT check_order FROM resource_config_versions WHERE id = $2)
				ORDER BY v.check_order ASC
				LIMIT $3
			) sub
			ORDER BY sub.check_order DESC
		`, query), r.id, *page.From, page.Limit, filterJSON)
		if err != nil {
			return nil, Pagination{}, false, err
		}
	} else if page.To != nil {
		rows, err = tx.Query(fmt.Sprintf(`
			%s
				AND version @> $4
				AND v.check_order <= (SELECT check_order FROM resource_config_versions WHERE id = $2)
			ORDER BY v.check_order DESC
			LIMIT $3
		`, query), r.id, *page.To, page.Limit, filterJSON)
		if err != nil {
			return nil, Pagination{}, false, err
		}
	} else {
		rows, err = tx.Query(fmt.Sprintf(`
			%s
			AND version @> $3
			ORDER BY v.check_order DESC
			LIMIT $2
		`, query), r.id, page.Limit, filterJSON)
		if err != nil {
			return nil, Pagination{}, false, err
		}
	}

	defer Close(rows)

	type rcvCheckOrder struct {
		ResourceConfigVersionID int
		CheckOrder              int
	}

	rvs := make([]atc.ResourceVersion, 0)
	checkOrderRVs := make([]rcvCheckOrder, 0)
	for rows.Next() {
		var (
			metadataBytes sql.NullString
			versionBytes  string
			checkOrder    int
		)

		rv := atc.ResourceVersion{}
		err := rows.Scan(&rv.ID, &versionBytes, &metadataBytes, &checkOrder, &rv.Enabled)
		if err != nil {
			return nil, Pagination{}, false, err
		}

		err = json.Unmarshal([]byte(versionBytes), &rv.Version)
		if err != nil {
			return nil, Pagination{}, false, err
		}

		if metadataBytes.Valid {
			err = json.Unmarshal([]byte(metadataBytes.String), &rv.Metadata)
			if err != nil {
				return nil, Pagination{}, false, err
			}
		}

		checkOrderRV := rcvCheckOrder{
			ResourceConfigVersionID: rv.ID,
			CheckOrder:              checkOrder,
		}

		rvs = append(rvs, rv)
		checkOrderRVs = append(checkOrderRVs, checkOrderRV)
	}

	if len(rvs) == 0 {
		return nil, Pagination{}, true, nil
	}

	newestRCVCheckOrder := checkOrderRVs[0]
	oldestRCVCheckOrder := checkOrderRVs[len(checkOrderRVs)-1]

	var pagination Pagination

	var olderRCVId int
	err = tx.QueryRow(`
		SELECT v.id
		FROM resource_config_versions v, resources r
		WHERE v.check_order < $2 AND r.id = $1 AND v.resource_config_scope_id = r.resource_config_scope_id
		ORDER BY v.check_order DESC
		LIMIT 1
	`, r.id, oldestRCVCheckOrder.CheckOrder).Scan(&olderRCVId)
	if err != nil && err != sql.ErrNoRows {
		return nil, Pagination{}, false, err
	} else if err == nil {
		pagination.Older = &Page{
			To:    &olderRCVId,
			Limit: page.Limit,
		}
	}

	var newerRCVId int
	err = tx.QueryRow(`
		SELECT v.id
		FROM resource_config_versions v, resources r
		WHERE v.check_order > $2 AND r.id = $1 AND v.resource_config_scope_id = r.resource_config_scope_id
		ORDER BY v.check_order ASC
		LIMIT 1
	`, r.id, newestRCVCheckOrder.CheckOrder).Scan(&newerRCVId)
	if err != nil && err != sql.ErrNoRows {
		return nil, Pagination{}, false, err
	} else if err == nil {
		pagination.Newer = &Page{
			From:  &newerRCVId,
			Limit: page.Limit,
		}
	}

	err = tx.Commit()
	if err != nil {
		return nil, Pagination{}, false, nil
	}

	return rvs, pagination, true, nil
}

func (r *resource) EnableVersion(rcvID int) error {
	return r.toggleVersion(rcvID, true)
}

func (r *resource) DisableVersion(rcvID int) error {
	return r.toggleVersion(rcvID, false)
}

func (r *resource) PinVersion(rcvID int) (bool, error) {
	tx, err := r.conn.Begin()
	if err != nil {
		return false, err
	}
	defer Rollback(tx)
	var pinnedThroughConfig bool
	err = tx.QueryRow(`
		SELECT EXISTS (
			SELECT 1
			FROM resource_pins
			WHERE resource_id = $1
			AND config
		)`, r.id).Scan(&pinnedThroughConfig)
	if err != nil {
		return false, err
	}

	if pinnedThroughConfig {
		return false, ErrPinnedThroughConfig
	}

	results, err := tx.Exec(`
	    INSERT INTO resource_pins(resource_id, version, comment_text, config)
			VALUES ($1,
				( SELECT rcv.version
				FROM resource_config_versions rcv
				WHERE rcv.id = $2 ),
				'', false)
			ON CONFLICT (resource_id) DO UPDATE SET version=EXCLUDED.version`, r.id, rcvID)
	if err != nil {
		if err == sql.ErrNoRows {
			return false, nil
		}
		return false, err
	}

	rowsAffected, err := results.RowsAffected()
	if err != nil {
		return false, err
	}

	if rowsAffected != 1 {
		return false, nil
	}

	err = requestScheduleForJobsUsingResource(tx, r.id)
	if err != nil {
		return false, err
	}

	err = tx.Commit()
	if err != nil {
		return false, err
	}

	return true, nil
}

func (r *resource) UnpinVersion() error {
	tx, err := r.conn.Begin()
	if err != nil {
		return err
	}

	defer tx.Rollback()

	results, err := psql.Delete("resource_pins").
		Where(sq.Eq{"resource_pins.resource_id": r.id}).
		RunWith(tx).
		Exec()
	if err != nil {
		return err
	}

	rowsAffected, err := results.RowsAffected()
	if err != nil {
		return err
	}

	if rowsAffected != 1 {
		return NonOneRowAffectedError{rowsAffected}
	}

	err = requestScheduleForJobsUsingResource(tx, r.id)
	if err != nil {
		return err
	}

	err = tx.Commit()
	if err != nil {
		return err
	}

	return nil
}

func (r *resource) toggleVersion(rcvID int, enable bool) error {
	tx, err := r.conn.Begin()
	if err != nil {
		return err
	}

	defer Rollback(tx)

	var results sql.Result
	if enable {
		results, err = tx.Exec(`
			DELETE FROM resource_disabled_versions
			WHERE resource_id = $1
			AND version_md5 = (SELECT version_md5 FROM resource_config_versions rcv WHERE rcv.id = $2)
			`, r.id, rcvID)
	} else {
		results, err = tx.Exec(`
			INSERT INTO resource_disabled_versions (resource_id, version_md5)
			SELECT $1, rcv.version_md5
			FROM resource_config_versions rcv
			WHERE rcv.id = $2
			`, r.id, rcvID)
	}
	if err != nil {
		return err
	}

	rowsAffected, err := results.RowsAffected()
	if err != nil {
		return err
	}

	if rowsAffected != 1 {
		return NonOneRowAffectedError{rowsAffected}
	}

	err = requestScheduleForJobsUsingResource(tx, r.id)
	if err != nil {
		return err
	}

	return tx.Commit()
}

func (r *resource) NotifyScan() error {
	return r.conn.Bus().Notify(fmt.Sprintf("resource_scan_%d", r.id))
}

func (r *resource) ClearResourceCache(version atc.Version) (int64, error) {
	tx, err := r.conn.Begin()
	if err != nil {
		return 0, err
	}

	defer Rollback(tx)

	selectStatement := psql.Select("id").
		From("resource_caches").
		Where(sq.Eq{
			"resource_config_id": r.resourceConfigID,
		})

	if version != nil {
		versionJson, err := json.Marshal(version)
		if err != nil {
			return 0, err
		}

		selectStatement = selectStatement.Where(
			sq.Expr("version_md5 = md5(?)", versionJson),
		)
	}

	sqlStatement, args, err := selectStatement.ToSql()
	if err != nil {
		return 0, err
	}

	results, err := tx.Exec(`DELETE FROM worker_resource_caches WHERE resource_cache_id IN (`+sqlStatement+`)`, args...)

	if err != nil {
		return 0, err
	}

	rowsDeleted, err := results.RowsAffected()
	if err != nil {
		return 0, err
	}

	return rowsDeleted, tx.Commit()
}

func (r *resource) SharedResourcesAndTypes() (atc.ResourcesAndTypes, error) {
	return sharedResourcesAndTypes(r.conn, r.resourceConfigScopeID, r.name)
}

func sharedResourcesAndTypes(conn Conn, resourceConfigScopeID int, name string) (atc.ResourcesAndTypes, error) {
	if resourceConfigScopeID == 0 {
		return atc.ResourcesAndTypes{}, ResourceHasNoScopeErr{name}
	}

	rows, err := psql.Select("r.name", "p.name", "t.name").
		From("resources r").
		Join("pipelines p ON p.id = r.pipeline_id").
		Join("teams t ON t.id = p.team_id").
		Where(sq.Eq{
			"r.resource_config_scope_id": resourceConfigScopeID,
		}).
		RunWith(conn).
		Query()
	if err != nil {
		return atc.ResourcesAndTypes{}, err
	}

	var shared atc.ResourcesAndTypes
	for rows.Next() {
		var resourceName, pipelineName, teamName string
		err = rows.Scan(&resourceName, &pipelineName, &teamName)
		if err != nil {
			return atc.ResourcesAndTypes{}, err
		}

		shared.Resources = append(shared.Resources, atc.ResourceIdentifier{
			Name:         resourceName,
			PipelineName: pipelineName,
			TeamName:     teamName,
		})
	}

	rows, err = psql.Select("rt.name", "p.name", "t.name").
		From("resource_types rt").
		Join("pipelines p ON p.id = rt.pipeline_id").
		Join("teams t ON t.id = p.team_id").
		Join("resource_config_scopes rs ON rs.resource_config_id = rt.resource_config_id").
		Where(sq.Eq{
			"rs.id": resourceConfigScopeID,
		}).
		RunWith(conn).
		Query()
	if err != nil {
		return atc.ResourcesAndTypes{}, err
	}

	for rows.Next() {
		var resourceTypeName, pipelineName, teamName string
		err = rows.Scan(&resourceTypeName, &pipelineName, &teamName)
		if err != nil {
			return atc.ResourcesAndTypes{}, err
		}

		shared.ResourceTypes = append(shared.ResourceTypes, atc.ResourceIdentifier{
			Name:         resourceTypeName,
			PipelineName: pipelineName,
			TeamName:     teamName,
		})
	}

	return shared, nil
}

func scanResource(r *resource, row scannable) error {
	var (
		configBlob                                        sql.NullString
		nonce, rcID, rcScopeID, pinnedVersion, pinComment sql.NullString
		pinnedThroughConfig                               sql.NullBool
		pipelineInstanceVars                              sql.NullString
		buildData                                         buildData
	)

	err := row.Scan(&r.id, &r.name, &r.type_, &configBlob, &buildData.lastCheckStartTime,
		&buildData.lastCheckEndTime, &buildData.lastCheckBuildId, &buildData.lastCheckSucceeded, &buildData.lastCheckBuildPlan,
		&r.pipelineID, &nonce, &rcID, &rcScopeID,
		&r.pipelineName, &pipelineInstanceVars, &r.teamID, &r.teamName,
		&pinnedVersion, &pinComment, &pinnedThroughConfig,
		&buildData.inMemoryBuildId, &buildData.inMemoryBuildStartTime, &buildData.inMemoryBuildPlan, &buildData.inMemoryBuildStatus)
	if err != nil {
		return err
	}

	es := r.conn.EncryptionStrategy()

	var noncense *string
	if nonce.Valid {
		noncense = &nonce.String
	}

	if configBlob.Valid {
		decryptedConfig, err := es.Decrypt(configBlob.String, noncense)
		if err != nil {
			return err
		}

		err = json.Unmarshal(decryptedConfig, &r.config)
		if err != nil {
			return err
		}
	} else {
		r.config = atc.ResourceConfig{}
	}

	if pinnedVersion.Valid {
		var version atc.Version
		err = json.Unmarshal([]byte(pinnedVersion.String), &version)
		if err != nil {
			return err
		}

		if pinnedThroughConfig.Valid && pinnedThroughConfig.Bool {
			r.configPinnedVersion = version
			r.apiPinnedVersion = nil
		} else {
			r.configPinnedVersion = nil
			r.apiPinnedVersion = version
		}
	} else {
		r.apiPinnedVersion = nil
		r.configPinnedVersion = nil
	}

	if pinComment.Valid {
		r.pinComment = pinComment.String
	} else {
		r.pinComment = ""
	}

	if rcID.Valid {
		r.resourceConfigID, err = strconv.Atoi(rcID.String)
		if err != nil {
			return err
		}
	}

	if rcScopeID.Valid {
		r.resourceConfigScopeID, err = strconv.Atoi(rcScopeID.String)
		if err != nil {
			return err
		}
	}

	if pipelineInstanceVars.Valid {
		err = json.Unmarshal([]byte(pipelineInstanceVars.String), &r.pipelineInstanceVars)
		if err != nil {
			return err
		}
	}

	if buildData.inMemoryBuildId.Valid || buildData.lastCheckBuildId.Valid {
		r.buildSummary = &atc.BuildSummary{
			Name: CheckBuildName,

			TeamName: r.teamName,

			PipelineID:           r.pipelineID,
			PipelineName:         r.pipelineName,
			PipelineInstanceVars: r.pipelineInstanceVars,
		}

		err := buildData.populate(r.buildSummary, &r.lastCheckStartTime, &r.lastCheckEndTime)
		if err != nil {
			return err
		}
	}

	return nil
}

type buildData struct {
	inMemoryBuildId        sql.NullInt64
	inMemoryBuildStartTime pq.NullTime
	inMemoryBuildPlan      sql.NullString
	inMemoryBuildStatus    sql.NullString

	lastCheckBuildId   sql.NullInt64
	lastCheckStartTime pq.NullTime
	lastCheckEndTime   pq.NullTime
	lastCheckSucceeded sql.NullBool
	lastCheckBuildPlan sql.NullString
}

func (d buildData) populate(buildSummary *atc.BuildSummary, lastCheckStart *time.Time, lastCheckEnd *time.Time) error {
	if d.inMemoryBuildId.Valid && d.lastCheckBuildId.Valid {
		// If both ids are valid, and they are same, then we should use info
		// from resource_config_scope; otherwise we use build start time to
		// determine which one is newer.
		if d.inMemoryBuildId.Int64 == d.lastCheckBuildId.Int64 {
			return d.useLastCheckBuild(buildSummary, lastCheckStart, lastCheckEnd)
		} else {
			if d.inMemoryBuildStartTime.Time.Before(d.lastCheckStartTime.Time) {
				return d.useLastCheckBuild(buildSummary, lastCheckStart, lastCheckEnd)
			} else {
				return d.useInMemoryBuild(buildSummary, lastCheckStart)
			}
		}
	} else if d.lastCheckBuildId.Valid {
		return d.useLastCheckBuild(buildSummary, lastCheckStart, lastCheckEnd)
	} else if d.inMemoryBuildId.Valid {
		return d.useInMemoryBuild(buildSummary, lastCheckStart)
	}
	return errors.New("no build info available")
}

func (d buildData) useInMemoryBuild(buildSummary *atc.BuildSummary, lastCheckStart *time.Time) error {
	buildSummary.ID = int(d.inMemoryBuildId.Int64)
	buildSummary.StartTime = d.inMemoryBuildStartTime.Time.Unix()
	buildSummary.Status = atc.BuildStatus(d.inMemoryBuildStatus.String)
	*lastCheckStart = d.inMemoryBuildStartTime.Time
	if d.inMemoryBuildPlan.Valid {
		err := json.Unmarshal([]byte(d.inMemoryBuildPlan.String), &buildSummary.PublicPlan)
		if err != nil {
			return err
		}
	}
	return nil
}

func (d buildData) useLastCheckBuild(buildSummary *atc.BuildSummary, lastCheckStart *time.Time, lastCheckEnd *time.Time) error {
	buildSummary.ID = int(d.lastCheckBuildId.Int64)
	buildSummary.StartTime = d.lastCheckStartTime.Time.Unix()
	*lastCheckStart = d.lastCheckStartTime.Time
	if d.lastCheckEndTime.Valid && d.lastCheckStartTime.Time.Before(d.lastCheckEndTime.Time) {
		buildSummary.EndTime = d.lastCheckEndTime.Time.Unix()
		*lastCheckEnd = d.lastCheckEndTime.Time
		if d.lastCheckSucceeded.Valid && d.lastCheckSucceeded.Bool {
			buildSummary.Status = atc.StatusSucceeded
		} else {
			buildSummary.Status = atc.StatusFailed
		}
	} else {
		buildSummary.Status = atc.StatusStarted
	}

	if d.lastCheckBuildPlan.Valid {
		err := json.Unmarshal([]byte(d.lastCheckBuildPlan.String), &buildSummary.PublicPlan)
		if err != nil {
			return err
		}
	}
	return nil
}

// The SELECT query orders the jobs for updating to prevent deadlocking.
// Updating multiple rows using a SELECT subquery does not preserve the same
// order for the updates, which can lead to deadlocking.
func requestScheduleForJobsUsingResource(tx Tx, resourceID int) error {
	rows, err := psql.Select("DISTINCT job_id").
		From("job_inputs").
		Where(sq.Eq{
			"resource_id": resourceID,
		}).
		OrderBy("job_id DESC").
		RunWith(tx).
		Query()
	if err != nil {
		return err
	}

	var jobs []int
	for rows.Next() {
		var jid int
		err = rows.Scan(&jid)
		if err != nil {
			return err
		}

		jobs = append(jobs, jid)
	}

	for _, j := range jobs {
		_, err := psql.Update("jobs").
			Set("schedule_requested", sq.Expr("now()")).
			Where(sq.Eq{
				"id": j,
			}).
			RunWith(tx).
			Exec()
		if err != nil {
			return err
		}
	}

	return nil
}

// this allows us to reuse getCausalityResourceVersions to construct both upstream and downstream trees by passing in a different updater fn
type resourceVersionUpdater func(*atc.CausalityResourceVersion, *atc.CausalityBuild)

func contains(lst []int, e int) bool {
	for _, v := range lst {
		if e == v {
			return true
		}
	}
	return false
}

func causalityQuery(direction CausalityDirection) string {
	switch direction {
	case CausalityDownstream:
		return downStreamCausalityQuery
	case CausalityUpstream:
		return upStreamCausalityQuery
	default:
		return ""
	}
}

type resourceVersionKey struct {
	resourceID int
	versionID  int
}

// causalityBuilds figures out all the builds that are related to a particular resource version
// This can include builds that were used the resource version (and its descendents) as an input,
// and builds that generated some ancestor of the build that generated the resource version itself.
func causalityBuilds(tx Tx, resourceID int, versionMD5 string, direction CausalityDirection) (map[int]*atc.CausalityBuild, map[int]*atc.CausalityJob, error) {
	query := causalityQuery(direction)
	// construct the job and build nodes. These are placed into a map for easy access down the line
	rows, err := psql.Select("b.id", "b.name", "b.status", "j.id", "j.name").
		Prefix(query, resourceID, versionMD5).
		From("build_ids bi").
		Join("builds b ON b.id = bi.build_id").
		Join("jobs j ON b.job_id = j.id").
		Limit(causalityMaxBuilds).
		RunWith(tx).
		Query()
	if err != nil {
		return nil, nil, err
	}

	defer rows.Close()

	builds := make(map[int]*atc.CausalityBuild)
	jobs := make(map[int]*atc.CausalityJob)

	var i int
	for i = 0; rows.Next(); i++ {
		var buildID, jobID int
		var buildName, jobName, status string

		err = rows.Scan(&buildID, &buildName, &status, &jobID, &jobName)
		if err != nil {
			return nil, nil, err
		}

		job, found := jobs[jobID]
		if !found {
			job = &atc.CausalityJob{
				ID:   jobID,
				Name: jobName,
			}
		}
		// since we only iterate over each build once, this should never insert any duplicates
		job.BuildIDs = append(job.BuildIDs, buildID)

		build := &atc.CausalityBuild{
			ID:     buildID,
			Name:   buildName,
			JobId:  jobID,
			Status: atc.BuildStatus(status),
		}

		builds[buildID] = build
		jobs[jobID] = job
	}
	if i == causalityMaxBuilds {
		return nil, nil, ErrTooManyBuilds
	}

	return builds, jobs, nil
}

func causalityResourceVersions(tx Tx, resourceID int, versionMD5 string, direction CausalityDirection, result *atc.Causality) error {
	// Bitmap to filter out resources that are not part of a output-input chain. This is done to filter out any other "root" resources.
	// For now, the causality view is only intersted in the "downstream" resources, not neccessarily "parallel input" resources
	// (reverse is true for upstream causality). If this ever changes in the future, it would be trivial to remove this filtering and get
	// a more "pipeline-like" causality view
	resourceHasParent := make(map[int]bool)
	resourceHasParent[resourceID] = true // the root resource is the only one that is not required to have a parent

	buildAsChild := func(rv *atc.CausalityResourceVersion, build *atc.CausalityBuild) {
		if !contains(rv.BuildIDs, build.ID) { // in case the same resource is used multiple times
			rv.BuildIDs = append(rv.BuildIDs, build.ID)
		}
	}
	resourceVersionAsChild := func(rv *atc.CausalityResourceVersion, build *atc.CausalityBuild) {
		if !contains(build.ResourceVersionIDs, rv.ID) { // in case a build outputs the same resource multiple times
			build.ResourceVersionIDs = append(build.ResourceVersionIDs, rv.ID)
		}

		resourceHasParent[rv.ResourceID] = true
	}

	var handleInput, handleOutput resourceVersionUpdater
	switch direction {
	case CausalityDownstream:
		// for every build input (resource version), add the build to its children
		// for every build output, register it as a child of the build
		handleInput = buildAsChild
		handleOutput = resourceVersionAsChild
	case CausalityUpstream:
		// for every build input (resource version), register it as a child of the build
		// for every build output, add the build to its children
		handleInput = resourceVersionAsChild
		handleOutput = buildAsChild
	}

	builds, jobs, err := causalityBuilds(tx, resourceID, versionMD5, direction)
	if err != nil {
		return err
	}

	query := causalityQuery(direction) + `
	SELECT r.id, rcv.id, r.name, rcv.version, i.build_id, 'input' AS type
	FROM build_resource_config_version_inputs i
	JOIN resources r ON r.id = i.resource_id
	JOIN resource_config_versions rcv ON rcv.version_md5 = i.version_md5 AND rcv.resource_config_scope_id = r.resource_config_scope_id
	JOIN build_ids bi ON i.build_id = bi.build_id
UNION ALL
	SELECT r.id, rcv.id, r.name, rcv.version, o.build_id, 'output' AS type
	FROM build_resource_config_version_outputs o
	JOIN resources r ON r.id = o.resource_id
	JOIN resource_config_versions rcv ON rcv.version_md5 = o.version_md5 AND rcv.resource_config_scope_id = r.resource_config_scope_id
	JOIN build_ids bi ON o.build_id = bi.build_id
LIMIT $3
`

	rows, err := tx.Query(query, resourceID, versionMD5, causalityMaxInputsOutputs)
	if err != nil {
		return err
	}

	defer rows.Close()

	resources := make(map[int]*atc.CausalityResource)
	resourceVersions := make(map[resourceVersionKey]*atc.CausalityResourceVersion)

	var i int
	for i = 0; rows.Next(); i++ {
		var (
			rID, rcvID, bID        int
			rName, versionStr, typ string
			version                atc.Version
		)
		err = rows.Scan(&rID, &rcvID, &rName, &versionStr, &bID, &typ)
		if err != nil {
			return err
		}

		err = json.Unmarshal([]byte(versionStr), &version)
		if err != nil {
			return err
		}

		r, found := resources[rID]
		if !found {
			r = &atc.CausalityResource{
				ID:   rID,
				Name: rName,
			}
		}
		if !contains(r.VersionIDs, rcvID) {
			r.VersionIDs = append(r.VersionIDs, rcvID)
		}

		rv, found := resourceVersions[resourceVersionKey{rID, rcvID}]
		if !found {
			rv = &atc.CausalityResourceVersion{
				ID:         rcvID,
				Version:    version,
				ResourceID: rID,
			}
		}

		switch typ {
		case "input":
			handleInput(rv, builds[bID])
		case "output":
			handleOutput(rv, builds[bID])
		default:
			return fmt.Errorf("unknown type: %v", typ)
		}

		resources[rID] = r
		resourceVersions[resourceVersionKey{rID, rcvID}] = rv
	}

	if i == causalityMaxInputsOutputs {
		return ErrTooManyResourceVersions
	}

	// flattening
	result.ResourceVersions = make([]atc.CausalityResourceVersion, 0, len(resourceVersions))
	unusedResourceVersions := make([]int, 0)
	for _, rv := range resourceVersions {
		if resourceHasParent[rv.ResourceID] {
			result.ResourceVersions = append(result.ResourceVersions, *rv)
		} else {
			unusedResourceVersions = append(unusedResourceVersions, rv.ID)
		}
	}
	result.Resources = make([]atc.CausalityResource, 0, len(resources))
	for id, r := range resources {
		if resourceHasParent[id] {
			result.Resources = append(result.Resources, *r)
		}
	}

	result.Builds = make([]atc.CausalityBuild, 0, len(builds))
	for _, b := range builds {
		// remove any resource version ids that don't have a parent
		filteredResourceVersions := make([]int, 0)
		for _, rvID := range b.ResourceVersionIDs {
			if !contains(unusedResourceVersions, rvID) {
				filteredResourceVersions = append(filteredResourceVersions, rvID)
			}
		}

		b.ResourceVersionIDs = filteredResourceVersions
		result.Builds = append(result.Builds, *b)
	}
	result.Jobs = make([]atc.CausalityJob, 0, len(jobs))
	for _, j := range jobs {
		result.Jobs = append(result.Jobs, *j)
	}
	return nil
}

func (r *resource) Causality(rcvID int, direction CausalityDirection) (atc.Causality, bool, error) {
	result := atc.Causality{}

	tx, err := r.conn.Begin() // in case some new build is started in between the 2 expensive queries
	if err != nil {
		return result, false, err
	}

	defer Rollback(tx) // everything is readonly, so no need to commit

	var versionMD5 string
	err = psql.Select("version_md5").
		From("resource_config_versions").
		Where(sq.Eq{"id": rcvID}).
		RunWith(tx).
		Scan(&versionMD5)
	if err != nil {
		return result, false, err
	}

	err = causalityResourceVersions(tx, r.id, versionMD5, direction, &result)
	if err != nil {
		return result, false, err
	}

	return result, true, nil
}


text:
package uk.gov.dvsa.ui.pages.vts.ChangeDetails;

import org.openqa.selenium.By;
import uk.gov.dvsa.domain.model.site.ContactDetailsCountry;
import uk.gov.dvsa.framework.config.webdriver.MotAppDriver;
import uk.gov.dvsa.helper.FormDataHelper;

public class ChangeDetailsCountryPage extends ChangeDetailsPage {
    public static final String PAGE_TITLE = "Change country";
    public static final String PATH = "/vehicle-testing-station/%s/country/change";

    public ChangeDetailsCountryPage(MotAppDriver driver) {
        super(driver, PAGE_TITLE);
    }

    public ChangeDetailsCountryPage chooseOption(ContactDetailsCountry name) {
        FormDataHelper.selectInputBox(driver.findElement(By.cssSelector(String.format("input[value=%s]", name.getSiteContactDetailsCountryCode()))));
        return this;
    }
}

redpajama_set_name: RedPajamaGithub


text:
from ansible import errors

def exclude(a, b):
    temp = a.copy()
    if isinstance(a,dict):
        temp.pop(b, None)
    return temp
class FilterModule(object):
    def filters(self):
        return {
            'exclude': exclude
        }


text:
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#import <UIKit/UIKit.h>

#import <AccountKit/AKFButtonType.h>
#import <AccountKit/AKFLoginFlowState.h>
#import <AccountKit/AKFTextPosition.h>

NS_ASSUME_NONNULL_BEGIN

/**
 @protocol

  A controller that exposes actions to the AKFAdvancedUIManager
 */
@protocol AKFAdvancedUIActionController <NSObject>

/**
  Triggers a pop of the current state.
 */
- (void)back;

/**
  Triggers the login flow to cancel.
 */
- (void)cancel;

@end

/**
 @protocol

  Manager for advanced UI configuration.
 */
@protocol AKFAdvancedUIManager <NSObject>

@optional

/**
  Returns a custom view to use above the scrollable content.

 - Parameter state: the current state of the login flow

 - Returns: a View or null for the default view
 */
- (nullable UIView *)actionBarViewForState:(AKFLoginFlowState)state;

/**
  Returns a custom view for the body in the middle of the scrollable container.

 - Parameter state: the current state of the login flow

 - Returns: a View or null for the default view
 */
- (nullable UIView *)bodyViewForState:(AKFLoginFlowState)state;

/**
  Returns the button type for the given login state.

 This method is only called for PhoneLogin, EmailLogin and ConfirmationCode states.

 - Parameter state: the current state of the login flow

 - Returns: the button type for the state
 */
- (AKFButtonType)buttonTypeForState:(AKFLoginFlowState)state;

/**
  Returns a custom view for the bottom of the content in the scrollable container.

 - Parameter state: the current state of the login flow

 - Returns: a View or null for the default view
 */
- (nullable UIView *)footerViewForState:(AKFLoginFlowState)state;

/**
  Returns a custom view for the top of the content in the scrollable container.

 - Parameter state: the current state of the login flow

 - Returns: a View or null for the default view
 */
- (nullable UIView *)headerViewForState:(AKFLoginFlowState)state;

/**
  Provides a controller for the receiver that can send messages back to the current controller.

 This method will be called before any views are retrieved.

 - Parameter actionController: the action controller
 */
- (void)setActionController:(nonnull id<AKFAdvancedUIActionController>)actionController;

/**
  Called when an error is encountered and should be displayed in the UI.

 This method will be called before the views are retrieved.

 - Parameter error: the error
 */
- (void)setError:(nonnull NSError *)error;

/**
  Returns the position of the text relative to the content body view.

 - Parameter state: the current state of the login flow

 - Returns: a text position
 */
- (AKFTextPosition)textPositionForState:(AKFLoginFlowState)state;

@end

NS_ASSUME_NONNULL_END


text:
//=================================================================================================

//=================================================================================================

#ifndef _BLAZE_MATH_TYPETRAITS_HASASINH_H_
#define _BLAZE_MATH_TYPETRAITS_HASASINH_H_

//*************************************************************************************************
// Includes
//*************************************************************************************************

#include <utility>
#include <blaze/math/typetraits/IsMatrix.h>
#include <blaze/math/typetraits/IsVector.h>
#include <blaze/util/EnableIf.h>
#include <blaze/util/IntegralConstant.h>
#include <blaze/util/typetraits/Void.h>

namespace blaze {

//=================================================================================================
//
//  CLASS DEFINITION
//
//=================================================================================================

//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Auxiliary helper struct for the HasAsinh type trait.
// \ingroup math_type_traits
*/
template< typename T, typename = void >
struct HasAsinhHelper
   : public FalseType
{};
/*! \endcond */
//*************************************************************************************************

//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Specialization of the HasAsinhHelper type trait for types providing the asinh() operation.
// \ingroup math_type_traits
*/
template< typename T >
struct HasAsinhHelper< T, Void_t< decltype( asinh( std::declval<T>() ) ) > >
   : public TrueType
{};
/*! \endcond */
//*************************************************************************************************

//*************************************************************************************************
/*!\brief Availability of the asinh() operation for the given data types.
// \ingroup math_type_traits
//
// This type trait provides the information whether the asinh() operation exists for the given
// data type \a T (taking the cv-qualifiers into account). In case the operation is available,
// the \a value member constant is set to \a true, the nested type definition \a Type is
// \a TrueType, and the class derives from \a TrueType. Otherwise \a value is set to \a false,
// \a Type is \a FalseType, and the class derives from \a FalseType.

   \code
   struct NoAsinh {};  // Definition of a type without the asinh() operation

   blaze::HasAsinh< int >::value                  // Evaluates to 1
   blaze::HasAsinh< DynamicVector<float> >::Type  // Results in TrueType
   blaze::HasAsinh< DynamicMatrix<double> >       // Is derived from TrueType
   blaze::HasAsinh< NoAsinh >::value              // Evaluates to 0
   blaze::HasAsinh< NoAsinh >::Type               // Results in FalseType
   blaze::HasAsinh< NoAsinh >                     // Is derived from FalseType
   \endcode
*/
template< typename T, typename = void >
struct HasAsinh
   : public HasAsinhHelper<T>
{};
//*************************************************************************************************

//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Specialization of the HasAsinh type trait for vectors.
// \ingroup math_type_traits
*/
template< typename T >
struct HasAsinh< T, EnableIf_t< IsVector_v<T> > >
   : public HasAsinh< typename T::ElementType >
{};
/*! \endcond */
//*************************************************************************************************

//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Specialization of the HasAsinh type trait for matrices.
// \ingroup math_type_traits
*/
template< typename T >
struct HasAsinh< T, EnableIf_t< IsMatrix_v<T> > >
   : public HasAsinh< typename T::ElementType >
{};
/*! \endcond */
//*************************************************************************************************

//*************************************************************************************************
/*!\brief Auxiliary variable template for the HasAsinh type trait.
// \ingroup math_type_traits
//
// The HasAsinh_v variable template provides a convenient shortcut to access the nested \a value
// of the HasAsinh class template. For instance, given the type \a T the following two statements
// are identical:

   \code
   constexpr bool value1 = blaze::HasAsinh<T>::value;
   constexpr bool value2 = blaze::HasAsinh_v<T>;
   \endcode
*/
template< typename T >
constexpr bool HasAsinh_v = HasAsinh<T>::value;
//*************************************************************************************************

} // namespace blaze

#endif


text:
}
#button-dialog div {
	padding: 5px 0;
	height: 20px;
}
#button-dialog label {
	display: block;
	float: left;
	margin: 0 8px 0 0;
	width: 80px;
}
#button-dialog select, #button-dialog input {
	display: block;
	width: 165px;
	padding: 3px 5px;
}
#button-dialog select {
	width: 112px;
}
#button-dialog #insert {
	display: block;
	line-height: 24px;
	text-align: center;
	margin: 10px 0 0 0;
	float: right;
}

.description{margin-top:-.5em; }
.description{ margin: 3px 0 0 0; color: #666; font-style: italic; }


text:
<?php

namespace app\components\validators;

use yii\validators\Validator;

class SenhaValidator extends Validator
{
    public function validateAttribute($model, $attribute)
    {
        if (empty($model->password_repeat)) {
            $this->addError($model, "password_repeat", 'Confirme a senha deve ser preenchido!');
        }else if(!empty($model->password_repeat) && empty($model->password)){
            $this->addError($model, "password", 'A senha deve ser preenchida!');
        }else if($model->password_repeat != $model->password){
            $this->addError($model, "password_repeat", 'Senhas diferentes!');
        }
    }
}


text:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { DataTransferConfigEditorComponent } from './components/data-transfer-config-editor/data-transfer-config-editor.component';

const routes: Routes = [
  { path: '' , component: DataTransferConfigEditorComponent }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class DataTransferConfigEditorRoutingModule { }


text:
module Mapmaker
  class Page
    attr_accessor :url, :updated_at, :priority, :change_frequency

    def initialize(new_url, options = {})
      self.url = new_url
      options.each {|attr_name, value| self.send "#{attr_name}=", value }
    end
  end

  class UrlSet
    def initialize(hostname, proc)
      @hostname = hostname
      @page_store = []
      create_load_pages_method proc
    end

    def page(url, options = {})
      @page_store << Page.new(@hostname + url, options)
    end

    def reflect_off_controller(controller_class, url_format_string, options = {})
      controller_actions = controller_class.public_instance_methods -
                           controller_class.hidden_actions -
                           ApplicationController.public_instance_methods

      options[:mixins_to_exclude] and options[:mixins_to_exclude].each do |mixins|
        controller_actions -= mixins.public_instance_methods
      end

      controller_actions.each do |method_name|
        page url_format_string % method_name, options.except(:mixins_to_exclude)
      end
    end

    def pages
      send :load_pages if @page_store.empty?
      @page_store
    end
  private
    def create_load_pages_method(block)
      klass = class << self; self; end
      klass.instance_eval do
        define_method :load_pages, block
      end
    end
  end

  class ConfigurationManager
    DEFAULT_KEY = :default
    @@configurations = {}

    def self.config
      @@configurations unless @@configurations.empty?

      file_name = RAILS_ROOT + '/config/sitemap.rb'
      instance_eval read_config_file(file_name)

      @@configurations
    end

  private
    def self.read_config_file(file_name)
      File.open(file_name) { |f| f.read }
    end

    def self.sitemap(*args)
      unless args.size == 1 or args.size == 2
        raise "Must specify either the hostname or a key/hostname combo in the case of multiple sitemaps"
      end

      key = args.size > 1 ? args.shift : DEFAULT_KEY

      @@current_config = @@configurations[key] = Configuration.new(args.shift)
      yield
      @@current_config = nil
    end

    def self.url_set(name, &block)
      @@current_config.send :add_url_set, name, block
    end
  end

  class Configuration
    attr_reader :hostname

    def initialize(hostname)
      @hostname = hostname
      @urlsets = {}
    end

    def [](key)
      @urlsets[key].pages
    end

    def keys
      @urlsets.keys
    end

    def only_one_url_set?
      @urlsets.size == 1
    end

  private
    def add_url_set(name, block)
      @urlsets[name] = UrlSet.new(@hostname, block)
    end
  end # end config
end


text:
@interface UIFont (Octicons)

+ (UIFont *)octicon_fontOfSize:(CGFloat)size;

@end


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2017.11.30 at 08:24:17 PM JST
//

package uk.org.siri.siri;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.datatype.XMLGregorianCalendar;

/**
 * Type for a range of date and times. Both start and end time are required.
 *
 *
Java class for ClosedTimestampRangeStructure complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="ClosedTimestampRangeStructure">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="StartTime" type="{http://www.w3.org/2001/XMLSchema}dateTime"/>
 *         <element name="EndTime" type="{http://www.w3.org/2001/XMLSchema}dateTime"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ClosedTimestampRangeStructure", propOrder = {
    "startTime",
    "endTime"
})
public class ClosedTimestampRangeStructure {

    @XmlElement(name = "StartTime", required = true)
    @XmlSchemaType(name = "dateTime")
    protected XMLGregorianCalendar startTime;
    @XmlElement(name = "EndTime", required = true)
    @XmlSchemaType(name = "dateTime")
    protected XMLGregorianCalendar endTime;

    /**
     * Gets the value of the startTime property.
     *
     * @return
     *     possible object is
     *     {@link XMLGregorianCalendar }
     *
     */
    public XMLGregorianCalendar getStartTime() {
        return startTime;
    }

    /**
     * Sets the value of the startTime property.
     *
     * @param value
     *     allowed object is
     *     {@link XMLGregorianCalendar }
     *
     */
    public void setStartTime(XMLGregorianCalendar value) {
        this.startTime = value;
    }

    /**
     * Gets the value of the endTime property.
     *
     * @return
     *     possible object is
     *     {@link XMLGregorianCalendar }
     *
     */
    public XMLGregorianCalendar getEndTime() {
        return endTime;
    }

    /**
     * Sets the value of the endTime property.
     *
     * @param value
     *     allowed object is
     *     {@link XMLGregorianCalendar }
     *
     */
    public void setEndTime(XMLGregorianCalendar value) {
        this.endTime = value;
    }

}


text:
package edu.internet2.middleware.shibboleth.common.config.attribute.filtering.match.basic;

import org.opensaml.xml.util.DatatypeHelper;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.w3c.dom.Element;

/**
 * Bean definition parser for match functions that match a string value against an attribute value.
 */
public abstract class AbstractAttributeTargetedRegexMatchFunctorBeanDefinitionParser extends
        AbstractRegexMatchFunctorBeanDefinitionParser {

    /** {@inheritDoc} */
    protected void doParse(Element configElement, BeanDefinitionBuilder builder) {
        super.doParse(configElement, builder);

        builder.addPropertyValue("attributeId", DatatypeHelper.safeTrimOrNullString(configElement.getAttributeNS(null,
                "attributeID")));
    }
}


text:
<?php
/**
 * This file is part of the tic-tac-toe project.
 *
 * (c) Yannick Voyer (http://github.com/yvoyer)
 */

namespace Star\TicTacToe\Grid;

use Star\TicTacToe\Id\CellId;
use Star\TicTacToe\Id\ColumnRowId;
use Star\TicTacToe\Player;

/**
 * Class ColumnRowGridTest
 *
 * @author  Yannick Voyer (http://github.com/yvoyer)
 *
 * @package Star\TicTacToe\Grid
 *
 * @covers Star\TicTacToe\Grid\CellGrid
 * @uses Star\TicTacToe\Id\ColumnRowId
 */
class CellGridTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var CellGrid|\PHPUnit_Framework_MockObject_MockObject
     */
    private $grid;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    private $player;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    private $display;

    public function setUp()
    {
        $this->player = $this->getMockPlayer();
        $this->display = $this->getMock('Star\TicTacToe\Display\Display');

        $this->grid = $this->getMockForAbstractClass('Star\TicTacToe\Grid\CellGrid', array(), '', false);
    }

    /**
     * @expectedException        \InvalidArgumentException
     * @expectedExceptionMessage The cell id 'r,4' is not found.
     */
    public function test_should_throw_exception_when_not_found_id()
    {
        $this->grid->play(new ColumnRowId('r', 4), $this->player);
    }

    /**
     * @return \PHPUnit_Framework_MockObject_MockObject
     */
    private function getMockPlayer()
    {
        return $this->getMockBuilder(Player::CLASS_NAME)->disableOriginalConstructor()->getMock();
    }
}


text:
import { chunk } from "lodash";
export = chunk;


text:
@echo off
echo OpenGL Programm Assistent - MinGW
echo =======================================

set staticDefault=-static-libgcc -static-libstdc++
set staticSFML=-lglew32 -lsfml-graphics-s -lsfml-window-s -lsfml-system-s -lopengl32 -lwinmm -lgdi32 -ljpeg
:: -lwinmm and -lgdi32 for staticSDL too, but static SFML already contains them
:: Information for static SDL linking from here: http://stackoverflow.com/a/18561999
set staticSDL=-lmingw32 -lSDL2main -lSDL2 -lm -ldinput8 -ldxguid -ldxerr8 -luser32 -limm32 -lole32 -loleaut32 -lshell32 -lversion -luuid
set staticSDLTTF=-lSDL2_ttf -lfreetype

g++ -IC:/MinGW/include/ -LC:/MinGW/lib/ -std=c++11 -fmax-errors=1 -s -Os -o lifeIsComplex.exe /path/to/src/lifeIsComplex.cpp %staticDefault% %staticSDL% %staticSFML% %staticSDLTTF%
echo.
upx lifeIsComplex.exe
echo.
pause


text:
package com.example.restservicedemo.service;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.example.restservicedemo.domain.Car;
import com.example.restservicedemo.domain.CarPerson;
import com.example.restservicedemo.domain.Person;

public class CarPersonManager {

	private Connection connection;

	private static final String URL = "jdbc:hsqldb:hsql://localhost/workdb";
	private static final String CREATE_TABLE_CAR_TO_PERSON = "CREATE TABLE CarHasPerson(idcar bigint, idperson bigint)";

	private PreparedStatement addCarToPersonStmt;
	private PreparedStatement deleteAllStmt;
	private PreparedStatement getAllCarsToPersonStmt;
	private PreparedStatement getCarPersonsStmt;
	private PreparedStatement getPersonCarsByIdStmt;
	private PreparedStatement getCarByIdStmt;
	private PreparedStatement getPersonByIdStmt;

	private Statement statement;

	public CarPersonManager() {
		try {
			connection = DriverManager.getConnection(URL);
			statement = connection.createStatement();

			ResultSet rs = connection.getMetaData().getTables(null, null, null,
					null);
			boolean tableExists = false;
			while (rs.next()) {
				if ("CarHasPerson".equalsIgnoreCase(rs.getString("TABLE_NAME"))) {
					tableExists = true;
					break;
				}
			}

			if (!tableExists)
				statement.executeUpdate(CREATE_TABLE_CAR_TO_PERSON);

			addCarToPersonStmt = connection
					.prepareStatement("INSERT INTO CarHasPerson (idcar,idperson) VALUES (?, ?)");
			deleteAllStmt = connection
					.prepareStatement("DELETE FROM CarHasPerson");
			getAllCarsToPersonStmt = connection
					.prepareStatement("SELECT idcar,idperson FROM CarHasPerson");
			getCarPersonsStmt = connection
					.prepareStatement("SELECT idcar, idperson FROM CarHasPerson where idcar = ?");
			getPersonCarsByIdStmt = connection
					.prepareStatement("SELECT idcar, idperson FROM CarHasPerson where idperson = ?");
			getPersonByIdStmt = connection
					.prepareStatement("SELECT id, name, yob FROM Person where id = ?");

		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	Connection getConnection() {
		return connection;
	}

	public void clearCarstoPersons() {
		try {
			deleteAllStmt.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public int addCarToPerson(Car Car,Person person) {
		int count = 0;
		try {
			addCarToPersonStmt.setLong(1, Car.getId());
			addCarToPersonStmt.setLong(2, person.getId());

			count = addCarToPersonStmt.executeUpdate();

		} catch (SQLException e) {
			e.printStackTrace();
		}
		return count;
	}

	public List<CarPerson> getAllCars() {
		List<CarPerson> Stmt = new ArrayList<CarPerson>();

		try {
			ResultSet rs = getAllCarsToPersonStmt.executeQuery();

			while (rs.next()) {
				CarPerson p = new CarPerson();
				p.setIdCar(rs.getInt("idcar"));
				p.setIdPerson(rs.getInt("idperson"));
				Stmt.add(p);
			}

		} catch (SQLException e) {
			e.printStackTrace();
		}
		return Stmt;
	}

	public List<Car> getAllPersonCars(Long id) {
		List<Car> Stmt = new ArrayList<Car>();
		CarManager cm = new CarManager();
		try {
			getPersonCarsByIdStmt.setLong(1, id);
			ResultSet rs = getPersonCarsByIdStmt.executeQuery();
			while (rs.next()) {
				Stmt.add(cm.getCar(rs.getLong("idcar")));
			}

		} catch (SQLException e) {
			e.printStackTrace();
		}

		return Stmt;
	}

	public List<Person> getAllCarPersons(Long id) {
		List<Person> Stmt = new ArrayList<Person>();
		try {
			getCarPersonsStmt.setLong(1, id);
			ResultSet rs = getCarPersonsStmt.executeQuery();

			while (rs.next()) {
				getPersonByIdStmt.setLong(1, rs.getInt("idperson"));
				ResultSet rsc = getCarByIdStmt.executeQuery();
				while (rsc.next()) {
					Person p = new Person();
					p.setId(rsc.getLong("id"));
					p.setFirstName(rsc.getString("name"));
					p.setYob(rsc.getInt("yob"));
					Stmt.add(p);
				}
			}

		} catch (SQLException e) {
			e.printStackTrace();
		}

		return Stmt;
	}

}


text:
var layout = {
    showlegend: false,
    xaxis: {
        title: "Votes",
        rangemode: 'tozero',
        autorange: true,
        dtick: 1,
        fixedrange: false
    }

};

$('#recentPolls').ready(function() {
    if(typeof polls !== typeof undefined || typeof myPolls !== typeof undefined) {
        var recentPolls = typeof polls !== typeof undefined ?  $('#recentPolls') : $('#myPolls');
        var currPolls = typeof polls !== typeof undefined ? polls : myPolls;
        for(var i = 0; i < currPolls.length; i++) {
            var pollDiv = document.createElement("div");
            pollDiv.id = "pollGraph" + currPolls[i]._id;
            recentPolls.append(pollDiv);

            var optionVotes = new Array();
            var options = new Array();

            for(var opt = 0; opt < currPolls[i].options.length; opt++)
            {
                var curr = currPolls[i].options[opt];
                optionVotes.push(curr.votes);
                options.push(curr.title);
            }

            var pollID = currPolls[i]._id;
            var data = [{
                type: 'bar',
                orientation: 'h',
                y: options,
                x: optionVotes,
                pollID: pollID,
                question: currPolls[i].question
            }];

            layout.title = currPolls[i].question;
            Plotly.newPlot('pollGraph' + pollID, data, layout, {displayModeBar: false});

            var myPlot = document.getElementById('pollGraph' + pollID);

            if(typeof currPolls === typeof polls)
                myPlot.on('plotly_click', function(data) {optionClicked(data);} );
        }

    }

});

function optionClicked(data)
{
    if(data.points.length > 0)
    {
        var pollID = data.points[0].data.pollID;
        var option = [];
        var newX = [];
        var newY = [];
        for(var i=0; i < data.points[0].data.x.length; i++)
        {
            let votes = data.points[0].data.x[i];
            let title = data.points[0].data.y[i];
            if(i === data.points[0].pointNumber)
                votes++;

            var curr = { title: title, votes: votes};
            newX.push(votes);
            newY.push(title);
            option.push(curr);
        }

        // var form = document.createElement('form');
        // var token =
        // form.setAttribute('action', '/polls/updateVote');
        // form.setAttribute('method', 'POST');
        // var pollIDField = document.createElement('input');
        // var optionNumField = document.createElement('input');
        // pollIDField.setAttribute('type','hidden');
        // optionNumField.setAttribute('type', 'hidden');
        // pollIDField.setAttribute('id', 'pollID');
        // optionNumField.setAttribute('id', 'optionNum');
        // pollIDField.value = pollID;
        // optionNumField.value = optionNum;
        //
        // form.appendChild(pollIDField);
        // form.appendChild(optionNumField);
        //
        // var submit = document.createElement('input');
        // submit.setAttribute('type', 'submit');
        //
        // form.appendChild(submit);

        var request = new XMLHttpRequest();

        request.onreadystatechange = function(response)
        {

        };

        var params = JSON.stringify({
            poll_id: pollID,
            option: option
        });

        request.open('POST', '/updateVotes');
        request.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
        request.setRequestHeader('X-CSRF-Token', $('meta[name=csrf-token]').attr('content'));
        request.send(params);

        var pollGraph = document.getElementById('pollGraph' + pollID);
        //Plotly.deleteTraces(pollGraph, [0, 1]);
        pollGraph.data[0].x = newX;
        pollGraph.data[0].y = newY;
        layout.title = pollGraph.data[0].question;
        Plotly.redraw(pollGraph);

    }

}


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="description" content="Hello World! It's on like Donkey Kong! My name's Marco and I'm a web and software developer from Lisbon, Portugal. Daily mumbling about technology and development on the horizon, so... Beware,...">
        <meta name="keywords" content="about, hello">
        <link rel="icon" href="https://marcogpinto.github.io/favicon.ico">

        <title>Hello World - MARCO PINTO . LOGR</title>

        <link href="https://marcogpinto.github.io/theme/css/all.min.css" rel="stylesheet">

        <link href="https://marcogpinto.github.io/feeds/all.atom.xml" type="application/atom+xml" rel="alternate" title="MARCO PINTO . LOGR Full Atom Feed" />
        <link href="https://marcogpinto.github.io/feeds/general.atom.xml" type="application/atom+xml" rel="alternate" title="MARCO PINTO . LOGR Categories Atom Feed" />

                        MARCO PINTO . LOGR

                                Homepage
                                Categories

Hello World

By Marco Pinto, Thu 20 July 2017, in category General

about, hello

Hello World! It's on like Donkey Kong!

My name's Marco and I'm a web and software developer from Lisbon, Portugal.

Daily mumbling about technology and development on the horizon, so... Beware, it's gonna get nerdy!

First do it, then do it right, then do it better. - Addy Osmani

Oh, by the way, this blog is powered by Pelican and Molivier is the guy who created this awesome theme!

Cheers!

        Please enable JavaScript to view the comments.

Sitemap

Archives

Tags

Atom Feed

Social

Twitter

LinkedIn

GitHub

About

Hello World

Except where otherwise noted, content on this site is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.


text:
"""
``MinDistance`` is an abstract type to be used
as the first argument for functions.
"""
abstract MinDistance


text:
<?php
namespace Concrete\Core\Tree;
use \Concrete\Core\Foundation\Object;
use Loader;
use \Concrete\Core\Package\PackageList;
class TreeType extends Object {

	public function getTreeTypeID() {
		return $this->treeTypeID;
	}
	public function getTreeTypeHandle() {
		return $this->treeTypeHandle;
	}
	public function getPackageID() { return $this->pkgID;}
	public function getPackageHandle() {
		return PackageList::getHandle($this->pkgID);
	}

	public function add($treeTypeHandle, $pkg = false) {

		$pkgID = 0;
		$db = Loader::db();
		if (is_object($pkg)) {
			$pkgID = $pkg->getPackageID();
		}

		$r = $db->query("insert into TreeTypes (treeTypeHandle, pkgID) values (?, ?)", array(
			$treeTypeHandle, $pkgID
		));

		$treeTypeID = $db->Insert_ID();
		return TreeType::getByID($treeTypeID);
	}

	public function delete() {
		$db = Loader::db();
		$db->Execute('delete from TreeTypes where treeTypeID = ?', array($this->treeTypeID));
	}

	public static function getByID($treeTypeID) {
		$db = Loader::db();
		$row = $db->GetRow('select * from TreeTypes where treeTypeID = ?', array($treeTypeID));
		if (is_array($row) && $row['treeTypeID']) {
			$type = new TreeType();
			$type->setPropertiesFromArray($row);
			return $type;
		}
	}

	public static function getByHandle($treeTypeHandle) {
		$db = Loader::db();
		$row = $db->GetRow('select * from TreeTypes where treeTypeHandle = ?', array($treeTypeHandle));
		if (is_array($row) && $row['treeTypeHandle']) {
			$type = new TreeType();
			$type->setPropertiesFromArray($row);
			return $type;
		}
	}

	public function getTreeTypeClass() {
		$txt = Loader::helper('text');
		$className = '\\Concrete\\Core\\Tree\\Type\\' . $txt->camelcase($this->treeTypeHandle);
		return $className;
	}

	public static function getListByPackage($pkg) {
		$db = Loader::db();
		$list = array();
		$r = $db->Execute('select treeTypeID from TreeTypes where pkgID = ? order by treeTypeID asc', array($pkg->getPackageID()));
		while ($row = $r->FetchRow()) {
			$list[] = TreeType::getByID($row['treeTypeID']);
		}

		$r->Close();
		return $list;
	}

}


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

namespace Twainsoft.GridSelection
{
    static class Program
    {
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new GridSelectionView());
        }
    }
}


text:
package org.cucina.loader;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.context.MessageSource;
import org.springframework.validation.BindException;

import java.util.Locale;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

/**
 * JAVADOC for Class Level
 *
 * @author $Author: $
 * @version $Revision: $
 */
public class LoaderExceptionFactoryTest {
	@Mock
	private MessageSource messageSource;

	/**
	 * JAVADOC Method Level Comments
	 */
	@Before
	public void onsetup() {
		MockitoAnnotations.initMocks(this);
	}

	/**
	 * JAVADOC Method Level Comments
	 *
	 * @throws Exception JAVADOC.
	 */
	@Test
	public void testFailureAndMessageSource()
			throws Exception {
		String returnMessage = "BLAAH oh BLAAH oh blaah blaah";

		//        MessageSource messageSource = mock(MessageSource.class);
		String errorCode = "loader.fileNullOrEmpty";

		when(messageSource.getMessage(errorCode, null, Locale.getDefault())).thenReturn(returnMessage);

		LoaderExceptionFactory service = new LoaderExceptionFactory(messageSource);

		BindException be = new BindException(new Object(), "");

		be.reject(errorCode, null, "");

		LoaderException le = service.getLoaderException(be);

		verify(messageSource).getMessage(errorCode, null, Locale.getDefault());
		assertEquals(le.getErrors()[0], returnMessage);
	}

	/**
	 * JAVADOC Method Level Comments
	 *
	 * @throws Exception JAVADOC.
	 */
	@Test
	public void testFailureAndMessageSourceDefaultLocale()
			throws Exception {
		String returnMessage = "BLAAH oh BLAAH oh blaah blaah";
		String errorCode = "loader.fileNullOrEmpty";

		when(messageSource.getMessage(errorCode, null, Locale.getDefault()))
				.thenReturn(returnMessage);

		LoaderExceptionFactory service = new LoaderExceptionFactory(messageSource);

		BindException be = new BindException(new Object(), "");

		be.reject(errorCode, null, "");

		LoaderException le = service.getLoaderException(be);

		verify(messageSource).getMessage(errorCode, null, Locale.getDefault());
		assertEquals(le.getErrors()[0], returnMessage);
	}

	/**
	 * JAVADOC Method Level Comments
	 *
	 * @throws Exception JAVADOC.
	 */
	@Test
	public void testFailureAndMessageSourceThrowsUp()
			throws Exception {
		String message = "BLAAH oh BLAAH oh blaah blaah";
		String errorCode = "loader.fileNullOrEmpty";

		when(messageSource.getMessage(errorCode, null, Locale.getDefault()))
				.thenThrow(new RuntimeException(message));

		LoaderExceptionFactory service = new LoaderExceptionFactory(messageSource);

		String defaultMessage = "This is the default message";
		BindException be = new BindException(new Object(), defaultMessage);

		be.reject(errorCode, null, defaultMessage);

		LoaderException le = service.getLoaderException(be);

		assertEquals("Should return the default message if MessageSource blows up", defaultMessage,
				le.getErrors()[0]);
	}
}


text:
A simple contacts AngularJS app built starting from Angular Seed and Firebase from a tutorial on Udemy.

After looking into Firebase some more, most of the code in the controller could be removed if this was done with three-way binding with Firebase API, not all of the copying of every single attribute between the controller and Firebase in every function.

Also, I used the "controller as" approach rather than setting everything in scope as done in the tutorial.


text:
import base64
from StringIO import StringIO
import urlparse
import urllib

try:
    from webob import Request as BaseRequest
except ImportError:
    raise ImportError('WebOb (http://pypi.python.org/pypi/WebOb) is required')

from .wsgi_proxy import Proxy

__doc__ = '''Subclasses of webob.Request who use restkit to get a
webob.Response via restkit.ext.wsgi_proxy.Proxy.

Example::

    >>> req = Request.blank('http://pypi.python.org/pypi/restkit')
    >>> resp = req.get_response()
    >>> print resp #doctest: +ELLIPSIS
    200 OK
    Date: ...
    Transfer-Encoding: chunked
    Content-Type: text/html; charset=utf-8
    Server: Apache/2...
    <BLANKLINE>
    <?xml version="1.0" encoding="UTF-8"?>
    ...

'''

PROXY = Proxy(allowed_methods=['GET', 'POST', 'HEAD', 'DELETE', 'PUT', 'PURGE'])

class Method(property):
    def __init__(self, name):
        self.name = name
    def __get__(self, instance, klass):
        if not instance:
            return self
        instance.method = self.name.upper()
        def req(*args, **kwargs):
            return instance.get_response(*args, **kwargs)
        return req

class Request(BaseRequest):
    get = Method('get')
    post = Method('post')
    put = Method('put')
    head = Method('head')
    delete = Method('delete')

    def get_response(self):
        if self.content_length < 0:
            self.content_length = 0
        if self.method in ('DELETE', 'GET'):
            self.body = ''
        elif self.method == 'POST' and self.POST:
            body = urllib.urlencode(self.POST.copy())
            stream = StringIO(body)
            stream.seek(0)
            self.body_file = stream
            self.content_length = stream.len
            if 'form' not in self.content_type:
                self.content_type = 'application/x-www-form-urlencoded'
        self.server_name = self.host
        return BaseRequest.get_response(self, PROXY)

    __call__ = get_response

    def set_url(self, url):

        path = url.lstrip('/')

        if url.startswith("http://") or url.startswith("https://"):
            u = urlparse.urlsplit(url)
            if u.username is not None:
                password = u.password or ""
                encode = base64.b64encode("%s:%s" % (u.username, password))
                self.headers['Authorization'] = 'Basic %s' %  encode

            self.scheme = u.scheme,
            self.host = u.netloc.split("@")[-1]
            self.path_info = u.path or "/"
            self.query_string = u.query
            url = urlparse.urlunsplit((u.scheme, u.netloc.split("@")[-1],
                u.path, u.query, u.fragment))
        else:

            if '?' in path:
                path, self.query_string = path.split('?', 1)
            self.path_info = '/' + path

            url = self.url
        self.scheme, self.host, self.path_info = urlparse.urlparse(url)[0:3]


text:
package it.quartara.boser.service;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import it.quartara.boser.model.SearchConfig;
import it.quartara.boser.model.SearchKey;

@Path("/searchKey")
@Stateless
public class SearchKeyService {

	private static final Logger log = LoggerFactory.getLogger(SearchKeyService.class);

	@PersistenceContext(unitName = "BoserPU")
	private EntityManager em;

	@POST
	public SearchConfig insert(@FormParam("text") String text,
							   @FormParam("searchConfigId") Long searchConfigId) {
		log.debug("inserting new key: {}", text);

		SearchConfig searchConfig = em.find(SearchConfig.class, searchConfigId);
		Set<SearchKey> keys = searchConfig.getKeys();
		if (keys==null) {
			keys = new HashSet<>();
		}
		/*
		 * bonifica stringa di input
		 */
		Set<String> terms = new HashSet<>();
		if (text.indexOf(",") == -1) {
			terms.add(text.trim());
		} else {
			String[] termsArray = StringUtils.removeEnd(StringUtils.removeStart(text, ","), ",")
								 .trim()
								 .split(",");
			for (String term : termsArray) {
				terms.add(term.trim());
			}
		}
		/*
		 * controllo duplicati
		 */
		if (checkDuplicatedTerms(keys, terms)) {
			SearchKey newKey = new SearchKey();
			Date now = new Date();
			newKey.setTerms(terms);
			newKey.setValidityStart(now);
			em.persist(newKey);
			keys.add(newKey);
			searchConfig.setKeys(keys);
			searchConfig.setLastUpdate(now);
			em.merge(searchConfig);
		} else {
			/*
			 * TODO raffinare gestione?
			 */
			throw new WebApplicationException(Response.Status.BAD_REQUEST);
		}
		return searchConfig;
	}

	/*
	 * controlla la presenza di duplicati.
	 * per ogni chiave di ricerca, se i termini sono uguali a quelli
	 * della chiave che si sta cercando di inserire, restituisce false.
	 */
	private boolean checkDuplicatedTerms(Set<SearchKey> keys, Set<String> newKeyTerms) {
		for (SearchKey searchKey : keys) {
			Set<String> existingTerms = searchKey.getTerms();
			if (existingTerms.equals(newKeyTerms)) {
				return false;
			}
		}
		return true;
	}

	@DELETE
	@Path("/{id}/searchConfig/{scId}")
	public SearchConfig delete(@PathParam("scId") Long searchConfigId,
						   @PathParam("id") Long searchKeyId) {
		Date now = new Date();
		SearchKey keyToDelete = em.find(SearchKey.class, searchKeyId);
		keyToDelete.setValidityEnd(now);

		SearchConfig searchConfig = em.find(SearchConfig.class, searchConfigId);
		Set<SearchKey> keys = searchConfig.getKeys();
		keys.remove(keyToDelete);
		searchConfig.setLastUpdate(now);
		em.merge(searchConfig);

		return searchConfig;
	}

	@PUT
	@Path("/{id}/searchConfig/{scId}")
	public SearchConfig update(@PathParam("scId") Long searchConfigId,
			   				   @PathParam("id") Long searchKeyId,
			   				   @FormParam("newValue") String newValue) {
		if (StringUtils.isEmpty(newValue)) {
			throw new WebApplicationException(Response.Status.BAD_REQUEST);
		}
		/*
		 * prima controllo se la modifica genera una chiave di ricerca duplicata
		 */
		Set<String> terms = new HashSet<>();
		if (newValue.indexOf(",") == -1) {
			terms.add(newValue.trim());
		} else {
			String[] termsArray = StringUtils.removeEnd(StringUtils.removeStart(newValue, ","), ",")
								 .trim()
								 .split(",");
			for (String term : termsArray) {
				terms.add(term.trim());
			}
		}
		SearchConfig searchConfig = em.find(SearchConfig.class, searchConfigId);
		Set<SearchKey> keys = searchConfig.getKeys();
		SearchKey searchKey = em.find(SearchKey.class, searchKeyId);
		if (checkDuplicatedTerms(keys, terms)) {
			searchKey.setTerms(terms);
			em.merge(searchKey);
		} else {
			throw new WebApplicationException(Response.Status.BAD_REQUEST);
		}

		em.refresh(searchConfig);
		return searchConfig;
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<!--

 This file is part of the Sylius package.

 (c) Paweł Jędrzejewski

 For the full copyright and license information, please view the LICENSE
 file that was distributed with this source code.

-->

<container xmlns="http://symfony.com/schema/dic/services"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://symfony.com/schema/dic/services
                               http://symfony.com/schema/dic/services/services-1.0.xsd">

    <parameters>
        <parameter key="sylius.templating.helper.restricted_zone.class">Sylius\Bundle\CoreBundle\Templating\Helper\RestrictedZoneHelper</parameter>
        <parameter key="sylius.templating.helper.money.class">Sylius\Bundle\CoreBundle\Templating\Helper\MoneyHelper</parameter>
        <parameter key="sylius.templating.helper.regular_price.class">Sylius\Bundle\CoreBundle\Templating\Helper\RegularPriceHelper</parameter>
    </parameters>

    <services>
        <service id="sylius.templating.helper.restricted_zone" class="%sylius.templating.helper.restricted_zone.class%" lazy="true">
            <argument type="service" id="sylius.checker.restricted_zone" />
            <tag name="templating.helper" alias="sylius_restricted_zone" />
        </service>

        <service id="sylius.templating.helper.money" class="%sylius.templating.helper.money.class%" lazy="true">
            <argument type="service" id="sylius.context.locale" />
            <argument type="service" id="sylius.context.currency" />
            <argument type="service" id="sylius.formatter.money" />
            <tag name="templating.helper" alias="sylius_money" />
        </service>

        <service id="sylius.templating.helper.regular_price" class="%sylius.templating.helper.regular_price.class%" lazy="true">
            <tag name="templating.helper" alias="sylius_regular_price" />
        </service>
    </services>

</container>


text:
title: How to install Apache HTTPD in openSUSE
description: This tutorial will explain how to install Apache HTTPD in openSUSE 15.
date: 2018-06-20T12:00:00+02:00
lastmod: 2019-08-06T14:30:00+02:00
tags: [opensuse, httpd]
author: dalanzg
image:
  url: "img/it-works-apache2.png"
  width: 597
  height: 263
comments: true
---

This tutorial will explain how to install Apache HTTPD in openSUSE 15.

The original documentation is found in [The Apache HTTP Server Project](https://httpd.apache.org/). And the official documentation for openSUSE is in [The Apache HTTP Server](https://doc.opensuse.org/documentation/leap/reference/html/book.opensuse.reference/cha.apache2.html).

## Requirements

You will need the following:

- openSUSE Leap 15

## Steps

- [Set hostname and domain](#set-hostname-and-domain)
- [Install Apache HTTPD](#install-apache-httpd)
- [Start and stop Apache](#start-and-stop-apache)
- [Start Apache automatically at boot time](#start-apache-automatically-at-boot-time)

### Set hostname and domain

Files **/etc/hostname** and **/etc/hosts** will be modified to resolve the following:

- **Hostname** -> apachesrv
- **Domain** -> dalanzg.com

More information in [Setting hostname and domain in openSUSE.]({{< ref "/posts/2017/2017-04-13-setting-hostname-and-domain-in-opensuse" >}})

```terminal
dalanz@apachesrv:~> hostname
apachesrv
dalanz@apachesrv:~> hostname --fqdn
apachesrv.dalanzg.com
```

### Install Apache HTTPD

Install Apache HTTPD with example pages in **YaST2** or **zipper** command.

```terminal
dalanz@apachesrv:~> sudo zypper install apache2 apache2-example-pages
```

### Start and stop Apache

Start the Apache service with the following command:

```terminal
dalanz@apachesrv:~> sudo systemctl start apache2
```

Check you can access the example page -> [http://localhost](http://localhost)

{{< bootstrap-figure src="img/it-works-apache2.png" title="It works" width="500">}}

Check the status:

```terminal
dalanz@apachesrv:~> sudo systemctl status apache2
● apache2.service - The Apache Webserver
   Loaded: loaded (/usr/lib/systemd/system/apache2.service; disabled; vendor preset: di>
   Active: active (running) since Mon 2018-08-20 11:35:59 CEST; 2min 56s ago
 Main PID: 4788 (httpd-prefork)
   Status: "Total requests: 0; Current requests/sec: 0; Current traffic:   0 B/sec"
    Tasks: 6
   CGroup: /system.slice/apache2.service
           ├─4788 /usr/sbin/httpd-prefork -DSYSCONFIG -C PidFile /var/run/httpd.pid -C >
           ├─4794 /usr/sbin/httpd-prefork -DSYSCONFIG -C PidFile /var/run/httpd.pid -C >
           ├─4795 /usr/sbin/httpd-prefork -DSYSCONFIG -C PidFile /var/run/httpd.pid -C >
           ├─4796 /usr/sbin/httpd-prefork -DSYSCONFIG -C PidFile /var/run/httpd.pid -C >
           ├─4797 /usr/sbin/httpd-prefork -DSYSCONFIG -C PidFile /var/run/httpd.pid -C >
           └─4799 /usr/sbin/httpd-prefork -DSYSCONFIG -C PidFile /var/run/httpd.pid -C >

Aug 20 11:35:59 apachesrv systemd[1]: Starting The Apache Webserver...
Aug 20 11:35:59 apachesrv systemd[1]: Started The Apache Webserver.
```

And stop the service:

```terminal
dalanz@apachesrv:~> sudo systemctl stop apache2
```

### Start Apache automatically at boot time

You can start Apache automatically at boot time.

```terminal
dalanz@apachesrv:~> sudo systemctl enable apache2
Created symlink /etc/systemd/system/httpd.service → /usr/lib/systemd/system/apache2.service.
Created symlink /etc/systemd/system/apache.service → /usr/lib/systemd/system/apache2.service.
Created symlink /etc/systemd/system/multi-user.target.wants/apache2.service → /usr/lib/systemd/system/apache2.service.
```


text:
var _dec, _class;

import { ObserverLocator } from 'aurelia-binding';
import { ValidationGroup } from './validation-group';
import { inject } from 'aurelia-dependency-injection';
import { ValidationConfig } from './validation-config';

export let Validation = (_dec = inject(ObserverLocator), _dec(_class = class Validation {
  constructor(observerLocator, validationConfig) {
    this.observerLocator = observerLocator;
    this.config = validationConfig ? validationConfig : Validation.defaults;
  }

  on(subject, configCallback) {
    let conf = new ValidationConfig(this.config);
    if (configCallback !== null && configCallback !== undefined && typeof configCallback === 'function') {
      configCallback(conf);
    }
    return new ValidationGroup(subject, this.observerLocator, conf);
  }
  onBreezeEntity(breezeEntity, configCallback) {
    let validation = this.on(breezeEntity, configCallback);
    validation.onBreezeEntity();
    return validation;
  }
}) || _class);
Validation.defaults = new ValidationConfig();


text:
doublemetaphone-haskell
=======================

Unusably unfinished doublemetaphone implementation in Haskell


text:
*2018-07-05*

* Added vendor utility get-eula-license-infringements - gets a CSV of all
customer License EULA infringements in a given month.

## 0.0.7

*2017-11-30*

* Changed build to omit symbol table rather than applying post-build strip command

## 0.0.6

*2017-10-23*

* Added do DELETE

## 0.0.5

*2017-09-14*

* Rulesets functionality fixed (didn't list rulesets, could not get a single ruleset)

## 0.0.4

*2017-09-01*

* Now statically compiled

## 0.0.3

* Updated to use sirupsen/logrus 1.0.0

----
## 0.0.2

New features:

### users `<email address>` accessKeys `<action>`

Where `<action>` is one of:
- **create** - Create a new API Access Key
- **delete** - Deled an API Access Key

### Vendors `<vendorID>` `<action>`

Where `<action>` is one of:
- **get** - (Elastic Licensing Employees only) Get details about a vendor
- **put** - (Elastic Licensing Employees only) - Update or Create a vendor

### Vendors `<vendorID>` rulesets `<action>`

Where `<action>` is one of:
- **put** - put a pricing ruleset
- **get** - get a pricing ruleset
- **activate** - activate a ruleset (i.e. so it is the ruleset used to generate pricing for Fuel)


text:
/* ----------------------------------------------------------------------------
 * This file was automatically generated by SWIG (http://www.swig.org).
 * Version 2.0.1
 *
 * Do not make changes to this file unless you know what you are doing--modify
 * the SWIG interface file instead.
 * ----------------------------------------------------------------------------- */

namespace RakNet {

using System;
using System.Runtime.InteropServices;

public class NatPunchthroughDebugInterface_Printf : NatPunchthroughDebugInterface {
  private HandleRef swigCPtr;

  internal NatPunchthroughDebugInterface_Printf(IntPtr cPtr, bool cMemoryOwn) : base(RakNetPINVOKE.NatPunchthroughDebugInterface_Printf_SWIGUpcast(cPtr), cMemoryOwn) {
    swigCPtr = new HandleRef(this, cPtr);
  }

  internal static HandleRef getCPtr(NatPunchthroughDebugInterface_Printf obj) {
    return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr;
  }

  ~NatPunchthroughDebugInterface_Printf() {
    Dispose();
  }

  public override void Dispose() {
    lock(this) {
      if (swigCPtr.Handle != IntPtr.Zero) {
        if (swigCMemOwn) {
          swigCMemOwn = false;
          RakNetPINVOKE.delete_NatPunchthroughDebugInterface_Printf(swigCPtr);
        }
        swigCPtr = new HandleRef(null, IntPtr.Zero);
      }
      GC.SuppressFinalize(this);
      base.Dispose();
    }
  }

  public override void OnClientMessage(string msg) {
    RakNetPINVOKE.NatPunchthroughDebugInterface_Printf_OnClientMessage(swigCPtr, msg);
  }

  public NatPunchthroughDebugInterface_Printf() : this(RakNetPINVOKE.new_NatPunchthroughDebugInterface_Printf(), true) {
  }

}

}


text:
import * as redis from 'redis';
import * as ioredis from 'ioredis';
import Limiter = require('ratelimiter');

declare let id: string;
declare let db: redis.RedisClient;
declare let iodb: ioredis.Redis;

const limit = new Limiter({ id, db, duration: 3_600, max: 1_000 });
const ioLimit = new Limiter({ id, db: iodb });

limit.inspect(); // $ExpectType string

limit.get((error, limit): void => {
    if (error) {
        console.error(error);
        return;
    }

    limit.total; // $ExpectType number
    limit.remaining; // $ExpectType number
    limit.reset; // $ExpectType number
    limit.resetMs; // $ExpectType number
});


text:
package com.tempestas.dependent;

import com.tempestas.dependency.Dependency;

import javax.annotation.Nonnull;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by jaaha on 2017-09-01.
 */
public final class ClassDependent implements Dependent {

    private final Dependent dependent;

    public ClassDependent(Class<?> clazz) {
        dependent = new DependentImpl(getDependencies(clazz));
    }

    public static Dependent of(Class<?> clazz) {
        return new ClassDependent(clazz);
    }

    public static Collection<Class<?>> filter(Collection<Class<?>> classes, Collection<String> dependencyNames) {
        Map<Class<?>, Dependent> classDependentMap = new HashMap<>();
        for (Class<?> clazz : classes) {
            Dependent dependent = of(clazz);
            classDependentMap.put(clazz, dependent);
        }
        return filter(classDependentMap, dependencyNames);
    }

    public static Collection<Class<?>> filter(Map<Class<?>, Dependent> classDependentMap, Collection<String>
            dependencyNames) {
        Collection<Class<?>> toRet = new ArrayList<>();
        for (Map.Entry<Class<?>, Dependent> entry : classDependentMap.entrySet()) {
            if (matchesDependencies(entry.getValue(), dependencyNames))
                toRet.add(entry.getKey());
        }
        return toRet;
    }

    public static boolean matchesDependencies(Dependent dependent, Collection<String> dependencyNames) {
        return dependencyNames.equals(dependent.getDependencyMap().keySet());
    }

    private static Collection<? extends Dependency<?>> getDependencies(Class<?> clazz) {
        Collection<Dependency<?>> toRet = new ArrayList<>();
        for (Field field : clazz.getFields()) {
            if (!Dependency.class.isAssignableFrom(field.getType()))
                continue;
            if (!Modifier.isStatic(field.getModifiers()))
                continue;
            if (!Modifier.isFinal(field.getModifiers()))
                continue;
            Dependency<?> dependency = requireDependency(field);
            toRet.add(dependency);
        }
        return toRet;
    }

    private static Dependency<?> requireDependency(Field field) {
        try {
            return (Dependency<?>) field.get(null);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    @Nonnull
    @Override
    public Map<String, Dependency<?>> getDependencyMap() {
        return dependent.getDependencyMap();
    }
}


text:
layout: page
title: Lessons
header: Lessons
group: navigation
---
{% include JB/setup %}

{% for category in site.categories %}
  {% if category[0] == 'lessons' %}
  <ul>
    {% assign pages_list = category[1] %}
    {% assign pages_limit = 5 %}
    {% include JB/pages_list %}
  </ul>
  {% endif %}
{% endfor %}


text:
from typing import List
class Solution:
    def subarraySum(self, nums: List[int], k: int) -> int:
        dp = dict()
        def subarraySumRecursive(nums, index, k):
            key = (index, k)
            if key in dp:
                return dp[key]
            if k == 0:
                return 1
            if index >= len(nums):
                return 0
            count = subarraySumRecursive(nums, index + 1, k) + subarraySumRecursive(nums, index + 1, k - nums[index])
            dp[key] = count
            return count
        return subarraySumRecursive(nums, 0, k)

nums = [1 for _ in range(3)]
#nums.extend([2 for _ in range(8)])
ob = Solution()
for i in range(10):
    print("num of sum for {0} is {1}".format(i, ob.subarraySum(nums, i)))


text:
// Class: FileReferenceList
module Shumway.AVMX.AS.flash.net {
  import notImplemented = Shumway.Debug.notImplemented;
  import axCoerceString = Shumway.AVMX.axCoerceString;
  export class FileReferenceList extends flash.events.EventDispatcher {

    static classInitializer: any = null;

    constructor () {
      super();
    }

    // _fileList: any [];
    get fileList(): ASArray {
      release || notImplemented("public flash.net.FileReferenceList::get fileList"); return;
      // return this._fileList;
    }
    browse(typeFilter: ASArray = null): boolean {
      typeFilter = typeFilter;
      release || notImplemented("public flash.net.FileReferenceList::browse"); return;
    }
  }
}