text:
if $: #need for running on PC
     $: << '.'
end

load "engine.rb"
load "components.rb"
load "maps.rb"

class AnimateFrame

  def initialize(seq, options = {})
    @seq = seq
    @options = options
  end

  def render(sheet, renderer, pos)
    sheet.blit(@seq[0].at(0), @seq[0].at(1), renderer, pos)
  end
end

class BasicSheet
  def initialize(renderer, file, width, height, cell)
    @size_cell = cell
    @width = width; @height = height
    @sheet = SDL2::Video::Surface.load_bmp(file)

    @sheet.rle true

    @sheet.color_key_set(1, @sheet.format.mapRGB(0xff, 0x00, 0xff))

    @texture = SDL2::Video::Texture.new(renderer, @sheet)
    @static = {}
  end

  def set(id, idx, idy)
    @static[id] = [idx, idy]
  end

  def blit_static(id, renderer, pos)
    blit(@static[id].at(0), @static[id].at(1), renderer, pos)
  end

  def blit(idx, idy, renderer, pos)
    frame = SDL2::Rect.new(@size_cell * idx, @size_cell * idy, @size_cell, @size_cell)
    renderer.copy(@texture, frame, SDL2::Rect.new(pos.x * @size_cell, pos.y * @size_cell, @size_cell, @size_cell))
  end
end

class BasicMap

  #::sheet:: the sprite sheet
  #::map:: [[sheetx, sheety, mapx, mapy]...]
  def initialize(sheet, map, objects)
    @sheet = sheet
    @map = map
    @objects = objects
  end

  def blit(renderer)
    @map.each { |cell|
      @sheet.blit(cell.at(0), cell.at(1), renderer, SDL2::Point.new(cell.at(2), cell.at(3)))
    }
  end

  def build(entity_manager, component_manager, sheet)
    @objects.each{ |cell|
      entity_manager.build {|eid|
        case cell.at(4)
        when :brick
          component_manager.set(eid, ComponentBrick.new)
          component_manager.set(eid, ComponentFrameSheet.new(cell.at(0), cell.at(1)))
        else
          component_manager.set(eid, ComponentFrameSheet.new(cell.at(0), cell.at(1)))
        end
        component_manager.set(eid, ComponentSolid.new)
        component_manager.set(eid, ComponentPosition.new(cell.at(2), cell.at(3)))

      }
    }

  end
end

### SYSTEM MANAGER
SystemManager.instance.userdata[:screen] = {
  :width => 256, :height => 256,
  :cols => 15, :rows => 15
}
SystemManager.instance.userdata[:player] = {
  life: 4
}

SystemManager.instance.observer.add(:collision) {|entity, with|
  if entity[ComponentHurt] and with[ComponentSolid]
    EntityManager.instance.delete(entity[ComponentEntityID].id)
    ComponentManager.instance.delete(entity[ComponentEntityID].id)
  end

  #destroy something brickable when receive damage
  if entity[ComponentHurt] and with[ComponentBrick]
    EntityManager.instance.delete(with[ComponentEntityID].id)
    ComponentManager.instance.delete(with[ComponentEntityID].id)
  end

  #ups the fire destroy the item
  if entity[ComponentHurt] and with[ComponentDrag]
    EntityManager.instance.delete(with[ComponentEntityID].id)
    ComponentManager.instance.delete(with[ComponentEntityID].id)
  end

  #the entity take a item
  if entity[ComponentAvatar] and with[ComponentDrag]
    EntityManager.instance.delete(with[ComponentEntityID].id)
    ComponentManager.instance.delete(with[ComponentEntityID].id)
  end

  if entity[ComponentHurt] and with[ComponentPlayer]
    puts "upss that's hurt"
  end

  if entity[ComponentPlayer]
    puts "upss tha't to hard"
  end
}

SystemManager.instance.add{|userdata, observer|

  ComponentManager.instance.select{|entity| entity[ComponentBomb] || entity[ComponentHurt] || entity[ComponentTickout]}.each{|entity|
    tickout = entity[ComponentBomb] || entity[ComponentHurt] || entity[ComponentTickout]
    tickout.tick
    if tickout.out?
      tickout.out(entity)
      EntityManager.instance.delete(entity[ComponentEntityID].id)
      ComponentManager.instance.delete(entity[ComponentEntityID].id)
    end
  }

}

#System for player manager
SystemManager.instance.add{|userdata, observer|
  ComponentManager.instance.select{|entity| entity[ComponentSystemEvent] and entity[ComponentPlayer] and entity[ComponentPosition] and entity[ComponentDirection]}.each{|entity|
    entity[ComponentDirection].clean!
    until (ev = entity[ComponentSystemEvent].events.pop).nil?
      case ev.type
      when SDL2::Input::SDL_KEYDOWN
        case ev.keysym.scancode
        when entity[ComponentPlayer].up
          entity[ComponentDirection].up!
        when entity[ComponentPlayer].down
          entity[ComponentDirection].down!
        when entity[ComponentPlayer].left
          entity[ComponentDirection].left!
        when entity[ComponentPlayer].right
          entity[ComponentDirection].right!
        when entity[ComponentPlayer].bomb
          EntityManager.instance.build{|eid|
            bomb = ComponentBomb.new(100, entity[ComponentPlayer].bomb_strong) {|bentity|
              %w(right left up down).each {|dir|
                EntityManager.instance.build{|hid|
                  ComponentManager.instance.set(hid, ComponentHurt.new(1 * bentity[ComponentBomb].strong))
                  ComponentManager.instance.set(hid, ComponentFrameSheet.new(15, 4))
                  ComponentManager.instance.set(hid, ComponentSharedData.new(:counter => 0, :strong => bentity[ComponentBomb].strong))
                  ComponentManager.instance.set(hid, ComponentSolid.new)
                  ComponentManager.instance.set(hid, ComponentDirection.new(dir.to_sym))
                  ComponentManager.instance.set(hid, ComponentStep.new(bentity[ComponentBomb].strong))
                  ComponentManager.instance.set(hid, ComponentPosition.new(bentity[ComponentPosition].x, bentity[ComponentPosition].y))

                }
              }
            }
            ComponentManager.instance.set(eid, bomb)
            ComponentManager.instance.set(eid, ComponentSolid.new)
            ComponentManager.instance.set(eid, ComponentFrameSheet.new(14, 3))
            ComponentManager.instance.set(eid, ComponentPosition.new(entity[ComponentPosition].x, entity[ComponentPosition].y))
          }
        end
      end
    end
  }

  #collision
  ComponentManager.instance.select{|entity| entity[ComponentDirection] and entity[ComponentPosition]}.each{|entity|

    ComponentManager.instance.select{|e| e[ComponentSolid] and e[ComponentPosition] and e != entity}.each{|block|
      case entity[ComponentDirection].direction
      when :right
        if block[ComponentPosition].y == entity[ComponentPosition].y and block[ComponentPosition].x == entity[ComponentPosition].x + 1
          observer.notify(:collision, entity, block)
          entity[ComponentDirection].clean!
          break
        end
      when :left
        if block[ComponentPosition].y == entity[ComponentPosition].y and block[ComponentPosition].x == entity[ComponentPosition].x - 1
          observer.notify(:collision, entity, block)
          entity[ComponentDirection].clean!
          break
        end
      when :up
        if block[ComponentPosition].x == entity[ComponentPosition].x and block[ComponentPosition].y == entity[ComponentPosition].y - 1
          observer.notify(:collision, entity, block)
          entity[ComponentDirection].clean!
          break
        end
      when :down
        if  block[ComponentPosition].x == entity[ComponentPosition].x and block[ComponentPosition].y == entity[ComponentPosition].y + 1
          observer.notify(:collision, entity, block)
          entity[ComponentDirection].clean!
          break
        end
      end
    }
    entity[ComponentDirection].clean! if entity[ComponentStep] and entity[ComponentStep].steps == 0
    case entity[ComponentDirection].direction
    when :right
      entity[ComponentPosition].x += 1 if entity[ComponentPosition].x + 1 < userdata[:screen][:cols]
    when :left
      entity[ComponentPosition].x -= 1 if entity[ComponentPosition].x - 1 > 0
    when :up
      entity[ComponentPosition].y -= 1 if entity[ComponentPosition].y - 1 > 0
    when :down
      entity[ComponentPosition].y += 1 if entity[ComponentPosition].y + 1 < userdata[:screen][:rows]
    end

    #guard steps
    entity[ComponentStep].dec if entity[ComponentStep]

  }

}

### MAIN

X = SDL2::Video::Window::SDL_WINDOWPOS_CENTERED
Y = SDL2::Video::Window::SDL_WINDOWPOS_CENTERED
W = 256
H = 256
$quit = false

SDL2::init
begin
  SDL2::Video::init
  begin
    w = SDL2::Video::Window.new "test1", X, Y, W, H, SDL2::Video::Window::SDL_WINDOW_SHOWN
    renderer = SDL2::Video::Renderer.new(w)

    sheet = BasicSheet.new(renderer, "sheet.bmp", 256, 96, 16)
    map = BasicMap.new(sheet, $maps[:lost_ruby][:data], $maps[:lost_ruby][:objects])

    map.build(EntityManager.instance, ComponentManager.instance, sheet)

    #build player
    EntityManager.instance.build {|eid|
      ComponentManager.instance.set(eid, ComponentSystemEvent.new)
      ComponentManager.instance.set(eid, ComponentDirection.new(:right))
      ComponentManager.instance.set(eid, ComponentPosition.new(5, 5))
      ComponentManager.instance.set(eid, ComponentSolid.new)
      ComponentManager.instance.set(eid, ComponentPlayer.new(SDL2::Input::Keyboard::SDL_SCANCODE_8, SDL2::Input::Keyboard::SDL_SCANCODE_5, SDL2::Input::Keyboard::SDL_SCANCODE_4, SDL2::Input::Keyboard::SDL_SCANCODE_6, SDL2::Input::Keyboard::SDL_SCANCODE_0))
      ComponentManager.instance.set(eid, ComponentAvatar.new({
                                                               standing: AnimateFrame.new([[0, 4]]),
                                                               walking_right: AnimateFrame.new([[4, 4], [5, 4], [6, 4]]),
                                                               walking_left: AnimateFrame.new([[4, 4], [5, 4], [6, 4]], mirror: true),
                                                               walking_up: AnimateFrame.new([[8, 4], [9, 4]]),
                                                               walking_down: AnimateFrame.new([[3, 4], [4, 4]]),
                                                             })
                                   )
    }

    while !$quit

      while !(ev = SDL2::Input::poll).nil?
        if ev.type == SDL2::Input::SDL_QUIT then
          $quit = true; break
        end
        ComponentManager.instance.select{|entity| entity[ComponentSystemEvent]}.each{|entity|
          entity[ComponentSystemEvent].events << ev
        }
      end

      renderer.draw_color = SDL2::RGB.new(0, 0, 0)
      renderer.clear

      SystemManager.instance.run { |userdata, observer|
        map.blit(renderer)
        ComponentManager.instance.select{|entity| entity[ComponentFrameSheet] and entity[ComponentPosition]}.each{|entity|
          sheet.blit(entity[ComponentFrameSheet].x, entity[ComponentFrameSheet].y,
                     renderer,
                     SDL2::Point.new(entity[ComponentPosition].x, entity[ComponentPosition].y)
                    )
        }

        ComponentManager.instance.select{|entity| entity[ComponentAvatar] and entity[ComponentPosition] and entity[ComponentDirection]}.each{|entity|

          userdata[entity] ||=  {}
          case entity[ComponentDirection].direction
          when :left
            userdata[entity][:anim] = entity[ComponentAvatar].frames[:walking_left]
          when :right
            userdata[entity][:anim] = entity[ComponentAvatar].frames[:walking_right]
          when :up
            userdata[entity][:anim] = entity[ComponentAvatar].frames[:walking_up]
          when :down
            userdata[entity][:anim] = entity[ComponentAvatar].frames[:walking_down]
          end
          userdata[entity][:anim] = entity[ComponentAvatar].frames[:standing] if userdata[entity][:anim].nil?
          userdata[entity][:anim].render(sheet, renderer, entity[ComponentPosition])
        }

      }

      renderer.present
    end

    renderer.destroy
    w.destroy
  ensure
    SDL2::Video::quit
  end
rescue Exception => e
  puts e
  puts e.backtrace
ensure
  exit 0
end

redpajama_set_name: RedPajamaGithub


text:
This document is a declaration of software quality for the `rmw` package, based on the guidelines in [REP-2004](https://www.ros.org/reps/rep-2004.html).

# `rmw` Quality Declaration

The package `rmw` claims to be in the **Quality Level 1** category.

Below are the rationales, notes, and caveats for this claim, organized by each requirement listed in the [Package Requirements for Quality Level 1 in REP-2004](https://www.ros.org/reps/rep-2004.html).

## Version Policy [1]

### Version Scheme [1.i]

`rmw` uses `semver` according to the recommendation for ROS Core packages in the [ROS 2 Developer Guide](https://docs.ros.org/en/rolling/Contributing/Developer-Guide.html#versioning).

### Version Stability [1.ii]

`rmw` is at a stable version, i.e. `>= 1.0.0`.
The current version can be found in its [package.xml](package.xml), and its change history can be found in its [CHANGELOG](CHANGELOG.rst).

### Public API Declaration [1.iii]

All symbols in the installed headers are considered part of the public API.

All installed headers are in the `include` directory of the package, headers in any other folders are not installed and considered private.

### API Stability Within a Released ROS Distribution [1.iv]/[1.vi]

`rmw` will not break public API within a released ROS distribution, i.e. no major releases once the ROS distribution is released.

### ABI Stability Within a Released ROS Distribution [1.v]/[1.vi]

`rmw` contains C code and therefore must be concerned with ABI stability, and will maintain ABI stability within a ROS distribution.

## Change Control Process [2]

`rmw` follows the recommended guidelines for ROS Core packages in the [ROS 2 Developer Guide](https://docs.ros.org/en/rolling/Contributing/Developer-Guide.html#quality-practices).

### Change Requests [2.i]

This package requires that all changes occur through a pull request.

### Contributor Origin [2.ii]

This package uses DCO as its confirmation of contributor origin policy. More information can be found in [CONTRIBUTING](../CONTRIBUTING.md).

### Peer Review Policy [2.iii]

Following the recommended guidelines for ROS Core packages, all pull requests must have at least 1 peer review.

### Continuous Integration [2.iv]

All pull request must pass CI on all [tier 1 platforms](https://www.ros.org/reps/rep-2000.html#support-tiers)

### Documentation Policy [2.v]

All pull requests must resolve related documentation changes before merging.

## Documentation [3]

### Feature Documentation [3.i]

`rmw` has a [feature list](http://docs.ros2.org/latest/api/rmw/) and each item in the list links to the corresponding feature documentation.
There is documentation for all of the features, and new features require documentation before being added.

### Public API Documentation [3.ii]

`rmw` has embedded API documentation and it is generated using doxygen and is [hosted](https://docs.ros2.org/latest/api/rmw/index.html) alongside the feature documentation.
There is documentation for all of the public API, and new additions to the public API require documentation before being added.

### License [3.iii]

The license for `rmw_implementation_cmake` is Apache 2.0, and a summary is in each source file, the type is declared in the [package.xml](package.xml) manifest file, and a full copy of the license is in the [LICENSE](../LICENSE) file.

There is an automated test which runs a linter that ensures each file has a license statement.

Most recent test results can be found [here](http://build.ros2.org/view/Rpr/job/Rpr__rmw__ubuntu_focal_amd64/lastCompletedBuild/testReport/rmw/).

### Copyright Statements [3.iv]

The copyright holders each provide a statement of copyright in each source code file in `rmw`.

There is an automated test which runs a linter that ensures each file has at least one copyright statement.

The results of those tests are available [here](http://build.ros2.org/view/Rpr/job/Rpr__rmw__ubuntu_focal_amd64/lastCompletedBuild/testReport/rmw/copyright/).

Results of the copyright test can be found [here](http://build.ros2.org/view/Rpr/job/Rpr__rmw__ubuntu_focal_amd64/lastCompletedBuild/testReport/rmw/copyright/).

## Testing [4]

### Feature Testing [4.i]

Some features in `rmw` have corresponding tests which simulate typical usage, and they are located in the `test` directory.
New features are required to have tests before being added.

### Public API Testing [4.ii]

Much of the public API has tests, and new additions or changes to the public API require tests before being added.
The tests aim to cover both typical usage and corner cases, but are quantified by contributing to code coverage.

### Coverage [4.iii]

`rmw` follows the recommendations for ROS Core packages in the [ROS 2 Developer Guide](https://docs.ros.org/en/rolling/Contributing/Developer-Guide.html#code-coverage), and opts to use line coverage instead of branch coverage.

This includes:

- tracking and reporting line coverage statistics
- achieving and maintaining a reasonable branch line coverage (90-100%)
- no lines are manually skipped in coverage calculations

Changes are required to make a best effort to keep or increase coverage before being accepted, but decreases are allowed if properly justified and accepted by reviewers.

This package has testing coverage of at least 95%.
Current coverage statistics can be viewed [here](https://ci.ros2.org/job/ci_linux_coverage/lastSuccessfulBuild/cobertura/).
A description of how coverage statistics are summarized from this page can be found in the [ROS 2 On-boarding Guide](https://docs.ros.org/en/rolling/Contributing/Developer-Guide.html#note-on-coverage-runs).

### Performance [4.iv]

`rmw` follows the recommendations for performance testing of C code in the [ROS 2 Developer Guide](https://docs.ros.org/en/rolling/Contributing/Developer-Guide.html#performance), and opts to do performance analysis on each release rather than each change.

System level performance benchmarks that cover features of `rmw` can be found at:
* [Benchmarks](http://build.ros2.org/view/Rci/job/Rci__benchmark_ubuntu_focal_amd64/BenchmarkTable/)
* [Performance](http://build.ros2.org/view/Rci/job/Rci__nightly-performance_ubuntu_focal_amd64/lastCompletedBuild/)

Changes that introduce regressions in performance must be adequately justified in order to be accepted and merged.

### Linters and Static Analysis [4.v]

`rmw` uses and passes all the standard linters and static analysis tools for a C++ package as described in the [ROS 2 Developer Guide](https://docs.ros.org/en/rolling/Contributing/Developer-Guide.html#linters-and-static-analysis).

Results of linter tests can be found [here](http://build.ros2.org/view/Rpr/job/Rpr__rmw__ubuntu_focal_amd64/lastCompletedBuild/testReport/rmw/).

## Dependencies [5]

Below are evaluations of each of `rmw`'s run-time and build-time dependencies that have been determined to influence the quality.

It has several "buildtool" dependencies, which do not affect the resulting quality of the package, because they do not contribute to the public library API.
It also has several test dependencies, which do not affect the resulting quality of the package, because they are only used to build and run the test code.

### Direct Runtime ROS Dependencies [5.i]/[5.ii]

#### `rcutils`

The `rcutils` package provides an API which contains common utilities and data structures needed when programming in C.

It is **Quality Level 1**, see its [Quality Declaration document](https://github.com/ros2/rcutils/blob/master/QUALITY_DECLARATION.md).

#### `rosidl_runtime_c`

The `rosidl_runtime_c` package provides runtime interfaces in C based on user defined ROS Messages and ROS Services, as well as associated support functions for those types.

It is **Quality Level 1**, see its [Quality Declaration document](https://github.com/ros2/rosidl/tree/master/rosidl_runtime_c/Quality_Declaration.md).

### Direct Runtime Non-ROS Dependencies [5.iii]

`rmw` does not have any runtime non-ROS dependencies.

## Platform Support [6]

`rmw` supports all of the tier 1 platforms as described in [REP-2000](https://www.ros.org/reps/rep-2000.html#support-tiers), and tests each change against all of them.

Currently nightly results can be seen here:
* [linux-aarch64_release](https://ci.ros2.org/view/nightly/job/nightly_linux-aarch64_release/lastBuild/testReport/rmw/)
* [linux_release](https://ci.ros2.org/view/nightly/job/nightly_linux_release/lastBuild/testReport/rmw/)
* [mac_osx_release](https://ci.ros2.org/view/nightly/job/nightly_osx_release/lastBuild/testReport/rmw/)
* [windows_release](https://ci.ros2.org/view/nightly/job/nightly_win_rel/lastBuild/testReport/rmw/)

## Security [7]

### Vulnerability Disclosure Policy [7.i]

This package conforms to the Vulnerability Disclosure Policy in [REP-2006](https://www.ros.org/reps/rep-2006.html).


text:
Deploy MSOnlineExt {
    By AppVeyorModule {
        FromSource src\MSOnlineExt
        To AppVeyor
        Tagged Test
        WithOptions @{
            Version = $env:APPVEYOR_BUILD_VERSION
        }
    }
}


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

<title>com.example.habittracker2017.entityTests</title>
<meta name="date" content="2017-12-04">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

com.example.habittracker2017.entityTests

Classes

UserTests


text:
package commands

import (
	"github.com/spf13/cobra"

	"github.com/mantl/consul-cli/action"
)

func newCatalogCommand() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "catalog",
		Short: "Consul /catalog endpoint interface",
		Long:  "Consul /catalog endpoint interface",
		Run: func(cmd *cobra.Command, args []string) {
			cmd.HelpFunc()(cmd, []string{})
		},
	}

	cmd.AddCommand(newCatalogDatacentersCommand())
	cmd.AddCommand(newCatalogDeregisterCommand())
	cmd.AddCommand(newCatalogNodeCommand())
	cmd.AddCommand(newCatalogNodesCommand())
	cmd.AddCommand(newCatalogRegisterCommand())
	cmd.AddCommand(newCatalogServiceCommand())
	cmd.AddCommand(newCatalogServicesCommand())

	return cmd
}

func newCatalogDatacentersCommand() *cobra.Command {
	c := action.CatalogDatacentersAction()

	cmd := &cobra.Command{
		Use:   "datacenters",
		Short: "Get all the datacenters known by the Consul server",
		Long:  "Get all the datacenters known by the Consul server",
		RunE: func(cmd *cobra.Command, args []string) error {
			return c.Run(args)
		},
	}

	cmd.Flags().AddGoFlagSet(c.CommandFlags())

	return cmd
}

var deregisterLongHelp = `Deregister a service, node or check from the catalog

  If only --node is provided, the node and all associated services and checks are
deleted.

  If --check-id is provided, only that check is removed.

  If --service-id is provided, only that service is removed.
`

func newCatalogDeregisterCommand() *cobra.Command {
	c := action.CatalogDeregisterAction()

	cmd := &cobra.Command{
		Use:   "deregister",
		Short: "Deregisters a node, service or check",
		Long:  deregisterLongHelp,
		RunE: func(cmd *cobra.Command, args []string) error {
			return c.Run(args)
		},
	}

	cmd.Flags().AddGoFlagSet(c.CommandFlags())

	return cmd
}

func newCatalogNodeCommand() *cobra.Command {
	c := action.CatalogNodeAction()

	cmd := &cobra.Command{
		Use:   "node",
		Short: "Get the services provided by a node",
		Long:  "Get the services provided by a node",
		RunE: func(cmd *cobra.Command, args []string) error {
			return c.Run(args)
		},
	}

	cmd.Flags().AddGoFlagSet(c.CommandFlags())

	return cmd
}

func newCatalogNodesCommand() *cobra.Command {
	c := action.CatalogNodesAction()

	cmd := &cobra.Command{
		Use:   "nodes",
		Short: "Get all the nodes registered with a given DC",
		Long:  "Get all the nodes registered with a given DC",
		RunE: func(cmd *cobra.Command, args []string) error {
			return c.Run(args)
		},
	}

	cmd.Flags().AddGoFlagSet(c.CommandFlags())

	return cmd
}

func newCatalogRegisterCommand() *cobra.Command {
	c := action.CatalogRegisterAction()

	cmd := &cobra.Command{
		Use:   "register-service <name>",
		Short: "Register external services",
		Long:  "Register external services",
		RunE: func(cmd *cobra.Command, args []string) error {
			return c.Run(args)
		},
	}

	cmd.Flags().AddGoFlagSet(c.CommandFlags())

	return cmd
}

func newCatalogServiceCommand() *cobra.Command {
	c := action.CatalogServiceAction()

	cmd := &cobra.Command{
		Use:   "service",
		Short: "Get the services provided by a node",
		Long:  "Get the services provided by a node",
		RunE: func(cmd *cobra.Command, args []string) error {
			return c.Run(args)
		},
	}

	cmd.Flags().AddGoFlagSet(c.CommandFlags())

	return cmd
}

func newCatalogServicesCommand() *cobra.Command {
	c := action.CatalogServicesAction()

	cmd := &cobra.Command{
		Use:   "services",
		Short: "Get all the services registered with a given DC",
		Long:  "Get all the services registered with a given DC",
		RunE: func(cmd *cobra.Command, args []string) error {
			return c.Run(args)
		},
	}

	cmd.Flags().AddGoFlagSet(c.CommandFlags())

	return cmd
}


text:
/**
 * XMLHttpRequest shim for node.js
 *
 * @method xhr
 * @return {Object} XMLHttpRequest instance
 */
var xhr = function () {
	var UNSENT           = 0,
	    OPENED           = 1,
	    HEADERS_RECEIVED = 2,
	    LOADING          = 3,
	    DONE             = 4,
	    ERR_REFUSED      = /ECONNREFUSED/,
	    ready            = new RegExp( HEADERS_RECEIVED + "|" + LOADING ),
	    XMLHttpRequest, headers, handler, handlerError, state;

	headers = {
		"User-Agent"   : "abaaso/{{VERSION}} node.js/" + process.versions.node.replace( /^v/, "" ) + " (" + string.capitalize( process.platform ) + " V8/" + process.versions.v8 + " )",
		"Content-Type" : "text/plain",
		"Accept"       : "*/*"
	};

	/**
	 * Changes the readyState of an XMLHttpRequest
	 *
	 * @method state
	 * @param  {String} arg New readyState
	 * @return {Object}     XMLHttpRequest instance
	 */
	state = function ( arg ) {
		if ( this.readyState !== arg ) {
			this.readyState = arg;
			this.dispatchEvent( "readystatechange" );

			if ( this.readyState === DONE && !this._error ) {
				this.dispatchEvent( "load" );
				this.dispatchEvent( "loadend" );
			}
		}

		return this;
	};

	/**
	 * Response handler
	 *
	 * @method handler
	 * @param  {Object} res HTTP(S) Response Object
	 * @return {undefined}  undefined
	 */
	handler = function ( res ) {
		var self = this;

		state.call( this, HEADERS_RECEIVED );

		this.status      = res.statusCode;
		this._resheaders = res.headers;

		if ( this._resheaders["set-cookie"] !== undefined && this._resheaders["set-cookie"] instanceof Array ) {
			this._resheaders["set-cookie"] = this._resheaders["set-cookie"].join( ";" );
		}

		res.on( "data", function ( arg ) {
			res.setEncoding( "utf8" );

			if ( self._send ) {
				if ( arg ) {
					self.responseText += arg;
				}

				state.call( self, LOADING );
			}
		});

		res.on( "end", function () {
			if ( self._send ) {
				state.call( self, DONE );
				self._send = false;
			}
		});
	};

	/**
	 * Response error handler
	 *
	 * @method handlerError
	 * @param  {Object} e Error
	 * @return {Undefined} undefined
	 */
	handlerError = function ( e ) {
		this.status       = ERR_REFUSED.test( e.message ) ? 503 : 500;
		this.statusText   = "";
		this.responseText = e.message || label.error.serverError;
		this._error       = true;
		this._send        = false;
		this.dispatchEvent( "error" );
		state.call( this, DONE );
	};

	/**
	 * XMLHttpRequest
	 *
	 * @method XMLHttpRequest
	 * @constructor
	 * @return {Object} XMLHttpRequest instance
	 */
	XMLHttpRequest = function () {
		this.onabort            = null;
		this.onerror            = null;
		this.onload             = null;
		this.onloadend          = null;
		this.onloadstart        = null;
		this.onreadystatechange = null;
		this.readyState         = UNSENT;
		this.response           = null;
		this.responseText       = "";
		this.responseType       = "";
		this.responseXML        = null;
		this.status             = UNSENT;
		this.statusText         = "";

		// Psuedo private for prototype chain
		this._id                = utility.genId();
		this._error             = false;
		this._headers           = {};
		this._listeners         = {};
		this._params            = {};
		this._request           = null;
		this._resheaders        = {};
		this._send              = false;
	};

	/**
	 * Aborts a request
	 *
	 * @method abort
	 * @return {Object} XMLHttpRequest instance
	 */
	XMLHttpRequest.prototype.abort = function () {
		if ( this._request !== null ) {
			this._request.abort();
			this._request = null;
		}

		this.responseText = "";
		this.responseXML  = "";
		this._error       = true;
		this._headers     = {};

		if ( this._send === true || ready.test( this.readyState ) ) {
			this._send = false;
			state.call( this, DONE );
		}

		this.dispatchEvent( "abort" );
		this.readyState = UNSENT;

		return this;
	};

	/**
	 * Adds an event listener to an XMLHttpRequest instance
	 *
	 * @method addEventListener
	 * @param {String}   event Event to listen for
	 * @param {Function} fn    Event handler
	 * @return {Object}        XMLHttpRequest instance
	 */
	XMLHttpRequest.prototype.addEventListener = function ( event, fn ) {
		if ( !this._listeners.hasOwnProperty( event ) ) {
			this._listeners[event] = [];
		}

		this._listeners[event].add( fn );

		return this;
	};

	/**
	 * Dispatches an event
	 *
	 * @method dispatchEvent
	 * @param  {String} event Name of event
	 * @return {Object}       XMLHttpRequest instance
	 */
	XMLHttpRequest.prototype.dispatchEvent = function ( event ) {
		var self = this;

		if ( typeof this["on" + event] === "function" ) {
			this["on" + event]();
		}

		if ( this._listeners.hasOwnProperty( event )) {
			array.each( this._listeners[event], function ( i ) {
				if ( typeof i === "function" ) {
					i.call( self );
				}
			});
		}

		return this;
	};

	/**
	 * Gets all response headers
	 *
	 * @method getAllResponseHeaders
	 * @return {Object} Response headers
	 */
	XMLHttpRequest.prototype.getAllResponseHeaders = function () {
		var result = "";

		if ( this.readyState < HEADERS_RECEIVED ) {
			throw new Error( label.error.invalidStateNoHeaders );
		}

		utility.iterate( this._resheaders, function ( v, k ) {
			result += k + ": " + v + "\n";
		});

		return result;
	};

	/**
	 * Gets a specific response header
	 *
	 * @method getResponseHeader
	 * @param  {String} header Header to get
	 * @return {String}        Response header value
	 */
	XMLHttpRequest.prototype.getResponseHeader = function ( header ) {
		var result;

		if ( this.readyState < HEADERS_RECEIVED || this._error ) {
			throw new Error( label.error.invalidStateNoHeaders );
		}

		result = this._resheaders[header] || this._resheaders[header.toLowerCase()];

		return result;
	};

	/**
	 * Prepares an XMLHttpRequest instance to make a request
	 *
	 * @method open
	 * @param  {String}  method   HTTP method
	 * @param  {String}  url      URL to receive request
	 * @param  {Boolean} async    [Optional] Asynchronous request
	 * @param  {String}  user     [Optional] Basic auth username
	 * @param  {String}  password [Optional] Basic auth password
	 * @return {Object}           XMLHttpRequest instance
	 */
	XMLHttpRequest.prototype.open = function ( method, url, async, user, password ) {
		var self = this;

		if ( async !== undefined && async !== true) {
			throw new Error( label.error.invalidStateNoSync );
		}

		this.abort();
		this._error  = false;
		this._params = {
			method   : method,
			url      : url,
			async    : async    || true,
			user     : user     || null,
			password : password || null
		};

		utility.iterate( headers, function ( v, k ) {
			self._headers[k] = v;
		});

		this.readyState = OPENED;

		return this;
	};

	/**
	 * Overrides the Content-Type of the request
	 *
	 * @method overrideMimeType
	 * @param  {String} mime Mime type of the request ( media type )
	 * @return {Object}      XMLHttpRequest instance
	 */
	XMLHttpRequest.prototype.overrideMimeType = function ( mime ) {
		this._headers["Content-Type"] = mime;

		return this;
	};

	/**
	 * Removes an event listener from an XMLHttpRequest instance
	 *
	 * @method removeEventListener
	 * @param {String}   event Event to listen for
	 * @param {Function} fn    Event handler
	 * @return {Object}        XMLHttpRequest instance
	 */
	XMLHttpRequest.prototype.removeEventListener = function ( event, fn ) {
		if ( !this._listeners.hasOwnProperty( event ) ) {
			return;
		}

		this._listeners[event].remove( fn );

		return this;
	};

	/**
	 * Sends an XMLHttpRequest request
	 *
	 * @method send
	 * @param  {Mixed} data [Optional] Payload to send with the request
	 * @return {Object}     XMLHttpRequest instance
	 */
	XMLHttpRequest.prototype.send = function ( data ) {
		data     = data || null;
		var self = this,
		    options, parsed, request, obj;

		if ( this.readyState < OPENED ) {
			throw new Error( label.error.invalidStateNotOpen );
		}
		else if ( this._send ) {
			throw new Error( label.error.invalidStateNotSending );
		}

		parsed      = utility.parse( this._params.url );
		parsed.port = parsed.port || ( parsed.protocol === "https:" ? 443 : 80 );

		if ( this._params.user !== null && this._params.password !== null ) {
			parsed.auth = this._params.user + ":" + this._params.password;
		}

		// Specifying Content-Length accordingly
		if ( regex.put_post.test( this._params.method ) || regex.patch.test( this._params.method ) ) {
			if ( data === null ) {
				this._headers["content-length"] = 0;
			}
			else if ( typeof data == "string" ) {
				this._headers["content-length"] = Buffer.byteLength( data );
			}
			else if ( data instanceof Buffer || typeof data.toString == "function" ) {
				data = data.toString();
				this._headers["content-length"] = Buffer.byteLength( data );
			}
			else {
				throw new Error( label.error.invalidArguments );
			}
		}

		this._headers.Host = parsed.host;

		options = {
			hostname : parsed.hostname,
			path     : parsed.path,
			port     : parsed.port,
			method   : this._params.method,
			headers  : this._headers,
			agent    : false
		};

		if ( parsed.protocol === "https:" ) {
			options.rejectUnauthorized = false;
		}

		if ( parsed.auth !== undefined && !string.isEmpty( parsed.auth ) ) {
			options.auth = parsed.auth;
		}

		self._send = true;
		self.dispatchEvent( "readystatechange" );

		obj = parsed.protocol === "http:" ? http : https;

		request = obj.request( options, function ( arg ) {
			handler.call( self, arg );
		} ).on( "error", function ( e ) {
			handlerError.call( self, e );
		} ).on( "timeout", function () {
			request.abort();
		} );

		data === null ? request.setSocketKeepAlive( true ) : request.write( data, "utf8" );
		this._request = request;
		request.end();

		self.dispatchEvent( "loadstart" );

		return this;
	};

	/**
	 * Sets a request header of an XMLHttpRequest instance
	 *
	 * @method setRequestHeader
	 * @param {String} header HTTP header
	 * @param {String} value  Header value
	 * @return {Object}       XMLHttpRequest instance
	 */
	XMLHttpRequest.prototype.setRequestHeader = function ( header, value ) {
		if ( this.readyState !== OPENED ) {
			throw new Error( label.error.invalidStateNotUsable );
		}
		else if ( this._send ) {
			throw new Error( label.error.invalidStateNotSending );
		}

		this._headers[header] = value;

		return this;
	};

	return XMLHttpRequest;
};


text:
require File.expand_path("../Abstract/abstract-osquery-formula", __FILE__)

class Libdevmapper < AbstractOsqueryFormula
  desc "Device Mapper development"
  homepage "https://www.sourceware.org/dm/"
  url "https://osquery-packages.s3.amazonaws.com/deps/LVM2.2.02.145.tar.gz"
  sha256 "98b7c4c07c485a462c6a86e1a5265757133ceea36289ead8a419af29ef39560b"

  bottle do
    root_url "https://osquery-packages.s3.amazonaws.com/bottles"
    cellar :any_skip_relocation
    sha256 "e1041607e866c145ee82c3a5babc2df4942b3ac1ba905c7bc135d98a6256dbf4" => :x86_64_linux
  end

  def install
    # When building with LLVM/clang do not expect symbol versioning information.
    inreplace "lib/misc/lib.h", "defined(__GNUC__)", "defined(__GNUC__) && !defined(__clang__)"

    args = [
      "--with-lvm1=none",
      "--disable-selinux",
      "--enable-static_link",
    ]

    system "./configure", "--prefix=#{prefix}", *args
    system "make", "libdm.device-mapper"
    cd "libdm" do
      system "make", "install"
    end
  end
end


text:
package types

// VPCRouterFirewallProtocolStrings VPCルータでのファイアウォールプロトコルを表す文字列
var VPCRouterFirewallProtocolStrings = []string{"tcp", "udp", "icmp", "ip"}

// EVPCRouterFirewallProtocol VPCルータでのファイアウォールプロトコルを表す文字列
type EVPCRouterFirewallProtocol string

// VPCRouterFirewallProtocols ファイアアウォール プロトコル
var VPCRouterFirewallProtocols = struct {
	// TCP tcp
	TCP EVPCRouterFirewallProtocol
	// UDP udp
	UDP EVPCRouterFirewallProtocol
	// ICMP udp
	ICMP EVPCRouterFirewallProtocol
	// ICMP udp
	IP EVPCRouterFirewallProtocol
}{
	TCP:  EVPCRouterFirewallProtocol("tcp"),
	UDP:  EVPCRouterFirewallProtocol("udp"),
	ICMP: EVPCRouterFirewallProtocol("icmp"),
	IP:   EVPCRouterFirewallProtocol("ip"),
}


text:
from time import asctime
import logging
from logging.config import fileConfig
from argparse import ArgumentParser
from os.path import exists
from frontera.utils.misc import load_object

from frontera.core.manager import FrontierManager
from frontera.logger.handlers import CONSOLE
from twisted.internet.task import LoopingCall
from twisted.internet import reactor

from frontera.settings import Settings
from frontera.contrib.backends.remote.codecs.msgpack import Decoder, Encoder
from collections import Sequence

logger = logging.getLogger("strategy-worker")

class UpdateScoreStream(object):
    def __init__(self, encoder, scoring_log_producer, size):
        self._encoder = encoder
        self._buffer = []
        self._producer = scoring_log_producer
        self._size = size

    def send(self, url, fingerprint, score=1.0, dont_queue=False):
        encoded = self._encoder.encode_update_score(
            fingerprint,
            score,
            url,
            not dont_queue
        )
        self._buffer.append(encoded)
        if len(self._buffer) > self._size:
            self.flush()

    def flush(self):
        self._producer.send(None, *self._buffer)
        self._buffer = []

class StatesContext(object):

    def __init__(self, states):
        self._requests = []
        self._states = states
        self._fingerprints = set()
        self.cache_flush_counter = 0

    def to_fetch(self, requests):
        if isinstance(requests, Sequence):
            self._fingerprints.update(map(lambda x: x.meta['fingerprint'], requests))
            return
        self._fingerprints.add(requests.meta['fingerprint'])

    def fetch(self):
        self._states.fetch(self._fingerprints)
        self._fingerprints.clear()

    def refresh_and_keep(self, request):
        self._states.fetch([request.meta['fingerprint']])
        self._states.set_states(request)
        self._requests.append(request)

    def release(self):
        self._states.update_cache(self._requests)
        self._requests = []

        # Flushing states cache if needed
        if self.cache_flush_counter == 30:
            logger.info("Flushing states")
            self._states.flush(force_clear=False)
            logger.info("Flushing states finished")
            self.cache_flush_counter = 0

        self.cache_flush_counter += 1

class StrategyWorker(object):
    def __init__(self, settings, strategy_class):
        partition_id = settings.get('SCORING_PARTITION_ID')
        if partition_id is None or type(partition_id) != int:
            raise AttributeError("Scoring worker partition id isn't set.")

        messagebus = load_object(settings.get('MESSAGE_BUS'))
        mb = messagebus(settings)
        spider_log = mb.spider_log()
        scoring_log = mb.scoring_log()
        self.consumer = spider_log.consumer(partition_id=partition_id, type='sw')
        self.scoring_log_producer = scoring_log.producer()

        self._manager = FrontierManager.from_settings(settings, strategy_worker=True)
        self._decoder = Decoder(self._manager.request_model, self._manager.response_model)
        self._encoder = Encoder(self._manager.request_model)

        self.update_score = UpdateScoreStream(self._encoder, self.scoring_log_producer, 1024)
        self.states_context = StatesContext(self._manager.backend.states)

        self.consumer_batch_size = settings.get('CONSUMER_BATCH_SIZE')
        self.strategy = strategy_class.from_worker(self._manager, self.update_score, self.states_context)
        self.states = self._manager.backend.states
        self.stats = {
            'consumed_since_start': 0
        }
        self.job_id = 0
        self.task = LoopingCall(self.work)
        self._logging_task = LoopingCall(self.log_status)
        logger.info("Strategy worker is initialized and consuming partition %d", partition_id)

    def work(self):
        # Collecting batch to process
        consumed = 0
        batch = []
        for m in self.consumer.get_messages(count=self.consumer_batch_size, timeout=1.0):
            try:
                msg = self._decoder.decode(m)
            except (KeyError, TypeError), e:
                logger.error("Decoding error: %s", e)
                continue
            else:
                type = msg[0]
                batch.append(msg)
                if type == 'add_seeds':
                    _, seeds = msg
                    self.states_context.to_fetch(seeds)
                    continue

                if type == 'page_crawled':
                    _, response, links = msg
                    self.states_context.to_fetch(response)
                    self.states_context.to_fetch(links)
                    continue

                if type == 'request_error':
                    _, request, error = msg
                    self.states_context.to_fetch(request)
                    continue

                if type == 'offset':
                    continue
                raise TypeError('Unknown message type %s' % type)
            finally:
                consumed += 1

        # Fetching states
        self.states_context.fetch()

        # Batch processing
        for msg in batch:
            type = msg[0]
            if type == 'add_seeds':
                _, seeds = msg
                for seed in seeds:
                    seed.meta['jid'] = self.job_id
                self.on_add_seeds(seeds)
                continue

            if type == 'page_crawled':
                _, response, links = msg
                if response.meta['jid'] != self.job_id:
                    continue
                self.on_page_crawled(response, links)
                continue

            if type == 'request_error':
                _, request, error = msg
                if request.meta['jid'] != self.job_id:
                    continue
                self.on_request_error(request, error)
                continue

        self.update_score.flush()
        self.states_context.release()

        # Exiting, if crawl is finished
        if self.strategy.finished():
            logger.info("Successfully reached the crawling goal.")
            logger.info("Closing crawling strategy.")
            self.strategy.close()
            logger.info("Exiting.")
            exit(0)

        self.stats['last_consumed'] = consumed
        self.stats['last_consumption_run'] = asctime()
        self.stats['consumed_since_start'] += consumed

    def run(self):
        self.task.start(interval=0)
        self._logging_task.start(interval=30)
        reactor.addSystemEventTrigger('before', 'shutdown', self.stop)
        reactor.run()

    def log_status(self):
        for k, v in self.stats.iteritems():
            logger.info("%s=%s", k, v)

    def stop(self):
        logger.info("Closing crawling strategy.")
        self.strategy.close()
        logger.info("Stopping frontier manager.")
        self._manager.stop()

    def on_add_seeds(self, seeds):
        logger.info('Adding %i seeds', len(seeds))
        self.states.set_states(seeds)
        self.strategy.add_seeds(seeds)
        self.states.update_cache(seeds)

    def on_page_crawled(self, response, links):
        logger.debug("Page crawled %s", response.url)
        objs_list = [response]
        objs_list.extend(links)
        self.states.set_states(objs_list)
        self.strategy.page_crawled(response, links)
        self.states.update_cache(links)
        self.states.update_cache(response)

    def on_request_error(self, request, error):
        logger.debug("Page error %s (%s)", request.url, error)
        self.states.set_states(request)
        self.strategy.page_error(request, error)
        self.states.update_cache(request)

if __name__ == '__main__':
    parser = ArgumentParser(description="Frontera strategy worker.")
    parser.add_argument('--config', type=str, required=True,
                        help='Settings module name, should be accessible by import')
    parser.add_argument('--log-level', '-L', type=str, default='INFO',
                        help="Log level, for ex. DEBUG, INFO, WARN, ERROR, FATAL")
    parser.add_argument('--strategy', type=str,
                        help='Crawling strategy class path')
    parser.add_argument('--partition-id', type=int,
                        help="Instance partition id.")
    args = parser.parse_args()
    settings = Settings(module=args.config)
    strategy_classpath = args.strategy if args.strategy else settings.get('CRAWLING_STRATEGY')
    if not strategy_classpath:
        raise ValueError("Couldn't locate strategy class path. Please supply it either using command line option or "
                         "settings file.")
    strategy_class = load_object(strategy_classpath)

    partition_id = args.partition_id if args.partition_id is not None else settings.get('SCORING_PARTITION_ID')
    if partition_id >= settings.get('SPIDER_LOG_PARTITIONS') or partition_id < 0:
        raise ValueError("Partition id (%d) cannot be less than zero or more than SPIDER_LOG_PARTITIONS." %
                         partition_id)
    settings.set('SCORING_PARTITION_ID', partition_id)

    logging_config_path = settings.get("LOGGING_CONFIG")
    if logging_config_path and exists(logging_config_path):
        fileConfig(logging_config_path)
    else:
        logging.basicConfig(level=args.log_level)
        logger.setLevel(args.log_level)
        logger.addHandler(CONSOLE)
    worker = StrategyWorker(settings, strategy_class)
    worker.run()


text:
  <form class="usa-form">
    <label for="options">Dropdown label</label>
    <select name="options" id="options">
      <option value="value1">Option A</option>
      <option value="value2">Option B</option>
      <option value="value3">Option C</option>
    </select>
  </form>


text:
package org.apache.flink.api.java.hadoop.mapreduce.utils;

import org.apache.flink.annotation.Internal;
import org.apache.flink.configuration.GlobalConfiguration;

import org.apache.hadoop.conf.Configuration;

import java.util.Map;

/** Utility class to work with next generation of Apache Hadoop MapReduce classes. */
@Internal
public final class HadoopUtils {

    /**
     * Merge HadoopConfiguration into Configuration. This is necessary for the HDFS configuration.
     */
    public static void mergeHadoopConf(Configuration hadoopConfig) {

        // we have to load the global configuration here, because the HadoopInputFormatBase does not
        // have access to a Flink configuration object
        org.apache.flink.configuration.Configuration flinkConfiguration =
                GlobalConfiguration.loadConfiguration();

        Configuration hadoopConf =
                org.apache.flink.api.java.hadoop.mapred.utils.HadoopUtils.getHadoopConfiguration(
                        flinkConfiguration);

        for (Map.Entry<String, String> e : hadoopConf) {
            if (hadoopConfig.get(e.getKey()) == null) {
                hadoopConfig.set(e.getKey(), e.getValue());
            }
        }
    }

    /** Private constructor to prevent instantiation. */
    private HadoopUtils() {
        throw new RuntimeException();
    }
}


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

<TITLE>

</TITLE>

<META NAME="date" CONTENT="2010-06-15">

<LINK REL ="stylesheet" TYPE="text/css" HREF="stylesheet.css" TITLE="Style">

      Package
      Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV PACKAGE
 NEXT PACKAGE

  FRAMES
 NO FRAMES

  All Classes

Package <Unnamed>

Class Summary

Actor
An actor is any object that has a degree of autonomy or intelligent input (Human / AIManager) dictating the object's behavior ingame
 Subclass of GameObject

AIManager
Strategy management behind the AI (Ghost objects)

AStarHeuristic
A heuristic that uses the tile that is closest to the target
 as the next best tile.

EditorFrame
This code was edited or generated using CloudGarden's Jigloo
 SWT/Swing GUI Builder, which is free for non-commercial
 use.

EditorMarker
The EditorMarker is used by the StateEditor for navigation and selecting tiles on the map
 EditorMarker is NOT tracked inside the Map
 EditorMarker is a subclass of GameObject

Game
The Game Supervisor.

GameObject
A game object is anything on the pacman grid (wall, cherry, ghost, player).

Ghost
The Ghost class is the primary enemy in Pacman.

Item
Item objects are GameObject's that can be manipulated by the Player on the map (teleports, dots, powerups, fruit)
 Item is a subclass of GameObject

JPacmanGame
The entry point of the program

Map
Map class keeps track objects on the playing grid, helper methods to make movement decisions, and export/import methods for the editor

Path
A path determined by some path finding algorithm.

PathFinder
A path finder implementation that uses the AStar heuristic based algorithm
 to determine a path.

Player
Player (pacman) is the object controlled by the human playing the game
 Player is a subclass of Actor

State
A State is a mode of the program where input and functionality are radically different from others portions of the program.

StateEditor
The StateEditor is a mode of the program that allows the user to create and modify map files that can be played in StateGame.

StateGame
StateGame is a mode of the program where the user can play the game of Pacman various maps
 StateGame is a subclass of State

StateMenu
StateMenu is a graphical representation that allows users to switch into other States of the program like the Game and editor

StateScoreboard
StateScoreboard is a mode of the program that allows the user to view (and sometimes modify) scores set in StateGame
 StateScoreboard is a subclass of State

      Package
      Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV PACKAGE
 NEXT PACKAGE

  FRAMES
 NO FRAMES

  All Classes


text:
module.exports = function(app){
  // API handling
  require('./apiHandlers')(app);

  // pages
  app.get('/', function(req, res){
    res.redirect('/games');
    /*
    res.render('index/index', {
      subtitle: 'Home',
      title: 'Colonies'
    });
    */
  });

  app.get('/games', function(req, res){
    app.transmit.request('api/' + app.config.apiVersion + '/get/games', function(err, data){
      if(err){
        return app.err(err);
      }

      res.render('games/list', {
        subtitle: 'Game',
        games: data
      });
    });
  });

  app.get('/games/:id', function(req, res){
    app.transmit.request('api/' + app.config.apiVersion + '/get/games/' + req.params.id, function(err, data){
      if(err){
        return app.err(req, res, err);
      }

      res.render('games/show', {
        subtitle: 'Game',
        game: data
      });
    });
  });
};


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title>(A => B) !=> (B => A) | React</title>
  <meta name="viewport" content="width=device-width">
  <meta property="og:title" content="(A => B) !=> (B => A) | React">
  <meta property="og:type" content="website">
  <meta property="og:url" content="https://facebook.github.io/react/blog/2016/01/08/A-implies-B-does-not-imply-B-implies-A.html">
  <meta property="og:image" content="https://facebook.github.io/react/img/logo_og.png">
  <meta property="og:description" content="A JavaScript library for building user interfaces">
  <meta property="fb:app_id" content="623268441017527">

  <link rel="shortcut icon" href="/react/favicon.ico">
  <link rel="alternate" type="application/rss+xml" title="React" href="https://127.0.0.1/react/feed.xml">

  <link rel="stylesheet" href="https://cdn.jsdelivr.net/docsearch.js/1/docsearch.min.css" />
  <link rel="stylesheet" href="/react/css/syntax.css">
  <link rel="stylesheet" href="/react/css/codemirror.css">
  <link rel="stylesheet" href="/react/css/react.css">

  <link href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css" rel="stylesheet">

          React

Docs/文档

Support/支持

Download/下载

Blog/博客

            <input id="algolia-doc-search" type="text" placeholder="Search docs..." />

GitHub

React Native

Recent posts

Relay: State of the State

Create Apps with No Configuration

Mixins Considered Harmful

Introducing React's Error Code System

React v15.0.1

React v15.0

React v0.14.8

React v15.0 Release Candidate 2

React v15.0 Release Candidate

New Versioning Scheme

All posts ...

  (A => B) !=> (B => A)

  January  8, 2016
  by

      Jim Sproch

The documentation for componentWillReceiveProps states that componentWillReceiveProps will be invoked when the props change as the result of a rerender. Some people assume this means "if componentWillReceiveProps is called, then the props must have changed", but that conclusion is logically incorrect.

The guiding principle is one of my favorites from formal logic/mathematics:

A implies B does not imply B implies A

Example: "If I eat moldy food, then I will get sick" does not imply "if I am sick, then I must have eaten moldy food". There are many other reasons I could be feeling sick. For instance, maybe the flu is circulating around the office. Similarly, there are many reasons that componentWillReceiveProps might get called, even if the props didn't change.

If you don't believe me, call ReactDOM.render() three times with the exact same props, and try to predict the number of times componentWillReceiveProps will get called:

class Component extends React.Component {
  componentWillReceiveProps(nextProps) {
    console.log('componentWillReceiveProps', nextProps.data.bar);
  }
  render() {
    return <div>Bar {this.props.data.bar}!</div>;
  }
}

var container = document.getElementById('container');

var mydata = {bar: 'drinks'};
ReactDOM.render(<Component data={mydata} />, container);
ReactDOM.render(<Component data={mydata} />, container);
ReactDOM.render(<Component data={mydata} />, container);

In this case, the answer is "2". React calls componentWillReceiveProps twice (once for each of the two updates). Both times, the value of "drinks" is printed (ie. the props didn't change).

To understand why, we need to think about what could have happened. The data could have changed between the initial render and the two subsequent updates, if the code had performed a mutation like this:

var mydata = {bar: 'drinks'};
ReactDOM.render(<Component data={mydata} />, container);
mydata.bar = 'food'
ReactDOM.render(<Component data={mydata} />, container);
mydata.bar = 'noise'
ReactDOM.render(<Component data={mydata} />, container);

React has no way of knowing that the data didn't change. Therefore, React needs to call componentWillReceiveProps, because the component needs to be notified of the new props (even if the new props happen to be the same as the old props).

You might think that React could just use smarter checks for equality, but there are some issues with this idea:

The old mydata and the new mydata are actually the same physical object (only the object's internal value changed). Since the references are triple-equals-equal, doing an equality check doesn't tell us if the value has changed. The only possible solution would be to have created a deep copy of the data, and then later do a deep comparison - but this can be prohibitively expensive for large data structures (especially ones with cycles).

The mydata object might contain references to functions which have captured variables within closures. There is no way for React to peek into these closures, and thus no way for React to copy them and/or verify equality.

The mydata object might contain references to objects which are re-instantiated during the parent's render (ie. not triple-equals-equal) but are conceptually equal (ie. same keys and same values). A deep-compare (expensive) could detect this, except that functions present a problem again because there is no reliable way to compare two functions to see if they are semantically equivalent.

Given the language constraints, it is sometimes impossible for us to achieve meaningful equality semantics. In such cases, React will call componentWillReceiveProps (even though the props might not have changed) so the component has an opportunity to examine the new props and act accordingly.

As a result, your implementation of componentWillReceiveProps MUST NOT assume that your props have changed. If you want an operation (such as a network request) to occur only when props have changed, your componentWillReceiveProps code needs to check to see if the props actually changed.

        A Facebook & Instagram collaboration.

        Acknowledgements

        © 2013–2016 Facebook Inc.

        Documentation licensed under CC BY 4.0.


text:
package com.netflix.astyanax.recipes.queue.shard;

import java.util.Collection;
import java.util.Map;

import com.netflix.astyanax.recipes.queue.MessageQueueMetadata;
import com.netflix.astyanax.recipes.queue.MessageQueueShard;
import com.netflix.astyanax.recipes.queue.MessageQueueShardStats;

/**
 * Policy for scheduling shards to be processed
 *
 * @author elandau
 *
 */
public interface ShardReaderPolicy {
    public static interface Factory {
        public ShardReaderPolicy create(MessageQueueMetadata metadata);
    }

    /**
     * Acquire the next shard to be processed.  Must call releaseShard when done reading
     * from the shard
     * @return A reference to the acquired shard.
     * @throws InterruptedException
     */
    public MessageQueueShard nextShard() throws InterruptedException;

    /**
     * Release a shard after acquiring and reading messages
     * @param shard
     */
    public void releaseShard(MessageQueueShard shard, int messagesRead);

    /**
     * @return List all the shards
     */
    public Collection<MessageQueueShard> listShards();

    /**
     * @return Return map of all shard stats
     */
    public Map<String, MessageQueueShardStats> getShardStats();

    /**
     * @return number of shards in the work or active queue
     */
    public int getWorkQueueDepth();

    /**
     * @return number of shards in the idle queue
     */
    public int getIdleQueueDepth();

    /**
     * a ShardReaderPolicy is in catch up mode when more than two time buckets are in the work or active queue.
     * @return is the shard reader catching up.
     */
    public boolean isCatchingUp();

    /**
     * @return the correct polling interval.  if in catch up mode returns the catchUpPollInterval otherwise
     * returns the "normal" pollInterval
     */
    public long getPollInterval();
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.TextInputLayout
        android:id="@+id/input_password_wrapper"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:layout_marginBottom="8dp"
        android:layout_marginRight="24dp"
        android:layout_marginLeft="24dp">
        <EditText android:id="@+id/input_password"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textPassword"
            android:hint="@string/prompt_password"/>
    </android.support.design.widget.TextInputLayout>

    <Switch
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="24dp"
        android:padding="12dp"
        android:text="@string/remember_password"
        android:id="@+id/switch_save_password"
        android:layout_marginRight="12dp"
        android:layout_marginLeft="12dp" />
</LinearLayout>


text:
package com.camnter.smartsave.compiler.scanner;

/**
 * 封装一个具有 PackageName 的 Id
 *
 * @author CaMnter
 */

final class QualifiedId {

    final String packageName;
    final String enclosingElementName;
    final String elementSimpleName;
    final int id;

    QualifiedId(String packageName, String enclosingElementName, String elementSimpleName, int id) {
        this.packageName = packageName;
        this.enclosingElementName = enclosingElementName;
        this.elementSimpleName = elementSimpleName;
        this.id = id;
    }

    @Override
    public String toString() {
        return "QualifiedId{packageName='" + packageName + "', id=" + id + '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof QualifiedId)) return false;
        QualifiedId other = (QualifiedId) o;
        return id == other.id
            && packageName.equals(other.packageName);
    }

    @Override
    public int hashCode() {
        int result = packageName.hashCode();
        result = 31 * result + id;
        return result;
    }

}


text:
const autoplay = {
  props: {
    /**
     * Flag to enable autoplay
     */
    autoplay: {
      type: Boolean,
      default: false,
    },
    /**
     * Time elapsed before advancing slide
     */
    autoplayTimeout: {
      type: Number,
      default: 2000,
    },
    /**
     * Flag to pause autoplay on hover
     */
    autoplayHoverPause: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      autoplayInterval: null,
    }
  },
  destroyed() {
    if (!this.$isServer) {
      this.$el.removeEventListener("mouseenter", this.pauseAutoplay)
      this.$el.removeEventListener("mouseleave", this.startAutoplay)
    }
  },
  methods: {
    pauseAutoplay() {
      if (this.autoplayInterval) {
        this.autoplayInterval = clearInterval(this.autoplayInterval)
      }
    },
    startAutoplay() {
      if (this.autoplay) {
        this.autoplayInterval = setInterval(this.advancePage, this.autoplayTimeout)
      }
    },
  },
  mounted() {
    if (!this.$isServer && this.autoplayHoverPause) {
      this.$el.addEventListener("mouseenter", this.pauseAutoplay)
      this.$el.addEventListener("mouseleave", this.startAutoplay)
    }

    this.startAutoplay()
  },
}

export default autoplay


text:
package org.apache.jena.shacl.vocabulary;

import org.apache.jena.irix.IRIException;
import org.apache.jena.irix.IRIx;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.Property;
import org.apache.jena.rdf.model.Resource;
import org.apache.jena.shacl.ShaclException;

/**
 * SHACL related vocabulary, not the {@link SHACL} namespace.
 */
public class VocabSHACL {

    private static String NS = "http://jena.apache.org/shacl#";
    private static Model model = ModelFactory.createDefaultModel();

    public static Resource opValidate = resource("validate");

    private static Resource resource(String localname) { return model.createResource(iri(localname)); }
    private static Property property(String localname) { return model.createProperty(iri(localname)); }

    private static String iri(String localname) {
        String uri = NS + localname;
        try {
            IRIx iri = IRIx.create(uri);
            if ( ! iri.isReference() )
                throw new ShaclException("Bad IRI (relative): "+uri);
            return uri;
        } catch (IRIException ex) {
            throw new ShaclException("Bad IRI: "+uri);
        }
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Die Gattung der Pyrenomyzeten, Sphaeropsideen und Melanconieen 51 (1926)

#### Original name
null

### Remarks
null


text:
define([
	'dojo/_base/declare',
	'rql/js-array',
	'../SimpleQuery'
], function (declare, arrayEngine, SimpleQuery) {
	return declare(SimpleQuery, {
		_createFilterQuerier: function (filter) {
			return filter.type === 'string'
				? arrayEngine.query(filter.args[0])
				: this.inherited(arguments);
		}
	});
});


text:
SCRIPT_DIR=$(dirname $0)
cd $SCRIPT_DIR

function usage
{
	echo "Usage: $0 [-i] [-e ENV] [-p ENV] [-r REMOTE] [EXTRA_REPOS]"
	echo
	echo "    -i		install required packages"
	echo "    -C		don't do the actual installation (quit after cloning)"
	echo "    -w		use pre-built packages where available"
	echo "    -v		verbose (don't redirect installation logging)"
	echo "    -e ENV	create a cpython environment ENV"
	echo "    -E ENV	re-create a cpython environment ENV"
	echo "    -p ENV	create a pypy environment ENV"
	echo "    -P ENV	re-create a pypy environment ENV"
	echo "    -r REMOTE	use a different remote base (default: https://github.com/angr/)"
	echo "             	Can be specified multiple times."
	echo "    -b BRANCH     Check out a given branch across all the repositories."
	echo "    -D            Ignore the default repo list."
	echo "    EXTRA_REPOS	any extra repositories you want to clone from the angr org."
	echo
	echo "This script clones all the angr repositories and sets up an angr"
	echo "development environment."

	exit 1
}

DEBS=${DEBS-virtualenvwrapper python2.7-dev build-essential libxml2-dev libxslt1-dev git libffi-dev cmake libreadline-dev libtool debootstrap debian-archive-keyring libglib2.0-dev libpixman-1-dev}
REPOS=${REPOS-ana idalink cooldict mulpyplexer capstone unicorn monkeyhex superstruct archinfo vex pyvex cle claripy simuvex angr angr-management angr-doc binaries}

ORIGIN_REMOTE=$(git remote -v | grep origin | head -n1 | awk '{print $2}' | sed -e "s/\/angr-dev.*//")
REMOTES=${REMOTES-${ORIGIN_REMOTE/\/github.com/\/git:@github.com} https://git:@github.com/zardus https://git:@github.com/rhelmot}

INSTALL_REQS=0
ANGR_VENV=
USE_PYPY=
RMVENV=0
INSTALL=1
WHEELS=0
VERBOSE=0
BRANCH=

while getopts "iCwDve:E:p:P:r:b:h" opt
do
	case $opt in
		i)
			INSTALL_REQS=1
			;;
		v)
			VERBOSE=1
			;;
		e)
			ANGR_VENV=$OPTARG
			USE_PYPY=0
			;;
		E)
			ANGR_VENV=$OPTARG
			USE_PYPY=0
			RMVENV=1
			;;
		p)
			ANGR_VENV=$OPTARG
			USE_PYPY=1
			;;
		P)
			ANGR_VENV=$OPTARG
			USE_PYPY=1
			RMVENV=1
			;;
		b)
			BRANCH=$OPTARG
			;;
		r)
			REMOTES="$OPTARG $REMOTES"
			;;
		C)
			INSTALL=0
			;;
		w)
			WHEELS=1
			;;
		D)
			REPOS=""
			;;
		\?)
			usage
			;;
		h)
			usage
			;;
	esac
done

if [ $WHEELS -eq 1 ]
then
	REPOS="$REPOS wheels"
	REPOS=${REPOS// unicorn/}
	REPOS=${REPOS// capstone/}
fi

EXTRA_REPOS=${@:$OPTIND:$OPTIND+100}
REPOS="$REPOS $EXTRA_REPOS"

if [ $VERBOSE -eq 1 ]
then
	OUTFILE=/dev/stdout
	ERRFILE=/dev/stderr
else
	OUTFILE=/tmp/pip-$$
	ERRFILE=/tmp/pip-$$
fi

function info
{
	echo "$(tput setaf 4 2>/dev/null)[+] $@$(tput sgr0 2>/dev/null)"
}

function warning
{
	echo "$(tput setaf 3 2>/dev/null)[!] $@$(tput sgr0 2>/dev/null)"
}

function debug
{
	echo "$(tput setaf 6 2>/dev/null)[-] $@$(tput sgr0 2>/dev/null)"
}

function error
{
	echo "$(tput setaf 1 2>/dev/null)[!!] $@$(tput sgr0 2>/dev/null)" >&2
	exit 1
}

if [ "$INSTALL_REQS" -eq 1 ]
then
	info Installing dependencies...
	[ -e /etc/debian_version ] && sudo apt-get install -y $DEBS
	[ ! -e /etc/debian_version ] && error "We don't know which dependencies to install for this sytem.\nPlease install the equivalents of these debian packages: $DEBS."
fi

info "Checking dependencies..."
[ -e /etc/debian_version -a $(dpkg --get-selections $DEBS | wc -l) -ne $(echo $DEBS | wc -w) ] && echo "Please install the following packages: $DEBS" && exit 1
[ ! -e /etc/debian_version ] && echo -e "WARNING: make sure you have dependencies installed.\nThe debian equivalents are: $DEBS.\nPress enter to continue." && read a

set +e
source /etc/bash_completion.d/virtualenvwrapper
set -e

if [ -n "$ANGR_VENV" ]
then
	set +e
	if [ -n "$VIRTUAL_ENV" ]
	then
		# We can't just deactivate, since those functions are in the parent shell.
		# So, we do some hackish stuff.
		PATH=${PATH/$VIRTUAL_ENV\/bin:/}
		unset VIRTUAL_ENV
	fi

	if [ "$RMVENV" -eq 1 ]
	then
		info "Removing existing virtual environment $ANGR_VENV..."
		rmvirtualenv $ANGR_VENV || error "Failed to remote virtualenv $ANGR_VENV."
	elif lsvirtualenv | grep -q "^$ANGR_VENV$"
	then
		error "Virtualenv $ANGR_VENV already exists. Use -E instead of -e if you want to re-create the environment."
	fi

	if [ "$USE_PYPY" -eq 1 ]
	then
		./pypy_venv.sh $ANGR_VENV
	else
		mkvirtualenv --python=$(which python2) $ANGR_VENV
	fi

	set -e
	workon $ANGR_VENV || error "Unable to activate the virtual environment."
fi

function try_remote
{
	URL=$1
	debug "Trying to clone from $URL"
	rm -f /tmp/clone-$$
	git clone $URL >> /tmp/clone-$$ 2>> /tmp/clone-$$
	r=$?

	if grep -q -E "(ssh_exchange_identification: read: Connection reset by peer|ssh_exchange_identification: Connection closed by remote host)" /tmp/clone-$$
	then
		warning "Too many concurrent connections to the server. Retrying after sleep."
		sleep $[$RANDOM % 5]
		try_remote $URL
		return $?
	else
		[ $r -eq 0 ] && rm -f /tmp/clone-$$
		return $r
	fi
}

function clone_repo
{
	NAME=$1
	if [ -e $NAME ]
	then
		info "Skipping $NAME -- already cloned. Use ./git_all.sh pull for update."
		return 0
	fi

	info "Cloning repo $NAME."
	for r in $REMOTES
	do
		URL="$r/$NAME"
		try_remote $URL && debug "Success!" && break
	done

	if [ ! -e $NAME ]
	then
		error "Failed to clone $NAME. Error was:"
		cat /tmp/clone-$$
		rm -f /tmp/clone-$$
		return 1
	fi

	return 0
}

function install_wheels
{
	#LATEST_Z3=$(ls -tr wheels/angr_only_z3_custom-*)
	#echo "Installing $LATEST_Z3..." >> $OUTFILE 2>> $ERRFILE
	#pip install $LATEST_Z3 >> $OUTFILE 2>> $ERRFILE

	LATEST_VEX=$(ls -tr wheels/vex-*)
	echo "Extracting $LATEST_VEX..." >> $OUTFILE 2>> $ERRFILE
	tar xvzf $LATEST_VEX >> $OUTFILE 2>> $ERRFILE
	touch vex/*/*.o vex/libvex.a

	#LATEST_QEMU=$(ls -tr wheels/shellphish_qemu-*)
	#echo "Installing $LATEST_QEMU" >> $OUTFILE 2>> $ERRFILE
	#pip install $LATEST_QEMU >> $OUTFILE 2>> $ERRFILE

	#LATEST_AFL=$(ls -tr wheels/shellphish_afl-*)
	#echo "Installing $LATEST_AFL" >> $OUTFILE 2>> $ERRFILE
	#pip install $LATEST_AFL >> $OUTFILE 2>> $ERRFILE
}

info "Cloning angr components!"
for r in $REPOS
do
	clone_repo $r || exit 1
	[ -e "$NAME/setup.py" ] && TO_INSTALL="$TO_INSTALL $NAME"
done

if [ -n "$BRANCH" ]
then
	info "Checking out branch $BRANCH."
	./git_all.sh checkout $BRANCH
fi

if [ $INSTALL -eq 1 ]
then
	if [ -z "$VIRTUAL_ENV" ]
	then
		warning "You are installing angr outside of a virtualenv. This is NOT"
		warning "RECOMMENDED. Activate a virtualenv before running this script"
		warning "or use one of the following options: -e -E -p -P. Please type"
		warning "\"I know this is a bad idea.\" (without quotes) and press enter"
		warning "to continue."

		read ans
		if [ "$ans" != "I know this is a bad idea." ]
		then
			exit 1
		fi
	fi

	if [ $VERBOSE -eq 1 ]
	then
		info "Installing python packages!"
	else
		info "Installing python packages (logging to $OUTFILE)!"
	fi

	if [ $WHEELS -eq 1 ]
	then
		install_wheels
		PIP_OPTIONS="$PIP_OPTIONS --find-links=$PWD/wheels"
	fi

	# remove angr-management if running in pypy or in travis
	(python --version 2>&1| grep -q PyPy) && TO_INSTALL=${TO_INSTALL// angr-management/}
	[ -n "$TRAVIS" ] && TO_INSTALL=${TO_INSTALL// angr-management/}

	if pip install $PIP_OPTIONS -v ${TO_INSTALL// / -e } >> $OUTFILE 2>> $ERRFILE
	then
		info "Success!"
		[ $VERBOSE -eq 1 ] || rm -f $OUTFILE
	else
		error "Something failed to install. Check $OUTFILE for details, or read it here:"
		cat $OUTFILE
		exit 1
	fi

	info "Installing some other helpful stuff (logging to $OUTFILE)."
	if pip install ipython pylint ipdb nose nose-timer coverage >> $OUTFILE 2>> $ERRFILE
	then
		info "Success!"
		[ $VERBOSE -eq 1 ] || rm -f $OUTFILE
	else
		error "Something failed to install. Check $OUTFILE for details, or read it here:"
		cat $OUTFILE
		exit 1
	fi
fi

echo ''
info "All done! Execute \"workon $ANGR_VENV\" to use your new angr virtual"
info "environment. Any changes you make in the repositories will reflect"
info "immediately in the virtual environment, with the exception of things"
info "requiring compilation (i.e., pyvex). For those, you will need to rerun"
info "the install after changes (i.e., \"pip install -I -e pyvex\")."


text:
import { injectable } from 'inversify';
import { QuickOpenService, QuickOpenModel, QuickOpenOptions, QuickOpenItem, QuickOpenGroupItem, QuickOpenMode } from "@theia/core/lib/browser";
import { KEY_CODE_MAP } from './monaco-keycode-map';

export interface InternalMonacoQuickOpenModel extends monaco.quickOpen.IQuickOpenControllerOpts {
    readonly prefix?: string;
    onClose?(canceled: boolean): void;
}

@injectable()
export class MonacoQuickOpenService extends QuickOpenService {

    protected readonly container: HTMLElement;
    protected _widget: monaco.quickOpen.QuickOpenWidget | undefined;
    protected model: InternalMonacoQuickOpenModel | undefined;

    constructor() {
        super();
        const overlayWidgets = document.createElement('div');
        overlayWidgets.classList.add('quick-open-overlay');
        document.body.appendChild(overlayWidgets);

        const container = this.container = document.createElement('quick-open-container');
        container.style.position = 'absolute';
        container.style.top = '0px';
        container.style.right = '50%';
        overlayWidgets.appendChild(container);
    }

    open(model: QuickOpenModel, options?: QuickOpenOptions): void {
        this.internalOpen(new MonacoQuickOpenModel(model, options));
    }

    internalOpen(model: InternalMonacoQuickOpenModel): void {
        this.model = model;
        const widget = this.widget;
        widget.show(this.model.prefix || '');
        widget.setPlaceHolder(model.inputAriaLabel);
    }

    protected get widget(): monaco.quickOpen.QuickOpenWidget {
        if (this._widget) {
            return this._widget;
        }

        this._widget = new monaco.quickOpen.QuickOpenWidget(this.container, {
            onOk: () => this.onClose(false),
            onCancel: () => this.onClose(true),
            onType: lookFor => this.onType(lookFor || ''),
            onFocusLost: () => false
        }, {});
        this.attachQuickOpenStyler();
        this._widget.create();
        return this._widget;
    }

    protected attachQuickOpenStyler(): void {
        if (!this._widget) {
            return;
        }
        const themeService = monaco.services.StaticServices.standaloneThemeService.get();
        const detach = monaco.theme.attachQuickOpenStyler(this._widget, themeService);
        themeService.onThemeChange(() => {
            detach.dispose();
            this.attachQuickOpenStyler();
        });
    }

    protected onClose(cancelled: boolean): void {
        if (this.model && this.model.onClose) {
            this.model.onClose(cancelled);
        }
    }

    protected onType(lookFor: string): void {
        const options = this.model;
        if (this.widget && options) {
            this.widget.setInput(options.getModel(lookFor), options.getAutoFocus(lookFor), options.inputAriaLabel);
        }
    }

}

export class MonacoQuickOpenModel implements InternalMonacoQuickOpenModel {

    protected readonly options: QuickOpenOptions.Resolved;

    constructor(
        protected readonly model: QuickOpenModel,
        options?: QuickOpenOptions
    ) {
        this.model = model;
        this.options = QuickOpenOptions.resolve(options);
    }

    get prefix(): string {
        return this.options.prefix;
    }

    get inputAriaLabel(): string {
        return this.options.placeholder;
    }

    onClose(cancelled: boolean): void {
        this.options.onClose(cancelled);
    }

    getModel(lookFor: string): monaco.quickOpen.QuickOpenModel {
        const entries: monaco.quickOpen.QuickOpenEntry[] = [];
        const items = this.model.getItems(lookFor);
        for (const item of items) {
            const entry = this.createEntry(item, lookFor);
            if (entry) {
                entries.push(entry);
            }
        }
        if (this.options.fuzzySort) {
            entries.sort((a, b) => monaco.quickOpen.QuickOpenEntry.compare(a, b, lookFor));
        }
        return new monaco.quickOpen.QuickOpenModel(entries);
    }

    protected createEntry(item: QuickOpenItem, lookFor: string): monaco.quickOpen.QuickOpenEntry | undefined {
        const labelHighlights = this.options.fuzzyMatchLabel ? this.matchesFuzzy(lookFor, item.getLabel()) : item.getLabelHighlights();
        if (!labelHighlights) {
            return undefined;
        }
        const descriptionHighlights = this.options.fuzzyMatchDescription ? this.matchesFuzzy(lookFor, item.getDescription()) : item.getDescriptionHighlights();
        const detailHighlights = this.options.fuzzyMatchDetail ? this.matchesFuzzy(lookFor, item.getDetail()) : item.getDetailHighlights();

        const entry = item instanceof QuickOpenGroupItem ? new QuickOpenEntryGroup(item) : new QuickOpenEntry(item);
        entry.setHighlights(labelHighlights, descriptionHighlights, detailHighlights);
        return entry;
    }

    protected matchesFuzzy(lookFor: string, value: string | undefined): monaco.quickOpen.IHighlight[] | undefined {
        if (!lookFor || !value) {
            return [];
        }
        return monaco.filters.matchesFuzzy(lookFor, value);
    }

    getAutoFocus(lookFor: string): monaco.quickOpen.IAutoFocus {
        return {
            autoFocusFirstEntry: true,
            autoFocusPrefixMatch: lookFor
        };
    }

}

export class QuickOpenEntry extends monaco.quickOpen.QuickOpenEntry {

    constructor(
        public readonly item: QuickOpenItem
    ) {
        super();
    }

    getLabel(): string | undefined {
        return this.item.getLabel();
    }

    getAriaLabel(): string | undefined {
        return this.item.getTooltip();
    }

    getDetail(): string | undefined {
        return this.item.getDetail();
    }

    getDescription(): string | undefined {
        return this.item.getDescription();
    }

    isHidden(): boolean {
        return super.isHidden() || this.item.isHidden();
    }

    getResource(): monaco.Uri | undefined {
        const uri = this.item.getUri();
        return uri ? monaco.Uri.parse(uri.toString()) : undefined;
    }

    getIcon(): string | undefined {
        return this.item.getIconClass();
    }

    getKeybinding(): monaco.keybindings.ResolvedKeybinding | undefined {
        const keybinding = this.item.getKeybinding();
        if (!keybinding) {
            return undefined;
        }
        const simple = new monaco.keybindings.SimpleKeybinding(
            keybinding.keyCode.ctrl,
            keybinding.keyCode.shift,
            keybinding.keyCode.alt,
            keybinding.keyCode.meta,
            KEY_CODE_MAP[keybinding.keyCode.key.keyCode]
        );
        return new monaco.keybindings.USLayoutResolvedKeybinding(simple, monaco.platform.OS);
    }

    run(mode: monaco.quickOpen.Mode): boolean {
        if (mode === monaco.quickOpen.Mode.OPEN) {
            return this.item.run(QuickOpenMode.OPEN);
        }
        if (mode === monaco.quickOpen.Mode.OPEN_IN_BACKGROUND) {
            return this.item.run(QuickOpenMode.OPEN_IN_BACKGROUND);
        }
        if (mode === monaco.quickOpen.Mode.PREVIEW) {
            return this.item.run(QuickOpenMode.PREVIEW);
        }
        return false;
    }

}

export class QuickOpenEntryGroup extends monaco.quickOpen.QuickOpenEntryGroup {

    constructor(
        public readonly item: QuickOpenGroupItem
    ) {
        super(new QuickOpenEntry(item));
    }

    getGroupLabel(): string {
        return this.item.getGroupLabel() || '';
    }

    showBorder(): boolean {
        return this.item.showBorder();
    }

}


text:
<?php

/**
 * WPBakery Visual Composer shortcodes
 *
 * @package WPBakeryVisualComposer
 *
 */
class WPBakeryShortCode_VC_Column extends WPBakeryShortCode {
	/**
	 * @var array
	 */
	protected $predefined_atts = array(
		'font_color'  => '',
		'el_class'    => '',
		'el_position' => '',
		'width'       => '1/1'
	);

	/**
	 * @param $controls
	 * @param string $extended_css
	 *
	 * @return string
	 */
	public function getColumnControls( $controls, $extended_css = '' ) {
		$output       = '
';
		$controls_end = '
';

		if ( $extended_css == 'bottom-controls' ) {
			$control_title = __( 'Append to this column', 'js_composer' );
		} else {
			$control_title = __( 'Prepend to this column', 'js_composer' );
		}
		$controls_add    = ' ';
		$controls_edit   = ' ';
		$controls_delete = ' ';
		if ( is_array( $controls ) && !empty( $controls ) ) {
			foreach ( $controls as $control ) {
				$method_name = vc_camel_case( 'output-editor-control-' . $control );
				if ( method_exists( $this, $method_name ) ) {
					$output .= $this->$method_name();
				} else {
					$control_var = 'controls_' . $control;
					$output .= $$control_var;
				}
			}
			return $output . $controls_end;
		} elseif ( is_string( $controls ) && 'full' === $controls ) {
			return $output . $controls_add . $controls_edit . $controls_delete . $controls_end;
		} elseif ( is_string( $controls ) ) {
			$control_var = 'controls_' . $controls;
			if ( isset( $$control_var ) ) {
				return $output . $$control_var . $controls_end;
			}
		}
		return $output . $controls_add . $controls_edit . $controls_delete . $controls_end;
	}

	/**
	 * @param $param
	 * @param $value
	 * @param array $settings
	 * @param array $atts
	 *
	 * @return string
	 */
	public function singleParamHtmlHolder( $param, $value ) {
		$output = '';
		// Compatibility fixes.
		$old_names = array(
			'yellow_message',
			'blue_message',
			'green_message',
			'button_green',
			'button_grey',
			'button_yellow',
			'button_blue',
			'button_red',
			'button_orange'
		);
		$new_names = array(
			'alert-block',
			'alert-info',
			'alert-success',
			'btn-success',
			'btn',
			'btn-info',
			'btn-primary',
			'btn-danger',
			'btn-warning'
		);
		$value     = str_ireplace( $old_names, $new_names, $value );
		//$value = __($value, "js_composer");
		//
		$param_name = isset( $param['param_name'] ) ? $param['param_name'] : '';
		$type       = isset( $param['type'] ) ? $param['type'] : '';
		$class      = isset( $param['class'] ) ? $param['class'] : '';

		if ( isset( $param['holder'] ) == true && $param['holder'] != 'hidden' ) {
			$output .= '<' . $param['holder'] . ' class="wpb_vc_param_value ' . $param_name . ' ' . $type . ' ' . $class . '" name="' . $param_name . '">' . $value . '</' . $param['holder'] . '>';
		}

		return $output;
	}

	/**
	 * @param $atts
	 * @param null $content
	 *
	 * @return string
	 */
	public function contentAdmin( $atts, $content = null ) {
		$width = $el_class = '';
		extract( shortcode_atts( $this->predefined_atts, $atts ) );
		$output = '';

		$column_controls        = $this->getColumnControls( $this->settings( 'controls' ) );
		$column_controls_bottom = $this->getColumnControls( 'add', 'bottom-controls' );

		if ( $width == 'column_14' || $width == '1/4' ) {
			$width = array( 'vc_col-sm-3' );
		} else if ( $width == 'column_14-14-14-14' ) {
			$width = array( 'vc_col-sm-3', 'vc_col-sm-3', 'vc_col-sm-3', 'vc_col-sm-3' );
		} else if ( $width == 'column_13' || $width == '1/3' ) {
			$width = array( 'vc_col-sm-4' );
		} else if ( $width == 'column_13-23' ) {
			$width = array( 'vc_col-sm-4', 'vc_col-sm-8' );
		} else if ( $width == 'column_13-13-13' ) {
			$width = array( 'vc_col-sm-4', 'vc_col-sm-4', 'vc_col-sm-4' );
		} else if ( $width == 'column_12' || $width == '1/2' ) {
			$width = array( 'vc_col-sm-6' );
		} else if ( $width == 'column_12-12' ) {
			$width = array( 'vc_col-sm-6', 'vc_col-sm-6' );
		} else if ( $width == 'column_23' || $width == '2/3' ) {
			$width = array( 'vc_col-sm-8' );
		} else if ( $width == 'column_34' || $width == '3/4' ) {
			$width = array( 'vc_col-sm-9' );
		} else if ( $width == 'column_16' || $width == '1/6' ) {
			$width = array( 'vc_col-sm-2' );
		} else if ( $width == 'column_56' || $width == '5/6' ) {
			$width = array( 'vc_col-sm-10' );
		} else {
			$width = array( '' );
		}
		for ( $i = 0; $i < count( $width ); $i ++ ) {
			$output .= '
mainHtmlBlockParams( $width, $i ) . '>';
			$output .= str_replace( "%column_size%", wpb_translateColumnWidthToFractional( $width[$i] ), $column_controls );
			$output .= '
';
			$output .= '
containerHtmlBlockParams( $width, $i ) . '>';
			$output .= do_shortcode( shortcode_unautop( $content ) );
			$output .= '
';
			if ( isset( $this->settings['params'] ) ) {
				$inner = '';
				foreach ( $this->settings['params'] as $param ) {
					$param_value = isset( $$param['param_name'] ) ? $$param['param_name'] : '';
					if ( is_array( $param_value ) ) {
						// Get first element from the array
						reset( $param_value );
						$first_key   = key( $param_value );
						$param_value = $param_value[$first_key];
					}
					$inner .= $this->singleParamHtmlHolder( $param, $param_value );
				}
				$output .= $inner;
			}
			$output .= '
';
			$output .= str_replace( "%column_size%", wpb_translateColumnWidthToFractional( $width[$i] ), $column_controls_bottom );
			$output .= '
';
		}

		return $output;
	}

	/**
	 * @return string
	 */
	public function customAdminBlockParams() {
		return '';
	}

	/**
	 * @param $width
	 * @param $i
	 *
	 * @return string
	 */
	public function mainHtmlBlockParams( $width, $i ) {
		return 'data-element_type="' . $this->settings["base"] . '" data-vc-column-width="' . wpb_vc_get_column_width_indent( $width[$i] ) . '" class="wpb_' . $this->settings['base'] . ' wpb_sortable ' . $this->templateWidth() . ' wpb_content_holder"' . $this->customAdminBlockParams();
	}

	/**
	 * @param $width
	 * @param $i
	 *
	 * @return string
	 */
	public function containerHtmlBlockParams( $width, $i ) {
		return 'class="wpb_column_container vc_container_for_children"';
	}

	/**
	 * @param string $content
	 *
	 * @return string
	 */
	public function template( $content = '' ) {
		return $this->contentAdmin( $this->atts );
	}

	/**
	 * @return string
	 */
	protected function templateWidth() {
		return '<%= window.vc_convert_column_size(params.width) %>';
	}

	/**
	 * @param string $font_color
	 *
	 * @return string
	 */
	public function buildStyle( $font_color = '' ) {
		$style = '';
		if ( !empty( $font_color ) ) {
			$style .= vc_get_css_color( 'color', $font_color );
		}

		return empty( $style ) ? $style : ' style="' . esc_attr($style) . '"';
	}
}


text:
package ru.mirea.documentation;

//import java.io.Serializable; для ввода данных в файлы (другой разработчик)

import java.io.*;
import java.util.*;

/*
Класс экземпляра документа.
Содержит основные поля, необходимые для работы с различными типами документов.
Максимальный размер = 10 МB
Проверка данных на размер реализуется суммированием всех полей (кроме заголовка) и сравнением их с заданым значением
*/

public class Document {
    private String Name;//Имя документа (Изменяемый)
    private Date DataCreation;//Дата создания документа (Неизменяемый, только в конструкторе)
    private Date DataEdition;//Дата последнего изменения документа (Неизменяемый извне, задаётся в конструктореб меняется в update)
    private Integer AuthorID;//Код пользователя, создавшего или изменившего документ (Изменяемый)
    private DocumentType Type;//Тип или расширение документа. Допускаются .pdf .doc .docx .txt (10 байт) (Изменяемый)
    private int DocID;//Уникальный номер документа (30 байт) (Неизменяемый)
    private Map<String, String> Header;// Заголовок документа. Реализован с помощью карты заголовков (Обязательно сеттер и геттер) (Изменяемый)
    private byte[] Body;//бинарное наполнение(Изменяемый)

    //метод прибавления единички к последнему числу в файле
    public int PlusOne(int number) {
        number = number + 1;
        return number;
    }
    @Override
    public boolean equals(Object Obj) {
        if (!(Obj instanceof Document)) return false;
        Document N = (Document) Obj;

        if (!Arrays.equals(this.Body, N.Body)) {
            return false;
        }
        //Objects.equals(key, e.getKey())
        if (this.Header == N.Header) {
            return true;
        }
        //Objects.equals()
        if (!Objects.equals(this.DataCreation, N.DataCreation)) {
            return false;
        }
        if (!Objects.equals(this.DataEdition, N.DataCreation)) {
            return false;
        }
        if (!Objects.equals(this.AuthorID, N.AuthorID)) {
            return false;
        }
        //тут все ок
        if (this.Type == N.Type) {
            return true;
        }
        if (this.DocID == N.DocID) {
            return true;
        }
        return false;
    }//сравнение по полям документа

    public Date getDataCreation() {
        return this.DataCreation;
    }//Метод, возвращающий значение даты создания документа

    public Date getDataEdition() {
        return this.DataEdition;
    }//Метод, возвращающий значение даты последнего изменения документа

    public int getAuthorID() {
        return this.AuthorID;
    }//Метод, возвращающий имя пользователя, создавшего или изменившего документ

    public String getName() {
        return this.Name;
    }//Метод, реализующий получение имени документа

    public int getDocID() {
        return this.DocID;
    }//Метод, возвращающий уникальный номер документа

    public byte[] getBody() {
        return this.Body;
    }//Метод, возвращающий текст документа

    public Map<String, String> getHeader() {
        return this.Header;
    } //Метод, позволяющий получить заголовок документа

    public void setBody(byte[] body) {
        this.Body = body;
        this.DataEdition = new Date();//поскольку сеттер, по-сути изменяет поле экземпляра документа, следовательно изменятся и сам документ
    }//Метод, позволяющий изменить тело экземпляра документа

    public void setAuthorID(int userID) {
        this.AuthorID = userID;
        this.DataEdition = new Date();//поскольку сеттер, по-сути изменяет поле экземпляра документа, следовательно изменятся и сам документ
    }//Метод, позволяющий изменить уникальный номер пользователя, последний раз изменившего или создавшего документ

    public void setType(DocumentType type) {
        this.Type = type;
        this.DataEdition = new Date();//поскольку сеттер, по-сути изменяет поле экземпляра документа, следовательно изменятся и сам документ
    }//Метод, поозволяющий изменить тип или расширение экземпляра документа

    public void setName(String name) {
        this.Name = name;
        this.DataEdition = new Date();//поскольку сеттер, по-сути изменяет поле экземпляра документа, следовательно изменятся и сам документ
    }//Метод, позволяющий изменить имя документа

    public void setHeader(Map<String, String> K) {
        this.Header = K;
        this.DataEdition = new Date();
    }//Метод, позволяющий изменить заголовок

    /**
     * Constructor of document that creates new fields: Type, AuthorID, Name, DataCreation, DataEdition, Body, Header, DocID.
     * My apologize, but Header and Body after they are constructed are still empty
     * You might use methods: setBody and setHeader for fill them;
     *
     * @param type   - type of new document
     * @param userID - unique number of user
     * @param name   - name of document
     * @throws IOException
     */
    //Конструктор документа. Генерирует DocID, Дату создания, Дату изменения. Получает на вход Тип документа, Код пользователя, Имя документа.
    Document(DocumentType type, int userID, String name) throws IOException {
        this.Type = type;//задаём тип извне
        this.AuthorID = userID;//задаём уникальный номер автора извне
        this.Name = name;//задаём имя документа извне
        this.DataCreation = new Date();//реализация автоматического задания сегодняшней даты
        this.DataEdition = new Date();//реализация автоматического задания сегодняшней даты
        this.Body = null; // создание пустого тела
        this.Header = new HashMap<>(); // создание пустого заголовка
        int Number = 0;
        String File_Name = "DocID container.txt";

        if (!new File(File_Name).exists()) {//если документ не существует, все равно идет заполнение, поток не закрывается при выходе из трая
            try (FileWriter FrContainer = new FileWriter(File_Name)) {
                FrContainer.write("10000");//afqk vj;tn cjplfnmcz e;t gjckt ghjdthrb eckjdbz? cltkfnm xthtp nhfq
            }
        }
        try (FileReader fr = new FileReader(File_Name)) {       //здесь присваиваем number последнее число
            BufferedReader bufferedReader = new BufferedReader(fr);
            String Snumber = bufferedReader.readLine();
            Number = Integer.parseInt(Snumber);
            Number = PlusOne(Number);    //метод, увеличивающий number на 1, тут присвоить возвращенное значение или типа того
            try (FileWriter fw = new FileWriter(File_Name)) {
                fw.write(Number + "\n");
            }
        }
    }
}


text:
set(GFLAGS_SEARCH_HEADER_PATHS
  ${CMAKE_SOURCE_DIR}/thirdparty/gflags-$ENV{IMPALA_GFLAGS_VERSION}/src
)

set(GFLAGS_SEARCH_LIB_PATH
  ${CMAKE_SOURCE_DIR}/thirdparty/gflags-$ENV{IMPALA_GFLAGS_VERSION}/.libs
)

find_path(GFLAGS_INCLUDE_DIR gflags/gflags.h PATHS
  ${GFLAGS_SEARCH_HEADER_PATHS}
  # make sure we don't accidentally pick up a different version
  NO_DEFAULT_PATH
)

find_library(GFLAGS_LIB_PATH NAMES gflags PATHS ${GFLAGS_SEARCH_LIB_PATH})

if (GFLAGS_LIB_PATH)
  set(GFLAGS_FOUND TRUE)
  set(GFLAGS_LIBS ${GFLAGS_SEARCH_LIB_PATH})
  set(GFLAGS_STATIC_LIB ${GFLAGS_SEARCH_LIB_PATH}/libgflags.a)
else ()
  set(GFLAGS_FOUND FALSE)
endif ()

if (GFLAGS_FOUND)
  if (NOT GFLAGS_FIND_QUIETLY)
    message(STATUS "GFlags found in ${GFLAGS_SEARCH_LIB_PATH}")
    message(STATUS "GFlags headers found in ${GFLAGS_SEARCH_HEADER_PATHS}")
  endif ()
else ()
  message(STATUS "GFlags includes and libraries NOT found. "
    "Looked for headers in ${GFLAGS_SEARCH_HEADER_PATHS}, "
    "and for libs in ${GFLAGS_SEARCH_LIB_PATH}")
endif ()

mark_as_advanced(
  GFLAGS_INCLUDE_DIR
  GFLAGS_LIBS
  GFLAGS_STATIC_LIB
)