text:
package mybase

import (
	"bufio"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
	"reflect"
	"sort"
	"strings"
	"unicode"
)

// Section represents a labeled section of an option file. Option values that
// precede any named section are still associated with a Section object, but
// with a Name of "".
type Section struct {
	Name   string
	Values map[string]string  // mapping of option name => value as string
	opts   map[string]*Option // mapping of option name => option definition
}

// File represents a form of ini-style option file. Lines can contain
// [sections], option=value, option without value (usually for bools), or
// comments.
type File struct {
	Dir                  string
	Name                 string
	IgnoreUnknownOptions bool
	sections             []*Section
	sectionIndex         map[string]*Section
	read                 bool
	parsed               bool
	contents             string
	selected             []string
	ignoredOptionNames   map[string]bool
}

// NewFile returns a value representing an option file. The arg(s) will be
// joined to create a single path, so it does not matter if the path is provided
// in a way that separates the dir from the base filename or not.
func NewFile(paths ...string) *File {
	pathAndName := filepath.Join(paths...)
	cleanPath, err := filepath.Abs(filepath.Clean(pathAndName))
	if err == nil {
		pathAndName = cleanPath
	}

	defaultSection := &Section{
		Name:   "",
		Values: make(map[string]string),
		opts:   make(map[string]*Option),
	}

	return &File{
		Dir:                filepath.Dir(pathAndName),
		Name:               filepath.Base(pathAndName),
		sections:           []*Section{defaultSection},
		sectionIndex:       map[string]*Section{"": defaultSection},
		ignoredOptionNames: make(map[string]bool),
	}
}

// Exists returns true if the file exists and is visible to the current user.
func (f *File) Exists() bool {
	_, err := os.Stat(f.Path())
	return (err == nil)
}

// Path returns the file's full absolute path with filename.
func (f *File) Path() string {
	return filepath.Join(f.Dir, f.Name)
}

func (f *File) String() string {
	return f.Path()
}

// Write writes out the file's contents to disk. If overwrite=false and the
// file already exists, an error will be returned.
// Note that if overwrite=true and the file already exists, any comments
// and extra whitespace in the file will be lost upon re-writing. All option
// names and values will be normalized in the rewritten file. Any "loose-"
// prefix option names that did not exist will not be written, and any that
// did exist will have their "loose-" prefix stripped. These shortcomings will
// be fixed in a future release.
func (f *File) Write(overwrite bool) error {
	lines := make([]string, 0)
	for n, section := range f.sections {
		if section.Name != "" {
			lines = append(lines, fmt.Sprintf("[%s]", section.Name))
		}

		ks := make([]string, 0, len(section.Values))
		for k := range section.Values {
			ks = append(ks, k)
		}
		sort.Strings(ks)
		for _, k := range ks {
			// Note: section.opts[k] will be nil if the option value came from
			// File.SetOptionValue() and was not previously set! In this case we always
			// treat the opt as stringy, to avoid converting some-int=0 to skip-some-int
			optionIsBoolean := (section.opts[k] != nil && section.opts[k].Type == OptionTypeBool)
			val := section.Values[k]
			if (optionIsBoolean && !BoolValue(val)) || val == "''" { // false-valued boolean, or explicitly-empty-string non-boolean
				lines = append(lines, fmt.Sprintf("skip-%s", k))
			} else if optionIsBoolean || val == "" { // true-valued boolean, or valueless (implying value-optional) non-boolean
				lines = append(lines, k)
			} else { // non-boolean with a value
				lines = append(lines, fmt.Sprintf("%s=%s", k, val))
			}
		}

		// Append a blank line after the section, unless it was the last one, or
		// it was the default section and had no values
		if n < len(f.sections)-1 && (section.Name != "" || len(section.Values) > 0) {
			lines = append(lines, "")
		}
	}

	if len(lines) == 0 {
		log.Printf("Skipping write to %s due to empty configuration", f.Path())
		return nil
	}
	f.contents = fmt.Sprintf("%s\n", strings.Join(lines, "\n"))
	f.read = true
	f.parsed = true

	flag := os.O_WRONLY | os.O_CREATE
	if overwrite {
		flag |= os.O_TRUNC
	} else {
		flag |= os.O_EXCL
	}
	osFile, err := os.OpenFile(f.Path(), flag, 0666)
	if err != nil {
		return err
	}
	n, err := osFile.Write([]byte(f.contents))
	if err == nil && n < len(f.contents) {
		err = io.ErrShortWrite
	}
	if err1 := osFile.Close(); err == nil {
		err = err1
	}
	return err
}

// Read loads the contents of the option file, but does not parse it.
func (f *File) Read() error {
	file, err := os.Open(f.Path())
	if err != nil {
		return err
	}
	defer file.Close()
	bytes, err := ioutil.ReadAll(file)
	if err != nil {
		return err
	}
	f.contents = string(bytes)
	f.read = true
	return nil
}

// Parse parses the file contents into a series of Sections. A Config object
// must be supplied so that the list of valid Options is known.
func (f *File) Parse(cfg *Config) error {
	if !f.read {
		if err := f.Read(); err != nil {
			return err
		}
	}

	section := f.sectionIndex[""]

	var lineNumber int
	contents := strings.TrimPrefix(f.contents, "\uFEFF") // strip utf8 BOM if present
	scanner := bufio.NewScanner(strings.NewReader(contents))
	for scanner.Scan() {
		line := scanner.Text()
		lineNumber++

		parsedLine, err := parseLine(line)
		if err != nil {
			return FileParseFormatError{
				Problem:    err.Error(),
				FilePath:   f.Path(),
				LineNumber: lineNumber,
			}
		}

		switch parsedLine.kind {
		case lineTypeSectionHeader:
			section = f.getOrCreateSection(parsedLine.sectionName)
		case lineTypeKeyOnly, lineTypeKeyValue:
			if f.ignoredOptionNames[parsedLine.key] {
				continue
			}
			opt := cfg.FindOption(parsedLine.key)
			if opt == nil {
				if parsedLine.isLoose || f.IgnoreUnknownOptions || cfg.LooseFileOptions {
					continue
				} else {
					return OptionNotDefinedError{parsedLine.key, fmt.Sprintf("%s line %d", f.Path(), lineNumber)}
				}
			}
			if parsedLine.kind == lineTypeKeyOnly {
				if opt.RequireValue {
					return OptionMissingValueError{opt.Name, fmt.Sprintf("%s line %d", f.Path(), lineNumber)}
				} else if opt.Type == OptionTypeBool {
					// For booleans, option without value indicates option is being enabled
					parsedLine.value = "1"
				}
			} else if parsedLine.value == "" && opt.Type == OptionTypeString {
				// Convert empty strings into quote-wrapped empty strings, so that callers
				// may differentiate between bare "foo" vs "foo=" if desired, by using
				// Config.GetRaw(). Meanwhile Config.Get and most other getters strip
				// surrounding quotes, so this does not break anything.
				parsedLine.value = "''"
			}
			section.Values[parsedLine.key] = parsedLine.value
			section.opts[parsedLine.key] = opt
		}
	}

	f.parsed = true
	f.selected = []string{""}
	return scanner.Err()
}

// UseSection changes which section(s) of the file are used when calling
// OptionValue. If multiple section names are supplied, multiple sections will
// be checked by OptionValue, with sections listed first taking precedence over
// subsequent ones.
// Note that the default nameless section "" (i.e. lines at the top of the file
// prior to a section header) is automatically appended to the end of the list.
// So this section is always checked, at lowest priority, need not be
// passed to this function.
func (f *File) UseSection(names ...string) error {
	notFound := make([]string, 0)
	already := make(map[string]bool, len(names))

	// This intentionally allocates a new []string for selected. This way, even
	// if there are other shallow copies of f, calling UseSection on one won't
	// affect the others.
	f.selected = make([]string, 0, len(names)+1)

	for _, name := range names {
		if already[name] {
			continue
		}
		already[name] = true
		if f.HasSection(name) {
			f.selected = append(f.selected, name)
		} else {
			notFound = append(notFound, name)
		}
	}
	if !already[""] {
		f.selected = append(names, "")
	}

	if len(notFound) == 0 {
		return nil
	}
	return fmt.Errorf("File %s missing section: %s", f.Path(), strings.Join(notFound, ", "))
}

// HasSection returns true if the file has a section with the supplied name.
func (f *File) HasSection(name string) bool {
	_, ok := f.sectionIndex[name]
	return ok
}

// SectionsWithOption returns a list of section names that set the supplied
// option name.
func (f *File) SectionsWithOption(optionName string) []string {
	result := make([]string, 0, len(f.sections))
	for _, section := range f.sections {
		if _, ok := section.Values[optionName]; ok {
			result = append(result, section.Name)
		}
	}
	return result
}

// SomeSectionHasOption returns true if at least one section sets the supplied
// option name.
func (f *File) SomeSectionHasOption(optionName string) bool {
	return len(f.SectionsWithOption(optionName)) > 0
}

// SectionValues returns a map of option name to raw option string values for
// the supplied section name. The returned map is a copy; modifying it will not
// affect the File.
func (f *File) SectionValues(name string) map[string]string {
	section := f.sectionIndex[name]
	if section == nil {
		return map[string]string{}
	}
	result := make(map[string]string, len(section.Values))
	for k, v := range section.Values {
		result[k] = v
	}
	return result
}

// OptionValue returns the value for the requested option from the option file.
// Only the previously-selected section(s) of the file will be used, or the
// default section "" if no section has been selected via UseSection.
// Panics if the file has not yet been parsed, as this would indicate a bug.
// This is satisfies the OptionValuer interface, allowing Files to be used as
// an option source in Config.
func (f *File) OptionValue(optionName string) (string, bool) {
	if !f.parsed {
		panic(fmt.Errorf("Call to OptionValue(\"%s\") on unparsed file %s", optionName, f.Path()))
	}
	for _, sectionName := range f.selected {
		section := f.sectionIndex[sectionName]
		if section == nil {
			continue
		}
		if value, ok := section.Values[optionName]; ok {
			return value, true
		}
	}
	return "", false
}

// SetOptionValue sets an option value in the named section. This is not
// persisted to the file until Write is called on the File. This is not
// guaranteed to affect any Config that is already using the File as a
// Source.
func (f *File) SetOptionValue(sectionName, optionName, value string) {
	section := f.getOrCreateSection(sectionName)
	section.Values[optionName] = value
}

// UnsetOptionValue removes an option value in the named section. This is not
// persisted to the file until Write is called on the File. This is not
// guaranteed to affect any Config that is already using the File as a
// Source.
func (f *File) UnsetOptionValue(sectionName, optionName string) {
	section := f.getOrCreateSection(sectionName)
	delete(section.Values, optionName)
}

// SameContents returns true if f and other have the same sections and values.
// Ordering, formatting, comments, filename, and directory do not affect the
// results of this comparison. Both files must be parsed by the caller prior
// to calling this method, otherwise this method panics to indicate programmer
// error.
// This method is primarily intended for unit testing purposes.
func (f *File) SameContents(other *File) bool {
	if !f.parsed || !other.parsed {
		panic(errors.New("File.SameContents called on a file that has not yet been parsed"))
	}
	if len(f.sectionIndex) != len(other.sectionIndex) {
		return false
	}
	for name := range f.sectionIndex {
		a := f.sectionIndex[name]
		b, ok := other.sectionIndex[name]
		if !ok || a.Name != b.Name {
			return false
		}
		if !reflect.DeepEqual(a.Values, b.Values) {
			return false
		}
	}
	return true
}

// IgnoreOptions causes the supplied option names to be ignored by a subsequent
// call to Parse. The supplied option names do not need to exist as valid
// options.
// Note that if the file is later re-written, ignored options will be stripped
// from the rewritten version.
// Panics if the file has already been parsed, as this would indicate a bug.
func (f *File) IgnoreOptions(names ...string) {
	if f.parsed {
		panic(errors.New("File.IgnoreOptions called on a file that has already been parsed"))
	}
	for _, name := range names {
		f.ignoredOptionNames[name] = true
	}
}

func (f *File) getOrCreateSection(name string) *Section {
	if s, exists := f.sectionIndex[name]; exists {
		return s
	}
	s := &Section{
		Name:   name,
		Values: make(map[string]string),
		opts:   make(map[string]*Option),
	}
	f.sections = append(f.sections, s)
	f.sectionIndex[name] = s
	return s
}

type lineType int

const (
	lineTypeBlank lineType = iota
	lineTypeComment
	lineTypeSectionHeader
	lineTypeKeyOnly
	lineTypeKeyValue
)

type parsedLine struct {
	sectionName string
	key         string
	value       string
	comment     string
	kind        lineType
	isLoose     bool
}

// parseLine parses a file line into its components
func parseLine(line string) (*parsedLine, error) {
	line = strings.TrimLeftFunc(line, unicode.IsSpace)
	result := new(parsedLine)

	if line == "" {
		result.kind = lineTypeBlank
		return result, nil
	}
	if line[0] == ';' || line[0] == '#' {
		result.kind = lineTypeComment
		result.comment = line[1:]
		return result, nil
	}

	if line[0] == '[' {
		endIndex := strings.Index(line, "]")
		hashIndex := strings.Index(line, "#")
		if endIndex == -1 || (hashIndex > -1 && hashIndex < endIndex) {
			return nil, errors.New("unterminated section name")
		}
		if endIndex < len(line)-1 {
			var after string
			if hashIndex > -1 {
				after = line[endIndex+1 : hashIndex]
			} else {
				after = line[endIndex+1:]
			}
			if len(strings.TrimSpace(after)) > 0 {
				return nil, errors.New("extra characters after section name")
			}
		}
		result.kind = lineTypeSectionHeader
		result.sectionName = line[1:endIndex]
		if hashIndex > -1 {
			result.comment = line[hashIndex+1:]
		}
		return result, nil
	}

	// If we get here, it's one of the key/value types
	var inValue, escapeNext bool
	var inQuote rune

	// Parse out any inline comment, being careful to still allow escaped hashes or
	// hashes inside of quoted values
	for n, c := range line {
		if escapeNext {
			escapeNext = false
			continue
		}
		if c == '#' && inQuote == 0 {
			result.comment = line[n+1:]
			line = line[0:n]
			break
		}
		if !inValue {
			switch c {
			case '=':
				inValue = true
			case '\'', '"', '`', '\\':
				return nil, fmt.Errorf("Illegal character %c in option name", c)
			}
			continue
		}
		switch c {
		case '\'', '"', '`':
			if c == inQuote {
				inQuote = 0
			} else if inQuote == 0 {
				inQuote = c
			}
		case '\\':
			escapeNext = true
		}
	}

	if inQuote != 0 {
		return nil, errors.New("Quoted value has no terminating quote")
	}
	if escapeNext {
		return nil, errors.New("Value ends in a single backslash")
	}

	var hasValue bool
	result.key, result.value, hasValue, result.isLoose = NormalizeOptionToken(line)
	if hasValue {
		result.kind = lineTypeKeyValue
	} else {
		result.kind = lineTypeKeyOnly
	}
	return result, nil
}

// FileParseFormatError is an error returned when File.Parse encounters a
// problem with the formatting of a file (separate from an unknown option or a
// lack of a required value for an option, which are handled by other types)
type FileParseFormatError struct {
	Problem    string
	FilePath   string
	LineNumber int
}

// Error satisfies golang's error interface.
func (fpf FileParseFormatError) Error() string {
	return fmt.Sprintf("Parse error in %s line %d: %s", fpf.FilePath, fpf.LineNumber, fpf.Problem)
}


text:
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using EaServices.Doors.ReqIfs;
using hoLinqToSql.LinqUtils;
using LinqToDB.DataProvider;

namespace EaServices.AddInSearch
{
    /// <summary>
    /// Add-In Searches
    /// </summary>
    public class AddInSearches
    {
        // Dictionary of all TaggedValues of a search
        private static Dictionary<string, string> _tv = new Dictionary<string, string>();

        ///  <summary>
        ///  Add-In simple Search to find nested Elements for:
        ///  -  Selected
        ///  -- Package
        ///  -- Element
        ///  - Comma separated GUID list of Packages or Elements in 'Search Term'
        ///
        ///   It outputs:
        ///  - All elements in it's hierarchical structure
        ///  - Tagged Values
        ///
        ///
        ///  How it's works:
        ///  1. Create a Table and fill it with your code
        ///  2. Adapt LINQ to output the table (powerful)
        ///     -- Where to select only certain rows
        ///     -- Order By to order the result set
        ///     -- Grouping
        ///     -- Filter
        ///     -- JOIN
        ///     -- etc.
        ///  3. Deploy and test
        ///  </summary>
        ///  <param name="repository"></param>
        ///  <param name="searchText"></param>
        /// <returns></returns>
        public static string SearchObjectsNestedUsingEaApi(EA.Repository repository, string searchText)
        {
            // 1. Collect data into a data table
            DataTable dt = AddinSearchObjectsNestedInitTableUsingEaApi(repository, searchText);
            // 2. Order, Filter, Join, Format to XML
            return AddinSearchObjectsNestedMakeXml(dt);
        }

        /// <summary>
        /// Search objects nested optimized
        /// </summary>
        /// <param name="repository"></param>
        /// <param name="searchText"></param>
        /// <returns></returns>
        public static string SearchObjectsNested(EA.Repository repository, string searchText)
        {
            // 1. Collect data into a data table
            DataTable dt = AddinSearchObjectsNestedInitTable(repository, searchText);
            // 2. Order, Filter, Join, Format to XML
            return AddinSearchObjectsNestedMakeXml(dt);
        }

        /// <summary>
        /// Query to make EA xml from a Data Table by using MakeXml.
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        private static string AddinSearchObjectsNestedMakeXml(DataTable dt)
        {
            try
            {
                // Make a LINQ query (WHERE, JOIN, ORDER,)
                EnumerableRowCollection<DataRow> rows = from row in dt.AsEnumerable()
                                                        select row;

                return Xml.MakeXml(dt, rows);
            }
            catch (Exception e)
            {
                MessageBox.Show($@"{e}", @"Error LINQ query Test query to show Table to EA xml format");
                return "";

            }
        }
        /// <summary>
        /// InitializeTable for search results using EA API
        /// </summary>
        /// <param name="rep"></param>
        /// <param name="searchText">Optional: List of packages, EA elements as a comma separated list</param>
        /// <returns></returns>
        private static DataTable AddinSearchObjectsNestedInitTableUsingEaApi(EA.Repository rep, string searchText)
        {
            _tv = new Dictionary<string, string>();
            DataTable dt = new DataTable();
            dt.Columns.Add("CLASSGUID", typeof(string));
            dt.Columns.Add("CLASSTYPE", typeof(string));
            dt.Columns.Add("Name", typeof(string));
            dt.Columns.Add("Alias", typeof(string));
            dt.Columns.Add("Note", typeof(string));
            int level = 0;
            if (searchText.Trim().StartsWith("{"))
            {
                // handle string
                string[] earchTextArr = GetEaFromCommaSeparatedList(searchText);
                foreach (var txt in earchTextArr)
                {
                    EA.Element el = rep.GetElementByGuid(txt);
                    if (el == null) continue;
                    if (el.Type != "Package") NestedElementsRecursiveUsingEaApi(dt, el, level);
                    if (el.Type == "Package") NestedPackageElementsRecursiveUsingEaApi(dt, rep.GetPackageByGuid(txt), level);
                }

                EA.Package pkg = rep.GetPackageByGuid(searchText);
                if (pkg != null)
                {
                    NestedPackageElementsRecursiveUsingEaApi(dt, pkg, level);
                }
            }
            else
            {
                // handle context element
                rep.GetContextItem(out var item);
                if (item is EA.Element element) NestedElementsRecursiveUsingEaApi(dt, element, level);
                if (item is EA.Package package) NestedPackageElementsRecursiveUsingEaApi(dt, package, level);
            }
            return dt;
        }

        /// <summary>
        /// InitializeTable for search results using EA API
        /// </summary>
        /// <param name="rep"></param>
        /// <param name="searchText">Optional: List of packages, EA elements as a comma separated list</param>
        /// <returns></returns>
        private static DataTable AddinSearchObjectsNestedInitTable(EA.Repository rep,  string searchText)
        {
            // get connection string of repository
            string connectionString = LinqUtil.GetConnectionString(rep, out var provider);

            _tv = new Dictionary<string, string>();
            DataTable dt = new DataTable();
            dt.Columns.Add("CLASSGUID", typeof(string));
            dt.Columns.Add("CLASSTYPE", typeof(string));
            dt.Columns.Add("Name", typeof(string));
            dt.Columns.Add("Alias", typeof(string));
            dt.Columns.Add("Note", typeof(string));
            if (searchText.Trim().StartsWith("{"))
            {
                // handle string
                string[] guidList = GetEaFromCommaSeparatedList(searchText);
                foreach (var guid in guidList)
                {
                    EA.Element el = rep.GetElementByGuid(guid);
                    if (el == null) continue;
                    if (el.Type != "Package")
                    {
                        NestedElementsRecursive(connectionString, provider, dt, rep.GetPackageByID(el.PackageID).PackageGUID, el.ElementID);
                    }
                    if (el.Type == "Package") NestedPackageElementsRecursive(connectionString, provider, dt, guid);
                }

                EA.Package pkg = rep.GetPackageByGuid(searchText);
                if (pkg != null)
                {
                    NestedPackageElementsRecursive(connectionString, provider, dt, pkg.PackageGUID);
                }
            }
            else
            {
                // handle context element
                rep.GetContextItem(out var item);
                if (item is EA.Element element) NestedElementsRecursive(connectionString, provider,  dt, rep.GetPackageByID(element.PackageID).PackageGUID, element.ElementID);
                if (item is EA.Package package) NestedPackageElementsRecursive(connectionString, provider, dt, package.PackageGUID);
            }
            return dt;
        }

        /// <summary>
        /// Make a Data Table from Package Elements recursive using EA API
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="pkg"></param>
        /// <param name="level"></param>
        private static void NestedPackageElementsRecursiveUsingEaApi(DataTable dt, EA.Package pkg, int level)
        {
            foreach (EA.Element el in pkg.Elements)
            {
                NestedElementsRecursiveUsingEaApi(dt, el, level);
            }

        }

        /// <summary>
        /// Make a Data Table from Package Elements recursive using EA API
        /// </summary>
        /// <param name="provider"></param>
        /// <param name="dt"></param>
        /// <param name="guid"></param>
        /// <param name="connectionString"></param>
        private static void NestedPackageElementsRecursive(string connectionString, IDataProvider provider, DataTable dt, string guid)
        {
            Dictionary<int, NestedObject> nestedElements = GetPackageNestedElements(connectionString, provider, guid);
            AddElementsToTable( nestedElements, dt, 0, 0);

        }

        /// <summary>
        /// Get Dictionary of nested elements for a package GUID.
        /// </summary>
        /// <param name="provider"></param>
        /// <param name="guid"></param>
        /// <param name="connectionString"></param>
        /// <returns></returns>
        private static Dictionary<int, NestedObject> GetPackageNestedElements(string connectionString, IDataProvider provider, string guid)
        {

            using (var db = new DataModels.EaDataModel(provider, connectionString))
            {
                // optimize Access to database, without this the query takes > 30 seconds
                // Split query and group into two queries.
                // - The first query make the db acccess and writes to array
                // - The second query makes the grouping
               var reqTvAll0 = (from r in db.t_object
                                join tv2 in db.t_objectproperties on r.Object_ID equals tv2.Object_ID into tv1 from tv in tv1.DefaultIfEmpty()
                                join pkg in db.t_package on r.Package_ID equals pkg.Package_ID
                                where pkg.ea_guid == guid
                                orderby r.Object_ID, tv.Property
                                select new {r, tv}).ToArray();

                return  (from r in reqTvAll0
                    group r by new { r.r.Object_ID, r.r.ParentID, r.r.TPos, r.r.Name, r.r.Alias, r.r.Note, r.r.ea_guid, r.r.Object_Type } into grp1
                    select new
                    {
                        Id = grp1.Key.Object_ID,
                        Property = new NestedObject(
                            grp1.Key.ParentID??0,
                            grp1.Key.TPos??0,
                            grp1.Key.Name??"",
                            grp1.Key.Alias??"",
                            grp1.Key.Note??"",
                            grp1.Key.ea_guid??"",
                            grp1.Key.Object_Type??"",
                            // Tagged Value
                            grp1.Select(g => new Tv(
                                g?.tv?.Property??"",
                                ((g?.tv?.Value ?? "") == "<memo>") ? g?.tv?.Notes??"" : g?.tv?.Value??"")
                            ).ToList())
                    }).ToDictionary(ta => ta.Id, ta => ta.Property);
            }

        }

        /// <summary>
        /// Get Dictionary of nested elements for a package GUID.
        /// </summary>
        /// <param name="provider"></param>
        /// <param name="connectionString"></param>
        /// <returns></returns>
        private static Dictionary<int, NestedObject> GetElementNestedElements(string connectionString, IDataProvider provider, int pkgId, IndexOutOfRangeException elId)
        {

            using (var db = new DataModels.EaDataModel(provider, connectionString))
            {
                // optimize Access to database, without this the query takes > 30 seconds
                // Split query and group into two queries.
                // - The first query make the db acccess and writes to array
                // - The second query makes the grouping
                var reqTvAll0 = (from r in db.t_object
                    join pkg in db.t_package on r.Package_ID equals pkg.Package_ID
                    join tv in db.t_objectproperties on r.Object_ID equals tv.Object_ID
                    where pkg.Package_ID == pkgId
                    orderby r.Object_ID, tv.Property
                    select new { r, tv }).ToArray();

                return (from r in reqTvAll0
                        group r by new { r.r.Object_ID, r.r.ParentID, r.r.TPos, r.r.Name, r.r.Alias, r.r.Note, r.r.ea_guid, r.r.Object_Type } into grp1
                        select new
                        {
                            Id = grp1.Key.Object_ID,
                            Property = new NestedObject(
                                grp1.Key.ParentID??0,
                                grp1.Key.TPos??0,
                                grp1.Key.Name,
                                grp1.Key.Alias,
                                grp1.Key.Note,
                                grp1.Key.ea_guid,
                                grp1.Key.Object_Type,
                                // Tagged Value
                                grp1.Select(g => new Tv(
                                    g.tv.Property,
                                    ((g.tv.Value ?? "") == "<memo>") ? g.tv.Notes : g.tv.Value)
                                ).ToList())
                        }).ToDictionary(ta => ta.Id, ta => ta.Property);
            }

        }
        /// <summary>
        /// Add elements to Data Table
        /// </summary>
        /// <param name="nestedElements"></param>
        /// <param name="dt"></param>
        /// <param name="parentId"></param>
        /// <param name="level"></param>
        private static void AddElementsToTable( Dictionary<int, NestedObject> nestedElements, DataTable dt, int parentId, int level)
        {
            // output current element

            var req = from r in nestedElements
                //join tv in reqTvAll on r.Object_ID equals tv.Object_ID
                where r.Value.ParentId == parentId
                orderby r.Value.TPos
                select r;
                foreach (var r in req)
                {
                    NestedElementToDataTable(dt, r, level);
                    AddElementsToTable(nestedElements, dt, r.Key, level + 1);
                }

        }
        /// <summary>
        /// Nested Elements to Data Table
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="nestedObject"></param>
        /// <param name="level"></param>
        private static void NestedElementToDataTable(DataTable dt, KeyValuePair<int, NestedObject> nestedObject, int level)
        {
            var row = dt.NewRow();
            row["CLASSGUID"] = nestedObject.Value.Guid;
            row["CLASSTYPE"] = nestedObject.Value.ObjectType;
            string t = $"{new string('.', 2 * level)}{nestedObject.Value.Name}";
            row["Name"] = t;
            row["Alias"] = nestedObject.Value.Alias;
            row["Note"] = nestedObject.Value.Notes;
            foreach (Tv tv in nestedObject.Value.Tv)
            {
                if (tv.Property == "") continue;
                if (!_tv.ContainsKey(tv.Property))
                {
                    _tv.Add(tv.Property, null);
                    dt.Columns.Add(tv.Property, typeof(string));
                }

                string value = tv.Value;
               row[$"{tv.Property}"] = value;
            }
            dt.Rows.Add(row);
        }

        /// <summary>
        /// Make a Data Table from nested Elements recursive using EA API
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="el"></param>
        /// <param name="level"></param>
        private static void NestedElementsRecursiveUsingEaApi(DataTable dt, EA.Element el, int level)
        {

            var row = dt.NewRow();
            row["CLASSGUID"] = el.ElementGUID;
            row["CLASSTYPE"] = el.Type;
            string t = $"{new string('.',2 * level)}{el.Name}";
            row["Name"] = t;
            row["Alias"] = el.Alias;
            row["Note"] = el.Notes;
            AddTaggedValues(dt, el, row);
            dt.Rows.Add(row);
            level += 1;
            foreach (EA.Element elChild in el.Elements)
            {

                NestedElementsRecursiveUsingEaApi(dt, elChild, level);
            }

        }

        /// <summary>
        /// Make a Data Table from nested Elements recursive using EA API
        /// </summary>
        /// <param name="provider"></param>
        /// <param name="dt"></param>
        /// <param name="connectionString"></param>
        /// <param name="pkgGuid"></param>
        /// <param name="elId"></param>
        private static void NestedElementsRecursive(string connectionString, IDataProvider provider, DataTable dt, string pkgGuid, int elId)
        {
            Dictionary<int, NestedObject> nestedElements = GetPackageNestedElements(connectionString, provider, pkgGuid);
            int level = 0;
            KeyValuePair<int, NestedObject> r = new KeyValuePair<int, NestedObject> (elId, nestedElements[elId]);
            // Output the top level
            NestedElementToDataTable(dt, r, level);
            AddElementsToTable(nestedElements, dt, elId, level+1);

        }

        /// <summary>
        /// Add Tagged Values of element to current data table row
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="el"></param>
        /// <param name="dataRow"></param>
        private static void AddTaggedValues(DataTable dt, EA.Element el, DataRow dataRow)
        {
            foreach (EA.TaggedValue tv in el.TaggedValues)
            {
                if (!_tv.ContainsKey(tv.Name))
                {
                    _tv.Add(tv.Name, null);
                    dt.Columns.Add(tv.Name, typeof(string));
                }

                dataRow[$"{tv.Name}"] = ReqIfUtils.GetEaTaggedValue(tv.Value, tv.Notes);
            }
        }
        /// <summary>
        /// Get list of strings from a comma separated string.
        /// </summary>
        /// <param name="commaSeparated"></param>
        /// <returns></returns>
        private static string[] GetEaFromCommaSeparatedList(string commaSeparated)
        {
            if (String.IsNullOrWhiteSpace(commaSeparated)) return new string[0];
            // delete special characters like blank, linefeed, ', ""
            commaSeparated = Regex.Replace(commaSeparated, @"\r\n?|\n|'|""", "");

            // allow different delimiters
            commaSeparated = Regex.Replace(commaSeparated, @"  ", " ");
            commaSeparated = Regex.Replace(commaSeparated, @";|:| ", ",");

            return commaSeparated.Split(',');
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.genyris.string;

import org.genyris.core.Constants;
import org.genyris.core.Exp;
import org.genyris.core.StrinG;
import org.genyris.exception.GenyrisException;
import org.genyris.interp.Closure;
import org.genyris.interp.Environment;
import org.genyris.interp.Interpreter;

public class LengthMethod extends AbstractStringMethod {

	public static String getStaticName() {return Constants.LENGTH;};
  public LengthMethod(Interpreter interp) {
        super(interp, getStaticName());
    }

    public Exp bindAndExecute(Closure proc, Exp[] arguments, Environment env)
      throws GenyrisException {

    StrinG theString = getSelfString(env);
    return theString.length();
  }
}


text:
<button type="button" class="btn btn-primary" style="margin: 1% 1% 1% 1%; width: 98%;" ng-click="syncEvents()">Sync</button>

<div ng-repeat="event in events" ng-if="event.organization_id == currentOrganizationID">
<label>
<input type="radio" ng-model="currentEventID" name="selectEvent" value="{{event.id}}" ng-click="selectEvent(event.id)"/>{{event.name}}
</label>
</div>


text:
<!DOCTYPE html>

    <title>Mr Minsky's Favorite CS Class</title>

This is an h1 header

This is an h2 header

This is an h3 header

This is an h4 header

This is an h5 header

This is an h6 header

Hello, this is text.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas porta  lacinia condimentum. Sed aliquet, velit at ultricies posuere, dui neque ullamcorper metus, vitae lacinia diam ipsum a est. In id pretium neque.

Aliquam lacinia bibendum accumsan. In condimentum pellentesque libero, sit amet ullamcorper libero vulputate at. Phasellus placerat mi imperdiet metus tincidunt suscipit. Sed sit amet enim a nunc convallis aliquam. Suspendisse vitae tellus sit amet lacus lacinia ornare dapibus sed tortor. Phasellus auctor nisi cursus nibh fringilla convallis. Vivamus venenatis, erat nec finibus pellentesque, nibh ex vulputate magna, ac commodo lorem diam et neque. Vestibulum elementum massa vel mi ultricies, sed lacinia metus egestas. Morbi faucibus sollicitudin molestie. Nullam id vehicula sem.


text:
import forge from "node-forge";
import debug from "debug";
import fs from "fs";
import jwt from "jsonwebtoken";
import { splitca, pemToDerArray, derArrayToPem } from "./utils";
import { parse as urlParse } from "url";

const log = debug("sk:dove-jwt");

const throwCode = function(code) {
  const err = new Error(code);
  throw err;
};

export class DoveJwt {
  /**
   * Create a new DoveJwt instance. Usually you won't need to do this -- we've already created one
   * for you that you can get at `import dove from "dove-jwt".` But if you need to have different
   * instances of dove that trust different root CAs, you might make more than one.
   * @return {DoveJwt}
   */
  constructor() {
    this.caStore = forge.pki.createCaStore();
  }

  /**
   * Add one or more trusted root CAs.
   *
   * The behavior here is kinda weird. We only support RSA keys, but we also want to be able to
   * seamlessly import /etc/ssl/certs/ca-certificates.crt. So, if you try and pass in a single PEM
   * file which we can't parse, that's an error. But if you pass in a big ol' bundle of
   * concatenated CAs, we only throw an error if they're all invalid. (And we print a warning, but
   * that'll have to change if people actually lose this library for anything 😀)
   *
   * @param {String} rootCA PEM-encoded root CA. Lots of them concatted together is fine too.
   */
  addCertAuthority(rootCA) {
    let added = 0;
    let failed = 0;
    let lastError;
    splitca(rootCA).forEach(ca => {
      try {
        this.caStore.addCertificate(ca);
        added += 1;
      } catch (e) {
        // We can safely ignore this very specific error... I guess. Eew for matching this error
        // this way.
        if (e.message !== "Cannot read public key. OID is not RSA.") {
          throw e;
        } else {
          failed += 1;
        }
      }
    });
    if (added === 0 && failed === 0) {
      throw new Error("addCertAuthority called with no keys.");
    }
    if (added === 0) {
      throw new Error(
        "None of the keys passed to addCertAuthority were RSA keys, none added."
      );
    }
    if (failed > 0) {
      log(
        `${added} RSA CAs added, ${failed} non-RSA CAs ignored. (This is normal because we only support RSA certs, and is not ordinarily cause for concern)`
      );
    }
  }

  /**
   * Use the system's built-in root CAs. This is kind of what we had in mind writing dove-jwt, but
   * it's disabled by default b/c self-signed is good too.
   */
  useSystemCertAuthorities() {
    // if your life is worse because this is is sync, let me know and I'll change it! -Eli
    const myCAs = fs.readFileSync(DoveJwt.SYSTEM_CA_PATH, "utf8");
    return this.addCertAuthority(myCAs);
  }

  /**
   * Throws a cert_untrusted error if the cert isn't trusted according to our CA store.
   * @param  {Strong} cert PEM formatted cert
   */
  verifyCertTrusted(cert) {
    try {
      const result = forge.pki.verifyCertificateChain(
        this.caStore,
        splitca(cert).map(forge.pki.certificateFromPem)
      );
    } catch (e) {
      log("Error from forge.pki.verifyCertificateChain", e);
      throwCode("cert_untrusted");
    }
  }

  /**
   * If we weren't provided an issuer, derive it from the cert
   * @param  {String} cert PEM-formatted certificate
   * @return {String} https://example.com/
   */
  getIssuer(cert) {
    const forgeCert = forge.pki.certificateFromPem(cert);
    const subject = forgeCert.subject.getField("CN");
    const commonName = subject.value;
    return `https://${commonName}/`;
  }

  verifyCertIssuerMatch(cert, issuer) {
    if (!issuer) {
      throwCode("issuer_missing");
    }
    const { host } = urlParse(issuer);
    if (issuer !== `https://${host}/`) {
      log(`Malformed issuer: "${issuer}" should be of form "https://${host}/"`);
      throwCode("issuer_invalid");
    }
    let commonName;
    try {
      const forgeCert = forge.pki.certificateFromPem(cert);
      const subject = forgeCert.subject.getField("CN");
      commonName = subject.value;
    } catch (e) {
      log("Error from forge", e);
      throwCode("x5c_invalid");
    }
    if (host !== commonName) {
      log(`Incorrect issuer: ${host} !== ${commonName}`);
      throwCode("issuer_wrong");
    }
  }

  /**
   * Create a new dove-jwt.
   * @param  {Object} payload   Body of the JWT you'd like to produce. Passed directly to jsonwebtoken.
   * @param  {String} secretKey RSA secret key.
   * @param  {String} cert      RSA cert, signed by your relevant CA.
   * @param  {Object} options   Options object, passed through to [the same configuration options
   *                            of node-jsonwebtoken](https://github.com/auth0/node-jsonwebtoken#usage).
   * @return {String} The dove-jwt.
   */
  sign(payload, secretKey, cert, options = {}) {
    if (!payload || !secretKey || !cert) {
      throw new Error("Missing required parameters to dove.sign.");
    }
    this.verifyCertTrusted(cert);
    options.algorithm = "RS256";
    if (!options.issuer) {
      options.issuer = this.getIssuer(cert);
    } else {
      this.verifyCertIssuerMatch(cert, options.issuer);
    }
    if (!options.header) {
      options.header = {};
    }
    options.header.x5c = pemToDerArray(cert);
    return jwt.sign(payload, secretKey, options);
  }

  /**
   * Parse and verify a dove-jwt.
   * @param  {[type]} token The dove-jwt
   * @return {Object}       Returns a decrypted JWT. Otherwise, throws an error otherwise. If
   *                        you want to look at the (evil, invalid, not-to-be-trusted) JWT
   *                        after a verification failure, it's available on the `decryptedJwt`
   *                        property of the error.
   */
  verify(token) {
    const { header, payload: untrustedPayload } = jwt.decode(token, {
      complete: true
    });
    if (!header.x5c) {
      throwCode("x5c_missing");
    }
    let cert;
    try {
      cert = derArrayToPem(header.x5c);
    } catch (e) {
      log("Error from forge", e);
      throwCode("x5c_invalid");
    }
    this.verifyCertTrusted(cert);
    this.verifyCertIssuerMatch(cert, untrustedPayload.iss);
    // jsonwebtoken checks for this, but it's v important, so let's check too
    if (header.alg !== "RS256") {
      throwCode("algorithm_invalid");
    }
    const trustedPayload = jwt.verify(token, cert, { algorithms: "RS256" });
    return trustedPayload;
  }
}

// Mostly so it can be overridden in test mocks
DoveJwt.SYSTEM_CA_PATH = "/etc/ssl/certs/ca-certificates.crt";

export default new DoveJwt();


text:
<!-- Start src/server/api.js -->

<!-- End src/server/api.js -->


text:
<!DOCTYPE html>

  <link href="http://gmpg.org/xfn/11" rel="profile">
  <meta http-equiv="content-type" content="text/html; charset=utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">

  <title>

      zacharytamas ·

  </title>

  <link rel="stylesheet" href="/public/css/poole.css">
  <link rel="stylesheet" href="/public/css/syntax.css">
  <link rel="stylesheet" href="/public/css/hyde.css">
  <link rel="stylesheet" href="/public/css/zblog.css">
  <link rel="stylesheet" href="/public/css/portfolio.css">
  <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Open+Sans:400italic,600italic,700italic,400,600,700|Abril+Fatface">

  <link rel="alternate" type="application/rss+xml" title="RSS" href="/atom.xml">

Choose a project for more details.

Lights-On Network

              2014

Screenly

              2013

YippieMove

              2012

Lifetime Income Process

              2011

Older Projects

              Years Past

          « back home

      12 years
      HTML & CSS/LESS

      9 years
      Python (with Django)

      4 years
      JavaScript

      3 years
      Backbone.js

      1.5 years
      Polymer.js

      1.5 years
      Google Cloud Services

      Design

      Android (Java)

  Other skills I'm familiar with include ActionScript, Adobe AIR, Adobe Photoshop, Agile and Scrum, Apache, Celery task queue, D3.js, Git, Jasmine, MongoDB, MySQL, Node.js, Objective-C, PostgreSQL, Ruby on Rails, Selenium, Sketch, Subversion, Swift, Ubuntu, quantitative finance concepts, and test-driven and behavior-driven development.

Positions Held

Web Application Developer

      Google (with Adecco)

    —

      Jul 2014-Present

Working at Google with their People Operations organization to create new learning technology products to make learning more fun and efficient.

Software Engineer

      Cerner Corporation

    —

      May 2013-Mar 2014

Worked with the Lights-On team to create rich, analytical dashboards for the study of system performance and efficiency.

Software Engineer

      Independent Consultant

    —

      Aug 2006-May 2013

Developed custom, tailor-made software for a broad range of companies and organizations, including a leading email migration service used by Ivy League universities and major Internet service providers.

Computer Science Tutor

      University of West Florida

    —

      Aug 2011-Dec 2011

Assisted Computer Science students with projects involving data structures, algorithms, and some web technologies. Languages I tutored included: C, Python, HTML/CSS, Javascript, and Java. Sometimes taught concepts to small groups.


text:
 DROP TABLE `Dictionary`;
 DROP TABLE `externalLInks`;
 DROP TABLE `PortFoliLables`;
 DROP TABLE `portfolilinkslabel`;
 DROP TABLE `Portfolio`;
 DROP TABLE `PortFolioLinks`;
 DROP TABLE `PortfolioLInks`;
 DROP TABLE `PortFolioLinksLabel`;
 DROP TABLE `PortfolioStatus`;
 DROP TABLE `portfoliostatus`;
 DROP TABLE `PortfolioType`;
 DROP TABLE `portfoliotype`;
 DROP TABLE `portfoliReleases`;
 DROP TABLE `ProgressRatio`;
 DROP TABLE `progressratio`;
 DROP TABLE `Resource`;
 DROP TABLE `ResourceType`;
 DROP TABLE `resourcetype`;
 DROP TABLE `t1`;
 DROP TABLE `t2`;
 DROP TABLE `t3`;
 DROP TABLE `t4`;
 DROP TABLE `Task`;
 DROP TABLE `TaskLinksLabel`;
 DROP TABLE `tasklinkslabel`;
 DROP TABLE `TaskStatus`;
 DROP TABLE `taskstatus`;
 DROP TABLE `Team`;
 DROP TABLE `team`;
 DROP TABLE `TeamResource`;
 DROP TABLE `UserStory`;
 DROP TABLE `WorkLog`;


text:
using namespace arangodb;
using namespace arangodb::aql;
using namespace arangodb::graph;

namespace {
static bool isValidId(VPackSlice id) {
  TRI_ASSERT(id.isString());
  arangodb::velocypack::StringRef tester(id);
  return tester.find('/') != std::string::npos;
}
}  // namespace

ShortestPathExecutorInfos::ShortestPathExecutorInfos(
    std::unique_ptr<graph::ShortestPathFinder>&& finder,
    std::unordered_map<OutputName, RegisterId, OutputNameHash>&& registerMapping,
    InputVertex&& source, InputVertex&& target)
    : _finder(std::move(finder)),
      _registerMapping(std::move(registerMapping)),
      _source(std::move(source)),
      _target(std::move(target)) {}

arangodb::graph::ShortestPathFinder& ShortestPathExecutorInfos::finder() const {
  TRI_ASSERT(_finder);
  return *_finder.get();
}

bool ShortestPathExecutorInfos::useRegisterForSourceInput() const {
  return _source.type == InputVertex::Type::REGISTER;
}

bool ShortestPathExecutorInfos::useRegisterForTargetInput() const {
  return _target.type == InputVertex::Type::REGISTER;
}

RegisterId ShortestPathExecutorInfos::getSourceInputRegister() const {
  TRI_ASSERT(useRegisterForSourceInput());
  return _source.reg;
}

RegisterId ShortestPathExecutorInfos::getTargetInputRegister() const {
  TRI_ASSERT(useRegisterForTargetInput());
  return _target.reg;
}

std::string const& ShortestPathExecutorInfos::getSourceInputValue() const {
  TRI_ASSERT(!useRegisterForSourceInput());
  return _source.value;
}

std::string const& ShortestPathExecutorInfos::getTargetInputValue() const {
  TRI_ASSERT(!useRegisterForTargetInput());
  return _target.value;
}

bool ShortestPathExecutorInfos::usesOutputRegister(OutputName type) const {
  return _registerMapping.find(type) != _registerMapping.end();
}

ShortestPathExecutorInfos::InputVertex ShortestPathExecutorInfos::getSourceVertex() const noexcept {
  return _source;
}

ShortestPathExecutorInfos::InputVertex ShortestPathExecutorInfos::getTargetVertex() const noexcept {
  return _target;
}

static std::string typeToString(ShortestPathExecutorInfos::OutputName type) {
  switch (type) {
    case ShortestPathExecutorInfos::VERTEX:
      return std::string{"VERTEX"};
    case ShortestPathExecutorInfos::EDGE:
      return std::string{"EDGE"};
    default:
      return std::string{"<INVALID("} + std::to_string(type) + ")>";
  }
}

RegisterId ShortestPathExecutorInfos::findRegisterChecked(OutputName type) const {
  auto const& it = _registerMapping.find(type);
  if (ADB_UNLIKELY(it == _registerMapping.end())) {
    THROW_ARANGO_EXCEPTION_MESSAGE(
        TRI_ERROR_INTERNAL,
        "Logic error: requested unused register type " + typeToString(type));
  }
  return it->second;
}

RegisterId ShortestPathExecutorInfos::getOutputRegister(OutputName type) const {
  TRI_ASSERT(usesOutputRegister(type));
  return findRegisterChecked(type);
}

graph::TraverserCache* ShortestPathExecutorInfos::cache() const {
  return _finder->options().cache();
}

ShortestPathExecutor::ShortestPathExecutor(Fetcher&, Infos& infos)
    : _infos(infos),
      _inputRow{CreateInvalidInputRowHint{}},
      _finder{infos.finder()},
      _path{new arangodb::graph::ShortestPathResult{}},
      _posInPath(0),
      _sourceBuilder{},
      _targetBuilder{} {
  if (!_infos.useRegisterForSourceInput()) {
    _sourceBuilder.add(VPackValue(_infos.getSourceInputValue()));
  }
  if (!_infos.useRegisterForTargetInput()) {
    _targetBuilder.add(VPackValue(_infos.getTargetInputValue()));
  }
  // Make sure the finder does not contain any leftovers in case of
  // the executor being reconstructed.
  _finder.clear();
}

auto ShortestPathExecutor::doOutputPath(OutputAqlItemRow& output) -> void {
  while (!output.isFull() && _posInPath < _path->length()) {
    if (_infos.usesOutputRegister(ShortestPathExecutorInfos::VERTEX)) {
      AqlValue vertex = _path->vertexToAqlValue(_infos.cache(), _posInPath);
      AqlValueGuard guard{vertex, true};
      output.moveValueInto(_infos.getOutputRegister(ShortestPathExecutorInfos::VERTEX),
                           _inputRow, guard);
    }
    if (_infos.usesOutputRegister(ShortestPathExecutorInfos::EDGE)) {
      AqlValue edge = _path->edgeToAqlValue(_infos.cache(), _posInPath);
      AqlValueGuard guard{edge, true};
      output.moveValueInto(_infos.getOutputRegister(ShortestPathExecutorInfos::EDGE),
                           _inputRow, guard);
    }
    output.advanceRow();
    _posInPath++;
  }
}

auto ShortestPathExecutor::doSkipPath(AqlCall& call) -> size_t {
  auto skip = size_t{0};

  // call.getOffset() > 0 means we're in SKIP mode
  if (call.getOffset() > 0) {
    if (call.getOffset() < pathLengthAvailable()) {
      skip = call.getOffset();
    } else {
      skip = pathLengthAvailable();
    }
  } else {
    // call.getOffset() == 0, we might be in SKIP, PRODUCE, or
    // FASTFORWARD/FULLCOUNT, but we only FASTFORWARD/FULLCOUNT if
    // call.getLimit() == 0 as well.
    if (call.needsFullCount() && call.getLimit() == 0) {
      skip = pathLengthAvailable();
    }
  }
  _posInPath += skip;
  call.didSkip(skip);
  return skip;
}

auto ShortestPathExecutor::fetchPath(AqlItemBlockInputRange& input) -> bool {
  // We only want to call fetchPath if we don't have a path currently available
  TRI_ASSERT(pathLengthAvailable() == 0);
  _finder.clear();
  _path->clear();
  _posInPath = 0;

  while (input.hasDataRow()) {
    auto source = VPackSlice{};
    auto target = VPackSlice{};
    std::tie(std::ignore, _inputRow) = input.nextDataRow(AqlItemBlockInputRange::HasDataRow{});
    TRI_ASSERT(_inputRow.isInitialized());

    // Ordering important here.
    // Read source and target vertex, then try to find a shortest path (if both worked).
    if (getVertexId(_infos.getSourceVertex(), _inputRow, _sourceBuilder, source) &&
        getVertexId(_infos.getTargetVertex(), _inputRow, _targetBuilder, target) &&
        _finder.shortestPath(source, target, *_path)) {
      return true;
    }
  }
  // Note that we only return false if
  // the input does not have a data row, so if we return false
  // here, we are DONE (we cannot produce any output anymore).
  return false;
}
auto ShortestPathExecutor::pathLengthAvailable() -> size_t {
  // Subtraction must not undeflow
  TRI_ASSERT(_posInPath <= _path->length());
  return _path->length() - _posInPath;
}

auto ShortestPathExecutor::produceRows(AqlItemBlockInputRange& input, OutputAqlItemRow& output)
    -> std::tuple<ExecutorState, Stats, AqlCall> {
  while (true) {
    if (pathLengthAvailable() > 0) {
      // TODO maybe have doOutput report whether output is full?
      doOutputPath(output);
      if (output.isFull()) {
        if (pathLengthAvailable() > 0) {
          return {ExecutorState::HASMORE, NoStats{}, AqlCall{}};
        } else {
          // We don't have rows available for output. If
          // upstream is DONE, we will not be able to produce more
          // if upstream HASMORE, we do not know, so we say HASMORE.
          return {input.upstreamState(), NoStats{}, AqlCall{}};
        }
      }
    } else {
      // If fetchPath fails, this means that input has not given us a dataRow
      // that yielded a path.
      // If upstream is DONE, we are done too, and if upstream
      // HASMORE, we can potentially make more.
      if (!fetchPath(input)) {
        TRI_ASSERT(!input.hasDataRow());
        return {input.upstreamState(), NoStats{}, AqlCall{}};
      }
    }
  }
}

auto ShortestPathExecutor::skipRowsRange(AqlItemBlockInputRange& input, AqlCall& call)
    -> std::tuple<ExecutorState, Stats, size_t, AqlCall> {
  auto skipped = size_t{0};

  while (true) {
    skipped += doSkipPath(call);

    if (pathLengthAvailable() == 0) {
      if (!fetchPath(input)) {
        TRI_ASSERT(!input.hasDataRow());
        return {input.upstreamState(), NoStats{}, skipped, AqlCall{}};
      }
    } else {
      // if we end up here there is path available, but
      // we have skipped as much as we were asked to.
      TRI_ASSERT(call.getOffset() == 0);
      return {ExecutorState::HASMORE, NoStats{}, skipped, AqlCall{}};
    }
  }
}

bool ShortestPathExecutor::getVertexId(ShortestPathExecutorInfos::InputVertex const& vertex,
                                       InputAqlItemRow& row,
                                       VPackBuilder& builder, VPackSlice& id) {
  switch (vertex.type) {
    case ShortestPathExecutorInfos::InputVertex::Type::REGISTER: {
      AqlValue const& in = row.getValue(vertex.reg);
      if (in.isObject()) {
        try {
          auto idString = _finder.options().trx()->extractIdString(in.slice());
          builder.clear();
          builder.add(VPackValue(idString));
          id = builder.slice();
          // Guranteed by extractIdValue
          TRI_ASSERT(::isValidId(id));
        } catch (...) {
          // _id or _key not present... ignore this error and fall through
          // returning no path
          return false;
        }
        return true;
      } else if (in.isString()) {
        id = in.slice();
        // Validation
        if (!::isValidId(id)) {
          _finder.options().query().warnings().registerWarning(
              TRI_ERROR_BAD_PARAMETER,
              "Invalid input for Shortest Path: "
              "Only id strings or objects with "
              "_id are allowed");
          return false;
        }
        return true;
      } else {
        _finder.options().query().warnings().registerWarning(
            TRI_ERROR_BAD_PARAMETER,
            "Invalid input for Shortest Path: "
            "Only id strings or objects with "
            "_id are allowed");
        return false;
      }
    }
    case ShortestPathExecutorInfos::InputVertex::Type::CONSTANT: {
      id = builder.slice();
      if (!::isValidId(id)) {
        _finder.options().query().warnings().registerWarning(
            TRI_ERROR_BAD_PARAMETER,
            "Invalid input for Shortest Path: "
            "Only id strings or objects with "
            "_id are allowed");
        return false;
      }
      return true;
    }
  }
  return false;
}


text:
package com.tngtech.archunit.lang.syntax;

import java.util.Optional;

import com.tngtech.archunit.Internal;
import com.tngtech.archunit.base.DescribedPredicate;

@Internal
public final class PredicateAggregator<T> {
    private final AddMode<T> addMode;
    private final Optional<DescribedPredicate<T>> predicate;

    public PredicateAggregator() {
        this(AddMode.and(), Optional.empty());
    }

    private PredicateAggregator(AddMode<T> addMode, Optional<DescribedPredicate<T>> predicate) {
        this.addMode = addMode;
        this.predicate = predicate;
    }

    public PredicateAggregator<T> add(DescribedPredicate<? super T> other) {
        return new PredicateAggregator<>(addMode, Optional.of(addMode.apply(predicate, other)));
    }

    public boolean isPresent() {
        return predicate.isPresent();
    }

    public DescribedPredicate<T> get() {
        return predicate.get();
    }

    public PredicateAggregator<T> thatANDs() {
        return new PredicateAggregator<>(AddMode.and(), predicate);
    }

    public PredicateAggregator<T> thatORs() {
        return new PredicateAggregator<>(AddMode.or(), predicate);
    }

    private abstract static class AddMode<T> {
        static <T> AddMode<T> and() {
            return new AddMode<T>() {
                @Override
                DescribedPredicate<T> apply(Optional<DescribedPredicate<T>> first, DescribedPredicate<? super T> other) {
                    DescribedPredicate<T> second = other.forSubtype();
                    return first.isPresent() ? first.get().and(second) : second;
                }
            };
        }

        static <T> AddMode<T> or() {
            return new AddMode<T>() {
                @Override
                DescribedPredicate<T> apply(Optional<DescribedPredicate<T>> first, DescribedPredicate<? super T> other) {
                    DescribedPredicate<T> second = other.forSubtype();
                    return first.isPresent() ? first.get().or(second) : second;
                }
            };
        }

        abstract DescribedPredicate<T> apply(Optional<DescribedPredicate<T>> first, DescribedPredicate<? super T> other);
    }
}


text:
'use strict';

const { execSync } = require('child_process');

const commands = {
  'meta-j': `
    local awful = require('awful')
    awful.client.focus.byidx( 1)
    if client.focus then client.focus:raise() end
  `,
  'meta-k': `
    local awful = require('awful')
    awful.client.focus.byidx(-1)
    if client.focus then client.focus:raise() end
  `
};

module.exports = command => {
  if (commands[command]) {
    execSync(`echo "${commands[command]}" | awesome-client`);
    return true;
  } else {
    return false;
  }
};


text:
power-assert-formatter
================================

[![Build Status][travis-image]][travis-url]
[![NPM package][npm-image]][npm-url]
[![Bower package][bower-image]][bower-url]
[![Dependency Status][depstat-image]][depstat-url]
[![Coverage Status][coverage-image]][coverage-url]
[![Code Climate][codeclimate-image]][codeclimate-url]
[![License][license-image]][license-url]
[![Built with Gulp][gulp-image]][gulp-url]

Power Assert output formatter.

DESCRIPTION
---------------------------------------
`power-assert-formatter` is a formatter module for Power Assert output.

Pull-requests, issue reports and patches are always welcomed. See [power-assert](http://github.com/power-assert-js/power-assert) project for more documentation.

CHANGELOG
---------------------------------------
See [CHANGELOG](https://github.com/power-assert-js/power-assert-formatter/blob/master/CHANGELOG.md)

API
---------------------------------------

### var createFormatter = require('power-assert-formatter');

| return type |
|:------------|
| `function`  |

Returns creator function for power-assert.

### var formatter = createFormatter([options]);

| return type |
|:------------|
| `function`  |

Create formatter function with options. `options` argument is optional.

#### options

| type     | default value |
|:---------|:--------------|
| `object` | (return value of `createFormatter.defaultOptions()`) |

Configuration options. If not passed, default options will be used.

#### options.lineDiffThreshold

| type     | default value |
|:---------|:--------------|
| `number` | `5`           |

Threshold to show diff at character level or line level. If number of lines in target string is greater than `lineDiffThreshold`, then line diff mode will be used to show diff output.

#### options.maxDepth

| type     | default value |
|:---------|:--------------|
| `number` | `1`           |

Depth of object traversal. If object depth is greater than `maxDepth`, compound object (IOW, `Array` or `object`) will be pruned with `#` like `["foo",#Array#,#Object#]`.

#### options.outputOffset

| type     | default value |
|:---------|:--------------|
| `number` | `2`           |

Number of spaces inserted at the left in power-assert output.

#### options.anonymous

| type     | default value |
|:---------|:--------------|
| `string` | `"Object"`    |

Type name to show when target object is created by anonymous constructor.

#### options.circular

| type     | default value   |
|:---------|:----------------|
| `string` | `"#@Circular#"` |

Name to show when target object is detected as circular structure.

#### options.lineSeparator

| type     | default value |
|:---------|:--------------|
| `string` | `"\n"`        |

Line separator in power assert output.

#### options.ambiguousEastAsianCharWidth

| type     | default value |
|:---------|:--------------|
| `number` | `2`           |

Width of 'Ambiguous' characters defined in [Unicode Standard Annex \#11 EAST ASIAN WIDTH](http://www.unicode.org/reports/tr11/#Ambiguous). Configure `options.ambiguousEastAsianCharWidth` to treat ambiguous east asian character as fullwidth (= `2`) or narrow (= `1`). Default is `2`.

#### options.widthOf

| type       | default value |
|:-----------|:--------------|
| `function` | [string-width.js](https://github.com/power-assert-js/power-assert-formatter/blob/master/lib/string-width.js) |

Function to calculate width of string.

#### options.stringify

| type       | default value |
|:-----------|:--------------|
| `function` | [stringifier module](https://github.com/twada/stringifier) |

Function to stringify any target value.

#### options.diff

| type       | default value |
|:-----------|:--------------|
| `function` | [udiff.js](https://github.com/power-assert-js/power-assert-formatter/blob/master/lib/udiff.js) |

Function to create diff string between two strings.

#### options.writerClass

| type       | default value |
|:-----------|:--------------|
| `function` | [string-writer.js](https://github.com/power-assert-js/power-assert-formatter/blob/master/lib/string-writer.js) |

Constructor Function for output writer class.

#### options.renderers

| type                                | default value |
|:------------------------------------|:--------------|
| `Array` of (`string` or `function` )| shown below   |

```javascript
[
    './built-in/file',
    './built-in/assertion',
    './built-in/diagram',
    './built-in/binary-expression'
]
```

Output renderers. Power assert output is rendered by renderers in order. You can create custom renderer and add its constructor function to customize power-assert-output.

```javascript
[
    './built-in/file',
    './built-in/assertion',
    YourCustomRenderer,
    './built-in/binary-expression'
]
```

### var options = createFormatter.defaultOptions();

Returns default options object for createFormatter function. In other words, returns

```javascript
{
    lineDiffThreshold: 5,
    maxDepth: 1,
    anonymous: 'Object',
    circular: '#@Circular#',
    lineSeparator: '\n',
    ambiguousEastAsianCharWidth: 2,
    renderers: [
        './built-in/file',
        './built-in/assertion',
        './built-in/diagram',
        './built-in/binary-expression'
    ]
};
```

### var formattedText = formatter(powerAssertContext);

| return type |
|:------------|
| `string`  |

Format `powerAssertContext` into `formattedText`. `powerAssertContext` is an internal object structure, containing informations to render. Example of `powerAssertContext` is:

```javascript
{
    source: {
        content: "assert.equal(foo, bar)",
        filepath: "/path/to/some_test.js",
        line: 1
    },
    args: [
        {
            value: "foo",
            events: [
                {
                    value: "foo",
                    espath: "arguments/0"
                }
            ]
        },
        {
            value: "bar",
            events: [
                {
                    value: "bar",
                    espath: "arguments/1"
                }
            ]
        }
    ]
}
```

Note that structure of powerAssertContext may change.

INSTALL
---------------------------------------

### via npm

Install

    $ npm install --save-dev power-assert-formatter

#### use power-assert-formatter npm module on browser

`powerAssertFormatter` function is exported

    <script type="text/javascript" src="./path/to/node_modules/power-assert-formatter/build/power-assert-formatter.js"></script>

### via bower

Install

    $ bower install --save-dev power-assert-formatter

Then load (`powerAssertFormatter` function is exported)

    <script type="text/javascript" src="./path/to/bower_components/power-assert-formatter/build/power-assert-formatter.js"></script>

AUTHOR
---------------------------------------
* [Takuto Wada](http://github.com/twada)

CONTRIBUTORS
---------------------------------------
* [James Talmage (jamestalmage)](https://github.com/jamestalmage)

LICENSE
---------------------------------------
Licensed under the [MIT](https://github.com/power-assert-js/power-assert-formatter/blob/master/MIT-LICENSE.txt) license.

[npm-url]: https://npmjs.org/package/power-assert-formatter
[npm-image]: https://badge.fury.io/js/power-assert-formatter.svg

[bower-url]: http://badge.fury.io/bo/power-assert-formatter
[bower-image]: https://badge.fury.io/bo/power-assert-formatter.svg

[travis-url]: http://travis-ci.org/power-assert-js/power-assert-formatter
[travis-image]: https://secure.travis-ci.org/power-assert-js/power-assert-formatter.svg?branch=master

[depstat-url]: https://gemnasium.com/power-assert-js/power-assert-formatter
[depstat-image]: https://gemnasium.com/power-assert-js/power-assert-formatter.svg

[license-url]: https://github.com/power-assert-js/power-assert-formatter/blob/master/MIT-LICENSE.txt
[license-image]: http://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat

[codeclimate-url]: https://codeclimate.com/github/power-assert-js/power-assert-formatter
[codeclimate-image]: https://codeclimate.com/github/power-assert-js/power-assert-formatter/badges/gpa.svg

[coverage-url]: https://coveralls.io/r/power-assert-js/power-assert-formatter?branch=master
[coverage-image]: https://coveralls.io/repos/power-assert-js/power-assert-formatter/badge.svg?branch=master

[gulp-url]: http://gulpjs.com/
[gulp-image]: http://img.shields.io/badge/built_with-gulp-brightgreen.svg


text:
<!DOCTYPE html>

    <meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>
  Class: UclItkpdConfigurator::Errors::ComponentTypeError

    — ITk Producation Database Configurator Application Server Documentation

</title>

  <link rel="stylesheet" href="../../css/style.css" type="text/css" charset="utf-8" />

  <link rel="stylesheet" href="../../css/common.css" type="text/css" charset="utf-8" />

  <link rel="stylesheet" href="../../css/cucumber.css" type="text/css" charset="utf-8" />

    Index (C) »
    UclItkpdConfigurator » Errors
     »
    ComponentTypeError

        <svg width="24" height="24">
          <rect x="0" y="4" width="24" height="4" rx="1" ry="1"></rect>
          <rect x="0" y="12" width="24" height="4" rx="1" ry="1"></rect>
          <rect x="0" y="20" width="24" height="4" rx="1" ry="1"></rect>
        </svg>

Class: UclItkpdConfigurator::Errors::ComponentTypeError

Inherits:

      ConfiguratorAppError

Object

UuCommand::Server::Error::CommandError

ConfiguratorAppError

UclItkpdConfigurator::Errors::ComponentTypeError

        show all

Defined in:

app/ucl_itkpd_configurator/errors/component_type_error.rb

Constant Summary

MODEL_CODE =

'CONFIGURATOR'

MESSAGES =

{
    e001: { message: 'The component type %s is not registered', status: 400 },
    e002: { message: 'The attribute <b>%s</b> is already registered', status: 400 },
    e003: { message: 'The attribute <b>%s</b> does not exist', status: 400 },
    e004: { message: 'The stage <b>%s</b> is already registered', status: 400 },
    e005: { message: 'The stage <b>%s</b> does not exist', status: 400 },
    e006: { message: 'The child component type <b>%s</b> is already added', status: 400 },
    e007: { message: 'The parent component type <b>%s</b> is already referenced', status: 400 },
    e008: { message: 'The child component type <b>%s</b> is not added to the assembly', status: 400 },
    e009: { message: 'The parent component type <b>%s</b> is not referenced', status: 400 },
    e010: { message: 'There is a <b>component type</b> added to the assembly %s', status: 400 },
    e011: { message: 'The component type %s is added to the assembly: <b>%s</b>', status: 400 }
}

Constants inherited
     from ConfiguratorAppError

UclItkpdConfigurator::Errors::ConfiguratorAppError::ERROR_CODE_PREFIX

      Instance Method Summary
      collapse

      #get_error_code(error_code)  ⇒ Object

      #initialize(error_code, *input)  ⇒ ComponentTypeError

    constructor

A new instance of ComponentTypeError.

Methods inherited from ConfiguratorAppError

#_code_to_upcase

Constructor Details

    #initialize(error_code, *input)  ⇒ <tt>ComponentTypeError</tt>

Returns a new instance of ComponentTypeError

9
10
11

# File 'app/ucl_itkpd_configurator/errors/component_type_error.rb', line 9

def initialize(error_code, *input)
  super(error_code, MESSAGES[error_code], MODEL_CODE, *input)
end

Instance Method Details

    #get_error_code(error_code)  ⇒ <tt>Object</tt>

27
28
29

# File 'app/ucl_itkpd_configurator/errors/component_type_error.rb', line 27

def get_error_code(error_code)
  super.get_error_code(MODEL_CODE, error_code)
end

  Generated on Wed Mar  1 21:06:17 2017 by
  yard
  0.9.8 (ruby-2.0.0).


text:
from Scheduler import Scheduler
import logging

class PIDSetting():
    '''Settings for the PID servo algorithm.  These may differ between motors.  The default values are here.

    Distances are in clicks, times in ms, motor power between -255 and +255, the sum of distance is added 20 times/sec.
    Speeds in clicks per second.
    '''
    def __init__(self,distanceMultiplier=0.9,speedMultiplier=0.23,integratedDistanceMultiplier=(0.05/20.0),
                 closeEnoughPosition=4, closeEnoughSpeed=10.0):
        #: Factor for motor power as function of distance - in power units per click distance.
        self.distanceMultiplier = distanceMultiplier
        #: Factor for motor power as function of speed - in power units per (click per millisecond)
        self.speedMultiplier = speedMultiplier
        #: Factor for motor power as a function of the integrated distance - in power units per (click-millisecond)
        self.integratedDistanceMultiplier = integratedDistanceMultiplier
        #: Distance in clicks from the target that we'll accept as got there.
        self.closeEnoughPosition = closeEnoughPosition
        #: Speed that we'll consider as close enough to zero.
        self.closeEnoughSpeed = closeEnoughSpeed

    def __repr__(self):
        return "PID Setting (distanceMultiplier=%3.4f, speedMultiplier=%3.4f, integratedDistanceMultiplier=%3.4f)" % (self.distanceMultiplier,
                                                                        self.speedMultiplier, self.integratedDistanceMultiplier)

class TimePosition():
    "Represents a motor position at a specific time.  Time in milliseconds, position in clicks."
    def __init__(self,time=0.0,position=0):
        #: Time created
        self.time = float(time)
        #: Position at that time
        self.position = int(position)

    def __repr__(self):
        return "TimeDist (%.3f, %d)" % (self.time, self.position)

    def averageSpeedFrom(self, other):
        'Answers the speed in clicks per second coming to this point from other'
        result = 0.0
        if self.time != other.time:
            result = 1000.0 * (self.position - other.position) / (self.time - other.time)
        return result

class Motor():
    '''An NXT motor connected to a BrickPi port.

    A motor is identified by its idChar ('A' through 'D').
    It has a current position, relative to the basePosition it has set, and a current speed.

    It also defines coroutines to position it using the standard PID servo motor algorithm, and
    to run at a specific speed.
    '''
    def timeMillis(self):
        # Answers the current time - member function so we can mock it easily for testing.
        return Scheduler.currentTimeMillis()

    def __init__(self, port, scheduler = None):
        self.port = port
        #: Identifier for the motor
        self.idChar = chr(port + ord('A'))
        self._enabled = False
        self._position = 0
        self._power = 0
        self.pidSetting = PIDSetting()
        self.currentTP = self.previousTP = TimePosition(0, self.timeMillis())
        self.scheduler = scheduler
        self.basePosition = 0

    def setPIDSetting( self, pidSetting ):
        'Sets the parameters for the PID servo motor algorithm'
        self.pidSetting = pidSetting
    def setPower(self, p):
        'Sets the power to be sent to the motor'
        self._power = int(p)
    def power(self):
        'Answers the current power setting'
        return self._power
    def position(self):
        'Answers the current position'
        return self.currentTP.position
    def enabled(self):
        'Answers true if the motor is enabled'
        return self._enabled
    def enable(self, whether):
        'Sets whether the motor is enabled'
        self._enabled = whether

    def zeroPosition(self):
        'Resets the motor base for its position to the current position.'
        self.basePosition += self.position()

    def speed(self):
        'Answers the current speed calculated from the latest two position readings'
        return self.currentTP.averageSpeedFrom( self.previousTP )

    def __repr__(self):
        return "Motor %s (location=%d, speed=%f)" % (self.idChar, self.position(), self.speed())

    def updatePosition(self, newPosition):
        # Called by the framework when the BrickPi provides a new motor position.
        self.previousTP = self.currentTP
        self.currentTP = TimePosition( self.timeMillis(), newPosition - self.basePosition )

    def stopAndDisable(self):
        'Stops and disables the motor'
        self.setPower(0)
        self.enable(False)
        logging.info("Motor %s stopped" % (self.idChar))

    def moveTo( self, *args, **kwargs ):
        'Alternative name for coroutine positionUsingPIDAlgorithm'
        return self.positionUsingPIDAlgorithm( *args, **kwargs )

    def positionUsingPIDAlgorithm( self, target, timeoutMillis = 3000 ):
        'Coroutine to move the motor to position *target*, stopping after *timeoutMillis* if it hasnt reached it yet'
        return self.scheduler.withTimeout( timeoutMillis, self.positionUsingPIDAlgorithmWithoutTimeout( target ) )

    def positionUsingPIDAlgorithmWithoutTimeout( self, target ):
        'Coroutine to move the motor to position *target*, using the PID algorithm with the current PIDSettings'
        distanceIntegratedOverTime = 0 # I bit of PID.
        self.enable(True)
        logging.info( "Motor %s moving to %d" % (self.idChar, target) )
        try:
            while True:
                delta = (target - self.currentTP.position)
                distanceIntegratedOverTime += delta * (self.currentTP.time - self.previousTP.time)
                speed = self.speed()

                if abs(delta) <= self.pidSetting.closeEnoughPosition and abs(speed) < self.pidSetting.closeEnoughSpeed:
                    break # Near enough - finish.

                power = (self.pidSetting.distanceMultiplier * delta
                         - self.pidSetting.speedMultiplier * speed
                         + self.pidSetting.integratedDistanceMultiplier * distanceIntegratedOverTime )
                self.setPower( power )

                yield

        finally:
            self.stopAndDisable()

    def setSpeed( self, targetSpeedInClicksPerSecond, timeoutMillis = 3000 ):
        'Coroutine to run the motor at constant speed *targetSpeedInClicksPerSecond* for time *timeoutMillis*'
        return self.scheduler.withTimeout( timeoutMillis, self.runAtConstantSpeed( targetSpeedInClicksPerSecond ) )

    def runAtConstantSpeed( self, targetSpeedInClicksPerSecond ):
        '''Coroutine to run the motor at constant speed *targetSpeedInClicksPerSecond*
        '''
        # TODO: Algorithm needs work.
        #       Seems to hunt rather than stick at a fixed speed, and magic numbers should be configurable.
        speedErrorMargin = 10
        power = 20.0
        if targetSpeedInClicksPerSecond < 0:
            power = -power
        self.enable(True)
        logging.info( "Motor %s moving at constant speed %.3f" % (self.idChar, targetSpeedInClicksPerSecond) )
        try:
            while abs(targetSpeedInClicksPerSecond - 0.0) > speedErrorMargin: # Don't move if the target speed is zero.
                speed = self.speed()
                if abs(speed - targetSpeedInClicksPerSecond) < speedErrorMargin:
                    pass
                elif abs(speed) < abs(targetSpeedInClicksPerSecond):
                    power *= 1.1
                elif abs(speed) > abs(targetSpeedInClicksPerSecond):
                    power /= 1.1
                self.setPower( power )

                yield

        finally:
            self.stopAndDisable()


text:
package com.facebook.buck.jvm.java;

import com.facebook.buck.android.AndroidPackageable;
import com.facebook.buck.android.AndroidPackageableCollector;
import com.facebook.buck.io.BuckPaths;
import com.facebook.buck.io.ProjectFilesystem;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.model.BuildTargets;
import com.facebook.buck.rules.AbstractBuildRuleWithDeclaredAndExtraDeps;
import com.facebook.buck.rules.AddToRuleKey;
import com.facebook.buck.rules.ArchiveMemberSourcePath;
import com.facebook.buck.rules.BuildContext;
import com.facebook.buck.rules.BuildOutputInitializer;
import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.rules.BuildRuleParams;
import com.facebook.buck.rules.BuildRuleResolver;
import com.facebook.buck.rules.BuildableContext;
import com.facebook.buck.rules.CellPathResolver;
import com.facebook.buck.rules.DefaultBuildTargetSourcePath;
import com.facebook.buck.rules.ExplicitBuildTargetSourcePath;
import com.facebook.buck.rules.ExportDependencies;
import com.facebook.buck.rules.InitializableFromDisk;
import com.facebook.buck.rules.OnDiskBuildInfo;
import com.facebook.buck.rules.SourcePath;
import com.facebook.buck.rules.SourcePathResolver;
import com.facebook.buck.rules.SourcePathRuleFinder;
import com.facebook.buck.rules.TargetGraph;
import com.facebook.buck.rules.keys.SupportsDependencyFileRuleKey;
import com.facebook.buck.rules.keys.SupportsInputBasedRuleKey;
import com.facebook.buck.step.Step;
import com.facebook.buck.util.HumanReadableException;
import com.facebook.buck.util.MoreCollectors;
import com.google.common.base.Preconditions;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedMap;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Sets;
import com.google.common.hash.HashCode;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Optional;
import java.util.Set;
import java.util.SortedSet;
import java.util.function.Predicate;
import javax.annotation.Nullable;

/**
 * Suppose this were a rule defined in src/com/facebook/feed/BUCK:
 *
 *

 * java_library(
 *   name = 'feed',
 *   srcs = [
 *     'FeedStoryRenderer.java',
 *   ],
 *   deps = [
 *     '//src/com/facebook/feed/model:model',
 *     '//third-party/java/guava:guava',
 *   ],
 * )
 *

 *
 * Then this would compile {@code FeedStoryRenderer.java} against Guava and the classes generated
 * from the {@code //src/com/facebook/feed/model:model} rule.
 */
public class DefaultJavaLibrary extends AbstractBuildRuleWithDeclaredAndExtraDeps
    implements JavaLibrary,
        HasClasspathEntries,
        ExportDependencies,
        InitializableFromDisk<JavaLibrary.Data>,
        AndroidPackageable,
        SupportsInputBasedRuleKey,
        SupportsDependencyFileRuleKey,
        JavaLibraryWithTests {

  private static final Path METADATA_DIR = Paths.get("META-INF");

  @AddToRuleKey private final ImmutableSortedSet<SourcePath> srcs;
  @AddToRuleKey private final ImmutableSortedSet<SourcePath> resources;

  @AddToRuleKey(stringify = true)
  private final Optional<Path> resourcesRoot;

  @AddToRuleKey private final Optional<SourcePath> manifestFile;
  @AddToRuleKey private final Optional<String> mavenCoords;
  private final Optional<Path> outputJar;
  private final JarContentsSupplier outputJarContentsSupplier;
  @Nullable private final BuildTarget abiJar;
  @AddToRuleKey private final Optional<SourcePath> proguardConfig;
  @AddToRuleKey private final ImmutableList<String> postprocessClassesCommands;

  // It's very important that these deps are non-ABI rules, even if compiling against ABIs is turned
  // on. This is because various methods in this class perform dependency traversal that rely on
  // these deps being represented as their full-jar dependency form.
  private final SortedSet<BuildRule> fullJarDeclaredDeps;
  private final ImmutableSortedSet<BuildRule> fullJarExportedDeps;
  private final ImmutableSortedSet<BuildRule> fullJarProvidedDeps;

  private final Supplier<ImmutableSet<SourcePath>> outputClasspathEntriesSupplier;
  private final Supplier<ImmutableSet<SourcePath>> transitiveClasspathsSupplier;
  private final Supplier<ImmutableSet<JavaLibrary>> transitiveClasspathDepsSupplier;

  private final boolean trackClassUsage;
  private final ImmutableSortedSet<SourcePath> compileTimeClasspathSourcePaths;

  @AddToRuleKey
  @SuppressWarnings("PMD.UnusedPrivateField")
  private final ZipArchiveDependencySupplier abiClasspath;

  @Nullable private Path depFileRelativePath;

  private final BuildOutputInitializer<Data> buildOutputInitializer;
  private final ImmutableSortedSet<BuildTarget> tests;
  private final Optional<Path> generatedSourceFolder;

  @SuppressWarnings("PMD.UnusedPrivateField")
  @AddToRuleKey
  private final RemoveClassesPatternsMatcher classesToRemoveFromJar;

  private final SourcePathRuleFinder ruleFinder;
  @AddToRuleKey private final CompileToJarStepFactory compileStepFactory;

  public static DefaultJavaLibraryBuilder builder(
      TargetGraph targetGraph,
      BuildTarget buildTarget,
      ProjectFilesystem projectFilesystem,
      BuildRuleParams params,
      BuildRuleResolver buildRuleResolver,
      CellPathResolver cellRoots,
      JavaBuckConfig javaBuckConfig) {
    return new DefaultJavaLibraryBuilder(
        targetGraph,
        buildTarget,
        projectFilesystem,
        params,
        buildRuleResolver,
        cellRoots,
        javaBuckConfig);
  }

  @Override
  public ImmutableSortedSet<BuildTarget> getTests() {
    return tests;
  }

  protected DefaultJavaLibrary(
      BuildTarget buildTarget,
      final ProjectFilesystem projectFilesystem,
      BuildRuleParams params,
      SourcePathResolver resolver,
      SourcePathRuleFinder ruleFinder,
      Set<? extends SourcePath> srcs,
      Set<? extends SourcePath> resources,
      Optional<Path> generatedSourceFolder,
      Optional<SourcePath> proguardConfig,
      ImmutableList<String> postprocessClassesCommands,
      SortedSet<BuildRule> fullJarDeclaredDeps,
      ImmutableSortedSet<BuildRule> fullJarExportedDeps,
      ImmutableSortedSet<BuildRule> fullJarProvidedDeps,
      ImmutableSortedSet<SourcePath> compileTimeClasspathSourcePaths,
      ZipArchiveDependencySupplier abiClasspath,
      @Nullable BuildTarget abiJar,
      boolean trackClassUsage,
      CompileToJarStepFactory compileStepFactory,
      Optional<Path> resourcesRoot,
      Optional<SourcePath> manifestFile,
      Optional<String> mavenCoords,
      ImmutableSortedSet<BuildTarget> tests,
      RemoveClassesPatternsMatcher classesToRemoveFromJar) {
    super(buildTarget, projectFilesystem, params);
    this.ruleFinder = ruleFinder;
    this.compileStepFactory = compileStepFactory;

    // Exported deps are meant to be forwarded onto the CLASSPATH for dependents,
    // and so only make sense for java library types.
    for (BuildRule dep : fullJarExportedDeps) {
      if (!(dep instanceof JavaLibrary)) {
        throw new HumanReadableException(
            buildTarget
                + ": exported dep "
                + dep.getBuildTarget()
                + " ("
                + dep.getType()
                + ") "
                + "must be a type of java library.");
      }
    }

    this.srcs = ImmutableSortedSet.copyOf(srcs);
    this.resources = ImmutableSortedSet.copyOf(resources);
    this.proguardConfig = proguardConfig;
    this.postprocessClassesCommands = postprocessClassesCommands;
    this.fullJarDeclaredDeps = fullJarDeclaredDeps;
    this.fullJarExportedDeps = fullJarExportedDeps;
    this.fullJarProvidedDeps = fullJarProvidedDeps;
    this.compileTimeClasspathSourcePaths = compileTimeClasspathSourcePaths;
    this.resourcesRoot = resourcesRoot;
    this.manifestFile = manifestFile;
    this.mavenCoords = mavenCoords;
    this.tests = tests;

    this.trackClassUsage = trackClassUsage;
    if (this.trackClassUsage) {
      depFileRelativePath = getUsedClassesFilePath(buildTarget, projectFilesystem);
    }
    this.abiClasspath = abiClasspath;
    if (!srcs.isEmpty() || !resources.isEmpty() || manifestFile.isPresent()) {
      this.outputJar = Optional.of(getOutputJarPath(getBuildTarget(), getProjectFilesystem()));
    } else {
      this.outputJar = Optional.empty();
    }
    this.outputJarContentsSupplier = new JarContentsSupplier(resolver, getSourcePathToOutput());
    this.abiJar = abiJar;

    this.outputClasspathEntriesSupplier =
        Suppliers.memoize(
            () ->
                JavaLibraryClasspathProvider.getOutputClasspathJars(
                    DefaultJavaLibrary.this, sourcePathForOutputJar()));

    this.transitiveClasspathsSupplier =
        Suppliers.memoize(
            () ->
                JavaLibraryClasspathProvider.getClasspathsFromLibraries(
                    getTransitiveClasspathDeps()));

    this.transitiveClasspathDepsSupplier =
        Suppliers.memoize(
            () -> JavaLibraryClasspathProvider.getTransitiveClasspathDeps(DefaultJavaLibrary.this));

    this.buildOutputInitializer = new BuildOutputInitializer<>(buildTarget, this);
    this.generatedSourceFolder = generatedSourceFolder;
    this.classesToRemoveFromJar = classesToRemoveFromJar;
  }

  public static Path getOutputJarDirPath(BuildTarget target, ProjectFilesystem filesystem) {
    return BuildTargets.getGenPath(filesystem, target, "lib__%s__output");
  }

  private Optional<SourcePath> sourcePathForOutputJar() {
    return outputJar.map(input -> new ExplicitBuildTargetSourcePath(getBuildTarget(), input));
  }

  static Path getOutputJarPath(BuildTarget target, ProjectFilesystem filesystem) {
    return Paths.get(
        String.format(
            "%s/%s.jar",
            getOutputJarDirPath(target, filesystem), target.getShortNameAndFlavorPostfix()));
  }

  static Path getUsedClassesFilePath(BuildTarget target, ProjectFilesystem filesystem) {
    return getOutputJarDirPath(target, filesystem).resolve("used-classes.json");
  }

  /**
   * @return directory path relative to the project root where .class files will be generated. The
   *     return value does not end with a slash.
   */
  public static Path getClassesDir(BuildTarget target, ProjectFilesystem filesystem) {
    return BuildTargets.getScratchPath(filesystem, target, "lib__%s__classes");
  }

  @Override
  public ImmutableSortedSet<SourcePath> getJavaSrcs() {
    return srcs;
  }

  @Override
  public ImmutableSortedSet<SourcePath> getSources() {
    return srcs;
  }

  @Override
  public ImmutableSortedSet<SourcePath> getResources() {
    return resources;
  }

  @Override
  public Set<BuildRule> getDepsForTransitiveClasspathEntries() {
    return Sets.union(fullJarDeclaredDeps, fullJarExportedDeps);
  }

  @Override
  public ImmutableSet<SourcePath> getTransitiveClasspaths() {
    return transitiveClasspathsSupplier.get();
  }

  @Override
  public ImmutableSet<JavaLibrary> getTransitiveClasspathDeps() {
    return transitiveClasspathDepsSupplier.get();
  }

  @Override
  public ImmutableSet<SourcePath> getImmediateClasspaths() {
    ImmutableSet.Builder<SourcePath> builder = ImmutableSet.builder();

    // Add any exported deps.
    for (BuildRule exported : getExportedDeps()) {
      if (exported instanceof JavaLibrary) {
        builder.addAll(((JavaLibrary) exported).getImmediateClasspaths());
      }
    }

    // Add ourselves to the classpath if there's a jar to be built.
    Optional<SourcePath> sourcePathForOutputJar = sourcePathForOutputJar();
    if (sourcePathForOutputJar.isPresent()) {
      builder.add(sourcePathForOutputJar.get());
    }

    return builder.build();
  }

  @Override
  public ImmutableSet<SourcePath> getOutputClasspaths() {
    return outputClasspathEntriesSupplier.get();
  }

  public ImmutableSortedSet<SourcePath> getCompileTimeClasspathSourcePaths() {
    return compileTimeClasspathSourcePaths;
  }

  @Override
  public Optional<Path> getGeneratedSourcePath() {
    return generatedSourceFolder;
  }

  @Override
  public SortedSet<BuildRule> getExportedDeps() {
    return fullJarExportedDeps;
  }

  /**
   * Building a java_library() rule entails compiling the .java files specified in the srcs
   * attribute. They are compiled into a directory under {@link BuckPaths#getScratchDir()}.
   */
  @Override
  public final ImmutableList<Step> getBuildSteps(
      BuildContext context, BuildableContext buildableContext) {
    ImmutableList.Builder<Step> steps = ImmutableList.builder();
    BuildTarget buildTarget = this.getBuildTarget();
    ProjectFilesystem projectFilesystem = this.getProjectFilesystem();
    JavaLibraryRules.addCompileToJarSteps(
        buildTarget,
        projectFilesystem,
        context,
        buildableContext,
        outputJar,
        ruleFinder,
        srcs,
        resources,
        postprocessClassesCommands,
        compileTimeClasspathSourcePaths,
        trackClassUsage,
        depFileRelativePath,
        compileStepFactory,
        resourcesRoot,
        manifestFile,
        classesToRemoveFromJar,
        steps);

    JavaLibraryRules.addAccumulateClassNamesStep(
        buildTarget, projectFilesystem, getSourcePathToOutput(), buildableContext, context, steps);

    return steps.build();
  }

  @Override
  public ImmutableSortedSet<SourcePath> getJarContents() {
    return outputJarContentsSupplier.get();
  }

  /** Instructs this rule to report the ABI it has on disk as its current ABI. */
  @Override
  public JavaLibrary.Data initializeFromDisk(OnDiskBuildInfo onDiskBuildInfo) throws IOException {
    // Warm up the jar contents. We just wrote the thing, so it should be in the filesystem cache
    outputJarContentsSupplier.load();
    return JavaLibraryRules.initializeFromDisk(
        getBuildTarget(), getProjectFilesystem(), onDiskBuildInfo);
  }

  @Override
  public BuildOutputInitializer<Data> getBuildOutputInitializer() {
    return buildOutputInitializer;
  }

  @Override
  public final Optional<BuildTarget> getAbiJar() {
    return Optional.ofNullable(abiJar);
  }

  @Override
  public ImmutableSortedMap<String, HashCode> getClassNamesToHashes() {
    return buildOutputInitializer.getBuildOutput().getClassNamesToHashes();
  }

  @Override
  @Nullable
  public SourcePath getSourcePathToOutput() {
    return outputJar.map(o -> new ExplicitBuildTargetSourcePath(getBuildTarget(), o)).orElse(null);
  }

  @Override
  public Iterable<AndroidPackageable> getRequiredPackageables() {
    return AndroidPackageableCollector.getPackageableRules(
        ImmutableSortedSet.copyOf(
            Sets.difference(
                Sets.union(fullJarDeclaredDeps, fullJarExportedDeps), fullJarProvidedDeps)));
  }

  @Override
  public Optional<String> getMavenCoords() {
    return mavenCoords;
  }

  @Override
  public void addToCollector(AndroidPackageableCollector collector) {
    SourcePath output = getSourcePathToOutput();
    if (output != null) {
      collector.addClasspathEntry(this, output);
    }
    if (proguardConfig.isPresent()) {
      collector.addProguardConfig(getBuildTarget(), proguardConfig.get());
    }
  }

  @Override
  public boolean useDependencyFileRuleKeys() {
    return !getJavaSrcs().isEmpty() && trackClassUsage;
  }

  @Override
  public Predicate<SourcePath> getCoveredByDepFilePredicate(SourcePathResolver pathResolver) {
    // a hash set is intentionally used to achieve constant time look-up
    return abiClasspath.getArchiveMembers(pathResolver).collect(MoreCollectors.toImmutableSet())
        ::contains;
  }

  @Override
  public Predicate<SourcePath> getExistenceOfInterestPredicate(SourcePathResolver pathResolver) {
    // Annotation processors might enumerate all files under a certain path and then generate
    // code based on that list (without actually reading the files), making the list of files
    // itself a used dependency that must be part of the dependency-based key. We don't
    // currently have the instrumentation to detect such enumeration perfectly, but annotation
    // processors are most commonly looking for files under META-INF, so as a stopgap we add
    // the listing of META-INF to the rule key.
    return (SourcePath path) ->
        (path instanceof ArchiveMemberSourcePath)
            && pathResolver
                .getRelativeArchiveMemberPath(path)
                .getMemberPath()
                .startsWith(METADATA_DIR);
  }

  @Override
  public ImmutableList<SourcePath> getInputsAfterBuildingLocally(
      BuildContext context, CellPathResolver cellPathResolver) throws IOException {
    Preconditions.checkState(useDependencyFileRuleKeys());
    return DefaultClassUsageFileReader.loadFromFile(
        getProjectFilesystem(),
        cellPathResolver,
        getProjectFilesystem()
            .getPathForRelativePath(Preconditions.checkNotNull(depFileRelativePath)),
        getDepOutputPathToAbiSourcePath(context.getSourcePathResolver()));
  }

  private ImmutableMap<Path, SourcePath> getDepOutputPathToAbiSourcePath(
      SourcePathResolver pathResolver) {
    ImmutableMap.Builder<Path, SourcePath> pathToSourcePathMapBuilder = ImmutableMap.builder();
    for (SourcePath sourcePath : compileTimeClasspathSourcePaths) {
      BuildRule rule = ruleFinder.getRule(sourcePath).get();
      Path path = pathResolver.getAbsolutePath(sourcePath);
      if (rule instanceof HasJavaAbi) {
        if (((HasJavaAbi) rule).getAbiJar().isPresent()) {
          BuildTarget buildTarget = ((HasJavaAbi) rule).getAbiJar().get();
          pathToSourcePathMapBuilder.put(path, new DefaultBuildTargetSourcePath(buildTarget));
        }
      } else if (rule instanceof CalculateAbi) {
        pathToSourcePathMapBuilder.put(path, sourcePath);
      }
    }
    return pathToSourcePathMapBuilder.build();
  }
}