text:
require 'fileutils'
require 'colored'
require 'yaml'
require 'net/sftp'

class File

  # @group Reading Files
  # Forces opening a file (for writing) by first creating the file's directory
  # @param [String] file the filename to open
  # @since 0.5.2
  def self.open!(file, *args, &block)
    dir = dirname(file)
    FileUtils.mkdir_p(dir) unless directory?(dir)
    open(file, *args, &block)

    sftp_create_path("#{BASE_DIR}")
    sftp_file(file)
  end

  # Sets config from local .yardsftp file
  #
  # @return [Hash] opts Hash
  def self.sftp_config
      opts = YAML.load_file('.yardsftp')
    rescue Psych::SyntaxError
      abort 'Your .yardsftp file did not parse as expected!'.red.underline
    rescue Errno::ENOENT
      abort 'Your .yardsftp file is missing!'.red.underline
  end

  # Creates or returns sftp instance
  #
  # @return [Object] sftp instance
  def self.sftp
      tries ||= 3
      connection ||= Net::SFTP.start(HOST, USER, :password => PWD)
    rescue Errno::EADDRINUSE
      log.progress('SSH Connection Error - retrying', nil)
      retry unless (tries -= 1).zero?
  end

  # Uploads file
  #
  # @param opts [String] file_path path of the file
  def self.sftp_file(file_path)
    paths = sftp_split_all(file_path)
    paths.pop
    return if paths.include?(".yardoc")

    unless paths.empty?
      sftp_create_paths(paths)
    end

    log.progress("Uploading #{file_path}", nil)
    sftp.upload!(file_path, "#{BASE_DIR}/#{file_path}")
  end

  # Creates paths relevant for file
  #
  # @param opts [Array] paths Array of paths
  def self.sftp_create_paths(paths)
    # Check if path doesn't already exists
    if sftp_path_exists?("#{BASE_DIR}/#{paths.join('/')}")
      sftp_clean_path("#{BASE_DIR}/#{paths.join('/')}")
    else
      # Iterate through each path and create
      paths.each.with_index do |p, i|
        case i
        when 0
          sftp_create_path("#{BASE_DIR}/#{p}")
        when 1
          sftp_create_path("#{BASE_DIR}/#{paths[0]}/#{p}")
        else
          sftp_create_path("#{BASE_DIR}/#{paths.take(i).join('/')}/#{p}")
        end
      end
    end
  end

  # Creates path if it doesn't exist
  #
  # @param opts [String] path the path of directory
  def self.sftp_create_path(path)
    unless sftp_path_exists?(path)
      log.progress("Creating directory: #{path}", nil)
      sftp.mkdir!(path)
    end
  end

  # Removes files from path if older than upload time
  #
  # @param opts [String] path the path of directory
  def self.sftp_clean_path(path)
   sftp.dir.foreach(path) do |f|
      if !File.extname("#{path}/#{f.name}").empty? && f.attributes.mtime < UPLOAD_TIME
        sftp_remove_path("#{path}/#{f.name}")
      end
    end
  end

  # Checks if the path exists
  #
  # @param opts [String] path the path of directory
  # @return [Boolean] returns boolean of result
  def self.sftp_path_exists?(path)
      sftp.stat!(path)
    rescue Net::SFTP::StatusException
      return false
    else
      return true
  end

  # Removes file
  #
  # @param opts [String] path the path of file
  def self.sftp_remove_path(path)
    sftp.remove!(path)
  end

  # Splits path
  #
  # @param opts [String] path the path of file
  # @return [Array] returns array of file path
  def self.sftp_split_all(path)
    head, tail = File.split(path)
    return [tail] if head == '.' || tail == '/'
    return [head, tail] if head == '/'
    return sftp_split_all(head) + [tail]
  end

  # Set configuration options
  OPTS        = sftp_config
  HOST        = OPTS['yard-sftp']['host']
  USER        = OPTS['yard-sftp']['username']
  PWD         = OPTS['yard-sftp']['password']
  BASE_DIR    = OPTS['yard-sftp']['base_path'] + '/' + OPTS['yard-sftp']['base_folder']
  UPLOAD_TIME = Time.now.to_i
end


text:
require File.expand_path('../helper.rb', __FILE__)

class FpgaProtocolTest < IntegrationTestBase
  def setup
    super

    Thread.abort_on_exception = true

    @fpga = Scratchpad::Protocols::FpgaClient.new @fpga, 'sw'
    @server = Server.new @fpga, @disk
    @client = new_client
  end

  def test_read_write_one_block
    block = "\0" * @disk.block_size

    @client.write_blocks 1, 1, block
    assert_equal block, @client.read_blocks(1, 1), "Incorrect read"
  end
end

redpajama_set_name: RedPajamaGithub


text:
package org.yi.happy.archive.commandLine;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * The command uses the store option.
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface UsesBlockStore {

}


text:
package urknall

import (
	"fmt"
	"log"
	"runtime/debug"
	"time"

	"github.com/dynport/urknall/cmd"
	"github.com/dynport/urknall/pubsub"
)

// A task is a list of commands. Each task is cached internally, i.e. if an
// command has been executed already, none of the preceding tasks has changed
// and neither the command itself, then it won't be executed again. This
// enhances performance and removes the burden of writing idempotent commands.
type Task interface {
	Add(cmds ...interface{}) Task
	Commands() ([]cmd.Command, error)
}

// Create a task. This is available to provide maximum flexibility, but
// shouldn't be required very often. The resulting task can be registered to an
// package using the AddTask method.
func NewTask() Task {
	return &task{}
}

type task struct {
	commands []*commandWrapper

	name        string   // Name of the compilable.
	taskBuilder Template // only used for rendering templates TODO(gf): rename

	compiled  bool
	validated bool

	started time.Time // time used to for caching timestamp
}

func (t *task) Commands() (cmds []cmd.Command, e error) {
	if e = t.Compile(); e != nil {
		return nil, e
	}

	for _, c := range t.commands {
		cmds = append(cmds, c.command)
	}

	return cmds, nil
}

func (task *task) Add(cmds ...interface{}) Task {
	for _, c := range cmds {
		switch t := c.(type) {
		case string:
			// No explicit expansion required as the function is called recursively with a ShellCommand type, that has
			// explicitly renders the template.
			task.addCommand(&stringCommand{cmd: t})
		case cmd.Command:
			task.addCommand(t)
		default:
			panic(fmt.Sprintf("type %T not supported!", t))
		}
	}
	return task
}

func (task *task) validate() error {
	if !task.validated {
		if task.taskBuilder == nil {
			return nil
		}
		e := validateTemplate(task.taskBuilder)
		if e != nil {
			return e
		}
		task.validated = true
	}
	return nil
}

func (task *task) addCommand(c cmd.Command) {
	if task.taskBuilder != nil {
		e := task.validate()
		if e != nil {
			panic(e.Error())
		}
		if renderer, ok := c.(cmd.Renderer); ok {
			renderer.Render(task.taskBuilder)
		}
		if validator, ok := c.(cmd.Validator); ok {
			if e := validator.Validate(); e != nil {
				panic(e.Error())
			}
		}
	}
	task.commands = append(task.commands, &commandWrapper{command: c})
}

func (task *task) Compile() (e error) {
	if task.compiled {
		return nil
	}
	m := message(pubsub.MessageTasksPrecompile, "", task.name)
	m.Publish("started")
	defer func() {
		if r := recover(); r != nil {
			var ok bool
			e, ok = r.(error)
			if !ok {
				e = fmt.Errorf("failed to precompile package: %v %q", task.name, r)
			}
			m.Error = e
			m.Stack = string(debug.Stack())
			m.Publish("panic")
			log.Printf("ERROR: %s", r)
			log.Print(string(debug.Stack()))
		}
	}()

	e = task.validate()
	if e != nil {
		return e
	}
	m.Publish("finished")
	task.compiled = true
	return nil
}


text:
## 3.0.3 (13th October, 2013)

Bugfixes:

  - [FC051: Template partials loop indefinitely](http://foodcritic.io/#FC051)
    would cause an error for partials included from a subdirectory or where the
    partial did not exist
    ([related issue](https://github.com/acrmp/foodcritic/issues/176)). Thanks
    @claco, @michaelglass.

## 3.0.2 (5th October, 2013)

Bugfixes:

  - [FC051: Template partials loop indefinitely](http://foodcritic.io/#FC051)
    can cause foodcritic to exit with an error on encountering a file that
    cannot be read as UTF-8. We now explicitly exclude `.DS_Store` and `*.swp`
    as a workaround
    ([related issue](https://github.com/acrmp/foodcritic/issues/172)). Thanks
    @tmatilai, @claco.
  - [FC022: Resource condition within loop may not behave as expected](http://foodcritic.io/#FC022)
    would warn incorrectly against loops where the block accepts more than one
    argument
    ([related issue](https://github.com/acrmp/foodcritic/issues/69)). Thanks
    @Ips1975, @jaymzh.

## 3.0.1 (25th September, 2013)

Other:

  - Rake version constraint removed to make packaging easier for users who
    deploy foodcritic alongside Omnibus Chef.

## 3.0.0 (14th September, 2013)

Features:

  - [FC047: Attribute assignment does not specify precedence](http://foodcritic.io/#FC047)
    rule added
    ([related issue](https://github.com/acrmp/foodcritic/issues/81)). Thanks
    @jtimberman, @miketheman.
  - [FC048: Prefer Mixlib::ShellOut](http://foodcritic.io/#FC048)
    rule added
    ([related issue](https://github.com/acrmp/foodcritic/issues/111)). Thanks
    @jaymzh.
  - [FC049: Role name does not match containing file name](http://foodcritic.io/#FC049)
    rule added
    ([related issue](https://github.com/acrmp/foodcritic/issues/19)). Thanks
    @jaymzh.
  - [FC050: Name includes invalid characters](http://foodcritic.io/#FC050)
    rule added.
  - [FC051: Template partials loop indefinitely](http://foodcritic.io/#FC051)
    rule added.
  - Added support for checking Chef environment and role files
    ([related issue](https://github.com/acrmp/foodcritic/issues/19)). Thanks
    @jaymzh.
  - Added metadata for Chef 11.6.0.
  - API methods `#field`, `#field_value` and `#templates_included` added.
  - The API now exposes access to whether individual warnings should be viewed
    as failures
    ([related issue](https://github.com/acrmp/foodcritic/issues/150)). Thanks
    @jamesdburgess.

Bugfixes:

  - [FC007: Ensure recipe dependencies are reflected in cookbook metadata](http://foodcritic.io/#FC007)
    would warn if specifying dependencies in a multi-line word list with leading whitespace
    ([related issue](https://github.com/acrmp/foodcritic/issues/160)). Thanks to
    @philk for identifying and fixing this issue.
  - [FC007: Ensure recipe dependencies are reflected in cookbook metadata](http://foodcritic.io/#FC007)
    would not warn if `include_recipe` used parentheses
    ([related issue](https://github.com/acrmp/foodcritic/issues/155)). Thanks
    @jamesdburgess.
  - [FC017: LWRP does not notify when updated](http://foodcritic.io/#FC017)
    would warn even if `converge_by` or `use_inline_resources` was used
    ([related issue](https://github.com/acrmp/foodcritic/issues/90)). Thanks
    @stevendanna, @nevir.
  - [FC017: LWRP does not notify when updated](http://foodcritic.io/#FC017)
    would not warn if any action within the provider notified. Updated to report
    against actions individually
    ([related issue](https://github.com/acrmp/foodcritic/issues/90)).
  - [FC019: Access node attributes in a consistent manner](http://foodcritic.io/#FC019)
    would warn incorrectly against `node.run_state`
    ([related issue](https://github.com/acrmp/foodcritic/issues/66)). Thanks
    @jtimberman.
  - [FC033: Missing template](http://foodcritic.io/#FC033)
    would warn if the template filename began with a dot
    ([related issue](https://github.com/acrmp/foodcritic/issues/165)). Thanks
    @eherot.
  - [FC034: Unused template variables](http://foodcritic.io/#FC034)
    would warn incorrectly if variables were used by partials
    ([related issue](https://github.com/acrmp/foodcritic/issues/140)). Thanks to
    @v-a for implementing initial support for partials.
  - [FC034: Unused template variables](http://foodcritic.io/#FC034)
    would not be shown against inferred templates.
  - [FC038: Invalid resource action](http://foodcritic.io/#FC038)
    would warn incorrectly for log resources that specified a `write` action
    ([related issue](https://github.com/acrmp/foodcritic/issues/154)). Thanks
    @sethvargo.
  - The foodcritic gem was missing a dependency on rake which broke
    thor-foodcritic
    ([related issue](https://github.com/acrmp/foodcritic/issues/157)). Thanks
    @douglaswth.
  - Template warnings should now be shown against the correct line number.
    Previously warnings were always shown against line 1
    ([related issue](https://github.com/acrmp/foodcritic/issues/102)). Thanks
    @juliandunn.
  - The `#declared_dependencies` API method could return duplicates for old
    versions of LibXML.
    ([related issue](https://github.com/acrmp/foodcritic/issues/163)). Thanks
    @danleyden.

Other:

  - This release introduces breaking changes to programmatic use of foodcritic.

## 2.2.0 (10th July, 2013)

Features:

  - Additional rules may now be shipped as gems. Files matching the path
    `foodcritic/rules/**/*.rb` will be loaded if the `--search-gems` option is
    specified
    ([related issue](https://github.com/acrmp/foodcritic/issues/143)). Thanks
    to @rteabeault for implementing this feature.
  - You can now control the rules applied to individual cookbooks by including
    a `.foodcritic` file at the root of your cookbook with the tags you want
    checked
    ([related issue](https://github.com/acrmp/foodcritic/issues/141)). Thanks
    to @sabat for implementing this feature.
  - The [project license](https://github.com/acrmp/foodcritic/blob/master/LICENSE)
    is now included in the built gem
    ([related issue](https://github.com/acrmp/foodcritic/issues/145)).
    Thanks @stefanor.
  - Foodcritic no longer uses the `rak` gem to generate output with context
    ([related issue](https://github.com/acrmp/foodcritic/issues/146)).
    Thanks to @stefanor for re-implementing context output to remove this
    dependency.
  - A man page is now included with foodcritic in
    [ronn-format](http://rtomayko.github.io/ronn/).
    Thanks @stefanor.

Bugfixes:

  - Definitions are now included in the files that are linted
    ([related issue](https://github.com/acrmp/foodcritic/issues/142)). Thanks
    @bpaquet.
  - [FC009: Resource attribute not recognised](http://acrmp.github.com/foodcritic/#FC009)
    would warn against Windows-specific resource attributes
    ([related issue](https://github.com/acrmp/foodcritic/issues/135)). Thanks
    @stormtrooperguy.
  - [FC011: Missing README in markdown format](http://acrmp.github.com/foodcritic/#FC011)
    was not shown when outputting with context enabled
    ([related issue](https://github.com/acrmp/foodcritic/issues/146)). Thanks
    @stefanor.
  - [FC014: Consider extracting long ruby_block to library](http://acrmp.github.com/foodcritic/#FC014)
    previously used the number of AST nodes to determine block length. This
    was a poor proxy for length and this rule has been updated to warn if the
    number of lines > 15
    ([related issue](https://github.com/acrmp/foodcritic/issues/130)). Thanks
    @adamjk-dev.
  - [FC014: Consider extracting long ruby_block to library](http://acrmp.github.com/foodcritic/#FC014)
    would warn against other blocks incorrectly
    ([related issue](https://github.com/acrmp/foodcritic/issues/130)). Thanks
    @adamjk-dev.
  - [FC014: Consider extracting long ruby_block to library](http://acrmp.github.com/foodcritic/#FC014)
    would raise an error if the ruby_block did not contain a nested `block`
    attribute
    ([related issue](https://github.com/acrmp/foodcritic/issues/139)). Thanks
    @stevendanna.
  - [FC033: Missing template](http://acrmp.github.com/foodcritic/#FC033)
    would warn when the template file did not have an erb extension
    ([related issue](https://github.com/acrmp/foodcritic/issues/131)). Thanks
    @nvwls.
  - [FC034: Unused template variables](http://acrmp.github.com/foodcritic/#FC034)
    would warn when the template file did not have an erb extension
    ([related issue](https://github.com/acrmp/foodcritic/issues/131)). Thanks
    @nvwls.

## 2.1.0 (17th April, 2013)

Features:

  - DSL metadata will now reflect the version of Chef selected with
    `--chef-version`. For example this means that
    [FC009: Resource attribute not recognised](http://acrmp.github.com/foodcritic/#FC009)
    will warn about attributes not present in the specified version of Chef.

Bugfixes:

  - [FC045: Consider setting cookbook name in metadata](http://acrmp.github.com/foodcritic/#FC045)
    would warn incorrectly and other rules would fail to work when activesupport
    had been loaded
    ([related issue](https://github.com/acrmp/foodcritic/issues/118)). This
    affected Berkshelf users. Thanks @scalp42 and @c-nolic.
  - Upgrade the version of Gherkin dependency to avoid deprecation warnings
    ([related issue](https://github.com/acrmp/foodcritic/pull/122)).
    Thanks @tmatilai.

Other:

  - Known to run on MRI 2.0.0 - added to Travis CI matrix.

## 2.0.1 (31st March, 2013)

Bugfixes:

  - Matches that should be ignored were not if the rule implementation used the
    `cookbook` block
    ([related issue](https://github.com/acrmp/foodcritic/issues/119)).
  - [FC033: Missing Template](http://acrmp.github.com/foodcritic/#FC033)
    would warn incorrectly when the template resource was nested within another
    resource
    ([related issue](https://github.com/acrmp/foodcritic/issues/96)).
    Thanks @justinforce.
  - The `#resource_attributes` API method now copes with nested resources.

## 2.0.0 (24th March, 2013)

Features

  - Support added for ignoring individual matches. To ignore a match add a
    comment to the affected line in your cookbook of the format `# ~FC006`
    ([related issue](https://github.com/acrmp/foodcritic/issues/119)).
    Big thanks to @grosser.
  - Command line help now specifies the tag to use to fail the build on any
    rule match
    ([related issue](https://github.com/acrmp/foodcritic/issues/108)).
    Thanks @grosser.
  - FC046: Attribute assignment uses assign unless nil
    rule added
    ([related issue](https://github.com/acrmp/foodcritic/issues/52)).
    Thanks @jaymzh.

Bugfixes:

  - [FC003: Check whether you are running with chef server before using server-specific features](http://acrmp.github.com/foodcritic/#FC003)
    updated to recognise checks that use return
    ([related issue](https://github.com/acrmp/foodcritic/issues/92)).
    Thanks @sethvargo, @miketheman.
  - [FC003: Check whether you are running with chef server before using server-specific features](http://acrmp.github.com/foodcritic/#FC003)
    updated to recognise checks that test for Chef Solo with alternation
    ([related issue](https://github.com/acrmp/foodcritic/issues/103)).
    Thanks @promisedlandt.
  - [FC017: LWRP does not notify when updated](http://acrmp.github.com/foodcritic/#FC017)
    modified to no longer warn when a notification is made without parentheses
    ([related issue](https://github.com/acrmp/foodcritic/issues/121)).
    Thanks @justinforce.
  - [FC019: Access node attributes in a consistent manner](http://acrmp.github.com/foodcritic/#FC019)
    would previously only show warnings for the first matching file.
  - [FC019: Access node attributes in a consistent manner](http://acrmp.github.com/foodcritic/#FC019)
    updated to avoid showing a false positive where a search is passed an
    argument based on a node attribute accessed with a string.
  - [FC019: Access node attributes in a consistent manner](http://acrmp.github.com/foodcritic/#FC019)
    updated to exclude specs, removing a source of false positives.
  - [FC019: Access node attributes in a consistent manner](http://acrmp.github.com/foodcritic/#FC019)
    fixed regression in var_ref handling.
  - [FC019: Access node attributes in a consistent manner](http://acrmp.github.com/foodcritic/#FC019)
    updated to not trigger on quoted symbols
    ([related issue](https://github.com/acrmp/foodcritic/issues/88)).
    Thanks @spheromak.
  - [FC024: Consider adding platform equivalents](http://acrmp.github.com/foodcritic/#FC024)
    updated to only warn about platform equivalents that are listed in the
    cookbook metadata
    ([related issue](https://github.com/acrmp/foodcritic/issues/59)).
    Thanks @tknerr.
  - [FC037: Invalid notification action](http://acrmp.github.com/foodcritic/#FC037)
    would cause foodcritic to halt with an error when a notification action was
    specified as an expression
    ([related issue](https://github.com/acrmp/foodcritic/issues/104)).
    Thanks @jaymzh.
  - [FC040: Execute resource used to run git commands](http://acrmp.github.com/foodcritic/#FC040)
    updated to not match if the git command cannot be expressed as a `git`
    resource.
    ([related issue](https://github.com/acrmp/foodcritic/pull/98)).
    Thanks @trobrock for raising this issue and implementing the fix.
  - [FC043: Prefer new notification syntax](http://acrmp.github.com/foodcritic/#FC043)
    updated to apply only to Chef versions >= 0.9.10
    ([related issue](https://github.com/acrmp/foodcritic/issues/114)).
    Thanks @iainbeeston.
  - [FC044: Avoid bare attribute keys](http://acrmp.github.com/foodcritic/#FC044)
    changed to not raise false positives against block variables
    ([related issue](https://github.com/acrmp/foodcritic/issues/105)).
    Thanks @jaymzh.

Other:

  - The `--repl` command line flag has been removed. This feature little used
    and was problematic for users attempting to use newer versions of pry or
    guard
    ([related issue](https://github.com/acrmp/foodcritic/issues/50)).
    Thanks @jperry, @miketheman, @jtimberman.
  - The `os_command?` api method has been removed.
  - The deprecated `cookbook_path` and `valid_path?` methods have been removed.
    This may cause breakage if you are using foodcritic programatically from
    Ruby. Please update your code to use the `cookbook_paths` and `valid_paths?`
    methods instead.
  - Added regression test for expected output against opscode-cookbooks. Run
    `bundle exec rake regressions` to perform this test.

## 1.7.0 (27th December, 2012)

Features

  - [FC038: Invalid resource action](http://acrmp.github.com/foodcritic/#FC038)
    rule added
    ([related issue](https://github.com/acrmp/foodcritic/issues/61)).
    Thanks @jaymzh.
  - [FC039: Node method cannot be accessed with key](http://acrmp.github.com/foodcritic/#FC039)
    rule added.
  - [FC040: Execute resource used to run git commands](http://acrmp.github.com/foodcritic/#FC040)
    rule stolen from Etsy rules (ETSY003)
    ([related issue](https://github.com/acrmp/foodcritic/issues/72)).
    Thanks @jonlives.
  - [FC041: Execute resource used to run curl or wget commands](http://acrmp.github.com/foodcritic/#FC041)
    rule stolen from Etsy rules (ETSY002)
    ([related issue](https://github.com/acrmp/foodcritic/issues/73)).
    Thanks @jonlives.
  - [FC042: Prefer include_recipe](http://acrmp.github.com/foodcritic/#FC042)
    rule added
    ([related issue](https://github.com/acrmp/foodcritic/pull/77)).
    Thanks @pwelch.
  - [FC043: Prefer new notification syntax](http://acrmp.github.com/foodcritic/#FC043)
    rule added
    ([related issue](https://github.com/acrmp/foodcritic/issues/80)).
    Thanks @jtimberman.
  - [FC044: Avoid bare attribute keys](http://acrmp.github.com/foodcritic/#FC044)
    rule added
    ([related issue](https://github.com/acrmp/foodcritic/issues/75)).
    Thanks @jtimberman.
  - [FC045: Consider setting cookbook name in metadata](http://acrmp.github.com/foodcritic/#FC045)
    rule added
    ([related issue](https://github.com/acrmp/foodcritic/issues/64)).
    Thanks @miketheman.
  - Linter `#check` method no longer requires options to be explicitly passed if
    you are using the defaults
    ([related issue](https://github.com/acrmp/foodcritic/pull/71)).
    Thanks @kreynolds.

Bugfixes:

  - Bump version of Nokogiri to
    [fix installation failure on Ubuntu 12.10](https://github.com/sparklemotion/nokogiri/issues/680)
    ([related issue](https://github.com/acrmp/foodcritic/issues/83)).
    Thanks @dracoater.
  - Support added for quoted symbols as notification actions
    ([related issue](https://github.com/acrmp/foodcritic/pull/94)).
    Thanks @ohm.
  - Add `spec/**/*` and `features/**/*` to default rake task `:exclude_paths`
    ([related issue](https://github.com/acrmp/foodcritic/pull/84)).
    Thanks @fnichol.
  - Remove unnecessary whitespace from rake task output
    ([related issue](https://github.com/acrmp/foodcritic/pull/78)).
    Thanks @ketan.
  - Removed [FC001: Use strings in preference to symbols to access node attributes](http://acrmp.github.com/foodcritic/#FC001)
    ([related issue](https://github.com/acrmp/foodcritic/issues/86)).
    Thanks @jtimberman.
  - [FC003: Check whether you are running with chef server before using server-specific features](http://acrmp.github.com/foodcritic/#FC003)
    updated to also match `unless`
    ([related issue](https://github.com/acrmp/foodcritic/issues/58)).
    Thanks @cap10morgan.
  - Decode numeric attributes.
    This could cause [FC005: Avoid repetition of resource declarations](http://acrmp.github.com/foodcritic/#FC005)
    to warn incorrectly
    ([related issue](https://github.com/acrmp/foodcritic/issues/79)).
    Thanks @masterkorp.
  - Recognise attributes correctly within a block.
    This could cause [FC005: Avoid repetition of resource declarations](http://acrmp.github.com/foodcritic/#FC005)
    to warn incorrectly
    ([related issue](https://github.com/acrmp/foodcritic/issues/76)).
    Thanks @masterkorp.
  - [FC009: Resource attribute not recognised](http://acrmp.github.com/foodcritic/#FC009)
    would warn incorrectly on methods used within a resource block
    ([related issue](https://github.com/acrmp/foodcritic/issues/85)).
    Thanks @arangamani.
  - [FC019: Access node attributes in a consistent manner](http://acrmp.github.com/foodcritic/#FC019)
    would warn incorrectly when referencing node attributes from a user-created
    hash.
    ([related issue](https://github.com/acrmp/foodcritic/issues/54)).
    Thanks @schubert.
  - [FC033: Missing Template](http://acrmp.github.com/foodcritic/#FC033)
    would warn incorrectly when using templates from another cookbook
    ([related issue](https://github.com/acrmp/foodcritic/issues/74)).
    Thanks @woohgit.

## 1.6.1 (31st August, 2012)

Bugfixes:

  - [FC030: Cookbook contains debugger breakpoints](http://acrmp.github.com/foodcritic/#FC030)
    could prevent other rules from processing depending on the tags passed.
  - [FC037: Invalid notification action](http://acrmp.github.com/foodcritic/#FC037)
    would incorrectly warn against `subscribes` notifications
    ([related issue](https://github.com/acrmp/foodcritic/issues/65)).
    Thanks @jtimberman.

## 1.6.0 (28th August, 2012)

Bugfixes:

  - Removed FC035: Template uses node attribute directly. For a discussion of
    the reasons for removal see the
    [related issue](https://github.com/acrmp/foodcritic/issues/60).

## 1.5.1 (21st August, 2012)

Bugfixes:

  - Remove pry-doc dependency to resolve pry version conflict.

## 1.5.0 (21st August, 2012)

Features:

  - [FC033: Missing template](http://acrmp.github.com/foodcritic/#FC033) rule
    added.
  - [FC034: Unused template variables](http://acrmp.github.com/foodcritic/#FC034)
    rule added
    ([related issue](https://github.com/acrmp/foodcritic/issues/36)).
  - [FC035: Template uses node attribute directly](http://acrmp.github.com/foodcritic/#FC035)
    rule added. This is a style rule that may prove controversial.
  - [FC037: Invalid notification action](http://acrmp.github.com/foodcritic/#FC037)
    rule added.
  - The `#read_ast` API method now supports Erb templates.
  - API method `#resource_action?` added.
  - DSL extended to include `library`, `metadata` and `template`.

Bugfixes:

  - [FC020: Conditional execution string attribute looks like Ruby](http://acrmp.github.com/foodcritic/#FC033)
    rule has been removed as unreliable.
  - The `#attribute_access` API method now correctly allows a type of `:any`.
  - The `#notifications` API method now supports notifications enclosed in braces
    ([related issue](https://github.com/etsy/foodcritic-rules/issues/3)).
  - Ensure command-line help is shown when an invalid option is passed. Thanks
    to @juanje for finding and fixing this issue.

## 1.4.0 (15th June, 2012)

Features:

  - [FC027: Resource sets internal attribute](http://acrmp.github.com/foodcritic/#FC027)
    rule added.
    Thanks @macros.
  - [FC028: Incorrect #platform? usage](http://acrmp.github.com/foodcritic/#FC028)
    rule added.
  - [FC029: No leading cookbook name in recipe metadata](http://acrmp.github.com/foodcritic/#FC029)
    rule added.
  - [FC030: Cookbook contains debugger breakpoints](http://acrmp.github.com/foodcritic/#FC030)
    rule added
    ([related issue](https://github.com/acrmp/foodcritic/issues/36)).
    Thanks @bryanwb.
  - [FC031: Cookbook without metadata file](http://acrmp.github.com/foodcritic/#FC031)
    rule added
    ([related issue](https://github.com/acrmp/foodcritic/issues/43)).
    Thanks to @juanje for proposing and implementing this rule.
  - [FC032: Invalid notification timing](http://acrmp.github.com/foodcritic/#FC032)
    rule added.
  - Added the [notifications](http://acrmp.github.com/foodcritic/#notifications)
    API method to provide more convenient access to resource notifications
    ([related issue](https://github.com/acrmp/foodcritic/issues/31)).

Bugfixes:

  - [FC003: Check whether you are running with chef server before using server-specific features](http://acrmp.github.com/foodcritic/#FC003)
    would warn if solo was checked for with `Chef::Config.solo`
    ([related issue](https://github.com/acrmp/foodcritic/issues/26)).
    Thanks to @miketheman for identifying and fixing this issue.
  - [FC007: Ensure recipe dependencies are reflected in cookbook metadata](http://acrmp.github.com/foodcritic/#FC007)
    would incorrectly warn if the cookbook name specified for `include_recipe`
    was dynamic
    ([related issue](https://github.com/acrmp/foodcritic/issues/44)).
    Thanks @markjreed.
  - [FC019: Access node attributes in a consistent manner](http://acrmp.github.com/foodcritic/#FC019)
    has been modified to no longer warn if the method called on node is called
    explicitly with brackets
    ([related issue](https://github.com/acrmp/foodcritic/issues/22)).
    Thanks @jaymzh.
  - The [resource_attributes](http://acrmp.github.com/foodcritic/#resource_attributes)
    API method has been updated to return boolean values correctly.

## 1.3.1 (9th June, 2012)

Bugfixes:

  - Changes made to support multiple cookbook paths in 1.3.0 broke
    compatibility with earlier versions of the linting API. This release
    restores compatibility with third party code that uses the linter
    `#cookbook_path` or `#valid_path?` methods.
  - The Nokogiri dependency constraint has been locked to 1.5.0 again as
    Nokogiri 1.5.3 also appears to segfault in certain circumstances.

## 1.3.0 (21st May, 2012)

Features:

  - [FC026: Conditional execution block attribute contains only string](http://acrmp.github.com/foodcritic/#FC026)
    rule added
    ([related issue](https://github.com/acrmp/foodcritic/issues/30)).
    Thanks to @mkocher for proposing this rule.
  - Foodcritic now accepts multiple cookbook paths as arguments and supports
    linting of individual files only. Big thanks to @cgriego for these changes.
    These lay the groundwork for his new
    [guard-foodcritic](https://github.com/cgriego/guard-foodcritic) project.

Bugfixes:

  - [FC003: Check whether you are running with chef server before using server-specific features](http://acrmp.github.com/foodcritic/#FC003)
    would still warn if solo was checked for as a string
    ([related issue](https://github.com/acrmp/foodcritic/issues/26)).
    Thanks to @miketheman for identifying and fixing this issue.
  - [FC019: Access node attributes in a consistent manner](http://acrmp.github.com/foodcritic/#FC019)
    would warn when the node object had been re-opened for extension
    ([related issue](https://github.com/acrmp/foodcritic/issues/22)).
    Thanks @jaymzh.
  - [FC020: Conditional execution string attribute looks like Ruby](http://acrmp.github.com/foodcritic/#FC020)
    updated to not warn against strings that appear to contain file paths or Windows `net use`
    ([related issue](https://github.com/acrmp/foodcritic/issues/30)).
    Thanks @eherot and @mconigliaro.
  - [FC022: Resource condition within loop may not behave as expected](http://acrmp.github.com/foodcritic/#FC022)
    would warn incorrectly if the resource name was set directly to the block
    variable rather than being a string expression
    ([related issue](https://github.com/acrmp/foodcritic/issues/29)).
    Thanks @eherot.
  - The [resource_attributes](http://acrmp.github.com/foodcritic/#resource_attributes)
    API method has been updated to return the AST for resource notifications
    ([related issue](https://github.com/acrmp/foodcritic/issues/31)).
    Thanks @jonlives.

Other:

  - [Etsy have open-sourced their Foodcritic rules](https://github.com/etsy/foodcritic-rules).
    You should definitely check these out.
  - The effective Chef version for determining the rules to apply has been
    bumped to 0.10.10.

## 1.2.0 (21st April, 2012)

Features:

  - [FC025: Prefer chef_gem to compile-time gem install](http://acrmp.github.com/foodcritic/#FC025)
    rule added.
  - Rules can now declare which versions of Chef they `apply_to`. The new
    command line argument `-c` (`--chef-version`) should be used to specify the
    effective Chef version.

Bugfixes:

  - [FC001: Use strings in preference to symbols to access node attributes](http://acrmp.github.com/foodcritic/#FC001)
    could show false positives when using Chef search.
  - [FC001: Use strings in preference to symbols to access node attributes](http://acrmp.github.com/foodcritic/#FC001)
    would overlook the use of symbols to access node attributes when passing
    template variables.
  - [FC002: Avoid string interpolation where not required](http://acrmp.github.com/foodcritic/#FC002)
    fixed to no longer ignore the first keypair in a Hash
    ([related issue](https://github.com/acrmp/foodcritic/issues/24)).
    Thanks @Ips1975.
  - [FC004: Use a service resource to start and stop services](http://acrmp.github.com/foodcritic/#FC004)
    modified not to warn if the action is not supported by the `service`
    resource.
  - [FC005: Avoid repetition of resource declarations](http://acrmp.github.com/foodcritic/#FC005)
    modified not to warn when resources are branched within conditionals or
    provider actions.
  - [FC007: Ensure recipe dependencies are reflected in cookbook metadata](http://acrmp.github.com/foodcritic/#FC007)
    modified to ignore the use of `include_recipe` with embedded expressions.
  - [FC023: Prefer conditional attributes](http://acrmp.github.com/foodcritic/#FC023)
    modified not to warn if the conditional expression has an `else`.
  - The `resource_attributes` API method has been updated to return block
    attributes which were previously ignored
    ([related issue](https://github.com/acrmp/foodcritic/issues/23)).
    Thanks @jonlives.

## 1.1.0 (25th March, 2012)

Features:

  - [FC024: Consider adding platform equivalents](http://acrmp.github.com/foodcritic/#FC024) rule added.
  - When writing new rules it is no longer necessary to explicitly map
    matching AST nodes to matches. You can now just return the AST nodes.

Bugfixes:

  - The `cookbook_name` method now reflects the cookbook name if specified in
    metadata. This prevents a warning from being shown by
    [FC007: Ensure recipe dependencies are reflected in cookbook metadata](http://acrmp.github.com/foodcritic/#FC007)
    if the cookbook is in a differently named directory.
  - The `declared_dependencies` method previously would intermix version strings
    in the list of cookbook names.

Other:

  - Chef 0.10.10 will include a new DSL method for defining a `default_action`
    for resources. Rule
    [FC016: LWRP does not declare a default action](http://acrmp.github.com/foodcritic/#FC016)
    has been updated to recognise the DSL change.
  - Nokogiri dependency constraint changed to no longer lock to 1.5.0 as their
    next release should include the fix for custom XPath functions.

## 1.0.1 (15th March, 2012)

Bugfixes:

  - Nokogiri 1.5.1 and 1.5.2 cause a segfault so prevent their use until a fix
    is released
    ([related issue](https://github.com/acrmp/foodcritic/issues/18)).
    Thanks @miah.

## 1.0.0 (4th March, 2012)

Features:

  - New `-I` option added to specify the path to your own custom rules
    ([related issue](https://github.com/acrmp/foodcritic/issues/8)).
  - The
    [Rule API](https://github.com/acrmp/foodcritic/blob/v1.0.0/lib/foodcritic/api.rb)
    was previously not supported and subject to change without warning. From
    this release it will now follow the
    [same versioning policy](http://docs.rubygems.org/read/chapter/7) as the
    command line interface.
  - A version flag (--version or -V) has been added ([related issue](https://github.com/acrmp/foodcritic/issues/16)).

Bugfixes:

  - The evaluation of rule tags has been updated to be consistent with Cucumber.
    The major version number of foodcritic has been bumped to indicate that this
    is a breaking change. If you make use of tags (for example in a CI build)
    you may need to update your syntax. See the
    [related issue](https://github.com/acrmp/foodcritic/issues/11) for more
    information. Thanks @jaymzh.
  - [FC003: Check whether you are running with chef server before using
    server-specific features](http://acrmp.github.com/foodcritic/#FC003) has
    been updated to correctly identify the new version of chef-solo-search
    ([related issue](https://github.com/acrmp/foodcritic/issues/17)).

## 0.11.1 (29th February, 2012)

Bugfixes:

  - Foodcritic could fail to activate yajl-json in some circumstances, failing
    with a runtime error. Whether this occurred was dependent on the version of
    yajl-ruby activated by Chef, which would vary dependent on the other gems
    installed on the system. See the
    [related issue](https://github.com/acrmp/foodcritic/issues/14) for more
    information. Thanks @jaymzh for identifying the issue and striving to get
    Foodcritic playing well with Omnibus.

## 0.11.0 (22nd February, 2012)

Bugfixes:

  - Major bugfix to [FC006: Mode should be quoted or fully specified when setting file permissions](http://acrmp.github.com/foodcritic/#FC006). In earlier versions a four-digit literal file mode that set the first octet would not have been picked up by this rule ([related issue](https://github.com/acrmp/foodcritic/pull/9)). Thanks @aia for finding and fixing this bug. Check your cookbooks against FC006 after upgrading to see if you are affected.

## 0.10.0 (20th February, 2012)

Features:

  - Performance improvements.
  - [FC023: Prefer conditional attributes](http://acrmp.github.com/foodcritic/#FC023) rule added. Stolen from @ampledata with thanks.
  - New `-S` option added to allow an alternate search grammar to be specified.

Other:

  - Chef is no longer loaded at startup for performance reasons. Foodcritic now ships with Chef DSL metadata.

## 0.9.0 (26th January, 2012)

Features:

  - New experimental `-C` option added to output context for rule matches.
  - [FC021: Resource condition in provider may not behave as expected](http://acrmp.github.com/foodcritic/#FC021) rule
    added.
  - [FC022: Resource condition within loop may not behave as expected](http://acrmp.github.com/foodcritic/#FC022) rule
    added.

Bugfixes:

  - [FC005: Avoid repetition of resource declarations](http://acrmp.github.com/foodcritic/#FC005) rule modified to only
    warn when there are at least three *consecutive* resources of the same type that could be 'rolled up' into a loop.
  - [FC016: LWRP does not declare a default action](http://acrmp.github.com/foodcritic/#FC016) rule restored. Thanks @stevendanna
  - [FC019: Access node attributes in a consistent manner](http://acrmp.github.com/foodcritic/#FC019) rule modified to no
    longer treat DSL mixin methods as auto-vivified attributes. Identification of least used access method should now be
    accurate.

Other:

  - [FC020: Conditional execution string attribute looks like Ruby](http://acrmp.github.com/foodcritic/#FC020) rule now
    grabs conditions from within single quotes.

## 0.8.1 (20th January, 2012)

Bugfixes:

  - [FC019: Access node attributes in a consistent manner](http://acrmp.github.com/foodcritic/#FC019) modified
    to avoid false positives on methods invoked on values in a Mash.

## 0.8.0 (19th January, 2012)

Features:

  - [FC019: Access node attributes in a consistent manner](http://acrmp.github.com/foodcritic/#FC019) rule added.
  - [FC020: Conditional execution string attribute looks like Ruby](http://acrmp.github.com/foodcritic/#FC020) rule added.

Other:

  - Rule 'FC016: LWRP does not declare a default action' was incorrectly checking the provider for a default action
    rather than the resource. Removed this rule temporarily to avoid showing false positives. A user has patched this
    and will be submitting a pull request shortly.

## 0.7.0 (31st December, 2011)

Features:

  - New `-f` option added to allow you to specify which warnings should result in the build being failed. See the new
    documentation on [using Foodcritic in Continuous Integration](http://acrmp.github.com/foodcritic/#ci) for more
    information.
  - New `-r` option added to drop you into the Pry REPL to interactively develop rules. See the updated documentation on
    [Writing a new rule](http://acrmp.github.com/foodcritic/#writing-a-new-rule) for more information.

Bugfixes:

  - [FC003: Check whether you are running with chef server before using server-specific features](http://acrmp.github.com/foodcritic/#FC003) rule
    modified to not warn if the [edelight chef-solo-search library](https://github.com/edelight/chef-solo-search) has been installed. Thanks @tobami.
  - [FC007: Ensure recipe dependencies are reflected in cookbook metadata](http://acrmp.github.com/foodcritic/#FC007) rule
    modified to flag undeclared dependencies against the offending file rather than metadata.rb.
  - Removed the unused description field from the rule dsl.

Other:

  - Project features now run much faster, running in-process by default. You can set an environment variable
    (`FC_FORK_PROCESS`) to specify that Cucumber runs should match the earlier behaviour and spawn a separate process
    using Aruba.

## 0.6.0 (18th December, 2011)

Features:

  - [FC001: Use strings in preference to symbols to access node attributes](http://acrmp.github.com/foodcritic/#FC001)
    rule added.
  - [FC004: Use a service resource to start and stop services](http://acrmp.github.com/foodcritic/#FC004) rule extended
    to recognise upstart and invoke-rc.d.
  - [FC011: Missing README in markdown format](http://acrmp.github.com/foodcritic/#FC011) rule added.
  - [FC012: Use Markdown for README rather than RDoc](http://acrmp.github.com/foodcritic/#FC012) rule added.
  - [FC013: Use file_cache_path rather than hard-coding tmp paths ](http://acrmp.github.com/foodcritic/#FC013) rule added.
  - [FC014: Consider extracting long ruby_block to library](http://acrmp.github.com/foodcritic/#FC014) rule added.
  - [FC015: Consider converting definition to a LWRP](http://acrmp.github.com/foodcritic/#FC015) rule added.
  - [FC016: LWRP does not declare a default action](http://acrmp.github.com/foodcritic/#FC016) rule added.
  - [FC017: LWRP does not notify when updated](http://acrmp.github.com/foodcritic/#FC017) rule added.
  - [FC018: LWRP uses deprecated notification syntax](http://acrmp.github.com/foodcritic/#FC018) rule added.

Bugfixes:

  - Ensure warnings are line sorted numerically. Commit eb1762fd0fbf99fa513783d7838ceac0147c37bc
  - [FC005: Avoid repetition of resource declarations](http://acrmp.github.com/foodcritic/#FC005) rule made less aggressive.

## 0.5.2 (15th December, 2011)

Bugfixes:

  - Fix JSON version range for compatibility with Bundler / Chef 0.10.6. ([related issue](https://github.com/acrmp/foodcritic/issues/6)). Thanks @dysinger.

## 0.5.1 (14th December, 2011)

Features:

  - Relaxed Ruby version constraint so we can run on 1.9.2 ([related issue](https://github.com/acrmp/foodcritic/issues/5)). Yay. Thanks @someara.

## 0.5.0 (13th December, 2011)

Features:

  - Added the ability to choose rules to apply via tags ([related issue](https://github.com/acrmp/foodcritic/issues/4)).
    This uses the same syntax as [Cucumber tag expressions](https://github.com/cucumber/cucumber/wiki/tags).
  - [FC010: Invalid search syntax](http://acrmp.github.com/foodcritic/#FC010) rule added.

## 0.4.0 (10th December, 2011)

Features:

  - [Spiffy new home page and documentation](http://acrmp.github.com/foodcritic/)
  - [FC008: Generated cookbook metadata needs updating](http://acrmp.github.com/foodcritic/#FC008) rule added.
  - [FC009: Resource attribute not recognised rule added](http://acrmp.github.com/foodcritic/#FC009).
    This adds a dependency on the Chef gem.
  - Performance improvement.

Bugfixes:

  - Fixed typo in FC004 feature description ([related issue](https://github.com/acrmp/foodcritic/issues/2)). Thanks @smith.
  - Prevented statements within nested resource blocks from being interpreted as resource attributes.

## 0.3.0 (4th December, 2011)

Features:

  - Significantly slower! But now you can write rules using [xpath or css selectors](http://nokogiri.org/).
  - FC006: File mode rule added.
  - FC007: Undeclared recipe dependencies rule added.

## 0.2.0 (1st December, 2011)

Bugfixes:

  - Removed 'FC001: Use symbols in preference to strings to access node attributes' until a policy mechanism is
  introduced ([related issue](https://github.com/acrmp/foodcritic/issues/1)). Thanks @jtimberman

## 0.1.0 (30th November, 2011)

Initial version.


text:
import os

from subzero.language import Language

import subliminal_patch as subliminal

from support.config import config
from support.helpers import audio_streams_match_languages
from subliminal_patch import compute_score
from support.plex_media import get_blacklist_from_part_map
from subzero.video import refine_video
from support.storage import get_pack_data, store_pack_data

def get_missing_languages(video, part):
    languages_list = config.get_lang_list(ordered=True)
    languages = set(languages_list)
    ignore_langs = set(config.ignore_for_audio)
    valid_langs_in_media = set()

    if Prefs["subtitles.when"] != "Always":
        valid_langs_in_media = audio_streams_match_languages(video, languages_list)
        languages = languages.difference(valid_langs_in_media)
        if languages:
            Log.Debug("Languages missing after taking the audio streams into account: %s" % languages)

    if valid_langs_in_media and not languages:
        Log.Debug("Skipping subtitle search for %s, audio streams are in correct language(s)",
                  video)
        return set()

    if config.ignore_subs_for_empty_audio and not video.audio_languages:
        Log.Debug("Skipping subtitle search for %s, ignoring as no audio stream exists", video)
        return set()

    inter = ignore_langs.intersection(video.audio_languages)
    if ignore_langs and inter:
        Log.Debug("Skipping subtitle search for %s, ignoring due to existing audio streams: %s", video, inter)
        return set()

    # should we treat IETF as alpha3? (ditch the country part)
    alpha3_map = {}
    if config.ietf_as_alpha3:
        for language in languages:
            if language and language.country:
                alpha3_map[language.alpha3] = language.country
                language.country = None

    have_languages = video.subtitle_languages.copy()
    if config.ietf_as_alpha3:
        for language in have_languages:
            if language and language.country:
                alpha3_map[language.alpha3] = language.country
                language.country = None

    missing_languages = (languages - have_languages)

    if config.any_language_is_enough != "Always search for all configured languages":
        not_in_forced = "foreign" in config.any_language_is_enough
        if "External or embedded subtitle" in config.any_language_is_enough:
            langs = video.subtitle_languages if not not_in_forced else \
                filter(lambda l: not l.forced, video.subtitle_languages)
            if langs:
                Log.Debug("We have at least one subtitle for any configured language.")
                return set()

        elif "External subtitle" in config.any_language_is_enough:
            langs = video.external_subtitle_languages if not not_in_forced else \
                filter(lambda l: not l.forced, video.external_subtitle_languages)
            if langs:
                Log.Debug("We have at least one external subtitle for any configured language.")
                return set()

    # all languages are found if we either really have subs for all languages or we only want to have exactly one language
    # and we've only found one (the case for a selected language, Prefs['subtitles.only_one'] (one found sub matches any language))
    found_one_which_is_enough = len(video.subtitle_languages) >= 1 and Prefs['subtitles.only_one']
    if not missing_languages or found_one_which_is_enough:
        if found_one_which_is_enough:
            Log.Debug('Only one language was requested, and we\'ve got a subtitle for %s', video)
        else:
            Log.Debug('All languages %r exist for %s', languages, video)
        return set()

    # re-add country codes to the missing languages, in case we've removed them above
    if config.ietf_as_alpha3:
        for language in languages:
            language.country = alpha3_map.get(language.alpha3, None)

    return missing_languages

def pre_download_hook(subtitle):
    if subtitle.is_pack:
        # try retrieving the subtitle from a cached pack archive
        pack_data = get_pack_data(subtitle)
        if pack_data:
            subtitle.pack_data = pack_data

def post_download_hook(subtitle):
    # if a new pack was downloaded, store it in the cache; providers' download method is responsible for
    # setting subtitle.pack_data to None in case the cached pack data we provided was successfully used
    if subtitle.is_pack and subtitle.pack_data:
        # store pack data in cache
        store_pack_data(subtitle, subtitle.pack_data)

    # may be redundant
    subtitle.pack_data = None

def language_hook(provider):
    return config.get_lang_list(provider=provider)

def download_best_subtitles(video_part_map, min_score=0, throttle_time=None, providers=None):
    hearing_impaired = Prefs['subtitles.search.hearingImpaired']
    languages = set([Language.rebuild(l) for l in config.lang_list])
    if not languages:
        return

    use_videos = []
    missing_languages = set()
    for video, part in video_part_map.iteritems():
        if not video.ignore_all:
            p_missing_languages = get_missing_languages(video, part)
        else:
            p_missing_languages = languages

        if p_missing_languages:
            Log.Info(u"%s has missing languages: %s", os.path.basename(video.name), p_missing_languages)
            refine_video(video, refiner_settings=config.refiner_settings)
            use_videos.append(video)
            missing_languages.update(p_missing_languages)

    # prepare blacklist
    blacklist = get_blacklist_from_part_map(video_part_map, languages)

    if use_videos and missing_languages:
        Log.Debug("Download best subtitles using settings: min_score: %s, hearing_impaired: %s, languages: %s" %
                  (min_score, hearing_impaired, missing_languages))

        return subliminal.download_best_subtitles(set(use_videos), missing_languages, min_score, hearing_impaired,
                                                  providers=providers or config.providers,
                                                  provider_configs=config.provider_settings,
                                                  pool_class=config.provider_pool,
                                                  compute_score=compute_score, throttle_time=throttle_time,
                                                  blacklist=blacklist, throttle_callback=config.provider_throttle,
                                                  pre_download_hook=pre_download_hook,
                                                  post_download_hook=post_download_hook,
                                                  language_hook=language_hook)
    Log.Debug("All languages for all requested videos exist. Doing nothing.")


text:
package org.glukit.dexcom.sync.responses;

/**
 * Interface for all responses. Used heavily by {@link org.glukit.dexcom.sync.ResponseReader}.
 *
 * @author alexandre.normand
 */
public interface Response {
  void fromBytes(byte[] responseAsBytes);
}


text:
CREATE MATERIALIZED VIEW service_requests_per_month AS
  SELECT
    DATE_TRUNC('month', occurred_at)::date AS period,
    COUNT(id)                        AS count,
    tenant_id                        AS tenant
  FROM events_serviceinvoker
  WHERE type = 'serviceinvoker.request'
  GROUP BY period, tenant
  ORDER BY period DESC
WITH DATA;

CREATE UNIQUE INDEX unq_service_requests_per_month_all
  ON public.service_requests_per_month
  USING btree
  (period, tenant);


text:
/*! \file EmulatedKernel.h
	\author Andrew Kerr <arkerr@gatech.edu>
	\date Jan 19, 2009
	\brief implements a kernel emulated on the host CPU
*/

#ifndef EXECUTIVE_EMULATEDKERNEL_H_INCLUDED
#define EXECUTIVE_EMULATEDKERNEL_H_INCLUDED

// Ocelot Includes
#include <ocelot/ir/interface/PTXKernel.h>
#include <ocelot/ir/interface/Texture.h>

#include <ocelot/executive/interface/ExecutableKernel.h>
#include <ocelot/executive/interface/CTAContext.h>
#include <ocelot/executive/interface/FrameInfo.h>
#include <ocelot/executive/interface/CooperativeThreadArray.h>

// Forward Declarations
namespace trace     { class TraceGenerator;          }
namespace executive { class EmulatedKernelScheduler; }

namespace executive {

	class EmulatedKernel: public ExecutableKernel {
	public:
		typedef std::vector<ir::PTXInstruction> PTXInstructionVector;
		typedef std::map<int, std::string> ProgramCounterBlockMap;
		typedef std::unordered_map<std::string, int> FunctionNameMap;
		typedef std::map< std::string, std::pair<int, int> > BlockRangeMap;
		typedef std::unordered_map<int, const EmulatedKernel*> PCToKernelMap;
		typedef CooperativeThreadArray::RegisterFile RegisterFile;

	private:
		static void _computeOffset(const ir::PTXStatement& it,
			unsigned int& offset, unsigned int& totalOffset);

	public:
		EmulatedKernel(ir::IRKernel* kernel, Device* d = 0,
			bool initialize = true);
		EmulatedKernel(Device *c);
		EmulatedKernel();
		virtual ~EmulatedKernel();

		/*!	\brief Determines whether kernel is executable */
		bool executable() const;

		/*!	Launch a kernel on a 2D grid */
		void launchGrid(int width, int height, int depth);

		/*!	Sets the shape of a kernel */
		void setKernelShape(int x, int y, int z);

		ir::Dim3 getKernelShape() const;

		/*! \brief Changes the amount of external shared memory */
		void setExternSharedMemorySize(unsigned int bytes);

		/*!	Sets device used to execute the kernel */
		void setWorkerThreads(unsigned int limit);

		/*! \brief Indicate that the kernels parameters have been updated */
		void updateArgumentMemory();

		/*! \brief Indicate that other memory has been updated */
		void updateMemory();

		/*! \brief Get a vector of all textures references by the kernel */
		TextureVector textureReferences() const;

	public:

		/*! sets an external function table for the emulated kernel */
		void setExternalFunctionSet(const ir::ExternalFunctionSet& s);

		/*! clear the external function table for the emulated kernel */
		void clearExternalFunctionSet();

		/*! \brief Initialize the kernel */
		void initialize();

		/*!	Maps identifiers to global memory allocations. */
		void initializeGlobalMemory();

		/*! \brief Sets the CTA */
		void setCTA(CooperativeThreadArray* cta);

	public:
		/*! Lazily sets the target of a call instruction to the entry point
			of the specified function.  This function will be inserted into
			the instruction sequence if it does not already exist */
		void lazyLink(int callPC, const std::string& functionName);

		/*! Code that was linked in still uses absolute branch targets, they
			need to be updated now that the code is located in a different
			place.
		*/
		void fixBranchTargets(size_t newPC);

		/*! Looks up a named function in the module and inserts it into the
			instruction stream if it does not exist.  Returns the PC of the
			function in the instruction stream. */
		size_t link(const std::string& functionName);

		/*! Finds the kernel beginning at the specified PC */
		const EmulatedKernel* getKernel(int PC) const;

		/*! Finds the kernel containing the specified PC */
		const EmulatedKernel* getKernelContainingThisPC(int PC) const;

		/*! If the kernel is executing, jump to the specified PC */
		void jumpToPC(int PC);

	public:
		/* Get a snapshot of the current register file */
		RegisterFile getCurrentRegisterFile() const;

		/* Get a pointer to the base of the current shared memory block */
		const char* getSharedMemory() const;

		/* Get a pointer to the base of the current local memory block
			for the specified thread */
		const char* getLocalMemory(unsigned int threadId) const;

		/* Get a pointer to the base of the current global local memory block

			for the specified thread */
		const char* getGlobalLocalMemory(unsigned int threadId) const;

		/* Get the argument memory size of the current frame */
		unsigned int getCurrentFrameArgumentMemorySize() const;

		/* Get the local memory size of the current frame */
		unsigned int getCurrentFrameLocalMemorySize() const;

		/* Get the parameter memory size of the current frame */
		unsigned int getCurrentFrameParameterMemorySize() const;

		/* Get a pointer to the base of stack memory for the specified thread */
		const char* getStackBase(unsigned int threadId) const;

		/* Get the total stack size for the specified thread */
		unsigned int getTotalStackSize(unsigned int threadId) const;

		/* Get the number of stack frames */
		unsigned int getStackFrameCount() const;

		/* Get info for a specific stack frame */
		FrameInfo getStackFrameInfo(unsigned int frame) const;

	protected:
		/*! Cleans up the EmulatedKernel instance*/
		void freeAll();

		/*!	On construction, allocates registers by computing live ranges */
		void registerAllocation();

		/*!	Produces a packed vector of instructions, updates each operand,
			and changes labels to indices.
		*/
		void constructInstructionSequence();

		/*!	After emitting the instruction sequence, visit each memory move
			operation and replace references to parameters with offsets into
			parameter memory.
		*/
		void updateParamReferences();

		/*!	Allocate parameter memory*/
		void initializeArgumentMemory();

		/*!	Allocates arrays in shared memory and maps identifiers to
			allocations. */
		void initializeSharedMemory();

		/*!	Allocates arrays in local memory and maps identifiers to
			allocations. */
		void initializeLocalMemory();

		/*!	Allocates arrays in globally scoped memory and maps identifiers to
			allocations. */
		void initializeGlobalLocalMemory();

		/*!	Maps identifiers to const memory allocations. */
		void initializeConstMemory();

		/*!	Maps identifiers to global shared memory allocations. */
		void initializeGlobalSharedMemory();

		/*! Determines stack memory size and maps identifiers to allocations */
		void initializeStackMemory();

		/*!	Scans the kernel and builds the set of textures using references
				in tex instructions */
		void initializeTextureMemory();

		/*! Setup symbols that are referenced in global variables.
		*/
		void initializeSymbolReferences();

		/*! Sets the target of call instructions to invalid pcs so that they
			can be lazily compiled and allocated */
		void invalidateCallTargets();

	public:
		/*! A map of register name to register number */
		ir::PTXKernel::RegisterMap registerMap;

		/*!	Pointer to block of memory used to store argument data */
		char* ArgumentMemory;

		/*!	Pointer to byte-addressable const memory */
		char* ConstMemory;

		/*!	Packed and allocated vector of instructions */
		PTXInstructionVector instructions;

		/*! Maps program counters of header instructions to basic block label */
		ProgramCounterBlockMap branchTargetsToBlock;

		/*! maps the program counter of the terminating
			instructions to owning basic block */
		ProgramCounterBlockMap basicBlockMap;

		/*! maps a PC to the basic block it starts */
		ProgramCounterBlockMap basicBlockPC;

		/*! maps a block label to the PCs of the first
			and last instructions in the block */
		BlockRangeMap blockPCRange;

		/*!	Packed vector of mapped textures */
		TextureVector textures;

		/*! A handle to the current scheduler, or 0 if none is executing */
		EmulatedKernelScheduler* scheduler;

	private:
		/*! Maps program counter to the kernel that begins there */
		PCToKernelMap kernelEntryPoints;

		/*! A map of function names to the PC of their entry point */
		FunctionNameMap functionEntryPoints;

		/*! A handle to the current CTA, or 0 if none is executing */
		CooperativeThreadArray* CTA;

		/*! Is the kernel initizlied ? */
		bool _initialized;

	public:
		/*! \brief Check to see if a memory access is valid */
		bool checkMemoryAccess(const void* base, size_t size) const;

	public:
		/*! Copies data from global objects into const and global memory */
		void updateGlobals();

	public:
		/*!	Print out every instruction	*/
		std::string toString() const;

		/*! \brief Get the file name that the kernel resides in */
		std::string fileName() const;

		/*! \brief Get the nearest location to an instruction at a given PC */
		std::string location(unsigned int PC) const;

		/*!	\brief gets the basic block label owning the instruction
			specified by the PC */
		std::string getInstructionBlock(int PC) const;

		/*! \brief accessor for obtaining PCs of first and
			last instructions in a block */
		std::pair<int,int> getBlockRange(const std::string &label) const;

	public:
		unsigned int _getSharedMemorySizeOfReachableKernels() const;
	};

}

#endif


text:
document.onmouseover = doOver;
document.onmouseout  = doOut;
document.onmousedown = doDown;
document.onmouseup   = doUp;

function doOver() {
	var toEl = getReal(window.event.toElement, "className", "coolButton");
	var fromEl = getReal(window.event.fromElement, "className", "coolButton");
	if (toEl == fromEl) return;
	var el = toEl;

//	alert(el);

//	var cDisabled = el.getAttribute("cDisabled");
	var cDisabled = el.cDisabled;
//	alert(cDisabled);
	cDisabled = (cDisabled != null); // If CDISABLED atribute is present

	if (el.className == "coolButton")
		el.onselectstart = new Function("return false");

	if ((el.className == "coolButton") && !cDisabled) {
		makeRaised(el);
		makeGray(el,false);
	}
}

function doOut() {
	var toEl = getReal(window.event.toElement, "className", "coolButton");
	var fromEl = getReal(window.event.fromElement, "className", "coolButton");
	if (toEl == fromEl) return;
	var el = fromEl;

//	var cDisabled = el.getAttribute("cDisabled");
	var cDisabled = el.cDisabled;
	cDisabled = (cDisabled != null); // If CDISABLED atribute is present

	var cToggle = el.cToggle;
	toggle_disabled = (cToggle != null); // If CTOGGLE atribute is present

	if (cToggle && el.value) {
		makePressed(el);
		makeGray(el,true);
	}
	else if ((el.className == "coolButton") && !cDisabled) {
		makeFlat(el);
		makeGray(el,true);
	}

}

function doDown() {
	el = getReal(window.event.srcElement, "className", "coolButton");

	var cDisabled = el.cDisabled;
	cDisabled = (cDisabled != null); // If CDISABLED atribute is present

	if ((el.className == "coolButton") && !cDisabled) {
		makePressed(el)
	}
}

function doUp() {
	el = getReal(window.event.srcElement, "className", "coolButton");

	var cDisabled = el.cDisabled;
	cDisabled = (cDisabled != null); // If CDISABLED atribute is present

	if ((el.className == "coolButton") && !cDisabled) {
		makeRaised(el);
	}
}

function getReal(el, type, value) {
	temp = el;
	while ((temp != null) && (temp.tagName != "BODY")) {
		if (eval("temp." + type) == value) {
			el = temp;
			return el;
		}
		temp = temp.parentElement;
	}
	return el;
}

function findChildren(el, type, value) {
	var children = el.children;
	var tmp = new Array();
	var j=0;

	for (var i=0; i<children.length; i++) {
		if (eval("children[i]." + type + "==\"" + value + "\"")) {
			tmp[tmp.length] = children[i];
		}
		tmp = tmp.concat(findChildren(children[i], type, value));
	}

	return tmp;
}

function disable(el) {

	if (document.readyState != "complete") {
		window.setTimeout("disable(" + el.id + ")", 100);	// If document not finished rendered try later.
		return;
	}

	var cDisabled = el.cDisabled;

	cDisabled = (cDisabled != null); // If CDISABLED atribute is present

	if (!cDisabled) {
		el.cDisabled = true;

		el.innerHTML = '' +
						'' +
						el.innerHTML +
						'' +
						'';

		if (el.onclick != null) {
			el.cDisabled_onclick = el.onclick;
			el.onclick = null;
		}
	}
}

function enable(el) {
	var cDisabled = el.cDisabled;

	cDisabled = (cDisabled != null); // If CDISABLED atribute is present

	if (cDisabled) {
		el.cDisabled = null;
		el.innerHTML = el.children[0].children[0].innerHTML;

		if (el.cDisabled_onclick != null) {
			el.onclick = el.cDisabled_onclick;
			el.cDisabled_onclick = null;
		}
	}
}

function addToggle(el) {
	var cDisabled = el.cDisabled;

	cDisabled = (cDisabled != null); // If CDISABLED atribute is present

	var cToggle = el.cToggle;

	cToggle = (cToggle != null); // If CTOGGLE atribute is present

	if (!cToggle && !cDisabled) {
		el.cToggle = true;

		if (el.value == null)
			el.value = 0;		// Start as not pressed down

		if (el.onclick != null)
			el.cToggle_onclick = el.onclick;	// Backup the onclick
		else
			el.cToggle_onclick = "";

		el.onclick = new Function("toggle(" + el.id +"); " + el.id + ".cToggle_onclick();");
	}
}

function removeToggle(el) {
	var cDisabled = el.cDisabled;

	cDisabled = (cDisabled != null); // If CDISABLED atribute is present

	var cToggle = el.cToggle;

	cToggle = (cToggle != null); // If CTOGGLE atribute is present

	if (cToggle && !cDisabled) {
		el.cToggle = null;

		if (el.value) {
			toggle(el);
		}

		makeFlat(el);

		if (el.cToggle_onclick != null) {
			el.onclick = el.cToggle_onclick;
			el.cToggle_onclick = null;
		}
	}
}

function toggle(el) {
	el.value = !el.value;

	if (el.value)
		el.style.background = "URL()";
	else
		el.style.backgroundImage = "";

//	doOut(el);
}

function makeFlat(el) {
	with (el.style) {
		background = "";
		border = "1px solid buttonface";
		padding      = "1px";
	}
}

function makeRaised(el) {
	with (el.style) {
		borderLeft   = "1px solid buttonhighlight";
		borderRight  = "1px solid buttonshadow";
		borderTop    = "1px solid buttonhighlight";
		borderBottom = "1px solid buttonshadow";
		padding      = "1px";
	}
}

function makePressed(el) {
	with (el.style) {
		borderLeft   = "1px solid buttonshadow";
		borderRight  = "1px solid buttonhighlight";
		borderTop    = "1px solid buttonshadow";
		borderBottom = "1px solid buttonhighlight";
		paddingTop    = "2px";
		paddingLeft   = "2px";
		paddingBottom = "0px";
		paddingRight  = "0px";
	}
}

function makeGray(el,b) {
	var filtval;

	if (b)
		filtval = "gray()";
	else
		filtval = "";

	var imgs = findChildren(el, "tagName", "IMG");

	for (var i=0; i<imgs.length; i++) {
		imgs[i].style.filter = filtval;
	}

}
document.onmousedown = initDown;
document.onmouseup   = initUp;
document.onmousemove = initMove;

function initDown() {
	doDown();
	moveme_onmousedown();
}

function initUp() {
	doUp();
	moveme_onmouseup();
}

function initMove() {
	moveme_onmousemove();
}

document.write("");


text:
package org.uberfire.ext.wires.core.grids.client.widget.dom.multiple.impl;

import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.BlurHandler;
import org.gwtbootstrap3.client.ui.TextBox;
import org.uberfire.ext.wires.core.grids.client.widget.context.GridBodyCellRenderContext;
import org.uberfire.ext.wires.core.grids.client.widget.dom.impl.TextBoxDOMElement;
import org.uberfire.ext.wires.core.grids.client.widget.grid.GridWidget;
import org.uberfire.ext.wires.core.grids.client.widget.layer.GridLayer;

/**
 * A DOMElement Factory for multi-instance TextBoxes.
 */
public class TextBoxDOMElementFactory extends BaseDOMElementFactory<String, TextBox, TextBoxDOMElement> {

    public TextBoxDOMElementFactory( final GridLayer gridLayer,
                                     final GridWidget gridWidget ) {
        super( gridLayer,
               gridWidget );
    }

    @Override
    public TextBox createWidget() {
        return new TextBox();
    }

    @Override
    public TextBoxDOMElement createDomElement( final GridLayer gridLayer,
                                               final GridWidget gridWidget,
                                               final GridBodyCellRenderContext context ) {
        final TextBox widget = createWidget();
        final TextBoxDOMElement e = new TextBoxDOMElement( widget,
                                                           gridLayer,
                                                           gridWidget );
        widget.addBlurHandler( new BlurHandler() {
            @Override
            public void onBlur( final BlurEvent event ) {
                e.flush( widget.getValue() );
                gridLayer.batch();
            }
        } );
        return e;
    }

}


text:
<!DOCTYPE html>
<meta charset="utf-8">
<title>crash when closing a MessagePort with messages queued for dispatch</title>
<script src="../../../resources/testharness.js"></script>
<script src="../../../resources/testharnessreport.js"></script>
<body>
</body>
<script>
var resolve_done;
let done_promise = new Promise(resolve => resolve_done = resolve);

function done() {
  document.querySelector('iframe').remove();
  resolve_done();
}

// This test creates an iframe with a SharedWorker that does multiple
// postMessages back to the iframe. Once a message is received, the
// iframe is removed. The test passes if it does not crash
// https://crbug.com/649616.
promise_test(t => {
  const frame = document.createElement('iframe');
  frame.src = 'resources/close-context-messageport-crash-iframe.html';
  document.body.appendChild(frame);
  return done_promise;
}, 'closing a MessagePort with messages queued for dispatch should not crash');
</script>


text:
package com.scaleunlimited.wikiwords.tools;

import java.io.BufferedReader;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.Option;

import com.scaleunlimited.wikiwords.Category;
import com.scaleunlimited.wikiwords.CategoryGraph;

public class CategoryGraphTool {
    private static final Logger LOGGER = Logger.getLogger(CategoryGraphTool.class);

    public CategoryGraphTool() {
    }

    public void run(CategoryGraphOptions options) throws IOException {

        // We'll get lines of text with the following format:
        //
        //  <category name> <tab> <parent category> | <parent category> ...
        //
        // Category names are in the xxx_yyy format (Nevada_County).
        //
        // There are 0...n parent categories. There can also be cyclic loops
        // in the resulting graph, which we break at arbitrary locations.

        Map<Category, String> categoriesWithParents = new HashMap<>();
        CategoryGraph graph = new CategoryGraph();

        File inputFile = new File(options.getInputFilename());
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile), "UTF-8"))) {

            String line;
            while ((line = reader.readLine()) != null) {
                String[] pieces = line.split("\t");
                if (pieces.length == 1) {
                    graph.add(new Category(pieces[0]));
                } else if (pieces.length == 2) {
                    Category category = new Category(pieces[0]);
                    graph.add(category);

                    if (categoriesWithParents.put(category, pieces[1]) != null) {
                        LOGGER.error("Multiple entries for category " + pieces[0]);
                    }
                } else {
                    LOGGER.error("Invalid category line: " + line);
                    continue;
                }
            }
        }

        LOGGER.info("Number of categories: " + graph.size());

        // Now we have to run over the categories with parents, and update those categories
        // now that we've created the parent category objects and added them to the graph.
        LOGGER.info("Linking parents...");

        Category c = new Category();
        for (Category category : categoriesWithParents.keySet()) {
            String parentNames = categoriesWithParents.get(category);
            Set<Category> parents = new HashSet<>();
            for (String parentName : parentNames.split("\\|")) {
                c.setName(parentName);

                Category parent = graph.getCategory(c);
                if (parent == null) {
                    // We have a category that has a parent category that doesn't exist,
                    // so go add it.
                    parent = new Category(parentName);
                    graph.add(parent);
                }

                parents.add(parent);
            }

            category.setParents(parents);
        }

        // See if we have cycles.
        LOGGER.info("Checking for cycles...");
        if (graph.hasCycles()) {
            LOGGER.info("Breaking cycles...");
            int numBroken = graph.breakCycles();
            LOGGER.info(String.format("Broke %d cycles", numBroken));
        }

        File outputFile = new File(options.getOutputFilename());
        File outputDir = outputFile.getParentFile();
        outputDir.mkdirs();
        FileOutputStream fos = new FileOutputStream(outputFile);
        DataOutput out = new DataOutputStream(fos);
        graph.write(out);
        fos.close();

        FileUtils.sizeOf(outputFile);
        LOGGER.info(String.format(  "Wrote category map (size = %s) to %s",
                                    FileUtils.byteCountToDisplaySize(FileUtils.sizeOf(outputFile)),
                                    outputFile));
    }

    public static void main(String[] args) {
        CategoryGraphOptions options = new CategoryGraphOptions();
        CmdLineParser parser = new CmdLineParser(options);

        try {
            parser.parseArgument(args);
        } catch (CmdLineException e) {
            System.err.println(e.getMessage());
            printUsageAndExit(parser);
        }

        CategoryGraphTool tool = new CategoryGraphTool();

        try {
            tool.run(options);
        } catch (IllegalArgumentException e) {
            System.err.println(e.getMessage());
            printUsageAndExit(parser);
        } catch (Throwable t) {
            System.err.println("Exception running tool: " + t.getMessage());
            t.printStackTrace(System.err);
            System.exit(-1);
        }
    }

    private static void printUsageAndExit(CmdLineParser parser) {
        parser.printUsage(System.err);
        System.exit(-1);
    }

    public static class CategoryGraphOptions {
        private String _inputFilename;
        private String _outputFilename;

        @Option(name = "-inputfile", usage = "path to categories data file generated by WikiDumpTool", required = true)
        public void setInputFilename(String inputFilename) {
            _inputFilename = inputFilename;
        }

        public String getInputFilename() {
            return _inputFilename;
        }

        @Option(name = "-outputfile", usage = "path to file for generated graph", required = true)
        public void setOutputFilename(String outputFilename) {
            _outputFilename = outputFilename;
        }

        public String getOutputFilename() {
            return _outputFilename;
        }

    }

}


text:
#if !defined(XERCESATTRIBUTEBRIDGEALLOCATOR_INCLUDE_GUARD_12455133)
#define XERCESATTRIBUTEBRIDGEALLOCATOR_INCLUDE_GUARD_12455133

#include <xalanc/XercesParserLiaison/XercesParserLiaisonDefinitions.hpp>

#include <xalanc/PlatformSupport/ArenaAllocator.hpp>

#include <xalanc/XercesParserLiaison/Deprecated/XercesAttrBridge.hpp>

XALAN_CPP_NAMESPACE_BEGIN

/**
 * This class is deprecated.
 *
 * @deprecated This class is part of the deprecated Xerces DOM bridge.
 */
class XALAN_XERCESPARSERLIAISON_EXPORT XercesAttributeBridgeAllocator
{
public:

    typedef XercesAttrBridge                        ObjectType;

#if defined(XALAN_NO_DEFAULT_TEMPLATE_ARGUMENTS)
    typedef ArenaBlock<ObjectType>                  ArenaBlockType;

    typedef ArenaAllocator<ObjectType,
                           ArenaBlockType>          ArenaAllocatorType;
#else
    typedef ArenaAllocator<ObjectType>              ArenaAllocatorType;
#endif

    typedef ArenaAllocatorType::size_type           size_type;

    /**
     * Construct an instance that will allocate blocks of the specified size.
     *
     * @param theBlockSize The block size.
     */
    XercesAttributeBridgeAllocator(size_type    theBlockCount);

    ~XercesAttributeBridgeAllocator();

    /**
     * Create a XercesAttrBridge instance.
     *
     * @param theXercesAttr The Xerces attribute node
     * @param theNavigator The navigator for this instance.
     *
     * @return pointer to the instance
     */
    ObjectType*
    create(
            const DOM_AttrType&             theXercesAttr,
            const XercesBridgeNavigator&    theNavigator);

    /**
     * Delete all objects from allocator.
     */
    void
    reset();

    /**
     * Get size of an ArenaBlock, that is, the number
     * of objects in each block.
     *
     * @return The size of the block
     */
    size_type
    getBlockCount() const
    {
        return m_allocator.getBlockCount();
    }

    /**
     * Get the number of ArenaBlocks currently allocated.
     *
     * @return The number of blocks.
     */
    size_type
    getBlockSize() const
    {
        return m_allocator.getBlockSize();
    }

private:

    // Not implemented...
    XercesAttributeBridgeAllocator(const XercesAttributeBridgeAllocator&);

    XercesAttributeBridgeAllocator&
    operator=(const XercesAttributeBridgeAllocator&);

    // Data members...
    ArenaAllocatorType  m_allocator;
};

XALAN_CPP_NAMESPACE_END

#endif  // XERCESATTRIBUTEBRIDGEALLOCATOR_INCLUDE_GUARD_12455133


text:
package coursier.error

// should be effectively sealed (only ResolutionError and FetchError as direct implementations)
abstract class CoursierError(message: String, cause: Throwable = null)
    extends Exception(message, cause)


text:
package connection;

import java.io.IOException;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * Ports connect to other ports and send data between each other. There may only be one port connected to another at a time.
 */
public class Port {
    private String program;
    private int portNumber;
    private String protocol;

    private ConcurrentLinkedQueue<Integer> in;
    private final ConcurrentLinkedQueue<Integer> out;

    private boolean connected;
    private Port remotePort;

    public Port(String program, int portNumber) {
        this.program = program;
        this.portNumber = portNumber;

        out = new ConcurrentLinkedQueue<Integer>();
    }

    public Port(String program, int portNumber, String protocol) {
        this.program = program;
        this.portNumber = portNumber;
        this.protocol = protocol.toUpperCase();

        out = new ConcurrentLinkedQueue<Integer>();
    }

    public synchronized void connect(Port port) throws IOException {
        if (connected || port.isConnected()) {
            throw new IOException("Port is already in use.");
        }

        remotePort = port;
        port.remotePort = port;

        connected = true;
        remotePort.connected = true;

        in = port.getOut();
        remotePort.in = this.out;
    }

    /**
     * Reads data sent from the remote port.
     *
     * @return Returns the first byte in the data queue. <br> Returns -1 if the queue is empty.
     */
    public int read() {
        Integer b = in.poll();
        if (b == null) {
            return -1;
        } else {
            return b;
        }
    }

    /**
     * Sends data to the remote port. Only accepts bytes(0-255). If b is larger than 255, it will take the last 8 bits.
     */
    public void write(int b) {
        out.offer(b % 256);
        // TODO sleep(inverse of connection speed or something)
    }

    public void write(int[] b) {
        for (int i : b) {
            out.offer(i);
        }
    }

    /**
     * Disconnects from the remote port.
     */
    public void disconnect() {
        in.clear(); // clear the history or else any new connection can see your past sent data
        out.clear();

        connected = false;
        remotePort.connected = false;

        in = null;
        remotePort.in = null;

        remotePort.remotePort = null;
        remotePort = null;
    }

    public String getProgram() {
        return program;
    }

    public int getPortNumber() {
        return portNumber;
    }

    public String getProtocol() {
        return protocol;
    }

    public boolean isConnected() {
        return connected;
    }

    public ConcurrentLinkedQueue<Integer> getIn() {
        return in;
    }

    public ConcurrentLinkedQueue<Integer> getOut() {
        return out;
    }

    public Port getRemotePort() {
        return remotePort;
    }

    void setProtocol(String protocol) {
        this.protocol = protocol;
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta content="text/html; charset=UTF-8" http-equiv="Content-Type"/>
    <meta content="no-cache" http-equiv="Pragma"/>
    <meta content="0" http-equiv="Expires"/>
    <meta content="no-cache" http-equiv="Cache-Control"/>
    <link href="/TouchPoint/default/common/touchpoint.css" type="text/css" rel="stylesheet"/>
    <link href="default/images/favicon.ico" rel="shortcut icon"/>
    <link href="js/jquery/jquery.all.css" rel="stylesheet"/>
    <link href="default/common/alerts.css" rel="stylesheet"/>

    <link href="./default/common/colorbox/colorbox.css" rel="stylesheet" media="screen"
          type="text/css"/>
    <link href="./default/common/colorbox/colorbox-custom.css" rel="stylesheet" media="screen"
          type="text/css"/>

    <title>TouchPoint</title>

        Springe zum Inhalt... (mit Enter-Taste)
        Springe zur Navigation... (mit Enter-Taste)

solr

SolrQueryCompletionProxy

QueryCompletionProxy

            2,

            3

                    Home

Aktuelles

                    Hilfe

                    Auskunft

                Suche

.
                        Einfache Suche

.
                        Erweiterte Suche

.
                        Suchhistorie

.
                Merkliste

.

                Meine Daten

. Konto

. Benutzerdaten

. Sucheinstellungen

. Suchdienste

                . Weitere Angebote

	   Benutzernummer XXXXXXXXXXX

      Abmelden

		Suche in Standarddatenbankauswahlliste

                <form id="AdvancedSearchForm" method="get" action="/TouchPoint/search.do">
                    <input type="hidden" name="methodToCall" value="submitButtonCall"/>
                    <input type="hidden" name="CSId"
                           value="414N71S97b9e1cd42e77c5c331e63a568801009f84662ef"/>
                    <input type="hidden" name="methodToCallParameter" value="submitSearch"/>
                    <input type="hidden" name="refine" value="false"/>
                    <input type="hidden" name="tab" value="tab1"/>
                    <input type="hidden" name="View" value="dav"/>

Sucheingabe

                            <fieldset id="search-simple">
                                <input type="hidden" name="searchCategories[0]" value="-1"/>
                                <legend class="hide-content">Sucheingabe</legend>

                                <input type="text" name="searchString[0]" value="" class=""/>

                                <input name="submitButtonCall_submitSearch" type="submit"
                                       value="Suchen" class="dbuttonb" id="submitSearch"/>

                                <input type="submit" name="submitButtonCall_switchSearchPage_2"
                                       value="Erweiterte Suche" id="advancedSearch"
                                       class="linkbutton"/>

                            </fieldset>

Suche eingrenzen

/TouchPoint/statistic.do

accordionname=searchparameter&statisticcontext=searchpage&action=accordion

                                <fieldset id="search-parameter-fieldset">
                                    <legend class="hide-content">Sucheingrenzungen</legend>

                                                <input type="radio" name="linguistic" value="false"
                                                       checked="checked"
                                                       class="radio"/>genaue Suche
                                                <input type="radio" name="linguistic" value="true"
                                                       class="radio"/>auch ähnliche Begriffe finden

                                                Jahr von

                                                <input type="text" name="searchRestrictionValue1[0]"
                                                       size="5" value=""
                                                       id="searchRestrictionValue1_0"/>
                                                <input type="hidden" name="searchRestrictionID[0]"
                                                       value="1"/>

                                                Jahr  bis

                                                <input type="text" name="searchRestrictionValue2[0]"
                                                       size="5" value=""
                                                       id="searchRestrictionValue2_0"/>

                                </fieldset>

Datenbank-Auswahl

/TouchPoint/statistic.do

accordionname=dbselection&statisticcontext=searchpage&action=accordion

                                    <fieldset>
                                        <legend class="hide-content">Datenbanken</legend>

Datenbanken

<input type="submit"
                                                       name="submitButtonCall_selectAllDatabases"
                                                       value="alle" id="selectAllDatabases"
                                                       class="linkbutton"/>

<input type="submit"
                                                       name="submitButtonCall_deselectAllDatabases"
                                                       value="keine" id="deselectAllDatabases"
                                                       class="linkbutton"/>

                                                <input type="checkbox" name="dbSelection[0]"
                                                       value="2" checked="checked" id="DB_2"
                                                       class="selectDatabase"
                                                       title="Deutscher Alpenverein"/>

                                                Deutscher Alpenverein

                                                <input type="hidden" name="dbSelection[1]"
                                                       value=""/>

                                                Alpinbücherei Innsbruck (Suchanfrage neu eingeben)

/TouchPoint/statistic.do

statisticcontext=searchpage&action=openurl&url=https://alpenverein.web-opac.at/index.php?path=search&target=6

                                            Auswahl speichern

                                            <input type="text" name="databaseSelectionName"
                                                   maxlength="25" value="" style="width: 12em;"/>
                                            <input type="submit"
                                                   name="submitButtonCall_saveDatabaseSelection"
                                                   value="Speichern" class="dbutton"/>

                                    </fieldset>

                </form>

            OPAC-Ansicht:

              Klassisch
             |

            Mobil

        Bitte verwenden Sie die Funktion
        Abmelden , um den versehentlichen Zugriff auf Ihre persönlichen Daten zu vermeiden.

            Copyright © 2013. Alle Rechte vorbehalten.


text:
package org.zmpp.zcode

import org.scalatest._
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
import org.zmpp.base.Memory

@RunWith(classOf[JUnitRunner])
class CustomAccentTableSpec extends FlatSpec with Matchers {
  object MockMem extends Memory {
    val Data = Array[Byte](0x03, 0x04, 0x01, 0x04, 0x02, 0x04, 0x03)
    def size = Data.length
    def buffer = Data
    def byteAt(addr: Int) = Data(addr)
    def shortAt(addr: Int) = {
      ((Data(addr) & 0xff) << 8 | (Data(addr + 1) & 0xff))
    }
    def intAt(addr: Int) = throw new UnsupportedOperationException()
    def setByteAt(addr: Int, value: Int) {}
    def setShortAt(addr: Int, value: Int) {}
    def setIntAt(addr: Int, value: Int) {}
    def copyBytesTo(dest: Array[Byte], srcOffest: Int, numBytes: Int) {}
    def copyBytesTo(dstOffset: Int, srcOffest: Int, numBytes: Int) {}
    def copyBytesFrom(src: Array[Byte], srcOffset: Int, destOffset: Int, numBytes: Int) {}
  }

  "CustomAccentTable" should "lookup an accent" in {
    val accentTable = new CustomAccentTable(MockMem, 0)
    accentTable.numWords should be (3)
    accentTable(0) should be (0x401.asInstanceOf[Char])
    accentTable(1) should be (0x402.asInstanceOf[Char])
    accentTable(2) should be (0x403.asInstanceOf[Char])
  }
  it should "return the index of an accent" in {
    val accentTable = new CustomAccentTable(MockMem, 0)
    accentTable.indexOf(0x401.asInstanceOf[Char]) should be (0)
    accentTable.indexOf(0x402.asInstanceOf[Char]) should be (1)
    accentTable.indexOf(0x403.asInstanceOf[Char]) should be (2)
  }
}


text:
(function () {
'use strict';
var module = angular.module('fim.base');
module.factory('settings', function($log, db, $timeout) {

  function resolve(id, value) {
    var list = [];
    if (registry[id].resolve) {
      list.push(registry[id].resolve);
    }
    angular.forEach(resolvers, function (_resolvers, _id) {
      if (_id == id) {
        list = list.concat(_resolvers);
      }
    });
    $timeout(function () {
      angular.forEach(list, function (_resolve) {
        _resolve(value);
      })
    });
  }

  db.settings.addObserver(null, {
    create: function (settings) {
      angular.forEach(settings, function (setting) {
        registry[setting.id] = setting;
        resolve(setting.id, setting.value);
      });
    },
    update: function (settings) {
      angular.forEach(settings, function (setting) {
        angular.extend(registry[setting.id], setting);
        resolve(setting.id, setting.value);
      });
    },
    remove: function (settings) {
      angular.forEach(settings, function (setting) {
        delete registry[setting.id];
      });
    }
  });

  var stored_settings = null;
  var registry        = {};
  var resolvers       = {};
  var initializers    = [];

  db.settings.toArray().then(
    function (settings) {
      stored_settings  = {};
      angular.forEach(settings, function (stored_setting) {
        stored_settings[stored_setting.id] = stored_setting.value;
      });
      db.transaction('rw', db.settings, function () {
        angular.forEach(initializers, function (initializer, index) {
          initialize(initializer);
        });
        initializers = null;
      }).catch(function (e) { console.error(e); });
    }
  ).catch(function (e) { console.error(e); });

  function initialize(setting) {
    if (setting.id in registry) {
      throw new Error('Duplicate initialization of setting '+setting.id);
    }

    /* Validate that the type and value are a match */
    if (setting.type && !(new Object(setting.value) instanceof setting.type)) {
      throw new Error("Setting for "+setting.id+" of wrong type");
    }

    /* Store default settings in local registry */
    registry[setting.id] = setting;
    registry[setting.id].__initialized = true;

    var stored_setting = stored_settings[setting.id];
    if (stored_setting==undefined) {
      db.settings.add({ id: setting.id, value: setting.value, label: setting.label }).catch(function (e) { console.error(e); });
    }
    else {
      registry[setting.id].value = stored_setting;
    }
    if (setting.resolve || resolvers[setting.id]) {
      $timeout(function () {
        resolve(setting.id, stored_setting==undefined ? setting.value : stored_setting);
      });
    }
  }

  return {
    // DEBUG
    __registry: registry,

    /**
     * Returns a setting directly from memory.
     *
     * @param key String
     * @returns Object
     */
    get: function (key) {
      return registry[key] ? registry[key].value : undefined;
    },

    /**
     * All settings have a unique id which is made from several nested namespaces.
     * Namespaces are separated with dots to form unique ids.
     *
     * Settings have a type to protect against unsupported values. Users can use
     * one of these values for type: String, Number, Boolean, Object.
     *
     * A setting of undefined is never supported, use null in that case and Object
     * as type.
     *
     * @param settings Array of { id: String, value: Object, label: String, type: Object, resolve: Function }
     */
    initialize: function (settings) {
      if (stored_settings == null) {
        initializers = initializers.concat(settings);
      }
      else {
        db.transaction('rw', db.settings, function () {
          angular.forEach(settings, function (setting) {
            initialize(setting);
          });
        }).catch(function (e) { console.error(e); });
      }
    },

    /**
     * Update a setting.
     */
    update: function (id, value) {
      console.log('update.setting', { id: id, value: value });
      var setting = registry[id];
      console.log('update.setting-setting', setting);
      if (!setting) {
        throw new Error("Unknown setting "+id);
      }

      /* Validate that the type and value are a match */
      if (setting.type == undefined) {
        console.log('WARNING. Setting type is undefined for "'+id+'"');
      }
      else if (!(new Object(value) instanceof setting.type)) {
        throw new Error("Setting for "+setting.id+" of wrong type");
      }

      if (setting.type != undefined) {
        setting.value = value;
        db.settings.put({
          id:    setting.id,
          value: setting.value,
          label: setting.label
        }).catch(function (e) { console.error(e); });
      }
    },

    /**
     * Accepts an iterator function that iterates over all settings that have a key
     * that (partially) matches the provided setting key.
     *
     * This allows to iterate over all settings for a certain namespace.
     *
     * @param key String (partial) key
     */
    getAll: function (prefix, callback) {
      var settings = [];
      angular.forEach(registry, function (setting, key) {
        if (key.indexOf(prefix) == 0) {
          settings.push(setting);
        }
      });
      console.log('getAll.'+prefix, settings);
      callback(settings);
    },

    /**
     * Option to register a resolve listener for a plugin.
     *
     * @param key String (partial) key
     * @param resolve Function
     * */
    resolve: function (key, resolve, $scope) {
      if (!resolvers[key]) {
        resolvers[key] = [];
      }
      resolvers[key].push(resolve);
      if (registry[key] && registry[key].__initialized) {
        resolve(registry[key].value);
      }
      if ($scope) {
        $scope.$on('$destroy', function () {
          for (var i=0; i<resolvers[key].length; i++) {
            if (resolvers[key][i] == resolve) {
              resolvers[key].splice(i, 1);
            }
          }
        });
      }
    }
  }
});
})();


text:
package org.apache.ignite.cache.hibernate;

import org.apache.ignite.*;
import org.apache.ignite.internal.processors.cache.*;
import org.hibernate.cache.*;
import org.hibernate.cache.spi.*;
import org.jetbrains.annotations.*;

/**
 * Implementation of {@link GeneralDataRegion}. This interface defines common contract for {@link QueryResultsRegion}
 * and {@link TimestampsRegion}.
 */
public class HibernateGeneralDataRegion extends HibernateRegion implements GeneralDataRegion {
    /**
     * @param factory Region factory.
     * @param name Region name.
     * @param ignite Grid.
     * @param cache Region cache.
     */
    public HibernateGeneralDataRegion(HibernateRegionFactory factory, String name,
        Ignite ignite, GridCache<Object, Object> cache) {
        super(factory, name, ignite, cache);
    }

    /** {@inheritDoc} */
    @Nullable @Override public Object get(Object key) throws CacheException {
        try {
            return cache.get(key);
        } catch (IgniteCheckedException e) {
            throw new CacheException(e);
        }
    }

    /** {@inheritDoc} */
    @Override public void put(Object key, Object val) throws CacheException {
        try {
            cache.putx(key, val);
        } catch (IgniteCheckedException e) {
            throw new CacheException(e);
        }
    }

    /** {@inheritDoc} */
    @Override public void evict(Object key) throws CacheException {
        HibernateAccessStrategyAdapter.evict(ignite, cache, key);
    }

    /** {@inheritDoc} */
    @Override public void evictAll() throws CacheException {
        HibernateAccessStrategyAdapter.evictAll(cache);
    }
}