text:
var Immutable = require('immutable')
var Map = require('immutable').Map
var List = require('immutable').List
var Reactor = require('../src/main').Reactor
var Store = require('../src/main').Store
var toImmutable = require('../src/immutable-helpers').toImmutable
var logging = require('../src/logging')

describe('Reactor', () => {
  it('should construct without \'new\'', () => {
    var reactor = Reactor()
    expect(reactor instanceof Reactor).toBe(true)
  })

  describe('Reactor with no initial state', () => {
    var checkoutActions
    var reactor
    var subtotalGetter
    var taxGetter
    var totalGetter

    beforeEach(() => {
      var itemStore = Store({
        getInitialState() {
          return toImmutable({
            all: [],
          })
        },

        initialize() {
          this.on('storeError', (state, payload) => {
            throw new Error('Store Error')
          })
          this.on('addItem', (state, payload) => {
            return state.update('all', items => {
              return items.push(Map({
                name: payload.name,
                price: payload.price,
              }))
            })
          })
        },
      })

      var taxPercentStore = Store({
        getInitialState() {
          return 0
        },

        initialize() {
          this.on('setTax', (state, payload) => {
            return payload
          })
        },
      })

      reactor = new Reactor({
        debug: true,
      })
      reactor.registerStores({
        'items': itemStore,
        'taxPercent': taxPercentStore,
      })

      subtotalGetter = [
        ['items', 'all'],
        (items) => {
          return items.reduce((total, item) => {
            return total + item.get('price')
          }, 0)
        },
      ]

      taxGetter = [
        subtotalGetter,
        ['taxPercent'],
        (subtotal, taxPercent) => {
          return (subtotal * (taxPercent / 100))
        },
      ]

      totalGetter = [
        subtotalGetter,
        taxGetter,
        (subtotal, tax) => {
          return Math.round(subtotal + tax, 2)
        },
      ]

      checkoutActions = {
        addItem(name, price) {
          reactor.dispatch('addItem', {
            name: name,
            price: price,
          })
        },

        setTaxPercent(percent) {
          reactor.dispatch('setTax', percent)
        },
      }
    })
    afterEach(() => {
      reactor.reset()
    })

    describe('initialization', () => {
      it('should initialize with the core level computeds', () => {
        expect(reactor.evaluateToJS(['items', 'all'])).toEqual([])

        expect(reactor.evaluate(['taxPercent'])).toEqual(0)
      })

      it('should return the whole state when calling reactor.evaluate([])', () => {
        var state = reactor.evaluate([])
        var expected = Map({
          items: Map({
            all: List(),
          }),
          taxPercent: 0,
        })

        expect(Immutable.is(state, expected)).toBe(true)
      })

      it('should return the whole state coerced to JS when calling reactor.evaluateToJS()', () => {
        var state = reactor.evaluateToJS([])
        var expected = {
          items: {
            all: [],
          },
          taxPercent: 0,
        }

        expect(state).toEqual(expected)
      })
    })

    describe('when dispatching a relevant action', () => {
      var item = {
        name: 'item 1',
        price: 10,
      }

      it('should update all state', () => {
        checkoutActions.addItem(item.name, item.price)
        expect(reactor.evaluateToJS(['items', 'all'])).toEqual([item])

        expect(reactor.evaluate(['taxPercent'])).toEqual(0)
        expect(reactor.evaluate(taxGetter)).toEqual(0)
        expect(reactor.evaluate(totalGetter)).toEqual(10)
      })

      it('should emit the state of the reactor to a handler registered with observe()', () => {
        var mockFn = jasmine.createSpy()
        reactor.observe(mockFn)

        checkoutActions.addItem(item.name, item.price)

        var expected = Immutable.fromJS({
          items: {
            all: [
              item,
            ],
          },
          taxPercent: 0,
        })

        var firstCallArg = mockFn.calls.argsFor(0)[0]

        expect(mockFn.calls.count()).toBe(1)
        expect(Immutable.is(firstCallArg, expected)).toBe(true)
      })

      it('should not emit to the outputStream if state does not change after a dispatch', () => {
        var mockFn = jasmine.createSpy()
        reactor.observe(mockFn)

        reactor.dispatch('noop', {})

        expect(mockFn.calls.count()).toEqual(0)
      })

      it('should raise an error if already dispatching another action', () => {
        reactor.observe([], state => reactor.dispatch('noop', {}))

        expect(() => checkoutActions.setTaxPercent(5)).toThrow(
          new Error('Dispatch may not be called while a dispatch is in progress'))
      })

      it('should keep working after it raised for dispatching while dispatching', () => {
        var unWatchFn = reactor.observe([], state => reactor.dispatch('noop', {}))

        expect(() => checkoutActions.setTaxPercent(5)).toThrow(
          new Error('Dispatch may not be called while a dispatch is in progress'))

        unWatchFn()

        expect(() => checkoutActions.setTaxPercent(5)).not.toThrow(
          new Error('Dispatch may not be called while a dispatch is in progress'))
      })

      it('should allow subsequent dispatches if a store throws an error', () => {
        try {
          reactor.dispatch('storeError')
        } catch (e) {} // eslint-disable-line

        expect(() => reactor.dispatch('setTax', 5)).not.toThrow()
      })

      it('should allow subsequent dispatches if a dispatched action doesnt cause state change', () => {
        reactor.dispatch('noop')

        expect(() => reactor.dispatch('setTax', 5)).not.toThrow()
      })

      it('should allow subsequent dispatches if an observer throws an error', () => {
        var unWatchFn = reactor.observe([], state => {
          throw new Error('observer error')
        })

        try {
          checkoutActions.setTaxPercent(1)
        } catch (e) {} // eslint-disable-line

        unWatchFn()

        expect(() => {
          checkoutActions.setTaxPercent(2)
        }).not.toThrow()
      })
    }) // when dispatching a relevant action

    describe('#observe', () => {
      it('should invoke a change handler if the specific keypath changes', () => {
        var mockFn = jasmine.createSpy()
        reactor.observe(['taxPercent'], mockFn)

        checkoutActions.setTaxPercent(5)

        expect(mockFn.calls.count()).toEqual(1)
        expect(mockFn.calls.argsFor(0)).toEqual([5])
      })
      it('should not invoke a change handler if another keypath changes', () => {
        var mockFn = jasmine.createSpy()
        reactor.observe(['taxPercent'], mockFn)

        checkoutActions.addItem('item', 1)

        expect(mockFn.calls.count()).toEqual(0)
      })
      it('should invoke a change handler if a getter value changes', () => {
        var mockFn = jasmine.createSpy()
        checkoutActions.addItem('item', 100)

        reactor.observe(totalGetter, mockFn)

        checkoutActions.setTaxPercent(5)

        expect(mockFn.calls.count()).toEqual(1)
        expect(mockFn.calls.argsFor(0)).toEqual([105])
      })

      it('should not invoke a change handler if a getters deps dont change', () => {
        var mockFn = jasmine.createSpy()
        reactor.observe(['taxPercent'], mockFn)

        checkoutActions.addItem('item', 100)

        expect(mockFn.calls.count()).toEqual(0)
      })

      it('should return an unwatch function', () => {
        var mockFn = jasmine.createSpy()
        checkoutActions.addItem('item', 100)

        var unwatch = reactor.observe(totalGetter, mockFn)

        unwatch()

        checkoutActions.setTaxPercent(5)

        expect(mockFn.calls.count()).toEqual(0)
      })
    })
  }) // Reactor with no initial state

  describe('reactor#reset', () => {
    var reactor

    beforeEach(() => {
      var standardStore = Store({
        getInitialState() {
          return toImmutable([])
        },

        initialize() {
          this.on('addItem', (state, item) => {
            return state.push(item)
          })
        },
      })

      var persistentStore = Store({
        getInitialState() {
          return toImmutable([])
        },

        initialize() {
          this.on('addItem', (state, item) => {
            return state.push(item)
          })
        },

        handleReset(state) {
          return state
        },
      })

      reactor = new Reactor({
        debug: true,
      })
      reactor.registerStores({
        standard: standardStore,
        persistent: persistentStore,
      })
    })

    afterEach(() => {
      reactor.reset()
    })

    it('should go back to initial state for normal stores', () => {
      var item = { foo: 'bar' }
      reactor.dispatch('addItem', item)

      expect(reactor.evaluateToJS(['standard'])).toEqual([item])

      reactor.reset()

      expect(reactor.evaluateToJS(['standard'])).toEqual([])
    })

    it('should respect the handleReset method for stores that override it', () => {
      var item = { foo: 'bar' }
      reactor.dispatch('addItem', item)

      expect(reactor.evaluateToJS(['persistent'])).toEqual([item])

      reactor.reset()

      expect(reactor.evaluateToJS(['persistent'])).toEqual([item])
    })
  })

  describe('when a reactor is observing mutable values', () => {
    var reactor
    var observeSpy

    beforeEach(() => {
      observeSpy = jasmine.createSpy('observe')

      var mapStore = Store({
        getInitialState() {
          return toImmutable({})
        },

        initialize() {
          this.on('set', (state, payload) => {
            return state.set(payload.key, payload.value)
          })
        },
      })

      var keyStore = Store({
        getInitialState() {
          return 'foo'
        },

        initialize() {
          this.on('setKey', (state, payload) => {
            return payload
          })
        },
      })

      reactor = new Reactor({
        debug: true,
      })
      reactor.registerStores({
        mapStore: mapStore,
        keyStore: keyStore,
      })
    })

    afterEach(() => {
      reactor.reset()
    })

    it('should go back to initial state for normal stores', () => {
      function Foo(val) {
        this.val = val
      }

      var item = new Foo('bar')
      var item2 = new Foo('baz')

      var getter = [
        ['mapStore'],
        ['keyStore'],
        (map, key) => {
          return map.get(key)
        },
      ]

      reactor.evaluate(getter)

      reactor.observe(getter, (fooValue) => {
        observeSpy(fooValue)
      })

      reactor.dispatch('set', {
        key: 'foo',
        value: item,
      })

      expect(observeSpy.calls.count()).toBe(1)

      reactor.dispatch('set', {
        key: 'foo',
        value: item2,
      })
      expect(observeSpy.calls.count()).toBe(2)
    })
  })

  describe('a reactor with a store that has `null` as its initial state', () => {
    var reactor

    beforeEach(() => {
      var nullStateStore = new Store({
        getInitialState() {
          return null
        },
        initialize() {
          this.on('set', (_, val) => val)
        },
      })

      reactor = new Reactor({
        debug: true,
      })
      reactor.registerStores({
        test: nullStateStore,
      })
    })

    afterEach(() => {
      reactor.reset()
    })

    it('the store should respond to a registered action', () => {
      reactor.dispatch('set', 'foo')
      expect(reactor.evaluate(['test'])).toBe('foo')
    })

    it('the store should have the same initial state for an action it doesnt handle', () => {
      reactor.dispatch('unknown', 'foo')
      expect(reactor.evaluate(['test'])).toBe(null)
    })
  })

  describe('when debug is true and a store has a handler for an action but returns undefined', () => {
    var reactor

    beforeEach(() => {
      var undefinedStore = new Store({
        getInitialState() {
          return 1
        },
        initialize() {
          this.on('set', (_, val) => undefined)
        },
      })

      reactor = new Reactor({
        debug: true,
      })
      reactor.registerStores({
        test: undefinedStore,
      })
    })

    afterEach(() => {
      reactor.reset()
    })

    it('should throw an error', function() {
      expect(function() {
        reactor.dispatch('set', 'foo')
      }).toThrow()
    })
  })

  describe('when debug is true and a store has a handler for an action but throws', () => {
    var reactor

    beforeEach(() => {
      spyOn(logging, 'dispatchError')
      var throwingStore = new Store({
        getInitialState() {
          return 1
        },
        initialize() {
          this.on('set', (_, val) => {throw new Error('Error during action handling')})
        },
      })

      reactor = new Reactor({
        debug: true,
      })
      reactor.registerStores({
        test: throwingStore,
      })
    })

    afterEach(() => {
      reactor.reset()
    })

    it('should log and throw an error', function() {
      expect(function() {
        reactor.dispatch('set', 'foo')
      }).toThrow(new Error('Error during action handling'))
      expect(logging.dispatchError).toHaveBeenCalledWith('Error during action handling')
    })
  })

  describe('#registerStores', () => {
    var reactor

    afterEach(() => {
      reactor.reset()
    })

    describe('when another store is already registered for the same id', () => {
      var store1
      var store2

      beforeEach(() => {
        spyOn(console, 'warn')

        store1 = new Store()
        store2 = new Store()

        reactor = new Reactor({
          debug: true,
        })
        reactor.registerStores({
          store1: store1,
        })
      })

      it('should warn', function() {
        reactor.registerStores({
          store1: store2,
        })
        /* eslint-disable no-console */
        expect(console.warn).toHaveBeenCalled()
        /* eslint-enable no-console */
      })
    })

    describe('when the stores getInitialState method returns a non immutable object', () => {
      var store1

      beforeEach(() => {
        store1 = new Store({
          getInitialState() {
            return {
              foo: 'bar',
            }
          },
        })

        reactor = new Reactor({
          debug: true,
        })
      })

      it('should throw an error', function() {
        expect(function() {
          reactor.registerStores({
            store1: store1,
          })
        }).toThrow()
      })
    })

    describe('when calling registerStores with an observer', () => {
      var store1
      var observeSpy

      beforeEach(() => {
        observeSpy = jasmine.createSpy()

        store1 = new Store({
          getInitialState() {
            return 'foo'
          },
          initialize() {
            this.on('set', (_, val) => val)
          },
        })

        reactor = new Reactor({
          debug: true,
        })

        reactor.observe(['test'], observeSpy)
      })

      it('should notify observers immediately', function() {
        var notify = true
        reactor.registerStores({
          test: store1,
        }, notify)

        expect(observeSpy.calls.count()).toEqual(1)
        expect(observeSpy).toHaveBeenCalledWith('foo')
      })
    })
  })

  describe('#registerStore', () => {
    var reactor
    var store1

    beforeEach(() => {
      store1 = new Store({
        getInitialState() {
          return 'foo'
        },
      })

      reactor = new Reactor({
        debug: true,
      })
    })

    afterEach(() => {
      reactor.reset()
    })

    it('it should register a store by id', () => {
      reactor.registerStore('test', store1)
      expect(reactor.evaluate(['test'])).toBe('foo')
    })
  })

  describe('#reset', () => {
    var reactor

    describe('when a store doesnt define a handleReset method', () => {
      var store1

      beforeEach(() => {
        store1 = new Store({
          getInitialState() {
            return 'foo'
          },
          initialize() {
            this.on('set', (_, val) => val)
          },
        })

        reactor = new Reactor({
          debug: true,
        })

        reactor.registerStores({
          test: store1,
        })
      })

      it('should fallback to the getInitialState', () => {
        reactor.dispatch('set', 'bar')

        expect(reactor.evaluate(['test'])).toBe('bar')

        reactor.reset()

        expect(reactor.evaluate(['test'])).toBe('foo')
      })
    })

    describe('when a store defines a handleReset method', () => {
      var store1

      beforeEach(() => {
        store1 = new Store({
          getInitialState() {
            return 'foo'
          },
          initialize() {
            this.on('set', (_, val) => val)
          },
          handleReset() {
            return 'reset'
          },
        })

        reactor = new Reactor({
          debug: true,
        })

        reactor.registerStores({
          test: store1,
        })
      })

      it('should fallback to the getInitialState', () => {
        reactor.dispatch('set', 'bar')

        expect(reactor.evaluate(['test'])).toBe('bar')

        reactor.reset()

        expect(reactor.evaluate(['test'])).toBe('reset')
      })
    })

    describe('when the handleReset method returns undefined', () => {
      var store1

      beforeEach(() => {
        store1 = new Store({
          getInitialState() {
            return 'foo'
          },
          initialize() {
            this.on('set', (_, val) => val)
          },
          handleReset() {
          },
        })

        reactor = new Reactor({
          debug: true,
        })

        reactor.registerStores({
          test: store1,
        })
      })

      it('should throw an error', () => {
        expect(function() {
          reactor.reset()
        }).toThrow()
      })
    })

    describe('when the handleReset method returns a non immutable object', () => {
      var store1

      beforeEach(() => {
        store1 = new Store({
          getInitialState() {
            return 'foo'
          },
          initialize() {
            this.on('set', (_, val) => val)
          },
          handleReset() {
            return {
              foo: 'bar',
            }
          },
        })

        reactor = new Reactor({
          debug: true,
        })

        reactor.registerStores({
          test: store1,
        })
      })

      it('should throw an error', () => {
        expect(function() {
          reactor.reset()
        }).toThrow()
      })
    })
  })

  describe('serialize/loadState', () => {
    var reactor
    var stores

    beforeEach(() => {
      reactor = new Reactor({
        debug: true,
      })

      stores = {
        mapStore: Store({
          getInitialState() {
            return Immutable.Map([
              [1, 'one'],
              [2, 'two'],
            ])
          },
          initialize() {
            this.on('clear', state => null)
          },
          serialize(state) {
            if (!state) {
              return state
            }
            return state.entrySeq().toJS()
          },
          deserialize(state) {
            return Immutable.Map(state)
          },
        }),

        stringStore: Store({
          getInitialState() {
            return 'foo'
          },
          initialize() {
            this.on('clear', state => null)
          },
        }),

        listStore: Store({
          getInitialState() {
            return toImmutable([1, 2, 'three'])
          },
          initialize() {
            this.on('clear', state => null)
          },
        }),

        booleanStore: Store({
          getInitialState() {
            return true
          },
          initialize() {
            this.on('clear', state => null)
          },
        }),
      }

      reactor.registerStores(stores)
    })

    afterEach(() => {
      reactor.reset()
    })

    it('should serialize -> loadState effectively', () => {
      var serialized = reactor.serialize()
      var reactor2 = new Reactor()
      reactor2.registerStores(stores)
      reactor2.dispatch('clear')

      expect(Immutable.is(reactor.evaluate([]), reactor2.evaluate([]))).toBe(false)

      reactor2.loadState(serialized)
      expect(Immutable.is(reactor.evaluate([]), reactor2.evaluate([]))).toBe(true)
    })

    it('should allow loading of state from outside source', () => {
      reactor.loadState({
        stringStore: 'bar',
        listStore: [4, 5, 6],
      })

      expect(reactor.evaluateToJS([])).toEqual({
        mapStore: {
          1: 'one',
          2: 'two',
        },
        stringStore: 'bar',
        listStore: [4, 5, 6],
        booleanStore: true,
      })
    })

    it('should notify observer', () => {
      var mockFn = jasmine.createSpy()
      var serialized = reactor.serialize()
      var reactor2 = new Reactor()
      reactor2.registerStores(stores)
      reactor2.dispatch('clear')

      reactor2.observe(['stringStore'], mockFn)

      reactor2.loadState(serialized)

      var firstCallArg = mockFn.calls.argsFor(0)

      expect(mockFn.calls.count()).toBe(1)
      expect(Immutable.is(firstCallArg, 'foo'))
    })

    describe('when extending Reactor#serialize and Reactor#loadState', () => {
      var loadStateSpy = jasmine.createSpy('loadState')
      var serializeSpy = jasmine.createSpy('serialize')

      it('should respect the extended methods', () => {
        class MyReactor extends Reactor {
          constructor() {
            super(arguments)
          }

          serialize(state) {
            serializeSpy(state)
            var serialized = super(state)
            return JSON.stringify(serialized)
          }

          loadState(state) {
            loadStateSpy(state)
            super(JSON.parse(state))
          }
        }
        var reactor1 = new MyReactor()
        reactor1.registerStores(stores)
        var reactor2 = new MyReactor()
        reactor2.registerStores(stores)

        var serialized = reactor1.serialize()

        reactor2.dispatch('clear')

        expect(Immutable.is(reactor1.evaluate([]), reactor2.evaluate([]))).toBe(false)

        reactor2.loadState(serialized)
        expect(Immutable.is(reactor.evaluate([]), reactor2.evaluate([]))).toBe(true)

        expect(serializeSpy.calls.count()).toBe(1)
        expect(loadStateSpy.calls.count()).toBe(1)
      })
    })

    describe('when a store returns undefined from serialize/deserialize', () => {
      beforeEach(() => {
        reactor = new Reactor()
        reactor.registerStores({
          serializableStore: Store({
            getInitialState() {
              return 'real'
            },
          }),

          ignoreStore: Store({
            getInitialState() {
              return 'ignore'
            },
            serialize() {
              return
            },
            deserialize() {
              return
            },
          }),
        })
      })

      it('should not have an entry in the serialized app state', () => {
        var serialized = reactor.serialize()
        expect(serialized).toEqual({
          serializableStore: 'real',
        })
      })

      it('should not load state for a store where deserialize returns undefined', () => {
        var serialized = {
          serializableStore: 'changed',
          ignoreStore: 'changed',
        }
        reactor.loadState(serialized)
        expect(reactor.evaluateToJS([])).toEqual({
          serializableStore: 'changed',
          ignoreStore: 'ignore',
        })
      })
    })
  })

  describe('#batch', () => {
    var reactor

    beforeEach(() => {
      reactor = new Reactor({
        debug: true,
      })
      reactor.registerStores({
        listStore: Store({
          getInitialState() {
            return toImmutable([])
          },
          initialize() {
            this.on('add', (state, item) => state.push(toImmutable(item)))
            this.on('error', (state, payload) => {
              throw new Error('store error')
            })
          },
        }),
      })
    })

    afterEach(() => {
      reactor.reset()
    })

    it('should execute multiple dispatches within the queue function', () => {
      reactor.batch(() => {
        reactor.dispatch('add', 'one')
        reactor.dispatch('add', 'two')
      })

      expect(reactor.evaluateToJS(['listStore'])).toEqual(['one', 'two'])
    })

    it('should notify observers only once', () => {
      var observeSpy = jasmine.createSpy()

      reactor.observe(['listStore'], list => observeSpy(list.toJS()))

      reactor.batch(() => {
        reactor.dispatch('add', 'one')
        reactor.dispatch('add', 'two')
      })

      expect(observeSpy.calls.count()).toBe(1)

      var firstCallArg = observeSpy.calls.argsFor(0)[0]

      expect(observeSpy.calls.count()).toBe(1)
      expect(firstCallArg).toEqual(['one', 'two'])
    })

    it('should allow nested batches and only notify observers once', () => {
      var observeSpy = jasmine.createSpy()

      reactor.observe(['listStore'], list => observeSpy(list.toJS()))

      reactor.batch(() => {
        reactor.dispatch('add', 'one')
        reactor.batch(() => {
          reactor.dispatch('add', 'two')
          reactor.dispatch('add', 'three')
        })
      })

      expect(observeSpy.calls.count()).toBe(1)

      var firstCallArg = observeSpy.calls.argsFor(0)[0]

      expect(observeSpy.calls.count()).toBe(1)
      expect(firstCallArg).toEqual(['one', 'two', 'three'])
    })

    it('should not allow dispatch to be called from an observer', () => {
      reactor.observe([], state => reactor.dispatch('noop', {}))

      expect(() => {
        reactor.batch(() => {
          reactor.dispatch('add', 'one')
          reactor.dispatch('add', 'two')
        })
      }).toThrow(
        new Error('Dispatch may not be called while a dispatch is in progress'))
    })

    it('should keep working after it raised for dispatching while dispatching', () => {
      var unWatchFn = reactor.observe([], state => reactor.dispatch('noop', {}))

      expect(() => {
        reactor.batch(() => {
          reactor.dispatch('add', 'one')
          reactor.dispatch('add', 'two')
        })
      }).toThrow(
        new Error('Dispatch may not be called while a dispatch is in progress'))

      unWatchFn()

      expect(() => {
        reactor.batch(() => {
          reactor.dispatch('add', 'one')
          reactor.dispatch('add', 'two')
        })
      }).not.toThrow(
        new Error('Dispatch may not be called while a dispatch is in progress'))
    })

    it('should allow subsequent dispatches if an error is raised by a store handler', () => {
      expect(() => {
        reactor.batch(() => {
          reactor.dispatch('add', 'one')
          reactor.dispatch('error')
        })
      }).toThrow(new Error('store error'))

      expect(() => {
        reactor.dispatch('add', 'three')
      }).not.toThrow()
    })

    it('should allow subsequent dispatches if batched action doesnt cause state change', () => {
      reactor.batch(() => {
        reactor.dispatch('noop')
      })

      expect(() => reactor.dispatch('add', 'one')).not.toThrow()
    })

    it('should allow subsequent dispatches if an error is raised in an observer', () => {
      var unWatchFn = reactor.observe([], state => {
        throw new Error('observe error')
      })

      expect(() => {
        reactor.batch(() => {
          reactor.dispatch('add', 'one')
          reactor.dispatch('add', 'two')
        })
      }).toThrow(
        new Error('observe error'))

      unWatchFn()

      expect(() => {
        reactor.dispatch('add', 'three')
      }).not.toThrow()
    })
  })
})


text:
 'use strict';

// const util      = require('util');
const path      = require('path');
const HTMLRenderer = require('./HTMLRenderer');

const nunjucks = require('nunjucks');

const _nunjuck_env = Symbol('id');

const getMounted = (dir) => {
    if (typeof dir === 'string') return dir;
    else return dir.src;
};

module.exports = class NunjucksRenderer extends HTMLRenderer {
    constructor() {
        super(".html.njk", /^(.*\.html)\.(njk)$/);
        this[_nunjuck_env] = undefined;
    }

    njkenv(config) {
        if (this[_nunjuck_env]) return this[_nunjuck_env];
        // console.log(`njkenv layoutDirs ${util.inspect(config.layoutDirs)}`);
        // Detect if config is not set
        if (!config) throw new Error(`render-nunjucks no config`);

        // Get the paths for both the Layouts and Partials directories,
        // because with Nunjucks we are storing macros files in some
        // layouts directories.
        const layoutsMounted = config.layoutDirs.map(getMounted);
        const partialsMounted = config.partialsDirs.map(getMounted);
        const loadFrom = layoutsMounted.concat(partialsMounted);

        // console.log(`njkenv `, loadFrom);

        // An open question is whether to create a custom Loader
        // class to integrate Nunjucks better with FileCache.  Clearly
        // Nunjucks can handle files being updated behind the scene.

        this[_nunjuck_env] = new nunjucks.Environment(
            // Using watch=true requires installing chokidar
            new nunjucks.FileSystemLoader(loadFrom, { watch: false }),
                // config.layoutDirs.concat(config.partialsDirs), { watch: false }),
            {
                autoescape: false
            }
        );
        // console.log(`njkenv`, this[_nunjuck_env]);
        return this[_nunjuck_env];
    }

    async render(text, metadata) {
        try {
            let env = this.njkenv(metadata.config);
            return env.renderString(text, metadata);
            // nunjucks.configure({ autoescape: false });
            // return nunjucks.renderString(text, metadata);
        } catch(e) {
            var docpath = metadata.document ? metadata.document.path : "unknown";
            var errstack = e.stack ? e.stack : e;
            throw new Error(`Error with Nunjucks in file ${docpath} ${errstack}`);
        }
    }

    renderSync(text, metadata) {
        try {
            if (!metadata.config) {
                // This condition can cause a problem in this.njkenv
                throw new Error(`render-nunjucks renderSync no config`);
            }
            let env = this.njkenv(metadata.config);
            return env.renderString(text, metadata);
            // nunjucks.configure({ autoescape: false });
            // return nunjucks.renderString(text, metadata);
        } catch(e) {
            var docpath = metadata.document ? metadata.document.path : "unknown";
            var errstack = e.stack ? e.stack : e;
            throw new Error(`Error with Nunjucks in file ${docpath} ${errstack}`);
        }
    }

    /**
     * We cannot allow PHP code to run through Mahabhuta.
     */
    doMahabhuta(fpath) {
        return true;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package au.com.mineauz.minigames.script;

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

class ScriptCollectionMapImpl<E extends ScriptReference> extends ScriptCollection {
    private final Map<String, E> map;

    public ScriptCollectionMapImpl(Map<String, E> map) {
        this.map = map;
    }

    @Override
    public ScriptReference getValue(String key) throws IllegalArgumentException, NoSuchElementException {
        ScriptReference ref = map.get(key);
        if (ref == null) {
            throw new NoSuchElementException();
        }

        return ref;
    }

    @Override
    public Collection<String> getKeys() {
        return map.keySet();
    }
}


text:
<resources>
    <color name="colorPrimary">#016AA8</color>
    <color name="colorPrimaryDark">#01579B</color>
</resources>


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.drools.lang;

import java.util.HashMap;
import java.util.Map;

import org.drools.lang.descr.PackageDescr;
import org.drools.rule.builder.DroolsCompilerComponentFactory;
import org.mvel2.integration.impl.MapVariableResolverFactory;
import org.mvel2.optimizers.OptimizerFactory;
import org.mvel2.templates.SimpleTemplateRegistry;
import org.mvel2.templates.TemplateCompiler;
import org.mvel2.templates.TemplateRegistry;
import org.mvel2.templates.TemplateRuntime;
import org.mvel2.templates.res.Node;

/**
 * Dumps a PackageDescr into a DRL String
 */
public class DrlDumper  {

    protected final TemplateRegistry REPORT_REGISTRY = new SimpleTemplateRegistry();

    protected ExpressionRewriter mvel = new MVELDumper();

    public DrlDumper() {
        OptimizerFactory.setDefaultOptimizer( "reflective" );

        REPORT_REGISTRY.addNamedTemplate( "drl",
                                          TemplateCompiler.compileTemplate( DrlDumper.class.getResourceAsStream( "drl.mvel" ),
                                                                            (Map<String, Class< ? extends Node>>) null ) );

        /**
         * Process these templates
         */
        TemplateRuntime.execute( REPORT_REGISTRY.getNamedTemplate( "drl" ),
                                 null,
                                 REPORT_REGISTRY );
    }

    public String dump( final PackageDescr pkg ) {
        Map<String, Object> context = new HashMap<String, Object>();
        context.put( "pkg",
                     pkg );
        context.put( "mvel",
                     mvel );

        return (String) TemplateRuntime.execute( REPORT_REGISTRY.getNamedTemplate( "drl" ),
                                                 null,
                                                 new MapVariableResolverFactory( context ),
                                                 REPORT_REGISTRY );
    }

}


text:
import sys
import numpy as np
from scipy.stats import pearsonr

def calculate_minor_allele_frequency(genotypes):
    """
    Returns a dataframe of the allele frequencies

    Parameters
    ----------
    genotypes : a genotype dataframe with polymorphisms going row-wise
    """
    try:
        maf = genotypes.sum(axis=1) / (2 * genotypes.shape[1])
    except IndexError:
        maf = genotypes.sum() / (2 * len(genotypes))
    return(maf)

def calculate_ld(genotypes, snp):
    """ Calculates SNP linkage disquilibrium

    Parameters
    ----------
    genotypes : a genotype dataframe with polymorphisms going rowise and samples
    columnwise.
    snp: snp-identifier

    Returns
    -------
    A vector of linkage disequilibrium

    """
    ld = genotypes.corrwith(genotypes.ix[snp, :], axis=1)
    ld[np.isnan(ld.values)] = 0
    ld = np.sqrt(ld ** 2)
    return(ld)

def regionParse(string):
    """
    Parses region:start_position-end_position, returns a tuple
    >>> regionParse('chr4:200000-200100')
    ('chr4', 200000, 200100)
    """
    start = string[string.find(':') + 1:string.find('-')]
    end = string[string.find('-') + 1:]
    start = start.replace(',', '')
    end = end.replace(',', '')

    try:
        start = int(start)
        end = int(end)
    except ValueError:
        sys.exit()
    return(string[0:string.find(':')], start, end)

if __name__ == "__main__":
    import doctest
    doctest.testmod()


text:
package org.fiteagle.adapters.tosca.model;

/**
 * Created by dne on 15.10.15.
 */
public class Location {

    private String name;
    private String id;
    private int version;
    private double latitude;
    private double longitude;

    public String getName() {
        return name;
    }

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

    public String getId() {
        return id;
    }

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

    public int getVersion() {
        return version;
    }

    public void setVersion(int version) {
        this.version = version;
    }

    public double getLatitude() {
        return latitude;
    }

    public void setLatitude(double latitude) {
        this.latitude = latitude;
    }

    public double getLongitude() {
        return longitude;
    }

    public void setLongitude(double longitude) {
        this.longitude = longitude;
    }
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<resources>
  <resource name="blockplace" type="RESOURCE"/>
  <resource name="linecheck" type="RESOURCE"/>
  <resource name="lineclear" type="RESOURCE"/>
</resources>


text:
<?php

namespace Acme\FindMartialBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Acme\FindMartialBundle\Entity\AddServ;
use Acme\FindMartialBundle\Form\AddServType;
use Symfony\Component\Security\Acl\Domain\ObjectIdentity;
use Symfony\Component\Security\Acl\Domain\UserSecurityIdentity;
use Symfony\Component\Security\Acl\Permission\MaskBuilder;

/**
 * AddServ controller.
 *
 * @Route("/addserv")
 */
class AddServController extends Controller
{
    /**
     * Lists all AddServ entities.
     *
     * @Route("/", name="addserv")
     * @Method("GET")
     * @Template()
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('AcmeFindMartialBundle:AddServ')->findAll();

        return array(
            'entities' => $entities,
        );
    }

    /**
     * Creates a new AddServ entity.
     *
     * @Route("/", name="addserv_create")
     * @Method("POST")
     * @Template("AcmeFindMartialBundle:AddServ:new.html.twig")
     */
    public function createAction(Request $request)
    {
        $entity  = new AddServ();
        $form = $this->createForm(new AddServType(), $entity);
        $form->bind($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            // creating the ACL
            $aclProvider = $this->get('security.acl.provider');
            $objectIdentity = ObjectIdentity::fromDomainObject($entity);
            $acl = $aclProvider->createAcl($objectIdentity);

            // retrieving the security identity of the currently logged-in user
            $securityContext = $this->get('security.context');
            $user = $securityContext->getToken()->getUser();
            $securityIdentity = UserSecurityIdentity::fromAccount($user);

            // grant owner access
            $acl->insertObjectAce($securityIdentity, MaskBuilder::MASK_OWNER);
            $aclProvider->updateAcl($acl);

            return $this->redirect($this->generateUrl('addserv', array('id' => $entity->getId())));
        }

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Displays a form to create a new AddServ entity.
     *
     * @Route("/new", name="addserv_new")
     * @Method("GET")
     * @Template()
     */
    public function newAction()
    {
        $entity = new AddServ();
        $form   = $this->createForm(new AddServType(), $entity);

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Displays a form to edit an existing AddServ entity.
     *
     * @Route("/{id}/edit", name="addserv_edit")
     * @Method("GET")
     * @Template()
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('AcmeFindMartialBundle:AddServ')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find AddServ entity.');
        }

        $securityContext = $this->get('security.context');

        // check for edit access
        if (false === $securityContext->isGranted('EDIT', $entity)) {
            throw new AccessDeniedException();
        }

        $editForm = $this->createForm(new AddServType(), $entity);
        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Edits an existing AddServ entity.
     *
     * @Route("/{id}", name="addserv_update")
     * @Method("PUT")
     * @Template("AcmeFindMartialBundle:AddServ:edit.html.twig")
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('AcmeFindMartialBundle:AddServ')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find AddServ entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createForm(new AddServType(), $entity);
        $editForm->bind($request);

        if ($editForm->isValid()) {
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('addserv_edit', array('id' => $id)));
        }

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Deletes a AddServ entity.
     *
     * @Route("/{id}", name="addserv_delete")
     * @Method("DELETE")
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->bind($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('AcmeFindMartialBundle:AddServ')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find AddServ entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('addserv'));
    }

    /**
     * Creates a form to delete a AddServ entity by id.
     *
     * @param mixed $id The entity id
     *
     * @return Symfony\Component\Form\Form The form
     */
    private function createDeleteForm($id)
    {
        return $this->createFormBuilder(array('id' => $id))
            ->add('id', 'hidden')
            ->getForm()
        ;
    }
}


text:
/**
 * Renders a MDL **content** component.
 */

import React, { PropTypes } from 'react';
import classNames from 'classnames';

/** Props **/
const propTypes = {
  tag: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.object,
    PropTypes.func
  ])
};
const defaultProps = {
  tag: 'div'
};

/** Component **/
const Content = (props) => {
  const {
    tag,
    className,
    children,

    // "kind of content"
    layout,
    listItemPrimary,
    listItemSecondary,

    // other props
    ...otherProps
  } = props;
  const classes = classNames({
    'mdl-layout__content': layout,
    'mdl-list__item-primary-content': listItemPrimary,
    'mdl-list__item-secondary-content': listItemSecondary
  }, className);
  const _props = Object.assign({}, otherProps, {className: classes});

  return React.createElement(tag, _props, children)
}

/** exports **/
Content.propTypes = propTypes;
Content.defaultProps = defaultProps;
export default Content;


text: void HexDump(const void *, std::size_t, std::ostream& = std::cout);


text:
/* ========================================================================
	Project  Name			: Win32 Lightweight  Class Library Test
	Module Name				: Main Header
	Create					: 1996-06-01(Sat)
	Update					: 2012-04-02(Mon)
	Copyright				: H.Shirouzu
	Reference				:
	======================================================================== */

#ifndef TLIB_H
#define TLIB_H

#ifndef STRICT
#define STRICT
#endif

// for debug allocator (like a efence)
//#define REPLACE_DEBUG_ALLOCATOR
#ifdef REPLACE_DEBUG_ALLOCATOR
#define malloc  valloc
#define calloc  vcalloc
#define realloc vrealloc
#define free    vfree
#define strdup  vstrdup
#define wcsdup  vwcsdup
extern "C" {
void *valloc(size_t size);
void *vcalloc(size_t num, size_t ele);
void *vrealloc(void *d, size_t size);
void vfree(void *d);
char *vstrdup(const char *s);
//unsigned short *vwcsdup(const unsigned short *s);
}
#endif

/* for crypto api */
#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0600
#endif

/* for new version VC */
#if _MSC_VER >= 1400
#pragma warning ( disable : 4996 )
#else
#define LONG_PTR LONG
#endif
#pragma warning ( disable : 4355 )

#include <windows.h>
#include <windowsx.h>
#include <stdio.h>
#include <stdlib.h>

#include "commctrl.h"
#include <regstr.h>
#include <shlobj.h>
#include <tchar.h>
#include "tmisc.h"
#include "tapi32ex.h"
#include "tapi32v.h"
#include "twinsock.h"
//#include "tapi32u8.h"	 /* describe last line */

extern DWORD TWinVersion;	// define in tmisc.cpp

#define WINEXEC_ERR_MAX		31
#define TLIB_SLEEPTIMER		32000

#define TLIB_CRYPT		0x00000001
#define TLIB_PROTECT	0x00000002
#define TLIB_WIN32V		0x00000004

#define IsNewShell()	(LOBYTE(LOWORD(TWinVersion)) >= 4)

#define IsWin31()		(LOBYTE(LOWORD(TWinVersion)) == 3 && HIBYTE(LOWORD(TWinVersion)) < 20)
#define IsWin95()		(LOBYTE(LOWORD(TWinVersion)) >= 4 && TWinVersion >= 0x80000000)

#define IsWinNT350()	(LOBYTE(LOWORD(TWinVersion)) == 3 && TWinVersion < 0x80000000 \
							&& HIBYTE(LOWORD(TWinVersion)) == 50)
#define IsWinNT()		(LOBYTE(LOWORD(TWinVersion)) >= 4 && TWinVersion < 0x80000000)
#define IsWin2K()		(LOBYTE(LOWORD(TWinVersion)) >= 5 && TWinVersion < 0x80000000)
#define IsWinXP()		((LOBYTE(LOWORD(TWinVersion)) >= 6 || LOBYTE(LOWORD(TWinVersion)) == 5 \
							&& HIBYTE(LOWORD(TWinVersion)) >= 1) && TWinVersion < 0x80000000)
#define IsWinVista()	(LOBYTE(LOWORD(TWinVersion)) >= 6 && TWinVersion < 0x80000000)
#define IsWin7()		((LOBYTE(LOWORD(TWinVersion)) >= 7 || LOBYTE(LOWORD(TWinVersion)) == 6 \
							&& HIBYTE(LOWORD(TWinVersion)) >= 1) && TWinVersion < 0x80000000)

#define IsLang(lang)	(PRIMARYLANGID(LANGIDFROMLCID(GetThreadLocale())) == lang)

#define ALIGN_SIZE(all_size, block_size) (((all_size) + (block_size) -1) \
										 / (block_size) * (block_size))

#define ALIGN_BLOCK(size, align_size) (((size) + (align_size) -1) / (align_size))

#define BUTTON_CLASS		"BUTTON"
#define COMBOBOX_CLASS		"COMBOBOX"
#define EDIT_CLASS			"EDIT"
#define LISTBOX_CLASS		"LISTBOX"
#define MDICLIENT_CLASS		"MDICLIENT"
#define SCROLLBAR_CLASS		"SCROLLBAR"
#define STATIC_CLASS		"STATIC"

#define MAX_WPATH		32000
#define MAX_PATH_EX		(MAX_PATH * 8)
#define MAX_PATH_U8		(MAX_PATH * 3)
#define MAX_FNAME_LEN	255

#define BITS_OF_BYTE	8
#define BYTE_NUM		256

#ifndef EM_SETTARGETDEVICE
#define COLOR_BTNFACE           15
#define COLOR_3DFACE            COLOR_BTNFACE
#define EM_SETBKGNDCOLOR		(WM_USER + 67)
#define EM_SETTARGETDEVICE		(WM_USER + 72)
#endif

#ifndef WM_COPYGLOBALDATA
#define WM_COPYGLOBALDATA	0x0049
#endif

#ifndef CSIDL_PROGRAM_FILES
#define CSIDL_LOCAL_APPDATA		0x001c
#define CSIDL_WINDOWS			0x0024
#define CSIDL_PROGRAM_FILES		0x0026
#endif
#ifndef CSIDL_PROGRAM_FILESX86
#define CSIDL_PROGRAM_FILESX86	0x002a
#endif

#ifndef CSIDL_APPDATA
#define CSIDL_APPDATA  0x1a
#endif

#ifndef CSIDL_COMMON_APPDATA
#define CSIDL_COMMON_APPDATA  0x23
#endif

#ifndef SHCNF_PATHW
#define SHCNF_PATHW 0x0005
#endif

#ifndef BCM_FIRST
#define BCM_FIRST     0x1600
#define IDI_SHIELD    1022
#endif

#ifndef BCM_SETSHIELD
#define BCM_SETSHIELD (BCM_FIRST + 0x000C)
#endif

#ifndef PROCESS_MODE_BACKGROUND_BEGIN
#define PROCESS_MODE_BACKGROUND_BEGIN 0x00100000
#define PROCESS_MODE_BACKGROUND_END   0x00200000
#endif

#ifndef SM_XVIRTUALSCREEN
#define SM_XVIRTUALSCREEN	76
#define SM_YVIRTUALSCREEN	77
#define SM_CXVIRTUALSCREEN	78
#define SM_CYVIRTUALSCREEN	79
#endif

#ifndef SPI_GETFOREGROUNDLOCKTIMEOUT
#define SPI_GETFOREGROUNDLOCKTIMEOUT 0x2000
#define SPI_SETFOREGROUNDLOCKTIMEOUT 0x2001
#endif

#ifndef SPI_GETMESSAGEDURATION
#define SPI_GETMESSAGEDURATION	0x2016
#define SPI_SETMESSAGEDURATION	0x2017
#endif

#ifdef _WIN64
#define SetClassLongA	SetClassLongPtrA
#define SetClassLongW	SetClassLongPtrW
#define GetClassLongA	GetClassLongPtrA
#define GetClassLongW	GetClassLongPtrW
#define SetWindowLongA	SetWindowLongPtrA
#define SetWindowLongW	SetWindowLongPtrW
#define GetWindowLongA	GetWindowLongPtrA
#define GetWindowLongW	GetWindowLongPtrW
#define GCL_HICON		GCLP_HICON
#define GCL_HCURSOR		GCLP_HCURSOR
#define GWL_WNDPROC		GWLP_WNDPROC
#define DWL_MSGRESULT	DWLP_MSGRESULT
#else
#define DWORD_PTR		DWORD
#endif

struct WINPOS {
	int		x;
	int		y;
	int		cx;
	int		cy;
};

#if _MSC_VER <= 1200
typedef struct {
  DWORD        bV5Size;
  LONG         bV5Width;
  LONG         bV5Height;
  WORD         bV5Planes;
  WORD         bV5BitCount;
  DWORD        bV5Compression;
  DWORD        bV5SizeImage;
  LONG         bV5XPelsPerMeter;
  LONG         bV5YPelsPerMeter;
  DWORD        bV5ClrUsed;
  DWORD        bV5ClrImportant;
  DWORD        bV5RedMask;
  DWORD        bV5GreenMask;
  DWORD        bV5BlueMask;
  DWORD        bV5AlphaMask;
  DWORD        bV5CSType;
  CIEXYZTRIPLE bV5Endpoints;
  DWORD        bV5GammaRed;
  DWORD        bV5GammaGreen;
  DWORD        bV5GammaBlue;
  DWORD        bV5Intent;
  DWORD        bV5ProfileData;
  DWORD        bV5ProfileSize;
  DWORD        bV5Reserved;
} BITMAPV5HEADER, *PBITMAPV5HEADER;
#define CF_DIBV5 17
#endif

enum DlgItemFlags {
	NONE_FIT	= 0x000,
	LEFT_FIT	= 0x001,
	HMID_FIT	= 0x002,
	RIGHT_FIT	= 0x004,
	TOP_FIT		= 0x008,
	VMID_FIT	= 0x010,
	BOTTOM_FIT	= 0x020,
	FIT_SKIP	= 0x800,
	X_FIT		= LEFT_FIT|RIGHT_FIT,
	Y_FIT		= TOP_FIT|BOTTOM_FIT,
	XY_FIT		= X_FIT|Y_FIT,
};

struct DlgItem {
	DWORD	flags;	// DlgItemFlags
	HWND	hWnd;
	UINT	id;
	WINPOS	wpos;
};

// UTF8 string class
enum StrMode { BY_UTF8, BY_MBCS };

/* for internal use end */

class TWin : public THashObj {
protected:
	RECT			rect;
	RECT			orgRect;
	HACCEL			hAccel;
	TWin			*parent;
	BOOL			sleepBusy;	// for TWin::Sleep() only
	BOOL			isUnicode;

public:
	TWin(TWin *_parent = NULL);
	virtual	~TWin();

	HWND			hWnd;

	virtual void	Show(int mode = SW_SHOWDEFAULT);
	virtual BOOL	Create(LPCSTR className=NULL, LPCSTR title="",
						DWORD style=(WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN),
						DWORD exStyle=0, HMENU hMenu=NULL);
	virtual BOOL	CreateU8(LPCSTR className=NULL, LPCSTR title="",
						DWORD style=(WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN),
						DWORD exStyle=0, HMENU hMenu=NULL);
	virtual BOOL	CreateV(const void *className=NULL, const void *title=L"",
						DWORD style=(WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN),
						DWORD exStyle=0, HMENU hMenu=NULL);
	virtual	void	Destroy(void);

	virtual BOOL	EvCommand(WORD wNotifyCode, WORD wID, LPARAM hwndCtl);
	virtual BOOL	EvSysCommand(WPARAM uCmdType, POINTS pos);
	virtual BOOL	EvCreate(LPARAM lParam);
	virtual BOOL	EvClose(void);
	virtual BOOL	EvDestroy(void);
	virtual BOOL	EvNcDestroy(void);
	virtual BOOL	EvQueryEndSession(BOOL nSession, BOOL nLogOut);
	virtual BOOL	EvEndSession(BOOL nSession, BOOL nLogOut);
	virtual BOOL	EvQueryOpen(void);
	virtual BOOL	EvPaint(void);
	virtual BOOL	EvNcPaint(HRGN hRgn);
	virtual BOOL	EvSize(UINT fwSizeType, WORD nWidth, WORD nHeight);
	virtual BOOL	EvMove(int xpos, int ypos);
	virtual BOOL	EvShowWindow(BOOL fShow, int fnStatus);
	virtual BOOL	EvGetMinMaxInfo(MINMAXINFO *info);
	virtual BOOL	EvTimer(WPARAM timerID, TIMERPROC proc);
	virtual BOOL	EvSetCursor(HWND cursorWnd, WORD nHitTest, WORD wMouseMsg);
	virtual BOOL	EvMouseMove(UINT fwKeys, POINTS pos);
	virtual BOOL	EvNcHitTest(POINTS pos, LRESULT *result);
	virtual BOOL	EvMeasureItem(UINT ctlID, MEASUREITEMSTRUCT *lpMis);
	virtual BOOL	EvDrawItem(UINT ctlID, DRAWITEMSTRUCT *lpDis);
	virtual BOOL	EvMenuSelect(UINT uItem, UINT fuFlag, HMENU hMenu);
	virtual BOOL	EvDropFiles(HDROP hDrop);
	virtual BOOL	EvNotify(UINT ctlID, NMHDR *pNmHdr);
	virtual BOOL	EvContextMenu(HWND childWnd, POINTS pos);
	virtual BOOL	EvHotKey(int hotKey);
	virtual BOOL	EvActivateApp(BOOL fActivate, DWORD dwThreadID);
	virtual BOOL	EvActivate(BOOL fActivate, DWORD fMinimized, HWND hActiveWnd);
	virtual BOOL	EvChar(WCHAR code, LPARAM keyData);
	virtual BOOL	EvWindowPosChanged(WINDOWPOS *pos);
	virtual BOOL	EvWindowPosChanging(WINDOWPOS *pos);

	virtual BOOL	EventScroll(UINT uMsg, int nCode, int nPos, HWND scrollBar);

	virtual BOOL	EventButton(UINT uMsg, int nHitTest, POINTS pos);
	virtual BOOL	EventKey(UINT uMsg, int nVirtKey, LONG lKeyData);
	virtual BOOL	EventMenuLoop(UINT uMsg, BOOL fIsTrackPopupMenu);
	virtual BOOL	EventInitMenu(UINT uMsg, HMENU hMenu, UINT uPos, BOOL fSystemMenu);
	virtual BOOL	EventCtlColor(UINT uMsg, HDC hDcCtl, HWND hWndCtl, HBRUSH *result);
	virtual BOOL	EventFocus(UINT uMsg, HWND focusWnd);

	virtual BOOL	EventApp(UINT uMsg, WPARAM wParam, LPARAM lParam);
	virtual BOOL	EventUser(UINT uMsg, WPARAM wParam, LPARAM lParam);
	virtual BOOL	EventSystem(UINT uMsg, WPARAM wParam, LPARAM lParam);

	virtual UINT	GetDlgItemText(int ctlId, LPSTR buf, int len);
	virtual UINT	GetDlgItemTextV(int ctlId, void *buf, int len);
	virtual UINT	GetDlgItemTextU8(int ctlId, char *buf, int len);
	virtual BOOL	SetDlgItemText(int ctlId, LPCSTR buf);
	virtual BOOL	SetDlgItemTextV(int ctlId, const void *buf);
	virtual BOOL	SetDlgItemTextU8(int ctlId, const char *buf);
	virtual int		GetDlgItemInt(int ctlId, BOOL *err=NULL, BOOL sign=TRUE);
	virtual BOOL	SetDlgItemInt(int ctlId, int val, BOOL sign=TRUE);
	virtual HWND	GetDlgItem(int ctlId);
	virtual BOOL	CheckDlgButton(int ctlId, UINT check);
	virtual UINT	IsDlgButtonChecked(int ctlId);
	virtual BOOL	IsWindowVisible(void);
	virtual BOOL	EnableWindow(BOOL is_enable);

	virtual	int		MessageBox(LPCSTR msg, LPCSTR title="msg", UINT style=MB_OK);
	virtual	int		MessageBoxV(void *msg, void *title=EMPTY_STR_V, UINT style=MB_OK);
	virtual	int		MessageBoxW(LPCWSTR msg, LPCWSTR title=L"", UINT style=MB_OK);
	virtual	int		MessageBoxU8(const char *msg, char *title="msg", UINT style=MB_OK);
	virtual BOOL	BringWindowToTop(void);
	virtual BOOL	SetForegroundWindow(void);
	virtual BOOL	SetForceForegroundWindow(void);
	virtual BOOL	ShowWindow(int mode);
	virtual BOOL	PostMessage(UINT uMsg, WPARAM wParam, LPARAM lParam);
	virtual BOOL	PostMessageW(UINT uMsg, WPARAM wParam, LPARAM lParam);
	virtual BOOL	PostMessageV(UINT uMsg, WPARAM wParam, LPARAM lParam);
	virtual LRESULT	SendMessage(UINT uMsg, WPARAM wParam, LPARAM lParam);
	virtual LRESULT	SendMessageW(UINT uMsg, WPARAM wParam, LPARAM lParam);
	virtual LRESULT	SendMessageV(UINT uMsg, WPARAM wParam, LPARAM lParam);
	virtual LRESULT	SendDlgItemMessage(int ctlId, UINT uMsg, WPARAM wParam, LPARAM lParam);
	virtual LRESULT	SendDlgItemMessageW(int ctlId, UINT uMsg, WPARAM wParam, LPARAM lParam);
	virtual LRESULT	SendDlgItemMessageV(int ctlId, UINT uMsg, WPARAM wParam, LPARAM lParam);
	virtual BOOL	GetWindowRect(RECT *_rect=NULL);
	virtual BOOL	SetWindowPos(HWND hInsAfter, int x, int y, int cx, int cy, UINT fuFlags);
	virtual HWND	SetActiveWindow(void);
	virtual int		GetWindowText(LPSTR text, int size);
	virtual BOOL	SetWindowText(LPCSTR text);
	virtual BOOL	GetWindowTextV(void *text, int size);
	virtual BOOL	GetWindowTextU8(char *text, int size);
	virtual BOOL	SetWindowTextV(const void *text);
	virtual BOOL	SetWindowTextU8(const char *text);
	virtual int		GetWindowTextLengthV(void);
	virtual int		GetWindowTextLengthU8(void);
	virtual BOOL	InvalidateRect(const RECT *rc, BOOL fErase);

	virtual LONG_PTR SetWindowLong(int index, LONG_PTR val);
	virtual WORD	SetWindowWord(int index, WORD val);
	virtual LONG_PTR GetWindowLong(int index);
	virtual WORD	GetWindowWord(int index);
	virtual TWin	*GetParent(void) { return parent; };
	virtual void	SetParent(TWin *_parent) { parent = _parent; };
	virtual BOOL	MoveWindow(int x, int y, int cx, int cy, int bRepaint);
	virtual BOOL	FitMoveWindow(int x, int y);
	virtual BOOL	Sleep(UINT mSec);
	virtual BOOL	Idle(void);
	virtual RECT	*Rect() { return ▭ }

	virtual	BOOL	PreProcMsg(MSG *msg);
	virtual	LRESULT	WinProc(UINT uMsg, WPARAM wParam, LPARAM lParam);
	virtual	LRESULT	DefWindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam);
};

class TDlg : public TWin {
protected:
	UINT	resId;
	BOOL	modalFlg;
	int		maxItems;
	DlgItem	*dlgItems;

public:
	TDlg(UINT	resid=0, TWin *_parent = NULL);
	virtual ~TDlg();

	virtual BOOL	Create(HINSTANCE hI = NULL);
	virtual	void	Destroy(void);
	virtual int		Exec(void);
	virtual void	EndDialog(int);
	UINT			ResId(void) { return resId; }
	virtual int		SetDlgItem(UINT ctl_id, DWORD flags=0);
	virtual BOOL	FitDlgItems();

	virtual BOOL	EvCreate(LPARAM lParam);
	virtual BOOL	EvCommand(WORD wNotifyCode, WORD wID, LPARAM hwndCtl);
	virtual BOOL	EvSysCommand(WPARAM uCmdType, POINTS pos);
	virtual BOOL	EvQueryOpen(void);

	virtual	BOOL	PreProcMsg(MSG *msg);
	virtual LRESULT	WinProc(UINT uMsg, WPARAM wParam, LPARAM lParam);
};

class TSubClass : public TWin {
protected:
	WNDPROC		oldProc;

public:
	TSubClass(TWin *_parent = NULL);
	virtual ~TSubClass();

	virtual BOOL	AttachWnd(HWND _hWnd);
	virtual BOOL	DetachWnd();
	virtual	LRESULT	DefWindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam);
};

class TSubClassCtl : public TSubClass {
protected:
public:
	TSubClassCtl(TWin *_parent);

	virtual	BOOL	PreProcMsg(MSG *msg);
	virtual LRESULT WinProc(UINT uMsg, WPARAM wParam, LPARAM lParam);
};

BOOL TRegisterClass(LPCSTR class_name, UINT style=CS_DBLCLKS, HICON hIcon=0, HCURSOR hCursor=0,
		HBRUSH hbrBackground=0, int classExtra=0, int wndExtra=0, LPCSTR menu_str=0);
BOOL TRegisterClassU8(LPCSTR class_name, UINT style=CS_DBLCLKS, HICON hIcon=0, HCURSOR hCursor=0,
		HBRUSH hbrBackground=0, int classExtra=0, int wndExtra=0, LPCSTR menu_str=0);
BOOL TRegisterClassV(const void *class_name, UINT style=CS_DBLCLKS, HICON hIcon=0,
		HCURSOR hCursor=0, HBRUSH hbrBackground=0, int classExtra=0, int wndExtra=0,
		const void *menu_str=0);

class TWinHashTbl : public THashTbl {
protected:
	virtual BOOL	IsSameVal(THashObj *obj, const void *val) {
		return ((TWin *)obj)->hWnd == *(HWND *)val;
	}

public:
	TWinHashTbl(int _hashNum) : THashTbl(_hashNum) {}
	~TWinHashTbl() {}

	u_int	MakeHashId(HWND hWnd) { return (u_int)hWnd * 0xf3f77d13; }
};

class TApp {
protected:
	static TApp	*tapp;
	TWinHashTbl	*hash;
	LPCSTR		defaultClass;
	LPCVOID		defaultClassV;

	LPSTR		cmdLine;
	int			nCmdShow;
	TWin		*mainWnd;
	TWin		*preWnd;
	HINSTANCE	hI;

	TWin	*SearchWnd(HWND hWnd) { return (TWin *)hash->Search(&hWnd, hash->MakeHashId(hWnd)); }
	virtual BOOL	InitApp(void);

public:
	TApp(HINSTANCE _hI, LPSTR _cmdLine, int _nCmdShow);
	virtual ~TApp();
	virtual void	InitWindow() = 0;
	virtual int		Run();
	virtual BOOL	PreProcMsg(MSG *msg);

	LPCSTR	GetDefaultClass() { return defaultClass; }
	LPCVOID	GetDefaultClassV() { return (void *)defaultClassV; }
	void	AddWin(TWin *win) { preWnd = win; }
	void	AddWinByWnd(TWin *win, HWND hWnd) {
			win->hWnd = hWnd; hash->Register(win, hash->MakeHashId(hWnd));
	}
	void	DelWin(TWin *win) { hash->UnRegister(win); }

	static TApp *GetApp() { return tapp; }
	static void Idle(DWORD timeout=0);
	static HINSTANCE GetInstance() { return tapp->hI; }
	static LRESULT CALLBACK WinProc(HWND hW, UINT uMsg, WPARAM wParam, LPARAM lParam);
};

struct TListObj {
	TListObj *prior, *next;
};

class TList {
protected:
	TListObj	top;
	int			num;

public:
	TList(void);
	void		Init(void);
	void		AddObj(TListObj *obj);
	void		DelObj(TListObj *obj);
	TListObj	*TopObj(void);
	TListObj	*EndObj(void);
	TListObj	*NextObj(TListObj *obj);
	TListObj	*PriorObj(TListObj *obj);
	BOOL		IsEmpty() { return	top.next == ⊤ }
	void		MoveList(TList *from_list);
	int			Num() { return num; }
};

#define FREE_LIST	0
#define USED_LIST	1
#define	RLIST_MAX	2
class TRecycleList {
protected:
	char	*data;
	TList	list[RLIST_MAX];

public:
	TRecycleList(int init_cnt, int size);
	~TRecycleList();
	TListObj *GetObj(int list_type);
	void PutObj(int list_type, TListObj *obj);
};

#define MAX_KEYARRAY	30

class TRegistry {
protected:
	HKEY	topKey;
	int		openCnt;
	StrMode	strMode;
	HKEY	hKey[MAX_KEYARRAY];

public:
	TRegistry(LPCSTR company, LPSTR appName=NULL, StrMode mode=BY_UTF8);
	TRegistry(LPCWSTR company, LPCWSTR appName=NULL, StrMode mode=BY_UTF8);
	TRegistry(HKEY top_key, StrMode mode=BY_UTF8);
	~TRegistry();

	void	ChangeTopKey(HKEY topKey);
	void	SetStrMode(StrMode mode) { strMode = mode; }

	BOOL	ChangeApp(LPCSTR company, LPSTR appName=NULL);
	BOOL	ChangeAppV(const void *company, const void *appName=NULL);

	BOOL	OpenKey(LPCSTR subKey, BOOL createFlg=FALSE);
	BOOL	OpenKeyV(const void *subKey, BOOL createFlg=FALSE);

	BOOL	CreateKey(LPCSTR subKey) { return OpenKey(subKey, TRUE); }
	BOOL	CreateKeyV(const void *subKey) { return OpenKeyV(subKey, TRUE); }

	BOOL	CloseKey(void);

	BOOL	GetInt(LPCSTR key, int *val);
	BOOL	GetIntV(const void *key, int *val);

	BOOL	SetInt(LPCSTR key, int val);
	BOOL	SetIntV(const void *key, int val);

	BOOL	GetLong(LPCSTR key, long *val);
	BOOL	GetLongV(const void *key, long *val);

	BOOL	SetLong(LPCSTR key, long val);
	BOOL	SetLongV(const void *key, long val);

	BOOL	GetStr(LPCSTR key, LPSTR str, int size_byte);
	BOOL	GetStrA(LPCSTR key, LPSTR str, int size_byte);
	BOOL	GetStrV(const void *key, void *str, int size_byte);

	BOOL	SetStr(LPCSTR key, LPCSTR str);
	BOOL	SetStrA(LPCSTR key, LPCSTR str);
	BOOL	SetStrV(const void *key, const void *str);

	BOOL	GetByte(LPCSTR key, BYTE *data, int *size);
	BOOL	GetByteV(const void *key, BYTE *data, int *size);

	BOOL	SetByte(LPCSTR key, const BYTE *data, int size);
	BOOL	SetByteV(const void *key, const BYTE *data, int size);

	BOOL	DeleteKey(LPCSTR str);
	BOOL	DeleteKeyV(const void *str);

	BOOL	DeleteValue(LPCSTR str);
	BOOL	DeleteValueV(const void *str);

	BOOL	EnumKey(DWORD cnt, LPSTR buf, int size);
	BOOL	EnumKeyV(DWORD cnt, void *buf, int size);

	BOOL	EnumValue(DWORD cnt, LPSTR buf, int size, DWORD *type=NULL);
	BOOL	EnumValueV(DWORD cnt, void *buf, int size, DWORD *type=NULL);

	BOOL	DeleteChildTree(LPCSTR subkey=NULL);
	BOOL	DeleteChildTreeV(const void *subkey=NULL);
};

class TIniKey : public TListObj {
protected:
	char	*key;	// null means comment line
	char	*val;

public:
	TIniKey(const char *_key=NULL, const char *_val=NULL) {
		key = val = NULL; if (_key || _val) Set(_key, _val);
	}
	~TIniKey() { free(key); free(val); }

	void Set(const char *_key=NULL, const char *_val=NULL) {
		if (_key) { free(key); key=strdup(_key); }
		if (_val) { free(val); val=strdup(_val); }
	}
	const char *Key() { return key; }
	const char *Val() { return val; }
};

class TIniSection : public TListObj, public TList {
protected:
	char	*name;

public:
	TIniSection() { name = NULL; }
	~TIniSection() {
		free(name);
		for (TIniKey *key; (key = (TIniKey *)TopObj()); ) {
			DelObj(key);
			delete key;
		}
	}

	void Set(const char *_name=NULL) {
		if (_name) { free(name); name=strdup(_name); }
	}
	TIniKey *SearchKey(const char *key_name) {
		for (TIniKey *key = (TIniKey *)TopObj(); key; key = (TIniKey *)NextObj(key)) {
			if (key->Key() && strcmpi(key->Key(), key_name) == 0) return key;
		}
		return	NULL;
	}
	BOOL AddKey(const char *key_name, const char *val) {
		TIniKey	*key = key_name ? SearchKey(key_name) : NULL;
		if (!key) {
			key = new TIniKey(key_name, val);
			AddObj(key);
		}
		else {
			key->Set(NULL, val);
		}
		return	TRUE;
	}
	BOOL DelKey(const char *key_name) {
		TIniKey	*key = SearchKey(key_name);
		if (!key) return FALSE;
		DelObj(key);
		delete key;
		return	TRUE;
	}
	const char *Name() { return name; }
};

class TInifile: public TList {
protected:
	char		*ini_file;
	TIniSection	*cur_sec;
	TIniSection	*root_sec;
	FILETIME	ini_ft;
	int			ini_size;
	HANDLE		hMutex;

	BOOL Strip(const char *s, char *d=NULL, const char *strip_chars=" \t\r\n",
		const char *quote_chars="\"\"");
	BOOL Parse(const char *buf, BOOL *is_section, char *name, char *val);
	BOOL GetFileInfo(const char *fname, FILETIME *ft, int *size);
	TIniSection *SearchSection(const char *section);
	BOOL WriteIni();
	BOOL Lock();
	void UnLock();

public:
	TInifile(const char *ini_name=NULL);
	~TInifile();
	void Init(const char *ini_name=NULL);
	void UnInit();
	void SetSection(const char *section);
	BOOL StartUpdate();
	BOOL EndUpdate();
	BOOL SetStr(const char *key, const char *val);
	DWORD GetStr(const char *key, char *val, int max_size, const char *default_val="");
	BOOL SetInt(const char *key, int val);
	BOOL DelSection(const char *section);
	BOOL DelKey(const char *key);
	int GetInt(const char *key, int default_val=-1);
	const char *GetIniFileName(void) { return	ini_file; }
};

#include "tapi32u8.h"

#endif


text:
package almhirt.common

/** Wow, let's hope you'll never trigger that one in production code ...
 */
case class ResultForcedFromValidationException(val problem: Problem) extends Exception("A value has been forced from a failure: %s".format(problem.message))

/** Wow, let's hope you'll never trigger that one in production code ...
 */
case class ProblemForcedFromValidationException() extends Exception("A problem has been forced from a success.")


text:
package org.thymeleaf.messageresolver;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *

 *   Base abstract implementation for message resolvers implementing the
 *   {@link IMessageResolver} interface.
 *

 *
 * @author Daniel Fernández
 *
 * @since 1.0
 *
 */
public abstract class AbstractMessageResolver
        implements IMessageResolver {

    private static final Logger logger = LoggerFactory.getLogger(AbstractMessageResolver.class);

    private String name = this.getClass().getName();
    private Integer order = null;

    protected AbstractMessageResolver() {
        super();
    }

    public final String getName() {
        return this.name;
    }

    /**
     *

     *   Sets a name for this message resolver.
     *

     *
     * @param name the new name
     */
    public void setName(final String name) {
        this.name = name;
    }

    public final Integer getOrder() {
        return this.order;
    }

    /**
     *

     *   Sets a new order for the message resolver.
     *

     *
     * @param order the new order
     */
    public void setOrder(final Integer order) {
        this.order = order;
    }

}


text:
<?php

namespace Predis\Command;

use \PHPUnit_Framework_TestCase as StandardTestCase;

/**
 * @group commands
 * @group realm-string
 */
class StringPreciseSetExpireTest extends CommandTestCase
{
    /**
     * {@inheritdoc}
     */
    protected function getExpectedCommand()
    {
        return 'Predis\Command\StringPreciseSetExpire';
    }

    /**
     * {@inheritdoc}
     */
    protected function getExpectedId()
    {
        return 'PSETEX';
    }

    /**
     * @group disconnected
     */
    public function testFilterArguments()
    {
        $arguments = array('key', 10, 'hello');
        $expected = array('key', 10, 'hello');

        $command = $this->getCommand();
        $command->setArguments($arguments);

        $this->assertSame($expected, $command->getArguments());
    }

    /**
     * @group disconnected
     */
    public function testParseResponse()
    {
        $this->assertTrue($this->getCommand()->parseResponse(true));
    }

    /**
     * @group disconnected
     */
    public function testPrefixKeys()
    {
        $arguments = array('key', 10, 'hello');
        $expected = array('prefix:key', 10, 'hello');

        $command = $this->getCommandWithArgumentsArray($arguments);
        $command->prefixKeys('prefix:');

        $this->assertSame($expected, $command->getArguments());
    }

    /**
     * @group disconnected
     */
    public function testPrefixKeysIgnoredOnEmptyArguments()
    {
        $command = $this->getCommand();
        $command->prefixKeys('prefix:');

        $this->assertSame(array(), $command->getArguments());
    }

    /**
     * @group connected
     */
    public function testCreatesNewKeyAndSetsTTL()
    {
        $redis = $this->getClient();

        $this->assertTrue($redis->psetex('foo', 10000, 'bar'));
        $this->assertTrue($redis->exists('foo'));
        $this->assertEquals(10, $redis->ttl('foo'));
    }

    /**
     * @group connected
     * @group slow
     */
    public function testKeyExpiresAfterTTL()
    {
        $redis = $this->getClient();

        $redis->psetex('foo', 50, 'bar');
        $this->sleep(0.5);
        $this->assertFalse($redis->exists('foo'));;
    }

    /**
     * @group connected
     * @expectedException Predis\ServerException
     * @expectedExceptionMessage ERR value is not an integer or out of range
     */
    public function testThrowsExceptionOnNonIntegerTTL()
    {
        $this->getClient()->psetex('foo', 2.5, 'bar');
    }

    /**
     * @group connected
     * @expectedException Predis\ServerException
     * @expectedExceptionMessage ERR invalid expire time in SETEX
     * @todo Should not Redis return PSETEX instead of SETEX here?
     */
    public function testThrowsExceptionOnZeroTTL()
    {
        $this->getClient()->psetex('foo', 0, 'bar');
    }

    /**
     * @group connected
     * @expectedException Predis\ServerException
     * @expectedExceptionMessage ERR invalid expire time in SETEX
     * @todo Should not Redis return PSETEX instead of SETEX here?
     */
    public function testThrowsExceptionOnNegativeTTL()
    {
        $this->getClient()->psetex('foo', -10000, 'bar');
    }
}


text:
require "unit_helper"
require "revily/event/hook/incident_trigger"

class Revily::Event::Hook
  describe IncidentTrigger do

    describe "initialize" do
      let(:hook) { described_class.new }

      it "initializes with correct attributes" do
        expect(hook.name).to eq "incident_trigger"
        expect(hook.events).to eq [ "incident.trigger", "incident.escalate" ]
        expect(hook.config).to eq({})
      end
    end
  end
end


text:
struct Controller : Processor {
  enum : bool { Port1 = 0, Port2 = 1 };
  enum { SaveSize = 16 };
  const bool port;

  static void Enter();
  virtual void enter();
  void step(unsigned clocks);
  void synchronize_cpu();
  virtual void serialize(serializer& s);

  bool iobit();
  void iobit(bool data);
  virtual uint2 data() { return 0; }
  virtual void latch(bool data) {}
  Controller(bool port);
};

#include "gamepad/gamepad.hpp"
#include "multitap/multitap.hpp"
#include "mouse/mouse.hpp"
#include "superscope/superscope.hpp"
#include "justifier/justifier.hpp"
#include "usart/usart.hpp"


text:
"""

An example program for renaming lots of files with FAile

Created by bunnyman on 2013/03/19.
Copyright (c) 2013 Bunni.biz. All rights reserved.
"""
import os
import argparse
from FAiler import FAile, FAError

RENAME = '{0.artist} - {0.name}.{0.fileType}'

parser = argparse.ArgumentParser(description='Rename Files with FAile')
parser.add_argument('file', nargs='+', help="Files to rename")
parser.add_argument('--rename', default=RENAME, nargs=1,
                    help='Optional format string to rename with')
args = parser.parse_args()

failes = []
for x in args.file:
    try:
        failes.append(FAile(x))
    except FAError as e:
        pass

for faile in failes:
    try:
        faile.clean_reupload()
        os.rename(
            os.path.join(faile.directory, faile.filename),
            os.path.join(faile.directory, args.rename.format(faile))
        )
    except OSError as e:
        print("File {} failed because of {}".format(faile.basename, e))


text:
using DotNetNuke.Instrumentation;
using DotNetNuke.Modules.SQL.Components;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;

/// <summary>
/// Summary description for SQLProvider
/// </summary>
///
namespace Satrabel.HttpModules.Provider
{
    public class SqlUrlRuleProvider : UrlRuleProvider
    {
        protected static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(SqlUrlRuleProvider));
        public SqlUrlRuleProvider()
        {

        }
        public override List<UrlRule> GetRules(int PortalId)
        {
            List<UrlRule> Rules = new List<UrlRule>();
            SqlQueryController sqlCtrl = new SqlQueryController();
            var queries = sqlCtrl.GetQueries().Where(q => q.Name.StartsWith("OpenUrlRewriter")); ;
            try
            {
                foreach (var query in queries)
                {
                    //SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString);
                    SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[query.ConnectionStringName].ConnectionString);
                    SqlCommand cmd = new SqlCommand();
                    SqlDataReader reader;
                    //cmd.CommandText = "SELECT * FROM OpenUrlRewriter_CustomUrlRule WHERE PortalId = " + PortalId;
                    cmd.CommandText = query.Query;
                    cmd.CommandType = CommandType.Text;
                    cmd.Connection = sqlConnection;
                    cmd.Parameters.Add("@PortalId", SqlDbType.Int);
                    cmd.Parameters["@PortalId"].Value = PortalId;

                    sqlConnection.Open();
                    reader = cmd.ExecuteReader();
                    try
                    {
                        while (reader.Read())
                        {
                            var rule = new UrlRule
                            {
                                RuleType = UrlRuleType.Module,
                                CultureCode = ColumnExists(reader, "CultureCode") ? (string)reader["CultureCode"] : null,
                                TabId = ColumnExists(reader, "TabId") ? (int)reader["TabId"] : 0,
                                Parameters = ColumnExists(reader, "Parameters") ? (string)reader["Parameters"] : "",
                                Action = ColumnExists(reader, "RuleAction") ? (UrlRuleAction)reader["RuleAction"] : UrlRuleAction.Rewrite,
                                Url = CleanupUrl((string)reader["Url"]),
                                RemoveTab = ColumnExists(reader, "RemoveTab") ? (bool)reader["RemoveTab"] : false,
                                RedirectDestination = ColumnExists(reader, "RedirectDestination") ? (string)reader["RedirectDestination"] : null,
                                RedirectStatus = ColumnExists(reader, "RedirectStatus") ? (int)reader["RedirectStatus"] : 0,
                                InSitemap = ColumnExists(reader, "InSitemap") ? (bool)reader["InSitemap"] : true
                            };
                            Rules.Add(rule);
                        }
                    }
                    finally
                    {
                        reader.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error(" SqlUrlRuleProvider error : " + ex.Message, ex);
            }

            return Rules;
        }

        public bool ColumnExists(IDataReader reader, string columnName)
        {
            for (int i = 0; i < reader.FieldCount; i++)
            {
                if (reader.GetName(i).Equals(columnName, StringComparison.InvariantCultureIgnoreCase))
                    return true;
            }
            return false;
            /*
            return reader.GetSchemaTable()
                         .Rows
                         .OfType<DataRow>()
                         .Any(row => row["ColumnName"] == columnName);
             */
        }

    }
}


text:
module ThreeTaps
  # NOT USED
  #
  # Class ExistsResponse represents server response on +exists+ Posting API
  # request. Server response is sent to +from_hash+ method which creates object
  # with attribute +success+ accessible via getter:
  #
  #  response = ExistsResponse.from_hash("success" => "true")
  #  response.success       # => true
  #
  class ExistsResponse < Struct.new(:indexed, :postKey, :exists, :failures)
    def initialize(hash = {})
      hash.each do |key, value|
        self.send("#{key}=".to_sym, value )
      end
    end
  end
end


text:
// Copyright 2017 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;

namespace Daydream.MediaAppTemplate {

  /// Serialized Data Model that defines the properties for a UI page that is used
  /// to display a category of levels that the player can select and load.
  [CreateAssetMenu(fileName = "FileSelectorTilePrefabData",
    menuName = "MediaApp/FileSelector/TilePrefabData",
    order = 1000)]
  public class FileSelectorTilePrefabData : ScriptableObject {
    [Serializable]
    public class ExtensionPrefab {
      public string extension;
      public GameObject prefab;

      [NonSerialized]
      public string prefabName;
    }

    [SerializeField]
    private GameObject directoryPrefab;

    [SerializeField]
    private GameObject defaultFilePrefab;

    [SerializeField]
    private ExtensionPrefab[] extentionsToPrefabs;

    private Dictionary<string, ExtensionPrefab> extensionPrefabsDict;
    private string directoryPrefabName;
    private string defaultFilePrefabName;

    public GameObject DirectoryPrefab {
      get {
        return directoryPrefab;
      }
    }

    public string DirectoryPrefabName {
      get {
        if (directoryPrefabName == null) {
          directoryPrefabName = directoryPrefab.name;
        }

        return directoryPrefabName;
      }
    }

    public GameObject DefaultFilePrefab {
      get {
        return defaultFilePrefab;
      }
    }

    private Dictionary<string, ExtensionPrefab> ExtensionPrefabsDict {
      get {
        if (extensionPrefabsDict != null) {
          return extensionPrefabsDict;
        }

        extensionPrefabsDict = new Dictionary<string, ExtensionPrefab>();
        for (int i = 0; i < extentionsToPrefabs.Length; i++) {
          ExtensionPrefab extensionPrefab = extentionsToPrefabs[i];
          extensionPrefabsDict[extensionPrefab.extension] = extensionPrefab;
        }

        return extensionPrefabsDict;
      }
    }

    public string DefaultFilePrefabName {
      get {
        if (defaultFilePrefabName == null) {
          defaultFilePrefabName = defaultFilePrefab.name;
        }

        return defaultFilePrefabName;
      }
    }

    public GameObject GetPrefabForExtension(string extension) {
      ExtensionPrefab result = null;
      if (ExtensionPrefabsDict.TryGetValue(extension, out result)) {
        return result.prefab;
      }

      return DefaultFilePrefab;
    }

    public string GetPrefabNameForExtension(string extension) {
      ExtensionPrefab result = null;
      if (ExtensionPrefabsDict.TryGetValue(extension, out result)) {
        if (result.prefabName == null) {
          result.prefabName = result.prefab.name;
        }

        return result.prefabName;
      }

      return DefaultFilePrefabName;
    }
  }
}


text:
 /*
  * Authors:
  *   Keith Whitwell <keith@tungstengraphics.com>
  *   Brian Paul
  */

#include "main/glheader.h"
#include "main/macros.h"
#include "main/context.h"
#include "st_context.h"
#include "st_cb_bitmap.h"
#include "st_cb_flush.h"
#include "st_cb_clear.h"
#include "st_cb_fbo.h"
#include "st_manager.h"
#include "pipe/p_context.h"
#include "pipe/p_defines.h"
#include "pipe/p_screen.h"
#include "util/u_gen_mipmap.h"
#include "util/u_blit.h"

/** Check if we have a front color buffer and if it's been drawn to. */
static INLINE GLboolean
is_front_buffer_dirty(struct st_context *st)
{
   GLframebuffer *fb = st->ctx->DrawBuffer;
   struct st_renderbuffer *strb
      = st_renderbuffer(fb->Attachment[BUFFER_FRONT_LEFT].Renderbuffer);
   return strb && strb->defined;
}

/**
 * Tell the screen to display the front color buffer on-screen.
 */
static void
display_front_buffer(struct st_context *st)
{
   GLframebuffer *fb = st->ctx->DrawBuffer;
   struct st_renderbuffer *strb
      = st_renderbuffer(fb->Attachment[BUFFER_FRONT_LEFT].Renderbuffer);

   if (strb) {
      /* Hook for copying "fake" frontbuffer if necessary:
       */
      st_manager_flush_frontbuffer(st);
   }
}

void st_flush( struct st_context *st, uint pipeFlushFlags,
               struct pipe_fence_handle **fence )
{
   FLUSH_CURRENT(st->ctx, 0);

   /* Release any vertex buffers that might potentially be accessed in
    * successive frames:
    */
   st_flush_bitmap(st);
   st_flush_clear(st);
   util_blit_flush(st->blit);
   util_gen_mipmap_flush(st->gen_mipmap);

   st->pipe->flush( st->pipe, pipeFlushFlags, fence );
}

/**
 * Flush, and wait for completion.
 */
void st_finish( struct st_context *st )
{
   struct pipe_fence_handle *fence = NULL;

   st_flush(st, PIPE_FLUSH_RENDER_CACHE | PIPE_FLUSH_FRAME, &fence);

   if(fence) {
      st->pipe->screen->fence_finish(st->pipe->screen, fence, 0);
      st->pipe->screen->fence_reference(st->pipe->screen, &fence, NULL);
   }
}

/**
 * Called via ctx->Driver.Flush()
 */
static void st_glFlush(GLcontext *ctx)
{
   struct st_context *st = st_context(ctx);

   /* Don't call st_finish() here.  It is not the state tracker's
    * responsibilty to inject sleeps in the hope of avoiding buffer
    * synchronization issues.  Calling finish() here will just hide
    * problems that need to be fixed elsewhere.
    */
   st_flush(st, PIPE_FLUSH_RENDER_CACHE | PIPE_FLUSH_FRAME, NULL);

   if (is_front_buffer_dirty(st)) {
      display_front_buffer(st);
   }
}

/**
 * Called via ctx->Driver.Finish()
 */
static void st_glFinish(GLcontext *ctx)
{
   struct st_context *st = st_context(ctx);

   st_finish(st);

   if (is_front_buffer_dirty(st)) {
      display_front_buffer(st);
   }
}

void st_init_flush_functions(struct dd_function_table *functions)
{
   functions->Flush = st_glFlush;
   functions->Finish = st_glFinish;

   /* Windows opengl32.dll calls glFinish prior to every swapbuffers.
    * This is unnecessary and degrades performance.  Luckily we have some
    * scope to work around this, as the externally-visible behaviour of
    * Finish() is identical to Flush() in all cases - no differences in
    * rendering or ReadPixels are visible if we opt not to wait here.
    *
    * Only set this up on windows to avoid suprise elsewhere.
    */
#ifdef PIPE_OS_WINDOWS
   functions->Finish = st_glFlush;
#endif
}


text:
/*jslint browser:true*/
var _ = require('lodash');
var path = require('path');
var Provider = require(path.resolve(__dirname, '../provider'));
var messenger = require(path.resolve(__dirname, '../messenger'));
var fileSystem = require(path.resolve(__dirname, '../files/fileSystem'));
var fileMgr = require(path.resolve(__dirname, '../files/fileMgr'));
var utils = require(path.resolve(__dirname, '../utils'));
var storage = require('local-storage');
var synchronizer = {};

// Create a map with providerId: providerModule
/**var providerMap = _.chain(arguments).map(function (argument) {
  return argument instanceof Provider && [
    argument.providerId,
    argument
  ];
}).compact().object().value();**/

var providerMap = require('require-all')({
  dirname: path.resolve(__dirname, '../../providers'),
  excludeDirs: /^\.(git|svn)$/,
  recursive: false,
  resolve: function (argument) {
    return argument instanceof Provider && [
      argument.providerId,
      argument
    ];
  }
});

// Retrieve sync locations from storage
(function () {
  var syncIndexMap = {};
  _.each(fileSystem, function (fileDesc) {
    utils.retrieveIndexArray(fileDesc.fileIndex + ".sync").forEach(function (syncIndex) {
      try {
        var syncAttributes = JSON.parse(storage[syncIndex]);
        // Store syncIndex
        syncAttributes.syncIndex = syncIndex;
        // Replace provider ID by provider module in attributes
        var provider = providerMap[syncAttributes.provider];
        if (!provider) {
          throw new Error("Invalid provider ID: " + syncAttributes.provider);
        }
        syncAttributes.provider = provider;
        fileDesc.syncLocations[syncIndex] = syncAttributes;
        syncIndexMap[syncIndex] = syncAttributes;
      } catch (e) {
        // storage can be corrupted
        //eventMgr.onError(e);
        messenger.publish.extension("onError", e);
        // Remove sync location
        utils.removeIndexFromArray(fileDesc.fileIndex + ".sync", syncIndex);
      }
    });
  });

  // Clean fields from deleted files in local storage
  Object.keys(storage).forEach(function (key) {
    var match = key.match(/sync\.\S+/);
    if (match && !syncIndexMap.hasOwnProperty(match[0])) {
      storage.removeItem(key);
    }
  });
})();

// AutoSync configuration
_.each(providerMap, function (provider) {
  provider.autosyncConfig = utils.retrieveIgnoreError(provider.providerId + ".autosyncConfig") || {};
});

// Returns true if at least one file has synchronized location
synchronizer.hasSync = function (provider) {
  return _.some(fileSystem, function (fileDesc) {
    return _.some(fileDesc.syncLocations, function (syncAttributes) {
      return provider === undefined || syncAttributes.provider === provider;
    });
  });
};

/***************************************************************************
 * Synchronization
 **************************************************************************/

// Entry point for up synchronization (upload changes)
var uploadCycle = false;

function syncUp(callback) {
  var uploadFileList = [];

  // Recursive function to upload multiple files
  function fileUp() {
    // No more fileDesc to synchronize
    if (uploadFileList.length === 0) {
      return syncUp(callback);
    }

    // Dequeue a fileDesc to synchronize
    var fileDesc = uploadFileList.pop();
    var uploadSyncAttributesList = _.values(fileDesc.syncLocations);
    if (uploadSyncAttributesList.length === 0) {
      return fileUp();
    }

    // Here we are freezing the data to make sure it's uploaded consistently
    var uploadContent = fileDesc.content;
    var uploadContentCRC = utils.crc32(uploadContent);
    var uploadTitle = fileDesc.title;
    var uploadTitleCRC = utils.crc32(uploadTitle);
    var uploadDiscussionList = fileDesc.discussionListJSON;
    var uploadDiscussionListCRC = utils.crc32(uploadDiscussionList);
    var uploadFrontMatter = fileDesc.frontMatter;

    // Recursive function to upload a single file on multiple locations
    function locationUp() {

      // No more synchronized location for this document
      if (uploadSyncAttributesList.length === 0) {
        return fileUp();
      }

      // Dequeue a synchronized location
      var syncAttributes = uploadSyncAttributesList.pop();

      syncAttributes.provider.syncUp(
        uploadContent,
        uploadContentCRC,
        uploadTitle,
        uploadTitleCRC,
        uploadDiscussionList,
        uploadDiscussionListCRC,
        uploadFrontMatter,
        syncAttributes,
        function (error, uploadFlag) {
          if (uploadFlag === true) {
            // If uploadFlag is true, request another upload cycle
            uploadCycle = true;
          }
          if (error) {
            return callback(error);
          }
          if (uploadFlag) {
            // Update syncAttributes in storage
            utils.storeAttributes(syncAttributes);
          }
          locationUp();
        }
      );
    }

    locationUp();
  }

  if (uploadCycle === true) {
    // New upload cycle
    uploadCycle = false;
    uploadFileList = _.values(fileSystem);
    fileUp();
  } else {
    callback();
  }
}

// Entry point for down synchronization (download changes)
function syncDown(callback) {
  var providerList = _.values(providerMap);

  // Recursive function to download changes from multiple providers
  function providerDown() {
    if (providerList.length === 0) {
      return callback();
    }
    var provider = providerList.pop();

    // Check that provider has files to sync
    if (!synchronizer.hasSync(provider)) {
      return providerDown();
    }

    // Perform provider's syncDown
    provider.syncDown(function (error) {
      if (error) {
        return callback(error);
      }
      providerDown();
    });
  }

  providerDown();
}

// Entry point for the autosync feature
function autosyncAll(callback) {
  var autosyncFileList = _.filter(fileSystem, function (fileDesc) {
    return _.size(fileDesc.syncLocations) === 0;
  });

  // Recursive function to autosync multiple files
  function fileAutosync() {
    // No more fileDesc to synchronize
    if (autosyncFileList.length === 0) {
      return callback();
    }
    var fileDesc = autosyncFileList.pop();

    var providerList = _.filter(providerMap, function (provider) {
      return provider.autosyncConfig.mode == 'all';
    });

    function providerAutosync() {
      // No more provider
      if (providerList.length === 0) {
        return fileAutosync();
      }
      var provider = providerList.pop();

      provider.autosyncFile(fileDesc.title, fileDesc.content, fileDesc.discussionListJSON, provider.autosyncConfig,
        function (error, syncAttributes) {
          if (error) {
            return callback(error);
          }
          fileDesc.addSyncLocation(syncAttributes);
          //eventMgr.onSyncExportSuccess(fileDesc, syncAttributes);
          messenger.publish.extension("onSyncExportSuccess", fileDesc, syncAttributes);
          providerAutosync();
        });
    }

    providerAutosync();
  }

  fileAutosync();
}

// Listen to offline status changes
var isOffline = false;
//eventMgr.addListener("onOfflineChanged", function (isOfflineParam) {
messenger.subscribe.extension("onOfflineChanged", function (isOfflineParam) {
  isOffline = isOfflineParam;
});

// Main entry point for synchronization
var syncRunning = false;
synchronizer.sync = function () {
  // If sync is already running or offline
  if (syncRunning === true || isOffline === true) {
    return false;
  }
  syncRunning = true;
  //eventMgr.onSyncRunning(true);
  messenger.publish.extension("onSyncRunning", true);

  uploadCycle = true;

  function isError(error) {
    if (error !== undefined) {
      syncRunning = false;
      // eventMgr.onSyncRunning(false);
      messenger.publish.extension("onSyncRunning", false);

      return true;
    }
    return false;
  }

  autosyncAll(function (error) {
    if (isError(error)) {
      return;
    }
    syncDown(function (error) {
      if (isError(error)) {
        return;
      }
      syncUp(function (error) {
        if (isError(error)) {
          return;
        }
        syncRunning = false;
        //eventMgr.onSyncRunning(false);
        messenger.publish.extension("onSyncRunning", false);
        //eventMgr.onSyncSuccess();
        messenger.publish.extension("onSyncSuccess", false);
      });
    });
  });
  return true;
};

/***************************************************************************
 * Initialize module
 **************************************************************************/

function loadPreferences(provider, action) {
  utils.resetModalInputs();
  var preferences = utils.retrieveIgnoreError(provider.providerId + '.' + action + 'Preferences');
  if (preferences) {
    _.each(provider[action + 'PreferencesInputIds'], function (inputId) {
      var exportPreferenceValue = preferences[inputId];
      var setValue = utils.setInputValue;
      if (_.isBoolean(exportPreferenceValue)) {
        setValue = utils.setInputChecked;
      }
      setValue('#input-sync-' + action + '-' + inputId, exportPreferenceValue);
    });
  }
}

// Initialize the import dialog
function initImportDialog(provider) {
  loadPreferences(provider, 'import');
  $(".modal-download-" + provider.providerId).modal();
}

// Initialize the export dialog
function initExportDialog(provider) {
  loadPreferences(provider, 'export');
  $(".modal-upload-" + provider.providerId).modal();
}

//eventMgr.addListener("onFileCreated", function (fileDesc) {
messenger.subscribe.extension("onFileCreated", function (fileDesc) {
  if (_.size(fileDesc.syncLocations) === 0) {
    _.each(providerMap, function (provider) {
      if (provider.autosyncConfig.mode != 'new') {
        return;
      }
      provider.autosyncFile(fileDesc.title, fileDesc.content, fileDesc.discussionListJSON, provider.autosyncConfig,
        function (error, syncAttributes) {
          if (error) {
            return;
          }
          fileDesc.addSyncLocation(syncAttributes);
          //eventMgr.onSyncExportSuccess(fileDesc, syncAttributes);
          messenger.publish.extension("onSyncExportSuccess", fileDesc, syncAttributes);
        });
    });
  }
});

//eventMgr.addListener("onReady", function () {
messenger.subscribe.extension("onReady", function () {
  // Init each provider
  _.each(providerMap, function (provider) {
    // Provider's import button
    $(".action-sync-import-" + provider.providerId).click(function (event) {
      provider.importFiles(event);

      // Store input values as preferences for next time we open the
      // import dialog
      var importPreferences = {};
      _.each(provider.importPreferencesInputIds, function (inputId) {
        var inputElt = document.getElementById("input-sync-import-" + inputId);
        if (inputElt.type == 'checkbox') {
          importPreferences[inputId] = inputElt.checked;
        } else {
          importPreferences[inputId] = inputElt.value;
        }
      });
      storage[provider.providerId + ".importPreferences"] = JSON.stringify(importPreferences);
    });
    // Provider's import dialog action
    $(".action-sync-import-dialog-" + provider.providerId).click(function () {
      initImportDialog(provider);
    });
    // Provider's export dialog action
    $(".action-sync-export-dialog-" + provider.providerId).click(function () {
      initExportDialog(provider);
    });
    // Provider's autosync action
    $(".action-autosync-dialog-" + provider.providerId).click(function () {
      // Reset fields
      utils.resetModalInputs();
      // Load config
      provider.setAutosyncDialogConfig(provider);
      // Open dialog
      $(".modal-autosync-" + provider.providerId).modal();
    });
    $(".action-sync-export-" + provider.providerId).click(function (event) {
      var fileDesc = fileMgr.currentFile;

      provider.exportFile(event, fileDesc.title, fileDesc.content, fileDesc.discussionListJSON, fileDesc.frontMatter,
        function (error, syncAttributes) {
          if (error) {
            return;
          }
          fileDesc.addSyncLocation(syncAttributes);
          //eventMgr.onSyncExportSuccess(fileDesc, syncAttributes);
          messenger.publish.extension("onSyncExportSuccess", fileDesc, syncAttributes);
        });

      // Store input values as preferences for next time we open the
      // export dialog
      var exportPreferences = {};
      _.each(provider.exportPreferencesInputIds, function (inputId) {
        var inputElt = document.getElementById("input-sync-export-" + inputId);
        if (inputElt.type == 'checkbox') {
          exportPreferences[inputId] = inputElt.checked;
        } else {
          exportPreferences[inputId] = inputElt.value;
        }
      });
      storage[provider.providerId + ".exportPreferences"] = JSON.stringify(exportPreferences);
    });
    $(".action-autosync-" + provider.providerId).click(function (event) {
      var config = provider.getAutosyncDialogConfig(event);
      if (config !== undefined) {
        storage[provider.providerId + ".autosyncConfig"] = JSON.stringify(config);
        provider.autosyncConfig = config;
      }
    });
  });
});

//eventMgr.onSynchronizerCreated(synchronizer);
messenger.publish.extension("onSynchronizerCreated", synchronizer);
module.exports = synchronizer;


text:
package com.microsoft.bingads.v10.campaignmanagement;

import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for AdRotationType.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *

 *

 * <simpleType name="AdRotationType">
 *   <restriction base="{http://www.w3.org/2001/XMLSchema}string">
 *     <enumeration value="OptimizeForClicks"/>
 *     <enumeration value="RotateAdsEvenly"/>
 *   </restriction>
 * </simpleType>
 *

 *
 */
@XmlType(name = "AdRotationType")
@XmlEnum
public enum AdRotationType {

    @XmlEnumValue("OptimizeForClicks")
    OPTIMIZE_FOR_CLICKS("OptimizeForClicks"),
    @XmlEnumValue("RotateAdsEvenly")
    ROTATE_ADS_EVENLY("RotateAdsEvenly");
    private final String value;

    AdRotationType(String v) {
        value = v;
    }

    public String value() {
        return value;
    }

    public static AdRotationType fromValue(String v) {
        for (AdRotationType c: AdRotationType.values()) {
            if (c.value.equals(v)) {
                return c;
            }
        }
        throw new IllegalArgumentException(v);
    }

}


text:
from pycassa.system_manager import *

KS = 'logsandra'

# Create keyspace
sys = SystemManager()
sys.create_keyspace(KS, 1)

# Create column families
sys.create_column_family(KS, 'keyword', comparator_type=TIME_UUID_TYPE)