text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

using Microsoft.MixedReality.Toolkit.Utilities;
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityPhysics = UnityEngine.Physics;

namespace Microsoft.MixedReality.Toolkit.Audio
{
    /// <summary>
    /// Class which supports components implementing <see cref="Microsoft.MixedReality.Toolkit.Audio.IAudioInfluencer"/> being used with audio sources.
    /// </summary>
    /// <remarks>
    /// AudioInfluencerController requires an <see href="https://docs.unity3d.com/ScriptReference/AudioSource.html">AudioSource</see> component. If one is not attached, it will be added automatically.
    /// Each sound playing game object needs to have an AudioInfluencerController attached in order to have it's audio influenced.
    /// </remarks>
    [RequireComponent(typeof(AudioSource))]
    [DisallowMultipleComponent]
    [AddComponentMenu("Scripts/MRTK/SDK/AudioInfluencerController")]
    public class AudioInfluencerController : MonoBehaviour
    {
        /// <summary>
        /// Frequency below the nominal range of human hearing.
        /// </summary>
        /// <remarks>
        /// This frequency can be used to set a high pass filter to allow all
        /// audible frequencies through the filter.
        /// </remarks>
        public static readonly float NeutralLowFrequency = 10.0f;

        /// <summary>
        /// Frequency above the nominal range of human hearing.
        /// </summary>
        /// <remarks>
        /// This frequency can be used to set a low pass filter to allow all
        /// audible frequencies through the filter.
        /// </remarks>
        public static readonly float NeutralHighFrequency = 22000.0f;

        /// <summary>
        /// Time, in seconds, between audio influence updates.
        /// </summary>
        /// <remarks>
        /// The UpdateInterval range is between 0.0 and 1.0, inclusive.
        /// The default value is 0.25.
        /// A value of 0.0f indicates that updates occur every frame.
        /// </remarks>
        [Tooltip("Time, in seconds, between audio influence updates.  0 indicates to update every frame.")]
        [Range(0.0f, 1.0f)]
        [SerializeField]
        private float updateInterval = 0.25f;
        public float UpdateInterval
        {
            get { return updateInterval; }
            set
            {
                updateInterval = Mathf.Clamp(value, 0.0f, 1.0f);
            }
        }

        /// <summary>
        /// Maximum distance, in meters, to look when attempting to find the user and any influencers.
        /// </summary>
        /// <remarks>
        /// The MaxDistance range is 1.0 to 50.0, inclusive.
        /// The default value is 20.0.
        /// </remarks>
        [Tooltip("Maximum distance, in meters, to look when attempting to find the user and any influencers.")]
        [Range(1.0f, 50.0f)]
        [SerializeField]
        private float maxDistance = 20.0f;
        public float MaxDistance
        {
            get { return maxDistance; }
            set
            {
                maxDistance = Mathf.Clamp(value, 1.0f, 50.0f);
            }
        }

        /// <summary>
        /// Maximum number of objects that will be considered when looking for influencers.
        /// Setting this value too high may have a negative impact on the performance of your experience.
        /// </summary>
        /// <remarks>
        /// MaxObjects can only be set in the Unity Inspector.
        /// The MaxObjects range is 1 to 25, inclusive.
        /// The default value is 10.
        /// </remarks>
        [Tooltip("Maximum number of objects that will be considered when looking for influencers.")]
        [Range(1, 25)]
        [SerializeField]
        private int maxObjects = 10;

        /// <summary>
        /// Time of last audio processing update.
        /// </summary>
        private DateTime lastUpdate = DateTime.MinValue;

        /// <summary>
        /// The source of the audio.
        /// </summary>
        [SerializeField]
        private AudioSource audioSource;

        /// <summary>
        /// The initial volume level of the audio source.
        /// </summary>
        private float initialAudioSourceVolume;

        /// <summary>
        /// The hits returned by Physics.RaycastAll
        /// </summary>
        private RaycastHit[] hits;

        /// <summary>
        /// The collection of previously applied audio influencers.
        /// </summary>
        private List<IAudioInfluencer> previousInfluencers = new List<IAudioInfluencer>();

        /// <summary>
        /// Potential effects manipulated by an audio influencer.
        /// </summary>
        private AudioLowPassFilter lowPassFilter;
        private AudioHighPassFilter highPassFilter;

        private float nativeLowPassCutoffFrequency;

        /// <summary>
        /// Gets or sets the native low pass cutoff frequency for the
        /// sound emitter.
        /// </summary>
        public float NativeLowPassCutoffFrequency
        {
            get { return nativeLowPassCutoffFrequency; }
            set { value = nativeLowPassCutoffFrequency; }
        }

        private float nativeHighPassCutoffFrequency;

        /// <summary>
        /// Gets or sets the native high pass cutoff frequency for the
        /// sound emitter.
        /// </summary>
        public float NativeHighPassCutoffFrequency
        {
            get { return nativeHighPassCutoffFrequency; }
            set { value = nativeHighPassCutoffFrequency; }
        }

        private void Awake()
        {
            if (audioSource == null)
            {
                audioSource = GetComponent<AudioSource>();
            }

            initialAudioSourceVolume = audioSource.volume;

            // Get optional filters (and initial values) that the sound designer / developer
            // may have applied to this game object
            lowPassFilter = gameObject.GetComponent<AudioLowPassFilter>();
            nativeLowPassCutoffFrequency = (lowPassFilter != null) ? lowPassFilter.cutoffFrequency : NeutralHighFrequency;
            highPassFilter = gameObject.GetComponent<AudioHighPassFilter>();
            nativeHighPassCutoffFrequency = (highPassFilter != null) ? highPassFilter.cutoffFrequency : NeutralLowFrequency;

            // Preallocate the array that will be used to collect RaycastHit structures.
            hits = new RaycastHit[maxObjects];
        }

        private void Update()
        {
            DateTime now = DateTime.UtcNow;

            // Audio influences are not updated every frame.
            if ((UpdateInterval * 1000.0f) <= (now - lastUpdate).TotalMilliseconds)
            {
                audioSource.volume = initialAudioSourceVolume;

                // Get the audio influencers that should apply to the audio source.
                List<IAudioInfluencer> influencers = GetInfluencers();
                for (int i = 0; i < influencers.Count; i++)
                {
                    // Apply the influencer's effect.
                    influencers[i].ApplyEffect(gameObject);
                }

                // Find and remove the audio influencers that are to be removed from the audio source.
                List<IAudioInfluencer> influencersToRemove = new List<IAudioInfluencer>();
                for (int i = 0; i < previousInfluencers.Count; i++)
                {
                    MonoBehaviour mbPrev = previousInfluencers[i] as MonoBehaviour;

                    // Remove influencers that are no longer in line of sight
                    // OR
                    // Have been disabled
                    if (!influencers.Contains(previousInfluencers[i]) ||
                        ((mbPrev != null) && !mbPrev.isActiveAndEnabled))
                    {
                        influencersToRemove.Add(previousInfluencers[i]);
                    }
                }
                RemoveInfluencers(influencersToRemove);

                previousInfluencers = influencers;
                lastUpdate = now;
            }
        }

        /// <summary>
        /// Removes the effects applied by specified audio influencers.
        /// </summary>
        /// <param name="influencers">Collection of IAudioInfluencer objects on which to remove the effect.</param>
        private void RemoveInfluencers(List<IAudioInfluencer> influencers)
        {
            for (int i = 0; i < influencers.Count; i++)
            {
                influencers[i].RemoveEffect(gameObject);
            }
        }

        /// <summary>
        /// Finds the IAudioInfluencer objects that are to be applied to the audio source.
        /// </summary>
        /// <returns>Collection of IAudioInfluencers between the user and the game object.</returns>
        private List<IAudioInfluencer> GetInfluencers()
        {
            List<IAudioInfluencer> influencers = new List<IAudioInfluencer>();
            Transform cameraTransform = CameraCache.Main.transform;

            // Influencers take effect only when between the emitter and the user.
            // Perform a raycast from the user toward the object.
            Vector3 direction = (gameObject.transform.position - cameraTransform.position).normalized;
            float distance = Vector3.Distance(cameraTransform.position, gameObject.transform.position);

            int count = UnityPhysics.RaycastNonAlloc(cameraTransform.position,
                                                direction,
                                                hits,
                                                distance,
                                                UnityPhysics.DefaultRaycastLayers,
                                                QueryTriggerInteraction.Ignore);

            for (int i = 0; i < count; i++)
            {
                IAudioInfluencer influencer = hits[i].collider.gameObject.GetComponentInParent<IAudioInfluencer>();
                if (influencer != null)
                {
                    influencers.Add(influencer);
                }
            }

            return influencers;
        }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<meta name="generator" content="JDiff v1.1.0">

<meta name="description" content="JDiff is a Javadoc doclet which generates an HTML report of all the packages, classes, constructors, methods, and fields which have been removed, added or changed in any way, including their documentation, when two APIs are compared.">
<meta name="keywords" content="diff, jdiff, javadiff, java diff, java difference, API difference, difference between two APIs, API diff, Javadoc, doclet">
<TITLE>
android.provider.Settings
</TITLE>
<link href="../../../../assets/android-developer-docs.css" rel="stylesheet" type="text/css" />
<link href="../stylesheet-jdiff.css" rel="stylesheet" type="text/css" />

<nobr>Android Developers | Android.com</nobr>

        API Diff Specification

        To Level:
        23

        From Level:
        22

        Generated
        2015.08.14 14:28

        Statistics

Class android.provider.Settings

  Added Methods

  <nobr>boolean canDrawOverlays(Context)</nobr>

  Added Fields

  <nobr>String ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS</nobr>

  <nobr>String ACTION_MANAGE_OVERLAY_PERMISSION</nobr>

  <nobr>String ACTION_MANAGE_WRITE_SETTINGS</nobr>

  <nobr>String ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS</nobr>

  <nobr>String ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS</nobr>

  <nobr>String ACTION_VOICE_CONTROL_AIRPLANE_MODE</nobr>

  <nobr>String ACTION_VOICE_CONTROL_BATTERY_SAVER_MODE</nobr>

  <nobr>String ACTION_VOICE_CONTROL_DO_NOT_DISTURB_MODE</nobr>

  <nobr>String EXTRA_AIRPLANE_MODE_ENABLED</nobr>

  <nobr>String EXTRA_BATTERY_SAVER_MODE_ENABLED</nobr>

  <nobr>String EXTRA_DO_NOT_DISTURB_MODE_ENABLED</nobr>

  <nobr>String EXTRA_DO_NOT_DISTURB_MODE_MINUTES</nobr>

  <nobr>String INTENT_CATEGORY_USAGE_ACCESS_CONFIG</nobr>

  <nobr>String METADATA_USAGE_ACCESS_REASON</nobr>

        Except as noted, this content is licensed under
         Creative Commons Attribution 2.5.
        For details and restrictions, see the Content License.

        Site Terms of Service -
        Privacy Policy -
        Brand Guidelines

redpajama_set_name: RedPajamaGithub


text:
from __future__ import unicode_literals

import base64
import hashlib
import logging
import os
import shutil
import subprocess
from tempfile import mkdtemp

from distutils import version
from distutils.spawn import find_executable
from flask import Flask, send_file, abort
from jinja2 import Template
from PIL import Image, ImageChops

try:
    from urllib import unquote
except ImportError:
    # Python 3
    from urllib.parse import unquote  # NOQA

__author__ = 'Luke Pomfrey'
__email__ = 'lpomfrey@gmail.com'
__version__ = '0.3.6'
version_info = tuple(version.LooseVersion(__version__).version)

OUTPUT_DIR = os.environ.get('LATEXRENDER_OUTPUT_DIR', '/tmp/latexrender/')
TEMPLATE = os.environ.get('LATEXRENDER_TEMPLATE')
XELATEX = os.environ.get('LATEXRENDER_XELATEX')
DVIPNG = os.environ.get('LATEXRENDER_DVIPNG')
USE_X_SENDFILE = os.environ.get('USE_X_SENDFILE', 'true') in (
    'true', 't', 'y', 'yes', '1', 'on')
SENDFILE_ROOT = os.environ.get('LATEXRENDER_SENDFILE_ROOT', '')

app = Flask('latexrender')
app.config.from_object(__name__)

log = logging.getLogger(__name__)
logging.basicConfig()

class SuspiciousOperation(Exception):
    pass

class InvalidLatex(Exception):
    pass

class LatexRenderer(object):

    def __init__(self, output_dir, template=None, latex=None, dvipng=None):
        self.output_dir = os.path.abspath(output_dir)
        if not os.path.exists(self.output_dir):
            os.makedirs(self.output_dir)
        self.latex = latex or find_executable('latex')
        self.dvipng = dvipng or find_executable('dvipng')
        self.template = \
            template or os.path.join(os.path.dirname(__file__), 'template.tex')
        assert self.latex, 'No xelatex executable found'
        assert self.dvipng, 'No dvipng executable found'
        self.illegal_tags = [
            '\\afterassignment',
            '\\aftergroup',
            '\\errhelp',
            '\\errorstopmode',
            '\\every',
            '\\expandafter',
            '\\lowercase',
            '\\newhelp',
            '\\noexpand',
            '\\nonstopmode',
            '\\read',
            '\\relax',
            '\\scrollmode',
            '\\special'
            '\\uppercase',
            '\\write',
            '\\batchmode',
            '^^',
            'catcode',
            'command',
            'csname',
            'def',
            'include',
            'input',
            'loop',
            'name',
            'open',
            'output',
            'repeat',
            'toks',
        ]

    def render_template(self, latex, **kwargs):
        with open(self.template, 'r') as tmpl:
            template = Template(tmpl.read())
        return template.render(latex=latex, **kwargs)

    def render_image(self, working_dir, basename, latex, img_filename):
        tex_filename = os.path.join(working_dir, '{0}.tex'.format(basename))
        dvi_filename = os.path.join(working_dir, '{0}.dvi'.format(basename))
        png_filename = os.path.join(working_dir, '{0}.png'.format(basename))
        with open(tex_filename, 'w') as tex_file:
            tex_file.write(latex)
        latex_args = [
            self.latex,
            '-interaction=nonstopmode',
            '-output-directory={0}'.format(working_dir),
            '-output-format=dvi',
            tex_filename
        ]
        try:
            subprocess.check_call(latex_args)
        except subprocess.CalledProcessError:
            raise InvalidLatex('Error running latex command')
        dvipng_args = [
            self.dvipng,
            '-pp',
            '1',
            '-bg',
            'Transparent',
            '-q',
            '-o',
            png_filename,
            dvi_filename,
        ]
        subprocess.check_call(dvipng_args)
        img = Image.open(png_filename)
        bg = Image.new(img.mode, img.size, img.getpixel((0, 0)))
        diff = ImageChops.difference(img, bg)
        bbox = diff.getbbox()
        if bbox:
            img = img.crop(bbox)
        if not os.path.exists(os.path.dirname(img_filename)):
            os.makedirs(os.path.dirname(img_filename))
        img.convert('RGBA')
        img.save(img_filename, 'PNG', optimize=True)
        return img_filename

    def render(self, b64latex):
        basename = hashlib.md5(b64latex).hexdigest()
        img_filename = os.path.join(
            self.output_dir, '{0}.png'.format(basename)
        )
        if os.path.exists(img_filename):
            return img_filename
        working_dir = mkdtemp(prefix='latexrenderwd')
        latex = base64.b64decode(b64latex)
        latex = latex.decode('utf-8')
        if any(tag in latex for tag in self.illegal_tags):
            raise SuspiciousOperation('Illegal tag found')
        latex = self.render_template(latex)
        self.render_image(working_dir, basename, latex, img_filename)
        shutil.rmtree(working_dir)
        return img_filename

@app.route('/<b64latex>.png')
@app.route('/<b64latex>/')
def latexrender(b64latex=''):
    try:
        renderer = LatexRenderer(
            output_dir=app.config['OUTPUT_DIR'],
            template=app.config['TEMPLATE'],
            latex=app.config['XELATEX'],
            dvipng=app.config['DVIPNG'],
        )
        b64latex = unquote(b64latex)
        if not isinstance(b64latex, bytes):
            b64latex = b64latex.encode('utf-8')
        img = renderer.render(b64latex)
        if app.config['SENDFILE_ROOT'] and app.use_x_sendfile:
            img = os.path.join(app.config['SENDFILE_ROOT'], img)
        return send_file(img)
    except (SuspiciousOperation, InvalidLatex):
        return abort(400)
    except (Exception, EnvironmentError) as e:
        log.exception(e)
        return abort(500)

if __name__ == '__main__':
    app.run()


text:
package com.foxconn.cnsbg.escort.subsys.dao;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;

import de.greenrobot.dao.AbstractDao;
import de.greenrobot.dao.Property;
import de.greenrobot.dao.internal.DaoConfig;

import com.foxconn.cnsbg.escort.subsys.dao.CachedAlertMsg;

// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
/**
 * DAO for table CACHED_ALERT_MSG.
*/
public class CachedAlertMsgDao extends AbstractDao<CachedAlertMsg, Long> {

    public static final String TABLENAME = "CACHED_ALERT_MSG";

    /**
     * Properties of entity CachedAlertMsg.<br/>
     * Can be used for QueryBuilder and for referencing column names.
    */
    public static class Properties {
        public final static Property Id = new Property(0, Long.class, "id", true, "_id");
        public final static Property DeviceID = new Property(1, String.class, "deviceID", false, "DEVICE_ID");
        public final static Property Time = new Property(2, java.util.Date.class, "time", false, "TIME");
        public final static Property Type = new Property(3, String.class, "type", false, "TYPE");
        public final static Property Level = new Property(4, String.class, "level", false, "LEVEL");
        public final static Property Info = new Property(5, String.class, "info", false, "INFO");
    };

    public CachedAlertMsgDao(DaoConfig config) {
        super(config);
    }

    public CachedAlertMsgDao(DaoConfig config, DaoSession daoSession) {
        super(config, daoSession);
    }

    /** Creates the underlying database table. */
    public static void createTable(SQLiteDatabase db, boolean ifNotExists) {
        String constraint = ifNotExists? "IF NOT EXISTS ": "";
        db.execSQL("CREATE TABLE " + constraint + "'CACHED_ALERT_MSG' (" + //
                "'_id' INTEGER PRIMARY KEY ," + // 0: id
                "'DEVICE_ID' TEXT," + // 1: deviceID
                "'TIME' INTEGER," + // 2: time
                "'TYPE' TEXT," + // 3: type
                "'LEVEL' TEXT," + // 4: level
                "'INFO' TEXT);"); // 5: info
    }

    /** Drops the underlying database table. */
    public static void dropTable(SQLiteDatabase db, boolean ifExists) {
        String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "'CACHED_ALERT_MSG'";
        db.execSQL(sql);
    }

    /** @inheritdoc */
    @Override
    protected void bindValues(SQLiteStatement stmt, CachedAlertMsg entity) {
        stmt.clearBindings();

        Long id = entity.getId();
        if (id != null) {
            stmt.bindLong(1, id);
        }

        String deviceID = entity.getDeviceID();
        if (deviceID != null) {
            stmt.bindString(2, deviceID);
        }

        java.util.Date time = entity.getTime();
        if (time != null) {
            stmt.bindLong(3, time.getTime());
        }

        String type = entity.getType();
        if (type != null) {
            stmt.bindString(4, type);
        }

        String level = entity.getLevel();
        if (level != null) {
            stmt.bindString(5, level);
        }

        String info = entity.getInfo();
        if (info != null) {
            stmt.bindString(6, info);
        }
    }

    /** @inheritdoc */
    @Override
    public Long readKey(Cursor cursor, int offset) {
        return cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0);
    }

    /** @inheritdoc */
    @Override
    public CachedAlertMsg readEntity(Cursor cursor, int offset) {
        CachedAlertMsg entity = new CachedAlertMsg( //
            cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0), // id
            cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1), // deviceID
            cursor.isNull(offset + 2) ? null : new java.util.Date(cursor.getLong(offset + 2)), // time
            cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3), // type
            cursor.isNull(offset + 4) ? null : cursor.getString(offset + 4), // level
            cursor.isNull(offset + 5) ? null : cursor.getString(offset + 5) // info
        );
        return entity;
    }

    /** @inheritdoc */
    @Override
    public void readEntity(Cursor cursor, CachedAlertMsg entity, int offset) {
        entity.setId(cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0));
        entity.setDeviceID(cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1));
        entity.setTime(cursor.isNull(offset + 2) ? null : new java.util.Date(cursor.getLong(offset + 2)));
        entity.setType(cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3));
        entity.setLevel(cursor.isNull(offset + 4) ? null : cursor.getString(offset + 4));
        entity.setInfo(cursor.isNull(offset + 5) ? null : cursor.getString(offset + 5));
     }

    /** @inheritdoc */
    @Override
    protected Long updateKeyAfterInsert(CachedAlertMsg entity, long rowId) {
        entity.setId(rowId);
        return rowId;
    }

    /** @inheritdoc */
    @Override
    public Long getKey(CachedAlertMsg entity) {
        if(entity != null) {
            return entity.getId();
        } else {
            return null;
        }
    }

    /** @inheritdoc */
    @Override
    protected boolean isEntityUpdateable() {
        return true;
    }

}


text:
.. _ci:

Continuous Integration
======================

`Continuous Integration (CI, wiki) <http://en.wikipedia.org/wiki/Continuous_integration>`_
is the practice, in software engineering, of merging all developer working
copies with a shared mainline several times a day.

:ref:`cmd_ci` command is intended to be used in combination with the build
servers and the popular
`Continuous Integration Software <http://en.wikipedia.org/wiki/Comparison_of_continuous_integration_software>`_.

By integrating regularly, you can detect errors quickly, and locate them more
easily.

.. toctree::
    :maxdepth: 2

    appveyor
    circleci
    drone
    shippable
    travis


text:
#include "SkTypes.h"

#if !SK_ALLOW_STATIC_GLOBAL_INITIALIZERS

#include "../../include/effects/SkEffects.h"

void SkEffects::Init() {
}

#endif


text:
title: "New package tcR with initial version 1.0 "
kind: article
created_at: 2014-12-12 13:18:00 UTC
author: CRANberries
categories:
tags:
layout: post
---
Package: tcR

Type: Package

Title: Data Analysis of T-cell Receptor Repertoires

Version: 1.0

Date: 2014-12-12

Author: Vadim Nazarov, Mikhail Pogorelyy

Maintainer: Vadim Nazarov <vdm.nazarov@gmail.com>

Description: Platform for the advanced analysis of T-cell receptor repertoires
data and visualisation of the analysis results.

License: Apache License 2.0

Depends: R (>= 2.10), ggplot2 (>= 1.0.0), dplyr (>= 0.2), gridExtra (>=
0.9.0), reshape2 (>= 1.2.0)

Imports: utils (>= 3.1.0), Rcpp (>= 0.11.1), grid (>= 3.0.0),
data.table (>= 1.9.0), gtable (>= 0.1.2), roxygen2 (>= 3.0.0),
stringdist (>= 0.7.3)

LinkingTo: Rcpp

Packaged: 2014-12-12 11:34:00 UTC; n-san

NeedsCompilation: yes

Repository: CRAN

Date/Publication: 2014-12-12 14:50:19

More information about tcR at CRAN

    Original post by CRANberries - check out CRANberries


text:
layout: page
title: Diamond Software Executive Retreat
date: 2016-05-24
author: Anna Hanna
tags: weekly links, java
status: published
summary: Etiam at nisi euismod, finibus nisi convallis, molestie.
banner: images/banner/leisure-02.jpg
booking:
  startDate: 06/09/2017
  endDate: 06/10/2017
  ctyhocn: NCLHXHX
  groupCode: DSER
published: true
---
Fusce maximus arcu nunc, vel pellentesque ligula faucibus bibendum. Pellentesque non nisi at sem feugiat lobortis. Etiam pretium nulla elit, a efficitur mauris sollicitudin ac. Nam eget quam semper, rhoncus diam sed, tristique tellus. Mauris arcu lectus, interdum vitae dignissim vitae, iaculis sed quam. Quisque fermentum vulputate tempus. Aliquam eu tortor diam. Aenean pulvinar metus neque, et tristique ante tristique sit amet.
Sed ultrices malesuada vehicula. Vivamus nisi felis, finibus non mattis sit amet, molestie non enim. Integer sed magna tincidunt, scelerisque justo sed, placerat eros. In non tempus risus, nec consequat nunc. Fusce id scelerisque velit, a aliquam tellus. Integer elit mi, hendrerit nec cursus vel, sodales ut dui. Etiam tortor ipsum, varius eu pharetra ac, commodo sit amet mi. Vivamus fermentum lacinia nulla, ac semper tellus semper accumsan. Cras fringilla a mi eget consequat. In vitae hendrerit ipsum. Phasellus sed sapien mauris. Sed tortor nisi, ultricies eget eleifend quis, consequat vel nibh. Ut mauris erat, molestie ut dictum vitae, fermentum a nisl.

* Nullam ut nisi sed augue rutrum vestibulum
* Maecenas quis magna sed magna scelerisque viverra
* Sed sed velit faucibus, dapibus nibh non, blandit urna
* Praesent finibus eros quis dui porttitor malesuada.

Nam elementum sapien ac nisl hendrerit, vitae convallis tellus bibendum. Phasellus lobortis nibh nibh, eu imperdiet nisl pretium eu. Nullam vulputate bibendum tellus vel ultrices. Vivamus id urna feugiat, blandit elit dapibus, rhoncus diam. Proin feugiat erat ullamcorper, consectetur dui vel, convallis neque. Suspendisse varius cursus metus, ac molestie dui lacinia ut. Etiam tempus tortor pharetra, condimentum augue ac, ultricies orci. Phasellus porttitor non ante id imperdiet. Quisque maximus, elit vitae laoreet lobortis, massa nisl tempor dui, id venenatis erat sem eget sapien. Nulla semper fringilla diam a auctor.


text:
'use strict';
describe('Gait Analysis controller specification', function () {
	var $scope, mockedSamples, $httpBackend, $location, webapi;
	var $controller;
	var gait_sample;
	var patient;

	beforeEach(module('oga_web.gait_analysis'));
	beforeEach(module('oga_web.oga_facade'));

	beforeEach(inject(function($rootScope, _$controller_, _$httpBackend_, _$location_, urlApi){
		$scope = $rootScope.$new();
		$httpBackend = _$httpBackend_;
		$location = _$location_;
		webapi = urlApi.urlString();
		$controller = _$controller_;
		patient = buildMockedPatients().getPatients()[0];
		patient.gait_samples = [];
		gait_sample = {id:0, date: new Date(2010, 1, 1), description: 'testing'};
		patient.gait_samples.push(gait_sample);
		var patient_ = {data:patient};
		$controller('gaitAnalysisCtrl', {$scope:$scope, patient:patient_});
	}));

	var checkInitialState = function(){
		expect($scope.patient).toEqual(patient);
		expect($scope.isAdding).toEqual(false);
		expect($scope.gaitSampleEnabled).toEqual(true);
		expect($scope.gait_sample).toBeDefined();
		expect($scope.patient.gait_samples).toBeDefined();
		expect($scope.isShowMarkers).toBe(false);
		expect($scope.positionalsData).toBe(null);
		expect($scope.isPlaySample).toBe(false);
	};

	it('Test initial state without gait samples', function () {
		$scope.patient.gait_samples.pop();
		$controller('gaitAnalysisCtrl', {$scope:$scope, patient:{data: $scope.patient}});
		expect($scope.gait_sample).toBeDefined();
		expect($scope.gaitSampleEnabled).toEqual(false);
	});

	it('Test initial state', function() {
		checkInitialState();
	 });

	it('Test add gait sample state', function(){
		$scope.addGaitData();
		expect($scope.patient).toEqual(patient);
		expect($scope.isAdding).toEqual(true);
		expect($scope.gaitSampleEnabled).toEqual(false);
		expect($scope.gait_sample).toBeDefined();
		expect($scope.gait_sample.patient).toEqual($scope.patient.id);
		expect($scope.patient.gait_samples).toBeDefined();
		expect($scope.isShowMarkers).toEqual(false);
		expect($scope.positionalsData).toEqual(null);
		expect($scope.isPlaySample).toEqual(false);
	});
	it('Test add gait sample state after edit markers', function(){
		$scope.addGaitData();
		expect($scope.isShowMarkers).toEqual(false);
		$scope.showMarkers();
		$scope.addGaitData();
		expect($scope.isShowMarkers).toEqual(false);
	});

	it('Test add new gait sample', function() {
		$httpBackend.whenPUT(webapi + 'patients/').respond(function(method, url, data, headers){
			var d = JSON.parse(data);
			expect(d.gait_samples).toBeDefined();
			expect(d.gait_samples.length).toEqual(1);
			return [204, angular.fromJson(data), {}];
		});
		$httpBackend.whenGET(webapi + 'gait_sample/positional_data/0/0/').respond(function(){
			return [404, {}, {}];
		});
		$scope.addGaitData();
		$scope.gait_sample.description = "testing";
		$scope.gait_sample.date = new Date(2011, 10, 10);
		delete $scope.patient.gait_samples;
		expect($scope.patient.gait_samples).toBeUndefined();
		$scope.saveSample();
		$httpBackend.flush();
		expect($scope.patient.gait_samples).toBeDefined();
		expect($scope.patient.gait_samples.length).toEqual(1);
		expect($scope.isAdding).toBe(false);
		expect($scope.gaitSampleEnabled).toBe(true);
	});

	it('Test save a gait sample.', function(){
		$httpBackend.whenPUT(webapi + 'patients/').respond(function(method, url, data, headers){
			var d = JSON.parse(data);
			expect(d.gait_samples).toBeDefined();
			expect(d.gait_samples.length).toEqual(1);
			return [204, angular.fromJson(data), {}];
		});
		$httpBackend.whenPUT(webapi + 'gait_sample/positionals_data/').respond(function(method, url, data, headers){
			return [200, {}, {}];
		});
		$httpBackend.whenGET(webapi + 'gait_sample/positional_data/0/0/').respond(function(){
			return [200, {_id:11}, {}];
		});
		expect($scope.isAdding).toBe(false);
		$scope.showGaitSample(gait_sample);
		$httpBackend.flush();
		expect($scope.positionalsData).toBeDefined();
		$scope.saveSample();
		$httpBackend.flush();
		expect($scope.isAdding).toBe(false);
		expect($scope.gaitSampleEnabled).toBe(true);
		expect($scope.positionalsData).toBeDefined();
		expect($scope.positionalsData._id).toBeDefined();
		expect($scope.positionalsData._id).toBe(11);
		expect($scope.isPlaySample = false);
	});

	it('Test gait sample is undefined and there are gait samples', function(){
		expect($scope.gait_sample).toBeDefined();
	});

	it('Test show gait sample.', function(){
		$scope.showGaitSample(gait_sample);
		expect($scope.patient).toEqual(patient);
		expect($scope.isAdding).toEqual(false);
		expect($scope.gaitSampleEnabled).toEqual(true);
		expect($scope.gait_sample).toEqual(gait_sample);
		expect($scope.patient.gait_samples.length).toBe(1);
		expect($scope.isShowMarkers).toBe(false);
	});

	it ('Test upload a gait sample', function() {
		var files = [new File([''], 'mocks.txt')];
		var mock_data = {'id_patient': 0, 'gait_sample_index': 0, 'frame_rate': 315, 'frames': 2000, 'number_marks': 20, 'original_filename': 'mocks.txt'};
		$httpBackend.whenPOST(webapi + 'gait_sample/upload/0/0/').respond(function(method, url, data, headers) {
			expect(data).toBeDefined();
			return [200, mock_data, {}];
		});
		$httpBackend.whenGET(webapi + 'gait_sample/positional_data/0/0/').respond(function(){
			return [200, {_id:11}, {}];
		});
		$scope.upload(files);
		$httpBackend.flush();
		expect($scope.gait_sample).toBeDefined();
		expect($scope.positionalsData).toNotBe(null);
		expect($scope.positionalsData.original_filename).toBe('mocks.txt');
	});

	it('Test showmarkers', function () {
		$scope.showMarkers()
		expect($scope.isShowMarkers).toBe(true);
	});

	it('Test add new angle', function () {
		$scope.addNewAngle();
		expect($scope.isAddingNewAngle).toBe(true);
	});

	it('Test save new angle', function () {
		$httpBackend.whenGET(webapi + 'gait_sample/positional_data/0/0/').respond(function(){
			return [200, {}, {}];
		});
		$httpBackend.whenPUT(webapi + 'patients/').respond(function(method, url, data, headers){
			return [204, angular.fromJson(data), {}];
		});

		$scope.addNewAngle();
		$scope.angle = {'description': 'New Angle'}
		$scope.positionalsData = {angles:[]};
		$scope.$apply(function(){
			$scope.$broadcast('saveNewAngle');
		});
		expect($scope.positionalsData.angles.length).toBe(1);
		expect($scope.isAddingNewAngle).toBe(false);
	});

	it('Test cancel add New Angle()', function () {
		$httpBackend.whenGET(webapi + 'gait_sample/positional_data/0/0/').respond(function(){
			return [200, {}, {}];
		});
		$httpBackend.whenPUT(webapi + 'patients/').respond(function(method, url, data, headers){
			return [204, angular.fromJson(data), {}];
		});

		$scope.addNewAngle();
		$scope.$apply(function() {
			$scope.$broadcast('cancelAddNewAngle');
		});
		expect($scope.isAddingNewAngle).toBe(false);
	});
});


text:
namespace sw {

struct Configuration
{
	enum class AffinityPolicy : int
	{
		// A thread has affinity with any core in the affinity mask.
		AnyOf = 0,
		// A thread has affinity with a single core in the affinity mask.
		OneOf = 1,
	};

	// -------- [Processor] --------
	// Number of threads used by the scheduler. A thread count of 0 is
	// interpreted as min(cpu_cores_available, 16).
	uint32_t threadCount = 0;

	// Core affinity and affinity policy used by the scheduler.
	uint64_t affinityMask = 0xFFFFFFFFFFFFFFFFu;
	AffinityPolicy affinityPolicy = AffinityPolicy::AnyOf;

	// -------- [Profiler] --------
	// Whether SPIR-V profiling is enabled.
	bool enableSpirvProfiling = false;
	// Period controlling how often SPIR-V profiles are reported.
	uint64_t spvProfilingReportPeriodMs = 1000;
	// Directory where SPIR-V profile reports will be written.
	std::string spvProfilingReportDir = "";
};

// Get the configuration as parsed from a configuration file.
const Configuration &getConfiguration();

// Get the scheduler configuration given a configuration.
marl::Scheduler::Config getSchedulerConfiguration(const Configuration &config);

}  // namespace sw

#endif


text:
 A [Sass]/[PostCSS] toolbelt for superspeed front-end development

[PostCSS]: https://github.com/postcss/postcss
[Gulp]: https://github.com/gulpjs/gulp
[Sass]: http://sass-lang.com

## Installation

```js
npm install postcss-styler
```

## Example
Documentation coming soon...


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Beih. Nova Hedwigia 59: 225 (1979)

#### Original name
Rhodophyllus stylobates Romagn. & Gilles

### Remarks
null


text:
require 'minitest/autorun'

require "java"

VENDOR_PATH = File.expand_path("../../vendor", __FILE__)

# load all vendored jar dependencies
Dir["#{VENDOR_PATH}/*.jar"].each { |jar| require jar }

# load native jars for platform
if RbConfig::CONFIG["target_cpu"] =~ /x86/ && RbConfig::CONFIG["host_os"] =~ /darwin/
  require "#{VENDOR_PATH}/macosx/couchbase-lite-java-native.jar"
elsif RbConfig::CONFIG["target_cpu"] =~ /arm/
  require "#{VENDOR_PATH}/linux_arm/couchbase-lite-java-native.jar"
end


text:
// checkconfig loads configuration for Prow to validate it
package main

import (
	"errors"
	"flag"
	"fmt"
	"io/fs"
	"io/ioutil"
	"net/url"
	"os"
	"reflect"
	"strings"

	"github.com/sirupsen/logrus"
	"k8s.io/apimachinery/pkg/util/sets"
	"k8s.io/apimachinery/pkg/util/validation"
	"sigs.k8s.io/yaml"

	utilerrors "k8s.io/apimachinery/pkg/util/errors"

	v1 "k8s.io/test-infra/prow/apis/prowjobs/v1"
	"k8s.io/test-infra/prow/config"
	"k8s.io/test-infra/prow/config/secret"
	needsrebase "k8s.io/test-infra/prow/external-plugins/needs-rebase/plugin"
	"k8s.io/test-infra/prow/flagutil"
	configflagutil "k8s.io/test-infra/prow/flagutil/config"
	pluginsflagutil "k8s.io/test-infra/prow/flagutil/plugins"
	"k8s.io/test-infra/prow/github"
	_ "k8s.io/test-infra/prow/hook/plugin-imports"
	"k8s.io/test-infra/prow/kube"
	"k8s.io/test-infra/prow/labels"
	"k8s.io/test-infra/prow/logrusutil"
	"k8s.io/test-infra/prow/plugins"
	"k8s.io/test-infra/prow/plugins/approve"
	"k8s.io/test-infra/prow/plugins/blockade"
	"k8s.io/test-infra/prow/plugins/blunderbuss"
	"k8s.io/test-infra/prow/plugins/bugzilla"
	"k8s.io/test-infra/prow/plugins/cherrypickunapproved"
	"k8s.io/test-infra/prow/plugins/hold"
	"k8s.io/test-infra/prow/plugins/lgtm"
	ownerslabel "k8s.io/test-infra/prow/plugins/owners-label"
	"k8s.io/test-infra/prow/plugins/releasenote"
	"k8s.io/test-infra/prow/plugins/trigger"
	verifyowners "k8s.io/test-infra/prow/plugins/verify-owners"
	"k8s.io/test-infra/prow/plugins/wip"
)

type options struct {
	config        configflagutil.ConfigOptions
	pluginsConfig pluginsflagutil.PluginOptions

	prowYAMLRepoName string
	prowYAMLPath     string

	warnings        flagutil.Strings
	excludeWarnings flagutil.Strings
	strict          bool
	expensive       bool

	github flagutil.GitHubOptions
}

func reportWarning(strict bool, errs utilerrors.Aggregate) {
	for _, item := range errs.Errors() {
		logrus.Warn(item.Error())
	}
	if strict {
		logrus.Fatal("Strict is set and there were warnings")
	}
}

func (o *options) warningEnabled(warning string) bool {
	return sets.NewString(o.warnings.Strings()...).Difference(sets.NewString(o.excludeWarnings.Strings()...)).Has(warning)
}

const (
	mismatchedTideWarning                         = "mismatched-tide"
	mismatchedTideLenientWarning                  = "mismatched-tide-lenient"
	tideStrictBranchWarning                       = "tide-strict-branch"
	tideContextPolicy                             = "tide-context-policy"
	nonDecoratedJobsWarning                       = "non-decorated-jobs"
	validDecorationConfigWarning                  = "valid-decoration-config"
	jobNameLengthWarning                          = "long-job-names"
	jobRefsDuplicationWarning                     = "duplicate-job-refs"
	needsOkToTestWarning                          = "needs-ok-to-test"
	managedWebhooksWarning                        = "managed-webhooks"
	validateOwnersWarning                         = "validate-owners"
	missingTriggerWarning                         = "missing-trigger"
	validateURLsWarning                           = "validate-urls"
	unknownFieldsWarning                          = "unknown-fields"
	verifyOwnersFilePresence                      = "verify-owners-presence"
	validateClusterFieldWarning                   = "validate-cluster-field"
	validateSupplementalProwConfigOrgRepoHirarchy = "validate-supplemental-prow-config-hirarchy"
	validateUnmanagedBranchConfigHasNoSubconfig   = "validate-unmanaged-branchconfig-has-no-subconfig"

	defaultHourlyTokens = 3000
	defaultAllowedBurst = 100
)

var defaultWarnings = []string{
	mismatchedTideWarning,
	tideStrictBranchWarning,
	tideContextPolicy,
	mismatchedTideLenientWarning,
	nonDecoratedJobsWarning,
	jobNameLengthWarning,
	jobRefsDuplicationWarning,
	needsOkToTestWarning,
	managedWebhooksWarning,
	validateOwnersWarning,
	missingTriggerWarning,
	validateURLsWarning,
	unknownFieldsWarning,
	validateClusterFieldWarning,
	validateSupplementalProwConfigOrgRepoHirarchy,
	validateUnmanagedBranchConfigHasNoSubconfig,
}

var expensiveWarnings = []string{
	verifyOwnersFilePresence,
}

var throttlerDefaults = flagutil.ThrottlerDefaults(defaultHourlyTokens, defaultAllowedBurst)

func getAllWarnings() []string {
	var all []string
	all = append(all, defaultWarnings...)
	all = append(all, expensiveWarnings...)

	return all
}

func (o *options) DefaultAndValidate() error {
	allWarnings := getAllWarnings()
	for _, validate := range []interface{ Validate(bool) error }{&o.config, &o.pluginsConfig} {
		if err := validate.Validate(false); err != nil {
			return err
		}
	}

	if o.prowYAMLPath != "" && o.prowYAMLRepoName == "" {
		return errors.New("--prow-yaml-repo-path requires --prow-yaml-repo-name to be set")
	}
	if o.prowYAMLRepoName != "" {
		if o.prowYAMLPath == "" {
			o.prowYAMLPath = fmt.Sprintf("/home/prow/go/src/github.com/%s/.prow.yaml", o.prowYAMLRepoName)
		}
	}
	for _, warning := range o.warnings.Strings() {
		found := false
		for _, registeredWarning := range allWarnings {
			if warning == registeredWarning {
				found = true
				break
			}
		}
		if !found {
			return fmt.Errorf("no such warning %q, valid warnings: %v", warning, allWarnings)
		}
	}
	return nil
}

func parseOptions() (options, error) {
	o := options{}

	if err := o.gatherOptions(flag.CommandLine, os.Args[1:]); err != nil {
		return options{}, err
	}
	return o, nil
}

func (o *options) gatherOptions(flag *flag.FlagSet, args []string) error {
	o.pluginsConfig.CheckUnknownPlugins = true
	flag.StringVar(&o.prowYAMLRepoName, "prow-yaml-repo-name", "", "Name of the repo whose .prow.yaml should be checked.")
	flag.StringVar(&o.prowYAMLPath, "prow-yaml-path", "", "Path to the .prow.yaml file to check. Requires --prow-yaml-repo-name to be set. Defaults to `/home/prow/go/src/github.com/<< prow-yaml-repo-name >>/.prow.yaml`")
	flag.Var(&o.warnings, "warnings", "Warnings to validate. Use repeatedly to provide a list of warnings")
	flag.Var(&o.excludeWarnings, "exclude-warning", "Warnings to exclude. Use repeatedly to provide a list of warnings to exclude")
	flag.BoolVar(&o.expensive, "expensive-checks", false, "If set, additional expensive warnings will be enabled")
	flag.BoolVar(&o.strict, "strict", false, "If set, consider all warnings as errors.")
	o.github.AddCustomizedFlags(flag, throttlerDefaults)
	o.github.AllowAnonymous = true
	o.config.AddFlags(flag)
	o.pluginsConfig.AddFlags(flag)
	if err := flag.Parse(args); err != nil {
		return fmt.Errorf("parse flags: %v", err)
	}
	if err := o.DefaultAndValidate(); err != nil {
		return fmt.Errorf("invalid options: %v", err)
	}
	return nil
}

func main() {
	logrusutil.ComponentInit()

	o, err := parseOptions()
	if err != nil {
		logrus.Fatalf("Error parsing options - %v", err)
	}

	if err := validate(o); err != nil {
		switch e := err.(type) {
		case utilerrors.Aggregate:
			reportWarning(o.strict, e)
		default:
			logrus.WithError(err).Fatal("Validation failed")
		}

	} else {
		logrus.Info("checkconfig passes without any error!")
	}

}

func validate(o options) error {
	// use all warnings by default
	if len(o.warnings.Strings()) == 0 {
		if o.expensive {
			o.warnings = flagutil.NewStrings(getAllWarnings()...)
		} else {
			o.warnings = flagutil.NewStrings(defaultWarnings...)
		}
	}

	configAgent, err := o.config.ConfigAgent()
	if err != nil {
		return fmt.Errorf("error loading prow config: %w", err)
	}
	cfg := configAgent.Config()

	if o.prowYAMLRepoName != "" {
		if err := validateInRepoConfig(cfg, o.prowYAMLPath, o.prowYAMLRepoName); err != nil {
			return fmt.Errorf("error validating .prow.yaml: %w", err)
		}
	}

	var pcfg *plugins.Configuration
	if o.pluginsConfig.PluginConfigPath != "" {
		pluginAgent, err := o.pluginsConfig.PluginAgent()
		if err != nil {
			return fmt.Errorf("error loading Prow plugin config: %w", err)
		}
		pcfg = pluginAgent.Config()
	}

	// the following checks are useful in finding user errors but their
	// presence won't lead to strictly incorrect behavior, so we can
	// detect them here but don't necessarily want to stop config re-load
	// in all components on their failure.
	var errs []error
	if pcfg != nil && o.warningEnabled(verifyOwnersFilePresence) {
		if o.github.TokenPath == "" {
			return errors.New("cannot verify OWNERS file presence without a GitHub token")
		}
		secretAgent := &secret.Agent{}
		if err := secretAgent.Start(nil); err != nil {
			return fmt.Errorf("error starting secrets agent: %w", err)
		}

		githubClient, err := o.github.GitHubClient(secretAgent, false)
		if err != nil {
			return fmt.Errorf("error loading GitHub client: %w", err)
		}
		// 404s are expected to happen, no point in retrying
		githubClient.SetMax404Retries(0)

		if err := verifyOwnersPresence(pcfg, githubClient); err != nil {
			errs = append(errs, err)
		}
	}
	if pcfg != nil && o.warningEnabled(mismatchedTideWarning) {
		if err := validateTideRequirements(cfg, pcfg, true); err != nil {
			errs = append(errs, err)
		}
	} else if pcfg != nil && o.warningEnabled(mismatchedTideLenientWarning) {
		if err := validateTideRequirements(cfg, pcfg, false); err != nil {
			errs = append(errs, err)
		}
	}
	if o.warningEnabled(nonDecoratedJobsWarning) {
		if err := validateDecoratedJobs(cfg); err != nil {
			errs = append(errs, err)
		}
	}
	if o.warningEnabled(validDecorationConfigWarning) {
		if err := validateDecorationConfig(cfg); err != nil {
			errs = append(errs, err)
		}
	}
	if o.warningEnabled(jobNameLengthWarning) {
		if err := validateJobRequirements(cfg.JobConfig); err != nil {
			errs = append(errs, err)
		}
	}
	if o.warningEnabled(jobRefsDuplicationWarning) {
		if err := validateJobExtraRefs(cfg.JobConfig); err != nil {
			errs = append(errs, err)
		}
	}
	if o.warningEnabled(needsOkToTestWarning) {
		if err := validateNeedsOkToTestLabel(cfg); err != nil {
			errs = append(errs, err)
		}
	}
	if o.warningEnabled(managedWebhooksWarning) {
		if err := validateManagedWebhooks(cfg); err != nil {
			errs = append(errs, err)
		}
	}
	if pcfg != nil && o.warningEnabled(validateOwnersWarning) {
		if err := verifyOwnersPlugin(pcfg); err != nil {
			errs = append(errs, err)
		}
	}
	if pcfg != nil && o.warningEnabled(missingTriggerWarning) {
		if err := validateTriggers(cfg, pcfg); err != nil {
			errs = append(errs, err)
		}
	}
	if pcfg != nil && o.warningEnabled(validateURLsWarning) {
		if err := validateURLs(cfg.ProwConfig); err != nil {
			errs = append(errs, err)
		}
	}
	if o.warningEnabled(unknownFieldsWarning) {
		cfgBytes, err := ioutil.ReadFile(o.config.ConfigPath)
		if err != nil {
			return fmt.Errorf("error reading Prow config for validation: %w", err)
		}
		if err := validateUnknownFields(&config.Config{}, cfgBytes, o.config.ConfigPath); err != nil {
			errs = append(errs, err)
		}
	}
	if pcfg != nil && o.warningEnabled(unknownFieldsWarning) {
		pcfgBytes, err := ioutil.ReadFile(o.pluginsConfig.PluginConfigPath)
		if err != nil {
			return fmt.Errorf("error reading Prow plugin config for validation: %w", err)
		}
		if err := validateUnknownFields(&plugins.Configuration{}, pcfgBytes, o.pluginsConfig.PluginConfigPath); err != nil {
			errs = append(errs, err)
		}
	}
	if o.warningEnabled(tideStrictBranchWarning) {
		if err := validateStrictBranches(cfg.ProwConfig); err != nil {
			errs = append(errs, err)
		}
	}
	if o.warningEnabled(tideContextPolicy) {
		if err := validateTideContextPolicy(cfg); err != nil {
			errs = append(errs, err)
		}
	}
	if o.warningEnabled(validateClusterFieldWarning) {
		if err := validateCluster(cfg); err != nil {
			errs = append(errs, err)
		}
	}

	if o.warningEnabled(validateSupplementalProwConfigOrgRepoHirarchy) {
		if err := validateAdditionalProwConfigIsInOrgRepoDirectoryStructure(os.DirFS("./"), o.config.SupplementalProwConfigDirs.Strings(), o.pluginsConfig.SupplementalPluginsConfigDirs.Strings(), o.config.SupplementalProwConfigsFileNameSuffix, o.pluginsConfig.SupplementalPluginsConfigsFileNameSuffix); err != nil {
			errs = append(errs, err)
		}
	}

	if o.warningEnabled(validateUnmanagedBranchConfigHasNoSubconfig) {
		if err := validateUnmanagedBranchprotectionConfigDoesntHaveSubconfig(cfg.BranchProtection); err != nil {
			errs = append(errs, err)
		}
	}

	return utilerrors.NewAggregate(errs)
}
func policyIsStrict(p config.Policy) bool {
	if p.Protect == nil || !*p.Protect {
		return false
	}
	if p.RequiredStatusChecks == nil || p.RequiredStatusChecks.Strict == nil {
		return false
	}
	return *p.RequiredStatusChecks.Strict
}

func strictBranchesConfig(c config.ProwConfig) (*orgRepoConfig, error) {
	strictOrgExceptions := make(map[string]sets.String)
	strictRepos := sets.NewString()
	for orgName := range c.BranchProtection.Orgs {
		org := c.BranchProtection.GetOrg(orgName)
		// First find explicitly configured repos and partition based on strictness.
		// If any branch in a repo is strict we assume that the whole repo is to
		// simplify this validation.
		strictExplicitRepos, nonStrictExplicitRepos := sets.NewString(), sets.NewString()
		for repoName := range org.Repos {
			repo := org.GetRepo(repoName)
			strict := policyIsStrict(repo.Policy)
			if !strict {
				for branchName := range repo.Branches {
					branch, err := repo.GetBranch(branchName)
					if err != nil {
						return nil, err
					}
					if policyIsStrict(branch.Policy) {
						strict = true
						break
					}
				}
			}
			fullRepoName := fmt.Sprintf("%s/%s", orgName, repoName)
			if strict {
				strictExplicitRepos.Insert(fullRepoName)
			} else {
				nonStrictExplicitRepos.Insert(fullRepoName)
			}
		}
		// Done partitioning the repos.

		if policyIsStrict(org.Policy) {
			// This org is strict, record with repo exceptions ("denylist")
			strictOrgExceptions[orgName] = nonStrictExplicitRepos
		} else {
			// The org is not strict, record member repos that are allowed
			strictRepos.Insert(strictExplicitRepos.UnsortedList()...)
		}
	}
	return newOrgRepoConfig(strictOrgExceptions, strictRepos), nil
}

func validateStrictBranches(c config.ProwConfig) error {
	const explanation = "See #5: https://github.com/kubernetes/test-infra/blob/master/prow/cmd/tide/maintainers.md#best-practices Also note that this validation is imperfect, see the check-config code for details"
	if len(c.Tide.Queries) == 0 {
		// Short circuit here so that we can allow global level branchprotector
		// 'strict: true' if Tide is not enabled.
		// Ignoring the case where Tide is enabled only on orgs/repos specifically
		// exempted from the global setting simplifies validation immensely.
		return nil
	}
	if policyIsStrict(c.BranchProtection.Policy) {
		return fmt.Errorf("strict branchprotection context requirements cannot be globally enabled when Tide is configured for use. %s", explanation)
	}
	// The two assumptions below are not necessarily true, but they hold for all
	// known instances and make this validation much simpler.

	// Assumes if any branch is managed by Tide, the whole repo is.
	overallTideConfig := newOrgRepoConfig(c.Tide.Queries.OrgExceptionsAndRepos())
	// Assumes if any branch is strict the repo is strict.
	strictBranchConfig, err := strictBranchesConfig(c)
	if err != nil {
		return err
	}

	conflicts := overallTideConfig.intersection(strictBranchConfig).items()
	if len(conflicts) == 0 {
		return nil
	}
	return fmt.Errorf(
		"the following enable strict branchprotection context requirements even though Tide handles merges: [%s]. %s",
		strings.Join(conflicts, "; "),
		explanation,
	)
}

func validateURLs(c config.ProwConfig) error {
	var validationErrs []error

	if _, err := url.Parse(c.StatusErrorLink); err != nil {
		validationErrs = append(validationErrs, fmt.Errorf("status_error_link is not a valid url: %s", c.StatusErrorLink))
	}

	return utilerrors.NewAggregate(validationErrs)
}

func validateUnknownFields(cfg interface{}, cfgBytes []byte, filePath string) error {
	err := yaml.Unmarshal(cfgBytes, &cfg, yaml.DisallowUnknownFields)
	if err != nil {
		return fmt.Errorf("unknown fields or bad config in %s: %v", filePath, err)
	}
	return nil
}

func validateJobRequirements(c config.JobConfig) error {
	var validationErrs []error
	for repo, jobs := range c.PresubmitsStatic {
		for _, job := range jobs {
			validationErrs = append(validationErrs, validatePresubmitJob(repo, job))
		}
	}
	for repo, jobs := range c.PostsubmitsStatic {
		for _, job := range jobs {
			validationErrs = append(validationErrs, validatePostsubmitJob(repo, job))
		}
	}
	for _, job := range c.Periodics {
		validationErrs = append(validationErrs, validatePeriodicJob(job))
	}

	return utilerrors.NewAggregate(validationErrs)
}

func validatePresubmitJob(repo string, job config.Presubmit) error {
	var validationErrs []error
	// Prow labels k8s resources with job names. Labels are capped at 63 chars.
	if job.Agent == string(v1.KubernetesAgent) && len(job.Name) > validation.LabelValueMaxLength {
		validationErrs = append(validationErrs, fmt.Errorf("name of Presubmit job %q (for repo %q) too long (should be at most 63 characters)", job.Name, repo))
	}
	return utilerrors.NewAggregate(validationErrs)
}

func validatePostsubmitJob(repo string, job config.Postsubmit) error {
	var validationErrs []error
	// Prow labels k8s resources with job names. Labels are capped at 63 chars.
	if job.Agent == string(v1.KubernetesAgent) && len(job.Name) > validation.LabelValueMaxLength {
		validationErrs = append(validationErrs, fmt.Errorf("name of Postsubmit job %q (for repo %q) too long (should be at most 63 characters)", job.Name, repo))
	}
	return utilerrors.NewAggregate(validationErrs)
}

func validateJobExtraRefs(cfg config.JobConfig) error {
	var validationErrs []error
	for repo, presubmits := range cfg.PresubmitsStatic {
		for _, presubmit := range presubmits {
			if err := config.ValidateRefs(repo, presubmit.JobBase); err != nil {
				validationErrs = append(validationErrs, err)
			}
		}
	}
	return utilerrors.NewAggregate(validationErrs)
}

func validatePeriodicJob(job config.Periodic) error {
	var validationErrs []error
	// Prow labels k8s resources with job names. Labels are capped at 63 chars.
	if job.Agent == string(v1.KubernetesAgent) && len(job.Name) > validation.LabelValueMaxLength {
		validationErrs = append(validationErrs, fmt.Errorf("name of Periodic job %q too long (should be at most 63 characters)", job.Name))
	}
	return utilerrors.NewAggregate(validationErrs)
}

func validateTideRequirements(cfg *config.Config, pcfg *plugins.Configuration, includeForbidden bool) error {
	type matcher struct {
		// matches determines if the tide query appropriately honors the
		// label in question -- whether by requiring it or forbidding it
		matches func(label string, query config.TideQuery) bool
		// verb is used in forming error messages
		verb string
	}
	requires := matcher{
		matches: func(label string, query config.TideQuery) bool {
			return sets.NewString(query.Labels...).Has(label)
		},
		verb: "require",
	}
	forbids := matcher{
		matches: func(label string, query config.TideQuery) bool {
			return sets.NewString(query.MissingLabels...).Has(label)
		},
		verb: "forbid",
	}

	type plugin struct {
		// name and label identify the relationship we are validating
		name, label string
		// external indicates plugin is external or not
		external bool
		// matcher determines if the tide query appropriately honors the
		// label in question -- whether by requiring it or forbidding it
		matcher matcher
		// config holds the orgs and repos for which tide does honor the
		// label; this container is populated conditionally from queries
		// using the matcher
		config *orgRepoConfig
	}
	// configs list relationships between tide config
	// and plugin enablement that we want to validate
	configs := []plugin{
		{name: lgtm.PluginName, label: labels.LGTM, matcher: requires},
		{name: approve.PluginName, label: labels.Approved, matcher: requires},
	}
	if includeForbidden {
		configs = append(configs,
			plugin{name: hold.PluginName, label: labels.Hold, matcher: forbids},
			plugin{name: wip.PluginName, label: labels.WorkInProgress, matcher: forbids},
			plugin{name: bugzilla.PluginName, label: labels.InvalidBug, matcher: forbids},
			plugin{name: verifyowners.PluginName, label: labels.InvalidOwners, matcher: forbids},
			plugin{name: releasenote.PluginName, label: labels.ReleaseNoteLabelNeeded, matcher: forbids},
			plugin{name: cherrypickunapproved.PluginName, label: labels.CpUnapproved, matcher: forbids},
			plugin{name: blockade.PluginName, label: labels.BlockedPaths, matcher: forbids},
			plugin{name: needsrebase.PluginName, label: labels.NeedsRebase, external: true, matcher: forbids},
		)
	}

	for i := range configs {
		// For each plugin determine the subset of tide queries that match and then
		// the orgs and repos that the subset matches.
		var matchingQueries config.TideQueries
		for _, query := range cfg.Tide.Queries {
			if configs[i].matcher.matches(configs[i].label, query) {
				matchingQueries = append(matchingQueries, query)
			}
		}
		configs[i].config = newOrgRepoConfig(matchingQueries.OrgExceptionsAndRepos())
	}

	overallTideConfig := newOrgRepoConfig(cfg.Tide.Queries.OrgExceptionsAndRepos())

	// Now actually execute the checks we just configured.
	var validationErrs []error
	for _, pluginConfig := range configs {
		err := ensureValidConfiguration(
			pluginConfig.name,
			pluginConfig.label,
			pluginConfig.matcher.verb,
			pluginConfig.config,
			overallTideConfig,
			enabledOrgReposForPlugin(pcfg, pluginConfig.name, pluginConfig.external),
		)
		validationErrs = append(validationErrs, err)
	}

	return utilerrors.NewAggregate(validationErrs)
}

func newOrgRepoConfig(orgExceptions map[string]sets.String, repos sets.String) *orgRepoConfig {
	return &orgRepoConfig{
		orgExceptions: orgExceptions,
		repos:         repos,
	}
}

// orgRepoConfig describes a set of repositories with an explicit
// allowlist and a mapping of denied repos for owning orgs
type orgRepoConfig struct {
	// orgExceptions holds explicit denylists of repos for owning orgs
	orgExceptions map[string]sets.String
	// repos is an allowed list of repos
	repos sets.String
}

func (c *orgRepoConfig) items() []string {
	items := make([]string, 0, len(c.orgExceptions)+len(c.repos))
	for org, excepts := range c.orgExceptions {
		item := fmt.Sprintf("org: %s", org)
		if excepts.Len() > 0 {
			item = fmt.Sprintf("%s without repo(s) %s", item, strings.Join(excepts.List(), ", "))
			for _, repo := range excepts.List() {
				item = fmt.Sprintf("%s '%s'", item, repo)
			}
		}
		items = append(items, item)
	}
	for _, repo := range c.repos.List() {
		items = append(items, fmt.Sprintf("repo: %s", repo))
	}
	return items
}

// difference returns a new orgRepoConfig that represents the set difference of
// the repos specified by the receiver and the parameter orgRepoConfigs.
func (c *orgRepoConfig) difference(c2 *orgRepoConfig) *orgRepoConfig {
	res := &orgRepoConfig{
		orgExceptions: make(map[string]sets.String),
		repos:         sets.NewString().Union(c.repos),
	}
	for org, excepts1 := range c.orgExceptions {
		if excepts2, ok := c2.orgExceptions[org]; ok {
			res.repos.Insert(excepts2.Difference(excepts1).UnsortedList()...)
		} else {
			excepts := sets.NewString().Union(excepts1)
			// Add any applicable repos in repos2 to excepts
			for _, repo := range c2.repos.UnsortedList() {
				if parts := strings.SplitN(repo, "/", 2); len(parts) == 2 && parts[0] == org {
					excepts.Insert(repo)
				}
			}
			res.orgExceptions[org] = excepts
		}
	}

	res.repos = res.repos.Difference(c2.repos)

	for _, repo := range res.repos.UnsortedList() {
		if parts := strings.SplitN(repo, "/", 2); len(parts) == 2 {
			if excepts2, ok := c2.orgExceptions[parts[0]]; ok && !excepts2.Has(repo) {
				res.repos.Delete(repo)
			}
		}
	}
	return res
}

// intersection returns a new orgRepoConfig that represents the set intersection
// of the repos specified by the receiver and the parameter orgRepoConfigs.
func (c *orgRepoConfig) intersection(c2 *orgRepoConfig) *orgRepoConfig {
	res := &orgRepoConfig{
		orgExceptions: make(map[string]sets.String),
		repos:         sets.NewString(),
	}
	for org, excepts1 := range c.orgExceptions {
		// Include common orgs, but union exceptions.
		if excepts2, ok := c2.orgExceptions[org]; ok {
			res.orgExceptions[org] = excepts1.Union(excepts2)
		} else {
			// Include right side repos that match left side org.
			for _, repo := range c2.repos.UnsortedList() {
				if parts := strings.SplitN(repo, "/", 2); len(parts) == 2 && parts[0] == org && !excepts1.Has(repo) {
					res.repos.Insert(repo)
				}
			}
		}
	}
	for _, repo := range c.repos.UnsortedList() {
		if c2.repos.Has(repo) {
			res.repos.Insert(repo)
		} else if parts := strings.SplitN(repo, "/", 2); len(parts) == 2 {
			// Include left side repos that match right side org.
			if excepts2, ok := c2.orgExceptions[parts[0]]; ok && !excepts2.Has(repo) {
				res.repos.Insert(repo)
			}
		}
	}
	return res
}

// union returns a new orgRepoConfig that represents the set union of the
// repos specified by the receiver and the parameter orgRepoConfigs
func (c *orgRepoConfig) union(c2 *orgRepoConfig) *orgRepoConfig {
	res := &orgRepoConfig{
		orgExceptions: make(map[string]sets.String),
		repos:         sets.NewString(),
	}

	for org, excepts1 := range c.orgExceptions {
		// keep only items in both denylists that are not in the
		// explicit repo allowlist for the other configuration;
		// we know from how the orgRepoConfigs are constructed that
		// a org denylist won't intersect it's own repo allowlist
		pruned := excepts1.Difference(c2.repos)
		if excepts2, ok := c2.orgExceptions[org]; ok {
			res.orgExceptions[org] = pruned.Intersection(excepts2.Difference(c.repos))
		} else {
			res.orgExceptions[org] = pruned
		}
	}

	for org, excepts2 := range c2.orgExceptions {
		// update any denylists not previously updated
		if _, exists := res.orgExceptions[org]; !exists {
			res.orgExceptions[org] = excepts2.Difference(c.repos)
		}
	}

	// we need to prune out repos in the allowed lists which are
	// covered by an org already; we know from above that no
	// org denylist in the result will contain a repo allowlist
	for _, repo := range c.repos.Union(c2.repos).UnsortedList() {
		parts := strings.SplitN(repo, "/", 2)
		if len(parts) != 2 {
			logrus.Warnf("org/repo %q is formatted incorrectly", repo)
			continue
		}
		if _, exists := res.orgExceptions[parts[0]]; !exists {
			res.repos.Insert(repo)
		}
	}
	return res
}

func enabledOrgReposForPlugin(c *plugins.Configuration, plugin string, external bool) *orgRepoConfig {
	var (
		orgs  []string
		repos []string
	)
	var orgMap map[string]sets.String
	if external {
		orgs, repos = c.EnabledReposForExternalPlugin(plugin)
		orgMap = make(map[string]sets.String, len(orgs))
		for _, org := range orgs {
			orgMap[org] = nil
		}
	} else {
		_, repos, orgMap = c.EnabledReposForPlugin(plugin)
	}
	return newOrgRepoConfig(orgMap, sets.NewString(repos...))
}

// ensureValidConfiguration enforces rules about tide and plugin config.
// In this context, a subset is the set of repos or orgs for which a specific
// plugin is either enabled (for plugins) or required for merge (for tide). The
// tide superset is every org or repo that has any configuration at all in tide.
// Specifically:
//   - every item in the tide subset must also be in the plugins subset
//   - every item in the plugins subset that is in the tide superset must also be in the tide subset
// For example:
//   - if org/repo is configured in tide to require lgtm, it must have the lgtm plugin enabled
//   - if org/repo is configured in tide, the tide configuration must require the same set of
//     plugins as are configured. If the repository has LGTM and approve enabled, the tide query
//     must require both labels
func ensureValidConfiguration(plugin, label, verb string, tideSubSet, tideSuperSet, pluginsSubSet *orgRepoConfig) error {
	notEnabled := tideSubSet.difference(pluginsSubSet).items()
	notRequired := pluginsSubSet.intersection(tideSuperSet).difference(tideSubSet).items()

	var configErrors []error
	if len(notEnabled) > 0 {
		configErrors = append(configErrors, fmt.Errorf("the following orgs or repos %s the %s label for merging but do not enable the %s plugin: %v", verb, label, plugin, notEnabled))
	}
	if len(notRequired) > 0 {
		configErrors = append(configErrors, fmt.Errorf("the following orgs or repos enable the %s plugin but do not %s the %s label for merging: %v", plugin, verb, label, notRequired))
	}

	return utilerrors.NewAggregate(configErrors)
}

func validateDecoratedJobs(cfg *config.Config) error {
	var nonDecoratedJobs []string
	for _, presubmit := range cfg.AllStaticPresubmits([]string{}) {
		if presubmit.Agent == string(v1.KubernetesAgent) && !*presubmit.JobBase.UtilityConfig.Decorate {
			nonDecoratedJobs = append(nonDecoratedJobs, presubmit.Name)
		}
	}

	for _, postsubmit := range cfg.AllStaticPostsubmits([]string{}) {
		if postsubmit.Agent == string(v1.KubernetesAgent) && !*postsubmit.JobBase.UtilityConfig.Decorate {
			nonDecoratedJobs = append(nonDecoratedJobs, postsubmit.Name)
		}
	}

	for _, periodic := range cfg.AllPeriodics() {
		if periodic.Agent == string(v1.KubernetesAgent) && !*periodic.JobBase.UtilityConfig.Decorate {
			nonDecoratedJobs = append(nonDecoratedJobs, periodic.Name)
		}
	}

	if len(nonDecoratedJobs) > 0 {
		return fmt.Errorf("the following jobs use the kubernetes provider but do not use the pod utilities: %v", nonDecoratedJobs)
	}
	return nil
}

func validateDecorationConfig(cfg *config.Config) error {
	var configErrors []error
	for _, presubmit := range cfg.AllStaticPresubmits([]string{}) {
		if presubmit.Agent == string(v1.KubernetesAgent) && presubmit.Decorate != nil && *presubmit.Decorate && presubmit.DecorationConfig != nil {
			if err := presubmit.DecorationConfig.Validate(); err != nil {
				configErrors = append(configErrors, err)
			}
		}
	}

	for _, postsubmit := range cfg.AllStaticPostsubmits([]string{}) {
		if postsubmit.Agent == string(v1.KubernetesAgent) && postsubmit.Decorate != nil && *postsubmit.Decorate && postsubmit.DecorationConfig != nil {
			if err := postsubmit.DecorationConfig.Validate(); err != nil {
				configErrors = append(configErrors, err)
			}
		}
	}

	for _, periodic := range cfg.AllPeriodics() {
		if periodic.Agent == string(v1.KubernetesAgent) && periodic.Decorate != nil && *periodic.Decorate && periodic.DecorationConfig != nil {
			if err := periodic.DecorationConfig.Validate(); err != nil {
				configErrors = append(configErrors, err)
			}
		}
	}
	return utilerrors.NewAggregate(configErrors)
}

func validateNeedsOkToTestLabel(cfg *config.Config) error {
	var queryErrors []error
	for i, query := range cfg.Tide.Queries {
		for _, label := range query.Labels {
			if label == lgtm.LGTMLabel {
				for _, label := range query.MissingLabels {
					if label == labels.NeedsOkToTest {
						queryErrors = append(queryErrors, fmt.Errorf(
							"the tide query at position %d"+
								"forbids the %q label and requires the %q label, "+
								"which is not recommended; "+
								"see https://github.com/kubernetes/test-infra/blob/master/prow/cmd/tide/maintainers.md#best-practices "+
								"for more information",
							i, labels.NeedsOkToTest, lgtm.LGTMLabel),
						)
					}
				}
			}
		}
	}
	return utilerrors.NewAggregate(queryErrors)
}

func validateManagedWebhooks(cfg *config.Config) error {
	mw := cfg.ManagedWebhooks
	var errs []error
	orgs := sets.String{}
	for repo := range mw.OrgRepoConfig {
		if !strings.Contains(repo, "/") {
			org := repo
			orgs.Insert(org)
		}
	}
	for repo := range mw.OrgRepoConfig {
		if strings.Contains(repo, "/") {
			org := strings.SplitN(repo, "/", 2)[0]
			if orgs.Has(org) {
				errs = append(errs, fmt.Errorf(
					"org-level and repo-level webhooks are configured together for %q, "+
						"which is not allowed as there will be duplicated webhook events", repo))
			}
		}
	}
	return utilerrors.NewAggregate(errs)
}

func pluginsWithOwnersFile() string {
	return strings.Join([]string{approve.PluginName, blunderbuss.PluginName, ownerslabel.PluginName}, ", ")
}

func orgReposUsingOwnersFile(cfg *plugins.Configuration) *orgRepoConfig {
	// we do not know the set of repos that use OWNERS, but we
	// can get a reasonable proxy for this by looking at where
	// the `approve', `blunderbuss' and `owners-label' plugins
	// are enabled
	approveConfig := enabledOrgReposForPlugin(cfg, approve.PluginName, false)
	blunderbussConfig := enabledOrgReposForPlugin(cfg, blunderbuss.PluginName, false)
	ownersLabelConfig := enabledOrgReposForPlugin(cfg, ownerslabel.PluginName, false)
	return approveConfig.union(blunderbussConfig).union(ownersLabelConfig)
}

type FileInRepoExistsChecker interface {
	GetRepos(org string, isUser bool) ([]github.Repo, error)
	GetFile(org, repo, filepath, commit string) ([]byte, error)
}

func verifyOwnersPresence(cfg *plugins.Configuration, rc FileInRepoExistsChecker) error {
	ownersConfig := orgReposUsingOwnersFile(cfg)

	var missing []string
	for org, excluded := range ownersConfig.orgExceptions {
		repos, err := rc.GetRepos(org, false)
		if err != nil {
			return err
		}

		for _, repo := range repos {
			if excluded.Has(repo.FullName) || repo.Archived {
				continue
			}
			if _, err := rc.GetFile(repo.Owner.Login, repo.Name, "OWNERS", ""); err != nil {
				if _, nf := err.(*github.FileNotFound); nf {
					missing = append(missing, repo.FullName)
				} else {
					return fmt.Errorf("got error: %v", err)
				}
			}
		}
	}

	for repo := range ownersConfig.repos {
		items := strings.Split(repo, "/")
		if len(items) != 2 {
			return fmt.Errorf("bad repository '%s', expected org/repo format", repo)
		}
		if _, err := rc.GetFile(items[0], items[1], "OWNERS", ""); err != nil {
			if _, nf := err.(*github.FileNotFound); nf {
				missing = append(missing, repo)
			} else {
				return fmt.Errorf("got error: %v", err)
			}
		}
	}

	if len(missing) > 0 {
		return fmt.Errorf("the following orgs or repos enable at least one"+
			" plugin that uses OWNERS files (%s), but its master branch does not contain"+
			" a root level OWNERS file: %v", pluginsWithOwnersFile(), missing)
	}
	return nil
}

func verifyOwnersPlugin(cfg *plugins.Configuration) error {
	ownersConfig := orgReposUsingOwnersFile(cfg)
	validateOwnersConfig := enabledOrgReposForPlugin(cfg, verifyowners.PluginName, false)

	invalid := ownersConfig.difference(validateOwnersConfig).items()
	if len(invalid) > 0 {
		return fmt.Errorf("the following orgs or repos "+
			"enable at least one plugin that uses OWNERS files (%s) "+
			"but do not enable the %s plugin to ensure validity of OWNERS files: %v",
			pluginsWithOwnersFile(), verifyowners.PluginName, invalid,
		)
	}
	return nil
}

func validateTriggers(cfg *config.Config, pcfg *plugins.Configuration) error {
	configuredRepos := sets.NewString()
	for orgRepo := range cfg.JobConfig.PresubmitsStatic {
		configuredRepos.Insert(orgRepo)
	}
	for orgRepo := range cfg.JobConfig.PostsubmitsStatic {
		configuredRepos.Insert(orgRepo)
	}

	configured := newOrgRepoConfig(map[string]sets.String{}, configuredRepos)
	enabled := enabledOrgReposForPlugin(pcfg, trigger.PluginName, false)

	if missing := configured.difference(enabled).items(); len(missing) > 0 {
		return fmt.Errorf("the following repos have jobs configured but do not have the %s plugin enabled: %s", trigger.PluginName, strings.Join(missing, ", "))
	}
	return nil
}

func validateInRepoConfig(cfg *config.Config, filePath, repoIdentifier string) error {
	data, err := ioutil.ReadFile(filePath)
	if err != nil {
		if !os.IsNotExist(err) {
			return fmt.Errorf("failed to read file %q: %v", filePath, err)
		}
		return nil
	}

	prowYAML := &config.ProwYAML{}
	if err := yaml.Unmarshal(data, prowYAML); err != nil {
		return fmt.Errorf("failed to deserialize content of %q: %v", filePath, err)
	}

	if err := config.DefaultAndValidateProwYAML(cfg, prowYAML, repoIdentifier); err != nil {
		return fmt.Errorf("failed to validate .prow.yaml: %v", err)
	}

	return nil
}

func validateTideContextPolicy(cfg *config.Config) error {
	// We can not know all possible branches without asking GitHub, so instead we verify
	// all branches that are explicitly configured on any job. This will hopefully catch
	// most cases.
	allKnownOrgRepoBranches := map[string]sets.String{}
	for orgRepo, jobs := range cfg.PresubmitsStatic {
		if _, ok := allKnownOrgRepoBranches[orgRepo]; !ok {
			allKnownOrgRepoBranches[orgRepo] = sets.String{}
		}

		for _, job := range jobs {
			allKnownOrgRepoBranches[orgRepo].Insert(job.Branches...)
		}
	}

	// We have to disableInRepoConfig for this check, else we will
	// attempt to clone the repo if its enabled
	originalInRepoConfig := cfg.InRepoConfig
	cfg.InRepoConfig = config.InRepoConfig{}
	defer func() { cfg.InRepoConfig = originalInRepoConfig }()

	var errs []error
	for orgRepo, branches := range allKnownOrgRepoBranches {
		split := strings.Split(orgRepo, "/")
		if n := len(split); n != 2 {
			// May happen for gerrit
			continue
		}
		org, repo := split[0], split[1]

		if branches.Len() == 0 {
			// Make sure we always test at least one branch per repo
			// to catch cases where ppl only have jobs with empty branch
			// configs.
			branches.Insert("master")
		}
		for _, branch := range branches.List() {
			if _, err := cfg.GetTideContextPolicy(nil, org, repo, branch, nil, ""); err != nil {
				errs = append(errs, fmt.Errorf("context policy for %s branch in %s/%s is invalid: %w", branch, org, repo, err))
			}
		}
	}

	return utilerrors.NewAggregate(errs)
}

var agentsNotSupportingCluster = sets.NewString("jenkins")

func validateJobCluster(job config.JobBase) error {
	if job.Cluster != "" && job.Cluster != kube.DefaultClusterAlias && agentsNotSupportingCluster.Has(job.Agent) {
		return fmt.Errorf("%s: cannot set cluster field if agent is %s", job.Name, job.Agent)
	}
	return nil
}

func validateCluster(cfg *config.Config) error {
	var errs []error
	for orgRepo, jobs := range cfg.PresubmitsStatic {
		for _, job := range jobs {
			if err := validateJobCluster(job.JobBase); err != nil {
				errs = append(errs, fmt.Errorf("%s: %w", orgRepo, err))
			}
		}
	}
	for _, job := range cfg.Periodics {
		if err := validateJobCluster(job.JobBase); err != nil {
			errs = append(errs, fmt.Errorf("%s: %w", "invalid periodic job", err))
		}

	}
	for orgRepo, jobs := range cfg.PostsubmitsStatic {
		for _, job := range jobs {
			if err := validateJobCluster(job.JobBase); err != nil {
				errs = append(errs, fmt.Errorf("%s: %w", orgRepo, err))
			}
		}
	}
	return utilerrors.NewAggregate(errs)
}

func validateAdditionalProwConfigIsInOrgRepoDirectoryStructure(filesystem fs.FS, supplementalProwConfigDirs, supplementalPluginsConfigDirs []string, supplementalProwConfigsFileNameSuffix, supplementalPluginsConfigFileNameSuffix string) error {
	var errs []error

	for _, supplementalProwConfigDir := range supplementalPluginsConfigDirs {
		if err := validateAdditionalConfigIsInOrgRepoDirectoryStructure(supplementalProwConfigDir, filesystem, func() hierarchicalConfig { return &config.Config{} }, supplementalProwConfigsFileNameSuffix); err != nil {
			errs = append(errs, err)
		}
	}
	for _, supplementalPluginsConfigDir := range supplementalPluginsConfigDirs {
		if err := validateAdditionalConfigIsInOrgRepoDirectoryStructure(supplementalPluginsConfigDir, filesystem, func() hierarchicalConfig { return &plugins.Configuration{} }, supplementalPluginsConfigFileNameSuffix); err != nil {
			errs = append(errs, err)
		}
	}

	return utilerrors.NewAggregate(errs)
}

func validateAdditionalConfigIsInOrgRepoDirectoryStructure(root string, filesystem fs.FS, target func() hierarchicalConfig, filesuffix string) error {
	var errs []error
	errs = append(errs, fs.WalkDir(filesystem, root, func(path string, d fs.DirEntry, err error) error {
		if err != nil {
			errs = append(errs, fmt.Errorf("error when walking: %w", err))
			return nil
		}
		// Kubernetes configmap mounts create symlinks for the configmap keys that point to files prefixed with '..'.
		// This allows it to do  atomic changes by changing the symlink to a new target when the configmap content changes.
		// This means that we should ignore the '..'-prefixed files, otherwise we might end up reading a half-written file and will
		// get duplicate data.
		if strings.HasPrefix(d.Name(), "..") {
			if d.IsDir() {
				return fs.SkipDir
			}
			return nil
		}

		fs.ReadFile(filesystem, path)

		if d.IsDir() || !strings.HasSuffix(path, filesuffix) {
			return nil
		}

		pathWithoutRoot := strings.TrimPrefix(path, root)
		pathWithoutRoot = strings.TrimPrefix(pathWithoutRoot, "/")

		pathElements := strings.Split(pathWithoutRoot, "/")
		nestingDepth := len(pathElements) - 1

		var isOrgConfig, isRepoConfig bool
		switch nestingDepth {
		case 0:
			// Global config, might contain anything or not even be a Prow config
			return nil
		case 1:
			isOrgConfig = true
		case 2:
			isRepoConfig = true
		default:
			errs = append(errs, fmt.Errorf("config %s is at an invalid location. All configs must be below %s. If they are org-specific, they must be in a folder named like the org. If they are repo-specific, they must be in a folder named like the repo below a folder named like the org.", path, root))
			return nil
		}

		cfg := target()
		isGlobal, targetedOrgs, targetedRepos, err := getSupplementalConfigScope(path, filesystem, cfg)
		if err != nil {
			errs = append(errs, err)
			return nil
		}

		if isOrgConfig {
			expectedTargetOrg := pathElements[0]
			if !isGlobal && len(targetedOrgs) == 1 && targetedOrgs.Has(expectedTargetOrg) && len(targetedRepos) == 0 {
				return nil
			}
			errMsg := fmt.Sprintf("config %s is invalid: Must contain only config for org %s, but", path, expectedTargetOrg)
			var needsAnd bool
			if isGlobal {
				errMsg += " contains global config"
				needsAnd = true
			}
			for _, org := range targetedOrgs.Delete(expectedTargetOrg).List() {
				errMsg += prefixWithAndIfNeeded(fmt.Sprintf(" contains config for org %s", org), needsAnd)
				needsAnd = true
			}
			for _, repo := range targetedRepos.List() {
				errMsg += prefixWithAndIfNeeded(fmt.Sprintf(" contains config for repo %s", repo), needsAnd)
				needsAnd = true
			}
			errs = append(errs, errors.New(errMsg))
			return nil
		}

		if isRepoConfig {
			expectedTargetRepo := pathElements[0] + "/" + pathElements[1]
			if !isGlobal && len(targetedOrgs) == 0 && len(targetedRepos) == 1 && targetedRepos.Has(expectedTargetRepo) {
				return nil
			}

			errMsg := fmt.Sprintf("config %s is invalid: Must only contain config for repo %s, but", path, expectedTargetRepo)
			var needsAnd bool
			if isGlobal {
				errMsg += " contains global config"
				needsAnd = true
			}
			for _, org := range targetedOrgs.List() {
				errMsg += prefixWithAndIfNeeded(fmt.Sprintf(" contains config for org %s", org), needsAnd)
				needsAnd = true
			}
			for _, repo := range targetedRepos.Delete(expectedTargetRepo).List() {
				errMsg += prefixWithAndIfNeeded(fmt.Sprintf(" contains config for repo %s", repo), needsAnd)
				needsAnd = true
			}
			errs = append(errs, errors.New(errMsg))
			return nil
		}

		// We should have left the function earlier. Error out so bugs in this code can not be abused.
		return fmt.Errorf("BUG: You should never see this. Path: %s, isGlobal: %t, targetedOrgs: %v, targetedRepos: %v", path, isGlobal, targetedOrgs, targetedRepos)
	}))

	return utilerrors.NewAggregate(errs)
}

func validateUnmanagedBranchprotectionConfigDoesntHaveSubconfig(bp config.BranchProtection) error {
	var errs []error
	if bp.Unmanaged != nil && *bp.Unmanaged {
		if doesUnmanagedBranchprotectionPolicyHaveSettings(bp.Policy) {
			errs = append(errs, errors.New("branch protection is globally set to unmanaged, but has configuration"))
		}
		for org := range bp.Orgs {
			errs = append(errs, fmt.Errorf("branch protection config is globally set to unmanaged but has configuration for org %s", org))
		}
	}
	for orgName, orgConfig := range bp.Orgs {
		if orgConfig.Unmanaged != nil && *orgConfig.Unmanaged {
			if doesUnmanagedBranchprotectionPolicyHaveSettings(orgConfig.Policy) {
				errs = append(errs, fmt.Errorf("branch protection config for org %s is set to unmanaged, but it defines settings", orgName))
			}
			for repo := range orgConfig.Repos {
				errs = append(errs, fmt.Errorf("branch protection config for repo %s/%s is defined, but branch protection is unmanaged for org %s", orgName, repo, orgName))
			}
		}

		for repoName, repoConfig := range orgConfig.Repos {
			if repoConfig.Unmanaged != nil && *repoConfig.Unmanaged {
				if doesUnmanagedBranchprotectionPolicyHaveSettings(repoConfig.Policy) {
					errs = append(errs, fmt.Errorf("branch protection config for repo %s/%s is set to unmanaged, but it defines settings", orgName, repoName))
				}

				for branchName := range repoConfig.Branches {
					errs = append(errs, fmt.Errorf("branch protection for repo %s/%s is set to unmanaged, but it defines settings for branch %s", orgName, repoName, branchName))
				}

			}

			for branchName, branchConfig := range repoConfig.Branches {
				if branchConfig.Unmanaged != nil && *branchConfig.Unmanaged && doesUnmanagedBranchprotectionPolicyHaveSettings(branchConfig.Policy) {
					errs = append(errs, fmt.Errorf("branch protection config for branch %s in repo %s/%s is set to unmanaged but defines settings", branchName, orgName, repoName))
				}
			}
		}
	}

	return utilerrors.NewAggregate(errs)
}

func doesUnmanagedBranchprotectionPolicyHaveSettings(p config.Policy) bool {
	emptyRef := config.Policy{Unmanaged: p.Unmanaged}
	return !reflect.DeepEqual(p, emptyRef)
}

func prefixWithAndIfNeeded(s string, needsAnd bool) string {
	if needsAnd {
		return " and" + s
	}
	return s
}

type hierarchicalConfig interface {
	HasConfigFor() (bool, sets.String, sets.String)
}

func getSupplementalConfigScope(path string, filesystem fs.FS, cfg hierarchicalConfig) (global bool, orgs sets.String, repos sets.String, err error) {
	data, err := fs.ReadFile(filesystem, path)
	if err != nil {
		return false, nil, nil, fmt.Errorf("failed to read %s: %w", path, err)
	}
	if err := yaml.Unmarshal(data, cfg); err != nil {
		return false, nil, nil, fmt.Errorf("failed to unmarshal %s into %T: %w", path, cfg, err)
	}

	global, orgs, repos = cfg.HasConfigFor()
	return global, orgs, repos, nil
}


text:
class ShortBitIteratorTest : public ::testing::Test {
};

TEST_F(ShortBitIteratorTest, translates_0) {
    ShortBitIterator bit_iterator(0x0000);

    ASSERT_TRUE(matches<16>("0000000000000000", bit_iterator));
    ASSERT_FALSE(bit_iterator.has_next());
}

TEST_F(ShortBitIteratorTest, translates_FFFF) {
    ShortBitIterator bit_iterator(0xFFFF);

    ASSERT_TRUE(matches<16>("1111111111111111", bit_iterator));
    ASSERT_FALSE(bit_iterator.has_next());
}

TEST_F(ShortBitIteratorTest, translates_9999) {
    ShortBitIterator bit_iterator(0x9999);

    ASSERT_TRUE(matches<16>("1001100110011001", bit_iterator));
    ASSERT_FALSE(bit_iterator.has_next());
}

TEST_F(ShortBitIteratorTest, translates_1234) {
    ShortBitIterator bit_iterator(0x1234);

    ASSERT_TRUE(matches<16>("0001001000110100", bit_iterator));
    ASSERT_FALSE(bit_iterator.has_next());
}


text:
package io.github.suzp1984.rx.demos;

/**
 * Created by jacobsu on 3/23/16.
 */
public class DemoRunner implements IRxRunner {
    public void run() {
        System.out.println("Demo Runner");
    }
}


text:
sudo apt install -y wget

# import the repository signing key:
wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -

# add repository contents to your system:
RELEASE=$(lsb_release -cs)
echo "deb http://apt.postgresql.org/pub/repos/apt/ ${RELEASE}"-pgdg main | sudo tee  /etc/apt/sources.list.d/pgdg.list

# install and launch the postgresql service:
sudo apt update
sudo apt -y install postgresql-11
sudo service postgresql start


text:
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Example</title>
  <script src="../../dist/modular/js/core.js" type="text/javascript"></script>
  <link href="../../dist/modular/css/core.css" rel="stylesheet" type="text/css">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet" type="text/css">
  <link href="../../dist/modular/css/datepicker.css" rel="stylesheet" type="text/css">
  <script src="../../dist/modular/js/datepicker.js"></script>
</head>
<body style="padding: 8px;">
 <input id="datepicker" width="234" />
 <script>
     new GijgoDatePicker(document.getElementById('datepicker'), {
         uiLibrary: 'bootstrap4',
         icons: {
             rightIcon: '<i class="material-icons">date_range</i>'
         }
     });
 </script>
</body>
</html>


text:
package nl.weeaboo.styledtext.layout;

import nl.weeaboo.styledtext.TextStyle;

final class BasicFontMetrics extends AbstractFontMetrics {

    public BasicFontMetrics(float spaceWidth, float lineHeight) {
        super(spaceWidth, lineHeight);
    }

    @Override
    public ILayoutElement layoutText(CharSequence str, TextStyle style, int bidiLevel,
            LayoutParameters params) {

        return new BasicTextElement(str, style, bidiLevel);
    }

}


text:
ALTER TABLE action_edge_parameter ADD COLUMN advanced BOOLEAN NOT NULL DEFAULT false;
ALTER TABLE action_parameter ADD COLUMN advanced BOOLEAN NOT NULL DEFAULT false;
update action_parameter set advanced = false;
update action_edge_parameter set advanced = false;

-- +migrate Down

ALTER TABLE action_edge_parameter DROP COLUMN advanced;
ALTER TABLE action_parameter DROP COLUMN advanced;


text:
function [ CXX, CXY,W,rates,obs_count] = GetStat(sampled_spikes,observations,glasso,restricted_penalty,pos_def,sparsity,true_W)
% inputs:
% sampled_spikes -NxT observed spikes (with zeros in unobsereved samples)
% observations - NxT matrix of which timebins were observed
% glasso - flag that indicate whether or not use glasso
% restricted_penalty - flag that indicates whether or not to use a restricted l1 penality in glasso (only on parts of the inv_COV matrix)
% pos_def - restict Covariance matrix to be positive semi definite
% sparsity-  the average nnz in the inv(CXX) matrix.  if empty, test using true matrix
% true_W - for  testing purposes

% outputs:
% Cxx  - NxN matrix of estimated spike covariance at a single timestep
% Cxy - NxN matrix of estimated spike cross-covariance  between two adjacent timesteps
% W - infered weights matrix
% rates - mean firing rates
% obs_count - observation count for each neuron

% internal parameters
Tol=1e-6; %numerical tolerance for glasso
msg=1; %verbosity of glasso algorithm
maxIter=100;  %glasso max iterations
Tol_sparse=1e-2; % tolerance for sparsity of W
thresh=inf; %max size of spikes array for which we use effiecient computation of sufficient statistics

[N, T] = size(sampled_spikes);

%initialize the sufficient statistics arrays
observations=double(observations);
if N*T<thresh
    XX=sampled_spikes*sampled_spikes';
    XXn=observations*observations';
    XY=sampled_spikes(:,1:(end-1))*(sampled_spikes(:,2:end))';
    XYn=observations(:,1:(end-1))*(observations(:,2:end))';
else

    XX=zeros(N);
    XXn=zeros(N);
    XY=zeros(N);
    XYn=zeros(N);
    g = find(observations(:,1));
    sg = double(sampled_spikes(g,1));
    disp(['Gathering sufficient statistics...'])
    for tt = 2:T
        f = g;
        sf = sg;
        g = find(observations(:,tt));
        sg = double(sampled_spikes(g,tt));

        XX(f,f)=XX(f,f)+sf*sf';
        XXn(f,f)=XXn(f,f)+1;

        XY(f,g)=XY(f,g)+sf*sg';
        XYn(f,g)=XYn(f,g)+1;
        if ~mod(tt,T/10)
            disp([num2str(100*tt/T,2) '%'])
        end
    end
end

mY=full(sum(sampled_spikes,2));
mYn=sum(observations,2);

%% Calculate sufficient stats

rates=mY./(mYn+eps); %estimate the mean firing rates
CXX=full(XX)./(XXn+eps)-rates*rates'; %estimate the covariance (not including stim terms for now)
% CXX((XXn<10))=0;%set elements to zero that haven't been observed sufficiently
CXY=full(XY)./(XYn+eps)-rates*rates'; %estimate cross-covariance
% CXY((XYn<10))=0;
COV = [CXX CXY; CXY' CXX];

if(any(eig(COV)<0))
    disp('COV is not positive semidefinite;')
    if pos_def %positive semidefinite projection, so we won't have problems with glasso
        disp('correcting...');
        [v,d]=eig(COV);
        X0=v*spdiags(max(diag(d),0),0,2*N,2*N)*v';
        COV=X0;
    end
end

inv_COV=COV\eye(2*N);

%% Use glasso to sparsify stats
if glasso==1
    disp('starting glasso...')

    addpath(fullfile('EstimateStatistics','QUIC')) %mex files for QUIC glasso implementation

    lambda_high=1; %maximum bound for lambda
    lambda_low=1e-4;  %minimum bound for lambda
    if restricted_penalty %more accurate, but much slower
        regularization_mat=ones(2*N);
        regularization_mat(1:N,1:N)=0; %remove penalty with upper left block
        regularization_mat(eye(2*N)>0.5)=0;  %remove penalty from diagonal
        regularization_mat([zeros(N), eye(N); zeros(N), zeros(N)]>0.5)=0;  %remove penalty from diagonal of upper right block
        regularization_mat([zeros(N), zeros(N); eye(N), zeros(N)]>0.5)=0;  %remove penalty from diagonal of lower left block
    else
         regularization_mat=1;
    end

    if isempty(sparsity) % in case we "cheat" choouse optimal lambda
        func= @(x) OptFun( x,COV,regularization_mat, Tol, msg, maxIter ,true_W);
        lambda_opt=fminbnd(func,lambda_low,lambda_high);
        lambda_mat=lambda_opt*regularization_mat;
        [inv_COV_res, COV_res, opt, cputime, iter, dGap] = QUIC('default', COV, lambda_mat, Tol, msg, maxIter);

    else %set lambda according to estimated sparsity level of W, using binary search
        loop_cond=1;  %flag for while llop
        flag_first=1; % flag for first iteration of loop

        while  loop_cond
            if sparsity==1
                lambda=0;
            else
                lambda=(lambda_high+lambda_low)/2;
            end
                lambda_mat=lambda*regularization_mat;
                if flag_first
                    [inv_COV_res, COV_res, opt, cputime, iter, dGap] = QUIC('default', COV, lambda_mat, Tol, msg, maxIter);
                else %use warm start
                    flag_first=0;
                    [inv_COV_res, COV_res, opt, cputime, iter, dGap] = QUIC('default', COV, lambda_mat, Tol, msg, maxIter,inv_COV_res, COV_res);
                end

                % W block
                temp=inv_COV_res((N+1):end,1:N);
                temp(eye(N)>0.5)=0;

                sparsity_measure=mean(~~temp(:));
                cond=sparsity_measure<sparsity;
                loop_cond=(abs(sparsity_measure-sparsity)/sparsity >  Tol_sparse);
                 if sparsity==1
                    loop_cond=0;
                 end

            if cond
                lambda_high=lambda
            else
                lambda_low=lambda
            end
        end
    end

        CXY = COV_res(1:N,N+1:end);%%%%%
        CXX = COV_res(1:N,1:N);%%%%%
        W=-inv_COV_res((N+1):end,1:N);
    else
        CXY = COV(1:N,N+1:end);%%%%%
        CXX = COV(1:N,1:N);%%%%%
        W=-inv_COV((N+1):end,1:N); % W estimate without glasso
end

obs_count=mYn;
end


text:
/*
 *
 *  Somado (System Optymalizacji Małych Dostaw)
 *  Optymalizacja dostaw towarów, dane OSM, problem VRP
 *
 *  Autor: Maciej Kawecki 2016 (praca inż. EE PW)
 *
 */
package spatial_vrp;

import java.util.LinkedList;
import java.util.List;

import org.jxmapviewer.viewer.GeoPosition;

import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;

import datamodel.IAddressPoint;
import datamodel.Order;

/**
 *
 * Szablon obiektu reprezentującego pojedynczy punkt odbioru towaru na wyznaczonej trasie
 * dla planu dostawy
 *
 * @author Maciej Kawecki
 * @version 1.0
 *
 */
public class RoutePoint implements IAddressPoint {

    /** Identyfikator punktu trasy */
    private Integer id;
    /** Odległość do tego punktu */
    private double distance;
    /** Szacowany czas przejazdu [w sek] części trasy do tego punktu */
    private double time;
    /** Zrealizowane w tym punkcie zamówienie */
    private Order order;
    /** Geometria odcinka od poprzedniego punktu */
    private Geometry geometry;
    /** Dodatkowa geometria (odcinek drogi od lub do najbliższego węzła) */
    private Geometry additionalGeometry;
    /** Etykieta punktu na mapie */
    private String label;

    /**
     * Konstruktor
     * @param id Identyfikator punktu trasy
     * @param distance Odległość do tego punktu
     * @param time Szacowany czas przejazdu [w sek] części trasy do tego punktu
     * @param order Zrealizowane w tym punkcie zamówienie
     * @param geometry Geometria odcinka od poprzedniego punktu
     * @param additionalGeometry Dodatkowa geometria (odcinek drogi od najbliższego węzła)
     */
    public RoutePoint(Integer id, double distance, double time, Order order, Geometry geometry,
            Geometry additionalGeometry) {

      this.id = id;
      this.distance = distance;
      this.time = time;
      this.order = order;
      this.geometry = geometry;
      this.additionalGeometry = additionalGeometry;

    }

    /**
     * Konstruktor kopiujący obiekt
     * @param point Kopiowany obiekt
     */
    public RoutePoint(RoutePoint point) {

      this.id = point.id;
      this.distance = point.distance;
      this.time = point.time;
      this.order = point.order;
      this.geometry = point.geometry;
      this.additionalGeometry = point.additionalGeometry;
      this.label = point.label;

    }

    @Override
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public double getTime() {
        return time;
    }

    public void setTime(double time) {
        this.time = time;
    }

    public Order getOrder() {
        return order;
    }

    public void setOrder(Order order) {
        this.order = order;
    }

    public Geometry getGeometry() {
        return geometry;
    }

    public void setGeometry(Geometry geometry) {
        this.geometry = geometry;
    }

    public double getDistance() {
        return distance;
    }

    public void setDistance(double distance) {
        this.distance = distance;
    }

    public Geometry getAdditionalGeometry() {
        return additionalGeometry;
    }

    public void setAdditionalGeometry(Geometry additionalGeometry) {
        this.additionalGeometry = additionalGeometry;
    }

    public String getLabel() {
        return label;
    }

    public void setLabel(String label) {
        this.label = label;
    }

  /**
   * Konwersja trasy z geometrii na listę koordynat
   * @param geometry Geometria trasy
   * @return Lista koordynat
   */
  public static List<GeoPosition> getCoordsList(Geometry geometry) {

    List<GeoPosition> route = new LinkedList<>();
    if (geometry == null) return route;

    for (int i=0; i < geometry.getNumGeometries(); i++){

      Geometry lineGeometry = geometry.getGeometryN(i);
      for (Coordinate coordinate : lineGeometry.getCoordinates()) {

         route.add(new GeoPosition(coordinate.y, coordinate.x));

      }
    }

    return route;

  }

  @Override
  public List<GeoPosition> getAdditionalGeometryCoords() {
	return getCoordsList(additionalGeometry);
  }

  @Override
  public List<GeoPosition> getGeometryCoords() {
	return getCoordsList(geometry);
  }

  @Override
  public double getCustomerLatitude() {
   return order != null ? order.getCustomer().getLatitude() : -1.0;
  }

  @Override
  public double getCustomerLongitude() {
	return order != null ? order.getCustomer().getLongitude() : -1.0;
  }

  @Override
  public String getCustomerLabel() {
	return label;
  }

  @Override
  public boolean isOnRoute() {
	return order != null;
  }

}


text:
package game.components;

import game.GameWorld;

/**
 * Updateable component interface
 */
public interface IUpdateableComponent
{
	/**
	 * Updates component
	 * @param world GameWorld to which the component belongs to
	 */
	public void update(GameWorld world);
}