text:
<?php

/**
 * @file
 * Definition of Drupal\menu\Tests\MenuTest.
 */

namespace Drupal\menu\Tests;

/**
 * Defines a test class for testing menu and menu link functionality.
 */
class MenuTest extends MenuWebTestBase {

  /**
   * Modules to enable.
   *
   * @var array
   */
  public static $modules = array('block', 'test_page_test', 'contextual');

  protected $big_user;
  protected $std_user;
  protected $menu;
  protected $items;

  public static function getInfo() {
    return array(
      'name' => 'Menu link creation/deletion',
      'description' => 'Add a custom menu, add menu links to the custom menu and Tools menu, check their data, and delete them using the menu module UI.',
      'group' => 'Menu'
    );
  }

  function setUp() {
    parent::setUp();

    $this->drupalCreateContentType(array('type' => 'article', 'name' => 'Article'));

    // Create users.
    $this->big_user = $this->drupalCreateUser(array('access administration pages', 'administer blocks', 'administer menu', 'create article content'));
    $this->std_user = $this->drupalCreateUser(array());
  }

  /**
   * Login users, add menus and menu links, and test menu functionality through the admin and user interfaces.
   */
  function testMenu() {
    // Login the user.
    $this->drupalLogin($this->big_user);
    $this->items = array();

    $this->menu = $this->addCustomMenu();
    $this->doMenuTests($this->menu->id());
    $this->addInvalidMenuLink($this->menu->id());
    $this->addCustomMenuCRUD();

    // Do standard user tests.
    // Login the user.
    $this->drupalLogin($this->std_user);
    $this->verifyAccess(403, $this->menu->id());
    foreach ($this->items as $item) {
      $node = node_load(substr($item['link_path'], 5)); // Paths were set as 'node/$nid'.
      $this->verifyMenuLink($item, $node);
    }

    // Login the user.
    $this->drupalLogin($this->big_user);

    // Delete menu links.
    foreach ($this->items as $item) {
      $this->deleteMenuLink($item);
    }

    // Delete custom menu.
    $this->deleteCustomMenu($this->menu);

    // Modify and reset a standard menu link.
    $item = $this->getStandardMenuLink();
    $old_title = $item['link_title'];
    $this->modifyMenuLink($item);
    $item = entity_load('menu_link', $item['mlid']);
    // Verify that a change to the description is saved.
    $description = $this->randomName(16);
    $item['options']['attributes']['title']  = $description;
    $return_value = menu_link_save($item);
    // Save the menu link again to test the return value of the procedural save
    // helper.
    $this->assertIdentical($return_value, $item->save(), 'Return value of menu_link_save() is identical to the return value of $menu_link->save().');
    $saved_item = entity_load('menu_link', $item['mlid']);
    $this->assertEqual($description, $saved_item['options']['attributes']['title'], 'Saving an existing link updates the description (title attribute)');
    $this->resetMenuLink($item, $old_title);
  }

  /**
   * Add custom menu using CRUD functions.
   */
  function addCustomMenuCRUD() {
    // Add a new custom menu.
    $menu_name = substr(hash('sha256', $this->randomName(16)), 0, MENU_MAX_MENU_NAME_LENGTH_UI);
    $label = $this->randomName(16);

    $menu = entity_create('menu', array(
      'id' => $menu_name,
      'label' => $label,
      'description' => 'Description text',
    ));
    $menu->save();

    // Assert the new menu.
    $this->drupalGet('admin/structure/menu/manage/' . $menu_name);
    $this->assertRaw($label, 'Custom menu was added.');

    // Edit the menu.
    $new_label = $this->randomName(16);
    $menu->set('label', $new_label);
    $menu->save();
    $this->drupalGet('admin/structure/menu/manage/' . $menu_name);
    $this->assertRaw($new_label, 'Custom menu was edited.');
  }

  /**
   * Add custom menu.
   */
  function addCustomMenu() {

    // Try adding a menu using a menu_name that is too long.
    $this->drupalGet('admin/structure/menu/add');
    $menu_name = substr(hash('sha256', $this->randomName(16)), 0, MENU_MAX_MENU_NAME_LENGTH_UI + 1);
    $label = $this->randomName(16);
    $edit = array(
      'id' => $menu_name,
      'description' => '',
      'label' =>  $label,
    );
    $this->drupalPost('admin/structure/menu/add', $edit, t('Save'));

    // Verify that using a menu_name that is too long results in a validation message.
    $this->assertRaw(t('!name cannot be longer than %max characters but is currently %length characters long.', array(
      '!name' => t('Menu name'),
      '%max' => MENU_MAX_MENU_NAME_LENGTH_UI,
      '%length' => drupal_strlen($menu_name),
    )));

    // Change the menu_name so it no longer exceeds the maximum length.
    $menu_name = substr(hash('sha256', $this->randomName(16)), 0, MENU_MAX_MENU_NAME_LENGTH_UI);
    $edit['id'] = $menu_name;
    $this->drupalPost('admin/structure/menu/add', $edit, t('Save'));

    // Verify that no validation error is given for menu_name length.
    $this->assertNoRaw(t('!name cannot be longer than %max characters but is currently %length characters long.', array(
      '!name' => t('Menu name'),
      '%max' => MENU_MAX_MENU_NAME_LENGTH_UI,
      '%length' => drupal_strlen($menu_name),
    )));
    // Verify that confirmation message displayed.
    $this->assertRaw(t('Menu %label has been added.', array('%label' => $label)));
    $this->drupalGet('admin/structure/menu');
    $this->assertText($label, 'Menu created');

    // Enable the custom menu block.
    $menu_name = 'menu-' . $menu_name; // Drupal prepends the name with 'menu-'.
    // Confirm that the custom menu block is available.
    $this->drupalGet('admin/structure/block/list/block_plugin_ui:' . config('system.theme')->get('default') . '/add');
    $this->assertText($label);

    // Enable the block.
    $this->drupalPlaceBlock('menu_menu_block:' . $menu_name);
    return menu_load($menu_name);
  }

  /**
   * Delete custom menu.
   *
   * @param string $menu_name Custom menu name.
   */
  function deleteCustomMenu($menu) {
    $menu_name = $this->menu->id();
    $label = $this->menu->label();

    // Delete custom menu.
    $this->drupalPost("admin/structure/menu/manage/$menu_name/delete", array(), t('Delete'));
    $this->assertResponse(200);
    $this->assertRaw(t('The custom menu %title has been deleted.', array('%title' => $label)), 'Custom menu was deleted');
    $this->assertFalse(menu_load($menu_name), 'Custom menu was deleted');
    // Test if all menu links associated to the menu were removed from database.
    $result = entity_load_multiple_by_properties('menu_link', array('menu_name' => $menu_name));
    $this->assertFalse($result, 'All menu links associated to the custom menu were deleted.');

    // Make sure there's no delete button on system menus.
    $this->drupalGet('admin/structure/menu/manage/main');
    $this->assertNoRaw('edit-delete', 'The delete button was not found');

    // Try to delete the main menu.
    $this->drupalGet('admin/structure/menu/manage/main/delete');
    $this->assertText(t('You are not authorized to access this page.'));
  }

  /**
   * Tests menu functionality.
   */
  function doMenuTests($menu_name) {
    // Add nodes to use as links for menu links.
    $node1 = $this->drupalCreateNode(array('type' => 'article'));
    $node2 = $this->drupalCreateNode(array('type' => 'article'));
    $node3 = $this->drupalCreateNode(array('type' => 'article'));
    $node4 = $this->drupalCreateNode(array('type' => 'article'));
    $node5 = $this->drupalCreateNode(array('type' => 'article'));

    // Add menu links.
    $item1 = $this->addMenuLink(0, 'node/' . $node1->id(), $menu_name);
    $item2 = $this->addMenuLink($item1['mlid'], 'node/' . $node2->id(), $menu_name, FALSE);
    $item3 = $this->addMenuLink($item2['mlid'], 'node/' . $node3->id(), $menu_name);
    $this->assertMenuLink($item1['mlid'], array(
      'depth' => 1,
      'has_children' => 1,
      'p1' => $item1['mlid'],
      'p2' => 0,
      // We assert the language code here to make sure that the language
      // selection element degrades gracefully without Language module.
      'langcode' => 'en',
    ));
    $this->assertMenuLink($item2['mlid'], array(
      'depth' => 2, 'has_children' => 1,
      'p1' => $item1['mlid'],
      'p2' => $item2['mlid'],
      'p3' => 0,
      // See above.
      'langcode' => 'en',
    ));
    $this->assertMenuLink($item3['mlid'], array(
      'depth' => 3,
      'has_children' => 0,
      'p1' => $item1['mlid'],
      'p2' => $item2['mlid'],
      'p3' => $item3['mlid'],
      'p4' => 0,
      // See above.
      'langcode' => 'en',
    ));

    // Verify menu links.
    $this->verifyMenuLink($item1, $node1);
    $this->verifyMenuLink($item2, $node2, $item1, $node1);
    $this->verifyMenuLink($item3, $node3, $item2, $node2);

    // Add more menu links.
    $item4 = $this->addMenuLink(0, 'node/' . $node4->id(), $menu_name);
    $item5 = $this->addMenuLink($item4['mlid'], 'node/' . $node5->id(), $menu_name);
    $this->assertMenuLink($item4['mlid'], array(
      'depth' => 1,
      'has_children' => 1,
      'p1' => $item4['mlid'],
      'p2' => 0,
      // See above.
      'langcode' => 'en',
    ));
    $this->assertMenuLink($item5['mlid'], array(
      'depth' => 2,
      'has_children' => 0,
      'p1' => $item4['mlid'],
      'p2' => $item5['mlid'],
      'p3' => 0,
      // See above.
      'langcode' => 'en',
    ));

    // Modify menu links.
    $this->modifyMenuLink($item1);
    $this->modifyMenuLink($item2);

    // Toggle menu links.
    $this->toggleMenuLink($item1);
    $this->toggleMenuLink($item2);

    // Move link and verify that descendants are updated.
    $this->moveMenuLink($item2, $item5['mlid'], $menu_name);
    $this->assertMenuLink($item1['mlid'], array(
      'depth' => 1,
      'has_children' => 0,
      'p1' => $item1['mlid'],
      'p2' => 0,
      // See above.
      'langcode' => 'en',
    ));
    $this->assertMenuLink($item4['mlid'], array(
      'depth' => 1,
      'has_children' => 1,
      'p1' => $item4['mlid'],
      'p2' => 0,
      // See above.
      'langcode' => 'en',
    ));
    $this->assertMenuLink($item5['mlid'], array(
      'depth' => 2,
      'has_children' => 1,
      'p1' => $item4['mlid'],
      'p2' => $item5['mlid'],
      'p3' => 0,
      // See above.
      'langcode' => 'en',
    ));
    $this->assertMenuLink($item2['mlid'], array(
      'depth' => 3,
      'has_children' => 1,
      'p1' => $item4['mlid'],
      'p2' => $item5['mlid'],
      'p3' => $item2['mlid'],
      'p4' => 0,
      // See above.
      'langcode' => 'en',
    ));
    $this->assertMenuLink($item3['mlid'], array(
      'depth' => 4,
      'has_children' => 0,
      'p1' => $item4['mlid'],
      'p2' => $item5['mlid'],
      'p3' => $item2['mlid'],
      'p4' => $item3['mlid'],
      'p5' => 0,
      // See above.
      'langcode' => 'en',
    ));

    // Add 102 menu links with increasing weights, then make sure the last-added
    // item's weight doesn't get changed because of the old hardcoded delta=50
    $items = array();
    for ($i = -50; $i <= 51; $i++) {
      $items[$i] = $this->addMenuLink(0, 'node/' . $node1->id(), $menu_name, TRUE, strval($i));
    }
    $this->assertMenuLink($items[51]['mlid'], array('weight' => '51'));

    // Enable a link via the overview form.
    $this->disableMenuLink($item1);
    $edit = array();

    // Note in the UI the 'links[mlid:x][hidden]' form element maps to enabled,
    // or NOT hidden.
    $edit['links[mlid:' . $item1['mlid'] . '][hidden]'] = TRUE;
    $this->drupalPost('admin/structure/menu/manage/' . $item1['menu_name'], $edit, t('Save'));

    // Verify in the database.
    $this->assertMenuLink($item1['mlid'], array('hidden' => 0));

    // Save menu links for later tests.
    $this->items[] = $item1;
    $this->items[] = $item2;
  }

  /**
   * Add and remove a menu link with a query string and fragment.
   */
  function testMenuQueryAndFragment() {
    $this->drupalLogin($this->big_user);

    // Make a path with query and fragment on.
    $path = 'test-page?arg1=value1&arg2=value2';
    $item = $this->addMenuLink(0, $path);

    $this->drupalGet('admin/structure/menu/item/' . $item['mlid'] . '/edit');
    $this->assertFieldByName('link_path', $path, 'Path is found with both query and fragment.');

    // Now change the path to something without query and fragment.
    $path = 'test-page';
    $this->drupalPost('admin/structure/menu/item/' . $item['mlid'] . '/edit', array('link_path' => $path), t('Save'));
    $this->drupalGet('admin/structure/menu/item/' . $item['mlid'] . '/edit');
    $this->assertFieldByName('link_path', $path, 'Path no longer has query or fragment.');
  }

  /**
   * Test renaming built-in menu.
   */
  function testSystemMenuRename() {
    $this->drupalLogin($this->big_user);
    $edit = array(
      'label' => $this->randomName(16),
    );
    $this->drupalPost('admin/structure/menu/manage/main', $edit, t('Save'));

    // Make sure menu shows up with new name in block addition.
    $default_theme = variable_get('theme_default', 'stark');
    $this->drupalget('admin/structure/block/list/block_plugin_ui:' . $default_theme . '/add');
    $this->assertText($edit['label']);
  }

  /**
   * Tests the contextual links on a menu block.
   */
  public function testBlockContextualLinks() {
    $this->drupalLogin($this->drupalCreateUser(array('administer menu', 'access contextual links', 'administer blocks')));
    $this->addMenuLink();
    $block = $this->drupalPlaceBlock('system_menu_block:menu-tools', array('label' => 'Tools', 'module' => 'system'));
    $this->drupalGet('test-page');

    $id = 'block:admin/structure/block/manage:' . $block->id() . ':|menu:admin/structure/menu/manage:tools:';
    // @see \Drupal\contextual\Tests\ContextualDynamicContextTest:assertContextualLinkPlaceHolder()
    $this->assertRaw('

', format_string('Contextual link placeholder with id @id exists.', array('@id' => $id)));

    // Get server-rendered contextual links.
    // @see \Drupal\contextual\Tests\ContextualDynamicContextTest:renderContextualLinks()
    $post = urlencode('ids[0]') . '=' . urlencode($id);
    $response = $this->curlExec(array(
      CURLOPT_URL => url('contextual/render', array('absolute' => TRUE, 'query' => array('destination' => 'test-page'))),
      CURLOPT_POST => TRUE,
      CURLOPT_POSTFIELDS => $post,
      CURLOPT_HTTPHEADER => array(
        'Accept: application/json',
        'Content-Type: application/x-www-form-urlencoded',
      ),
    ));
    $this->assertResponse(200);
    $json = drupal_json_decode($response);
    $this->assertIdentical($json[$id], '

id() . '?destination=test-page">Configure block

Edit menu

');
  }

  /**
   * Tests menu link bundles.
   */
  public function testMenuBundles() {
    $this->drupalLogin($this->big_user);
    $menu = $this->addCustomMenu();
    // Clear the entity info cache to ensure the static caches are rebuilt.
    entity_info_cache_clear();
    $bundles = entity_get_bundles('menu_link');
    $this->assertTrue(isset($bundles[$menu->id()]));
    $menus = menu_list_system_menus();
    $menus[$menu->id()] = $menu->label();
    ksort($menus);
    $this->assertIdentical(array_keys($bundles), array_keys($menus));

    // Test if moving a menu link between menus changes the bundle.
    $node = $this->drupalCreateNode(array('type' => 'article'));
    $item = $this->addMenuLink(0, 'node/' . $node->id(), 'tools');
    $this->moveMenuLink($item, 0, $menu->id());
    $this->assertEqual($item->bundle(), 'tools', 'Menu link bundle matches the menu');

    $moved_item = entity_load('menu_link', $item->id(), TRUE);
    $this->assertNotEqual($moved_item->bundle(), $item->bundle(), 'Menu link bundle was changed');
    $this->assertEqual($moved_item->bundle(), $menu->id(), 'Menu link bundle matches the menu');

    $unsaved_item = entity_create('menu_link', array('menu_name' => $menu->id(), 'link_title' => $this->randomName(16), 'link_path' => '<front>'));
    $this->assertEqual($unsaved_item->bundle(), $menu->id(), 'Unsaved menu link bundle matches the menu');
    $this->assertEqual($unsaved_item->menu_name, $menu->id(), 'Unsaved menu link menu name matches the menu');

  }

  /**
   * Add a menu link using the menu module UI.
   *
   * @param integer $plid Parent menu link id.
   * @param string $link Link path.
   * @param string $menu_name Menu name.
   * @param string $weight Menu weight
   *
   * @return \Drupal\menu_link\Plugin\Core\Entity\MenuLink $menu_link
   *   A menu link entity.
   */
  function addMenuLink($plid = 0, $link = '<front>', $menu_name = 'tools', $expanded = TRUE, $weight = '0') {
    // View add menu link page.
    $this->drupalGet("admin/structure/menu/manage/$menu_name/add");
    $this->assertResponse(200);

    $title = '!link_' . $this->randomName(16);
    $edit = array(
      'link_path' => $link,
      'link_title' => $title,
      'description' => '',
      'enabled' => TRUE, // Use this to disable the menu and test.
      'expanded' => $expanded, // Setting this to true should test whether it works when we do the std_user tests.
      'parent' =>  $menu_name . ':' . $plid,
      'weight' => $weight,
    );

    // Add menu link.
    $this->drupalPost(NULL, $edit, t('Save'));
    $this->assertResponse(200);
    $this->assertText('The menu link has been saved.');

    $menu_links = entity_load_multiple_by_properties('menu_link', array('link_title' => $title));
    $menu_link = reset($menu_links);
    $this->assertTrue($menu_link, 'Menu link was found in database.');
    $this->assertMenuLink($menu_link->id(), array('menu_name' => $menu_name, 'link_path' => $link, 'has_children' => 0, 'plid' => $plid));

    return $menu_link;
  }

  /**
   * Attempt to add menu link with invalid path or no access permission.
   *
   * @param string $menu_name Menu name.
   */
  function addInvalidMenuLink($menu_name = 'tools') {
    foreach (array('-&-', 'admin/people/permissions', '#') as $link_path) {
      $edit = array(
        'link_path' => $link_path,
        'link_title' => 'title',
      );
      $this->drupalPost("admin/structure/menu/manage/$menu_name/add", $edit, t('Save'));
      $this->assertRaw(t("The path '@path' is either invalid or you do not have access to it.", array('@path' => $link_path)), 'Menu link was not created');
    }
  }

  /**
   * Verify a menu link using the menu module UI.
   *
   * @param array $item Menu link.
   * @param object $item_node Menu link content node.
   * @param array $parent Parent menu link.
   * @param object $parent_node Parent menu link content node.
   */
  function verifyMenuLink($item, $item_node, $parent = NULL, $parent_node = NULL) {
    // View home page.
    $this->drupalGet('');
    $this->assertResponse(200);

    // Verify parent menu link.
    if (isset($parent)) {
      // Verify menu link.
      $title = $parent['link_title'];
      $this->assertLink($title, 0, 'Parent menu link was displayed');

      // Verify menu link link.
      $this->clickLink($title);
      $title = $parent_node->label();
      $this->assertTitle(t("@title | Drupal", array('@title' => $title)), 'Parent menu link link target was correct');
    }

    // Verify menu link.
    $title = $item['link_title'];
    $this->assertLink($title, 0, 'Menu link was displayed');

    // Verify menu link link.
    $this->clickLink($title);
    $title = $item_node->label();
    $this->assertTitle(t("@title | Drupal", array('@title' => $title)), 'Menu link link target was correct');
  }

  /**
   * Change the parent of a menu link using the menu module UI.
   */
  function moveMenuLink($item, $plid, $menu_name) {
    $mlid = $item['mlid'];

    $edit = array(
      'parent' => $menu_name . ':' . $plid,
    );
    $this->drupalPost("admin/structure/menu/item/$mlid/edit", $edit, t('Save'));
    $this->assertResponse(200);
  }

  /**
   * Modify a menu link using the menu module UI.
   *
   * @param array $item Menu link passed by reference.
   */
  function modifyMenuLink(&$item) {
    $item['link_title'] = $this->randomName(16);

    $mlid = $item['mlid'];
    $title = $item['link_title'];

    // Edit menu link.
    $edit = array();
    $edit['link_title'] = $title;
    $this->drupalPost("admin/structure/menu/item/$mlid/edit", $edit, t('Save'));
    $this->assertResponse(200);
    $this->assertText('The menu link has been saved.');
    // Verify menu link.
    $this->drupalGet('admin/structure/menu/manage/' . $item['menu_name']);
    $this->assertText($title, 'Menu link was edited');
  }

  /**
   * Reset a standard menu link using the menu module UI.
   *
   * @param array $item Menu link.
   * @param string $old_title Original title for menu link.
   */
  function resetMenuLink($item, $old_title) {
    $mlid = $item['mlid'];
    $title = $item['link_title'];

    // Reset menu link.
    $this->drupalPost("admin/structure/menu/item/$mlid/reset", array(), t('Reset'));
    $this->assertResponse(200);
    $this->assertRaw(t('The menu link was reset to its default settings.'), 'Menu link was reset');

    // Verify menu link.
    $this->drupalGet('');
    $this->assertNoText($title, 'Menu link was reset');
    $this->assertText($old_title, 'Menu link was reset');
  }

  /**
   * Delete a menu link using the menu module UI.
   *
   * @param array $item Menu link.
   */
  function deleteMenuLink($item) {
    $mlid = $item['mlid'];
    $title = $item['link_title'];

    // Delete menu link.
    $this->drupalPost("admin/structure/menu/item/$mlid/delete", array(), t('Confirm'));
    $this->assertResponse(200);
    $this->assertRaw(t('The menu link %title has been deleted.', array('%title' => $title)), 'Menu link was deleted');

    // Verify deletion.
    $this->drupalGet('');
    $this->assertNoText($title, 'Menu link was deleted');
  }

  /**
   * Alternately disable and enable a menu link.
   *
   * @param $item
   *   Menu link.
   */
  function toggleMenuLink($item) {
    $this->disableMenuLink($item);

    // Verify menu link is absent.
    $this->drupalGet('');
    $this->assertNoText($item['link_title'], 'Menu link was not displayed');
    $this->enableMenuLink($item);

    // Verify menu link is displayed.
    $this->drupalGet('');
    $this->assertText($item['link_title'], 'Menu link was displayed');
  }

  /**
   * Disable a menu link.
   *
   * @param $item
   *   Menu link.
   */
  function disableMenuLink($item) {
    $mlid = $item['mlid'];
    $edit['enabled'] = FALSE;
    $this->drupalPost("admin/structure/menu/item/$mlid/edit", $edit, t('Save'));

    // Unlike most other modules, there is no confirmation message displayed.
    // Verify in the database.
    $this->assertMenuLink($mlid, array('hidden' => 1));
  }

  /**
   * Enable a menu link.
   *
   * @param $item
   *   Menu link.
   */
  function enableMenuLink($item) {
    $mlid = $item['mlid'];
    $edit['enabled'] = TRUE;
    $this->drupalPost("admin/structure/menu/item/$mlid/edit", $edit, t('Save'));

    // Verify in the database.
    $this->assertMenuLink($mlid, array('hidden' => 0));
  }

  /**
   * Test administrative users other than user 1 can access the menu parents AJAX callback.
   */
  public function testMenuParentsJsAccess() {

    $admin = $this->drupalCreateUser(array('administer menu'));
    $this->drupalLogin($admin);
    // Just check access to the callback overall, the POST data is irrelevant.
    $this->drupalGetAJAX('admin/structure/menu/parents');
    $this->assertResponse(200);

    // Do standard user tests.
    // Login the user.
    $this->drupalLogin($this->std_user);
    $this->drupalGetAJAX('admin/structure/menu/parents');
    $this->assertResponse(403);
  }

  /**
   * Get standard menu link.
   */
  private function getStandardMenuLink() {
    $mlid = 0;
    // Retrieve menu link id of the Log out menu link, which will always be on
    // the front page.
    $query = \Drupal::entityQuery('menu_link')
      ->condition('module', 'system')
      ->condition('router_path', 'user/logout');
    $result = $query->execute();
    if (!empty($result)) {
      $mlid = reset($result);
    }

    $this->assertTrue($mlid > 0, 'Standard menu link id was found');
    // Load menu link.
    // Use api function so that link is translated for rendering.
    $item = entity_load('menu_link', $mlid);
    $this->assertTrue((bool) $item, 'Standard menu link was loaded');
    return $item;
  }

  /**
   * Verify the logged in user has the desired access to the various menu nodes.
   *
   * @param integer $response HTTP response code.
   */
  private function verifyAccess($response = 200, $menu_name = 'tools') {
    // View menu help node.
    $this->drupalGet('admin/help/menu');
    $this->assertResponse($response);
    if ($response == 200) {
      $this->assertText(t('Menu'), 'Menu help was displayed');
    }

    // View menu build overview node.
    $this->drupalGet('admin/structure/menu');
    $this->assertResponse($response);
    if ($response == 200) {
      $this->assertText(t('Menus'), 'Menu build overview node was displayed');
    }

    // View tools menu customization node.
    $this->drupalGet('admin/structure/menu/manage/' . $menu_name);
        $this->assertResponse($response);
    if ($response == 200) {
      $this->assertText(t('Tools'), 'Tools menu node was displayed');
    }

    // View menu edit node.
    $item = $this->getStandardMenuLink();
    $this->drupalGet('admin/structure/menu/item/' . $item['mlid'] . '/edit');
    $this->assertResponse($response);
    if ($response == 200) {
      $this->assertText(t('Edit menu item'), 'Menu edit node was displayed');
    }

    // View menu settings node.
    $this->drupalGet('admin/structure/menu/settings');
    $this->assertResponse($response);
    if ($response == 200) {
      $this->assertText(t('Menus'), 'Menu settings node was displayed');
    }

    // View add menu node.
    $this->drupalGet('admin/structure/menu/add');
    $this->assertResponse($response);
    if ($response == 200) {
      $this->assertText(t('Menus'), 'Add menu node was displayed');
    }
  }
}


text:
package cruise.ui.jsf.templates.impl.fragment.get;

import cruise.model.abstractObjects.IGenerator;

import java.util.*;
import cruise.umple.compiler.Attribute;
import cruise.ui.jsf.*;;

public class SetteableTimeGet implements IGenerator {

  protected static String nl;
  public static synchronized SetteableTimeGet create(String lineSeparator)
  {
    nl = lineSeparator;
    SetteableTimeGet result = new SetteableTimeGet();
    nl = null;
    return result;
  }

  public final String NL = nl == null ? (System.getProperties().getProperty("line.separator")) : nl;
  protected final String TEXT_1 = "\t";
  protected final String TEXT_2 = NL + "\t\tpublic int get";
  protected final String TEXT_3 = "() {" + NL + "\t\t\treturn ";
  protected final String TEXT_4 = ";" + NL + "\t\t}" + NL + "\t\tpublic int get";
  protected final String TEXT_5 = "() {" + NL + "\t\t\treturn ";
  protected final String TEXT_6 = ";" + NL + "\t\t}" + NL + "\t\tpublic Time get";
  protected final String TEXT_7 = "() {" + NL + "\t\t\treturn ";
  protected final String TEXT_8 = ".components.bean.TimeBean.getSqlTime(";
  protected final String TEXT_9 = ", ";
  protected final String TEXT_10 = ");" + NL + "\t\t}\t\t" + NL + "" + NL + "\t\tpublic ";
  protected final String TEXT_11 = " getInitial";
  protected final String TEXT_12 = "() {" + NL + "\t\t\t";
  protected final String TEXT_13 = NL + "\t\t\ttry{" + NL + "\t\t\t \treturn java.sql.Time.valueOf( ";
  protected final String TEXT_14 = " );" + NL + "\t\t\t}catch(Exception e){" + NL + "\t\t\t\t\treturn null;" + NL + "\t\t\t}" + NL + "\t\t\t";
  protected final String TEXT_15 = NL + "\t\t    \treturn null;" + NL + "\t\t    ";
  protected final String TEXT_16 = NL + "\t\t}" + NL + "\t\t" + NL + "\t\tpublic int getInitial";
  protected final String TEXT_17 = "Minute() {" + NL + "\t\t\tTime time=getInitial";
  protected final String TEXT_18 = "();" + NL + "\t\t\tif (time!=null){" + NL + "\t\t\t\tCalendar cal=Calendar.getInstance();" + NL + "\t\t    \tcal.setTime(time);" + NL + "   \t\t\t\treturn cal.get(Calendar.MINUTE); " + NL + "\t\t      }" + NL + "\t\t    \treturn 0;" + NL + "\t\t}" + NL + "\t\t    " + NL + "\t\tpublic int getInitial";
  protected final String TEXT_19 = "Hour() {" + NL + "\t\t\tTime time=getInitial";
  protected final String TEXT_20 = "();" + NL + "\t\t\tif (time!=null){" + NL + "\t\t\t\tCalendar cal=Calendar.getInstance();" + NL + "\t\t    \tcal.setTime(time);" + NL + "   \t\t\t\treturn cal.get(Calendar.HOUR_OF_DAY);" + NL + "\t\t      }" + NL + "\t\t    \treturn 0;" + NL + "\t\t}" + NL + "\t\t  " + NL + "\t\t";
  protected final String TEXT_21 = NL;

	public String generate(Object argument)
  {
    final StringBuffer stringBuffer = new StringBuffer();
     Attribute attVar = (Attribute) argument;
    stringBuffer.append(TEXT_1);
    	String preffix=JSFProvider.properties.getProperty(cruise.model.Constants.PACKAGE_PREFIX);
    stringBuffer.append(TEXT_2);
    stringBuffer.append( attVar.getUpperCaseName()+"Minute");
    stringBuffer.append(TEXT_3);
    stringBuffer.append("a"+ attVar.getUpperCaseName()+"Minute");
    stringBuffer.append(TEXT_4);
    stringBuffer.append( attVar.getUpperCaseName()+"Hour");
    stringBuffer.append(TEXT_5);
    stringBuffer.append("a"+ attVar.getUpperCaseName()+"Hour");
    stringBuffer.append(TEXT_6);
    stringBuffer.append( attVar.getUpperCaseName()+"");
    stringBuffer.append(TEXT_7);
    stringBuffer.append(preffix);
    stringBuffer.append(TEXT_8);
    stringBuffer.append( "a"+attVar.getUpperCaseName()+"Hour");
    stringBuffer.append(TEXT_9);
    stringBuffer.append( "a"+attVar.getUpperCaseName()+"Minute");
    stringBuffer.append(TEXT_10);
    stringBuffer.append( attVar.getType());
    stringBuffer.append(TEXT_11);
    stringBuffer.append( attVar.getUpperCaseName());
    stringBuffer.append(TEXT_12);
     if (attVar.getValue()!=null){
    stringBuffer.append(TEXT_13);
    stringBuffer.append( attVar.getValue() );
    stringBuffer.append(TEXT_14);
     }  else{
    stringBuffer.append(TEXT_15);
     }
    stringBuffer.append(TEXT_16);
    stringBuffer.append( attVar.getUpperCaseName());
    stringBuffer.append(TEXT_17);
    stringBuffer.append( attVar.getUpperCaseName());
    stringBuffer.append(TEXT_18);
    stringBuffer.append( attVar.getUpperCaseName());
    stringBuffer.append(TEXT_19);
    stringBuffer.append( attVar.getUpperCaseName());
    stringBuffer.append(TEXT_20);
    stringBuffer.append(TEXT_21);
    return stringBuffer.toString();
  }
}

redpajama_set_name: RedPajamaGithub


text:
![build](https://travis-ci.org/granturing/spark-power-bi.svg)

# This is no longer being maintained
Please see Azure Databricks for the latest [instructions](https://docs.azuredatabricks.net/user-guide/clusters/power-bi.html) on using Apache Spark with Power BI

# spark-power-bi
A library for pushing data from Spark, SparkSQL, or Spark Streaming to [Power BI](https://powerbi.com/).

## Requirements
This library is supported on Apache Spark 1.4 and 1.5. The versions of the library match to the Spark version. So v1.4.0_0.0.7 is for Apache Spark 1.4 and v1.5.0_0.0.7 is for Apache Spark 1.5.

## Power BI API
Additional details regarding the Power BI API are available in the [developer center](https://msdn.microsoft.com/en-us/library/dn877544.aspx). Authentication is handled via OAuth2 with your Azure AD credentials specified via Spark properties. More details on registering an app and authenticating are available in the Power BI dev center. When pushing rows to Power BI the library will create the target dataset with table if necessary. The current Power BI service is limited to 10,000 rows per call so the library handles batching internally. The service also limits to no more than 5 concurrent calls at a time when adding rows. This is handled by the library using coalesce and can be tuned by with the `spark.powerbi.max_partitions` property.

## Scaladoc
Scaladoc is available [here](http://granturing.github.io/spark-power-bi/docs)

## Configuration
A few of the key properties are related to OAuth2. These depend on your application's registration in Azure AD.
```
spark.powerbi.username
spark.powerbi.password
spark.powerbi.clientid
```

Rather than using your personal AD credentials for publishing data, you may want to create a service account instead. Then you can logon to Power BI using that account and share the data sets and dashboards with other users in your organization. Unfortunately, there's currently no other way of authenticating to Power BI. Hopefully in the future there'll be an organization-level API token that can publish shared data sets, without having to use an actual AD account. You can also use a Power BI group when publishing data.

### Setting Up Azure Active Directory
You'll need to create an application within your Azure AD in order to have a client id to publish data sets.

1. Using the Azure management portal, open up your directory and add a new Application (under the Apps tab)
2. Select "Add an application my organization is developing"
![step0](http://granturing.github.io/spark-power-bi/images/AD_Setup_0.png)
3. Enter any name you want and select "Native Client Application"
![step1](http://granturing.github.io/spark-power-bi/images/AD_Setup_1.png)
4. Enter a redirect URI, this can be anything since it won't be used
![step2](http://granturing.github.io/spark-power-bi/images/AD_Setup_2.png)
5. Once the app has been added you need to grant permissions, click "Add application"
![step3](http://granturing.github.io/spark-power-bi/images/AD_Setup_3.png)
6. Select the "Power BI Service"
![step4](http://granturing.github.io/spark-power-bi/images/AD_Setup_4.png)
7. Add all 3 of the delegated permissions
![step5](http://granturing.github.io/spark-power-bi/images/AD_Setup_5.png)
8. Save your changes and use the newly assigned client id for the `spark.powerbi.clientid` property
![step6](http://granturing.github.io/spark-power-bi/images/AD_Setup_6.png)

## Spark Core
```
import com.granturing.spark.powerbi._

case class Person(name: String, age: Int)

val input = sc.textFile("examples/src/main/resources/people.txt")
val people = input.map(_.split(",")).map(l => Person(l(0), l(1).trim.toInt))

people.saveToPowerBI("Test", "People")
```

## SparkSQL
```
import com.granturing.spark.powerbi._
import org.apache.spark.sql._

val sqlCtx = new SQLContext(sc)
val people = sqlCtx.jsonFile("examples/src/main/resources/people.json")

people.write.format("com.granturing.spark.powerbi").options(Map("dataset" -> "Test", "table" -> "People")).save
```

## Spark Streaming
```
val sc = new SparkContext(new SparkConf())
val ssc = new StreamingContext(sc, Seconds(5))

val filters = args

val input = TwitterUtils.createStream(ssc, None, filters)

val tweets = input.map(t => Tweet(t.getId, t.getCreatedAt, t.getText, t.getUser.getScreenName))
val hashTags = input.flatMap(t => t.getHashtagEntities.map(h => HashTag(t.getId, h.getText, t.getUser.getScreenName)))

tweets.saveToPowerBI(dataset, "Tweets")
hashTags.saveToPowerBI(dataset, "HashTags")

ssc.start()
ssc.awaitTermination()
```

## Referencing As A Dependency
You can also easily reference dependencies using the `--packages` argument:
```bash
spark-shell --package com.granturing:spark-power-bi_2.10:1.5.0_0.0.7
```

## Building From Source
The library uses SBT and can be built by running ```sbt package```.


text:
namespace boost {

namespace units {

/// derived dimension for conductance : L^-2 M^-1 T^3 I^2
typedef derived_dimension<length_base_dimension,-2,
                          mass_base_dimension,-1,
                          time_base_dimension,3,
                          current_base_dimension,2>::type conductance_dimension;

} // namespace units

} // namespace boost

#endif // BOOST_UNITS_CONDUCTANCE_DERIVED_DIMENSION_HPP


text:
<head>
<link rel="stylesheet" type="text/css" href="http://snipplicious.com/css/bootstrap-3.1.1.min.css">

<link rel="stylesheet" type="text/css" href="http://snipplicious.com/css/font-awesome-4.0.3.min.css">
<style>
    .forum.table > tbody > tr > td {
        vertical-align: middle;
    }

    .forum .fa {
        width: 1em;
        text-align: center;
    }

    .forum.table th.cell-stat {
        width: 6em;
    }

    .forum.table th.cell-stat-2x {
        width: 14em;
    }

</style>
<script src="http://snipplicious.com/js/jquery.js"></script>
<script src="http://snipplicious.com/js/bootstrap.min.js"></script>
</head>


text:
git checkout -b gh-pages
git commit -am "init"
git push origin gh-pages
git checkout master
git push origin `git subtree split --prefix example gh-pages`:gh-pages --force

# every push

git subtree push --prefix example origin gh-pages


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.github.pojomvcc</groupId>
    <artifactId>pojo-mvcc</artifactId>
    <version>1.0-RC2-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>pojo-mvcc</name>
    <description>A simple in-memory POJO Multi Version Concurrency Control (MVCC) cache.</description>
    <url>https://github.com/pojomvcc/pojomvcc.git</url>

    <licenses>
        <license>
            <name>The Apache Software License, Version 2.0</name>
            <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
            <distribution>repo</distribution>
            <comments>A business-friendly OSS license</comments>
        </license>
    </licenses>

    <developers>
        <developer>
            <name>Aidan Morgan</name>
            <url>http://au.linkedin.com/pub/aidan-morgan/2/5b4/928/</url>
        </developer>
        <developer>
            <name>Michael Fazio</name>
            <url>http://au.linkedin.com/pub/michael-fazio/b/b20/a23/</url>
        </developer>
    </developers>

    <properties>
        <gpg.passphrase />
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <scm>
        <connection>scm:git:git://github.com/pojomvcc/pojomvcc.git</connection>
        <developerConnection>scm:git:git@github.com:pojomvcc/pojomvcc.git</developerConnection>
        <url>http://github.com/pojomvcc/pojomvcc</url>
        <tag>pojo-mvcc-1.0-RC1</tag>
    </scm>

    <distributionManagement>
        <snapshotRepository>
            <id>sonatype-nexus-snapshots</id>
            <name>Sonatype Nexus snapshot repository</name>
            <url>https://oss.sonatype.org/content/repositories/snapshots</url>
        </snapshotRepository>
        <repository>
            <id>sonatype-nexus-staging</id>
            <name>Sonatype Nexus release repository</name>
            <url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
        </repository>
    </distributionManagement>

    <profiles>
        <profile>
            <id>release-sign-artifacts</id>
            <activation>
                <property>
                    <name>performRelease</name>
                    <value>true</value>
                </property>
            </activation>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-gpg-plugin</artifactId>
                        <version>1.4</version>
                        <configuration>
                            <passphrase>${gpg.passphrase}</passphrase>
                        </configuration>
                        <executions>
                            <execution>
                                <id>sign-artifacts</id>
                                <phase>verify</phase>
                                <goals>
                                    <goal>sign</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-source-plugin</artifactId>
                        <executions>
                            <execution>
                                <id>attach-sources</id>
                                <goals>
                                    <goal>jar</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-javadoc-plugin</artifactId>
                        <executions>
                            <execution>
                                <id>attach-javadocs</id>
                                <goals>
                                    <goal>jar</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>


text:
package com.guanglian.question.params;

import com.guanglian.question.enums.QuestionCategory;
import com.guanglian.question.enums.QuestionType;
import com.guanglian.question.model.Question;

public class QuestionParameter {
    private Integer questionId;
    private Integer workId;
    private QuestionType questionType;
    private QuestionCategory questionCategory;
    private String questionContent;
    private Integer start;
    private Integer end;
    private Integer adminId;
    private String adminName;

    public String getAdminName() { return adminName; }
    public void setAdminName(String adminName) { this.adminName = adminName; }
    public QuestionParameter() {}
    public QuestionParameter(Integer workId, QuestionType questionType, QuestionCategory questionCategory, String questionContent, Integer start, Integer end, Integer adminId) {
        this.workId = workId;
        this.questionType = questionType;
        this.questionCategory = questionCategory;
        this.questionContent = questionContent;
        this.start = start;
        this.end = end;
        this.adminId = adminId;
    }

    public QuestionParameter(Question question, Integer start, Integer end) {
        this.workId = question.getWorkId();
        this.adminId = question.getAdminId();
        this.questionId = question.getQuestionId();
        this.questionType = question.getQuestionType();
        this.questionCategory = question.getQuestionCategory();
        this.questionContent = question.getQuestionContent();
        this.start = start;
        this.end = end;
    }
    public Integer getQuestionId() {
        return questionId;
    }

    public void setQuestionId(Integer questionId) {
        this.questionId = questionId;
    }

    public Integer getWorkId() {
        return workId;
    }

    public void setWorkId(Integer workId) {
        this.workId = workId;
    }

    public QuestionType getQuestionType() {
        return questionType;
    }

    public void setQuestionType(QuestionType questionType) {
        this.questionType = questionType;
    }

    public QuestionCategory getQuestionCategory() {
        return questionCategory;
    }

    public void setQuestionCategory(QuestionCategory questionCategory) {
        this.questionCategory = questionCategory;
    }

    public String getQuestionContent() {
        return questionContent;
    }

    public void setQuestionContent(String questionContent) {
        this.questionContent = questionContent;
    }

    public Integer getStart() {
        return start;
    }

    public void setStart(Integer start) {
        this.start = start;
    }

    public Integer getEnd() {
        return end;
    }

    public void setEnd(Integer end) {
        this.end = end;
    }

    public Integer getAdminId() {
        return adminId;
    }

    public void setAdminId(Integer adminId) {
        this.adminId = adminId;
    }
}


text:
@implementation NSString (Shoulda)

- (void) shouldBeEqualToString:(NSString *)expected withDescription:(NSString *)reason;
{
	[self runTestCase:(TestBlock)^{
		return [self isEqualToString:expected];
	} withDescription:(ExpressionBlock)^{
		return [NSString stringWithFormat:@"'%@' should be equal to '%@'", self, expected];
	} andReason:reason];
}

- (void) shouldNotBeEqualToString:(NSString *)notExpected withDescription:(NSString *)reason;
{
	[self runTestCase:(TestBlock)^{
		return ![self isEqualToString:notExpected];
	} withDescription:(ExpressionBlock)^{
		return [NSString stringWithFormat:@"'%@' should NOT be equal to '%@'", self, notExpected];
	} andReason:reason];
}

- (void) shouldBeEqualToCString:(char *)expected withDescription:(NSString *)reason;
{
	[[NSException exceptionWithName:@"Not Yet implemented" reason:@"Fix Me!" userInfo:nil] raise];
}

- (void) shouldNotBeEqualToCString:(char *)notExpected withDescription:(NSString *)reason;
{
	[[NSException exceptionWithName:@"Not Yet implemented" reason:@"Fix Me!" userInfo:nil] raise];
}

@end

@implementation NSString (SimpleShoulda)

- (void) shouldBeEqualToString:(NSString *)expected
{
	[self shouldBeEqualToString:expected withDescription:@""];
}

- (void) shouldNotBeEqualToString:(NSString *)notExpected
{
	[self shouldNotBeEqualToString:notExpected withDescription:@""];
}

- (void) shouldBeEqualToCString:(char *)expected
{
	[self shouldBeEqualToCString:expected withDescription:@""];
}

- (void) shouldNotBeEqualToCString:(char *)notExpected
{
	[self shouldNotBeEqualToCString:notExpected withDescription:@""];
}

@end


text:
import {
    Entity,
    PrimaryGeneratedColumn,
    TableInheritance,
} from "../../../../../src"

@Entity({ name: "issueNote" })
@TableInheritance({ column: { type: String, name: "type" } })
export class Note {
    @PrimaryGeneratedColumn()
    public id: number
}


text:
package helper

import (
	"encoding/json"
	"net/http"
)

func GetResponseJson(object interface{}) (response string, responseCode int) {
	js, err := json.Marshal(object)
	if err != nil {
		return emptyJson(), http.StatusInternalServerError
	}
	return string(js[:]), http.StatusOK
}

func emptyJson() string {
	return "{}"
}

func IsValidRequest(inputArgs ...string) bool {
	for _, inputArg := range inputArgs {
		if len(inputArg) == 0 {
			return false
		}
	}
	return true
}


text:
System.register(['aurelia-framework', 'gooy/aurelia-compiler'], function (_export) {
  'use strict';

  var Container, ViewSlot, transient, Compiler, ElementSelectors;

  var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();

  function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }

  return {
    setters: [function (_aureliaFramework) {
      Container = _aureliaFramework.Container;
      ViewSlot = _aureliaFramework.ViewSlot;
      transient = _aureliaFramework.transient;
    }, function (_gooyAureliaCompiler) {
      Compiler = _gooyAureliaCompiler.Compiler;
    }],
    execute: function () {
      ElementSelectors = (function () {
        function ElementSelectors() {
          _classCallCheck(this, _ElementSelectors);
        }

        var _ElementSelectors = ElementSelectors;

        _createClass(_ElementSelectors, [{
          key: 'init',
          value: function init(container) {
            this.container = container;
            this.element = container.get(Element);
            this.compiler = container.get(Compiler);
          }
        }, {
          key: 'applySelectors',
          value: function applySelectors() {
            var i = undefined,
                l = undefined,
                promise = undefined;

            var behavior = this.element.primaryBehavior;
            var fragment = behavior.originalFragment;

            if (!fragment) throw new Error('no originalFragment found for', this.element);

            var targets = this.element.querySelectorAll('[select]');
            this.unknownTargets = [].slice.call(targets);

            for (i = 0, l = targets.length; i < l; i++) {
              var target = targets[i];
              var selector = target.getAttribute('select');

              var source = fragment.querySelector(selector);

              if (!source) continue;

              this.copyContentAndAttributes(source, target);

              this.unknownTargets = this.unknownTargets.filter(function (el) {
                return el !== target;
              });
            }
          }
        }, {
          key: 'createCompositions',
          value: function createCompositions() {
            var elements = this.element.querySelectorAll('[select]');

            for (var i = 0, l = elements.length; i < l; i++) {
              var el = elements[i];

              var vm = el.getAttribute('view-model');
              var view = el.getAttribute('view');

              if (vm || view) {
                var compose = document.createElement('compose');
                if (vm) compose.setAttribute('view-model', vm);
                if (view) compose.setAttribute('view', view);
                el.appendChild(compose);
              }
            }
          }
        }, {
          key: 'destroyCompositions',
          value: function destroyCompositions() {
            var remove = arguments[0] === undefined ? true : arguments[0];

            var compositions = this.element.querySelectorAll('compose');
            for (var i = 0, l = compositions.length; i < l; i++) {
              var compose = compositions[i];
              compose.innerHTML = '';
              if (remove) compose.parentNode.removeChild(compose);
            }
          }
        }, {
          key: 'copyContentAndAttributes',
          value: function copyContentAndAttributes(source, target) {
            for (var i = 0, l = source.attributes.length; i < l; i++) {
              var attr = source.attributes[i];
              if (attr === 'select') continue;
              target.setAttribute(attr.nodeName, attr.nodeValue);
            }
            target.textContent = source.textContent;
            target.innerHTML = source.innerHTML;
          }
        }]);

        ElementSelectors = transient()(ElementSelectors) || ElementSelectors;
        return ElementSelectors;
      })();

      _export('ElementSelectors', ElementSelectors);
    }
  };
});
//# sourceMappingURL=element-selectors.js.map


text:
package s2a

import (
	"errors"
	"sync"

	s2apb "github.com/google/s2a-go/internal/proto/common_go_proto"
)

// Identity is the interface for S2A identities.
type Identity interface {
	// Name returns the name of the identity.
	Name() string
}

type spiffeID struct {
	spiffeID string
}

func (s *spiffeID) Name() string { return s.spiffeID }

// NewSpiffeID creates a SPIFFE ID from id.
func NewSpiffeID(id string) Identity {
	return &spiffeID{spiffeID: id}
}

type hostname struct {
	hostname string
}

func (h *hostname) Name() string { return h.hostname }

// NewHostname creates a hostname from name.
func NewHostname(name string) Identity {
	return &hostname{hostname: name}
}

type uid struct {
	uid string
}

func (h *uid) Name() string { return h.uid }

// NewUID creates a UID from name.
func NewUID(name string) Identity {
	return &uid{uid: name}
}

// VerificationModeType specifies the mode that S2A must use to verify the peer
// certificate chain.
type VerificationModeType int

// Three types of verification modes.
const (
	Unspecified = iota
	ConnectToGoogle
	Spiffe
)

// ClientOptions contains the client-side options used to establish a secure
// channel using the S2A handshaker service.
type ClientOptions struct {
	// TargetIdentities contains a list of allowed server identities. One of the
	// target identities should match the peer identity in the handshake
	// result; otherwise, the handshake fails.
	TargetIdentities []Identity
	// LocalIdentity is the local identity of the client application. If none is
	// provided, then the S2A will choose the default identity, if one exists.
	LocalIdentity Identity
	// S2AAddress is the address of the S2A.
	S2AAddress string
	// EnsureProcessSessionTickets waits for all session tickets to be sent to
	// S2A before a process completes.
	//
	// This functionality is crucial for processes that complete very soon after
	// using S2A to establish a TLS connection, but it can be ignored for longer
	// lived processes.
	//
	// Usage example:
	//   func main() {
	//     var ensureProcessSessionTickets sync.WaitGroup
	//     clientOpts := &s2a.ClientOptions{
	//       EnsureProcessSessionTickets: &ensureProcessSessionTickets,
	//       // Set other members.
	//     }
	//     creds, _ := s2a.NewClientCreds(clientOpts)
	//     conn, _ := grpc.Dial(serverAddr, grpc.WithTransportCredentials(creds))
	//     defer conn.Close()
	//
	//     // Make RPC call.
	//
	//     // The process terminates right after the RPC call ends.
	//     // ensureProcessSessionTickets can be used to ensure resumption
	//     // tickets are fully processed. If the process is long-lived, using
	//     // ensureProcessSessionTickets is not necessary.
	//     ensureProcessSessionTickets.Wait()
	//   }
	EnsureProcessSessionTickets *sync.WaitGroup
	// DEPRECATED: Should always be set to true.
	//
	// If true, enables the use of S2Av2.
	EnableV2 bool
	// VerificationMode specifies the mode that S2A must use to verify the
	// peer certificate chain.
	VerificationMode VerificationModeType
}

// DefaultClientOptions returns the default client options.
func DefaultClientOptions(s2aAddress string) *ClientOptions {
	return &ClientOptions{
		S2AAddress:       s2aAddress,
		VerificationMode: ConnectToGoogle,
		EnableV2:         true,
	}
}

// ServerOptions contains the server-side options used to establish a secure
// channel using the S2A handshaker service.
type ServerOptions struct {
	// LocalIdentities is the list of local identities that may be assumed by
	// the server. If no local identity is specified, then the S2A chooses a
	// default local identity, if one exists.
	LocalIdentities []Identity
	// S2AAddress is the address of the S2A.
	S2AAddress string
	// DEPRECATED: Should always be set to true.
	//
	// If true, enables the use of S2Av2.
	EnableV2 bool
	// VerificationMode specifies the mode that S2A must use to verify the
	// peer certificate chain.
	VerificationMode VerificationModeType
}

// DefaultServerOptions returns the default server options.
func DefaultServerOptions(s2aAddress string) *ServerOptions {
	return &ServerOptions{
		S2AAddress:       s2aAddress,
		VerificationMode: ConnectToGoogle,
		EnableV2:         true,
	}
}

func toProtoIdentity(identity Identity) (*s2apb.Identity, error) {
	if identity == nil {
		return nil, nil
	}
	switch id := identity.(type) {
	case *spiffeID:
		return &s2apb.Identity{IdentityOneof: &s2apb.Identity_SpiffeId{SpiffeId: id.Name()}}, nil
	case *hostname:
		return &s2apb.Identity{IdentityOneof: &s2apb.Identity_Hostname{Hostname: id.Name()}}, nil
	case *uid:
		return &s2apb.Identity{IdentityOneof: &s2apb.Identity_Uid{Uid: id.Name()}}, nil
	default:
		return nil, errors.New("unrecognized identity type")
	}
}


text:
import re
from user import make_anonymous_user
from exeptions import HttpStatusError, RegexError

def make_subject_url(url):
    if url.endswith("/"):
        return url + "subject.txt"
    else:
        return url + "/subject.txt"

def parse_board(string):
    if not isinstance(string, unicode):
        raise TypeError("unsupported string type:" + str(type(string)))
    thread_expressions = re.compile(
        r"^(?P<dat>\d+\.dat)<>(?P<title>.*) \((?P<n_comments>\d*)\)$")
    results = []
    for thread_string in string.split("\n"):
        thread_data = thread_expressions.search(thread_string)
        if thread_data:
            results.append({
                "title": thread_data.group("title"),
                "n_comments": int(thread_data.group("n_comments")),
                "dat": thread_data.group("dat"),
            })
        elif len(thread_string) != 0:
            raise RegexError(
                "Regex unmatched in parsing the thread's data",
                thread_expressions)
    return results

def retrieve_board(board_url, user=None):
    my_user = user if user else make_anonymous_user()
    subject_url = make_subject_url(board_url)

    response = my_user.urlopen(subject_url, gzip=False)
    if response.code == 200:
        retrieved_string = unicode(response.read(), "Shift_JIS", "ignore")
        print type(retrieved_string)
        return parse_board(retrieved_string)
    else:
        message = "HTTP status is invalid: " + str(response.code)
        raise HttpStatusError(message, response)


text:
@implementation NSObject (MKBlockTimer)

+(void) logTime:(void (^)(void)) block withPrefix:(NSString*) prefixString {

	double a = CFAbsoluteTimeGetCurrent();
	block();
	double b = CFAbsoluteTimeGetCurrent();

	unsigned int m = ((b-a) * 1000.0f); // convert from seconds to milliseconds

    NSString *log = [NSString stringWithFormat:@"%@: %d ms", prefixString ? prefixString : @"Time taken", m ];
	NSLog(@"LOG TIMER: %@", log);
//    POP_ALERT(log);
}

-(void) logTimeMethod:(void (^)(void)) block withPrefix:(NSString*) prefixString {
	[NSObject logTime:block withPrefix:prefixString];
}
@end


text:
<!DOCTYPE html>

    <title>Anna Kournikova</title>


text:
<?php

namespace ChartBlocks\Repository;

class ChartData extends AbstractWriteableRepository {

    public $url = 'chart/data/';
    public $class = '\\ChartBlocks\\Entity\\ChartData';
    public $singleResponseKey = 'data';

}


text:
                    Fintech doesn just disrupt banks, it makes them platforms

                    Uber Offers get merchants to pay for your ride

                    Apple brings in ex-Googler and robotics expert Yoky Matsuoka to work on Healthkit

                    Surging on Taboola: VR Headsets Changing Retail Experience

                    Earny app gets your money back on purchases after prices drop

                    YouTube VP Matt Glotzbach graduates to CEO role at Quizlet

                    Age of Learning, a quiet giant in education apps, raised $150M at a $1B valuation from Iconiq

                    Craig Wright backs out and won prove that he is bitcoin creator Satoshi Nakamoto

                    Club W rebrands as Winc, raises $17.5 million for personalized wine

                    Farfetch grabs another $110 million for its fashion marketplace

        Powered by Reefeed


text:
var _ = require('underscore');
var $ = require('jquery'),
    Backbone = require('backbone'),
    forgotPasswordSuccessTemplate = require('../../assets/templates/forgotPasswordSuccess.tpl');

Backbone.$ = $;

exports = module.exports = Backbone.View.extend({

	el: '#content',

	render: function(){
		this.$el.html(forgotPasswordSuccessTemplate());
		return this;
	}
});


text:
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

import { AuthService } from '../../../services/auth.service';

import { User } from '../../../model/User';

@Component({
	selector: 'registration',
	templateUrl: 'registration.component.html',
	styleUrls: ['./registration.component.css']
})

export class RegistrationComponent {
	users: User[];
	_id: any;
    username: string;
    password: string;
    email: string;
    firstName: string;
    lastName: string;
    country: string;
    city: string;
    address: string;
    postalCode: number;
    creditCardNumber: number;
    userRole: string;

	constructor(private authService: AuthService, public router: Router) {}

	addUser() {
		event.preventDefault();
		var newUser = {
			username: this.username,
			password: this.password,
			email: this.email,
			firstName: this.firstName,
			lastName: this.lastName,
			country: this.country,
			city: this.city,
			address: this.address,
			postalCode: this.postalCode,
			creditCardNumber: this.creditCardNumber,
			userRole: this.userRole
		}
		console.log(newUser);

		this.authService.addUser(newUser).subscribe();
		this.router.navigate(['/login']);

	}
}


text:
var express = require('express');
var app = express();

app.use('/things', express.static(__dirname + '/dist'));

var port = process.env.PORT || 3333;
app.listen(port);

console.log('Express listening on ' + port);


text:
module Backup
  module Configuration
    module Storage
      class CloudFiles < Base
        class << self

          ##
          # Rackspace Cloud Files Credentials
          attr_accessor :api_key, :username

          ##
          # Rackspace Cloud Files container name and path
          attr_accessor :container, :path

        end
      end
    end
  end
end


text:
package org.apache.hadoop.hive.serde2.avro;

import static org.apache.avro.Schema.Type.BOOLEAN;
import static org.apache.avro.Schema.Type.BYTES;
import static org.apache.avro.Schema.Type.DOUBLE;
import static org.apache.avro.Schema.Type.FIXED;
import static org.apache.avro.Schema.Type.FLOAT;
import static org.apache.avro.Schema.Type.INT;
import static org.apache.avro.Schema.Type.LONG;
import static org.apache.avro.Schema.Type.NULL;
import static org.apache.avro.Schema.Type.STRING;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Hashtable;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.avro.Schema;
import org.apache.hadoop.hive.serde2.typeinfo.HiveDecimalUtils;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoFactory;

/**
 * Convert an Avro Schema to a Hive TypeInfo
 */
class SchemaToTypeInfo {
  // Conversion of Avro primitive types to Hive primitive types
  // Avro             Hive
  // Null
  // boolean          boolean    check
  // int              int        check
  // long             bigint     check
  // float            double     check
  // double           double     check
  // bytes            binary     check
  // fixed            binary     check
  // string           string     check
  //                  tinyint
  //                  smallint

  // Map of Avro's primitive types to Hives (for those that are supported by both)
  private static final Map<Schema.Type, TypeInfo> primitiveTypeToTypeInfo = initTypeMap();
  private static Map<Schema.Type, TypeInfo> initTypeMap() {
    Map<Schema.Type, TypeInfo> theMap = new Hashtable<Schema.Type, TypeInfo>();
    theMap.put(NULL, TypeInfoFactory.getPrimitiveTypeInfo("void"));
    theMap.put(BOOLEAN, TypeInfoFactory.getPrimitiveTypeInfo("boolean"));
    theMap.put(INT, TypeInfoFactory.getPrimitiveTypeInfo("int"));
    theMap.put(LONG, TypeInfoFactory.getPrimitiveTypeInfo("bigint"));
    theMap.put(FLOAT, TypeInfoFactory.getPrimitiveTypeInfo("float"));
    theMap.put(DOUBLE, TypeInfoFactory.getPrimitiveTypeInfo("double"));
    theMap.put(BYTES, TypeInfoFactory.getPrimitiveTypeInfo("binary"));
    theMap.put(FIXED, TypeInfoFactory.getPrimitiveTypeInfo("binary"));
    theMap.put(STRING, TypeInfoFactory.getPrimitiveTypeInfo("string"));
    return Collections.unmodifiableMap(theMap);
  }

  /**
   * Generate a list of of TypeInfos from an Avro schema.  This method is
   * currently public due to some weirdness in deserializing unions, but
   * will be made private once that is resolved.
   * @param schema Schema to generate field types for
   * @return List of TypeInfos, each element of which is a TypeInfo derived
   *         from the schema.
   * @throws AvroSerdeException for problems during conversion.
   */
  public static List<TypeInfo> generateColumnTypes(Schema schema) throws AvroSerdeException {
    return generateColumnTypes (schema, null);
  }

  /**
   * Generate a list of of TypeInfos from an Avro schema.  This method is
   * currently public due to some weirdness in deserializing unions, but
   * will be made private once that is resolved.
   * @param schema Schema to generate field types for
   * @param seenSchemas stores schemas processed in the parsing done so far,
   *         helping to resolve circular references in the schema
   * @return List of TypeInfos, each element of which is a TypeInfo derived
   *         from the schema.
   * @throws AvroSerdeException for problems during conversion.
   */
  public static List<TypeInfo> generateColumnTypes(Schema schema,
      Set<Schema> seenSchemas) throws AvroSerdeException {
    List<Schema.Field> fields = schema.getFields();

    List<TypeInfo> types = new ArrayList<TypeInfo>(fields.size());

    for (Schema.Field field : fields) {
      types.add(generateTypeInfo(field.schema(), seenSchemas));
    }

    return types;
  }

  static InstanceCache<Schema, TypeInfo> typeInfoCache = new InstanceCache<Schema, TypeInfo>() {
                                  @Override
                                  protected TypeInfo makeInstance(Schema s,
                                      Set<Schema> seenSchemas)
                                      throws AvroSerdeException {
                                    return generateTypeInfoWorker(s, seenSchemas);
                                  }
                                };
  /**
   * Convert an Avro Schema into an equivalent Hive TypeInfo.
   * @param schema to record. Must be of record type.
   * @param seenSchemas stores schemas processed in the parsing done so far,
   *         helping to resolve circular references in the schema
   * @return TypeInfo matching the Avro schema
   * @throws AvroSerdeException for any problems during conversion.
   */
  public static TypeInfo generateTypeInfo(Schema schema,
      Set<Schema> seenSchemas) throws AvroSerdeException {
    // For bytes type, it can be mapped to decimal.
    Schema.Type type = schema.getType();
    if (type == BYTES && AvroSerDe.DECIMAL_TYPE_NAME
      .equalsIgnoreCase(schema.getProp(AvroSerDe.AVRO_PROP_LOGICAL_TYPE))) {
      int precision = 0;
      int scale = 0;
      try {
        precision = schema.getJsonProp(AvroSerDe.AVRO_PROP_PRECISION).getIntValue();
        scale = schema.getJsonProp(AvroSerDe.AVRO_PROP_SCALE).getIntValue();
      } catch (Exception ex) {
        throw new AvroSerdeException("Failed to obtain scale value from file schema: " + schema, ex);
      }

      try {
        HiveDecimalUtils.validateParameter(precision, scale);
      } catch (Exception ex) {
        throw new AvroSerdeException("Invalid precision or scale for decimal type", ex);
      }

      return TypeInfoFactory.getDecimalTypeInfo(precision, scale);
    }

    if (type == STRING &&
      AvroSerDe.CHAR_TYPE_NAME.equalsIgnoreCase(schema.getProp(AvroSerDe.AVRO_PROP_LOGICAL_TYPE))) {
      int maxLength = 0;
      try {
        maxLength = schema.getJsonProp(AvroSerDe.AVRO_PROP_MAX_LENGTH).getValueAsInt();
      } catch (Exception ex) {
        throw new AvroSerdeException("Failed to obtain maxLength value from file schema: " + schema, ex);
      }
      return TypeInfoFactory.getCharTypeInfo(maxLength);
    }

    if (type == STRING && AvroSerDe.VARCHAR_TYPE_NAME
      .equalsIgnoreCase(schema.getProp(AvroSerDe.AVRO_PROP_LOGICAL_TYPE))) {
      int maxLength = 0;
      try {
        maxLength = schema.getJsonProp(AvroSerDe.AVRO_PROP_MAX_LENGTH).getValueAsInt();
      } catch (Exception ex) {
        throw new AvroSerdeException("Failed to obtain maxLength value from file schema: " + schema, ex);
      }
      return TypeInfoFactory.getVarcharTypeInfo(maxLength);
    }

    if (type == INT &&
      AvroSerDe.DATE_TYPE_NAME.equals(schema.getProp(AvroSerDe.AVRO_PROP_LOGICAL_TYPE))) {
      return TypeInfoFactory.dateTypeInfo;
    }

    if (type == LONG &&
      AvroSerDe.TIMESTAMP_TYPE_NAME.equals(schema.getProp(AvroSerDe.AVRO_PROP_LOGICAL_TYPE))) {
      return TypeInfoFactory.timestampTypeInfo;
    }

    return typeInfoCache.retrieve(schema, seenSchemas);
  }

  private static TypeInfo generateTypeInfoWorker(Schema schema,
      Set<Schema> seenSchemas) throws AvroSerdeException {
    // Avro requires NULLable types to be defined as unions of some type T
    // and NULL.  This is annoying and we're going to hide it from the user.
    if(AvroSerdeUtils.isNullableType(schema)) {
      return generateTypeInfo(
        AvroSerdeUtils.getOtherTypeFromNullableType(schema), seenSchemas);
    }

    Schema.Type type = schema.getType();
    if(primitiveTypeToTypeInfo.containsKey(type)) {
      return primitiveTypeToTypeInfo.get(type);
    }

    switch(type) {
      case RECORD: return generateRecordTypeInfo(schema, seenSchemas);
      case MAP:    return generateMapTypeInfo(schema, seenSchemas);
      case ARRAY:  return generateArrayTypeInfo(schema, seenSchemas);
      case UNION:  return generateUnionTypeInfo(schema, seenSchemas);
      case ENUM:   return generateEnumTypeInfo(schema);
      default:     throw new AvroSerdeException("Do not yet support: " + schema);
    }
  }

  private static TypeInfo generateRecordTypeInfo(Schema schema,
      Set<Schema> seenSchemas) throws AvroSerdeException {
    assert schema.getType().equals(Schema.Type.RECORD);

    if (seenSchemas == null) {
        seenSchemas = Collections.newSetFromMap(new IdentityHashMap<Schema, Boolean>());
    } else if (seenSchemas.contains(schema)) {
      throw new AvroSerdeException(
          "Recursive schemas are not supported. Recursive schema was " + schema
              .getFullName());
    }
    seenSchemas.add(schema);

    List<Schema.Field> fields = schema.getFields();
    List<String> fieldNames = new ArrayList<String>(fields.size());
    List<TypeInfo> typeInfos = new ArrayList<TypeInfo>(fields.size());

    for(int i = 0; i < fields.size(); i++) {
      fieldNames.add(i, fields.get(i).name());
      typeInfos.add(i, generateTypeInfo(fields.get(i).schema(), seenSchemas));
    }

    return TypeInfoFactory.getStructTypeInfo(fieldNames, typeInfos);
  }

  /**
   * Generate a TypeInfo for an Avro Map.  This is made slightly simpler in that
   * Avro only allows maps with strings for keys.
   */
  private static TypeInfo generateMapTypeInfo(Schema schema,
      Set<Schema> seenSchemas) throws AvroSerdeException {
    assert schema.getType().equals(Schema.Type.MAP);
    Schema valueType = schema.getValueType();
    TypeInfo ti = generateTypeInfo(valueType, seenSchemas);

    return TypeInfoFactory.getMapTypeInfo(TypeInfoFactory.getPrimitiveTypeInfo("string"), ti);
  }

  private static TypeInfo generateArrayTypeInfo(Schema schema,
      Set<Schema> seenSchemas) throws AvroSerdeException {
    assert schema.getType().equals(Schema.Type.ARRAY);
    Schema itemsType = schema.getElementType();
    TypeInfo itemsTypeInfo = generateTypeInfo(itemsType, seenSchemas);

    return TypeInfoFactory.getListTypeInfo(itemsTypeInfo);
  }

  private static TypeInfo generateUnionTypeInfo(Schema schema,
      Set<Schema> seenSchemas) throws AvroSerdeException {
    assert schema.getType().equals(Schema.Type.UNION);
    List<Schema> types = schema.getTypes();

    List<TypeInfo> typeInfos = new ArrayList<TypeInfo>(types.size());

    for(Schema type : types) {
      typeInfos.add(generateTypeInfo(type, seenSchemas));
    }

    return TypeInfoFactory.getUnionTypeInfo(typeInfos);
  }

  // Hive doesn't have an Enum type, so we're going to treat them as Strings.
  // During the deserialize/serialize stage we'll check for enumness and
  // convert as such.
  private static TypeInfo generateEnumTypeInfo(Schema schema) {
    assert schema.getType().equals(Schema.Type.ENUM);

    return TypeInfoFactory.getPrimitiveTypeInfo("string");
  }
}


text:
RSpec.describe "A consumer" do
  let(:connection) { MarchHare.connect }
  let(:channel)    { connection.create_channel }

  after :each do
    channel.close
    connection.close
  end

  it "can access message metadata (both message properties and delivery information)" do
    latch    = java.util.concurrent.CountDownLatch.new(1)
    queue    = channel.queue("", :exclusive => true)
    exchange = channel.exchange("amq.fanout", :type => :fanout)

    queue.bind(exchange, :routing_key => "march.hare.key")

    @now     = Time.now
    @payload = "Hello, world!"
    @meta    = nil

    _ = queue.subscribe(:blocking => false) do |metadata, payload|
      begin
        # we will run assertions on the main thread because RSpec uses exceptions
        # for its purposes every once in a while. MK.
        @meta = metadata
      rescue Exception => e
        e.print_stack_trace
      ensure
        latch.count_down
      end
    end

    exchange.publish(@payload,
                     :properties => {
                       :app_id      => "march.hare.tests",
                       :persistent  => true,
                       :priority    => 8,
                       :type        => "kinda.checkin",
                       # headers table keys can be anything
                       :headers     => {
                         :coordinates => {
                           :latitude  => 59.35,
                           "longitude" => 18.066667
                         },
                         "time"         => @now,
                         "participants" => 11,
                         :venue         => "Stockholm",
                         "true_field"   => true,
                         "false_field"  => false,
                         "nil_field"    => nil,
                         "ary_field"    => ["one", 2.0, 3, [{ :abc => 123 }]]
                       },
                       :timestamp        => @now,
                       :reply_to         => "a.sender",
                       :correlation_id   => "r-1",
                       :message_id       => "m-1",
                       :content_type     => "application/octet-stream",
                       # just an example. MK.
                       :content_encoding => "zip/zap"
                     },
                     :routing_key    => "march.hare.key")
    latch.await

    expect(@meta.routing_key).to eq("march.hare.key")
    expect(@meta.content_type).to eq("application/octet-stream")
    expect(@meta.content_encoding).to eq("zip/zap")
    expect(@meta.priority).to eq(8)

    time = Time.at(@meta.headers["time"].getTime/1000)
    expect(time.to_i).to eq(@now.to_i)

    expect(@meta.headers["coordinates"]["latitude"]).to eq(59.35)
    expect(@meta.headers["participants"]).to eq(11)
    expect(@meta.headers["true_field"]).to eq(true)
    expect(@meta.headers["false_field"]).to eq(false)
    expect(@meta.headers["nil_field"]).to be_nil

    expect(@meta.timestamp).to eq(Time.at(@now.to_i))
    expect(@meta.type).to eq("kinda.checkin")
    expect(@meta.consumer_tag).not_to be_nil
    expect(@meta.consumer_tag).not_to be_empty
    expect(@meta.delivery_tag.to_i).to eq(1)
    expect(@meta.delivery_mode).to eq(2)
    expect(@meta).to be_persistent
    expect(@meta.reply_to).to eq("a.sender")
    expect(@meta.correlation_id).to eq("r-1")
    expect(@meta.message_id).to eq("m-1")
    expect(@meta).not_to be_redelivered

    expect(@meta.app_id).to eq("march.hare.tests")
    expect(@meta.exchange).to eq("amq.fanout")
  end

  it "can handle properties being set at the top level" do
    latch    = java.util.concurrent.CountDownLatch.new(1)
    queue    = channel.queue("", :exclusive => true)
    exchange = channel.exchange("amq.fanout", :type => :fanout)

    queue.bind(exchange, :routing_key => "march.hare.key")

    @now     = Time.now
    @payload = "Hello, world!"
    @meta    = nil

    _ = queue.subscribe(:blocking => false) do |metadata, payload|
      begin
        # we will run assertions on the main thread because RSpec uses exceptions
        # for its purposes every once in a while. MK.
        @meta = metadata
      rescue Exception => e
        e.print_stack_trace
      ensure
        latch.count_down
      end
    end

    exchange.publish(@payload,
                     :app_id      => "march.hare.tests",
                     :persistent  => true,
                     :priority    => 8,
                     :type        => "kinda.checkin",
                     # headers table keys can be anything
                     :headers     => {
                       "coordinates" => {
                         "latitude"  => 59.35,
                         "longitude" => 18.066667
                       },
                       "time"         => @now,
                       "participants" => 11,
                       "venue"        => "Stockholm",
                       "true_field"   => true,
                       "false_field"  => false,
                       "nil_field"    => nil,
                       "ary_field"    => ["one", 2.0, 3, [{ "abc" => 123 }]]
                     },
                     :timestamp        => @now,
                     :reply_to         => "a.sender",
                     :correlation_id   => "r-1",
                     :message_id       => "m-1",
                     :content_type     => "application/octet-stream",
                     # just an example. MK.
                     :content_encoding => "zip/zap",
                     :routing_key    => "march.hare.key")
    latch.await

    expect(@meta.routing_key).to eq("march.hare.key")
    expect(@meta.content_type).to eq("application/octet-stream")
    expect(@meta.content_encoding).to eq("zip/zap")
    expect(@meta.priority).to eq(8)

    time = Time.at(@meta.headers["time"].getTime/1000)
    expect(time.to_i).to eq(@now.to_i)

    expect(@meta.headers["coordinates"]["latitude"]).to eq(59.35)
    expect(@meta.headers["participants"]).to eq(11)
    expect(@meta.headers["true_field"]).to eq(true)
    expect(@meta.headers["false_field"]).to eq(false)
    expect(@meta.headers["nil_field"]).to be_nil

    expect(@meta.timestamp).to eq(Time.at(@now.to_i))
    expect(@meta.type).to eq("kinda.checkin")
    expect(@meta.consumer_tag).not_to be_nil
    expect(@meta.consumer_tag).not_to be_empty
    expect(@meta.delivery_tag.to_i).to eq(1)
    expect(@meta.delivery_mode).to eq(2)
    expect(@meta).to be_persistent
    expect(@meta.reply_to).to eq("a.sender")
    expect(@meta.correlation_id).to eq("r-1")
    expect(@meta.message_id).to eq("m-1")
    expect(@meta).not_to be_redelivered

    expect(@meta.app_id).to eq("march.hare.tests")
    expect(@meta.exchange).to eq("amq.fanout")
  end
end


text:
layout:     post
author:     Christoph Broschinski
author_lnk: https://github.com/cbroschinski
title:      TU Dresden reports its 2017 APC expenditures
date:       2018-05-29 08:00:00
summary:
categories: [general, openAPC]
comments: true
---

The [Technische Universität Dresden](https://tu-dresden.de/?set_language=en) has provided its APC expenditures for the 2017 period.

The [Saxon State and University Library Dresden (SLUB)](http://www.slub-dresden.de/en/home/) is in charge of the [Open Access Publication Funds of the TU Dresden](https://www.slub-dresden.de/service/open-science-service/open-access/publikationsfonds/), which receives support by the Deutsche Forschungsgemeinschaft (DFG) under its [Open-Access Publishing Programme](http://www.dfg.de/en/research_funding/programmes/infrastructure/lis/funding_opportunities/open_access/).

Contact person is [Michael Wohlgemuth](mailto:michael.wohlgemuth@slub-dresden.de).

## Cost data

The new dataset covers publication fees for 80 articles. Total expenditure amounts to 116 372€ and the average fee is 1 455€.

The following table shows the payments the SLUB has made to publishers in 2017.

|                                          | Articles| Fees paid in EURO| Mean Fee paid|
|:-----------------------------------------|--------:|-----------------:|-------------:|
|Springer Nature                           |       37|             57389|          1551|
|Frontiers Media SA                        |       10|             16070|          1607|
|MDPI AG                                   |        9|             11241|          1249|
|Public Library of Science (PLoS)          |        5|              7960|          1592|
|Elsevier BV                               |        4|              4818|          1204|
|BioResources                              |        3|              3954|          1318|
|Hindawi Publishing Corporation            |        2|              2925|          1462|
|SAGE Publications                         |        2|              3835|          1918|
|Bentham Science Publishers Ltd.           |        1|               835|           835|
|Copernicus GmbH                           |        1|              1696|          1696|
|EDP Sciences                              |        1|              1071|          1071|
|Kritische Geographie Berlin e.V.          |        1|               400|           400|
|Omics Group                               |        1|               602|           602|
|Ovid Technologies (Wolters Kluwer Health) |        1|              1064|          1064|
|Ubiquity Press, Ltd.                      |        1|              1681|          1681|
|Walter de Gruyter GmbH                    |        1|               833|           833|

## Overview

With the recent contribution included, the overall APC data for the TU Dresden now looks as follows:

### Fees paid per publisher (in EURO)

![plot of chunk tree_dresden_2018_05_29_full](/figure/tree_dresden_2018_05_29_full-1.png)

###  Average costs per year (in EURO)

![plot of chunk box_dresden_2018_05_29_year_full](/figure/box_dresden_2018_05_29_year_full-1.png)

###  Average costs per publisher (in EURO)

![plot of chunk box_dresden_2018_05_29_publisher_full](/figure/box_dresden_2018_05_29_publisher_full-1.png)


text:
from flask import Flask, request, render_template
import os

app = Flask(__name__, static_url_path='/static')

# Determine our running port.  Updated to support Diego which uses the
# 'PORT' environment variable, vs non-Diego which uses VCAP_APP_PORT

if os.getenv('VCAP_APP_PORT'):
    port = os.getenv('VCAP_APP_PORT')
elif os.getenv('PORT'):
    port = os.getenv('PORT')
else:
    port = "8080"

def getName():
	return "Philadelphia, PA"

@app.route('/')
def index_page():
    return render_template('index.tmpl',Name=getName())

if __name__ == '__main__':
    app.debug = True
    print "Running on Port: " + port
    app.run(host='0.0.0.0', port=int(port))


text:
using System;
using System.Windows.Data;

namespace Maple
{
    /// <summary>
    ///
    /// </summary>
    /// <seealso cref="System.Windows.Data.IValueConverter" />
    [ValueConversion(typeof(object), typeof(bool))]
    public class RadioButtonCheckedConverter : ConverterMarkupExtension<RadioButtonCheckedConverter>, IValueConverter
    {
        /// <summary>
        /// Converts a value.
        /// </summary>
        /// <param name="value">The value produced by the binding source.</param>
        /// <param name="targetType">The type of the binding target property.</param>
        /// <param name="parameter">The converter parameter to use.</param>
        /// <param name="culture">The culture to use in the converter.</param>
        /// <returns>
        /// A converted value. If the method returns null, the valid null value is used.
        /// </returns>
        public override object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return value.Equals(parameter);
        }

        /// <summary>
        /// Converts a value.
        /// </summary>
        /// <param name="value">The value that is produced by the binding target.</param>
        /// <param name="targetType">The type to convert to.</param>
        /// <param name="parameter">The converter parameter to use.</param>
        /// <param name="culture">The culture to use in the converter.</param>
        /// <returns>
        /// A converted value. If the method returns null, the valid null value is used.
        /// </returns>
        public override object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return value.Equals(true) ? parameter : Binding.DoNothing;
        }
    }
}


text:
var wordwrap = require('wordwrap')
var inquirer = require('inquirer')
var minimist = require('minimist')
var opener   = require('opener')
var chalk    = require('chalk')

console.error()
console.error(chalk.yellow(' =============================='))
console.error(chalk.yellow(' = ~~~~~ ')+'webgl-workshop'+chalk.yellow(' ~~~~~ ='))
console.error(chalk.yellow(' =============================='))
console.error()

var argv = minimist(process.argv.slice(2), {
    boolean: ['o', 'y']
  , default: { o: true }
  , alias: {
      o: 'open'
    , y: 'yes'
  }
})

if (argv.yes) {
  boot()
} else {
  prompt()
}

function prompt() {
  inquirer.prompt([{
      'type': 'confirm'
    , 'name': 'ok'
    , 'default': true
    , 'message': wordwrap(4, 80)(
      "We're about to populate this directory with some code for you to " +
      "use for your answers. If they've already been created then don't worry, " +
      "they won't be replaced. Continue?"
    ).replace(/^\s+/, '')
  }], function(result) {
    if (!result.ok) return process.exit(1)

    console.error()
    boot()
  })
}

function boot() {
  require('@workshop/server')({}, function(err, address) {
    if (err) throw err

    if (argv.open) {
      console.error('Done! Booting up the workshop in your browser in just a second...')
    }

    console.error('Workshop running on: '+chalk.blue(address))
    console.error()

    if (argv.open) {
      setTimeout(function() {
        opener(address)
      }, 1000)
    }
  })
}


text:
"""Get event logs relating to security groups"""
# :license: MIT, see LICENSE for more details.

import json

import click

import SoftLayer
from SoftLayer.CLI import environment
from SoftLayer.CLI import formatting

COLUMNS = ['event', 'label', 'date', 'metadata']

@click.command()
@click.argument('request_id')
@environment.pass_env
def get_by_request_id(env, request_id):
    """Search for event logs by request id"""
    mgr = SoftLayer.NetworkManager(env.client)

    logs = mgr.get_event_logs_by_request_id(request_id)

    table = formatting.Table(COLUMNS)
    table.align['metadata'] = "l"

    for log in logs:
        metadata = json.dumps(json.loads(log['metaData']), indent=4, sort_keys=True)

        table.add_row([log['eventName'], log['label'], log['eventCreateDate'], metadata])

    env.fout(table)


text:
module BF
  class Interpreter

    attr_reader :program

    def initialize(program)
      @program = Program.new(instructions: load_program(program))
    end

    def execute
      #binding.pry
      #puts "Executing program:\n #{program.instructions}\n\n"

      begin
        loop do
          program.execute_current_command
          break if program.terminated?
          #break if terminated?
        end
      rescue EOFError
        # Finished
      rescue => ex
        #log_status
        #puts ex.message
        #puts ex.backtrace
        #binding.pry
      end

      #puts "Done"
      program.output
    end

    def load_program(program)
      if program.end_with?('bf')
        IO.binread("#{BF::ROOT}/#{program}").strip
      else
        program.strip
      end
    end

    def log_status
      puts "#{program.cmd_ptr}\t#{program.current_command}\t#{program.data_ptr}\t#{program.current_data}\t#{program.data_range(0..30)}"
    end
  end
end


text:
using Chiro.Gap.Poco.Model;
using Chiro.Gap.Test;
using Chiro.Kip.ServiceContracts;
using Chiro.Kip.ServiceContracts.DataContracts;
using NUnit.Framework;
using Moq;
using Persoon = Chiro.Gap.Poco.Model.Persoon;

namespace Chiro.Gap.Sync.Test
{
    /// <summary>
    ///This is a test class for VerzekeringenSyncTest and is intended
    ///to contain all VerzekeringenSyncTest Unit Tests
    ///</summary>
    [TestFixture]
    public class VerzekeringenSyncTest: ChiroTest
    {
        /// <summary>
        /// Kijkt na of verzekeringen loonverlies ook gesynct worden voor personen zonder AD-nummer
        /// (dat AD-nummer is dan waarschijnlijk in aanvraag.)
        /// </summary>
        [Test]
        public void BewarenTest()
        {
            // ARRANGE

            var groepsWerkJaar = new GroepsWerkJaar {Groep = new ChiroGroep()};
            var gelieerdePersoon = new GelieerdePersoon
            {
                Groep = groepsWerkJaar.Groep,
                Persoon = new Persoon
                {
                    AdNummer = null,
                    InSync = true,
                }
            };
            gelieerdePersoon.Persoon.GelieerdePersoon.Add(gelieerdePersoon);
            groepsWerkJaar.Groep.GelieerdePersoon.Add(gelieerdePersoon);

            var persoonsVerzekering = new PersoonsVerzekering
                                          {
                                              Persoon = gelieerdePersoon.Persoon
                                          };

            var kipSyncMock = new Mock<ISyncPersoonService>();
            kipSyncMock.Setup(
                src =>
                src.LoonVerliesVerzekerenAdOnbekend(It.IsAny<PersoonDetails>(), It.IsAny<string>(), It.IsAny<int>(), It.IsAny<bool>())).Verifiable();
            Factory.InstantieRegistreren(kipSyncMock.Object);

            // ACT
            var target = Factory.Maak<VerzekeringenSync>();
            target.Bewaren(persoonsVerzekering, groepsWerkJaar);

            // ASSERT

            kipSyncMock.VerifyAll();
        }
    }
}


text:
import DS from 'ember-data';
import Ember from 'ember';

const { attr, belongsTo } = DS;
const { computed } = Ember;

export default DS.Model.extend({
  providerName: attr(),
  providerUrl: attr(),
  referencer: attr(),
  type: attr(),
  url: attr(),

  canvas: belongsTo('canvas', { async: true }),

  insertedAt: attr('date'),
  updatedAt: attr('date'),

  unfurled: computed('url', function() {
    return this.store.findRecord('unfurl', this.get('url'));
  })
});