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

goog.module('goog.ui.SubMenuTest');
goog.setTestOnly();

const Component = goog.require('goog.ui.Component');
const GoogEvent = goog.require('goog.events.Event');
const KeyCodes = goog.require('goog.events.KeyCodes');
const KeyHandler = goog.require('goog.events.KeyHandler');
const Menu = goog.require('goog.ui.Menu');
const MenuItem = goog.require('goog.ui.MenuItem');
const MockClock = goog.require('goog.testing.MockClock');
const Overflow = goog.require('goog.positioning.Overflow');
const State = goog.require('goog.a11y.aria.State');
const SubMenu = goog.require('goog.ui.SubMenu');
const SubMenuRenderer = goog.require('goog.ui.SubMenuRenderer');
const aria = goog.require('goog.a11y.aria');
const classlist = goog.require('goog.dom.classlist');
const dom = goog.require('goog.dom');
const events = goog.require('goog.events');
const functions = goog.require('goog.functions');
const positioning = goog.require('goog.positioning');
const style = goog.require('goog.style');
const testSuite = goog.require('goog.testing.testSuite');
const testingEvents = goog.require('goog.testing.events');

let menu;
let clonedMenuDom;

let mockClock;

// mock out goog.positioning.positionAtCoordinate so that
// the menu always fits. (we don't care about testing the
// dynamic menu positioning if the menu doesn't fit in the window.)
const oldPositionFn = positioning.positionAtCoordinate;
positioning.positionAtCoordinate =
    (absolutePos, movableElement, movableElementCorner, margin = undefined,
     overflow = undefined) =>
        oldPositionFn.call(
            null, absolutePos, movableElement, movableElementCorner, margin,
            Overflow.IGNORE);

function assertKeyHandlingIsCorrect(keyToOpenSubMenu, keyToCloseSubMenu) {
  menu.setFocusable(true);
  menu.decorate(dom.getElement('demoMenu'));

  const plainItem = menu.getChildAt(0);
  plainItem.setMnemonic(KeyCodes.F);

  const subMenuItem1 = menu.getChildAt(1);
  subMenuItem1.setMnemonic(KeyCodes.S);
  const subMenuItem1Menu = subMenuItem1.getMenu();
  menu.setHighlighted(plainItem);

  const fireKeySequence = testingEvents.fireKeySequence;

  const keySequenceReturn =
      fireKeySequence(plainItem.getElement(), keyToOpenSubMenu);

  // Expect keyToOpenSubMenu to only be handled when ENTER because menuItem
  // handles ENTER, while subMenu handles LEFT, RIGHT and ENTER.
  if (keyToOpenSubMenu == KeyCodes.ENTER) {
    assertFalse(
        'Expected OpenSubMenu key to be handled when KeyCode is ENTER',
        keySequenceReturn);
  } else {
    assertTrue('Expected OpenSubMenu key to not be handled', keySequenceReturn);
  }
  assertFalse(subMenuItem1Menu.isVisible());

  // Expect ENTER to be handled when subMenu is visible.
  subMenuItem1Menu.setVisible(true);
  assertFalse(fireKeySequence(subMenuItem1.getElement(), KeyCodes.ENTER));

  assertFalse(
      'Expected F key to be handled',
      fireKeySequence(plainItem.getElement(), KeyCodes.F));

  assertFalse(
      'Expected DOWN key to be handled',
      fireKeySequence(plainItem.getElement(), KeyCodes.DOWN));
  assertEquals(subMenuItem1, menu.getChildAt(1));

  // Expect keyToOpenSubMenu to be handled when subMenu is not visible.
  subMenuItem1Menu.setVisible(false);
  assertFalse(
      'Expected OpenSubMenu key to be handled',
      fireKeySequence(subMenuItem1.getElement(), keyToOpenSubMenu));
  assertTrue(subMenuItem1Menu.isVisible());

  assertFalse(
      'Expected CloseSubMenu key to be handled',
      fireKeySequence(subMenuItem1.getElement(), keyToCloseSubMenu));
  assertFalse(subMenuItem1Menu.isVisible());

  assertFalse(
      'Expected UP key to be handled',
      fireKeySequence(subMenuItem1.getElement(), KeyCodes.UP));

  assertFalse(
      'Expected S key to be handled',
      fireKeySequence(plainItem.getElement(), KeyCodes.S));
  assertTrue(subMenuItem1Menu.isVisible());
}

/**
 * Asserts that this sub menu renders in the right direction relative to
 * the parent menu.
 * @param {SubMenu} subMenu The sub menu.
 * @param {boolean} left True for left-pointing, false for right-pointing.
 */
function assertRenderDirection(subMenu, left) {
  subMenu.getParent().setHighlighted(subMenu);
  subMenu.showSubMenu();
  const menuItemPosition = style.getPageOffset(subMenu.getElement());
  const menuPosition = style.getPageOffset(subMenu.getMenu().getElement());
  assert(Math.abs(menuItemPosition.y - menuPosition.y) < 5);
  assertEquals(
      'Menu at: ' + menuPosition.x + ', submenu item at: ' + menuItemPosition.x,
      left, menuPosition.x < menuItemPosition.x);
}

/**
 * Asserts that this sub menu has a properly-oriented arrow.
 * @param {SubMenu} subMenu The sub menu.
 * @param {boolean} left True for left-pointing, false for right-pointing.
 */
function assertArrowDirection(subMenu, left) {
  assertEquals(
      left ? SubMenuRenderer.LEFT_ARROW_ : SubMenuRenderer.RIGHT_ARROW_,
      getArrowElement(subMenu).innerHTML);
}

/**
 * Asserts that the arrow position is correct.
 * @param {SubMenu} subMenu The sub menu.
 * @param {boolean} leftAlign True for left-aligned, false for right-aligned.
 */
function assertArrowPosition(subMenu, left) {
  const arrow = getArrowElement(subMenu);
  const expectedLeft =
      left ? 0 : arrow.offsetParent.offsetWidth - arrow.offsetWidth;
  const actualLeft = arrow.offsetLeft;
  assertTrue(
      `Expected left offset: ${expectedLeft}
` +
          'Actual left offset: ' + actualLeft + '\n',
      Math.abs(expectedLeft - actualLeft) < 5);
}

/**
 * Gets the arrow element of a sub menu.
 * @param {SubMenu} subMenu The sub menu.
 * @return {Element} The arrow.
 */
function getArrowElement(subMenu) {
  return subMenu.getContentElement().lastChild;
}
testSuite({
  setUp() {
    clonedMenuDom = dom.getElement('demoMenu').cloneNode(true);

    menu = new Menu();
  },

  tearDown() {
    document.body.style.direction = 'ltr';
    menu.dispose();

    const element = dom.getElement('demoMenu');
    element.parentNode.replaceChild(clonedMenuDom, element);

    dom.removeChildren(dom.getElement('sandbox'));

    if (mockClock) {
      mockClock.uninstall();
      mockClock = null;
    }
  },

  testEnterOpensSubmenu() {
    assertKeyHandlingIsCorrect(KeyCodes.ENTER, KeyCodes.LEFT);
  },

  testKeyHandling_ltr() {
    assertKeyHandlingIsCorrect(KeyCodes.RIGHT, KeyCodes.LEFT);
  },

  testKeyHandling_rtl() {
    document.body.style.direction = 'rtl';
    assertKeyHandlingIsCorrect(KeyCodes.LEFT, KeyCodes.RIGHT);
  },

  testNormalLtrSubMenu() {
    menu.decorate(dom.getElement('demoMenu'));
    const subMenu = menu.getChildAt(1);
    assertArrowDirection(subMenu, false);
    assertRenderDirection(subMenu, false);
    assertArrowPosition(subMenu, false);
  },

  testNormalRtlSubMenu() {
    document.body.style.direction = 'rtl';
    menu.decorate(dom.getElement('demoMenu'));
    const subMenu = menu.getChildAt(1);
    assertArrowDirection(subMenu, true);
    assertRenderDirection(subMenu, true);
    assertArrowPosition(subMenu, true);
  },

  testLtrSubMenuAlignedToStart() {
    menu.decorate(dom.getElement('demoMenu'));
    const subMenu = menu.getChildAt(1);
    subMenu.setAlignToEnd(false);
    assertArrowDirection(subMenu, true);
    assertRenderDirection(subMenu, true);
    assertArrowPosition(subMenu, false);
  },

  testNullContentElement() {
    const subMenu = new SubMenu();
    subMenu.setContent('demo');
  },

  testRtlSubMenuAlignedToStart() {
    document.body.style.direction = 'rtl';
    menu.decorate(dom.getElement('demoMenu'));
    const subMenu = menu.getChildAt(1);
    subMenu.setAlignToEnd(false);
    assertArrowDirection(subMenu, false);
    assertRenderDirection(subMenu, false);
    assertArrowPosition(subMenu, true);
  },

  testSetContentKeepsArrow_ltr() {
    document.body.style.direction = 'ltr';
    menu.decorate(dom.getElement('demoMenu'));
    const subMenu = menu.getChildAt(1);
    subMenu.setAlignToEnd(false);
    subMenu.setContent('test');
    assertArrowDirection(subMenu, true);
    assertRenderDirection(subMenu, true);
    assertArrowPosition(subMenu, false);
  },

  testSetContentKeepsArrow_rtl() {
    document.body.style.direction = 'rtl';
    menu.decorate(dom.getElement('demoMenu'));
    const subMenu = menu.getChildAt(1);
    subMenu.setAlignToEnd(false);
    subMenu.setContent('test');
    assertArrowDirection(subMenu, false);
    assertRenderDirection(subMenu, false);
    assertArrowPosition(subMenu, true);
  },

  testExitDocument() {
    menu.decorate(dom.getElement('demoMenu'));
    const subMenu = menu.getChildAt(1);
    const innerMenu = subMenu.getMenu();

    assertTrue('Top-level menu was not in document', menu.isInDocument());
    assertTrue('Submenu was not in document', subMenu.isInDocument());
    assertTrue('Inner menu was not in document', innerMenu.isInDocument());

    menu.exitDocument();

    assertFalse('Top-level menu was in document', menu.isInDocument());
    assertFalse('Submenu was in document', subMenu.isInDocument());
    assertFalse('Inner menu was in document', innerMenu.isInDocument());
  },

  testDisposal() {
    menu.decorate(dom.getElement('demoMenu'));
    const subMenu = menu.getChildAt(1);
    const innerMenu = subMenu.getMenu();
    menu.dispose();

    assert('Top-level menu was not disposed', menu.getDisposed());
    assert('Submenu was not disposed', subMenu.getDisposed());
    assert('Inner menu was not disposed', innerMenu.getDisposed());
  },

  testShowAndDismissSubMenu() {
    let openEventDispatched = false;
    let closeEventDispatched = false;

    function handleEvent(e) {
      switch (e.type) {
        case Component.EventType.OPEN:
          openEventDispatched = true;
          break;
        case Component.EventType.CLOSE:
          closeEventDispatched = true;
          break;
        default:
          fail('Invalid event type: ' + e.type);
      }
    }

    menu.decorate(dom.getElement('demoMenu'));
    const subMenu = menu.getChildAt(1);
    subMenu.setHighlighted(true);

    events.listen(
        subMenu, [Component.EventType.OPEN, Component.EventType.CLOSE],
        handleEvent);

    assertFalse(
        'Submenu must not have "-open" CSS class',
        classlist.contains(subMenu.getElement(), 'goog-submenu-open'));
    assertFalse(
        'Popup menu must not be visible', subMenu.getMenu().isVisible());
    assertFalse('No OPEN event must have been dispatched', openEventDispatched);
    assertFalse(
        'No CLOSE event must have been dispatched', closeEventDispatched);

    subMenu.showSubMenu();
    assertTrue(
        'Submenu must have "-open" CSS class',
        classlist.contains(subMenu.getElement(), 'goog-submenu-open'));
    assertTrue('Popup menu must be visible', subMenu.getMenu().isVisible());
    assertTrue('OPEN event must have been dispatched', openEventDispatched);
    assertFalse(
        'No CLOSE event must have been dispatched', closeEventDispatched);

    subMenu.dismissSubMenu();
    assertFalse(
        'Submenu must not have "-open" CSS class',
        classlist.contains(subMenu.getElement(), 'goog-submenu-open'));
    assertFalse(
        'Popup menu must not be visible', subMenu.getMenu().isVisible());
    assertTrue('CLOSE event must have been dispatched', closeEventDispatched);

    events.unlisten(
        subMenu, [Component.EventType.OPEN, Component.EventType.CLOSE],
        handleEvent);
  },

  testDismissWhenSubMenuNotVisible() {
    let openEventDispatched = false;
    let closeEventDispatched = false;

    function handleEvent(e) {
      switch (e.type) {
        case Component.EventType.OPEN:
          openEventDispatched = true;
          break;
        case Component.EventType.CLOSE:
          closeEventDispatched = true;
          break;
        default:
          fail('Invalid event type: ' + e.type);
      }
    }

    menu.decorate(dom.getElement('demoMenu'));
    const subMenu = menu.getChildAt(1);
    subMenu.setHighlighted(true);

    events.listen(
        subMenu, [Component.EventType.OPEN, Component.EventType.CLOSE],
        handleEvent);

    assertFalse(
        'Submenu must not have "-open" CSS class',
        classlist.contains(subMenu.getElement(), 'goog-submenu-open'));
    assertFalse(
        'Popup menu must not be visible', subMenu.getMenu().isVisible());
    assertFalse('No OPEN event must have been dispatched', openEventDispatched);
    assertFalse(
        'No CLOSE event must have been dispatched', closeEventDispatched);

    subMenu.showSubMenu();
    subMenu.getMenu().setVisible(false);

    subMenu.dismissSubMenu();
    assertFalse(
        'Submenu must not have "-open" CSS class',
        classlist.contains(subMenu.getElement(), 'goog-submenu-open'));
    assertFalse(subMenu.menuIsVisible_);
    assertFalse(
        'Popup menu must not be visible', subMenu.getMenu().isVisible());
    assertTrue('CLOSE event must have been dispatched', closeEventDispatched);

    events.unlisten(
        subMenu, [Component.EventType.OPEN, Component.EventType.CLOSE],
        handleEvent);
  },

  testCloseSubMenuBehavior() {
    menu.decorate(dom.getElement('demoMenu'));
    const subMenu = menu.getChildAt(1);
    subMenu.getElement().id = 'subMenu';

    const innerMenu = subMenu.getMenu();
    innerMenu.getChildAt(0).getElement().id = 'child1';

    subMenu.setHighlighted(true);
    subMenu.showSubMenu();

    function MyFakeEvent(keyCode, opt_eventType) {
      this.type = opt_eventType || KeyHandler.EventType.KEY;
      this.keyCode = keyCode;
      this.propagationStopped = false;
      this.preventDefault = goog.nullFunction;
      this.stopPropagation = function() {
        this.propagationStopped = true;
      };
    }

    // Focus on the first item in the submenu and verify the activedescendant is
    // set correctly.
    subMenu.handleKeyEvent(new MyFakeEvent(KeyCodes.DOWN));
    assertEquals(
        'First item in submenu must be the aria-activedescendant', 'child1',
        aria.getState(menu.getElement(), State.ACTIVEDESCENDANT));

    // Dismiss the submenu and verify the activedescendant is updated correctly.
    subMenu.handleKeyEvent(new MyFakeEvent(KeyCodes.LEFT));
    assertEquals(
        'Submenu must be the aria-activedescendant', 'subMenu',
        aria.getState(menu.getElement(), State.ACTIVEDESCENDANT));
  },

  testLazyInstantiateSubMenu() {
    menu.decorate(dom.getElement('demoMenu'));
    const subMenu = menu.getChildAt(1);
    subMenu.setHighlighted(true);

    let lazyMenu;

    const key = events.listen(subMenu, Component.EventType.OPEN, (e) => {
      lazyMenu = new Menu();
      lazyMenu.addItem(new MenuItem('foo'));
      lazyMenu.addItem(new MenuItem('bar'));
      subMenu.setMenu(lazyMenu, /* opt_internal */ false);
    });

    subMenu.showSubMenu();
    assertNotNull('Popup menu must have been created', lazyMenu);
    assertEquals(
        'Popup menu must be a child of the submenu', subMenu,
        lazyMenu.getParent());
    assertTrue('Popup menu must have been rendered', lazyMenu.isInDocument());
    assertTrue('Popup menu must be visible', lazyMenu.isVisible());

    menu.dispose();
    assertTrue('Submenu must have been disposed of', subMenu.isDisposed());
    assertFalse(
        'Popup menu must not have been disposed of', lazyMenu.isDisposed());

    lazyMenu.dispose();

    events.unlistenByKey(key);
  },

  testReusableMenu() {
    const subMenuOne = new SubMenu('SubMenu One');
    const subMenuTwo = new SubMenu('SubMenu Two');
    menu.addItem(subMenuOne);
    menu.addItem(subMenuTwo);
    menu.render(dom.getElement('sandbox'));

    // It is possible for the same popup menu to be shared between different
    // submenus.
    const sharedMenu = new Menu();
    sharedMenu.addItem(new MenuItem('Hello'));
    sharedMenu.addItem(new MenuItem('World'));

    assertNull('Shared menu must not have a parent', sharedMenu.getParent());

    subMenuOne.setMenu(sharedMenu);
    assertEquals(
        'SubMenuOne must point to the shared menu', sharedMenu,
        subMenuOne.getMenu());
    assertEquals(
        'SubMenuOne must be the shared menu\'s parent', subMenuOne,
        sharedMenu.getParent());

    subMenuTwo.setMenu(sharedMenu);
    assertEquals(
        'SubMenuTwo must point to the shared menu', sharedMenu,
        subMenuTwo.getMenu());
    assertEquals(
        'SubMenuTwo must be the shared menu\'s parent', subMenuTwo,
        sharedMenu.getParent());
    assertEquals(
        'SubMenuOne must still point to the shared menu', sharedMenu,
        subMenuOne.getMenu());

    menu.setHighlighted(subMenuOne);
    subMenuOne.showSubMenu();
    assertEquals(
        'SubMenuOne must point to the shared menu', sharedMenu,
        subMenuOne.getMenu());
    assertEquals(
        'SubMenuOne must be the shared menu\'s parent', subMenuOne,
        sharedMenu.getParent());
    assertEquals(
        'SubMenuTwo must still point to the shared menu', sharedMenu,
        subMenuTwo.getMenu());
    assertTrue('Shared menu must be visible', sharedMenu.isVisible());

    menu.setHighlighted(subMenuTwo);
    subMenuTwo.showSubMenu();
    assertEquals(
        'SubMenuTwo must point to the shared menu', sharedMenu,
        subMenuTwo.getMenu());
    assertEquals(
        'SubMenuTwo must be the shared menu\'s parent', subMenuTwo,
        sharedMenu.getParent());
    assertEquals(
        'SubMenuOne must still point to the shared menu', sharedMenu,
        subMenuOne.getMenu());
    assertTrue('Shared menu must be visible', sharedMenu.isVisible());
  },

  /**
   * If you remove a submenu in the interval between when a mouseover event
   * is fired on it, and showSubMenu() is called, showSubMenu causes a null
   * value to be dereferenced. This test validates that the fix for this works.
   * (See bug 1823144).
   */
  testDeleteItemDuringSubmenuDisplayInterval() {
    mockClock = new MockClock(true);

    const submenu = new SubMenu('submenu');
    submenu.addItem(new MenuItem('submenu item 1'));
    menu.addItem(submenu);

    // Trigger mouseover, and remove item before showSubMenu can be called.
    const e = new GoogEvent();
    submenu.handleMouseOver(e);
    menu.removeItem(submenu);
    mockClock.tick(SubMenu.MENU_DELAY_MS);
    // (No JS error should occur.)
  },

  testShowSubMenuAfterRemoval() {
    const submenu = new SubMenu('submenu');
    menu.addItem(submenu);
    menu.removeItem(submenu);
    submenu.showSubMenu();
    // (No JS error should occur.)
  },

  /** Tests that if a sub menu is selectable, then it can handle actions. */
  testSubmenuSelectable() {
    const submenu = new SubMenu('submenu');
    submenu.addItem(new MenuItem('submenu item 1'));
    menu.addItem(submenu);
    submenu.setSelectable(true);

    let numClicks = 0;
    const menuClickedFn = (e) => {
      numClicks++;
    };

    events.listen(submenu, Component.EventType.ACTION, menuClickedFn);
    submenu.performActionInternal(null);
    submenu.performActionInternal(null);

    assertEquals('The submenu should have fired an event', 2, numClicks);

    submenu.setSelectable(false);
    submenu.performActionInternal(null);

    assertEquals(
        'The submenu should not have fired any further events', 2, numClicks);
  },

  /** Tests that if a sub menu is checkable, then it can handle actions. */
  testSubmenuCheckable() {
    const submenu = new SubMenu('submenu');
    submenu.addItem(new MenuItem('submenu item 1'));
    menu.addItem(submenu);
    submenu.setCheckable(true);

    let numClicks = 0;
    const menuClickedFn = (e) => {
      numClicks++;
    };

    events.listen(submenu, Component.EventType.ACTION, menuClickedFn);
    submenu.performActionInternal(null);
    submenu.performActionInternal(null);

    assertEquals('The submenu should have fired an event', 2, numClicks);

    submenu.setCheckable(false);
    submenu.performActionInternal(null);

    assertEquals(
        'The submenu should not have fired any further events', 2, numClicks);
  },

  /**
     Tests that entering a child menu cancels the dismiss timer for the
     submenu.
   */
  testEnteringChildCancelsDismiss() {
    const submenu = new SubMenu('submenu');
    submenu.isInDocument = functions.TRUE;
    submenu.addItem(new MenuItem('submenu item 1'));
    menu.addItem(submenu);

    mockClock = new MockClock(true);
    submenu.getMenu().setVisible(true);

    // This starts the dismiss timer.
    submenu.setHighlighted(false);

    // This should cancel the dismiss timer.
    submenu.getMenu().dispatchEvent(Component.EventType.ENTER);

    // Tick the length of the dismiss timer.
    mockClock.tick(SubMenu.MENU_DELAY_MS);

    // Check that the menu is now highlighted and still visible.
    assertTrue(submenu.getMenu().isVisible());
    assertTrue(submenu.isHighlighted());
  },
});

redpajama_set_name: RedPajamaGithub


text:
module Rails
  module Rack
    class LogTailer
      EnvironmentLog = "#{File.expand_path(Rails.root)}/log/#{Rails.env}.log"

      def initialize(app, log = nil)
        @app = app

        path = Pathname.new(log || EnvironmentLog).cleanpath
        @cursor = ::File.size(path)
        @last_checked = Time.now.to_f

        @file = ::File.open(path, 'r')
      end

      def call(env)
        response = @app.call(env)
        tail_log
        response
      end

      def tail_log
        @file.seek @cursor

        mod = @file.mtime.to_f
        if mod > @last_checked
          contents = @file.read
          @last_checked = mod
          @cursor += contents.size
          $stdout.print contents
        end
      end
    end
  end
end


text:
import sys
import urllib2

from fabric.context_managers import cd
from fabric.decorators import task
from fabric.operations import local
from fabric.operations import put
from fabric.operations import run
from fabric.operations import sudo
from fabric.state import env

env.colorize_errors = True
# the servers where the commands are executed
env.hosts = ['daimaduan.com']
# the user to use for the remote commands
env.user = 'daimaduan'
# application data
APP_NAME = 'daimaduan'
TEST_WEBSITE = {
    'preview': 'https://preview.daimaduan.com',
    'production': 'https://daimaduan.com'
}
NEWRELIC_APPLICATION_ID = {
    'preview': '13327736',
    'production': '13331097'
}

@task
def pack():
    """Create a new source distribution as tarball"""
    local('python setup.py sdist --formats=gztar', capture=False)

@task
def bootstrap(app_env):
    """Create bootstrap environment for daimaduan"""
    if not app_env:
        print "fab pack deploy:<ENV>"
        sys.exit(1)

    app_path = '/var/www/%s/%s' % (APP_NAME, app_env)
    log_path = '/var/log/%s/%s' % (APP_NAME, app_env)
    sudo('mkdir -p %s' % app_path)
    sudo('chown %s:%s %s' % (env.user, env.user, app_path))
    sudo('mkdir -p %s' % log_path)
    sudo('chown %s:%s %s' % (env.user, env.user, log_path))
    with cd(app_path):
        run('virtualenv --distribute venv')

@task
def deploy(app_env):
    """Deploy it to server"""
    if not app_env:
        print "fab pack deploy:<ENV>"
        sys.exit(1)

    with open('.newrelic_key') as f:
        newrelic_key = f.read().strip()
    if not newrelic_key:
        print "cannot find newrelic_key in .newrelic_key file"
        sys.exit(1)

    app_path = '/var/www/%s/%s' % (APP_NAME, app_env)
    out = run('ls -t %s | grep -v current | grep daimaduan.com' % app_path)
    versions = [i.strip() for i in out.split("\n")]
    # figure out the release name and version
    dist = local('python setup.py --fullname', capture=True).strip()
    # upload the source tarball to the temporary folder on the server
    put('dist/%s.tar.gz' % dist, '%s/%s.tar.gz' % (app_path, dist))
    with cd(app_path):
        run('tar xzf %s.tar.gz' % dist)
    with cd('%s/%s' % (app_path, dist)):
        run('%s/venv/bin/python setup.py develop > /dev/null 2>&1' % app_path)
    run('rm -f %s/current' % app_path)
    run('ln -s %s/%s/daimaduan %s/current' % (app_path, dist, app_path))
    run('cp %s/shared/config.cfg %s/current' % (app_path, app_path))
    run('cp %s/shared/deploy.py %s/current' % (app_path, app_path))

    # touching uwsgi ini file will reload this app
    sudo('touch /etc/uwsgi.d/daimaduan_%s.ini' % app_env)

    run('rm -f %s/%s.tar.gz' % (app_path, dist))

    # after deploying, we need to test if deployment succeed
    is_deploy_succeed = True
    try:
        resp = urllib2.urlopen(TEST_WEBSITE[app_env])
    except Exception:
        is_deploy_succeed = False
    else:
        if resp.code != 200:
            is_deploy_succeed = False
            if versions:
                print "Deploy failed, switch back to previous version"
                run('rm -f %s/current' % app_path)
                run('ln -s %s/%s/daimaduan %s/current' % (app_path, versions[0], app_path))
                sudo('touch /etc/uwsgi.d/daimaduan_%s.ini' % app_env)
                sys.exit(1)

    # clean old versions
    if is_deploy_succeed:
        versions.insert(0, dist)
    else:
        versions.append(dist)
    if len(versions) > 4:
        versions = ["%s/%s" % (app_path, i) for i in versions]
        versions_to_delete = " ".join(versions[3:])
        run('rm -rf %s' % versions_to_delete)

    # send deployments notification to newrelic
    version = local('python setup.py --version', capture=True).strip()
    local('curl -H "x-api-key:%s" -d "deployment[application_id]=%s" '
          '-d "deployment[revision]=%s" -d "deployment[user]=David Xie" '
          'https://api.newrelic.com/deployments.xml' % (newrelic_key, NEWRELIC_APPLICATION_ID[app_env], version))


text:
package com.muller.lambo;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;

import timber.log.Timber;

public class MainActivity extends ActionBarActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Timber.plant(new Timber.DebugTree()); //todo: remove Timber throughout

		setContentView(R.layout.activity_main);
		Lambo.get().show(new TestScreen(), null);
		initView();
	}

	@Override
	public void onBackPressed() {
		if (!Lambo.get().back())
			super.onBackPressed();
	}

	private void initView() {

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.menu_main, menu);
		return true;
	}

//	@Override
//	public boolean onOptionsItemSelected(MenuItem item) {
//		// Handle action bar item clicks here. The action bar will
//		// automatically handle clicks on the Home/Up button, so long
//		// as you specify a parent activity in AndroidManifest.xml.
//		int id = item.getItemId();
//
//		//noinspection SimplifiableIfStatement
//		if (id == R.id.action_settings) {
//			if (test)
//				lambo.show(new Test2Screen(), new SlideScreenTransition());
//			else {
//				lambo.show(new Test3Screen(), new ScaleViewTransition());
//				initView();
//			}
//
//			test = !test;
//			return true;
//		}
//
//		return super.onOptionsItemSelected(item);
//	}
}


text:
(function() {
    'use strict';

    angular
        .module('app')
        .controller('HomeController', LocationsController);

        HomeController.$inject = ['$http'];

        function HomeController($http) {
            var vm = this;

        }
}());


text:
{% extends "base.html" %}

{% if section %}
    {% set active_nav = section.slug %}
{% endif %}

{% block page_title %}{% if section %}{{ section.name }}{% else %}Articles{% endif %}{% if tags %} tagged: {% for tag in tags %}{{ tag.name|smartypants }}{% if not loop.last %}, {% endif %}{% endfor %}{% endif %} - {{ super() }}{% endblock %}


text: Netty Cookbook - chapter 1 code


text:
<?php
session_start();
include_once('database-operations.php');

$postdata = file_get_contents("php://input");
$request = json_decode($postdata);

$user = $request->username;
$pass = $request->password;
$email = $request->email;
$requestType = $request->type;

$db = connectToDatabase();

if ($requestType === 'signup') {
    createNewUser($db, $user, $pass, $email);
} else if ($requestType === 'login') {
    authenticateUser($db, $user, $pass);
} else if ($requestType === 'auto-login') {
    authenticateUserFromCookie($db);
} else if ($requestType === 'logout') {
    logoutUser($db, $user);
} else if($requestType === 'checkUsernameAvailability') {
    checkUsernameAvailability($db, $user);
} else if ($requestType === 'checkEmailAvailability') {
    checkEmailAvailability($db, $email);
} else {
    fail('Invalid Request Type');
}
?>


text:
"""
This module contains the classes and utility functions for distance and
cartesian coordinates.
"""

import warnings

import numpy as np

from astropy import units as u
from astropy.utils.exceptions import AstropyWarning

from .angles import Angle

__all__ = ['Distance']

__doctest_requires__ = {'*': ['scipy']}

class Distance(u.SpecificTypeQuantity):
    """
    A one-dimensional distance.

    This can be initialized by providing one of the following:

    * Distance ``value`` (array or float) and a ``unit``
    * |Quantity| object with dimensionality of length
    * Redshift and (optionally) a `~astropy.cosmology.Cosmology`
    * Distance modulus
    * Parallax

    Parameters
    ----------
    value : scalar or `~astropy.units.Quantity` ['length']
        The value of this distance.
    unit : `~astropy.units.UnitBase` ['length']
        The unit for this distance.
    z : float
        A redshift for this distance.  It will be converted to a distance
        by computing the luminosity distance for this redshift given the
        cosmology specified by ``cosmology``. Must be given as a keyword
        argument.
    cosmology : `~astropy.cosmology.Cosmology` or None
        A cosmology that will be used to compute the distance from ``z``.
        If `None`, the current cosmology will be used (see
        `astropy.cosmology` for details).
    distmod : float or `~astropy.units.Quantity`
        The distance modulus for this distance. Note that if ``unit`` is not
        provided, a guess will be made at the unit between AU, pc, kpc, and Mpc.
    parallax : `~astropy.units.Quantity` or `~astropy.coordinates.Angle`
        The parallax in angular units.
    dtype : `~numpy.dtype`, optional
        See `~astropy.units.Quantity`.
    copy : bool, optional
        See `~astropy.units.Quantity`.
    order : {'C', 'F', 'A'}, optional
        See `~astropy.units.Quantity`.
    subok : bool, optional
        See `~astropy.units.Quantity`.
    ndmin : int, optional
        See `~astropy.units.Quantity`.
    allow_negative : bool, optional
        Whether to allow negative distances (which are possible in some
        cosmologies).  Default: `False`.

    Raises
    ------
    `~astropy.units.UnitsError`
        If the ``unit`` is not a length unit.
    ValueError
        If value specified is less than 0 and ``allow_negative=False``.

        If ``cosmology`` is provided when ``z`` is *not* given.

        If either none or more than one of ``value``, ``z``, ``distmod``,
        or ``parallax`` were given.

    Examples
    --------
    >>> from astropy import units as u
    >>> from astropy.cosmology import WMAP5
    >>> Distance(10, u.Mpc)
    <Distance 10. Mpc>
    >>> Distance(40*u.pc, unit=u.kpc)
    <Distance 0.04 kpc>
    >>> Distance(z=0.23)                      # doctest: +FLOAT_CMP
    <Distance 1184.01657566 Mpc>
    >>> Distance(z=0.23, cosmology=WMAP5)     # doctest: +FLOAT_CMP
    <Distance 1147.78831918 Mpc>
    >>> Distance(distmod=24.47*u.mag)         # doctest: +FLOAT_CMP
    <Distance 783.42964277 kpc>
    >>> Distance(parallax=21.34*u.mas)        # doctest: +FLOAT_CMP
    <Distance 46.86035614 pc>
    """

    _equivalent_unit = u.m
    _include_easy_conversion_members = True

    def __new__(cls, value=None, unit=None, z=None, cosmology=None,
                distmod=None, parallax=None, dtype=np.inexact, copy=True,
                order=None, subok=False, ndmin=0, allow_negative=False):

        n_not_none = sum(x is not None for x in [value, z, distmod, parallax])
        if n_not_none == 0:
            raise ValueError('none of `value`, `z`, `distmod`, or `parallax` '
                             'were given to Distance constructor')
        elif n_not_none > 1:
            raise ValueError('more than one of `value`, `z`, `distmod`, or '
                             '`parallax` were given to Distance constructor')

        if value is None:
            # If something else but `value` was provided then a new array will
            # be created anyways and there is no need to copy that.
            copy = False

        if z is not None:
            if cosmology is None:
                from astropy.cosmology import default_cosmology
                cosmology = default_cosmology.get()

            value = cosmology.luminosity_distance(z)

        elif cosmology is not None:
            raise ValueError('a `cosmology` was given but `z` was not '
                             'provided in Distance constructor')

        elif distmod is not None:
            value = cls._distmod_to_pc(distmod)
            if unit is None:
                # if the unit is not specified, guess based on the mean of
                # the log of the distance
                meanlogval = np.log10(value.value).mean()
                if meanlogval > 6:
                    unit = u.Mpc
                elif meanlogval > 3:
                    unit = u.kpc
                elif meanlogval < -3:  # ~200 AU
                    unit = u.AU
                else:
                    unit = u.pc

        elif parallax is not None:
            if unit is None:
                unit = u.pc
            value = parallax.to_value(unit, equivalencies=u.parallax())

            if np.any(parallax < 0):
                if allow_negative:
                    warnings.warn(
                        "negative parallaxes are converted to NaN "
                        "distances even when `allow_negative=True`, "
                        "because negative parallaxes cannot be transformed "
                        "into distances. See the discussion in this paper: "
                        "https://arxiv.org/abs/1507.02105", AstropyWarning)
                else:
                    raise ValueError(
                        "some parallaxes are negative, which are not "
                        "interpretable as distances. See the discussion in "
                        "this paper: https://arxiv.org/abs/1507.02105 . You "
                        "can convert negative parallaxes to NaN distances by "
                        "providing the `allow_negative=True` argument.")

        # now we have arguments like for a Quantity, so let it do the work
        distance = super().__new__(
            cls, value, unit, dtype=dtype, copy=copy, order=order,
            subok=subok, ndmin=ndmin)

        # This invalid catch block can be removed when the minimum numpy
        # version is >= 1.19 (NUMPY_LT_1_19)
        with np.errstate(invalid='ignore'):
            any_negative = np.any(distance.value < 0)

        if not allow_negative and any_negative:
            raise ValueError("distance must be >= 0. Use the argument "
                             "`allow_negative=True` to allow negative values.")

        return distance

    @property
    def z(self):
        """Short for ``self.compute_z()``"""
        return self.compute_z()

    def compute_z(self, cosmology=None, **atzkw):
        """
        The redshift for this distance assuming its physical distance is
        a luminosity distance.

        Parameters
        ----------
        cosmology : `~astropy.cosmology.Cosmology` or None
            The cosmology to assume for this calculation, or `None` to use the
            current cosmology (see `astropy.cosmology` for details).
        **atzkw
            keyword arguments for :func:`~astropy.cosmology.z_at_value`

        Returns
        -------
        z : `~astropy.units.Quantity`
            The redshift of this distance given the provided ``cosmology``.

        Warnings
        --------
        This method can be slow for large arrays.
        The redshift is determined using :func:`astropy.cosmology.z_at_value`,
        which handles vector inputs (e.g. an array of distances) by
        element-wise calling of :func:`scipy.optimize.minimize_scalar`.
        For faster results consider using an interpolation table;
        :func:`astropy.cosmology.z_at_value` provides details.

        See Also
        --------
        :func:`astropy.cosmology.z_at_value` : Find the redshift corresponding to a
            :meth:`astropy.cosmology.FLRW.luminosity_distance`.
        """
        from astropy.cosmology import z_at_value

        if cosmology is None:
            from astropy.cosmology import default_cosmology
            cosmology = default_cosmology.get()

        atzkw.setdefault("ztol", 1.e-10)
        return z_at_value(cosmology.luminosity_distance, self, **atzkw)

    @property
    def distmod(self):
        """The distance modulus as a `~astropy.units.Quantity`"""
        val = 5. * np.log10(self.to_value(u.pc)) - 5.
        return u.Quantity(val, u.mag, copy=False)

    @classmethod
    def _distmod_to_pc(cls, dm):
        dm = u.Quantity(dm, u.mag)
        return cls(10 ** ((dm.value + 5) / 5.), u.pc, copy=False)

    @property
    def parallax(self):
        """The parallax angle as an `~astropy.coordinates.Angle` object"""
        return Angle(self.to(u.milliarcsecond, u.parallax()))


text:
using System.Web.Mvc;

namespace Swagolicious
{
    public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
            base.OnActionExecuting(filterContext);
        }
    }
}


text:
Honeymoon
=========

A tiny web framework written in Swift 2.0, built on top of [GCDWebServer](https://github.com/swisspol/GCDWebServer) and [GRMustache](https://github.com/groue/GRMustache.swift).

## Usage

Honeymoon itself is heavily inspired by [Flask](http://flask.pocoo.org). At this moment, Honeymoon provides these following APIs:

```swift
let app = Honeymoon()
```

### Basic Reponse

```swift
app.get("/") { req in
    return "Honeymoon started."
}
```

###  Paramaters in URL

```swift
app.get("/list/<userId>") { req in
    let userId = req.params!["userId"]!
    return "list\(userId)"
}
```

###  HTML Template

```swift
app.get("/testTemplate") { req in
    return app.renderTemplate("Test", data: ["name": "Chester","value": 10000, "taxed_value": 10000 - (10000 * 0.4), "in_ca": true])
}
```

### Form

```swift
app.post("/post") { req in
    let c = req.form!["content"]!
    return "Content: \(c)"
}
```

### Redirect

```swift
app.get("/testRedirect") { req in
    return app.redirect("/target")
}
```

## Try it out

Currently there's a [bug](https://github.com/Carthage/Carthage/issues/808) in Xcode when trying to use Swift framework in OS X command line application. So the example code is now in the tests.

Clone the project , use `pod install` to install the dependencies. Open the generated `xcworkspace` file and use `Cmd + U` to run the test. Go to `localhost:8000` and that's it.

## License

The MIT License


text:
<?xml version="1.0" encoding="UTF-8"?>
<bathinfos>
<baths>
  <bath>
    <title>Flussbad Au-Höngg</title>
    <temperatureWater>18</temperatureWater>
    <dateModified>Sa, 16.06.2012 14:26</dateModified>
    <openClosedTextPlain><![CDATA[geöffnet]]></openClosedTextPlain>
    <urlPage>http://www.stadt-zuerich.ch/content/ssd/de/index/sport/schwimmen/sommerbaeder/flussbad_au_hoengg.html</urlPage>
    <pathPage>/content/ssd/de/index/sport/schwimmen/sommerbaeder/flussbad_au_hoengg</pathPage>
    <urlAddressAndOpeningHours>http://www.stadt-zuerich.ch/content/ssd/de/index/sport/schwimmen/sommerbaeder/flussbad_au_hoengg/adresse/jcr:content/contenttabparsys/_ffnungszeiten.html</urlAddressAndOpeningHours>
  </bath>
  <bath>
    <title>Flussbad Oberer Letten</title>
    <temperatureWater>10</temperatureWater>
    <dateModified>Mo, 14.05.2012 08:48</dateModified>
    <openClosedTextPlain><![CDATA[Saisonstart 16. Juni 2012]]></openClosedTextPlain>
    <urlPage>http://www.stadt-zuerich.ch/content/ssd/de/index/sport/schwimmen/sommerbaeder/flussbad_oberer_letten.html</urlPage>
    <pathPage>/content/ssd/de/index/sport/schwimmen/sommerbaeder/flussbad_oberer_letten</pathPage>
    <urlAddressAndOpeningHours>http://www.stadt-zuerich.ch/content/ssd/de/index/sport/schwimmen/sommerbaeder/flussbad_oberer_letten/adresse/jcr:content/contenttabparsys/_ffnungszeiten.html</urlAddressAndOpeningHours>
  </bath>
  <bath>
    <title>Flussbad Unterer Letten</title>
    <temperatureWater>21</temperatureWater>
    <dateModified>Sa, 16.06.2012 14:18</dateModified>
    <openClosedTextPlain><![CDATA[geöffnet]]></openClosedTextPlain>
    <urlPage>http://www.stadt-zuerich.ch/content/ssd/de/index/sport/schwimmen/sommerbaeder/flussbad_unterer_letten.html</urlPage>
    <pathPage>/content/ssd/de/index/sport/schwimmen/sommerbaeder/flussbad_unterer_letten</pathPage>
    <urlAddressAndOpeningHours>http://www.stadt-zuerich.ch/content/ssd/de/index/sport/schwimmen/sommerbaeder/flussbad_unterer_letten/adresse/jcr:content/contenttabparsys/_ffnungszeiten.html</urlAddressAndOpeningHours>
  </bath>
  <bath>
    <title>Frauenbad Stadthausquai</title>
    <temperatureWater>17</temperatureWater>
    <dateModified>Sa, 16.06.2012 10:02</dateModified>
    <openClosedTextPlain><![CDATA[geöffnet]]></openClosedTextPlain>
    <urlPage>http://www.stadt-zuerich.ch/content/ssd/de/index/sport/schwimmen/sommerbaeder/frauenbad_stadthausquai.html</urlPage>
    <pathPage>/content/ssd/de/index/sport/schwimmen/sommerbaeder/frauenbad_stadthausquai</pathPage>
    <urlAddressAndOpeningHours>http://www.stadt-zuerich.ch/content/ssd/de/index/sport/schwimmen/sommerbaeder/frauenbad_stadthausquai/adresse/jcr:content/contenttabparsys/_ffnungszeiten.html</urlAddressAndOpeningHours>
  </bath>
  <bath>
    <title>Freibad Allenmoos</title>
    <temperatureWater>20</temperatureWater>
    <dateModified>Sa, 16.06.2012 09:50</dateModified>
    <openClosedTextPlain><![CDATA[geöffnet]]></openClosedTextPlain>
    <urlPage>http://www.stadt-zuerich.ch/content/ssd/de/index/sport/schwimmen/sommerbaeder/freibad_allenmoos.html</urlPage>
    <pathPage>/content/ssd/de/index/sport/schwimmen/sommerbaeder/freibad_allenmoos</pathPage>
    <urlAddressAndOpeningHours>http://www.stadt-zuerich.ch/content/ssd/de/index/sport/schwimmen/sommerbaeder/freibad_allenmoos/adresse/jcr:content/contenttabparsys/_ffnungszeiten.html</urlAddressAndOpeningHours>
  </bath>
  <bath>
    <title>Freibad Auhof</title>
    <temperatureWater>25</temperatureWater>
    <dateModified>Sa, 16.06.2012 08:38</dateModified>
    <openClosedTextPlain><![CDATA[geöffnet]]></openClosedTextPlain>
    <urlPage>http://www.stadt-zuerich.ch/content/ssd/de/index/sport/schwimmen/sommerbaeder/freibad_auhof.html</urlPage>
    <pathPage>/content/ssd/de/index/sport/schwimmen/sommerbaeder/freibad_auhof</pathPage>
    <urlAddressAndOpeningHours>http://www.stadt-zuerich.ch/content/ssd/de/index/sport/schwimmen/sommerbaeder/freibad_auhof/adresse/jcr:content/contenttabparsys/_ffnungszeiten.html</urlAddressAndOpeningHours>
  </bath>
  <bath>
    <title>Freibad Heuried</title>
    <temperatureWater>24</temperatureWater>
    <dateModified>Sa, 16.06.2012 16:14</dateModified>
    <openClosedTextPlain><![CDATA[geöffnet]]></openClosedTextPlain>
    <urlPage>http://www.stadt-zuerich.ch/content/ssd/de/index/sport/schwimmen/sommerbaeder/freibad_heuried.html</urlPage>
    <pathPage>/content/ssd/de/index/sport/schwimmen/sommerbaeder/freibad_heuried</pathPage>
    <urlAddressAndOpeningHours>http://www.stadt-zuerich.ch/content/ssd/de/index/sport/schwimmen/sommerbaeder/freibad_heuried/adresse/jcr:content/contenttabparsys/_ffnungszeiten.html</urlAddressAndOpeningHours>
  </bath>
  <bath>
    <title>Freibad Letzigraben</title>
    <temperatureWater>23</temperatureWater>
    <dateModified>Sa, 16.06.2012 08:25</dateModified>
    <openClosedTextPlain><![CDATA[geöffnet]]></openClosedTextPlain>
    <urlPage>http://www.stadt-zuerich.ch/content/ssd/de/index/sport/schwimmen/sommerbaeder/freibad_letzigraben.html</urlPage>
    <pathPage>/content/ssd/de/index/sport/schwimmen/sommerbaeder/freibad_letzigraben</pathPage>
    <urlAddressAndOpeningHours>http://www.stadt-zuerich.ch/content/ssd/de/index/sport/schwimmen/sommerbaeder/freibad_letzigraben/adresse/jcr:content/contenttabparsys/_ffnungszeiten.html</urlAddressAndOpeningHours>
  </bath>
  <bath>
    <title>Freibad Seebach</title>
    <temperatureWater>26</temperatureWater>
    <dateModified>Sa, 16.06.2012 12:51</dateModified>
    <openClosedTextPlain><![CDATA[geöffnet]]></openClosedTextPlain>
    <urlPage>http://www.stadt-zuerich.ch/content/ssd/de/index/sport/schwimmen/sommerbaeder/freibad_seebach.html</urlPage>
    <pathPage>/content/ssd/de/index/sport/schwimmen/sommerbaeder/freibad_seebach</pathPage>
    <urlAddressAndOpeningHours>http://www.stadt-zuerich.ch/content/ssd/de/index/sport/schwimmen/sommerbaeder/freibad_seebach/adresse/jcr:content/contenttabparsys/_ffnungszeiten.html</urlAddressAndOpeningHours>
  </bath>
  <bath>
    <title>Freibad Zwischen den Hölzern</title>
    <temperatureWater>20</temperatureWater>
    <dateModified>Sa, 16.06.2012 09:12</dateModified>
    <openClosedTextPlain><![CDATA[geöffnetbis20h]]></openClosedTextPlain>
    <urlPage>http://www.stadt-zuerich.ch/content/ssd/de/index/sport/schwimmen/sommerbaeder/freibad_zwischen_den_hoelzern.html</urlPage>
    <pathPage>/content/ssd/de/index/sport/schwimmen/sommerbaeder/freibad_zwischen_den_hoelzern</pathPage>
    <urlAddressAndOpeningHours>http://www.stadt-zuerich.ch/content/ssd/de/index/sport/schwimmen/sommerbaeder/freibad_zwischen_den_hoelzern/adresse/jcr:content/contenttabparsys/_ffnungszeiten.html</urlAddressAndOpeningHours>
  </bath>
  <bath>
    <title>Seebad Katzensee</title>
    <temperatureWater>22</temperatureWater>
    <dateModified>Sa, 16.06.2012 12:23</dateModified>
    <openClosedTextPlain><![CDATA[geöffnet]]></openClosedTextPlain>
    <urlPage>http://www.stadt-zuerich.ch/content/ssd/de/index/sport/schwimmen/sommerbaeder/seebad_katzensee.html</urlPage>
    <pathPage>/content/ssd/de/index/sport/schwimmen/sommerbaeder/seebad_katzensee</pathPage>
    <urlAddressAndOpeningHours>http://www.stadt-zuerich.ch/content/ssd/de/index/sport/schwimmen/sommerbaeder/seebad_katzensee/adresse/jcr:content/contenttabparsys/_ffnungszeiten.html</urlAddressAndOpeningHours>
  </bath>
  <bath>
    <title>Seebad Utoquai</title>
    <temperatureWater>19</temperatureWater>
    <dateModified>Sa, 16.06.2012 06:47</dateModified>
    <openClosedTextPlain><![CDATA[geöffnet]]></openClosedTextPlain>
    <urlPage>http://www.stadt-zuerich.ch/content/ssd/de/index/sport/schwimmen/sommerbaeder/seebad_utoquai.html</urlPage>
    <pathPage>/content/ssd/de/index/sport/schwimmen/sommerbaeder/seebad_utoquai</pathPage>
    <urlAddressAndOpeningHours>http://www.stadt-zuerich.ch/content/ssd/de/index/sport/schwimmen/sommerbaeder/seebad_utoquai/adresse/jcr:content/contenttabparsys/_ffnungszeiten.html</urlAddressAndOpeningHours>
  </bath>
  <bath>
    <title>Strandbad Mythenquai</title>
    <temperatureWater>19</temperatureWater>
    <dateModified>Sa, 16.06.2012 14:10</dateModified>
    <openClosedTextPlain><![CDATA[geöffnet]]></openClosedTextPlain>
    <urlPage>http://www.stadt-zuerich.ch/content/ssd/de/index/sport/schwimmen/sommerbaeder/strandbad_mythenquai.html</urlPage>
    <pathPage>/content/ssd/de/index/sport/schwimmen/sommerbaeder/strandbad_mythenquai</pathPage>
    <urlAddressAndOpeningHours>http://www.stadt-zuerich.ch/content/ssd/de/index/sport/schwimmen/sommerbaeder/strandbad_mythenquai/adresse/jcr:content/contenttabparsys/_ffnungszeiten.html</urlAddressAndOpeningHours>
  </bath>
  <bath>
    <title>Strandbad Tiefenbrunnen</title>
    <temperatureWater>19</temperatureWater>
    <dateModified>Sa, 16.06.2012 15:06</dateModified>
    <openClosedTextPlain><![CDATA[geöffnet]]></openClosedTextPlain>
    <urlPage>http://www.stadt-zuerich.ch/content/ssd/de/index/sport/schwimmen/sommerbaeder/strandbad_tiefenbrunnen.html</urlPage>
    <pathPage>/content/ssd/de/index/sport/schwimmen/sommerbaeder/strandbad_tiefenbrunnen</pathPage>
    <urlAddressAndOpeningHours>http://www.stadt-zuerich.ch/content/ssd/de/index/sport/schwimmen/sommerbaeder/strandbad_tiefenbrunnen/adresse/jcr:content/contenttabparsys/_ffnungszeiten.html</urlAddressAndOpeningHours>
  </bath>
  <bath>
    <title>Strandbad Wollishofen </title>
    <temperatureWater>19</temperatureWater>
    <dateModified>Sa, 16.06.2012 08:40</dateModified>
    <openClosedTextPlain><![CDATA[geöffnet]]></openClosedTextPlain>
    <urlPage>http://www.stadt-zuerich.ch/content/ssd/de/index/sport/schwimmen/sommerbaeder/strandbad_wollishofen.html</urlPage>
    <pathPage>/content/ssd/de/index/sport/schwimmen/sommerbaeder/strandbad_wollishofen</pathPage>
    <urlAddressAndOpeningHours>http://www.stadt-zuerich.ch/content/ssd/de/index/sport/schwimmen/sommerbaeder/strandbad_wollishofen/adresse/jcr:content/contenttabparsys/_ffnungszeiten.html</urlAddressAndOpeningHours>
  </bath>
</baths>
<meta>
  <dateformat>EE, dd.MM.yyyy HH:mm</dateformat>
  <uvindexValue>8</uvindexValue>
  <uvindexImgUrl>http://www.stadt-zuerich.ch/apps/stzh/statics/media/uvindex/uvindex_08.gif</uvindexImgUrl>
  <uvindexImgPath>/apps/stzh/statics/media/uvindex/uvindex_08.gif</uvindexImgPath>
  <uvindexLegalText>Quelle: MeteoSchweiz</uvindexLegalText>
  <uvindexImgLinkPath>/ssd/de/index/sport/schwimmen/uv_schutz.html</uvindexImgLinkPath>
  <urlLegal>http://www.stadt-zuerich.ch/portal/de/index/footer/rechtliche_hinweise.html</urlLegal>
  <dateTimeSent>Sa, 16.06.2012 17:00</dateTimeSent>
  <dateTimeLastModified>Sa, 16.06.2012 16:14</dateTimeLastModified>
  <orderedBy>
    <property>{page}jcr:content/navTitle</property>
    <mode>ascending</mode>
  </orderedBy>
</meta>
</bathinfos>


text:
this.errorAction = function(msg) {
		msg = msg || "";
		var message = msg.message || msg || "Error.";
		bootbox.dialog({
			message: message,
			title: "Error",
			animate: false,
			buttons: {
				success: {
					label: "OK",
					className: "btn-success",
				}
			}
		});
	}


text:
package main

import (
	"flag"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"

	"github.com/vetcher/easystarter/backend/services"
)

const (
	VERSION    = "0.1"
	WelcomeTip = "Easy Starter Server " + VERSION
)

var addr = flag.String("addr", ":8999", "Server's listen port")

func handleSignals() {
	sigChan := make(chan os.Signal)
	signal.Notify(sigChan, syscall.SIGTERM, syscall.SIGINT, syscall.SIGQUIT)
	sig := <-sigChan
	log.Print("Stop all services")
	err := <-services.ServeStopServices(<-services.ServeAllServicesNames()...)
	if err != nil {
		log.Println(err)
	}
	log.Print("Terminate")
	os.Exit(int(sig.(syscall.Signal)))
}

func main() {
	flag.Parse()
	go handleSignals()
	http.HandleFunc("/cfg/loadall", services.NewHTTPWrapper(services.HandleLoadAllServices))
	http.HandleFunc("/cfg/load", services.NewHTTPWrapper(services.HandleLoadServices))
	http.HandleFunc("/env/get", services.NewHTTPWrapper(services.HandleGetEnv))
	http.HandleFunc("/env/reload", services.NewHTTPWrapper(services.HandleReloadEnv))
	http.HandleFunc("/svc/names", services.NewHTTPWrapper(services.HandleAllServicesNames))
	http.HandleFunc("/svc/info", services.NewHTTPWrapper(services.HandleServicesInfo))
	http.HandleFunc("/svc/start", services.NewHTTPWrapper(services.HandleStartServices))
	http.HandleFunc("/svc/stop", services.NewHTTPWrapper(services.HandleStopServices))
	http.HandleFunc("/svc/restart", services.NewHTTPWrapper(services.HandleRestartServices))
	http.HandleFunc("/svc/kill", services.NewHTTPWrapper(services.HandleKillServices))
	http.HandleFunc("/stop", services.StopServer)
	log.Println(WelcomeTip)
	log.Println("Serve on", *addr)
	log.Println(http.ListenAndServe(*addr, nil))
}


text:
'use strict';

const flattenNodes = require('../lib/flatten-nodes');

module.exports = function () {
	return function (stylus) {
		flatten.raw = true;
		stylus.define('flatten', flatten);

		function flatten() {
			let expr = new stylus.nodes.Expression();
			expr.nodes = flattenNodes(Array.from(arguments));
			return expr;
		}
	};
};


text:
package com.hazelcast.client;

import com.hazelcast.AbstractLifecycleServiceNullTest;
import com.hazelcast.client.test.TestHazelcastFactory;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.test.HazelcastParallelClassRunner;
import com.hazelcast.test.annotation.ParallelJVMTest;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.After;
import org.junit.Before;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;

/**
 * Client implementation for basic lifecycle service methods nullability tests
 */
@RunWith(HazelcastParallelClassRunner.class)
@Category({QuickTest.class, ParallelJVMTest.class})
public class ClientLifecycleServiceNullTest extends AbstractLifecycleServiceNullTest {

    private final TestHazelcastFactory hazelcastFactory = new TestHazelcastFactory();
    private HazelcastInstance member;
    private HazelcastInstance client;

    @Before
    public void setup() {
        member = hazelcastFactory.newHazelcastInstance();
        client = hazelcastFactory.newHazelcastClient();
    }

    @After
    public void tearDown() {
        hazelcastFactory.terminateAll();
    }

    @Override
    protected HazelcastInstance getDriver() {
        return client;
    }
}


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

<title>G-Index</title>
<meta name="date" content="2018-12-20">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A B C E F G I M Q S U V

G

getScriptState(String, Object) - Method in interface io.polestar.api.IPolestarAPI

Get the value of a script state variable

getSensorError(String) - Method in interface io.polestar.api.IPolestarAPI

Get the current error of a sensor

getSensorLastModified(String) - Method in interface io.polestar.api.IPolestarAPI

Get the time the sensor was last modified

getSensorLastUpdated(String) - Method in interface io.polestar.api.IPolestarAPI

Get the time the sensor was last updated (even if not modified)

getSensorValue(String) - Method in interface io.polestar.api.IPolestarAPI

Get the current value of a sensor

getTimestamp(int) - Method in interface io.polestar.api.IPolestarQueryResultSet

return timestamp for this index

getValue(int) - Method in interface io.polestar.api.IPolestarQueryResultSet

return value for this index

A B C E F G I M Q S U V

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
<?php
/**
 * @package php_rbac
 * @author  Leigh MacDonald <leigh.macdonald@gmail.com>
 */
namespace RBAC\Manager;

use RBAC\Manager\RoleManager;

class APCRoleManager extends RoleManager
{
    const DEFAULT_TTL = 300;
    const KEY_SEP = "_";

    public function permissionFetchById($permission_id)
    {
        $key = join(self::KEY_SEP, ["perm", $permission_id]);
        $permission = apc_fetch($key);
        if (!$permission) {
            $permission = parent::permissionFetchById($permission_id);
            if ($permission) {
                apc_store("perm_{$permission_id}", $permission, self::DEFAULT_TTL);
            }
        }
        return $permission;
    }
}


text:
package org.drools.guvnor.client.explorer.navigation.qa;

import com.google.gwt.event.shared.EventBus;
import org.drools.guvnor.client.common.GenericCallback;
import org.drools.guvnor.client.explorer.AcceptItem;
import org.drools.guvnor.client.explorer.ClientFactory;
import org.drools.guvnor.client.messages.Constants;
import org.drools.guvnor.client.rpc.Module;
import org.drools.guvnor.client.util.Activity;

public class VerifierActivity extends Activity {

    private final String moduleUuid;
    private final ClientFactory clientFactory;

    public VerifierActivity(String moduleUuid,
                            ClientFactory clientFactory) {
        this.moduleUuid = moduleUuid;
        this.clientFactory = clientFactory;
    }

    @Override
    public void start(AcceptItem tabbedPanel, EventBus eventBus) {
        openVerifierView( tabbedPanel );
    }

    public void openVerifierView(final AcceptItem tabbedPanel) {

        clientFactory.getModuleService().loadModule(
                moduleUuid,
                new GenericCallback<Module>() {
                    public void onSuccess(Module packageConfigData) {
                        tabbedPanel.add(
                                Constants.INSTANCE.AnalysisForPackage( packageConfigData.getName() ),
                                new VerifierScreen(
                                        packageConfigData.getUuid(),
                                        packageConfigData.getName() ) );
                    }
                } );

    }

}


text:
package com.midi_automator.tests.functional;

import static com.midi_automator.tests.utils.GUIAutomations.*;
import static org.junit.Assert.*;

import java.awt.event.KeyEvent;

import org.assertj.swing.fixture.JPopupMenuFixture;
import org.junit.Test;

import com.midi_automator.tests.utils.MockUpUtils;
import com.midi_automator.view.windows.MainFrame.menus.MainFramePopupMenu;

public class MoveEntriesFunctionalITCase extends FunctionalBaseCase {

	@Test
	public void moveUpDownMenuShouldBeDisabledIfListIsEmpty() {

		MockUpUtils.setMockupMidoFile("mockups/empty.mido");
		MockUpUtils.setMockupPropertiesFile("mockups/empty.properties");
		startApplication();

		// check for disabled menu entry
		JPopupMenuFixture popupMenu = getFileList().showPopupMenu();

		popupMenu.menuItem(MainFramePopupMenu.NAME_MENU_ITEM_MOVE_UP)
				.requireDisabled();
		popupMenu.menuItem(MainFramePopupMenu.NAME_MENU_ITEM_MOVE_DOWN)
				.requireDisabled();

	}

	@Test
	public void entryShouldBeMovedDownByMenu() {

		MockUpUtils.setMockupMidoFile("mockups/Hello_world_312.mido");
		MockUpUtils.setMockupPropertiesFile("mockups/empty.properties");
		startApplication();

		// move down entry
		moveDownEntry(0);
		moveDownEntry(1);

		// check for correct order
		assertEquals((getFileList().contents())[0], "1 Hello World 1");
		assertEquals((getFileList().contents())[1], "2 Hello World 2");
		assertEquals((getFileList().contents())[2], "3 Hello World 3");

		// check for inactive menu at last item
		getFileList().showPopupMenuAt(2)
				.menuItem(MainFramePopupMenu.NAME_MENU_ITEM_MOVE_DOWN)
				.requireDisabled();
	}

	@Test
	public void entryShouldBeMovedDownByGlobalKeyListener() {

		MockUpUtils.setMockupMidoFile("mockups/Hello_world_312.mido");
		MockUpUtils.setMockupPropertiesFile("mockups/empty.properties");
		startApplication();

		// move down entry
		selectEntryByLeftClick(0);
		pressKeyOnMainFrame(KeyEvent.VK_ALT);
		pressAndReleaseKeysOnMainFrame(KeyEvent.VK_DOWN);
		pressKeyOnMainFrame(KeyEvent.VK_ALT);
		pressAndReleaseKeysOnMainFrame(KeyEvent.VK_DOWN);

		// check for correct order
		assertEquals((getFileList().contents())[0], "1 Hello World 1");
		assertEquals((getFileList().contents())[1], "2 Hello World 2");
		assertEquals((getFileList().contents())[2], "3 Hello World 3");

		// check for inactive menu at last item
		getFileList().showPopupMenuAt(2)
				.menuItem(MainFramePopupMenu.NAME_MENU_ITEM_MOVE_DOWN)
				.requireDisabled();

		pressAndReleaseKeysOnMainFrame(KeyEvent.VK_ALT);
	}

	@Test
	public void entryShouldBeMovedUpByGlobalKeyListener() {

		MockUpUtils.setMockupMidoFile("mockups/Hello_world_123.mido");
		MockUpUtils.setMockupPropertiesFile("mockups/empty.properties");
		startApplication();

		// move up entry
		selectEntryByLeftClick(2);
		pressKeyOnMainFrame(KeyEvent.VK_ALT);
		pressAndReleaseKeysOnMainFrame(KeyEvent.VK_UP);
		pressKeyOnMainFrame(KeyEvent.VK_ALT);
		pressAndReleaseKeysOnMainFrame(KeyEvent.VK_UP);

		// check for correct order
		assertEquals((getFileList().contents())[0], "1 Hello World 3");
		assertEquals((getFileList().contents())[1], "2 Hello World 1");
		assertEquals((getFileList().contents())[2], "3 Hello World 2");

		// check for inactive menu on first item
		getFileList().showPopupMenuAt(0)
				.menuItem(MainFramePopupMenu.NAME_MENU_ITEM_MOVE_UP)
				.requireDisabled();

		pressAndReleaseKeysOnMainFrame(KeyEvent.VK_ALT);
	}

	@Test
	public void entryShouldBeMovedUpByMenu() {

		MockUpUtils.setMockupMidoFile("mockups/Hello_world_123.mido");
		MockUpUtils.setMockupPropertiesFile("mockups/empty.properties");
		startApplication();

		// move up entry
		moveUpEntry(2);
		moveUpEntry(1);

		// check for correct order
		assertEquals((getFileList().contents())[0], "1 Hello World 3");
		assertEquals((getFileList().contents())[1], "2 Hello World 1");
		assertEquals((getFileList().contents())[2], "3 Hello World 2");

		// check for inactive menu on first item
		getFileList().showPopupMenuAt(0)
				.menuItem(MainFramePopupMenu.NAME_MENU_ITEM_MOVE_UP)
				.requireDisabled();
	}

	@Test
	public void entryShouldBeMovedDownByDND() {

		MockUpUtils.setMockupMidoFile("mockups/Hello_world_312.mido");
		MockUpUtils.setMockupPropertiesFile("mockups/empty.properties");
		startApplication();

		// move entry down
		getFileList().drag(0);
		getFileList().drop(2);

		// check for correct order
		assertEquals((getFileList().contents())[0], "1 Hello World 1");
		assertEquals((getFileList().contents())[1], "2 Hello World 2");
		assertEquals((getFileList().contents())[2], "3 Hello World 3");
	}

	@Test
	public void entryShouldBeMovedUpByDND() {

		MockUpUtils.setMockupMidoFile("mockups/Hello_world_123.mido");
		MockUpUtils.setMockupPropertiesFile("mockups/empty.properties");
		startApplication();

		// move up entry
		getFileList().drag(2);
		getFileList().drop(0);

		// check for correct order
		assertEquals((getFileList().contents())[0], "1 Hello World 1");
		assertEquals((getFileList().contents())[1], "2 Hello World 3");
		assertEquals((getFileList().contents())[2], "3 Hello World 2");
	}

	@Test
	public void emptyEntryShouldBeMovedUpByDND() {

		MockUpUtils.setMockupMidoFile("mockups/Hello_world_12SPACE.mido");
		MockUpUtils.setMockupPropertiesFile("mockups/empty.properties");
		startApplication();

		// move up entry
		getFileList().drag(2);
		getFileList().drop(0);

		// check for correct order
		assertEquals((getFileList().contents())[0], "1 Hello World 1");
		assertEquals((getFileList().contents())[1], "2  ");
		assertEquals((getFileList().contents())[2], "3 Hello World 2");
	}
}


text:
package com.navercorp.pinpoint.plugin.httpclient3;

import com.navercorp.pinpoint.bootstrap.logging.PLogger;
import com.navercorp.pinpoint.bootstrap.logging.PLoggerFactory;
import com.navercorp.pinpoint.bootstrap.plugin.request.ClientHeaderAdaptor;
import org.apache.commons.httpclient.HttpMethod;

/**
 * @author Woonduk Kang(emeroad)
 */
public class HttpMethodClientHeaderAdaptor implements ClientHeaderAdaptor<HttpMethod> {

    private final PLogger logger = PLoggerFactory.getLogger(this.getClass());
    private final boolean isDebug = logger.isDebugEnabled();

    @Override
    public void setHeader(HttpMethod httpMethod, String name, String value) {
        httpMethod.setRequestHeader(name, value);
        if (isDebug) {
            logger.debug("Set header {}={}", name, value);
        }
    }
}


text:
import os
import sys
import re
import numpy as np
import logging
import struct
import random
import math
import wave
import shutil
import collections
import functools
import operator
import heapq

from collections import namedtuple
from contextlib import contextmanager

# special vocabulary symbols

_BOS = '<S>'
_EOS = '</S>'
_UNK = '<UNK>'
_KEEP = '<KEEP>'
_DEL = '<DEL>'
_INS = '<INS>'
_SUB = '<SUB>'
_NONE = '<NONE>'

_START_VOCAB = [_BOS, _EOS, _UNK, _KEEP, _DEL, _INS, _SUB, _NONE]

BOS_ID = 0
EOS_ID = 1
UNK_ID = 2
KEEP_ID = 3
DEL_ID = 4
INS_ID = 5
SUB_ID = 6
NONE_ID = 7

class FinishedTrainingException(Exception):
    def __init__(self):
        debug('finished training')

class CheckpointException(Exception):
    pass
class EvalException(Exception):
    pass

@contextmanager
def open_files(names, mode='r'):
    """ Safely open a list of files in a context manager.
    Example:
    >>> with open_files(['foo.txt', 'bar.csv']) as (f1, f2):
    ...   pass
    """

    files = []
    try:
        for name_ in names:
            if name_ is None:
                file_ = sys.stdin if 'r' in mode else sys.stdout
            else:
                file_ = open(name_, mode=mode)
            files.append(file_)
        yield files
    finally:
        for file_ in files:
            file_.close()

class AttrDict(dict):
    """
    Dictionary whose keys can be accessed as attributes.
    Example:
    >>> d = AttrDict(x=1, y=2)
    >>> d.x
    1
    >>> d.y = 3
    """

    def __init__(self, *args, **kwargs):
        super(AttrDict, self).__init__(*args, **kwargs)
        self.__dict__ = self  # dark magic

    def __getattr__(self, item):
        return self.__dict__.get(item)

def reverse_edits(source, edits, fix=True, strict=False):
    if len(edits) == 1:    # transform list of edits as a list of (op, word) tuples
        edits = edits[0]
        for i, edit in enumerate(edits):
            if edit in (_KEEP, _DEL, _INS, _SUB):
                edit = (edit, edit)
            elif edit.startswith(_INS + '_'):
                edit = (_INS, edit[len(_INS + '_'):])
            elif edit.startswith(_SUB + '_'):
                edit = (_SUB, edit[len(_SUB + '_'):])
            else:
                edit = (_INS, edit)

            edits[i] = edit
    else:
        edits = zip(*edits)

    src_words = source
    target = []
    consistent = True
    i = 0

    for op, word in edits:
        if strict and not consistent:
            break
        if op in (_DEL, _KEEP, _SUB):
            if i >= len(src_words):
                consistent = False
                continue

            if op == _KEEP:
                target.append(src_words[i])
            elif op == _SUB:
                target.append(word)

            i += 1
        else:   # op is INS
            target.append(word)

    if fix:
        target += src_words[i:]

    return target

def initialize_vocabulary(vocabulary_path):
    """
    Initialize vocabulary from file.

    We assume the vocabulary is stored one-item-per-line, so a file:
      dog
      cat
    will result in a vocabulary {'dog': 0, 'cat': 1}, and a reversed vocabulary ['dog', 'cat'].

    :param vocabulary_path: path to the file containing the vocabulary.
    :return:
      the vocabulary (a dictionary mapping string to integers), and
      the reversed vocabulary (a list, which reverses the vocabulary mapping).
    """
    if os.path.exists(vocabulary_path):
        rev_vocab = []
        with open(vocabulary_path) as f:
            rev_vocab.extend(f.readlines())
        rev_vocab = [line.rstrip('\n') for line in rev_vocab]
        vocab = dict([(x, y) for (y, x) in enumerate(rev_vocab)])
        return namedtuple('vocab', 'vocab reverse')(vocab, rev_vocab)
    else:
        raise ValueError("vocabulary file %s not found", vocabulary_path)

def sentence_to_token_ids(sentence, vocabulary, character_level=False):
    """
    Convert a string to list of integers representing token-ids.

    For example, a sentence "I have a dog" may become tokenized into
    ["I", "have", "a", "dog"] and with vocabulary {"I": 1, "have": 2,
    "a": 4, "dog": 7"} this function will return [1, 2, 4, 7].

    :param sentence: a string, the sentence to convert to token-ids
    :param vocabulary: a dictionary mapping tokens to integers
    :param character_level: treat sentence as a string of characters, and
        not as a string of words
    :return: a list of integers, the token-ids for the sentence.
    """
    sentence = sentence.rstrip('\n') if character_level else sentence.split()
    return [vocabulary.get(w, UNK_ID) for w in sentence]

def get_filenames(data_dir, model_dir, extensions, train_prefix, dev_prefix, vocab_prefix, name=None,
                  ref_ext=None, binary=None, decode=None, eval=None, align=None, **kwargs):
    """
    Get a bunch of file prefixes and extensions, and output the list of filenames to be used
    by the model.

    :param data_dir: directory where all the the data is stored
    :param extensions: list of file extensions, in the right order (last extension is always the target)
    :param train_prefix: name of the training corpus (usually 'train')
    :param dev_prefix: name of the dev corpus (usually 'dev')
    :param vocab_prefix: prefix of the vocab files (usually 'vocab')
    :param kwargs: optional contains an additional 'decode', 'eval' or 'align' parameter
    :return: namedtuple containing the filenames
    """
    train_path = os.path.join(data_dir, train_prefix)
    dev_path = [os.path.join(data_dir, prefix) for prefix in dev_prefix]

    train = ['{}.{}'.format(train_path, ext) for ext in extensions]

    dev_extensions = list(extensions)
    if ref_ext is not None and ref_ext != extensions[-1]:
        dev_extensions.append(ref_ext)

    dev = [['{}.{}'.format(path, ext) for ext in dev_extensions] for path in dev_path]

    vocab_path = os.path.join(data_dir, vocab_prefix)
    vocab_src = ['{}.{}'.format(vocab_path, ext) for ext in extensions]

    data = 'data' if name is None else 'data_{}'.format(name)
    vocab_path = os.path.join(model_dir, data, 'vocab')
    vocab = ['{}.{}'.format(vocab_path, ext) for ext in extensions]
    os.makedirs(os.path.dirname(vocab_path), exist_ok=True)

    binary = binary or [False] * len(vocab)
    for src, dest, binary_ in zip(vocab_src, vocab, binary):
        if not binary_ and not os.path.exists(dest):
            debug('copying vocab to {}'.format(dest))
            shutil.copy(src, dest)

    exts = list(extensions)
    if decode is not None:  # empty list means we decode from standard input
        test = decode
        exts.pop(-1)
    elif eval is not None:
        if ref_ext is not None:
            exts[-1] = ref_ext
        test = eval or dev_prefix[:1]
    else:
        test = align or dev_prefix[:1]

    if len(test) == 1 and not (decode and os.path.exists(test[0])):
        corpus_path = os.path.join(data_dir, test[0]) if not os.path.dirname(test[0]) else test[0]
        test = ['{}.{}'.format(corpus_path, ext) for ext in exts]

    filenames = namedtuple('filenames', ['train', 'dev', 'test', 'vocab'])
    return filenames(train, dev, test, vocab)

def read_dataset(paths, extensions, vocabs, max_size=None, character_level=None, sort_by_length=False,
                 max_seq_len=None, from_position=None, binary=None):
    data_set = []

    if from_position is not None:
        debug('reading from position: {}'.format(from_position))

    line_reader = read_lines_from_position(paths, from_position=from_position, binary=binary)
    character_level = character_level or {}

    positions = None

    for inputs, positions in line_reader:
        if len(data_set) > 0 and len(data_set) % 100000 == 0:
            debug("  lines read: {}".format(len(data_set)))

        lines = [
            input_ if binary_ else
            sentence_to_token_ids(input_, vocab.vocab, character_level=character_level.get(ext))
            for input_, vocab, binary_, ext in zip(inputs, vocabs, binary, extensions)
        ]

        if not all(lines):  # skip empty inputs
            continue
        # skip lines that are too long
        if max_seq_len and any(len(line) > max_seq_len[ext] for line, ext in zip(lines, extensions)):
            continue

        data_set.append(lines)

        if max_size and len(data_set) >= max_size:
            break

    debug('files: {}'.format(' '.join(paths)))
    debug('lines reads: {}'.format(len(data_set)))

    if sort_by_length:
        data_set.sort(key=lambda lines: list(map(len, lines)))

    return data_set, positions

def random_batch_iterator(data, batch_size):
    """
    The most basic form of batch iterator.

    :param data: the dataset to segment into batches
    :param batch_size: the size of a batch
    :return: an iterator which yields random batches (indefinitely)
    """
    while True:
        yield random.sample(data, batch_size)

def basic_batch_iterator(data, batch_size, shuffle=False, allow_smaller=True):
    if shuffle:
        random.shuffle(data)

    batch_count = len(data) // batch_size

    if allow_smaller and batch_count * batch_size < len(data):
        batch_count += 1

    for i in range(batch_count):
        yield data[i * batch_size:(i + 1) * batch_size]

def cycling_batch_iterator(data, batch_size, shuffle=True, allow_smaller=True):
    """
    Indefinitely cycle through a dataset and yield batches (the dataset is shuffled
    at each new epoch)

    :param data: the dataset to segment into batches
    :param batch_size: the size of a batch
    :return: an iterator which yields batches (indefinitely)
    """
    while True:
        iterator = basic_batch_iterator(data, batch_size, shuffle=shuffle, allow_smaller=allow_smaller)
        for batch in iterator:
            yield batch

def read_ahead_batch_iterator(data, batch_size, read_ahead=10, shuffle=True, allow_smaller=True,
                              mode='standard', cycle=True, crash_test=False, **kwargs):
    """
    Same iterator as `cycling_batch_iterator`, except that it reads a number of batches
    at once, and sorts their content according to their size.

    This is useful for training, where all the sequences in one batch need to be padded
     to the same length as the longest sequence in the batch.

    :param data: the dataset to segment into batches
    :param batch_size: the size of a batch
    :param read_ahead: number of batches to read ahead of time and sort (larger numbers
      mean faster training, but less random behavior)
    :return: an iterator which yields batches (indefinitely)
    """
    if not cycle:
        iterator = basic_batch_iterator(data, batch_size, shuffle=shuffle, allow_smaller=allow_smaller)
    elif mode == 'random':
        iterator = random_batch_iterator(data, batch_size)
    else:
        iterator = cycling_batch_iterator(data, batch_size, shuffle=shuffle, allow_smaller=allow_smaller)

    if crash_test:
        n = batch_size // 2
        dummy_batch = heapq.nlargest(n, data, key=lambda p: len(p[0]))
        dummy_batch += heapq.nlargest(batch_size - n, data, key=lambda p: len(p[1]))

        while True:
            yield dummy_batch

    if read_ahead is None or read_ahead <= 1:
        yield from iterator

    while True:
        batches = []
        for batch in iterator:
            batches.append(batch)
            if len(batches) >= read_ahead:
                break

        data_ = sorted(sum(batches, []), key=lambda lines: len(lines[-1]))
        batches = [data_[i * batch_size:(i + 1) * batch_size] for i in range(read_ahead)]
        batches = [batch for batch in batches if batch]  # filter empty batches

        if not any(batches):
            break

        if shuffle:  # TODO: enable shuffling here without epoch shuffling
            random.shuffle(batches)
        for batch in batches:
            yield batch

def get_batch_iterator(paths, extensions, vocabs, batch_size, max_size=None, character_level=None,
                       sort_by_length=False, max_seq_len=None, read_ahead=10, shuffle=True,
                       binary=None, mode='standard', crash_test=False):
    read_shard = functools.partial(read_dataset,
        paths=paths, extensions=extensions, vocabs=vocabs, max_size=max_size, max_seq_len=max_seq_len,
        character_level=character_level, sort_by_length=sort_by_length, binary=binary)
    batch_iterator = functools.partial(read_ahead_batch_iterator, batch_size=batch_size, read_ahead=read_ahead,
                                       shuffle=shuffle, mode=mode, crash_test=crash_test)

    # FIXME: crash test only for first shard
    with open(paths[-1]) as f:   # count lines
        line_count = sum(1 for _ in f)
        debug('total line count: {}'.format(line_count))

    shard, position = read_shard()
    if not max_size or line_count <= max_size:
        # training set is small enough to fit entirely into memory (single shard)
        return batch_iterator(shard), line_count
    else:
        batch_iterator = functools.partial(batch_iterator, cycle=False)

        def generator(position, shard):
            while True:
                if len(shard) < max_size:
                    # last shard, start again from the beginning of the dataset
                    position = None

                size = 0
                for batch in batch_iterator(shard):
                    size += len(batch)
                    yield batch

                    if size >= len(shard):  # cycle through this shard only once, then read next shard
                        shard, position = read_shard(from_position=position)
                        break

        return generator(position, shard), line_count

def get_batches(data, batch_size, batches=0, allow_smaller=True):
    """
    Segment `data` into a given number of fixed-size batches. The dataset is automatically shuffled.

    This function is for smaller datasets, when you need access to the entire dataset at once (e.g. dev set).
    For larger (training) datasets, where you may want to lazily iterate over batches
    and cycle several times through the entire dataset, prefer batch iterators
    (such as `cycling_batch_iterator`).

    :param data: the dataset to segment into batches (a list of data points)
    :param batch_size: the size of a batch
    :param batches: number of batches to return (0 for the largest possible number)
    :param allow_smaller: allow the last batch to be smaller
    :return: a list of batches (which are lists of `batch_size` data points)
    """
    if not allow_smaller:
        max_batches = len(data) // batch_size
    else:
        max_batches = int(math.ceil(len(data) / batch_size))

    if batches < 1 or batches > max_batches:
        batches = max_batches

    random.shuffle(data)
    batches = [data[i * batch_size:(i + 1) * batch_size] for i in range(batches)]
    return batches

def read_binary_features(filename, from_position=None):
    """
    Reads a binary file containing vector features. First two (int32) numbers correspond to
    number of entries (lines), and dimension of the vectors.
    Each entry is a numpy array of shape (nframes, dim).

    Use `scripts/speech/extract-audio-features.py` or `scripts/speech/extract.py` to create such a file for audio (MFCCs).

    :param filename: path to the binary file containing the features
    :return: list of arrays of shape (frames, dimension)
    """
    with open(filename, 'rb') as f:
        lines, dim = np.load(f)
        if from_position is not None:
            f.seek(from_position)

        for _ in range(lines):
            try:
                feats = np.load(f)
                yield list(feats), f.tell()
            except OSError:
                pass

def read_lines(paths, binary=None):
    binary = binary or [False] * len(paths)
    return zip(*[sys.stdin if path is None else
                 map(operator.itemgetter(0), read_binary_features(path)) if binary_
                 else open(path)
                 for path, binary_ in zip(paths, binary)])

def read_text_from_position(filename, from_position=None):
    with open(filename) as f:
        if from_position is not None:
            f.seek(from_position)
        while True:
            line = f.readline()
            if not line:
                break
            yield line, f.tell()

def read_lines_from_position(paths, from_position=None, binary=None):
    binary = binary or [False] * len(paths)
    from_position = from_position or [None] * len(paths)

    iterators = [
        read_binary_features(path, from_position_) if binary_ else
        read_text_from_position(path, from_position_)
        for path, binary_, from_position_ in zip(paths, binary, from_position)
    ]

    for data in zip(*iterators):
        yield tuple(zip(*data))

def create_logger(log_file=None):
    """
    Initialize global logger and return it.

    :param log_file: log to this file, or to standard output if None
    :return: created logger
    """
    formatter = logging.Formatter(fmt='%(asctime)s %(message)s', datefmt='%m/%d %H:%M:%S')
    if log_file is not None:
        os.makedirs(os.path.dirname(log_file), exist_ok=True)
        handler = logging.FileHandler(log_file)
        handler.setFormatter(formatter)
        logger = logging.getLogger(__name__)
        logger.addHandler(handler)

    handler = logging.StreamHandler()
    handler.setFormatter(formatter)
    logger = logging.getLogger(__name__)
    logger.addHandler(handler)
    return logger

def log(msg, level=logging.INFO):
    logging.getLogger(__name__).log(level, msg)

def debug(msg): log(msg, level=logging.DEBUG)

def warn(msg): log(msg, level=logging.WARN)

def heatmap(xlabels=None, ylabels=None, weights=None, output_file=None, reverse=False):
    """
    Draw a heatmap showing the alignment between two sequences.

    :param xlabels: input words
    :param ylabels: output words
    :param weights: numpy array of shape (len(xlabels), len(ylabels))
    :param output_file: write the figure to this file, or show it into a window if None
    """
    import matplotlib
    from matplotlib import pyplot as plt

    if reverse and not ylabels:
        matplotlib.rcParams.update({'font.size': 18})

    def prettify(token):
        token_mapping = {
            '"': '"',
            ''': '\'',
            '&': '&',
            '@@': '_'
        }
        for x, y in token_mapping.items():
            token = token.replace(x, y)
        return token

    xlabels = xlabels or []
    ylabels = ylabels or []
    xlabels = list(map(prettify, xlabels))
    ylabels = list(map(prettify, ylabels))

    if reverse:
        xlabels, ylabels = ylabels, xlabels
        weights = weights.T

    fig, ax = plt.subplots()

    plt.autoscale(enable=True, axis='x', tight=True)
    #ax.pcolor(weights, cmap=plt.cm.Greys)
    ax.pcolor(weights, cmap=plt.cm.Greys)
    ax.set_frame_on(False)
    # plt.colorbar(mappable=heatmap_)

    # put the major ticks at the middle of each cell
    ax.set_yticks(np.arange(weights.shape[0]) + 0.5, minor=False)
    ax.set_xticks(np.arange(weights.shape[1]) + 0.5, minor=False)
    ax.invert_yaxis()
    ax.xaxis.tick_top()

    ax.set_xticklabels(xlabels, minor=False)
    ax.set_yticklabels(ylabels, minor=False)
    ax.tick_params(axis='both', which='both', length=0)

    if not reverse:
        plt.xticks(rotation=90)

    plt.xticks(fontsize=18)
    plt.yticks(fontsize=18)
    plt.subplots_adjust(wspace=0, hspace=0)

    if not reverse or ylabels:
        plt.tight_layout()
        ax.set_aspect('equal')
        ax.grid(True)

    xsize = max(2.0 + len(xlabels) / 3, 8.0)
    ysize = max(2.0 + len(ylabels) / 3, 8.0)
    fig.set_size_inches(xsize, ysize, forward=True)

    if output_file is None:
        plt.show()
    else:
        plt.savefig(output_file, bbox_inches='tight')

def alignment_to_text(xlabels=None, ylabels=None, weights=None, output_file=None):
    """
    :param xlabels: input words
    :param ylabels: output words
    :param weights: numpy array of shape (len(xlabels), len(ylabels))
    :param output_file: write the matrix in this file
    """
    with open(output_file.replace('svg', 'txt').replace('jpg', 'txt'), 'w') as output_file:
        output_file.write(' \t' + '\t'.join(xlabels) + '\n')
        for i in range(len(ylabels)):
            output_file.write(ylabels[i])
            for j in range(len(xlabels)):
                output_file.write('\t' + str(weights[i][j]))
            output_file.write('\n')


text:
from modeltranslation.translator import translator, TranslationOptions
from openbudgets.apps.sheets import models

class SheetTransOps(TranslationOptions):
    fields = ('description',)

class SheetItemTransOps(TranslationOptions):
    fields = ('description',)

class TemplateTransOps(TranslationOptions):
    fields = ('name', 'description')

class TemplateNodeTransOps(TranslationOptions):
    fields = ('name', 'description')

translator.register(models.Sheet, SheetTransOps)
translator.register(models.SheetItem, SheetItemTransOps)
translator.register(models.Template, TemplateTransOps)
translator.register(models.TemplateNode, TemplateNodeTransOps)


text:
package madgik.exareme.master.queryProcessor.analyzer.fanalyzer;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.HashSet;
import java.util.Set;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * @author jim
 */
public class Demo {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws Exception {
        // TODO code application logic here

		/* analyze all tables */
    /*
     * FederatedAnalyzer fa = new FederatedAnalyzer(); fa.analyzeAll();
		 */

		/* analyze specific table */
        FederatedAnalyzer fa = new FederatedAnalyzer();
        Set<String> tableNames = new HashSet<String>();

        // This txt file contains all the tables we need to analyze
        try (BufferedReader br = new BufferedReader(new FileReader("./files/input/slegge.txt"))) {
            String line;
            while ((line = br.readLine()) != null) {
                // process the line.
                tableNames.add(line);
            }
        }

        for (String s : tableNames) {
            fa.analyzeTable(s);
        }
        fa.closeConnection();

    }

}


text:
HOME=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )/..
DATADIR="$HOME/backup/"

mkdir -p "$DATADIR" && cd "$DATADIR"
/usr/bin/git init

mkdir db-dumps files
touch db-dumps/.keep files/.keep

/usr/bin/git add db-dumps/.keep files/.keep
/usr/bin/git commit -q -a -m 'initialize backup directory structure'

cd $HOME
chmod go-rwx config backup


text:
import isObject from '../../../src/isObject';

describe('isObject', () => {
  it('returns input if input is an object', () => {
    const input = { object: true };
    expect(isObject(input)).to.deep.equal(input);
  });

  [[], null, undefined, false, true, 0, 1, 'invalid'].forEach((invalidInput) => {
    it(`throws an error if input is type ${typeof invalidInput} of value ${invalidInput}`, () => {
      const func = () => isObject(invalidInput);
      expect(func).to.throw(Error);
      return new Promise(func)
                .catch((err) => {
                  expect(err.message).to.equal('invalid input, should be of type object');
                });
    });
  });

  [[], true, 1, {}].forEach((invalidInput) => {
    it(`throws an error if options.errorMessage is type ${typeof invalidInput} of value ${invalidInput}`, () => {
      const func = () => isObject({}, { errorMessage: invalidInput });
      expect(func).to.throw(Error);
      return new Promise(func)
                .catch((err) => {
                  expect(err.message).to.equal('options.errorMessage must be a string');
                });
    });
  });

  it('throws an error if input is a date object', () => {
    const func = () => isObject(new Date());
    expect(func).to.throw(Error);
    return new Promise(func)
            .catch((err) => {
              expect(err.message).to.equal('invalid input, should be of type object');
            });
  });

  it('throws an error if input is a function', () => {
    const func = () => isObject(() => {
    });
    expect(func).to.throw(Error);
    return new Promise(func)
            .catch((err) => {
              expect(err.message).to.equal('invalid input, should be of type object');
            });
  });

  it('throws an error with options.errorMessage if passed as options', () => {
    const errorMessage = 'custom error message';
    const func = () => isObject(null, { errorMessage });
    expect(func).to.throw(Error);

    return new Promise(func)
            .catch((err) => {
              expect(err.message).to.equal(errorMessage);
            });
  });

  it('throws default error if options is passed without errorMessage property', () => {
    const func = () => isObject(null, {});
    expect(func).to.throw(Error);

    return new Promise(func)
            .catch((err) => {
              expect(err.message).to.equal('invalid input, should be of type object');
            });
  });

  [1, [], 'string', true].forEach((invalidInput) => {
    it(`throws error message if options.shape is a ${typeof invalidInput} with value ${invalidInput}`, () => {
      const func = () => isObject({}, { shape: invalidInput });
      expect(func).to.throw(Error);

      return new Promise(func)
                .catch((err) => {
                  expect(err.message).to.equal('options.shape must be an object');
                });
    });
  });

  it('validates the shape of an object', () => {
    const shape = {
      age: { type: 'number' },
      name: { type: 'string' },
      school: {
        type: 'object',
        shape: {
          name: { type: 'string' },
          location: { type: 'string' },
        },
      },
      hobbies: { type: 'array', elementType: 'string' },
    };
    const object = {
      age: '25',
      name: 'Edd',
      school: {
        name: 'Marling',
        location: 'Stroud',
      },
      hobbies: ['guitar', 'coding'],
    };

    const expectedOutput = JSON.parse(JSON.stringify(object));
    expectedOutput.age = 25;
    expect(isObject(object, { shape })).to.deep.equal(expectedOutput);
  });

  it('throws error if array items do not match elementType', () => {
    const shape = {
      hobbies: { type: 'array', elementType: 'number' },
    };
    const object = {
      hobbies: ['guitar', 'football'],
    };
    const func = () => isObject(object, { shape });
    expect(func).to.throw(Error);

    return new Promise(func)
        .catch((err) => {
          expect(err.message).to.equal('hobbies must be an array of numbers');
        });
  });

  it('returns object when array has a shape matching expected shape', () => {
    const shape = {
      hobbies: {
        type: 'array',
        shape: {
          name: { type: 'string' },
          years: { type: 'number' },
        },
      },
    };
    const object = {
      hobbies: [{ name: 'guitar', years: 1 }, { name: 'coding', years: '4' }],
    };
    expect(isObject(object, { shape })).to.deep.equal(object);
  });

  it('returns object if property missing does not have required set to true', () => {
    const shape = {
      hobbies: {
        type: 'array',
        elementType: 'object',
        shape: {
          name: { type: 'string', required: true },
          years: { type: 'number' },
        },
      },
    };
    const object = {
      hobbies: [{ name: 'guitar' }, { name: 'coding', years: '4' }],
    };
    const expectedOutput = {
      hobbies: [{ name: 'guitar' }, { name: 'coding', years: 4 }],
    };
    expect(isObject(object, { shape })).to.deep.equal(expectedOutput);
  });

  it('throws error when missing property has required:true', () => {
    const shape = {
      hobbies: {
        type: 'array',
        shape: {
          name: { type: 'string', required: true },
          years: { type: 'number', required: true },
        },
      },
    };
    const object = {
      hobbies: [{ name: 'guitar' }, { name: 'coding', years: 4 }],
    };

    const func = () => isObject(object, { shape });
    expect(func).to.throw(Error);

    return new Promise(func)
            .catch((err) => {
              expect(err.message).to.equal('years must be a number');
            });
  });

  it('throws error when array shape does not match expected shape', () => {
    const shape = {
      hobbies: {
        type: 'array',
        shape: {
          name: { type: 'string' },
          years: { type: 'number' },
        },
      },
    };
    const object = {
      hobbies: [{ name: 'guitar', years: 'one' }, { name: 'coding', years: 4 }],
    };

    const func = () => isObject(object, { shape });
    expect(func).to.throw(Error);

    return new Promise(func)
        .catch((err) => {
          expect(err.message).to.equal('years must be a number');
        });
  });

  it('throws an error if object shape does not match options.shape of an object', () => {
    const shape = {
      age: { type: 'number' },
      name: { type: 'string' },
      school: {
        type: 'object',
        shape: {
          name: { type: 'string' },
          location: { type: 'string' },
        },
      },
    };
    const object = {
      age: 25,
      name: 'Edd',
      school: {
        name: 'Marling',
        location: 12,
      },
    };
    const func = () => isObject(object, { shape });
    expect(func).to.throw(Error);
    return new Promise(func)
            .catch((err) => {
              expect(err.message).to.equal('location must be a string');
            });
  });

  it('throws an error if object shape contains an invalid type', () => {
    const shape = {
      age: { type: 'not valid type' },
    };
    const object = {
      age: 25,
    };
    const func = () => isObject(object, { shape });
    expect(func).to.throw(Error);
    return new Promise(func)
            .catch((err) => {
              expect(err.message).to.equal('not valid type is not a valid type - must be string, number, object or array');
            });
  });
});


text:
<?php

namespace Zicht\Itertools\lib;

use Zicht\Itertools\lib\Interfaces\FiniteIterableInterface;
use Zicht\Itertools\lib\Traits\FiniteIterableTrait;

class IterableIterator extends \IteratorIterator implements FiniteIterableInterface
{
    use FiniteIterableTrait;
}


text:
<!DOCTYPE html>

  <title>new Text( name, optional )</title>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <meta name="viewport" content="width=device-width, target-densitydpi=160dpi, initial-scale=1.0; maximum-scale=1.0; user-scalable=0;">
  <link rel="stylesheet" media="all" href="docco.css" />

          Jump To …
          +

                  helpers.coffee

                  key.coffee

                  resource.coffee

                  route.coffee

                  router.coffee

                  text.coffee

                ¶

new Text( name, optional )

                ¶

those variable thingies

text = new Static('text')

exports.Text =
class Text
  constructor: ( @text )->

                ¶

no-op

                ¶

text.regexString()

                ¶

makes a regex string of the text path - used by text.test()

returns a string of this path's regex

  regexString: ->
    @text.replace /[.*+?^${}()|[\]\\]/g, "\\$&"

                ¶

text.test( string )

                ¶

validates a string using the key's regex pattern

returns true/false if the string matches

  test: ( string )->
    @text == string

                ¶

text.url( string )

                ¶

returns a string for building the url
if it matches the key conditions

  url: ( string )->
    if @test(string) then string else false

                ¶

text.toString()

                ¶

returns a unique id that can be compared to other parts

  toString: ->
    @text

  @regex = /[\w\-_\\\/\.]+/

  @parse = ( string )->
    pattern = new RegExp "^#{ @regex.source }"

    name = pattern.exec(string)[0]

    new @ name


text:
package com.wut.resources.photos;

import java.util.ArrayList;
import java.util.Random;

import com.wut.model.Data;
import com.wut.model.map.MappedData;
import com.wut.model.raw.RawData;
import com.wut.pipeline.WutRequest;
import com.wut.resources.common.MissingParameterException;
import com.wut.resources.common.ObsoleteCrudResource;
import com.wut.resources.common.ResourceGroupAnnotation;

@ResourceGroupAnnotation(name = "single", group = "photos", desc = "data store for session data")
public class SinglePhotoResource extends ObsoleteCrudResource {

	private static final long serialVersionUID = 7563899849244315413L;

	@Override
	public Data read(WutRequest ri) throws MissingParameterException {
		FlickrSource flickrSrc = new FlickrSource();
		ArrayList<MappedData> flickrUrls = flickrSrc.getFlickrUrls(ri
				.getStringParameter("tags"), "50", "1");
		Random r = new Random();
		int randomIndex = Math.abs(r.nextInt()) % flickrUrls.size();
		String uri = flickrUrls.get(randomIndex).get("url").toString();
		return new RawData(uri);
	}

}


text:
var baseIsRegExp = require('./_baseIsRegExp'),
    baseUnary = require('./_baseUnary'),
    nodeUtil = require('./_nodeUtil');

/* Node.js helper references. */
var nodeIsRegExp = nodeUtil && nodeUtil.isRegExp;

/**
 * Checks if `value` is classified as a `RegExp` object.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a regexp, else `false`.
 * @example
 *
 * _.isRegExp(/abc/);
 * // => true
 *
 * _.isRegExp('/abc/');
 * // => false
 */
var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp;

module.exports = isRegExp;


text:
$packageName = 'andy'
$installerType = 'exe'
$url = 'http://d1ubedgu4eka0j.cloudfront.net/ANDY/installer/v45/Andy_Android_Emulator_v45_5_36.exe'
$silentArgs = '/S'
$validExitCodes = @(0)
$checksum = '3c8e8b3eca433eb1fcdb4b2b255237f9'
$checksumType = 'md5'

Install-ChocolateyPackage -PackageName "$packageName" `
                          -FileType "$installerType" `
                          -SilentArgs "$silentArgs" `
                          -Url "$url" `
                          -ValidExitCodes $validExitCodes `
                          -Checksum "$checksum" `
                          -ChecksumType "$checksumType"


text:
The important rules to follow to make this script available as a git sub-command are:

- It should be named git-COMMANDNAME, in this case it's called git-activity
- and it needs to be executable and available on the $PATH

## Man pages

If the custom command has an accompanying man page, the git help command will show the help information as well.
Bonus tip Man pages can easily be generated from Markdown using [Pandoc](http://pandoc.org)