text:
module Rubinius

  # IdentityMap is customized for uniquely storing elements from an Array to
  # implement the following Array methods: #&, #|, #-, #uniq, and #uniq!
  #
  # The algorithm used is double hashing with an overflow array. For each
  # array element, the element, its hash value, and its ordinal in the
  # sequence of elements added to the map are stored.
  #
  # Methods are provided to test an element for inclusion in the map and to
  # delete an entry from the map. The contents of a map can be returned as an
  # array in the order the elements were added to the map.

  class IdentityMap
    attr_reader :size

    Row = Table = Rubinius::Tuple
    MIN_CAPACITY = 64
    MIN_ROW = 10
    ROW_GROWTH = 9

    # Converts one or more Enumerable instances to a single IdentityMap
    def self.from(*arrays, &block)
      im = allocate
      Rubinius.privately { im.load(arrays, &block) }
      im
    end

    def initialize
      capacity = MIN_CAPACITY
      @table = Table.new capacity
      @mask = capacity - 4
      @max = capacity
      @size = 0
    end

    # Adds +item+ to the IdentityMap if it does not already exist. May cause
    # a row to be added or enlarged. Returns +self+.
    def insert(item, &block)
      redistribute if @size > @max

      if block_given?
        item_hash = yield(item).hash
      else
        item_hash = item.hash
      end

      index = item_hash & @mask
      table = @table

      if num_entries = table[index]
        index += 1

        if num_entries == 1
          return self if match?(table, index, item, item_hash, &block)

          table[index-1] = 2
          table[index] = promote_row table, index, item, item_hash, @size
        else
          i = 1
          row = table[index]
          total = row[0]

          while i < total
            return self if match?(row, i, item, item_hash, &block)
            i += 3
          end

          if total == row.size
            table[index] = enlarge_row row, item, item_hash, @size
          else
            i = row[0]
            set_item row, i, item, item_hash, @size
            row[0] = i + 3
          end
        end
      else
        table[index] = 1
        set_item table, index+1, item, item_hash, @size
      end
      @size += 1

      self
    end

    # Returns +true+ if +item+ is in the IdentityMap, +false+ otherwise.
    def include?(item)
      item_hash = item.hash

      index = item_hash & @mask
      table = @table
      if num_entries = table[index]
        index += 1

        if num_entries == 1
          return true if match? table, index, item, item_hash
        else
          row = table[index]
          i = 1
          total = row[0]
          while i < total
            return true if match? row, i, item, item_hash
            i += 3
          end
        end
      end

      false
    end

    # If +item+ is in the IdentityMap, removes it and returns +true+.
    # Otherwise, returns +false+.
    def delete(item)
      item_hash = item.hash

      index = item_hash & @mask
      table = @table

      if num_entries = table[index]
        index += 1
        if num_entries == 1
          if match? table, index, item, item_hash
            table[index] = nil
            @size -= 1
            return true
          end
        else
          row = table[index]
          i = 1
          total = row[0]
          while i < total
            if match? row, i, item, item_hash
              row[i] = nil
              @size -= 1
              return true
            end
            i += 3
          end
        end
      end

      false
    end

    # Returns an Array containing all items in the IdentityMap in the order
    # in which they were added to the IdentityMap.
    def to_array
      array = Array.new @size

      i = 0
      table = @table
      total = table.size

      while i < total
        if num_entries = table[i]
          if num_entries == 1
            array[table[i+3]] = table[i+2] if table[i+1]
          else
            row = table[i+1]
            k = row[0]
            j = 1
            while j < k
              array[row[j+2]] = row[j+1] if row[j]
              j += 3
            end
          end
        end

        i += 4
      end

      array
    end

    # Private implementation methods

    def resize(total)
      capacity = MIN_CAPACITY
      while capacity < total
        capacity <<= 2
      end

      @table = Table.new capacity
      @mask = capacity - 4
      @max = capacity
    end
    private :resize

    def redistribute
      table = @table
      resize @size

      i = 0
      total = table.size

      while i < total
        if num_entries = table[i]
          if num_entries == 1
            if item_hash = table[i+1]
              add_item table[i+2], item_hash, table[i+3]
            end
          else
            row = table[i+1]
            k = row[0]
            j = 1
            while j < k
              if item_hash = row[j]
                add_item row[j+1], item_hash, row[j+2]
              end
              j += 3
            end
          end
        end

        i += 4
      end
    end
    private :redistribute

    def add_item(item, item_hash, ordinal)
      index = item_hash & @mask
      table = @table

      if num_entries = table[index]
        index += 1

        if num_entries == 1
          table[index-1] = 2
          table[index] = promote_row table, index, item, item_hash, ordinal
        else
          row = table[index]
          i = row[0]

          if i == row.size
            table[index] = enlarge_row row, item, item_hash, ordinal
          else
            set_item row, i, item, item_hash, ordinal
            row[0] = i + 3
          end
        end
      else
        table[index] = 1
        set_item table, index+1, item, item_hash, ordinal
      end
    end
    private :add_item

    # Given an Array of Enumerable instances, computes a bounding set
    # to contain them and then adds each item to the IdentityMap.
    def load(arrays, &block)
      resize(arrays.inject(0) { |sum, array| sum + array.size })
      @size = 0

      arrays.each do |array|
        array.each { |item| insert(item, &block) }
      end
    end
    private :load

    def match?(table, index, item, item_hash, &block)
      if block_given?
        table[index] == item_hash and yield(item).eql? yield(table[index+1])
      else
        table[index] == item_hash and item.eql? table[index+1]
      end
    end
    private :match?

    def set_item(table, index, item, item_hash, ordinal)
      table[index]   = item_hash
      table[index+1] = item
      table[index+2] = ordinal
    end
    private :set_item

    def promote_row(row, index, item, item_hash, ordinal)
      new_row = Row.new MIN_ROW

      new_row[0] = 7
      new_row[1] = row[index]
      new_row[2] = row[index+1]
      new_row[3] = row[index+2]
      new_row[4] = item_hash
      new_row[5] = item
      new_row[6] = ordinal

      new_row
    end
    private :promote_row

    def enlarge_row(row, item, item_hash, ordinal)
      new_row = Row.new row.size + ROW_GROWTH
      new_row.copy_from row, 1, row.size-1, 1

      index = row[0]
      new_row[0] = index + 3
      set_item new_row, index, item, item_hash, ordinal

      new_row
    end
    private :enlarge_row
  end
end


text:
var app = angular.module('ProfileEvaluator',
                         ['ngMaterial', 'ngAnimate', 'ngMessages', 'ngAria', 'ui.router'])
.config(['$mdThemingProvider', '$stateProvider', '$urlRouterProvider', '$locationProvider',
         function($mdThemingProvider, $stateProvider, $urlRouterProvider, $locationProvider){
  $mdThemingProvider
    .theme("docs-dark","default")
    .primaryPalette("yellow").dark()
    .accentPalette("orange");

           // For routing
           $urlRouterProvider.otherwise('/home');

           $stateProvider.state('home', {
             url : '/home',
             templateUrl : './partials/home.html',
             controller : 'HomeController'
           });
           $stateProvider.state('university', {
             url : '/university',
             templateUrl : './partials/university.html',
             controller : 'HomeController'
           });
           $locationProvider.html5Mode(true).hashPrefix('!');
}]);

app.controller('HomeController', ['$scope', '$mdSidenav', function($scope, $mdSidenav){

}]);

redpajama_set_name: RedPajamaGithub


text:
import warnings

warnings.warn("This module has been moved to pexpect.fdpexpect, please update imports.",
                ImportWarning)
del warnings

from pexpect.fdpexpect import *  # analysis:ignore


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright company="" file="PkgCmdID.cs">
//
// </copyright>
// <summary>
//   The pkg cmd id list.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace PubliWeb.Tools.ReferenceSwitcher
{
    /// <summary>
    ///     The pkg cmd id list.
    /// </summary>
    internal static class PkgCmdIDList
    {
        /// <summary>
        ///     The cmdid reset project references.
        /// </summary>
        public const uint cmdidResetProjectReferences = 0x101;

        /// <summary>
        ///     The cmdid switch to project references.
        /// </summary>
        public const uint cmdidSwitchToProjectReferences = 0x100;
    };
}


text:
package org.apache.activemq.memory;

import java.util.Map;

import java.util.concurrent.ConcurrentHashMap;

/**
 * Use any Map to implement the Cache.  No cache eviction going on here.  Just gives
 * a Map a Cache interface.
 *
 *
 */
public class MapCache implements Cache {

    protected final Map<Object, Object> map;

    public MapCache() {
        this(new ConcurrentHashMap<Object, Object>());
    }

    public MapCache(Map<Object, Object> map) {
        this.map = map;
    }

    public Object put(Object key, Object value) {
        return map.put(key, value);
    }

    public Object get(Object key) {
        return map.get(key);
    }

    public Object remove(Object key) {
        return map.remove(key);
    }

    public void close() {
        map.clear();
    }

    public int size() {
        return map.size();
    }
}


text:
import React, { useCallback, useEffect, useRef, useState } from 'react'
import styled from 'styled-components'
import { assertUnreachable } from '../../common/assert-unreachable'
import { LocalSettingsData, ScrSettingsData } from '../../common/local-settings'
import { closeDialog, openDialog } from '../dialogs/action-creators'
import { CommonDialogProps } from '../dialogs/common-dialog-props'
import { DialogType } from '../dialogs/dialog-type'
import SetPathIcon from '../icons/material/settings-36px.svg'
import { JsonLocalStorageValue } from '../local-storage'
import { IconButton, TextButton } from '../material/button'
import { Dialog } from '../material/dialog'
import { TabItem, Tabs } from '../material/tabs'
import { useAppDispatch, useAppSelector } from '../redux-hooks'
import { colorError, colorTextSecondary } from '../styles/colors'
import { body1, subtitle1 } from '../styles/typography'
import { mergeLocalSettings, mergeScrSettings } from './action-creators'
import AppSettings from './app-settings'
import GameplaySettings from './gameplay-settings'
import InputSettings from './input-settings'
import { SettingsFormHandle } from './settings-form-ref'
import { LocalSettings, ScrSettings } from './settings-records'
import SoundSettings from './sound-settings'
import VideoSettings from './video-settings'

const TitleActionContainer = styled.div`
  display: flex;
  align-items: center;
  margin-right: 24px;
`

const TitleActionText = styled.div`
  ${body1};
  color: ${colorTextSecondary};
  margin-right: 4px;

  &:hover {
    cursor: pointer;
  }
`

const TitleActionButton = styled(IconButton)`
  flex-shrink: 0;
  min-height: 40px;
  width: 40px;
  line-height: 40px;
`

const ContentsBody = styled.div`
  margin-top: 24px;
`

const ErrorText = styled.div`
  ${subtitle1};
  color: ${colorError};
`

enum SettingsTab {
  App = 'app',
  Input = 'input',
  Video = 'video',
  Sound = 'sound',
  Gameplay = 'gameplay',
}

const savedSettingsTab = new JsonLocalStorageValue<SettingsTab>('settingsTab')

export default function SettingsDialog({ dialogRef, onCancel }: CommonDialogProps) {
  const dispatch = useAppDispatch()
  const localSettings = useAppSelector(s => s.settings.local)
  const scrSettings = useAppSelector(s => s.settings.scr)
  const lastError = useAppSelector(s => s.settings.lastError)

  const [activeTab, setActiveTab] = useState(savedSettingsTab.getValue() ?? SettingsTab.App)
  const [tempLocalSettings, setTempLocalSettings] = useState<LocalSettings>(localSettings)
  const [tempScrSettings, setTempScrSettings] = useState<ScrSettings>(scrSettings)

  const formRef = useRef<SettingsFormHandle>(null)
  const saveButtonRef = useRef<HTMLButtonElement>(null)

  const onTabChange = useCallback((value: SettingsTab) => {
    setActiveTab(value)
    savedSettingsTab.setValue(value)
  }, [])
  const onSetPathClick = useCallback(() => {
    dispatch(openDialog({ type: DialogType.StarcraftPath }))
  }, [dispatch])
  const onSettingsSave = useCallback(() => {
    formRef.current?.submit()
  }, [])
  const onSettingsCancel = useCallback(() => {
    dispatch(closeDialog(DialogType.Settings))
  }, [dispatch])
  const onSettingsChange = useCallback((settings: Partial<LocalSettings & ScrSettings>) => {
    setTempLocalSettings(prev => prev.merge(settings))
    setTempScrSettings(prev => prev.merge(settings))
  }, [])

  const onSettingsSubmit = useCallback(() => {
    // NOTE(tec27): We remove the StarCraft path here because we don't provide a way to change it
    // in this dialog anyway, and depending on how IPC events interleave, the SC Path dialog may
    // not have merged a new path by the time this dialog is first rendered. We don't want to merge
    // an old path back into the settings, so we just remove it instead.
    const localSettingsToMerge = tempLocalSettings.toJS()
    delete localSettingsToMerge.starcraftPath
    dispatch(mergeLocalSettings(localSettingsToMerge as Partial<LocalSettingsData>))
    dispatch(mergeScrSettings(tempScrSettings.toJS() as Partial<ScrSettingsData>))

    // TODO(tec27): This doesn't seem like it would actually catch errors from saving here? Since
    // those would happen async-ly. Should probably have a form of this that doesn't bother with
    // dispatching and just returns a promise we can await
    if (!lastError) {
      dispatch(closeDialog(DialogType.Settings))
    }
  }, [dispatch, tempLocalSettings, tempScrSettings, lastError])

  useEffect(() => {
    saveButtonRef.current?.focus()
  }, [])

  const starcraftVersionText = 'StarCraft: Remastered'
  const titleAction = (
    <TitleActionContainer>
      <TitleActionText onClick={onSetPathClick}>{starcraftVersionText}</TitleActionText>
      <TitleActionButton
        icon={<SetPathIcon />}
        title='Change StarCraft path'
        onClick={onSetPathClick}
      />
    </TitleActionContainer>
  )

  const tabs = (
    <Tabs activeTab={activeTab} onChange={onTabChange}>
      <TabItem key='app' text='App' value={SettingsTab.App} />
      <TabItem key='input' text='Input' value={SettingsTab.Input} />
      <TabItem key='sound' text='Sound' value={SettingsTab.Sound} />
      <TabItem key='video' text='Video' value={SettingsTab.Video} />
      <TabItem key='gameplay' text='Gameplay' value={SettingsTab.Gameplay} />
    </Tabs>
  )

  const buttons = [
    <TextButton label='Cancel' key='cancel' color='accent' onClick={onSettingsCancel} />,
    <TextButton
      ref={saveButtonRef}
      label='Save'
      key='save'
      color='accent'
      onClick={onSettingsSave}
    />,
  ]

  let contents: React.ReactNode
  switch (activeTab) {
    case SettingsTab.App:
      contents = (
        <AppSettings
          localSettings={tempLocalSettings}
          formRef={formRef}
          onChange={onSettingsChange}
          onSubmit={onSettingsSubmit}
        />
      )
      break
    case SettingsTab.Input:
      contents = (
        <InputSettings
          scrSettings={tempScrSettings}
          formRef={formRef}
          onChange={onSettingsChange}
          onSubmit={onSettingsSubmit}
        />
      )
      break
    case SettingsTab.Sound:
      contents = (
        <SoundSettings
          scrSettings={tempScrSettings}
          formRef={formRef}
          onChange={onSettingsChange}
          onSubmit={onSettingsSubmit}
        />
      )
      break
    case SettingsTab.Video:
      contents = (
        <VideoSettings
          scrSettings={tempScrSettings}
          formRef={formRef}
          onChange={onSettingsChange}
          onSubmit={onSettingsSubmit}
        />
      )
      break
    case SettingsTab.Gameplay:
      contents = (
        <GameplaySettings
          localSettings={tempLocalSettings}
          scrSettings={tempScrSettings}
          formRef={formRef}
          onChange={onSettingsChange}
          onSubmit={onSettingsSubmit}
        />
      )
      break
    default:
      contents = assertUnreachable(activeTab)
  }

  return (
    <Dialog
      dialogRef={dialogRef}
      title='Settings'
      titleAction={titleAction}
      tabs={tabs}
      alwaysHasTopDivider={true}
      buttons={buttons}
      onCancel={onCancel}>
      <ContentsBody>
        {lastError ? (
          <ErrorText>There was an issue saving the settings. Please try again.</ErrorText>
        ) : null}

        {contents}
      </ContentsBody>
    </Dialog>
  )
}


text:
package com.facebook.buck.rules.coercer;

import com.facebook.buck.core.cell.nameresolver.CellNameResolver;
import com.facebook.buck.core.model.TargetConfiguration;
import com.facebook.buck.core.path.ForwardRelativePath;
import com.facebook.buck.core.test.rule.TestRunnerSpec;
import com.facebook.buck.io.filesystem.ProjectFilesystem;
import com.facebook.buck.rules.macros.StringWithMacros;
import com.google.common.collect.ImmutableMap;
import com.google.common.reflect.TypeToken;
import java.util.Map;

/**
 * Coerces a freeform JSON as a {@link TestRunnerSpec}, which is basically a JSON containing {@link
 * StringWithMacros}
 */
public class TestRunnerSpecCoercer implements TypeCoercer<Object, TestRunnerSpec> {

  private final TypeCoercer<Object, StringWithMacros> macrosTypeCoercer;
  private final TypeCoercer<
          ImmutableMap<Object, Object>, ImmutableMap<StringWithMacros, TestRunnerSpec>>
      mapTypeCoercer;
  private final ListTypeCoercer<Object, TestRunnerSpec> listTypeCoercer;

  public TestRunnerSpecCoercer(TypeCoercer<Object, StringWithMacros> macrosTypeCoercer) {
    this.macrosTypeCoercer = macrosTypeCoercer;
    this.mapTypeCoercer = new MapTypeCoercer<>(macrosTypeCoercer, this);
    this.listTypeCoercer = new ListTypeCoercer<>(this);
  }

  @Override
  public TypeToken<TestRunnerSpec> getOutputType() {
    return TypeToken.of(TestRunnerSpec.class);
  }

  @Override
  public TypeToken<Object> getUnconfiguredType() {
    return TypeToken.of(Object.class);
  }

  @Override
  public boolean hasElementClass(Class<?>... types) {
    return false;
  }

  @Override
  public void traverse(CellNameResolver cellRoots, TestRunnerSpec object, Traversal traversal) {}

  @Override
  public Object coerceToUnconfigured(
      CellNameResolver cellRoots,
      ProjectFilesystem filesystem,
      ForwardRelativePath pathRelativeToProjectRoot,
      Object object)
      throws CoerceFailedException {
    return object;
  }

  @Override
  public TestRunnerSpec coerce(
      CellNameResolver cellRoots,
      ProjectFilesystem filesystem,
      ForwardRelativePath pathRelativeToProjectRoot,
      TargetConfiguration targetConfiguration,
      TargetConfiguration hostConfiguration,
      Object object)
      throws CoerceFailedException {

    return TestRunnerSpec.of(
        coerceRecursively(
            cellRoots,
            filesystem,
            pathRelativeToProjectRoot,
            targetConfiguration,
            hostConfiguration,
            object));
  }

  private Object coerceRecursively(
      CellNameResolver cellNameResolver,
      ProjectFilesystem filesystem,
      ForwardRelativePath pathRelativeToProjectRoot,
      TargetConfiguration targetConfiguration,
      TargetConfiguration hostConfiguration,
      Object object)
      throws CoerceFailedException {
    if (object instanceof Map) {
      return mapTypeCoercer.coerceBoth(
          cellNameResolver,
          filesystem,
          pathRelativeToProjectRoot,
          targetConfiguration,
          hostConfiguration,
          object);
    }
    if (object instanceof Iterable) {
      return listTypeCoercer.coerceBoth(
          cellNameResolver,
          filesystem,
          pathRelativeToProjectRoot,
          targetConfiguration,
          hostConfiguration,
          object);
    }
    if (object instanceof Number || object instanceof Boolean) {
      return object;
    }
    return macrosTypeCoercer.coerce(
        cellNameResolver,
        filesystem,
        pathRelativeToProjectRoot,
        targetConfiguration,
        hostConfiguration,
        object);
  }
}


text:
import Sequelize from 'sequelize'

import { DATABASE_NAME } from './constants'

const dbConfig = {
  query: {
    raw: false
  },
  logging: false,
  pool: {
    max: 10,
    idle: 10000
  },
  timezone: 'Asia/Bangkok'
}

const db = new Sequelize(`postgres://postgres:@localhost:5432/${DATABASE_NAME}`, dbConfig)

const AuthorModel = db.define('author', {
  id: {
    type: Sequelize.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  name: {
    type: Sequelize.STRING,
    require: true
  }
}, {
  underscored: true,
  timestamps: true,
  freezeTableName: true
})

const BookModel = db.define('book', {
  id: {
    type: Sequelize.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  title: Sequelize.STRING,
  isbn: Sequelize.STRING,
  price: Sequelize.INTEGER
}, {
  underscored: true,
  timestamps: true,
  freezeTableName: true
})

const CommentModel = db.define('comment', {
  id: {
    type: Sequelize.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  text: {
    type: Sequelize.STRING
  }
}, {
  underscored: true,
  timestamps: true,
  freezeTableName: true
})

BookModel.belongsTo(AuthorModel, {
  foreignKey: 'author_id'
})

CommentModel.belongsTo(AuthorModel, {
  foreignKey: 'author_id'
})

CommentModel.belongsTo(BookModel, {
  foreignKey: 'book_id'
})

const Author = db.models.author
const Book = db.models.book
const Comment = db.models.comment

Author.sync({force: false})
Book.sync({force: false})
Comment.sync({force: false})

export { Author, Book, Comment }


text:
import { CommandLineOptions } from '../../../../definitions';
import { AngularServeCLI, AngularServeRunner } from '../serve';

describe('@ionic/cli', () => {

  describe('lib/project/angular/serve', () => {

    describe('AngularServeRunner', () => {

      describe('createOptionsFromCommandLine', () => {

        const defaults = {
          '--': [],
          publicHost: undefined,
          host: 'localhost',
          browser: undefined,
          browserOption: undefined,
          engine: 'browser',
          externalAddressRequired: false,
          lab: false,
          labHost: 'localhost',
          labPort: 8200,
          livereload: true,
          open: false,
          port: 8100,
          proxy: true,
          project: 'app',
          prod: undefined,
          platform: undefined,
          verbose: false,
        };

        it('should provide defaults with no options', () => {
          const runner = new AngularServeRunner({} as any);
          const result = runner.createOptionsFromCommandLine([], {} as CommandLineOptions);
          expect(result).toEqual(defaults);
        });

        it('should provide options from negations of cli flag defaults', () => {
          const runner = new AngularServeRunner({} as any);
          const result = runner.createOptionsFromCommandLine([], { _: [], livereload: false, proxy: false, lab: true, open: true, externalAddressRequired: true });
          expect(result).toEqual({ ...defaults, livereload: false, proxy: false, lab: true, open: true, externalAddressRequired: true });
        });

        it('should allow overrides of default values', () => {
          const runner = new AngularServeRunner({} as any);
          const result = runner.createOptionsFromCommandLine([], { _: [], host: '0.0.0.0', port: '1111' });
          expect(result).toEqual({ ...defaults, host: '0.0.0.0', port: 1111 });
        });

        it('should respect --external flag', () => {
          const runner = new AngularServeRunner({} as any);
          const result = runner.createOptionsFromCommandLine([], { _: [], host: 'localhost', external: true });
          expect(result).toEqual({ ...defaults, host: '0.0.0.0' });
        });

        it('should respect --consolelogs flag', () => {
          const runner = new AngularServeRunner({} as any);
          const result = runner.createOptionsFromCommandLine([], { _: [], consolelogs: true });
          expect(result).toEqual({ ...defaults, consolelogs: true, consolelogsPort: 53703 });
        });

        it('should respect --project and --configuration flags', () => {
          const runner = new AngularServeRunner({} as any);
          const result = runner.createOptionsFromCommandLine([], { _: [], project: 'otherProject', configuration: 'production' });
          expect(result).toEqual({ ...defaults, project: 'otherProject', configuration: 'production' });
        });

        it('should pass on separated args', () => {
          const runner = new AngularServeRunner({} as any);
          const result = runner.createOptionsFromCommandLine([], { _: [], '--': ['foo', '--bar'] });
          expect(result).toEqual({ ...defaults, '--': ['foo', '--bar'] });
        });

      });

    });

    describe('AngularServeCLI', () => {

      describe('serveOptionsToNgArgs', () => {

        const defaults = {
          '--': [],
        };

        it('should pass options', async () => {
          const project = {};
          const cli = new AngularServeCLI({ project } as any);
          const options = {
            ...defaults,
            host: 'localhost',
            port: 4200,
            sourcemaps: true,
            ssl: true,
          };

          const result = await (cli as any).serveOptionsToNgArgs(options);
          expect(result).toEqual([
            `--host=${options.host}`,
            `--port=${options.port}`,
            `--source-map`,
            `--ssl`,
          ]);
        });

        it('should pass verbose flag', async () => {
          const project = {};
          const cli = new AngularServeCLI({ project } as any);
          const options = {
            ...defaults,
            verbose: true,
          };

          const result = await (cli as any).serveOptionsToNgArgs(options);
          expect(result).toEqual(['--verbose']);
        });

        it('should pass cordova options', async () => {
          const root = 'fakeRoot';
          const project = {
            requireIntegration: jest.fn(() => ({ root })),
          };
          const cli = new AngularServeCLI({ project } as any);
          const options = {
            ...defaults,
            engine: 'cordova',
            platform: 'fakePlatform',
          };

          const result = await (cli as any).serveOptionsToNgArgs(options);
          expect(result).toEqual([
            `--platform=${options.platform}`,
            `--cordova-base-path=${root}`,
          ]);
        });

        it('should pass separated options', async () => {
          const project = {};
          const cli = new AngularServeCLI({ project } as any);
          const options = {
            ...defaults,
            '--': ['--extra=true'],
          };

          const result = await (cli as any).serveOptionsToNgArgs(options);
          expect(result).toEqual(['--extra=true']);
        });

        it('should not pass separated options for cordova', async () => {
          const root = 'fakeRoot';
          const project = {
            requireIntegration: jest.fn(() => ({ root })),
          };
          const cli = new AngularServeCLI({ project } as any);
          const options = {
            ...defaults,
            engine: 'cordova',
            platform: 'fakePlatform',
            '--': ['--extra=true'],
          };

          const result = await (cli as any).serveOptionsToNgArgs(options);
          expect(result).not.toEqual(expect.arrayContaining(['--extra=true']));
        });

        it('should pass configuration and project for custom program', async () => {
          const project = {};
          const cli = new AngularServeCLI({ project } as any);
          (cli as any)._resolvedProgram = 'npm';
          const options = {
            ...defaults,
            configuration: 'production',
            project: 'otherProject',
          };

          const result = await (cli as any).serveOptionsToNgArgs(options);
          expect(result).toEqual(['--configuration=production', '--project=otherProject']);
        });

        it('should not pass configuration and project for custom program if they are the defaults', async () => {
          const project = {};
          const cli = new AngularServeCLI({ project } as any);
          (cli as any)._resolvedProgram = 'npm';
          const options = {
            ...defaults,
          };

          const result = await (cli as any).serveOptionsToNgArgs(options);
          expect(result).toEqual([]);
        });

      });

    });

  });

});


text:
namespace sd {
    SIMDEE_INL int lsb(unsigned int in) { return __builtin_ctz(in); }
    SIMDEE_INL int msb(unsigned int in) {
        return (8 * int(sizeof(unsigned int)) - 1) - __builtin_clz(in);
    }
    SIMDEE_INL int lsb(unsigned long in) { return __builtin_ctzl(in); }
    SIMDEE_INL int msb(unsigned long in) {
        return (8 * int(sizeof(unsigned long)) - 1) - __builtin_clzl(in);
    }
    SIMDEE_INL int lsb(unsigned long long in) { return __builtin_ctzll(in); }
    SIMDEE_INL int msb(unsigned long long in) {
        return (8 * int(sizeof(unsigned long long)) - 1) - __builtin_clzll(in);
    }
    SIMDEE_INL uint16_t bswap(uint16_t in) { return __builtin_bswap16(in); }
    SIMDEE_INL uint32_t bswap(uint32_t in) { return __builtin_bswap32(in); }
    SIMDEE_INL uint64_t bswap(uint64_t in) { return __builtin_bswap64(in); }
}

#elif defined(_MSC_VER) // Visual Studio

#include <intrin.h>

namespace sd {
    SIMDEE_INL unsigned long lsb(unsigned __int32 in) {
        unsigned long res;
        _BitScanForward(&res, in);
        return res;
    }
    SIMDEE_INL unsigned long msb(unsigned __int32 in) {
        unsigned long res;
        _BitScanReverse(&res, in);
        return res;
    }
    SIMDEE_INL uint16_t bswap(uint16_t in) { return _byteswap_ushort(in); }
    SIMDEE_INL uint32_t bswap(uint32_t in) { return _byteswap_ulong(in); }
    SIMDEE_INL uint64_t bswap(uint64_t in) { return _byteswap_uint64(in); }

#if defined(_M_X64)
    SIMDEE_INL unsigned long lsb(unsigned __int64 in) {
        unsigned long res;
        _BitScanForward64(&res, in);
        return res;
    }
    SIMDEE_INL unsigned long msb(unsigned __int64 in) {
        unsigned long res;
        _BitScanReverse64(&res, in);
        return res;
    }
#endif
}

#else

#error "util_1b.h: incompatible compiler"

#endif

namespace sd {
    // provides indices of set (1) bits, ordered from least significant to most significant
    struct bit_iterator : std::iterator<std::input_iterator_tag, uint32_t> {
        uint32_t mask;

        SIMDEE_INL constexpr bit_iterator(uint32_t mask_) : mask(mask_) {}
        SIMDEE_INL uint32_t operator*() const { return uint32_t(lsb(mask)); }
        SIMDEE_INL uint32_t operator->() const { return uint32_t(lsb(mask)); }
        SIMDEE_INL bit_iterator& operator++() {
            mask = mask & (mask - 1);
            return *this;
        }
        SIMDEE_INL bit_iterator operator++(int) {
            bit_iterator r = mask;
            operator++();
            return r;
        }
        SIMDEE_INL bool operator!=(const bit_iterator& rhs) const { return mask != rhs.mask; }
    };
}

#endif // SIMDEE_UTIL_BITFIDDLE_HPP


text:
package com.blogspot.sontx.chatsocket.client.model;

import java.io.Closeable;

/**
 * Lowest layer that communicates with {@link com.blogspot.sontx.chatsocket.server.model.Server}.
 */
public interface Client extends Closeable {
    void start();
}


text:
. setenv
$ADT -package -target ipa-test -storetype pkcs12 -storepass *** -keystore certificates.p12 -provisioning-profile profiles.mobileprovision Main.ipa app.xml Main.swf


text:
const areaService = require('../data/entityServices/areaService')

const createArea = (req, res) => {
    return areaService.createArea(req.body)
        .then(area => {
            res.send(area)
        })
}

const getAreaById = (req, res) => {
    return areaService.getAreaById(req.params.id)
        .then(area => {
            res.send(area);
        })
}

const createNoteForArea = (req, res) => {
    return areaService.createNoteForArea(req.body)
        .then(areaNote => {
            res.send(areaNote)
        })
}

const addTagToArea = (req, res) => {
    const {areaId, tagId} = req.params;

    return areaService.addTagToArea(areaId, tagId)
        .then(() => {
            res.send()
        })
}

const removeTagFromArea = (req, res) => {
    const {areaId, tagId} = req.params;

    return areaService.removeTagFromArea(areaId, tagId)
        .then(() => {
            res.send()
        })
}

const getAllAreas = (req, res) => {
    return areaService.getAllAreas()
        .then(areas => {
            res.send(areas)
        })
}

module.exports = app => {
    const url = '/api/area';
    app.post(`${url}/note`, createNoteForArea)
    app.put(`${url}/:areaId/tag/:tagId`, addTagToArea)
    app.delete(`${url}/:areaId/tag/:tagId`, removeTagFromArea)
    app.post(url, createArea)
    app.get(`${url}/:id`, getAreaById)
    app.get(url, getAllAreas)
}


text:
"""exec" "`dirname \"$0\"`/call.sh" "$0" "$@";" """
from __future__ import print_function

import collections
import os
import sys
import csv
import json
import re

import util

__doc__ = """
Created on Tue Jan 20 14:10:00 2015

@author: joschi
"""

input_format = {}

TYPE_PRESCRIBED = "prescribed"
TYPE_LABTEST    = "lab-test"
TYPE_DIAGNOSIS  = "diagnosis"
TYPE_PROCEDURE  = "procedure"
TYPE_PROVIDER   = "provider"
TYPE_PHYSICIAN  = "physician"

MODE_OPTIONAL = 0
MODE_DEFAULT = 1
MODE_ARRAY = 2

STATUS_UNKNOWN = 0
STATUS_IN = 1
STATUS_PROF = 2
STATUS_OUT = -1

STATUS_FLAG_MAP = {
    "I": STATUS_IN,
    "O": STATUS_OUT,
    "P": STATUS_PROF
}

gender_label = {
    "1": "primary",
    "2": "danger",
    "M": "primary",
    "W": "danger"
}
gender_map = {
    "1": "M",
    "2": "W",
    "M": "M",
    "W": "W"
}

def addInfo(obj, id, key, value, hasLabel = False, label = ""):
    for info in obj["info"]:
        if info["id"] == id:
            if str(value) != str(info["value"]):
                print('duplicate "'+id+'" new: '+str(value)+' old: '+str(info["value"]), file=sys.stderr)
            return
    node = {
        "id": id,
        "name": key,
        "value": value,
    }
    if hasLabel:
        node["label"] = label
    obj["info"].append(node)

def handleKey(row, key, mode, hnd):
    if mode == MODE_ARRAY:
        for k in input_format[key]:
            if k in row and row[k] != '':
                hnd(row[k])
        return
    ignore_missing = mode == MODE_DEFAULT
    if key in input_format:
        k = input_format[key]
        if util.is_array(k):
            found = False
            for key in k:
                if key in row and row[key] != '':
                    hnd(row[key])
                    found = True
                    break
            if not found and ignore_missing:
                hnd('')
        else:
            if k in row and row[k] != '':
                hnd(row[k])
            elif ignore_missing:
                hnd('')
    elif ignore_missing:
        hnd('')

def createEntry(group, id, claim_id, hasResult = False, resultFlag = False, result = ""):
    res = {
        "id": id,
        "group": group
    }
    if claim_id[0] is not None:
        res["row_id"] = claim_id[0]
    if hasResult:
        res["flag_value"] = result
        res["flag"] = resultFlag
    return res

def handleEvent(row, claim_id):
    res = []
    def emit(type, value):
        if value != '':
            res.append(createEntry(type, value, claim_id))

    handleKey(row, "diagnosis_icd9", MODE_ARRAY, lambda value: emit(TYPE_DIAGNOSIS, "icd9__" + value))
    handleKey(row, "procedures_icd9", MODE_ARRAY, lambda value: emit(TYPE_PROCEDURE, "icd9__" + value))
    handleKey(row, "procedures_cpt", MODE_ARRAY, lambda value: emit(TYPE_PROCEDURE, "cpt__" + value))
    # TODO HCPCS_CD_1 – HCPCS_CD_45: DESYNPUF: Revenue Center HCFA Common Procedure Coding System
    #handleKey(row, "procedures_hcpcs", MODE_ARRAY, lambda value: emit(TYPE_PROCEDURE, "hcpcs__" + value))
    handleKey(row, "provider_alt", MODE_ARRAY, lambda value: emit(TYPE_PROVIDER, "alt__" + value))
    handleKey(row, "provider_cms", MODE_ARRAY, lambda value: emit(TYPE_PROVIDER, "cms__" + value))
    handleKey(row, "physician_alt", MODE_ARRAY, lambda value: emit(TYPE_PHYSICIAN, "alt__" + value))
    handleKey(row, "physician_cms", MODE_ARRAY, lambda value: emit(TYPE_PHYSICIAN, "cms__" + value))
    return res

def handleRow(row, obj, statusMap={}, status=STATUS_UNKNOWN):
    curStatus = status
    claim_id = [ None ]

    def setClaimId(cid):
        claim_id[0] = cid

    handleKey(row, "claim_id", MODE_OPTIONAL, lambda value:
            setClaimId(value)
        )

    handleKey(row, "age", MODE_OPTIONAL, lambda value:
            addInfo(obj, 'age', 'Age', value)
        )
    handleKey(row, "born", MODE_OPTIONAL, lambda value:
            addInfo(obj, 'born', 'Born', int(str(value)[0:4]) if len(str(value)) >= 4 else 'N/A')
        )
    handleKey(row, "death", MODE_DEFAULT, lambda value:
            addInfo(obj, 'death', 'Died', int(str(value)[0:4]) if len(str(value)) >= 4 else 'N/A')
        )
    handleKey(row, "gender", MODE_OPTIONAL, lambda value:
            addInfo(obj, 'gender', 'Gender', gender_map.get(str(value), 'U'), True, gender_label.get(str(value), "default"))
        )

    def addCost(event, amount):
        event['cost'] = amount

    def handleStatusEvent(date, st):
        if date in statusMap:
            if statusMap[date] != STATUS_IN and st == STATUS_IN:
                statusMap[date] = st
            elif statusMap[date] != STATUS_PROF and st == STATUS_PROF:
                statusMap[date] = st
            elif statusMap[date] == STATUS_UNKNOWN:
                statusMap[date] = st
        else:
            statusMap[date] = st

    def admissionDates(fromDate, toDate):
        if fromDate == '':
            if toDate == '':
                return
            fromDate = toDate
            toDate = ''
        curDate = util.toTime(fromDate)
        endDate = util.toTime(toDate) if toDate != '' else curDate
        while curDate <= endDate:
            handleStatusEvent(curDate, STATUS_IN)
            curDate = util.nextDay(curDate)

    handleKey(row, "admission", MODE_OPTIONAL, lambda in_from:
        handleKey(row, "discharge", MODE_OPTIONAL, lambda in_to:
                admissionDates(in_from, in_to)
            )
        )

    def dates(fromDate, toDate):
        if fromDate == '':
            if toDate == '':
                return
            fromDate = toDate
            toDate = ''
        curDate = util.toTime(fromDate)
        endDate = util.toTime(toDate) if toDate != '' else curDate
        while curDate <= endDate:
            for event in handleEvent(row, claim_id):
                event['time'] = curDate
                handleKey(row, "claim_amount", MODE_OPTIONAL, lambda amount:
                    addCost(event, amount)
                )
                obj['events'].append(event)
            handleStatusEvent(curDate, curStatus)
            handleKey(row, "location_flag", MODE_OPTIONAL, lambda flag:
                handleStatusEvent(curDate, STATUS_FLAG_MAP.get(flag, STATUS_UNKNOWN))
            )
            curDate = util.nextDay(curDate)

    handleKey(row, "claim_from", MODE_OPTIONAL, lambda fromDate:
            handleKey(row, "claim_to", MODE_DEFAULT, lambda toDate:
                dates(fromDate, toDate)
            )
        )

    def emitNDC(date, ndc):
        # TODO add provider/physician here as well?
        event = createEntry(TYPE_PRESCRIBED, "ndc__" + ndc, claim_id)
        curDate = util.toTime(date)
        event['time'] = curDate
        handleKey(row, "location_flag", MODE_OPTIONAL, lambda flag:
            handleStatusEvent(curDate, STATUS_FLAG_MAP.get(flag, STATUS_UNKNOWN))
        )
        handleKey(row, "prescribed_amount", MODE_OPTIONAL, lambda amount:
            addCost(event, amount)
        )
        obj['events'].append(event)

    handleKey(row, "prescribed_date", MODE_OPTIONAL, lambda date:
            handleKey(row, "prescribed", MODE_OPTIONAL, lambda ndc:
                emitNDC(date, ndc)
            )
        )

    def emitLab(date, loinc, result, resultFlag):
        # TODO add provider/physician here as well?
        event = createEntry(TYPE_LABTEST, "loinc__" + loinc, claim_id, result != '' or resultFlag != '', resultFlag, result)
        event['time'] = util.toTime(date)
        obj['events'].append(event)

    handleKey(row, "lab_date", MODE_OPTIONAL, lambda date:
            handleKey(row, "lab_code", MODE_OPTIONAL, lambda loinc:
                handleKey(row, "lab_result", MODE_DEFAULT, lambda result:
                    handleKey(row, "lab_flag", MODE_DEFAULT, lambda flag:
                        emitLab(date, loinc, result, flag)
                    )
                )
            )
        )

def processFile(inputFile, id, obj, statusMap):
    if inputFile == '-':
        for row in csv.DictReader(sys.stdin):
            if id == row[input_format["patient_id"]]:
                handleRow(row, obj, statusMap, STATUS_UNKNOWN)
        return
    with open(inputFile) as csvFile:
        for row in csv.DictReader(csvFile):
            if id == row[input_format["patient_id"]]:
                status = STATUS_UNKNOWN
                if "inpatient" in inputFile.lower():
                    status = STATUS_IN
                elif "outpatient" in inputFile.lower():
                    status = STATUS_OUT
                handleRow(row, obj, statusMap, status)

def process(allPaths, lineFile, classFile, id):
    obj = {
        "info": [],
        "events": [],
        "h_bars": [],
        "v_bars": [ "auto" ],
        "v_spans": [],
        "classes": {}
    }
    util.add_files(obj, lineFile, classFile)

    addInfo(obj, "pid", "Patient", id)
    if len(allPaths) == 0:
        print('warning: no path given', file=sys.stderr)
    statusMap = {}
    for (path, isfile) in allPaths:
        if isfile:
            processFile(path, id, obj, statusMap)
        else:
            util.process_id_directory(path, id, lambda file, id: processFile(file, id, obj, statusMap))
    curInStart = None
    curInEnd = None
    curStatus = STATUS_UNKNOWN
    for k in sorted(statusMap):
        status = statusMap[k]
        if status == curStatus:
            if curInStart is None:
                curInStart = k
            curInEnd = k
        else:
            if curInStart is not None:
                if curStatus == STATUS_IN:
                    obj["v_spans"].append({
                        "from": curInStart,
                        "to": util.nextDay(curInEnd),
                        "class": "in_hospital"
                    })
                elif curStatus == STATUS_PROF:
                    obj["v_spans"].append({
                        "from": curInStart,
                        "to": util.nextDay(curInEnd),
                        "class": "professional"
                    })
                curInStart = None
            curStatus = status
    min_time = float('inf')
    max_time = float('-inf')
    for e in obj["events"]:
        time = e["time"]
        if time < min_time:
            min_time = time
        if time > max_time:
            max_time = time
    obj["start"] = min_time
    obj["end"] = max_time
    addInfo(obj, "event_count", "Events", len(obj["events"]))
    return obj

def usage():
    print('usage: {0} [-h] [-o <output>] -f <format> -p <id> [-l <file>] [-c <file>] -- <file or path>...'.format(sys.argv[0]), file=sys.stderr)
    print('-h: print help', file=sys.stderr)
    print('-o <output>: specifies output file. stdout if omitted or "-"', file=sys.stderr)
    print('-f <format>: specifies table format file', file=sys.stderr)
    print('-p <id>: specifies the patient id', file=sys.stderr)
    print('-l <file>: specifies a file for line and span infos', file=sys.stderr)
    print('-c <file>: specifies a file for class definitions as json object', file=sys.stderr)
    print('<file or path>: a list of input files or paths containing them. "-" represents stdin', file=sys.stderr)
    exit(1)

if __name__ == '__main__':
    lineFile = None
    classFile = None
    pid = None
    output = '-'
    args = sys.argv[:]
    args.pop(0)
    while args:
        arg = args.pop(0)
        if arg == '--':
            break
        if arg == '-h':
            usage()
        if arg == '-f':
            if not args or args[0] == '--':
                print('-f requires format file', file=sys.stderr)
                usage()
            util.read_format(args.pop(0), input_format, usage)
        elif arg == '-o':
            if not args or args[0] == '--':
                print('-o requires output file', file=sys.stderr)
                usage()
            output = args.pop(0)
            output = re.sub(r'(^|[^%])((?:%%)*)%p', r'\1\2foo', output).replace('%%', '%')
        elif arg == '-p':
            if not args or args[0] == '--':
                print('no id specified', file=sys.stderr)
                usage()
            pid = args.pop(0)
        elif arg == '-l':
            if not args or args[0] == '--':
                print('no file specified', file=sys.stderr)
                usage()
            lineFile = args.pop(0)
        elif arg == '-c':
            if not args or args[0] == '--':
                print('no file specified', file=sys.stderr)
                usage()
            classFile = args.pop(0)
        else:
            print('unrecognized argument: ' + arg, file=sys.stderr)
            usage()
    if pid is None:
        print('need to specify id with -p', file=sys.stderr)
        usage()
    allPaths = []
    util.convert_paths(args, allPaths)
    obj = process(allPaths, lineFile, classFile, pid)
    if output != '-' and not os.path.exists(os.path.dirname(output)):
        os.makedirs(os.path.dirname(output))
    with util.OutWrapper(output) as out:
        print(json.dumps(obj, indent=2, sort_keys=True), file=out)


text:
<?php

namespace AppBundle\Tools;

use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;

/**
 * Class FakeLogService
 */
class FakeLogService
{
    /**
     * @var LoggerInterface
     */
    protected $logger;
    /**
     * @var string
     */
    protected $exerciseName;

    /**
     * Exercise1Service constructor.
     * @param string $exerciseName
     * @param LoggerInterface $logger
     */
    public function __construct($exerciseName, LoggerInterface $logger = null)
    {
        $this->exerciseName = $exerciseName;
        $this->logger = $logger ? $logger : new NullLogger();
    }

    /**
     * @return string
     */
    public function createFakeErrorLog()
    {
        $message = sprintf('This is an error message for %s', $this->exerciseName);
        $this->fakeErrorLog($message);
    }

    /**
     * @return string
     */
    public function createFakeLogs()
    {
        $message = sprintf('This is an error message for %s', $this->exerciseName);
        $count = 1;
        while ($count <= 10) {
            $this->fakeErrorLog($message . ' : ' . $count);
            $this->fakeInfoLog($message . ' : ' . $count);
            $count++;
        }
    }

    /**
     * @param $message
     */
    private function fakeInfoLog($message)
    {
        $this->logger->info($message);
    }
    /**
     * @param $message
     */
    private function fakeErrorLog($message)
    {
        $this->logger->error($message);
    }
}


text:
#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHICS_FILTERS_FE_FLOOD_H_
#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHICS_FILTERS_FE_FLOOD_H_

#include "third_party/blink/renderer/platform/graphics/filters/filter_effect.h"
#include "third_party/skia/include/core/SkColor.h"

namespace blink {

class PLATFORM_EXPORT FEFlood final : public FilterEffect {
 public:
  FEFlood(Filter*, const SkColor4f&, float);

  SkColor4f FloodColor() const;
  bool SetFloodColor(const SkColor4f&);

  float FloodOpacity() const;
  bool SetFloodOpacity(float);

  // feFlood does not perform color interpolation of any kind, so the result is
  // always in the current color space regardless of the value of
  // color-interpolation-filters.
  void SetOperatingInterpolationSpace(InterpolationSpace) override {}

  WTF::TextStream& ExternalRepresentation(WTF::TextStream&,
                                          int indention) const override;

 private:
  sk_sp<PaintFilter> CreateImageFilter() override;

  SkColor4f flood_color_;
  float flood_opacity_;
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHICS_FILTERS_FE_FLOOD_H_


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Phyllostictella cucurbitacearum Tassi

### Remarks
null


text:
package org.apache.pulsar.functions.instance;

import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.testng.Assert;
import org.testng.annotations.Test;

import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

@Slf4j
/**
 * This test serves to make sure that the correct classes are included in the java-instance.jar
 * THAT JAR SHOULD ONLY CONTAIN THE INTERFACES THAT PULSAR FUNCTION'S FRAMEWORK USES TO INTERACT WITH USER CODE
 * WHICH INCLUDES CLASSES FROM THE FOLLOWING LIBRARIES
 *     1. pulsar-io-core
 *     2. pulsar-functions-api
 *     3. pulsar-client-api
 *     4. slf4j-api
 *     5. log4j-slf4j-impl
 *     6. log4j-api
 *     7. log4j-core
 *     8. Apache AVRO
 *     9. Jackson Mapper and Databind (dependency of AVRO)
 *     10. Apache Commons Compress (dependency of AVRO)
 */
public class JavaInstanceDepsTest {

    @Test
    public void testInstanceJarDeps() throws IOException {
        File jar = new File("target/java-instance.jar");

        @Cleanup
        ZipInputStream zip = new ZipInputStream(jar.toURI().toURL().openStream());

        List<String> notAllowedClasses = new LinkedList<>();
        while(true) {
            ZipEntry e = zip.getNextEntry();
            if (e == null)
                break;
            String name = e.getName();
            if (name.endsWith(".class") && !name.startsWith("META-INF") && !name.equals("module-info.class")) {
                // The only classes in the java-instance.jar should be org.apache.pulsar, slf4j, and log4j classes
                // (see the full list above)
                // filter out those classes to see if there are any other classes that should not be allowed
                if (!name.startsWith("org/apache/pulsar")
                        && !name.startsWith("org/slf4j")
                        && !name.startsWith("org/apache/avro")
                        && !name.startsWith("com/fasterxml/jackson")
                        && !name.startsWith("org/apache/commons/compress")
                        && !name.startsWith("com/google")
                        && !name.startsWith("org/checkerframework")
                        && !name.startsWith("javax/annotation")
                        && !name.startsWith("org/apache/logging/slf4j")
                        && !name.startsWith("org/apache/logging/log4j")) {
                    notAllowedClasses.add(name);
                }
            }
        }

        Assert.assertEquals(notAllowedClasses, Collections.emptyList(), notAllowedClasses.toString());
    }
}


text:
package com.vanhal.recallstones.client;

import com.vanhal.recallstones.ItemRecallStoneBlank;
import com.vanhal.recallstones.RecallStones;
import com.vanhal.recallstones.Messages.MessageMarkStone;

import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.GuiTextField;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.ResourceLocation;

public class GUINameStone extends GuiScreen  {
	public final ResourceLocation texture = new ResourceLocation("recallstones", "textures/gui/gui.png");
	public final int xSizeOfTexture = 176;
	public final int ySizeOfTexture = 88;

	private GuiTextField locationField;
	private String locationName = "";

	public GUINameStone(EntityPlayer player) {

	}

	public void drawScreen(int x, int y, float f) {
		drawDefaultBackground();

		this.mc.getTextureManager().bindTexture(this.texture);
		int startX = (width - xSizeOfTexture) / 2;
        int startY = (height - ySizeOfTexture) / 2;
		this.drawTexturedModalRect(startX, startY, 0, 0, xSizeOfTexture, ySizeOfTexture);

		this.drawString(fontRendererObj, "Enter a Name for this location:", startX + 6, startY + 12, 0xEEEEEE);

		locationField.drawTextBox();

		super.drawScreen(x, y, f);
	}

	public void initGui() {
		int posX = (width - xSizeOfTexture) / 2;
        int posY = (height - ySizeOfTexture) / 2;

        this.buttonList.clear();
        this.buttonList.add(new GuiButton(1, posX + 6, posY + 60, 78, 20, "Cancel"));
        this.buttonList.add(new GuiButton(2, posX + 90, posY + 60, 78, 20, "Mark Location"));

        locationField = new GuiTextField(fontRendererObj, posX + 6, posY + 30, 162, 20);
        locationField.setFocused(true);
        locationField.setMaxStringLength(80);

	}

	protected void keyTyped(char c, int i) {
		super.keyTyped(c, i);
		if (locationField.isFocused()) {
			locationField.textboxKeyTyped(c, i);
		}
		if (i == 28) {
			submitButton();
		}
	}

	public void mouseClicked(int i, int j, int k) {
		super.mouseClicked(i, j, k);
		locationField.mouseClicked(i, j, k);
	}

	public void actionPerformed(GuiButton button) {
		if (button.id == 1) { //cancel
			this.mc.thePlayer.closeScreen();
		} else if (button.id == 2) {
			submitButton();
		}
	}

	public void submitButton() {
		this.mc.thePlayer.closeScreen();
		if (this.mc.thePlayer.getHeldItem().getItem() instanceof ItemRecallStoneBlank) {
			//send pack to server with name.
			MessageMarkStone msg = new MessageMarkStone(locationField.getText());
			RecallStones.network.sendToServer(msg);
		}
	}

	public boolean doesGuiPauseGame() {
		return false;
	}

}


text:
cd /app

echo "Creating a new django superuser"
python manage.py createsuperuser

echo "Updating authentication provider settings"
python manage.py update_auth_providers

echo "Running migration of the pontoon-intro module"
python manage.py sync_projects --projects=pontoon-intro --no-commit


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

<TITLE>
B-Index
</TITLE>

<META NAME="date" CONTENT="2013-09-29">

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

      Overview
      Package
      Class
      Use
      Tree
      Deprecated
    Index
      Help

 PREV LETTER
 NEXT LETTER

  FRAMES
 NO FRAMES

  All Classes

A B C G I L P S

B

bucketName -
Variable in class com.vaadin.server.sessionstorage.AmazonS3SessionStorage

      Overview
      Package
      Class
      Use
      Tree
      Deprecated
    Index
      Help

 PREV LETTER
 NEXT LETTER

  FRAMES
 NO FRAMES

  All Classes

A B C G I L P S


text:
package com.njyb.gbdbas.lock;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
/**
 * 重写异步的各种子方法
 * @author 贾红平
 *
 */
public class LockQueuedSynchronizer extends AbstractQueuedSynchronizer {
	private static final long serialVersionUID = 1L;
	//声明原子量 来实现异步
	private AtomicInteger state;
	public LockQueuedSynchronizer() {
		state=new AtomicInteger(0);
	}

	 /**
	  * 类似锁的功能
	  */
	@Override
	protected boolean tryAcquire(int arg) {
		return state.compareAndSet(0, 1);
	}

	 /**
	  * 类似释放锁的功能
	  */
	@Override
	protected boolean tryRelease(int arg) {
		return state.compareAndSet(1, 0);
	}
}


text:
'''
Created on April 10, 2012

@author: Paul Klingelhuber - s1010455@students.fh-hagenberg.at
'''
import os
# CONFIGURE HERE:

## FOLDERS SETUP  \n
## you can use your own simply by replacing it with sth like: \n
#COPY_RSS_AND_HTML_HERE = "C:/apache/htdocs/reporter/" \n
## or on Linux: \n
#COPY_RSS_AND_HTML_HERE = "/var/www/reporter/" \n

COPY_RSS_AND_HTML_HERE = os.path.join(os.getenv('USERPROFILE') or os.getenv('HOME'), "Dropbox/Public/PyReport")
## lastly specify the base url for the links inside the html report \n
##RSS_AND_HTML_BASE_URL = "http://www.yourserver.com/reporter/" \n
## This is an example BASE_URL if you use the Dropbox public folder \n
##RSS_AND_HTML_BASE_URL = "http://dl.dropbox.com/u/0000000/"
RSS_AND_HTML_BASE_URL = "file:///" + COPY_RSS_AND_HTML_HERE.replace("\\", "/") #@UnusedVariable

## EMAIL SETUP \n
## for most simple setup, use a gmail address  \n
## specify the email address and the password below   \n
## in the basic setup, you will receive an email from yourself   \n
## NON-GMAIL: change settings accordingly further below
ALERT_EMAIL_ENABLED = True
ALERT_EMAIL_ADDRESS = "yourname@gmail.com"
ALERT_EMAIL_ADDRESS_PASSWORD = "your_pw" #@UnusedVariable

# ADVANCED EMAIL SETUP (for non-gmail setup)

## by default, you will get an email from yourself, you could change this here
ALERT_EMAIL_ADDRESS_FROM = ALERT_EMAIL_ADDRESS

## the server that is used for sending
EMAIL_SERVER = "smtp.gmail.com:587"
## ssl or not
EMAIL_USE_TLS = True

## this tries to load a cusotm local config file (ConfigLocal.py)
try:
    from ConfigLocal import * #@UnusedWildImport

    if ALERT_EMAIL_ADDRESS_FROM == "yourname@gmail.com":
        ALERT_EMAIL_ADDRESS_FROM = ALERT_EMAIL_ADDRESS
except:
    pass


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>SB Admin - Bootstrap Admin Template</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/bootstrap-theme.min.css" rel="stylesheet">

    <link href="css/sb-admin.css" rel="stylesheet">

    <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">

    <link rel="stylesheet" href="./kanban/jquery-ui-1.8.6.css" type="text/css" media="all">
    <link rel="stylesheet" href="./kanban/kanban.css" type="text/css" media="all">

    <link rel="stylesheet" href="malihu-custom-scrollbar-plugin/jquery.mCustomScrollbar.css">

                show menu

                Change color

            Background

                Lists

            Item 2
            Item 3

            Activity

John Smith

Lorem ipsum dolor sit amet, consectetur
                            Yesterday at 4:32 PM

John Smith

Lorem ipsum dolor sit amet, consectetur
                            Yesterday at 4:32 PM

John Smith

Lorem ipsum dolor sit amet, consectetur
                            Yesterday at 4:32 PM

John Smith

Lorem ipsum dolor sit amet, consectetur
                            Yesterday at 4:32 PM

John Smith

Lorem ipsum dolor sit amet, consectetur
                            Yesterday at 4:32 PM

                    Read All New Messages

                        <button id="add_task" type="button" value="NEW TASK" class="btn btn-info btn-sm"></button>
                        <button id="remove_col" type="button" value="DELETE COLUMN" class="btn btn-sm btn-danger"></button>
                        <button id="add_col" type="button" value="NEW COLUMN" class="btn btn-sm btn-primary"></button>

Backlog

In Process

Finished

Item 1

resp 1

<input n="1" class="color colorete" type="color" data-text="hidden" data-colorlink="box_itm1" value="rgb(180,0,200)">

<button class="btn btn-danger btn-xs"></button>

<button class="btn btn-info btn-xs"></button>


text:
using System;

namespace CodeSearcher.Interfaces
{
    /// <summary>
    /// Interface to write findings to file
    /// </summary>
    public interface IResultExporter : IDisposable
    {
        /// <summary>
        /// Dump the results (findings) into a file with a specific format
        /// </summary>
        /// <param name="searchResultContainer">Enumeration of all finding of word to look for within index</param>
        /// <param name="searchedWord">Word to look for</param>
        void Export(ISearchResultContainer searchResultContainer, string searchedWord);
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Squirrel;

namespace SalesforcePackager
{
    class UpdaterClass
    {
        public static async Task updateApp()
        {
            using (var mgr = new UpdateManager(Common.Settings.getAppCache().updaterPath))
            {
                ReleaseEntry re =  await mgr.UpdateApp();

            }
        }
    }
}


text:
using Newtonsoft.Json;
using System.Collections.Generic;

namespace ShopifySharp
{
    /// <summary>
    /// An object representing a Shopify line item edit.
    /// The Id of this object is the Id of the line item being edited
    /// </summary>
    public class OrderEditLineItems
    {
        /// <summary>
        /// The additions to the line item
        /// </summary>
        [JsonProperty("additions")]
        public IEnumerable<OrderEditLineItemDelta> Additions { get; set; }

        /// <summary>
        /// The removals to the line item
        /// </summary>
        [JsonProperty("removals")]
        public IEnumerable<OrderEditLineItemDelta> Removals { get; set; }
    }
}


text:
/* global describe, it */

var map    = require('./');
var expect = require('chai').expect;

describe('map', function () {
  it('should map over strings', function () {
    var result = map('test', function (letter, index, string) {
      expect(index).to.be.a('number');
      expect(letter).to.equal('test'.charAt(index));
      expect(string).to.equal('test');

      return index + 1;
    });

    expect(result).to.equal('1234');
  });

  it('should map over arrays', function () {
    var input = ['t', 'e', 's', 't'];

    var result = map(input, function (letter, index, array) {
      expect(index).to.be.a('number');
      expect(letter).to.equal('test'.charAt(index));
      expect(array).to.equal(input);

      return String.fromCharCode(letter.charCodeAt(0) + 1);
    });

    expect(result).to.deep.equal(['u', 'f', 't', 'u']);
  });

  it('should map over object properties', function () {
    var input = {
      this: 'that',
      something: 'else'
    };

    var result = map(input, function (value, key, object) {
      expect(key).to.be.a('string');
      expect(value).to.equal(input[key]);
      expect(object).to.equal(input);

      return 'welp';
    });

    expect(result).to.deep.equal({
      this: 'welp',
      something: 'welp'
    });
  });

  it('should be able to set the callback context', function () {
    var context = {};

    map('test', function () {
      expect(this).to.equal(context);
    }, context);
  });

  it('should ignore properties inherited on the prototype', function () {
    var parent = {
      test: 'property'
    };

    var child = Object.create(parent);
    child.property = 'test';

    map(child, function (value, key) {
      expect(key).to.not.equal('test');
      expect(value).to.not.equal('property');
    });
  });

  it('should not error with undefined value', function () {
    map(null /*, function () {} */);
  });
});


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Spring Twitter Client</string>
    <string name="twitter_description">Twitter example using Spring Social.</string>
    <string name="user">User</string>
    <string name="message">Message</string>
    <string name="send">Send</string>
    <string name="whats_happening">What\'s happening?</string>
    <string name="tweet">Tweet</string>

</resources>


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

    <title>Overview (${title})</title>
    <link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

    All Classes

Packages

Primitive types

        <% packages.grep().each { %>

${it.name}

        <% } %>


text:
01
--

Intro
-----

Welcome to <Company>.

For the past 20 our scientists and engineers have been working on a top secret project.

At last, they have succeeded in creating a marvelous machine, a computing machine.

We call it 'The Computing Machine'.

You had the fortune to be selected as one of the chosen few to operate The Computing Machine.

At <Company>, we have a lot of challenges waiting to be solved.

Fortunately for you, The Computing Machine is really simple to operate, it only has two buttons!

All you have to do is insert the right combination of the two buttons, and The Computing Machine will do the rest!

Good Luck!


text:
package org.apache.predictionio.controller

import org.apache.predictionio.workflow.WorkflowParams
import org.scalatest.FunSuite
import org.scalatest.Inside
import org.scalatest.Matchers._
import org.scalatest.Inspectors._

import org.apache.predictionio.workflow.SharedSparkContext

class FastEngineSuite
extends FunSuite with Inside with SharedSparkContext {
  import org.apache.predictionio.controller.Engine0._

  test("Single Evaluation") {
    val engine = new FastEvalEngine(
      Map("" -> classOf[PDataSource2]),
      Map("" -> classOf[PPreparator1]),
      Map(
        "PAlgo2" -> classOf[PAlgo2],
        "PAlgo3" -> classOf[PAlgo3]
      ),
      Map("" -> classOf[LServing1]))

    val qn = 10
    val en = 3

    val engineParams = EngineParams(
      dataSourceParams = PDataSource2.Params(id = 0, en = en, qn = qn),
      preparatorParams = PPreparator1.Params(1),
      algorithmParamsList = Seq(
        ("PAlgo2", PAlgo2.Params(20)),
        ("PAlgo2", PAlgo2.Params(21)),
        ("PAlgo3", PAlgo3.Params(22))
      ),
      servingParams = LServing1.Params(3))

    val algoCount = engineParams.algorithmParamsList.size
    val pd = ProcessedData(1, TrainingData(0))
    val model0 = PAlgo2.Model(20, pd)
    val model1 = PAlgo2.Model(21, pd)
    val model2 = PAlgo3.Model(22, pd)

    val evalDataSet = engine.eval(sc, engineParams, WorkflowParams())

    evalDataSet should have size en

    forAll(evalDataSet.zipWithIndex) { case (evalData, ex) => {
      val (evalInfo, qpaRDD) = evalData
      evalInfo shouldBe EvalInfo(0)

      val qpaSeq: Seq[(Query, Prediction, Actual)] = qpaRDD.collect

      qpaSeq should have size qn

      forAll (qpaSeq) { case (q, p, a) =>
        val Query(qId, qEx, qQx, _) = q
        val Actual(aId, aEx, aQx) = a
        qId shouldBe aId
        qEx shouldBe ex
        aEx shouldBe ex
        qQx shouldBe aQx

        inside (p) { case Prediction(pId, pQ, pModels, pPs) => {
          pId shouldBe 3
          pQ shouldBe q
          pModels shouldBe None
          pPs should have size algoCount
          pPs shouldBe Seq(
            Prediction(id = 20, q = q, models = Some(model0)),
            Prediction(id = 21, q = q, models = Some(model1)),
            Prediction(id = 22, q = q, models = Some(model2))
          )
        }}
      }
    }}
  }

  test("Batch Evaluation") {
    val engine = new FastEvalEngine(
      Map("" -> classOf[PDataSource2]),
      Map("" -> classOf[PPreparator1]),
      Map("" -> classOf[PAlgo2]),
      Map("" -> classOf[LServing1]))

    val qn = 10
    val en = 3

    val baseEngineParams = EngineParams(
      dataSourceParams = PDataSource2.Params(id = 0, en = en, qn = qn),
      preparatorParams = PPreparator1.Params(1),
      algorithmParamsList = Seq(("", PAlgo2.Params(2))),
      servingParams = LServing1.Params(3))

    val ep0 = baseEngineParams
    val ep1 = baseEngineParams.copy(
      algorithmParamsList = Seq(("", PAlgo2.Params(2))))
    val ep2 = baseEngineParams.copy(
      algorithmParamsList = Seq(("", PAlgo2.Params(20))))

    val engineEvalDataSet = engine.batchEval(
      sc,
      Seq(ep0, ep1, ep2),
      WorkflowParams())

    val evalDataSet0 = engineEvalDataSet(0)._2
    val evalDataSet1 = engineEvalDataSet(1)._2
    val evalDataSet2 = engineEvalDataSet(2)._2

    evalDataSet0 shouldBe evalDataSet1
    evalDataSet0 should not be evalDataSet2
    evalDataSet1 should not be evalDataSet2

    // evalDataSet0._1 should be theSameInstanceAs evalDataSet1._1
    // When things are cached correctly, evalDataSet0 and 1 should share the
    // same EI
    evalDataSet0.zip(evalDataSet1).foreach { case (e0, e1) => {
      e0._1 should be theSameInstanceAs e1._1
      e0._2 should be theSameInstanceAs e1._2
    }}

    // So as set1 and set2, however, the QPA-RDD should be different.
    evalDataSet1.zip(evalDataSet2).foreach { case (e1, e2) => {
      e1._1 should be theSameInstanceAs e2._1
      val e1Qpa = e1._2
      val e2Qpa = e2._2
      e1Qpa should not be theSameInstanceAs (e2Qpa)
    }}
  }

  test("Not cached when isEqual not implemented") {
    // PDataSource3.Params is a class not case class. Need to implement the
    // isEqual function for hashing.
    val engine = new FastEvalEngine(
      Map("" -> classOf[PDataSource4]),
      Map("" -> classOf[PPreparator1]),
      Map("" -> classOf[PAlgo2]),
      Map("" -> classOf[LServing1]))

    val qn = 10
    val en = 3

    val baseEngineParams = EngineParams(
      dataSourceParams = new PDataSource4.Params(id = 0, en = en, qn = qn),
      preparatorParams = PPreparator1.Params(1),
      algorithmParamsList = Seq(("", PAlgo2.Params(2))),
      servingParams = LServing1.Params(3))

    val ep0 = baseEngineParams
    val ep1 = baseEngineParams.copy(
      algorithmParamsList = Seq(("", PAlgo2.Params(3))))
    // ep2.dataSource is different from ep0.
    val ep2 = baseEngineParams.copy(
      dataSourceParams = ("", new PDataSource4.Params(id = 0, en = en, qn = qn)),
      algorithmParamsList = Seq(("", PAlgo2.Params(3))))

    val engineEvalDataSet = engine.batchEval(
      sc,
      Seq(ep0, ep1, ep2),
      WorkflowParams())

    val evalDataSet0 = engineEvalDataSet(0)._2
    val evalDataSet1 = engineEvalDataSet(1)._2
    val evalDataSet2 = engineEvalDataSet(2)._2

    evalDataSet0 should not be evalDataSet1
    evalDataSet0 should not be evalDataSet2
    evalDataSet1 should not be evalDataSet2

    // Set0 should have same EI as Set1, since their dsp are the same instance.
    evalDataSet0.zip(evalDataSet1).foreach { case (e0, e1) => {
      e0._1 should be theSameInstanceAs (e1._1)
    }}

    // Set1 should have different EI as Set2, since Set2's dsp is another
    // instance
    evalDataSet1.zip(evalDataSet2).foreach { case (e1, e2) => {
      e1._1 should not be theSameInstanceAs (e2._1)
    }}
  }
}


text:
//imports
var http = require('http');
var url = require('url');
var crypto = require('crypto');
var uuid = require('node-uuid');
var querystring = require('querystring');
var mongoose = require('mongoose');
var bunyan = require('bunyan');
var fs = require('fs');

//variables
var port =  1337;
var root = '';
var path = '';
var base = '/';
var contentType = '';
var responseCj = {};
var responseBody = '';
var responseHeaders = null;
var responseStatus = null;
var queryData = null;
var requestBody = null;
var log = bunyan.createLogger({name: "api"});

/**
 * Setup DB Connection
 */

// Connect to mongodb
var connect = function () {
    var options = { server: { socketOptions: { keepAlive: 1 } } };
    mongoose.connect('mongodb://localhost/api', options);
};
connect();

// Error handler
mongoose.connection.on('error', function (err) {
    log.info(err);
});

// Reconnect when closed
mongoose.connection.on('disconnected', function () {
    connect();
});

// On Connection
mongoose.connection.once('open', function callback() {
    log.info('mongodb connected successfully');
});

// load mongoose models
fs.readdirSync('../models').forEach(function (file) {
    if (~file.indexOf('.js')) {
        require('../models/' + file);
    }
});

/**
 * Route Patterns
 */
var reAPIBillboard = new RegExp('^\/api\/$', 'i');
var reAPIListMovies = new RegExp('^\/api\/movies$', 'i');
var reAPIListMoviesParams = new RegExp('^\/api\/movies\\?.*', 'i');
var reAPIItemMovies = new RegExp('^\/api\/movies\/.*', 'i');

/**
 * Handle incoming requests
 */
var handler = function (req, res) {
    var segments, i, x, parts, flg;

    //some simple content negotiation
    if (req.headers.accept && req.headers.accept.indexOf('application/vnd.collection+json') != -1) {
        contentType = 'application/vnd.collection+json';
    } else {
        contentType = 'application/json';
    }

    // parse incoming request URL
    parts = [];
    segments = req.url.split('/');
    for (i = 0, x = segments.length; i < x; i++) {
        if (segments[i] !== '') {
            parts.push(segments[i]);
        }
    }

    flg = false;
//    root = 'http://' + req.headers.host + ':' + port;
    root = 'http://' + req.headers.host;
    console.log('root: ' + root);
    base = root + '/api/';
    path = url.parse(req.url).pathname;
    queryData = url.parse(req.url, true).query;

    //billboard route - RegExp('^\/api\/$','i')
    if (reAPIBillboard.test(req.url)) {
        flg = true;
        log.info('request handler route => ' + req.method + ':reAPIBillboard');

        switch (req.method) {
            case 'GET':
                sendBillboardResponse(req, res);
                break;
            default:
                sendErrorResponse(req, res, 'Method Not Allowed', 405);
                break;
        }
    }

    //movies collection route - RegExp('^\/api\/movies$','i')
    if (flg === false && reAPIListMovies.test(req.url)) {
        flg = true;
        log.info('request handler route => ' + req.method + ':reAPIListMovies');

        switch (req.method) {
            case 'GET':
                sendListResponseMovies(req, res);
                break;
            case 'POST':
                sendAddMovieResponse(req, res);
                break;
            default:
                sendErrorResponse(req, res, 'Method Not Allowed', 405);
                break;
        }
    }

    //movies collection route - RegExp('^\/api\/movies?.*','i')
    if (flg === false && reAPIListMoviesParams.test(req.url)) {
        flg = true;
        log.info('request handler route => ' + req.method + ':reAPIListMoviesParams');

        switch (req.method) {
            case 'GET':
                sendListResponseMovies(req, res);
                break;
            default:
                sendErrorResponse(req, res, 'Method Not Allowed', 405);
                break;
        }
    }

    //movie item route - RegExp('^\/api\/movies\/.*','i')
    if (flg === false && reAPIItemMovies.test(req.url)) {
        flg = true;
        log.info('request handler route => ' + req.method + ':reAPIItemMovies');

        switch (req.method) {
            case 'GET':
                sendItemResponseMovies(req, res, parts[2]);
                break;
            case 'PUT':
                sendItemUpdateResponseMovies(req, res, parts[2]);
                break;
            case 'DELETE':
                sendDeleteResponse(req, res, parts[2]);
                break;
            default:
                sendErrorResponse(req, res, 'Method Not Allowed', 405);
                break;
        }
    }

    //not found
    if (flg === false) {
        log.info('request handler route not found. URL: ' + req.url);
        sendErrorResponse(req, res, 'Resource Not Found', 404);
    }
};

/**
 * Send Billboard Response - API Starting Point
 */
var sendBillboardResponse = function (req, res) {
    try {
        responseCj = {};
        renderBillboardCollection();
        responseBody = JSON.stringify(responseCj);
        responseHeaders = {
            'Content-Type': contentType,
            'Content-Length': Buffer.byteLength(responseBody)
        };
        responseStatus = 200;

        sendResponse(req, res, responseStatus, responseHeaders, responseBody);
    } catch (ex) {
        sendErrorResponseHelper(req, res, 'Server Error', 500);
    }
};

/**
 *  Create a new Movie Resource
 */
var sendAddMovieResponse = function (req, res) {
    requestBody = '';
    req.on('data', function (chunk) {
        requestBody += chunk;
    });

    req.on('end', function () {
        try {
            var requestMsg = JSON.parse(requestBody);
            var movie = {};

            for (var i = 0; i < requestMsg.template.data.length; i++) {
                movie[requestMsg.template.data[i].name] = requestMsg.template.data[i].value;
            }

            //add default attributes
            if (movie) {
                movie.sysid = genId();
                movie.created_on = new Date();
                movie.updated_on = new Date();
            }

            var movieInstance = new mongoose.models.Movie(movie);

            movieInstance.save(function (err, movieInstance) {
                if (err) {
                    log.error(err);
                    sendErrorResponseHelper(req, res, 'Server Error', 500);
                }
                responseBody = '';
                responseStatus = 201;
                responseHeaders = { 'Location': base + 'movies/' + movie.sysid };
                sendResponse(req, res, responseStatus, responseHeaders, responseBody);
            });

        } catch (ex) {
            sendErrorResponseHelper(req, res, 'Server Error', 500);
        }
    });
};

/**
 * DELETE an existing movie resource
 * @param movieId
 */
var sendDeleteResponse = function (req, res, movieId) {
    try {
        mongoose.models.Movie.findOneAndRemove({sysid: movieId}, function (err, movie) {
            if (err) {
                log.error(err);
                sendErrorResponseHelper(req, res, 'Server Error', 500);
            }
            log.info('movie ' + movieId + ' - ' + movie.name + ' deleted from db');
        });

        responseBody = '';
        responseHeaders = {};
        responseStatus = 204;
        sendResponse(req, res, responseStatus, responseHeaders, responseBody);
    } catch (ex) {
        sendErrorResponseHelper(req, res, 'Server Error', 500);
    }
};

/**
 * GET collection movie resources
 */
var sendListResponseMovies = function (req, res) {
    var movies = null;
    var offset = null;
    var limit = null;
    var pagestart = null;
    var pageend = null;
    responseCj = {}; //default template

    try {

        limit = 5; // default limit
        if (queryData.limit) {
            limit = parseInt(queryData.limit);
        }

        offset = 0; // default offset
        if (queryData.offset) {
            offset = parseInt(queryData.offset);
        }

        pagestart = offset;
        pageend = offset + limit;

        //define query
        if (queryData.name) {
            log.info('queryData.name: ' + queryData.name);
            movies = mongoose.models.Movie.find({name: new RegExp(queryData.name, 'i')}).sort('-created_on');
        } else {
            movies = mongoose.models.Movie.find().sort('-created_on');
        }

        createResponseCjTemplate();
        renderMovieCollectionLinks();
        renderMovieCollectionQueries();
        renderMovieCollectionTemplate();

        //execute query and handle response
        movies.exec(function (err, movies) {
            if (err) {
                log.error(err);
                sendErrorResponseHelper(req, res, 'Server Error', 500);
            }

            log.info(movies.length + ' records found matching query passed to mongoDB');

            if (movies && movies.length > 0) {
                log.info('pagestart: ' + pagestart + ' pageend: ' + pageend);
                renderMovieCollectionItems(movies.slice(pagestart, pageend));
            } else {
                responseCj.collection.items = [];
            }

            if (queryData.name) {

                //href
                responseCj.collection.href = base + 'movies?name=' + queryData.name + '&offset=' + offset.toString() +
                    '&limit=' + limit.toString();

                // first page of movies
                var link = {};
                link.href = base + 'movies?name=' + queryData.name;
                link.rel = 'first';
                link.prompt = 'first page of results';
                responseCj.collection.links.push(link);

                // next page of movies
                if(pageend < movies.length) {
                    link = {};
                    link.href = base + 'movies?name=' + queryData.name + '&offset=' + (offset + limit).toString() +
                        '&limit=' + limit.toString();
                    link.rel = 'next';
                    link.prompt = 'immediate next page results';
                    responseCj.collection.links.push(link);
                }

                // prev page of movies
                    link = {};
                if (offset < limit) {
                    link.href = base + 'movies?name=' + queryData.name;
                } else {
                    link.href = base + 'movies?name=' + queryData.name + '&offset=' + (offset - limit).toString() +
                        '&limit=' + limit.toString();
                }

                link.rel = 'previous';
                link.prompt = 'immediate previous page results';
                responseCj.collection.links.push(link);

                //last
                link = {};
                link.href = base + 'movies?name=' + queryData.name + '&offset=' + (movies.length - limit).toString() +
                    '&limit=' + limit.toString();
                link.rel = 'last';
                link.prompt = 'last page of results';
                responseCj.collection.links.push(link);

            } else {

                //href
                responseCj.collection.href = base + 'movies?offset=' + offset.toString() +
                    '&limit=' + limit.toString();

                // first page of movies
                var link = {};
                link.href = base + 'movies';
                link.rel = 'first';
                link.prompt = 'first page of results';
                responseCj.collection.links.push(link);

                // next page of movies
                if(pageend < movies.length) {
                    link = {};
                    link.href = base + 'movies?offset=' + (offset + limit).toString() +
                        '&limit=' + limit.toString();
                    link.rel = 'next';
                    link.prompt = 'immediate next page results';
                    responseCj.collection.links.push(link);
                }

                // prev page of movies
                link = {};
                if (offset < limit) {
                    link.href = base + 'movies';
                } else {
                    link.href = base + 'movies?offset=' + (offset - limit).toString() +
                        '&limit=' + limit.toString();
                }
                link.rel = 'previous';
                link.prompt = 'immediate previous page results';
                responseCj.collection.links.push(link);

                //last
                link = {};
                link.href = base + 'movies?offset=' + (movies.length - limit).toString() +
                    '&limit=' + limit.toString();
                link.rel = 'last';
                link.prompt = 'last page of results';
                responseCj.collection.links.push(link);
            }

            responseBody = JSON.stringify(responseCj);
            responseHeaders = {
                'Content-Type': contentType,
                'Content-Length': Buffer.byteLength(responseBody)
            };
            responseStatus = 200;
            sendResponse(req, res, responseStatus, responseHeaders, responseBody);
        });
    } catch (ex) {
        sendErrorResponseHelper(req, res, 'Server Error', 500);
    }
};

/**
 * PUT (update) existing movie
 */
var sendItemUpdateResponseMovies = function (req, res, movieId) {
    requestBody = '';
    req.on('data', function (chunk) {
        requestBody += chunk;
    });

    req.on('end', function () {
        try {
            var requestMsg = JSON.parse(requestBody);
            log.info({requestMsg: requestMsg}, "log incoming movie put");

            var movie = {};
            for (var i = 0; i < requestMsg.template.data.length; i++) {
                movie[requestMsg.template.data[i].name] = requestMsg.template.data[i].value;
            }

            var movieInstance = new mongoose.models.Movie(movie);
            movieInstance.validate(function (err) {
                if (err) {
                    log.error(err);
                    sendErrorResponseHelper(req, res, 'missing required parameter', 500);
                }

                log.info('validated successfully');
                mongoose.models.Movie.findOne({'sysid': movieId}, function (err, existingMovie) {
                    if (err) {
                        log.error(err);
                        sendErrorResponseHelper(req, res, 'Movie not found for updating, check ID', 500);
                    }

                    existingMovie.name = movie.name;
                    existingMovie.description = movie.description;
                    existingMovie.datePublished = movie.datePublished;
                    existingMovie.about = movie.about;
                    existingMovie.genre = movie.genre;
                    existingMovie.version = movie.version;
                    existingMovie.timeRequired = movie.timeRequired;
                    existingMovie.contentRating = movie.contentRating;
                    existingMovie.updated_on = new Date();

                    log.info({existingMovie: existingMovie});
                    existingMovie.save(function (err) {
                        if (err) {
                            sendErrorResponseHelper(req, res, 'Failed updating movie', 500);
                        }
                        sendItemResponseMovies(req, res, movieId);
                    });
                });
            });
        } catch (ex) {
            sendErrorResponseHelper(req, res, 'Server Error', 500);
        }
    });
};

/**
 *  GET movie individual movie resource
 */
var sendItemResponseMovies = function (req, res, movieId) {
    try {
        responseCj = {};
        mongoose.models.Movie.findOne({'sysid': movieId}, function (err, movie) {
            if (err) {
                log.error(err);
                sendErrorResponseHelper(req, res, 'Error, Invalid ID', 204);
            }

            if (movie) {
                createResponseCjTemplate();
                renderMovieCollectionLinks();
                renderMovieCollectionItems([movie]);
                renderMovieCollectionQueries();
                renderMovieCollectionTemplate();

                responseBody = JSON.stringify(responseCj);
                responseHeaders = {
                    'Content-Type': contentType,
                    'Content-Length': Buffer.byteLength(responseBody)
                };
                responseStatus = 200;
                sendResponse(req, res, responseStatus, responseHeaders, responseBody);
            } else {
                responseBody = null;
                responseHeaders = {
                    'Content-Type': contentType
                };
                responseStatus = 404;
                sendResponse(req, res, responseStatus, responseHeaders, responseBody);
            }
        });
    } catch (ex) {
        sendErrorResponseHelper(req, res, 'Server Error', 500);
    }
};

var sendErrorResponse = function (req, res, title, code) {
    req.on('end', function () {
        sendErrorResponseHelper(req, res, title, code);
    });
};

var sendErrorResponseHelper = function (req, res, title, code) {
    responseCj = {};
    responseCj.collection = {};
    responseCj.collection.version = "1.0";
    responseCj.collection.href = base;
    responseCj.error = {
        title: title,
        code: code
    };

    responseBody = JSON.stringify(responseCj);
    responseHeaders = {
        'Content-Type': contentType,
        'Content-Length': Buffer.byteLength(responseBody)
    };
    responseStatus = code;

    sendResponse(req, res, responseStatus, responseHeaders, responseBody);
};

/**
 * send the http response to client
 */
var sendResponse = function (req, res, responseStatus, responseHeaders, responseBody) {
    var now = new Date();

    responseHeaders["Cache-Control"] = "no-cache, no-store, must-revalidate";
    responseHeaders["Connection"] = "Close";
    responseHeaders["Date"] = now.toISOString();
    res.writeHead(responseStatus, responseHeaders);
    res.end(responseBody);
};

/**
 * Render Movie Write Template (POST, PUT)
 */
var renderMovieCollectionTemplate = function () {
    var template = {};
    var item = {};

    template.data = [];

    item = {};
    item.name = 'name';
    item.value = '';
    item.prompt = 'title of movie';
    item.required = 'true';
    template.data.push(item);

    item = {};
    item.name = 'description';
    item.value = '';
    item.prompt = 'description of movie';
    item.required = 'true';
    template.data.push(item);

    item = {};
    item.name = 'datePublished';
    item.value = '';
    item.prompt = 'date movie was published';
    item.required = 'true';
    template.data.push(item);

    item = {};
    item.name = 'about';
    item.value = '';
    item.prompt = 'short description of film';
    item.required = 'true';
    template.data.push(item);

    item = {};
    item.name = 'genre';
    item.value = '';
    item.prompt = 'movie genre';
    item.required = 'true';
    template.data.push(item);

    item = {};
    item.name = 'version';
    item.value = '';
    item.prompt = 'version of this release';
    item.required = 'true';
    template.data.push(item);

    item = {};
    item.name = 'timeRequired';
    item.value = '';
    item.prompt = 'time required to view this movie aka duration';
    item.required = 'true';
    template.data.push(item);

    item = {};
    item.name = 'contentRating';
    item.value = '';
    item.prompt = 'movie content rating';
    item.required = 'true';
    template.data.push(item);

    responseCj.collection.template = template;
};

/**
 * Render movie collection queries
 */
var renderMovieCollectionQueries = function () {
    var query = {};
    query.href = base + 'movies';
    query.rel = 'search';
    query.rt = 'movie';
    query.prompt = 'Movie-Search By Name';
    query.name = 'movie-search';
    query.data = {'name': 'name', 'value': '', 'prompt': 'Name'};
    responseCj.collection.queries.push(query);
};

/**
 * Render movie collection items
 */
var renderMovieCollectionItems = function (coll) {

    log.info('coll.length: ' + coll.length);
    var item, dataItem, linkItem;
    responseCj.collection.items = [];

    //iterate coll
    if (coll && coll.length > 0) {
        for (var i = 0; i < coll.length; i++) {

            //item
            item = {};
            item.href = base + 'movies/' + coll[i].sysid;
            item.rel = 'item';
            item.rt = 'movie';
            item.data = [];
            item.links = [];

            //conditional linkItem
            if (coll[i].director) {
                linkItem = {};
                linkItem.name = coll[i].director;
                linkItem.rel = 'director';
                linkItem.prompt = 'director of the movie';
                linkItem.href = base + 'persons/1234';
                linkItem.render = 'link';
                item.links.push(linkItem);
            }

            linkItem = {};
            linkItem.rel = 'type';
            linkItem.href = 'https://rawgithub.com/bryanbarnard/ISWQ2014/master/docs/movies.xml#movie';
            item.links.push(linkItem);

            //data
            dataItem = {};
            dataItem.name = 'name';
            dataItem.value = coll[i].name;
            dataItem.prompt = 'title of the movie';
            item.data.push(dataItem);

            dataItem = {};
            dataItem.name = 'description';
            dataItem.value = coll[i].description;
            dataItem.prompt = 'description of movie';
            item.data.push(dataItem);

            dataItem = {};
            dataItem.name = 'datePublished';
            dataItem.value = coll[i].datePublished;
            dataItem.prompt = 'date movie was published';
            item.data.push(dataItem);

            dataItem = {};
            dataItem.name = 'about';
            dataItem.value = coll[i].about;
            dataItem.prompt = 'short description of this item';
            item.data.push(dataItem);

            dataItem = {};
            dataItem.name = 'genre';
            dataItem.value = coll[i].genre;
            dataItem.prompt = 'movie genre';
            item.data.push(dataItem);

            dataItem = {};
            dataItem.name = 'version';
            dataItem.value = coll[i].version;
            dataItem.prompt = 'version of this release';
            item.data.push(dataItem);

            dataItem = {};
            dataItem.name = 'timeRequired';
            dataItem.value = coll[i].timeRequired;
            dataItem.prompt = 'time required to view this movie, aka duration';
            item.data.push(dataItem);

            dataItem = {};
            dataItem.name = 'contentRating';
            dataItem.value = coll[i].contentRating;
            dataItem.prompt = 'rating of the movie';
            item.data.push(dataItem);

            dataItem = {};
            dataItem.name = 'created';
            dataItem.value = coll[i].created_on.toISOString();
            dataItem.prompt = 'record created';
            item.data.push(dataItem);

            dataItem = {};
            dataItem.name = 'updated';
            dataItem.value = coll[i].updated_on.toISOString();
            dataItem.prompt = 'record last updated';
            item.data.push(dataItem);

            responseCj.collection.items.push(item);
        }
    }
};

/**
 * Build and render Default MovieCollection Links
 */
var renderMovieCollectionLinks = function () {
    var link = {};

    link = {};
    link.href = 'https://rawgithub.com/bryanbarnard/ISWQ2014/master/docs/movies.xml';
    link.rel = 'profile';
    responseCj.collection.links.push(link);

    link = {};
    link.href = 'https://rawgithub.com/bryanbarnard/ISWQ2014/master/docs/movies.xml#movie';
    link.rel = 'type';
    responseCj.collection.links.push(link);
};

/**
 *  Render Billboard Response
 */
var renderBillboardCollection = function () {
    var links, linkItem;
    links = [];

    responseCj = {};
    responseCj.collection = {};
    responseCj.collection.version = "1.0";
    responseCj.collection.href = base;

    linkItem = {};
    linkItem.href = 'https://rawgithub.com/bryanbarnard/ISWQ2014/master/docs/movies.xml';
    linkItem.prompt = "profile";
    linkItem.rel = "profile";
    links.push(linkItem);

    linkItem = {};
    linkItem.href = base + "movies";
    linkItem.prompt = "Movies Collection";
    linkItem.rel = "movies";
    links.push(linkItem);

    linkItem = {};
    linkItem.href = "http://bryanbarnard.github.io/ISWQ2014/";
    linkItem.prompt = "API Documentation";
    linkItem.rel = "help";
    links.push(linkItem);

    responseCj.collection.links = links;
};

/**
 * Gen ID Helper Method
 */
var genId = function () {
    var id = uuid();
    id = id.replace(/-/g, '');
    return id;
};

/**
 * Create Collection JSON Response Template
 */
var createResponseCjTemplate = function () {
    responseCj.collection = {};
    responseCj.collection.version = "1.0";
    responseCj.collection.href = base;
    responseCj.collection.links = [];
    responseCj.collection.items = [];
    responseCj.collection.queries = [];
    responseCj.collection.template = {};
};

//main
http.createServer(handler).listen(port);
log.info('http server listening http://localhost:' + port + '/api/');

/**
 * Sample CURL Requests
 */
//curl -X POST -v -H "Content-Type: application/vnd.collection+json" -H "Connection: close" -H "Cache-Control: no-cache" -d '{"template":{"data":[{"name":"text","value":"testing"},{"name":"junk","value":""}]}}' http://localhost:8080/api/


text:
/*********************************************/
/*            COMMON ELFINDER STUFFS         */
/*********************************************/

/* common container */
.elfinder { padding:0; position:relative; display:block; }

/* right to left enviroment */
.elfinder-rtl { text-align:right; direction:rtl; }

/* nav and cwd container */
.elfinder-workzone {
	padding: 0;
	position:relative;
	overflow:hidden;
}

/* dir/file permissions and symlink markers */
.elfinder-perms,
.elfinder-symlink {
	position:absolute;
	width:16px;
	height:16px;
	background-image:url(../img/toolbar.png);
	background-repeat:no-repeat;
	background-position:0 -528px;
}

.elfinder-symlink { }

/* noaccess */
.elfinder-na .elfinder-perms { background-position:0 -96px; }

/* read only */
.elfinder-ro .elfinder-perms { background-position:0 -64px;}

/* write only */
.elfinder-wo .elfinder-perms { background-position:0 -80px;}

/* drag helper */
.elfinder-drag-helper {
	width:60px;
	height:50px;
	padding:0 0 0 25px;
	z-index:100000;
}

/* drag helper "plus" icon */
.elfinder-drag-helper-icon-plus {
	position:absolute;
	width:16px;
	height:16px;
	left:43px;
	top:55px;
	background:url('../img/toolbar.png') 0 -544px no-repeat;
	display:none;
}

/* show "plus" icon when ctrl/shift pressed */
.elfinder-drag-helper-plus .elfinder-drag-helper-icon-plus { display:block; }

/* files num in drag helper */
.elfinder-drag-num {
	position:absolute;
	top:0;
	left:0;
	width:16px;
	height:14px;
	text-align:center;
	padding-top:2px;
	font-size:12px;
	font-weight:bold;
	color:#fff;
	background-color:red;
	-moz-border-radius: 8px;
	-webkit-border-radius: 8px;
	border-radius: 8px;
}

/* icon in drag helper */
.elfinder-drag-helper .elfinder-cwd-icon { margin:0 0 0 -24px; float:left; }

/* transparent overlay >_< */
.elfinder-overlay { opacity: 0; filter:Alpha(Opacity=0); }

/* panels under/below cwd (for search field etc) */
.elfinder .elfinder-panel {
	position:relative;
	background-image:none;
	padding:7px 12px;
}