text:
require 'spec_helper'
require 'glimmer/data_binding/observer'
require 'glimmer/data_binding/observable_hash'

describe Glimmer::DataBinding::ObservableHash do
  context 'hash' do
    it 'adds observer based on key' do
      task = {}
      @observer_called = nil
      observer = Glimmer::DataBinding::Observer.proc do |new_value|
        @observer_called = new_value
      end
      observer.observe(task, :name)
      observer.observe(task, :address)
      task[:other] = 'Something'
      expect(@observer_called).to be_nil
      task[:name] = 'Sean'
      expect(@observer_called).to eq('Sean')
      task[:address] = '123 Main St'
      expect(@observer_called).to eq('123 Main St')
    end

    it 'adds observer to all keys' do
      task = {}
      @key_called = nil
      @observer_called = nil
      @called = 0

      o = Glimmer::DataBinding::Observer.proc do |new_value, key|
        @called += 1
        @key_called = key if key
        @observer_called = new_value
      end
      o.observe(task)
      o.observe(task, :address)

      task[:other] = 'Something'
      expect(@key_called).to eq(:other)
      expect(@observer_called).to eq('Something')
      expect(@called).to eq(1)

      task[:name] = 'Sean'
      expect(@key_called).to eq(:name)
      expect(@observer_called).to eq('Sean')
      expect(@called).to eq(2)

      task[:address] = '123 Main St'
      expect(@key_called).to eq(:address)
      expect(@observer_called).to eq('123 Main St')
      expect(@called).to eq(3)
    end

    it 'adds observer to Array key value' do
      task = {}
      task[:name] = 'Sean'
      task[:subtasks] = ['subtask1', 'subtask2']
      @observer_called = nil
      Glimmer::DataBinding::Observer.proc do |new_value|
        @observer_called = new_value
      end.observe(task, :subtasks)
      task[:subtasks] << 'subtask3'
      expect(@observer_called).to eq(['subtask1', 'subtask2', 'subtask3'])
    end

    it 'adds observer to Array of Arrays key value recursively' do
      task = {}
      task[:name] = 'Sean'
      task[:subtasks] = [[['subtask1', 'subtask2']]]
      @observer_called = nil
      observer = Glimmer::DataBinding::Observer.proc do |new_value|
        @observer_called = new_value
      end

      observer.observe(task, :subtasks, recursive: true)
      task[:subtasks][0][0] << 'subtask4'
      expect(@observer_called).to eq([[["subtask1", "subtask2", "subtask4"]]])

      task[:subtasks] = [[["subtask1", "subtask2", "subtask3"]]]
      @observer_called = nil
      task[:subtasks][0][0][0] = 'subtask4'
      expect(@observer_called).to eq([[["subtask4", "subtask2", "subtask3"]]])
    end

    it 'removes observer' do
      task = {}
      observer = Glimmer::DataBinding::Observer.proc do |new_value|
        @observer_called = new_value
      end
      observer.observe(task, :name)
      observer.unobserve(task, :name)
      task[:name] = 'Sean'
      expect(@observer_called).to be_nil
    end

    it 'removes observers for a key' do
      task = {}
      observer = Glimmer::DataBinding::Observer.proc do |new_value|
        @observer_called = new_value
      end
      observer.observe(task, :name)
      task.remove_observers(:name)
      task[:name] = 'Sean'
      expect(@observer_called).to be_nil
    end

    it 'removes all observers for all keys' do
      task = {}
      observer = Glimmer::DataBinding::Observer.proc do |new_value|
        @observer_called = new_value
      end
      observer.observe(task, :name)
      observer.observe(task, :subtasks)
      task.remove_all_observers
      task[:name] = 'Sean'
      task[:subtasks] = ['subtask1', 'subtask2']
      expect(@observer_called).to be_nil
    end

    it 'checks if object has observer for any key' do
      task = {}
      @observer_called = nil
      observer = Glimmer::DataBinding::Observer.proc do |new_value|
        @observer_called = new_value
      end
      observer.observe(task, :name)
      expect(task.has_observer_for_any_key?(observer)).to eq(true)
      observer.unobserve(task, :name)
      expect(task.has_observer_for_any_key?(observer)).to eq(false)
    end
  end

  describe 'hash mutation method' do
    it 'notifies observers when Hash#delete is called and changes key value (i.e. was not nil before)' do
      @fired = false
      @changed_value = nil
      @changed_key = nil
      observer = Glimmer::DataBinding::Observer.proc do |value, key|
        @fired = true
        @changed_value = value
        @changed_key = key
      end
      hash = {name: 'John'}
      hash.singleton_class.include(described_class)
      hash.add_observer(observer, :name)

      hash.delete(:name)
      expect(@fired).to eq(true)
      expect(@changed_value).to eq(nil)
      expect(@changed_key).to eq(:name)

      @fired = false
      @changed_value = nil
      @changed_key = nil
      hash.remove_observer(observer, :name)
      hash[:name] = 'John'
      hash.add_observer(observer) # observe all keys

      hash.delete(:name)
      expect(@fired).to eq(true)
      expect(@changed_value).to eq(nil)
      expect(@changed_key).to eq(:name)
    end

    it 'does not notify observers when Hash#delete is called and previous key value was nil' do
      @fired = false
      @changed_value = nil
      @changed_key = nil
      observer = Glimmer::DataBinding::Observer.proc do |value, key|
        @fired = true
        @changed_value = value
        @changed_key = key
      end
      hash = {name: nil}
      hash.singleton_class.include(described_class)
      hash.add_observer(observer, :name)

      hash.delete(:name)
      expect(@fired).to eq(false)
      expect(@changed_value).to eq(nil)
      expect(@changed_key).to eq(nil)

      @fired = false
      @changed_value = nil
      @changed_key = nil
      hash.remove_observer(observer, :name)
      hash[:name] = nil
      hash.add_observer(observer) # observe all keys

      hash.delete(:name)
      expect(@fired).to eq(false)
      expect(@changed_value).to eq(nil)
      expect(@changed_key).to eq(nil)
    end

    it 'notifies observers when Hash#delete_if is called and changes key value (i.e. was not nil before)' do
      @fired = false
      @changed_value = nil
      @changed_key = nil
      observer = Glimmer::DataBinding::Observer.proc do |value, key|
        @fired = true
        @changed_value = value
        @changed_key = key
      end
      hash = {name: 'John'}
      hash.singleton_class.include(described_class)
      hash.add_observer(observer, :name)

      hash.delete_if { |k,v| k == :name }
      expect(@fired).to eq(true)
      expect(@changed_value).to eq(nil)
      expect(@changed_key).to eq(:name)

      @fired = false
      @changed_value = nil
      @changed_key = nil
      hash.remove_observer(observer, :name)
      hash[:name] = 'John'
      hash.add_observer(observer) # observe all keys

      hash.delete_if { |k,v| k == :name }
      expect(@fired).to eq(true)
      expect(@changed_value).to eq(nil)
      expect(@changed_key).to eq(:name)
    end

    it 'does not notify observers when Hash#delete_if is called and previous key value was nil' do
      @fired = false
      @changed_value = nil
      @changed_key = nil
      observer = Glimmer::DataBinding::Observer.proc do |value, key|
        @fired = true
        @changed_value = value
        @changed_key = key
      end
      hash = {name: nil}
      hash.singleton_class.include(described_class)
      hash.add_observer(observer, :name)

      hash.delete_if { |k,v| k == :name }
      expect(@fired).to eq(false)
      expect(@changed_value).to eq(nil)
      expect(@changed_key).to eq(nil)

      @fired = false
      @changed_value = nil
      @changed_key = nil
      hash.remove_observer(observer, :name)
      hash[:name] = nil
      hash.add_observer(observer) # observe all keys

      hash.delete_if { |k,v| k == :name }
      expect(@fired).to eq(false)
      expect(@changed_value).to eq(nil)
      expect(@changed_key).to eq(nil)
    end

    it 'notifies observers when Hash#select! is called and changes key value (i.e. was not nil before)' do
      @fired = false
      @changed_value = nil
      @changed_key = nil
      observer = Glimmer::DataBinding::Observer.proc do |value, key|
        @fired = true
        @changed_value = value
        @changed_key = key
      end
      hash = {name: 'John', address: '123 Main St, St Antonio, Texas, USA'}
      hash.singleton_class.include(described_class)
      hash.add_observer(observer, :name)

      hash.select! { |k,v| k != :name }
      expect(@fired).to eq(true)
      expect(@changed_value).to eq(nil)
      expect(@changed_key).to eq(:name)

      @fired = false
      @changed_value = nil
      @changed_key = nil
      hash.remove_observer(observer, :name)
      hash[:name] = 'John'
      hash.add_observer(observer) # observe all keys

      hash.select! { |k,v| k != :name }
      expect(@fired).to eq(true)
      expect(@changed_value).to eq(nil)
      expect(@changed_key).to eq(:name)
    end

    it 'does not notify observers when Hash#select! is called and previous key value was nil' do
      @fired = false
      @changed_value = nil
      @changed_key = nil
      observer = Glimmer::DataBinding::Observer.proc do |value, key|
        @fired = true
        @changed_value = value
        @changed_key = key
      end
      hash = {name: nil, address: '123 Main St, St Antonio, Texas, USA'}
      hash.singleton_class.include(described_class)
      hash.add_observer(observer, :name)

      hash.select! { |k,v| k != :name }
      expect(@fired).to eq(false)
      expect(@changed_value).to eq(nil)
      expect(@changed_key).to eq(nil)

      @fired = false
      @changed_value = nil
      @changed_key = nil
      hash.remove_observer(observer, :name)
      hash[:name] = nil
      hash.add_observer(observer) # observe all keys

      hash.select! { |k,v| k != :name }
      expect(@fired).to eq(false)
      expect(@changed_value).to eq(nil)
      expect(@changed_key).to eq(nil)
    end

    it 'notifies observers when Hash#filter! is called and changes key value (i.e. was not nil before)' do
      @fired = false
      @changed_value = nil
      @changed_key = nil
      observer = Glimmer::DataBinding::Observer.proc do |value, key|
        @fired = true
        @changed_value = value
        @changed_key = key
      end
      hash = {name: 'John', address: '123 Main St, St Antonio, Texas, USA'}
      hash.singleton_class.include(described_class)
      hash.add_observer(observer, :name)

      hash.filter! { |k,v| k != :name }
      expect(@fired).to eq(true)
      expect(@changed_value).to eq(nil)
      expect(@changed_key).to eq(:name)

      @fired = false
      @changed_value = nil
      @changed_key = nil
      hash.remove_observer(observer, :name)
      hash[:name] = 'John'
      hash.add_observer(observer) # observe all keys

      hash.filter! { |k,v| k != :name }
      expect(@fired).to eq(true)
      expect(@changed_value).to eq(nil)
      expect(@changed_key).to eq(:name)
    end

    it 'does not notify observers when Hash#filter! is called and previous key value was nil' do
      @fired = false
      @changed_value = nil
      @changed_key = nil
      observer = Glimmer::DataBinding::Observer.proc do |value, key|
        @fired = true
        @changed_value = value
        @changed_key = key
      end
      hash = {name: nil, address: '123 Main St, St Antonio, Texas, USA'}
      hash.singleton_class.include(described_class)
      hash.add_observer(observer, :name)

      hash.filter! { |k,v| k != :name }
      expect(@fired).to eq(false)
      expect(@changed_value).to eq(nil)
      expect(@changed_key).to eq(nil)

      @fired = false
      @changed_value = nil
      @changed_key = nil
      hash.remove_observer(observer, :name)
      hash[:name] = nil
      hash.add_observer(observer) # observe all keys

      hash.filter! { |k,v| k != :name }
      expect(@fired).to eq(false)
      expect(@changed_value).to eq(nil)
      expect(@changed_key).to eq(nil)
    end

    it 'notifies observers when Hash#keep_if is called and changes key value (i.e. was not nil before)' do
      @fired = false
      @changed_value = nil
      @changed_key = nil
      observer = Glimmer::DataBinding::Observer.proc do |value, key|
        @fired = true
        @changed_value = value
        @changed_key = key
      end
      hash = {name: 'John', address: '123 Main St, St Antonio, Texas, USA'}
      hash.singleton_class.include(described_class)
      hash.add_observer(observer, :name)

      hash.keep_if { |k,v| k != :name }
      expect(@fired).to eq(true)
      expect(@changed_value).to eq(nil)
      expect(@changed_key).to eq(:name)

      @fired = false
      @changed_value = nil
      @changed_key = nil
      hash.remove_observer(observer, :name)
      hash[:name] = 'John'
      hash.add_observer(observer) # observe all keys

      hash.keep_if { |k,v| k != :name }
      expect(@fired).to eq(true)
      expect(@changed_value).to eq(nil)
      expect(@changed_key).to eq(:name)
    end

    it 'does not notify observers when Hash#keep_if is called and previous key value was nil' do
      @fired = false
      @changed_value = nil
      @changed_key = nil
      observer = Glimmer::DataBinding::Observer.proc do |value, key|
        @fired = true
        @changed_value = value
        @changed_key = key
      end
      hash = {name: nil, address: '123 Main St, St Antonio, Texas, USA'}
      hash.singleton_class.include(described_class)
      hash.add_observer(observer, :name)

      hash.keep_if { |k,v| k != :name }
      expect(@fired).to eq(false)
      expect(@changed_value).to eq(nil)
      expect(@changed_key).to eq(nil)

      @fired = false
      @changed_value = nil
      @changed_key = nil
      hash.remove_observer(observer, :name)
      hash[:name] = nil
      hash.add_observer(observer) # observe all keys

      hash.keep_if { |k,v| k != :name }
      expect(@fired).to eq(false)
      expect(@changed_value).to eq(nil)
      expect(@changed_key).to eq(nil)
    end

    it 'notifies observers when Hash#reject! is called and changes key value (i.e. was not nil before)' do
      @fired = false
      @changed_value = nil
      @changed_key = nil
      observer = Glimmer::DataBinding::Observer.proc do |value, key|
        @fired = true
        @changed_value = value
        @changed_key = key
      end
      hash = {name: 'John', address: '123 Main St, St Antonio, Texas, USA'}
      hash.singleton_class.include(described_class)
      hash.add_observer(observer, :name)

      hash.reject! { |k,v| k == :name }
      expect(@fired).to eq(true)
      expect(@changed_value).to eq(nil)
      expect(@changed_key).to eq(:name)

      @fired = false
      @changed_value = nil
      @changed_key = nil
      hash.remove_observer(observer, :name)
      hash[:name] = 'John'
      hash.add_observer(observer) # observe all keys

      hash.reject! { |k,v| k == :name }
      expect(@fired).to eq(true)
      expect(@changed_value).to eq(nil)
      expect(@changed_key).to eq(:name)
    end

    it 'does not notify observers when Hash#reject! is called and previous key value was nil' do
      @fired = false
      @changed_value = nil
      @changed_key = nil
      observer = Glimmer::DataBinding::Observer.proc do |value, key|
        @fired = true
        @changed_value = value
        @changed_key = key
      end
      hash = {name: nil, address: '123 Main St, St Antonio, Texas, USA'}
      hash.singleton_class.include(described_class)
      hash.add_observer(observer, :name)

      hash.reject! { |k,v| k == :name }
      expect(@fired).to eq(false)
      expect(@changed_value).to eq(nil)
      expect(@changed_key).to eq(nil)

      @fired = false
      @changed_value = nil
      @changed_key = nil
      hash.remove_observer(observer, :name)
      hash[:name] = nil
      hash.add_observer(observer) # observe all keys

      hash.reject! { |k,v| k == :name }
      expect(@fired).to eq(false)
      expect(@changed_value).to eq(nil)
      expect(@changed_key).to eq(nil)
    end

    it 'notifies observers when Hash#shift is called and changes key value (i.e. was not nil before)' do
      @fired = false
      @changed_value = nil
      @changed_key = nil
      observer = Glimmer::DataBinding::Observer.proc do |value, key|
        @fired = true
        @changed_value = value
        @changed_key = key
      end
      hash = {name: 'John', address: '123 Main St, St Antonio, Texas, USA'}
      hash.singleton_class.include(described_class)
      hash.add_observer(observer, :name)
      hash.add_observer(observer, :address)

      hash.shift
      expect(@fired).to eq(true)
      expect(@changed_value).to eq(nil)
      expect(@changed_key).to eq(:name)

      @fired = false
      @changed_value = nil
      @changed_key = nil
      hash.remove_observer(observer, :name)
      hash.remove_observer(observer, :address)
      hash.add_observer(observer) # observe all keys

      hash.shift
      expect(@fired).to eq(true)
      expect(@changed_value).to eq(nil)
      expect(@changed_key).to eq(:address)
    end

    it 'does not notify observers when Hash#shift is called and previous key value was nil' do
      @fired = false
      @changed_value = nil
      @changed_key = nil
      observer = Glimmer::DataBinding::Observer.proc do |value, key|
        @fired = true
        @changed_value = value
        @changed_key = key
      end
      hash = {name: nil, address: nil}
      hash.singleton_class.include(described_class)
      hash.add_observer(observer, :name)
      hash.add_observer(observer, :address)

      hash.shift
      expect(@fired).to eq(false)
      expect(@changed_value).to eq(nil)
      expect(@changed_key).to eq(nil)

      @fired = false
      @changed_value = nil
      @changed_key = nil
      hash.remove_observer(observer, :name)
      hash.remove_observer(observer, :address)
      hash.add_observer(observer) # observe all keys

      hash.shift
      expect(@fired).to eq(false)
      expect(@changed_value).to eq(nil)
      expect(@changed_key).to eq(nil)
    end

    it 'notifies observers when Hash#merge! is called and changes key value' do
      @fired = false
      @changed_value = nil
      @changed_key = nil
      observer = Glimmer::DataBinding::Observer.proc do |value, key|
        @fired = true
        @changed_value = value
        @changed_key = key
      end
      hash = {}
      hash.singleton_class.include(described_class)
      hash.add_observer(observer, :name)

      hash.merge!(name: 'John')
      expect(@fired).to eq(true)
      expect(@changed_value).to eq('John')
      expect(@changed_key).to eq(:name)

      @fired = false
      @changed_value = nil
      @changed_key = nil
      hash.remove_observer(observer, :name)
      hash = {name: 'John'}
      hash.singleton_class.include(described_class)
      hash.add_observer(observer, :name)

      hash.merge!(name: 'Bob')
      expect(@fired).to eq(true)
      expect(@changed_value).to eq('Bob')
      expect(@changed_key).to eq(:name)

      @fired = false
      @changed_value = nil
      @changed_key = nil
      hash.remove_observer(observer, :name)
      hash = {name: 'John'}
      hash.singleton_class.include(described_class)
      hash.add_observer(observer, :name)

      hash.merge!({name: 'Jon'}, {name: 'Bob'})
      expect(@fired).to eq(true)
      expect(@changed_value).to eq('Bob')
      expect(@changed_key).to eq(:name)

      @fired = false
      @changed_value = nil
      @changed_key = nil
      hash.remove_observer(observer, :name)
      hash = {name: 'John'}
      hash.singleton_class.include(described_class)
      hash.add_observer(observer, :name)

      hash.merge!({name: 'Sid'}) {|key, old_value, new_value| 'Bob' if new_value == 'Sid'}
      expect(@fired).to eq(true)
      expect(@changed_value).to eq('Bob')
      expect(@changed_key).to eq(:name)

      @fired = false
      @changed_value = nil
      @changed_key = nil
      hash.remove_observer(observer, :name)
      hash[:name] = 'John'
      hash.add_observer(observer) # observe all keys

      hash.merge!(name: 'Bob')
      expect(@fired).to eq(true)
      expect(@changed_value).to eq('Bob')
      expect(@changed_key).to eq(:name)
    end

    it 'does not notify observers when Hash#merge! is called and previous key value remains the same' do
      @fired = false
      @changed_value = nil
      @changed_key = nil
      observer = Glimmer::DataBinding::Observer.proc do |value, key|
        @fired = true
        @changed_value = value
        @changed_key = key
      end
      hash = {name: 'John'}
      hash.singleton_class.include(described_class)
      hash.add_observer(observer, :name)

      hash.merge!(name: 'John')
      expect(@fired).to eq(false)
      expect(@changed_value).to eq(nil)
      expect(@changed_key).to eq(nil)

      @fired = false
      @changed_value = nil
      @changed_key = nil
      hash.remove_observer(observer, :name)
      hash[:name] = 'John'
      hash.add_observer(observer) # observe all keys

      hash.merge!(name: 'John')
      expect(@fired).to eq(false)
      expect(@changed_value).to eq(nil)
      expect(@changed_key).to eq(nil)
    end

    it 'notifies observers when Hash#replace is called and changes key value' do
      @fired = false
      @changed_values = []
      @changed_keys = []
      observer = Glimmer::DataBinding::Observer.proc do |value, key|
        @fired = true
        @changed_values << value
        @changed_keys << key
      end
      hash = {address: 'Los Angeles, California, USA'}
      hash.singleton_class.include(described_class)
      hash.add_observer(observer, :name)
      hash.add_observer(observer, :address)

      hash.replace(name: 'John')
      expect(@fired).to eq(true)
      expect(@changed_values).to eq([nil, 'John'])
      expect(@changed_keys).to eq([:address, :name])

      @fired = false
      @changed_values = []
      @changed_keys = []
      hash.remove_observer(observer, :name)
      hash.remove_observer(observer, :address)
      hash.delete(:name)
      hash[:address] = 'Los Angeles, California, USA'
      hash.add_observer(observer) # observe all keys

      hash.replace(name: 'John')
      expect(@fired).to eq(true)
      expect(@changed_values).to eq([nil, 'John'])
      expect(@changed_keys).to eq([:address, :name])
    end

    it 'does not notify observers when Hash#replace is called and previous key value remains the same' do
      @fired = false
      @changed_value = nil
      @changed_key = nil
      observer = Glimmer::DataBinding::Observer.proc do |value, key|
        @fired = true
        @changed_value = value
        @changed_key = key
      end
      hash = {name: 'John'}
      hash.singleton_class.include(described_class)
      hash.add_observer(observer, :name)

      hash.replace(name: 'John')
      expect(@fired).to eq(false)
      expect(@changed_value).to eq(nil)
      expect(@changed_key).to eq(nil)

      @fired = false
      @changed_value = nil
      @changed_key = nil
      hash.remove_observer(observer, :name)
      hash[:name] = 'John'
      hash.add_observer(observer) # observe all keys

      hash.replace(name: 'John')
      expect(@fired).to eq(false)
      expect(@changed_value).to eq(nil)
      expect(@changed_key).to eq(nil)
    end

    it 'notifies observers when Hash#transform_keys! is called and changes key value' do
      @fired = false
      @changed_values = []
      @changed_keys = []
      observer = Glimmer::DataBinding::Observer.proc do |value, key|
        @fired = true
        @changed_values << value
        @changed_keys << key
      end
      hash = {address: 'Los Angeles, California, USA'}
      hash.singleton_class.include(described_class)
      hash.add_observer(observer, :location)
      hash.add_observer(observer, :address)

      hash.transform_keys! { |key| :location }
      expect(@fired).to eq(true)
      expect(@changed_values).to eq([nil, 'Los Angeles, California, USA'])
      expect(@changed_keys).to eq([:address, :location])

      @fired = false
      @changed_values = []
      @changed_keys = []
      hash.remove_observer(observer, :location)
      hash.remove_observer(observer, :address)
      hash.delete(:location)
      hash[:address] = 'Los Angeles, California, USA'
      hash.add_observer(observer) # observe all keys

      hash.transform_keys! { |key| :location }
      expect(@fired).to eq(true)
      expect(@changed_values).to eq([nil, 'Los Angeles, California, USA'])
      expect(@changed_keys).to eq([:address, :location])
    end

    it 'does not notify observers when Hash#transform_keys! is called and previous key value remains the same' do
      @fired = false
      @changed_value = nil
      @changed_key = nil
      observer = Glimmer::DataBinding::Observer.proc do |value, key|
        @fired = true
        @changed_value = value
        @changed_key = key
      end
      hash = {name: 'John'}
      hash.singleton_class.include(described_class)
      hash.add_observer(observer, :name)

      hash.transform_keys! {|key| :name}
      expect(@fired).to eq(false)
      expect(@changed_value).to eq(nil)
      expect(@changed_key).to eq(nil)

      @fired = false
      @changed_value = nil
      @changed_key = nil
      hash.remove_observer(observer, :name)
      hash.add_observer(observer) # observe all keys

      hash.transform_keys! {|key| :name}
      expect(@fired).to eq(false)
      expect(@changed_value).to eq(nil)
      expect(@changed_key).to eq(nil)
    end

    it 'notifies observers when Hash#transform_values! is called and changes key value' do
      @fired = false
      @changed_value = nil
      @changed_key = nil
      observer = Glimmer::DataBinding::Observer.proc do |value, key|
        @fired = true
        @changed_value = value
        @changed_key = key
      end
      hash = {address: 'Los Angeles, California, USA'}
      hash.singleton_class.include(described_class)
      hash.add_observer(observer, :address)

      hash.transform_values! { |key| 'New York, New York, USA' }
      expect(@fired).to eq(true)
      expect(@changed_value).to eq('New York, New York, USA')
      expect(@changed_key).to eq(:address)

      @fired = false
      @changed_value = nil
      @changed_key = nil
      hash.remove_observer(observer, :address)
      hash[:address] = 'Los Angeles, California, USA'
      hash.add_observer(observer) # observe all keys

      hash.transform_values! { |key| 'New York, New York, USA' }
      expect(@fired).to eq(true)
      expect(@changed_value).to eq('New York, New York, USA')
      expect(@changed_key).to eq(:address)
    end

    it 'does not notify observers when Hash#transform_values! is called and previous key value remains the same' do
      @fired = false
      @changed_value = nil
      @changed_key = nil
      observer = Glimmer::DataBinding::Observer.proc do |value, key|
        @fired = true
        @changed_value = value
        @changed_key = key
      end
      hash = {name: 'John'}
      hash.singleton_class.include(described_class)
      hash.add_observer(observer, :name)

      hash.transform_values! {|key| 'John'}
      expect(@fired).to eq(false)
      expect(@changed_value).to eq(nil)
      expect(@changed_key).to eq(nil)

      @fired = false
      @changed_value = nil
      @changed_key = nil
      hash.remove_observer(observer, :name)
      hash.add_observer(observer) # observe all keys

      hash.transform_values! {|key| 'John'}
      expect(@fired).to eq(false)
      expect(@changed_value).to eq(nil)
      expect(@changed_key).to eq(nil)
    end
  end
end


text:
<?php
include_once '../../dbconfig.php';

$id = $_POST['food_id'];
$query = "SELECT * FROM foods WHERE food_id= $id";
$query2 = "DELETE FROM foods WHERE food_id= $id";
$result = mysqli_query($connect, $query);
$row = mysqli_fetch_array($result);
unlink("../../" . $row["image"]);

if ($connect->query($query2) === TRUE)
    echo "success";
else
    echo "Error: " . $query . "<br>" . $connect->error;

$connect->close();

redpajama_set_name: RedPajamaGithub


text:
$version     = '8.6.3'
$packageName = 'ghc'
$url         = 'https://downloads.haskell.org/~ghc/8.6.3/ghc-8.6.3-i386-unknown-mingw32.tar.xz'
$url64       = 'https://downloads.haskell.org/~ghc/8.6.3/ghc-8.6.3-x86_64-unknown-mingw32.tar.xz'

$binRoot         = $(Split-Path -parent $MyInvocation.MyCommand.Definition)
$packageFullName = Join-Path $binRoot ($packageName + '-' + $version)
$binPackageDir   = Join-Path $packageFullName "bin"

$tmpPath = Join-Path $env:chocolateyPackageFolder tmp
$tarFile = $packageName + "Install"
$tarPath = Join-Path $tmpPath $tarFile
$tmpFile = Join-Path $binRoot ($tarFile + "~")

Get-ChocolateyWebFile -PackageName $packageName -FileFullPath $tarPath `
    -Url $url -ChecksumType sha256 -Checksum 6d221bde8e1864dab0ac121b11bae486bbbeea161b0a2591d22c4c3e322b3590 `
    -Url64bit $url64 -ChecksumType64 sha256 -Checksum64 2fec383904e5fa79413e9afd328faf9bc700006c8c3d4bcdd8d4f2ccf0f7fa2a
Get-ChocolateyUnzip -fileFullPath $tarPath -destination $binRoot
Get-ChocolateyUnzip -fileFullPath $tmpFile -destination $binRoot
rm $tmpFile # Clean up temporary file

Install-ChocolateyPath "$binPackageDir"

Write-Host "Hiding shims for `'$binRoot`'."
$files = get-childitem $binRoot -include *.exe -recurse

foreach ($file in $files) {
    #generate an ignore file
    New-Item "$file.ignore" -type file -force | Out-Null
}


text:
package ui.components.pickers;

import util.Utility;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * This class handles the state and logic of the MilestonePickerDialog,
 * which determine the result of the user's input
 */
public class MilestonePickerState {
    public static final int BEST_MATCHING_LIMIT = 5;
    private final List<PickerMilestone> allMilestones;
    private final List<PickerMilestone> bestMatchingMilestones;

    public MilestonePickerState(List<PickerMilestone> milestones, String userQuery) {
        allMilestones = cloneList(milestones);
        bestMatchingMilestones = new ArrayList<>();
        processQuery(userQuery);
    }

    public MilestonePickerState(List<PickerMilestone> milestones) {
        this(milestones, "");
    }

    private List<PickerMilestone> cloneList(List<PickerMilestone> sourceList) {
        return sourceList.stream()
                .map(PickerMilestone::new)
                .collect(Collectors.toList());
    }

    private void processQuery(String querySentence) {
        processMatchingMilestonesByQuerySentence(allMilestones, querySentence);
        populateBestMatchingMilestones(querySentence);
        if (querySentence.isEmpty()) return;
        toggleFirstMilestone(bestMatchingMilestones);
    }

    private void processMatchingMilestonesByQuerySentence(List<PickerMilestone> milestones, String querySentence) {
        String[] queryWords = querySentence.split(" ");
        Stream.of(queryWords)
                .forEach(queryWord -> processMatchingMilestonesByQueryWord(milestones, queryWord));
    }

    private void processMatchingMilestonesByQueryWord(List<PickerMilestone> milestones, String queryWord) {
        milestones.stream()
                .forEach(milestone -> {
                    if (milestone.isMatching()) milestone.setMatching(isMatchingQuery(milestone, queryWord));
                });
    }

    /**
     * Selects the next milestone in the list of best matching milestones
     */
    public void selectNextBestMatchingMilestone() {
        Optional<Integer> curSelectedIndex = getSelectedIndex(bestMatchingMilestones);
        if (!canIncreaseIndex(curSelectedIndex, bestMatchingMilestones)) return;
        selectMilestoneAtIndex(bestMatchingMilestones, curSelectedIndex.get() + 1);
    }

    /**
     * Selects the previous milestone in the list of best matching milestones
     */
    public void selectPreviousBestMatchingMilestone() {
        Optional<Integer> curSelectedIndex = getSelectedIndex(bestMatchingMilestones);
        if (!canDecreaseIndex(curSelectedIndex)) return;
        selectMilestoneAtIndex(bestMatchingMilestones, curSelectedIndex.get() - 1);
    }

    private boolean canIncreaseIndex(Optional<Integer> curSelectedIndex, List<PickerMilestone> list) {
        return curSelectedIndex.isPresent() && curSelectedIndex.get() < list.size() - 1;
    }

    private boolean canDecreaseIndex(Optional<Integer> curSelectedIndex) {
        return curSelectedIndex.isPresent() && curSelectedIndex.get() > 0;
    }

    /**
     * Returns the first index at which a milestone is selected
     *
     * @param milestones
     */
    private Optional<Integer> getSelectedIndex(List<PickerMilestone> milestones) {
        for (int i = 0; i < milestones.size(); i++) {
            if (milestones.get(i).isSelected()) {
                return Optional.of(i);
            }
        }
        return Optional.empty();
    }

    /**
     * Selects the milestone at the given index and deselects the rest
     * @param milestones
     * @param index
     */
    private void selectMilestoneAtIndex(List<PickerMilestone> milestones, int index) {
        for (int i = 0; i < milestones.size(); i++) {
            milestones.get(i).setSelected(i == index);
        }
    }

    /**
     * Toggles the selection status of the milestone whose name is exactly milestoneName. This method is
     * case-sensitive
     *
     * @param milestoneName
     */
    public final void toggleExactMatchMilestone(String milestoneName) {
        Optional<PickerMilestone> exactMatchMilestone = getExactMatchMilestone(allMilestones, milestoneName);
        exactMatchMilestone.ifPresent(this::toggleMilestone);
    }

    /**
     * Toggles the selection status of the first milestone in the list
     *
     * @param milestones
     */
    private final void toggleFirstMilestone(List<PickerMilestone> milestones) {
        Optional<PickerMilestone> firstMilestone = milestones.stream()
                                                            .findFirst();
        firstMilestone.ifPresent(this::toggleMilestone);
    }

    /**
     * Changes the selection statuses of all milestones in allMilestones,
     * such that the given milestone is toggled and the rest are not selected
     *
     * @param milestone
     */
    private void toggleMilestone(PickerMilestone milestone) {
        allMilestones.stream()
                .forEach(listMilestone -> listMilestone.setSelected(listMilestone.equals(milestone)
                        && !listMilestone.isSelected()));
    }

    public List<PickerMilestone> getAllMilestones() {
        return allMilestones;
    }

    public List<PickerMilestone> getBestMatchingMilestones() {
        return bestMatchingMilestones;
    }

    /**
     * Populates bestMatchingMilestones with milestones from allMilestones that best match
     * {@code querySentence} and are not already assigned.
     *
     * The added milestones are references to the actual elements in allMilestones, and thus should not be
     * unnecessarily mutated.
     * @param querySentence
     */
    private void populateBestMatchingMilestones(String querySentence) {
        bestMatchingMilestones.clear();
        List<PickerMilestone> selectableMilestones = PickerMilestone.getSelectableMilestones(allMilestones);

        addMatchingMilestones(bestMatchingMilestones, getRemainingBestMatchesToLimit(), selectableMilestones);
        if (isMilestonesSizeBelowLimit(bestMatchingMilestones, BEST_MATCHING_LIMIT)) {
            addPartiallyMatchingMilestones(bestMatchingMilestones, getRemainingBestMatchesToLimit(), querySentence,
                                           selectableMilestones);
        }
        if (isMilestonesSizeBelowLimit(bestMatchingMilestones, BEST_MATCHING_LIMIT)) {
            addLikelyUnmatchedMilestones(bestMatchingMilestones, getRemainingBestMatchesToLimit(),
                                         selectableMilestones);
        }
    }

    private boolean isMilestonesSizeBelowLimit(List<PickerMilestone> milestones, int limit) {
        return milestones.size() < limit;
    }

    private int getRemainingBestMatchesToLimit() {
        return BEST_MATCHING_LIMIT - bestMatchingMilestones.size();
    }

    /**
     * Adds a limited number of milestones to {@code milestonesToBePopulated}.
     * These milestones are taken from {@code allMilestones}, in the same order given,
     * if they are not already in {@code milestonesToBePopulated}.
     *
     * Assumption: {@code limit} is a positive integer
     * @param milestonesToBePopulated
     * @param limit
     * @param allMilestones
     */
    private void addLikelyUnmatchedMilestones(List<PickerMilestone> milestonesToBePopulated, int limit,
                                              List<PickerMilestone> allMilestones) {
        assert limit > 0;
        List<PickerMilestone> likelyUnmatchedMilestones =
                getLimitedFirstMilestones(milestonesToBePopulated, limit, allMilestones);
        milestonesToBePopulated.addAll(likelyUnmatchedMilestones);
    }

    /**
     * Adds a limited number of milestones to {@code milestonesToBePopulated}.
     * These milestones are taken from {@code allMilestones} if they match subsets of {@code querySentence} and are
     * not already in {@code milestonesToBePopulated}.
     *
     * Assumption: {@code limit} is a positive integer
     * @param milestonesToBePopulated
     * @param limit
     * @param querySentence
     * @param allMilestones
     */
    private void addPartiallyMatchingMilestones(List<PickerMilestone> milestonesToBePopulated, int limit,
                                                String querySentence, List<PickerMilestone> allMilestones) {
        assert limit > 0;
        List<PickerMilestone> partiallyMatchingMilestones =
                getLimitedMatchesFromPreviousQuery(querySentence, milestonesToBePopulated, limit, allMilestones);
        milestonesToBePopulated.addAll(partiallyMatchingMilestones);
    }

    /**
     * Adds a limited number of milestones to {@code milestonesToBePopulated}.
     * These milestones are taken from {@code allMilestones} if its isMatching() returns true.
     *
     * Assumption: {@code limit} is a positive integer
     * @param milestonesToBePopulated
     * @param limit
     * @param allMilestones
     */
    private void addMatchingMilestones(List<PickerMilestone> milestonesToBePopulated, int limit,
                                       List<PickerMilestone> allMilestones) {
        assert limit > 0;
        List<PickerMilestone> matchingMilestones = getLimitedMatchingMilestones(limit, allMilestones);
        milestonesToBePopulated.addAll(matchingMilestones);
    }

    /**
     * Gets a limited number of milestones from {@code allMilestones} matching previous querySentence(s)
     * which are not already in {@code currentMilestones}.
     *
     * Previous querySentence(s) refer to querySentence as it gets shorter after repetitively removing the last char
     * e.g. previous querySentences of "milestones" are "milestone", "mileston", "milesto", ..., and they will be
     * checked for matching milestones in that order
     *
     * Assumption: {@code limit} is not negative
     * @param querySentence
     * @param currentMilestones
     * @param limit
     * @param allMilestones
     */
    private List<PickerMilestone> getLimitedMatchesFromPreviousQuery(String querySentence,
                                                                     List<PickerMilestone> currentMilestones,
                                                                     int limit, List<PickerMilestone> allMilestones) {
        List<PickerMilestone> matchesForPreviousQuery = new ArrayList<>();
        String curQuerySentence = querySentence;
        while (matchesForPreviousQuery.size() < limit && curQuerySentence.length() > 0) {
            List<PickerMilestone> totalList = new ArrayList<>(currentMilestones);
            totalList.addAll(matchesForPreviousQuery);

            List<PickerMilestone> matchingMilestones = getNewMatchingMilestones(curQuerySentence, totalList,
                                                                                allMilestones);
            matchesForPreviousQuery.addAll(matchingMilestones);

            curQuerySentence = curQuerySentence.substring(0, curQuerySentence.length() - 1);
        }

        return matchesForPreviousQuery.stream()
                .limit(limit)
                .collect(Collectors.toList());
    }

    /**
     * Gets milestones from {@code allMilestones} which match {@code querySentence} and are not already
     * included in {@code currentMilestones}
     *
     * @param querySentence
     * @param currentMilestones
     * @param allMilestones
     */
    private List<PickerMilestone> getNewMatchingMilestones(String querySentence,
                                                           List<PickerMilestone> currentMilestones,
                                                           List<PickerMilestone> allMilestones) {
        String[] curQueryWords = querySentence.split(" ");

        List<PickerMilestone> matchingMilestones = allMilestones;
        for (String word : curQueryWords) {
            matchingMilestones = matchingMilestones.stream()
                    .filter(milestone -> isMatchingQuery(milestone, word))
                    .collect(Collectors.toList());
        }
        return matchingMilestones.stream()
                .filter(milestone -> !currentMilestones.contains(milestone))
                .collect(Collectors.toList());
    }

    /**
     * Gets a limited number of milestones from {@code milestones} whose isMatching() returns true
     *
     * Assumption: {@code limit} is not negative
     * @param limit non-negative integer
     * @param milestones milestones to get the matching milestones from
     */
    private List<PickerMilestone> getLimitedMatchingMilestones(int limit, List<PickerMilestone> milestones) {
        return milestones.stream()
                .filter(PickerMilestone::isMatching)
                .limit(limit)
                .collect(Collectors.toList());
    }

    /**
     * Gets the first {@code limit} milestones from {@code allMilestones} which are not already in
     * {@code currentMilestones}.
     *
     * Assumptions: {@code limit} is not negative and {@code allMilestones} should already be ordered
     * in the desired priority
     * @param currentMilestones
     * @param limit
     * @param allMilestones
     */
    private List<PickerMilestone> getLimitedFirstMilestones(List<PickerMilestone> currentMilestones,
                                                            int limit, List<PickerMilestone> allMilestones) {
        return allMilestones.stream()
                .filter(milestone -> !currentMilestones.contains(milestone))
                .limit(limit)
                .collect(Collectors.toList());
    }

    private Optional<PickerMilestone> getExactMatchMilestone(List<PickerMilestone> milestones, String query) {
        return milestones.stream()
                .filter(milestone -> milestone.getTitle().equals(query))
                .findFirst();
    }

    private boolean isMatchingQuery(PickerMilestone milestone, String query) {
        return Utility.containsIgnoreCase(milestone.getTitle(), query);
    }
}


text:
extern crate rand;
use rand::{thread_rng};
use rand::distributions::{IndependentSample, Range};
use std::env::args as cmd_args;

#[inline(always)]
fn usage() {
    println!("Usage:");
    println!("    gen_random [number of digits]");
}

fn gen_random_number_string(number: usize) -> String {
    let num_range = Range::new(0, 9);
    let mut rng = rand::thread_rng();
    let mut final_string = String::with_capacity(number);
    for _ in 0..number {
        final_string.push_str(format!("{}", num_range.ind_sample(&mut rng)).as_ref());
    }
    final_string
}

fn main() {
    if let Some(arg1) = cmd_args().skip(1).next() {
        if let Ok(arg1_number) = arg1.parse::<usize>() {
            if arg1_number == 0 { return; }

            println!("Got number: {}", gen_random_number_string(arg1_number));
        }
        else {
            println!("Cannon parse >{}< into positive number", &arg1);
        }
    }
    else { usage() }
}


text:
{% if request.logged_in? %}

{% elsif request.sorta_logged_in? %}

	Hi {{ request.current_signup.name_or_email }}.

		Sign in with Facebook, Twitter or email.

		Not {{ request.current_signup.name_or_email }}? click here.

{% else %}

  {% form_for signup %}
   {% hidden_field_tag "page_id", page.id %}
{% error_messages_for signup %}

   	{% email_field "email", class:"text", placeholder:"Email address", required: "required" %}{% submit_tag "Join", class:"submit-button" %}

  {% endform_for %}

{% endif %}


text:
Smart rate limiter middleware for both express and koa.

[![NPM version][npm-image]][npm-url]
[![Build Status][travis-image]][travis-url]
[![Downloads][downloads-image]][downloads-url]

## Requirements

- Redis 2.8+ with thunk-redis client

## Installation

```sh
npm install smart-limiter
```

## Example

### koa v2

```js
'use strict'

const Koa = require('koa')
const smartLimiter = require('smart-limiter')

const app = new Koa()

app.use(smartLimiter.koav2({
  redis: 6379,
  duration: 10000,
  getId: function (ctx) {
    return ctx.ip
  },
  policy: {
    'GET': [3, 5000],
    'GET /test': [3, 5000, 3, 10000],
    '/test': 5
  }
}))

app.use((ctx) => {
  ctx.body = ctx.headers
})

app.listen(3000)
console.log('Start at 3000')
```

### express

```js
'use strict'

const express = require('express')
const smartLimiter = require('smart-limiter')

const app = express()

app.use(function (req, res, next) {
  if (req.path !== '/favicon.ico') return next()
  res.end()
})

app.use(smartLimiter({
  redis: 6379,
  duration: 10000,
  getId: function (req) {
    return req.ip
  },
  policy: {
    'GET': [3, 5000],
    'GET /test': [3, 5000, 3, 10000],
    '/test': 5
  }
}))

app.use(function (req, res) {
  res.json(res._headers)
})

app.listen(3000)
console.log('Start at 3000')
```

### koa v1

```js
'use strict'

const Koa = require('koa')
const smartLimiter = require('smart-limiter')

const app = new Koa()

app.use(smartLimiter.koa({
  redis: 6379,
  duration: 10000,
  getId: function (ctx) {
    return ctx.ip
  },
  policy: {
    'GET': [3, 5000],
    'GET /test': [3, 5000, 3, 10000],
    '/test': 5
  }
}))

app.use(function * () {
  this.body = this.headers
})

app.listen(3000)
console.log('Start at 3000')
```

## API

```js
var smartLimiter = require('smart-limiter')
```

### smartLimiter(options)

```js
const limiter = smartLimiter({
  redis: thunkRedisClient,
  duration: 10000,
  getId: function (req) {
    return req.ip
  },
  policy: {
    'GET': [3, 5000],
    'GET /test': [3, 5000, 3, 10000],
    '/test': 5
  }
})
app.use(limiter)
```

return a express middleware.

- `options.prefix`: *Optional*, Type: `String`, redis key namespace, default to `LIMIT`.
- `options.redis`: *Optional*, {Mix}, thunk-redis instance or [thunk-redis options](https://github.com/thunks/thunk-redis#api-more)
- `options.duration`: *Optional*, {Number}, of limit in milliseconds, default to `3600000`
- `options.getId`: *Required*, {Function}, generate a identifier for requests
- `options.policy`: *Required*, {Object}, limit policy

    **policy key:**
    It support 3 types: `METHOD /path`, `/path` and `METHOD`. Limiter will try match `METHOD /path` first, then `/path`, then `METHOD`. It means that `METHOD /path` has highest priority, then fallback to `/path` and `METHOD`.

    **policy value:**
    If value is a member, it means max count with `options.duration`. If value is array, it should be a pair of `max` and `duration`, support one more pairs.

    The first pair is default limit policy. If someone touch the maximum of default limit,
    then the next policy will be apply, and so on. So next policy should be stricter than previous one.

    If someone touch the maximum of limit and request again after double current `duration` time, it will rollback to default policy.

    **example policy:**
    ```js
    options.policy = {
      'HEAD': 100,
      'GET': [60, 60000, 30, 60000, 30, 120000],
      'PUT': [40, 60000, 20, 60000, 10, 120000],
      'POST': [40, 60000, 10, 60000],
      'DELETE': [40, 60000, 10, 60000],
      'POST /api/organizations': [10, 60000, 2, 60000],
      'POST /api/projects': [20, 60000, 5, 60000],
      '/api/auth': [10, 60000, 5, 120000],
    }
    ```

### limiter.get(id, max, duration, max, duration...) => Promise

Return a promise that guarantee a limiter result. it support more `max` and `duration` pairs ad limit policy. The first pairs will be used as default. If some trigger limit, then the limiter will apply the next pair policy.

### limiter.remove(req, callback)
### limiter.remove(req) => Promise

Remove `req`'s rate limit data. Only available when using express middleware.

```js
limiter.remove(req, function (err, res) {
  console.log(err, res) // null, 1
})
```

## Responses

Example 200 with header fields:

```text
HTTP/1.1 200 OK

Connection:keep-alive
Content-Length:111
Content-Type:application/json; charset=utf-8
Date:Thu, 10 Dec 2015 13:21:55 GMT
X-Powered-By:Express
X-RateLimit-Limit:3
X-RateLimit-Remaining:2
X-RateLimit-Reset:1449753721
```

Example 429 with header fields:

```text
HTTP/1.1 429 Too Many Requests

Connection:keep-alive
Content-Length:39
Content-Type:text/html; charset=utf-8
Date:Thu, 10 Dec 2015 13:22:36 GMT
Retry-After:3
X-Powered-By:Express
X-RateLimit-Limit:3
X-RateLimit-Remaining:-1
X-RateLimit-Reset:1449753759
```

[npm-url]: https://npmjs.org/package/smart-limiter
[npm-image]: http://img.shields.io/npm/v/smart-limiter.svg

[travis-url]: https://travis-ci.org/teambition/smart-limiter
[travis-image]: http://img.shields.io/travis/teambition/smart-limiter.svg

[downloads-url]: https://npmjs.org/package/smart-limiter
[downloads-image]: http://img.shields.io/npm/dm/smart-limiter.svg?style=flat-square


text:
<!DOCTYPE html>

  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="HandheldFriendly" content="true" />
  <link rel="shortcut icon" href="https://www.epa.gov/sites/all/themes/epa/favicon.ico" type="image/vnd.microsoft.icon" />
  <meta name="MobileOptimized" content="width" />
  <meta http-equiv="cleartype" content="on" />
  <meta http-equiv="ImageToolbar" content="false" />
  <meta name="viewport" content="width=device-width" />
  <meta name="version" content="20161218" />

  <meta name="DC.description" content="" />
  <meta name="DC.title" content="" />
  <title>
  Project to Further Research, Develop, and Apply a New Air Pollution Modeling System|

  Research Project Database | Grantee Research Project | ORD | US EPA</title>

  <meta name="keywords" content="" />
  <link rel="shortlink" href="" />
  <link rel="canonical" href="" />
  <meta name="DC.creator" content="" />
  <meta name="DC.language" content="en" />
  <meta name="DC.Subject.epachannel" content="" />
  <meta name="DC.type" content="" />
  <meta name="DC.date.created" content="" />
  <meta name="DC.date.modified" content="2017-01-26" />

  <link type="text/css" rel="stylesheet" href="https://www.epa.gov/misc/ui/jquery.ui.autocomplete.css" media="all" />
  <link type="text/css" rel="stylesheet" href="https://www.epa.gov/sites/all/themes/epa/css/lib/jquery.ui.theme.css" media="all" />
  <link type="text/css" rel="stylesheet" href="https://www.epa.gov/sites/all/libraries/template2/s.css" media="all" />

	<link rel="alternate" type="application/atom+xml" title="EPA.gov All Press Releases" href="https://www.epa.gov/newsreleases/search/rss" />
	<link rel="alternate" type="application/atom+xml" title="EPA.gov Headquarters Press Releases" href="https://www.epa.gov/newsreleases/search/rss/field_press_office/headquarters" />
	<link rel="alternate" type="application/atom+xml" title="Greenversations, EPA's Blog" href="https://blog.epa.gov/blog/feed/" />

Jump to main content

  <hgroup class="site-name-and-slogan">

US EPA

United States Environmental Protection Agency

  </hgroup>
  <form class="epa-search" method="get" action="https://search.epa.gov/epasearch/epasearch">
    Search
    <input class="form-text" placeholder="Search EPA.gov" name="querytext" id="search-box" value=""/>
    <button class="epa-search-button" id="search-button" type="submit" title="Search">Search</button>
    <input type="hidden" name="fld" value="" />
    <input type="hidden" name="areaname" value="" />
    <input type="hidden" name="areacontacts" value="" />
    <input type="hidden" name="areasearchurl" value="" />
    <input type="hidden" name="typeofsearch" value="epa" />
    <input type="hidden" name="result_template" value="2col.ftl" />
    <input type="hidden" name="filter" value="sample4filt.hts" />
  </form>

Contact Us

Project Research Results

Final Report

                      28 publications for this project

                        11 journal articles for this project

Related Information

Research Grants

P3: Student Design Competition

Research Fellowships

Small Business Innovation Research (SBIR)

Grantee Research Project Results Search

      Project to Further Research, Develop, and Apply a New Air Pollution Modeling System

    EPA Grant Number: R823186

    Title: Project to Further Research, Develop, and Apply a New Air Pollution Modeling System

    Investigators:
     Jacobson, Mark Z.

    Institution:

      Stanford University

    	EPA Project Officer:

           Shapiro, Paul

      Project Period:
      September 1, 1995 through
        August 31, 1998

        Project Amount:

          $325,701

      RFA:
      Exploratory Research - Chemistry and Physics of Air (1995)

        		RFA Text |
          Recipients Lists

      Research Category:

          Air
          ,
          Air Quality and Air Toxics
          ,
          Engineering and Environmental Chemistry

Description:

      	The primary goal of the project is to improve treatment of chemical and physical processes in a numerical air pollution model.  Specifically, treatment of aerosol and cloud processes needs the most attention.  A second important goal is to apply and test the revised air pollution model in Los Angeles and the San Francisco Bay Area.

To accomplish the first goal, new algorithms will be developed.  For example, a numerical algorithm that simulates transfer of gases to multiple sizes of aerosols and cloud drops will be produced.  The algorithm treats both condensation of a gas onto particles and dissolution of a gas into particles.  The transfer algorithm will be coupled to a chemical equilibrium solver, which calculates internal particle composition.  To treat particles of different sizes in different grid cells of a model, a new particle size bin structure is being developed.  In this structure, size bin edges are fixed but size bin centers are allowed to fluctuate.  Thus, the structure is called the moving-bin structure.

To partly accomplish the second goal, simulations of air pollution in the Los Angeles Basin will be carried out.  Simulations results will be compared to data from the Southern California Air Quality Study (SCAQS) period of August 26 - 29, 1987.  Model predictions will be compared to data for aerosol, gas, radiative, and meteorological parameters.  One objective will be to study peak daytime surface solar radiation, night time temperatures, and overall temperatures in the presence and absence of aerosols in Los Angeles.

Finally, simulations of pollution in the San Francisco Bay Area are being planned.  Such simulations require improved treatment of cloud processes.  To that end, different numerical cloud algorithms are being tested, and one will be implemented into the air pollution model.

Publications and Presentations:

        Publications have been submitted on this project: View all 28 publications for this project

Journal Articles:

          Journal Articles have been submitted on this project: View all 11 journal articles for this project

Supplemental Keywords:

      air, ambient air, atmosphere, ozone, particulates, modeling, western, California, CA, Region 9, RFA, Scientific Discipline, Air, Geographic Area, particulate matter, Physics, Chemistry, State, tropospheric ozone, Engineering, Engineering,  Chemistry,  & Physics, ambient aerosol, environmental monitoring, particle size, particulates, chemical equilibrium solver, chemical treatment, aerosol particles, ozone, air modeling, cloud drop composition, air pollution modeling system, air pollution models, aerosol/ cloud interactions, atmospheric aerosol particles, California (CA), surface solar radiation

Progress and Final Reports:

                Final Report

Top of Page

 The perspectives, information and conclusions conveyed in research project abstracts, progress reports, final reports, journal abstracts and journal publications convey the viewpoints of the principal investigator and may not represent the views and policies of ORD and EPA.  Conclusions drawn by the principal investigators have not been reviewed by the Agency.

Main menu

Environmental Topics

Laws & Regulations

About EPA

Discover.

Accessibility

EPA Administrator

Budget & Performance

Contracting

Grants

No FEAR Act Data

Privacy and Security

Connect.

Data.gov

Inspector General

Jobs

Newsroom

Open Government

Regulations.gov

Subscribe

USA.gov

White House

Ask.

Contact Us

Hotlines

FOIA Requests

Frequent Questions

Follow.

Facebook

Twitter

YouTube

Flickr

Instagram

Last updated on Thursday, January 26, 2017


text:
#ifndef __DEV_IO_DEVICE_HH__
#define __DEV_IO_DEVICE_HH__

#include "mem/mem_object.hh"
#include "mem/tport.hh"
#include "params/BasicPioDevice.hh"
#include "params/PioDevice.hh"

class PioDevice;
class System;

/**
 * The PioPort class is a programmed i/o port that all devices that are
 * sensitive to an address range use. The port takes all the memory
 * access types and roles them into one read() and write() call that the device
 * must respond to. The device must also provide getAddrRanges() function
 * with which it returns the address ranges it is interested in.
 */
class PioPort : public SimpleTimingPort
{
  protected:
    /** The device that this port serves. */
    PioDevice *device;

    virtual Tick recvAtomic(PacketPtr pkt);

    virtual AddrRangeList getAddrRanges() const;

  public:

    PioPort(PioDevice *dev);
};

/**
 * This device is the base class which all devices senstive to an address range
 * inherit from. There are three pure virtual functions which all devices must
 * implement getAddrRanges(), read(), and write(). The magic do choose which
 * mode we are in, etc is handled by the PioPort so the device doesn't have to
 * bother.
 */
class PioDevice : public MemObject
{
  protected:
    System *sys;

    /** The pioPort that handles the requests for us and provides us requests
     * that it sees. */
    PioPort pioPort;

    /**
     * Every PIO device is obliged to provide an implementation that
     * returns the address ranges the device responds to.
     *
     * @return a list of non-overlapping address ranges
     */
    virtual AddrRangeList getAddrRanges() const = 0;

    /** Pure virtual function that the device must implement. Called
     * when a read command is recieved by the port.
     * @param pkt Packet describing this request
     * @return number of ticks it took to complete
     */
    virtual Tick read(PacketPtr pkt) = 0;

    /** Pure virtual function that the device must implement. Called when a
     * write command is recieved by the port.
     * @param pkt Packet describing this request
     * @return number of ticks it took to complete
     */
    virtual Tick write(PacketPtr pkt) = 0;

  public:
    typedef PioDeviceParams Params;
    PioDevice(const Params *p);
    virtual ~PioDevice();

    const Params *
    params() const
    {
        return dynamic_cast<const Params *>(_params);
    }

    virtual void init();

    virtual BaseSlavePort &getSlavePort(const std::string &if_name,
                                        PortID idx = InvalidPortID);

    friend class PioPort;

};

class BasicPioDevice : public PioDevice
{
  protected:
    /** Address that the device listens to. */
    Addr pioAddr;

    /** Size that the device's address range. */
    Addr pioSize;

    /** Delay that the device experinces on an access. */
    Tick pioDelay;

  public:
    typedef BasicPioDeviceParams Params;
    BasicPioDevice(const Params *p, Addr size);

    const Params *
    params() const
    {
        return dynamic_cast<const Params *>(_params);
    }

    /**
     * Determine the address ranges that this device responds to.
     *
     * @return a list of non-overlapping address ranges
     */
    virtual AddrRangeList getAddrRanges() const;

};

#endif // __DEV_IO_DEVICE_HH__


text:
package org.elasticsearch.index.fielddata;

import org.elasticsearch.ElasticSearchIllegalStateException;
import org.elasticsearch.index.fielddata.util.IntArrayRef;
import org.elasticsearch.index.fielddata.util.LongArrayRef;

/**
 */
public interface LongValues {

    static final LongValues EMPTY = new Empty();

    /**
     * Is one of the documents in this field data values is multi valued?
     */
    boolean isMultiValued();

    /**
     * Is there a value for this doc?
     */
    boolean hasValue(int docId);

    long getValue(int docId);

    long getValueMissing(int docId, long missingValue);

    LongArrayRef getValues(int docId);

    Iter getIter(int docId);

    void forEachValueInDoc(int docId, ValueInDocProc proc);

    static interface ValueInDocProc {

        void onValue(int docId, long value);

        void onMissing(int docId);
    }

    static interface Iter {

        boolean hasNext();

        long next();

        static class Empty implements Iter {

            public static final Empty INSTANCE = new Empty();

            @Override
            public boolean hasNext() {
                return false;
            }

            @Override
            public long next() {
                throw new ElasticSearchIllegalStateException();
            }
        }

        static class Single implements Iter {

            public long value;
            public boolean done;

            public Single reset(long value) {
                this.value = value;
                this.done = false;
                return this;
            }

            @Override
            public boolean hasNext() {
                return !done;
            }

            @Override
            public long next() {
                assert !done;
                done = true;
                return value;
            }
        }
    }

    static class Empty implements LongValues {
        @Override
        public boolean isMultiValued() {
            return false;
        }

        @Override
        public boolean hasValue(int docId) {
            return false;
        }

        @Override
        public long getValue(int docId) {
            throw new ElasticSearchIllegalStateException("Can't retrieve a value from an empty LongValues");
        }

        @Override
        public long getValueMissing(int docId, long missingValue) {
            return missingValue;
        }

        @Override
        public LongArrayRef getValues(int docId) {
            return LongArrayRef.EMPTY;
        }

        @Override
        public Iter getIter(int docId) {
            return Iter.Empty.INSTANCE;
        }

        @Override
        public void forEachValueInDoc(int docId, ValueInDocProc proc) {
            proc.onMissing(docId);
        }
    }

}


text:
using System.Runtime.Serialization;
using System;

namespace EspaceClient.FrontOffice.Domaine
{
    public partial class OrganismeCertificationDto
    {

        [DataMember]
        public long ID { get; set; }

        [DataMember]
        public string Code { get; set; }

        [DataMember]
        public string CodeEchange { get; set; }

        [DataMember]
        public string Description { get; set; }

        [DataMember]
        public string CleModificationLot { get; set; }

        [DataMember]
        public Nullable<long> SocieteID { get; set; }

        [DataMember]
        public bool ExportEspaceClient { get; set; }

        [DataMember]
        public string CodeEchangeEspaceClient { get; set; }

        [DataMember]
        public string EmailEchangeEspaceClient { get; set; }

        [DataMember]
        public Nullable<long> RessourceID { get; set; }
    }
}


text:
package com.dictionaryapp.presenters;

import android.content.Context;
import android.database.Cursor;
import android.widget.ArrayAdapter;
import android.widget.Toast;

import com.dictionaryapp.android.app.R;
import com.dictionaryapp.helpers.CategoryDbContract;
import com.dictionaryapp.helpers.WordsSqlService;
import com.dictionaryapp.interfaces.CategoriesService;
import com.dictionaryapp.interfaces.DeleteCategoryApi;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Sergey on 10/3/2017.
 */

public class DeleteActivityPresenter {
    //TODO : Delete all words within category
    private Context mCtx;
    private DeleteCategoryApi mApi;
    private CategoriesService mService;

    public DeleteActivityPresenter(Context ctx, DeleteCategoryApi api) {
        this.mCtx = ctx;
        this.mApi = api;
        this.mService = new WordsSqlService(mCtx);
    }

    public void removeCategory() {
        String categoryName = mApi.getSelectedCategoryName();
        mService.removeCategory(categoryName);
        String toastMessage = mCtx.getString(R.string.category_deleted);
        Toast.makeText(mCtx, toastMessage, Toast.LENGTH_SHORT).show();
        initializeSpinnerDataSource();

    }

    public void initializeSpinnerDataSource() {
        Cursor items = mService.getAllCategories();
        int position = 0;

        List<CharSequence> categories = new ArrayList<>();
        while (items.moveToPosition(position)) {
            String categoryName = items.getString(items.getColumnIndex
                    (CategoryDbContract.COLUMN_CATEGORY_NAME));
            categories.add(categoryName);
            position++;
        }

        items.close();
        ArrayAdapter<CharSequence> adapter = new ArrayAdapter<>(mCtx, android.R.layout.simple_spinner_item,
                categories);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mApi.setSpinnerAdapter(adapter);

        if (categories.isEmpty()) {
            mApi.lockDeleteFunction();
        }
    }
}


text:
package synergyspace.jme.gfx.twod;

import com.jme.scene.Node;
import com.jme.scene.Text;
import com.jme.scene.state.RenderState;
import com.jme.util.Timer;

public class FPSNode extends Node {

	private static final long serialVersionUID = 7521550035241588792L;
	protected StringBuffer updateBuffer = new StringBuffer( 30 );
	protected StringBuffer tempBuffer = new StringBuffer();
	protected Text fps;

	public FPSNode(String name) {
		super(name);
		fps = Text.createDefaultTextLabel( "FPS label" );
		fps.setCullHint(CullHint.Never);
		fps.setTextureCombineMode(TextureCombineMode.Replace);

		this.setRenderState(fps.getRenderState(RenderState.StateType.Blend));
		this.setRenderState(fps.getRenderState(RenderState.StateType.Texture));
		this.attachChild( fps );
		this.setCullHint(CullHint.Never);
		this.updateGeometricState( 0.0f, true );
		this.updateRenderState();
	}

	public void update(Timer timer) {
		updateBuffer.setLength(0);
		updateBuffer.append("FPS: ").append((int)timer.getFrameRate()).append(" - ");
		//TODO: fix FPS display
//		updateBuffer.append(DisplaySystem.getDisplaySystem().getRenderer().getStatistics(tempBuffer));
//		fps.print(updateBuffer);

	}
}


text:
// MonoGame - Copyright (C) The MonoGame Team
// This file is subject to the terms and conditions defined in
// file 'LICENSE.txt', which is part of this source code package.

using Microsoft.Xna.Framework.Content.Pipeline.Graphics;
using Microsoft.Xna.Framework.Graphics;

namespace Microsoft.Xna.Framework.Content.Pipeline.Processors
{
    public sealed class ModelMeshPartContent
    {
        private IndexCollection _indexBuffer;
        private MaterialContent _material;
        private int _numVertices;
        private int _primitiveCount;
        private int _startIndex;
        private VertexBufferContent _vertexBuffer;
        private int _vertexOffset;

        internal ModelMeshPartContent() { }

        internal ModelMeshPartContent(VertexBufferContent vertexBuffer, IndexCollection indices, int vertexOffset,
                                      int numVertices, int startIndex, int primitiveCount)
        {
            _vertexBuffer = vertexBuffer;
            _indexBuffer = indices;
            _vertexOffset = vertexOffset;
            _numVertices = numVertices;
            _startIndex = startIndex;
            _primitiveCount = primitiveCount;
        }

        public IndexCollection IndexBuffer
        {
            get { return _indexBuffer; }
        }

        public MaterialContent Material
        {
            get { return _material; }
            set { _material = value; }
        }

        public int NumVertices
        {
            get { return _numVertices; }
        }

        public int PrimitiveCount
        {
            get { return _primitiveCount; }
        }

        public int StartIndex
        {
            get { return _startIndex; }
        }

        public object Tag { get; set; }

        public VertexBufferContent VertexBuffer
        {
            get { return _vertexBuffer; }
        }

        public int VertexOffset
        {
            get { return _vertexOffset; }
        }
    }
}


text:
package pl.edu.agh.planner.domain;

import javax.persistence.*;
import java.util.Set;

@Entity(name = "building")
public class BuildingEntity {

    @Id
    @SequenceGenerator(name="building_id_seq", sequenceName="building_id_seq", allocationSize=1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator="building_id_seq")
    @Column(name = "b_id")
    private Long id;

    @Column(name = "b_name")
    private String name;

    @OneToMany(mappedBy = "building", fetch = FetchType.EAGER)
    private Set<ClassroomEntity> classrooms;

    public BuildingEntity() {
    }

    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Set<ClassroomEntity> getClassrooms() {
        return classrooms;
    }

    public void setClassrooms(Set<ClassroomEntity> classrooms) {
        this.classrooms = classrooms;
    }
}


text:
import commonware
import json

from test_utils import TestCase
from nose.tools import eq_

from django.contrib.auth.models import User
from django.core.urlresolvers import reverse

from jetpack.models import Package, PackageRevision, Module
from jetpack.errors import UpdateDeniedException, IllegalFilenameException

log = commonware.log.getLogger('f.test')

def next(revision):
    number = revision.revision_number
    return (PackageRevision.objects.filter(revision_number__gt=number,
                                           package=revision.package)
                                   .order_by('-revision_number')[:1])[0]

class ModuleTest(TestCase):
    " Testing module methods "

    fixtures = ['users']

    def test_update_module_using_save(self):
        " updating module is not allowed "
        author = User.objects.get(username='john')
        mod = Module.objects.create(
            filename='test_filename',
            author=author
        )
        self.assertRaises(UpdateDeniedException, mod.save)

    def test_create_module_with_utf_content(self):
        author = User.objects.get(username='john')
        Module.objects.create(
                filename='test_filename',
                author=author,
                code=u'ą')
        eq_(Module.objects.get(author=author).code, u'ą')

    def test_illegal_filename(self):
        mod = Module(filename='.../...///foo.js',
                     author=User.objects.get(username='john'))
        self.assertRaises(IllegalFilenameException, mod.save)

class TestModules(TestCase):

    fixtures = ['mozilla_user', 'users', 'core_sdk', 'packages']

    def setUp(self):
        self.author = User.objects.get(username='john')
        self.author.set_password('password')
        self.author.save()

        self.package = self.author.packages_originated.addons()[0:1].get()
        self.revision = self.package.revisions.all()[0]

        self.client.login(username=self.author.username, password='password')

    def add_one(self, filename='tester'):
        self.client.post(self.get_add_url(self.revision.revision_number), { 'filename': filename })
        self.revision = next(self.revision)
        return self.revision

    def get_add_url(self, revision_number):
        revision = self.package.revisions.get(revision_number=revision_number)
        return reverse('jp_package_revision_add_module', args=[revision.pk])

    def get_rename_url(self, revision_number):
        revision = self.package.revisions.get(revision_number=revision_number)
        return reverse('jp_package_revision_rename_module', args=[revision.pk])

    def get_delete_url(self, revision_number):
        revision = self.package.revisions.get(revision_number=revision_number)
        return reverse('jp_addon_revision_remove_module', args=[revision.pk])

    def test_module_add(self):
        revision = self.add_one('a-module')
        # 1 for main, 1 for added, so 2
        eq_(revision.modules.all().count(), 2)
        eq_(revision.modules.all().order_by('-id')[0].filename, 'a-module')

    def test_module_add_with_extension(self):
        revision = self.add_one('test.js')
        eq_(revision.modules.all().order_by('-id')[0].filename, 'test')

    def test_module_name_sanitization(self):
        revision = self.add_one(filename='A"> <a href="google.com">malicious module')
        eq_(revision.modules.all().order_by('-id')[0].filename, 'A-a-href=-google')

        revision = self.add_one(filename='void:myXSSFunction(fd.item)')
        eq_(revision.modules.all().order_by('-id')[0].filename, 'void-myXSSFunction(fd')

    def test_module_rename(self):
        first_name = 'a-module'
        revision = self.add_one(first_name)

        res = self.client.post(self.get_rename_url(self.revision.revision_number),
                               {'old_filename': first_name,
                                'new_filename': 'different-module.js'})

        eq_(res.status_code, 200)
        data = json.loads(res.content)

        eq_(data.get('filename'), 'different-module')

    def test_getting_recursive_module_names(self):
        module_names = self.package.latest.get_module_names()
        eq_(module_names, {self.package.name: ['main']})
        assert not self.package.latest.get_conflicting_module_names()
        # 2 modules
        mod = self.package.latest.module_create(
                filename='test',
                author=self.author)
        module_names = self.package.latest.get_module_names()
        assert 'test' in module_names[self.package.name]
        assert 'main' in module_names[self.package.name]
        assert not self.package.latest.get_conflicting_module_names()
        # dependency
        lib = Package.objects.create(
                full_name='test',
                author=self.author,
                type='l')
        self.package.latest.dependency_add(lib.latest)
        module_names = self.package.latest.get_module_names()
        assert 'test' in module_names[self.package.name]
        assert 'main' in module_names[self.package.name]
        assert module_names.has_key('test')
        assert 'index' in module_names['test']
        assert not self.package.latest.get_conflicting_module_names()
        # nested dependencies
        lib2 = Package.objects.create(
                full_name='test2',
                author=self.author,
                type='l')
        lib_revision = lib.latest
        lib.latest.dependency_add(lib2.latest)
        self.package.latest.dependency_update(lib_revision)
        module_names = self.package.latest.get_module_names()
        assert 'test' in module_names[self.package.name]
        assert 'main' in module_names[self.package.name]
        assert module_names.has_key('test')
        assert 'index' in module_names['test']
        assert module_names.has_key('test2')
        assert 'index' in module_names['test2']
        # this should have a conflicting names
        conflicts = self.package.latest.get_conflicting_module_names()
        assert conflicts.has_key('test')
        assert 'index' in conflicts['test']
        assert conflicts.has_key('test2')
        assert 'index' in conflicts['test2']
        response = self.client.get(
                self.package.latest.get_conflicting_modules_list_url())
        eq_(response.status_code, 200)
        conflicts = json.loads(response.content)
        assert conflicts.has_key('test')
        assert 'index' in conflicts['test']
        assert conflicts.has_key('test2')
        assert 'index' in conflicts['test2']

    def test_private_modules(self):
        revision = self.add_one()
        revision.package.active = False
        revision.package.save()

        mod = revision.modules.all()[0]
        url = reverse('jp_module', args=[mod.pk])
        res = self.client.get(url)
        eq_(res.status_code, 200)

        self.client.logout()
        res = self.client.get(url)
        eq_(res.status_code, 403)


text:
module UbiquoMenus
  module Extensions
    module MenuSelectionResolver

      def menu_item_selected?(item, url = request.path)
        begin
          return false unless item.is_active && item.is_linkable
          case item.link
          when Page
            page_selected?(item.link, url)
          when String
            url_selected?(item.link, url)
          end
        rescue Exception => e
          Rails.logger.warn("Application crash computing menu_item selection:\n #{e.backtrace}")
          false
        end
      end

      protected

      def page_selected?(page, url)
        if url_for_page(page) == "/"
          url_for_page(page) == url
        else
          url.include?(url_for_page(page)) || url.include?(url_for_page(page.published))
        end
      end

      def url_selected?(item_url, current_url)
        if root_url?(item_url)
          root_url?(current_url)
        else
          current_url.include?(item_url)
        end
      end

      def root_url?(url)
        url.blank? || url == '/'
      end
    end
  end
end


text:
package org.apache.hadoop.hbase.client;

import static org.junit.Assert.fail;

import java.io.IOException;
import java.util.Arrays;
import java.util.Set;

import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
import org.apache.hadoop.hbase.protobuf.generated.ClientProtos;
import org.apache.hadoop.hbase.security.visibility.Authorizations;
import org.apache.hadoop.hbase.testclassification.ClientTests;
import org.apache.hadoop.hbase.testclassification.SmallTests;
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.Assert;
import org.junit.Test;
import org.junit.experimental.categories.Category;

// TODO: cover more test cases
@Category({ClientTests.class, SmallTests.class})
public class TestScan {
  @Test
  public void testAttributesSerialization() throws IOException {
    Scan scan = new Scan();
    scan.setAttribute("attribute1", Bytes.toBytes("value1"));
    scan.setAttribute("attribute2", Bytes.toBytes("value2"));
    scan.setAttribute("attribute3", Bytes.toBytes("value3"));

    ClientProtos.Scan scanProto = ProtobufUtil.toScan(scan);

    Scan scan2 = ProtobufUtil.toScan(scanProto);

    Assert.assertNull(scan2.getAttribute("absent"));
    Assert.assertTrue(Arrays.equals(Bytes.toBytes("value1"), scan2.getAttribute("attribute1")));
    Assert.assertTrue(Arrays.equals(Bytes.toBytes("value2"), scan2.getAttribute("attribute2")));
    Assert.assertTrue(Arrays.equals(Bytes.toBytes("value3"), scan2.getAttribute("attribute3")));
    Assert.assertEquals(3, scan2.getAttributesMap().size());
  }

  @Test
  public void testScanAttributes() {
    Scan scan = new Scan();
    Assert.assertTrue(scan.getAttributesMap().isEmpty());
    Assert.assertNull(scan.getAttribute("absent"));

    scan.setAttribute("absent", null);
    Assert.assertTrue(scan.getAttributesMap().isEmpty());
    Assert.assertNull(scan.getAttribute("absent"));

    // adding attribute
    scan.setAttribute("attribute1", Bytes.toBytes("value1"));
    Assert.assertTrue(Arrays.equals(Bytes.toBytes("value1"), scan.getAttribute("attribute1")));
    Assert.assertEquals(1, scan.getAttributesMap().size());
    Assert.assertTrue(Arrays.equals(Bytes.toBytes("value1"), scan.getAttributesMap().get("attribute1")));

    // overriding attribute value
    scan.setAttribute("attribute1", Bytes.toBytes("value12"));
    Assert.assertTrue(Arrays.equals(Bytes.toBytes("value12"), scan.getAttribute("attribute1")));
    Assert.assertEquals(1, scan.getAttributesMap().size());
    Assert.assertTrue(Arrays.equals(Bytes.toBytes("value12"), scan.getAttributesMap().get("attribute1")));

    // adding another attribute
    scan.setAttribute("attribute2", Bytes.toBytes("value2"));
    Assert.assertTrue(Arrays.equals(Bytes.toBytes("value2"), scan.getAttribute("attribute2")));
    Assert.assertEquals(2, scan.getAttributesMap().size());
    Assert.assertTrue(Arrays.equals(Bytes.toBytes("value2"), scan.getAttributesMap().get("attribute2")));

    // removing attribute
    scan.setAttribute("attribute2", null);
    Assert.assertNull(scan.getAttribute("attribute2"));
    Assert.assertEquals(1, scan.getAttributesMap().size());
    Assert.assertNull(scan.getAttributesMap().get("attribute2"));

    // removing non-existed attribute
    scan.setAttribute("attribute2", null);
    Assert.assertNull(scan.getAttribute("attribute2"));
    Assert.assertEquals(1, scan.getAttributesMap().size());
    Assert.assertNull(scan.getAttributesMap().get("attribute2"));

    // removing another attribute
    scan.setAttribute("attribute1", null);
    Assert.assertNull(scan.getAttribute("attribute1"));
    Assert.assertTrue(scan.getAttributesMap().isEmpty());
    Assert.assertNull(scan.getAttributesMap().get("attribute1"));
  }

  @Test
  public void testNullQualifier() {
    Scan scan = new Scan();
    byte[] family = Bytes.toBytes("family");
    scan.addColumn(family, null);
    Set<byte[]> qualifiers = scan.getFamilyMap().get(family);
    Assert.assertEquals(1, qualifiers.size());
  }

  @Test
  public void testSetAuthorizations() {
    Scan scan = new Scan();
    try {
      scan.setAuthorizations(new Authorizations("\u002b|\u0029"));
      scan.setAuthorizations(new Authorizations("A", "B", "0123", "A0", "1A1", "_a"));
      scan.setAuthorizations(new Authorizations("A|B"));
      scan.setAuthorizations(new Authorizations("A&B"));
      scan.setAuthorizations(new Authorizations("!B"));
      scan.setAuthorizations(new Authorizations("A", "(A)"));
      scan.setAuthorizations(new Authorizations("A", "{A"));
      scan.setAuthorizations(new Authorizations(" "));
      scan.setAuthorizations(new Authorizations(":B"));
      scan.setAuthorizations(new Authorizations("-B"));
      scan.setAuthorizations(new Authorizations(".B"));
      scan.setAuthorizations(new Authorizations("/B"));
    } catch (IllegalArgumentException e) {
      fail("should not throw exception");
    }
  }
}


text:
import path from 'path';
import {optimize} from 'webpack';

import packages, {makeScoped} from './packageList';
import {isMain} from './scripts/helpers';
import {
  libName,
  moduleProp,
  minify,
  banner,
} from './webpack.parts';

const {ModuleConcatenationPlugin} = optimize;

export default ({modern, cover}, {mode, cache}) => ({
  mode,
  entry: packages.reduce((pkgs, [{name}, file]) => (
    {...pkgs, [name]: path.resolve(file)}
  ), {}),
  devtool: 'source-map',
  output: {
    path: path.resolve('dist'),
    filename: ({chunk: {name}}) => `${isMain(name) ? libName : makeScoped(name)}/${
      (modern ? '' : 'legacy/') +
      (mode === 'production' ? 'min' : 'index')
    }.js`,
    library: '[name]',
    libraryTarget: 'umd',
    libraryExport: 'default',
    umdNamedDefine: true,
    globalObject: 'typeof self !== \'undefined\' ? self : this',
    pathinfo: false,
  },
  module: moduleProp(cache, modern, cover),
  optimization: mode === 'production' ? minify() : {},
  plugins: [
    banner,
    new ModuleConcatenationPlugin(),
  ],
});


text:
/******************************************************************************/
#ifdef JEMALLOC_H_TYPES

typedef struct tcache_bin_info_s tcache_bin_info_t;
typedef struct tcache_bin_s tcache_bin_t;
typedef struct tcache_s tcache_t;
typedef struct tcaches_s tcaches_t;

/*
 * tcache pointers close to NULL are used to encode state information that is
 * used for two purposes: preventing thread caching on a per thread basis and
 * cleaning up during thread shutdown.
 */
#define	TCACHE_STATE_DISABLED		((tcache_t *)(uintptr_t)1)
#define	TCACHE_STATE_REINCARNATED	((tcache_t *)(uintptr_t)2)
#define	TCACHE_STATE_PURGATORY		((tcache_t *)(uintptr_t)3)
#define	TCACHE_STATE_MAX		TCACHE_STATE_PURGATORY

/*
 * Absolute minimum number of cache slots for each small bin.
 */
#define	TCACHE_NSLOTS_SMALL_MIN		20

/*
 * Absolute maximum number of cache slots for each small bin in the thread
 * cache.  This is an additional constraint beyond that imposed as: twice the
 * number of regions per run for this size class.
 *
 * This constant must be an even number.
 */
#define	TCACHE_NSLOTS_SMALL_MAX		200

/* Number of cache slots for large size classes. */
#define	TCACHE_NSLOTS_LARGE		20

/* (1U << opt_lg_tcache_max) is used to compute tcache_maxclass. */
#define	LG_TCACHE_MAXCLASS_DEFAULT	15

/*
 * TCACHE_GC_SWEEP is the approximate number of allocation events between
 * full GC sweeps.  Integer rounding may cause the actual number to be
 * slightly higher, since GC is performed incrementally.
 */
#define	TCACHE_GC_SWEEP			8192

/* Number of tcache allocation/deallocation events between incremental GCs. */
#define	TCACHE_GC_INCR							\
    ((TCACHE_GC_SWEEP / NBINS) + ((TCACHE_GC_SWEEP / NBINS == 0) ? 0 : 1))

#endif /* JEMALLOC_H_TYPES */
/******************************************************************************/
#ifdef JEMALLOC_H_STRUCTS

typedef enum {
	tcache_enabled_false   = 0, /* Enable cast to/from bool. */
	tcache_enabled_true    = 1,
	tcache_enabled_default = 2
} tcache_enabled_t;

/*
 * Read-only information associated with each element of tcache_t's tbins array
 * is stored separately, mainly to reduce memory usage.
 */
struct tcache_bin_info_s {
	unsigned	ncached_max;	/* Upper limit on ncached. */
};

struct tcache_bin_s {
	tcache_bin_stats_t tstats;
	int		low_water;	/* Min # cached since last GC. */
	unsigned	lg_fill_div;	/* Fill (ncached_max >> lg_fill_div). */
	unsigned	ncached;	/* # of cached objects. */
	void		**avail;	/* Stack of available objects. */
};

struct tcache_s {
	ql_elm(tcache_t) link;		/* Used for aggregating stats. */
	uint64_t	prof_accumbytes;/* Cleared after arena_prof_accum(). */
	unsigned	ev_cnt;		/* Event count since incremental GC. */
	index_t		next_gc_bin;	/* Next bin to GC. */
	tcache_bin_t	tbins[1];	/* Dynamically sized. */
	/*
	 * The pointer stacks associated with tbins follow as a contiguous
	 * array.  During tcache initialization, the avail pointer in each
	 * element of tbins is initialized to point to the proper offset within
	 * this array.
	 */
};

/* Linkage for list of available (previously used) explicit tcache IDs. */
struct tcaches_s {
	union {
		tcache_t	*tcache;
		tcaches_t	*next;
	};
};

#endif /* JEMALLOC_H_STRUCTS */
/******************************************************************************/
#ifdef JEMALLOC_H_EXTERNS

extern bool	opt_tcache;
extern ssize_t	opt_lg_tcache_max;

extern tcache_bin_info_t	*tcache_bin_info;

/*
 * Number of tcache bins.  There are NBINS small-object bins, plus 0 or more
 * large-object bins.
 */
extern size_t	nhbins;

/* Maximum cached size class. */
extern size_t	tcache_maxclass;

/*
 * Explicit tcaches, managed via the tcache.{create,flush,destroy} mallctls and
 * usable via the MALLOCX_TCACHE() flag.  The automatic per thread tcaches are
 * completely disjoint from this data structure.  tcaches starts off as a sparse
 * array, so it has no physical memory footprint until individual pages are
 * touched.  This allows the entire array to be allocated the first time an
 * explicit tcache is created without a disproportionate impact on memory usage.
 */
extern tcaches_t	*tcaches;

size_t	tcache_salloc(const void *ptr);
void	tcache_event_hard(tsd_t *tsd, tcache_t *tcache);
void	*tcache_alloc_small_hard(tsd_t *tsd, arena_t *arena, tcache_t *tcache,
    tcache_bin_t *tbin, index_t binind);
void	tcache_bin_flush_small(tsd_t *tsd, tcache_t *tcache, tcache_bin_t *tbin,
    index_t binind, unsigned rem);
void	tcache_bin_flush_large(tsd_t *tsd, tcache_bin_t *tbin, index_t binind,
    unsigned rem, tcache_t *tcache);
void	tcache_arena_associate(tcache_t *tcache, arena_t *arena);
void	tcache_arena_reassociate(tcache_t *tcache, arena_t *oldarena,
    arena_t *newarena);
void	tcache_arena_dissociate(tcache_t *tcache, arena_t *arena);
tcache_t *tcache_get_hard(tsd_t *tsd);
tcache_t *tcache_create(tsd_t *tsd, arena_t *arena);
void	tcache_cleanup(tsd_t *tsd);
void	tcache_enabled_cleanup(tsd_t *tsd);
void	tcache_stats_merge(tcache_t *tcache, arena_t *arena);
bool	tcaches_create(tsd_t *tsd, unsigned *r_ind);
void	tcaches_flush(tsd_t *tsd, unsigned ind);
void	tcaches_destroy(tsd_t *tsd, unsigned ind);
bool	tcache_boot(void);

#endif /* JEMALLOC_H_EXTERNS */
/******************************************************************************/
#ifdef JEMALLOC_H_INLINES

#ifndef JEMALLOC_ENABLE_INLINE
void	tcache_event(tsd_t *tsd, tcache_t *tcache);
void	tcache_flush(void);
bool	tcache_enabled_get(void);
tcache_t *tcache_get(tsd_t *tsd, bool create);
void	tcache_enabled_set(bool enabled);
void	*tcache_alloc_easy(tcache_bin_t *tbin);
void	*tcache_alloc_small(tsd_t *tsd, arena_t *arena, tcache_t *tcache,
    size_t size, bool zero);
void	*tcache_alloc_large(tsd_t *tsd, arena_t *arena, tcache_t *tcache,
    size_t size, bool zero);
void	tcache_dalloc_small(tsd_t *tsd, tcache_t *tcache, void *ptr,
    index_t binind);
void	tcache_dalloc_large(tsd_t *tsd, tcache_t *tcache, void *ptr,
    size_t size);
tcache_t	*tcaches_get(tsd_t *tsd, unsigned ind);
#endif

#if (defined(JEMALLOC_ENABLE_INLINE) || defined(JEMALLOC_TCACHE_C_))
JEMALLOC_INLINE void
tcache_flush(void)
{
	tsd_t *tsd;

	cassert(config_tcache);

	tsd = tsd_fetch();
	tcache_cleanup(tsd);
}

JEMALLOC_INLINE bool
tcache_enabled_get(void)
{
	tsd_t *tsd;
	tcache_enabled_t tcache_enabled;

	cassert(config_tcache);

	tsd = tsd_fetch();
	tcache_enabled = tsd_tcache_enabled_get(tsd);
	if (tcache_enabled == tcache_enabled_default) {
		tcache_enabled = (tcache_enabled_t)opt_tcache;
		tsd_tcache_enabled_set(tsd, tcache_enabled);
	}

	return ((bool)tcache_enabled);
}

JEMALLOC_INLINE void
tcache_enabled_set(bool enabled)
{
	tsd_t *tsd;
	tcache_enabled_t tcache_enabled;

	cassert(config_tcache);

	tsd = tsd_fetch();

	tcache_enabled = (tcache_enabled_t)enabled;
	tsd_tcache_enabled_set(tsd, tcache_enabled);

	if (!enabled)
		tcache_cleanup(tsd);
}

JEMALLOC_ALWAYS_INLINE tcache_t *
tcache_get(tsd_t *tsd, bool create)
{
	tcache_t *tcache;

	if (!config_tcache)
		return (NULL);

	tcache = tsd_tcache_get(tsd);
	if (!create)
		return (tcache);
	if (unlikely(tcache == NULL) && tsd_nominal(tsd)) {
		tcache = tcache_get_hard(tsd);
		tsd_tcache_set(tsd, tcache);
	}

	return (tcache);
}

JEMALLOC_ALWAYS_INLINE void
tcache_event(tsd_t *tsd, tcache_t *tcache)
{

	if (TCACHE_GC_INCR == 0)
		return;

	tcache->ev_cnt++;
	assert(tcache->ev_cnt <= TCACHE_GC_INCR);
	if (unlikely(tcache->ev_cnt == TCACHE_GC_INCR))
		tcache_event_hard(tsd, tcache);
}

JEMALLOC_ALWAYS_INLINE void *
tcache_alloc_easy(tcache_bin_t *tbin)
{
	void *ret;

	if (unlikely(tbin->ncached == 0)) {
		tbin->low_water = -1;
		return (NULL);
	}
	tbin->ncached--;
	if (unlikely((int)tbin->ncached < tbin->low_water))
		tbin->low_water = tbin->ncached;
	ret = tbin->avail[tbin->ncached];
	return (ret);
}

JEMALLOC_ALWAYS_INLINE void *
tcache_alloc_small(tsd_t *tsd, arena_t *arena, tcache_t *tcache, size_t size,
    bool zero)
{
	void *ret;
	index_t binind;
	size_t usize;
	tcache_bin_t *tbin;

	binind = size2index(size);
	assert(binind < NBINS);
	tbin = &tcache->tbins[binind];
	usize = index2size(binind);
	ret = tcache_alloc_easy(tbin);
	if (unlikely(ret == NULL)) {
		ret = tcache_alloc_small_hard(tsd, arena, tcache, tbin, binind);
		if (ret == NULL)
			return (NULL);
	}
	assert(tcache_salloc(ret) == usize);

	if (likely(!zero)) {
		if (config_fill) {
			if (unlikely(opt_junk_alloc)) {
				arena_alloc_junk_small(ret,
				    &arena_bin_info[binind], false);
			} else if (unlikely(opt_zero))
				memset(ret, 0, usize);
		}
	} else {
		if (config_fill && unlikely(opt_junk_alloc)) {
			arena_alloc_junk_small(ret, &arena_bin_info[binind],
			    true);
		}
		memset(ret, 0, usize);
	}

	if (config_stats)
		tbin->tstats.nrequests++;
	if (config_prof)
		tcache->prof_accumbytes += usize;
	tcache_event(tsd, tcache);
	return (ret);
}

JEMALLOC_ALWAYS_INLINE void *
tcache_alloc_large(tsd_t *tsd, arena_t *arena, tcache_t *tcache, size_t size,
    bool zero)
{
	void *ret;
	index_t binind;
	size_t usize;
	tcache_bin_t *tbin;

	binind = size2index(size);
	usize = index2size(binind);
	assert(usize <= tcache_maxclass);
	assert(binind < nhbins);
	tbin = &tcache->tbins[binind];
	ret = tcache_alloc_easy(tbin);
	if (unlikely(ret == NULL)) {
		/*
		 * Only allocate one large object at a time, because it's quite
		 * expensive to create one and not use it.
		 */
		ret = arena_malloc_large(arena, usize, zero);
		if (ret == NULL)
			return (NULL);
	} else {
		if (config_prof && usize == LARGE_MINCLASS) {
			arena_chunk_t *chunk =
			    (arena_chunk_t *)CHUNK_ADDR2BASE(ret);
			size_t pageind = (((uintptr_t)ret - (uintptr_t)chunk) >>
			    LG_PAGE);
			arena_mapbits_large_binind_set(chunk, pageind,
			    BININD_INVALID);
		}
		if (likely(!zero)) {
			if (config_fill) {
				if (unlikely(opt_junk_alloc))
					memset(ret, 0xa5, usize);
				else if (unlikely(opt_zero))
					memset(ret, 0, usize);
			}
		} else
			memset(ret, 0, usize);

		if (config_stats)
			tbin->tstats.nrequests++;
		if (config_prof)
			tcache->prof_accumbytes += usize;
	}

	tcache_event(tsd, tcache);
	return (ret);
}

JEMALLOC_ALWAYS_INLINE void
tcache_dalloc_small(tsd_t *tsd, tcache_t *tcache, void *ptr, index_t binind)
{
	tcache_bin_t *tbin;
	tcache_bin_info_t *tbin_info;

	assert(tcache_salloc(ptr) <= SMALL_MAXCLASS);

	if (config_fill && unlikely(opt_junk_free))
		arena_dalloc_junk_small(ptr, &arena_bin_info[binind]);

	tbin = &tcache->tbins[binind];
	tbin_info = &tcache_bin_info[binind];
	if (unlikely(tbin->ncached == tbin_info->ncached_max)) {
		tcache_bin_flush_small(tsd, tcache, tbin, binind,
		    (tbin_info->ncached_max >> 1));
	}
	assert(tbin->ncached < tbin_info->ncached_max);
	tbin->avail[tbin->ncached] = ptr;
	tbin->ncached++;

	tcache_event(tsd, tcache);
}

JEMALLOC_ALWAYS_INLINE void
tcache_dalloc_large(tsd_t *tsd, tcache_t *tcache, void *ptr, size_t size)
{
	index_t binind;
	tcache_bin_t *tbin;
	tcache_bin_info_t *tbin_info;

	assert((size & PAGE_MASK) == 0);
	assert(tcache_salloc(ptr) > SMALL_MAXCLASS);
	assert(tcache_salloc(ptr) <= tcache_maxclass);

	binind = size2index(size);

	if (config_fill && unlikely(opt_junk_free))
		arena_dalloc_junk_large(ptr, size);

	tbin = &tcache->tbins[binind];
	tbin_info = &tcache_bin_info[binind];
	if (unlikely(tbin->ncached == tbin_info->ncached_max)) {
		tcache_bin_flush_large(tsd, tbin, binind,
		    (tbin_info->ncached_max >> 1), tcache);
	}
	assert(tbin->ncached < tbin_info->ncached_max);
	tbin->avail[tbin->ncached] = ptr;
	tbin->ncached++;

	tcache_event(tsd, tcache);
}

JEMALLOC_ALWAYS_INLINE tcache_t *
tcaches_get(tsd_t *tsd, unsigned ind)
{
	tcaches_t *elm = &tcaches[ind];
	if (unlikely(elm->tcache == NULL))
		elm->tcache = tcache_create(tsd, arena_choose(tsd, NULL));
	return (elm->tcache);
}
#endif

#endif /* JEMALLOC_H_INLINES */
/******************************************************************************/


text:
set -o errexit
set -o pipefail

readonly SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
readonly TEST_INFRA_SOURCES_DIR="$(cd "${SCRIPT_DIR}/../../" && pwd)"
readonly TMP_DIR=$(mktemp -d)

# shellcheck source=prow/scripts/lib/log.sh
source "${TEST_INFRA_SOURCES_DIR}/prow/scripts/lib/log.sh"

if [[ "${BUILD_TYPE}" == "pr" ]]; then
    log::info "Check if web deployment was updated in PR."
    if grep -w "${PULL_NUMBER}" "/home/prow/go/src/github.com/kyma-project/busola/resources/web/deployment.yaml"; then
        log::success "Pull request number found."
    else
        log::error "Pull request number not found. Please update deployment image in your PR."
        exit 1
    fi
fi


text:
using namespace std;

	const unsigned long m=10; //número de muestras
	const unsigned long n=5; // número de hebras
	double resultado_parcial[n]; //vector de resultados parciales

double f(double x)
{
	return 4.0/(1+x*x);
}

double calcular_integral_secuencial( )
{
	struct timespec inicio = ahora();
	double suma = 0.0 ; // inicializar suma
	for( unsigned long i = 0 ; i < m ; i++ ) // para cada i entre 0 y m− 1
		suma += f( ((i+0.5)/m )); //añadir f (xi ) a la suma actual
	struct timespec fin = ahora();
	cout << "Tiempo Secuencial: " << duracion( &inicio, &fin) << " seg." << endl;
	return suma/m ;	// devolver valor promedio de f

}

void * funcion_hebra( void *ih_void) //función que ejecuta cada hebra
{
	unsigned long ih = (unsigned long) ih_void; //índice de cada hebra
   	double sumap = 0.0;
	//cálculo de la suma parcial
	for(unsigned long i = ih; i < m; i+=n){
		sumap += f( ((i+0.5)/m));
	}
	resultado_parcial[ih] = sumap;
}

double calcular_integral_concurrente()
{
	struct timespec inicio = ahora();
	double Sum;
	//crear y lanzar n hebras, cada una ejecuta "funcion_concurrente"
	pthread_t id_hebra[n];
	for(unsigned i = 0; i < n; i++){
		pthread_create( &(id_hebra[i]),NULL,funcion_hebra,(void *) i);
	}
	//esperar (join) a que termine cada hebra, sumar su resultado
	for(unsigned i = 0; i < n; i++){
		unsigned long resultado;
		pthread_join(id_hebra[i], (void **) (&resultado));
		//devolver resultado completo
		Sum += resultado_parcial[i];
	}
	struct timespec fin = ahora();
	cout << "Tiempo Concurrente " << duracion( &inicio, &fin) << " seg." << endl;
	return Sum/m;

}

int main(int argc, char* argv[]){

	cout << "Integral secuencial " << calcular_integral_secuencial() << endl;

	cout << "Integral concurrente " << calcular_integral_concurrente() << endl;

}