text:
namespace lld {
namespace mach_o {

///
/// The ArchHandler class handles all architecture specific aspects of
/// mach-o linking.
///
class ArchHandler {
public:
  virtual ~ArchHandler();

  /// There is no public interface to subclasses of ArchHandler, so this
  /// is the only way to instantiate an ArchHandler.
  static std::unique_ptr<ArchHandler> create(MachOLinkingContext::Arch arch);

  /// Get (arch specific) kind strings used by Registry.
  virtual const Registry::KindStrings *kindStrings() = 0;

  /// Convert mach-o Arch to Reference::KindArch.
  virtual Reference::KindArch kindArch() = 0;

  /// Used by StubPass to update References to shared library functions
  /// to be references to a stub.
  virtual bool isCallSite(const Reference &) = 0;

  /// Used by GOTPass to locate GOT References
  virtual bool isGOTAccess(const Reference &, bool &canBypassGOT) {
    return false;
  }

  /// Used by TLVPass to locate TLV References.
  virtual bool isTLVAccess(const Reference &) const { return false; }

  /// Used by the TLVPass to update TLV References.
  virtual void updateReferenceToTLV(const Reference *) {}

  /// Used by ShimPass to insert shims in branches that switch mode.
  virtual bool isNonCallBranch(const Reference &) = 0;

  /// Used by GOTPass to update GOT References
  virtual void updateReferenceToGOT(const Reference *, bool targetIsNowGOT) {}

  /// Does this architecture make use of __unwind_info sections for exception
  /// handling? If so, it will need a separate pass to create them.
  virtual bool needsCompactUnwind() = 0;

  /// Returns the kind of reference to use to synthesize a 32-bit image-offset
  /// value, used in the __unwind_info section.
  virtual Reference::KindValue imageOffsetKind() = 0;

  /// Returns the kind of reference to use to synthesize a 32-bit image-offset
  /// indirect value. Used for personality functions in the __unwind_info
  /// section.
  virtual Reference::KindValue imageOffsetKindIndirect() = 0;

  /// Architecture specific compact unwind type that signals __eh_frame should
  /// actually be used.
  virtual uint32_t dwarfCompactUnwindType() = 0;

  /// Reference from an __eh_frame CIE atom to its personality function it's
  /// describing. Usually pointer-sized and PC-relative, but differs in whether
  /// it needs to be in relocatable objects.
  virtual Reference::KindValue unwindRefToPersonalityFunctionKind() = 0;

  /// Reference from an __eh_frame FDE to the CIE it's based on.
  virtual Reference::KindValue unwindRefToCIEKind() = 0;

  /// Reference from an __eh_frame FDE atom to the function it's
  /// describing. Usually pointer-sized and PC-relative, but differs in whether
  /// it needs to be in relocatable objects.
  virtual Reference::KindValue unwindRefToFunctionKind() = 0;

  /// Reference from an __unwind_info entry of dwarfCompactUnwindType to the
  /// required __eh_frame entry. On current architectures, the low 24 bits
  /// represent the offset of the function's FDE entry from the start of
  /// __eh_frame.
  virtual Reference::KindValue unwindRefToEhFrameKind() = 0;

  /// Returns a pointer sized reference kind.  On 64-bit targets this will
  /// likely be something like pointer64, and pointer32 on 32-bit targets.
  virtual Reference::KindValue pointerKind() = 0;

  virtual const Atom *fdeTargetFunction(const DefinedAtom *fde);

  /// Used by normalizedFromAtoms() to know where to generated rebasing and
  /// binding info in final executables.
  virtual bool isPointer(const Reference &) = 0;

  /// Used by normalizedFromAtoms() to know where to generated lazy binding
  /// info in final executables.
  virtual bool isLazyPointer(const Reference &);

  /// Reference from an __stub_helper entry to the required offset of the
  /// lazy bind commands.
  virtual Reference::KindValue lazyImmediateLocationKind() = 0;

  /// Returns true if the specified relocation is paired to the next relocation.
  virtual bool isPairedReloc(const normalized::Relocation &) = 0;

  /// Prototype for a helper function.  Given a sectionIndex and address,
  /// finds the atom and offset with that atom of that address.
  typedef std::function<llvm::Error (uint32_t sectionIndex, uint64_t addr,
                        const lld::Atom **, Reference::Addend *)>
                        FindAtomBySectionAndAddress;

  /// Prototype for a helper function.  Given a symbolIndex, finds the atom
  /// representing that symbol.
  typedef std::function<llvm::Error (uint32_t symbolIndex,
                        const lld::Atom **)> FindAtomBySymbolIndex;

  /// Analyzes a relocation from a .o file and returns the info
  /// (kind, target, addend) needed to instantiate a Reference.
  /// Two helper functions are passed as parameters to find the target atom
  /// given a symbol index or address.
  virtual llvm::Error
          getReferenceInfo(const normalized::Relocation &reloc,
                           const DefinedAtom *inAtom,
                           uint32_t offsetInAtom,
                           uint64_t fixupAddress, bool isBigEndian,
                           FindAtomBySectionAndAddress atomFromAddress,
                           FindAtomBySymbolIndex atomFromSymbolIndex,
                           Reference::KindValue *kind,
                           const lld::Atom **target,
                           Reference::Addend *addend) = 0;

  /// Analyzes a pair of relocations from a .o file and returns the info
  /// (kind, target, addend) needed to instantiate a Reference.
  /// Two helper functions are passed as parameters to find the target atom
  /// given a symbol index or address.
  virtual llvm::Error
      getPairReferenceInfo(const normalized::Relocation &reloc1,
                           const normalized::Relocation &reloc2,
                           const DefinedAtom *inAtom,
                           uint32_t offsetInAtom,
                           uint64_t fixupAddress, bool isBig, bool scatterable,
                           FindAtomBySectionAndAddress atomFromAddress,
                           FindAtomBySymbolIndex atomFromSymbolIndex,
                           Reference::KindValue *kind,
                           const lld::Atom **target,
                           Reference::Addend *addend) = 0;

  /// Prototype for a helper function.  Given an atom, finds the symbol table
  /// index for it in the output file.
  typedef std::function<uint32_t (const Atom &atom)> FindSymbolIndexForAtom;

  /// Prototype for a helper function.  Given an atom, finds the index
  /// of the section that will contain the atom.
  typedef std::function<uint32_t (const Atom &atom)> FindSectionIndexForAtom;

  /// Prototype for a helper function.  Given an atom, finds the address
  /// assigned to it in the output file.
  typedef std::function<uint64_t (const Atom &atom)> FindAddressForAtom;

  /// Some architectures require local symbols on anonymous atoms.
  virtual bool needsLocalSymbolInRelocatableFile(const DefinedAtom *atom) {
    return false;
  }

  /// Copy raw content then apply all fixup References on an Atom.
  virtual void generateAtomContent(const DefinedAtom &atom, bool relocatable,
                                   FindAddressForAtom findAddress,
                                   FindAddressForAtom findSectionAddress,
                                   uint64_t imageBaseAddress,
                          llvm::MutableArrayRef<uint8_t> atomContentBuffer) = 0;

  /// Used in -r mode to convert a Reference to a mach-o relocation.
  virtual void appendSectionRelocations(const DefinedAtom &atom,
                                        uint64_t atomSectionOffset,
                                        const Reference &ref,
                                        FindSymbolIndexForAtom,
                                        FindSectionIndexForAtom,
                                        FindAddressForAtom,
                                        normalized::Relocations&) = 0;

  /// Add arch-specific References.
  virtual void addAdditionalReferences(MachODefinedAtom &atom) { }

  // Add Reference for data-in-code marker.
  virtual void addDataInCodeReference(MachODefinedAtom &atom, uint32_t atomOff,
                                      uint16_t length, uint16_t kind) { }

  /// Returns true if the specificed Reference value marks the start or end
  /// of a data-in-code range in an atom.
  virtual bool isDataInCodeTransition(Reference::KindValue refKind) {
    return false;
  }

  /// Returns the Reference value for a Reference that marks that start of
  /// a data-in-code range.
  virtual Reference::KindValue dataInCodeTransitionStart(
                                                const MachODefinedAtom &atom) {
    return 0;
  }

  /// Returns the Reference value for a Reference that marks that end of
  /// a data-in-code range.
  virtual Reference::KindValue dataInCodeTransitionEnd(
                                                const MachODefinedAtom &atom) {
    return 0;
  }

  /// Only relevant for 32-bit arm archs.
  virtual bool isThumbFunction(const DefinedAtom &atom) { return false; }

  /// Only relevant for 32-bit arm archs.
  virtual const DefinedAtom *createShim(MachOFile &file, bool thumbToArm,
                                        const DefinedAtom &) {
    llvm_unreachable("shims only support on arm");
  }

  /// Does a given unwind-cfi atom represent a CIE (as opposed to an FDE).
  static bool isDwarfCIE(bool isBig, const DefinedAtom *atom);

  struct ReferenceInfo {
    Reference::KindArch arch;
    uint16_t            kind;
    uint32_t            offset;
    int32_t             addend;
  };

  struct OptionalRefInfo {
    bool                used;
    uint16_t            kind;
    uint32_t            offset;
    int32_t             addend;
  };

  /// Table of architecture specific information for creating stubs.
  struct StubInfo {
    const char*     binderSymbolName;
    ReferenceInfo   lazyPointerReferenceToHelper;
    ReferenceInfo   lazyPointerReferenceToFinal;
    ReferenceInfo   nonLazyPointerReferenceToBinder;
    uint8_t         codeAlignment;

    uint32_t        stubSize;
    uint8_t         stubBytes[16];
    ReferenceInfo   stubReferenceToLP;
    OptionalRefInfo optStubReferenceToLP;

    uint32_t        stubHelperSize;
    uint8_t         stubHelperBytes[16];
    ReferenceInfo   stubHelperReferenceToImm;
    ReferenceInfo   stubHelperReferenceToHelperCommon;

    DefinedAtom::ContentType stubHelperImageCacheContentType;

    uint32_t        stubHelperCommonSize;
    uint8_t         stubHelperCommonAlignment;
    uint8_t         stubHelperCommonBytes[36];
    ReferenceInfo   stubHelperCommonReferenceToCache;
    OptionalRefInfo optStubHelperCommonReferenceToCache;
    ReferenceInfo   stubHelperCommonReferenceToBinder;
    OptionalRefInfo optStubHelperCommonReferenceToBinder;
  };

  virtual const StubInfo &stubInfo() = 0;

protected:
  ArchHandler();

  static std::unique_ptr<mach_o::ArchHandler> create_x86_64();
  static std::unique_ptr<mach_o::ArchHandler> create_x86();
  static std::unique_ptr<mach_o::ArchHandler> create_arm();
  static std::unique_ptr<mach_o::ArchHandler> create_arm64();

  // Handy way to pack mach-o r_type and other bit fields into one 16-bit value.
  typedef uint16_t RelocPattern;
  enum {
    rScattered = 0x8000,
    rPcRel     = 0x4000,
    rExtern    = 0x2000,
    rLength1   = 0x0000,
    rLength2   = 0x0100,
    rLength4   = 0x0200,
    rLength8   = 0x0300,
    rLenArmLo  = rLength1,
    rLenArmHi  = rLength2,
    rLenThmbLo = rLength4,
    rLenThmbHi = rLength8
  };
  /// Extract RelocPattern from normalized mach-o relocation.
  static RelocPattern relocPattern(const normalized::Relocation &reloc);
  /// Create normalized Relocation initialized from pattern.
  static normalized::Relocation relocFromPattern(RelocPattern pattern);
  /// One liner to add a relocation.
  static void appendReloc(normalized::Relocations &relocs, uint32_t offset,
                          uint32_t symbol, uint32_t value,
                          RelocPattern pattern);

  static int16_t  readS16(const uint8_t *addr, bool isBig);
  static int32_t  readS32(const uint8_t *addr, bool isBig);
  static uint32_t readU32(const uint8_t *addr, bool isBig);
  static int64_t  readS64(const uint8_t *addr, bool isBig);
};

} // namespace mach_o
} // namespace lld

#endif // LLD_READER_WRITER_MACHO_ARCH_HANDLER_H


text:
package org.jbehave.core.embedder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.jbehave.core.model.Meta;
import org.jbehave.core.model.Scenario;
import org.jbehave.core.model.Story;
import org.jbehave.core.model.StoryMap;
import org.jbehave.core.model.StoryMaps;

/**
 * Maps {@link Story}s by a {@link MetaFilter}.
 *
 * @author Mauro Talevi
 */
public class StoryMapper {

    private Map<String, Set<Story>> map = new HashMap<>();

    /**
     * Maps a story if it is allowed by the meta filter
     *
     * @param story
     *            the Story
     * @param metaFilter
     *            the meta filter
     */
    public void map(Story story, MetaFilter metaFilter) {
        if (metaFilter.allow(story.getMeta())) {
            boolean allowed = false;
            for (Scenario scenario : story.getScenarios()) {
                // scenario also inherits meta from story
                Meta inherited = scenario.getMeta().inheritFrom(story.getMeta());
                if (metaFilter.allow(inherited)) {
                    allowed = true;
                    break;
                }
            }
            if (allowed) {
                add(metaFilter.asString(), story);
            }
        }
    }

    public StoryMap getStoryMap(String filter) {
        return new StoryMap(filter, storiesFor(filter));
    }

    public StoryMaps getStoryMaps() {
        List<StoryMap> maps = new ArrayList<>();
        for (String filter : map.keySet()) {
            maps.add(getStoryMap(filter));
        }
        return new StoryMaps(maps);
    }

    private void add(String filter, Story story) {
        storiesFor(filter).add(story);
    }

    private Set<Story> storiesFor(String filter) {
        Set<Story> stories = map.get(filter);
        if (stories == null) {
            stories = new HashSet<>();
            map.put(filter, stories);
        }
        return stories;
    }

    @Override
    public String toString() {
        return this.getClass().getSimpleName();
    }

}

redpajama_set_name: RedPajamaGithub


text:
module Blacklight::SearchHistoryConstraintsHelperBehavior

  # Simpler textual version of constraints, used on Search History page.
  # Theoretically can may be DRY'd up with results page render_constraints,
  # maybe even using the very same HTML with different CSS?
  # But too tricky for now, too many changes to existing CSS. TODO.
  def render_search_to_s(params)
    render_search_to_s_q(params) +
    render_search_to_s_filters(params)
  end

  ##
  # Render the search query constraint
  def render_search_to_s_q(params)
    return "".html_safe if params['q'].blank?

    label = (default_search_field && params[:search_field] == default_search_field[:key]) ?
      nil :
      label_for_search_field(params[:search_field])

    render_search_to_s_element(label , render_filter_value(params['q']) )
  end

  ##
  # Render the search facet constraints
  def render_search_to_s_filters(params)
    return "".html_safe unless params[:f]

    safe_join(params[:f].collect do |facet_field, value_list|
      render_search_to_s_element(facet_field_label(facet_field),
        safe_join(value_list.collect do |value|
          render_filter_value(value, facet_field)
        end, content_tag(:span, " #{t('blacklight.and')} ", :class =>'filterSeparator'))
      )
    end, " \n ")
  end

  # value can be Array, in which case elements are joined with
  # 'and'.   Pass in option :escape_value => false to pass in pre-rendered
  # html for value. key with escape_key if needed.
  def render_search_to_s_element(key, value, options = {})
    content_tag(:span, render_filter_name(key) + content_tag(:span, value, :class => 'filterValues'), :class => 'constraint')
  end

  ##
  # Render the name of the facet
  def render_filter_name name
    return "".html_safe if name.blank?
    content_tag(:span, t('blacklight.search.filters.label', :label => name), :class => 'filterName')
  end

  ##
  # Render the value of the facet
  def render_filter_value value, key = nil
    display_value = value
    display_value = facet_display_value(key, value) if key
    content_tag(:span, h(display_value), :class => 'filterValue')
  end

end


text:
<?php

namespace GraphAware\Neo4j\OGM\Metadata\Factory\Xml;

use GraphAware\Neo4j\OGM\Annotations\Label;
use GraphAware\Neo4j\OGM\Exception\MappingException;
use GraphAware\Neo4j\OGM\Metadata\EntityPropertyMetadata;
use GraphAware\Neo4j\OGM\Metadata\LabeledPropertyMetadata;
use GraphAware\Neo4j\OGM\Metadata\PropertyAnnotationMetadata;

class PropertyXmlMetadataFactory
{
    /**
     * @param \SimpleXMLElement $node
     * @param string            $className
     * @param \ReflectionClass  $reflection
     *
     * @return array
     */
    public function buildPropertiesMetadata(\SimpleXMLElement $node, $className, \ReflectionClass $reflection)
    {
        $properties = [];
        foreach ($node->property as $propertyNode) {
            $properties[] = $this->buildPropertyMetadata($propertyNode, $className, $reflection);
            if (isset($propertyNode->label)) {
                $properties[] = $this->buildLabeledPropertyMetadata($propertyNode, $className, $reflection);
            }
        }

        return $properties;
    }

    /**
     * @param \SimpleXMLElement $propertyNode
     * @param string            $className
     * @param \ReflectionClass  $reflection
     *
     * @return EntityPropertyMetadata
     */
    private function buildPropertyMetadata(\SimpleXMLElement $propertyNode, $className, \ReflectionClass $reflection)
    {
        if (!isset($propertyNode['name']) || !isset($propertyNode['type'])) {
            throw new MappingException(
                sprintf('Class "%s" OGM XML property configuration is missing "name" or "type" attribute', $className)
            );
        }
        $name = (string) $propertyNode['name'];
        $nullable = true;
        if (isset($propertyNode['nullable'])) {
            if ((string) $propertyNode['nullable'] === 'true') {
                $nullable = true;
            }
            if ((string) $propertyNode['nullable'] === 'false') {
                $nullable = false;
            }
        }

        return new EntityPropertyMetadata(
            $name,
            $reflection->getProperty($name),
            new PropertyAnnotationMetadata(
                (string) $propertyNode['type'],
                isset($propertyNode['key']) ? (string) $propertyNode['key'] : null,
                $nullable
            )
        );
    }

    /**
     * @param \SimpleXMLElement $propertyNode
     * @param string            $className
     * @param \ReflectionClass  $reflection
     *
     * @return LabeledPropertyMetadata
     */
    private function buildLabeledPropertyMetadata(
        \SimpleXMLElement $propertyNode,
        $className,
        \ReflectionClass $reflection
    ) {
        if (!isset($propertyNode->label['name'])) {
            throw new MappingException(
                sprintf('Class "%s" OGM XML property label configuration is missing "name" attribute', $className)
            );
        }

        $name = (string) $propertyNode['name'];
        $label = new Label();
        $label->name = (string) $propertyNode->label['name'];

        return new LabeledPropertyMetadata(
            $name,
            $reflection->getProperty($name),
            $label
        );
    }
}


text:
import java.util.*;

/**
 * This class maintains a queue of events used for
 * simulating the behaviour of the system. Events are
 * kept in a cronologically sorted list. This class is
 * an example of a priority queue (event time being the
 * priority in this case).
 */
public class EventQueue
{
	/** The list of events */
	private ArrayList events;

	/**
	 * Creates a new Event Queue.
	 */
	public EventQueue() {
		events = new ArrayList();
	}

	/**
	 * Inserts an event in the queue.
	 * The event is added to the event list, which
	 * is then resorted.
	 * @param event	The event to be inserted.
	 */
    public void insertEvent(Event event) {
		if(event != null) {
			events.add(event);
			Collections.sort(events);
		}
    }

	/**
	 * Removes and returns the earliest event (the event
	 * with the lowest time value) from the queue.
	 * @return	The event with the lowest time value in the queue.
	 */
    public Event getNextEvent() {
		  return (Event)events.remove(0);
    }

    /**
     * Checks whether or not the event queue is empty.
     * @return	Whether or not the event queue is empty.
     */
    public boolean isEmpty() {
		return events.size() == 0;
	}
}


text:
// CyTargetLinker,
// a Cytoscape plugin to extend biological networks with regulatory interactions and other relationships
//
// Copyright 2011-2018 Department of Bioinformatics - BiGCaT, Maastricht University
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package org.cytargetlinker.app.internal.io;

import java.io.File;
import java.io.FileInputStream;
import java.util.Set;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.cytargetlinker.app.internal.data.LinkSet;
import org.cytargetlinker.app.internal.data.Direction;
import org.cytargetlinker.app.internal.data.Result;
import org.xml.sax.InputSource;
import org.xml.sax.helpers.ParserAdapter;

/**
 *
 * @author mkutmon
 * sets up the cytargetlinker parser to extract interactions from one datasource file
 *
 */
public class XgmmlParser {

	public Result parseXgmmlFile(File file, Set<String> nodeIds, Direction dir, LinkSet ds) {
		Result res = new Result();
		try {
			SAXParserFactory spf = SAXParserFactory.newInstance();
			SAXParser sp = spf.newSAXParser();
			ParserAdapter pa = new ParserAdapter(sp.getParser());
			CyTargetLinkerParser parser = new CyTargetLinkerParser(nodeIds, dir, ds);
			pa.setContentHandler(parser);
			pa.parse(new InputSource(new FileInputStream(file)));

			res.setLinkSetName(parser.getNetworkName());
			res.setDirection(dir);
			if(parser.getNetworkAttr().containsKey("url")) {
				res.setLinkSetURL(parser.getNetworkAttr().get("url"));
			}
			if(parser.getNetworkAttr().containsKey("type")) {
				res.setLinkSetType(parser.getNetworkAttr().get("type"));
			}

			res.getEdges().addAll(parser.getEdgeList());

			parser.clean();
		} catch(Exception e) {
			e.printStackTrace();
		}
		return res;
	}

}


text:
/*
 * FRC 4931 (http://www.evilletech.com)
 *
 * Open source software. Licensed under the FIRST BSD license file in the
 * root directory of this project's Git repository.
 */
package org.frc4931.robot.commandnew.auto;

import java.util.function.Supplier;

import org.frc4931.robot.commandnew.CommandGroup;
import org.frc4931.robot.commandnew.grabber.CloseGrabber;
import org.frc4931.robot.commandnew.grabber.MoveGrabberToGround;
import org.frc4931.robot.commandnew.grabber.MoveGrabberToStep;
import org.frc4931.robot.commandnew.guardrail.CloseGuardrail;
import org.frc4931.robot.commandnew.ramplifter.LowerRamp;
import org.frc4931.robot.component.Counter;
import org.frc4931.robot.system.DriveInterpreter;
import org.frc4931.robot.system.Superstructure;

import com.ni.vision.NIVision.Image;

public class AutoMode extends CommandGroup{
    public AutoMode(DriveInterpreter drive, Superstructure structure, Supplier<Image> eyes, Counter totes) {
        totes.increase();
        sequentially(
                     // Grab can in guardrails
                     new Drive(drive, 0.6, 0.65),
                     new CloseGuardrail(structure.ramp.rail),
                     new Pause(0.4),
                     new LowerRamp(structure.ramp.lifter),
                     new Pause(1.5),
                     // Put kicker under can
//                     new MoveKickerToTransfer(structure.kickerSystem.kicker),

                     // Transfer from guardrail to kicker
//                     fork(sequentially(
//                         new OpenGuardrail(structure.ramp.rail),
//                         new Pause(1),
//                         new MoveKickerToGuardrail(structure.kickerSystem.kicker),
//                         new CloseGuardrail(structure.ramp.rail))
//                     ),
//                     // Reset kicker and turn towards yellow tote
                     new Drive(drive, -0.6, 0.95),

                     // Turn TO Tote
                     new Turn(drive, -1, 0.26),
                     new Drive(drive, 0.8, 0.85),
//
//                     // Grab yellow tote with grabbers
                     new CloseGrabber(structure.grabber),
                     new Pause(0.25),
                     fork(new MoveGrabberToStep(structure.grabber)),
//                     new MoveGrabberToStep(structure.grabber),
                     new Turn(drive, 1, 0.425),
                     new Drive(drive, -0.7, 2.5),
                     new Turn(drive, 1, 1.75),
                     new Drive(drive, 0,0.1),
                     new MoveGrabberToGround(structure.grabber)
//                     new OpenGuardrail(structure.ramp.rail),
//                     new RaiseRamp(structure.ramp.lifter)
//                     new Drive(drive, -0.75, 3)
                     );
    }
}


text:
namespace Algorytm_wieżowy
{
    internal class Sample
    {
        public int[] Cells = new int[Globals.GridSize];
        public string Digit;
    }
}


text:
define([
	"doh/runner",
	"dojo/_base/sniff",
	"../../../equals",
	"../../StatefulModelOptions"
], function(doh, has){
	try{
		var userArgs = window.location.search.replace(/[\?&](dojoUrl|testUrl|testModule)=[^&]*/g, "").replace(/^&/, "?");

		// only run the regression Robot tests
		if(!has("ie")){
			// Hit an error with the mobile parser with IE, need to investigate more
			doh.registerUrl("dojox.mvc.tests.regression.robot.mobile-demo-test", dojo.moduleUrl("dojox.mvc","tests/regression/robot/mobile-demo-test.html"+userArgs), 999999);
			doh.registerUrl("dojox.mvc.tests.regression.robot.android_repeat-ins", dojo.moduleUrl("dojox.mvc","tests/regression/robot/android_repeat-ins.html"+userArgs), 999999);
		}
		doh.registerUrl("dojox.mvc.tests.regression.robot.mvc_shipto-billto-simple", dojo.moduleUrl("dojox.mvc","tests/regression/robot/mvc_shipto-billto-simple.html"+userArgs), 999999);
		doh.registerUrl("dojox.mvc.tests.regression.robot.mvc_generate-view", dojo.moduleUrl("dojox.mvc","tests/regression/robot/mvc_generate-view.html"+userArgs), 999999);
		doh.registerUrl("dojox.mvc.tests.regression.robot.mvc_loan-stateful", dojo.moduleUrl("dojox.mvc","tests/regression/robot/mvc_loan-stateful.html"+userArgs), 999999);
		doh.registerUrl("dojox.mvc.tests.regression.robot.mvc_ref-set-repeat", dojo.moduleUrl("dojox.mvc","tests/regression/robot/mvc_ref-set-repeat.html"+userArgs), 999999);
		doh.registerUrl("dojox.mvc.tests.regression.robot.mvc_search-results-repeat", dojo.moduleUrl("dojox.mvc","tests/regression/robot/mvc_search-results-repeat.html"+userArgs), 999999);
		doh.registerUrl("dojox.mvc.tests.regression.robot.mvc_search-results-ins-del", dojo.moduleUrl("dojox.mvc","tests/regression/robot/mvc_search-results-ins-del.html"+userArgs), 999999);
		doh.registerUrl("dojox.mvc.tests.regression.robot.iphone_shipto-billto", dojo.moduleUrl("dojox.mvc","tests/regression/robot/iphone_shipto-billto.html"+userArgs), 999999);
		doh.registerUrl("dojox.mvc.tests.regression.robot.mvc_shipto-billto-hierarchical", dojo.moduleUrl("dojox.mvc","tests/regression/robot/mvc_shipto-billto-hierarchical.html"+userArgs), 999999);
	}catch(e){
		doh.debug(e);
	}
});


text:
package com.caibowen.gplume.web.actions;

import com.caibowen.gplume.web.RequestContext;

import java.lang.invoke.MethodHandle;
import java.lang.reflect.Method;

/**
 *
 *
 * public void action(Date date, RequestContext context) {
 * 		context.render("xxx.jsp");
 * }
 * returns void, must has requestContext
 * @author BowenCai
 *
 */
public class RestAction extends SimpleAction {

	private static final long serialVersionUID = 7479824844662522176L;

	final PathValResolver pathResolver;
	final boolean inMethodCall;

	public RestAction(String uri, MethodHandle handle, Method _m, boolean call, PathValResolver pr) {

		super(uri, handle, _m);
		pathResolver = pr;
		inMethodCall = call;
	}

	@Override
	public void perform(RequestContext requestContext) throws Throwable {

		Object var = pathResolver.resolveAndCast(requestContext.path, null);

		requestContext.putAttr(ACTION_NAME, this);

		if (inMethodCall) {
			methodHandle.invoke(var, requestContext);
		} else {
			requestContext.putAttr(pathResolver.getArgName(), var);
			methodHandle.invoke(requestContext);
		}
	}

}


text:
"""Read CIFAR-10 data from pickled numpy arrays and writes TFRecords.

Generates tf.train.Example protos and writes them to TFRecord files from the
python version of the CIFAR-10 dataset downloaded from
https://www.cs.toronto.edu/~kriz/cifar.html.

Based on script from
https://github.com/tensorflow/models/blob/master/tutorials/image/cifar10_estimator/generate_cifar10_tfrecords.py

To run:
  python generate_cifar10_tfrecords.py --data_dir=/tmp/cifar-tfrecord
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import argparse
import os
import sys

import tarfile
from six.moves import cPickle as pickle
import tensorflow as tf

CIFAR_FILENAME = 'cifar-10-python.tar.gz'
CIFAR_DOWNLOAD_URL = 'https://www.cs.toronto.edu/~kriz/' + CIFAR_FILENAME
CIFAR_LOCAL_FOLDER = 'cifar-10-batches-py'

def download_and_extract(data_dir):
  # download CIFAR-10 if not already downloaded.
  tf.contrib.learn.datasets.base.maybe_download(CIFAR_FILENAME, data_dir,
                                                CIFAR_DOWNLOAD_URL)
  tarfile.open(os.path.join(data_dir, CIFAR_FILENAME),
               'r:gz').extractall(data_dir)

def _int64_feature(value):
  return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))

def _bytes_feature(value):
  return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))

def _get_file_names():
  """Returns the file names expected to exist in the input_dir."""
  file_names = {}
  for i in range(1, 5):
    file_names['train_%d' % i] = 'data_batch_%d' % i
  file_names['validation'] = 'data_batch_5'
  file_names['test'] = 'test_batch'
  return file_names

def read_pickle_from_file(filename):
  with tf.gfile.Open(filename, 'rb') as f:
    if sys.version_info >= (3, 0):
      data_dict = pickle.load(f, encoding='bytes')
    else:
      data_dict = pickle.load(f)
  return data_dict

def convert_to_tfrecord(input_file, output_file):
  """Converts a file to TFRecords."""
  print('Generating %s' % output_file)
  with tf.python_io.TFRecordWriter(output_file) as record_writer:
    data_dict = read_pickle_from_file(input_file)
    data = data_dict[b'data']
    labels = data_dict[b'labels']
    num_entries_in_batch = len(labels)
    print('Converting %d images' % num_entries_in_batch)
    for i in range(num_entries_in_batch):
      example = tf.train.Example(features=tf.train.Features(
          feature={
              'image': _bytes_feature(data[i].tobytes()),
              'label': _int64_feature(labels[i])
          }))
      record_writer.write(example.SerializeToString())

def main(data_dir):
  print('Download from {} and extract.'.format(CIFAR_DOWNLOAD_URL))
  download_and_extract(data_dir)
  file_names = _get_file_names()
  input_dir = os.path.join(data_dir, CIFAR_LOCAL_FOLDER)
  for mode, f in file_names.items():
    input_file = os.path.join(input_dir, f)
    output_file = os.path.join(data_dir, mode + '.tfrecords')
    try:
      os.remove(output_file)
    except OSError:
      pass
    # Convert to tf.train.Example and write the to TFRecords.
    convert_to_tfrecord(input_file, output_file)

  # Save fixed batch of 100 examples (first 10 of each class sampled at the
  # front of the validation set). Ordered by label, i.e. 10 "airplane" images
  # followed by 10 "automobile" images...
  images = [[] for _ in range(10)]
  num_images = 0
  input_file = os.path.join(input_dir, file_names['validation'])
  data_dict = read_pickle_from_file(input_file)
  data = data_dict[b'data']
  labels = data_dict[b'labels']
  for i in range(len(labels)):
    label = labels[i]
    if len(images[label]) < 10:
      images[label].append(
          tf.train.Example(features=tf.train.Features(
              feature={
                  'image': _bytes_feature(data[i].tobytes()),
                  'label': _int64_feature(label)
              })))
      num_images += 1
      if num_images == 100:
        break

  output_file = os.path.join(data_dir, 'sample.tfrecords')
  print('Generating %s' % output_file)
  with tf.python_io.TFRecordWriter(output_file) as record_writer:
    for label_images in images:
      for example in label_images:
        record_writer.write(example.SerializeToString())
  print('Done!')

if __name__ == '__main__':
  parser = argparse.ArgumentParser()
  parser.add_argument(
      '--data_dir',
      type=str,
      default='',
      help='Directory to download and extract CIFAR-10 to.')

  args = parser.parse_args()
  main(args.data_dir)


text:
import ResultPoint from '../../ResultPoint';
import AztecDetectorResult from '../AztecDetectorResult';
import BitMatrix from '../../common/BitMatrix';
import CornerDetector from '../../common/detector/CornerDetector';
import MathUtils from '../../common/detector/MathUtils';
import WhiteRectangleDetector from '../../common/detector/WhiteRectangleDetector';
import GenericGF from '../../common/reedsolomon/GenericGF';
import ReedSolomonDecoder from '../../common/reedsolomon/ReedSolomonDecoder';
import NotFoundException from '../../NotFoundException';
import GridSamplerInstance from '../../common/GridSamplerInstance';
import Integer from '../../util/Integer';

export class Point {
    private x: number;
    private y: number;

    public toResultPoint(): ResultPoint {
        return new ResultPoint(this.getX(), this.getY());
    }

    public constructor(x: number, y: number) {
        this.x = x;
        this.y = y;
    }

    public getX(): number {
        return this.x;
    }

    public getY(): number {
        return this.y;
    }

    // @Override
    // public String toString() {
    //     return "<" + x + ' ' + y + '>';
    // }
}

/**
 * Encapsulates logic that can detect an Aztec Code in an image, even if the Aztec Code
 * is rotated or skewed, or partially obscured.
 *
 * @author David Olivier
 * @author Frank Yellin
 */
export default class Detector {

    private EXPECTED_CORNER_BITS = new Int32Array([
        0xee0,  // 07340  XXX .XX X.. ...
        0x1dc,  // 00734  ... XXX .XX X..
        0x83b,  // 04073  X.. ... XXX .XX
        0x707,  // 03407 .XX X.. ... XXX
    ]);

    private image: BitMatrix;

    private compact: boolean;
    private nbLayers: number;
    private nbDataBlocks: number;
    private nbCenterLayers: number;
    private shift: number;

    public constructor(image: BitMatrix) {
        this.image = image;
    }

    public detect(): AztecDetectorResult {
        return this.detectMirror(false);
    }

    /**
     * Detects an Aztec Code in an image.
     *
     * @param isMirror if true, image is a mirror-image of original
     * @return {@link AztecDetectorResult} encapsulating results of detecting an Aztec Code
     * @throws NotFoundException if no Aztec Code can be found
     */
    public detectMirror(isMirror: boolean): AztecDetectorResult {

        // 1. Get the center of the aztec matrix
        let pCenter = this.getMatrixCenter();

        // 2. Get the center points of the four diagonal points just outside the bull's eye
        //  [topRight, bottomRight, bottomLeft, topLeft]
        let bullsEyeCorners = this.getBullsEyeCorners(pCenter);

        if (isMirror) {
            let temp = bullsEyeCorners[0];
            bullsEyeCorners[0] = bullsEyeCorners[2];
            bullsEyeCorners[2] = temp;
        }

        // 3. Get the size of the matrix and other parameters from the bull's eye
        this.extractParameters(bullsEyeCorners);

        // 4. Sample the grid
        let bits: BitMatrix = this.sampleGrid(this.image,
            bullsEyeCorners[this.shift % 4],
            bullsEyeCorners[(this.shift + 1) % 4],
            bullsEyeCorners[(this.shift + 2) % 4],
            bullsEyeCorners[(this.shift + 3) % 4]
        );

        // 5. Get the corners of the matrix.
        let corners: ResultPoint[] = this.getMatrixCornerPoints(bullsEyeCorners);

        return new AztecDetectorResult(bits, corners, this.compact, this.nbDataBlocks, this.nbLayers);
    }

    /**
     * Extracts the number of data layers and data blocks from the layer around the bull's eye.
     *
     * @param bullsEyeCorners the array of bull's eye corners
     * @throws NotFoundException in case of too many errors or invalid parameters
     */
    private extractParameters(bullsEyeCorners: ResultPoint[]): void {
        if (!this.isValidPoint(bullsEyeCorners[0]) || !this.isValidPoint(bullsEyeCorners[1]) ||
            !this.isValidPoint(bullsEyeCorners[2]) || !this.isValidPoint(bullsEyeCorners[3])) {
            throw new NotFoundException();
        }
        let length = 2 * this.nbCenterLayers;
        // Get the bits around the bull's eye
        let sides = new Int32Array([
            this.sampleLine(bullsEyeCorners[0], bullsEyeCorners[1], length), // Right side
            this.sampleLine(bullsEyeCorners[1], bullsEyeCorners[2], length), // Bottom
            this.sampleLine(bullsEyeCorners[2], bullsEyeCorners[3], length), // Left side
            this.sampleLine(bullsEyeCorners[3], bullsEyeCorners[0], length)  // Top
        ]);

        // bullsEyeCorners[shift] is the corner of the bulls'eye that has three
        // orientation marks.
        // sides[shift] is the row/column that goes from the corner with three
        // orientation marks to the corner with two.
        this.shift = this.getRotation(sides, length);

        // Flatten the parameter bits into a single 28- or 40-bit long
        let parameterData = 0;
        for (let i = 0; i < 4; i++) {
            let side = sides[(this.shift + i) % 4];
            if (this.compact) {
                // Each side of the form ..XXXXXXX. where Xs are parameter data
                parameterData <<= 7;
                parameterData += (side >> 1) & 0x7F;
            } else {
                // Each side of the form ..XXXXX.XXXXX. where Xs are parameter data
                parameterData <<= 10;
                parameterData += ((side >> 2) & (0x1f << 5)) + ((side >> 1) & 0x1F);
            }
        }

        // Corrects parameter data using RS.  Returns just the data portion
        // without the error correction.
        let correctedData = this.getCorrectedParameterData(parameterData, this.compact);

        if (this.compact) {
            // 8 bits:  2 bits layers and 6 bits data blocks
            this.nbLayers = (correctedData >> 6) + 1;
            this.nbDataBlocks = (correctedData & 0x3F) + 1;
        } else {
            // 16 bits:  5 bits layers and 11 bits data blocks
            this.nbLayers = (correctedData >> 11) + 1;
            this.nbDataBlocks = (correctedData & 0x7FF) + 1;
        }
    }

    private getRotation(sides: Int32Array, length: number): number {
        // In a normal pattern, we expect to See
        //   **    .*             D       A
        //   *      *
        //
        //   .      *
        //   ..    ..             C       B
        //
        // Grab the 3 bits from each of the sides the form the locator pattern and concatenate
        // into a 12-bit integer.  Start with the bit at A
        let cornerBits = 0;
        sides.forEach((side, idx, arr) => {
            // XX......X where X's are orientation marks
            let t = ((side >> (length - 2)) << 1) + (side & 1);
            cornerBits = (cornerBits << 3) + t;
        });
        // for (var side in sides) {
        //     // XX......X where X's are orientation marks
        //     var t = ((side >> (length - 2)) << 1) + (side & 1);
        //     cornerBits = (cornerBits << 3) + t;
        // }

        // Mov the bottom bit to the top, so that the three bits of the locator pattern at A are
        // together.  cornerBits is now:
        //  3 orientation bits at A || 3 orientation bits at B || ... || 3 orientation bits at D
        cornerBits = ((cornerBits & 1) << 11) + (cornerBits >> 1);
        // The result shift indicates which element of BullsEyeCorners[] goes into the top-left
        // corner. Since the four rotation values have a Hamming distance of 8, we
        // can easily tolerate two errors.
        for (let shift = 0; shift < 4; shift++) {
            if (Integer.bitCount(cornerBits ^ this.EXPECTED_CORNER_BITS[shift]) <= 2) {
                return shift;
            }
        }
        throw new NotFoundException();
    }

    /**
     * Corrects the parameter bits using Reed-Solomon algorithm.
     *
     * @param parameterData parameter bits
     * @param compact true if this is a compact Aztec code
     * @throws NotFoundException if the array contains too many errors
     */
    private getCorrectedParameterData(parameterData: number, compact: boolean): number {
        let numCodewords;
        let numDataCodewords;

        if (compact) {
            numCodewords = 7;
            numDataCodewords = 2;
        } else {
            numCodewords = 10;
            numDataCodewords = 4;
        }

        let numECCodewords = numCodewords - numDataCodewords;
        let parameterWords: Int32Array = new Int32Array(numCodewords);
        for (let i = numCodewords - 1; i >= 0; --i) {
            parameterWords[i] = parameterData & 0xF;
            parameterData >>= 4;
        }
        try {
            let rsDecoder = new ReedSolomonDecoder(GenericGF.AZTEC_PARAM);
            rsDecoder.decode(parameterWords, numECCodewords);
        } catch (ignored) {
            throw new NotFoundException();
        }
        // Toss the error correction.  Just return the data as an integer
        let result = 0;
        for (let i = 0; i < numDataCodewords; i++) {
            result = (result << 4) + parameterWords[i];
        }
        return result;
    }

    /**
     * Finds the corners of a bull-eye centered on the passed point.
     * This returns the centers of the diagonal points just outside the bull's eye
     * Returns [topRight, bottomRight, bottomLeft, topLeft]
     *
     * @param pCenter Center point
     * @return The corners of the bull-eye
     * @throws NotFoundException If no valid bull-eye can be found
     */
    private getBullsEyeCorners(pCenter: Point): ResultPoint[] {

        let pina = pCenter;
        let pinb = pCenter;
        let pinc = pCenter;
        let pind = pCenter;

        let color = true;

        for (this.nbCenterLayers = 1; this.nbCenterLayers < 9; this.nbCenterLayers++) {

            let pouta = this.getFirstDifferent(pina, color, 1, -1);
            let poutb = this.getFirstDifferent(pinb, color, 1, 1);
            let poutc = this.getFirstDifferent(pinc, color, -1, 1);
            let poutd = this.getFirstDifferent(pind, color, -1, -1);

            // d      a
            //
            // c      b

            if (this.nbCenterLayers > 2) {
                let q = (this.distancePoint(poutd, pouta) * this.nbCenterLayers) / (this.distancePoint(pind, pina) * (this.nbCenterLayers + 2));
                if (q < 0.75 || q > 1.25 || !this.isWhiteOrBlackRectangle(pouta, poutb, poutc, poutd)) {
                    break;
                }
            }

            pina = pouta;
            pinb = poutb;
            pinc = poutc;
            pind = poutd;

            color = !color;
        }

        if (this.nbCenterLayers !== 5 && this.nbCenterLayers !== 7) {
            throw new NotFoundException();
        }

        this.compact = this.nbCenterLayers === 5;

        // Expand the square by .5 pixel in each direction so that we're on the border
        // between the white square and the black square
        let pinax = new ResultPoint(pina.getX() + 0.5, pina.getY() - 0.5);
        let pinbx = new ResultPoint(pinb.getX() + 0.5, pinb.getY() + 0.5);
        let pincx = new ResultPoint(pinc.getX() - 0.5, pinc.getY() + 0.5);
        let pindx = new ResultPoint(pind.getX() - 0.5, pind.getY() - 0.5);

        // Expand the square so that its corners are the centers of the points
        // just outside the bull's eye.
        return this.expandSquare([pinax, pinbx, pincx, pindx],
            2 * this.nbCenterLayers - 3,
            2 * this.nbCenterLayers);
    }

    /**
     * Finds a candidate center point of an Aztec code from an image
     *
     * @return the center point
     */
    private getMatrixCenter(): Point {

        let pointA: ResultPoint;
        let pointB: ResultPoint;
        let pointC: ResultPoint;
        let pointD: ResultPoint;

        // Get a white rectangle that can be the border of the matrix in center bull's eye or
        try {

            let cornerPoints = new WhiteRectangleDetector(this.image).detect();
            pointA = cornerPoints[0];
            pointB = cornerPoints[1];
            pointC = cornerPoints[2];
            pointD = cornerPoints[3];

        } catch (e) {

            // This exception can be in case the initial rectangle is white
            // In that case, surely in the bull's eye, we try to expand the rectangle.
            let cx = this.image.getWidth() / 2;
            let cy = this.image.getHeight() / 2;
            pointA = this.getFirstDifferent(new Point(cx + 7, cy - 7), false, 1, -1).toResultPoint();
            pointB = this.getFirstDifferent(new Point(cx + 7, cy + 7), false, 1, 1).toResultPoint();
            pointC = this.getFirstDifferent(new Point(cx - 7, cy + 7), false, -1, 1).toResultPoint();
            pointD = this.getFirstDifferent(new Point(cx - 7, cy - 7), false, -1, -1).toResultPoint();

        }

        // Compute the center of the rectangle
        let cx = MathUtils.round((pointA.getX() + pointD.getX() + pointB.getX() + pointC.getX()) / 4.0);
        let cy = MathUtils.round((pointA.getY() + pointD.getY() + pointB.getY() + pointC.getY()) / 4.0);

        // Redetermine the white rectangle starting from previously computed center.
        // This will ensure that we end up with a white rectangle in center bull's eye
        // in order to compute a more accurate center.
        try {
            let cornerPoints = new WhiteRectangleDetector(this.image, 15, cx, cy).detect();
            pointA = cornerPoints[0];
            pointB = cornerPoints[1];
            pointC = cornerPoints[2];
            pointD = cornerPoints[3];
        } catch (e) {
            // This exception can be in case the initial rectangle is white
            // In that case we try to expand the rectangle.
            pointA = this.getFirstDifferent(new Point(cx + 7, cy - 7), false, 1, -1).toResultPoint();
            pointB = this.getFirstDifferent(new Point(cx + 7, cy + 7), false, 1, 1).toResultPoint();
            pointC = this.getFirstDifferent(new Point(cx - 7, cy + 7), false, -1, 1).toResultPoint();
            pointD = this.getFirstDifferent(new Point(cx - 7, cy - 7), false, -1, -1).toResultPoint();
        }

        // Recompute the center of the rectangle
        cx = MathUtils.round((pointA.getX() + pointD.getX() + pointB.getX() + pointC.getX()) / 4.0);
        cy = MathUtils.round((pointA.getY() + pointD.getY() + pointB.getY() + pointC.getY()) / 4.0);

        return new Point(cx, cy);
    }

    /**
     * Gets the Aztec code corners from the bull's eye corners and the parameters.
     *
     * @param bullsEyeCorners the array of bull's eye corners
     * @return the array of aztec code corners
     */
    private getMatrixCornerPoints(bullsEyeCorners: ResultPoint[]): ResultPoint[] {
        return this.expandSquare(bullsEyeCorners, 2 * this.nbCenterLayers, this.getDimension());
    }

    /**
     * Creates a BitMatrix by sampling the provided image.
     * topLeft, topRight, bottomRight, and bottomLeft are the centers of the squares on the
     * diagonal just outside the bull's eye.
     */
    private sampleGrid(image: BitMatrix,
        topLeft: ResultPoint,
        topRight: ResultPoint,
        bottomRight: ResultPoint,
        bottomLeft: ResultPoint): BitMatrix {

        let sampler = GridSamplerInstance.getInstance();
        let dimension = this.getDimension();

        let low = dimension / 2 - this.nbCenterLayers;
        let high = dimension / 2 + this.nbCenterLayers;

        return sampler.sampleGrid(image,
            dimension,
            dimension,
            low, low,   // topleft
            high, low,  // topright
            high, high, // bottomright
            low, high,  // bottomleft
            topLeft.getX(), topLeft.getY(),
            topRight.getX(), topRight.getY(),
            bottomRight.getX(), bottomRight.getY(),
            bottomLeft.getX(), bottomLeft.getY());
    }

    /**
     * Samples a line.
     *
     * @param p1   start point (inclusive)
     * @param p2   end point (exclusive)
     * @param size number of bits
     * @return the array of bits as an int (first bit is high-order bit of result)
     */
    private sampleLine(p1: ResultPoint, p2: ResultPoint, size: number): number {
        let result = 0;

        let d = this.distanceResultPoint(p1, p2);
        let moduleSize = d / size;
        let px = p1.getX();
        let py = p1.getY();
        let dx = moduleSize * (p2.getX() - p1.getX()) / d;
        let dy = moduleSize * (p2.getY() - p1.getY()) / d;
        for (let i = 0; i < size; i++) {
            if (this.image.get(MathUtils.round(px + i * dx), MathUtils.round(py + i * dy))) {
                result |= 1 << (size - i - 1);
            }
        }
        return result;
    }

    /**
     * @return true if the border of the rectangle passed in parameter is compound of white points only
     *         or black points only
     */
    private isWhiteOrBlackRectangle(p1: Point,
        p2: Point,
        p3: Point,
        p4: Point): boolean {

        let corr = 3;
        p1 = new Point(p1.getX() - corr, p1.getY() + corr);
        p2 = new Point(p2.getX() - corr, p2.getY() - corr);
        p3 = new Point(p3.getX() + corr, p3.getY() - corr);
        p4 = new Point(p4.getX() + corr, p4.getY() + corr);

        let cInit = this.getColor(p4, p1);

        if (cInit === 0) {
            return false;
        }

        let c = this.getColor(p1, p2);

        if (c !== cInit) {
            return false;
        }

        c = this.getColor(p2, p3);

        if (c !== cInit) {
            return false;
        }

        c = this.getColor(p3, p4);

        return c === cInit;

    }

    /**
     * Gets the color of a segment
     *
     * @return 1 if segment more than 90% black, -1 if segment is more than 90% white, 0 else
     */
    private getColor(p1: Point, p2: Point): number {
        let d = this.distancePoint(p1, p2);
        let dx = (p2.getX() - p1.getX()) / d;
        let dy = (p2.getY() - p1.getY()) / d;
        let error = 0;

        let px = p1.getX();
        let py = p1.getY();

        let colorModel = this.image.get(p1.getX(), p1.getY());

        let iMax = Math.ceil(d);
        for (let i = 0; i < iMax; i++) {
            px += dx;
            py += dy;
            if (this.image.get(MathUtils.round(px), MathUtils.round(py)) !== colorModel) {
                error++;
            }
        }

        let errRatio = error / d;

        if (errRatio > 0.1 && errRatio < 0.9) {
            return 0;
        }

        return (errRatio <= 0.1) === colorModel ? 1 : -1;
    }

    /**
     * Gets the coordinate of the first point with a different color in the given direction
     */
    private getFirstDifferent(init: Point, color: boolean, dx: number, dy: number): Point {
        let x = init.getX() + dx;
        let y = init.getY() + dy;

        while (this.isValid(x, y) && this.image.get(x, y) === color) {
            x += dx;
            y += dy;
        }

        x -= dx;
        y -= dy;

        while (this.isValid(x, y) && this.image.get(x, y) === color) {
            x += dx;
        }
        x -= dx;

        while (this.isValid(x, y) && this.image.get(x, y) === color) {
            y += dy;
        }
        y -= dy;

        return new Point(x, y);
    }

    /**
     * Expand the square represented by the corner points by pushing out equally in all directions
     *
     * @param cornerPoints the corners of the square, which has the bull's eye at its center
     * @param oldSide the original length of the side of the square in the target bit matrix
     * @param newSide the new length of the size of the square in the target bit matrix
     * @return the corners of the expanded square
     */
    private expandSquare(cornerPoints: ResultPoint[], oldSide: number, newSide: number): ResultPoint[] {
        let ratio = newSide / (2.0 * oldSide);
        let dx = cornerPoints[0].getX() - cornerPoints[2].getX();
        let dy = cornerPoints[0].getY() - cornerPoints[2].getY();
        let centerx = (cornerPoints[0].getX() + cornerPoints[2].getX()) / 2.0;
        let centery = (cornerPoints[0].getY() + cornerPoints[2].getY()) / 2.0;

        let result0 = new ResultPoint(centerx + ratio * dx, centery + ratio * dy);
        let result2 = new ResultPoint(centerx - ratio * dx, centery - ratio * dy);

        dx = cornerPoints[1].getX() - cornerPoints[3].getX();
        dy = cornerPoints[1].getY() - cornerPoints[3].getY();
        centerx = (cornerPoints[1].getX() + cornerPoints[3].getX()) / 2.0;
        centery = (cornerPoints[1].getY() + cornerPoints[3].getY()) / 2.0;
        let result1 = new ResultPoint(centerx + ratio * dx, centery + ratio * dy);
        let result3 = new ResultPoint(centerx - ratio * dx, centery - ratio * dy);

        let results: ResultPoint[] = [result0, result1, result2, result3];
        return results;
    }

    private isValid(x: number, y: number): boolean {
        return x >= 0 && x < this.image.getWidth() && y > 0 && y < this.image.getHeight();
    }

    private isValidPoint(point: ResultPoint): boolean {
        let x = MathUtils.round(point.getX());
        let y = MathUtils.round(point.getY());
        return this.isValid(x, y);
    }

    private distancePoint(a: Point, b: Point): number {
        return MathUtils.distance(a.getX(), a.getY(), b.getX(), b.getY());
    }

    private distanceResultPoint(a: ResultPoint, b: ResultPoint): number {
        return MathUtils.distance(a.getX(), a.getY(), b.getX(), b.getY());
    }

    private getDimension(): number {
        if (this.compact) {
            return 4 * this.nbLayers + 11;
        }
        if (this.nbLayers <= 4) {
            return 4 * this.nbLayers + 15;
        }
        return 4 * this.nbLayers + 2 * (Integer.truncDivision((this.nbLayers - 4), 8) + 1) + 15;
    }

}


text:
module TrmixRails
    class Rails
      require 'trmix/rails/engine'
      require 'trmix/rails/version'
    end
end


text:
.. title:: Welcome to Extra Clang Tools's documentation!

Introduction
============
Welcome to the clang-tools-extra project which contains extra tools built using
Clang's tooling APIs.

.. toctree::
   :maxdepth: 1

   ReleaseNotes

Contents
========
.. toctree::
   :maxdepth: 2

   clang-tidy/index
   clang-include-fixer
   modularize
   pp-trace
   clang-rename
   clangd <https://clangd.llvm.org/>
   clang-doc

Doxygen Documentation
=====================
The Doxygen documentation describes the **internal** software that makes up the
tools of clang-tools-extra, not the **external** use of these tools. The Doxygen
documentation contains no instructions about how to use the tools, only the APIs
that make up the software. For usage instructions, please see the user's guide
or reference manual for each tool.

* `Doxygen documentation`_

.. _`Doxygen documentation`: doxygen/annotated.html

.. note::
    This documentation is generated directly from the source code with doxygen.
    Since the tools of clang-tools-extra are constantly under active
    development, what you're about to read is out of date!

Indices and tables
==================

* :ref:`genindex`
* :ref:`search`


text:
package fuse

import (
	"github.com/restic/restic/internal/errors"
	"github.com/restic/restic/internal/restic"

	"github.com/restic/restic/internal/debug"

	"bazil.org/fuse"
	"bazil.org/fuse/fs"
	"golang.org/x/net/context"
)

// The default block size to report in stat
const blockSize = 512

// Statically ensure that *file implements the given interface
var _ = fs.HandleReader(&file{})
var _ = fs.HandleReleaser(&file{})

type file struct {
	root  *Root
	node  *restic.Node
	inode uint64

	sizes []int
	blobs [][]byte
}

func newFile(ctx context.Context, root *Root, inode uint64, node *restic.Node) (fusefile *file, err error) {
	debug.Log("create new file for %v with %d blobs", node.Name, len(node.Content))
	var bytes uint64
	sizes := make([]int, len(node.Content))
	for i, id := range node.Content {
		size, ok := root.blobSizeCache.Lookup(id)
		if !ok {
			var found bool
			size, found = root.repo.LookupBlobSize(id, restic.DataBlob)
			if !found {
				return nil, errors.Errorf("id %v not found in repository", id)
			}
		}

		sizes[i] = int(size)
		bytes += uint64(size)
	}

	if bytes != node.Size {
		debug.Log("sizes do not match: node.Size %v != size %v, using real size", node.Size, bytes)
		node.Size = bytes
	}

	return &file{
		inode: inode,
		root:  root,
		node:  node,
		sizes: sizes,
		blobs: make([][]byte, len(node.Content)),
	}, nil
}

func (f *file) Attr(ctx context.Context, a *fuse.Attr) error {
	debug.Log("Attr(%v)", f.node.Name)
	a.Inode = f.inode
	a.Mode = f.node.Mode
	a.Size = f.node.Size
	a.Blocks = (f.node.Size / blockSize) + 1
	a.BlockSize = blockSize
	a.Nlink = uint32(f.node.Links)

	if !f.root.cfg.OwnerIsRoot {
		a.Uid = f.node.UID
		a.Gid = f.node.GID
	}
	a.Atime = f.node.AccessTime
	a.Ctime = f.node.ChangeTime
	a.Mtime = f.node.ModTime

	return nil

}

func (f *file) getBlobAt(ctx context.Context, i int) (blob []byte, err error) {
	debug.Log("getBlobAt(%v, %v)", f.node.Name, i)
	if f.blobs[i] != nil {
		return f.blobs[i], nil
	}

	// release earlier blobs
	for j := 0; j < i; j++ {
		f.blobs[j] = nil
	}

	buf := restic.NewBlobBuffer(f.sizes[i])
	n, err := f.root.repo.LoadBlob(ctx, restic.DataBlob, f.node.Content[i], buf)
	if err != nil {
		debug.Log("LoadBlob(%v, %v) failed: %v", f.node.Name, f.node.Content[i], err)
		return nil, err
	}
	f.blobs[i] = buf[:n]

	return buf[:n], nil
}

func (f *file) Read(ctx context.Context, req *fuse.ReadRequest, resp *fuse.ReadResponse) error {
	debug.Log("Read(%v, %v, %v), file size %v", f.node.Name, req.Size, req.Offset, f.node.Size)
	offset := req.Offset

	if uint64(offset) > f.node.Size {
		debug.Log("Read(%v): offset is greater than file size: %v > %v",
			f.node.Name, req.Offset, f.node.Size)

		// return no data
		resp.Data = resp.Data[:0]
		return nil
	}

	// handle special case: file is empty
	if f.node.Size == 0 {
		resp.Data = resp.Data[:0]
		return nil
	}

	// Skip blobs before the offset
	startContent := 0
	for offset > int64(f.sizes[startContent]) {
		offset -= int64(f.sizes[startContent])
		startContent++
	}

	dst := resp.Data[0:req.Size]
	readBytes := 0
	remainingBytes := req.Size
	for i := startContent; remainingBytes > 0 && i < len(f.sizes); i++ {
		blob, err := f.getBlobAt(ctx, i)
		if err != nil {
			return err
		}

		if offset > 0 {
			blob = blob[offset:]
			offset = 0
		}

		copied := copy(dst, blob)
		remainingBytes -= copied
		readBytes += copied

		dst = dst[copied:]
	}
	resp.Data = resp.Data[:readBytes]

	return nil
}

func (f *file) Release(ctx context.Context, req *fuse.ReleaseRequest) error {
	for i := range f.blobs {
		f.blobs[i] = nil
	}
	return nil
}

func (f *file) Listxattr(ctx context.Context, req *fuse.ListxattrRequest, resp *fuse.ListxattrResponse) error {
	debug.Log("Listxattr(%v, %v)", f.node.Name, req.Size)
	for _, attr := range f.node.ExtendedAttributes {
		resp.Append(attr.Name)
	}
	return nil
}

func (f *file) Getxattr(ctx context.Context, req *fuse.GetxattrRequest, resp *fuse.GetxattrResponse) error {
	debug.Log("Getxattr(%v, %v, %v)", f.node.Name, req.Name, req.Size)
	attrval := f.node.GetExtendedAttribute(req.Name)
	if attrval != nil {
		resp.Xattr = attrval
		return nil
	}
	return fuse.ErrNoXattr
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.books.model;

/**
 * Model definition for BooksVolumesRecommendedRateResponse.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Books API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class BooksVolumesRecommendedRateResponse extends com.google.api.client.json.GenericJson {

  /**
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key("consistency_token")
  private java.lang.String consistencyToken;

  /**
   * @return value or {@code null} for none
   */
  public java.lang.String getConsistencyToken() {
    return consistencyToken;
  }

  /**
   * @param consistencyToken consistencyToken or {@code null} for none
   */
  public BooksVolumesRecommendedRateResponse setConsistencyToken(java.lang.String consistencyToken) {
    this.consistencyToken = consistencyToken;
    return this;
  }

  @Override
  public BooksVolumesRecommendedRateResponse set(String fieldName, Object value) {
    return (BooksVolumesRecommendedRateResponse) super.set(fieldName, value);
  }

  @Override
  public BooksVolumesRecommendedRateResponse clone() {
    return (BooksVolumesRecommendedRateResponse) super.clone();
  }

}


text:
namespace HashTable
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    public class CustomHashTable<K, V> : IEnumerable<KeyValuePair<K, V>>
    {
        private const int InitialCapacity = 16;
        private const double LoadFactor = 0.75d;

        private LinkedList<KeyValuePair<K, V>>[] elements;
        private ICollection<K> keys;
        private int elementsCounter;

        public CustomHashTable(int capacity)
        {
            this.elements = new LinkedList<KeyValuePair<K, V>>[capacity];
            this.elementsCounter = 0;
            this.Count = 0;
            this.keys = new HashSet<K>();

        }

        public CustomHashTable()
            : this(InitialCapacity)
        {
        }

        public int Count { get; private set; }

        public ICollection<K> Keys
        {
            get
            {
                return this.keys;
            }
        }

        public void Add(K key, V value)
        {
            this.ResizeIfNeeded();

            this.keys.Add(key);

            var pairToAdd = new KeyValuePair<K, V>(key, value);
            var position = this.GetPosition(key);

            if (this.elements[position] == null)
            {
                this.elements[position] = new LinkedList<KeyValuePair<K, V>>();
                this.elements[position].AddFirst(pairToAdd);

                this.Count++;
            }
            else
            {
                this.Remove(key);

                if (this.elements[position].Count == 0)
                {
                    this.Count++;
                }

                this.elements[position].AddLast(pairToAdd);
            }

            this.elementsCounter++;
        }

        public void Remove(K key)
        {
            var position = this.GetPosition(key);
            V valueToRemove = default(V);

            if (this.Find(key, out valueToRemove))
            {
                var pairToRemove = this.elements[position].First(x => x.Key.Equals(key));
                this.elements[position].Remove(pairToRemove);
                this.elementsCounter--;
                this.keys.Remove(key);

                if (this.elements[position].Count == 0)
                {
                    this.Count--;
                }
            }
        }

        public V this[K key]
        {
            get
            {
                V value = default(V);

                if (!this.Find(key, out value))
                {
                    throw new KeyNotFoundException("No such key can be found.");
                }

                return value;
            }

            set
            {
                this.Add(key, value);
            }
        }

        public void Clear()
        {
            this.elements = new LinkedList<KeyValuePair<K, V>>[this.elements.Length];
            this.keys = new HashSet<K>();
            this.Count = 0;
            this.elementsCounter = 0;
        }

        public bool Find(K key, out V value)
        {
            int position = this.GetPosition(key);
            if (this.elements[position] != null && this.elements[position].Count != 0)
            {
                foreach (var pair in this.elements[position])
                {
                    if (pair.Key.Equals(key))
                    {
                        value = pair.Value;
                        return true;
                    }
                }
            }

            value = default(V);
            return false;
        }

        public IEnumerator<KeyValuePair<K, V>> GetEnumerator()
        {
            foreach (var list in this.elements)
            {
                if (list != null)
                {
                    foreach (var pair in list)
                    {
                        yield return pair;
                    }
                }
            }
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }

        public override string ToString()
        {
            var result = new StringBuilder();

            foreach (var pair in this)
            {
                result.AppendFormat("K: {0}; V: {1}\t|\t", pair.Key, pair.Value);
            }

            return result.ToString().TrimEnd(new[] { '\t', ' ', '|' });
        }

        private int GetPosition(K key)
        {
            return Math.Abs(key.GetHashCode() % this.elements.Length);
        }

        private void ResizeIfNeeded()
        {
            if (this.elementsCounter >= this.elements.Length * LoadFactor)
            {
                var newCustomHashTable = new CustomHashTable<K, V>(this.elements.Length * 2);

                foreach (var pair in this)
                {
                    newCustomHashTable.Add(pair.Key, pair.Value);
                }

                this.elements = newCustomHashTable.elements;
            }
        }
    }
}


text:
#include <miopen/config.h>
#include <miopen/hip_build_utils.hpp>
#include <miopen/logger.hpp>
#include <miopen/mlir_build.hpp>

#include <Miir.h>

#include <fstream>
#include <vector>

namespace miopen {
// Anonymous namespace
namespace {
/// Destroys handle in case of exception.
class AutoMiirHandle
{
    MiirHandle handle;

public:
    AutoMiirHandle(const std::string& options) : handle(miirCreateHandle(options.c_str())) {}
    // Explicitly disable copy and assignment of the handle to avoid double-free risk
    AutoMiirHandle(const AutoMiirHandle&) = delete;
    void operator=(const AutoMiirHandle&) = delete;
    ~AutoMiirHandle() { miirDestroyHandle(handle); }
    MiirHandle operator()() { return handle; }
};

void check_miir_error(MiirStatus status, const std::string& miir_fn_name)
{
    switch(status)
    {
    case MIIR_SUCCESS: return;
    case MIIR_INVALID_PARAM: MIOPEN_THROW(miir_fn_name + " MIIR_INVALID_PARAM"); break;
    case MIIR_INVALID_MODULE: MIOPEN_THROW(miir_fn_name + " MIIR_INVALID_MODULE"); break;
    case MIIR_BUILD_FAILURE: MIOPEN_THROW(miir_fn_name + " MIIR_BUILD_FAILURE"); break;
    default: MIOPEN_THROW(miir_fn_name + " <UNKNOWN ERROR>");
    }
}
} // namespace

void MiirGenLaunchParams(const std::string& params, size_t& local_size, size_t& global_size)
{
    AutoMiirHandle handle(params);
    auto status = miirLowerTuningParams(handle());
    check_miir_error(status, "miirLowerTuningParams");
    miirGetExecutionDims(handle(), &global_size, &local_size);
    check_miir_error(status, "miirGetExecutionDims");
}

bool MiirIsConfigApplicable(const std::string& params)
{
    AutoMiirHandle handle(params);
    return MIIR_SUCCESS == miirLowerTuningParams(handle());
}

void MiirGenBin(const std::string& params, std::vector<char>& buffer)
{
    AutoMiirHandle handle(params);
    miirLowerBin(handle());

    size_t size = 0;
    auto status = miirBufferGet(handle(), nullptr, &size);
    check_miir_error(status, "miirBufferGet");
    buffer.resize(size);
    status = miirBufferGet(handle(), buffer.data(), &size);
    check_miir_error(status, "miirBufferGet");
}

int MiirGetKernelCount(const std::string& params)
{
    AutoMiirHandle handle(params);
    const auto kernel_count = miirGetKernelCount(handle());
    if(kernel_count < 1)
        MIOPEN_THROW("miirGetKernelCount invalid count: " + std::to_string(kernel_count));
    return kernel_count;
}

int MiirGetWorkspaceSize(const std::string& params)
{
    AutoMiirHandle handle(params);
    return miirGetWorkspaceSize(handle());
}

} // namespace miopen


text:
using System;
using umbraco.interfaces;
using umbraco.BasePages;
using Umbraco.Core;
using Umbraco.Core.CodeAnnotations;

namespace umbraco.BusinessLogic.Actions
{
    /// <summary>
    /// This action is invoked when children to a document is being sent to published (by an editor without publishrights)
    /// </summary>
    [ActionMetadata(Constants.Conventions.PermissionCategories.ContentCategory)]
    public class ActionToPublish : IAction
	{
		//create singleton
#pragma warning disable 612,618
		private static readonly ActionToPublish m_instance = new ActionToPublish();
#pragma warning restore 612,618

		/// <summary>
		/// A public constructor exists ONLY for backwards compatibility in regards to 3rd party add-ons.
		/// All Umbraco assemblies should use the singleton instantiation (this.Instance)
		/// When this applicatio is refactored, this constuctor should be made private.
		/// </summary>
		[Obsolete("Use the singleton instantiation instead of a constructor")]
		public ActionToPublish() { }

		public static ActionToPublish Instance
		{
			get { return m_instance; }
		}

		#region IAction Members

		public char Letter
		{
			get
			{
				return 'H';
			}
		}

		public string JsFunctionName
		{
			get
			{
				return string.Format("{0}.actionToPublish()", ClientTools.Scripts.GetAppActions);
			}
		}

		public string JsSource
		{
			get
			{
				return null;
			}
		}

		public string Alias
		{
			get
			{
				return "sendtopublish";
			}
		}

		public string Icon
		{
			get
			{
                return "outbox";
			}
		}

		public bool ShowInNotifier
		{
			get
			{
				return true;
			}
		}
		public bool CanBePermissionAssigned
		{
			get
			{
				//SD: Changed this to true so that any user may be able to perform this action, not just a writer
				return true;
			}
		}
		#endregion
	}
}


text:
enyo.kind({
	name: "moon.sample.DrawerSample",
	classes: "moon enyo-unselectable enyo-fit",
	components: [
		{
			name: "drawers",
			kind: "moon.Drawers",
			drawers: [
				{
					name: "partialDrawer",
					open: false,
					controlsOpen: false,
					onActivate: "partialDrawerChanged",
					onDeactivate: "partialDrawerChanged",
					handle: {name: "handleButton", content: "Partial drawer with long text truncation"},
					components: [
						{kind: "moon.Panel", classes:"enyo-fit", title: "Partial Drawer", components: [
							{kind: "moon.Item", content: "Item One"},
							{kind: "moon.Item", content: "Item Two"}
						]}
					],
					controlDrawerComponents: [
						{classes:"moon-hspacing", components: [
							{kind: "moon.Button", name: "openMoreButton", content: "Open More", ontap: "openMainDrawer"},
							{kind: "moon.Button", content: "Close", ontap: "close"}
						]}
					]
				},
				{
					name: "searchDrawer",
					handle: {content: "Full drawer"},
					components: [
						{kind: "moon.Panel", classes:"enyo-fit", title: "Full Drawer", components: [
							{kind: "moon.Item", content: "Item One"},
							{kind: "moon.Item", content: "Item Two"}
						]}
					]
				}
			],
			components: [
				{
					name: "panels",
					kind: "moon.Panels",
					pattern: "activity",
					classes: "enyo-fit",
					components: [
						{title: "First Panel", classes: "moon-7h", components: [
							{kind: "moon.Scroller", horizontal: "hidden", classes: "enyo-fill", components: [
								{kind: "moon.ExpandablePicker", onChange: "pickerChangedImg", content: "Select Image", components: [
									{content: "Music",value: "$lib/moonstone/samples/assets/drawer_icon.png"},
									{content: "LG", value: "$lib/moonstone/samples/assets/lg.png"},
									{content: "HTML5", value: "$lib/moonstone/samples/assets/html5.png"},
									{content: "CSS3", value: "$lib/moonstone/samples/assets/css3.png"},
									{content: "Default", value: "", active: true}
								]},
								{kind: "moon.ExpandablePicker", onChange: "pickerChangedIcon", content: "Select Icon", components: [
									{content: "Drawer", value: "drawer"},
									{content: "FullScreen", value: "fullscreen"},
									{content: "Circle", value: "circle"},
									{content: "Stop", value: "stop"},
									{content: "Play", value: "play"},
									{content: "Pause", value: "pause"},
									{content: "Forward", value: "forward"},
									{content: "Default", value: "", active: true}
								]},
								{kind: "moon.Item", content: "Item One", ontap: "next"},
								{kind: "moon.Item", content: "Item Two", ontap: "next"}
							]}
						]},
						{title: "Second Panel", classes: "moon-7h", components: [
							{kind: "moon.Item", content: "Item One", ontap: "next"},
							{kind: "moon.Item", content: "Item Two", ontap: "next"},
							{kind: "moon.Item", content: "Item Three", ontap: "next"},
							{kind: "moon.Item", content: "Item Four", ontap: "next"},
							{kind: "moon.Item", content: "Item Five", ontap: "next"}
						]},
						{title: "Third Panel", classes: "moon-7h", components: [
							{kind: "moon.Item", content: "Item One", ontap: "next"},
							{kind: "moon.Item", content: "Item Two", ontap: "next"},
							{kind: "moon.Item", content: "Item Three", ontap: "next"},
							{kind: "moon.Item", content: "Item Four", ontap: "next"},
							{kind: "moon.Item", content: "Item Five", ontap: "next"}
						]},
						{title: "Fourth Panel", classes: "moon-7h", components: [
							{kind: "moon.Item", content: "Item One", ontap: "next"},
							{kind: "moon.Item", content: "Item Two", ontap: "next"},
							{kind: "moon.Item", content: "Item Three", ontap: "next"},
							{kind: "moon.Item", content: "Item Four", ontap: "next"},
							{kind: "moon.Item", content: "Item Five", ontap: "next"}
						]},
						{title: "Fifth Panel", classes: "moon-7h", components: [
							{kind: "moon.Item", content: "Item One", ontap: "next"},
							{kind: "moon.Item", content: "Item Two", ontap: "next"},
							{kind: "moon.Item", content: "Item Three", ontap: "next"},
							{kind: "moon.Item", content: "Item Four", ontap: "next"},
							{kind: "moon.Item", content: "Item Five", ontap: "next"}
						]}
					]
				}
			]
		}
	],
	next: function(inSender, inEvent) {
		this.$.panels.next();
		return true;
	},
	openMainDrawer: function() {
		this.$.partialDrawer.setOpen(true);
	},
	close: function() {
		if (this.$.partialDrawer.getOpen()) {
			this.$.partialDrawer.setOpen(false);
		} else {
			this.$.partialDrawer.setControlsOpen(false);
		}
	},
	partialDrawerChanged: function() {
		this.$.openMoreButton.setShowing(!this.$.partialDrawer.getOpen());
	},
	pickerChangedImg:function(inSender,inEvent){
		this.$.drawers.set('src',inEvent.selected.value);
	},
	pickerChangedIcon:function(inSender,inEvent){
		this.$.drawers.set('icon',inEvent.selected.value);
	}
});


text:
void GameState::update() {
	m_objects.update();
}

void GameState::render() {
	m_objects.render();
}

bool GameState::onExit() {
	m_objects.clean();
	return true;
}


text:
"""
Display song currently playing in Spotify.

Configuration parameters:
    button_next: button to switch to next song (default None)
    button_play_pause: button to toggle play/pause (default None)
    button_previous: button to switch to previous song (default None)
    cache_timeout: how often to update the bar (default 5)
    format: see placeholders below (default '{artist} : {title}')
    format_down: define output if spotify is not running
        (default 'Spotify not running')
    format_stopped: define output if spotify is not playing
        (default 'Spotify stopped')
    sanitize_titles: whether to remove meta data from album/track title
        (default True)
    sanitize_words: which meta data to remove
        *(default ['bonus', 'demo', 'edit', 'explicit', 'extended',
            'feat', 'mono', 'remaster', 'stereo', 'version'])*

Format placeholders:
    {album} album name
    {artist} artiste name (first one)
    {playback} state of the playback: Playing, Paused
    {time} time duration of the song
    {title} name of the song

Color options:
    color_offline: Spotify is not running, defaults to color_bad
    color_paused: Song is stopped or paused, defaults to color_degraded
    color_playing: Song is playing, defaults to color_good

Requires:
    spotify: a proprietary music streaming service

Examples:
```
spotify {
    button_next = 4
    button_play_pause = 1
    button_previous = 5
    format = "{title} by {artist} -> {time}"
    format_down = "no Spotify"
}
```

@author Pierre Guilbert, Jimmy Garpehäll, sondrele, Andrwe

SAMPLE OUTPUT
{'color': '#00FF00', 'full_text': 'Rick Astley : Never Gonna Give You Up'}

paused
{'color': '#FFFF00', 'full_text': 'Rick Astley : Never Gonna Give You Up'}

stopped
{'color': '#FF0000', 'full_text': 'Spotify stopped'}
"""

import re
from datetime import timedelta
from time import sleep

import dbus

SPOTIFY_CMD = """dbus-send --print-reply --dest=org.mpris.MediaPlayer2.spotify
                 /org/mpris/MediaPlayer2 org.mpris.MediaPlayer2.Player.{cmd}"""

class Py3status:
    """
    """

    # available configuration parameters
    button_next = None
    button_play_pause = None
    button_previous = None
    cache_timeout = 5
    format = "{artist} : {title}"
    format_down = "Spotify not running"
    format_stopped = "Spotify stopped"
    sanitize_titles = True
    sanitize_words = [
        "bonus",
        "demo",
        "edit",
        "explicit",
        "extended",
        "feat",
        "mono",
        "remaster",
        "stereo",
        "version",
    ]

    def _spotify_cmd(self, action):
        return SPOTIFY_CMD.format(cmd=action)

    def post_config_hook(self):
        """
        """
        # Match string after hyphen, comma, semicolon or slash containing any metadata word
        # examples:
        # - Remastered 2012
        # / Radio Edit
        # ; Remastered
        self.after_delimiter = self._compile_re(
            r"([\-,;/])([^\-,;/])*(META_WORDS_HERE).*"
        )

        # Match brackets with their content containing any metadata word
        # examples:
        # (Remastered 2017)
        # [Single]
        # (Bonus Track)
        self.inside_brackets = self._compile_re(
            r"([\(\[][^)\]]*?(META_WORDS_HERE)[^)\]]*?[\)\]])"
        )

    def _compile_re(self, expression):
        """
        Compile given regular expression for current sanitize words
        """
        meta_words = "|".join(self.sanitize_words)
        expression = expression.replace("META_WORDS_HERE", meta_words)
        return re.compile(expression, re.IGNORECASE)

    def _get_text(self):
        """
        Get the current song metadatas (artist - title)
        """
        bus = dbus.SessionBus()
        try:
            self.__bus = bus.get_object(
                "org.mpris.MediaPlayer2.spotify", "/org/mpris/MediaPlayer2"
            )
            self.player = dbus.Interface(self.__bus, "org.freedesktop.DBus.Properties")

            try:
                metadata = self.player.Get("org.mpris.MediaPlayer2.Player", "Metadata")
                album = metadata.get("xesam:album")
                artist = metadata.get("xesam:artist")[0]
                microtime = metadata.get("mpris:length")
                rtime = str(timedelta(microseconds=microtime))[:-7]
                title = metadata.get("xesam:title")
                if self.sanitize_titles:
                    album = self._sanitize_title(album)
                    title = self._sanitize_title(title)

                playback_status = self.player.Get(
                    "org.mpris.MediaPlayer2.Player", "PlaybackStatus"
                )
                if playback_status == "Playing":
                    color = self.py3.COLOR_PLAYING or self.py3.COLOR_GOOD
                else:
                    color = self.py3.COLOR_PAUSED or self.py3.COLOR_DEGRADED
            except Exception:
                return (
                    self.format_stopped,
                    self.py3.COLOR_PAUSED or self.py3.COLOR_DEGRADED,
                )

            return (
                self.py3.safe_format(
                    self.format,
                    dict(
                        title=title,
                        artist=artist,
                        album=album,
                        time=rtime,
                        playback=playback_status,
                    ),
                ),
                color,
            )
        except Exception:
            return (self.format_down, self.py3.COLOR_OFFLINE or self.py3.COLOR_BAD)

    def _sanitize_title(self, title):
        """
        Remove redundant metadata from title and return it
        """
        title = re.sub(self.inside_brackets, "", title)
        title = re.sub(self.after_delimiter, "", title)
        return title.strip()

    def spotify(self):
        """
        Get the current "artist - title" and return it.
        """
        (text, color) = self._get_text()
        response = {
            "cached_until": self.py3.time_in(self.cache_timeout),
            "color": color,
            "full_text": text,
        }
        return response

    def on_click(self, event):
        """
        """
        button = event["button"]
        if button == self.button_play_pause:
            self.py3.command_run(self._spotify_cmd("PlayPause"))
            sleep(0.1)
        elif button == self.button_next:
            self.py3.command_run(self._spotify_cmd("Next"))
            sleep(0.1)
        elif button == self.button_previous:
            self.py3.command_run(self._spotify_cmd("Previous"))
            sleep(0.1)

if __name__ == "__main__":
    """
    Run module in test mode.
    """
    from py3status.module_test import module_test

    module_test(Py3status)


text:
When 'the system processes jobs' do
  Delayed::Worker.new(:quiet => true).work_off
end


text:
'use strict';

const fs = require('fs');

const rootDataPath = './data';

module.exports.getData = function(fileName, doneCallBack) {
  const filePath = `${rootDataPath}/${fileName}.json`;
  const jsonReadCallBack = function(err, data){
    if (err) doneCallBack({message: 'Data readFile error', filePath});
    else {
      const jsonData = JSON.parse(data.toString());
      doneCallBack(jsonData);
    }
  };
  fs.readFile(filePath, jsonReadCallBack);
};

module.exports.setData = function(fileName, data, doneCallBack) {
  const filePath = `${rootDataPath}/${fileName}.json`;
  const writeFileCallBack = function (err) {
    if (err) doneCallBack({message: 'Data writeFile error', filePath});
    if (doneCallBack) doneCallBack({setResponse: 'ok'});
  };
  fs.writeFile(filePath, JSON.stringify(data, null, 2), writeFileCallBack);
};


text:
package com.hyphenate.easeui.widget;

import android.content.Context;
import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.hyphenate.easeui.R;

/**
 * 聊天输入栏主菜单栏
 *
 */
public class EaseChatPrimaryMenu extends EaseChatPrimaryMenuBase implements OnClickListener {
    private EditText editText;
    private View buttonSetModeKeyboard;
    private RelativeLayout edittext_layout;
    private View buttonSetModeVoice;
    private View buttonSend;
    private View buttonPressToSpeak;
    private ImageView faceNormal;
    private ImageView faceChecked;
    private ImageView cam;
    private Button buttonMore;
    private RelativeLayout faceLayout;
    private Context context;
    private EaseVoiceRecorderView voiceRecorderView;

    public EaseChatPrimaryMenu(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context, attrs);
    }

    public EaseChatPrimaryMenu(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public EaseChatPrimaryMenu(Context context) {
        super(context);
        init(context, null);
    }

    private void init(final Context context, AttributeSet attrs) {
        this.context = context;
        LayoutInflater.from(context).inflate(R.layout.ease_widget_chat_primary_menu, this);
        editText = (EditText) findViewById(R.id.et_sendmessage);
        buttonSetModeKeyboard = findViewById(R.id.btn_set_mode_keyboard);
        edittext_layout = (RelativeLayout) findViewById(R.id.edittext_layout);
        buttonSetModeVoice = findViewById(R.id.btn_set_mode_voice);
        buttonSend = findViewById(R.id.btn_send);
        buttonPressToSpeak = findViewById(R.id.btn_press_to_speak);
        faceNormal = (ImageView) findViewById(R.id.iv_face_normal);
        faceChecked = (ImageView) findViewById(R.id.iv_face_checked);
        cam = (ImageView) findViewById(R.id.cam);
        faceLayout = (RelativeLayout) findViewById(R.id.rl_face);
        buttonMore = (Button) findViewById(R.id.btn_more);
//        edittext_layout.setBackgroundResource(R.drawable.ease_input_bar_bg_normal);

        buttonSend.setOnClickListener(this);
        buttonSetModeKeyboard.setOnClickListener(this);
        buttonSetModeVoice.setOnClickListener(this);
        buttonMore.setOnClickListener(this);
        faceLayout.setOnClickListener(this);
        editText.setOnClickListener(this);
        cam.setOnClickListener(this);
        editText.requestFocus();

        editText.setOnFocusChangeListener(new OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
//                    edittext_layout.setBackgroundResource(R.drawable.ease_input_bar_bg_active);
                } else {
//                    edittext_layout.setBackgroundResource(R.drawable.ease_input_bar_bg_normal);
                }

            }
        });
        // 监听文字框
        editText.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!TextUtils.isEmpty(s)) {
                    buttonMore.setVisibility(View.GONE);
                    buttonSend.setVisibility(View.VISIBLE);
                } else {
                    buttonMore.setVisibility(View.VISIBLE);
                    buttonSend.setVisibility(View.GONE);
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        buttonPressToSpeak.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(listener != null){
                    return listener.onPressToSpeakBtnTouch(v, event);
                }
                return false;
            }
        });
        buttonMore.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(listener != null){
                    return listener.onPressToSpeakBtnTouch(v, event);
                }
                return false;
            }
        });
    }

    /**
     * 设置长按说话录制控件
     * @param voiceRecorderView
     */
    public void setPressToSpeakRecorderView(EaseVoiceRecorderView voiceRecorderView){
        this.voiceRecorderView = voiceRecorderView;
    }

    /**
     * 表情输入
     * @param emojiContent
     */
    public void onEmojiconInputEvent(CharSequence emojiContent){
        editText.append(emojiContent);
    }

    /**
     * 表情删除
     */
    public void onEmojiconDeleteEvent(){
        if (!TextUtils.isEmpty(editText.getText())) {
            KeyEvent event = new KeyEvent(0, 0, 0, KeyEvent.KEYCODE_DEL, 0, 0, 0, 0, KeyEvent.KEYCODE_ENDCALL);
            editText.dispatchKeyEvent(event);
        }
    }

    /**
     * 点击事件
     * @param view
     */
    @Override
    public void onClick(View view){
        int id = view.getId();
        if (id == R.id.btn_send) {
            if(listener != null){
                String s = editText.getText().toString();
                editText.setText("");
                listener.onSendBtnClicked(s);
            }
        } else if (id == R.id.btn_set_mode_voice) {
            setModeVoice();
            showNormalFaceImage();
            if(listener != null)
                listener.onToggleVoiceBtnClicked();
        } else if (id == R.id.btn_set_mode_keyboard) {
            setModeKeyboard();
            showNormalFaceImage();
            if(listener != null)
                listener.onToggleVoiceBtnClicked();
        } else if (id == R.id.btn_more) {
//            buttonSetModeVoice.setVisibility(View.GONE);
//            buttonSetModeKeyboard.setVisibility(View.GONE);
//            edittext_layout.setVisibility(View.VISIBLE);
//            buttonPressToSpeak.setVisibility(View.GONE);
//            showNormalFaceImage();
//            if(listener != null)
//                listener.onToggleExtendClicked();

        } else if (id == R.id.et_sendmessage) {
//            edittext_layout.setBackgroundResource(R.drawable.ease_input_bar_bg_active);
            faceNormal.setVisibility(View.VISIBLE);
            faceChecked.setVisibility(View.INVISIBLE);
            if(listener != null)
                listener.onEditTextClicked();
        } else if (id == R.id.rl_face) {
            toggleFaceImage();
            if(listener != null){
                listener.onToggleEmojiconClicked();
            }
        } else if(id == R.id.cam){
            Intent intent = new Intent("chat");
            intent.putExtra("select","camera");
            context.sendBroadcast(intent);
        } else {
        }
    }

    /**
     * 显示语音图标按钮
     *
     */
    protected void setModeVoice() {
        hideKeyboard();
        edittext_layout.setVisibility(View.GONE);
        buttonSetModeVoice.setVisibility(View.GONE);
        buttonSetModeKeyboard.setVisibility(View.GONE);
        buttonSend.setVisibility(View.GONE);
        buttonMore.setVisibility(View.VISIBLE);
        buttonPressToSpeak.setVisibility(View.VISIBLE);
        faceNormal.setVisibility(View.VISIBLE);
        faceChecked.setVisibility(View.INVISIBLE);

    }

    /**
     * 显示键盘图标
     */
    protected void setModeKeyboard() {
        edittext_layout.setVisibility(View.VISIBLE);
        buttonSetModeKeyboard.setVisibility(View.GONE);
        buttonSetModeVoice.setVisibility(View.GONE);
        // mEditTextContent.setVisibility(View.VISIBLE);
        editText.requestFocus();
        // buttonSend.setVisibility(View.VISIBLE);
        buttonPressToSpeak.setVisibility(View.GONE);
        if (TextUtils.isEmpty(editText.getText())) {
            buttonMore.setVisibility(View.VISIBLE);
            buttonSend.setVisibility(View.GONE);
        } else {
            buttonMore.setVisibility(View.GONE);
            buttonSend.setVisibility(View.VISIBLE);
        }

    }

    protected void toggleFaceImage(){
        if(faceNormal.getVisibility() == View.VISIBLE){
            showSelectedFaceImage();
        }else{
            showNormalFaceImage();
        }
    }

    private void showNormalFaceImage(){
        faceNormal.setVisibility(View.VISIBLE);
        faceChecked.setVisibility(View.INVISIBLE);
    }

    private void showSelectedFaceImage(){
        faceNormal.setVisibility(View.INVISIBLE);
        faceChecked.setVisibility(View.VISIBLE);
    }

    @Override
    public void onExtendMenuContainerHide() {
        showNormalFaceImage();
    }

}


text:
typedef struct _FooStruct2 FooStruct2;

#include "foo_struct_2_internal.h"

#endif


text:
*GraphsJ - Scenario Development Kit (SDK)*

## Introduction

**GraphsJ SDK** is a library providing traits and classes to easily create scenarios that can be imported and run within [GraphsJ](http://gianlucacosta.info/GraphsJ/).

The framework is very minimalist and inspired by Functional Programming - in particular, it employs the [EighthBridge](https://github.com/giancosta86/EighthBridge) toolkit.

## Referencing the SDK

The SDK is available on [Hephaestus](https://bintray.com/giancosta86/Hephaestus) and can be declared as a Gradle or Maven dependency; please refer to [its dedicated page](https://bintray.com/giancosta86/Hephaestus/GraphsJ-sdk).

Alternatively, you could download the JAR file from Hephaestus and manually add it to your project structure.

**IMPORTANT**: the SDK should be referenced as a **provided** dependency, needed only during the compilation of your project - as it is provided by GraphsJ itself at runtime.

## Employing the SDK

Basically speaking, to create a new scenario for GraphsJ, you should:

0. Implement the **Algorithm** trait, to express the algorithm logic

0. Implement the **Scenario** trait, to provide details on:
  * the scenario

  * the graph

  * the controllers handling user interaction

0. Implement the **ScenarioFactory** trait, which should instantiate the Scenario

Creating a scenario requires knowledge of [EighthBridge](https://github.com/giancosta86/EighthBridge), the ScalaFX library dedicated to graph modeling and interactive rendering.

Interesting examples are available in [GraphsJ - Scenarios](https://bintray.com/giancosta86/Hephaestus/GraphsJ-scenarios), an open source project containing scenarios for both Artificial Intelligence and Operations Research.

For further information, please refer to the related Scaladoc documentation.

## Referencing external libraries

The following libraries are automatically provided by GraphsJ SDK:

* [EighthBridge](https://github.com/giancosta86/EighthBridge): for graph modeling and rendering

* [LambdaPrism](https://github.com/giancosta86/LambdaPrism): for Artificial Intelligence

* [OmniEditor](https://github.com/giancosta86/OmniEditor): providing an editor with syntax highlighting

* [Helios-fx](https://github.com/giancosta86/Helios-fx): library of shared utilities

Other libraries *cannot* be referenced by a scenario, unless your build tools includes their classes within your jar, making it self-contained.

## Further references

* [Facebook page](https://www.facebook.com/graphsj)

* [GraphsJ](https://github.com/giancosta86/GraphsJ)


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

namespace Magpie.Compilation
{
    /// <summary>
    /// Represents a named type generated and used by a foreign interface.
    /// To the rest of Magpie, the type is essentially an opaque object
    /// with a name.
    /// </summary>
    public class ForeignType : INamedType
    {
        public ForeignType(string name)
        {
            Name = name;
        }

        #region INamedType Members

        public Position Position { get { return Position.None; } }

        public string Name { get; private set; }

        public IBoundDecl[] TypeArguments
        {
            get { return new IBoundDecl[0]; }
        }

        #endregion

        #region IBoundDecl Members

        public TReturn Accept<TReturn>(IBoundDeclVisitor<TReturn> visitor)
        {
            return visitor.Visit(this);
        }

        #endregion
    }
}